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

refactor([issue-3016]): quality pass — one injection seam, cheap-checks-first, canonical compare

[._.]/ Adam Eivyde466c5862e9
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 488006fc76..dfc60b423f 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -13,7 +13,7 @@
## Internal
-- **[issue-3016] The sprite atlas grid can now pack multiple animation tracks of differing lengths** — the runtime grid was walk-shaped by construction: `atlasColumns()` was literally `['idle', ...walkLabels]`, and the compiler refused any set whose directions disagreed on frame count. Both were right for a one-animation world and both blocked a second track — a four-frame action beside a twelve-frame walk needs variable-length column spans. A new sharp-free leaf, `server/services/sprites/atlasGrid.js`, owns the grid the compiler (`atlas.js`, which imports sharp) and the published sidecar (`atlasLayout.js`, which must not) now share: `buildAtlasGrid` emits `idle` first and then each track's contiguous span in registry-registration order, returning the flat `columns` list and the `{ start, count }` `tracks` descriptor together so the two can never drift; `resolveTrackUniformity` resolves one track's frame count and fps from its per-direction rows, asserting the 8 facings agree while **never** comparing one track to another and range-checking against the *named track's* #3015 registry row rather than the global walk-shaped 6–16 / 4–24 constants. That within-track-not-between-track rule is the central semantic change. The compiler persists `geometry.tracks` into the manifest and pointer, `buildAtlasLayout` republishes it, and the pre-pixel idempotency check (which #2986 already taught to compare the column list) now compares the **track set** too, so re-partitioning the same columns into different tracks correctly invalidates instead of reading as up to date. Legacy is fully preserved: a grid with no `tracks` field falls back to the historical column-name derivation — so pre-#3016 atlases stay idempotent instead of recompiling their pixels forever — a pre-#2986 `scanner` placeholder still describes itself honestly, and walk keeps its exact historical column labels. Absent and present-but-empty stay distinct: `{}` is a descriptor that fails to describe the grid and is refused, never silently re-derived. No migration is needed (the field is additive and every reader has a fallback), and no second track is registered here — the multi-track paths are proven against synthetic track rows and a synthetic registration order, since shipping a real second track is #3018's job.
+- **[issue-3016] The sprite atlas grid can now pack multiple animation tracks of differing lengths** — the runtime grid was walk-shaped by construction: `atlasColumns()` was literally `['idle', ...walkLabels]`, and the compiler refused any set whose directions disagreed on frame count. Both were right for a one-animation world and both blocked a second track — a four-frame action beside a twelve-frame walk needs variable-length column spans. A new sharp-free leaf, `server/services/sprites/atlasGrid.js`, owns the grid the compiler (`atlas.js`, which imports sharp) and the published sidecar (`atlasLayout.js`, which must not) now share: `buildAtlasGrid` emits `idle` first and then each track's contiguous span in registry-registration order, returning the flat `columns` list and the `{ start, count }` `tracks` descriptor together so the two can never drift; `resolveTrackUniformity` resolves one track's frame count and fps from its per-direction rows, asserting the 8 facings agree while **never** comparing one track to another and range-checking against the *named track's* #3015 registry row rather than the global walk-shaped 6–16 / 4–24 constants. That within-track-not-between-track rule is the central semantic change. The compiler persists `geometry.tracks` into the manifest and pointer, `buildAtlasLayout` republishes it, and the pre-pixel idempotency check (which #2986 already taught to compare the column list) now compares the **track set** too, so re-partitioning the same columns into different tracks correctly invalidates instead of reading as up to date. Legacy is fully preserved: a grid with no `tracks` field falls back to the historical column-name derivation — so pre-#3016 atlases stay idempotent instead of recompiling their pixels forever — a pre-#2986 `scanner` placeholder still describes itself honestly, and walk keeps its exact historical column labels. Absent and present-but-empty stay distinct: `{}` is a descriptor that fails to describe the grid and is refused, never silently re-derived. No migration is needed (the field is additive and every reader has a fallback), and no second track is registered here — the multi-track paths are proven against a synthetic registry TABLE (the injected-table idiom `assertAnimationTrackRows` already uses, so a synthetic row flows through exactly the lookup, ordering and unknown-id boundary a real one would), since shipping a real second track is #3018's job.
- **[issue-3015] Per-track animation registry — frame-count/fps bounds stop being walk-shaped** — the authoring range (`6–16` frames, `4–24` fps) was global and defined once in `server/services/sprites/walkBounds.js`, so it described *every* animation as if it were a walk cycle; a 3-frame ambient loop or a 4-frame scanner action sits below walk's floor of 6 and was literally unrepresentable. A new sharp-free leaf, `server/services/sprites/animationTracks.js`, holds one row per known track (`{ id, label, directional, min/max/defaultFrameCount, min/max/defaultFps, contractFrameCountField, contractFpsField }`), with `walk` as its only row carrying today's exact values. `walkBounds.js` keeps every historical export as a thin re-read of that row, so `walkPostprocess`, `atlas`, `walk`, `server/lib/validation.js`, and the client mirror need no changes. `resolveAnimationTarget` / `targetDrift` / `withTrackTarget` now range-check against the *named track's* row (and read the app rung through the field names that row declares, instead of hard-coded `walkFrameCount`), and the Zod ranges are built by `spriteTrackFrameCountSchema(track)` / `spriteTrackFpsSchema(track)` factories. An absent track resolves to `walk` — which is what keeps every existing call site identical — while an *unrecognized* one throws rather than silently validating against walk's range. The registry validates its own rows at module load (the `navManifest.js` / `catalogTypes.js` idiom), so a half-declared track blocks boot with a message naming the field instead of surfacing later as a `NaN` frame count. #2985's invariant is preserved: an unrecognized sibling track key still round-trips untouched on write, even though writing to an unknown track is now refused. Pure refactor — walk behaves identically end to end; no second track is added here.
- **New `server/lib/staticImportGraph.js` — one static-import scanner for the structural test guards** — `agentImportCycles.test.js` (the agent-lifecycle acyclicity guard) and the new sprite guard each had their own copy of the ES-module import regex pair and graph walk, which is how a structural guard rots: a fix to one parser silently under-reports in the other. Both now call `staticImportSpecifiers` / `staticImportClosure`. The sprite guard also asserts the property that actually matters — `server/lib/validation.js`'s whole import closure reaches no native image dependency — rather than only the three leaf modules, with a positive control pinning that the walk genuinely traverses. A companion parity test pins the client's mirrored walk bounds (`spriteTrimmer.js`, `PublishWorkflow.jsx`) against the registry row, so the first real per-track bounds change can't silently desync the pickers from the server's range.
- **[issue-3001] Approving and compiling a walk direction now agree on what "valid packaged frames" means** — the check that a direction's per-frame images are all present was written twice: the cheap gate that runs when you *approve* a direction only checked the files existed (and, for an imported character, could silently drop a frame whose path it couldn't re-anchor — understating the count in its own error), while the stricter gate that runs when you *compile* the atlas also verified each frame's checksum and gait-phase order. So a direction could pass approval and then fail compile for a frame reason the approve step was meant to catch. Both now call one shared `verifyPackagedFrames` helper: approve runs its existence-only prefix (resolving imported frame paths the same drift-tolerant way the clip and strip checks beside it already do, and counting an un-re-anchorable path as a failure instead of dropping it), and compile runs the same resolution plus the checksum/order checks — reading each frame's bytes exactly once. The approve gate is now a strict prefix of the compile gate, so the two can no longer disagree.
diff --git a/server/services/sprites/animationTracks.js b/server/services/sprites/animationTracks.js
index df01d7661e..c65f9d679c 100644
--- a/server/services/sprites/animationTracks.js
+++ b/server/services/sprites/animationTracks.js
@@ -134,24 +134,30 @@ export function assertAnimationTrackRows(tracks) {
assertAnimationTrackRows(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);
+/** 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) {
+export function getAnimationTrack(id, tracks = ANIMATION_TRACKS) {
const key = id === undefined || id === null ? WALK_TRACK : id;
- if (!isAnimationTrack(key)) {
+ if (!isAnimationTrack(key, tracks)) {
throw new Error(
- `Unknown animation track '${String(key)}' — known tracks: ${ANIMATION_TRACK_IDS.join(', ')}.`,
+ `Unknown animation track '${String(key)}' — known tracks: ${Object.keys(tracks).join(', ')}.`,
);
}
- return ANIMATION_TRACKS[key];
+ return tracks[key];
}
// Round-then-clamp, with unusable input (NaN, non-numeric) falling back to the
diff --git a/server/services/sprites/atlas.js b/server/services/sprites/atlas.js
index d8784a318d..7691c723f3 100644
--- a/server/services/sprites/atlas.js
+++ b/server/services/sprites/atlas.js
@@ -66,10 +66,8 @@ import { verifyPackagedFrames } from './walkFrames.js';
// atlasGrid.js so the compiler that WRITES the grid and the sidecar that
// DESCRIBES it (atlasLayout.js) share one definition.
//
-// `atlasGrid(specs)` returns both the flat column list and the `{ start, count }`
-// track descriptor; `atlasColumns(specs)` is the column half, kept under its
-// historical name. ATLAS_COLUMNS remains the historical walk-only 8-frame
-// layout, used as the default/fallback.
+// ATLAS_COLUMNS remains the historical walk-only 8-frame layout, used as the
+// default/fallback.
//
// A trailing `scanner` column used to follow the walk phases — a verbatim copy
// of the idle cell that no consumer ever sampled (#2986). It is no longer
@@ -77,9 +75,14 @@ import { verifyPackagedFrames } from './walkFrames.js';
// onto the walk cycle. Imported/legacy atlases and manifests that still carry
// the column keep loading and displaying unchanged — this is a write-side
// change only.
-export const atlasGrid = (trackSpecs) => buildAtlasGrid(trackSpecs);
-export const atlasColumns = (trackSpecs) => buildAtlasGrid(trackSpecs).columns;
-export const ATLAS_COLUMNS = atlasColumns([{ id: WALK_TRACK, frameCount: WALK_PHASES.length }]);
+export const ATLAS_COLUMNS = buildAtlasGrid([{ id: WALK_TRACK, frameCount: WALK_PHASES.length }]).columns;
+
+// A track whose historical run manifests predate the frameRate field falls back
+// to the rate its frames were extracted at, not to the track's authoring
+// default — so an older set compiles to exactly the atlas it always did. Keyed
+// by track so a new track states its own answer (or omits it and takes its
+// registry default) instead of adding a branch here.
+const LEGACY_MANIFEST_FPS = { [WALK_TRACK]: WALK_FPS };
export const DEFAULT_ATLAS_GEOMETRY = {
cellSize: 96,
pivot: [48, 88],
@@ -265,14 +268,19 @@ export async function validateForCompile(recordId) {
anchors[direction] = { ...anchor, bytes };
}
- const runs = {};
- // Per-direction rows for the WALK track, collected in direction order and
- // resolved together below. Uniformity is a WITHIN-track rule (#3016): all 8
- // facings of one track must share a frame count and speed because the atlas is
- // a rectangular grid, but a second track is free to differ from this one — so
- // the rows are keyed by track rather than reduced into one set-wide number.
- // Only `walk` is registered today; a second track adds a sibling row list here
- // plus its own resolveTrackUniformity call, with no change to the shape.
+ // TWO PASSES, cheap first. Pass 1 reads the (small) run manifests and resolves
+ // each track's frame count and fps; pass 2 does the expensive per-frame byte
+ // verification. Doing it the other way round would byte-verify 8 directions
+ // (48–128 PNGs read and hashed) before noticing a frame count that was out of
+ // range or ragged — and verifyPackagedFrames documents the frame count as
+ // already agreed across directions when it runs.
+ //
+ // Rows are keyed by TRACK because uniformity is a within-track rule (#3016):
+ // all 8 facings of one track must share a frame count and speed since the
+ // atlas is a rectangular grid, but a second track is free to differ. Only
+ // `walk` is registered today; a second track adds a sibling row list here and
+ // is resolved by the same loop, with no change to the shape.
+ const manifests = {};
const trackRows = { [WALK_TRACK]: [] };
for (const direction of SPRITE_DIRECTIONS) {
const entry = walkSet.directions?.[direction];
@@ -287,19 +295,13 @@ export async function validateForCompile(recordId) {
if (!manifest || manifest.direction !== direction) {
throw compileError(`Run manifest for ${direction} is unreadable or mislabeled`);
}
+ manifests[direction] = { entry, manifest };
trackRows[WALK_TRACK].push({
direction,
frameCount: (manifest.frames || []).length,
declaredFrameCount: manifest.frameCount,
fps: manifest.frameRate,
});
- // Same frame-validity definition the approve gate uses (verifyPackagedFrames),
- // here in its byte-verifying mode: existence + per-frame sha256 + gait-phase/
- // order, reading each frame's bytes exactly once for read-once-verify-in-memory.
- // Approve runs the existence-only prefix, so a set that passed approve cannot
- // fail this for frame-existence reasons (#3001).
- const { frameBytes } = await verifyPackagedFrames(recordId, manifest, { bytes: true });
- runs[direction] = { runId: entry.runId, manifestPath: entry.runManifest, manifest, frameBytes };
}
// Registration order, so the compiled grid's span order is stable regardless
@@ -308,13 +310,22 @@ export async function validateForCompile(recordId) {
.filter((id) => trackRows[id]?.length)
.map((id) => resolveTrackUniformity(id, trackRows[id], {
error: compileError,
- // Pre-fps manifests fall back to the legacy source-extraction rate (12),
- // not to the track's authoring default, so older sets compile to exactly
- // the same atlas they always did.
- defaultFps: id === WALK_TRACK ? WALK_FPS : undefined,
+ defaultFps: LEGACY_MANIFEST_FPS[id],
}));
const walk = tracks.find((t) => t.id === WALK_TRACK);
+ const runs = {};
+ for (const direction of SPRITE_DIRECTIONS) {
+ const { entry, manifest } = manifests[direction];
+ // Same frame-validity definition the approve gate uses (verifyPackagedFrames),
+ // here in its byte-verifying mode: existence + per-frame sha256 + gait-phase/
+ // order, reading each frame's bytes exactly once for read-once-verify-in-memory.
+ // Approve runs the existence-only prefix, so a set that passed approve cannot
+ // fail this for frame-existence reasons (#3001).
+ const { frameBytes } = await verifyPackagedFrames(recordId, manifest, { bytes: true });
+ runs[direction] = { runId: entry.runId, manifestPath: entry.runManifest, manifest, frameBytes };
+ }
+
return {
walkSet,
walkSetPath: walkSetRel,
@@ -324,9 +335,10 @@ export async function validateForCompile(recordId) {
anchors,
runs,
tracks,
+ // The walk view of `tracks`, kept because the published geometry names these
+ // exact fields in the runtime contract (walkFrameCount / walkFps).
walkFrameCount: walk?.frameCount ?? null,
walkFps: walk?.fps ?? null,
- walkLabels: walk?.labels ?? null,
};
}
@@ -440,9 +452,7 @@ export async function compileAtlasInTail(recordId, { geometry: geometryOverride
// historical 8 — and `tracks` names each track's `{ start, count }` span, so
// the grid, the manifest geometry and the published sidecar can never
// disagree about where a track's columns are.
- const { columns, tracks } = atlasGrid(
- validated.tracks.map(({ id, frameCount, labels }) => ({ id, frameCount, labels })),
- );
+ const { columns, tracks } = buildAtlasGrid(validated.tracks);
// Pre-pixel idempotency: the compile is deterministic, so an unchanged
// walk set + identical geometry means identical bytes by construction —
@@ -471,23 +481,14 @@ export async function compileAtlasInTail(recordId, { geometry: geometryOverride
return { ...current, created: false };
}
+ // compileDirectionRow still emits `idle` + this direction's walk frames, and
+ // verifyPackagedFrames has already asserted each frame's phase against the
+ // walk labels — so row/column agreement remains structural for the one track
+ // that exists. Making the row compiler span-driven (so it stays structural for
+ // a second track) belongs with the track that needs it, #3018.
const rows = [];
for (const direction of SPRITE_DIRECTIONS) {
- const row = await compileDirectionRow(recordId, direction, validated, geometry);
- // The grid is built from the registry's track spans while each row's cells
- // come from that direction's run manifests, so the two are only guaranteed
- // to line up if we say so. Before #3016 a single hardcoded `['idle', ...walk]`
- // made the agreement structural; with variable-length spans a track whose
- // pipeline emitted the wrong labels would otherwise composite silently into
- // the wrong columns and ship an atlas that contradicts its own descriptor.
- if (row.cells.length !== columns.length) {
- throw compileError(`Direction ${direction} compiled ${row.cells.length} cells but the grid has ${columns.length} columns`);
- }
- const misplaced = row.cells.findIndex((cell, c) => cell.column !== columns[c]);
- if (misplaced >= 0) {
- throw compileError(`Direction ${direction} column ${misplaced} is "${row.cells[misplaced].column}" but the grid expects "${columns[misplaced]}"`);
- }
- rows.push(row);
+ rows.push(await compileDirectionRow(recordId, direction, validated, geometry));
}
const { cellSize } = geometry;
diff --git a/server/services/sprites/atlasGrid.js b/server/services/sprites/atlasGrid.js
index 04400a314b..5b7b2fae9c 100644
--- a/server/services/sprites/atlasGrid.js
+++ b/server/services/sprites/atlasGrid.js
@@ -32,14 +32,18 @@
* state, or the image graph.
*
* **Only ONE track is registered today** (`walk`). The multi-track paths below
- * are proven against synthetic track rows and a synthetic registration order in
- * `atlasGrid.test.js` rather than by shipping a second track's artwork — that is
- * #3018's job, and it should land as a registry row plus its pipeline, with no
- * shape change here.
+ * are proven in `atlasGrid.test.js` against a synthetic REGISTRY TABLE rather
+ * than by shipping a second track's artwork. The registry table is the
+ * injection seam throughout — the same idiom `assertAnimationTrackRows(tracks)`
+ * uses — so a synthetic row flows through exactly the lookup, ordering and
+ * unknown-id boundary a real one would. Shipping a real second track is #3018's
+ * job, and it should land as a registry ROW plus its pipeline, with no shape
+ * change here.
*/
-import { ANIMATION_TRACK_IDS, WALK_TRACK, getAnimationTrack } from './animationTracks.js';
+import { ANIMATION_TRACKS, WALK_TRACK, getAnimationTrack } from './animationTracks.js';
import { ATLAS_IDLE_COLUMN, ATLAS_SCANNER_COLUMN, walkPhaseLabels } from './walkBounds.js';
+import { canonicalStringify } from '../../lib/objects.js';
/**
* Column labels for one track's span.
@@ -57,6 +61,9 @@ import { ATLAS_IDLE_COLUMN, ATLAS_SCANNER_COLUMN, walkPhaseLabels } from './walk
* what its non-contiguity guard reports as an undescribable grid.
*/
export function trackColumnLabels(trackId, frameCount) {
+ // A structural bound, not an authoring one: a track occupies at least one
+ // column. Whether the count is *legal to author* is the registry's business
+ // and is checked by resolveTrackUniformity against the track's own row.
if (!Number.isInteger(frameCount) || frameCount < 1) {
throw new Error(`Atlas track '${trackId}' needs a positive integer frame count, got ${frameCount}`);
}
@@ -65,7 +72,7 @@ export function trackColumnLabels(trackId, frameCount) {
}
/**
- * Build the atlas grid from a set of track specs (`{ id, frameCount, labels? }`).
+ * Build the atlas grid from a set of track specs (`{ id, frameCount }`).
*
* Returns `{ columns, tracks }` where `tracks` maps each track id to its
* contiguous `{ start, count }` column span — mutually consistent by
@@ -73,16 +80,20 @@ export function trackColumnLabels(trackId, frameCount) {
* sidecar's spans can never drift apart.
*
* `idle` is always column 0 and is described as a track of its own, matching
- * what the sidecar has always emitted. Specs are sorted into `trackOrder`
- * (the registry's registration order by default) rather than trusted in call
- * order, so two call sites that list tracks differently still produce the same
- * grid. `trackOrder` is injectable so the multi-track path can be proven against
- * a synthetic order while only `walk` is actually registered.
+ * what the sidecar has always emitted. Specs are sorted into the registry's
+ * registration order rather than trusted in call order, so two call sites that
+ * list tracks differently still produce the same grid, and an id the registry
+ * doesn't know is refused through `getAnimationTrack`'s own unknown-track
+ * boundary. The registry TABLE is the injection seam (the
+ * `assertAnimationTrackRows(tracks)` idiom) so the multi-track path can be
+ * proven against a synthetic table without a private lookup that would bypass
+ * that boundary.
*/
-export function buildAtlasGrid(specs, trackOrder = ANIMATION_TRACK_IDS) {
+export function buildAtlasGrid(specs, tracks = ANIMATION_TRACKS) {
if (!Array.isArray(specs) || !specs.length) {
throw new Error('Atlas grid needs at least one animation track');
}
+ const order = Object.keys(tracks);
const seen = new Set();
for (const spec of specs) {
const id = spec?.id;
@@ -92,24 +103,21 @@ export function buildAtlasGrid(specs, trackOrder = ANIMATION_TRACK_IDS) {
}
if (seen.has(id)) throw new Error(`Atlas grid lists track '${id}' twice`);
seen.add(id);
- if (!trackOrder.includes(id)) {
- throw new Error(`Atlas grid lists unknown track '${id}' — known tracks: ${trackOrder.join(', ')}`);
- }
+ getAnimationTrack(id, tracks);
}
- const ordered = [...specs].sort((a, b) => trackOrder.indexOf(a.id) - trackOrder.indexOf(b.id));
+ const ordered = [...specs].sort((a, b) => order.indexOf(a.id) - order.indexOf(b.id));
const columns = [ATLAS_IDLE_COLUMN];
- const tracks = { [ATLAS_IDLE_COLUMN]: { start: 0, count: 1 } };
+ const spans = { [ATLAS_IDLE_COLUMN]: { start: 0, count: 1 } };
for (const spec of ordered) {
- const labels = Array.isArray(spec.labels) ? [...spec.labels] : trackColumnLabels(spec.id, spec.frameCount);
- if (Number.isInteger(spec.frameCount) && labels.length !== spec.frameCount) {
- throw new Error(`Atlas track '${spec.id}' declares ${spec.frameCount} frames but supplies ${labels.length} column labels`);
- }
- if (!labels.length) throw new Error(`Atlas track '${spec.id}' has no columns`);
- tracks[spec.id] = { start: columns.length, count: labels.length };
+ // Labels are DERIVED, never supplied: trackColumnLabels is total and
+ // deterministic, so accepting them from the caller would only create a
+ // mismatch the builder then has to reconcile against itself.
+ const labels = trackColumnLabels(spec.id, spec.frameCount);
+ spans[spec.id] = { start: columns.length, count: labels.length };
columns.push(...labels);
}
- return { columns, tracks };
+ return { columns, tracks: spans };
}
/**
@@ -199,7 +207,7 @@ export function deriveTracks(columns, walkFrameCount, compiledTracks = null) {
}
/** Non-throwing `deriveTracks` — `{ tracks }` or `{ error }`. */
-export function describeTracks(columns, walkFrameCount, compiledTracks = null) {
+function describeTracks(columns, walkFrameCount, compiledTracks = null) {
if (!Array.isArray(columns) || !columns.length) {
return { error: 'Compiled atlas geometry has no column list' };
}
@@ -259,7 +267,14 @@ export function compiledGridUpToDate(current, expected) {
if (JSON.stringify(current.columns) !== JSON.stringify(expected.columns)) return false;
const described = describeTracks(current.columns, resolveWalkFrameCount(current), current.tracks ?? null);
if (described.error) return false;
- return JSON.stringify(described.tracks) === JSON.stringify(expected.tracks);
+ // canonicalStringify, NOT JSON.stringify: the two sides are built by three
+ // different producers with three different key-insertion orders
+ // (buildAtlasGrid inserts idle then registry order; validateCompiledTracks
+ // re-inserts sorted by start; the legacy branch inserts in column-index
+ // order). A key-order-sensitive compare would report "not up to date" forever
+ // and re-run the whole pixel pipeline on every compile — precisely the
+ // failure this predicate exists to avoid.
+ return canonicalStringify(described.tracks) === canonicalStringify(expected.tracks);
}
/**
@@ -273,14 +288,16 @@ export function compiledGridUpToDate(current, expected) {
* check reads the named track's own registry row (#3015) instead of the global
* walk-shaped 6–16 / 4–24 constants.
*
- * `rows` are `{ direction, frameCount, declaredFrameCount, fps }`.
- * `trackRow` and `error` are injectable so the multi-track path can be proven
- * against a synthetic row while `walk` is the only registered track, and so this
- * leaf stays free of the error-handler import (callers pass the 422-shaped
- * `compileError`). Returns `{ id, frameCount, fps, labels }`.
+ * `rows` are `{ direction, frameCount, declaredFrameCount, fps }`. The registry
+ * `tracks` table is the injection seam (as in `buildAtlasGrid`), and `error` is
+ * injectable so this leaf stays free of the error-handler import — callers pass
+ * the 422-shaped `compileError`. `defaultFps` covers a track whose historical
+ * manifests predate the fps field and must keep resolving to the exact value
+ * they always did. Returns `{ id, frameCount, fps, labels }`.
*/
export function resolveTrackUniformity(trackId, rows, {
- trackRow = getAnimationTrack(trackId),
+ tracks = ANIMATION_TRACKS,
+ trackRow = getAnimationTrack(trackId, tracks),
error = (message) => new Error(message),
defaultFps = trackRow.defaultFps,
} = {}) {
diff --git a/server/services/sprites/atlasGrid.test.js b/server/services/sprites/atlasGrid.test.js
index aa8fff9947..227453cfb2 100644
--- a/server/services/sprites/atlasGrid.test.js
+++ b/server/services/sprites/atlasGrid.test.js
@@ -3,7 +3,10 @@
* pre-pixel up-to-date comparison. Pure module: no fs, no compiler, no sharp.
*
* Only ONE track (`walk`) is registered today, so every multi-track assertion
- * here runs against a SYNTHETIC track row and a synthetic registration order.
+ * here runs against a SYNTHETIC registry table — the same injected-table idiom
+ * `assertAnimationTrackRows(tracks)` uses, so a synthetic row flows through
+ * exactly the lookup, ordering and unknown-id boundary a real second row would.
+ *
* That is deliberate: proving the multi-track path against the shipped
* single-row table would only re-derive the implementation — the whole span
* builder could collapse back to `['idle', ...walkLabels]` and such a test would
@@ -13,11 +16,11 @@
import { describe, it, expect } from 'vitest';
import {
- trackColumnLabels, buildAtlasGrid, deriveTracks, describeTracks,
+ trackColumnLabels, buildAtlasGrid, deriveTracks,
resolveWalkFrameCount, compiledGridUpToDate, resolveTrackUniformity,
} from './atlasGrid.js';
import { walkPhaseLabels } from './walkBounds.js';
-import { getAnimationTrack } from './animationTracks.js';
+import { getAnimationTrack, ANIMATION_TRACKS } from './animationTracks.js';
// A second track that does NOT exist in the registry, shaped like a short
// action animation: four frames, which sits BELOW walk's floor of 6 — the exact
@@ -35,7 +38,7 @@ const SCANNER_ROW = Object.freeze({
contractFrameCountField: 'scannerFrameCount',
contractFpsField: null,
});
-const TWO_TRACK_ORDER = ['walk', 'scanner'];
+const TWO_TRACK_REGISTRY = Object.freeze({ walk: ANIMATION_TRACKS.walk, scanner: SCANNER_ROW });
const DIRECTIONS = ['S', 'SE', 'E', 'NE', 'N', 'NW', 'W', 'SW'];
const rowsFor = (frameCount, fps, overrides = {}) =>
@@ -80,7 +83,7 @@ describe('buildAtlasGrid', () => {
// The whole point of #3016: a 4-frame action beside a 12-frame walk.
const grid = buildAtlasGrid(
[{ id: 'walk', frameCount: 12 }, { id: 'scanner', frameCount: 4 }],
- TWO_TRACK_ORDER,
+ TWO_TRACK_REGISTRY,
);
expect(grid.columns).toEqual([
'idle', ...walkPhaseLabels(12),
@@ -102,11 +105,11 @@ describe('buildAtlasGrid', () => {
it('sorts specs into registration order rather than call order', () => {
const asGiven = buildAtlasGrid(
[{ id: 'scanner', frameCount: 4 }, { id: 'walk', frameCount: 6 }],
- TWO_TRACK_ORDER,
+ TWO_TRACK_REGISTRY,
);
const reversed = buildAtlasGrid(
[{ id: 'walk', frameCount: 6 }, { id: 'scanner', frameCount: 4 }],
- TWO_TRACK_ORDER,
+ TWO_TRACK_REGISTRY,
);
expect(asGiven).toEqual(reversed);
expect(asGiven.tracks.walk.start).toBeLessThan(asGiven.tracks.scanner.start);
@@ -117,13 +120,16 @@ describe('buildAtlasGrid', () => {
expect(() => buildAtlasGrid([{ frameCount: 8 }])).toThrow(/needs an id/);
expect(() => buildAtlasGrid([{ id: 'walk', frameCount: 8 }, { id: 'walk', frameCount: 6 }]))
.toThrow(/lists track 'walk' twice/);
- // `idle` is the anchor column, never a registrable track.
- expect(() => buildAtlasGrid([{ id: 'idle', frameCount: 1 }], ['idle']))
+ // `idle` is the anchor column, never a registrable track — even if some
+ // future registry tried to claim it.
+ expect(() => buildAtlasGrid([{ id: 'idle', frameCount: 1 }], { idle: SCANNER_ROW }))
.toThrow(/the idle anchor owns that column/);
+ // Unknown ids are refused through the registry's OWN boundary, so the grid
+ // can't develop a second, more permissive idea of what a track is.
expect(() => buildAtlasGrid([{ id: 'scanner', frameCount: 4 }]))
- .toThrow(/unknown track 'scanner'/);
- expect(() => buildAtlasGrid([{ id: 'walk', frameCount: 8, labels: ['a', 'b'] }]))
- .toThrow(/declares 8 frames but supplies 2 column labels/);
+ .toThrow(/Unknown animation track 'scanner'/);
+ expect(() => buildAtlasGrid([{ id: 'walk', frameCount: 0 }]))
+ .toThrow(/positive integer frame count/);
});
});
@@ -131,7 +137,7 @@ describe('deriveTracks', () => {
it('prefers a persisted descriptor over the legacy column-name derivation', () => {
const grid = buildAtlasGrid(
[{ id: 'walk', frameCount: 6 }, { id: 'scanner', frameCount: 4 }],
- TWO_TRACK_ORDER,
+ TWO_TRACK_REGISTRY,
);
expect(deriveTracks(grid.columns, 6, grid.tracks)).toEqual(grid.tracks);
// …and the descriptor is genuinely load-bearing: without it the legacy
@@ -176,7 +182,6 @@ describe('deriveTracks', () => {
it('reports an undescribable grid rather than lying about it', () => {
expect(() => deriveTracks(['idle', 'scanner', 'idle'], 0)).toThrow(/non-contiguously/);
expect(() => deriveTracks([], 0)).toThrow(/no column list/);
- expect(describeTracks([], 0).error).toMatch(/no column list/);
});
});
@@ -270,7 +275,7 @@ describe('resolveTrackUniformity', () => {
// never a between-track one. A 4-frame / 6 fps scanner sits below walk's
// floor of 6 frames and is resolved against ITS OWN registry row.
const walk = resolveTrackUniformity('walk', rowsFor(12, 10));
- const scanner = resolveTrackUniformity('scanner', rowsFor(4, 6), { trackRow: SCANNER_ROW });
+ const scanner = resolveTrackUniformity('scanner', rowsFor(4, 6), { tracks: TWO_TRACK_REGISTRY });
expect(walk.frameCount).toBe(12);
expect(scanner.frameCount).toBe(4);
expect(scanner.fps).toBe(6);
@@ -280,9 +285,9 @@ describe('resolveTrackUniformity', () => {
expect(() => resolveTrackUniformity('walk', rowsFor(4, 6)))
.toThrow(/outside the supported 6–16 range/);
// …and 12 frames is out of range for the scanner's own row.
- expect(() => resolveTrackUniformity('scanner', rowsFor(12, 6), { trackRow: SCANNER_ROW }))
+ expect(() => resolveTrackUniformity('scanner', rowsFor(12, 6), { tracks: TWO_TRACK_REGISTRY }))
.toThrow(/outside the supported 2–8 range/);
- expect(() => resolveTrackUniformity('scanner', rowsFor(4, 20), { trackRow: SCANNER_ROW }))
+ expect(() => resolveTrackUniformity('scanner', rowsFor(4, 20), { tracks: TWO_TRACK_REGISTRY }))
.toThrow(/fps 20 is outside the supported 2–12 range/);
});
@@ -296,7 +301,7 @@ describe('resolveTrackUniformity', () => {
it('falls back to the supplied default fps for pre-fps manifests', () => {
// Older run manifests carry no frameRate at all — they must keep compiling.
expect(resolveTrackUniformity('walk', rowsFor(12, undefined), { defaultFps: 12 }).fps).toBe(12);
- expect(resolveTrackUniformity('scanner', rowsFor(4, undefined), { trackRow: SCANNER_ROW }).fps)
+ expect(resolveTrackUniformity('scanner', rowsFor(4, undefined), { tracks: TWO_TRACK_REGISTRY }).fps)
.toBe(SCANNER_ROW.defaultFps);
});
diff --git a/server/services/sprites/atlasLayout.js b/server/services/sprites/atlasLayout.js
index 09b730b7f2..72e59f62d7 100644
--- a/server/services/sprites/atlasLayout.js
+++ b/server/services/sprites/atlasLayout.js
@@ -44,10 +44,6 @@
import { basename } from 'path';
import { deriveTracks, resolveWalkFrameCount } from './atlasGrid.js';
-// Re-exported so the sidecar's public surface is unchanged for its consumers
-// and tests: atlasGrid.js is where they live, atlasLayout.js is where they were.
-export { deriveTracks, resolveWalkFrameCount } from './atlasGrid.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.
export const ATLAS_LAYOUT_SCHEMA_VERSION = 1;
diff --git a/server/services/sprites/atlasLayout.test.js b/server/services/sprites/atlasLayout.test.js
index a658196340..f73e5678d8 100644
--- a/server/services/sprites/atlasLayout.test.js
+++ b/server/services/sprites/atlasLayout.test.js
@@ -5,11 +5,14 @@
import { describe, it, expect } from 'vitest';
import {
- buildAtlasLayout, deriveTracks, layoutSidecarPath, resolveWalkFrameCount,
- runtimeContractMismatch, ATLAS_LAYOUT_SCHEMA_VERSION,
+ buildAtlasLayout, layoutSidecarPath, runtimeContractMismatch, ATLAS_LAYOUT_SCHEMA_VERSION,
} from './atlasLayout.js';
import { walkPhaseLabels } from './walkBounds.js';
-import { buildAtlasGrid } from './atlasGrid.js';
+// The span math moved to atlasGrid.js (#3016) — one public path, no re-export
+// shim. The cases below exercise it through SIDECAR-shaped geometry fixtures;
+// atlasGrid.test.js owns the module's own unit coverage.
+import { buildAtlasGrid, deriveTracks, resolveWalkFrameCount } from './atlasGrid.js';
+import { ANIMATION_TRACKS } from './animationTracks.js';
const DIRECTIONS = ['S', 'SE', 'E', 'NE', 'N', 'NW', 'W', 'SW'];
// The grid the compiler emits today: idle + N walk phases (#2986 dropped the
@@ -141,7 +144,7 @@ describe('buildAtlasLayout', () => {
// fixture is the point rather than a shortcut).
const grid = buildAtlasGrid(
[{ id: 'walk', frameCount: 12 }, { id: 'scanner', frameCount: 4 }],
- ['walk', 'scanner'],
+ { ...ANIMATION_TRACKS, scanner: { ...ANIMATION_TRACKS.walk, id: 'scanner' } },
);
const layout = buildAtlasLayout({
characterId: 'example-character',