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

fix: address local-review findings on Story Builder (data-loss class)

Adam Eivyc085a11c5046
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 23bbc35cfe..808452c4ff 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -16,6 +16,17 @@ TBD
## Fixed
+- **Story Builder data-loss fixes** surfaced by the local-review pass on the unified-story-builder branch:
+ - `generateStep('plotArc')` was wholesale-replacing `series.arc` and `series.seasons` via a plain `updateSeries({ arc, seasons })`, which silently dropped per-field arc locks, locked seasons, and orphaned every child issue attached to a renamed/removed season. Route through `commitSeasonsWithRemap` (same helper the Arc Canvas regenerator uses) so locks are honored and orphaned issues are remapped via normalized title → number → positional fallback.
+ - `resolveVerifyIssues` (the auto-resolve path off the Arc Canvas verify panel) was silently wiping `series.arc.readerMap`: the LLM payload doesn't author the reader map, so omitting it from the sanitizeArc call defaulted the field to `null` and `commitSeasonsWithRemap`'s `mergeArcWithLocks` only restores fields when their per-field lock is `true`. A user who'd generated a reader map without locking it lost the entire map the first time they auto-resolved a finding. The sibling `generateArcOverview` already had this fix; `resolveVerifyIssues` drifted from it despite the "Mirrors `resolveVerifyIssues`" comment.
+ - Reader-map prompt JSON example used a pipe-separated enum string for `kind` (`"hook|reveal|payoff|emotional|cliffhanger"`), which LLMs reproduced literally; `sanitizeReaderBeat` then dropped every beat because the joined string isn't in `READER_MAP_BEAT_KINDS`, leaving `beats: []` and tripping the empty-payload check. Replaced with a single valid example (`"hook"`); the earlier `{{beatKindsCsv}}` line still enumerates the controlled vocabulary.
+ - Story Builder `currentStep` PATCH schema was `z.string().max(40)` and the sanitizer silently coerced unknown values to `STEP_IDS[0]` — a stale client that posted a removed step id would land on the first step with no error. Now `z.enum(STEP_IDS)`; the sanitizer's coerce-on-load fallback stays for resilience against pre-existing corrupted files.
+ - `styleImageRefs` route caps (`.max(50)` on POST and PATCH) were 4× the sanitizer cap (`IMAGE_REFS_PER_ENTRY_MAX` = 12), so a 40-entry POST silently 200'd with 28 entries dropped. Aligned to the shared `entryImageRefsField` so over-the-cap requests get a loud 400.
+ - Boot-time `verifyCollectionVersions` array didn't include the Story Builder store; type-level schema drift would have gone unnoticed.
+ - "Lock the earlier steps first" toast misfired when the step was blocked by upstream-staleness (every earlier step IS locked, but one is stale). Discriminated `reachable()` → `'unlocked' | 'stale' | true` so the toast says "Re-review the stale earlier step first" in that case.
+
+ Dev machines that already ran migration 043 with the buggy reader-map prompts keep the bad copies in `data/prompts/stages/` — delete `story-builder-reader-map.md` and `story-builder-reader-map-refine.md` from that directory, then restart, and migration 043 will re-copy the fixed versions from `data.reference/`. Fresh installs are unaffected.
+
- Series detail page: when the Story Bible drawer is open, the Series Arc + Editorial Roadmap split and the inner text + 260px Themes panel split now respond to the actual content-area width instead of viewport width. Switched to Tailwind v4 container queries — Roadmap drops below Arc when the content area is < 1024px, and Themes stacks below the logline/summary column when the Arc card is < 672px, preventing the text column from being squeezed into an unreadable strip.
## Removed
diff --git a/PLAN.md b/PLAN.md
index 3c46c18653..312233b5e1 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -198,11 +198,17 @@ The first slice shipped a working **seed-mode** conductor (`/story-builder`): cr
- [ ] [story-builder-arc-refine-feedback] **AI refine-with-feedback for the plot-arc step.** `refineStep` supports `universeAesthetic` (via `refineWorldPrompts`), `readerMap` (`refineReaderMap`), and `characters` (`refineUniverseCharacter`), but `plotArc` only offers full regenerate (`generateArcOverview`) — there's no "refine the arc against this note" path. Add an arc-refine prompt + `refineArc` in `arcPlanner.js` and wire it into `refineStep`'s `plotArc` branch + the `StepPanel` plotArc RefineBox.
- [ ] [story-builder-embed-arccanvas] **Embed `ArcCanvas` / `StoryShapes` inline instead of read-only field blocks.** The plotArc + readerMap steps currently render read-only `FieldBlock`s + a deep-link to the Pipeline for editing. The plan called for reusing `client/src/components/pipeline/ArcCanvas.jsx` and the Vonnegut `StoryShapes` sparkline inline (and a beat timeline for the reader map). Embed them so editing happens in-builder. Deferred because `ArcCanvas` has a wide prop surface; the deep-link covers editing for v1.
- [ ] [story-builder-create-rollback] **`createStorySession` seed mode leaves an orphan universe if `createSeries` throws.** `server/services/storyBuilder.js` creates the universe shell, then the series shell, with no rollback — a `createSeries` failure (validation, disk, peer-import) leaves a stray universe (which also fired peer auto-subscribe) with no session pointing at it. Low severity under the single-user trust model, but repeated failed creates accumulate orphans. Wrap the two creates so a series failure deletes the just-created universe, or create the series first. Surfaced by the xhigh code-review (2026-05-27); deferred as non-blocking.
-- [ ] [story-builder-goto-step-gate-divergence] **`goToStep` in `client/src/pages/StoryBuilder.jsx` (~line 414) swallows a `setStoryCurrentStep` rejection and navigates anyway.** If the server re-gate (fresh hashes) rejects the move while the client's `staleSteps` is stale, the UI lands on the target step but the persisted `currentStep` pointer stays behind, so reopening the session drops the user on a different step. Low severity (disabled controls prevent most cases). Either toast + revert nav on rejection, or refetch on failure. Surfaced by the xhigh code-review (2026-05-27).
+- [ ] [story-builder-goto-step-gate-divergence] **Two `setStoryCurrentStep` paths swallow a rejection and navigate anyway.** (a) `goToStep` in `client/src/pages/StoryBuilder.jsx` (~line 769) on a manual step click and (b) the `lock.toggle` `onSuccess` auto-advance after a successful "Lock & continue" (~line 754). If the server re-gate (fresh hashes) rejects the move while the client's `staleSteps` is stale, the UI lands on the target step but the persisted `currentStep` pointer stays behind, so reopening the session drops the user on a different step. Low severity (disabled controls prevent most cases). Either toast + revert nav on rejection, or refetch on failure. Both paths share the fix. Surfaced by the xhigh code-review (2026-05-27); auto-advance path also surfaced by the codex/gemini local-review pass (2026-05-27).
- [ ] [story-builder-import-partial-commit] **Import flow doesn't handle a partial commit.** `ImportPanel.importAndBuild` (`client/src/pages/StoryBuilder.jsx`) calls `commitImport` once; if it fails after the universe/arc/canon persist but the issue-create rolls back (`IMPORTER_PARTIAL_COMMIT_ISSUES`/`arcAlreadyPersisted`), it just toasts a generic error. Re-clicking re-sends the full payload — lower-risk than the standalone Importer (no editable preview, so arc/seasons are the same idempotent values) but a retry could duplicate issues. The standalone `Importer.jsx` guards this with the `arcAlreadyPersisted` retry (sends `arc:null, seasons:[]`). Either reuse that path or surface a "open in the Importer to recover" link. Surfaced by xhigh code-review (2026-05-27); deferred — rare, not data-corruption.
- [ ] [universe-styleImageRefs-wire-and-journal] **`styleImageRefs` is wire-synced but not version-gated, and feeds the conflict-journal content hash.** Confirmed by review: `sanitizeRecordForWire('universe')` ships `styleImageRefs` to peers; an older (field-unaware) peer drops it on receive and, after its own edit bumps `updatedAt`, LWW-strips it back off a newer peer (same class as the readerMap bug, deliberately left ungated since a probe is one-click-regenerable). Separately, `contentHashForRecord` now includes `styleImageRefs`, so a probe render can contribute to a 3-way-divergence conflict-journal entry whose diff won't mention it (`RESTORABLE_FIELDS.universe` omits it) — Conflicts-tab noise on mixed-version federations. Options if it becomes annoying: bump the `universes` schema version (gate it), make `styleImageRefs` local-only (strip from wire), or exclude it from the content hash. Surfaced 2026-05-27; deferred — low-stakes, regenerable.
- [ ] [story-builder-extract-image-render-hook] **Cleanup: the image-render lifecycle is duplicated 5×.** `StepCharacters` (StoryBuilder.jsx) + `StyleProbeImage.jsx` each re-implement `getSettings → readPipelineImageSettings → imageCfg` + a single-render jobId lifecycle, and `StepCharacters` near-verbatim copies `UniverseCanonSection`'s styled-render-and-persist routine (the `getSettings→imageCfg` block alone repeats in NounsStage/ComicScriptStage/UniverseBuilder too). Extract a `useImageRenderSettings()` + `useSingleImageRender({ buildPrompt, onComplete })` hook (home: `client/src/hooks/`) and a shared canon styled-render helper. Also: `ProviderModelPicker` (StoryBuilder.jsx) duplicates the Importer's `LlmPicker` + the `SeriesLlmPicker`/`FeatureProviderPicker`/`StagePromptModelPicker` pattern — promote one shared provider/model picker. Surfaced by xhigh code-review (2026-05-27); deferred — tech debt, not a bug.
- [ ] [story-builder-session-sync] **Optional cross-machine resumable sessions.** Sessions are intentionally local-only in v1 (excluded from peer sync — see `storyBuilder.js` header). If cross-machine resume is wanted later, key the staleness model on a content hash carried in the session (the integrity helper already produces one) rather than live-record diffing, so a peer's universe edit doesn't false-positive-stale the local session.
+- [ ] [story-builder-step-content-staleness] **Upstream-hash detects when a step's INPUTS drift, not when its OUTPUTS are edited out-of-band.** A user can lock the universeAesthetic step, then mutate `universe.logline` directly in Universe Builder, and the aesthetic step lock won't flag stale (the lock is supposed to prevent mutation, but the lock is only soft — it gates the StoryBuilder UI, not the underlying universe record). Same shape for the characters step's `cast`. Either: (i) extend `buildUpstreamInputs` to fingerprint each step's *own outputs* as well as upstream inputs, treating any post-lock mutation as stale (UX over correctness — the integrity hash starts conflating "upstream drift" with "tampering"), or (ii) enforce harder locks at the underlying-record layer so out-of-band edits 400 while a story-builder step is locked. Surfaced by local-review (2026-05-27); deferred — current behavior matches the design intent of "upstream-only" hashing.
+- [ ] [story-builder-refine-returns-provider] **`refineStep('readerMap')` drops `providerId`/`model` from the conductor's return.** Every other refine branch surfaces them so the route/UI can show which model ran; the readerMap branch destructures `runId` only. Two-line fix (see local-review SC-6, 2026-05-27).
+- [ ] [story-builder-refine-fallback-changes] **`refineReaderMap` returns `changes`/`rationale` describing a refine attempt that was discarded in favor of the existing map.** When the LLM payload is empty, the function falls back to `arc.readerMap` but still surfaces the change list the LLM described, so the UI shows a non-empty change list describing a value that wasn't applied. Fix: when falling back, clear `changes` and `rationale`. Surfaced by local-review SC-7 (2026-05-27).
+- [ ] [story-builder-hash-shape-vs-derivation-tests] **storyBuilder.test.js asserts `upstreamHash` is a 64-char hex string but never that it equals `hashUpstream(stepId, inputs)`.** A buggy implementation that always stamped `hashUpstream('idea', null)` would also pass. Import `hashUpstream` and assert exact equality so future input-set drift (the deferred staleness item above) surfaces as a test failure. Surfaced by local-review SC-8 (2026-05-27).
+- [ ] [migration-043-line-ending-precedent] **Migration 043 (story-builder prompts) is first-shipment-only — no OLD_SHIPPED_MD5 hashing.** That's correct today: the prompts haven't shipped to anyone, so a hash-compare-and-update would be no-op. But the precedent matters: when a future migration AMENDS these prompts, follow migration 003's pattern — normalize line endings (`\r\n` → `\n`, bare `\r` → `\n`) before hashing, and ship both `OLD_SHIPPED_MD5` and `NEW_SHIPPED_MD5` so existing installs whose copy still matches the prior shipped hash auto-upgrade. Add a one-line reminder comment to the migration. Surfaced by local-review SS-3 (2026-05-27).
+- [ ] [style-probe-image-uses-draft-not-saved] **`<StyleProbeImage>` in Universe Builder renders against the in-memory draft but persists the resulting filename to the SERVER's saved record.** A probe image semantically built from in-progress styleNotes/influences gets pinned to a saved universe whose actual style fields are still on the prior values; once the user discards the draft, the styleImageRefs persists on a record that never had those style notes. Either gate `canRender` on `!draftDirty` (require save first — but users want to evaluate unsaved edits) or warn when the draft has uncommitted style changes. Story Builder's aesthetic step is fine because it persists before render. Surfaced by local-review C-5 (2026-05-27).
## Future Ideas
diff --git a/client/src/pages/StoryBuilder.jsx b/client/src/pages/StoryBuilder.jsx
index 8457fa9ac1..b705b11d12 100644
--- a/client/src/pages/StoryBuilder.jsx
+++ b/client/src/pages/StoryBuilder.jsx
@@ -730,12 +730,16 @@ function StoryBuilderDetail({ storyId, stepParam }) {
const isStale = staleSteps.includes(activeStepId);
// A step is reachable when every earlier step is locked AND not stale.
+ // Returns `true` (reachable) or a discriminator string identifying the
+ // first blocking earlier step's reason, so the caller can render the
+ // matching toast ("Lock the earlier steps first" vs "Re-review the
+ // stale earlier step first" — same boolean truthiness, different copy).
const reachable = useCallback((idx) => {
if (idx <= 0) return true;
for (let i = 0; i < idx; i++) {
const id = stepIds[i];
- if (session?.steps?.[id]?.locked !== true) return false;
- if (staleSteps.includes(id)) return false;
+ if (session?.steps?.[id]?.locked !== true) return 'unlocked';
+ if (staleSteps.includes(id)) return 'stale';
}
return true;
}, [stepIds, session, staleSteps]);
@@ -762,7 +766,13 @@ function StoryBuilderDetail({ storyId, stepParam }) {
});
const goToStep = async (id, idx) => {
- if (!reachable(idx)) { toast.error('Lock the earlier steps first'); return; }
+ const why = reachable(idx);
+ if (why !== true) {
+ toast.error(why === 'stale'
+ ? 'Re-review the stale earlier step first'
+ : 'Lock the earlier steps first');
+ return;
+ }
// Persist the current-step pointer (server re-gates); navigate optimistically.
await setStoryCurrentStep(storyId, id, { silent: true }).catch(() => {});
navigate(`/story-builder/${storyId}/${id}`);
@@ -810,7 +820,10 @@ function StoryBuilderDetail({ storyId, stepParam }) {
const st = session.steps?.[s.id] || { status: 'pending', locked: false };
const stale = staleSteps.includes(s.id);
const isActive = s.id === activeStepId;
- const canGo = reachable(idx);
+ // `reachable` returns `true` or a string discriminator ('unlocked' / 'stale');
+ // canGo must be strictly boolean — `disabled={!canGo}` would otherwise
+ // treat the truthy string as "reachable" and re-enable a blocked button.
+ const canGo = reachable(idx) === true;
return (
<button
key={s.id} onClick={() => goToStep(s.id, idx)} disabled={!canGo}
diff --git a/data.reference/prompts/stages/story-builder-reader-map-refine.md b/data.reference/prompts/stages/story-builder-reader-map-refine.md
index 3483d2afda..221f4d50b7 100644
--- a/data.reference/prompts/stages/story-builder-reader-map-refine.md
+++ b/data.reference/prompts/stages/story-builder-reader-map-refine.md
@@ -33,7 +33,7 @@ Return ONLY a JSON object (no prose, no code fence):
{
"hooks": [{ "label": "string", "atArcPosition": 0, "note": "string" }],
"payoffs": [{ "label": "string", "atArcPosition": 0, "resolvesHookId": null, "note": "string" }],
- "beats": [{ "kind": "hook|reveal|payoff|emotional|cliffhanger", "atArcPosition": 0, "intensity": 0.5, "note": "string" }],
+ "beats": [{ "kind": "hook", "atArcPosition": 0, "intensity": 0.5, "note": "string" }],
"cliffhangers": [{ "atIssueBoundary": 1, "note": "string" }],
"changes": ["string"],
"rationale": "string"
diff --git a/data.reference/prompts/stages/story-builder-reader-map.md b/data.reference/prompts/stages/story-builder-reader-map.md
index 0432a7cd68..bba013d6b1 100644
--- a/data.reference/prompts/stages/story-builder-reader-map.md
+++ b/data.reference/prompts/stages/story-builder-reader-map.md
@@ -57,7 +57,7 @@ Return ONLY a JSON object (no prose, no code fence):
{
"hooks": [{ "label": "string", "atArcPosition": 0, "note": "string" }],
"payoffs": [{ "label": "string", "atArcPosition": 0, "resolvesHookId": null, "note": "string" }],
- "beats": [{ "kind": "hook|reveal|payoff|emotional|cliffhanger", "atArcPosition": 0, "intensity": 0.5, "note": "string" }],
+ "beats": [{ "kind": "hook", "atArcPosition": 0, "intensity": 0.5, "note": "string" }],
"cliffhangers": [{ "atIssueBoundary": 1, "note": "string" }]
}
```
diff --git a/server/index.js b/server/index.js
index 756598e7b4..49d14b74fd 100644
--- a/server/index.js
+++ b/server/index.js
@@ -152,6 +152,7 @@ import { conflictJournalStore } from './lib/conflictJournal.js';
import { universeStore } from './services/universeBuilder.js';
import { seriesStore } from './services/pipeline/series.js';
import { issueStore } from './services/pipeline/issues.js';
+import { storyBuilderStore } from './services/storyBuilder.js';
import { createPortOSProviderRoutes } from './routes/providers.js';
import { createPortOSRunsRoutes } from './routes/runs.js';
import { createPortOSPromptsRoutes } from './routes/prompts.js';
@@ -207,7 +208,7 @@ await runMigrations({ rootDir: join(__dirname, '..') }).catch(err => {
// but DO NOT crash the server. PortOS is single-user (CLAUDE.md "Security
// Model"); a hard exit on startup is worse than a noisy log the user can act
// on. Returns per-store statuses for downstream telemetry; we discard them.
-await verifyCollectionVersions([universeStore(), seriesStore(), issueStore(), conflictJournalStore()]).catch(err => {
+await verifyCollectionVersions([universeStore(), seriesStore(), issueStore(), conflictJournalStore(), storyBuilderStore()]).catch(err => {
console.error(`❌ Collection version check failed at startup: ${err?.stack ?? err}`);
});
diff --git a/server/lib/validation.js b/server/lib/validation.js
index be4c138d91..a42bebf187 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -5,6 +5,7 @@ import { WORK_KINDS, WORK_STATUSES, ANALYSIS_KINDS } from './writersRoomPresets.
import { ALL_STYLE_IDS, STYLE_ID } from './writersRoomStylePresets.js';
import { BIBLE_LIMITS } from './storyBible.js';
import { ARC_SHAPE_IDS, ARC_ROLES } from './storyArc.js';
+import { STEP_IDS as STORY_STEP_IDS } from './storyBuilderSteps.js';
import { MIN_TIMEOUT as STAGE_TIMEOUT_MIN_MS, MAX_TIMEOUT as STAGE_TIMEOUT_MAX_MS } from './aiToolkit/constants.js';
// gpt-image-2 (codex backend) caps at 3840px per edge and 8,294,400 total
@@ -1795,7 +1796,10 @@ export const storySessionCreateSchema = z.object({
export const storySessionUpdateSchema = z.object({
title: z.string().trim().min(1).max(200).optional(),
seedIdea: z.string().trim().max(4000).optional(),
- currentStep: z.string().trim().max(40).optional(),
+ // Reject removed/unknown step ids loudly — the sanitizer would otherwise
+ // silently coerce them to STEP_IDS[0], landing a stale client on the first
+ // step with no error.
+ currentStep: z.enum(STORY_STEP_IDS).optional(),
llm: z.object({
provider: z.string().trim().max(80).nullable().optional(),
model: z.string().trim().max(200).nullable().optional(),
diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.js
index 495e646db9..596ae26439 100644
--- a/server/routes/universeBuilder.js
+++ b/server/routes/universeBuilder.js
@@ -163,7 +163,10 @@ const createSchema = z.object({
compositeSheets: z.array(compositeSheetSchema).max(svc.COMPOSITE_SHEETS_MAX).optional(),
influences: influencesSchema.optional(),
// Base "style probe" render filenames — sanitized + capped server-side.
- styleImageRefs: z.array(z.string().trim().min(1).max(500)).max(50).optional(),
+ // Match the sanitizer cap so over-the-cap requests get a loud 400 instead
+ // of a silent 200 with N entries dropped (sanitizer keeps the most recent
+ // IMAGE_REFS_PER_ENTRY_MAX). Per-element filename cap is shared too.
+ styleImageRefs: entryImageRefsField,
locked: lockedSchema.optional(),
llm: llmSchema,
// Canon registries on POST (Phase B.4): writers-room promote, share-bucket
@@ -193,7 +196,10 @@ const patchSchema = z.object({
compositeSheets: z.array(compositeSheetSchema).max(svc.COMPOSITE_SHEETS_MAX).optional(),
influences: influencesSchema.optional(),
// Base "style probe" render filenames — sanitized + capped server-side.
- styleImageRefs: z.array(z.string().trim().min(1).max(500)).max(50).optional(),
+ // Match the sanitizer cap so over-the-cap requests get a loud 400 instead
+ // of a silent 200 with N entries dropped (sanitizer keeps the most recent
+ // IMAGE_REFS_PER_ENTRY_MAX). Per-element filename cap is shared too.
+ styleImageRefs: entryImageRefsField,
locked: lockedSchema.optional(),
llm: llmSchema,
// Canon writes — these flow through sanitizeBibleList server-side so
diff --git a/server/services/pipeline/arcPlanner.js b/server/services/pipeline/arcPlanner.js
index 0f0917f3da..3c9893fd72 100644
--- a/server/services/pipeline/arcPlanner.js
+++ b/server/services/pipeline/arcPlanner.js
@@ -1041,6 +1041,10 @@ export async function resolveVerifyIssues(seriesId, options = {}) {
themes: content?.arc?.themes ?? series.arc.themes,
protagonistArc: content?.arc?.protagonistArc ?? series.arc.protagonistArc ?? '',
shape: content?.arc?.shape ?? series.arc.shape ?? null,
+ // The resolve prompt doesn't author the reader map — preserve any existing
+ // one so auto-resolve never silently wipes a reader map the user already
+ // built on the next step. Mirrors `generateArcOverview` above.
+ readerMap: series.arc?.readerMap ?? null,
status: 'draft',
});
diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.js
index b69c286876..7c1e6c30b3 100644
--- a/server/services/pipeline/arcPlanner.test.js
+++ b/server/services/pipeline/arcPlanner.test.js
@@ -732,6 +732,40 @@ describe('arcPlanner — resolveVerifyIssues', () => {
const finalI1 = await issuesSvc.getIssue(i1.id);
expect(finalI1.seasonId).toBeNull();
});
+
+ it('preserves series.arc.readerMap when the resolve LLM does not author one', async () => {
+ // Regression for the drift between generateArcOverview (which preserves
+ // readerMap) and resolveVerifyIssues (which silently wiped it pre-fix).
+ const s = await setupSeries();
+ const priorReaderMap = {
+ hooks: [{ id: 'rm-h-1', label: 'why is the foundry silent', atArcPosition: 0.1, note: '' }],
+ payoffs: [],
+ beats: [],
+ cliffhangers: [],
+ status: 'draft',
+ };
+ await seriesSvc.updateSeries(s.id, {
+ arc: { logline: 'L', summary: 'S', shape: 'man-in-hole', readerMap: priorReaderMap },
+ });
+ stageRunnerSpy = vi.fn(async () => ({
+ content: {
+ // The resolve prompt doesn't ask the LLM for a reader map — make sure
+ // omitting it doesn't wipe the user's existing one.
+ arc: { logline: 'L2', summary: 'S2', themes: [], protagonistArc: '' },
+ seasons: [],
+ notes: '',
+ },
+ runId: 'r', providerId: 'p', model: 'm',
+ }));
+ const out = await planner.resolveVerifyIssues(s.id, {
+ findings: [{ severity: 'medium', problem: 'X', suggestion: 'Y' }],
+ });
+ expect(out.applied).toBe(true);
+ expect(out.series.arc.logline).toBe('L2');
+ // shape and readerMap come from the prior series.arc and must survive.
+ expect(out.series.arc.shape).toBe('man-in-hole');
+ expect(out.series.arc.readerMap?.hooks?.[0]?.label).toBe('why is the foundry silent');
+ });
});
describe('arcPlanner — commitSeasonsWithRemap', () => {
diff --git a/server/services/storyBuilder.js b/server/services/storyBuilder.js
index d42dca139f..68762d0117 100644
--- a/server/services/storyBuilder.js
+++ b/server/services/storyBuilder.js
@@ -36,7 +36,9 @@ import { refineUniverseCharacter } from './universeCanon.js';
import {
createSeries, getSeries, updateSeries, setArcFieldLock,
} from './pipeline/series.js';
-import { generateArcOverview, generateReaderMap, refineReaderMap } from './pipeline/arcPlanner.js';
+import {
+ generateArcOverview, generateReaderMap, refineReaderMap, commitSeasonsWithRemap,
+} from './pipeline/arcPlanner.js';
const TYPE_SCHEMA_VERSION = 1;
@@ -473,7 +475,13 @@ export async function generateStep(id, stepId, options = {}) {
// A null arc means the LLM returned nothing identifying — refuse rather
// than wiping a previously-generated arc with `updateSeries({ arc: null })`.
if (!arc) throw makeErr('LLM returned an empty arc — try regenerating', ERR_VALIDATION);
- const updated = await updateSeries(session.seriesId, { arc, seasons });
+ // Route through commitSeasonsWithRemap so per-field arc locks, per-season
+ // locks, and orphaned child issues are all honored — same path the Arc
+ // Canvas's regenerate uses. A plain updateSeries({ arc, seasons }) would
+ // bypass mergeArcWithLocks / mergeSeasonsWithLocks / buildSeasonRemap and
+ // silently wipe locked seasons and orphan their issues.
+ const series = await getSeries(session.seriesId);
+ const { series: updated } = await commitSeasonsWithRemap(series, { arc, seasons });
return { result: updated, runId, providerId, model };
}
if (stepId === 'readerMap') {