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

feat([issue-3152]): load sprite animation tracks from a user-defined store, leaving walk the only compiled row

[._.]/ Adam Eivy89be17260cc7
diff --git a/data.reference/sprites/animation-tracks.json b/data.reference/sprites/animation-tracks.json
new file mode 100644
index 0000000000..a49c71f8e0
--- /dev/null
+++ b/data.reference/sprites/animation-tracks.json
@@ -0,0 +1,44 @@
+{
+ "schemaVersion": 1,
+ "_comment": "User-defined sprite animation tracks (issue #3152). `walk` is the one mandatory built-in and is NOT listed here — it is compiled into server/services/sprites/animationTracks.js. Every row below is ordinary seed data you may retune, add to, or delete. `scanner` and `ambient` shipped as compiled rows through #3018/#3045 and are seeded here verbatim so an install holding an approved scanner set or ambient loop keeps compiling after the upgrade: their `selectionKind`/`setKind` strings are what the atlas compiler re-verifies on disk, so do not rename those on a record you have already authored.",
+ "tracks": [
+ {
+ "id": "scanner",
+ "label": "Scanner action",
+ "directional": true,
+ "kinds": ["character"],
+ "minFrameCount": 2,
+ "maxFrameCount": 8,
+ "defaultFrameCount": 4,
+ "minFps": 2,
+ "maxFps": 12,
+ "defaultFps": 6,
+ "contractFrameCountField": "scannerFrameCount",
+ "contractFpsField": null,
+ "selectionKind": "reviewed-directional-scanner-selection",
+ "setKind": "finalized-eight-direction-scanner-set",
+ "finalErrorCode": "SCANNER_SET_FINAL",
+ "standaloneContract": false,
+ "promptTemplate": "Create a short, seamless scanner action for {{name}}, facing {{direction}}. The character raises a handheld scanner, makes one deliberate sweep, then returns to the exact starting pose. Keep the character centered, full body visible, and animate only over a solid {{chromaKey}} background. No text, UI, scenery, camera movement, cuts, or additional characters."
+ },
+ {
+ "id": "ambient",
+ "label": "Ambient loop",
+ "directional": false,
+ "kinds": ["place", "object", "props"],
+ "minFrameCount": 2,
+ "maxFrameCount": 6,
+ "defaultFrameCount": 3,
+ "minFps": 2,
+ "maxFps": 12,
+ "defaultFps": 4,
+ "contractFrameCountField": "ambientFrameCount",
+ "contractFpsField": null,
+ "selectionKind": "reviewed-single-row-ambient-selection",
+ "setKind": "finalized-single-row-ambient-set",
+ "finalErrorCode": "AMBIENT_SET_FINAL",
+ "standaloneContract": true,
+ "promptTemplate": "The source image is the locked at-rest {{kind}} sprite {{name}}. Animate one subtle seamless ambient loop (for example wind, water, flame, or a gentle flicker appropriate to the source), then return to the exact starting pose. Preserve its identity, silhouette, palette, scale, and centered ground position. Use a locked camera and an exactly uniform non-emissive {{chromaKeyPhrase}} background only as a compositing matte: no scenery, text, labels, camera movement, cuts, added objects, or people."
+ }
+ ]
+}
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 5d9ba21fbb..8ce8da0ca7 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -54,6 +54,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
- Writers Room draft bodies — `data/writers-room/works/{workId}/drafts/{draftId}.md`. Keep `.md` file-backed; store metadata/index rows in DB.
- MortalLoom / Health / Meatspace health data — `data/health`, `data/meatspace`, MortalLoom iCloud store. Kept file-backed to preserve iCloud/file sync and avoid routing sensitive health records through the app DB before that boundary is designed.
- App scaffolds / cloned repos / browser profiles — `data/repos`, `data/browser-profile` — inherently filesystem-oriented.
+- Sprite animation-track definitions — `data/sprites/animation-tracks.json` (#3152). A small hand-editable authoring config: which animation types exist beyond the compiled-in `walk` (label, directionality, frame/fps bounds, prompt template, and the on-disk `setKind` strings). `file-primary` rather than `db-primary` because it is **machine-local and inseparable from the on-disk sprite tree it describes** — a row names the `setKind` an approved set under `data/sprites/{id}/` already carries, so the two travel together or neither means anything — and because it has no cross-record queries, no relationships beyond `kinds` strings, and no sync cursor. Read synchronously and cached per process (`server/services/sprites/animationTrackStore.js`): `server/lib/validation.js` builds sprite Zod ranges from it at module load, so it must resolve without `await`. Seeded from `data.reference/sprites/animation-tracks.json` (migration 211), which is also the fallback read when no user copy exists yet. Backed up in full by the rsync snapshot.
- LoRA training datasets — `data/lora-datasets/{id}/index.json` + `images/*.png` (collectionStore). The record is inseparable from the image bytes it organizes, has no cross-record queries beyond a small characterId scan, and is **machine-local** like `data/loras/` itself (training artifacts tied to this machine's GPU output — never federates, no sync cursor/tombstone). Backed up in full: uploads and hand-edited captions are not re-creatable. Training RUN records are `db-primary` (`lora_training_runs`); run artifacts (checkpoints/samples) live under `data/training-runs/{runId}/` with checkpoints/cache excluded from backup.
---
diff --git a/docs/features/sprite-export-contract.md b/docs/features/sprite-export-contract.md
index 5f9539aace..5e77afd90e 100644
--- a/docs/features/sprite-export-contract.md
+++ b/docs/features/sprite-export-contract.md
@@ -22,7 +22,12 @@ Frame-count and fps uniformity is a **within-track** rule, never a between-track
### Animation tracks are data, with `walk` the one built-in
-**Which tracks exist is not a fixed list.** `walk` is the mandatory baseline for a character — the one animation every character has, and the only one this document can promise a reader will be there. Everything else, including the shipped `scanner` action and `ambient` loop, is an ordinary **row** in the track registry describing its own label, facing count, frame/fps range, the locked reference its render is seeded from, and the `runtimeContract` field it occupies. A consuming app must therefore treat the track set as **discovered from `geometry.tracks`, never enumerated in code** (see "Resolve columns by name, not by constant" below) — the atlas it reads next year may carry a track nobody had named when it was written.
+**Which tracks exist is not a fixed list, and it is not fixed by PortOS either.** `walk` is the mandatory baseline for a character — the one animation every character has, the only one compiled into PortOS, and the only one this document can promise a reader will be there. Everything else, including the shipped `scanner` action and `ambient` loop, is an ordinary **row** describing its own label, facing count, frame/fps range, the locked reference its render is seeded from, the `runtimeContract` field it occupies, and its image-to-video prompt. A consuming app must therefore treat the track set as **discovered from `geometry.tracks`, never enumerated in code** (see "Resolve columns by name, not by constant" below) — the atlas it reads next year may carry a track nobody had named when it was written.
+
+**Non-walk rows are user data, stored per install.** They live in `data/sprites/animation-tracks.json` (`server/services/sprites/animationTrackStore.js` merges them with `walk` into the effective registry). `scanner` and `ambient` ship as **seed rows** in `data.reference/sprites/animation-tracks.json` — a user may retune their bounds, reword their prompts, or delete them outright, and may add their own ("a chest opening", "a flower blossoming", "a jetpack burst") without a PortOS code change. Two consequences worth stating plainly:
+
+- **Two installs can legitimately disagree about which tracks exist.** An atlas is self-describing (`geometry.tracks` + `columns`) precisely so a consumer never needs the producing install's registry.
+- **A row's `selectionKind` / `setKind` are on-disk contracts, not labels.** The compiler re-verifies an approved set by those exact strings, so renaming them on a track you have already authored orphans that set. Adding, deleting, or retuning a row takes effect on the next server start.
The consequence for the app side is small but load-bearing: a track's *presence* is optional and its *name* is user-chosen, so an app keys off the track ids it actually needs and ignores the rest. Nothing about the grid, cell metrics, pivot, or row semantics changes when a track is added.
@@ -125,9 +130,10 @@ Two mechanisms guard that:
|---|---|
| `server/services/sprites/atlas.js` | Compiles the atlas; owns the geometry block and the pre-pixel up-to-date check |
| `server/services/sprites/atlasGrid.js` | The grid itself: column spans and row spans per track, within-track uniformity, reading a persisted (or legacy) grid back |
-| `server/services/sprites/animationTracks.js` | One row per animation track — its bounds, defaults, directionality, which record kinds may carry it, its on-disk set/selection kinds, and whether it is the kind's publishable baseline (`standaloneContract`) |
+| `server/services/sprites/animationTracks.js` | The one COMPILED row (`walk`) and the row contract itself — bounds, defaults, directionality, which record kinds may carry a track, its on-disk set/selection kinds, and whether it is the kind's publishable baseline (`standaloneContract`). Imports nothing: `server/lib/validation.js` builds its sprite Zod ranges from here, so the native image graph must stay out |
+| `server/services/sprites/animationTrackStore.js` | Loads the user-defined rows from `data/sprites/animation-tracks.json` (falling back to the `data.reference/` seed) and merges them with `walk` into the effective registry every reader resolves against |
| `server/services/sprites/animationTrackWorkflow.js` | The ONE generate/package/review/approve implementation every non-walk track runs, parameterized by its registry row |
-| `server/services/sprites/trackPrompts.js` | Resolves a track id to its image-to-video prompt builder |
+| `server/services/sprites/trackPrompts.js` | Resolves a track id to its image-to-video prompt — the compiled builder for `walk`, the row's own `promptTemplate` for a stored track |
| `server/services/sprites/reference.js` | The two animation gates: `requireCharacter` (walk workflow) and `requireAnimatable` (compile/publish) |
| `server/services/sprites/atlasLayout.js` | Builds the sidecar payload; compares geometry against a runtime contract |
| `server/services/sprites/publish.js` | Binding validation, the publish-time guard, the atomic PNG + sidecar write |
diff --git a/scripts/migrations/211-seed-user-defined-animation-tracks.js b/scripts/migrations/211-seed-user-defined-animation-tracks.js
new file mode 100644
index 0000000000..1072a785d3
--- /dev/null
+++ b/scripts/migrations/211-seed-user-defined-animation-tracks.js
@@ -0,0 +1,83 @@
+/**
+ * Migration 211 — give existing installs an editable animation-track store.
+ *
+ * Until #3152, `scanner` and `ambient` were COMPILED rows in
+ * `server/services/sprites/animationTracks.js`. They are now ordinary user-defined
+ * rows in `data/sprites/animation-tracks.json`, seeded verbatim from
+ * `data.reference/sprites/animation-tracks.json` — so a user can retune their
+ * bounds, reword their prompts, or delete them outright without a PortOS release.
+ * `walk` stays the one mandatory built-in and is deliberately NOT in the store.
+ *
+ * **The regression this exists to prevent is a silent one.** An install holding an
+ * approved scanner set or ambient loop validates that set by its exact `setKind`
+ * string (`finalized-eight-direction-scanner-set`), and the runtime-contract Zod
+ * schema builds its `scannerFrameCount` / `ambientFrameCount` fields from the
+ * effective registry. Without the rows, the compiler would report "unknown
+ * animation track 'scanner'" on a record that compiled fine yesterday, and a
+ * publish binding pinning `scannerFrameCount` would have that field silently
+ * stripped by Zod. So the rows must be present on every upgraded install.
+ *
+ * **Why this migration is a convenience, not a correctness dependency.** The store
+ * falls back to reading `data.reference/sprites/animation-tracks.json` whenever
+ * the user copy is absent (see `animationTrackStore.js`) — which is what makes the
+ * upgrade safe even on the very first boot, where module load happens before
+ * migrations run. This migration's actual job is to materialize an EDITABLE copy
+ * under `data/`, so the "Manage animation types" UI (#3153) and a hand-editing
+ * user have a file to change. That split is deliberate: correctness never depends
+ * on migration ordering, and the user still gets a real file.
+ *
+ * Idempotent and non-destructive. A store file that already exists is NEVER
+ * touched — not merged, not topped up — because a user who deleted `scanner` must
+ * have it stay deleted, and a merge would resurrect it on every upgrade. An
+ * unreadable existing store is likewise left alone: possibly-recoverable user data
+ * beats a clean reseed.
+ */
+
+import { readFile, writeFile, mkdir, access } from 'fs/promises';
+import { join, dirname } from 'path';
+
+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);
+
+ // 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)) {
+ console.log('🎬 animation-tracks: store already present — no-op.');
+ return { ok: true, reason: 'already-present' };
+ }
+
+ let seed;
+ try {
+ seed = await readFile(seedPath, 'utf-8');
+ } catch (err) {
+ // A checkout missing the seed file is a packaging problem, not a data
+ // problem: the store's data.reference fallback already covers the runtime, so
+ // report and continue rather than failing the whole migration run.
+ console.error(`❌ animation-tracks: no seed at data.reference/${STORE_REL} (${err.message}) — skipping.`);
+ return { ok: true, reason: 'no-seed' };
+ }
+ // Parse before writing: shipping a corrupt seed into `data/` would turn the
+ // store's "exists but unreadable" throw into a boot failure the user can only
+ // fix by deleting a file they never created.
+ let parsed;
+ try {
+ parsed = JSON.parse(seed);
+ } catch (err) {
+ console.error(`❌ animation-tracks: data.reference/${STORE_REL} is not valid JSON (${err.message}) — skipping.`);
+ return { ok: true, reason: 'invalid-seed' };
+ }
+
+ await mkdir(dirname(storePath), { recursive: true });
+ await writeFile(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 };
+}
+
+export default { up };
diff --git a/scripts/migrations/211-seed-user-defined-animation-tracks.test.js b/scripts/migrations/211-seed-user-defined-animation-tracks.test.js
new file mode 100644
index 0000000000..e99e70fa61
--- /dev/null
+++ b/scripts/migrations/211-seed-user-defined-animation-tracks.test.js
@@ -0,0 +1,113 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+import migration from './211-seed-user-defined-animation-tracks.js';
+
+/**
+ * Migration 211 — materialize an editable animation-track store (#3152).
+ *
+ * The behavior that matters is the NON-destructive half: an install where the user
+ * has already deleted `scanner`, retuned `ambient`, or broken their JSON must come
+ * out the other side untouched. A merge-on-upgrade would resurrect a deleted track
+ * every release, which is exactly the "starter entry comes back" trade-off
+ * `setup-data.js` documents and which is wrong here — a track's `setKind` gates
+ * whether a record compiles, so re-adding one is not cosmetic.
+ */
+
+let rootDir;
+let seedPath;
+let storePath;
+
+// An invented seed (privacy convention) shaped like the shipped one.
+const SEED = {
+ schemaVersion: 1,
+ tracks: [
+ { id: 'scanner', label: 'Scanner action', promptTemplate: 'Sweep once.' },
+ { id: 'ambient', label: 'Ambient loop', promptTemplate: 'Sway gently.' },
+ ],
+};
+
+const writeSeed = (obj = SEED) => writeFileSync(
+ seedPath, typeof obj === 'string' ? obj : `${JSON.stringify(obj, null, 2)}\n`,
+);
+const writeStore = (obj) => {
+ mkdirSync(join(rootDir, 'data', 'sprites'), { recursive: true });
+ writeFileSync(storePath, typeof obj === 'string' ? obj : `${JSON.stringify(obj, null, 2)}\n`);
+};
+const readStore = () => JSON.parse(readFileSync(storePath, 'utf-8'));
+
+beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-211-'));
+ seedPath = join(rootDir, 'data.reference', 'sprites', 'animation-tracks.json');
+ storePath = join(rootDir, 'data', 'sprites', 'animation-tracks.json');
+ mkdirSync(join(rootDir, 'data.reference', 'sprites'), { recursive: true });
+});
+
+afterEach(() => rmSync(rootDir, { recursive: true, force: true }));
+
+describe('migration 211 — seed the user-defined animation-track store', () => {
+ it('creates the store (with parent dirs) from the shipped seed', async () => {
+ writeSeed();
+ const result = await migration.up({ rootDir });
+ expect(result).toMatchObject({ ok: true, reason: 'seeded', count: 2 });
+ expect(readStore().tracks.map((t) => t.id)).toEqual(['scanner', 'ambient']);
+ });
+
+ it('copies the seed byte-for-byte, so the shipped prompts arrive intact', async () => {
+ // Not re-serialized: a round-trip through JSON.parse/stringify would silently
+ // drop the seed's explanatory `_comment` and reformat the prompt strings a
+ // user is about to edit.
+ writeSeed();
+ await migration.up({ rootDir });
+ expect(readFileSync(storePath, 'utf-8')).toBe(readFileSync(seedPath, 'utf-8'));
+ });
+
+ it('leaves an existing store completely alone (a deleted track STAYS deleted)', async () => {
+ // The regression a merge would cause: `scanner` comes back every upgrade.
+ const userStore = { schemaVersion: 1, tracks: [{ id: 'ambient', label: 'My ambient' }] };
+ writeStore(userStore);
+ writeSeed();
+ const result = await migration.up({ rootDir });
+ expect(result).toMatchObject({ ok: true, reason: 'already-present' });
+ expect(readStore()).toEqual(userStore);
+ });
+
+ it('leaves an UNREADABLE existing store alone rather than reseeding over it', async () => {
+ // Possibly-recoverable user edits beat a clean reseed.
+ const broken = '{ "tracks": [ oops ';
+ writeStore(broken);
+ writeSeed();
+ const result = await migration.up({ rootDir });
+ expect(result).toMatchObject({ ok: true, reason: 'already-present' });
+ expect(readFileSync(storePath, 'utf-8')).toBe(broken);
+ });
+
+ it('is idempotent — a second run is a no-op', async () => {
+ writeSeed();
+ await migration.up({ rootDir });
+ const after = readFileSync(storePath, 'utf-8');
+ const second = await migration.up({ rootDir });
+ expect(second).toMatchObject({ reason: 'already-present' });
+ expect(readFileSync(storePath, 'utf-8')).toBe(after);
+ });
+
+ it('no-ops (without throwing) when the seed file is missing', async () => {
+ // A packaging gap, not a data problem — the store's own data.reference
+ // fallback already covers the runtime, so this must not fail the whole
+ // migration run and block every later migration.
+ const result = await migration.up({ rootDir });
+ expect(result).toMatchObject({ ok: true, reason: 'no-seed' });
+ expect(existsSync(storePath)).toBe(false);
+ });
+
+ it('refuses to write a corrupt seed into data/', async () => {
+ // Shipping invalid JSON into `data/` would turn the store's "exists but
+ // unreadable" throw into a boot failure over a file the user never created.
+ writeSeed('{ nope ');
+ const result = await migration.up({ rootDir });
+ expect(result).toMatchObject({ ok: true, reason: 'invalid-seed' });
+ expect(existsSync(storePath)).toBe(false);
+ });
+});
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 814e7dde8e..881107af96 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -5,9 +5,15 @@ 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';
+// #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 {
- WALK_TRACK, ANIMATION_TRACK_IDS, getAnimationTrack,
-} from '../services/sprites/animationTracks.js';
+ getEffectiveAnimationTracks, getEffectiveAnimationTrackIds,
+} from '../services/sprites/animationTrackStore.js';
import { QUEUEABLE_IMAGE_MODES } from '../services/imageGen/modes.js';
import { GROK_VIDEO_DURATIONS } from './grokVideoClip.js';
import { PR_COMPLETION_VALUES } from './prDisposition.js';
@@ -990,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);
+ const row = getAnimationTrack(track, getEffectiveAnimationTracks());
return z.number().int().min(row.minFrameCount).max(row.maxFrameCount);
}
export function spriteTrackFpsSchema(track) {
- const row = getAnimationTrack(track);
+ const row = getAnimationTrack(track, getEffectiveAnimationTracks());
return z.number().int().min(row.minFps).max(row.maxFps);
}
@@ -1054,10 +1060,8 @@ const spriteRepoRelativePath = z.string().min(1).max(1024)
// here — and forgetting meant the field was silently stripped by Zod and the
// app rung of the target-precedence chain went dead for that track.
const spriteTrackContractFields = Object.fromEntries(
- ANIMATION_TRACK_IDS.map((id) => {
- const row = getAnimationTrack(id);
- return [row.contractFrameCountField, spriteTrackFrameCountSchema(id).optional()];
- }),
+ Object.values(getEffectiveAnimationTracks())
+ .map((row) => [row.contractFrameCountField, spriteTrackFrameCountSchema(row.id).optional()]),
);
// The tracks whose frame count is enough ON ITS OWN to make a contract
@@ -1067,9 +1071,9 @@ const spriteTrackContractFields = Object.fromEntries(
// historical "walkFrameCount or ambientFrameCount" rule and stays correct for a
// user-defined track. It is the same field `atlas.js` dispatches its compile
// evidence chain on, so publish validation and compile can't disagree.
-const SPRITE_STANDALONE_CONTRACT_FIELDS = ANIMATION_TRACK_IDS
- .filter((id) => getAnimationTrack(id).standaloneContract)
- .map((id) => getAnimationTrack(id).contractFrameCountField);
+const SPRITE_STANDALONE_CONTRACT_FIELDS = Object.values(getEffectiveAnimationTracks())
+ .filter((row) => row.standaloneContract)
+ .map((row) => row.contractFrameCountField);
export const spriteRuntimeContractSchema = z.object({
// Ranges come from each track's registry row (#3015/#3136). `walkFrameCount`
@@ -1276,7 +1280,7 @@ const buildSpriteTrackGenerateSchema = (track) => z.object({
// derive-from-the-registry idiom `spriteTrackContractFields` uses, rather than
// re-allocating six Zod objects on every generate request.
const SPRITE_TRACK_GENERATE_SCHEMAS = Object.fromEntries(
- ANIMATION_TRACK_IDS.map((id) => [id, buildSpriteTrackGenerateSchema(id)]),
+ getEffectiveAnimationTrackIds().map((id) => [id, buildSpriteTrackGenerateSchema(id)]),
);
/**
diff --git a/server/lib/validation.test.js b/server/lib/validation.test.js
index ec13cd01e5..ee3a05a353 100644
--- a/server/lib/validation.test.js
+++ b/server/lib/validation.test.js
@@ -52,8 +52,15 @@ import {
spriteTrackGenerateSchema,
} from './validation.js';
import {
- WALK_TRACK, ANIMATION_TRACK_IDS, getAnimationTrack, tracksForKind,
+ WALK_TRACK, getAnimationTrack, tracksForKind,
} from '../services/sprites/animationTracks.js';
+// #3152 — the contract schema is built from the EFFECTIVE table (compiled `walk` +
+// the user-defined store), so these assertions must enumerate the same set the
+// schema did; walking the compiled ids would narrow them to `walk` alone and stop
+// covering the seeded `scanner`/`ambient` fields entirely.
+import {
+ getEffectiveAnimationTracks, getEffectiveAnimationTrackIds,
+} from '../services/sprites/animationTrackStore.js';
import {
telegramForwardTypesSchema,
} from './telegramValidation.js';
@@ -1920,8 +1927,8 @@ describe('ad-hoc route schemas (#2521)', () => {
// STRIPPED by Zod and the app rung of the target-precedence chain went
// dead for it with no error anywhere. Derived from the registry, every
// registered row's field is accepted at its own bounds by construction.
- for (const id of ANIMATION_TRACK_IDS) {
- const row = getAnimationTrack(id);
+ for (const id of getEffectiveAnimationTrackIds()) {
+ const row = getAnimationTrack(id, getEffectiveAnimationTracks());
// Pair a non-primary track's field with walk's so the contract is
// publishable — this asserts the FIELD is known, not the primacy rule
// (covered below).
@@ -1941,13 +1948,14 @@ describe('ad-hoc route schemas (#2521)', () => {
// track on an existing kind (scanner) describes no publishable atlas,
// because the compiler requires the primary's finalized set before it
// emits anything at all.
- const primaries = ANIMATION_TRACK_IDS.filter(
- (id) => getAnimationTrack(id).kinds.some((kind) => tracksForKind(kind)[0]?.id === id),
+ const effective = getEffectiveAnimationTracks();
+ const primaries = getEffectiveAnimationTrackIds().filter(
+ (id) => effective[id].kinds.some((kind) => tracksForKind(kind, effective)[0]?.id === id),
);
expect(primaries).toEqual([WALK_TRACK, 'ambient']);
for (const id of primaries) {
expect(spriteRuntimeContractSchema.safeParse({
- [getAnimationTrack(id).contractFrameCountField]: getAnimationTrack(id).defaultFrameCount,
+ [effective[id].contractFrameCountField]: effective[id].defaultFrameCount,
}).success, `${id} alone is a publishable contract`).toBe(true);
}
expect(spriteRuntimeContractSchema.safeParse({ scannerFrameCount: 4 }).success).toBe(false);
diff --git a/server/routes/sprites.js b/server/routes/sprites.js
index f00552f003..d4f182ad63 100644
--- a/server/routes/sprites.js
+++ b/server/routes/sprites.js
@@ -50,10 +50,16 @@ import {
} from '../services/sprites/reference.js';
import { resolveSpriteAssetPrompt } from '../services/sprites/assetPrompt.js';
import {
- WALK_TRACK, ANIMATION_TRACK_IDS,
+ WALK_TRACK,
isAnimationTrack, kindSupportsTrack, tracksForKind,
getAnimationTrack as getAnimationTrackRow,
} from '../services/sprites/animationTracks.js';
+// #3152 — every registry question a request asks is answered against the
+// EFFECTIVE table (compiled `walk` + the user-defined store), so a user's own
+// track is routable, gated, and listed with no route edit.
+import {
+ getEffectiveAnimationTracks, getEffectiveAnimationTrackIds,
+} from '../services/sprites/animationTrackStore.js';
import {
getWalkState, startWalkGeneration, approveWalkDirection, rerunWalkPostprocess, unlockWalkSet,
reopenWalkDirection, setWalkTarget, getWalkSourceFrames,
@@ -93,9 +99,9 @@ function resolveTrackParam(params) {
{ status: 400, code: 'WALK_NOT_GENERIC' },
);
}
- if (!isAnimationTrack(trackId)) {
+ if (!isAnimationTrack(trackId, getEffectiveAnimationTracks())) {
throw new ServerError(
- `Unknown animation track '${trackId}' — the registered tracks are: ${ANIMATION_TRACK_IDS.join(', ')}`,
+ `Unknown animation track '${trackId}' — the registered tracks are: ${getEffectiveAnimationTrackIds().join(', ')}`,
{ status: 404, code: 'UNKNOWN_ANIMATION_TRACK' },
);
}
@@ -112,7 +118,7 @@ function resolveTrackParam(params) {
* anchor", blaming the reference set for a missing request field.
*/
function requireDirectionForTrack(trackId, body) {
- if (!getAnimationTrackRow(trackId).directional || body.direction) return;
+ if (!getAnimationTrackRow(trackId, getEffectiveAnimationTracks()).directional || body.direction) return;
throw new ServerError(
`The ${trackId} track is directional — name the facing to animate`,
{ status: 400, code: 'DIRECTION_REQUIRED' },
@@ -169,8 +175,9 @@ router.get('/:id', asyncHandler(async (req, res) => {
// as `kind === 'character'` would have left the UI blank for exactly the
// records the registry had just admitted.
const { kind } = detail.record;
- const kindTracks = tracksForKind(kind);
- const runsWalk = kindSupportsTrack(kind, WALK_TRACK);
+ const effectiveTracks = getEffectiveAnimationTracks();
+ const kindTracks = tracksForKind(kind, effectiveTracks);
+ const runsWalk = kindSupportsTrack(kind, WALK_TRACK, effectiveTracks);
// Every non-walk track this record's kind may carry, resolved from the registry
// (#3136) instead of one hand-written `runsScanner`/`runsAmbient` flag per
// track. Each state carries its own `definition` (the registry row), so the
diff --git a/server/services/sprites/animationTargets.js b/server/services/sprites/animationTargets.js
index 37f2d5cfbc..68ded13fd2 100644
--- a/server/services/sprites/animationTargets.js
+++ b/server/services/sprites/animationTargets.js
@@ -32,6 +32,10 @@
import {
WALK_TRACK, getAnimationTrack,
} 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';
// 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.
@@ -85,7 +89,7 @@ export function resolveAnimationTarget({
packagedCycles = [],
} = {}) {
// Absent → the default track; unrecognized → throws (see getAnimationTrack).
- const row = getAnimationTrack(track);
+ const row = getAnimationTrack(track, getEffectiveAnimationTracks());
// The bound app's declared expectation for its own atlas (#2982) — a stronger
// authority than any per-render pick. Read defensively: that field lands
@@ -137,7 +141,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);
+ const row = getAnimationTrack(track, getEffectiveAnimationTracks());
const existing = (animationTargets && typeof animationTargets === 'object' && !Array.isArray(animationTargets))
? animationTargets
: {};
@@ -155,7 +159,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);
+ const row = getAnimationTrack(target?.track, getEffectiveAnimationTracks());
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.js
new file mode 100644
index 0000000000..d36b445ffe
--- /dev/null
+++ b/server/services/sprites/animationTrackStore.js
@@ -0,0 +1,195 @@
+/**
+ * Sprites — the user-defined animation-track store (issue #3152).
+ *
+ * #3136 made a track's whole workflow registry DATA — bounds, directionality,
+ * on-disk kinds, source reference, prompt — so `animationTrackWorkflow.js` +
+ * `POST /:id/tracks/:trackId/{generate,approve}` drive any row without new code.
+ * What was still missing is a way for a *user* to add a row: the table was three
+ * hardcoded entries, and "a chest opening", "a flower blossoming", or "a jetpack
+ * burst" needed a PortOS release. This module is that store, and
+ * `getEffectiveAnimationTracks()` is the merged table every registry reader now
+ * resolves against.
+ *
+ * **Why a separate module.** `animationTracks.js` is asserted to be a TRUE LEAF
+ * (`animationTracks.test.js`, "keeps animationTracks.js a true leaf") because
+ * `server/lib/validation.js` builds its sprite Zod ranges from it and must not
+ * drag the native image graph into request validation. A store that reads a file
+ * cannot live there. So the dependency runs one way only: this module imports the
+ * leaf, never the reverse. It reaches `fileUtils.js` (fs + crypto + path, no
+ * native image deps — `validation.js` already imports it), so the sharp-free
+ * property that guard actually protects still holds through the merge.
+ *
+ * **Reads are SYNCHRONOUS, deliberately — and this is the answer to #3152's
+ * "lazily-built schema or boot-ordering guarantee" question: NEITHER.** Every
+ * registry reader is sync (`getAnimationTrack`, `trackDirections`,
+ * `clampTrackFrameCount`) and `server/lib/validation.js` builds
+ * `spriteRuntimeContractSchema` from the table at MODULE LOAD. An async store
+ * would force one of two bad answers: thread `await` through ~30 pure call sites
+ * (including Zod schema construction, which cannot await), or promise that the
+ * store is read before validation.js is imported — a guarantee nothing enforces
+ * and that ES module hoisting actively breaks, since `server/index.js` imports
+ * the whole route graph before it awaits `bootstrapServices`. A `readFileSync` of
+ * one small hand-editable config at first use is the same call
+ * `lib/curatedGenomeMarkers.js` and `lib/mediaModels.js` already make, costs one
+ * stat+read per process, and keeps every existing signature untouched.
+ *
+ * **The shipped seed is the fallback, so no boot ordering is load-bearing.** When
+ * `data/sprites/animation-tracks.json` is ABSENT the store reads
+ * `data.reference/sprites/animation-tracks.json` instead. That matters for the
+ * upgrade path: module load happens before boot migrations run, so on the first
+ * boot after this ships, migration 211 has not yet materialized the user copy —
+ * and without the fallback that boot would build a contract schema with no
+ * `scannerFrameCount` and refuse to compile an already-approved scanner set. With
+ * it, an install sees the seeded rows from the first import onward and the
+ * migration's job narrows to giving the user an editable copy. A store file that
+ * EXISTS is authoritative and never merged with the seed — that is what lets a
+ * user delete `scanner` and have it stay deleted.
+ *
+ * **`file-primary`, per docs/STORAGE.md.** `data/sprites/animation-tracks.json`
+ * is a small, hand-editable, machine-local authoring config that the on-disk
+ * sprite tree is meaningless without — a stored row names the `setKind` strings
+ * an approved set on THIS machine already carries, so the two travel together or
+ * neither means anything. No cross-record queries, no relationships beyond the
+ * `kinds` strings, no sync cursor: same class as the LoRA-dataset and MortalLoom
+ * stores, and it rides the rsync snapshot rather than a Postgres dump.
+ *
+ * **A bad stored row fails loudly at LOAD, not at render.** The merged table goes
+ * through `assertAnimationTrackRows` — the same guard the compiled table runs at
+ * module load — so a row missing a bound, colliding on a contract field, or
+ * claiming another track's `setKind` throws here with the field named, instead of
+ * surfacing hours later as a `NaN` frame count or one track's finalized set
+ * satisfying another's evidence check.
+ *
+ * **The cache is the restart boundary.** Per #3136/#3152's scope, adding or
+ * editing a track takes effect on the next server start. The cache is what makes
+ * that explicit rather than accidental: the merge is called on hot paths (every
+ * generate, every compile, every route resolve) and re-reading the file each time
+ * 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.
+ */
+
+import { readFileSync } from 'fs';
+import { join } from 'path';
+import { PATHS } from '../../lib/fileUtils.js';
+import { ANIMATION_TRACKS, WALK_TRACK, assertAnimationTrackRows } 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';
+/** The store's on-disk layout version (distinct from any per-row shape version). */
+export const ANIMATION_TRACK_STORE_SCHEMA_VERSION = 1;
+
+/** The user-owned store — authoritative when it exists. */
+export const animationTrackStorePath = () => join(PATHS.data, ANIMATION_TRACK_STORE_REL);
+/** 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.
+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.
+ */
+function readStoreDoc(path) {
+ let raw;
+ try {
+ raw = readFileSync(path, 'utf-8');
+ } catch (err) {
+ if (err?.code === 'ENOENT') return null;
+ throw new Error(`${ANIMATION_TRACK_STORE_REL}: cannot read ${path} — ${err.message}`);
+ }
+ try {
+ return JSON.parse(raw);
+ } catch (err) {
+ throw new Error(`${ANIMATION_TRACK_STORE_REL}: ${path} is not valid JSON — ${err.message}`);
+ }
+}
+
+/**
+ * Freeze one raw stored row into the exact shape a compiled row has, with
+ * `builtin: false` forced.
+ *
+ * Forced rather than read: a stored row claiming `builtin: true` would pass the
+ * "builtin rows carry no promptTemplate" guard by shedding its own prompt and
+ * then throw at generate time with no builder to fall back to. Where a row came
+ * from is a fact about the store, not a field the store's contents get a vote on.
+ */
+const normalizeStoredRow = (raw) => Object.freeze({
+ ...raw,
+ kinds: Object.freeze([...(Array.isArray(raw?.kinds) ? raw.kinds : [])]),
+ builtin: false,
+});
+
+/**
+ * The user-defined rows, keyed by id — `{}` when neither the store nor the seed
+ * exists, or when the resolved file holds no `tracks` array.
+ */
+function loadStoredRows() {
+ if (cachedStoredRows) return cachedStoredRows;
+ const doc = readStoreDoc(animationTrackStorePath()) ?? readStoreDoc(animationTrackSeedPath());
+ const rows = Array.isArray(doc?.tracks) ? doc.tracks : [];
+ const byId = {};
+ for (const raw of rows) {
+ const id = raw?.id;
+ if (typeof id !== 'string' || !id) {
+ throw new Error(`${ANIMATION_TRACK_STORE_REL}: every stored track needs a non-empty string id`);
+ }
+ // Shadowing `walk` would replace the one mandatory built-in through a data
+ // edit — its bounds feed the Zod schemas and its `setKind` gates every
+ // character compile, so a store row could brick authoring with no code change
+ // to point at. Refuse it by name rather than letting the spread decide.
+ if (id === WALK_TRACK) {
+ throw new Error(`${ANIMATION_TRACK_STORE_REL}: '${WALK_TRACK}' is the mandatory built-in track and cannot be redefined by a stored row`);
+ }
+ 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;
+}
+
+/**
+ * The compiled table merged with the user-defined store: `{ walk, …stored }`.
+ *
+ * Registration order puts `walk` first, which is what keeps every derived
+ * ordering (the atlas span order, the effective id list) byte-stable across
+ * installs regardless of what the user has added.
+ *
+ * Validated as a WHOLE table, not row by row: the invariants that matter most
+ * here are cross-row (two tracks claiming one contract field or one `setKind`, or
+ * a record kind ending up with two standalone baselines), and a per-row check
+ * would miss every one of them.
+ */
+export function getEffectiveAnimationTracks() {
+ if (cachedEffectiveTracks) return cachedEffectiveTracks;
+ const merged = Object.freeze({ ...ANIMATION_TRACKS, ...loadStoredRows() });
+ assertAnimationTrackRows(merged);
+ cachedEffectiveTracks = merged;
+ return merged;
+}
+
+/** Effective track ids, in registration order (`walk` first, then stored). */
+export function getEffectiveAnimationTrackIds() {
+ return Object.keys(getEffectiveAnimationTracks());
+}
+
+/**
+ * Drop the cached store read.
+ *
+ * For tests, and for the CRUD UI (#3153) to call after it writes — a write that
+ * left the cache standing would report success while the running server kept
+ * 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.js
new file mode 100644
index 0000000000..7ae622e836
--- /dev/null
+++ b/server/services/sprites/animationTrackStore.test.js
@@ -0,0 +1,223 @@
+/**
+ * The user-defined animation-track store (#3152).
+ *
+ * The store is what turns "add an animation type" from a PortOS release into a
+ * data edit, so what matters here is not that it can read a file — it is that
+ * every way a stored row could quietly corrupt the sprite pipeline fails LOUDLY
+ * instead. `assertAnimationTrackRows` already owns the row-shape rules
+ * (`animationTracks.test.js` proves those against synthetic tables); this suite
+ * covers what only the store can get wrong:
+ *
+ * - the MERGE — `walk` stays, stored rows join, order is stable
+ * - the SEED FALLBACK — an install with no user copy still sees scanner/ambient,
+ * which is the upgrade path's whole safety net
+ * - the SENTINEL rules — absent ≠ empty ≠ corrupt
+ * - the `walk`-shadow refusal and the duplicate-id refusal
+ * - `builtin: false` FORCED, not read from the row
+ * - the cache, and that resetting it re-reads
+ *
+ * `PATHS` is redirected at a temp tree so every case writes a real store file: the
+ * store's contract is about files on disk, and mocking its reader away would leave
+ * the sentinel distinctions (ENOENT vs. unparseable) untested — those are exactly
+ * where a "helpful" fallback would silently revert a user's tracks to the shipped
+ * defaults.
+ */
+
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-track-store-test-'));
+
+vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ Object.assign(actual.PATHS, { data: TEST_ROOT, sprites: join(TEST_ROOT, 'sprites') });
+ return actual;
+});
+
+const {
+ getEffectiveAnimationTracks, getEffectiveAnimationTrackIds, __resetAnimationTrackStore,
+ animationTrackStorePath, animationTrackSeedPath, ANIMATION_TRACK_STORE_SCHEMA_VERSION,
+} = await import('./animationTrackStore.js');
+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,
+});
+
+const writeStore = (doc) => {
+ mkdirSync(join(TEST_ROOT, 'sprites'), { recursive: true });
+ writeFileSync(STORE_PATH, typeof doc === 'string' ? doc : JSON.stringify(doc, null, 2));
+};
+
+const writeTracks = (tracks) => writeStore({ schemaVersion: ANIMATION_TRACK_STORE_SCHEMA_VERSION, tracks });
+
+beforeEach(() => {
+ rmSync(STORE_PATH, { force: true });
+ __resetAnimationTrackStore();
+});
+afterAll(() => rmSync(TEST_ROOT, { recursive: true, force: true }));
+
+describe('the merge', () => {
+ it('keeps walk and appends stored rows in a stable order', () => {
+ writeTracks([userRow(), userRow({
+ id: 'flower-blossoming',
+ label: 'Flower blossoming',
+ kinds: ['place'],
+ contractFrameCountField: 'flowerBlossomingFrameCount',
+ selectionKind: 'reviewed-flower-blossoming-selection',
+ setKind: 'finalized-flower-blossoming-set',
+ finalErrorCode: 'FLOWER_BLOSSOMING_SET_FINAL',
+ // `place` already has a standalone baseline in this table only if another
+ // row claims it — here nothing else does, so this row is `place`'s primary.
+ })]);
+ // `walk` FIRST, then store order — load-bearing, because the atlas span order
+ // and every derived id list follow it, so a shuffle would recompile pixels.
+ expect(getEffectiveAnimationTrackIds()).toEqual([WALK_TRACK, 'chest-opening', 'flower-blossoming']);
+ expect(getEffectiveAnimationTracks()[WALK_TRACK]).toEqual(ANIMATION_TRACKS[WALK_TRACK]);
+ });
+
+ it('marks a stored row user-defined even when the row claims otherwise', () => {
+ // FORCED, not read. A row claiming `builtin: true` would otherwise pass the
+ // "builtin rows carry no promptTemplate" guard by shedding its prompt, then
+ // throw at generate time with no compiled builder to fall back to.
+ writeTracks([{ ...userRow(), builtin: true }]);
+ expect(getEffectiveAnimationTracks()['chest-opening'].builtin).toBe(false);
+ });
+
+ it('validates the merged table, so a row that collides WITH WALK is refused', () => {
+ // The invariant a per-row check would miss: this row is internally fine and
+ // only conflicts across rows. Claiming walk's contract field would make
+ // `resolveAnimationTarget` read walk's `walkFrameCount` for this track and
+ // return it as a locked value, citing a binding that never mentioned it.
+ writeTracks([userRow({ contractFrameCountField: 'walkFrameCount' })]);
+ expect(() => getEffectiveAnimationTracks()).toThrow(/claimed by both/);
+ });
+
+ it('refuses a stored row that collides with another stored row\'s on-disk kind', () => {
+ writeTracks([userRow(), userRow({
+ id: 'second',
+ contractFrameCountField: 'secondFrameCount',
+ // Same setKind as the first row: the compiler validates a finalized set BY
+ // its kind, so a duplicate lets one track's set satisfy the other's
+ // evidence check and compile the wrong frames into its span.
+ selectionKind: 'reviewed-second-selection',
+ standaloneContract: false,
+ })]);
+ expect(() => getEffectiveAnimationTracks()).toThrow(/finalized-chest-opening-set/);
+ });
+
+ it('refuses a stored row missing its promptTemplate', () => {
+ // There is no compiled builder for a stored row, so a blank template would
+ // surface as a throw only AFTER the user clicked generate.
+ const { promptTemplate, ...noPrompt } = userRow();
+ expect(promptTemplate).toBeTruthy();
+ writeTracks([noPrompt]);
+ expect(() => getEffectiveAnimationTracks()).toThrow(/needs a non-empty 'promptTemplate'/);
+ __resetAnimationTrackStore();
+ writeTracks([userRow({ promptTemplate: ' ' })]);
+ expect(() => getEffectiveAnimationTracks()).toThrow(/needs a non-empty 'promptTemplate'/);
+ });
+
+ it('refuses a stored row that redefines walk', () => {
+ // Walk's bounds feed the Zod schemas and its setKind gates every character
+ // compile, so a data edit must not be able to replace it.
+ writeTracks([userRow({ id: WALK_TRACK })]);
+ expect(() => getEffectiveAnimationTracks()).toThrow(/mandatory built-in/);
+ });
+
+ it('refuses a duplicate stored id rather than letting the last one win', () => {
+ writeTracks([userRow(), userRow({ label: 'A different label' })]);
+ expect(() => getEffectiveAnimationTracks()).toThrow(/defined twice/);
+ });
+
+ it('refuses a stored row with no usable id', () => {
+ writeTracks([{ ...userRow(), id: '' }]);
+ expect(() => getEffectiveAnimationTracks()).toThrow(/non-empty string id/);
+ });
+});
+
+describe('absent vs. empty vs. corrupt (the sentinel rules)', () => {
+ it('falls back to the shipped seed when the user copy is absent', () => {
+ // The upgrade path's safety net: module load happens BEFORE boot migrations,
+ // so on the first boot after #3152 there is no user copy yet. Without this,
+ // that boot would build a contract schema with no `scannerFrameCount` and
+ // refuse to compile an already-approved scanner set.
+ expect(getEffectiveAnimationTrackIds()).toEqual([WALK_TRACK, 'scanner', 'ambient']);
+ expect(animationTrackSeedPath()).toMatch(/data\.reference[/\\]sprites[/\\]animation-tracks\.json$/);
+ });
+
+ it('treats an EXISTING store as authoritative — the seed is not merged in', () => {
+ // What makes a deletion stick. A user who removed `scanner` must not have it
+ // resurrected from the seed on the next read.
+ writeTracks([userRow()]);
+ expect(getEffectiveAnimationTrackIds()).toEqual([WALK_TRACK, 'chest-opening']);
+ expect(getEffectiveAnimationTracks().scanner).toBeUndefined();
+ });
+
+ it('treats an empty tracks array as "the user deleted everything", not as absent', () => {
+ // `[]` is a legitimate state — walk alone — and must NOT fall through to the
+ // seed, which would make deleting every track impossible.
+ writeTracks([]);
+ expect(getEffectiveAnimationTrackIds()).toEqual([WALK_TRACK]);
+ });
+
+ it('throws on an unreadable store rather than silently reverting to the seed', () => {
+ // The sentinel rule that matters most: a user whose hand edit broke the JSON
+ // must get an error naming the file, not a silent revert to shipped defaults
+ // that reads as "my tracks vanished".
+ writeStore('{ "tracks": [ oops ');
+ expect(() => getEffectiveAnimationTracks()).toThrow(/is not valid JSON/);
+ });
+});
+
+describe('the cache', () => {
+ it('reads once per process and re-reads after a reset', () => {
+ writeTracks([userRow()]);
+ expect(getEffectiveAnimationTrackIds()).toEqual([WALK_TRACK, 'chest-opening']);
+
+ // A write with no reset must NOT take effect — that is the documented
+ // restart boundary, and it is what keeps a compile from validating spans
+ // against a table the render that produced them never saw.
+ writeTracks([userRow({
+ id: 'other',
+ contractFrameCountField: 'otherFrameCount',
+ selectionKind: 'reviewed-other-selection',
+ setKind: 'finalized-other-set',
+ finalErrorCode: 'OTHER_SET_FINAL',
+ })]);
+ expect(getEffectiveAnimationTrackIds()).toEqual([WALK_TRACK, 'chest-opening']);
+
+ __resetAnimationTrackStore();
+ expect(getEffectiveAnimationTrackIds()).toEqual([WALK_TRACK, 'other']);
+ });
+
+ it('returns the identical frozen table object on repeat calls', () => {
+ writeTracks([userRow()]);
+ const first = getEffectiveAnimationTracks();
+ expect(getEffectiveAnimationTracks()).toBe(first);
+ expect(Object.isFrozen(first)).toBe(true);
+ expect(() => { first['chest-opening'].minFrameCount = 1; }).toThrow();
+ });
+});
diff --git a/server/services/sprites/animationTrackWorkflow.js b/server/services/sprites/animationTrackWorkflow.js
index 1e8422f1c7..262a12b54a 100644
--- a/server/services/sprites/animationTrackWorkflow.js
+++ b/server/services/sprites/animationTrackWorkflow.js
@@ -51,6 +51,10 @@ import { requireTrack, loadManifest } from './reference.js';
import { anchorIdForDirection } from './prompts.js';
import { buildTrackVideoPrompt } from './trackPrompts.js';
import { clampTrackFrameCount, clampTrackFps, getAnimationTrack, 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 { trackDirections } from './atlasGrid.js';
import { spriteDir, resolveSpriteAssetPath, SOURCE_CLIP_NAME } from './paths.js';
import { prepareWalkAnchorChromaInput, runWalkPostprocess } from './walkPostprocess.js';
@@ -130,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);
+ const row = getAnimationTrack(trackId, getEffectiveAnimationTracks());
const [selection, set, runs] = await Promise.all([
loadSelection(row.id, recordId), loadSet(row.id, recordId), trackRuns(row.id, recordId),
]);
@@ -153,7 +157,7 @@ export async function getTrackState(trackId, recordId) {
* different answer from "frozen but gone", handled by the caller's disk check.
*/
function trackSourceFor(row, manifest, direction) {
- if (sourceReferenceFor(row.id) === 'main') {
+ if (sourceReferenceFor(row.id, getEffectiveAnimationTracks()) === 'main') {
const main = lockedMainFor(manifest);
return {
label: 'main reference',
@@ -209,7 +213,7 @@ export function startTrackGeneration(trackId, recordId, body) {
}
async function startTrackGenerationImpl(trackId, recordId, body) {
- const row = getAnimationTrack(trackId);
+ const row = getAnimationTrack(trackId, getEffectiveAnimationTracks());
const [record, reference, existingSet, existingRuns] = await Promise.all([
requireTrack(recordId, row.id), loadManifest(recordId), loadSet(row.id, recordId), trackRuns(row.id, recordId),
]);
@@ -233,8 +237,8 @@ async function startTrackGenerationImpl(trackId, recordId, body) {
);
}
- const frameCount = clampTrackFrameCount(body.frameCount, row.id);
- const fps = clampTrackFps(body.fps, row.id);
+ const frameCount = clampTrackFrameCount(body.frameCount, row.id, getEffectiveAnimationTracks());
+ const fps = clampTrackFps(body.fps, row.id, getEffectiveAnimationTracks());
// 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() : '';
@@ -320,7 +324,7 @@ async function runTrackTuiRender(row, recordId, { runId, direction, generatedAbs
}
export async function attachTrackTuiResult(trackId, recordId, runId, videoAbs) {
- const row = getAnimationTrack(trackId);
+ const row = getAnimationTrack(trackId, getEffectiveAnimationTracks());
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);
@@ -360,8 +364,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),
- fps: clampTrackFps(run.fps, row.id),
+ frameCount: clampTrackFrameCount(run.frameCount, row.id, getEffectiveAnimationTracks()),
+ fps: clampTrackFps(run.fps, row.id, getEffectiveAnimationTracks()),
});
run.frameCount = result.manifest.frameCount;
run.fps = result.manifest.frameRate;
@@ -382,7 +386,7 @@ export function approveTrackRun(trackId, recordId, args) {
}
async function approveTrackRunImpl(trackId, recordId, { direction: requested, runId }) {
- const row = getAnimationTrack(trackId);
+ const row = getAnimationTrack(trackId, getEffectiveAnimationTracks());
await requireTrack(recordId, row.id);
if (await loadSet(row.id, recordId)) throw setFinalError(row);
const direction = resolveTrackDirection(row, requested);
@@ -476,7 +480,7 @@ export function invalidateTrackForTurnaroundRevision(trackId, recordId) {
}
async function invalidateTrackDirectionImpl(trackId, recordId, direction) {
- const row = getAnimationTrack(trackId);
+ const row = getAnimationTrack(trackId, getEffectiveAnimationTracks());
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/animationTrackWorkflow.test.js b/server/services/sprites/animationTrackWorkflow.test.js
index a94b5e1be0..c4df0411d3 100644
--- a/server/services/sprites/animationTrackWorkflow.test.js
+++ b/server/services/sprites/animationTrackWorkflow.test.js
@@ -66,6 +66,13 @@ const {
const {
getAnimationTrack, sourceReferenceFor, SCANNER_TRACK, AMBIENT_TRACK,
} = await import('./animationTracks.js');
+// #3152 — `scanner`/`ambient` are seeded STORE rows now, so the expectations below
+// resolve them through the merged table exactly as the module under test does.
+// This suite deliberately reads the SHIPPED seed rather than writing a synthetic
+// store: its subject is "the generic workflow reads the row it was handed", and the
+// two seeded rows are precisely the directional/non-directional pair that proves it.
+const { getEffectiveAnimationTracks } = await import('./animationTrackStore.js');
+const EFFECTIVE = getEffectiveAnimationTracks();
let sequence = 0;
const newId = () => `track-${++sequence}`;
@@ -122,7 +129,7 @@ beforeEach(() => {
afterAll(() => rmSync(TEST_ROOT, { recursive: true, force: true }));
describe.each(TRACKS)('the generic workflow drives the $id track', (track) => {
- const row = () => getAnimationTrack(track.id);
+ const row = () => getAnimationTrack(track.id, EFFECTIVE);
it('is provider-silent on reads, then starts one user-triggered render at the row\'s defaults', async () => {
const id = await track.seed(newId());
@@ -242,7 +249,7 @@ describe.each(TRACKS)('the generic workflow drives the $id track', (track) => {
);
await expect(startTrackGeneration(track.id, id, track.body)).rejects.toMatchObject({
status: 409,
- code: sourceReferenceFor(track.id) === 'main' ? 'MAIN_NOT_LOCKED' : 'ANCHOR_NOT_LOCKED',
+ code: sourceReferenceFor(track.id, EFFECTIVE) === 'main' ? 'MAIN_NOT_LOCKED' : 'ANCHOR_NOT_LOCKED',
});
expect(executeTuiRun).not.toHaveBeenCalled();
});
diff --git a/server/services/sprites/animationTracks.js b/server/services/sprites/animationTracks.js
index 3dac8e7892..74c01a5bab 100644
--- a/server/services/sprites/animationTracks.js
+++ b/server/services/sprites/animationTracks.js
@@ -49,17 +49,46 @@
* the render), and `animationTrackWorkflow.js` is the one implementation both
* drive. A user-defined track is therefore a row plus a prompt template — no new
* service module, no new routes.
+ *
+ * **`walk` is the only COMPILED-IN row (#3152).** Every other track — including
+ * `scanner` and `ambient`, which shipped as compiled rows through #3018/#3045 —
+ * now lives in the user-defined store `animationTrackStore.js` reads, seeded
+ * from `data.reference/sprites/animation-tracks.json` by migration 211. That
+ * store is what makes "a chest opening" or "a flower blossoming" a user action
+ * rather than a PortOS code change, and it is why this table shrank to one row
+ * instead of growing a fourth. The MERGE cannot live here: this module does file
+ * I/O nowhere and imports nothing (see the leaf note above), so the store
+ * imports this and never the reverse. Callers that must see user rows resolve
+ * `getEffectiveAnimationTracks()` and pass it through the `tracks` parameter
+ * every reader below already takes.
+ *
+ * A stored row carries two fields a compiled one doesn't: `promptTemplate` (the
+ * i2v wording `trackPrompts.js` falls back to, since a user row has no compiled
+ * builder) and `builtin: false`. `assertAnimationTrackRows` validates a stored
+ * row exactly as it validates this table's, so a bad row fails loudly at load
+ * rather than corrupting a render hours later.
*/
-/** The default track — the only one that exists today. */
+/** The default track — and the only one compiled into this build (#3152). */
export const WALK_TRACK = 'walk';
-/** The first short, directional character action (#3018). */
+/**
+ * The seeded short directional character action (#3018) and non-directional
+ * environment loop (#3045).
+ *
+ * Still NAMED here because `atlas.js` dispatches its two bespoke evidence chains
+ * on these exact ids and existing on-disk sets carry them — but they are no
+ * longer ROWS in `ANIMATION_TRACKS`: migration 211 moved both into the
+ * user-defined store, where a user can retune or delete them like any other
+ * track. Resolve them through `getEffectiveAnimationTracks()`; a `getAnimationTrack`
+ * call against the compiled table alone will (correctly) throw for them.
+ */
export const SCANNER_TRACK = 'scanner';
-/** The first non-directional environment loop (#3045). */
export const AMBIENT_TRACK = 'ambient';
/**
- * Every known animation track.
+ * Every animation track compiled into this build — `walk`, and only `walk`
+ * (#3152). Merge with the user-defined store via `getEffectiveAnimationTracks()`
+ * before handing this to any reader that must see a user's tracks.
*
* - `minFrameCount` / `maxFrameCount` — the authoring range the packer clamps
* into and the Zod schemas range-check against.
@@ -92,6 +121,14 @@ export const AMBIENT_TRACK = 'ambient';
* that could exist. DECLARED rather than inferred from registration order: it
* is a load-bearing publish-validation rule, and #3152 merges rows from a
* user-ordered store where "first row for this kind" would silently change.
+ * - `builtin` (#3152) — true for a row compiled into this build, false for one
+ * loaded from the user-defined store. Read by the store's merge (a user row may
+ * not shadow `walk`) and by the prompt resolver (a builtin row has a compiled
+ * prompt builder; a stored one carries `promptTemplate` instead).
+ * - `promptTemplate` (#3152, stored rows ONLY) — the i2v instruction sent to the
+ * provider for this track, as literal text. A builtin row omits it and resolves
+ * through the compiled builder in `trackPrompts.js`; a stored row must carry it,
+ * because there is no code to fall back to.
*
* Which locked reference an i2v render is seeded from is DERIVED, not declared:
* a directional track renders one clip per facing and so must seed from that
@@ -131,57 +168,9 @@ export const ANIMATION_TRACKS = Object.freeze({
// A character publishes off its walk — the compile path requires a finalized
// walk set before it emits anything at all.
standaloneContract: true,
- }),
- [SCANNER_TRACK]: Object.freeze({
- id: SCANNER_TRACK,
- label: 'Scanner action',
- directional: true,
- // A scanner pose is still one per character facing, so it reuses the
- // locked directional anchors and fills all eight atlas rows.
- kinds: Object.freeze(['character']),
- minFrameCount: 2,
- maxFrameCount: 8,
- defaultFrameCount: 4,
- minFps: 2,
- maxFps: 12,
- defaultFps: 6,
- contractFrameCountField: 'scannerFrameCount',
- // The game owns action timing; PortOS carries fps as preview provenance.
- contractFpsField: null,
- // The historical on-disk spellings, kept verbatim: an already-approved
- // scanner set on any install must keep validating after the clone collapsed
- // into the generic workflow, and the compiler matches these exact strings.
- selectionKind: 'reviewed-directional-scanner-selection',
- setKind: 'finalized-eight-direction-scanner-set',
- finalErrorCode: 'SCANNER_SET_FINAL',
- // A scanner action rides beside the walk it shares atlas rows with — it is
- // never the only thing a character publishes, so its span alone doesn't
- // describe an atlas.
- standaloneContract: false,
- }),
- [AMBIENT_TRACK]: Object.freeze({
- id: AMBIENT_TRACK,
- label: 'Ambient loop',
- directional: false,
- // `props` is the legacy import-only spelling of `object`; keeping it here
- // makes an imported prop atlas and a newly-authored object behave alike.
- kinds: Object.freeze(['place', 'object', 'props']),
- minFrameCount: 2,
- maxFrameCount: 6,
- defaultFrameCount: 3,
- minFps: 2,
- maxFps: 12,
- defaultFps: 4,
- contractFrameCountField: 'ambientFrameCount',
- // Ambient cadence belongs to the consuming app. PortOS keeps fps only as
- // authoring-preview provenance, like scanner.
- contractFpsField: null,
- selectionKind: 'reviewed-single-row-ambient-selection',
- setKind: 'finalized-single-row-ambient-set',
- finalErrorCode: 'AMBIENT_SET_FINAL',
- // A place publishes off its ambient loop — it has no walk, so this IS its
- // baseline and the compile path requires its finalized set.
- standaloneContract: true,
+ // The one mandatory built-in. `scanner` and `ambient` were `builtin: true`
+ // rows here until #3152 moved them into the user-defined store as seed data.
+ builtin: true,
}),
});
@@ -237,6 +226,22 @@ export function assertAnimationTrackRows(tracks) {
if (typeof row.standaloneContract !== 'boolean') {
throw new Error(`animationTracks: track '${id}' needs a boolean 'standaloneContract'`);
}
+ // #3152 — where the row came from, and (for a stored row) its prompt.
+ 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`);
+ }
// 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 a
// duplicate would let one track's finalized set satisfy the other's evidence
@@ -414,14 +419,20 @@ const clampInto = (n, min, max, fallback) => {
return Math.max(min, Math.min(max, v));
};
-/** Clamp a requested frame count into `track`'s authoring range. */
-export function clampTrackFrameCount(n, track) {
- const row = getAnimationTrack(track);
+/**
+ * Clamp a requested frame count into `track`'s authoring range.
+ *
+ * `tracks` is the same injectable table every reader above takes (#3152) —
+ * callers that must clamp a USER-DEFINED track pass the effective table, since a
+ * stored row is unknown to the compiled default and would throw.
+ */
+export function clampTrackFrameCount(n, track, tracks = ANIMATION_TRACKS) {
+ const row = getAnimationTrack(track, tracks);
return clampInto(n, row.minFrameCount, row.maxFrameCount, row.defaultFrameCount);
}
/** Clamp a requested playback fps into `track`'s authoring range. */
-export function clampTrackFps(n, track) {
- const row = getAnimationTrack(track);
+export function clampTrackFps(n, track, tracks = ANIMATION_TRACKS) {
+ const row = getAnimationTrack(track, tracks);
return clampInto(n, row.minFps, row.maxFps, row.defaultFps);
}
diff --git a/server/services/sprites/animationTracks.test.js b/server/services/sprites/animationTracks.test.js
index ab1755af7f..51c4db9289 100644
--- a/server/services/sprites/animationTracks.test.js
+++ b/server/services/sprites/animationTracks.test.js
@@ -6,6 +6,14 @@
* The walk row is pinned to its historical values on purpose: #3015 is a
* refactor, and a registry that quietly moved walk's floor would change every
* render's geometry while looking like plumbing.
+ *
+ * **Compiled vs. effective, since #3152.** `ANIMATION_TRACKS` now holds only
+ * `walk`; `scanner` and `ambient` are seeded rows in the user-defined store. So a
+ * test about the SHIPPED SET of tracks resolves `EFFECTIVE` (the merge) while a
+ * test about the compiled table asserts `walk` alone — and the difference is
+ * itself asserted, because "walk is the only built-in" is the property #3152
+ * exists to establish. The store's own behavior (merge, seed fallback, bad-row
+ * rejection) lives in `animationTrackStore.test.js`.
*/
import { describe, it, expect } from 'vitest';
@@ -18,6 +26,7 @@ import {
assertAnimationTrackRows, trackRowCount, tracksForKind, kindSupportsTrack,
sourceReferenceFor, primaryTrackForKind,
} from './animationTracks.js';
+import { getEffectiveAnimationTracks, getEffectiveAnimationTrackIds } from './animationTrackStore.js';
import { SPRITE_RECORD_KINDS } from './recordsLogic.js';
import { AMBIENT_TRACK_ROW } from './spriteTestFixtures.js';
import {
@@ -33,6 +42,12 @@ import {
const SPRITES_DIR = dirname(fileURLToPath(import.meta.url));
const SERVER_DIR = dirname(dirname(SPRITES_DIR));
+// The merged table this install actually serves — compiled `walk` plus the seeded
+// store rows. Resolved once: the store caches its read, so every call in this file
+// sees one consistent table.
+const EFFECTIVE = getEffectiveAnimationTracks();
+const effectiveTrack = (id) => getAnimationTrack(id, EFFECTIVE);
+
describe('the registry rows', () => {
it('reproduces the walk track\'s historical bounds and defaults exactly', () => {
// #3015 is a refactor — walk behaves identically end to end.
@@ -53,8 +68,24 @@ describe('the registry rows', () => {
});
});
+ it('compiles in walk and ONLY walk (#3152)', () => {
+ // The property #3152 establishes. Asserted against the compiled constant
+ // 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(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();
+ // …and still reachable through the merge, carrying the marker that says
+ // where it came from. Both halves matter: "not compiled" without "still
+ // served" would be satisfied by simply deleting the track.
+ expect(effectiveTrack(id).builtin, `${id} must be marked user-defined`).toBe(false);
+ }
+ });
+
it('registers the short scanner action independently of walk', () => {
- expect(getAnimationTrack(SCANNER_TRACK)).toMatchObject({
+ expect(effectiveTrack(SCANNER_TRACK)).toMatchObject({
id: SCANNER_TRACK,
directional: true,
kinds: ['character'],
@@ -70,7 +101,7 @@ describe('the registry rows', () => {
});
it('registers the single-row ambient loop for places and objects', () => {
- expect(getAnimationTrack(AMBIENT_TRACK)).toMatchObject({
+ expect(effectiveTrack(AMBIENT_TRACK)).toMatchObject({
id: AMBIENT_TRACK,
label: 'Ambient loop',
directional: false,
@@ -90,8 +121,11 @@ describe('the registry rows', () => {
// Mirrors the module-load guard in animationTracks.js (which is what
// actually blocks boot on a bad row) so a shape violation reads as a named
// assertion here rather than only as an import-time throw somewhere else.
- for (const id of ANIMATION_TRACK_IDS) {
- const row = ANIMATION_TRACKS[id];
+ // Walks the EFFECTIVE table so a malformed SEEDED row is caught here too —
+ // scoping this to the compiled table would have narrowed it to one row the
+ // moment #3152 landed.
+ for (const id of getEffectiveAnimationTrackIds()) {
+ const row = EFFECTIVE[id];
expect(row.id, `${id}.id must match its registry key`).toBe(id);
expect(typeof row.label).toBe('string');
expect(typeof row.directional).toBe('boolean');
@@ -228,8 +262,8 @@ describe('registry-derived source reference and primacy (#3136)', () => {
// non-directional one has no anchor to read at all — a place record never
// generates directional anchors.
expect(sourceReferenceFor(WALK_TRACK)).toBe('anchor');
- expect(sourceReferenceFor(SCANNER_TRACK)).toBe('anchor');
- expect(sourceReferenceFor(AMBIENT_TRACK)).toBe('main');
+ expect(sourceReferenceFor(SCANNER_TRACK, EFFECTIVE)).toBe('anchor');
+ expect(sourceReferenceFor(AMBIENT_TRACK, EFFECTIVE)).toBe('main');
// Reads the row it's HANDED, not the shipped table.
expect(sourceReferenceFor('ambient', { ambient: AMBIENT_TRACK_ROW })).toBe('main');
expect(() => sourceReferenceFor('unknown')).toThrow(/Unknown animation track/);
@@ -238,16 +272,16 @@ describe('registry-derived source reference and primacy (#3136)', () => {
it('answers which track a record kind publishes off', () => {
// ONE definition, shared by the publish-contract schema (which field is
// required) and the compile dispatch (which evidence chain to validate).
- expect(primaryTrackForKind('character')?.id).toBe(WALK_TRACK);
- expect(primaryTrackForKind('place')?.id).toBe(AMBIENT_TRACK);
- expect(primaryTrackForKind('object')?.id).toBe(AMBIENT_TRACK);
- expect(primaryTrackForKind('props')?.id).toBe(AMBIENT_TRACK);
+ expect(primaryTrackForKind('character', EFFECTIVE)?.id).toBe(WALK_TRACK);
+ expect(primaryTrackForKind('place', EFFECTIVE)?.id).toBe(AMBIENT_TRACK);
+ expect(primaryTrackForKind('object', EFFECTIVE)?.id).toBe(AMBIENT_TRACK);
+ expect(primaryTrackForKind('props', EFFECTIVE)?.id).toBe(AMBIENT_TRACK);
// A short action a record can't publish off alone is never the primary.
- expect(primaryTrackForKind('character')?.id).not.toBe(SCANNER_TRACK);
+ expect(primaryTrackForKind('character', EFFECTIVE)?.id).not.toBe(SCANNER_TRACK);
// Absent/unknown answers null rather than defaulting to a kind.
- expect(primaryTrackForKind('nope')).toBeNull();
- expect(primaryTrackForKind('')).toBeNull();
- expect(primaryTrackForKind(undefined)).toBeNull();
+ expect(primaryTrackForKind('nope', EFFECTIVE)).toBeNull();
+ expect(primaryTrackForKind('', EFFECTIVE)).toBeNull();
+ expect(primaryTrackForKind(undefined, EFFECTIVE)).toBeNull();
});
});
@@ -262,7 +296,7 @@ describe('getAnimationTrack — absent vs unrecognized', () => {
// The sentinel rule: "not set" resolves to the default; "set to something
// this build does not know" is an error. Silently handing back walk's 6–16
// would reject a legitimate 4-frame action for reasons nothing explains.
- expect(getAnimationTrack(SCANNER_TRACK).id).toBe(SCANNER_TRACK);
+ expect(effectiveTrack(SCANNER_TRACK).id).toBe(SCANNER_TRACK);
expect(() => getAnimationTrack('unknown')).toThrow(/Unknown animation track 'unknown'/);
});
@@ -327,9 +361,9 @@ describe('directionality and record-kind support (#3017)', () => {
});
it('admits ambient loops for non-character sprite kinds', () => {
- expect(tracksForKind('character').map((r) => r.id)).toEqual([WALK_TRACK, SCANNER_TRACK]);
+ expect(tracksForKind('character', EFFECTIVE).map((r) => r.id)).toEqual([WALK_TRACK, SCANNER_TRACK]);
for (const kind of ['place', 'object', 'props']) {
- expect(tracksForKind(kind).map((r) => r.id), `${kind} carries the ambient loop`).toEqual([AMBIENT_TRACK]);
+ expect(tracksForKind(kind, EFFECTIVE).map((r) => r.id), `${kind} carries the ambient loop`).toEqual([AMBIENT_TRACK]);
}
});
@@ -341,8 +375,8 @@ describe('directionality and record-kind support (#3017)', () => {
// as the baffling "No animation track applies to character records".
// Cross-checked here, where reaching another module is fine — the same
// place the client-mirror parity check lives.
- for (const id of ANIMATION_TRACK_IDS) {
- for (const kind of ANIMATION_TRACKS[id].kinds) {
+ for (const id of getEffectiveAnimationTrackIds()) {
+ for (const kind of EFFECTIVE[id].kinds) {
expect(SPRITE_RECORD_KINDS, `${id}.kinds names an unknown record kind '${kind}'`).toContain(kind);
}
}
@@ -369,17 +403,17 @@ describe('per-track clamps', () => {
});
it('clamps scanner values against scanner bounds', () => {
- expect(clampTrackFrameCount(99, SCANNER_TRACK)).toBe(8);
- expect(clampTrackFrameCount(-1, SCANNER_TRACK)).toBe(2);
- expect(clampTrackFps(99, SCANNER_TRACK)).toBe(12);
- expect(clampTrackFps(-1, SCANNER_TRACK)).toBe(2);
+ expect(clampTrackFrameCount(99, SCANNER_TRACK, EFFECTIVE)).toBe(8);
+ expect(clampTrackFrameCount(-1, SCANNER_TRACK, EFFECTIVE)).toBe(2);
+ expect(clampTrackFps(99, SCANNER_TRACK, EFFECTIVE)).toBe(12);
+ expect(clampTrackFps(-1, SCANNER_TRACK, EFFECTIVE)).toBe(2);
});
it('clamps ambient values against the ambient range', () => {
- expect(clampTrackFrameCount(99, AMBIENT_TRACK)).toBe(6);
- expect(clampTrackFrameCount(-1, AMBIENT_TRACK)).toBe(2);
- expect(clampTrackFps(99, AMBIENT_TRACK)).toBe(12);
- expect(clampTrackFps(-1, AMBIENT_TRACK)).toBe(2);
+ expect(clampTrackFrameCount(99, AMBIENT_TRACK, EFFECTIVE)).toBe(6);
+ expect(clampTrackFrameCount(-1, AMBIENT_TRACK, EFFECTIVE)).toBe(2);
+ expect(clampTrackFps(99, AMBIENT_TRACK, EFFECTIVE)).toBe(12);
+ expect(clampTrackFps(-1, AMBIENT_TRACK, EFFECTIVE)).toBe(2);
});
});
@@ -426,6 +460,11 @@ describe('sharp-free leaf property', () => {
it.each([
['the request-validation graph', join(SERVER_DIR, 'lib', 'validation.js')],
['animationTracks.js', join(SPRITES_DIR, 'animationTracks.js')],
+ // #3152: the store sits BETWEEN the leaf registry and validation.js — every
+ // sprite Zod range now resolves through it — so if it ever reached sharp, the
+ // whole split collapses at its narrowest point. It does file I/O (which the
+ // leaf below may not), but native image deps are still forbidden.
+ ['animationTrackStore.js', join(SPRITES_DIR, 'animationTrackStore.js')],
['walkBounds.js', join(SPRITES_DIR, 'walkBounds.js')],
['animationTargets.js', join(SPRITES_DIR, 'animationTargets.js')],
// #3016: the atlas grid is the ONE definition of a column span, shared by
@@ -444,6 +483,19 @@ describe('sharp-free leaf property', () => {
expect(staticImportSpecifiers(join(SPRITES_DIR, 'animationTracks.js'))).toEqual([]);
});
+ it('runs the store→leaf dependency ONE way (#3152)', () => {
+ // The store does file I/O; the leaf may not. So the store imports the leaf and
+ // never the reverse — the assertion above already forbids ANY import from the
+ // leaf, but state the direction explicitly, because "move the merge into
+ // animationTracks.js" is the natural-looking refactor that would drag fs into
+ // the request-validation graph and break the split this whole describe exists
+ // to protect.
+ expect(staticImportSpecifiers(join(SPRITES_DIR, 'animationTrackStore.js')))
+ .toContain('./animationTracks.js');
+ const leafClosure = staticImportClosure(join(SPRITES_DIR, 'animationTracks.js'));
+ expect([...leafClosure.files]).not.toContain(join(SPRITES_DIR, 'animationTrackStore.js'));
+ });
+
it('actually walks the graph (positive control — the guard is not vacuous)', () => {
// Three ways the assertions above could pass for the wrong reason: the walk
// never follows relative imports, it never records bare packages, or an
diff --git a/server/services/sprites/atlas.js b/server/services/sprites/atlas.js
index 447aab45c9..e54d543f3d 100644
--- a/server/services/sprites/atlas.js
+++ b/server/services/sprites/atlas.js
@@ -51,9 +51,17 @@ import {
} from './walkPostprocess.js';
import { ATLAS_IDLE_COLUMN } from './walkBounds.js';
import {
- WALK_TRACK, SCANNER_TRACK, AMBIENT_TRACK, ANIMATION_TRACK_IDS,
+ WALK_TRACK, SCANNER_TRACK, AMBIENT_TRACK,
kindSupportsTrack, getAnimationTrack, primaryTrackForKind,
} from './animationTracks.js';
+// #3152 — `scanner` and `ambient` are now STORED rows, not compiled ones, so the
+// two bespoke evidence chains below (which still name them, because existing
+// on-disk sets carry their exact `setKind` strings) must resolve through the
+// effective table or every lookup would throw as unknown. The span-order sweep
+// likewise walks the effective id list, so a user's track gets a stable span.
+import {
+ getEffectiveAnimationTracks, getEffectiveAnimationTrackIds,
+} from './animationTrackStore.js';
import {
buildAtlasGrid, resolveTrackUniformity, compiledGridUpToDate, trackDirections,
} from './atlasGrid.js';
@@ -272,7 +280,7 @@ export async function validateForCompile(recordId) {
// (`primaryTrackForKind`) rather than spelled as "ambient-and-not-walk", so it
// is the same definition `spriteRuntimeContractSchema` requires a frame count
// for; the two used to agree only by coincidence.
- if (recordForTrack && primaryTrackForKind(recordForTrack.kind)?.id === AMBIENT_TRACK) {
+ if (recordForTrack && primaryTrackForKind(recordForTrack.kind, getEffectiveAnimationTracks())?.id === AMBIENT_TRACK) {
return validateAmbientForCompile(recordId, recordForTrack);
}
// Every hashed input is read exactly once: verify the bytes in memory and
@@ -388,7 +396,7 @@ export async function validateForCompile(recordId) {
// `setKind` comes from the registry row (#3136) rather than a literal, so
// the track that WRITES the set and the compiler that re-verifies it share
// one definition — the same single-source rule the contract fields follow.
- if (scannerSet.kind !== getAnimationTrack(SCANNER_TRACK).setKind || scannerSet.track !== SCANNER_TRACK
+ if (scannerSet.kind !== getAnimationTrack(SCANNER_TRACK, getEffectiveAnimationTracks()).setKind || scannerSet.track !== SCANNER_TRACK
|| scannerSet.status !== 'final' || scannerSet.characterId !== recordId
|| JSON.stringify(scannerSet.directionOrder) !== JSON.stringify(SPRITE_DIRECTIONS)) {
throw compileError('Scanner set manifest is not a finalized directional scanner set');
@@ -452,7 +460,7 @@ export async function validateForCompile(recordId) {
// Registration order, so the compiled grid's span order is stable regardless
// of the order the rows happened to be collected in.
- const tracks = ANIMATION_TRACK_IDS
+ const tracks = getEffectiveAnimationTrackIds()
.filter((id) => trackRows[id]?.length)
.map((id) => resolveTrackUniformity(id, trackRows[id], {
error: compileError,
@@ -525,7 +533,7 @@ async function validateAmbientForCompile(recordId, record) {
} catch {
throw compileError('Ambient set manifest is unreadable');
}
- if (ambientSet.kind !== getAnimationTrack(AMBIENT_TRACK).setKind || ambientSet.track !== AMBIENT_TRACK
+ if (ambientSet.kind !== getAnimationTrack(AMBIENT_TRACK, getEffectiveAnimationTracks()).setKind || ambientSet.track !== AMBIENT_TRACK
|| ambientSet.status !== 'final' || ambientSet.characterId !== recordId
|| JSON.stringify(ambientSet.directionOrder) !== JSON.stringify(['south'])) {
throw compileError('Ambient set manifest is not a finalized single-row ambient set');
diff --git a/server/services/sprites/atlas.test.js b/server/services/sprites/atlas.test.js
index 33c3629d5d..ad6331e842 100644
--- a/server/services/sprites/atlas.test.js
+++ b/server/services/sprites/atlas.test.js
@@ -7,12 +7,13 @@
* with a correct hash chain.
*/
-import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';
+import { describe, it, expect, beforeEach, afterEach, afterAll, vi } from 'vitest';
import { mkdtempSync, rmSync } from 'fs';
import { tmpdir } from 'os';
-import { join } from 'path';
+import { dirname, join } from 'path';
+import { fileURLToPath } from 'url';
import sharp from 'sharp';
-import { mkdir, writeFile, readFile } from 'fs/promises';
+import { mkdir, writeFile, readFile, rm } from 'fs/promises';
import { createHash } from 'crypto';
import { lockAllAnchors as lockAllAnchorsFixture, placeCandidate, trackSpan as fullSpan } from './spriteTestFixtures.js';
@@ -46,6 +47,9 @@ const { SPRITE_DIRECTIONS } = await import('./prompts.js');
const { WALK_PHASES, walkPhaseLabels, WALK_FPS } = await import('./walkPostprocess.js');
const { buildAtlasGrid, compiledGridUpToDate } = await import('./atlasGrid.js');
const { getAnimationTrack, SCANNER_TRACK, AMBIENT_TRACK } = await import('./animationTracks.js');
+const { __resetAnimationTrackStore } = await import('./animationTrackStore.js');
+
+const SPRITES_DIR = dirname(fileURLToPath(import.meta.url));
let seq = 0;
const newId = () => `atlas-char-${++seq}`;
@@ -325,6 +329,67 @@ describe('compileAtlas', () => {
}
});
+ // #3152's stated "regression that matters": `scanner`/`ambient` stopped being
+ // compiled rows and became rows in `data/sprites/animation-tracks.json`. The
+ // cases above prove the PRE-migration state compiles (no store file → the
+ // data.reference seed answers). These two prove the POST-migration state does
+ // too, with a real user-owned store on disk — which is the shape every upgraded
+ // install actually runs, and the one where a broken store→registry hand-off
+ // would surface as "unknown animation track 'scanner'" on a record that
+ // compiled fine yesterday.
+ describe('after migration 211 materializes the user-owned store (#3152)', () => {
+ // 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.
+ 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);
+ __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 });
+ __resetAnimationTrackStore();
+ });
+
+ it('still compiles an approved scanner set beside the walk span', async () => {
+ const id = newId();
+ await lockAllAnchors(id);
+ await buildFinalizedWalkSet(id, { frameCount: 12, fps: 10 });
+ await buildFinalizedScannerSet(id);
+ await installUserStore();
+
+ const result = await compileAtlas(id);
+ const manifest = JSON.parse(await readFile(join(TEST_ROOT, 'sprites', id, result.manifestPath), 'utf8'));
+ // Identical geometry to the compiled-row era: the span order, the column
+ // labels, and the frame count all still resolve from the (now stored) row.
+ expect(manifest.geometry.columns).toEqual([
+ 'idle', ...walkPhaseLabels(12), 'scanner-00', 'scanner-01', 'scanner-02', 'scanner-03',
+ ]);
+ expect(manifest.geometry.tracks.scanner).toMatchObject({ start: 13, count: 4, rows: 8 });
+ expect(manifest.geometry.scannerFrameCount).toBe(4);
+ });
+
+ it('still compiles an approved ambient loop for a place record', async () => {
+ const id = await finalizedAmbientPlace();
+ await installUserStore();
+
+ const result = await compileAtlas(id);
+ const manifest = JSON.parse(await readFile(join(TEST_ROOT, 'sprites', id, result.manifestPath), 'utf8'));
+ // The ambient dispatch runs off `primaryTrackForKind('place')`, which is
+ // now answered by a STORED row — a compiled-table lookup there returns null
+ // and silently routes a place into the walk evidence chain, failing with
+ // "No finalized walk set" on a record that has no walk at all.
+ expect(manifest.kind).toBe('reviewed-ambient-set-runtime-atlas');
+ expect(manifest.geometry).toMatchObject({
+ columns: ['idle', 'ambient-00', 'ambient-01', 'ambient-02'],
+ ambientFrameCount: 3,
+ });
+ });
+ });
+
it('compiles the 9×8 player atlas with full provenance and a current pointer', async () => {
const id = await finalizedCharacter();
const result = await compileAtlas(id);
diff --git a/server/services/sprites/atlasGrid.js b/server/services/sprites/atlasGrid.js
index fc60b08233..73fbcd00d5 100644
--- a/server/services/sprites/atlasGrid.js
+++ b/server/services/sprites/atlasGrid.js
@@ -51,19 +51,26 @@
* defaulting to the grid's row count is what keeps existing atlases idempotent
* instead of condemning them to recompile their pixels forever.
*
- * **Only ONE track is registered today** (`walk`). The multi-track paths below
- * are proven in `atlasGrid.test.js` against a synthetic REGISTRY TABLE rather
- * than by shipping a second track's artwork. The registry table is the
+ * **Only ONE track is COMPILED IN** (`walk`); every other row — including the
+ * seeded `scanner`/`ambient` — comes from the user-defined store (#3152), which
+ * is why the default `tracks` table below is `getEffectiveAnimationTracks()`
+ * rather than the compiled constant. The multi-track paths are still proven in
+ * `atlasGrid.test.js` against a synthetic REGISTRY TABLE rather than against
+ * whatever a given install happens to have stored: the registry table is the
* injection seam throughout — the same idiom `assertAnimationTrackRows(tracks)`
* uses — so a synthetic row flows through exactly the lookup, ordering and
- * unknown-id boundary a real one would. Shipping a real second track is #3018's
- * job, and it should land as a registry ROW plus its pipeline, with no shape
- * change here.
+ * unknown-id boundary a real one would, and the suite doesn't depend on a user's
+ * data.
*/
-import {
- ANIMATION_TRACKS, WALK_TRACK, getAnimationTrack, trackRowCount,
-} from './animationTracks.js';
+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
+// 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.
+import { getEffectiveAnimationTracks } from './animationTrackStore.js';
import { ATLAS_IDLE_COLUMN, ATLAS_SCANNER_COLUMN, walkPhaseLabels } from './walkBounds.js';
import { SPRITE_DIRECTIONS } from './prompts.js';
import { canonicalStringify } from '../../lib/objects.js';
@@ -93,7 +100,7 @@ export const ATLAS_DEFAULT_ROWS = SPRITE_DIRECTIONS.length;
* manifest, and `reference.js`'s eight anchors, all still hardcode the facing
* list, and generalizing them is the job of the track that needs it (#3045).
*/
-export function trackDirections(trackId, directions = SPRITE_DIRECTIONS, tracks = ANIMATION_TRACKS) {
+export function trackDirections(trackId, directions = SPRITE_DIRECTIONS, tracks = getEffectiveAnimationTracks()) {
if (!Array.isArray(directions) || !directions.length) {
throw new Error(`Atlas track '${trackId}' needs a non-empty direction list`);
}
@@ -149,7 +156,7 @@ export function trackColumnLabels(trackId, frameCount) {
* proven against a synthetic table without a private lookup that would bypass
* that boundary.
*/
-export function buildAtlasGrid(specs, tracks = ANIMATION_TRACKS) {
+export function buildAtlasGrid(specs, tracks = getEffectiveAnimationTracks()) {
if (!Array.isArray(specs) || !specs.length) {
throw new Error('Atlas grid needs at least one animation track');
}
@@ -425,7 +432,7 @@ export function compiledGridUpToDate(current, expected) {
* column labels, which `buildAtlasGrid` derives itself so the two can't disagree.
*/
export function resolveTrackUniformity(trackId, rows, {
- tracks = ANIMATION_TRACKS,
+ tracks = getEffectiveAnimationTracks(),
trackRow = getAnimationTrack(trackId, tracks),
error = (message) => new Error(message),
defaultFps = trackRow.defaultFps,
diff --git a/server/services/sprites/reference.js b/server/services/sprites/reference.js
index 606807072f..d1d8fa746a 100644
--- a/server/services/sprites/reference.js
+++ b/server/services/sprites/reference.js
@@ -46,8 +46,14 @@ import {
} from './prompts.js';
import { pickChromaKey, keyProximityWarning, CHROMA_KEY_HEXES, DEFAULT_CHROMA_KEY } from './chromaKey.js';
import {
- WALK_TRACK, ANIMATION_TRACK_IDS, kindSupportsTrack, tracksForKind,
+ WALK_TRACK, kindSupportsTrack, tracksForKind,
} from './animationTracks.js';
+// #3152 — the gates below ask the EFFECTIVE table (compiled `walk` + the
+// user-defined store) so a record kind a user's own track admits gets the same
+// animation path a seeded one does.
+import {
+ getEffectiveAnimationTracks, getEffectiveAnimationTrackIds,
+} from './animationTrackStore.js';
import {
analyzeForeground, paletteFromAnalysis, normalizeFromAnalysis, recompositeOnKey,
} from './normalize.js';
@@ -189,9 +195,10 @@ function seedManifest(recordId, { directional = true } = {}) {
export async function requireTrack(recordId, trackId = null) {
const record = await getRecord(recordId);
if (!record) throw new ServerError('Sprite record not found', { status: 404, code: 'NOT_FOUND' });
+ const effectiveTracks = getEffectiveAnimationTracks();
const supported = trackId
- ? kindSupportsTrack(record.kind, trackId)
- : tracksForKind(record.kind).length > 0;
+ ? kindSupportsTrack(record.kind, trackId, effectiveTracks)
+ : tracksForKind(record.kind, effectiveTracks).length > 0;
if (!supported) {
// The walk gate keeps its historical message and code — callers (and
// reference.test.js) match on NOT_A_CHARACTER, and walk is character-only,
@@ -200,7 +207,7 @@ export async function requireTrack(recordId, trackId = null) {
throw new ServerError('Reference workflow applies to character records only', { status: 400, code: 'NOT_A_CHARACTER' });
}
throw new ServerError(
- `No animation track applies to ${record.kind} records — the registered tracks are: ${ANIMATION_TRACK_IDS.join(', ')}`,
+ `No animation track applies to ${record.kind} records — the registered tracks are: ${getEffectiveAnimationTrackIds().join(', ')}`,
{ status: 400, code: 'NOT_ANIMATABLE' },
);
}
@@ -366,7 +373,7 @@ export function startReferenceGeneration(recordId, body, upload = null) {
async function startReferenceGenerationImpl(recordId, body, upload = null) {
const record = await requireTrack(recordId);
- const directional = kindSupportsTrack(record.kind, WALK_TRACK);
+ const directional = kindSupportsTrack(record.kind, WALK_TRACK, getEffectiveAnimationTracks());
const manifest = (await loadManifest(recordId)) || seedManifest(recordId, { directional });
const target = body.target;
if (!directional && target !== 'main') {
@@ -663,7 +670,7 @@ export async function listReferenceSources() {
// Same question requireCharacter asks — a reference set exists only for a
// kind that carries the walk track — so a row admitting another kind is
// picked up here too instead of this list silently staying character-only.
- if (r.deleted || !kindSupportsTrack(r.kind, WALK_TRACK)) continue;
+ if (r.deleted || !kindSupportsTrack(r.kind, WALK_TRACK, getEffectiveAnimationTracks())) continue;
const manifest = await loadManifest(r.id);
// Same picker resolveSourceReference uses, so the advertised image is
// exactly the one a seed will attach.
@@ -700,7 +707,7 @@ export async function listSpriteThumbnails() {
// Registry-driven for the same reason as listReferenceSources: a locked
// main reference is a property of carrying the walk track, not of the
// literal kind name.
- if (tracksForKind(r.kind).length) {
+ if (tracksForKind(r.kind, getEffectiveAnimationTracks()).length) {
const manifest = await loadManifest(r.id);
const main = manifest?.mainReference;
if (main?.locked && main.path) return { id: r.id, path: main.path };
@@ -980,7 +987,7 @@ async function unlockReferenceTurnaroundImpl(recordId) {
async function lockReferenceImpl(recordId, { target, candidate, acceptClipRisk = false }) {
const record = await requireTrack(recordId);
- const directional = kindSupportsTrack(record.kind, WALK_TRACK);
+ const directional = kindSupportsTrack(record.kind, WALK_TRACK, getEffectiveAnimationTracks());
// Seed on demand — a candidate may predate the manifest (e.g. files placed
// by an import or a crash-recovered tree); the lock is what makes it real.
const manifest = (await loadManifest(recordId)) || seedManifest(recordId, { directional });
diff --git a/server/services/sprites/spriteTestFixtures.js b/server/services/sprites/spriteTestFixtures.js
index d9dd844714..b8e5e1fd23 100644
--- a/server/services/sprites/spriteTestFixtures.js
+++ b/server/services/sprites/spriteTestFixtures.js
@@ -114,4 +114,11 @@ export const AMBIENT_TRACK_ROW = Object.freeze({
setKind: 'finalized-single-row-ambient-set',
finalErrorCode: 'AMBIENT_SET_FINAL',
standaloneContract: true,
+ // #3152 — `builtin: true` because this fixture stands in for a COMPILED row in
+ // the injected-table tests: those exercise the readers' row-handling, not the
+ // store's loading, and a `builtin: false` row would additionally have to carry
+ // a `promptTemplate` (which `assertAnimationTrackRows` requires of a stored row)
+ // for reasons that have nothing to do with what they assert. The store's own
+ // user-defined-row shape is exercised in `animationTrackStore.test.js`.
+ builtin: true,
});
diff --git a/server/services/sprites/trackPrompts.js b/server/services/sprites/trackPrompts.js
index 3c2052937c..a65e0c979f 100644
--- a/server/services/sprites/trackPrompts.js
+++ b/server/services/sprites/trackPrompts.js
@@ -1,26 +1,45 @@
/**
- * Per-track image-to-video prompt resolution (#3136).
+ * Per-track image-to-video prompt resolution (#3136, #3152).
*
* The generic animation workflow needs ONE call that answers "what do I send the
- * provider for this track?" — because that question is the last thing that was
- * still track-specific code rather than track-specific data. Today the answer is
- * a lookup into the builders `prompts.js` already owns; when a user-defined
- * track store lands, an unknown id resolves to that track's stored
- * `promptTemplate` here instead of throwing, and no caller changes.
- *
- * Kept separate from `prompts.js` deliberately: that module is the pure catalog
- * of prompt TEXT (and its tests assert the exact wording of each stage), while
- * this is the small dispatch layer over it. Folding the dispatch in would make
- * every prompt-wording test also a routing test.
- *
- * Pure — no I/O, no state.
+ * provider for this track?" — because that question was the last thing that was
+ * still track-specific code rather than track-specific data. #3152 made it fully
+ * data: a track resolves through the compiled builder when it is the built-in
+ * `walk`, and through its own stored `promptTemplate` when it came from the
+ * user-defined store. A genuinely unknown id — neither compiled nor stored — still
+ * throws, which is the same unknown-id boundary `getAnimationTrack` draws and for
+ * the same reason: a mis-keyed track that silently sent the walk prompt would
+ * render a gait loop and pass every later check, since nothing downstream re-reads
+ * what was asked for.
+ *
+ * **Exactly one prompt source per track, never two.** The dispatch below keys on
+ * `row.builtin` rather than trying the compiled table first and the template
+ * second. A precedence chain would leave `scanner` with two definitions of its
+ * wording — the compiled `buildScannerPrompt` and the seeded template — and the
+ * seed is the one a user edits, so the edit would silently do nothing. Instead the
+ * seeded rows resolve through their templates, and `trackPrompts.test.js` pins
+ * those templates byte-for-byte against the compiled builders that produced them,
+ * so the migration is provably a no-op on the wire. The compiled
+ * `buildScannerPrompt`/`buildAmbientVideoPrompt` stay exported from `prompts.js` as
+ * that pinned reference (and for `prompts.test.js`'s wording assertions), not as a
+ * live fallback.
+ *
+ * Kept separate from `prompts.js` deliberately: that module is the pure catalog of
+ * prompt TEXT (and its tests assert the exact wording of each stage), while this is
+ * the small dispatch layer over it. Folding the dispatch in would make every
+ * prompt-wording test also a routing test.
+ *
+ * Pure apart from the store read the effective registry performs (a cached
+ * `readFileSync` of one small config — see `animationTrackStore.js`).
*/
-import { buildWalkVideoPrompt, buildScannerPrompt, buildAmbientVideoPrompt } from './prompts.js';
-import { WALK_TRACK, SCANNER_TRACK, AMBIENT_TRACK } from './animationTracks.js';
+import { buildWalkVideoPrompt, correctionClause, keyColorPhrase } from './prompts.js';
+import { WALK_TRACK } from './animationTracks.js';
+import { getEffectiveAnimationTracks } from './animationTrackStore.js';
/**
- * The i2v prompt builder for each track compiled into this build.
+ * The i2v prompt builder for each track compiled into this build — `walk` alone
+ * since #3152 moved `scanner` and `ambient` into the store as seed data.
*
* Every builder takes the same superset argument object and reads only what it
* needs, so the dispatch below passes one shape and never has to know which
@@ -28,30 +47,79 @@ import { WALK_TRACK, SCANNER_TRACK, AMBIENT_TRACK } from './animationTracks.js';
*/
const TRACK_VIDEO_PROMPTS = Object.freeze({
[WALK_TRACK]: buildWalkVideoPrompt,
- [SCANNER_TRACK]: buildScannerPrompt,
- [AMBIENT_TRACK]: buildAmbientVideoPrompt,
});
+/**
+ * The placeholders a stored `promptTemplate` may interpolate.
+ *
+ * `chromaKey` is the raw hex and `chromaKeyPhrase` is the named form
+ * ("magenta (#FF00FF)") — BOTH, because the two seeded templates disagree: the
+ * scanner wording embeds the bare hex and the ambient wording embeds the phrase,
+ * and collapsing them to one variable would change one of the two prompts on the
+ * wire. A user's template picks whichever reads better in its sentence.
+ *
+ * `correctionPrompt` is deliberately NOT a placeholder: its clause is appended
+ * last by every builder (`correctionClause`), because a correction that reads as an
+ * override of the base wording is the whole contract — a template that
+ * interpolated it mid-sentence would bury it.
+ */
+const templateVariables = ({ name, kind, direction, chromaKey }) => ({
+ name: name ?? '',
+ kind: kind ?? '',
+ direction: direction ?? '',
+ chromaKey: chromaKey ?? '',
+ chromaKeyPhrase: keyColorPhrase(chromaKey),
+});
+
+/**
+ * Interpolate `{{variable}}` placeholders in a stored template.
+ *
+ * An UNKNOWN placeholder is left literal rather than replaced with an empty
+ * string: the user authored it, the prompt is shown back to them (the sprite asset
+ * preview rebuilds provenance through this same call), and a visible `{{drection}}`
+ * is a typo they can find and fix, where a silently-dropped clause reads as the
+ * model ignoring their instruction. Whitespace inside the braces is tolerated.
+ */
+export function renderPromptTemplate(template, args) {
+ const vars = templateVariables(args || {});
+ return String(template).replace(/\{\{\s*([a-zA-Z][a-zA-Z0-9_]*)\s*\}\}/g, (match, key) => (
+ Object.prototype.hasOwnProperty.call(vars, key) ? vars[key] : match
+ ));
+}
+
/**
* The image-to-video instruction for one track's render.
*
- * Throws on an unregistered track rather than falling back to walk's wording —
- * the same unknown-id boundary `getAnimationTrack` draws, and for the same
- * reason: a mis-keyed track that silently sent the walk prompt would render a
- * gait loop and pass every later check, since nothing downstream re-reads what
- * was asked for.
+ * Throws on a track the effective registry doesn't know — see the header.
*/
export function buildTrackVideoPrompt(trackId, args) {
- const build = TRACK_VIDEO_PROMPTS[trackId];
- if (!build) {
+ const tracks = getEffectiveAnimationTracks();
+ const row = tracks[trackId];
+ if (!row) {
throw new Error(
`No image-to-video prompt is registered for animation track '${String(trackId)}' `
- + `— known tracks: ${Object.keys(TRACK_VIDEO_PROMPTS).join(', ')}.`,
+ + `— known tracks: ${Object.keys(tracks).join(', ')}.`,
);
}
+ if (!row.builtin) {
+ return renderPromptTemplate(row.promptTemplate, args)
+ + correctionClause(args?.correctionPrompt, 'source image');
+ }
+ const build = TRACK_VIDEO_PROMPTS[trackId];
+ // A builtin row with no compiled builder is unreachable today (`walk` is the
+ // only one) but would otherwise fall through as `undefined(args)` — report the
+ // registry/code mismatch by name instead.
+ if (!build) {
+ throw new Error(`Builtin animation track '${String(trackId)}' has no compiled image-to-video prompt builder.`);
+ }
return build(args);
}
-/** True when `trackId` has a registered i2v prompt builder. */
-export const hasTrackVideoPrompt = (trackId) =>
- Object.prototype.hasOwnProperty.call(TRACK_VIDEO_PROMPTS, trackId);
+/** 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;
+};
diff --git a/server/services/sprites/trackPrompts.test.js b/server/services/sprites/trackPrompts.test.js
new file mode 100644
index 0000000000..9c667eaf59
--- /dev/null
+++ b/server/services/sprites/trackPrompts.test.js
@@ -0,0 +1,202 @@
+/**
+ * Per-track i2v prompt resolution (#3136, #3152).
+ *
+ * Two things are proven here, and the first is the load-bearing one:
+ *
+ * 1. **The seeded templates are byte-identical to the compiled builders they
+ * replaced.** #3152 demoted `scanner` and `ambient` from compiled rows to store
+ * rows, which moved their wording from `prompts.js` code into a
+ * `promptTemplate` string. That is only a safe refactor if the bytes sent to
+ * the provider are unchanged — a template that dropped a clause, mangled a
+ * placeholder, or reordered the correction note would render a subtly different
+ * animation and pass every other check, because nothing downstream re-reads
+ * what was asked for. So this compares `buildTrackVideoPrompt` (template path)
+ * against `buildScannerPrompt`/`buildAmbientVideoPrompt` (the compiled builders
+ * kept exported precisely as this reference) across the argument space that
+ * varies the output: chroma key form, facing, record kind, and the correction
+ * clause. `prompts.test.js` still pins the builders' own wording, so the two
+ * suites together pin the templates to reviewed text rather than to themselves.
+ *
+ * 2. **A user-defined row resolves through its own template**, with the
+ * placeholder and unknown-track rules the resolver promises.
+ */
+
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-track-prompts-test-'));
+
+vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ Object.assign(actual.PATHS, { data: TEST_ROOT, sprites: join(TEST_ROOT, 'sprites') });
+ return actual;
+});
+
+const {
+ buildTrackVideoPrompt, hasTrackVideoPrompt, renderPromptTemplate,
+} = await import('./trackPrompts.js');
+const {
+ buildWalkVideoPrompt, buildScannerPrompt, buildAmbientVideoPrompt,
+} = await import('./prompts.js');
+const { WALK_TRACK, SCANNER_TRACK, AMBIENT_TRACK } = await import('./animationTracks.js');
+const {
+ __resetAnimationTrackStore, animationTrackStorePath, ANIMATION_TRACK_STORE_SCHEMA_VERSION,
+} = await import('./animationTrackStore.js');
+
+const STORE_PATH = animationTrackStorePath();
+
+const writeTracks = (tracks) => {
+ mkdirSync(join(TEST_ROOT, 'sprites'), { recursive: true });
+ writeFileSync(STORE_PATH, JSON.stringify({
+ schemaVersion: ANIMATION_TRACK_STORE_SCHEMA_VERSION, tracks,
+ }, null, 2));
+};
+
+beforeEach(() => {
+ rmSync(STORE_PATH, { force: true });
+ __resetAnimationTrackStore();
+});
+afterAll(() => rmSync(TEST_ROOT, { recursive: true, force: true }));
+
+// The argument space that actually varies these prompts. Each seeded template
+// interpolates a DIFFERENT chroma form (scanner embeds the bare hex, ambient the
+// named phrase), so both keys are exercised — a template that used the wrong
+// variable would change one prompt on the wire and this is what catches it.
+const ARG_CASES = [
+ { label: 'magenta key', args: { name: 'Placeholder Hero', kind: 'character', direction: 'east', chromaKey: '#FF00FF' } },
+ { label: 'green key', args: { name: 'Example Willow', kind: 'place', direction: 'south', chromaKey: '#00FF00' } },
+ {
+ label: 'with a correction note',
+ args: {
+ name: 'Placeholder Hero', kind: 'character', direction: 'north-west', chromaKey: '#FF00FF',
+ correctionPrompt: 'the sweep never returns to the start pose',
+ },
+ },
+ {
+ // A whitespace-only note must leave the prompt byte-identical to a blind
+ // regenerate — the hard contract `correctionClause` promises, which the
+ // template path has to inherit rather than re-implement.
+ label: 'with a blank correction note',
+ args: { name: 'Example Willow', kind: 'object', direction: 'south', chromaKey: '#00FF00', correctionPrompt: ' ' },
+ },
+ {
+ // An unrecognized chroma hex falls back inside `keyColorPhrase`; both paths
+ // must make the same fallback or the ambient wording diverges.
+ label: 'with an unnamed chroma hex',
+ args: { name: 'Example Willow', kind: 'place', direction: 'south', chromaKey: '#123456' },
+ },
+];
+
+describe('the seeded templates reproduce the compiled builders exactly (#3152)', () => {
+ it.each(ARG_CASES)('scanner — $label', ({ args }) => {
+ expect(buildTrackVideoPrompt(SCANNER_TRACK, args)).toBe(buildScannerPrompt(args));
+ });
+
+ it.each(ARG_CASES)('ambient — $label', ({ args }) => {
+ expect(buildTrackVideoPrompt(AMBIENT_TRACK, args)).toBe(buildAmbientVideoPrompt(args));
+ });
+
+ it('is not vacuous — the two tracks\' prompts genuinely differ', () => {
+ // Guards the assertions above against the failure mode where every builder
+ // returns the same string (or an empty one) and equality proves nothing.
+ const args = ARG_CASES[0].args;
+ const scanner = buildTrackVideoPrompt(SCANNER_TRACK, args);
+ const ambient = buildTrackVideoPrompt(AMBIENT_TRACK, args);
+ expect(scanner).not.toBe(ambient);
+ expect(scanner).toContain('scanner');
+ expect(ambient).toContain('ambient loop');
+ expect(scanner.length).toBeGreaterThan(100);
+ });
+
+ it('routes walk through its COMPILED builder, not a template', () => {
+ // Walk is the one built-in, so its wording must still come from code — a
+ // stored template shadowing it would move the mandatory baseline's prompt out
+ // of the reviewed catalog.
+ const args = ARG_CASES[0].args;
+ expect(buildTrackVideoPrompt(WALK_TRACK, args)).toBe(buildWalkVideoPrompt(args));
+ });
+});
+
+describe('a user-defined row resolves through its own template', () => {
+ const CUSTOM = {
+ 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]);
+ expect(buildTrackVideoPrompt('jetpack-burst', {
+ name: 'Placeholder Hero', kind: 'character', direction: 'east', chromaKey: '#FF00FF',
+ })).toBe(
+ 'Animate Placeholder Hero (character) firing a jetpack burst while facing east. '
+ + 'Matte: magenta (#FF00FF) / raw #FF00FF.',
+ );
+ });
+
+ it('appends the correction clause LAST, like every compiled builder', () => {
+ // Not a placeholder on purpose: a correction reads as an override of the base
+ // wording, so a template that interpolated it mid-sentence would bury it.
+ writeTracks([CUSTOM]);
+ const prompt = buildTrackVideoPrompt('jetpack-burst', {
+ name: 'Placeholder Hero', kind: 'character', direction: 'east', chromaKey: '#FF00FF',
+ correctionPrompt: 'more flame, less smoke',
+ });
+ expect(prompt.endsWith(
+ ' Important correction — apply this over the attached source image: more flame, less smoke',
+ )).toBe(true);
+ });
+
+ it('reports a stored row as having a prompt, and an unknown id as not', () => {
+ writeTracks([CUSTOM]);
+ expect(hasTrackVideoPrompt('jetpack-burst')).toBe(true);
+ expect(hasTrackVideoPrompt(WALK_TRACK)).toBe(true);
+ expect(hasTrackVideoPrompt('never-registered')).toBe(false);
+ });
+
+ it('throws for a track neither compiled nor stored, naming what IS known', () => {
+ // The unknown-id boundary: silently sending walk's wording would render a
+ // gait loop that passes every later check.
+ writeTracks([CUSTOM]);
+ expect(() => buildTrackVideoPrompt('never-registered', {})).toThrow(/never-registered/);
+ expect(() => buildTrackVideoPrompt('never-registered', {})).toThrow(/jetpack-burst/);
+ });
+});
+
+describe('renderPromptTemplate', () => {
+ const args = { name: 'Placeholder Hero', kind: 'character', direction: 'east', chromaKey: '#FF00FF' };
+
+ it('leaves an UNKNOWN placeholder literal rather than blanking it', () => {
+ // A visible `{{drection}}` is a typo the user can find and fix; a silently
+ // dropped clause reads as the model ignoring their instruction.
+ expect(renderPromptTemplate('facing {{drection}} now', args)).toBe('facing {{drection}} now');
+ });
+
+ it('tolerates whitespace inside the braces', () => {
+ expect(renderPromptTemplate('{{ name }} and {{name}}', args)).toBe('Placeholder Hero and Placeholder Hero');
+ });
+
+ it('renders an absent value as empty rather than as "undefined"', () => {
+ expect(renderPromptTemplate('[{{direction}}]', { name: 'x' })).toBe('[]');
+ });
+
+ it('does not interpolate inherited Object keys', () => {
+ expect(renderPromptTemplate('{{toString}}', args)).toBe('{{toString}}');
+ });
+});
diff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.js
index b69aaca0ff..ea0b18c345 100644
--- a/server/services/sprites/walk.js
+++ b/server/services/sprites/walk.js
@@ -59,8 +59,14 @@ import {
GROK_TUI_IDLE_MS, GROK_TUI_TIMEOUT_MS, grokTuiProvider, buildGrokI2vTask,
} from './animationWorkflow.js';
import {
- ANIMATION_TRACKS, SCANNER_TRACK, sourceReferenceFor,
+ SCANNER_TRACK, sourceReferenceFor,
} from './animationTracks.js';
+// #3152 — the anchor-invalidation sweep below must cover a USER-DEFINED track too:
+// a stored row seeded from a directional anchor holds approvals descended from the
+// same reference, and sweeping only the compiled table would leave them standing
+// after an anchor revision (the atlas would then compile frames drawn from an
+// image that no longer exists — exactly what this sweep exists to prevent).
+import { getEffectiveAnimationTracks } from './animationTrackStore.js';
import {
invalidateTrackDirectionForAnchorRevision, invalidateTrackForTurnaroundRevision,
} from './animationTrackWorkflow.js';
@@ -1897,8 +1903,11 @@ async function invalidateAnchorDependentTracks(recordId, direction) {
* anchor revision invalidates. Walk is excluded because it owns its own
* invalidation path above.
*/
-const anchorSeededTracks = () => Object.values(ANIMATION_TRACKS)
- .filter((row) => row.id !== WALK_TRACK && sourceReferenceFor(row.id) === 'anchor');
+const anchorSeededTracks = () => {
+ const tracks = getEffectiveAnimationTracks();
+ return Object.values(tracks)
+ .filter((row) => row.id !== WALK_TRACK && sourceReferenceFor(row.id, tracks) === 'anchor');
+};
/**
* Reopen the main (south) reference and invalidate only animations conditioned
diff --git a/server/services/sprites/walkFrames.js b/server/services/sprites/walkFrames.js
index 0108996acc..3c8f59055e 100644
--- a/server/services/sprites/walkFrames.js
+++ b/server/services/sprites/walkFrames.js
@@ -36,6 +36,9 @@ import {
} from './paths.js';
import { sha256Buffer } from './walkPostprocess.js';
import { WALK_TRACK, getAnimationTrack } from './animationTracks.js';
+// #3152 — a manifest's `track` may name a user-defined row, so the id is resolved
+// against the effective table rather than the compiled `walk`-only default.
+import { getEffectiveAnimationTracks } from './animationTrackStore.js';
import { trackColumnLabels } from './atlasGrid.js';
const compileFrameError = (message) =>
@@ -48,7 +51,9 @@ export async function verifyPackagedFrames(recordId, manifest, { bytes = false,
// Compile checks each frame's gait-phase against the set's phase labels. The
// set's frame count is enforced identical across directions before this runs
// (atlas.js), so labels derived from THIS manifest's length match the set's.
- const labels = bytes ? trackColumnLabels(getAnimationTrack(track).id, total) : null;
+ const labels = bytes
+ ? trackColumnLabels(getAnimationTrack(track, getEffectiveAnimationTracks()).id, total)
+ : null;
const frameBytes = bytes ? [] : null;
let missing = 0;
diff --git a/server/services/sprites/walkPostprocess.js b/server/services/sprites/walkPostprocess.js
index 55932c147c..6c860ed5f4 100644
--- a/server/services/sprites/walkPostprocess.js
+++ b/server/services/sprites/walkPostprocess.js
@@ -35,6 +35,9 @@ import {
WALK_FRAME_COUNT, WALK_DEFAULT_FRAME_COUNT, WALK_DEFAULT_FPS,
} from './walkBounds.js';
import { WALK_TRACK, getAnimationTrack, clampTrackFrameCount, clampTrackFps } from './animationTracks.js';
+// #3152 — the packer runs for any track the generic workflow drives, including a
+// user-defined one, so its bounds come from the effective table.
+import { getEffectiveAnimationTracks } from './animationTrackStore.js';
import { trackColumnLabels } from './atlasGrid.js';
export {
@@ -884,9 +887,10 @@ export async function runWalkPostprocess({
recordId, direction, chromaKey, runAbs, runRel, anchorRel, anchorAbs, videoAbs,
frameCount = WALK_DEFAULT_FRAME_COUNT, fps = WALK_DEFAULT_FPS, track = WALK_TRACK,
}) {
- const trackRow = getAnimationTrack(track);
- const targetFrames = clampTrackFrameCount(frameCount, track);
- const playbackFps = clampTrackFps(fps, track);
+ const effectiveTracks = getEffectiveAnimationTracks();
+ const trackRow = getAnimationTrack(track, effectiveTracks);
+ const targetFrames = clampTrackFrameCount(frameCount, track, effectiveTracks);
+ const playbackFps = clampTrackFps(fps, track, effectiveTracks);
const phaseLabels = trackColumnLabels(track, targetFrames);
const split = keyChannelSplit(chromaKey);
const generatedAbs = join(runAbs, 'generated');