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: publish presentation-ready game assets
[._.]/ Adam Eivy81e53d3bac2c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 897a2cecee..ee952d2404 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -41,6 +41,7 @@- **Agy's model field is now labeled for what it actually selects, and can be overridden per render.** The Image Gen settings field was labeled "Image model" while listing Gemini agent models, which read as the wrong list being loaded. It isn't: `agy models` is the catalog of *agent* models the CLI's `--model` flag accepts, and that agent is what drives the built-in `generate_image` tool. Agy exposes no knob for the underlying image model — its `generate_image` takes prompt, image name, aspect ratio, and reference paths and nothing else — so there is no `imagen-*` option to offer, and passing one makes agy exit before it generates. The field is now "Default agent model" with that explanation, and the Image Gen page adds an **Agent model** picker so a single queue item can run on a different agent model than the saved default without a settings round-trip. Leaving it blank inherits the Settings value; a pinned model that Google later drops from the catalog falls back to the default instead of failing the render. The retry editor on a failed Agy job now edits that same model field (it was bound to the local model-id field, which Agy never reads).## Game+- **Sprite publishing now gives games the right asset for both play and presentation.** A Sprite Manager binding can publish a dedicated 512px transparent selector portrait and a presentation-resolution idle strip from approved source frames alongside its compact runtime atlas. The idle strip carries a consumer sidecar with frame geometry, playback speed, image hash, and source-frame provenance; both presentation outputs retain the same repo anchoring, occupied-file consent, and outside-edit divergence guards as atlas publishing. User-authored animation tracks can also be deliberately reopened from their finalized state and replaced without discarding the superseded render evidence, so a game can evolve a menu idle into a character-specific field vignette without revising the character's identity art. Game artwork can now be assigned a first-class logo role, generated with a role-specific creative brief, and published into managed game UI assets with the existing provenance and drift guards.- **Game workspaces now manage launch art, biome cards, and other game-facing artwork alongside sprites and music.** Choose any image from the PortOS gallery, assign its design role and game destination, generate a role-specific replacement in Image Gen, preview and edit the binding in place, then publish hash-verified bytes into the managed game with protection against overwriting outside changes; artwork also participates in bundle readiness and AI asset reviews.- **[issue-3228] Game detail workspaces keep asset blockers and controls in reach.** The compact header and section tabs stay pinned while each panel scrolls independently, blocked rows explain how to recover and link directly to surviving Sprite or Music records, and missing, malformed, and deleted music audio now report distinct causes.- **[issue-3177] Added a Game studio for assembling managed-app asset bundles.** Create a Game workspace, bind reusable Sprite records and Music tracks, compile an immutable versioned manifest with SHA-256 asset references, and request persisted AI feedback with any configured provider, model, and supported effort. The new `/game/:id` workspace is reachable from Create, Cmd+K, and voice navigation.diff --git a/client/src/components/games/GameBindings.jsx b/client/src/components/games/GameBindings.jsxindex 234c647346..289165d894 100644--- a/client/src/components/games/GameBindings.jsx+++ b/client/src/components/games/GameBindings.jsx@@ -27,6 +27,12 @@ const ARTWORK_ROLES = [destinationPath: 'game/assets/art/title/title-key-art.png',prompt: 'Premium cinematic 16:9 title-screen key art for a cozy science-fiction homesteading game, painterly stylized realism, rich alien world, sophisticated AAA composition, dark calm negative space for a menu, no text, no logo, no UI.',},+ {+ id: 'game-logo',+ label: 'Game logo',+ destinationPath: 'game/assets/art/ui/branding/game-logo.png',+ prompt: 'Premium illustrated game-title wordmark for a cozy science-fiction frontier game, handcrafted expedition-map lettering, subtle botanical and astronomical motifs, strong silhouette, transparent-ready flat chroma background, exact title text only, no mockup, no extra words.',+ },{id: 'biome-luminous-wilds',label: 'Luminous Wilds',diff --git a/client/src/components/games/GameBindings.test.jsx b/client/src/components/games/GameBindings.test.jsxindex 5f96f4cdb5..35848a2102 100644--- a/client/src/components/games/GameBindings.test.jsx+++ b/client/src/components/games/GameBindings.test.jsx@@ -112,5 +112,6 @@ describe('GameBindings', () => {expect(screen.getByRole('button', { name: 'Publish to game' })).toBeEnabled();expect(screen.getByRole('link', { name: 'Generate for this role' })).toHaveAttribute('href', expect.stringContaining('/media/image?prompt='));+ expect(screen.getAllByRole('option', { name: 'Game logo' })).toHaveLength(2);});});diff --git a/client/src/components/sprites/PublishWorkflow.jsx b/client/src/components/sprites/PublishWorkflow.jsxindex 0042e259ec..c15d68f40b 100644--- a/client/src/components/sprites/PublishWorkflow.jsx+++ b/client/src/components/sprites/PublishWorkflow.jsx@@ -62,6 +62,8 @@ export default function PublishWorkflow({const apps = useSidebarApps();const [appId, setAppId] = useState(saved?.appId || '');const [destPath, setDestPath] = useState(saved?.atlasDestPath || '');+ const [portraitPath, setPortraitPath] = useState(saved?.portraitDestPath || '');+ const [presentationIdlePath, setPresentationIdlePath] = useState(saved?.presentationIdleDestPath || '');const [codePath, setCodePath] = useState(saved?.codeBinding?.path || '');const [resourcePath, setResourcePath] = useState(saved?.codeBinding?.resourcePath || '');const [contractTrackCounts, setContractTrackCounts] = useState(seedTrackCounts);@@ -80,13 +82,16 @@ export default function PublishWorkflow({useEffect(() => {setAppId(saved?.appId || '');setDestPath(saved?.atlasDestPath || '');+ setPortraitPath(saved?.portraitDestPath || '');+ setPresentationIdlePath(saved?.presentationIdleDestPath || '');setCodePath(saved?.codeBinding?.path || '');setResourcePath(saved?.codeBinding?.resourcePath || '');setContractTrackCounts(seedTrackCounts);setContractCell(seedCell);setContractCols(seedCols);setConfirmStage(null);- }, [saved?.appId, saved?.atlasDestPath, saved?.codeBinding?.path, saved?.codeBinding?.resourcePath,+ }, [saved?.appId, saved?.atlasDestPath, saved?.portraitDestPath, saved?.presentationIdleDestPath,+ saved?.codeBinding?.path, saved?.codeBinding?.resourcePath,seedTrackCounts, seedCell, seedCols]);const trackInputs = trackDefinitions.map((definition) => {@@ -170,6 +175,8 @@ export default function PublishWorkflow({? {appId,atlasDestPath: destPath.trim(),+ portraitDestPath: portraitPath.trim() || null,+ presentationIdleDestPath: presentationIdlePath.trim() || null,codeBinding: codePath.trim() && resourcePath.trim()? { path: codePath.trim(), resourcePath: resourcePath.trim() }: null,@@ -203,8 +210,22 @@ export default function PublishWorkflow({// The destination holds an atlas — or a layout sidecar — PortOS never// published. Escalate to an explicit overwrite consent instead of// toasting a dead end the UI offers no way to act on.- if (err?.code === 'PUBLISH_DEST_OCCUPIED' || err?.code === 'PUBLISH_LAYOUT_OCCUPIED') {- setOccupiedFile(err.code === 'PUBLISH_LAYOUT_OCCUPIED' ? 'layout' : 'atlas');+ if ([+ 'PUBLISH_DEST_OCCUPIED',+ 'PUBLISH_LAYOUT_OCCUPIED',+ 'PUBLISH_PORTRAIT_OCCUPIED',+ 'PUBLISH_PRESENTATION_IDLE_OCCUPIED',+ 'PUBLISH_PRESENTATION_IDLE_LAYOUT_OCCUPIED',+ ].includes(err?.code)) {+ setOccupiedFile(err.code === 'PUBLISH_LAYOUT_OCCUPIED'+ ? 'layout'+ : err.code === 'PUBLISH_PORTRAIT_OCCUPIED'+ ? 'portrait'+ : err.code === 'PUBLISH_PRESENTATION_IDLE_OCCUPIED'+ ? 'picker animation'+ : err.code === 'PUBLISH_PRESENTATION_IDLE_LAYOUT_OCCUPIED'+ ? 'picker animation layout'+ : 'atlas');setConfirmStage('overwrite');return null;}@@ -217,8 +238,8 @@ export default function PublishWorkflow({? ' — code binding rewritten to the new resource path': '';toast.success(result.published- ? `Atlas v${result.publication.version} published${rewriteNote}`- : `Destination already up to date${rewriteNote}`);+ ? `Atlas v${result.publication.version}${result.portraitWritten ? ', portrait' : ''}${result.presentationIdleWritten ? ', and picker animation' : ''} published${rewriteNote}`+ : `Destination${result.portraitWritten || result.presentationIdleWritten ? ' atlas already current; presentation art published' : ' already up to date'}${rewriteNote}`);onChanged?.();}return result;@@ -252,6 +273,8 @@ export default function PublishWorkflow({const bindingDirty = (saved?.appId || '') !== appId|| (saved?.atlasDestPath || '') !== destPath.trim()+ || (saved?.portraitDestPath || '') !== portraitPath.trim()+ || (saved?.presentationIdleDestPath || '') !== presentationIdlePath.trim()|| (saved?.codeBinding?.path || '') !== codePath.trim()|| (saved?.codeBinding?.resourcePath || '') !== resourcePath.trim()|| contractDirty;@@ -349,6 +372,12 @@ export default function PublishWorkflow({<FormField label="Atlas destination (repo-relative .png)" labelClassName={fieldLabelClass}><input value={destPath} onChange={(e) => setDestPath(e.target.value)} placeholder="assets/sprites/hero/hero-atlas.png" className={inputClass} /></FormField>+ <FormField label="Selector portrait (optional .png)" labelClassName={fieldLabelClass}>+ <input value={portraitPath} onChange={(e) => setPortraitPath(e.target.value)} placeholder="assets/portraits/hero.png" className={inputClass} />+ </FormField>+ <FormField label="Picker idle strip (optional .png)" labelClassName={fieldLabelClass}>+ <input value={presentationIdlePath} onChange={(e) => setPresentationIdlePath(e.target.value)} placeholder="assets/presentation/hero-idle.png" className={inputClass} />+ </FormField><FormField label="Code binding file (optional)" labelClassName={fieldLabelClass}><input value={codePath} onChange={(e) => setCodePath(e.target.value)} placeholder="src/Hero.cs" className={inputClass} /></FormField>@@ -472,6 +501,12 @@ export default function PublishWorkflow({<InlineConfirmRowquestion={occupiedFile === 'layout'? `${destLabel} already has a layout sidecar PortOS did not write. Overwrite it?`+ : occupiedFile === 'portrait'+ ? `The selector portrait destination already contains an image PortOS did not publish. Overwrite it?`+ : occupiedFile === 'picker animation'+ ? `The picker animation destination already contains an image PortOS did not publish. Overwrite it?`+ : occupiedFile === 'picker animation layout'+ ? `The picker animation layout destination already contains metadata PortOS did not publish. Overwrite it?`: `${destLabel} already contains an atlas PortOS did not publish. Overwrite it?`}confirmText={publishing ? 'Publishing…' : 'Overwrite'}tone="error"@@ -490,6 +525,8 @@ export default function PublishWorkflow({<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.portraitDestPath && <span>portrait: {p.portraitDestPath}</span>}+ {p.presentationIdleDestPath && <span>picker idle: {p.presentationIdleDestPath}</span>}{p.codeBinding?.rewritten && <span className="text-port-warning">code binding rewritten</span>}<span>{timeAgo(p.publishedAt)}</span></li>diff --git a/client/src/components/sprites/PublishWorkflow.test.jsx b/client/src/components/sprites/PublishWorkflow.test.jsxindex 49300f205f..b25e43e5f8 100644--- a/client/src/components/sprites/PublishWorkflow.test.jsx+++ b/client/src/components/sprites/PublishWorkflow.test.jsx@@ -102,6 +102,18 @@ const lastBindingArg = () => setSpritePublishBinding.mock.calls.at(-1)[1];describe('PublishWorkflow runtime contract', () => {beforeEach(() => setSpritePublishBinding.mockClear());+ it('saves the player-facing picker animation destination', async () => {+ renderWorkflow({ appId: 'app-1', atlasDestPath: 'assets/hero.png', codeBinding: null });++ fireEvent.change(screen.getByLabelText(/Picker idle strip/), {+ target: { value: 'assets/presentation/hero-idle.png' },+ });+ await act(async () => { fireEvent.click(screen.getByText('Save binding')); });++ expect(lastBindingArg().presentationIdleDestPath)+ .toBe('assets/presentation/hero-idle.png');+ });+it('SETS the contract from a populated field group', async () => {renderWorkflow({ appId: 'app-1', atlasDestPath: 'assets/hero.png', codeBinding: null });diff --git a/client/src/components/sprites/TrackWorkflow.jsx b/client/src/components/sprites/TrackWorkflow.jsxindex 5ba44800f2..947d1c7db9 100644--- a/client/src/components/sprites/TrackWorkflow.jsx+++ b/client/src/components/sprites/TrackWorkflow.jsx@@ -1,7 +1,7 @@import { useEffect, useMemo } from 'react';import { Check, Film, Radio, RefreshCw, Wind } from 'lucide-react';import toast from '../ui/Toast';-import { approveSpriteTrack } from '../../services/apiSprites.js';+import { approveSpriteTrack, reopenSpriteTrack } from '../../services/apiSprites.js';import { useAsyncAction } from '../../hooks/useAsyncAction.js';import { SPRITE_DIRECTIONS } from '../../lib/spriteFacets.js';import { CorrectionNoteToggle, trackCorrectionKey } from './CorrectionNote.jsx';@@ -57,6 +57,16 @@ export default function TrackWorkflow({toast.success(`${definition.label} ${directional ? `${direction} ` : ''}approved`);onChanged();}, { errorMessage: `${definition?.label || 'Track'} approval failed` });+ const [reopen, reopening] = useAsyncAction(async (direction) => {+ await reopenSpriteTrack(+ record.id,+ definition.id,+ directional ? { direction } : {},+ { silent: true },+ );+ toast.success(`${definition.label} reopened for a replacement render`);+ onChanged();+ }, { errorMessage: `${definition?.label || 'Track'} reopen failed` });// A track can only render from a locked reference, so the surface stays hidden// until one exists — otherwise it offers a Generate that always 409s. The main@@ -158,6 +168,16 @@ export default function TrackWorkflow({</div></div>)}+ {finalized && approved && (+ <button+ type="button"+ disabled={reopening}+ onClick={() => reopen(direction)}+ className="w-full rounded border border-port-warning/50 px-2 py-1 text-xs text-port-warning hover:border-port-warning disabled:opacity-50"+ >+ {reopening ? 'Reopening…' : 'Reopen for replacement'}+ </button>+ )}{run?.postprocessError && <p className="text-[10px] text-red-300">{run.postprocessError}</p>}</article>);diff --git a/client/src/services/apiSprites.js b/client/src/services/apiSprites.jsindex 1379451c59..5aa88d0440 100644--- a/client/src/services/apiSprites.js+++ b/client/src/services/apiSprites.js@@ -150,6 +150,11 @@ export const approveSpriteTrack = (id, trackId, body = {}, options = {}) => requ{ method: 'POST', body: JSON.stringify(body), ...options },);+export const reopenSpriteTrack = (id, trackId, body = {}, options = {}) => request(+ `/sprites/${encodeURIComponent(id)}/tracks/${encodeURIComponent(trackId)}/reopen`,+ { method: 'POST', body: JSON.stringify(body), ...options },+);+// Animation-type definitions (#3153) — the registry the workflow surfaces render// from, and the CRUD over the user-defined half of it. The list returns// `{ tracks, storePath, origin }` (`origin: 'seed' | 'store'` — whether thisdiff --git a/server/lib/validation.js b/server/lib/validation.jsindex acf2012ab8..a50a5db72a 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -345,6 +345,7 @@ export const gameMusicBindingSchema = z.object({export const GAME_ARTWORK_ROLES = ['title-key-art',+ 'game-logo','biome-luminous-wilds','biome-mineral-steppe','biome-tide-meadow',@@ -1287,6 +1288,12 @@ export const spritePublishBindingSchema = z.object({atlasDestPath: spriteRepoRelativePath.refine((p) => p.toLowerCase().endsWith('.png'), {message: 'atlasDestPath must point at a .png atlas file',}),+ portraitDestPath: spriteRepoRelativePath.refine((p) => p.toLowerCase().endsWith('.png'), {+ message: 'portraitDestPath must point at a .png image file',+ }).nullable().optional(),+ presentationIdleDestPath: spriteRepoRelativePath.refine((p) => p.toLowerCase().endsWith('.png'), {+ message: 'presentationIdleDestPath must point at a .png sprite strip',+ }).nullable().optional(),codeBinding: z.object({path: spriteRepoRelativePath,resourcePath: z.string().min(1).max(1024),@@ -1476,6 +1483,10 @@ export const spriteTrackApproveSchema = z.object({runId: spriteResolvableRunIdSchema,});+export const spriteTrackReopenSchema = z.object({+ direction: spriteWalkDirectionSchema.optional(),+});+// The `:trackId` path param. Shape gate only — whether the id names a REGISTERED// track (and whether this record's kind may carry it) is the service's job, so// the 404/400 names the known tracks instead of a regex failure. The charsetdiff --git a/server/routes/games.test.js b/server/routes/games.test.jsindex 57b8bb01bf..68a9ffbe4a 100644--- a/server/routes/games.test.js+++ b/server/routes/games.test.js@@ -79,6 +79,23 @@ describe('Game routes', () => {expect(games.publishGameArtwork).toHaveBeenCalledWith('game-1', 'artwork-1', {});});+ it('accepts a game logo as managed interface artwork', async () => {+ const binding = {+ imageFilename: 'example-game-logo.png',+ label: 'Example Game Logo',+ role: 'game-logo',+ destinationPath: 'game/assets/art/ui/branding/example-game-logo.png',+ };+ games.bindArtwork.mockResolvedValueOnce({ id: 'game-1', artworkBindings: [binding] });++ const response = await request(makeApp())+ .post('/api/games/game-1/artwork')+ .send(binding);++ expect(response.status).toBe(201);+ expect(games.bindArtwork).toHaveBeenCalledWith('game-1', binding);+ });+it('rejects artwork destinations that escape the managed repository', async () => {const response = await request(makeApp()).post('/api/games/game-1/artwork')diff --git a/server/routes/sprites.js b/server/routes/sprites.jsindex b750d3bfda..f54e854904 100644--- a/server/routes/sprites.js+++ b/server/routes/sprites.js@@ -24,6 +24,7 @@ import {spriteForkSchema,spriteTrackGenerateSchema,spriteTrackApproveSchema,+ spriteTrackReopenSchema,spriteTrackParamsSchema,spriteAnimationTrackCreateSchema,spriteAnimationTrackUpdateSchema,@@ -67,7 +68,9 @@ import {reopenWalkDirection, setWalkTarget, getWalkSourceFrames,unlockDirectionalAnchor, unlockMainReference, unlockTurnaroundReference,} from '../services/sprites/walk.js';-import { getTrackState, startTrackGeneration, approveTrackRun } from '../services/sprites/animationTrackWorkflow.js';+import {+ getTrackState, startTrackGeneration, approveTrackRun, reopenTrackDirection,+} from '../services/sprites/animationTrackWorkflow.js';// #3153 — CRUD over the user-defined store. Separate from the read-side store// module so `validation.js`'s import graph stays free of the record scan the// in-use refusal needs (see animationTrackCrud.js's header).@@ -343,6 +346,13 @@ router.post('/:id/tracks/:trackId/approve', asyncHandler(async (req, res) => {res.json(await approveTrackRun(trackId, req.params.id, body));}));+router.post('/:id/tracks/:trackId/reopen', asyncHandler(async (req, res) => {+ const trackId = resolveTrackParam(req.params);+ const body = validateRequest(spriteTrackReopenSchema, req.body ?? {});+ requireDirectionForTrack(trackId, body);+ res.json(await reopenTrackDirection(trackId, req.params.id, body));+}));+// Approve one direction's packaged candidate; the 8th approval freezes the// finalized walk set (immutable — 409 on later generate/approve).router.post('/:id/walk/approve', asyncHandler(async (req, res) => {diff --git a/server/services/sprites/animationTrackWorkflow.js b/server/services/sprites/animationTrackWorkflow.jsindex 0957254861..064fecb4ea 100644--- a/server/services/sprites/animationTrackWorkflow.js+++ b/server/services/sprites/animationTrackWorkflow.js@@ -515,7 +515,38 @@ export function invalidateTrackForTurnaroundRevision(trackId, recordId) {});}-async function invalidateTrackDirectionImpl(trackId, recordId, direction) {+/**+ * Deliberately reopen one approved facing (or the sole row of a non-directional+ * track) so a user can replace a finalized motion without revising its identity+ * source. Approved files remain on disk as superseded provenance.+ */+export function reopenTrackDirection(trackId, recordId, { direction: requested } = {}) {+ return withAnimationWriteTail(recordId, async () => {+ const row = effectiveTrack(trackId);+ await requireTrack(recordId, row.id);+ const direction = resolveTrackDirection(row, requested);+ const reopened = await invalidateTrackDirectionImpl(+ row.id,+ recordId,+ direction,+ 'manual-track-revision',+ );+ if (!reopened) {+ throw new ServerError(+ `${row.label} ${row.directional ? `${direction} ` : ''}has no approved render to reopen`,+ { status: 409, code: 'TRACK_NOT_APPROVED' },+ );+ }+ return getTrackState(row.id, recordId);+ });+}++async function invalidateTrackDirectionImpl(+ trackId,+ recordId,+ direction,+ supersededReason = 'directional-anchor-revised',+) {const row = effectiveTrack(trackId);const [finalizedSet, loaded] = await Promise.all([loadSet(row.id, recordId), loadSelection(row.id, recordId)]);const approved = loaded?.directions?.[direction] || finalizedSet?.directions?.[direction];@@ -530,11 +561,12 @@ async function invalidateTrackDirectionImpl(trackId, recordId, direction) {if (run?.track === row.id) {await saveRun(recordId, {...run,- status: 'superseded-anchor',+ status: supersededReason === 'manual-track-revision' ? 'superseded' : 'superseded-anchor',supersededAt: new Date().toISOString(),- supersededReason: 'directional-anchor-revised',+ supersededReason,});}- console.log(`♻️ sprite ${row.id} direction ${recordId}/${direction} invalidated after anchor revision`);+ const reasonLabel = supersededReason === 'manual-track-revision' ? 'manual revision' : 'anchor revision';+ console.log(`♻️ sprite ${row.id} direction ${recordId}/${direction} reopened after ${reasonLabel}`);return true;}diff --git a/server/services/sprites/animationTrackWorkflow.test.js b/server/services/sprites/animationTrackWorkflow.test.jsindex 6d8494a701..6af9bf5e93 100644--- a/server/services/sprites/animationTrackWorkflow.test.js+++ b/server/services/sprites/animationTrackWorkflow.test.js@@ -62,7 +62,7 @@ const records = await import('./records.js');const { lockReference } = await import('./reference.js');const {getTrackState, startTrackGeneration, approveTrackRun, trackAuthoringDirections, trackSetRelPath,- recordsCarryingTrack,+ recordsCarryingTrack, reopenTrackDirection,} = await import('./animationTrackWorkflow.js');const {getAnimationTrack, sourceReferenceFor, SCANNER_TRACK, AMBIENT_TRACK,@@ -311,6 +311,38 @@ describe('registry-derived authoring shape (#3136)', () => {// The sentinel rule: a mis-keyed track must not silently author walk state.await expect(getTrackState('jetpack', 'pioneer')).rejects.toThrow(/Unknown animation track 'jetpack'/);});++ it('reopens a finalized non-directional row while retaining its evidence', async () => {+ const id = newId();+ await records.createRecord({ kind: 'place', name: 'Example Willow' }, id);+ const runId = 'ambient-approved-run';+ const recordDir = join(TEST_ROOT, 'sprites', id);+ await mkdir(join(recordDir, 'ambient'), { recursive: true });+ await mkdir(join(recordDir, 'runs', runId), { recursive: true });+ await writeFile(join(recordDir, 'runs', runId, 'animation-run.json'), JSON.stringify({+ track: AMBIENT_TRACK,+ id: runId,+ status: 'candidate',+ }));+ await writeFile(join(recordDir, `ambient/${id}-ambient-selection-v1.json`), JSON.stringify({+ kind: 'reviewed-single-row-ambient-selection',+ status: 'complete',+ directions: { south: { status: 'approved', runId } },+ }));+ await writeFile(join(recordDir, trackSetRelPath(AMBIENT_TRACK, id)), JSON.stringify({+ kind: 'finalized-single-row-ambient-set',+ directions: { south: { status: 'approved', runId } },+ }));++ const reopened = await reopenTrackDirection(AMBIENT_TRACK, id);+ expect(reopened.set).toBeNull();+ expect(reopened.selection.status).toBe('in-progress');+ expect(reopened.selection.directions).toEqual({});+ expect(reopened.runs.find((run) => run.id === runId)).toMatchObject({+ status: 'superseded',+ supersededReason: 'manual-track-revision',+ });+ });});describe('recordsCarryingTrack (#3153)', () => {diff --git a/server/services/sprites/atlas.js b/server/services/sprites/atlas.jsindex 07f17e052d..581151f495 100644--- a/server/services/sprites/atlas.js+++ b/server/services/sprites/atlas.js@@ -45,8 +45,8 @@ import { SPRITE_DIRECTIONS } from './prompts.js';import { keyChannelSplit } from './chromaKey.js';import {WALK_PHASES, WALK_FPS,- pyRound, pyRoundTo, median, decodeRgbaFrame, premultipliedResize,- sampleBorderKey, validateMeasuredKey, recoverAlphaFrame, despillKeyFrame,+ pyRound, pyRoundTo, median, premultipliedResize, decodeTransparentSpriteSource,+ despillKeyFrame,alphaBbox, robustBottomRow, rootX, rootBandForManifest, ROBUST_BASELINE_MIN_PIXELS, compositeOnto, sha256Buffer,} from './walkPostprocess.js';import { ATLAS_IDLE_COLUMN } from './walkBounds.js';@@ -148,29 +148,6 @@ function occupiedDimensions(frame, threshold, label, robust = false) {return { width: bounds.right - bounds.left, height: bottom - bounds.top };}-/**- * Decode a validated source buffer 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. Takes the in-memory bytes validateForCompile already hashed, so- * the pixels compiled are provably the pixels verified.- */-async function transparentSource(bytes, split, keyHex) {- const frame = await decodeRgbaFrame(bytes);- 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 measure what placement needs from it: the bbox* the cell-edge guards test, and the sole the ground line is pinned to.@@ -483,7 +460,7 @@ async function prepareTrackCells(track, direction, validated, geometry, split) {const sources = [];for (const bytes of run.frameBytes) {// eslint-disable-next-line no-await-in-loop -- sharp transforms preserve frame order- sources.push(await transparentSource(bytes, split, validated.chromaKey));+ sources.push(await decodeTransparentSpriteSource(bytes, split, validated.chromaKey));}const dims = sources.map((source, index) => occupiedDimensions(source,@@ -552,7 +529,7 @@ async function compileTrackRow(direction, validated, geometry) {? 'locked-directional-reference-anchor': 'locked-main-reference';const idleLabel = `${direction}-idle`;- const idleSource = await transparentSource(source.bytes, split, validated.chromaKey);+ const idleSource = await decodeTransparentSpriteSource(source.bytes, split, validated.chromaKey);const idleDims = occupiedDimensions(idleSource, SILHOUETTE_ALPHA_THRESHOLD, idleLabel);const desiredIdleHeight = median(primary.dims.map((dim) => dim.height)) * primary.scale;const idleScale = Math.min(desiredIdleHeight / idleDims.height, geometry.targetMaxWidth / idleDims.width);diff --git a/server/services/sprites/presentationIdle.js b/server/services/sprites/presentationIdle.jsnew file mode 100644index 0000000000..573f38e5d6--- /dev/null+++ b/server/services/sprites/presentationIdle.js@@ -0,0 +1,143 @@+/**+ * High-resolution, player-facing idle animation derived from the approved+ * `idle-loop` track. Runtime atlases optimize for compact gameplay cells; this+ * horizontal strip keeps the authored source frames at menu presentation size.+ */++import { readFile } from 'fs/promises';+import { basename } from 'path';+import sharp from 'sharp';+import { ServerError } from '../../lib/errorHandler.js';+import { keyChannelSplit } from './chromaKey.js';+import { getTrackState } from './animationTrackWorkflow.js';+import { resolveSpriteAssetPath } from './paths.js';+import { loadManifest } from './reference.js';+import { getRecord } from './records.js';+import { resolveChromaKey } from './walk.js';+import { verifyPackagedFrames } from './walkFrames.js';+import { decodeTransparentSpriteSource, sha256Buffer } from './walkPostprocess.js';++export const PRESENTATION_IDLE_TRACK_ID = 'idle-loop';+export const PRESENTATION_IDLE_CELL_SIZE = 512;+export const PRESENTATION_IDLE_LAYOUT_KIND = 'portos-presentation-animation-layout';++export const presentationIdleSidecarPath = (destPath) =>+ destPath.replace(/\.png$/i, '.presentation.json');++export function buildPresentationIdleLayout(presentationIdle, destPath) {+ return {+ schemaVersion: 1,+ kind: PRESENTATION_IDLE_LAYOUT_KIND,+ track: PRESENTATION_IDLE_TRACK_ID,+ imageFile: basename(destPath),+ imageSha256: presentationIdle.sha256,+ frameCount: presentationIdle.frameCount,+ frameRate: presentationIdle.frameRate,+ cellSize: presentationIdle.cellSize,+ sourceManifestPath: presentationIdle.sourceManifestPath,+ sourceManifestSha256: presentationIdle.sourceManifestSha256,+ sourceFrameSha256s: presentationIdle.sourceFrameSha256s,+ };+}++const idleError = (message, code) =>+ new ServerError(message, { status: 422, code });++export async function composePresentationIdleStrip(frameBytes, chromaKey) {+ if (!Array.isArray(frameBytes) || frameBytes.length === 0) {+ throw idleError('The approved idle loop has no presentation frames', 'PRESENTATION_IDLE_FRAMES_REQUIRED');+ }++ const split = keyChannelSplit(chromaKey);+ const tiles = [];+ for (let index = 0; index < frameBytes.length; index++) {+ // eslint-disable-next-line no-await-in-loop -- frame order is the animation order+ const frame = await decodeTransparentSpriteSource(frameBytes[index], split, chromaKey);+ // eslint-disable-next-line no-await-in-loop -- each normalized tile feeds the ordered strip+ const input = await sharp(frame.data, {+ raw: { width: frame.width, height: frame.height, channels: 4 },+ })+ .resize(PRESENTATION_IDLE_CELL_SIZE, PRESENTATION_IDLE_CELL_SIZE, {+ fit: 'contain',+ background: { r: 0, g: 0, b: 0, alpha: 0 },+ kernel: sharp.kernel.nearest,+ })+ .png()+ .toBuffer();+ tiles.push({ input, left: index * PRESENTATION_IDLE_CELL_SIZE, top: 0 });+ }++ return sharp({+ create: {+ width: PRESENTATION_IDLE_CELL_SIZE * tiles.length,+ height: PRESENTATION_IDLE_CELL_SIZE,+ channels: 4,+ background: { r: 0, g: 0, b: 0, alpha: 0 },+ },+ })+ .composite(tiles)+ .png()+ .toBuffer();+}++export async function buildPresentationIdle(recordId) {+ const [record, referenceManifest, state] = await Promise.all([+ getRecord(recordId),+ loadManifest(recordId),+ getTrackState(PRESENTATION_IDLE_TRACK_ID, recordId),+ ]);+ const set = state?.set;+ const directionEntries = Object.entries(set?.directions || {});+ if (set?.status !== 'final'+ || set?.track !== PRESENTATION_IDLE_TRACK_ID+ || directionEntries.length !== 1) {+ throw idleError(+ 'Approve the complete idle-loop track before publishing a picker animation',+ 'PRESENTATION_IDLE_TRACK_REQUIRED',+ );+ }++ const [direction, approved] = directionEntries[0];+ if (approved?.status !== 'approved' || !approved.runManifest || !approved.runManifestSha256) {+ throw idleError(+ 'The finalized idle-loop track has no approved source manifest',+ 'PRESENTATION_IDLE_TRACK_INVALID',+ );+ }++ const manifestBytes = await readFile(+ resolveSpriteAssetPath(recordId, approved.runManifest),+ ).catch(() => null);+ if (!manifestBytes || sha256Buffer(manifestBytes) !== approved.runManifestSha256) {+ throw idleError(+ 'The approved idle-loop manifest is missing or no longer matches its recorded hash',+ 'PRESENTATION_IDLE_TRACK_INVALID',+ );+ }++ const runManifest = JSON.parse(manifestBytes);+ if (runManifest.track !== PRESENTATION_IDLE_TRACK_ID+ || runManifest.direction !== direction) {+ throw idleError(+ 'The approved idle-loop manifest is mislabeled',+ 'PRESENTATION_IDLE_TRACK_INVALID',+ );+ }+ const { frameBytes } = await verifyPackagedFrames(recordId, runManifest, {+ bytes: true,+ track: PRESENTATION_IDLE_TRACK_ID,+ });+ const chromaKey = resolveChromaKey({ manifest: referenceManifest, record });+ const buffer = await composePresentationIdleStrip(frameBytes, chromaKey);++ return {+ buffer,+ sha256: sha256Buffer(buffer),+ sourceManifestPath: approved.runManifest,+ sourceManifestSha256: approved.runManifestSha256,+ sourceFrameSha256s: runManifest.frames.map((frame) => frame.sha256),+ frameCount: frameBytes.length,+ frameRate: runManifest.frameRate,+ cellSize: PRESENTATION_IDLE_CELL_SIZE,+ };+}diff --git a/server/services/sprites/presentationIdle.test.js b/server/services/sprites/presentationIdle.test.jsnew file mode 100644index 0000000000..9132fc96b9--- /dev/null+++ b/server/services/sprites/presentationIdle.test.js@@ -0,0 +1,64 @@+import { describe, expect, it } from 'vitest';+import sharp from 'sharp';+import {+ buildPresentationIdleLayout,+ composePresentationIdleStrip,+ PRESENTATION_IDLE_CELL_SIZE,+ PRESENTATION_IDLE_LAYOUT_KIND,+ presentationIdleSidecarPath,+} from './presentationIdle.js';++const chromaFrame = async (offset) => {+ const width = 32;+ const height = 24;+ const pixels = Buffer.alloc(width * height * 3);+ for (let y = 0; y < height; y++) {+ for (let x = 0; x < width; x++) {+ const index = ((y * width) + x) * 3;+ const subject = x >= 8 + offset && x < 18 + offset && y >= 4 && y < 22;+ pixels[index] = subject ? 20 : 255;+ pixels[index + 1] = subject ? 90 : 0;+ pixels[index + 2] = subject ? 110 : 255;+ }+ }+ return sharp(pixels, { raw: { width, height, channels: 3 } }).png().toBuffer();+};++describe('presentation idle strip', () => {+ it('preserves approved frame order in transparent presentation-size cells', async () => {+ const strip = await composePresentationIdleStrip(+ await Promise.all([chromaFrame(0), chromaFrame(2), chromaFrame(4)]),+ '#FF00FF',+ );+ const metadata = await sharp(strip).metadata();+ expect(metadata).toMatchObject({+ width: PRESENTATION_IDLE_CELL_SIZE * 3,+ height: PRESENTATION_IDLE_CELL_SIZE,+ channels: 4,+ });+ const raw = await sharp(strip).ensureAlpha().raw().toBuffer();+ expect(raw[3]).toBe(0);+ expect(raw[((256 * metadata.width + 256) * 4) + 3]).toBeGreaterThan(0);+ });++ it('describes the strip with a deterministic consumer sidecar', () => {+ const path = 'assets/presentation/hero-idle.png';+ const layout = buildPresentationIdleLayout({+ sha256: 'a'.repeat(64),+ frameCount: 6,+ frameRate: 6,+ cellSize: 512,+ sourceManifestPath: 'idle-loop/approved.json',+ sourceManifestSha256: 'b'.repeat(64),+ sourceFrameSha256s: ['c'.repeat(64)],+ }, path);+ expect(presentationIdleSidecarPath(path)).toBe('assets/presentation/hero-idle.presentation.json');+ expect(layout).toMatchObject({+ kind: PRESENTATION_IDLE_LAYOUT_KIND,+ imageFile: 'hero-idle.png',+ frameCount: 6,+ frameRate: 6,+ cellSize: 512,+ });+ });+});diff --git a/server/services/sprites/presentationPortrait.js b/server/services/sprites/presentationPortrait.jsnew file mode 100644index 0000000000..099413698b--- /dev/null+++ b/server/services/sprites/presentationPortrait.js@@ -0,0 +1,60 @@+/**+ * Deterministic high-resolution presentation portrait derived from a sprite's+ * locked identity master. Runtime atlases optimize for gameplay cells; menus+ * should not upscale those cells when the immutable source art is available.+ */++import { readFile } from 'fs/promises';+import sharp from 'sharp';+import { ServerError } from '../../lib/errorHandler.js';+import { keyChannelSplit } from './chromaKey.js';+import { resolveSpriteAssetPath } from './paths.js';+import { loadManifest } from './reference.js';+import { resolveChromaKey } from './walk.js';+import { decodeTransparentSpriteSource, sha256Buffer } from './walkPostprocess.js';++export const PRESENTATION_PORTRAIT_SIZE = 512;++export async function buildPresentationPortrait(recordId, record) {+ const manifest = await loadManifest(recordId);+ const source = manifest?.mainReference;+ if (!source?.locked || !source.path) {+ throw new ServerError(+ 'Lock the main reference before publishing a presentation portrait',+ { status: 422, code: 'PORTRAIT_REFERENCE_REQUIRED' },+ );+ }++ const sourceAbs = resolveSpriteAssetPath(recordId, source.path);+ const sourceBuffer = await readFile(sourceAbs).catch(() => null);+ if (!sourceBuffer) {+ throw new ServerError(+ 'The locked main reference is missing on disk',+ { status: 422, code: 'PORTRAIT_REFERENCE_MISSING' },+ );+ }++ const chromaKey = resolveChromaKey({ manifest, record });+ const frame = await decodeTransparentSpriteSource(+ sourceBuffer,+ keyChannelSplit(chromaKey),+ chromaKey,+ );+ const portraitBuffer = await sharp(frame.data, {+ raw: { width: frame.width, height: frame.height, channels: 4 },+ })+ .resize(PRESENTATION_PORTRAIT_SIZE, PRESENTATION_PORTRAIT_SIZE, {+ fit: 'fill',+ kernel: sharp.kernel.nearest,+ })+ .png()+ .toBuffer();++ return {+ buffer: portraitBuffer,+ sha256: sha256Buffer(portraitBuffer),+ sourcePath: source.path,+ sourceSha256: sha256Buffer(sourceBuffer),+ size: PRESENTATION_PORTRAIT_SIZE,+ };+}diff --git a/server/services/sprites/publish.js b/server/services/sprites/publish.jsindex 1669b3f9e9..8c7323337a 100644--- a/server/services/sprites/publish.js+++ b/server/services/sprites/publish.js@@ -3,7 +3,8 @@* (issue #2898, phase 4).** The game consumes sprites from its own tree; PortOS owns provenance. A- * per-record `publishBinding` ({ appId, atlasDestPath, codeBinding? }) names+ * per-record `publishBinding` ({ appId, atlasDestPath, portraitDestPath?,+ * presentationIdleDestPath?, 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@@ -49,6 +50,13 @@ import { spriteRuntimeContractSchema } from '../../lib/validation.js';import {ATLAS_LAYOUT_KIND, buildAtlasLayout, layoutSidecarPath, runtimeContractMismatch,} from './atlasLayout.js';+import { buildPresentationPortrait } from './presentationPortrait.js';+import {+ buildPresentationIdle,+ buildPresentationIdleLayout,+ PRESENTATION_IDLE_LAYOUT_KIND,+ presentationIdleSidecarPath,+} from './presentationIdle.js';// Per-repo serialization: keyed by the resolved repoPath (matching// appDeployer's `deployingApps` key), so two app records pointing at the@@ -123,12 +131,21 @@ function validateRuntimeContract(runtimeContract) {/** Validate a publishBinding shape (null clears it). */export async function validatePublishBinding(binding) {if (binding === null) return null;- const { appId, atlasDestPath, codeBinding, runtimeContract } = binding;+ const {+ appId, atlasDestPath, portraitDestPath, presentationIdleDestPath,+ codeBinding, runtimeContract,+ } = binding;const { app } = await requireAppRepo(appId, 400);anchorRepoPath(app.repoPath, atlasDestPath, 'atlasDestPath');// The sidecar lands beside the atlas, so its path must anchor too — catch a// destination whose sidecar would escape the repo at SAVE time, not mid-publish.anchorRepoPath(app.repoPath, layoutSidecarPath(atlasDestPath), 'atlas layout sidecar');+ if (portraitDestPath) {+ anchorRepoPath(app.repoPath, portraitDestPath, 'portraitDestPath');+ }+ if (presentationIdleDestPath) {+ anchorRepoPath(app.repoPath, presentationIdleDestPath, 'presentationIdleDestPath');+ }if (codeBinding) {anchorRepoPath(app.repoPath, codeBinding.path, 'codeBinding.path');if (typeof codeBinding.resourcePath !== 'string' || !codeBinding.resourcePath.trim()) {@@ -138,6 +155,8 @@ export async function validatePublishBinding(binding) {return {appId,atlasDestPath,+ ...(portraitDestPath === undefined ? {} : { portraitDestPath }),+ ...(presentationIdleDestPath === undefined ? {} : { presentationIdleDestPath }),codeBinding: codeBinding? {path: codeBinding.path,@@ -177,6 +196,12 @@ export async function setPublishBinding(recordId, binding) {if (validated && binding.runtimeContract === undefined && validated.appId === stored?.appId) {validated.runtimeContract = stored.runtimeContract ?? null;}+ if (validated && binding.portraitDestPath === undefined && validated.appId === stored?.appId) {+ validated.portraitDestPath = stored.portraitDestPath ?? null;+ }+ if (validated && binding.presentationIdleDestPath === undefined && validated.appId === stored?.appId) {+ validated.presentationIdleDestPath = stored.presentationIdleDestPath ?? null;+ }return updateRecord(recordId, { publishBinding: validated });}@@ -199,6 +224,8 @@ export async function listPublishBindingsForApp(appId) {name: r.name || r.id,kind: r.kind || null,atlasDestPath: r.publishBinding.atlasDestPath || null,+ portraitDestPath: r.publishBinding.portraitDestPath || null,+ presentationIdleDestPath: r.publishBinding.presentationIdleDestPath || null,codeBindingPath: r.publishBinding.codeBinding?.path || null,}));}@@ -298,6 +325,24 @@ async function publishAtlasImpl(recordId, { acknowledgeOverwrite = false } = {})const layoutBuffer = Buffer.from(`${JSON.stringify(layout, null, 2)}\n`);const layoutSha256 = sha256Buffer(layoutBuffer);const layoutDestPath = layoutSidecarPath(binding.atlasDestPath);+ const portrait = binding.portraitDestPath+ ? await buildPresentationPortrait(recordId, record)+ : null;+ const presentationIdle = binding.presentationIdleDestPath+ ? await buildPresentationIdle(recordId)+ : null;+ const presentationIdleLayout = presentationIdle+ ? buildPresentationIdleLayout(presentationIdle, binding.presentationIdleDestPath)+ : null;+ const presentationIdleLayoutBuffer = presentationIdleLayout+ ? Buffer.from(`${JSON.stringify(presentationIdleLayout, null, 2)}\n`)+ : null;+ const presentationIdleLayoutSha256 = presentationIdleLayoutBuffer+ ? sha256Buffer(presentationIdleLayoutBuffer)+ : null;+ const presentationIdleLayoutDestPath = presentationIdle+ ? presentationIdleSidecarPath(binding.presentationIdleDestPath)+ : null;return repoPublishTail(resolve(repoRoot), async () => {// Don't mutate a tree a deploy is currently building from — appDeployer@@ -311,6 +356,15 @@ async function publishAtlasImpl(recordId, { acknowledgeOverwrite = false } = {})// as the PNG, so the pair is never interleaved with another publish into// the same checkout.const layoutAbs = anchorRepoPath(repoRoot, layoutDestPath, 'atlas layout sidecar');+ const portraitAbs = portrait+ ? anchorRepoPath(repoRoot, binding.portraitDestPath, 'portraitDestPath')+ : null;+ const presentationIdleAbs = presentationIdle+ ? anchorRepoPath(repoRoot, binding.presentationIdleDestPath, 'presentationIdleDestPath')+ : null;+ const presentationIdleLayoutAbs = presentationIdle+ ? anchorRepoPath(repoRoot, presentationIdleLayoutDestPath, 'picker animation sidecar')+ : null;const existingLayout = await readFile(layoutAbs).catch(() => null);const layoutUpToDate = Boolean(existingLayout?.equals(layoutBuffer));// Occupied-destination guard, mirroring the atlas's: PortOS owns files it@@ -364,6 +418,17 @@ async function publishAtlasImpl(recordId, { acknowledgeOverwrite = false } = {})(p) => p.appId === binding.appId && p.codeBinding?.path === binding.codeBinding.path,): null;+ const previousPortrait = portrait+ ? [...publications].reverse().find(+ (p) => p.appId === binding.appId && p.portraitDestPath === binding.portraitDestPath,+ )+ : null;+ const previousPresentationIdle = presentationIdle+ ? [...publications].reverse().find(+ (p) => p.appId === binding.appId+ && p.presentationIdleDestPath === binding.presentationIdleDestPath,+ )+ : null;const recordPublication = async (extra) => {const publication = {@@ -375,6 +440,21 @@ async function publishAtlasImpl(recordId, { acknowledgeOverwrite = false } = {})appId: binding.appId,appName: app.name || null,atlasDestPath: binding.atlasDestPath,+ portraitDestPath: binding.portraitDestPath || null,+ portraitSha256: portrait?.sha256 || null,+ portraitSourcePath: portrait?.sourcePath || null,+ portraitSourceSha256: portrait?.sourceSha256 || null,+ portraitSize: portrait?.size || null,+ presentationIdleDestPath: binding.presentationIdleDestPath || null,+ presentationIdleSha256: presentationIdle?.sha256 || null,+ presentationIdleSourceManifestPath: presentationIdle?.sourceManifestPath || null,+ presentationIdleSourceManifestSha256: presentationIdle?.sourceManifestSha256 || null,+ presentationIdleSourceFrameSha256s: presentationIdle?.sourceFrameSha256s || null,+ presentationIdleFrameCount: presentationIdle?.frameCount || null,+ presentationIdleFrameRate: presentationIdle?.frameRate || null,+ presentationIdleCellSize: presentationIdle?.cellSize || null,+ presentationIdleLayoutDestPath,+ presentationIdleLayoutSha256,...extra,};publications.push(publication);@@ -382,9 +462,91 @@ async function publishAtlasImpl(recordId, { acknowledgeOverwrite = false } = {})return publication;};+ const portraitDestSha256 = portrait && await pathExists(portraitAbs)+ ? await sha256File(portraitAbs)+ : null;+ const portraitUpToDate = Boolean(portrait && portraitDestSha256 === portrait.sha256);+ const assertPortraitDestWritable = () => {+ if (!portrait || portraitUpToDate || acknowledgeOverwrite || portraitDestSha256 === null) return;+ if (previousPortrait && portraitDestSha256 !== previousPortrait.portraitSha256) {+ throw new ServerError(+ 'Destination portrait no longer matches the previous publish — it was changed outside PortOS. Resolve it in the game repo, then re-publish.',+ { status: 409, code: 'PUBLISH_PORTRAIT_DIVERGED' },+ );+ }+ if (!previousPortrait) {+ throw new ServerError(+ 'Destination already contains a portrait PortOS did not publish — confirm the overwrite to replace it.',+ { status: 409, code: 'PUBLISH_PORTRAIT_OCCUPIED' },+ );+ }+ };+ const writePortrait = async () => {+ if (!portrait || portraitUpToDate) return false;+ await atomicWrite(portraitAbs, portrait.buffer);+ return true;+ };+ const presentationIdleDestSha256 = presentationIdle && await pathExists(presentationIdleAbs)+ ? await sha256File(presentationIdleAbs)+ : null;+ const presentationIdleUpToDate = Boolean(+ presentationIdle && presentationIdleDestSha256 === presentationIdle.sha256,+ );+ const assertPresentationIdleDestWritable = () => {+ if (!presentationIdle+ || presentationIdleUpToDate+ || acknowledgeOverwrite+ || presentationIdleDestSha256 === null) return;+ if (previousPresentationIdle+ && presentationIdleDestSha256 !== previousPresentationIdle.presentationIdleSha256) {+ throw new ServerError(+ 'Destination picker animation no longer matches the previous publish — it was changed outside PortOS. Resolve it in the game repo, then re-publish.',+ { status: 409, code: 'PUBLISH_PRESENTATION_IDLE_DIVERGED' },+ );+ }+ if (!previousPresentationIdle) {+ throw new ServerError(+ 'Destination already contains a picker animation PortOS did not publish — confirm the overwrite to replace it.',+ { status: 409, code: 'PUBLISH_PRESENTATION_IDLE_OCCUPIED' },+ );+ }+ };+ const writePresentationIdle = async () => {+ if (!presentationIdle || presentationIdleUpToDate) return false;+ await atomicWrite(presentationIdleAbs, presentationIdle.buffer);+ return true;+ };+ const existingPresentationIdleLayout = presentationIdle+ ? await readFile(presentationIdleLayoutAbs).catch(() => null)+ : null;+ const presentationIdleLayoutUpToDate = Boolean(+ existingPresentationIdleLayout?.equals(presentationIdleLayoutBuffer),+ );+ const assertPresentationIdleLayoutWritable = () => {+ if (!presentationIdle+ || presentationIdleLayoutUpToDate+ || acknowledgeOverwrite+ || !existingPresentationIdleLayout) return;+ if (safeJSONParse(existingPresentationIdleLayout.toString('utf8'))?.kind+ !== PRESENTATION_IDLE_LAYOUT_KIND) {+ throw new ServerError(+ `${presentationIdleLayoutDestPath} already exists and was not written by PortOS — confirm the overwrite to replace it.`,+ { status: 409, code: 'PUBLISH_PRESENTATION_IDLE_LAYOUT_OCCUPIED' },+ );+ }+ };+ const writePresentationIdleLayout = async () => {+ if (!presentationIdle || presentationIdleLayoutUpToDate) return false;+ await atomicWrite(presentationIdleLayoutAbs, presentationIdleLayoutBuffer);+ return true;+ };+const destSha256 = (await pathExists(destAbs)) ? await sha256File(destAbs) : null;if (destSha256 === compiled.atlasSha256) {assertLayoutDestWritable();+ assertPortraitDestWritable();+ assertPresentationIdleDestWritable();+ assertPresentationIdleLayoutWritable();// Verify the code binding even on a no-op so drift never hides.const codeBinding = binding.codeBinding? await applyCodeBinding(repoRoot, binding.codeBinding, previousForCode?.codeBinding?.resourcePath)@@ -393,6 +555,9 @@ async function publishAtlasImpl(recordId, { acknowledgeOverwrite = false } = {})// sidecar — from a publish that predates it, or a hand-deleted file.// Reconcile it here so the pair converges on the next publish.const layoutWritten = await writeLayoutSidecar();+ const portraitWritten = await writePortrait();+ const presentationIdleLayoutWritten = await writePresentationIdleLayout();+ const presentationIdleWritten = await writePresentationIdle();// The destination already holds the current bytes, but three sub-cases// still mutate durable state and must be recorded: a code-binding// rewrite just changed the game's source, the sidecar was just written,@@ -400,13 +565,29 @@ async function publishAtlasImpl(recordId, { acknowledgeOverwrite = false } = {})// baseline (otherwise the next changed-atlas publish reads the dest as// foreign and 409s OCCUPIED).let publication = null;- if ((codeBinding?.rewritten || layoutWritten || !previous)) {+ if ((codeBinding?.rewritten+ || layoutWritten+ || portraitWritten+ || presentationIdleLayoutWritten+ || presentationIdleWritten+ || !previous+ || (portrait && !previousPortrait)+ || (presentationIdle && !previousPresentationIdle))) {publication = await recordPublication({destPreviousSha256: destSha256, codeBinding, layoutDestPath, layoutSha256, upToDateBaseline: true,});}return {- published: false, upToDate: true, compiled, codeBinding, publication, layoutWritten, layoutDestPath,+ published: false,+ upToDate: true,+ compiled,+ codeBinding,+ publication,+ layoutWritten,+ layoutDestPath,+ portraitWritten,+ presentationIdleWritten,+ presentationIdleLayoutWritten,};}if (previous && destSha256 !== null && destSha256 !== previous.atlasSha256) {@@ -429,6 +610,9 @@ async function publishAtlasImpl(recordId, { acknowledgeOverwrite = false } = {})// binding aborts the publish with the game repo untouched — and assert the// sidecar destination first, since that rewrite is itself a mutation.assertLayoutDestWritable();+ assertPortraitDestWritable();+ assertPresentationIdleDestWritable();+ assertPresentationIdleLayoutWritable();const codeBinding = binding.codeBinding? await applyCodeBinding(repoRoot, binding.codeBinding, previousForCode?.codeBinding?.resourcePath): null;@@ -439,12 +623,24 @@ async function publishAtlasImpl(recordId, { acknowledgeOverwrite = false } = {})// new atlas under a stale/absent layout is exactly the silent column shift// this whole contract exists to prevent.const layoutWritten = await writeLayoutSidecar();+ const portraitWritten = await writePortrait();+ const presentationIdleLayoutWritten = await writePresentationIdleLayout();+ const presentationIdleWritten = await writePresentationIdle();await atomicWrite(destAbs, atlasBuffer);const publication = await recordPublication({destPreviousSha256: destSha256, codeBinding, layoutDestPath, layoutSha256,});console.log(`🚚 sprite atlas v${compiled.version} published for ${recordId} → ${appLabel}:${binding.atlasDestPath}`);- return { published: true, publication, compiled, layoutWritten, layoutDestPath };+ return {+ published: true,+ publication,+ compiled,+ layoutWritten,+ layoutDestPath,+ portraitWritten,+ presentationIdleWritten,+ presentationIdleLayoutWritten,+ };});}diff --git a/server/services/sprites/publish.test.js b/server/services/sprites/publish.test.jsindex 0cc7bc8ecc..b684035daf 100644--- a/server/services/sprites/publish.test.js+++ b/server/services/sprites/publish.test.js@@ -16,6 +16,7 @@ import { tmpdir } from 'os';import { join } from 'path';import { mkdir, writeFile, readFile } from 'fs/promises';import { createHash } from 'crypto';+import sharp from 'sharp';import { trackSpan as fullSpan } from './spriteTestFixtures.js';const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-publish-test-'));@@ -45,6 +46,20 @@ const compileAtlasInTail = vi.fn();vi.mock('./atlas.js', () => ({compileAtlasInTail: (...args) => compileAtlasInTail(...args),}));+const presentationIdleMocks = vi.hoisted(() => ({ buildPresentationIdle: vi.fn() }));+vi.mock('./presentationIdle.js', () => ({+ ...presentationIdleMocks,+ PRESENTATION_IDLE_LAYOUT_KIND: 'portos-presentation-animation-layout',+ presentationIdleSidecarPath: (path) => path.replace(/\.png$/, '.presentation.json'),+ buildPresentationIdleLayout: (idle, path) => ({+ kind: 'portos-presentation-animation-layout',+ imageFile: path.split('/').at(-1),+ imageSha256: idle.sha256,+ frameCount: idle.frameCount,+ frameRate: idle.frameRate,+ cellSize: idle.cellSize,+ }),+}));const records = await import('./records.js');const { setPublishBinding, publishAtlas, validatePublishBinding, listPublishBindingsForApp } = await import('./publish.js');@@ -98,11 +113,42 @@ async function characterWithAtlas(atlasBytes = 'atlas-png-bytes-v1', geometry =const BINDING = { appId: 'game-app', atlasDestPath: 'assets/sprites/hero/hero-atlas.png' };+async function addLockedMainReference(id) {+ const referenceDir = join(TEST_ROOT, 'sprites', id, 'reference');+ await mkdir(referenceDir, { recursive: true });+ const width = 32;+ const height = 32;+ const pixels = Buffer.alloc(width * height * 3);+ for (let y = 0; y < height; y++) {+ for (let x = 0; x < width; x++) {+ const index = (y * width + x) * 3;+ const subject = x >= 10 && x < 22 && y >= 6 && y < 28;+ pixels[index] = subject ? 18 : 255;+ pixels[index + 1] = subject ? 84 : 0;+ pixels[index + 2] = subject ? 102 : 255;+ }+ }+ const sourcePath = `reference/${id}-walk-south-v1.png`;+ await sharp(pixels, { raw: { width, height, channels: 3 } })+ .png()+ .toFile(join(TEST_ROOT, 'sprites', id, sourcePath));+ await writeFile(+ join(referenceDir, `${id}-reference-set-v1.json`),+ JSON.stringify({+ schemaVersion: 2,+ chromaKey: '#FF00FF',+ mainReference: { path: sourcePath, locked: true },+ anchors: [],+ }),+ );+}+beforeEach(async () => {getAppById.mockClear();isDeploying.mockReset();isDeploying.mockReturnValue(false);compileAtlasInTail.mockReset();+ presentationIdleMocks.buildPresentationIdle.mockReset();rmSync(join(TEST_ROOT, 'sprite-records.json'), { force: true });rmSync(APP_REPO, { recursive: true, force: true });rmSync(OTHER_APP_REPO, { recursive: true, force: true });@@ -265,6 +311,73 @@ describe('publishAtlas', () => {expect(history).toHaveLength(1);});+ it('publishes a transparent 512px presentation portrait from the locked identity master', async () => {+ const { id } = await characterWithAtlas();+ await addLockedMainReference(id);+ const portraitDestPath = 'assets/portraits/hero.png';+ await setPublishBinding(id, { ...BINDING, portraitDestPath });++ const result = await publishAtlas(id);+ expect(result.portraitWritten).toBe(true);+ expect(result.publication).toMatchObject({+ portraitDestPath,+ portraitSize: 512,+ portraitSha256: expect.stringMatching(/^[0-9a-f]{64}$/),+ portraitSourcePath: `reference/${id}-walk-south-v1.png`,+ });+ const portraitAbs = join(APP_REPO, portraitDestPath);+ const metadata = await sharp(portraitAbs).metadata();+ expect(metadata).toMatchObject({ width: 512, height: 512, channels: 4 });+ const raw = await sharp(portraitAbs).ensureAlpha().raw().toBuffer();+ expect(raw[3]).toBe(0);+ const centerAlpha = raw[((256 * 512 + 256) * 4) + 3];+ expect(centerAlpha).toBe(255);+ });++ it('publishes a presentation-resolution picker idle strip with source provenance', async () => {+ const { id } = await characterWithAtlas();+ const presentationIdleDestPath = 'assets/presentation/hero-idle.png';+ const strip = await sharp({+ create: {+ width: 512 * 3,+ height: 512,+ channels: 4,+ background: { r: 20, g: 90, b: 110, alpha: 1 },+ },+ }).png().toBuffer();+ presentationIdleMocks.buildPresentationIdle.mockResolvedValue({+ buffer: strip,+ sha256: sha256(strip),+ sourceManifestPath: 'idle-loop/approved-run.json',+ sourceManifestSha256: 'a'.repeat(64),+ sourceFrameSha256s: ['b'.repeat(64), 'c'.repeat(64), 'd'.repeat(64)],+ frameCount: 3,+ frameRate: 6,+ cellSize: 512,+ });+ await setPublishBinding(id, { ...BINDING, presentationIdleDestPath });++ const result = await publishAtlas(id);+ expect(result.presentationIdleWritten).toBe(true);+ expect(result.publication).toMatchObject({+ presentationIdleDestPath,+ presentationIdleFrameCount: 3,+ presentationIdleFrameRate: 6,+ presentationIdleCellSize: 512,+ presentationIdleSourceManifestPath: 'idle-loop/approved-run.json',+ presentationIdleLayoutDestPath: 'assets/presentation/hero-idle.presentation.json',+ });+ expect(await readFile(join(APP_REPO, presentationIdleDestPath))).toEqual(strip);+ expect(JSON.parse(await readFile(+ join(APP_REPO, 'assets/presentation/hero-idle.presentation.json'),+ 'utf8',+ ))).toMatchObject({+ kind: 'portos-presentation-animation-layout',+ frameCount: 3,+ cellSize: 512,+ });+ });+it('resolves purely from repoPath — no dependency on registered processes/ports (#2991)', async () => {// The mocked app carries only { id, name, repoPath } — no processes, no// ports, portless. Publishing must still succeed: it targets the repo tree,diff --git a/server/services/sprites/walkPostprocess.js b/server/services/sprites/walkPostprocess.jsindex 6c860ed5f4..b6afde5510 100644--- a/server/services/sprites/walkPostprocess.js+++ b/server/services/sprites/walkPostprocess.js@@ -121,6 +121,29 @@ export async function decodeRgbaFrame(src) {return { data, width: info.width, height: info.height };}+/**+ * Decode a validated sprite source into a straight-alpha transparent frame.+ * Already-transparent sources receive the same despill safety pass as packaged+ * animation frames. Opaque chroma-key sources first recover alpha from their+ * measured border key, preserving the deterministic evidence path used by both+ * runtime-atlas compilation and presentation-portrait publishing.+ */+export async function decodeTransparentSpriteSource(src, split, keyHex) {+ const frame = await decodeRgbaFrame(src);+ const { data } = frame;+ let alphaMin = 255;+ let alphaMax = 0;+ for (let i = 3; i < data.length; i += 4) {+ const alpha = data[i];+ if (alpha < alphaMin) alphaMin = alpha;+ if (alpha > alphaMax) alphaMax = alpha;+ }+ if (alphaMin < alphaMax) return despillKeyFrame(frame, split);+ const measured = sampleBorderKey(frame);+ validateMeasuredKey(measured, split, keyHex);+ return despillKeyFrame(recoverAlphaFrame(frame, measured, split), split);+}+// Encode + write + hash in one pass — hashing the in-memory PNG buffer saves// reading every just-written artifact back off disk purely to checksum it.async function encodePngWithHash(frame, dest, channels = 4) {