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

address review (codex): close four ways the unlock pass could over-reach

[._.]/ Adam Eivy37b9582a08c0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index c6c44dda9a..5dbd7673bd 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, 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** 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 and every issue stage lock, then reports exactly what it cleared and what it deliberately left frozen. Two boundaries are hard. **Shared records stay locked:** the universe's canon and world fields are only unlocked when this is the universe's *only* series — a stamp saying this series introduced a character records provenance, not exclusive use, and once a sibling series shares the universe that character may be one the sibling is built on. **Nothing is ever deleted:** the pass 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, and existing volumes win the per-series volume cap so a large regeneration can't push them out of the list. Consent is per run and per series: it is never saved as a default, the box clears itself once you launch, and it resets when you switch series — so a scheduled, repeat, or other-series run can't inherit lock-clearing. The dry-run plan names the step, 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 53428e5d38..7905fc226b 100644
--- a/client/src/components/pipeline/AutopilotPanel.jsx
+++ b/client/src/components/pipeline/AutopilotPanel.jsx
@@ -327,6 +327,13 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
return () => { canceled = true; };
}, []);
+ // Disarm the unlock consent whenever the panel switches series. This
+ // component is reused across `seriesId` changes rather than remounted, so
+ // without this a box ticked for series A would still be armed — invisibly,
+ // since the Options popover is collapsed — when the user lands on series B
+ // and hits Run. Consent is per series AND per run; never inherited.
+ useEffect(() => { setUnlockForRun(false); }, [seriesId]);
+
// Effective provider/model this run will use: per-run override → series.llm →
// active provider (the client mirror of the server's resolveAutopilotLlm), so
// the Options copy names what will actually run.
@@ -558,6 +565,12 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
if (!res) return;
setMode(res.mode || null);
setShowOpts(false);
+ // Spend the unlock consent — it authorizes exactly the run just started.
+ // Without this it stays armed behind a now-collapsed Options popover while
+ // the Run button remains visible, so the next click would silently clear
+ // locks again with no checkbox on screen to reveal it. Re-arming is one
+ // deliberate tick, which is the whole contract of this option.
+ setUnlockForRun(false);
// Track this run's id BEFORE enabling the stream so the terminal-frame
// effect can reject a stale terminal frame from the previous run.
activeRunIdRef.current = res.runId || null;
@@ -689,7 +702,7 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
</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 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.
+ Clears the arc freeze, arc-field locks, volume locks and issue stage locks — so the run can actually apply the fixes its editorial passes find. Universe canon is only unlocked when this is the universe&apos;s <em>only</em> series: once another series shares the universe, its cast and setting stay locked, because a character this series introduced may well be one the other series is built on. 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 — it is never saved as a default and the box clears itself after you launch, so a scheduled or repeat 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 ba4bd4187d..eedeaa4a64 100644
--- a/client/src/components/pipeline/AutopilotPanel.test.jsx
+++ b/client/src/components/pipeline/AutopilotPanel.test.jsx
@@ -27,6 +27,8 @@ import {
startPipelineAutopilot,
getPipelineAutopilotStatus,
getPipelineSeriesCanonReadiness,
+ getPipelineSeries,
+ listPipelineIssues,
getProviders,
getSettings,
patchSettingsSlice,
@@ -131,6 +133,60 @@ describe('AutopilotPanel', () => {
);
});
+ // The consent authorizes ONE run. It must not stay armed behind the collapsed
+ // Options popover while the Run button is still on screen.
+ it('clears the unlock consent after launching, so the next run does not inherit it', async () => {
+ const { rerender } = 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 }));
+ fireEvent.click(screen.getByRole('button', { name: /run autopilot/i }));
+ await waitFor(() => expect(startPipelineAutopilot).toHaveBeenCalledWith(
+ 's1', expect.objectContaining({ unlockForRun: true }), { silent: true },
+ ));
+ // Finish the run so the Run/Options controls come back, then launch again:
+ // the consent was spent by the first launch and must not silently re-apply.
+ // The terminal-frame effect refetches the series + issues, so give those
+ // mocks a resolved value or the effect throws on `undefined.then`.
+ getPipelineSeries.mockResolvedValue(null);
+ listPipelineIssues.mockResolvedValue(null);
+ sseLatest = { type: 'complete', runId: 'r1' };
+ rerender(
+ <MemoryRouter>
+ <AutopilotPanel series={{ id: 's1', targetFormat: 'comic' }} onSeriesUpdate={vi.fn()} onIssuesUpdate={vi.fn()} />
+ </MemoryRouter>,
+ );
+ await waitFor(() => expect(screen.getByRole('button', { name: /run autopilot/i })).toBeInTheDocument());
+ fireEvent.click(screen.getByRole('button', { name: /options/i }));
+ 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).toHaveBeenLastCalledWith(
+ 's1', { includeVisual: true, fileGaps: false }, { silent: true },
+ ));
+ });
+
+ // The panel is reused across seriesId changes rather than remounted, so a box
+ // ticked for one series must not still be armed — invisibly — on the next.
+ it('clears the unlock consent when the panel switches series', async () => {
+ const { rerender } = 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 }));
+ expect(screen.getByRole('checkbox', { name: /unlock everything this series owns/i })).toBeChecked();
+ rerender(
+ <MemoryRouter>
+ <AutopilotPanel series={{ id: 's2', targetFormat: 'comic' }} onSeriesUpdate={vi.fn()} onIssuesUpdate={vi.fn()} />
+ </MemoryRouter>,
+ );
+ await waitFor(() => 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(
+ 's2', { includeVisual: true, fileGaps: false }, { silent: true },
+ ));
+ });
+
it('starts unticked even when settings carry a stale unlockForRun value', async () => {
getSettings.mockResolvedValue({ pipelineEditorialChecks: { unlockForRun: true } });
renderPanel({ id: 's1', targetFormat: 'comic' });
diff --git a/server/lib/storyBible.js b/server/lib/storyBible.js
index b7bc889731..c58760674c 100644
--- a/server/lib/storyBible.js
+++ b/server/lib/storyBible.js
@@ -850,25 +850,43 @@ function applyCanonExtras(raw) {
}
/**
- * PURE: does `sourceSeriesId` make this canon entry a given series' to edit?
+ * PURE: is this canon entry safe for a given series to bulk-unlock?
*
* 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:
+ * any future "reset what this series introduced" affordance) must not remove
+ * protection from a record another series depends on. Lives here, next to the
+ * sanitizer that owns and caps `sourceSeriesId`, so the rule 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.
+ * **`sourceSeriesId` is PROVENANCE, not exclusivity** — it records which series
+ * first minted the entry, and nothing stops a sibling series from referencing
+ * that same character/place/object (`getSeriesCanon` hands every linked series
+ * the whole universe canon). So "series A minted it" does NOT mean "only series
+ * A uses it", and treating it that way would let A's autopilot rewrite a
+ * character B's issues are built on. Proving actual exclusivity would need the
+ * prose cross-reference in `canonUsage.js` — O(series × issues × matchers) and
+ * still only a text-match heuristic, not a sound proof.
+ *
+ * So the rule is deliberately conservative, and `soleSeries` is REQUIRED:
+ *
+ * - not `soleSeries` (a sibling series shares this universe) → out of scope,
+ * always. Nothing is unlocked, whoever minted it.
+ * - `soleSeries` + `sourceSeriesId` naming a DIFFERENT series → still out of
+ * scope. A stale stamp pointing at an unlinked/deleted series is not a
+ * licence to unfreeze.
+ * - `soleSeries` + minted by this series, or unstamped (universe-authored /
+ * legacy) → in scope. There is no other series left to damage.
+ *
+ * Note this only governs clearing the `locked` BIT. An already-unlocked canon
+ * entry stays editable by any series exactly as before — this never widens
+ * access, it only refuses to narrow protection.
*/
export function isSeriesScopedCanonEntry(entry, { seriesId, soleSeries = false } = {}) {
if (!entry || typeof entry !== 'object') return false;
+ if (soleSeries !== true) return false;
const owner = typeof entry.sourceSeriesId === 'string' ? entry.sourceSeriesId : '';
- if (owner) return owner === seriesId;
- return soleSeries === true;
+ return !owner || owner === seriesId;
}
// Pipeline + writers-room shapes both use `physicalDescription`. Migration 019
diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.js
index 3b4cc61f65..f98f889b34 100644
--- a/server/services/pipeline/arcPlanner.test.js
+++ b/server/services/pipeline/arcPlanner.test.js
@@ -1269,6 +1269,27 @@ describe('arcPlanner — commitSeasonsWithRemap (season locks)', () => {
expect(await issuesSvc.getIssue(i1.id).then((i) => i.seasonId)).toBe(dropped.id);
});
+ // Regression: preserved records must survive `sanitizeSeasonList`'s
+ // first-N cap. Appending them meant a rewrite returning a full cap's worth of
+ // brand-new volumes pushed every existing volume past the cap, the sanitizer
+ // dropped them, and the remap then reassigned their issues — the exact
+ // deletion `preserveDroppedSeasons` exists to refuse.
+ it('keeps existing volumes when the rewrite returns a full cap of brand-new ones', async () => {
+ const s = await setupSeries();
+ const existing = await seasonsSvc.createSeason(s.id, { title: 'Must survive', episodeCountTarget: 3, number: 1 });
+ const i1 = await issuesSvc.createIssue({ seriesId: s.id, seasonId: existing.id, title: 'Pilot' });
+ const cur = await seriesSvc.getSeries(s.id);
+ // SEASONS_PER_SERIES_MAX brand-new volumes, none reusing the existing id.
+ const flood = Array.from({ length: 50 }, (_, i) => ({
+ id: `sea-new-${i}`, number: i + 10, title: `New ${i}`,
+ logline: '', synopsis: '', endingHook: '', episodeCountTarget: 3, themes: [],
+ }));
+ const out = await planner.commitSeasonsWithRemap(cur, { arc: DRAFT_ARC, seasons: flood }, { preserveDroppedSeasons: true });
+ expect(out.series.seasons.map((x) => x.id)).toContain(existing.id);
+ // Its issue was never reassigned to a surviving volume.
+ expect(await issuesSvc.getIssue(i1.id).then((i) => i.seasonId)).toBe(existing.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 });
diff --git a/server/services/pipeline/arcPlanner/arcCore.js b/server/services/pipeline/arcPlanner/arcCore.js
index cabf1fa6e8..f10a79ab77 100644
--- a/server/services/pipeline/arcPlanner/arcCore.js
+++ b/server/services/pipeline/arcPlanner/arcCore.js
@@ -591,14 +591,23 @@ export function mergeSeasonsWithLocks(currentSeasons, nextSeasons) {
// 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.
+// DELETE (see seriesAutopilot/unlockPass.js).
+//
+// The preserved records go FIRST, and that ordering is load-bearing rather than
+// cosmetic: `sanitizeSeasonList` caps the list at SEASONS_PER_SERIES_MAX by
+// keeping the first N it sees. Appending them would mean an LLM that returned a
+// full cap's worth of brand-new volumes silently pushed every existing volume
+// past the cap — the sanitizer would drop them and `commitSeasonsWithRemap`
+// would then treat them as deleted and reassign their issues, which is exactly
+// the deletion this helper exists to refuse. Existing records therefore win the
+// cap; the rewrite's surplus new volumes are what gets trimmed. Final display
+// order is unaffected — `sanitizeSeasonList` sorts by `number` at the end.
export function preserveDroppedSeasonRecords(currentSeasons, nextSeasons) {
if (!Array.isArray(nextSeasons)) 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];
+ return dropped.length === 0 ? nextSeasons : [...dropped, ...nextSeasons];
}
/**
diff --git a/server/services/pipeline/seriesAutopilot/unlockPass.js b/server/services/pipeline/seriesAutopilot/unlockPass.js
index 4c92a5bbe6..704c559ae8 100644
--- a/server/services/pipeline/seriesAutopilot/unlockPass.js
+++ b/server/services/pipeline/seriesAutopilot/unlockPass.js
@@ -113,41 +113,47 @@ async function unlockIssueStages(seriesId, issues) {
// different key sets on an SSE frame the client reads field by field.
const NO_UNIVERSE_UNLOCKS = Object.freeze({ canon: 0, canonForeignKept: 0, worldFields: 0, worldFieldsKept: 0 });
-// 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.
+// Is this series the ONLY one linked to `universeId`? EVERY universe-side
+// unlock is gated on this (see `isSeriesScopedCanonEntry`), so it decides
+// whether shared records get unfrozen — and it therefore FAILS CLOSED. A
+// `listSeries()` that throws on a storage/DB read error must never be read as
+// "no siblings found": `[]` would report sole-series and hand the pass
+// permission to clear locks on canon a sibling series depends on. Uncertain
+// linkage returns false — the run just keeps those locks, which is the
+// recoverable direction. `listSeries()` loads every series in the install, so
+// callers gate it on there actually being a locked record to decide about.
async function isSoleSeriesOfUniverse(seriesId, universeId) {
- const all = await listSeries().catch(() => []);
+ const all = await listSeries().catch((err) => {
+ console.log(`⚠️ autopilot unlock: could not list series to prove sole-universe ownership (${err.message}) — keeping universe-side locks`);
+ return null;
+ });
+ if (!Array.isArray(all)) return false;
return !all.some((s) => s.id !== seriesId && s.universeId === universeId);
}
-// Does the universe hold a locked canon entry whose fate depends on this series
-// being the universe's only one? Asks `isSeriesScopedCanonEntry` rather than
-// re-testing `sourceSeriesId` here, so the ownership rule keeps exactly one
-// definition (see storyBible.js).
-const hasSoleSeriesDependentCanon = (universe, seriesId) => BIBLE_KEYS.some((key) =>
- (Array.isArray(universe?.[key]) ? universe[key] : []).some((e) => e?.locked === true
- && !isSeriesScopedCanonEntry(e, { seriesId })
- && isSeriesScopedCanonEntry(e, { seriesId, soleSeries: true })));
+// Does the universe hold ANY locked canon entry? Only then is the install-wide
+// sole-series read worth paying for — with no locked canon and no locked world
+// field there is nothing for `soleSeries` to decide.
+const hasLockedCanon = (universe) => BIBLE_KEYS.some((key) =>
+ (Array.isArray(universe?.[key]) ? universe[key] : []).some((e) => e?.locked === true));
// Clear the locks on the universe-side records this series owns: its canon
// entries, plus the universe's own world fields (logline / premise / styleNotes
-// / influence lists) when this series is the universe's only one. Those world
-// fields are worth covering because 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.
+// / influence lists). Those world fields are worth covering because 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.
//
-// BOTH live on the universe record, so they go out as ONE write: a second
-// updateUniverse would re-read and re-sanitize the whole record and emit a
-// second peer-sync `recordUpdated` for one user action.
+// BOTH are gated on this series being the universe's only one, and both live on
+// the universe record, so they go out as ONE write: a second updateUniverse
+// would re-read and re-sanitize the whole record and emit a second peer-sync
+// `recordUpdated` for one user action.
async function unlockUniverseFor(seriesId, universeId) {
const universe = await getUniverse(universeId).catch(() => null);
if (!universe) return NO_UNIVERSE_UNLOCKS;
const worldLocked = Object.values(universe.locked || {}).filter((v) => v === true).length;
- // One install-wide read at most, and only when an unowned record's fate
- // actually depends on it.
- const soleSeries = (worldLocked > 0 || hasSoleSeriesDependentCanon(universe, seriesId))
+ // One install-wide read at most, and only when a locked record's fate
+ // actually depends on the answer.
+ const soleSeries = (worldLocked > 0 || hasLockedCanon(universe))
&& await isSoleSeriesOfUniverse(seriesId, universeId);
const canon = await setCanonLocksForSeries(universeId, seriesId, false, {
soleSeries,
@@ -162,40 +168,64 @@ async function unlockUniverseFor(seriesId, universeId) {
}
/**
- * Run the unlock pass for a series. Returns the per-scope counts (also
- * broadcast as an `unlock:applied` SSE frame by the step handler). Idempotent
- * — a second run finds nothing locked and writes nothing.
+ * Run the unlock pass for a series. Returns the per-scope counts plus a
+ * `failures[]` of the scopes that threw (both ride the `unlock:applied` SSE
+ * frame). Idempotent — a second run finds nothing locked and writes nothing.
+ *
+ * The three scopes are SEPARATELY settled, not `Promise.all`-ed. They write to
+ * three independent stores, so one rejecting does NOT undo the two that already
+ * committed — and a rejection that propagated out of here would make the step
+ * handler report "locked records stay frozen" while some locks were in fact
+ * permanently cleared. The run would then continue with mixed protection and no
+ * frame naming what actually changed. Each scope reports its own outcome
+ * instead, so the report always matches the disk.
*/
export async function unlockSeriesForAutopilot(seriesId) {
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([
+ const [record, stages, universe] = await Promise.allSettled([
unlockSeriesRecord(series),
unlockIssueStages(seriesId, issues),
series.universeId
? unlockUniverseFor(seriesId, series.universeId)
: Promise.resolve(NO_UNIVERSE_UNLOCKS),
]);
- return { ...record, stages, ...universe };
+ const failures = [];
+ const settled = (result, scope, zero) => {
+ if (result.status === 'fulfilled') return result.value;
+ failures.push(`${scope} (${result.reason?.message || 'unknown error'})`);
+ return zero;
+ };
+ return {
+ ...settled(record, 'series record', { arc: 0, arcFields: 0, seasons: 0 }),
+ stages: settled(stages, 'issue stages', 0),
+ ...settled(universe, 'universe canon', NO_UNIVERSE_UNLOCKS),
+ failures,
+ };
}
/**
* 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.
+ * so the user knows which locks are still in place.
*/
export async function runUnlockPass(seriesId, record) {
record.runState.locksUnlocked = true;
const counts = await unlockSeriesForAutopilot(seriesId).catch((err) => {
+ // Only the pre-read (series / issues) can land here — the three write
+ // scopes settle individually above — so nothing was cleared.
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 {};
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}`);
+ if (counts.failures.length) {
+ broadcast(seriesId, { type: 'note', message: `Unlock was partial — ${counts.failures.join('; ')} failed, so those records stay frozen for this run.` });
+ }
+ 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} failed=${counts.failures.length}`);
return {};
}
diff --git a/server/services/pipeline/seriesAutopilot/unlockPass.test.js b/server/services/pipeline/seriesAutopilot/unlockPass.test.js
index 747980cdf7..a771bc3f63 100644
--- a/server/services/pipeline/seriesAutopilot/unlockPass.test.js
+++ b/server/services/pipeline/seriesAutopilot/unlockPass.test.js
@@ -60,8 +60,14 @@ beforeEach(() => {
});
describe('unlockPass — series-scoped canon predicate', () => {
- it('unlocks an entry this series minted', () => {
- expect(isSeriesScopedCanonEntry(charEntry({ sourceSeriesId: 's1' }), { seriesId: 's1' })).toBe(true);
+ it('unlocks an entry this series minted, when it is the universe\'s only series', () => {
+ expect(isSeriesScopedCanonEntry(charEntry({ sourceSeriesId: 's1' }), { seriesId: 's1', soleSeries: true })).toBe(true);
+ });
+
+ // `sourceSeriesId` is PROVENANCE, not exclusivity — every linked series can
+ // reference any canon entry, so "s1 minted it" does not make it s1's alone.
+ it('refuses even an entry this series minted once a sibling series shares the universe', () => {
+ expect(isSeriesScopedCanonEntry(charEntry({ sourceSeriesId: 's1' }), { seriesId: 's1', soleSeries: false })).toBe(false);
});
it('refuses an entry another series minted, even when this series is the only one left linked', () => {
@@ -160,18 +166,77 @@ describe('unlockPass — end-to-end over the real series/issue services', () =>
};
const counts = await unlockSeriesForAutopilot(mine.id);
- expect(counts.canon).toBe(2); // 'mine' + 'p1'
- expect(counts.canonForeignKept).toBe(2); // 'theirs' + 'shared'
+ // A sibling series shares the universe, so NOTHING is unlocked — not even
+ // the entries this series minted. `sourceSeriesId` is provenance, not
+ // exclusivity: the sibling can be built on 'mine' just as easily.
+ expect(counts.canon).toBe(0);
+ expect(counts.canonForeignKept).toBe(4);
const byId = Object.fromEntries(universe.characters.map((e) => [e.id, e]));
- expect(byId.mine.locked).toBe(false);
+ expect(byId.mine.locked).toBe(true);
expect(byId.theirs.locked).toBe(true);
expect(byId.shared.locked).toBe(true);
- expect(universe.places[0].locked).toBe(false);
+ expect(universe.places[0].locked).toBe(true);
// Never destructive: every entry is still present in the universe.
expect(universe.characters).toHaveLength(3);
expect(universe.places).toHaveLength(1);
});
+ it('unlocks the canon this series minted once it is the universe\'s only series', async () => {
+ const mine = await buildSeries({ universeId: 'uni-solo' });
+ universe = {
+ id: 'uni-solo',
+ characters: [
+ charEntry({ id: 'mine', locked: true, sourceSeriesId: mine.id }),
+ // A stale stamp pointing at a series that is no longer linked is still
+ // not a licence to unfreeze — sole-series is necessary, not sufficient.
+ charEntry({ id: 'stale', locked: true, sourceSeriesId: 'ser-long-gone' }),
+ ],
+ places: [], objects: [],
+ };
+ const counts = await unlockSeriesForAutopilot(mine.id);
+ expect(counts).toMatchObject({ canon: 1, canonForeignKept: 1 });
+ const byId = Object.fromEntries(universe.characters.map((e) => [e.id, e]));
+ expect(byId.mine.locked).toBe(false);
+ expect(byId.stale.locked).toBe(true);
+ });
+
+ // Fails CLOSED: a listSeries() that throws must never read as "no siblings".
+ it('keeps universe locks frozen when the sole-series lookup fails', async () => {
+ const mine = await buildSeries({ universeId: 'uni-solo' });
+ universe = {
+ id: 'uni-solo',
+ characters: [charEntry({ id: 'mine', locked: true, sourceSeriesId: mine.id })],
+ places: [], objects: [],
+ locked: { logline: true },
+ };
+ const spy = vi.spyOn(seriesSvc, 'listSeries').mockRejectedValueOnce(new Error('db down'));
+ const counts = await unlockSeriesForAutopilot(mine.id);
+ spy.mockRestore();
+ expect(counts).toMatchObject({ canon: 0, worldFields: 0, worldFieldsKept: 1 });
+ expect(universe.characters[0].locked).toBe(true);
+ expect(universe.locked).toEqual({ logline: true });
+ });
+
+ // A rejecting scope must not make the report claim nothing was unlocked while
+ // another scope has already permanently cleared its locks.
+ it('reports the scopes that succeeded when another scope throws', async () => {
+ const s = await buildSeries({ universeId: 'uni-boom' });
+ await seriesSvc.updateSeries(s.id, { locked: { arc: true } });
+ universe = null; // getUniverse resolves null -> universe scope is a clean zero
+ const spy = vi.spyOn(issuesSvc, 'updateStagesWithLatest').mockRejectedValueOnce(new Error('stale issue'));
+ const issue = await issuesSvc.createIssue({ seriesId: s.id, title: 'I1' });
+ await issuesSvc.updateStage(issue.id, 'idea', { locked: true });
+ const counts = await unlockSeriesForAutopilot(s.id);
+ spy.mockRestore();
+ // The series record really was unlocked — say so, instead of reporting a
+ // blanket failure that would leave the run lying about its own state.
+ expect(counts.arc).toBe(1);
+ expect(counts.stages).toBe(0);
+ expect(counts.failures).toHaveLength(1);
+ expect(counts.failures[0]).toContain('issue stages');
+ expect((await seriesSvc.getSeries(s.id)).locked).toEqual({});
+ });
+
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: [] };