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(pipeline): remap orphaned issues when arc/generate rewrites season ids

[._.]/ Adam Eivyb77394957dae
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 532e13d19e..f9a4ad7f9e 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -13,6 +13,8 @@
## Fixed
+- **Pipeline arc regenerate — preserve child issues when the LLM mints fresh season uuids.** The follow-up to the `arc/resolve` remap shipped earlier today: the "Regenerate arc" button (`POST /api/pipeline/series/:id/arc/generate` with `commit:true`) was writing brand-new season ids on every run without remapping child issues — every regenerate stranded every issue behind a defunct `seasonId`. Hoisted the resolve path's remap+reassign body into a shared `commitSeasonsWithRemap(currentSeries, { arc, seasons })` helper on `arcPlanner`; the `/arc/generate` commit branch now routes through it, so a regenerate now reattaches existing issues to the new seasons by normalized title → unique `number` → positional fallback (exact mirror of the resolve path). Also added `scripts/repair-orphaned-issues.js --series=<id>` as a one-shot data tool for installs already affected by the gap — runs dry-run by default, requires `--apply` to write, refuses non-1:1 orphan/season counts.
+
- **Pipeline arc resolve — preserve child issues when the LLM rewrites the seasons array.** Auto-resolve (`POST /api/pipeline/series/:id/arc/resolve`) replaces `series.seasons[]` with whatever the LLM returns. The prompt instructs the LLM to "preserve volume `id` for every existing volume you keep", but when it ignored that and minted fresh UUIDs (or returned seasons without ids), every child issue still pointed at the now-defunct seasonId and vanished from the Arc canvas — the UI groups issues by `seasonId` and never iterated the orphan buckets. `resolveVerifyIssues()` now tags each merged season with its provenance, derives the set of dropped old seasons, and builds an old→new remap (normalized title → unique `number` → positional fallback when counts line up). Affected child issues are migrated to the matched new seasonId (or `null` = ungrouped, which is visible) in the same write, mirroring `deleteSeason`'s bulk-reassign idiom: `updateIssue(…, { skipRenumber: true })` per call + one `recomputeIssueNumbersForSeries` after, wrapped in `withReexportSuppressed('series', seriesId, …)` so a 96-issue series doesn't fan out N socket emits + N debounced re-exports. As a backstop, `ArcCanvas.jsx` now buckets any issue whose `seasonId` isn't in the current `seasons[]` under the existing "Unassigned issues" group instead of a key nothing renders — so non-resolve-path orphans (stale data, future bugs) stay visible too.
- **Sharing exporter — fall back to per-image metadata sidecar when the media-job archive has aged out.** The `mediaJobQueue` archive trims completed jobs after 24h, so subscription re-exports of any universe with older images were spamming `⚠️ sharing.exporter: imageJobId <id> not found in live queue or archive` for every aged-out job, and the recipient's bundle lost the per-job metadata record (prompt, model, dimensions) used for full-fidelity re-renders. `exportMediaJobAndAsset` now falls back to reading `data/images/<jobId>.metadata.json` (written at gen time by both the codex and local image-gen paths, lifetime tied to the asset file) and synthesizes a job record from it when the in-memory queue/archive miss. The warning now only fires when both lookups miss — meaning the image file or its sidecar is actually gone — and the message text now includes `or sidecar` to reflect the new lookup path.
diff --git a/scripts/repair-orphaned-issues.js b/scripts/repair-orphaned-issues.js
new file mode 100644
index 0000000000..717ef08a19
--- /dev/null
+++ b/scripts/repair-orphaned-issues.js
@@ -0,0 +1,108 @@
+/**
+ * One-shot repair for issues stranded behind a defunct seasonId.
+ *
+ * Background: a "Regenerate arc" against a series replaced series.seasons[]
+ * with brand-new uuids without remapping the existing child issues, so the
+ * Arc Canvas grouped them under an "Un-grouped" bucket instead of their
+ * actual seasons. The structural fix lives in arcPlanner; this script
+ * heals the data that was already broken.
+ *
+ * Strategy: for the target series, group orphaned issues by their stale
+ * seasonId, order each group's issues by min(number), and map orphan
+ * groups 1:1 onto the series' current seasons (sorted by number). After
+ * reassigning seasonIds, run recomputeIssueNumbersForSeries so number
+ * gaps from the reorder collapse.
+ *
+ * Usage:
+ * node scripts/repair-orphaned-issues.js --series=<seriesId> # dry-run
+ * node scripts/repair-orphaned-issues.js --series=<seriesId> --apply # write
+ */
+import { getSeries } from '../server/services/pipeline/series.js';
+import {
+ listIssues,
+ updateIssue,
+ recomputeIssueNumbersForSeries,
+} from '../server/services/pipeline/issues.js';
+import { withReexportSuppressed } from '../server/services/sharing/recordEvents.js';
+
+function parseArgs(argv) {
+ const out = { apply: false, seriesId: null };
+ for (const arg of argv.slice(2)) {
+ if (arg === '--apply') out.apply = true;
+ else if (arg.startsWith('--series=')) out.seriesId = arg.slice('--series='.length);
+ }
+ return out;
+}
+
+async function main() {
+ const { seriesId, apply } = parseArgs(process.argv);
+ if (!seriesId) {
+ console.error('❌ --series=<id> is required');
+ process.exit(1);
+ }
+
+ const series = await getSeries(seriesId);
+ const seasons = (series.seasons || []).slice().sort(
+ (a, b) => (a.number || 0) - (b.number || 0),
+ );
+ const validIds = new Set(seasons.map((s) => s.id));
+ const issues = await listIssues({ seriesId });
+
+ const orphans = issues.filter((i) => i.seasonId && !validIds.has(i.seasonId));
+ if (!orphans.length) {
+ console.log(`✅ No orphaned issues on ${seriesId} — nothing to repair`);
+ return;
+ }
+
+ const groups = new Map();
+ for (const iss of orphans) {
+ if (!groups.has(iss.seasonId)) groups.set(iss.seasonId, []);
+ groups.get(iss.seasonId).push(iss);
+ }
+ const orphanGroups = [...groups.entries()]
+ .map(([oldId, list]) => ({
+ oldId,
+ list: list.slice().sort((a, b) => (a.number || 0) - (b.number || 0)),
+ minNumber: list.reduce((m, i) => Math.min(m, i.number || Infinity), Infinity),
+ }))
+ .sort((a, b) => a.minNumber - b.minNumber);
+
+ if (orphanGroups.length !== seasons.length) {
+ console.error(
+ `❌ Refusing to remap: ${orphanGroups.length} orphan groups vs ${seasons.length} current seasons — not 1:1. Resolve manually.`,
+ );
+ process.exit(2);
+ }
+
+ console.log(`🔍 Series: ${series.name || seriesId}`);
+ console.log(`🔍 Current seasons (${seasons.length}):`);
+ seasons.forEach((s, i) => console.log(` ${i + 1}. ${s.id} #${s.number} ${s.title}`));
+ console.log(`🔍 Orphan groups (${orphanGroups.length}):`);
+ const remap = new Map();
+ orphanGroups.forEach((g, i) => {
+ const target = seasons[i];
+ remap.set(g.oldId, target.id);
+ const titles = g.list.slice(0, 3).map((i) => i.title || '(untitled)').join(' | ');
+ console.log(` ${i + 1}. ${g.oldId} (${g.list.length} issues, #${g.list[0].number}-${g.list[g.list.length - 1].number}) → ${target.id} "${target.title}"`);
+ console.log(` ${titles}${g.list.length > 3 ? ' | …' : ''}`);
+ });
+
+ if (!apply) {
+ console.log('\nℹ️ Dry-run. Re-run with --apply to write.');
+ return;
+ }
+
+ await withReexportSuppressed('series', seriesId, async () => {
+ for (const iss of orphans) {
+ const target = remap.get(iss.seasonId);
+ await updateIssue(iss.id, { seasonId: target }, { skipRenumber: true });
+ }
+ await recomputeIssueNumbersForSeries(seriesId);
+ });
+ console.log(`\n✅ Reassigned ${orphans.length} issue${orphans.length === 1 ? '' : 's'} and recomputed numbers.`);
+}
+
+main().catch((err) => {
+ console.error(`❌ ${err?.message || err}`);
+ process.exit(1);
+});
diff --git a/server/routes/pipeline.js b/server/routes/pipeline.js
index 9459d080d0..dbd7e41179 100644
--- a/server/routes/pipeline.js
+++ b/server/routes/pipeline.js
@@ -953,10 +953,13 @@ router.post('/series/:id/arc/generate', asyncHandler(async (req, res) => {
.catch((err) => { throw mapServiceError(err); });
let series = null;
if (body.commit) {
- series = await seriesSvc.updateSeries(req.params.id, {
+ const cur = await seriesSvc.getSeries(req.params.id)
+ .catch((err) => { throw mapServiceError(err); });
+ const committed = await arcPlanner.commitSeasonsWithRemap(cur, {
arc: result.arc,
seasons: result.seasons,
}).catch((err) => { throw mapServiceError(err); });
+ series = committed.series;
}
res.json({
arc: result.arc,
diff --git a/server/services/pipeline/arcPlanner.js b/server/services/pipeline/arcPlanner.js
index c62c3a68cd..83094eaef4 100644
--- a/server/services/pipeline/arcPlanner.js
+++ b/server/services/pipeline/arcPlanner.js
@@ -829,30 +829,51 @@ export async function resolveVerifyIssues(seriesId, options = {}) {
}).filter((entry) => entry?.season);
const seasons = sanitizeSeasonList(seasonEntries.map((e) => e.season));
- // `sanitizeSeasonList` can drop entries (e.g. title-less + no number), so
- // re-key remap inputs against what actually survived.
- const finalIds = new Set(seasons.map((s) => s.id));
- const preservedOldIds = new Set(
- seasonEntries
- .filter((e) => e.sourceId && finalIds.has(e.season.id))
- .map((e) => e.sourceId),
- );
- const droppedOldSeasons = (series.seasons || []).filter((s) => !preservedOldIds.has(s.id));
- const newlyMintedSeasons = seasonEntries
- .filter((e) => !e.sourceId && finalIds.has(e.season.id))
- .map((e) => e.season);
- const remap = buildSeasonRemap(droppedOldSeasons, newlyMintedSeasons);
- // Without the seasonId migration, the LLM replacing an id strands every
- // child issue behind a key the UI never iterates. Mirrors `deleteSeason`'s
- // bulk-reassign idiom — `skipRenumber` per call + one `recomputeIssueNumbers`
- // after, wrapped in `withReexportSuppressed` so we don't fan out N socket
- // events + N debounced re-exports of the same series.
+ const { series: updated } = await commitSeasonsWithRemap(series, { arc, seasons });
+
+ const notes = typeof content?.notes === 'string' ? content.notes.trim().slice(0, 2000) : '';
+ return {
+ series: updated,
+ applied: true,
+ notes,
+ findings,
+ runId,
+ providerId,
+ model,
+ };
+}
+
+/**
+ * Persist a new `arc` + `seasons[]` onto a series, migrating any child issues
+ * whose `seasonId` referenced a season that the new shape dropped or renamed.
+ * Shared by `resolveVerifyIssues` (auto-resolve) and `/arc/generate` — both
+ * paths can rewrite season ids, and without this migration the orphans land
+ * behind keys the Arc Canvas never iterates back.
+ *
+ * Match priority (via `buildSeasonRemap`): normalized title → unique number →
+ * positional 1:1 fallback. Unmatched orphans get `seasonId: null` so they fall
+ * into the visible "Un-grouped" bucket instead of vanishing.
+ *
+ * `currentSeries` is the pre-write snapshot; pass the result of `getSeries(id)`
+ * so we know which ids existed before the write.
+ */
+export async function commitSeasonsWithRemap(currentSeries, { arc, seasons }) {
+ const seriesId = currentSeries.id;
+ const newIds = new Set((seasons || []).map((s) => s.id));
+ const droppedOldSeasons = (currentSeries.seasons || []).filter((s) => !newIds.has(s.id));
+ const oldIds = new Set((currentSeries.seasons || []).map((s) => s.id));
+ const newlyMintedSeasons = (seasons || []).filter((s) => !oldIds.has(s.id));
+ const remap = buildSeasonRemap(droppedOldSeasons, newlyMintedSeasons);
const droppedIdSet = new Set(droppedOldSeasons.map((s) => s.id));
const reassignList = droppedIdSet.size
? (await listIssues({ seriesId })).filter((iss) => droppedIdSet.has(iss.seasonId))
: [];
+ // Mirrors `deleteSeason`'s bulk-reassign idiom — `skipRenumber` per call +
+ // one `recomputeIssueNumbers` after, wrapped in `withReexportSuppressed` so
+ // we don't fan out N socket events + N debounced re-exports of the same
+ // series.
let updated;
await withReexportSuppressed('series', seriesId, async () => {
for (const iss of reassignList) {
@@ -863,17 +884,7 @@ export async function resolveVerifyIssues(seriesId, options = {}) {
if (reassignList.length) await recomputeIssueNumbersForSeries(seriesId);
});
if (reassignList.length) emitRecordUpdated('series', seriesId);
-
- const notes = typeof content?.notes === 'string' ? content.notes.trim().slice(0, 2000) : '';
- return {
- series: updated,
- applied: true,
- notes,
- findings,
- runId,
- providerId,
- model,
- };
+ return { series: updated, reassignedIssueCount: reassignList.length };
}
// Build a Map<oldSeasonId, newSeasonId|null> from the set of removed seasons
diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.js
index 272ae94872..b242cc8518 100644
--- a/server/services/pipeline/arcPlanner.test.js
+++ b/server/services/pipeline/arcPlanner.test.js
@@ -708,6 +708,72 @@ describe('arcPlanner — resolveVerifyIssues', () => {
});
});
+describe('arcPlanner — commitSeasonsWithRemap', () => {
+ beforeEach(() => {
+ fileStore.clear();
+ uuidCounter = 0;
+ stageRunnerSpy = undefined;
+ });
+
+ it('remaps child issues onto title-matched replacement seasons (the regenerate-arc path)', async () => {
+ const s = await setupSeries();
+ const oldS1 = await seasonsSvc.createSeason(s.id, { title: 'The Velvet Pouch', episodeCountTarget: 3 });
+ const oldS2 = await seasonsSvc.createSeason(s.id, { title: 'Six Blocks Down', episodeCountTarget: 3 });
+
+ const i1 = await issuesSvc.createIssue({ seriesId: s.id, seasonId: oldS1.id, title: 'Pilot' });
+ const i2 = await issuesSvc.createIssue({ seriesId: s.id, seasonId: oldS2.id, title: 'Middle' });
+
+ const cur = await seriesSvc.getSeries(s.id);
+ const freshSeasons = [
+ // Same titles, brand-new ids — exactly what shapeSeasonOutlines emits.
+ { id: 'sea-fresh-1', number: 1, title: 'The Velvet Pouch', logline: '', synopsis: '', endingHook: '', episodeCountTarget: 3, themes: [] },
+ { id: 'sea-fresh-2', number: 2, title: 'Six Blocks Down', logline: '', synopsis: '', endingHook: '', episodeCountTarget: 3, themes: [] },
+ ];
+ const out = await planner.commitSeasonsWithRemap(cur, {
+ arc: { logline: 'L', summary: '', themes: [], protagonistArc: '', shape: null, status: 'draft' },
+ seasons: freshSeasons,
+ });
+
+ expect(out.reassignedIssueCount).toBe(2);
+ expect(out.series.seasons.map((s) => s.id)).toEqual(['sea-fresh-1', 'sea-fresh-2']);
+
+ const finalI1 = await issuesSvc.getIssue(i1.id);
+ const finalI2 = await issuesSvc.getIssue(i2.id);
+ expect(finalI1.seasonId).toBe('sea-fresh-1');
+ expect(finalI2.seasonId).toBe('sea-fresh-2');
+ });
+
+ it('does nothing to issues when seasons[] preserves existing ids', async () => {
+ const s = await setupSeries();
+ const oldS1 = await seasonsSvc.createSeason(s.id, { title: 'Keep me', episodeCountTarget: 3 });
+ const i1 = await issuesSvc.createIssue({ seriesId: s.id, seasonId: oldS1.id, title: 'Pilot' });
+
+ const cur = await seriesSvc.getSeries(s.id);
+ const out = await planner.commitSeasonsWithRemap(cur, {
+ arc: { logline: 'L', summary: '', themes: [], protagonistArc: '', shape: null, status: 'draft' },
+ seasons: [{ ...oldS1, logline: 'updated' }],
+ });
+ expect(out.reassignedIssueCount).toBe(0);
+ const finalI1 = await issuesSvc.getIssue(i1.id);
+ expect(finalI1.seasonId).toBe(oldS1.id);
+ });
+
+ it('drops orphans to null when no remap target exists (collapsed seasons)', async () => {
+ const s = await setupSeries();
+ const oldS1 = await seasonsSvc.createSeason(s.id, { title: 'Only', episodeCountTarget: 3 });
+ const i1 = await issuesSvc.createIssue({ seriesId: s.id, seasonId: oldS1.id, title: 'Orphan' });
+
+ const cur = await seriesSvc.getSeries(s.id);
+ const out = await planner.commitSeasonsWithRemap(cur, {
+ arc: { logline: 'L', summary: '', themes: [], protagonistArc: '', shape: null, status: 'draft' },
+ seasons: [],
+ });
+ expect(out.reassignedIssueCount).toBe(1);
+ const finalI1 = await issuesSvc.getIssue(i1.id);
+ expect(finalI1.seasonId).toBeNull();
+ });
+});
+
describe('arcPlanner — buildSeasonRemap', () => {
it('matches by normalized title first', () => {
const dropped = [{ id: 'old1', number: 1, title: 'The Velvet Pouch' }];