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 resolve rewrites season ids

[._.]/ Adam Eivy7cb76abf9047
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index de58a19a0b..667c71f5ff 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -13,6 +13,8 @@
## Fixed
+- **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.
+
- **Universe Builder — coalesce per-image share re-exports during a batch render.** When a subscribed universe was rendering a large batch (e.g. 160 prompts), every completed image fired a per-item `emitRecordUpdated('universe', …)` → debounced re-export, walking every historical `imageJobId` in the linked collection and warning for any that aged out of the 24h in-memory media-job archive. The render route now registers each run's job count with `universeBuilderCollectionHook`, which wraps every per-item `addItem` in `withReexportSuppressed` while the run is active and emits a single `emitRecordUpdated` once the last terminal event (completed / failed / canceled) lands. A 160-image batch now schedules one debounced re-export at the end instead of ~one per completion, and the "imageJobId not found in live queue or archive" warnings collapse to a single sweep. Server restart mid-run drops the in-memory tracker entry — the hook falls back to the legacy per-image emits for the rest of that run.
- **Media annotations now sync across PortOS instances via shared Drive buckets, with per-author attribution.** Previously, a note or star added on one machine was invisible to peers sharing the same Drive bucket — `data/media-annotations.json` lived purely client-local. Storage is now per-author: each instance owns its own `instanceId` sub-entry under each `<kind>:<ref>` key (`{ authors: { [instanceId]: { authorName, starred, note, updatedAt } } }`), so my notes never clobber yours and vice versa. A new manifest kind (`media-annotations`) carries each instance's annotation snapshot into every auto-merge bucket via a stable filename (`annotations-<instanceId>.json`), debounced 2s after the last local edit. The export is per-bucket scoped to assets actually present in that bucket, so a private annotation can't leak into an unrelated share. On import, peer records merge per-author by `updatedAt` LWW and re-broadcast `media:annotation:updated` so open clients refresh without a reload. Stars are also per-author — "my favorites" remains my view, not a tug-of-war. The lightbox now shows my note in the editable textarea and "Notes from others" as labeled read-only blocks below (with the peer's display name + their star). Migration `012-attribute-existing-annotations.js` rewraps existing notes under the local instance's id on first run.
diff --git a/client/src/components/pipeline/ArcCanvas.jsx b/client/src/components/pipeline/ArcCanvas.jsx
index 1034cd5483..a7acfb06bb 100644
--- a/client/src/components/pipeline/ArcCanvas.jsx
+++ b/client/src/components/pipeline/ArcCanvas.jsx
@@ -112,10 +112,12 @@ function VerifyScopeHint({ scope }) {
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.
+ // Stale seasonIds (e.g. after a verify-resolve season rewrite) bucket under
+ // null so they show as ungrouped instead of vanishing into an un-iterated key.
+ const validSeasonIds = new Set(seasons.map((s) => s.id));
const issuesBySeason = new Map();
for (const iss of issues) {
- const key = iss.seasonId || null;
+ const key = iss.seasonId && validSeasonIds.has(iss.seasonId) ? iss.seasonId : null;
if (!issuesBySeason.has(key)) issuesBySeason.set(key, []);
issuesBySeason.get(key).push(iss);
}
@@ -255,8 +257,8 @@ function ArcHeader({ series, onSeriesUpdate, onIssuesUpdate, onFlushPending }) {
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.
+ // Server may reassign child issues' seasonId when resolve replaces
+ // season records — refresh so the tree reflects the moves.
const refreshed = await listPipelineIssues(series.id).catch(() => null);
if (refreshed) onIssuesUpdate(refreshed);
}
diff --git a/server/services/pipeline/arcPlanner.js b/server/services/pipeline/arcPlanner.js
index aca7f6ea2d..c62c3a68cd 100644
--- a/server/services/pipeline/arcPlanner.js
+++ b/server/services/pipeline/arcPlanner.js
@@ -22,7 +22,8 @@
import { runStagedLLM } from '../../lib/stageRunner.js';
import { ServerError } from '../../lib/errorHandler.js';
import { getSeries, updateSeries, updateSeasonOnSeries } from './series.js';
-import { listIssues } from './issues.js';
+import { listIssues, updateIssue, recomputeIssueNumbersForSeries } from './issues.js';
+import { emitRecordUpdated, withReexportSuppressed } from '../sharing/recordEvents.js';
import { getSeason } from './seasons.js';
import {
sanitizeArc,
@@ -793,34 +794,75 @@ export async function resolveVerifyIssues(seriesId, options = {}) {
// 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) => {
+ // Track each entry's provenance (existing id vs freshly minted) so we can
+ // remap orphaned child issues after sanitization.
+ const seasonEntries = 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 {
+ season: 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,
+ }),
+ sourceId: existing.id,
+ };
}
- 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 });
+ return {
+ season: buildSeason({
+ number: raw?.number,
+ title: raw?.title,
+ logline: raw?.logline,
+ synopsis: raw?.synopsis,
+ endingHook: raw?.endingHook,
+ episodeCountTarget: raw?.episodeCountTarget,
+ }),
+ sourceId: null,
+ };
+ }).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 droppedIdSet = new Set(droppedOldSeasons.map((s) => s.id));
+ const reassignList = droppedIdSet.size
+ ? (await listIssues({ seriesId })).filter((iss) => droppedIdSet.has(iss.seasonId))
+ : [];
+
+ let updated;
+ await withReexportSuppressed('series', seriesId, async () => {
+ for (const iss of reassignList) {
+ const target = remap.get(iss.seasonId) ?? null;
+ await updateIssue(iss.id, { seasonId: target }, { skipRenumber: true });
+ }
+ updated = await updateSeries(seriesId, { arc, seasons });
+ 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 {
@@ -834,6 +876,67 @@ export async function resolveVerifyIssues(seriesId, options = {}) {
};
}
+// Build a Map<oldSeasonId, newSeasonId|null> from the set of removed seasons
+// and the freshly-minted ones in the same resolve. Matching priority:
+// 1. normalized title equality (LLM was told to preserve titles when it can)
+// 2. `number` equality (only when the target number is unique among new ones)
+// 3. positional fallback (only when counts match and ordering aligns)
+// Anything that can't be matched maps to null so the issue lands in the
+// ungrouped bucket instead of staying stranded behind a defunct id.
+export function buildSeasonRemap(droppedOldSeasons, newlyMintedSeasons) {
+ const remap = new Map();
+ const claimed = new Set();
+ const norm = (s) => (typeof s === 'string' ? s.trim().toLowerCase() : '');
+
+ // Pass 1: normalized title
+ for (const old of droppedOldSeasons) {
+ const oldTitle = norm(old.title);
+ if (!oldTitle) continue;
+ const hit = newlyMintedSeasons.find(
+ (n) => norm(n.title) === oldTitle && !claimed.has(n.id),
+ );
+ if (hit) {
+ claimed.add(hit.id);
+ remap.set(old.id, hit.id);
+ }
+ }
+
+ // Pass 2: unique `number` match
+ for (const old of droppedOldSeasons) {
+ if (remap.has(old.id)) continue;
+ if (!Number.isFinite(old.number)) continue;
+ const matches = newlyMintedSeasons.filter(
+ (n) => n.number === old.number && !claimed.has(n.id),
+ );
+ if (matches.length === 1) {
+ claimed.add(matches[0].id);
+ remap.set(old.id, matches[0].id);
+ }
+ }
+
+ // Pass 3: positional fallback when the unclaimed sets line up 1:1
+ const oldRemaining = droppedOldSeasons.filter((s) => !remap.has(s.id));
+ const newRemaining = newlyMintedSeasons.filter((n) => !claimed.has(n.id));
+ if (oldRemaining.length && oldRemaining.length === newRemaining.length) {
+ const oldSorted = [...oldRemaining].sort(
+ (a, b) => (a.number ?? 0) - (b.number ?? 0),
+ );
+ const newSorted = [...newRemaining].sort(
+ (a, b) => (a.number ?? 0) - (b.number ?? 0),
+ );
+ for (let i = 0; i < oldSorted.length; i += 1) {
+ remap.set(oldSorted[i].id, newSorted[i].id);
+ claimed.add(newSorted[i].id);
+ }
+ }
+
+ // Anything still unmapped → null (ungrouped bucket).
+ for (const old of droppedOldSeasons) {
+ if (!remap.has(old.id)) remap.set(old.id, null);
+ }
+ return remap;
+}
+
// Export internals for tests.
export const __testing = {
buildArcOverviewContext,
diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.js
index 1eb716e6b4..272ae94872 100644
--- a/server/services/pipeline/arcPlanner.test.js
+++ b/server/services/pipeline/arcPlanner.test.js
@@ -639,4 +639,125 @@ describe('arcPlanner — resolveVerifyIssues', () => {
expect(stageRunnerSpy).toHaveBeenCalledTimes(1);
expect(stageRunnerSpy.mock.calls[0][0]).toBe('pipeline-arc-verify');
});
+
+ it('remaps child issues off dropped seasonIds onto matched replacements', async () => {
+ const s = await setupSeries();
+ await seriesSvc.updateSeries(s.id, { arc: { logline: 'L' } });
+ 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 oldS3 = await seasonsSvc.createSeason(s.id, { title: 'The City Looks Back', 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 i3 = await issuesSvc.createIssue({ seriesId: s.id, seasonId: oldS3.id, title: 'Finale' });
+
+ // LLM returns seasons by title without preserving ids; the remap must
+ // reattach orphaned issues via normalized title match.
+ stageRunnerSpy = vi.fn(async () => ({
+ content: {
+ arc: { logline: 'L2', summary: 'S', themes: [], protagonistArc: '' },
+ seasons: [
+ { number: 1, title: 'The Velvet Pouch', logline: '', synopsis: '', endingHook: '', episodeCountTarget: 3 },
+ { number: 2, title: 'Six Blocks Down', logline: '', synopsis: '', endingHook: '', episodeCountTarget: 3 },
+ { number: 3, title: 'The City Looks Back', logline: '', synopsis: '', endingHook: '', episodeCountTarget: 3 },
+ ],
+ notes: '',
+ },
+ runId: 'r', providerId: 'p', model: 'm',
+ }));
+
+ const out = await planner.resolveVerifyIssues(s.id, {
+ findings: [{ severity: 'medium', problem: 'X', suggestion: 'Y' }],
+ });
+
+ expect(out.applied).toBe(true);
+ expect(out.series.seasons).toHaveLength(3);
+ const [newS1, newS2, newS3] = out.series.seasons;
+ expect(newS1.id).not.toBe(oldS1.id); // freshly minted
+
+ const finalI1 = await issuesSvc.getIssue(i1.id);
+ const finalI2 = await issuesSvc.getIssue(i2.id);
+ const finalI3 = await issuesSvc.getIssue(i3.id);
+ expect(finalI1.seasonId).toBe(newS1.id);
+ expect(finalI2.seasonId).toBe(newS2.id);
+ expect(finalI3.seasonId).toBe(newS3.id);
+ });
+
+ it('drops orphans to null seasonId when no replacement can be matched', async () => {
+ const s = await setupSeries();
+ await seriesSvc.updateSeries(s.id, { arc: { logline: 'L' } });
+ const oldS = await seasonsSvc.createSeason(s.id, { title: 'Only Season', episodeCountTarget: 3 });
+ const i1 = await issuesSvc.createIssue({ seriesId: s.id, seasonId: oldS.id, title: 'Orphan' });
+
+ // LLM returns zero seasons — nothing to remap to, issue should go ungrouped.
+ stageRunnerSpy = vi.fn(async () => ({
+ content: {
+ arc: { logline: 'L2', summary: 'S', themes: [], protagonistArc: '' },
+ seasons: [],
+ notes: 'collapsed',
+ },
+ runId: 'r', providerId: 'p', model: 'm',
+ }));
+
+ await planner.resolveVerifyIssues(s.id, {
+ findings: [{ severity: 'medium', problem: 'X', suggestion: 'Y' }],
+ });
+
+ 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' }];
+ const minted = [{ id: 'new1', number: 1, title: ' THE VELVET POUCH ' }];
+ const remap = planner.buildSeasonRemap(dropped, minted);
+ expect(remap.get('old1')).toBe('new1');
+ });
+
+ it('falls back to unique number match', () => {
+ const dropped = [{ id: 'old1', number: 2, title: 'Renamed' }];
+ const minted = [
+ { id: 'new1', number: 1, title: 'Different' },
+ { id: 'new2', number: 2, title: 'Also Different' },
+ ];
+ const remap = planner.buildSeasonRemap(dropped, minted);
+ expect(remap.get('old1')).toBe('new2');
+ });
+
+ it('falls back positionally when counts match and unique-number is ambiguous', () => {
+ const dropped = [
+ { id: 'old1', number: 1, title: 'A' },
+ { id: 'old2', number: 2, title: 'B' },
+ ];
+ const minted = [
+ { id: 'new1', number: 1, title: 'X' },
+ { id: 'new2', number: 2, title: 'Y' },
+ ];
+ const remap = planner.buildSeasonRemap(dropped, minted);
+ expect(remap.get('old1')).toBe('new1');
+ expect(remap.get('old2')).toBe('new2');
+ });
+
+ it('maps to null when nothing plausible exists', () => {
+ const dropped = [{ id: 'old1', number: 1, title: 'A' }];
+ const minted = [];
+ const remap = planner.buildSeasonRemap(dropped, minted);
+ expect(remap.get('old1')).toBeNull();
+ });
+
+ it('claims each minted season only once', () => {
+ const dropped = [
+ { id: 'old1', number: 1, title: 'Same' },
+ { id: 'old2', number: 2, title: 'Same' },
+ ];
+ const minted = [
+ { id: 'new1', number: 1, title: 'Same' },
+ ];
+ const remap = planner.buildSeasonRemap(dropped, minted);
+ // First old gets the title match; second has no remaining mint.
+ expect(remap.get('old1')).toBe('new1');
+ expect(remap.get('old2')).toBeNull();
+ });
});