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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-2898]): compile the immutable runtime atlas and publish it into a managed game app
[._.]/ Adam Eivy7552ca088123
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 6c4db76c5a..1c687e3645 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -6,6 +6,7 @@## Sprite Manager+- **[issue-2898] Compile the runtime atlas and publish it to your game (phase 4)** — a finalized walk set can now be compiled into the immutable runtime sprite-sheet (the 10×8 grid of idle, the 8 named gait phases, and a scanner placeholder for all 8 directions, each frame scaled once per direction and pinned to the pivot ground line) and published straight into a managed app's repository. Every compile revalidates the whole evidence chain first — the finalized walk set, every packaged frame, and every locked anchor are checksum-verified — and recompiling the same set is a no-op instead of a new version. Publishing binds a character to a managed app and a repo-relative destination, replaces the atlas atomically, and refuses to clobber a destination that changed outside PortOS since the last publish; an optional code-binding guard verifies (occurrence-counted) that the game source still references the atlas where expected before anything is written. The Sprites tab gains the compile/publish panel with an inline confirmation and a publish history, and sprite walk-run raw frame intermediates are now excluded from backups by default (they regenerate deterministically from the archived source video — the toggle to re-include them is in the Backup tab).- **[issue-2897] Animate walk cycles from locked anchors (phase 3)** — each locked directional anchor can now be animated: PortOS asks Grok for exactly one walk-in-place video on the character's key-color matte, then packages it locally and deterministically — no further AI involved — into the canonical 8-phase walk strip (frame extraction, chroma un-key and de-spill keyed to the character's selected key color, automatic walk-cycle detection, fixed-scale pivot alignment, and a light/dark/checker contrast review sheet). Review each direction's loop right in the Sprites tab (animated preview), optionally trim frames non-destructively into a versioned loop GIF, and approve per direction; the eighth approval freezes the finalized walk set, which becomes immutable like the reference set. Every run carries a full provenance manifest with per-frame checksums, matching the format the phase-1 importer already understands.- **[issue-2896] Create characters and build their reference sets with AI (phase 2)** — the Sprites tab can now create a character from a name plus a text description and/or an uploaded design image, generate main-reference candidates through your configured image backend (Codex, Grok, or local), and freeze the approved candidate as the character's immutable identity root. From the frozen main you then derive the 8 directional anchors (front/back/profiles/three-quarters), review each candidate, and lock the set. On lock, PortOS normalizes the art onto a clean key-color square and auto-picks the best chroma key for that character — magenta, green, or blue, whichever sits farthest from the character's own colors (with a manual override limited to the same three keys, and a warning when every key risks clipping). Locked references are server-side immutable: regeneration and replacement are refused, corrections always land as new versions.- **[issue-2895] Media Gen gains a Sprites section (phase 1: library + import)** — a new Sprites tab lists your game-sprite characters and prop atlas families, browses each one's locked reference set, walk-cycle strips, and published atlas versions (with pixel-perfect previews), and imports the approved production assets from an existing sprite-pipeline checkout in one click. Only final/approved artifacts import — rejected candidates and raw video intermediates stay behind — and every file the source manifests hash-pin is verified on the way in. Reachable from ⌘K and voice ("take me to sprites"). Generation (reference → anchors → walk videos → publish-to-game) lands in the follow-up phases.diff --git a/client/src/components/sprites/PublishWorkflow.jsx b/client/src/components/sprites/PublishWorkflow.jsxnew file mode 100644index 0000000000..c457614e8d--- /dev/null+++ b/client/src/components/sprites/PublishWorkflow.jsx@@ -0,0 +1,192 @@+import { useEffect, useState } from 'react';+import { Package, Rocket, RefreshCw } from 'lucide-react';+import {+ compileSpriteAtlas, setSpritePublishBinding, publishSpriteAtlas,+} from '../../services/apiSprites.js';+import { getApps } from '../../services/apiApps.js';+import { useAsyncAction } from '../../hooks/useAsyncAction.js';+import { spriteAssetUrl } from './spriteAssets.js';+import { timeAgo } from '../../utils/formatters.js';++// Publish workflow (issue #2898): compile the immutable runtime atlas from+// the finalized walk set, bind a managed app + repo-relative destination,+// and publish (atomic replace, divergence-refusing) into the game repo.+// Appears only once the walk set is finalized — the compile input.++function Field({ label, children }) {+ return (+ <label className="block text-xs text-gray-400">+ <span className="block mb-1">{label}</span>+ {children}+ </label>+ );+}++const inputClass = 'w-full px-2 py-1 text-xs bg-port-bg border border-port-border rounded text-gray-200 focus:border-port-accent focus:outline-none';++export default function PublishWorkflow({ record, walk, atlas, onChanged }) {+ const finalized = Boolean(walk?.walkSet);+ const current = atlas?.current || null;+ const publications = atlas?.publications || [];+ const saved = record.publishBinding || null;++ const [apps, setApps] = useState([]);+ const [appId, setAppId] = useState(saved?.appId || '');+ const [destPath, setDestPath] = useState(saved?.atlasDestPath || '');+ const [codePath, setCodePath] = useState(saved?.codeBinding?.path || '');+ const [resourcePath, setResourcePath] = useState(saved?.codeBinding?.resourcePath || '');+ const [confirming, setConfirming] = useState(false);++ useEffect(() => {+ if (!finalized) return;+ getApps({ silent: true })+ .then((list) => setApps((Array.isArray(list) ? list : []).filter((a) => !a.archived)))+ .catch(() => {});+ }, [finalized]);++ // Re-seed the form when the server-side binding changes (save round-trip).+ useEffect(() => {+ setAppId(saved?.appId || '');+ setDestPath(saved?.atlasDestPath || '');+ setCodePath(saved?.codeBinding?.path || '');+ setResourcePath(saved?.codeBinding?.resourcePath || '');+ }, [saved?.appId, saved?.atlasDestPath, saved?.codeBinding?.path, saved?.codeBinding?.resourcePath]);++ const [compile, compiling] = useAsyncAction(async () => {+ const result = await compileSpriteAtlas(record.id, {}, { silent: true });+ onChanged?.();+ return result;+ }, { errorMessage: 'Atlas compile failed' });++ const [saveBinding, savingBinding] = useAsyncAction(async () => {+ const binding = appId && destPath+ ? {+ appId,+ atlasDestPath: destPath.trim(),+ codeBinding: codePath.trim() && resourcePath.trim()+ ? { path: codePath.trim(), resourcePath: resourcePath.trim() }+ : null,+ }+ : null;+ const result = await setSpritePublishBinding(record.id, binding, { silent: true });+ onChanged?.();+ return result;+ }, { errorMessage: 'Could not save the publish binding' });++ const [publish, publishing] = useAsyncAction(async () => {+ setConfirming(false);+ const result = await publishSpriteAtlas(record.id, { silent: true });+ onChanged?.();+ return result;+ }, { errorMessage: 'Publish failed' });++ if (!finalized) return null;++ const bindingDirty = (saved?.appId || '') !== appId+ || (saved?.atlasDestPath || '') !== destPath.trim()+ || (saved?.codeBinding?.path || '') !== codePath.trim()+ || (saved?.codeBinding?.resourcePath || '') !== resourcePath.trim();+ // Publish reads the SAVED binding server-side — gate on it, and hold while+ // a binding save is in flight so a click can't race the PUT.+ const canPublish = Boolean(saved?.appId && saved?.atlasDestPath) && !bindingDirty && !savingBinding && !publishing;+ const boundApp = apps.find((a) => a.id === saved?.appId);++ return (+ <div className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">+ <div className="flex items-center justify-between gap-2 flex-wrap">+ <h3 className="text-sm font-medium text-gray-200 flex items-center gap-2">+ <Package size={16} className="text-port-accent" /> Runtime Atlas+ </h3>+ <span className="text-[10px] px-2 py-0.5 rounded bg-port-bg border border-port-border text-gray-400">+ {current ? `v${current.version} · ${timeAgo(current.compiledAt)}` : 'not compiled'}+ </span>+ </div>++ <div className="flex flex-col sm:flex-row gap-3">+ <div className="space-y-2">+ {current && (+ <img+ src={spriteAssetUrl(record.id, current.atlasPath)}+ alt="compiled runtime atlas"+ className="w-full sm:w-60 object-contain bg-port-bg border border-port-border rounded"+ style={{ imageRendering: 'pixelated' }}+ />+ )}+ <button+ onClick={compile}+ disabled={compiling}+ className="flex items-center gap-1 px-2 py-1 text-xs bg-port-bg border border-port-border rounded text-gray-300 hover:border-port-accent disabled:opacity-50"+ >+ <RefreshCw size={12} className={compiling ? 'animate-spin' : ''} />+ {current ? 'Recompile atlas' : 'Compile atlas'}+ </button>+ </div>++ <div className="flex-1 space-y-2 min-w-0">+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">+ <Field label="Managed app">+ <select value={appId} onChange={(e) => setAppId(e.target.value)} className={inputClass}>+ <option value="">— none —</option>+ {apps.map((app) => <option key={app.id} value={app.id}>{app.name}</option>)}+ </select>+ </Field>+ <Field label="Atlas destination (repo-relative .png)">+ <input value={destPath} onChange={(e) => setDestPath(e.target.value)} placeholder="assets/sprites/hero/hero-atlas.png" className={inputClass} />+ </Field>+ <Field label="Code binding file (optional)">+ <input value={codePath} onChange={(e) => setCodePath(e.target.value)} placeholder="src/Hero.cs" className={inputClass} />+ </Field>+ <Field label="Resource path in code (optional)">+ <input value={resourcePath} onChange={(e) => setResourcePath(e.target.value)} placeholder="res://assets/sprites/hero/hero-atlas.png" className={inputClass} />+ </Field>+ </div>+ <div className="flex items-center gap-2 flex-wrap">+ <button+ onClick={saveBinding}+ disabled={savingBinding || !bindingDirty}+ className="px-2 py-1 text-xs bg-port-bg border border-port-border rounded text-gray-300 hover:border-port-accent disabled:opacity-50"+ >+ {savingBinding ? 'Saving…' : 'Save binding'}+ </button>+ {!confirming ? (+ <button+ onClick={() => setConfirming(true)}+ disabled={!canPublish}+ title={bindingDirty ? 'Save the binding first' : undefined}+ className="flex items-center gap-1 px-2 py-1 text-xs bg-port-accent/20 border border-port-accent rounded text-port-accent hover:bg-port-accent/30 disabled:opacity-50"+ >+ <Rocket size={12} /> Publish to app+ </button>+ ) : (+ <span className="flex items-center gap-2 text-xs text-gray-300">+ Replace <code className="text-port-warning">{saved?.atlasDestPath}</code> in {boundApp?.name || saved?.appId}?+ <button onClick={publish} disabled={publishing} className="px-2 py-0.5 text-xs bg-port-error/20 border border-port-error rounded text-port-error hover:bg-port-error/30 disabled:opacity-50">+ {publishing ? 'Publishing…' : 'Confirm'}+ </button>+ <button onClick={() => setConfirming(false)} className="px-2 py-0.5 text-xs bg-port-bg border border-port-border rounded text-gray-400 hover:border-port-accent">+ Cancel+ </button>+ </span>+ )}+ </div>+ </div>+ </div>++ {publications.length > 0 && (+ <div className="space-y-1">+ <h4 className="text-xs font-medium text-gray-400">Publish history</h4>+ <ul className="space-y-0.5">+ {publications.map((p) => (+ <li key={p.publishedAt} className="text-[11px] text-gray-500 flex items-center gap-2 flex-wrap">+ <span className="text-gray-300">v{p.version}</span>+ <span>→ {p.appName || p.appId}:{p.atlasDestPath}</span>+ {p.codeBinding?.rewritten && <span className="text-port-warning">code binding rewritten</span>}+ <span>{timeAgo(p.publishedAt)}</span>+ </li>+ ))}+ </ul>+ </div>+ )}+ </div>+ );+}diff --git a/client/src/pages/Sprites.jsx b/client/src/pages/Sprites.jsxindex e6d0abf681..07f3da1b5a 100644--- a/client/src/pages/Sprites.jsx+++ b/client/src/pages/Sprites.jsx@@ -5,6 +5,7 @@ import toast from '../components/ui/Toast';import { listSpriteRecords, getSpriteRecord, importSprites, createSpriteRecord } from '../services/apiSprites.js';import ReferenceWorkflow from '../components/sprites/ReferenceWorkflow.jsx';import WalkWorkflow from '../components/sprites/WalkWorkflow.jsx';+import PublishWorkflow from '../components/sprites/PublishWorkflow.jsx';import { spriteAssetUrl } from '../components/sprites/spriteAssets.js';import { useAsyncAction } from '../hooks/useAsyncAction.js';import { formatBytes, timeAgo } from '../utils/formatters.js';@@ -386,6 +387,12 @@ export default function Sprites() {walk={detail.walk}onChanged={onWorkflowChanged}/>+ <PublishWorkflow+ record={detail.record}+ walk={detail.walk}+ atlas={detail.atlas}+ onChanged={onWorkflowChanged}+ /></>)}{detail.assets.length === 0 ? (diff --git a/client/src/services/apiSprites.js b/client/src/services/apiSprites.jsindex af1f93f9b7..060ff8427f 100644--- a/client/src/services/apiSprites.js+++ b/client/src/services/apiSprites.js@@ -70,3 +70,22 @@ export const postprocessSpriteWalk = (id, body, options = {}) => request(`/spritexport const trimSpriteWalk = (id, body, options = {}) => request(`/sprites/${encodeURIComponent(id)}/walk/trim`, {method: 'POST', body: JSON.stringify(body), ...options,});++// Phase 4 (#2898): runtime atlas compile + publish into a managed app.++// Compile (idempotently) the immutable runtime atlas from the finalized walk+// set. Returns the current pointer ({ version, atlasPath, atlasSha256, ... }+// plus created).+export const compileSpriteAtlas = (id, body = {}, options = {}) => request(`/sprites/${encodeURIComponent(id)}/atlas/compile`, {+ method: 'POST', body: JSON.stringify(body), ...options,+});++// Set (binding object) or clear (null) the record's publish binding.+export const setSpritePublishBinding = (id, binding, options = {}) => request(`/sprites/${encodeURIComponent(id)}/publish-binding`, {+ method: 'PUT', body: JSON.stringify({ binding }), ...options,+});++// Publish the compiled atlas into the bound managed app's repo.+export const publishSpriteAtlas = (id, options = {}) => request(`/sprites/${encodeURIComponent(id)}/atlas/publish`, {+ method: 'POST', body: JSON.stringify({}), ...options,+});diff --git a/server/lib/validation.js b/server/lib/validation.jsindex d3b8f2b2a5..a4cdd4c23c 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -974,6 +974,35 @@ export const spriteRecordUpdateSchema = z.object({chromaKey: z.enum(CHROMA_KEY_HEXES).nullable().optional(),});+// Phase 4 (issue #2898): publish binding — the shape check only; app+// existence and repo path anchoring are the publish service's job (they need+// filesystem + apps access). Repo-relative paths, no traversal, no absolutes.+const spriteRepoRelativePath = z.string().min(1).max(1024)+ .refine((p) => !p.startsWith('/') && !p.includes('\\') && !p.split('/').includes('..'), {+ message: 'must be a repo-relative path with no traversal',+ });++export const spritePublishBindingSchema = z.object({+ appId: z.string().min(1).max(200),+ atlasDestPath: spriteRepoRelativePath,+ codeBinding: z.object({+ path: spriteRepoRelativePath,+ resourcePath: z.string().min(1).max(1024),+ requiredOccurrenceCount: z.number().int().min(1).max(1000).optional(),+ }).nullable().optional(),+}).nullable();++// Optional per-compile geometry overrides (player default: 96px cells,+// pivot (48,88), 86×74 content bounds). Columns/rows are the fixed contract.+export const spriteAtlasCompileSchema = z.object({+ geometry: z.object({+ cellSize: z.number().int().min(16).max(1024).optional(),+ pivot: z.tuple([z.number().int().min(0), z.number().int().min(0)]).optional(),+ targetMaxHeight: z.number().int().min(8).max(1024).optional(),+ targetMaxWidth: z.number().int().min(8).max(1024).optional(),+ }).optional(),+});+// Phase 2 (issue #2896): reference workflow. prompts.js / chromaKey.js are// pure sprite modules (like recordsLogic.js) so importing their constants// here can't disturb mocked suites; modes.js is the dependency-free image-gendiff --git a/server/routes/sprites.js b/server/routes/sprites.jsindex 0660e9a25e..7102ecd65c 100644--- a/server/routes/sprites.js+++ b/server/routes/sprites.js@@ -23,7 +23,10 @@ import {spriteWalkApproveSchema,spriteWalkPostprocessSchema,spriteWalkTrimSchema,+ spritePublishBindingSchema,+ spriteAtlasCompileSchema,} from '../lib/validation.js';+import { z } from 'zod';import { optionalUploadFields } from '../lib/multipart.js';import {listRecords, getRecordWithAssets, createCharacter, deleteRecord,@@ -36,6 +39,8 @@ import {getWalkState, startWalkGeneration, approveWalkDirection, rerunWalkPostprocess,} from '../services/sprites/walk.js';import { saveLoopTrim } from '../services/sprites/walkTrims.js';+import { compileAtlas, getAtlasState } from '../services/sprites/atlas.js';+import { setPublishBinding, publishAtlas } from '../services/sprites/publish.js';const router = Router();@@ -72,9 +77,14 @@ router.get('/:id', asyncHandler(async (req, res) => {const detail = await getRecordWithAssets(req.params.id);if (!detail) throw new ServerError('Sprite record not found', { status: 404, code: 'NOT_FOUND' });const isCharacter = detail.record.kind === 'character';- const reference = isCharacter ? await getReferenceSet(req.params.id) : null;- const walk = isCharacter ? await getWalkState(req.params.id) : null;- res.json({ ...detail, reference, walk });+ const [reference, walk, atlas] = isCharacter+ ? await Promise.all([+ getReferenceSet(req.params.id),+ getWalkState(req.params.id),+ getAtlasState(req.params.id),+ ])+ : [null, null, null];+ res.json({ ...detail, reference, walk, atlas });}));// Queue one reference candidate render (main or a directional anchor).@@ -131,6 +141,26 @@ router.post('/:id/walk/trim', asyncHandler(async (req, res) => {res.status(201).json(await saveLoopTrim(req.params.id, body));}));+// Phase 4 (#2898): atlas compile + publish-to-managed-app. Compile is+// deterministic local work (no AI call); publish additionally requires a+// configured binding and is the only path that writes outside data/.+router.post('/:id/atlas/compile', asyncHandler(async (req, res) => {+ const body = validateRequest(spriteAtlasCompileSchema, req.body ?? {});+ res.json(await compileAtlas(req.params.id, body));+}));++// Set (or clear, with binding: null) the publish binding. App existence and+// path anchoring are validated here so a bad binding fails at save time, not+// at publish time.+router.put('/:id/publish-binding', asyncHandler(async (req, res) => {+ const { binding } = validateRequest(z.object({ binding: spritePublishBindingSchema }), req.body);+ res.json(await setPublishBinding(req.params.id, binding));+}));++router.post('/:id/atlas/publish', asyncHandler(async (req, res) => {+ res.json(await publishAtlas(req.params.id));+}));+// Chroma-key changes route through patchSpriteRecord, which re-checks the// lock state inside the same per-record write tail as `/reference/lock`// (409 CHROMA_KEY_LOCKED after the main freezes).diff --git a/server/routes/sprites.test.js b/server/routes/sprites.test.jsindex 8ba8de4063..018d11cbe5 100644--- a/server/routes/sprites.test.js+++ b/server/routes/sprites.test.js@@ -32,11 +32,23 @@ vi.mock('../services/sprites/walkTrims.js', () => ({saveLoopTrim: vi.fn(async () => ({ strip: 'walk/trims/t-v001-strip.png', loop: 'walk/trims/t-v001.gif', manifest: 'walk/trims/t-v001.json', frameCount: 3, disabledFrameCount: 1 })),}));+vi.mock('../services/sprites/atlas.js', () => ({+ compileAtlas: vi.fn(async () => ({ created: true, version: 1, atlasPath: 'runtime/v1/pioneer-animation-atlas-v1.png' })),+ getAtlasState: vi.fn(async () => ({ current: null, publications: [] })),+}));++vi.mock('../services/sprites/publish.js', () => ({+ setPublishBinding: vi.fn(async (id, binding) => ({ id, publishBinding: binding })),+ publishAtlas: vi.fn(async () => ({ published: true, publication: { version: 1 } })),+}));+import * as records from '../services/sprites/records.js';import * as importer from '../services/sprites/importer.js';import * as reference from '../services/sprites/reference.js';import * as walk from '../services/sprites/walk.js';import * as walkTrims from '../services/sprites/walkTrims.js';+import * as atlas from '../services/sprites/atlas.js';+import * as publish from '../services/sprites/publish.js';import { errorMiddleware } from '../lib/errorHandler.js';import spriteRoutes from './sprites.js';@@ -294,4 +306,44 @@ describe('sprites routes', () => {.send({ runId: '../escape', enabledColumns: [0, 2] })).status).toBe(400);expect(walkTrims.saveLoopTrim).toHaveBeenCalledOnce();});++ it('POST /:id/atlas/compile validates and delegates (geometry optional)', async () => {+ const r = await request(app).post('/api/sprites/pioneer/atlas/compile').send({});+ expect(r.status).toBe(200);+ expect(atlas.compileAtlas).toHaveBeenCalledWith('pioneer', {});++ const withGeometry = { geometry: { cellSize: 64, pivot: [32, 56] } };+ await request(app).post('/api/sprites/pioneer/atlas/compile').send(withGeometry);+ expect(atlas.compileAtlas).toHaveBeenLastCalledWith('pioneer', withGeometry);++ expect((await request(app).post('/api/sprites/pioneer/atlas/compile')+ .send({ geometry: { cellSize: 4 } })).status).toBe(400);+ });++ it('PUT /:id/publish-binding validates the binding shape and delegates', async () => {+ const binding = { appId: 'game-app', atlasDestPath: 'assets/sprites/hero/atlas.png' };+ const r = await request(app).put('/api/sprites/pioneer/publish-binding').send({ binding });+ expect(r.status).toBe(200);+ expect(publish.setPublishBinding).toHaveBeenCalledWith('pioneer', binding);++ // null clears the binding+ await request(app).put('/api/sprites/pioneer/publish-binding').send({ binding: null });+ expect(publish.setPublishBinding).toHaveBeenLastCalledWith('pioneer', null);++ // traversal / absolute destinations die at the schema+ expect((await request(app).put('/api/sprites/pioneer/publish-binding')+ .send({ binding: { ...binding, atlasDestPath: '../escape.png' } })).status).toBe(400);+ expect((await request(app).put('/api/sprites/pioneer/publish-binding')+ .send({ binding: { ...binding, atlasDestPath: '/abs.png' } })).status).toBe(400);+ expect((await request(app).put('/api/sprites/pioneer/publish-binding')+ .send({ binding: { ...binding, codeBinding: { path: 'src/Hero.cs', resourcePath: '' } } })).status).toBe(400);+ expect(publish.setPublishBinding).toHaveBeenCalledTimes(2);+ });++ it('POST /:id/atlas/publish delegates to publishAtlas', async () => {+ const r = await request(app).post('/api/sprites/pioneer/atlas/publish').send({});+ expect(r.status).toBe(200);+ expect(publish.publishAtlas).toHaveBeenCalledWith('pioneer');+ expect(r.body.published).toBe(true);+ });});diff --git a/server/services/backup.js b/server/services/backup.jsindex c6539010c3..173a14afbd 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -60,7 +60,14 @@ export const DEFAULT_EXCLUDES = [{ path: '/training-runs/*/data/.mflux_cache/', reason: 'mflux low_ram disk-backed encode cache (written inside the staged training data dir) — regenerable', overridable: false },{ path: '/repos/', reason: 'Cloned git repositories — large, re-cloneable from origin', overridable: true },{ path: '/cos/reference-repos/', reason: 'Reference upstream repos used by agents — re-cloneable', overridable: true },- { path: '/browser-downloads/', reason: 'Browser downloads cache — large, re-downloadable', overridable: true }+ { path: '/browser-downloads/', reason: 'Browser downloads cache — large, re-downloadable', overridable: true },+ // Sprite animation-run raw intermediates: 30–96 ffmpeg-extracted PNGs per+ // run, byte-for-byte regenerable from the archived source video by the+ // deterministic postprocess (walkPostprocess.js). The source video, packaged+ // frames, strips, manifests, and runtime atlases ARE backed up. `grok/` is+ // the live layout; `runs/` covers imported legacy runs.+ { path: '/sprites/*/grok/*/generated/raw/', reason: 'Sprite walk-run raw extracted frames — regenerable from the archived source video', overridable: true },+ { path: '/sprites/*/runs/*/generated/raw/', reason: 'Imported sprite-run raw extracted frames — regenerable from the archived source video', overridable: true }// NOTE: legacy file→Postgres migration artifacts (`.imported` / `.bak-NNN`)// are intentionally NOT excluded here. They are deleted on disk by the// boot-time prune (pruneImportedLegacyFiles.js) the same boot the migrationdiff --git a/server/services/sprites/atlas.js b/server/services/sprites/atlas.jsnew file mode 100644index 0000000000..b6c3c46f75--- /dev/null+++ b/server/services/sprites/atlas.js@@ -0,0 +1,481 @@+/**+ * Sprites — runtime atlas compiler (issue #2898, phase 4).+ *+ * Compiles the immutable runtime sprite-sheet from a finalized eight-direction+ * walk set: a 10-column × 8-row grid (idle, the 8 named gait phases, scanner ×+ * S/SE/E/NE/N/NW/W/SW) of fixed-size cells, each frame scaled once per+ * direction and translated so its silhouette centers on the pivot x and its+ * feet land exactly on the pivot ground line. Ports the source pipeline's+ * `runtime_publish.py` compile stage; all math preserves Python semantics+ * (banker's rounding via pyRound, exclusive-bbox bounds) so cell placement+ * matches the production atlases the importer brought over.+ *+ * Every input is revalidated before any pixel work: walk-set kind/status/+ * direction order, the selection + per-direction run-manifest sha256s, every+ * packaged frame's sha256, and the locked reference set's anchor sha256s. A+ * failed hash means the evidence chain is broken — compile refuses rather+ * than compiling from tampered bytes.+ *+ * Output is immutable-by-version under data/sprites/<id>/runtime/vN/+ * (a differing byte-write to an existing version path is refused), with a+ * mutable current.json pointer. Recompiling the same finalized set is+ * idempotent: identical bytes → the existing version is returned untouched.+ */++import { join } from 'path';+import { readdir } from 'fs/promises';+import { createHash } from 'crypto';+import sharp from 'sharp';+import {+ atomicWrite, ensureDir, pathExists, readJSONFile, sha256File, tryReadFile,+} from '../../lib/fileUtils.js';+import { ServerError } from '../../lib/errorHandler.js';+import { spriteDir } from './paths.js';+import { requireCharacter, loadManifest } from './reference.js';+import { SPRITE_DIRECTIONS } from './prompts.js';+import { keyChannelSplit } from './chromaKey.js';+import {+ WALK_PHASES, pyRound, pyRoundTo, median, decodeRgbaFrame, premultipliedResize,+ sampleBorderKey, validateMeasuredKey, recoverAlphaFrame, despillKeyFrame,+} from './walkPostprocess.js';+import { withWalkWriteTail } from './walk.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 —+// content bounded to 86×74 so nothing touches a cell edge.+export const ATLAS_COLUMNS = ['idle', ...WALK_PHASES, 'scanner'];+export const DEFAULT_ATLAS_GEOMETRY = {+ cellSize: 96,+ pivot: [48, 88],+ targetMaxHeight: 74,+ targetMaxWidth: 86,+};++// Silhouette-visibility alpha thresholds (exclusive bbox at alpha > N).+// Walk frames measure at 8; the idle anchor measures at 64 so chroma-key+// recovery noise can't inflate the character and shrink its scale.+const ALPHA_THRESHOLD = 8;+const SILHOUETTE_ALPHA_THRESHOLD = 64;+// Post-resize alpha snap (Python premultiplied_resize's ALPHA_NOISE_FLOOR).+const ALPHA_NOISE_FLOOR = 2;+// Compiled idle height must match the walk row's median height within 2px.+const IDLE_HEIGHT_TOLERANCE = 2;++const RUNTIME_DIR = 'runtime';+const CURRENT_POINTER = 'runtime/current.json';+const atlasStem = (recordId) => `${recordId}-animation-atlas`;++const compileError = (message, code = 'ATLAS_COMPILE_INVALID') =>+ new ServerError(message, { status: 422, code });++const sha256Buffer = (buffer) => createHash('sha256').update(buffer).digest('hex');++/** Tight bbox of pixels with alpha > threshold; exclusive right/bottom. */+function thresholdBbox(frame, threshold) {+ const { data, width, height } = frame;+ let left = width; let top = height; let right = -1; let bottom = -1;+ for (let y = 0; y < height; y++) {+ for (let x = 0; x < width; x++) {+ if (data[(y * width + x) * 4 + 3] > threshold) {+ if (x < left) left = x;+ if (x > right) right = x;+ if (y < top) top = y;+ if (y > bottom) bottom = y;+ }+ }+ }+ if (right < 0) return null;+ return { left, top, right: right + 1, bottom: bottom + 1 };+}++function occupiedDimensions(frame, threshold, label) {+ const bounds = thresholdBbox(frame, threshold);+ if (!bounds) throw compileError(`${label} has no visible pixels`);+ return { width: bounds.right - bounds.left, height: bounds.bottom - bounds.top };+}++/**+ * Load a source image as a straight-alpha transparent frame. Already-keyed+ * sources (packaged walk frames) get a despill safety pass; opaque key-matte+ * sources (locked anchors) go through measured-key alpha recovery first —+ * the same treatment the walk postprocess gives its raw frames.+ */+async function transparentSource(absPath, split, keyHex) {+ const frame = await decodeRgbaFrame(absPath);+ const { data } = frame;+ let alphaMin = 255; let alphaMax = 0;+ for (let i = 3; i < data.length; i += 4) {+ const a = data[i];+ if (a < alphaMin) alphaMin = a;+ if (a > alphaMax) alphaMax = a;+ }+ if (alphaMin < alphaMax) return despillKeyFrame(frame, split);+ const measured = sampleBorderKey(frame);+ validateMeasuredKey(measured, split, keyHex);+ return despillKeyFrame(recoverAlphaFrame(frame, measured, split), split);+}++/**+ * Scale a source frame once and translate it into a cell so the silhouette+ * centers on pivot x with its feet exactly on the pivot ground line —+ * translation-only placement, refusing any content that touches a cell edge.+ */+async function normalizeCellFrame(source, scale, label, geometry) {+ const { cellSize, pivot } = geometry;+ const width = Math.max(1, pyRound(source.width * scale));+ const height = Math.max(1, pyRound(source.height * scale));+ const scaled = await premultipliedResize(source, width, height);+ // Python's premultiplied_resize snaps sub-noise alpha after re-straightening.+ for (let i = 3; i < scaled.data.length; i += 4) {+ if (scaled.data[i] <= ALPHA_NOISE_FLOOR) {+ scaled.data[i - 3] = 0; scaled.data[i - 2] = 0; scaled.data[i - 1] = 0; scaled.data[i] = 0;+ }+ }+ const bounds = thresholdBbox(scaled, ALPHA_THRESHOLD);+ if (!bounds) throw compileError(`${label} has no visible pixels after scaling`);+ const centerX = (bounds.left + bounds.right - 1) / 2;+ const pasteX = pyRound(pivot[0] - centerX);+ const pasteY = pivot[1] - (bounds.bottom - 1);+ if (pasteX + bounds.left <= 0 || pasteY + bounds.top <= 0) {+ throw compileError(`${label} touches the top or left runtime cell edge`);+ }+ if (pasteX + bounds.right >= cellSize || pasteY + bounds.bottom >= cellSize) {+ throw compileError(`${label} touches the right or bottom runtime cell edge`);+ }+ const cell = { data: Buffer.alloc(cellSize * cellSize * 4), width: cellSize, height: cellSize };+ blitFrame(cell, scaled, pasteX, pasteY);+ const final = thresholdBbox(cell, ALPHA_THRESHOLD);+ if (!final || final.bottom - 1 !== pivot[1]) {+ throw compileError(`${label} misses the runtime ground line y=${pivot[1]}`);+ }+ return {+ cell,+ meta: {+ scale: pyRoundTo(scale, 8),+ translation: [pasteX, pasteY],+ occupiedBounds: {+ left: final.left,+ top: final.top,+ width: final.right - final.left,+ height: final.bottom - final.top,+ },+ },+ };+}++/** Copy a straight-alpha frame onto a transparent canvas (no overlap). */+function blitFrame(canvas, frame, dx, dy) {+ for (let y = 0; y < frame.height; y++) {+ const ty = dy + y;+ if (ty < 0 || ty >= canvas.height) continue;+ for (let x = 0; x < frame.width; x++) {+ const tx = dx + x;+ if (tx < 0 || tx >= canvas.width) continue;+ const si = (y * frame.width + x) * 4;+ if (frame.data[si + 3] === 0) continue;+ frame.data.copy(canvas.data, (ty * canvas.width + tx) * 4, si, si + 4);+ }+ }+}++/**+ * Revalidate the full evidence chain: finalized walk set → selection →+ * per-direction run manifests → packaged frame bytes, plus the locked+ * reference set's anchors. Returns everything the compiler consumes.+ */+export async function validateForCompile(recordId) {+ const dir = spriteDir(recordId);+ const walkSetAbs = join(dir, `walk/${recordId}-walk-set-v1.json`);+ const walkSet = await readJSONFile(walkSetAbs, null);+ if (!walkSet) throw compileError('No finalized walk set — approve all 8 directions first', 'WALK_SET_REQUIRED');+ if (walkSet.kind !== 'finalized-eight-direction-walk-set' || walkSet.status !== 'final') {+ throw compileError('Walk set manifest is not a finalized eight-direction walk set');+ }+ if (walkSet.characterId !== recordId) throw compileError('Walk set characterId mismatch');+ if (JSON.stringify(walkSet.directionOrder) !== JSON.stringify(SPRITE_DIRECTIONS)) {+ throw compileError('Walk set direction order does not match the runtime contract');+ }+ const selectionAbs = join(dir, walkSet.selectionPath);+ if ((await sha256File(selectionAbs)) !== walkSet.selectionSha256) {+ throw compileError('Walk selection file no longer matches its finalized sha256');+ }++ const referenceManifest = await loadManifest(recordId);+ if (!referenceManifest || referenceManifest.status !== 'complete') {+ throw compileError('Reference set is not complete — all 8 anchors must be locked', 'REFERENCE_INCOMPLETE');+ }+ const chromaKey = referenceManifest.chromaKey;+ if (!chromaKey) throw compileError('Reference manifest has no frozen chroma key');++ const anchors = {};+ for (const direction of SPRITE_DIRECTIONS) {+ const anchor = (referenceManifest.anchors || []).find((a) => a.direction === direction);+ if (!anchor || anchor.status !== 'locked' || !anchor.path) {+ throw compileError(`Anchor for ${direction} is not locked`);+ }+ const anchorAbs = join(dir, anchor.path);+ if ((await sha256File(anchorAbs)) !== anchor.sha256) {+ throw compileError(`Anchor for ${direction} no longer matches its locked sha256`);+ }+ anchors[direction] = { ...anchor, abs: anchorAbs };+ }++ const runs = {};+ for (const direction of SPRITE_DIRECTIONS) {+ const entry = walkSet.directions?.[direction];+ if (!entry || entry.status !== 'approved') throw compileError(`Direction ${direction} is not approved`);+ const manifestAbs = join(dir, entry.runManifest);+ if ((await sha256File(manifestAbs)) !== entry.runManifestSha256) {+ throw compileError(`Run manifest for ${direction} no longer matches its approved sha256`);+ }+ const manifest = await readJSONFile(manifestAbs, null);+ if (!manifest || manifest.direction !== direction) {+ throw compileError(`Run manifest for ${direction} is unreadable or mislabeled`);+ }+ const frames = manifest.frames || [];+ if (frames.length !== WALK_PHASES.length) {+ throw compileError(`Direction ${direction} has ${frames.length} frames — expected ${WALK_PHASES.length}`);+ }+ for (let i = 0; i < frames.length; i++) {+ if (frames[i].phase !== WALK_PHASES[i] || frames[i].outputIndex !== i) {+ throw compileError(`Direction ${direction} frame ${i} is out of gait-phase order`);+ }+ if ((await sha256File(join(dir, frames[i].path))) !== frames[i].sha256) {+ throw compileError(`Direction ${direction} frame ${frames[i].phase} no longer matches its packaged sha256`);+ }+ }+ runs[direction] = { runId: entry.runId, manifestPath: entry.runManifest, manifest };+ }++ return {+ walkSet,+ walkSetPath: `walk/${recordId}-walk-set-v1.json`,+ walkSetSha256: await sha256File(walkSetAbs),+ referenceManifest,+ chromaKey,+ anchors,+ runs,+ };+}++async function compileDirectionRow(recordId, direction, validated, geometry) {+ const dir = spriteDir(recordId);+ const split = keyChannelSplit(validated.chromaKey);+ const { manifest, runId, manifestPath } = validated.runs[direction];++ const walkSources = [];+ for (const frame of manifest.frames) {+ walkSources.push(await transparentSource(join(dir, frame.path), split, validated.chromaKey));+ }+ const dims = walkSources.map((f, i) => occupiedDimensions(f, ALPHA_THRESHOLD, `${direction}-${WALK_PHASES[i]}`));+ const directionScale = Math.min(+ geometry.targetMaxHeight / Math.max(...dims.map((d) => d.height)),+ geometry.targetMaxWidth / Math.max(...dims.map((d) => d.width)),+ );++ const cells = [];+ const anchor = validated.anchors[direction];+ const idleSource = await transparentSource(anchor.abs, split, validated.chromaKey);+ const idleDims = occupiedDimensions(idleSource, SILHOUETTE_ALPHA_THRESHOLD, `${direction}-idle`);+ const desiredIdleHeight = median(dims.map((d) => d.height)) * directionScale;+ const idleScale = Math.min(desiredIdleHeight / idleDims.height, geometry.targetMaxWidth / idleDims.width);+ const idle = await normalizeCellFrame(idleSource, idleScale, `${direction}-idle`, geometry);+ if (Math.abs(idle.meta.occupiedBounds.height - desiredIdleHeight) > IDLE_HEIGHT_TOLERANCE) {+ throw compileError(`${direction} idle height ${idle.meta.occupiedBounds.height} misses the walk median ${pyRoundTo(desiredIdleHeight, 2)}`);+ }+ cells.push({+ column: 'idle',+ ...idle,+ sourcePath: anchor.path,+ sourceSha256: anchor.sha256,+ policy: 'locked-directional-reference-anchor',+ });++ for (let i = 0; i < walkSources.length; i++) {+ const frame = manifest.frames[i];+ const normalized = await normalizeCellFrame(walkSources[i], directionScale, `${direction}-${frame.phase}`, geometry);+ cells.push({ column: frame.phase, ...normalized, sourcePath: frame.path, sourceSha256: frame.sha256 });+ }++ cells.push({+ column: 'scanner',+ cell: { ...idle.cell, data: Buffer.from(idle.cell.data) },+ meta: idle.meta,+ sourcePath: anchor.path,+ sourceSha256: anchor.sha256,+ policy: 'locked-idle-placeholder',+ });++ return {+ direction,+ runId,+ runManifestPath: manifestPath,+ walkDirectionScale: pyRoundTo(directionScale, 8),+ idleScale: pyRoundTo(idleScale, 8),+ idlePolicy: 'locked-directional-reference-anchor',+ scannerPolicy: 'locked-idle-placeholder',+ cells,+ };+}++async function nextAtlasVersion(runtimeAbs, stem) {+ let entries = [];+ try {+ entries = await readdir(runtimeAbs, { withFileTypes: true });+ } catch {+ return 1;+ }+ const pattern = /^v(\d+)$/;+ let max = 0;+ for (const entry of entries) {+ const match = entry.isDirectory() && entry.name.match(pattern);+ if (!match) continue;+ const version = Number(match[1]);+ if (version > max && await pathExists(join(runtimeAbs, entry.name, `${stem}-v${version}.png`))) {+ max = version;+ }+ }+ return max + 1;+}++/** Refuse to overwrite an immutable artifact with differing bytes. */+async function writeImmutable(absPath, buffer) {+ const existing = await tryReadFile(absPath, null);+ if (existing !== null) {+ if (!existing.equals(buffer)) {+ throw new ServerError(`Immutable runtime output differs: ${absPath}`, { status: 409, code: 'IMMUTABLE_CONFLICT' });+ }+ return;+ }+ await atomicWrite(absPath, buffer);+}++function mergeGeometry(override = {}) {+ const geometry = { ...DEFAULT_ATLAS_GEOMETRY, ...override };+ if (geometry.targetMaxWidth >= geometry.cellSize || geometry.targetMaxHeight >= geometry.cellSize) {+ throw new ServerError('Atlas geometry target bounds must fit inside the cell', { status: 400, code: 'INVALID_GEOMETRY' });+ }+ return geometry;+}++/**+ * Compile (idempotently) the runtime atlas for a finalized walk set. Returns+ * `{ created, version, atlasPath, atlasSha256, manifestPath, geometry }` —+ * `created: false` when the current pointer already covers identical bytes.+ * Runs inside the record's walk write tail; callers already inside the tail+ * use compileAtlasInTail.+ */+export function compileAtlas(recordId, options = {}) {+ return withWalkWriteTail(recordId, () => compileAtlasInTail(recordId, options));+}++export async function compileAtlasInTail(recordId, { geometry: geometryOverride } = {}) {+ await requireCharacter(recordId);+ const geometry = mergeGeometry(geometryOverride);+ const validated = await validateForCompile(recordId);+ const dir = spriteDir(recordId);++ const rows = [];+ for (const direction of SPRITE_DIRECTIONS) {+ rows.push(await compileDirectionRow(recordId, direction, validated, geometry));+ }++ const { cellSize } = geometry;+ const atlasWidth = cellSize * ATLAS_COLUMNS.length;+ const atlasHeight = cellSize * SPRITE_DIRECTIONS.length;+ const atlas = { data: Buffer.alloc(atlasWidth * atlasHeight * 4), width: atlasWidth, height: atlasHeight };+ for (let r = 0; r < rows.length; r++) {+ rows[r].cells.forEach((cell, c) => blitFrame(atlas, cell.cell, c * cellSize, r * cellSize));+ }+ const atlasBuffer = await sharp(atlas.data, { raw: { width: atlasWidth, height: atlasHeight, channels: 4 } })+ .png()+ .toBuffer();+ const atlasSha256 = sha256Buffer(atlasBuffer);++ const current = await readJSONFile(join(dir, CURRENT_POINTER), null);+ if (current && current.walkSetSha256 === validated.walkSetSha256 && current.atlasSha256 === atlasSha256) {+ return { ...current, created: false };+ }++ const stem = atlasStem(recordId);+ const runtimeAbs = join(dir, RUNTIME_DIR);+ const version = await nextAtlasVersion(runtimeAbs, stem);+ const versionRel = `${RUNTIME_DIR}/v${version}`;+ const atlasRel = `${versionRel}/${stem}-v${version}.png`;+ const manifestRel = `${versionRel}/${stem}-v${version}-manifest.json`;+ await ensureDir(join(dir, versionRel));+ await writeImmutable(join(dir, atlasRel), atlasBuffer);++ const manifest = {+ schemaVersion: 1,+ kind: 'reviewed-walk-set-runtime-atlas',+ characterId: recordId,+ version,+ createdAt: new Date().toISOString(),+ chromaKey: validated.chromaKey,+ compilerPath: 'server/services/sprites/atlas.js',+ walkSetPath: validated.walkSetPath,+ walkSetSha256: validated.walkSetSha256,+ atlasPath: atlasRel,+ atlasSha256,+ geometry: {+ columns: ATLAS_COLUMNS,+ directionOrder: SPRITE_DIRECTIONS,+ rows: SPRITE_DIRECTIONS.length,+ cellSize,+ pivot: geometry.pivot,+ targetMaxHeight: geometry.targetMaxHeight,+ targetMaxWidth: geometry.targetMaxWidth,+ widthPx: atlasWidth,+ heightPx: atlasHeight,+ },+ directions: rows.map((row) => ({+ direction: row.direction,+ runId: row.runId,+ runManifestPath: row.runManifestPath,+ walkDirectionScale: row.walkDirectionScale,+ idleScale: row.idleScale,+ idlePolicy: row.idlePolicy,+ scannerPolicy: row.scannerPolicy,+ cells: row.cells.map((cell, c) => ({+ column: cell.column,+ columnIndex: c,+ translation: cell.meta.translation,+ scale: cell.meta.scale,+ occupiedBounds: cell.meta.occupiedBounds,+ sourcePath: cell.sourcePath,+ sourceSha256: cell.sourceSha256,+ ...(cell.policy ? { policy: cell.policy } : {}),+ })),+ })),+ };+ const manifestBuffer = Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`);+ await writeImmutable(join(dir, manifestRel), manifestBuffer);++ const pointer = {+ schemaVersion: 1,+ kind: 'runtime-atlas-selection',+ characterId: recordId,+ version,+ atlasPath: atlasRel,+ atlasSha256,+ manifestPath: manifestRel,+ manifestSha256: sha256Buffer(manifestBuffer),+ walkSetSha256: validated.walkSetSha256,+ geometry: manifest.geometry,+ compiledAt: manifest.createdAt,+ };+ await atomicWrite(join(dir, CURRENT_POINTER), pointer);+ console.log(`🧩 sprite atlas compiled for ${recordId} → v${version}`);+ return { ...pointer, created: true };+}++/** Atlas view for the detail endpoint: current pointer + publish history. */+export async function getAtlasState(recordId) {+ const dir = spriteDir(recordId);+ const [current, publications] = await Promise.all([+ readJSONFile(join(dir, CURRENT_POINTER), null),+ readJSONFile(join(dir, 'runtime/publications.json'), []),+ ]);+ return { current, publications: [...publications].reverse() };+}diff --git a/server/services/sprites/atlas.test.js b/server/services/sprites/atlas.test.jsnew file mode 100644index 0000000000..e57d5067e1--- /dev/null+++ b/server/services/sprites/atlas.test.js@@ -0,0 +1,258 @@+/**+ * Runtime atlas compiler (#2898): evidence-chain validation (walk set,+ * selection, run manifests, frame + anchor sha256s), the geometry contract+ * (10×8 grid, per-direction single scale, pivot ground line), immutable+ * versioning, and compile idempotency. Fixtures lock a real reference set+ * (real normalize + chroma-key selection) and hand-write the walk artifacts+ * with a correct hash chain.+ */++import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';+import { mkdtempSync, rmSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import sharp from 'sharp';+import { mkdir, writeFile, readFile } from 'fs/promises';+import { createHash } from 'crypto';++const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-atlas-test-'));++vi.mock('../../lib/fileUtils.js', async (importOriginal) => {+ const actual = await importOriginal();+ Object.assign(actual.PATHS, {+ data: TEST_ROOT,+ sprites: join(TEST_ROOT, 'sprites'),+ images: join(TEST_ROOT, 'images'),+ });+ return actual;+});++vi.mock('../imageGen/index.js', () => ({+ resolveImageCleaners: () => ({ cleanC2PA: false, denoise: false }),+}));+vi.mock('../settings.js', () => ({+ getSettings: async () => ({ imageGen: { mode: 'codex' } }),+}));+vi.mock('../mediaJobQueue/index.js', () => ({+ enqueueJob: () => ({ jobId: 'job-1', position: 0, status: 'queued' }),+ mediaJobEvents: { on: () => {}, off: () => {} },+}));++const records = await import('./records.js');+const { lockReference, loadManifest } = await import('./reference.js');+const { compileAtlas, getAtlasState, ATLAS_COLUMNS, DEFAULT_ATLAS_GEOMETRY } = await import('./atlas.js');+const { SPRITE_DIRECTIONS } = await import('./prompts.js');+const { WALK_PHASES } = await import('./walkPostprocess.js');++let seq = 0;+const newId = () => `atlas-char-${++seq}`;+const sha256 = (buf) => createHash('sha256').update(buf).digest('hex');++async function writeCandidatePng(path) {+ const w = 64; const h = 64;+ const buf = Buffer.alloc(w * h * 3);+ for (let p = 0; p < w * h; p++) buf.set([255, 0, 255], p * 3);+ for (let y = 10; y < 40; y++) for (let x = 22; x < 32; x++) buf.set([23, 107, 101], (y * w + x) * 3);+ await mkdir(join(path, '..'), { recursive: true });+ await sharp(buf, { raw: { width: w, height: h, channels: 3 } }).png().toFile(path);+}++async function placeCandidate(recordId, target, name) {+ const candDir = join(TEST_ROOT, 'sprites', recordId, 'reference', 'candidates');+ await writeCandidatePng(join(candDir, name));+ await writeFile(join(candDir, `${name.replace(/\.png$/, '')}.generation.json`), JSON.stringify({+ schemaVersion: 1, target, chromaKey: '#FF00FF',+ }));+ return `reference/candidates/${name}`;+}++async function lockAllAnchors(id) {+ await records.createRecord({ kind: 'character', name: 'Atlas Walker' }, id);+ await lockReference(id, { target: 'main', candidate: await placeCandidate(id, 'main', 'walk-south-candidate-01.png') });+ for (const dir of SPRITE_DIRECTIONS.filter((d) => d !== 'south')) {+ await lockReference(id, { target: dir, candidate: await placeCandidate(id, dir, `walk-${dir}-candidate-01.png`) });+ }+}++/** Transparent 40×40 RGBA frame with an opaque 20×30 figure. */+async function walkFramePng(path, tint) {+ const w = 40; const h = 40;+ const buf = Buffer.alloc(w * h * 4);+ for (let y = 5; y < 35; y++) {+ for (let x = 10; x < 30; x++) {+ buf.set([tint, 107, 101, 255], (y * w + x) * 4);+ }+ }+ await mkdir(join(path, '..'), { recursive: true });+ await sharp(buf, { raw: { width: w, height: h, channels: 4 } }).png().toFile(path);+}++async function buildFinalizedWalkSet(recordId) {+ const manifest = await loadManifest(recordId);+ const chromaKey = manifest.chromaKey;+ const dir = join(TEST_ROOT, 'sprites', recordId);+ const selection = {+ schemaVersion: 1,+ kind: 'reviewed-directional-walk-selection',+ characterId: recordId,+ status: 'complete',+ directions: {},+ };+ for (const direction of SPRITE_DIRECTIONS) {+ const runId = `walk-${direction}-${(seq++).toString(16).padStart(8, '0')}`;+ const generatedRel = `grok/${runId}/generated`;+ const frames = [];+ for (let i = 0; i < WALK_PHASES.length; i++) {+ const name = `${String(i).padStart(2, '0')}-${WALK_PHASES[i]}.png`;+ const rel = `${generatedRel}/frames/${name}`;+ await walkFramePng(join(dir, rel), 20 + i * 8);+ frames.push({+ outputIndex: i,+ phase: WALK_PHASES[i],+ path: rel,+ sha256: sha256(await readFile(join(dir, rel))),+ });+ }+ const runManifest = {+ schemaVersion: 1,+ kind: 'deterministically-packaged-grok-walk-video',+ characterId: recordId,+ direction,+ chromaKey,+ frames,+ };+ const manifestRel = `${generatedRel}/${recordId}-walk-${direction}-manifest.json`;+ const manifestBytes = JSON.stringify(runManifest);+ await writeFile(join(dir, manifestRel), manifestBytes);+ selection.directions[direction] = {+ status: 'approved',+ runId,+ runPath: `grok/${runId}`,+ runManifest: manifestRel,+ runManifestSha256: sha256(Buffer.from(manifestBytes)),+ approvedAt: new Date().toISOString(),+ };+ }+ await mkdir(join(dir, 'walk'), { recursive: true });+ const selectionRel = `walk/${recordId}-walk-selection-v1.json`;+ const selectionBytes = JSON.stringify(selection);+ await writeFile(join(dir, selectionRel), selectionBytes);+ const walkSet = {+ schemaVersion: 1,+ kind: 'finalized-eight-direction-walk-set',+ characterId: recordId,+ status: 'final',+ directionOrder: SPRITE_DIRECTIONS,+ selectionPath: selectionRel,+ selectionSha256: sha256(Buffer.from(selectionBytes)),+ directions: selection.directions,+ finalizedAt: new Date().toISOString(),+ };+ await writeFile(join(dir, `walk/${recordId}-walk-set-v1.json`), JSON.stringify(walkSet));+ return { walkSet, selection };+}++async function finalizedCharacter() {+ const id = newId();+ await lockAllAnchors(id);+ await buildFinalizedWalkSet(id);+ return id;+}++beforeEach(() => {+ rmSync(join(TEST_ROOT, 'sprite-records.json'), { force: true });+});+afterAll(() => rmSync(TEST_ROOT, { recursive: true, force: true }));++describe('compileAtlas', () => {+ it('compiles the 10×8 player atlas with full provenance and a current pointer', async () => {+ const id = await finalizedCharacter();+ const result = await compileAtlas(id);++ expect(result.created).toBe(true);+ expect(result.version).toBe(1);+ expect(result.atlasPath).toBe(`runtime/v1/${id}-animation-atlas-v1.png`);++ const atlasAbs = join(TEST_ROOT, 'sprites', id, result.atlasPath);+ const meta = await sharp(atlasAbs).metadata();+ expect(meta.width).toBe(DEFAULT_ATLAS_GEOMETRY.cellSize * ATLAS_COLUMNS.length);+ expect(meta.height).toBe(DEFAULT_ATLAS_GEOMETRY.cellSize * SPRITE_DIRECTIONS.length);+ expect(sha256(await readFile(atlasAbs))).toBe(result.atlasSha256);++ const manifest = JSON.parse(await readFile(join(TEST_ROOT, 'sprites', id, result.manifestPath), 'utf8'));+ expect(manifest.kind).toBe('reviewed-walk-set-runtime-atlas');+ expect(manifest.geometry.columns).toEqual(['idle', ...WALK_PHASES, 'scanner']);+ expect(manifest.geometry.directionOrder).toEqual(SPRITE_DIRECTIONS);+ expect(manifest.directions).toHaveLength(8);+ for (const row of manifest.directions) {+ expect(row.cells).toHaveLength(10);+ expect(row.cells[0].policy).toBe('locked-directional-reference-anchor');+ expect(row.cells[9].policy).toBe('locked-idle-placeholder');+ // Scanner mirrors the idle cell's placement exactly.+ expect(row.cells[9].occupiedBounds).toEqual(row.cells[0].occupiedBounds);+ for (const cell of row.cells) {+ // Feet on the pivot ground line: bounds bottom (top + height - 1) = pivot y.+ expect(cell.occupiedBounds.top + cell.occupiedBounds.height - 1).toBe(DEFAULT_ATLAS_GEOMETRY.pivot[1]);+ // Target bounds drive the scale; lanczos soft edges may extend the+ // visible bbox ~1px per side (the edge-touch checks are the hard gate).+ expect(cell.occupiedBounds.height).toBeLessThanOrEqual(DEFAULT_ATLAS_GEOMETRY.targetMaxHeight + 2);+ expect(cell.sourceSha256).toMatch(/^[0-9a-f]{64}$/);+ }+ }++ const state = await getAtlasState(id);+ expect(state.current.version).toBe(1);+ expect(state.current.walkSetSha256).toMatch(/^[0-9a-f]{64}$/);+ expect(state.publications).toEqual([]);+ });++ it('is idempotent for the same finalized set — and versions on a changed one', async () => {+ const id = await finalizedCharacter();+ const first = await compileAtlas(id);+ const second = await compileAtlas(id);+ expect(second.created).toBe(false);+ expect(second.version).toBe(first.version);+ expect(second.atlasSha256).toBe(first.atlasSha256);+ });++ it('refuses a tampered frame (per-frame sha256 revalidation)', async () => {+ const id = await finalizedCharacter();+ const walkSet = JSON.parse(await readFile(join(TEST_ROOT, 'sprites', id, `walk/${id}-walk-set-v1.json`), 'utf8'));+ const frameRel = JSON.parse(+ await readFile(join(TEST_ROOT, 'sprites', id, walkSet.directions.east.runManifest), 'utf8'),+ ).frames[3].path;+ await walkFramePng(join(TEST_ROOT, 'sprites', id, frameRel), 250);+ await expect(compileAtlas(id)).rejects.toMatchObject({ status: 422 });+ });++ it('refuses without a finalized walk set', async () => {+ const id = newId();+ await lockAllAnchors(id);+ await expect(compileAtlas(id)).rejects.toMatchObject({ status: 422, code: 'WALK_SET_REQUIRED' });+ });++ it('refuses an unapproved direction', async () => {+ const id = await finalizedCharacter();+ const setAbs = join(TEST_ROOT, 'sprites', id, `walk/${id}-walk-set-v1.json`);+ const walkSet = JSON.parse(await readFile(setAbs, 'utf8'));+ walkSet.directions.north.status = 'rejected';+ await writeFile(setAbs, JSON.stringify(walkSet));+ await expect(compileAtlas(id)).rejects.toMatchObject({ status: 422 });+ });++ it('honors a geometry override', async () => {+ const id = await finalizedCharacter();+ const result = await compileAtlas(id, {+ geometry: { cellSize: 64, pivot: [32, 56], targetMaxHeight: 44, targetMaxWidth: 52 },+ });+ const meta = await sharp(join(TEST_ROOT, 'sprites', id, result.atlasPath)).metadata();+ expect(meta.width).toBe(64 * 10);+ expect(meta.height).toBe(64 * 8);+ });++ it('rejects geometry whose content bounds cannot fit the cell', async () => {+ const id = await finalizedCharacter();+ await expect(compileAtlas(id, { geometry: { cellSize: 64, targetMaxWidth: 64 } }))+ .rejects.toMatchObject({ status: 400, code: 'INVALID_GEOMETRY' });+ });+});diff --git a/server/services/sprites/publish.js b/server/services/sprites/publish.jsnew file mode 100644index 0000000000..db076ad467--- /dev/null+++ b/server/services/sprites/publish.js@@ -0,0 +1,209 @@+/**+ * Sprites — publish the compiled runtime atlas into a managed app's repo+ * (issue #2898, phase 4).+ *+ * The game consumes sprites from its own tree; PortOS owns provenance. A+ * per-record `publishBinding` ({ appId, atlasDestPath, codeBinding? }) names+ * the managed app and the repo-relative destination. Publishing compiles the+ * atlas (idempotently), path-anchors the destination under the app's+ * repoPath, and atomically replaces the file — refusing when the destination+ * bytes no longer match the previous publish (something else changed the+ * game's atlas; clobbering it silently would destroy that change).+ *+ * The optional codeBinding is a verify-or-rewrite guard over the game source+ * file that references the atlas: the binding's resourcePath must appear in+ * the file exactly requiredOccurrenceCount times. When a previous publish+ * recorded a different resourcePath (a destination move), the old string is+ * rewritten to the new one — occurrence-count guarded, refusing on any+ * drift. Engine sidecars (e.g. Godot .png.import) are the game repo's+ * concern and are never touched.+ *+ * Publishes serialize on a per-app queue (the appDeployer per-app-lock+ * posture) nested inside the record's walk write tail.+ */++import { join, resolve } from 'path';+import { readFile, stat } from 'fs/promises';+import {+ atomicWrite, isPathInsideDir, readJSONFile, sha256File, pathExists,+} from '../../lib/fileUtils.js';+import { ServerError } from '../../lib/errorHandler.js';+import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';+import { getAppById } from '../apps.js';+import { spriteDir } from './paths.js';+import { requireCharacter } from './reference.js';+import { updateRecord } from './records.js';+import { withWalkWriteTail } from './walk.js';+import { compileAtlasInTail } from './atlas.js';++const PUBLICATIONS_REL = 'runtime/publications.json';++// Per-app serialization: two records publishing into the same app repo queue+// behind each other instead of interleaving reads/writes of the same tree.+const appPublishTail = createKeyCachedQueue();++const bindingError = (message, code) => new ServerError(message, { status: 400, code });++/**+ * Anchor a repo-relative path under a managed app's repoPath, refusing+ * absolute paths, traversal, and the repo root itself.+ */+function anchorRepoPath(repoRoot, relPath, label) {+ if (typeof relPath !== 'string' || !relPath || relPath.startsWith('/') || relPath.includes('\\')) {+ throw bindingError(`${label} must be a repo-relative path`, 'INVALID_PUBLISH_PATH');+ }+ const abs = resolve(repoRoot, relPath);+ if (abs === resolve(repoRoot) || !isPathInsideDir(repoRoot, abs)) {+ throw bindingError(`${label} escapes the app repository: ${relPath}`, 'INVALID_PUBLISH_PATH');+ }+ return abs;+}++/** Validate a publishBinding shape (null clears it). */+export async function validatePublishBinding(binding) {+ if (binding === null) return null;+ const { appId, atlasDestPath, codeBinding } = binding;+ const app = await getAppById(appId);+ if (!app) throw bindingError(`Unknown app: ${appId}`, 'UNKNOWN_APP');+ if (!app.repoPath || !(await pathExists(app.repoPath))) {+ throw bindingError(`App ${app.name || appId} has no accessible repoPath`, 'APP_REPO_MISSING');+ }+ anchorRepoPath(app.repoPath, atlasDestPath, 'atlasDestPath');+ if (!atlasDestPath.toLowerCase().endsWith('.png')) {+ throw bindingError('atlasDestPath must point at a .png atlas file', 'INVALID_PUBLISH_PATH');+ }+ if (codeBinding) {+ anchorRepoPath(app.repoPath, codeBinding.path, 'codeBinding.path');+ if (typeof codeBinding.resourcePath !== 'string' || !codeBinding.resourcePath.trim()) {+ throw bindingError('codeBinding.resourcePath is required', 'INVALID_CODE_BINDING');+ }+ }+ return {+ appId,+ atlasDestPath,+ codeBinding: codeBinding+ ? {+ path: codeBinding.path,+ resourcePath: codeBinding.resourcePath.trim(),+ requiredOccurrenceCount: codeBinding.requiredOccurrenceCount ?? 1,+ }+ : null,+ };+}++/** Persist a validated binding on the record. */+export async function setPublishBinding(recordId, binding) {+ await requireCharacter(recordId);+ const validated = await validatePublishBinding(binding);+ return updateRecord(recordId, { publishBinding: validated });+}++const countOccurrences = (text, needle) => (needle ? text.split(needle).length - 1 : 0);++/**+ * Verify (or occurrence-guarded-rewrite) the game-source code binding.+ * Returns the publication's codeBinding summary; throws on drift.+ */+async function applyCodeBinding(repoRoot, codeBinding, previousResourcePath) {+ const abs = anchorRepoPath(repoRoot, codeBinding.path, 'codeBinding.path');+ const required = codeBinding.requiredOccurrenceCount ?? 1;+ const text = await readFile(abs, 'utf8').catch(() => null);+ if (text === null) {+ throw new ServerError(`Code binding file not found in app repo: ${codeBinding.path}`, { status: 409, code: 'CODE_BINDING_MISSING' });+ }+ const currentCount = countOccurrences(text, codeBinding.resourcePath);+ if (currentCount === required) {+ return { ...codeBinding, rewritten: false };+ }+ // Destination moved since the last publish: the file should still hold the+ // previously-published resource path exactly N times — rewrite it.+ if (previousResourcePath && previousResourcePath !== codeBinding.resourcePath) {+ const previousCount = countOccurrences(text, previousResourcePath);+ if (previousCount === required) {+ await atomicWrite(abs, text.split(previousResourcePath).join(codeBinding.resourcePath));+ return { ...codeBinding, rewritten: true, previousResourcePath };+ }+ }+ throw new ServerError(+ `Code binding drifted: ${codeBinding.path} contains ${currentCount} occurrence(s) of the resource path (expected ${required})`,+ { status: 409, code: 'CODE_BINDING_DRIFTED' },+ );+}++/**+ * Compile (idempotently) and publish the runtime atlas into the bound+ * managed app. Refuses without a binding, on a diverged destination, and on+ * code-binding drift. Idempotent: a destination already holding the current+ * atlas bytes records nothing and touches nothing.+ */+export function publishAtlas(recordId) {+ return withWalkWriteTail(recordId, () => publishAtlasImpl(recordId));+}++async function publishAtlasImpl(recordId) {+ const record = await requireCharacter(recordId);+ const binding = record.publishBinding;+ if (!binding?.appId || !binding?.atlasDestPath) {+ throw new ServerError('No publish binding configured — set the target app and atlas path first', { status: 409, code: 'PUBLISH_BINDING_REQUIRED' });+ }+ const app = await getAppById(binding.appId);+ if (!app) throw new ServerError(`Bound app no longer exists: ${binding.appId}`, { status: 409, code: 'UNKNOWN_APP' });+ const repoRoot = app.repoPath;+ const repoStat = repoRoot ? await stat(repoRoot).catch(() => null) : null;+ if (!repoStat?.isDirectory()) {+ throw new ServerError(`App ${app.name || binding.appId} has no accessible repoPath`, { status: 409, code: 'APP_REPO_MISSING' });+ }++ const compiled = await compileAtlasInTail(recordId);++ return appPublishTail(binding.appId, async () => {+ const dir = spriteDir(recordId);+ const destAbs = anchorRepoPath(repoRoot, binding.atlasDestPath, 'atlasDestPath');+ const atlasBuffer = await readFile(join(dir, compiled.atlasPath));++ const publications = await readJSONFile(join(dir, PUBLICATIONS_REL), []);+ const previous = [...publications].reverse().find(+ (p) => p.appId === binding.appId && p.atlasDestPath === binding.atlasDestPath,+ );++ const destSha256 = (await pathExists(destAbs)) ? await sha256File(destAbs) : null;+ if (destSha256 === compiled.atlasSha256) {+ // Verify the code binding even on a no-op so drift never hides.+ const codeBinding = binding.codeBinding+ ? await applyCodeBinding(repoRoot, binding.codeBinding, previous?.codeBinding?.resourcePath)+ : null;+ return { published: false, upToDate: true, compiled, codeBinding };+ }+ if (previous && destSha256 !== null && destSha256 !== previous.atlasSha256) {+ throw new ServerError(+ 'Destination atlas no longer matches the previous publish — it was changed outside PortOS. Resolve in the game repo, then re-publish.',+ { status: 409, code: 'PUBLISH_DEST_DIVERGED' },+ );+ }++ // Verify/rewrite the code binding BEFORE replacing the atlas so a drifted+ // binding aborts the publish with the game repo untouched.+ const codeBinding = binding.codeBinding+ ? await applyCodeBinding(repoRoot, binding.codeBinding, previous?.codeBinding?.resourcePath)+ : null;++ await atomicWrite(destAbs, atlasBuffer);++ const publication = {+ publishedAt: new Date().toISOString(),+ characterId: recordId,+ version: compiled.version,+ atlasPath: compiled.atlasPath,+ atlasSha256: compiled.atlasSha256,+ appId: binding.appId,+ appName: app.name || null,+ atlasDestPath: binding.atlasDestPath,+ destPreviousSha256: destSha256,+ codeBinding,+ };+ publications.push(publication);+ await atomicWrite(join(dir, PUBLICATIONS_REL), publications);+ console.log(`🚚 sprite atlas v${compiled.version} published for ${recordId} → ${app.name || binding.appId}:${binding.atlasDestPath}`);+ return { published: true, publication, compiled };+ });+}diff --git a/server/services/sprites/publish.test.js b/server/services/sprites/publish.test.jsnew file mode 100644index 0000000000..b191e47422--- /dev/null+++ b/server/services/sprites/publish.test.js@@ -0,0 +1,216 @@+/**+ * Publish-to-managed-app (#2898): binding validation (app existence, repo+ * anchoring, traversal refusal), atomic destination replace, diverged-+ * 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.+ */++import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';+import { mkdtempSync, rmSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { mkdir, writeFile, readFile } from 'fs/promises';+import { createHash } from 'crypto';++const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-publish-test-'));+const APP_REPO = join(TEST_ROOT, 'game-repo');++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;+});++const getAppById = vi.fn(async (id) => (id === 'game-app'+ ? { id: 'game-app', name: 'Example Game', repoPath: APP_REPO }+ : null));+vi.mock('../apps.js', () => ({ getAppById: (...args) => getAppById(...args) }));++const compileAtlasInTail = vi.fn();+vi.mock('./atlas.js', () => ({+ compileAtlasInTail: (...args) => compileAtlasInTail(...args),+}));++const records = await import('./records.js');+const { setPublishBinding, publishAtlas, validatePublishBinding } = await import('./publish.js');++let seq = 0;+const sha256 = (buf) => createHash('sha256').update(buf).digest('hex');++async function characterWithAtlas(atlasBytes = 'atlas-png-bytes-v1') {+ const id = `pub-char-${++seq}`;+ await records.createRecord({ kind: 'character', name: 'Publisher' }, id);+ const atlasRel = `runtime/v1/${id}-animation-atlas-v1.png`;+ const abs = join(TEST_ROOT, 'sprites', id, atlasRel);+ await mkdir(join(abs, '..'), { recursive: true });+ await writeFile(abs, atlasBytes);+ compileAtlasInTail.mockResolvedValue({+ created: false,+ version: 1,+ atlasPath: atlasRel,+ atlasSha256: sha256(Buffer.from(atlasBytes)),+ });+ return { id, atlasRel, atlasBytes };+}++const BINDING = { appId: 'game-app', atlasDestPath: 'assets/sprites/hero/hero-atlas.png' };++beforeEach(async () => {+ getAppById.mockClear();+ compileAtlasInTail.mockReset();+ rmSync(join(TEST_ROOT, 'sprite-records.json'), { force: true });+ rmSync(APP_REPO, { recursive: true, force: true });+ await mkdir(APP_REPO, { recursive: true });+});+afterAll(() => rmSync(TEST_ROOT, { recursive: true, force: true }));++describe('validatePublishBinding / setPublishBinding', () => {+ it('persists a normalized binding on the record', async () => {+ const { id } = await characterWithAtlas();+ const updated = await setPublishBinding(id, {+ ...BINDING,+ codeBinding: { path: 'src/Hero.cs', resourcePath: 'res://assets/sprites/hero/hero-atlas.png' },+ });+ expect(updated.publishBinding).toEqual({+ appId: 'game-app',+ atlasDestPath: 'assets/sprites/hero/hero-atlas.png',+ codeBinding: {+ path: 'src/Hero.cs',+ resourcePath: 'res://assets/sprites/hero/hero-atlas.png',+ requiredOccurrenceCount: 1,+ },+ });+ });++ it('clears with null', async () => {+ const { id } = await characterWithAtlas();+ await setPublishBinding(id, BINDING);+ const cleared = await setPublishBinding(id, null);+ expect(cleared.publishBinding).toBeNull();+ });++ it('refuses an unknown app and a traversal destination', async () => {+ await expect(validatePublishBinding({ ...BINDING, appId: 'nope' }))+ .rejects.toMatchObject({ code: 'UNKNOWN_APP' });+ await expect(validatePublishBinding({ ...BINDING, atlasDestPath: '../outside.png' }))+ .rejects.toMatchObject({ code: 'INVALID_PUBLISH_PATH' });+ await expect(validatePublishBinding({ ...BINDING, atlasDestPath: '/abs/path.png' }))+ .rejects.toMatchObject({ code: 'INVALID_PUBLISH_PATH' });+ await expect(validatePublishBinding({ ...BINDING, atlasDestPath: 'assets/atlas.jpg' }))+ .rejects.toMatchObject({ code: 'INVALID_PUBLISH_PATH' });+ });+});++describe('publishAtlas', () => {+ it('refuses without a binding', async () => {+ const { id } = await characterWithAtlas();+ await expect(publishAtlas(id)).rejects.toMatchObject({ status: 409, code: 'PUBLISH_BINDING_REQUIRED' });+ });++ it('atomically writes the atlas into the app repo and records the publication', async () => {+ const { id, atlasBytes } = await characterWithAtlas();+ await setPublishBinding(id, BINDING);+ const result = await publishAtlas(id);++ expect(result.published).toBe(true);+ const destAbs = join(APP_REPO, BINDING.atlasDestPath);+ expect((await readFile(destAbs)).toString()).toBe(atlasBytes);+ expect(result.publication).toMatchObject({+ appId: 'game-app',+ appName: 'Example Game',+ atlasDestPath: BINDING.atlasDestPath,+ version: 1,+ destPreviousSha256: null,+ codeBinding: null,+ });+ const history = JSON.parse(+ await readFile(join(TEST_ROOT, 'sprites', id, 'runtime/publications.json'), 'utf8'),+ );+ expect(history).toHaveLength(1);+ });++ it('is idempotent when the destination already holds the current bytes', async () => {+ const { id } = await characterWithAtlas();+ await setPublishBinding(id, BINDING);+ await publishAtlas(id);+ const again = await publishAtlas(id);+ expect(again.published).toBe(false);+ expect(again.upToDate).toBe(true);+ const history = JSON.parse(+ await readFile(join(TEST_ROOT, 'sprites', id, 'runtime/publications.json'), 'utf8'),+ );+ expect(history).toHaveLength(1);+ });++ it('refuses a destination changed outside PortOS since the previous publish', async () => {+ const { id } = await characterWithAtlas();+ await setPublishBinding(id, BINDING);+ await publishAtlas(id);+ await writeFile(join(APP_REPO, BINDING.atlasDestPath), 'hand-edited-in-game-repo');+ // A NEW compiled atlas (different bytes) must refuse rather than clobber.+ 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)),+ });+ await expect(publishAtlas(id)).rejects.toMatchObject({ status: 409, code: 'PUBLISH_DEST_DIVERGED' });+ });++ it('verifies the code binding by occurrence count and refuses drift', async () => {+ const { id } = await characterWithAtlas();+ const resource = 'res://assets/sprites/hero/hero-atlas.png';+ await mkdir(join(APP_REPO, 'src'), { recursive: true });+ await writeFile(join(APP_REPO, 'src/Hero.cs'), `var atlas = load("${resource}");\n`);+ await setPublishBinding(id, {+ ...BINDING,+ codeBinding: { path: 'src/Hero.cs', resourcePath: resource },+ });+ const ok = await publishAtlas(id);+ expect(ok.published).toBe(true);+ expect(ok.publication.codeBinding).toMatchObject({ rewritten: false });++ // Drift: the resource path appears twice now.+ await writeFile(join(APP_REPO, 'src/Hero.cs'), `load("${resource}"); load("${resource}");\n`);+ 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)),+ });+ await expect(publishAtlas(id)).rejects.toMatchObject({ status: 409, code: 'CODE_BINDING_DRIFTED' });+ // The drifted binding aborted BEFORE the atlas was replaced.+ expect((await readFile(join(APP_REPO, BINDING.atlasDestPath))).toString()).toBe('atlas-png-bytes-v1');+ });++ it('rewrites an occurrence-guarded moved resource path', async () => {+ const { id } = await characterWithAtlas();+ const oldResource = 'res://assets/sprites/hero/old-atlas.png';+ const newResource = 'res://assets/sprites/hero/hero-atlas.png';+ await mkdir(join(APP_REPO, 'src'), { recursive: true });+ await writeFile(join(APP_REPO, 'src/Hero.cs'), `var atlas = load("${oldResource}");\n`);++ // Simulate a previous publish that recorded the old resource path.+ await setPublishBinding(id, {+ ...BINDING,+ codeBinding: { path: 'src/Hero.cs', resourcePath: oldResource },+ });+ await publishAtlas(id);++ // Destination moved: same dest bytes, new resource path in the binding.+ await setPublishBinding(id, {+ ...BINDING,+ codeBinding: { path: 'src/Hero.cs', resourcePath: newResource },+ });+ const result = await publishAtlas(id);+ expect(result.published).toBe(false); // dest bytes unchanged — binding-only fix+ expect(result.codeBinding).toMatchObject({ rewritten: true, previousResourcePath: oldResource });+ expect(await readFile(join(APP_REPO, 'src/Hero.cs'), 'utf8')).toContain(newResource);+ });+});diff --git a/server/services/sprites/walkPostprocess.js b/server/services/sprites/walkPostprocess.jsindex 4f485c35b8..37d89a0022 100644--- a/server/services/sprites/walkPostprocess.js+++ b/server/services/sprites/walkPostprocess.js@@ -369,7 +369,7 @@ function cropFrame(frame, bbox) {// sharp premultiplies alpha before resampling and unpremultiplies after —// the same alpha-weighted LANCZOS the source's premultiplied_resize does.-async function premultipliedResize(frame, width, height) {+export async function premultipliedResize(frame, width, height) {const data = await sharp(frame.data, { raw: { width: frame.width, height: frame.height, channels: 4 } }).resize(width, height, { kernel: 'lanczos3', fit: 'fill' }).raw()