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: pipeline arc planning with world-grounded volumes and auto-resolve

[._.]/ Adam Eivy27ef3c274c0c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index dd7d64b20d..85e43d19c6 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,8 +2,52 @@
## Added
+- **Pipeline Series — auto-resolve verification findings.** The verify panel
+ now has a *Resolve all* button at the top and a per-finding *Resolve* button
+ on each row. Each kicks off an LLM pass that rewrites the arc + volume
+ outlines (logline, summary, synopses, episode-count targets) to address the
+ selected finding(s) and persists the result. Per-issue scripts are never
+ touched. New stage prompt `pipeline-arc-resolve` and route
+ `POST /pipeline/series/:id/arc/resolve-issues`.
+
+- **Pipeline Series — recommended-structure hint.** The *Target issues /
+ episodes* field shows a live suggestion next to it ("3 volumes × 8
+ episodes", etc.) computed from comic-as-TV norms: 1 volume for ≤ 12, 2 for
+ 13–17, 3 for 18–32, 4 for 33–44, 5 beyond. The arc-overview LLM prompt now
+ receives the same recommendation so it stops slicing 12-issue runs into
+ three 4-issue seasons.
+
+- **Pipeline Series — linked World context flows into arc planning.** The
+ arc-overview, verify, resolve, and season-episode-breakdown prompts now
+ receive the linked World Builder world's full entity set (categories like
+ factions / characters / environments / artifacts + composite reference
+ sheets + influences). The LLM is instructed to ground every volume's
+ logline and synopsis in those entities by name rather than inventing
+ parallel ones, and the verify pass flags arc references that don't exist
+ in the world (or major world entities that go entirely unused).
+
+- **Pipeline Series — auto-flush bible state before LLM actions.** Clicking
+ *Regenerate arc*, *Verify arc*, *Resolve all*, or *Resolve* now first
+ pushes any pending local bible edits (issue count target, logline,
+ premise, etc.) to the server so the LLM runs against the on-screen state
+ rather than the last manually-saved snapshot.
+
## Changed
+- **Pipeline Series — combined comic/TV terminology.** Every series now ships
+ in both formats by default — graphic novel (issues → volumes) AND TV
+ (episodes → seasons). Dropped the *Target format* picker from the new-
+ series form and the bible sidebar; all labels read as `issues / episodes`
+ and `volumes / seasons` so a single record drives both pipelines. The
+ arc-overview / verify / resolve prompts were rewritten to author for both
+ formats simultaneously.
+
+- **Pipeline Series — flush-edge layout.** The series detail page now uses
+ the same edge-to-edge canvas as World Builder. The bible sidebar sits flush
+ against the main app sidebar (no Layout padding between them) and the
+ collapse rail is a plain hairline toggle instead of a floating rounded
+ button.
+
- **World Builder — inline Refine prompts.** Clicking *Refine prompts* now
expands a feedback textarea right under the header buttons instead of
opening a modal. The LLM picked in the page's own provider/model selectors
@@ -11,6 +55,12 @@
straight to the prompt fields below so you can see the changes in place. A
short rationale + change list appears below the textarea after each refine.
+- **World Builder — explicit-removal handling in Refine.** When the user
+ feedback names a specific variation or composite to remove, the LLM is now
+ told to omit it entirely (including composite sheets whose primary subject
+ is the removed entity, e.g. a "Faction A vs Faction B branding sheet") and
+ to scrub stray references from sibling unlocked composites' prompts.
+
## Fixed
## Removed
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index 2d28029047..cfb6b8f883 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -980,6 +980,7 @@ export default function Layout() {
location.pathname.startsWith('/media') ||
location.pathname.startsWith('/messages') ||
location.pathname.startsWith('/pipeline/issues/') ||
+ location.pathname.startsWith('/pipeline/series/') ||
location.pathname.startsWith('/post') ||
location.pathname === '/review' ||
location.pathname.startsWith('/settings') ||
diff --git a/client/src/components/pipeline/ArcCanvas.jsx b/client/src/components/pipeline/ArcCanvas.jsx
index 667270d170..77f928d445 100644
--- a/client/src/components/pipeline/ArcCanvas.jsx
+++ b/client/src/components/pipeline/ArcCanvas.jsx
@@ -36,6 +36,7 @@ import {
createPipelineIssue, deletePipelineIssue, updatePipelineIssue,
createPipelineSeason, updatePipelineSeason, deletePipelineSeason,
generatePipelineArcOverview, generatePipelineSeasonEpisodes, verifyPipelineArc,
+ resolvePipelineArcIssues,
listPipelineIssues, updatePipelineSeries,
} from '../../services/api';
@@ -52,7 +53,7 @@ const SEVERITY_COLORS = {
low: 'text-gray-400 border-gray-500/30 bg-gray-700/20',
};
-export default function ArcCanvas({ series, issues, onSeriesUpdate, onIssuesUpdate }) {
+export default function ArcCanvas({ series, issues, onSeriesUpdate, onIssuesUpdate, onFlushPending }) {
const seasons = series.seasons || [];
// Group issues by seasonId for the tree; ungrouped issues land under null.
const issuesBySeason = new Map();
@@ -68,7 +69,12 @@ export default function ArcCanvas({ series, issues, onSeriesUpdate, onIssuesUpda
return (
<div className="space-y-4">
- <ArcHeader series={series} onSeriesUpdate={onSeriesUpdate} />
+ <ArcHeader
+ series={series}
+ onSeriesUpdate={onSeriesUpdate}
+ onIssuesUpdate={onIssuesUpdate}
+ onFlushPending={onFlushPending}
+ />
{seasons.length > 0 ? (
<ul className="space-y-3">
@@ -101,17 +107,30 @@ export default function ArcCanvas({ series, issues, onSeriesUpdate, onIssuesUpda
// ---- Arc header (logline, themes, action buttons) ----
-function ArcHeader({ series, onSeriesUpdate }) {
+function ArcHeader({ series, onSeriesUpdate, onIssuesUpdate, onFlushPending }) {
const arc = series.arc;
- const [running, setRunning] = useState(null); // 'generate' | 'verify' | null
+ const [running, setRunning] = useState(null); // 'generate' | 'verify' | 'resolve' | null
const [verifyIssues, setVerifyIssues] = useState(null);
+ // Which finding indexes have an in-flight per-finding resolve. Lets the row
+ // show its own spinner without blocking the rest of the page.
+ const [resolvingIdx, setResolvingIdx] = useState(new Set());
+
+ // Persist any pending bible edits BEFORE the LLM call reads from the server.
+ // Without this, typing "32" into the issue count and clicking Regenerate
+ // would run against the previously-saved value.
+ const withFlush = async (fn) => {
+ if (onFlushPending) await onFlushPending();
+ return fn();
+ };
const runGenerate = async () => {
setRunning('generate');
- const result = await generatePipelineArcOverview(series.id, { commit: true }).catch((err) => {
- toast.error(err.message || 'Failed to generate arc');
- return null;
- });
+ const result = await withFlush(() =>
+ generatePipelineArcOverview(series.id, { commit: true }).catch((err) => {
+ toast.error(err.message || 'Failed to generate arc');
+ return null;
+ }),
+ );
setRunning(null);
if (!result) return;
onSeriesUpdate(result.series);
@@ -124,10 +143,12 @@ function ArcHeader({ series, onSeriesUpdate }) {
const runVerify = async () => {
setRunning('verify');
- const result = await verifyPipelineArc(series.id).catch((err) => {
- toast.error(err.message || 'Failed to verify arc');
- return null;
- });
+ const result = await withFlush(() =>
+ verifyPipelineArc(series.id).catch((err) => {
+ toast.error(err.message || 'Failed to verify arc');
+ return null;
+ }),
+ );
setRunning(null);
if (!result) return;
setVerifyIssues(result.issues || []);
@@ -138,6 +159,53 @@ function ArcHeader({ series, onSeriesUpdate }) {
}
};
+ // Auto-resolve. `findings` undefined = resolve all currently-displayed
+ // findings (server re-verifies first if findings comes through empty).
+ const runResolve = async (findingsSubset) => {
+ setRunning('resolve');
+ const result = await withFlush(() =>
+ resolvePipelineArcIssues(series.id, {
+ findings: findingsSubset,
+ }).catch((err) => {
+ toast.error(err.message || 'Auto-resolve failed');
+ return null;
+ }),
+ );
+ setRunning(null);
+ if (!result) return null;
+ if (result.series) onSeriesUpdate(result.series);
+ if (onIssuesUpdate) {
+ // Server doesn't touch issues during resolve, but season reassignments
+ // can shift counts — refresh so the UI tree stays in sync.
+ const refreshed = await listPipelineIssues(series.id).catch(() => null);
+ if (refreshed) onIssuesUpdate(refreshed);
+ }
+ if (result.applied) {
+ toast.success('Arc updated to resolve findings — re-verify when ready');
+ } else {
+ toast.success(result.notes || 'Nothing to resolve');
+ }
+ return result;
+ };
+
+ const resolveAll = async () => {
+ const result = await runResolve(verifyIssues || []);
+ if (result?.applied) setVerifyIssues(null);
+ };
+
+ const resolveOne = async (idx, finding) => {
+ setResolvingIdx((prev) => new Set(prev).add(idx));
+ const result = await runResolve([finding]);
+ setResolvingIdx((prev) => {
+ const next = new Set(prev);
+ next.delete(idx);
+ return next;
+ });
+ if (result?.applied) {
+ setVerifyIssues((prev) => (prev || []).filter((_, i) => i !== idx));
+ }
+ };
+
const generateBtnLabel = !arc ? 'Generate arc'
: armReplace ? 'Click again to replace'
: 'Regenerate arc';
@@ -178,12 +246,19 @@ function ArcHeader({ series, onSeriesUpdate }) {
<ArcContent series={series} onSeriesUpdate={onSeriesUpdate} />
) : (
<p className="text-xs text-gray-500 italic">
- No arc yet — describe the series in the bible, then click <em>Generate arc</em> to have an LLM propose a multi-season spine + season breakdown.
+ No arc yet — describe the series in the bible, then click <em>Generate arc</em> to have an LLM propose a multi-volume spine + volume breakdown.
</p>
)}
{verifyIssues && verifyIssues.length > 0 ? (
- <VerifyResults issues={verifyIssues} onDismiss={() => setVerifyIssues(null)} />
+ <VerifyResults
+ issues={verifyIssues}
+ onDismiss={() => setVerifyIssues(null)}
+ onResolveAll={resolveAll}
+ onResolveOne={resolveOne}
+ resolvingAll={running === 'resolve' && resolvingIdx.size === 0}
+ resolvingIdx={resolvingIdx}
+ />
) : null}
</section>
);
@@ -232,7 +307,7 @@ function ArcContent({ series, onSeriesUpdate }) {
<textarea
value={draft.summary || ''}
onChange={(e) => setDraft({ ...draft, summary: e.target.value })}
- placeholder="Multi-season summary (~500 words)"
+ placeholder="Multi-volume / multi-season summary (~500 words)"
rows={6}
className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"
maxLength={8000}
@@ -240,7 +315,7 @@ function ArcContent({ series, onSeriesUpdate }) {
<textarea
value={draft.protagonistArc || ''}
onChange={(e) => setDraft({ ...draft, protagonistArc: e.target.value })}
- placeholder="Protagonist arc across all seasons"
+ placeholder="Protagonist arc across all volumes / seasons"
rows={3}
className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"
maxLength={4000}
@@ -309,31 +384,62 @@ function ArcContent({ series, onSeriesUpdate }) {
);
}
-function VerifyResults({ issues, onDismiss }) {
+function VerifyResults({ issues, onDismiss, onResolveAll, onResolveOne, resolvingAll, resolvingIdx }) {
+ const busy = resolvingAll || (resolvingIdx && resolvingIdx.size > 0);
return (
<div className="border border-port-border rounded p-3 bg-port-bg/50 space-y-2">
- <div className="flex items-center justify-between">
+ <div className="flex items-center justify-between gap-2 flex-wrap">
<h3 className="text-xs uppercase tracking-wider text-gray-500">Verification — {issues.length} issue{issues.length === 1 ? '' : 's'}</h3>
- <button
- type="button"
- onClick={onDismiss}
- className="text-xs text-gray-400 hover:text-white"
- >
- Dismiss
- </button>
+ <div className="flex items-center gap-2">
+ {onResolveAll ? (
+ <button
+ type="button"
+ onClick={onResolveAll}
+ disabled={busy}
+ className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium border bg-port-accent/10 text-port-accent border-port-accent/40 hover:bg-port-accent/20 disabled:opacity-40"
+ title="Run an LLM pass that rewrites the arc to resolve every finding"
+ >
+ {resolvingAll ? <Loader2 size={12} className="animate-spin" /> : <Wand2 size={12} />}
+ Resolve all
+ </button>
+ ) : null}
+ <button
+ type="button"
+ onClick={onDismiss}
+ disabled={busy}
+ className="text-xs text-gray-400 hover:text-white disabled:opacity-40"
+ >
+ Dismiss
+ </button>
+ </div>
</div>
<ul className="space-y-2">
- {issues.map((iss, i) => (
- <li key={i} className={`text-xs p-2 rounded border ${SEVERITY_COLORS[iss.severity] || SEVERITY_COLORS.medium}`}>
- <div className="flex items-center gap-2 mb-1">
- <AlertCircle size={12} />
- <span className="uppercase tracking-wider font-semibold">{iss.severity}</span>
- {iss.location ? <span className="text-gray-500">— {iss.location}</span> : null}
- </div>
- <p className="text-gray-200">{iss.problem}</p>
- {iss.suggestion ? <p className="mt-1 text-gray-400 italic">→ {iss.suggestion}</p> : null}
- </li>
- ))}
+ {issues.map((iss, i) => {
+ const resolvingThis = resolvingIdx && resolvingIdx.has(i);
+ return (
+ <li key={i} className={`text-xs p-2 rounded border ${SEVERITY_COLORS[iss.severity] || SEVERITY_COLORS.medium}`}>
+ <div className="flex items-center gap-2 mb-1">
+ <AlertCircle size={12} />
+ <span className="uppercase tracking-wider font-semibold">{iss.severity}</span>
+ {iss.location ? <span className="text-gray-500">— {iss.location}</span> : null}
+ {onResolveOne ? (
+ <button
+ type="button"
+ onClick={() => onResolveOne(i, iss)}
+ disabled={busy}
+ className="ml-auto inline-flex items-center gap-1 px-2 py-0.5 rounded text-[10px] uppercase tracking-wider border border-port-border bg-port-bg text-gray-300 hover:text-white hover:border-port-accent/40 disabled:opacity-40"
+ title="Run an LLM pass that rewrites the arc to resolve only this finding"
+ >
+ {resolvingThis ? <Loader2 size={10} className="animate-spin" /> : <Wand2 size={10} />}
+ Resolve
+ </button>
+ ) : null}
+ </div>
+ <p className="text-gray-200">{iss.problem}</p>
+ {iss.suggestion ? <p className="mt-1 text-gray-400 italic">→ {iss.suggestion}</p> : null}
+ </li>
+ );
+ })}
</ul>
</div>
);
@@ -348,21 +454,22 @@ function SeasonRow({ series, season, seasons, issues, onSeriesUpdate, onIssuesUp
const runGenerateEpisodes = async () => {
if (issues.length > 0) {
- toast.error('Season already has episodes — clear them first or use the per-episode regenerate flow');
+ toast.error('Volume already has issues / episodes — clear them first or use the per-issue regenerate flow');
return;
}
setGeneratingEpisodes(true);
const result = await generatePipelineSeasonEpisodes(series.id, season.id, { commit: true })
.catch((err) => {
- toast.error(err.message || 'Failed to generate episodes');
+ toast.error(err.message || 'Failed to generate issues / episodes');
return null;
});
setGeneratingEpisodes(false);
if (!result) return;
- // Refresh the issues list so the new ones appear under this season.
+ // Refresh the issues list so the new ones land under this volume.
const refreshed = await listPipelineIssues(series.id).catch(() => null);
if (refreshed) onIssuesUpdate(refreshed);
- toast.success(`Generated ${result.createdIssues?.length || 0} episode${result.createdIssues?.length === 1 ? '' : 's'}`);
+ const n = result.createdIssues?.length || 0;
+ toast.success(`Generated ${n} issue${n === 1 ? '' : 's'} / episode${n === 1 ? '' : 's'}`);
};
const runDeleteSeason = async () => {
@@ -375,9 +482,10 @@ function SeasonRow({ series, season, seasons, issues, onSeriesUpdate, onIssuesUp
const refreshed = await listPipelineIssues(series.id).catch(() => null);
if (refreshed) onIssuesUpdate(refreshed);
if (result.reassignedIssueCount > 0) {
- toast.success(`Season deleted; ${result.reassignedIssueCount} episode${result.reassignedIssueCount === 1 ? '' : 's'} un-grouped`);
+ const n = result.reassignedIssueCount;
+ toast.success(`Volume deleted; ${n} issue${n === 1 ? '' : 's'} / episode${n === 1 ? '' : 's'} un-grouped`);
} else {
- toast.success('Season deleted');
+ toast.success('Volume / season deleted');
}
};
const [armDelete, deleteSeason] = useArmedAction(runDeleteSeason);
@@ -389,14 +497,14 @@ function SeasonRow({ series, season, seasons, issues, onSeriesUpdate, onIssuesUp
type="button"
onClick={() => setCollapsed(!collapsed)}
className="text-gray-500 hover:text-white p-0.5"
- aria-label={collapsed ? 'Expand season' : 'Collapse season'}
+ aria-label={collapsed ? 'Expand volume / season' : 'Collapse volume / season'}
>
{collapsed ? <ChevronRight size={16} /> : <ChevronDown size={16} />}
</button>
- <span className="text-xs text-gray-500 font-mono">S{season.number}</span>
+ <span className="text-xs text-gray-500 font-mono" title="Volume / Season">V{season.number}</span>
<span className="text-sm text-white font-medium truncate">{season.title || '(untitled)'}</span>
- <span className="text-[10px] uppercase tracking-wider text-gray-500">
- {issues.length} / {season.episodeCountTarget || '?'} episodes
+ <span className="text-[10px] uppercase tracking-wider text-gray-500" title="Issues / Episodes">
+ {issues.length} / {season.episodeCountTarget || '?'} issues
</span>
<button
type="button"
@@ -409,8 +517,8 @@ function SeasonRow({ series, season, seasons, issues, onSeriesUpdate, onIssuesUp
type="button"
onClick={deleteSeason}
className={`p-1.5 ${armDelete ? 'text-port-error' : 'text-gray-500 hover:text-port-error'}`}
- aria-label={armDelete ? `Confirm delete season ${season.title}` : `Delete season ${season.title}`}
- title={armDelete ? 'Click again to confirm' : 'Delete season'}
+ aria-label={armDelete ? `Confirm delete volume / season ${season.title}` : `Delete volume / season ${season.title}`}
+ title={armDelete ? 'Click again to confirm' : 'Delete volume / season'}
>
<Trash2 size={12} />
</button>
@@ -481,7 +589,7 @@ function SeasonEditor({ series, season, seasons, onSeriesUpdate }) {
...series,
seasons: seasons.map((s) => s.id === season.id ? updated : s).sort((a, b) => (a.number || 0) - (b.number || 0)),
});
- toast.success('Season saved');
+ toast.success('Volume / season saved');
};
return (
@@ -531,7 +639,8 @@ function SeasonEditor({ series, season, seasons, onSeriesUpdate }) {
type="number"
value={draft.episodeCountTarget || 0}
onChange={(e) => setDraft({ ...draft, episodeCountTarget: parseInt(e.target.value, 10) || 0 })}
- placeholder="Episode target"
+ placeholder="Issue / episode target"
+ title="Issue / episode count target for this volume / season"
className="px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"
min={0}
/>
@@ -585,7 +694,7 @@ function SeasonActions({ series, season, hasEpisodes, generatingEpisodes, onGene
if (refreshed) onIssuesUpdate(refreshed);
setNewTitle('');
setAdding(false);
- toast.success(`Episode "${created.title}" added`);
+ toast.success(`Issue / Episode "${created.title}" added`);
};
return (
@@ -595,7 +704,7 @@ function SeasonActions({ series, season, hasEpisodes, generatingEpisodes, onGene
<input
value={newTitle}
onChange={(e) => setNewTitle(e.target.value)}
- placeholder="Episode title…"
+ placeholder="Issue / Episode title…"
className="flex-1 px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"
autoFocus
maxLength={300}
@@ -622,7 +731,7 @@ function SeasonActions({ series, season, hasEpisodes, generatingEpisodes, onGene
onClick={() => setAdding(true)}
className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs text-gray-300 hover:text-white border border-port-border bg-port-bg"
>
- <Plus size={12} /> Add episode
+ <Plus size={12} /> Add issue / episode
</button>
<button
type="button"
@@ -630,15 +739,15 @@ function SeasonActions({ series, season, hasEpisodes, generatingEpisodes, onGene
disabled={generatingEpisodes || hasEpisodes || !seasonHasContext}
title={
hasEpisodes
- ? 'Season already has episodes'
+ ? 'Volume already has issues / episodes'
: !seasonHasContext
- ? 'Add a season logline or synopsis first'
- : 'Have an LLM plan the per-episode breakdown'
+ ? 'Add a volume logline or synopsis first'
+ : 'Have an LLM plan the per-issue / per-episode breakdown'
}
className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs text-port-accent hover:text-white border border-port-border bg-port-bg hover:border-port-accent/40 disabled:opacity-40 disabled:hover:text-port-accent"
>
{generatingEpisodes ? <Loader2 size={12} className="animate-spin" /> : <Wand2 size={12} />}
- Generate episodes (LLM)
+ Generate issues / episodes (LLM)
</button>
</>
)}
@@ -702,7 +811,7 @@ function IssueRow({ issue, seasons, onIssuesUpdate }) {
>
<option value="">— ungrouped —</option>
{seasons.map((s) => (
- <option key={s.id} value={s.id}>S{s.number}: {s.title}</option>
+ <option key={s.id} value={s.id}>V{s.number}: {s.title}</option>
))}
</select>
<button
@@ -710,7 +819,7 @@ function IssueRow({ issue, seasons, onIssuesUpdate }) {
onClick={handleDelete}
className={`p-1 ${armDelete ? 'text-port-error opacity-100' : 'text-gray-500 hover:text-port-error opacity-0 group-hover:opacity-100 focus:opacity-100'}`}
aria-label={armDelete ? `Confirm delete ${issue.title}` : `Delete ${issue.title}`}
- title={armDelete ? 'Click again to confirm' : 'Delete episode'}
+ title={armDelete ? 'Click again to confirm' : 'Delete issue / episode'}
>
<Trash2 size={12} />
</button>
@@ -724,7 +833,7 @@ function UngroupedIssues({ issues, seasons, onIssuesUpdate }) {
<div className="flex items-center gap-2 p-3 border-b border-port-border">
<ChevronsUpDown size={16} className="text-gray-500" />
<h3 className="text-xs uppercase tracking-wider text-gray-500">
- Un-grouped episodes ({issues.length})
+ Un-grouped issues / episodes ({issues.length})
</h3>
</div>
<ul className="px-3 py-2 space-y-1.5">
@@ -752,7 +861,7 @@ function AddSeasonRow({ series, onSeriesUpdate }) {
if (!t) return;
setSaving(true);
const created = await createPipelineSeason(series.id, { title: t }).catch((err) => {
- toast.error(err.message || 'Failed to create season');
+ toast.error(err.message || 'Failed to create volume / season');
return null;
});
setSaving(false);
@@ -763,7 +872,7 @@ function AddSeasonRow({ series, onSeriesUpdate }) {
});
setTitle('');
setAdding(false);
- toast.success(`Season ${created.number}: ${created.title} added`);
+ toast.success(`Volume / Season ${created.number}: ${created.title} added`);
};
if (!adding) {
@@ -773,7 +882,7 @@ function AddSeasonRow({ series, onSeriesUpdate }) {
onClick={() => setAdding(true)}
className="inline-flex items-center gap-1 px-3 py-2 rounded border border-dashed border-port-border bg-port-bg text-sm text-gray-400 hover:text-white hover:border-port-accent/40"
>
- <Plus size={14} /> Add season
+ <Plus size={14} /> Add volume / season
</button>
);
}
@@ -782,7 +891,7 @@ function AddSeasonRow({ series, onSeriesUpdate }) {
<input
value={title}
onChange={(e) => setTitle(e.target.value)}
- placeholder="Season title…"
+ placeholder="Volume / Season title…"
className="w-72 px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"
autoFocus
maxLength={200}
@@ -793,7 +902,7 @@ function AddSeasonRow({ series, onSeriesUpdate }) {
className="inline-flex items-center gap-1 px-3 py-2 rounded bg-port-accent text-white text-sm font-medium disabled:opacity-40"
>
{saving ? <Loader2 size={14} className="animate-spin" /> : <Plus size={14} />}
- Add season
+ Add volume / season
</button>
<button
type="button"
diff --git a/client/src/lib/seasonStructure.js b/client/src/lib/seasonStructure.js
new file mode 100644
index 0000000000..34f6568dfe
--- /dev/null
+++ b/client/src/lib/seasonStructure.js
@@ -0,0 +1,44 @@
+/**
+ * Mirror of server/lib/seasonStructure.js — kept here so the client-side
+ * issue-count hint can render without round-tripping through the API.
+ *
+ * 6–10 issues per volume/season is the comic-as-TV sweet spot. Single volume
+ * up to 12; 3-volume arc lands roughly at 18–30. The "3 × 8 = 24" point is
+ * the canonical "3-season arc" target.
+ *
+ * Keep this in sync with the server file — there's no shared bundle, but
+ * the function bodies are tiny and tested on the server side.
+ */
+
+function pickSeasonCount(total) {
+ if (total <= 12) return 1;
+ if (total <= 17) return 2;
+ if (total <= 32) return 3;
+ if (total <= 44) return 4;
+ return 5;
+}
+
+export function recommendStructure(total) {
+ const n = Math.floor(Number(total) || 0);
+ if (n <= 0) return null;
+ const seasons = pickSeasonCount(n);
+ const base = Math.floor(n / seasons);
+ const remainder = n % seasons;
+ const perSeason = Array.from(
+ { length: seasons },
+ (_, i) => base + (i < remainder ? 1 : 0),
+ );
+ return { seasons, perSeason };
+}
+
+export function describeStructure(structure) {
+ if (!structure) return '';
+ const { seasons, perSeason } = structure;
+ const allSame = perSeason.every((n) => n === perSeason[0]);
+ if (allSame) {
+ return seasons === 1
+ ? `1 volume × ${perSeason[0]} episodes`
+ : `${seasons} volumes × ${perSeason[0]} episodes`;
+ }
+ return `${seasons} volumes × ~${Math.round(perSeason.reduce((a, b) => a + b, 0) / seasons)} (${perSeason.join(', ')})`;
+}
diff --git a/client/src/pages/Pipeline.jsx b/client/src/pages/Pipeline.jsx
index db35d9e468..547ad30e98 100644
--- a/client/src/pages/Pipeline.jsx
+++ b/client/src/pages/Pipeline.jsx
@@ -15,7 +15,6 @@ import {
listPipelineSeries,
createPipelineSeries,
deletePipelineSeries,
- PIPELINE_TARGET_FORMATS,
listWorlds,
WORLD_LOGLINE_MAX,
WORLD_PREMISE_MAX,
@@ -28,7 +27,6 @@ const emptyForm = () => ({
logline: '',
premise: '',
styleNotes: '',
- targetFormat: 'comic+tv',
});
export default function Pipeline() {
@@ -92,7 +90,6 @@ export default function Pipeline() {
premise: form.premise.trim(),
styleNotes: form.styleNotes.trim(),
worldId: form.worldId || undefined,
- targetFormat: form.targetFormat,
}).catch((err) => {
toast.error(err.message || 'Failed to create series');
return null;
@@ -233,21 +230,6 @@ export default function Pipeline() {
/>
</div>
</div>
- <div>
- <label htmlFor="series-format" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">
- Target format
- </label>
- <select
- id="series-format"
- value={form.targetFormat}
- onChange={(e) => setForm((f) => ({ ...f, targetFormat: e.target.value }))}
- className="px-3 py-2 bg-port-bg border border-port-border rounded text-white"
- >
- {PIPELINE_TARGET_FORMATS.map((tf) => (
- <option key={tf} value={tf}>{tf}</option>
- ))}
- </select>
- </div>
<div className="flex gap-2">
<button
type="submit"
@@ -283,9 +265,11 @@ export default function Pipeline() {
) : (
<div className="text-xs text-gray-600 italic">No logline yet</div>
)}
- <div className="text-xs text-gray-600 mt-1">
- {s.targetFormat} {s.issueCountTarget ? `• target ${s.issueCountTarget} issues` : ''}
- </div>
+ {s.issueCountTarget ? (
+ <div className="text-xs text-gray-600 mt-1">
+ Target {s.issueCountTarget} issues / episodes
+ </div>
+ ) : null}
</Link>
<button
type="button"
diff --git a/client/src/pages/PipelineSeries.jsx b/client/src/pages/PipelineSeries.jsx
index fb406b8fac..c4bf5d3439 100644
--- a/client/src/pages/PipelineSeries.jsx
+++ b/client/src/pages/PipelineSeries.jsx
@@ -10,7 +10,7 @@
* Mobile (< lg): single column, sidebar reflows above canvas.
*/
-import { useEffect, useState } from 'react';
+import { useEffect, useRef, useState } from 'react';
import { Link, useParams, useNavigate } from 'react-router-dom';
import {
ArrowLeft, Plus, Save, Trash2, Loader2, Workflow as WorkflowIcon, Globe, NotebookPen,
@@ -22,8 +22,8 @@ import {
getPipelineSeries, updatePipelineSeries,
listPipelineIssues,
listWorlds,
- PIPELINE_TARGET_FORMATS,
} from '../services/api';
+import { recommendStructure, describeStructure } from '../lib/seasonStructure';
const PIPELINE_SIDEBAR_KEY = 'portos-pipeline-series-sidebar-collapsed';
@@ -69,29 +69,57 @@ export default function PipelineSeries() {
});
};
+ // Track the last server-persisted snapshot so `flushPending` knows whether
+ // the local draft has diverged. Ref instead of state — we don't want
+ // re-renders, just up-to-date comparison data for the async LLM hooks below.
+ const lastSavedRef = useRef(null);
+ useEffect(() => { if (series && !lastSavedRef.current) lastSavedRef.current = series; }, [series]);
+
const patchSeries = (patch) => setSeries((prev) => ({ ...prev, ...patch }));
- const handleSave = async () => {
- if (!series) return;
- setSaving(true);
+ // Wrapped setter that ArcCanvas (and other LLM-flow children) use when the
+ // server has just confirmed a save. Keeps the dirty-check ref aligned so a
+ // subsequent flushPending() doesn't re-PATCH the same state.
+ const updateSeriesFromServer = (next) => {
+ setSeries(next);
+ lastSavedRef.current = next;
+ };
+
+ // If local bible fields diverged from the last server snapshot, PATCH so
+ // generate / verify / resolve work against the on-screen state. Returns
+ // `true` if a save occurred so the caller can decide whether to surface a
+ // confirmation toast.
+ const flushPending = async () => {
+ if (!series) return false;
+ const saved = lastSavedRef.current || series;
+ const fields = ['name', 'logline', 'premise', 'styleNotes', 'issueCountTarget', 'worldId'];
+ const dirty = fields.some((k) => (series[k] ?? '') !== (saved[k] ?? ''))
+ || JSON.stringify(series.characters || []) !== JSON.stringify(saved.characters || []);
+ if (!dirty) return false;
const updated = await updatePipelineSeries(series.id, {
name: series.name,
logline: series.logline,
premise: series.premise,
worldId: series.worldId || null,
styleNotes: series.styleNotes,
- targetFormat: series.targetFormat,
issueCountTarget: series.issueCountTarget,
characters: series.characters,
}).catch((err) => {
- toast.error(err.message || 'Save failed');
+ toast.error(`Pre-flush save failed: ${err.message}`);
return null;
});
+ if (!updated) return false;
+ setSeries(updated);
+ lastSavedRef.current = updated;
+ return true;
+ };
+
+ const handleSave = async () => {
+ if (!series) return;
+ setSaving(true);
+ const didSave = await flushPending();
setSaving(false);
- if (updated) {
- setSeries(updated);
- toast.success('Series saved');
- }
+ if (didSave) toast.success('Series saved');
};
const handleAddCharacter = () => {
@@ -126,55 +154,32 @@ export default function PipelineSeries() {
if (loading) return <div className="p-6 text-gray-500 text-sm">Loading series…</div>;
if (!series) return null;
- // Tailwind doesn't accept arbitrary classes via interpolation, so the grid
- // template flips between collapsed-rail (48px) and expanded (360px) via two
- // explicit class strings. `minmax(0,1fr)` is required on the canvas column
- // so long titles in cards don't push the layout horizontally.
- const gridCls = sidebarCollapsed
- ? 'grid grid-cols-1 lg:grid-cols-[48px_minmax(0,1fr)] gap-4 lg:gap-6'
- : 'grid grid-cols-1 lg:grid-cols-[360px_minmax(0,1fr)] gap-4 lg:gap-6';
+ // Mobile = flex column (grid template ignored); lg+ = grid where the inline
+ // `gridTemplateColumns` swap between collapsed/expanded widths takes effect.
+ // Mirrors the WorldBuilder full-bleed layout so the bible rail sits flush
+ // against the main app sidebar instead of floating inside Layout padding.
+ const desktopGridCols = sidebarCollapsed ? '32px minmax(0, 1fr)' : '360px minmax(0, 1fr)';
return (
- <div className="space-y-4">
- <div className="flex items-center gap-3 flex-wrap">
- <Link to="/pipeline" className="inline-flex items-center gap-1 text-sm text-gray-400 hover:text-white">
- <ArrowLeft size={14} /> All Series
- </Link>
- <WorkflowIcon className="w-5 h-5 text-port-accent ml-2" />
- <h1 className="text-xl font-bold text-white truncate">{series.name || 'Untitled series'}</h1>
- {series.writersRoomWorkId ? (
- <Link
- to={`/writers-room/works/${encodeURIComponent(series.writersRoomWorkId)}`}
- className="ml-2 inline-flex items-center gap-1 px-2 py-1 rounded text-xs text-gray-400 hover:text-white border border-port-border bg-port-card"
- title="Open the Writers Room draft this series was promoted from"
- >
- <NotebookPen size={12} /> Writers Room
- </Link>
- ) : null}
- <button
- type="button"
- onClick={handleSave}
- disabled={saving}
- className="ml-auto inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-accent text-white text-sm font-medium disabled:opacity-50"
- >
- {saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}
- Save series
- </button>
- </div>
-
- <div className={gridCls}>
- <aside className="lg:sticky lg:top-4 lg:self-start lg:max-h-[calc(100vh-2rem)] lg:overflow-y-auto">
- {sidebarCollapsed ? (
+ <div className="flex flex-col h-full">
+ <div
+ className="flex-1 flex flex-col lg:grid min-h-0"
+ style={{ gridTemplateColumns: desktopGridCols }}
+ >
+ {sidebarCollapsed ? (
+ <aside className="hidden lg:flex border-r border-port-border bg-port-card/40 items-start justify-center pt-3">
<button
type="button"
onClick={toggleSidebar}
- className="hidden lg:flex w-12 h-12 items-center justify-center rounded-lg border border-port-border bg-port-card text-gray-400 hover:text-white hover:border-port-accent/40"
+ className="p-1.5 text-gray-500 hover:text-white"
title="Show series bible"
aria-label="Expand series bible sidebar"
>
- <PanelLeftOpen size={16} />
+ <PanelLeftOpen size={14} />
</button>
- ) : (
+ </aside>
+ ) : (
+ <aside className="border-b lg:border-b-0 lg:border-r border-port-border bg-port-card/40 lg:overflow-y-auto">
<BibleSidebar
series={series}
worlds={worlds}
@@ -184,17 +189,44 @@ export default function PipelineSeries() {
onRemoveCharacter={handleRemoveCharacter}
onCollapse={toggleSidebar}
/>
- )}
- </aside>
+ </aside>
+ )}
+
+ <section className="flex flex-col gap-4 p-4 min-h-0 lg:overflow-y-auto">
+ <header className="flex items-center gap-3 flex-wrap">
+ <Link to="/pipeline" className="inline-flex items-center gap-1 text-sm text-gray-400 hover:text-white">
+ <ArrowLeft size={14} /> All Series
+ </Link>
+ <WorkflowIcon className="w-5 h-5 text-port-accent ml-2" />
+ <h1 className="text-xl font-bold text-white truncate">{series.name || 'Untitled series'}</h1>
+ {series.writersRoomWorkId ? (
+ <Link
+ to={`/writers-room/works/${encodeURIComponent(series.writersRoomWorkId)}`}
+ className="ml-2 inline-flex items-center gap-1 px-2 py-1 rounded text-xs text-gray-400 hover:text-white border border-port-border bg-port-card"
+ title="Open the Writers Room draft this series was promoted from"
+ >
+ <NotebookPen size={12} /> Writers Room
+ </Link>
+ ) : null}
+ <button
+ type="button"
+ onClick={handleSave}
+ disabled={saving}
+ className="ml-auto inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-accent text-white text-sm font-medium disabled:opacity-50"
+ >
+ {saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}
+ Save series
+ </button>
+ </header>
- <main className="min-w-0">
<ArcCanvas
series={series}
issues={issues}
- onSeriesUpdate={setSeries}
+ onSeriesUpdate={updateSeriesFromServer}
onIssuesUpdate={handleIssuesUpdate}
+ onFlushPending={flushPending}
/>
- </main>
+ </section>
</div>
</div>
);
@@ -202,7 +234,7 @@ export default function PipelineSeries() {
function BibleSidebar({ series, worlds, patchSeries, onAddCharacter, onUpdateCharacter, onRemoveCharacter, onCollapse }) {
return (
- <section className="p-4 bg-port-card border border-port-border rounded-lg space-y-4">
+ <section className="px-3 py-3 space-y-4">
<div className="flex items-center justify-between">
<h2 className="text-xs uppercase tracking-wider text-gray-500">Bible</h2>
<button
@@ -224,15 +256,6 @@ function BibleSidebar({ series, worlds, patchSeries, onAddCharacter, onUpdateCha
maxLength={200}
/>
</Field>
- <Field label="Target format">
- <select
- value={series.targetFormat || 'comic+tv'}
- onChange={(e) => patchSeries({ targetFormat: e.target.value })}
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
- >
- {PIPELINE_TARGET_FORMATS.map((tf) => <option key={tf} value={tf}>{tf}</option>)}
- </select>
- </Field>
<Field label="Logline">
<input
value={series.logline || ''}
@@ -242,15 +265,18 @@ function BibleSidebar({ series, worlds, patchSeries, onAddCharacter, onUpdateCha
maxLength={500}
/>
</Field>
- <Field label="Target issue count">
- <input
- type="number"
- min={0}
- max={999}
- value={series.issueCountTarget || 0}
- onChange={(e) => patchSeries({ issueCountTarget: parseInt(e.target.value, 10) || 0 })}
- className="w-32 px-3 py-2 bg-port-bg border border-port-border rounded text-white"
- />
+ <Field label="Target issues / episodes">
+ <div className="flex items-center gap-3 flex-wrap">
+ <input
+ type="number"
+ min={0}
+ max={999}
+ value={series.issueCountTarget || 0}
+ onChange={(e) => patchSeries({ issueCountTarget: parseInt(e.target.value, 10) || 0 })}
+ className="w-32 px-3 py-2 bg-port-bg border border-port-border rounded text-white"
+ />
+ <StructureHint total={series.issueCountTarget || 0} />
+ </div>
</Field>
<Field label="Premise (the bible — fed into every stage's prompt context)">
@@ -377,3 +403,19 @@ function Field({ label, children }) {
</label>
);
}
+
+function StructureHint({ total }) {
+ const structure = recommendStructure(total);
+ if (!structure) {
+ return (
+ <span className="text-xs text-gray-500 italic">
+ Enter total issues — we'll suggest a volume/season split (norm: 6–10 per volume).
+ </span>
+ );
+ }
+ return (
+ <span className="text-xs text-gray-400">
+ Suggested: <span className="text-port-accent">{describeStructure(structure)}</span>
+ </span>
+ );
+}
diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.js
index 37ba759eaa..4ca444eeff 100644
--- a/client/src/services/apiPipeline.js
+++ b/client/src/services/apiPipeline.js
@@ -191,6 +191,16 @@ export const verifyPipelineArc = (seriesId, { providerOverride, modelOverride }
body: JSON.stringify({ providerOverride, modelOverride }),
});
+// Auto-resolve verification findings — server runs an LLM pass that rewrites
+// the arc + volume/season outlines to address every finding, then persists.
+// Pass `findings: [...]` to resolve only that subset; omit to re-verify and
+// resolve everything. Returns { series, applied, notes, findings, runId, ... }.
+export const resolvePipelineArcIssues = (seriesId, { findings, providerOverride, modelOverride } = {}) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/arc/resolve-issues`, {
+ method: 'POST',
+ body: JSON.stringify({ findings, providerOverride, modelOverride }),
+ });
+
// ---- Auto-run text chain ----
export const startPipelineAutoRunText = (issueId, opts = {}) =>
request(`/pipeline/issues/${encodeURIComponent(issueId)}/auto-run-text`, {
diff --git a/server/lib/seasonStructure.js b/server/lib/seasonStructure.js
new file mode 100644
index 0000000000..fa792410fe
--- /dev/null
+++ b/server/lib/seasonStructure.js
@@ -0,0 +1,68 @@
+/**
+ * Season/episode structure recommendation.
+ *
+ * Comic-as-TV norms: 6–10 issues per season/volume is the sweet spot. Single
+ * volume up to 12 (the classic 12-issue maxi-series); 3-volume arc lands
+ * roughly at 18–30 issues; 4+ volumes only past 30. The "3 × 8 = 24" point
+ * is the canonical "3-season arc" target.
+ *
+ * Used both as renderer input to the arc-overview LLM prompt (so the LLM
+ * stops slicing 12-issue runs into three 4-issue seasons) and as the
+ * client-side hint shown next to the issue-count input.
+ */
+
+export const SEASON_MIN_EPISODES = 6;
+export const SEASON_MAX_EPISODES = 11;
+
+/**
+ * Pick the natural season count for a given total. Boundaries are tuned so
+ * 12 → 1 season, 18 → 3, 24 → 3, 30 → 3, 36 → 4.
+ */
+function pickSeasonCount(total) {
+ if (total <= 12) return 1;
+ if (total <= 17) return 2;
+ if (total <= 32) return 3;
+ if (total <= 44) return 4;
+ return 5;
+}
+
+/**
+ * Compute the recommended structure for a total issue/episode count.
+ *
+ * recommendStructure(12) → { seasons: 1, perSeason: [12] }
+ * recommendStructure(24) → { seasons: 3, perSeason: [8, 8, 8] }
+ * recommendStructure(20) → { seasons: 3, perSeason: [7, 7, 6] }
+ *
+ * Returns `null` for zero/negative input so callers can short-circuit
+ * (e.g. the UI hint hides itself when the user hasn't entered a target yet).
+ */
+export function recommendStructure(total) {
+ const n = Math.floor(Number(total) || 0);
+ if (n <= 0) return null;
+ const seasons = pickSeasonCount(n);
+ const base = Math.floor(n / seasons);
+ const remainder = n % seasons;
+ // Front-load extras into the earlier seasons so the array stays
+ // monotonically non-increasing — a 22-issue run reads as [8,7,7] not [7,7,8].
+ const perSeason = Array.from(
+ { length: seasons },
+ (_, i) => base + (i < remainder ? 1 : 0),
+ );
+ return { seasons, perSeason };
+}
+
+/**
+ * Human-readable summary like "3 volumes × 8 episodes" or "2 volumes
+ * × ~9 (9, 9)". Used in the LLM prompt and the client hint.
+ */
+export function describeStructure(structure) {
+ if (!structure) return '';
+ const { seasons, perSeason } = structure;
+ const allSame = perSeason.every((n) => n === perSeason[0]);
+ if (allSame) {
+ return seasons === 1
+ ? `1 volume × ${perSeason[0]} episodes`
+ : `${seasons} volumes × ${perSeason[0]} episodes`;
+ }
+ return `${seasons} volumes × ~${Math.round(perSeason.reduce((a, b) => a + b, 0) / seasons)} (${perSeason.join(', ')})`;
+}
diff --git a/server/lib/seasonStructure.test.js b/server/lib/seasonStructure.test.js
new file mode 100644
index 0000000000..ce5cd6a45c
--- /dev/null
+++ b/server/lib/seasonStructure.test.js
@@ -0,0 +1,58 @@
+import { describe, expect, it } from 'vitest';
+import { recommendStructure, describeStructure } from './seasonStructure.js';
+
+describe('recommendStructure', () => {
+ it('returns null for non-positive totals', () => {
+ expect(recommendStructure(0)).toBeNull();
+ expect(recommendStructure(-5)).toBeNull();
+ expect(recommendStructure(null)).toBeNull();
+ expect(recommendStructure(undefined)).toBeNull();
+ });
+
+ it('keeps 12 or fewer in a single volume', () => {
+ expect(recommendStructure(6)).toEqual({ seasons: 1, perSeason: [6] });
+ expect(recommendStructure(10)).toEqual({ seasons: 1, perSeason: [10] });
+ expect(recommendStructure(12)).toEqual({ seasons: 1, perSeason: [12] });
+ });
+
+ it('lands the canonical 3-volume arc points', () => {
+ // 18 = 3 × 6 (tight)
+ expect(recommendStructure(18)).toEqual({ seasons: 3, perSeason: [6, 6, 6] });
+ // 24 = 3 × 8 (sweet spot)
+ expect(recommendStructure(24)).toEqual({ seasons: 3, perSeason: [8, 8, 8] });
+ // 30 = 3 × 10 (streaming pacing)
+ expect(recommendStructure(30)).toEqual({ seasons: 3, perSeason: [10, 10, 10] });
+ });
+
+ it('splits 13–17 issues into two volumes', () => {
+ expect(recommendStructure(13)).toEqual({ seasons: 2, perSeason: [7, 6] });
+ expect(recommendStructure(16)).toEqual({ seasons: 2, perSeason: [8, 8] });
+ expect(recommendStructure(17)).toEqual({ seasons: 2, perSeason: [9, 8] });
+ });
+
+ it('front-loads remainder into earlier volumes', () => {
+ expect(recommendStructure(20)).toEqual({ seasons: 3, perSeason: [7, 7, 6] });
+ expect(recommendStructure(22)).toEqual({ seasons: 3, perSeason: [8, 7, 7] });
+ });
+
+ it('caps at 5 volumes for very long runs', () => {
+ expect(recommendStructure(50).seasons).toBe(5);
+ expect(recommendStructure(100).seasons).toBe(5);
+ expect(recommendStructure(100).perSeason.reduce((a, b) => a + b, 0)).toBe(100);
+ });
+});
+
+describe('describeStructure', () => {
+ it('renders even splits compactly', () => {
+ expect(describeStructure({ seasons: 1, perSeason: [12] })).toBe('1 volume × 12 episodes');
+ expect(describeStructure({ seasons: 3, perSeason: [8, 8, 8] })).toBe('3 volumes × 8 episodes');
+ });
+
+ it('renders uneven splits with the per-volume breakdown', () => {
+ expect(describeStructure({ seasons: 3, perSeason: [8, 7, 7] })).toBe('3 volumes × ~7 (8, 7, 7)');
+ });
+
+ it('returns empty string for null', () => {
+ expect(describeStructure(null)).toBe('');
+ });
+});
diff --git a/server/lib/worldPromptRenderers.js b/server/lib/worldPromptRenderers.js
new file mode 100644
index 0000000000..464befa27a
--- /dev/null
+++ b/server/lib/worldPromptRenderers.js
@@ -0,0 +1,33 @@
+/**
+ * Shared renderers that turn a World Builder world's `categories` map and
+ * `compositeSheets` array into prompt-friendly text blocks. Used by both
+ * `worldBuilderRefine` (which needs `[LOCKED]` flags) and `arcPlanner` (which
+ * does not). The two prior copies in those files had drifted in formatting;
+ * consolidating here keeps the LLM input shape consistent across stages.
+ */
+
+export function renderCategoriesForPrompt(categories, { showLocked = false } = {}) {
+ const entries = Object.entries(categories || {});
+ if (!entries.length) return '';
+ return entries
+ .map(([key, cat]) => {
+ const variations = (cat?.variations || [])
+ .map((v) => {
+ const flag = showLocked && v.locked ? ' [LOCKED]' : '';
+ return ` - "${v.label}"${flag}: ${v.prompt}`;
+ })
+ .join('\n');
+ return ` ${key}:\n${variations || ' (no variations yet)'}`;
+ })
+ .join('\n');
+}
+
+export function renderCompositesForPrompt(composites, { showLocked = false } = {}) {
+ if (!composites?.length) return '';
+ return composites
+ .map((c) => {
+ const flag = showLocked && c.locked ? ' [LOCKED]' : '';
+ return ` - (${c.kind || 'reference_sheet'}) "${c.label}"${flag}: ${c.prompt}`;
+ })
+ .join('\n');
+}
diff --git a/server/routes/pipeline.js b/server/routes/pipeline.js
index 415e8ae078..c17a4bf6ec 100644
--- a/server/routes/pipeline.js
+++ b/server/routes/pipeline.js
@@ -317,6 +317,20 @@ const arcGenerateSchema = z.object({ ...providerOverrideShape, commit: z.boolean
const seasonEpisodesGenerateSchema = z.object({ ...providerOverrideShape, commit: z.boolean().optional() });
const arcVerifySchema = z.object(providerOverrideShape);
+// Auto-resolve verification findings. `findings` empty/omitted = re-verify
+// first then resolve everything; otherwise the LLM only addresses the
+// caller-supplied subset (per-finding "Resolve" buttons).
+const verifyFindingSchema = z.object({
+ severity: z.enum(['high', 'medium', 'low']).optional(),
+ location: z.string().trim().max(200).optional(),
+ problem: z.string().trim().min(1).max(2000),
+ suggestion: z.string().trim().max(2000).optional(),
+});
+const arcResolveSchema = z.object({
+ ...providerOverrideShape,
+ findings: z.array(verifyFindingSchema).max(50).optional(),
+});
+
const autoRunSchema = z.object({
providerId: z.string().trim().max(80).optional(),
model: z.string().trim().max(200).optional(),
@@ -528,6 +542,16 @@ router.post('/series/:id/arc/verify', asyncHandler(async (req, res) => {
res.json(result);
}));
+// Auto-resolve verification findings. Persists the LLM's patched arc + season
+// outlines in one call. Per-episode issue records are not touched.
+router.post('/series/:id/arc/resolve-issues', asyncHandler(async (req, res) => {
+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
+ const body = validateRequest(arcResolveSchema, req.body ?? {});
+ const result = await arcPlanner.resolveVerifyIssues(req.params.id, body)
+ .catch((err) => { throw mapServiceError(err); });
+ res.json(result);
+}));
+
// =====================
// Issue routes
// =====================
diff --git a/server/services/pipeline/arcPlanner.js b/server/services/pipeline/arcPlanner.js
index eb7251582b..4f103fb4ae 100644
--- a/server/services/pipeline/arcPlanner.js
+++ b/server/services/pipeline/arcPlanner.js
@@ -21,9 +21,12 @@
import { runStagedLLM } from '../../lib/stageRunner.js';
import { ServerError } from '../../lib/errorHandler.js';
-import { getSeries } from './series.js';
+import { getSeries, updateSeries } from './series.js';
import { listIssues } from './issues.js';
import { sanitizeArc, sanitizeSeasonList, sanitizeSeason, buildSeason } from '../../lib/storyArc.js';
+import { recommendStructure, describeStructure } from '../../lib/seasonStructure.js';
+import { getWorld } from '../worldBuilder.js';
+import { renderCategoriesForPrompt, renderCompositesForPrompt } from '../../lib/worldPromptRenderers.js';
export const ERR_VALIDATION = 'PIPELINE_ARC_VALIDATION';
const makeErr = (message, code) => Object.assign(new Error(message), { code });
@@ -31,20 +34,71 @@ const makeErr = (message, code) => Object.assign(new Error(message), { code });
const VERIFY_SEVERITIES = new Set(['high', 'medium', 'low']);
const ARC_ROLES = new Set(['pilot', 'complication', 'midpoint', 'b-plot', 'all-is-lost', 'finale']);
-/**
- * Pull only the fields the arc-overview prompt cares about from the series
- * bible, so a verbose series record doesn't blow the prompt budget.
- */
-function buildArcOverviewContext(series) {
+// The world is the canonical source for factions, characters, environments,
+// etc. — without this, the arc planner would only see the series' own
+// characters/settings/objects which are usually empty pre-prose.
+async function loadWorldContext(worldId) {
+ if (!worldId) return null;
+ const world = await getWorld(worldId).catch(() => null);
+ if (!world) return null;
+
+ const embrace = Array.isArray(world.influences?.embrace) ? world.influences.embrace : [];
+ const avoid = Array.isArray(world.influences?.avoid) ? world.influences.avoid : [];
+
+ return {
+ worldName: world.name || '',
+ worldStarter: world.starterPrompt || '',
+ worldLogline: world.logline || '',
+ worldPremise: world.premise || '',
+ worldStyleNotes: world.styleNotes || '',
+ worldInfluencesEmbrace: embrace.length ? embrace.join(', ') : '(none)',
+ worldInfluencesAvoid: avoid.length ? avoid.join(', ') : '(none)',
+ worldCategoriesText: renderCategoriesForPrompt(world.categories) || '(none)',
+ worldCompositesText: renderCompositesForPrompt(world.compositeSheets) || '(none)',
+ };
+}
+
+// Fallback when series has no linked world — prompt partials still expect
+// these variables to be defined.
+const EMPTY_WORLD_CONTEXT = {
+ worldName: '(no linked world)',
+ worldStarter: '',
+ worldLogline: '',
+ worldPremise: '',
+ worldStyleNotes: '',
+ worldInfluencesEmbrace: '(none)',
+ worldInfluencesAvoid: '(none)',
+ worldCategoriesText: '(none — series has no linked World Builder world)',
+ worldCompositesText: '(none)',
+};
+
+// Resolve world context, accepting an optional preloaded value so callers
+// that chain (verify → resolve) don't reload the same world twice.
+async function resolveWorldContext(series, preloaded) {
+ if (preloaded) return preloaded;
+ return (await loadWorldContext(series.worldId)) || EMPTY_WORLD_CONTEXT;
+}
+
+// The `recommendedStructure` field encodes comic-as-TV norms (6–10 per
+// season, single season ≤ 12, 3-season arc around 18–30) so the LLM stops
+// defaulting to 3 seasons regardless of total count.
+async function buildArcOverviewContext(series, preloadedWorld) {
+ const structure = recommendStructure(series.issueCountTarget);
+ const world = await resolveWorldContext(series, preloadedWorld);
return {
series: {
name: series.name,
logline: series.logline,
premise: series.premise,
styleNotes: series.styleNotes,
- targetFormat: series.targetFormat,
issueCountTarget: series.issueCountTarget,
},
+ ...world,
+ recommendedStructure: structure
+ ? describeStructure(structure)
+ : '(no target episode count set — propose 1–3 volumes based on premise weight)',
+ recommendedSeasonCount: structure ? structure.seasons : '',
+ recommendedPerSeasonJson: structure ? JSON.stringify(structure.perSeason) : '[]',
existingCharactersJson: JSON.stringify(series.characters || [], null, 2),
existingSettingsJson: JSON.stringify(series.settings || [], null, 2),
existingObjectsJson: JSON.stringify(series.objects || [], null, 2),
@@ -75,7 +129,7 @@ function shapeSeasonOutlines(rawOutlines) {
export async function generateArcOverview(seriesId, options = {}) {
const series = await getSeries(seriesId);
- const ctx = buildArcOverviewContext(series);
+ const ctx = await buildArcOverviewContext(series);
const { content, runId, providerId, model } = await runStagedLLM(
'pipeline-arc-overview',
ctx,
@@ -112,7 +166,7 @@ export async function generateArcOverview(seriesId, options = {}) {
* is a textual summary of the seasons BEFORE this one (synopsis + logline),
* so the LLM has continuity to work against without re-reading every season.
*/
-function buildSeasonEpisodesContext(series, season, priorSeasons) {
+async function buildSeasonEpisodesContext(series, season, priorSeasons, preloadedWorld) {
const arc = series.arc || {};
const themesCsv = Array.isArray(arc.themes) ? arc.themes.join(', ') : '';
const priorSeasonsContext = priorSeasons.length === 0
@@ -120,6 +174,7 @@ function buildSeasonEpisodesContext(series, season, priorSeasons) {
: priorSeasons
.map((s) => `### Season ${s.number} — ${s.title}\n\n${s.logline}\n\n${s.synopsis || '(no synopsis)'}`)
.join('\n\n');
+ const world = await resolveWorldContext(series, preloadedWorld);
return {
series: {
name: series.name,
@@ -127,6 +182,7 @@ function buildSeasonEpisodesContext(series, season, priorSeasons) {
premise: series.premise,
styleNotes: series.styleNotes,
},
+ ...world,
arc: {
logline: arc.logline || '',
protagonistArc: arc.protagonistArc || '',
@@ -205,7 +261,7 @@ export async function generateSeasonEpisodes(seriesId, seasonId, options = {}) {
// sanitizer; this matches what the user is editing on screen.
const priorSeasons = seasons.filter((s) => (s.number || 0) < (season.number || 0));
- const ctx = buildSeasonEpisodesContext(series, season, priorSeasons);
+ const ctx = await buildSeasonEpisodesContext(series, season, priorSeasons);
const { content, runId, providerId, model } = await runStagedLLM(
'pipeline-season-episodes',
ctx,
@@ -233,7 +289,7 @@ export async function generateSeasonEpisodes(seriesId, seasonId, options = {}) {
* looked up via `listIssues` so the verify pass sees the *current* set, not
* a stale snapshot.
*/
-async function buildVerifyContext(series) {
+async function buildVerifyContext(series, preloadedWorld) {
const seasons = sanitizeSeasonList(series.seasons || []);
const issues = await listIssues({ seriesId: series.id });
// Group issues by seasonId so the tree's leaf order matches the seasons'
@@ -273,13 +329,14 @@ async function buildVerifyContext(series) {
});
}
const arc = series.arc || {};
+ const world = await resolveWorldContext(series, preloadedWorld);
return {
series: {
name: series.name,
logline: series.logline,
premise: series.premise,
- targetFormat: series.targetFormat,
},
+ ...world,
arc: {
logline: arc.logline || '',
summary: arc.summary || '',
@@ -322,7 +379,7 @@ export async function verifyArc(seriesId, options = {}) {
{ status: 400, code: 'PIPELINE_NO_ARC' },
);
}
- const ctx = await buildVerifyContext(series);
+ const ctx = await buildVerifyContext(series, options.preloadedWorld);
const { content, runId, providerId, model } = await runStagedLLM(
'pipeline-arc-verify',
ctx,
@@ -337,12 +394,143 @@ export async function verifyArc(seriesId, options = {}) {
return { issues, raw: content, runId, providerId, model };
}
+async function buildResolveContext(series, findings, preloadedWorld) {
+ const ctx = await buildVerifyContext(series, preloadedWorld);
+ const structure = recommendStructure(series.issueCountTarget);
+ return {
+ ...ctx,
+ findingsJson: JSON.stringify(findings, null, 2),
+ recommendedStructure: structure
+ ? describeStructure(structure)
+ : '(no target episode count set)',
+ recommendedSeasonCount: structure ? structure.seasons : '',
+ recommendedPerSeasonJson: structure ? JSON.stringify(structure.perSeason) : '[]',
+ };
+}
+
+const RESOLVE_FINDING_MAX = 50;
+
+function shapeFindings(rawFindings) {
+ if (!Array.isArray(rawFindings)) return [];
+ const out = [];
+ for (const f of rawFindings) {
+ const problem = typeof f?.problem === 'string' ? f.problem.trim() : '';
+ if (!problem) continue;
+ out.push({
+ severity: VERIFY_SEVERITIES.has(f?.severity) ? f.severity : 'medium',
+ location: typeof f?.location === 'string' ? f.location.trim().slice(0, 200) : '',
+ problem: problem.slice(0, 2000),
+ suggestion: typeof f?.suggestion === 'string' ? f.suggestion.trim().slice(0, 2000) : '',
+ });
+ if (out.length >= RESOLVE_FINDING_MAX) break;
+ }
+ return out;
+}
+
+// Per-episode (issue) records are NOT touched — those are user-owned scripts
+// and shouldn't get clobbered by a structural fix. If a finding's only
+// actionable resolution would require deleting issues, the LLM is told to
+// flag that in the response's `notes` field rather than executing it.
+// `options.findings` empty / omitted = re-run verify first and resolve
+// everything it returns.
+export async function resolveVerifyIssues(seriesId, options = {}) {
+ const series = await getSeries(seriesId);
+ if (!series.arc) {
+ throw new ServerError(
+ 'Series has no arc to resolve — run /arc/generate first',
+ { status: 400, code: 'PIPELINE_NO_ARC' },
+ );
+ }
+
+ // Load the world once and thread it through verify + resolve so the
+ // refresh-then-resolve path doesn't hit the filesystem twice for the same
+ // world.
+ const world = await resolveWorldContext(series);
+
+ let findings = shapeFindings(options.findings);
+ if (!findings.length) {
+ const fresh = await verifyArc(seriesId, { ...options, preloadedWorld: world });
+ findings = fresh.issues || [];
+ if (!findings.length) {
+ return { series, applied: false, notes: 'No findings to resolve', findings: [] };
+ }
+ }
+
+ const ctx = await buildResolveContext(series, findings, world);
+ const { content, runId, providerId, model } = await runStagedLLM(
+ 'pipeline-arc-resolve',
+ ctx,
+ {
+ providerOverride: options.providerOverride,
+ modelOverride: options.modelOverride,
+ returnsJson: true,
+ source: 'pipeline-arc-resolve',
+ },
+ );
+
+ const arc = sanitizeArc({
+ logline: content?.arc?.logline || series.arc.logline || '',
+ summary: content?.arc?.summary || series.arc.summary || '',
+ themes: content?.arc?.themes ?? series.arc.themes,
+ protagonistArc: content?.arc?.protagonistArc ?? series.arc.protagonistArc ?? '',
+ status: 'draft',
+ });
+
+ // Round-trip the LLM's seasons through `buildSeason` if they include a
+ // brand-new entry (no `id`), otherwise preserve the existing `id` so child
+ // issues still join their season cleanly. The sanitizer enforces the
+ // canonical shape regardless.
+ const existingById = new Map((series.seasons || []).map((s) => [s.id, s]));
+ const proposedSeasons = Array.isArray(content?.seasons) ? content.seasons : [];
+ const merged = proposedSeasons.map((raw) => {
+ const existing = raw?.id ? existingById.get(raw.id) : null;
+ if (existing) {
+ return sanitizeSeason({
+ ...existing,
+ title: typeof raw.title === 'string' ? raw.title : existing.title,
+ number: Number.isFinite(raw.number) ? raw.number : existing.number,
+ logline: typeof raw.logline === 'string' ? raw.logline : existing.logline,
+ synopsis: typeof raw.synopsis === 'string' ? raw.synopsis : existing.synopsis,
+ endingHook: typeof raw.endingHook === 'string' ? raw.endingHook : existing.endingHook,
+ episodeCountTarget: Number.isFinite(raw.episodeCountTarget)
+ ? raw.episodeCountTarget
+ : existing.episodeCountTarget,
+ themes: Array.isArray(raw.themes) ? raw.themes : existing.themes,
+ });
+ }
+ return buildSeason({
+ number: raw?.number,
+ title: raw?.title,
+ logline: raw?.logline,
+ synopsis: raw?.synopsis,
+ endingHook: raw?.endingHook,
+ episodeCountTarget: raw?.episodeCountTarget,
+ });
+ }).filter(Boolean);
+
+ const seasons = sanitizeSeasonList(merged);
+ const updated = await updateSeries(seriesId, { arc, seasons });
+
+ const notes = typeof content?.notes === 'string' ? content.notes.trim().slice(0, 2000) : '';
+ return {
+ series: updated,
+ applied: true,
+ notes,
+ findings,
+ runId,
+ providerId,
+ model,
+ };
+}
+
// Export internals for tests.
export const __testing = {
buildArcOverviewContext,
buildSeasonEpisodesContext,
buildVerifyContext,
+ buildResolveContext,
shapeSeasonOutlines,
shapeEpisodes,
shapeVerifyIssues,
+ shapeFindings,
};
diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.js
index 424eb8a875..5740675f53 100644
--- a/server/services/pipeline/arcPlanner.test.js
+++ b/server/services/pipeline/arcPlanner.test.js
@@ -26,6 +26,7 @@ vi.mock('../../lib/stageRunner.js', () => ({
const seriesSvc = await import('./series.js');
const issuesSvc = await import('./issues.js');
const seasonsSvc = await import('./seasons.js');
+const worldSvc = await import('../worldBuilder.js');
const planner = await import('./arcPlanner.js');
async function setupSeries(overrides = {}) {
@@ -114,6 +115,61 @@ describe('arcPlanner — generateArcOverview', () => {
expect(out.arc).toBe(null);
expect(out.seasons).toEqual([]);
});
+
+ it('feeds the linked world\'s categories + composite sheets into the prompt context', async () => {
+ // Create a world with factions + a composite sheet, then a series linked to it.
+ const world = await worldSvc.createWorld({
+ name: 'Clandestiny',
+ starterPrompt: 'paranormal investigators in a candy-bright city',
+ logline: 'World logline',
+ premise: 'World premise',
+ styleNotes: 'cel-shaded, pastels',
+ influences: { embrace: ['Moebius', 'Saga'], avoid: ['gritty'] },
+ categories: {
+ factions: { variations: [
+ { label: 'The Lollipop Bureau', prompt: 'pastel public-facing agency' },
+ { label: 'The Velvet Null', prompt: 'minimalist rival' },
+ ] },
+ characters: { variations: [
+ { label: 'Mira Holt', prompt: 'field detective' },
+ ] },
+ },
+ compositeSheets: [
+ { kind: 'reference_sheet', label: 'Rival agencies branding', prompt: 'comparison sheet' },
+ ],
+ });
+ const s = await setupSeries({ worldId: world.id });
+
+ stageRunnerSpy = vi.fn(async () => ({
+ content: {
+ logline: 'L', summary: 'S', themes: [], protagonistArc: 'A',
+ seasonOutlines: [{ number: 1, title: 'Pilot' }],
+ },
+ runId: 'r1', providerId: 'p', model: 'm',
+ }));
+ await planner.generateArcOverview(s.id);
+
+ const ctx = stageRunnerSpy.mock.calls[0][1];
+ expect(ctx.worldName).toBe('Clandestiny');
+ expect(ctx.worldCategoriesText).toContain('factions');
+ expect(ctx.worldCategoriesText).toContain('The Lollipop Bureau');
+ expect(ctx.worldCategoriesText).toContain('Mira Holt');
+ expect(ctx.worldCompositesText).toContain('Rival agencies branding');
+ expect(ctx.worldInfluencesEmbrace).toContain('Moebius');
+ expect(ctx.worldInfluencesAvoid).toContain('gritty');
+ });
+
+ it('renders an "(no linked world)" placeholder when the series has no worldId', async () => {
+ const s = await setupSeries({ worldId: null });
+ stageRunnerSpy = vi.fn(async () => ({
+ content: { logline: 'L', summary: 'S', themes: [], protagonistArc: 'A', seasonOutlines: [] },
+ runId: 'r1', providerId: 'p', model: 'm',
+ }));
+ await planner.generateArcOverview(s.id);
+ const ctx = stageRunnerSpy.mock.calls[0][1];
+ expect(ctx.worldName).toMatch(/no linked world/i);
+ expect(ctx.worldCategoriesText).toMatch(/none/i);
+ });
});
describe('arcPlanner — generateSeasonEpisodes', () => {
@@ -256,3 +312,81 @@ describe('arcPlanner — verifyArc', () => {
expect(out.issues[2].severity).toBe('medium');
});
});
+
+describe('arcPlanner — resolveVerifyIssues', () => {
+ beforeEach(() => {
+ fileStore.clear();
+ uuidCounter = 0;
+ stageRunnerSpy = undefined;
+ });
+
+ it('throws 400 NO_ARC if the series has no arc to resolve', async () => {
+ const s = await setupSeries();
+ await expect(planner.resolveVerifyIssues(s.id, { findings: [{ problem: 'X' }] }))
+ .rejects.toMatchObject({ status: 400, code: 'PIPELINE_NO_ARC' });
+ });
+
+ it('persists the LLM-patched arc + seasons and preserves existing season ids', async () => {
+ const s = await setupSeries();
+ await seriesSvc.updateSeries(s.id, { arc: { logline: 'old logline', summary: 'old summary' } });
+ const existingSeason = await seasonsSvc.createSeason(s.id, {
+ title: 'Season 1',
+ logline: 'old s1 logline',
+ synopsis: 'old s1 synopsis',
+ episodeCountTarget: 4,
+ });
+
+ stageRunnerSpy = vi.fn(async () => ({
+ content: {
+ arc: { logline: 'new logline', summary: 'new summary', themes: ['legacy'], protagonistArc: 'arc' },
+ seasons: [
+ {
+ id: existingSeason.id,
+ number: 1,
+ title: 'Season 1',
+ logline: 'new s1 logline',
+ synopsis: 'new s1 synopsis',
+ endingHook: 'hook',
+ episodeCountTarget: 12,
+ },
+ ],
+ notes: '',
+ },
+ runId: 'r1', providerId: 'p', model: 'm',
+ }));
+
+ const out = await planner.resolveVerifyIssues(s.id, {
+ findings: [{ severity: 'medium', problem: 'count vs weight', suggestion: 'raise count' }],
+ });
+
+ expect(out.applied).toBe(true);
+ expect(out.series.arc.logline).toBe('new logline');
+ expect(out.series.seasons).toHaveLength(1);
+ expect(out.series.seasons[0].id).toBe(existingSeason.id); // id preserved
+ expect(out.series.seasons[0].episodeCountTarget).toBe(12);
+ expect(out.series.seasons[0].logline).toBe('new s1 logline');
+
+ const call = stageRunnerSpy.mock.calls[0];
+ expect(call[0]).toBe('pipeline-arc-resolve');
+ expect(call[1]).toMatchObject({
+ findingsJson: expect.stringContaining('count vs weight'),
+ recommendedStructure: expect.any(String),
+ });
+ });
+
+ it('re-runs verify when no findings are supplied and short-circuits on a clean arc', async () => {
+ const s = await setupSeries();
+ await seriesSvc.updateSeries(s.id, { arc: { logline: 'L' } });
+ // First call (from verify) returns no issues — resolve should short-circuit
+ // without making a second LLM call.
+ stageRunnerSpy = vi.fn(async () => ({
+ content: { issues: [] },
+ runId: 'verify-r', providerId: 'p', model: 'm',
+ }));
+ const out = await planner.resolveVerifyIssues(s.id, {});
+ expect(out.applied).toBe(false);
+ expect(out.notes).toMatch(/no findings/i);
+ expect(stageRunnerSpy).toHaveBeenCalledTimes(1);
+ expect(stageRunnerSpy.mock.calls[0][0]).toBe('pipeline-arc-verify');
+ });
+});
diff --git a/server/services/worldBuilderRefine.js b/server/services/worldBuilderRefine.js
index c2f61b139e..2c029701f0 100644
--- a/server/services/worldBuilderRefine.js
+++ b/server/services/worldBuilderRefine.js
@@ -15,6 +15,10 @@ import { ServerError } from "../lib/errorHandler.js";
import { getActiveProvider, getProviderById } from "./providers.js";
import { createRun, executeApiRun, executeCliRun } from "./runner.js";
import { resolveEffectiveModel } from "../lib/promptRunner.js";
+import {
+ renderCategoriesForPrompt as renderCategoriesShared,
+ renderCompositesForPrompt as renderCompositesShared,
+} from "../lib/worldPromptRenderers.js";
import {
COMPOSITE_PROMPT_MAX,
COMPOSITE_SHEETS_MAX,
@@ -151,31 +155,11 @@ export function collapseStyleDirectionDupes(starter) {
return `${stripped}\n\n${last}`.trim();
}
-const renderCategoriesForPrompt = (categories) => {
- const entries = Object.entries(categories || {});
- if (!entries.length) return "";
- return entries
- .map(([key, cat]) => {
- const variations = (cat?.variations || [])
- .map((v) => {
- const flag = v.locked ? " [LOCKED]" : "";
- return ` - "${v.label}"${flag}: ${v.prompt}`;
- })
- .join("\n");
- return ` ${key}:\n${variations || " (no variations yet)"}`;
- })
- .join("\n");
-};
+const renderCategoriesForPrompt = (categories) =>
+ renderCategoriesShared(categories, { showLocked: true });
-const renderCompositesForPrompt = (composites) => {
- if (!composites?.length) return "";
- return composites
- .map((c) => {
- const flag = c.locked ? " [LOCKED]" : "";
- return ` - (${c.kind || "reference_sheet"}) "${c.label}"${flag}: ${c.prompt}`;
- })
- .join("\n");
-};
+const renderCompositesForPrompt = (composites) =>
+ renderCompositesShared(composites, { showLocked: true });
export function buildWorldRefinePrompt({
starterPrompt,
@@ -212,6 +196,11 @@ STRUCTURE RULES (the world has been expanded — categories and composite sheets
- Each composite sheet is a multi-subject board (kind "reference_sheet" or "world_pitch_poster") with { "label", "prompt" }, also [LOCKED]-flaggable.
- Variations / composites flagged [LOCKED] must be returned with their EXACT original label + prompt — do not rephrase, expand, trim, or "lightly clean up" them. The server discards changes to locked items.
- Unlocked variations / composites may be rewritten, replaced (same label, new prompt), or REMOVED if the user's feedback warrants it. Removing an item means omitting it from the response.
+- EXPLICIT REMOVAL IS A DIRECT ORDER. If the user names a specific variation, composite, faction, character, location, or other entity to remove ("drop X", "remove X", "delete X", "get rid of X", "no more X"), you MUST:
+ (a) OMIT any variation whose label matches X from the response entirely (do not return it under a renamed label either).
+ (b) OMIT any composite sheet whose primary subject IS X — even if a sibling subject remains. For example, if the user removes "Faction A" and a sheet is titled "Faction A vs Faction B branding sheet", omit the whole sheet; replace it with a single-subject sheet for Faction B only if the world still warrants it.
+ (c) SCRUB every textual reference to X from the prompts of any remaining unlocked composites and variations (faction lists, inset panels, comparison columns, callouts, etc.). Rewrite those prompts so X is not mentioned. If a remaining unlocked composite's prompt becomes incoherent once X is scrubbed, remove that composite too.
+ (d) References to X inside LOCKED items (locked variations, locked composites, locked narrative fields) cannot be edited — leave them, but do not let them tempt you into re-adding X under a new label. The server will not re-add X just because a locked field still mentions it.
- You MAY ADD new variations to any existing category, propose ENTIRELY NEW categories, and ADD new composite sheets when the feedback motivates it. Use snake_case keys for new category names (e.g. "secret_rituals").
- Keep category counts manageable: at most ${WORLD_CATEGORY_COUNT_MAX} total categories, ${VARIATIONS_PER_CATEGORY_MAX} variations per category, ${COMPOSITE_SHEETS_MAX} composite sheets.
- Variation prompts ≤${PROMPT_FRAGMENT_MAX} chars; composite prompts ≤${COMPOSITE_PROMPT_MAX} chars; labels ≤${VARIATION_LABEL_MAX} chars.