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 xhigh code-review findings on Story Builder + reader map

Adam Eivye1c0fd0dfa7c
diff --git a/PLAN.md b/PLAN.md
index 72b4b4dc67..51b01d83ee 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -197,6 +197,8 @@ The first slice shipped a working **seed-mode** conductor (`/story-builder`): cr
- [ ] [story-builder-sse-progress] **SSE streaming for long generations.** `generateStep`/`refineStep` are synchronous request/response (await the LLM, return the result) — fine for arc/reader-map but a long arc-overview blocks the button with only a spinner. Add a `GET /api/story-builder/:id/steps/:stepId/progress` EventSource endpoint (reuse `client/src/hooks/useSseProgress.js`) and stream stage progress like the pipeline auto-run does. The plan specced this; deferred as a v1 simplification.
- [ ] [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-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.
## Future Ideas
diff --git a/client/src/pages/StoryBuilder.jsx b/client/src/pages/StoryBuilder.jsx
index ed2713c657..0fb6722eee 100644
--- a/client/src/pages/StoryBuilder.jsx
+++ b/client/src/pages/StoryBuilder.jsx
@@ -366,21 +366,30 @@ function StoryBuilderDetail({ storyId, stepParam }) {
if (!s) { setSession(null); setLoading(false); return; }
setSession(s);
setStaleSteps(s.staleSteps || []);
+ // These GETs own their fallback (.catch → null/[]), so silence the helper's
+ // default error toast — otherwise a transient failure double-toasts.
const [u, ser] = await Promise.all([
- s.universeId ? getUniverse(s.universeId).catch(() => null) : Promise.resolve(null),
- s.seriesId ? getPipelineSeries(s.seriesId).catch(() => null) : Promise.resolve(null),
+ s.universeId ? getUniverse(s.universeId, { silent: true }).catch(() => null) : Promise.resolve(null),
+ s.seriesId ? getPipelineSeries(s.seriesId, { silent: true }).catch(() => null) : Promise.resolve(null),
]);
setUniverse(u);
setSeries(ser);
if (s.seriesId) {
- const iss = await listPipelineIssues(s.seriesId).catch(() => []);
+ const iss = await listPipelineIssues(s.seriesId, { silent: true }).catch(() => []);
setIssues(Array.isArray(iss) ? iss : (iss?.items || []));
}
setLoading(false);
}, [storyId]);
- useEffect(() => { getStoryBuilderSteps({ silent: true }).then((r) => setSteps(r.steps || [])).catch(() => {}); }, []);
- useEffect(() => { setLoading(true); reload(); }, [reload]);
+ // Load the step manifest first; gate the loading spinner on BOTH it and the
+ // session so the detail view never renders with an empty step rail.
+ useEffect(() => {
+ setLoading(true);
+ getStoryBuilderSteps({ silent: true })
+ .then((r) => setSteps(r.steps || []))
+ .catch(() => {})
+ .finally(reload);
+ }, [reload]);
const stepIds = steps.map((s) => s.id);
const activeStepId = stepIds.includes(stepParam) ? stepParam : (session?.currentStep || 'idea');
@@ -470,6 +479,7 @@ function StoryBuilderDetail({ storyId, stepParam }) {
)}
<StepPanel
+ key={activeStepId}
session={session} universe={universe} series={series} issues={issues}
stepId={activeStepId} locked={stepState.locked} onChanged={reload}
/>
diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.js
index 0c310393c8..6f74be6d4a 100644
--- a/client/src/services/apiPipeline.js
+++ b/client/src/services/apiPipeline.js
@@ -62,7 +62,7 @@ export const PIPELINE_STAGE_STATUS_COLOR = Object.freeze({
// `options` lets a caller suppress request()'s auto-toast with `{ silent: true }`
// (e.g. an optional join that should fail quietly) — see CLAUDE.md.
export const listPipelineSeries = (options = {}) => request('/pipeline/series', options);
-export const getPipelineSeries = (id) => request(`/pipeline/series/${encodeURIComponent(id)}`);
+export const getPipelineSeries = (id, options = {}) => request(`/pipeline/series/${encodeURIComponent(id)}`, options);
export const createPipelineSeries = (data) => request('/pipeline/series', {
method: 'POST',
body: JSON.stringify(data),
@@ -97,8 +97,8 @@ export const SERIES_TITLE_LOGO_MAX = 2000;
export const SERIES_AUTHOR_MAX = 120;
// ---- Issues ----
-export const listPipelineIssues = (seriesId) =>
- request(`/pipeline/series/${encodeURIComponent(seriesId)}/issues`);
+export const listPipelineIssues = (seriesId, options = {}) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/issues`, options);
export const createPipelineIssue = (seriesId, data) =>
request(`/pipeline/series/${encodeURIComponent(seriesId)}/issues`, {
diff --git a/client/src/services/apiUniverseBuilder.js b/client/src/services/apiUniverseBuilder.js
index cc5f2605d2..0e4eb772c0 100644
--- a/client/src/services/apiUniverseBuilder.js
+++ b/client/src/services/apiUniverseBuilder.js
@@ -17,7 +17,7 @@ export const WORLD_INFLUENCES_PER_LIST_MAX = 30;
// `options` lets a caller that owns its own error toast pass `{ silent: true }`
// so request() doesn't also toast — see CLAUDE.md "Custom catch ⇒ silent: true".
export const listUniverses = (options = {}) => request('/universe-builder', options);
-export const getUniverse = (id) => request(`/universe-builder/${encodeURIComponent(id)}`);
+export const getUniverse = (id, options = {}) => request(`/universe-builder/${encodeURIComponent(id)}`, options);
export const createUniverse = (data) => request('/universe-builder', {
method: 'POST',
diff --git a/server/routes/pipeline.js b/server/routes/pipeline.js
index fb82c55f21..e1559a9efc 100644
--- a/server/routes/pipeline.js
+++ b/server/routes/pipeline.js
@@ -144,6 +144,12 @@ const arcSchema = z.object({
themes: z.array(z.string().trim().min(1).max(ARC_LIMITS.THEME_MAX))
.max(ARC_LIMITS.THEMES_PER_ARC_MAX).optional(),
shape: z.enum(ARC_SHAPE_IDS).nullable().optional(),
+ // Reader map (audience-experience roadmap). Accepted as an opaque object and
+ // validated/sanitized server-side by sanitizeReaderMap (storyArc.js) — mirrors
+ // how visualStageInputSchema defers artifact validation to the service. Must
+ // be listed here or Zod's default key-stripping would silently drop it on any
+ // arc PATCH, and updateSeries's wholesale arc replace would then wipe it.
+ readerMap: z.object({}).passthrough().nullable().optional(),
status: z.enum(ARC_STATUSES).optional(),
});
diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.js
index f5bb4ea5c2..c24c5dee80 100644
--- a/server/routes/pipeline.test.js
+++ b/server/routes/pipeline.test.js
@@ -477,6 +477,30 @@ describe('pipeline routes', () => {
expect(r.status).toBe(404);
});
+ it('PATCH /series/:id preserves arc.readerMap through the route schema (no key-strip)', async () => {
+ // Regression: arcSchema must list readerMap, or Zod strips it and the
+ // wholesale arc replace in updateSeries silently wipes the user's map.
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'RM', universeId: 'u-test' });
+ const patch = await request(app).patch(`/api/pipeline/series/${ser.body.id}`).send({
+ arc: {
+ logline: 'spine',
+ summary: 'sum',
+ readerMap: { hooks: [{ label: 'Who fell?' }], beats: [{ kind: 'reveal', intensity: 0.7 }] },
+ },
+ });
+ expect(patch.status).toBe(200);
+ expect(patch.body.arc.readerMap).toBeTruthy();
+ expect(patch.body.arc.readerMap.hooks).toHaveLength(1);
+ expect(patch.body.arc.readerMap.beats[0].kind).toBe('reveal');
+ // And a subsequent arc edit that re-sends the full arc keeps it.
+ const edit = await request(app).patch(`/api/pipeline/series/${ser.body.id}`).send({
+ arc: { ...patch.body.arc, logline: 'new spine' },
+ });
+ expect(edit.body.arc.logline).toBe('new spine');
+ expect(edit.body.arc.readerMap.hooks).toHaveLength(1);
+ });
+
it('POST /series/:id/issues creates an issue under the series', async () => {
const app = makeApp();
const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
diff --git a/server/services/pipeline/arcPlanner.js b/server/services/pipeline/arcPlanner.js
index f70c1870a2..0f0917f3da 100644
--- a/server/services/pipeline/arcPlanner.js
+++ b/server/services/pipeline/arcPlanner.js
@@ -358,6 +358,12 @@ export async function generateReaderMap(seriesId, options = {}) {
cliffhangers: content?.cliffhangers,
status: 'draft',
});
+ // A null sanitize means the LLM returned nothing usable — surface an error
+ // rather than letting the caller persist `readerMap: null` over an existing
+ // map (silent data loss).
+ if (!readerMap) {
+ throw makeErr('LLM returned an empty reader map — try regenerating', ERR_VALIDATION);
+ }
return { readerMap, raw: content, runId, providerId, model };
}
@@ -385,10 +391,17 @@ export async function refineReaderMap(seriesId, feedback, options = {}) {
logTag: `Story Builder reader-map refine series=${seriesId.slice(0, 8)}`,
});
const readerMap = sanitizeReaderMap({ ...content, status: 'draft' });
+ // Refine is meant to PRESERVE — never let an empty LLM payload null out the
+ // existing map. Fall back to the current reader map when the refine produced
+ // nothing usable (mirrors the CLAUDE.md absent-vs-empty rule).
+ const safeReaderMap = readerMap || arc.readerMap || null;
+ if (!safeReaderMap) {
+ throw makeErr('LLM returned an empty reader map and there is none to preserve', ERR_VALIDATION);
+ }
const changes = Array.isArray(content.changes)
? content.changes.map((c) => String(c).slice(0, 240)).filter(Boolean).slice(0, 12)
: [];
- return { readerMap, changes, rationale, runId, providerId, model };
+ return { readerMap: safeReaderMap, changes, rationale, runId, providerId, model };
}
/**
diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.js
index bc544ac9ed..b69c286876 100644
--- a/server/services/pipeline/arcPlanner.test.js
+++ b/server/services/pipeline/arcPlanner.test.js
@@ -1420,4 +1420,26 @@ describe('arcPlanner — refineReaderMap', () => {
const s = await setupSeries({ locked: { arcFields: { readerMap: true } } });
await expect(planner.refineReaderMap(s.id, 'x')).rejects.toMatchObject({ code: 'PIPELINE_ARC_VALIDATION' });
});
+
+ it('preserves the existing reader map when the LLM returns an empty refinement (non-destructive)', async () => {
+ const s = await setupSeries({
+ arc: { logline: 'rise', summary: 'spine', readerMap: { hooks: [{ label: 'keep me' }] } },
+ });
+ // LLM returns nothing usable (only meta) — must NOT null out the map.
+ stageRunnerSpy = vi.fn(async () => ({
+ content: { hooks: [], payoffs: [], beats: [], cliffhangers: [], changes: [], rationale: 'no change' },
+ runId: 'r', providerId: 'p', model: 'm',
+ }));
+ const out = await planner.refineReaderMap(s.id, 'tweak');
+ expect(out.readerMap.hooks[0].label).toBe('keep me');
+ });
+
+ it('throws (rather than returns null) when generateReaderMap yields an empty map', async () => {
+ const s = await setupSeries({ arc: { logline: 'x', summary: 'y' } });
+ stageRunnerSpy = vi.fn(async () => ({
+ content: { hooks: [], payoffs: [], beats: [], cliffhangers: [] },
+ runId: 'r', providerId: 'p', model: 'm',
+ }));
+ await expect(planner.generateReaderMap(s.id)).rejects.toMatchObject({ code: 'PIPELINE_ARC_VALIDATION' });
+ });
});
diff --git a/server/services/storyBuilder.js b/server/services/storyBuilder.js
index 1a8a737c5e..978584a1c7 100644
--- a/server/services/storyBuilder.js
+++ b/server/services/storyBuilder.js
@@ -325,12 +325,14 @@ async function applyUnderlyingLock(session, stepId, locked) {
await updateSeries(session.seriesId, { locked: nextLocked });
} else if (stepId === 'readerMap' && session.seriesId) {
await setArcFieldLock(session.seriesId, 'readerMap', locked);
- } else if (stepId === 'characters' && session.universeId) {
- const universe = await getUniverse(session.universeId).catch(() => null);
- if (!universe || !Array.isArray(universe.characters)) return;
- const characters = universe.characters.map((c) => ({ ...c, locked }));
- await updateUniverse(session.universeId, { characters });
}
+ // NOTE: the 'characters' step deliberately has NO underlying record lock.
+ // Universe canon is shared across series, and per-entry character locks are
+ // user-managed (in the Universe Builder / via this step's per-entry Refine).
+ // Blanket-toggling locked on every character would clobber those individual
+ // locks and mutate a universe other series depend on. The session-level step
+ // lock alone gates the wizard; the UI hides the per-character Refine when the
+ // step is locked.
}
export async function lockStep(id, stepId) {
@@ -463,6 +465,9 @@ export async function generateStep(id, stepId, options = {}) {
const { arc, seasons, runId, providerId, model } = await generateArcOverview(session.seriesId, {
providerOverride: options.providerId, modelOverride: options.model,
});
+ // 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 });
return { result: updated, runId, providerId, model };
}