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): derive issue numbers from volume order, not series-wide max

[._.]/ Adam Eivy01c930129aab
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 8101abe6b0..5acebb9854 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -96,6 +96,33 @@
`client/src/components/imageGen/HfTokenBanner.jsx` (renamed from
`Flux2TokenBanner.jsx`).
+- **Issue numbers now reflect volume order across the whole series.** The
+ series-wide issue counter was monotonic — adding new episodes to V1 in a
+ series that already had V2 produced issues like `#33` instead of slotting
+ into V1's range. `issue.number` is now a derived attribute computed from
+ (volume order, `arcPosition`) by a renumber pass that runs after every
+ mutation that can shift the canonical sequence (`createIssue`,
+ `deleteIssue`, `updateIssue` when `seasonId`/`arcPosition` changes,
+ `updateSeason` when a volume's number changes, `deleteSeason` after the
+ reassign loop). Earlier volumes stay frozen — the renumber anchors at the
+ affected volume so an unrelated V2 edit never reshuffles V1, and a stale
+ `seasonId` (one pointing at a deleted season) is normalized to the
+ unscoped tail so it never triggers a full series renumber. The pure
+ algorithm lives in `server/lib/pipelineIssueOrder.js` so the new
+ `recomputeIssueNumbersForSeries(seriesId, fromSeasonId?)` export (used by
+ the seasons service after a volume reorder) and the one-shot migration
+ share one implementation — neither can drift from the other. The
+ `nextIssueNumber` helper is gone. A new migration
+ (`scripts/migrations/010-renumber-pipeline-issues-by-volume.js`) walks
+ every existing series once on next startup so on-disk state matches the
+ new model without requiring a manual edit. Touches:
+ `server/lib/pipelineIssueOrder.js` (new),
+ `server/services/pipeline/issues.js`,
+ `server/services/pipeline/seasons.js`,
+ `server/routes/pipeline.js`,
+ `server/services/pipeline/issues.test.js` (+5 cases),
+ `scripts/migrations/010-renumber-pipeline-issues-by-volume.js` (new).
+
- **Visual Style Preset dropdown clipped inside the bible sidebar.** The
prior z-30 → z-50 bump was a no-op for the real problem: the dropdown
lives inside the Pipeline Series bible `<aside class="lg:overflow-y-auto">`,
diff --git a/PLAN.md b/PLAN.md
index e18c7fec22..04dbb710b6 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -258,3 +258,4 @@ Skeleton landed in `server/services/pipeline/` + `client/src/pages/Pipeline*.jsx
- [ ] **Extract `listDirectoryByExtension(dir, { extensions, mapEntry })` helper in `server/lib/fileUtils.js`.** Three call sites today follow the same readdir + filter-by-extension + stat-per-entry shape: `server/services/loras.js#listLoras` (sidecar reads), `server/services/imageGen/local.js#listGallery` (civitai-aware fields), `server/services/pipeline/musicLibrary.js#listMusicLibrary`. Each carries domain-specific per-entry mapping, so the shared helper takes a `mapEntry(dirent, statResult) → entry|null` callback. Saves ~15 LOC at each site plus a single fix-point for future "use `readdir(withFileTypes:true)` to skip the stat when only `.isFile()` is needed" optimization. Surfaced from the /simplify pass on Phase 4c.
- [ ] **Teach `request()` in `client/src/services/apiCore.js` about FormData.** Two helpers today bypass `request()` because it hard-codes `Content-Type: application/json`: `apiHealth.js#uploadAppleHealthXml` and `apiPipeline.js#uploadPipelineMusicTrack`. Each re-implements the error-shape extraction (`{ error, code, status }`) inline. Fix: in `request()`, when `body instanceof FormData`, omit the `Content-Type` header so the browser sets `multipart/form-data; boundary=...` automatically. Both call sites then collapse to a single `request()` call. Surfaced from the /simplify pass on Phase 4c.
- [ ] **Per-panel/scene image progress in the Pipeline UI.** Right now ComicPages and Storyboards record `jobId` but don't subscribe to the media-job SSE for live preview. Tie into the existing per-job progress hook so each panel shows live render thumbnails.
+- [ ] **Bulk reassign helper to collapse N+1 writes in `deleteSeason`.** `server/services/pipeline/seasons.js#deleteSeason` reassigns each child issue via `issuesSvc.updateIssue(..., { skipRenumber: true })` in a loop, then runs one final `recomputeIssueNumbersForSeries`. Each `updateIssue` still calls `writeState` on `pipeline-issues.json`, so a 50-issue volume = 51 sequential `atomicWrite` calls. Add `issuesSvc.bulkReassignSeason(seriesId, fromSeasonId, toSeasonId)` that does one `readState` + N in-memory mutations + one `writeState` + one renumber. Surfaced from /simplify on the volume-ordered numbering fix (2026-05-16).
diff --git a/scripts/migrations/010-renumber-pipeline-issues-by-volume.js b/scripts/migrations/010-renumber-pipeline-issues-by-volume.js
new file mode 100644
index 0000000000..5e9a3e8017
--- /dev/null
+++ b/scripts/migrations/010-renumber-pipeline-issues-by-volume.js
@@ -0,0 +1,76 @@
+/**
+ * Backfill issue.number on existing pipeline data after the switch to
+ * volume-ordered numbering.
+ *
+ * Previously, `issue.number` was a series-wide counter that only ever moved
+ * forward — a series with V1 (#1–11) and V2 (#12–43) kept those numbers
+ * even though they no longer reflected volume position. The new model derives
+ * `number` from (volume order, arcPosition). This walks every series once
+ * and rewrites `pipeline-issues.json` so the on-disk state matches what the
+ * live renumber pass would produce on the next mutation — users don't have
+ * to edit a record to see correct numbers.
+ *
+ * Imports the same algorithm the live service uses, so the migration can't
+ * drift from `createIssue`'s renumber pass. Idempotent: a series whose
+ * issues already match the derived order is left alone.
+ */
+
+import { readFile, writeFile } from 'fs/promises';
+import { join } from 'path';
+import { applyVolumeOrderedNumbers } from '../../server/lib/pipelineIssueOrder.js';
+
+const readJson = async (path, fallback) => {
+ const raw = await readFile(path, 'utf-8').catch((err) => {
+ if (err.code === 'ENOENT') return null;
+ throw err;
+ });
+ if (raw == null) return fallback;
+ try { return JSON.parse(raw); } catch { return fallback; }
+};
+
+const writeJson = (path, value) =>
+ writeFile(path, JSON.stringify(value, null, 2) + '\n');
+
+export async function renumberPipelineIssuesByVolume({ rootDir }) {
+ const dataDir = join(rootDir, 'data');
+ const seriesPath = join(dataDir, 'pipeline-series.json');
+ const issuesPath = join(dataDir, 'pipeline-issues.json');
+
+ const seriesDoc = await readJson(seriesPath, null);
+ const issuesDoc = await readJson(issuesPath, null);
+ if (!seriesDoc || !issuesDoc) {
+ console.log('🔢 issue-renumber: no pipeline data — nothing to do');
+ return { changedSeries: 0 };
+ }
+
+ const seriesList = Array.isArray(seriesDoc.series) ? seriesDoc.series : [];
+ const issuesList = Array.isArray(issuesDoc.issues) ? issuesDoc.issues : [];
+ if (seriesList.length === 0 || issuesList.length === 0) {
+ console.log('🔢 issue-renumber: empty series or issue list — nothing to do');
+ return { changedSeries: 0 };
+ }
+
+ let changedSeries = 0;
+ for (const series of seriesList) {
+ if (!series?.id) continue;
+ const changed = applyVolumeOrderedNumbers({
+ issues: issuesList,
+ seriesId: series.id,
+ seasons: Array.isArray(series.seasons) ? series.seasons : [],
+ });
+ if (changed) changedSeries += 1;
+ }
+
+ if (changedSeries === 0) {
+ console.log('✅ issue-renumber: all issues already match volume order');
+ return { changedSeries: 0 };
+ }
+
+ await writeJson(issuesPath, issuesDoc);
+ console.log(`✅ issue-renumber: renumbered issues in ${changedSeries} series`);
+ return { changedSeries };
+}
+
+export default {
+ up: renumberPipelineIssuesByVolume,
+};
diff --git a/server/lib/pipelineIssueOrder.js b/server/lib/pipelineIssueOrder.js
new file mode 100644
index 0000000000..025b0dc26b
--- /dev/null
+++ b/server/lib/pipelineIssueOrder.js
@@ -0,0 +1,90 @@
+/**
+ * Pure renumber algorithm for pipeline issues. Lives in `lib/` so the
+ * one-shot migration (`scripts/migrations/010-…js`) and the live service
+ * (`server/services/pipeline/issues.js`) share one implementation —
+ * otherwise the two would drift as anchoring / sort-tiebreak rules evolve.
+ *
+ * `issue.number` is derived: it reflects the issue's position when the
+ * series is walked volume-by-volume (in `season.number` ascending order) and
+ * then arcPosition-by-arcPosition within each volume. Earlier volumes' numbers
+ * don't move when later volumes change — `fromSeasonId` anchors the renumber
+ * to the earliest affected volume so an unrelated V2 edit never reshuffles V1.
+ *
+ * fromSeasonId = null → renumber from the first volume.
+ * fromSeasonId = '<some seasonId>' → renumber from that volume onward.
+ * fromSeasonId = UNSCOPED_ANCHOR → only the trailing unscoped tail.
+ * fromSeasonId = unknown id → treated as UNSCOPED_ANCHOR (stale ref).
+ *
+ * Mutates the provided `issues` array's elements in place; returns true iff
+ * any `iss.number` actually changed (callers gate their disk writes on this).
+ */
+
+export const UNSCOPED_ANCHOR = Symbol('pipelineIssueOrder.unscopedAnchor');
+
+const byArcPosThenCreated = (a, b) => {
+ const pa = a.arcPosition || 0;
+ const pb = b.arcPosition || 0;
+ if (pa !== pb) return pa - pb;
+ return (a.createdAt || '').localeCompare(b.createdAt || '');
+};
+
+export function applyVolumeOrderedNumbers({ issues, seriesId, seasons = [], fromSeasonId = null }) {
+ const orderedSeasons = [...seasons].sort((a, b) => (a?.number || 0) - (b?.number || 0));
+ const knownSeasonIds = new Set(orderedSeasons.map((s) => s.id).filter(Boolean));
+ const byVolume = new Map();
+ const unscoped = [];
+ for (const iss of issues) {
+ if (iss.seriesId !== seriesId) continue;
+ if (iss.seasonId && knownSeasonIds.has(iss.seasonId)) {
+ const list = byVolume.get(iss.seasonId) || [];
+ list.push(iss);
+ byVolume.set(iss.seasonId, list);
+ } else {
+ unscoped.push(iss);
+ }
+ }
+
+ // Resolve the anchor. A stale `fromSeasonId` (string that doesn't match any
+ // current season) means the affected issue is in the unscoped bucket, so
+ // collapse to unscoped-only — that way one stale-seasonId append doesn't
+ // trigger a full series renumber.
+ let anchorIdx = 0;
+ let unscopedOnly = false;
+ if (fromSeasonId === UNSCOPED_ANCHOR) {
+ anchorIdx = orderedSeasons.length;
+ unscopedOnly = true;
+ } else if (fromSeasonId) {
+ const idx = orderedSeasons.findIndex((s) => s.id === fromSeasonId);
+ if (idx >= 0) anchorIdx = idx;
+ else { anchorIdx = orderedSeasons.length; unscopedOnly = true; }
+ }
+
+ // Seed the counter from the highest issue.number before the anchor, so
+ // pre-anchor volumes keep their persisted numbers untouched.
+ let counter = 1;
+ for (let i = 0; i < anchorIdx; i += 1) {
+ const list = byVolume.get(orderedSeasons[i].id) || [];
+ for (const iss of list) {
+ if ((iss.number || 0) >= counter) counter = (iss.number || 0) + 1;
+ }
+ }
+
+ let changed = false;
+ if (!unscopedOnly) {
+ for (let i = anchorIdx; i < orderedSeasons.length; i += 1) {
+ const list = (byVolume.get(orderedSeasons[i].id) || []).sort(byArcPosThenCreated);
+ for (const iss of list) {
+ if (iss.number !== counter) { iss.number = counter; changed = true; }
+ counter += 1;
+ }
+ }
+ }
+ // Unscoped issues trail the volumes, ordered by createdAt so the sequence
+ // stays deterministic across runs.
+ unscoped.sort((a, b) => (a.createdAt || '').localeCompare(b.createdAt || ''));
+ for (const iss of unscoped) {
+ if (iss.number !== counter) { iss.number = counter; changed = true; }
+ counter += 1;
+ }
+ return changed;
+}
diff --git a/server/routes/pipeline.js b/server/routes/pipeline.js
index 4e162ebfb9..1a23281aa4 100644
--- a/server/routes/pipeline.js
+++ b/server/routes/pipeline.js
@@ -946,10 +946,9 @@ router.post('/series/:id/seasons/:seasonId/episodes/generate', asyncHandler(asyn
const created = await issuesSvc.createIssue({
seriesId: req.params.id,
title: ep.title,
- // Issue `number` is series-scoped (the existing canonical counter);
- // `arcPosition` is the season-scoped ordinal the LLM gave us. We let
- // `createIssue` pick the series number so existing issues' numbers
- // don't collide.
+ // 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.
diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.js
index 7632b9f8cc..954d8ffa6f 100644
--- a/server/services/pipeline/issues.js
+++ b/server/services/pipeline/issues.js
@@ -30,6 +30,8 @@ import { sanitizeVisualStyleRef } from '../../lib/visualStyles.js';
import { ARC_ROLES } from '../../lib/storyArc.js';
import { isStr, trimTo } from '../../lib/storyBible.js';
import { emitRecordUpdated } from '../sharing/recordEvents.js';
+import { applyVolumeOrderedNumbers, UNSCOPED_ANCHOR } from '../../lib/pipelineIssueOrder.js';
+import * as seriesSvc from './series.js';
// Lazy resolution — see series.js for context.
const statePath = () => join(PATHS.data, 'pipeline-issues.json');
@@ -415,7 +417,8 @@ export function createIssue(input = {}) {
const next = sanitizeIssue({
id: `iss-${randomUUID()}`,
seriesId,
- number: input.number || nextIssueNumber(state.issues, seriesId),
+ // Placeholder — `renumberInline` below derives the canonical number.
+ number: 0,
title,
status: 'draft',
// Phase 2: optional arc pointers passed by the season-episodes generator
@@ -432,6 +435,7 @@ export function createIssue(input = {}) {
});
if (!next) throw makeErr('Invalid issue payload', ERR_VALIDATION);
state.issues.push(next);
+ await renumberInline(state, seriesId, next.seasonId || UNSCOPED_ANCHOR);
await writeState(state);
// New issue = series-level change for any active share subscription.
emitRecordUpdated('series', next.seriesId);
@@ -439,10 +443,25 @@ export function createIssue(input = {}) {
}); // end queueIssueWrite
}
-function nextIssueNumber(issues, seriesId) {
- const peers = issues.filter((i) => i.seriesId === seriesId);
- if (peers.length === 0) return 1;
- return Math.max(...peers.map((i) => i.number || 0)) + 1;
+async function renumberInline(state, seriesId, fromSeasonId = null) {
+ const series = await seriesSvc.getSeries(seriesId).catch(() => null);
+ return applyVolumeOrderedNumbers({
+ issues: state.issues,
+ seriesId,
+ seasons: series?.seasons || [],
+ fromSeasonId,
+ });
+}
+
+export function recomputeIssueNumbersForSeries(seriesId, fromSeasonId = null) {
+ return queueIssueWrite(null, async () => {
+ const state = await readState();
+ const changed = await renumberInline(state, seriesId, fromSeasonId);
+ if (!changed) return { changed: false };
+ await writeState(state);
+ emitRecordUpdated('series', seriesId);
+ return { changed: true };
+ });
}
/**
@@ -466,12 +485,15 @@ export function insertIssueWithId(input = {}) {
const next = sanitizeIssue({ ...input, seriesId, title });
if (!next) throw makeErr('Invalid issue payload', ERR_VALIDATION);
state.issues.push(next);
+ // Imported `number` is a starting hint — local canonical numbering still
+ // comes from (volume order, arcPosition) of the local state.
+ await renumberInline(state, seriesId, next.seasonId || UNSCOPED_ANCHOR);
await writeState(state);
return next;
});
}
-export function updateIssue(id, patch = {}) {
+export function updateIssue(id, patch = {}, { skipRenumber = false } = {}) {
return queueIssueWrite(id, async () => {
const state = await readState();
const idx = state.issues.findIndex((i) => i.id === id);
@@ -543,6 +565,17 @@ export function updateIssue(id, patch = {}) {
});
if (!merged) throw makeErr('Invalid issue payload', ERR_VALIDATION);
state.issues[idx] = merged;
+ // A seasonId move affects both source and destination volumes, so full
+ // renumber. An arcPosition change only reorders within the current volume.
+ // `skipRenumber` lets bulk callers (e.g. deleteSeason) collapse N per-update
+ // renumbers into one final pass.
+ if (!skipRenumber) {
+ if ('seasonId' in patch && cur.seasonId !== merged.seasonId) {
+ await renumberInline(state, merged.seriesId, null);
+ } else if ('arcPosition' in patch && cur.arcPosition !== merged.arcPosition) {
+ await renumberInline(state, merged.seriesId, merged.seasonId || UNSCOPED_ANCHOR);
+ }
+ }
await writeState(state);
// Issues are exported as part of their parent series — re-export the
// series so any active subscription picks up the issue change.
@@ -570,8 +603,10 @@ export function deleteIssue(id) {
const state = await readState();
const idx = state.issues.findIndex((i) => i.id === id);
if (idx < 0) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);
- const seriesId = state.issues[idx].seriesId;
+ const removed = state.issues[idx];
+ const seriesId = removed.seriesId;
state.issues.splice(idx, 1);
+ await renumberInline(state, seriesId, removed.seasonId || UNSCOPED_ANCHOR);
await writeState(state);
// Series export bundles every issue, so a deletion is an update on the
// parent series for any active share-bucket subscription.
diff --git a/server/services/pipeline/issues.test.js b/server/services/pipeline/issues.test.js
index 40a219a68f..8e345290a2 100644
--- a/server/services/pipeline/issues.test.js
+++ b/server/services/pipeline/issues.test.js
@@ -16,6 +16,8 @@ vi.mock('crypto', async () => {
});
const svc = await import('./issues.js');
+const seriesSvc = await import('./series.js');
+const seasonsSvc = await import('./seasons.js');
describe('pipeline issues service', () => {
beforeEach(() => {
@@ -33,6 +35,87 @@ describe('pipeline issues service', () => {
expect(c.number).toBe(1); // independent counter per series
});
+ describe('volume-ordered numbering', () => {
+ const setupTwoVolumeSeries = async () => {
+ const series = await seriesSvc.createSeries({ name: 'Saga' });
+ const v1 = await seasonsSvc.createSeason(series.id, { title: 'Volume 1', number: 1 });
+ const v2 = await seasonsSvc.createSeason(series.id, { title: 'Volume 2', number: 2 });
+ return { series, v1, v2 };
+ };
+
+ it('issues number contiguously across volumes in season order', async () => {
+ const { series, v1, v2 } = await setupTwoVolumeSeries();
+ // V1 first (10 issues), then V2 (3 issues) — V2 should start at #11.
+ for (let i = 1; i <= 10; i += 1) {
+ await svc.createIssue({ seriesId: series.id, seasonId: v1.id, arcPosition: i, title: `V1 E${i}` });
+ }
+ for (let i = 1; i <= 3; i += 1) {
+ await svc.createIssue({ seriesId: series.id, seasonId: v2.id, arcPosition: i, title: `V2 E${i}` });
+ }
+ const list = await svc.listIssues({ seriesId: series.id });
+ const v1Numbers = list.filter((i) => i.seasonId === v1.id).map((i) => i.number).sort((a, b) => a - b);
+ const v2Numbers = list.filter((i) => i.seasonId === v2.id).map((i) => i.number).sort((a, b) => a - b);
+ expect(v1Numbers).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
+ expect(v2Numbers).toEqual([11, 12, 13]);
+ });
+
+ it('adding an issue to V1 shifts V2 numbers up', async () => {
+ const { series, v1, v2 } = await setupTwoVolumeSeries();
+ // Seed V1 with 2, V2 with 2.
+ await svc.createIssue({ seriesId: series.id, seasonId: v1.id, arcPosition: 1, title: 'V1 E1' });
+ await svc.createIssue({ seriesId: series.id, seasonId: v1.id, arcPosition: 2, title: 'V1 E2' });
+ const v2first = await svc.createIssue({ seriesId: series.id, seasonId: v2.id, arcPosition: 1, title: 'V2 E1' });
+ const v2second = await svc.createIssue({ seriesId: series.id, seasonId: v2.id, arcPosition: 2, title: 'V2 E2' });
+ expect(v2first.number).toBe(3);
+ expect(v2second.number).toBe(4);
+ // Add a third issue to V1 — V2 should shift from #3..4 to #4..5.
+ await svc.createIssue({ seriesId: series.id, seasonId: v1.id, arcPosition: 3, title: 'V1 E3' });
+ const after = await svc.listIssues({ seriesId: series.id });
+ const v2NumbersAfter = after.filter((i) => i.seasonId === v2.id).map((i) => i.number).sort((a, b) => a - b);
+ expect(v2NumbersAfter).toEqual([4, 5]);
+ });
+
+ it('deleting an issue compacts the sequence', async () => {
+ const { series, v1, v2 } = await setupTwoVolumeSeries();
+ const a = await svc.createIssue({ seriesId: series.id, seasonId: v1.id, arcPosition: 1, title: 'V1 E1' });
+ await svc.createIssue({ seriesId: series.id, seasonId: v1.id, arcPosition: 2, title: 'V1 E2' });
+ await svc.createIssue({ seriesId: series.id, seasonId: v2.id, arcPosition: 1, title: 'V2 E1' });
+ await svc.deleteIssue(a.id);
+ const after = await svc.listIssues({ seriesId: series.id });
+ expect(after.map((i) => i.number)).toEqual([1, 2]);
+ });
+
+ it('changes to a later volume do not move earlier volumes', async () => {
+ const { series, v1, v2 } = await setupTwoVolumeSeries();
+ const v1a = await svc.createIssue({ seriesId: series.id, seasonId: v1.id, arcPosition: 1, title: 'V1 E1' });
+ const v1b = await svc.createIssue({ seriesId: series.id, seasonId: v1.id, arcPosition: 2, title: 'V1 E2' });
+ await svc.createIssue({ seriesId: series.id, seasonId: v2.id, arcPosition: 1, title: 'V2 E1' });
+ // Append another V2 issue — V1's persisted numbers must not change.
+ await svc.createIssue({ seriesId: series.id, seasonId: v2.id, arcPosition: 2, title: 'V2 E2' });
+ const after = await svc.listIssues({ seriesId: series.id });
+ const refetchedV1a = after.find((i) => i.id === v1a.id);
+ const refetchedV1b = after.find((i) => i.id === v1b.id);
+ expect(refetchedV1a.number).toBe(1);
+ expect(refetchedV1b.number).toBe(2);
+ });
+
+ it('reordering season numbers triggers full series renumber', async () => {
+ const { series, v1, v2 } = await setupTwoVolumeSeries();
+ await svc.createIssue({ seriesId: series.id, seasonId: v1.id, arcPosition: 1, title: 'V1 E1' });
+ await svc.createIssue({ seriesId: series.id, seasonId: v1.id, arcPosition: 2, title: 'V1 E2' });
+ await svc.createIssue({ seriesId: series.id, seasonId: v2.id, arcPosition: 1, title: 'V2 E1' });
+ await svc.createIssue({ seriesId: series.id, seasonId: v2.id, arcPosition: 2, title: 'V2 E2' });
+ // Swap volume order: make v2 come first.
+ await seasonsSvc.updateSeason(series.id, v2.id, { number: 1 });
+ await seasonsSvc.updateSeason(series.id, v1.id, { number: 2 });
+ const after = await svc.listIssues({ seriesId: series.id });
+ const v2Nums = after.filter((i) => i.seasonId === v2.id).map((i) => i.number).sort((a, b) => a - b);
+ const v1Nums = after.filter((i) => i.seasonId === v1.id).map((i) => i.number).sort((a, b) => a - b);
+ expect(v2Nums).toEqual([1, 2]);
+ expect(v1Nums).toEqual([3, 4]);
+ });
+ });
+
it('createIssue requires seriesId and title', async () => {
await expect(svc.createIssue({ title: 'x' })).rejects.toMatchObject({ code: svc.ERR_VALIDATION });
await expect(svc.createIssue({ seriesId: 'ser-1' })).rejects.toMatchObject({ code: svc.ERR_VALIDATION });
diff --git a/server/services/pipeline/seasons.js b/server/services/pipeline/seasons.js
index 938fb16ed6..984bc9e5a1 100644
--- a/server/services/pipeline/seasons.js
+++ b/server/services/pipeline/seasons.js
@@ -78,6 +78,11 @@ export async function updateSeason(seriesId, seasonId, patch = {}) {
// `number` ascending so a number change moves the season automatically.
const merged = seasons.map((s) => (s.id === seasonId ? next : s));
const updated = await seriesSvc.updateSeries(seriesId, { seasons: merged });
+ // Issue numbers derive from volume order — a volume `number` swap
+ // reshuffles every issue's slot in the series.
+ if (cur.number !== next.number) {
+ await issuesSvc.recomputeIssueNumbersForSeries(seriesId);
+ }
return updated.seasons.find((s) => s.id === seasonId);
}
@@ -122,9 +127,12 @@ export async function deleteSeason(seriesId, seasonId, { reassignTo = null } = {
// once at the end against the final state.
await withReexportSuppressed('series', seriesId, async () => {
for (const iss of reassignList) {
- await issuesSvc.updateIssue(iss.id, { seasonId: reassignTo });
+ await issuesSvc.updateIssue(iss.id, { seasonId: reassignTo }, { skipRenumber: true });
}
await seriesSvc.updateSeries(seriesId, { seasons: merged });
+ // One renumber pass after the bulk reassign + season removal so the loop
+ // doesn't pay for N per-update renumbers.
+ await issuesSvc.recomputeIssueNumbersForSeries(seriesId);
});
emitRecordUpdated('series', seriesId);
return { id: seasonId, reassignedIssueCount: reassignList.length, reassignedTo: reassignTo };