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
add an autopilot option that unlocks the series' own records before a run
[._.]/ Adam Eivybf6481f2b999
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex d1afd87c4c..a1d9dfa966 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Added+- Series Pipeline **Autonomous mode** gains an **"Unlock everything this series owns first"** option. A locked arc, volume, issue stage, or canon entry makes the corresponding fix path throw or silently skip, so a run would surface an editorial finding and then pause on a problem it was never allowed to resolve — leaving you to hunt down every lock toggle by hand before re-running. With the option on, the run's first step clears the arc freeze, the per-field arc locks, every volume lock, every issue stage lock, and the locks on the universe canon **this series owns**, then reports exactly what it cleared. Two boundaries are hard: canon belonging to (or shared with) another series in the same universe stays locked, and the pass is never destructive — it clears lock bits only, so characters and objects can be rewritten in full but stay in the Universe and the Catalog. Because unlocking the volume locks also removes the only thing that used to stop a regenerated arc from *dropping* a volume, arc rewrites in this mode now re-insert any volume the rewrite omitted. Off by default, saved as the default once toggled, and shown in the dry-run plan before you commit.+- Series Pipeline **Autonomous mode** now says which AI it will spend on. The Options popover names the provider and model the run resolves to, links to where per-stage pins and reasoning effort are configured, and offers a per-run provider/model override (never persisted — a one-off run can't silently re-point the whole series). The live progress line names the provider of an in-flight run too, including one the scheduler started.## Fixeddiff --git a/client/src/components/pipeline/AutopilotPanel.jsx b/client/src/components/pipeline/AutopilotPanel.jsxindex 4793a7d9ed..2cd7258ea9 100644--- a/client/src/components/pipeline/AutopilotPanel.jsx+++ b/client/src/components/pipeline/AutopilotPanel.jsx@@ -46,6 +46,10 @@ const DEFAULT_REVISION_PLATEAU_DELTA = 0.3;// defaults ON (the point of the phase); the weighted [0,10] threshold the// foundation must clear before drafting mirrors autonovel's 7.5 bar; the improve// loop is bounded by MAX_FOUNDATION_ROUNDS (3).+// Unlock-everything pre-pass — mirror the server default (off). Opt-in because+// it mutates lock state the user set by hand; it only ever CLEARS locks (and+// only on records this series owns), never deletes anything.+const DEFAULT_UNLOCK_FOR_RUN = false;const DEFAULT_FOUNDATION_GATE = true;const DEFAULT_FOUNDATION_THRESHOLD = 7.5;const DEFAULT_FOUNDATION_ROUNDS = 3;@@ -133,6 +137,7 @@ const SEVERITY_COLORS = {// Human labels for each conductor step kind (matches seriesAutopilot.js).const STEP_LABELS = {+ unlockLocks: 'Unlocking series records',generateArc: 'Generating arc',generateEpisodes: 'Generating episodes',verifyArc: 'Verifying arc',@@ -175,6 +180,19 @@ function frameLabel(f) {const sev = s && (s.high || s.medium || s.low) ? ` (${s.high}H/${s.medium}M/${s.low}L)` : '';return `Editorial check: ${name} — ${f.count} finding(s)${sev}`;}+ // Unlock pre-pass: report what it actually cleared (and what it deliberately+ // left frozen), so "unlocked everything" is never an unverifiable claim.+ case 'unlock:applied': {+ if (!f.unlockedAny) return 'Unlock — nothing was locked';+ const parts = [];+ if (f.arc) parts.push('arc');+ if (f.arcFields) parts.push(`${f.arcFields} arc field(s)`);+ if (f.seasons) parts.push(`${f.seasons} volume(s)`);+ if (f.stages) parts.push(`${f.stages} stage(s)`);+ if (f.canon) parts.push(`${f.canon} canon entr${f.canon === 1 ? 'y' : 'ies'}`);+ const kept = f.canonForeignKept ? ` · kept ${f.canonForeignKept} other series' canon locked` : '';+ return `Unlocked ${parts.join(', ')}${kept}`;+ }case 'render:queued': return `Queued draft render: ${f.target}`;case 'gap:filed': return `Filed CoS task (${f.gapKind})`;// #1617 — immediate cancel ack; the active step finishes before `canceled`.@@ -254,6 +272,10 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdateconst [revisionPlateauDelta, setRevisionPlateauDelta] = useState(DEFAULT_REVISION_PLATEAU_DELTA);// Foundation-quality gate (#2176) — enable toggle + weighted threshold + round// bound. Persisted like the other options (saved default + per-run override).+ // Unlock-everything pre-pass. Persisted like the other booleans (saved default+ // + per-run override) so a series the user drives unlocked stays that way on+ // Resume.+ const [unlockForRun, setUnlockForRun] = useState(DEFAULT_UNLOCK_FOR_RUN);const [foundationGate, setFoundationGate] = useState(DEFAULT_FOUNDATION_GATE);const [foundationThreshold, setFoundationThreshold] = useState(DEFAULT_FOUNDATION_THRESHOLD);const [foundationRounds, setFoundationRounds] = useState(DEFAULT_FOUNDATION_ROUNDS);@@ -271,6 +293,7 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdateconst revisionMinEditedRef = useRef(false);const revisionMaxEditedRef = useRef(false);const revisionDeltaEditedRef = useRef(false);+ const unlockForRunEditedRef = useRef(false);const foundationGateEditedRef = useRef(false);const foundationThresholdEditedRef = useRef(false);const foundationRoundsEditedRef = useRef(false);@@ -351,6 +374,7 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdateif (!revisionMinEditedRef.current) setRevisionMinCycles(Number.isInteger(pec.revisionMinCycles) ? pec.revisionMinCycles : DEFAULT_REVISION_MIN_CYCLES);if (!revisionMaxEditedRef.current) setRevisionMaxCycles(Number.isInteger(pec.revisionMaxCycles) ? pec.revisionMaxCycles : DEFAULT_REVISION_MAX_CYCLES);if (!revisionDeltaEditedRef.current) setRevisionPlateauDelta(Number.isFinite(pec.revisionPlateauDelta) ? pec.revisionPlateauDelta : DEFAULT_REVISION_PLATEAU_DELTA);+ if (!unlockForRunEditedRef.current) setUnlockForRun(typeof pec.unlockForRun === 'boolean' ? pec.unlockForRun : DEFAULT_UNLOCK_FOR_RUN);if (!foundationGateEditedRef.current) setFoundationGate(typeof pec.foundationGate === 'boolean' ? pec.foundationGate : DEFAULT_FOUNDATION_GATE);if (!foundationThresholdEditedRef.current) setFoundationThreshold(Number.isFinite(pec.foundationThreshold) ? pec.foundationThreshold : DEFAULT_FOUNDATION_THRESHOLD);if (!foundationRoundsEditedRef.current) setFoundationRounds(Number.isInteger(pec.maxFoundationRounds) ? pec.maxFoundationRounds : DEFAULT_FOUNDATION_ROUNDS);@@ -386,6 +410,11 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdateconst editFoundationRounds = useCallback((v) => { foundationRoundsEditedRef.current = true; setFoundationRounds(v); }, []);// Boolean toggle — persist immediately (like notifyOnPause) so the saved// default tracks the choice and Resume reuses it.+ const editUnlockForRun = useCallback((v) => {+ unlockForRunEditedRef.current = true;+ setUnlockForRun(v);+ persistRounds({ unlockForRun: v });+ }, [persistRounds]);const editFoundationGate = useCallback((v) => {foundationGateEditedRef.current = true;setFoundationGate(v);@@ -508,6 +537,9 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate// #2176 — foundation gate. Persist + override like the other options, only// when edited (untouched → server resolves from the persisted setting, then// the default: gate ON / threshold 7.5 / 3 rounds).+ // Unlock pre-pass — persists + overrides like the other booleans. Untouched+ // sends nothing → the server resolves it from the persisted setting, then off.+ if (unlockForRunEditedRef.current) roundOverrides.unlockForRun = unlockForRun;if (foundationGateEditedRef.current) roundOverrides.foundationGate = foundationGate;if (foundationThresholdEditedRef.current) roundOverrides.foundationThreshold = clampFoundationThreshold(foundationThreshold, DEFAULT_FOUNDATION_THRESHOLD);if (foundationRoundsEditedRef.current) roundOverrides.maxFoundationRounds = clampRound(foundationRounds, DEFAULT_FOUNDATION_ROUNDS);@@ -534,7 +566,7 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate// effect can reject a stale terminal frame from the previous run.activeRunIdRef.current = res.runId || null;setActive(true);- }, [seriesId, includeVisual, fileGaps, arcRounds, editorialRounds, beatContinuityRounds, checkPauseThreshold, notifyOnPause, revisionEnabled, revisionMinCycles, revisionMaxCycles, revisionPlateauDelta, foundationGate, foundationThreshold, foundationRounds, readinessGate, providerOverride, modelOverride, persistRounds]);+ }, [seriesId, includeVisual, fileGaps, arcRounds, editorialRounds, beatContinuityRounds, checkPauseThreshold, notifyOnPause, unlockForRun, revisionEnabled, revisionMinCycles, revisionMaxCycles, revisionPlateauDelta, foundationGate, foundationThreshold, foundationRounds, readinessGate, providerOverride, modelOverride, persistRounds]);const cancel = useCallback(async () => {await cancelPipelineAutopilot(seriesId).catch(() => null);@@ -655,6 +687,15 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate<input type="checkbox" checked={foundationGate} onChange={(e) => editFoundationGate(e.target.checked)} />Judge the foundation (world / characters / arc) before drafting</label>+ <label className="flex items-center gap-2 text-xs text-gray-300">+ <input type="checkbox" checked={unlockForRun} onChange={(e) => editUnlockForRun(e.target.checked)} />+ Unlock everything this series owns first (full edit control)+ </label>+ {unlockForRun ? (+ <p className="text-[11px] text-gray-500">+ Clears the arc freeze, arc-field locks, volume locks, issue stage locks, and the locks on the universe canon this series owns — so the run can actually apply the fixes its editorial passes find. Canon belonging to (or shared with) another series in the same universe stays locked, and nothing is ever deleted: characters and objects can be rewritten but stay in the Universe and the Catalog. Locks are <em>not</em> restored when the run ends. Saved as the default and reused on Resume.+ </p>+ ) : null}<div className="flex flex-wrap gap-4 pt-1"><RoundInputid="autopilot-arc-rounds"diff --git a/client/src/components/pipeline/AutopilotPanel.test.jsx b/client/src/components/pipeline/AutopilotPanel.test.jsxindex 1c9e02e099..b1b9a158bc 100644--- a/client/src/components/pipeline/AutopilotPanel.test.jsx+++ b/client/src/components/pipeline/AutopilotPanel.test.jsx@@ -112,6 +112,43 @@ describe('AutopilotPanel', () => {);});+ it('sends AND persists unlockForRun once the unlock checkbox is toggled', async () => {+ renderPanel({ id: 's1', targetFormat: 'comic' });+ await waitFor(() => expect(getPipelineAutopilotStatus).toHaveBeenCalled());+ fireEvent.click(screen.getByRole('button', { name: /options/i }));+ fireEvent.click(screen.getByRole('checkbox', { name: /unlock everything this series owns/i }));+ // The explainer only appears once armed — it carries the two guarantees.+ expect(screen.getByText(/nothing is ever deleted/i)).toBeInTheDocument();+ // The persist rides the serialized tail promise, so it lands a tick later.+ await waitFor(() => expect(patchSettingsSlice).toHaveBeenCalledWith('pipelineEditorialChecks', { unlockForRun: true }, { silent: true }));+ fireEvent.click(screen.getByRole('button', { name: /run autopilot/i }));+ await waitFor(() => expect(startPipelineAutopilot).toHaveBeenCalledWith(+ 's1', { includeVisual: true, fileGaps: false, unlockForRun: true }, { silent: true },+ ));+ });++ it('omits unlockForRun when the checkbox is untouched (server resolves the saved default)', async () => {+ getSettings.mockResolvedValue({ pipelineEditorialChecks: { unlockForRun: true } });+ renderPanel({ id: 's1', targetFormat: 'comic' });+ await waitFor(() => expect(getPipelineAutopilotStatus).toHaveBeenCalled());+ fireEvent.click(screen.getByRole('button', { name: /options/i }));+ await waitFor(() => expect(screen.getByRole('checkbox', { name: /unlock everything this series owns/i })).toBeChecked());+ fireEvent.click(screen.getByRole('button', { name: /run autopilot/i }));+ await waitFor(() => expect(startPipelineAutopilot).toHaveBeenCalledWith(+ 's1', { includeVisual: true, fileGaps: false }, { silent: true },+ ));+ });++ it('reports what the unlock pass cleared and what it left frozen', async () => {+ sseFrames = [{ type: 'unlock:applied', unlockedAny: true, arc: 1, arcFields: 0, seasons: 2, stages: 3, canon: 4, canonForeignKept: 5 }];+ sseLatest = sseFrames[0];+ getPipelineAutopilotStatus.mockResolvedValue({ autopilot: { runId: 'r1', status: 'running' }, active: true });+ renderPanel({ id: 's1', targetFormat: 'comic' });+ await waitFor(() => expect(+ screen.getAllByText(/Unlocked arc, 2 volume\(s\), 3 stage\(s\), 4 canon entries · kept 5 other series' canon locked/).length,+ ).toBeGreaterThan(0));+ });+it('sends a chosen readiness gate as a per-run override without persisting it (#1580)', async () => {renderPanel({ id: 's1', targetFormat: 'comic' });await waitFor(() => expect(getPipelineAutopilotStatus).toHaveBeenCalled());diff --git a/server/lib/pipelineValidation.js b/server/lib/pipelineValidation.jsindex 192fb844ad..8c47bc9513 100644--- a/server/lib/pipelineValidation.js+++ b/server/lib/pipelineValidation.js@@ -255,6 +255,15 @@ export const pipelineEditorialChecksSettingsSchema = z.object({revisionMinCycles: z.number().int().min(1).max(MAX_CONVERGENCE_ROUNDS).optional(),revisionMaxCycles: z.number().int().min(1).max(MAX_CONVERGENCE_ROUNDS).optional(),revisionPlateauDelta: z.number().min(0).max(10).optional(),+ // Unlock-everything pre-pass. When on, an autopilot run first clears every+ // lock the SERIES owns (arc freeze + per-field arc locks, volume locks, issue+ // stage locks, and the universe-canon entries this series owns) so the run can+ // actually apply the fixes its editorial passes surface. Canon owned by — or+ // shared with — another series in the same universe stays locked, and the pass+ // is never destructive: it clears lock bits only. Defaults OFF (opt-in) since+ // it mutates lock state the user set by hand. Optional + additive so older+ // peers fall through to off.+ unlockForRun: z.boolean().optional(),}).strict();// Cursor-context payload for the CD-bridge suggest route — identical shape todiff --git a/server/lib/validation.test.js b/server/lib/validation.test.jsindex 65d79dd60d..1e33502928 100644--- a/server/lib/validation.test.js+++ b/server/lib/validation.test.js@@ -1744,6 +1744,14 @@ describe('validation.js', () => {expect(pipelineEditorialChecksSettingsSchema.safeParse({ checkFindingsPauseThreshold: 2.5 }).success).toBe(false);});+ it('accepts an optional boolean unlockForRun and rejects a non-boolean', () => {+ expect(pipelineEditorialChecksSettingsSchema.safeParse({ unlockForRun: true }).success).toBe(true);+ expect(pipelineEditorialChecksSettingsSchema.safeParse({ unlockForRun: false }).success).toBe(true);+ // additive + optional: an older peer that never set it still validates+ expect(pipelineEditorialChecksSettingsSchema.safeParse({}).success).toBe(true);+ expect(pipelineEditorialChecksSettingsSchema.safeParse({ unlockForRun: 'yes' }).success).toBe(false);+ });+it('the settings slice accepts forward/older-peer custom-check shapes (lenient)', () => {// A def carrying a future field (or a not-yet-known scope) must not 400 an// unrelated settings save — runtime buildCustomCheck decides runnability.diff --git a/server/routes/pipeline/autopilot.js b/server/routes/pipeline/autopilot.jsindex 10799dd2fb..040af3e26e 100644--- a/server/routes/pipeline/autopilot.js+++ b/server/routes/pipeline/autopilot.js@@ -94,6 +94,15 @@ const autopilotStartSchema = z.object({// comic issue is drafted the run mints + starts a Creative Director teaser video// per issue. Falls back to pipelineEditorialChecks.produceTeaser, then off.produceTeaser: z.boolean().optional(),+ // Unlock-everything pre-pass. When true, the run's first step clears every+ // lock this SERIES owns — the arc freeze + per-field arc locks, each volume's+ // lock, every issue stage lock, and the universe-canon entries this series+ // owns — so the autopilot can apply the fixes its editorial passes surface+ // instead of pausing on findings it isn't allowed to resolve. Canon owned by+ // (or shared with) another series in the same universe stays locked, and the+ // pass never deletes anything. Falls back to+ // pipelineEditorialChecks.unlockForRun, then off.+ unlockForRun: z.boolean().optional(),// Iterate-to-quality revision loop (CWQE Phase 7, #2171). When true, after the// editorial-health gate the run cycles the weakest drafted issue through// adversarial cuts + a judge-gated keep/revert, stopping on plateau /diff --git a/server/services/pipeline/arcPlanner.js b/server/services/pipeline/arcPlanner.jsindex f82d30858c..3f68659d6f 100644--- a/server/services/pipeline/arcPlanner.js+++ b/server/services/pipeline/arcPlanner.js@@ -35,7 +35,7 @@ export * from './arcPlanner/coverConcepts.js';// the split). Pulled back together here from their new home modules so the// existing `__testing` import contract is preserved.import { buildArcOverviewContext, shapeSeasonOutlines, buildVerifyContext, buildResolveContext, shapeVerifyIssues, shapeFindings, renderVolumeIssue, buildNeighborVolumes, buildBeatContinuityContext, shapeBeatResolutions } from './arcPlanner/context.js';-import { buildVolumeVerifyContext, mergeArcWithLocks, mergeSeasonsWithLocks } from './arcPlanner/arcCore.js';+import { buildVolumeVerifyContext, mergeArcWithLocks, mergeSeasonsWithLocks, preserveDroppedSeasonRecords } from './arcPlanner/arcCore.js';import { applyBeatResolutions } from './arcPlanner/beatContinuity.js';import { buildSeasonEpisodesContext, shapeEpisodes } from './arcPlanner/episodeSeedPass.js';import { shapeCompletenessFindings, buildCompletenessContext } from './arcPlanner/completenessPass.js';@@ -58,6 +58,7 @@ export const __testing = {buildNeighborVolumes,mergeArcWithLocks,mergeSeasonsWithLocks,+ preserveDroppedSeasonRecords,buildBeatContinuityContext,shapeBeatResolutions,applyBeatResolutions,diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.jsindex 796e36834a..02dd887cf1 100644--- a/server/services/pipeline/arcPlanner.test.js+++ b/server/services/pipeline/arcPlanner.test.js@@ -1247,6 +1247,71 @@ describe('arcPlanner — commitSeasonsWithRemap (season locks)', () => {});});+// Non-destructive guarantee behind the autopilot's unlock-for-run mode: once+// that pass clears the per-season locks, nothing else stops an LLM-proposed arc+// from deleting a volume — so the commit re-inserts dropped records while still+// applying content rewrites to the ones that survived.+describe('arcPlanner — preserveDroppedSeasonRecords', () => {+ const { preserveDroppedSeasonRecords } = planner.__testing;++ it('re-appends a dropped season without freezing the ones that survived', () => {+ const current = [{ id: 'sea-a', number: 1, title: 'Drop me' }, { id: 'sea-b', number: 2, title: 'Old' }];+ const next = [{ id: 'sea-b', number: 2, title: 'Rewritten' }];+ const merged = preserveDroppedSeasonRecords(current, next);+ expect(merged).toHaveLength(2);+ expect(merged.find((s) => s.id === 'sea-b').title).toBe('Rewritten');+ expect(merged.find((s) => s.id === 'sea-a')).toBe(current[0]);+ });++ it('returns next untouched when nothing was dropped', () => {+ const current = [{ id: 'sea-a', number: 1 }];+ const next = [{ id: 'sea-a', number: 1, title: 'x' }];+ expect(preserveDroppedSeasonRecords(current, next)).toBe(next);+ });++ it('is a no-op for a missing/empty current list or a non-array next', () => {+ const next = [{ id: 'a' }];+ expect(preserveDroppedSeasonRecords([], next)).toBe(next);+ expect(preserveDroppedSeasonRecords(null, next)).toBe(next);+ expect(preserveDroppedSeasonRecords([{ id: 'a' }], null)).toBeNull();+ });+});++describe('arcPlanner — commitSeasonsWithRemap (preserveDroppedSeasons)', () => {+ beforeEach(() => {+ fileStore.clear();+ uuidCounter = 0;+ stageRunnerSpy = undefined;+ });++ it('keeps an UNLOCKED season the rewrite dropped, and still applies rewrites to survivors', async () => {+ const s = await setupSeries();+ const dropped = await seasonsSvc.createSeason(s.id, { title: 'Would vanish', episodeCountTarget: 3, number: 1 });+ const kept = await seasonsSvc.createSeason(s.id, { title: 'Old title', episodeCountTarget: 3, number: 2 });+ const i1 = await issuesSvc.createIssue({ seriesId: s.id, seasonId: dropped.id, title: 'Pilot' });+ const cur = await seriesSvc.getSeries(s.id);+ const out = await planner.commitSeasonsWithRemap(cur, {+ arc: { logline: 'L', summary: '', themes: [], protagonistArc: '', shape: null, status: 'draft' },+ seasons: [{ id: kept.id, number: 2, title: 'New title', logline: '', synopsis: '', endingHook: '', episodeCountTarget: 4, themes: [] }],+ }, { preserveDroppedSeasons: true });+ expect(out.series.seasons.map((x) => x.id)).toContain(dropped.id);+ expect(out.series.seasons.find((x) => x.id === kept.id).title).toBe('New title');+ // The dropped volume's issue stays attached — nothing was reassigned away.+ expect(await issuesSvc.getIssue(i1.id).then((i) => i.seasonId)).toBe(dropped.id);+ });++ it('still drops an unlocked season when the flag is off (default behavior unchanged)', async () => {+ const s = await setupSeries();+ const dropped = await seasonsSvc.createSeason(s.id, { title: 'Would vanish', episodeCountTarget: 3, number: 1 });+ const cur = await seriesSvc.getSeries(s.id);+ const out = await planner.commitSeasonsWithRemap(cur, {+ arc: { logline: 'L', summary: '', themes: [], protagonistArc: '', shape: null, status: 'draft' },+ seasons: [],+ });+ expect(out.series.seasons.map((x) => x.id)).not.toContain(dropped.id);+ });+});+describe('arcPlanner — mergeArcWithLocks', () => {it('replaces locked fields with the current arc values', () => {const current = { logline: 'a', summary: 'b', themes: ['t1'], protagonistArc: 'c', shape: 's1' };diff --git a/server/services/pipeline/arcPlanner/arcCore.js b/server/services/pipeline/arcPlanner/arcCore.jsindex 8f3b3de129..e9777fbdef 100644--- a/server/services/pipeline/arcPlanner/arcCore.js+++ b/server/services/pipeline/arcPlanner/arcCore.js@@ -444,7 +444,14 @@ export async function resolveVerifyIssues(seriesId, options = {}) {const seasons = sanitizeSeasonList(seasonEntries.map((e) => e.season));- const { series: updated } = await commitSeasonsWithRemap(series, { arc, seasons });+ // `preserveDroppedSeasons` (autopilot unlock-for-run) rides through so an+ // auto-resolve can rewrite a volume but never delete one — see the option's+ // contract on commitSeasonsWithRemap.+ const { series: updated } = await commitSeasonsWithRemap(+ series,+ { arc, seasons },+ { preserveDroppedSeasons: options.preserveDroppedSeasons === true },+ );// Apply any episode-level synopsis corrections the resolver returned. This is// the heal capability that lets episode-scoped findings converge: when a@@ -576,6 +583,24 @@ export function mergeSeasonsWithLocks(currentSeasons, nextSeasons) {return merged;}+// Re-insert every EXISTING season the rewrite dropped, without freezing the+// ones it kept. Distinct from `mergeSeasonsWithLocks`: that one restores a+// locked season's CONTENT verbatim (the user froze it); this one only+// guarantees the record survives, so a same-id rewrite still applies in full.+//+// Used by the autopilot's `unlockForRun` mode — once that pass clears the+// per-season locks, nothing else stops an LLM-proposed arc from silently+// deleting a volume, and unlocking for EDITING must not become a licence to+// DELETE (see seriesAutopilot/unlockPass.js). Appended dropped seasons are+// re-sorted by `number` in `sanitizeSeasonList` at the call site.+export function preserveDroppedSeasonRecords(currentSeasons, nextSeasons) {+ if (!Array.isArray(nextSeasons)) return nextSeasons;+ if (!Array.isArray(currentSeasons) || currentSeasons.length === 0) return nextSeasons;+ const keptIds = new Set(nextSeasons.map((s) => s?.id).filter(Boolean));+ const dropped = currentSeasons.filter((s) => s?.id && !keptIds.has(s.id));+ return dropped.length === 0 ? nextSeasons : [...nextSeasons, ...dropped];+}+/*** Persist a new `arc` + `seasons[]` onto a series, migrating any child issues* whose `seasonId` referenced a season that the new shape dropped or renamed.@@ -594,8 +619,14 @@ export function mergeSeasonsWithLocks(currentSeasons, nextSeasons) {* `currentSeries` identifies the target series. The helper refreshes the* latest snapshot before writing so locks toggled while an LLM run is in* flight are honored at commit time.+ *+ * `options.preserveDroppedSeasons` additionally re-inserts any existing season+ * the new shape omitted, whether or not it was locked — the non-destructive+ * guarantee the autopilot's `unlockForRun` mode relies on (it clears the very+ * per-season locks that would otherwise have preserved them). Content rewrites+ * to surviving seasons still apply; only deletion is refused.*/-export async function commitSeasonsWithRemap(currentSeries, { arc, seasons }) {+export async function commitSeasonsWithRemap(currentSeries, { arc, seasons }, options = {}) {const seriesId = currentSeries.id;const latestSeries = await getSeries(seriesId);if (latestSeries.locked?.arc === true) {@@ -608,8 +639,11 @@ export async function commitSeasonsWithRemap(currentSeries, { arc, seasons }) {// Per-season locks: restore any locked existing seasons over LLM-proposed// rewrites, and re-insert any locked seasons the LLM dropped. Re-sanitize// so the locked records merge with the new shape (sort by number, dedup).+ const lockMerged = mergeSeasonsWithLocks(latestSeries.seasons, seasons);const mergedSeasons = sanitizeSeasonList(- mergeSeasonsWithLocks(latestSeries.seasons, seasons),+ options.preserveDroppedSeasons === true+ ? preserveDroppedSeasonRecords(latestSeries.seasons, lockMerged)+ : lockMerged,);const newIds = new Set(mergedSeasons.map((s) => s.id));const droppedOldSeasons = (latestSeries.seasons || []).filter((s) => !newIds.has(s.id));diff --git a/server/services/pipeline/seriesAutopilot.js b/server/services/pipeline/seriesAutopilot.jsindex 893e4c5c98..995c78878f 100644--- a/server/services/pipeline/seriesAutopilot.js+++ b/server/services/pipeline/seriesAutopilot.js@@ -81,6 +81,7 @@ export * from './seriesAutopilot/childRuns.js';export * from './seriesAutopilot/editorialSteps.js';export * from './seriesAutopilot/visualSteps.js';export * from './seriesAutopilot/revisionSteps.js';+export * from './seriesAutopilot/unlockPass.js';export * from './seriesAutopilot/dispatch.js';export * from './seriesAutopilot/dryRun.js';export * from './seriesAutopilot/orchestrator.js';diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.jsindex 9dc57867bd..ba1360c855 100644--- a/server/services/pipeline/seriesAutopilot.test.js+++ b/server/services/pipeline/seriesAutopilot.test.js@@ -761,6 +761,37 @@ describe('resolveAutopilotProduceTeaser (config gate, #2185)', () => {});});+describe('resolveAutopilotUnlockForRun (config gate)', () => {+ it('defaults OFF — it mutates lock state the user set by hand', () => {+ expect(autopilot.resolveAutopilotUnlockForRun({}, null)).toBe(false);+ });+ it('per-run option wins over the persisted setting', () => {+ expect(autopilot.resolveAutopilotUnlockForRun({ unlockForRun: true }, { pipelineEditorialChecks: { unlockForRun: false } })).toBe(true);+ expect(autopilot.resolveAutopilotUnlockForRun({ unlockForRun: false }, { pipelineEditorialChecks: { unlockForRun: true } })).toBe(false);+ });+ it('falls back to the persisted setting when no per-run option', () => {+ expect(autopilot.resolveAutopilotUnlockForRun({}, { pipelineEditorialChecks: { unlockForRun: true } })).toBe(true);+ });+});++describe('resolveNextStep — unlock pre-pass ordering', () => {+ // A locked arc makes generateArc/resolveVerifyIssues throw and a locked stage+ // makes text generation skip, so the unlock MUST precede every generation step+ // — pin that it sorts ahead of even the very first one.+ const bare = { targetFormat: 'comic', arc: null, seasons: [] };++ it('runs before generateArc when enabled', () => {+ expect(resolveNextStep(bare, [], {}, { unlockForRun: true }).kind).toBe('unlockLocks');+ });+ it('is skipped entirely when not enabled', () => {+ expect(resolveNextStep(bare, [], {}, {}).kind).toBe('generateArc');+ expect(resolveNextStep(bare, [], {}, { unlockForRun: false }).kind).toBe('generateArc');+ });+ it('runs at most once per run (latched by runState.locksUnlocked)', () => {+ expect(resolveNextStep(bare, [], { locksUnlocked: true }, { unlockForRun: true }).kind).toBe('generateArc');+ });+});+// CWQE Phase 7 (#2171) — iterate-to-quality revision loop.describe('resolveAutopilotRevision (config gate, #2171)', () => {const {@@ -930,6 +961,7 @@ describe('dry-run plan ↔ resolveNextStep drift guard (#1577)', () => {// parity is covered separately by the dedicated cases above.const freshRunState = () => ({+ locksUnlocked: false,arcAttempted: false, arcVerified: false, foundationGated: false, beatContinuityChecked: false,editorialReviewed: false, reverseOutlineRefreshed: false,editorialChecksReviewed: false, editorialHealthReady: false, canonVerified: false,@@ -944,6 +976,9 @@ describe('dry-run plan ↔ resolveNextStep drift guard (#1577)', () => {// rendered pages) so the resolver actually advances past them.const completeStep = (step, issues, runState, edRounds) => {switch (step.kind) {+ case 'unlockLocks':+ runState.locksUnlocked = true;+ break;case 'generateArc':case 'generateEpisodes':// These steps CREATE downstream work (seasons / issues) that buildDryRunPlan@@ -1071,6 +1106,7 @@ describe('dry-run plan ↔ resolveNextStep drift guard (#1577)', () => {{ name: 'comic, editorial rounds 0 (skips editorial gate)', series: baseComic(), issues: bareIssue(), options: { maxEditorialRounds: 0 } },{ name: 'tv (no comic script / canon / visual)', series: baseTv(), issues: bareIssue(), options: {} },{ name: 'comic + visual, 2 seasons × 1 issue (per-step multiplicity)', series: twoSeasonComic(), issues: twoIssues(), options: {} },+ { name: 'comic + unlock-for-run pre-pass', series: baseComic(), issues: bareIssue(), options: { unlockForRun: true } },];for (const c of cases) {diff --git a/server/services/pipeline/seriesAutopilot/childRuns.js b/server/services/pipeline/seriesAutopilot/childRuns.jsindex 43abed0060..99dc54c631 100644--- a/server/services/pipeline/seriesAutopilot/childRuns.js+++ b/server/services/pipeline/seriesAutopilot/childRuns.js@@ -69,7 +69,14 @@ export async function runArcVerify(seriesId, record) {// step can't overspend the daily cap mid-loop.const beforeResolve = await budgetPause();if (beforeResolve) return beforeResolve;- const resolved = await resolveVerifyIssues(seriesId, { findings: blocking, ...providerOverrideOpts(record) });+ const resolved = await resolveVerifyIssues(seriesId, {+ findings: blocking,+ ...providerOverrideOpts(record),+ // Unlock-for-run cleared the per-season locks that used to stop an+ // auto-resolve from dropping a volume — keep the records regardless, so+ // "unlocked for editing" never means "deletable" (see unlockPass.js).+ preserveDroppedSeasons: record.options.unlockForRun === true,+ });await recordDomainUsage('cos', { actions: 1 });broadcast(seriesId, {type: 'resolve:round', scope: 'arc', round,diff --git a/server/services/pipeline/seriesAutopilot/config.js b/server/services/pipeline/seriesAutopilot/config.jsindex f5cd291de4..222bfb9edb 100644--- a/server/services/pipeline/seriesAutopilot/config.js+++ b/server/services/pipeline/seriesAutopilot/config.js@@ -145,6 +145,23 @@ export function wantsTeaser(options = {}) {return options.produceTeaser === true && wantsVisual(options);}+// Unlock-everything-first (see ./unlockPass.js). When on, the run's FIRST step+// clears every lock this series owns — the arc freeze + per-field arc locks,+// each volume's lock, every issue stage lock, and the universe-canon entries+// this series owns — so the autopilot can actually apply the fixes the+// editorial passes surface instead of pausing on findings it isn't allowed to+// resolve. Defaults OFF: it mutates persisted lock state the user set by hand,+// so it must be an explicit choice. Per-run option wins, then the persisted+// setting, then false. Stamped onto run options once at start so the resolver,+// the dry-run plan and a later resume all read the same effective flag.+export const DEFAULT_UNLOCK_FOR_RUN = false;+export function resolveAutopilotUnlockForRun(options = {}, settings = null) {+ if (typeof options?.unlockForRun === 'boolean') return options.unlockForRun;+ const pec = settings?.pipelineEditorialChecks || {};+ if (typeof pec?.unlockForRun === 'boolean') return pec.unlockForRun;+ return DEFAULT_UNLOCK_FOR_RUN;+}+// Iterate-to-quality revision loop (CWQE Phase 7, #2171). Opt-in per run; when// enabled the autopilot cycles the weakest issue through adversarial cuts +// judge-gated keep/revert instead of stopping at the editorial-health gate.diff --git a/server/services/pipeline/seriesAutopilot/dispatch.js b/server/services/pipeline/seriesAutopilot/dispatch.jsindex 6b011ddee5..3af2edcee0 100644--- a/server/services/pipeline/seriesAutopilot/dispatch.js+++ b/server/services/pipeline/seriesAutopilot/dispatch.js@@ -11,15 +11,28 @@ import { runArcVerify, runBeats, runBeatContinuity, runFoundationGate, runText }import { runScriptVerify, runEditorial, runReverseOutlineRefresh, runEditorialChecksPass, runEditorialHealthGate } from './editorialSteps.js';import { runCanonVerify, runVisualDraft, runProduceTeaser } from './visualSteps.js';import { runRevisionCycle } from './revisionSteps.js';+import { runUnlockPass } from './unlockPass.js';++// Once the unlock pass has cleared the per-season locks, those locks can no+// longer stop an LLM-proposed arc from DROPPING a volume — and "unlock so the+// autopilot can edit" must never become "unlock so the autopilot can delete"+// (see the unlockPass module header). `preserveDroppedSeasons` re-inserts any+// existing season the rewrite omitted while still letting same-id rewrites+// through, so content is fully editable and the record itself survives.+const seasonPreserveOpts = (record) => ({+ preserveDroppedSeasons: record.options.unlockForRun === true,+});export async function dispatchStep(sId, step, record) {switch (step.kind) {+ case 'unlockLocks':+ return runUnlockPass(sId, record);case 'generateArc': {// Mark attempted up front so the resolver won't re-route here if arc// generation yields no seasons (avoids an infinite generateArc loop).record.runState.arcAttempted = true;const r = await generateArcOverview(sId, providerOverrideOpts(record));- const committed = await commitSeasonsWithRemap(await getSeries(sId), { arc: r.arc, seasons: r.seasons });+ const committed = await commitSeasonsWithRemap(await getSeries(sId), { arc: r.arc, seasons: r.seasons }, seasonPreserveOpts(record));await recordDomainUsage('cos', { actions: 1 });const seasonCount = committed?.series?.seasons?.length ?? (await getSeries(sId)).seasons?.length ?? 0;if (seasonCount === 0) {diff --git a/server/services/pipeline/seriesAutopilot/dryRun.js b/server/services/pipeline/seriesAutopilot/dryRun.jsindex 1fc4dc0b4a..8b61c79a81 100644--- a/server/services/pipeline/seriesAutopilot/dryRun.js+++ b/server/services/pipeline/seriesAutopilot/dryRun.js@@ -28,12 +28,39 @@ import { editorialSubsetIds } from './editorialSteps.js';// When provided it drives the editorialChecks step's estLlmCalls (issues × LLM// checks) and whether that pass bills a cos action at all; absent, the step// estimates a single LLM check.+// How many locks the unlock pre-pass would clear on the SERIES records — the+// arc freeze, each locked arc field, each locked volume, each locked issue+// stage. Universe-canon locks are deliberately excluded: they live on another+// record that only an async read could reach, and buildDryRunPlan is pure ++// synchronous. The plan note says so rather than implying this is the total.+export function countSeriesRecordLocks(series, issues) {+ const locked = series?.locked || {};+ let n = locked.arc === true ? 1 : 0;+ n += Object.values(locked.arcFields || {}).filter((v) => v === true).length;+ n += (Array.isArray(series?.seasons) ? series.seasons : []).filter((s) => s?.locked === true).length;+ for (const issue of Array.isArray(issues) ? issues : []) {+ n += Object.values(issue?.stages || {}).filter((st) => st?.locked === true).length;+ }+ return n;+}+export function buildDryRunPlan(series, issues, options, costContext = {}) {const plan = [];const ordered = orderedIssues(issues);const seasons = Array.isArray(series?.seasons) ? [...series.seasons].sort(byNumber) : [];// Mirror the resolver: generateArc runs when arc text is missing OR there are// no volumes at all (an arc-only series), so a dry-run plan must show it too.+ // Unlock pre-pass (opt-in). Costs nothing — it only clears lock bits — but it+ // is the one step that MUTATES records the user froze by hand, so the dry-run+ // plan must name it (and how many locks it would clear) before they commit.+ if (options?.unlockForRun === true) {+ plan.push({+ kind: 'unlockLocks',+ count: 1,+ note: `unlock ${countSeriesRecordLocks(series, ordered)} series-record lock(s) + this series' universe canon — other series' canon stays locked; nothing is deleted`,+ estActions: 0,+ });+ }const noArc = !series?.arc?.logline && !series?.arc?.summary;if (noArc || seasons.length === 0) plan.push({ kind: 'generateArc', count: 1, estActions: 1 });const emptySeasons = seasons.filter((s) => !ordered.some((i) => i.seasonId === s.id));diff --git a/server/services/pipeline/seriesAutopilot/orchestrator.js b/server/services/pipeline/seriesAutopilot/orchestrator.jsindex 0aabd96643..2268cb6745 100644--- a/server/services/pipeline/seriesAutopilot/orchestrator.js+++ b/server/services/pipeline/seriesAutopilot/orchestrator.js@@ -18,6 +18,7 @@ import {resolveAutopilotRounds, resolveAutopilotFoundationGate, resolveAutopilotFoundationThreshold,resolveAutopilotReadinessGate, resolveAutopilotCheckPauseThreshold, resolveAutopilotNotifyOnPause,resolveAutopilotProduceTeaser, resolveAutopilotRevision, resolveAutopilotLlm,+ resolveAutopilotUnlockForRun,} from './config.js';import { VISUAL_DRAFT_ENABLED, summarizePlanCost } from './convergence.js';import { broadcast, broadcastStart, persistMarker, clearPauseNotice, notifyPause, fileGap, scheduleCleanup } from './session.js';@@ -69,6 +70,7 @@ export async function startSeriesAutopilot(sId, options = {}) {checkFindingsPauseThreshold: resolveAutopilotCheckPauseThreshold(options, settings),notifyOnPause: resolveAutopilotNotifyOnPause(options, settings),produceTeaser: resolveAutopilotProduceTeaser(options, settings),+ unlockForRun: resolveAutopilotUnlockForRun(options, settings),...resolveAutopilotRevision(options, settings),// Run provider/model: per-run override → the series' own `series.llm` →// unset (stage pin / active provider downstream). Resolved ONCE here so the@@ -102,6 +104,10 @@ export async function startSeriesAutopilot(sId, options = {}) {mode,options: runOptions,runState: {+ // Unlock-everything pre-pass (opt-in, see unlockPass.js) has run this+ // run. Boolean latch like arcVerified so the resolver routes there at+ // most once, and a resume re-runs it (idempotent) against fresh state.+ locksUnlocked: false,arcAttempted: false,arcVerified: false,// #2176 — foundation-quality gate satisfied this run (threshold cleared,@@ -241,9 +247,14 @@ export async function startSeriesAutopilot(sId, options = {}) {|| (step.kind === 'beatContinuity' && runOptions.maxBeatContinuityRounds === 0)|| (step.kind === 'editorialReview' && runOptions.maxEditorialRounds === 0)|| (step.kind === 'foundationGate' && (runOptions.maxFoundationRounds === 0 || runOptions.foundationGate === false));+ // `unlockLocks` is exempt for a simpler reason than the self-gating+ // steps: it makes no LLM call and bills nothing (it only clears lock+ // bits), so pausing it on an exhausted budget would strand the run+ // before its first real step for no spend at all.const selfGatingStep = step.kind === 'editorialChecks'|| step.kind === 'editorialHealthGate'- || step.kind === 'reverseOutline';+ || step.kind === 'reverseOutline'+ || step.kind === 'unlockLocks';if (!selfGatingStep && !zeroRoundSkip) {const budget = await getDomainBudgetStatus('cos');if (!budget.withinBudget) {diff --git a/server/services/pipeline/seriesAutopilot/stepResolver.js b/server/services/pipeline/seriesAutopilot/stepResolver.jsindex 9576d0d73d..b32835666f 100644--- a/server/services/pipeline/seriesAutopilot/stepResolver.js+++ b/server/services/pipeline/seriesAutopilot/stepResolver.js@@ -144,6 +144,16 @@ export function resolveNextStep(series, issues, runState = {}, options = {}) {const seasons = Array.isArray(series?.seasons) ? [...series.seasons].sort(byNumber) : [];const ordered = orderedIssues(issues);+ // STEP 0 — unlock everything this series owns (opt-in, see unlockPass.js).+ // Must run BEFORE any generation step: a locked arc makes generateArc /+ // resolveVerifyIssues throw, a locked stage makes text generation skip, and a+ // locked canon entry makes the describe/refine fixes no-op — so unlocking+ // after the fact would leave the run pausing on findings it could have fixed.+ // Latched by `runState.locksUnlocked` so it runs at most once per run.+ if (options.unlockForRun === true && !runState.locksUnlocked) {+ return { kind: 'unlockLocks', reason: 'unlock series-owned records before the run' };+ }+// STEP 1 — arc. Also (re)generate when there are no seasons at all: an// arc-only series (arc text present, seasons: []) has nothing for the// episode/issue steps to expand, and would otherwise sail through verify/diff --git a/server/services/pipeline/seriesAutopilot/unlockPass.js b/server/services/pipeline/seriesAutopilot/unlockPass.jsnew file mode 100644index 0000000000..97b682235b--- /dev/null+++ b/server/services/pipeline/seriesAutopilot/unlockPass.js@@ -0,0 +1,207 @@+/**+ * Series Autopilot — "unlock everything this series owns" pre-pass.+ *+ * Opt-in via the `unlockForRun` run option. A user who wants the autopilot to+ * act on the editorial findings END-TO-END (rewrite the arc, re-cut volumes,+ * re-describe a character the checks flagged as thin) otherwise has to hunt+ * down every lock toggle by hand first — a locked arc/season/stage/canon entry+ * makes the corresponding fix path throw or silently skip, and the run pauses+ * on findings it was never allowed to resolve. This pass clears those locks+ * once, at the top of the run.+ *+ * TWO HARD BOUNDARIES — both are the point of the feature, not incidental:+ *+ * 1. SERIES SCOPE. Universe canon (characters / places / objects) is shared+ * across every series linked to that universe, so a blanket unlock would+ * hand the autopilot edit rights over another series' cast. An entry is+ * unlocked only when it is provably THIS series' to edit:+ * - `sourceSeriesId === seriesId` → this series minted it. Unlock.+ * - `sourceSeriesId` names another series → foreign. Stays locked.+ * - no `sourceSeriesId` at all → unlock ONLY when this series is the sole+ * series linked to the universe (nothing else can be affected).+ * Everything else the pass touches (arc, arc fields, seasons, issue stages)+ * is wholly series-owned, so it unlocks unconditionally.+ *+ * 2. NEVER DESTRUCTIVE. The pass only clears `locked` bits — it never removes a+ * canon entry, a season, an issue or a catalog ingredient. Unlocking is what+ * lets the autopilot FULLY EDIT a character or object in the story; the+ * entry itself stays in the Universe (and its projected Catalog ingredient+ * stays in the Catalog) regardless. If a record ever needs to leave, that is+ * a catalog ARCHIVE (soft-delete/tombstone), performed by a human — the+ * autopilot has no canon/catalog deletion path and must not grow one here.+ * Season records get the same treatment: see `preserveDroppedSeasons` in+ * `arcPlanner/arcCore.js#commitSeasonsWithRemap`, which the autopilot sets+ * on its arc-rewriting calls whenever this pass has run, so a regenerated+ * arc can rewrite a volume's content but can never make the volume vanish+ * (the per-season lock used to be the only thing preventing that).+ *+ * Locks are NOT restored when the run ends. The user opted into an unlocked+ * series; silently re-freezing records the autopilot just rewrote would leave+ * the lock state lying about what is user-frozen. The pass reports exactly what+ * it changed (SSE frame + run marker) so re-locking is an informed choice.+ */++import { BIBLE_KEYS } from '../../../lib/storyBible.js';+import { getUniverse, updateUniverse } from '../../universeBuilder.js';+import { getSeries, updateSeries, listSeries } from '../series.js';+import { listIssues, updateStagesWithLatest, STAGE_IDS } from '../issues.js';+import { broadcast } from './session.js';++/**+ * PURE: is this universe-canon entry this series' to unlock?+ *+ * `soleSeries` is true when `seriesId` is the ONLY series linked to the+ * universe — the case where an unowned (legacy / universe-authored) entry has+ * no other series association to damage.+ */+export function isSeriesScopedCanonEntry(entry, { seriesId, soleSeries = false } = {}) {+ if (!entry || typeof entry !== 'object') return false;+ const owner = typeof entry.sourceSeriesId === 'string' ? entry.sourceSeriesId : '';+ if (owner) return owner === seriesId;+ return soleSeries === true;+}++/**+ * PURE: split a canon list into the locked entries this series may unlock and+ * the locked entries that must stay frozen (owned by, or shared with, another+ * series). Unlocked entries are ignored by both buckets — nothing to do.+ */+export function partitionLockedCanon(list, scope) {+ const unlockable = [];+ const foreign = [];+ for (const entry of Array.isArray(list) ? list : []) {+ if (entry?.locked !== true) continue;+ if (isSeriesScopedCanonEntry(entry, scope)) unlockable.push(entry);+ else foreign.push(entry);+ }+ return { unlockable, foreign };+}++// Clear `series.locked` (the binary arc freeze + every per-field arc lock).+// `locked: {}` is a wholesale replace in updateSeries, so this drops both.+async function unlockSeriesArc(seriesId, series) {+ const locked = series.locked || {};+ const arcLocked = locked.arc === true ? 1 : 0;+ const arcFieldsLocked = Object.keys(locked.arcFields || {}).length;+ if (arcLocked === 0 && arcFieldsLocked === 0) return { arc: 0, arcFields: 0 };+ await updateSeries(seriesId, { locked: {} });+ return { arc: arcLocked, arcFields: arcFieldsLocked };+}++// Clear every season's `locked`. Written as ONE series patch rather than N+// `updateSeason` calls: updateSeason refuses a content patch on a locked season+// and re-derives issue numbers per call, neither of which we want N times.+async function unlockSeasons(seriesId, series) {+ const seasons = Array.isArray(series.seasons) ? series.seasons : [];+ const lockedCount = seasons.filter((s) => s?.locked === true).length;+ if (lockedCount === 0) return 0;+ await updateSeries(seriesId, { seasons: seasons.map((s) => (s?.locked === true ? { ...s, locked: false } : s)) });+ return lockedCount;+}++// Clear `locked` on every stage of every issue in the series. Batched through+// updateStagesWithLatest so the whole sweep is a single serialized write.+async function unlockIssueStages(seriesId, issues) {+ const updates = [];+ for (const issue of issues) {+ for (const stageId of STAGE_IDS) {+ if (issue?.stages?.[stageId]?.locked !== true) continue;+ // computeFn re-reads the freshest stage inside the write queue — a stage+ // unlocked between our read and the write yields `{}` (a no-op).+ updates.push({+ issueId: issue.id,+ stageId,+ computeFn: (cur) => (cur?.locked === true ? { locked: false } : {}),+ });+ }+ }+ if (updates.length === 0) return 0;+ await updateStagesWithLatest(seriesId, updates);+ return updates.length;+}++// Clear `locked` on the series-scoped canon entries of the linked universe.+// Foreign entries (another series' cast, or shared entries in a multi-series+// universe) are counted and reported but left frozen — see boundary 1.+async function unlockSeriesCanon(seriesId, series) {+ if (!series.universeId) return { unlocked: 0, foreign: 0, universeId: null };+ const universe = await getUniverse(series.universeId).catch(() => null);+ if (!universe) return { unlocked: 0, foreign: 0, universeId: null };+ // "Sole series" decides whether an UNOWNED entry (no sourceSeriesId) is safe+ // to unlock. Deleted series don't count — listSeries already excludes them.+ const siblings = await listSeries().catch(() => []);+ const soleSeries = !siblings.some((s) => s.id !== seriesId && s.universeId === series.universeId);+ const scope = { seriesId, soleSeries };++ let unlocked = 0;+ let foreign = 0;+ // Mutator form so the patch is built from the freshest persisted canon inside+ // updateUniverse's write queue — a read-modify-write split would replace the+ // whole array from a stale read and clobber a concurrent render-completion+ // `imageRefs[]` append (the same reason setCanonKindLockAll uses it).+ await updateUniverse(series.universeId, (cur) => {+ unlocked = 0;+ foreign = 0;+ const patch = {};+ for (const key of BIBLE_KEYS) {+ const list = Array.isArray(cur[key]) ? cur[key] : null;+ if (!list) continue;+ const { unlockable, foreign: frozen } = partitionLockedCanon(list, scope);+ foreign += frozen.length;+ if (unlockable.length === 0) continue;+ const unlockIds = new Set(unlockable.map((e) => e.id));+ unlocked += unlockable.length;+ patch[key] = list.map((e) => (unlockIds.has(e.id) ? { ...e, locked: false } : e));+ }+ return Object.keys(patch).length > 0 ? patch : null;+ });+ return { unlocked, foreign, universeId: series.universeId };+}++/**+ * Run the unlock pass for a series. Returns the per-scope counts (also+ * broadcast as an `unlock:applied` SSE frame by the dispatch step). Idempotent+ * — a second run finds nothing locked and writes nothing.+ */+export async function unlockSeriesForAutopilot(seriesId) {+ const series = await getSeries(seriesId);+ const issues = await listIssues({ seriesId });+ const arcResult = await unlockSeriesArc(seriesId, series);+ // Re-read: unlockSeriesArc may have rewritten the record, and unlockSeasons+ // patches the whole `seasons` array (a stale copy would resurrect the locks+ // the arc patch just cleared alongside it).+ const seasons = await unlockSeasons(seriesId, await getSeries(seriesId));+ const stages = await unlockIssueStages(seriesId, issues);+ const canon = await unlockSeriesCanon(seriesId, series);+ return {+ arc: arcResult.arc,+ arcFields: arcResult.arcFields,+ seasons,+ stages,+ canon: canon.unlocked,+ canonForeignKept: canon.foreign,+ universeId: canon.universeId,+ };+}++/**+ * Autopilot step handler. Unlocks the series, marks the run state so the+ * resolver routes past this step, and reports what changed. Never pauses — an+ * unlock failure is not worth stopping a run over, but it IS surfaced as a note+ * so the user knows the locks are still in place.+ */+export async function runUnlockPass(seriesId, record) {+ record.runState.locksUnlocked = true;+ const counts = await unlockSeriesForAutopilot(seriesId).catch((err) => {+ broadcast(seriesId, { type: 'note', message: `Could not unlock series records: ${err.message} — locked records stay frozen for this run.` });+ console.log(`⚠️ autopilot: unlock pass failed for ${seriesId.slice(0, 12)}: ${err.message}`);+ return null;+ });+ if (!counts) return {};+ // `unlockedAny` drives the UI copy: a run on an already-unlocked series should+ // read as a no-op, not as "unlocked 0 things".+ const unlockedAny = counts.arc + counts.arcFields + counts.seasons + counts.stages + counts.canon > 0;+ broadcast(seriesId, { type: 'unlock:applied', ...counts, unlockedAny });+ console.log(`🔓 autopilot unlock — series=${seriesId.slice(0, 12)} arc=${counts.arc} arcFields=${counts.arcFields} seasons=${counts.seasons} stages=${counts.stages} canon=${counts.canon} foreignKept=${counts.canonForeignKept}`);+ return {};+}diff --git a/server/services/pipeline/seriesAutopilot/unlockPass.test.js b/server/services/pipeline/seriesAutopilot/unlockPass.test.jsnew file mode 100644index 0000000000..58baad9ce7--- /dev/null+++ b/server/services/pipeline/seriesAutopilot/unlockPass.test.js@@ -0,0 +1,220 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { readdirSync, readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, join } from 'node:path';+import { mockNoPeerSync, mockNoPeers } from '../../../lib/mockPathsDataRoot.js';++// File-backed store (same idiom as seriesAutopilot.test.js) so the REAL+// series/issues services run against an in-memory map, not Postgres. Partial+// mock — this suite loads `./session.js` transitively (for `broadcast`), which+// pulls in the cos/apps graph, and those modules read fileUtils members the+// autopilot itself never touches.+const fileStore = new Map();+vi.mock('../../../lib/fileUtils.js', async (importOriginal) => ({+ ...(await importOriginal()),+ tryReadFile: vi.fn().mockResolvedValue(null),+ ensureDir: vi.fn().mockResolvedValue(undefined),+ atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),+ readJSONFile: vi.fn(async (path, fallback) => (fileStore.has(path) ? fileStore.get(path) : fallback)),+}));++let uuidCounter = 0;+vi.mock('crypto', async () => {+ const actual = await vi.importActual('crypto');+ return { ...actual, randomUUID: () => `uuid-${++uuidCounter}` };+});++vi.mock('../../instances.js', () => mockNoPeers());+vi.mock('../../sharing/peerSync.js', () => mockNoPeerSync());++// Stand-in universe record the pass reads + writes through the mutator form.+let universe = null;+const getUniverse = vi.fn(async (id) => (universe?.id === id ? universe : null));+const updateUniverse = vi.fn(async (id, patchOrMutator) => {+ const patch = typeof patchOrMutator === 'function' ? await patchOrMutator(universe) : patchOrMutator;+ if (!patch) return universe;+ universe = { ...universe, ...patch };+ return universe;+});+// Partial mock — other modules in the transitive graph import constants off the+// real barrel; only the two functions this pass uses are replaced.+vi.mock('../../universeBuilder.js', async (importOriginal) => ({+ ...(await importOriginal()),+ getUniverse: (...a) => getUniverse(...a),+ updateUniverse: (...a) => updateUniverse(...a),+}));++const seriesSvc = await import('../series.js');+const issuesSvc = await import('../issues.js');+const { isSeriesScopedCanonEntry, partitionLockedCanon, unlockSeriesForAutopilot } = await import('./unlockPass.js');++const charEntry = (over = {}) => ({ id: 'c1', name: 'Kai', physicalDescription: 'Tall.', ...over });++beforeEach(() => {+ fileStore.clear();+ uuidCounter = 0;+ universe = null;+ getUniverse.mockClear();+ updateUniverse.mockClear();+});++describe('unlockPass — series-scoped canon predicate', () => {+ it('unlocks an entry this series minted', () => {+ expect(isSeriesScopedCanonEntry(charEntry({ sourceSeriesId: 's1' }), { seriesId: 's1' })).toBe(true);+ });++ it('refuses an entry another series minted, even when this series is the only one left linked', () => {+ expect(isSeriesScopedCanonEntry(charEntry({ sourceSeriesId: 's2' }), { seriesId: 's1', soleSeries: true })).toBe(false);+ });++ it('unlocks an unowned entry ONLY when this series is the universe\'s only series', () => {+ const unowned = charEntry();+ expect(isSeriesScopedCanonEntry(unowned, { seriesId: 's1', soleSeries: true })).toBe(true);+ expect(isSeriesScopedCanonEntry(unowned, { seriesId: 's1', soleSeries: false })).toBe(false);+ });++ it('partitions only LOCKED entries — unlocked ones are neither unlockable nor foreign', () => {+ const { unlockable, foreign } = partitionLockedCanon([+ charEntry({ id: 'a', locked: true, sourceSeriesId: 's1' }),+ charEntry({ id: 'b', locked: true, sourceSeriesId: 's2' }),+ charEntry({ id: 'c', locked: false, sourceSeriesId: 's1' }),+ charEntry({ id: 'd', sourceSeriesId: 's1' }),+ ], { seriesId: 's1' });+ expect(unlockable.map((e) => e.id)).toEqual(['a']);+ expect(foreign.map((e) => e.id)).toEqual(['b']);+ });+});++describe('unlockPass — end-to-end over the real series/issue services', () => {+ const buildSeries = async ({ universeId = null } = {}) => {+ const s = await seriesSvc.createSeries({ name: 'Test Series', targetFormat: 'comic' });+ if (universeId) await seriesSvc.updateSeries(s.id, { universeId });+ return seriesSvc.getSeries(s.id);+ };++ it('clears the arc freeze, every arc-field lock, every volume lock and every stage lock', async () => {+ const s = await buildSeries();+ const seasons = [+ { id: 'sea-a', number: 1, title: 'One', locked: true },+ { id: 'sea-b', number: 2, title: 'Two', locked: false },+ ];+ await seriesSvc.updateSeries(s.id, {+ seasons,+ arc: { logline: 'L', summary: 'S' },+ locked: { arc: true, arcFields: { logline: true, themes: true } },+ });+ const issue = await issuesSvc.createIssue({ seriesId: s.id, title: 'I1' });+ await issuesSvc.updateStage(issue.id, 'idea', { locked: true });+ await issuesSvc.updateStage(issue.id, 'comicScript', { locked: true });+ // Visual stages carry the same lock bit and gate their own enqueue paths —+ // the sweep must cover every STAGE_ID, not just the text ones.+ await issuesSvc.updateStage(issue.id, 'comicPages', { locked: true });++ const counts = await unlockSeriesForAutopilot(s.id);+ expect(counts).toMatchObject({ arc: 1, arcFields: 2, seasons: 1, stages: 3, canon: 0 });++ const after = await seriesSvc.getSeries(s.id);+ expect(after.locked).toEqual({});+ expect(after.seasons.every((x) => x.locked !== true)).toBe(true);+ // Volume content survives the unlock — the pass only clears the lock bit.+ expect(after.seasons.find((x) => x.id === 'sea-a').title).toBe('One');+ const afterIssue = await issuesSvc.getIssue(issue.id);+ expect(afterIssue.stages.idea.locked).toBe(false);+ expect(afterIssue.stages.comicScript.locked).toBe(false);+ expect(afterIssue.stages.comicPages.locked).toBe(false);+ });++ it('is idempotent — a second pass finds nothing locked and reports zero', async () => {+ const s = await buildSeries();+ await seriesSvc.updateSeries(s.id, { locked: { arc: true } });+ await unlockSeriesForAutopilot(s.id);+ const second = await unlockSeriesForAutopilot(s.id);+ expect(second).toMatchObject({ arc: 0, arcFields: 0, seasons: 0, stages: 0, canon: 0 });+ });++ it('unlocks only the canon this series owns and keeps another series\' canon frozen', async () => {+ const mine = await buildSeries({ universeId: 'uni-1' });+ const other = await seriesSvc.createSeries({ name: 'Sibling', targetFormat: 'comic' });+ await seriesSvc.updateSeries(other.id, { universeId: 'uni-1' });+ universe = {+ id: 'uni-1',+ characters: [+ charEntry({ id: 'mine', locked: true, sourceSeriesId: mine.id }),+ charEntry({ id: 'theirs', locked: true, sourceSeriesId: other.id }),+ charEntry({ id: 'shared', locked: true }), // unowned + a sibling series exists+ ],+ places: [charEntry({ id: 'p1', locked: true, sourceSeriesId: mine.id })],+ objects: [],+ };++ const counts = await unlockSeriesForAutopilot(mine.id);+ expect(counts.canon).toBe(2); // 'mine' + 'p1'+ expect(counts.canonForeignKept).toBe(2); // 'theirs' + 'shared'+ const byId = Object.fromEntries(universe.characters.map((e) => [e.id, e]));+ expect(byId.mine.locked).toBe(false);+ expect(byId.theirs.locked).toBe(true);+ expect(byId.shared.locked).toBe(true);+ expect(universe.places[0].locked).toBe(false);+ // Never destructive: every entry is still present in the universe.+ expect(universe.characters).toHaveLength(3);+ expect(universe.places).toHaveLength(1);+ });++ it('unlocks unowned canon when this series is the universe\'s only series', async () => {+ const mine = await buildSeries({ universeId: 'uni-solo' });+ universe = { id: 'uni-solo', characters: [charEntry({ id: 'legacy', locked: true })], places: [], objects: [] };+ const counts = await unlockSeriesForAutopilot(mine.id);+ expect(counts.canon).toBe(1);+ expect(counts.canonForeignKept).toBe(0);+ expect(universe.characters[0].locked).toBe(false);+ });++ it('skips the universe read entirely for an orphan series (no universeId)', async () => {+ const s = await buildSeries();+ const counts = await unlockSeriesForAutopilot(s.id);+ expect(counts.canon).toBe(0);+ expect(counts.universeId).toBeNull();+ expect(getUniverse).not.toHaveBeenCalled();+ });++ it('writes nothing to the universe when no owned canon entry is locked', async () => {+ const mine = await buildSeries({ universeId: 'uni-1' });+ universe = { id: 'uni-1', characters: [charEntry({ id: 'mine', sourceSeriesId: mine.id })], places: [], objects: [] };+ await unlockSeriesForAutopilot(mine.id);+ // The mutator still runs (that is how the freshest state is read), but it+ // must return null so updateUniverse short-circuits with no write.+ expect(universe.characters[0].locked).toBeUndefined();+ });+});++// Source-level guard, not a behavioral one: unlocking is what lets the autopilot+// FULLY EDIT a character/object/volume, and the standing rule is that it must+// never turn into permission to DELETE one. A record that has to leave is a+// catalog archive (soft-delete/tombstone) performed by a human. Nothing in the+// conductor calls a destructive service today; this fails the moment something+// does, so the decision is made deliberately rather than by an innocent import.+describe('unlockPass — the conductor has no destructive canon/record path', () => {+ const DIR = dirname(fileURLToPath(import.meta.url));+ const DESTRUCTIVE = ['removeCanonEntry', 'deleteSeason', 'deleteIssue', 'deleteSeries', 'deleteUniverse'];+ const sources = readdirSync(DIR)+ .filter((f) => f.endsWith('.js') && !f.endsWith('.test.js'))+ .map((f) => [f, readFileSync(join(DIR, f), 'utf8')]);++ it('reads every conductor module (guard would pass vacuously on an empty list)', () => {+ expect(sources.length).toBeGreaterThan(5);+ });++ it.each(DESTRUCTIVE)('never calls %s', (fn) => {+ // Match a CALL (`fn(`), not a mention — the module headers name these+ // deliberately when explaining the policy, and prose must not fail the guard.+ const callSite = new RegExp(`\\b${fn}\\s*\\(`);+ const offenders = sources.filter(([, src]) => callSite.test(src)).map(([f]) => f);+ expect(offenders).toEqual([]);+ });++ it('the guard actually detects a call (bypass probe)', () => {+ const callSite = new RegExp('\\bremoveCanonEntry\\s*\\(');+ expect(callSite.test('await removeCanonEntry(universeId, kind, id);')).toBe(true);+ expect(callSite.test('// removeCanonEntry is deliberately never used here')).toBe(false);+ });+});