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

fix: reject contentless packaged sprite frames at compile time (#4695)

[._.]/ Adam Eivy3542da113664
diff --git a/server/services/sprites/atlas.test.js b/server/services/sprites/atlas.test.js
index 183e2af570..da27391b8a 100644
--- a/server/services/sprites/atlas.test.js
+++ b/server/services/sprites/atlas.test.js
@@ -278,6 +278,28 @@ async function finalizedCharacter() {
return id;
}
+async function replaceFinalizedFrame(recordId, direction, index, bytes) {
+ const dir = join(TEST_ROOT, 'sprites', recordId);
+ const walkSetRel = `walk/${recordId}-walk-set-v1.json`;
+ const walkSet = JSON.parse(await readFile(join(dir, walkSetRel), 'utf8'));
+ const selection = JSON.parse(await readFile(join(dir, walkSet.selectionPath), 'utf8'));
+ const entry = selection.directions[direction];
+ const manifest = JSON.parse(await readFile(join(dir, entry.runManifest), 'utf8'));
+ const frame = manifest.frames[index];
+ await writeFile(join(dir, frame.path), bytes);
+ frame.sha256 = sha256(bytes);
+ const manifestBytes = Buffer.from(JSON.stringify(manifest));
+ await writeFile(join(dir, entry.runManifest), manifestBytes);
+ entry.runManifestSha256 = sha256(manifestBytes);
+ selection.directions[direction] = entry;
+ const selectionBytes = Buffer.from(JSON.stringify(selection));
+ await writeFile(join(dir, walkSet.selectionPath), selectionBytes);
+ walkSet.directions[direction] = entry;
+ walkSet.selectionSha256 = sha256(selectionBytes);
+ await writeFile(join(dir, walkSetRel), JSON.stringify(walkSet));
+ return frame.phase;
+}
+
beforeEach(() => {
rmSync(join(TEST_ROOT, 'sprite-records.json'), { force: true });
});
@@ -462,7 +484,7 @@ describe('compileAtlas', () => {
const changed = await compileAtlas(id, { tracks: customTracks });
expect(changed.created).toBe(true);
expect(changed.version).toBe(backfilled.version + 1);
- });
+ }, 20_000);
it('compiles the 9×8 player atlas with full provenance and a current pointer', async () => {
const id = await finalizedCharacter();
@@ -789,6 +811,23 @@ describe('compileAtlas', () => {
await expect(compileAtlas(id)).rejects.toMatchObject({ status: 422 });
});
+ it('surfaces a degenerate packaged frame through atlas validation', async () => {
+ const id = await finalizedCharacter();
+ const direction = SPRITE_DIRECTIONS[0];
+ const empty = await sharp({
+ create: { width: 40, height: 40, channels: 4, background: { r: 0, g: 0, b: 0, alpha: 0 } },
+ }).png().toBuffer();
+ const phase = await replaceFinalizedFrame(id, direction, 3, empty);
+
+ await expect(compileAtlas(id)).rejects.toMatchObject({
+ status: 422,
+ code: 'ATLAS_COMPILE_INVALID',
+ message: expect.stringContaining(
+ `Direction ${direction} frame 3 (${phase}) has no content`,
+ ),
+ });
+ }, 20_000);
+
it('refuses without a finalized walk set', async () => {
const id = newId();
await lockAllAnchors(id);
diff --git a/server/services/sprites/walkFrames.js b/server/services/sprites/walkFrames.js
index f3ab7254f1..6c0fd61f02 100644
--- a/server/services/sprites/walkFrames.js
+++ b/server/services/sprites/walkFrames.js
@@ -10,7 +10,7 @@
* later" the approve-time check exists to prevent, just narrowed rather than
* closed. This helper makes the cheap approve check a strict PREFIX of the
* expensive compile check — identical path resolution, with compile layering
- * byte-level checks on top.
+ * byte-level and content checks on top.
*
* Every declared frame is re-anchored to record-relative (an imported manifest
* names its frames against the SOURCE repo root) and resolved drift-tolerantly —
@@ -22,11 +22,12 @@
* { bytes: false } (approve) — existence only. Returns `{ total, missing }`,
* never throwing; the caller turns a non-zero `missing` into its own
* RUN_FRAMES_MISSING error, reporting the true declared `total`.
- * { bytes: true } (compile) — existence PLUS per-frame sha256 and
+ * { bytes: true } (compile) — existence PLUS per-frame sha256, content, and
* gait-phase/outputIndex ordering, reading each frame's bytes exactly once
* and returning them (read-once-verify-in-memory) as `{ total, missing: 0,
* frameBytes }` so the compiler composites the pixels it verified. Any
- * missing / mis-ordered / tampered frame throws a 422 ATLAS_COMPILE_INVALID.
+ * missing / mis-ordered / tampered / degenerate frame throws a 422
+ * ATLAS_COMPILE_INVALID.
*/
import { readFile } from 'fs/promises';
@@ -38,6 +39,7 @@ import { sha256Buffer } from './walkPostprocess.js';
import { WALK_TRACK, getAnimationTrack } from './animationTracks.js';
import { getEffectiveAnimationTracks } from './animationTrackStore.js';
import { trackColumnLabels } from './atlasGrid.js';
+import { describeFrameStats, isDegenerateFrame } from '../../lib/imageFrameStats.js';
const compileFrameError = (message) =>
new ServerError(message, { status: 422, code: 'ATLAS_COMPILE_INVALID' });
@@ -88,5 +90,19 @@ export async function verifyPackagedFrames(recordId, manifest, {
frameBytes.push(buf);
}
+ if (bytes) {
+ // Content probes are independent once every frame's hash and ordering have
+ // passed. Measure them together, then report the first failing frame in
+ // manifest order while preserving the read-once verification seam above.
+ const stats = await Promise.all(frameBytes.map((buf) => describeFrameStats(buf)));
+ const degenerateIndex = stats.findIndex(isDegenerateFrame);
+ if (degenerateIndex >= 0) {
+ const frame = frames[degenerateIndex];
+ throw compileFrameError(
+ `Direction ${manifest?.direction} frame ${degenerateIndex} (${frame.phase}) has no content — regenerate that frame and recompile`,
+ );
+ }
+ }
+
return { total, missing, frameBytes };
}
diff --git a/server/services/sprites/walkFrames.test.js b/server/services/sprites/walkFrames.test.js
index 22017b4b56..61e509991b 100644
--- a/server/services/sprites/walkFrames.test.js
+++ b/server/services/sprites/walkFrames.test.js
@@ -1,7 +1,7 @@
/**
* verifyPackagedFrames (#3001) — the single definition of "this manifest's
* packaged frames are valid", shared by the approve gate (existence-only) and
- * the compile gate (existence + sha256 + gait-phase/order, read once). These
+ * the compile gate (existence + sha256 + content + gait-phase/order, read once). These
* tests assert the two modes agree on resolution and that the compile mode is a
* strict superset: it rejects present-but-tampered frames the approve mode lets
* through, and reads each frame's bytes exactly once.
@@ -14,6 +14,7 @@ import { tmpdir } from 'os';
import { join } from 'path';
import { mkdir, writeFile } from 'fs/promises';
import { createHash } from 'crypto';
+import sharp from 'sharp';
const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-frames-test-'));
@@ -44,6 +45,28 @@ afterAll(() => rmSync(TEST_ROOT, { recursive: true, force: true }));
const sha256 = (buf) => createHash('sha256').update(buf).digest('hex');
+const makeRgbaPng = (pixelAt) => {
+ const side = 32;
+ const raw = Buffer.alloc(side * side * 4);
+ for (let y = 0; y < side; y++) {
+ for (let x = 0; x < side; x++) {
+ raw.set(pixelAt(x, y), (y * side + x) * 4);
+ }
+ }
+ return sharp(raw, { raw: { width: side, height: side, channels: 4 } }).png().toBuffer();
+};
+
+let healthyPngPromise;
+const healthyPng = () => {
+ healthyPngPromise ??= makeRgbaPng((x, y) => {
+ const inSubject = x >= 8 && x < 24 && y >= 8 && y < 24;
+ return inSubject ? [220, 80, 40, 255] : [0, 0, 0, 0];
+ });
+ return healthyPngPromise;
+};
+
+const transparentPng = () => makeRgbaPng(() => [0, 0, 0, 0]);
+
let seq = 0;
const newId = () => `frametest-${++seq}`;
@@ -56,13 +79,15 @@ const newId = () => `frametest-${++seq}`;
*/
async function makeFrames(id, {
count = 8, runId = 'run-abcdef', fileLayout = 'grok', declaredLayout = 'grok', anchored = false, track = 'walk',
+ frameBytes: customFrameBytes = null,
} = {}) {
const labels = track === 'walk'
? walkPhaseLabels(count)
: Array.from({ length: count }, (_, i) => `${track}-${String(i).padStart(2, '0')}`);
+ const defaultFrameBytes = customFrameBytes ? null : await healthyPng();
const frames = [];
for (let i = 0; i < count; i++) {
- const bytes = Buffer.from(`frame-${id}-${i}`);
+ const bytes = customFrameBytes?.[i] ?? defaultFrameBytes;
const fileRel = `${fileLayout}/${runId}/generated/frames/f${i}.png`;
const abs = join(TEST_ROOT, 'sprites', id, fileRel);
await mkdir(join(abs, '..'), { recursive: true }); // eslint-disable-line no-await-in-loop
@@ -137,6 +162,44 @@ describe('verifyPackagedFrames — existence mode (approve gate)', () => {
});
describe('verifyPackagedFrames — byte mode (compile gate)', () => {
+ it('rejects a transparent frame by index and gait phase while approve stays existence-only', async () => {
+ const id = newId();
+ const healthy = await healthyPng();
+ const empty = await transparentPng();
+ const frameBytes = Array(8).fill(healthy);
+ frameBytes[5] = empty;
+ const manifest = await makeFrames(id, { frameBytes });
+
+ await expect(verifyPackagedFrames(id, manifest)).resolves.toMatchObject({ total: 8, missing: 0 });
+ await expect(verifyPackagedFrames(id, manifest, { bytes: true }))
+ .rejects.toMatchObject({
+ status: 422,
+ code: 'ATLAS_COMPILE_INVALID',
+ message: expect.stringContaining(`Direction east frame 5 (${manifest.frames[5].phase}) has no content`),
+ });
+ });
+
+ it('compiles a set when every decoded frame has content', async () => {
+ const id = newId();
+ const healthy = await healthyPng();
+ const manifest = await makeFrames(id, { frameBytes: Array(8).fill(healthy) });
+
+ const result = await verifyPackagedFrames(id, manifest, { bytes: true });
+ expect(result).toMatchObject({ total: 8, missing: 0 });
+ expect(result.frameBytes).toHaveLength(8);
+ });
+
+ it('passes an undecodable frame through without treating the null stats sentinel as degenerate', async () => {
+ const id = newId();
+ const healthy = await healthyPng();
+ const frameBytes = Array(8).fill(healthy);
+ frameBytes[2] = Buffer.from('not an image at all');
+ const manifest = await makeFrames(id, { frameBytes });
+
+ const result = await verifyPackagedFrames(id, manifest, { bytes: true });
+ expect(result.frameBytes[2]).toEqual(frameBytes[2]);
+ });
+
it('returns the verified bytes and reads each frame exactly once', async () => {
const id = newId();
const manifest = await makeFrames(id);
@@ -145,7 +208,7 @@ describe('verifyPackagedFrames — byte mode (compile gate)', () => {
expect(total).toBe(8);
expect(missing).toBe(0);
expect(frameBytes).toHaveLength(8);
- expect(frameBytes[0].toString()).toBe(`frame-${id}-0`);
+ expect(frameBytes[0]).toEqual(await healthyPng());
// Read-once-verify-in-memory: every frame read exactly once, none twice.
const frameReads = readCalls.filter((p) => posixPath(p).includes('/frames/'));
expect(frameReads).toHaveLength(8);