Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor([issue-3015]): make sprite frame-count/fps bounds per-track instead of walk-shaped
[._.]/ Adam Eivy627b63f4f2a4
diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 84bd8dd890..8f5f1dfc88 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -6,8 +6,8 @@ import { SPRITE_ID_PATTERN, SPRITE_RECORD_KINDS } from '../services/sprites/recoimport { ANCHOR_DIRECTIONS, SPRITE_DIRECTIONS, TURNAROUND_ID } from '../services/sprites/prompts.js';import { CHROMA_KEY_HEXES } from '../services/sprites/chromaKey.js';import {- WALK_MIN_FRAME_COUNT, WALK_MAX_FRAME_COUNT, WALK_MIN_FPS, WALK_MAX_FPS,-} from '../services/sprites/walkBounds.js';+ WALK_TRACK, ANIMATION_TRACK_IDS, isAnimationTrack, getAnimationTrack,+} from '../services/sprites/animationTracks.js';import { QUEUEABLE_IMAGE_MODES } from '../services/imageGen/modes.js';// gpt-image-2 (codex backend) caps at 3840px per edge and 8,294,400 total@@ -956,6 +956,28 @@ export const videoDownloadSchema = z.object({url: z.string().url().max(2048)});+// Animation-track-aware bounds (#3015). Frame-count / fps ranges are per track,+// not global, so the schema factories below take a track id and build the range+// from that track's registry row. `walk` is the default, which is what keeps+// every pre-#3015 call site behaving identically. An unrecognized id throws out+// of `getAnimationTrack` at schema-construction time (a wiring bug, caught at+// boot) rather than degrading to walk's range; a track id arriving in a REQUEST+// is validated by `spriteAnimationTrackSchema`, which rejects it with a message+// naming the known tracks.+export const spriteAnimationTrackSchema = z.string().refine(isAnimationTrack, {+ message: `unknown animation track — expected one of: ${ANIMATION_TRACK_IDS.join(', ')}`,+});++export function spriteTrackFrameCountSchema(track = WALK_TRACK) {+ const row = getAnimationTrack(track);+ return z.number().int().min(row.minFrameCount).max(row.maxFrameCount);+}++export function spriteTrackFpsSchema(track = WALK_TRACK) {+ const row = getAnimationTrack(track);+ return z.number().int().min(row.minFps).max(row.maxFps);+}+// Sprite Manager (issue #2895, phase 1). Import runs against a local// filesystem path the user supplies (the source pipeline checkout); the// importer validates the tree shape server-side. The id pattern is owned by@@ -1004,7 +1026,10 @@ const spriteRepoRelativePath = z.string().min(1).max(1024)// have no animation-fps concept, so PortOS's fps is preview-only and never// part of the contract.export const spriteRuntimeContractSchema = z.object({- walkFrameCount: z.number().int().min(WALK_MIN_FRAME_COUNT).max(WALK_MAX_FRAME_COUNT),+ // Field name and range both come from the walk registry row (#3015) — the+ // row names the contract field it occupies, so a second track declaring its+ // own contract field can't drift from what resolveAnimationTarget reads.+ [getAnimationTrack(WALK_TRACK).contractFrameCountField]: spriteTrackFrameCountSchema(WALK_TRACK),cellSize: z.number().int().min(16).max(1024).nullable().optional(),columnCount: z.number().int().min(1).max(256).nullable().optional(),});@@ -1124,11 +1149,12 @@ const spriteWalkDirectionSchema = z.enum(SPRITE_DIRECTIONS);const spriteResolvableRunIdSchema = z.string().min(1).max(1024).refine(isSafeSubdirFilter, { message: 'invalid run id' });-// Walk-cycle authoring bounds — imported from the sharp-free walkBounds leaf so-// the request schema and the server-side clamp share ONE range definition (a-// bounds change can't silently diverge). walkBounds pulls in no native deps.-const spriteWalkFrameCountSchema = z.number().int().min(WALK_MIN_FRAME_COUNT).max(WALK_MAX_FRAME_COUNT);-const spriteWalkFpsSchema = z.number().int().min(WALK_MIN_FPS).max(WALK_MAX_FPS);+// Walk-cycle authoring bounds — built from the walk row of the sharp-free+// animation-track registry so the request schema and the server-side clamp+// share ONE range definition (a bounds change can't silently diverge).+// animationTracks pulls in no deps at all, native or otherwise.+const spriteWalkFrameCountSchema = spriteTrackFrameCountSchema(WALK_TRACK);+const spriteWalkFpsSchema = spriteTrackFpsSchema(WALK_TRACK);export const spriteWalkGenerateSchema = z.object({direction: spriteWalkDirectionSchema,diff --git a/server/lib/validation.test.js b/server/lib/validation.test.jsindex ec8eb37464..099a46d460 100644--- a/server/lib/validation.test.js+++ b/server/lib/validation.test.js@@ -38,6 +38,11 @@ import {databaseSwitchSchema,databaseBackendSchema,databaseExportSchema,+ spriteAnimationTrackSchema,+ spriteTrackFrameCountSchema,+ spriteTrackFpsSchema,+ spriteRuntimeContractSchema,+ spriteWalkGenerateSchema,} from './validation.js';import {telegramForwardTypesSchema,@@ -1429,6 +1434,52 @@ describe('ad-hoc route schemas (#2521)', () => {});});+ describe('animation-track-aware sprite bounds (#3015)', () => {+ it('accepts a known track id and rejects an unknown one by name', () => {+ expect(spriteAnimationTrackSchema.safeParse('walk').success).toBe(true);+ const bad = spriteAnimationTrackSchema.safeParse('scanner');+ expect(bad.success).toBe(false);+ expect(JSON.stringify(bad.error.issues)).toMatch(/unknown animation track/);+ expect(JSON.stringify(bad.error.issues)).toMatch(/walk/);+ });++ it('builds the walk range from the registry row, unchanged from pre-#3015', () => {+ const frames = spriteTrackFrameCountSchema('walk');+ expect(frames.safeParse(6).success).toBe(true);+ expect(frames.safeParse(16).success).toBe(true);+ expect(frames.safeParse(5).success).toBe(false);+ expect(frames.safeParse(17).success).toBe(false);+ expect(frames.safeParse(12.5).success).toBe(false);+ const fps = spriteTrackFpsSchema('walk');+ expect(fps.safeParse(4).success).toBe(true);+ expect(fps.safeParse(24).success).toBe(true);+ expect(fps.safeParse(3).success).toBe(false);+ expect(fps.safeParse(25).success).toBe(false);+ });++ it('defaults to the walk track when no track is named', () => {+ expect(spriteTrackFrameCountSchema().safeParse(16).success).toBe(true);+ expect(spriteTrackFpsSchema().safeParse(24).success).toBe(true);+ });++ it('throws at schema-construction time for an unrecognized track', () => {+ // A wiring bug surfaces at boot rather than degrading to walk's range.+ expect(() => spriteTrackFrameCountSchema('scanner')).toThrow(/Unknown animation track/);+ expect(() => spriteTrackFpsSchema('scanner')).toThrow(/Unknown animation track/);+ });++ it('leaves the walk request/contract schemas behaving exactly as before', () => {+ expect(spriteRuntimeContractSchema.safeParse({ walkFrameCount: 12 }).success).toBe(true);+ expect(spriteRuntimeContractSchema.safeParse({ walkFrameCount: 5 }).success).toBe(false);+ expect(spriteWalkGenerateSchema.safeParse({+ direction: 'south', frameCount: 12, fps: 10,+ }).success).toBe(true);+ expect(spriteWalkGenerateSchema.safeParse({+ direction: 'south', frameCount: 3,+ }).success).toBe(false);+ });+ });+describe('telegramForwardTypesSchema', () => {it('accepts a string array (including empty to clear all)', () => {expect(telegramForwardTypesSchema.safeParse({ forwardTypes: [] }).success).toBe(true);diff --git a/server/services/sprites/animationTargets.js b/server/services/sprites/animationTargets.jsindex 15eaf0b3bc..2acd428c05 100644--- a/server/services/sprites/animationTargets.js+++ b/server/services/sprites/animationTargets.js@@ -20,21 +20,30 @@* tracks of DIFFERING lengths into one atlas needs a column-span descriptor and* is deliberately out of scope here.*- * Dependency-free apart from the sharp-free `walkBounds` leaf, so the service- * layer and the (native-dep-free) validation graph can both reach it.+ * Dependency-free apart from the sharp-free `animationTracks` registry, so the+ * service layer and the (native-dep-free) validation graph can both reach it.+ *+ * Since #3015 the bounds this module range-checks against come from that+ * registry PER TRACK, not from one global walk-shaped range — so a future+ * 4-frame scanner action resolves against its own row instead of being rejected+ * by walk's floor of 6.*/import {- WALK_DEFAULT_FRAME_COUNT, WALK_DEFAULT_FPS,- WALK_MIN_FRAME_COUNT, WALK_MAX_FRAME_COUNT, WALK_MIN_FPS, WALK_MAX_FPS,-} from './walkBounds.js';+ WALK_TRACK, getAnimationTrack,+} from './animationTracks.js';-/** The only animation track that exists today. */-export const WALK_TRACK = 'walk';+// Re-exported so existing importers (walk.js) keep reaching the walk track id+// here; the registry owns the value now, so the two can never disagree.+export { WALK_TRACK };const intInRange = (v, min, max) => (Number.isInteger(v) && v >= min && v <= max ? v : null);-const readFrameCount = (v) => intInRange(v, WALK_MIN_FRAME_COUNT, WALK_MAX_FRAME_COUNT);-const readFps = (v) => intInRange(v, WALK_MIN_FPS, WALK_MAX_FPS);+// Range readers bound to ONE track's row. Out-of-range values read as `null`+// (absent) rather than being clamped — see resolveAnimationTarget's contract.+const trackReaders = (row) => ({+ readFrameCount: (v) => intInRange(v, row.minFrameCount, row.maxFrameCount),+ readFps: (v) => intInRange(v, row.minFps, row.maxFps),+});/*** Resolve one track's pinned target from the precedence chain, newest authority@@ -48,7 +57,7 @@ const readFps = (v) => intInRange(v, WALK_MIN_FPS, WALK_MAX_FPS);* rule atlas.js already applies), auto-pinned on first resolve so* it stops being implicit. Persisted with `source: 'derived'` so a* value PortOS inferred never masquerades as one the user chose.- * 'default' — WALK_DEFAULT_FRAME_COUNT / WALK_DEFAULT_FPS.+ * 'default' — the track's `defaultFrameCount` / `defaultFps`.** Out-of-range or non-integer values at any rung are ignored rather than* clamped: a hand-edited record must not silently pin a value the packer would@@ -57,14 +66,14 @@ const readFps = (v) => intInRange(v, WALK_MIN_FPS, WALK_MAX_FPS);* `source` names the highest rung that supplied EITHER knob, and* `frameCountLocked` / `fpsLocked` say precisely which the app nailed down.*- * `track` selects which persisted entry to read. The CONTRACT fields and the- * range checks below are walk-specific (the contract declares `walkFrameCount`,- * and the bounds come from `walkBounds`) — a second track will need both- * generalized at the same time, so parameterizing only one of them today would- * be a false promise. The persisted shape is what has to be track-keyed now.+ * `track` selects which persisted entry to read AND which registry row supplies+ * the bounds, the defaults, and the `runtimeContract` field names — all three+ * were walk-specific before #3015. An absent track resolves to `walk`+ * (preserving every existing call site); an UNRECOGNIZED one throws rather than+ * silently validating against walk's range.** @param {object} input- * @param {string} [input.track] Track key (only 'walk' exists today).+ * @param {string} [input.track] Track id from `animationTracks.js` (default 'walk').* @param {object} [input.runtimeContract] `publishBinding.runtimeContract`, if any.* @param {object} [input.animationTargets] The selection record's block.* @param {Array<{direction?: string, frameCount?: number, fps?: number}>} [input.packagedCycles]@@ -78,13 +87,18 @@ export function resolveAnimationTarget({animationTargets = null,packagedCycles = [],} = {}) {+ // Throws on an unrecognized track — an explicit error beats silently+ // range-checking a scanner action against the walk's 6–16.+ const row = getAnimationTrack(track);+ const { readFrameCount, readFps } = trackReaders(row);+// The bound app's declared expectation for its own atlas (#2982) — a stronger// authority than any per-render pick. Read defensively: that field lands// independently of this module, so an absent contract just falls through.- const appCount = readFrameCount(runtimeContract?.walkFrameCount);- const appFps = readFps(runtimeContract?.walkFps);+ const appCount = readFrameCount(runtimeContract?.[row.contractFrameCountField]);+ const appFps = readFps(runtimeContract?.[row.contractFpsField]);- const pinned = animationTargets?.[track] || null;+ const pinned = animationTargets?.[row.id] || null;const setCount = readFrameCount(pinned?.frameCount);const setFps = readFps(pinned?.fps);@@ -100,9 +114,9 @@ export function resolveAnimationTarget({if (appCount !== null || appFps !== null) source = 'app';return {- track,- frameCount: appCount ?? setCount ?? derivedCount ?? WALK_DEFAULT_FRAME_COUNT,- fps: appFps ?? setFps ?? derivedFps ?? WALK_DEFAULT_FPS,+ track: row.id,+ frameCount: appCount ?? setCount ?? derivedCount ?? row.defaultFrameCount,+ fps: appFps ?? setFps ?? derivedFps ?? row.defaultFps,source,frameCountLocked: appCount !== null,fpsLocked: appFps !== null,@@ -122,12 +136,18 @@ function firstDefined(list, read) {* disturbing sibling tracks. Load-bearing forward-compatibility: a peer (or a* later PortOS) may have written a `scanner` / ambient entry this build knows* nothing about, and a naive `{ walk: … }` overwrite would silently drop it.+ *+ * The track being WRITTEN must be one this build knows (#3015) — an unrecognized+ * write target is a bug, not a forward-compat case, and would persist a row+ * nothing can range-check. Sibling keys are untouched either way: preserving+ * what a newer peer wrote and writing a bogus key are different things.*/export function withTrackTarget(animationTargets, track, { frameCount, fps, source }) {+ const row = getAnimationTrack(track);const existing = (animationTargets && typeof animationTargets === 'object' && !Array.isArray(animationTargets))? animationTargets: {};- return { ...existing, [track]: { frameCount, fps, source } };+ return { ...existing, [row.id]: { frameCount, fps, source } };}/**@@ -136,8 +156,12 @@ export function withTrackTarget(animationTargets, track, { frameCount, fps, sour* can badge exactly which ones need re-deriving, instead of the user discovering* it at atlas-compile time. A cycle with no usable geometry (an import that* never declared one) is not "drift" — there is nothing to compare.+ *+ * Range-checks each cycle against the TARGET's own track (#3015), falling back+ * to the default track when the caller passed a bare `{ frameCount, fps }`.*/export function targetDrift(target, packagedCycles = []) {+ const { readFrameCount, readFps } = trackReaders(getAnimationTrack(target?.track));return (packagedCycles || []).flatMap((cycle) => {const frameCount = readFrameCount(cycle?.frameCount);const fps = readFps(cycle?.fps);diff --git a/server/services/sprites/animationTargets.test.js b/server/services/sprites/animationTargets.test.jsindex 596e8d662e..39568775fb 100644--- a/server/services/sprites/animationTargets.test.js+++ b/server/services/sprites/animationTargets.test.js@@ -9,6 +9,7 @@ import { describe, it, expect } from 'vitest';import {WALK_TRACK, resolveAnimationTarget, withTrackTarget, targetDrift, describeTargetSource,} from './animationTargets.js';+import { getAnimationTrack } from './animationTracks.js';describe('resolveAnimationTarget precedence', () => {it('falls back to the documented defaults when nothing is pinned or packaged', () => {@@ -80,6 +81,24 @@ describe('resolveAnimationTarget precedence', () => {animationTargets: { scanner: { frameCount: 6, fps: 4 } },})).toMatchObject({ frameCount: 12, fps: 10, source: 'default' });});++ it('reads the app rung through the track\'s declared contract fields (#3015)', () => {+ // The registry row names which runtimeContract fields the track occupies,+ // so the app rung is track-driven rather than hard-coded to walkFrameCount.+ const row = getAnimationTrack(WALK_TRACK);+ expect(resolveAnimationTarget({+ track: WALK_TRACK,+ runtimeContract: { [row.contractFrameCountField]: 16, [row.contractFpsField]: 24 },+ })).toMatchObject({ frameCount: 16, fps: 24, source: 'app' });+ });++ it('rejects an unrecognized track instead of resolving it against walk\'s range', () => {+ // Sentinel discipline: absent ⇒ the default track; unrecognized ⇒ an error+ // naming the known tracks, never a silent fall-through to 6–16 / 4–24.+ expect(() => resolveAnimationTarget({ track: 'scanner' }))+ .toThrow(/Unknown animation track 'scanner'/);+ expect(resolveAnimationTarget({ track: undefined }).track).toBe(WALK_TRACK);+ });});describe('withTrackTarget', () => {@@ -103,6 +122,14 @@ describe('withTrackTarget', () => {expect(withTrackTarget(['nope'], WALK_TRACK, { frameCount: 12, fps: 10, source: 'set' })).toEqual({ walk: { frameCount: 12, fps: 10, source: 'set' } });});++ it('refuses to WRITE a track this build does not know (#3015)', () => {+ // Preserving a sibling key a newer peer wrote and minting a bogus one are+ // different things: the first is forward-compat, the second is a bug that+ // would persist a row nothing can range-check.+ expect(() => withTrackTarget({}, 'scanner', { frameCount: 4, fps: 6, source: 'set' }))+ .toThrow(/Unknown animation track 'scanner'/);+ });});describe('targetDrift', () => {@@ -126,6 +153,18 @@ describe('targetDrift', () => {it('does not call a direction with no declared geometry "drifted"', () => {expect(targetDrift(target, [{ direction: 'south' }])).toEqual([]);});++ it('range-checks against the target\'s own track, defaulting when it carries none', () => {+ // A bare `{ frameCount, fps }` target (every pre-#3015 caller) still reads+ // against the walk row; an explicit track is honored.+ expect(targetDrift({ ...target, track: WALK_TRACK }, [+ { direction: 'east', frameCount: 8, fps: 10 },+ ])).toEqual([{+ direction: 'east', frameCount: 8, fps: 10, frameCountDrifts: true, fpsDrifts: false,+ }]);+ expect(() => targetDrift({ ...target, track: 'scanner' }, []))+ .toThrow(/Unknown animation track 'scanner'/);+ });});describe('describeTargetSource', () => {diff --git a/server/services/sprites/animationTracks.js b/server/services/sprites/animationTracks.jsnew file mode 100644index 0000000000..edf7220aaf--- /dev/null+++ b/server/services/sprites/animationTracks.js@@ -0,0 +1,102 @@+/**+ * 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) or+ * a 4-frame scanner action was unrepresentable: both sit 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.+ */++/** The default track — the only one that exists today. */+export const WALK_TRACK = 'walk';++/**+ * Every known animation track.+ *+ * - `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).+ * - `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`.+ */+export const ANIMATION_TRACKS = Object.freeze({+ [WALK_TRACK]: Object.freeze({+ id: WALK_TRACK,+ label: 'Walk cycle',+ directional: true,+ minFrameCount: 6,+ maxFrameCount: 16,+ defaultFrameCount: 12,+ minFps: 4,+ maxFps: 24,+ defaultFps: 10,+ contractFrameCountField: 'walkFrameCount',+ contractFpsField: 'walkFps',+ }),+});++/** Known track ids, in registry order. */+export const ANIMATION_TRACK_IDS = Object.freeze(Object.keys(ANIMATION_TRACKS));++/** True when `id` names a track this build knows. */+export function isAnimationTrack(id) {+ return typeof id === 'string' && Object.prototype.hasOwnProperty.call(ANIMATION_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.+ */+export function getAnimationTrack(id) {+ const key = id === undefined || id === null ? WALK_TRACK : id;+ if (!isAnimationTrack(key)) {+ throw new Error(+ `Unknown animation track '${String(key)}' — known tracks: ${ANIMATION_TRACK_IDS.join(', ')}.`,+ );+ }+ return ANIMATION_TRACKS[key];+}++/** Clamp a requested frame count into `track`'s authoring range. */+export function clampTrackFrameCount(n, track) {+ const row = getAnimationTrack(track);+ const v = Math.round(Number(n));+ if (!Number.isFinite(v)) return row.defaultFrameCount;+ return Math.max(row.minFrameCount, Math.min(row.maxFrameCount, v));+}++/** Clamp a requested playback fps into `track`'s authoring range. */+export function clampTrackFps(n, track) {+ const row = getAnimationTrack(track);+ const v = Math.round(Number(n));+ if (!Number.isFinite(v)) return row.defaultFps;+ return Math.max(row.minFps, Math.min(row.maxFps, v));+}diff --git a/server/services/sprites/animationTracks.test.js b/server/services/sprites/animationTracks.test.jsnew file mode 100644index 0000000000..dd2ed09d3c--- /dev/null+++ b/server/services/sprites/animationTracks.test.js@@ -0,0 +1,216 @@+/**+ * The per-track animation registry (#3015) — the rows themselves, the+ * unknown-track error boundary, the per-track clamps, and the sharp-free+ * property `server/lib/validation.js` depends on.+ *+ * The walk row is pinned to its historical values on purpose: #3015 is a+ * refactor, and a registry that quietly moved walk's floor would change every+ * render's geometry while looking like plumbing.+ */++import { describe, it, expect } from 'vitest';+import { readFileSync, existsSync } from 'fs';+import { fileURLToPath } from 'url';+import { dirname, join, resolve } from 'path';+import {+ WALK_TRACK, ANIMATION_TRACKS, ANIMATION_TRACK_IDS,+ isAnimationTrack, getAnimationTrack, clampTrackFrameCount, clampTrackFps,+} from './animationTracks.js';++const SPRITES_DIR = dirname(fileURLToPath(import.meta.url));++describe('the registry rows', () => {+ it('reproduces the walk track\'s historical bounds and defaults exactly', () => {+ // #3015 is a refactor — walk behaves identically end to end.+ expect(getAnimationTrack(WALK_TRACK)).toMatchObject({+ id: 'walk',+ directional: true,+ minFrameCount: 6,+ maxFrameCount: 16,+ defaultFrameCount: 12,+ minFps: 4,+ maxFps: 24,+ defaultFps: 10,+ contractFrameCountField: 'walkFrameCount',+ contractFpsField: 'walkFps',+ });+ });++ it('describes every declared track completely', () => {+ // A row missing a bound would fall through as `undefined` into a Math.min+ // (→ NaN) or a Zod .min() (→ throw at boot); assert the shape up front so+ // adding a track can't half-land.+ for (const id of ANIMATION_TRACK_IDS) {+ const row = ANIMATION_TRACKS[id];+ expect(row.id, `${id}.id must match its registry key`).toBe(id);+ expect(typeof row.label).toBe('string');+ expect(typeof row.directional).toBe('boolean');+ expect(typeof row.contractFrameCountField).toBe('string');+ expect(typeof row.contractFpsField).toBe('string');+ for (const field of ['minFrameCount', 'maxFrameCount', 'defaultFrameCount', 'minFps', 'maxFps', 'defaultFps']) {+ expect(Number.isInteger(row[field]), `${id}.${field} must be an integer`).toBe(true);+ }+ expect(row.minFrameCount).toBeLessThanOrEqual(row.maxFrameCount);+ expect(row.minFps).toBeLessThanOrEqual(row.maxFps);+ expect(row.defaultFrameCount).toBeGreaterThanOrEqual(row.minFrameCount);+ expect(row.defaultFrameCount).toBeLessThanOrEqual(row.maxFrameCount);+ expect(row.defaultFps).toBeGreaterThanOrEqual(row.minFps);+ expect(row.defaultFps).toBeLessThanOrEqual(row.maxFps);+ }+ });++ it('is frozen so a caller cannot mutate the shared bounds', () => {+ expect(() => { ANIMATION_TRACKS.walk.minFrameCount = 1; }).toThrow();+ expect(ANIMATION_TRACKS.walk.minFrameCount).toBe(6);+ });+});++describe('getAnimationTrack — absent vs unrecognized', () => {+ it('treats an absent id as the default track, preserving pre-#3015 call sites', () => {+ expect(getAnimationTrack().id).toBe(WALK_TRACK);+ expect(getAnimationTrack(undefined).id).toBe(WALK_TRACK);+ expect(getAnimationTrack(null).id).toBe(WALK_TRACK);+ });++ it('throws on an unrecognized id instead of falling back to walk\'s range', () => {+ // The sentinel rule: "not set" resolves to the default; "set to something+ // this build does not know" is an error. Silently handing back walk's 6–16+ // would reject a legitimate 4-frame action for reasons nothing explains.+ expect(() => getAnimationTrack('scanner')).toThrow(/Unknown animation track 'scanner'/);+ expect(() => getAnimationTrack('scanner')).toThrow(/known tracks: walk/);+ });++ it('treats an empty string as present-and-invalid, not absent', () => {+ expect(() => getAnimationTrack('')).toThrow(/Unknown animation track/);+ });++ it('rejects a non-string id and inherited Object keys', () => {+ expect(isAnimationTrack('toString')).toBe(false);+ expect(isAnimationTrack(7)).toBe(false);+ expect(() => getAnimationTrack('toString')).toThrow(/Unknown animation track/);+ });+});++describe('per-track clamps', () => {+ it('clamps into the named track\'s range and rounds', () => {+ expect(clampTrackFrameCount(2, WALK_TRACK)).toBe(6);+ expect(clampTrackFrameCount(99, WALK_TRACK)).toBe(16);+ expect(clampTrackFrameCount(11.6, WALK_TRACK)).toBe(12);+ expect(clampTrackFps(1, WALK_TRACK)).toBe(4);+ expect(clampTrackFps(240, WALK_TRACK)).toBe(24);+ });++ it('falls back to the track\'s default for unusable input', () => {+ expect(clampTrackFrameCount('nope', WALK_TRACK)).toBe(12);+ expect(clampTrackFps(undefined, WALK_TRACK)).toBe(10);+ });++ it('defaults to the walk track when none is named', () => {+ expect(clampTrackFrameCount(99)).toBe(16);+ expect(clampTrackFps(99)).toBe(24);+ });++ it('refuses to clamp against an unrecognized track', () => {+ expect(() => clampTrackFrameCount(8, 'scanner')).toThrow(/Unknown animation track/);+ expect(() => clampTrackFps(8, 'scanner')).toThrow(/Unknown animation track/);+ });+});++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 row = getAnimationTrack(WALK_TRACK);+ expect({+ min: bounds.WALK_MIN_FRAME_COUNT,+ max: bounds.WALK_MAX_FRAME_COUNT,+ def: bounds.WALK_DEFAULT_FRAME_COUNT,+ minFps: bounds.WALK_MIN_FPS,+ maxFps: bounds.WALK_MAX_FPS,+ defFps: bounds.WALK_DEFAULT_FPS,+ }).toEqual({+ min: row.minFrameCount,+ max: row.maxFrameCount,+ def: row.defaultFrameCount,+ minFps: row.minFps,+ maxFps: row.maxFps,+ defFps: row.defaultFps,+ });+ });++ it('keeps clampFrameCount / clampFps behaving as the walk-track clamps', async () => {+ const { clampFrameCount, clampFps } = await import('./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));+ }+ });+});++// Matches `import … from './x.js'` / `export … from './x.js'` / bare+// `import './x.js'` at the start of a line — the same static-only scan+// agentImportCycles.test.js uses. Deliberately does NOT match `await import()`+// (deferred to call time) or the string inside a comment.+const STATIC_FROM = /^\s*(?:import|export)\b[^;]*?from\s*['"]([^'"]+)['"]/gm;+const STATIC_BARE = /^\s*import\s*['"]([^'"]+)['"]/gm;++function staticSpecifiers(file) {+ const src = readFileSync(file, 'utf-8');+ const out = [];+ for (const re of [STATIC_FROM, STATIC_BARE]) {+ re.lastIndex = 0;+ let match;+ while ((match = re.exec(src)) !== null) out.push(match[1]);+ }+ return out;+}++/** Every module statically reachable from `entry`, plus the bare packages hit. */+function importClosure(entry) {+ const seen = new Set();+ const packages = new Set();+ const walk = (file) => {+ if (seen.has(file)) return;+ seen.add(file);+ for (const spec of staticSpecifiers(file)) {+ if (!spec.startsWith('.')) { packages.add(spec); continue; }+ const next = resolve(dirname(file), spec);+ if (existsSync(next)) walk(next);+ }+ };+ walk(entry);+ return { files: seen, packages };+}++describe('sharp-free leaf property', () => {+ // server/lib/validation.js builds its sprite frame-count/fps ranges from this+ // registry. If the registry (or anything it reaches) ever imports sharp, the+ // native image graph lands in the request-validation graph — the exact+ // regression walkBounds.js was split out to prevent, now one level deeper.+ const NATIVE = ['sharp', 'canvas', 'fluent-ffmpeg', '@ffmpeg-installer/ffmpeg'];++ it.each([+ ['animationTracks.js'],+ ['walkBounds.js'],+ ['animationTargets.js'],+ ])('%s reaches no native image/video dependency', (file) => {+ const { packages } = importClosure(join(SPRITES_DIR, file));+ const offending = [...packages].filter((p) => NATIVE.some((n) => p === n || p.startsWith(`${n}/`)));+ expect(offending, `${file} must not reach ${offending.join(', ')}`).toEqual([]);+ });++ it('keeps animationTracks.js a true leaf — it imports nothing at all', () => {+ expect(staticSpecifiers(join(SPRITES_DIR, 'animationTracks.js'))).toEqual([]);+ });++ it('actually walks the graph (positive control — the guard is not vacuous)', () => {+ // Two ways this assertion could pass for the wrong reason: the closure+ // never follows relative imports, or it never records bare packages. Pin+ // both against a module that genuinely reaches sharp.+ const walkBounds = importClosure(join(SPRITES_DIR, 'walkBounds.js'));+ expect([...walkBounds.files]).toContain(join(SPRITES_DIR, 'animationTracks.js'));++ const packer = importClosure(join(SPRITES_DIR, 'walkPostprocess.js'));+ expect([...packer.packages], 'walkPostprocess is the native-graph module this split exists to fence off')+ .toContain('sharp');+ });+});diff --git a/server/services/sprites/atlasLayout.js b/server/services/sprites/atlasLayout.jsindex dc247c67db..e01d467b85 100644--- a/server/services/sprites/atlasLayout.js+++ b/server/services/sprites/atlasLayout.js@@ -34,6 +34,11 @@import { basename } from 'path';import { ATLAS_IDLE_COLUMN, ATLAS_SCANNER_COLUMN } from './walkBounds.js';+// The track id the sidecar names its walk span with — read from the registry+// (#3015) so the layout descriptor and `animationTargets.walk` can never key the+// same track differently. animationTracks imports nothing, so this keeps the+// module dependency-free.+import { WALK_TRACK } from './animationTracks.js';// Bump only on a breaking shape change. Adding a field (or a new track) is// additive — consumers read `tracks`/`columns` by name, not by position.@@ -45,8 +50,6 @@ export const ATLAS_LAYOUT_KIND = 'portos-sprite-atlas-layout';export const PREVIEW_FPS_NOTE = 'Authoring metadata only — the speed PortOS previews this walk at. '+ 'The consuming app determines real playback (e.g. from movement distance); do not use this as a runtime frame rate.';-const WALK_TRACK = 'walk';-/*** Sidecar path for a published atlas: `…/hero-atlas.png` →* `…/hero-atlas.layout.json`. The binding schema already forces a `.png`diff --git a/server/services/sprites/walkBounds.js b/server/services/sprites/walkBounds.jsindex ad8379cb31..07f7c37580 100644--- a/server/services/sprites/walkBounds.js+++ b/server/services/sprites/walkBounds.js@@ -9,8 +9,22 @@* Zod schema let the schema and the server-side clamp silently diverge. This* module is the single source of truth for both — see the recordsLogic.js* sharp-free split for the same pattern.+ *+ * Since #3015 the *numbers* live one level deeper, in the per-track registry+ * (`animationTracks.js`), because a range that applies to every animation is+ * walk-shaped by construction — a 4-frame scanner action sits below walk's+ * floor of 6. What remains here is the WALK view of that registry: the exports+ * below are thin re-reads of the `walk` row, kept so every existing importer+ * (walkPostprocess, atlas, walk, validation, the client mirror) needs no churn.+ * New track-aware code should reach for `animationTracks.js` directly.*/+import {+ WALK_TRACK, getAnimationTrack, clampTrackFrameCount, clampTrackFps,+} from './animationTracks.js';++const WALK = getAnimationTrack(WALK_TRACK);+// Source-pipeline gait phases (the historical 8-frame packing). Part of the// cross-install artifact contract — imported manifests carry these exact labels.export const WALK_PHASES = [@@ -31,16 +45,17 @@ export const WALK_FRAME_COUNT = 8;export const ATLAS_IDLE_COLUMN = 'idle';export const ATLAS_SCANNER_COLUMN = 'scanner';-// Configurable authoring range (#sprite-walk-variable-frames). The packer+// Configurable authoring range (#sprite-walk-variable-frames), read from the+// walk row of the track registry (#3015) rather than restated here. The packer// resamples the detected gait window DOWN to `frameCount` distinct source frames// (never upsamples), and playback fps is metadata — so a slower/smoother walk// needs no regeneration, only a reprocess of the on-disk clip at a new count/fps.-export const WALK_DEFAULT_FRAME_COUNT = 12;-export const WALK_DEFAULT_FPS = 10;-export const WALK_MIN_FRAME_COUNT = 6;-export const WALK_MAX_FRAME_COUNT = 16;-export const WALK_MIN_FPS = 4;-export const WALK_MAX_FPS = 24;+export const WALK_DEFAULT_FRAME_COUNT = WALK.defaultFrameCount;+export const WALK_DEFAULT_FPS = WALK.defaultFps;+export const WALK_MIN_FRAME_COUNT = WALK.minFrameCount;+export const WALK_MAX_FRAME_COUNT = WALK.maxFrameCount;+export const WALK_MIN_FPS = WALK.minFps;+export const WALK_MAX_FPS = WALK.maxFps;/*** Column/phase labels for an N-frame packed strip. The historical 8-frame@@ -55,16 +70,12 @@ export function walkPhaseLabels(n) {return Array.from({ length: n }, (_, i) => `frame-${String(i).padStart(2, '0')}`);}-/** Clamp a requested frame count into the supported authoring range. */+/** Clamp a requested frame count into the WALK track's authoring range. */export function clampFrameCount(n) {- const v = Math.round(Number(n));- if (!Number.isFinite(v)) return WALK_DEFAULT_FRAME_COUNT;- return Math.max(WALK_MIN_FRAME_COUNT, Math.min(WALK_MAX_FRAME_COUNT, v));+ return clampTrackFrameCount(n, WALK_TRACK);}-/** Clamp a requested playback fps into the supported authoring range. */+/** Clamp a requested playback fps into the WALK track's authoring range. */export function clampFps(n) {- const v = Math.round(Number(n));- if (!Number.isFinite(v)) return WALK_DEFAULT_FPS;- return Math.max(WALK_MIN_FPS, Math.min(WALK_MAX_FPS, v));+ return clampTrackFps(n, WALK_TRACK);}