Skip to content

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

refactor: unify packaged-frame validation across approve and compile (#3001)

[._.]/ Adam Eivy3c8ce7d0fbdf
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 4d949e84df..d71357d923 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -13,6 +13,7 @@
## Internal
+- **[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.
- **The Agents page no longer lists macOS's native text-caret helper as a "Cursor" agent** — the running-agents scan matches process names by substring, so `cursor` also matched `CursorUIViewService` — a macOS TextInputUI framework helper (the blinking text caret), not the Cursor AI editor — and it showed up as a running agent. The scan now excludes system framework / XPC-service helpers (paths under `/System/Library/`, `*.framework/`, `*.xpc/`) alongside the existing `.app` bundle exclusion, so only real agent CLIs appear.
- **[issue-2958] Polyfill jsdom `scrollIntoView` in the client test setup** — jsdom doesn't implement `Element.prototype.scrollIntoView`, so a `requestAnimationFrame` callback that calls it (e.g. `Tribe.jsx`, `CmdKSearch.jsx`, and other components) could fire after its test unmounted and turn into an unhandled error that failed the *entire* client suite despite every assertion passing — an intermittent CI flake that forced no-op re-runs on unrelated PRs. `client/src/test/setup.js` now installs a guarded no-op `scrollIntoView` stub alongside the storage polyfill, killing the whole class of flake in one place. Production is unaffected (the stub only fills the jsdom gap).
- **[issue-2951] Image-to-3D target registry (foundation)** — added a pluggable `server/services/imageTo3d/targets.js` registry (mirroring `imageGen/modes.js`) that models image→3D models as selectable targets with hardware-gated availability resolution, TRELLIS.2 registered as the first target, and a read-only `GET /api/image-to-3d/targets` endpoint. Backend groundwork for the forthcoming 3D page under Create (#2952 install/runner, #2953 page/viewer, #2954 CUDA lane); no user-visible surface yet.
diff --git a/server/services/sprites/atlas.js b/server/services/sprites/atlas.js
index d9c1d2c93f..8d7f0ccad1 100644
--- a/server/services/sprites/atlas.js
+++ b/server/services/sprites/atlas.js
@@ -50,6 +50,7 @@ import { ATLAS_IDLE_COLUMN } from './walkBounds.js';
import {
withWalkWriteTail, walkSetRelPath, importedWalkDirections,
} from './walk.js';
+import { verifyPackagedFrames } from './walkFrames.js';
// Player atlas contract (source pipeline runtime_publish.py): 96px cells,
// pivot (48,88) — silhouette centered on x=48, feet on the y=88 ground line —
@@ -304,13 +305,12 @@ export async function validateForCompile(recordId) {
} 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`);
}
- const frameBytes = [];
- for (let i = 0; i < frames.length; i++) {
- if (frames[i].phase !== walkLabels[i] || frames[i].outputIndex !== i) {
- throw compileError(`Direction ${direction} frame ${i} is out of gait-phase order`);
- }
- frameBytes.push(await readVerified(frames[i].path, frames[i].sha256, `Direction ${direction} frame ${frames[i].phase}`));
- }
+ // Same frame-validity definition the approve gate uses (verifyPackagedFrames),
+ // here in its byte-verifying mode: existence + per-frame sha256 + gait-phase/
+ // order, reading each frame's bytes exactly once for read-once-verify-in-memory.
+ // Approve runs the existence-only prefix, so a set that passed approve cannot
+ // fail this for frame-existence reasons (#3001).
+ const { frameBytes } = await verifyPackagedFrames(recordId, manifest, { bytes: true });
runs[direction] = { runId: entry.runId, manifestPath: entry.runManifest, manifest, frameBytes };
}
diff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.js
index 4709b9e5d0..7613d00f92 100644
--- a/server/services/sprites/walk.js
+++ b/server/services/sprites/walk.js
@@ -44,6 +44,7 @@ import {
import {
WALK_TRACK, resolveAnimationTarget, withTrackTarget, targetDrift, describeTargetSource,
} from './animationTargets.js';
+import { verifyPackagedFrames } from './walkFrames.js';
import { GROK_VIDEO_DURATIONS } from '../videoGen/grok.js';
// grok's image_to_video honors only 6s/10s and clamps shorter requests to ~6s,
@@ -1321,17 +1322,15 @@ async function approveWalkDirectionImpl(recordId, { direction, runId }) {
// here (exactly the shape a source-pipeline import has: its manifest was copied,
// its frames/ was not) would sail through the strip check above and surface at
// compile time as an unexplained sha mismatch. Refuse it where the cause is
- // still legible, and name the remedy. A minimal manifest that declares no
- // frames[] is unchanged — the strip sha stays the primary tamper check. (#2993)
- const framePaths = (Array.isArray(packaged.frames) ? packaged.frames : [])
- .map((frame) => toRecordRelativeAssetPath(recordId, frame?.path))
- .filter(Boolean);
- const framesOnDisk = await Promise.all(framePaths
- .map((rel) => pathExists(join(spriteDir(recordId), rel))));
- const missingFrames = framesOnDisk.filter((present) => !present).length;
+ // still legible, and name the remedy. This is the SAME frame-validity definition
+ // the compiler uses (verifyPackagedFrames) run in its existence-only mode, so
+ // the approve gate is a strict prefix of the compile gate and the two can no
+ // longer disagree (#3001). A minimal manifest that declares no frames[] is
+ // unchanged — the strip sha stays the primary tamper check. (#2993)
+ const { total: declaredFrames, missing: missingFrames } = await verifyPackagedFrames(recordId, packaged);
if (missingFrames) {
throw new ServerError(
- `${missingFrames} of this run's ${framePaths.length} packaged frames are missing on disk — reprocess the direction from its source clip to re-derive them before approving.`,
+ `${missingFrames} of this run's ${declaredFrames} packaged frames are missing on disk — reprocess the direction from its source clip to re-derive them before approving.`,
{ status: 409, code: 'RUN_FRAMES_MISSING' },
);
}
diff --git a/server/services/sprites/walkFrames.js b/server/services/sprites/walkFrames.js
new file mode 100644
index 0000000000..a1967164f5
--- /dev/null
+++ b/server/services/sprites/walkFrames.js
@@ -0,0 +1,79 @@
+/**
+ * Sprites — the single definition of "this run manifest's packaged frames are
+ * valid" (issue #3001).
+ *
+ * Approve (walk.js#approveWalkDirectionImpl) and compile
+ * (atlas.js#validateForCompile) both gate on the same artifact — the per-frame
+ * PNGs a packaged walk manifest declares — but used to define validity twice,
+ * with the more permissive approve gate running FIRST. So a direction could
+ * freeze into the set that compile then rejected: the "unexplained failure much
+ * 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.
+ *
+ * Every declared frame is re-anchored to record-relative (an imported manifest
+ * names its frames against the SOURCE repo root) and resolved drift-tolerantly —
+ * the run-layout twin resolution (paths.js#resolveDriftTolerantRel) the clip and
+ * strip resolvers beside it already use. A frame whose path CANNOT be re-anchored
+ * is a real fault counted in the declared total, never silently dropped (which is
+ * how the old approve sweep could understate the count in its error message).
+ *
+ * { 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
+ * 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.
+ */
+
+import { readFile } from 'fs/promises';
+import { ServerError } from '../../lib/errorHandler.js';
+import {
+ spriteDir, resolveSpriteAssetPath, toRecordRelativeAssetPath, resolveDriftTolerantRel,
+} from './paths.js';
+import { sha256Buffer } from './walkPostprocess.js';
+import { walkPhaseLabels } from './walkBounds.js';
+
+const compileFrameError = (message) =>
+ new ServerError(message, { status: 422, code: 'ATLAS_COMPILE_INVALID' });
+
+export async function verifyPackagedFrames(recordId, manifest, { bytes = false } = {}) {
+ const dir = spriteDir(recordId);
+ const frames = Array.isArray(manifest?.frames) ? manifest.frames : [];
+ const total = frames.length;
+ // Compile checks each frame's gait-phase against the set's phase labels. The
+ // set's frame count is enforced identical across directions before this runs
+ // (atlas.js), so labels derived from THIS manifest's length match the set's.
+ const labels = bytes ? walkPhaseLabels(total) : null;
+ const frameBytes = bytes ? [] : null;
+ let missing = 0;
+
+ for (let i = 0; i < total; i++) {
+ const frame = frames[i];
+ // Re-anchor drift-tolerantly, matching the clip/strip resolvers. A path that
+ // cannot be re-anchored (rel === null) is a fault, counted in `total`.
+ const rel = toRecordRelativeAssetPath(recordId, frame?.path);
+ // eslint-disable-next-line no-await-in-loop -- per-frame verification is ordered (read-once, in gait-phase sequence)
+ const found = rel ? await resolveDriftTolerantRel(dir, rel) : null;
+ if (!found) {
+ if (!bytes) { missing += 1; continue; }
+ throw compileFrameError(`Direction ${manifest?.direction} frame ${i} image is missing on disk`);
+ }
+ if (!bytes) continue;
+ // Compile-only: gait-phase/order, then read-once-verify-in-memory.
+ if (frame.phase !== labels[i] || frame.outputIndex !== i) {
+ throw compileFrameError(`Direction ${manifest?.direction} frame ${i} is out of gait-phase order`);
+ }
+ // eslint-disable-next-line no-await-in-loop -- see above; each frame read exactly once for verify-in-memory
+ const buf = await readFile(resolveSpriteAssetPath(recordId, found));
+ if (sha256Buffer(buf) !== frame.sha256) {
+ throw compileFrameError(`Direction ${manifest?.direction} frame ${frame.phase} no longer matches its recorded sha256`);
+ }
+ frameBytes.push(buf);
+ }
+
+ return { total, missing, frameBytes };
+}
diff --git a/server/services/sprites/walkFrames.test.js b/server/services/sprites/walkFrames.test.js
new file mode 100644
index 0000000000..bc15b64813
--- /dev/null
+++ b/server/services/sprites/walkFrames.test.js
@@ -0,0 +1,173 @@
+/**
+ * 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
+ * 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.
+ */
+
+import { describe, it, expect, vi, afterAll } from 'vitest';
+import { mkdtempSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { mkdir, writeFile } from 'fs/promises';
+import { createHash } from 'crypto';
+
+const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-frames-test-'));
+
+vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ Object.assign(actual.PATHS, {
+ data: TEST_ROOT,
+ sprites: join(TEST_ROOT, 'sprites'),
+ });
+ return actual;
+});
+
+// Count every fs/promises readFile so the compile mode's read-once-verify
+// property can be asserted directly. mkdir/writeFile stay real (spread through).
+const { readCalls } = vi.hoisted(() => ({ readCalls: [] }));
+vi.mock('fs/promises', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ readFile: (path, ...rest) => { readCalls.push(String(path)); return actual.readFile(path, ...rest); },
+ };
+});
+
+const { verifyPackagedFrames } = await import('./walkFrames.js');
+const { walkPhaseLabels } = await import('./walkBounds.js');
+
+afterAll(() => rmSync(TEST_ROOT, { recursive: true, force: true }));
+
+const sha256 = (buf) => createHash('sha256').update(buf).digest('hex');
+
+let seq = 0;
+const newId = () => `frametest-${++seq}`;
+
+/**
+ * Write `count` frame PNGs under `<id>/<layout>/<runId>/generated/frames/` and
+ * return a manifest whose frames[] declares them, hash-pinned in gait-phase
+ * order. `declaredLayout` lets the manifest name a different run-dir spelling
+ * than the files live under (drift), and `anchored` prefixes the source repo
+ * root so re-anchoring is exercised.
+ */
+async function makeFrames(id, {
+ count = 8, runId = 'run-abcdef', fileLayout = 'grok', declaredLayout = 'grok', anchored = false,
+} = {}) {
+ const labels = walkPhaseLabels(count);
+ const frames = [];
+ for (let i = 0; i < count; i++) {
+ const bytes = Buffer.from(`frame-${id}-${i}`);
+ 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
+ await writeFile(abs, bytes); // eslint-disable-line no-await-in-loop
+ const declaredRel = `${declaredLayout}/${runId}/generated/frames/f${i}.png`;
+ frames.push({
+ outputIndex: i,
+ phase: labels[i],
+ path: anchored ? `art-source/sprites/${id}/${declaredRel}` : declaredRel,
+ sha256: sha256(bytes),
+ });
+ }
+ return { direction: 'east', characterId: id, frameCount: count, frames };
+}
+
+describe('verifyPackagedFrames — existence mode (approve gate)', () => {
+ it('passes when every declared frame is on disk', async () => {
+ const id = newId();
+ const manifest = await makeFrames(id);
+ const { total, missing } = await verifyPackagedFrames(id, manifest);
+ expect(total).toBe(8);
+ expect(missing).toBe(0);
+ });
+
+ it('counts an absent frame as missing without changing the declared total', async () => {
+ const id = newId();
+ const manifest = await makeFrames(id);
+ manifest.frames[2].path = manifest.frames[2].path.replace('f2.png', 'gone.png');
+ const { total, missing } = await verifyPackagedFrames(id, manifest);
+ expect(total).toBe(8);
+ expect(missing).toBe(1);
+ });
+
+ it('resolves frame paths drift-tolerantly (declared runs/, stored grok/)', async () => {
+ const id = newId();
+ const manifest = await makeFrames(id, { fileLayout: 'grok', declaredLayout: 'runs' });
+ const { total, missing } = await verifyPackagedFrames(id, manifest);
+ expect(total).toBe(8);
+ expect(missing).toBe(0);
+ });
+
+ it('re-anchors a source-repo-anchored frame path before resolving', async () => {
+ const id = newId();
+ const manifest = await makeFrames(id, { anchored: true });
+ const { total, missing } = await verifyPackagedFrames(id, manifest);
+ expect(total).toBe(8);
+ expect(missing).toBe(0);
+ });
+
+ it('reports an un-re-anchorable frame path as a failure, not a silent drop', async () => {
+ const id = newId();
+ const manifest = await makeFrames(id);
+ // A foreign repo-anchored path toRecordRelativeAssetPath returns null for.
+ manifest.frames[5].path = 'art-pipeline/scripts/whatever.png';
+ const { total, missing } = await verifyPackagedFrames(id, manifest);
+ expect(total).toBe(8); // still counted in the declared total
+ expect(missing).toBe(1);
+ });
+
+ it('treats a manifest with no frames[] as valid (strip sha stays primary)', async () => {
+ const id = newId();
+ const { total, missing } = await verifyPackagedFrames(id, { direction: 'east' });
+ expect(total).toBe(0);
+ expect(missing).toBe(0);
+ });
+});
+
+describe('verifyPackagedFrames — byte mode (compile gate)', () => {
+ it('returns the verified bytes and reads each frame exactly once', async () => {
+ const id = newId();
+ const manifest = await makeFrames(id);
+ readCalls.length = 0;
+ const { total, missing, frameBytes } = await verifyPackagedFrames(id, manifest, { bytes: true });
+ expect(total).toBe(8);
+ expect(missing).toBe(0);
+ expect(frameBytes).toHaveLength(8);
+ expect(frameBytes[0].toString()).toBe(`frame-${id}-0`);
+ // Read-once-verify-in-memory: every frame read exactly once, none twice.
+ const frameReads = readCalls.filter((p) => p.includes('/frames/'));
+ expect(frameReads).toHaveLength(8);
+ expect(new Set(frameReads).size).toBe(8);
+ });
+
+ it('rejects a present-but-tampered frame (sha mismatch, not just absent)', async () => {
+ const id = newId();
+ const manifest = await makeFrames(id);
+ // The file exists (so the approve/existence gate passes) but its recorded
+ // sha no longer matches its bytes — only the byte mode catches it.
+ const existence = await verifyPackagedFrames(id, manifest);
+ expect(existence.missing).toBe(0);
+ manifest.frames[3].sha256 = 'deadbeef';
+ await expect(verifyPackagedFrames(id, manifest, { bytes: true }))
+ .rejects.toMatchObject({ status: 422, code: 'ATLAS_COMPILE_INVALID' });
+ });
+
+ it('rejects a frame out of gait-phase order', async () => {
+ const id = newId();
+ const manifest = await makeFrames(id);
+ manifest.frames[4].outputIndex = 99;
+ await expect(verifyPackagedFrames(id, manifest, { bytes: true }))
+ .rejects.toMatchObject({ status: 422, code: 'ATLAS_COMPILE_INVALID' });
+ });
+
+ it('rejects a missing frame with a compile error', async () => {
+ const id = newId();
+ const manifest = await makeFrames(id);
+ manifest.frames[1].path = manifest.frames[1].path.replace('f1.png', 'gone.png');
+ await expect(verifyPackagedFrames(id, manifest, { bytes: true }))
+ .rejects.toMatchObject({ status: 422, code: 'ATLAS_COMPILE_INVALID' });
+ });
+});