Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-2979]): derive sprite references from a locked turnaround sheet
[._.]/ Adam Eivy8bee04f14939
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 6aea1ba336..32cd1f11e5 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -24,6 +24,8 @@## Sprite Manager+- **[issue-2979] Characters now start from a turnaround sheet, so accessories stop jumping sides** — directional anchors used to be drawn from a single front-facing reference, which meant the AI had to invent every side it hadn't seen: a hip bag on the character's front would migrate to their back in the north view, and pockets or straps would swap sides between the east and west profiles. The reference workflow is now three ordered steps. **1 · Turnaround sheet**: describe the character (or attach a design image) and generate one image showing them from four angles — front, right, back, left — with every accessory pinned to the same side of the body in each panel. Lock it, and it becomes the character's identity root. **2 · Main reference**: redrawn from the sheet's front panel with one click, no separate design input. **3 · Directional anchors**: each pose is now redrawn from the sheet's panel for *that* side, so the model can see the hip bag instead of guessing at it. Picking the chroma-key background also moved to the sheet lock, where it can see the character from every angle — so a green backpack that's only visible from behind is accounted for up front instead of surprising you later. Forking a character now seeds the new one's sheet from the original's, inheriting every side.+- **[issue-2979] Existing characters can backfill a turnaround sheet from their locked main** — a character you built before this shows the same three steps, with step 1 offering **Generate from locked main**: it expands the front view you already froze into the full four-view sheet, keeps your existing chroma key exactly as-is, and unblocks the directional anchors you haven't locked yet — which are then drawn from the sheet like a new character's. Already-locked references and anchors are untouched (they're immutable by design), so the benefit applies to whatever poses you still have left to derive.- **Steer a directional-anchor re-roll with a correction note** — when a directional anchor comes out wrong (say the north-east pose grew a pocket on the arm that has none in every other view), re-rolling it with the same inputs tended to just reproduce the same mistake. Each unlocked anchor tile now has a small **Correction (optional)** box: type what to fix ("no pocket on the right sleeve") and hit **Regenerate**, and the note is appended to that pose's prompt as an explicit override so the new render actually diverges. The button reads **Generate** on the first render and **Regenerate** once candidates exist, the correction is per-direction (so eight different fixes don't collide), and it rides into the candidate's saved prompt so the image preview shows exactly what was asked for. Main-reference iteration is unchanged — it already has its own design-prompt box.- **[issue-2964] The same correction note now steers a re-roll from the asset card too** — the correction box used to live only on the Reference Set's anchor grid, so re-rolling a directional-anchor candidate from its card in the Assets library ignored any fix you'd typed. Each anchor candidate card now carries the same correction affordance: click its note icon to type ("no pocket on the right sleeve") and hit **Regenerate**, and that guidance is appended to the pose's prompt exactly as it is from the grid. The two surfaces share one correction per direction, so a note you type in either place shows up in the other, and both re-rolls send the identical instruction.- **Locking a main reference no longer leaves a colored halo around the character** — when you lock a character's main reference, PortOS re-keys the background to whichever chroma color (magenta, green, or blue) sits farthest from the character's own palette. If that swapped the background — e.g. a magenta render re-keyed onto blue — the anti-aliased pixels along the character's outline kept their old magenta tint and showed up as a faint magenta ring against the new blue backdrop. Locking now cleans those edge pixels as it re-keys, so the outline blends into the new background with no leftover halo. Already-locked references (which are immutable and can't be re-locked) are healed automatically on upgrade: each one is re-derived from its saved candidate with the fix applied, and its stored checksum is refreshed — no action needed on your part.diff --git a/client/src/components/sprites/ReferenceWorkflow.jsx b/client/src/components/sprites/ReferenceWorkflow.jsxindex f3341f0d76..66fefd3f16 100644--- a/client/src/components/sprites/ReferenceWorkflow.jsx+++ b/client/src/components/sprites/ReferenceWorkflow.jsx@@ -12,11 +12,12 @@ import SpriteReferencePicker from './SpriteReferencePicker.jsx';import ForkSpriteModal from './ForkSpriteModal.jsx';import CorrectionNote, { correctionPromptPayload } from './CorrectionNote.jsx';-// 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.+// Reference workflow (issues #2896, #2979): three ordered steps — generate a+// turnaround sheet from text + an optional design image and freeze it, derive+// and freeze the main (walk-south) from that sheet, then derive + lock the 8+// directional anchors, each redrawn from the sheet's panel for that side. The+// manifest (server-owned) is the source of truth for status; this component+// only renders it and fires the generate/lock/override actions.// Mirrors server/services/sprites/chromaKey.js CHROMA_KEYS (client can't// import server modules).@@ -78,6 +79,14 @@ export default function ReferenceWorkflow({ record, reference, renders, correcticonst manifest = reference?.manifest || null;const candidates = reference?.candidates || [];const mainLocked = manifest?.mainReference?.locked === true;+ // Turnaround-first (#2979): the sheet is step 1 and the identity root — the+ // main is its front view and every anchor is redrawn from the panel showing+ // that side. A character created before this shows the same three steps with+ // step 1 as a backfill from its already-locked main.+ const turnaroundLocked = manifest?.turnaround?.locked === true;+ const backfilling = mainLocked && !turnaroundLocked;+ // Whichever lock froze the canonical key closes the pin control.+ const keyFrozen = mainLocked || turnaroundLocked;// Once every anchor is locked this grid is just static previews of files the// "Reference set" file browser below already lists (and makes inspectable /// downloadable), so it reads as duplicate content. Collapse it by default@@ -152,16 +161,18 @@ export default function ReferenceWorkflow({ record, reference, renders, correcticonst { jobId } = await generateSpriteReference(recordId, {target,...(mode ? { mode } : {}),- ...(target === 'main' ? {+ // The sheet owns the design inputs; the main derives from it with no+ // inputs of its own; anchors carry only their correction note.+ ...(target === 'turnaround' ? {designPrompt,...(refSource?.type === 'upload' ? { referenceImageFile: refSource.file } : {}),...(refSource?.type === 'gallery' ? { initImageGalleryFile: refSource.filename } : {}),...(refSource?.type === 'sprite' ? { initImageSpriteId: refSource.id } : {}),...(refSource ? { initImageStrength: strength } : {}),- } : correctionPromptPayload(corrections, target)),+ } : target === 'main' ? {} : correctionPromptPayload(corrections, target)),}, { silent: true });resolveSubmit(target, jobId);- if (target === 'main') clearSource();+ if (target === 'turnaround') clearSource();} catch (err) {cancelSubmit(target);toast.error(err?.message || `Failed to queue ${target} render`);@@ -189,7 +200,9 @@ export default function ReferenceWorkflow({ record, reference, renders, correctidelete next[candidate.path];return next;});- toast.success(target === 'main' ? 'Main reference frozen' : `Anchor ${target} locked`);+ toast.success(target === 'turnaround' ? 'Turnaround sheet frozen'+ : target === 'main' ? 'Main reference frozen'+ : `Anchor ${target} locked`);onChanged();}, { errorMessage: 'Lock failed' });@@ -225,14 +238,14 @@ export default function ReferenceWorkflow({ record, reference, renders, correcti</h3><divclassName="flex items-center gap-1.5"- title={mainLocked+ title={keyFrozen? 'Chroma key is frozen with the locked reference set'- : 'Chroma key — auto-selected at main lock; pin one of the three standard keys, or auto to let the lock decide'}+ : 'Chroma key — auto-selected when the turnaround sheet locks; pin one of the three standard keys, or auto to let the lock decide'}><span className="text-xs text-gray-500">key</span><buttononClick={() => setChromaKey(null)}- disabled={keySaving || mainLocked}+ disabled={keySaving || keyFrozen}className={`px-1.5 h-5 rounded-sm border text-[10px] ${!record.chromaKey ? 'border-white ring-1 ring-port-accent text-white' : 'border-port-border text-gray-400 opacity-60 hover:opacity-100'} disabled:opacity-40`}>auto@@ -241,7 +254,7 @@ export default function ReferenceWorkflow({ record, reference, renders, correcti<buttonkey={hex}onClick={() => setChromaKey(hex)}- disabled={keySaving || mainLocked}+ disabled={keySaving || keyFrozen}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'} disabled:opacity-40`}style={{ backgroundColor: hex }}@@ -258,27 +271,28 @@ export default function ReferenceWorkflow({ record, reference, renders, correcti</p>)}- {/* Main reference — the immutable identity root */}+ {/* Step 1 — the turnaround sheet, the identity root every later render+ descends from. A character created before #2979 backfills one from its+ already-locked main so its remaining anchors get all sides too. */}<div className="space-y-2">- <h4 className="text-xs uppercase tracking-wide text-gray-500">Main reference (walk-south)</h4>- {mainLocked ? (+ <h4 className="text-xs uppercase tracking-wide text-gray-500">+ 1 · Turnaround sheet+ {turnaroundLocked && <span className="ml-1 text-[10px] text-port-success normal-case tracking-normal">· locked</span>}+ </h4>+ {turnaroundLocked ? (<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" />- <div className="space-y-2">- <p className="text-xs text-gray-500 flex items-center gap-1"><Lock className="w-3 h-3" /> frozen · immutable root</p>- {/* A locked main can never be regenerated — to iterate on it, fork- into a new character seeded from this reference (image+text→image). */}- <button- type="button"- onClick={() => setForkOpen(true)}- className="flex items-center gap-1.5 px-2.5 py-1 text-xs bg-port-card border border-port-border rounded text-gray-300 hover:border-port-accent"- >- <GitFork className="w-3.5 h-3.5" /> Fork from this reference- </button>- </div>+ <SpriteImg recordId={recordId} path={manifest.turnaround.path} className="w-48 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 · identity root+ </p></div>) : (<div className="space-y-2">+ <p className="text-[11px] text-gray-500">+ {backfilling+ ? 'This character was built before turnaround sheets. Generate one from its locked main reference — the remaining directional anchors will be drawn from it, so accessories stay on the same side of the body.'+ : 'One image, four views (front · right · back · left). Every later render is redrawn from it, so a bag or pocket keeps the same anatomical side from every angle.'}+ </p><textareavalue={designPrompt}onChange={(e) => setDesignPrompt(e.target.value)}@@ -359,15 +373,63 @@ export default function ReferenceWorkflow({ record, reference, renders, correcti</button></div>)}+ <div className="flex flex-wrap items-center gap-3">+ {modePicker}+ <button+ onClick={() => generate('turnaround')}+ disabled={!mode || !!pendingJobs.turnaround || (!designPrompt.trim() && !refSource && !backfilling)}+ 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.turnaround ? <RefreshCw className="w-3.5 h-3.5 animate-spin" /> : <Sparkles className="w-3.5 h-3.5" />}+ {pendingJobs.turnaround ? 'Rendering…' : backfilling ? 'Generate from locked main' : 'Generate candidate'}+ </button>+ </div>+ {(candidatesByTarget.turnaround || []).length > 0 && (+ <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">+ {candidatesByTarget.turnaround.map((c) => (+ <CandidateTile key={c.path} recordId={recordId} candidate={c} locking={locking} clipRisk={clipRisks[c.path]} onLock={(cand, accept) => lock('turnaround', cand, accept)} />+ ))}+ </div>+ )}+ </div>+ )}+ </div>++ {/* Step 2 — the main reference: the sheet's front view, and the sprite's+ canonical face (thumbnails, fork seeds, the walk-south anchor). */}+ <div className="space-y-2">+ <h4 className="text-xs uppercase tracking-wide text-gray-500">+ 2 · Main reference (walk-south)+ {mainLocked && <span className="ml-1 text-[10px] text-port-success normal-case tracking-normal">· locked</span>}+ </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" />+ <div className="space-y-2">+ <p className="text-xs text-gray-500 flex items-center gap-1"><Lock className="w-3 h-3" /> frozen · immutable root</p>+ {/* A locked main can never be regenerated — to iterate on it, fork+ into a new character seeded from this reference (image+text→image). */}+ <button+ type="button"+ onClick={() => setForkOpen(true)}+ className="flex items-center gap-1.5 px-2.5 py-1 text-xs bg-port-card border border-port-border rounded text-gray-300 hover:border-port-accent"+ >+ <GitFork className="w-3.5 h-3.5" /> Fork from this reference+ </button>+ </div>+ </div>+ ) : turnaroundLocked ? (+ <div className="space-y-2">+ <p className="text-[11px] text-gray-500">Redrawn from the sheet’s front panel — no separate design input.</p><div className="flex flex-wrap items-center gap-3">{modePicker}<buttononClick={() => generate('main')}- disabled={!mode || !!pendingJobs.main || (!designPrompt.trim() && !refSource)}+ disabled={!mode || !!pendingJobs.main}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'}+ {pendingJobs.main ? 'Rendering…' : (candidatesByTarget.main || []).length ? 'Regenerate' : 'Generate candidate'}</button></div>{(candidatesByTarget.main || []).length > 0 && (@@ -378,10 +440,13 @@ export default function ReferenceWorkflow({ record, reference, renders, correcti</div>)}</div>+ ) : (+ <p className="text-[11px] text-gray-600">Lock the turnaround sheet first.</p>)}</div>- {/* Directional anchors — derive from the frozen main */}+ {/* Step 3 — directional anchors, each redrawn from the sheet's panel for+ that side (gated on the sheet even for pre-#2979 characters). */}{mainLocked && (<div className="space-y-2"><div className="flex items-center gap-3">@@ -392,7 +457,7 @@ export default function ReferenceWorkflow({ record, reference, renders, correcticlassName="flex items-center gap-1 text-xs uppercase tracking-wide text-gray-500 hover:text-gray-300">{anchorsOpen ? <ChevronDown className="w-3 h-3" /> : <ChevronRight className="w-3 h-3" />}- Directional anchors+ 3 · Directional anchors{allAnchorsLocked && (<span className="text-[10px] text-port-success normal-case tracking-normal flex items-center gap-0.5">· <Lock className="w-2.5 h-2.5" /> all locked@@ -404,6 +469,13 @@ export default function ReferenceWorkflow({ record, reference, renders, correcti{!anchorsOpen && allAnchorsLocked && (<p className="text-[10px] text-gray-600">Locked anchors are listed under “Reference set” below.</p>)}+ {anchorsOpen && !allAnchorsLocked && (+ <p className="text-[10px] text-gray-600">+ {turnaroundLocked+ ? 'Each anchor is redrawn from the turnaround sheet’s panel for that side.'+ : 'Blocked: generate and lock the turnaround sheet above first — anchors are drawn from it.'}+ </p>+ )}{anchorsOpen && (<div className="grid grid-cols-2 sm:grid-cols-4 gap-3">{manifest.anchors.map((anchor) => {diff --git a/client/src/lib/spriteCollectionActions.js b/client/src/lib/spriteCollectionActions.jsindex bd40a706e9..370dfc83d1 100644--- a/client/src/lib/spriteCollectionActions.js+++ b/client/src/lib/spriteCollectionActions.js@@ -87,12 +87,14 @@ export function buildCollectionActions({};}- // A reference CANDIDATE can be re-rolled; an approved/superseded anchor- // file only exists after the lock, and locks are irreversible. `south` is- // excluded because the main reference needs a design prompt or an uploaded- // image, neither of which an asset card can supply — that stays in- // ReferenceWorkflow.- if (role === 'reference' && status === 'candidate' && direction !== 'south') {+ // A directional reference CANDIDATE can be re-rolled; an approved/superseded+ // anchor file only exists after the lock, and locks are irreversible.+ // `south` is excluded because the main reference is derived from the+ // turnaround sheet in ReferenceWorkflow's guided flow, and a DIRECTIONLESS+ // candidate (the turnaround sheet itself, #2979) has no direction to+ // re-roll — it carries the design prompt and seed sources, which an asset+ // card can't supply. Both stay in ReferenceWorkflow.+ if (role === 'reference' && status === 'candidate' && direction && direction !== 'south') {const locked = lockedDirections.has(direction);const pending = Boolean(referencePending[direction]);return {diff --git a/client/src/lib/spriteCollectionActions.test.js b/client/src/lib/spriteCollectionActions.test.jsindex ec4cf97746..72982b4e3b 100644--- a/client/src/lib/spriteCollectionActions.test.js+++ b/client/src/lib/spriteCollectionActions.test.js@@ -120,6 +120,13 @@ describe('regenerateFor — reference anchors', () => {it('never offers a re-roll for a LOCKED reference file (not a candidate)', () => {expect(build().regenerateFor(asset('reference/example-walk-east-v1.png'))).toBeNull();});++ it('never offers a re-roll for a turnaround candidate — it has no direction (#2979)', () => {+ // A directionless candidate would otherwise call generateAnchor(null) and+ // 400 on an invalid target; the sheet's design inputs live in the workflow.+ expect(build().regenerateFor(asset('reference/candidates/turnaround-candidate-1.png'))).toBeNull();+ expect(build().regenerateFor(asset('reference/example-turnaround-v1.png'))).toBeNull();+ });});describe('regenerateFor — backend gate (#2938)', () => {diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 56761dd35c..71460da0b0 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1039,7 +1039,9 @@ export const spriteCreateSchema = z.object({spec: z.record(z.string(), z.unknown()).nullable().optional(),});-const spriteReferenceTargetSchema = z.enum(['main', ...ANCHOR_DIRECTIONS]);+// 'turnaround' is the identity root of the turnaround-first workflow (#2979) —+// generated and locked before the main, which the anchors then descend from.+const spriteReferenceTargetSchema = z.enum(['turnaround', 'main', ...ANCHOR_DIRECTIONS]);// Multipart callers send numbers as form-field strings — coerce before range// checks ('' → undefined so an empty field doesn't become 0).diff --git a/server/routes/sprites.js b/server/routes/sprites.jsindex e9d2f35bb6..2476893597 100644--- a/server/routes/sprites.js+++ b/server/routes/sprites.js@@ -130,8 +130,11 @@ router.post('/:id/reference/generate', referenceUpload, asyncHandler(async (req,const upload = file ? { tempPath: file.path, originalname: file.originalname } : null;if (upload) res.on('close', () => { unlink(upload.tempPath).catch(() => {}); });const body = validateRequest(spriteReferenceGenerateSchema, req.body ?? {});- 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' });+ // A design upload seeds the identity root only. That's the turnaround sheet+ // on a turnaround-first record and the main on a legacy one (#2979) — the+ // service decides which applies; everything downstream derives from the sheet.+ if (upload && body.target !== 'turnaround' && body.target !== 'main') {+ throw new ServerError('Reference image uploads seed the turnaround sheet or the main reference — directional anchors always derive from the locked turnaround', { status: 400, code: 'UPLOAD_MAIN_ONLY' });}res.json(await startReferenceGeneration(req.params.id, body, upload));}));diff --git a/server/routes/sprites.test.js b/server/routes/sprites.test.jsindex dcaaf32585..0b73b1d2e5 100644--- a/server/routes/sprites.test.js+++ b/server/routes/sprites.test.js@@ -256,7 +256,21 @@ describe('sprites routes', () => {);});- it('POST /:id/reference/generate rejects an upload for a non-main target', async () => {+ it('POST /:id/reference/generate accepts a multipart design-image upload for the turnaround', async () => {+ const boundary = '----spritetest3';+ const res = await request(app)+ .post('/api/sprites/pioneer/reference/generate')+ .set('content-type', `multipart/form-data; boundary=${boundary}`)+ .send(buildMultipart(boundary, { fields: { target: 'turnaround', designPrompt: 'a ranger' } }));+ expect(res.status).toBe(200);+ expect(reference.startReferenceGeneration).toHaveBeenCalledWith(+ 'pioneer',+ expect.objectContaining({ target: 'turnaround', designPrompt: 'a ranger' }),+ expect.objectContaining({ originalname: 'design.png', tempPath: expect.any(String) }),+ );+ });++ it('POST /:id/reference/generate rejects an upload for a directional-anchor target', async () => {const boundary = '----spritetest2';const res = await request(app).post('/api/sprites/pioneer/reference/generate')@@ -267,6 +281,23 @@ describe('sprites routes', () => {expect(reference.startReferenceGeneration).not.toHaveBeenCalled();});+ it('POST /:id/reference/generate + /lock accept the turnaround target', async () => {+ const gen = await request(app)+ .post('/api/sprites/pioneer/reference/generate')+ .send({ target: 'turnaround', designPrompt: 'a ranger' });+ expect(gen.status).toBe(200);+ expect(reference.startReferenceGeneration).toHaveBeenCalledWith(+ 'pioneer', { target: 'turnaround', designPrompt: 'a ranger' }, null,+ );+ const lock = await request(app)+ .post('/api/sprites/pioneer/reference/lock')+ .send({ target: 'turnaround', candidate: 'reference/candidates/turnaround-candidate-01.png' });+ expect(lock.status).toBe(200);+ expect(reference.lockReference).toHaveBeenCalledWith(+ 'pioneer', { target: 'turnaround', candidate: 'reference/candidates/turnaround-candidate-01.png' },+ );+ });+it('POST /:id/reference/generate rejects a non-image mime upload', async () => {const boundary = '----spritetest3';const res = await request(app)diff --git a/server/services/sprites/assetPrompt.js b/server/services/sprites/assetPrompt.jsindex e85a619518..4a7f21a1be 100644--- a/server/services/sprites/assetPrompt.js+++ b/server/services/sprites/assetPrompt.js@@ -29,7 +29,9 @@ import { readJSONFile } from '../../lib/fileUtils.js';import { spriteDir, resolveSpriteAssetPath, RUN_DIR_MATCH } from './paths.js';import { getRecord } from './records.js';import { loadManifest } from './reference.js';-import { buildMainReferencePrompt, buildAnchorPrompt, buildWalkVideoPrompt } from './prompts.js';+import {+ buildMainReferencePrompt, buildAnchorPrompt, buildWalkVideoPrompt, buildTurnaroundPrompt,+} from './prompts.js';import { DEFAULT_CHROMA_KEY } from './chromaKey.js';const CANDIDATE_RE = /^reference\/candidates\/(.+)\.png$/i;@@ -39,15 +41,17 @@ const CANDIDATE_RE = /^reference\/candidates\/(.+)\.png$/i;* source }` result — the stored literal prompt when captured, otherwise a* faithful rebuild from the parameters the sidecar did record.*/-function fromCandidateSidecar(sidecar, name) {+function fromCandidateSidecar(sidecar, name, { fromTurnaround = false } = {}) {if (!sidecar) return null;if (typeof sidecar.prompt === 'string' && sidecar.prompt) {return { prompt: sidecar.prompt, designPrompt: sidecar.designPrompt || null, source: 'candidate' };}// Pre-capture candidate — rebuild with the builder that produced it.- const prompt = sidecar.target === 'main'- ? buildMainReferencePrompt({ name, designPrompt: sidecar.designPrompt, chromaKey: sidecar.chromaKey })- : buildAnchorPrompt({ name, direction: sidecar.direction || sidecar.target, chromaKey: sidecar.chromaKey });+ const prompt = sidecar.target === 'turnaround'+ ? buildTurnaroundPrompt({ name, designPrompt: sidecar.designPrompt, chromaKey: sidecar.chromaKey })+ : sidecar.target === 'main'+ ? buildMainReferencePrompt({ name, designPrompt: sidecar.designPrompt, chromaKey: sidecar.chromaKey, fromTurnaround })+ : buildAnchorPrompt({ name, direction: sidecar.direction || sidecar.target, chromaKey: sidecar.chromaKey, fromTurnaround });return { prompt, designPrompt: sidecar.designPrompt || null, source: 'candidate-reconstructed' };}@@ -77,23 +81,50 @@ export async function resolveSpriteAssetPrompt(recordId, relPath) {if (/^reference\//i.test(relPath)) {const manifest = await loadManifest(recordId);if (manifest) {+ // Everything below the sheet was derived from it (#2979), so a rebuild+ // must use the turnaround-aware copy or it won't match what was sent.+ const derived = { fromTurnaround: manifest.turnaround?.locked === true };+ const turnaround = manifest.turnaround;+ // `manifest.chromaKey` is the key FROZEN at a lock — which, when+ // auto-selected (user didn't pin), differs from the key the artifact that+ // TRIGGERED that selection was generated against: it was rendered before+ // the key existed, so its prompt embedded the default. Exactly one lock+ // per character freezes the key — the turnaround's on a turnaround-first+ // record, the main's on a legacy one (including a backfilled sheet, which+ // locks later and inherits) — so compare lock times to find it.+ const wasFreezer = (artifact) => {+ const other = artifact === turnaround ? manifest.mainReference : turnaround;+ return !other?.lockedAt || !artifact?.lockedAt || artifact.lockedAt <= other.lockedAt;+ };+ const renderKey = (artifact) => (+ manifest.chromaKeyAutoSelected && wasFreezer(artifact) ? DEFAULT_CHROMA_KEY : manifest.chromaKey+ );+ if (turnaround?.path === relPath) {+ const stem = candidateStem(turnaround.lockedFrom);+ const fromCandidate = stem ? fromCandidateSidecar(await candidateSidecarFor(recordId, stem), name) : null;+ return fromCandidate || {+ prompt: buildTurnaroundPrompt({+ name,+ designPrompt: manifest.designPrompt,+ chromaKey: renderKey(turnaround),+ }),+ designPrompt: manifest.designPrompt || null,+ source: 'reference-turnaround',+ };+ }const main = manifest.mainReference;if (main?.path === relPath) {// Prefer the frozen candidate's literal prompt; fall back to a rebuild// from the manifest's own recorded design prompt + key.const stem = candidateStem(main.lockedFrom);- const fromCandidate = stem ? fromCandidateSidecar(await candidateSidecarFor(recordId, stem), name) : null;+ const fromCandidate = stem ? fromCandidateSidecar(await candidateSidecarFor(recordId, stem), name, derived) : null;// Fallback (source candidate sidecar gone): rebuild from the manifest.- // `manifest.chromaKey` is the key FROZEN at lock — which, when- // auto-selected (user didn't pin), differs from the key the main was- // actually GENERATED against. A non-pinned main is rendered before the- // key is chosen, so its prompt embedded the default key, not the- // auto-picked one — use the default here to match what was really sent.return fromCandidate || {prompt: buildMainReferencePrompt({name,designPrompt: manifest.designPrompt,- chromaKey: manifest.chromaKeyAutoSelected ? DEFAULT_CHROMA_KEY : manifest.chromaKey,+ chromaKey: renderKey(main),+ ...derived,}),designPrompt: manifest.designPrompt || null,source: 'reference-main',@@ -102,9 +133,11 @@ export async function resolveSpriteAssetPrompt(recordId, relPath) {const anchor = (manifest.anchors || []).find((a) => a.path === relPath);if (anchor) {const stem = candidateStem(anchor.lockedFrom);- const fromCandidate = stem ? fromCandidateSidecar(await candidateSidecarFor(recordId, stem), name) : null;+ const fromCandidate = stem ? fromCandidateSidecar(await candidateSidecarFor(recordId, stem), name, derived) : null;return fromCandidate || {- prompt: buildAnchorPrompt({ name, direction: anchor.direction, chromaKey: manifest.chromaKey }),+ // An anchor always locks after the key is frozen, so the frozen key+ // is what its prompt embedded — no default-key caveat here.+ prompt: buildAnchorPrompt({ name, direction: anchor.direction, chromaKey: manifest.chromaKey, ...derived }),designPrompt: null,source: 'reference-anchor',};diff --git a/server/services/sprites/assetPrompt.test.js b/server/services/sprites/assetPrompt.test.jsindex 60372050ae..8c735b26b4 100644--- a/server/services/sprites/assetPrompt.test.js+++ b/server/services/sprites/assetPrompt.test.js@@ -10,7 +10,7 @@ import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';import { mkdtempSync, rmSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';-import { mkdir, writeFile } from 'fs/promises';+import { mkdir, writeFile, rm } from 'fs/promises';import { writeCandidatePng, placeCandidate as placeCandidateFixture } from './spriteTestFixtures.js';const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-assetprompt-test-'));@@ -111,6 +111,70 @@ describe('resolveSpriteAssetPrompt', () => {expect(res.prompt).toContain('walk-south identity reference');});+ it('resolves the locked turnaround sheet through the manifest (#2979)', async () => {+ const id = newId();+ await createCharacter(id);+ await lockReference(id, { target: 'turnaround', candidate: await placeCandidate(id, 'turnaround', 'turnaround-candidate-01.png') });+ const { manifest } = await getReferenceSet(id);++ const res = await resolveSpriteAssetPrompt(id, manifest.turnaround.path);+ expect(res).not.toBeNull();+ expect(res.prompt).toContain('turnaround model sheet');+ expect(res.prompt).toContain('named Hero');+ });++ it('reconstructs a turnaround-candidate prompt when the sidecar predates prompt capture', async () => {+ const id = newId();+ await createCharacter(id);+ const candDir = join(TEST_ROOT, 'sprites', id, 'reference', 'candidates');+ await mkdir(candDir, { recursive: true });+ await writeFile(join(candDir, 'turnaround-candidate-01.generation.json'), JSON.stringify({+ target: 'turnaround', chromaKey: '#00FF00', designPrompt: 'a wiry ranger',+ }));+ const res = await resolveSpriteAssetPrompt(id, 'reference/candidates/turnaround-candidate-01.png');+ expect(res.source).toBe('candidate-reconstructed');+ expect(res.prompt).toContain('turnaround model sheet');+ expect(res.prompt).toContain('a wiry ranger');+ expect(res.prompt).toContain('green (#00FF00)');+ });++ it('rebuilds anchors on a turnaround-first record with the sheet-aware copy', async () => {+ const id = newId();+ await createCharacter(id);+ await lockReference(id, { target: 'turnaround', candidate: await placeCandidate(id, 'turnaround', 'turnaround-candidate-01.png') });+ await lockReference(id, { target: 'main', candidate: await placeCandidate(id, 'main', 'walk-south-candidate-01.png') });+ await lockReference(id, { target: 'east', candidate: await placeCandidate(id, 'east', 'walk-east-candidate-01.png') });+ const { manifest } = await getReferenceSet(id);+ // Drop the source sidecar so the deterministic rebuild is what answers.+ const anchor = manifest.anchors.find((a) => a.id === 'walk-east');+ await rm(join(TEST_ROOT, 'sprites', id, 'reference', 'candidates', 'walk-east-candidate-01.generation.json'));++ const res = await resolveSpriteAssetPrompt(id, anchor.path);+ expect(res.source).toBe('reference-anchor');+ expect(res.prompt).toContain('turnaround model sheet');+ expect(res.prompt).toContain('strict right-facing side profile');+ });++ it('a backfilled sheet rebuilds with the inherited key, not the default', async () => {+ // The sheet did NOT choose the key here — the main lock did, before the+ // backfill — so the sheet was rendered against the already-frozen key.+ const id = newId();+ await createCharacter(id);+ await lockReference(id, { target: 'main', candidate: await placeCandidate(id, 'main', 'walk-south-candidate-01.png', { fg: { r: 255, g: 80, b: 230 }, sidecarKey: '#FF00FF' }), acceptClipRisk: true });+ let manifest = (await getReferenceSet(id)).manifest;+ expect(manifest.chromaKeyAutoSelected).toBe(true);+ const frozen = manifest.chromaKey;+ expect(frozen).not.toBe('#FF00FF'); // auto-selected away from the clash++ await lockReference(id, { target: 'turnaround', candidate: await placeCandidate(id, 'turnaround', 'turnaround-candidate-01.png') });+ manifest = (await getReferenceSet(id)).manifest;+ await rm(join(TEST_ROOT, 'sprites', id, 'reference', 'candidates', 'turnaround-candidate-01.generation.json'));++ const res = await resolveSpriteAssetPrompt(id, manifest.turnaround.path);+ expect(res.source).toBe('reference-turnaround');+ expect(res.prompt).toContain(frozen);+ });+it('main manifest-fallback uses the generation-time default key, not the auto-selected lock key', async () => {// Reproduces the reviewer finding: a non-pinned main is GENERATED against// the default (magenta) key before auto-selection picks green/blue at lock.diff --git a/server/services/sprites/normalize.js b/server/services/sprites/normalize.jsindex 07925499df..5edce272a0 100644--- a/server/services/sprites/normalize.js+++ b/server/services/sprites/normalize.js@@ -182,6 +182,50 @@ export async function normalizeFromAnalysis(analysis, src, dest, canvasKeyHex) {return { side, charW, charH };}+/**+ * Re-key an analyzed image onto `canvasKeyHex` WITHOUT reframing it (issue+ * #2979). Same canvas dimensions, every non-foreground pixel replaced by the+ * canonical key, surviving fringe run through the same decontaminator+ * normalizeFromAnalysis uses.+ *+ * This is the turnaround sheet's lock path: `normalizeFromAnalysis`'s+ * single-figure geometry (character at 80% of a square, feet 7% up) is+ * meaningless for a multi-figure model sheet, but the key swap still matters —+ * the locked sheet is the i2i init image for the main and every anchor, whose+ * prompts name the canonical key, so a sheet still wearing its generation key+ * would contradict the instruction it is attached to.+ *+ * A no-op re-encode when the mask key already equals the canvas key (the+ * decontaminator is null and the fill matches), which is the common case for a+ * legacy record whose key was frozen before the sheet was ever generated.+ */+export async function recompositeOnKey(analysis, src, dest, canvasKeyHex) {+ const { data, width, height, mask, bbox, maskKey } = analysis;+ if (!bbox) {+ await copyFile(src, dest);+ return { copiedThrough: true };+ }+ const fill = hexToRgb(canvasKeyHex);+ const canvas = Buffer.alloc(width * height * 3, Buffer.from([fill.r, fill.g, fill.b]));+ const decon = buildKeyDecontaminator(maskKey, canvasKeyHex);+ for (let p = 0; p < width * height; p++) {+ if (!mask[p]) continue;+ const i = p * 3;+ if (decon) {+ const share = decon.share(data, i);+ canvas[i] = clampByte(data[i] + share * decon.delta[0]);+ canvas[i + 1] = clampByte(data[i + 1] + share * decon.delta[1]);+ canvas[i + 2] = clampByte(data[i + 2] + share * decon.delta[2]);+ } else {+ canvas[i] = data[i];+ canvas[i + 1] = data[i + 1];+ canvas[i + 2] = data[i + 2];+ }+ }+ await sharp(canvas, { raw: { width, height, channels: 3 } }).png().toFile(dest);+ return { width, height };+}+/*** One-shot normalize: mask `src` against the key it was GENERATED on, then* composite onto the SELECTED key. An image with no detectable foregrounddiff --git a/server/services/sprites/normalize.test.js b/server/services/sprites/normalize.test.jsindex 162c5655d7..20e2088e21 100644--- a/server/services/sprites/normalize.test.js+++ b/server/services/sprites/normalize.test.js@@ -10,7 +10,9 @@ import { mkdtempSync, rmSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';import sharp from 'sharp';-import { normalizeAnchorFrame, extractForegroundPalette, hexToRgb } from './normalize.js';+import {+ normalizeAnchorFrame, extractForegroundPalette, hexToRgb, recompositeOnKey, analyzeForeground,+} from './normalize.js';let dir;beforeAll(() => { dir = mkdtempSync(join(tmpdir(), 'sprite-normalize-test-')); });@@ -169,3 +171,76 @@ describe('hexToRgb', () => {expect(() => hexToRgb('red')).toThrow(/Invalid hex/);});});++describe('recompositeOnKey (#2979 — turnaround sheet re-key)', () => {+ it('preserves the original canvas instead of reframing onto a square', async () => {+ // A wide multi-figure sheet: normalizeFromAnalysis would crop to the+ // figures' bbox and rebuild an 80%-height square, which is meaningless for+ // a model sheet. The re-key must leave geometry alone.+ const src = join(dir, 'sheet.png');+ const dest = join(dir, 'sheet-out.png');+ const w = 128; const h = 48;+ const buf = Buffer.alloc(w * h * 3);+ for (let y = 0; y < h; y++) {+ for (let x = 0; x < w; x++) {+ // Four green figures spread across the sheet.+ const inFigure = (x % 32) >= 12 && (x % 32) < 20 && y >= 8 && y < 40;+ const c = inFigure ? GREEN : MAGENTA;+ 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(src);++ const analysis = await analyzeForeground(src, '#FF00FF');+ const result = await recompositeOnKey(analysis, src, dest, '#0000FF');+ expect(result).toMatchObject({ width: w, height: h });++ const img = await readRaw(dest);+ expect(img.width).toBe(w);+ expect(img.height).toBe(h);+ // Background is exactly the new key; every figure pixel survives untouched.+ const at = (x, y) => [img.data[(y * w + x) * 3], img.data[(y * w + x) * 3 + 1], img.data[(y * w + x) * 3 + 2]];+ expect(at(0, 0)).toEqual([0, 0, 255]);+ expect(at(64, 0)).toEqual([0, 0, 255]);+ expect(at(14, 20)).toEqual([0, 255, 0]);+ expect(at(110, 20)).toEqual([0, 255, 0]); // the last panel, not cropped away+ });++ it('decontaminates fringe carrying the old key on a swap', async () => {+ const src = join(dir, 'sheet-fringe.png');+ const dest = join(dir, 'sheet-fringe-out.png');+ await writeFringeCandidate(src);+ const analysis = await analyzeForeground(src, '#FF00FF');+ await recompositeOnKey(analysis, src, dest, '#0000FF');+ const img = await readRaw(dest);+ let magentaTinted = 0;+ for (let p = 0; p < img.width * img.height; p++) {+ const [r, g, b] = [img.data[p * 3], img.data[p * 3 + 1], img.data[p * 3 + 2]];+ if (r === 204 && g === 51 && b === 204) magentaTinted++;+ }+ // The 0.8-magenta blend is shifted toward the new key, not left as a+ // magenta halo around the figure.+ expect(magentaTinted).toBe(0);+ });++ it('is a plain re-encode when the key does not change', async () => {+ const src = join(dir, 'sheet-samekey.png');+ const dest = join(dir, 'sheet-samekey-out.png');+ await writeCandidate(src);+ const analysis = await analyzeForeground(src, '#FF00FF');+ await recompositeOnKey(analysis, src, dest, '#FF00FF');+ const before = await readRaw(src);+ const after = await readRaw(dest);+ expect(after.width).toBe(before.width);+ expect(Buffer.compare(Buffer.from(after.data), Buffer.from(before.data))).toBe(0);+ });++ it('copies through a sheet with no detectable foreground', async () => {+ const src = join(dir, 'sheet-blank.png');+ const dest = join(dir, 'sheet-blank-out.png');+ await writeCandidate(src, { fg: MAGENTA });+ const analysis = await analyzeForeground(src, '#FF00FF');+ expect((await recompositeOnKey(analysis, src, dest, '#00FF00')).copiedThrough).toBe(true);+ });+});diff --git a/server/services/sprites/prompts.js b/server/services/sprites/prompts.jsindex 8c2dca67b0..fde4ec9008 100644--- a/server/services/sprites/prompts.js+++ b/server/services/sprites/prompts.js@@ -53,16 +53,77 @@ export function keyColorPhrase(hex) {return name ? `${name} (${normalized})` : normalized || 'magenta (#FF00FF)';}+// Panels the turnaround sheet carries, left to right (issue #2979). Four+// canonical views — not all eight directions — so each figure keeps enough+// pixels to read: the four three-quarter facings interpolate between adjacent+// panels, and the failure this sheet exists to fix (an accessory teleporting+// between front and back, or swapping sides) is a front/back/left/right+// problem. Order is fixed; the anchor prompt tells the model which panel to+// read a given facing from.+export const TURNAROUND_VIEWS = ['south', 'east', 'north', 'west'];++// How each turnaround panel is described inside the sheet prompt.+const TURNAROUND_PANEL_LABEL = {+ south: 'front view, facing the viewer',+ east: 'right-side profile, facing due east',+ north: 'back view, facing directly away from the viewer (no face)',+ west: 'left-side profile, facing due west',+};++/**+ * Stage-0 prompt (issue #2979): the character turnaround sheet — the identity+ * root every later render descends from. One image, `TURNAROUND_VIEWS.length`+ * panels of the SAME character, so the model that later draws a back or side+ * anchor has actually been shown that side instead of inventing it.+ */+export function buildTurnaroundPrompt({ name, designPrompt, chromaKey }) {+ const description = (typeof designPrompt === 'string' && designPrompt.trim())+ ? designPrompt.trim()+ : 'Use the attached visual reference as the character design.';+ const panels = TURNAROUND_VIEWS+ .map((view, i) => `${i + 1}) ${TURNAROUND_PANEL_LABEL[view] || view}`)+ .join(', ');+ return (+ `Create a character turnaround model sheet for a game character named ${name}. `+ + `Character design: ${description} `+ + `Draw exactly ${TURNAROUND_VIEWS.length} full-body figures of the SAME character in one `+ + `image, evenly spaced left to right in this exact order: ${panels}. `+ + 'Every figure is the identical character in a neutral standing pose, arms relaxed, at '+ + 'the same scale, with feet level on one shared baseline. Identity, proportions, palette, '+ + 'clothing, hairstyle, and accessories must match across all panels, and every accessory '+ + '(bag, strap, pouch, pocket, weapon) must stay on the SAME anatomical side of the body in '+ + 'every panel — an item worn on the character\'s right hip appears on the right hip from '+ + 'the front, from behind, and in both profiles. Flat non-isometric pixel-art game sprite '+ + `reference on a plain exact ${keyColorPhrase(chromaKey)} background. No panel borders, `+ + 'labels, captions, arrows, grid, shadows, scenery, wireframe, or extra characters. '+ + 'Return exactly one PNG.'+ );+}++// Shared preamble for a render seeded from the locked turnaround sheet: the+// init image is a multi-figure sheet, so the model must be told to read ONE+// panel and emit ONE figure — otherwise it happily returns another sheet.+const fromTurnaroundClause = (facing) => (+ `The attached image is a turnaround model sheet showing the same character from `+ + `${TURNAROUND_VIEWS.length} angles. Read the panel that shows the character ${facing}, and `+ + 'take accessory placement (which anatomical side each bag, strap, pouch, or pocket sits on) '+ + 'from the panels that show that side. Do not reproduce the sheet layout: return one single '+ + 'figure, not multiple figures and not panels. '+);+/*** Stage-1 prompt: create the frozen walk-south identity reference from a- * text description and/or an attached visual reference.+ * text description and/or an attached visual reference. `fromTurnaround`+ * switches the copy for the turnaround-first flow (#2979), where the main is+ * derived from the locked sheet like any other direction.*/-export function buildMainReferencePrompt({ name, designPrompt, chromaKey }) {+export function buildMainReferencePrompt({ name, designPrompt, chromaKey, fromTurnaround = false }) {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}. `+ (fromTurnaround ? fromTurnaroundClause(REFERENCE_FACING.south) : '')+ + `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 '@@ -96,19 +157,22 @@ export function buildWalkVideoPrompt({ name, direction, chromaKey }) {}/**- * Stage-2 prompt: derive one directional anchor from the attached frozen- * main reference. `correctionPrompt` is optional free-text the user adds when- * re-rolling a candidate that came out wrong (e.g. "no pocket on the right- * sleeve") — appended as an explicit, high-priority correction so the re-roll- * diverges from the previous render instead of reproducing the same mistake.+ * Stage-2 prompt: derive one directional anchor from the attached reference —+ * the locked turnaround sheet (`fromTurnaround`, the #2979 standard) or, on a+ * legacy record with no sheet, the frozen main. `correctionPrompt` is optional+ * free-text the user adds when re-rolling a candidate that came out wrong (e.g.+ * "no pocket on the right sleeve") — appended as an explicit, high-priority+ * correction so the re-roll diverges from the previous render instead of+ * reproducing the same mistake.*/-export function buildAnchorPrompt({ name, direction, chromaKey, correctionPrompt }) {+export function buildAnchorPrompt({ name, direction, chromaKey, correctionPrompt, fromTurnaround = false }) {const facing = REFERENCE_FACING[direction] || direction;const correction = (typeof correctionPrompt === 'string' && correctionPrompt.trim())? ` Important correction — apply this over the attached reference: ${correctionPrompt.trim()}`: '';return (- `Redraw the attached ${name} character as one `+ (fromTurnaround ? fromTurnaroundClause(facing) : '')+ + `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 'diff --git a/server/services/sprites/prompts.test.js b/server/services/sprites/prompts.test.jsindex e73d6cb3d8..3c1478af2d 100644--- a/server/services/sprites/prompts.test.js+++ b/server/services/sprites/prompts.test.js@@ -1,7 +1,8 @@import { describe, it, expect } from 'vitest';import {SPRITE_DIRECTIONS, ANCHOR_DIRECTIONS, REFERENCE_FACING, anchorIdForDirection,- keyColorPhrase, buildMainReferencePrompt, buildAnchorPrompt,+ keyColorPhrase, buildMainReferencePrompt, buildAnchorPrompt, buildTurnaroundPrompt,+ TURNAROUND_VIEWS,} from './prompts.js';describe('sprite direction contracts', () => {@@ -86,3 +87,69 @@ describe('buildAnchorPrompt', () => {expect(blank).toBe(base);});});++describe('buildTurnaroundPrompt (#2979)', () => {+ it('names every panel in TURNAROUND_VIEWS order and pins accessory sides', () => {+ const p = buildTurnaroundPrompt({ name: 'Scout', designPrompt: 'a wiry ranger', chromaKey: '#00FF00' });+ expect(p).toContain('named Scout');+ expect(p).toContain('a wiry ranger');+ expect(p).toContain(`exactly ${TURNAROUND_VIEWS.length} full-body figures`);+ expect(p).toContain('1) front view, facing the viewer');+ expect(p).toContain('2) right-side profile');+ expect(p).toContain('3) back view');+ expect(p).toContain('4) left-side profile');+ // The constraint the sheet exists to enforce.+ expect(p).toContain('SAME anatomical side');+ expect(p).toContain('green (#00FF00) background');+ });++ it('falls back to the attached reference when no design prompt is given', () => {+ const p = buildTurnaroundPrompt({ name: 'Scout', designPrompt: ' ', chromaKey: '#FF00FF' });+ expect(p).toContain('Use the attached visual reference as the character design.');+ });++ it('panel order matches SPRITE_DIRECTIONS\' cardinal facings', () => {+ // The sheet's four panels are the cardinal directions; the three-quarter+ // facings interpolate between adjacent ones.+ expect(TURNAROUND_VIEWS).toEqual(['south', 'east', 'north', 'west']);+ for (const v of TURNAROUND_VIEWS) expect(SPRITE_DIRECTIONS).toContain(v);+ });+});++describe('fromTurnaround prompt variants (#2979)', () => {+ it('tells an anchor to read one panel and emit one figure', () => {+ const p = buildAnchorPrompt({+ name: 'Scout', direction: 'north', chromaKey: '#FF00FF', fromTurnaround: true,+ });+ expect(p).toContain('turnaround model sheet');+ expect(p).toContain(REFERENCE_FACING.north);+ expect(p).toContain('not multiple figures and not panels');+ // Still carries the base anchor contract.+ expect(p).toContain('magenta (#FF00FF) background');+ });++ it('keeps the correction clause last, after the turnaround preamble', () => {+ const p = buildAnchorPrompt({+ name: 'Scout', direction: 'west', chromaKey: '#FF00FF', fromTurnaround: true,+ correctionPrompt: 'satchel on the left hip',+ });+ expect(p.indexOf('turnaround model sheet')).toBeLessThan(p.indexOf('Important correction'));+ expect(p.trimEnd().endsWith('satchel on the left hip')).toBe(true);+ });++ it('is opt-in — the default stays the legacy single-reference copy', () => {+ const legacy = buildAnchorPrompt({ name: 'Scout', direction: 'east', chromaKey: '#FF00FF' });+ expect(legacy).not.toContain('turnaround model sheet');+ const legacyMain = buildMainReferencePrompt({ name: 'Scout', designPrompt: 'x', chromaKey: '#FF00FF' });+ expect(legacyMain).not.toContain('turnaround model sheet');+ });++ it('points the main at the sheet\'s front panel', () => {+ const p = buildMainReferencePrompt({+ name: 'Scout', designPrompt: 'a wiry ranger', chromaKey: '#FF00FF', fromTurnaround: true,+ });+ expect(p).toContain('turnaround model sheet');+ expect(p).toContain(REFERENCE_FACING.south);+ expect(p).toContain('a wiry ranger');+ });+});diff --git a/server/services/sprites/reference.js b/server/services/sprites/reference.jsindex 8a8f076ab5..d7a3747e3e 100644--- a/server/services/sprites/reference.js+++ b/server/services/sprites/reference.js@@ -33,19 +33,33 @@ import { getSettings } from '../settings.js';import { getRecord, updateRecord, listRecords, createCharacter } from './records.js';import { spriteDir, resolveSpriteAssetPath, listSpriteAssets } from './paths.js';import {- SPRITE_DIRECTIONS, ANCHOR_DIRECTIONS, anchorIdForDirection,- buildMainReferencePrompt, buildAnchorPrompt,+ SPRITE_DIRECTIONS, ANCHOR_DIRECTIONS, anchorIdForDirection, TURNAROUND_VIEWS,+ buildMainReferencePrompt, buildAnchorPrompt, buildTurnaroundPrompt,} from './prompts.js';import { pickChromaKey, keyProximityWarning, CHROMA_KEY_HEXES, DEFAULT_CHROMA_KEY } from './chromaKey.js';-import { analyzeForeground, paletteFromAnalysis, normalizeFromAnalysis } from './normalize.js';+import {+ analyzeForeground, paletteFromAnalysis, normalizeFromAnalysis, recompositeOnKey,+} from './normalize.js';-// 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.+// Default i2i strengths: a render that redraws a NEW figure from the frozen+// sheet (every anchor, and the main in the turnaround-first flow) mostly+// follows the prompt and borrows identity; an uploaded visual reference guides+// the turnaround it seeds 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;+// The turnaround sheet's candidate/asset id — the `anchorIdForDirection`+// analogue for the one reference artifact that has no direction.+const TURNAROUND_ID = 'turnaround';++// Manifests seeded from #2979 onward are turnaround-first: the sheet is the+// identity root, the main descends from it, and so does every anchor. A v1+// manifest was main-first (key frozen at main lock) and keeps that flow — it+// only has to backfill a sheet before deriving further anchors.+const TURNAROUND_FIRST_SCHEMA = 2;+const isTurnaroundFirst = (manifest) => (manifest?.schemaVersion || 1) >= TURNAROUND_FIRST_SCHEMA;+const manifestRelPath = (id) => `reference/${id}-reference-set-v1.json`;// Serialize the manifest read-modify-write per record: two overlapping locks@@ -71,6 +85,10 @@ export async function loadManifest(recordId) {manifest.mainReference.path = rebaseLegacyPath(manifest.mainReference.path, recordId);manifest.mainReference.lockedFrom = rebaseLegacyPath(manifest.mainReference.lockedFrom, recordId);}+ if (manifest.turnaround) {+ manifest.turnaround.path = rebaseLegacyPath(manifest.turnaround.path, recordId);+ manifest.turnaround.lockedFrom = rebaseLegacyPath(manifest.turnaround.lockedFrom, recordId);+ }for (const anchor of manifest.anchors || []) {anchor.path = rebaseLegacyPath(anchor.path, recordId);anchor.lockedFrom = rebaseLegacyPath(anchor.lockedFrom, recordId);@@ -86,20 +104,23 @@ async function saveManifest(recordId, manifest) {function seedManifest(recordId) {return {- schemaVersion: 1,+ schemaVersion: TURNAROUND_FIRST_SCHEMA,manifestId: `${recordId}-reference-set-v1`,- status: 'needs-main-reference',+ status: 'needs-turnaround',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.',+ rule: 'Every reference descends from the frozen turnaround sheet: the main reference is its front view, and every directional anchor is redrawn from the panel that shows that side. Locked artifacts 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,+ turnaround: {+ path: null, role: 'identity-root', background: 'chroma-key', locked: false, views: TURNAROUND_VIEWS,+ },mainReference: { path: null, role: 'immutable-root', background: 'chroma-key', locked: false },anchors: SPRITE_DIRECTIONS.map((direction) => ({id: anchorIdForDirection(direction),kind: 'walk-anchor',direction,status: 'pending',- source: direction === 'south' ? 'main-reference' : 'derive-from-main',+ source: direction === 'south' ? 'main-reference' : 'derive-from-turnaround',})),note: 'walk-south and walk-north double as the front/back idle stills, so no separate idle anchors are kept.',};@@ -156,6 +177,26 @@ function combinedClipWarning(palette, maskKeyHex, canvasKeyHex) {].filter(Boolean).join(' — ') || null;}+/**+ * Which key a lock composites onto, and whether this lock is the one choosing+ * it. Exactly one lock per character freezes the canonical key — the turnaround+ * lock on a turnaround-first record, the main lock on a legacy one — and every+ * lock after it inherits, so a later artifact can never fork the frozen set+ * onto a different background.+ *+ * `alreadyFrozen` is the caller's "a predecessor already locked" signal.+ * Returns `{ frozenKey, pinnedKey, auto, selectedKey }`; `frozenKey` non-null+ * means "inherited — do not touch the manifest's key fields."+ */+function resolveLockKey(manifest, record, palette, alreadyFrozen) {+ const frozenKey = alreadyFrozen ? (manifest.chromaKey || record.chromaKey || DEFAULT_CHROMA_KEY) : null;+ // Case-insensitive pin check: phase-1 accepted any-case hex, so an+ // upgraded record can hold '#00ff00' — that is still a pin, not auto.+ const pinnedKey = CHROMA_KEY_HEXES.find((k) => k === (record.chromaKey || '').toUpperCase()) || null;+ const auto = (frozenKey || pinnedKey) ? null : pickChromaKey(palette);+ return { frozenKey, pinnedKey, auto, selectedKey: frozenKey || pinnedKey || auto.hex };+}+/*** Record patch that is safe against a concurrent lock: a chromaKey change* must re-check the manifest INSIDE the per-record write tail, or a PATCH@@ -167,7 +208,9 @@ export function patchSpriteRecord(recordId, patch) {if (!('chromaKey' in patch)) return updateRecord(recordId, patch);return manifestWriteTail(recordId, async () => {const manifest = await loadManifest(recordId);- if (manifest?.mainReference?.locked) {+ // Either lock can be the one that froze the canonical key: turnaround-first+ // records freeze it at turnaround lock, legacy ones at main lock.+ if (manifest?.mainReference?.locked || manifest?.turnaround?.locked) {throw new ServerError('Chroma key is frozen with the locked reference set', { status: 409, code: 'CHROMA_KEY_LOCKED' });}return updateRecord(recordId, patch);@@ -188,10 +231,13 @@ export async function getReferenceSet(recordId) {const sidecar = await readJSONFile(join(candidatesDir, `${name.replace(/\.png$/, '')}.generation.json`), null);// Sidecarless (crash between copy and sidecar write): infer the target// from the filename so the client can't group it under the wrong slot.- const inferred = /^walk-(.+)-candidate-\d+\.png$/.exec(name)?.[1] || null;+ const inferredDirection = /^walk-(.+)-candidate-\d+\.png$/.exec(name)?.[1] || null;+ const inferred = new RegExp(`^${TURNAROUND_ID}-candidate-\\d+\\.png$`).test(name)+ ? TURNAROUND_ID+ : (inferredDirection === 'south' ? 'main' : inferredDirection);return {path: `reference/candidates/${name}`,- target: sidecar?.target || (inferred === 'south' ? 'main' : inferred),+ target: sidecar?.target || inferred,anchorId: sidecar?.anchorId || null,chromaKey: sidecar?.chromaKey || null,mode: sidecar?.mode || null,@@ -235,55 +281,89 @@ async function startReferenceGenerationImpl(recordId, body, upload = null) {let designReferencePath;let correctionPrompt;- 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 turnaroundLocked = manifest.turnaround?.locked === true;++ if (target === TURNAROUND_ID) {+ if (turnaroundLocked) {+ throw new ServerError('Turnaround sheet is locked — corrections require a new character version, never regeneration', { status: 409, code: 'REFERENCE_LOCKED' });}const designPrompt = typeof body.designPrompt === 'string' ? body.designPrompt.trim() : '';- // A main render needs SOME input: a prompt, an uploaded image, a gallery- // pick, or another sprite's reference to seed from.- const hasInitSource = !!upload || !!body.initImageGalleryFile || !!body.initImageSpriteId;+ // The sheet is the first render, so it needs SOME design input: a prompt,+ // an uploaded image, a gallery pick, another sprite's reference to seed+ // from — or, on a legacy record, the already-locked main it backfills from.+ const backfillFrom = !designPrompt && manifest.mainReference.locked ? manifest.mainReference.path : null;+ const hasInitSource = !!upload || !!body.initImageGalleryFile || !!body.initImageSpriteId || !!backfillFrom;if (!designPrompt && !hasInitSource) {throw new ServerError('Provide a design prompt and/or a reference image', { status: 400, code: 'DESIGN_INPUT_REQUIRED' });}+ anchorId = TURNAROUND_ID;+ prompt = buildTurnaroundPrompt({+ name: record.name,+ designPrompt: designPrompt || manifest.designPrompt,+ chromaKey: genKey,+ });+ ({ initImagePath, designReferencePath } = await resolveSeedSource(recordId, body, upload));+ // Legacy backfill: no explicit seed, but a frozen main exists — expand the+ // one view we already have into the full sheet rather than inventing a new+ // character from text.+ if (!initImagePath && manifest.mainReference.locked) {+ 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' });+ }+ designReferencePath = manifest.mainReference.path;+ }+ if (initImagePath) initImageStrength ??= UPLOAD_DEFAULT_STRENGTH;+ if (designPrompt) manifest.designPrompt = designPrompt;+ // Only the turnaround/main branches mutate (or may have just seeded) the+ // manifest — the anchor branch requires locked predecessors, so its+ // manifest already exists on disk unchanged.+ await saveManifest(recordId, manifest);+ } else 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' });+ }+ // Turnaround-first (#2979): on a manifest seeded under the new standard the+ // main is the sheet's front view, so the sheet must exist first. A legacy+ // v1 manifest predates the sheet and keeps its main-first flow — it only+ // has to backfill a sheet before deriving further anchors.+ if (!turnaroundLocked && isTurnaroundFirst(manifest)) {+ throw new ServerError('Lock the turnaround sheet before deriving the main reference', { status: 409, code: 'TURNAROUND_NOT_LOCKED' });+ }+ const designPrompt = typeof body.designPrompt === 'string' ? body.designPrompt.trim() : '';anchorId = anchorIdForDirection('south');direction = 'south';- prompt = buildMainReferencePrompt({ name: record.name, designPrompt, chromaKey: genKey });- // Resolve the i2i seed image from exactly one source (upload wins, then a- // gallery pick, then another sprite's locked main). `designReferencePath`- // is the provenance marker that rides the tag into the candidate sidecar.- if (upload) {- // Shared temp-import (uuid-prefixed name, EXDEV-safe copy+unlink) — the- // upload persists in the record dir as design provenance so a locked- // candidate stays traceable to the upload that guided it.- const uploadsDir = join(spriteDir(recordId), 'reference', 'uploads');- const { filename } = await importFileToDir(upload.tempPath, upload.originalname || 'design-reference.png', uploadsDir);- initImagePath = join(uploadsDir, filename);- designReferencePath = `reference/uploads/${filename}`;- } else if (body.initImageGalleryFile) {- const resolved = resolveGalleryImage(body.initImageGalleryFile);- if (!resolved) {- throw new ServerError('Reference image not found in the render-history gallery', { status: 400, code: 'INIT_IMAGE_NOT_FOUND' });+ prompt = buildMainReferencePrompt({+ name: record.name,+ designPrompt: designPrompt || manifest.designPrompt,+ chromaKey: genKey,+ fromTurnaround: turnaroundLocked,+ });+ if (turnaroundLocked) {+ initImagePath = await requireLockedTurnaroundPath(recordId, manifest);+ initImageStrength ??= ANCHOR_DEFAULT_STRENGTH;+ } else {+ // Legacy v1 main: a prompt, an uploaded image, a gallery pick, or another+ // sprite's reference — one of them is required.+ const hasInitSource = !!upload || !!body.initImageGalleryFile || !!body.initImageSpriteId;+ if (!designPrompt && !hasInitSource) {+ throw new ServerError('Provide a design prompt and/or a reference image', { status: 400, code: 'DESIGN_INPUT_REQUIRED' });}- initImagePath = resolved;- designReferencePath = `gallery:${body.initImageGalleryFile}`;- } else if (body.initImageSpriteId) {- const sourceMain = await resolveSourceReference(body.initImageSpriteId);- initImagePath = sourceMain.absPath;- designReferencePath = `sprite:${body.initImageSpriteId}/${sourceMain.relPath}`;+ ({ initImagePath, designReferencePath } = await resolveSeedSource(recordId, body, upload));+ if (initImagePath) initImageStrength ??= UPLOAD_DEFAULT_STRENGTH;}- // Every main seed source shares the same default fidelity (anchors use a- // higher one, set in their own branch).- if (initImagePath) initImageStrength ??= UPLOAD_DEFAULT_STRENGTH;if (designPrompt) manifest.designPrompt = designPrompt;- // Only the main branch mutates (or may have just seeded) the manifest —- // the anchor branch requires a locked main, so its manifest already- // exists on disk unchanged.await saveManifest(recordId, manifest);} else {if (!ANCHOR_DIRECTIONS.includes(target)) {throw new ServerError(`Unknown reference target: ${target}`, { status: 400, code: 'INVALID_TARGET' });}+ // The whole point of the sheet: an anchor drawn from a single front view+ // has to invent the side it is facing, which is how a hip bag ends up on+ // the character's back. Required on every record — a legacy one backfills.+ if (!turnaroundLocked) {+ throw new ServerError('Lock the turnaround sheet before deriving directional anchors', { status: 409, code: 'TURNAROUND_NOT_LOCKED' });+ }if (!manifest.mainReference.locked) {throw new ServerError('Lock the main reference before deriving directional anchors', { status: 409, code: 'MAIN_NOT_LOCKED' });}@@ -296,11 +376,10 @@ async function startReferenceGenerationImpl(recordId, body, upload = null) {// Optional user correction re-appended on every re-roll — diverges the// render from the previous candidate rather than reproducing its mistakes.correctionPrompt = typeof body.correctionPrompt === 'string' ? body.correctionPrompt.trim() : '';- prompt = buildAnchorPrompt({ name: record.name, direction, chromaKey: genKey, correctionPrompt });- 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' });- }+ prompt = buildAnchorPrompt({+ name: record.name, direction, chromaKey: genKey, correctionPrompt, fromTurnaround: true,+ });+ initImagePath = await requireLockedTurnaroundPath(recordId, manifest);initImageStrength ??= ANCHOR_DEFAULT_STRENGTH;// Known limitation shared with every i2i surface (proof-as-base, refine):// the WINDOWS local runner (imagine_win.py) has no i2i and drops the@@ -325,7 +404,7 @@ async function startReferenceGenerationImpl(recordId, body, upload = null) {// Destination tag the completion hook files the render by.spriteRef: {recordId, target, direction, anchorId, chromaKey: genKey, mode, model: effectiveModel,- ...(target === 'main' && body.designPrompt ? { designPrompt: body.designPrompt } : {}),+ ...((target === TURNAROUND_ID || target === 'main') && body.designPrompt ? { designPrompt: body.designPrompt } : {}),...(correctionPrompt ? { correctionPrompt } : {}),...(designReferencePath ? { designReferencePath } : {}),},@@ -345,28 +424,80 @@ async function startReferenceGenerationImpl(recordId, body, upload = null) {}/**- * Resolve a source sprite's locked main reference to an on-disk init image.- * Throws (400/500) rather than silently degrading to text-to-image so the- * caller learns the fork/derive source is unusable up front.+ * The locked turnaround sheet as an on-disk init image. Every render that+ * descends from the sheet routes through here so a manifest that claims a lock+ * whose file vanished fails loudly instead of silently degrading to+ * text-to-image (which would reintroduce the invented-sides bug).+ */+async function requireLockedTurnaroundPath(recordId, manifest) {+ const abs = resolveSpriteAssetPath(recordId, manifest.turnaround.path);+ if (!await pathExists(abs)) {+ throw new ServerError('Locked turnaround sheet file is missing on disk', { status: 500, code: 'TURNAROUND_MISSING' });+ }+ return abs;+}++/**+ * Resolve the optional i2i seed image from exactly one source — an upload wins,+ * then a render-history gallery pick, then another sprite's locked reference.+ * Returns `{ initImagePath, designReferencePath }` (both undefined when the+ * caller supplied no seed); `designReferencePath` is the provenance marker that+ * rides the tag into the candidate sidecar.+ */+async function resolveSeedSource(recordId, body, upload) {+ if (upload) {+ // Shared temp-import (uuid-prefixed name, EXDEV-safe copy+unlink) — the+ // upload persists in the record dir as design provenance so a locked+ // candidate stays traceable to the upload that guided it.+ const uploadsDir = join(spriteDir(recordId), 'reference', 'uploads');+ const { filename } = await importFileToDir(upload.tempPath, upload.originalname || 'design-reference.png', uploadsDir);+ return { initImagePath: join(uploadsDir, filename), designReferencePath: `reference/uploads/${filename}` };+ }+ if (body.initImageGalleryFile) {+ const resolved = resolveGalleryImage(body.initImageGalleryFile);+ if (!resolved) {+ throw new ServerError('Reference image not found in the render-history gallery', { status: 400, code: 'INIT_IMAGE_NOT_FOUND' });+ }+ return { initImagePath: resolved, designReferencePath: `gallery:${body.initImageGalleryFile}` };+ }+ if (body.initImageSpriteId) {+ const source = await resolveSourceReference(body.initImageSpriteId);+ return {+ initImagePath: source.absPath,+ designReferencePath: `sprite:${body.initImageSpriteId}/${source.relPath}`,+ };+ }+ return {};+}++/**+ * Resolve a source sprite's best locked reference to an on-disk init image —+ * its turnaround sheet when it has one (all sides, so a fork inherits accessory+ * placement), else its locked main. Throws (400/500) rather than silently+ * degrading to text-to-image so the caller learns the fork/derive source is+ * unusable up front.*/async function resolveSourceReference(sourceId) {- // loadManifest, not getReferenceSet — we only need mainReference, and the- // latter also enumerates + reads every candidate sidecar (wasted here).+ // loadManifest, not getReferenceSet — we only need the locked artifacts, and+ // the latter also enumerates + reads every candidate sidecar (wasted here).const manifest = await loadManifest(sourceId);- const main = manifest?.mainReference;- if (!main?.locked || !main.path) {- throw new ServerError('The source sprite has no locked main reference to seed from', { status: 400, code: 'SOURCE_REFERENCE_MISSING' });+ const best = [manifest?.turnaround, manifest?.mainReference].find((a) => a?.locked && a.path);+ if (!best) {+ throw new ServerError('The source sprite has no locked reference to seed from', { status: 400, code: 'SOURCE_REFERENCE_MISSING' });}- const absPath = resolveSpriteAssetPath(sourceId, main.path);+ const absPath = resolveSpriteAssetPath(sourceId, best.path);if (!await pathExists(absPath)) {throw new ServerError('The source sprite reference file is missing on disk', { status: 500, code: 'SOURCE_REFERENCE_FILE_MISSING' });}- return { absPath, relPath: main.path };+ return { absPath, relPath: best.path };}/**- * List every character whose main reference is locked — the pool that can seed- * a new main (the "select an existing reference sprite" picker) or be forked.+ * List every character with a locked reference to seed from — the pool behind+ * the "select an existing reference sprite" picker and the fork flow. `path` is+ * what a seed actually attaches (the turnaround sheet when there is one, per+ * resolveSourceReference); `turnaroundPath` is non-null when that pick carries+ * all sides, so the client can say so.* Reads each character's manifest (loadManifest, not getReferenceSet — the* candidate enumeration the latter does is wasted here), so it's a per-request* O(characters) scan; fine for a user-triggered modal fetch, revisit if the@@ -378,8 +509,14 @@ export async function listReferenceSources() {for (const r of records) {if (r.kind !== 'character' || r.deleted) continue;const manifest = await loadManifest(r.id);- const main = manifest?.mainReference;- if (main?.locked && main.path) out.push({ id: r.id, name: r.name, kind: r.kind, path: main.path });+ const turnaround = manifest?.turnaround?.locked && manifest.turnaround.path ? manifest.turnaround.path : null;+ const main = manifest?.mainReference?.locked && manifest.mainReference.path ? manifest.mainReference.path : null;+ const path = turnaround || main;+ if (path) {+ out.push({+ id: r.id, name: r.name, kind: r.kind, path, turnaroundPath: turnaround, mainPath: main,+ });+ }}return out;}@@ -416,17 +553,18 @@ export async function listSpriteThumbnails() {}/**- * Fork a new character from an existing sprite's locked main reference: create- * the record, then image+text→image its main from the source reference via the- * shared generate path (`initImageSpriteId`). Validates the source BEFORE- * creating the record so a bad fork never leaves an orphan character behind.- * User-triggered only.+ * Fork a new character from an existing sprite's locked reference: create the+ * record, then image+text→image its TURNAROUND from the source reference via+ * the shared generate path (`initImageSpriteId`) — the fork enters the same+ * turnaround-first workflow every new character does. Validates the source+ * BEFORE creating the record so a bad fork never leaves an orphan character+ * behind. User-triggered only.*/export async function forkSprite(sourceId, body) {await resolveSourceReference(sourceId); // fail fast before creating a recordconst record = await createCharacter({ name: body.name, id: body.id, kind: 'character' });const gen = await startReferenceGeneration(record.id, {- target: 'main',+ target: TURNAROUND_ID,designPrompt: body.designPrompt,initImageSpriteId: sourceId,...(body.mode ? { mode: body.mode } : {}),@@ -519,7 +657,9 @@ async function lockReferenceImpl(recordId, { target, candidate, acceptClipRisk =if (sidecar?.target && sidecar.target !== target) {throw new ServerError(`Candidate was generated for target "${sidecar.target}", not "${target}"`, { status: 400, code: 'CANDIDATE_TARGET_MISMATCH' });}- const expectedPrefix = `${anchorIdForDirection(target === 'main' ? 'south' : target)}-candidate-`;+ const expectedPrefix = target === TURNAROUND_ID+ ? `${TURNAROUND_ID}-candidate-`+ : `${anchorIdForDirection(target === 'main' ? 'south' : target)}-candidate-`;if (!candidate.slice('reference/candidates/'.length).startsWith(expectedPrefix)) {throw new ServerError(`Candidate filename does not match target "${target}" (expected ${expectedPrefix}*)`, { status: 400, code: 'CANDIDATE_TARGET_MISMATCH' });}@@ -528,23 +668,64 @@ async function lockReferenceImpl(recordId, { target, candidate, acceptClipRisk =const maskKey = sidecar?.chromaKey || record.chromaKey || DEFAULT_CHROMA_KEY;const now = new Date().toISOString();- if (target === 'main') {+ if (target === TURNAROUND_ID) {+ if (manifest.turnaround?.locked) {+ throw new ServerError('Turnaround sheet is already locked', { status: 409, code: 'REFERENCE_LOCKED' });+ }+ const analysis = await analyzeForeground(candAbs, maskKey);+ const palette = paletteFromAnalysis(analysis);+ // Turnaround-first records choose the canonical key HERE, off a holistic+ // palette: a key-colored item only visible from behind is counted up front+ // instead of surfacing as a surprise clip 409 at anchor-lock time. A legacy+ // record froze its key at main lock — inherit it, never reselect.+ const { frozenKey, pinnedKey, auto, selectedKey } = resolveLockKey(manifest, record, palette, manifest.mainReference.locked);+ const clipWarning = combinedClipWarning(palette, maskKey, selectedKey);+ if (clipWarning && !acceptClipRisk) {+ throw new ServerError(`${clipWarning}. Re-send with acceptClipRisk to lock anyway.`, { status: 409, code: 'CHROMA_CLIP_RISK' });+ }+ const rel = `reference/${await nextVersionPath(refDir, `${recordId}-${TURNAROUND_ID}`)}`;+ const destAbs = join(spriteDir(recordId), rel);+ // Re-key, don't reframe: the single-figure geometry normalizeFromAnalysis+ // applies is meaningless for a multi-figure sheet, but the sheet is the+ // init image for every later render whose prompt names the canonical key.+ await recompositeOnKey(analysis, candAbs, destAbs, selectedKey);+ const sha256 = await sha256File(destAbs);+ if (!frozenKey) {+ manifest.chromaKey = selectedKey;+ manifest.chromaKeyAutoSelected = !pinnedKey;+ manifest.chromaKeyWarning = [auto?.warning, clipWarning].filter(Boolean).join(' — ') || null;+ }+ manifest.turnaround = {+ ...(manifest.turnaround || {}),+ path: rel,+ role: 'identity-root',+ background: 'chroma-key',+ views: manifest.turnaround?.views || TURNAROUND_VIEWS,+ locked: true,+ lockedFrom: candidate,+ lockedAt: now,+ sha256,+ ...(frozenKey && clipWarning ? { clipWarning } : {}),+ };+ if (!manifest.mainReference.locked) manifest.status = 'needs-main-reference';+ // Record BEFORE manifest, same rationale as the main lock below. A legacy+ // backfill inherits an already-frozen key and an already-set record status,+ // so it touches the record not at all.+ if (!frozenKey) await updateRecord(recordId, { chromaKey: selectedKey, status: 'reference' });+ await saveManifest(recordId, manifest);+ } else 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. One analyzeForeground decode feeds- // the palette and the composite; the palette is computed even when- // pinned because the clip warning below needs it.+ // already pinned a key on the record, or the turnaround lock already froze+ // one (#2979). One analyzeForeground decode feeds the palette and the+ // composite; the palette is computed even when pinned/frozen because the+ // clip warning below needs it.const analysis = await analyzeForeground(candAbs, maskKey);const palette = paletteFromAnalysis(analysis);- // Case-insensitive pin check: phase-1 accepted any-case hex, so an- // upgraded record can hold '#00ff00' — that is still a pin, not auto.- const pinnedKey = CHROMA_KEY_HEXES.find((k) => k === (record.chromaKey || '').toUpperCase()) || null;- const auto = pinnedKey ? null : pickChromaKey(palette);- const selectedKey = pinnedKey || auto.hex;- const userPinned = Boolean(pinnedKey);+ const { frozenKey, pinnedKey, auto, selectedKey } = resolveLockKey(manifest, record, palette, manifest.turnaround?.locked);// Selection only sees pixels that SURVIVED the generation-key mask —// exact-key details (magenta garment on the magenta default) are already// gone from the palette — and a pinned key can collide with the palette@@ -561,9 +742,11 @@ async function lockReferenceImpl(recordId, { target, candidate, acceptClipRisk =const destAbs = join(spriteDir(recordId), rel);await normalizeFromAnalysis(analysis, candAbs, destAbs, selectedKey);const sha256 = await sha256File(destAbs);- manifest.chromaKey = selectedKey;- manifest.chromaKeyAutoSelected = !userPinned;- manifest.chromaKeyWarning = [auto?.warning, clipWarning].filter(Boolean).join(' — ') || null;+ if (!frozenKey) {+ manifest.chromaKey = selectedKey;+ manifest.chromaKeyAutoSelected = !pinnedKey;+ manifest.chromaKeyWarning = [auto?.warning, clipWarning].filter(Boolean).join(' — ') || null;+ }manifest.mainReference = {...manifest.mainReference,path: rel,@@ -572,6 +755,7 @@ async function lockReferenceImpl(recordId, { target, candidate, acceptClipRisk =lockedFrom: candidate,lockedAt: now,sha256,+ ...(frozenKey && clipWarning ? { clipWarning } : {}),};const south = findAnchor(manifest, anchorIdForDirection('south'));if (south) Object.assign(south, { status: 'locked', path: rel, lockedFrom: candidate, sha256 });diff --git a/server/services/sprites/reference.test.js b/server/services/sprites/reference.test.jsindex 03d0d571d4..b65d6e2462 100644--- a/server/services/sprites/reference.test.js+++ b/server/services/sprites/reference.test.js@@ -65,7 +65,35 @@ async function createCharacter(id, input = {}) {const placeCandidate = (recordId, target, name, opts) => placeCandidateFixture(TEST_ROOT, recordId, target, name, opts);+async function lockTurnaround(recordId) {+ const rel = await placeCandidate(recordId, 'turnaround', 'turnaround-candidate-01.png');+ return lockReference(recordId, { target: 'turnaround', candidate: rel });+}++// Walks the turnaround-first order (#2979): the sheet freezes the key, then the+// main descends from it. Anchor tests start from here.async function lockMain(recordId) {+ await lockTurnaround(recordId);+ const rel = await placeCandidate(recordId, 'main', 'walk-south-candidate-01.png');+ return lockReference(recordId, { target: 'main', candidate: rel });+}++// A pre-#2979 record: main-first manifest (schemaVersion 1, no turnaround+// block), written straight to disk the way an install upgraded from phase 2+// would have it, then locked through the legacy main path.+async function legacyLockedMain(recordId) {+ const dir = join(TEST_ROOT, 'sprites', recordId, 'reference');+ await mkdir(dir, { recursive: true });+ await writeFile(join(dir, `${recordId}-reference-set-v1.json`), JSON.stringify({+ schemaVersion: 1,+ manifestId: `${recordId}-reference-set-v1`,+ status: 'needs-main-reference',+ characterFamily: recordId,+ chromaKey: null,+ mainReference: { path: null, role: 'immutable-root', background: 'chroma-key', locked: false },+ anchors: ['south', 'south-east', 'east', 'north-east', 'north', 'north-west', 'west', 'south-west']+ .map((direction) => ({ id: `walk-${direction}`, kind: 'walk-anchor', direction, status: 'pending' })),+ }));const rel = await placeCandidate(recordId, 'main', 'walk-south-candidate-01.png');return lockReference(recordId, { target: 'main', candidate: rel });}@@ -85,18 +113,18 @@ describe('startReferenceGeneration', () => {.rejects.toMatchObject({ code: 'NOT_A_CHARACTER' });});- it('requires a design prompt or upload for the main target', async () => {+ it('requires a design prompt or upload for the turnaround target', async () => {const id = newId();await createCharacter(id);- await expect(startReferenceGeneration(id, { target: 'main' }))+ await expect(startReferenceGeneration(id, { target: 'turnaround' })).rejects.toMatchObject({ code: 'DESIGN_INPUT_REQUIRED' });});- it('queues a main render with the sprite tag and seeds the manifest', async () => {+ it('queues a turnaround 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 result = await startReferenceGeneration(id, { target: 'turnaround', designPrompt: 'a wiry ranger' });+ expect(result).toMatchObject({ jobId: 'job-1234567890', mode: 'codex', target: 'turnaround', anchorId: 'turnaround' });const call = enqueueJob.mock.calls[0][0];expect(call.kind).toBe('image');@@ -105,15 +133,20 @@ describe('startReferenceGeneration', () => {expect(call.params.prompt).toContain('named Hero');expect(call.params.prompt).toContain('a wiry ranger');expect(call.params.prompt).toContain('magenta (#FF00FF)');+ // The panels, in order, and the constraint the sheet exists to enforce.+ expect(call.params.prompt).toContain('1) front view');+ expect(call.params.prompt).toContain('3) back view');+ expect(call.params.prompt).toContain('SAME anatomical side');expect(call.params.spriteRef).toMatchObject({- recordId: id, target: 'main', anchorId: 'walk-south', chromaKey: '#FF00FF',+ recordId: id, target: 'turnaround', anchorId: 'turnaround', chromaKey: '#FF00FF',// Provenance records the model the provider will actually run, not// null on the default path.model: 'gpt-5.6-luna',});const { manifest } = await getReferenceSet(id);- expect(manifest.status).toBe('needs-main-reference');+ expect(manifest.schemaVersion).toBe(2);+ expect(manifest.status).toBe('needs-turnaround');expect(manifest.anchors).toHaveLength(8);expect(manifest.designPrompt).toBe('a wiry ranger');});@@ -123,32 +156,63 @@ describe('startReferenceGeneration', () => {await createCharacter(id);const tmp = join(TEST_ROOT, 'upload-tmp.png');await writeCandidatePng(tmp);- await startReferenceGeneration(id, { target: 'main' }, { tempPath: tmp, originalname: 'concept.png' });+ await startReferenceGeneration(id, { target: 'turnaround' }, { tempPath: tmp, originalname: 'concept.png' });const call = enqueueJob.mock.calls[0][0];expect(call.params.spriteRef.designReferencePath).toMatch(/^reference\/uploads\/.+concept\.png$/);expect(call.params.initImagePath).toContain('/reference/uploads/');expect(call.params.initImageStrength).toBe(0.65);});- it('refuses anchors before the main is locked, and south always', async () => {+ it('refuses the main and anchors before the turnaround is locked, and south always', async () => {const id = newId();await createCharacter(id);- await startReferenceGeneration(id, { target: 'main', designPrompt: 'x' });+ await startReferenceGeneration(id, { target: 'turnaround', designPrompt: 'x' });+ await expect(startReferenceGeneration(id, { target: 'main', designPrompt: 'x' }))+ .rejects.toMatchObject({ code: 'TURNAROUND_NOT_LOCKED', status: 409 });await expect(startReferenceGeneration(id, { target: 'east' }))- .rejects.toMatchObject({ code: 'MAIN_NOT_LOCKED' });+ .rejects.toMatchObject({ code: 'TURNAROUND_NOT_LOCKED', status: 409 });// '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 () => {+ it('refuses anchors between the turnaround lock and the main lock', async () => {+ const id = newId();+ await createCharacter(id);+ await lockTurnaround(id);+ await expect(startReferenceGeneration(id, { target: 'east' }))+ .rejects.toMatchObject({ code: 'MAIN_NOT_LOCKED', status: 409 });+ });++ it('derives the main from the locked turnaround via i2i', async () => {+ const id = newId();+ await createCharacter(id);+ await startReferenceGeneration(id, { target: 'turnaround', designPrompt: 'a wiry ranger' });+ enqueueJob.mockClear();+ await lockTurnaround(id);+ const result = await startReferenceGeneration(id, { target: 'main' });+ expect(result.anchorId).toBe('walk-south');+ const call = enqueueJob.mock.calls[0][0];+ expect(call.params.initImagePath).toContain(`${id}-turnaround-v1.png`);+ expect(call.params.initImageStrength).toBe(0.8);+ expect(call.params.prompt).toContain('turnaround model sheet');+ expect(call.params.prompt).toContain('facing the viewer (front)');+ // The design prompt persists from the turnaround step — the main render+ // still describes the character even though the body carried no prompt.+ expect(call.params.prompt).toContain('a wiry ranger');+ });++ it('derives anchors from the locked turnaround via i2i with the selected key in the prompt', async () => {const id = newId();await createCharacter(id);await lockMain(id);+ enqueueJob.mockClear();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.initImagePath).toContain(`${id}-turnaround-v1.png`);+ expect(call.params.prompt).toContain('turnaround model sheet');+ expect(call.params.prompt).toContain('not multiple figures and not panels');// The queue's providers re-validate initImagePath through the approved// image-input roots — a sprite path must survive that gate or the i2i// silently degrades to text-to-image (identity drift).@@ -282,7 +346,137 @@ describe('attachReferenceCandidate', () => {});});+describe('lockReference — turnaround (#2979)', () => {+ it('locks the sheet: freezes the key off its holistic palette and advances the status', async () => {+ const id = newId();+ await createCharacter(id);+ const result = await lockTurnaround(id);++ expect(result.manifest.turnaround.locked).toBe(true);+ expect(result.manifest.turnaround.path).toBe(`reference/${id}-turnaround-v1.png`);+ expect(result.manifest.turnaround.sha256).toMatch(/^[0-9a-f]{64}$/);+ expect(result.manifest.turnaround.role).toBe('identity-root');+ expect(result.manifest.turnaround.views).toEqual(['south', 'east', 'north', 'west']);+ // The sheet, not the main, is what chooses the canonical key now.+ expect(result.manifest.chromaKey).toBe('#FF00FF'); // green char → magenta kept+ expect(result.manifest.chromaKeyAutoSelected).toBe(true);+ expect(result.manifest.status).toBe('needs-main-reference');+ expect(result.manifest.mainReference.locked).toBe(false);++ const record = await records.getRecord(id);+ expect(record.chromaKey).toBe('#FF00FF');+ expect(record.status).toBe('reference');+ });++ it('re-keys the sheet without reframing it to a single-figure square', async () => {+ const id = newId();+ await createCharacter(id, { chromaKey: '#0000FF' }); // pin, so lock re-keys+ const rel = await placeCandidate(id, 'turnaround', 'turnaround-candidate-01.png');+ await lockReference(id, { target: 'turnaround', candidate: rel });+ // The fixture candidate is 64×64; normalizeFromAnalysis would rebuild it+ // around the 10×30 figure bbox. recompositeOnKey must leave it alone.+ const meta = await sharp(join(TEST_ROOT, 'sprites', id, `reference/${id}-turnaround-v1.png`)).metadata();+ expect([meta.width, meta.height]).toEqual([64, 64]);+ });++ it('409s a clip-risk sheet lock until accepted', async () => {+ const id = newId();+ await createCharacter(id);+ // A magenta-ish character on the magenta generation key: near-key detail is+ // already masked away, so locking it is lossy.+ const rel = await placeCandidate(id, 'turnaround', 'turnaround-candidate-01.png', {+ fg: { r: 255, g: 80, b: 230 }, // pink outfit near the magenta key+ });+ await expect(lockReference(id, { target: 'turnaround', candidate: rel }))+ .rejects.toMatchObject({ status: 409, code: 'CHROMA_CLIP_RISK' });+ const accepted = await lockReference(id, { target: 'turnaround', candidate: rel, acceptClipRisk: true });+ expect(accepted.manifest.turnaround.locked).toBe(true);+ });++ it('409s a relock and enforces the candidate filename prefix', async () => {+ const id = newId();+ await createCharacter(id);+ await lockTurnaround(id);+ const second = await placeCandidate(id, 'turnaround', 'turnaround-candidate-02.png');+ await expect(lockReference(id, { target: 'turnaround', candidate: second }))+ .rejects.toMatchObject({ status: 409, code: 'REFERENCE_LOCKED' });++ const other = newId();+ await createCharacter(other);+ const mismatched = await placeCandidate(other, 'turnaround', 'walk-east-candidate-01.png');+ await expect(lockReference(other, { target: 'turnaround', candidate: mismatched }))+ .rejects.toMatchObject({ status: 400, code: 'CANDIDATE_TARGET_MISMATCH' });+ });++ it('does not reselect the key when the main lock already froze one (legacy backfill)', async () => {+ const id = newId();+ await createCharacter(id);+ await legacyLockedMain(id);+ const before = await getReferenceSet(id);+ expect(before.manifest.schemaVersion).toBe(1);+ expect(before.manifest.chromaKey).toBe('#FF00FF');+ const recordBefore = await records.getRecord(id);++ const result = await lockTurnaround(id);+ expect(result.manifest.turnaround.locked).toBe(true);+ // Key stays exactly as the main lock froze it, and the legacy manifest is+ // NOT silently upgraded to the turnaround-first schema.+ expect(result.manifest.chromaKey).toBe('#FF00FF');+ expect(result.manifest.schemaVersion).toBe(1);+ // A backfill has nothing to say about the record — the main lock set it.+ const recordAfter = await records.getRecord(id);+ expect(recordAfter.chromaKey).toBe(recordBefore.chromaKey);+ expect(recordAfter.status).toBe(recordBefore.status);+ });++ it('unblocks anchor derivation on a legacy record once the sheet is backfilled', async () => {+ const id = newId();+ await createCharacter(id);+ await legacyLockedMain(id);+ await expect(startReferenceGeneration(id, { target: 'east' }))+ .rejects.toMatchObject({ code: 'TURNAROUND_NOT_LOCKED', status: 409 });+ await lockTurnaround(id);+ enqueueJob.mockClear();+ await startReferenceGeneration(id, { target: 'east' });+ const call = enqueueJob.mock.calls[0][0];+ expect(call.params.initImagePath).toContain(`${id}-turnaround-v1.png`);+ expect(call.params.prompt).toContain('turnaround model sheet');+ });++ it('freezes the key against a post-turnaround repin', async () => {+ const id = newId();+ await createCharacter(id);+ await lockTurnaround(id);+ await expect(patchSpriteRecord(id, { chromaKey: '#00FF00' }))+ .rejects.toMatchObject({ status: 409, code: 'CHROMA_KEY_LOCKED' });+ });++ it('groups a sidecarless turnaround candidate under its own target', async () => {+ const id = newId();+ await createCharacter(id);+ const candDir = join(TEST_ROOT, 'sprites', id, 'reference', 'candidates');+ await mkdir(candDir, { recursive: true });+ await writeCandidatePng(join(candDir, 'turnaround-candidate-01.png')); // no sidecar+ const { candidates } = await getReferenceSet(id);+ expect(candidates.find((c) => c.path.endsWith('turnaround-candidate-01.png')).target).toBe('turnaround');+ });+});+describe('lockReference', () => {+ it('does not reselect the key when the sheet already froze one', async () => {+ const id = newId();+ await createCharacter(id);+ await lockTurnaround(id);+ // A magenta-ish main would auto-select AWAY from magenta if the main lock+ // still ran selection — it must inherit the sheet's frozen key instead.+ const rel = await placeCandidate(id, 'main', 'walk-south-candidate-01.png', {+ fg: { r: 255, g: 80, b: 230 },+ });+ const result = await lockReference(id, { target: 'main', candidate: rel, acceptClipRisk: true });+ expect(result.manifest.chromaKey).toBe('#FF00FF');+ expect(result.manifest.mainReference.clipWarning).toMatch(/generation key #FF00FF/);+ });+it('locks the main: normalizes, auto-selects the chroma key, freezes the manifest + record', async () => {const id = newId();await createCharacter(id);@@ -369,7 +563,7 @@ describe('lockReference', () => {it('threads the saved local model into local-mode renders and provenance', async () => {const id = newId();await createCharacter(id);- await startReferenceGeneration(id, { target: 'main', designPrompt: 'x', mode: 'local' });+ await startReferenceGeneration(id, { target: 'turnaround', designPrompt: 'x', mode: 'local' });const call = enqueueJob.mock.calls[0][0];expect(call.params.mode).toBe('local');expect(call.params.modelId).toBe('flux-dev-4bit');@@ -397,9 +591,12 @@ describe('lockReference', () => {expect(manifest.mainReference.path).toBe(`reference/${id}-walk-south-v1.png`);expect(manifest.anchors[0].path).toBe(`reference/${id}-walk-south-v1.png`);- // Anchor derivation must resolve the rebased main as its i2i init.- const result = await startReferenceGeneration(id, { target: 'east' });- expect(result.anchorId).toBe('walk-east');+ // An imported record is main-first with no sheet, so anchors are gated on+ // the backfill — which must resolve the REBASED main as its i2i init.+ await expect(startReferenceGeneration(id, { target: 'east' }))+ .rejects.toMatchObject({ code: 'TURNAROUND_NOT_LOCKED', status: 409 });+ const result = await startReferenceGeneration(id, { target: 'turnaround' });+ expect(result.anchorId).toBe('turnaround');expect(enqueueJob.mock.calls[0][0].params.initImagePath).toBe(join(TEST_ROOT, 'sprites', id, `reference/${id}-walk-south-v1.png`));});@@ -500,14 +697,14 @@ describe('lockReference', () => {});});-describe('main-reference i2i seed sources', () => {- it('seeds the main from a gallery image (initImageGalleryFile)', async () => {+describe('turnaround i2i seed sources', () => {+ it('seeds the turnaround from a gallery image (initImageGalleryFile)', async () => {const id = newId();await createCharacter(id);// resolveGalleryImage resolves a basename under PATHS.images (the test root).const galleryName = 'render-history-pick.png';await writeCandidatePng(join(TEST_ROOT, 'images', galleryName));- await startReferenceGeneration(id, { target: 'main', designPrompt: 'red coat', initImageGalleryFile: galleryName });+ await startReferenceGeneration(id, { target: 'turnaround', designPrompt: 'red coat', initImageGalleryFile: galleryName });const call = enqueueJob.mock.calls[0][0];expect(call.params.initImagePath).toBe(join(TEST_ROOT, 'images', galleryName));expect(call.params.initImageStrength).toBe(0.65);@@ -517,47 +714,69 @@ describe('main-reference i2i seed sources', () => {it('400s a gallery pick that is not in the gallery', async () => {const id = newId();await createCharacter(id);- await expect(startReferenceGeneration(id, { target: 'main', designPrompt: 'x', initImageGalleryFile: 'ghost.png' }))+ await expect(startReferenceGeneration(id, { target: 'turnaround', designPrompt: 'x', initImageGalleryFile: 'ghost.png' })).rejects.toMatchObject({ code: 'INIT_IMAGE_NOT_FOUND', status: 400 });});- it('seeds the main from another sprite\'s locked reference (initImageSpriteId)', async () => {+ it('seeds from another sprite\'s locked turnaround, preferring the sheet over its main', async () => {const source = newId();await createCharacter(source);- await lockMain(source);+ await lockMain(source); // locks the sheet AND the mainconst dest = newId();await createCharacter(dest);enqueueJob.mockClear();- await startReferenceGeneration(dest, { target: 'main', designPrompt: 'now with a hat', initImageSpriteId: source });+ await startReferenceGeneration(dest, { target: 'turnaround', designPrompt: 'now with a hat', initImageSpriteId: source });+ const call = enqueueJob.mock.calls[0][0];+ // The sheet carries every side, so a derive inherits accessory placement.+ expect(call.params.initImagePath).toBe(join(TEST_ROOT, 'sprites', source, `reference/${source}-turnaround-v1.png`));+ expect(call.params.spriteRef.designReferencePath).toBe(`sprite:${source}/reference/${source}-turnaround-v1.png`);+ });++ it('falls back to a legacy source\'s locked main when it has no sheet', async () => {+ const source = newId();+ await createCharacter(source);+ await legacyLockedMain(source);+ const dest = newId();+ await createCharacter(dest);+ enqueueJob.mockClear();+ await startReferenceGeneration(dest, { target: 'turnaround', designPrompt: 'x', initImageSpriteId: source });const call = enqueueJob.mock.calls[0][0];expect(call.params.initImagePath).toBe(join(TEST_ROOT, 'sprites', source, `reference/${source}-walk-south-v1.png`));- expect(call.params.spriteRef.designReferencePath).toBe(`sprite:${source}/reference/${source}-walk-south-v1.png`);});- it('400s seeding from a source with no locked main', async () => {+ it('400s seeding from a source with no locked reference', async () => {const source = newId();await createCharacter(source); // never lockedconst dest = newId();await createCharacter(dest);- await expect(startReferenceGeneration(dest, { target: 'main', designPrompt: 'x', initImageSpriteId: source }))+ await expect(startReferenceGeneration(dest, { target: 'turnaround', designPrompt: 'x', initImageSpriteId: source })).rejects.toMatchObject({ code: 'SOURCE_REFERENCE_MISSING', status: 400 });});});describe('listReferenceSources', () => {- it('returns only characters whose main reference is locked', async () => {+ it('returns characters with a locked reference, preferring the turnaround sheet', async () => {const locked = newId();await createCharacter(locked, { name: 'Locked One' });await lockMain(locked);+ const legacy = newId();+ await createCharacter(legacy, { name: 'Legacy One' });+ await legacyLockedMain(legacy);const draft = newId();- await createCharacter(draft, { name: 'Draft One' }); // no main lock+ await createCharacter(draft, { name: 'Draft One' }); // nothing lockedconst sources = await listReferenceSources();const ids = sources.map((s) => s.id);expect(ids).toContain(locked);+ expect(ids).toContain(legacy);expect(ids).not.toContain(draft);const entry = sources.find((s) => s.id === locked);expect(entry).toMatchObject({ id: locked, name: 'Locked One', kind: 'character' });- expect(entry.path).toContain(`${locked}-walk-south-v1.png`);+ expect(entry.path).toContain(`${locked}-turnaround-v1.png`);+ expect(entry.turnaroundPath).toContain(`${locked}-turnaround-v1.png`);+ // A legacy source is still seedable — it just has no sheet to advertise.+ const legacyEntry = sources.find((s) => s.id === legacy);+ expect(legacyEntry.path).toContain(`${legacy}-walk-south-v1.png`);+ expect(legacyEntry.turnaroundPath).toBeNull();});});@@ -596,13 +815,14 @@ describe('listSpriteThumbnails', () => {});describe('forkSprite', () => {- it('creates a new character and queues its main seeded from the source reference', async () => {+ it('creates a new character and queues its turnaround seeded from the source sheet', async () => {const source = newId();await createCharacter(source, { name: 'Origin' });await lockMain(source);enqueueJob.mockClear();const { record, jobId, target } = await forkSprite(source, { name: 'Origin Fork', designPrompt: 'wearing a red coat' });- expect(target).toBe('main');+ // A fork enters the same turnaround-first workflow every new character does.+ expect(target).toBe('turnaround');expect(jobId).toBe('job-1234567890');expect(record.kind).toBe('character');expect(record.name).toBe('Origin Fork');@@ -610,7 +830,7 @@ describe('forkSprite', () => {expect(await records.getRecord(record.id)).toBeTruthy();const call = enqueueJob.mock.calls[0][0];expect(call.params.spriteRef.recordId).toBe(record.id);- expect(call.params.initImagePath).toBe(join(TEST_ROOT, 'sprites', source, `reference/${source}-walk-south-v1.png`));+ expect(call.params.initImagePath).toBe(join(TEST_ROOT, 'sprites', source, `reference/${source}-turnaround-v1.png`));});it('400s forking a source with no locked main and creates no orphan record', async () => {diff --git a/server/services/sprites/spriteTestFixtures.js b/server/services/sprites/spriteTestFixtures.jsindex 8fa0ac4125..6a5930eaf9 100644--- a/server/services/sprites/spriteTestFixtures.js+++ b/server/services/sprites/spriteTestFixtures.js@@ -38,11 +38,16 @@ export async function placeCandidate(testRoot, recordId, target, name, opts = {}return `reference/candidates/${name}`;}-// Locks 'main' plus every other direction in `directions`, in south-first-// order — the shape shared by walk.test.js's characterWithLockedAnchors and-// atlas.test.js's lockAllAnchors (which only differ in which directions they-// pass and how they name/create the character beforehand).+// Locks the turnaround sheet, then 'main', then every other direction in+// `directions` — the shape shared by walk.test.js's characterWithLockedAnchors+// and atlas.test.js's lockAllAnchors (which only differ in which directions+// they pass and how they name/create the character beforehand). The turnaround+// comes first because anchors are gated on it (#2979).export async function lockAllAnchors(testRoot, recordId, { lockReference, directions }) {+ await lockReference(recordId, {+ target: 'turnaround',+ candidate: await placeCandidate(testRoot, recordId, 'turnaround', 'turnaround-candidate-01.png'),+ });await lockReference(recordId, {target: 'main',candidate: await placeCandidate(testRoot, recordId, 'main', 'walk-south-candidate-01.png'),