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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([story-builder-issue-llm-seeding]): seed issues from the arc inside the builder
[._.]/ Adam Eivy20ce18662ee0
diff --git a/client/src/pages/StoryBuilder.jsx b/client/src/pages/StoryBuilder.jsxindex a057b1a476..ff6b48d2c6 100644--- a/client/src/pages/StoryBuilder.jsx+++ b/client/src/pages/StoryBuilder.jsx@@ -17,7 +17,7 @@ import { useLockToggle } from '../hooks/useLockToggle';import {getStoryBuilderSteps, listStorySessions, getStorySession, createStorySession,updateStorySession, setStoryCurrentStep, lockStoryStep, unlockStoryStep,- generateStoryStep, refineStoryStep, setStoryIssueLock,+ generateStoryStep, refineStoryStep, setStoryIssueLock, generateStoryIssues,getUniverse, getPipelineSeries, listPipelineIssues,analyzeImport, commitImport, retryImporterIssues, IMPORTER_CONTENT_TYPES,getProviders, getSettings, generateImage, updateUniverse,@@ -670,6 +670,8 @@ function StepCharacters({ session, universe, locked, onChanged }) {function IssuesPanel({ session, series, issues, onChanged }) {const locks = session.steps?.issues?.issueLocks || {};const [busyId, setBusyId] = useState(null);+ const [generating, setGenerating] = useState(false);+ const hasSeasons = Array.isArray(series?.seasons) && series.seasons.length > 0;const toggleIssue = async (issueId, next) => {setBusyId(issueId);@@ -679,18 +681,57 @@ function IssuesPanel({ session, series, issues, onChanged }) {if (res) { toast.success(next ? 'Issue marked done' : 'Issue reopened'); onChanged(); }};+ // Seed issues from the arc — generates a per-episode breakdown for every+ // season and persists one issue per episode, so the user never leaves the+ // builder. Provider/model is resolved server-side from the session picker.+ const generateIssues = async () => {+ setGenerating(true);+ const res = await generateStoryIssues(session.id, {}, { silent: true })+ .catch((err) => { toast.error(err?.message || 'Failed to generate issues'); return null; });+ setGenerating(false);+ if (!res) return;+ const created = res.createdIssues?.length || 0;+ const skipped = (res.seasons || []).filter((s) => s.skipped);+ if (created > 0) {+ toast.success(`Created ${created} issue${created === 1 ? '' : 's'} from the arc`);+ } else {+ toast.error(skipped.length ? `No issues created — ${skipped[0].reason}` : 'No issues were generated');+ }+ // Surface partial-batch skips so a locked/empty season doesn't fail silently.+ if (created > 0 && skipped.length) {+ toast.error(`Skipped ${skipped.length} season${skipped.length === 1 ? '' : 's'}: ${skipped[0].reason}`);+ }+ onChanged();+ };+return (<div className="space-y-3">- <div className="flex items-center justify-between">+ <div className="flex items-center justify-between gap-2 flex-wrap"><p className="text-sm text-gray-400">Complete issues one at a time. Lock issue #1 before moving to #2.</p>- {series?.id && (- <Link to={`/pipeline/series/${series.id}`} className="text-sm text-port-accent inline-flex items-center gap-1">- Plan issues in Pipeline <ExternalLink className="w-4 h-4" />- </Link>- )}+ <div className="flex items-center gap-3">+ {hasSeasons && (+ <button+ onClick={generateIssues} disabled={generating}+ title="Generate a per-episode breakdown for every season and create the issues here"+ className="inline-flex items-center gap-2 bg-port-accent hover:bg-blue-600 disabled:opacity-50 text-white px-3 py-1.5 rounded text-sm"+ >+ {generating ? <Loader2 className="w-4 h-4 animate-spin" /> : <Sparkles className="w-4 h-4" />}+ Generate issues from arc+ </button>+ )}+ {series?.id && (+ <Link to={`/pipeline/series/${series.id}`} className="text-sm text-port-accent inline-flex items-center gap-1">+ Plan issues in Pipeline <ExternalLink className="w-4 h-4" />+ </Link>+ )}+ </div></div>{(!issues || issues.length === 0) && (- <p className="text-gray-600 italic text-sm">No issues yet — generate seasons on the plot-arc step, then plan issues in the Pipeline.</p>+ <p className="text-gray-600 italic text-sm">+ {hasSeasons+ ? 'No issues yet — “Generate issues from arc” seeds one issue per episode for each season, or plan them in the Pipeline.'+ : 'No issues yet — generate seasons on the plot-arc step first, then seed issues from the arc.'}+ </p>)}{(issues || []).map((i) => {const isLocked = locks[i.id]?.locked;diff --git a/client/src/services/apiStoryBuilder.js b/client/src/services/apiStoryBuilder.jsindex f1ce2d127a..2db9165161 100644--- a/client/src/services/apiStoryBuilder.js+++ b/client/src/services/apiStoryBuilder.js@@ -50,6 +50,13 @@ export const refineStoryStep = (id, stepId, payload = {}, options = {}) =>...options,});+export const generateStoryIssues = (id, payload = {}, options = {}) =>+ request(`/story-builder/${id}/issues/generate`, {+ method: 'POST',+ body: JSON.stringify(payload),+ ...options,+ });+export const setStoryIssueLock = (id, issueId, locked, options = {}) =>request(`/story-builder/${id}/issues/${issueId}/lock`, {method: 'POST',diff --git a/server/lib/validation.js b/server/lib/validation.jsindex d32bd47984..cdef4d1cc5 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1899,3 +1899,11 @@ export const storyStepRefineSchema = z.object({export const storyIssueLockSchema = z.object({locked: z.boolean(),}).strict();++export const storyIssuesGenerateSchema = z.object({+ providerId: storyProviderField,+ model: storyModelField,+ // Optional: scope generation to a single season; omit to cover every season+ // on the arc.+ seasonId: z.preprocess(emptyToUndefined, z.string().trim().max(64).optional()),+}).strict();diff --git a/server/routes/pipeline.js b/server/routes/pipeline.jsindex ec7ae40832..8041b7a957 100644--- a/server/routes/pipeline.js+++ b/server/routes/pipeline.js@@ -1183,38 +1183,14 @@ router.post('/series/:id/seasons/:seasonId/episodes/generate', asyncHandler(asynconst result = await arcPlanner.generateSeasonEpisodes(req.params.id, req.params.seasonId, body).catch((err) => { throw mapServiceError(err); });- const createdIssues = [];+ let createdIssues = [];let bibleExtracted = null;if (body.commit) {// Create one issue per episode under this season. The issue sanitizer- // already accepts `seasonId` + `arcPosition`, so we forward them in the- // create payload. The episode's `synopsis` lands in `stages.idea.input`- // so the downstream auto-run-text chain has a seed to expand against.- for (const ep of result.episodes) {- const created = await issuesSvc.createIssue({- seriesId: req.params.id,- title: ep.title,- // Issue `number` is derived from (volume order, arcPosition) by- // `createIssue`'s renumber pass — a new V1 episode falls into V1's- // slot and later volumes' numbers shift to make room.- seasonId: req.params.seasonId,- arcPosition: ep.number,- // `arcRole` carries the LLM's pilot / complication / midpoint / etc.- // classification forward so the idea-expansion prompt can size beats- // to the role (a finale needs a different cadence than a complication).- arcRole: ep.arcRole,- // Episode-level length sizing from the season-episodes LLM pass.- // Defaults to 'standard' inside the issue sanitizer when missing.- lengthProfile: ep.lengthProfile,- stages: {- idea: {- status: ep.synopsis ? 'edited' : 'empty',- input: [ep.logline, ep.synopsis].filter(Boolean).join('\n\n'),- },- },- });- createdIssues.push(created);- }+ // already accepts `seasonId` + `arcPosition`; the shared helper owns the+ // per-episode → createIssue mapping so the Story Builder's batch path+ // mints identical issue shapes.+ createdIssues = await arcPlanner.commitEpisodesToIssues(req.params.id, req.params.seasonId, result.episodes);// Non-fatal: episode creation already succeeded, so a noisy extraction// failure must not invalidate the user's accepted breakdown. Phase B.4:diff --git a/server/routes/storyBuilder.js b/server/routes/storyBuilder.jsindex a067769481..c5290ecd53 100644--- a/server/routes/storyBuilder.js+++ b/server/routes/storyBuilder.js@@ -7,6 +7,7 @@ import {storyStepGenerateSchema,storyStepRefineSchema,storyIssueLockSchema,+ storyIssuesGenerateSchema,} from '../lib/validation.js';import { STEPS, isValidStepId } from '../lib/storyBuilderSteps.js';import {@@ -21,6 +22,7 @@ import {setIssueLock,generateStep,refineStep,+ generateIssuesFromArc,ERR_NOT_FOUND,ERR_VALIDATION,} from '../services/storyBuilder.js';@@ -110,7 +112,15 @@ router.post('/:id/steps/:stepId/refine', asyncHandler(async (req, res) => {res.json(result);}));-// ── Per-issue locks (issues step loop) ───────────────────────────────────────+// ── Issues step: seed issues from the arc + per-issue locks ──────────────────++// Generate the per-episode breakdown for the linked series' seasons and+// persist one issue per episode, so the user never has to leave the builder.+router.post('/:id/issues/generate', asyncHandler(async (req, res) => {+ const input = validateRequest(storyIssuesGenerateSchema, req.body || {});+ const result = await generateIssuesFromArc(req.params.id, input).catch((err) => { throw mapServiceError(err); });+ res.json(result);+}));router.post('/:id/issues/:issueId/lock', asyncHandler(async (req, res) => {const { locked } = validateRequest(storyIssueLockSchema, req.body || {});diff --git a/server/services/pipeline/arcPlanner.js b/server/services/pipeline/arcPlanner.jsindex 9f77db6edb..770f37c401 100644--- a/server/services/pipeline/arcPlanner.js+++ b/server/services/pipeline/arcPlanner.js@@ -24,7 +24,7 @@ import { planManuscriptPass, estimateTokens } from '../../lib/contextBudget.js';import { ServerError } from '../../lib/errorHandler.js';import { stripAnsi } from '../../lib/ansiStrip.js';import { getSeries, updateSeries, updateSeasonOnSeries, ARC_LOCKABLE_FIELDS, MANUSCRIPT_TYPES } from './series.js';-import { listIssues, updateIssue, recomputeIssueNumbersForSeries, getIssue, updateStage, updateStageWithLatest, assertStageUnlocked } from './issues.js';+import { listIssues, updateIssue, recomputeIssueNumbersForSeries, getIssue, updateStage, updateStageWithLatest, assertStageUnlocked, createIssue } from './issues.js';import { emitRecordUpdated, withReexportSuppressed } from '../sharing/recordEvents.js';import { getSeason } from './seasons.js';import {@@ -1100,6 +1100,44 @@ export async function generateSeasonEpisodes(seriesId, seasonId, options = {}) {};}+/**+ * Persist a season's generated episodes as issue records — one issue per+ * episode, with the season pointer + arcPosition + arcRole + length profile+ * forwarded so the downstream auto-run-text chain has a seed to expand+ * against. Shared by the pipeline season-episodes route and the Story+ * Builder's "generate issues from arc" action so both mint byte-identical+ * issue shapes. The episode's logline + synopsis land in `stages.idea.input`.+ */+export async function commitEpisodesToIssues(seriesId, seasonId, episodes = []) {+ const created = [];+ for (const ep of episodes) {+ const issue = await createIssue({+ seriesId,+ title: ep.title,+ // Issue `number` is derived from (volume order, arcPosition) by+ // `createIssue`'s renumber pass — a new episode falls into its volume's+ // slot and later volumes' numbers shift to make room.+ seasonId,+ arcPosition: ep.number,+ // `arcRole` carries the LLM's pilot / complication / midpoint / etc.+ // classification forward so the idea-expansion prompt can size beats to+ // the role (a finale needs a different cadence than a complication).+ arcRole: ep.arcRole,+ // Episode-level length sizing from the season-episodes LLM pass.+ // Defaults to 'standard' inside the issue sanitizer when missing.+ lengthProfile: ep.lengthProfile,+ stages: {+ idea: {+ status: ep.synopsis ? 'edited' : 'empty',+ input: [ep.logline, ep.synopsis].filter(Boolean).join('\n\n'),+ },+ },+ });+ created.push(issue);+ }+ return created;+}+/*** Generate FRONT + BACK cover-art concepts for one volume (season). Returns* the proposed text without persisting; pass `commit: true` to write thediff --git a/server/services/storyBuilder.js b/server/services/storyBuilder.jsindex b5f0b95c80..d8d0269e3a 100644--- a/server/services/storyBuilder.js+++ b/server/services/storyBuilder.js@@ -38,7 +38,7 @@ import {} from './pipeline/series.js';import {generateArcOverview, generateArcFromSource, generateReaderMap, refineReaderMap, commitSeasonsWithRemap,- collectIssueSourceText,+ collectIssueSourceText, generateSeasonEpisodes, commitEpisodesToIssues,} from './pipeline/arcPlanner.js';const TYPE_SCHEMA_VERSION = 1;@@ -420,6 +420,65 @@ export async function setIssueLock(id, issueId, locked) {});}+// ── Seed issues from the arc (issues step) ─────────────────────────────────++/**+ * Generate the per-episode breakdown for the linked series' seasons and+ * persist one issue per episode — so the user doesn't have to leave the+ * builder for the Pipeline. Delegates to arcPlanner.generateSeasonEpisodes+ * (per season) + commitEpisodesToIssues, the same path the Pipeline's+ * season-episodes route uses.+ *+ * Provider/model resolution mirrors generateStep: an explicit override wins,+ * else the session's saved picker choice (session.llm).+ *+ * Batch semantics: generateSeasonEpisodes throws on a locked season or one+ * with no synopsis/logline. In a multi-season run one ineligible season must+ * not abort the rest, so each season is caught independently and reported as+ * `skipped` with its reason — the eligible seasons still produce issues.+ *+ * `options.seasonId` scopes generation to a single season; omit to cover every+ * season on the arc.+ */+export async function generateIssuesFromArc(id, options = {}) {+ const session = await getStorySession(id);+ if (!session.seriesId) throw makeErr('No series linked', ERR_VALIDATION);+ const series = await getSeries(session.seriesId);+ const seasons = Array.isArray(series?.seasons) ? series.seasons : [];+ if (seasons.length === 0) {+ throw makeErr('No seasons on the arc yet — generate the plot arc first', ERR_VALIDATION);+ }++ const targetSeasons = options.seasonId+ ? seasons.filter((s) => s.id === options.seasonId)+ : seasons;+ if (options.seasonId && targetSeasons.length === 0) {+ throw makeErr(`Season not found on series: ${options.seasonId}`, ERR_VALIDATION);+ }++ const reqProviderId = options.providerId || session.llm?.provider || undefined;+ const reqModel = options.model || session.llm?.model || undefined;++ const createdIssues = [];+ const seasonResults = [];+ for (const season of targetSeasons) {+ const label = season.title || `Volume ${season.number ?? '?'}`;+ const res = await generateSeasonEpisodes(session.seriesId, season.id, {+ providerOverride: reqProviderId,+ modelOverride: reqModel,+ }).catch((err) => ({ error: err?.message || 'Failed to generate episodes' }));+ if (res.error) {+ seasonResults.push({ seasonId: season.id, title: label, created: 0, skipped: true, reason: res.error });+ continue;+ }+ const issues = await commitEpisodesToIssues(session.seriesId, season.id, res.episodes);+ createdIssues.push(...issues);+ seasonResults.push({ seasonId: season.id, title: label, created: issues.length, skipped: false, runId: res.runId });+ }++ return { createdIssues, seasons: seasonResults };+}+// ── Backfill (generate upstream from downstream) ───────────────────────────// ── Generate / refine delegation ──────────────────────────────────────────diff --git a/server/services/storyBuilder.test.js b/server/services/storyBuilder.test.jsindex 06a5636048..c81dfaf083 100644--- a/server/services/storyBuilder.test.js+++ b/server/services/storyBuilder.test.js@@ -329,3 +329,108 @@ describe('generateStep backfill (fromDownstream)', () => {.rejects.toThrow(/No issue content/);});});++describe('generateIssuesFromArc (issues step)', () => {+ // Attach one or more seasons to a freshly-minted seed session's series and+ // return the persisted season ids (sanitizer may re-mint them).+ async function seedSeasons(seriesId, seasons) {+ await seriesSvc.updateSeries(seriesId, { seasons });+ const series = await seriesSvc.getSeries(seriesId);+ return series.seasons;+ }++ // The season-episodes LLM pass returns `{ episodes: [...] }`; shapeEpisodes+ // keeps title + number + arcRole + lengthProfile + logline/synopsis.+ function episodesSpy(episodesBySeasonTitle) {+ stageRunnerSpy = vi.fn(async (stage, vars) => {+ if (stage !== 'pipeline-season-episodes') return { content: {}, runId: 'r', providerId: 'p', model: 'm' };+ const episodes = episodesBySeasonTitle[vars?.season?.title] || [];+ return { content: { episodes }, runId: 'r', providerId: 'p', model: 'm' };+ });+ }++ it('creates one issue per episode for every season and seeds idea input', async () => {+ const s = await sb.createStorySession({ title: 'Arc Seed' });+ const seasons = await seedSeasons(s.seriesId, [+ { number: 1, title: 'Vol 1', synopsis: 'foundry goes silent' },+ ]);+ episodesSpy({+ 'Vol 1': [+ { number: 1, title: 'Pilot', logline: 'it begins', synopsis: 'cold open', arcRole: 'pilot', lengthProfile: 'standard' },+ { number: 2, title: 'Complication', logline: 'it worsens', synopsis: '', arcRole: 'complication' },+ ],+ });+ const res = await sb.generateIssuesFromArc(s.id);+ expect(res.createdIssues).toHaveLength(2);+ expect(res.seasons).toEqual([+ expect.objectContaining({ seasonId: seasons[0].id, created: 2, skipped: false }),+ ]);+ const issues = await issuesSvc.listIssues({ seriesId: s.seriesId });+ expect(issues.map((i) => i.title).sort()).toEqual(['Complication', 'Pilot']);+ const pilot = issues.find((i) => i.title === 'Pilot');+ expect(pilot.seasonId).toBe(seasons[0].id);+ // logline + synopsis land in stages.idea.input; status is 'edited' when a+ // synopsis exists, 'empty' otherwise.+ expect(pilot.stages.idea.input).toBe('it begins\n\ncold open');+ expect(pilot.stages.idea.status).toBe('edited');+ const comp = issues.find((i) => i.title === 'Complication');+ expect(comp.stages.idea.status).toBe('empty');+ expect(comp.stages.idea.input).toBe('it worsens');+ });++ it('skips a locked season but still seeds the eligible ones (partial batch)', async () => {+ const s = await sb.createStorySession({ title: 'Partial' });+ const seasons = await seedSeasons(s.seriesId, [+ { number: 1, title: 'Vol 1', synopsis: 'open', locked: true },+ { number: 2, title: 'Vol 2', synopsis: 'rises' },+ ]);+ episodesSpy({ 'Vol 2': [{ number: 1, title: 'V2 E1', arcRole: 'pilot' }] });+ const res = await sb.generateIssuesFromArc(s.id);+ expect(res.createdIssues).toHaveLength(1);+ const locked = res.seasons.find((r) => r.seasonId === seasons[0].id);+ const open = res.seasons.find((r) => r.seasonId === seasons[1].id);+ expect(locked).toMatchObject({ skipped: true, created: 0 });+ expect(locked.reason).toMatch(/locked/i);+ expect(open).toMatchObject({ skipped: false, created: 1 });+ });++ it('scopes to a single season when seasonId is given', async () => {+ const s = await sb.createStorySession({ title: 'Scoped' });+ const seasons = await seedSeasons(s.seriesId, [+ { number: 1, title: 'Vol 1', synopsis: 'a' },+ { number: 2, title: 'Vol 2', synopsis: 'b' },+ ]);+ episodesSpy({+ 'Vol 1': [{ number: 1, title: 'V1 E1', arcRole: 'pilot' }],+ 'Vol 2': [{ number: 1, title: 'V2 E1', arcRole: 'pilot' }],+ });+ const res = await sb.generateIssuesFromArc(s.id, { seasonId: seasons[1].id });+ expect(res.seasons).toHaveLength(1);+ expect(res.seasons[0].seasonId).toBe(seasons[1].id);+ const issues = await issuesSvc.listIssues({ seriesId: s.seriesId });+ expect(issues.map((i) => i.title)).toEqual(['V2 E1']);+ });++ it('forwards the session.llm provider/model into the episodes pass', async () => {+ const s = await sb.createStorySession({ title: 'LLM', llm: { provider: 'prov-x', model: 'model-y' } });+ await seedSeasons(s.seriesId, [{ number: 1, title: 'Vol 1', synopsis: 'a' }]);+ episodesSpy({ 'Vol 1': [{ number: 1, title: 'E1', arcRole: 'pilot' }] });+ await sb.generateIssuesFromArc(s.id);+ expect(stageRunnerSpy).toHaveBeenCalledWith(+ 'pipeline-season-episodes', expect.any(Object),+ expect.objectContaining({ providerOverride: 'prov-x', modelOverride: 'model-y' }),+ );+ });++ it('throws when the series has no seasons yet', async () => {+ const s = await sb.createStorySession({ title: 'No Seasons' });+ await expect(sb.generateIssuesFromArc(s.id)).rejects.toMatchObject({ code: sb.ERR_VALIDATION });+ });++ it('throws when the scoped seasonId is unknown', async () => {+ const s = await sb.createStorySession({ title: 'Bad Season' });+ await seedSeasons(s.seriesId, [{ number: 1, title: 'Vol 1', synopsis: 'a' }]);+ await expect(sb.generateIssuesFromArc(s.id, { seasonId: 'season-nope' }))+ .rejects.toMatchObject({ code: sb.ERR_VALIDATION });+ });+});