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: ship scanner animation track (#3018)
[._.]/ Adam Eivy67cb177b87dc
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 0a8a45e9f4..e0b9faa552 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -51,6 +51,8 @@## Sprite Manager+- **[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.- **A locked turnaround can now be reopened and regenerated without losing its history** — if you spot a bad side or inconsistent detail after freezing a character’s turnaround, the Reference Set now offers **Unlock turnaround** behind a confirmation that names the full consequence: because the main reference, all 8 directional anchors, and their walks descend from that sheet, they reopen together. Any approved walks are invalidated before the reference pointers reset, so stale animation cannot survive the revision. The old turnaround, main, anchors, rendered clips, and runtime atlases remain as versioned history; replacements lock at the next `vN` filename. A chroma key PortOS auto-picked for the rejected sheet is chosen afresh, while a key you explicitly pinned stays pinned.- **[issue-3017] Sprite sheets can now describe an animation that has no facing — the groundwork for animating places and objects** — every animation in a sprite sheet was assumed to be a character walk: eight rows, one per direction. That is wrong for most of what would come next. A tree moving in the wind, water, a flickering lamp — none of them face anywhere, and a sheet that insisted on eight facings for them would be seven-eighths empty with no way to say so. An animation now states whether it is directional, and one with no facing occupies a single row that the published layout file marks as such (`"rows": 1`), so a game reads that one row no matter which way anything is pointing instead of sampling seven blank ones. Everything still ships as **one** sheet per record — a second image would double what a game has to load and bind, and the unused cells compress to almost nothing. The rule that all of a walk's directions must agree on frame count and speed now applies *within* each animation rather than across the whole sheet, so a three-frame ambient loop can sit beside a twelve-frame walk. The other half is the gate: animation was refused outright for anything that wasn't a character, which is why **Places** and **Objects** had no animation path at all — that check now asks which animations a record kind can actually carry, so admitting those kinds becomes a matter of adding the animation rather than unpicking the refusal. To be clear about what this does and doesn't do: it is the sheet-and-publishing groundwork, not a feature you can use yet. No animation that places or objects can carry exists so far, and rendering and approving one is still walk-shaped — that work is tracked separately. Nothing changes for an existing character: walks compile to byte-identical sheets, already-published sheets are untouched until you republish, and the layout file gains the new row field additively.diff --git a/client/src/components/sprites/PublishWorkflow.jsx b/client/src/components/sprites/PublishWorkflow.jsxindex 388fbf06cc..00e10f303c 100644--- a/client/src/components/sprites/PublishWorkflow.jsx+++ b/client/src/components/sprites/PublishWorkflow.jsx@@ -23,10 +23,12 @@ const fieldLabelClass = 'block text-xs text-gray-400 mb-1';// Mirrors of the server contract (server/services/sprites/walkBounds.js is the// single source of truth; kept as literals here rather than importing a server// module into the client bundle). WALK_MIN/MAX bound the walk-frame-count-// input; IDLE/SCANNER name the non-walk columns so the "Match current atlas"-// fallback can count walk columns the same way resolveWalkFrameCount does.+// input; IDLE/SCANNER name the legacy non-walk columns so the "Match current+// atlas" fallback can count walk columns the same way resolveWalkFrameCount does.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 ATLAS_IDLE_COLUMN = 'idle';const ATLAS_SCANNER_COLUMN = 'scanner';@@ -41,6 +43,11 @@ function walkFrameCountOf(geometry) {).length;}+function scannerFrameCountOf(geometry) {+ if (Number.isInteger(geometry?.scannerFrameCount)) return geometry.scannerFrameCount;+ 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);const current = atlas?.current || null;@@ -52,6 +59,7 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {// The stored contract seeds them; walkFrameCount is the anchor field (an// empty walk-frame-count means "no contract").const seedFrames = savedContract?.walkFrameCount != null ? String(savedContract.walkFrameCount) : '';+ const seedScanner = savedContract?.scannerFrameCount != null ? String(savedContract.scannerFrameCount) : '';const seedCell = savedContract?.cellSize != null ? String(savedContract.cellSize) : '';const seedCols = savedContract?.columnCount != null ? String(savedContract.columnCount) : '';@@ -61,6 +69,7 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {const [codePath, setCodePath] = useState(saved?.codeBinding?.path || '');const [resourcePath, setResourcePath] = useState(saved?.codeBinding?.resourcePath || '');const [contractFrames, setContractFrames] = useState(seedFrames);+ const [contractScanner, setContractScanner] = useState(seedScanner);const [contractCell, setContractCell] = useState(seedCell);const [contractCols, setContractCols] = useState(seedCols);// null → idle; 'publish' → normal confirm; 'overwrite' → the server@@ -79,19 +88,22 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {setCodePath(saved?.codeBinding?.path || '');setResourcePath(saved?.codeBinding?.resourcePath || '');setContractFrames(seedFrames);+ setContractScanner(seedScanner);setContractCell(seedCell);setContractCols(seedCols);setConfirmStage(null);}, [saved?.appId, saved?.atlasDestPath, saved?.codeBinding?.path, saved?.codeBinding?.resourcePath,- savedContract?.walkFrameCount, savedContract?.cellSize, savedContract?.columnCount,- seedFrames, seedCell, seedCols]);+ savedContract?.walkFrameCount, savedContract?.scannerFrameCount, savedContract?.cellSize, savedContract?.columnCount,+ seedFrames, seedScanner, seedCell, seedCols]);- // Parse the three contract inputs. walkFrameCount is the anchor: an empty+ // Parse the four contract inputs. walkFrameCount is the anchor: an empty// field means "no contract". cellSize/columnCount are optional (empty → null).const framesRaw = contractFrames.trim();+ const scannerRaw = contractScanner.trim();const cellRaw = contractCell.trim();const colsRaw = contractCols.trim();const framesNum = framesRaw === '' ? null : Number(framesRaw);+ const scannerNum = scannerRaw === '' ? null : Number(scannerRaw);const cellNum = cellRaw === '' ? null : Number(cellRaw);const colsNum = colsRaw === '' ? null : Number(colsRaw);const hasContract = framesNum !== null;@@ -100,7 +112,8 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {// 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 || seedCell !== cellRaw || seedCols !== colsRaw;+ const contractFieldsDirty = seedFrames !== framesRaw || seedScanner !== scannerRaw+ || 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@@ -108,10 +121,12 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {// typed contract is also 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 && (cellRaw !== '' || colsRaw !== '')) {+ 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 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 (cellNum !== null && !intInRange(cellNum, 16, 1024)) {contractError = 'Cell size must be a whole number 16–1024.';} else if (colsNum !== null && !intInRange(colsNum, 1, 256)) {@@ -130,13 +145,16 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {const geometry = current?.geometry;if (!geometry) return;const frames = walkFrameCountOf(geometry);+ const scannerFrames = scannerFrameCountOf(geometry);setContractFrames(frames != null ? String(frames) : '');+ setContractScanner(scannerFrames != null ? String(scannerFrames) : '');setContractCell(Number.isInteger(geometry.cellSize) ? String(geometry.cellSize) : '');setContractCols(Array.isArray(geometry.columns) ? String(geometry.columns.length) : '');};const clearContract = () => {setContractFrames('');+ setContractScanner('');setContractCell('');setContractCols('');};@@ -163,7 +181,12 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {// dirty, a populated walkFrameCount sets it, an emptied one clears it (null).if (binding && contractDirty) {binding.runtimeContract = hasContract- ? { walkFrameCount: framesNum, cellSize: cellNum, columnCount: colsNum }+ ? {+ walkFrameCount: framesNum,+ ...(scannerNum === null ? {} : { scannerFrameCount: scannerNum }),+ cellSize: cellNum,+ columnCount: colsNum,+ }: null;}const result = await setSpritePublishBinding(record.id, binding, { silent: true });@@ -246,16 +269,20 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {// fields runtimeContractMismatch compares server-side.const atlasGeom = current?.geometry || null;const atlasFrames = walkFrameCountOf(atlasGeom);+ const atlasScannerFrames = scannerFrameCountOf(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 · ${atlasCols ?? '?'} cols${atlasCell != null ? ` · ${atlasCell}px` : ''}`+ ? `${atlasFrames ?? '?'} walk frames${atlasScannerFrames != null ? ` · ${atlasScannerFrames} scanner frames` : ''} · ${atlasCols ?? '?'} cols${atlasCell != null ? ` · ${atlasCell}px` : ''}`: null;const savedContractMismatch = (() => {if (!savedContract || !atlasGeom) return null;if (Number.isInteger(savedContract.walkFrameCount) && savedContract.walkFrameCount !== atlasFrames) {return `contract expects ${savedContract.walkFrameCount} walk frames, atlas has ${atlasFrames ?? '?'}`;}+ if (Number.isInteger(savedContract.scannerFrameCount) && savedContract.scannerFrameCount !== atlasScannerFrames) {+ return `contract expects ${savedContract.scannerFrameCount} scanner frames, atlas has ${atlasScannerFrames ?? 'none'}`;+ }if (Number.isInteger(savedContract.columnCount) && savedContract.columnCount !== atlasCols) {return `contract expects ${savedContract.columnCount} cols, atlas has ${atlasCols ?? '?'}`;}@@ -335,7 +362,7 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {<buttontype="button"onClick={clearContract}- disabled={framesRaw === '' && cellRaw === '' && colsRaw === ''}+ disabled={framesRaw === '' && scannerRaw === '' && 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@@ -346,7 +373,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-3 gap-2">+ <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-2"><FormField label={`Walk frames (${WALK_MIN_FRAME_COUNT}–${WALK_MAX_FRAME_COUNT})`} labelClassName={fieldLabelClass}><inputtype="number"@@ -358,6 +385,17 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {className={inputClass}/></FormField>+ <FormField label={`Scanner frames (${SCANNER_MIN_FRAME_COUNT}–${SCANNER_MAX_FRAME_COUNT}, optional)`} labelClassName={fieldLabelClass}>+ <input+ type="number"+ min={SCANNER_MIN_FRAME_COUNT}+ max={SCANNER_MAX_FRAME_COUNT}+ value={contractScanner}+ onChange={(e) => setContractScanner(e.target.value)}+ placeholder="4"+ 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 6e00a53df4..38fdf516dc 100644--- a/client/src/components/sprites/PublishWorkflow.test.jsx+++ b/client/src/components/sprites/PublishWorkflow.test.jsx@@ -128,6 +128,15 @@ describe('PublishWorkflow runtime contract', () => {expect(screen.getByText('Save binding')).toBeDisabled();});+ it('requires walk frames 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('Save binding')).toBeDisabled();+ });+it('MATCHES the current atlas geometry into the fields', () => {renderWorkflow({ appId: 'app-1', atlasDestPath: 'assets/hero.png', codeBinding: null });@@ -138,6 +147,30 @@ describe('PublishWorkflow runtime contract', () => {expect(screen.getByLabelText(/Column count/).value).toBe('13');});+ it('carries the scanner span into a runtime contract when the atlas has one', async () => {+ const scannerAtlas = atlasWith({+ current: {+ version: 3,+ compiledAt: '2026-07-01T00:00:00.000Z',+ atlasPath: 'runtime/v3/a.png',+ geometry: {+ ...GEOMETRY,+ scannerFrameCount: 4,+ tracks: { scanner: { start: 13, count: 4, rows: 8 } },+ },+ },+ });+ renderWorkflow({ appId: 'app-1', atlasDestPath: 'assets/hero.png', codeBinding: null }, scannerAtlas);++ fireEvent.click(screen.getByText('Match current atlas'));+ expect(screen.getByLabelText(/Scanner frames/).value).toBe('4');+ await act(async () => { fireEvent.click(screen.getByText('Save binding')); });++ expect(lastBindingArg().runtimeContract).toEqual({+ walkFrameCount: 12, scannerFrameCount: 4, cellSize: 96, columnCount: 13,+ });+ });+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/components/sprites/ScannerWorkflow.jsx b/client/src/components/sprites/ScannerWorkflow.jsxnew file mode 100644index 0000000000..a883c3e056--- /dev/null+++ b/client/src/components/sprites/ScannerWorkflow.jsx@@ -0,0 +1,106 @@+import { useEffect, useMemo } from 'react';+import { Check, Film, Radio, RefreshCw } from 'lucide-react';+import toast from '../ui/Toast';+import { approveSpriteScanner } from '../../services/apiSprites.js';+import { useAsyncAction } from '../../hooks/useAsyncAction.js';+import { SPRITE_DIRECTIONS } from '../../lib/spriteFacets.js';+import { checkerboardStyle, spriteAssetUrl } from './spriteAssets.js';++// Scanner is intentionally compact: it is a named action track, not a second+// walk editor. The server owns the 4-frame / 6fps default and validates its+// track-specific range; this UI exposes the direct user action, candidate review+// strip, and per-direction approval that freezes its atlas input.+export default function ScannerWorkflow({ record, reference, scanner, onGenerate, onChanged }) {+ const runs = scanner?.runs || [];+ const selection = scanner?.selection || null;+ const finalized = Boolean(scanner?.scannerSet);+ const renderable = Boolean(reference?.manifest?.mainReference?.locked);+ const latestByDirection = useMemo(() => Object.fromEntries(SPRITE_DIRECTIONS.map((direction) => [+ direction,+ runs.find((run) => run.direction === direction),+ ])), [runs]);+ const working = runs.some((run) => ['rendering', 'postprocessing'].includes(run.status));++ useEffect(() => {+ if (!working) return undefined;+ const timer = setInterval(onChanged, 4000);+ return () => clearInterval(timer);+ }, [working, onChanged]);++ const [approve, approving] = useAsyncAction(async (direction, runId) => {+ await approveSpriteScanner(record.id, { direction, runId }, { silent: true });+ toast.success(`Scanner ${direction} approved`);+ onChanged();+ }, { errorMessage: 'Scanner approval failed' });++ if (!renderable) return null;+ const approvedCount = Object.values(selection?.directions || {})+ .filter((entry) => entry?.status === 'approved').length;++ 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">+ <Radio className="w-4 h-4" /> Scanner Action+ <span className="text-xs font-normal text-gray-500">{finalized ? 'finalized' : `${approvedCount}/8 approved`} · 4f @ 6fps</span>+ </h3>+ <span className="text-[11px] text-gray-500">directly requested Grok render; local deterministic packing</span>+ </div>+ <div className="grid gap-2 sm:grid-cols-2 xl:grid-cols-4">+ {SPRITE_DIRECTIONS.map((direction) => {+ const run = latestByDirection[direction];+ const approved = selection?.directions?.[direction]?.status === 'approved';+ const busy = ['rendering', 'postprocessing'].includes(run?.status);+ const candidate = run?.status === 'candidate';+ const preview = run?.stripPreview;+ return (+ <article key={direction} className="rounded border border-port-border bg-port-bg p-2 space-y-2">+ <div className="flex items-center justify-between gap-2">+ <span className="text-xs font-medium text-white">{direction}</span>+ <span className={`text-[10px] ${approved ? 'text-port-success' : busy ? 'text-port-accent' : 'text-gray-500'}`}>+ {approved ? 'approved' : busy ? run.status : candidate ? 'review' : 'not generated'}+ </span>+ </div>+ {preview?.stripPath ? (+ <img+ className="h-20 w-full rounded object-contain"+ style={checkerboardStyle(5)}+ src={spriteAssetUrl(record.id, preview.stripPath, preview.stripSha256)}+ alt={`${direction} scanner action preview`}+ />+ ) : (+ <div className="h-20 rounded text-xs text-gray-600 grid place-items-center" style={checkerboardStyle(5)}>+ <Film className="w-4 h-4" />+ </div>+ )}+ {!finalized && !approved && (+ <div className="flex gap-1.5">+ <button+ type="button"+ disabled={busy}+ onClick={() => onGenerate(direction)}+ className="flex-1 rounded border border-port-border px-2 py-1 text-xs text-gray-300 hover:border-port-accent disabled:opacity-50"+ >+ {busy ? <RefreshCw className="mx-auto w-3 h-3 animate-spin" /> : run?.status === 'error' ? 'Retry' : 'Generate'}+ </button>+ {candidate && (+ <button+ type="button"+ disabled={approving}+ aria-label={`Approve scanner ${direction}`}+ onClick={() => approve(direction, run.id)}+ 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>+ );+ })}+ </div>+ </section>+ );+}diff --git a/client/src/components/sprites/ScannerWorkflow.test.jsx b/client/src/components/sprites/ScannerWorkflow.test.jsxnew file mode 100644index 0000000000..cb27b2f0b0--- /dev/null+++ b/client/src/components/sprites/ScannerWorkflow.test.jsx@@ -0,0 +1,53 @@+import { describe, it, expect, vi } from 'vitest';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';++vi.mock('../../services/apiSprites.js', () => ({+ approveSpriteScanner: vi.fn(() => Promise.resolve({})),+}));++import ScannerWorkflow from './ScannerWorkflow.jsx';+import { approveSpriteScanner } from '../../services/apiSprites.js';++const record = { id: 'example-walker' };+const reference = { manifest: { mainReference: { locked: true } } };++describe('ScannerWorkflow', () => {+ it('exposes the user-triggered scanner generation path and reviews a candidate strip', () => {+ const onGenerate = vi.fn();+ render(+ <ScannerWorkflow+ record={record}+ reference={reference}+ scanner={{+ runs: [{+ id: 'scanner-east-12345678', direction: 'east', status: 'candidate',+ stripPreview: { stripPath: 'runs/scanner-east-12345678/generated/example-scanner-east-strip.png', stripSha256: 'abc' },+ }],+ selection: { directions: {} },+ }}+ onGenerate={onGenerate}+ onChanged={vi.fn()}+ />,+ );+ expect(screen.getByText(/Scanner Action/)).toBeInTheDocument();+ fireEvent.click(screen.getAllByRole('button', { name: 'Generate' })[0]);+ expect(onGenerate).toHaveBeenCalled();+ expect(screen.getByRole('img', { name: /east scanner action preview/i })).toBeInTheDocument();+ });++ it('approves the reviewed scanner candidate through the named endpoint', async () => {+ render(+ <ScannerWorkflow+ record={record}+ reference={reference}+ scanner={{ runs: [{ id: 'scanner-east-12345678', direction: 'east', status: 'candidate' }], selection: { directions: {} } }}+ onGenerate={vi.fn()}+ onChanged={vi.fn()}+ />,+ );+ fireEvent.click(screen.getByRole('button', { name: 'Approve scanner east' }));+ await waitFor(() => expect(approveSpriteScanner).toHaveBeenCalledWith(+ 'example-walker', { direction: 'east', runId: 'scanner-east-12345678' }, { silent: true },+ ));+ });+});diff --git a/client/src/pages/Sprites.jsx b/client/src/pages/Sprites.jsxindex 74a52d6147..af82454b9b 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, generateSpriteReference, listSpriteThumbnails,+ generateSpriteWalk, generateSpriteScanner, generateSpriteReference, listSpriteThumbnails,} from '../services/apiSprites.js';import { getApps } from '../services/apiApps.js';import { getSettings } from '../services/apiSystem.js';@@ -13,6 +13,7 @@ import { deriveAvailableBackends } from '../lib/imageGenBackends.js';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 { GROK_VIDEO_DEFAULT_DURATION } from '../lib/grokVideoClip.js';import LoopTrimmer from '../components/sprites/LoopTrimmer.jsx';import PublishWorkflow from '../components/sprites/PublishWorkflow.jsx';@@ -509,6 +510,8 @@ export default function Sprites() {};collect(detail?.walk?.selection?.directions);collect(detail?.walk?.walkSet?.directions);+ collect(detail?.scanner?.selection?.directions);+ collect(detail?.scanner?.scannerSet?.directions);return set;}, [detail]);@@ -553,6 +556,21 @@ export default function Sprites() {onWorkflowChanged,), [id, duration, walkBegin, walkResolve, walkCancel, submitRender, onWorkflowChanged]);+ // Scanner has its own server-side in-flight guard and independent named set;+ // keeping its submit path separate means a scanner render never occupies the+ // walk direction's optimistic reservation (both can legitimately be authored+ // at once). It also owns its short default source clip instead of inheriting+ // the walk duration picker. The immediate refetch persists the observable+ // TUI run for polling.+ const generateScanner = useCallback(async (direction) => {+ try {+ await generateSpriteScanner(id, { direction }, { silent: true });+ onWorkflowChanged();+ } catch (err) {+ toast.error(err?.message || `Failed to queue ${direction} scanner action`);+ }+ }, [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@@ -707,6 +725,13 @@ export default function Sprites() {onOpenTrimmer={openTrimmer}onChanged={onWorkflowChanged}/>+ <ScannerWorkflow+ record={detail.record}+ reference={detail.reference}+ scanner={detail.scanner}+ onGenerate={generateScanner}+ onChanged={onWorkflowChanged}+ />{/* Keyed by record so form state and an armed publish/overwriteconfirmation never survive switching characters. */}<PublishWorkflowdiff --git a/client/src/services/README.md b/client/src/services/README.mdindex 5fa75b95a5..ebf5738654 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -96,7 +96,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiCreativeDirector.js` | Creative Director (video production). || `apiCreativeCommission.js` | Creative Commissions (Autonomous Creation Engine — standing recurring briefs). || `apiMusicVideo.js` | Music Video projects + scene board + audio analysis. |-| `apiSprites.js` | Sprite Manager records, asset library, production-set import (#2895), reference workflow: create/generate/lock (#2896), walk workflow: generate/approve/trim/postprocess (#2897), per-run source-frame listing for the Loop Trimmer's re-derive (#2980). |+| `apiSprites.js` | Sprite Manager records, asset library, production-set import (#2895), reference workflow: create/generate/lock (#2896), directional walk and scanner-track generation/approval, trim/postprocess, and per-run source-frame listing for the Loop Trimmer's re-derive (#2980). || `apiThreejsModels.js` | Procedural Three.js model workspaces: gallery-image generation, refinement, source export, and deletion. || `apiImageTo3d.js` | Image-to-3D (`/media/3d`): selectable targets (TRELLIS.2) with host availability/install status, and per-image model records — create/list/get/generate/delete + GLB asset URL. || `apiPipeline.js` | Pipeline (issues + stages + canon). |diff --git a/client/src/services/apiSprites.js b/client/src/services/apiSprites.jsindex 2109bb9031..dc40b234ee 100644--- a/client/src/services/apiSprites.js+++ b/client/src/services/apiSprites.js@@ -113,12 +113,22 @@ export const generateSpriteWalk = (id, body, options = {}) => request(`/sprites/method: 'POST', body: JSON.stringify(body), ...options,});+// Queue one user-requested scanner action. Its 2–8 frame, 2–12fps contract is+// validated by the named scanner track on the server, independently of walk.+export const generateSpriteScanner = (id, body, options = {}) => request(`/sprites/${encodeURIComponent(id)}/scanner/generate`, {+ method: 'POST', body: JSON.stringify(body), ...options,+});+// Approve a packaged candidate run for its direction. Returns the updated// { runs, selection, walkSet } walk state.export const approveSpriteWalk = (id, body, options = {}) => request(`/sprites/${encodeURIComponent(id)}/walk/approve`, {method: 'POST', body: JSON.stringify(body), ...options,});+export const approveSpriteScanner = (id, body, options = {}) => request(`/sprites/${encodeURIComponent(id)}/scanner/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 5b64e379f9..25a4a17b25 100644--- a/docs/features/sprite-export-contract.md+++ b/docs/features/sprite-export-contract.md@@ -6,19 +6,19 @@ Publishing is the only sprite path that writes outside `data/`. Everything else## The atlas grid-The compiler (`server/services/sprites/atlas.js`) produces one PNG: a fixed-cell grid of `idle + N walk phases` columns × 8 direction rows.+The compiler (`server/services/sprites/atlas.js`) produces one PNG: a fixed-cell grid of `idle` plus one named span for every approved animation track, across 8 direction rows.| Property | Value ||---|---|| 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 animation track in registration order — the N walk phases from 1 |+| 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 || 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.**-Frame-count and fps uniformity is a **within-track** rule, never a between-track one: every facing of a given track shares a column span because the atlas is a rectangular grid, but two different tracks may legally differ in both length and speed (a four-frame action beside a twelve-frame walk). Each track's authoring range comes from its own row in `server/services/sprites/animationTracks.js`, and its column span is recorded in `geometry.tracks` and republished in the sidecar. Only `walk` is registered today.+Frame-count and fps uniformity is a **within-track** rule, never a between-track one: every facing of a given track shares a column span because the atlas is a rectangular grid, but two different tracks may legally differ in both length and speed. The shipped directional `scanner` action is four frames at 6fps by default beside the 6–16-frame walk; its source video is generated only by an explicit scanner action, then packed and approved through its own evidence chain. Each track's authoring range comes from its own row in `server/services/sprites/animationTracks.js`, and its column span is recorded in `geometry.tracks` and republished in the sidecar.**Not every track has eight rows.** A track is *directional* (one row per facing — a character walk) or *non-directional* (one row, period — a tree moving in the wind, water, a flickering lamp, which have no facing at all). A non-directional track occupies **row 0** across its whole column span and leaves the remaining rows transparent. Its span says so: `rows: 1`. There is still exactly **one atlas per record** — a second image would double the publish and binding surface for no gain, and the transparent cells cost only file size, which PNG compresses to near nothing.@@ -50,13 +50,15 @@ Nothing else crosses. The compile manifest, the run provenance, the trims, and t"cellSize": 96,"rows": 8,"rowOrder": ["south", "south-east", "east", "north-east", "north", "north-west", "west", "south-west"],- "columns": ["idle", "left-contact", "…", "right-up"],- "columnCount": 9,+ "columns": ["idle", "left-contact", "…", "right-up", "scanner-00", "…", "scanner-03"],+ "columnCount": 13,"tracks": {"idle": { "start": 0, "count": 1, "rows": 8 },- "walk": { "start": 1, "count": 8, "rows": 8 }+ "walk": { "start": 1, "count": 8, "rows": 8 },+ "scanner": { "start": 9, "count": 4, "rows": 8 }},"walkFrameCount": 8,+ "scannerFrameCount": 4,"previewFps": 12,"previewFpsNote": "Authoring metadata only — …"}@@ -85,7 +87,7 @@ Column layout is the one thing an app genuinely has to agree with PortOS about.Two mechanisms guard that:-- **`publishBinding.runtimeContract`** (optional): `{ walkFrameCount, 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 walk set). A binding with no contract publishes unchecked, exactly as before the field existed.+- **`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.- **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 7579b0511d..b23ce3226a 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, getAnimationTrack } from '../services/sprites/animationTracks.js';+import { WALK_TRACK, SCANNER_TRACK, getAnimationTrack } from '../services/sprites/animationTracks.js';import { QUEUEABLE_IMAGE_MODES } from '../services/imageGen/modes.js';import { GROK_VIDEO_DURATIONS } from './grokVideoClip.js';@@ -1037,6 +1037,9 @@ export const spriteRuntimeContractSchema = z.object({// `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),+ // 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(),cellSize: z.number().int().min(16).max(1024).nullable().optional(),columnCount: z.number().int().min(1).max(256).nullable().optional(),});@@ -1171,6 +1174,8 @@ const spriteResolvableRunIdSchema = z.string().min(1).max(1024)// animationTracks pulls in no deps at all, native or otherwise.const spriteWalkFrameCountSchema = spriteTrackFrameCountSchema(WALK_TRACK);const spriteWalkFpsSchema = spriteTrackFpsSchema(WALK_TRACK);+const spriteScannerFrameCountSchema = spriteTrackFrameCountSchema(SCANNER_TRACK);+const spriteScannerFpsSchema = spriteTrackFpsSchema(SCANNER_TRACK);export const spriteWalkGenerateSchema = z.object({direction: spriteWalkDirectionSchema,@@ -1187,6 +1192,21 @@ export const spriteWalkGenerateSchema = z.object({fps: spriteWalkFpsSchema.optional(),});+// The scanner is a separate, short directional action. It deliberately has its+// own bounds (2–8 frames, 2–12fps) rather than inheriting the walk cycle's+// 6–16 / 4–24 shape.+export const spriteScannerGenerateSchema = z.object({+ direction: spriteWalkDirectionSchema,+ duration: grokVideoDurationSchema.optional(),+ frameCount: spriteScannerFrameCountSchema.optional(),+ fps: spriteScannerFpsSchema.optional(),+});++export const spriteScannerApproveSchema = z.object({+ direction: spriteWalkDirectionSchema,+ 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 8e65c0365e..9daca6f7a9 100644--- a/server/lib/validation.test.js+++ b/server/lib/validation.test.js@@ -42,6 +42,7 @@ import {spriteTrackFpsSchema,spriteRuntimeContractSchema,spriteWalkGenerateSchema,+ spriteScannerGenerateSchema,} from './validation.js';import {telegramForwardTypesSchema,@@ -1453,14 +1454,18 @@ describe('ad-hoc route schemas (#2521)', () => {expect(spriteTrackFpsSchema().safeParse(24).success).toBe(true);});- it('throws at schema-construction time for an unrecognized track', () => {+ it('uses the shipped scanner row and throws for an actually unknown track', () => {// A wiring bug surfaces at boot rather than degrading to walk's range.- expect(() => spriteTrackFrameCountSchema('scanner')).toThrow(/Unknown animation track/);- expect(() => spriteTrackFpsSchema('scanner')).toThrow(/Unknown animation track/);+ expect(spriteTrackFrameCountSchema('scanner').safeParse(4).success).toBe(true);+ expect(spriteTrackFpsSchema('scanner').safeParse(6).success).toBe(true);+ expect(() => spriteTrackFrameCountSchema('unknown')).toThrow(/Unknown animation track/);+ expect(() => spriteTrackFpsSchema('unknown')).toThrow(/Unknown animation track/);});it('leaves the walk request/contract schemas behaving exactly as before', () => {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(spriteWalkGenerateSchema.safeParse({direction: 'south', frameCount: 12, fps: 10,@@ -1468,6 +1473,8 @@ describe('ad-hoc route schemas (#2521)', () => {expect(spriteWalkGenerateSchema.safeParse({direction: 'south', frameCount: 3,}).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);});});diff --git a/server/routes/sprites.js b/server/routes/sprites.jsindex cefec01c1b..945e4067a7 100644--- a/server/routes/sprites.js+++ b/server/routes/sprites.js@@ -22,6 +22,8 @@ import {spriteReferenceLockSchema,spriteReferenceUnlockSchema,spriteForkSchema,+ spriteScannerGenerateSchema,+ spriteScannerApproveSchema,spriteWalkGenerateSchema,spriteWalkApproveSchema,spriteWalkReopenSchema,@@ -46,12 +48,13 @@ import {listReferenceSources, listSpriteThumbnails, forkSprite,} from '../services/sprites/reference.js';import { resolveSpriteAssetPrompt } from '../services/sprites/assetPrompt.js';-import { WALK_TRACK, kindSupportsTrack, tracksForKind } from '../services/sprites/animationTracks.js';+import { WALK_TRACK, SCANNER_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 { saveLoopTrim } from '../services/sprites/walkTrims.js';import { compileAtlas, getAtlasState } from '../services/sprites/atlas.js';import { setPublishBinding, publishAtlas } from '../services/sprites/publish.js';@@ -113,12 +116,14 @@ router.get('/:id', asyncHandler(async (req, res) => {// records the registry had just admitted.const { kind } = detail.record;const runsWalk = kindSupportsTrack(kind, WALK_TRACK);- const [reference, walk, atlas] = await Promise.all([+ const runsScanner = kindSupportsTrack(kind, SCANNER_TRACK);+ const [reference, walk, scanner, atlas] = await Promise.all([runsWalk ? getReferenceSet(req.params.id) : null,runsWalk ? getWalkState(req.params.id) : null,+ runsScanner ? getScannerState(req.params.id) : null,tracksForKind(kind).length ? getAtlasState(req.params.id) : null,]);- res.json({ ...detail, reference, walk, atlas });+ res.json({ ...detail, reference, walk, scanner, atlas });}));// The generation prompt behind one on-disk asset (record-relative `path`) —@@ -190,6 +195,19 @@ router.post('/:id/walk/generate', asyncHandler(async (req, res) => {res.json(await startWalkGeneration(req.params.id, body));}));+// The scanner action is a distinct named track with its own short bounds and+// its own finalized set. This endpoint is the only path that starts its Grok+// render, preserving the no-cold-bootstrap provider contract.+router.post('/:id/scanner/generate', asyncHandler(async (req, res) => {+ const body = validateRequest(spriteScannerGenerateSchema, req.body);+ res.json(await startScannerGeneration(req.params.id, body));+}));++router.post('/:id/scanner/approve', asyncHandler(async (req, res) => {+ const body = validateRequest(spriteScannerApproveSchema, req.body);+ res.json(await approveScannerDirection(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/routes/sprites.test.js b/server/routes/sprites.test.jsindex 219e233fb6..0fb36c3dfd 100644--- a/server/routes/sprites.test.js+++ b/server/routes/sprites.test.js@@ -62,6 +62,12 @@ vi.mock('../services/sprites/walk.js', () => ({})),}));+vi.mock('../services/sprites/scanner.js', () => ({+ getScannerState: vi.fn(async () => ({ track: 'scanner', runs: [], selection: null, scannerSet: null })),+ startScannerGeneration: vi.fn(async () => ({ runId: 'scanner-east-0a1b2c3d', direction: 'east', duration: 6 })),+ approveScannerDirection: vi.fn(async () => ({ track: 'scanner', runs: [], selection: { status: 'in-progress' }, scannerSet: null })),+}));+vi.mock('../services/sprites/walkTrims.js', () => ({saveLoopTrim: vi.fn(async () => ({ strip: 'walk/trims/t-v001-strip.png', loop: 'walk/trims/t-v001.gif', manifest: 'walk/trims/t-v001.json', frameCount: 3, disabledFrameCount: 1 })),}));@@ -85,6 +91,7 @@ import * as importer from '../services/sprites/importer.js';import * as reference from '../services/sprites/reference.js';import * as assetPrompt from '../services/sprites/assetPrompt.js';import * as walk from '../services/sprites/walk.js';+import * as scanner from '../services/sprites/scanner.js';import * as walkTrims from '../services/sprites/walkTrims.js';import * as atlas from '../services/sprites/atlas.js';import * as publish from '../services/sprites/publish.js';@@ -420,19 +427,22 @@ describe('sprites routes', () => {expect(assets.deleteSpriteAsset).not.toHaveBeenCalled();});- it('GET /:id includes the walk state for characters only', async () => {+ it('GET /:id includes the walk and scanner states for characters only', async () => {records.getRecordWithAssets.mockResolvedValueOnce({record: { id: 'pioneer', kind: 'character' }, assets: [],});const r = await request(app).get('/api/sprites/pioneer');expect(r.body.walk).toEqual({ runs: [], selection: null, walkSet: null });+ expect(r.body.scanner).toEqual({ track: 'scanner', runs: [], selection: null, scannerSet: null });expect(walk.getWalkState).toHaveBeenCalledWith('pioneer');+ expect(scanner.getScannerState).toHaveBeenCalledWith('pioneer');records.getRecordWithAssets.mockResolvedValueOnce({record: { id: 'crates', kind: 'props' }, assets: [],});const props = await request(app).get('/api/sprites/crates');expect(props.body.walk).toBeNull();+ expect(props.body.scanner).toBeNull();});it('POST /:id/walk/generate validates direction and duration', async () => {@@ -463,6 +473,26 @@ describe('sprites routes', () => {.send({ direction: 'east', fps: 99 })).status).toBe(400);});+ it('POST /:id/scanner/generate validates scanner-specific short bounds', async () => {+ const r = await request(app).post('/api/sprites/pioneer/scanner/generate')+ .send({ direction: 'east', frameCount: 4, fps: 6 });+ expect(r.status).toBe(200);+ expect(scanner.startScannerGeneration).toHaveBeenCalledWith('pioneer', { direction: 'east', frameCount: 4, fps: 6 });+ expect((await request(app).post('/api/sprites/pioneer/scanner/generate')+ .send({ direction: 'east', frameCount: 9 })).status).toBe(400);+ expect((await request(app).post('/api/sprites/pioneer/scanner/generate')+ .send({ direction: 'east', fps: 13 })).status).toBe(400);+ });++ it('POST /:id/scanner/approve forwards a reviewed scanner candidate', async () => {+ const r = await request(app).post('/api/sprites/pioneer/scanner/approve')+ .send({ direction: 'east', runId: 'scanner-east-0a1b2c3d' });+ expect(r.status).toBe(200);+ expect(scanner.approveScannerDirection).toHaveBeenCalledWith('pioneer', {+ direction: 'east', runId: 'scanner-east-0a1b2c3d',+ });+ });+it('PUT /:id/walk/target pins the set-level cycle target and bounds it', async () => {const r = await request(app).put('/api/sprites/pioneer/walk/target').send({ frameCount: 14, fps: 8 });diff --git a/server/services/sprites/animationTargets.test.js b/server/services/sprites/animationTargets.test.jsindex 85a1ba5011..2e8dc7dccf 100644--- a/server/services/sprites/animationTargets.test.js+++ b/server/services/sprites/animationTargets.test.js@@ -9,7 +9,7 @@ import { describe, it, expect, vi } from 'vitest';import {WALK_TRACK, resolveAnimationTarget, withTrackTarget, targetDrift, describeTargetSource,} from './animationTargets.js';-import { getAnimationTrack } from './animationTracks.js';+import { getAnimationTrack, SCANNER_TRACK } from './animationTracks.js';describe('resolveAnimationTarget precedence', () => {it('falls back to the documented defaults when nothing is pinned or packaged', () => {@@ -121,11 +121,14 @@ describe('resolveAnimationTarget precedence', () => {vi.resetModules();});- it('rejects an unrecognized track instead of resolving it against walk\'s range', () => {+ it('resolves scanner against its own range and rejects unknown tracks', () => {// Sentinel discipline: absent ⇒ the default track; unrecognized ⇒ an error// naming the known tracks, never a silent fall-through to 6–16 / 4–24.- expect(() => resolveAnimationTarget({ track: 'scanner' }))- .toThrow(/Unknown animation track 'scanner'/);+ expect(resolveAnimationTarget({ track: SCANNER_TRACK })).toMatchObject({+ track: SCANNER_TRACK, frameCount: 4, fps: 6, source: 'default',+ });+ expect(() => resolveAnimationTarget({ track: 'unknown' }))+ .toThrow(/Unknown animation track 'unknown'/);expect(resolveAnimationTarget({ track: undefined }).track).toBe(WALK_TRACK);});});@@ -156,8 +159,10 @@ describe('withTrackTarget', () => {// Preserving a sibling key a newer peer wrote and minting a bogus one are// different things: the first is forward-compat, the second is a bug that// would persist a row nothing can range-check.- expect(() => withTrackTarget({}, 'scanner', { frameCount: 4, fps: 6, source: 'set' }))- .toThrow(/Unknown animation track 'scanner'/);+ expect(withTrackTarget({}, SCANNER_TRACK, { frameCount: 4, fps: 6, source: 'set' }))+ .toEqual({ scanner: { frameCount: 4, fps: 6, source: 'set' } });+ expect(() => withTrackTarget({}, 'unknown', { frameCount: 4, fps: 6, source: 'set' }))+ .toThrow(/Unknown animation track 'unknown'/);});});@@ -191,8 +196,9 @@ describe('targetDrift', () => {])).toEqual([{direction: 'east', frameCount: 8, fps: 10, frameCountDrifts: true, fpsDrifts: false,}]);- expect(() => targetDrift({ ...target, track: 'scanner' }, []))- .toThrow(/Unknown animation track 'scanner'/);+ expect(targetDrift({ ...target, track: SCANNER_TRACK }, [])).toEqual([]);+ expect(() => targetDrift({ ...target, track: 'unknown' }, []))+ .toThrow(/Unknown animation track 'unknown'/);});});diff --git a/server/services/sprites/animationTracks.js b/server/services/sprites/animationTracks.jsindex d4a714686c..7b270a9505 100644--- a/server/services/sprites/animationTracks.js+++ b/server/services/sprites/animationTracks.js@@ -5,8 +5,9 @@* 4–24 range applied to every animation, because the walk cycle was the only* animation that existed. #2985 made the persisted target *track-keyed** (`animationTargets.walk`), but nothing described what tracks exist or what- * each one's legal range is — so a 3-frame ambient loop (a tree in the wind) or- * a 4-frame scanner action was unrepresentable: both sit BELOW walk's floor.+ * each one's legal range is — so a 3-frame ambient loop (a tree in the wind)+ * was unrepresentable. The shipped 4-frame scanner action proves the registry+ * supports a real non-walk range below walk's floor.** This module is that description. One row per known track carries its own* bounds, defaults, directionality, and the `runtimeContract` field names it@@ -41,6 +42,8 @@/** The default track — the only one that exists today. */export const WALK_TRACK = 'walk';+/** The first short, directional character action (#3018). */+export const SCANNER_TRACK = 'scanner';/*** Every known animation track.@@ -85,6 +88,23 @@ export const ANIMATION_TRACKS = Object.freeze({// A second track copying this row should decide its own answer.contractFpsField: 'walkFps',}),+ [SCANNER_TRACK]: Object.freeze({+ id: SCANNER_TRACK,+ label: 'Scanner action',+ directional: true,+ // A scanner pose is still one per character facing, so it reuses the+ // locked directional anchors and fills all eight atlas rows.+ kinds: Object.freeze(['character']),+ minFrameCount: 2,+ maxFrameCount: 8,+ defaultFrameCount: 4,+ minFps: 2,+ maxFps: 12,+ defaultFps: 6,+ contractFrameCountField: 'scannerFrameCount',+ // The game owns action timing; PortOS carries fps as preview provenance.+ contractFpsField: null,+ }),});/** Known track ids, in registry order. */diff --git a/server/services/sprites/animationTracks.test.js b/server/services/sprites/animationTracks.test.jsindex ad5b1f5928..b2afe9adba 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, ANIMATION_TRACKS, ANIMATION_TRACK_IDS,+ WALK_TRACK, SCANNER_TRACK, ANIMATION_TRACKS, ANIMATION_TRACK_IDS,isAnimationTrack, getAnimationTrack, clampTrackFrameCount, clampTrackFps,assertAnimationTrackRows, trackRowCount, tracksForKind, kindSupportsTrack,} from './animationTracks.js';@@ -52,6 +52,22 @@ describe('the registry rows', () => {});});+ it('registers the short scanner action independently of walk', () => {+ expect(getAnimationTrack(SCANNER_TRACK)).toMatchObject({+ id: SCANNER_TRACK,+ directional: true,+ kinds: ['character'],+ minFrameCount: 2,+ maxFrameCount: 8,+ defaultFrameCount: 4,+ minFps: 2,+ maxFps: 12,+ defaultFps: 6,+ contractFrameCountField: 'scannerFrameCount',+ 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@@ -153,12 +169,12 @@ describe('getAnimationTrack — absent vs unrecognized', () => {expect(getAnimationTrack(null).id).toBe(WALK_TRACK);});- it('throws on an unrecognized id instead of falling back to walk\'s range', () => {+ it('keeps unknown ids distinct from the shipped scanner track', () => {// The sentinel rule: "not set" resolves to the default; "set to something// this build does not know" is an error. Silently handing back walk's 6–16// would reject a legitimate 4-frame action for reasons nothing explains.- expect(() => getAnimationTrack('scanner')).toThrow(/Unknown animation track 'scanner'/);- expect(() => getAnimationTrack('scanner')).toThrow(/known tracks: walk/);+ expect(getAnimationTrack(SCANNER_TRACK).id).toBe(SCANNER_TRACK);+ expect(() => getAnimationTrack('unknown')).toThrow(/Unknown animation track 'unknown'/);});it('treats an empty string as present-and-invalid, not absent', () => {@@ -221,8 +237,8 @@ describe('directionality and record-kind support (#3017)', () => {expect(kindSupportsTrack('character', 'nope', MIXED)).toBe(false);});- it('keeps the shipped registry character-only, so no gate loosened today', () => {- expect(tracksForKind('character').map((r) => r.id)).toEqual([WALK_TRACK]);+ it('keeps the shipped registry character-only while admitting walk and scanner', () => {+ 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([]);}@@ -263,9 +279,11 @@ describe('per-track clamps', () => {expect(clampTrackFps(99)).toBe(24);});- it('refuses to clamp against an unrecognized track', () => {- expect(() => clampTrackFrameCount(8, 'scanner')).toThrow(/Unknown animation track/);- expect(() => clampTrackFps(8, 'scanner')).toThrow(/Unknown animation track/);+ it('clamps scanner values against scanner bounds', () => {+ expect(clampTrackFrameCount(99, SCANNER_TRACK)).toBe(8);+ expect(clampTrackFrameCount(-1, SCANNER_TRACK)).toBe(2);+ expect(clampTrackFps(99, SCANNER_TRACK)).toBe(12);+ expect(clampTrackFps(-1, SCANNER_TRACK)).toBe(2);});});diff --git a/server/services/sprites/animationWorkflow.js b/server/services/sprites/animationWorkflow.jsnew file mode 100644index 0000000000..5bf54259e7--- /dev/null+++ b/server/services/sprites/animationWorkflow.js@@ -0,0 +1,15 @@+/** Shared per-record animation serialization and reference-key resolution. */++import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';++const animationWriteTail = createKeyCachedQueue();++// Walk and every named action mutate adjacent records under one sprite. Keep+// their write tail shared so a scanner approval cannot race a walk revision.+export const withAnimationWriteTail = (recordId, fn) => animationWriteTail(recordId, fn);++// manifest → record is the frozen chroma-key precedence for every animation+// track. A run's own key is the strongest provenance rung while packaging.+export const resolveChromaKey = ({ manifest, record, run } = {}) => (+ run?.chromaKey || manifest?.chromaKey || record?.chromaKey || null+);diff --git a/server/services/sprites/atlas.js b/server/services/sprites/atlas.jsindex dd59ed1139..d413f19016 100644--- a/server/services/sprites/atlas.js+++ b/server/services/sprites/atlas.js@@ -50,13 +50,14 @@ import {alphaBbox, robustBottomRow, rootX, rootBandForManifest, ROBUST_BASELINE_MIN_PIXELS, compositeOnto, sha256Buffer,} from './walkPostprocess.js';import { ATLAS_IDLE_COLUMN } from './walkBounds.js';-import { WALK_TRACK, ANIMATION_TRACK_IDS } from './animationTracks.js';+import { WALK_TRACK, SCANNER_TRACK, ANIMATION_TRACK_IDS } from './animationTracks.js';import {buildAtlasGrid, resolveTrackUniformity, compiledGridUpToDate, trackDirections,} from './atlasGrid.js';import {withWalkWriteTail, walkSetRelPath, importedWalkDirections, resolveChromaKey,} from './walk.js';+import { scannerSetRelPath } from './scanner.js';import { verifyPackagedFrames } from './walkFrames.js';import { getRecord } from './records.js';@@ -363,7 +364,27 @@ export async function validateForCompile(recordId) {// `trackDirections` is called ONCE per track and the result kept, so the// facings a track was collected against and the count it is later held to are// the same value rather than two derivations that could drift.- const trackDirs = { [WALK_TRACK]: trackDirections(WALK_TRACK, SPRITE_DIRECTIONS) };+ const scannerSetRel = scannerSetRelPath(recordId);+ const scannerSetBytes = await readFile(join(dir, scannerSetRel)).catch(() => null);+ let scannerSet = null;+ if (scannerSetBytes) {+ try {+ scannerSet = JSON.parse(scannerSetBytes);+ } catch {+ throw compileError('Scanner set manifest is unreadable');+ }+ if (scannerSet.kind !== 'finalized-eight-direction-scanner-set' || scannerSet.track !== SCANNER_TRACK+ || scannerSet.status !== 'final' || scannerSet.characterId !== recordId+ || JSON.stringify(scannerSet.directionOrder) !== JSON.stringify(SPRITE_DIRECTIONS)) {+ throw compileError('Scanner set manifest is not a finalized directional scanner set');+ }+ await readVerified(scannerSet.selectionPath, scannerSet.selectionSha256, 'Scanner selection file');+ }++ const trackDirs = {+ [WALK_TRACK]: trackDirections(WALK_TRACK, SPRITE_DIRECTIONS),+ ...(scannerSet ? { [SCANNER_TRACK]: trackDirections(SCANNER_TRACK, SPRITE_DIRECTIONS) } : {}),+ };const manifests = {};const trackRows = { [WALK_TRACK]: [] };for (const direction of trackDirs[WALK_TRACK]) {@@ -388,6 +409,32 @@ export async function validateForCompile(recordId) {});}+ if (scannerSet) {+ manifests[SCANNER_TRACK] = {};+ trackRows[SCANNER_TRACK] = [];+ for (const direction of trackDirs[SCANNER_TRACK]) {+ const entry = scannerSet.directions?.[direction];+ if (!entry || entry.status !== 'approved') throw compileError(`Scanner direction ${direction} is not approved`);+ const manifestBytes = await readVerified(entry.runManifest, entry.runManifestSha256, `Scanner run manifest for ${direction}`);+ let manifest;+ try {+ manifest = JSON.parse(manifestBytes);+ } catch {+ manifest = null;+ }+ if (!manifest || manifest.track !== SCANNER_TRACK || manifest.direction !== direction) {+ throw compileError(`Scanner run manifest for ${direction} is unreadable or mislabeled`);+ }+ manifests[SCANNER_TRACK][direction] = { entry, manifest };+ trackRows[SCANNER_TRACK].push({+ direction,+ frameCount: (manifest.frames || []).length,+ declaredFrameCount: manifest.frameCount,+ fps: manifest.frameRate,+ });+ }+ }+// Registration order, so the compiled grid's span order is stable regardless// of the order the rows happened to be collected in.const tracks = ANIMATION_TRACK_IDS@@ -400,6 +447,7 @@ export async function validateForCompile(recordId) {expectedRows: trackDirs[id].length,}));const walk = tracks.find((t) => t.id === WALK_TRACK);+ const scanner = tracks.find((t) => t.id === SCANNER_TRACK);const runs = {};for (const direction of trackDirs[WALK_TRACK]) {@@ -413,19 +461,33 @@ export async function validateForCompile(recordId) {runs[direction] = { runId: entry.runId, manifestPath: entry.runManifest, manifest, frameBytes };}+ const scannerRuns = {};+ if (scannerSet) {+ for (const direction of trackDirs[SCANNER_TRACK]) {+ const { entry, manifest } = manifests[SCANNER_TRACK][direction];+ const { frameBytes } = await verifyPackagedFrames(recordId, manifest, { bytes: true, track: SCANNER_TRACK });+ scannerRuns[direction] = { runId: entry.runId, manifestPath: entry.runManifest, manifest, frameBytes };+ }+ }+return {walkSet,walkSetPath: walkSetRel,walkSetSha256: sha256Buffer(walkSetBytes),+ scannerSet,+ scannerSetPath: scannerSet ? scannerSetRel : null,+ scannerSetSha256: scannerSetBytes ? sha256Buffer(scannerSetBytes) : null,referenceManifest,chromaKey,anchors,runs,+ scannerRuns,tracks,// The walk view of `tracks`, kept because the published geometry names these// exact fields in the runtime contract (walkFrameCount / walkFps).walkFrameCount: walk?.frameCount ?? null,walkFps: walk?.fps ?? null,+ scannerFrameCount: scanner?.frameCount ?? null,};}@@ -523,6 +585,53 @@ async function compileDirectionRow(recordId, direction, validated, geometry) {});}+ // Scanner is an independent short action: it gets its own named span and+ // scale, while still sharing the directional row and baseline contract that+ // keeps every animation grounded on the same atlas pivot.+ const scannerRun = validated.scannerRuns?.[direction];+ if (scannerRun) {+ const scannerSources = [];+ for (const bytes of scannerRun.frameBytes) {+ scannerSources.push(await transparentSource(bytes, split, validated.chromaKey));+ }+ const scannerDims = scannerSources.map((source, index) => occupiedDimensions(+ source, ALPHA_THRESHOLD, `${direction}-${scannerRun.manifest.frames[index].phase}`, true,+ ));+ const scannerScale = Math.min(+ geometry.targetMaxHeight / Math.max(...scannerDims.map((dim) => dim.height)),+ geometry.targetMaxWidth / Math.max(...scannerDims.map((dim) => dim.width)),+ );+ const scannerPivotX = Number(scannerRun.manifest.alignment?.targetPivot?.[0]);+ const scannerAnchorX = Number.isFinite(scannerPivotX)+ ? scannerPivotX+ : (Number(scannerRun.manifest.alignment?.cellSize) || scannerSources[0].width) / 2;+ const scannerScaled = [];+ for (let i = 0; i < scannerSources.length; i++) {+ scannerScaled.push(await scaleForCell(+ scannerSources[i], scannerScale, `${direction}-${scannerRun.manifest.frames[i].phase}`,+ ));+ }+ const scannerPasteX = sharedRowPasteX(+ pyRound(geometry.pivot[0] - scannerAnchorX * scannerScale),+ scannerScaled.map((item) => item.bounds), geometry,+ );+ for (let i = 0; i < scannerScaled.length; i++) {+ const frame = scannerRun.manifest.frames[i];+ const { scaled, bounds, baseline } = scannerScaled[i];+ const normalized = placeCell(+ scaled, bounds, baseline, scannerPasteX, `${direction}-${frame.phase}`, geometry, scannerScale,+ );+ cells.push({+ column: frame.phase,+ track: SCANNER_TRACK,+ frameIndex: i,+ ...normalized,+ sourcePath: frame.path,+ sourceSha256: frame.sha256,+ });+ }+ }+return {direction,runId,@@ -624,6 +733,7 @@ export async function compileAtlasInTail(recordId, { geometry: geometryOverridecurrent&& currentAtlasOnDisk&& current.walkSetSha256 === validated.walkSetSha256+ && (current.scannerSetSha256 ?? null) === validated.scannerSetSha256&& compiledGridUpToDate(current.geometry, { ...geometry, columns, tracks })) {return { ...current, created: false };@@ -683,7 +793,8 @@ export async function compileAtlasInTail(recordId, { geometry: geometryOverride.toBuffer();const atlasSha256 = sha256Buffer(atlasBuffer);- if (current && currentAtlasOnDisk && current.walkSetSha256 === validated.walkSetSha256 && current.atlasSha256 === atlasSha256) {+ if (current && currentAtlasOnDisk && current.walkSetSha256 === validated.walkSetSha256+ && (current.scannerSetSha256 ?? null) === validated.scannerSetSha256 && current.atlasSha256 === atlasSha256) {return { ...current, created: false };}@@ -724,6 +835,7 @@ export async function compileAtlasInTail(recordId, { geometry: geometryOverridemanifestPath: manifestRel,manifestSha256: sha256Buffer(survivingBuffer),walkSetSha256: validated.walkSetSha256,+ ...(survivingManifest.scannerSetSha256 ? { scannerSetSha256: survivingManifest.scannerSetSha256 } : {}),geometry: survivingManifest.geometry,compiledAt: survivingManifest.createdAt,};@@ -742,6 +854,10 @@ export async function compileAtlasInTail(recordId, { geometry: geometryOverridecompilerPath: 'server/services/sprites/atlas.js',walkSetPath: validated.walkSetPath,walkSetSha256: validated.walkSetSha256,+ ...(validated.scannerSet ? {+ scannerSetPath: validated.scannerSetPath,+ scannerSetSha256: validated.scannerSetSha256,+ } : {}),atlasPath: atlasRel,atlasSha256,geometry: {@@ -763,6 +879,7 @@ export async function compileAtlasInTail(recordId, { geometry: geometryOverride// walk row at the authored speed over the right number of columns.walkFrameCount: validated.walkFrameCount,walkFps: validated.walkFps,+ ...(validated.scannerSet ? { scannerFrameCount: validated.scannerFrameCount } : {}),},directions: rows.map((row) => ({direction: row.direction,@@ -798,6 +915,7 @@ export async function compileAtlasInTail(recordId, { geometry: geometryOverridemanifestPath: manifestRel,manifestSha256: sha256Buffer(manifestBuffer),walkSetSha256: validated.walkSetSha256,+ ...(validated.scannerSet ? { scannerSetSha256: validated.scannerSetSha256 } : {}),geometry: manifest.geometry,compiledAt: manifest.createdAt,};diff --git a/server/services/sprites/atlas.test.js b/server/services/sprites/atlas.test.jsindex b9de576111..9c6cea7217 100644--- a/server/services/sprites/atlas.test.js+++ b/server/services/sprites/atlas.test.js@@ -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 } = await import('./animationTracks.js');+const { getAnimationTrack, SCANNER_TRACK } = await import('./animationTracks.js');let seq = 0;const newId = () => `atlas-char-${++seq}`;@@ -155,6 +155,64 @@ async function buildFinalizedWalkSet(recordId, {return { walkSet, selection };}+async function buildFinalizedScannerSet(recordId, { frameCount = 4, fps = 6 } = {}) {+ const manifest = await loadManifest(recordId);+ const dir = join(TEST_ROOT, 'sprites', recordId);+ const labels = Array.from({ length: frameCount }, (_, i) => `${SCANNER_TRACK}-${String(i).padStart(2, '0')}`);+ const selection = {+ schemaVersion: 1,+ kind: 'reviewed-directional-scanner-selection',+ track: SCANNER_TRACK,+ characterId: recordId,+ status: 'complete',+ directions: {},+ };+ for (const direction of SPRITE_DIRECTIONS) {+ const runId = `${SCANNER_TRACK}-${direction}-${(seq++).toString(16).padStart(8, '0')}`;+ const generatedRel = `runs/${runId}/generated`;+ const frames = [];+ for (let i = 0; i < labels.length; i++) {+ const rel = `${generatedRel}/frames/${String(i).padStart(2, '0')}-${labels[i]}.png`;+ await walkFramePng(join(dir, rel), 36 + i * 12, 2 + i * 2);+ frames.push({ outputIndex: i, phase: labels[i], path: rel, sha256: sha256(await readFile(join(dir, rel))) });+ }+ const runManifest = {+ schemaVersion: 1,+ kind: 'deterministically-packaged-grok-scanner-video',+ track: SCANNER_TRACK,+ characterId: recordId,+ direction,+ chromaKey: manifest.chromaKey,+ frameCount,+ frameRate: fps,+ frames,+ };+ const manifestRel = `${generatedRel}/${recordId}-${SCANNER_TRACK}-${direction}-manifest.json`;+ const manifestBytes = JSON.stringify(runManifest);+ await writeFile(join(dir, manifestRel), manifestBytes);+ selection.directions[direction] = {+ status: 'approved', runId, runPath: `runs/${runId}`, runManifest: manifestRel,+ runManifestSha256: sha256(Buffer.from(manifestBytes)), approvedAt: new Date().toISOString(),+ };+ }+ await mkdir(join(dir, SCANNER_TRACK), { recursive: true });+ const selectionRel = `${SCANNER_TRACK}/${recordId}-${SCANNER_TRACK}-selection-v1.json`;+ const selectionBytes = JSON.stringify(selection);+ await writeFile(join(dir, selectionRel), selectionBytes);+ await writeFile(join(dir, `${SCANNER_TRACK}/${recordId}-${SCANNER_TRACK}-set-v1.json`), JSON.stringify({+ schemaVersion: 1,+ kind: 'finalized-eight-direction-scanner-set',+ track: SCANNER_TRACK,+ characterId: recordId,+ status: 'final',+ directionOrder: SPRITE_DIRECTIONS,+ selectionPath: selectionRel,+ selectionSha256: sha256(Buffer.from(selectionBytes)),+ directions: selection.directions,+ finalizedAt: new Date().toISOString(),+ }));+}+async function finalizedCharacter() {const id = newId();await lockAllAnchors(id);@@ -168,6 +226,24 @@ beforeEach(() => {afterAll(() => rmSync(TEST_ROOT, { recursive: true, force: true }));describe('compileAtlas', () => {+ it('compiles an approved four-frame scanner span beside the walk span', async () => {+ const id = newId();+ await lockAllAnchors(id);+ await buildFinalizedWalkSet(id, { frameCount: 12, fps: 10 });+ await buildFinalizedScannerSet(id);+ const result = await compileAtlas(id);+ const manifest = JSON.parse(await readFile(join(TEST_ROOT, 'sprites', id, result.manifestPath), 'utf8'));+ expect(manifest.geometry.columns).toEqual([+ 'idle', ...walkPhaseLabels(12), 'scanner-00', 'scanner-01', 'scanner-02', 'scanner-03',+ ]);+ expect(manifest.geometry.tracks.scanner).toMatchObject({ start: 13, count: 4, rows: 8 });+ expect(manifest.geometry.scannerFrameCount).toBe(4);+ expect(manifest.scannerSetSha256).toMatch(/^[0-9a-f]{64}$/);+ for (const row of manifest.directions) {+ expect(row.cells.filter((cell) => cell.column.startsWith('scanner-'))).toHaveLength(4);+ }+ });+it('compiles the 9×8 player atlas with full provenance and a current pointer', async () => {const id = await finalizedCharacter();const result = await compileAtlas(id);diff --git a/server/services/sprites/atlasGrid.test.js b/server/services/sprites/atlasGrid.test.jsindex f596ebc4cd..f19c520ce0 100644--- a/server/services/sprites/atlasGrid.test.js+++ b/server/services/sprites/atlasGrid.test.js@@ -174,10 +174,13 @@ describe('buildAtlasGrid', () => {// future registry tried to claim it.expect(() => buildAtlasGrid([{ id: 'idle', frameCount: 1 }], { idle: SCANNER_ROW })).toThrow(/the idle anchor owns that column/);- // Unknown ids are refused through the registry's OWN boundary, so the grid- // can't develop a second, more permissive idea of what a track is.- expect(() => buildAtlasGrid([{ id: 'scanner', frameCount: 4 }]))- .toThrow(/Unknown animation track 'scanner'/);+ // The first real non-walk track compiles through the shipped registry.+ expect(buildAtlasGrid([{ id: 'scanner', frameCount: 4 }]).tracks.scanner)+ .toEqual(span(1, 4));+ // Unknown ids are still refused through the registry's OWN boundary, so the+ // grid cannot develop a second, more permissive idea of what a track is.+ expect(() => buildAtlasGrid([{ id: 'unknown', frameCount: 4 }]))+ .toThrow(/Unknown animation track 'unknown'/);expect(() => buildAtlasGrid([{ id: 'walk', frameCount: 0 }])).toThrow(/positive integer frame count/);});diff --git a/server/services/sprites/atlasLayout.js b/server/services/sprites/atlasLayout.jsindex 7c70a2a495..58a6ad6044 100644--- a/server/services/sprites/atlasLayout.js+++ b/server/services/sprites/atlasLayout.js@@ -111,6 +111,7 @@ export function buildAtlasLayout({// through `undefined` to re-trigger a default.tracks: deriveTracks(columns, walkFrameCount, geometry.tracks ?? null, rows ?? ATLAS_DEFAULT_ROWS),walkFrameCount,+ ...(Number.isInteger(geometry.scannerFrameCount) ? { scannerFrameCount: geometry.scannerFrameCount } : {}),previewFps: Number.isFinite(geometry.walkFps) ? geometry.walkFps : null,previewFpsNote: PREVIEW_FPS_NOTE,};@@ -131,7 +132,10 @@ export function runtimeContractMismatch(geometry, contract, appLabel = 'the bounconst actualColumns = geometry.columns.length;const actualFrames = resolveWalkFrameCount(geometry);- const { walkFrameCount: expectedFrames, columnCount: expectedColumns, cellSize: expectedCellSize } = contract;+ const {+ walkFrameCount: expectedFrames, scannerFrameCount: expectedScannerFrames,+ columnCount: expectedColumns, cellSize: expectedCellSize,+ } = contract;const actualDesc = `Atlas has ${actualColumns} columns (${actualFrames} walk frames)`;const expectedDesc = Number.isInteger(expectedColumns)? `${expectedColumns} (${expectedFrames} walk frames)`@@ -148,6 +152,14 @@ export function runtimeContractMismatch(geometry, contract, appLabel = 'the boun`The grid shape changed — update the app's expected column layout, or re-bind its runtime contract to ${actualColumns} columns before publishing.`,);}+ const actualScannerFrames = Number.isInteger(geometry.scannerFrameCount)+ ? geometry.scannerFrameCount+ : geometry.tracks?.scanner?.count ?? null;+ if (Number.isInteger(expectedScannerFrames) && expectedScannerFrames !== actualScannerFrames) {+ const actual = Number.isInteger(actualScannerFrames) ? actualScannerFrames : 'no';+ return `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.';+ }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/publish.js b/server/services/sprites/publish.jsindex c8f8adee73..4181f29b7d 100644--- a/server/services/sprites/publish.js+++ b/server/services/sprites/publish.js@@ -109,8 +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, cellSize, columnCount } = parsed.data;- return { walkFrameCount, cellSize: cellSize ?? null, columnCount: columnCount ?? null };+ const { walkFrameCount, scannerFrameCount, cellSize, columnCount } = parsed.data;+ return {+ walkFrameCount,+ ...(scannerFrameCount === undefined ? {} : { scannerFrameCount }),+ cellSize: cellSize ?? null,+ columnCount: columnCount ?? null,+ };}/** Validate a publishBinding shape (null clears it). */diff --git a/server/services/sprites/scanner.js b/server/services/sprites/scanner.jsnew file mode 100644index 0000000000..5d6006c116--- /dev/null+++ b/server/services/sprites/scanner.js@@ -0,0 +1,339 @@+/**+ * The first named, non-walk animation track: a short directional scanner action.+ *+ * The render is deliberately reachable only through `startScannerGeneration`.+ * Everything after Grok writes the requested MP4 is deterministic local packing,+ * review, approval, and atlas input; no boot path or read endpoint calls a+ * provider.+ */++import { join } from 'path';+import { readdir, rm } 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 { SPRITE_DIRECTIONS, anchorIdForDirection } from './prompts.js';+import { SCANNER_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';++const RUN_RECORD_NAME = 'animation-run.json';+const selectionRelPath = (id) => `scanner/${id}-scanner-selection-v1.json`;+export const scannerSetRelPath = (id) => `scanner/${id}-scanner-set-v1.json`;+const runRelPath = (runId) => `runs/${runId}`;+const TUI_IDLE_MS = 90_000;+const TUI_TIMEOUT_MS = 30 * 60_000;++const scannerSetFinalError = () => new ServerError(+ 'Scanner set is finalized — reopen it before generating or approving another scanner action',+ { status: 409, code: 'SCANNER_SET_FINAL' },+);++async function loadSelection(recordId) {+ return readJSONFile(join(spriteDir(recordId), selectionRelPath(recordId)), null);+}++async function loadSet(recordId) {+ return readJSONFile(join(spriteDir(recordId), scannerSetRelPath(recordId)), null);+}++const seedSelection = (recordId) => ({+ schemaVersion: 1,+ kind: 'reviewed-directional-scanner-selection',+ track: SCANNER_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 loadRun(recordId, runId) {+ return readJSONFile(join(spriteDir(recordId), runRelPath(runId), RUN_RECORD_NAME), null);+}++async function scannerRuns(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 === SCANNER_TRACK)+ .sort((a, b) => Date.parse(b.createdAt || 0) - Date.parse(a.createdAt || 0));+}++export async function getScannerState(recordId) {+ const [selection, scannerSet, runs] = await Promise.all([+ loadSelection(recordId), loadSet(recordId), scannerRuns(recordId),+ ]);+ return {+ track: SCANNER_TRACK,+ bounds: getAnimationTrack(SCANNER_TRACK),+ selection,+ scannerSet,+ runs,+ };+}++const lockedAnchorFor = (manifest, direction) => {+ const anchor = manifest?.anchors?.find((item) => item.direction === direction);+ return anchor?.status === 'locked' && anchor.path ? anchor : null;+};++function scannerPrompt({ name, direction, chromaKey }) {+ return `Create a short, seamless scanner action for ${name}, facing ${direction}. `+ + 'The character raises a handheld scanner, makes one deliberate sweep, then returns to the exact starting pose. '+ + `Keep the character centered, full body visible, and animate only over a solid ${chromaKey} background. `+ + 'No text, UI, scenery, camera movement, cuts, or additional characters.';+}++function scannerTask({ prompt, inputAbs, videoAbs, duration }) {+ return `${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 startScannerGeneration(recordId, body) {+ return withAnimationWriteTail(recordId, () => startScannerGenerationImpl(recordId, body));+}++async function startScannerGenerationImpl(recordId, body) {+ const [record, reference, scannerSet, existingRuns] = await Promise.all([+ requireTrack(recordId, SCANNER_TRACK), loadManifest(recordId), loadSet(recordId), scannerRuns(recordId),+ ]);+ if (scannerSet) throw scannerSetFinalError();+ const { direction } = body;+ const anchor = lockedAnchorFor(reference, direction);+ if (!anchor) throw new ServerError(`Lock the ${anchorIdForDirection(direction)} anchor before generating its scanner action`, { status: 409, code: 'ANCHOR_NOT_LOCKED' });+ const chromaKey = resolveChromaKey({ manifest: reference, record });+ if (!chromaKey) throw new ServerError('No frozen chroma key is available for this character', { status: 409, code: 'CHROMA_KEY_REQUIRED' });+ if (existingRuns.some((run) => run.direction === direction && ['rendering', 'postprocessing'].includes(run.status))) {+ throw new ServerError(`A scanner render for ${direction} is already in progress`, { status: 409, code: 'SCANNER_RENDER_IN_PROGRESS' });+ }++ const frameCount = clampTrackFrameCount(body.frameCount, SCANNER_TRACK);+ const fps = clampTrackFps(body.fps, SCANNER_TRACK);+ const runId = `${SCANNER_TRACK}-${direction}-${randomUUID().slice(0, 8)}`;+ const runRel = runRelPath(runId);+ const generatedAbs = join(spriteDir(recordId), runRel, 'generated');+ await ensureDir(generatedAbs);+ const anchorAbs = resolveSpriteAssetPath(recordId, anchor.path);+ if (!await pathExists(anchorAbs)) throw new ServerError('Locked anchor file is missing on disk', { status: 500, code: 'ANCHOR_MISSING' });+ const inputAbs = join(generatedAbs, 'input-anchor-chroma.png');+ const [{ preparation, sha256: inputSha256 }, settings] = await Promise.all([+ prepareWalkAnchorChromaInput(anchorAbs, 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: SCANNER_TRACK,+ provider: GROK_TUI_ID,+ status: 'rendering',+ id: runId,+ shellSession: runId,+ characterId: recordId,+ direction,+ chromaKey,+ duration,+ frameCount,+ fps,+ anchorPath: anchor.path,+ anchorSha256: anchor.sha256 || await sha256File(anchorAbs),+ animationInputPath: `${runRel}/generated/input-anchor-chroma.png`,+ animationInputSha256: inputSha256,+ animationInputPreparation: preparation,+ createdAt: new Date().toISOString(),+ };+ await saveRun(recordId, run);+ runScannerTuiRender(recordId, {+ runId,+ direction,+ generatedAbs,+ videoAbs,+ grokPath: settings.imageGen?.grok?.grokPath,+ task: scannerTask({ prompt: scannerPrompt({ name: record.name, direction, chromaKey }), inputAbs, videoAbs, duration }),+ }).catch((err) => console.error(`❌ sprite scanner grok-tui render crashed ${recordId}/${runId}: ${err?.message || err}`));+ console.log(`📡 sprite scanner grok-tui render started ${recordId}/${runId}`);+ return { runId, direction, duration, shellSession: runId };+}++async function runScannerTuiRender(recordId, { runId, direction, 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 scanner ${recordId}/${direction}`,+ }).catch((err) => console.error(`❌ sprite scanner grok-tui run failed ${recordId}/${runId}: ${err?.message || err}`));+ await withAnimationWriteTail(recordId, () => attachScannerTuiResult(recordId, runId, videoAbs));+}++export async function attachScannerTuiResult(recordId, runId, videoAbs) {+ const run = await loadRun(recordId, runId);+ if (!run || run.track !== SCANNER_TRACK || await loadSet(recordId)) return;+ const selection = await loadSelection(recordId);+ if (selection?.directions?.[run.direction]?.runId === runId) return;+ if (!await pathExists(videoAbs)) {+ run.status = 'error';+ run.postprocessError = 'Grok finished without writing the scanner 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 packageScannerRun(recordId, run);+ await saveRun(recordId, run);+}++async function packageScannerRun(recordId, run) {+ try {+ const [reference, record] = await Promise.all([loadManifest(recordId), getRecord(recordId)]);+ const anchor = lockedAnchorFor(reference, run.direction);+ if (!anchor) throw new Error(`No locked ${run.direction} anchor in the reference manifest`);+ const chromaKey = resolveChromaKey({ manifest: reference, record, run });+ if (!chromaKey) throw new Error('No chroma key is available for the scanner matte');+ const runRel = runRelPath(run.id);+ const result = await runWalkPostprocess({+ recordId,+ track: SCANNER_TRACK,+ direction: run.direction,+ chromaKey,+ runAbs: join(spriteDir(recordId), runRel),+ runRel,+ anchorRel: anchor.path,+ anchorAbs: resolveSpriteAssetPath(recordId, anchor.path),+ videoAbs: resolveSpriteAssetPath(recordId, run.sourceVideoPath),+ frameCount: clampTrackFrameCount(run.frameCount, SCANNER_TRACK),+ fps: clampTrackFps(run.fps, SCANNER_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 scanner postprocess failed ${recordId}/${run.id}: ${err.message}`);+ }+ run.completedAt = new Date().toISOString();+}++export function approveScannerDirection(recordId, args) {+ return withAnimationWriteTail(recordId, () => approveScannerDirectionImpl(recordId, args));+}++async function approveScannerDirectionImpl(recordId, { direction, runId }) {+ await requireTrack(recordId, SCANNER_TRACK);+ if (await loadSet(recordId)) throw scannerSetFinalError();+ const run = await loadRun(recordId, runId);+ if (!run || run.track !== SCANNER_TRACK) throw new ServerError(`Unknown scanner run: ${runId}`, { status: 404, code: 'RUN_NOT_FOUND' });+ if (run.direction !== direction) throw new ServerError(`Run ${runId} animates '${run.direction}', not '${direction}'`, { status: 400, code: 'RUN_DIRECTION_MISMATCH' });+ 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 anchor = lockedAnchorFor(reference, direction);+ if (!anchor) throw new ServerError(`Lock the ${anchorIdForDirection(direction)} anchor before approving its scanner action`, { status: 409, code: 'ANCHOR_NOT_LOCKED' });+ if (run.anchorSha256) {+ const currentAnchorSha256 = anchor.sha256 || await sha256File(resolveSpriteAssetPath(recordId, anchor.path));+ if (run.anchorSha256 !== currentAnchorSha256) {+ throw new ServerError('This scanner action was rendered from an older directional anchor — generate it again from the current anchor', { status: 409, code: 'RUN_ANCHOR_STALE' });+ }+ }+ if (!packaged || packaged.track !== SCANNER_TRACK || packaged.direction !== direction || packaged.characterId !== recordId+ || packaged.frameCount !== run.frameCount || packaged.frameRate !== run.fps) {+ throw new ServerError('Packaged scanner manifest is missing or inconsistent', { status: 409, code: 'RUN_MANIFEST_INVALID' });+ }+ const frameCheck = await verifyPackagedFrames(recordId, packaged, { track: SCANNER_TRACK });+ if (frameCheck.missing) throw new ServerError(+ `${frameCheck.missing} of this scanner 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[direction] = {+ status: 'approved',+ runId,+ runPath: runRelPath(runId),+ runManifest: run.postprocessManifest,+ runManifestSha256: await sha256File(resolveSpriteAssetPath(recordId, run.postprocessManifest)),+ approvedAt: new Date().toISOString(),+ };+ const allApproved = SPRITE_DIRECTIONS.every((item) => selection.directions[item]?.status === 'approved');+ selection.status = allApproved ? 'complete' : 'in-progress';+ const selectionAbs = join(spriteDir(recordId), selectionRelPath(recordId));+ await ensureDir(join(spriteDir(recordId), SCANNER_TRACK));+ await atomicWrite(selectionAbs, selection);+ if (allApproved) {+ await atomicWrite(join(spriteDir(recordId), scannerSetRelPath(recordId)), {+ schemaVersion: 1,+ kind: 'finalized-eight-direction-scanner-set',+ track: SCANNER_TRACK,+ characterId: recordId,+ status: 'final',+ directionOrder: SPRITE_DIRECTIONS,+ selectionPath: selectionRelPath(recordId),+ selectionSha256: await sha256File(selectionAbs),+ directions: selection.directions,+ finalizedAt: new Date().toISOString(),+ });+ console.log(`🏁 sprite scanner set finalized for ${recordId}`);+ }+ return getScannerState(recordId);+}++export function invalidateScannerDirectionForAnchorRevision(recordId, { direction }) {+ return withAnimationWriteTail(recordId, () => invalidateScannerDirectionForAnchorRevisionImpl(recordId, direction));+}++export function invalidateScannerForTurnaroundRevision(recordId) {+ return withAnimationWriteTail(recordId, async () => {+ const invalidated = [];+ for (const direction of SPRITE_DIRECTIONS) {+ if (await invalidateScannerDirectionForAnchorRevisionImpl(recordId, direction)) invalidated.push(direction);+ }+ return invalidated;+ });+}++async function invalidateScannerDirectionForAnchorRevisionImpl(recordId, direction) {+ const [scannerSet, loaded] = await Promise.all([loadSet(recordId), loadSelection(recordId)]);+ const approved = loaded?.directions?.[direction] || scannerSet?.directions?.[direction];+ if (approved?.status !== 'approved') return false;+ const selection = loaded || { ...seedSelection(recordId), directions: { ...(scannerSet?.directions || {}) } };+ if (scannerSet) await rm(join(spriteDir(recordId), scannerSetRelPath(recordId)), { force: true });+ delete selection.directions[direction];+ selection.status = 'in-progress';+ await ensureDir(join(spriteDir(recordId), SCANNER_TRACK));+ await atomicWrite(join(spriteDir(recordId), selectionRelPath(recordId)), selection);+ const run = approved.runId ? await loadRun(recordId, approved.runId) : null;+ if (run?.track === SCANNER_TRACK) {+ await saveRun(recordId, {+ ...run,+ status: 'superseded-anchor',+ supersededAt: new Date().toISOString(),+ supersededReason: 'directional-anchor-revised',+ });+ }+ console.log(`♻️ sprite scanner direction ${recordId}/${direction} invalidated after anchor revision`);+ return true;+}diff --git a/server/services/sprites/scanner.test.js b/server/services/sprites/scanner.test.jsnew file mode 100644index 0000000000..cd815e2a95--- /dev/null+++ b/server/services/sprites/scanner.test.js@@ -0,0 +1,100 @@+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 { lockAllAnchors } from './spriteTestFixtures.js';++const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-scanner-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 (_anchorAbs, inputAbs) => {+ await mkdir(join(inputAbs, '..'), { recursive: true });+ const bytes = Buffer.from('scanner-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 { getScannerState, startScannerGeneration } = await import('./scanner.js');++let sequence = 0;+const newId = () => `scanner-${++sequence}`;++async function characterWithEastAnchor(id) {+ await records.createRecord({ kind: 'character', name: 'Scanner' }, id);+ await lockAllAnchors(TEST_ROOT, id, { lockReference, directions: ['east'] });+ 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('scanner animation track', () => {+ it('is provider-silent on reads, then starts a user-triggered four-frame scanner render', async () => {+ const id = await characterWithEastAnchor(newId());++ const initial = await getScannerState(id);+ expect(initial).toMatchObject({+ track: 'scanner',+ bounds: { minFrameCount: 2, maxFrameCount: 8, defaultFrameCount: 4, defaultFps: 6 },+ runs: [],+ });+ expect(executeTuiRun).not.toHaveBeenCalled();++ const result = await startScannerGeneration(id, { direction: 'east' });+ expect(result).toMatchObject({ direction: 'east', duration: 6 });+ expect(result.runId).toMatch(/^scanner-east-[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('scanner action');++ expect((await getScannerState(id)).runs).toMatchObject([{+ id: result.runId,+ track: 'scanner',+ status: 'rendering',+ frameCount: 4,+ fps: 6,+ direction: 'east',+ }]);+ });+});diff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.jsindex be87d3514e..5d0dbcc9b8 100644--- a/server/services/sprites/walk.js+++ b/server/services/sprites/walk.js@@ -25,7 +25,6 @@ import {ensureDir, atomicWrite, readJSONFile, pathExists, sha256File,} from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';-import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';import { executeTuiRun } from '../../lib/tuiPromptRunner.js';import { GROK_TUI_ID } from '../../lib/grok.js';import { getSettings } from '../settings.js';@@ -54,6 +53,10 @@ import {import { verifyPackagedFrames } from './walkFrames.js';import { probeVideoDuration } from '../../lib/ffmpeg.js';import { resolveGrokDuration } from '../../lib/grokVideoClip.js';+import { withAnimationWriteTail, resolveChromaKey } from './animationWorkflow.js';+import {+ invalidateScannerDirectionForAnchorRevision, invalidateScannerForTurnaroundRevision,+} from './scanner.js';// grok's walk render runs as an OBSERVABLE TUI session (issue: user wants to// watch/course-correct grok in the Shell) rather than a headless mediaJobQueue@@ -88,9 +91,8 @@ const RUN_RECORD_NAME = 'animation-run.json';// same convention as reference.js's manifestWriteTail. Exported for// walkTrims.js so its scan-then-write version claim can't race an attach or// a concurrent trim.-const walkWriteTail = createKeyCachedQueue();--export const withWalkWriteTail = (recordId, fn) => walkWriteTail(recordId, fn);+const walkWriteTail = (recordId, fn) => withAnimationWriteTail(recordId, fn);+export const withWalkWriteTail = walkWriteTail;async function loadWalkSet(recordId) {return readJSONFile(join(spriteDir(recordId), walkSetRelPath(recordId)), null);@@ -185,6 +187,16 @@ async function resolveRunAt(recordId, runDirRel) {const resolveRunById = (recordId, runId) => resolveRunAt(recordId, runRelPath(runId));+// The shared `runs/` tree now holds named tracks as well as walk. Legacy walk+// records predate the field, so an absent track remains walk-compatible; a+// declared non-walk track must never surface through, or be mutated by, the+// walk endpoints.+const isWalkRun = (run) => !run?.track || run.track === WALK_TRACK;+async function resolveWalkRunById(recordId, runId) {+ const found = await resolveRunById(recordId, runId);+ return isWalkRun(found?.run) ? found : null;+}+async function saveRunRecordAt(recordId, run, runDirRel) {const dir = join(spriteDir(recordId), runDirRel);await ensureDir(dir);@@ -676,7 +688,7 @@ export async function getWalkState(recordId) {return loadRunRecordAt(recordId, runDirRel).then((run) => (run ? normalizeRunRecord(recordId, run, runDirRel) : null));}),- )).filter(Boolean)+ )).filter(isWalkRun)// Second pass: a record whose own `id` differs from its directory name is// already covered by an entry that named it by id. Dedupe on id too, so a// run that somehow exists under both scan roots surfaces once.@@ -863,9 +875,7 @@ async function setWalkTargetImpl(recordId, { frameCount, fps }) {* Returns null when no rung has one, so callers refuse explicitly rather than* handing `undefined` to a color parser.*/-export const resolveChromaKey = ({ manifest, record, run } = {}) => (- run?.chromaKey || manifest?.chromaKey || record?.chromaKey || null-);+export { resolveChromaKey } from './animationWorkflow.js';/*** The locked directional anchor for a direction, or null. Third copy of this@@ -1241,7 +1251,7 @@ async function rerunWalkPostprocessImpl(recordId, runId, overrides) {await requireCharacter(recordId);// Layout-aware (#2993): an imported run commonly lives under `grok/<run-id>/`,// and its regenerated frames + record must go back to that same directory.- const found = await resolveRunById(recordId, runId);+ const found = await resolveWalkRunById(recordId, runId);if (!found) throw new ServerError(`Unknown walk run: ${runId}`, { status: 404, code: 'RUN_NOT_FOUND' });const { run, runDirRel } = found;// One state read serves the re-derive gate and the target below.@@ -1459,7 +1469,7 @@ export async function getWalkSourceFrames(recordId, runId, { extract = false } =// fallback below) — so pay for them once, concurrently.const [, found, state] = await Promise.all([requireCharacter(recordId),- resolveRunById(recordId, runId),+ resolveWalkRunById(recordId, runId),getWalkState(recordId),]);const { walkTarget, selection, walkSet } = state;@@ -1816,8 +1826,9 @@ export function invalidateWalkDirectionForAnchorRevision(recordId, { direction }export async function unlockDirectionalAnchor(recordId, { direction }) {await assertReferenceAnchorUnlockable(recordId, { direction });const walkInvalidated = await invalidateWalkDirectionForAnchorRevision(recordId, { direction });+ const scannerInvalidated = await invalidateScannerDirectionForAnchorRevision(recordId, { direction });const reference = await unlockReferenceAnchor(recordId, { direction });- return { ...reference, walkInvalidated };+ return { ...reference, walkInvalidated, scannerInvalidated };}/**@@ -1831,8 +1842,9 @@ export async function unlockDirectionalAnchor(recordId, { direction }) {export async function unlockTurnaroundReference(recordId) {await assertReferenceTurnaroundUnlockable(recordId);const walkInvalidatedDirections = await invalidateWalkForTurnaroundRevision(recordId);+ const scannerInvalidatedDirections = await invalidateScannerForTurnaroundRevision(recordId);const reference = await unlockReferenceTurnaround(recordId);- return { ...reference, walkInvalidatedDirections };+ return { ...reference, walkInvalidatedDirections, scannerInvalidatedDirections };}function invalidateWalkForTurnaroundRevision(recordId) {@@ -1909,7 +1921,7 @@ async function approveWalkDirectionImpl(recordId, { direction, runId }) {await requireUnfinalized(recordId);// Layout-aware, like the rerun above: a re-derived import stays in the run// directory it was imported into, and its approval must record THAT path.- const found = await resolveRunById(recordId, runId);+ const found = await resolveWalkRunById(recordId, runId);if (!found) throw new ServerError(`Unknown walk run: ${runId}`, { status: 404, code: 'RUN_NOT_FOUND' });const { run, runDirRel } = found;if (run.direction !== direction) {diff --git a/server/services/sprites/walk.test.js b/server/services/sprites/walk.test.jsindex aca49ab263..40750cf553 100644--- a/server/services/sprites/walk.test.js+++ b/server/services/sprites/walk.test.js@@ -273,6 +273,27 @@ async function importedCharacter(id, perDirection) {return runIds;}+describe('named-track isolation', () => {+ it('does not surface or reprocess a scanner run through the walk workflow', async () => {+ const id = await characterWithLockedAnchors(newId(), []);+ const runId = 'scanner-east-00000001';+ const runDir = join(TEST_ROOT, 'sprites', id, 'runs', runId);+ await mkdir(runDir, { recursive: true });+ await writeFile(join(runDir, 'animation-run.json'), JSON.stringify({+ id: runId,+ track: 'scanner',+ status: 'rendering',+ characterId: id,+ direction: 'east',+ createdAt: new Date().toISOString(),+ }));++ expect((await getWalkState(id)).runs).toEqual([]);+ await expect(rerunWalkPostprocess(id, { runId, frameCount: 8, fps: 12 }))+ .rejects.toMatchObject({ code: 'RUN_NOT_FOUND' });+ });+});+beforeEach(() => {executeTuiRun.mockClear();executeTuiRun.mockImplementation(() => new Promise(() => {}));diff --git a/server/services/sprites/walkFrames.js b/server/services/sprites/walkFrames.jsindex a1967164f5..0108996acc 100644--- a/server/services/sprites/walkFrames.js+++ b/server/services/sprites/walkFrames.js@@ -35,19 +35,20 @@ import {spriteDir, resolveSpriteAssetPath, toRecordRelativeAssetPath, resolveDriftTolerantRel,} from './paths.js';import { sha256Buffer } from './walkPostprocess.js';-import { walkPhaseLabels } from './walkBounds.js';+import { WALK_TRACK, getAnimationTrack } from './animationTracks.js';+import { trackColumnLabels } from './atlasGrid.js';const compileFrameError = (message) =>new ServerError(message, { status: 422, code: 'ATLAS_COMPILE_INVALID' });-export async function verifyPackagedFrames(recordId, manifest, { bytes = false } = {}) {+export async function verifyPackagedFrames(recordId, manifest, { bytes = false, track = manifest?.track || WALK_TRACK } = {}) {const dir = spriteDir(recordId);const frames = Array.isArray(manifest?.frames) ? manifest.frames : [];const total = frames.length;// Compile checks each frame's gait-phase against the set's phase labels. The// set's frame count is enforced identical across directions before this runs// (atlas.js), so labels derived from THIS manifest's length match the set's.- const labels = bytes ? walkPhaseLabels(total) : null;+ const labels = bytes ? trackColumnLabels(getAnimationTrack(track).id, total) : null;const frameBytes = bytes ? [] : null;let missing = 0;diff --git a/server/services/sprites/walkFrames.test.js b/server/services/sprites/walkFrames.test.jsindex bc15b64813..a9fb5ed2d9 100644--- a/server/services/sprites/walkFrames.test.js+++ b/server/services/sprites/walkFrames.test.js@@ -54,9 +54,11 @@ const newId = () => `frametest-${++seq}`;* root so re-anchoring is exercised.*/async function makeFrames(id, {- count = 8, runId = 'run-abcdef', fileLayout = 'grok', declaredLayout = 'grok', anchored = false,+ count = 8, runId = 'run-abcdef', fileLayout = 'grok', declaredLayout = 'grok', anchored = false, track = 'walk',} = {}) {- const labels = walkPhaseLabels(count);+ const labels = track === 'walk'+ ? walkPhaseLabels(count)+ : Array.from({ length: count }, (_, i) => `${track}-${String(i).padStart(2, '0')}`);const frames = [];for (let i = 0; i < count; i++) {const bytes = Buffer.from(`frame-${id}-${i}`);@@ -72,10 +74,16 @@ async function makeFrames(id, {sha256: sha256(bytes),});}- return { direction: 'east', characterId: id, frameCount: count, frames };+ return { track, direction: 'east', characterId: id, frameCount: count, frames };}describe('verifyPackagedFrames — existence mode (approve gate)', () => {+ it('uses the named scanner columns for a short scanner action', async () => {+ const id = newId();+ const manifest = await makeFrames(id, { track: 'scanner', count: 4 });+ await expect(verifyPackagedFrames(id, manifest, { bytes: true, track: 'scanner' }))+ .resolves.toMatchObject({ total: 4, missing: 0 });+ });it('passes when every declared frame is on disk', async () => {const id = newId();const manifest = await makeFrames(id);diff --git a/server/services/sprites/walkPostprocess.js b/server/services/sprites/walkPostprocess.jsindex a8396621d2..acfa4d779f 100644--- a/server/services/sprites/walkPostprocess.js+++ b/server/services/sprites/walkPostprocess.js@@ -33,8 +33,9 @@ import { keyChannelSplit, keyness, keyShareFn, hexToRgb } from './chromaKey.js';// consumers (walk.js, atlas.js) keep importing them from walkPostprocess.import {WALK_FRAME_COUNT, WALK_DEFAULT_FRAME_COUNT, WALK_DEFAULT_FPS,- walkPhaseLabels, clampFrameCount, clampFps,} from './walkBounds.js';+import { WALK_TRACK, getAnimationTrack, clampTrackFrameCount, clampTrackFps } from './animationTracks.js';+import { trackColumnLabels } from './atlasGrid.js';export {WALK_PHASES, WALK_FRAME_COUNT, WALK_DEFAULT_FRAME_COUNT, WALK_DEFAULT_FPS,@@ -839,11 +840,12 @@ export async function prepareWalkAnchorChromaInput(anchorAbs, destAbs, chromaKey*/export async function runWalkPostprocess({recordId, direction, chromaKey, runAbs, runRel, anchorRel, anchorAbs, videoAbs,- frameCount = WALK_DEFAULT_FRAME_COUNT, fps = WALK_DEFAULT_FPS,+ frameCount = WALK_DEFAULT_FRAME_COUNT, fps = WALK_DEFAULT_FPS, track = WALK_TRACK,}) {- const targetFrames = clampFrameCount(frameCount);- const playbackFps = clampFps(fps);- const phaseLabels = walkPhaseLabels(targetFrames);+ const trackRow = getAnimationTrack(track);+ const targetFrames = clampTrackFrameCount(frameCount, track);+ const playbackFps = clampTrackFps(fps, track);+ const phaseLabels = trackColumnLabels(track, targetFrames);const split = keyChannelSplit(chromaKey);const generatedAbs = join(runAbs, 'generated');const generatedRel = `${runRel}/generated`;@@ -904,19 +906,20 @@ export async function runWalkPostprocess({});}- const stripName = `${recordId}-walk-${direction}-strip.png`;+ const stripName = `${recordId}-${track}-${direction}-strip.png`;const stripSha256 = await encodePngWithHash(packStrip(despilled), join(generatedAbs, stripName));const reviewDir = join(generatedAbs, 'review');await ensureDir(reviewDir);- const contrastName = `${recordId}-walk-${direction}-contrast-review.png`;+ const contrastName = `${recordId}-${track}-${direction}-contrast-review.png`;const comparisonSha256 = await encodePngWithHash(await buildContrastSheet(despilled), join(reviewDir, contrastName), 3);- const manifestName = `${recordId}-walk-${direction}-manifest.json`;+ const manifestName = `${recordId}-${track}-${direction}-manifest.json`;const manifest = {schemaVersion: 1,- kind: 'deterministically-packaged-grok-walk-video',+ kind: `deterministically-packaged-grok-${track}-video`,status: 'candidate',+ track: trackRow.id,characterId: recordId,direction,chromaKey,