Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix magenta fringe halo left when locking a sprite reference re-keys the background
[._.]/ Adam Eivyc8f921685be1
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex b79097a7f1..6ac7625275 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -18,6 +18,8 @@## Sprite Manager+- **Locking a main reference no longer leaves a colored halo around the character** — when you lock a character's main reference, PortOS re-keys the background to whichever chroma color (magenta, green, or blue) sits farthest from the character's own palette. If that swapped the background — e.g. a magenta render re-keyed onto blue — the anti-aliased pixels along the character's outline kept their old magenta tint and showed up as a faint magenta ring against the new blue backdrop. Locking now cleans those edge pixels as it re-keys, so the outline blends into the new background with no leftover halo. Already-locked references (which are immutable and can't be re-locked) are healed automatically on upgrade: each one is re-derived from its saved candidate with the fix applied, and its stored checksum is refreshed — no action needed on your part.+- **See — and copy — the prompt behind any sprite image** — click a reference-set image (the frozen main, a locked directional anchor, or any generation candidate) and the enlarged preview now shows the exact prompt that produced it, with a one-click **Copy prompt** button, the same way the image render-history preview does. The asset inspector gains the same prompt block, so a walk-animation clip or any generated asset you open there shows its prompt too. Older images generated before this shipped still show their prompt — it's reconstructed from the render's recorded design description, direction, and background color — so nothing in your existing library is blank. Imported artwork and internal metadata files simply omit the block. New endpoint `GET /api/sprites/:id/asset-prompt`.- **Seed a character's main reference from an existing sprite, an upload, or your render history — and fork a character from its reference** — the "design image (optional)" upload on the main-reference form is now a three-way **Reference image** picker: upload a file, pick one from your image render-history gallery, or pick another sprite that already has a locked reference, each with a fidelity slider controlling how tightly the render follows it (image+text→image). Separately, a locked reference is immutable and can never be regenerated — so a character with a frozen main now shows a **Fork from this reference** button that spins up a brand-new character whose main is generated from this one's reference plus a prompt describing the change ("same character but in a red coat"), then opens the new sprite. New endpoints `GET /api/sprites/reference-sources` and `POST /api/sprites/:id/fork`.- **The Sprite Manager opens on a full Library catalog, with rename and delete built in** — landing on the Sprite Manager now shows the **Library** itself: a searchable, grouped grid of every character/place/object, each card carrying a real preview thumbnail — a character's locked main reference, or, for a place/object (or a character with no reference yet), the first image asset on disk, falling back to a kind icon only when there's no image at all — instead of jumping you straight into one sprite. The catalog is the `/sprites` route (not a modal buried behind a button), so it's directly linkable, and each card gives you full record control: click to open it, the pencil to **rename** in place (for records whose generated name you want to fix), or the trash to **delete** behind a cautious inline Cancel/Delete confirm (a delete drops the record from your library; its files stay on disk and its id stays reserved). The same **rename** and **delete** controls sit in a sprite's detail header, so you can fix or remove the one you're looking at without going back to the grid (deleting it returns you there). Search, **New Sprite**, and **Import** live in the page header (New Sprite/Import are modals), the left sidebar is gone so the catalog and detail panes run full width, and opening a sprite shows a **Library** link back to the grid. The per-character workspace tab that used to read "Library" is now **Assets**, since "Library" means the catalog. New endpoint `GET /api/sprites/thumbnails`.diff --git a/scripts/migrations/204-heal-swapped-key-reference-fringe.js b/scripts/migrations/204-heal-swapped-key-reference-fringe.jsnew file mode 100644index 0000000000..827d14e17d--- /dev/null+++ b/scripts/migrations/204-heal-swapped-key-reference-fringe.js@@ -0,0 +1,151 @@+/**+ * Migration 204 — heal the magenta (old-key) fringe left on main-reference+ * sprites that were locked with a chroma-key SWAP.+ *+ * Background:+ * Locking the main reference (#2896) runs dynamic chroma-key selection: the+ * candidate is masked against the key it was GENERATED on and re-composited+ * onto whichever standard key sits farthest in hue from the character's+ * palette. When those two keys differ (e.g. a green-clothed character rendered+ * on the magenta default, then re-keyed onto blue), the pre-fix+ * `normalizeFromAnalysis` copied every surviving foreground pixel VERBATIM —+ * so the anti-aliased edge pixels, which are a blend of character + magenta,+ * kept their magenta tint and showed up as a magenta halo ringing the+ * character against the new blue background.+ *+ * The code fix (in normalize.js, shipped with this migration) decontaminates+ * that fringe at composite time by+ * shifting each foreground pixel by keyShare·(newKey − oldKey). But locked+ * references are immutable (409 on relock), so already-locked mains stay+ * broken until re-normalized from their preserved candidate.+ *+ * What this migration does (per affected record):+ * Re-normalize the locked main reference from its preserved `lockedFrom`+ * candidate through the now-fixed normalizer (mask on the generation key,+ * composite onto the selected key). If the decontaminated bytes differ from+ * what's on disk, overwrite the locked PNG in place and refresh its content+ * sha in the manifest (`mainReference.sha256` plus the south anchor that+ * shares the same file). The candidate, geometry, and selected key are all+ * unchanged — only the fringe pixels move — so the artifact's identity is+ * preserved; only the corruption is removed.+ *+ * Scope gate (per record): the main reference is locked, the manifest carries a+ * selected `chromaKey`, the `lockedFrom` candidate + its generation sidecar+ * exist on disk, the generation key differs from the selected key (a swap+ * happened — the only case that could leave fringe), and re-normalizing yields+ * bytes whose sha differs from the stored one. A same-key lock (no swap) never+ * had fringe and is skipped by the key-difference gate; an already-clean lock+ * (post-fix, or nothing to fix) is skipped by the sha comparison.+ *+ * NOT touched: directional anchors (they generate on the ALREADY-selected key,+ * so their mask key equals their canvas key — no swap, no fringe); walk-run+ * `anchorSha256` pins (frozen evidence nothing verifies at read time — a walk+ * built from a fringed anchor is regenerated by the user, not rewritten here);+ * records with no locked main; the selected key itself.+ *+ * Idempotency: after a pass the locked bytes are the decontaminated output, so+ * a re-run re-derives the identical bytes and the sha comparison skips the+ * record. The migration is tracked in data/migrations.applied.json and runs+ * once regardless.+ */++import { readdir, readFile, writeFile, rename, stat, unlink } from 'fs/promises';+import { join } from 'path';+import { createHash } from 'crypto';+import { normalizeAnchorFrame } from '../../server/services/sprites/normalize.js';++const exists = (abs) => stat(abs).then(() => true, () => false);+const sha256File = async (abs) => createHash('sha256').update(await readFile(abs)).digest('hex');+const readJson = async (abs) => { try { return JSON.parse(await readFile(abs, 'utf8')); } catch { return null; } };+// Atomic write (temp + rename) so a crash mid-migration can't leave a torn,+// unparseable manifest behind — mirrors migrations 202/203.+const writeJson = async (abs, obj) => {+ const tmp = `${abs}.204.tmp`;+ await writeFile(tmp, `${JSON.stringify(obj, null, 2)}\n`);+ await rename(tmp, abs);+};++// Resolve a possibly repo-anchored path VALUE (imports embed+// `art-source/sprites/<id>/…`) to the record-relative form used on disk.+// Returns null for a value that doesn't resolve safely inside this record.+const recordRelative = (id, p) => {+ if (typeof p !== 'string' || !p) return null;+ const marker = `art-source/sprites/${id}/`;+ const idx = p.indexOf(marker);+ const rel = idx >= 0 ? p.slice(idx + marker.length) : p.replace(/^\/+/, '');+ if (!rel || rel.split(/[\\/]/).some((seg) => seg === '..' || seg === '')) return null;+ return rel;+};++async function migrateRecord(recDir, recordId) {+ const manifestAbs = join(recDir, 'reference', `${recordId}-reference-set-v1.json`);+ const manifest = await readJson(manifestAbs);+ const main = manifest?.mainReference;+ if (!main?.locked) return false;++ const canvasKey = manifest.chromaKey;+ if (typeof canvasKey !== 'string') return false;++ const lockedFromRel = recordRelative(recordId, main.lockedFrom);+ const lockedRel = recordRelative(recordId, main.path);+ if (!lockedFromRel || !lockedRel) return false;++ const candAbs = join(recDir, lockedFromRel);+ const lockedAbs = join(recDir, lockedRel);+ if (!await exists(candAbs) || !await exists(lockedAbs)) return false;++ const sidecar = await readJson(`${candAbs.replace(/\.png$/, '')}.generation.json`);+ const genKey = sidecar?.chromaKey;+ // Only a genuine key SWAP could have left old-key fringe. Same-key locks+ // (and records whose generation key we can't recover) are already clean.+ if (typeof genKey !== 'string' || genKey.toUpperCase() === canvasKey.toUpperCase()) return false;++ // Re-normalize to a temp file first; only touch the locked artifact if the+ // decontaminated bytes actually differ from what's stored.+ const tmpAbs = `${lockedAbs}.204.tmp.png`;+ const result = await normalizeAnchorFrame(candAbs, tmpAbs, { maskKeyHex: genKey, canvasKeyHex: canvasKey });+ if (result?.copiedThrough) { await unlink(tmpAbs).catch(() => {}); return false; }+ const newSha = await sha256File(tmpAbs);+ if (newSha === main.sha256) { await unlink(tmpAbs).catch(() => {}); return false; }++ await rename(tmpAbs, lockedAbs);+ main.sha256 = newSha;+ // The south anchor shares the main-reference file — refresh any anchor that+ // resolves to the same locked path so its pinned sha stays truthful.+ for (const anchor of manifest.anchors || []) {+ if (recordRelative(recordId, anchor.path) === lockedRel) anchor.sha256 = newSha;+ }+ await writeJson(manifestAbs, manifest);+ return true;+}++export default {+ up: async ({ rootDir }) => {+ const spritesDir = join(rootDir, 'data', 'sprites');+ let records;+ try {+ records = await readdir(spritesDir, { withFileTypes: true });+ } catch {+ return { ok: true, migrated: 0 }; // no sprites tree on this install+ }++ let migrated = 0;+ const failures = [];+ for (const rec of records) {+ if (!rec.isDirectory()) continue;+ try {+ if (await migrateRecord(join(spritesDir, rec.name), rec.name)) {+ migrated++;+ console.log(`🎨 migration 204: healed swapped-key reference fringe for sprite ${rec.name}`);+ }+ } catch (err) {+ failures.push(rec.name);+ console.error(`❌ migration 204 (${rec.name}): ${err.message}`);+ }+ }+ if (failures.length > 0) {+ throw new Error(`migration 204: ${failures.length} sprite record(s) failed to heal (${failures.join(', ')}) — the rest healed; reboot to retry.`);+ }+ return { ok: true, migrated };+ },+};diff --git a/scripts/migrations/204-heal-swapped-key-reference-fringe.test.js b/scripts/migrations/204-heal-swapped-key-reference-fringe.test.jsnew file mode 100644index 0000000000..969ba2604b--- /dev/null+++ b/scripts/migrations/204-heal-swapped-key-reference-fringe.test.js@@ -0,0 +1,166 @@+/**+ * Migration 204 — re-normalize main-reference sprites that were locked with a+ * chroma-key swap so the leftover old-key (magenta) fringe is decontaminated.+ * Builds a locked record whose on-disk main-reference PNG still carries the+ * magenta halo (the pre-#2963 verbatim-copy output), then asserts the migration+ * re-derives the reference from its preserved candidate, removes the halo,+ * repins the content sha on both the main reference and the shared south+ * anchor, and leaves same-key / already-clean records alone.+ */++import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync } from 'fs';+import { mkdir, writeFile, readFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import { createHash } from 'crypto';+import sharp from 'sharp';+import migration from './204-heal-swapped-key-reference-fringe.js';++let ROOT;+const sprites = () => join(ROOT, 'data', 'sprites');+const sha = (buf) => createHash('sha256').update(buf).digest('hex');+const shaFile = async (abs) => sha(await readFile(abs));+const readJson = async (abs) => JSON.parse(await readFile(abs, 'utf8'));+const writeJson = (abs, obj) => writeFile(abs, JSON.stringify(obj, null, 2));++const MAGENTA = { r: 255, g: 0, b: 255 };+const GREEN = { r: 0, g: 255, b: 0 };+const FRINGE = { r: 204, g: 51, b: 204 }; // 0.8 magenta / 0.2 green — survives the mask++// 64×64 magenta candidate: green rect + an anti-aliased magenta/green fringe+// column just left of it (the source the lock masked against magenta).+async function fringeCandidatePng() {+ const w = 64; const h = 64;+ const buf = Buffer.alloc(w * h * 3);+ for (let y = 0; y < h; y++) {+ for (let x = 0; x < w; x++) {+ let c = MAGENTA;+ if (x >= 20 && x < 30 && y >= 10 && y < 30) c = GREEN;+ else if (x === 19 && y >= 10 && y < 30) c = FRINGE;+ const i = (y * w + x) * 3;+ buf[i] = c.r; buf[i + 1] = c.g; buf[i + 2] = c.b;+ }+ }+ return sharp(buf, { raw: { width: w, height: h, channels: 3 } }).png().toBuffer();+}++// Scan a locked reference PNG for magenta-dominant (old-key halo) pixels.+async function magentaHaloCount(abs) {+ const { data, info } = await sharp(abs).raw().toBuffer({ resolveWithObject: true });+ let halo = 0;+ for (let p = 0; p < info.width * info.height; p++) {+ const r = data[p * info.channels];+ const g = data[p * info.channels + 1];+ const b = data[p * info.channels + 2];+ if (r > 150 && b > 150 && g < 120) halo++;+ }+ return halo;+}++// A locked main reference in the broken (swapped-key, fringe-left) state:+// generation key magenta, selected key blue, and the on-disk locked PNG is the+// raw candidate (stand-in for the pre-fix verbatim-copy output — any bytes that+// differ from the decontaminated re-normalize exercise the repair path).+async function buildLockedRecord(id, { genKey = '#FF00FF', canvasKey = '#0000FF' } = {}) {+ const recDir = join(sprites(), id);+ const candDir = join(recDir, 'reference', 'candidates');+ await mkdir(candDir, { recursive: true });++ const candPng = await fringeCandidatePng();+ await writeFile(join(candDir, 'walk-south-candidate-01.png'), candPng);+ await writeJson(join(candDir, 'walk-south-candidate-01.generation.json'), {+ schemaVersion: 1, kind: 'sprite-reference-generation', characterId: id,+ target: 'main', anchorId: 'walk-south', direction: 'south', chromaKey: genKey,+ });++ const lockedRel = `reference/${id}-walk-south-v1.png`;+ const lockedAbs = join(recDir, lockedRel);+ await writeFile(lockedAbs, candPng); // fringed stand-in+ const lockedSha = sha(candPng);++ await writeJson(join(recDir, 'reference', `${id}-reference-set-v1.json`), {+ schemaVersion: 1, manifestId: `${id}-reference-set-v1`, status: 'in-progress',+ chromaKey: canvasKey, chromaKeyAutoSelected: true,+ mainReference: {+ path: lockedRel, role: 'immutable-root', background: 'chroma-key',+ locked: true, lockedFrom: 'reference/candidates/walk-south-candidate-01.png',+ lockedAt: 't', sha256: lockedSha,+ },+ anchors: [+ { id: 'walk-south', kind: 'walk-anchor', direction: 'south', status: 'locked', path: lockedRel, sha256: lockedSha },+ { id: 'walk-north', kind: 'walk-anchor', direction: 'north', status: 'pending' },+ ],+ });+ return { recDir, lockedAbs, lockedSha };+}++beforeEach(() => { ROOT = mkdtempSync(join(tmpdir(), 'mig-204-')); });+afterEach(() => rmSync(ROOT, { recursive: true, force: true }));++describe('migration 204 — heal swapped-key reference fringe', () => {+ it('re-normalizes the locked main, removes the magenta halo, and repins shas', async () => {+ const id = 'xeno-fixture';+ const { recDir, lockedAbs, lockedSha } = await buildLockedRecord(id);+ expect(await magentaHaloCount(lockedAbs)).toBeGreaterThan(0); // fringed before++ const res = await migration.up({ rootDir: ROOT });+ expect(res).toMatchObject({ ok: true, migrated: 1 });++ expect(await magentaHaloCount(lockedAbs)).toBe(0); // halo gone after re-key+ const newSha = await shaFile(lockedAbs);+ expect(newSha).not.toBe(lockedSha);++ const manifest = await readJson(join(recDir, 'reference', `${id}-reference-set-v1.json`));+ expect(manifest.mainReference.sha256).toBe(newSha);+ const south = manifest.anchors.find((a) => a.id === 'walk-south');+ expect(south.sha256).toBe(newSha); // shared file — sha repinned+ // Identity is preserved: same selected key, same lockedFrom candidate.+ expect(manifest.chromaKey).toBe('#0000FF');+ expect(manifest.mainReference.lockedFrom).toBe('reference/candidates/walk-south-candidate-01.png');+ });++ it('is idempotent — a second run re-derives identical bytes and reports migrated: 0', async () => {+ const id = 'xeno-idem';+ const { recDir, lockedAbs } = await buildLockedRecord(id);+ await migration.up({ rootDir: ROOT });+ const healed = await shaFile(lockedAbs);+ const manifest = await readFile(join(recDir, 'reference', `${id}-reference-set-v1.json`), 'utf8');++ const res = await migration.up({ rootDir: ROOT });+ expect(res).toMatchObject({ ok: true, migrated: 0 });+ expect(await shaFile(lockedAbs)).toBe(healed);+ expect(await readFile(join(recDir, 'reference', `${id}-reference-set-v1.json`), 'utf8')).toBe(manifest);+ });++ it('leaves a same-key lock (no swap, no fringe) untouched', async () => {+ const id = 'no-swap';+ const { recDir, lockedAbs, lockedSha } = await buildLockedRecord(id, { genKey: '#0000FF', canvasKey: '#0000FF' });+ const before = await readFile(join(recDir, 'reference', `${id}-reference-set-v1.json`), 'utf8');++ const res = await migration.up({ rootDir: ROOT });+ expect(res).toMatchObject({ ok: true, migrated: 0 });+ expect(await shaFile(lockedAbs)).toBe(lockedSha); // file untouched+ expect(await readFile(join(recDir, 'reference', `${id}-reference-set-v1.json`), 'utf8')).toBe(before);+ });++ it('skips a record with no locked main reference', async () => {+ const id = 'unlocked';+ const recDir = join(sprites(), id);+ await mkdir(join(recDir, 'reference'), { recursive: true });+ const manifest = {+ schemaVersion: 1, chromaKey: null,+ mainReference: { path: null, role: 'immutable-root', background: 'chroma-key', locked: false },+ anchors: [],+ };+ await writeJson(join(recDir, 'reference', `${id}-reference-set-v1.json`), manifest);+ const res = await migration.up({ rootDir: ROOT });+ expect(res).toMatchObject({ ok: true, migrated: 0 });+ expect(await readJson(join(recDir, 'reference', `${id}-reference-set-v1.json`))).toEqual(manifest);+ });++ it('returns migrated: 0 on an install with no sprites tree', async () => {+ const res = await migration.up({ rootDir: ROOT });+ expect(res).toMatchObject({ ok: true, migrated: 0 });+ });+});diff --git a/server/services/sprites/chromaKey.js b/server/services/sprites/chromaKey.jsindex b86de6e2b9..d9cc17b01f 100644--- a/server/services/sprites/chromaKey.js+++ b/server/services/sprites/chromaKey.js@@ -132,6 +132,36 @@ export function keyness(pixel, split) {return minHigh - maxLow;}+/**+ * Build the per-pixel background-key "share" sampler for a key: the fraction of+ * a pixel that is the key color, reversing anti-aliased source-over-key+ * compositing. Measured as the min over the key's (high, low) channel pairs of+ * (pixel[high] − pixel[low]) / (key[high] − key[low]), clamped to [0, 1] — a+ * pure-key pixel scores 1, a pixel unlike the key scores 0, an anti-aliased+ * blend lands in between (the exact weight of the key still contaminating it).+ *+ * `keyRgb` is the key as `[r, g, b]` (a nominal key OR a measured border key);+ * `split` is its keyChannelSplit. The returned sampler reads channels from+ * `arr` at `base + channelIndex`, so one factory serves both a 3-element pixel+ * array (`base` 0) and a flat RGB/RGBA buffer (`base` = pixelIndex * channels).+ * The (high, low) pairs and their spans are precomputed once per key so the+ * hot per-pixel path only does the reads, subtracts, and min.+ */+export function keyShareFn(keyRgb, split) {+ const pairs = [];+ for (const h of split.highs) {+ for (const l of split.lows) pairs.push([h, l, Math.max(1, keyRgb[h] - keyRgb[l])]);+ }+ return (arr, base = 0) => {+ let s = Infinity;+ for (const [h, l, span] of pairs) {+ const v = (arr[base + h] - arr[base + l]) / span;+ if (v < s) s = v;+ }+ return s < 0 ? 0 : s > 1 ? 1 : s;+ };+}+export function pickChromaKey(palette, opts = {}) {const significant = significantHues(palette, opts);diff --git a/server/services/sprites/chromaKey.test.js b/server/services/sprites/chromaKey.test.jsindex 88aa39502d..1316c1fb0b 100644--- a/server/services/sprites/chromaKey.test.js+++ b/server/services/sprites/chromaKey.test.js@@ -2,6 +2,7 @@ import { describe, it, expect } from 'vitest';import {CHROMA_KEYS, CHROMA_KEY_HEXES, MIN_HUE_SEPARATION,rgbToHsv, hueDistance, pickChromaKey, keyProximityWarning,+ keyChannelSplit, keyShareFn,} from './chromaKey.js';describe('chroma key set', () => {@@ -104,3 +105,26 @@ describe('keyProximityWarning', () => {expect(keyProximityWarning([], '#FF00FF')).toBeNull();});});++describe('keyShareFn', () => {+ const magenta = [255, 0, 255];+ const split = keyChannelSplit('#FF00FF'); // highs r+b, low g++ it('scores a pure key pixel 1 and a pixel unlike the key 0', () => {+ const share = keyShareFn(magenta, split);+ expect(share(magenta)).toBe(1); // exact key+ expect(share([0, 255, 0])).toBe(0); // pure green — opposite of magenta+ });++ it('scores an anti-aliased blend by its key weight', () => {+ const share = keyShareFn(magenta, split);+ // 0.8·magenta + 0.2·green = (204,51,204): min((204-51)/255) = 0.6.+ expect(share([204, 51, 204])).toBeCloseTo(0.6, 5);+ });++ it('reads from a flat buffer at an arbitrary base offset', () => {+ const share = keyShareFn(magenta, split);+ const buf = [0, 0, 0, 204, 51, 204]; // key blend at pixel index 1+ expect(share(buf, 3)).toBeCloseTo(0.6, 5);+ });+});diff --git a/server/services/sprites/normalize.js b/server/services/sprites/normalize.jsindex bc6b100946..07925499df 100644--- a/server/services/sprites/normalize.js+++ b/server/services/sprites/normalize.js@@ -16,11 +16,20 @@* pixel is foreground when max-channel |pixel − key| > 40 — a DELIBERATE* deviation from the source's luma metric, which is blind to black-vs-blue* (see MASK_CHANNEL_THRESHOLD).+ *+ * Fringe decontamination: the hard mask keeps anti-aliased edge pixels+ * that are a BLEND of the character and the generation key. When lock swaps the+ * key (dynamic selection composites onto a key different from the one the+ * candidate was masked against), those fringe pixels still carry the OLD key's+ * tint — a magenta ring on a magenta→blue re-key. Each surviving foreground+ * pixel is shifted by keyShare·(newKey − oldKey), the same straight-alpha+ * recomposite `recoverAlphaFrame` performs, so the residual old key is replaced+ * by the correct amount of the new key. A no-op when the keys match.*/import sharp from 'sharp';import { copyFile } from 'fs/promises';-import { hexToRgb } from './chromaKey.js';+import { hexToRgb, keyChannelSplit, keyShareFn } from './chromaKey.js';const FRAME_HEIGHT_FRAC = 0.80;const FRAME_BOTTOM_FRAC = 0.07;@@ -70,7 +79,32 @@ export async function analyzeForeground(src, maskKeyHex) {}}const bbox = right >= 0 ? { left, top, right: right + 1, bottom: bottom + 1 } : null;- return { data, width, height, mask, bbox };+ // maskKeyHex rides along so the composite can decontaminate fringe pixels+ // when it re-keys onto a DIFFERENT canvas key (see normalizeFromAnalysis).+ return { data, width, height, mask, bbox, maskKey: maskKeyHex };+}++const clampByte = (v) => Math.max(0, Math.min(255, Math.round(v)));++/**+ * Build the per-pixel fringe decontaminator for a mask-key → canvas-key swap,+ * or null when no swap happens (keys equal, or the mask key is unknown). Reuses+ * the shared `keyShareFn` unmix (the same one recoverAlphaFrame runs) to measure+ * how much old key each foreground pixel still carries, then shifts it by+ * share·(newKey − oldKey) so the old key is replaced by the correct amount of+ * the new one — the opaque source-over analogue of recoverAlphaFrame's straight-+ * alpha recomposite.+ */+function buildKeyDecontaminator(maskKeyHex, canvasKeyHex) {+ if (typeof maskKeyHex !== 'string' || maskKeyHex.toUpperCase() === canvasKeyHex.toUpperCase()) {+ return null;+ }+ const oldKey = hexToRgb(maskKeyHex);+ const newKey = hexToRgb(canvasKeyHex);+ return {+ delta: [newKey.r - oldKey.r, newKey.g - oldKey.g, newKey.b - oldKey.b],+ share: keyShareFn([oldKey.r, oldKey.g, oldKey.b], keyChannelSplit(maskKeyHex)),+ };}/**@@ -107,7 +141,7 @@ export async function extractForegroundPalette(src, maskKeyHex) {* `src` is still needed for the no-foreground copy-through path.*/export async function normalizeFromAnalysis(analysis, src, dest, canvasKeyHex) {- const { data, width, mask, bbox } = analysis;+ const { data, width, mask, bbox, maskKey } = analysis;if (!bbox) {await copyFile(src, dest);return { copiedThrough: true };@@ -123,14 +157,25 @@ export async function normalizeFromAnalysis(analysis, src, dest, canvasKeyHex) {const offsetX = Math.floor((side - charW) / 2);const feetY = side - Math.round(side * FRAME_BOTTOM_FRAC);const offsetY = feetY - charH;+ // Non-null only when the composite re-keys onto a different canvas — then the+ // anti-aliased fringe that survived the hard mask is decontaminated of the+ // old key it still carries; otherwise foreground pixels copy through verbatim.+ const decon = buildKeyDecontaminator(maskKey, canvasKeyHex);for (let y = bbox.top; y < bbox.bottom; y++) {for (let x = bbox.left; x < bbox.right; x++) {if (!mask[y * width + x]) continue;const srcI = (y * width + x) * 3;const dstI = ((offsetY + (y - bbox.top)) * side + offsetX + (x - bbox.left)) * 3;- canvas[dstI] = data[srcI];- canvas[dstI + 1] = data[srcI + 1];- canvas[dstI + 2] = data[srcI + 2];+ if (decon) {+ const share = decon.share(data, srcI);+ canvas[dstI] = clampByte(data[srcI] + share * decon.delta[0]);+ canvas[dstI + 1] = clampByte(data[srcI + 1] + share * decon.delta[1]);+ canvas[dstI + 2] = clampByte(data[srcI + 2] + share * decon.delta[2]);+ } else {+ canvas[dstI] = data[srcI];+ canvas[dstI + 1] = data[srcI + 1];+ canvas[dstI + 2] = data[srcI + 2];+ }}}await sharp(canvas, { raw: { width: side, height: side, channels: 3 } }).png().toFile(dest);diff --git a/server/services/sprites/normalize.test.js b/server/services/sprites/normalize.test.jsindex c2e85dfb2a..162c5655d7 100644--- a/server/services/sprites/normalize.test.js+++ b/server/services/sprites/normalize.test.js@@ -34,6 +34,25 @@ async function writeCandidate(path, { bg = MAGENTA, fg = GREEN } = {}) {await sharp(buf, { raw: { width: w, height: h, channels: 3 } }).png().toFile(path);}+// 64×64 magenta bg + green rect, with one anti-aliased fringe column (0.8+// magenta / 0.2 green = (204,51,204)) just left of the rect — a blend that+// survives the hard mask but still carries the magenta key's tint.+async function writeFringeCandidate(path) {+ const w = 64; const h = 64;+ const FRINGE = { r: 204, g: 51, b: 204 };+ const buf = Buffer.alloc(w * h * 3);+ for (let y = 0; y < h; y++) {+ for (let x = 0; x < w; x++) {+ let c = MAGENTA;+ if (x >= 20 && x < 30 && y >= 10 && y < 30) c = GREEN;+ else if (x === 19 && y >= 10 && y < 30) c = FRINGE;+ const i = (y * w + x) * 3;+ buf[i] = c.r; buf[i + 1] = c.g; buf[i + 2] = c.b;+ }+ }+ await sharp(buf, { raw: { width: w, height: h, channels: 3 } }).png().toFile(path);+}+async function readRaw(path) {const { data, info } = await sharp(path).raw().toBuffer({ resolveWithObject: true });return { data, width: info.width, height: info.height };@@ -89,6 +108,36 @@ describe('normalizeAnchorFrame', () => {expect(px(img, 0, 0)).toEqual(BLUE);});+ it('decontaminates anti-aliased key fringe when re-keying magenta → blue', async () => {+ const src = join(dir, 'fringe.png');+ const dest = join(dir, 'fringe-out.png');+ await writeFringeCandidate(src);+ await normalizeAnchorFrame(src, dest, { maskKeyHex: '#FF00FF', canvasKeyHex: '#0000FF' });+ const img = await readRaw(dest);+ let magentaHalo = 0; let greenKept = 0;+ for (let p = 0; p < img.width * img.height; p++) {+ const r = img.data[p * 3]; const g = img.data[p * 3 + 1]; const b = img.data[p * 3 + 2];+ if (r > 150 && b > 150 && g < 120) magentaHalo++; // residual old-key ring+ if (g > 200 && r < 80 && b < 80) greenKept++; // character pixels+ }+ expect(magentaHalo).toBe(0); // no magenta halo survives the re-key+ expect(greenKept).toBeGreaterThan(0); // the character itself is untouched+ });++ it('copies fringe through verbatim when the key is not swapped', async () => {+ const src = join(dir, 'fringe2.png');+ const dest = join(dir, 'fringe2-out.png');+ await writeFringeCandidate(src);+ await normalizeAnchorFrame(src, dest, { maskKeyHex: '#FF00FF', canvasKeyHex: '#FF00FF' });+ const img = await readRaw(dest);+ let fringe = 0;+ for (let p = 0; p < img.width * img.height; p++) {+ const r = img.data[p * 3]; const g = img.data[p * 3 + 1]; const b = img.data[p * 3 + 2];+ if (r === 204 && g === 51 && b === 204) fringe++;+ }+ expect(fringe).toBeGreaterThan(0); // same-key composite leaves the blend as-is+ });+it('copies through an image with no detectable foreground', async () => {const src = join(dir, 'blank.png');const dest = join(dir, 'blank-out.png');diff --git a/server/services/sprites/walkPostprocess.js b/server/services/sprites/walkPostprocess.jsindex ea620c7a8f..e848818400 100644--- a/server/services/sprites/walkPostprocess.js+++ b/server/services/sprites/walkPostprocess.js@@ -25,7 +25,7 @@ import { readdir, writeFile } from 'fs/promises';import { createHash } from 'crypto';import { ensureDir, atomicWrite, sha256File } from '../../lib/fileUtils.js';import { findFfmpeg, runFfmpegProcess } from '../../lib/ffmpeg.js';-import { keyChannelSplit, keyness } from './chromaKey.js';+import { keyChannelSplit, keyness, keyShareFn } from './chromaKey.js';// Source pipeline constants (animation_postprocess.py) — values are part of// the cross-install artifact contract (imported manifests carry them).@@ -70,7 +70,6 @@ export function pyRoundTo(x, dp) {}const clampChannel = (v) => Math.max(0, Math.min(255, pyRound(v)));-const clamp01 = (v) => Math.max(0, Math.min(1, v));/** statistics.median: middle value, or mean of the two middles. */export function median(values) {@@ -150,22 +149,12 @@ export function validateMeasuredKey(measured, split, keyHex) {export function recoverAlphaFrame(frame, measuredKey, split) {const { data, width, height } = frame;const out = Buffer.alloc(width * height * 4);- const pairs = [];- for (const h of split.highs) {- for (const l of split.lows) {- pairs.push([h, l, Math.max(1, measuredKey[h] - measuredKey[l])]);- }- }+ const shareOf = keyShareFn(measuredKey, split);const px = [0, 0, 0];for (let p = 0; p < width * height; p++) {const i = p * 4;px[0] = data[i]; px[1] = data[i + 1]; px[2] = data[i + 2];- let share = Infinity;- for (const [h, l, span] of pairs) {- const s = (px[h] - px[l]) / span;- if (s < share) share = s;- }- share = clamp01(share);+ const share = shareOf(px);if (share < KEY_NOISE_FLOOR) {out[i] = px[0]; out[i + 1] = px[1]; out[i + 2] = px[2]; out[i + 3] = 255;continue;