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

feat([story-builder-arc-refine-feedback]): add AI refine-with-feedback for the plot-arc step

[._.]/ Adam Eivy5f49cda97c7b
diff --git a/client/src/pages/StoryBuilder.jsx b/client/src/pages/StoryBuilder.jsx
index 5a57d9e829..9a3023eead 100644
--- a/client/src/pages/StoryBuilder.jsx
+++ b/client/src/pages/StoryBuilder.jsx
@@ -586,6 +586,9 @@ function StepPanel({ session, universe, series, issues, stepId, locked, onChange
{issuesHaveContent && (
<p className="text-xs text-gray-500">Started from drafted issues? Backfill extracts the arc from their scripts / prose.</p>
)}
+ {!locked && (arc.logline || arc.summary) && (
+ <RefineBox onRefine={(fb) => runRefine(fb)} busy={busy} running={isRunning('refine')} phase={phase} />
+ )}
</div>
);
}
diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.json
index 090e80c85d..c34f3d69cc 100644
--- a/data.reference/prompts/stage-config.json
+++ b/data.reference/prompts/stage-config.json
@@ -256,6 +256,13 @@
"returnsJson": true,
"variables": []
},
+ "story-builder-arc-refine": {
+ "name": "Story Builder — Plot Arc Refine",
+ "description": "Refine an existing plot arc's narrative fields (logline, summary, protagonist arc, themes) against free-text feedback, returning the full revised arc plus a changes list and rationale (the AI-feedback affordance for the Story Builder plot-arc step). Does not re-plan the season breakdown.",
+ "model": "default",
+ "returnsJson": true,
+ "variables": []
+ },
"pipeline-arc-overview": {
"name": "Pipeline — Series Arc Overview",
"description": "Plan the top-level multi-season story spine for a series from its bible: a series-level logline, summary, themes, protagonist arc, and a 2–5 season breakdown with per-season loglines, ending hooks, and episode-count targets. Runs at `heavy` tier — most expensive single call in the pipeline.",
diff --git a/data.reference/prompts/stages/story-builder-arc-refine.md b/data.reference/prompts/stages/story-builder-arc-refine.md
new file mode 100644
index 0000000000..36c31c2411
--- /dev/null
+++ b/data.reference/prompts/stages/story-builder-arc-refine.md
@@ -0,0 +1,42 @@
+# Story Builder — Plot Arc Refine
+
+You are refining an existing **plot arc** (the top-level narrative spine of a serialized story) in response to specific feedback. Apply the feedback surgically — keep what works, change only what the feedback calls for. Do NOT re-plan the season/volume breakdown; this pass refines only the arc's narrative fields (logline, summary, protagonist arc, themes).
+
+## Current plot arc
+
+- Logline: {{currentLogline}}
+- Summary: {{currentSummary}}
+- Protagonist arc: {{currentProtagonistArc}}
+- Themes: {{currentThemesCsv}}
+
+### Emotional backbone (Vonnegut shape)
+
+{{shapeGuidance}}
+
+## Story context (for grounding)
+
+{{#series.name}}- Series: {{series.name}}{{/series.name}}
+{{#series.premise}}- Premise: {{series.premise}}{{/series.premise}}
+
+## Feedback to apply
+
+{{#feedback}}{{feedback}}{{/feedback}}{{^feedback}}(no specific feedback — tighten the arc: sharpen the logline, make the protagonist's transformation specific and causal, and ensure the themes are dramatized by the summary rather than just named.){{/feedback}}
+
+## Task
+
+Return the FULL revised arc (not a diff). Preserve fields the feedback doesn't touch. Keep the same emotional shape unless the feedback explicitly asks to change it. Also return a short `changes` list (≤ 12 bullet strings) describing what you changed, and a one-sentence `rationale`.
+
+## Output
+
+Return ONLY a JSON object (no prose, no code fence):
+
+```json
+{
+ "logline": "string",
+ "summary": "string",
+ "protagonistArc": "string",
+ "themes": ["string"],
+ "changes": ["string"],
+ "rationale": "string"
+}
+```
diff --git a/server/services/pipeline/arcPlanner.js b/server/services/pipeline/arcPlanner.js
index ad98dd23fa..8000d5294d 100644
--- a/server/services/pipeline/arcPlanner.js
+++ b/server/services/pipeline/arcPlanner.js
@@ -942,6 +942,75 @@ export async function refineReaderMap(seriesId, feedback, options = {}) {
return { readerMap: safeReaderMap, changes, rationale, runId, providerId, model };
}
+/**
+ * Refine an existing plot arc's NARRATIVE fields (logline / summary /
+ * protagonist arc / themes) against free-text feedback — the AI-feedback
+ * affordance the arc step lacked (it only had full regenerate). Deliberately
+ * does NOT re-plan seasons or change the Vonnegut shape: the refine prompt
+ * authors only the narrative fields, and `shape`/`readerMap` are carried over
+ * from the current arc. Returns the merged arc plus `changes` + `rationale`.
+ *
+ * Honors the absent-vs-intentionally-empty rule: a field the LLM omits or
+ * returns empty falls back to the current value (refine PRESERVES; it must
+ * never null out an arc the user already has). The same `locked.arc` guard the
+ * arc-overview regenerator uses applies.
+ */
+export async function refineArc(seriesId, feedback, options = {}) {
+ const series = await getSeries(seriesId);
+ if (series.locked?.arc === true) {
+ throw makeErr('Arc is locked — unlock it on the Arc Canvas before refining', ERR_VALIDATION);
+ }
+ const arc = series.arc || {};
+ const { content, rationale, runId, providerId, model } = await runPromptRefineRaw({
+ templateName: 'story-builder-arc-refine',
+ variables: {
+ currentLogline: arc.logline || '',
+ currentSummary: arc.summary || '',
+ currentProtagonistArc: arc.protagonistArc || '',
+ currentThemesCsv: Array.isArray(arc.themes) ? arc.themes.join(', ') : '',
+ shapeGuidance: renderArcShapeGuidance(arc.shape) || SHAPE_GUIDANCE_NONE,
+ series: { name: series.name, premise: series.premise },
+ feedback: typeof feedback === 'string' ? feedback.trim().slice(0, 4000) : '',
+ },
+ options,
+ source: 'story-builder-arc-refine',
+ logTag: `Story Builder arc refine series=${seriesId.slice(0, 8)}`,
+ });
+ // Merge the refined narrative fields over the current arc, preserving any the
+ // LLM omitted (absent) or returned empty (a refine should never blank a field
+ // the user already had). `shape`, `readerMap`, and status pass through from
+ // the current arc — this pass is narrative-only. sanitizeArc trims/cleans the
+ // fields (incl. themes) on the way in, so pass raw values and only choose
+ // between the refined value and the current one here.
+ const refinedStr = (next, current) => {
+ const trimmed = typeof next === 'string' ? next.trim() : '';
+ return trimmed || current || '';
+ };
+ const refinedThemes = Array.isArray(content.themes) && content.themes.length > 0
+ ? content.themes
+ : (arc.themes || []);
+ const refinedArc = sanitizeArc({
+ logline: refinedStr(content.logline, arc.logline),
+ summary: refinedStr(content.summary, arc.summary),
+ protagonistArc: refinedStr(content.protagonistArc, arc.protagonistArc),
+ themes: refinedThemes,
+ shape: arc.shape ?? null,
+ readerMap: arc.readerMap ?? null,
+ status: 'draft',
+ });
+ // sanitizeArc returns null only when every identifying field is empty —
+ // impossible here unless the current arc was already empty AND the LLM
+ // returned nothing. Preserve the current arc in that degenerate case.
+ const safeArc = refinedArc || (arc.logline || arc.summary ? arc : null);
+ if (!safeArc) {
+ throw makeErr('LLM returned an empty arc 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 { arc: safeArc, changes, rationale, runId, providerId, model };
+}
+
/**
* Build the context for one season's episode breakdown. `priorSeasonsContext`
* gives the LLM granular per-episode continuity — without it the verifier and
diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.js
index eb5d0c645c..2660a215b8 100644
--- a/server/services/pipeline/arcPlanner.test.js
+++ b/server/services/pipeline/arcPlanner.test.js
@@ -1536,6 +1536,76 @@ describe('arcPlanner — refineReaderMap', () => {
});
});
+describe('arcPlanner — refineArc', () => {
+ beforeEach(() => {
+ fileStore.clear();
+ uuidCounter = 0;
+ stageRunnerSpy = undefined;
+ });
+
+ it('returns the revised arc narrative fields plus changes and rationale', async () => {
+ const s = await setupSeries({
+ arc: { logline: 'old logline', summary: 'old summary', protagonistArc: 'old arc', themes: ['loss'], shape: 'man-in-hole' },
+ });
+ stageRunnerSpy = vi.fn(async () => ({
+ content: {
+ logline: 'sharper logline',
+ summary: 'sharper summary',
+ protagonistArc: 'sharper protagonist arc',
+ themes: ['loss', 'redemption'],
+ changes: ['sharpened the logline'],
+ rationale: 'tightened the spine',
+ },
+ runId: 'r', providerId: 'p', model: 'm',
+ }));
+
+ const out = await planner.refineArc(s.id, 'make the logline sharper');
+ expect(stageRunnerSpy).toHaveBeenCalledWith('story-builder-arc-refine', expect.any(Object), expect.objectContaining({ returnsJson: true }));
+ expect(out.arc.logline).toBe('sharper logline');
+ expect(out.arc.summary).toBe('sharper summary');
+ expect(out.arc.themes).toEqual(['loss', 'redemption']);
+ // shape is narrative-only refine → carried over unchanged.
+ expect(out.arc.shape).toBe('man-in-hole');
+ expect(out.changes).toEqual(['sharpened the logline']);
+ expect(out.rationale).toBe('tightened the spine');
+ });
+
+ it('preserves the picked Vonnegut shape and any reader map (narrative-only refine)', async () => {
+ const s = await setupSeries({
+ arc: {
+ logline: 'L', summary: 'S', shape: 'man-in-hole',
+ readerMap: { hooks: [{ label: 'keep me' }], payoffs: [], beats: [], cliffhangers: [], status: 'draft' },
+ },
+ });
+ stageRunnerSpy = vi.fn(async () => ({
+ content: { logline: 'L2', summary: 'S2', changes: [], rationale: '' },
+ runId: 'r', providerId: 'p', model: 'm',
+ }));
+ const out = await planner.refineArc(s.id, 'tweak');
+ expect(out.arc.shape).toBe('man-in-hole');
+ expect(out.arc.readerMap?.hooks?.[0]?.label).toBe('keep me');
+ });
+
+ it('preserves a field the LLM returns empty (refine never blanks existing content)', async () => {
+ const s = await setupSeries({ arc: { logline: 'keep logline', summary: 'keep summary', protagonistArc: 'keep arc' } });
+ // LLM rewrites the summary but blanks logline + omits protagonistArc — both
+ // must fall back to the current values (absent-vs-intentionally-empty rule).
+ stageRunnerSpy = vi.fn(async () => ({
+ content: { logline: '', summary: 'new summary', changes: [], rationale: '' },
+ runId: 'r', providerId: 'p', model: 'm',
+ }));
+ const out = await planner.refineArc(s.id, 'tweak the summary');
+ expect(out.arc.logline).toBe('keep logline');
+ expect(out.arc.summary).toBe('new summary');
+ expect(out.arc.protagonistArc).toBe('keep arc');
+ });
+
+ 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' });
+ });
+});
+
describe('arcPlanner — manuscript completeness + derive-from-manuscript', () => {
beforeEach(() => {
fileStore.clear();
diff --git a/server/services/storyBuilder.js b/server/services/storyBuilder.js
index 87f5a0205f..0b6ffd72fb 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, commitSeasonsWithRemap,
+ generateArcOverview, generateArcFromSource, generateReaderMap, refineReaderMap, refineArc, commitSeasonsWithRemap,
collectIssueSourceText, generateSeasonEpisodes, commitEpisodesToIssues,
ERR_VALIDATION as ARC_ERR_VALIDATION,
} from './pipeline/arcPlanner.js';
@@ -669,6 +669,19 @@ export async function refineStep(id, stepId, { feedback, entryId, providerId, mo
});
return { result: updated, changes: refined.changes || [], rationale: refined.rationale || '' };
}
+ if (stepId === 'plotArc') {
+ if (!session.seriesId) throw makeErr('No series linked', ERR_VALIDATION);
+ emit('Refining the plot arc…', 'generate');
+ 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 = await getSeries(session.seriesId);
+ const { series: updated } = await commitSeasonsWithRemap(series, { arc, seasons: series.seasons || [] });
+ return { result: updated, changes, rationale, runId };
+ }
if (stepId === 'readerMap') {
if (!session.seriesId) throw makeErr('No series linked', ERR_VALIDATION);
emit('Refining the reader map…', 'generate');
diff --git a/server/services/storyBuilder.test.js b/server/services/storyBuilder.test.js
index e04bafa5e9..bff5d87bd6 100644
--- a/server/services/storyBuilder.test.js
+++ b/server/services/storyBuilder.test.js
@@ -242,6 +242,35 @@ describe('storyBuilder — generate delegation', () => {
});
});
+describe('storyBuilder — refine delegation', () => {
+ it('refineStep(plotArc) persists the refined arc narrative onto the series', async () => {
+ const s = await sb.createStorySession({ title: 'X' });
+ await seriesSvc.updateSeries(s.seriesId, { arc: { logline: 'old', summary: 'old summary', shape: 'man-in-hole' } });
+ stageRunnerSpy = vi.fn(async () => ({
+ content: { logline: 'refined logline', summary: 'refined summary', changes: ['x'], rationale: 'y' },
+ runId: 'r', providerId: 'p', model: 'm',
+ }));
+ const out = await sb.refineStep(s.id, 'plotArc', { feedback: 'sharpen it' });
+ expect(stageRunnerSpy).toHaveBeenCalledWith('story-builder-arc-refine', expect.any(Object), expect.objectContaining({ returnsJson: true }));
+ const series = await seriesSvc.getSeries(s.seriesId);
+ expect(series.arc.logline).toBe('refined logline');
+ expect(series.arc.summary).toBe('refined summary');
+ // narrative-only refine preserves the picked shape.
+ expect(series.arc.shape).toBe('man-in-hole');
+ expect(out.changes).toEqual(['x']);
+ expect(out.rationale).toBe('y');
+ });
+
+ 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' } });
+ await sb.lockStep(s.id, 'plotArc'); // sets series.locked.arc = true
+ stageRunnerSpy = vi.fn();
+ await expect(sb.refineStep(s.id, 'plotArc', { feedback: 'x' })).rejects.toMatchObject({ code: 'PIPELINE_ARC_VALIDATION' });
+ expect(stageRunnerSpy).not.toHaveBeenCalled();
+ });
+});
+
describe('generateStep backfill (fromDownstream)', () => {
// Record the stage + vars of the most recent staged-LLM call so a test can
// assert which prompt a backfill routed through.