Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-2895]): add Sprites section to Media Gen — record store, production-asset importer, read-only library (phase 1)
[._.]/ Adam Eivy7875424ea01b
diff --git a/client/src/App.jsx b/client/src/App.jsxindex 2222cf1520..448f521451 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -73,6 +73,7 @@ const CreativeDirectorDetail = lazyWithReload(() => import('./pages/CreativeDireconst CreativeCommissions = lazyWithReload(() => import('./pages/CreativeCommissions'));const CreativeCommissionDetail = lazyWithReload(() => import('./pages/CreativeCommissionDetail'));const MusicVideo = lazyWithReload(() => import('./pages/MusicVideo'));+const Sprites = lazyWithReload(() => import('./pages/Sprites'));const MoodBoards = lazyWithReload(() => import('./pages/MoodBoards'));const MoodBoardDetail = lazyWithReload(() => import('./pages/MoodBoardDetail'));const CreateApp = lazyWithReload(() => import('./pages/CreateApp'));@@ -326,6 +327,8 @@ export default function App() {<Route path="creative-director/:id/:tab" element={<CreativeDirectorLegacyRedirect />} /><Route path="music-video" element={<MusicVideo />} /><Route path="music-video/:projectId" element={<MusicVideo />} />+ <Route path="sprites" element={<Sprites />} />+ <Route path="sprites/:id" element={<Sprites />} /><Route path="timeline" element={<VideoTimeline />} /><Route path="timeline/:projectId" element={<VideoTimelineEditor />} /><Route path="models" element={<MediaModels />} />diff --git a/client/src/pages/MediaGen.jsx b/client/src/pages/MediaGen.jsxindex 9b874c202a..41b5a67c50 100644--- a/client/src/pages/MediaGen.jsx+++ b/client/src/pages/MediaGen.jsx@@ -1,5 +1,5 @@import { useNavigate, useLocation, Outlet } from 'react-router-dom';-import { Layers, Image as ImageIcon, Film, History, HardDrive, Scissors, FolderOpen, Sparkles, GraduationCap, Music } from 'lucide-react';+import { Layers, Image as ImageIcon, Film, History, HardDrive, Scissors, FolderOpen, Sparkles, GraduationCap, Music, PersonStanding } from 'lucide-react';import TabPills from '../components/ui/TabPills';const TABS = [@@ -7,6 +7,7 @@ const TABS = [{ id: 'video', label: 'Video', icon: Film },{ id: 'timeline', label: 'Timeline', icon: Scissors },{ id: 'music-video', label: 'Music Video', icon: Music },+ { id: 'sprites', label: 'Sprites', icon: PersonStanding },{ id: 'history', label: 'History', icon: History },{ id: 'collections', label: 'Collections', icon: FolderOpen },{ id: 'loras', label: 'LoRAs', icon: Sparkles },diff --git a/client/src/pages/Sprites.jsx b/client/src/pages/Sprites.jsxnew file mode 100644index 0000000000..d6c55b63a9--- /dev/null+++ b/client/src/pages/Sprites.jsx@@ -0,0 +1,269 @@+import { useEffect, useState, useCallback } from 'react';+import { useParams, useNavigate } from 'react-router-dom';+import { PersonStanding, Package, Download, FolderOpen, X, RefreshCw } from 'lucide-react';+import toast from '../components/ui/Toast';+import { listSpriteRecords, getSpriteRecord, importSprites } from '../services/apiSprites.js';+import { formatBytes, timeAgo } from '../utils/formatters.js';++// Sprite Manager (issue #2895, phase 1): read-only library over imported+// production sprites — characters (reference sets, walk strips, runtime+// atlases) and props atlas families — plus the source-tree importer. The+// generation workflow (reference → anchors → animation → publish) lands in+// later phases.++const IMAGE_EXT = /\.(png|gif|webp|jpe?g)$/i;++function topLevelGroup(assetPath) {+ const idx = assetPath.indexOf('/');+ return idx < 0 ? '' : assetPath.slice(0, idx);+}++function ImportPanel({ onImported }) {+ const [open, setOpen] = useState(false);+ const [sourceRoot, setSourceRoot] = useState('');+ const [includeProps, setIncludeProps] = useState(true);+ const [importing, setImporting] = useState(false);++ const runImport = async () => {+ setImporting(true);+ try {+ const { totals } = await importSprites({ sourceRoot: sourceRoot.trim(), includeProps });+ toast.success(`Imported ${totals.subjects} subjects (${totals.files} files, ${totals.verified} hash-verified${totals.errors ? `, ${totals.errors} errors` : ''})`);+ setOpen(false);+ onImported();+ } catch {+ // request() already toasted the failure — keep the panel open for a retry.+ } finally {+ setImporting(false);+ }+ };++ if (!open) {+ return (+ <button+ onClick={() => setOpen(true)}+ className="flex items-center gap-2 px-3 py-1.5 bg-port-accent hover:bg-blue-600 text-white rounded text-sm"+ >+ <Download className="w-4 h-4" /> Import+ </button>+ );+ }++ return (+ <div className="w-full bg-port-card border border-port-border rounded-lg p-4 space-y-3">+ <div className="flex items-center justify-between">+ <h3 className="text-sm font-semibold text-white">Import production sprites</h3>+ <button onClick={() => setOpen(false)} aria-label="Close import panel" className="text-gray-400 hover:text-white">+ <X className="w-4 h-4" />+ </button>+ </div>+ <p className="text-xs text-gray-400">+ Point at a sprite-pipeline checkout (expects <code>art-pipeline/characters/</code> and/or <code>game/assets/sprites/</code>).+ Only approved/final assets import — reference candidates and raw run intermediates stay behind.+ </p>+ <div>+ <label htmlFor="sprite-import-source" className="block text-xs text-gray-400 mb-1">Source root path</label>+ <input+ id="sprite-import-source"+ type="text"+ value={sourceRoot}+ onChange={(e) => setSourceRoot(e.target.value)}+ placeholder="~/path/to/game-project"+ className="w-full bg-port-bg border border-port-border rounded px-3 py-1.5 text-sm text-white"+ />+ </div>+ <label htmlFor="sprite-import-props" className="flex items-center gap-2 text-sm text-gray-300">+ <input+ id="sprite-import-props"+ type="checkbox"+ checked={includeProps}+ onChange={(e) => setIncludeProps(e.target.checked)}+ />+ Include props atlas families from the game tree+ </label>+ <button+ onClick={runImport}+ disabled={importing || !sourceRoot.trim()}+ className="flex items-center gap-2 px-3 py-1.5 bg-port-accent hover:bg-blue-600 disabled:opacity-50 text-white rounded text-sm"+ >+ {importing ? <RefreshCw className="w-4 h-4 animate-spin" /> : <Download className="w-4 h-4" />}+ {importing ? 'Importing…' : 'Run Import'}+ </button>+ </div>+ );+}++function RecordList({ records, selectedId, onSelect }) {+ const characters = records.filter((r) => r.kind === 'character');+ const props = records.filter((r) => r.kind !== 'character');+ const Section = ({ title, icon: Icon, items }) => (+ items.length > 0 && (+ <div>+ <h3 className="flex items-center gap-1.5 text-xs uppercase tracking-wide text-gray-500 mb-1.5">+ <Icon className="w-3.5 h-3.5" /> {title}+ </h3>+ <ul className="space-y-1">+ {items.map((r) => (+ <li key={r.id}>+ <button+ onClick={() => onSelect(r.id)}+ className={`w-full text-left px-3 py-2 rounded text-sm ${selectedId === r.id ? 'bg-port-accent/20 text-white border border-port-accent' : 'bg-port-card text-gray-300 border border-port-border hover:border-gray-500'}`}+ >+ <span className="font-medium">{r.name}</span>+ <span className="block text-xs text-gray-500">{r.status}{r.chromaKey ? ` · key ${r.chromaKey}` : ''}</span>+ </button>+ </li>+ ))}+ </ul>+ </div>+ )+ );+ return (+ <div className="space-y-4">+ <Section title="Characters" icon={PersonStanding} items={characters} />+ <Section title="Props" icon={Package} items={props} />+ </div>+ );+}++function AssetGroups({ recordId, assets }) {+ const [preview, setPreview] = useState(null);+ const groups = assets.reduce((acc, a) => {+ const g = topLevelGroup(a.path) || 'files';+ (acc[g] ||= []).push(a);+ return acc;+ }, {});+ return (+ <div className="space-y-4">+ {Object.entries(groups).map(([group, files]) => (+ <div key={group}>+ <h4 className="flex items-center gap-1.5 text-sm font-semibold text-gray-300 mb-2">+ <FolderOpen className="w-4 h-4" /> {group}+ <span className="text-xs text-gray-500 font-normal">({files.length})</span>+ </h4>+ <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-2">+ {files.map((a) => {+ const url = `/data/sprites/${encodeURIComponent(recordId)}/${a.path.split('/').map(encodeURIComponent).join('/')}`;+ return IMAGE_EXT.test(a.path) ? (+ <button+ key={a.path}+ onClick={() => setPreview({ url, path: a.path })}+ className="bg-port-bg border border-port-border rounded p-1 hover:border-port-accent"+ title={a.path}+ >+ <img src={url} alt={a.path} loading="lazy" className="w-full h-20 object-contain" style={{ imageRendering: 'pixelated' }} />+ <span className="block text-[10px] text-gray-500 truncate">{a.path.split('/').pop()}</span>+ </button>+ ) : (+ <a+ key={a.path}+ href={url}+ target="_blank"+ rel="noreferrer"+ className="bg-port-bg border border-port-border rounded p-2 text-xs text-gray-400 hover:border-gray-500 truncate"+ title={a.path}+ >+ {a.path.split('/').pop()}+ <span className="block text-[10px] text-gray-600">{formatBytes(a.size)}</span>+ </a>+ );+ })}+ </div>+ </div>+ ))}+ {preview && (+ <div+ className="fixed inset-0 z-50 bg-black/80 flex items-center justify-center p-4"+ role="dialog"+ aria-label={`Preview ${preview.path}`}+ onClick={() => setPreview(null)}+ >+ <div className="max-w-full max-h-full">+ <img src={preview.url} alt={preview.path} className="max-w-full max-h-[85vh] object-contain" style={{ imageRendering: 'pixelated' }} />+ <p className="text-center text-xs text-gray-400 mt-2">{preview.path}</p>+ </div>+ </div>+ )}+ </div>+ );+}++export default function Sprites() {+ const { id } = useParams();+ const navigate = useNavigate();+ const [records, setRecords] = useState(null);+ const [detail, setDetail] = useState(null);+ const [detailMissing, setDetailMissing] = useState(false);++ const refresh = useCallback(() => {+ listSpriteRecords().then(setRecords);+ }, []);++ useEffect(() => { refresh(); }, [refresh]);++ useEffect(() => {+ if (!id) { setDetail(null); setDetailMissing(false); return; }+ setDetail(null);+ setDetailMissing(false);+ getSpriteRecord(id, { silent: true })+ .then(setDetail)+ .catch(() => setDetailMissing(true));+ }, [id]);++ return (+ <div className="flex flex-col md:flex-row gap-4 h-full">+ <aside className="md:w-64 shrink-0 space-y-3">+ <ImportPanel onImported={refresh} />+ {records === null ? (+ <p className="text-sm text-gray-500">Loading…</p>+ ) : records.length === 0 ? (+ <p className="text-sm text-gray-500">+ No sprites yet. Import a production set from a sprite-pipeline checkout to get started.+ </p>+ ) : (+ <RecordList records={records} selectedId={id} onSelect={(rid) => navigate(`/media/sprites/${rid}`)} />+ )}+ </aside>+ <section className="flex-1 min-w-0">+ {!id ? (+ <p className="text-sm text-gray-500">Select a sprite to browse its reference set, animation strips, and atlases.</p>+ ) : detailMissing ? (+ <div className="text-sm text-gray-400">+ Sprite not found.{' '}+ <button onClick={() => navigate('/media/sprites')} className="text-port-accent hover:underline">Back to library</button>+ </div>+ ) : !detail ? (+ <p className="text-sm text-gray-500">Loading…</p>+ ) : (+ <div className="space-y-4">+ <div>+ <h2 className="text-lg font-semibold text-white flex items-center gap-2">+ {detail.record.kind === 'character' ? <PersonStanding className="w-5 h-5" /> : <Package className="w-5 h-5" />}+ {detail.record.name}+ </h2>+ <p className="text-xs text-gray-500">+ {detail.record.kind} · {detail.record.status}+ {detail.record.chromaKey && (+ <>+ {' · chroma key '}+ <span className="inline-block w-3 h-3 rounded-sm align-middle border border-port-border" style={{ backgroundColor: detail.record.chromaKey }} />{' '}+ {detail.record.chromaKey}+ </>+ )}+ {detail.record.importedFrom?.importedAt && ` · imported ${timeAgo(detail.record.importedFrom.importedAt)}`}+ </p>+ {detail.record.spec?.archetype && (+ <p className="text-xs text-gray-500">archetype: {detail.record.spec.archetype}</p>+ )}+ </div>+ {detail.assets.length === 0 ? (+ <p className="text-sm text-gray-500">No assets on disk for this record.</p>+ ) : (+ <AssetGroups recordId={detail.record.id} assets={detail.assets} />+ )}+ </div>+ )}+ </section>+ </div>+ );+}diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 9164e8b7dd..7a654bc702 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -96,6 +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). || `apiPipeline.js` | Pipeline (issues + stages + canon). || `apiUniverseBuilder.js` | Universe Builder (generate + edit + commit). || `apiAuthors.js` | Author personas (name, writing style, bio, headshot description/style). |diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 3d28f9daf1..745e3e9785 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -70,6 +70,7 @@ export * from './apiSyncReview.js';export * from './apiCreativeDirector.js';export * from './apiCreativeCommission.js';export * from './apiMusicVideo.js';+export * from './apiSprites.js';export * from './apiMoodBoard.js';export * from './apiImporter.js';export * from './apiStoryBuilder.js';diff --git a/client/src/services/apiSprites.js b/client/src/services/apiSprites.jsnew file mode 100644index 0000000000..244bb9900b--- /dev/null+++ b/client/src/services/apiSprites.js@@ -0,0 +1,21 @@+import { request } from './apiCore.js';++// Sprite Manager (issue #2895, phase 1): record list/detail, production-asset+// import, and the few user-managed record fields. `options` lets a caller+// suppress request()'s auto-toast with `{ silent: true }` when it owns its own+// error UI.++export const listSpriteRecords = (options = {}) => request('/sprites', options);+export const getSpriteRecord = (id, options = {}) => request(`/sprites/${encodeURIComponent(id)}`, options);+export const updateSpriteRecord = (id, patch, options = {}) => request(`/sprites/${encodeURIComponent(id)}`, {+ method: 'PATCH', body: JSON.stringify(patch), ...options,+});+export const deleteSpriteRecord = (id, options = {}) => request(`/sprites/${encodeURIComponent(id)}`, {+ method: 'DELETE', ...options,+});++// Import approved production assets from a source pipeline checkout.+// Returns { results: [...perSubject], totals }.+export const importSprites = (body, options = {}) => request('/sprites/import', {+ method: 'POST', body: JSON.stringify(body), ...options,+});diff --git a/server/index.js b/server/index.jsindex 8a9203485d..41534c6b68 100644--- a/server/index.js+++ b/server/index.js@@ -120,6 +120,7 @@ import mediaJobsRoutes from './routes/mediaJobs.js';import creativeDirectorRoutes from './routes/creativeDirector.js';import creativeCommissionRoutes from './routes/creativeCommissions.js';import musicVideoRoutes from './routes/musicVideo.js';+import spriteRoutes from './routes/sprites.js';import moodBoardRoutes from './routes/moodBoard.js';import privacyRoutes from './routes/privacy.js';import writersRoomRoutes from './routes/writersRoom.js';@@ -554,6 +555,7 @@ app.use('/api/media-jobs', mediaJobsRoutes);app.use('/api/creative-director', creativeDirectorRoutes);app.use('/api/creative-commission', creativeCommissionRoutes);app.use('/api/music-video', musicVideoRoutes);+app.use('/api/sprites', spriteRoutes);app.use('/api/mood-boards', moodBoardRoutes);app.use('/api/privacy', privacyRoutes);app.use('/api/writers-room', writersRoomRoutes);@@ -744,6 +746,9 @@ app.use('/data/lora-datasets', express.static(PATHS.loraDatasets, ASSET_STATIC_O// can pull them by URL without going through an explicit download route.app.use('/data/videos', express.static(PATHS.videos, ASSET_STATIC_OPTS));app.use('/data/video-thumbnails', express.static(PATHS.videoThumbnails, ASSET_STATIC_OPTS));+// Sprite Manager library previews (anchors, strips, atlases) render inline+// via <img src="/data/sprites/<id>/<rel>"> (#2895).+app.use('/data/sprites', express.static(PATHS.sprites, ASSET_STATIC_OPTS));// Voice-over WAVs rendered by the pipeline audio stage — the AudioStage UI// pulls them inline via <audio src="/data/audio/<filename>">.app.use('/data/audio', express.static(PATHS.audio));diff --git a/server/lib/db/schema/media.js b/server/lib/db/schema/media.jsindex bf1340f759..51d093e20e 100644--- a/server/lib/db/schema/media.js+++ b/server/lib/db/schema/media.js@@ -80,6 +80,24 @@ export const mediaDdl = [// Partial index for the live-list filter (deleted = FALSE).`CREATE INDEX IF NOT EXISTS idx_mood_boards_live ON mood_boards (deleted) WHERE deleted = FALSE`,+ // Sprite records (issue #2895, phase 1). One row per sprite subject — a+ // character or a props atlas family; the full record (spec, chromaKey,+ // publishBinding, importedFrom) in `data` JSONB with kind/status mirrored+ // for queries. Binary assets live under data/sprites/<id>/ — the row is+ // metadata + workflow state only. Not federated in phase 1; the tombstone+ // trio keeps peer-sync additive later.+ `CREATE TABLE IF NOT EXISTS sprite_records (+ id TEXT PRIMARY KEY,+ kind VARCHAR(16) NOT NULL DEFAULT 'character',+ status VARCHAR(32) NOT NULL DEFAULT 'draft',+ data JSONB NOT NULL DEFAULT '{}'::jsonb,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW(),+ deleted BOOLEAN DEFAULT FALSE,+ deleted_at TIMESTAMPTZ+ )`,+ `CREATE INDEX IF NOT EXISTS idx_sprite_records_live ON sprite_records (deleted) WHERE deleted = FALSE`,+// Media asset index (Phase 3.2, issue #1000). One row per generated image// or video; the bytes stay on disk (data/images, data/videos) and the// sidecar/.json history files remain authoritative — this table is adiff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex 62cab55f86..1d49a32cf1 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -113,6 +113,10 @@ export const PATHS = {trainingRuns: join(INSTALL_ROOT, 'data/training-runs'),videos: join(INSTALL_ROOT, 'data/videos'),videoThumbnails: join(INSTALL_ROOT, 'data/video-thumbnails'),+ // Sprite Manager (issue #2895): per-record asset trees+ // (sprites/<id>/{reference,walk,runs,runtime,atlas}/...). Records live in+ // Postgres (sprite_records); only binary artifacts + manifests live here.+ sprites: join(INSTALL_ROOT, 'data/sprites'),// Persisted audio renders (voice-over lines). Kept distinct from// the in-memory voice-agent synthesis path in services/voice/ — that path// streams WAV over Socket.IO without ever touching disk.diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 5169679974..24a839c0d5 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -23,6 +23,7 @@ export const NAV_COMMANDS = [{ id: 'nav.create.creative-commission', path: '/creative-commission', label: 'Creative Commissions', section: 'Create', aliases: ['creative-commission', 'commissions', 'commission', 'creation-engine', 'autonomous-creation', 'standing-brief', 'recurring-brief'], keywords: ['schedule', 'recurring', 'nightly', 'brief', 'autonomous', 'creation engine', 'cron', 'feedback', 'taste', 'standing commission', 'auto-generate'] },{ id: 'nav.media.music-video', path: '/media/music-video', label: 'Music Video', section: 'Create', aliases: ['music-video', 'musicvideo', 'music video', 'mv', 'sync-to-beat'], keywords: ['music', 'beat', 'sync', 'audio-reactive', 'director', 'scene board', 'tempo', 'choreography'] },{ id: 'nav.create.mood-boards', path: '/mood-boards', label: 'Mood Boards', section: 'Create', aliases: ['mood-boards', 'mood-board', 'moodboard', 'mood', 'inspiration', 'references'], keywords: ['inspiration', 'reference', 'pin', 'visual', 'canvas', 'collect', 'pinboard', 'palette', 'ideas'] },+ { id: 'nav.media.sprites', path: '/media/sprites', label: 'Sprites', section: 'Create', aliases: ['sprites', 'sprite', 'sprite-manager', 'sprite-sheets'], keywords: ['sprite sheet', 'atlas', 'game art', 'pixel art', 'character animation', 'walk cycle', 'anchors'] },{ id: 'nav.media.timeline', path: '/media/timeline', label: 'Timeline', section: 'Create', aliases: ['timeline', 'video-timeline', 'editor'], keywords: ['edit', 'trim', 'composite', 'stitch', 'cut', 'compose'] },{ id: 'nav.media.models', path: '/media/models', label: 'Media Models', section: 'Create', aliases: ['media-models', 'image-models', 'video-models', 'huggingface'], keywords: ['hf cache', 'model storage', 'disk', 'add model', 'install model', 'custom model'] },{ id: 'nav.create.authors', path: '/authors', label: 'Authors', section: 'Create', aliases: ['authors', 'author', 'byline', 'author-persona', 'writer-persona'], keywords: ['author', 'byline', 'pen name', 'persona', 'writing style', 'bio', 'headshot', 'cover', 'book author'] },diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 3d91fd8879..276d283750 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -938,6 +938,23 @@ export const videoDownloadSchema = z.object({url: z.string().url().max(2048)});+// Sprite Manager (issue #2895, phase 1). Import runs against a local+// filesystem path the user supplies (the source pipeline checkout); the+// importer validates the tree shape server-side.+export const spriteImportRequestSchema = z.object({+ sourceRoot: z.string().min(1).max(1024),+ characters: z.array(z.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/)).optional(),+ includeProps: z.boolean().optional(),+});++export const spriteRecordUpdateSchema = z.object({+ name: z.string().min(1).max(200).optional(),+ notes: z.string().max(10000).nullable().optional(),+ // Phase 2 constrains this to the three standard keys; phase 1 stores any hex+ // color so imported legacy magenta round-trips.+ chromaKey: z.string().regex(/^#[0-9a-fA-F]{6}$/).nullable().optional(),+});+// =============================================================================// TRANSITIONAL RE-EXPORTS (issue #1151 split)// =============================================================================diff --git a/server/routes/sprites.js b/server/routes/sprites.jsnew file mode 100644index 0000000000..a30b8cb23b--- /dev/null+++ b/server/routes/sprites.js@@ -0,0 +1,52 @@+/**+ * Sprites Routes — REST surface for the Sprite Manager (issue #2895, phase 1).+ *+ * Phase 1 is the read-only library + importer: list/get sprite records (with+ * their on-disk asset listing), import approved production assets from a+ * source pipeline tree, and patch the few user-managed record fields. The+ * generation workflow (reference/anchors/animation/publish) lands in later+ * phases.+ */++import { Router } from 'express';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import {+ validateRequest,+ spriteImportRequestSchema,+ spriteRecordUpdateSchema,+} from '../lib/validation.js';+import { listRecords, getRecord, updateRecord, deleteRecord } from '../services/sprites/records.js';+import { listSpriteAssets } from '../services/sprites/paths.js';+import { importFromSource } from '../services/sprites/importer.js';++const router = Router();++router.get('/', asyncHandler(async (_req, res) => {+ res.json(await listRecords());+}));++// Import approved production assets from a source tree. A direct user action+// (never boot-triggered) per the AI Provider / cold-start policy — though this+// endpoint itself makes no AI calls, only file copies.+router.post('/import', asyncHandler(async (req, res) => {+ const input = validateRequest(spriteImportRequestSchema, req.body);+ res.json(await importFromSource(input));+}));++router.get('/:id', asyncHandler(async (req, res) => {+ const record = await getRecord(req.params.id);+ if (!record) throw new ServerError('Sprite record not found', { status: 404, code: 'NOT_FOUND' });+ const assets = await listSpriteAssets(record.id);+ res.json({ record, assets });+}));++router.patch('/:id', asyncHandler(async (req, res) => {+ const patch = validateRequest(spriteRecordUpdateSchema, req.body);+ res.json(await updateRecord(req.params.id, patch));+}));++router.delete('/:id', asyncHandler(async (req, res) => {+ res.json(await deleteRecord(req.params.id));+}));++export default router;diff --git a/server/routes/sprites.test.js b/server/routes/sprites.test.jsnew file mode 100644index 0000000000..768c1a6ebb--- /dev/null+++ b/server/routes/sprites.test.js@@ -0,0 +1,89 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';++vi.mock('../services/sprites/records.js', () => ({+ listRecords: vi.fn(async () => [{ id: 'pioneer', kind: 'character', name: 'Pioneer' }]),+ getRecord: vi.fn(),+ updateRecord: vi.fn(async (id, patch) => ({ id, ...patch })),+ deleteRecord: vi.fn(async () => ({ ok: true })),+}));++vi.mock('../services/sprites/paths.js', () => ({+ listSpriteAssets: vi.fn(async () => [{ path: 'reference/main.png', size: 10, mtime: 1 }]),+}));++vi.mock('../services/sprites/importer.js', () => ({+ importFromSource: vi.fn(async () => ({ results: [], totals: { subjects: 0, files: 0, verified: 0, errors: 0 } })),+}));++import * as records from '../services/sprites/records.js';+import * as paths from '../services/sprites/paths.js';+import * as importer from '../services/sprites/importer.js';+import { errorMiddleware } from '../lib/errorHandler.js';+import spriteRoutes from './sprites.js';++function makeApp() {+ const app = express();+ app.use(express.json());+ app.use('/api/sprites', spriteRoutes);+ app.use(errorMiddleware);+ return app;+}++describe('sprites routes', () => {+ let app;+ beforeEach(() => { app = makeApp(); vi.clearAllMocks(); });++ it('GET / returns the record list', async () => {+ const r = await request(app).get('/api/sprites');+ expect(r.status).toBe(200);+ expect(r.body).toEqual([{ id: 'pioneer', kind: 'character', name: 'Pioneer' }]);+ });++ it('GET /:id returns record + asset listing', async () => {+ records.getRecord.mockResolvedValueOnce({ id: 'pioneer', kind: 'character' });+ const r = await request(app).get('/api/sprites/pioneer');+ expect(r.status).toBe(200);+ expect(r.body.record.id).toBe('pioneer');+ expect(r.body.assets).toHaveLength(1);+ expect(records.getRecord).toHaveBeenCalledWith('pioneer');+ expect(paths.listSpriteAssets).toHaveBeenCalledWith('pioneer');+ });++ it('GET /:id 404s on an unknown record', async () => {+ records.getRecord.mockResolvedValueOnce(null);+ const r = await request(app).get('/api/sprites/ghost');+ expect(r.status).toBe(404);+ });++ it('POST /import validates and forwards the parsed input', async () => {+ const r = await request(app).post('/api/sprites/import')+ .send({ sourceRoot: '/tmp/src', includeProps: false });+ expect(r.status).toBe(200);+ expect(importer.importFromSource).toHaveBeenCalledWith({ sourceRoot: '/tmp/src', includeProps: false });+ });++ it('POST /import rejects a missing sourceRoot', async () => {+ const r = await request(app).post('/api/sprites/import').send({});+ expect(r.status).toBe(400);+ expect(importer.importFromSource).not.toHaveBeenCalled();+ });++ it('PATCH /:id validates the whitelist patch', async () => {+ const r = await request(app).patch('/api/sprites/pioneer').send({ chromaKey: '#00FF00', notes: null });+ expect(r.status).toBe(200);+ expect(records.updateRecord).toHaveBeenCalledWith('pioneer', { chromaKey: '#00FF00', notes: null });+ });++ it('PATCH /:id rejects a malformed chroma key', async () => {+ const r = await request(app).patch('/api/sprites/pioneer').send({ chromaKey: 'magenta' });+ expect(r.status).toBe(400);+ });++ it('DELETE /:id soft-deletes', async () => {+ const r = await request(app).delete('/api/sprites/pioneer');+ expect(r.status).toBe(200);+ expect(records.deleteRecord).toHaveBeenCalledWith('pioneer');+ });+});diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex 59b1eee9b7..5b9f8fa6fa 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -705,6 +705,24 @@ CREATE TABLE IF NOT EXISTS music_video_projects (-- Partial index for the live-list filter (deleted = FALSE).CREATE INDEX IF NOT EXISTS idx_music_video_projects_live ON music_video_projects (deleted) WHERE deleted = FALSE;+-- Sprite records (issue #2895, phase 1). One row per sprite subject — a+-- character or a props atlas family; the full record (spec, chromaKey,+-- publishBinding, importedFrom) in `data` JSONB with kind/status mirrored for+-- queries. Binary assets live under data/sprites/<id>/. Not federated in+-- phase 1; the tombstone trio keeps peer-sync additive later. Mirrors the+-- sprite_records block in db/schema/media.js.+CREATE TABLE IF NOT EXISTS sprite_records (+ id TEXT PRIMARY KEY,+ kind VARCHAR(16) NOT NULL DEFAULT 'character',+ status VARCHAR(32) NOT NULL DEFAULT 'draft',+ data JSONB NOT NULL DEFAULT '{}'::jsonb,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW(),+ deleted BOOLEAN DEFAULT FALSE,+ deleted_at TIMESTAMPTZ+);+CREATE INDEX IF NOT EXISTS idx_sprite_records_live ON sprite_records (deleted) WHERE deleted = FALSE;+-- Mood boards (issue #911). A dedicated inspiration/mood-board canvas, distinct-- from raw Media History, for collecting visual + textual references that feed-- the Create suite. One row per board, the full record (name/description/items[])diff --git a/server/services/sprites/importer.js b/server/services/sprites/importer.jsnew file mode 100644index 0000000000..5d6271f55f--- /dev/null+++ b/server/services/sprites/importer.js@@ -0,0 +1,295 @@+/**+ * Sprites — production-asset importer (issue #2895, phase 1).+ *+ * Ingests the approved/final artifacts of an ElsewhereAcres-layout sprite+ * pipeline into data/sprites/, creating/refreshing a sprite record per+ * subject. Expected source layout (all paths relative to `sourceRoot`):+ *+ * art-pipeline/characters/<id>.json character specs+ * art-source/sprites/<id>/reference/ locked main + anchors (+ candidates/, skipped)+ * art-source/sprites/<id>/walk/ finalized walk-set manifests+ * art-source/sprites/<id>/grok|runs/<run-id>/ animation runs (only files the walk set references)+ * art-source/sprites/<id>/runtime/vN/ immutable published atlas archives+ * art-source/sprites/<id>/imagegen/vN/ approved redraw sources+ * art-pipeline/catalog/runtime-selection.json current published-atlas pointer+ * game/assets/sprites/<family>/ props atlas families (PNG + README)+ *+ * Only approved/final artifacts import: reference candidates, raw video, and+ * extracted frame intermediates stay behind. Where a source manifest carries a+ * sha256 for a file, the copied bytes are verified against it — a mismatch is+ * recorded per-item (the import continues) so one corrupt file can't abort a+ * whole tree. Runs on demand only (a user action) — never at boot.+ */++import { join, basename, dirname } from 'path';+import { readdir, copyFile, stat } from 'fs/promises';+import { PATHS, ensureDir, sha256File, tryReadFile, atomicWrite } from '../../lib/fileUtils.js';+import { ServerError } from '../../lib/errorHandler.js';+import { upsertImportedRecord } from './records.js';+import { spriteDir } from './paths.js';+import { isValidSpriteId } from './recordsLogic.js';++// The source pipeline keys everything on magenta; imported characters carry it+// so later re-renders stay consistent with their existing anchors/strips.+const LEGACY_CHROMA_KEY = '#FF00FF';++const PROP_FILE_EXTENSIONS = ['.png', '.md'];++async function pathExists(p) {+ try {+ await stat(p);+ return true;+ } catch {+ return false;+ }+}++async function readJson(p) {+ const raw = await tryReadFile(p);+ if (raw === null) return null;+ try {+ return JSON.parse(raw);+ } catch {+ return null;+ }+}++/**+ * Recursively copy `srcDir` into `destDir`, filtering by `shouldCopy(relPath,+ * isDir)`. Returns the list of copied file paths relative to destDir.+ */+async function copyTree(srcDir, destDir, shouldCopy = () => true) {+ const copied = [];+ async function walk(current, rel) {+ let entries;+ try {+ entries = await readdir(current, { withFileTypes: true });+ } catch {+ return;+ }+ for (const entry of entries) {+ if (entry.name.startsWith('.')) continue;+ const entryRel = rel ? `${rel}/${entry.name}` : entry.name;+ if (!shouldCopy(entryRel, entry.isDirectory())) continue;+ const srcPath = join(current, entry.name);+ if (entry.isDirectory()) {+ await walk(srcPath, entryRel);+ } else if (entry.isFile()) {+ const destPath = join(destDir, entryRel);+ await ensureDir(dirname(destPath));+ await copyFile(srcPath, destPath);+ copied.push(entryRel);+ }+ }+ }+ await walk(srcDir, '');+ return copied;+}++/**+ * Verify copied files against the sha256 map a source manifest declares.+ * `expectations` is [{ relPath, sha256 }] relative to destDir; missing files+ * and hash mismatches land in the returned errors list.+ */+async function verifyHashes(destDir, expectations, errors) {+ let verified = 0;+ for (const { relPath, sha256 } of expectations) {+ if (typeof sha256 !== 'string' || !sha256) continue;+ const abs = join(destDir, relPath);+ if (!(await pathExists(abs))) {+ errors.push(`missing after copy: ${relPath}`);+ continue;+ }+ const actual = await sha256File(abs);+ if (actual !== sha256) errors.push(`sha256 mismatch: ${relPath}`);+ else verified += 1;+ }+ return verified;+}++// Manifest paths reference files repo-relative (art-source/sprites/<id>/…) or+// occasionally bare. Normalize to a path relative to the character's source+// dir so it can be re-anchored under data/sprites/<id>/.+function relToCharacterDir(manifestPath, characterId) {+ if (typeof manifestPath !== 'string' || !manifestPath) return null;+ const marker = `sprites/${characterId}/`;+ const idx = manifestPath.indexOf(marker);+ if (idx >= 0) return manifestPath.slice(idx + marker.length);+ return manifestPath.replace(/^\/+/, '');+}++async function importCharacter({ sourceRoot, characterId, spec, specPath }) {+ const result = { id: characterId, kind: 'character', files: 0, verified: 0, errors: [] };+ const srcCharDir = join(sourceRoot, 'art-source', 'sprites', characterId);+ const destDir = spriteDir(characterId);+ await ensureDir(destDir);++ // Character spec — verbatim copy for provenance alongside the record.+ await copyFile(specPath, join(destDir, 'character-spec.json'));+ result.files += 1;++ const hashExpectations = [];++ // reference/ — locked main + anchors; candidates/ (unapproved) stay behind.+ if (await pathExists(join(srcCharDir, 'reference'))) {+ const copied = await copyTree(+ join(srcCharDir, 'reference'),+ join(destDir, 'reference'),+ (rel, isDir) => !(isDir && basename(rel) === 'candidates') && !rel.includes('candidates/'),+ );+ result.files += copied.length;+ for (const rel of copied) {+ if (!rel.endsWith('.json')) continue;+ const manifest = await readJson(join(destDir, 'reference', rel));+ for (const anchor of manifest?.anchors || []) {+ const anchorRel = relToCharacterDir(anchor?.path, characterId);+ if (anchorRel && anchor?.sha256) hashExpectations.push({ relPath: anchorRel, sha256: anchor.sha256 });+ }+ }+ }++ // walk/ — finalized walk-set manifests, then the run files each direction+ // references (manifest + packed strip + previews; never raw/ or frames/).+ const walkDir = join(srcCharDir, 'walk');+ if (await pathExists(walkDir)) {+ const copied = await copyTree(walkDir, join(destDir, 'walk'));+ result.files += copied.length;+ for (const rel of copied) {+ if (!rel.endsWith('.json')) continue;+ const walkSet = await readJson(join(destDir, 'walk', rel));+ for (const [, dir] of Object.entries(walkSet?.directions || {})) {+ const runRel = relToCharacterDir(dir?.runPath, characterId);+ if (!runRel) continue;+ const srcRunDir = join(srcCharDir, runRel);+ if (!(await pathExists(srcRunDir))) {+ result.errors.push(`walk set references missing run: ${runRel}`);+ continue;+ }+ // Root-level files only — manifests, packed strips, previews. The+ // run's raw/, frames/, review/, generated/ intermediates stay behind.+ const runCopied = await copyTree(srcRunDir, join(destDir, runRel), (r, isDir) => !isDir && !r.includes('/'));+ result.files += runCopied.length;+ if (dir?.runManifest && dir?.runManifestSha256) {+ const manifestRel = relToCharacterDir(dir.runManifest, characterId);+ if (manifestRel) hashExpectations.push({ relPath: manifestRel, sha256: dir.runManifestSha256 });+ }+ }+ }+ }++ // runtime/ (immutable atlas archives) + imagegen/ (approved redraw sources).+ for (const sub of ['runtime', 'imagegen']) {+ if (await pathExists(join(srcCharDir, sub))) {+ const copied = await copyTree(join(srcCharDir, sub), join(destDir, sub));+ result.files += copied.length;+ }+ }++ result.verified = await verifyHashes(destDir, hashExpectations, result.errors);++ const record = await upsertImportedRecord(characterId, {+ kind: 'character',+ name: spec?.displayName || characterId,+ status: 'imported',+ spec,+ chromaKey: LEGACY_CHROMA_KEY,+ importedFrom: { sourceRoot, importedAt: new Date().toISOString() },+ });+ result.record = record;+ return result;+}++async function importPropsFamily({ sourceRoot, familyId, srcFamilyDir }) {+ const result = { id: familyId, kind: 'props', files: 0, verified: 0, errors: [] };+ const destDir = join(spriteDir(familyId), 'atlas');+ const copied = await copyTree(srcFamilyDir, destDir, (rel, isDir) => {+ if (isDir) return true;+ const lower = rel.toLowerCase();+ return PROP_FILE_EXTENSIONS.some((ext) => lower.endsWith(ext));+ });+ result.files += copied.length;+ const record = await upsertImportedRecord(familyId, {+ kind: 'props',+ name: familyId,+ status: 'imported',+ importedFrom: { sourceRoot, importedAt: new Date().toISOString() },+ });+ result.record = record;+ return result;+}++/**+ * Import approved sprite assets from `sourceRoot`. Options:+ * - characters: limit to these character ids (default: all specs found)+ * - includeProps: also import game/assets/sprites/ prop families (default true)+ *+ * Returns { results: [...perSubject], totals: { subjects, files, verified, errors } }.+ */+export async function importFromSource({ sourceRoot, characters, includeProps = true }) {+ const specsDir = join(sourceRoot, 'art-pipeline', 'characters');+ const propsDir = join(sourceRoot, 'game', 'assets', 'sprites');+ const hasSpecs = await pathExists(specsDir);+ const hasProps = await pathExists(propsDir);+ if (!hasSpecs && !hasProps) {+ throw new ServerError(+ 'Source root does not look like a sprite pipeline (expected art-pipeline/characters/ or game/assets/sprites/)',+ { status: 400, code: 'INVALID_SOURCE_ROOT' },+ );+ }++ await ensureDir(PATHS.sprites);+ const results = [];+ const characterIds = new Set();++ if (hasSpecs) {+ const wanted = Array.isArray(characters) && characters.length ? new Set(characters) : null;+ for (const entry of (await readdir(specsDir)).sort()) {+ if (!entry.endsWith('.json')) continue;+ const specPath = join(specsDir, entry);+ const spec = await readJson(specPath);+ // A real character spec carries characterId; sibling files in the specs+ // dir (JSON-schema definitions, templates) don't and are not subjects.+ if (!spec?.characterId) continue;+ const characterId = spec.characterId;+ if (!isValidSpriteId(characterId)) {+ results.push({ id: characterId, kind: 'character', files: 0, verified: 0, errors: ['invalid character id'] });+ continue;+ }+ if (wanted && !wanted.has(characterId)) continue;+ characterIds.add(characterId);+ results.push(await importCharacter({ sourceRoot, characterId, spec, specPath }));+ }+ }++ if (hasProps && includeProps) {+ for (const entry of (await readdir(propsDir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {+ if (!entry.isDirectory()) continue;+ // A character's published atlas dir duplicates what runtime/ archives —+ // only non-character families import from the game tree.+ if (characterIds.has(entry.name)) continue;+ if (!isValidSpriteId(entry.name)) continue;+ results.push(await importPropsFamily({ sourceRoot, familyId: entry.name, srcFamilyDir: join(propsDir, entry.name) }));+ }+ }++ // Published-atlas pointer — provenance for the current selection, kept with+ // the character it points at.+ const selection = await readJson(join(sourceRoot, 'art-pipeline', 'catalog', 'runtime-selection.json'));+ if (selection?.characterId && characterIds.has(selection.characterId)) {+ const destDir = join(spriteDir(selection.characterId), 'catalog');+ await ensureDir(destDir);+ await atomicWrite(join(destDir, 'runtime-selection.json'), selection);+ }++ const totals = results.reduce(+ (acc, r) => ({+ subjects: acc.subjects + 1,+ files: acc.files + r.files,+ verified: acc.verified + r.verified,+ errors: acc.errors + r.errors.length,+ }),+ { subjects: 0, files: 0, verified: 0, errors: 0 },+ );+ console.log(`🎞️ Sprite import: ${totals.subjects} subjects, ${totals.files} files, ${totals.verified} hash-verified, ${totals.errors} errors`);+ return { results, totals };+}diff --git a/server/services/sprites/importer.test.js b/server/services/sprites/importer.test.jsnew file mode 100644index 0000000000..02c455f9e4--- /dev/null+++ b/server/services/sprites/importer.test.js@@ -0,0 +1,149 @@+/**+ * Sprite importer against a synthetic source tree (#2895, phase 1). Builds an+ * ElsewhereAcres-layout fixture in a tmpdir, imports it into a tmp data root,+ * and asserts the selective-copy rules (candidates/raw intermediates stay+ * behind), the manifest sha256 verification, and the record upserts. Also+ * covers the path-confinement gate in paths.js.+ */++import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest';+import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync } from 'fs';+import { createHash } from 'crypto';+import { tmpdir } from 'os';+import { join } from 'path';++const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'sprite-importer-data-'));+const SOURCE_ROOT = mkdtempSync(join(tmpdir(), 'sprite-importer-src-'));+const SPRITES_ROOT = join(TEST_DATA_ROOT, 'sprites');++vi.mock('../../lib/fileUtils.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT, sprites: SPRITES_ROOT } };+});++const { importFromSource } = await import('./importer.js');+const { getRecord, updateRecord } = await import('./records.js');+const { resolveSpriteAssetPath, listSpriteAssets } = await import('./paths.js');++const sha256 = (buf) => createHash('sha256').update(buf).digest('hex');++function writeTree(root, files) {+ for (const [rel, content] of Object.entries(files)) {+ const abs = join(root, rel);+ mkdirSync(join(abs, '..'), { recursive: true });+ writeFileSync(abs, typeof content === 'string' ? content : JSON.stringify(content, null, 2));+ }+}++beforeAll(() => {+ const anchorBytes = 'FAKE-PNG-ANCHOR-SOUTH';+ const runManifest = JSON.stringify({ kind: 'deterministically-packaged-grok-walk-video', direction: 'south' }, null, 2);+ writeTree(SOURCE_ROOT, {+ 'art-pipeline/characters/hero.json': {+ schemaVersion: 1, characterId: 'hero', displayName: 'Hero', archetype: 'adult-humanoid-v1',+ },+ 'art-source/sprites/hero/reference/hero-reference-set-v1.json': {+ schemaVersion: 1,+ mainReference: { path: 'art-source/sprites/hero/reference/hero-main.png' },+ anchors: [+ { id: 'south', path: 'art-source/sprites/hero/reference/hero-anchor-south.png', sha256: sha256(anchorBytes) },+ { id: 'east', path: 'art-source/sprites/hero/reference/hero-anchor-east.png', sha256: sha256('DIFFERENT-BYTES') },+ ],+ },+ 'art-source/sprites/hero/reference/hero-main.png': 'FAKE-PNG-MAIN',+ 'art-source/sprites/hero/reference/hero-anchor-south.png': anchorBytes,+ 'art-source/sprites/hero/reference/hero-anchor-east.png': 'TAMPERED-ANCHOR-EAST',+ 'art-source/sprites/hero/reference/candidates/reject-1.png': 'UNAPPROVED',+ 'art-source/sprites/hero/walk/hero-walk-set-v1.json': {+ schemaVersion: 1, kind: 'finalized-eight-direction-walk-set', characterId: 'hero', status: 'final',+ directions: {+ south: {+ status: 'approved',+ runPath: 'art-source/sprites/hero/grok/run-1',+ runManifest: 'art-source/sprites/hero/grok/run-1/south-manifest.json',+ runManifestSha256: sha256(runManifest),+ },+ },+ },+ 'art-source/sprites/hero/grok/run-1/south-manifest.json': runManifest,+ 'art-source/sprites/hero/grok/run-1/south-strip.png': 'FAKE-STRIP',+ 'art-source/sprites/hero/grok/run-1/raw/frame-000.png': 'RAW-INTERMEDIATE',+ 'art-source/sprites/hero/runtime/v1/hero-animation-atlas-v1.png': 'FAKE-ATLAS',+ 'art-pipeline/catalog/runtime-selection.json': { selectionId: 's1', characterId: 'hero', status: 'selected' },+ 'game/assets/sprites/flora/flora-atlas.png': 'FAKE-FLORA-ATLAS',+ 'game/assets/sprites/flora/flora-atlas.png.import': 'GODOT-IMPORT-SIDECAR',+ 'game/assets/sprites/flora/README.md': '# flora',+ 'game/assets/sprites/hero/hero-animation-atlas.png': 'PUBLISHED-COPY',+ });+});++afterAll(() => {+ rmSync(TEST_DATA_ROOT, { recursive: true, force: true });+ rmSync(SOURCE_ROOT, { recursive: true, force: true });+});++describe('importFromSource', () => {+ it('imports approved assets, skips intermediates, verifies hashes, upserts records', async () => {+ const { results, totals } = await importFromSource({ sourceRoot: SOURCE_ROOT });++ const hero = results.find((r) => r.id === 'hero');+ expect(hero.kind).toBe('character');+ // one good anchor + the run manifest verify; the tampered east anchor errors+ expect(hero.verified).toBe(2);+ expect(hero.errors).toEqual(['sha256 mismatch: reference/hero-anchor-east.png']);++ const heroDir = join(SPRITES_ROOT, 'hero');+ expect(existsSync(join(heroDir, 'character-spec.json'))).toBe(true);+ expect(existsSync(join(heroDir, 'reference/hero-anchor-south.png'))).toBe(true);+ expect(existsSync(join(heroDir, 'reference/candidates/reject-1.png'))).toBe(false);+ expect(existsSync(join(heroDir, 'walk/hero-walk-set-v1.json'))).toBe(true);+ expect(existsSync(join(heroDir, 'grok/run-1/south-strip.png'))).toBe(true);+ expect(existsSync(join(heroDir, 'grok/run-1/raw/frame-000.png'))).toBe(false);+ expect(existsSync(join(heroDir, 'runtime/v1/hero-animation-atlas-v1.png'))).toBe(true);+ expect(existsSync(join(heroDir, 'catalog/runtime-selection.json'))).toBe(true);++ // props family imported (PNG + README, never the Godot .import sidecar);+ // the character's published game dir is NOT double-imported as props.+ const flora = results.find((r) => r.id === 'flora');+ expect(flora.kind).toBe('props');+ expect(existsSync(join(SPRITES_ROOT, 'flora/atlas/flora-atlas.png'))).toBe(true);+ expect(existsSync(join(SPRITES_ROOT, 'flora/atlas/flora-atlas.png.import'))).toBe(false);+ expect(results.some((r) => r.id === 'hero' && r.kind === 'props')).toBe(false);++ expect(totals.subjects).toBe(2);+ expect(totals.errors).toBe(1);++ const record = await getRecord('hero');+ expect(record).toMatchObject({ kind: 'character', name: 'Hero', status: 'imported', chromaKey: '#FF00FF' });+ expect(record.spec.archetype).toBe('adult-humanoid-v1');+ });++ it('re-import preserves user-managed record fields', async () => {+ await updateRecord('hero', { notes: 'reviewed', chromaKey: '#00FF00' });+ await importFromSource({ sourceRoot: SOURCE_ROOT, characters: ['hero'], includeProps: false });+ const record = await getRecord('hero');+ expect(record.notes).toBe('reviewed');+ expect(record.chromaKey).toBe('#00FF00');+ });++ it('rejects a root that is not a sprite pipeline', async () => {+ const empty = mkdtempSync(join(tmpdir(), 'sprite-importer-empty-'));+ await expect(importFromSource({ sourceRoot: empty })).rejects.toMatchObject({ code: 'INVALID_SOURCE_ROOT' });+ rmSync(empty, { recursive: true, force: true });+ });+});++describe('paths confinement', () => {+ it('resolves inside the record dir and lists imported assets', async () => {+ const abs = resolveSpriteAssetPath('hero', 'reference/hero-main.png');+ expect(abs.startsWith(join(SPRITES_ROOT, 'hero'))).toBe(true);+ const assets = await listSpriteAssets('hero');+ expect(assets.some((a) => a.path === 'reference/hero-main.png')).toBe(true);+ });++ it('refuses traversal and bad ids', () => {+ expect(() => resolveSpriteAssetPath('hero', '../other/file.png')).toThrow(/escapes/);+ expect(() => resolveSpriteAssetPath('hero', '/etc/passwd')).toThrow(/escapes/);+ expect(() => resolveSpriteAssetPath('../hero', 'x.png')).toThrow(/Invalid sprite id/);+ });+});diff --git a/server/services/sprites/paths.js b/server/services/sprites/paths.jsnew file mode 100644index 0000000000..83aef26ea6--- /dev/null+++ b/server/services/sprites/paths.js@@ -0,0 +1,76 @@+/**+ * Sprites — on-disk layout + path confinement (issue #2895, phase 1).+ *+ * Binary sprite assets live under data/sprites/<recordId>/ mirroring the+ * source pipeline's per-character tree (reference/, walk/, runs/<run-id>/,+ * runtime/vN/, atlas/ for props families). Every request-influenced path MUST+ * resolve through `resolveSpriteAssetPath` — the confinement gate that keeps a+ * crafted record id or relative path from escaping the sprites root (the port+ * of the source pipeline's pathsec gate). `safeUnder` in lib/ffmpeg.js is+ * single-segment-only, so this module carries the multi-segment equivalent.+ */++import { join, resolve, sep } from 'path';+import { readdir, stat } from 'fs/promises';+import { PATHS } from '../../lib/fileUtils.js';+import { ServerError } from '../../lib/errorHandler.js';+import { isValidSpriteId } from './recordsLogic.js';++export function spritesRoot() {+ return PATHS.sprites;+}++/** Asset directory for one sprite record. Throws on a non-slug id. */+export function spriteDir(recordId) {+ if (!isValidSpriteId(recordId)) {+ throw new ServerError(`Invalid sprite id: ${recordId}`, { status: 400, code: 'INVALID_SPRITE_ID' });+ }+ return join(PATHS.sprites, recordId);+}++/**+ * Resolve a relative asset path inside a record's directory, refusing any+ * path that escapes it (`..`, absolute paths, symlink-free lexical check).+ */+export function resolveSpriteAssetPath(recordId, relPath) {+ const dir = spriteDir(recordId);+ if (typeof relPath !== 'string' || !relPath) {+ throw new ServerError('Missing asset path', { status: 400, code: 'INVALID_ASSET_PATH' });+ }+ const abs = resolve(dir, relPath);+ if (abs !== dir && !abs.startsWith(dir + sep)) {+ throw new ServerError(`Asset path escapes sprite directory: ${relPath}`, { status: 400, code: 'INVALID_ASSET_PATH' });+ }+ return abs;+}++/**+ * Recursively list a record's on-disk assets as+ * `[{ path, size, mtime }]` with `path` relative (posix separators) to the+ * record dir. Dotfiles are skipped. A record with no directory yet returns [].+ */+export async function listSpriteAssets(recordId) {+ const dir = spriteDir(recordId);+ const out = [];+ async function walk(current, relPrefix) {+ let entries;+ try {+ entries = await readdir(current, { withFileTypes: true });+ } catch {+ return; // dir absent → no assets+ }+ for (const entry of entries) {+ if (entry.name.startsWith('.')) continue;+ const rel = relPrefix ? `${relPrefix}/${entry.name}` : entry.name;+ if (entry.isDirectory()) {+ await walk(join(current, entry.name), rel);+ } else if (entry.isFile()) {+ const s = await stat(join(current, entry.name));+ out.push({ path: rel, size: s.size, mtime: s.mtimeMs });+ }+ }+ }+ await walk(dir, '');+ out.sort((a, b) => a.path.localeCompare(b.path));+ return out;+}diff --git a/server/services/sprites/records.js b/server/services/sprites/records.jsnew file mode 100644index 0000000000..0dc0058aab--- /dev/null+++ b/server/services/sprites/records.js@@ -0,0 +1,69 @@+/**+ * Sprites — record store backend dispatcher (issue #2895, phase 1).+ *+ * Mirrors the Music Video dispatcher (services/musicVideo/projects.js): a thin+ * layer that picks the backend so every import site + test mock targets one+ * module.+ *+ * Backend selection (same posture as the memory backend):+ * - PostgreSQL (recordsDB.js) for normal installs.+ * - File (recordsFile.js) only via MEMORY_BACKEND=file (escape hatch) or+ * NODE_ENV=test — both UNSUPPORTED for production.+ *+ * No federation wiring: sprite records are machine-local in phase 1 (per+ * #2895's scope); the tombstone trio on the record keeps peer-sync additive.+ */++import { checkHealth, ensureSchema } from '../../lib/db.js';++let backend = null;+let backendName = null;++async function selectBackend() {+ if (backend) return backend;++ const envBackend = process.env.MEMORY_BACKEND;+ if (envBackend === 'file' || process.env.NODE_ENV === 'test') {+ backend = await import('./recordsFile.js');+ backendName = 'file';+ return backend;+ }++ const health = await checkHealth();+ if (!health.connected) {+ throw new Error('Sprites requires PostgreSQL — run `npm run setup:db` (dev/test only: set MEMORY_BACKEND=file in .env)');+ }+ await ensureSchema();+ backend = await import('./recordsDB.js');+ backendName = 'postgres';+ return backend;+}++/** Name of the active backend, or null before first call (for diagnostics/tests). */+export function getSpriteRecordsBackendName() {+ return backendName;+}++export async function listRecords(options = {}) {+ return (await selectBackend()).listRecords(options);+}++export async function getRecord(id, options = {}) {+ return (await selectBackend()).getRecord(id, options);+}++export async function createRecord(input, id) {+ return (await selectBackend()).createRecord(input, id);+}++export async function updateRecord(id, patch) {+ return (await selectBackend()).updateRecord(id, patch);+}++export async function deleteRecord(id) {+ return (await selectBackend()).deleteRecord(id);+}++export async function upsertImportedRecord(id, input) {+ return (await selectBackend()).upsertImportedRecord(id, input);+}diff --git a/server/services/sprites/recordsDB.js b/server/services/sprites/recordsDB.jsnew file mode 100644index 0000000000..4a174eb2e4--- /dev/null+++ b/server/services/sprites/recordsDB.js@@ -0,0 +1,116 @@+/**+ * Sprites — PostgreSQL-backed record store (default backend).+ *+ * One row per sprite record in `sprite_records`: id / kind / status /+ * created_at / updated_at mirrored as columns, the full record in `data`+ * JSONB. Mutators run inside withTransaction + `SELECT … FOR UPDATE` so two+ * write paths against the same record serialize instead of losing an update.+ * Mutation semantics live in recordsLogic.js (shared with recordsFile.js) so+ * the two backends can't drift. Mirrors musicVideo/projectsDB.js — minus+ * federation (sprite records are machine-local in phase 1; the tombstone trio+ * is present so peer-sync later is additive).+ */++import { query, withTransaction } from '../../lib/db.js';+import { ServerError } from '../../lib/errorHandler.js';+import {+ buildSpriteRecord,+ applySpriteRecordPatch,+ mergeImportedRecord,+ mirrorTimestamp,+} from './recordsLogic.js';++function rowToRecord(row) {+ return row ? row.data : null;+}++async function persist(exec, record) {+ const now = new Date().toISOString();+ const createdAt = mirrorTimestamp(record.createdAt, now);+ await exec(+ `INSERT INTO sprite_records (id, kind, status, data, created_at, updated_at, deleted, deleted_at)+ VALUES ($1, $2, $3, $4::jsonb, $5, $6, $7, $8)+ ON CONFLICT (id) DO UPDATE SET+ kind = EXCLUDED.kind,+ status = EXCLUDED.status,+ data = EXCLUDED.data,+ updated_at = EXCLUDED.updated_at,+ deleted = EXCLUDED.deleted,+ deleted_at = EXCLUDED.deleted_at`,+ [+ record.id,+ record.kind,+ record.status,+ JSON.stringify(record),+ createdAt,+ mirrorTimestamp(record.updatedAt, createdAt),+ record.deleted === true,+ mirrorTimestamp(record.deletedAt, null),+ ],+ );+ return record;+}++export async function listRecords({ includeDeleted = false } = {}) {+ const result = includeDeleted+ ? await query(`SELECT data FROM sprite_records ORDER BY created_at ASC`)+ : await query(`SELECT data FROM sprite_records WHERE deleted = FALSE ORDER BY created_at ASC`);+ return result.rows.map(rowToRecord);+}++export async function getRecord(id, { includeDeleted = false } = {}) {+ const result = await query(`SELECT data FROM sprite_records WHERE id = $1`, [id]);+ const record = rowToRecord(result.rows[0]);+ if (!record) return null;+ return includeDeleted || !record.deleted ? record : null;+}++export async function createRecord(input, id) {+ return withTransaction(async (client) => {+ const sel = await client.query(`SELECT data FROM sprite_records WHERE id = $1 FOR UPDATE`, [id]);+ const existing = rowToRecord(sel.rows[0]);+ if (existing && !existing.deleted) {+ throw new ServerError(`Sprite record already exists: ${id}`, { status: 409, code: 'ALREADY_EXISTS' });+ }+ const now = new Date().toISOString();+ const record = buildSpriteRecord(input, { id, now });+ await persist(client.query.bind(client), record);+ console.log(`🎞️ Created sprite record: ${id} (${record.kind})`);+ return record;+ });+}++export async function updateRecord(id, patch) {+ return withTransaction(async (client) => {+ const sel = await client.query(`SELECT data FROM sprite_records WHERE id = $1 FOR UPDATE`, [id]);+ const record = rowToRecord(sel.rows[0]);+ if (!record || record.deleted) throw new ServerError('Sprite record not found', { status: 404, code: 'NOT_FOUND' });+ const next = applySpriteRecordPatch(record, patch);+ await persist(client.query.bind(client), next);+ return next;+ });+}++export async function deleteRecord(id) {+ return withTransaction(async (client) => {+ const sel = await client.query(`SELECT data FROM sprite_records WHERE id = $1 FOR UPDATE`, [id]);+ const record = rowToRecord(sel.rows[0]);+ if (!record || record.deleted) throw new ServerError('Sprite record not found', { status: 404, code: 'NOT_FOUND' });+ const now = new Date().toISOString();+ await persist(client.query.bind(client), { ...record, deleted: true, deletedAt: now, updatedAt: now });+ return { ok: true };+ });+}++/** Importer upsert — create or refresh a record from a source-tree import. */+export async function upsertImportedRecord(id, input) {+ return withTransaction(async (client) => {+ const sel = await client.query(`SELECT data FROM sprite_records WHERE id = $1 FOR UPDATE`, [id]);+ const existing = rowToRecord(sel.rows[0]);+ const now = new Date().toISOString();+ const imported = buildSpriteRecord(input, { id, now });+ const next = mergeImportedRecord(existing, imported, now);+ await persist(client.query.bind(client), next);+ return next;+ });+}diff --git a/server/services/sprites/recordsFile.js b/server/services/sprites/recordsFile.jsnew file mode 100644index 0000000000..993bc04f4b--- /dev/null+++ b/server/services/sprites/recordsFile.js@@ -0,0 +1,81 @@+/**+ * Sprites — file-backed record store (escape-hatch / test backend).+ *+ * Persists to data/sprite-records.json (array, atomicWrite). Reachable only+ * via MEMORY_BACKEND=file or NODE_ENV=test — PostgreSQL (recordsDB.js) is the+ * default. Mutation semantics live in recordsLogic.js so this backend and the+ * PG backend can't drift. Mirrors musicVideo/projectsFile.js.+ */++import { join } from 'path';+import { PATHS, readJSONFile, atomicWrite, ensureDir } from '../../lib/fileUtils.js';+import { ServerError } from '../../lib/errorHandler.js';+import { buildSpriteRecord, applySpriteRecordPatch, mergeImportedRecord } from './recordsLogic.js';++const RECORDS_FILE = join(PATHS.data, 'sprite-records.json');++async function loadAll() {+ const raw = await readJSONFile(RECORDS_FILE, []);+ return Array.isArray(raw) ? raw : [];+}++async function saveAll(records) {+ await ensureDir(PATHS.data);+ await atomicWrite(RECORDS_FILE, records);+}++export async function listRecords({ includeDeleted = false } = {}) {+ const all = await loadAll();+ return includeDeleted ? all : all.filter((r) => !r.deleted);+}++export async function getRecord(id, { includeDeleted = false } = {}) {+ const all = await loadAll();+ const found = all.find((r) => r.id === id);+ if (!found) return null;+ return includeDeleted || !found.deleted ? found : null;+}++export async function createRecord(input, id) {+ const now = new Date().toISOString();+ const all = await loadAll();+ if (all.some((r) => r.id === id && !r.deleted)) {+ throw new ServerError(`Sprite record already exists: ${id}`, { status: 409, code: 'ALREADY_EXISTS' });+ }+ const record = buildSpriteRecord(input, { id, now });+ all.push(record);+ await saveAll(all);+ console.log(`🎞️ Created sprite record: ${id} (${record.kind})`);+ return record;+}++export async function updateRecord(id, patch) {+ const all = await loadAll();+ const idx = all.findIndex((r) => r.id === id);+ if (idx < 0 || all[idx].deleted) throw new ServerError('Sprite record not found', { status: 404, code: 'NOT_FOUND' });+ all[idx] = applySpriteRecordPatch(all[idx], patch);+ await saveAll(all);+ return all[idx];+}++export async function deleteRecord(id) {+ const all = await loadAll();+ const idx = all.findIndex((r) => r.id === id);+ if (idx < 0 || all[idx].deleted) throw new ServerError('Sprite record not found', { status: 404, code: 'NOT_FOUND' });+ const now = new Date().toISOString();+ all[idx] = { ...all[idx], deleted: true, deletedAt: now, updatedAt: now };+ await saveAll(all);+ return { ok: true };+}++/** Importer upsert — create or refresh a record from a source-tree import. */+export async function upsertImportedRecord(id, input) {+ const now = new Date().toISOString();+ const imported = buildSpriteRecord(input, { id, now });+ const all = await loadAll();+ const idx = all.findIndex((r) => r.id === id);+ const next = mergeImportedRecord(idx >= 0 ? all[idx] : null, imported, now);+ if (idx >= 0) all[idx] = next; else all.push(next);+ await saveAll(all);+ return next;+}diff --git a/server/services/sprites/recordsFile.test.js b/server/services/sprites/recordsFile.test.jsnew file mode 100644index 0000000000..4468936cf6--- /dev/null+++ b/server/services/sprites/recordsFile.test.js@@ -0,0 +1,58 @@+/**+ * Sprites file-backend round-trip (#2895). Runs against a tmpdir in the normal+ * (non-DB) suite — covers create/list/get/update/delete + the importer upsert,+ * without touching real `data/` or needing Postgres. The PG backend shares the+ * same recordsLogic decisions, so its row I/O mirrors this.+ */++import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';+import { mkdtempSync, rmSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'sprite-records-file-test-'));++vi.mock('../../lib/fileUtils.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT } };+});++const file = await import('./recordsFile.js');++beforeEach(() => rmSync(join(TEST_DATA_ROOT, 'sprite-records.json'), { force: true }));+afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));++describe('recordsFile backend', () => {+ it('creates, lists, gets, updates, soft-deletes', async () => {+ const created = await file.createRecord({ kind: 'character', name: 'Hero' }, 'hero');+ expect(created.id).toBe('hero');+ expect(await file.listRecords()).toHaveLength(1);++ const updated = await file.updateRecord('hero', { notes: 'n1' });+ expect(updated.notes).toBe('n1');++ await file.deleteRecord('hero');+ expect(await file.listRecords()).toHaveLength(0);+ expect(await file.getRecord('hero')).toBeNull();+ expect((await file.getRecord('hero', { includeDeleted: true })).deleted).toBe(true);+ });++ it('refuses a duplicate live id', async () => {+ await file.createRecord({ name: 'Hero' }, 'hero');+ await expect(file.createRecord({ name: 'Hero 2' }, 'hero')).rejects.toMatchObject({ code: 'ALREADY_EXISTS' });+ });++ it('upsertImportedRecord creates then refreshes while preserving user fields', async () => {+ const first = await file.upsertImportedRecord('hero', { kind: 'character', name: 'Hero', status: 'imported' });+ expect(first.status).toBe('imported');+ await file.updateRecord('hero', { notes: 'keep me' });++ const second = await file.upsertImportedRecord('hero', {+ kind: 'character', name: 'Hero v2', status: 'imported', spec: { v: 2 },+ });+ expect(second.name).toBe('Hero v2');+ expect(second.spec).toEqual({ v: 2 });+ expect(second.notes).toBe('keep me');+ expect(await file.listRecords()).toHaveLength(1);+ });+});diff --git a/server/services/sprites/recordsLogic.js b/server/services/sprites/recordsLogic.jsnew file mode 100644index 0000000000..2b8bb263a5--- /dev/null+++ b/server/services/sprites/recordsLogic.js@@ -0,0 +1,94 @@+/**+ * Sprites — pure record builders/mutators shared by the DB and file backends+ * (issue #2895, phase 1). Mirrors musicVideo/projectsLogic.js: all mutation+ * semantics live here so the two backends can't drift.+ *+ * A sprite record is the db-primary metadata for one sprite subject — either a+ * `character` (identity reference → anchors → walk animations → atlas) or a+ * `props` family (a fixed-cell atlas of non-character sprites). Binary assets+ * (reference images, strips, atlases, manifests) live on disk under+ * data/sprites/<id>/ — the record holds only metadata and workflow state.+ */++export const SPRITE_RECORD_KINDS = ['character', 'props'];++// Record ids double as the on-disk directory name under data/sprites/ — keep+// them strict kebab-case so a record id can never traverse the filesystem.+export const SPRITE_ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}$/;++export function isValidSpriteId(id) {+ return typeof id === 'string' && SPRITE_ID_PATTERN.test(id);+}++export function mirrorTimestamp(value, fallback) {+ return typeof value === 'string' && value ? value : fallback;+}++const trimOrNull = (v) => (typeof v === 'string' && v.trim() ? v.trim() : null);++export function buildSpriteRecord(input, { id, now }) {+ const kind = SPRITE_RECORD_KINDS.includes(input.kind) ? input.kind : 'character';+ return {+ id,+ kind,+ name: trimOrNull(input.name) || id,+ status: trimOrNull(input.status) || 'draft',+ // Character spec (proportions/materials/appearance) — verbatim from the+ // source pipeline for characters, null for props families.+ spec: input.spec && typeof input.spec === 'object' ? input.spec : null,+ // Matte color used for video keying (per-character, phase 2 makes this+ // dynamic — one of the standard keys #FF00FF / #00FF00 / #0000FF).+ chromaKey: trimOrNull(input.chromaKey),+ // Publish binding ({ appId, atlasDestPath, codeBinding? }) — configured in+ // phase 4; imported records start unbound.+ publishBinding: input.publishBinding && typeof input.publishBinding === 'object'+ ? input.publishBinding+ : null,+ importedFrom: input.importedFrom && typeof input.importedFrom === 'object'+ ? input.importedFrom+ : null,+ notes: trimOrNull(input.notes),+ createdAt: now,+ updatedAt: now,+ deleted: false,+ deletedAt: null,+ };+}++// Whitelist patch — key-absent preserves, key-present applies (including an+// intentional clear via null/''), per the LLM/merge convention in CLAUDE.md.+const PATCHABLE = ['name', 'status', 'spec', 'chromaKey', 'publishBinding', 'notes'];++export function applySpriteRecordPatch(record, patch) {+ const next = { ...record };+ for (const key of PATCHABLE) {+ if (!(key in patch)) continue;+ if (key === 'name') next.name = trimOrNull(patch.name) || record.name;+ else if (key === 'status') next.status = trimOrNull(patch.status) || record.status;+ else if (key === 'spec' || key === 'publishBinding') {+ next[key] = patch[key] && typeof patch[key] === 'object' ? patch[key] : null;+ } else next[key] = trimOrNull(patch[key]);+ }+ next.updatedAt = new Date().toISOString();+ return next;+}++/**+ * Merge a fresh import over an existing record: import metadata wins for the+ * source-derived fields (kind/spec/importedFrom), but user-managed fields the+ * importer doesn't know about (publishBinding, notes, a manually-set+ * chromaKey) survive a re-import.+ */+export function mergeImportedRecord(existing, imported, now) {+ if (!existing || existing.deleted) return { ...imported, createdAt: imported.createdAt || now, updatedAt: now };+ return {+ ...existing,+ kind: imported.kind,+ name: imported.name,+ status: imported.status,+ spec: imported.spec,+ chromaKey: existing.chromaKey || imported.chromaKey,+ importedFrom: imported.importedFrom,+ updatedAt: now,+ };+}diff --git a/server/services/sprites/recordsLogic.test.js b/server/services/sprites/recordsLogic.test.jsnew file mode 100644index 0000000000..9df71a4155--- /dev/null+++ b/server/services/sprites/recordsLogic.test.js@@ -0,0 +1,89 @@+import { describe, it, expect } from 'vitest';+import {+ buildSpriteRecord,+ applySpriteRecordPatch,+ mergeImportedRecord,+ isValidSpriteId,+} from './recordsLogic.js';++const NOW = '2026-07-22T00:00:00.000Z';++describe('isValidSpriteId', () => {+ it('accepts kebab-case slugs', () => {+ expect(isValidSpriteId('pioneer')).toBe(true);+ expect(isValidSpriteId('landing-kit')).toBe(true);+ });++ it('rejects traversal-capable and malformed ids', () => {+ for (const bad of ['../etc', 'a/b', 'UPPER', '', '-lead', null, 'a'.repeat(65)]) {+ expect(isValidSpriteId(bad)).toBe(false);+ }+ });+});++describe('buildSpriteRecord', () => {+ it('defaults kind/status and falls back name to the id', () => {+ const r = buildSpriteRecord({}, { id: 'hero', now: NOW });+ expect(r).toMatchObject({ id: 'hero', kind: 'character', name: 'hero', status: 'draft', deleted: false });+ expect(r.createdAt).toBe(NOW);+ });++ it('keeps spec/chromaKey/importedFrom when provided', () => {+ const spec = { characterId: 'hero', archetype: 'adult-humanoid-v1' };+ const r = buildSpriteRecord(+ { kind: 'props', name: ' Flora ', status: 'imported', spec, chromaKey: '#FF00FF', importedFrom: { sourceRoot: '/x' } },+ { id: 'flora', now: NOW },+ );+ expect(r.kind).toBe('props');+ expect(r.name).toBe('Flora');+ expect(r.spec).toBe(spec);+ expect(r.chromaKey).toBe('#FF00FF');+ expect(r.importedFrom.sourceRoot).toBe('/x');+ });+});++describe('applySpriteRecordPatch', () => {+ const base = buildSpriteRecord({ name: 'Hero', chromaKey: '#FF00FF' }, { id: 'hero', now: NOW });++ it('key-absent preserves; key-present applies (including a clear)', () => {+ const next = applySpriteRecordPatch(base, { notes: 'walk set locked', chromaKey: null });+ expect(next.name).toBe('Hero');+ expect(next.notes).toBe('walk set locked');+ expect(next.chromaKey).toBeNull();+ expect(next.updatedAt).not.toBe(base.updatedAt);+ });++ it('ignores keys outside the whitelist', () => {+ const next = applySpriteRecordPatch(base, { id: 'evil', deleted: true });+ expect(next.id).toBe('hero');+ expect(next.deleted).toBe(false);+ });+});++describe('mergeImportedRecord', () => {+ const existing = {+ ...buildSpriteRecord({ name: 'Hero', chromaKey: '#00FF00' }, { id: 'hero', now: NOW }),+ notes: 'user note',+ publishBinding: { appId: 'my-game' },+ };+ const imported = buildSpriteRecord(+ { name: 'Hero v2', status: 'imported', spec: { a: 1 }, chromaKey: '#FF00FF', importedFrom: { sourceRoot: '/y' } },+ { id: 'hero', now: '2026-07-23T00:00:00.000Z' },+ );++ it('refreshes source-derived fields but keeps user-managed ones', () => {+ const next = mergeImportedRecord(existing, imported, '2026-07-23T00:00:00.000Z');+ expect(next.name).toBe('Hero v2');+ expect(next.spec).toEqual({ a: 1 });+ expect(next.notes).toBe('user note');+ expect(next.publishBinding).toEqual({ appId: 'my-game' });+ expect(next.chromaKey).toBe('#00FF00'); // manually-set key survives re-import+ expect(next.createdAt).toBe(NOW);+ });++ it('uses the imported record wholesale when nothing exists', () => {+ const next = mergeImportedRecord(null, imported, '2026-07-23T00:00:00.000Z');+ expect(next.chromaKey).toBe('#FF00FF');+ expect(next.notes).toBeNull();+ });+});