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
harden the scene-id backfill: atomic record writes + duplicate-id normalization (#3413)
[._.]/ Adam Eivy8e8f94e0c602
diff --git a/scripts/migrations/222-storyboard-scene-durable-ids.js b/scripts/migrations/222-storyboard-scene-durable-ids.jsindex d45d1c593c..c48d2e9ee4 100644--- a/scripts/migrations/222-storyboard-scene-durable-ids.js+++ b/scripts/migrations/222-storyboard-scene-durable-ids.js@@ -29,8 +29,9 @@* writes nothing.*/-import { readFile, writeFile, readdir, stat } from 'fs/promises';+import { readFile, readdir, stat } from 'fs/promises';import { join } from 'path';+import { atomicWrite } from '../../server/lib/fileUtils.js';import { ensureStoryboardIds } from '../../server/lib/storyboardScenes.js';const readJsonOrNull = async (path) => {@@ -87,7 +88,12 @@ export default {const issue = await readJsonOrNull(recordPath);if (!issue) continue;if (stampIssue(issue)) {- await writeFile(recordPath, `${JSON.stringify(issue, null, 2)}\n`);+ // atomicWrite (temp file + rename), never a truncating writeFile: an+ // interrupted rewrite of a live issue record would otherwise leave+ // unparseable JSON that the next pass silently skips — permanent data+ // loss for that issue, since the migration would already be marked+ // applied.+ await atomicWrite(recordPath, `${JSON.stringify(issue, null, 2)}\n`);touched += 1;}}diff --git a/server/lib/README.md b/server/lib/README.mdindex 98a1e2858c..5f6d1c1fe4 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -71,7 +71,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `sceneExtractor.js` | Split prose or teleplay into scene list via LLM. || `proseExportSettings.js` | Per-series prose-export settings (#2181): `sanitizeProseExportSettings` + `resolveExportSettings` + `TRIM_SIZES`/`INTERIOR_FONTS` for the manuscript/ePub/PDF exports. || `shotGrammar.js` | Pure shot-grammar vocabularies (`SHOT_TYPES`, `SCREEN_DIRECTIONS`) + normalizers (`normalizeShotType`, `normalizeScreenDirection`) for a storyboard shot's camera framing + on-screen direction. Shared by the scene extractor's sanitizer, the storyboards Zod schema, and the `visual.shot-continuity` editorial check (#1315). |-| `storyboardScenes.js` | Durable ids + id-first addressing for `stages.storyboards.scenes[]` (#3413). `ensureStoryboardIds(scenes)` stamps a deterministic `scene-NN` / `shot-NN` id on any entry lacking one (collision-escaped with a `-2` suffix, so peers and concurrent readers derive identical ids); `resolveStoryboardTarget(list, { id, index })` → `{ index, record, matchedBy, stale }` resolves a captured id against a fresh array, falling back to the index only when no id was captured, and reporting `stale: true` (409, never an index retarget) when a captured id is gone. |+| `storyboardScenes.js` | Durable ids + id-first addressing for `stages.storyboards.scenes[]` (#3413). `ensureStoryboardIds(scenes)` stamps a deterministic `scene-NN` / `shot-NN` id on any entry lacking one — and re-stamps later copies of a DUPLICATE id (collision-escaped with a `-2` suffix, so peers and concurrent readers derive identical ids); `resolveStoryboardTarget(list, { id, index })` → `{ index, record, matchedBy, stale }` resolves a captured id against a fresh array, falling back to the index only when no id was captured, and reporting `stale: true` (409, never an index retarget) when a captured id is gone. || `seasonStructure.js` | Season/episode structure recommendation. || `seriesCharacterArc.js` | Per-character story-arc shapes (`series.characterArcs[]`): want/need, start → end state, transition beats. Sanitizers + `renderCharacterArcsForPrompt` for the `arc.transitions` editorial check. || `seriesLlmOverride.js` | Pure `resolveSeriesLlmOverride(series, { overrideProvider, overrideModel })` → `{ provider, model, providerMatchesSeries }` — shared fallback so Pipeline LLM actions honor the series' configured provider/model, only inheriting the series model when the effective provider still matches. |diff --git a/server/lib/storyboardScenes.js b/server/lib/storyboardScenes.jsindex b7affc60ed..6f0298195b 100644--- a/server/lib/storyboardScenes.js+++ b/server/lib/storyboardScenes.js@@ -29,7 +29,10 @@** A deterministic base that is already taken gets a `-2`, `-3`, … suffix, so* an array that already holds `scene-01` never gets a duplicate stamped onto- * it (duplicate ids would make id resolution ambiguous).+ * it — and an array that ALREADY carries duplicate ids (a duplicated scene, or+ * the scene extractor's tolerated duplicate shot ids) has the later copies+ * re-stamped. Duplicate ids would make id resolution ambiguous, which is the+ * mis-target this module exists to prevent.*/const ID_MAX = 80;@@ -47,19 +50,35 @@ const uniqueId = (base, taken) => {return `${base}-${n}`;};-// Stamp `id` on every entry that lacks one. Returns the ORIGINAL array-// reference when nothing changed so callers can cheaply detect a no-op.+// Stamp `id` on every entry that lacks one, and re-stamp any entry whose id+// DUPLICATES an earlier entry's. A duplicate id is as bad as no id: the+// resolver tie-breaks on the captured index, so once two same-id entries are+// reordered the write lands on the wrong one — exactly the mis-target this+// module exists to prevent. First occurrence keeps the id (matching+// `sanitizeShots`' first-wins resolution of `continuityFromShotId`), later+// ones are re-stamped.+//+// Returns the ORIGINAL array reference when nothing changed so callers can+// cheaply detect a no-op.const stampIds = (list, idFor) => {if (!Array.isArray(list) || list.length === 0) return list;- const taken = new Set(- list.filter((r) => r && typeof r === 'object' && isNonEmptyStr(r.id)).map((r) => r.id),- );+ // Only ids that survive as-is (the FIRST occurrence of each) count as taken;+ // a duplicate is about to be replaced, so it must not reserve its own id.+ const taken = new Set();+ for (const rec of list) {+ if (rec && typeof rec === 'object' && isNonEmptyStr(rec.id)) taken.add(rec.id);+ }+ const seen = new Set();let changed = false;const out = list.map((rec, i) => {if (!rec || typeof rec !== 'object' || Array.isArray(rec)) return rec;- if (isNonEmptyStr(rec.id)) return rec;+ if (isNonEmptyStr(rec.id) && !seen.has(rec.id)) {+ seen.add(rec.id);+ return rec;+ }const id = uniqueId(idFor(i).slice(0, ID_MAX), taken);taken.add(id);+ seen.add(id);changed = true;return { ...rec, id };});diff --git a/server/lib/storyboardScenes.test.js b/server/lib/storyboardScenes.test.jsindex 6cc9a28b41..7acefc2638 100644--- a/server/lib/storyboardScenes.test.js+++ b/server/lib/storyboardScenes.test.js@@ -28,6 +28,36 @@ describe('ensureStoryboardIds', () => {expect(out[1].id).toBe('scene-01');});+ it('re-stamps a DUPLICATE id, keeping the first occurrence', () => {+ // A duplicated scene is as ambiguous as an id-less one: after a reorder the+ // captured-index tiebreak would land the write on the wrong copy.+ const out = ensureStoryboardIds([+ { id: 'scene-01', description: 'original' },+ { id: 'scene-01', description: 'duplicate' },+ ]);+ expect(out[0].id).toBe('scene-01');+ expect(out[0].description).toBe('original');+ expect(out[1].id).toBe('scene-02');+ expect(new Set(out.map((s) => s.id)).size).toBe(2);+ });++ it('re-stamps duplicate SHOT ids too (the scene extractor tolerates them)', () => {+ const out = ensureStoryboardIds([{+ id: 'scene-01',+ shots: [{ id: 'shot-01' }, { id: 'shot-01' }, { id: 'shot-01' }],+ }]);+ expect(out[0].shots.map((s) => s.id)).toEqual(['shot-01', 'shot-02', 'shot-03']);+ });++ it('escapes when the deterministic replacement for a duplicate is itself taken', () => {+ const out = ensureStoryboardIds([+ { id: 'dup' },+ { id: 'dup' },+ { id: 'scene-02' },+ ]);+ expect(out.map((s) => s.id)).toEqual(['dup', 'scene-02-2', 'scene-02']);+ });+it('passes non-array / empty input straight through', () => {expect(ensureStoryboardIds(null)).toBe(null);expect(ensureStoryboardIds(undefined)).toBe(undefined);