Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: allow sprite turnaround regeneration

[._.]/ Adam Eivy45537e5852d7
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index a8cee7917a..bcca0cf1df 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -44,6 +44,7 @@
## Sprite Manager
+- **A locked turnaround can now be reopened and regenerated without losing its history** — if you spot a bad side or inconsistent detail after freezing a character’s turnaround, the Reference Set now offers **Unlock turnaround** behind a confirmation that names the full consequence: because the main reference, all 8 directional anchors, and their walks descend from that sheet, they reopen together. Any approved walks are invalidated before the reference pointers reset, so stale animation cannot survive the revision. The old turnaround, main, anchors, rendered clips, and runtime atlases remain as versioned history; replacements lock at the next `vN` filename. A chroma key PortOS auto-picked for the rejected sheet is chosen afresh, while a key you explicitly pinned stays pinned.
- **[issue-3017] Sprite sheets can now describe an animation that has no facing — the groundwork for animating places and objects** — every animation in a sprite sheet was assumed to be a character walk: eight rows, one per direction. That is wrong for most of what would come next. A tree moving in the wind, water, a flickering lamp — none of them face anywhere, and a sheet that insisted on eight facings for them would be seven-eighths empty with no way to say so. An animation now states whether it is directional, and one with no facing occupies a single row that the published layout file marks as such (`"rows": 1`), so a game reads that one row no matter which way anything is pointing instead of sampling seven blank ones. Everything still ships as **one** sheet per record — a second image would double what a game has to load and bind, and the unused cells compress to almost nothing. The rule that all of a walk's directions must agree on frame count and speed now applies *within* each animation rather than across the whole sheet, so a three-frame ambient loop can sit beside a twelve-frame walk. The other half is the gate: animation was refused outright for anything that wasn't a character, which is why **Places** and **Objects** had no animation path at all — that check now asks which animations a record kind can actually carry, so admitting those kinds becomes a matter of adding the animation rather than unpicking the refusal. To be clear about what this does and doesn't do: it is the sheet-and-publishing groundwork, not a feature you can use yet. No animation that places or objects can carry exists so far, and rendering and approving one is still walk-shaped — that work is tracked separately. Nothing changes for an existing character: walks compile to byte-identical sheets, already-published sheets are untouched until you republish, and the layout file gains the new row field additively.
- **[issue-3021] Walk cycles no longer jitter — the character stays put while only the limbs move** — every frame of a walk was being positioned independently of its neighbours, so the character slid sideways as the arms swung and bobbed up and down when a stray speck of leftover background sat below the feet. Two separate things caused it. First, each frame was horizontally anchored on wherever *its own* hips happened to measure, which drifts as the legs scissor and could flip by a pixel on alternating frames — a walk rendered in place has a fixed hip position by definition, so all frames of a direction now share one. Second, the compiler that builds the final sprite sheet was re-positioning every cell from scratch on a *different* rule than the packer had used (the silhouette's centre rather than the hips), which threw away the alignment and let a swinging arm drag the whole body with it — it now carries the packer's anchor through instead. The feet also now land on the ground line based on the actual sole rather than the single lowest visible pixel, so one leftover speck of background can't lift the body — at both stages, since fixing only the first was silently undone by the second. The standing (idle) pose is anchored the same way as the walk frames now too, so a character no longer pops sideways the moment it starts or stops walking. Feet still sit exactly on the ground line in every frame, so nothing changes for a game using these sheets. Existing walks keep their packed frames until you reprocess them — but simply recompiling one picks up the corrected alignment and saves it as a new atlas version, so you can fix a character's jitter without re-rendering anything.
- **[issue-3020] Reprocessing a walk at a new frame count now updates every preview immediately, instead of showing the old art** — re-deriving a direction from 8 frames to 12 left the loop preview playing a violently jumpy, mis-centered animation: it had already picked up the new 12-frame timing, but your browser was still painting the *previous* 8-frame image, so it stepped 12 times across a picture that only had 8 poses in it. It looked like the sprite had been packed off-center — the packed art was fine all along, and reloading the page fixed it. Every sprite asset's address now carries a fingerprint of its contents, so the moment a reprocess changes the art the loop preview, the Loop Trimmer, and the asset browser and inspector all repaint on their own. That last part matters because the same reprocess also rewrites the individual pose frames and the contrast review sheet — the very things you'd open to check whether the strip really was repacked, which until now kept showing you the pre-reprocess art. This also covers a reprocess that changes the art *without* changing the frame count (a different cycle window, different background-removal settings), which previously went unnoticed entirely — and because the fingerprint only changes when the art does, unchanged assets are still served from cache rather than re-downloaded over Tailscale.
diff --git a/client/src/components/sprites/ReferenceWorkflow.jsx b/client/src/components/sprites/ReferenceWorkflow.jsx
index bf290fc29d..403fd7960e 100644
--- a/client/src/components/sprites/ReferenceWorkflow.jsx
+++ b/client/src/components/sprites/ReferenceWorkflow.jsx
@@ -5,7 +5,8 @@ import {
} from 'lucide-react';
import toast from '../ui/Toast';
import {
- generateSpriteReference, lockSpriteReference, unlockSpriteReferenceAnchor, updateSpriteRecord,
+ generateSpriteReference, lockSpriteReference,
+ unlockSpriteReferenceAnchor, unlockSpriteTurnaround, updateSpriteRecord,
} from '../../services/apiSprites.js';
import { useAsyncAction } from '../../hooks/useAsyncAction.js';
import SpritePreview from './SpritePreview.jsx';
@@ -41,9 +42,9 @@ function SpriteImg({ recordId, path, className }) {
return <SpritePreview recordId={recordId} path={path} className={className} zoomable />;
}
-// Candidate thumbnail with an inline lock confirm (locking is irreversible —
-// per the repo's confirmation UX convention this is an inline confirm row,
-// not a browser dialog or a hidden two-click arm).
+// Candidate thumbnail with an inline lock confirm. Locking freezes this
+// version and its downstream workflow until the relevant explicit unlock, so
+// the consequential action stays visible in an inline confirm row.
function CandidateTile({ recordId, candidate, locking, onLock, clipRisk }) {
const [confirming, setConfirming] = useState(false);
return (
@@ -69,7 +70,7 @@ function CandidateTile({ recordId, candidate, locking, onLock, clipRisk }) {
</div>
) : confirming ? (
<div className="mt-auto flex flex-wrap items-center gap-1 text-xs">
- <span className="text-port-warning">Freeze forever?</span>
+ <span className="text-port-warning">Freeze this version?</span>
<button onClick={() => { setConfirming(false); onLock(candidate); }} disabled={locking} className="px-1.5 py-0.5 bg-port-accent text-white rounded disabled:opacity-50">Lock</button>
<button onClick={() => setConfirming(false)} className="px-1.5 py-0.5 text-gray-400 hover:text-white">Cancel</button>
</div>
@@ -234,6 +235,8 @@ export default function ReferenceWorkflow({ record, reference, renders, correcti
const [galleryOpen, setGalleryOpen] = useState(false);
const [spritePickerOpen, setSpritePickerOpen] = useState(false);
const [forkOpen, setForkOpen] = useState(false);
+ const [turnaroundUnlockConfirming, setTurnaroundUnlockConfirming] = useState(false);
+ useEffect(() => { setTurnaroundUnlockConfirming(false); }, [recordId]);
// Revoke the previous upload's object URL whenever the source changes or the
// component unmounts (cleanup runs with the prior closure).
@@ -319,6 +322,16 @@ export default function ReferenceWorkflow({ record, reference, renders, correcti
onChanged();
}, { errorMessage: 'Failed to unlock anchor' });
+ const [unlockTurnaround, turnaroundUnlocking] = useAsyncAction(async () => {
+ const result = await unlockSpriteTurnaround(recordId, { silent: true });
+ const invalidated = result.walkInvalidatedDirections?.length || 0;
+ toast.success(invalidated
+ ? `Turnaround unlocked; ${invalidated} dependent walks were reopened`
+ : 'Turnaround unlocked; dependent references were reopened');
+ setTurnaroundUnlockConfirming(false);
+ onChanged();
+ }, { errorMessage: 'Failed to unlock turnaround' });
+
const [setChromaKey, keySaving] = useAsyncAction(async (hex) => {
await updateSpriteRecord(recordId, { chromaKey: hex }, { silent: true });
// A key change invalidates any clip-risk warning the user was shown —
@@ -447,8 +460,43 @@ export default function ReferenceWorkflow({ record, reference, renders, correcti
<Lock className="h-3.5 w-3.5" /> Frozen identity root
</p>
<p className="mt-2 text-[11px] leading-relaxed text-gray-500">
- The front, right, back, and left views are fixed. The main reference and every directional anchor derive from this sheet.
+ The front, right, back, and left views are fixed while this version is active. The main reference and every directional anchor derive from this sheet.
</p>
+ {turnaroundUnlockConfirming ? (
+ <div className="mt-3 rounded border border-port-warning/40 bg-port-warning/10 p-2 text-[11px]">
+ <p className="text-port-warning">
+ Reopen the turnaround, main, all 8 anchors, and any approved walks? Existing versioned files stay in history.
+ </p>
+ <div className="mt-2 flex gap-2">
+ <button
+ type="button"
+ aria-label="Confirm unlock turnaround"
+ onClick={unlockTurnaround}
+ disabled={turnaroundUnlocking}
+ className="flex-1 rounded bg-port-warning px-2 py-1.5 font-medium text-black disabled:opacity-50"
+ >
+ {turnaroundUnlocking ? 'Unlocking…' : 'Unlock for regeneration'}
+ </button>
+ <button
+ type="button"
+ onClick={() => setTurnaroundUnlockConfirming(false)}
+ disabled={turnaroundUnlocking}
+ className="rounded px-2 py-1.5 text-gray-400 hover:text-white disabled:opacity-50"
+ >
+ Cancel
+ </button>
+ </div>
+ </div>
+ ) : (
+ <button
+ type="button"
+ onClick={() => setTurnaroundUnlockConfirming(true)}
+ disabled={turnaroundUnlocking}
+ className="mt-3 flex min-h-9 w-full items-center justify-center gap-1.5 rounded border border-port-border bg-port-card px-2.5 py-1.5 text-xs text-gray-300 hover:border-port-warning hover:text-port-warning disabled:opacity-50"
+ >
+ <Unlock className="h-3.5 w-3.5" /> Unlock turnaround
+ </button>
+ )}
</div>
</div>
) : (
@@ -613,10 +661,10 @@ export default function ReferenceWorkflow({ record, reference, renders, correcti
/>
<div className="space-y-3">
<p className="flex items-center gap-1.5 text-xs text-port-success">
- <Lock className="h-3.5 w-3.5" /> Frozen · immutable root
+ <Lock className="h-3.5 w-3.5" /> Frozen · turnaround-derived
</p>
<p className="text-[11px] leading-relaxed text-gray-500">
- This front-facing reference seeds thumbnails and the walk-south identity. Fork to make a new editable version.
+ This front-facing reference seeds thumbnails and the walk-south identity. Fork for a separate character, or reopen the turnaround to rebuild this reference chain.
</p>
<button
type="button"
diff --git a/client/src/components/sprites/ReferenceWorkflow.test.jsx b/client/src/components/sprites/ReferenceWorkflow.test.jsx
index ea06fbe741..a481ded9e5 100644
--- a/client/src/components/sprites/ReferenceWorkflow.test.jsx
+++ b/client/src/components/sprites/ReferenceWorkflow.test.jsx
@@ -6,6 +6,9 @@ vi.mock('../../services/apiSprites.js', () => ({
generateSpriteReference: vi.fn(() => Promise.resolve({ jobId: 'job-1' })),
lockSpriteReference: vi.fn(() => Promise.resolve({})),
unlockSpriteReferenceAnchor: vi.fn(() => Promise.resolve({ walkInvalidated: true })),
+ unlockSpriteTurnaround: vi.fn(() => Promise.resolve({
+ walkInvalidatedDirections: ['south', 'east'],
+ })),
updateSpriteRecord: vi.fn(() => Promise.resolve({})),
}));
@@ -23,7 +26,9 @@ vi.mock('./SpritePreview.jsx', () => ({
}));
import ReferenceWorkflow from './ReferenceWorkflow.jsx';
-import { unlockSpriteReferenceAnchor } from '../../services/apiSprites.js';
+import {
+ unlockSpriteReferenceAnchor, unlockSpriteTurnaround,
+} from '../../services/apiSprites.js';
const DIRECTIONS = ['south', 'south-east', 'east', 'north-east', 'north', 'north-west', 'west', 'south-west'];
@@ -118,4 +123,25 @@ describe('ReferenceWorkflow workspace', () => {
{ silent: true },
);
});
+
+ it('confirms the dependent reset before unlocking a frozen turnaround', async () => {
+ const user = userEvent.setup();
+ unlockSpriteTurnaround.mockClear();
+ renderWorkflow({
+ turnaround: {
+ locked: true,
+ path: 'reference/example-pioneer-turnaround-v1.png',
+ },
+ });
+
+ const turnaround = screen.getByRole('region', { name: 'Turnaround sheet' });
+ await user.click(within(turnaround).getByRole('button', { name: 'Unlock turnaround' }));
+ expect(within(turnaround).getByText(/Reopen the turnaround, main, all 8 anchors/)).toBeInTheDocument();
+
+ await user.click(within(turnaround).getByRole('button', { name: 'Confirm unlock turnaround' }));
+ expect(unlockSpriteTurnaround).toHaveBeenCalledWith(
+ 'example-pioneer',
+ { silent: true },
+ );
+ });
});
diff --git a/client/src/services/apiSprites.js b/client/src/services/apiSprites.js
index 3bba3a7ef7..bc29e50675 100644
--- a/client/src/services/apiSprites.js
+++ b/client/src/services/apiSprites.js
@@ -89,6 +89,13 @@ export const unlockSpriteReferenceAnchor = (id, body, options = {}) => request(`
method: 'POST', body: JSON.stringify(body), ...options,
});
+// Re-open the turnaround identity root and its full dependent chain. Old
+// versioned references, walks, and atlases remain available as history.
+export const unlockSpriteTurnaround = (id, options = {}) => request(
+ `/sprites/${encodeURIComponent(id)}/reference/turnaround/unlock`,
+ { method: 'POST', ...options },
+);
+
// Fork `id` into a new character seeded (image+text→image) from its locked main
// reference. Body: { name, id?, designPrompt, mode?, model?, effort?,
// initImageStrength? }. Returns { record, jobId, mode, target, anchorId }.
diff --git a/server/routes/sprites.js b/server/routes/sprites.js
index a40919bf8b..0559032f83 100644
--- a/server/routes/sprites.js
+++ b/server/routes/sprites.js
@@ -6,7 +6,8 @@
* reference workflow — generate turnaround/main/anchor candidates through the
* shared image-gen queue, review, then lock (normalize + dynamic chroma-key
* selection). Generation is strictly user-triggered per the AI-provider policy;
- * locked artifacts are immutable (409 on regenerate/relock).
+ * locked artifacts are versioned and protected from overwrite; deliberate
+ * unlock actions reopen either one derived anchor or the full turnaround chain.
*/
import { Router } from 'express';
@@ -47,7 +48,8 @@ import { resolveSpriteAssetPrompt } from '../services/sprites/assetPrompt.js';
import { WALK_TRACK, kindSupportsTrack, tracksForKind } from '../services/sprites/animationTracks.js';
import {
getWalkState, startWalkGeneration, approveWalkDirection, rerunWalkPostprocess, unlockWalkSet,
- reopenWalkDirection, setWalkTarget, getWalkSourceFrames, unlockDirectionalAnchor,
+ reopenWalkDirection, setWalkTarget, getWalkSourceFrames,
+ unlockDirectionalAnchor, unlockTurnaroundReference,
} from '../services/sprites/walk.js';
import { saveLoopTrim } from '../services/sprites/walkTrims.js';
import { compileAtlas, getAtlasState } from '../services/sprites/atlas.js';
@@ -164,6 +166,13 @@ router.post('/:id/reference/unlock', asyncHandler(async (req, res) => {
res.json(await unlockDirectionalAnchor(req.params.id, body));
}));
+// Re-open the turnaround identity root for regeneration. This deliberately
+// resets the main, all directional anchors, and every approved dependent walk;
+// versioned files remain on disk as history.
+router.post('/:id/reference/turnaround/unlock', asyncHandler(async (req, res) => {
+ res.json(await unlockTurnaroundReference(req.params.id));
+}));
+
// Fork `:id` into a new character seeded (image+text→image) from its locked
// main reference. Creates the record then queues the main render; returns the
// new record + jobId. User-triggered per the AI-provider policy.
diff --git a/server/routes/sprites.test.js b/server/routes/sprites.test.js
index 0578d2b367..219e233fb6 100644
--- a/server/routes/sprites.test.js
+++ b/server/routes/sprites.test.js
@@ -45,6 +45,11 @@ vi.mock('../services/sprites/walk.js', () => ({
candidates: [],
walkInvalidated: true,
})),
+ unlockTurnaroundReference: vi.fn(async () => ({
+ manifest: { status: 'needs-turnaround' },
+ candidates: [],
+ walkInvalidatedDirections: ['south', 'east'],
+ })),
getWalkSourceFrames: vi.fn(async () => ({
available: true,
reason: null,
@@ -360,6 +365,16 @@ describe('sprites routes', () => {
expect(walk.unlockDirectionalAnchor).toHaveBeenCalledTimes(1);
});
+ it('POST /:id/reference/turnaround/unlock reopens the full dependent chain', async () => {
+ const unlocked = await request(app)
+ .post('/api/sprites/pioneer/reference/turnaround/unlock')
+ .send();
+ expect(unlocked.status).toBe(200);
+ expect(unlocked.body.manifest.status).toBe('needs-turnaround');
+ expect(unlocked.body.walkInvalidatedDirections).toEqual(['south', 'east']);
+ expect(walk.unlockTurnaroundReference).toHaveBeenCalledWith('pioneer');
+ });
+
it('PATCH /:id accepts the three standard chroma keys and null, delegating to the lock-aware patch', async () => {
for (const chromaKey of ['#FF00FF', '#00FF00', '#0000FF', null]) {
const r = await request(app).patch('/api/sprites/pioneer').send({ chromaKey });
diff --git a/server/services/sprites/reference.js b/server/services/sprites/reference.js
index b5fc7b59f7..2c5c33aeb8 100644
--- a/server/services/sprites/reference.js
+++ b/server/services/sprites/reference.js
@@ -14,10 +14,11 @@
* renders into reference/candidates/); locking is deterministic sharp work
* (normalize.js) plus the dynamic chroma-key selection (chromaKey.js).
*
- * Evidence contract: a locked artifact is never regenerated or overwritten.
- * The turnaround and main remain frozen identity roots; a turnaround-derived
- * directional anchor may be deliberately reopened, but its old versioned PNG
- * stays on disk and the replacement lands at the next `-vN` filename.
+ * Evidence contract: a locked artifact is never overwritten. A
+ * turnaround-derived directional anchor may be deliberately reopened on its
+ * own; the turnaround may also be deliberately reopened together with every
+ * artifact that descends from it. In either revision flow the old versioned
+ * PNG stays on disk and the replacement lands at the next `-vN` filename.
*/
import { join } from 'path';
@@ -144,7 +145,7 @@ function seedManifest(recordId) {
status: 'needs-turnaround',
characterFamily: recordId,
projection: 'flat',
- 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. The turnaround and main are immutable identity evidence. A directional anchor can be reopened for correction without overwriting its prior version. Walk cycles are conditioned only on the current locked directional anchor plus the deterministic pose scaffold, never on prior walk output, and the identity root 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. A directional anchor can be reopened alone; the turnaround can be reopened only by also reopening its main, every anchor, and every dependent walk. Prior versioned evidence is never overwritten. Walk cycles are conditioned only on the current locked directional anchor plus the deterministic pose scaffold, never on prior walk output.',
chromaKey: null,
turnaround: {
path: null, role: 'identity-root', background: 'chroma-key', locked: false, views: TURNAROUND_VIEWS,
@@ -369,7 +370,7 @@ async function startReferenceGenerationImpl(recordId, body, upload = null) {
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' });
+ throw new ServerError('Turnaround sheet is locked — unlock the turnaround before regenerating it', { status: 409, code: 'REFERENCE_LOCKED' });
}
// The sheet establishes the character's look, so it needs SOME input: a
// prompt, an uploaded image, a gallery pick, another sprite's reference —
@@ -403,7 +404,7 @@ async function startReferenceGenerationImpl(recordId, body, upload = null) {
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' });
+ throw new ServerError('Main reference is locked — unlock the turnaround to rebuild its dependent reference chain', { status: 409, code: 'REFERENCE_LOCKED' });
}
// The main is always the sheet's front view: a manifest that reaches here
// with no locked sheet was either seeded turnaround-first or upgraded to it
@@ -450,7 +451,7 @@ async function startReferenceGenerationImpl(recordId, body, upload = null) {
anchorId = anchorIdForDirection(direction);
const anchor = findAnchor(manifest, anchorId);
if (anchor?.status === 'locked') {
- throw new ServerError(`Anchor ${anchorId} is locked — locked anchors are immutable`, { status: 409, code: 'REFERENCE_LOCKED' });
+ throw new ServerError(`Anchor ${anchorId} is locked — unlock the anchor before regenerating it`, { status: 409, code: 'REFERENCE_LOCKED' });
}
// Optional user correction re-appended on every re-roll — diverges the
// render from the previous candidate rather than reproducing its mistakes.
@@ -744,6 +745,19 @@ export function unlockReferenceAnchor(recordId, args) {
return manifestWriteTail(recordId, () => unlockReferenceAnchorImpl(recordId, args));
}
+/**
+ * Re-open the turnaround identity root and every reference artifact derived
+ * from it. The walk service coordinates dependent animation invalidation before
+ * calling this write; this layer owns only the reference manifest reset.
+ *
+ * Every old PNG remains on disk. Clearing the active pointers makes the next
+ * lock use `nextVersionPath`, so turnaround/main/anchors advance to v2+ rather
+ * than overwriting the evidence the user rejected.
+ */
+export function unlockReferenceTurnaround(recordId) {
+ return manifestWriteTail(recordId, () => unlockReferenceTurnaroundImpl(recordId));
+}
+
async function loadUnlockableReferenceAnchor(recordId, direction) {
await requireCharacter(recordId);
if (!ANCHOR_DIRECTIONS.includes(direction)) {
@@ -767,6 +781,21 @@ export async function assertReferenceAnchorUnlockable(recordId, { direction }) {
await loadUnlockableReferenceAnchor(recordId, direction);
}
+async function loadUnlockableReferenceTurnaround(recordId) {
+ const record = await requireCharacter(recordId);
+ const manifest = await loadManifest(recordId);
+ if (!manifest?.turnaround?.locked) {
+ throw new ServerError('Turnaround sheet is not locked', { status: 409, code: 'TURNAROUND_NOT_LOCKED' });
+ }
+ return { record, manifest };
+}
+
+// Read-only preflight for the cross-service revision coordinator. Walk
+// approvals are removed before the reference pointers they depend on.
+export async function assertReferenceTurnaroundUnlockable(recordId) {
+ await loadUnlockableReferenceTurnaround(recordId);
+}
+
async function unlockReferenceAnchorImpl(recordId, { direction }) {
const { manifest, anchor } = await loadUnlockableReferenceAnchor(recordId, direction);
Object.assign(anchor, {
@@ -789,6 +818,49 @@ async function unlockReferenceAnchorImpl(recordId, { direction }) {
return getReferenceSet(recordId);
}
+async function unlockReferenceTurnaroundImpl(recordId) {
+ const { record, manifest } = await loadUnlockableReferenceTurnaround(recordId);
+ const autoSelectedKey = manifest.chromaKeyAutoSelected === true;
+
+ manifest.turnaround = {
+ path: null,
+ role: 'identity-root',
+ background: 'chroma-key',
+ locked: false,
+ views: manifest.turnaround?.views || TURNAROUND_VIEWS,
+ };
+ manifest.mainReference = {
+ path: null,
+ role: 'immutable-root',
+ background: 'chroma-key',
+ locked: false,
+ };
+ manifest.anchors = SPRITE_DIRECTIONS.map((direction) => {
+ const previous = findAnchor(manifest, anchorIdForDirection(direction));
+ return {
+ id: anchorIdForDirection(direction),
+ kind: previous?.kind || 'walk-anchor',
+ direction,
+ status: 'pending',
+ source: direction === 'south' ? 'main-reference' : 'derive-from-turnaround',
+ };
+ });
+ manifest.status = 'needs-turnaround';
+ manifest.chromaKey = null;
+ delete manifest.chromaKeyAutoSelected;
+ delete manifest.chromaKeyWarning;
+
+ // Auto-selection belonged to the rejected sheet, so let its replacement pick
+ // afresh. An explicitly pinned key is user input and survives the reset.
+ await updateRecord(recordId, {
+ status: 'reference',
+ ...(autoSelectedKey && record.chromaKey ? { chromaKey: null } : {}),
+ });
+ await saveManifest(recordId, manifest);
+ console.log(`🔓 sprite turnaround ${recordId} unlocked with dependent references reset`);
+ return getReferenceSet(recordId);
+}
+
async function lockReferenceImpl(recordId, { target, candidate, acceptClipRisk = false }) {
const record = await requireCharacter(recordId);
// Seed on demand — a candidate may predate the manifest (e.g. files placed
diff --git a/server/services/sprites/reference.test.js b/server/services/sprites/reference.test.js
index 8ae779a5c8..6f2b869492 100644
--- a/server/services/sprites/reference.test.js
+++ b/server/services/sprites/reference.test.js
@@ -53,7 +53,8 @@ vi.mock('../settings.js', () => ({ getSettings: async () => settings }));
const records = await import('./records.js');
const {
getReferenceSet, startReferenceGeneration, attachReferenceCandidate, lockReference, patchSpriteRecord,
- unlockReferenceAnchor, listReferenceSources, listSpriteThumbnails, forkSprite,
+ unlockReferenceAnchor, unlockReferenceTurnaround,
+ listReferenceSources, listSpriteThumbnails, forkSprite,
requireCharacter, requireAnimatable,
} = await import('./reference.js');
@@ -834,6 +835,58 @@ describe('lockReference', () => {
.rejects.toMatchObject({ status: 409, code: 'ANCHOR_NOT_LOCKED' });
});
+ it('reopens the full turnaround chain, preserves v1 evidence, and relocks the sheet as v2', async () => {
+ const id = newId();
+ await createCharacter(id);
+ const first = await lockMain(id);
+ const eastCandidate = await placeCandidate(id, 'east', 'walk-east-candidate-01.png');
+ const withEast = await lockReference(id, { target: 'east', candidate: eastCandidate });
+ const oldPaths = [
+ withEast.manifest.turnaround.path,
+ first.manifest.mainReference.path,
+ withEast.manifest.anchors.find((anchor) => anchor.direction === 'east').path,
+ ];
+ const oldBytes = await Promise.all(oldPaths.map(
+ (path) => readFile(join(TEST_ROOT, 'sprites', id, path)),
+ ));
+
+ const reopened = await unlockReferenceTurnaround(id);
+ expect(reopened.manifest).toMatchObject({
+ status: 'needs-turnaround',
+ chromaKey: null,
+ turnaround: { locked: false, path: null },
+ mainReference: { locked: false, path: null },
+ });
+ expect(reopened.manifest.anchors).toHaveLength(8);
+ expect(reopened.manifest.anchors.every((anchor) => anchor.status === 'pending')).toBe(true);
+ expect((await records.getRecord(id))).toMatchObject({ status: 'reference', chromaKey: null });
+ for (let i = 0; i < oldPaths.length; i++) {
+ expect(await readFile(join(TEST_ROOT, 'sprites', id, oldPaths[i]))).toEqual(oldBytes[i]);
+ }
+
+ const replacement = await placeCandidate(id, 'turnaround', 'turnaround-candidate-02.png');
+ const relocked = await lockReference(id, { target: 'turnaround', candidate: replacement });
+ expect(relocked.manifest.turnaround.path).toBe(`reference/${id}-turnaround-v2.png`);
+ });
+
+ it('preserves an explicitly pinned chroma key when reopening the turnaround', async () => {
+ const id = newId();
+ await createCharacter(id);
+ await records.updateRecord(id, { chromaKey: '#0000FF' });
+ await lockMain(id);
+
+ const reopened = await unlockReferenceTurnaround(id);
+ expect(reopened.manifest.chromaKey).toBeNull();
+ expect((await records.getRecord(id)).chromaKey).toBe('#0000FF');
+ });
+
+ it('refuses to reopen a turnaround that is not locked', async () => {
+ const id = newId();
+ await createCharacter(id);
+ await expect(unlockReferenceTurnaround(id))
+ .rejects.toMatchObject({ status: 409, code: 'TURNAROUND_NOT_LOCKED' });
+ });
+
it('completes the set when the last anchor locks', async () => {
const id = newId();
await createCharacter(id);
diff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.js
index 7c9b002c27..a36eef9068 100644
--- a/server/services/sprites/walk.js
+++ b/server/services/sprites/walk.js
@@ -36,7 +36,9 @@ import {
rawFramesRelOf, RAW_FRAME_NAME,
} from './paths.js';
import {
- requireCharacter, loadManifest, assertReferenceAnchorUnlockable, unlockReferenceAnchor,
+ requireCharacter, loadManifest,
+ assertReferenceAnchorUnlockable, unlockReferenceAnchor,
+ assertReferenceTurnaroundUnlockable, unlockReferenceTurnaround,
} from './reference.js';
import { SPRITE_DIRECTIONS, anchorIdForDirection, buildWalkVideoPrompt } from './prompts.js';
import {
@@ -1605,6 +1607,33 @@ export async function unlockDirectionalAnchor(recordId, { direction }) {
return { ...reference, walkInvalidated };
}
+/**
+ * Reopen the turnaround and invalidate every approved walk descended from it.
+ *
+ * The reference preflight runs before any dependent state is touched. Approved
+ * walks are then removed under one walk write tail before the reference layer
+ * clears the turnaround, main, and anchor pointers. Old reference PNGs, clips,
+ * packaged strips, and runtime atlases remain as versioned history.
+ */
+export async function unlockTurnaroundReference(recordId) {
+ await assertReferenceTurnaroundUnlockable(recordId);
+ const walkInvalidatedDirections = await invalidateWalkForTurnaroundRevision(recordId);
+ const reference = await unlockReferenceTurnaround(recordId);
+ return { ...reference, walkInvalidatedDirections };
+}
+
+function invalidateWalkForTurnaroundRevision(recordId) {
+ return walkWriteTail(recordId, async () => {
+ const invalidated = [];
+ for (const direction of SPRITE_DIRECTIONS) {
+ if (await invalidateWalkDirectionForAnchorRevisionImpl(recordId, direction)) {
+ invalidated.push(direction);
+ }
+ }
+ return invalidated;
+ });
+}
+
async function invalidateWalkDirectionForAnchorRevisionImpl(recordId, direction) {
await requireCharacter(recordId);
const [walkSet, loaded] = await Promise.all([loadWalkSet(recordId), loadSelection(recordId)]);
diff --git a/server/services/sprites/walk.test.js b/server/services/sprites/walk.test.js
index 55e80e9f2b..806924fa11 100644
--- a/server/services/sprites/walk.test.js
+++ b/server/services/sprites/walk.test.js
@@ -121,7 +121,8 @@ const { listSpriteAssets } = await import('./paths.js');
const { lockReference } = await import('./reference.js');
const {
getWalkState, startWalkGeneration, attachTuiWalkResult, approveWalkDirection, rerunWalkPostprocess, unlockWalkSet,
- reopenWalkDirection, invalidateWalkDirectionForAnchorRevision, unlockDirectionalAnchor,
+ reopenWalkDirection, invalidateWalkDirectionForAnchorRevision,
+ unlockDirectionalAnchor, unlockTurnaroundReference,
setWalkTarget, importedWalkDirections, getWalkSourceFrames,
} = await import('./walk.js');
const { SPRITE_DIRECTIONS, ANCHOR_DIRECTIONS } = await import('./prompts.js');
@@ -989,6 +990,35 @@ describe('invalidateWalkDirectionForAnchorRevision', () => {
const id = await characterWithLockedAnchors(newId(), ['east']);
await expect(invalidateWalkDirectionForAnchorRevision(id, { direction: 'east' })).resolves.toBe(false);
});
+
+ it('reopens the turnaround only after invalidating every dependent approval', async () => {
+ const id = await characterWithLockedAnchors(newId(), ANCHOR_DIRECTIONS);
+ const runIds = {};
+ for (const direction of SPRITE_DIRECTIONS) {
+ const { runId } = await makeCandidateRun(id, direction);
+ runIds[direction] = runId;
+ await approveWalkDirection(id, { direction, runId });
+ }
+
+ const result = await unlockTurnaroundReference(id);
+ const state = await getWalkState(id);
+ expect(result.walkInvalidatedDirections).toEqual(SPRITE_DIRECTIONS);
+ expect(result.manifest).toMatchObject({
+ status: 'needs-turnaround',
+ turnaround: { locked: false, path: null },
+ mainReference: { locked: false, path: null },
+ });
+ expect(result.manifest.anchors.every((anchor) => anchor.status === 'pending')).toBe(true);
+ expect(state.walkSet).toBeNull();
+ expect(state.selection.directions).toEqual({});
+ for (const runId of Object.values(runIds)) {
+ expect(state.runs.find((run) => run.id === runId)).toMatchObject({
+ status: 'superseded-anchor',
+ supersededReason: 'directional-anchor-revised',
+ });
+ }
+ expect((await records.getRecord(id)).status).toBe('reference');
+ });
});
/**