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
refactor([issue-3152]): collapse the effective-registry boilerplate and drop three dead exports
[._.]/ Adam Eivyb06ba1ea58e7
diff --git a/client/src/components/sprites/ReferenceWorkflow.jsx b/client/src/components/sprites/ReferenceWorkflow.jsxindex bef8c76ed8..60c381a279 100644--- a/client/src/components/sprites/ReferenceWorkflow.jsx+++ b/client/src/components/sprites/ReferenceWorkflow.jsx@@ -376,7 +376,12 @@ export default function ReferenceWorkflow({ record, reference, renders, correcticonst [unlockMain, mainUnlocking] = useAsyncAction(async () => {const result = await unlockSpriteMainReference(recordId, { silent: true });- toast.success(result.walkInvalidated || result.scannerInvalidated+ // Read the per-track MAP, not the legacy `scannerInvalidated` alias (#3152):+ // every non-walk track is user-defined now, so a user who deleted `scanner` and+ // added their own anchor-seeded track would otherwise be told nothing was+ // reopened while their approvals had in fact been dropped.+ const tracksReopened = Object.values(result.tracksInvalidated || {}).some(Boolean);+ toast.success(result.walkInvalidated || tracksReopened? 'Main reference unlocked; its south animations were reopened': 'Main reference unlocked; ready to regenerate from the turnaround');setMainUnlockConfirming(false);diff --git a/scripts/migrations/211-seed-user-defined-animation-tracks.js b/scripts/migrations/211-seed-user-defined-animation-tracks.jsindex 1072a785d3..a2d5a7753b 100644--- a/scripts/migrations/211-seed-user-defined-animation-tracks.js+++ b/scripts/migrations/211-seed-user-defined-animation-tracks.js@@ -33,13 +33,18 @@* beats a clean reseed.*/-import { readFile, writeFile, mkdir, access } from 'fs/promises';-import { join, dirname } from 'path';+import { readFile } from 'fs/promises';+import { join } from 'path';+// `atomicWrite` (ensureDir + temp + rename) rather than mkdir+writeFile, the same+// helper `_seedStageHelpers.js` and 30-odd sibling migrations use. Not cosmetic+// here: a truncated store would make this migration's own existence check report+// `already-present` forever while the store throws "not valid JSON" at module+// load, taking down everything that imports validation.js. It passes a string+// through unchanged, so the seed still lands byte-for-byte.+import { atomicWrite, pathExists } from '../../server/lib/fileUtils.js';const STORE_REL = join('sprites', 'animation-tracks.json');-const exists = async (path) => access(path).then(() => true, () => false);-export async function up({ rootDir }) {const seedPath = join(rootDir, 'data.reference', STORE_REL);const storePath = join(rootDir, 'data', STORE_REL);@@ -47,7 +52,7 @@ export async function up({ rootDir }) {// Present in ANY state (valid, empty, corrupt) means the user owns this file —// stop. Checked by existence rather than by parsing, because a file that fails// to parse is exactly the case where overwriting would destroy user edits.- if (await exists(storePath)) {+ if (await pathExists(storePath)) {console.log('🎬 animation-tracks: store already present — no-op.');return { ok: true, reason: 'already-present' };}@@ -73,8 +78,7 @@ export async function up({ rootDir }) {return { ok: true, reason: 'invalid-seed' };}- await mkdir(dirname(storePath), { recursive: true });- await writeFile(storePath, seed.endsWith('\n') ? seed : `${seed}\n`);+ await atomicWrite(storePath, seed.endsWith('\n') ? seed : `${seed}\n`);const count = Array.isArray(parsed?.tracks) ? parsed.tracks.length : 0;console.log(`🎬 animation-tracks: seeded ${count} editable animation ${count === 1 ? 'track' : 'tracks'} into data/${STORE_REL}.`);return { ok: true, reason: 'seeded', count };diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 881107af96..fb86af0dfc 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -5,14 +5,14 @@ import { WORK_TRACKERS } from './workTracker.js';import { SPRITE_ID_PATTERN, SPRITE_RECORD_KINDS } from '../services/sprites/recordsLogic.js';import { ANCHOR_DIRECTIONS, SPRITE_DIRECTIONS, TURNAROUND_ID } from '../services/sprites/prompts.js';import { CHROMA_KEY_HEXES } from '../services/sprites/chromaKey.js';-import { WALK_TRACK, getAnimationTrack } from '../services/sprites/animationTracks.js';+import { WALK_TRACK } from '../services/sprites/animationTracks.js';// #3152 — the EFFECTIVE table (compiled `walk` + the user-defined store), so a// user's track validates against its own bounds and occupies its own contract// field with no schema edit. The store reads one small JSON config synchronously// (see its header for why sync is the right answer here), which is what lets the// schemas below stay module-load constants rather than becoming lazily-built.import {- getEffectiveAnimationTracks, getEffectiveAnimationTrackIds,+ effectiveTrack, getEffectiveAnimationTracks, getEffectiveAnimationTrackIds,} from '../services/sprites/animationTrackStore.js';import { QUEUEABLE_IMAGE_MODES } from '../services/imageGen/modes.js';import { GROK_VIDEO_DURATIONS } from './grokVideoClip.js';@@ -996,12 +996,12 @@ export const videoDownloadSchema = z.object({// carries a track id until the first second track lands, and an exported-but-// unwired validator is false confidence.export function spriteTrackFrameCountSchema(track) {- const row = getAnimationTrack(track, getEffectiveAnimationTracks());+ const row = effectiveTrack(track);return z.number().int().min(row.minFrameCount).max(row.maxFrameCount);}export function spriteTrackFpsSchema(track) {- const row = getAnimationTrack(track, getEffectiveAnimationTracks());+ const row = effectiveTrack(track);return z.number().int().min(row.minFps).max(row.maxFps);}diff --git a/server/services/sprites/animationTargets.js b/server/services/sprites/animationTargets.jsindex 68ded13fd2..4c2313537d 100644--- a/server/services/sprites/animationTargets.js+++ b/server/services/sprites/animationTargets.js@@ -29,13 +29,11 @@* by walk's floor of 6.*/-import {- WALK_TRACK, getAnimationTrack,-} from './animationTracks.js';+import { WALK_TRACK } from './animationTracks.js';// #3152 — resolve against the EFFECTIVE table (compiled `walk` + the user-defined// store) so a user's track resolves its own bounds and contract field rather than// throwing as unknown. Still sharp-free: the store reaches only fs/path/crypto.-import { getEffectiveAnimationTracks } from './animationTrackStore.js';+import { effectiveTrack } from './animationTrackStore.js';// Re-exported so existing importers (walk.js) keep reaching the walk track id// here; the registry owns the value now, so the two can never disagree.@@ -89,7 +87,7 @@ export function resolveAnimationTarget({packagedCycles = [],} = {}) {// Absent → the default track; unrecognized → throws (see getAnimationTrack).- const row = getAnimationTrack(track, getEffectiveAnimationTracks());+ const row = effectiveTrack(track);// The bound app's declared expectation for its own atlas (#2982) — a stronger// authority than any per-render pick. Read defensively: that field lands@@ -141,7 +139,7 @@ function firstDefined(list, read) {* unrecognized write target throws while sibling keys are untouched either way.*/export function withTrackTarget(animationTargets, track, { frameCount, fps, source }) {- const row = getAnimationTrack(track, getEffectiveAnimationTracks());+ const row = effectiveTrack(track);const existing = (animationTargets && typeof animationTargets === 'object' && !Array.isArray(animationTargets))? animationTargets: {};@@ -159,7 +157,7 @@ export function withTrackTarget(animationTargets, track, { frameCount, fps, sour* to the default track when the caller passed a bare `{ frameCount, fps }`.*/export function targetDrift(target, packagedCycles = []) {- const row = getAnimationTrack(target?.track, getEffectiveAnimationTracks());+ const row = effectiveTrack(target?.track);return (packagedCycles || []).flatMap((cycle) => {const frameCount = readFrameCount(row, cycle?.frameCount);const fps = readFps(row, cycle?.fps);diff --git a/server/services/sprites/animationTrackStore.js b/server/services/sprites/animationTrackStore.jsindex 494ffbd95b..bed677dc37 100644--- a/server/services/sprites/animationTrackStore.js+++ b/server/services/sprites/animationTrackStore.js@@ -67,14 +67,17 @@* would make the registry silently mutable mid-request — a compile could then* validate spans against a table the render that produced them never saw.* `__resetAnimationTrackStore()` exists for tests and for the CRUD UI (#3153) to- * invalidate after a write. `null` = not loaded, `{}` = loaded and legitimately- * empty, so a zero-row install caches instead of re-reading on every lookup.+ * invalidate after a write. The memo holds the MERGED table (never `null` once+ * resolved, since `walk` is always in it), so a zero-row install caches too rather+ * than re-reading on every lookup.*/import { readFileSync } from 'fs';import { join } from 'path';import { PATHS } from '../../lib/fileUtils.js';-import { ANIMATION_TRACKS, WALK_TRACK, assertAnimationTrackRows } from './animationTracks.js';+import {+ ANIMATION_TRACKS, WALK_TRACK, assertAnimationTrackRows, getAnimationTrack,+} from './animationTracks.js';/** The store file, relative to `data/` (and to `data.reference/` for the seed). */export const ANIMATION_TRACK_STORE_REL = 'sprites/animation-tracks.json';@@ -86,19 +89,12 @@ export const animationTrackStorePath = () => join(PATHS.data, ANIMATION_TRACK_ST/** The shipped seed, read only when the user copy is absent (see the header). */export const animationTrackSeedPath = () => join(PATHS.root, 'data.reference', ANIMATION_TRACK_STORE_REL);-// `null` = not read yet; `{}` = read and empty. See the header's sentinel note.-let cachedStoredRows = null;-// The merged table, memoized alongside the rows so `assertAnimationTrackRows`-// runs once per process rather than on every registry lookup.+// The merged table — `null` until first resolve. ONE cache, on the merged result+// rather than also on the raw rows: `assertAnimationTrackRows` runs over the merge,+// so memoizing the raw read too would only pin a row set that failed validation,+// and a user who then fixed their JSON would keep getting the stale error.let cachedEffectiveTracks = null;-/**- * Read one candidate store file. Returns `null` for "not there" (try the next- * candidate) and THROWS for "there but unreadable" — the sentinel rule: a- * corrupt store must not silently degrade to the seed, or a user whose edits- * broke the JSON would see their tracks quietly revert to shipped defaults with- * no error to explain it.- *//*** Which of the three failure kinds a read error is:*@@ -117,6 +113,13 @@ export function classifyStoreReadError(err) {return err.code === 'ENOENT' ? 'absent' : 'io-error';}+/**+ * Read one candidate store file. Returns `null` for "not there" (try the next+ * candidate) and THROWS for "there but unreadable" — the sentinel rule: a corrupt+ * store must not silently degrade to the seed, or a user whose edits broke the JSON+ * would see their tracks quietly revert to shipped defaults with no error to+ * explain it.+ */function readStoreDoc(path) {let raw;try {@@ -188,7 +191,6 @@ const normalizeStoredRow = (raw) => Object.freeze({* exists, or when the resolved file holds no `tracks` array.*/function loadStoredRows() {- if (cachedStoredRows) return cachedStoredRows;const doc = resolveStoreDoc();const rows = Array.isArray(doc?.tracks) ? doc.tracks : [];const byId = {};@@ -207,8 +209,7 @@ function loadStoredRows() {if (byId[id]) throw new Error(`${ANIMATION_TRACK_STORE_REL}: track '${id}' is defined twice`);byId[id] = normalizeStoredRow(raw);}- cachedStoredRows = Object.freeze(byId);- return cachedStoredRows;+ return Object.freeze(byId);}/**@@ -236,6 +237,19 @@ export function getEffectiveAnimationTrackIds() {return Object.keys(getEffectiveAnimationTracks());}+/**+ * One row out of the effective table — `getAnimationTrack(id, getEffectiveAnimationTracks())`,+ * which was being spelled out at a dozen call sites.+ *+ * Keeps `getAnimationTrack`'s exact boundary (absent ⇒ `walk`, unrecognized ⇒+ * throws naming the known tracks) — it IS that call, just named. Modules that must+ * work against an injected table still call `getAnimationTrack(id, tracks)`+ * directly; that parameter is the test seam and is deliberately untouched.+ */+export function effectiveTrack(id) {+ return getAnimationTrack(id, getEffectiveAnimationTracks());+}+/*** Drop the cached store read.*@@ -244,6 +258,5 @@ export function getEffectiveAnimationTrackIds() {* serving the old table.*/export function __resetAnimationTrackStore() {- cachedStoredRows = null;cachedEffectiveTracks = null;}diff --git a/server/services/sprites/animationTrackStore.test.js b/server/services/sprites/animationTrackStore.test.jsindex 3e2457b29c..c7c0f87571 100644--- a/server/services/sprites/animationTrackStore.test.js+++ b/server/services/sprites/animationTrackStore.test.js@@ -27,6 +27,7 @@ import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';import { mkdtempSync, rmSync, mkdirSync, writeFileSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';+import { storedTrackRow } from './spriteTestFixtures.js';const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-track-store-test-'));@@ -45,28 +46,13 @@ const { ANIMATION_TRACKS, WALK_TRACK } = await import('./animationTracks.js');const STORE_PATH = animationTrackStorePath();-/** A minimal well-formed user row — every field the guard requires, nothing more. */-const userRow = (overrides = {}) => ({- id: 'chest-opening',- label: 'Chest opening',- directional: false,- kinds: ['object'],- minFrameCount: 2,- maxFrameCount: 8,- defaultFrameCount: 4,- minFps: 2,- maxFps: 12,- defaultFps: 6,- contractFrameCountField: 'chestOpeningFrameCount',- contractFpsField: null,- selectionKind: 'reviewed-chest-opening-selection',- setKind: 'finalized-chest-opening-set',- finalErrorCode: 'CHEST_OPENING_SET_FINAL',- standaloneContract: true,- promptTemplate: 'Animate the {{kind}} {{name}} opening once, then hold. Matte on {{chromaKeyPhrase}}.',- ...overrides,-});+// The shared stored-row shape (spriteTestFixtures.js), so a future required row+// field is one edit rather than one per suite.+const userRow = storedTrackRow;+// Written synchronously here (not through the shared async `writeAnimationTrackStore`)+// because `beforeEach` must have the file in place before the first sync store read,+// and several cases write a deliberately malformed string.const writeStore = (doc) => {mkdirSync(join(TEST_ROOT, 'sprites'), { recursive: true });writeFileSync(STORE_PATH, typeof doc === 'string' ? doc : JSON.stringify(doc, null, 2));diff --git a/server/services/sprites/animationTrackWorkflow.js b/server/services/sprites/animationTrackWorkflow.jsindex 262a12b54a..a1eed60f76 100644--- a/server/services/sprites/animationTrackWorkflow.js+++ b/server/services/sprites/animationTrackWorkflow.js@@ -50,11 +50,11 @@ import { getRecord } from './records.js';import { requireTrack, loadManifest } from './reference.js';import { anchorIdForDirection } from './prompts.js';import { buildTrackVideoPrompt } from './trackPrompts.js';-import { clampTrackFrameCount, clampTrackFps, getAnimationTrack, sourceReferenceFor } from './animationTracks.js';+import { clampTrackFrameCount, clampTrackFps, sourceReferenceFor } from './animationTracks.js';// #3152 — this workflow drives ANY row, so every registry lookup resolves against// the effective table (compiled `walk` + the user-defined store); a user's own// track reaches generate/approve through exactly this path with no new code.-import { getEffectiveAnimationTracks } from './animationTrackStore.js';+import { effectiveTrack, getEffectiveAnimationTracks } from './animationTrackStore.js';import { trackDirections } from './atlasGrid.js';import { spriteDir, resolveSpriteAssetPath, SOURCE_CLIP_NAME } from './paths.js';import { prepareWalkAnchorChromaInput, runWalkPostprocess } from './walkPostprocess.js';@@ -134,7 +134,7 @@ async function trackRuns(trackId, recordId) {* spellings (`scannerSet`/`ambientSet`) went away with the clones.*/export async function getTrackState(trackId, recordId) {- const row = getAnimationTrack(trackId, getEffectiveAnimationTracks());+ const row = effectiveTrack(trackId);const [selection, set, runs] = await Promise.all([loadSelection(row.id, recordId), loadSet(row.id, recordId), trackRuns(row.id, recordId),]);@@ -213,7 +213,7 @@ export function startTrackGeneration(trackId, recordId, body) {}async function startTrackGenerationImpl(trackId, recordId, body) {- const row = getAnimationTrack(trackId, getEffectiveAnimationTracks());+ const row = effectiveTrack(trackId);const [record, reference, existingSet, existingRuns] = await Promise.all([requireTrack(recordId, row.id), loadManifest(recordId), loadSet(row.id, recordId), trackRuns(row.id, recordId),]);@@ -237,8 +237,9 @@ async function startTrackGenerationImpl(trackId, recordId, body) {);}- const frameCount = clampTrackFrameCount(body.frameCount, row.id, getEffectiveAnimationTracks());- const fps = clampTrackFps(body.fps, row.id, getEffectiveAnimationTracks());+ const effectiveTracks = getEffectiveAnimationTracks();+ const frameCount = clampTrackFrameCount(body.frameCount, row.id, effectiveTracks);+ const fps = clampTrackFps(body.fps, row.id, effectiveTracks);// Optional re-roll note (#3134) — blank leaves the prompt and the run record// exactly as a blind regenerate would.const correctionPrompt = typeof body.correctionPrompt === 'string' ? body.correctionPrompt.trim() : '';@@ -324,7 +325,7 @@ async function runTrackTuiRender(row, recordId, { runId, direction, generatedAbs}export async function attachTrackTuiResult(trackId, recordId, runId, videoAbs) {- const row = getAnimationTrack(trackId, getEffectiveAnimationTracks());+ const row = effectiveTrack(trackId);const run = await loadRun(recordId, runId);if (!run || run.track !== row.id || await loadSet(row.id, recordId)) return;const selection = await loadSelection(row.id, recordId);@@ -354,6 +355,7 @@ async function packageTrackRun(row, recordId, run) {const chromaKey = resolveChromaKey({ manifest: reference, record, run });if (!chromaKey) throw new Error(`No chroma key is available for the ${row.label.toLowerCase()} matte`);const runRel = runRelPath(run.id);+ const effectiveTracks = getEffectiveAnimationTracks();const result = await runWalkPostprocess({recordId,track: row.id,@@ -364,8 +366,8 @@ async function packageTrackRun(row, recordId, run) {anchorRel: source.locked.path,anchorAbs: resolveSpriteAssetPath(recordId, source.locked.path),videoAbs: resolveSpriteAssetPath(recordId, run.sourceVideoPath),- frameCount: clampTrackFrameCount(run.frameCount, row.id, getEffectiveAnimationTracks()),- fps: clampTrackFps(run.fps, row.id, getEffectiveAnimationTracks()),+ frameCount: clampTrackFrameCount(run.frameCount, row.id, effectiveTracks),+ fps: clampTrackFps(run.fps, row.id, effectiveTracks),});run.frameCount = result.manifest.frameCount;run.fps = result.manifest.frameRate;@@ -386,7 +388,7 @@ export function approveTrackRun(trackId, recordId, args) {}async function approveTrackRunImpl(trackId, recordId, { direction: requested, runId }) {- const row = getAnimationTrack(trackId, getEffectiveAnimationTracks());+ const row = effectiveTrack(trackId);await requireTrack(recordId, row.id);if (await loadSet(row.id, recordId)) throw setFinalError(row);const direction = resolveTrackDirection(row, requested);@@ -480,7 +482,7 @@ export function invalidateTrackForTurnaroundRevision(trackId, recordId) {}async function invalidateTrackDirectionImpl(trackId, recordId, direction) {- const row = getAnimationTrack(trackId, getEffectiveAnimationTracks());+ const row = effectiveTrack(trackId);const [finalizedSet, loaded] = await Promise.all([loadSet(row.id, recordId), loadSelection(row.id, recordId)]);const approved = loaded?.directions?.[direction] || finalizedSet?.directions?.[direction];if (approved?.status !== 'approved') return false;diff --git a/server/services/sprites/animationTracks.js b/server/services/sprites/animationTracks.jsindex 74c01a5bab..6a38f3407e 100644--- a/server/services/sprites/animationTracks.js+++ b/server/services/sprites/animationTracks.js@@ -174,8 +174,12 @@ export const ANIMATION_TRACKS = Object.freeze({}),});-/** Known track ids, in registry order. */-export const ANIMATION_TRACK_IDS = Object.freeze(Object.keys(ANIMATION_TRACKS));+// There is deliberately no `ANIMATION_TRACK_IDS` export (#3152 removed it). It+// would now mean "the COMPILED ids" — `['walk']` — while reading as "every track+// id", which is the wrong answer at every call site that wanted it: those want the+// merged table's ids and must ask `getEffectiveAnimationTrackIds()` in+// `animationTrackStore.js`. Iterate `Object.keys(ANIMATION_TRACKS)` inline when you+// genuinely mean the compiled rows only./*** Validate a registry's rows, throwing on the first violation.@@ -230,17 +234,20 @@ export function assertAnimationTrackRows(tracks) {if (typeof row.builtin !== 'boolean') {throw new Error(`animationTracks: track '${id}' needs a boolean 'builtin'`);}- // A stored row has no compiled prompt builder, so a missing/blank template- // would surface as a throw out of `buildTrackVideoPrompt` only AFTER the user- // clicked generate — refuse it at load, where the message can name the row.- // A builtin row must NOT carry one: two prompt sources for one track is the- // drift this whole registry exists to prevent, and the stored value would- // silently win over the wording `prompts.test.js` pins.- if (!row.builtin && (typeof row.promptTemplate !== 'string' || !row.promptTemplate.trim())) {- throw new Error(`animationTracks: user-defined track '${id}' needs a non-empty 'promptTemplate'`);- }- if (row.builtin && row.promptTemplate !== undefined) {- throw new Error(`animationTracks: builtin track '${id}' must not carry a 'promptTemplate' — its prompt is the compiled builder`);+ // EXACTLY ONE prompt source per row — the invariant, stated as itself rather+ // than as two provenance checks. A row's prompt is either the compiled builder+ // `trackPrompts.js` holds for it (`builtin`, no template) or its own+ // `promptTemplate` (stored). Neither means a throw out of `buildTrackVideoPrompt`+ // AFTER the user clicked generate; both means two definitions of one track's+ // wording, where the stored value silently wins over the text+ // `prompts.test.js` pins. Refuse either at load, where the message names the row.+ const hasTemplate = typeof row.promptTemplate === 'string' && !!row.promptTemplate.trim();+ if (hasTemplate === row.builtin) {+ throw new Error(+ row.builtin+ ? `animationTracks: builtin track '${id}' must not carry a 'promptTemplate' — its prompt is the compiled builder`+ : `animationTracks: user-defined track '${id}' needs a non-empty 'promptTemplate'`,+ );}// Two tracks sharing a selection/set `kind` is the same class of bug as two// sharing a contract field: the compiler validates a set by its `kind`, so adiff --git a/server/services/sprites/animationTracks.test.js b/server/services/sprites/animationTracks.test.jsindex c71205d92b..d41ab6d40b 100644--- a/server/services/sprites/animationTracks.test.js+++ b/server/services/sprites/animationTracks.test.js@@ -21,7 +21,7 @@ import { readFileSync } from 'fs';import { fileURLToPath } from 'url';import { dirname, join } from 'path';import {- WALK_TRACK, SCANNER_TRACK, AMBIENT_TRACK, ANIMATION_TRACKS, ANIMATION_TRACK_IDS,+ WALK_TRACK, SCANNER_TRACK, AMBIENT_TRACK, ANIMATION_TRACKS,isAnimationTrack, getAnimationTrack, clampTrackFrameCount, clampTrackFps,assertAnimationTrackRows, trackRowCount, tracksForKind, kindSupportsTrack,sourceReferenceFor, primaryTrackForKind,@@ -73,7 +73,7 @@ describe('the registry rows', () => {// specifically — `EFFECTIVE` would pass here forever, since it contains the// seeded rows, so a regression that re-added `scanner` to the literal would// slip through a merged-table assertion.- expect(ANIMATION_TRACK_IDS).toEqual([WALK_TRACK]);+ expect(Object.keys(ANIMATION_TRACKS)).toEqual([WALK_TRACK]);expect(ANIMATION_TRACKS[WALK_TRACK].builtin).toBe(true);for (const id of [SCANNER_TRACK, AMBIENT_TRACK]) {expect(ANIMATION_TRACKS[id], `${id} must be a stored row, not compiled in`).toBeUndefined();@@ -223,6 +223,14 @@ describe('the module-load row guard', () => {['a missing setKind', { setKind: undefined }, /needs a non-empty 'setKind'/],['a missing finalErrorCode', { finalErrorCode: '' }, /needs a non-empty 'finalErrorCode'/],['a non-boolean standaloneContract', { standaloneContract: 'yes' }, /boolean 'standaloneContract'/],+ ['a non-boolean builtin', { builtin: 'yes' }, /boolean 'builtin'/],+ // #3152 — exactly ONE prompt source per row, asserted in BOTH directions. The+ // second case is the one a provenance-shaped guard misses: a builtin row that+ // also carries a template has two definitions of its wording, and the stored one+ // silently wins over the text `prompts.test.js` pins.+ ['a stored row with no promptTemplate', { builtin: false }, /needs a non-empty 'promptTemplate'/],+ ['a stored row with a blank promptTemplate', { builtin: false, promptTemplate: ' ' }, /needs a non-empty 'promptTemplate'/],+ ['a builtin row carrying a promptTemplate', { promptTemplate: 'Animate it.' }, /must not carry a 'promptTemplate'/],])('rejects %s', (_label, overrides, message) => {expect(() => assertAnimationTrackRows(twoRows(overrides))).toThrow(message);});diff --git a/server/services/sprites/assetPrompt.js b/server/services/sprites/assetPrompt.jsindex 000346a7a8..8fa35fa83b 100644--- a/server/services/sprites/assetPrompt.js+++ b/server/services/sprites/assetPrompt.js@@ -35,7 +35,7 @@ import {buildMainReferencePrompt, buildAmbientReferencePrompt, buildAnchorPrompt,buildTurnaroundPrompt, TURNAROUND_ID,} from './prompts.js';-import { buildTrackVideoPrompt, hasTrackVideoPrompt } from './trackPrompts.js';+import { tryBuildTrackVideoPrompt } from './trackPrompts.js';import { WALK_TRACK } from './animationTracks.js';import { DEFAULT_CHROMA_KEY } from './chromaKey.js';@@ -178,7 +178,7 @@ export async function resolveSpriteAssetPrompt(recordId, relPath) {const runRecord = await readJSONFile(join(spriteDir(recordId), run[0], 'animation-run.json'), null);if (runRecord?.direction) {const { chromaKey, correctionPrompt, track } = runRecord;- // One dispatch through `buildTrackVideoPrompt` (#3136) rather than a+ // One dispatch through `tryBuildTrackVideoPrompt` (#3136) rather than a// per-track branch here — so a user-defined track's provenance rebuilds// with its own prompt instead of silently falling through to walk's.// An UNREGISTERED track (a run written by a newer peer, or one whose row@@ -186,13 +186,9 @@ export async function resolveSpriteAssetPrompt(recordId, relPath) {// the run itself stamped, and otherwise null, rather than mislabelling it// as a walk. `source` is the track id, which is what it always was for// the shipped rows.- const rebuild = () => (- hasTrackVideoPrompt(track ?? WALK_TRACK)- ? buildTrackVideoPrompt(track ?? WALK_TRACK, {- name, kind: record.kind, direction: runRecord.direction, chromaKey, correctionPrompt,- })- : null- );+ const rebuild = () => tryBuildTrackVideoPrompt(track ?? WALK_TRACK, {+ name, kind: record.kind, direction: runRecord.direction, chromaKey, correctionPrompt,+ });const stamped = typeof runRecord.prompt === 'string' && runRecord.prompt ? runRecord.prompt : null;const prompt = stamped ?? rebuild();if (!prompt) return null;diff --git a/server/services/sprites/atlas.js b/server/services/sprites/atlas.jsindex eb496df0b6..54182ba8da 100644--- a/server/services/sprites/atlas.js+++ b/server/services/sprites/atlas.js@@ -599,7 +599,6 @@ async function compileTrackRow(direction, validated, geometry) {runId: primary.run.runId,runManifestPath: primary.run.manifestPath,walkDirectionScale: trackScales[WALK_TRACK],- ambientScale: trackScales[AMBIENT_TRACK],trackScales,idleScale: pyRoundTo(idleScale, 8),idlePolicy: sourcePolicy,@@ -836,6 +835,14 @@ export async function compileAtlasInTail(recordId, {const manifest = {schemaVersion: 1,+ // The two named `kind`s are HISTORICAL spellings, kept so a recompile of a+ // record that was compiled before #3158 writes the same discriminator it always+ // did. They are matched on `primaryTrackId` rather than derived from it, which+ // means a user who deletes the seeded `ambient` row and authors their own+ // place-baseline track (#3152) gets the generic third spelling — correct for a+ // genuinely new track, and the same reason the two legacy names can't simply be+ // computed from the id: nothing else on disk records which name a record's+ // earlier atlases used.kind: validated.primaryTrackId === AMBIENT_TRACK? 'reviewed-ambient-set-runtime-atlas': validated.primaryTrackId === WALK_TRACKdiff --git a/server/services/sprites/atlas.test.js b/server/services/sprites/atlas.test.jsindex baa138961b..d9d272e23b 100644--- a/server/services/sprites/atlas.test.js+++ b/server/services/sprites/atlas.test.js@@ -10,15 +10,13 @@import { describe, it, expect, beforeEach, afterEach, afterAll, vi } from 'vitest';import { mkdtempSync, rmSync } from 'fs';import { tmpdir } from 'os';-import { dirname, join } from 'path';-import { fileURLToPath } from 'url';+import { join } from 'path';import sharp from 'sharp';import { mkdir, writeFile, readFile, rm } from 'fs/promises';import { createHash } from 'crypto';import { lockAllAnchors as lockAllAnchorsFixture, placeCandidate, trackSpan as fullSpan } from './spriteTestFixtures.js';const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-atlas-test-'));-const SPRITES_DIR = dirname(fileURLToPath(import.meta.url));vi.mock('../../lib/fileUtils.js', async (importOriginal) => {const actual = await importOriginal();@@ -52,6 +50,7 @@ const { getAnimationTrack, SCANNER_TRACK, AMBIENT_TRACK } = await import('./anim// is the merge. Resolved once; the store caches its read.const {getEffectiveAnimationTracks, __resetAnimationTrackStore,+ animationTrackStorePath, animationTrackSeedPath,} = await import('./animationTrackStore.js');const EFFECTIVE_TRACKS = getEffectiveAnimationTracks();@@ -350,16 +349,19 @@ describe('compileAtlas', () => {// A byte copy of the shipped seed, exactly as the migration writes it — so this// asserts the migration's OUTPUT is sufficient, not merely that some// hand-written store works.+ // Paths come from the store's own exports rather than a hand-walked `../../..`:+ // the PATHS mock above leaves `PATHS.root` real, so `animationTrackSeedPath()`+ // and `animationTrackStorePath()` resolve exactly where the migration reads and+ // writes — and a future relocation of either file moves both at once.const installUserStore = async () => {- const seed = await readFile(join(SPRITES_DIR, '..', '..', '..', 'data.reference', 'sprites', 'animation-tracks.json'), 'utf-8');await mkdir(join(TEST_ROOT, 'sprites'), { recursive: true });- await writeFile(join(TEST_ROOT, 'sprites', 'animation-tracks.json'), seed);+ await writeFile(animationTrackStorePath(), await readFile(animationTrackSeedPath(), 'utf-8'));__resetAnimationTrackStore();};// Restore the seed-fallback state the rest of this file compiles under, so// ordering between suites can't matter.afterEach(async () => {- await rm(join(TEST_ROOT, 'sprites', 'animation-tracks.json'), { force: true });+ await rm(animationTrackStorePath(), { force: true });__resetAnimationTrackStore();});diff --git a/server/services/sprites/atlasGrid.js b/server/services/sprites/atlasGrid.jsindex 500b59a7cd..9e519083d6 100644--- a/server/services/sprites/atlasGrid.js+++ b/server/services/sprites/atlasGrid.js@@ -64,12 +64,9 @@*/import { WALK_TRACK, getAnimationTrack, trackRowCount } from './animationTracks.js';-// #3152 — the DEFAULT table is now the effective one (compiled `walk` + the-// user-defined store) rather than the compiled constant, so a user's track gets a-// span and a row count here without every caller learning to pass one. Each+// Supplies the default `tracks` table below — see the header's #3152 note. Each// default is evaluated per CALL (default params are lazy), so the store's cached-// read happens on first use rather than at this module's load. `tracks` stays an-// explicit parameter — it is still the injection seam the multi-track tests use.+// read happens on first use rather than at this module's load.import { getEffectiveAnimationTracks } from './animationTrackStore.js';// These two names describe columns found in imported/legacy compiled grids;// neither declares an animation track in the registry.diff --git a/server/services/sprites/spriteTestFixtures.js b/server/services/sprites/spriteTestFixtures.jsindex b8e5e1fd23..7f0222739a 100644--- a/server/services/sprites/spriteTestFixtures.js+++ b/server/services/sprites/spriteTestFixtures.js@@ -122,3 +122,56 @@ export const AMBIENT_TRACK_ROW = Object.freeze({// user-defined-row shape is exercised in `animationTrackStore.test.js`.builtin: true,});++/**+ * A well-formed USER-DEFINED track row for the store (#3152) — every field+ * `assertAnimationTrackRows` requires of a stored row and nothing more, including+ * the `promptTemplate` a stored row must carry (a compiled row must not).+ *+ * Distinct from `AMBIENT_TRACK_ROW` above, which stands in for a COMPILED row in+ * the injected-table tests. This one is what a user actually authors, and it is+ * shared because #3152 alone added two required row fields — a per-suite literal+ * means the next such change updates one copy and leaves the other suite green on+ * a stale shape.+ *+ * `overrides` is shallow-merged, so a second row in one table renames the fields+ * that must be unique (`id`, `contractFrameCountField`, `selectionKind`, `setKind`,+ * `finalErrorCode`) without restating the rest.+ */+export const storedTrackRow = (overrides = {}) => ({+ id: 'chest-opening',+ label: 'Chest opening',+ directional: false,+ kinds: ['object'],+ minFrameCount: 2,+ maxFrameCount: 8,+ defaultFrameCount: 4,+ minFps: 2,+ maxFps: 12,+ defaultFps: 6,+ contractFrameCountField: 'chestOpeningFrameCount',+ contractFpsField: null,+ selectionKind: 'reviewed-chest-opening-selection',+ setKind: 'finalized-chest-opening-set',+ finalErrorCode: 'CHEST_OPENING_SET_FINAL',+ standaloneContract: true,+ promptTemplate: 'Animate the {{kind}} {{name}} opening once, then hold. Matte on {{chromaKeyPhrase}}.',+ ...overrides,+});++/**+ * Write a track store under a suite's TEST_ROOT, in the on-disk shape+ * `animationTrackStore.js` reads.+ *+ * Accepts either an array of rows or a raw string (for the malformed-JSON cases),+ * so the sentinel tests and the happy path share one writer. Callers must still+ * call `__resetAnimationTrackStore()` — the store caches per process, and making+ * this helper do it would hide the restart boundary the tests exist to assert.+ */+export async function writeAnimationTrackStore(testRoot, tracks) {+ await mkdir(join(testRoot, 'sprites'), { recursive: true });+ await writeFile(+ join(testRoot, 'sprites', 'animation-tracks.json'),+ typeof tracks === 'string' ? tracks : `${JSON.stringify({ schemaVersion: 1, tracks }, null, 2)}\n`,+ );+}diff --git a/server/services/sprites/trackPrompts.js b/server/services/sprites/trackPrompts.jsindex a65e0c979f..a27bf0d073 100644--- a/server/services/sprites/trackPrompts.js+++ b/server/services/sprites/trackPrompts.js@@ -115,11 +115,19 @@ export function buildTrackVideoPrompt(trackId, args) {return build(args);}-/** True when `trackId` resolves to an i2v prompt — compiled or stored. */-export const hasTrackVideoPrompt = (trackId) => {- const row = getEffectiveAnimationTracks()[trackId];- if (!row) return false;- return row.builtin- ? Object.prototype.hasOwnProperty.call(TRACK_VIDEO_PROMPTS, trackId)- : true;-};+/**+ * The i2v prompt for `trackId`, or `null` when this build cannot produce one.+ *+ * For the provenance rebuild in `assetPrompt.js`, whose question is "rebuild this+ * run's prompt if you still can" — a run may name a track a newer peer wrote, or+ * one whose row the user has since deleted. A separate `hasTrackVideoPrompt`+ * predicate used to answer the first half, which meant duplicating+ * `buildTrackVideoPrompt`'s own resolution branch and keeping the two in step; this+ * asks the one resolver and turns its unknown-track throw into the `null` the+ * caller wanted. It does NOT swallow anything else — a malformed template or a+ * builtin/builder mismatch still throws.+ */+export function tryBuildTrackVideoPrompt(trackId, args) {+ if (!getEffectiveAnimationTracks()[trackId]) return null;+ return buildTrackVideoPrompt(trackId, args);+}diff --git a/server/services/sprites/trackPrompts.test.js b/server/services/sprites/trackPrompts.test.jsindex 9c667eaf59..01b5e799a8 100644--- a/server/services/sprites/trackPrompts.test.js+++ b/server/services/sprites/trackPrompts.test.js@@ -25,6 +25,7 @@ import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';import { mkdtempSync, rmSync, mkdirSync, writeFileSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';+import { storedTrackRow } from './spriteTestFixtures.js';const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-track-prompts-test-'));@@ -35,7 +36,7 @@ vi.mock('../../lib/fileUtils.js', async (importOriginal) => {});const {- buildTrackVideoPrompt, hasTrackVideoPrompt, renderPromptTemplate,+ buildTrackVideoPrompt, tryBuildTrackVideoPrompt, renderPromptTemplate,} = await import('./trackPrompts.js');const {buildWalkVideoPrompt, buildScannerPrompt, buildAmbientVideoPrompt,@@ -120,25 +121,22 @@ describe('the seeded templates reproduce the compiled builders exactly (#3152)',});describe('a user-defined row resolves through its own template', () => {- const CUSTOM = {+ // The shared stored-row shape (spriteTestFixtures.js) with only the fields this+ // suite cares about overridden — the template (every placeholder, both chroma+ // forms) and `kinds: ['character']`, so walk stays `character`'s baseline and the+ // merged table still validates.+ const CUSTOM = storedTrackRow({id: 'jetpack-burst',label: 'Jetpack burst',directional: true,kinds: ['character'],- minFrameCount: 2,- maxFrameCount: 8,- defaultFrameCount: 4,- minFps: 2,- maxFps: 12,- defaultFps: 6,contractFrameCountField: 'jetpackBurstFrameCount',- contractFpsField: null,selectionKind: 'reviewed-jetpack-burst-selection',setKind: 'finalized-jetpack-burst-set',finalErrorCode: 'JETPACK_BURST_SET_FINAL',standaloneContract: false,promptTemplate: 'Animate {{name}} ({{kind}}) firing a jetpack burst while facing {{direction}}. Matte: {{chromaKeyPhrase}} / raw {{chromaKey}}.',- };+ });it('interpolates every supported placeholder', () => {writeTracks([CUSTOM]);@@ -163,11 +161,15 @@ describe('a user-defined row resolves through its own template', () => {)).toBe(true);});- it('reports a stored row as having a prompt, and an unknown id as not', () => {+ it('rebuilds a known track and answers null for an unknown one (tryBuild…)', () => {+ // The provenance-rebuild path in `assetPrompt.js`: a run may name a track a+ // newer peer wrote, or one whose row the user has since deleted. Only that case+ // becomes `null`; a known track still returns its real prompt.writeTracks([CUSTOM]);- expect(hasTrackVideoPrompt('jetpack-burst')).toBe(true);- expect(hasTrackVideoPrompt(WALK_TRACK)).toBe(true);- expect(hasTrackVideoPrompt('never-registered')).toBe(false);+ const args = { name: 'Placeholder Hero', kind: 'character', direction: 'east', chromaKey: '#FF00FF' };+ expect(tryBuildTrackVideoPrompt('jetpack-burst', args)).toContain('jetpack burst');+ expect(tryBuildTrackVideoPrompt(WALK_TRACK, args)).toBe(buildWalkVideoPrompt(args));+ expect(tryBuildTrackVideoPrompt('never-registered', args)).toBeNull();});it('throws for a track neither compiled nor stored, naming what IS known', () => {