Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: repair duplicate volumes before autopilot generation

[._.]/ Adam Eivy4c7c54a29367
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 2e82f4130f..caa0dfa840 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -104,3 +104,5 @@
- **Series autopilot no longer manufactures the duplicate volumes it then gets stuck on.** Arc auto-resolve matched the LLM's rewritten volumes back to your existing ones by `id` alone — but the resolve prompt routinely returns a rewritten volume *without* echoing its id, and that read as "a brand new volume", minting a second record. In the autopilot's unlock-for-run mode, which deliberately refuses to let a rewrite delete a volume, the original was then re-inserted right next to the mint. So every auto-resolve round left one more `Volume 1` than it started with, arc-verify filed the pile-up as a blocking finding, and the run paused for "no net progress" while pointing at damage it had caused itself. A rewrite is now matched to the record it is a rewrite *of* — by id, then title, then an unambiguous volume number — and lands on that record, keeping its episodes, themes and lock attached. There is no positional guessing: a volume that genuinely doesn't match still mints, because a wrong guess would overwrite one volume's prose with another's.
- **An arc write now repairs duplicate volume numbers instead of preserving them forever.** Two volumes sharing a number is not a state you can act on — the Arc Canvas draws both, an export can't tell which is canonical, and arc-verify blocks on it every round — but the sanitizer only ever de-duplicated by `id`, so the pair survived every pass untouched. Any ordinary arc write now collapses them, keeping whichever record has the strongest claim to the episodes underneath it (a volume you locked, else the one holding the most episodes, else the original), and re-points episodes stranded under the absorbed copies onto the survivor rather than dropping them into "Un-grouped". Content is only ever rescued, never overwritten: a field the survivor left empty is back-filled from the newest copy, and a field it already has is kept. A number shared by *two locked volumes* is deliberately left alone and warns instead — only you can say which freeze was meant. Installs already carrying duplicates heal on their next arc write, with no migration to run.
+
+- **Autopilot now repairs duplicate volumes before it can waste work filling them.** Resume previously looked for empty volumes before any arc write reached the duplicate-volume self-heal, so malformed empty copies could receive a full issue breakdown only to be absorbed later. A zero-cost structural preflight now runs first, keeps existing issues attached to the canonical volume, and only then considers episode generation. If locks make the repair ambiguous, the run pauses before spending and asks for full edit control. Dry-run estimates mirror the same repair and no longer charge issue-generation calls for copies that will be absorbed.
diff --git a/client/src/components/pipeline/AutopilotPanel.jsx b/client/src/components/pipeline/AutopilotPanel.jsx
index 2dc32be68a..835baaecb2 100644
--- a/client/src/components/pipeline/AutopilotPanel.jsx
+++ b/client/src/components/pipeline/AutopilotPanel.jsx
@@ -238,6 +238,7 @@ const SEVERITY_COLORS = {
const STEP_LABELS = {
unlockLocks: 'Unlocking series records',
generateArc: 'Generating arc',
+ repairArcStructure: 'Repairing volume structure',
generateEpisodes: 'Generating episodes',
verifyArc: 'Verifying arc',
foundationGate: 'Judging foundation',
diff --git a/server/services/pipeline/arcPlanner/arcCore.js b/server/services/pipeline/arcPlanner/arcCore.js
index 7abd362a2d..63a2ff1df7 100644
--- a/server/services/pipeline/arcPlanner/arcCore.js
+++ b/server/services/pipeline/arcPlanner/arcCore.js
@@ -859,7 +859,7 @@ export function hasDuplicateSeasonNumbers(seasons) {
* which freeze was intended. Those groups keep warning every write, which is
* the correct nag.
*/
-export function collapseDuplicateSeasonNumbers(seasons, issueCountBySeasonId = new Map()) {
+export function collapseDuplicateSeasonNumbers(seasons, issueCountBySeasonId = new Map(), { log = true } = {}) {
const absorbed = new Map();
if (!Array.isArray(seasons)) return { seasons, absorbed };
const byNumber = new Map();
@@ -878,9 +878,11 @@ export function collapseDuplicateSeasonNumbers(seasons, issueCountBySeasonId = n
}
const lockedCount = group.filter((s) => s.locked === true).length;
if (lockedCount > 1) {
- console.warn(
- `⚠️ collapseDuplicateSeasonNumbers: volume ${number} has ${group.length} records including ${lockedCount} locked — left intact, unlock all but one to collapse`,
- );
+ if (log) {
+ console.warn(
+ `⚠️ collapseDuplicateSeasonNumbers: volume ${number} has ${group.length} records including ${lockedCount} locked — left intact, unlock all but one to collapse`,
+ );
+ }
survivors.push(...group);
continue;
}
@@ -894,9 +896,11 @@ export function collapseDuplicateSeasonNumbers(seasons, issueCountBySeasonId = n
for (const s of group) {
if (s.id !== survivor.id) absorbed.set(s.id, survivor.id);
}
- console.warn(
- `⚠️ collapseDuplicateSeasonNumbers: volume ${number} had ${group.length} records — kept ${survivor.id} (${episodes(survivor)} episode(s)), absorbed ${group.length - 1} into it`,
- );
+ if (log) {
+ console.warn(
+ `⚠️ collapseDuplicateSeasonNumbers: volume ${number} had ${group.length} records — kept ${survivor.id} (${episodes(survivor)} episode(s)), absorbed ${group.length - 1} into it`,
+ );
+ }
}
// Re-sort: `sanitizeSeasonList`'s number ordering is the contract consumers
// render straight from, and the group walk above emits in first-seen order.
diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.js
index b5a7732a04..2013bce4cb 100644
--- a/server/services/pipeline/seriesAutopilot.test.js
+++ b/server/services/pipeline/seriesAutopilot.test.js
@@ -199,6 +199,7 @@ const seasonsSvc = await import('./seasons.js');
const issuesSvc = await import('./issues.js');
const autopilot = await import('./seriesAutopilot.js');
const arcPlanner = await import('./arcPlanner.js');
+const { commitSeasonsWithRemap: realCommitSeasonsWithRemap } = await import('./arcPlanner/arcCore.js');
const { stageContentOf } = await import('./textStages.js');
const { resolveNextStep, requiredScriptStages, scriptStructurallyReady, visualReady, wantsComic } = autopilot;
@@ -426,6 +427,31 @@ describe('resolveNextStep (pure)', () => {
expect(resolveNextStep(arcOnly, [], { arcAttempted: true }).kind).not.toBe('generateArc');
});
+ it('repairs duplicate volume numbers before generating episodes for empty duplicates', () => {
+ const duplicate = {
+ targetFormat: 'comic', arc: { logline: 'L', summary: 'S' },
+ seasons: [{ id: 'se1', number: 1 }, { id: 'dup1', number: 1 }, { id: 'dup2', number: 1 }],
+ };
+ const step = resolveNextStep(duplicate, [
+ { id: 'i1', seasonId: 'se1', number: 1, arcPosition: 1, stages: {} },
+ ]);
+ expect(step.kind).toBe('repairArcStructure');
+ });
+
+ it('dry-run previews duplicate-volume repair without charging episode generation for absorbed records', () => {
+ const duplicate = {
+ targetFormat: 'comic', arc: { logline: 'L', summary: 'S' },
+ // A lock makes the empty first record the survivor; the issue-bearing
+ // duplicate is absorbed and its issue must be projected onto that survivor.
+ seasons: [{ id: 'se1', number: 1, locked: true }, { id: 'dup1', number: 1 }],
+ };
+ const plan = autopilot.__testing.buildDryRunPlan(duplicate, [
+ { id: 'i1', seasonId: 'dup1', number: 1, arcPosition: 1, stages: {} },
+ ], {});
+ expect(plan[0]).toMatchObject({ kind: 'repairArcStructure', estActions: 0 });
+ expect(plan.some((entry) => entry.kind === 'generateEpisodes')).toBe(false);
+ });
+
it('dry-run plan includes generateArc for an arc-only series (parity with execute)', () => {
const plan = autopilot.__testing.buildDryRunPlan(
{ targetFormat: 'comic', arc: { logline: 'L', summary: 'S' }, seasons: [] }, [], {},
@@ -812,6 +838,14 @@ describe('resolveNextStep — unlock pre-pass ordering', () => {
it('runs at most once per run (latched by runState.locksUnlocked)', () => {
expect(resolveNextStep(bare, [], { locksUnlocked: true }, { unlockForRun: true }).kind).toBe('generateArc');
});
+ it('unlocks before repairing duplicate volume structure', () => {
+ const duplicate = {
+ targetFormat: 'comic', arc: { logline: 'L', summary: 'S' },
+ seasons: [{ id: 'se1', number: 1, locked: true }, { id: 'dup1', number: 1, locked: true }],
+ };
+ expect(resolveNextStep(duplicate, [], {}, { unlockForRun: true }).kind).toBe('unlockLocks');
+ expect(resolveNextStep(duplicate, [], { locksUnlocked: true }, { unlockForRun: true }).kind).toBe('repairArcStructure');
+ });
});
describe('resolveAutopilotSelfImprove (config gate)', () => {
@@ -1257,6 +1291,33 @@ async function seedComplete({ script = VALID_SCRIPT } = {}) {
return { seriesId: series.id, seasonId, issueId: issue.id };
}
+it('normalizes duplicate volume records before the conductor can seed their empty copies', async () => {
+ const { seriesId, seasonId } = await seedComplete();
+ const current = await seriesSvc.getSeries(seriesId);
+ const canonical = current.seasons.find((season) => season.id === seasonId);
+ await seriesSvc.updateSeries(seriesId, {
+ seasons: [
+ ...current.seasons,
+ { ...canonical, id: 'duplicate-volume-a', locked: false },
+ { ...canonical, id: 'duplicate-volume-b', locked: false },
+ ],
+ });
+ // The suite normally stubs this persistence boundary so conductor tests can
+ // isolate LLM behavior. Use the real deterministic commit once here: the
+ // arcPlanner store tests cover the collapse itself, while this pins the new
+ // resolver → dispatcher ordering around it.
+ arcSpies.commitSeasonsWithRemap.mockImplementationOnce(realCommitSeasonsWithRemap);
+
+ await autopilot.startSeriesAutopilot(seriesId, { includeVisual: false });
+ await waitFor(runFinished(seriesId));
+
+ const repaired = await seriesSvc.getSeries(seriesId);
+ expect(repaired.seasons).toHaveLength(1);
+ expect(repaired.seasons[0].id).toBe(seasonId);
+ expect(arcSpies.generateSeasonEpisodes).not.toHaveBeenCalled();
+ expect(autopilot.__testing.runs.get(seriesId)?.lastPayload?.type).toBe('complete');
+});
+
describe('trackConvergence (pure divergence/oscillation guard — #1571)', () => {
const { trackConvergence, DIVERGENCE_PATIENCE } = autopilot;
diff --git a/server/services/pipeline/seriesAutopilot/dispatch.js b/server/services/pipeline/seriesAutopilot/dispatch.js
index e6e311f97b..ed0b4b031e 100644
--- a/server/services/pipeline/seriesAutopilot/dispatch.js
+++ b/server/services/pipeline/seriesAutopilot/dispatch.js
@@ -5,7 +5,10 @@
import { recordDomainUsage } from '../../domainUsage.js';
import { getSeries } from '../series.js';
-import { generateArcOverview, commitSeasonsWithRemap, generateSeasonEpisodes, commitEpisodesToIssues } from '../arcPlanner.js';
+import {
+ generateArcOverview, commitSeasonsWithRemap, generateSeasonEpisodes, commitEpisodesToIssues,
+ hasDuplicateSeasonNumbers,
+} from '../arcPlanner.js';
import { providerOverrideOpts, seasonPreserveOpts } from './session.js';
import { runArcVerify, runBeats, runBeatContinuity, runFoundationGate, runText } from './childRuns.js';
import { runScriptVerify, runEditorial, runReverseOutlineRefresh, runEditorialChecksPass, runEditorialHealthGate } from './editorialSteps.js';
@@ -39,6 +42,39 @@ export async function dispatchStep(sId, step, record) {
}
return {};
}
+ case 'repairArcStructure': {
+ const current = await getSeries(sId);
+ // commitSeasonsWithRemap owns the safe duplicate-collapse + child remap,
+ // but correctly refuses every arc write while the arc freeze is set. Pause
+ // here with an actionable reason rather than turning a deterministic
+ // preflight into a generic run error (or, worse, seeding duplicate volumes).
+ if (current.locked?.arc === true) {
+ return {
+ pause: true,
+ pauseKind: 'inapplicable',
+ reason: 'Duplicate volume records must be normalized before issue generation, but the arc is locked. Resume with full edit control enabled.',
+ residual: [{ severity: 'high', location: 'series volumes', problem: 'duplicate volume numbers are blocked from repair by the arc lock' }],
+ };
+ }
+ const committed = await commitSeasonsWithRemap(
+ current,
+ { arc: current.arc, seasons: current.seasons },
+ seasonPreserveOpts(record),
+ );
+ const repaired = committed?.series ?? await getSeries(sId);
+ // Two user-locked duplicates are deliberately not collapsed by the shared
+ // helper. Stop before generation and ask for the same explicit full-control
+ // consent that clears those locks; never fill malformed records with work.
+ if (hasDuplicateSeasonNumbers(repaired.seasons)) {
+ return {
+ pause: true,
+ pauseKind: 'inapplicable',
+ reason: 'Duplicate volume records are still locked and could not be normalized. Resume with full edit control enabled.',
+ residual: [{ severity: 'high', location: 'series volumes', problem: 'multiple locked records share a volume number' }],
+ };
+ }
+ return {};
+ }
case 'generateEpisodes': {
// Mark attempted up front so an empty/invalid episode list can't re-loop
// the resolver back into generateEpisodes for the same still-empty volume.
diff --git a/server/services/pipeline/seriesAutopilot/dryRun.js b/server/services/pipeline/seriesAutopilot/dryRun.js
index e1cd785fbb..f0037d9e7b 100644
--- a/server/services/pipeline/seriesAutopilot/dryRun.js
+++ b/server/services/pipeline/seriesAutopilot/dryRun.js
@@ -5,6 +5,7 @@
*/
import { isStageReady } from '../issues.js';
+import { collapseDuplicateSeasonNumbers, hasDuplicateSeasonNumbers } from '../arcPlanner.js';
import { resolveReadinessGate } from '../editorialScore.js';
import {
MAX_ARC_VERIFY_ROUNDS, MAX_FOUNDATION_ROUNDS, MAX_BEAT_CONTINUITY_ROUNDS, MAX_EDITORIAL_ROUNDS,
@@ -31,8 +32,8 @@ import { countSeriesLocks } from './unlockPass.js';
// estimates a single LLM check.
export function buildDryRunPlan(series, issues, options, costContext = {}) {
const plan = [];
- const ordered = orderedIssues(issues);
- const seasons = Array.isArray(series?.seasons) ? [...series.seasons].sort(byNumber) : [];
+ let ordered = orderedIssues(issues);
+ let seasons = Array.isArray(series?.seasons) ? [...series.seasons].sort(byNumber) : [];
// Unlock pre-pass (opt-in). Costs nothing — it only clears lock bits — but it
// is the one step that MUTATES records the user froze by hand, so the dry-run
// plan must name it (and how many locks it would clear) before they commit.
@@ -51,6 +52,43 @@ export function buildDryRunPlan(series, issues, options, costContext = {}) {
// no volumes at all (an arc-only series), so a dry-run plan must show it too.
const noArc = !series?.arc?.logline && !series?.arc?.summary;
if (noArc || seasons.length === 0) plan.push({ kind: 'generateArc', count: 1, estActions: 1 });
+ // A present arc with duplicate volume numbers takes the deterministic repair
+ // path before any empty-volume episode generation. Preview that collapse so
+ // the plan does not advertise LLM calls for malformed records that execute
+ // will absorb. When locks would block the repair, the execute run pauses at
+ // this step, so downstream work is intentionally omitted from the plan.
+ if (!noArc && seasons.length > 0 && hasDuplicateSeasonNumbers(seasons)) {
+ const issueCounts = new Map();
+ for (const issue of ordered) {
+ if (issue.seasonId) issueCounts.set(issue.seasonId, (issueCounts.get(issue.seasonId) || 0) + 1);
+ }
+ const previewInput = options?.unlockForRun === true
+ ? seasons.map((season) => ({ ...season, locked: false }))
+ : seasons;
+ const preview = collapseDuplicateSeasonNumbers(previewInput, issueCounts, { log: false });
+ const blocked = (series?.locked?.arc === true && options?.unlockForRun !== true)
+ || hasDuplicateSeasonNumbers(preview.seasons);
+ plan.push({
+ kind: 'repairArcStructure',
+ count: 1,
+ note: blocked
+ ? 'normalize duplicate volume numbers before issue generation — pauses until full edit control clears the blocking locks'
+ : 'normalize duplicate volume numbers and keep their existing issues attached before generation',
+ estActions: 0,
+ });
+ if (blocked) return plan;
+ seasons = preview.seasons;
+ // Execute re-points children of an absorbed duplicate to the survivor in the
+ // same commit. Mirror that projected identity here so the later empty-volume
+ // and beat-sheet counts do not charge work for a survivor that will already
+ // own those issues once the repair lands.
+ if (preview.absorbed.size) {
+ ordered = ordered.map((issue) => {
+ const survivorId = preview.absorbed.get(issue.seasonId);
+ return survivorId ? { ...issue, seasonId: survivorId } : issue;
+ });
+ }
+ }
const emptySeasons = seasons.filter((s) => !ordered.some((i) => i.seasonId === s.id));
if (emptySeasons.length) plan.push({ kind: 'generateEpisodes', count: emptySeasons.length, estActions: emptySeasons.length });
// Foundation runs first at synopsis altitude. Arc/volume repairs and
diff --git a/server/services/pipeline/seriesAutopilot/stepResolver.js b/server/services/pipeline/seriesAutopilot/stepResolver.js
index d4f7a126fb..8e5aa4d187 100644
--- a/server/services/pipeline/seriesAutopilot/stepResolver.js
+++ b/server/services/pipeline/seriesAutopilot/stepResolver.js
@@ -6,7 +6,7 @@
import { parseComicScript } from '../../../lib/comicScriptParser.js';
import { isStageReady } from '../issues.js';
-import { compareIssuesByPosition } from '../arcPlanner.js';
+import { compareIssuesByPosition, hasDuplicateSeasonNumbers } from '../arcPlanner.js';
import { wantsTeaser, wantsVisual } from './config.js';
import { VISUAL_DRAFT_ENABLED } from './convergence.js';
@@ -165,6 +165,17 @@ export function resolveNextStep(series, issues, runState = {}, options = {}) {
return { kind: 'generateArc', reason: seasons.length === 0 && !noArc ? 'series has no volumes' : 'series has no arc' };
}
+ // STEP 1.5 — deterministic structural preflight. A prior arc rewrite could
+ // leave two records with the same volume number; some of those duplicates are
+ // commonly empty. Seeding their episodes first would manufacture throwaway
+ // issues before arc verification eventually reports the duplicate. Normalize
+ // the records before ANY empty-volume generation instead. The dispatcher uses
+ // commitSeasonsWithRemap, whose duplicate collapse keeps the issue-bearing
+ // survivor and re-points any children from absorbed records.
+ if (hasDuplicateSeasonNumbers(seasons)) {
+ return { kind: 'repairArcStructure', reason: 'duplicate volume numbers must be normalized before issue generation' };
+ }
+
// STEP 2 — a season with zero issues (in season order). Skip volumes already
// attempted this run so an empty episode generation can't re-loop (the
// dispatch pauses when it produces no issues).