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(sprites): make regenerate corrections outrank the prompt's pin-to-reference clauses

[._.]/ Adam Eivydf71db480fd8
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 8175b6ab96..f554b0e408 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -43,6 +43,7 @@
## Fixed
+- **Sprite correction notes are no longer ignored on regenerate.** Typing a correction on a sprite re-roll ("hip bag should be on the other leg") and hitting Regenerate produced a render essentially identical to the one you'd just rejected. The note was being sent — it was losing an argument inside the prompt. Every regenerate prompt spends several sentences pinning the render to the attached reference ("keep accessories on the same anatomical side", "treat the turnaround panels as the source of truth"), and the correction was one trailing sentence asking to change exactly that, phrased as an edit to the *attached* image rather than a fix in the image being produced — so the model sided with the bulk of the prompt. Corrections now frame the render up front, before any preservation rule is read, and close it with an explicit override. Verified on the reported case: the note that had left the sprite unchanged now moves the bag on both samples. A blank note still produces a byte-identical blind regenerate on every surface (turnaround, main, the 7 directional anchors, walk, and every animation track including user-defined ones).
- **The Chief of Staff 3D avatar no longer sometimes renders as an empty glowing ring.** The Cyber Muse and Mini-Character avatars share one loaded 3D model with the CyberCity player avatar, and letting the 3D engine free that model's data when one avatar left the screen left the next one pointing at freed data — so it drew nothing, leaving just the halo ring behind it (which looked like a lone SVG circle). This happened intermittently after switching avatar styles, changing tabs, or visiting CyberCity. Each avatar now keeps the shared model intact when it unmounts, so it reloads cleanly every time.
- **Music Video analysis now finds the beat in guitar-led songs and shows its evidence.** The offline detector uses spectral change instead of whole-track loudness changes, with later-window consensus for quiet or rubato intros. The director timeline now includes a full-song energy waveform, beat/downbeat markers, section energy, time rulers, a clickable overview, and an explicit 4/4-grid assumption instead of presenting an empty “beat-quantized” strip when the cached analysis contains no visible musical information.
- **Music Video final renders now honor the authored song timeline.** Scene clips loop when their generated source is shorter than the beat-aligned cut, so an arrangement can cover the full track instead of being silently truncated to each model's native clip length.
diff --git a/server/services/sprites/animationTrackWorkflow.test.js b/server/services/sprites/animationTrackWorkflow.test.js
index 7c03597399..6d8494a701 100644
--- a/server/services/sprites/animationTrackWorkflow.test.js
+++ b/server/services/sprites/animationTrackWorkflow.test.js
@@ -20,7 +20,7 @@ import { tmpdir } from 'os';
import { join } from 'path';
import { mkdir, writeFile } from 'fs/promises';
import { createHash } from 'crypto';
-import { lockAllAnchors, placeCandidate } from './spriteTestFixtures.js';
+import { lockAllAnchors, placeCandidate, expectCarriesCorrection } from './spriteTestFixtures.js';
const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-track-workflow-test-'));
@@ -212,8 +212,7 @@ describe.each(TRACKS)('the generic workflow drives the $id track', (track) => {
const { runId } = await startTrackGeneration(track.id, id, {
...track.body, correctionPrompt: ` ${track.correction} `,
});
- expect(executeTuiRun.mock.calls[0][0].prompt)
- .toContain(`Important correction — apply this over the attached source image: ${track.correction}`);
+ expectCarriesCorrection(expect, executeTuiRun.mock.calls[0][0].prompt, track.correction);
const { runs } = await getTrackState(track.id, id);
expect(runs.find((r) => r.id === runId).correctionPrompt).toBe(track.correction);
});
diff --git a/server/services/sprites/assetPrompt.js b/server/services/sprites/assetPrompt.js
index 8fa35fa83b..088ce20fbb 100644
--- a/server/services/sprites/assetPrompt.js
+++ b/server/services/sprites/assetPrompt.js
@@ -54,6 +54,9 @@ function fromCandidateSidecar(sidecar, name, fromTurnaround = false, kind = 'cha
// Pre-capture candidate — rebuild with the builder that produced it. The
// sidecar records the re-roll correction whenever one was used (#2964/#3134),
// so the rebuild reproduces the corrected prompt rather than the blind one.
+ // Accepted: a pre-capture candidate that carried a correction rebuilds with
+ // #3216's stronger wording, not the weaker sentence sent. Versioning the clause
+ // would freeze wording we just had to change.
const { designPrompt, chromaKey, correctionPrompt } = sidecar;
let prompt;
if (sidecar.target === TURNAROUND_ID) {
diff --git a/server/services/sprites/assetPrompt.test.js b/server/services/sprites/assetPrompt.test.js
index 18f1724c9c..fae6f12b24 100644
--- a/server/services/sprites/assetPrompt.test.js
+++ b/server/services/sprites/assetPrompt.test.js
@@ -11,7 +11,7 @@ import { mkdtempSync, rmSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { mkdir, writeFile, rm } from 'fs/promises';
-import { writeCandidatePng, placeCandidate as placeCandidateFixture } from './spriteTestFixtures.js';
+import { writeCandidatePng, placeCandidate as placeCandidateFixture, expectCarriesCorrection } from './spriteTestFixtures.js';
const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-assetprompt-test-'));
@@ -293,8 +293,7 @@ describe('resolveSpriteAssetPrompt', () => {
const res = await resolveSpriteAssetPrompt(id, 'runs/walk-east-abc12345/generated/source-video.mp4');
expect(res.source).toBe('walk');
- expect(res.prompt)
- .toContain('Important correction — apply this over the attached source image: the legs barely lift');
+ expectCarriesCorrection(expect, res.prompt, 'the legs barely lift');
});
it('rebuilds a corrected reference candidate with its correction clause (#3134)', async () => {
@@ -311,8 +310,7 @@ describe('resolveSpriteAssetPrompt', () => {
const res = await resolveSpriteAssetPrompt(id, 'reference/candidates/walk-east-candidate-03.png');
expect(res.source).toBe('candidate-reconstructed');
- expect(res.prompt)
- .toContain('Important correction — apply this over the attached reference: no pocket on the right sleeve');
+ expectCarriesCorrection(expect, res.prompt, 'no pocket on the right sleeve');
});
it('returns null for an asset with no prompt provenance', async () => {
diff --git a/server/services/sprites/prompts.js b/server/services/sprites/prompts.js
index 0bafdfa645..13730a609e 100644
--- a/server/services/sprites/prompts.js
+++ b/server/services/sprites/prompts.js
@@ -138,22 +138,69 @@ export function viewGeometryClause(direction) {
// target vocabulary so validation.js and the services share one spelling.
export const TURNAROUND_ID = 'turnaround';
+// --- Corrections (#2964 / #3134, made to actually land by #3216) -------------
+//
+// `subject` names the ATTACHED image/clip the render derives from ("turnaround",
+// "reference", "source image") so each surface reads naturally while the
+// instruction shape stays identical everywhere.
+//
+// Why the original single trailing sentence didn't work: every body pins the
+// render to the attachment — an anchor does it in three separate sentences ("keep
+// accessories/straps on the same anatomical side as the attached reference",
+// "treat the turnaround panels as the source of truth", plus the per-facing
+// occlusion rule). A note asking to CHANGE one of those ("hip bag should be on
+// the other leg") contradicts the bulk of the prompt, and the model sided with
+// the bulk: the corrected re-roll came back identical to the candidate the user
+// had just rejected. Two things were needed, both of them:
+//
+// 1. State precedence. Position last is not authority.
+// 2. Target the OUTPUT. "Apply this over the attached reference" pointed the
+// model at a frozen, usually-correct sheet — inviting "nothing to do". The
+// user is describing a defect in the PREVIOUS RENDER.
+//
+// So the note is stated twice: a lead-in that frames the render before any
+// preservation rule is read, and a closing override. One mention buried in a
+// ~200-word instruction is exactly what got ignored.
+//
+// If this ever stops holding, the next step is structural, NOT a third round of
+// stronger adjectives: suppress the body clauses the note contradicts (compare
+// `refineComicPageRender` in services/pipeline/comicPages.js, which merges the
+// user's instruction into the stored prompt so no clause disagrees with it).
+
+// Users type notes as fragments, and both halves quote the note mid-paragraph, so
+// terminate it — otherwise it runs into the next sentence ("…other leg Make that
+// fix…") and the boundary between the user's words and ours disappears.
+const asSentence = (note) => (/[.!?]$/.test(note) ? note : `${note}.`);
+
+const leadInFor = (note, subject) => (
+ 'This is a corrected re-render: a previous attempt at this exact image was rejected. '
+ + `Required fix: ${note} Make that fix in the image you produce. It takes priority over any `
+ + `instruction below to match or preserve the attached ${subject} — change what the fix names, `
+ + 'and keep everything else identical. '
+);
+
+const overrideFor = (note, subject) => (
+ ` Required fix (highest priority — this overrides any conflicting instruction above): ${note}`
+ + ' The previous render was rejected for exactly this, so an image that does not visibly'
+ + ' reflect this fix is a failed render. Change only what the fix names; everything it does'
+ + ` not mention stays as the attached ${subject} shows it.`
+);
+
/**
- * The one appended clause that turns a blind re-roll into a corrected one
- * (#2964, extended to every surface by #3134). `subject` names what the model is
- * being corrected ON — the noun of whatever image/clip is attached ("turnaround",
- * "reference", "source image") — so each surface reads naturally while the
- * instruction shape stays identical everywhere.
+ * Wrap a built prompt body in the correction sandwich — the ONLY way a builder
+ * takes a correction. The two halves stay private so a surface cannot ship with
+ * one of them wired and not the other; that half-wired state is precisely what
+ * reads to the user as "the model ignored my feedback".
*
- * Returns `''` for absent/blank input, which is the hard contract every caller
- * depends on: a whitespace-only note must leave the prompt byte-identical to
- * today's blind regenerate. Callers append the result LAST so the correction
- * reads as an override of the base clauses rather than one more of them.
+ * An absent, blank, or non-string note returns `body` untouched. That is the hard
+ * contract every surface depends on: a whitespace-only note must leave the prompt
+ * byte-identical to a blind regenerate.
*/
-export function correctionClause(correctionPrompt, subject) {
- return (typeof correctionPrompt === 'string' && correctionPrompt.trim())
- ? ` Important correction — apply this over the attached ${subject}: ${correctionPrompt.trim()}`
- : '';
+export function applyCorrection(body, correctionPrompt, subject) {
+ const raw = typeof correctionPrompt === 'string' ? correctionPrompt.trim() : '';
+ if (!raw) return body;
+ const note = asSentence(raw);
+ return leadInFor(note, subject) + body + overrideFor(note, subject);
}
/**
@@ -179,8 +226,7 @@ export function buildTurnaroundPrompt({ name, designPrompt, chromaKey, correctio
const panelRules = TURNAROUND_VIEWS
.map((view, i) => `Panel ${i + 1} (${REFERENCE_FACING[view] || view}): ${viewGeometryClause(view)}`)
.join(' ');
- const correction = correctionClause(correctionPrompt, 'turnaround');
- return (
+ return applyCorrection(
`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 `
@@ -209,8 +255,9 @@ export function buildTurnaroundPrompt({ name, designPrompt, chromaKey, correctio
+ 'Flat non-isometric pixel-art game sprite '
+ `reference on a plain exact ${keyColorPhrase(chromaKey)} background on a square 1:1 canvas. No panel borders, `
+ 'labels, captions, arrows, grid, shadows, scenery, wireframe, or extra characters. '
- + 'Return exactly one PNG.'
- + correction
+ + 'Return exactly one PNG.',
+ correctionPrompt,
+ 'turnaround',
);
}
@@ -266,11 +313,7 @@ export function buildMainReferencePrompt({ name, designPrompt, chromaKey, correc
const description = (typeof designPrompt === 'string' && designPrompt.trim())
? designPrompt.trim()
: 'Use the attached visual reference as the character design.';
- // The main derives from the sheet when there is one, so name the sheet as
- // what the correction applies OVER; a legacy record has only its own
- // reference attached.
- const correction = correctionClause(correctionPrompt, fromTurnaround ? 'turnaround' : 'reference');
- return (
+ return applyCorrection(
(fromTurnaround ? fromTurnaroundClause('south') : '')
+ `Create the frozen walk-south identity reference for a game character named ${name}. `
+ `Character direction: ${description} `
@@ -279,8 +322,12 @@ export function buildMainReferencePrompt({ name, designPrompt, chromaKey, correc
+ 'attached visual reference when provided. Preserve physical-left and physical-right '
+ `accessories exactly. ${geometryRule('south')}Flat non-isometric pixel-art game sprite reference, centered on `
+ `a plain exact ${keyColorPhrase(chromaKey)} background on a square 1:1 canvas. No motion, labels, grid, shadows, scenery, `
- + 'wireframe, or extra figures. Return exactly one PNG.'
- + correction
+ + 'wireframe, or extra figures. Return exactly one PNG.',
+ correctionPrompt,
+ // The main derives from the sheet when there is one, so name the sheet as
+ // the attachment the untouched details come from; a legacy record has only
+ // its own reference attached.
+ fromTurnaround ? 'turnaround' : 'reference',
);
}
@@ -295,12 +342,13 @@ export function buildAmbientReferencePrompt({ name, kind, designPrompt, chromaKe
const description = (typeof designPrompt === 'string' && designPrompt.trim())
? designPrompt.trim()
: 'Use the attached visual reference as the design.';
- return (
+ return applyCorrection(
`Create one centered game-sprite ${kind} named ${name}. Design: ${description} `
+ 'Show its at-rest state with a clear readable silhouette. Match the attached visual reference when provided. '
+ `Use a plain exact ${keyColorPhrase(chromaKey)} background on a square 1:1 canvas. No people, scenery, text, labels, grid, `
- + 'camera angle, shadows, wireframe, or extra objects. Return exactly one PNG.'
- + correctionClause(correctionPrompt, 'reference')
+ + 'camera angle, shadows, wireframe, or extra objects. Return exactly one PNG.',
+ correctionPrompt,
+ 'reference',
);
}
@@ -311,13 +359,14 @@ export function buildAmbientReferencePrompt({ name, kind, designPrompt, chromaKe
* trunk") so a re-roll diverges instead of reproducing it.
*/
export function buildAmbientVideoPrompt({ name, kind, chromaKey, correctionPrompt }) {
- return (
+ return applyCorrection(
`The source image is the locked at-rest ${kind} sprite ${name}. Animate one subtle seamless ambient loop `
+ '(for example wind, water, flame, or a gentle flicker appropriate to the source), then return to the exact starting pose. '
+ 'Preserve its identity, silhouette, palette, scale, and centered ground position. Use a locked camera and an exactly '
+ `uniform non-emissive ${keyColorPhrase(chromaKey)} background only as a compositing matte: no scenery, text, labels, `
- + 'camera movement, cuts, added objects, or people.'
- + correctionClause(correctionPrompt, 'source image')
+ + 'camera movement, cuts, added objects, or people.',
+ correctionPrompt,
+ 'source image',
);
}
@@ -335,7 +384,7 @@ export function buildAmbientVideoPrompt({ name, kind, chromaKey, correctionPromp
*/
export function buildWalkVideoPrompt({ name, direction, chromaKey, correctionPrompt }) {
const facing = REFERENCE_FACING[direction] || direction;
- return (
+ return applyCorrection(
`The source image is the locked directional identity anchor for the game character ${name}, `
+ `${facing}. Animate a walk-in-place loop, walking ${direction}. `
+ 'Preserve identity, palette, proportions, facing, and physical-left and physical-right '
@@ -345,8 +394,9 @@ export function buildWalkVideoPrompt({ name, direction, chromaKey, correctionPro
+ `${keyColorPhrase(chromaKey)} background that acts only as a compositing matte: no rim light, `
+ 'bounce light, reflections, color cast, glow, or shadow on the character. Keep a stable '
+ 'pivot and ground line with loop-friendly walk-in-place motion. No scenery, no text, no '
- + 'labels, no camera motion, no extra figures.'
- + correctionClause(correctionPrompt, 'source image')
+ + 'labels, no camera motion, no extra figures.',
+ correctionPrompt,
+ 'source image',
);
}
@@ -360,11 +410,14 @@ export function buildWalkVideoPrompt({ name, direction, chromaKey, correctionPro
* existing scanner run's rebuilt provenance prompt still matches what was sent.
*/
export function buildScannerPrompt({ name, direction, chromaKey, correctionPrompt }) {
- return `Create a short, seamless scanner action for ${name}, facing ${direction}. `
+ return applyCorrection(
+ `Create a short, seamless scanner action for ${name}, facing ${direction}. `
+ 'The character raises a handheld scanner, makes one deliberate sweep, then returns to the exact starting pose. '
+ `Keep the character centered, full body visible, and animate only over a solid ${chromaKey} background. `
- + 'No text, UI, scenery, camera movement, cuts, or additional characters.'
- + correctionClause(correctionPrompt, 'source image');
+ + 'No text, UI, scenery, camera movement, cuts, or additional characters.',
+ correctionPrompt,
+ 'source image',
+ );
}
/**
@@ -378,8 +431,7 @@ export function buildScannerPrompt({ name, direction, chromaKey, correctionPromp
*/
export function buildAnchorPrompt({ name, direction, chromaKey, correctionPrompt, fromTurnaround = false }) {
const facing = REFERENCE_FACING[direction] || direction;
- const correction = correctionClause(correctionPrompt, 'reference');
- return (
+ return applyCorrection(
(fromTurnaround ? fromTurnaroundClause(direction) : '')
+ `Redraw the attached ${name} character as one `
+ `full-body figure in a neutral standing pose, ${facing}. Keep the exact same `
@@ -389,7 +441,8 @@ export function buildAnchorPrompt({ name, direction, chromaKey, correctionPrompt
+ 'facing can physically reveal it. This is a rotation of the character, '
+ `not a mirrored copy of the reference. ${geometryRule(direction)}Flat, non-isometric view; a `
+ `single centered figure on a square 1:1 canvas; plain flat ${keyColorPhrase(chromaKey)} background; no labels, no `
- + 'grid lines, no wireframe or guide colors. Return exactly one PNG.'
- + correction
+ + 'grid lines, no wireframe or guide colors. Return exactly one PNG.',
+ correctionPrompt,
+ 'reference',
);
}
diff --git a/server/services/sprites/prompts.test.js b/server/services/sprites/prompts.test.js
index 9b12d348cf..f1b6bee3b1 100644
--- a/server/services/sprites/prompts.test.js
+++ b/server/services/sprites/prompts.test.js
@@ -3,8 +3,11 @@ import {
SPRITE_DIRECTIONS, ANCHOR_DIRECTIONS, REFERENCE_FACING, anchorIdForDirection,
keyColorPhrase, buildMainReferencePrompt, buildAnchorPrompt, buildTurnaroundPrompt,
buildWalkVideoPrompt, buildScannerPrompt, buildAmbientReferencePrompt, buildAmbientVideoPrompt,
- correctionClause, viewGeometryClause, TURNAROUND_VIEWS, SPRITE_REFERENCE_CANVAS_SIZE,
+ applyCorrection, viewGeometryClause, TURNAROUND_VIEWS, SPRITE_REFERENCE_CANVAS_SIZE,
} from './prompts.js';
+// Namespace import so the SURFACES exhaustiveness guard below can enumerate every
+// exported builder rather than trusting a hand-maintained list.
+import * as allPrompts from './prompts.js';
describe('sprite direction contracts', () => {
it('uses a square canvas for reviewable reference candidates', () => {
@@ -77,21 +80,22 @@ describe('buildAnchorPrompt', () => {
expect(p).toContain('Treat the turnaround panels as the source of truth');
});
- it('appends a trimmed correction clause when provided', () => {
+ // The bug that motivated #3216. The anchor body pins accessory placement to the
+ // attached reference in three separate sentences (and, from the sheet, tells the
+ // model to read a specific panel first), so a correction asking to MOVE an
+ // accessory contradicts the bulk of the prompt. It has to bracket those clauses
+ // — framed before them, overriding after them — not merely follow them.
+ // The sandwich's own wording is pinned once, in the `applyCorrection` suite.
+ it('brackets the pin-to-reference clauses with an accessory-moving correction', () => {
+ const NOTE = 'Hip bag should be on the other leg';
const p = buildAnchorPrompt({
- name: 'Scout', direction: 'north-east', chromaKey: '#FF00FF',
- correctionPrompt: ' no pocket on the right sleeve ',
+ name: 'Scout', direction: 'west', chromaKey: '#FF00FF', fromTurnaround: true,
+ correctionPrompt: NOTE,
});
- expect(p).toContain('Important correction — apply this over the attached reference: no pocket on the right sleeve');
- // The correction rides at the end so it reads as an override, not a base clause.
- expect(p.trimEnd().endsWith('no pocket on the right sleeve')).toBe(true);
- });
-
- it('omits the correction clause for blank/absent input', () => {
- const base = buildAnchorPrompt({ name: 'Scout', direction: 'east', chromaKey: '#FF00FF' });
- const blank = buildAnchorPrompt({ name: 'Scout', direction: 'east', chromaKey: '#FF00FF', correctionPrompt: ' ' });
- expect(base).not.toContain('Important correction');
- expect(blank).toBe(base);
+ for (const pinned of ['turnaround model sheet', 'same anatomical side as the attached reference']) {
+ expect(p.indexOf(NOTE), pinned).toBeLessThan(p.indexOf(pinned));
+ expect(p.lastIndexOf(NOTE), pinned).toBeGreaterThan(p.indexOf(pinned));
+ }
});
});
@@ -246,15 +250,6 @@ describe('fromTurnaround prompt variants (#2979)', () => {
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('sends a diagonal facing to the two panels it sits between (#3004)', () => {
// The sheet only has the 4 cardinals, so naming "the panel that shows a
// three-quarter rear view" points the model at a panel that isn't there.
@@ -297,62 +292,96 @@ describe('correction prompts on every regeneration surface (#3134)', () => {
const SURFACES = [
{
label: 'turnaround sheet',
+ fn: buildTurnaroundPrompt,
build: (extra) => buildTurnaroundPrompt({ name: 'Scout', designPrompt: 'a wiry ranger', chromaKey: '#FF00FF', ...extra }),
subject: 'turnaround',
},
{
label: 'main reference (from the sheet)',
+ fn: buildMainReferencePrompt,
build: (extra) => buildMainReferencePrompt({ name: 'Scout', designPrompt: 'a wiry ranger', chromaKey: '#FF00FF', fromTurnaround: true, ...extra }),
subject: 'turnaround',
},
{
label: 'main reference (legacy, no sheet)',
+ fn: buildMainReferencePrompt,
build: (extra) => buildMainReferencePrompt({ name: 'Scout', designPrompt: 'a wiry ranger', chromaKey: '#FF00FF', ...extra }),
subject: 'reference',
},
{
label: 'directional anchor',
+ fn: buildAnchorPrompt,
build: (extra) => buildAnchorPrompt({ name: 'Scout', direction: 'east', chromaKey: '#FF00FF', ...extra }),
subject: 'reference',
},
{
label: 'ambient/place reference',
+ fn: buildAmbientReferencePrompt,
build: (extra) => buildAmbientReferencePrompt({ name: 'Old Willow', kind: 'place', designPrompt: 'a willow by a pond', chromaKey: '#FF00FF', ...extra }),
subject: 'reference',
},
{
label: 'walk video',
+ fn: buildWalkVideoPrompt,
build: (extra) => buildWalkVideoPrompt({ name: 'Scout', direction: 'east', chromaKey: '#FF00FF', ...extra }),
subject: 'source image',
},
{
label: 'scanner action video',
+ fn: buildScannerPrompt,
build: (extra) => buildScannerPrompt({ name: 'Scout', direction: 'east', chromaKey: '#FF00FF', ...extra }),
subject: 'source image',
},
{
label: 'ambient loop video',
+ fn: buildAmbientVideoPrompt,
build: (extra) => buildAmbientVideoPrompt({ name: 'Old Willow', kind: 'place', chromaKey: '#FF00FF', ...extra }),
subject: 'source image',
},
];
+ // The table above is only a contract if it is exhaustive. This set grew #2964 →
+ // #3134 → #3152 → #3216 by hand, and a 9th builder that accepted
+ // `correctionPrompt` without routing it through `applyCorrection` would ship
+ // green — reintroducing exactly the silently-ignored-feedback bug.
+ it('covers every prompt builder the module exports', () => {
+ const exported = Object.entries(allPrompts)
+ .filter(([name, value]) => /^build[A-Za-z]*Prompt$/.test(name) && typeof value === 'function')
+ .map(([name]) => name);
+ expect(exported.length).toBeGreaterThan(0); // not vacuous
+ const covered = new Set(SURFACES.map((s) => s.fn.name));
+ expect(exported.filter((name) => !covered.has(name))).toEqual([]);
+ });
+
for (const { label, build, subject } of SURFACES) {
describe(label, () => {
- it('appends one trimmed correction clause, last', () => {
+ it('wraps the body in one trimmed correction sandwich', () => {
const p = build({ correctionPrompt: ' the strap floats off the shoulder ' });
- expect(p).toContain(`Important correction — apply this over the attached ${subject}: the strap floats off the shoulder`);
- // Last so it reads as an override of the base clauses, not one more of them.
- expect(p.trimEnd().endsWith('the strap floats off the shoulder')).toBe(true);
- // Exactly one clause — a second would let the surfaces disagree on emphasis.
- expect(p.match(/Important correction/g)).toHaveLength(1);
+ // Framed up front (before any preservation clause can forbid the change)…
+ expect(p.startsWith('This is a corrected re-render')).toBe(true);
+ expect(p).toContain(
+ 'Required fix: the strap floats off the shoulder. Make that fix in the image you produce.'
+ + ' It takes priority over any instruction below to match or preserve the attached'
+ + ` ${subject}`,
+ );
+ // …and again as the closing override, which names the attachment the
+ // untouched details come from.
+ expect(p.trimEnd().endsWith(`stays as the attached ${subject} shows it.`)).toBe(true);
+ expect(p).toContain(
+ 'Required fix (highest priority — this overrides any conflicting instruction above):'
+ + ' the strap floats off the shoulder',
+ );
+ // Exactly the two halves — the note is stated twice by design (once was
+ // what got ignored), never three times.
+ expect(p.match(/the strap floats off the shoulder/g)).toHaveLength(2);
});
// The hard acceptance criterion: a blank note must not perturb the blind
// regenerate by even one byte, on any surface.
it('is byte-identical to a blind regenerate for absent/blank input', () => {
const base = build({});
- expect(base).not.toContain('Important correction');
+ expect(base).not.toContain('Required fix');
+ expect(base).not.toContain('corrected re-render');
for (const blank of [undefined, null, '', ' ', '\n\t ', 42, {}]) {
expect(build({ correctionPrompt: blank }), String(blank)).toBe(base);
}
@@ -361,15 +390,35 @@ describe('correction prompts on every regeneration surface (#3134)', () => {
}
});
-describe('correctionClause', () => {
- it('names the subject the correction applies over', () => {
- expect(correctionClause('fix the arm', 'turnaround'))
- .toBe(' Important correction — apply this over the attached turnaround: fix the arm');
- });
-
- it('returns the empty string for anything blank or non-string', () => {
- for (const v of [undefined, null, '', ' ', 0, 7, [], {}, () => {}]) {
- expect(correctionClause(v, 'reference'), String(v)).toBe('');
+describe('applyCorrection', () => {
+ // The one place the correction wording is pinned to reviewed text. Every other
+ // suite asserts that its surface ROUTES through this helper, not what it says.
+ it('states precedence and targets the OUTPUT, not the attachment', () => {
+ const p = applyCorrection('BODY.', ' fix the arm ', 'turnaround');
+ // "apply this over the attached turnaround" (the pre-#3216 wording) pointed the
+ // model at a frozen, usually-correct sheet — so it concluded there was nothing
+ // to do. The fix belongs in the image being produced.
+ expect(p).not.toContain('apply this over the attached');
+ expect(p).toBe(
+ 'This is a corrected re-render: a previous attempt at this exact image was rejected. '
+ + 'Required fix: fix the arm. Make that fix in the image you produce. It takes priority over '
+ + 'any instruction below to match or preserve the attached turnaround — change what the fix '
+ + 'names, and keep everything else identical. '
+ + 'BODY.'
+ + ' Required fix (highest priority — this overrides any conflicting instruction above): fix '
+ + 'the arm. The previous render was rejected for exactly this, so an image that does not '
+ + 'visibly reflect this fix is a failed render. Change only what the fix names; everything it '
+ + 'does not mention stays as the attached turnaround shows it.',
+ );
+ });
+
+ it('keeps a note that already ends in punctuation as written', () => {
+ expect(applyCorrection('BODY.', 'Move it up!', 'reference')).toContain('Required fix: Move it up! Make');
+ });
+
+ it('returns the body untouched for anything blank or non-string', () => {
+ for (const v of [undefined, null, '', ' ', '\n\t ', 0, 7, [], {}, () => {}]) {
+ expect(applyCorrection('BODY.', v, 'reference'), String(v)).toBe('BODY.');
}
});
});
diff --git a/server/services/sprites/reference.test.js b/server/services/sprites/reference.test.js
index 658a2d5df9..7020b8ef42 100644
--- a/server/services/sprites/reference.test.js
+++ b/server/services/sprites/reference.test.js
@@ -12,7 +12,7 @@ import { tmpdir } from 'os';
import { join } from 'path';
import sharp from 'sharp';
import { mkdir, writeFile, readFile } from 'fs/promises';
-import { writeCandidatePng, placeCandidate as placeCandidateFixture } from './spriteTestFixtures.js';
+import { writeCandidatePng, placeCandidate as placeCandidateFixture, expectCarriesCorrection } from './spriteTestFixtures.js';
const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-reference-test-'));
@@ -340,7 +340,7 @@ describe('startReferenceGeneration', () => {
await lockMain(id);
await startReferenceGeneration(id, { target: 'north-east', correctionPrompt: ' no pocket on the right sleeve ' });
const call = enqueueJob.mock.calls[0][0];
- expect(call.params.prompt).toContain('Important correction — apply this over the attached reference: no pocket on the right sleeve');
+ expectCarriesCorrection(expect, call.params.prompt, 'no pocket on the right sleeve');
// Trimmed and carried on the tag so the completion hook's sidecar records it.
expect(call.params.spriteRef.correctionPrompt).toBe('no pocket on the right sleeve');
});
@@ -357,7 +357,7 @@ describe('startReferenceGeneration', () => {
const call = enqueueJob.mock.calls[0][0];
expect(call.params.initImagePath).toBe(join(TEST_ROOT, 'sprites', id, candidate));
expect(call.params.initImageStrength).toBe(0.65);
- expect(call.params.prompt).toContain('Important correction — apply this over the attached turnaround: add the missing pocket to the right sleeve');
+ expectCarriesCorrection(expect, call.params.prompt, 'add the missing pocket to the right sleeve');
expect(call.params.spriteRef).toMatchObject({
designReferencePath: candidate,
correctionPrompt: 'add the missing pocket to the right sleeve',
@@ -380,8 +380,7 @@ describe('startReferenceGeneration', () => {
enqueueJob.mockClear();
await startReferenceGeneration(id, { target: 'main', correctionPrompt: ' the cloak hem is cut off ' });
const call = enqueueJob.mock.calls[0][0];
- expect(call.params.prompt)
- .toContain('Important correction — apply this over the attached turnaround: the cloak hem is cut off');
+ expectCarriesCorrection(expect, call.params.prompt, 'the cloak hem is cut off');
expect(call.params.spriteRef.correctionPrompt).toBe('the cloak hem is cut off');
});
@@ -409,14 +408,13 @@ describe('startReferenceGeneration', () => {
const call = enqueueJob.mock.calls[0][0];
// Both inputs land: designPrompt replaces the design, the correction is additive.
expect(call.params.prompt).toContain('Design: a willow by a pond');
- expect(call.params.prompt)
- .toContain('Important correction — apply this over the attached reference: the trunk leans too far right');
+ expectCarriesCorrection(expect, call.params.prompt, 'the trunk leans too far right');
expect(call.params.spriteRef.correctionPrompt).toBe('the trunk leans too far right');
enqueueJob.mockClear();
await startReferenceGeneration(id, { target: 'main', designPrompt: 'a willow by a pond', correctionPrompt: ' ' });
const blank = enqueueJob.mock.calls[0][0];
- expect(blank.params.prompt).not.toContain('Important correction');
+ expect(blank.params.prompt).not.toContain('Required fix');
expect(blank.params.spriteRef).not.toHaveProperty('correctionPrompt');
});
@@ -426,7 +424,7 @@ describe('startReferenceGeneration', () => {
await lockMain(id);
await startReferenceGeneration(id, { target: 'east', correctionPrompt: ' ' });
const call = enqueueJob.mock.calls[0][0];
- expect(call.params.prompt).not.toContain('Important correction');
+ expect(call.params.prompt).not.toContain('Required fix');
expect(call.params.spriteRef).not.toHaveProperty('correctionPrompt');
});
diff --git a/server/services/sprites/spriteTestFixtures.js b/server/services/sprites/spriteTestFixtures.js
index 7f0222739a..56f15290a8 100644
--- a/server/services/sprites/spriteTestFixtures.js
+++ b/server/services/sprites/spriteTestFixtures.js
@@ -68,6 +68,23 @@ export async function lockAllAnchors(testRoot, recordId, { lockReference, direct
}
}
+/**
+ * Assert that `prompt` carries the re-roll correction for `note` (#3216).
+ *
+ * The routing suites (reference / walk / animationTrackWorkflow / assetPrompt /
+ * trackPrompts) are proving that a note reached the builder — NOT what the clause
+ * says. They used to each hardcode the full sentence, so a wording change was a
+ * six-file edit and the copies drifted. `prompts.js` owns the wording and
+ * `prompts.test.js` pins it; everyone else routes through here.
+ *
+ * Both halves are checked because half a sandwich is the #3216 bug.
+ */
+export function expectCarriesCorrection(expect, prompt, note) {
+ const sentence = /[.!?]$/.test(note) ? note : `${note}.`;
+ expect(prompt).toContain(`Required fix: ${sentence} Make that fix in the image you produce.`);
+ expect(prompt).toContain(`instruction above): ${sentence}`);
+}
+
/**
* A track's column span as `buildAtlasGrid` and the layout sidecar emit it.
* `rows` defaults to the full grid height, which is what every shipped track
diff --git a/server/services/sprites/trackPrompts.js b/server/services/sprites/trackPrompts.js
index a27bf0d073..d7c21df57c 100644
--- a/server/services/sprites/trackPrompts.js
+++ b/server/services/sprites/trackPrompts.js
@@ -33,7 +33,7 @@
* `readFileSync` of one small config — see `animationTrackStore.js`).
*/
-import { buildWalkVideoPrompt, correctionClause, keyColorPhrase } from './prompts.js';
+import { buildWalkVideoPrompt, applyCorrection, keyColorPhrase } from './prompts.js';
import { WALK_TRACK } from './animationTracks.js';
import { getEffectiveAnimationTracks } from './animationTrackStore.js';
@@ -58,10 +58,11 @@ const TRACK_VIDEO_PROMPTS = Object.freeze({
* and collapsing them to one variable would change one of the two prompts on the
* wire. A user's template picks whichever reads better in its sentence.
*
- * `correctionPrompt` is deliberately NOT a placeholder: its clause is appended
- * last by every builder (`correctionClause`), because a correction that reads as an
- * override of the base wording is the whole contract — a template that
- * interpolated it mid-sentence would bury it.
+ * `correctionPrompt` is deliberately NOT a placeholder: every builder wraps its
+ * body with `applyCorrection`, which frames the render as a correction up front
+ * and closes with the override clause. Reading as an override of the base wording
+ * is the whole contract — a template that interpolated it mid-sentence would bury
+ * it, which is precisely the failure mode #3216 fixed.
*/
const templateVariables = ({ name, kind, direction, chromaKey }) => ({
name: name ?? '',
@@ -102,8 +103,11 @@ export function buildTrackVideoPrompt(trackId, args) {
);
}
if (!row.builtin) {
- return renderPromptTemplate(row.promptTemplate, args)
- + correctionClause(args?.correctionPrompt, 'source image');
+ return applyCorrection(
+ renderPromptTemplate(row.promptTemplate, args),
+ args?.correctionPrompt,
+ 'source image',
+ );
}
const build = TRACK_VIDEO_PROMPTS[trackId];
// A builtin row with no compiled builder is unreachable today (`walk` is the
diff --git a/server/services/sprites/trackPrompts.test.js b/server/services/sprites/trackPrompts.test.js
index 01b5e799a8..cb8a340ad0 100644
--- a/server/services/sprites/trackPrompts.test.js
+++ b/server/services/sprites/trackPrompts.test.js
@@ -25,7 +25,7 @@ import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
import { mkdtempSync, rmSync, mkdirSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
-import { storedTrackRow } from './spriteTestFixtures.js';
+import { storedTrackRow, expectCarriesCorrection } from './spriteTestFixtures.js';
const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-track-prompts-test-'));
@@ -148,17 +148,19 @@ describe('a user-defined row resolves through its own template', () => {
);
});
- it('appends the correction clause LAST, like every compiled builder', () => {
- // Not a placeholder on purpose: a correction reads as an override of the base
- // wording, so a template that interpolated it mid-sentence would bury it.
+ it('wraps a user template in the same correction sandwich as every compiled builder', () => {
+ // Not a placeholder on purpose: a correction has to frame the render up front
+ // and override it at the end, so a template that interpolated it mid-sentence
+ // would bury it — the failure #3216 fixed.
writeTracks([CUSTOM]);
const prompt = buildTrackVideoPrompt('jetpack-burst', {
name: 'Placeholder Hero', kind: 'character', direction: 'east', chromaKey: '#FF00FF',
correctionPrompt: 'more flame, less smoke',
});
- expect(prompt.endsWith(
- ' Important correction — apply this over the attached source image: more flame, less smoke',
- )).toBe(true);
+ expectCarriesCorrection(expect, prompt, 'more flame, less smoke');
+ // The template body sits BETWEEN the two halves, not after them.
+ expect(prompt.indexOf('jetpack burst')).toBeGreaterThan(prompt.indexOf('Required fix:'));
+ expect(prompt.trimEnd().endsWith('stays as the attached source image shows it.')).toBe(true);
});
it('rebuilds a known track and answers null for an unknown one (tryBuild…)', () => {
diff --git a/server/services/sprites/walk.test.js b/server/services/sprites/walk.test.js
index 764c7c55e8..6d6a25eda6 100644
--- a/server/services/sprites/walk.test.js
+++ b/server/services/sprites/walk.test.js
@@ -12,7 +12,7 @@ import { tmpdir } from 'os';
import { join } from 'path';
import { mkdir, writeFile, readFile, rm } from 'fs/promises';
import { createHash } from 'crypto';
-import { lockAllAnchors } from './spriteTestFixtures.js';
+import { lockAllAnchors, expectCarriesCorrection } from './spriteTestFixtures.js';
const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-walk-test-'));
@@ -354,8 +354,7 @@ describe('startWalkGeneration', () => {
const { runId } = await startWalkGeneration(id, {
direction: 'east', correctionPrompt: ' the legs barely lift ',
});
- expect(executeTuiRun.mock.calls[0][0].prompt)
- .toContain('Important correction — apply this over the attached source image: the legs barely lift');
+ expectCarriesCorrection(expect, executeTuiRun.mock.calls[0][0].prompt, 'the legs barely lift');
// Persisted on the run so the provenance rebuild can reproduce it.
const { runs } = await getWalkState(id);
expect(runs.find((r) => r.id === runId).correctionPrompt).toBe('the legs barely lift');