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
autopilot: heal episode-level arc contradictions + per-run format targeting
[._.]/ Adam Eivy4f12210260a4
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 81b70bfa85..3f429a41c2 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -30,6 +30,8 @@- **Install additional audio models from HuggingFace.** The Track editor's generator panel can pull extra checkpoints (e.g. a larger MusicGen, an AudioLDM2 variant) straight from HuggingFace into the local cache — same streamed-download path as the image/video model installer — and they become selectable for generation immediately. User-installed models persist in `data/audio-models.json` and can be removed from the same panel.- **"Audio & Music" category in the Local LLM model installer (Settings → Local LLM).** The Hugging Face model search gained an audio/music output category that surfaces generation models (MusicGen, AudioLDM2, ACE-Step, Stable Audio, Magenta…) — the GGUF filter is relaxed for this category since audio models aren't GGUF. Installing an audio model downloads it into the HF cache and registers it in the **same** shared audio-model registry the Music studio reads (`data/audio-models.json`), so there's one DRY place to manage audio models: install it once from the installer and it's immediately selectable in the Music studio. Models no on-device engine can run yet — and ACE-Step, which uses a fixed checkpoint — are discovery-only with a "Visit" link. Curated suggestions lead the list: **ACE-Step v1.5**, **`google/magenta-realtime-2`**, and **`stabilityai/stable-audio-3-medium`** (the last gated behind a Hugging Face data-sharing agreement).+- **Autopilot now heals episode-level arc contradictions instead of pausing on them.** The arc-verify convergence loop re-verifies and auto-resolves the arc each round, but auto-resolve could previously only rewrite the arc + volume/season synopses — it was explicitly forbidden from touching episodes. So a contradiction that *originated* inside one episode's planning synopsis (e.g. an episode stages an event a later volume reserves as its own "first" occurrence) could never be fixed: every round re-flagged it because the episode text never changed, and the run always hard-paused with "arc verification did not converge." The auto-resolve pass can now return targeted episode-synopsis corrections (keyed by season + episode number), applied at the arc-verify gate **before** any beats/scripts are generated — so the cheap structural layer is made consistent before expensive script generation. Locked episodes are left untouched; already-expanded beats on a corrected episode are cleared so they regenerate from the fixed synopsis. (`pipeline-arc-resolve` prompt + migration 120.)+- **Autopilot can target one format of a multi-format series.** A `comic+tv` series can now be driven to just its comic draft (or just TV) in a single run via a per-run format restriction, so you don't pay to generate, say, 24 teleplays when you only want the comic proof. Absent a restriction the run authors every format the series targets (unchanged default).- **Autopilot convergence rounds are now configurable.** The series autopilot re-verifies the arc (and re-reviews the manuscript) in bounded auto-resolve loops, and previously hard-stopped after 3 arc rounds / 2 editorial rounds with "did not converge after 3 rounds" — leaving no way to give a stubborn arc more attempts. You can now set **Arc verify rounds** and **Editorial rounds** (0–20, where 0 skips that gate) in Autonomous mode → **Options**; the values persist as a per-install default and are reused on **Resume**. A per-run override still wins over the saved default, which wins over the built-in floor (3 / 2). When a gate still can't auto-resolve within the limit, the pause message now says how many blocking findings remain and points you to edit the arc/manuscript or raise the limit and resume.- Editorial Checks page now has an AI provider + model selector that configures the editorial pass. Leave it on "Default provider" to use the active/stage provider, or pick a specific provider/model to override the LLM-backed checks for that run.- App **Automation** tabs now show a banner when scheduled automation is globally paused, with a one-click **Resume**. Manually clicking **Run** on a task now bypasses the global pause — the pause only stops scheduled/autonomous spawning, not explicit user triggers.diff --git a/data.reference/prompts/stages/pipeline-arc-resolve.md b/data.reference/prompts/stages/pipeline-arc-resolve.mdindex 029cb4afda..9df1c4c7c6 100644--- a/data.reference/prompts/stages/pipeline-arc-resolve.md+++ b/data.reference/prompts/stages/pipeline-arc-resolve.md@@ -82,14 +82,14 @@ The verification pass flagged these problems. Resolve **every** one of them in y## How to resolve-1. **Anchor every edit in the per-episode `synopsis` entries.** Each volume's `episodes[]` array carries the user's authored episode lineup — those `synopsis` strings are the ground truth for what actually happens. Volume-level `synopsis` rewrites must summarize what the child episodes describe; don't invent beats no episode synopsis covers, and don't paper over contradictions that originate at the episode level. When a finding cites an episode (e.g. `season:2 / episode:5`), the fix usually means re-framing the volume around what that episode already shows — not contradicting it. Empty/null episode synopses mean the user hasn't drafted that issue yet; treat that volume as load-bearing on its own `synopsis` only.+1. **Anchor every edit in the per-episode `synopsis` entries.** Each volume's `episodes[]` array carries the planned episode lineup — those `synopsis` strings describe what actually happens in each issue. Prefer the **minimal** edit: most findings resolve by re-framing a volume's `synopsis` around what its child episodes already show. Don't invent beats no episode synopsis covers. When a finding cites an episode (e.g. `season:2 / episode:5`), first ask whether the volume synopsis can summarize what that episode shows without contradicting a neighbor. Empty/null episode synopses mean that issue hasn't been drafted yet; treat that volume as load-bearing on its own `synopsis` only.2. **Read each finding's `problem` + `suggestion`.** The suggestion is a hint, not gospel — feel free to take a different path if it cleans up the arc better, but the resulting arc MUST make the finding go away.3. **Volume-count-vs-weight mismatches** (the most common finding) — usually the right fix is to **trim or expand a volume's `synopsis`** so it matches its `episodeCountTarget`, OR adjust `episodeCountTarget` toward the structural recommendation. Don't split a volume into two unless the structural recommendation calls for more volumes than currently exist.4. **Character contradictions** — adjust the offending volume's `synopsis` (or the protagonist arc) so the contradiction disappears. Do not silently delete the contradicting beat — replace it with one that preserves the dramatic intent.5. **Dropped subplots** — add the missing payoff to a later volume's `synopsis` or `endingHook`, OR remove the dangling setup from the earlier volume if the payoff would derail the arc.6. **Unresolved finale hooks / theme drift** — surface the missing theme or arc payoff in the final volume's `synopsis`.7. **Preserve volume `id`** for every existing volume you keep. Only assign no `id` to brand-new volumes you are adding. If you remove a volume, simply omit it from the response — the server will reconcile child issues separately.-8. **Do NOT edit per-episode (issue) records.** Those are the user's hand-authored scripts. If a finding only resolves by deleting issues, write that in the `notes` field instead of doing it.+8. **Correct an episode synopsis when the contradiction *originates* in that episode.** Sometimes a finding can't be fixed at the volume level because the wrong content lives in a specific episode's `synopsis` — e.g. an episode stages an event that a later volume reserves as its own "first" occurrence, or a promised through-line silently disappears from the episodes that should carry it. In those cases the only convergent fix is to rewrite the offending episode's `synopsis` so it stops contradicting the rest of the arc. Return those rewrites in the `episodes[]` output array below, keyed by `seasonNumber` + `episodeNumber`. These are early planning synopses (no script has been drafted yet), so editing them is safe and is preferred over papering over the conflict at the volume level. Rules: edit an episode synopsis ONLY when a finding genuinely originates there; make the smallest change that removes the contradiction while preserving the episode's dramatic purpose; never delete an episode (omit it from `episodes[]` to leave it untouched). If a finding could only be resolved by removing issues entirely, write that in the `notes` field instead of doing it.## Output contract@@ -115,8 +115,17 @@ Return ONLY valid JSON matching this shape — no prose, no markdown fence, no c"themes": ["string"]}],+ "episodes": [+ {+ "seasonNumber": 2,+ "episodeNumber": 13,+ "synopsis": "string (the corrected episode synopsis — only for episodes whose own content caused a finding)"+ }+ ],"notes": "string (optional — flag any finding you could only partially resolve, and explain why. Empty string if every finding is fully addressed.)"}```The `seasons[]` array must be the FULL list of volumes you want the series to have after the resolve — not a delta. Any current volume not in the response is treated as removed.++The `episodes[]` array is a SPARSE list of episode-synopsis corrections — include only the episodes you actually rewrote (per rule 8). Omit the array entirely (or leave it empty) when every finding was resolved at the arc/volume level. Episodes you don't list are left exactly as they are.diff --git a/scripts/migrations/120-arc-resolve-episode-corrections.js b/scripts/migrations/120-arc-resolve-episode-corrections.jsnew file mode 100644index 0000000000..7c23b2e69e--- /dev/null+++ b/scripts/migrations/120-arc-resolve-episode-corrections.js@@ -0,0 +1,49 @@+/**+ * Update the `pipeline-arc-resolve` stage prompt to add an episode-correction+ * channel.+ *+ * The arc auto-resolve pass used to rewrite only the arc + volume/season+ * synopses and was explicitly forbidden from touching episodes. That made any+ * finding whose contradiction *originates* inside one episode's planning+ * synopsis structurally unresolvable — every verify round re-flagged it because+ * the offending episode text never changed, so the autopilot's arc-verify loop+ * could never converge and always paused for human review.+ *+ * The new prompt lets the resolver return a sparse `episodes[]` array of+ * corrected episode synopses (keyed by seasonNumber + episodeNumber), which+ * `resolveVerifyIssues` writes back to each issue's `idea.input` seed. Editing+ * is safe at the arc-verify gate because no script has been drafted yet.+ *+ * Strategy: hash-driven prompt-replace via `./_lib.js`. Idempotent.+ */++import { makePromptReplaceMigration } from './_lib.js';++export const ACCEPTED_OLD_MD5 = {+ 'pipeline-arc-resolve.md': [+ '5b340885c6e8f8afc63424d6b5bc7eb7', // pre-120 (episodes forbidden)+ ],+};++export const NEW_SHIPPED_MD5 = {+ 'pipeline-arc-resolve.md': 'cc27b4da1d1a13c35e35d1c2d6183815', // post-120 (episodes[] channel)+};++const { applyMigration, up } = makePromptReplaceMigration({+ accepted: ACCEPTED_OLD_MD5,+ current: NEW_SHIPPED_MD5,+ label: 'arc-resolve stage prompt',+ customizedHint: (filename) =>+ ` To add the episode-correction channel manually, diff:\n` ++ ` data.reference/prompts/stages/${filename}\n` ++ ` against your current:\n` ++ ` data/prompts/stages/${filename}\n` ++ ` and merge instruction 8 + the episodes[] output field.`,+ skipFooter: (count) =>+ `⚠️ ${count} prompt(s) could not be auto-updated because they were customized.\n` ++ ` Arc auto-resolve will keep working but won't be able to fix episode-level\n` ++ ` contradictions until you merge the episodes[] channel manually.`,+});++export { applyMigration };+export default { up };diff --git a/server/routes/pipeline/autopilot.js b/server/routes/pipeline/autopilot.jsindex e18d4fd54e..65dd7a8dd7 100644--- a/server/routes/pipeline/autopilot.js+++ b/server/routes/pipeline/autopilot.js@@ -31,6 +31,10 @@ const autopilotStartSchema = z.object({target: z.enum(['auto', 'text', 'visual']).optional().default('auto'),// Create CoS tasks for capability gaps (Phase 3).fileGaps: z.boolean().optional().default(false),+ // Restrict a multi-format (comic+tv) series to one format's scripts for this+ // run — e.g. ['comic'] produces the comic draft and skips teleplay generation.+ // Absent/empty = author every format the series targets.+ targetFormats: z.array(z.enum(['comic', 'tv'])).optional(),// Per-run convergence bounds for the verify/review loops (0 = skip that gate).// When omitted, the autopilot falls back to the persisted// pipelineEditorialChecks.{maxArcVerifyRounds,maxEditorialRounds} setting, thendiff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.jsindex e37ca8103f..8cd0f136af 100644--- a/server/services/pipeline/arcPlanner.test.js+++ b/server/services/pipeline/arcPlanner.test.js@@ -851,6 +851,117 @@ describe('arcPlanner — resolveVerifyIssues', () => {expect(out.series.arc.tickingClock?.enabled).toBe(true);expect(out.series.arc.tickingClock?.label).toBe('The dam breaks');});++ it('applies episode-synopsis corrections the resolve LLM returns (heals episode-level findings)', async () => {+ const s = await setupSeries();+ await seriesSvc.updateSeries(s.id, { arc: { logline: 'L' } });+ const season = await seasonsSvc.createSeason(s.id, { title: 'Vol 1', episodeCountTarget: 1 });+ const issue = await issuesSvc.createIssue({ seriesId: s.id, seasonId: season.id, title: 'Ep' });+ await issuesSvc.updateStage(issue.id, 'idea', { input: 'old synopsis that stages the Atrium', status: 'empty' });+ const fresh = await issuesSvc.getIssue(issue.id);++ stageRunnerSpy = vi.fn(async () => ({+ content: {+ arc: { logline: 'L2', summary: 'S', themes: [], protagonistArc: '' },+ seasons: [{ id: season.id, number: season.number, title: 'Vol 1', logline: '', synopsis: '', endingHook: '', episodeCountTarget: 1 }],+ episodes: [{ seasonNumber: season.number, episodeNumber: fresh.number, synopsis: 'corrected — the Atrium is NOT convened here' }],+ notes: '',+ },+ runId: 'r', providerId: 'p', model: 'm',+ }));++ const out = await planner.resolveVerifyIssues(s.id, {+ findings: [{ severity: 'high', problem: 'episode 1 stages the Atrium', suggestion: 'move it' }],+ });++ expect(out.episodesResolved).toHaveLength(1);+ expect(out.episodesResolved[0]).toMatchObject({ issueId: issue.id, number: fresh.number, clearedBeats: false });+ const updated = await issuesSvc.getIssue(issue.id);+ expect(updated.stages.idea.input).toBe('corrected — the Atrium is NOT convened here');+ });++ it('clears stale beats when correcting an episode that was already expanded', async () => {+ const s = await setupSeries();+ await seriesSvc.updateSeries(s.id, { arc: { logline: 'L' } });+ const season = await seasonsSvc.createSeason(s.id, { title: 'Vol 1', episodeCountTarget: 1 });+ const issue = await issuesSvc.createIssue({ seriesId: s.id, seasonId: season.id, title: 'Ep' });+ await issuesSvc.updateStage(issue.id, 'idea', { input: 'old synopsis', output: 'BEAT 1\nBEAT 2', status: 'ready' });+ const fresh = await issuesSvc.getIssue(issue.id);++ stageRunnerSpy = vi.fn(async () => ({+ content: {+ arc: { logline: 'L2', summary: 'S', themes: [], protagonistArc: '' },+ seasons: [{ id: season.id, number: season.number, title: 'Vol 1', logline: '', synopsis: '', endingHook: '', episodeCountTarget: 1 }],+ episodes: [{ seasonNumber: season.number, episodeNumber: fresh.number, synopsis: 'corrected synopsis' }],+ notes: '',+ },+ runId: 'r', providerId: 'p', model: 'm',+ }));++ const out = await planner.resolveVerifyIssues(s.id, {+ findings: [{ severity: 'high', problem: 'contradiction', suggestion: 'fix' }],+ });++ expect(out.episodesResolved[0].clearedBeats).toBe(true);+ const updated = await issuesSvc.getIssue(issue.id);+ expect(updated.stages.idea.input).toBe('corrected synopsis');+ expect(updated.stages.idea.output).toBe(''); // stale beats cleared so beatSheet regenerates+ expect(updated.stages.idea.status).toBe('empty');+ });++ it('leaves a locked idea stage untouched and reports it skipped', async () => {+ const s = await setupSeries();+ await seriesSvc.updateSeries(s.id, { arc: { logline: 'L' } });+ const season = await seasonsSvc.createSeason(s.id, { title: 'Vol 1', episodeCountTarget: 1 });+ const issue = await issuesSvc.createIssue({ seriesId: s.id, seasonId: season.id, title: 'Ep' });+ await issuesSvc.updateStage(issue.id, 'idea', { input: 'frozen synopsis', status: 'edited', locked: true });+ const fresh = await issuesSvc.getIssue(issue.id);++ stageRunnerSpy = vi.fn(async () => ({+ content: {+ arc: { logline: 'L2', summary: 'S', themes: [], protagonistArc: '' },+ seasons: [{ id: season.id, number: season.number, title: 'Vol 1', logline: '', synopsis: '', endingHook: '', episodeCountTarget: 1 }],+ episodes: [{ seasonNumber: season.number, episodeNumber: fresh.number, synopsis: 'attempted overwrite' }],+ notes: '',+ },+ runId: 'r', providerId: 'p', model: 'm',+ }));++ const out = await planner.resolveVerifyIssues(s.id, {+ findings: [{ severity: 'high', problem: 'contradiction', suggestion: 'fix' }],+ });++ expect(out.episodesResolved[0].skipped).toBe('locked');+ const updated = await issuesSvc.getIssue(issue.id);+ expect(updated.stages.idea.input).toBe('frozen synopsis'); // unchanged+ });+});++describe('arcPlanner — shapeEpisodeResolutions', () => {+ it('keeps well-formed entries and drops malformed ones', () => {+ const out = planner.shapeEpisodeResolutions([+ { seasonNumber: 2, episodeNumber: 13, synopsis: ' fixed ' },+ { episodeNumber: 5, synopsis: 'no season is fine' },+ { seasonNumber: 1, episodeNumber: 2 }, // no synopsis → dropped+ { seasonNumber: 1, episodeNumber: 'x', synopsis: 'bad number' }, // non-int → dropped+ { seasonNumber: 1, synopsis: 'no episode number' }, // → dropped+ ]);+ expect(out).toEqual([+ { seasonNumber: 2, episodeNumber: 13, synopsis: 'fixed' },+ { seasonNumber: null, episodeNumber: 5, synopsis: 'no season is fine' },+ ]);+ });++ it('returns [] for non-array input', () => {+ expect(planner.shapeEpisodeResolutions(undefined)).toEqual([]);+ expect(planner.shapeEpisodeResolutions(null)).toEqual([]);+ expect(planner.shapeEpisodeResolutions('nope')).toEqual([]);+ });++ it('caps at RESOLVE_EPISODE_MAX entries', () => {+ const many = Array.from({ length: 60 }, (_, i) => ({ episodeNumber: i + 1, synopsis: `s${i}` }));+ expect(planner.shapeEpisodeResolutions(many)).toHaveLength(50);+ });});describe('arcPlanner — commitSeasonsWithRemap', () => {diff --git a/server/services/pipeline/arcPlanner/arcCore.js b/server/services/pipeline/arcPlanner/arcCore.jsindex 70d2841c8b..68505fb020 100644--- a/server/services/pipeline/arcPlanner/arcCore.js+++ b/server/services/pipeline/arcPlanner/arcCore.js@@ -11,12 +11,12 @@ import { runStagedLLM } from '../../../lib/stageRunner.js';import { ServerError } from '../../../lib/errorHandler.js';import { stripAnsi } from '../../../lib/ansiStrip.js';import { ARC_LOCKABLE_FIELDS, getSeries, updateSeries } from '../series.js';-import { listIssues, recomputeIssueNumbersForSeries, updateIssue } from '../issues.js';+import { listIssues, recomputeIssueNumbersForSeries, updateIssue, updateStageWithLatest } from '../issues.js';import { emitRecordUpdated, withReexportSuppressed } from '../../sharing/recordEvents.js';import { getSeason } from '../seasons.js';import { READER_MAP_BEAT_KINDS, buildSeason, cleanThemes, renderArcShapeGuidance, renderArcShapePositionSummary, sanitizeArc, sanitizeReaderMap, sanitizeSeason, sanitizeSeasonList } from '../../../lib/storyArc.js';import { runPromptRefineRaw, trimChanges } from '../refineHelpers.js';-import { ERR_VALIDATION, SHAPE_GUIDANCE_NONE, appendTickingClock, buildArcBaseContext, buildArcOverviewContext, buildNeighborVolumes, buildReaderMapContext, buildResolveContext, buildVerifyContext, compareIssuesByPosition, makeErr, renderVolumeIssue, resolveWorldContext, shapeFindings, shapeSeasonOutlines, shapeVerifyIssues } from './context.js';+import { ERR_VALIDATION, SHAPE_GUIDANCE_NONE, appendTickingClock, buildArcBaseContext, buildArcOverviewContext, buildNeighborVolumes, buildReaderMapContext, buildResolveContext, buildVerifyContext, compareIssuesByPosition, makeErr, renderVolumeIssue, resolveWorldContext, shapeEpisodeResolutions, shapeFindings, shapeSeasonOutlines, shapeVerifyIssues } from './context.js';export async function generateArcOverview(seriesId, options = {}) {const series = await getSeries(seriesId);@@ -427,18 +427,86 @@ export async function resolveVerifyIssues(seriesId, options = {}) {const { series: updated } = await commitSeasonsWithRemap(series, { arc, seasons });+ // Apply any episode-level synopsis corrections the resolver returned. This is+ // the heal capability that lets episode-scoped findings converge: when a+ // contradiction originates inside one episode's planning synopsis (e.g. it+ // stages an event a later volume reserves as its own "first"), the only fix is+ // to rewrite that episode — the volume/arc layer can't make it go away. Done+ // here (after the arc+season commit) against the freshest issue set.+ const episodesResolved = await applyEpisodeResolutions(+ seriesId,+ updated,+ shapeEpisodeResolutions(content?.episodes),+ );+const notes = typeof content?.notes === 'string' ? content.notes.trim().slice(0, 2000) : '';return {series: updated,applied: true,notes,findings,+ episodesResolved,runId,providerId,model,};}+/**+ * Apply the auto-resolve pass's episode-synopsis corrections to the canonical+ * issue records. Each correction targets one issue by its series-global episode+ * number (with `seasonNumber` as a disambiguating cross-check). Writes the new+ * synopsis to the issue's `idea.input` seed. If that issue already has expanded+ * beats (`idea.output`) — only possible on a resume where beats ran in a prior+ * pass — they are cleared and the stage reset to `empty` so the beat-sheet step+ * regenerates them from the corrected synopsis instead of leaving stale beats+ * that still encode the contradiction.+ *+ * A locked `idea` stage is left untouched (the user froze it) and reported as+ * skipped. Returns `[{ issueId, number, seasonNumber, clearedBeats, skipped }]`+ * for the conductor to surface; never throws — a bad match is dropped, not fatal.+ */+export async function applyEpisodeResolutions(seriesId, series, episodes) {+ if (!Array.isArray(episodes) || episodes.length === 0) return [];+ const issues = await listIssues({ seriesId });+ const seasonIdByNumber = new Map(+ (series?.seasons || []).filter((s) => Number.isInteger(s?.number)).map((s) => [s.number, s.id]),+ );+ const applied = [];+ for (const edit of episodes) {+ const wantSeasonId = edit.seasonNumber != null ? seasonIdByNumber.get(edit.seasonNumber) : null;+ // Prefer an issue that matches BOTH season and number; fall back to the+ // series-global number alone (issue numbers are unique across the series).+ const issue = issues.find((i) => i.number === edit.episodeNumber && (!wantSeasonId || i.seasonId === wantSeasonId))+ || issues.find((i) => i.number === edit.episodeNumber);+ if (!issue) {+ // A correction we can't land is a silent path to non-convergence — log it+ // so a number-scheme mismatch (per-season vs series-global) is diagnosable.+ console.log(`⚠️ arc-resolve: no issue matched episode correction (season ${edit.seasonNumber}, episode ${edit.episodeNumber})`);+ applied.push({ seasonNumber: edit.seasonNumber, episodeNumber: edit.episodeNumber, skipped: 'no-match' });+ continue;+ }+ if (issue.stages?.idea?.locked === true) {+ applied.push({ issueId: issue.id, number: issue.number, seasonNumber: edit.seasonNumber, skipped: 'locked' });+ continue;+ }+ const hadBeats = !!(issue.stages?.idea?.output && issue.stages.idea.output.trim());+ await updateStageWithLatest(issue.id, 'idea', (current) => (+ hadBeats+ ? { input: edit.synopsis, output: '', status: 'empty', errorMessage: '' }+ : { input: edit.synopsis }+ )).catch((err) => {+ console.log(`⚠️ arc-resolve: episode ${edit.episodeNumber} synopsis edit failed: ${err.message}`);+ });+ applied.push({ issueId: issue.id, number: issue.number, seasonNumber: edit.seasonNumber, clearedBeats: hadBeats });+ }+ if (applied.length) {+ const fixed = applied.filter((a) => !a.skipped).length;+ console.log(`📝 arc-resolve: corrected ${fixed} episode synopsis(es) for series ${seriesId.slice(0, 12)}`);+ }+ return applied;+}+// Preserve per-field arc locks. When `currentSeries.locked.arcFields[k]` is// true, the incoming arc's value for `k` is replaced with the existing one so// auto-resolve / regenerate flows can rewrite unlocked fields withoutdiff --git a/server/services/pipeline/arcPlanner/context.js b/server/services/pipeline/arcPlanner/context.jsindex 2fc3c5d0ae..425e13d9d7 100644--- a/server/services/pipeline/arcPlanner/context.js+++ b/server/services/pipeline/arcPlanner/context.js@@ -8,7 +8,7 @@*/import { MANUSCRIPT_TYPES } from '../series.js';-import { listIssues } from '../issues.js';+import { listIssues, STAGE_INPUT_MAX } from '../issues.js';import { ARC_ROLES as ARC_ROLE_LIST, ARC_SHAPE_IDS, READER_MAP_BEAT_KINDS, buildSeason, renderArcShapeGuidance, renderTickingClock, sanitizeSeasonList } from '../../../lib/storyArc.js';import { composeStyleNotes } from '../../../lib/styleGuide.js';import { describeStructure, recommendStructure } from '../../../lib/seasonStructure.js';@@ -491,6 +491,37 @@ export function shapeVerifyIssues(rawIssues) {return out;}+// Max episode-synopsis corrections an auto-resolve pass may apply in one round.+// A bound (mirrors RESOLVE_FINDING_MAX) so a runaway LLM response can't rewrite+// the entire episode lineup in a single convergence step.+export const RESOLVE_EPISODE_MAX = 50;++/**+ * Shape the auto-resolve pass's optional `episodes[]` output — a SPARSE list of+ * episode-synopsis corrections the resolver applies when a finding originates at+ * the episode level (see pipeline-arc-resolve.md rule 8). Each entry must carry+ * an integer `episodeNumber` and a non-empty `synopsis`; `seasonNumber` is+ * optional disambiguation. Malformed entries are dropped so a partial response+ * never throws.+ */+export function shapeEpisodeResolutions(rawEpisodes) {+ if (!Array.isArray(rawEpisodes)) return [];+ const out = [];+ for (const raw of rawEpisodes) {+ const synopsis = typeof raw?.synopsis === 'string' ? raw.synopsis.trim() : '';+ const episodeNumber = Number(raw?.episodeNumber);+ if (!synopsis || !Number.isInteger(episodeNumber)) continue;+ const seasonNumberRaw = Number(raw?.seasonNumber);+ out.push({+ seasonNumber: Number.isInteger(seasonNumberRaw) ? seasonNumberRaw : null,+ episodeNumber,+ synopsis: synopsis.slice(0, STAGE_INPUT_MAX),+ });+ if (out.length >= RESOLVE_EPISODE_MAX) break;+ }+ return out;+}+// Set exactly one of `beats` / `synopsis` so the prompt's beat-level checks// don't run against synopsis-only issues (and vice-versa). Beats land in// idea.output once the LLM-expand pass runs; before that, idea.input stilldiff --git a/server/services/pipeline/seriesAutopilot.js b/server/services/pipeline/seriesAutopilot.jsindex 7dc41eef30..2b680de6a1 100644--- a/server/services/pipeline/seriesAutopilot.js+++ b/server/services/pipeline/seriesAutopilot.js@@ -168,11 +168,26 @@ const byNumber = (a, b) => (a?.number ?? 9999) - (b?.number ?? 9999);// from its targetFormat. prose is the intermediate source the scripts adapt// from — we gate on the final scripts so a script-first import (prose empty,// script authored) is already considered ready and never regenerated.-export function requiredScriptStages(series) {+export function requiredScriptStages(series, options = {}) {const fmt = series?.targetFormat || 'comic+tv';- if (fmt === 'comic') return ['comicScript'];- if (fmt === 'tv') return ['teleplay'];- return ['comicScript', 'teleplay'];+ // Per-run format restriction: a multi-format (comic+tv) series can be driven+ // to just one format's scripts in a single autopilot run — e.g. "produce the+ // comic draft only, skip the 24 teleplays." `options.targetFormats` is a+ // subset of ['comic','tv']; absent/empty means "all formats the series wants".+ const restrict = Array.isArray(options?.targetFormats) && options.targetFormats.length+ ? options.targetFormats+ : null;+ const wantComic = fmt.includes('comic') && (!restrict || restrict.includes('comic'));+ const wantTv = fmt.includes('tv') && (!restrict || restrict.includes('tv'));+ const stages = [];+ if (wantComic) stages.push('comicScript');+ if (wantTv) stages.push('teleplay');+ // Never strand the run with zero required script stages (which would mark every+ // issue text-ready with no script authored). If the restriction excludes+ // everything this series supports, ignore it and fall back to the series' own+ // formats.+ if (stages.length === 0) return requiredScriptStages(series);+ return stages;}export function isComicTarget(series) {@@ -194,8 +209,8 @@ function orderedIssues(issues) {return [...(Array.isArray(issues) ? issues : [])].sort(compareIssuesByPosition);}-function textReady(issue, series) {- return requiredScriptStages(series).every((stageId) => isStageReady(issue.stages?.[stageId]));+function textReady(issue, series, options = {}) {+ return requiredScriptStages(series, options).every((stageId) => isStageReady(issue.stages?.[stageId]));}// Structural script gate (pure): does the comic script parse into >=1 page with@@ -294,7 +309,7 @@ export function resolveNextStep(series, issues, runState = {}, options = {}) {// STEP 4b — per-issue text stages (prose + required scripts).for (const issue of ordered) {if (setHas(runState.textAttempted, issue.id)) continue;- if (!textReady(issue, series)) {+ if (!textReady(issue, series, options)) {return { kind: 'textStages', issueId: issue.id, reason: 'prose / scripts not ready' };}}@@ -482,8 +497,12 @@ async function runArcVerify(seriesId, record) {// step can't overspend the daily cap mid-loop.const beforeResolve = await budgetPause();if (beforeResolve) return beforeResolve;- await resolveVerifyIssues(seriesId, { findings: blocking, ...providerOverrideOpts(record) });+ const resolved = await resolveVerifyIssues(seriesId, { findings: blocking, ...providerOverrideOpts(record) });await recordDomainUsage('cos', { actions: 1 });+ broadcast(seriesId, {+ type: 'resolve:round', scope: 'arc', round,+ episodesEdited: Array.isArray(resolved?.episodesResolved) ? resolved.episodesResolved.length : 0,+ });}return {};}@@ -516,7 +535,7 @@ async function runText(issueId, record) {// spend LLM calls populating the off-target script across every issue.const preIssue = await getIssue(issueId);const preSeries = await getSeries(preIssue.seriesId).catch(() => null);- const scripts = requiredScriptStages(preSeries);+ const scripts = requiredScriptStages(preSeries, record.options);// Forward the run's provider/model override so prose + scripts honor it like// every other step (autoRunner threads these into generateStage).await autoRunner.startAutoRunTextStages(issueId, { force: false, scripts, ...providerIdOpts(record) });@@ -530,8 +549,8 @@ async function runText(issueId, record) {// required stages landed and pause for review if they didn't.const issue = await getIssue(issueId);const series = await getSeries(issue.seriesId).catch(() => null);- if (!textReady(issue, series)) {- const missing = requiredScriptStages(series).filter((s) => !isStageReady(issue.stages?.[s]));+ if (!textReady(issue, series, record.options)) {+ const missing = requiredScriptStages(series, record.options).filter((s) => !isStageReady(issue.stages?.[s]));return {pause: true,reason: `text generation for issue ${issue.number ?? issueId} did not produce required stage(s): ${missing.join(', ')}`,@@ -990,7 +1009,7 @@ function buildDryRunPlan(series, issues, options) {const beatsNeeded = seasons.filter((s) =>ordered.some((i) => i.seasonId === s.id && !isStageReady(i.stages?.idea))).length;if (beatsNeeded) plan.push({ kind: 'beatSheet', count: beatsNeeded });- const textNeeded = ordered.filter((i) => !textReady(i, series)).length;+ const textNeeded = ordered.filter((i) => !textReady(i, series, options)).length;if (textNeeded) plan.push({ kind: 'textStages', count: textNeeded });if (isComicTarget(series)) plan.push({ kind: 'scriptVerify', count: ordered.length });const edRounds = Number.isInteger(options?.maxEditorialRounds) ? options.maxEditorialRounds : MAX_EDITORIAL_ROUNDS;diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.jsindex faf9ffb879..f9738e7b42 100644--- a/server/services/pipeline/seriesAutopilot.test.js+++ b/server/services/pipeline/seriesAutopilot.test.js@@ -366,6 +366,21 @@ describe('requiredScriptStages / scriptStructurallyReady', () => {expect(requiredScriptStages({})).toEqual(['comicScript', 'teleplay']);});+ it('restricts a comic+tv series to one format via options.targetFormats', () => {+ const series = { targetFormat: 'comic+tv' };+ expect(requiredScriptStages(series, { targetFormats: ['comic'] })).toEqual(['comicScript']);+ expect(requiredScriptStages(series, { targetFormats: ['tv'] })).toEqual(['teleplay']);+ expect(requiredScriptStages(series, { targetFormats: ['comic', 'tv'] })).toEqual(['comicScript', 'teleplay']);+ });++ it('ignores a restriction the series cannot satisfy (never strands the run with zero scripts)', () => {+ // A comic-only series asked to produce tv-only falls back to its own format.+ expect(requiredScriptStages({ targetFormat: 'comic' }, { targetFormats: ['tv'] })).toEqual(['comicScript']);+ // Empty / non-array restrictions are no-ops.+ expect(requiredScriptStages({ targetFormat: 'comic+tv' }, { targetFormats: [] })).toEqual(['comicScript', 'teleplay']);+ expect(requiredScriptStages({ targetFormat: 'comic+tv' }, {})).toEqual(['comicScript', 'teleplay']);+ });+it('passes a parseable comic script and fails an unparseable one', () => {expect(scriptStructurallyReady({ stages: { comicScript: ready(VALID_SCRIPT) } })).toBe(true);expect(scriptStructurallyReady({ stages: { comicScript: ready('just some prose, no pages') } })).toBe(false);