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
fix: stop arc auto-resolve minting a duplicate volume every round
[._.]/ Adam Eivy509695c86c96
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 458b7aee53..340740d9b7 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -88,3 +88,9 @@- Internal: the shared test helper that redirects `PATHS.data` at a temp dir now re-roots *every* `PATHS` member that lives under `data/`, not just `data` itself. 45 of the 49 members are built as `join(INSTALL_ROOT, 'data/…')` independently of `PATHS.data`, so "redirect `data` and the suite is isolated" was false for almost every disk-touching test — each one had to independently rediscover that and restate the on-disk layout by hand, and the failure mode when it didn't was #3683/#3687: green CI, writes landing in the developer's live install. The whole `data/` subtree now moves with the temp root, preserving each member's relative layout, while explicit per-suite overrides still merge last as the escape hatch for a member that genuinely wants a different target (a scratch root, `~/Downloads`, a pre-seeded fixture dir). Twenty call sites that merely restated the shipped layout are gone. Test-only change; no production code touched.- Internal: the task-schedule suite's "perpetual task parked on every app" case no longer passes or fails depending on what time of day it runs. It parked one app at the *next* 9am and another 30 minutes out, then asserted the 30-minute park was the soonest — true at 10am, false at 08:45, when 9am is only 15 minutes away. The case now freezes the clock at a fixed instant and uses two absolute park timestamps, so the comparison it makes is the one it means to make; a suite-wide `afterEach` restores real time so a failed assertion inside a frozen block can't leak fake time into later cases. Verified the case still fails when the soonest-park selection is inverted. Test-only change; no production code touched.++## Series Pipeline++- **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.diff --git a/server/services/pipeline/arcPlanner.js b/server/services/pipeline/arcPlanner.jsindex 3f68659d6f..09c169e86a 100644--- a/server/services/pipeline/arcPlanner.js+++ b/server/services/pipeline/arcPlanner.js@@ -35,7 +35,7 @@ export * from './arcPlanner/coverConcepts.js';// the split). Pulled back together here from their new home modules so the// existing `__testing` import contract is preserved.import { buildArcOverviewContext, shapeSeasonOutlines, buildVerifyContext, buildResolveContext, shapeVerifyIssues, shapeFindings, renderVolumeIssue, buildNeighborVolumes, buildBeatContinuityContext, shapeBeatResolutions } from './arcPlanner/context.js';-import { buildVolumeVerifyContext, mergeArcWithLocks, mergeSeasonsWithLocks, preserveDroppedSeasonRecords } from './arcPlanner/arcCore.js';+import { buildVolumeVerifyContext, collapseDuplicateSeasonNumbers, hasDuplicateSeasonNumbers, matchProposedSeasons, mergeArcWithLocks, mergeSeasonsWithLocks, preserveDroppedSeasonRecords } from './arcPlanner/arcCore.js';import { applyBeatResolutions } from './arcPlanner/beatContinuity.js';import { buildSeasonEpisodesContext, shapeEpisodes } from './arcPlanner/episodeSeedPass.js';import { shapeCompletenessFindings, buildCompletenessContext } from './arcPlanner/completenessPass.js';@@ -59,6 +59,9 @@ export const __testing = {mergeArcWithLocks,mergeSeasonsWithLocks,preserveDroppedSeasonRecords,+ matchProposedSeasons,+ hasDuplicateSeasonNumbers,+ collapseDuplicateSeasonNumbers,buildBeatContinuityContext,shapeBeatResolutions,applyBeatResolutions,diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.jsindex f98f889b34..98f92e908b 100644--- a/server/services/pipeline/arcPlanner.test.js+++ b/server/services/pipeline/arcPlanner.test.js@@ -724,7 +724,7 @@ describe('arcPlanner — resolveVerifyIssues', () => {expect(stageRunnerSpy.mock.calls[0][0]).toBe('pipeline-arc-verify');});- it('remaps child issues off dropped seasonIds onto matched replacements', async () => {+ it('rewrites title-matched seasons in place when the LLM omits their ids', 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 });@@ -735,8 +735,9 @@ describe('arcPlanner — resolveVerifyIssues', () => {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.+ // LLM returns seasons by title without preserving ids. These are rewrites+ // of the existing volumes, not new ones — `matchProposedSeasons` must land+ // them on the existing records rather than minting title-alike siblings.stageRunnerSpy = vi.fn(async () => ({content: {arc: { logline: 'L2', summary: 'S', themes: [], protagonistArc: '' },@@ -757,7 +758,9 @@ describe('arcPlanner — resolveVerifyIssues', () => {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+ // Rewritten in place — no mint, so nothing to remap and no duplicate+ // "Volume 1" left behind.+ expect([newS1.id, newS2.id, newS3.id]).toEqual([oldS1.id, oldS2.id, oldS3.id]);const finalI1 = await issuesSvc.getIssue(i1.id);const finalI2 = await issuesSvc.getIssue(i2.id);@@ -767,6 +770,42 @@ describe('arcPlanner — resolveVerifyIssues', () => {expect(finalI3.seasonId).toBe(newS3.id);});+ it('does not mint a duplicate volume across repeated unlock-for-run resolves', async () => {+ // The divergence regression: the autopilot's unlock-for-run mode passes+ // `preserveDroppedSeasons`, so a minted look-alike volume gets the original+ // re-inserted next to it. Two rounds used to leave three Volume 1 records —+ // a blocking arc-verify finding that no further round could clear.+ const s = await setupSeries();+ await seriesSvc.updateSeries(s.id, { arc: { logline: 'L' } });+ const v1 = await seasonsSvc.createSeason(s.id, { number: 1, title: 'Salt at the Root', episodeCountTarget: 12 });+ const ep = await issuesSvc.createIssue({ seriesId: s.id, seasonId: v1.id, title: 'Ep 1' });++ let round = 0;+ stageRunnerSpy = vi.fn(async () => ({+ content: {+ arc: { logline: 'L2', summary: 'S', themes: [], protagonistArc: '' },+ // Same volume, rewritten synopsis, id omitted — verbatim the shape the+ // resolve prompt returns.+ seasons: [{ number: 1, title: 'Salt at the Root', synopsis: `revision ${++round}`, endingHook: '', episodeCountTarget: 12 }],+ notes: '',+ },+ runId: 'r', providerId: 'p', model: 'm',+ }));++ for (let i = 0; i < 2; i += 1) {+ await planner.resolveVerifyIssues(s.id, {+ findings: [{ severity: 'high', problem: 'X', suggestion: 'Y' }],+ preserveDroppedSeasons: true,+ });+ }++ const after = await seriesSvc.getSeries(s.id);+ expect(after.seasons).toHaveLength(1);+ expect(after.seasons[0].id).toBe(v1.id);+ expect(after.seasons[0].synopsis).toBe('revision 2'); // the rewrite still applied+ expect((await issuesSvc.getIssue(ep.id)).seasonId).toBe(v1.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' } });@@ -1130,6 +1169,31 @@ describe('arcPlanner — commitSeasonsWithRemap', () => {expect(out.series.arc.logline).toBe('latest locked logline');expect(out.series.arc.summary).toBe('incoming summary');});++ it('self-heals a pre-existing duplicate volume number and keeps its episodes attached', async () => {+ const s = await setupSeries();+ const keep = await seasonsSvc.createSeason(s.id, { number: 1, title: 'Salt at the Root', episodeCountTarget: 12 });+ const dupe = await seasonsSvc.createSeason(s.id, { number: 1, title: 'Salt at the Root', episodeCountTarget: 12 });+ const i1 = await issuesSvc.createIssue({ seriesId: s.id, seasonId: keep.id, title: 'Ep 1' });+ // An episode stranded under the duplicate must follow the survivor, not+ // fall into the ungrouped bucket.+ const i2 = await issuesSvc.createIssue({ seriesId: s.id, seasonId: dupe.id, title: 'Stranded' });++ const cur = await seriesSvc.getSeries(s.id);+ expect(cur.seasons).toHaveLength(2);++ // A perfectly ordinary arc write — the heal rides along with it.+ const out = await planner.commitSeasonsWithRemap(+ cur,+ { arc: DRAFT_ARC, seasons: cur.seasons },+ { preserveDroppedSeasons: true },+ );++ expect(out.series.seasons).toHaveLength(1);+ expect(out.series.seasons[0].id).toBe(keep.id);+ expect((await issuesSvc.getIssue(i1.id)).seasonId).toBe(keep.id);+ expect((await issuesSvc.getIssue(i2.id)).seasonId).toBe(keep.id);+ });});describe('arcPlanner — mergeSeasonsWithLocks', () => {@@ -1329,6 +1393,127 @@ describe('arcPlanner — preserveDroppedSeasonRecords', () => {});});+// The duplicate-volume divergence (2026-08-09): auto-resolve returned a+// rewritten Volume 1 without echoing its id, `preserveDroppedSeasons` re-inserted+// the original alongside the mint, and arc-verify filed "three records numbered+// 1" as a blocking finding — one MORE finding than the round started with, every+// round, until the autopilot paused for no net progress.+describe('arcPlanner — matchProposedSeasons', () => {+ const { matchProposedSeasons } = planner.__testing;+ const existing = [+ { id: 'sea-a', number: 1, title: 'Salt at the Root' },+ { id: 'sea-b', number: 2, title: 'Six Blocks Down' },+ ];++ it('matches an id-less rewrite to the existing record by title', () => {+ const matched = matchProposedSeasons(existing, [+ { number: 1, title: 'salt at the ROOT ', synopsis: 'rewritten' },+ ]);+ expect(matched[0]).toBe(existing[0]);+ });++ it('matches by number when the title was rewritten too', () => {+ const matched = matchProposedSeasons(existing, [{ number: 2, title: 'A New Name' }]);+ expect(matched[0]).toBe(existing[1]);+ });++ it('lets an id-carrying proposal win its own record over a same-titled sibling', () => {+ // Greedy single-pass matching would let the title-only proposal claim+ // sea-a first, forcing the id-carrying one to mint a duplicate.+ const matched = matchProposedSeasons(existing, [+ { number: 1, title: 'Salt at the Root' },+ { id: 'sea-a', number: 1, title: 'Salt at the Root' },+ ]);+ expect(matched[1]).toBe(existing[0]);+ expect(matched[0]).toBeNull();+ });++ it('leaves a genuinely new volume unmatched so it mints', () => {+ expect(matchProposedSeasons(existing, [{ number: 3, title: 'Brand New' }])).toEqual([null]);+ });++ it('refuses an ambiguous number match', () => {+ const dupes = [+ { id: 'sea-a', number: 1, title: 'One' },+ { id: 'sea-b', number: 1, title: 'Two' },+ ];+ expect(matchProposedSeasons(dupes, [{ number: 1, title: 'Neither' }])).toEqual([null]);+ });++ it('tolerates missing/empty inputs', () => {+ expect(matchProposedSeasons(null, [{ number: 1 }])).toEqual([null]);+ expect(matchProposedSeasons(existing, null)).toEqual([]);+ });+});++describe('arcPlanner — collapseDuplicateSeasonNumbers', () => {+ const { collapseDuplicateSeasonNumbers, hasDuplicateSeasonNumbers } = planner.__testing;++ it('detects duplicate numbers', () => {+ expect(hasDuplicateSeasonNumbers([{ number: 1 }, { number: 2 }])).toBe(false);+ expect(hasDuplicateSeasonNumbers([{ number: 1 }, { number: 1 }])).toBe(true);+ expect(hasDuplicateSeasonNumbers(null)).toBe(false);+ });++ it('keeps the record holding the episodes and reports the absorbed ids', () => {+ // The live shape: the original carries the 12 episodes, the two mints are+ // newer and empty.+ const seasons = [+ { id: 'sea-orig', number: 1, title: 'V1', createdAt: '2026-05-11T00:00:00.000Z', updatedAt: '2026-05-11T00:00:00.000Z', synopsis: 'original', themes: ['t'] },+ { id: 'sea-dup1', number: 1, title: 'V1', createdAt: '2026-08-09T14:25:00.000Z', updatedAt: '2026-08-09T14:25:00.000Z', synopsis: 'rev a', themes: [] },+ { id: 'sea-dup2', number: 1, title: 'V1', createdAt: '2026-08-09T14:30:00.000Z', updatedAt: '2026-08-09T14:30:00.000Z', synopsis: 'rev b', themes: [] },+ ];+ const { seasons: out, absorbed } = collapseDuplicateSeasonNumbers(+ seasons,+ new Map([['sea-orig', 12]]),+ );+ expect(out).toHaveLength(1);+ expect(out[0].id).toBe('sea-orig');+ expect(out[0].synopsis).toBe('original'); // never clobbered by a duplicate+ expect([...absorbed]).toEqual([['sea-dup1', 'sea-orig'], ['sea-dup2', 'sea-orig']]);+ });++ it('back-fills only fields the survivor left empty, newest duplicate first', () => {+ const seasons = [+ { id: 'sea-orig', number: 1, title: 'V1', createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z', synopsis: '', endingHook: 'keep me', themes: [] },+ { id: 'sea-old', number: 1, title: 'V1', createdAt: '2026-02-01T00:00:00.000Z', updatedAt: '2026-02-01T00:00:00.000Z', synopsis: 'stale', endingHook: 'drop me', themes: ['old'] },+ { id: 'sea-new', number: 1, title: 'V1', createdAt: '2026-03-01T00:00:00.000Z', updatedAt: '2026-03-01T00:00:00.000Z', synopsis: 'freshest', endingHook: 'drop me too', themes: ['new'] },+ ];+ const { seasons: out } = collapseDuplicateSeasonNumbers(seasons, new Map([['sea-orig', 3]]));+ expect(out[0].id).toBe('sea-orig');+ expect(out[0].synopsis).toBe('freshest');+ expect(out[0].endingHook).toBe('keep me');+ expect(out[0].themes).toEqual(['new']);+ });++ it('prefers a locked record over a better-populated unlocked one', () => {+ const seasons = [+ { id: 'sea-loose', number: 1, title: 'V1', createdAt: '2026-01-01T00:00:00.000Z' },+ { id: 'sea-locked', number: 1, title: 'V1', locked: true, createdAt: '2026-02-01T00:00:00.000Z' },+ ];+ const { seasons: out, absorbed } = collapseDuplicateSeasonNumbers(seasons, new Map([['sea-loose', 9]]));+ expect(out[0].id).toBe('sea-locked');+ expect(absorbed.get('sea-loose')).toBe('sea-locked');+ });++ it('leaves a group with two locked records intact rather than deleting a frozen volume', () => {+ const seasons = [+ { id: 'sea-l1', number: 1, title: 'V1', locked: true },+ { id: 'sea-l2', number: 1, title: 'V1', locked: true },+ ];+ const { seasons: out, absorbed } = collapseDuplicateSeasonNumbers(seasons, new Map());+ expect(out).toHaveLength(2);+ expect(absorbed.size).toBe(0);+ });++ it('leaves a clean list untouched and keeps number ordering', () => {+ const seasons = [{ id: 'b', number: 2 }, { id: 'a', number: 1 }];+ const { seasons: out, absorbed } = collapseDuplicateSeasonNumbers(seasons, new Map());+ expect(out.map((s) => s.id)).toEqual(['a', 'b']);+ expect(absorbed.size).toBe(0);+ });+});+describe('arcPlanner — mergeArcWithLocks', () => {it('replaces locked fields with the current arc values', () => {const current = { logline: 'a', summary: 'b', themes: ['t1'], protagonistArc: 'c', shape: 's1' };diff --git a/server/services/pipeline/arcPlanner/arcCore.js b/server/services/pipeline/arcPlanner/arcCore.jsindex 0e273a6681..8e4782f825 100644--- a/server/services/pipeline/arcPlanner/arcCore.js+++ b/server/services/pipeline/arcPlanner/arcCore.js@@ -411,12 +411,19 @@ export async function resolveVerifyIssues(seriesId, options = {}) {// brand-new entry (no `id`), otherwise preserve the existing `id` so child// issues still join their season cleanly. The sanitizer enforces the// canonical shape regardless.- const existingById = new Map((series.seasons || []).map((s) => [s.id, s]));const proposedSeasons = Array.isArray(content?.seasons) ? content.seasons : [];+ // Resolve each proposal to an existing record BEFORE minting. The resolve+ // prompt frequently returns a rewritten volume WITHOUT echoing its `id`;+ // matching on id alone read that as a brand-new season and minted one. With+ // `preserveDroppedSeasons` on (the autopilot's unlock-for-run mode) the+ // original was then re-inserted alongside the mint — so every auto-resolve+ // round ADDED a duplicate "Volume 1" instead of clearing a finding, and+ // arc-verify could never converge. See the divergence pause on 2026-08-09.+ const matchedExisting = matchProposedSeasons(series.seasons, proposedSeasons);// 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;+ const seasonEntries = proposedSeasons.map((raw, idx) => {+ const existing = matchedExisting[idx];if (existing) {return {season: sanitizeSeason({@@ -615,6 +622,176 @@ export function preserveDroppedSeasonRecords(currentSeasons, nextSeasons) {return dropped.length === 0 ? nextSeasons : [...dropped, ...nextSeasons];}+// Normalized title comparison, shared by the two season matchers below.+const normTitle = (s) => (typeof s === 'string' ? s.trim().toLowerCase() : '');++/**+ * Resolve each LLM-proposed season to the EXISTING season record it is a+ * rewrite of, so a rewrite lands on that record instead of minting a sibling.+ * Returns an array parallel to `proposedSeasons` holding the matched existing+ * season (or `null` when the proposal is genuinely new).+ *+ * Match priority mirrors `buildSeasonRemap`, and runs as three ordered passes+ * rather than one greedy sweep so a proposal that DOES carry an `id` always+ * wins its own record: a same-titled sibling processed earlier must not claim+ * it and push the id-carrying proposal into minting a duplicate.+ * 1. explicit `id`+ * 2. normalized title (the resolve prompt is told to preserve titles)+ * 3. `number`, only when exactly one unclaimed existing season has it+ *+ * Deliberately NOT a positional fallback — unlike `buildSeasonRemap`'s 1↔1+ * pass, a wrong guess here doesn't just misfile child issues, it overwrites a+ * volume's prose with another volume's rewrite. Unmatched proposals mint, which+ * is the recoverable outcome.+ */+export function matchProposedSeasons(existingSeasons, proposedSeasons) {+ const existing = Array.isArray(existingSeasons) ? existingSeasons.filter((s) => s?.id) : [];+ const proposed = Array.isArray(proposedSeasons) ? proposedSeasons : [];+ const matched = new Array(proposed.length).fill(null);+ if (existing.length === 0) return matched;+ const byId = new Map(existing.map((s) => [s.id, s]));+ const claimed = new Set();++ const claim = (idx, season) => {+ matched[idx] = season;+ claimed.add(season.id);+ };++ // Pass 1 — explicit id.+ proposed.forEach((raw, idx) => {+ const hit = raw?.id ? byId.get(raw.id) : null;+ if (hit && !claimed.has(hit.id)) claim(idx, hit);+ });++ // Pass 2 — normalized title.+ proposed.forEach((raw, idx) => {+ if (matched[idx]) return;+ const title = normTitle(raw?.title);+ if (!title) return;+ const hit = existing.find((s) => normTitle(s.title) === title && !claimed.has(s.id));+ if (hit) claim(idx, hit);+ });++ // Pass 3 — unambiguous `number`.+ proposed.forEach((raw, idx) => {+ if (matched[idx]) return;+ if (!Number.isFinite(raw?.number)) return;+ const hits = existing.filter((s) => s.number === raw.number && !claimed.has(s.id));+ if (hits.length === 1) claim(idx, hits[0]);+ });++ return matched;+}++// Prose fields a collapse may back-fill onto the surviving record. Only ever+// used to fill a field that is EMPTY on the survivor — never to overwrite.+const SEASON_FILLABLE_FIELDS = ['logline', 'synopsis', 'endingHook'];++// Rescue content that only exists on the records being absorbed, so collapsing+// a duplicate can't silently delete the one revision that had a synopsis.+function backfillSeasonGaps(survivor, group) {+ // Newest first — if several duplicates could fill a gap, the latest rewrite+ // is the one the user last saw.+ const donors = group+ .filter((s) => s.id !== survivor.id)+ .sort((a, b) => String(b.updatedAt || '').localeCompare(String(a.updatedAt || '')));+ let next = survivor;+ for (const key of SEASON_FILLABLE_FIELDS) {+ if (next[key]) continue;+ const donor = donors.find((d) => d[key]);+ if (donor) next = { ...next, [key]: donor[key] };+ }+ if (!next.themes?.length) {+ const donor = donors.find((d) => d.themes?.length);+ if (donor) next = { ...next, themes: donor.themes };+ }+ if (!next.episodeCountTarget) {+ const donor = donors.find((d) => d.episodeCountTarget);+ if (donor) next = { ...next, episodeCountTarget: donor.episodeCountTarget };+ }+ return next;+}++/** True when two or more seasons in the list share a `number`. Pure. */+export function hasDuplicateSeasonNumbers(seasons) {+ if (!Array.isArray(seasons)) return false;+ const seen = new Set();+ for (const s of seasons) {+ if (!s) continue;+ if (seen.has(s.number)) return true;+ seen.add(s.number);+ }+ return false;+}++/**+ * Collapse seasons that share a `number` down to one record per number, and+ * report which ids were absorbed so the caller can re-point their child issues.+ * Returns `{ seasons, absorbed: Map<absorbedId, survivorId> }`.+ *+ * Two volumes numbered the same is never a state a user can act on — the Arc+ * Canvas renders both, a volume export can't tell which is canonical, and+ * arc-verify files it as a blocking finding every round. Before+ * `matchProposedSeasons` existed, auto-resolve manufactured exactly this shape,+ * so the collapse doubles as the self-heal for installs that already diverged:+ * the next arc write repairs the record without a migration (the file-migration+ * runner executes before the Postgres pool, and series are db-primary).+ *+ * Survivor preference — the record with the strongest claim to the child+ * issues, so a collapse never strands episodes:+ * 1. `locked` (the user froze it)+ * 2. most child issues+ * 3. oldest `createdAt` (the original, not the bug's mint)+ *+ * A group holding TWO OR MORE locked records is left intact: silently deleting+ * a user-frozen volume is worse than the duplicate, and only a human can say+ * which freeze was intended. Those groups keep warning every write, which is+ * the correct nag.+ */+export function collapseDuplicateSeasonNumbers(seasons, issueCountBySeasonId = new Map()) {+ const absorbed = new Map();+ if (!Array.isArray(seasons)) return { seasons, absorbed };+ const byNumber = new Map();+ for (const s of seasons) {+ if (!s) continue;+ const group = byNumber.get(s.number);+ if (group) group.push(s);+ else byNumber.set(s.number, [s]);+ }++ const survivors = [];+ for (const [number, group] of byNumber) {+ if (group.length === 1) {+ survivors.push(group[0]);+ continue;+ }+ 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`,+ );+ survivors.push(...group);+ continue;+ }+ const episodes = (s) => issueCountBySeasonId.get(s.id) || 0;+ const [survivor] = [...group].sort((a, b) => (+ (b.locked === true ? 1 : 0) - (a.locked === true ? 1 : 0)+ || episodes(b) - episodes(a)+ || String(a.createdAt || '').localeCompare(String(b.createdAt || ''))+ ));+ survivors.push(backfillSeasonGaps(survivor, group));+ 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`,+ );+ }+ // Re-sort: `sanitizeSeasonList`'s number ordering is the contract consumers+ // render straight from, and the group walk above emits in first-seen order.+ return { seasons: survivors.sort((a, b) => (a.number || 0) - (b.number || 0)), absorbed };+}+/*** Persist a new `arc` + `seasons[]` onto a series, migrating any child issues* whose `seasonId` referenced a season that the new shape dropped or renamed.@@ -654,19 +831,47 @@ export async function commitSeasonsWithRemap(currentSeries, { arc, seasons }, op// rewrites, and re-insert any locked seasons the LLM dropped. Re-sanitize// so the locked records merge with the new shape (sort by number, dedup).const lockMerged = mergeSeasonsWithLocks(latestSeries.seasons, seasons);- const mergedSeasons = sanitizeSeasonList(+ let mergedSeasons = sanitizeSeasonList(options.preserveDroppedSeasons === true? preserveDroppedSeasonRecords(latestSeries.seasons, lockMerged): lockMerged,);++ // One `listIssues` for the whole commit — the collapse below needs per-season+ // episode counts and the reassign sweep needs the same list.+ let allIssues = null;+ const loadIssues = async () => {+ if (allIssues === null) allIssues = await listIssues({ seriesId });+ return allIssues;+ };++ // Self-heal duplicate volume numbers on the way through. `sanitizeSeasonList`+ // dedupes by `id` only, so two records both numbered 1 survive it happily —+ // and that shape is a blocking arc-verify finding no amount of LLM rewriting+ // can clear. Absorbed ids are threaded into the remap below so their episodes+ // follow the survivor instead of falling into the ungrouped bucket.+ let absorbed = new Map();+ if (hasDuplicateSeasonNumbers(mergedSeasons)) {+ const counts = new Map();+ for (const iss of await loadIssues()) {+ if (iss.seasonId) counts.set(iss.seasonId, (counts.get(iss.seasonId) || 0) + 1);+ }+ ({ seasons: mergedSeasons, absorbed } = collapseDuplicateSeasonNumbers(mergedSeasons, counts));+ }+const newIds = new Set(mergedSeasons.map((s) => s.id));const droppedOldSeasons = (latestSeries.seasons || []).filter((s) => !newIds.has(s.id));const oldIds = new Set((latestSeries.seasons || []).map((s) => s.id));const newlyMintedSeasons = mergedSeasons.filter((s) => !oldIds.has(s.id));const remap = buildSeasonRemap(droppedOldSeasons, newlyMintedSeasons);+ // An absorbed duplicate has a KNOWN survivor, which beats buildSeasonRemap's+ // title/number inference — that pass only considers freshly-minted seasons as+ // targets, so a duplicate absorbed into an existing record would otherwise+ // map to null and orphan every episode under it.+ for (const [absorbedId, survivorId] of absorbed) remap.set(absorbedId, survivorId);const droppedIdSet = new Set(droppedOldSeasons.map((s) => s.id));const reassignList = droppedIdSet.size- ? (await listIssues({ seriesId })).filter((iss) => droppedIdSet.has(iss.seasonId))+ ? (await loadIssues()).filter((iss) => droppedIdSet.has(iss.seasonId)): [];// Mirrors `deleteSeason`'s bulk-reassign idiom — `skipRenumber` per call +