Skip to content

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

feat([issue-2896]): sprite reference workflow — character create, main-reference freeze, 8 directional anchors, dynamic chroma-key selection

[._.]/ Adam Eivy67ebdfb25979
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index f963f0f88d..10fb96ce29 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,7 @@
## Sprite Manager
+- **[issue-2896] Create characters and build their reference sets with AI (phase 2)** — the Sprites tab can now create a character from a name plus a text description and/or an uploaded design image, generate main-reference candidates through your configured image backend (Codex, Grok, or local), and freeze the approved candidate as the character's immutable identity root. From the frozen main you then derive the 8 directional anchors (front/back/profiles/three-quarters), review each candidate, and lock the set. On lock, PortOS normalizes the art onto a clean key-color square and auto-picks the best chroma key for that character — magenta, green, or blue, whichever sits farthest from the character's own colors (with a manual override limited to the same three keys, and a warning when every key risks clipping). Locked references are server-side immutable: regeneration and replacement are refused, corrections always land as new versions.
- **[issue-2895] Media Gen gains a Sprites section (phase 1: library + import)** — a new Sprites tab lists your game-sprite characters and prop atlas families, browses each one's locked reference set, walk-cycle strips, and published atlas versions (with pixel-perfect previews), and imports the approved production assets from an existing sprite-pipeline checkout in one click. Only final/approved artifacts import — rejected candidates and raw video intermediates stay behind — and every file the source manifests hash-pin is verified on the way in. Reachable from ⌘K and voice ("take me to sprites"). Generation (reference → anchors → walk videos → publish-to-game) lands in the follow-up phases.
## Image generation
diff --git a/client/src/components/sprites/ReferenceWorkflow.jsx b/client/src/components/sprites/ReferenceWorkflow.jsx
new file mode 100644
index 0000000000..f2dc2fec78
--- /dev/null
+++ b/client/src/components/sprites/ReferenceWorkflow.jsx
@@ -0,0 +1,284 @@
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { Lock, Sparkles, RefreshCw, Upload } from 'lucide-react';
+import toast from '../ui/Toast';
+import { generateSpriteReference, lockSpriteReference, updateSpriteRecord } from '../../services/apiSprites.js';
+import { getMediaJob } from '../../services/apiMediaJobs.js';
+import { getSettings } from '../../services/apiSystem.js';
+import { deriveAvailableBackends } from '../../lib/imageGenBackends.js';
+
+// Reference workflow (issue #2896): generate main-reference candidates from
+// text + optional uploaded design image, freeze the approved main, then
+// derive + lock the 8 directional anchors. The manifest (server-owned) is the
+// source of truth for status; this component only renders it and fires the
+// generate/lock/override actions.
+
+const CHROMA_KEYS = ['#FF00FF', '#00FF00', '#0000FF'];
+
+const assetUrl = (recordId, relPath) => `/data/sprites/${encodeURIComponent(recordId)}/${relPath.split('/').map(encodeURIComponent).join('/')}`;
+
+function SpriteImg({ recordId, path, className }) {
+ return (
+ <img
+ src={assetUrl(recordId, path)}
+ alt={path}
+ loading="lazy"
+ className={className}
+ style={{ imageRendering: 'pixelated' }}
+ />
+ );
+}
+
+// Candidate thumbnail with an inline lock confirm (locking is irreversible —
+// per the repo's confirmation UX convention this is an inline confirm row,
+// not a browser dialog or a hidden two-click arm).
+function CandidateTile({ recordId, candidate, locking, onLock }) {
+ const [confirming, setConfirming] = useState(false);
+ return (
+ <div className="bg-port-bg border border-port-border rounded p-1 space-y-1">
+ <SpriteImg recordId={recordId} path={candidate.path} className="w-full h-24 object-contain" />
+ <p className="text-[10px] text-gray-500 truncate" title={candidate.path}>
+ {candidate.path.split('/').pop()}{candidate.mode ? ` · ${candidate.mode}` : ''}
+ </p>
+ {confirming ? (
+ <div className="flex items-center gap-1 text-xs">
+ <span className="text-port-warning">Freeze forever?</span>
+ <button onClick={() => { setConfirming(false); onLock(candidate); }} className="px-1.5 py-0.5 bg-port-accent text-white rounded">Lock</button>
+ <button onClick={() => setConfirming(false)} className="px-1.5 py-0.5 text-gray-400 hover:text-white">Cancel</button>
+ </div>
+ ) : (
+ <button
+ onClick={() => setConfirming(true)}
+ disabled={locking}
+ className="flex items-center gap-1 w-full justify-center px-1.5 py-0.5 text-xs bg-port-card border border-port-border rounded text-gray-300 hover:border-port-accent disabled:opacity-50"
+ >
+ <Lock className="w-3 h-3" /> Lock
+ </button>
+ )}
+ </div>
+ );
+}
+
+export default function ReferenceWorkflow({ record, reference, onChanged }) {
+ const recordId = record.id;
+ const manifest = reference?.manifest || null;
+ const candidates = reference?.candidates || [];
+ const mainLocked = manifest?.mainReference?.locked === true;
+
+ const [backends, setBackends] = useState([]);
+ const [mode, setMode] = useState('');
+ const [designPrompt, setDesignPrompt] = useState(manifest?.designPrompt || '');
+ const [uploadFile, setUploadFile] = useState(null);
+ // target → jobId for in-flight renders; polled until the candidate lands.
+ const [pendingJobs, setPendingJobs] = useState({});
+ const [locking, setLocking] = useState(false);
+ const [keySaving, setKeySaving] = useState(false);
+ const fileInputRef = useRef(null);
+
+ useEffect(() => {
+ getSettings({ silent: true })
+ .then((settings) => {
+ const available = deriveAvailableBackends(settings, { excludeExternal: true });
+ setBackends(available);
+ setMode((m) => m || available[0]?.id || '');
+ })
+ .catch(() => setBackends([]));
+ }, []);
+
+ // Poll in-flight render jobs; on a terminal state drop the entry and
+ // refresh the detail so the new candidate (or the failure) shows up.
+ useEffect(() => {
+ const jobIds = Object.values(pendingJobs);
+ if (jobIds.length === 0) return undefined;
+ const timer = setInterval(async () => {
+ for (const [target, jobId] of Object.entries(pendingJobs)) {
+ const job = await getMediaJob(jobId).catch(() => null);
+ if (!job || ['completed', 'failed', 'canceled'].includes(job.status)) {
+ setPendingJobs((prev) => {
+ const next = { ...prev };
+ delete next[target];
+ return next;
+ });
+ if (job?.status === 'failed') toast.error(`Render failed for ${target}: ${job.error || 'see media jobs'}`);
+ // Completed candidates land server-side via the completion hook —
+ // small delay so the copy is on disk before the refetch.
+ setTimeout(onChanged, 500);
+ }
+ }
+ }, 4000);
+ return () => clearInterval(timer);
+ }, [pendingJobs, onChanged]);
+
+ const candidatesByTarget = useMemo(() => candidates.reduce((acc, c) => {
+ const t = c.target || 'main';
+ (acc[t] ||= []).push(c);
+ return acc;
+ }, {}), [candidates]);
+
+ const generate = async (target) => {
+ try {
+ const { jobId } = await generateSpriteReference(recordId, {
+ target,
+ ...(mode ? { mode } : {}),
+ ...(target === 'main' ? { designPrompt, referenceImageFile: uploadFile || undefined } : {}),
+ }, { silent: true });
+ setPendingJobs((prev) => ({ ...prev, [target]: jobId }));
+ setUploadFile(null);
+ if (fileInputRef.current) fileInputRef.current.value = '';
+ } catch (err) {
+ toast.error(err?.message || `Failed to queue ${target} render`);
+ }
+ };
+
+ const lock = async (target, candidate) => {
+ setLocking(true);
+ try {
+ await lockSpriteReference(recordId, { target, candidate: candidate.path }, { silent: true });
+ toast.success(target === 'main' ? 'Main reference frozen' : `Anchor ${target} locked`);
+ onChanged();
+ } catch (err) {
+ toast.error(err?.message || 'Lock failed');
+ } finally {
+ setLocking(false);
+ }
+ };
+
+ const setChromaKey = async (hex) => {
+ setKeySaving(true);
+ try {
+ await updateSpriteRecord(recordId, { chromaKey: hex }, { silent: true });
+ onChanged();
+ } catch (err) {
+ toast.error(err?.message || 'Failed to set chroma key');
+ } finally {
+ setKeySaving(false);
+ }
+ };
+
+ const modePicker = backends.length > 0 && (
+ <label className="flex items-center gap-2 text-xs text-gray-400">
+ Backend
+ <select
+ value={mode}
+ onChange={(e) => setMode(e.target.value)}
+ className="bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-white"
+ >
+ {backends.map((b) => <option key={b.id} value={b.id}>{b.label || b.id}</option>)}
+ </select>
+ </label>
+ );
+
+ return (
+ <div className="bg-port-card border border-port-border rounded-lg p-4 space-y-4">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <h3 className="text-sm font-semibold text-white flex items-center gap-1.5">
+ <Sparkles className="w-4 h-4" /> Reference Set
+ <span className="text-xs font-normal text-gray-500">{manifest?.status || 'not started'}</span>
+ </h3>
+ <div className="flex items-center gap-1.5" title="Chroma key — auto-selected at main lock; override is limited to the three standard keys">
+ <span className="text-xs text-gray-500">key</span>
+ {CHROMA_KEYS.map((hex) => (
+ <button
+ key={hex}
+ onClick={() => setChromaKey(hex)}
+ disabled={keySaving}
+ aria-label={`Set chroma key ${hex}`}
+ className={`w-5 h-5 rounded-sm border ${record.chromaKey === hex ? 'border-white ring-1 ring-port-accent' : 'border-port-border opacity-60 hover:opacity-100'}`}
+ style={{ backgroundColor: hex }}
+ />
+ ))}
+ </div>
+ </div>
+ {manifest?.chromaKeyWarning && (
+ <p className="text-xs text-port-warning">{manifest.chromaKeyWarning}</p>
+ )}
+
+ {/* Main reference — the immutable identity root */}
+ <div className="space-y-2">
+ <h4 className="text-xs uppercase tracking-wide text-gray-500">Main reference (walk-south)</h4>
+ {mainLocked ? (
+ <div className="flex items-start gap-3">
+ <SpriteImg recordId={recordId} path={manifest.mainReference.path} className="w-32 h-32 object-contain bg-port-bg border border-port-border rounded" />
+ <p className="text-xs text-gray-500 flex items-center gap-1"><Lock className="w-3 h-3" /> frozen · immutable root</p>
+ </div>
+ ) : (
+ <div className="space-y-2">
+ <textarea
+ value={designPrompt}
+ onChange={(e) => setDesignPrompt(e.target.value)}
+ placeholder="Describe the character (or attach a design reference image)…"
+ rows={2}
+ className="w-full bg-port-bg border border-port-border rounded px-3 py-1.5 text-sm text-white"
+ />
+ <div className="flex flex-wrap items-center gap-3">
+ <label className="flex items-center gap-1.5 text-xs text-gray-400 cursor-pointer">
+ <Upload className="w-3.5 h-3.5" />
+ {uploadFile ? uploadFile.name : 'Design image (optional)'}
+ <input
+ ref={fileInputRef}
+ type="file"
+ accept="image/png,image/jpeg,image/webp"
+ className="hidden"
+ onChange={(e) => setUploadFile(e.target.files?.[0] || null)}
+ />
+ </label>
+ {modePicker}
+ <button
+ onClick={() => generate('main')}
+ disabled={!!pendingJobs.main || (!designPrompt.trim() && !uploadFile)}
+ className="flex items-center gap-1.5 px-3 py-1 bg-port-accent hover:bg-blue-600 disabled:opacity-50 text-white rounded text-sm"
+ >
+ {pendingJobs.main ? <RefreshCw className="w-3.5 h-3.5 animate-spin" /> : <Sparkles className="w-3.5 h-3.5" />}
+ {pendingJobs.main ? 'Rendering…' : 'Generate candidate'}
+ </button>
+ </div>
+ {(candidatesByTarget.main || []).length > 0 && (
+ <div className="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-6 gap-2">
+ {candidatesByTarget.main.map((c) => (
+ <CandidateTile key={c.path} recordId={recordId} candidate={c} locking={locking} onLock={(cand) => lock('main', cand)} />
+ ))}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+
+ {/* Directional anchors — derive from the frozen main */}
+ {mainLocked && (
+ <div className="space-y-2">
+ <div className="flex items-center gap-3">
+ <h4 className="text-xs uppercase tracking-wide text-gray-500">Directional anchors</h4>
+ {modePicker}
+ </div>
+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
+ {manifest.anchors.map((anchor) => (
+ <div key={anchor.id} className="bg-port-bg border border-port-border rounded p-2 space-y-1.5">
+ <p className="text-xs text-gray-400 flex items-center justify-between">
+ {anchor.direction}
+ {anchor.status === 'locked' && <Lock className="w-3 h-3 text-port-success" />}
+ </p>
+ {anchor.status === 'locked' ? (
+ <SpriteImg recordId={recordId} path={anchor.path} className="w-full h-24 object-contain" />
+ ) : (
+ <div className="space-y-1.5">
+ <button
+ onClick={() => generate(anchor.direction)}
+ disabled={!!pendingJobs[anchor.direction]}
+ className="flex items-center gap-1 w-full justify-center px-2 py-1 text-xs bg-port-card border border-port-border rounded text-gray-300 hover:border-port-accent disabled:opacity-50"
+ >
+ {pendingJobs[anchor.direction]
+ ? <><RefreshCw className="w-3 h-3 animate-spin" /> Rendering…</>
+ : <><Sparkles className="w-3 h-3" /> Generate</>}
+ </button>
+ {(candidatesByTarget[anchor.direction] || []).map((c) => (
+ <CandidateTile key={c.path} recordId={recordId} candidate={c} locking={locking} onLock={(cand) => lock(anchor.direction, cand)} />
+ ))}
+ </div>
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/pages/Sprites.jsx b/client/src/pages/Sprites.jsx
index 931330a8d3..d0ca6a78aa 100644
--- a/client/src/pages/Sprites.jsx
+++ b/client/src/pages/Sprites.jsx
@@ -1,15 +1,17 @@
import { useEffect, useState, useCallback, useMemo } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
-import { PersonStanding, Package, Download, FolderOpen, X, RefreshCw } from 'lucide-react';
+import { PersonStanding, Package, Download, FolderOpen, X, RefreshCw, Plus } from 'lucide-react';
import toast from '../components/ui/Toast';
-import { listSpriteRecords, getSpriteRecord, importSprites } from '../services/apiSprites.js';
+import { listSpriteRecords, getSpriteRecord, importSprites, createSpriteRecord } from '../services/apiSprites.js';
+import ReferenceWorkflow from '../components/sprites/ReferenceWorkflow.jsx';
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.
+// Sprite Manager: library over imported production sprites — characters
+// (reference sets, walk strips, runtime atlases) and props atlas families —
+// plus the source-tree importer (#2895) and the phase-2 reference workflow
+// (create a character, generate + freeze the main reference, derive + lock
+// the 8 directional anchors — #2896). Animation and publish land in later
+// phases.
const IMAGE_EXT = /\.(png|gif|webp|jpe?g)$/i;
@@ -107,6 +109,68 @@ function ImportPanel({ onImported }) {
);
}
+function NewCharacterPanel({ onCreated }) {
+ const [open, setOpen] = useState(false);
+ const [name, setName] = useState('');
+ const [creating, setCreating] = useState(false);
+
+ const create = async () => {
+ setCreating(true);
+ try {
+ const record = await createSpriteRecord({ name: name.trim() });
+ setOpen(false);
+ setName('');
+ onCreated(record);
+ } catch {
+ // request() already toasted — keep the panel open for a retry.
+ } finally {
+ setCreating(false);
+ }
+ };
+
+ if (!open) {
+ return (
+ <button
+ onClick={() => setOpen(true)}
+ className="flex items-center gap-2 px-3 py-1.5 bg-port-card border border-port-border hover:border-port-accent text-gray-300 rounded text-sm"
+ >
+ <Plus className="w-4 h-4" /> New Character
+ </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">New character</h3>
+ <button onClick={() => setOpen(false)} aria-label="Close new character panel" className="text-gray-400 hover:text-white">
+ <X className="w-4 h-4" />
+ </button>
+ </div>
+ <div>
+ <label htmlFor="sprite-new-name" className="block text-xs text-gray-400 mb-1">Name</label>
+ <input
+ id="sprite-new-name"
+ type="text"
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ onKeyDown={(e) => { if (e.key === 'Enter' && name.trim()) create(); }}
+ placeholder="Trail Hand"
+ className="w-full bg-port-bg border border-port-border rounded px-3 py-1.5 text-sm text-white"
+ />
+ </div>
+ <button
+ onClick={create}
+ disabled={creating || !name.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"
+ >
+ {creating ? <RefreshCw className="w-4 h-4 animate-spin" /> : <Plus className="w-4 h-4" />}
+ Create
+ </button>
+ </div>
+ );
+}
+
function RecordSection({ title, icon: Icon, items, selectedId, onSelect }) {
if (items.length === 0) return null;
return (
@@ -234,6 +298,7 @@ export default function Sprites() {
return (
<div className="flex flex-col md:flex-row gap-4 h-full">
<aside className="md:w-64 shrink-0 space-y-3">
+ <NewCharacterPanel onCreated={(record) => { refresh(); navigate(`/media/sprites/${record.id}`); }} />
{/* Re-import while a sprite is open must refresh the open detail too,
not just the sidebar list. */}
<ImportPanel onImported={() => { refresh(); if (id) setRetryTick((t) => t + 1); }} />
@@ -284,6 +349,13 @@ export default function Sprites() {
<p className="text-xs text-gray-500">archetype: {detail.record.spec.archetype}</p>
)}
</div>
+ {detail.record.kind === 'character' && (
+ <ReferenceWorkflow
+ record={detail.record}
+ reference={detail.reference}
+ onChanged={() => { refresh(); setRetryTick((t) => t + 1); }}
+ />
+ )}
{detail.assets.length === 0 ? (
<p className="text-sm text-gray-500">No assets on disk for this record.</p>
) : (
diff --git a/client/src/services/README.md b/client/src/services/README.md
index 7a654bc702..8dfafd9bab 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). |
+| `apiSprites.js` | Sprite Manager records, asset library, production-set import (#2895), reference workflow: create/generate/lock (#2896). |
| `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/apiSprites.js b/client/src/services/apiSprites.js
index 9c9f48d36b..651b9efcca 100644
--- a/client/src/services/apiSprites.js
+++ b/client/src/services/apiSprites.js
@@ -1,15 +1,47 @@
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.
+// Sprite Manager: record list/detail + production-asset import (#2895), and
+// the phase-2 reference workflow — create characters, queue main/anchor
+// candidate renders, lock reviewed candidates (#2896). `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 createSpriteRecord = (body, options = {}) => request('/sprites', {
+ method: 'POST', body: JSON.stringify(body), ...options,
+});
+
+export const updateSpriteRecord = (id, patch, options = {}) => request(`/sprites/${encodeURIComponent(id)}`, {
+ method: 'PATCH', body: JSON.stringify(patch), ...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,
});
+
+// Queue one reference candidate render. `referenceImageFile` (main target
+// only) switches the POST to multipart so the design reference uploads with
+// the fields. Returns { jobId, mode, target, anchorId }.
+export const generateSpriteReference = (id, { referenceImageFile, ...fields }, options = {}) => {
+ let body;
+ if (referenceImageFile) {
+ body = new FormData();
+ for (const [key, value] of Object.entries(fields)) {
+ if (value !== undefined && value !== null && value !== '') body.append(key, value);
+ }
+ body.append('referenceImage', referenceImageFile);
+ } else {
+ body = JSON.stringify(fields);
+ }
+ return request(`/sprites/${encodeURIComponent(id)}/reference/generate`, { method: 'POST', body, ...options });
+};
+
+// Freeze a reviewed candidate as the main reference or a directional anchor.
+// Returns the updated { manifest, candidates } reference set.
+export const lockSpriteReference = (id, body, options = {}) => request(`/sprites/${encodeURIComponent(id)}/reference/lock`, {
+ method: 'POST', body: JSON.stringify(body), ...options,
+});
diff --git a/server/index.js b/server/index.js
index 41534c6b68..8214211082 100644
--- a/server/index.js
+++ b/server/index.js
@@ -135,6 +135,7 @@ import { initUniverseBuilderCollectionHook } from './services/universeBuilderCol
import { initCatalogImageAttachHook } from './services/catalogImageAttachHook.js';
import { initWritersRoomSceneImageHook } from './services/writersRoomSceneImageHook.js';
import { initMusicVideoSceneImageHook } from './services/musicVideoSceneImageHook.js';
+import { initSpriteReferenceImageHook } from './services/spriteReferenceImageHook.js';
import { initMusicVideoSceneVideoHook } from './services/musicVideoSceneVideoHook.js';
import { initCreativeDirectorMusicBedHook } from './services/creativeDirectorMusicBedHook.js';
import { initCreativeDirectorSceneImageHook } from './services/creativeDirectorSceneImageHook.js';
@@ -862,6 +863,10 @@ ensureSelf()
// the requesting client unmounted mid-render (#1928). Also depends on the
// queue being loaded.
initCreativeDirectorMusicBedHook();
+ // Sprite reference-candidate hook — copies a completed reference/anchor
+ // render into the sprite record's reference/candidates/ with a generation
+ // sidecar (#2896). Also depends on the queue being loaded.
+ initSpriteReferenceImageHook();
// Creative Director scene-frame hook — durably files a queued first-pass
// reference-frame render onto its project scene's `sourceImageFile` on
// completion, even if no client is watching (#1867). Also depends on the
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 51105a2f2a..04df173d9f 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -3,6 +3,9 @@ import { ServerError } from './errorHandler.js';
import { partialWithoutDefaults, emptyToUndefined, emptyToNull } from './zodCompat.js';
import { WORK_TRACKERS } from './workTracker.js';
import { SPRITE_ID_PATTERN } from '../services/sprites/recordsLogic.js';
+import { ANCHOR_DIRECTIONS } from '../services/sprites/prompts.js';
+import { CHROMA_KEY_HEXES } from '../services/sprites/chromaKey.js';
+import { QUEUEABLE_IMAGE_MODES } from '../services/imageGen/modes.js';
// gpt-image-2 (codex backend) caps at 3840px per edge and 8,294,400 total
// pixels. Mirror the ceiling for every image-gen route. Local mflux can
@@ -953,9 +956,44 @@ export const spriteImportRequestSchema = z.object({
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(),
+ // Fixed three-key set (#2895 decision) — manual override is limited to the
+ // same keys the auto-selection picks from. Imported legacy records keep
+ // whatever hex they carried (the importer writes via upsert, not this
+ // schema); null clears back to auto-select-on-lock.
+ chromaKey: z.enum(CHROMA_KEY_HEXES).nullable().optional(),
+});
+
+// Phase 2 (issue #2896): reference workflow. prompts.js / chromaKey.js are
+// pure sprite modules (like recordsLogic.js) so importing their constants
+// here can't disturb mocked suites; modes.js is the dependency-free image-gen
+// enum module.
+export const spriteCreateSchema = z.object({
+ id: z.string().regex(SPRITE_ID_PATTERN).optional(),
+ name: z.string().trim().min(1).max(200),
+ spec: z.record(z.string(), z.unknown()).nullable().optional(),
+});
+
+const spriteReferenceTargetSchema = z.enum(['main', ...ANCHOR_DIRECTIONS]);
+
+// Multipart callers send numbers as form-field strings — coerce before range
+// checks ('' → undefined so an empty field doesn't become 0).
+const optionalUnitNumber = z.preprocess(
+ (v) => (v === '' || v === undefined || v === null ? undefined : Number(v)),
+ z.number().min(0).max(1).optional(),
+);
+
+export const spriteReferenceGenerateSchema = z.object({
+ target: spriteReferenceTargetSchema,
+ mode: z.enum(QUEUEABLE_IMAGE_MODES).optional(),
+ model: z.string().trim().max(64).optional(),
+ effort: z.string().trim().max(32).optional(),
+ designPrompt: z.string().max(4000).optional(),
+ initImageStrength: optionalUnitNumber,
+});
+
+export const spriteReferenceLockSchema = z.object({
+ target: spriteReferenceTargetSchema,
+ candidate: z.string().min(1).max(500),
});
// =============================================================================
diff --git a/server/routes/sprites.js b/server/routes/sprites.js
index 76b126a366..86f4488896 100644
--- a/server/routes/sprites.js
+++ b/server/routes/sprites.js
@@ -1,29 +1,60 @@
/**
- * Sprites Routes — REST surface for the Sprite Manager (issue #2895, phase 1).
+ * Sprites Routes — REST surface for the Sprite Manager.
*
- * 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.
+ * Phase 1 (#2895): library list/get, source-tree importer, record patch.
+ * Phase 2 (#2896): character create + the reference workflow — generate
+ * main/anchor candidates through the shared image-gen queue, review, then
+ * lock (normalize + dynamic chroma-key selection). Generation is strictly
+ * user-triggered per the AI-provider policy; locked artifacts are immutable
+ * (409 on regenerate/relock).
*/
import { Router } from 'express';
+import { unlink } from 'fs/promises';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import {
validateRequest,
spriteImportRequestSchema,
spriteRecordUpdateSchema,
+ spriteCreateSchema,
+ spriteReferenceGenerateSchema,
+ spriteReferenceLockSchema,
} from '../lib/validation.js';
-import { listRecords, getRecordWithAssets, updateRecord, deleteRecord } from '../services/sprites/records.js';
+import { optionalUploadFields } from '../lib/multipart.js';
+import {
+ listRecords, getRecordWithAssets, createRecord, updateRecord, deleteRecord,
+} from '../services/sprites/records.js';
import { importFromSource } from '../services/sprites/importer.js';
+import { getReferenceSet, startReferenceGeneration, lockReference } from '../services/sprites/reference.js';
+import { SPRITE_ID_PATTERN } from '../services/sprites/recordsLogic.js';
const router = Router();
+const MAX_REFERENCE_UPLOAD_BYTES = 20 * 1024 * 1024;
+const ACCEPTED_REFERENCE_MIME = new Set(['image/png', 'image/jpeg', 'image/webp']);
+
+const referenceUpload = optionalUploadFields(['referenceImage'], {
+ limits: { fileSize: MAX_REFERENCE_UPLOAD_BYTES },
+ fileFilter: (file) => ACCEPTED_REFERENCE_MIME.has(file.mimetype),
+});
+
+const slugify = (name) => name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 64);
+
router.get('/', asyncHandler(async (_req, res) => {
res.json(await listRecords());
}));
+// Create a character record — the entry point of the reference workflow.
+// Props families remain import-only.
+router.post('/', asyncHandler(async (req, res) => {
+ const input = validateRequest(spriteCreateSchema, req.body);
+ const id = input.id || slugify(input.name);
+ if (!SPRITE_ID_PATTERN.test(id)) {
+ throw new ServerError(`Cannot derive a valid sprite id from "${input.name}" — pass an explicit id`, { status: 400, code: 'INVALID_SPRITE_ID' });
+ }
+ res.status(201).json(await createRecord({ kind: 'character', name: input.name, spec: input.spec ?? null }, id));
+}));
+
// 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.
@@ -35,7 +66,32 @@ router.post('/import', asyncHandler(async (req, res) => {
router.get('/:id', asyncHandler(async (req, res) => {
const detail = await getRecordWithAssets(req.params.id);
if (!detail) throw new ServerError('Sprite record not found', { status: 404, code: 'NOT_FOUND' });
- res.json(detail);
+ const reference = detail.record.kind === 'character' ? await getReferenceSet(req.params.id) : null;
+ res.json({ ...detail, reference });
+}));
+
+// Queue one reference candidate render (main or a directional anchor).
+// Accepts JSON, or multipart with an optional `referenceImage` file for the
+// main target (an uploaded visual design reference → i2i).
+router.post('/:id/reference/generate', referenceUpload, asyncHandler(async (req, res) => {
+ const body = validateRequest(spriteReferenceGenerateSchema, req.body ?? {});
+ const file = req.files?.referenceImage;
+ const upload = file ? { tempPath: file.path, originalname: file.originalname } : null;
+ // Sweep the staged temp file whenever the request ends without the service
+ // having consumed it (validation failure, locked target, etc). The service
+ // moves it on success, so this unlink is a harmless ENOENT there.
+ if (upload) res.on('close', () => { unlink(upload.tempPath).catch(() => {}); });
+ if (upload && body.target !== 'main') {
+ throw new ServerError('Reference image uploads apply to the main target only — anchors always derive from the locked main', { status: 400, code: 'UPLOAD_MAIN_ONLY' });
+ }
+ res.json(await startReferenceGeneration(req.params.id, body, upload));
+}));
+
+// Lock a reviewed candidate: normalize onto the canonical key-color square
+// and freeze it in the reference-set manifest. 409 when already locked.
+router.post('/:id/reference/lock', asyncHandler(async (req, res) => {
+ const body = validateRequest(spriteReferenceLockSchema, req.body);
+ res.json(await lockReference(req.params.id, body));
}));
router.patch('/:id', asyncHandler(async (req, res) => {
diff --git a/server/routes/sprites.test.js b/server/routes/sprites.test.js
index c117f8b843..84f8eab78c 100644
--- a/server/routes/sprites.test.js
+++ b/server/routes/sprites.test.js
@@ -5,6 +5,7 @@ import { request } from '../lib/testHelper.js';
vi.mock('../services/sprites/records.js', () => ({
listRecords: vi.fn(async () => [{ id: 'pioneer', kind: 'character', name: 'Pioneer' }]),
getRecordWithAssets: vi.fn(),
+ createRecord: vi.fn(async (input, id) => ({ id, ...input })),
updateRecord: vi.fn(async (id, patch) => ({ id, ...patch })),
deleteRecord: vi.fn(async () => ({ ok: true })),
}));
@@ -13,8 +14,15 @@ vi.mock('../services/sprites/importer.js', () => ({
importFromSource: vi.fn(async () => ({ results: [], totals: { subjects: 0, files: 0, verified: 0, errors: 0 } })),
}));
+vi.mock('../services/sprites/reference.js', () => ({
+ getReferenceSet: vi.fn(async () => ({ manifest: null, candidates: [] })),
+ startReferenceGeneration: vi.fn(async () => ({ jobId: 'j1', mode: 'codex', target: 'main', anchorId: 'walk-south' })),
+ lockReference: vi.fn(async () => ({ manifest: { status: 'in-progress' }, candidates: [] })),
+}));
+
import * as records from '../services/sprites/records.js';
import * as importer from '../services/sprites/importer.js';
+import * as reference from '../services/sprites/reference.js';
import { errorMiddleware } from '../lib/errorHandler.js';
import spriteRoutes from './sprites.js';
@@ -36,7 +44,30 @@ describe('sprites routes', () => {
expect(r.body).toEqual([{ id: 'pioneer', kind: 'character', name: 'Pioneer' }]);
});
- it('GET /:id returns record + asset listing', async () => {
+ it('POST / creates a character, slugifying the name into an id', async () => {
+ const r = await request(app).post('/api/sprites').send({ name: 'Trail Hand #2' });
+ expect(r.status).toBe(201);
+ expect(records.createRecord).toHaveBeenCalledWith(
+ { kind: 'character', name: 'Trail Hand #2', spec: null },
+ 'trail-hand-2',
+ );
+ });
+
+ it('POST / honors an explicit id and rejects an invalid one', async () => {
+ await request(app).post('/api/sprites').send({ name: 'Hero', id: 'hero-alt' });
+ expect(records.createRecord).toHaveBeenCalledWith(expect.anything(), 'hero-alt');
+
+ const bad = await request(app).post('/api/sprites').send({ name: 'Hero', id: 'Not A Slug' });
+ expect(bad.status).toBe(400);
+ });
+
+ it('POST / 400s a name that slugifies to nothing', async () => {
+ const r = await request(app).post('/api/sprites').send({ name: '!!!' });
+ expect(r.status).toBe(400);
+ expect(r.body.error).toMatch(/explicit id/);
+ });
+
+ it('GET /:id returns record + assets + reference set for characters', async () => {
records.getRecordWithAssets.mockResolvedValueOnce({
record: { id: 'pioneer', kind: 'character' },
assets: [{ path: 'reference/main.png', size: 10, mtime: 1 }],
@@ -45,7 +76,18 @@ describe('sprites routes', () => {
expect(r.status).toBe(200);
expect(r.body.record.id).toBe('pioneer');
expect(r.body.assets).toHaveLength(1);
- expect(records.getRecordWithAssets).toHaveBeenCalledWith('pioneer');
+ expect(r.body.reference).toEqual({ manifest: null, candidates: [] });
+ expect(reference.getReferenceSet).toHaveBeenCalledWith('pioneer');
+ });
+
+ it('GET /:id skips the reference set for props records', async () => {
+ records.getRecordWithAssets.mockResolvedValueOnce({
+ record: { id: 'crates', kind: 'props' }, assets: [],
+ });
+ const r = await request(app).get('/api/sprites/crates');
+ expect(r.status).toBe(200);
+ expect(r.body.reference).toBeNull();
+ expect(reference.getReferenceSet).not.toHaveBeenCalled();
});
it('GET /:id 404s on an unknown record', async () => {
@@ -67,17 +109,59 @@ describe('sprites routes', () => {
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 });
+ it('POST /:id/reference/generate validates and forwards (JSON, no upload)', async () => {
+ const r = await request(app).post('/api/sprites/pioneer/reference/generate')
+ .send({ target: 'main', designPrompt: 'a ranger', mode: 'codex' });
expect(r.status).toBe(200);
- expect(records.updateRecord).toHaveBeenCalledWith('pioneer', { chromaKey: '#00FF00', notes: null });
+ expect(r.body.jobId).toBe('j1');
+ expect(reference.startReferenceGeneration).toHaveBeenCalledWith(
+ 'pioneer', { target: 'main', designPrompt: 'a ranger', mode: 'codex' }, null,
+ );
+ });
+
+ it('POST /:id/reference/generate rejects south and unknown targets', async () => {
+ for (const target of ['south', 'up', '']) {
+ const r = await request(app).post('/api/sprites/pioneer/reference/generate').send({ target });
+ expect(r.status, target).toBe(400);
+ }
+ expect(reference.startReferenceGeneration).not.toHaveBeenCalled();
});
- it('PATCH /:id rejects a malformed chroma key', async () => {
- const r = await request(app).patch('/api/sprites/pioneer').send({ chromaKey: 'magenta' });
+ it('POST /:id/reference/generate rejects a non-queueable mode', async () => {
+ const r = await request(app).post('/api/sprites/pioneer/reference/generate')
+ .send({ target: 'main', mode: 'external' });
expect(r.status).toBe(400);
});
+ it('POST /:id/reference/lock validates and forwards', async () => {
+ const r = await request(app).post('/api/sprites/pioneer/reference/lock')
+ .send({ target: 'east', candidate: 'reference/candidates/walk-east-candidate-01.png' });
+ expect(r.status).toBe(200);
+ expect(reference.lockReference).toHaveBeenCalledWith(
+ 'pioneer', { target: 'east', candidate: 'reference/candidates/walk-east-candidate-01.png' },
+ );
+ });
+
+ it('POST /:id/reference/lock rejects a missing candidate', async () => {
+ const r = await request(app).post('/api/sprites/pioneer/reference/lock').send({ target: 'east' });
+ expect(r.status).toBe(400);
+ });
+
+ it('PATCH /:id accepts the three standard chroma keys and null', async () => {
+ for (const chromaKey of ['#FF00FF', '#00FF00', '#0000FF', null]) {
+ const r = await request(app).patch('/api/sprites/pioneer').send({ chromaKey });
+ expect(r.status, String(chromaKey)).toBe(200);
+ }
+ });
+
+ it('PATCH /:id rejects hex colors outside the three-key set', async () => {
+ for (const chromaKey of ['#123456', 'magenta', '#ff00ff']) {
+ const r = await request(app).patch('/api/sprites/pioneer').send({ chromaKey });
+ expect(r.status, chromaKey).toBe(400);
+ }
+ expect(records.updateRecord).not.toHaveBeenCalled();
+ });
+
it('DELETE /:id soft-deletes', async () => {
const r = await request(app).delete('/api/sprites/pioneer');
expect(r.status).toBe(200);
diff --git a/server/services/spriteReferenceImageHook.js b/server/services/spriteReferenceImageHook.js
new file mode 100644
index 0000000000..585e1a5483
--- /dev/null
+++ b/server/services/spriteReferenceImageHook.js
@@ -0,0 +1,46 @@
+/**
+ * Sprite reference candidate attach hook (issue #2896, phase 2).
+ *
+ * Subscribes to mediaJobEvents and, for each completed image job carrying
+ * `params.spriteRef`, copies the rendered file out of the shared gallery into
+ * that sprite record's `reference/candidates/` with a generation sidecar —
+ * server-side, so a slow cloud render still lands after the user navigated
+ * away. Candidates accumulate for review (every render is kept), so unlike
+ * the scene hooks there is no newest-wins guard — only per-record
+ * serialization so two finishing renders can't race the candidate numbering.
+ */
+
+import { createMediaJobImageHook } from './mediaJobImageHook.js';
+import { attachReferenceCandidate } from './sprites/reference.js';
+
+const hook = createMediaJobImageHook({
+ label: 'sprite reference-candidate',
+ initLog: '🧍 Sprite reference-candidate hook initialized',
+ tagKey: 'spriteRef',
+ identify: (tag, job) => (tag?.recordId && tag.target && tag.anchorId
+ ? {
+ recordId: tag.recordId,
+ target: tag.target,
+ direction: tag.direction,
+ anchorId: tag.anchorId,
+ chromaKey: tag.chromaKey,
+ mode: tag.mode,
+ model: tag.model,
+ designPrompt: tag.designPrompt,
+ jobId: job?.id || null,
+ }
+ : null),
+ serializeKey: ({ recordId }) => recordId,
+ describe: ({ recordId, anchorId }) => `${recordId}/${anchorId}`,
+ attach: (ctx) => attachReferenceCandidate(ctx),
+ onAttached: ({ recordId, anchorId }, result) => {
+ console.log(`🧍 sprite reference candidate ${recordId}/${anchorId} ← ${result.candidatePath}`);
+ },
+});
+
+export function initSpriteReferenceImageHook() {
+ hook.init();
+}
+
+// Test-only reset so suites that re-init can do so cleanly.
+export const __testing = hook.__testing;
diff --git a/server/services/sprites/chromaKey.js b/server/services/sprites/chromaKey.js
new file mode 100644
index 0000000000..0dc9c9cfc0
--- /dev/null
+++ b/server/services/sprites/chromaKey.js
@@ -0,0 +1,85 @@
+/**
+ * Sprites — dynamic chroma-key selection (issue #2896, phase 2).
+ *
+ * The source pipeline hardcoded magenta because its one character wore green;
+ * per the #2895 decision the key is now picked per character from a FIXED set
+ * of three standard keys, by hue distance from the character's own palette
+ * (a green-clothed character keys on magenta; a pink one keys on green/blue).
+ *
+ * Pure module — palette extraction (sharp) lives in normalize.js; this file
+ * is just color math so it stays unit-testable and safe to import anywhere.
+ */
+
+export const CHROMA_KEYS = [
+ { hex: '#FF00FF', name: 'magenta', hue: 300 },
+ { hex: '#00FF00', name: 'green', hue: 120 },
+ { hex: '#0000FF', name: 'blue', hue: 240 },
+];
+
+export const CHROMA_KEY_HEXES = CHROMA_KEYS.map((k) => k.hex);
+
+// Below this hue separation (degrees) between the chosen key and the nearest
+// significant palette color, keying will likely eat character pixels — the
+// selection still returns the best key but carries a warning.
+export const MIN_HUE_SEPARATION = 60;
+
+export function rgbToHsv(r, g, b) {
+ const rn = r / 255; const gn = g / 255; const bn = b / 255;
+ const max = Math.max(rn, gn, bn);
+ const min = Math.min(rn, gn, bn);
+ const delta = max - min;
+ let h = 0;
+ if (delta > 0) {
+ if (max === rn) h = 60 * (((gn - bn) / delta) % 6);
+ else if (max === gn) h = 60 * ((bn - rn) / delta + 2);
+ else h = 60 * ((rn - gn) / delta + 4);
+ if (h < 0) h += 360;
+ }
+ return { h, s: max === 0 ? 0 : delta / max, v: max };
+}
+
+export function hueDistance(a, b) {
+ const d = Math.abs(a - b) % 360;
+ return d > 180 ? 360 - d : d;
+}
+
+/**
+ * Pick the key whose hue is farthest from every significant color in the
+ * character's palette.
+ *
+ * `palette` is `[{ r, g, b, count }]` (see extractForegroundPalette). Colors
+ * below the saturation/value floors are ignored — near-grays and near-blacks
+ * have no meaningful hue and never conflict with a saturated key; colors
+ * below `minCountFrac` of the total are single-pixel noise.
+ *
+ * Returns `{ hex, name, minHueDistance, warning }` — never null; a fully
+ * achromatic palette conflicts with nothing, so the first key (magenta, the
+ * legacy default) wins with distance Infinity.
+ */
+export function pickChromaKey(palette, {
+ minCountFrac = 0.005,
+ minSaturation = 0.25,
+ minValue = 0.15,
+} = {}) {
+ const entries = Array.isArray(palette) ? palette : [];
+ const total = entries.reduce((sum, e) => sum + (e.count || 0), 0);
+ const significant = entries
+ .map((e) => ({ ...rgbToHsv(e.r, e.g, e.b), count: e.count || 0 }))
+ .filter((c) => c.count >= total * minCountFrac && c.s >= minSaturation && c.v >= minValue);
+
+ let best = null;
+ for (const key of CHROMA_KEYS) {
+ const minDist = significant.length
+ ? Math.min(...significant.map((c) => hueDistance(key.hue, c.h)))
+ : Infinity;
+ if (!best || minDist > best.minHueDistance) {
+ best = { hex: key.hex, name: key.name, minHueDistance: minDist };
+ }
+ }
+ return {
+ ...best,
+ warning: best.minHueDistance < MIN_HUE_SEPARATION
+ ? `Closest palette hue is within ${Math.round(best.minHueDistance)}° of the ${best.name} key — keying may clip character pixels`
+ : null,
+ };
+}
diff --git a/server/services/sprites/chromaKey.test.js b/server/services/sprites/chromaKey.test.js
new file mode 100644
index 0000000000..daf0c80e76
--- /dev/null
+++ b/server/services/sprites/chromaKey.test.js
@@ -0,0 +1,88 @@
+import { describe, it, expect } from 'vitest';
+import {
+ CHROMA_KEYS, CHROMA_KEY_HEXES, MIN_HUE_SEPARATION,
+ rgbToHsv, hueDistance, pickChromaKey,
+} from './chromaKey.js';
+
+describe('chroma key set', () => {
+ it('is exactly the three standard keys', () => {
+ expect(CHROMA_KEY_HEXES).toEqual(['#FF00FF', '#00FF00', '#0000FF']);
+ });
+
+ it('key hues match their RGB definitions', () => {
+ for (const key of CHROMA_KEYS) {
+ const n = parseInt(key.hex.slice(1), 16);
+ const { h, s, v } = rgbToHsv((n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff);
+ expect(Math.round(h)).toBe(key.hue);
+ expect(s).toBe(1);
+ expect(v).toBe(1);
+ }
+ });
+});
+
+describe('hueDistance', () => {
+ it('wraps around the circle', () => {
+ expect(hueDistance(350, 10)).toBe(20);
+ expect(hueDistance(0, 180)).toBe(180);
+ expect(hueDistance(120, 120)).toBe(0);
+ });
+});
+
+describe('pickChromaKey', () => {
+ const solid = (r, g, b, count = 1000) => ({ r, g, b, count });
+
+ it('keeps magenta for a green-clothed character (the legacy Pioneer case)', () => {
+ const pick = pickChromaKey([
+ solid(23, 107, 101), // teal jacket
+ solid(34, 139, 34), // green trim
+ solid(185, 120, 69), // skin
+ ]);
+ expect(pick.hex).toBe('#FF00FF');
+ expect(pick.warning).toBeNull();
+ });
+
+ it('moves off magenta for a pink/magenta character', () => {
+ const pick = pickChromaKey([
+ solid(255, 0, 255), // magenta outfit
+ solid(255, 105, 180), // pink accents
+ ]);
+ expect(pick.hex).toBe('#00FF00'); // green is 180° from magenta
+ expect(pick.minHueDistance).toBeGreaterThanOrEqual(MIN_HUE_SEPARATION);
+ });
+
+ it('avoids green for a green character even when magenta also conflicts a little', () => {
+ const pick = pickChromaKey([solid(0, 255, 0)]);
+ expect(pick.hex).not.toBe('#00FF00');
+ });
+
+ it('ignores achromatic palettes (grays have no meaningful hue) and defaults to magenta', () => {
+ const pick = pickChromaKey([solid(40, 40, 40), solid(200, 200, 200), solid(120, 122, 121)]);
+ expect(pick.hex).toBe('#FF00FF');
+ expect(pick.minHueDistance).toBe(Infinity);
+ expect(pick.warning).toBeNull();
+ });
+
+ it('ignores single-pixel noise below the count floor', () => {
+ const pick = pickChromaKey([
+ solid(23, 107, 101, 100000), // real green clothing
+ solid(255, 0, 255, 3), // 3 stray magenta pixels
+ ]);
+ expect(pick.hex).toBe('#FF00FF');
+ });
+
+ it('warns when every key sits near some palette hue', () => {
+ const pick = pickChromaKey([
+ solid(255, 0, 255), // magenta
+ solid(0, 255, 0), // green
+ solid(0, 0, 255), // blue
+ ]);
+ expect(pick.warning).toMatch(/keying may clip/);
+ expect(pick.minHueDistance).toBeLessThan(MIN_HUE_SEPARATION);
+ });
+
+ it('handles an empty palette', () => {
+ const pick = pickChromaKey([]);
+ expect(pick.hex).toBe('#FF00FF');
+ expect(pick.warning).toBeNull();
+ });
+});
diff --git a/server/services/sprites/normalize.js b/server/services/sprites/normalize.js
new file mode 100644
index 0000000000..86e895f4ff
--- /dev/null
+++ b/server/services/sprites/normalize.js
@@ -0,0 +1,135 @@
+/**
+ * Sprites — reference-frame normalization + palette extraction (issue #2896).
+ *
+ * Node/sharp port of the source pipeline's `normalize_anchor_frame` (Pillow):
+ * mask the character out of the generated candidate by per-pixel difference
+ * from the background key color, then re-composite ONLY the masked pixels
+ * onto a fresh solid-key square canvas. Because the composite always starts
+ * from a clean canvas, switching key colors at lock time (mask on the
+ * generation key, fill with the selected key) is free — that's what makes the
+ * dynamic chroma-key selection possible without regenerating.
+ *
+ * Geometry contract (verbatim from the source): character height is 80% of
+ * the square side (or width fits inside 10% side margins, whichever needs a
+ * bigger canvas), feet baseline sits 7% above the bottom edge, pixels are
+ * never rescaled — only the canvas is sized around them.
+ */
+
+import sharp from 'sharp';
+import { copyFile } from 'fs/promises';
+
+export const REFERENCE_FRAME_HEIGHT_FRAC = 0.80;
+export const REFERENCE_FRAME_BOTTOM_FRAC = 0.07;
+export const REFERENCE_FRAME_SIDE_FRAC = 0.10;
+
+// Pillow's mask threshold: a pixel is foreground when the luminance of its
+// per-channel difference from the key color exceeds this.
+export const MASK_LUMA_THRESHOLD = 40;
+
+export function hexToRgb(hex) {
+ const m = /^#?([0-9a-fA-F]{6})$/.exec(typeof hex === 'string' ? hex : '');
+ if (!m) throw new Error(`Invalid hex color: ${hex}`);
+ const n = parseInt(m[1], 16);
+ return { r: (n >> 16) & 0xff, g: (n >> 8) & 0xff, b: n & 0xff };
+}
+
+// Load as flat RGB (alpha dropped over white like Pillow's convert("RGB")
+// after flatten; generated candidates are opaque PNGs so this is a no-op in
+// practice) plus a foreground mask + tight bounding box vs the key color.
+async function loadMasked(src, maskKeyHex) {
+ const key = hexToRgb(maskKeyHex);
+ const { data, info } = await sharp(src)
+ .flatten({ background: { r: 255, g: 255, b: 255 } })
+ .raw()
+ .toBuffer({ resolveWithObject: true });
+ const { width, height } = info;
+ const mask = new Uint8Array(width * height);
+ let left = width; let top = height; let right = -1; let bottom = -1;
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ const i = (y * width + x) * 3;
+ const dr = Math.abs(data[i] - key.r);
+ const dg = Math.abs(data[i + 1] - key.g);
+ const db = Math.abs(data[i + 2] - key.b);
+ // Pillow convert("L") luminance of the difference image.
+ const luma = (dr * 299 + dg * 587 + db * 114) / 1000;
+ if (luma > MASK_LUMA_THRESHOLD) {
+ mask[y * width + x] = 1;
+ if (x < left) left = x;
+ if (x > right) right = x;
+ if (y < top) top = y;
+ if (y > bottom) bottom = y;
+ }
+ }
+ }
+ const bbox = right >= 0 ? { left, top, right: right + 1, bottom: bottom + 1 } : null;
+ return { data, width, height, mask, bbox };
+}
+
+/**
+ * Histogram the foreground (non-key) pixels of an image, quantized to 4 bits
+ * per channel so anti-aliased shades collapse into their parent color.
+ * Returns `[{ r, g, b, count }]` sorted by count desc — pickChromaKey's input.
+ */
+export async function extractForegroundPalette(src, maskKeyHex) {
+ const { data, width, height, mask } = await loadMasked(src, maskKeyHex);
+ const counts = new Map();
+ for (let p = 0; p < width * height; p++) {
+ if (!mask[p]) continue;
+ const i = p * 3;
+ const bucket = ((data[i] >> 4) << 8) | ((data[i + 1] >> 4) << 4) | (data[i + 2] >> 4);
+ counts.set(bucket, (counts.get(bucket) || 0) + 1);
+ }
+ return [...counts.entries()]
+ .map(([bucket, count]) => ({
+ // Bucket midpoint (e.g. 0xF? → 0xF8) so hue math sees representative values.
+ r: (((bucket >> 8) & 0xf) << 4) | 0x8,
+ g: (((bucket >> 4) & 0xf) << 4) | 0x8,
+ b: ((bucket & 0xf) << 4) | 0x8,
+ count,
+ }))
+ .sort((a, b) => b.count - a.count);
+}
+
+/**
+ * Normalize a candidate into the canonical key-color square described above.
+ * `maskKeyHex` is the background the candidate was GENERATED on (what to key
+ * out); `canvasKeyHex` is the key to composite onto (the selected key). An
+ * image with no detectable foreground copies through unchanged, mirroring
+ * the source behavior.
+ */
+export async function normalizeAnchorFrame(src, dest, { maskKeyHex, canvasKeyHex }) {
+ const { data, width, mask, bbox } = await loadMasked(src, maskKeyHex);
+ if (!bbox) {
+ await copyFile(src, dest);
+ return { copiedThrough: true };
+ }
+ const charW = bbox.right - bbox.left;
+ const charH = bbox.bottom - bbox.top;
+ const side = Math.max(
+ Math.round(charH / REFERENCE_FRAME_HEIGHT_FRAC),
+ Math.round(charW / (1 - 2 * REFERENCE_FRAME_SIDE_FRAC)),
+ );
+ const fill = hexToRgb(canvasKeyHex);
+ const canvas = Buffer.alloc(side * side * 3);
+ for (let p = 0; p < side * side; p++) {
+ canvas[p * 3] = fill.r;
+ canvas[p * 3 + 1] = fill.g;
+ canvas[p * 3 + 2] = fill.b;
+ }
+ const offsetX = Math.floor((side - charW) / 2);
+ const feetY = side - Math.round(side * REFERENCE_FRAME_BOTTOM_FRAC);
+ const offsetY = feetY - charH;
+ for (let y = bbox.top; y < bbox.bottom; y++) {
+ for (let x = bbox.left; x < bbox.right; x++) {
+ if (!mask[y * width + x]) continue;
+ const srcI = (y * width + x) * 3;
+ const dstI = ((offsetY + (y - bbox.top)) * side + offsetX + (x - bbox.left)) * 3;
+ canvas[dstI] = data[srcI];
+ canvas[dstI + 1] = data[srcI + 1];
+ canvas[dstI + 2] = data[srcI + 2];
+ }
+ }
+ await sharp(canvas, { raw: { width: side, height: side, channels: 3 } }).png().toFile(dest);
+ return { side, charW, charH };
+}
diff --git a/server/services/sprites/normalize.test.js b/server/services/sprites/normalize.test.js
new file mode 100644
index 0000000000..91e179e51f
--- /dev/null
+++ b/server/services/sprites/normalize.test.js
@@ -0,0 +1,107 @@
+/**
+ * Sharp port of the source pipeline's normalize_anchor_frame — geometry and
+ * keying verified against the Pillow reference implementation's contract:
+ * 80% height square, 7% bottom margin, mask = luma(diff vs key) > 40, pixels
+ * never rescaled, composite always lands on a fresh solid-key canvas.
+ */
+
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { mkdtempSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import sharp from 'sharp';
+import { normalizeAnchorFrame, extractForegroundPalette, hexToRgb } from './normalize.js';
+
+let dir;
+beforeAll(() => { dir = mkdtempSync(join(tmpdir(), 'sprite-normalize-test-')); });
+afterAll(() => rmSync(dir, { recursive: true, force: true }));
+
+const MAGENTA = { r: 255, g: 0, b: 255 };
+const GREEN = { r: 0, g: 255, b: 0 };
+
+// 64×64 key-color canvas with a green rectangle at x∈[20,30), y∈[10,30).
+async function writeCandidate(path, { bg = MAGENTA, fg = GREEN } = {}) {
+ const w = 64; const h = 64;
+ const buf = Buffer.alloc(w * h * 3);
+ for (let y = 0; y < h; y++) {
+ for (let x = 0; x < w; x++) {
+ const inRect = x >= 20 && x < 30 && y >= 10 && y < 30;
+ const c = inRect ? fg : bg;
+ const i = (y * w + x) * 3;
+ buf[i] = c.r; buf[i + 1] = c.g; buf[i + 2] = c.b;
+ }
+ }
+ await sharp(buf, { raw: { width: w, height: h, channels: 3 } }).png().toFile(path);
+}
+
+async function readRaw(path) {
+ const { data, info } = await sharp(path).raw().toBuffer({ resolveWithObject: true });
+ return { data, width: info.width, height: info.height };
+}
+
+const px = ({ data, width }, x, y) => ({
+ r: data[(y * width + x) * 3],
+ g: data[(y * width + x) * 3 + 1],
+ b: data[(y * width + x) * 3 + 2],
+});
+
+describe('normalizeAnchorFrame', () => {
+ it('centers the character on the canonical square with the feet baseline', async () => {
+ const src = join(dir, 'cand.png');
+ const dest = join(dir, 'locked.png');
+ await writeCandidate(src);
+ const result = await normalizeAnchorFrame(src, dest, { maskKeyHex: '#FF00FF', canvasKeyHex: '#FF00FF' });
+
+ // charH=20 → side = round(20/0.8) = 25; feet at 25 - round(25*0.07) = 23.
+ expect(result).toMatchObject({ side: 25, charW: 10, charH: 20 });
+ const img = await readRaw(dest);
+ expect(img.width).toBe(25);
+ expect(img.height).toBe(25);
+ expect(px(img, 0, 0)).toEqual(MAGENTA); // corner is clean key
+ expect(px(img, 7, 3)).toEqual(GREEN); // char top-left at (7, 3)
+ expect(px(img, 16, 22)).toEqual(GREEN); // char bottom-right at (16, 22)
+ expect(px(img, 12, 23)).toEqual(MAGENTA); // below the feet baseline
+ expect(px(img, 6, 3)).toEqual(MAGENTA); // left of the character
+ });
+
+ it('switches key color at composite time (mask on generation key, fill with selected key)', async () => {
+ const src = join(dir, 'cand2.png');
+ const dest = join(dir, 'locked2.png');
+ await writeCandidate(src);
+ await normalizeAnchorFrame(src, dest, { maskKeyHex: '#FF00FF', canvasKeyHex: '#0000FF' });
+ const img = await readRaw(dest);
+ expect(px(img, 0, 0)).toEqual({ r: 0, g: 0, b: 255 }); // background re-keyed to blue
+ expect(px(img, 7, 3)).toEqual(GREEN); // character pixels untouched
+ });
+
+ it('copies through an image with no detectable foreground', async () => {
+ const src = join(dir, 'blank.png');
+ const dest = join(dir, 'blank-out.png');
+ await writeCandidate(src, { fg: MAGENTA }); // rectangle same as background
+ const result = await normalizeAnchorFrame(src, dest, { maskKeyHex: '#FF00FF', canvasKeyHex: '#FF00FF' });
+ expect(result.copiedThrough).toBe(true);
+ const img = await readRaw(dest);
+ expect(img.width).toBe(64); // untouched original
+ });
+});
+
+describe('extractForegroundPalette', () => {
+ it('histograms only non-key pixels, bucketed to 4 bits per channel', async () => {
+ const src = join(dir, 'palette.png');
+ await writeCandidate(src);
+ const palette = await extractForegroundPalette(src, '#FF00FF');
+ expect(palette).toHaveLength(1);
+ expect(palette[0]).toEqual({ r: 8, g: 248, b: 8, count: 200 }); // 10×20 green rect
+ });
+});
+
+describe('hexToRgb', () => {
+ it('parses with or without the leading #', () => {
+ expect(hexToRgb('#FF00FF')).toEqual(MAGENTA);
+ expect(hexToRgb('00ff00')).toEqual(GREEN);
+ });
+
+ it('throws on junk', () => {
+ expect(() => hexToRgb('red')).toThrow(/Invalid hex/);
+ });
+});
diff --git a/server/services/sprites/prompts.js b/server/services/sprites/prompts.js
new file mode 100644
index 0000000000..eb9edc77aa
--- /dev/null
+++ b/server/services/sprites/prompts.js
@@ -0,0 +1,88 @@
+/**
+ * Sprites — reference-workflow prompt builders (issue #2896, phase 2).
+ *
+ * Faithful port of the source pipeline's stage-1/2 prompt contracts
+ * (character_workflow.main_prompt + reference_anchors.reference_prompt),
+ * genericized for PortOS: no project-specific naming, and the chroma-key
+ * background color is a parameter (the source hardcoded magenta) so the
+ * per-character key selected at lock time flows into every later prompt.
+ *
+ * Pure module — no I/O, no imports from the rest of the server — so
+ * validation.js and the client can lean on its constants safely.
+ */
+
+// Canonical 8-direction order (the source pipeline's RUNTIME_DIRECTION_ORDER)
+// — atlas row order in later phases depends on this, so keep it stable.
+export const SPRITE_DIRECTIONS = [
+ 'south',
+ 'south-east',
+ 'east',
+ 'north-east',
+ 'north',
+ 'north-west',
+ 'west',
+ 'south-west',
+];
+
+// Directions that get a derived anchor. `south` is never generated — the
+// frozen main reference IS the south anchor.
+export const ANCHOR_DIRECTIONS = SPRITE_DIRECTIONS.filter((d) => d !== 'south');
+
+export const anchorIdForDirection = (direction) => `walk-${direction}`;
+
+// Per-direction facing clause — verbatim from the source pipeline.
+export const REFERENCE_FACING = {
+ east: 'facing due east, a strict right-facing side profile',
+ west: 'facing due west, a strict left-facing side profile',
+ south: 'facing the viewer (front)',
+ north: 'facing directly away from the viewer (back view, no face)',
+ 'south-east': 'a three-quarter front view angled down and to screen-right',
+ 'south-west': 'a three-quarter front view angled down and to screen-left',
+ 'north-east': 'a three-quarter rear view angled up and to screen-right (no face)',
+ 'north-west': 'a three-quarter rear view angled up and to screen-left (no face)',
+};
+
+const KEY_NAMES = { '#FF00FF': 'magenta', '#00FF00': 'green', '#0000FF': 'blue' };
+
+/** "magenta (#FF00FF)" — the phrase both prompt templates embed. */
+export function keyColorPhrase(hex) {
+ const normalized = typeof hex === 'string' ? hex.toUpperCase() : '';
+ const name = KEY_NAMES[normalized];
+ return name ? `${name} (${normalized})` : normalized || 'magenta (#FF00FF)';
+}
+
+/**
+ * Stage-1 prompt: create the frozen walk-south identity reference from a
+ * text description and/or an attached visual reference.
+ */
+export function buildMainReferencePrompt({ name, designPrompt, chromaKey }) {
+ const description = (typeof designPrompt === 'string' && designPrompt.trim())
+ ? designPrompt.trim()
+ : 'Use the attached visual reference as the character design.';
+ return (
+ `Create the frozen walk-south identity reference for a game character named ${name}. `
+ + `Character direction: ${description} `
+ + 'Draw exactly one full-body figure facing the viewer in a neutral standing pose, feet '
+ + 'level on one baseline, arms relaxed, with a clear readable silhouette. Match the '
+ + 'attached visual reference when provided. Preserve physical-left and physical-right '
+ + 'accessories exactly. Flat non-isometric pixel-art game sprite reference, centered on '
+ + `a plain exact ${keyColorPhrase(chromaKey)} background. No motion, labels, grid, shadows, scenery, `
+ + 'wireframe, or extra figures. Return exactly one PNG.'
+ );
+}
+
+/**
+ * Stage-2 prompt: derive one directional anchor from the attached frozen
+ * main reference.
+ */
+export function buildAnchorPrompt({ name, direction, chromaKey }) {
+ const facing = REFERENCE_FACING[direction] || direction;
+ return (
+ `Redraw the attached ${name} character as one `
+ + `full-body figure in a neutral standing pose, ${facing}. Keep the exact same `
+ + 'identity, proportions, palette, clothing, hairstyle, and accessories/straps on the '
+ + 'same anatomical side as the attached reference. Flat, non-isometric view; a '
+ + `single centered figure; plain flat ${keyColorPhrase(chromaKey)} background; no labels, no `
+ + 'grid lines, no wireframe or guide colors. Return exactly one PNG.'
+ );
+}
diff --git a/server/services/sprites/prompts.test.js b/server/services/sprites/prompts.test.js
new file mode 100644
index 0000000000..e5178ae365
--- /dev/null
+++ b/server/services/sprites/prompts.test.js
@@ -0,0 +1,71 @@
+import { describe, it, expect } from 'vitest';
+import {
+ SPRITE_DIRECTIONS, ANCHOR_DIRECTIONS, REFERENCE_FACING, anchorIdForDirection,
+ keyColorPhrase, buildMainReferencePrompt, buildAnchorPrompt,
+} from './prompts.js';
+
+describe('sprite direction contracts', () => {
+ it('exposes the canonical 8-direction order starting at south', () => {
+ expect(SPRITE_DIRECTIONS).toHaveLength(8);
+ expect(SPRITE_DIRECTIONS[0]).toBe('south');
+ expect(new Set(SPRITE_DIRECTIONS).size).toBe(8);
+ });
+
+ it('anchors exclude south (the frozen main IS the south anchor)', () => {
+ expect(ANCHOR_DIRECTIONS).toHaveLength(7);
+ expect(ANCHOR_DIRECTIONS).not.toContain('south');
+ });
+
+ it('has a facing clause for every direction', () => {
+ for (const d of SPRITE_DIRECTIONS) {
+ expect(REFERENCE_FACING[d], d).toBeTruthy();
+ }
+ });
+
+ it('rear-facing clauses forbid a face', () => {
+ for (const d of ['north', 'north-east', 'north-west']) {
+ expect(REFERENCE_FACING[d]).toContain('no face');
+ }
+ });
+
+ it('derives anchor ids', () => {
+ expect(anchorIdForDirection('north-west')).toBe('walk-north-west');
+ });
+});
+
+describe('keyColorPhrase', () => {
+ it('names the three standard keys', () => {
+ expect(keyColorPhrase('#FF00FF')).toBe('magenta (#FF00FF)');
+ expect(keyColorPhrase('#00ff00')).toBe('green (#00FF00)');
+ expect(keyColorPhrase('#0000FF')).toBe('blue (#0000FF)');
+ });
+
+ it('falls back to magenta when unset', () => {
+ expect(keyColorPhrase(null)).toBe('magenta (#FF00FF)');
+ });
+});
+
+describe('buildMainReferencePrompt', () => {
+ it('embeds name, design prompt, and the key color', () => {
+ const p = buildMainReferencePrompt({ name: 'Scout', designPrompt: 'a wiry ranger in a mossy cloak', chromaKey: '#00FF00' });
+ expect(p).toContain('named Scout');
+ expect(p).toContain('a wiry ranger in a mossy cloak');
+ expect(p).toContain('green (#00FF00) background');
+ expect(p).toContain('walk-south identity reference');
+ expect(p).toContain('Return exactly one PNG.');
+ });
+
+ it('falls back to the attached-reference instruction without a design prompt', () => {
+ const p = buildMainReferencePrompt({ name: 'Scout', designPrompt: ' ', chromaKey: '#FF00FF' });
+ expect(p).toContain('Use the attached visual reference as the character design.');
+ });
+});
+
+describe('buildAnchorPrompt', () => {
+ it('embeds the facing clause and key color', () => {
+ const p = buildAnchorPrompt({ name: 'Scout', direction: 'east', chromaKey: '#FF00FF' });
+ expect(p).toContain('facing due east, a strict right-facing side profile');
+ expect(p).toContain('magenta (#FF00FF) background');
+ expect(p).toContain('attached Scout character');
+ });
+});
diff --git a/server/services/sprites/reference.js b/server/services/sprites/reference.js
new file mode 100644
index 0000000000..30020f1c7a
--- /dev/null
+++ b/server/services/sprites/reference.js
@@ -0,0 +1,386 @@
+/**
+ * Sprites — reference workflow orchestration (issue #2896, phase 2).
+ *
+ * Ports the source pipeline's stage 1–2: create a character, generate main-
+ * reference candidates (text and/or an uploaded visual reference), freeze the
+ * approved main as the immutable identity root, then derive and lock the 8
+ * directional anchors from it. Generation rides the shared media-job queue
+ * (`enqueueJob` kind:'image' with a `spriteRef` destination tag — the
+ * completion hook in services/spriteReferenceImageHook.js files finished
+ * renders into reference/candidates/); locking is deterministic sharp work
+ * (normalize.js) plus the dynamic chroma-key selection (chromaKey.js).
+ *
+ * Immutability contract: a locked artifact is never regenerated or
+ * overwritten — locked targets 409 on generate/lock, and versioned filenames
+ * (`-vN`) always land on the first free version.
+ */
+
+import { join } from 'path';
+import { readdir, copyFile, unlink } from 'fs/promises';
+import {
+ PATHS, ensureDir, sha256File, atomicWrite, pathExists, readJSONFile,
+} from '../../lib/fileUtils.js';
+import { ServerError } from '../../lib/errorHandler.js';
+import { enqueueJob } from '../mediaJobQueue/index.js';
+import { IMAGE_GEN_MODE } from '../imageGen/modes.js';
+import { resolveImageCleaners } from '../imageGen/index.js';
+import { getSettings } from '../settings.js';
+import { getRecord, updateRecord } from './records.js';
+import { spriteDir, resolveSpriteAssetPath } from './paths.js';
+import {
+ SPRITE_DIRECTIONS, ANCHOR_DIRECTIONS, anchorIdForDirection,
+ buildMainReferencePrompt, buildAnchorPrompt,
+} from './prompts.js';
+import { pickChromaKey, CHROMA_KEY_HEXES } from './chromaKey.js';
+import { normalizeAnchorFrame, extractForegroundPalette } from './normalize.js';
+
+const LEGACY_KEY = '#FF00FF';
+
+// Default i2i strengths: anchors redraw a NEW facing from the main (mostly
+// follow the prompt, borrow identity), an uploaded visual reference guides
+// the main more tightly. Local mflux honors the number; codex/grok attach
+// the image and pick their own fidelity.
+const ANCHOR_DEFAULT_STRENGTH = 0.8;
+const UPLOAD_DEFAULT_STRENGTH = 0.65;
+
+const manifestRelPath = (id) => `reference/${id}-reference-set-v1.json`;
+
+async function loadManifest(recordId) {
+ return readJSONFile(join(spriteDir(recordId), manifestRelPath(recordId)), null);
+}
+
+async function saveManifest(recordId, manifest) {
+ const abs = join(spriteDir(recordId), manifestRelPath(recordId));
+ await ensureDir(join(spriteDir(recordId), 'reference'));
+ await atomicWrite(abs, manifest);
+}
+
+function seedManifest(recordId) {
+ return {
+ schemaVersion: 1,
+ manifestId: `${recordId}-reference-set-v1`,
+ status: 'needs-main-reference',
+ characterFamily: recordId,
+ projection: 'flat',
+ rule: 'Every anchor descends from the frozen main reference. Locked anchors are immutable evidence. Walk cycles are conditioned only on a locked directional anchor plus the deterministic pose scaffold, never on prior walk output, and the identity anchor is never regenerated.',
+ chromaKey: null,
+ mainReference: { path: null, role: 'immutable-root', background: 'chroma-key', locked: false },
+ anchors: SPRITE_DIRECTIONS.map((direction) => ({
+ id: anchorIdForDirection(direction),
+ kind: 'walk-anchor',
+ direction,
+ status: 'pending',
+ source: direction === 'south' ? 'main-reference' : 'derive-from-main',
+ })),
+ note: 'walk-south and walk-north double as the front/back idle stills, so no separate idle anchors are kept.',
+ };
+}
+
+async function requireCharacter(recordId) {
+ const record = await getRecord(recordId);
+ if (!record) throw new ServerError('Sprite record not found', { status: 404, code: 'NOT_FOUND' });
+ if (record.kind !== 'character') {
+ throw new ServerError('Reference workflow applies to character records only', { status: 400, code: 'NOT_A_CHARACTER' });
+ }
+ return record;
+}
+
+// First free `-vN` filename — locked artifacts are never overwritten; a
+// correction after a crash (or a future unlock flow) lands on the next
+// version instead of replacing evidence.
+async function nextVersionPath(dir, base) {
+ for (let n = 1; ; n++) {
+ const rel = `${base}-v${n}.png`;
+ if (!await pathExists(join(dir, rel))) return rel;
+ }
+}
+
+async function nextCandidateName(candidatesDir, anchorId) {
+ let entries = [];
+ try {
+ entries = await readdir(candidatesDir);
+ } catch {
+ // dir absent → first candidate
+ }
+ const re = new RegExp(`^${anchorId}-candidate-(\\d+)\\.png$`);
+ const max = entries.reduce((m, name) => {
+ const match = re.exec(name);
+ return match ? Math.max(m, parseInt(match[1], 10)) : m;
+ }, 0);
+ return `${anchorId}-candidate-${String(max + 1).padStart(2, '0')}.png`;
+}
+
+// Mirrors the pipeline visual stages' mode resolution: per-request override
+// (honored only when that backend is enabled), else the saved dispatcher
+// default, else codex → grok → local. External never queues.
+function resolveGenMode(requested, settings) {
+ const codexEnabled = settings?.imageGen?.codex?.enabled === true;
+ const grokEnabled = settings?.imageGen?.grok?.enabled === true;
+ if (requested === IMAGE_GEN_MODE.CODEX && codexEnabled) return IMAGE_GEN_MODE.CODEX;
+ if (requested === IMAGE_GEN_MODE.GROK && grokEnabled) return IMAGE_GEN_MODE.GROK;
+ if (requested === IMAGE_GEN_MODE.LOCAL) return IMAGE_GEN_MODE.LOCAL;
+ const settingsMode = settings?.imageGen?.mode;
+ if (settingsMode === IMAGE_GEN_MODE.CODEX && codexEnabled) return IMAGE_GEN_MODE.CODEX;
+ if (settingsMode === IMAGE_GEN_MODE.GROK && grokEnabled) return IMAGE_GEN_MODE.GROK;
+ if (settingsMode === IMAGE_GEN_MODE.LOCAL) return IMAGE_GEN_MODE.LOCAL;
+ if (codexEnabled) return IMAGE_GEN_MODE.CODEX;
+ if (grokEnabled) return IMAGE_GEN_MODE.GROK;
+ return IMAGE_GEN_MODE.LOCAL;
+}
+
+function findAnchor(manifest, anchorId) {
+ return manifest.anchors.find((a) => a.id === anchorId) || null;
+}
+
+/**
+ * Reference-set view for the detail endpoint: the manifest (null until the
+ * first generate) plus the reviewable candidates parsed from their
+ * generation sidecars, newest first per target.
+ */
+export async function getReferenceSet(recordId) {
+ const manifest = await loadManifest(recordId);
+ const candidatesDir = join(spriteDir(recordId), 'reference', 'candidates');
+ let entries = [];
+ try {
+ entries = await readdir(candidatesDir);
+ } catch {
+ // no candidates yet
+ }
+ const candidates = (await Promise.all(entries
+ .filter((name) => name.endsWith('.png'))
+ .map(async (name) => {
+ const sidecar = await readJSONFile(join(candidatesDir, `${name.replace(/\.png$/, '')}.generation.json`), null);
+ return {
+ path: `reference/candidates/${name}`,
+ target: sidecar?.target || null,
+ anchorId: sidecar?.anchorId || null,
+ chromaKey: sidecar?.chromaKey || null,
+ mode: sidecar?.mode || null,
+ model: sidecar?.model || null,
+ generatedAt: sidecar?.generatedAt || null,
+ };
+ })))
+ .sort((a, b) => (b.generatedAt || '').localeCompare(a.generatedAt || '') || a.path.localeCompare(b.path));
+ return { manifest, candidates };
+}
+
+/**
+ * Queue one main-reference or directional-anchor candidate render.
+ * User-triggered only (route-invoked); never called at boot.
+ *
+ * `upload` is an optional `{ tempPath, originalname }` from the route's
+ * multipart parse (main target only) — copied into the record's
+ * reference/uploads/ so provenance survives the temp-file sweep.
+ */
+export async function startReferenceGeneration(recordId, body, upload = null) {
+ const record = await requireCharacter(recordId);
+ const manifest = (await loadManifest(recordId)) || seedManifest(recordId);
+ const target = body.target;
+ const genKey = record.chromaKey || manifest.chromaKey || LEGACY_KEY;
+ const settings = await getSettings();
+ const mode = resolveGenMode(body.mode, settings);
+
+ let prompt;
+ let initImagePath;
+ let initImageStrength = Number.isFinite(body.initImageStrength) ? body.initImageStrength : undefined;
+ let anchorId;
+ let direction;
+
+ if (target === 'main') {
+ if (manifest.mainReference.locked) {
+ throw new ServerError('Main reference is locked — corrections require a new character version, never regeneration', { status: 409, code: 'REFERENCE_LOCKED' });
+ }
+ const designPrompt = typeof body.designPrompt === 'string' ? body.designPrompt.trim() : '';
+ if (!designPrompt && !upload) {
+ throw new ServerError('Provide a design prompt and/or a reference image', { status: 400, code: 'DESIGN_INPUT_REQUIRED' });
+ }
+ anchorId = anchorIdForDirection('south');
+ direction = 'south';
+ prompt = buildMainReferencePrompt({ name: record.name, designPrompt, chromaKey: genKey });
+ if (upload) {
+ const uploadsDir = join(spriteDir(recordId), 'reference', 'uploads');
+ await ensureDir(uploadsDir);
+ const ext = /\.(png|jpe?g|webp)$/i.exec(upload.originalname || '')?.[0]?.toLowerCase() || '.png';
+ // Timestamp-named (not -vN): uploads may mix extensions, which would
+ // defeat a .png-only version scan and overwrite an earlier upload.
+ initImagePath = join(uploadsDir, `design-reference-${Date.now()}${ext}`);
+ await copyFile(upload.tempPath, initImagePath);
+ await unlink(upload.tempPath).catch(() => {});
+ initImageStrength ??= UPLOAD_DEFAULT_STRENGTH;
+ }
+ if (designPrompt) manifest.designPrompt = designPrompt;
+ } else {
+ if (!ANCHOR_DIRECTIONS.includes(target)) {
+ throw new ServerError(`Unknown reference target: ${target}`, { status: 400, code: 'INVALID_TARGET' });
+ }
+ if (!manifest.mainReference.locked) {
+ throw new ServerError('Lock the main reference before deriving directional anchors', { status: 409, code: 'MAIN_NOT_LOCKED' });
+ }
+ direction = target;
+ anchorId = anchorIdForDirection(direction);
+ const anchor = findAnchor(manifest, anchorId);
+ if (anchor?.status === 'locked') {
+ throw new ServerError(`Anchor ${anchorId} is locked — locked anchors are immutable`, { status: 409, code: 'REFERENCE_LOCKED' });
+ }
+ prompt = buildAnchorPrompt({ name: record.name, direction, chromaKey: genKey });
+ initImagePath = resolveSpriteAssetPath(recordId, manifest.mainReference.path);
+ if (!await pathExists(initImagePath)) {
+ throw new ServerError('Locked main reference file is missing on disk', { status: 500, code: 'MAIN_REFERENCE_MISSING' });
+ }
+ initImageStrength ??= ANCHOR_DEFAULT_STRENGTH;
+ }
+
+ const { cleanC2PA, denoise } = resolveImageCleaners(undefined, settings, mode);
+ const model = body.model
+ || (mode === IMAGE_GEN_MODE.CODEX ? settings.imageGen?.codex?.model : undefined);
+ const baseParams = {
+ prompt,
+ ...(initImagePath ? { initImagePath, initImageStrength } : {}),
+ cleanC2PA,
+ denoise,
+ // Destination tag the completion hook files the render by.
+ spriteRef: {
+ recordId, target, direction, anchorId, chromaKey: genKey, mode, model: model || null,
+ ...(target === 'main' && body.designPrompt ? { designPrompt: body.designPrompt } : {}),
+ },
+ };
+ const params = mode === IMAGE_GEN_MODE.CODEX
+ ? { mode, codexPath: settings.imageGen?.codex?.codexPath, model, effort: body.effort || settings.imageGen?.codex?.effort, ...baseParams }
+ : mode === IMAGE_GEN_MODE.GROK
+ ? { mode, grokPath: settings.imageGen?.grok?.grokPath, aspectRatio: settings.imageGen?.grok?.aspectRatio, ...baseParams }
+ : { mode, pythonPath: settings.imageGen?.local?.pythonPath || null, ...(body.model ? { modelId: body.model } : {}), ...baseParams };
+
+ await saveManifest(recordId, manifest);
+ const { jobId } = enqueueJob({ kind: 'image', params, owner: 'sprites' });
+ console.log(`🧍 sprite reference render queued ${recordId}/${anchorId} mode=${mode} jobId=${jobId.slice(0, 8)}`);
+ return { jobId, mode, target, anchorId };
+}
+
+/**
+ * Completion-hook attach: copy a finished render from the shared image
+ * gallery into the record's reference/candidates/ with a generation sidecar.
+ * Returns the candidate rel path (falsy result = hook logs a skip).
+ */
+export async function attachReferenceCandidate(ctx) {
+ const { recordId, anchorId, filename } = ctx;
+ const src = join(PATHS.images, filename);
+ if (!await pathExists(src)) return null;
+ const candidatesDir = join(spriteDir(recordId), 'reference', 'candidates');
+ await ensureDir(candidatesDir);
+ const name = await nextCandidateName(candidatesDir, anchorId);
+ const dest = join(candidatesDir, name);
+ await copyFile(src, dest);
+ const relPath = `reference/candidates/${name}`;
+ await atomicWrite(join(candidatesDir, `${name.replace(/\.png$/, '')}.generation.json`), {
+ schemaVersion: 1,
+ kind: 'sprite-reference-generation',
+ characterId: recordId,
+ target: ctx.target,
+ anchorId,
+ direction: ctx.direction,
+ chromaKey: ctx.chromaKey || null,
+ mode: ctx.mode || null,
+ model: ctx.model || null,
+ jobId: ctx.jobId || null,
+ ...(ctx.designPrompt ? { designPrompt: ctx.designPrompt } : {}),
+ generatedAt: new Date().toISOString(),
+ candidatePath: relPath,
+ candidateSha256: await sha256File(dest),
+ sourceFilename: filename,
+ });
+ return { candidatePath: relPath };
+}
+
+async function loadCandidateSidecar(candAbs) {
+ return readJSONFile(`${candAbs.replace(/\.png$/, '')}.generation.json`, null);
+}
+
+/**
+ * Lock a reviewed candidate: normalize it onto the canonical key-color
+ * square and record it in the manifest as immutable evidence. Locking the
+ * main also runs the dynamic chroma-key selection (unless the user already
+ * pinned one on the record).
+ */
+export async function lockReference(recordId, { target, candidate }) {
+ const record = await requireCharacter(recordId);
+ // Seed on demand — a candidate may predate the manifest (e.g. files placed
+ // by an import or a crash-recovered tree); the lock is what makes it real.
+ const manifest = (await loadManifest(recordId)) || seedManifest(recordId);
+ if (typeof candidate !== 'string' || !candidate.startsWith('reference/candidates/')) {
+ throw new ServerError('Candidate must be a reference/candidates/ path', { status: 400, code: 'INVALID_CANDIDATE' });
+ }
+ const candAbs = resolveSpriteAssetPath(recordId, candidate);
+ if (!await pathExists(candAbs)) {
+ throw new ServerError(`Candidate not found: ${candidate}`, { status: 404, code: 'CANDIDATE_NOT_FOUND' });
+ }
+ const refDir = join(spriteDir(recordId), 'reference');
+ const sidecar = await loadCandidateSidecar(candAbs);
+ // A candidate generated for one facing must not land in another slot — a
+ // misclick would freeze the wrong pose as immutable evidence.
+ if (sidecar?.target && sidecar.target !== target) {
+ throw new ServerError(`Candidate was generated for target "${sidecar.target}", not "${target}"`, { status: 400, code: 'CANDIDATE_TARGET_MISMATCH' });
+ }
+ // Mask on the key the candidate was GENERATED against (its actual
+ // background), which may differ from the key selected at lock time.
+ const maskKey = sidecar?.chromaKey || record.chromaKey || LEGACY_KEY;
+ const now = new Date().toISOString();
+
+ if (target === 'main') {
+ if (manifest.mainReference.locked) {
+ throw new ServerError('Main reference is already locked', { status: 409, code: 'REFERENCE_LOCKED' });
+ }
+ // Dynamic key selection (#2895): histogram the character's own palette
+ // and pick the standard key farthest from it in hue — unless the user
+ // already pinned a key on the record.
+ const auto = pickChromaKey(await extractForegroundPalette(candAbs, maskKey));
+ const userPinned = CHROMA_KEY_HEXES.includes(record.chromaKey);
+ const selectedKey = userPinned ? record.chromaKey : auto.hex;
+ const rel = `reference/${await nextVersionPath(refDir, `${recordId}-walk-south`)}`;
+ const destAbs = join(spriteDir(recordId), rel);
+ await normalizeAnchorFrame(candAbs, destAbs, { maskKeyHex: maskKey, canvasKeyHex: selectedKey });
+ const sha256 = await sha256File(destAbs);
+ manifest.chromaKey = selectedKey;
+ manifest.chromaKeyAutoSelected = !userPinned;
+ manifest.chromaKeyWarning = userPinned ? null : auto.warning;
+ manifest.mainReference = {
+ ...manifest.mainReference,
+ path: rel,
+ background: 'chroma-key',
+ locked: true,
+ lockedFrom: candidate,
+ lockedAt: now,
+ sha256,
+ };
+ const south = findAnchor(manifest, anchorIdForDirection('south'));
+ if (south) Object.assign(south, { status: 'locked', path: rel, lockedFrom: candidate, sha256 });
+ manifest.status = 'in-progress';
+ await saveManifest(recordId, manifest);
+ await updateRecord(recordId, { chromaKey: selectedKey, status: 'reference' });
+ } else {
+ if (!ANCHOR_DIRECTIONS.includes(target)) {
+ throw new ServerError(`Unknown reference target: ${target}`, { status: 400, code: 'INVALID_TARGET' });
+ }
+ if (!manifest.mainReference.locked) {
+ throw new ServerError('Lock the main reference first', { status: 409, code: 'MAIN_NOT_LOCKED' });
+ }
+ const anchorId = anchorIdForDirection(target);
+ const anchor = findAnchor(manifest, anchorId);
+ if (!anchor) throw new ServerError(`Unknown anchor: ${anchorId}`, { status: 400, code: 'INVALID_TARGET' });
+ if (anchor.status === 'locked') {
+ throw new ServerError(`Anchor ${anchorId} is already locked`, { status: 409, code: 'REFERENCE_LOCKED' });
+ }
+ const canvasKey = record.chromaKey || manifest.chromaKey || LEGACY_KEY;
+ const rel = `reference/${await nextVersionPath(refDir, `${recordId}-${anchorId}`)}`;
+ const destAbs = join(spriteDir(recordId), rel);
+ await normalizeAnchorFrame(candAbs, destAbs, { maskKeyHex: maskKey, canvasKeyHex: canvasKey });
+ Object.assign(anchor, {
+ status: 'locked', path: rel, lockedFrom: candidate, lockedAt: now, sha256: await sha256File(destAbs),
+ });
+ const allLocked = manifest.anchors.every((a) => a.status === 'locked');
+ if (allLocked) manifest.status = 'complete';
+ await saveManifest(recordId, manifest);
+ if (allLocked) await updateRecord(recordId, { status: 'reference-complete' });
+ }
+ console.log(`🔒 sprite reference locked ${recordId}/${target} from ${candidate}`);
+ return getReferenceSet(recordId);
+}
diff --git a/server/services/sprites/reference.test.js b/server/services/sprites/reference.test.js
new file mode 100644
index 0000000000..2c54f28af4
--- /dev/null
+++ b/server/services/sprites/reference.test.js
@@ -0,0 +1,306 @@
+/**
+ * Reference workflow orchestration (#2896): generate → candidates → lock,
+ * against the file record backend + a tmpdir asset tree. The media-job queue
+ * and image-gen dispatcher are mocked — this suite covers the workflow
+ * contracts (prompt/tag/param shaping, manifest lifecycle, immutability
+ * 409s, dynamic chroma-key selection at lock).
+ */
+
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import { mkdtempSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import sharp from 'sharp';
+import { mkdir, writeFile, readFile } from 'fs/promises';
+
+const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-reference-test-'));
+
+vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ PATHS: {
+ ...actual.PATHS,
+ data: TEST_ROOT,
+ sprites: join(TEST_ROOT, 'sprites'),
+ images: join(TEST_ROOT, 'images'),
+ },
+ };
+});
+
+const enqueueJob = vi.fn(() => ({ jobId: 'job-1234567890', position: 0, status: 'queued' }));
+vi.mock('../mediaJobQueue/index.js', () => ({
+ enqueueJob: (...args) => enqueueJob(...args),
+ mediaJobEvents: { on: () => {}, off: () => {} },
+}));
+
+vi.mock('../imageGen/index.js', () => ({
+ resolveImageCleaners: () => ({ cleanC2PA: false, denoise: false }),
+}));
+
+const settings = {
+ imageGen: {
+ mode: 'codex',
+ codex: { enabled: true, codexPath: '/usr/local/bin/codex', model: 'gpt-5.6-luna', effort: 'low' },
+ grok: { enabled: true, grokPath: '/usr/local/bin/grok', aspectRatio: '1:1' },
+ local: { pythonPath: '/usr/bin/python3' },
+ },
+};
+vi.mock('../settings.js', () => ({ getSettings: async () => settings }));
+
+const records = await import('./records.js');
+const {
+ getReferenceSet, startReferenceGeneration, attachReferenceCandidate, lockReference,
+} = await import('./reference.js');
+
+let seq = 0;
+const newId = () => `hero-${++seq}`;
+
+async function createCharacter(id, input = {}) {
+ return records.createRecord({ kind: 'character', name: 'Hero', ...input }, id);
+}
+
+// A green character rectangle on a magenta background — the legacy Pioneer
+// shape, so auto-selection should keep magenta.
+async function writeCandidatePng(path, { bg = { r: 255, g: 0, b: 255 }, fg = { r: 23, g: 107, b: 101 } } = {}) {
+ const w = 64; const h = 64;
+ const buf = Buffer.alloc(w * h * 3);
+ for (let y = 0; y < h; y++) {
+ for (let x = 0; x < w; x++) {
+ const inRect = x >= 20 && x < 30 && y >= 10 && y < 40;
+ const c = inRect ? fg : bg;
+ const i = (y * w + x) * 3;
+ buf[i] = c.r; buf[i + 1] = c.g; buf[i + 2] = c.b;
+ }
+ }
+ await mkdir(join(path, '..'), { recursive: true });
+ await sharp(buf, { raw: { width: w, height: h, channels: 3 } }).png().toFile(path);
+}
+
+async function placeCandidate(recordId, target, name, opts = {}) {
+ const candDir = join(TEST_ROOT, 'sprites', recordId, 'reference', 'candidates');
+ await mkdir(candDir, { recursive: true });
+ await writeCandidatePng(join(candDir, name), opts);
+ await writeFile(join(candDir, `${name.replace(/\.png$/, '')}.generation.json`), JSON.stringify({
+ schemaVersion: 1, target, chromaKey: opts.sidecarKey ?? '#FF00FF',
+ }));
+ return `reference/candidates/${name}`;
+}
+
+async function lockMain(recordId) {
+ const rel = await placeCandidate(recordId, 'main', 'walk-south-candidate-01.png');
+ return lockReference(recordId, { target: 'main', candidate: rel });
+}
+
+beforeEach(() => {
+ enqueueJob.mockClear();
+ rmSync(join(TEST_ROOT, 'sprite-records.json'), { force: true });
+});
+afterAll(() => rmSync(TEST_ROOT, { recursive: true, force: true }));
+
+describe('startReferenceGeneration', () => {
+ it('404s an unknown record and 400s a props record', async () => {
+ await expect(startReferenceGeneration('nope', { target: 'main', designPrompt: 'x' }))
+ .rejects.toMatchObject({ code: 'NOT_FOUND' });
+ await records.createRecord({ kind: 'props', name: 'Crates' }, 'crates');
+ await expect(startReferenceGeneration('crates', { target: 'main', designPrompt: 'x' }))
+ .rejects.toMatchObject({ code: 'NOT_A_CHARACTER' });
+ });
+
+ it('requires a design prompt or upload for the main target', async () => {
+ const id = newId();
+ await createCharacter(id);
+ await expect(startReferenceGeneration(id, { target: 'main' }))
+ .rejects.toMatchObject({ code: 'DESIGN_INPUT_REQUIRED' });
+ });
+
+ it('queues a main render with the sprite tag and seeds the manifest', async () => {
+ const id = newId();
+ await createCharacter(id);
+ const result = await startReferenceGeneration(id, { target: 'main', designPrompt: 'a wiry ranger' });
+ expect(result).toMatchObject({ jobId: 'job-1234567890', mode: 'codex', target: 'main', anchorId: 'walk-south' });
+
+ const call = enqueueJob.mock.calls[0][0];
+ expect(call.kind).toBe('image');
+ expect(call.params.mode).toBe('codex');
+ expect(call.params.model).toBe('gpt-5.6-luna');
+ expect(call.params.prompt).toContain('named Hero');
+ expect(call.params.prompt).toContain('a wiry ranger');
+ expect(call.params.prompt).toContain('magenta (#FF00FF)');
+ expect(call.params.spriteRef).toMatchObject({ recordId: id, target: 'main', anchorId: 'walk-south', chromaKey: '#FF00FF' });
+
+ const { manifest } = await getReferenceSet(id);
+ expect(manifest.status).toBe('needs-main-reference');
+ expect(manifest.anchors).toHaveLength(8);
+ expect(manifest.designPrompt).toBe('a wiry ranger');
+ });
+
+ it('refuses anchors before the main is locked, and south always', async () => {
+ const id = newId();
+ await createCharacter(id);
+ await startReferenceGeneration(id, { target: 'main', designPrompt: 'x' });
+ await expect(startReferenceGeneration(id, { target: 'east' }))
+ .rejects.toMatchObject({ code: 'MAIN_NOT_LOCKED' });
+ // 'south' is not a valid anchor target at all (schema also blocks it).
+ await expect(startReferenceGeneration(id, { target: 'south' }))
+ .rejects.toMatchObject({ code: 'INVALID_TARGET' });
+ });
+
+ it('derives anchors from the locked main via i2i with the selected key in the prompt', async () => {
+ const id = newId();
+ await createCharacter(id);
+ await lockMain(id);
+ const result = await startReferenceGeneration(id, { target: 'east' });
+ expect(result.anchorId).toBe('walk-east');
+ const call = enqueueJob.mock.calls[0][0];
+ expect(call.params.initImagePath).toContain(`${id}-walk-south-v1.png`);
+ expect(call.params.initImageStrength).toBe(0.8);
+ expect(call.params.prompt).toContain('strict right-facing side profile');
+ expect(call.params.prompt).toContain('magenta (#FF00FF)'); // green char kept magenta
+ });
+
+ it('409s generation for a locked target', async () => {
+ const id = newId();
+ await createCharacter(id);
+ await lockMain(id);
+ await expect(startReferenceGeneration(id, { target: 'main', designPrompt: 'x' }))
+ .rejects.toMatchObject({ code: 'REFERENCE_LOCKED', status: 409 });
+
+ const rel = await placeCandidate(id, 'east', 'walk-east-candidate-01.png');
+ await lockReference(id, { target: 'east', candidate: rel });
+ await expect(startReferenceGeneration(id, { target: 'east' }))
+ .rejects.toMatchObject({ code: 'REFERENCE_LOCKED', status: 409 });
+ });
+});
+
+describe('attachReferenceCandidate', () => {
+ it('copies the render into candidates/ with a numbered name and sidecar', async () => {
+ const id = newId();
+ await createCharacter(id);
+ await mkdir(join(TEST_ROOT, 'images'), { recursive: true });
+ await writeCandidatePng(join(TEST_ROOT, 'images', 'render-1.png'));
+
+ const ctx = {
+ recordId: id, target: 'main', direction: 'south', anchorId: 'walk-south',
+ chromaKey: '#FF00FF', mode: 'codex', model: 'm', jobId: 'j1',
+ designPrompt: 'a ranger', filename: 'render-1.png',
+ };
+ const first = await attachReferenceCandidate(ctx);
+ expect(first.candidatePath).toBe('reference/candidates/walk-south-candidate-01.png');
+ const second = await attachReferenceCandidate(ctx);
+ expect(second.candidatePath).toBe('reference/candidates/walk-south-candidate-02.png');
+
+ const sidecar = JSON.parse(await readFile(
+ join(TEST_ROOT, 'sprites', id, 'reference', 'candidates', 'walk-south-candidate-01.generation.json'), 'utf8',
+ ));
+ expect(sidecar).toMatchObject({
+ kind: 'sprite-reference-generation', characterId: id, target: 'main',
+ anchorId: 'walk-south', chromaKey: '#FF00FF', jobId: 'j1', designPrompt: 'a ranger',
+ });
+ expect(sidecar.candidateSha256).toMatch(/^[0-9a-f]{64}$/);
+
+ const { candidates } = await getReferenceSet(id);
+ expect(candidates).toHaveLength(2);
+ expect(candidates[0].target).toBe('main');
+ });
+
+ it('returns null when the gallery file is gone', async () => {
+ const id = newId();
+ await createCharacter(id);
+ expect(await attachReferenceCandidate({
+ recordId: id, target: 'main', anchorId: 'walk-south', filename: 'vanished.png',
+ })).toBeNull();
+ });
+});
+
+describe('lockReference', () => {
+ it('locks the main: normalizes, auto-selects the chroma key, freezes the manifest + record', async () => {
+ const id = newId();
+ await createCharacter(id);
+ const result = await lockMain(id);
+
+ expect(result.manifest.mainReference.locked).toBe(true);
+ expect(result.manifest.mainReference.path).toBe(`reference/${id}-walk-south-v1.png`);
+ expect(result.manifest.mainReference.sha256).toMatch(/^[0-9a-f]{64}$/);
+ expect(result.manifest.chromaKey).toBe('#FF00FF'); // green char → magenta kept
+ expect(result.manifest.chromaKeyAutoSelected).toBe(true);
+ expect(result.manifest.status).toBe('in-progress');
+ const south = result.manifest.anchors.find((a) => a.id === 'walk-south');
+ expect(south.status).toBe('locked');
+
+ const record = await records.getRecord(id);
+ expect(record.chromaKey).toBe('#FF00FF');
+ expect(record.status).toBe('reference');
+ });
+
+ it('auto-selects AWAY from the key a magenta-clothed character would clash with', async () => {
+ const id = newId();
+ await createCharacter(id);
+ const rel = await placeCandidate(id, 'main', 'walk-south-candidate-01.png', {
+ fg: { r: 255, g: 80, b: 230 }, // pink/magenta outfit
+ });
+ const result = await lockReference(id, { target: 'main', candidate: rel });
+ expect(result.manifest.chromaKey).not.toBe('#FF00FF');
+ const record = await records.getRecord(id);
+ expect(record.chromaKey).toBe(result.manifest.chromaKey);
+ });
+
+ it('respects a user-pinned key instead of auto-selecting', async () => {
+ const id = newId();
+ await createCharacter(id);
+ await records.updateRecord(id, { chromaKey: '#0000FF' });
+ const result = await lockMain(id);
+ expect(result.manifest.chromaKey).toBe('#0000FF');
+ expect(result.manifest.chromaKeyAutoSelected).toBe(false);
+ });
+
+ it('409s a relock and enforces candidate/target agreement', async () => {
+ const id = newId();
+ await createCharacter(id);
+ await lockMain(id);
+ const rel = await placeCandidate(id, 'main', 'walk-south-candidate-02.png');
+ await expect(lockReference(id, { target: 'main', candidate: rel }))
+ .rejects.toMatchObject({ code: 'REFERENCE_LOCKED', status: 409 });
+
+ const eastRel = await placeCandidate(id, 'east', 'walk-east-candidate-01.png');
+ await expect(lockReference(id, { target: 'west', candidate: eastRel }))
+ .rejects.toMatchObject({ code: 'CANDIDATE_TARGET_MISMATCH' });
+ });
+
+ it('refuses candidates outside reference/candidates/ and traversal paths', async () => {
+ const id = newId();
+ await createCharacter(id);
+ await expect(lockReference(id, { target: 'main', candidate: 'runtime/sneaky.png' }))
+ .rejects.toMatchObject({ code: 'INVALID_CANDIDATE' });
+ await expect(lockReference(id, { target: 'main', candidate: 'reference/candidates/../../../escape.png' }))
+ .rejects.toMatchObject({ code: 'INVALID_ASSET_PATH' });
+ });
+
+ it('never overwrites an existing versioned artifact (crash-recovery lands on v2)', async () => {
+ const id = newId();
+ await createCharacter(id);
+ // Simulate a crash that wrote v1 but never updated the manifest.
+ const refDir = join(TEST_ROOT, 'sprites', id, 'reference');
+ await mkdir(refDir, { recursive: true });
+ await writeFile(join(refDir, `${id}-walk-south-v1.png`), 'stale-bytes');
+ const result = await lockMain(id);
+ expect(result.manifest.mainReference.path).toBe(`reference/${id}-walk-south-v2.png`);
+ expect(await readFile(join(refDir, `${id}-walk-south-v1.png`), 'utf8')).toBe('stale-bytes');
+ });
+
+ it('completes the set when the last anchor locks', async () => {
+ const id = newId();
+ await createCharacter(id);
+ await lockMain(id);
+ const { ANCHOR_DIRECTIONS } = await import('./prompts.js');
+ for (const direction of ANCHOR_DIRECTIONS) {
+ const rel = await placeCandidate(id, direction, `walk-${direction}-candidate-01.png`);
+ await lockReference(id, { target: direction, candidate: rel });
+ }
+ const { manifest } = await getReferenceSet(id);
+ expect(manifest.status).toBe('complete');
+ expect(manifest.anchors.every((a) => a.status === 'locked')).toBe(true);
+ const record = await records.getRecord(id);
+ expect(record.status).toBe('reference-complete');
+ });
+});