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

move the sprite vocabulary and pure track modules below validation

[._.]/ Adam Eivy97f794d0e9e7
diff --git a/server/lib/README.md b/server/lib/README.md
index cf260c9ff6..f3b2b5e0a5 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -31,6 +31,10 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `fableLoomLimits.js` | FableLoom record caps (`LOOM_LIMITS`) — the single source of truth shared by the route schemas and the record sanitizer. A leaf module, below both. |
| `fableLoomFormats.js` | FableLoom scene formats (`LOOM_FORMATS`, `asLoomFormat`, `sceneFormatContract`, …) — how a loom writes scene text, read by validation, the sanitizer, and every generative stage. |
| `postDrillTypes.js` | MeatSpace POST drill vocabularies (`CACHEABLE_TYPES`, `COGNITIVE_DRILL_TYPES`), kept below validation so a route schema never pulls in the POST services (and, through them, the LLM drill generator). |
+| `spriteVocabulary.js` | Sprite id pattern, record kinds, the canonical 8-direction order + derived anchor set, `TURNAROUND_ID`, and the animation provider ids — the alphabets the sprite route schemas enumerate, kept below the sprite services. |
+| `spriteChromaKey.js` | Chroma-key selection color math (`CHROMA_KEYS`, `CHROMA_KEY_HEXES`, `DEFAULT_CHROMA_KEY`, hue-distance picking). Pure color math, no image I/O — that lives in `services/sprites/normalize.js`. |
+| `spriteAnimationTracks.js` | The animation-track registry (`ANIMATION_TRACKS`, `WALK_TRACK`, `TRACK_BOUND_TRIPLES`, `AUTHORED_TRACK_FIELDS`) — a zero-import table of per-track frame/fps bounds. |
+| `spriteAnimationTrackStore.js` | The EFFECTIVE track table — compiled built-ins plus the user-defined store read from one small JSON config, so sprite schemas stay module-load constants rather than lazily-built. |
| `agentOutputMarkers.js` | Status lines PortOS itself appends to an agent's output buffer: `SENTINEL_COMPLETION_MARKER` (the line `ingestDoneSentinel` writes just before the agent's `.agent-done` summary) plus `isAgentLifecycleLine(line)`/`stripLifecycleLines(lines)`, which match PortOS's telemetry on its actual message shapes rather than on a leading emoji (an agent's own summary may well start a line with `✅`). Pure — shared by the emitter (`services/agentTuiSpawning.js`) and by readers that must show only the agent's own words (notably the generated PR description). |
| `agentRunEvents.js` | CoS run lifecycle-event envelope (#4540) — pure half of the append-only ledger in `services/agentRunEventLog.js`. `AGENT_RUN_EVENT_KINDS` (closed vocabulary: spawned, handoff, output, reconnected, paused, resumed, interrupted, pr-verified, orphan-recovered, runner-recovered, finalized), `agentRunEventSchema` (Zod, `.strict()`), `buildRunEvent()` which redacts then mints a CONTENT-derived `eventId` (sha256 of the canonicalized envelope) so a redelivered lifecycle transition dedupes instead of double-counting, `redactRunEventData()` (drops prompt/description/output/result-class keys to a `{ redacted, chars }` stub, scrubs the home-dir prefix out of every remaining string via `scrubHomePath`, runs `redactOutput`, and caps string/array/key/depth per `RUN_EVENT_LIMITS`), and `projectRunStates()` — the clock-free fold that derives current run status from the ordered stream, so replay-after-restart and read-current-status are one code path. Unknown kinds fold as no-ops so a newer install's ledger replays on an older one. |
| `agentRunReconcile.js` | CoS run reconciliation (#4540) — pure diff between a ledger projection (`projectRunStates`) and the durable run record. Closed finding vocabulary `RUN_RECONCILE_FINDINGS` (`record-open`, `record-missing`, `verdict-mismatch`, `ledger-open`), `diffRunRecord()`, `reconcileRunRecords()` with a zero-filled per-kind summary, and `planRunRecordRepair()` — the metadata patch that closes a record the ledger proves is finished. Repairs are one-directional (ledger → record) by design: a record closed while the ledger missed the close is reported, never back-filled, so the stream stays an audit of the record rather than a copy of it. I/O half: `services/agentRunReconciler.js`. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 8adb1f20f1..3098ddf897 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -349,6 +349,10 @@ export * from './markdownText.js';
export * from './renderSlot.js';
export * from './renderTargets.js';
export * from './generationModes.js';
+export * from './spriteVocabulary.js';
+export * from './spriteChromaKey.js';
+export * from './spriteAnimationTracks.js';
+export * from './spriteAnimationTrackStore.js';
export * from './postDrillTypes.js';
export * from './telegramClient.js';
export * from './tempPathGuard.js';
diff --git a/server/lib/layering.test.js b/server/lib/layering.test.js
index 1b6e2acd2a..eacf6ee615 100644
--- a/server/lib/layering.test.js
+++ b/server/lib/layering.test.js
@@ -28,7 +28,6 @@ const PREEXISTING_LIB_TO_SERVICES_ALLOWLIST = new Set([
'createSettingsGatedSyncScheduler.js',
'creativeDirectorPrompts.js',
'promptRunner.js',
- 'spriteValidation.js',
'stageRunner.js',
'tuiPromptRunner.js',
]);
diff --git a/server/lib/spriteAnimationTrackStore.js b/server/lib/spriteAnimationTrackStore.js
new file mode 100644
index 0000000000..580cb49d2a
--- /dev/null
+++ b/server/lib/spriteAnimationTrackStore.js
@@ -0,0 +1,275 @@
+/**
+ * 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. The memo holds the MERGED table (never `null` once
+ * resolved, since `walk` is always in it), so a zero-row install caches too rather
+ * than re-reading on every lookup.
+ */
+
+import { readFileSync } from 'fs';
+import { join } from 'path';
+import { PATHS } from './fileUtils.js';
+import {
+ ANIMATION_TRACKS, WALK_TRACK, assertAnimationTrackRows, getAnimationTrack,
+} from './spriteAnimationTracks.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);
+
+// The merged table — `null` until first resolve. ONE cache, on the merged result
+// rather than also on the raw rows: `assertAnimationTrackRows` runs over the merge,
+// so memoizing the raw read too would only pin a row set that failed validation,
+// and a user who then fixed their JSON would keep getting the stale error.
+let cachedEffectiveTracks = null;
+
+/**
+ * Which of the three failure kinds a read error is:
+ *
+ * `absent` — ENOENT. Nothing there; try the next candidate.
+ * `io-error` — any other errno. A real, user-facing problem: report it.
+ * `no-filesystem` — NO errno at all, so the call never reached a filesystem.
+ * See `resolveStoreDoc`'s header for the environment that
+ * produces this and why it degrades instead of throwing.
+ *
+ * Exported so the classification is asserted directly (`animationTrackStore.test.js`):
+ * this module binds `readFileSync` at import, so a test that re-mocked `fs` would not
+ * intercept it and would pass without exercising anything.
+ */
+export function classifyStoreReadError(err) {
+ if (!err?.code) return 'no-filesystem';
+ return err.code === 'ENOENT' ? 'absent' : 'io-error';
+}
+
+/**
+ * Read one candidate store file. Returns `null` for "not there" (try the next
+ * candidate) and THROWS for "there but unreadable" — the sentinel rule: a corrupt
+ * store must not silently degrade to the seed, or a user whose edits broke the JSON
+ * would see their tracks quietly revert to shipped defaults with no error to
+ * explain it.
+ */
+function readStoreDoc(path) {
+ let raw;
+ try {
+ raw = readFileSync(path, 'utf-8');
+ } catch (err) {
+ const kind = classifyStoreReadError(err);
+ if (kind === 'absent') return null;
+ // A `no-filesystem` error is re-thrown BARE for `resolveStoreDoc` to read as
+ // "no store", rather than dressed up as an unreadable file the user would go
+ // looking for. Only a real errno becomes this module's own named error.
+ if (kind === 'no-filesystem') throw err;
+ 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}`);
+ }
+}
+
+/**
+ * The authoritative store doc: the user copy if it exists, else the shipped seed,
+ * else `null` (walk alone).
+ *
+ * **Why the whole resolution is guarded.** `server/lib/validation.js` builds its
+ * sprite Zod ranges from the effective registry AT MODULE LOAD, and nearly every
+ * route and service imports `validation.js`. So this runs inside test suites that
+ * have nothing to do with sprites — including ones that legitimately stub the
+ * filesystem with a partial factory (`vi.mock('fs', () => ({ existsSync }))`, or a
+ * `fileUtils.js` double exporting no `PATHS`). In that environment there is no
+ * filesystem to consult, and the honest answer is "no store" — walk alone — not a
+ * hard import-time failure over a file the suite never asked about.
+ *
+ * Scoped deliberately to the *environment* being unusable, never to a real read
+ * failure: `readStoreDoc` still throws on a store that exists but won't parse,
+ * because that is a user's broken hand edit and silently reverting to shipped
+ * defaults is the sentinel violation this module's header calls out. A TypeError
+ * from a missing mock export cannot reach a real install — an install always has
+ * `fs` and `PATHS`.
+ */
+function resolveStoreDoc() {
+ try {
+ return readStoreDoc(animationTrackStorePath()) ?? readStoreDoc(animationTrackSeedPath());
+ } catch (err) {
+ // Rethrow anything that came from an actual file: those carry this module's
+ // own prefix (unreadable / not-valid-JSON) and must stay loud.
+ if (err?.message?.startsWith(ANIMATION_TRACK_STORE_REL)) throw err;
+ return null;
+ }
+}
+
+/**
+ * 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() {
+ const doc = resolveStoreDoc();
+ 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);
+ }
+ return Object.freeze(byId);
+}
+
+/**
+ * The compiled table merged with the user-defined store: `{ walk, …stored }`.
+ *
+ * **SYNCHRONOUS, and never a Promise** — this is safe to use as a default
+ * parameter (`tracks = getEffectiveAnimationTracks()`), which is how atlas.js,
+ * atlasGrid.js, atlasLayout.js and walkFrames.js consume it. The header explains
+ * why sync is required rather than merely convenient; stated again here because a
+ * reader (or a reviewer) landing on one of those default params sees only the call.
+ *
+ * **`walk` is always present**, on every path — it comes from the compiled table,
+ * not the store, so an absent/empty/deleted store yields `{ walk }` rather than
+ * `{}`. A caller resolving `WALK_TRACK` can never miss.
+ *
+ * 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());
+}
+
+/**
+ * One row out of the effective table — `getAnimationTrack(id, getEffectiveAnimationTracks())`,
+ * which was being spelled out at a dozen call sites.
+ *
+ * Keeps `getAnimationTrack`'s exact boundary — it IS that call, just named:
+ * an absent id (`undefined`/`null`) resolves to `walk`, and an unrecognized one
+ * **THROWS** naming the known tracks. It never returns `undefined`, so callers
+ * dereference `.id`/`.label`/bounds on the result without a guard (as every call
+ * site does). Modules that must work against an injected table still call
+ * `getAnimationTrack(id, tracks)` directly; that parameter is the test seam and is
+ * deliberately untouched.
+ */
+export function effectiveTrack(id) {
+ return getAnimationTrack(id, getEffectiveAnimationTracks());
+}
+
+/**
+ * Drop the cached store read.
+ *
+ * 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() {
+ cachedEffectiveTracks = null;
+}
diff --git a/server/services/sprites/animationTrackStore.test.js b/server/lib/spriteAnimationTrackStore.test.js
similarity index 97%
rename from server/services/sprites/animationTrackStore.test.js
rename to server/lib/spriteAnimationTrackStore.test.js
index c7c0f87571..ef3584971d 100644
--- a/server/services/sprites/animationTrackStore.test.js
+++ b/server/lib/spriteAnimationTrackStore.test.js
@@ -27,11 +27,11 @@ import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
import { mkdtempSync, rmSync, mkdirSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
-import { storedTrackRow } from './spriteTestFixtures.js';
+import { storedTrackRow } from '../services/sprites/spriteTestFixtures.js';
const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-track-store-test-'));
-vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
+vi.mock('./fileUtils.js', async (importOriginal) => {
const actual = await importOriginal();
Object.assign(actual.PATHS, { data: TEST_ROOT, sprites: join(TEST_ROOT, 'sprites') });
return actual;
@@ -41,8 +41,8 @@ const {
getEffectiveAnimationTracks, getEffectiveAnimationTrackIds, __resetAnimationTrackStore,
animationTrackStorePath, animationTrackSeedPath, ANIMATION_TRACK_STORE_SCHEMA_VERSION,
classifyStoreReadError,
-} = await import('./animationTrackStore.js');
-const { ANIMATION_TRACKS, WALK_TRACK } = await import('./animationTracks.js');
+} = await import('./spriteAnimationTrackStore.js');
+const { ANIMATION_TRACKS, WALK_TRACK } = await import('./spriteAnimationTracks.js');
const STORE_PATH = animationTrackStorePath();
diff --git a/server/lib/spriteAnimationTracks.js b/server/lib/spriteAnimationTracks.js
new file mode 100644
index 0000000000..82f9c735e7
--- /dev/null
+++ b/server/lib/spriteAnimationTracks.js
@@ -0,0 +1,501 @@
+/**
+ * Sprites — the animation-track registry (issue #3015).
+ *
+ * Frame-count and fps bounds used to be GLOBAL and walk-shaped: one 6–16 /
+ * 4–24 range applied to every animation, because the walk cycle was the only
+ * animation that existed. #2985 made the persisted target *track-keyed*
+ * (`animationTargets.walk`), but nothing described what tracks exist or what
+ * each one's legal range is — so a 3-frame ambient loop (a tree in the wind)
+ * was unrepresentable. The shipped 4-frame scanner action proves the registry
+ * supports a real non-walk range below walk's floor.
+ *
+ * This module is that description. One row per known track carries its own
+ * bounds, defaults, directionality, and the `runtimeContract` field names it
+ * occupies — so adding a track is a row here plus its pipeline, never a hunt
+ * for hard-coded 6/16 literals. `walk` is the first and (today) only row and
+ * reproduces its historical values exactly; `walkBounds.js` now re-reads this
+ * row rather than defining the range itself.
+ *
+ * **Sharp-free leaf, deliberately.** `server/lib/validation.js` builds its Zod
+ * ranges from these rows and must not drag the native image graph
+ * (sharp/ffmpeg, via walkPostprocess) into the request-validation graph — the
+ * same split walkBounds.js was created for, now one level deeper. This module
+ * imports NOTHING. `animationTracks.test.js` asserts that transitively.
+ *
+ * **Unknown track ids are an error, not a fallback.** `getAnimationTrack('nope')`
+ * throws instead of quietly handing back walk's range — a mis-keyed track that
+ * silently validated against walk's 6–16 would let a 4-frame action be rejected
+ * for reasons no message explains. Absent (`undefined`/`null`) means "the
+ * default track" and resolves to `walk`, which is what preserves every existing
+ * call site; an empty string is *present and invalid*, so it throws.
+ *
+ * **Which records may carry a track is registry data too (#3017).** The whole
+ * sprite animation surface used to be gated on a literal `kind !== 'character'`
+ * check, which is why `place` and `object` records had no animation path at all
+ * — a tree in the wind or a flickering lamp was unrepresentable not because the
+ * atlas couldn't hold it but because the gate refused the record. Each row now
+ * declares the record `kinds` that may carry it, and the gates ask the registry
+ * (`tracksForKind` / `kindSupportsTrack`) instead of naming a kind. Walk stays
+ * character-only, so behavior is unchanged today; a row that lists `place` is
+ * all it takes to unlock those records, with no gate edit anywhere.
+ *
+ * **The per-track WORKFLOW is registry data too (#3136).** `scanner` and
+ * `ambient` each shipped as a ~300-line clone of walk's state/start/package/
+ * approve/invalidate stack — identical control flow differing only in which
+ * reference image seeds the render, what the on-disk selection/set files are
+ * called, and which prompt text goes to the provider. Those differences are now
+ * either FIELDS on the row (`selectionKind`/`setKind`) or derived from one
+ * (`directional` decides both the facing count and which locked reference seeds
+ * 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 — and the only one compiled into this build (#3152). */
+export const WALK_TRACK = 'walk';
+/**
+ * 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';
+export const AMBIENT_TRACK = 'ambient';
+
+/**
+ * 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.
+ * - `defaultFrameCount` / `defaultFps` — the bottom rung of the target
+ * precedence chain (see `animationTargets.js`).
+ * - `directional` — true when the track occupies one atlas ROW per facing
+ * (walk: 8 directions); a future ambient loop would be false (one row).
+ * Load-bearing since #3017: `trackRowCount` turns it into the number of rows
+ * the track's cells may occupy, and the compiler refuses a cell outside them.
+ * - `kinds` — the sprite record kinds that may carry this track. The animation
+ * gates read this instead of testing for `'character'`, so unlocking a record
+ * kind is a data change here rather than a hunt through the service layer.
+ * - `contractFrameCountField` / `contractFpsField` — the field names this track
+ * occupies in an app's `publishBinding.runtimeContract` (#2982). Named here so
+ * the app rung of the precedence chain is track-driven rather than hard-coded
+ * to `walkFrameCount`. `contractFpsField` may be `null` for a track whose
+ * speed an app has no say in.
+ * - `selectionKind` / `setKind` (#3136) — the `kind` discriminators the track's
+ * on-disk review selection and finalized set carry. Registry data because the
+ * atlas compiler VALIDATES them (`atlas.js`), so a track's on-disk contract
+ * and the compiler's expectation cannot drift.
+ * - `finalErrorCode` (#3136) — the `code` on the 409 a finalized set answers
+ * generate/approve with. Named per row so an existing client that matches on
+ * `SCANNER_SET_FINAL` keeps working after the clone collapsed.
+ * - `standaloneContract` (#3136) — true when this track's frame count is enough
+ * ON ITS OWN to describe a publishable atlas, because a record can be
+ * published with only this track authored. Walk (a character's baseline) and
+ * ambient (a place's) qualify; a short ACTION like scanner always rides beside
+ * the walk it shares rows with, so pinning only its span describes no atlas
+ * 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
+ * facing's own anchor (`sourceReferenceFor` below), while a non-directional one
+ * has no per-facing anchor and seeds from the single locked main. Stating it as
+ * a field would let a row claim a pairing that cannot work.
+ */
+export const ANIMATION_TRACKS = Object.freeze({
+ [WALK_TRACK]: Object.freeze({
+ id: WALK_TRACK,
+ label: 'Walk cycle',
+ directional: true,
+ // A walk cycle is a character gait — a place or an object has no gait to
+ // author, so walk stays character-only and every existing gate keeps its
+ // exact behavior. What changed in #3017 is only WHERE that fact lives.
+ kinds: Object.freeze(['character']),
+ minFrameCount: 6,
+ maxFrameCount: 16,
+ defaultFrameCount: 12,
+ minFps: 4,
+ maxFps: 24,
+ defaultFps: 10,
+ contractFrameCountField: 'walkFrameCount',
+ // `spriteRuntimeContractSchema` deliberately declares no fps key (a
+ // distance-driven consumer has no animation-fps concept), so today this is
+ // reachable only by a legacy/hand-built contract object — kept, not
+ // nulled, because dropping it would change resolution behavior for those.
+ // A second track copying this row should decide its own answer.
+ contractFpsField: 'walkFps',
+ // Walk predates the generic workflow and keeps its own bespoke service
+ // (walk.js — reprocess, trims, per-direction reopen, source-frame
+ // extraction, set-level targets), so these describe its on-disk contract
+ // for the compiler's benefit without routing it through the generic module.
+ selectionKind: 'reviewed-directional-walk-selection',
+ setKind: 'finalized-eight-direction-walk-set',
+ finalErrorCode: 'WALK_SET_FINAL',
+ // A character publishes off its walk — the compile path requires a finalized
+ // walk set before it emits anything at all.
+ 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,
+ }),
+});
+
+// There is deliberately no `ANIMATION_TRACK_IDS` export (#3152 removed it). It
+// would now mean "the COMPILED ids" — `['walk']` — while reading as "every track
+// id", which is the wrong answer at every call site that wanted it: those want the
+// merged table's ids and must ask `getEffectiveAnimationTrackIds()` in
+// `animationTrackStore.js`. Iterate `Object.keys(ANIMATION_TRACKS)` inline when you
+// genuinely mean the compiled rows only.
+
+/**
+ * The min/default/max triples every row must keep in order.
+ *
+ * Exported because three places need this exact pairing and had each spelled their
+ * own copy: the assert below, the request schemas in `server/lib/validation.js`
+ * (which front-run the assert so the form gets a per-field 400), and the client's
+ * pre-submit check. A fourth knob added to one copy and missed in another is the
+ * drift this prevents.
+ */
+export const TRACK_BOUND_TRIPLES = Object.freeze([
+ Object.freeze(['minFrameCount', 'defaultFrameCount', 'maxFrameCount']),
+ Object.freeze(['minFps', 'defaultFps', 'maxFps']),
+]);
+
+/**
+ * The fields of a row a USER authors, as opposed to the ones PortOS derives.
+ *
+ * The complement is deliberate and load-bearing: everything NOT listed here
+ * (`contractFrameCountField`, `contractFpsField`, `selectionKind`, `setKind`,
+ * `finalErrorCode`, `standaloneContract`, `builtin`) names a file on disk, a
+ * publish-contract key, or a cross-row invariant that `assertAnimationTrackRows`
+ * requires to be globally unique — so it is derived from the id rather than typed
+ * (see `animationTrackCrud.js`). Named here, beside the assert that validates the
+ * whole row, so the request schema and the service's whitelist build from ONE list
+ * instead of two that fail in opposite directions when they drift: a field in the
+ * schema but not the whitelist validates and is then silently dropped, and one in
+ * the whitelist but not the schema is rejected as an unrecognized key.
+ */
+export const AUTHORED_TRACK_FIELDS = Object.freeze([
+ 'label', 'directional', 'kinds',
+ 'minFrameCount', 'maxFrameCount', 'defaultFrameCount',
+ 'minFps', 'maxFps', 'defaultFps',
+ 'promptTemplate',
+]);
+
+/**
+ * The five on-disk / publish-contract discriminators a track's id determines, plus
+ * the `contractFpsField` a user-defined row always declines.
+ *
+ * Derived rather than typed because `assertAnimationTrackRows` requires each to be
+ * globally unique and they name artifacts the atlas compiler re-verifies — a typo in
+ * one would hand this track another's evidence chain. Lives here, beside that
+ * assert, so one module knows a row's whole shape.
+ *
+ * `contractFpsField` is `null` to match both seeded rows: PortOS's fps is
+ * preview-only (a distance-driven consumer owns its timing), so a new track claiming
+ * an fps contract key would offer the app a knob nothing reads.
+ */
+export function deriveTrackFields(id) {
+ const camel = id.replace(/-([a-z0-9])/g, (_m, c) => c.toUpperCase());
+ return {
+ contractFrameCountField: `${camel}FrameCount`,
+ contractFpsField: null,
+ selectionKind: `reviewed-${id}-selection`,
+ setKind: `finalized-${id}-set`,
+ finalErrorCode: `${id.replace(/-/g, '_').toUpperCase()}_SET_FINAL`,
+ };
+}
+
+/**
+ * Validate a registry's rows, throwing on the first violation.
+ *
+ * Called at module load below (the navManifest.js / catalogTypes.js idiom): a
+ * row missing a bound would otherwise boot clean and surface much later as
+ * `NaN` out of a Math.min, or as `z.number().min(undefined)` throwing at the
+ * first sprite render. A bad row should block boot with a message naming the
+ * field, not corrupt a render hours later.
+ *
+ * Exported and pure — taking the table as an argument — so the guard can be
+ * proven against a synthetic multi-row fixture. Asserting set-uniqueness over
+ * the real (currently single-row) table would only re-derive the
+ * implementation: the whole guard could be deleted and such a test would stay
+ * green, which is exactly the regression it exists to prevent.
+ */
+export function assertAnimationTrackRows(tracks) {
+ const claimedContractFields = new Map();
+ const claimedOnDiskKinds = new Map();
+ for (const id of Object.keys(tracks)) {
+ const row = tracks[id];
+ if (row.id !== id) throw new Error(`animationTracks: row '${id}' declares mismatched id '${row.id}'`);
+ if (typeof row.label !== 'string' || !row.label) throw new Error(`animationTracks: track '${id}' needs a label`);
+ if (typeof row.directional !== 'boolean') throw new Error(`animationTracks: track '${id}' needs a boolean 'directional'`);
+ // A row with no kinds is unreachable work: nothing could ever carry it, and
+ // the gate would refuse every record with a message blaming the record.
+ if (!Array.isArray(row.kinds) || !row.kinds.length) {
+ throw new Error(`animationTracks: track '${id}' needs a non-empty 'kinds' array`);
+ }
+ if (row.kinds.some((kind) => typeof kind !== 'string' || !kind)) {
+ throw new Error(`animationTracks: track '${id}' has a non-string entry in 'kinds'`);
+ }
+ for (const field of ['minFrameCount', 'maxFrameCount', 'defaultFrameCount', 'minFps', 'maxFps', 'defaultFps']) {
+ if (!Number.isInteger(row[field])) throw new Error(`animationTracks: track '${id}' needs an integer '${field}'`);
+ }
+ if (typeof row.contractFrameCountField !== 'string' || !row.contractFrameCountField) {
+ throw new Error(`animationTracks: track '${id}' needs a contractFrameCountField`);
+ }
+ if (row.contractFpsField !== null && (typeof row.contractFpsField !== 'string' || !row.contractFpsField)) {
+ throw new Error(`animationTracks: track '${id}' needs a contractFpsField (or null)`);
+ }
+ // #3136 — the workflow shape.
+ for (const field of ['selectionKind', 'setKind', 'finalErrorCode']) {
+ if (typeof row[field] !== 'string' || !row[field]) {
+ throw new Error(`animationTracks: track '${id}' needs a non-empty '${field}'`);
+ }
+ }
+ 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'`);
+ }
+ // EXACTLY ONE prompt source per row — the invariant, stated as itself rather
+ // than as two provenance checks. A row's prompt is either the compiled builder
+ // `trackPrompts.js` holds for it (`builtin`, no template) or its own
+ // `promptTemplate` (stored). Neither means a throw out of `buildTrackVideoPrompt`
+ // AFTER the user clicked generate; both means two definitions of one track's
+ // wording, where the stored value silently wins over the text
+ // `prompts.test.js` pins. Refuse either at load, where the message names the row.
+ const hasTemplate = typeof row.promptTemplate === 'string' && !!row.promptTemplate.trim();
+ if (hasTemplate === row.builtin) {
+ throw new Error(
+ row.builtin
+ ? `animationTracks: builtin track '${id}' must not carry a 'promptTemplate' — its prompt is the compiled builder`
+ : `animationTracks: user-defined track '${id}' needs a non-empty 'promptTemplate'`,
+ );
+ }
+ // Two tracks sharing a selection/set `kind` is the same class of bug as two
+ // sharing a contract field: the compiler validates a set by its `kind`, so a
+ // duplicate would let one track's finalized set satisfy the other's evidence
+ // check and compile the wrong frames into its span.
+ for (const knob of ['selectionKind', 'setKind']) {
+ const owner = claimedOnDiskKinds.get(row[knob]);
+ if (owner) {
+ throw new Error(
+ `animationTracks: on-disk kind '${row[knob]}' is claimed by both '${owner.id}.${owner.knob}' and '${id}.${knob}'`,
+ );
+ }
+ claimedOnDiskKinds.set(row[knob], { id, knob });
+ }
+ for (const [min, def, max] of TRACK_BOUND_TRIPLES) {
+ if (!(row[min] <= row[def] && row[def] <= row[max])) {
+ throw new Error(`animationTracks: track '${id}' needs ${min} <= ${def} <= ${max}`);
+ }
+ }
+ // Two tracks must not claim the same runtimeContract field. The anticipated
+ // failure is a second row copy-pasted from walk's: `resolveAnimationTarget`
+ // would then read the WALK's `walkFrameCount` for that track and, whenever
+ // that value happens to land inside its range, return it with
+ // `frameCountLocked: true` — silently pinning one track to another's
+ // contract and throwing a lock error citing a binding that never mentioned
+ // it. The knob name rides along so a row that names ONE field for BOTH of
+ // its knobs doesn't report as "claimed by both 'walk' and 'walk'".
+ for (const knob of ['contractFrameCountField', 'contractFpsField']) {
+ const field = row[knob];
+ if (field === null) continue;
+ const owner = claimedContractFields.get(field);
+ if (owner) {
+ throw new Error(
+ `animationTracks: contract field '${field}' is claimed by both '${owner.id}.${owner.knob}' and '${id}.${knob}'`,
+ );
+ }
+ claimedContractFields.set(field, { id, knob });
+ }
+ }
+ // Every record kind any row admits must have EXACTLY ONE standalone track —
+ // the baseline it publishes off. Zero means a record of that kind can be
+ // authored but never publish (its runtime contract could name no required
+ // field, and the compiler has no evidence chain to require); more than one
+ // means "which set must be finalized before compiling?" has two answers. This
+ // is a cross-row invariant, so it runs after the per-row loop.
+ const standaloneByKind = new Map();
+ for (const id of Object.keys(tracks)) {
+ if (!tracks[id].standaloneContract) continue;
+ for (const kind of tracks[id].kinds) {
+ standaloneByKind.set(kind, [...(standaloneByKind.get(kind) || []), id]);
+ }
+ }
+ for (const id of Object.keys(tracks)) {
+ for (const kind of tracks[id].kinds) {
+ const owners = standaloneByKind.get(kind) || [];
+ if (owners.length !== 1) {
+ throw new Error(
+ `animationTracks: record kind '${kind}' needs exactly one standaloneContract track, has ${owners.length}${owners.length ? ` (${owners.join(', ')})` : ''}`,
+ );
+ }
+ }
+ }
+}
+
+assertAnimationTrackRows(ANIMATION_TRACKS);
+
+/**
+ * The locked reference artifact a track's image-to-video render is seeded from:
+ * `'anchor'` (this facing's own locked directional anchor) or `'main'` (the one
+ * locked main reference).
+ *
+ * DERIVED from `directional` rather than declared, because only one pairing can
+ * work. A directional track renders one clip per facing, so seeding all eight
+ * rows from the single main would render the same south-facing clip eight times
+ * and pass every later check — nothing downstream re-reads which facing was
+ * asked for. The inverse has no anchor to read at all: a place record never
+ * generates directional anchors.
+ */
+export function sourceReferenceFor(id, tracks = ANIMATION_TRACKS) {
+ return getAnimationTrack(id, tracks).directional ? 'anchor' : 'main';
+}
+
+/**
+ * The one track a record of `kind` publishes off — its baseline, whose finalized
+ * set the compile path requires and whose frame count alone is a valid runtime
+ * contract. `null` for a kind no row admits.
+ *
+ * One definition, asked by the publish-contract schema (which field is required)
+ * and the compile dispatch (which evidence chain to validate). Those two used to
+ * answer it separately — one by registration order, one as
+ * `ambient-and-not-walk` — and agreed only by coincidence.
+ */
+export function primaryTrackForKind(kind, tracks = ANIMATION_TRACKS) {
+ if (typeof kind !== 'string' || !kind) return null;
+ return Object.values(tracks).find((row) => row.standaloneContract && row.kinds.includes(kind)) || null;
+}
+
+/** True when `id` names a track in `tracks` (the shipped registry by default). */
+export function isAnimationTrack(id, tracks = ANIMATION_TRACKS) {
+ return typeof id === 'string' && Object.prototype.hasOwnProperty.call(tracks, id);
+}
+
+/**
+ * The registry row for `id`. Absent (`undefined`/`null`) resolves to the default
+ * track; anything else unrecognized THROWS rather than falling back, so a typo
+ * can never be validated against walk's range by accident.
+ *
+ * The table is a parameter — the same idiom `assertAnimationTrackRows(tracks)`
+ * uses — so a caller that must work across a *set* of tracks (the atlas grid,
+ * #3016) can be exercised against a synthetic multi-row table while the shipped
+ * registry has one row, WITHOUT that caller growing a private lookup that
+ * bypasses this unknown-id boundary.
+ */
+export function getAnimationTrack(id, tracks = ANIMATION_TRACKS) {
+ const key = id === undefined || id === null ? WALK_TRACK : id;
+ if (!isAnimationTrack(key, tracks)) {
+ throw new Error(
+ `Unknown animation track '${String(key)}' — known tracks: ${Object.keys(tracks).join(', ')}.`,
+ );
+ }
+ return tracks[key];
+}
+
+/**
+ * The atlas rows one track's cells may occupy, given how many facings the grid
+ * has: every row for a directional track, exactly one (row 0) for a
+ * non-directional one.
+ *
+ * `directionCount` is a PARAMETER rather than an import because this module is
+ * a true leaf — `animationTracks.test.js` asserts it imports nothing at all —
+ * and the canonical direction list lives in `prompts.js`. Callers that already
+ * know the grid pass its real height; `atlasGrid.js` supplies the default.
+ */
+export function trackRowCount(id, directionCount, tracks = ANIMATION_TRACKS) {
+ const row = getAnimationTrack(id, tracks);
+ if (!Number.isInteger(directionCount) || directionCount < 1) {
+ throw new Error(`animationTracks: trackRowCount needs a positive direction count, got ${directionCount}`);
+ }
+ return row.directional ? directionCount : 1;
+}
+
+/**
+ * Every track a record of this `kind` may carry, in registration order.
+ *
+ * This is the whole of the "track-presence gate" (#3017): a record kind with no
+ * rows has no animation path, and a kind with at least one does — replacing the
+ * literal `kind !== 'character'` test the sprite services used to make. An
+ * absent/blank kind matches nothing rather than defaulting to a kind, so a
+ * malformed record can't inherit character's permissions.
+ */
+export function tracksForKind(kind, tracks = ANIMATION_TRACKS) {
+ if (typeof kind !== 'string' || !kind) return [];
+ return Object.values(tracks).filter((row) => row.kinds.includes(kind));
+}
+
+/**
+ * True when a record of `kind` may carry the named track. A predicate, not a
+ * boundary: an unrecognized track id answers `false` rather than throwing,
+ * because the gates call this to DECIDE. The row is an O(1) lookup, so this
+ * asks it directly instead of rebuilding `tracksForKind`'s array to re-find it.
+ */
+export function kindSupportsTrack(kind, id, tracks = ANIMATION_TRACKS) {
+ if (!isAnimationTrack(id, tracks)) return false;
+ return typeof kind === 'string' && !!kind && tracks[id].kinds.includes(kind);
+}
+
+// Round-then-clamp, with unusable input (NaN, non-numeric) falling back to the
+// knob's default rather than to a bound — the two knobs differ only in which
+// three row fields they read.
+const clampInto = (n, min, max, fallback) => {
+ const v = Math.round(Number(n));
+ if (!Number.isFinite(v)) return fallback;
+ return Math.max(min, Math.min(max, v));
+};
+
+/**
+ * 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, 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/lib/spriteAnimationTracks.test.js
similarity index 95%
rename from server/services/sprites/animationTracks.test.js
rename to server/lib/spriteAnimationTracks.test.js
index c028db8078..76962df1a6 100644
--- a/server/services/sprites/animationTracks.test.js
+++ b/server/lib/spriteAnimationTracks.test.js
@@ -25,24 +25,28 @@ import {
isAnimationTrack, getAnimationTrack, clampTrackFrameCount, clampTrackFps,
assertAnimationTrackRows, trackRowCount, tracksForKind, kindSupportsTrack,
sourceReferenceFor, primaryTrackForKind,
-} from './animationTracks.js';
+} from './spriteAnimationTracks.js';
import {
getEffectiveAnimationTracks, getEffectiveAnimationTrackIds, animationTrackSeedPath,
-} from './animationTrackStore.js';
-import { SPRITE_RECORD_KINDS } from './recordsLogic.js';
-import { AMBIENT_TRACK_ROW } from './spriteTestFixtures.js';
+} from './spriteAnimationTrackStore.js';
+import { SPRITE_RECORD_KINDS } from '../services/sprites/recordsLogic.js';
+import { AMBIENT_TRACK_ROW } from '../services/sprites/spriteTestFixtures.js';
import {
staticImportSpecifiers, staticImportClosure, specifierMatchesPackage,
-} from '../../lib/staticImportGraph.js';
+} from './staticImportGraph.js';
import {
WALK_DEFAULT_FRAME_COUNT as CLIENT_DEFAULT_FRAME_COUNT,
WALK_DEFAULT_FPS as CLIENT_DEFAULT_FPS,
WALK_FRAME_COUNT_OPTIONS as CLIENT_FRAME_COUNT_OPTIONS,
walkFpsOptionsFor as clientWalkFpsOptionsFor,
-} from '../../../client/src/lib/spriteTrimmer.js';
+} from '../../client/src/lib/spriteTrimmer.js';
-const SPRITES_DIR = dirname(fileURLToPath(import.meta.url));
-const SERVER_DIR = dirname(dirname(SPRITES_DIR));
+// This suite moved to server/lib with the registry it covers (#4901), but it
+// still walks modules that stayed in services/sprites — so name both roots
+// explicitly rather than deriving one from the test's own location.
+const LIB_DIR = dirname(fileURLToPath(import.meta.url));
+const SERVER_DIR = dirname(LIB_DIR);
+const SPRITES_DIR = join(SERVER_DIR, 'services', 'sprites');
// The merged table this install actually serves — compiled `walk` plus the store
// rows, which on a machine that has authored its own tracks includes those too.
@@ -454,7 +458,7 @@ describe('per-track clamps', () => {
describe('walkBounds re-reads the walk row (no call-site churn)', () => {
it('exposes exactly the registry values under its historical export names', async () => {
- const bounds = await import('./walkBounds.js');
+ const bounds = await import('../services/sprites/walkBounds.js');
const row = getAnimationTrack(WALK_TRACK);
expect({
min: bounds.WALK_MIN_FRAME_COUNT,
@@ -474,7 +478,7 @@ describe('walkBounds re-reads the walk row (no call-site churn)', () => {
});
it('keeps clampFrameCount / clampFps behaving as the walk-track clamps', async () => {
- const { clampFrameCount, clampFps } = await import('./walkBounds.js');
+ const { clampFrameCount, clampFps } = await import('../services/sprites/walkBounds.js');
for (const n of [-1, 0, 5, 6, 11.6, 16, 99, 'nope', undefined, null]) {
expect(clampFrameCount(n)).toBe(clampTrackFrameCount(n, WALK_TRACK));
expect(clampFps(n)).toBe(clampTrackFps(n, WALK_TRACK));
@@ -494,12 +498,12 @@ describe('sharp-free leaf property', () => {
it.each([
['the request-validation graph', join(SERVER_DIR, 'lib', 'validation.js')],
- ['animationTracks.js', join(SPRITES_DIR, 'animationTracks.js')],
+ ['spriteAnimationTracks.js', join(LIB_DIR, 'spriteAnimationTracks.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')],
+ ['spriteAnimationTrackStore.js', join(LIB_DIR, 'spriteAnimationTrackStore.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
@@ -515,7 +519,7 @@ describe('sharp-free leaf property', () => {
});
it('keeps animationTracks.js a true leaf — it imports nothing at all', () => {
- expect(staticImportSpecifiers(join(SPRITES_DIR, 'animationTracks.js'))).toEqual([]);
+ expect(staticImportSpecifiers(join(LIB_DIR, 'spriteAnimationTracks.js'))).toEqual([]);
});
it('runs the store→leaf dependency ONE way (#3152)', () => {
@@ -525,10 +529,10 @@ describe('sharp-free leaf property', () => {
// 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'));
+ expect(staticImportSpecifiers(join(LIB_DIR, 'spriteAnimationTrackStore.js')))
+ .toContain('./spriteAnimationTracks.js');
+ const leafClosure = staticImportClosure(join(LIB_DIR, 'spriteAnimationTracks.js'));
+ expect([...leafClosure.files]).not.toContain(join(LIB_DIR, 'spriteAnimationTrackStore.js'));
});
it('actually walks the graph (positive control — the guard is not vacuous)', () => {
@@ -537,7 +541,7 @@ describe('sharp-free leaf property', () => {
// unresolvable specifier silently truncates it. Pin the first two against a
// module that genuinely reaches sharp.
const walkBounds = staticImportClosure(join(SPRITES_DIR, 'walkBounds.js'));
- expect([...walkBounds.files]).toContain(join(SPRITES_DIR, 'animationTracks.js'));
+ expect([...walkBounds.files]).toContain(join(LIB_DIR, 'spriteAnimationTracks.js'));
const packer = staticImportClosure(join(SPRITES_DIR, 'walkPostprocess.js'));
expect([...packer.packages], 'walkPostprocess is the native-graph module this split exists to fence off')
diff --git a/server/lib/spriteChromaKey.js b/server/lib/spriteChromaKey.js
new file mode 100644
index 0000000000..d9cc17b01f
--- /dev/null
+++ b/server/lib/spriteChromaKey.js
@@ -0,0 +1,183 @@
+/**
+ * Sprites — dynamic chroma-key selection (issue #2896, phase 2).
+ *
+ * The source pipeline hardcoded magenta because its one character wore green;
+ * per the #2895 decision the key is now picked per character from a FIXED set
+ * of three standard keys, by hue distance from the character's own palette
+ * (a green-clothed character keys on magenta; a pink one keys on green/blue).
+ *
+ * Pure module — palette extraction (sharp) lives in normalize.js; this file
+ * is just color math so it stays unit-testable and safe to import anywhere.
+ */
+
+export const CHROMA_KEYS = [
+ { hex: '#FF00FF', name: 'magenta', hue: 300 },
+ { hex: '#00FF00', name: 'green', hue: 120 },
+ { hex: '#0000FF', name: 'blue', hue: 240 },
+];
+
+export const CHROMA_KEY_HEXES = CHROMA_KEYS.map((k) => k.hex);
+
+// Magenta — the source pipeline's only key; the fallback wherever no key has
+// been selected yet (pre-lock generation, legacy imports).
+export const DEFAULT_CHROMA_KEY = CHROMA_KEYS[0].hex;
+
+// Below this hue separation (degrees) between the chosen key and the nearest
+// significant palette color, keying will likely eat character pixels — the
+// selection still returns the best key but carries a warning.
+export const MIN_HUE_SEPARATION = 60;
+
+export function hexToRgb(hex) {
+ const m = /^#?([0-9a-fA-F]{6})$/.exec(typeof hex === 'string' ? hex : '');
+ if (!m) throw new Error(`Invalid hex color: ${hex}`);
+ const n = parseInt(m[1], 16);
+ return { r: (n >> 16) & 0xff, g: (n >> 8) & 0xff, b: n & 0xff };
+}
+
+export function rgbToHsv(r, g, b) {
+ const rn = r / 255; const gn = g / 255; const bn = b / 255;
+ const max = Math.max(rn, gn, bn);
+ const min = Math.min(rn, gn, bn);
+ const delta = max - min;
+ let h = 0;
+ if (delta > 0) {
+ if (max === rn) h = 60 * (((gn - bn) / delta) % 6);
+ else if (max === gn) h = 60 * ((bn - rn) / delta + 2);
+ else h = 60 * ((rn - gn) / delta + 4);
+ if (h < 0) h += 360;
+ }
+ return { h, s: max === 0 ? 0 : delta / max, v: max };
+}
+
+export function hueDistance(a, b) {
+ const d = Math.abs(a - b) % 360;
+ return d > 180 ? 360 - d : d;
+}
+
+/**
+ * Pick the key whose hue is farthest from every significant color in the
+ * character's palette.
+ *
+ * `palette` is `[{ r, g, b, count }]` (see extractForegroundPalette). Colors
+ * below the saturation/value floors are ignored — near-grays and near-blacks
+ * have no meaningful hue and never conflict with a saturated key; colors
+ * below `minCountFrac` of the total are single-pixel noise.
+ *
+ * Returns `{ hex, name, minHueDistance, warning }` — never null; a fully
+ * achromatic palette conflicts with nothing, so the first key (magenta, the
+ * legacy default) wins with distance Infinity.
+ */
+function significantHues(palette, { minCountFrac = 0.005, minSaturation = 0.25, minValue = 0.15 } = {}) {
+ const entries = Array.isArray(palette) ? palette : [];
+ const total = entries.reduce((sum, e) => sum + (e.count || 0), 0);
+ return entries
+ .map((e) => ({ ...rgbToHsv(e.r, e.g, e.b), count: e.count || 0 }))
+ .filter((c) => c.count >= total * minCountFrac && c.s >= minSaturation && c.v >= minValue);
+}
+
+/**
+ * Warn when the character's surviving palette sits close in hue to the key
+ * it was GENERATED on: the normalize mask has already discarded any pixel
+ * within the luma threshold of that key, so near-key palette colors imply
+ * exact-key details (a magenta garment on the magenta default) may have been
+ * silently clipped from the immutable locked artifact. Returns a warning
+ * string or null.
+ */
+export function keyProximityWarning(palette, keyHex, { role = 'generation', ...opts } = {}) {
+ const { r, g, b } = hexToRgb(keyHex);
+ const keyHue = rgbToHsv(r, g, b).h;
+ const significant = significantHues(palette, opts);
+ if (!significant.length) return null;
+ const minDist = Math.min(...significant.map((c) => hueDistance(keyHue, c.h)));
+ if (minDist >= MIN_HUE_SEPARATION) return null;
+ // `selected` = the key the artifact will be COMPOSITED onto (runtime keying
+ // would clip character pixels); `generation` = the key it was RENDERED on
+ // (exact-key details are already gone from the mask).
+ return role === 'selected'
+ ? `Character palette sits within ${Math.round(minDist)}° of the selected key ${keyHex} — runtime keying on it would clip character pixels; pick a different key before locking`
+ : `Character palette sits within ${Math.round(minDist)}° of the generation key ${keyHex} — exact-key details may have been clipped by the mask; consider pinning a different key and regenerating before locking`;
+}
+
+/**
+ * Split a key color into its saturated ("high", 255) and dark ("low", 0)
+ * channel indices — the structure every key-parameterized un-key/despill
+ * formula in walkPostprocess.js is written against. The source pipeline
+ * hardcoded magenta (highs r+b, low g); the three standard keys are all
+ * pure-channel colors, so highs/lows fully describe them:
+ * magenta → highs [0,2], lows [1]
+ * green → highs [1], lows [0,2]
+ * blue → highs [2], lows [0,1]
+ * Channel indices are 0=r, 1=g, 2=b into an RGB(A) pixel.
+ */
+export function keyChannelSplit(hex) {
+ const { r, g, b } = hexToRgb(hex);
+ const values = [r, g, b];
+ const highs = [];
+ const lows = [];
+ values.forEach((v, i) => (v >= 128 ? highs : lows).push(i));
+ if (!highs.length || !lows.length) throw new Error(`Not a usable chroma key: ${hex}`);
+ return { rgb: values, highs, lows };
+}
+
+/**
+ * How key-like a pixel is: min(high channels) − max(low channels).
+ * Positive = the pixel leans toward the key color. For magenta this is the
+ * source pipeline's `min(r,b) − g` exactly.
+ */
+export function keyness(pixel, split) {
+ let minHigh = 255;
+ for (const h of split.highs) minHigh = Math.min(minHigh, pixel[h]);
+ let maxLow = 0;
+ for (const l of split.lows) maxLow = Math.max(maxLow, pixel[l]);
+ return minHigh - maxLow;
+}
+
+/**
+ * Build the per-pixel background-key "share" sampler for a key: the fraction of
+ * a pixel that is the key color, reversing anti-aliased source-over-key
+ * compositing. Measured as the min over the key's (high, low) channel pairs of
+ * (pixel[high] − pixel[low]) / (key[high] − key[low]), clamped to [0, 1] — a
+ * pure-key pixel scores 1, a pixel unlike the key scores 0, an anti-aliased
+ * blend lands in between (the exact weight of the key still contaminating it).
+ *
+ * `keyRgb` is the key as `[r, g, b]` (a nominal key OR a measured border key);
+ * `split` is its keyChannelSplit. The returned sampler reads channels from
+ * `arr` at `base + channelIndex`, so one factory serves both a 3-element pixel
+ * array (`base` 0) and a flat RGB/RGBA buffer (`base` = pixelIndex * channels).
+ * The (high, low) pairs and their spans are precomputed once per key so the
+ * hot per-pixel path only does the reads, subtracts, and min.
+ */
+export function keyShareFn(keyRgb, split) {
+ const pairs = [];
+ for (const h of split.highs) {
+ for (const l of split.lows) pairs.push([h, l, Math.max(1, keyRgb[h] - keyRgb[l])]);
+ }
+ return (arr, base = 0) => {
+ let s = Infinity;
+ for (const [h, l, span] of pairs) {
+ const v = (arr[base + h] - arr[base + l]) / span;
+ if (v < s) s = v;
+ }
+ return s < 0 ? 0 : s > 1 ? 1 : s;
+ };
+}
+
+export function pickChromaKey(palette, opts = {}) {
+ const significant = significantHues(palette, opts);
+
+ let best = null;
+ for (const key of CHROMA_KEYS) {
+ const minDist = significant.length
+ ? Math.min(...significant.map((c) => hueDistance(key.hue, c.h)))
+ : Infinity;
+ if (!best || minDist > best.minHueDistance) {
+ best = { hex: key.hex, name: key.name, minHueDistance: minDist };
+ }
+ }
+ return {
+ ...best,
+ warning: best.minHueDistance < MIN_HUE_SEPARATION
+ ? `Closest palette hue is within ${Math.round(best.minHueDistance)}° of the ${best.name} key — keying may clip character pixels`
+ : null,
+ };
+}
diff --git a/server/services/sprites/chromaKey.test.js b/server/lib/spriteChromaKey.test.js
similarity index 99%
rename from server/services/sprites/chromaKey.test.js
rename to server/lib/spriteChromaKey.test.js
index 1316c1fb0b..15b145db9b 100644
--- a/server/services/sprites/chromaKey.test.js
+++ b/server/lib/spriteChromaKey.test.js
@@ -3,7 +3,7 @@ import {
CHROMA_KEYS, CHROMA_KEY_HEXES, MIN_HUE_SEPARATION,
rgbToHsv, hueDistance, pickChromaKey, keyProximityWarning,
keyChannelSplit, keyShareFn,
-} from './chromaKey.js';
+} from './spriteChromaKey.js';
describe('chroma key set', () => {
it('is exactly the three standard keys', () => {
diff --git a/server/lib/spriteValidation.js b/server/lib/spriteValidation.js
index 25cac8734a..ac70a0ac02 100644
--- a/server/lib/spriteValidation.js
+++ b/server/lib/spriteValidation.js
@@ -1,11 +1,12 @@
import { z } from 'zod';
-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 { ANIMATION_PROVIDER_IDS } from '../services/sprites/animationWorkflow.js';
+import {
+ SPRITE_ID_PATTERN, SPRITE_RECORD_KINDS, ANCHOR_DIRECTIONS, SPRITE_DIRECTIONS,
+ TURNAROUND_ID, ANIMATION_PROVIDER_IDS,
+} from './spriteVocabulary.js';
+import { CHROMA_KEY_HEXES } from './spriteChromaKey.js';
import {
WALK_TRACK, AUTHORED_TRACK_FIELDS, TRACK_BOUND_TRIPLES,
-} from '../services/sprites/animationTracks.js';
+} from './spriteAnimationTracks.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
@@ -13,8 +14,9 @@ import {
// schemas below stay module-load constants rather than becoming lazily-built.
import {
effectiveTrack, getEffectiveAnimationTracks, getEffectiveAnimationTrackIds,
-} from '../services/sprites/animationTrackStore.js';
-import { QUEUEABLE_IMAGE_MODES } from '../services/imageGen/modes.js';
+} from './spriteAnimationTrackStore.js';
+// From lib since #5021 — the generation-mode alphabets live below validation.
+import { QUEUEABLE_IMAGE_MODES } from './generationModes.js';
import { RECORD_RENDER_MODEL_MAX } from './renderTargets.js';
import {
cloudModelIdString, grokVideoDurationSchema, isSafeSubdirFilter, recordRenderPinFields,
diff --git a/server/lib/spriteVocabulary.js b/server/lib/spriteVocabulary.js
new file mode 100644
index 0000000000..401574578f
--- /dev/null
+++ b/server/lib/spriteVocabulary.js
@@ -0,0 +1,37 @@
+/**
+ * Sprite identifier and direction vocabulary.
+ *
+ * The alphabets the sprite route schemas enumerate, kept below both validation
+ * and the sprite services so `lib/spriteValidation.js` can name a direction or a
+ * record kind without importing service orchestration (issue #4901). Each
+ * constant was defined beside the logic that consumes it; the owning service
+ * modules re-export from here, so those call sites are unchanged.
+ *
+ * A leaf module (no imports).
+ */
+
+// Sprite record ids: lowercase kebab, 1–64 chars, must start alphanumeric.
+export const SPRITE_ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}$/;
+
+export const SPRITE_RECORD_KINDS = ['character', 'place', 'object', 'props'];
+
+// Canonical 8-direction order (the source pipeline's RUNTIME_DIRECTION_ORDER)
+// — atlas row order in later phases depends on this, so keep it stable.
+export const SPRITE_DIRECTIONS = [
+ 'south',
+ 'south-east',
+ 'east',
+ 'north-east',
+ 'north',
+ 'north-west',
+ 'west',
+ 'south-west',
+];
+
+// Directions that get a derived anchor. `south` is never generated — the
+// frozen main reference IS the south anchor.
+export const ANCHOR_DIRECTIONS = SPRITE_DIRECTIONS.filter((d) => d !== 'south');
+
+export const TURNAROUND_ID = 'turnaround';
+
+export const ANIMATION_PROVIDER_IDS = Object.freeze(['grok', 'local']);
diff --git a/server/services/sprites/animationTargets.test.js b/server/services/sprites/animationTargets.test.js
index 2e8dc7dccf..2785bf2b3e 100644
--- a/server/services/sprites/animationTargets.test.js
+++ b/server/services/sprites/animationTargets.test.js
@@ -99,9 +99,14 @@ describe('resolveAnimationTarget precedence', () => {
// other track's contract key. Only one track exists today, so stand up a
// null-fps row via a scoped module mock to keep that branch covered.
vi.resetModules();
- const real = await vi.importActual('./animationTracks.js');
+ // Mock the LIB registry, not the services/sprites re-export shim: the row
+ // this resolver sees comes from animationTrackStore.js, which imports
+ // lib/spriteAnimationTracks.js directly (#4901). Mocking the shim would
+ // leave the store reading the real table and silently un-discriminate this
+ // test.
+ const real = await vi.importActual('../../lib/spriteAnimationTracks.js');
const nullFpsRow = { ...real.ANIMATION_TRACKS.walk, contractFpsField: null };
- vi.doMock('./animationTracks.js', () => ({
+ vi.doMock('../../lib/spriteAnimationTracks.js', () => ({
...real,
ANIMATION_TRACKS: { walk: nullFpsRow },
getAnimationTrack: (id) => {
@@ -117,7 +122,7 @@ describe('resolveAnimationTarget precedence', () => {
expect(resolveWithNullFps({
runtimeContract: { walkFrameCount: 16, walkFps: 24, null: 24 },
})).toMatchObject({ frameCount: 16, fps: 10, source: 'app', fpsLocked: false });
- vi.doUnmock('./animationTracks.js');
+ vi.doUnmock('../../lib/spriteAnimationTracks.js');
vi.resetModules();
});
diff --git a/server/services/sprites/animationTrackStore.js b/server/services/sprites/animationTrackStore.js
index 12b78f041a..7ae9c450e4 100644
--- a/server/services/sprites/animationTrackStore.js
+++ b/server/services/sprites/animationTrackStore.js
@@ -1,275 +1,9 @@
/**
- * 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. The memo holds the MERGED table (never `null` once
- * resolved, since `walk` is always in it), so a zero-row install caches too rather
- * than re-reading on every lookup.
+ * Re-export shim. The effective-track store moved to
+ * `lib/spriteAnimationTrackStore.js` so the sprite route schemas can stay
+ * module-load constants without importing upward into services (issue #4901).
+ * It reads one small JSON config through lib/fileUtils and depends on no
+ * service. Existing deep imports keep working.
*/
-import { readFileSync } from 'fs';
-import { join } from 'path';
-import { PATHS } from '../../lib/fileUtils.js';
-import {
- ANIMATION_TRACKS, WALK_TRACK, assertAnimationTrackRows, getAnimationTrack,
-} from './animationTracks.js';
-
-/** The store file, relative to `data/` (and to `data.reference/` for the seed). */
-export const ANIMATION_TRACK_STORE_REL = 'sprites/animation-tracks.json';
-/** 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);
-
-// The merged table — `null` until first resolve. ONE cache, on the merged result
-// rather than also on the raw rows: `assertAnimationTrackRows` runs over the merge,
-// so memoizing the raw read too would only pin a row set that failed validation,
-// and a user who then fixed their JSON would keep getting the stale error.
-let cachedEffectiveTracks = null;
-
-/**
- * Which of the three failure kinds a read error is:
- *
- * `absent` — ENOENT. Nothing there; try the next candidate.
- * `io-error` — any other errno. A real, user-facing problem: report it.
- * `no-filesystem` — NO errno at all, so the call never reached a filesystem.
- * See `resolveStoreDoc`'s header for the environment that
- * produces this and why it degrades instead of throwing.
- *
- * Exported so the classification is asserted directly (`animationTrackStore.test.js`):
- * this module binds `readFileSync` at import, so a test that re-mocked `fs` would not
- * intercept it and would pass without exercising anything.
- */
-export function classifyStoreReadError(err) {
- if (!err?.code) return 'no-filesystem';
- return err.code === 'ENOENT' ? 'absent' : 'io-error';
-}
-
-/**
- * Read one candidate store file. Returns `null` for "not there" (try the next
- * candidate) and THROWS for "there but unreadable" — the sentinel rule: a corrupt
- * store must not silently degrade to the seed, or a user whose edits broke the JSON
- * would see their tracks quietly revert to shipped defaults with no error to
- * explain it.
- */
-function readStoreDoc(path) {
- let raw;
- try {
- raw = readFileSync(path, 'utf-8');
- } catch (err) {
- const kind = classifyStoreReadError(err);
- if (kind === 'absent') return null;
- // A `no-filesystem` error is re-thrown BARE for `resolveStoreDoc` to read as
- // "no store", rather than dressed up as an unreadable file the user would go
- // looking for. Only a real errno becomes this module's own named error.
- if (kind === 'no-filesystem') throw err;
- 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}`);
- }
-}
-
-/**
- * The authoritative store doc: the user copy if it exists, else the shipped seed,
- * else `null` (walk alone).
- *
- * **Why the whole resolution is guarded.** `server/lib/validation.js` builds its
- * sprite Zod ranges from the effective registry AT MODULE LOAD, and nearly every
- * route and service imports `validation.js`. So this runs inside test suites that
- * have nothing to do with sprites — including ones that legitimately stub the
- * filesystem with a partial factory (`vi.mock('fs', () => ({ existsSync }))`, or a
- * `fileUtils.js` double exporting no `PATHS`). In that environment there is no
- * filesystem to consult, and the honest answer is "no store" — walk alone — not a
- * hard import-time failure over a file the suite never asked about.
- *
- * Scoped deliberately to the *environment* being unusable, never to a real read
- * failure: `readStoreDoc` still throws on a store that exists but won't parse,
- * because that is a user's broken hand edit and silently reverting to shipped
- * defaults is the sentinel violation this module's header calls out. A TypeError
- * from a missing mock export cannot reach a real install — an install always has
- * `fs` and `PATHS`.
- */
-function resolveStoreDoc() {
- try {
- return readStoreDoc(animationTrackStorePath()) ?? readStoreDoc(animationTrackSeedPath());
- } catch (err) {
- // Rethrow anything that came from an actual file: those carry this module's
- // own prefix (unreadable / not-valid-JSON) and must stay loud.
- if (err?.message?.startsWith(ANIMATION_TRACK_STORE_REL)) throw err;
- return null;
- }
-}
-
-/**
- * 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() {
- const doc = resolveStoreDoc();
- 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);
- }
- return Object.freeze(byId);
-}
-
-/**
- * The compiled table merged with the user-defined store: `{ walk, …stored }`.
- *
- * **SYNCHRONOUS, and never a Promise** — this is safe to use as a default
- * parameter (`tracks = getEffectiveAnimationTracks()`), which is how atlas.js,
- * atlasGrid.js, atlasLayout.js and walkFrames.js consume it. The header explains
- * why sync is required rather than merely convenient; stated again here because a
- * reader (or a reviewer) landing on one of those default params sees only the call.
- *
- * **`walk` is always present**, on every path — it comes from the compiled table,
- * not the store, so an absent/empty/deleted store yields `{ walk }` rather than
- * `{}`. A caller resolving `WALK_TRACK` can never miss.
- *
- * 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());
-}
-
-/**
- * One row out of the effective table — `getAnimationTrack(id, getEffectiveAnimationTracks())`,
- * which was being spelled out at a dozen call sites.
- *
- * Keeps `getAnimationTrack`'s exact boundary — it IS that call, just named:
- * an absent id (`undefined`/`null`) resolves to `walk`, and an unrecognized one
- * **THROWS** naming the known tracks. It never returns `undefined`, so callers
- * dereference `.id`/`.label`/bounds on the result without a guard (as every call
- * site does). Modules that must work against an injected table still call
- * `getAnimationTrack(id, tracks)` directly; that parameter is the test seam and is
- * deliberately untouched.
- */
-export function effectiveTrack(id) {
- return getAnimationTrack(id, getEffectiveAnimationTracks());
-}
-
-/**
- * Drop the cached store read.
- *
- * 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() {
- cachedEffectiveTracks = null;
-}
+export * from '../../lib/spriteAnimationTrackStore.js';
diff --git a/server/services/sprites/animationTracks.js b/server/services/sprites/animationTracks.js
index 82f9c735e7..ab3b81e1d0 100644
--- a/server/services/sprites/animationTracks.js
+++ b/server/services/sprites/animationTracks.js
@@ -1,501 +1,7 @@
/**
- * Sprites — the animation-track registry (issue #3015).
- *
- * Frame-count and fps bounds used to be GLOBAL and walk-shaped: one 6–16 /
- * 4–24 range applied to every animation, because the walk cycle was the only
- * animation that existed. #2985 made the persisted target *track-keyed*
- * (`animationTargets.walk`), but nothing described what tracks exist or what
- * each one's legal range is — so a 3-frame ambient loop (a tree in the wind)
- * was unrepresentable. The shipped 4-frame scanner action proves the registry
- * supports a real non-walk range below walk's floor.
- *
- * This module is that description. One row per known track carries its own
- * bounds, defaults, directionality, and the `runtimeContract` field names it
- * occupies — so adding a track is a row here plus its pipeline, never a hunt
- * for hard-coded 6/16 literals. `walk` is the first and (today) only row and
- * reproduces its historical values exactly; `walkBounds.js` now re-reads this
- * row rather than defining the range itself.
- *
- * **Sharp-free leaf, deliberately.** `server/lib/validation.js` builds its Zod
- * ranges from these rows and must not drag the native image graph
- * (sharp/ffmpeg, via walkPostprocess) into the request-validation graph — the
- * same split walkBounds.js was created for, now one level deeper. This module
- * imports NOTHING. `animationTracks.test.js` asserts that transitively.
- *
- * **Unknown track ids are an error, not a fallback.** `getAnimationTrack('nope')`
- * throws instead of quietly handing back walk's range — a mis-keyed track that
- * silently validated against walk's 6–16 would let a 4-frame action be rejected
- * for reasons no message explains. Absent (`undefined`/`null`) means "the
- * default track" and resolves to `walk`, which is what preserves every existing
- * call site; an empty string is *present and invalid*, so it throws.
- *
- * **Which records may carry a track is registry data too (#3017).** The whole
- * sprite animation surface used to be gated on a literal `kind !== 'character'`
- * check, which is why `place` and `object` records had no animation path at all
- * — a tree in the wind or a flickering lamp was unrepresentable not because the
- * atlas couldn't hold it but because the gate refused the record. Each row now
- * declares the record `kinds` that may carry it, and the gates ask the registry
- * (`tracksForKind` / `kindSupportsTrack`) instead of naming a kind. Walk stays
- * character-only, so behavior is unchanged today; a row that lists `place` is
- * all it takes to unlock those records, with no gate edit anywhere.
- *
- * **The per-track WORKFLOW is registry data too (#3136).** `scanner` and
- * `ambient` each shipped as a ~300-line clone of walk's state/start/package/
- * approve/invalidate stack — identical control flow differing only in which
- * reference image seeds the render, what the on-disk selection/set files are
- * called, and which prompt text goes to the provider. Those differences are now
- * either FIELDS on the row (`selectionKind`/`setKind`) or derived from one
- * (`directional` decides both the facing count and which locked reference seeds
- * 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.
+ * Re-export shim. The animation-track registry moved to
+ * `lib/spriteAnimationTracks.js` — a zero-import table of constants that route
+ * validation reads directly (issue #4901). Existing deep imports keep working.
*/
-/** The default track — and the only one compiled into this build (#3152). */
-export const WALK_TRACK = 'walk';
-/**
- * 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';
-export const AMBIENT_TRACK = 'ambient';
-
-/**
- * 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.
- * - `defaultFrameCount` / `defaultFps` — the bottom rung of the target
- * precedence chain (see `animationTargets.js`).
- * - `directional` — true when the track occupies one atlas ROW per facing
- * (walk: 8 directions); a future ambient loop would be false (one row).
- * Load-bearing since #3017: `trackRowCount` turns it into the number of rows
- * the track's cells may occupy, and the compiler refuses a cell outside them.
- * - `kinds` — the sprite record kinds that may carry this track. The animation
- * gates read this instead of testing for `'character'`, so unlocking a record
- * kind is a data change here rather than a hunt through the service layer.
- * - `contractFrameCountField` / `contractFpsField` — the field names this track
- * occupies in an app's `publishBinding.runtimeContract` (#2982). Named here so
- * the app rung of the precedence chain is track-driven rather than hard-coded
- * to `walkFrameCount`. `contractFpsField` may be `null` for a track whose
- * speed an app has no say in.
- * - `selectionKind` / `setKind` (#3136) — the `kind` discriminators the track's
- * on-disk review selection and finalized set carry. Registry data because the
- * atlas compiler VALIDATES them (`atlas.js`), so a track's on-disk contract
- * and the compiler's expectation cannot drift.
- * - `finalErrorCode` (#3136) — the `code` on the 409 a finalized set answers
- * generate/approve with. Named per row so an existing client that matches on
- * `SCANNER_SET_FINAL` keeps working after the clone collapsed.
- * - `standaloneContract` (#3136) — true when this track's frame count is enough
- * ON ITS OWN to describe a publishable atlas, because a record can be
- * published with only this track authored. Walk (a character's baseline) and
- * ambient (a place's) qualify; a short ACTION like scanner always rides beside
- * the walk it shares rows with, so pinning only its span describes no atlas
- * 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
- * facing's own anchor (`sourceReferenceFor` below), while a non-directional one
- * has no per-facing anchor and seeds from the single locked main. Stating it as
- * a field would let a row claim a pairing that cannot work.
- */
-export const ANIMATION_TRACKS = Object.freeze({
- [WALK_TRACK]: Object.freeze({
- id: WALK_TRACK,
- label: 'Walk cycle',
- directional: true,
- // A walk cycle is a character gait — a place or an object has no gait to
- // author, so walk stays character-only and every existing gate keeps its
- // exact behavior. What changed in #3017 is only WHERE that fact lives.
- kinds: Object.freeze(['character']),
- minFrameCount: 6,
- maxFrameCount: 16,
- defaultFrameCount: 12,
- minFps: 4,
- maxFps: 24,
- defaultFps: 10,
- contractFrameCountField: 'walkFrameCount',
- // `spriteRuntimeContractSchema` deliberately declares no fps key (a
- // distance-driven consumer has no animation-fps concept), so today this is
- // reachable only by a legacy/hand-built contract object — kept, not
- // nulled, because dropping it would change resolution behavior for those.
- // A second track copying this row should decide its own answer.
- contractFpsField: 'walkFps',
- // Walk predates the generic workflow and keeps its own bespoke service
- // (walk.js — reprocess, trims, per-direction reopen, source-frame
- // extraction, set-level targets), so these describe its on-disk contract
- // for the compiler's benefit without routing it through the generic module.
- selectionKind: 'reviewed-directional-walk-selection',
- setKind: 'finalized-eight-direction-walk-set',
- finalErrorCode: 'WALK_SET_FINAL',
- // A character publishes off its walk — the compile path requires a finalized
- // walk set before it emits anything at all.
- 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,
- }),
-});
-
-// There is deliberately no `ANIMATION_TRACK_IDS` export (#3152 removed it). It
-// would now mean "the COMPILED ids" — `['walk']` — while reading as "every track
-// id", which is the wrong answer at every call site that wanted it: those want the
-// merged table's ids and must ask `getEffectiveAnimationTrackIds()` in
-// `animationTrackStore.js`. Iterate `Object.keys(ANIMATION_TRACKS)` inline when you
-// genuinely mean the compiled rows only.
-
-/**
- * The min/default/max triples every row must keep in order.
- *
- * Exported because three places need this exact pairing and had each spelled their
- * own copy: the assert below, the request schemas in `server/lib/validation.js`
- * (which front-run the assert so the form gets a per-field 400), and the client's
- * pre-submit check. A fourth knob added to one copy and missed in another is the
- * drift this prevents.
- */
-export const TRACK_BOUND_TRIPLES = Object.freeze([
- Object.freeze(['minFrameCount', 'defaultFrameCount', 'maxFrameCount']),
- Object.freeze(['minFps', 'defaultFps', 'maxFps']),
-]);
-
-/**
- * The fields of a row a USER authors, as opposed to the ones PortOS derives.
- *
- * The complement is deliberate and load-bearing: everything NOT listed here
- * (`contractFrameCountField`, `contractFpsField`, `selectionKind`, `setKind`,
- * `finalErrorCode`, `standaloneContract`, `builtin`) names a file on disk, a
- * publish-contract key, or a cross-row invariant that `assertAnimationTrackRows`
- * requires to be globally unique — so it is derived from the id rather than typed
- * (see `animationTrackCrud.js`). Named here, beside the assert that validates the
- * whole row, so the request schema and the service's whitelist build from ONE list
- * instead of two that fail in opposite directions when they drift: a field in the
- * schema but not the whitelist validates and is then silently dropped, and one in
- * the whitelist but not the schema is rejected as an unrecognized key.
- */
-export const AUTHORED_TRACK_FIELDS = Object.freeze([
- 'label', 'directional', 'kinds',
- 'minFrameCount', 'maxFrameCount', 'defaultFrameCount',
- 'minFps', 'maxFps', 'defaultFps',
- 'promptTemplate',
-]);
-
-/**
- * The five on-disk / publish-contract discriminators a track's id determines, plus
- * the `contractFpsField` a user-defined row always declines.
- *
- * Derived rather than typed because `assertAnimationTrackRows` requires each to be
- * globally unique and they name artifacts the atlas compiler re-verifies — a typo in
- * one would hand this track another's evidence chain. Lives here, beside that
- * assert, so one module knows a row's whole shape.
- *
- * `contractFpsField` is `null` to match both seeded rows: PortOS's fps is
- * preview-only (a distance-driven consumer owns its timing), so a new track claiming
- * an fps contract key would offer the app a knob nothing reads.
- */
-export function deriveTrackFields(id) {
- const camel = id.replace(/-([a-z0-9])/g, (_m, c) => c.toUpperCase());
- return {
- contractFrameCountField: `${camel}FrameCount`,
- contractFpsField: null,
- selectionKind: `reviewed-${id}-selection`,
- setKind: `finalized-${id}-set`,
- finalErrorCode: `${id.replace(/-/g, '_').toUpperCase()}_SET_FINAL`,
- };
-}
-
-/**
- * Validate a registry's rows, throwing on the first violation.
- *
- * Called at module load below (the navManifest.js / catalogTypes.js idiom): a
- * row missing a bound would otherwise boot clean and surface much later as
- * `NaN` out of a Math.min, or as `z.number().min(undefined)` throwing at the
- * first sprite render. A bad row should block boot with a message naming the
- * field, not corrupt a render hours later.
- *
- * Exported and pure — taking the table as an argument — so the guard can be
- * proven against a synthetic multi-row fixture. Asserting set-uniqueness over
- * the real (currently single-row) table would only re-derive the
- * implementation: the whole guard could be deleted and such a test would stay
- * green, which is exactly the regression it exists to prevent.
- */
-export function assertAnimationTrackRows(tracks) {
- const claimedContractFields = new Map();
- const claimedOnDiskKinds = new Map();
- for (const id of Object.keys(tracks)) {
- const row = tracks[id];
- if (row.id !== id) throw new Error(`animationTracks: row '${id}' declares mismatched id '${row.id}'`);
- if (typeof row.label !== 'string' || !row.label) throw new Error(`animationTracks: track '${id}' needs a label`);
- if (typeof row.directional !== 'boolean') throw new Error(`animationTracks: track '${id}' needs a boolean 'directional'`);
- // A row with no kinds is unreachable work: nothing could ever carry it, and
- // the gate would refuse every record with a message blaming the record.
- if (!Array.isArray(row.kinds) || !row.kinds.length) {
- throw new Error(`animationTracks: track '${id}' needs a non-empty 'kinds' array`);
- }
- if (row.kinds.some((kind) => typeof kind !== 'string' || !kind)) {
- throw new Error(`animationTracks: track '${id}' has a non-string entry in 'kinds'`);
- }
- for (const field of ['minFrameCount', 'maxFrameCount', 'defaultFrameCount', 'minFps', 'maxFps', 'defaultFps']) {
- if (!Number.isInteger(row[field])) throw new Error(`animationTracks: track '${id}' needs an integer '${field}'`);
- }
- if (typeof row.contractFrameCountField !== 'string' || !row.contractFrameCountField) {
- throw new Error(`animationTracks: track '${id}' needs a contractFrameCountField`);
- }
- if (row.contractFpsField !== null && (typeof row.contractFpsField !== 'string' || !row.contractFpsField)) {
- throw new Error(`animationTracks: track '${id}' needs a contractFpsField (or null)`);
- }
- // #3136 — the workflow shape.
- for (const field of ['selectionKind', 'setKind', 'finalErrorCode']) {
- if (typeof row[field] !== 'string' || !row[field]) {
- throw new Error(`animationTracks: track '${id}' needs a non-empty '${field}'`);
- }
- }
- 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'`);
- }
- // EXACTLY ONE prompt source per row — the invariant, stated as itself rather
- // than as two provenance checks. A row's prompt is either the compiled builder
- // `trackPrompts.js` holds for it (`builtin`, no template) or its own
- // `promptTemplate` (stored). Neither means a throw out of `buildTrackVideoPrompt`
- // AFTER the user clicked generate; both means two definitions of one track's
- // wording, where the stored value silently wins over the text
- // `prompts.test.js` pins. Refuse either at load, where the message names the row.
- const hasTemplate = typeof row.promptTemplate === 'string' && !!row.promptTemplate.trim();
- if (hasTemplate === row.builtin) {
- throw new Error(
- row.builtin
- ? `animationTracks: builtin track '${id}' must not carry a 'promptTemplate' — its prompt is the compiled builder`
- : `animationTracks: user-defined track '${id}' needs a non-empty 'promptTemplate'`,
- );
- }
- // Two tracks sharing a selection/set `kind` is the same class of bug as two
- // sharing a contract field: the compiler validates a set by its `kind`, so a
- // duplicate would let one track's finalized set satisfy the other's evidence
- // check and compile the wrong frames into its span.
- for (const knob of ['selectionKind', 'setKind']) {
- const owner = claimedOnDiskKinds.get(row[knob]);
- if (owner) {
- throw new Error(
- `animationTracks: on-disk kind '${row[knob]}' is claimed by both '${owner.id}.${owner.knob}' and '${id}.${knob}'`,
- );
- }
- claimedOnDiskKinds.set(row[knob], { id, knob });
- }
- for (const [min, def, max] of TRACK_BOUND_TRIPLES) {
- if (!(row[min] <= row[def] && row[def] <= row[max])) {
- throw new Error(`animationTracks: track '${id}' needs ${min} <= ${def} <= ${max}`);
- }
- }
- // Two tracks must not claim the same runtimeContract field. The anticipated
- // failure is a second row copy-pasted from walk's: `resolveAnimationTarget`
- // would then read the WALK's `walkFrameCount` for that track and, whenever
- // that value happens to land inside its range, return it with
- // `frameCountLocked: true` — silently pinning one track to another's
- // contract and throwing a lock error citing a binding that never mentioned
- // it. The knob name rides along so a row that names ONE field for BOTH of
- // its knobs doesn't report as "claimed by both 'walk' and 'walk'".
- for (const knob of ['contractFrameCountField', 'contractFpsField']) {
- const field = row[knob];
- if (field === null) continue;
- const owner = claimedContractFields.get(field);
- if (owner) {
- throw new Error(
- `animationTracks: contract field '${field}' is claimed by both '${owner.id}.${owner.knob}' and '${id}.${knob}'`,
- );
- }
- claimedContractFields.set(field, { id, knob });
- }
- }
- // Every record kind any row admits must have EXACTLY ONE standalone track —
- // the baseline it publishes off. Zero means a record of that kind can be
- // authored but never publish (its runtime contract could name no required
- // field, and the compiler has no evidence chain to require); more than one
- // means "which set must be finalized before compiling?" has two answers. This
- // is a cross-row invariant, so it runs after the per-row loop.
- const standaloneByKind = new Map();
- for (const id of Object.keys(tracks)) {
- if (!tracks[id].standaloneContract) continue;
- for (const kind of tracks[id].kinds) {
- standaloneByKind.set(kind, [...(standaloneByKind.get(kind) || []), id]);
- }
- }
- for (const id of Object.keys(tracks)) {
- for (const kind of tracks[id].kinds) {
- const owners = standaloneByKind.get(kind) || [];
- if (owners.length !== 1) {
- throw new Error(
- `animationTracks: record kind '${kind}' needs exactly one standaloneContract track, has ${owners.length}${owners.length ? ` (${owners.join(', ')})` : ''}`,
- );
- }
- }
- }
-}
-
-assertAnimationTrackRows(ANIMATION_TRACKS);
-
-/**
- * The locked reference artifact a track's image-to-video render is seeded from:
- * `'anchor'` (this facing's own locked directional anchor) or `'main'` (the one
- * locked main reference).
- *
- * DERIVED from `directional` rather than declared, because only one pairing can
- * work. A directional track renders one clip per facing, so seeding all eight
- * rows from the single main would render the same south-facing clip eight times
- * and pass every later check — nothing downstream re-reads which facing was
- * asked for. The inverse has no anchor to read at all: a place record never
- * generates directional anchors.
- */
-export function sourceReferenceFor(id, tracks = ANIMATION_TRACKS) {
- return getAnimationTrack(id, tracks).directional ? 'anchor' : 'main';
-}
-
-/**
- * The one track a record of `kind` publishes off — its baseline, whose finalized
- * set the compile path requires and whose frame count alone is a valid runtime
- * contract. `null` for a kind no row admits.
- *
- * One definition, asked by the publish-contract schema (which field is required)
- * and the compile dispatch (which evidence chain to validate). Those two used to
- * answer it separately — one by registration order, one as
- * `ambient-and-not-walk` — and agreed only by coincidence.
- */
-export function primaryTrackForKind(kind, tracks = ANIMATION_TRACKS) {
- if (typeof kind !== 'string' || !kind) return null;
- return Object.values(tracks).find((row) => row.standaloneContract && row.kinds.includes(kind)) || null;
-}
-
-/** True when `id` names a track in `tracks` (the shipped registry by default). */
-export function isAnimationTrack(id, tracks = ANIMATION_TRACKS) {
- return typeof id === 'string' && Object.prototype.hasOwnProperty.call(tracks, id);
-}
-
-/**
- * The registry row for `id`. Absent (`undefined`/`null`) resolves to the default
- * track; anything else unrecognized THROWS rather than falling back, so a typo
- * can never be validated against walk's range by accident.
- *
- * The table is a parameter — the same idiom `assertAnimationTrackRows(tracks)`
- * uses — so a caller that must work across a *set* of tracks (the atlas grid,
- * #3016) can be exercised against a synthetic multi-row table while the shipped
- * registry has one row, WITHOUT that caller growing a private lookup that
- * bypasses this unknown-id boundary.
- */
-export function getAnimationTrack(id, tracks = ANIMATION_TRACKS) {
- const key = id === undefined || id === null ? WALK_TRACK : id;
- if (!isAnimationTrack(key, tracks)) {
- throw new Error(
- `Unknown animation track '${String(key)}' — known tracks: ${Object.keys(tracks).join(', ')}.`,
- );
- }
- return tracks[key];
-}
-
-/**
- * The atlas rows one track's cells may occupy, given how many facings the grid
- * has: every row for a directional track, exactly one (row 0) for a
- * non-directional one.
- *
- * `directionCount` is a PARAMETER rather than an import because this module is
- * a true leaf — `animationTracks.test.js` asserts it imports nothing at all —
- * and the canonical direction list lives in `prompts.js`. Callers that already
- * know the grid pass its real height; `atlasGrid.js` supplies the default.
- */
-export function trackRowCount(id, directionCount, tracks = ANIMATION_TRACKS) {
- const row = getAnimationTrack(id, tracks);
- if (!Number.isInteger(directionCount) || directionCount < 1) {
- throw new Error(`animationTracks: trackRowCount needs a positive direction count, got ${directionCount}`);
- }
- return row.directional ? directionCount : 1;
-}
-
-/**
- * Every track a record of this `kind` may carry, in registration order.
- *
- * This is the whole of the "track-presence gate" (#3017): a record kind with no
- * rows has no animation path, and a kind with at least one does — replacing the
- * literal `kind !== 'character'` test the sprite services used to make. An
- * absent/blank kind matches nothing rather than defaulting to a kind, so a
- * malformed record can't inherit character's permissions.
- */
-export function tracksForKind(kind, tracks = ANIMATION_TRACKS) {
- if (typeof kind !== 'string' || !kind) return [];
- return Object.values(tracks).filter((row) => row.kinds.includes(kind));
-}
-
-/**
- * True when a record of `kind` may carry the named track. A predicate, not a
- * boundary: an unrecognized track id answers `false` rather than throwing,
- * because the gates call this to DECIDE. The row is an O(1) lookup, so this
- * asks it directly instead of rebuilding `tracksForKind`'s array to re-find it.
- */
-export function kindSupportsTrack(kind, id, tracks = ANIMATION_TRACKS) {
- if (!isAnimationTrack(id, tracks)) return false;
- return typeof kind === 'string' && !!kind && tracks[id].kinds.includes(kind);
-}
-
-// Round-then-clamp, with unusable input (NaN, non-numeric) falling back to the
-// knob's default rather than to a bound — the two knobs differ only in which
-// three row fields they read.
-const clampInto = (n, min, max, fallback) => {
- const v = Math.round(Number(n));
- if (!Number.isFinite(v)) return fallback;
- return Math.max(min, Math.min(max, v));
-};
-
-/**
- * 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, tracks = ANIMATION_TRACKS) {
- const row = getAnimationTrack(track, tracks);
- return clampInto(n, row.minFps, row.maxFps, row.defaultFps);
-}
+export * from '../../lib/spriteAnimationTracks.js';
diff --git a/server/services/sprites/animationWorkflow.js b/server/services/sprites/animationWorkflow.js
index 6d481f4055..53ec490a41 100644
--- a/server/services/sprites/animationWorkflow.js
+++ b/server/services/sprites/animationWorkflow.js
@@ -98,7 +98,9 @@ export const buildGrokI2vTask = ({ prompt, inputAbs, videoAbs, duration }) => (
export const LOCAL_VIDEO_PROVIDER_ID = 'minimax-h3-local';
/** The provider ids a generate REQUEST may carry. */
-export const ANIMATION_PROVIDER_IDS = Object.freeze(['grok', 'local']);
+// Moved to lib/spriteVocabulary.js in #4901; re-exported for existing callers.
+export { ANIMATION_PROVIDER_IDS } from '../../lib/spriteVocabulary.js';
+import { ANIMATION_PROVIDER_IDS } from '../../lib/spriteVocabulary.js';
/**
* Absent → grok, so every pre-existing client, persisted retry, and test
diff --git a/server/services/sprites/chromaKey.js b/server/services/sprites/chromaKey.js
index d9cc17b01f..ca7e08f2cc 100644
--- a/server/services/sprites/chromaKey.js
+++ b/server/services/sprites/chromaKey.js
@@ -1,183 +1,8 @@
/**
- * Sprites — dynamic chroma-key selection (issue #2896, phase 2).
- *
- * The source pipeline hardcoded magenta because its one character wore green;
- * per the #2895 decision the key is now picked per character from a FIXED set
- * of three standard keys, by hue distance from the character's own palette
- * (a green-clothed character keys on magenta; a pink one keys on green/blue).
- *
- * Pure module — palette extraction (sharp) lives in normalize.js; this file
- * is just color math so it stays unit-testable and safe to import anywhere.
+ * Re-export shim. The chroma-key color math moved to `lib/spriteChromaKey.js`
+ * so route validation can read `CHROMA_KEY_HEXES` without importing upward into
+ * services (issue #4901). The module always described itself as "pure … safe to
+ * import anywhere"; lib is where that belongs. Existing deep imports keep working.
*/
-export const CHROMA_KEYS = [
- { hex: '#FF00FF', name: 'magenta', hue: 300 },
- { hex: '#00FF00', name: 'green', hue: 120 },
- { hex: '#0000FF', name: 'blue', hue: 240 },
-];
-
-export const CHROMA_KEY_HEXES = CHROMA_KEYS.map((k) => k.hex);
-
-// Magenta — the source pipeline's only key; the fallback wherever no key has
-// been selected yet (pre-lock generation, legacy imports).
-export const DEFAULT_CHROMA_KEY = CHROMA_KEYS[0].hex;
-
-// Below this hue separation (degrees) between the chosen key and the nearest
-// significant palette color, keying will likely eat character pixels — the
-// selection still returns the best key but carries a warning.
-export const MIN_HUE_SEPARATION = 60;
-
-export function hexToRgb(hex) {
- const m = /^#?([0-9a-fA-F]{6})$/.exec(typeof hex === 'string' ? hex : '');
- if (!m) throw new Error(`Invalid hex color: ${hex}`);
- const n = parseInt(m[1], 16);
- return { r: (n >> 16) & 0xff, g: (n >> 8) & 0xff, b: n & 0xff };
-}
-
-export function rgbToHsv(r, g, b) {
- const rn = r / 255; const gn = g / 255; const bn = b / 255;
- const max = Math.max(rn, gn, bn);
- const min = Math.min(rn, gn, bn);
- const delta = max - min;
- let h = 0;
- if (delta > 0) {
- if (max === rn) h = 60 * (((gn - bn) / delta) % 6);
- else if (max === gn) h = 60 * ((bn - rn) / delta + 2);
- else h = 60 * ((rn - gn) / delta + 4);
- if (h < 0) h += 360;
- }
- return { h, s: max === 0 ? 0 : delta / max, v: max };
-}
-
-export function hueDistance(a, b) {
- const d = Math.abs(a - b) % 360;
- return d > 180 ? 360 - d : d;
-}
-
-/**
- * Pick the key whose hue is farthest from every significant color in the
- * character's palette.
- *
- * `palette` is `[{ r, g, b, count }]` (see extractForegroundPalette). Colors
- * below the saturation/value floors are ignored — near-grays and near-blacks
- * have no meaningful hue and never conflict with a saturated key; colors
- * below `minCountFrac` of the total are single-pixel noise.
- *
- * Returns `{ hex, name, minHueDistance, warning }` — never null; a fully
- * achromatic palette conflicts with nothing, so the first key (magenta, the
- * legacy default) wins with distance Infinity.
- */
-function significantHues(palette, { minCountFrac = 0.005, minSaturation = 0.25, minValue = 0.15 } = {}) {
- const entries = Array.isArray(palette) ? palette : [];
- const total = entries.reduce((sum, e) => sum + (e.count || 0), 0);
- return entries
- .map((e) => ({ ...rgbToHsv(e.r, e.g, e.b), count: e.count || 0 }))
- .filter((c) => c.count >= total * minCountFrac && c.s >= minSaturation && c.v >= minValue);
-}
-
-/**
- * Warn when the character's surviving palette sits close in hue to the key
- * it was GENERATED on: the normalize mask has already discarded any pixel
- * within the luma threshold of that key, so near-key palette colors imply
- * exact-key details (a magenta garment on the magenta default) may have been
- * silently clipped from the immutable locked artifact. Returns a warning
- * string or null.
- */
-export function keyProximityWarning(palette, keyHex, { role = 'generation', ...opts } = {}) {
- const { r, g, b } = hexToRgb(keyHex);
- const keyHue = rgbToHsv(r, g, b).h;
- const significant = significantHues(palette, opts);
- if (!significant.length) return null;
- const minDist = Math.min(...significant.map((c) => hueDistance(keyHue, c.h)));
- if (minDist >= MIN_HUE_SEPARATION) return null;
- // `selected` = the key the artifact will be COMPOSITED onto (runtime keying
- // would clip character pixels); `generation` = the key it was RENDERED on
- // (exact-key details are already gone from the mask).
- return role === 'selected'
- ? `Character palette sits within ${Math.round(minDist)}° of the selected key ${keyHex} — runtime keying on it would clip character pixels; pick a different key before locking`
- : `Character palette sits within ${Math.round(minDist)}° of the generation key ${keyHex} — exact-key details may have been clipped by the mask; consider pinning a different key and regenerating before locking`;
-}
-
-/**
- * Split a key color into its saturated ("high", 255) and dark ("low", 0)
- * channel indices — the structure every key-parameterized un-key/despill
- * formula in walkPostprocess.js is written against. The source pipeline
- * hardcoded magenta (highs r+b, low g); the three standard keys are all
- * pure-channel colors, so highs/lows fully describe them:
- * magenta → highs [0,2], lows [1]
- * green → highs [1], lows [0,2]
- * blue → highs [2], lows [0,1]
- * Channel indices are 0=r, 1=g, 2=b into an RGB(A) pixel.
- */
-export function keyChannelSplit(hex) {
- const { r, g, b } = hexToRgb(hex);
- const values = [r, g, b];
- const highs = [];
- const lows = [];
- values.forEach((v, i) => (v >= 128 ? highs : lows).push(i));
- if (!highs.length || !lows.length) throw new Error(`Not a usable chroma key: ${hex}`);
- return { rgb: values, highs, lows };
-}
-
-/**
- * How key-like a pixel is: min(high channels) − max(low channels).
- * Positive = the pixel leans toward the key color. For magenta this is the
- * source pipeline's `min(r,b) − g` exactly.
- */
-export function keyness(pixel, split) {
- let minHigh = 255;
- for (const h of split.highs) minHigh = Math.min(minHigh, pixel[h]);
- let maxLow = 0;
- for (const l of split.lows) maxLow = Math.max(maxLow, pixel[l]);
- return minHigh - maxLow;
-}
-
-/**
- * Build the per-pixel background-key "share" sampler for a key: the fraction of
- * a pixel that is the key color, reversing anti-aliased source-over-key
- * compositing. Measured as the min over the key's (high, low) channel pairs of
- * (pixel[high] − pixel[low]) / (key[high] − key[low]), clamped to [0, 1] — a
- * pure-key pixel scores 1, a pixel unlike the key scores 0, an anti-aliased
- * blend lands in between (the exact weight of the key still contaminating it).
- *
- * `keyRgb` is the key as `[r, g, b]` (a nominal key OR a measured border key);
- * `split` is its keyChannelSplit. The returned sampler reads channels from
- * `arr` at `base + channelIndex`, so one factory serves both a 3-element pixel
- * array (`base` 0) and a flat RGB/RGBA buffer (`base` = pixelIndex * channels).
- * The (high, low) pairs and their spans are precomputed once per key so the
- * hot per-pixel path only does the reads, subtracts, and min.
- */
-export function keyShareFn(keyRgb, split) {
- const pairs = [];
- for (const h of split.highs) {
- for (const l of split.lows) pairs.push([h, l, Math.max(1, keyRgb[h] - keyRgb[l])]);
- }
- return (arr, base = 0) => {
- let s = Infinity;
- for (const [h, l, span] of pairs) {
- const v = (arr[base + h] - arr[base + l]) / span;
- if (v < s) s = v;
- }
- return s < 0 ? 0 : s > 1 ? 1 : s;
- };
-}
-
-export function pickChromaKey(palette, opts = {}) {
- const significant = significantHues(palette, opts);
-
- let best = null;
- for (const key of CHROMA_KEYS) {
- const minDist = significant.length
- ? Math.min(...significant.map((c) => hueDistance(key.hue, c.h)))
- : Infinity;
- if (!best || minDist > best.minHueDistance) {
- best = { hex: key.hex, name: key.name, minHueDistance: minDist };
- }
- }
- return {
- ...best,
- warning: best.minHueDistance < MIN_HUE_SEPARATION
- ? `Closest palette hue is within ${Math.round(best.minHueDistance)}° of the ${best.name} key — keying may clip character pixels`
- : null,
- };
-}
+export * from '../../lib/spriteChromaKey.js';
diff --git a/server/services/sprites/prompts.js b/server/services/sprites/prompts.js
index 4f18034c84..bfa4a9d2fe 100644
--- a/server/services/sprites/prompts.js
+++ b/server/services/sprites/prompts.js
@@ -13,20 +13,13 @@
// Canonical 8-direction order (the source pipeline's RUNTIME_DIRECTION_ORDER)
// — atlas row order in later phases depends on this, so keep it stable.
-export const SPRITE_DIRECTIONS = [
- 'south',
- 'south-east',
- 'east',
- 'north-east',
- 'north',
- 'north-west',
- 'west',
- 'south-west',
-];
+// Moved to lib/spriteVocabulary.js in #4901; re-exported for existing callers.
+export { SPRITE_DIRECTIONS, ANCHOR_DIRECTIONS } from '../../lib/spriteVocabulary.js';
+import { SPRITE_DIRECTIONS } from '../../lib/spriteVocabulary.js';
// Directions that get a derived anchor. `south` is never generated — the
// frozen main reference IS the south anchor.
-export const ANCHOR_DIRECTIONS = SPRITE_DIRECTIONS.filter((d) => d !== 'south');
+
export const anchorIdForDirection = (direction) => `walk-${direction}`;
@@ -136,7 +129,7 @@ export function viewGeometryClause(direction) {
// The sheet's candidate/asset id — the `anchorIdForDirection` analogue for the
// one reference artifact that has no direction. Lives here with the other
// target vocabulary so validation.js and the services share one spelling.
-export const TURNAROUND_ID = 'turnaround';
+export { TURNAROUND_ID } from '../../lib/spriteVocabulary.js';
// --- Corrections (#2964 / #3134, made to actually land by #3216) -------------
//
diff --git a/server/services/sprites/recordsLogic.js b/server/services/sprites/recordsLogic.js
index 799dfb38ce..48018d1ca7 100644
--- a/server/services/sprites/recordsLogic.js
+++ b/server/services/sprites/recordsLogic.js
@@ -16,7 +16,8 @@
* records created through the UI only ever get `character`/`place`/`object`.
*/
-export const SPRITE_RECORD_KINDS = ['character', 'place', 'object', 'props'];
+export { SPRITE_RECORD_KINDS } from '../../lib/spriteVocabulary.js';
+import { SPRITE_RECORD_KINDS } from '../../lib/spriteVocabulary.js';
// The one import is lib/renderTargets.js, itself a dependency-free leaf, so
// this module stays safe to import from mocked suites (see the note on
@@ -25,7 +26,10 @@ import { recordRenderPin } from '../../lib/renderTargets.js';
// Record ids double as the on-disk directory name under data/sprites/ — keep
// them strict kebab-case so a record id can never traverse the filesystem.
-export const SPRITE_ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}$/;
+// Moved to lib/spriteVocabulary.js in #4901 so route schemas can read it
+// without importing this module. Re-exported so existing imports are unchanged.
+export { SPRITE_ID_PATTERN } from '../../lib/spriteVocabulary.js';
+import { SPRITE_ID_PATTERN } from '../../lib/spriteVocabulary.js';
export function isValidSpriteId(id) {
return typeof id === 'string' && SPRITE_ID_PATTERN.test(id);