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: add ambient sprite loops (#3045)
[._.]/ Adam Eivyfe4bb1304347
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 76585e305f..06e405a538 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -58,6 +58,8 @@## Sprite Manager+- **[issue-3045] Places and objects can now export a compact ambient loop** — generate and freeze one at-rest main reference, explicitly request one image-to-video loop, review and approve its locally packed 2–6 frames, then compile the result into an atlas whose idle and ambient cells live on row 0 while rows 1–7 remain transparent. The published layout names the single-row `ambient` span and carries `ambientFrameCount`, so a consuming app can sample row 0 at its own timing without assuming a character-facing walk cycle.+- **[issue-3018] The scanner action is now a real named animation track, from direct render through publish** — characters can generate a short directional scanner sweep only when you press **Generate** in Sprite Manager; the Grok clip is then deterministically unpacked into a 2–8-frame scanner strip (4 frames at 6fps by default), reviewed and approved per facing into an independent finalized scanner set. Atlas compilation verifies that set's selection, manifests, and frame checksums alongside the unchanged walk evidence, and writes its `scanner-00…` span beside the walk span into the published layout. A walk remains a walk: its routes, bounds, storage, legacy layouts, and distance-driven runtime behavior are unchanged, while consumers can now resolve the scanner by its named span instead of guessing a trailing column.- **Steer a single turnaround candidate with a correction note, without re-rolling the whole sheet** — each turnaround candidate now has its own **Correction** box and a **Re-process with note** button: describe what's wrong with that one attempt ("add the missing sleeve pocket") and it re-renders image-to-image from that exact candidate with the fix appended to the prompt, instead of generating a fresh sheet from scratch and hoping the same issue doesn't recur.diff --git a/client/src/components/sprites/AmbientWorkflow.jsx b/client/src/components/sprites/AmbientWorkflow.jsxnew file mode 100644index 0000000000..abe19ec687--- /dev/null+++ b/client/src/components/sprites/AmbientWorkflow.jsx@@ -0,0 +1,90 @@+import { useEffect, useMemo, useState } from 'react';+import { Check, Film, Lock, RefreshCw, Wind } from 'lucide-react';+import toast from '../ui/Toast';+import { approveSpriteAmbient, lockSpriteReference } from '../../services/apiSprites.js';+import { useAsyncAction } from '../../hooks/useAsyncAction.js';+import { checkerboardStyle, spriteAssetUrl } from './spriteAssets.js';++// Places and objects have one identity root and one atlas row. Keeping this as+// a compact, dedicated surface prevents the character turnaround/8-direction+// affordances from leaking into a track that has neither concept.+export default function AmbientWorkflow({+ record, reference, ambient, renders, hasBackend, mode, onGenerateReference, onGenerateAmbient, onChanged,+}) {+ const [designPrompt, setDesignPrompt] = useState('');+ const main = reference?.manifest?.mainReference || null;+ const candidate = useMemo(+ () => (reference?.candidates || []).find((item) => item.target === 'main') || null,+ [reference?.candidates],+ );+ const run = ambient?.runs?.[0] || null;+ const finalized = Boolean(ambient?.ambientSet);+ const referenceBusy = Boolean(renders?.pendingJobs?.main);+ const ambientBusy = ['rendering', 'postprocessing'].includes(run?.status);++ useEffect(() => {+ if (!ambientBusy) return undefined;+ const timer = setInterval(onChanged, 4000);+ return () => clearInterval(timer);+ }, [ambientBusy, onChanged]);++ const [lock, locking] = useAsyncAction(async () => {+ await lockSpriteReference(record.id, { target: 'main', candidate: candidate.path }, { silent: true });+ toast.success('Ambient reference frozen');+ onChanged();+ }, { errorMessage: 'Could not freeze the ambient reference' });++ const [approve, approving] = useAsyncAction(async () => {+ await approveSpriteAmbient(record.id, { runId: run.id }, { silent: true });+ toast.success('Ambient loop approved');+ onChanged();+ }, { errorMessage: 'Ambient approval failed' });++ return (+ <section className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">+ <div className="flex items-center justify-between gap-3">+ <h3 className="flex items-center gap-1.5 text-sm font-semibold text-white"><Wind className="w-4 h-4" /> Ambient Loop</h3>+ <span className="text-[11px] text-gray-500">one at-rest reference · one atlas row</span>+ </div>+ {!main?.locked ? (+ <div className="space-y-2">+ <label htmlFor={`ambient-design-${record.id}`} className="block text-xs text-gray-400">Describe this {record.kind}</label>+ <textarea+ id={`ambient-design-${record.id}`}+ value={designPrompt}+ onChange={(event) => setDesignPrompt(event.target.value)}+ placeholder="A willow tree with long branches moving gently in the wind"+ className="min-h-20 w-full rounded border border-port-border bg-port-bg px-2 py-1.5 text-sm text-white"+ />+ {candidate?.path && (+ <div className="flex items-center gap-2">+ <img className="h-20 w-20 rounded object-contain" style={checkerboardStyle(5)} src={spriteAssetUrl(record.id, candidate.path)} alt="Ambient reference candidate" />+ <button type="button" disabled={locking} onClick={lock} className="flex items-center gap-1 rounded bg-port-accent px-2 py-1.5 text-xs text-white disabled:opacity-50"><Lock className="w-3 h-3" /> Freeze reference</button>+ </div>+ )}+ <button+ type="button"+ disabled={!hasBackend || !designPrompt.trim() || referenceBusy}+ onClick={() => onGenerateReference(designPrompt)}+ className="flex items-center gap-1 rounded border border-port-border px-2 py-1.5 text-xs text-gray-200 hover:border-port-accent disabled:opacity-50"+ >+ {referenceBusy ? <RefreshCw className="w-3 h-3 animate-spin" /> : <Film className="w-3 h-3" />}+ {candidate ? 'Regenerate reference' : 'Generate reference'}{mode ? '' : ' (select an image backend)'}+ </button>+ </div>+ ) : (+ <article className="rounded border border-port-border bg-port-bg p-2 space-y-2">+ <div className="flex items-center justify-between"><span className="text-xs font-medium text-white">Ambient row 0</span><span className={`text-[10px] ${finalized ? 'text-port-success' : ambientBusy ? 'text-port-accent' : 'text-gray-500'}`}>{finalized ? 'approved' : ambientBusy ? run.status : run?.status === 'candidate' ? 'review' : 'not generated'}</span></div>+ {run?.stripPreview?.stripPath ? (+ <img className="h-24 w-full rounded object-contain" style={checkerboardStyle(5)} src={spriteAssetUrl(record.id, run.stripPreview.stripPath, run.stripPreview.stripSha256)} alt="Ambient loop preview" />+ ) : <div className="h-24 grid place-items-center rounded text-gray-600" style={checkerboardStyle(5)}><Film className="w-4 h-4" /></div>}+ {!finalized && <div className="flex gap-1.5">+ <button type="button" disabled={ambientBusy} onClick={onGenerateAmbient} className="flex-1 rounded border border-port-border px-2 py-1 text-xs text-gray-300 hover:border-port-accent disabled:opacity-50">{ambientBusy ? 'Rendering…' : run?.status === 'error' ? 'Retry' : 'Generate loop'}</button>+ {run?.status === 'candidate' && <button type="button" disabled={approving} aria-label="Approve ambient loop" onClick={approve} className="rounded bg-port-accent px-2 py-1 text-xs text-white disabled:opacity-50"><Check className="w-3 h-3" /></button>}+ </div>}+ {run?.postprocessError && <p className="text-[10px] text-red-300">{run.postprocessError}</p>}+ </article>+ )}+ </section>+ );+}diff --git a/client/src/components/sprites/PublishWorkflow.jsx b/client/src/components/sprites/PublishWorkflow.jsxindex 00e10f303c..ad85ea37b4 100644--- a/client/src/components/sprites/PublishWorkflow.jsx+++ b/client/src/components/sprites/PublishWorkflow.jsx@@ -29,6 +29,8 @@ const WALK_MIN_FRAME_COUNT = 6;const WALK_MAX_FRAME_COUNT = 16;const SCANNER_MIN_FRAME_COUNT = 2;const SCANNER_MAX_FRAME_COUNT = 8;+const AMBIENT_MIN_FRAME_COUNT = 2;+const AMBIENT_MAX_FRAME_COUNT = 6;const ATLAS_IDLE_COLUMN = 'idle';const ATLAS_SCANNER_COLUMN = 'scanner';@@ -37,6 +39,9 @@ const ATLAS_SCANNER_COLUMN = 'scanner';// server's resolveWalkFrameCount so the compare and the fill button agree.function walkFrameCountOf(geometry) {if (Number.isInteger(geometry?.walkFrameCount)) return geometry.walkFrameCount;+ if (geometry?.tracks && typeof geometry.tracks === 'object' && !Array.isArray(geometry.tracks)) {+ return Number.isInteger(geometry.tracks.walk?.count) ? geometry.tracks.walk.count : null;+ }if (!Array.isArray(geometry?.columns)) return null;return geometry.columns.filter((c) => c !== ATLAS_IDLE_COLUMN && c !== ATLAS_SCANNER_COLUMN,@@ -48,18 +53,23 @@ function scannerFrameCountOf(geometry) {return Number.isInteger(geometry?.tracks?.scanner?.count) ? geometry.tracks.scanner.count : null;}-export default function PublishWorkflow({ record, walk, atlas, onChanged }) {- const finalized = Boolean(walk?.walkSet);+function ambientFrameCountOf(geometry) {+ if (Number.isInteger(geometry?.ambientFrameCount)) return geometry.ambientFrameCount;+ return Number.isInteger(geometry?.tracks?.ambient?.count) ? geometry.tracks.ambient.count : null;+}++export default function PublishWorkflow({ record, walk, ambient, atlas, onChanged }) {+ const finalized = Boolean(walk?.walkSet || ambient?.ambientSet);const current = atlas?.current || null;const publications = atlas?.publications || [];const saved = record.publishBinding || null;const savedContract = saved?.runtimeContract || null;// Contract fields are strings so an empty input is distinguishable from a 0.- // The stored contract seeds them; walkFrameCount is the anchor field (an- // empty walk-frame-count means "no contract").+ // The stored contract seeds them; a walk or ambient frame count anchors it.const seedFrames = savedContract?.walkFrameCount != null ? String(savedContract.walkFrameCount) : '';const seedScanner = savedContract?.scannerFrameCount != null ? String(savedContract.scannerFrameCount) : '';+ const seedAmbient = savedContract?.ambientFrameCount != null ? String(savedContract.ambientFrameCount) : '';const seedCell = savedContract?.cellSize != null ? String(savedContract.cellSize) : '';const seedCols = savedContract?.columnCount != null ? String(savedContract.columnCount) : '';@@ -70,6 +80,7 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {const [resourcePath, setResourcePath] = useState(saved?.codeBinding?.resourcePath || '');const [contractFrames, setContractFrames] = useState(seedFrames);const [contractScanner, setContractScanner] = useState(seedScanner);+ const [contractAmbient, setContractAmbient] = useState(seedAmbient);const [contractCell, setContractCell] = useState(seedCell);const [contractCols, setContractCols] = useState(seedCols);// null → idle; 'publish' → normal confirm; 'overwrite' → the server@@ -89,44 +100,48 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {setResourcePath(saved?.codeBinding?.resourcePath || '');setContractFrames(seedFrames);setContractScanner(seedScanner);+ setContractAmbient(seedAmbient);setContractCell(seedCell);setContractCols(seedCols);setConfirmStage(null);}, [saved?.appId, saved?.atlasDestPath, saved?.codeBinding?.path, saved?.codeBinding?.resourcePath,- savedContract?.walkFrameCount, savedContract?.scannerFrameCount, savedContract?.cellSize, savedContract?.columnCount,- seedFrames, seedScanner, seedCell, seedCols]);+ savedContract?.walkFrameCount, savedContract?.scannerFrameCount, savedContract?.ambientFrameCount, savedContract?.cellSize, savedContract?.columnCount,+ seedFrames, seedScanner, seedAmbient, seedCell, seedCols]);- // Parse the four contract inputs. walkFrameCount is the anchor: an empty- // field means "no contract". cellSize/columnCount are optional (empty → null).+ // Parse the five contract inputs. A walk or ambient frame count anchors the+ // contract; cellSize/columnCount are optional (empty → null).const framesRaw = contractFrames.trim();const scannerRaw = contractScanner.trim();+ const ambientRaw = contractAmbient.trim();const cellRaw = contractCell.trim();const colsRaw = contractCols.trim();const framesNum = framesRaw === '' ? null : Number(framesRaw);const scannerNum = scannerRaw === '' ? null : Number(scannerRaw);+ const ambientNum = ambientRaw === '' ? null : Number(ambientRaw);const cellNum = cellRaw === '' ? null : Number(cellRaw);const colsNum = colsRaw === '' ? null : Number(colsRaw);- const hasContract = framesNum !== null;+ const hasContract = framesNum !== null || ambientNum !== null;// Whether the contract INPUTS were edited (vs. merely seeded from the saved// binding). Used both for the dirty check and to scope the no-binding error// to a user who actually typed a contract — an untouched seeded contract must// not block an unbind (sending `binding: null` clears it server-side anyway).- const contractFieldsDirty = seedFrames !== framesRaw || seedScanner !== scannerRaw+ const contractFieldsDirty = seedFrames !== framesRaw || seedScanner !== scannerRaw || seedAmbient !== ambientRaw|| seedCell !== cellRaw || seedCols !== colsRaw;const intInRange = (n, lo, hi) => Number.isInteger(n) && n >= lo && n <= hi;- // Validate only what's populated; walkFrameCount is required whenever any- // contract field is set (the server rejects a contract without it). A freshly- // typed contract is also meaningless without an app + destination — the+ // Validate only what's populated; a freshly typed contract is meaningless+ // without an app + destination — the// binding it would ride on is null, so the value would be silently discarded.let contractError = null;if (!hasContract && (scannerRaw !== '' || cellRaw !== '' || colsRaw !== '')) {- contractError = 'Walk frame count is required for a runtime contract.';- } else if (hasContract && !intInRange(framesNum, WALK_MIN_FRAME_COUNT, WALK_MAX_FRAME_COUNT)) {+ contractError = 'Walk or ambient frame count is required for a runtime contract.';+ } else if (framesNum !== null && !intInRange(framesNum, WALK_MIN_FRAME_COUNT, WALK_MAX_FRAME_COUNT)) {contractError = `Walk frame count must be a whole number ${WALK_MIN_FRAME_COUNT}–${WALK_MAX_FRAME_COUNT}.`;} else if (scannerNum !== null && !intInRange(scannerNum, SCANNER_MIN_FRAME_COUNT, SCANNER_MAX_FRAME_COUNT)) {contractError = `Scanner frame count must be a whole number ${SCANNER_MIN_FRAME_COUNT}–${SCANNER_MAX_FRAME_COUNT}.`;+ } else if (ambientNum !== null && !intInRange(ambientNum, AMBIENT_MIN_FRAME_COUNT, AMBIENT_MAX_FRAME_COUNT)) {+ contractError = `Ambient frame count must be a whole number ${AMBIENT_MIN_FRAME_COUNT}–${AMBIENT_MAX_FRAME_COUNT}.`;} else if (cellNum !== null && !intInRange(cellNum, 16, 1024)) {contractError = 'Cell size must be a whole number 16–1024.';} else if (colsNum !== null && !intInRange(colsNum, 1, 256)) {@@ -146,8 +161,10 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {if (!geometry) return;const frames = walkFrameCountOf(geometry);const scannerFrames = scannerFrameCountOf(geometry);+ const ambientFrames = ambientFrameCountOf(geometry);setContractFrames(frames != null ? String(frames) : '');setContractScanner(scannerFrames != null ? String(scannerFrames) : '');+ setContractAmbient(ambientFrames != null ? String(ambientFrames) : '');setContractCell(Number.isInteger(geometry.cellSize) ? String(geometry.cellSize) : '');setContractCols(Array.isArray(geometry.columns) ? String(geometry.columns.length) : '');};@@ -155,6 +172,7 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {const clearContract = () => {setContractFrames('');setContractScanner('');+ setContractAmbient('');setContractCell('');setContractCols('');};@@ -178,12 +196,13 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {// Absent-vs-null: only touch runtimeContract when the contract group is// dirty. An OMITTED key inherits the stored contract server-side (see// setPublishBinding); an untouched save must not silently drop it. When- // dirty, a populated walkFrameCount sets it, an emptied one clears it (null).+ // dirty, a populated track frame count sets it, an emptied group clears it (null).if (binding && contractDirty) {binding.runtimeContract = hasContract? {- walkFrameCount: framesNum,+ ...(framesNum === null ? {} : { walkFrameCount: framesNum }),...(scannerNum === null ? {} : { scannerFrameCount: scannerNum }),+ ...(ambientNum === null ? {} : { ambientFrameCount: ambientNum }),cellSize: cellNum,columnCount: colsNum,}@@ -231,7 +250,7 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {// server-stamped flag rather than re-deriving the path convention: it is// per-direction, so it clears on its own as each direction is re-derived from// its imported clip — which is what makes an imported set compilable at all.- if (walk.walkSet.imported) {+ if (walk?.walkSet?.imported) {return (<div className="bg-port-card border border-port-border rounded-lg p-4 space-y-1"><h3 className="text-sm font-medium text-gray-200 flex items-center gap-2">@@ -270,10 +289,11 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {const atlasGeom = current?.geometry || null;const atlasFrames = walkFrameCountOf(atlasGeom);const atlasScannerFrames = scannerFrameCountOf(atlasGeom);+ const atlasAmbientFrames = ambientFrameCountOf(atlasGeom);const atlasCols = Array.isArray(atlasGeom?.columns) ? atlasGeom.columns.length : null;const atlasCell = Number.isInteger(atlasGeom?.cellSize) ? atlasGeom.cellSize : null;const atlasSummary = atlasGeom- ? `${atlasFrames ?? '?'} walk frames${atlasScannerFrames != null ? ` · ${atlasScannerFrames} scanner frames` : ''} · ${atlasCols ?? '?'} cols${atlasCell != null ? ` · ${atlasCell}px` : ''}`+ ? `${atlasFrames ?? 'no'} walk frames${atlasScannerFrames != null ? ` · ${atlasScannerFrames} scanner frames` : ''}${atlasAmbientFrames != null ? ` · ${atlasAmbientFrames} ambient frames` : ''} · ${atlasCols ?? '?'} cols${atlasCell != null ? ` · ${atlasCell}px` : ''}`: null;const savedContractMismatch = (() => {if (!savedContract || !atlasGeom) return null;@@ -283,6 +303,9 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {if (Number.isInteger(savedContract.scannerFrameCount) && savedContract.scannerFrameCount !== atlasScannerFrames) {return `contract expects ${savedContract.scannerFrameCount} scanner frames, atlas has ${atlasScannerFrames ?? 'none'}`;}+ if (Number.isInteger(savedContract.ambientFrameCount) && savedContract.ambientFrameCount !== atlasAmbientFrames) {+ return `contract expects ${savedContract.ambientFrameCount} ambient frames, atlas has ${atlasAmbientFrames ?? 'none'}`;+ }if (Number.isInteger(savedContract.columnCount) && savedContract.columnCount !== atlasCols) {return `contract expects ${savedContract.columnCount} cols, atlas has ${atlasCols ?? '?'}`;}@@ -362,7 +385,7 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {<buttontype="button"onClick={clearContract}- disabled={framesRaw === '' && scannerRaw === '' && cellRaw === '' && colsRaw === ''}+ disabled={framesRaw === '' && scannerRaw === '' && ambientRaw === '' && cellRaw === '' && colsRaw === ''}className="px-2 py-0.5 text-[11px] bg-port-bg border border-port-border rounded text-gray-300 hover:border-port-accent disabled:opacity-50">Clear@@ -373,7 +396,7 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {The grid a consuming app was built against. A publish whose compiled atlas disagrees isrefused. Leave blank to publish unchecked; clearing removes a stored contract.</p>- <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-2">+ <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-5 gap-2"><FormField label={`Walk frames (${WALK_MIN_FRAME_COUNT}–${WALK_MAX_FRAME_COUNT})`} labelClassName={fieldLabelClass}><inputtype="number"@@ -396,6 +419,17 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {className={inputClass}/></FormField>+ <FormField label={`Ambient frames (${AMBIENT_MIN_FRAME_COUNT}–${AMBIENT_MAX_FRAME_COUNT}, optional)`} labelClassName={fieldLabelClass}>+ <input+ type="number"+ min={AMBIENT_MIN_FRAME_COUNT}+ max={AMBIENT_MAX_FRAME_COUNT}+ value={contractAmbient}+ onChange={(e) => setContractAmbient(e.target.value)}+ placeholder="3"+ className={inputClass}+ />+ </FormField><FormField label="Cell size px (optional)" labelClassName={fieldLabelClass}><inputtype="number"diff --git a/client/src/components/sprites/PublishWorkflow.test.jsx b/client/src/components/sprites/PublishWorkflow.test.jsxindex 38fdf516dc..1054611bb1 100644--- a/client/src/components/sprites/PublishWorkflow.test.jsx+++ b/client/src/components/sprites/PublishWorkflow.test.jsx@@ -128,12 +128,12 @@ describe('PublishWorkflow runtime contract', () => {expect(screen.getByText('Save binding')).toBeDisabled();});- it('requires walk frames when a scanner contract is entered on its own', () => {+ it('requires a track frame count when a scanner contract is entered on its own', () => {renderWorkflow({ appId: 'app-1', atlasDestPath: 'assets/hero.png', codeBinding: null });fireEvent.change(screen.getByLabelText(/Scanner frames/), { target: { value: '4' } });- expect(screen.getByText(/Walk frame count is required/)).toBeInTheDocument();+ expect(screen.getByText(/Walk or ambient frame count is required/)).toBeInTheDocument();expect(screen.getByText('Save binding')).toBeDisabled();});@@ -171,6 +171,39 @@ describe('PublishWorkflow runtime contract', () => {});});+ it('uses ambientFrameCount for an ambient-only atlas instead of inventing walk frames', async () => {+ const ambientAtlas = atlasWith({+ current: {+ version: 3,+ compiledAt: '2026-07-01T00:00:00.000Z',+ atlasPath: 'runtime/v3/a.png',+ geometry: {+ columns: ['idle', 'ambient-00', 'ambient-01', 'ambient-02'],+ tracks: { idle: { start: 0, count: 1, rows: 1 }, ambient: { start: 1, count: 3, rows: 1 } },+ cellSize: 96,+ walkFrameCount: null,+ ambientFrameCount: 3,+ },+ },+ });+ render(+ <MemoryRouter>+ <PublishWorkflow+ record={{ id: 'example-tree', publishBinding: { appId: 'app-1', atlasDestPath: 'assets/tree.png', codeBinding: null } }}+ ambient={{ ambientSet: {} }}+ atlas={ambientAtlas}+ onChanged={vi.fn()}+ />+ </MemoryRouter>,+ );++ fireEvent.click(screen.getByText('Match current atlas'));+ expect(screen.getByLabelText(/Walk frames/).value).toBe('');+ expect(screen.getByLabelText(/Ambient frames/).value).toBe('3');+ await act(async () => { fireEvent.click(screen.getByText('Save binding')); });+ expect(lastBindingArg().runtimeContract).toEqual({ ambientFrameCount: 3, cellSize: 96, columnCount: 4 });+ });+it('rejects an out-of-range walk frame count and blocks the save', () => {renderWorkflow({ appId: 'app-1', atlasDestPath: 'assets/hero.png', codeBinding: null });diff --git a/client/src/pages/Sprites.jsx b/client/src/pages/Sprites.jsxindex af82454b9b..cd4e52e236 100644--- a/client/src/pages/Sprites.jsx+++ b/client/src/pages/Sprites.jsx@@ -5,7 +5,7 @@ import toast from '../components/ui/Toast';import Modal from '../components/ui/Modal.jsx';import {listSpriteRecords, getSpriteRecord, importSprites, createSpriteRecord,- generateSpriteWalk, generateSpriteScanner, generateSpriteReference, listSpriteThumbnails,+ generateSpriteWalk, generateSpriteScanner, generateSpriteAmbient, generateSpriteReference, listSpriteThumbnails,} from '../services/apiSprites.js';import { getApps } from '../services/apiApps.js';import { getSettings } from '../services/apiSystem.js';@@ -14,6 +14,7 @@ import AppContextPicker from '../components/AppContextPicker.jsx';import ReferenceWorkflow from '../components/sprites/ReferenceWorkflow.jsx';import WalkWorkflow from '../components/sprites/WalkWorkflow.jsx';import ScannerWorkflow from '../components/sprites/ScannerWorkflow.jsx';+import AmbientWorkflow from '../components/sprites/AmbientWorkflow.jsx';import { GROK_VIDEO_DEFAULT_DURATION } from '../lib/grokVideoClip.js';import LoopTrimmer from '../components/sprites/LoopTrimmer.jsx';import PublishWorkflow from '../components/sprites/PublishWorkflow.jsx';@@ -571,6 +572,25 @@ export default function Sprites() {}}, [id, onWorkflowChanged]);+ const generateAmbientReference = useCallback((designPrompt) => submitRender(+ refBegin, refResolve, refCancel, 'main',+ () => generateSpriteReference(id, {+ target: 'main', designPrompt,+ ...(imageMode ? { mode: imageMode } : {}),+ }, { silent: true }),+ 'Failed to queue ambient reference',+ onWorkflowChanged,+ ), [id, imageMode, refBegin, refResolve, refCancel, submitRender, onWorkflowChanged]);++ const generateAmbient = useCallback(async () => {+ try {+ await generateSpriteAmbient(id, {}, { silent: true });+ onWorkflowChanged();+ } catch (err) {+ toast.error(err?.message || 'Failed to queue ambient loop');+ }+ }, [id, onWorkflowChanged]);+// `mode` is the workflow-selected backend, threaded from the asset card via// buildCollectionActions (#2938) so a re-roll uses the same backend the// Reference workflow would, not the server default. Falls back to the@@ -743,6 +763,29 @@ export default function Sprites() {/></>)}+ {detail.record.kind !== 'character' && detail.ambient && (+ <>+ <AmbientWorkflow+ record={detail.record}+ reference={detail.reference}+ ambient={detail.ambient}+ renders={referenceRenders}+ hasBackend={hasImageBackend}+ mode={imageMode}+ onGenerateReference={generateAmbientReference}+ onGenerateAmbient={generateAmbient}+ onChanged={onWorkflowChanged}+ />+ <PublishWorkflow+ key={detail.record.id}+ record={detail.record}+ walk={detail.walk}+ ambient={detail.ambient}+ atlas={detail.atlas}+ onChanged={onWorkflowChanged}+ />+ </>+ )}{detail.assets.length === 0 ? (<p className="text-sm text-gray-500">No assets on disk for this record.</p>) : (diff --git a/client/src/services/apiSprites.js b/client/src/services/apiSprites.jsindex dc40b234ee..75cd70a9ea 100644--- a/client/src/services/apiSprites.js+++ b/client/src/services/apiSprites.js@@ -129,6 +129,14 @@ export const approveSpriteScanner = (id, body, options = {}) => request(`/spritemethod: 'POST', body: JSON.stringify(body), ...options,});+export const generateSpriteAmbient = (id, body = {}, options = {}) => request(`/sprites/${encodeURIComponent(id)}/ambient/generate`, {+ method: 'POST', body: JSON.stringify(body), ...options,+});++export const approveSpriteAmbient = (id, body, options = {}) => request(`/sprites/${encodeURIComponent(id)}/ambient/approve`, {+ method: 'POST', body: JSON.stringify(body), ...options,+});+// Re-run the deterministic postprocess on a run whose video already landed.export const postprocessSpriteWalk = (id, body, options = {}) => request(`/sprites/${encodeURIComponent(id)}/walk/postprocess`, {method: 'POST', body: JSON.stringify(body), ...options,diff --git a/docs/features/sprite-export-contract.md b/docs/features/sprite-export-contract.mdindex 25a4a17b25..77407d2ed0 100644--- a/docs/features/sprite-export-contract.md+++ b/docs/features/sprite-export-contract.md@@ -13,7 +13,7 @@ The compiler (`server/services/sprites/atlas.js`) produces one PNG: a fixed-cell| Cell size | 96 × 96 px (overridable per compile; the published geometry is whatever was compiled) || Pivot | `(48, 88)` — silhouette centered on x, feet on the y ground line || Rows | 8, in `directionOrder`: `south`, `south-east`, `east`, `north-east`, `north`, `north-west`, `west`, `south-west` |-| Columns | `idle` at 0, then one contiguous span per approved animation track in registration order — walk begins at 1 and scanner follows it when approved |+| Columns | `idle` at 0, then one contiguous span per approved animation track in registration order — walk begins at 1, scanner follows it when approved, and an ambient-only record has `idle` + its ambient span || N (walk frame count) | authorable, 6–16 (`animationTracks.js`); historically always 8 |`N` is read from the approved run manifests — every direction of a track must share it — so the atlas width tracks the authored count. **That makes the column layout a moving target for anything that hardcodes it.**@@ -24,6 +24,23 @@ Frame-count and fps uniformity is a **within-track** rule, never a between-trackNon-walk tracks namespace their column labels with the track id (`scanner-00`, `scanner-01`, …). Walk keeps its historical labels — the named gait phases at 8 frames, positional `frame-NN` at any other length — so existing and imported atlases round-trip unchanged.+### Ambient worked example++A `place`, `object`, or legacy `props` record can carry the `ambient` track: 2–6 coherent frames from one explicitly requested image-to-video clip, defaulting to 3 at 4fps for PortOS preview. Its locked main reference supplies the `idle` cell; the approved loop occupies row 0 and leaves rows 1–7 transparent:++```json+{+ "columns": ["idle", "ambient-00", "ambient-01", "ambient-02"],+ "tracks": {+ "idle": { "start": 0, "count": 1, "rows": 1 },+ "ambient": { "start": 1, "count": 3, "rows": 1 }+ },+ "ambientFrameCount": 3+}+```++`previewFps` remains authoring metadata. A consuming app picks the ambient playback rate and always samples row 0; it must not infer a facing from the unused transparent rows.+> **Atlases compiled before #2986 carry one extra trailing `scanner` column** — a verbatim copy of the idle cell, from an early render, that no consumer ever sampled. The compiler no longer emits it (an action animation is its own named track, not a column appended to the walk cycle), so an 8-frame grid is 9 columns wide rather than 10. Reading side is unchanged: an imported or previously published atlas that still has the column keeps loading, and its sidecar still describes the `scanner` span it really has. Recompiling a set drops the column and produces a new atlas version; existing published atlases are untouched until republished.## What crosses the publish boundary@@ -87,7 +104,7 @@ Column layout is the one thing an app genuinely has to agree with PortOS about.Two mechanisms guard that:-- **`publishBinding.runtimeContract`** (optional): `{ walkFrameCount, scannerFrameCount?, cellSize?, columnCount? }` — the grid the app was built against. Set it from the **Runtime contract** group in the publish binding form (the sprite's Publish workflow) — a "Match current atlas" button fills it from the compiled atlas geometry, and a "Clear" affordance removes it — or via `PUT /api/sprites/:id/publish-binding` directly. Publishing an atlas whose compiled geometry disagrees fails with a **409** naming both the actual and expected numbers and both resolutions (change the app's constant, or reprocess the relevant set). A binding with no contract publishes unchecked, exactly as before the field existed.+- **`publishBinding.runtimeContract`** (optional): `{ walkFrameCount?, scannerFrameCount?, ambientFrameCount?, cellSize?, columnCount? }` — the grid the app was built against. A contract names either `walkFrameCount` or `ambientFrameCount` (and may include the other spans); set it from the **Runtime contract** group in the publish binding form or via `PUT /api/sprites/:id/publish-binding` directly. Publishing an atlas whose compiled geometry disagrees fails with a **409** naming both the actual and expected numbers and both resolutions (change the app's constant, or reprocess the relevant set). A binding with no contract publishes unchecked, exactly as before the field existed.- **The sidecar**, so an app that reads it can fail loudly on its own terms instead of relying on PortOS to have been asked.`runtimeContract` follows absent-vs-null semantics: a saved binding that omits the key inherits the stored contract (saving the form with the contract group untouched omits it, so the stored contract survives an unrelated edit), while an explicit `null` — what the form's "Clear" sends — clears it. The inheritance is scoped to the same `appId` — re-pointing a character at a different app drops the old app's contract rather than holding the new one to it.diff --git a/server/lib/validation.js b/server/lib/validation.jsindex b23ce3226a..f148fe93b1 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -5,7 +5,7 @@ import { WORK_TRACKERS } from './workTracker.js';import { SPRITE_ID_PATTERN, SPRITE_RECORD_KINDS } from '../services/sprites/recordsLogic.js';import { ANCHOR_DIRECTIONS, SPRITE_DIRECTIONS, TURNAROUND_ID } from '../services/sprites/prompts.js';import { CHROMA_KEY_HEXES } from '../services/sprites/chromaKey.js';-import { WALK_TRACK, SCANNER_TRACK, getAnimationTrack } from '../services/sprites/animationTracks.js';+import { WALK_TRACK, SCANNER_TRACK, AMBIENT_TRACK, getAnimationTrack } from '../services/sprites/animationTracks.js';import { QUEUEABLE_IMAGE_MODES } from '../services/imageGen/modes.js';import { GROK_VIDEO_DURATIONS } from './grokVideoClip.js';@@ -1027,21 +1027,28 @@ const spriteRepoRelativePath = z.string().min(1).max(1024)// The grid the consuming app was built against (#2982). Optional: an absent// contract publishes unchecked, exactly as bindings did before it existed.-// `walkFrameCount` is required once a contract is declared — it is the value-// the app bakes in as a constant and the one a mismatched publish silently-// breaks. Playback speed is deliberately absent: distance-driven consumers-// have no animation-fps concept, so PortOS's fps is preview-only and never-// part of the contract.+// A directional consumer names `walkFrameCount`; an ambient-only consumer names+// `ambientFrameCount`. Playback speed is deliberately absent: consumers own+// timing, so PortOS's fps is preview-only and never part of the contract.export const spriteRuntimeContractSchema = z.object({// Range from the walk registry row (#3015). The KEY stays a literal so// `grep walkFrameCount` still finds the schema that validates it — the row's// `contractFrameCountField` is asserted to agree in animationTargets.test.js.- walkFrameCount: spriteTrackFrameCountSchema(WALK_TRACK),+ walkFrameCount: spriteTrackFrameCountSchema(WALK_TRACK).optional(),// Optional because older consumers only know walk. A scanner-aware consumer// can pin the named action span without relaxing its independent 2–8 range.scannerFrameCount: spriteTrackFrameCountSchema(SCANNER_TRACK).optional(),+ ambientFrameCount: spriteTrackFrameCountSchema(AMBIENT_TRACK).optional(),cellSize: z.number().int().min(16).max(1024).nullable().optional(),columnCount: z.number().int().min(1).max(256).nullable().optional(),+}).superRefine((value, ctx) => {+ if (value.walkFrameCount === undefined && value.ambientFrameCount === undefined) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ['walkFrameCount'],+ message: 'walkFrameCount or ambientFrameCount is required for a runtime contract',+ });+ }});export const spritePublishBindingSchema = z.object({@@ -1176,6 +1183,8 @@ const spriteWalkFrameCountSchema = spriteTrackFrameCountSchema(WALK_TRACK);const spriteWalkFpsSchema = spriteTrackFpsSchema(WALK_TRACK);const spriteScannerFrameCountSchema = spriteTrackFrameCountSchema(SCANNER_TRACK);const spriteScannerFpsSchema = spriteTrackFpsSchema(SCANNER_TRACK);+const spriteAmbientFrameCountSchema = spriteTrackFrameCountSchema(AMBIENT_TRACK);+const spriteAmbientFpsSchema = spriteTrackFpsSchema(AMBIENT_TRACK);export const spriteWalkGenerateSchema = z.object({direction: spriteWalkDirectionSchema,@@ -1207,6 +1216,18 @@ export const spriteScannerApproveSchema = z.object({runId: spriteResolvableRunIdSchema,});+// One non-directional row lives at the first atlas row, so no user-supplied+// direction can drift from the registry's `trackDirections()` result.+export const spriteAmbientGenerateSchema = z.object({+ duration: grokVideoDurationSchema.optional(),+ frameCount: spriteAmbientFrameCountSchema.optional(),+ fps: spriteAmbientFpsSchema.optional(),+});++export const spriteAmbientApproveSchema = z.object({+ runId: spriteResolvableRunIdSchema,+});+// Pin the walk track's cycle target at the SET level (#2985). Both knobs are// required: the target is one atomic set-level decision, and a partial write// would leave "which value did I actually pin?" ambiguous on a record everydiff --git a/server/lib/validation.test.js b/server/lib/validation.test.jsindex 9daca6f7a9..c7f0ad3409 100644--- a/server/lib/validation.test.js+++ b/server/lib/validation.test.js@@ -43,6 +43,7 @@ import {spriteRuntimeContractSchema,spriteWalkGenerateSchema,spriteScannerGenerateSchema,+ spriteAmbientGenerateSchema,} from './validation.js';import {telegramForwardTypesSchema,@@ -1462,11 +1463,14 @@ describe('ad-hoc route schemas (#2521)', () => {expect(() => spriteTrackFpsSchema('unknown')).toThrow(/Unknown animation track/);});- it('leaves the walk request/contract schemas behaving exactly as before', () => {+ it('keeps the walk schemas stable and admits the ambient contract shape', () => {expect(spriteRuntimeContractSchema.safeParse({ walkFrameCount: 12 }).success).toBe(true);expect(spriteRuntimeContractSchema.safeParse({ walkFrameCount: 12, scannerFrameCount: 4 }).success).toBe(true);expect(spriteRuntimeContractSchema.safeParse({ walkFrameCount: 12, scannerFrameCount: 9 }).success).toBe(false);expect(spriteRuntimeContractSchema.safeParse({ walkFrameCount: 5 }).success).toBe(false);+ expect(spriteRuntimeContractSchema.safeParse({ ambientFrameCount: 3 }).success).toBe(true);+ expect(spriteRuntimeContractSchema.safeParse({ ambientFrameCount: 7 }).success).toBe(false);+ expect(spriteRuntimeContractSchema.safeParse({ scannerFrameCount: 4 }).success).toBe(false);expect(spriteWalkGenerateSchema.safeParse({direction: 'south', frameCount: 12, fps: 10,}).success).toBe(true);@@ -1475,6 +1479,8 @@ describe('ad-hoc route schemas (#2521)', () => {}).success).toBe(false);expect(spriteScannerGenerateSchema.safeParse({ direction: 'south', frameCount: 4, fps: 6 }).success).toBe(true);expect(spriteScannerGenerateSchema.safeParse({ direction: 'south', frameCount: 9 }).success).toBe(false);+ expect(spriteAmbientGenerateSchema.safeParse({ frameCount: 3, fps: 4 }).success).toBe(true);+ expect(spriteAmbientGenerateSchema.safeParse({ frameCount: 7 }).success).toBe(false);});});diff --git a/server/routes/sprites.js b/server/routes/sprites.jsindex 945e4067a7..31525081da 100644--- a/server/routes/sprites.js+++ b/server/routes/sprites.js@@ -24,6 +24,8 @@ import {spriteForkSchema,spriteScannerGenerateSchema,spriteScannerApproveSchema,+ spriteAmbientGenerateSchema,+ spriteAmbientApproveSchema,spriteWalkGenerateSchema,spriteWalkApproveSchema,spriteWalkReopenSchema,@@ -48,13 +50,14 @@ import {listReferenceSources, listSpriteThumbnails, forkSprite,} from '../services/sprites/reference.js';import { resolveSpriteAssetPrompt } from '../services/sprites/assetPrompt.js';-import { WALK_TRACK, SCANNER_TRACK, kindSupportsTrack, tracksForKind } from '../services/sprites/animationTracks.js';+import { WALK_TRACK, SCANNER_TRACK, AMBIENT_TRACK, kindSupportsTrack, tracksForKind } from '../services/sprites/animationTracks.js';import {getWalkState, startWalkGeneration, approveWalkDirection, rerunWalkPostprocess, unlockWalkSet,reopenWalkDirection, setWalkTarget, getWalkSourceFrames,unlockDirectionalAnchor, unlockTurnaroundReference,} from '../services/sprites/walk.js';import { getScannerState, startScannerGeneration, approveScannerDirection } from '../services/sprites/scanner.js';+import { getAmbientState, startAmbientGeneration, approveAmbientLoop } from '../services/sprites/ambient.js';import { saveLoopTrim } from '../services/sprites/walkTrims.js';import { compileAtlas, getAtlasState } from '../services/sprites/atlas.js';import { setPublishBinding, publishAtlas } from '../services/sprites/publish.js';@@ -117,13 +120,15 @@ router.get('/:id', asyncHandler(async (req, res) => {const { kind } = detail.record;const runsWalk = kindSupportsTrack(kind, WALK_TRACK);const runsScanner = kindSupportsTrack(kind, SCANNER_TRACK);- const [reference, walk, scanner, atlas] = await Promise.all([- runsWalk ? getReferenceSet(req.params.id) : null,+ const runsAmbient = kindSupportsTrack(kind, AMBIENT_TRACK);+ const [reference, walk, scanner, ambient, atlas] = await Promise.all([+ tracksForKind(kind).length ? getReferenceSet(req.params.id) : null,runsWalk ? getWalkState(req.params.id) : null,runsScanner ? getScannerState(req.params.id) : null,+ runsAmbient ? getAmbientState(req.params.id) : null,tracksForKind(kind).length ? getAtlasState(req.params.id) : null,]);- res.json({ ...detail, reference, walk, scanner, atlas });+ res.json({ ...detail, reference, walk, scanner, ambient, atlas });}));// The generation prompt behind one on-disk asset (record-relative `path`) —@@ -208,6 +213,17 @@ router.post('/:id/scanner/approve', asyncHandler(async (req, res) => {res.json(await approveScannerDirection(req.params.id, body));}));+// One user-requested image-to-video clip for the non-directional ambient row.+router.post('/:id/ambient/generate', asyncHandler(async (req, res) => {+ const body = validateRequest(spriteAmbientGenerateSchema, req.body);+ res.json(await startAmbientGeneration(req.params.id, body));+}));++router.post('/:id/ambient/approve', asyncHandler(async (req, res) => {+ const body = validateRequest(spriteAmbientApproveSchema, req.body);+ res.json(await approveAmbientLoop(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/ambient.js b/server/services/sprites/ambient.jsnew file mode 100644index 0000000000..06ba0e6353--- /dev/null+++ b/server/services/sprites/ambient.js@@ -0,0 +1,278 @@+/**+ * The first real non-directional animation track: one ambient loop for a+ * place, object, or imported prop. The only provider call is the explicit+ * generate route; packing, review, approval, and atlas input are local.+ */++import { join } from 'path';+import { readdir } from 'fs/promises';+import { randomUUID } from 'crypto';+import { atomicWrite, ensureDir, pathExists, readJSONFile, sha256File } from '../../lib/fileUtils.js';+import { ServerError } from '../../lib/errorHandler.js';+import { executeTuiRun } from '../../lib/tuiPromptRunner.js';+import { GROK_TUI_ID } from '../../lib/grok.js';+import { getSettings } from '../settings.js';+import { getRecord } from './records.js';+import { requireTrack, loadManifest } from './reference.js';+import { AMBIENT_TRACK, clampTrackFrameCount, clampTrackFps, getAnimationTrack } from './animationTracks.js';+import { spriteDir, resolveSpriteAssetPath, SOURCE_CLIP_NAME } from './paths.js';+import { prepareWalkAnchorChromaInput, runWalkPostprocess } from './walkPostprocess.js';+import { verifyPackagedFrames } from './walkFrames.js';+import { resolveChromaKey, withAnimationWriteTail } from './animationWorkflow.js';+import { resolveGrokDuration } from '../../lib/grokVideoClip.js';+import { buildAmbientVideoPrompt } from './prompts.js';++const RUN_RECORD_NAME = 'animation-run.json';+const AMBIENT_DIRECTION = 'south';+const TUI_IDLE_MS = 90_000;+const TUI_TIMEOUT_MS = 30 * 60_000;+const selectionRelPath = (id) => `ambient/${id}-ambient-selection-v1.json`;+export const ambientSetRelPath = (id) => `ambient/${id}-ambient-set-v1.json`;+const runRelPath = (runId) => `runs/${runId}`;++const ambientSetFinalError = () => new ServerError(+ 'Ambient loop is finalized and immutable',+ { status: 409, code: 'AMBIENT_SET_FINAL' },+);++const loadSelection = (recordId) => readJSONFile(join(spriteDir(recordId), selectionRelPath(recordId)), null);+const loadSet = (recordId) => readJSONFile(join(spriteDir(recordId), ambientSetRelPath(recordId)), null);+const loadRun = (recordId, runId) => readJSONFile(join(spriteDir(recordId), runRelPath(runId), RUN_RECORD_NAME), null);++const seedSelection = (recordId) => ({+ schemaVersion: 1,+ kind: 'reviewed-single-row-ambient-selection',+ track: AMBIENT_TRACK,+ characterId: recordId,+ status: 'in-progress',+ directions: {},+});++async function saveRun(recordId, run) {+ const dir = join(spriteDir(recordId), runRelPath(run.id));+ await ensureDir(dir);+ await atomicWrite(join(dir, RUN_RECORD_NAME), run);+}++async function ambientRuns(recordId) {+ const runsDir = join(spriteDir(recordId), 'runs');+ const entries = await readdir(runsDir, { withFileTypes: true }).catch(() => []);+ const runs = await Promise.all(entries.filter((entry) => entry.isDirectory()).map((entry) => (+ readJSONFile(join(runsDir, entry.name, RUN_RECORD_NAME), null)+ )));+ return runs.filter((run) => run?.track === AMBIENT_TRACK)+ .sort((a, b) => Date.parse(b.createdAt || 0) - Date.parse(a.createdAt || 0));+}++export async function getAmbientState(recordId) {+ const [selection, ambientSet, runs] = await Promise.all([+ loadSelection(recordId), loadSet(recordId), ambientRuns(recordId),+ ]);+ return {+ track: AMBIENT_TRACK,+ bounds: getAnimationTrack(AMBIENT_TRACK),+ selection,+ ambientSet,+ runs,+ };+}++const lockedMain = (manifest) => (+ manifest?.mainReference?.locked && manifest.mainReference.path ? manifest.mainReference : null+);++const ambientTask = ({ prompt, inputAbs, videoAbs, duration }) => (+ `${prompt}\n\nUse your built-in image_to_video tool to animate this exact image for ${duration} seconds:\n${inputAbs}\n\n`+ + `Save the resulting animation as an MP4 file at exactly this path:\n${videoAbs}\n\n`+ + 'Do not create or modify any other files, and do not run any tools beyond what is needed to render and save that MP4.'+);++export function startAmbientGeneration(recordId, body) {+ return withAnimationWriteTail(recordId, () => startAmbientGenerationImpl(recordId, body));+}++async function startAmbientGenerationImpl(recordId, body) {+ const [record, reference, ambientSet, existingRuns] = await Promise.all([+ requireTrack(recordId, AMBIENT_TRACK), loadManifest(recordId), loadSet(recordId), ambientRuns(recordId),+ ]);+ if (ambientSet) throw ambientSetFinalError();+ const main = lockedMain(reference);+ if (!main) throw new ServerError('Lock the main reference before generating an ambient loop', { status: 409, code: 'MAIN_NOT_LOCKED' });+ const chromaKey = resolveChromaKey({ manifest: reference, record });+ if (!chromaKey) throw new ServerError('No frozen chroma key is available for this sprite', { status: 409, code: 'CHROMA_KEY_REQUIRED' });+ if (existingRuns.some((run) => ['rendering', 'postprocessing'].includes(run.status))) {+ throw new ServerError('An ambient render is already in progress', { status: 409, code: 'AMBIENT_RENDER_IN_PROGRESS' });+ }++ const frameCount = clampTrackFrameCount(body.frameCount, AMBIENT_TRACK);+ const fps = clampTrackFps(body.fps, AMBIENT_TRACK);+ const runId = `${AMBIENT_TRACK}-${randomUUID().slice(0, 8)}`;+ const runRel = runRelPath(runId);+ const generatedAbs = join(spriteDir(recordId), runRel, 'generated');+ await ensureDir(generatedAbs);+ const mainAbs = resolveSpriteAssetPath(recordId, main.path);+ if (!await pathExists(mainAbs)) throw new ServerError('Locked main reference file is missing on disk', { status: 500, code: 'MAIN_REFERENCE_MISSING' });+ const inputAbs = join(generatedAbs, 'input-main-chroma.png');+ const [{ preparation, sha256: inputSha256 }, settings] = await Promise.all([+ prepareWalkAnchorChromaInput(mainAbs, inputAbs, chromaKey), getSettings(),+ ]);+ const duration = resolveGrokDuration(body.duration);+ const videoAbs = join(generatedAbs, SOURCE_CLIP_NAME);+ const run = {+ schemaVersion: 1,+ kind: 'grok-game-animation-frames-run',+ track: AMBIENT_TRACK,+ provider: GROK_TUI_ID,+ status: 'rendering',+ id: runId,+ shellSession: runId,+ characterId: recordId,+ direction: AMBIENT_DIRECTION,+ chromaKey,+ duration,+ frameCount,+ fps,+ anchorPath: main.path,+ anchorSha256: main.sha256 || await sha256File(mainAbs),+ animationInputPath: `${runRel}/generated/input-main-chroma.png`,+ animationInputSha256: inputSha256,+ animationInputPreparation: preparation,+ createdAt: new Date().toISOString(),+ };+ await saveRun(recordId, run);+ runAmbientTuiRender(recordId, {+ runId,+ generatedAbs,+ videoAbs,+ grokPath: settings.imageGen?.grok?.grokPath,+ task: ambientTask({ prompt: buildAmbientVideoPrompt({ name: record.name, kind: record.kind, chromaKey }), inputAbs, videoAbs, duration }),+ }).catch((err) => console.error(`❌ sprite ambient grok-tui render crashed ${recordId}/${runId}: ${err?.message || err}`));+ console.log(`📡 sprite ambient grok-tui render started ${recordId}/${runId}`);+ return { runId, duration, shellSession: runId };+}++async function runAmbientTuiRender(recordId, { runId, generatedAbs, videoAbs, grokPath, task }) {+ await executeTuiRun({+ runId,+ provider: { id: GROK_TUI_ID, type: 'tui', command: grokPath || 'grok', args: [] },+ prompt: task,+ workspacePath: generatedAbs,+ idleMs: TUI_IDLE_MS,+ timeout: TUI_TIMEOUT_MS,+ label: `sprite ambient ${recordId}`,+ }).catch((err) => console.error(`❌ sprite ambient grok-tui run failed ${recordId}/${runId}: ${err?.message || err}`));+ await withAnimationWriteTail(recordId, () => attachAmbientTuiResult(recordId, runId, videoAbs));+}++export async function attachAmbientTuiResult(recordId, runId, videoAbs) {+ const run = await loadRun(recordId, runId);+ if (!run || run.track !== AMBIENT_TRACK || await loadSet(recordId)) return;+ const selection = await loadSelection(recordId);+ if (selection?.directions?.[AMBIENT_DIRECTION]?.runId === runId) return;+ if (!await pathExists(videoAbs)) {+ run.status = 'error';+ run.postprocessError = 'Grok finished without writing the ambient video — check the shell session output';+ run.completedAt = new Date().toISOString();+ await saveRun(recordId, run);+ return;+ }+ run.status = 'postprocessing';+ run.sourceVideoPath = `${runRelPath(run.id)}/generated/${SOURCE_CLIP_NAME}`;+ await saveRun(recordId, run);+ await packageAmbientRun(recordId, run);+ await saveRun(recordId, run);+}++async function packageAmbientRun(recordId, run) {+ try {+ const [reference, record] = await Promise.all([loadManifest(recordId), getRecord(recordId)]);+ const main = lockedMain(reference);+ if (!main) throw new Error('No locked main reference in the reference manifest');+ const chromaKey = resolveChromaKey({ manifest: reference, record, run });+ if (!chromaKey) throw new Error('No chroma key is available for the ambient matte');+ const runRel = runRelPath(run.id);+ const result = await runWalkPostprocess({+ recordId,+ track: AMBIENT_TRACK,+ direction: AMBIENT_DIRECTION,+ chromaKey,+ runAbs: join(spriteDir(recordId), runRel),+ runRel,+ anchorRel: main.path,+ anchorAbs: resolveSpriteAssetPath(recordId, main.path),+ videoAbs: resolveSpriteAssetPath(recordId, run.sourceVideoPath),+ frameCount: clampTrackFrameCount(run.frameCount, AMBIENT_TRACK),+ fps: clampTrackFps(run.fps, AMBIENT_TRACK),+ });+ run.frameCount = result.manifest.frameCount;+ run.fps = result.manifest.frameRate;+ run.status = 'candidate';+ run.postprocessManifest = result.manifestPath;+ run.stripPreview = result.stripPreview;+ delete run.postprocessError;+ } catch (err) {+ run.status = 'error';+ run.postprocessError = err.message;+ console.error(`❌ sprite ambient postprocess failed ${recordId}/${run.id}: ${err.message}`);+ }+ run.completedAt = new Date().toISOString();+}++export function approveAmbientLoop(recordId, args) {+ return withAnimationWriteTail(recordId, () => approveAmbientLoopImpl(recordId, args));+}++async function approveAmbientLoopImpl(recordId, { runId }) {+ await requireTrack(recordId, AMBIENT_TRACK);+ if (await loadSet(recordId)) throw ambientSetFinalError();+ const run = await loadRun(recordId, runId);+ if (!run || run.track !== AMBIENT_TRACK) throw new ServerError(`Unknown ambient run: ${runId}`, { status: 404, code: 'RUN_NOT_FOUND' });+ if (run.status !== 'candidate' || !run.postprocessManifest) throw new ServerError('Run has no packaged candidate to approve', { status: 409, code: 'RUN_NOT_CANDIDATE' });+ const [reference, packaged] = await Promise.all([+ loadManifest(recordId), readJSONFile(resolveSpriteAssetPath(recordId, run.postprocessManifest), null),+ ]);+ const main = lockedMain(reference);+ if (!main) throw new ServerError('Lock the main reference before approving its ambient loop', { status: 409, code: 'MAIN_NOT_LOCKED' });+ if (run.anchorSha256) {+ const currentMainSha256 = main.sha256 || await sha256File(resolveSpriteAssetPath(recordId, main.path));+ if (run.anchorSha256 !== currentMainSha256) {+ throw new ServerError('This ambient loop was rendered from an older main reference — generate it again from the current reference', { status: 409, code: 'RUN_ANCHOR_STALE' });+ }+ }+ if (!packaged || packaged.track !== AMBIENT_TRACK || packaged.direction !== AMBIENT_DIRECTION || packaged.characterId !== recordId+ || packaged.frameCount !== run.frameCount || packaged.frameRate !== run.fps) {+ throw new ServerError('Packaged ambient manifest is missing or inconsistent', { status: 409, code: 'RUN_MANIFEST_INVALID' });+ }+ const frameCheck = await verifyPackagedFrames(recordId, packaged, { track: AMBIENT_TRACK });+ if (frameCheck.missing) throw new ServerError(+ `${frameCheck.missing} of this ambient run's ${frameCheck.total} packaged frames are missing on disk`,+ { status: 409, code: 'RUN_FRAMES_MISSING' },+ );+ const selection = (await loadSelection(recordId)) || seedSelection(recordId);+ selection.directions[AMBIENT_DIRECTION] = {+ status: 'approved',+ runId,+ runPath: runRelPath(runId),+ runManifest: run.postprocessManifest,+ runManifestSha256: await sha256File(resolveSpriteAssetPath(recordId, run.postprocessManifest)),+ approvedAt: new Date().toISOString(),+ };+ selection.status = 'complete';+ const selectionAbs = join(spriteDir(recordId), selectionRelPath(recordId));+ await ensureDir(join(spriteDir(recordId), AMBIENT_TRACK));+ await atomicWrite(selectionAbs, selection);+ await atomicWrite(join(spriteDir(recordId), ambientSetRelPath(recordId)), {+ schemaVersion: 1,+ kind: 'finalized-single-row-ambient-set',+ track: AMBIENT_TRACK,+ characterId: recordId,+ status: 'final',+ directionOrder: [AMBIENT_DIRECTION],+ selectionPath: selectionRelPath(recordId),+ selectionSha256: await sha256File(selectionAbs),+ directions: selection.directions,+ finalizedAt: new Date().toISOString(),+ });+ console.log(`🏁 sprite ambient loop finalized for ${recordId}`);+ return getAmbientState(recordId);+}diff --git a/server/services/sprites/ambient.test.js b/server/services/sprites/ambient.test.jsnew file mode 100644index 0000000000..2e734d8d9e--- /dev/null+++ b/server/services/sprites/ambient.test.js@@ -0,0 +1,99 @@+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';+import { mkdtempSync, rmSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { mkdir, writeFile } from 'fs/promises';+import { createHash } from 'crypto';+import { placeCandidate } from './spriteTestFixtures.js';++const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-ambient-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'),+ videos: join(TEST_ROOT, 'videos'),+ });+ return actual;+});++const executeTuiRun = vi.fn(() => new Promise(() => {}));+vi.mock('../../lib/tuiPromptRunner.js', () => ({+ executeTuiRun: (...args) => executeTuiRun(...args),+}));++vi.mock('../settings.js', () => ({+ getSettings: async () => ({ imageGen: { grok: { grokPath: '/usr/local/bin/grok' } } }),+}));++const prepareWalkAnchorChromaInput = vi.fn(async (_mainAbs, inputAbs) => {+ await mkdir(join(inputAbs, '..'), { recursive: true });+ const bytes = Buffer.from('ambient-chroma-input');+ await writeFile(inputAbs, bytes);+ return {+ preparation: 'composited-over-solid-chroma-matte',+ sha256: createHash('sha256').update(bytes).digest('hex'),+ };+});+vi.mock('./walkPostprocess.js', async (importOriginal) => ({+ ...await importOriginal(),+ prepareWalkAnchorChromaInput: (...args) => prepareWalkAnchorChromaInput(...args),+}));++const records = await import('./records.js');+const { lockReference } = await import('./reference.js');+const { getAmbientState, startAmbientGeneration } = await import('./ambient.js');++let sequence = 0;+const newId = () => `ambient-${++sequence}`;++async function placeWithLockedMain(id) {+ await records.createRecord({ kind: 'place', name: 'Willow' }, id);+ const candidate = await placeCandidate(TEST_ROOT, id, 'main', 'main-candidate-01.png');+ await lockReference(id, { target: 'main', candidate });+ return id;+}++beforeEach(() => {+ executeTuiRun.mockClear();+ executeTuiRun.mockImplementation(() => new Promise(() => {}));+ prepareWalkAnchorChromaInput.mockClear();+ rmSync(join(TEST_ROOT, 'sprite-records.json'), { force: true });+});+afterAll(() => rmSync(TEST_ROOT, { recursive: true, force: true }));++describe('ambient animation track', () => {+ it('is provider-silent on reads, then starts one explicit non-directional image-to-video loop', async () => {+ const id = await placeWithLockedMain(newId());++ const initial = await getAmbientState(id);+ expect(initial).toMatchObject({+ track: 'ambient',+ bounds: { minFrameCount: 2, maxFrameCount: 6, defaultFrameCount: 3, defaultFps: 4 },+ runs: [],+ });+ expect(executeTuiRun).not.toHaveBeenCalled();++ const result = await startAmbientGeneration(id, {});+ expect(result).toMatchObject({ duration: 6 });+ expect(result.runId).toMatch(/^ambient-[0-9a-f]{8}$/);+ expect(result.shellSession).toBe(result.runId);+ expect(executeTuiRun).toHaveBeenCalledOnce();+ expect(executeTuiRun.mock.calls[0][0]).toMatchObject({+ runId: result.runId,+ workspacePath: join(TEST_ROOT, 'sprites', id, 'runs', result.runId, 'generated'),+ });+ expect(executeTuiRun.mock.calls[0][0].prompt).toContain('image_to_video');++ expect((await getAmbientState(id)).runs).toMatchObject([{+ id: result.runId,+ track: 'ambient',+ status: 'rendering',+ frameCount: 3,+ fps: 4,+ direction: 'south',+ }]);+ });+});diff --git a/server/services/sprites/animationTracks.js b/server/services/sprites/animationTracks.jsindex 7b270a9505..bfe2c90de7 100644--- a/server/services/sprites/animationTracks.js+++ b/server/services/sprites/animationTracks.js@@ -44,6 +44,8 @@export const WALK_TRACK = 'walk';/** The first short, directional character action (#3018). */export const SCANNER_TRACK = 'scanner';+/** The first non-directional environment loop (#3045). */+export const AMBIENT_TRACK = 'ambient';/*** Every known animation track.@@ -105,6 +107,24 @@ export const ANIMATION_TRACKS = Object.freeze({// The game owns action timing; PortOS carries fps as preview provenance.contractFpsField: null,}),+ [AMBIENT_TRACK]: Object.freeze({+ id: AMBIENT_TRACK,+ label: 'Ambient loop',+ directional: false,+ // `props` is the legacy import-only spelling of `object`; keeping it here+ // makes an imported prop atlas and a newly-authored object behave alike.+ kinds: Object.freeze(['place', 'object', 'props']),+ minFrameCount: 2,+ maxFrameCount: 6,+ defaultFrameCount: 3,+ minFps: 2,+ maxFps: 12,+ defaultFps: 4,+ contractFrameCountField: 'ambientFrameCount',+ // Ambient cadence belongs to the consuming app. PortOS keeps fps only as+ // authoring-preview provenance, like scanner.+ contractFpsField: null,+ }),});/** Known track ids, in registry order. */diff --git a/server/services/sprites/animationTracks.test.js b/server/services/sprites/animationTracks.test.jsindex b2afe9adba..787ab3805b 100644--- a/server/services/sprites/animationTracks.test.js+++ b/server/services/sprites/animationTracks.test.js@@ -13,7 +13,7 @@ import { readFileSync } from 'fs';import { fileURLToPath } from 'url';import { dirname, join } from 'path';import {- WALK_TRACK, SCANNER_TRACK, ANIMATION_TRACKS, ANIMATION_TRACK_IDS,+ WALK_TRACK, SCANNER_TRACK, AMBIENT_TRACK, ANIMATION_TRACKS, ANIMATION_TRACK_IDS,isAnimationTrack, getAnimationTrack, clampTrackFrameCount, clampTrackFps,assertAnimationTrackRows, trackRowCount, tracksForKind, kindSupportsTrack,} from './animationTracks.js';@@ -68,6 +68,23 @@ describe('the registry rows', () => {});});+ it('registers the single-row ambient loop for places and objects', () => {+ expect(getAnimationTrack(AMBIENT_TRACK)).toMatchObject({+ id: AMBIENT_TRACK,+ label: 'Ambient loop',+ directional: false,+ kinds: ['place', 'object', 'props'],+ minFrameCount: 2,+ maxFrameCount: 6,+ defaultFrameCount: 3,+ minFps: 2,+ maxFps: 12,+ defaultFps: 4,+ contractFrameCountField: 'ambientFrameCount',+ contractFpsField: null,+ });+ });+it('describes every declared track completely', () => {// Mirrors the module-load guard in animationTracks.js (which is what// actually blocks boot on a bad row) so a shape violation reads as a named@@ -237,10 +254,10 @@ describe('directionality and record-kind support (#3017)', () => {expect(kindSupportsTrack('character', 'nope', MIXED)).toBe(false);});- it('keeps the shipped registry character-only while admitting walk and scanner', () => {+ it('admits ambient loops for non-character sprite kinds', () => {expect(tracksForKind('character').map((r) => r.id)).toEqual([WALK_TRACK, SCANNER_TRACK]);for (const kind of ['place', 'object', 'props']) {- expect(tracksForKind(kind), `${kind} has no track yet`).toEqual([]);+ expect(tracksForKind(kind).map((r) => r.id), `${kind} carries the ambient loop`).toEqual([AMBIENT_TRACK]);}});@@ -285,6 +302,13 @@ describe('per-track clamps', () => {expect(clampTrackFps(99, SCANNER_TRACK)).toBe(12);expect(clampTrackFps(-1, SCANNER_TRACK)).toBe(2);});++ it('clamps ambient values against the ambient range', () => {+ expect(clampTrackFrameCount(99, AMBIENT_TRACK)).toBe(6);+ expect(clampTrackFrameCount(-1, AMBIENT_TRACK)).toBe(2);+ expect(clampTrackFps(99, AMBIENT_TRACK)).toBe(12);+ expect(clampTrackFps(-1, AMBIENT_TRACK)).toBe(2);+ });});describe('walkBounds re-reads the walk row (no call-site churn)', () => {diff --git a/server/services/sprites/assetPrompt.js b/server/services/sprites/assetPrompt.jsindex b3bc0040fb..727f0e0316 100644--- a/server/services/sprites/assetPrompt.js+++ b/server/services/sprites/assetPrompt.js@@ -32,8 +32,10 @@ import { spriteDir, resolveSpriteAssetPath, RUN_DIR_MATCH } from './paths.js';import { getRecord } from './records.js';import { loadManifest } from './reference.js';import {- buildMainReferencePrompt, buildAnchorPrompt, buildWalkVideoPrompt, buildTurnaroundPrompt, TURNAROUND_ID,+ buildMainReferencePrompt, buildAmbientReferencePrompt, buildAnchorPrompt,+ buildWalkVideoPrompt, buildAmbientVideoPrompt, buildTurnaroundPrompt, TURNAROUND_ID,} from './prompts.js';+import { AMBIENT_TRACK } from './animationTracks.js';import { DEFAULT_CHROMA_KEY } from './chromaKey.js';const CANDIDATE_RE = /^reference\/candidates\/(.+)\.png$/i;@@ -43,7 +45,7 @@ const CANDIDATE_RE = /^reference\/candidates\/(.+)\.png$/i;* source }` result — the stored literal prompt when captured, otherwise a* faithful rebuild from the parameters the sidecar did record.*/-function fromCandidateSidecar(sidecar, name, fromTurnaround = false) {+function fromCandidateSidecar(sidecar, name, fromTurnaround = false, kind = 'character') {if (!sidecar) return null;if (typeof sidecar.prompt === 'string' && sidecar.prompt) {return { prompt: sidecar.prompt, designPrompt: sidecar.designPrompt || null, source: 'candidate' };@@ -54,7 +56,9 @@ function fromCandidateSidecar(sidecar, name, fromTurnaround = false) {if (sidecar.target === TURNAROUND_ID) {prompt = buildTurnaroundPrompt({ name, designPrompt, chromaKey });} else if (sidecar.target === 'main') {- prompt = buildMainReferencePrompt({ name, designPrompt, chromaKey, fromTurnaround });+ prompt = kind === 'character'+ ? buildMainReferencePrompt({ name, designPrompt, chromaKey, fromTurnaround })+ : buildAmbientReferencePrompt({ name, kind, designPrompt, chromaKey });} else {prompt = buildAnchorPrompt({ name, direction: sidecar.direction || sidecar.target, chromaKey, fromTurnaround });}@@ -80,7 +84,7 @@ export async function resolveSpriteAssetPrompt(recordId, relPath) {// 1. Reviewable candidate — its own generation sidecar.const cand = CANDIDATE_RE.exec(relPath);if (cand) {- return fromCandidateSidecar(await candidateSidecarFor(recordId, cand[1]), name);+ return fromCandidateSidecar(await candidateSidecarFor(recordId, cand[1]), name, false, record.kind);}// 2. Locked main / directional anchor — resolved through the manifest.@@ -127,15 +131,19 @@ export async function resolveSpriteAssetPrompt(recordId, relPath) {// Prefer the frozen candidate's literal prompt; fall back to a rebuild// from the manifest's own recorded design prompt + key.const stem = candidateStem(main.lockedFrom);- const fromCandidate = stem ? fromCandidateSidecar(await candidateSidecarFor(recordId, stem), name, fromTurnaround(main)) : null;+ const fromCandidate = stem ? fromCandidateSidecar(await candidateSidecarFor(recordId, stem), name, fromTurnaround(main), record.kind) : null;// Fallback (source candidate sidecar gone): rebuild from the manifest.return fromCandidate || {- prompt: buildMainReferencePrompt({- name,- designPrompt: manifest.designPrompt,- chromaKey: renderKey(main, turnaround),- fromTurnaround: fromTurnaround(main),- }),+ prompt: record.kind === 'character'+ ? buildMainReferencePrompt({+ name,+ designPrompt: manifest.designPrompt,+ chromaKey: renderKey(main, turnaround),+ fromTurnaround: fromTurnaround(main),+ })+ : buildAmbientReferencePrompt({+ name, kind: record.kind, designPrompt: manifest.designPrompt, chromaKey: renderKey(main, turnaround),+ }),designPrompt: manifest.designPrompt || null,source: 'reference-main',};@@ -163,9 +171,11 @@ export async function resolveSpriteAssetPrompt(recordId, relPath) {return {prompt: typeof runRecord.prompt === 'string' && runRecord.prompt? runRecord.prompt- : buildWalkVideoPrompt({ name, direction: runRecord.direction, chromaKey: runRecord.chromaKey }),+ : runRecord.track === AMBIENT_TRACK+ ? buildAmbientVideoPrompt({ name, kind: record.kind, chromaKey: runRecord.chromaKey })+ : buildWalkVideoPrompt({ name, direction: runRecord.direction, chromaKey: runRecord.chromaKey }),designPrompt: null,- source: 'walk',+ source: runRecord.track === AMBIENT_TRACK ? 'ambient' : 'walk',};}}diff --git a/server/services/sprites/atlas.js b/server/services/sprites/atlas.jsindex d413f19016..3ddd3ed53c 100644--- a/server/services/sprites/atlas.js+++ b/server/services/sprites/atlas.js@@ -50,7 +50,9 @@ import {alphaBbox, robustBottomRow, rootX, rootBandForManifest, ROBUST_BASELINE_MIN_PIXELS, compositeOnto, sha256Buffer,} from './walkPostprocess.js';import { ATLAS_IDLE_COLUMN } from './walkBounds.js';-import { WALK_TRACK, SCANNER_TRACK, ANIMATION_TRACK_IDS } from './animationTracks.js';+import {+ WALK_TRACK, SCANNER_TRACK, AMBIENT_TRACK, ANIMATION_TRACK_IDS, kindSupportsTrack,+} from './animationTracks.js';import {buildAtlasGrid, resolveTrackUniformity, compiledGridUpToDate, trackDirections,} from './atlasGrid.js';@@ -58,6 +60,7 @@ import {withWalkWriteTail, walkSetRelPath, importedWalkDirections, resolveChromaKey,} from './walk.js';import { scannerSetRelPath } from './scanner.js';+import { ambientSetRelPath } from './ambient.js';import { verifyPackagedFrames } from './walkFrames.js';import { getRecord } from './records.js';@@ -263,6 +266,11 @@ function sharedRowPasteX(anchoredX, boundsList, geometry) {* reference set's anchors. Returns everything the compiler consumes.*/export async function validateForCompile(recordId) {+ const recordForTrack = await getRecord(recordId);+ if (recordForTrack && kindSupportsTrack(recordForTrack.kind, AMBIENT_TRACK)+ && !kindSupportsTrack(recordForTrack.kind, WALK_TRACK)) {+ return validateAmbientForCompile(recordId, recordForTrack);+ }// Every hashed input is read exactly once: verify the bytes in memory and// hand those same bytes to the compiler, so the pixels compiled are// provably the pixels verified (no re-read between check and use). Paths@@ -491,6 +499,152 @@ export async function validateForCompile(recordId) {};}+/** Validate the one-main-reference / one-row evidence chain for ambient-only records. */+async function validateAmbientForCompile(recordId, record) {+ const readVerified = async (relPath, expectedSha, label) => {+ const bytes = await readFile(resolveSpriteAssetPath(recordId, relPath)).catch(() => null);+ if (!bytes || sha256Buffer(bytes) !== expectedSha) {+ throw compileError(`${label} no longer matches its recorded sha256`);+ }+ return bytes;+ };+ const dir = spriteDir(recordId);+ const setRel = ambientSetRelPath(recordId);+ const setBytes = await readFile(join(dir, setRel)).catch(() => null);+ if (!setBytes) throw compileError('No finalized ambient loop — approve its single row first', 'AMBIENT_SET_REQUIRED');+ let ambientSet;+ try {+ ambientSet = JSON.parse(setBytes);+ } catch {+ throw compileError('Ambient set manifest is unreadable');+ }+ if (ambientSet.kind !== 'finalized-single-row-ambient-set' || ambientSet.track !== AMBIENT_TRACK+ || ambientSet.status !== 'final' || ambientSet.characterId !== recordId+ || JSON.stringify(ambientSet.directionOrder) !== JSON.stringify(['south'])) {+ throw compileError('Ambient set manifest is not a finalized single-row ambient set');+ }+ await readVerified(ambientSet.selectionPath, ambientSet.selectionSha256, 'Ambient selection file');+ const referenceManifest = await loadManifest(recordId);+ const main = referenceManifest?.mainReference;+ if (!main?.locked || !main.path || !main.sha256) {+ throw compileError('Main reference is not locked', 'REFERENCE_INCOMPLETE');+ }+ const chromaKey = resolveChromaKey({ manifest: referenceManifest, record });+ if (!chromaKey) throw compileError('Reference manifest has no frozen chroma key');+ const mainBytes = await readVerified(main.path, main.sha256, 'Locked main reference');+ const entry = ambientSet.directions?.south;+ if (!entry || entry.status !== 'approved') throw compileError('Ambient row is not approved');+ const manifestBytes = await readVerified(entry.runManifest, entry.runManifestSha256, 'Ambient run manifest');+ let manifest;+ try {+ manifest = JSON.parse(manifestBytes);+ } catch {+ manifest = null;+ }+ if (!manifest || manifest.track !== AMBIENT_TRACK || manifest.direction !== 'south') {+ throw compileError('Ambient run manifest is unreadable or mislabeled');+ }+ const ambient = resolveTrackUniformity(AMBIENT_TRACK, [{+ direction: 'south',+ frameCount: (manifest.frames || []).length,+ declaredFrameCount: manifest.frameCount,+ fps: manifest.frameRate,+ }], { error: compileError, expectedRows: 1 });+ const { frameBytes } = await verifyPackagedFrames(recordId, manifest, { bytes: true, track: AMBIENT_TRACK });+ return {+ ambientOnly: true,+ scannerSet: null,+ scannerSetSha256: null,+ ambientSet,+ ambientSetPath: setRel,+ ambientSetSha256: sha256Buffer(setBytes),+ referenceManifest,+ chromaKey,+ mainReference: { ...main, bytes: mainBytes },+ ambientRun: { runId: entry.runId, manifestPath: entry.runManifest, manifest, frameBytes },+ tracks: [ambient],+ walkFrameCount: null,+ walkFps: null,+ scannerFrameCount: null,+ ambientFrameCount: ambient.frameCount,+ };+}++async function compileAmbientRow(validated, geometry) {+ const split = keyChannelSplit(validated.chromaKey);+ const { manifest, runId, manifestPath, frameBytes } = validated.ambientRun;+ const ambientSources = [];+ for (const bytes of frameBytes) ambientSources.push(await transparentSource(bytes, split, validated.chromaKey));+ const dims = ambientSources.map((source, index) => occupiedDimensions(+ source, ALPHA_THRESHOLD, `ambient-${manifest.frames[index].phase}`, true,+ ));+ const ambientScale = Math.min(+ geometry.targetMaxHeight / Math.max(...dims.map((dim) => dim.height)),+ geometry.targetMaxWidth / Math.max(...dims.map((dim) => dim.width)),+ );+ const cells = [];+ const idleSource = await transparentSource(validated.mainReference.bytes, split, validated.chromaKey);+ const idleDims = occupiedDimensions(idleSource, SILHOUETTE_ALPHA_THRESHOLD, 'ambient-idle');+ const desiredIdleHeight = median(dims.map((dim) => dim.height)) * ambientScale;+ const idleScale = Math.min(desiredIdleHeight / idleDims.height, geometry.targetMaxWidth / idleDims.width);+ const idleScaled = await scaleForCell(idleSource, idleScale, 'ambient-idle');+ const idle = placeCell(+ idleScaled.scaled,+ idleScaled.bounds,+ idleScaled.baseline,+ sharedRowPasteX(pyRound((geometry.cellSize - idleScaled.scaled.width) / 2), [idleScaled.bounds], geometry),+ 'ambient-idle',+ geometry,+ idleScale,+ );+ cells.push({+ column: ATLAS_IDLE_COLUMN,+ track: ATLAS_IDLE_COLUMN,+ frameIndex: 0,+ ...idle,+ sourcePath: validated.mainReference.path,+ sourceSha256: validated.mainReference.sha256,+ policy: 'locked-main-reference',+ });+ const pivotX = Number(manifest.alignment?.targetPivot?.[0]);+ const sourcePivotX = Number.isFinite(pivotX)+ ? pivotX+ : (Number(manifest.alignment?.cellSize) || ambientSources[0].width) / 2;+ const scaled = [];+ for (let index = 0; index < ambientSources.length; index++) {+ scaled.push(await scaleForCell(ambientSources[index], ambientScale, `ambient-${manifest.frames[index].phase}`));+ }+ const pasteX = sharedRowPasteX(+ pyRound(geometry.pivot[0] - sourcePivotX * ambientScale),+ scaled.map((item) => item.bounds),+ geometry,+ );+ for (let index = 0; index < scaled.length; index++) {+ const frame = manifest.frames[index];+ const normalized = placeCell(+ scaled[index].scaled, scaled[index].bounds, scaled[index].baseline,+ pasteX, `ambient-${frame.phase}`, geometry, ambientScale,+ );+ cells.push({+ column: frame.phase,+ track: AMBIENT_TRACK,+ frameIndex: index,+ ...normalized,+ sourcePath: frame.path,+ sourceSha256: frame.sha256,+ });+ }+ return {+ direction: 'south',+ runId,+ runManifestPath: manifestPath,+ ambientScale: pyRoundTo(ambientScale, 8),+ idleScale: pyRoundTo(idleScale, 8),+ idlePolicy: 'locked-main-reference',+ cells,+ };+}+async function compileDirectionRow(recordId, direction, validated, geometry) {const split = keyChannelSplit(validated.chromaKey);const { manifest, runId, manifestPath, frameBytes } = validated.runs[direction];@@ -734,6 +888,7 @@ export async function compileAtlasInTail(recordId, { geometry: geometryOverride&& currentAtlasOnDisk&& current.walkSetSha256 === validated.walkSetSha256&& (current.scannerSetSha256 ?? null) === validated.scannerSetSha256+ && (current.ambientSetSha256 ?? null) === (validated.ambientSetSha256 ?? null)&& compiledGridUpToDate(current.geometry, { ...geometry, columns, tracks })) {return { ...current, created: false };@@ -747,10 +902,9 @@ export async function compileAtlasInTail(recordId, { geometry: geometryOverride// where the sidecar says it does or the compile fails loudly. Producing the// frames for a second track is still #3018's job; this is the grid contract// that track will slot into.- const rows = [];- for (const direction of SPRITE_DIRECTIONS) {- rows.push(await compileDirectionRow(recordId, direction, validated, geometry));- }+ const rows = validated.ambientOnly+ ? [await compileAmbientRow(validated, geometry)]+ : await Promise.all(SPRITE_DIRECTIONS.map((direction) => compileDirectionRow(recordId, direction, validated, geometry)));// Resolve one cell's place in the grid from its track's span, once, and stamp// the answer on the cell so the manifest below reports where the pixels@@ -794,7 +948,9 @@ export async function compileAtlasInTail(recordId, { geometry: geometryOverrideconst atlasSha256 = sha256Buffer(atlasBuffer);if (current && currentAtlasOnDisk && current.walkSetSha256 === validated.walkSetSha256- && (current.scannerSetSha256 ?? null) === validated.scannerSetSha256 && current.atlasSha256 === atlasSha256) {+ && (current.scannerSetSha256 ?? null) === validated.scannerSetSha256+ && (current.ambientSetSha256 ?? null) === (validated.ambientSetSha256 ?? null)+ && current.atlasSha256 === atlasSha256) {return { ...current, created: false };}@@ -834,8 +990,9 @@ export async function compileAtlasInTail(recordId, { geometry: geometryOverrideatlasSha256,manifestPath: manifestRel,manifestSha256: sha256Buffer(survivingBuffer),- walkSetSha256: validated.walkSetSha256,+ ...(validated.walkSet ? { walkSetSha256: validated.walkSetSha256 } : {}),...(survivingManifest.scannerSetSha256 ? { scannerSetSha256: survivingManifest.scannerSetSha256 } : {}),+ ...(survivingManifest.ambientSetSha256 ? { ambientSetSha256: survivingManifest.ambientSetSha256 } : {}),geometry: survivingManifest.geometry,compiledAt: survivingManifest.createdAt,};@@ -846,18 +1003,24 @@ export async function compileAtlasInTail(recordId, { geometry: geometryOverrideconst manifest = {schemaVersion: 1,- kind: 'reviewed-walk-set-runtime-atlas',+ kind: validated.ambientOnly ? 'reviewed-ambient-set-runtime-atlas' : '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,+ ...(validated.walkSet ? {+ walkSetPath: validated.walkSetPath,+ walkSetSha256: validated.walkSetSha256,+ } : {}),...(validated.scannerSet ? {scannerSetPath: validated.scannerSetPath,scannerSetSha256: validated.scannerSetSha256,} : {}),+ ...(validated.ambientSet ? {+ ambientSetPath: validated.ambientSetPath,+ ambientSetSha256: validated.ambientSetSha256,+ } : {}),atlasPath: atlasRel,atlasSha256,geometry: {@@ -880,6 +1043,7 @@ export async function compileAtlasInTail(recordId, { geometry: geometryOverridewalkFrameCount: validated.walkFrameCount,walkFps: validated.walkFps,...(validated.scannerSet ? { scannerFrameCount: validated.scannerFrameCount } : {}),+ ...(validated.ambientSet ? { ambientFrameCount: validated.ambientFrameCount } : {}),},directions: rows.map((row) => ({direction: row.direction,@@ -914,8 +1078,9 @@ export async function compileAtlasInTail(recordId, { geometry: geometryOverrideatlasSha256,manifestPath: manifestRel,manifestSha256: sha256Buffer(manifestBuffer),- walkSetSha256: validated.walkSetSha256,+ ...(validated.walkSet ? { walkSetSha256: validated.walkSetSha256 } : {}),...(validated.scannerSet ? { scannerSetSha256: validated.scannerSetSha256 } : {}),+ ...(validated.ambientSet ? { ambientSetSha256: validated.ambientSetSha256 } : {}),geometry: manifest.geometry,compiledAt: manifest.createdAt,};diff --git a/server/services/sprites/atlas.test.js b/server/services/sprites/atlas.test.jsindex 9c6cea7217..33c3629d5d 100644--- a/server/services/sprites/atlas.test.js+++ b/server/services/sprites/atlas.test.js@@ -14,7 +14,7 @@ import { join } from 'path';import sharp from 'sharp';import { mkdir, writeFile, readFile } from 'fs/promises';import { createHash } from 'crypto';-import { lockAllAnchors as lockAllAnchorsFixture, trackSpan as fullSpan } from './spriteTestFixtures.js';+import { lockAllAnchors as lockAllAnchorsFixture, placeCandidate, trackSpan as fullSpan } from './spriteTestFixtures.js';const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-atlas-test-'));@@ -45,7 +45,7 @@ const { compileAtlas, getAtlasState, ATLAS_COLUMNS, DEFAULT_ATLAS_GEOMETRY } = aconst { SPRITE_DIRECTIONS } = await import('./prompts.js');const { WALK_PHASES, walkPhaseLabels, WALK_FPS } = await import('./walkPostprocess.js');const { buildAtlasGrid, compiledGridUpToDate } = await import('./atlasGrid.js');-const { getAnimationTrack, SCANNER_TRACK } = await import('./animationTracks.js');+const { getAnimationTrack, SCANNER_TRACK, AMBIENT_TRACK } = await import('./animationTracks.js');let seq = 0;const newId = () => `atlas-char-${++seq}`;@@ -213,6 +213,68 @@ async function buildFinalizedScannerSet(recordId, { frameCount = 4, fps = 6 } =}));}+async function finalizedAmbientPlace() {+ const id = `atlas-ambient-${++seq}`;+ await records.createRecord({ kind: 'place', name: 'Willow' }, id);+ const candidate = await placeCandidate(TEST_ROOT, id, 'main', 'main-candidate-01.png');+ await lockReference(id, { target: 'main', candidate });+ const manifest = await loadManifest(id);+ const dir = join(TEST_ROOT, 'sprites', id);+ const runId = `${AMBIENT_TRACK}-${(seq++).toString(16).padStart(8, '0')}`;+ const frameCount = 3;+ const frames = [];+ for (let i = 0; i < frameCount; i++) {+ const phase = `${AMBIENT_TRACK}-${String(i).padStart(2, '0')}`;+ const rel = `runs/${runId}/generated/frames/${String(i).padStart(2, '0')}-${phase}.png`;+ await walkFramePng(join(dir, rel), 30 + i * 20, 2 + i * 3);+ frames.push({ outputIndex: i, phase, path: rel, sha256: sha256(await readFile(join(dir, rel))) });+ }+ const runManifest = {+ schemaVersion: 1,+ kind: 'deterministically-packaged-grok-ambient-video',+ track: AMBIENT_TRACK,+ characterId: id,+ direction: 'south',+ chromaKey: manifest.chromaKey,+ frameCount,+ frameRate: 4,+ frames,+ };+ const runManifestRel = `runs/${runId}/generated/${id}-${AMBIENT_TRACK}-manifest.json`;+ const runManifestBytes = JSON.stringify(runManifest);+ await writeFile(join(dir, runManifestRel), runManifestBytes);+ const selection = {+ schemaVersion: 1,+ kind: 'reviewed-single-row-ambient-selection',+ track: AMBIENT_TRACK,+ characterId: id,+ status: 'complete',+ directions: {+ south: {+ status: 'approved', runId, runPath: `runs/${runId}`, runManifest: runManifestRel,+ runManifestSha256: sha256(Buffer.from(runManifestBytes)), approvedAt: new Date().toISOString(),+ },+ },+ };+ await mkdir(join(dir, AMBIENT_TRACK), { recursive: true });+ const selectionRel = `${AMBIENT_TRACK}/${id}-ambient-selection-v1.json`;+ const selectionBytes = JSON.stringify(selection);+ await writeFile(join(dir, selectionRel), selectionBytes);+ await writeFile(join(dir, `${AMBIENT_TRACK}/${id}-ambient-set-v1.json`), JSON.stringify({+ schemaVersion: 1,+ kind: 'finalized-single-row-ambient-set',+ track: AMBIENT_TRACK,+ characterId: id,+ status: 'final',+ directionOrder: ['south'],+ selectionPath: selectionRel,+ selectionSha256: sha256(Buffer.from(selectionBytes)),+ directions: selection.directions,+ finalizedAt: new Date().toISOString(),+ }));+ return id;+}+async function finalizedCharacter() {const id = newId();await lockAllAnchors(id);@@ -226,6 +288,25 @@ beforeEach(() => {afterAll(() => rmSync(TEST_ROOT, { recursive: true, force: true }));describe('compileAtlas', () => {+ it('compiles an ambient-only atlas with one occupied row and transparent unused rows', async () => {+ const id = await finalizedAmbientPlace();+ const result = await compileAtlas(id);+ const manifest = JSON.parse(await readFile(join(TEST_ROOT, 'sprites', id, result.manifestPath), 'utf8'));+ expect(manifest.kind).toBe('reviewed-ambient-set-runtime-atlas');+ expect(manifest.geometry).toMatchObject({+ columns: ['idle', 'ambient-00', 'ambient-01', 'ambient-02'],+ tracks: { idle: { start: 0, count: 1, rows: 1 }, ambient: { start: 1, count: 3, rows: 1 } },+ walkFrameCount: null,+ ambientFrameCount: 3,+ });+ expect(manifest.directions).toHaveLength(1);+ expect(manifest.directions[0].cells).toHaveLength(4);+ const pixels = await sharp(join(TEST_ROOT, 'sprites', id, result.atlasPath)).raw().toBuffer();+ const width = DEFAULT_ATLAS_GEOMETRY.cellSize * 4;+ const rowOneAlpha = pixels[(DEFAULT_ATLAS_GEOMETRY.cellSize * width * 4) + 3];+ expect(rowOneAlpha).toBe(0);+ });+it('compiles an approved four-frame scanner span beside the walk span', async () => {const id = newId();await lockAllAnchors(id);diff --git a/server/services/sprites/atlasLayout.js b/server/services/sprites/atlasLayout.jsindex 58a6ad6044..d8d3a55595 100644--- a/server/services/sprites/atlasLayout.js+++ b/server/services/sprites/atlasLayout.js@@ -112,6 +112,7 @@ export function buildAtlasLayout({tracks: deriveTracks(columns, walkFrameCount, geometry.tracks ?? null, rows ?? ATLAS_DEFAULT_ROWS),walkFrameCount,...(Number.isInteger(geometry.scannerFrameCount) ? { scannerFrameCount: geometry.scannerFrameCount } : {}),+ ...(Number.isInteger(geometry.ambientFrameCount) ? { ambientFrameCount: geometry.ambientFrameCount } : {}),previewFps: Number.isFinite(geometry.walkFps) ? geometry.walkFps : null,previewFpsNote: PREVIEW_FPS_NOTE,};@@ -133,7 +134,7 @@ export function runtimeContractMismatch(geometry, contract, appLabel = 'the bounconst actualColumns = geometry.columns.length;const actualFrames = resolveWalkFrameCount(geometry);const {- walkFrameCount: expectedFrames, scannerFrameCount: expectedScannerFrames,+ walkFrameCount: expectedFrames, scannerFrameCount: expectedScannerFrames, ambientFrameCount: expectedAmbientFrames,columnCount: expectedColumns, cellSize: expectedCellSize,} = contract;const actualDesc = `Atlas has ${actualColumns} columns (${actualFrames} walk frames)`;@@ -160,6 +161,14 @@ export function runtimeContractMismatch(geometry, contract, appLabel = 'the bounreturn `Atlas has ${actual} scanner frame${actual === 1 ? '' : 's'} but ${appLabel} expects ${expectedScannerFrames}. `+ 'Approve a scanner set at that frame count, or update the app runtime contract before publishing.';}+ const actualAmbientFrames = Number.isInteger(geometry.ambientFrameCount)+ ? geometry.ambientFrameCount+ : geometry.tracks?.ambient?.count ?? null;+ if (Number.isInteger(expectedAmbientFrames) && expectedAmbientFrames !== actualAmbientFrames) {+ const actual = Number.isInteger(actualAmbientFrames) ? actualAmbientFrames : 'no';+ return `Atlas has ${actual} ambient frame${actual === 1 ? '' : 's'} but ${appLabel} expects ${expectedAmbientFrames}. `+ + 'Approve an ambient loop at that frame count, or update the app runtime contract before publishing.';+ }if (Number.isInteger(expectedCellSize) && expectedCellSize !== geometry.cellSize) {return `Atlas cells are ${geometry.cellSize}px but ${appLabel} expects ${expectedCellSize}px. `+ `Recompile this atlas at ${expectedCellSize}px cells, or update the app's cell-size constant before publishing.`;diff --git a/server/services/sprites/atlasLayout.test.js b/server/services/sprites/atlasLayout.test.jsindex a788e43888..5d671098c6 100644--- a/server/services/sprites/atlasLayout.test.js+++ b/server/services/sprites/atlasLayout.test.js@@ -170,4 +170,24 @@ describe('runtimeContractMismatch', () => {+ "Recompile this atlas at 96px cells, or update the app's cell-size constant before publishing.",);});++ it('describes and validates an ambient-only grid without inventing walk frames', () => {+ const geometry = {+ columns: ['idle', 'ambient-00', 'ambient-01', 'ambient-02'],+ tracks: { idle: span(0, 1, 1), ambient: span(1, 3, 1) },+ directionOrder: DIRECTIONS,+ rows: DIRECTIONS.length,+ cellSize: 96,+ walkFrameCount: null,+ ambientFrameCount: 3,+ };+ const layout = buildAtlasLayout({+ characterId: 'example-place', geometry, atlasSha256: 'abc123', atlasDestPath: 'assets/tree.png',+ });+ expect(layout.walkFrameCount).toBeNull();+ expect(layout.ambientFrameCount).toBe(3);+ expect(layout.tracks.ambient).toEqual(span(1, 3, 1));+ expect(runtimeContractMismatch(geometry, { ambientFrameCount: 3 })).toBeNull();+ expect(runtimeContractMismatch(geometry, { ambientFrameCount: 4 })).toMatch(/3 ambient frames.*expects 4/);+ });});diff --git a/server/services/sprites/prompts.js b/server/services/sprites/prompts.jsindex 2e34ae5f2c..8091ca951d 100644--- a/server/services/sprites/prompts.js+++ b/server/services/sprites/prompts.js@@ -256,6 +256,34 @@ export function buildMainReferencePrompt({ name, designPrompt, chromaKey, fromTu);}+/**+ * The identity root for a place/object ambient loop. Unlike a character it has+ * no facing or turnaround: this one locked still is both the idle cell and the+ * image-to-video source, so it must be legible on its own.+ */+export function buildAmbientReferencePrompt({ name, kind, designPrompt, chromaKey }) {+ const description = (typeof designPrompt === 'string' && designPrompt.trim())+ ? designPrompt.trim()+ : 'Use the attached visual reference as the design.';+ return (+ `Create one centered game-sprite ${kind} named ${name}. Design: ${description} `+ + 'Show its at-rest state with a clear readable silhouette. Match the attached visual reference when provided. '+ + `Use a plain exact ${keyColorPhrase(chromaKey)} background. No people, scenery, text, labels, grid, `+ + 'camera angle, shadows, wireframe, or extra objects. Return exactly one PNG.'+ );+}++/** Ambient image-to-video instruction: preserve the still while moving only its natural loop detail. */+export function buildAmbientVideoPrompt({ name, kind, chromaKey }) {+ return (+ `The source image is the locked at-rest ${kind} sprite ${name}. Animate one subtle seamless ambient loop `+ + '(for example wind, water, flame, or a gentle flicker appropriate to the source), then return to the exact starting pose. '+ + 'Preserve its identity, silhouette, palette, scale, and centered ground position. Use a locked camera and an exactly '+ + `uniform non-emissive ${keyColorPhrase(chromaKey)} background only as a compositing matte: no scenery, text, labels, `+ + 'camera movement, cuts, added objects, or people.'+ );+}+/*** Stage-3 motion prompt (issue #2897): the walk-video instruction handed to* the grok i2v lane along with the prepared transparent anchor. PortOS'sdiff --git a/server/services/sprites/publish.js b/server/services/sprites/publish.jsindex 4181f29b7d..515e9bf1cd 100644--- a/server/services/sprites/publish.js+++ b/server/services/sprites/publish.js@@ -19,8 +19,8 @@* concern and are never touched.** The optional runtimeContract (#2982) is the reverse direction: the app- * declares the grid it was built against ({ walkFrameCount, cellSize,- * columnCount }) and a publish whose compiled geometry disagrees is refused+ * declares the grid it was built against ({ walkFrameCount?, ambientFrameCount?,+ * cellSize, columnCount }) and a publish whose compiled geometry disagrees is refused* instead of silently shifting every column the game reads. Alongside the PNG,* publish writes a `<atlas-stem>.layout.json` sidecar describing the grid* PortOS actually produced, so the app can resolve columns by name rather than@@ -94,8 +94,8 @@ async function requireAppRepo(appId, status) {* parses, so a non-route caller (importer, peer sync, a test) can't persist a* contract the route would have rejected.*- * `walkFrameCount` is required once a contract is present (it is the whole- * point of declaring one); `cellSize` and `columnCount` are optional extra+ * A walk or ambient frame count is required once a contract is present;+ * `cellSize` and `columnCount` are optional extra* assertions. The fields are NOT cross-checked against each other: what counts* as a consistent column layout is the compiler's business and changes with the* grid (#2986 drops the scanner column), so a stale count surfaces at publish@@ -109,10 +109,13 @@ function validateRuntimeContract(runtimeContract) {const field = issue?.path?.length ? `runtimeContract.${issue.path.join('.')}` : 'runtimeContract';throw bindingError(`${field}: ${issue?.message || 'invalid'}`, 'INVALID_RUNTIME_CONTRACT');}- const { walkFrameCount, scannerFrameCount, cellSize, columnCount } = parsed.data;+ const {+ walkFrameCount, scannerFrameCount, ambientFrameCount, cellSize, columnCount,+ } = parsed.data;return {- walkFrameCount,+ ...(walkFrameCount === undefined ? {} : { walkFrameCount }),...(scannerFrameCount === undefined ? {} : { scannerFrameCount }),+ ...(ambientFrameCount === undefined ? {} : { ambientFrameCount }),cellSize: cellSize ?? null,columnCount: columnCount ?? null,};diff --git a/server/services/sprites/publish.test.js b/server/services/sprites/publish.test.jsindex a9de9e11e1..c2117177f2 100644--- a/server/services/sprites/publish.test.js+++ b/server/services/sprites/publish.test.js@@ -157,6 +157,14 @@ describe('validatePublishBinding / setPublishBinding', () => {walkFrameCount: 8, cellSize: 96, columnCount: 9,});+ const ambient = await setPublishBinding(id, {+ ...BINDING,+ runtimeContract: { ambientFrameCount: 3, cellSize: 96, columnCount: 4 },+ });+ expect(ambient.publishBinding.runtimeContract).toEqual({+ ambientFrameCount: 3, cellSize: 96, columnCount: 4,+ });+for (const bad of [{ walkFrameCount: 0 },{ walkFrameCount: 99 },diff --git a/server/services/sprites/reference.js b/server/services/sprites/reference.jsindex 47f937075a..bdb487a560 100644--- a/server/services/sprites/reference.js+++ b/server/services/sprites/reference.js@@ -40,7 +40,7 @@ import { getRecord, updateRecord, listRecords, createCharacter } from './recordsimport { spriteDir, resolveSpriteAssetPath, listSpriteAssets } from './paths.js';import {SPRITE_DIRECTIONS, ANCHOR_DIRECTIONS, anchorIdForDirection, TURNAROUND_VIEWS, TURNAROUND_ID,- buildMainReferencePrompt, buildAnchorPrompt, buildTurnaroundPrompt,+ buildMainReferencePrompt, buildAmbientReferencePrompt, buildAnchorPrompt, buildTurnaroundPrompt,} from './prompts.js';import { pickChromaKey, keyProximityWarning, CHROMA_KEY_HEXES, DEFAULT_CHROMA_KEY } from './chromaKey.js';import {@@ -138,7 +138,7 @@ async function saveManifest(recordId, manifest) {await atomicWrite(abs, manifest);}-function seedManifest(recordId) {+function seedManifest(recordId, { directional = true } = {}) {return {schemaVersion: TURNAROUND_FIRST_SCHEMA,manifestId: `${recordId}-reference-set-v1`,@@ -151,14 +151,16 @@ function seedManifest(recordId) {path: null, role: 'identity-root', background: 'chroma-key', locked: false, views: TURNAROUND_VIEWS,},mainReference: { path: null, role: 'immutable-root', background: 'chroma-key', locked: false },- anchors: SPRITE_DIRECTIONS.map((direction) => ({+ anchors: (directional ? SPRITE_DIRECTIONS : []).map((direction) => ({id: anchorIdForDirection(direction),kind: 'walk-anchor',direction,status: 'pending',source: direction === 'south' ? 'main-reference' : 'derive-from-turnaround',})),- note: 'walk-south and walk-north double as the front/back idle stills, so no separate idle anchors are kept.',+ note: directional+ ? 'walk-south and walk-north double as the front/back idle stills, so no separate idle anchors are kept.'+ : 'The locked main reference is the at-rest idle cell and the sole ambient-loop identity root.',};}@@ -361,9 +363,13 @@ export function startReferenceGeneration(recordId, body, upload = null) {}async function startReferenceGenerationImpl(recordId, body, upload = null) {- const record = await requireCharacter(recordId);- const manifest = (await loadManifest(recordId)) || seedManifest(recordId);+ const record = await requireTrack(recordId);+ const directional = kindSupportsTrack(record.kind, WALK_TRACK);+ const manifest = (await loadManifest(recordId)) || seedManifest(recordId, { directional });const target = body.target;+ if (!directional && target !== 'main') {+ throw new ServerError('Ambient references use one main identity root; they have no turnaround or directional anchors', { status: 400, code: 'INVALID_TARGET' });+ }// Once either identity artifact is locked — the sheet on a turnaround-first// record, the main on a legacy one — the manifest's key is canonical (set at// that lock, possibly auto-selected); a later record-level repin must not@@ -429,33 +435,49 @@ async function startReferenceGenerationImpl(recordId, body, upload = null) {if (manifest.mainReference.locked) {throw new ServerError('Main reference is locked — unlock the turnaround to rebuild its dependent reference chain', { status: 409, code: 'REFERENCE_LOCKED' });}- // The main is always the sheet's front view: a manifest that reaches here- // with no locked sheet was either seeded turnaround-first or upgraded to it- // on read (upgradeManifestShape), and the only manifests that skip that- // upgrade have a locked main — which threw REFERENCE_LOCKED just above.- if (!turnaroundLocked) {- throw new ServerError('Lock the turnaround sheet before deriving the main reference', { status: 409, code: 'TURNAROUND_NOT_LOCKED' });- }- anchorId = anchorIdForDirection('south');- direction = 'south';- prompt = buildMainReferencePrompt({- name: record.name,- designPrompt: designPrompt || manifest.designPrompt,- chromaKey: genKey,- fromTurnaround: true,- });- // The sheet IS the seed here, so a caller-supplied one has nowhere to go.- // Reject rather than silently dropping it.- if (upload || body.initImageGalleryFile || body.initImageSpriteId) {- throw new ServerError('The main reference derives from the locked turnaround sheet — seed a new design through the sheet, not the main', { status: 400, code: 'SEED_NOT_APPLICABLE' });- }- initImagePath = await requireLockedTurnaroundPath(recordId, manifest);- initImageStrength ??= ANCHOR_DEFAULT_STRENGTH;- // Nothing else in this branch mutates the manifest, so skip the write —- // and its per-record serialization — on the common no-prompt re-roll.- if (designPrompt) {- manifest.designPrompt = designPrompt;+ // A place/object ambient loop has one identity root, not a turnaround or+ // directional anchors. Its main is generated directly and later becomes+ // both its idle cell and image-to-video source.+ if (!directional) {+ if (!designPrompt && !upload && !body.initImageGalleryFile && !body.initImageSpriteId) {+ throw new ServerError('Provide a design prompt and/or a reference image', { status: 400, code: 'DESIGN_INPUT_REQUIRED' });+ }+ anchorId = 'main';+ direction = 'south';+ prompt = buildAmbientReferencePrompt({ name: record.name, kind: record.kind, designPrompt, chromaKey: genKey });+ ({ initImagePath, designReferencePath } = await resolveSeedSource(recordId, body, upload));+ if (initImagePath) initImageStrength ??= UPLOAD_DEFAULT_STRENGTH;+ if (designPrompt) manifest.designPrompt = designPrompt;await saveManifest(recordId, manifest);+ } else {+ // The main is always the sheet's front view: a manifest that reaches here+ // with no locked sheet was either seeded turnaround-first or upgraded to it+ // on read (upgradeManifestShape), and the only manifests that skip that+ // upgrade have a locked main — which threw REFERENCE_LOCKED just above.+ if (!turnaroundLocked) {+ throw new ServerError('Lock the turnaround sheet before deriving the main reference', { status: 409, code: 'TURNAROUND_NOT_LOCKED' });+ }+ anchorId = anchorIdForDirection('south');+ direction = 'south';+ prompt = buildMainReferencePrompt({+ name: record.name,+ designPrompt: designPrompt || manifest.designPrompt,+ chromaKey: genKey,+ fromTurnaround: true,+ });+ // The sheet IS the seed here, so a caller-supplied one has nowhere to go.+ // Reject rather than silently dropping it.+ if (upload || body.initImageGalleryFile || body.initImageSpriteId) {+ throw new ServerError('The main reference derives from the locked turnaround sheet — seed a new design through the sheet, not the main', { status: 400, code: 'SEED_NOT_APPLICABLE' });+ }+ initImagePath = await requireLockedTurnaroundPath(recordId, manifest);+ initImageStrength ??= ANCHOR_DEFAULT_STRENGTH;+ // Nothing else in this branch mutates the manifest, so skip the write —+ // and its per-record serialization — on the common no-prompt re-roll.+ if (designPrompt) {+ manifest.designPrompt = designPrompt;+ await saveManifest(recordId, manifest);+ }}} else {if (!ANCHOR_DIRECTIONS.includes(target)) {@@ -661,7 +683,7 @@ export async function listSpriteThumbnails() {// Registry-driven for the same reason as listReferenceSources: a locked// main reference is a property of carrying the walk track, not of the// literal kind name.- if (kindSupportsTrack(r.kind, WALK_TRACK)) {+ if (tracksForKind(r.kind).length) {const manifest = await loadManifest(r.id);const main = manifest?.mainReference;if (main?.locked && main.path) return { id: r.id, path: main.path };@@ -885,10 +907,14 @@ async function unlockReferenceTurnaroundImpl(recordId) {}async function lockReferenceImpl(recordId, { target, candidate, acceptClipRisk = false }) {- const record = await requireCharacter(recordId);+ const record = await requireTrack(recordId);+ const directional = kindSupportsTrack(record.kind, WALK_TRACK);// Seed on demand — a candidate may predate the manifest (e.g. files placed// by an import or a crash-recovered tree); the lock is what makes it real.- const manifest = (await loadManifest(recordId)) || seedManifest(recordId);+ const manifest = (await loadManifest(recordId)) || seedManifest(recordId, { directional });+ if (!directional && target !== 'main') {+ throw new ServerError('Ambient references use one main identity root; they have no turnaround or directional anchors', { status: 400, code: 'INVALID_TARGET' });+ }if (typeof candidate !== 'string' || !candidate.startsWith('reference/candidates/')) {throw new ServerError('Candidate must be a reference/candidates/ path', { status: 400, code: 'INVALID_CANDIDATE' });}@@ -908,7 +934,9 @@ async function lockReferenceImpl(recordId, { target, candidate, acceptClipRisk =}const expectedPrefix = target === TURNAROUND_ID? `${TURNAROUND_ID}-candidate-`- : `${anchorIdForDirection(target === 'main' ? 'south' : target)}-candidate-`;+ : target === 'main' && !directional+ ? 'main-candidate-'+ : `${anchorIdForDirection(target === 'main' ? 'south' : target)}-candidate-`;if (!candidate.slice('reference/candidates/'.length).startsWith(expectedPrefix)) {throw new ServerError(`Candidate filename does not match target "${target}" (expected ${expectedPrefix}*)`, { status: 400, code: 'CANDIDATE_TARGET_MISMATCH' });}@@ -987,7 +1015,8 @@ async function lockReferenceImpl(recordId, { target, candidate, acceptClipRisk =if (clipWarning && !acceptClipRisk) {throw new ServerError(`${clipWarning}. Re-send with acceptClipRisk to lock anyway.`, { status: 409, code: 'CHROMA_CLIP_RISK' });}- const rel = `reference/${await nextVersionPath(refDir, `${recordId}-walk-south`)}`;+ const stem = `${recordId}-${directional ? 'walk-south' : 'ambient-main'}`;+ const rel = `reference/${await nextVersionPath(refDir, stem)}`;const destAbs = join(spriteDir(recordId), rel);await normalizeFromAnalysis(analysis, candAbs, destAbs, selectedKey);const sha256 = await sha256File(destAbs);@@ -1008,13 +1037,16 @@ async function lockReferenceImpl(recordId, { target, candidate, acceptClipRisk =};const south = findAnchor(manifest, anchorIdForDirection('south'));if (south) Object.assign(south, { status: 'locked', path: rel, lockedFrom: candidate, sha256 });- manifest.status = 'in-progress';+ manifest.status = directional ? 'in-progress' : 'complete';// Record BEFORE manifest: a crash between the two leaves the record// updated but the manifest unlocked — recoverable by re-locking. The// reverse order would wedge (locked manifest + stale record, with both// relock and key PATCH returning 409 forever). Skipped entirely when the// turnaround lock already froze the key and set the status.- if (!frozenKey) await updateRecord(recordId, { chromaKey: selectedKey, status: 'reference' });+ if (!frozenKey) await updateRecord(recordId, {+ chromaKey: selectedKey, status: directional ? 'reference' : 'reference-complete',+ });+ else if (!directional) await updateRecord(recordId, { status: 'reference-complete' });await saveManifest(recordId, manifest);} else {if (!ANCHOR_DIRECTIONS.includes(target)) {diff --git a/server/services/sprites/reference.test.js b/server/services/sprites/reference.test.jsindex b5213a0b51..f1ee836558 100644--- a/server/services/sprites/reference.test.js+++ b/server/services/sprites/reference.test.js@@ -148,27 +148,23 @@ describe('the animation gates (#3017)', () => {await expect(requireAnimatable(id)).resolves.toMatchObject({ id, kind: 'character' });});- it('refuses a place/object record, naming the tracks that DO exist', async () => {+ it('admits a place record for ambient work while retaining the character-only walk gate', async () => {await records.createRecord({ kind: 'place', name: 'Grove' }, 'grove');// The walk gate keeps its historical code, so existing callers matching on// NOT_A_CHARACTER are unaffected.await expect(requireCharacter('grove')).rejects.toMatchObject({ code: 'NOT_A_CHARACTER' });- // The track-presence gate explains itself in terms of the registry, which- // is the thing a user (or a future track) can actually change.- await expect(requireAnimatable('grove')).rejects.toMatchObject({- code: 'NOT_ANIMATABLE',- message: /No animation track applies to place records.*walk/,- });+ await expect(requireAnimatable('grove')).resolves.toMatchObject({ id: 'grove', kind: 'place' });});});describe('startReferenceGeneration', () => {- it('404s an unknown record and 400s a props record', async () => {+ it('404s an unknown record and queues a props main reference for the ambient workflow', async () => {await expect(startReferenceGeneration('nope', { target: 'main', designPrompt: 'x' })).rejects.toMatchObject({ code: 'NOT_FOUND' });await records.createRecord({ kind: 'props', name: 'Crates' }, 'crates');await expect(startReferenceGeneration('crates', { target: 'main', designPrompt: 'x' }))- .rejects.toMatchObject({ code: 'NOT_A_CHARACTER' });+ .resolves.toMatchObject({ jobId: 'job-1234567890', target: 'main', anchorId: 'main' });+ expect(enqueueJob.mock.calls[0][0].params.prompt).toContain('at-rest state');});it('requires a design prompt or upload for the turnaround target', async () => {diff --git a/server/services/sprites/walkPostprocess.js b/server/services/sprites/walkPostprocess.jsindex acfa4d779f..55932c147c 100644--- a/server/services/sprites/walkPostprocess.js+++ b/server/services/sprites/walkPostprocess.js@@ -458,6 +458,48 @@ export function selectCycleIndices(signatures, frameCount = WALK_FRAME_COUNT) {};}+/**+ * Pick a non-directional ambient-loop window and resample it evenly.+ *+ * A walk needs gait-period detection because a half stride is not a loop. An+ * ambient clip has no gait phases; it needs the two ends to look alike. Search+ * every usable window that can supply the requested frames, rank it first by+ * first/last-frame similarity, then prefer the longer candidate (more temporal+ * coverage), and sample the selected window at even intervals. This preserves+ * image-to-video temporal coherence without pretending wind or water has a+ * two-beat walk cycle.+ */+export function selectAmbientLoopIndices(signatures, frameCount) {+ const n = signatures.length;+ if (n < frameCount + 1) {+ throw new Error(`Need at least ${frameCount + 1} extracted frames, got ${n}`);+ }+ let best = null;+ for (let start = 0; start <= n - frameCount - 1; start++) {+ for (let end = start + frameCount; end < n; end++) {+ const seam = imageDistance(signatures[start], signatures[end]);+ const candidate = [seam, -(end - start), start, end];+ if (!best || candLess(candidate, best)) best = candidate;+ }+ }+ const [seam, , start, end] = best;+ const windowLength = end - start;+ const indices = Array.from(+ { length: frameCount },+ (_, index) => start + Math.floor((index * windowLength + Math.floor(frameCount / 2)) / frameCount),+ );+ return {+ indices,+ cycle: {+ selection: 'ambient-even-resample',+ windowStart: start,+ windowLength,+ endpointSeamScore: pyRoundTo(seam, 4),+ heldFrames: 0,+ },+ };+}+/*** The frame's baseline: the lowest row carrying at least `minRun` opaque pixels,* returned as a height (exclusive bottom) so it drops into the same arithmetic@@ -879,7 +921,9 @@ export async function runWalkPostprocess({const recovered = usable.map((d) => recoverAlphaFrame(d.frame, d.measured, split));const signatures = await Promise.all(recovered.map(signatureOf));- const { indices, cycle } = selectCycleIndices(signatures, targetFrames);+ const { indices, cycle } = trackRow.directional+ ? selectCycleIndices(signatures, targetFrames)+ : selectAmbientLoopIndices(signatures, targetFrames);const selected = indices.map((i) => recovered[i]);const { frames: aligned, alignment } = await alignFrames(selected);diff --git a/server/services/sprites/walkPostprocess.test.js b/server/services/sprites/walkPostprocess.test.jsindex ace63ec002..8dc6921d22 100644--- a/server/services/sprites/walkPostprocess.test.js+++ b/server/services/sprites/walkPostprocess.test.js@@ -13,7 +13,7 @@ import sharp from 'sharp';import {pyRound, pyRoundTo, median, sampleBorderKey, validateMeasuredKey,isUsableMeasuredKey, longestUsableSpan,- recoverAlphaFrame, despillKeyFrame, imageDistance, selectCycleIndices,+ recoverAlphaFrame, despillKeyFrame, imageDistance, selectCycleIndices, selectAmbientLoopIndices,alphaBbox, rootX, robustBottomRow, alignFrames, packStrip, validateFrames, buildContrastSheet,rootBandForManifest, ROOT_BAND_TORSO, ROOT_BAND_HIP, ALIGN_OP_TORSO_X,prepareWalkAnchorChromaInput, WALK_PHASES, WALK_CELL_SIZE, WALK_FRAME_COUNT,@@ -259,6 +259,26 @@ describe('selectCycleIndices', () => {});});+describe('selectAmbientLoopIndices', () => {+ const SIG_LEN = 48 * 48 * 3;+ const constSig = (v) => Buffer.alloc(SIG_LEN, v);++ it('chooses the cleanest endpoint seam and resamples that window evenly', () => {+ // The loop closes only from source frame 2 back to source frame 6. This is+ // deliberately not gait-shaped: ambient uses endpoint similarity rather+ // than walk-period/motion detection.+ const signatures = [50, 40, 0, 10, 20, 10, 0, 80, 90].map(constSig);+ const { indices, cycle } = selectAmbientLoopIndices(signatures, 3);+ expect(cycle).toMatchObject({ selection: 'ambient-even-resample', windowStart: 2, windowLength: 4, endpointSeamScore: 0 });+ expect(indices).toEqual([2, 3, 5]);+ });++ it('needs a closing frame in addition to every authored frame', () => {+ expect(() => selectAmbientLoopIndices([constSig(0), constSig(1), constSig(2)], 3))+ .toThrow(/at least 4/);+ });+});+describe('alphaBbox / rootX', () => {it('finds the visible bbox (exclusive right/bottom) and the hip-band pivot', () => {const frame = makeFrame(40, 60);