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-2982]): guard the sprite atlas export contract and ship a layout sidecar

[._.]/ Adam Eivy4c7189ba0083
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index aa01a10f10..07cea615c0 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -24,6 +24,7 @@
## Sprite Manager
+- **[issue-2982] Publishing an atlas your game can't read now stops instead of silently breaking it** — the atlas PNG used to be the *entire* export: nothing described how many walk frames were in it, so a game with an 8-frame walk baked in as a constant would happily accept a 12-frame publish and then draw the wrong frames from the wrong columns forever, with no crash and no log. Two things fix that. A publish target can now declare the grid it was built against (`runtimeContract`: walk frame count, cell size, column count), and a publish whose compiled atlas disagrees is refused with a message naming both numbers — "Atlas has 14 columns (12 walk frames) but Example App expects 10 (8 walk frames)" — plus the two ways to resolve it. And every publish now writes a small `…​.layout.json` file beside the atlas describing the grid PortOS actually produced: cell size, ordered column names, per-track column spans (so a future multi-frame scanner or ambient action is additive, not a rewrite), row order, and the atlas checksum — so the game can resolve columns by name and verify what it loaded instead of trusting a constant. Targets with no declared contract publish exactly as before. Also documented: playback **fps in PortOS is preview-only**. It ships in the sidecar labeled as authoring metadata, because the consuming game drives its walk from movement distance and has no frame-rate concept at all — a 6 fps preview and a 24 fps preview export byte-identical atlases. See `docs/features/sprite-export-contract.md`.
- **[issue-2978] Saving a loop trim now works on imported characters** — for a character whose walk cycles came in through the source-pipeline import, the Loop Trimmer would load, scrub, and play the animation perfectly, then fail on **Save trim** with "Packaged run manifest is missing or inconsistent" — after you'd already picked your frames, and with nothing saved. The imported artwork was never damaged; PortOS was simply looking for the packaged manifest under the wrong folder and giving up. Trims now save on imported characters, keep the real gait-phase labels (left-contact, left-passing, …) for each kept frame, and record the correct source strip. A run whose manifest went missing entirely now falls back to the strip's own geometry and still trims, while a manifest that's genuinely corrupt still refuses loudly instead of quietly guessing. The same lookup fixed approving an imported walk direction, which would have failed the same way.
- **Steer a directional-anchor re-roll with a correction note** — when a directional anchor comes out wrong (say the north-east pose grew a pocket on the arm that has none in every other view), re-rolling it with the same inputs tended to just reproduce the same mistake. Each unlocked anchor tile now has a small **Correction (optional)** box: type what to fix ("no pocket on the right sleeve") and hit **Regenerate**, and the note is appended to that pose's prompt as an explicit override so the new render actually diverges. The button reads **Generate** on the first render and **Regenerate** once candidates exist, the correction is per-direction (so eight different fixes don't collide), and it rides into the candidate's saved prompt so the image preview shows exactly what was asked for. Main-reference iteration is unchanged — it already has its own design-prompt box.
- **[issue-2964] The same correction note now steers a re-roll from the asset card too** — the correction box used to live only on the Reference Set's anchor grid, so re-rolling a directional-anchor candidate from its card in the Assets library ignored any fix you'd typed. Each anchor candidate card now carries the same correction affordance: click its note icon to type ("no pocket on the right sleeve") and hit **Regenerate**, and that guidance is appended to the pose's prompt exactly as it is from the grid. The two surfaces share one correction per direction, so a note you type in either place shows up in the other, and both re-rolls send the identical instruction.
diff --git a/docs/README.md b/docs/README.md
index 7db9d31621..b5e5882659 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -31,7 +31,7 @@ Identity & self: [digital-twin](./features/digital-twin.md) · [identity-system]
Knowledge: [brain-system](./features/brain-system.md) · [messages-security](./features/messages-security.md)
-Create: [writers-room](./features/writers-room.md) · [cybercity-v2](./features/cybercity-v2.md)
+Create: [writers-room](./features/writers-room.md) · [cybercity-v2](./features/cybercity-v2.md) · [sprite-export-contract](./features/sprite-export-contract.md)
Comms & voice: [openclaw-operator-chat](./features/openclaw-operator-chat.md) ([pre-build audit](./research/2026-03-31-openclaw-operator-chat-audit.md)) · [voice](./features/voice.md)
diff --git a/docs/features/sprite-export-contract.md b/docs/features/sprite-export-contract.md
new file mode 100644
index 0000000000..5f6e245f14
--- /dev/null
+++ b/docs/features/sprite-export-contract.md
@@ -0,0 +1,93 @@
+# Sprite Export Contract
+
+What actually crosses the boundary when PortOS publishes a compiled sprite atlas into a managed app's repository — and, just as importantly, what does not.
+
+Publishing is the only sprite path that writes outside `data/`. Everything else (walk runs, trims, the compile manifest, previews) stays inside PortOS. So the contract below is the *entire* surface a consuming app can depend on.
+
+## The atlas grid
+
+The compiler (`server/services/sprites/atlas.js`) produces one PNG: a fixed-cell grid of `idle + N walk phases + scanner` columns × 8 direction rows.
+
+| Property | Value |
+|---|---|
+| 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`: S, SE, E, NE, N, NW, W, SW |
+| Columns | `idle` at 0, the N walk phases from 1, `scanner` last |
+| N (walk frame count) | authorable, 6–16 (`walkBounds.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.**
+
+## What crosses the publish boundary
+
+Exactly two files land in the app repo:
+
+1. **The atlas PNG**, atomically replaced at `publishBinding.atlasDestPath`. Refused when the destination diverged from the previous publish, or when it holds bytes PortOS never published and the overwrite wasn't acknowledged.
+2. **A `<atlas-stem>.layout.json` sidecar** beside it, describing the grid that PNG actually is.
+
+Optionally, a **code binding** verifies (or occurrence-count-guarded rewrites) a resource-path string in one game source file. Engine sidecars (e.g. Godot's `.png.import`) are the game repo's concern and are never touched.
+
+Nothing else crosses. The compile manifest, the run provenance, the trims, and the record itself never leave `data/`.
+
+### The layout sidecar
+
+```json
+{
+ "schemaVersion": 1,
+ "kind": "portos-sprite-atlas-layout",
+ "characterId": "example-character",
+ "atlasFile": "example-atlas.png",
+ "atlasVersion": 4,
+ "sourceAtlasSha256": "…",
+ "cellSize": 96,
+ "rows": 8,
+ "rowOrder": ["S", "SE", "E", "NE", "N", "NW", "W", "SW"],
+ "columns": ["idle", "left-contact", "…", "right-up", "scanner"],
+ "columnCount": 10,
+ "tracks": {
+ "idle": { "start": 0, "count": 1 },
+ "walk": { "start": 1, "count": 8 },
+ "scanner": { "start": 9, "count": 1 }
+ },
+ "walkFrameCount": 8,
+ "previewFps": 12,
+ "previewFpsNote": "Authoring metadata only — …"
+}
+```
+
+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. `columns` is the flat list for anything that wants raw names.
+- **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 destination guards; an atlas whose sidecar was deleted gets it back on the next publish.
+
+## Playback speed belongs to the consuming app
+
+PortOS's walk **fps is preview-only.** It is real provenance for the trim GIFs and the in-PortOS preview, and it rides along in the sidecar as `previewFps` — explicitly labeled authoring metadata. It is not an instruction.
+
+The reference consumer advances its walk cycle **per unit of distance travelled**, not per unit of time: frame index derives from movement distance over a cycle distance, scaled by move speed and terrain. Its effective playback rate is therefore continuous and emergent (roughly `speed ÷ distance-per-frame`), never a number PortOS chose. A 6 fps preview and a 24 fps preview produce **byte-identical exports**.
+
+If your app *is* time-driven, pick its own frame rate. Do not read `previewFps` as one.
+
+## Frame count is a coordinated cross-repo change
+
+Column layout is the one thing an app genuinely has to agree with PortOS about. Changing `N` shifts every column after `idle` — a game that reads walk columns 1–8 out of a 14-column atlas renders the wrong phases *and* draws a walk frame where the scanner belongs. No crash, no log.
+
+Two mechanisms guard that:
+
+- **`publishBinding.runtimeContract`** (optional): `{ walkFrameCount, cellSize?, columnCount? }` — the grid the app was built against. Set it via `PUT /api/sprites/:id/publish-binding`. Publishing an atlas whose compiled geometry disagrees fails with a **409** naming both the actual and expected numbers and both resolutions (change the app's constant, or reprocess the walk set). A binding with no contract publishes unchecked, exactly as before the field existed.
+- **The sidecar**, so an app that reads it can fail loudly on its own terms instead of relying on PortOS to have been asked.
+
+`runtimeContract` follows absent-vs-null semantics: a saved binding that omits the key inherits the stored contract (the publish form doesn't edit it), while an explicit `null` clears it.
+
+**A frame-count change is therefore a two-repo change.** Reprocess the walk set to the new count, update the app's frame-count constant *and* the distance/timing math derived from it, and update the contract — in whichever order, but neither half ships alone.
+
+## Related code
+
+| Path | Role |
+|---|---|
+| `server/services/sprites/atlas.js` | Compiles the atlas; owns `atlasColumns()` and the geometry block |
+| `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/lib/validation.js b/server/lib/validation.js
index 56761dd35c..8990719e01 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -996,6 +996,19 @@ const spriteRepoRelativePath = z.string().min(1).max(1024)
message: 'must be a repo-relative path with no traversal',
});
+// The grid the consuming app was built against (#2982). Optional: an absent
+// contract publishes unchecked, exactly as bindings did before it existed.
+// `walkFrameCount` is required once a contract is declared — it is the value
+// the app bakes in as a constant and the one a mismatched publish silently
+// breaks. Playback speed is deliberately absent: distance-driven consumers
+// have no animation-fps concept, so PortOS's fps is preview-only and never
+// part of the contract.
+export const spriteRuntimeContractSchema = z.object({
+ walkFrameCount: z.number().int().min(WALK_MIN_FRAME_COUNT).max(WALK_MAX_FRAME_COUNT),
+ cellSize: z.number().int().min(16).max(1024).nullable().optional(),
+ columnCount: z.number().int().min(1).max(256).nullable().optional(),
+});
+
export const spritePublishBindingSchema = z.object({
appId: z.string().min(1).max(200),
atlasDestPath: spriteRepoRelativePath.refine((p) => p.toLowerCase().endsWith('.png'), {
@@ -1006,6 +1019,10 @@ export const spritePublishBindingSchema = z.object({
resourcePath: z.string().min(1).max(1024),
requiredOccurrenceCount: z.number().int().min(1).max(1000).optional(),
}).nullable().optional(),
+ // Absent (key omitted) inherits the stored contract; explicit null clears it
+ // — see setPublishBinding. Keep the two distinguishable: `.optional()` must
+ // stay separate from `.nullable()` here.
+ runtimeContract: spriteRuntimeContractSchema.nullable().optional(),
}).nullable();
// acknowledgeOverwrite: explicit consent to replace a destination atlas
diff --git a/server/services/sprites/atlasLayout.js b/server/services/sprites/atlasLayout.js
new file mode 100644
index 0000000000..372d100ae0
--- /dev/null
+++ b/server/services/sprites/atlasLayout.js
@@ -0,0 +1,183 @@
+/**
+ * Sprites — the published atlas layout sidecar and the runtime-contract check
+ * (issue #2982).
+ *
+ * The atlas PNG is the entire export: the compile manifest never leaves
+ * `data/`, so a consuming app has had to hardcode the grid (idle at column 0,
+ * walk phases from column 1, the frame count baked in as a constant). That
+ * held by construction while every walk was 8 frames; since the count became
+ * authorable (#2970) a 12-frame publish silently shifts every column the app
+ * reads — no crash, no log, just the wrong pixels.
+ *
+ * Two pieces close that gap:
+ *
+ * - `buildAtlasLayout` produces the `<atlas-stem>.layout.json` sidecar written
+ * beside the published PNG, so the app can resolve columns BY NAME and
+ * verify the atlas it loaded is the one the layout describes
+ * (`sourceAtlasSha256`). Alongside the flat `columns` list it carries a
+ * per-track column span (`tracks`), so a future multi-frame scanner action or
+ * an ambient loop is an additive track rather than a v2 rewrite.
+ * - `runtimeContractMismatch` compares compiled geometry against the optional
+ * `publishBinding.runtimeContract` the app declared, so a publish the app
+ * cannot consume is refused with both numbers named instead of shipping.
+ *
+ * Playback speed is deliberately NOT part of the contract. Distance-driven
+ * consumers (the reference case advances the walk per unit of movement) have
+ * no animation-fps concept at all, so PortOS's authoring fps is preview-only:
+ * it rides along as `previewFps`, explicitly labeled as authoring metadata the
+ * consumer must ignore.
+ *
+ * Pure and dependency-free (no fs, no sharp): publish.js builds the payload
+ * before taking any write lock, and the shape is unit-testable on its own.
+ */
+
+// 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;
+export const ATLAS_LAYOUT_KIND = 'portos-sprite-atlas-layout';
+
+// Stated inside the file the app reads, so the "do not animate from this"
+// rule travels with the value instead of living only in our docs.
+export const PREVIEW_FPS_NOTE = 'Authoring metadata only — the speed PortOS previews this walk at. '
+ + 'The consuming app determines real playback (e.g. from movement distance); do not use this as a runtime frame rate.';
+
+const IDLE_COLUMN = 'idle';
+const SCANNER_COLUMN = 'scanner';
+const WALK_TRACK = 'walk';
+
+/**
+ * Sidecar path for a published atlas: `…/hero-atlas.png` →
+ * `…/hero-atlas.layout.json`. The binding schema already forces a `.png`
+ * destination; anything else keeps its full name plus the suffix rather than
+ * silently truncating an unexpected extension.
+ */
+export function layoutSidecarPath(atlasDestPath) {
+ const stem = atlasDestPath.replace(/\.png$/i, '');
+ return `${stem}.layout.json`;
+}
+
+/**
+ * Walk frame count for a compiled atlas. Pointers written before #2970 have no
+ * `walkFrameCount`, so fall back to counting the columns that are neither the
+ * idle anchor nor the scanner placeholder — which also survives #2986 dropping
+ * the scanner column from the grid.
+ */
+export function resolveWalkFrameCount(geometry) {
+ if (Number.isInteger(geometry?.walkFrameCount)) return geometry.walkFrameCount;
+ if (!Array.isArray(geometry?.columns)) return null;
+ return geometry.columns.filter((c) => c !== IDLE_COLUMN && c !== SCANNER_COLUMN).length;
+}
+
+/**
+ * Group the flat column list into named tracks of contiguous column spans:
+ * `{ idle: { start: 0, count: 1 }, walk: { start: 1, count: 8 }, … }`. Every
+ * walk-phase column collapses into the single `walk` track; any other column
+ * becomes a track of its own named for the column. A future four-frame scanner
+ * action therefore lands as `scanner: { start, count: 4 }` with no shape change
+ * on either side of the boundary.
+ */
+export function deriveTracks(columns, walkLabels = []) {
+ const walkColumns = new Set(walkLabels);
+ const tracks = {};
+ columns.forEach((column, index) => {
+ const name = walkColumns.has(column) ? 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.
+ *
+ * Deliberately carries NO publish timestamp: the payload is a pure function of
+ * the atlas bytes and their geometry, so an unchanged republish produces
+ * byte-identical content and the sidecar write stays idempotent (the publish
+ * path compares hashes to decide whether anything actually changed).
+ */
+export function buildAtlasLayout({
+ characterId, geometry, atlasSha256, version, atlasDestPath, walkLabels,
+}) {
+ const columns = geometry?.columns;
+ if (!Array.isArray(columns) || !columns.length) {
+ throw new Error('Compiled atlas geometry has no column list');
+ }
+ const walkFrameCount = resolveWalkFrameCount(geometry);
+ return {
+ schemaVersion: ATLAS_LAYOUT_SCHEMA_VERSION,
+ kind: ATLAS_LAYOUT_KIND,
+ characterId,
+ // Basename only: the sidecar sits beside the atlas, so a repo-relative
+ // path would just be a second copy of where the reader already is.
+ atlasFile: atlasDestPath.split('/').pop(),
+ atlasVersion: version ?? null,
+ sourceAtlasSha256: atlasSha256,
+ cellSize: geometry.cellSize ?? null,
+ rows: geometry.rows ?? (Array.isArray(geometry.directionOrder) ? geometry.directionOrder.length : null),
+ rowOrder: Array.isArray(geometry.directionOrder) ? [...geometry.directionOrder] : null,
+ columns: [...columns],
+ columnCount: columns.length,
+ tracks: deriveTracks(columns, walkLabels ?? []),
+ walkFrameCount,
+ previewFps: Number.isFinite(geometry.walkFps) ? geometry.walkFps : null,
+ previewFpsNote: PREVIEW_FPS_NOTE,
+ };
+}
+
+/**
+ * Compare compiled atlas geometry against an app's declared runtime contract.
+ * Returns `null` when they agree (or when no contract was declared — an absent
+ * contract publishes unchecked, exactly as before this existed), otherwise
+ * `{ code, message }` naming BOTH the actual and expected numbers and the two
+ * ways to resolve the disagreement.
+ */
+export function runtimeContractMismatch(geometry, contract, appLabel = 'the bound app') {
+ if (!contract) return null;
+
+ const actualColumns = Array.isArray(geometry?.columns) ? geometry.columns.length : null;
+ const actualFrames = resolveWalkFrameCount(geometry);
+ if (actualColumns === null || actualFrames === null) {
+ return {
+ code: 'ATLAS_GEOMETRY_UNKNOWN',
+ message: `The compiled atlas reports no column layout, so the runtime contract declared by ${appLabel} cannot be verified — recompile the atlas before publishing.`,
+ };
+ }
+
+ const { walkFrameCount: expectedFrames, columnCount: expectedColumns, cellSize: expectedCellSize } = contract;
+ const actualDesc = `Atlas has ${actualColumns} columns (${actualFrames} walk frames)`;
+ const expectedDesc = Number.isInteger(expectedColumns)
+ ? `${expectedColumns} (${expectedFrames} walk frames)`
+ : `${expectedFrames} walk frames`;
+
+ if (Number.isInteger(expectedFrames) && expectedFrames !== actualFrames) {
+ return {
+ code: 'PUBLISH_CONTRACT_MISMATCH',
+ message: `${actualDesc} but ${appLabel} expects ${expectedDesc}. `
+ + `Update the game's walk-frame constant and its cycle distance, or reprocess this walk set to ${expectedFrames} frames before publishing.`,
+ };
+ }
+ if (Number.isInteger(expectedColumns) && expectedColumns !== actualColumns) {
+ return {
+ code: 'PUBLISH_CONTRACT_MISMATCH',
+ message: `${actualDesc} but ${appLabel} expects ${expectedDesc}. `
+ + `The grid shape changed — update the app's expected column layout, or re-bind its runtime contract to ${actualColumns} columns before publishing.`,
+ };
+ }
+ if (Number.isInteger(expectedCellSize) && expectedCellSize !== geometry.cellSize) {
+ return {
+ code: 'PUBLISH_CONTRACT_MISMATCH',
+ message: `Atlas cells are ${geometry.cellSize}px but ${appLabel} expects ${expectedCellSize}px. `
+ + `Recompile this atlas at ${expectedCellSize}px cells, or update the app's cell-size constant before publishing.`,
+ };
+ }
+ return null;
+}
diff --git a/server/services/sprites/atlasLayout.test.js b/server/services/sprites/atlasLayout.test.js
new file mode 100644
index 0000000000..4c7d0cfcbd
--- /dev/null
+++ b/server/services/sprites/atlasLayout.test.js
@@ -0,0 +1,141 @@
+/**
+ * Atlas layout sidecar + runtime-contract comparison (#2982). Pure module —
+ * no fs, no compiler; publish.test.js owns the write/serialization side.
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ buildAtlasLayout, deriveTracks, layoutSidecarPath, resolveWalkFrameCount,
+ runtimeContractMismatch, ATLAS_LAYOUT_SCHEMA_VERSION,
+} from './atlasLayout.js';
+import { walkPhaseLabels } from './walkBounds.js';
+
+const DIRECTIONS = ['S', 'SE', 'E', 'NE', 'N', 'NW', 'W', 'SW'];
+const geometryFor = (walkFrameCount, overrides = {}) => ({
+ columns: ['idle', ...walkPhaseLabels(walkFrameCount), 'scanner'],
+ directionOrder: DIRECTIONS,
+ rows: DIRECTIONS.length,
+ cellSize: 96,
+ walkFrameCount,
+ walkFps: 10,
+ ...overrides,
+});
+
+describe('layoutSidecarPath', () => {
+ it('swaps the .png extension for .layout.json', () => {
+ expect(layoutSidecarPath('assets/sprites/hero/hero-atlas.png'))
+ .toBe('assets/sprites/hero/hero-atlas.layout.json');
+ expect(layoutSidecarPath('assets/HERO.PNG')).toBe('assets/HERO.layout.json');
+ });
+});
+
+describe('resolveWalkFrameCount', () => {
+ it('prefers the declared count and falls back to counting non-anchor columns', () => {
+ expect(resolveWalkFrameCount(geometryFor(12))).toBe(12);
+ // Pre-#2970 pointers carry no walkFrameCount.
+ expect(resolveWalkFrameCount({ columns: ['idle', 'a', 'b', 'c', 'scanner'] })).toBe(3);
+ // A scanner-less grid (#2986) still resolves.
+ expect(resolveWalkFrameCount({ columns: ['idle', 'a', 'b'] })).toBe(2);
+ expect(resolveWalkFrameCount({})).toBeNull();
+ });
+});
+
+describe('deriveTracks', () => {
+ it('collapses walk-phase columns into one span and gives every other column its own', () => {
+ const columns = ['idle', ...walkPhaseLabels(6), 'scanner'];
+ expect(deriveTracks(columns, walkPhaseLabels(6))).toEqual({
+ idle: { start: 0, count: 1 },
+ walk: { start: 1, count: 6 },
+ scanner: { start: 7, count: 1 },
+ });
+ });
+
+ it('describes a future multi-frame track as a span', () => {
+ const columns = ['idle', 'w0', 'w1', 'scan-a', 'scan-a', 'scan-a'];
+ expect(deriveTracks(columns, ['w0', 'w1'])).toEqual({
+ idle: { start: 0, count: 1 },
+ walk: { start: 1, count: 2 },
+ 'scan-a': { start: 3, count: 3 },
+ });
+ });
+
+ it('refuses a grid whose track columns are not contiguous', () => {
+ expect(() => deriveTracks(['idle', 'scanner', 'idle'], [])).toThrow(/non-contiguously/);
+ });
+});
+
+describe('buildAtlasLayout', () => {
+ it('describes the compiled grid, marking previewFps as authoring-only', () => {
+ const layout = buildAtlasLayout({
+ characterId: 'example-character',
+ geometry: geometryFor(8),
+ atlasSha256: 'abc123',
+ version: 4,
+ atlasDestPath: 'assets/sprites/hero/hero-atlas.png',
+ walkLabels: walkPhaseLabels(8),
+ });
+ expect(layout).toMatchObject({
+ schemaVersion: ATLAS_LAYOUT_SCHEMA_VERSION,
+ kind: 'portos-sprite-atlas-layout',
+ characterId: 'example-character',
+ atlasFile: 'hero-atlas.png',
+ atlasVersion: 4,
+ sourceAtlasSha256: 'abc123',
+ cellSize: 96,
+ rows: 8,
+ rowOrder: DIRECTIONS,
+ columnCount: 10,
+ walkFrameCount: 8,
+ previewFps: 10,
+ });
+ expect(layout.tracks.walk).toEqual({ start: 1, count: 8 });
+ expect(layout.previewFpsNote).toMatch(/do not use this as a runtime frame rate/);
+ // No timestamp: identical geometry must produce byte-identical content so
+ // an unchanged republish stays a no-op.
+ expect(JSON.stringify(layout)).not.toMatch(/publishedAt/);
+ });
+
+ it('refuses geometry with no column list', () => {
+ expect(() => buildAtlasLayout({ characterId: 'x', geometry: {}, atlasDestPath: 'a.png' }))
+ .toThrow(/no column list/);
+ });
+});
+
+describe('runtimeContractMismatch', () => {
+ const contract = { walkFrameCount: 8, cellSize: 96, columnCount: 10 };
+
+ it('passes an absent contract and a matching one', () => {
+ expect(runtimeContractMismatch(geometryFor(12), null)).toBeNull();
+ expect(runtimeContractMismatch(geometryFor(12), undefined)).toBeNull();
+ expect(runtimeContractMismatch(geometryFor(8), contract)).toBeNull();
+ });
+
+ it('names both counts and both resolutions on a frame-count mismatch', () => {
+ const result = runtimeContractMismatch(geometryFor(12), contract, 'Example App');
+ expect(result.code).toBe('PUBLISH_CONTRACT_MISMATCH');
+ expect(result.message).toContain('Atlas has 14 columns (12 walk frames)');
+ expect(result.message).toContain('Example App expects 10 (8 walk frames)');
+ expect(result.message).toMatch(/walk-frame constant/);
+ expect(result.message).toMatch(/reprocess this walk set to 8 frames/);
+ });
+
+ it('flags a column-count-only mismatch as a grid-shape change', () => {
+ // The scanner column removed (#2986) against a contract that still expects it.
+ const geometry = { columns: ['idle', ...walkPhaseLabels(8)], cellSize: 96, walkFrameCount: 8 };
+ const result = runtimeContractMismatch(geometry, contract, 'Example App');
+ expect(result.message).toContain('Atlas has 9 columns (8 walk frames)');
+ expect(result.message).toMatch(/grid shape changed/);
+ });
+
+ it('flags a cell-size mismatch', () => {
+ const result = runtimeContractMismatch(geometryFor(8, { cellSize: 64 }), contract, 'Example App');
+ expect(result.message).toBe(
+ 'Atlas cells are 64px but Example App expects 96px. '
+ + "Recompile this atlas at 96px cells, or update the app's cell-size constant before publishing.",
+ );
+ });
+
+ it('refuses to vouch for geometry it cannot read', () => {
+ expect(runtimeContractMismatch({}, contract).code).toBe('ATLAS_GEOMETRY_UNKNOWN');
+ });
+});
diff --git a/server/services/sprites/publish.js b/server/services/sprites/publish.js
index a850439444..a86c8bbcc6 100644
--- a/server/services/sprites/publish.js
+++ b/server/services/sprites/publish.js
@@ -18,6 +18,14 @@
* drift. Engine sidecars (e.g. Godot .png.import) are the game repo's
* concern and are never touched.
*
+ * The optional runtimeContract (#2982) is the reverse direction: the app
+ * declares the grid it was built against ({ walkFrameCount, cellSize,
+ * columnCount }) and a publish whose compiled geometry disagrees is refused
+ * instead of silently shifting every column the game reads. Alongside the PNG,
+ * publish writes a `<atlas-stem>.layout.json` sidecar describing the grid
+ * PortOS actually produced, so the app can resolve columns by name rather than
+ * by memory. An absent contract publishes unchecked, exactly as before.
+ *
* Publishes serialize on a per-app queue (the appDeployer per-app-lock
* posture) nested inside the record's walk write tail.
*/
@@ -37,6 +45,10 @@ import { updateRecord } from './records.js';
import { withWalkWriteTail } from './walk.js';
import { compileAtlasInTail } from './atlas.js';
import { sha256Buffer } from './walkPostprocess.js';
+import { walkPhaseLabels, WALK_MIN_FRAME_COUNT, WALK_MAX_FRAME_COUNT } from './walkBounds.js';
+import {
+ buildAtlasLayout, layoutSidecarPath, runtimeContractMismatch, resolveWalkFrameCount,
+} from './atlasLayout.js';
// Per-repo serialization: keyed by the resolved repoPath (matching
// appDeployer's `deployingApps` key), so two app records pointing at the
@@ -76,12 +88,53 @@ async function requireAppRepo(appId, status) {
return { app, repoRoot: app.repoPath };
}
+const isPositiveInt = (v) => Number.isInteger(v) && v > 0;
+
+/**
+ * Validate the optional runtimeContract — the grid the consuming app was built
+ * against (#2982). `walkFrameCount` is required when a contract is present (it
+ * is the whole point of declaring one); `cellSize` and `columnCount` are
+ * optional extra assertions. The fields are NOT cross-checked against each
+ * other here: what counts as a consistent column layout is the compiler's
+ * business and changes with the grid (#2986 drops the scanner column), so a
+ * stale count surfaces at publish with both numbers named rather than as an
+ * unexplained 400 at save.
+ */
+function validateRuntimeContract(runtimeContract) {
+ if (runtimeContract === undefined || runtimeContract === null) return null;
+ if (typeof runtimeContract !== 'object' || Array.isArray(runtimeContract)) {
+ throw bindingError('runtimeContract must be an object', 'INVALID_RUNTIME_CONTRACT');
+ }
+ const { walkFrameCount, cellSize, columnCount } = runtimeContract;
+ if (!Number.isInteger(walkFrameCount)
+ || walkFrameCount < WALK_MIN_FRAME_COUNT || walkFrameCount > WALK_MAX_FRAME_COUNT) {
+ throw bindingError(
+ `runtimeContract.walkFrameCount must be an integer between ${WALK_MIN_FRAME_COUNT} and ${WALK_MAX_FRAME_COUNT}`,
+ 'INVALID_RUNTIME_CONTRACT',
+ );
+ }
+ if (cellSize !== undefined && cellSize !== null && !isPositiveInt(cellSize)) {
+ throw bindingError('runtimeContract.cellSize must be a positive integer', 'INVALID_RUNTIME_CONTRACT');
+ }
+ if (columnCount !== undefined && columnCount !== null && !isPositiveInt(columnCount)) {
+ throw bindingError('runtimeContract.columnCount must be a positive integer', 'INVALID_RUNTIME_CONTRACT');
+ }
+ return {
+ walkFrameCount,
+ cellSize: isPositiveInt(cellSize) ? cellSize : null,
+ columnCount: isPositiveInt(columnCount) ? columnCount : null,
+ };
+}
+
/** Validate a publishBinding shape (null clears it). */
export async function validatePublishBinding(binding) {
if (binding === null) return null;
- const { appId, atlasDestPath, codeBinding } = binding;
+ const { appId, atlasDestPath, codeBinding, runtimeContract } = binding;
const { app } = await requireAppRepo(appId, 400);
anchorRepoPath(app.repoPath, atlasDestPath, 'atlasDestPath');
+ // The sidecar lands beside the atlas, so its path must anchor too — catch a
+ // destination whose sidecar would escape the repo at SAVE time, not mid-publish.
+ anchorRepoPath(app.repoPath, layoutSidecarPath(atlasDestPath), 'atlas layout sidecar');
if (codeBinding) {
anchorRepoPath(app.repoPath, codeBinding.path, 'codeBinding.path');
if (typeof codeBinding.resourcePath !== 'string' || !codeBinding.resourcePath.trim()) {
@@ -98,13 +151,26 @@ export async function validatePublishBinding(binding) {
requiredOccurrenceCount: codeBinding.requiredOccurrenceCount ?? 1,
}
: null,
+ // `undefined` (key absent) is distinct from `null` (explicit clear) — see
+ // setPublishBinding, which carries an absent contract over from the stored
+ // binding so a client that predates the field can't silently wipe it.
+ runtimeContract: validateRuntimeContract(runtimeContract),
};
}
-/** Persist a validated binding on the record. */
+/**
+ * Persist a validated binding on the record. A binding that omits
+ * `runtimeContract` entirely INHERITS the stored one (absent ≠ empty): the
+ * publish form saves appId/dest/codeBinding only, and a form save must not
+ * silently drop the contract an app declared through the API. Pass
+ * `runtimeContract: null` to clear it, or `binding: null` to clear everything.
+ */
export async function setPublishBinding(recordId, binding) {
- await requireCharacter(recordId);
+ const record = await requireCharacter(recordId);
const validated = await validatePublishBinding(binding);
+ if (validated && binding.runtimeContract === undefined) {
+ validated.runtimeContract = record.publishBinding?.runtimeContract ?? null;
+ }
return updateRecord(recordId, { publishBinding: validated });
}
@@ -175,6 +241,39 @@ async function publishAtlasImpl(recordId, { acknowledgeOverwrite = false } = {})
: undefined;
const compiled = await compileAtlasInTail(recordId, { geometry: geometryOverride });
+ // Export contract (#2982): refuse a publish the bound app cannot consume,
+ // BEFORE taking the repo write lock — the game tree stays untouched and the
+ // message names both the actual and expected counts. No declared contract ⇒
+ // unchanged, unchecked behavior.
+ const appLabel = app.name || binding.appId;
+ const mismatch = runtimeContractMismatch(compiled.geometry, binding.runtimeContract, appLabel);
+ if (mismatch) {
+ throw new ServerError(mismatch.message, { status: 409, code: mismatch.code });
+ }
+
+ // The sidecar describing the grid PortOS actually produced. Built here (pure,
+ // lock-free) so a geometry the compiler can't describe fails before any
+ // write, and so the same bytes are used by both the write and the up-to-date
+ // comparison below. It carries no timestamp: identical geometry ⇒ identical
+ // bytes ⇒ a republish is a genuine no-op.
+ if (!Array.isArray(compiled.geometry?.columns)) {
+ throw new ServerError(
+ 'The compiled atlas reports no column layout, so its layout sidecar cannot be written — recompile the atlas before publishing.',
+ { status: 422, code: 'ATLAS_GEOMETRY_UNKNOWN' },
+ );
+ }
+ const layout = buildAtlasLayout({
+ characterId: recordId,
+ geometry: compiled.geometry,
+ atlasSha256: compiled.atlasSha256,
+ version: compiled.version,
+ atlasDestPath: binding.atlasDestPath,
+ walkLabels: walkPhaseLabels(resolveWalkFrameCount(compiled.geometry)),
+ });
+ const layoutBuffer = Buffer.from(`${JSON.stringify(layout, null, 2)}\n`);
+ const layoutSha256 = sha256Buffer(layoutBuffer);
+ const layoutDestPath = layoutSidecarPath(binding.atlasDestPath);
+
return repoPublishTail(resolve(repoRoot), async () => {
// Don't mutate a tree a deploy is currently building from — appDeployer
// keys its lock by repoPath, so honor it here (the reverse direction —
@@ -183,6 +282,20 @@ async function publishAtlasImpl(recordId, { acknowledgeOverwrite = false } = {})
throw new ServerError(`App ${app.name || binding.appId} is deploying — retry when the deploy finishes`, { status: 409, code: 'APP_DEPLOY_IN_PROGRESS' });
}
const destAbs = anchorRepoPath(repoRoot, binding.atlasDestPath, 'atlasDestPath');
+ // The sidecar is repo-anchored and written inside this same per-repo tail
+ // as the PNG, so the pair is never interleaved with another publish into
+ // the same checkout.
+ const layoutAbs = anchorRepoPath(repoRoot, layoutDestPath, 'atlas layout sidecar');
+ // Write it only when the content actually differs, so a republish that
+ // changes nothing stays a genuine no-op. Returns whether the repo was
+ // mutated — an atlas already at the destination but MISSING its sidecar
+ // still gets one, so the two can never be permanently out of step.
+ const writeLayoutSidecar = async () => {
+ const existingLayoutSha = (await pathExists(layoutAbs)) ? await sha256File(layoutAbs) : null;
+ if (existingLayoutSha === layoutSha256) return false;
+ await atomicWrite(layoutAbs, layoutBuffer);
+ return true;
+ };
const atlasBuffer = await readFile(join(dir, compiled.atlasPath)).catch(() => null);
if (!atlasBuffer) {
throw new ServerError('Compiled atlas file is missing on disk — recompile before publishing', { status: 422, code: 'ATLAS_OUTPUT_MISSING' });
@@ -230,16 +343,25 @@ async function publishAtlasImpl(recordId, { acknowledgeOverwrite = false } = {})
const codeBinding = binding.codeBinding
? await applyCodeBinding(repoRoot, binding.codeBinding, previousForCode?.codeBinding?.resourcePath)
: null;
- // The destination already holds the current bytes, but two sub-cases
+ // An up-to-date atlas can still be missing (or carrying a stale) layout
+ // sidecar — from a publish that predates it, or a hand-deleted file.
+ // Reconcile it here so the pair converges on the next publish.
+ const layoutWritten = await writeLayoutSidecar();
+ // The destination already holds the current bytes, but three sub-cases
// still mutate durable state and must be recorded: a code-binding
- // rewrite just changed the game's source, and a first-ever publish
- // finding its own bytes needs a history baseline (otherwise the next
- // changed-atlas publish reads the dest as foreign and 409s OCCUPIED).
+ // rewrite just changed the game's source, the sidecar was just written,
+ // and a first-ever publish finding its own bytes needs a history
+ // baseline (otherwise the next changed-atlas publish reads the dest as
+ // foreign and 409s OCCUPIED).
let publication = null;
- if ((codeBinding?.rewritten || !previous)) {
- publication = await recordPublication({ destPreviousSha256: destSha256, codeBinding, upToDateBaseline: true });
+ if ((codeBinding?.rewritten || layoutWritten || !previous)) {
+ publication = await recordPublication({
+ destPreviousSha256: destSha256, codeBinding, layoutDestPath, layoutSha256, upToDateBaseline: true,
+ });
}
- return { published: false, upToDate: true, compiled, codeBinding, publication };
+ return {
+ published: false, upToDate: true, compiled, codeBinding, publication, layoutWritten, layoutDestPath,
+ };
}
if (previous && destSha256 !== null && destSha256 !== previous.atlasSha256) {
throw new ServerError(
@@ -263,10 +385,18 @@ async function publishAtlasImpl(recordId, { acknowledgeOverwrite = false } = {})
? await applyCodeBinding(repoRoot, binding.codeBinding, previousForCode?.codeBinding?.resourcePath)
: null;
+ // Sidecar BEFORE the atlas. Either order has a crash window, but only this
+ // one fails loudly: the layout carries `sourceAtlasSha256`, so a sidecar
+ // that landed without its atlas is DETECTABLE by the consumer, whereas a
+ // new atlas under a stale/absent layout is exactly the silent column shift
+ // this whole contract exists to prevent.
+ const layoutWritten = await writeLayoutSidecar();
await atomicWrite(destAbs, atlasBuffer);
- const publication = await recordPublication({ destPreviousSha256: destSha256, codeBinding });
+ const publication = await recordPublication({
+ destPreviousSha256: destSha256, codeBinding, layoutDestPath, layoutSha256,
+ });
console.log(`🚚 sprite atlas v${compiled.version} published for ${recordId} → ${app.name || binding.appId}:${binding.atlasDestPath}`);
- return { published: true, publication, compiled };
+ return { published: true, publication, compiled, layoutWritten, layoutDestPath };
});
}
diff --git a/server/services/sprites/publish.test.js b/server/services/sprites/publish.test.js
index 03f083a2fa..086c08e994 100644
--- a/server/services/sprites/publish.test.js
+++ b/server/services/sprites/publish.test.js
@@ -4,6 +4,10 @@
* destination refusal, idempotent re-publish, occurrence-count-guarded code
* binding verify/rewrite, and the publish history. The atlas compiler is
* mocked (covered by atlas.test.js) — these tests own everything after it.
+ *
+ * Also covers the export contract (#2982): the optional runtimeContract's
+ * shape validation, the publish-time geometry guard, and the layout.json
+ * sidecar written beside the published PNG.
*/
import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';
@@ -40,11 +44,30 @@ vi.mock('./atlas.js', () => ({
const records = await import('./records.js');
const { setPublishBinding, publishAtlas, validatePublishBinding } = await import('./publish.js');
+const { walkPhaseLabels } = await import('./walkBounds.js');
let seq = 0;
const sha256 = (buf) => createHash('sha256').update(buf).digest('hex');
-async function characterWithAtlas(atlasBytes = 'atlas-png-bytes-v1') {
+const DIRECTIONS = ['S', 'SE', 'E', 'NE', 'N', 'NW', 'W', 'SW'];
+
+// The geometry block a real compile writes into the runtime pointer — the
+// publish path reads it for the contract guard and the layout sidecar.
+const atlasGeometry = (walkFrameCount = 8, overrides = {}) => ({
+ columns: ['idle', ...walkPhaseLabels(walkFrameCount), 'scanner'],
+ directionOrder: DIRECTIONS,
+ rows: DIRECTIONS.length,
+ cellSize: 96,
+ walkFrameCount,
+ walkFps: 12,
+ ...overrides,
+});
+
+const sidecarPath = (destPath) => destPath.replace(/\.png$/, '.layout.json');
+const readSidecar = async (destPath) =>
+ JSON.parse(await readFile(join(APP_REPO, sidecarPath(destPath)), 'utf8'));
+
+async function characterWithAtlas(atlasBytes = 'atlas-png-bytes-v1', geometry = atlasGeometry()) {
const id = `pub-char-${++seq}`;
await records.createRecord({ kind: 'character', name: 'Publisher' }, id);
const atlasRel = `runtime/v1/${id}-animation-atlas-v1.png`;
@@ -56,6 +79,7 @@ async function characterWithAtlas(atlasBytes = 'atlas-png-bytes-v1') {
version: 1,
atlasPath: atlasRel,
atlasSha256: sha256(Buffer.from(atlasBytes)),
+ geometry,
});
return { id, atlasRel, atlasBytes };
}
@@ -88,6 +112,7 @@ describe('validatePublishBinding / setPublishBinding', () => {
resourcePath: 'res://assets/sprites/hero/hero-atlas.png',
requiredOccurrenceCount: 1,
},
+ runtimeContract: null,
});
});
@@ -107,6 +132,44 @@ describe('validatePublishBinding / setPublishBinding', () => {
.rejects.toMatchObject({ code: 'INVALID_PUBLISH_PATH' });
// Non-.png destinations die at the route's Zod schema (spritePublishBindingSchema).
});
+
+ it('validates the runtimeContract shape at save time', async () => {
+ const { id } = await characterWithAtlas();
+ const saved = await setPublishBinding(id, {
+ ...BINDING,
+ runtimeContract: { walkFrameCount: 8, cellSize: 96, columnCount: 10 },
+ });
+ expect(saved.publishBinding.runtimeContract).toEqual({
+ walkFrameCount: 8, cellSize: 96, columnCount: 10,
+ });
+
+ for (const bad of [
+ { walkFrameCount: 0 },
+ { walkFrameCount: 99 },
+ { walkFrameCount: 8.5 },
+ { cellSize: 96 },
+ { walkFrameCount: 8, cellSize: 'big' },
+ { walkFrameCount: 8, columnCount: -1 },
+ ]) {
+ await expect(validatePublishBinding({ ...BINDING, runtimeContract: bad }))
+ .rejects.toMatchObject({ status: 400, code: 'INVALID_RUNTIME_CONTRACT' });
+ }
+ await expect(validatePublishBinding({ ...BINDING, runtimeContract: [8] }))
+ .rejects.toMatchObject({ status: 400, code: 'INVALID_RUNTIME_CONTRACT' });
+ });
+
+ it('inherits an omitted runtimeContract and clears it only on an explicit null', async () => {
+ const { id } = await characterWithAtlas();
+ await setPublishBinding(id, { ...BINDING, runtimeContract: { walkFrameCount: 8 } });
+
+ // The publish form saves appId/dest/codeBinding only — an omitted key must
+ // not silently wipe the contract the app declared through the API.
+ const resaved = await setPublishBinding(id, { ...BINDING, atlasDestPath: 'assets/sprites/hero/moved.png' });
+ expect(resaved.publishBinding.runtimeContract).toEqual({ walkFrameCount: 8, cellSize: null, columnCount: null });
+
+ const cleared = await setPublishBinding(id, { ...BINDING, runtimeContract: null });
+ expect(cleared.publishBinding.runtimeContract).toBeNull();
+ });
});
describe('publishAtlas', () => {
@@ -161,7 +224,7 @@ describe('publishAtlas', () => {
await mkdir(join(TEST_ROOT, 'sprites', id, 'runtime/v2'), { recursive: true });
await writeFile(join(TEST_ROOT, 'sprites', id, nextRel), nextBytes);
compileAtlasInTail.mockResolvedValue({
- created: true, version: 2, atlasPath: nextRel, atlasSha256: sha256(Buffer.from(nextBytes)),
+ created: true, version: 2, atlasPath: nextRel, atlasSha256: sha256(Buffer.from(nextBytes)), geometry: atlasGeometry(),
});
await expect(publishAtlas(id)).rejects.toMatchObject({ status: 409, code: 'PUBLISH_DEST_DIVERGED' });
});
@@ -208,7 +271,7 @@ describe('publishAtlas', () => {
await mkdir(join(TEST_ROOT, 'sprites', id, 'runtime/v2'), { recursive: true });
await writeFile(join(TEST_ROOT, 'sprites', id, nextRel), nextBytes);
compileAtlasInTail.mockResolvedValue({
- created: true, version: 2, atlasPath: nextRel, atlasSha256: sha256(Buffer.from(nextBytes)),
+ created: true, version: 2, atlasPath: nextRel, atlasSha256: sha256(Buffer.from(nextBytes)), geometry: atlasGeometry(),
});
await expect(publishAtlas(id)).rejects.toMatchObject({ status: 409, code: 'CODE_BINDING_DRIFTED' });
// The drifted binding aborted BEFORE the atlas was replaced.
@@ -283,7 +346,7 @@ describe('publishAtlas', () => {
await mkdir(join(TEST_ROOT, 'sprites', id, 'runtime/v2'), { recursive: true });
await writeFile(join(TEST_ROOT, 'sprites', id, nextRel), nextBytes);
compileAtlasInTail.mockResolvedValue({
- created: true, version: 2, atlasPath: nextRel, atlasSha256: sha256(Buffer.from(nextBytes)),
+ created: true, version: 2, atlasPath: nextRel, atlasSha256: sha256(Buffer.from(nextBytes)), geometry: atlasGeometry(),
});
const second = await publishAtlas(id);
expect(second.published).toBe(true);
@@ -317,3 +380,138 @@ describe('publishAtlas', () => {
expect(await readFile(join(APP_REPO, BINDING.atlasDestPath)).catch(() => null)).toBeNull();
});
});
+
+describe('runtime contract guard (#2982)', () => {
+ it('publishes when the compiled geometry matches the declared contract', async () => {
+ const { id } = await characterWithAtlas();
+ await setPublishBinding(id, {
+ ...BINDING,
+ runtimeContract: { walkFrameCount: 8, cellSize: 96, columnCount: 10 },
+ });
+ const result = await publishAtlas(id);
+ expect(result.published).toBe(true);
+ });
+
+ it('refuses a frame-count mismatch with both counts named, leaving the repo untouched', async () => {
+ const { id } = await characterWithAtlas('atlas-png-bytes-12f', atlasGeometry(12));
+ await setPublishBinding(id, {
+ ...BINDING,
+ runtimeContract: { walkFrameCount: 8, cellSize: 96, columnCount: 10 },
+ });
+ await expect(publishAtlas(id)).rejects.toMatchObject({ status: 409, code: 'PUBLISH_CONTRACT_MISMATCH' });
+ await expect(publishAtlas(id)).rejects.toThrow(/14 columns \(12 walk frames\).*expects 10 \(8 walk frames\)/s);
+ await expect(publishAtlas(id)).rejects.toThrow(/reprocess this walk set to 8 frames/);
+ // Nothing landed in the game repo — not the atlas, not the sidecar.
+ expect(await readFile(join(APP_REPO, BINDING.atlasDestPath)).catch(() => null)).toBeNull();
+ expect(await readFile(join(APP_REPO, sidecarPath(BINDING.atlasDestPath))).catch(() => null)).toBeNull();
+ });
+
+ it('refuses a cell-size mismatch', async () => {
+ const { id } = await characterWithAtlas('atlas-png-bytes-64px', atlasGeometry(8, { cellSize: 64 }));
+ await setPublishBinding(id, { ...BINDING, runtimeContract: { walkFrameCount: 8, cellSize: 96 } });
+ await expect(publishAtlas(id)).rejects.toThrow(/cells are 64px but Example Game expects 96px/);
+ });
+
+ it('publishes a non-8-frame atlas unchecked when no contract is declared', async () => {
+ const { id } = await characterWithAtlas('atlas-png-bytes-12f', atlasGeometry(12));
+ await setPublishBinding(id, BINDING);
+ const result = await publishAtlas(id);
+ expect(result.published).toBe(true);
+ expect((await readSidecar(BINDING.atlasDestPath)).walkFrameCount).toBe(12);
+ });
+});
+
+describe('layout sidecar (#2982)', () => {
+ it('writes the sidecar beside the atlas with the column list the atlas actually has', async () => {
+ const { id, atlasBytes } = await characterWithAtlas('atlas-png-bytes-12f', atlasGeometry(12));
+ await setPublishBinding(id, BINDING);
+ const result = await publishAtlas(id);
+
+ const layout = await readSidecar(BINDING.atlasDestPath);
+ expect(layout).toMatchObject({
+ schemaVersion: 1,
+ kind: 'portos-sprite-atlas-layout',
+ characterId: id,
+ atlasFile: 'hero-atlas.png',
+ cellSize: 96,
+ rows: 8,
+ walkFrameCount: 12,
+ columnCount: 14,
+ previewFps: 12,
+ sourceAtlasSha256: sha256(Buffer.from(atlasBytes)),
+ });
+ expect(layout.columns[0]).toBe('idle');
+ expect(layout.columns.at(-1)).toBe('scanner');
+ expect(layout.columns).toHaveLength(14);
+ // Per-track spans so a future multi-frame track is additive, not a rewrite.
+ expect(layout.tracks).toEqual({
+ idle: { start: 0, count: 1 },
+ walk: { start: 1, count: 12 },
+ scanner: { start: 13, count: 1 },
+ });
+ // previewFps travels labeled as authoring-only — the app must not animate from it.
+ expect(layout.previewFpsNote).toMatch(/Authoring metadata only/);
+ expect(result.publication).toMatchObject({ layoutDestPath: 'assets/sprites/hero/hero-atlas.layout.json' });
+ });
+
+ it('is a no-op on an unchanged republish but self-heals a deleted sidecar', async () => {
+ const { id } = await characterWithAtlas();
+ await setPublishBinding(id, BINDING);
+ await publishAtlas(id);
+
+ const again = await publishAtlas(id);
+ expect(again.upToDate).toBe(true);
+ expect(again.layoutWritten).toBe(false);
+ let history = JSON.parse(await readFile(join(TEST_ROOT, 'sprites', id, 'runtime/publications.json'), 'utf8'));
+ expect(history).toHaveLength(1);
+
+ // The atlas is still current but its sidecar was deleted in the game repo —
+ // the pair must converge rather than leave the atlas undescribed.
+ rmSync(join(APP_REPO, sidecarPath(BINDING.atlasDestPath)));
+ const healed = await publishAtlas(id);
+ expect(healed.upToDate).toBe(true);
+ expect(healed.layoutWritten).toBe(true);
+ expect((await readSidecar(BINDING.atlasDestPath)).walkFrameCount).toBe(8);
+ history = JSON.parse(await readFile(join(TEST_ROOT, 'sprites', id, 'runtime/publications.json'), 'utf8'));
+ expect(history).toHaveLength(2);
+ });
+
+ it('rewrites the sidecar when the atlas changes', async () => {
+ const { id } = await characterWithAtlas();
+ await setPublishBinding(id, BINDING);
+ await publishAtlas(id);
+ expect((await readSidecar(BINDING.atlasDestPath)).walkFrameCount).toBe(8);
+
+ const nextBytes = 'atlas-png-bytes-v2';
+ const nextRel = `runtime/v2/${id}-animation-atlas-v2.png`;
+ await mkdir(join(TEST_ROOT, 'sprites', id, 'runtime/v2'), { recursive: true });
+ await writeFile(join(TEST_ROOT, 'sprites', id, nextRel), nextBytes);
+ compileAtlasInTail.mockResolvedValue({
+ created: true,
+ version: 2,
+ atlasPath: nextRel,
+ atlasSha256: sha256(Buffer.from(nextBytes)),
+ geometry: atlasGeometry(10),
+ });
+ const result = await publishAtlas(id);
+ expect(result.published).toBe(true);
+ expect(result.layoutWritten).toBe(true);
+ const layout = await readSidecar(BINDING.atlasDestPath);
+ expect(layout).toMatchObject({
+ walkFrameCount: 10, columnCount: 12, atlasVersion: 2, sourceAtlasSha256: sha256(Buffer.from(nextBytes)),
+ });
+ });
+
+ it('refuses to publish an atlas whose geometry carries no column layout', async () => {
+ const { id } = await characterWithAtlas('atlas-png-bytes-nogeo', undefined);
+ compileAtlasInTail.mockResolvedValue({
+ created: false,
+ version: 1,
+ atlasPath: `runtime/v1/${id}-animation-atlas-v1.png`,
+ atlasSha256: sha256(Buffer.from('atlas-png-bytes-nogeo')),
+ });
+ await setPublishBinding(id, BINDING);
+ await expect(publishAtlas(id)).rejects.toMatchObject({ status: 422, code: 'ATLAS_GEOMETRY_UNKNOWN' });
+ expect(await readFile(join(APP_REPO, BINDING.atlasDestPath)).catch(() => null)).toBeNull();
+ });
+});