Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat([issue-3016]): pack multiple animation tracks of differing lengths into one atlas grid

[._.]/ Adam Eivya180349e1c3a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index e75cc7a411..488006fc76 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -13,6 +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-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/docs/features/sprite-export-contract.md b/docs/features/sprite-export-contract.md
index cee32c8361..bf095fb47d 100644
--- a/docs/features/sprite-export-contract.md
+++ b/docs/features/sprite-export-contract.md
@@ -13,10 +13,14 @@ The compiler (`server/services/sprites/atlas.js`) produces one PNG: a fixed-cell
| Cell size | 96 × 96 px (overridable per compile; the published geometry is whatever was compiled) |
| Pivot | `(48, 88)` — silhouette centered on x, feet on the y ground line |
| Rows | 8, in `directionOrder`: `south`, `south-east`, `east`, `north-east`, `north`, `north-west`, `west`, `south-west` |
-| Columns | `idle` at 0, the N walk phases from 1 |
-| N (walk frame count) | authorable, 6–16 (`walkBounds.js`); historically always 8 |
+| Columns | `idle` at 0, then one contiguous span per animation track in registration order — the N walk phases from 1 |
+| N (walk frame count) | authorable, 6–16 (`animationTracks.js`); historically always 8 |
-`N` is read from the approved run manifests — every direction in one atlas must share it — so the atlas width tracks the authored count. **That makes the column layout a moving target for anything that hardcodes it.**
+`N` is read from the approved run manifests — every direction of a track must share it — so the atlas width tracks the authored count. **That makes the column layout a moving target for anything that hardcodes it.**
+
+Frame-count and fps uniformity is a **within-track** rule, never a between-track one: all 8 facings of a given track share a column span because the atlas is a rectangular grid, but two different tracks may legally differ in both length and speed (a four-frame action beside a twelve-frame walk). Each track's authoring range comes from its own row in `server/services/sprites/animationTracks.js`, and its column span is recorded in `geometry.tracks` and republished in the sidecar. Only `walk` is registered today.
+
+Non-walk tracks namespace their column labels with the track id (`scanner-00`, `scanner-01`, …). Walk keeps its historical labels — the named gait phases at 8 frames, positional `frame-NN` at any other length — so existing and imported atlases round-trip unchanged.
> **Atlases compiled before #2986 carry one extra trailing `scanner` column** — a verbatim copy of the idle cell, from an early render, that no consumer ever sampled. The compiler no longer emits it (an action animation is its own named track, not a column appended to the walk cycle), so an 8-frame grid is 9 columns wide rather than 10. Reading side is unchanged: an imported or previously published atlas that still has the column keeps loading, and its sidecar still describes the `scanner` span it really has. Recompiling a set drops the column and produces a new atlas version; existing published atlases are untouched until republished.
@@ -58,7 +62,8 @@ Nothing else crosses. The compile manifest, the run provenance, the trims, and t
Consumer guidance:
-- **Resolve columns by name, not by constant.** `tracks` gives each animation track a column span, so a walk of any length — and any future track (a four-frame scanner action, a three-frame ambient loop) — is additive rather than a breaking re-read. A track that isn't in the grid simply isn't in `tracks`; don't assume one is present. `columns` is the flat list for anything that wants raw names.
+- **Resolve columns by name, not by constant.** `tracks` gives each animation track a column span, so a walk of any length — and any additional track (a four-frame scanner action, a three-frame ambient loop) — is additive rather than a breaking re-read. A track that isn't in the grid simply isn't in `tracks`; don't assume one is present. `columns` is the flat list for anything that wants raw names.
+- **`tracks` tiles `columns` exactly.** The spans are contiguous, non-overlapping, and sum to `columnCount` — so `cellSize × columnCount` is the PNG width and a span always addresses real pixels. A sidecar whose spans disagreed with its own column list is refused at publish rather than shipped.
- **Verify before you trust.** `sourceAtlasSha256` identifies the atlas the layout describes. The sidecar is written *before* the PNG on each publish, so a partially-completed publish is detectable (hash mismatch) rather than silent.
- **The sidecar carries no timestamp** — identical geometry produces byte-identical content, so an unchanged republish rewrites nothing.
- The sidecar shares the PNG's per-repo write serialization and its occupied-destination guard: an atlas whose sidecar was deleted gets it back on the next publish, and a file at that path PortOS didn't write (no `kind: portos-sprite-atlas-layout`, or not valid JSON at all) is never replaced without an explicit overwrite acknowledgment. It has no *divergence* guard — unlike the PNG, a PortOS-written sidecar someone hand-edited is simply regenerated, since it is derived data.
@@ -88,7 +93,9 @@ Two mechanisms guard that:
| Path | Role |
|---|---|
-| `server/services/sprites/atlas.js` | Compiles the atlas; owns `atlasColumns()` and the geometry block |
+| `server/services/sprites/atlas.js` | Compiles the atlas; owns the geometry block and the pre-pixel up-to-date check |
+| `server/services/sprites/atlasGrid.js` | The grid itself: column spans per track, within-track uniformity, reading a persisted (or legacy) grid back |
+| `server/services/sprites/animationTracks.js` | One row per animation track — its bounds, defaults, and directionality |
| `server/services/sprites/atlasLayout.js` | Builds the sidecar payload; compares geometry against a runtime contract |
| `server/services/sprites/publish.js` | Binding validation, the publish-time guard, the atomic PNG + sidecar write |
| `server/services/sprites/walkBounds.js` | The authorable frame-count / fps ranges |
diff --git a/server/services/sprites/atlas.js b/server/services/sprites/atlas.js
index 8d7f0ccad1..d8784a318d 100644
--- a/server/services/sprites/atlas.js
+++ b/server/services/sprites/atlas.js
@@ -40,13 +40,14 @@ import { requireCharacter, loadManifest } from './reference.js';
import { SPRITE_DIRECTIONS } from './prompts.js';
import { keyChannelSplit } from './chromaKey.js';
import {
- WALK_PHASES, walkPhaseLabels, WALK_MIN_FRAME_COUNT, WALK_MAX_FRAME_COUNT,
- WALK_MIN_FPS, WALK_MAX_FPS, WALK_FPS,
+ WALK_PHASES, WALK_FPS,
pyRound, pyRoundTo, median, decodeRgbaFrame, premultipliedResize,
sampleBorderKey, validateMeasuredKey, recoverAlphaFrame, despillKeyFrame,
alphaBbox, compositeOnto, sha256Buffer,
} from './walkPostprocess.js';
import { ATLAS_IDLE_COLUMN } from './walkBounds.js';
+import { WALK_TRACK, ANIMATION_TRACK_IDS } from './animationTracks.js';
+import { buildAtlasGrid, resolveTrackUniformity, compiledGridUpToDate } from './atlasGrid.js';
import {
withWalkWriteTail, walkSetRelPath, importedWalkDirections,
} from './walk.js';
@@ -56,21 +57,29 @@ import { verifyPackagedFrames } from './walkFrames.js';
// pivot (48,88) — silhouette centered on x=48, feet on the y=88 ground line —
// content bounded to 86×74 so nothing touches a cell edge.
//
-// The runtime grid is `idle` + the N walk-phase columns. N is the walk set's
-// frame count (variable-frame walks: #sprite-walk-variable-frames); it is read
-// from the approved run manifests, not hardcoded, so the atlas width
-// grows/shrinks with the chosen count. ATLAS_COLUMNS is the historical 8-frame
-// layout, kept as the default/fallback; atlasColumns(labels) builds the actual
-// column list a given compile uses.
+// The runtime grid is `idle` followed by one variable-length column span per
+// animation track, in registry-registration order (#3016). Each track's length
+// is read from its approved run manifests, not hardcoded, so the atlas width
+// grows and shrinks with what was actually authored — and two tracks may
+// legally differ in length, which is what makes a four-frame action beside a
+// twelve-frame walk expressible. The span math lives in the sharp-free
+// 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.
//
// 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
-// compiled: an action animation is its own named track (per-track spans in the
-// layout sidecar, atlasLayout.js), not a column bolted 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 atlasColumns = (walkLabels) => [ATLAS_IDLE_COLUMN, ...walkLabels];
-export const ATLAS_COLUMNS = atlasColumns(WALK_PHASES);
+// compiled: an action animation is its own named track, not a column bolted
+// 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 DEFAULT_ATLAS_GEOMETRY = {
cellSize: 96,
pivot: [48, 88],
@@ -257,11 +266,14 @@ export async function validateForCompile(recordId) {
}
const runs = {};
- // Resolved from the first approved direction, then enforced identical across
- // the rest (see the loop body). null until the first direction is read.
- let frameCount = null;
- let walkFps = null;
- let walkLabels = null;
+ // 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.
+ const trackRows = { [WALK_TRACK]: [] };
for (const direction of SPRITE_DIRECTIONS) {
const entry = walkSet.directions?.[direction];
if (!entry || entry.status !== 'approved') throw compileError(`Direction ${direction} is not approved`);
@@ -275,36 +287,12 @@ export async function validateForCompile(recordId) {
if (!manifest || manifest.direction !== direction) {
throw compileError(`Run manifest for ${direction} is unreadable or mislabeled`);
}
- const frames = manifest.frames || [];
- // Frame count is variable, but every direction in ONE atlas MUST share it —
- // the atlas is a rectangular grid, so a ragged set can't compile. The first
- // approved direction sets N; the rest must match. N must also be in range and
- // agree with the manifest's declared frameCount.
- if (frameCount === null) {
- frameCount = frames.length;
- if (!Number.isInteger(frameCount)
- || frameCount < WALK_MIN_FRAME_COUNT || frameCount > WALK_MAX_FRAME_COUNT) {
- throw compileError(`Direction ${direction} has ${frames.length} frames — outside the supported ${WALK_MIN_FRAME_COUNT}–${WALK_MAX_FRAME_COUNT} range`);
- }
- walkLabels = walkPhaseLabels(frameCount);
- } else if (frames.length !== frameCount) {
- throw compileError(`Direction ${direction} has ${frames.length} frames but the set uses ${frameCount} — reprocess all directions to the same frame count before compiling`);
- }
- if (Number.isInteger(manifest.frameCount) && manifest.frameCount !== frames.length) {
- throw compileError(`Direction ${direction} manifest declares ${manifest.frameCount} frames but carries ${frames.length}`);
- }
- // Playback fps likewise must agree across directions so the whole walk set
- // animates at one speed. Range-checked; falls back to the legacy 12 for
- // pre-fps manifests so older sets still compile.
- const dirFps = Number.isFinite(manifest.frameRate) ? manifest.frameRate : WALK_FPS;
- if (dirFps < WALK_MIN_FPS || dirFps > WALK_MAX_FPS) {
- throw compileError(`Direction ${direction} playback fps ${dirFps} is outside the supported ${WALK_MIN_FPS}–${WALK_MAX_FPS} range`);
- }
- if (walkFps === null) {
- walkFps = dirFps;
- } else if (dirFps !== walkFps) {
- throw compileError(`Direction ${direction} plays at ${dirFps} fps but the set uses ${walkFps} — reprocess all directions to the same speed before compiling`);
- }
+ 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.
@@ -314,6 +302,19 @@ export async function validateForCompile(recordId) {
runs[direction] = { runId: entry.runId, manifestPath: entry.runManifest, manifest, frameBytes };
}
+ // Registration order, so the compiled grid's span order is stable regardless
+ // of the order the rows happened to be collected in.
+ const tracks = ANIMATION_TRACK_IDS
+ .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,
+ }));
+ const walk = tracks.find((t) => t.id === WALK_TRACK);
+
return {
walkSet,
walkSetPath: walkSetRel,
@@ -322,9 +323,10 @@ export async function validateForCompile(recordId) {
chromaKey,
anchors,
runs,
- walkFrameCount: frameCount,
- walkFps,
- walkLabels,
+ tracks,
+ walkFrameCount: walk?.frameCount ?? null,
+ walkFps: walk?.fps ?? null,
+ walkLabels: walk?.labels ?? null,
};
}
@@ -434,20 +436,26 @@ export async function compileAtlasInTail(recordId, { geometry: geometryOverride
const validated = await validateForCompile(recordId);
const dir = spriteDir(recordId);
- // Columns/width follow the set's actual frame count, not the historical 8.
- const columns = atlasColumns(validated.walkLabels);
+ // Columns/width follow the set's actual per-track frame counts, not the
+ // 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 })),
+ );
// Pre-pixel idempotency: the compile is deterministic, so an unchanged
// walk set + identical geometry means identical bytes by construction —
// skip the whole pixel pipeline. The evidence chain was still revalidated
// above; the post-encode sha comparison below stays as the fallback for a
// pointer whose geometry fields predate a shape change.
- // The COLUMN LIST is part of that geometry comparison, not just the cell
- // metrics: a grid-shape change (#2986 dropping the trailing scanner column)
- // leaves every cell metric identical, so without it a pre-#2986 pointer would
- // be returned as up-to-date and the stale wider atlas would never recompile.
- // A pointer predating the columns field at all (undefined) also falls through,
- // which is correct — the post-encode sha compare then decides.
+ // `compiledGridUpToDate` compares the GRID, not just the cell metrics: a
+ // grid-shape change (#2986 dropping the trailing scanner column) leaves every
+ // cell metric identical, and a track-SET change can leave even the column
+ // count identical, so both the column list and the track spans are part of
+ // the comparison (#3016). A pointer predating either field is described the
+ // legacy way rather than treated as a mismatch, so upgrading an install
+ // doesn't condemn every existing atlas to recompile its pixels forever.
// Both idempotent early-returns require the pointed-at atlas file to still
// exist — otherwise a deleted runtime/vN PNG would loop forever ("recompile"
// → pointer returned untouched → still missing); falling through re-writes
@@ -458,18 +466,28 @@ export async function compileAtlasInTail(recordId, { geometry: geometryOverride
current
&& currentAtlasOnDisk
&& current.walkSetSha256 === validated.walkSetSha256
- && current.geometry?.cellSize === geometry.cellSize
- && JSON.stringify(current.geometry?.pivot) === JSON.stringify(geometry.pivot)
- && current.geometry?.targetMaxHeight === geometry.targetMaxHeight
- && current.geometry?.targetMaxWidth === geometry.targetMaxWidth
- && JSON.stringify(current.geometry?.columns) === JSON.stringify(columns)
+ && compiledGridUpToDate(current.geometry, { ...geometry, columns, tracks })
) {
return { ...current, created: false };
}
const rows = [];
for (const direction of SPRITE_DIRECTIONS) {
- rows.push(await compileDirectionRow(recordId, direction, validated, geometry));
+ 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);
}
const { cellSize } = geometry;
@@ -547,6 +565,11 @@ export async function compileAtlasInTail(recordId, { geometry: geometryOverride
atlasSha256,
geometry: {
columns,
+ // Each track's `{ start, count }` column span (#3016). Additive: readers
+ // that predate it (and every atlas compiled before it) fall back to the
+ // legacy column-name derivation in atlasGrid.deriveTracks, so no migration
+ // is needed and imported/pre-#2986 grids keep describing themselves.
+ tracks,
directionOrder: SPRITE_DIRECTIONS,
rows: SPRITE_DIRECTIONS.length,
cellSize,
diff --git a/server/services/sprites/atlas.test.js b/server/services/sprites/atlas.test.js
index 1f2ca37a72..cb2b1618e8 100644
--- a/server/services/sprites/atlas.test.js
+++ b/server/services/sprites/atlas.test.js
@@ -235,6 +235,78 @@ describe('compileAtlas', () => {
expect(again.geometry.widthPx).toBe(DEFAULT_ATLAS_GEOMETRY.cellSize * 9);
});
+ it('records each track\'s column span in the compiled geometry (#3016)', async () => {
+ const id = newId();
+ await lockAllAnchors(id);
+ await buildFinalizedWalkSet(id, { frameCount: 12, fps: 8 });
+ const result = await compileAtlas(id);
+
+ const manifest = JSON.parse(await readFile(join(TEST_ROOT, 'sprites', id, result.manifestPath), 'utf8'));
+ expect(manifest.geometry.tracks).toEqual({
+ idle: { start: 0, count: 1 },
+ walk: { start: 1, count: 12 },
+ });
+ // The descriptor, the column list and the emitted PNG width all describe
+ // the same grid — a consumer resolving a track by span lands on the pixels
+ // the width accounts for.
+ const spanned = Object.values(manifest.geometry.tracks).reduce((n, s) => n + s.count, 0);
+ expect(spanned).toBe(manifest.geometry.columns.length);
+ expect(manifest.geometry.widthPx).toBe(DEFAULT_ATLAS_GEOMETRY.cellSize * spanned);
+ // The pointer carries the same geometry, so the publish path sees it too.
+ expect(result.geometry.tracks).toEqual(manifest.geometry.tracks);
+ });
+
+ it('recompiles a set whose pointer describes a DIFFERENT track set over the same columns', async () => {
+ const id = await finalizedCharacter();
+ const first = await compileAtlas(id);
+
+ // #2986's lesson one level up: a grid-shape change can leave every cell
+ // metric identical, and a TRACK-SET change can leave even the column list
+ // identical. Here the pointer keeps its exact column names and count but
+ // re-partitions them into three tracks — a different grid that must
+ // recompile. Only the atlas hash is falsified, so if the cheap pre-pixel
+ // check failed to notice the track change it would return the stale pointer
+ // untouched instead of writing a new version.
+ const pointerAbs = join(TEST_ROOT, 'sprites', id, 'runtime/current.json');
+ const pointer = JSON.parse(await readFile(pointerAbs, 'utf8'));
+ expect(pointer.geometry.tracks).toEqual({ idle: { start: 0, count: 1 }, walk: { start: 1, count: 8 } });
+ pointer.atlasSha256 = 'f'.repeat(64);
+ pointer.geometry = {
+ ...pointer.geometry,
+ tracks: {
+ idle: { start: 0, count: 1 },
+ walk: { start: 1, count: 4 },
+ scanner: { start: 5, count: 4 },
+ },
+ };
+ await writeFile(pointerAbs, JSON.stringify(pointer));
+
+ const again = await compileAtlas(id);
+ expect(again.created).toBe(true);
+ expect(again.version).toBe(first.version + 1);
+ expect(again.geometry.columns).toEqual(['idle', ...WALK_PHASES]);
+ expect(again.geometry.tracks).toEqual({ idle: { start: 0, count: 1 }, walk: { start: 1, count: 8 } });
+ });
+
+ it('stays idempotent for a legacy pointer written before the tracks descriptor existed', async () => {
+ const id = await finalizedCharacter();
+ const first = await compileAtlas(id);
+
+ // Every atlas compiled before #3016 has no `geometry.tracks`. It must still
+ // read as up to date, or upgrading an install re-runs the whole pixel
+ // pipeline on every compile of every existing character, forever (the
+ // pointer is never rewritten on the identical-bytes path, so it would never
+ // gain the field and never stop).
+ const pointerAbs = join(TEST_ROOT, 'sprites', id, 'runtime/current.json');
+ const pointer = JSON.parse(await readFile(pointerAbs, 'utf8'));
+ delete pointer.geometry.tracks;
+ await writeFile(pointerAbs, JSON.stringify(pointer));
+
+ const again = await compileAtlas(id);
+ expect(again.created).toBe(false);
+ expect(again.version).toBe(first.version);
+ });
+
it('refuses to compile a set whose directions disagree on frame count', async () => {
const id = newId();
await lockAllAnchors(id);
diff --git a/server/services/sprites/atlasGrid.js b/server/services/sprites/atlasGrid.js
new file mode 100644
index 0000000000..04400a314b
--- /dev/null
+++ b/server/services/sprites/atlasGrid.js
@@ -0,0 +1,320 @@
+/**
+ * Sprites — the atlas grid: column spans, per-track uniformity, and the
+ * up-to-date comparison (issue #3016).
+ *
+ * The runtime atlas used to be 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 world with
+ * exactly one animation and both blocked a second — a four-frame scanner action
+ * beside a twelve-frame walk needs the grid to express **variable-length column
+ * spans**, and needs uniformity to be a *within-track* rule (all 8 facings of
+ * one track share a row width) rather than a *between-track* one.
+ *
+ * This module is that grid. It owns three things the write side (atlas.js) and
+ * the describe side (atlasLayout.js) must never disagree about:
+ *
+ * - **`buildAtlasGrid`** — the span builder. `idle` is column 0, then each
+ * track's columns in stable registry-registration order, yielding both the
+ * flat `columns` list and the `{ start, count }` `tracks` descriptor the
+ * published `layout.json` sidecar carries (#2982).
+ * - **`resolveTrackUniformity`** — one track's frame count / fps resolved from
+ * its per-direction rows, asserting the 8 facings agree. It NEVER compares one
+ * track to another, and it range-checks against the *named track's* registry
+ * row (#3015) rather than the global walk-shaped constants.
+ * - **`deriveTracks` / `compiledGridUpToDate`** — reading a persisted grid back,
+ * including every legacy shape (a pointer with no `tracks` field, a pre-#2986
+ * grid that still carries a `scanner` column, a pre-#2970 one with no
+ * `walkFrameCount`).
+ *
+ * **Sharp-free leaf, deliberately** — same contract as `animationTracks.js` and
+ * `walkBounds.js`. atlas.js imports sharp; atlasLayout.js must not, so the one
+ * definition of a column span has to live below both. Nothing here touches fs,
+ * 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.
+ */
+
+import { ANIMATION_TRACK_IDS, WALK_TRACK, getAnimationTrack } from './animationTracks.js';
+import { ATLAS_IDLE_COLUMN, ATLAS_SCANNER_COLUMN, walkPhaseLabels } from './walkBounds.js';
+
+/**
+ * Column labels for one track's span.
+ *
+ * The walk track keeps its historical labels verbatim — the named 2-beat gait
+ * phases at 8 frames, positional `frame-NN` at any other length — so every
+ * existing atlas, manifest, and imported grid round-trips byte-identically.
+ *
+ * Every OTHER track namespaces its columns with its own id (`scanner-00`).
+ * Positional labels are per-track ordinals, so two four-frame tracks would
+ * otherwise both emit `frame-00…frame-03` and the flat `columns` list — which
+ * consumers are told to resolve BY NAME (docs/features/sprite-export-contract.md)
+ * — would carry duplicates that no reader could disambiguate. Namespacing also
+ * keeps the legacy `deriveTracks` fallback honest: a duplicated label is exactly
+ * what its non-contiguity guard reports as an undescribable grid.
+ */
+export function trackColumnLabels(trackId, frameCount) {
+ if (!Number.isInteger(frameCount) || frameCount < 1) {
+ throw new Error(`Atlas track '${trackId}' needs a positive integer frame count, got ${frameCount}`);
+ }
+ if (trackId === WALK_TRACK) return walkPhaseLabels(frameCount);
+ return Array.from({ length: frameCount }, (_, i) => `${trackId}-${String(i).padStart(2, '0')}`);
+}
+
+/**
+ * Build the atlas grid from a set of track specs (`{ id, frameCount, labels? }`).
+ *
+ * Returns `{ columns, tracks }` where `tracks` maps each track id to its
+ * contiguous `{ start, count }` column span — mutually consistent by
+ * construction, so the emitted PNG width (`cellSize × columns.length`) and the
+ * 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.
+ */
+export function buildAtlasGrid(specs, trackOrder = ANIMATION_TRACK_IDS) {
+ if (!Array.isArray(specs) || !specs.length) {
+ throw new Error('Atlas grid needs at least one animation track');
+ }
+ const seen = new Set();
+ for (const spec of specs) {
+ const id = spec?.id;
+ if (typeof id !== 'string' || !id) throw new Error('Atlas grid track spec needs an id');
+ if (id === ATLAS_IDLE_COLUMN) {
+ throw new Error(`Atlas grid cannot register a track named '${ATLAS_IDLE_COLUMN}' — the idle anchor owns that column`);
+ }
+ 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(', ')}`);
+ }
+ }
+
+ const ordered = [...specs].sort((a, b) => trackOrder.indexOf(a.id) - trackOrder.indexOf(b.id));
+ const columns = [ATLAS_IDLE_COLUMN];
+ const tracks = { [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 };
+ columns.push(...labels);
+ }
+ return { columns, tracks };
+}
+
+/**
+ * The walk-phase columns of a compiled grid: everything that is neither the
+ * idle anchor nor a legacy scanner placeholder. Derived from the ACTUAL column
+ * names rather than from `walkPhaseLabels(count)`, so a grid whose columns are
+ * positional (`frame-00…`) groups into one walk span just like the named
+ * 8-frame gait phases. The compiler no longer emits a scanner column (#2986),
+ * but imported/pre-#2986 grids still carry one, so it stays filtered here —
+ * otherwise their walk-frame count would come back one too high.
+ */
+const walkColumnsOf = (columns) =>
+ columns.filter((c) => c !== ATLAS_IDLE_COLUMN && c !== ATLAS_SCANNER_COLUMN);
+
+/**
+ * Walk frame count for a compiled atlas. Pointers written before #2970 have no
+ * `walkFrameCount`, so fall back to counting the walk columns themselves.
+ */
+export function resolveWalkFrameCount(geometry) {
+ if (Number.isInteger(geometry?.walkFrameCount)) return geometry.walkFrameCount;
+ if (!Array.isArray(geometry?.columns)) return null;
+ return walkColumnsOf(geometry.columns).length;
+}
+
+/**
+ * Validate a persisted `tracks` descriptor against the column list it claims to
+ * describe. Returns `{ tracks }` or `{ error }` — never throws, so the
+ * idempotency predicate can treat an undescribable grid as "not provably up to
+ * date" while `deriveTracks` turns the same reason into a loud failure.
+ *
+ * A descriptor that is *present* must tile the column list exactly: contiguous,
+ * non-overlapping, covering every column. A sidecar whose spans disagree with
+ * its own `columns` would silently point a consumer at the wrong pixels, which
+ * is the entire failure mode #2982 exists to prevent.
+ */
+function validateCompiledTracks(compiled, columns) {
+ const entries = Object.entries(compiled);
+ if (!entries.length) {
+ return { error: `Atlas track descriptor is empty but the grid has ${columns.length} columns` };
+ }
+ for (const [id, span] of entries) {
+ if (!Number.isInteger(span?.start) || !Number.isInteger(span?.count)) {
+ return { error: `Atlas track "${id}" needs integer start/count` };
+ }
+ if (span.count < 1) return { error: `Atlas track "${id}" spans ${span.count} columns` };
+ if (span.start < 0 || span.start + span.count > columns.length) {
+ return { error: `Atlas track "${id}" spans columns ${span.start}–${span.start + span.count - 1}, outside the ${columns.length}-column grid` };
+ }
+ }
+ const sorted = [...entries].sort((a, b) => a[1].start - b[1].start);
+ let cursor = 0;
+ const tracks = {};
+ for (const [id, span] of sorted) {
+ if (span.start !== cursor) {
+ return { error: `Atlas track "${id}" starts at column ${span.start} but the previous track ends at ${cursor} — the grid is not tiled by its tracks` };
+ }
+ cursor += span.count;
+ tracks[id] = { start: span.start, count: span.count };
+ }
+ if (cursor !== columns.length) {
+ return { error: `Atlas tracks describe ${cursor} of ${columns.length} columns` };
+ }
+ return { tracks };
+}
+
+/**
+ * Group a compiled grid into named tracks of contiguous column spans:
+ * `{ idle: { start: 0, count: 1 }, walk: { start: 1, count: 8 } }`.
+ *
+ * `compiledTracks` — the descriptor the compiler persisted into the manifest
+ * geometry — is authoritative when **present**, which is what lets a grid carry
+ * two tracks of differing length that no column-name heuristic could recover.
+ * When it is **absent** (`undefined`/`null` — every atlas compiled before
+ * #3016), fall back to the historical derivation: the `walkFrameCount` columns
+ * following the idle anchor are the walk track, and every other column becomes a
+ * track of its own named for the column, so a legacy grid's one-column `scanner`
+ * placeholder is still described honestly rather than folded into the walk span.
+ *
+ * Absent and present-but-empty are deliberately NOT the same: `{}` is a present
+ * descriptor that fails to describe the grid, and it is rejected rather than
+ * silently re-derived.
+ */
+export function deriveTracks(columns, walkFrameCount, compiledTracks = null) {
+ const described = describeTracks(columns, walkFrameCount, compiledTracks);
+ if (described.error) throw new Error(described.error);
+ return described.tracks;
+}
+
+/** Non-throwing `deriveTracks` — `{ tracks }` or `{ error }`. */
+export function describeTracks(columns, walkFrameCount, compiledTracks = null) {
+ if (!Array.isArray(columns) || !columns.length) {
+ return { error: 'Compiled atlas geometry has no column list' };
+ }
+ if (compiledTracks !== null && compiledTracks !== undefined) {
+ if (typeof compiledTracks !== 'object' || Array.isArray(compiledTracks)) {
+ return { error: 'Atlas track descriptor must be an object of column spans' };
+ }
+ return validateCompiledTracks(compiledTracks, columns);
+ }
+
+ const walkStart = columns[0] === ATLAS_IDLE_COLUMN ? 1 : 0;
+ const walkEnd = walkStart + (Number.isInteger(walkFrameCount) ? walkFrameCount : 0);
+ const tracks = {};
+ for (let index = 0; index < columns.length; index++) {
+ const column = columns[index];
+ const name = index >= walkStart && index < walkEnd ? WALK_TRACK : column;
+ const existing = tracks[name];
+ if (!existing) {
+ tracks[name] = { start: index, count: 1 };
+ continue;
+ }
+ if (existing.start + existing.count !== index) {
+ // A track split across non-adjacent columns can't be described as a
+ // span — refuse rather than emit a layout that lies about the grid.
+ return { error: `Atlas column "${column}" repeats non-contiguously — the grid cannot be described as tracks` };
+ }
+ existing.count += 1;
+ }
+ return { tracks };
+}
+
+/**
+ * True when a persisted pointer geometry describes exactly the grid this
+ * compile would emit — the pre-pixel idempotency test.
+ *
+ * #2986 found that comparing only the cell metrics let a grid-SHAPE change look
+ * up to date (dropping the trailing scanner column leaves every cell metric
+ * identical), so the column list joined the comparison. The **track set** joins
+ * it here for the same reason one level up: two different track sets can yield
+ * the same number of columns, and — for anything that labels its frames
+ * positionally — could in principle yield the same column *names* too. A grid
+ * that re-partitions the same columns into different tracks is a different grid
+ * and must recompile.
+ *
+ * The persisted side is read through `describeTracks`, not compared raw, so a
+ * pointer predating the `tracks` field (every atlas compiled before #3016) is
+ * described the legacy way and stays idempotent instead of re-running the whole
+ * pixel pipeline on every compile forever. A persisted grid that cannot be
+ * described at all is "not provably up to date" — recompile rather than trust it.
+ */
+export function compiledGridUpToDate(current, expected) {
+ if (!current || !expected) return false;
+ if (current.cellSize !== expected.cellSize) return false;
+ if (JSON.stringify(current.pivot) !== JSON.stringify(expected.pivot)) return false;
+ if (current.targetMaxHeight !== expected.targetMaxHeight) return false;
+ if (current.targetMaxWidth !== expected.targetMaxWidth) return false;
+ 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);
+}
+
+/**
+ * Resolve one track's frame count and playback fps from its per-direction rows,
+ * asserting that every facing agrees.
+ *
+ * **Uniformity is a within-track rule.** The atlas is a rectangular grid, so all
+ * 8 rows of a given track must share its column span — but two DIFFERENT tracks
+ * may legally differ in both length and speed, which is exactly what #3016 makes
+ * expressible. Nothing here reaches for another track's numbers, and the range
+ * 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 }`.
+ */
+export function resolveTrackUniformity(trackId, rows, {
+ trackRow = getAnimationTrack(trackId),
+ error = (message) => new Error(message),
+ defaultFps = trackRow.defaultFps,
+} = {}) {
+ if (!Array.isArray(rows) || !rows.length) {
+ throw error(`Track ${trackId} has no directions to compile`);
+ }
+ let frameCount = null;
+ let fps = null;
+ for (const row of rows) {
+ const { direction } = row;
+ if (frameCount === null) {
+ frameCount = row.frameCount;
+ if (!Number.isInteger(frameCount)
+ || frameCount < trackRow.minFrameCount || frameCount > trackRow.maxFrameCount) {
+ throw error(`Direction ${direction} has ${row.frameCount} frames — outside the supported ${trackRow.minFrameCount}–${trackRow.maxFrameCount} range`);
+ }
+ } else if (row.frameCount !== frameCount) {
+ throw error(`Direction ${direction} has ${row.frameCount} frames but the set uses ${frameCount} — reprocess all directions to the same frame count before compiling`);
+ }
+ if (Number.isInteger(row.declaredFrameCount) && row.declaredFrameCount !== row.frameCount) {
+ throw error(`Direction ${direction} manifest declares ${row.declaredFrameCount} frames but carries ${row.frameCount}`);
+ }
+ // Playback fps likewise must agree across a track's directions so the whole
+ // track animates at one speed. Range-checked; a manifest with no frameRate
+ // falls back to the legacy default so older sets still compile.
+ const rowFps = Number.isFinite(row.fps) ? row.fps : defaultFps;
+ if (rowFps < trackRow.minFps || rowFps > trackRow.maxFps) {
+ throw error(`Direction ${direction} playback fps ${rowFps} is outside the supported ${trackRow.minFps}–${trackRow.maxFps} range`);
+ }
+ if (fps === null) {
+ fps = rowFps;
+ } else if (rowFps !== fps) {
+ throw error(`Direction ${direction} plays at ${rowFps} fps but the set uses ${fps} — reprocess all directions to the same speed before compiling`);
+ }
+ }
+ return { id: trackId, frameCount, fps, labels: trackColumnLabels(trackId, frameCount) };
+}
diff --git a/server/services/sprites/atlasGrid.test.js b/server/services/sprites/atlasGrid.test.js
new file mode 100644
index 0000000000..aa8fff9947
--- /dev/null
+++ b/server/services/sprites/atlasGrid.test.js
@@ -0,0 +1,319 @@
+/**
+ * The atlas grid (#3016) — column spans, per-track uniformity, and the
+ * 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.
+ * 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
+ * stay green, which is exactly the regression it exists to prevent. Shipping a
+ * real second track is #3018's job.
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ trackColumnLabels, buildAtlasGrid, deriveTracks, describeTracks,
+ resolveWalkFrameCount, compiledGridUpToDate, resolveTrackUniformity,
+} from './atlasGrid.js';
+import { walkPhaseLabels } from './walkBounds.js';
+import { getAnimationTrack } 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
+// case #3015's per-track bounds and #3016's per-track uniformity exist for.
+const SCANNER_ROW = Object.freeze({
+ id: 'scanner',
+ label: 'Scanner sweep',
+ directional: true,
+ minFrameCount: 2,
+ maxFrameCount: 8,
+ defaultFrameCount: 4,
+ minFps: 2,
+ maxFps: 12,
+ defaultFps: 6,
+ contractFrameCountField: 'scannerFrameCount',
+ contractFpsField: null,
+});
+const TWO_TRACK_ORDER = ['walk', 'scanner'];
+const DIRECTIONS = ['S', 'SE', 'E', 'NE', 'N', 'NW', 'W', 'SW'];
+
+const rowsFor = (frameCount, fps, overrides = {}) =>
+ DIRECTIONS.map((direction) => ({
+ direction, frameCount, declaredFrameCount: frameCount, fps, ...overrides,
+ }));
+
+describe('trackColumnLabels', () => {
+ it('keeps the walk track on its historical labels', () => {
+ // Named 2-beat gait phases at 8 frames, positional otherwise — so existing
+ // and imported atlases round-trip byte-identically.
+ expect(trackColumnLabels('walk', 8)).toEqual(walkPhaseLabels(8));
+ expect(trackColumnLabels('walk', 12)).toEqual(walkPhaseLabels(12));
+ expect(trackColumnLabels('walk', 12)[0]).toBe('frame-00');
+ });
+
+ it('namespaces every other track so two tracks cannot collide on a column name', () => {
+ expect(trackColumnLabels('scanner', 4)).toEqual(['scanner-00', 'scanner-01', 'scanner-02', 'scanner-03']);
+ // The failure this prevents: positional labels are per-track ordinals, so
+ // two 4-frame tracks would otherwise both emit `frame-00…frame-03` and the
+ // flat column list — which consumers resolve BY NAME — would carry
+ // duplicates no reader could disambiguate.
+ const a = trackColumnLabels('scanner', 4);
+ const b = trackColumnLabels('idle-loop', 4);
+ expect(a.filter((label) => b.includes(label))).toEqual([]);
+ });
+
+ it('refuses a non-positive or non-integer frame count', () => {
+ expect(() => trackColumnLabels('scanner', 0)).toThrow(/positive integer frame count/);
+ expect(() => trackColumnLabels('scanner', 2.5)).toThrow(/positive integer frame count/);
+ });
+});
+
+describe('buildAtlasGrid', () => {
+ it('emits idle first, then one contiguous span per track', () => {
+ const grid = buildAtlasGrid([{ id: 'walk', frameCount: 8 }]);
+ expect(grid.columns).toEqual(['idle', ...walkPhaseLabels(8)]);
+ expect(grid.tracks).toEqual({ idle: { start: 0, count: 1 }, walk: { start: 1, count: 8 } });
+ });
+
+ it('packs two tracks of DIFFERENT lengths into one grid', () => {
+ // 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,
+ );
+ expect(grid.columns).toEqual([
+ 'idle', ...walkPhaseLabels(12),
+ 'scanner-00', 'scanner-01', 'scanner-02', 'scanner-03',
+ ]);
+ expect(grid.tracks).toEqual({
+ idle: { start: 0, count: 1 },
+ walk: { start: 1, count: 12 },
+ scanner: { start: 13, count: 4 },
+ });
+ // columns and tracks stay mutually consistent — the spans tile the grid,
+ // so the emitted PNG width (cellSize × columns.length) matches what the
+ // sidecar tells a consumer to sample.
+ const spanned = Object.values(grid.tracks).reduce((n, s) => n + s.count, 0);
+ expect(spanned).toBe(grid.columns.length);
+ expect(grid.columns.length).toBe(17);
+ });
+
+ it('sorts specs into registration order rather than call order', () => {
+ const asGiven = buildAtlasGrid(
+ [{ id: 'scanner', frameCount: 4 }, { id: 'walk', frameCount: 6 }],
+ TWO_TRACK_ORDER,
+ );
+ const reversed = buildAtlasGrid(
+ [{ id: 'walk', frameCount: 6 }, { id: 'scanner', frameCount: 4 }],
+ TWO_TRACK_ORDER,
+ );
+ expect(asGiven).toEqual(reversed);
+ expect(asGiven.tracks.walk.start).toBeLessThan(asGiven.tracks.scanner.start);
+ });
+
+ it('refuses a spec set it cannot describe', () => {
+ expect(() => buildAtlasGrid([])).toThrow(/at least one animation track/);
+ 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']))
+ .toThrow(/the idle anchor owns that column/);
+ 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/);
+ });
+});
+
+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,
+ );
+ expect(deriveTracks(grid.columns, 6, grid.tracks)).toEqual(grid.tracks);
+ // …and the descriptor is genuinely load-bearing: without it the legacy
+ // derivation cannot recover a second track's span, it can only hand back
+ // four one-column singletons.
+ const legacy = deriveTracks(grid.columns, 6, null);
+ expect(legacy.scanner).toBeUndefined();
+ expect(legacy['scanner-00']).toEqual({ start: 7, count: 1 });
+ });
+
+ it('treats an absent descriptor as legacy and a present-but-empty one as invalid', () => {
+ // Absent ≠ present-but-empty: `{}` is a descriptor that fails to describe
+ // the grid and must be refused, never silently re-derived.
+ expect(deriveTracks(['idle', 'a', 'b'], 2, null)).toEqual({
+ idle: { start: 0, count: 1 }, walk: { start: 1, count: 2 },
+ });
+ expect(deriveTracks(['idle', 'a', 'b'], 2, undefined)).toEqual({
+ idle: { start: 0, count: 1 }, walk: { start: 1, count: 2 },
+ });
+ expect(() => deriveTracks(['idle', 'a', 'b'], 2, {})).toThrow(/descriptor is empty/);
+ });
+
+ it('refuses a descriptor that does not tile its own column list', () => {
+ const columns = ['idle', 'a', 'b', 'c'];
+ expect(() => deriveTracks(columns, 3, { idle: { start: 0, count: 1 }, walk: { start: 1, count: 2 } }))
+ .toThrow(/describe 3 of 4 columns/);
+ // A gap between spans.
+ expect(() => deriveTracks(columns, 3, { idle: { start: 0, count: 1 }, walk: { start: 2, count: 2 } }))
+ .toThrow(/the grid is not tiled by its tracks/);
+ // Overlapping spans.
+ expect(() => deriveTracks(columns, 3, { idle: { start: 0, count: 2 }, walk: { start: 1, count: 3 } }))
+ .toThrow(/the grid is not tiled by its tracks/);
+ // Running off the end.
+ expect(() => deriveTracks(columns, 3, { idle: { start: 0, count: 1 }, walk: { start: 1, count: 9 } }))
+ .toThrow(/outside the 4-column grid/);
+ expect(() => deriveTracks(columns, 3, { idle: { start: 0, count: 1 }, walk: { start: 1, count: 'three' } }))
+ .toThrow(/needs integer start\/count/);
+ expect(() => deriveTracks(columns, 3, [{ start: 0, count: 4 }]))
+ .toThrow(/must be an object of column spans/);
+ });
+
+ 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/);
+ });
+});
+
+describe('compiledGridUpToDate', () => {
+ const expected = {
+ cellSize: 96,
+ pivot: [48, 88],
+ targetMaxHeight: 74,
+ targetMaxWidth: 86,
+ ...buildAtlasGrid([{ id: 'walk', frameCount: 8 }]),
+ };
+ const persisted = (overrides = {}) => ({
+ cellSize: 96,
+ pivot: [48, 88],
+ targetMaxHeight: 74,
+ targetMaxWidth: 86,
+ columns: [...expected.columns],
+ tracks: { ...expected.tracks },
+ walkFrameCount: 8,
+ ...overrides,
+ });
+
+ it('matches an identical grid, and a legacy pointer that predates the tracks field', () => {
+ expect(compiledGridUpToDate(persisted(), expected)).toBe(true);
+ // Every atlas compiled before #3016 has no `tracks`. It must still read as
+ // up to date, or upgrading an install condemns each existing atlas to
+ // re-run the whole pixel pipeline on every compile, forever.
+ expect(compiledGridUpToDate(persisted({ tracks: undefined }), expected)).toBe(true);
+ // Pre-#2970 pointers additionally carry no walkFrameCount; the walk span is
+ // recovered by counting the non-anchor columns.
+ expect(compiledGridUpToDate(persisted({ tracks: undefined, walkFrameCount: undefined }), expected)).toBe(true);
+ });
+
+ it('catches a TRACK-SET change even when the column list is identical', () => {
+ // The regression this exists for. #2986 showed a grid-shape change can leave
+ // every cell metric identical; one level up, re-partitioning the SAME
+ // columns into a different set of tracks leaves even the column count and
+ // the column names identical. That is a different grid and must recompile.
+ const repartitioned = persisted({
+ tracks: {
+ idle: { start: 0, count: 1 },
+ walk: { start: 1, count: 4 },
+ scanner: { start: 5, count: 4 },
+ },
+ });
+ expect(repartitioned.columns).toEqual(expected.columns);
+ expect(Object.values(repartitioned.tracks).reduce((n, s) => n + s.count, 0))
+ .toBe(Object.values(expected.tracks).reduce((n, s) => n + s.count, 0));
+ expect(compiledGridUpToDate(repartitioned, expected)).toBe(false);
+ });
+
+ it('catches a column-list change and a cell-metric change', () => {
+ // A pre-#2986 grid still carrying the trailing scanner placeholder.
+ expect(compiledGridUpToDate(
+ persisted({ columns: [...expected.columns, 'scanner'], tracks: undefined }),
+ expected,
+ )).toBe(false);
+ expect(compiledGridUpToDate(persisted({ cellSize: 64 }), expected)).toBe(false);
+ expect(compiledGridUpToDate(persisted({ pivot: [48, 90] }), expected)).toBe(false);
+ expect(compiledGridUpToDate(persisted({ targetMaxHeight: 70 }), expected)).toBe(false);
+ expect(compiledGridUpToDate(persisted({ targetMaxWidth: 80 }), expected)).toBe(false);
+ });
+
+ it('treats an undescribable or absent persisted grid as not up to date', () => {
+ expect(compiledGridUpToDate(null, expected)).toBe(false);
+ expect(compiledGridUpToDate(persisted({ tracks: {} }), expected)).toBe(false);
+ });
+});
+
+describe('resolveTrackUniformity', () => {
+ it('resolves a track from its per-direction rows', () => {
+ expect(resolveTrackUniformity('walk', rowsFor(12, 10))).toEqual({
+ id: 'walk', frameCount: 12, fps: 10, labels: walkPhaseLabels(12),
+ });
+ });
+
+ it('enforces uniformity WITHIN a track', () => {
+ const ragged = rowsFor(12, 10);
+ ragged[3] = { ...ragged[3], frameCount: 10, declaredFrameCount: 10 };
+ expect(() => resolveTrackUniformity('walk', ragged))
+ .toThrow(/Direction NE has 10 frames but the set uses 12/);
+
+ const uneven = rowsFor(12, 10);
+ uneven[5] = { ...uneven[5], fps: 16 };
+ expect(() => resolveTrackUniformity('walk', uneven))
+ .toThrow(/Direction NW plays at 16 fps but the set uses 10/);
+ });
+
+ it('lets two DIFFERENT tracks disagree on frame count and speed', () => {
+ // The central semantic change of #3016: uniformity is a within-track rule,
+ // 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 });
+ expect(walk.frameCount).toBe(12);
+ expect(scanner.frameCount).toBe(4);
+ expect(scanner.fps).toBe(6);
+ expect(scanner.labels).toEqual(['scanner-00', 'scanner-01', 'scanner-02', 'scanner-03']);
+ // 4 frames would be rejected outright by the walk row it used to share.
+ expect(getAnimationTrack('walk').minFrameCount).toBeGreaterThan(scanner.frameCount);
+ 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 }))
+ .toThrow(/outside the supported 2–8 range/);
+ expect(() => resolveTrackUniformity('scanner', rowsFor(4, 20), { trackRow: SCANNER_ROW }))
+ .toThrow(/fps 20 is outside the supported 2–12 range/);
+ });
+
+ it('catches a manifest whose declared count contradicts its frames', () => {
+ const rows = rowsFor(12, 10);
+ rows[0] = { ...rows[0], declaredFrameCount: 8 };
+ expect(() => resolveTrackUniformity('walk', rows))
+ .toThrow(/Direction S manifest declares 8 frames but carries 12/);
+ });
+
+ 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)
+ .toBe(SCANNER_ROW.defaultFps);
+ });
+
+ it('routes failures through the caller-supplied error factory', () => {
+ // atlas.js passes its 422-shaped compileError; the leaf stays free of the
+ // error-handler import.
+ const tagged = (message) => Object.assign(new Error(message), { status: 422, code: 'ATLAS_COMPILE_INVALID' });
+ expect(() => resolveTrackUniformity('walk', [], { error: tagged }))
+ .toThrow(expect.objectContaining({ code: 'ATLAS_COMPILE_INVALID' }));
+ });
+});
+
+describe('resolveWalkFrameCount', () => {
+ it('prefers the declared count and falls back to counting non-anchor columns', () => {
+ expect(resolveWalkFrameCount({ walkFrameCount: 12 })).toBe(12);
+ expect(resolveWalkFrameCount({ columns: ['idle', 'a', 'b'] })).toBe(2);
+ expect(resolveWalkFrameCount({ columns: ['idle', 'a', 'b', 'scanner'] })).toBe(2);
+ expect(resolveWalkFrameCount({})).toBeNull();
+ });
+});
diff --git a/server/services/sprites/atlasLayout.js b/server/services/sprites/atlasLayout.js
index d25add01ab..09b730b7f2 100644
--- a/server/services/sprites/atlasLayout.js
+++ b/server/services/sprites/atlasLayout.js
@@ -27,22 +27,26 @@
* it rides along as `previewFps`, explicitly labeled as authoring metadata the
* consumer must ignore.
*
- * Pure and dependency-free (no image graph, no state): publish.js builds the
- * payload before taking any write lock, and the shape is unit-testable on its
- * own.
+ * Pure and free of the image graph (no sharp, no fs, no state): publish.js
+ * builds the payload before taking any write lock, and the shape is
+ * unit-testable on its own.
+ *
+ * The span math itself lives one level down in `atlasGrid.js` (#3016), because
+ * the compiler that WRITES the grid imports sharp and this module must not —
+ * so the single definition of a column span has to sit below both. Since #3016
+ * the two namespaces ARE unified: a track's span is named for its registry id
+ * (#3015), the compiler persists that descriptor into the manifest geometry, and
+ * `deriveTracks` prefers it. Only a *legacy* grid (compiled before #3016, or
+ * imported) still falls back to minting a name from a column label, which is
+ * what keeps a pre-#2986 `scanner` placeholder describable.
*/
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) rather than restated as a local literal, so the descriptor and
-// `animationTargets.walk` agree on how the walk span is spelled. Note the two
-// namespaces are NOT otherwise unified: `deriveTracks` still mints track names
-// straight from column labels (`idle`, `scanner`), which are not registry ids,
-// and `walkColumnsOf` still defines walk as "everything that isn't idle or
-// scanner". Reconciling those is the second track's job, not this import's.
-// animationTracks imports nothing, so this keeps the module dependency-free.
-import { WALK_TRACK } from './animationTracks.js';
+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.
@@ -65,60 +69,6 @@ export function layoutSidecarPath(atlasDestPath) {
return `${stem}.layout.json`;
}
-/**
- * The walk-phase columns of a compiled grid: everything that is neither the
- * idle anchor nor a legacy scanner placeholder. Derived from the ACTUAL column
- * names rather than from `walkPhaseLabels(count)`, so a grid whose columns are
- * positional (`frame-00…`) groups into one walk span just like the named
- * 8-frame gait phases. The compiler no longer emits a scanner column (#2986),
- * but imported/pre-#2986 grids still carry one, so it stays filtered here —
- * otherwise their walk-frame count would come back one too high.
- */
-const walkColumnsOf = (columns) =>
- columns.filter((c) => c !== ATLAS_IDLE_COLUMN && c !== ATLAS_SCANNER_COLUMN);
-
-/**
- * Walk frame count for a compiled atlas. Pointers written before #2970 have no
- * `walkFrameCount`, so fall back to counting the walk columns themselves.
- */
-export function resolveWalkFrameCount(geometry) {
- if (Number.isInteger(geometry?.walkFrameCount)) return geometry.walkFrameCount;
- if (!Array.isArray(geometry?.columns)) return null;
- return walkColumnsOf(geometry.columns).length;
-}
-
-/**
- * Group the flat column list into named tracks of contiguous column spans:
- * `{ idle: { start: 0, count: 1 }, walk: { start: 1, count: 8 } }`. The walk
- * track is the `walkFrameCount` columns following the idle anchor — positional,
- * per the grid contract, so it doesn't care whether those columns carry named
- * gait phases or positional `frame-NN` labels. Every other column becomes a
- * track of its own named for the column, so a future four-frame scanner action
- * lands as `scanner: { start, count: 4 }` with no shape change on either side
- * of the boundary — and so a legacy grid's one-column `scanner` placeholder is
- * still described honestly rather than folded into the walk span.
- */
-export function deriveTracks(columns, walkFrameCount) {
- const walkStart = columns[0] === ATLAS_IDLE_COLUMN ? 1 : 0;
- const walkEnd = walkStart + (Number.isInteger(walkFrameCount) ? walkFrameCount : 0);
- const tracks = {};
- columns.forEach((column, index) => {
- const name = index >= walkStart && index < walkEnd ? WALK_TRACK : column;
- const existing = tracks[name];
- if (!existing) {
- tracks[name] = { start: index, count: 1 };
- return;
- }
- if (existing.start + existing.count !== index) {
- // A track split across non-adjacent columns can't be described as a
- // span — refuse rather than emit a layout that lies about the grid.
- throw new Error(`Atlas column "${column}" repeats non-contiguously — the grid cannot be described as tracks`);
- }
- existing.count += 1;
- });
- return tracks;
-}
-
/**
* Build the layout sidecar payload for a compiled atlas.
*
@@ -149,7 +99,10 @@ export function buildAtlasLayout({
rowOrder: Array.isArray(geometry.directionOrder) ? [...geometry.directionOrder] : null,
columns: [...columns],
columnCount: columns.length,
- tracks: deriveTracks(columns, walkFrameCount),
+ // Prefer the descriptor the compiler persisted (#3016) — the only thing
+ // that can describe two tracks of differing length — and fall back to the
+ // legacy column-name derivation for a grid compiled before it existed.
+ tracks: deriveTracks(columns, walkFrameCount, geometry.tracks ?? null),
walkFrameCount,
previewFps: Number.isFinite(geometry.walkFps) ? geometry.walkFps : null,
previewFpsNote: PREVIEW_FPS_NOTE,
diff --git a/server/services/sprites/atlasLayout.test.js b/server/services/sprites/atlasLayout.test.js
index c5739ae134..a658196340 100644
--- a/server/services/sprites/atlasLayout.test.js
+++ b/server/services/sprites/atlasLayout.test.js
@@ -9,6 +9,7 @@ import {
runtimeContractMismatch, ATLAS_LAYOUT_SCHEMA_VERSION,
} from './atlasLayout.js';
import { walkPhaseLabels } from './walkBounds.js';
+import { buildAtlasGrid } from './atlasGrid.js';
const DIRECTIONS = ['S', 'SE', 'E', 'NE', 'N', 'NW', 'W', 'SW'];
// The grid the compiler emits today: idle + N walk phases (#2986 dropped the
@@ -133,6 +134,49 @@ describe('buildAtlasLayout', () => {
expect(layout.tracks.scanner).toEqual({ start: 9, count: 1 });
});
+ it('describes a two-track grid whose tracks differ in length (#3016)', () => {
+ // Built through the compiler's own span builder, against a SYNTHETIC
+ // registration order — only `walk` is registered today, so shipping a real
+ // second track is #3018's job (see atlasGrid.test.js for why the synthetic
+ // fixture is the point rather than a shortcut).
+ const grid = buildAtlasGrid(
+ [{ id: 'walk', frameCount: 12 }, { id: 'scanner', frameCount: 4 }],
+ ['walk', 'scanner'],
+ );
+ const layout = buildAtlasLayout({
+ characterId: 'example-character',
+ geometry: geometryFor(12, { columns: grid.columns, tracks: grid.tracks }),
+ atlasSha256: 'abc123',
+ version: 7,
+ atlasDestPath: 'assets/sprites/hero/hero-atlas.png',
+ });
+ expect(layout.tracks).toEqual({
+ idle: { start: 0, count: 1 },
+ walk: { start: 1, count: 12 },
+ scanner: { start: 13, count: 4 },
+ });
+ // columns, tracks and the atlas width stay mutually consistent: the spans
+ // tile the column list exactly, so a consumer sampling by span lands on the
+ // pixels the PNG's width accounts for.
+ expect(layout.columnCount).toBe(17);
+ expect(layout.columns).toHaveLength(layout.columnCount);
+ expect(Object.values(layout.tracks).reduce((n, s) => n + s.count, 0)).toBe(layout.columnCount);
+ // The walk span is still recoverable by name for a consumer that only knows
+ // about walk — a second track is additive, not a re-read.
+ expect(layout.walkFrameCount).toBe(12);
+ });
+
+ it('refuses a persisted descriptor that contradicts its own column list', () => {
+ // A sidecar whose spans disagree with its columns would silently point a
+ // consumer at the wrong pixels — the exact failure #2982 exists to prevent.
+ expect(() => buildAtlasLayout({
+ characterId: 'example-character',
+ geometry: geometryFor(8, { tracks: { idle: { start: 0, count: 1 }, walk: { start: 1, count: 3 } } }),
+ atlasSha256: 'abc123',
+ atlasDestPath: 'assets/sprites/hero/hero-atlas.png',
+ })).toThrow(/describe 4 of 9 columns/);
+ });
+
it('refuses geometry with no column list', () => {
expect(() => buildAtlasLayout({ characterId: 'x', geometry: {}, atlasDestPath: 'a.png' }))
.toThrow(/no column list/);