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

refactor([issue-2985]): enforce the cycle target at approve time and cut duplicate reads

[._.]/ Adam Eivyf212b20e5bb1
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index b9ef398acd..a4b65d0a80 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -27,7 +27,7 @@
- **[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.
-- **[issue-2985] A walk set now has one cycle target, and a mismatched render is caught before you spend it** — frame count and playback speed used to be per-render controls, so it was easy to render one direction at 12 frames, nudge the slider, render the next at 8, and only find out eight renders and eight approvals later — when compiling the atlas refused with "reprocess all directions to the same frame count". Those two controls have moved out of the per-render form into a single **Cycle target** for the whole walk set, labeled with where the value came from (locked by the bound app · set target · from the first approved direction · default). Queuing a render or a reprocess that disagrees with the target is now refused up front, naming both values and how to fix it, instead of silently producing an artwork that can never compile. Any already-packaged direction that doesn't match shows a drift badge (with the fix for its situation — reprocess from its clip, reopen it first, or import its source clip), plus a set-level summary line, so an existing mixed set tells you what's wrong the moment you open it rather than at compile time. When a character is bound to a managed app, the app's declared frame count wins and the control goes read-only. The speed control is now labeled **Preview speed** — it drives the preview here and is recorded in the artwork, but the game decides how fast your sprite actually walks.
+- **[issue-2985] A walk set now has one cycle target, and a mismatched render is caught before you spend it** — frame count and playback speed used to be per-render controls, so it was easy to render one direction at 12 frames, nudge the slider, render the next at 8, and only find out eight renders and eight approvals later — when compiling the atlas refused with "reprocess all directions to the same frame count". Those two controls have moved out of the per-render form into a single **Cycle target** for the whole walk set, labeled with where the value came from (locked by the bound app · set target · from the first approved direction · default). Queuing a render or a reprocess that disagrees with the target is now refused up front, naming both values and how to fix it, instead of silently producing an artwork that can never compile. Any already-packaged direction that doesn't match shows a drift badge (with the fix for its situation — reprocess from its clip, reopen it first, or import its source clip), plus a set-level summary line, so an existing mixed set tells you what's wrong the moment you open it rather than at compile time. When a character is bound to a managed app that declares a frame count for its atlas, that value wins and the control goes read-only. The speed control is now labeled **Preview speed** — it drives the preview here and is recorded in the artwork, but the game decides how fast your sprite actually walks.
- **[issue-2977] Loop Trimmer frames now render pixel-crisp** — the frame thumbnails and the playback preview in the Loop Trimmer looked soft and washed-out, as if the artwork had been compressed, which made it impossible to judge a frame before saving a trim. Your artwork was never affected — the trimmer was shrinking each frame to a fraction of its real size to draw it, then blurrily stretching that back up. Frames now draw at their full source resolution with the same crisp pixel scaling every other sprite view uses, so what you review is exactly what gets saved. The transparency checkerboard behind each frame is drawn by the page now instead of being baked into the shrunken frame, so its squares stay crisp and a fixed size rather than coming out blurry and oversized.
- **[issue-2978] Saving a loop trim now works on imported characters** — for a character whose walk cycles came in through the source-pipeline import, the Loop Trimmer would load, scrub, and play the animation perfectly, then fail on **Save trim** with "Packaged run manifest is missing or inconsistent" — after you'd already picked your frames, and with nothing saved. The imported artwork was never damaged; PortOS was simply looking for the packaged manifest under the wrong folder and giving up. Trims now save on imported characters, keep the real gait-phase labels (left-contact, left-passing, …) for each kept frame, and record the correct source strip. A run whose manifest went missing entirely now falls back to the strip's own geometry and still trims, while a manifest that's genuinely corrupt still refuses loudly instead of quietly guessing. The same lookup fixed approving an imported walk direction, which would have failed the same way.
- **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.
diff --git a/client/src/components/sprites/WalkWorkflow.jsx b/client/src/components/sprites/WalkWorkflow.jsx
index c7a0eec933..5f7f453d54 100644
--- a/client/src/components/sprites/WalkWorkflow.jsx
+++ b/client/src/components/sprites/WalkWorkflow.jsx
@@ -133,13 +133,14 @@ function StripLoop({ recordId, stripPreview }) {
);
}
-// Where the resolved target came from, in the user's words. Mirrors the
-// server's describeTargetSource so the label and the 409 message agree.
-const TARGET_SOURCE_LABEL = {
- app: 'locked by the bound app',
- set: 'set target',
- derived: 'from the first approved direction',
- default: 'default',
+// How a drifted direction gets back onto the target, given what it still has
+// behind it. Named rather than inlined as a nested ternary so the three cases
+// read as the decision they are.
+const driftRemedy = ({ approved, hasSourceClip }) => {
+ if (approved) return 'reopen this direction to re-derive it';
+ return hasSourceClip
+ ? 'reprocess it from its clip'
+ : 'import this direction\'s source clip to re-derive it';
};
/**
@@ -164,7 +165,6 @@ function CycleTarget({
}, { errorMessage: 'Could not set the cycle target' });
const cycleSeconds = (target.frameCount / target.fps).toFixed(2);
- const provenance = TARGET_SOURCE_LABEL[target.source] || 'default';
return (
<div className="flex flex-wrap items-center gap-x-3 gap-y-1.5">
@@ -210,8 +210,10 @@ function CycleTarget({
? 'The bound app declares what its atlas may hold — retarget it in the Publish panel below.'
: undefined}
>
- {saving ? 'saving…' : provenance}
- {target.source === 'app' && ` (${target.appId || 'bound app'}) · change it in Publish below`}
+ {/* Provenance wording is stamped by the server (describeTargetSource), so
+ this label and the 409 the user may hit always agree. */}
+ {saving ? 'saving…' : target.sourceLabel || target.source}
+ {target.source === 'app' && ' · change it in Publish below'}
</span>
</div>
);
@@ -279,9 +281,7 @@ function DirectionCard({
{[drift.frameCountDrifts && `${drift.frameCount}f`, drift.fpsDrifts && `${drift.fps}fps`]
.filter(Boolean).join(' · ')} · re-derive to {cycleLabel}
<span className="block text-gray-400">
- {approved ? 'reopen this direction to re-derive it'
- : run?.sourceVideoPath ? 'reprocess it from its clip'
- : 'import this direction\'s source clip to re-derive it'}
+ {driftRemedy({ approved, hasSourceClip: Boolean(run?.sourceVideoPath) })}
</span>
</p>
)}
@@ -369,7 +369,16 @@ function DirectionCard({
<button onClick={() => setConfirming(false)} className="px-1.5 py-0.5 text-gray-400 hover:text-white">No</button>
</div>
) : (
- <button onClick={() => setConfirming(true)} className="w-full px-2 py-0.5 text-xs bg-port-success/20 border border-port-success rounded text-port-success">
+ // Approval is where a direction's geometry gets frozen into the
+ // set the atlas compiles, so a drifted candidate can't be approved
+ // — the server refuses it, and offering the button anyway would
+ // just hand back a 409 after the click.
+ <button
+ onClick={() => setConfirming(true)}
+ disabled={Boolean(drift)}
+ title={drift ? `Re-derive this direction to ${cycleLabel} before approving it` : undefined}
+ className="w-full px-2 py-0.5 text-xs bg-port-success/20 border border-port-success rounded text-port-success disabled:opacity-50"
+ >
Approve
</button>
)
diff --git a/client/src/components/sprites/WalkWorkflow.test.jsx b/client/src/components/sprites/WalkWorkflow.test.jsx
index 1062272a24..0c1f918332 100644
--- a/client/src/components/sprites/WalkWorkflow.test.jsx
+++ b/client/src/components/sprites/WalkWorkflow.test.jsx
@@ -297,8 +297,14 @@ describe('WalkWorkflow authoring controls', () => {
it('labels the target with where the value came from', () => {
renderRun(
{ id: 'walk-east-deadbeef', direction: 'east', status: 'error', postprocessError: 'x' },
- { walkTarget: { frameCount: 8, fps: 12, source: 'derived', drift: [] } },
+ {
+ walkTarget: {
+ frameCount: 8, fps: 12, source: 'derived', sourceLabel: 'from the first approved direction', drift: [],
+ },
+ },
);
+ // The provenance wording is stamped by the server, not re-mapped here, so
+ // the label and the 409 message can never describe the target differently.
expect(screen.getByText('from the first approved direction')).toBeTruthy();
expect(screen.getByRole('combobox', { name: /Cycle target/ }).value).toBe('8');
});
@@ -308,12 +314,18 @@ describe('WalkWorkflow authoring controls', () => {
{ id: 'walk-east-deadbeef', direction: 'east', status: 'error', postprocessError: 'x' },
{
walkTarget: {
- frameCount: 16, fps: 10, source: 'app', frameCountLocked: true, appId: 'example-game', drift: [],
+ frameCount: 16,
+ fps: 10,
+ source: 'app',
+ sourceLabel: 'locked by example-game',
+ frameCountLocked: true,
+ appId: 'example-game',
+ drift: [],
},
},
);
expect(screen.getByRole('combobox', { name: /Cycle target/ }).disabled).toBe(true);
- expect(screen.getByText(/locked by the bound app \(example-game\)/)).toBeTruthy();
+ expect(screen.getByText(/locked by example-game · change it in Publish below/)).toBeTruthy();
// fps is not in the contract, so it stays editable.
expect(screen.getByRole('combobox', { name: /Preview speed/ }).disabled).toBe(false);
});
@@ -359,6 +371,9 @@ describe('WalkWorkflow cycle-target drift', () => {
expect(screen.getByText('reprocess it from its clip')).toBeTruthy();
// …and a set-level summary so it is visible before eight renders are spent.
expect(screen.getByText(/1 of 8 packaged directions differs from the 12f @ 10fps target/)).toBeTruthy();
+ // Approving a drifted candidate would freeze a ragged set the atlas can
+ // never compile — the server refuses it, so the button doesn't offer it.
+ expect(screen.getByRole('button', { name: 'Approve' }).disabled).toBe(true);
});
it('points a drifted direction with no source clip at an import instead', () => {
diff --git a/server/services/sprites/animationTargets.js b/server/services/sprites/animationTargets.js
index b524278471..15eaf0b3bc 100644
--- a/server/services/sprites/animationTargets.js
+++ b/server/services/sprites/animationTargets.js
@@ -32,18 +32,6 @@ import {
/** The only animation track that exists today. */
export const WALK_TRACK = 'walk';
-/**
- * Which `publishBinding.runtimeContract` field pins which knob, per track. The
- * contract is the bound app's declared expectation for its own atlas (#2982) —
- * a stronger authority than any per-render pick — and lands independently of
- * this module, so every read is defensive: an absent contract simply falls
- * through to the next rung of the precedence chain. A future track adds its own
- * row here rather than reshaping the resolver.
- */
-const TRACK_CONTRACT_FIELDS = {
- [WALK_TRACK]: { frameCount: 'walkFrameCount', fps: 'walkFps' },
-};
-
const intInRange = (v, min, max) => (Number.isInteger(v) && v >= min && v <= max ? v : null);
const readFrameCount = (v) => intInRange(v, WALK_MIN_FRAME_COUNT, WALK_MAX_FRAME_COUNT);
const readFps = (v) => intInRange(v, WALK_MIN_FPS, WALK_MAX_FPS);
@@ -69,6 +57,12 @@ const readFps = (v) => intInRange(v, WALK_MIN_FPS, WALK_MAX_FPS);
* `source` names the highest rung that supplied EITHER knob, and
* `frameCountLocked` / `fpsLocked` say precisely which the app nailed down.
*
+ * `track` selects which persisted entry to read. The CONTRACT fields and the
+ * range checks below are walk-specific (the contract declares `walkFrameCount`,
+ * and the bounds come from `walkBounds`) — a second track will need both
+ * generalized at the same time, so parameterizing only one of them today would
+ * be a false promise. The persisted shape is what has to be track-keyed now.
+ *
* @param {object} input
* @param {string} [input.track] Track key (only 'walk' exists today).
* @param {object} [input.runtimeContract] `publishBinding.runtimeContract`, if any.
@@ -84,9 +78,11 @@ export function resolveAnimationTarget({
animationTargets = null,
packagedCycles = [],
} = {}) {
- const fields = TRACK_CONTRACT_FIELDS[track] || {};
- const appCount = fields.frameCount ? readFrameCount(runtimeContract?.[fields.frameCount]) : null;
- const appFps = fields.fps ? readFps(runtimeContract?.[fields.fps]) : null;
+ // The bound app's declared expectation for its own atlas (#2982) — a stronger
+ // authority than any per-render pick. Read defensively: that field lands
+ // independently of this module, so an absent contract just falls through.
+ const appCount = readFrameCount(runtimeContract?.walkFrameCount);
+ const appFps = readFps(runtimeContract?.walkFps);
const pinned = animationTargets?.[track] || null;
const setCount = readFrameCount(pinned?.frameCount);
diff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.js
index 8da2a434cf..689239a7b5 100644
--- a/server/services/sprites/walk.js
+++ b/server/services/sprites/walk.js
@@ -378,26 +378,29 @@ function packagedCyclesFrom(runs, approvedDirections) {
}
/**
- * Resolve the walk track's pinned cycle target for a record, plus the packaged
- * directions that disagree with it. Pure assembly over state the caller already
- * loaded — `getWalkState` stamps the result so the client never re-derives the
- * precedence chain, and the queue-time guards below compare against it.
+ * Resolve the walk track's pinned cycle target, plus the packaged directions
+ * that disagree with it. Pure assembly over state the caller already loaded —
+ * `getWalkState` stamps the result so the client never re-derives the precedence
+ * chain (nor the provenance wording), and the queue-time guards compare against
+ * it. `publishBinding.runtimeContract` is read defensively: it lands with #2982
+ * and may be absent on this install, on an older peer's record, or on any record
+ * with no binding at all.
*/
-async function resolveWalkTargetFor(recordId, { selection, runs, approvedDirections }) {
- // Read the app contract defensively: `publishBinding.runtimeContract` lands
- // with #2982 and may be absent on this install, on an older peer's record, or
- // on any record with no binding at all.
- const record = await getRecord(recordId);
- const packagedCycles = packagedCyclesFrom(runs, approvedDirections);
+function resolveWalkTargetFor({ record, selection, packagedCycles }) {
const target = resolveAnimationTarget({
track: WALK_TRACK,
runtimeContract: record?.publishBinding?.runtimeContract || null,
animationTargets: selection?.animationTargets,
packagedCycles,
});
+ const appId = record?.publishBinding?.appId || null;
return {
...target,
- appId: record?.publishBinding?.appId || null,
+ appId,
+ // Stamped server-side rather than re-mapped in the client, so the label the
+ // user reads and the 409 message they hit can never describe the same
+ // target differently.
+ sourceLabel: describeTargetSource(target, appId),
drift: targetDrift(target, packagedCycles),
};
}
@@ -424,6 +427,10 @@ export async function getWalkState(recordId) {
.then((entries) => entries.filter((e) => e.isDirectory() && e.name.startsWith('walk-')).map((e) => ({ base, name: e.name })))
.catch(() => []))) // dir absent → no runs there yet
.then((lists) => lists.flat());
+ // The record read (for the publish binding's runtime contract) is independent
+ // of everything below — start it here so it overlaps the run resolution
+ // instead of tacking a serial round-trip onto the end of this hot read.
+ const recordPromise = getRecord(recordId);
const [selection, walkSet] = await Promise.all([loadSelection(recordId), loadWalkSet(recordId)]);
const approvedDirections = walkSet?.directions || selection?.directions || {};
@@ -467,8 +474,10 @@ export async function getWalkState(recordId) {
// Stamp the imported flag so the client reads intent (`walkSet.imported`)
// instead of re-deriving the source-pipeline path convention itself.
const stampedWalkSet = walkSet ? { ...walkSet, imported: isImportedWalkSet(walkSet) } : null;
- const walkTarget = await resolveWalkTargetFor(recordId, {
- selection, runs: allRuns, approvedDirections,
+ const walkTarget = resolveWalkTargetFor({
+ record: await recordPromise,
+ selection,
+ packagedCycles: packagedCyclesFrom(allRuns, approvedDirections),
});
return {
runs: allRuns, selection, walkSet: stampedWalkSet, walkTarget,
@@ -486,16 +495,31 @@ export async function getWalkState(recordId) {
* invariant. atlas.js keeps its own compile-time checks as the backstop for
* imported and legacy sets that never passed this gate.
*/
-function assertWalkTargetMatch(target, { frameCount, fps }) {
+function assertWalkTargetMatch(target, { frameCount, fps }, what = 'render') {
if (frameCount === target.frameCount && fps === target.fps) return;
throw new ServerError(
- `This walk set targets ${target.frameCount} frames @ ${target.fps}fps (${describeTargetSource(target, target.appId)}). `
+ `This walk set targets ${target.frameCount} frames @ ${target.fps}fps (${target.sourceLabel}). `
+ `Requested ${frameCount} frames @ ${fps}fps — change the set's cycle target, `
- + `or render at ${target.frameCount} frames @ ${target.fps}fps.`,
+ + `or ${what} at ${target.frameCount} frames @ ${target.fps}fps.`,
{ status: 409, code: 'WALK_TARGET_MISMATCH' },
);
}
+/**
+ * Resolve the geometry ONE render/reprocess will actually pack: an omitted knob
+ * adopts the set target, a supplied one must agree with it, and resolving a
+ * previously-implicit target records it. Shared by both queue paths so the
+ * adopt/enforce/pin contract cannot drift between them.
+ */
+async function resolveRenderGeometry(recordId, { walkTarget, selection }, overrides = {}) {
+ const frameCount = overrides.frameCount === undefined
+ ? walkTarget.frameCount : clampFrameCount(overrides.frameCount);
+ const fps = overrides.fps === undefined ? walkTarget.fps : clampFps(overrides.fps);
+ assertWalkTargetMatch(walkTarget, { frameCount, fps });
+ await pinDerivedWalkTarget(recordId, walkTarget, selection);
+ return { frameCount, fps };
+}
+
/**
* Write an inferred ('derived') target back onto the selection the first time a
* write path resolves one, so the value stops being implicit — the same
@@ -508,12 +532,14 @@ function assertWalkTargetMatch(target, { frameCount, fps }) {
*
* Callers must already hold the per-record write tail.
*/
-async function pinDerivedWalkTarget(recordId, target) {
+async function pinDerivedWalkTarget(recordId, target, loadedSelection) {
if (target.source !== 'derived') return;
// A 'derived' target means the set already HAS packaged geometry, so the walk
// is underway even when no direction is approved yet — seed the selection
- // rather than skipping the pin and letting the target stay implicit.
- const selection = (await loadSelection(recordId)) || seedSelection(recordId);
+ // rather than skipping the pin and letting the target stay implicit. Callers
+ // resolving the target through `getWalkState` already hold the selection;
+ // reuse it rather than re-reading the same file inside the write tail.
+ const selection = loadedSelection || (await loadSelection(recordId)) || seedSelection(recordId);
const pinned = selection.animationTargets?.[WALK_TRACK];
if (pinned?.frameCount === target.frameCount && pinned?.fps === target.fps) return;
selection.animationTargets = withTrackTarget(selection.animationTargets, WALK_TRACK, {
@@ -539,21 +565,27 @@ export function setWalkTarget(recordId, body) {
}
async function setWalkTargetImpl(recordId, { frameCount, fps }) {
- await requireCharacter(recordId);
+ const record = await requireCharacter(recordId);
await requireUnfinalized(recordId);
- const state = await getWalkState(recordId);
- const { walkTarget } = state;
- if (walkTarget.frameCountLocked && walkTarget.frameCount !== frameCount) {
- throw new ServerError(
- `Frame count is locked to ${walkTarget.frameCount} by the publish binding (${walkTarget.appId || 'bound app'}) — change the binding's runtime contract to target ${frameCount}.`,
- { status: 409, code: 'WALK_TARGET_LOCKED' },
- );
- }
- if (walkTarget.fpsLocked && walkTarget.fps !== fps) {
- throw new ServerError(
- `Playback fps is locked to ${walkTarget.fps} by the publish binding (${walkTarget.appId || 'bound app'}) — change the binding's runtime contract to target ${fps}.`,
- { status: 409, code: 'WALK_TARGET_LOCKED' },
- );
+ // Only the app-contract rung can REFUSE a retarget, and that rung is derived
+ // from the record alone — so resolve it directly rather than paying for a full
+ // getWalkState (a two-tree run scan plus every approved direction's manifest)
+ // inside the write tail just to read two booleans.
+ const locked = resolveAnimationTarget({
+ track: WALK_TRACK,
+ runtimeContract: record?.publishBinding?.runtimeContract || null,
+ });
+ const appId = record?.publishBinding?.appId || 'bound app';
+ for (const [knob, label, requested] of [
+ ['frameCount', 'Frame count', frameCount],
+ ['fps', 'Playback fps', fps],
+ ]) {
+ if (locked[`${knob}Locked`] && locked[knob] !== requested) {
+ throw new ServerError(
+ `${label} is locked to ${locked[knob]} by the publish binding (${appId}) — change the binding's runtime contract to target ${requested}.`,
+ { status: 409, code: 'WALK_TARGET_LOCKED' },
+ );
+ }
}
const selection = (await loadSelection(recordId)) || seedSelection(recordId);
// `withTrackTarget` merges rather than replaces so a sibling track key written
@@ -603,17 +635,14 @@ async function startWalkGenerationImpl(recordId, body) {
// second paid grok render for the same direction. Serialized by the write tail,
// so no TOCTOU. getWalkState normalizes a stale 'rendering' run (server died
// mid-render) to 'error', so this blocks only a genuinely live render.
- const { runs: inFlight, walkTarget } = await getWalkState(recordId);
+ const { runs: inFlight, walkTarget, selection } = await getWalkState(recordId);
if (inFlight.some((r) => r.direction === direction && (r.status === 'rendering' || r.status === 'postprocessing'))) {
throw new ServerError(`A walk render for ${direction} is already in progress`, { status: 409, code: 'WALK_RENDER_IN_PROGRESS' });
}
// Cycle geometry is pinned at the SET level (#2985) — every direction in one
// atlas must share it. An omitted count/fps adopts the target; a disagreeing
// one is refused here rather than at atlas-compile time, eight renders later.
- const frameCount = body.frameCount === undefined ? walkTarget.frameCount : clampFrameCount(body.frameCount);
- const fps = body.fps === undefined ? walkTarget.fps : clampFps(body.fps);
- assertWalkTargetMatch(walkTarget, { frameCount, fps });
- await pinDerivedWalkTarget(recordId, walkTarget);
+ const { frameCount, fps } = await resolveRenderGeometry(recordId, { walkTarget, selection }, body);
const anchorAbs = resolveSpriteAssetPath(recordId, anchor.path);
if (!await pathExists(anchorAbs)) {
throw new ServerError('Locked anchor file is missing on disk', { status: 500, code: 'ANCHOR_MISSING' });
@@ -826,7 +855,8 @@ async function rerunWalkPostprocessImpl(recordId, runId, overrides) {
await requireUnfinalized(recordId);
const run = await loadRunRecord(recordId, runId);
if (!run) throw new ServerError(`Unknown walk run: ${runId}`, { status: 404, code: 'RUN_NOT_FOUND' });
- const selection = await loadSelection(recordId);
+ // One state read serves both the immutability check and the target below.
+ const { walkTarget, selection } = await getWalkState(recordId);
if (selection?.directions?.[run.direction]?.runId === runId) {
throw new ServerError('Run is approved — approved runs are immutable', { status: 409, code: 'RUN_APPROVED' });
}
@@ -837,14 +867,10 @@ async function rerunWalkPostprocessImpl(recordId, runId, overrides) {
// Same set-level gate as generation (#2985): a reprocess is exactly how a
// drifted direction is brought INTO line with the target, so it must land on
// the target — not somewhere new. An omitted override adopts the target.
- const { walkTarget } = await getWalkState(recordId);
- const frameCount = overrides.frameCount === undefined ? walkTarget.frameCount : clampFrameCount(overrides.frameCount);
- const fps = overrides.fps === undefined ? walkTarget.fps : clampFps(overrides.fps);
- assertWalkTargetMatch(walkTarget, { frameCount, fps });
- await pinDerivedWalkTarget(recordId, walkTarget);
+ const geometry = await resolveRenderGeometry(recordId, { walkTarget, selection }, overrides);
// Reprocess the SAME on-disk clip at the pinned frame count / playback speed —
// no grok call, no regeneration.
- await packageRun(recordId, run, { frameCount, fps });
+ await packageRun(recordId, run, geometry);
await saveRunRecord(recordId, run);
if (run.status === 'error') {
throw new ServerError(`Postprocess failed: ${run.postprocessError}`, { status: 422, code: 'POSTPROCESS_FAILED' });
@@ -986,8 +1012,8 @@ async function approveWalkDirectionImpl(recordId, { direction, runId }) {
// Frame count / fps are no longer pinned to a single value (variable-frame
// walks) — instead they must fall inside the supported authoring range and the
// declared frameCount must match the actual packed frames. Cross-direction
- // consistency (all approved directions sharing one count/fps) is enforced at
- // atlas-compile time, where the whole set is visible at once.
+ // consistency against the SET target is enforced below (#2985); atlas.js keeps
+ // its own compile-time check as the backstop for imported/legacy sets.
// `loadRunRecord` deliberately returns the RAW record (its results flow into
// saveRunRecord elsewhere, and an imported manifest's bytes are hash-pinned to
// the source), so re-anchor the repo-anchored path here at the point of use
@@ -1019,6 +1045,20 @@ async function approveWalkDirectionImpl(recordId, { direction, runId }) {
throw new ServerError('Packed strip is missing or was modified after packaging', { status: 409, code: 'RUN_STRIP_INVALID' });
}
+ // Approval — not generation — is the moment a direction's geometry gets frozen
+ // into the set the compiler will read, so the target has to hold HERE too. The
+ // queue-time gate alone leaves a real hole: retargeting the set mid-run is a
+ // sanctioned action, so a user could approve one direction at the old target,
+ // retarget, then approve the rest — and only find out at atlas-compile time,
+ // which is exactly the failure this issue exists to move earlier.
+ const { walkTarget, selection: currentSelection } = await getWalkState(recordId);
+ assertWalkTargetMatch(
+ walkTarget,
+ { frameCount: packaged.frameCount, fps: packaged.frameRate },
+ 'reprocess this direction',
+ );
+ await pinDerivedWalkTarget(recordId, walkTarget, currentSelection);
+
const selection = (await loadSelection(recordId)) || seedSelection(recordId);
selection.directions[direction] = {
status: 'approved',
diff --git a/server/services/sprites/walk.test.js b/server/services/sprites/walk.test.js
index 9c0fc14181..9ee2029f9a 100644
--- a/server/services/sprites/walk.test.js
+++ b/server/services/sprites/walk.test.js
@@ -483,6 +483,26 @@ describe('walk cycle target', () => {
expect((await getWalkState(id)).walkTarget).toMatchObject({ source: 'derived' });
});
+ it('409s approving a direction that drifts from the target, so a ragged set can\'t finalize', async () => {
+ // Retargeting mid-set is a sanctioned action, so the queue-time gate alone
+ // leaves a hole: approve one direction at the old target, retarget, approve
+ // the rest, and the ragged set only fails at atlas-compile time — exactly
+ // the failure this issue moves earlier. Approval is where geometry is frozen
+ // into the compiled set, so the target has to hold there too.
+ const id = await characterWithLockedAnchors(newId(), SPRITE_DIRECTIONS);
+ const { runId } = await makeCandidateRun(id, 'south', { frameCount: 12, fps: 10 });
+ await approveWalkDirection(id, { direction: 'south', runId });
+ const { runId: eastId } = await makeCandidateRun(id, 'east', { frameCount: 8, fps: 10 });
+ await expect(approveWalkDirection(id, { direction: 'east', runId: eastId }))
+ .rejects.toMatchObject({
+ code: 'WALK_TARGET_MISMATCH',
+ message: expect.stringContaining('targets 12 frames @ 10fps'),
+ });
+ // The drifted direction stays unapproved rather than half-recorded.
+ const { selection } = await getWalkState(id);
+ expect(selection.directions.east).toBeUndefined();
+ });
+
it('409s a retarget on a finalized set', async () => {
const id = await characterWithLockedAnchors(newId(), SPRITE_DIRECTIONS);
for (const direction of SPRITE_DIRECTIONS) {
@@ -720,6 +740,7 @@ describe('getWalkState', () => {
frameCount: 12,
fps: 10,
source: 'default',
+ sourceLabel: 'default',
frameCountLocked: false,
fpsLocked: false,
appId: null,