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-field-locks-arc-and-stage-granularity]): per-field arc locks + per-stage issue locks
[._.]/ Adam Eivy66ced0226358
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdnew file mode 100644index 0000000000..491db0dd0a--- /dev/null+++ b/.changelog/NEXT.md@@ -0,0 +1,15 @@+# Unreleased Changes++## Added++- **Per-stage editorial locks on Pipeline issues.** Each `issue.stages.{id}` now carries a `locked` flag; locked stages refuse regeneration (text generate, image / video enqueue, refine, extract-scenes / extract-pages, audio extract / render, episode-video fresh start, cover-concepts commit). UI exposes a lock toggle on every Pipeline Issue tab and renders a per-stage Lock indicator on the TabPills strip, so users can freeze a finalized comic script while still iterating storyboards.+- **Per-field arc locks on series.** `series.locked.arcFields` is an opt-in sub-map (`{ logline, summary, themes, protagonistArc, shape }`); locked fields are preserved verbatim through `commitSeasonsWithRemap` so arc regenerate + auto-resolve only rewrite the unlocked fields. Inline lock icons on the Arc Canvas read view toggle each field.++## Changed++- `/claim` slash command now hard-requires an isolated worktree with absolute paths, a single-Bash-invocation flow, and a `pwd` verification checkpoint — eliminates the failure mode where the claim branch was checked out in the main repo and blocked further parallel claims.+- Removed the CLAUDE.md "Worktrees" section that prohibited TUI worktrees; it conflicted with `/claim`'s explicit worktree requirement.++## Fixed++## Removeddiff --git a/.claude/commands/claim.md b/.claude/commands/claim.mdindex 27ec851e7a..12c3132ce4 100644--- a/.claude/commands/claim.md+++ b/.claude/commands/claim.md@@ -30,19 +30,37 @@ Claim the next unclaimed `- [ ]` item from PLAN.md via the slug-ID system, work- The line does NOT carry the `<!-- NEEDS_INPUT -->` annotation (those are waiting on a user clarification PR).5. **If no eligible item exists**, print why (all in flight / all drifted / all NEEDS_INPUT / nothing unchecked) and stop. Do NOT brainstorm new work — that's the `feature-ideas` scheduled task's job.-## Phase 2: Claim (worktree)+## Phase 2: Claim (worktree) — REQUIRED, NOT OPTIONAL++> **This phase overrides CLAUDE.md's "don't spawn a worktree in TUI" rule.** That rule exists so single-session TUI work doesn't fragment into stray worktrees. `/claim` is the documented exception: the worktree is what lets the user fire off a *second* `/claim` in another tab without the two claims fighting over the main repo's working tree. **A `/claim` without a worktree is a broken claim — it blocks every subsequent claim until cleaned up.**+>+> **Hard rules:**+> - ❌ NEVER run `git checkout -b claim/<slug>` in the main repo. That's the failure mode this phase exists to prevent.+> - ❌ NEVER run `git switch -c claim/<slug>` in the main repo. Same reason.+> - ✅ ALWAYS use `git worktree add` with an explicit absolute path.+> - ✅ ALWAYS `cd` into the worktree and verify with `pwd` before Phase 4. The bash-tool "avoid `cd`" guidance does not apply here — the user has explicitly requested a working-directory change by invoking `/claim`.Create the worktree on a branch named `claim/<slug>` (the `claim/` prefix is the convention for human-driven TUI sessions; CoS sub-agents use `cos/<task>/<slug>/<agent>`). Both forms place the slug as a `/`-segment, so any agent's in-flight scan sees both.+Run all of these in **a single Bash invocation** so the shell variables stay in scope, and substitute `<picked-slug>` with the real slug from Phase 1:+```bash-SLUG=<picked-slug>-WORKTREE="data/cos/worktrees/claim-${SLUG}"-git fetch origin main-git worktree add -b "claim/${SLUG}" "${WORKTREE}" origin/main-cd "${WORKTREE}"+SLUG="<picked-slug>" && \+REPO_ROOT="/Users/adameivy/github.com/atomantic/PortOS" && \+WORKTREE="${REPO_ROOT}/data/cos/worktrees/claim-${SLUG}" && \+mkdir -p "${REPO_ROOT}/data/cos/worktrees" && \+cd "${REPO_ROOT}" && \+git fetch origin main && \+git worktree add -b "claim/${SLUG}" "${WORKTREE}" origin/main && \+cd "${WORKTREE}" && \+pwd```-If `data/cos/worktrees/` doesn't exist, create it (`mkdir -p`). Stash the worktree path; you'll need it for cleanup.+**Verify the output of `pwd` is exactly `${WORKTREE}`** (i.e. `/Users/adameivy/github.com/atomantic/PortOS/data/cos/worktrees/claim-<slug>`). If `pwd` prints the main repo path instead, the worktree creation or `cd` failed — STOP, report the error to the user, and do not proceed to Phase 3.++**Re-anchor every subsequent Bash call.** Working directory persists between Bash tool calls, but a stray `cd` elsewhere or a fresh shell can drop you back at the main repo silently. Start each later Bash call in this flow with either `cd "${WORKTREE}"` (re-export the variable if needed) or use absolute paths under the worktree. Re-run `pwd` if you're ever unsure.++Stash the absolute worktree path; you'll need it for Phase 7 cleanup.## Phase 3: Verify still valid@@ -115,14 +133,20 @@ git commit -m "docs([<slug>]): archive to DONE.md"## Phase 7: Clean up-From the **source repo** (not the worktree — `cd` back to `/Users/adameivy/github.com/atomantic/PortOS` first):+From the **source repo** (not the worktree). Run as a single Bash invocation, re-substituting the slug and absolute worktree path you stashed in Phase 2:```bash-git worktree remove "${WORKTREE}"-git branch -d "claim/${SLUG}" # safe-delete; -D only if you know there's unmerged work-git pull --rebase --autostash # pull the merge commit into local main+SLUG="<picked-slug>" && \+REPO_ROOT="/Users/adameivy/github.com/atomantic/PortOS" && \+WORKTREE="${REPO_ROOT}/data/cos/worktrees/claim-${SLUG}" && \+cd "${REPO_ROOT}" && \+git worktree remove "${WORKTREE}" && \+git branch -d "claim/${SLUG}" && \+git pull --rebase --autostash```+(`git branch -d` is safe-delete; only fall back to `-D` if you've confirmed there's no unmerged work. `git pull --rebase --autostash` brings the merge commit into local main.)+Print a one-line summary:```diff --git a/CLAUDE.md b/CLAUDE.mdindex e3c91f297a..1f270eaed8 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -139,12 +139,6 @@ PortOS bundles [slashdo](https://github.com/atomantic/slashdo) as a git submodulWhen CoS agents or AI tools work on managed apps outside PortOS, all research, plans, docs, and code for those apps must be written to the target app's own repository/directory -- never to this repo. PortOS stores only its own features, plans, and documentation. If an agent generates a PLAN.md, research doc, or feature spec for another app, it goes in that app's directory.-## Worktrees--When working **directly in the Claude Code TUI** with the user driving, edit the main repo directly — don't spawn a worktree. Use normal feature branches and PRs (or push to `main`) when the work is done. The user is at the keyboard, so there is no risk of stepping on in-flight work.--**Worktrees are required only for CoS sub-agents** spawned out of `server/services/cos/subAgentSpawner.js`. Those run unattended in parallel and need isolation so they don't trample each other or the user's working tree. The worktree manager (`server/services/cos/worktreeManager.js`) handles this automatically — TUI sessions should not duplicate that behavior.-## Code Conventions- **No try/catch** - errors bubble to centralized middleware. **Exception:** PTY/child-process/`setTimeout`/`setInterval` callbacks and any code that runs *outside* the Express request lifecycle. An uncaught throw there crashes the Node process (there is no `next(err)` to bubble to). At those boundaries, wrap hook invocation in try/catch and log via the emoji-prefixed `console.error` style. Async event handlers that mutate shared module-level state (e.g. the TUI spawner's `handleData`) must also be serialized — chain them onto a per-session/per-actor `Promise.resolve()` queue rather than firing concurrently, otherwise interleaved awaits race on shared buffers.diff --git a/DONE.md b/DONE.mdindex 74f4e27094..216a72595a 100644--- a/DONE.md+++ b/DONE.md@@ -10,6 +10,7 @@ For active roadmap see [PLAN.md](./PLAN.md). For project goals see [GOALS.md](./### 2026-05-19+- **[per-field-locks-arc-and-stage-granularity] Per-field arc locks + per-stage issue locks.** Follow-on to per-season locks (`[per-season-and-per-field-locks-extend-arc-lock]`). Two layered ratchets, both enforced server-side and surfaced in the UI. (1) **Per-field arc locks** — `series.locked.arcFields` carries an opt-in sub-map (`{ logline, summary, themes, protagonistArc, shape }`); new `mergeArcWithLocks(currentArc, nextArc, lockedFields)` helper in `arcPlanner.js` rewrites the incoming arc to preserve locked field values verbatim from the existing arc, called from `commitSeasonsWithRemap` so both auto-resolve (via `resolveVerifyIssues`) and the `/series/:id/arc/generate?commit=true` path honor the lock; new `ARC_LOCKABLE_FIELDS = ['logline','summary','protagonistArc','themes','shape']` export in `pipeline/series.js` is mirrored as the Zod schema in `seriesLockedSchema`. Arc Canvas read view now renders a small `FieldLockToggle` icon (subtle 4×4 inline button, Lock/Unlock-with-spinner) next to each field that's currently displayed — logline paragraph, story-shape badge, themes chip row, summary `<summary>`, protagonistArc `<summary>` — toggling PATCHes through `updatePipelineSeries({ locked: { ...series.locked, arcFields: nextFields } })` with optimistic update + toast. (2) **Per-stage issue locks** — every `issue.stages.{id}` (text + visual + audio) carries `locked: boolean` (default `false`, strict-true coercion so `locked: 'yes'` typos can't accidentally freeze the stage). New `assertStageUnlocked(issue, stageId)` helper in `pipeline/issues.js` throws `ServerError({ status: 400, code: 'PIPELINE_STAGE_LOCKED' })` and is called from every regeneration entry point: `textStages.generateStage`, `visualStages.enqueueComicCoverLike` / `enqueueVisualComicPage` / `enqueueVisualImage` / `enqueueStoryboardSceneVideo` / `enqueueStoryboardShotStartFrame` / `refineComicPanelPrompt` / `refineStoryboardScenePrompt`, `episodeVideo.startEpisodeVideoForIssue` (fresh-start branch only; reuse of existing `cdProjectId` is still permitted), `arcPlanner.generateComicCoverConcepts` (`commit: true` path), and the four route-level audio/extract paths (`/audio/extract-lines`, `/audio/lines/:n/render`, `/storyboards/extract-scenes`, `/comicPages/extract-pages`). The text-stage gate runs *before* `updateStage({ status: 'generating' })` so a locked stage doesn't get stuck at "generating" only to be reset. `PipelineIssue.jsx` (a) gates the per-tab `<Lock>` indicator on per-stage `locked` first (then falls back to the ambient arc/season-wide lock); (b) adds a Lock/Unlock toggle button to the action bar that targets the currently-active stage and PATCHes `{ stages: { [stageId]: { locked: next } } }` via `updatePipelineIssue`; (c) the lock-banner under the TabPills strip prefers the per-stage message when the active tab is locked. Coverage: 11 new tests — 4 in `issues.test.js` (default `locked: false` on every stage, PATCH round-trip, non-boolean coerce-to-false, `assertStageUnlocked` throw/no-op), 1 in `textStages.test.js` (refuse + leave status untouched on locked stage), 6 in `arcPlanner.test.js` (`mergeArcWithLocks` per-field preservation, empty/null/undefined locks pass through, no-current-arc passthrough, null/undefined next no-op, unknown lock keys ignored, full `commitSeasonsWithRemap` round-trip with locked logline + themes). All 5689 server tests + 103 client tests pass.- **[pipeline-visual-stages-setting-field-injection] Inject setting `palette`/`era`/`weather`/`recurringDetails` into visual stages.** Visual prompts now pull the full RICH place descriptor set (description + Palette + Era + Weather + recurringDetails) instead of the SHORT subset (description + Palette + recurringDetails) — era + weather are continuity-critical visual cues that diffusion models weight strongly for lighting, atmosphere, and period dress, and they were already wired through the bible schema + LLM extraction but silently dropped at the visual-prompt boundary. Two surfaces touched: (1) `buildScenePrompt` in `server/lib/scenePrompt.js` + the client mirror at `client/src/lib/scenePrompt.js` swap `shortCanonDescriptorFragments('place', …)` for `richCanonDescriptorFragments('place', …)`, so storyboard scene renders (via `composeVisualPrompt` in `visualStages.js`) AND Writers Room's `SceneCard.jsx` pick up era/weather; (2) `composeComicPagePrompt`'s hand-rolled multi-place clause is replaced with the same `richCanonDescriptorFragments` helper, so the per-page `Setting — Place: description. Palette: X. Era: Y. Weather: Z. recurringDetails` shape is consistent with the scene-prompt path. The capital-cased `Palette:` prefix replaces the previous lowercase `palette:` in comic-page output as a side-effect of the shared helper (RICH_SPEC's uniform capitalization convention). UI card summaries (`KINDS[].descFor` in `UniverseCanonSection`) still use the narrower SHORT spec — those don't drive renders, so widening would just clutter the bible. Truncation order under tight budget pressure: description survives longest; recurringDetails drops first, then weather, era, palette — the priority order documented in `buildScenePrompt`'s header comment. Coverage: 2 new tests in `scenePrompt.test.js` (RICH frags pinned in display order; era/weather omitted when blank) + 3 new tests in `visualStages.test.js` for `composeComicPagePrompt` (full RICH injection + order; blank-field skip without bare prefixes; multi-place ` | `-join). All 5661 server tests + 103 client tests pass; client build clean. Two `/simplify` follow-ups deferred to PLAN.md: `[extract-flatten-canon-descriptor-fragments-helper]` (collapse the 4-site `.map(f => prefix ? ...).join(...)` pattern) and `[cleanplateprompt-migrate-to-rich-canon-fragments]` (sibling visual-prompt surface still on SHORT spec).### 2026-05-18diff --git a/PLAN.md b/PLAN.mdindex 6231b80094..583c1bf3b9 100644--- a/PLAN.md+++ b/PLAN.md@@ -27,7 +27,6 @@ _Nothing currently parked — pick the next item from the Backlog._### Pipeline continuity / approval-- [ ] [per-field-locks-arc-and-stage-granularity] **Per-field locks for arc and per-stage locks on issues.** Follow-on to `[per-season-and-per-field-locks-extend-arc-lock]` (per-season locks shipped). Two remaining ratchets: (1) per-field arc locks — let `series.locked` carry a sub-map (`{ arc: true, arcFields: { logline: true, themes: true } }`) so `resolveVerifyIssues` and `commitSeasonsWithRemap` can rewrite unlocked fields while preserving locked ones. (2) per-stage locks at the issue level — add `issue.stages.{id}.locked: boolean` so the user can freeze a finalized comic-script while still iterating the storyboard. Wire the trailing Lock indicator on `PipelineIssue.jsx`'s TabPills strip per-stage (currently shows arc/season-level lock for the whole strip).- [ ] [season-lock-aware-arc-resolve] **Make `resolveVerifyIssues` respect per-season locks.** Today the arc-level lock blocks resolve entirely. With per-season locks landed (the parent slug above), a user can unlock the arc but keep individual seasons frozen; auto-resolve would currently rewrite locked season metadata via `commitSeasonsWithRemap` → `updateSeries({ arc, seasons })`. Either (a) refuse resolve up-front with a "seasons X, Y are locked — unlock or skip" error, or (b) teach `commitSeasonsWithRemap` to preserve `locked` season payloads field-for-field on merge.- [ ] [pipeline-text-stages-worldentitiessummary] **Add `worldEntitiesSummary` to text stages.** Zero occurrences in codebase today; a one-string canon synopsis (top-N entities by frequency, name + 1-line descriptor) keeps text-stage prompts under context budget while still giving the LLM continuity anchors.- [ ] [bible-schema-speech-pattern-field] **Add a dedicated speech-pattern field to the character bible schema.** `voiceId` is the TTS engine pointer, not a written speech-pattern field. Add to `PROMPT_FIELDS[CHARACTER]` in `server/lib/storyBible.js:121` and pipe through extraction + script prompts.@@ -72,6 +71,8 @@ _Nothing currently parked — pick the next item from the Backlog._### Code quality / dedup (from `/simplify` passes)+- [ ] [extract-uselocktoggle-hook-for-arc-season-stage-field] **Extract `useLockToggle()` hook.** Four near-identical optimistic-PATCH lock toggles now exist: `toggleArcLock` (`client/src/components/pipeline/ArcCanvas.jsx:208`), `toggleSeasonLock` (same file, ~937), `FieldLockToggle#toggle` (same file, ~570, new in `[per-field-locks-arc-and-stage-granularity]`), `handleStageLockToggle` (`client/src/pages/PipelineIssue.jsx:179`, also new). All share: `useState(busy)` → optimistic PATCH-with-`.catch(() => null)` → `setBusy(false)` → on-success setState + toast. A `useLockToggle({ patchFn, onSuccess, lockedMessage, unlockedMessage })` returning `{ busy, toggle }` would absorb ~80 LOC. Pre-existing toggles AND new ones should be migrated in one pass to avoid the file having two patterns. Surfaced by `/simplify` during `[per-field-locks-arc-and-stage-granularity]`.+- [ ] [extract-optionalbooleanmap-zod-helper] **Extract `optionalBooleanMap(keys)` Zod helper.** Three call sites now build a Zod sub-schema from a string array of boolean-typed keys via `Object.fromEntries(KEYS.map((k) => [k, z.boolean().optional()]))`: `server/routes/universeBuilder.js:106` (`LOCKABLE_FIELDS`), `server/routes/pipeline.js:183` (`LOCKABLE_STAGES`), and `server/routes/pipeline.js:185` (`ARC_LOCKABLE_FIELDS`, new in `[per-field-locks-arc-and-stage-granularity]`). Tiny helper in `server/lib/validation.js` would collapse each site to `optionalBooleanMap(seriesSvc.ARC_LOCKABLE_FIELDS)`. Surfaced by `/simplify`.- [ ] [more-resolveproviderandmodel-migration-candidates] **More `resolveProviderAndModel` migration candidates.** When the helper landed in `server/lib/promptRunner.js` (universe-builder PR), three additional pure two-step provider-resolution chains were left alone to keep scope tight: `server/services/agentContentGenerator.js#runAIGeneration` (line ~80–90), `server/services/agentPersonalityGenerator.js` (line ~68–79), `server/services/loops.js` (line ~64–77). All three are textbook fits (no `enabled` gate, no typed-error throw mid-chain). Migration is one-import + 5-line collapse per file.- [ ] [extract-assertprovider-provider-errormessage-code] **Extract `assertProvider(provider, { errorMessage, code, status })` helper.** After the `resolveProviderAndModel` migration there are now 4 `if (!provider) throw …` sites with varying error shapes (`Error` vs `ServerError`, `status: 400/503`, codes `NO_PROVIDER`/`UNIVERSE_PROMOTE_NO_PROVIDER`/etc.). One helper that takes the error-shape args would consolidate without forcing each caller to share the same error type.- [ ] [extract-mergeexpandintodraft-draft-result-from] **Extract `mergeExpandIntoDraft(draft, result)` from `UniverseBuilder.jsx#handleExpand`.** The function is ~150 lines mixing pure-merge logic (categories, sheets, canon, locks) with I/O shell (API call, setDraft, auto-save, toast). Pull the merge into a top-level pure helper so the I/O surface shrinks and the merge is unit-testable. Deferred from Phase B `/simplify` to keep that PR tightly scoped.diff --git a/client/src/components/pipeline/ArcCanvas.jsx b/client/src/components/pipeline/ArcCanvas.jsxindex ca5474e17f..4eb579d808 100644--- a/client/src/components/pipeline/ArcCanvas.jsx+++ b/client/src/components/pipeline/ArcCanvas.jsx@@ -560,6 +560,51 @@ function ThemeChips({ series, arc, onSeriesUpdate }) {);}+// Per-field arc lock toggle. Click flips `series.locked.arcFields[field]`; the+// server-side `commitSeasonsWithRemap` honors the map so auto-resolve /+// regenerate rewrite unlocked fields while preserving locked ones verbatim.+// Subtle inline icon — not a full button — to stay out of the read flow.+function FieldLockToggle({ series, field, label, onSeriesUpdate }) {+ const lockedFields = series.locked?.arcFields || {};+ const locked = lockedFields[field] === true;+ const [saving, setSaving] = useState(false);+ const toggle = async () => {+ if (saving) return;+ const nextFields = { ...lockedFields };+ if (locked) delete nextFields[field];+ else nextFields[field] = true;+ setSaving(true);+ // `updatePipelineSeries` toasts the error itself on rejection — silent: false+ // by default in apiCore.request. No custom catch needed; just short-circuit.+ const updated = await updatePipelineSeries(series.id, {+ locked: { ...(series.locked || {}), arcFields: nextFields },+ }).catch(() => null);+ setSaving(false);+ if (!updated) return;+ onSeriesUpdate(updated);+ toast.success(locked ? `${label} unlocked` : `${label} locked — preserved on regenerate / auto-resolve`);+ };+ return (+ <button+ type="button"+ onClick={toggle}+ disabled={saving}+ aria-pressed={locked}+ title={locked+ ? `${label} is locked — click to unlock`+ : `Lock ${label} to preserve it through regenerate / auto-resolve`}+ aria-label={locked ? `Unlock ${label}` : `Lock ${label}`}+ className={`inline-flex items-center justify-center w-4 h-4 rounded transition-colors disabled:opacity-40 ${+ locked ? 'text-port-warning hover:text-port-warning/80' : 'text-gray-600 hover:text-gray-300'+ }`}+ >+ {saving+ ? <Loader2 size={10} className="animate-spin" />+ : (locked ? <Lock size={10} /> : <Unlock size={10} />)}+ </button>+ );+}+function ArcContent({ series, onSeriesUpdate }) {const arc = series.arc;const [editing, setEditing] = useState(false);@@ -649,28 +694,45 @@ function ArcContent({ series, onSeriesUpdate }) {return (<div className="space-y-2">- {arc.logline ? <p className="text-sm text-white">{arc.logline}</p> : null}+ {arc.logline ? (+ <div className="flex items-start gap-2">+ <p className="text-sm text-white flex-1">{arc.logline}</p>+ <FieldLockToggle series={series} field="logline" label="Logline" onSeriesUpdate={onSeriesUpdate} />+ </div>+ ) : null}<div className="flex flex-wrap items-center gap-1.5">{shapeDef ? (- <span- className="inline-flex items-center gap-1.5 text-[10px] uppercase tracking-wider px-2 py-0.5 rounded bg-port-bg border border-port-accent/40 text-port-accent"- title={shapeDef.description}- >- <ArcShapeSparkline shape={shapeDef} width={48} height={16} />- {shapeDef.label}- </span>+ <>+ <span+ className="inline-flex items-center gap-1.5 text-[10px] uppercase tracking-wider px-2 py-0.5 rounded bg-port-bg border border-port-accent/40 text-port-accent"+ title={shapeDef.description}+ >+ <ArcShapeSparkline shape={shapeDef} width={48} height={16} />+ {shapeDef.label}+ </span>+ <FieldLockToggle series={series} field="shape" label="Shape" onSeriesUpdate={onSeriesUpdate} />+ </>) : null}<ThemeChips series={series} arc={arc} onSeriesUpdate={onSeriesUpdate} />+ {(arc.themes?.length ?? 0) > 0 ? (+ <FieldLockToggle series={series} field="themes" label="Themes" onSeriesUpdate={onSeriesUpdate} />+ ) : null}</div>{arc.summary ? (<details className="text-xs text-gray-400">- <summary className="cursor-pointer hover:text-white">Summary</summary>+ <summary className="cursor-pointer hover:text-white inline-flex items-center gap-1.5">+ Summary+ <FieldLockToggle series={series} field="summary" label="Summary" onSeriesUpdate={onSeriesUpdate} />+ </summary><p className="mt-2 whitespace-pre-wrap">{arc.summary}</p></details>) : null}{arc.protagonistArc ? (<details className="text-xs text-gray-400">- <summary className="cursor-pointer hover:text-white">Protagonist arc</summary>+ <summary className="cursor-pointer hover:text-white inline-flex items-center gap-1.5">+ Protagonist arc+ <FieldLockToggle series={series} field="protagonistArc" label="Protagonist arc" onSeriesUpdate={onSeriesUpdate} />+ </summary><p className="mt-2 whitespace-pre-wrap">{arc.protagonistArc}</p></details>) : null}diff --git a/client/src/pages/PipelineIssue.jsx b/client/src/pages/PipelineIssue.jsxindex 4f15692167..c639364841 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, Lock,+ LayoutGrid, Image as ImageIcon, Clapperboard, Users, Settings, Mic, Lock, Unlock,} from 'lucide-react';import toast from '../components/ui/Toast';import Modal from '../components/ui/Modal';@@ -90,6 +90,7 @@ export default function PipelineIssue() {const [settingsOpen, setSettingsOpen] = useState(false);const [lengthProfileSaving, setLengthProfileSaving] = useState(false);const [genConfigSaving, setGenConfigSaving] = useState(false);+ const [stageLockSaving, setStageLockSaving] = useState(false);// Close the settings modal whenever the active stage changes so it doesn't// reopen unexpectedly when the user returns to a previously-visited stage.useEffect(() => { setSettingsOpen(false); }, [stageId]);@@ -175,6 +176,27 @@ export default function PipelineIssue() {if (updated) setIssue(updated);};+ // Toggle the per-stage lock for the currently-active tab. Routes through+ // the generic issue PATCH path so the issue sanitizer + write queue handle+ // the merge; the server enforces the lock semantics at the regenerate+ // boundary (textStages.generateStage, visualStages.enqueueXxx, etc.).+ const handleStageLockToggle = async () => {+ if (stageLockSaving || !issue) return;+ const next = !(issue.stages?.[stageId]?.locked === true);+ setStageLockSaving(true);+ // updatePipelineIssue toasts on rejection via apiCore.request — short-circuit+ // on null and skip a second toast.+ const updated = await updatePipelineIssue(issueId, {+ stages: { [stageId]: { locked: next } },+ }).catch(() => null);+ setStageLockSaving(false);+ if (!updated) return;+ setIssue(updated);+ toast.success(next+ ? `${PIPELINE_STAGE_LABELS[stageId]} locked — regeneration is now blocked`+ : `${PIPELINE_STAGE_LABELS[stageId]} unlocked`);+ };+const handleStageUpdate = (id, updatedStage, updatedIssue) => {if (updatedIssue) {setIssue(updatedIssue);@@ -191,13 +213,17 @@ export default function PipelineIssue() {// 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).+ // Per-stage locks (issue.stages.{id}.locked) layer on top — they refuse+ // regeneration of one stage while sibling stages remain runnable. The+ // pill trailing element prefers per-stage lock first, then the arc/season-+ // wide lock, then the status dot.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+ const ambientLockHint = 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'@@ -211,8 +237,12 @@ 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} />+ const stageLocked = issue?.stages?.[id]?.locked === true;+ const tabLockHint = stageLocked+ ? `${PIPELINE_STAGE_LABELS[id]} stage is locked — unlock it to regenerate`+ : ambientLockHint;+ const trailing = tabLockHint+ ? <Lock size={11} className="text-port-warning" aria-label={tabLockHint} />: <span className={`w-1.5 h-1.5 rounded-full ${STATUS_DOT[status] || STATUS_DOT.empty}`} aria-hidden="true" />;return {id,@@ -220,7 +250,14 @@ export default function PipelineIssue() {icon: STAGE_ICONS[id],trailing,};- }), [issue, series?.targetFormat, lockHint]);+ }), [issue, series?.targetFormat, ambientLockHint]);++ // Active-tab specific banner: prefer per-stage lock when the current tab is+ // locked, fall back to the arc/season-wide message otherwise.+ const activeStageLocked = issue?.stages?.[stageId]?.locked === true;+ const lockHint = activeStageLocked+ ? `${PIPELINE_STAGE_LABELS[stageId]} stage is locked — unlock it to regenerate`+ : ambientLockHint;if (loading) return <div className="p-6 text-gray-500 text-sm">Loading issue…</div>;if (!issue) return null;@@ -303,6 +340,25 @@ export default function PipelineIssue() {<Settings size={16} /></button>)}+ <button+ type="button"+ onClick={handleStageLockToggle}+ disabled={stageLockSaving || autoRunStarting || autoRunActive}+ aria-pressed={activeStageLocked}+ title={activeStageLocked+ ? `Unlock ${PIPELINE_STAGE_LABELS[stageId]} — allows regeneration again`+ : `Lock ${PIPELINE_STAGE_LABELS[stageId]} — blocks regeneration of this stage; siblings stay runnable`}+ aria-label={activeStageLocked ? `Unlock ${PIPELINE_STAGE_LABELS[stageId]}` : `Lock ${PIPELINE_STAGE_LABELS[stageId]}`}+ className={`inline-flex items-center justify-center p-2 rounded-lg border text-sm transition-colors disabled:opacity-40 ${+ activeStageLocked+ ? 'bg-port-warning/10 text-port-warning border-port-warning/40 hover:bg-port-warning/20'+ : 'bg-port-card text-gray-300 border-port-border hover:text-white hover:border-port-accent/40'+ }`}+ >+ {stageLockSaving+ ? <Loader2 size={16} className="animate-spin" />+ : (activeStageLocked ? <Lock size={16} /> : <Unlock size={16} />)}+ </button></div></div>diff --git a/server/routes/pipeline.js b/server/routes/pipeline.jsindex ec9456fbb9..775135c8c1 100644--- a/server/routes/pipeline.js+++ b/server/routes/pipeline.js@@ -175,11 +175,16 @@ const seasonSchema = z.object({locked: z.boolean().optional(),}).passthrough();-// `.passthrough` keeps the door open for future per-season / per-field locks-// without a schema bump — the series sanitizer is the source of truth.-const seriesLockedSchema = z.object(- Object.fromEntries(seriesSvc.LOCKABLE_STAGES.map((k) => [k, z.boolean().optional()])),-).passthrough();+// `.passthrough` keeps the door open for future per-season locks without a+// schema bump — the series sanitizer is the source of truth. `arcFields`+// holds the per-field arc locks (logline / summary / themes / etc.) that+// `commitSeasonsWithRemap` honors when rewriting `series.arc`.+const seriesLockedSchema = z.object({+ ...Object.fromEntries(seriesSvc.LOCKABLE_STAGES.map((k) => [k, z.boolean().optional()])),+ arcFields: z.object(+ Object.fromEntries(seriesSvc.ARC_LOCKABLE_FIELDS.map((k) => [k, z.boolean().optional()])),+ ).optional(),+}).passthrough();const seriesCreateSchema = z.object({name: z.string().trim().min(1).max(seriesSvc.NAME_MAX),@@ -598,6 +603,7 @@ const extractAudioLinesSchema = z.object({ force: z.boolean().optional() });router.post('/issues/:id/stages/audio/extract-lines', asyncHandler(async (req, res) => {const body = validateRequest(extractAudioLinesSchema, req.body ?? {});const issue = await issuesSvc.getIssue(req.params.id).catch((err) => { throw mapServiceError(err); });+ issuesSvc.assertStageUnlocked(issue, 'audio');const existingLines = issue.stages?.audio?.lines || [];if (existingLines.length > 0 && !body.force) {throw new ServerError(@@ -679,6 +685,7 @@ router.post('/issues/:id/stages/audio/lines/:lineIdx/render', asyncHandler(async}const body = validateRequest(lineRenderSchema, req.body ?? {});const issue = await issuesSvc.getIssue(req.params.id).catch((err) => { throw mapServiceError(err); });+ issuesSvc.assertStageUnlocked(issue, 'audio');const lines = issue.stages?.audio?.lines || [];const line = lines[lineIdx];if (!line) {@@ -1254,6 +1261,7 @@ router.post('/issues/:id/stages/:stageId/generate', asyncHandler(async (req, resrouter.post('/issues/:id/stages/storyboards/extract-scenes', asyncHandler(async (req, res) => {const body = validateRequest(extractScenesSchema, req.body ?? {});const issue = await issuesSvc.getIssue(req.params.id).catch((err) => { throw mapServiceError(err); });+ issuesSvc.assertStageUnlocked(issue, 'storyboards');const series = await seriesSvc.getSeries(issue.seriesId).catch((err) => { throw mapServiceError(err); });const sourceKind = body.from;@@ -1324,6 +1332,7 @@ router.post('/issues/:id/stages/storyboards/extract-scenes', asyncHandler(asyncrouter.post('/issues/:id/stages/comicPages/extract-pages', asyncHandler(async (req, res) => {const body = validateRequest(extractComicPagesSchema, req.body ?? {});const issue = await issuesSvc.getIssue(req.params.id).catch((err) => { throw mapServiceError(err); });+ issuesSvc.assertStageUnlocked(issue, 'comicPages');const source = (issue.stages?.comicScript?.output || '').trim();if (!source) {diff --git a/server/services/pipeline/arcPlanner.js b/server/services/pipeline/arcPlanner.jsindex a1f18a5de3..ceef5a27d6 100644--- a/server/services/pipeline/arcPlanner.js+++ b/server/services/pipeline/arcPlanner.js@@ -21,8 +21,8 @@import { runStagedLLM } from '../../lib/stageRunner.js';import { ServerError } from '../../lib/errorHandler.js';-import { getSeries, updateSeries, updateSeasonOnSeries } from './series.js';-import { listIssues, updateIssue, recomputeIssueNumbersForSeries, getIssue, updateStageWithLatest } from './issues.js';+import { getSeries, updateSeries, updateSeasonOnSeries, ARC_LOCKABLE_FIELDS } from './series.js';+import { listIssues, updateIssue, recomputeIssueNumbersForSeries, getIssue, updateStageWithLatest, assertStageUnlocked } from './issues.js';import { emitRecordUpdated, withReexportSuppressed } from '../sharing/recordEvents.js';import { getSeason } from './seasons.js';import {@@ -530,6 +530,10 @@ export async function generateComicCoverConcepts(issueId, options = {}) {throw makeErr(`Invalid target: ${target}`, ERR_VALIDATION);}const issue = await getIssue(issueId);+ // `commit: true` mutates `stages.comicPages.cover/backCover.script` —+ // refuse when the stage is locked. Preview-only (`commit !== true`) is+ // allowed: it just returns the LLM output without persisting.+ if (options.commit) assertStageUnlocked(issue, 'comicPages');const series = await getSeries(issue.seriesId);const proseFull = (issue.stages?.prose?.output || '').trim();// Cap prose at a generous excerpt so very long drafts don't blow the@@ -962,6 +966,21 @@ export async function resolveVerifyIssues(seriesId, options = {}) {};}+// Preserve per-field arc locks. When `currentSeries.locked.arcFields[k]` is+// true, the incoming arc's value for `k` is replaced with the existing one so+// auto-resolve / regenerate flows can rewrite unlocked fields without+// clobbering user-frozen ones. `null` next-arc (no incoming arc) is passed+// through unchanged — the persist layer's sanitizer drops it.+export function mergeArcWithLocks(currentArc, nextArc, lockedFields) {+ if (!nextArc || !lockedFields || typeof lockedFields !== 'object') return nextArc;+ if (!currentArc) return nextArc;+ const merged = { ...nextArc };+ for (const field of ARC_LOCKABLE_FIELDS) {+ if (lockedFields[field] === true) merged[field] = currentArc[field];+ }+ return merged;+}+/*** Persist a new `arc` + `seasons[]` onto a series, migrating any child issues* whose `seasonId` referenced a season that the new shape dropped or renamed.@@ -973,11 +992,16 @@ export async function resolveVerifyIssues(seriesId, options = {}) {* positional 1:1 fallback. Unmatched orphans get `seasonId: null` so they fall* into the visible "Un-grouped" bucket instead of vanishing.*+ * Per-field arc locks (`series.locked.arcFields`) are honored: locked fields+ * are restored from `currentSeries.arc` before the persist, so an auto-resolve+ * that proposes a new logline can preserve the user-frozen themes verbatim.+ ** `currentSeries` is the pre-write snapshot; pass the result of `getSeries(id)`* so we know which ids existed before the write.*/export async function commitSeasonsWithRemap(currentSeries, { arc, seasons }) {const seriesId = currentSeries.id;+ const mergedArc = mergeArcWithLocks(currentSeries.arc, arc, currentSeries.locked?.arcFields);const newIds = new Set((seasons || []).map((s) => s.id));const droppedOldSeasons = (currentSeries.seasons || []).filter((s) => !newIds.has(s.id));const oldIds = new Set((currentSeries.seasons || []).map((s) => s.id));@@ -1000,7 +1024,7 @@ export async function commitSeasonsWithRemap(currentSeries, { arc, seasons }) {// the exact orphan state this helper was written to prevent.let updated;await withReexportSuppressed('series', seriesId, async () => {- updated = await updateSeries(seriesId, { arc, seasons });+ updated = await updateSeries(seriesId, { arc: mergedArc, seasons });for (const iss of reassignList) {const target = remap.get(iss.seasonId) ?? null;await updateIssue(iss.id, { seasonId: target }, { skipRenumber: true });@@ -1085,4 +1109,5 @@ export const __testing = {shapeFindings,renderVolumeIssue,buildNeighborVolumes,+ mergeArcWithLocks,};diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.jsindex 016640acc7..5f893e2280 100644--- a/server/services/pipeline/arcPlanner.test.js+++ b/server/services/pipeline/arcPlanner.test.js@@ -793,6 +793,79 @@ describe('arcPlanner — commitSeasonsWithRemap', () => {const finalI1 = await issuesSvc.getIssue(i1.id);expect(finalI1.seasonId).toBeNull();});++ it('preserves locked arc fields when commit rewrites the arc', async () => {+ const s = await setupSeries({+ arc: {+ logline: 'KEEP THIS LOGLINE',+ summary: 'rewrite the summary',+ themes: ['keep', 'these'],+ protagonistArc: 'rewrite the pa',+ shape: 'rags-to-riches',+ status: 'draft',+ },+ locked: { arcFields: { logline: true, themes: true } },+ });+ const cur = await seriesSvc.getSeries(s.id);+ const out = await planner.commitSeasonsWithRemap(cur, {+ arc: {+ logline: 'NEW LOGLINE (should be ignored)',+ summary: 'a fresh summary',+ themes: ['fresh', 'replaced'],+ protagonistArc: 'a fresh pa',+ shape: 'icarus',+ status: 'draft',+ },+ seasons: [],+ });+ // Locked fields preserved verbatim from the existing arc.+ expect(out.series.arc.logline).toBe('KEEP THIS LOGLINE');+ expect(out.series.arc.themes).toEqual(['keep', 'these']);+ // Unlocked fields took the new value.+ expect(out.series.arc.summary).toBe('a fresh summary');+ expect(out.series.arc.protagonistArc).toBe('a fresh pa');+ expect(out.series.arc.shape).toBe('icarus');+ });+});++describe('arcPlanner — mergeArcWithLocks', () => {+ it('replaces locked fields with the current arc values', () => {+ const current = { logline: 'a', summary: 'b', themes: ['t1'], protagonistArc: 'c', shape: 's1' };+ const next = { logline: 'A', summary: 'B', themes: ['t2'], protagonistArc: 'C', shape: 's2' };+ const merged = planner.__testing.mergeArcWithLocks(current, next, { logline: true, themes: true });+ expect(merged.logline).toBe('a');+ expect(merged.themes).toEqual(['t1']);+ expect(merged.summary).toBe('B');+ expect(merged.shape).toBe('s2');+ });++ it('returns next unchanged when lockedFields is empty / absent', () => {+ const current = { logline: 'a' };+ const next = { logline: 'A' };+ expect(planner.__testing.mergeArcWithLocks(current, next, {})).toEqual({ logline: 'A' });+ expect(planner.__testing.mergeArcWithLocks(current, next, null)).toEqual({ logline: 'A' });+ expect(planner.__testing.mergeArcWithLocks(current, next, undefined)).toEqual({ logline: 'A' });+ });++ it('passes next through when there is no current arc to preserve from', () => {+ const next = { logline: 'A' };+ expect(planner.__testing.mergeArcWithLocks(null, next, { logline: true })).toEqual({ logline: 'A' });+ });++ it('returns next when next is null/undefined (no-op)', () => {+ expect(planner.__testing.mergeArcWithLocks({ logline: 'a' }, null, { logline: true })).toBeNull();+ expect(planner.__testing.mergeArcWithLocks({ logline: 'a' }, undefined, { logline: true })).toBeUndefined();+ });++ it('ignores unknown lock keys (only ARC_LOCKABLE_FIELDS are honored)', () => {+ const current = { logline: 'a', summary: 'b' };+ const next = { logline: 'A', summary: 'B' };+ const merged = planner.__testing.mergeArcWithLocks(current, next, { logline: true, bogusKey: true });+ expect(merged.logline).toBe('a');+ expect(merged.summary).toBe('B');+ // bogusKey didn't survive into the merged shape.+ expect(merged.bogusKey).toBeUndefined();+ });});describe('arcPlanner — buildSeasonRemap', () => {diff --git a/server/services/pipeline/episodeVideo.js b/server/services/pipeline/episodeVideo.jsindex f2b63d560f..8caa806600 100644--- a/server/services/pipeline/episodeVideo.js+++ b/server/services/pipeline/episodeVideo.js@@ -14,7 +14,7 @@* surface the final stitched video when complete.*/import { composeVisualPrompt } from './visualStages.js';-import { getIssue, updateStage } from './issues.js';+import { getIssue, updateStage, assertStageUnlocked } from './issues.js';import { getSeries } from './series.js';import { getSeriesCanon } from './seriesCanon.js';import { createProject as createCDProject, setTreatment as setCDTreatment } from '../creativeDirector/local.js';@@ -136,6 +136,10 @@ export function buildTreatmentFromStoryboards({ issue, series, canon = null }) {export async function startEpisodeVideoForIssue(issueId, options = {}) {const [issue, settings] = await Promise.all([getIssue(issueId), getSettings()]);+ // Reuse path (existing cdProjectId) is still allowed when locked — locking+ // a stage freezes regeneration, not status reads. The fresh-start branch+ // below builds a new CD project + treatment, which IS regeneration; the+ // lock check gates that branch only.const existing = issue.stages?.episodeVideo?.cdProjectId;const series = await getSeries(issue.seriesId);// Canon (characters / places / objects) lives on the linked universe@@ -151,6 +155,9 @@ export async function startEpisodeVideoForIssue(issueId, options = {}) {// times, so the user sees "N scenes" matching what was actually queued.return { cdProjectId: existing, reused: true, scenes: treatment.scenes.length };}+ // Fresh-start branch — gate on the per-stage lock now that we know we're+ // about to spin up a new CD project + render run.+ assertStageUnlocked(issue, 'episodeVideo');const aspectRatio = options.aspectRatio || '16:9';const quality = options.quality || 'standard';const modelId = options.modelId || settings?.videoGen?.defaultModelId || getDefaultVideoModelId();diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.jsindex 2919cebb14..f970eba562 100644--- a/server/services/pipeline/issues.js+++ b/server/services/pipeline/issues.js@@ -28,6 +28,7 @@ import {} from '../../lib/issueLength.js';import { sanitizeOrigin } from '../../lib/sharingOrigin.js';import { sanitizeVisualStyleRef } from '../../lib/visualStyles.js';+import { ServerError } from '../../lib/errorHandler.js';import { ARC_ROLES } from '../../lib/storyArc.js';import { isStr, trimTo } from '../../lib/storyBible.js';import { sanitizeCoverLike } from '../../lib/renderSlot.js';@@ -49,6 +50,7 @@ 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';+export const ERR_STAGE_LOCKED = 'PIPELINE_STAGE_LOCKED';const makeErr = (message, code) => Object.assign(new Error(message), { code });const ISSUE_ID_RE = /^iss-[A-Za-z0-9-]+$/;@@ -99,8 +101,26 @@ const emptyStage = () => ({lastRunId: null,errorMessage: '',updatedAt: null,+ locked: false,});+/**+ * Throw a 400 ServerError when `issue.stages[stageId].locked === true`.+ * Every code path that regenerates a stage's primary artifact (LLM text run,+ * image render, video render, audio synth, refine-prompt, extract-scenes /+ * extract-pages) must call this so the lock contract is uniform. Sibling to+ * the series-level (`series.locked.arc`) and season-level (`season.locked`)+ * checks elsewhere — any of the three rejects.+ */+export function assertStageUnlocked(issue, stageId) {+ if (issue?.stages?.[stageId]?.locked === true) {+ throw new ServerError(+ `Stage "${stageId}" is locked — unlock it before regenerating`,+ { status: 400, code: ERR_STAGE_LOCKED },+ );+ }+}+const sanitizeStage = (raw) => {if (!raw || typeof raw !== 'object') return emptyStage();const status = STAGE_STATUSES.includes(raw.status) ? raw.status : 'empty';@@ -111,6 +131,11 @@ const sanitizeStage = (raw) => {lastRunId: isStr(raw.lastRunId) && raw.lastRunId ? raw.lastRunId : null,errorMessage: trimTo(raw.errorMessage, STAGE_NOTES_MAX),updatedAt: isStr(raw.updatedAt) ? raw.updatedAt : null,+ // Per-stage editorial lock. When true, `generateStage` (text) and the+ // visual stage `enqueueXxx` entry points refuse — lets the user freeze a+ // finalized comic script while still iterating storyboards. Independent+ // of `series.locked.arc` and `season.locked`; any of the three rejects.+ locked: raw.locked === true,};};diff --git a/server/services/pipeline/issues.test.js b/server/services/pipeline/issues.test.jsindex c227cc8308..5734f6650c 100644--- a/server/services/pipeline/issues.test.js+++ b/server/services/pipeline/issues.test.js@@ -126,9 +126,43 @@ describe('pipeline issues service', () => {for (const id of svc.STAGE_IDS) {expect(i.stages[id].status).toBe('empty');expect(i.stages[id].output).toBe('');+ // Per-stage lock defaults to false so existing issues stay regenerable.+ expect(i.stages[id].locked).toBe(false);}});+ describe('per-stage lock', () => {+ it('round-trips locked:true through updateStage', async () => {+ const i = await svc.createIssue({ seriesId: 'ser-1', title: 'L' });+ const { stage } = await svc.updateStage(i.id, 'comicScript', { locked: true });+ expect(stage.locked).toBe(true);+ });++ it('updateStage with non-boolean locked coerces back to false', async () => {+ const i = await svc.createIssue({ seriesId: 'ser-1', title: 'L' });+ await svc.updateStage(i.id, 'idea', { locked: true });+ // Anything that isn't strictly `true` clears the lock — guards against+ // a truthy-but-not-boolean payload silently locking the stage.+ const after = await svc.updateStage(i.id, 'idea', { locked: 'yes' });+ expect(after.stage.locked).toBe(false);+ });++ it('assertStageUnlocked throws ERR_STAGE_LOCKED when stage is locked', () => {+ const issue = { stages: { idea: { locked: true } } };+ expect(() => svc.assertStageUnlocked(issue, 'idea')).toThrow(/locked/);+ try { svc.assertStageUnlocked(issue, 'idea'); } catch (err) {+ expect(err.code).toBe(svc.ERR_STAGE_LOCKED);+ expect(err.status).toBe(400);+ }+ });++ it('assertStageUnlocked is a no-op when stage is unlocked or missing', () => {+ expect(() => svc.assertStageUnlocked({ stages: { idea: { locked: false } } }, 'idea')).not.toThrow();+ expect(() => svc.assertStageUnlocked({ stages: {} }, 'idea')).not.toThrow();+ expect(() => svc.assertStageUnlocked(null, 'idea')).not.toThrow();+ });+ });+it('updateStage patches only the named stage', async () => {const i = await svc.createIssue({ seriesId: 'ser-1', title: 'First' });const { issue, stage } = await svc.updateStage(i.id, 'idea', {@@ -446,7 +480,7 @@ describe('pipeline issues service', () => {const i = await svc.createIssue({ seriesId: 'ser-1', title: 'P' });expect(i.stages.audio).toEqual({status: 'empty', input: '', output: '', lastRunId: null,- errorMessage: '', updatedAt: null, lines: [], music: null,+ errorMessage: '', updatedAt: null, lines: [], music: null, locked: false,});});diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.jsindex 730ab85d11..6ca0a5ff45 100644--- a/server/services/pipeline/series.js+++ b/server/services/pipeline/series.js@@ -59,12 +59,27 @@ export const ISSUE_COUNT_TARGET_MAX = 999;export const LOCKABLE_STAGES = Object.freeze(['arc']);+// Per-field arc lock targets. Each field can be individually frozen so+// `resolveVerifyIssues` / `commitSeasonsWithRemap` rewrite unlocked fields+// while preserving locked ones verbatim. Sibling to the binary `locked.arc`+// (which freezes everything); the two stack — `locked.arc: true` always wins.+export const ARC_LOCKABLE_FIELDS = Object.freeze([+ 'logline', 'summary', 'protagonistArc', 'themes', 'shape',+]);+const sanitizeSeriesLocked = (raw = {}) => {if (!raw || typeof raw !== 'object') return {};const out = {};for (const key of LOCKABLE_STAGES) {if (raw[key] === true) out[key] = true;}+ if (raw.arcFields && typeof raw.arcFields === 'object') {+ const arcFields = {};+ for (const k of ARC_LOCKABLE_FIELDS) {+ if (raw.arcFields[k] === true) arcFields[k] = true;+ }+ if (Object.keys(arcFields).length > 0) out.arcFields = arcFields;+ }return out;};diff --git a/server/services/pipeline/textStages.js b/server/services/pipeline/textStages.jsindex 4f25b7dce3..cd2a228b60 100644--- a/server/services/pipeline/textStages.js+++ b/server/services/pipeline/textStages.js@@ -17,7 +17,7 @@import { runStagedLLM } from '../../lib/stageRunner.js';import { getSeries } from './series.js';import { extractCanonFromProse } from '../universeCanon.js';-import { getIssue, listIssues, updateStage, TEXT_STAGE_IDS } from './issues.js';+import { getIssue, listIssues, updateStage, assertStageUnlocked, TEXT_STAGE_IDS } from './issues.js';import { getSeriesCanon } from './seriesCanon.js';import { compareIssuesByPosition } from './arcPlanner.js';import { computeIssueTargets } from '../../lib/issueLength.js';@@ -188,6 +188,12 @@ export async function generateStage(issueId, stageId, options = {}) {const series = await getSeries(issue.seriesId);const canon = await getSeriesCanon(series);+ // Per-stage editorial lock — refuse before touching the stage record so a+ // locked stage doesn't get bumped to 'generating' status only to be reset.+ // Sibling to the arc / season checks elsewhere in the planner; any of the+ // three rejects.+ assertStageUnlocked(issue, stageId);+await updateStage(issueId, stageId, { status: 'generating', errorMessage: '' });const ctx = buildStageContext({ series, canon, issue, stageId, seedInput: options.seedInput });diff --git a/server/services/pipeline/textStages.test.js b/server/services/pipeline/textStages.test.jsindex bee8f11d1b..082232ecc8 100644--- a/server/services/pipeline/textStages.test.js+++ b/server/services/pipeline/textStages.test.js@@ -124,6 +124,18 @@ describe('pipeline text stage generator', () => {await expect(textStages.generateStage(issue.id, 'comicPages')).rejects.toThrow(/unsupported stageId/);});+ it('refuses regeneration when the per-stage lock is set, and leaves status untouched', async () => {+ const { issue } = await seed();+ await issuesSvc.updateStage(issue.id, 'idea', { locked: true, status: 'ready', output: 'final beats' });+ await expect(textStages.generateStage(issue.id, 'idea'))+ .rejects.toMatchObject({ code: issuesSvc.ERR_STAGE_LOCKED });+ // No status drift to 'generating' — the guard runs before the updateStage call.+ const after = await issuesSvc.getIssue(issue.id);+ expect(after.stages.idea.status).toBe('ready');+ expect(after.stages.idea.output).toBe('final beats');+ expect(after.stages.idea.locked).toBe(true);+ });+it('prompt context carries lengthTargets from a named non-default profile (extended)', async () => {const { series } = await seed();// Create an issue with the 'extended' profile — distinct from 'standard' sodiff --git a/server/services/pipeline/visualStages.js b/server/services/pipeline/visualStages.jsindex 44af72c66a..68f1c4353e 100644--- a/server/services/pipeline/visualStages.js+++ b/server/services/pipeline/visualStages.js@@ -26,7 +26,7 @@import { enqueueJob } from '../mediaJobQueue/index.js';import { getSettings } from '../settings.js';import { getSeries } from './series.js';-import { getIssue, updateStage, VISUAL_STAGE_IDS } from './issues.js';+import { getIssue, updateStage, assertStageUnlocked, VISUAL_STAGE_IDS } from './issues.js';import { resolveGalleryImage } from '../../lib/fileUtils.js';import { buildComicPagesOwner, buildSeasonCoverOwner, buildStoryboardsShotOwner } from './owners.js';import { getUniverse, joinInfluenceList } from '../universeBuilder.js';@@ -398,6 +398,7 @@ async function enqueueComicCoverLike(issueId, target, options = {}) {throw new Error(`enqueueComicCoverLike: unknown target "${target}"`);}const { issue, settings, series, world } = await loadBibleContext(issueId);+ assertStageUnlocked(issue, 'comicPages');const record = issue.stages?.comicPages?.[target] || null;const scriptOptionKey = target === 'cover' ? 'coverScript' : 'backCoverScript';const script = typeof options[scriptOptionKey] === 'string'@@ -693,6 +694,7 @@ export async function enqueueVisualComicPage(issueId, options = {}) {});}const { issue, settings, series, world, canon } = await loadBibleContext(issueId);+ assertStageUnlocked(issue, 'comicPages');const pages = Array.isArray(issue.stages?.comicPages?.pages) ? issue.stages.comicPages.pages : [];const page = pages[pageIndex];if (!page) {@@ -780,6 +782,7 @@ export async function enqueueVisualImage(issueId, stageId, options = {}) {});}const { issue, settings, series, world, canon } = await loadBibleContext(issueId);+ assertStageUnlocked(issue, stageId);const mode = resolveMode(options, settings);const matchedCharacters = matchCharactersInText(options.description || '', canon.characters);const prompt = composeVisualPrompt({@@ -824,6 +827,7 @@ export async function enqueueStoryboardSceneVideo(issueId, sceneIndex, options =});}const { issue, settings, series, world, canon } = await loadBibleContext(issueId);+ assertStageUnlocked(issue, 'storyboards');const pythonPath = settings.imageGen?.local?.pythonPath || null;if (!pythonPath) {throw new ServerError(@@ -916,6 +920,7 @@ export async function enqueueStoryboardShotStartFrame(issueId, sceneIndex, shotI});}const { issue, settings, series, world, canon } = await loadBibleContext(issueId);+ assertStageUnlocked(issue, 'storyboards');const scenes = Array.isArray(issue.stages?.storyboards?.scenes)? [...issue.stages.storyboards.scenes]: [];@@ -1005,6 +1010,7 @@ export async function refineComicPanelPrompt(issueId, pageIndex, panelIndex, opt});}const { issue, series } = await loadRefineContext(issueId);+ assertStageUnlocked(issue, 'comicPages');const pages = Array.isArray(issue.stages?.comicPages?.pages) ? [...issue.stages.comicPages.pages] : [];const page = pages[pi];if (!page) {@@ -1087,6 +1093,7 @@ export async function refineStoryboardScenePrompt(issueId, sceneIndex, options =});}const { issue, series } = await loadRefineContext(issueId);+ assertStageUnlocked(issue, 'storyboards');const scenes = Array.isArray(issue.stages?.storyboards?.scenes)? [...issue.stages.storyboards.scenes]: [];diff --git a/server/services/pipeline/visualStages.test.js b/server/services/pipeline/visualStages.test.jsindex 9f5d71a6e6..63831e91b6 100644--- a/server/services/pipeline/visualStages.test.js+++ b/server/services/pipeline/visualStages.test.js@@ -34,6 +34,9 @@ const updateStageMock = vi.fn(async (issueId, stageId, patch) => ({vi.mock('./issues.js', () => ({getIssue: (...a) => getIssueMock(...a),updateStage: (...a) => updateStageMock(...a),+ // Default to "not locked" so existing tests keep their semantics; per-stage+ // lock enforcement is covered in its own describe block.+ assertStageUnlocked: vi.fn(() => undefined),VISUAL_STAGE_IDS: ['comicPages', 'storyboards', 'episodeVideo'],STAGE_IDS: ['idea', 'prose', 'comicScript', 'teleplay', 'comicPages', 'storyboards', 'episodeVideo'],}));