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-season-and-per-field-locks-extend-arc-lock]): per-season editorial locks
[._.]/ Adam Eivy1800a990e447
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 55594a0503..7b13699e12 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -31,6 +31,7 @@### Pipeline+- **Per-season editorial locks.** New `season.locked: boolean` field freezes a volume's editorial content (title, logline, synopsis, themes, ending hook, episode count target, delete) while leaving the production-status workflow free to advance. Strict-true sanitizer so a typo can't accidentally freeze a volume; the server's `LOCKED_SEASON_ALLOWED_KEYS` allow-list lets `{ locked: false }` and `{ status }` patches through, blocks everything else with `ERR_LOCKED` (409). `arcPlanner.generateSeasonEpisodes` refuses on a locked target before the LLM call (matches the existing `ERR_VALIDATION` arc-lock idiom); `issuesSvc.bulkReassignSeason` refuses to move issues OUT of or INTO a locked season (`ERR_SEASON_LOCKED`, 409); `seasonsSvc.deleteSeason` refuses to delete a locked season. Arc Canvas's `SeasonRow` gets a Lock/Unlock toggle next to Edit/Trash, the editor's six content inputs flip to `disabled` + `opacity-60` when locked (status select stays interactive — production workflow is independent of editorial freeze), and a locked-state banner explains the freeze. `PipelineIssue.jsx` reads the parent season from `series.seasons` and surfaces lock state both as a trailing `<Lock>` icon (in place of the per-stage status dot) across the TabPills strip AND as a sub-header pill linking the user to unlock-on-arc-canvas. 10 new server tests + zero client test additions (UI changes are minimal pass-through props; server gates own the contract). Closes PLAN.md `[per-season-and-per-field-locks-extend-arc-lock]`; two follow-ups deferred: `[per-field-locks-arc-and-stage-granularity]` (per-arc-field + per-issue-stage locks) and `[season-lock-aware-arc-resolve]` (resolveVerifyIssues currently still rewrites locked seasons via `commitSeasonsWithRemap` since the arc lock is the only gate at that path).- **Manual canon extraction from comicScript / teleplay stages.** Auto-extract still runs only after `prose`, but a new "Extract canon" button on both script stages lets writers pull characters/places/objects that surface only in panel directions or dialogue cues (a barkeep in a stage direction, a recurring location named only in the script) into the linked universe on demand. New route `POST /api/pipeline/issues/:id/stages/:stageId/extract-canon` (`stageId` must be `comicScript` or `teleplay`) reads the stage's `output` as the corpus and reuses the generic `extractCanonFromProse` with the same `parallel: true` + `autoLock: true` + `sourceSeriesId` stamping as the prose auto-extract, so script-derived entries survive later AI refines and stay attributable. Returns the merged universe + per-kind counts so the UI toast can summarize the merge. Three precondition errors: `PIPELINE_CANON_EXTRACT_BAD_STAGE`, `PIPELINE_CANON_EXTRACT_NO_CORPUS`, `PIPELINE_CANON_EXTRACT_NO_UNIVERSE`. New shared component `ExtractCanonButton.jsx` (gated on stage content + linked universe; tooltip explains the specific blocker when disabled); wired into `TeleplayStage` via `TextStagePanel.extraActions` and `ComicScriptStage` directly in its header. Client helper `extractPipelineCanonFromScript` in `apiPipeline.js`. 5 new vitest cases cover all precondition guards + happy path for both stage IDs.- **Auto-resolve prompt now anchors edits in per-episode synopses.** `buildVerifyContext` already wires `seasonsTreeJson.episodes[].synopsis` into both the verify AND resolve passes (resolve reuses verify's context via `buildResolveContext`), but the resolve prompt's "How to resolve" list never explicitly told the LLM to USE those episode-level entries — so the auto-resolve pass could rewrite a volume's `synopsis` in ways that contradicted what its child episodes already describe. New first bullet in `data.sample/prompts/stages/pipeline-arc-resolve.md` pins the LLM to treat episode synopses as ground truth: volume-level synopsis rewrites must summarize what the child episodes describe, can't invent beats no episode covers, and can't paper over contradictions that originate at the episode level. Empty/null episode synopses are called out as the "user hasn't drafted that issue yet" signal so the LLM doesn't infer the volume has no content. Migration `023-resolve-prompt-episode-anchor.js` auto-bumps unmodified installs from any of the three prior shipped hashes (pre-005, pre-019, post-019) to the new template; customized installs get a manual-merge warning. Migration 019's `NEW_SHIPPED_MD5` for `pipeline-arc-resolve.md` is bumped to track the live sample so fresh installs (where `data/` is seeded post-023) don't trip 019's "customized" warning. 6 new tests in `023-resolve-prompt-episode-anchor.test.js`. Closes PLAN.md `[resolve-issues-inherits-verify-gaps-verify-the]`.diff --git a/client/src/components/pipeline/ArcCanvas.jsx b/client/src/components/pipeline/ArcCanvas.jsxindex edd38c2a86..ca5474e17f 100644--- a/client/src/components/pipeline/ArcCanvas.jsx+++ b/client/src/components/pipeline/ArcCanvas.jsx@@ -759,6 +759,8 @@ function SeasonRow({ series, season, seasons, issues, onSeriesUpdate, onIssuesUpconst [editing, setEditing] = useState(false);const [verifying, setVerifying] = useState(false);const [verifyIssues, setVerifyIssues] = useState(null);+ const [lockBusy, setLockBusy] = useState(false);+ const seasonLocked = season.locked === true;// Volume beat-sheet bulk run — `active` gates SSE subscription; the latest// frame drives the per-issue label on the button.const [beatsActive, setBeatsActive] = useState(false);@@ -869,6 +871,24 @@ function SeasonRow({ series, season, seasons, issues, onSeriesUpdate, onIssuesUptoast.success(`Generated ${n} issue${n === 1 ? '' : 's'} / episode${n === 1 ? '' : 's'}${extractedSummary}`);};+ const toggleSeasonLock = async () => {+ const next = !seasonLocked;+ setLockBusy(true);+ const updated = await updatePipelineSeason(series.id, season.id, { locked: next }).catch((err) => {+ toast.error(err.message || 'Lock toggle failed');+ return null;+ });+ setLockBusy(false);+ if (!updated) return;+ onSeriesUpdate({+ ...series,+ seasons: seasons.map((s) => (s.id === season.id ? updated : s)),+ });+ toast.success(next+ ? `Volume ${season.number} locked — generation, delete, and content edits are blocked`+ : `Volume ${season.number} unlocked`);+ };+// 'idle' | 'confirm' | 'deleting' — drives an inline confirm row that swaps// in for the Edit/Trash buttons. Two-click "arm" was confusing (see// feedback memory); inline confirm matches LayoutEditor's pattern.@@ -913,6 +933,25 @@ function SeasonRow({ series, season, seasons, issues, onSeriesUpdate, onIssuesUp<div className="ml-auto flex items-center gap-2">{deleteMode === 'idle' && (<>+ <button+ type="button"+ onClick={toggleSeasonLock}+ disabled={lockBusy}+ className={`inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs border disabled:opacity-50 ${+ seasonLocked+ ? 'border-port-warning/40 text-port-warning hover:bg-port-warning/10'+ : 'border-port-border text-gray-400 hover:text-white'+ }`}+ title={seasonLocked+ ? 'Volume is locked — click to unlock and allow regeneration, delete, and content edits'+ : 'Lock this volume to prevent regeneration, delete, and content edits'}+ aria-pressed={seasonLocked}+ >+ {lockBusy+ ? <Loader2 size={12} className="animate-spin" />+ : (seasonLocked ? <Lock size={12} /> : <Unlock size={12} />)}+ {seasonLocked ? 'Locked' : 'Lock'}+ </button><buttontype="button"onClick={() => setEditing(!editing)}@@ -923,9 +962,12 @@ function SeasonRow({ series, season, seasons, issues, onSeriesUpdate, onIssuesUp<buttontype="button"onClick={() => setDeleteMode('confirm')}- className="p-1.5 text-gray-500 hover:text-port-error"+ disabled={seasonLocked}+ className="p-1.5 text-gray-500 hover:text-port-error disabled:opacity-40 disabled:hover:text-gray-500"aria-label={`Delete volume / season ${season.title}`}- title="Delete volume / season"+ title={seasonLocked+ ? 'Volume is locked — unlock to delete'+ : 'Delete volume / season'}><Trash2 size={12} /></button>@@ -960,7 +1002,13 @@ function SeasonRow({ series, season, seasons, issues, onSeriesUpdate, onIssuesUp</div>{editing ? (- <SeasonEditor series={series} season={season} seasons={seasons} onSeriesUpdate={onSeriesUpdate} />+ <SeasonEditor+ series={series}+ season={season}+ seasons={seasons}+ onSeriesUpdate={onSeriesUpdate}+ seasonLocked={seasonLocked}+ />) : !collapsed && (season.logline || season.synopsis) ? (<div className="px-3 pb-2 text-xs text-gray-400 space-y-1">{season.logline ? <p className="italic">{season.logline}</p> : null}@@ -974,6 +1022,12 @@ function SeasonRow({ series, season, seasons, issues, onSeriesUpdate, onIssuesUp</div>) : null}+ {!collapsed && seasonLocked ? (+ <div className="px-3 pb-2 text-xs text-port-warning flex items-center gap-1.5">+ <Lock size={11} /> Volume locked — generation, delete, and content edits are blocked. Unlock above to make changes.+ </div>+ ) : null}+{!collapsed ? (<><ul className="px-3 pb-2 space-y-1.5">@@ -1004,6 +1058,7 @@ function SeasonRow({ series, season, seasons, issues, onSeriesUpdate, onIssuesUp<SeasonActionsseries={series}season={season}+ seasonLocked={seasonLocked}hasArc={hasArc}hasEpisodes={hasEpisodes}generatingEpisodes={generatingEpisodes}@@ -1275,21 +1330,29 @@ function VolumeCoverEditorBox({);}-function SeasonEditor({ series, season, seasons, onSeriesUpdate }) {+function SeasonEditor({ series, season, seasons, onSeriesUpdate, seasonLocked = false }) {const [draft, setDraft] = useState(season);const [saving, setSaving] = useState(false);+ // Content fields (title/number/logline/synopsis/endingHook/episodeCountTarget)+ // are frozen when the season is locked — status stays editable since+ // production workflow can advance independently of editorial freeze.+ // Server's `LOCKED_SEASON_ALLOWED_KEYS` mirrors this contract.+ const contentDisabled = seasonLocked;const save = async () => {setSaving(true);- const updated = await updatePipelineSeason(series.id, season.id, {- title: draft.title,- number: Number(draft.number) || season.number,- logline: draft.logline,- synopsis: draft.synopsis,- endingHook: draft.endingHook,- episodeCountTarget: Number(draft.episodeCountTarget) || 0,- status: draft.status,- }).catch((err) => {+ const patch = seasonLocked+ ? { status: draft.status }+ : {+ title: draft.title,+ number: Number(draft.number) || season.number,+ logline: draft.logline,+ synopsis: draft.synopsis,+ endingHook: draft.endingHook,+ episodeCountTarget: Number(draft.episodeCountTarget) || 0,+ status: draft.status,+ };+ const updated = await updatePipelineSeason(series.id, season.id, patch).catch((err) => {toast.error(err.message || 'Save failed');return null;});@@ -1302,22 +1365,26 @@ function SeasonEditor({ series, season, seasons, onSeriesUpdate }) {toast.success('Volume / season saved');};+ const contentInputClass = `px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm ${contentDisabled ? 'opacity-60' : ''}`;+return (<div className="px-3 pb-3 space-y-2 bg-port-bg/40 border-t border-port-border"><div className="grid grid-cols-[1fr_auto] gap-2 pt-2"><inputvalue={draft.title || ''}onChange={(e) => setDraft({ ...draft, title: e.target.value })}+ disabled={contentDisabled}placeholder="Title"- className="px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"+ className={contentInputClass}maxLength={200}/><inputtype="number"value={draft.number || 0}onChange={(e) => setDraft({ ...draft, number: parseInt(e.target.value, 10) || 0 })}+ disabled={contentDisabled}placeholder="#"- className="w-16 px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"+ className={`w-16 ${contentInputClass}`}min={0}max={99}/>@@ -1325,33 +1392,37 @@ function SeasonEditor({ series, season, seasons, onSeriesUpdate }) {<inputvalue={draft.logline || ''}onChange={(e) => setDraft({ ...draft, logline: e.target.value })}+ disabled={contentDisabled}placeholder="One-sentence logline"- className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"+ className={`w-full ${contentInputClass}`}maxLength={500}/><textareavalue={draft.synopsis || ''}onChange={(e) => setDraft({ ...draft, synopsis: e.target.value })}+ disabled={contentDisabled}placeholder="Season synopsis (~200 words)"rows={4}- className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"+ className={`w-full ${contentInputClass}`}maxLength={4000}/><div className="grid grid-cols-2 gap-2"><inputvalue={draft.endingHook || ''}onChange={(e) => setDraft({ ...draft, endingHook: e.target.value })}+ disabled={contentDisabled}placeholder="Ending hook"- className="px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"+ className={contentInputClass}maxLength={1000}/><inputtype="number"value={draft.episodeCountTarget || 0}onChange={(e) => setDraft({ ...draft, episodeCountTarget: parseInt(e.target.value, 10) || 0 })}+ disabled={contentDisabled}placeholder="Issue / episode target"title="Issue / episode count target for this volume / season"- className="px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"+ className={contentInputClass}min={0}/></div>@@ -1392,7 +1463,7 @@ const BEATS_FRAME_LABELS = {};function SeasonActions({- series, season, hasArc, hasEpisodes, generatingEpisodes,+ series, season, seasonLocked = false, hasArc, hasEpisodes, generatingEpisodes,verifying, onGenerateEpisodes, onValidateVolume, onIssuesUpdate,beatsActive, beatsStarting, beatsLatest, onStartBeats, onCancelBeats,}) {@@ -1487,13 +1558,15 @@ function SeasonActions({<buttontype="button"onClick={onGenerateEpisodes}- disabled={generatingEpisodes || hasEpisodes || !seasonHasContext}+ disabled={generatingEpisodes || hasEpisodes || !seasonHasContext || seasonLocked}title={- hasEpisodes- ? 'Volume already has issues / episodes'- : !seasonHasContext- ? 'Add a volume logline or synopsis first'- : 'Have an LLM plan the per-issue / per-episode breakdown'+ seasonLocked+ ? 'Volume is locked — unlock to generate episodes'+ : hasEpisodes+ ? 'Volume already has issues / episodes'+ : !seasonHasContext+ ? 'Add a volume logline or synopsis first'+ : 'Have an LLM plan the per-issue / per-episode breakdown'}className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs text-port-accent hover:text-white border border-port-border bg-port-bg hover:border-port-accent/40 disabled:opacity-40 disabled:hover:text-port-accent">diff --git a/client/src/pages/PipelineIssue.jsx b/client/src/pages/PipelineIssue.jsxindex 1c948d9f30..4f15692167 100644--- a/client/src/pages/PipelineIssue.jsx+++ b/client/src/pages/PipelineIssue.jsx@@ -10,7 +10,7 @@ import { useEffect, useState, useMemo } from 'react';import { Link, useParams, useNavigate } from 'react-router-dom';import {ArrowLeft, Sparkles, Loader2, X, Lightbulb, BookOpen, FileText, Film as FilmIcon,- LayoutGrid, Image as ImageIcon, Clapperboard, Users, Settings, Mic,+ LayoutGrid, Image as ImageIcon, Clapperboard, Users, Settings, Mic, Lock,} from 'lucide-react';import toast from '../components/ui/Toast';import Modal from '../components/ui/Modal';@@ -186,6 +186,23 @@ export default function PipelineIssue() {}) : prev);};+ // Surface parent-season + arc lock state on the strip — generation actions+ // routed through generateSeasonEpisodes / arc-resolve are gated on these+ // server-side, so the user sees WHY the buttons inside each stage panel+ // refuse to fire. The lock indicator replaces the status dot when locked+ // because lock > status (a locked stage's status is frozen by definition).+ const parentSeason = useMemo(() => {+ if (!series?.seasons || !issue?.seasonId) return null;+ return series.seasons.find((s) => s.id === issue.seasonId) || null;+ }, [series?.seasons, issue?.seasonId]);+ const seasonLocked = parentSeason?.locked === true;+ const arcLocked = series?.locked?.arc === true;+ const lockHint = seasonLocked+ ? `Volume ${parentSeason.number || ''} is locked — unlock it on the Arc Canvas to enable regeneration`+ : arcLocked+ ? 'Arc is locked — unlock it on the Arc Canvas to enable regeneration'+ : null;+const stageTabs = useMemo(() => PIPELINE_TAB_STAGES// Audio is only meaningful when the series ships video — comic-only// series don't render dialogue as sound, so the tab is hidden to keep@@ -194,13 +211,16 @@ export default function PipelineIssue() {.filter((id) => id !== 'audio' || series?.targetFormat !== 'comic').map((id) => {const status = issue?.stages?.[id]?.status || 'empty';+ const trailing = lockHint+ ? <Lock size={11} className="text-port-warning" aria-label={lockHint} />+ : <span className={`w-1.5 h-1.5 rounded-full ${STATUS_DOT[status] || STATUS_DOT.empty}`} aria-hidden="true" />;return {id,label: PIPELINE_STAGE_LABELS[id],icon: STAGE_ICONS[id],- trailing: <span className={`w-1.5 h-1.5 rounded-full ${STATUS_DOT[status] || STATUS_DOT.empty}`} aria-hidden="true" />,+ trailing,};- }), [issue, series?.targetFormat]);+ }), [issue, series?.targetFormat, lockHint]);if (loading) return <div className="p-6 text-gray-500 text-sm">Loading issue…</div>;if (!issue) return null;@@ -306,6 +326,12 @@ export default function PipelineIssue() {ariaLabel="Pipeline stages"/>+ {lockHint ? (+ <div className="px-4 md:px-6 py-1.5 border-b border-port-border bg-port-warning/5 text-xs text-port-warning flex items-center gap-1.5">+ <Lock size={11} /> {lockHint}.+ </div>+ ) : null}+{/* Active stage panel */}<div className="flex-1 overflow-auto p-4 md:p-6">{StageComponent ? (diff --git a/server/lib/storyArc.js b/server/lib/storyArc.jsindex 25ea31ea7c..cde4556bac 100644--- a/server/lib/storyArc.js+++ b/server/lib/storyArc.js@@ -290,6 +290,14 @@ export function sanitizeSeason(raw, { preserveTimestamps = true } = {}) {cover: sanitizeCoverLike(raw.cover),backCover: sanitizeCoverLike(raw.backCover),status,+ // Per-season editorial lock. When true the season's metadata (title,+ // logline, synopsis, etc.) is frozen against rewriters: the+ // generateSeasonEpisodes LLM pass refuses to seed new issues, deleteSeason+ // refuses, and bulkReassignSeason refuses to move issues into or out of+ // it. Mirrors the binary semantics of `series.locked.arc`. Sibling to+ // `status` — `status` is descriptive (where am I in the workflow?) while+ // `locked` is enforcement (don't let LLM-driven jobs touch this).+ locked: raw.locked === true,createdAt: created,updatedAt: updated,};diff --git a/server/lib/storyArc.test.js b/server/lib/storyArc.test.jsindex 9953d5c77d..7fba7727d4 100644--- a/server/lib/storyArc.test.js+++ b/server/lib/storyArc.test.js@@ -133,6 +133,16 @@ describe('storyArc — sanitizeSeason', () => {expect(next.createdAt).not.toBe(original.createdAt); // both flippedexpect(next.updatedAt > original.updatedAt).toBe(true);});++ // `locked` defaults to false and only accepts strict-true so a typo+ // ("locked: 'yes'") can't accidentally freeze a season.+ it('defaults locked to false and coerces truthy non-booleans away', () => {+ expect(sanitizeSeason({ title: 'x' }).locked).toBe(false);+ expect(sanitizeSeason({ title: 'x', locked: false }).locked).toBe(false);+ expect(sanitizeSeason({ title: 'x', locked: 'yes' }).locked).toBe(false);+ expect(sanitizeSeason({ title: 'x', locked: 1 }).locked).toBe(false);+ expect(sanitizeSeason({ title: 'x', locked: true }).locked).toBe(true);+ });});describe('storyArc — sanitizeSeasonList', () => {diff --git a/server/routes/pipeline.js b/server/routes/pipeline.jsindex 362a09468d..ec9456fbb9 100644--- a/server/routes/pipeline.js+++ b/server/routes/pipeline.js@@ -92,6 +92,11 @@ const SERVICE_ERROR_STATUS = {[seriesSvc.ERR_VALIDATION]: 400,[issuesSvc.ERR_NOT_FOUND]: 404,[issuesSvc.ERR_VALIDATION]: 400,+ // Per-season-lock errors map to 409 (the lock-conflict idiom — same status+ // ERR_NO_VOLUME_COVER and friends use) so the client can disambiguate a+ // locked-resource refusal from a malformed-payload 400.+ [issuesSvc.ERR_SEASON_LOCKED]: 409,+ [seasonsSvc.ERR_LOCKED]: 409,[seasonsSvc.ERR_NOT_FOUND]: 404,[seasonsSvc.ERR_VALIDATION]: 400,[seasonsSvc.ERR_REASSIGN_TARGET]: 400,@@ -163,6 +168,11 @@ const seasonSchema = z.object({cover: seasonCoverSchema.nullable().optional(),backCover: seasonCoverSchema.nullable().optional(),status: z.enum(SEASON_STATUSES).optional(),+ // Per-season editorial lock. Enforced by `seasonsSvc.updateSeason` (refuses+ // content patches while locked) and `arcPlanner.generateSeasonEpisodes` /+ // `issuesSvc.bulkReassignSeason` / `seasonsSvc.deleteSeason` (refuse on+ // locked seasons). The sibling arc-level lock lives on `series.locked.arc`.+ locked: z.boolean().optional(),}).passthrough();// `.passthrough` keeps the door open for future per-season / per-field locksdiff --git a/server/services/pipeline/arcPlanner.js b/server/services/pipeline/arcPlanner.jsindex 43f6f1bfef..a1f18a5de3 100644--- a/server/services/pipeline/arcPlanner.js+++ b/server/services/pipeline/arcPlanner.js@@ -375,6 +375,16 @@ export async function generateSeasonEpisodes(seriesId, seasonId, options = {}) {if (!season) {throw makeErr(`Season not found on series: ${seasonId}`, ERR_VALIDATION);}+ // Per-season lock — same semantics as the arc-level lock above, scoped to+ // this volume. Generating episodes seeds new issue records under the+ // season; a locked season's shape is frozen, so refuse before the LLM call.+ // Verify (read-only) stays available so the user can still inspect findings.+ if (season.locked === true) {+ throw makeErr(+ `Season "${season.title || season.number}" is locked — unlock it before generating episodes`,+ ERR_VALIDATION,+ );+ }// A season with no synopsis + no logline gives the LLM nothing to riff// against — fail loud so the user sees the misconfiguration instead of// getting back 8 episodes of "a thing happens then another thing".diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.jsindex cf57253958..016640acc7 100644--- a/server/services/pipeline/arcPlanner.test.js+++ b/server/services/pipeline/arcPlanner.test.js@@ -313,6 +313,15 @@ describe('arcPlanner — generateSeasonEpisodes', () => {.rejects.toMatchObject({ code: planner.ERR_VALIDATION });});+ it('refuses + skips the LLM call when the target season is locked', async () => {+ const { series, seasons } = await setupSeriesWithSeasons();+ await seasonsSvc.updateSeason(series.id, seasons[0].id, { locked: true });+ stageRunnerSpy = vi.fn();+ await expect(planner.generateSeasonEpisodes(series.id, seasons[0].id))+ .rejects.toMatchObject({ code: planner.ERR_VALIDATION });+ expect(stageRunnerSpy).not.toHaveBeenCalled();+ });+it('shapes episodes, drops untitled entries, and validates arcRole', async () => {const { series, seasons } = await setupSeriesWithSeasons();stageRunnerSpy = vi.fn(async () => ({diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.jsindex aaba12a4bd..2919cebb14 100644--- a/server/services/pipeline/issues.js+++ b/server/services/pipeline/issues.js@@ -48,6 +48,7 @@ const queueIssueWrite = createFileWriteQueue();export const ERR_NOT_FOUND = 'PIPELINE_ISSUE_NOT_FOUND';export const ERR_VALIDATION = 'PIPELINE_ISSUE_VALIDATION';export const ERR_DUPLICATE = 'PIPELINE_ISSUE_DUPLICATE';+export const ERR_SEASON_LOCKED = 'PIPELINE_ISSUE_SEASON_LOCKED';const makeErr = (message, code) => Object.assign(new Error(message), { code });const ISSUE_ID_RE = /^iss-[A-Za-z0-9-]+$/;@@ -415,8 +416,26 @@ export function recomputeIssueNumbersForSeries(seriesId, fromSeasonId = null) {* the renumber pass — callers under `withReexportSuppressed` get exactly one* `series:updated` event regardless of the issue count.*/-export function bulkReassignSeason(seriesId, fromSeasonId, toSeasonId = null) {+export function bulkReassignSeason(seriesId, fromSeasonId, toSeasonId = null, { _preloadedSeries = null } = {}) {return queueIssueWrite(async () => {+ // Honor per-season locks — refuse to move issues OUT of or INTO a locked+ // volume. Series lives in a different write queue, so this is best-effort+ // single-user gating, not strict serialization (fine per CLAUDE.md).+ // Callers that already hold a fresh series (e.g. `deleteSeason` reads it+ // for the reassign-target validation) can pass `_preloadedSeries` to skip+ // the duplicate read.+ if (fromSeasonId || toSeasonId) {+ const series = _preloadedSeries || await seriesSvc.getSeries(seriesId);+ const seasons = Array.isArray(series.seasons) ? series.seasons : [];+ const findLocked = (id) => (id ? seasons.find((s) => s.id === id && s.locked === true) : null);+ const blocker = findLocked(fromSeasonId) || findLocked(toSeasonId);+ if (blocker) {+ throw makeErr(+ `Season "${blocker.title || blocker.number}" is locked — unlock it before reassigning issues`,+ ERR_SEASON_LOCKED,+ );+ }+ }const state = await readState();let reassigned = 0;const now = new Date().toISOString();diff --git a/server/services/pipeline/issues.test.js b/server/services/pipeline/issues.test.jsindex 3197cf04d8..c227cc8308 100644--- a/server/services/pipeline/issues.test.js+++ b/server/services/pipeline/issues.test.js@@ -562,5 +562,33 @@ describe('pipeline issues service', () => {expect(otherList).toHaveLength(1);expect(otherList[0].seasonId).toBe(otherSeason.id);});++ // Per-season editorial lock — refuses to move issues OUT of or INTO a+ // locked season. Pairs with `seasons.updateSeason`'s LOCKED_SEASON gate.+ it('refuses to reassign OUT of a locked source season', async () => {+ const { series, a, b } = await setup();+ await seasonsSvc.updateSeason(series.id, a.id, { locked: true });+ await expect(svc.bulkReassignSeason(series.id, a.id, b.id))+ .rejects.toMatchObject({ code: svc.ERR_SEASON_LOCKED });+ // Issues stayed put — unchanged seasonId.+ const list = await svc.listIssues({ seriesId: series.id });+ expect(list.filter((i) => i.seasonId === a.id)).toHaveLength(3);+ });++ it('refuses to reassign INTO a locked target season', async () => {+ const { series, a, b } = await setup();+ await seasonsSvc.updateSeason(series.id, b.id, { locked: true });+ await expect(svc.bulkReassignSeason(series.id, a.id, b.id))+ .rejects.toMatchObject({ code: svc.ERR_SEASON_LOCKED });+ });++ it('allows reassignment when neither season is locked', async () => {+ const { series, a, b } = await setup();+ // Sanity — explicitly lock and unlock to prove the gate clears.+ await seasonsSvc.updateSeason(series.id, a.id, { locked: true });+ await seasonsSvc.updateSeason(series.id, a.id, { locked: false });+ const result = await svc.bulkReassignSeason(series.id, a.id, b.id);+ expect(result.reassigned).toBe(3);+ });});});diff --git a/server/services/pipeline/seasons.js b/server/services/pipeline/seasons.jsindex f380fa1d8b..9ddf3c911f 100644--- a/server/services/pipeline/seasons.js+++ b/server/services/pipeline/seasons.js@@ -20,8 +20,15 @@ import { emitRecordUpdated, withReexportSuppressed } from '../sharing/recordEvenexport const ERR_NOT_FOUND = 'PIPELINE_SEASON_NOT_FOUND';export const ERR_VALIDATION = 'PIPELINE_SEASON_VALIDATION';export const ERR_REASSIGN_TARGET = 'PIPELINE_SEASON_REASSIGN_TARGET_INVALID';+export const ERR_LOCKED = 'PIPELINE_SEASON_LOCKED';const makeErr = (message, code) => Object.assign(new Error(message), { code });+// Fields a locked-season patch MUST NOT touch. `locked` itself is allowed+// (the user has to be able to unlock); `status` is allowed because it tracks+// production progress (e.g. flipping `verified` → `in-production`) which is+// orthogonal to editorial content. Timestamps are set by the sanitizer.+const LOCKED_SEASON_ALLOWED_KEYS = new Set(['locked', 'status']);+export async function listSeasons(seriesId) {const series = await seriesSvc.getSeries(seriesId);return series.seasons || [];@@ -65,6 +72,18 @@ export async function updateSeason(seriesId, seasonId, patch = {}) {let priorNumber = null;let nextNumber = null;const updated = await seriesSvc.updateSeasonOnSeries(seriesId, seasonId, (cur) => {+ // Locked seasons accept only `locked: false` or status patches — any+ // other content key requires an unlock-in-same-patch so the UI can+ // offer "unlock + edit" as one round-trip.+ if (cur.locked === true && patch.locked !== false) {+ const forbidden = Object.keys(patch).filter((k) => !LOCKED_SEASON_ALLOWED_KEYS.has(k));+ if (forbidden.length > 0) {+ throw makeErr(+ `Season "${cur.title || cur.number}" is locked — unlock it before editing (${forbidden.join(', ')})`,+ ERR_LOCKED,+ );+ }+ }priorNumber = cur.number;const next = sanitizeSeason({...cur,@@ -97,6 +116,15 @@ export async function deleteSeason(seriesId, seasonId, { reassignTo = null } = {const seasons = series.seasons || [];const cur = seasons.find((s) => s.id === seasonId);if (!cur) throw makeErr(`Season not found: ${seasonId}`, ERR_NOT_FOUND);+ // Refuse to delete a locked season — destructive ops on locked records+ // must require an explicit unlock first. Matches the editorial-freeze+ // semantics that block `updateSeason` content patches above.+ if (cur.locked === true) {+ throw makeErr(+ `Season "${cur.title || cur.number}" is locked — unlock it before deleting`,+ ERR_LOCKED,+ );+ }// Validate the reassign target up front. Passing a non-existent sibling id// here is a user-side bug (stale state, copy-paste error) — surfacing it// before any disk writes means the caller can retry cleanly.@@ -126,7 +154,9 @@ export async function deleteSeason(seriesId, seasonId, { reassignTo = null } = {const merged = seasons.filter((s) => s.id !== seasonId);let reassignedIssueCount = 0;await withReexportSuppressed('series', seriesId, async () => {- const result = await issuesSvc.bulkReassignSeason(seriesId, seasonId, reassignTo);+ // Pass the series we already loaded so bulkReassignSeason's lock check+ // doesn't re-fetch — same micro-opt as the cover-filer dispatcher.+ const result = await issuesSvc.bulkReassignSeason(seriesId, seasonId, reassignTo, { _preloadedSeries: series });reassignedIssueCount = result.reassigned;await seriesSvc.updateSeries(seriesId, { seasons: merged });});diff --git a/server/services/pipeline/seasons.test.js b/server/services/pipeline/seasons.test.jsindex a15e02d738..79c2832436 100644--- a/server/services/pipeline/seasons.test.js+++ b/server/services/pipeline/seasons.test.js@@ -145,4 +145,59 @@ describe('pipeline seasons service', () => {await expect(svc.deleteSeason(s.id, 'sea-nope')).rejects.toMatchObject({ code: svc.ERR_NOT_FOUND });});++ // ─── Per-season editorial lock ───────────────────────────────────────────+ // A locked season freezes its content fields against rewriters; only an+ // unlock (locked: false) or a production-status flip may patch through.+ // Pairs with `LOCKED_SEASON_ALLOWED_KEYS` server-side.+ it('updateSeason allows toggling lock on + off without other fields', async () => {+ const s = await setupSeries();+ const a = await svc.createSeason(s.id, { title: 'Pilot' });+ const locked = await svc.updateSeason(s.id, a.id, { locked: true });+ expect(locked.locked).toBe(true);+ const unlocked = await svc.updateSeason(s.id, a.id, { locked: false });+ expect(unlocked.locked).toBe(false);+ });++ it('updateSeason refuses content patches on a locked season', async () => {+ const s = await setupSeries();+ const a = await svc.createSeason(s.id, { title: 'Pilot' });+ await svc.updateSeason(s.id, a.id, { locked: true });+ await expect(svc.updateSeason(s.id, a.id, { logline: 'New' }))+ .rejects.toMatchObject({ code: svc.ERR_LOCKED });+ // Content unchanged.+ const reloaded = (await svc.listSeasons(s.id))[0];+ expect(reloaded.logline).toBe('');+ expect(reloaded.locked).toBe(true);+ });++ it('updateSeason allows status flips on a locked season', async () => {+ const s = await setupSeries();+ const a = await svc.createSeason(s.id, { title: 'Pilot' });+ await svc.updateSeason(s.id, a.id, { locked: true });+ // status is in `LOCKED_SEASON_ALLOWED_KEYS` — production workflow can+ // advance without an editorial unlock.+ const patched = await svc.updateSeason(s.id, a.id, { status: 'in-production' });+ expect(patched.status).toBe('in-production');+ expect(patched.locked).toBe(true);+ });++ it('updateSeason allows unlock + edit in one patch', async () => {+ const s = await setupSeries();+ const a = await svc.createSeason(s.id, { title: 'Pilot' });+ await svc.updateSeason(s.id, a.id, { locked: true });+ const patched = await svc.updateSeason(s.id, a.id, { locked: false, logline: 'Reopened' });+ expect(patched.locked).toBe(false);+ expect(patched.logline).toBe('Reopened');+ });++ it('deleteSeason refuses to delete a locked season', async () => {+ const s = await setupSeries();+ const a = await svc.createSeason(s.id, { title: 'Pilot' });+ await svc.updateSeason(s.id, a.id, { locked: true });+ await expect(svc.deleteSeason(s.id, a.id))+ .rejects.toMatchObject({ code: svc.ERR_LOCKED });+ // Season still present.+ expect((await svc.listSeasons(s.id)).map((x) => x.id)).toEqual([a.id]);+ });});