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([story-builder-arc-refine-feedback]): address codex review — migration, themes-wipe edge, season-safe persist

[._.]/ Adam Eivy70c0fddbd0a0
diff --git a/scripts/migrations/062-story-builder-arc-refine-prompt.js b/scripts/migrations/062-story-builder-arc-refine-prompt.js
new file mode 100644
index 0000000000..d0ef8c7824
--- /dev/null
+++ b/scripts/migrations/062-story-builder-arc-refine-prompt.js
@@ -0,0 +1,83 @@
+/**
+ * Seed the Story Builder plot-arc-refine prompt stage into existing installs.
+ *
+ * Single-stage sibling of `043-story-builder-prompts.js`: copies the
+ * `story-builder-arc-refine.md` template from `data.reference/prompts/stages/`
+ * and merges its stage-config entry into `data/prompts/stage-config.json`.
+ * Boot runs migrations (server/index.js) but NOT `setup-data.js`, so an upgrade
+ * that pulls + `pm2 restart`s (rather than running the full setup) would
+ * otherwise leave the new stage unseeded and the first plot-arc refine would
+ * throw "Stage not found".
+ *
+ * FIRST-SHIPMENT SEED ONLY — no MD5 hashing: it copies the template only when
+ * missing and never overwrites an install's existing prompt. A FUTURE migration
+ * that AMENDS this prompt must follow migration 003's hash-driven pattern
+ * (normalize line endings, ship OLD + NEW shipped hashes) instead.
+ */
+
+import { access, copyFile, mkdir, readFile, constants } from 'fs/promises';
+import { dirname, join } from 'path';
+import { atomicWrite } from '../../server/lib/fileUtils.js';
+
+// The prompt file's basename doubles as its stage-config key (sans `.md`).
+const STAGE = 'story-builder-arc-refine';
+
+export default {
+ async up({ rootDir }) {
+ const stagesDir = join(rootDir, 'data', 'prompts', 'stages');
+ await mkdir(stagesDir, { recursive: true });
+
+ // 1. Copy the prompt template if it's missing.
+ const filename = `${STAGE}.md`;
+ const dataPath = join(stagesDir, filename);
+ const samplePath = join(rootDir, 'data.reference', 'prompts', 'stages', filename);
+ const exists = await access(dataPath, constants.F_OK).then(() => true, () => false);
+ if (exists) {
+ console.log(`📝 story-builder prompt: ${filename} already present`);
+ } else {
+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);
+ if (!sampleExists) {
+ console.warn(`⚠️ story-builder: sample missing for ${filename} — skipping copy`);
+ } else {
+ try {
+ await copyFile(samplePath, dataPath);
+ console.log(`✅ seeded ${filename}`);
+ } catch (err) {
+ console.warn(`⚠️ story-builder: copy failed for ${filename}: ${err.message}`);
+ }
+ }
+ }
+
+ // 2. Merge the stage-config entry if it's missing.
+ const installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');
+ const sampleConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');
+ const sampleConfigExists = await access(sampleConfigPath, constants.F_OK).then(() => true, () => false);
+ if (!sampleConfigExists) {
+ console.warn('⚠️ story-builder: data.reference stage-config.json missing — skipping config write');
+ return;
+ }
+ try {
+ const sample = JSON.parse(await readFile(sampleConfigPath, 'utf8'));
+ const installedExists = await access(installedConfigPath, constants.F_OK).then(() => true, () => false);
+ const installed = installedExists
+ ? JSON.parse(await readFile(installedConfigPath, 'utf8'))
+ : { stages: {} };
+ installed.stages = installed.stages || {};
+ if (installed.stages[STAGE]) {
+ console.log(`📝 story-builder stage-config: ${STAGE} already present`);
+ return;
+ }
+ if (!sample?.stages?.[STAGE]) {
+ console.warn(`⚠️ story-builder: sample stage-config missing ${STAGE} — skipping`);
+ return;
+ }
+ installed.stages[STAGE] = sample.stages[STAGE];
+ await mkdir(dirname(installedConfigPath), { recursive: true });
+ await atomicWrite(installedConfigPath, `${JSON.stringify(installed, null, 2)}\n`);
+ const action = installedExists ? 'merged' : 'created';
+ console.log(`📝 story-builder stage-config (${action}): ${STAGE} added`);
+ } catch (err) {
+ console.warn(`⚠️ story-builder: stage-config merge failed: ${err.message}`);
+ }
+ },
+};
diff --git a/scripts/migrations/062-story-builder-arc-refine-prompt.test.js b/scripts/migrations/062-story-builder-arc-refine-prompt.test.js
new file mode 100644
index 0000000000..80698aecd6
--- /dev/null
+++ b/scripts/migrations/062-story-builder-arc-refine-prompt.test.js
@@ -0,0 +1,58 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+import migration from './062-story-builder-arc-refine-prompt.js';
+
+const STAGE = 'story-builder-arc-refine';
+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));
+
+describe('migration 062 — seed Story Builder plot-arc-refine prompt', () => {
+ let rootDir;
+ let installedStagesDir;
+ let installedConfigPath;
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-062-'));
+ const refStagesDir = join(rootDir, 'data.reference', 'prompts', 'stages');
+ mkdirSync(refStagesDir, { recursive: true });
+ writeFileSync(join(refStagesDir, `${STAGE}.md`), `# ${STAGE}\n\nbody\n`);
+ const refConfig = { stages: { [STAGE]: { name: STAGE, model: 'default', returnsJson: true, variables: [] } } };
+ writeFileSync(join(rootDir, 'data.reference', 'prompts', 'stage-config.json'), JSON.stringify(refConfig, null, 2) + '\n');
+
+ installedStagesDir = join(rootDir, 'data', 'prompts', 'stages');
+ installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');
+ });
+
+ afterEach(() => {
+ rmSync(rootDir, { recursive: true, force: true });
+ });
+
+ it('seeds the prompt file + stage-config entry on a fresh install', async () => {
+ await migration.up({ rootDir });
+ expect(existsSync(join(installedStagesDir, `${STAGE}.md`))).toBe(true);
+ expect(readJson(installedConfigPath).stages[STAGE]).toBeTruthy();
+ });
+
+ it('merges into an existing stage-config without clobbering other stages', async () => {
+ mkdirSync(installedStagesDir, { recursive: true });
+ writeFileSync(installedConfigPath, JSON.stringify({ stages: { 'pipeline-prose': { name: 'Prose' } } }, null, 2) + '\n');
+ await migration.up({ rootDir });
+ const config = readJson(installedConfigPath);
+ expect(config.stages['pipeline-prose']).toBeTruthy();
+ expect(config.stages[STAGE]).toBeTruthy();
+ });
+
+ it('is idempotent and preserves a user-customized installed prompt', async () => {
+ mkdirSync(installedStagesDir, { recursive: true });
+ const customPath = join(installedStagesDir, `${STAGE}.md`);
+ writeFileSync(customPath, '# CUSTOM arc refine\n');
+ await migration.up({ rootDir });
+ expect(readFileSync(customPath, 'utf-8')).toContain('CUSTOM');
+ // Second run is a clean no-op.
+ await migration.up({ rootDir });
+ expect(readFileSync(customPath, 'utf-8')).toContain('CUSTOM');
+ expect(readJson(installedConfigPath).stages[STAGE]).toBeTruthy();
+ });
+});
diff --git a/server/lib/storyArc.js b/server/lib/storyArc.js
index b6125969a8..ab6f8576e2 100644
--- a/server/lib/storyArc.js
+++ b/server/lib/storyArc.js
@@ -235,7 +235,7 @@ function ensureSeasonId(raw) {
return `${SEASON_ID_PREFIX}${randomUUID()}`;
}
-function cleanThemes(raw) {
+export function cleanThemes(raw) {
if (!Array.isArray(raw)) return [];
const out = [];
for (const v of raw) {
diff --git a/server/services/pipeline/arcPlanner.js b/server/services/pipeline/arcPlanner.js
index 5354db4118..b765b7f23e 100644
--- a/server/services/pipeline/arcPlanner.js
+++ b/server/services/pipeline/arcPlanner.js
@@ -29,6 +29,7 @@ import { emitRecordUpdated, withReexportSuppressed } from '../sharing/recordEven
import { getSeason } from './seasons.js';
import {
sanitizeArc,
+ cleanThemes,
sanitizeSeasonList,
sanitizeSeason,
buildSeason,
@@ -983,8 +984,13 @@ export async function refineArc(seriesId, feedback, options = {}) {
const trimmed = typeof next === 'string' ? next.trim() : '';
return trimmed || current || '';
};
- const refinedThemes = Array.isArray(content.themes) && content.themes.length > 0
- ? content.themes
+ // Clean the candidate themes BEFORE deciding to keep them: an LLM array of
+ // only blanks/nulls (`[' ']`, `[null]`) is non-empty but sanitizes to [],
+ // which would wipe the existing themes. Fall back to current when the cleaned
+ // candidate is empty (preserve, per the absent-vs-empty rule).
+ const cleanedCandidateThemes = cleanThemes(content.themes);
+ const refinedThemes = cleanedCandidateThemes.length > 0
+ ? cleanedCandidateThemes
: (arc.themes || []);
const refinedArc = sanitizeArc({
logline: refinedStr(content.logline, arc.logline),
@@ -1001,9 +1007,7 @@ export async function refineArc(seriesId, feedback, options = {}) {
if (!refinedArc) {
throw makeErr('LLM returned an empty arc and there is none to preserve', ERR_VALIDATION);
}
- // Return the freshly-read series so the caller can persist without a second
- // getSeries round-trip (it needs series.seasons for commitSeasonsWithRemap).
- return { arc: refinedArc, changes: trimChanges(content.changes), rationale, runId, providerId, model, series };
+ return { arc: refinedArc, changes: trimChanges(content.changes), rationale, runId, providerId, model };
}
/**
diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.js
index 2660a215b8..66bdb6d7e6 100644
--- a/server/services/pipeline/arcPlanner.test.js
+++ b/server/services/pipeline/arcPlanner.test.js
@@ -1600,6 +1600,18 @@ describe('arcPlanner — refineArc', () => {
expect(out.arc.protagonistArc).toBe('keep arc');
});
+ it('preserves existing themes when the LLM returns a non-empty but all-blank themes array', async () => {
+ // `[' ', null]` is non-empty so a naive length check would accept it, then
+ // sanitizeArc cleans it to [] and wipes the user's themes. Must fall back.
+ const s = await setupSeries({ arc: { logline: 'L', summary: 'S', themes: ['betrayal', 'hope'] } });
+ stageRunnerSpy = vi.fn(async () => ({
+ content: { logline: 'L2', summary: 'S2', themes: [' ', null], changes: [], rationale: '' },
+ runId: 'r', providerId: 'p', model: 'm',
+ }));
+ const out = await planner.refineArc(s.id, 'tweak');
+ expect(out.arc.themes).toEqual(['betrayal', 'hope']);
+ });
+
it('throws when the arc is locked', async () => {
const s = await setupSeries({ arc: { logline: 'x', summary: 'y' }, locked: { arc: true } });
await expect(planner.refineArc(s.id, 'x')).rejects.toMatchObject({ code: 'PIPELINE_ARC_VALIDATION' });
diff --git a/server/services/storyBuilder.js b/server/services/storyBuilder.js
index ce49efdd69..754067c874 100644
--- a/server/services/storyBuilder.js
+++ b/server/services/storyBuilder.js
@@ -37,7 +37,7 @@ import {
createSeries, getSeries, updateSeries, setArcFieldLock,
} from './pipeline/series.js';
import {
- generateArcOverview, generateArcFromSource, generateReaderMap, refineReaderMap, refineArc, commitSeasonsWithRemap,
+ generateArcOverview, generateArcFromSource, generateReaderMap, refineReaderMap, refineArc, commitSeasonsWithRemap, mergeArcWithLocks,
collectIssueSourceText, generateSeasonEpisodes, commitEpisodesToIssues,
ERR_VALIDATION as ARC_ERR_VALIDATION,
} from './pipeline/arcPlanner.js';
@@ -672,14 +672,17 @@ export async function refineStep(id, stepId, { feedback, entryId, providerId, mo
if (stepId === 'plotArc') {
if (!session.seriesId) throw makeErr('No series linked', ERR_VALIDATION);
emit('Refining the plot arc…', 'generate');
- // refineArc returns the series it read, so we persist without a 2nd fetch.
- const { arc, changes, rationale, runId, series } = await refineArc(session.seriesId, feedback, { providerId: reqProviderId, model: reqModel });
+ const { arc, changes, rationale, runId } = await refineArc(session.seriesId, feedback, { providerId: reqProviderId, model: reqModel });
emit('Saving…', 'persist');
- // Persist through commitSeasonsWithRemap (passing the EXISTING seasons
- // unchanged) so per-field arc locks are honored, exactly like the plotArc
- // generate path — refine only rewrites the arc's narrative fields, never
- // the season breakdown.
- const { series: updated } = await commitSeasonsWithRemap(series, { arc, seasons: series.seasons || [] });
+ // Persist arc-ONLY (never the season breakdown), so we deliberately do NOT
+ // route through commitSeasonsWithRemap — passing a stale season snapshot as
+ // the "proposed" set there could mis-remap/orphan a season edited during the
+ // LLM call. Re-read the latest series, apply per-field arc locks via
+ // mergeArcWithLocks (the same guard commitSeasonsWithRemap uses), and write
+ // only `arc` — seasons are untouched.
+ const latest = await getSeries(session.seriesId);
+ const mergedArc = mergeArcWithLocks(latest.arc, arc, latest.locked?.arcFields);
+ const updated = await updateSeries(session.seriesId, { arc: mergedArc });
return { result: updated, changes, rationale, runId };
}
if (stepId === 'readerMap') {
diff --git a/server/services/storyBuilder.test.js b/server/services/storyBuilder.test.js
index bff5d87bd6..f522a47064 100644
--- a/server/services/storyBuilder.test.js
+++ b/server/services/storyBuilder.test.js
@@ -261,6 +261,25 @@ describe('storyBuilder — refine delegation', () => {
expect(out.rationale).toBe('y');
});
+ it('refineStep(plotArc) leaves the season breakdown untouched (arc-only persist)', async () => {
+ const s = await sb.createStorySession({ title: 'X' });
+ await seriesSvc.updateSeries(s.seriesId, {
+ arc: { logline: 'old', summary: 'old summary' },
+ seasons: [{ number: 1, title: 'Volume One', episodeCountTarget: 6 }],
+ });
+ const before = await seriesSvc.getSeries(s.seriesId);
+ stageRunnerSpy = vi.fn(async () => ({
+ content: { logline: 'refined', summary: 'refined summary', changes: [], rationale: '' },
+ runId: 'r', providerId: 'p', model: 'm',
+ }));
+ await sb.refineStep(s.id, 'plotArc', { feedback: 'sharpen' });
+ const after = await seriesSvc.getSeries(s.seriesId);
+ expect(after.arc.logline).toBe('refined');
+ // Seasons are byte-for-byte unchanged — refine never routes through the
+ // season remap, so no id churn or issue reassignment.
+ expect(after.seasons).toEqual(before.seasons);
+ });
+
it('refineStep(plotArc) refuses when the arc is locked', async () => {
const s = await sb.createStorySession({ title: 'X' });
await seriesSvc.updateSeries(s.seriesId, { arc: { logline: 'spine', summary: 'sum' } });