Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

scope the unlock option to one run and close the paths it left open

[._.]/ Adam Eivy7dd2a13efe0a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index a1d9dfa966..c6c44dda9a 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,7 +2,7 @@
## 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** 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, the locks on the universe canon **this series owns**, and (only when this is the universe's sole series) the universe's own world-field locks — then reports exactly what it cleared and what it deliberately left frozen. 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, objects and volumes 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, all three arc-rewriting paths (arc generation, arc auto-resolve, and the foundation gate's structure fix) now re-insert any volume the rewrite omitted. It applies to one run only and is never saved as a default, so an unattended scheduled run can't inherit lock-clearing — and the dry-run plan names it, with a count of the locks it would clear, 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.
diff --git a/client/src/components/pipeline/AutopilotPanel.jsx b/client/src/components/pipeline/AutopilotPanel.jsx
index 2cd7258ea9..53428e5d38 100644
--- a/client/src/components/pipeline/AutopilotPanel.jsx
+++ b/client/src/components/pipeline/AutopilotPanel.jsx
@@ -46,10 +46,6 @@ 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;
@@ -183,15 +179,19 @@ function frameLabel(f) {
// 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}`;
+ if (f.worldFields) parts.push(`${f.worldFields} world field(s)`);
+ if (parts.length === 0) return 'Unlock — nothing was locked';
+ const kept = [
+ f.canonForeignKept ? `${f.canonForeignKept} other series' canon` : '',
+ f.worldFieldsKept ? `${f.worldFieldsKept} shared world field(s)` : '',
+ ].filter(Boolean);
+ return `Unlocked ${parts.join(', ')}${kept.length ? ` · kept ${kept.join(' + ')} locked` : ''}`;
}
case 'render:queued': return `Queued draft render: ${f.target}`;
case 'gap:filed': return `Filed CoS task (${f.gapKind})`;
@@ -270,12 +270,14 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
const [revisionMinCycles, setRevisionMinCycles] = useState(DEFAULT_REVISION_MIN_CYCLES);
const [revisionMaxCycles, setRevisionMaxCycles] = useState(DEFAULT_REVISION_MAX_CYCLES);
const [revisionPlateauDelta, setRevisionPlateauDelta] = useState(DEFAULT_REVISION_PLATEAU_DELTA);
+ // Unlock-everything pre-pass. PER-RUN ONLY and never persisted (like
+ // `readinessGate` below, unlike every other option here): it rewrites lock
+ // state the user set by hand, and a saved default would be picked up by
+ // scheduled unattended runs of every series. Always starts unticked, so
+ // clearing locks is a fresh, deliberate choice each run.
+ const [unlockForRun, setUnlockForRun] = useState(false);
// 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);
@@ -293,7 +295,6 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
const 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);
@@ -374,7 +375,6 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
if (!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);
@@ -410,11 +410,6 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
const 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);
@@ -537,9 +532,6 @@ 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);
@@ -548,6 +540,10 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
// specific gate. Unlike the round inputs we never persist it — '' leaves the
// server to resolve the gate from the saved setting (then the default).
const gateOverride = READINESS_GATE_LABELS[readinessGate] ? { readinessGate } : {};
+ // Per-run unlock pre-pass — sent only when ticked, and never persisted (see
+ // the state declaration): a saved default would reach unattended scheduled
+ // runs of every series, and this one rewrites user-set lock state.
+ const unlockOverride = unlockForRun ? { unlockForRun: true } : {};
// Per-run provider/model override, sent ONLY when the user picked one —
// otherwise the server resolves the series' own llm (then the active
// provider). Never persisted, like the readiness gate. Picking a provider
@@ -556,7 +552,7 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
...(providerOverride ? { providerOverride } : {}),
...(modelOverride ? { modelOverride } : {}),
};
- const res = await startPipelineAutopilot(seriesId, { includeVisual, fileGaps, ...roundOverrides, ...gateOverride, ...llmOverride }, { silent: true })
+ const res = await startPipelineAutopilot(seriesId, { includeVisual, fileGaps, ...roundOverrides, ...gateOverride, ...unlockOverride, ...llmOverride }, { silent: true })
.catch((err) => { toast.error(err.message || 'Could not start autopilot'); return null; });
setStarting(false);
if (!res) return;
@@ -688,12 +684,12 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
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)} />
+ <input type="checkbox" checked={unlockForRun} onChange={(e) => setUnlockForRun(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.
+ 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 the universe&apos;s own world fields are only cleared when this is its only series. Nothing is ever deleted: characters, objects and volumes can be rewritten in full but stay in the Universe and the Catalog. Locks are <em>not</em> restored when the run ends. Applies to this run only — never saved as a default, so a scheduled run can&apos;t inherit it.
</p>
) : null}
<div className="flex flex-wrap gap-4 pt-1">
diff --git a/client/src/components/pipeline/AutopilotPanel.test.jsx b/client/src/components/pipeline/AutopilotPanel.test.jsx
index b1b9a158bc..ba4bd4187d 100644
--- a/client/src/components/pipeline/AutopilotPanel.test.jsx
+++ b/client/src/components/pipeline/AutopilotPanel.test.jsx
@@ -112,27 +112,31 @@ describe('AutopilotPanel', () => {
);
});
- it('sends AND persists unlockForRun once the unlock checkbox is toggled', async () => {
+ it('sends unlockForRun as a per-run override and never persists it', 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 },
));
+ // Saving it would let a scheduled unattended run inherit lock-clearing.
+ expect(patchSettingsSlice).not.toHaveBeenCalledWith(
+ 'pipelineEditorialChecks',
+ expect.objectContaining({ unlockForRun: expect.anything() }),
+ expect.anything(),
+ );
});
- it('omits unlockForRun when the checkbox is untouched (server resolves the saved default)', async () => {
+ it('starts unticked even when settings carry a stale unlockForRun value', 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());
+ expect(screen.getByRole('checkbox', { name: /unlock everything this series owns/i })).not.toBeChecked();
fireEvent.click(screen.getByRole('button', { name: /run autopilot/i }));
await waitFor(() => expect(startPipelineAutopilot).toHaveBeenCalledWith(
's1', { includeVisual: true, fileGaps: false }, { silent: true },
@@ -140,15 +144,23 @@ describe('AutopilotPanel', () => {
});
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 }];
+ sseFrames = [{ type: 'unlock:applied', arc: 1, arcFields: 0, seasons: 2, stages: 3, canon: 4, canonForeignKept: 5, worldFields: 0, worldFieldsKept: 2 }];
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,
+ screen.getAllByText(/Unlocked arc, 2 volume\(s\), 3 stage\(s\), 4 canon entries · kept 5 other series' canon \+ 2 shared world field\(s\) locked/).length,
).toBeGreaterThan(0));
});
+ it('reads an already-unlocked series as a no-op rather than "unlocked 0 things"', async () => {
+ sseFrames = [{ type: 'unlock:applied', arc: 0, arcFields: 0, seasons: 0, stages: 0, canon: 0, canonForeignKept: 0, worldFields: 0, worldFieldsKept: 0 }];
+ sseLatest = sseFrames[0];
+ getPipelineAutopilotStatus.mockResolvedValue({ autopilot: { runId: 'r1', status: 'running' }, active: true });
+ renderPanel({ id: 's1', targetFormat: 'comic' });
+ await waitFor(() => expect(screen.getAllByText(/Unlock — nothing was 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.js
index 8c47bc9513..1916a425a1 100644
--- a/server/lib/pipelineValidation.js
+++ b/server/lib/pipelineValidation.js
@@ -255,15 +255,12 @@ 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(),
+ // NOTE: the autopilot's `unlockForRun` option is deliberately NOT stored here.
+ // Every knob in this slice is a spend/quality default that is harmless to
+ // reuse unattended; unlocking rewrites protection state the user set by hand,
+ // and `seriesAutopilotScheduler` reads this slice — so a saved default would
+ // arm lock-clearing for every scheduled run of every series. It is a per-run
+ // option only (see seriesAutopilot/config.js#resolveAutopilotUnlockForRun).
}).strict();
// Cursor-context payload for the CD-bridge suggest route — identical shape to
diff --git a/server/lib/storyBible.js b/server/lib/storyBible.js
index c96890aa2c..b7bc889731 100644
--- a/server/lib/storyBible.js
+++ b/server/lib/storyBible.js
@@ -849,6 +849,28 @@ function applyCanonExtras(raw) {
return out;
}
+/**
+ * PURE: does `sourceSeriesId` make this canon entry a given series' to edit?
+ *
+ * Universe canon is shared by every series linked to that universe, so a
+ * series-scoped bulk operation (the autopilot's unlock-for-run pre-pass, and
+ * any future "reset what this series introduced" affordance) must not touch
+ * another series' cast. Lives here, next to the sanitizer that owns and caps
+ * `sourceSeriesId`, so the meaning of that field has one definition:
+ *
+ * - `sourceSeriesId === seriesId` → this series minted it. In scope.
+ * - `sourceSeriesId` names another series → out of scope, always.
+ * - no `sourceSeriesId` (universe-authored / legacy) → in scope ONLY when
+ * `soleSeries`, i.e. the caller has established that this series is the
+ * universe's only one, so there is no other 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;
+}
+
// Pipeline + writers-room shapes both use `physicalDescription`. Migration 019
// rewrites the legacy `description` alias forward, but the read-side fallback
// stays in place so a load-before-migration doesn't silently drop the text on
diff --git a/server/lib/validation.test.js b/server/lib/validation.test.js
index 1e33502928..adc4fbb220 100644
--- a/server/lib/validation.test.js
+++ b/server/lib/validation.test.js
@@ -1744,12 +1744,10 @@ 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('rejects a saved unlockForRun default — the option is per-run only', () => {
+ // Persisting it would let `seriesAutopilotScheduler` (which reads this
+ // slice) arm lock-clearing on every unattended run of every series.
+ expect(pipelineEditorialChecksSettingsSchema.safeParse({ unlockForRun: true }).success).toBe(false);
});
it('the settings slice accepts forward/older-peer custom-check shapes (lenient)', () => {
diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.js
index 02dd887cf1..3b4cc61f65 100644
--- a/server/services/pipeline/arcPlanner.test.js
+++ b/server/services/pipeline/arcPlanner.test.js
@@ -1001,6 +1001,10 @@ describe('arcPlanner — shapeEpisodeResolutions', () => {
});
});
+// Shared by every commitSeasonsWithRemap case below — they all commit a fresh
+// draft arc and vary only the seasons.
+const DRAFT_ARC = Object.freeze({ logline: 'L', summary: '', themes: [], protagonistArc: '', shape: null, status: 'draft' });
+
describe('arcPlanner — commitSeasonsWithRemap', () => {
beforeEach(() => {
fileStore.clear();
@@ -1023,7 +1027,7 @@ describe('arcPlanner — commitSeasonsWithRemap', () => {
{ id: 'sea-fresh-2', number: 2, title: 'Six Blocks Down', logline: '', synopsis: '', endingHook: '', episodeCountTarget: 3, themes: [] },
];
const out = await planner.commitSeasonsWithRemap(cur, {
- arc: { logline: 'L', summary: '', themes: [], protagonistArc: '', shape: null, status: 'draft' },
+ arc: DRAFT_ARC,
seasons: freshSeasons,
});
@@ -1043,7 +1047,7 @@ describe('arcPlanner — commitSeasonsWithRemap', () => {
const cur = await seriesSvc.getSeries(s.id);
const out = await planner.commitSeasonsWithRemap(cur, {
- arc: { logline: 'L', summary: '', themes: [], protagonistArc: '', shape: null, status: 'draft' },
+ arc: DRAFT_ARC,
seasons: [{ ...oldS1, logline: 'updated' }],
});
expect(out.reassignedIssueCount).toBe(0);
@@ -1058,7 +1062,7 @@ describe('arcPlanner — commitSeasonsWithRemap', () => {
const cur = await seriesSvc.getSeries(s.id);
const out = await planner.commitSeasonsWithRemap(cur, {
- arc: { logline: 'L', summary: '', themes: [], protagonistArc: '', shape: null, status: 'draft' },
+ arc: DRAFT_ARC,
seasons: [],
});
expect(out.reassignedIssueCount).toBe(1);
@@ -1194,7 +1198,7 @@ describe('arcPlanner — commitSeasonsWithRemap (season locks)', () => {
await seasonsSvc.updateSeason(s.id, s1.id, { locked: true });
const cur = await seriesSvc.getSeries(s.id);
const out = await planner.commitSeasonsWithRemap(cur, {
- arc: { logline: 'L', summary: '', themes: [], protagonistArc: '', shape: null, status: 'draft' },
+ arc: DRAFT_ARC,
seasons: [
// LLM tries to rewrite the locked season's content under the same id.
{ id: s1.id, number: 1, title: 'LLM rewrite', logline: 'LLM logline', synopsis: 'LLM synopsis', endingHook: '', episodeCountTarget: 9, themes: [] },
@@ -1215,7 +1219,7 @@ describe('arcPlanner — commitSeasonsWithRemap (season locks)', () => {
const i1 = await issuesSvc.createIssue({ seriesId: s.id, seasonId: s1.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' },
+ arc: DRAFT_ARC,
// LLM proposed dropping the locked season entirely.
seasons: [],
});
@@ -1232,7 +1236,7 @@ describe('arcPlanner — commitSeasonsWithRemap (season locks)', () => {
const unlocked = await seasonsSvc.createSeason(s.id, { title: 'Editable', episodeCountTarget: 4, number: 2 });
const cur = await seriesSvc.getSeries(s.id);
const out = await planner.commitSeasonsWithRemap(cur, {
- arc: { logline: 'L', summary: '', themes: [], protagonistArc: '', shape: null, status: 'draft' },
+ arc: DRAFT_ARC,
seasons: [
{ id: locked.id, number: 1, title: 'LLM rewrite of frozen', logline: '', synopsis: '', endingHook: '', episodeCountTarget: 1, themes: [] },
{ id: unlocked.id, number: 2, title: 'Editable v2', logline: 'updated', synopsis: '', endingHook: '', episodeCountTarget: 5, themes: [] },
@@ -1245,6 +1249,33 @@ describe('arcPlanner — commitSeasonsWithRemap (season locks)', () => {
expect(editableAfter.title).toBe('Editable v2');
expect(editableAfter.episodeCountTarget).toBe(5);
});
+
+ // `preserveDroppedSeasons` — the autopilot's unlock-for-run mode clears the
+ // per-season locks above, so this is what keeps a rewrite from DELETING a
+ // volume once they're gone.
+ 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: DRAFT_ARC,
+ 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: DRAFT_ARC, seasons: [] });
+ expect(out.series.seasons.map((x) => x.id)).not.toContain(dropped.id);
+ });
});
// Non-destructive guarantee behind the autopilot's unlock-for-run mode: once
@@ -1277,41 +1308,6 @@ describe('arcPlanner — preserveDroppedSeasonRecords', () => {
});
});
-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.js
index e9777fbdef..cabf1fa6e8 100644
--- a/server/services/pipeline/arcPlanner/arcCore.js
+++ b/server/services/pipeline/arcPlanner/arcCore.js
@@ -595,7 +595,7 @@ export function mergeSeasonsWithLocks(currentSeasons, nextSeasons) {
// 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;
+ if (!Array.isArray(currentSeasons)) 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];
diff --git a/server/services/pipeline/foundationJudge.js b/server/services/pipeline/foundationJudge.js
index 24f193a775..c51a56b1b1 100644
--- a/server/services/pipeline/foundationJudge.js
+++ b/server/services/pipeline/foundationJudge.js
@@ -524,7 +524,7 @@ async function refineWorld(universeId, { providerId, model }) {
* `finding` is the judge's `{ gap, fix }` for the targeted dimension, threaded
* into the structure resolve as a synthesized arc finding.
*/
-export async function applyFoundationFix(seriesId, dimension, { finding = {}, providerOverride, modelOverride } = {}) {
+export async function applyFoundationFix(seriesId, dimension, { finding = {}, providerOverride, modelOverride, preserveDroppedSeasons = false } = {}) {
assertValidSeriesId(seriesId);
const series = await getSeries(seriesId);
const universeId = series?.universeId || null;
@@ -564,6 +564,11 @@ export async function applyFoundationFix(seriesId, dimension, { finding = {}, pr
findings,
providerDefault: providerOverride,
modelDefault: modelOverride,
+ // The autopilot's unlock-for-run mode clears both `series.locked.arc`
+ // (disarming the short-circuit above) and every per-season lock, so this
+ // is the third arc-rewriting path that could otherwise delete a volume.
+ // Carry the same non-deletion guarantee the other two do.
+ preserveDroppedSeasons,
});
return { dimension, applied: r?.applied !== false };
}
diff --git a/server/services/pipeline/issueStages.js b/server/services/pipeline/issueStages.js
index 67a2222cd1..82413aa5be 100644
--- a/server/services/pipeline/issueStages.js
+++ b/server/services/pipeline/issueStages.js
@@ -66,8 +66,13 @@ export function updateStagesWithLatest(seriesId, updates = [], { snapshotPrior =
const state = await readState();
const results = [];
let changed = false;
+ // Index once: `state.issues` is the INSTALL-wide list, and a bulk caller can
+ // pass one update per (issue, stage) — a per-update findIndex would make the
+ // write O(updates × issues in the install). Rebuilt in step with the
+ // in-place `state.issues[idx] = …` writes below (index positions are stable).
+ const indexById = new Map(state.issues.map((i, idx) => [i.id, idx]));
for (const update of updates) {
- const idx = state.issues.findIndex((i) => i.id === update.issueId);
+ const idx = indexById.get(update.issueId) ?? -1;
if (idx < 0) throw makeErr(`Issue not found: ${update.issueId}`, ERR_NOT_FOUND);
const cur = state.issues[idx];
if (cur.deleted || cur.seriesId !== seriesId) throw makeErr(`Issue not found: ${update.issueId}`, ERR_NOT_FOUND);
diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.js
index ba1360c855..31304d26d7 100644
--- a/server/services/pipeline/seriesAutopilot.test.js
+++ b/server/services/pipeline/seriesAutopilot.test.js
@@ -763,14 +763,17 @@ 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);
+ expect(autopilot.resolveAutopilotUnlockForRun({})).toBe(false);
+ expect(autopilot.resolveAutopilotUnlockForRun({ unlockForRun: false })).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('is on only when the run explicitly asks for it', () => {
+ expect(autopilot.resolveAutopilotUnlockForRun({ unlockForRun: true })).toBe(true);
});
- it('falls back to the persisted setting when no per-run option', () => {
- expect(autopilot.resolveAutopilotUnlockForRun({}, { pipelineEditorialChecks: { unlockForRun: true } })).toBe(true);
+ // The one autopilot option with NO persisted default: `seriesAutopilotScheduler`
+ // resolves unattended runs from the settings slice, so a saved value would arm
+ // lock-clearing on every scheduled run of every series.
+ it('ignores a persisted setting entirely — per-run only', () => {
+ expect(autopilot.resolveAutopilotUnlockForRun({}, { pipelineEditorialChecks: { unlockForRun: true } })).toBe(false);
});
});
diff --git a/server/services/pipeline/seriesAutopilot/childRuns.js b/server/services/pipeline/seriesAutopilot/childRuns.js
index 99dc54c631..51ce0bcc04 100644
--- a/server/services/pipeline/seriesAutopilot/childRuns.js
+++ b/server/services/pipeline/seriesAutopilot/childRuns.js
@@ -17,7 +17,7 @@ import {
CHILD_POLL_MS, DIVERGENCE_PATIENCE, trackConvergence, convergencePauseReason,
divergencePauseReason, foundationPauseReason, foundationDivergenceReason,
} from './convergence.js';
-import { broadcast, budgetPause, providerOverrideOpts, providerIdOpts } from './session.js';
+import { broadcast, budgetPause, providerOverrideOpts, providerIdOpts, seasonPreserveOpts } from './session.js';
import { requiredScriptStages, textReady } from './stepResolver.js';
// ---------------------------------------------------------------------------
@@ -72,10 +72,7 @@ export async function runArcVerify(seriesId, 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,
+ ...seasonPreserveOpts(record),
});
await recordDomainUsage('cos', { actions: 1 });
broadcast(seriesId, {
@@ -219,6 +216,7 @@ export async function runFoundationGate(seriesId, record) {
finding: snap.dimensions?.[weak.dimension] || {},
providerOverride: providerId,
modelOverride: model,
+ ...seasonPreserveOpts(record),
});
await recordDomainUsage('cos', { actions: 1 });
broadcast(seriesId, {
diff --git a/server/services/pipeline/seriesAutopilot/config.js b/server/services/pipeline/seriesAutopilot/config.js
index 222bfb9edb..b70c8ae484 100644
--- a/server/services/pipeline/seriesAutopilot/config.js
+++ b/server/services/pipeline/seriesAutopilot/config.js
@@ -147,19 +147,21 @@ export function wantsTeaser(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
+// each volume's lock, every issue stage lock, and the universe-side records
// 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;
+// resolve.
+//
+// PER-RUN ONLY, deliberately — the one autopilot option with NO persisted
+// default (mirrors `readinessGate`, and unlike every other gate here). The rest
+// of this file's options are spend/quality knobs where a saved default is
+// harmless; this one rewrites protection state the user set by hand. A saved
+// default would be read by `seriesAutopilotScheduler`, so ticking the box once
+// in one series' panel would silently arm lock-clearing for every future
+// unattended scheduled run of EVERY series. Stamped onto run options at start
+// so the resolver, the dry-run plan and a resume all read the same flag.
+export function resolveAutopilotUnlockForRun(options = {}) {
+ return options?.unlockForRun === true;
}
// Iterate-to-quality revision loop (CWQE Phase 7, #2171). Opt-in per run; when
diff --git a/server/services/pipeline/seriesAutopilot/dispatch.js b/server/services/pipeline/seriesAutopilot/dispatch.js
index 3af2edcee0..e6e311f97b 100644
--- a/server/services/pipeline/seriesAutopilot/dispatch.js
+++ b/server/services/pipeline/seriesAutopilot/dispatch.js
@@ -6,23 +6,13 @@
import { recordDomainUsage } from '../../domainUsage.js';
import { getSeries } from '../series.js';
import { generateArcOverview, commitSeasonsWithRemap, generateSeasonEpisodes, commitEpisodesToIssues } from '../arcPlanner.js';
-import { providerOverrideOpts } from './session.js';
+import { providerOverrideOpts, seasonPreserveOpts } from './session.js';
import { runArcVerify, runBeats, runBeatContinuity, runFoundationGate, runText } from './childRuns.js';
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':
@@ -32,7 +22,11 @@ export async function dispatchStep(sId, step, record) {
// 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 }, seasonPreserveOpts(record));
+ 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.js
index 8b61c79a81..70a0cf1e06 100644
--- a/server/services/pipeline/seriesAutopilot/dryRun.js
+++ b/server/services/pipeline/seriesAutopilot/dryRun.js
@@ -13,6 +13,7 @@ import {
import { roundsNote, convergenceLoopActions, VISUAL_DRAFT_ENABLED } from './convergence.js';
import { orderedIssues, byNumber, issueHasBeats, textReady, wantsComic, visualReady } from './stepResolver.js';
import { editorialSubsetIds } from './editorialSteps.js';
+import { countSeriesLocks } from './unlockPass.js';
// ---------------------------------------------------------------------------
// Dry-run planning — enumerate what execute WOULD do, no side effects.
@@ -28,39 +29,26 @@ 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.
+ // The count comes from the pass's own `countSeriesLocks` so the promise can't
+ // drift from what actually gets cleared; universe-side locks aren't included
+ // (they need an async read, and this builder is synchronous).
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`,
+ note: `unlock ${countSeriesLocks(series, ordered)} series-record lock(s) + this series' universe canon — other series' canon stays locked; nothing is deleted`,
estActions: 0,
});
}
+ // 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.
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.js
index 2268cb6745..c0229f6f02 100644
--- a/server/services/pipeline/seriesAutopilot/orchestrator.js
+++ b/server/services/pipeline/seriesAutopilot/orchestrator.js
@@ -70,7 +70,7 @@ export async function startSeriesAutopilot(sId, options = {}) {
checkFindingsPauseThreshold: resolveAutopilotCheckPauseThreshold(options, settings),
notifyOnPause: resolveAutopilotNotifyOnPause(options, settings),
produceTeaser: resolveAutopilotProduceTeaser(options, settings),
- unlockForRun: resolveAutopilotUnlockForRun(options, settings),
+ unlockForRun: resolveAutopilotUnlockForRun(options),
...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
@@ -247,15 +247,15 @@ 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 === 'unlockLocks';
- if (!selfGatingStep && !zeroRoundSkip) {
+ || step.kind === 'reverseOutline';
+ // Distinct from the self-gating steps (which bill, but decide for
+ // themselves when): `unlockLocks` makes no LLM call and bills nothing at
+ // all — it only clears lock bits — so pausing it on an exhausted budget
+ // would strand the run before its first real step for zero spend.
+ const costFreeStep = step.kind === 'unlockLocks';
+ if (!selfGatingStep && !costFreeStep && !zeroRoundSkip) {
const budget = await getDomainBudgetStatus('cos');
if (!budget.withinBudget) {
const budgetReason = `daily cos ${budget.exceeded} budget reached`;
diff --git a/server/services/pipeline/seriesAutopilot/session.js b/server/services/pipeline/seriesAutopilot/session.js
index 6eba5bf168..66cd344bbd 100644
--- a/server/services/pipeline/seriesAutopilot/session.js
+++ b/server/services/pipeline/seriesAutopilot/session.js
@@ -199,6 +199,17 @@ export const providerIdOpts = (record) => ({
},
});
+// Non-deletion guarantee for every arc-rewriting call this run makes. Once the
+// unlock pre-pass has cleared the per-season locks (see ./unlockPass.js), 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 it can
+// delete". Lives here beside the other record→options fragments so every arc
+// path (generateArc, arc auto-resolve, the foundation gate's structure fix)
+// spreads the SAME rule instead of each inlining its own copy.
+export const seasonPreserveOpts = (record) => ({
+ preserveDroppedSeasons: record.options.unlockForRun === true,
+});
+
// Pause result when the cos action budget is exhausted, else null. Used to gate
// EACH billable call inside the multi-call verify/editorial convergence loops —
// the conductor's per-step budget check only fires once before the step, so
diff --git a/server/services/pipeline/seriesAutopilot/unlockPass.js b/server/services/pipeline/seriesAutopilot/unlockPass.js
index 97b682235b..068b4aba87 100644
--- a/server/services/pipeline/seriesAutopilot/unlockPass.js
+++ b/server/services/pipeline/seriesAutopilot/unlockPass.js
@@ -11,14 +11,13 @@
*
* 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).
+ * 1. SERIES SCOPE. Universe canon (characters / places / objects) and the
+ * universe's own world fields are shared across every series linked to that
+ * universe, so a blanket unlock would hand the autopilot edit rights over
+ * another series' cast and setting. Canon is filtered by ownership
+ * (`isSeriesScopedCanonEntry`, which owns the `sourceSeriesId` rule); the
+ * universe's world-field locks have no per-series ownership at all, so they
+ * are cleared ONLY when this series is the universe's sole series.
* Everything else the pass touches (arc, arc fields, seasons, issue stages)
* is wholly series-owned, so it unlocks unconditionally.
*
@@ -31,72 +30,57 @@
* 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).
+ * on every arc-rewriting call once 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.
+ * it changed (SSE frame + log) so re-locking is an informed choice.
*/
-import { BIBLE_KEYS } from '../../../lib/storyBible.js';
+import { BIBLE_KEYS, isSeriesScopedCanonEntry } from '../../../lib/storyBible.js';
import { getUniverse, updateUniverse } from '../../universeBuilder.js';
+import { setCanonLocksForSeries } from '../../universeCanon.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);
+// Every lock on the SERIES records this pass would clear: the arc freeze, each
+// per-field arc lock, each volume lock, each issue stage lock. Exported so the
+// dry-run plan can promise the same number the pass reports — one definition,
+// so a new lock surface can't be counted in one place and cleared in the other.
+// Universe-side locks are deliberately excluded: they live on another record
+// that only an async read could reach, and the dry-run plan is synchronous.
+export function countSeriesLocks(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 { unlockable, foreign };
+ return n;
}
-// 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) {
+// Clear `series.locked` (the binary arc freeze + every per-field arc lock) AND
+// every volume's lock in ONE patch. `updateSeries` applies `locked` and
+// `seasons` as independent wholesale replaces over the freshest record inside
+// its write queue, so a single call costs one read/write/peer-emit instead of
+// two — and there is no re-read window between them.
+async function unlockSeriesRecord(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 arc = locked.arc === true ? 1 : 0;
+ const arcFields = Object.keys(locked.arcFields || {}).length;
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;
+ const lockedSeasons = seasons.filter((s) => s?.locked === true).length;
+ if (arc === 0 && arcFields === 0 && lockedSeasons === 0) return { arc: 0, arcFields: 0, seasons: 0 };
+ await updateSeries(series.id, {
+ ...(arc || arcFields ? { locked: {} } : {}),
+ ...(lockedSeasons ? { seasons: seasons.map((s) => (s?.locked === true ? { ...s, locked: false } : s)) } : {}),
+ });
+ return { arc, arcFields, seasons: lockedSeasons };
}
// Clear `locked` on every stage of every issue in the series. Batched through
@@ -120,68 +104,73 @@ async function unlockIssueStages(seriesId, issues) {
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 };
+// Is this series the ONLY one linked to `universeId`? Decides whether records
+// with no per-series owner (unowned canon, the universe's world fields) are
+// safe to unlock. `listSeries()` loads every series in the install, so callers
+// gate it on there actually being an unowned locked record to decide about.
+async function isSoleSeriesOfUniverse(seriesId, universeId) {
+ const all = await listSeries().catch(() => []);
+ return !all.some((s) => s.id !== seriesId && s.universeId === universeId);
+}
- 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 };
+// Does the universe hold a locked canon entry with no owning series? Only then
+// does `soleSeries` change any outcome — every owned entry is decided by its
+// own `sourceSeriesId`.
+const hasUnownedLockedCanon = (universe) => BIBLE_KEYS.some((key) =>
+ (Array.isArray(universe?.[key]) ? universe[key] : [])
+ .some((e) => e?.locked === true && !e?.sourceSeriesId));
+
+// Clear the universe's own world-field locks (logline / premise / styleNotes /
+// influence lists). These have no per-series owner, so they are only this
+// series' to clear when it is the universe's sole series. Worth covering: the
+// foundation gate's world + craft fixes report "every refinable world field is
+// locked" and pause the run — exactly the stall this option exists to remove.
+async function unlockUniverseWorldFields(universe, soleSeries) {
+ const lockedCount = Object.values(universe?.locked || {}).filter((v) => v === true).length;
+ if (lockedCount === 0 || !soleSeries) return { cleared: 0, kept: soleSeries ? 0 : lockedCount };
+ await updateUniverse(universe.id, { locked: {} });
+ return { cleared: lockedCount, kept: 0 };
+}
+
+// Clear the locks on the universe-side records this series owns: its canon
+// entries, plus the world fields when this series is the universe's only one.
+async function unlockUniverseFor(seriesId, universeId) {
+ const universe = await getUniverse(universeId).catch(() => null);
+ if (!universe) return { canon: 0, canonForeignKept: 0, worldFields: 0, worldFieldsKept: 0 };
+ const worldLocked = Object.values(universe.locked || {}).some((v) => v === true);
+ // One install-wide read at most, and only when an unowned record's fate
+ // actually depends on it.
+ const soleSeries = (hasUnownedLockedCanon(universe) || worldLocked)
+ ? await isSoleSeriesOfUniverse(seriesId, universeId)
+ : false;
+ const canon = await setCanonLocksForSeries(universeId, seriesId, false, { soleSeries });
+ const world = await unlockUniverseWorldFields(universe, soleSeries);
+ return {
+ canon: canon.changed,
+ canonForeignKept: canon.foreignKept,
+ worldFields: world.cleared,
+ worldFieldsKept: world.kept,
+ };
}
/**
* 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
+ * broadcast as an `unlock:applied` SSE frame by the step handler). 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,
- };
+ const [series, issues] = await Promise.all([getSeries(seriesId), listIssues({ seriesId })]);
+ // Three independent stores (series / issues / universe), so run them
+ // concurrently rather than paying three sequential round-trips at the top of
+ // every unlock-enabled run.
+ const [record, stages, universe] = await Promise.all([
+ unlockSeriesRecord(series),
+ unlockIssueStages(seriesId, issues),
+ series.universeId
+ ? unlockUniverseFor(seriesId, series.universeId)
+ : Promise.resolve({ canon: 0, canonForeignKept: 0, worldFields: 0, worldFieldsKept: 0 }),
+ ]);
+ return { ...record, stages, ...universe };
}
/**
@@ -198,10 +187,7 @@ export async function runUnlockPass(seriesId, record) {
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}`);
+ broadcast(seriesId, { type: 'unlock:applied', ...counts });
+ console.log(`🔓 autopilot unlock — series=${seriesId.slice(0, 12)} arc=${counts.arc} arcFields=${counts.arcFields} seasons=${counts.seasons} stages=${counts.stages} canon=${counts.canon} world=${counts.worldFields} foreignKept=${counts.canonForeignKept}`);
return {};
}
diff --git a/server/services/pipeline/seriesAutopilot/unlockPass.test.js b/server/services/pipeline/seriesAutopilot/unlockPass.test.js
index 58baad9ce7..3b275446a8 100644
--- a/server/services/pipeline/seriesAutopilot/unlockPass.test.js
+++ b/server/services/pipeline/seriesAutopilot/unlockPass.test.js
@@ -46,7 +46,8 @@ vi.mock('../../universeBuilder.js', async (importOriginal) => ({
const seriesSvc = await import('../series.js');
const issuesSvc = await import('../issues.js');
-const { isSeriesScopedCanonEntry, partitionLockedCanon, unlockSeriesForAutopilot } = await import('./unlockPass.js');
+const { isSeriesScopedCanonEntry } = await import('../../../lib/storyBible.js');
+const { unlockSeriesForAutopilot, countSeriesLocks } = await import('./unlockPass.js');
const charEntry = (over = {}) => ({ id: 'c1', name: 'Kai', physicalDescription: 'Tall.', ...over });
@@ -73,15 +74,26 @@ describe('unlockPass — series-scoped canon predicate', () => {
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']);
+});
+
+// The dry-run plan promises this number; the pass clears exactly these locks.
+// One definition, so the two can't drift when a lock surface is added.
+describe('unlockPass — countSeriesLocks', () => {
+ it('counts the arc freeze, each arc field, each volume and each issue stage', () => {
+ const series = {
+ locked: { arc: true, arcFields: { logline: true, themes: true } },
+ seasons: [{ id: 'a', locked: true }, { id: 'b' }],
+ };
+ const issues = [
+ { stages: { idea: { locked: true }, prose: { locked: false }, comicPages: { locked: true } } },
+ { stages: { idea: {} } },
+ ];
+ expect(countSeriesLocks(series, issues)).toBe(1 + 2 + 1 + 2);
+ });
+
+ it('is 0 for a fully-unlocked series and tolerates missing shapes', () => {
+ expect(countSeriesLocks({ seasons: [{ id: 'a' }] }, [{ stages: {} }])).toBe(0);
+ expect(countSeriesLocks(null, null)).toBe(0);
});
});
@@ -173,10 +185,35 @@ describe('unlockPass — end-to-end over the real series/issue services', () =>
const s = await buildSeries();
const counts = await unlockSeriesForAutopilot(s.id);
expect(counts.canon).toBe(0);
- expect(counts.universeId).toBeNull();
+ expect(counts.worldFields).toBe(0);
expect(getUniverse).not.toHaveBeenCalled();
});
+ // The foundation gate's world + craft fixes report "every refinable world
+ // field is locked" and pause the run — the exact stall this option removes.
+ it('clears the universe world-field locks when this series is its only series', async () => {
+ const mine = await buildSeries({ universeId: 'uni-solo' });
+ universe = {
+ id: 'uni-solo', characters: [], places: [], objects: [],
+ locked: { logline: true, styleNotes: true },
+ };
+ const counts = await unlockSeriesForAutopilot(mine.id);
+ expect(counts.worldFields).toBe(2);
+ expect(counts.worldFieldsKept).toBe(0);
+ expect(universe.locked).toEqual({});
+ });
+
+ it('leaves the universe world-field locks alone when a sibling series shares the universe', 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: [], places: [], objects: [], locked: { logline: true } };
+ const counts = await unlockSeriesForAutopilot(mine.id);
+ expect(counts.worldFields).toBe(0);
+ expect(counts.worldFieldsKept).toBe(1);
+ expect(universe.locked).toEqual({ logline: true });
+ });
+
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: [] };
diff --git a/server/services/universeCanon.js b/server/services/universeCanon.js
index c06df20d48..2e6b4ad2cc 100644
--- a/server/services/universeCanon.js
+++ b/server/services/universeCanon.js
@@ -8,7 +8,7 @@ import { getUniverse, updateUniverse, listUniverses, joinInfluenceList } from '.
import { extractBible } from '../lib/bibleExtractor.js';
import {
BIBLE_KIND, BIBLE_KINDS, BIBLE_FIELD, BIBLE_KEYS, BIBLE_SOURCE, BIBLE_LIMITS, mergeExtractedBible,
- listSheetPointers, applySheetPointerToCharacter,
+ listSheetPointers, applySheetPointerToCharacter, isSeriesScopedCanonEntry,
} from '../lib/storyBible.js';
import { runStagedLLM } from '../lib/stageRunner.js';
import { runPromptRefine } from './pipeline/refineHelpers.js';
@@ -641,6 +641,54 @@ export async function setCanonKindLockAll(universeId, kind, locked) {
return { universe: updated, kind, locked, changed, total };
}
+/**
+ * Set the `locked` flag on every canon entry — across ALL kinds — that a given
+ * SERIES owns, leaving every other entry untouched. The series-scoped sibling
+ * of `setCanonKindLockAll`: same mutator-form write-queue contract, but the
+ * selector is ownership (`isSeriesScopedCanonEntry`) rather than kind, and it
+ * covers all three buckets in ONE patch instead of one write per kind.
+ *
+ * `soleSeries` is the caller's assertion that this series is the universe's
+ * only one — the condition under which an entry carrying no `sourceSeriesId`
+ * (universe-authored / legacy) is safe to touch. Entries owned by another
+ * series are never touched, and are reported back as `foreignKept` so the
+ * caller can say what it deliberately left alone.
+ *
+ * Non-destructive by construction: only the `locked` bit is written. Nothing is
+ * removed from the universe — an entry that should leave is a catalog archive
+ * performed by a human, never a side effect of a bulk lock change.
+ *
+ * Returns `{ universe, changed, foreignKept }`.
+ */
+export async function setCanonLocksForSeries(universeId, seriesId, locked, { soleSeries = false } = {}) {
+ const scope = { seriesId, soleSeries };
+ let changed = 0;
+ let foreignKept = 0;
+ const universe = await updateUniverse(universeId, (cur) => {
+ changed = 0; // reset so a retried mutator can't double-count
+ foreignKept = 0;
+ const patch = {};
+ for (const key of BIBLE_KEYS) {
+ const list = Array.isArray(cur[key]) ? cur[key] : null;
+ if (!list) continue;
+ let keyTouched = false;
+ const nextList = list.map((entry) => {
+ if ((entry?.locked === true) === (locked === true)) return entry;
+ if (!isSeriesScopedCanonEntry(entry, scope)) {
+ if (entry?.locked === true) foreignKept += 1;
+ return entry;
+ }
+ changed += 1;
+ keyTouched = true;
+ return { ...entry, locked };
+ });
+ if (keyTouched) patch[key] = nextList;
+ }
+ return Object.keys(patch).length > 0 ? patch : null;
+ });
+ return { universe, changed, foreignKept };
+}
+
/**
* Remove ONE canon entry from a universe's characters/places/objects bucket.
*