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

feat([issue-2897]): port the deterministic walk postprocess to Node (un-key, cycle select, align, despill, pack)

[._.]/ Adam Eivyee71fe28c548
diff --git a/server/services/sprites/chromaKey.js b/server/services/sprites/chromaKey.js
index d8c007a7f2..b86de6e2b9 100644
--- a/server/services/sprites/chromaKey.js
+++ b/server/services/sprites/chromaKey.js
@@ -98,6 +98,40 @@ export function keyProximityWarning(palette, keyHex, { role = 'generation', ...o
: `Character palette sits within ${Math.round(minDist)}° of the generation key ${keyHex} — exact-key details may have been clipped by the mask; consider pinning a different key and regenerating before locking`;
}
+/**
+ * Split a key color into its saturated ("high", 255) and dark ("low", 0)
+ * channel indices — the structure every key-parameterized un-key/despill
+ * formula in walkPostprocess.js is written against. The source pipeline
+ * hardcoded magenta (highs r+b, low g); the three standard keys are all
+ * pure-channel colors, so highs/lows fully describe them:
+ * magenta → highs [0,2], lows [1]
+ * green → highs [1], lows [0,2]
+ * blue → highs [2], lows [0,1]
+ * Channel indices are 0=r, 1=g, 2=b into an RGB(A) pixel.
+ */
+export function keyChannelSplit(hex) {
+ const { r, g, b } = hexToRgb(hex);
+ const values = [r, g, b];
+ const highs = [];
+ const lows = [];
+ values.forEach((v, i) => (v >= 128 ? highs : lows).push(i));
+ if (!highs.length || !lows.length) throw new Error(`Not a usable chroma key: ${hex}`);
+ return { rgb: values, highs, lows };
+}
+
+/**
+ * How key-like a pixel is: min(high channels) − max(low channels).
+ * Positive = the pixel leans toward the key color. For magenta this is the
+ * source pipeline's `min(r,b) − g` exactly.
+ */
+export function keyness(pixel, split) {
+ let minHigh = 255;
+ for (const h of split.highs) minHigh = Math.min(minHigh, pixel[h]);
+ let maxLow = 0;
+ for (const l of split.lows) maxLow = Math.max(maxLow, pixel[l]);
+ return minHigh - maxLow;
+}
+
export function pickChromaKey(palette, opts = {}) {
const significant = significantHues(palette, opts);
diff --git a/server/services/sprites/prompts.js b/server/services/sprites/prompts.js
index 379cc8f9e0..8b627aa272 100644
--- a/server/services/sprites/prompts.js
+++ b/server/services/sprites/prompts.js
@@ -73,6 +73,28 @@ export function buildMainReferencePrompt({ name, designPrompt, chromaKey }) {
);
}
+/**
+ * Stage-3 motion prompt (issue #2897): the walk-video instruction handed to
+ * the grok i2v lane along with the prepared transparent anchor. PortOS's
+ * grok video wrapper (videoGen/grok.js buildGrokVideoPrompt) owns the tool
+ * mechanics (one image_to_video call, save one MP4), so this carries only
+ * the identity/matte/motion constraints — the source pipeline's
+ * `animation_prompt` minus its CLI/tool scaffolding.
+ */
+export function buildWalkVideoPrompt({ name, direction, chromaKey }) {
+ const facing = REFERENCE_FACING[direction] || direction;
+ return (
+ `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 '
+ + 'accessories exactly. Use a locked camera and an exactly uniform, non-emissive '
+ + `${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.'
+ );
+}
+
/**
* Stage-2 prompt: derive one directional anchor from the attached frozen
* main reference.
diff --git a/server/services/sprites/walkPostprocess.e2e.test.js b/server/services/sprites/walkPostprocess.e2e.test.js
new file mode 100644
index 0000000000..017b171941
--- /dev/null
+++ b/server/services/sprites/walkPostprocess.e2e.test.js
@@ -0,0 +1,176 @@
+/**
+ * Walk postprocess end-to-end + parity fixture (#2897).
+ *
+ * Synthesizes a deterministic keyed walk video with ffmpeg (an oscillating
+ * "character" over the solid key), runs the full postprocess, and asserts
+ * the packed geometry contract (8 phases, 3072×384 strip, pivot/baseline)
+ * plus bit-level determinism (two runs → identical artifacts). Skipped when
+ * ffmpeg is unavailable (CI runners without it still cover all the pixel
+ * math in walkPostprocess.test.js).
+ *
+ * Parity against a real imported ElsewhereAcres production run is opt-in —
+ * production sprite data is never committed (see the repo's privacy rules):
+ * SPRITE_WALK_PARITY_RUN=<abs path to an imported grok/walk-* run dir> \
+ * npx vitest run services/sprites/walkPostprocess.e2e.test.js
+ * re-runs the postprocess on that run's source video and asserts the same
+ * packed geometry + frame count as its imported manifest.
+ */
+
+import { describe, it, expect, afterAll } from 'vitest';
+import { mkdtempSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import sharp from 'sharp';
+import { mkdir, readFile } from 'fs/promises';
+import { findFfmpeg, runFfmpegProcess } from '../../lib/ffmpeg.js';
+import { runWalkPostprocess, WALK_PHASES, WALK_CELL_SIZE } from './walkPostprocess.js';
+
+const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-walk-e2e-'));
+afterAll(() => rmSync(TEST_ROOT, { recursive: true, force: true }));
+
+const ffmpegBin = await findFfmpeg();
+const KEY = '#FF00FF';
+
+// A 256×256 "character": dark body + two legs that scissor with a 12-frame
+// period, over the solid magenta key. yuv420p smears the key exactly like a
+// real codec, so the measured-key un-key path is exercised for real.
+async function writeSourceFrame(dir, index) {
+ const w = 256; const h = 256;
+ const buf = Buffer.alloc(w * h * 3);
+ for (let p = 0; p < w * h; p++) buf.set([255, 0, 255], p * 3);
+ const phase = Math.sin((2 * Math.PI * index) / 12);
+ const spread = Math.round(28 * phase);
+ const bob = Math.round(5 * Math.cos((2 * Math.PI * index) / 12));
+ const paint = (x0, y0, x1, y1, rgb) => {
+ for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) buf.set(rgb, (y * w + x) * 3);
+ };
+ // Bright, saturated body parts so the 48×48 signatures register the motion.
+ paint(96, 40 + bob, 160, 150 + bob, [235, 225, 205]); // torso
+ paint(112, 20 + bob, 144, 40 + bob, [220, 190, 160]); // head
+ paint(112 - spread, 150, 128 - spread, 220, [190, 40, 50]); // left leg
+ paint(128 + spread, 150, 144 + spread, 220, [50, 40, 190]); // right leg
+ await sharp(buf, { raw: { width: w, height: h, channels: 3 } })
+ .png()
+ .toFile(join(dir, `frame-${String(index).padStart(3, '0')}.png`));
+}
+
+async function synthesizeVideo(dest) {
+ const framesDir = join(TEST_ROOT, 'synth-frames');
+ await mkdir(framesDir, { recursive: true });
+ for (let i = 0; i < 30; i++) await writeSourceFrame(framesDir, i);
+ const result = await runFfmpegProcess({
+ bin: ffmpegBin,
+ args: [
+ '-y', '-framerate', '12', '-i', join(framesDir, 'frame-%03d.png'),
+ '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-crf', '18', dest,
+ ],
+ });
+ expect(result.ok).toBe(true);
+}
+
+async function writeAnchor(dest) {
+ const w = 128; const h = 128;
+ const buf = Buffer.alloc(w * h * 3);
+ for (let p = 0; p < w * h; p++) buf.set([255, 0, 255], p * 3);
+ for (let y = 20; y < 110; y++) for (let x = 48; x < 80; x++) buf.set([40, 60, 90], (y * w + x) * 3);
+ await sharp(buf, { raw: { width: w, height: h, channels: 3 } }).png().toFile(dest);
+}
+
+async function runOnce(label, videoAbs, anchorAbs) {
+ const runRel = 'grok/walk-east-fixture0';
+ const runAbs = join(TEST_ROOT, label, runRel);
+ await mkdir(join(runAbs, 'generated'), { recursive: true });
+ return {
+ runAbs,
+ result: await runWalkPostprocess({
+ recordId: 'fixture-hero',
+ direction: 'east',
+ chromaKey: KEY,
+ runAbs,
+ runRel,
+ anchorRel: 'reference/fixture-hero-walk-east-v1.png',
+ anchorAbs,
+ videoAbs,
+ }),
+ };
+}
+
+describe.skipIf(!ffmpegBin)('runWalkPostprocess e2e (synthetic keyed walk video)', () => {
+ it('packages the canonical strip geometry deterministically', async () => {
+ const videoAbs = join(TEST_ROOT, 'walk.mp4');
+ const anchorAbs = join(TEST_ROOT, 'anchor.png');
+ await synthesizeVideo(videoAbs);
+ await writeAnchor(anchorAbs);
+
+ const { runAbs, result } = await runOnce('run-a', videoAbs, anchorAbs);
+ const { manifest } = result;
+
+ // Geometry contract.
+ expect(manifest.kind).toBe('deterministically-packaged-grok-walk-video');
+ expect(manifest.frameCount).toBe(8);
+ expect(manifest.frameRate).toBe(12);
+ expect(manifest.frames.map((f) => f.phase)).toEqual(WALK_PHASES);
+ expect(manifest.alignment.cellSize).toBe(WALK_CELL_SIZE);
+ expect(manifest.alignment.targetPivot).toEqual([192, 352]);
+ expect(manifest.alignment.translations).toHaveLength(8);
+ expect(manifest.chromaKey).toBe(KEY);
+ expect(manifest.validation.keyDominantPixels).toEqual([0, 0, 0, 0, 0, 0, 0, 0]);
+ expect(manifest.cycleSelection.windowLength).toBeGreaterThanOrEqual(8);
+
+ const stripMeta = await sharp(join(runAbs, 'generated', 'fixture-hero-walk-east-strip.png')).metadata();
+ expect(stripMeta.width).toBe(WALK_CELL_SIZE * 8);
+ expect(stripMeta.height).toBe(WALK_CELL_SIZE);
+ const sheetMeta = await sharp(join(runAbs, 'generated', 'review', 'fixture-hero-walk-east-contrast-review.png')).metadata();
+ expect(sheetMeta.width).toBe(1024);
+ expect(sheetMeta.height).toBe(384);
+ const preview = JSON.parse(await readFile(join(runAbs, 'generated', 'review-preview.json'), 'utf8'));
+ expect(preview).toEqual({
+ stripPath: 'grok/walk-east-fixture0/generated/fixture-hero-walk-east-strip.png',
+ frameCount: 8, fps: 12, cellWidth: 384, cellHeight: 384, row: 0, startColumn: 0,
+ });
+
+ // Determinism: same video, second run → byte-identical manifest & strip.
+ const second = await runOnce('run-b', videoAbs, anchorAbs);
+ expect(second.result.manifest).toEqual(manifest);
+ expect(second.result.manifest.stripSha256).toBe(manifest.stripSha256);
+ }, 120000);
+});
+
+const parityRun = process.env.SPRITE_WALK_PARITY_RUN;
+
+describe.skipIf(!ffmpegBin || !parityRun)('parity vs an imported production run', () => {
+ it('reproduces the imported manifest geometry from the same source video', async () => {
+ const importedManifestName = (await import('fs/promises'))
+ .readdir(join(parityRun, 'generated'));
+ const names = await importedManifestName;
+ const manifestFile = names.find((n) => /-walk-.+-manifest\.json$/.test(n));
+ expect(manifestFile).toBeTruthy();
+ const imported = JSON.parse(await readFile(join(parityRun, 'generated', manifestFile), 'utf8'));
+ const videoAbs = join(parityRun, 'generated', 'source-video.mp4');
+
+ const runRel = 'grok/walk-parity-check00';
+ const runAbs = join(TEST_ROOT, 'parity', runRel);
+ await mkdir(join(runAbs, 'generated'), { recursive: true });
+ const anchorAbs = join(TEST_ROOT, 'parity-anchor.png');
+ await writeAnchor(anchorAbs);
+ const { manifest } = await runWalkPostprocess({
+ recordId: imported.characterId,
+ direction: imported.direction,
+ chromaKey: imported.chromaKey || '#FF00FF',
+ runAbs,
+ runRel,
+ anchorRel: imported.anchorPath,
+ anchorAbs,
+ videoAbs,
+ });
+ expect(manifest.frameCount).toBe(imported.frameCount);
+ expect(manifest.frameRate).toBe(imported.frameRate);
+ expect(manifest.alignment.cellSize).toBe(imported.alignment.cellSize);
+ expect(manifest.alignment.targetPivot).toEqual(imported.alignment.targetPivot);
+ expect(manifest.frames.map((f) => f.phase)).toEqual(imported.frames.map((f) => f.phase));
+ const stripMeta = await sharp(join(runAbs, 'generated', `${imported.characterId}-walk-${imported.direction}-strip.png`)).metadata();
+ const importedStrip = await sharp(join(parityRun, 'generated', imported.stripPath.split('/').pop())).metadata();
+ expect(stripMeta.width).toBe(importedStrip.width);
+ expect(stripMeta.height).toBe(importedStrip.height);
+ }, 240000);
+});
diff --git a/server/services/sprites/walkPostprocess.js b/server/services/sprites/walkPostprocess.js
new file mode 100644
index 0000000000..3d8448ae5d
--- /dev/null
+++ b/server/services/sprites/walkPostprocess.js
@@ -0,0 +1,698 @@
+/**
+ * Sprites — deterministic walk-animation postprocess (issue #2897, phase 3).
+ *
+ * Node/sharp/ffmpeg port of the source pipeline's `animation_postprocess.py`:
+ * extract frames from the one grok walk video → recover straight alpha from
+ * the keyed matte (measured border key, per-channel unmix) → select the best
+ * walk cycle by image distance → one-fixed-scale translation-only pivot
+ * alignment onto 384×384 cells → key-vector despill → validate → pack the 8
+ * named gait-phase strip + contrast review sheet + run manifest with
+ * per-frame sha256s. Everything after the video is deterministic local work —
+ * no AI calls.
+ *
+ * Deviations from the source (deliberate, per the #2895 decisions):
+ * - All "magenta" math is key-parameterized via keyChannelSplit (the record's
+ * chroma key may be magenta, green, or blue). For magenta the formulas
+ * reduce to the source's exactly (highs r+b, low g).
+ * - Python `round()` is half-to-even (banker's); `pyRound` replicates it
+ * because cycle resampling (`round(i*len/8)`) and channel math genuinely
+ * pick different frames/values under Math.round's half-up.
+ */
+
+import sharp from 'sharp';
+import { join } from 'path';
+import { readdir } 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';
+
+// Source pipeline constants (animation_postprocess.py) — values are part of
+// the cross-install artifact contract (imported manifests carry them).
+export const WALK_FPS = 12;
+export const WALK_FRAME_COUNT = 8;
+export const MAX_SOURCE_SECONDS = 8;
+export const MAX_SOURCE_DIMENSION = 512;
+export const WALK_CELL_SIZE = 384;
+export const WALK_PIVOT = [WALK_CELL_SIZE / 2, 352]; // [192, 352]
+export const WALK_PHASES = [
+ 'left-contact', 'left-down', 'left-passing', 'left-up',
+ 'right-contact', 'right-down', 'right-passing', 'right-up',
+];
+
+const KEY_NOISE_FLOOR = 0.01; // background share below this → fully opaque
+const BACKGROUND_ALPHA_FLOOR = 0.06; // source alpha at/below this → fully transparent
+const ALPHA_NOISE_FLOOR = 2; // output alpha at/below this → zeroed
+const KEY_DESPILL_FLOOR = 4; // keyness above this marks a despill suspect
+const KEY_VALIDATION_FLOOR = 8; // keyness above this fails validation
+const KEY_REPAIR_RADIUS = 8; // despill neighbor-search chebyshev radius
+const OPAQUE_EDGE_ALPHA = 245; // alpha at/above this counts as clean/opaque
+const BBOX_ALPHA_THRESHOLD = 24; // alpha_bbox visibility threshold
+const ROOT_ALPHA_THRESHOLD = 48; // root_x band pixel threshold
+const SIGNATURE_SIZE = 48;
+const SIGNATURE_BACKGROUND = { r: 48, g: 52, b: 54 };
+const MIN_CYCLE_MOTION = 0.75;
+const MAX_KEY_MASS = 2500;
+
+/** Python round(): half-to-even. Exported for tests. */
+export function pyRound(x) {
+ const floor = Math.floor(x);
+ const diff = x - floor;
+ if (diff > 0.5) return floor + 1;
+ if (diff < 0.5) return floor;
+ return floor % 2 === 0 ? floor : floor + 1;
+}
+
+/** Python round(x, dp): half-to-even at dp decimals (manifest floats). */
+export function pyRoundTo(x, dp) {
+ const scale = 10 ** dp;
+ return pyRound(x * scale) / scale;
+}
+
+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) {
+ const sorted = [...values].sort((a, b) => a - b);
+ const mid = sorted.length >> 1;
+ return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
+}
+
+const sha256Buffer = (buf) => createHash('sha256').update(buf).digest('hex');
+
+/** Decode a PNG to a raw RGBA frame `{ data, width, height }`. */
+export async function decodeRgbaFrame(src) {
+ const { data, info } = await sharp(src).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
+ return { data, width: info.width, height: info.height };
+}
+
+async function encodePng(frame, dest, channels = 4) {
+ await sharp(frame.data, { raw: { width: frame.width, height: frame.height, channels } })
+ .png()
+ .toFile(dest);
+}
+
+/**
+ * Measure the actual background key of a frame: per-channel median over a
+ * thin border band (the generated video's matte is close to, but rarely
+ * exactly, the requested key — codecs shift it).
+ */
+export function sampleBorderKey(frame) {
+ const { data, width, height } = frame;
+ const minDim = Math.min(width, height);
+ const band = Math.max(4, Math.floor(minDim / 120));
+ const step = Math.max(1, Math.floor(minDim / 320));
+ const rs = []; const gs = []; const bs = [];
+ const push = (x, y) => {
+ const i = (y * width + x) * 4;
+ rs.push(data[i]); gs.push(data[i + 1]); bs.push(data[i + 2]);
+ };
+ for (let x = 0; x < width; x += step) {
+ for (let o = 0; o < band && o < height; o++) {
+ push(x, o);
+ push(x, height - 1 - o);
+ }
+ }
+ for (let y = 0; y < height; y += step) {
+ for (let o = 0; o < band && o < width; o++) {
+ push(o, y);
+ push(width - 1 - o, y);
+ }
+ }
+ return [pyRound(median(rs)), pyRound(median(gs)), pyRound(median(bs))];
+}
+
+/**
+ * Reject a measured border key that isn't a plausible sample of the expected
+ * chroma key: its saturated channels must dominate its dark channels by ≥80,
+ * and channels within each group must be balanced within 80 (the source's
+ * "balanced magenta" check, generalized).
+ */
+export function validateMeasuredKey(measured, split, keyHex) {
+ const minHigh = Math.min(...split.highs.map((i) => measured[i]));
+ const maxLow = Math.max(...split.lows.map((i) => measured[i]));
+ const groupSpread = (idx) => Math.max(...idx.map((i) => measured[i])) - Math.min(...idx.map((i) => measured[i]));
+ if (minHigh - maxLow < 80 || groupSpread(split.highs) > 80 || groupSpread(split.lows) > 80) {
+ throw new Error(`Measured background [${measured.join(',')}] is not a usable ${keyHex} matte`);
+ }
+}
+
+/**
+ * Chroma un-key: reverse antialiased source-over-key compositing into a
+ * straight-alpha RGBA frame. Per-pixel math is the source's, generalized to
+ * (high, low) channel pairs of the record's key.
+ */
+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 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);
+ if (share < KEY_NOISE_FLOOR) {
+ out[i] = px[0]; out[i + 1] = px[1]; out[i + 2] = px[2]; out[i + 3] = 255;
+ continue;
+ }
+ const sourceAlpha = 1 - share;
+ if (sourceAlpha <= BACKGROUND_ALPHA_FLOOR) continue; // stays (0,0,0,0)
+ const outputAlpha = clampChannel(((sourceAlpha - BACKGROUND_ALPHA_FLOOR) * 255) / (1 - BACKGROUND_ALPHA_FLOOR));
+ if (outputAlpha <= ALPHA_NOISE_FLOOR) continue;
+ out[i] = clampChannel((px[0] - share * measuredKey[0]) / sourceAlpha);
+ out[i + 1] = clampChannel((px[1] - share * measuredKey[1]) / sourceAlpha);
+ out[i + 2] = clampChannel((px[2] - share * measuredKey[2]) / sourceAlpha);
+ out[i + 3] = outputAlpha;
+ }
+ return { data: out, width, height };
+}
+
+const lowMean = (data, i, split) => {
+ let sum = 0;
+ for (const l of split.lows) sum += data[i + l];
+ return sum / split.lows.length;
+};
+
+/**
+ * Key-vector despill: repair codec-spread key spill by borrowing RGB from
+ * the nearest clean opaque neighbor (ring search), falling back to direct
+ * spill subtraction from the key's high channels. Alpha is preserved.
+ */
+export function despillKeyFrame(frame, split) {
+ const { data, width, height } = frame;
+ const out = Buffer.from(data);
+ const suspects = new Uint8Array(width * height);
+ const px = [0, 0, 0];
+ for (let p = 0; p < width * height; p++) {
+ const i = p * 4;
+ const a = data[i + 3];
+ if (a <= ALPHA_NOISE_FLOOR) continue;
+ px[0] = data[i]; px[1] = data[i + 1]; px[2] = data[i + 2];
+ if (a < OPAQUE_EDGE_ALPHA || keyness(px, split) > KEY_DESPILL_FLOOR) suspects[p] = 1;
+ }
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ const p = y * width + x;
+ if (!suspects[p]) continue;
+ const i = p * 4;
+ const pixLow = lowMean(data, i, split);
+ let best = null; // [dist2, -alpha, lowDist, r, g, b]
+ for (let radius = 1; radius <= KEY_REPAIR_RADIUS && !best; radius++) {
+ for (let dy = -radius; dy <= radius; dy++) {
+ for (let dx = -radius; dx <= radius; dx++) {
+ if (Math.max(Math.abs(dx), Math.abs(dy)) !== radius) continue;
+ const nx = x + dx; const ny = y + dy;
+ if (nx < 0 || ny < 0 || nx >= width || ny >= height) continue;
+ const np = ny * width + nx;
+ if (suspects[np]) continue;
+ const ni = np * 4;
+ const na = data[ni + 3];
+ if (na < OPAQUE_EDGE_ALPHA) continue;
+ const cand = [
+ dx * dx + dy * dy, -na, Math.abs(lowMean(data, ni, split) - pixLow),
+ data[ni], data[ni + 1], data[ni + 2],
+ ];
+ if (!best || candLess(cand, best)) best = cand;
+ }
+ }
+ }
+ if (best) {
+ out[i] = best[3]; out[i + 1] = best[4]; out[i + 2] = best[5];
+ } else {
+ px[0] = data[i]; px[1] = data[i + 1]; px[2] = data[i + 2];
+ const spill = Math.max(0, keyness(px, split));
+ for (const h of split.highs) out[i + h] = Math.max(0, data[i + h] - spill);
+ }
+ }
+ }
+ // Final sweep: fully clear noise-floor alpha so transparent pixels carry
+ // no stray RGB into premultiplied resizes downstream.
+ for (let p = 0; p < width * height; p++) {
+ const i = p * 4;
+ if (out[i + 3] <= ALPHA_NOISE_FLOOR) {
+ out[i] = 0; out[i + 1] = 0; out[i + 2] = 0; out[i + 3] = 0;
+ }
+ }
+ return { data: out, width, height };
+}
+
+function candLess(a, b) {
+ for (let i = 0; i < a.length; i++) {
+ if (a[i] !== b[i]) return a[i] < b[i];
+ }
+ return false;
+}
+
+/**
+ * 48×48 RGB comparison signature: composite over the neutral gray, bilinear
+ * downscale. Drives cycle selection and loop-seam validation.
+ */
+export async function signatureOf(frame) {
+ return sharp(frame.data, { raw: { width: frame.width, height: frame.height, channels: 4 } })
+ .flatten({ background: SIGNATURE_BACKGROUND })
+ .resize(SIGNATURE_SIZE, SIGNATURE_SIZE, { kernel: 'linear', fit: 'fill' })
+ .raw()
+ .toBuffer();
+}
+
+/** Mean absolute RGB difference between two signatures (PIL ImageStat semantics). */
+export function imageDistance(a, b) {
+ let sum = 0;
+ for (let i = 0; i < a.length; i++) sum += Math.abs(a[i] - b[i]);
+ return sum / a.length;
+}
+
+/**
+ * Find the best walk-cycle window by endpoint-seam continuity vs motion, and
+ * resample it onto the 8 gait phases. `signatures` is one entry per recovered
+ * source frame.
+ */
+export function selectCycleIndices(signatures) {
+ const n = signatures.length;
+ if (n < WALK_FRAME_COUNT + 1) {
+ throw new Error(`Need at least ${WALK_FRAME_COUNT + 1} extracted frames, got ${n}`);
+ }
+ let best = null; // [score, start, cycleLength, seam, motion]
+ const maxLen = Math.min(18, n - 1);
+ for (let cycleLength = WALK_FRAME_COUNT; cycleLength <= maxLen; cycleLength++) {
+ for (let start = 0; start < n - cycleLength; start++) {
+ const seam = imageDistance(signatures[start], signatures[start + cycleLength]);
+ const motionSamples = [];
+ for (let i = start; i < start + cycleLength; i++) {
+ motionSamples.push(imageDistance(signatures[i], signatures[i + 1]));
+ }
+ const motion = median(motionSamples);
+ if (motion < MIN_CYCLE_MOTION) continue;
+ const score = seam + Math.abs(cycleLength - WALK_FPS) * 0.2 - Math.min(motion, 12) * 0.12;
+ const cand = [score, start, cycleLength, seam, motion];
+ if (!best || candLess(cand, best)) best = cand;
+ }
+ }
+ if (!best) throw new Error('No detectable moving walk cycle in the source video');
+ const [, start, cycleLength, seam, motion] = best;
+ const indices = Array.from({ length: WALK_FRAME_COUNT }, (_, i) => start + pyRound((i * cycleLength) / WALK_FRAME_COUNT));
+ if (new Set(indices).size !== WALK_FRAME_COUNT) {
+ throw new Error('Cycle window too short to resample 8 distinct phases');
+ }
+ return {
+ indices,
+ cycle: {
+ windowStart: start,
+ windowLength: cycleLength,
+ endpointSeamScore: pyRoundTo(seam, 4),
+ medianMotionScore: pyRoundTo(motion, 4),
+ },
+ };
+}
+
+/** Tight bbox of visible (alpha > 24) pixels; exclusive right/bottom. */
+export function alphaBbox(frame) {
+ const { data, width, height } = frame;
+ let left = width; let top = height; let right = -1; let bottom = -1;
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ if (data[(y * width + x) * 4 + 3] > BBOX_ALPHA_THRESHOLD) {
+ if (x < left) left = x;
+ if (x > right) right = x;
+ if (y < top) top = y;
+ if (y > bottom) bottom = y;
+ }
+ }
+ }
+ if (right < 0) return null;
+ return { left, top, right: right + 1, bottom: bottom + 1 };
+}
+
+/**
+ * x-center of the character at the hip/leg band (42%–76% of bbox height) —
+ * the per-frame pivot the alignment pins to x=192.
+ */
+export function rootX(frame, bbox) {
+ const { data, width } = frame;
+ const H = bbox.bottom - bbox.top;
+ const bandTop = bbox.top + pyRound(H * 0.42);
+ const bandBottom = bbox.top + pyRound(H * 0.76);
+ const xs = [];
+ for (let y = bandTop; y < bandBottom; y++) {
+ for (let x = bbox.left; x < bbox.right; x++) {
+ if (data[(y * width + x) * 4 + 3] > ROOT_ALPHA_THRESHOLD) xs.push(x);
+ }
+ }
+ return xs.length ? median(xs) : (bbox.left + bbox.right) / 2;
+}
+
+function cropFrame(frame, bbox) {
+ const w = bbox.right - bbox.left;
+ const h = bbox.bottom - bbox.top;
+ const out = Buffer.alloc(w * h * 4);
+ for (let y = 0; y < h; y++) {
+ const srcStart = ((bbox.top + y) * frame.width + bbox.left) * 4;
+ frame.data.copy(out, y * w * 4, srcStart, srcStart + w * 4);
+ }
+ return { data: out, width: w, height: h };
+}
+
+// sharp premultiplies alpha before resampling and unpremultiplies after —
+// the same alpha-weighted LANCZOS the source's premultiplied_resize does.
+async function premultipliedResize(frame, width, height) {
+ const data = await sharp(frame.data, { raw: { width: frame.width, height: frame.height, channels: 4 } })
+ .resize(width, height, { kernel: 'lanczos3', fit: 'fill' })
+ .raw()
+ .toBuffer();
+ return { data, width, height };
+}
+
+function compositeOnto(canvas, frame, dx, dy) {
+ // Straight-alpha source-over; destinations may be clipped at canvas edges.
+ const { data, width, height } = frame;
+ for (let y = 0; y < height; y++) {
+ const cy = dy + y;
+ if (cy < 0 || cy >= canvas.height) continue;
+ for (let x = 0; x < width; x++) {
+ const cx = dx + x;
+ if (cx < 0 || cx >= canvas.width) continue;
+ const si = (y * width + x) * 4;
+ const sa = data[si + 3] / 255;
+ if (sa === 0) continue;
+ const di = (cy * canvas.width + cx) * 4;
+ const da = canvas.data[di + 3] / 255;
+ const oa = sa + da * (1 - sa);
+ for (let c = 0; c < 3; c++) {
+ canvas.data[di + c] = oa === 0 ? 0 : pyRound((data[si + c] * sa + canvas.data[di + c] * da * (1 - sa)) / oa);
+ }
+ canvas.data[di + 3] = pyRound(oa * 255);
+ }
+ }
+}
+
+const blankFrame = (width, height) => ({ data: Buffer.alloc(width * height * 4), width, height });
+
+/**
+ * One fixed scale + per-frame integer translation: every frame shares the
+ * scale that fits the largest bbox into the cell; the hip pivot lands on
+ * x=192 and the feet baseline on y=352.
+ */
+export async function alignFrames(frames) {
+ const bboxes = frames.map((f) => {
+ const bbox = alphaBbox(f);
+ if (!bbox) throw new Error('Frame has no visible character');
+ return bbox;
+ });
+ const maxWidth = Math.max(...bboxes.map((b) => b.right - b.left));
+ const maxHeight = Math.max(...bboxes.map((b) => b.bottom - b.top));
+ const scale = Math.min(1, (WALK_CELL_SIZE * 0.78) / maxWidth, (WALK_CELL_SIZE * 0.82) / maxHeight);
+ const aligned = [];
+ const translations = [];
+ for (let i = 0; i < frames.length; i++) {
+ const bbox = bboxes[i];
+ const cropped = cropFrame(frames[i], bbox);
+ const size = [Math.max(1, pyRound(cropped.width * scale)), Math.max(1, pyRound(cropped.height * scale))];
+ const resized = await premultipliedResize(cropped, size[0], size[1]);
+ const sourceRootX = (rootX(frames[i], bbox) - bbox.left) * scale;
+ const dx = pyRound(WALK_PIVOT[0] - sourceRootX);
+ const dy = pyRound(WALK_PIVOT[1] - resized.height);
+ const canvas = blankFrame(WALK_CELL_SIZE, WALK_CELL_SIZE);
+ compositeOnto(canvas, resized, dx, dy);
+ aligned.push(canvas);
+ translations.push([dx, dy]);
+ }
+ return {
+ frames: aligned,
+ alignment: {
+ cellSize: WALK_CELL_SIZE,
+ fixedScale: pyRoundTo(scale, 8),
+ targetPivot: WALK_PIVOT,
+ operation: 'one-fixed-scale-plus-per-frame-translation',
+ translations,
+ },
+ };
+}
+
+/** Pack the 8 aligned frames into the single-row 3072×384 strip. */
+export function packStrip(frames) {
+ const strip = blankFrame(WALK_CELL_SIZE * frames.length, WALK_CELL_SIZE);
+ frames.forEach((frame, i) => compositeOnto(strip, frame, i * WALK_CELL_SIZE, 0));
+ return strip;
+}
+
+function keyMass(frame, split) {
+ const { data } = frame;
+ const px = [0, 0, 0];
+ let mass = 0;
+ for (let i = 0; i < data.length; i += 4) {
+ px[0] = data[i]; px[1] = data[i + 1]; px[2] = data[i + 2];
+ mass += Math.max(0, keyness(px, split)) * (data[i + 3] / 255);
+ }
+ return pyRoundTo(mass, 3);
+}
+
+function keyDominantPixels(frame, split) {
+ const { data } = frame;
+ const px = [0, 0, 0];
+ let count = 0;
+ for (let i = 0; i < data.length; i += 4) {
+ if (data[i + 3] <= ALPHA_NOISE_FLOOR) continue;
+ px[0] = data[i]; px[1] = data[i + 1]; px[2] = data[i + 2];
+ if (keyness(px, split) > KEY_VALIDATION_FLOOR) count++;
+ }
+ return count;
+}
+
+/**
+ * Validate the packed candidate: 8 distinct frames, tolerable loop seam,
+ * no visible key residue.
+ */
+export async function validateFrames(frames, split) {
+ if (frames.length !== WALK_FRAME_COUNT) {
+ throw new Error(`Expected ${WALK_FRAME_COUNT} frames, got ${frames.length}`);
+ }
+ const hashes = frames.map((f) => sha256Buffer(f.data));
+ if (new Set(hashes).size !== frames.length) throw new Error('Duplicate frames in the packed cycle');
+ const signatures = await Promise.all(frames.map(signatureOf));
+ const adjacent = signatures.map((sig, i) => pyRoundTo(imageDistance(sig, signatures[(i + 1) % frames.length]), 4));
+ const seam = adjacent[adjacent.length - 1];
+ const typical = median(adjacent.slice(0, -1));
+ if (seam > Math.max(12, typical * 2.5)) {
+ throw new Error(`Loop seam too visible (seam ${seam} vs typical ${pyRoundTo(typical, 4)})`);
+ }
+ const dominant = frames.map((f) => keyDominantPixels(f, split));
+ const masses = frames.map((f) => keyMass(f, split));
+ if (dominant.some((c) => c > 0)) throw new Error('Visible key color remains after despill');
+ if (masses.some((m) => m > MAX_KEY_MASS)) throw new Error('Excess alpha-weighted key mass after despill');
+ return {
+ distinctFrames: true,
+ adjacentDifferenceScores: adjacent,
+ loopSeamScore: seam,
+ medianAdjacentScore: pyRoundTo(typical, 4),
+ keyDominantPixels: dominant,
+ alphaWeightedKeyMass: masses,
+ backgroundsReviewed: ['light', 'dark', 'checker'],
+ };
+}
+
+const CONTRAST_THUMB = 128;
+const CONTRAST_ROWS = [
+ { key: 'light', color: [244, 241, 232] },
+ { key: 'dark', color: [22, 28, 31] },
+ { key: 'checker', color: null },
+];
+const CHECKER_LIGHT = [222, 227, 229];
+const CHECKER_DARK = [171, 181, 185];
+const CHECKER_SQUARE = 16;
+
+/** 3-row (light/dark/checker) contrast review sheet, RGB 1024×384. */
+export async function buildContrastSheet(frames) {
+ const width = CONTRAST_THUMB * frames.length;
+ const height = CONTRAST_THUMB * CONTRAST_ROWS.length;
+ const sheet = Buffer.alloc(width * height * 3);
+ const thumbs = await Promise.all(frames.map((f) => premultipliedResize(f, CONTRAST_THUMB, CONTRAST_THUMB)));
+ CONTRAST_ROWS.forEach((row, rowIdx) => {
+ thumbs.forEach((thumb, col) => {
+ for (let y = 0; y < CONTRAST_THUMB; y++) {
+ for (let x = 0; x < CONTRAST_THUMB; x++) {
+ const bg = row.color
+ || ((Math.floor(x / CHECKER_SQUARE) + Math.floor(y / CHECKER_SQUARE)) % 2 === 0 ? CHECKER_LIGHT : CHECKER_DARK);
+ const si = (y * CONTRAST_THUMB + x) * 4;
+ const a = thumb.data[si + 3] / 255;
+ const di = ((rowIdx * CONTRAST_THUMB + y) * width + col * CONTRAST_THUMB + x) * 3;
+ for (let c = 0; c < 3; c++) {
+ sheet[di + c] = clampChannel(thumb.data[si + c] * a + bg[c] * (1 - a));
+ }
+ }
+ }
+ });
+ });
+ return { data: sheet, width, height };
+}
+
+/**
+ * Extract raw frames from the walk video: 12fps, longest side capped at 512
+ * (decrease-only), first 8 seconds. Returns the sorted raw PNG filenames.
+ */
+export async function extractVideoFrames(videoPath, rawDir) {
+ const ffmpeg = await findFfmpeg();
+ if (!ffmpeg) throw new Error('ffmpeg not found — install ffmpeg to postprocess walk videos');
+ await ensureDir(rawDir);
+ const result = await runFfmpegProcess({
+ bin: ffmpeg,
+ args: [
+ '-hide_banner', '-loglevel', 'error', '-y',
+ '-i', videoPath,
+ '-vf', `fps=${WALK_FPS},scale=w='min(${MAX_SOURCE_DIMENSION},iw)':h='min(${MAX_SOURCE_DIMENSION},ih)':force_original_aspect_ratio=decrease`,
+ '-t', String(MAX_SOURCE_SECONDS),
+ join(rawDir, 'source-%04d.png'),
+ ],
+ });
+ if (!result.ok) throw new Error(`Frame extraction failed: ${result.reason}`);
+ const names = (await readdir(rawDir)).filter((n) => /^source-\d{4}\.png$/.test(n)).sort();
+ if (!names.length) throw new Error('Frame extraction produced no frames');
+ return names;
+}
+
+/**
+ * Prepare the transparent i2v motion input from a locked anchor (opaque on
+ * its key): measured-key alpha recovery + despill, saved as a straight-alpha
+ * PNG. An anchor that already carries transparency is passed through.
+ */
+export async function prepareWalkAnchorInput(anchorAbs, destAbs, chromaKey) {
+ const split = keyChannelSplit(chromaKey);
+ const frame = await decodeRgbaFrame(anchorAbs);
+ let alreadyTransparent = false;
+ for (let i = 3; i < frame.data.length; i += 4) {
+ if (frame.data[i] < 255) { alreadyTransparent = true; break; }
+ }
+ let prepared = frame;
+ if (!alreadyTransparent) {
+ const measured = sampleBorderKey(frame);
+ validateMeasuredKey(measured, split, chromaKey);
+ prepared = recoverAlphaFrame(frame, measured, split);
+ }
+ prepared = despillKeyFrame(prepared, split);
+ await encodePng(prepared, destAbs);
+ return { preparation: 'measured-key-alpha-recovery-plus-despill' };
+}
+
+/**
+ * The full deterministic postprocess for one completed walk video.
+ *
+ * `runRel` is the record-relative run root (`grok/walk-<dir>-<jobId>`); all
+ * artifacts are written under `<runAbs>/generated/` and all manifest paths
+ * are record-relative, matching what the phase-1 importer expects.
+ */
+export async function runWalkPostprocess({
+ recordId, direction, chromaKey, runAbs, runRel, anchorRel, anchorAbs, videoAbs,
+}) {
+ const split = keyChannelSplit(chromaKey);
+ const generatedAbs = join(runAbs, 'generated');
+ const generatedRel = `${runRel}/generated`;
+ const rawDir = join(generatedAbs, 'raw');
+
+ const rawNames = await extractVideoFrames(videoAbs, rawDir);
+ const rawFrames = [];
+ const recovered = [];
+ const measuredKeys = [];
+ for (const name of rawNames) {
+ const frame = await decodeRgbaFrame(join(rawDir, name));
+ const measured = sampleBorderKey(frame);
+ validateMeasuredKey(measured, split, chromaKey);
+ rawFrames.push(frame);
+ measuredKeys.push(measured);
+ recovered.push(recoverAlphaFrame(frame, measured, split));
+ }
+
+ const signatures = await Promise.all(recovered.map(signatureOf));
+ const { indices, cycle } = selectCycleIndices(signatures);
+ const selected = indices.map((i) => recovered[i]);
+
+ const { frames: aligned, alignment } = await alignFrames(selected);
+ const despilled = aligned.map((f) => despillKeyFrame(f, split));
+ const validation = await validateFrames(despilled, split);
+
+ const framesDir = join(generatedAbs, 'frames');
+ await ensureDir(framesDir);
+ const frameRecords = [];
+ for (let i = 0; i < despilled.length; i++) {
+ const phase = WALK_PHASES[i];
+ const name = `${String(i).padStart(2, '0')}-${phase}.png`;
+ const dest = join(framesDir, name);
+ await encodePng(despilled[i], dest);
+ frameRecords.push({
+ outputIndex: i,
+ phase,
+ sourceFrameIndex: indices[i] + 1, // 1-based, matches raw source-%04d numbering
+ sourcePath: `${generatedRel}/raw/${rawNames[indices[i]]}`,
+ sourceSha256: await sha256File(join(rawDir, rawNames[indices[i]])),
+ measuredKeyRgb: measuredKeys[indices[i]],
+ path: `${generatedRel}/frames/${name}`,
+ sha256: await sha256File(dest),
+ });
+ }
+
+ const stripName = `${recordId}-walk-${direction}-strip.png`;
+ const stripAbs = join(generatedAbs, stripName);
+ await encodePng(packStrip(despilled), stripAbs);
+
+ const reviewDir = join(generatedAbs, 'review');
+ await ensureDir(reviewDir);
+ const contrastName = `${recordId}-walk-${direction}-contrast-review.png`;
+ const contrastAbs = join(reviewDir, contrastName);
+ const sheet = await buildContrastSheet(despilled);
+ await encodePng(sheet, contrastAbs, 3);
+
+ const manifestName = `${recordId}-walk-${direction}-manifest.json`;
+ const manifest = {
+ schemaVersion: 1,
+ kind: 'deterministically-packaged-grok-walk-video',
+ status: 'candidate',
+ characterId: recordId,
+ direction,
+ chromaKey,
+ anchorPath: anchorRel,
+ anchorSha256: await sha256File(anchorAbs),
+ sourceVideoPath: `${generatedRel}/source-video.mp4`,
+ sourceVideoSha256: await sha256File(videoAbs),
+ postprocessorPath: 'server/services/sprites/walkPostprocess.js',
+ manifestPath: `${generatedRel}/${manifestName}`,
+ frameRate: WALK_FPS,
+ frameCount: WALK_FRAME_COUNT,
+ cycleSelection: cycle,
+ chromaCleanup: {
+ method: 'measured-key-unmixing-plus-key-vector-despill',
+ keyColor: chromaKey,
+ despillFloor: KEY_DESPILL_FLOOR,
+ validationFloor: KEY_VALIDATION_FLOOR,
+ },
+ alignment,
+ validation,
+ frames: frameRecords,
+ stripPath: `${generatedRel}/${stripName}`,
+ stripSha256: await sha256File(stripAbs),
+ comparisonPath: `${generatedRel}/review/${contrastName}`,
+ comparisonSha256: await sha256File(contrastAbs),
+ };
+ await atomicWrite(join(generatedAbs, manifestName), manifest);
+
+ const stripPreview = {
+ stripPath: `${generatedRel}/${stripName}`,
+ frameCount: WALK_FRAME_COUNT,
+ fps: WALK_FPS,
+ cellWidth: WALK_CELL_SIZE,
+ cellHeight: WALK_CELL_SIZE,
+ row: 0,
+ startColumn: 0,
+ };
+ await atomicWrite(join(generatedAbs, 'review-preview.json'), stripPreview);
+
+ return { manifest, manifestPath: `${generatedRel}/${manifestName}`, stripPreview };
+}
diff --git a/server/services/sprites/walkPostprocess.test.js b/server/services/sprites/walkPostprocess.test.js
new file mode 100644
index 0000000000..5f7a40403f
--- /dev/null
+++ b/server/services/sprites/walkPostprocess.test.js
@@ -0,0 +1,306 @@
+/**
+ * Deterministic walk postprocess (#2897): the per-pixel un-key/despill math,
+ * cycle selection (including Python round-half-to-even parity), alignment
+ * geometry, packing, and validation — all on synthetic raw frames, no ffmpeg.
+ * The video-in e2e lives in walkPostprocess.e2e.test.js (ffmpeg-gated).
+ */
+
+import { describe, it, expect, afterAll } from 'vitest';
+import { mkdtempSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import sharp from 'sharp';
+import {
+ pyRound, pyRoundTo, median, sampleBorderKey, validateMeasuredKey,
+ recoverAlphaFrame, despillKeyFrame, imageDistance, selectCycleIndices,
+ alphaBbox, rootX, alignFrames, packStrip, validateFrames, buildContrastSheet,
+ prepareWalkAnchorInput, WALK_PHASES, WALK_CELL_SIZE, WALK_FRAME_COUNT,
+} from './walkPostprocess.js';
+import { keyChannelSplit } from './chromaKey.js';
+
+const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-walkpp-test-'));
+afterAll(() => rmSync(TEST_ROOT, { recursive: true, force: true }));
+
+const MAGENTA = keyChannelSplit('#FF00FF');
+const GREEN = keyChannelSplit('#00FF00');
+
+function makeFrame(width, height, fill = [0, 0, 0, 0]) {
+ const data = Buffer.alloc(width * height * 4);
+ for (let p = 0; p < width * height; p++) data.set(fill, p * 4);
+ return { data, width, height };
+}
+
+function setPx(frame, x, y, rgba) {
+ frame.data.set(rgba, (y * frame.width + x) * 4);
+}
+
+function getPx(frame, x, y) {
+ const i = (y * frame.width + x) * 4;
+ return [...frame.data.subarray(i, i + 4)];
+}
+
+function fillRect(frame, x0, y0, x1, y1, rgba) {
+ for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) setPx(frame, x, y, rgba);
+}
+
+describe('pyRound / pyRoundTo / median', () => {
+ it('rounds half to even like Python', () => {
+ expect(pyRound(0.5)).toBe(0);
+ expect(pyRound(1.5)).toBe(2);
+ expect(pyRound(2.5)).toBe(2);
+ expect(pyRound(3.5)).toBe(4);
+ expect(pyRound(-0.5)).toBe(0);
+ expect(pyRound(-1.5)).toBe(-2);
+ expect(pyRound(2.4)).toBe(2);
+ expect(pyRound(2.6)).toBe(3);
+ });
+
+ it('rounds to decimals', () => {
+ expect(pyRoundTo(1.23456789, 4)).toBeCloseTo(1.2346, 10);
+ expect(pyRoundTo(10.123, 2)).toBeCloseTo(10.12, 10);
+ });
+
+ it('median matches statistics.median', () => {
+ expect(median([3, 1, 2])).toBe(2);
+ expect(median([4, 1, 3, 2])).toBe(2.5);
+ });
+});
+
+describe('sampleBorderKey / validateMeasuredKey', () => {
+ it('measures the border matte, ignoring the character', () => {
+ const frame = makeFrame(64, 64, [250, 5, 252, 255]);
+ fillRect(frame, 20, 20, 44, 44, [10, 200, 30, 255]);
+ expect(sampleBorderKey(frame)).toEqual([250, 5, 252]);
+ });
+
+ it('accepts a balanced key and rejects dim or lopsided ones', () => {
+ expect(() => validateMeasuredKey([250, 5, 252], MAGENTA, '#FF00FF')).not.toThrow();
+ expect(() => validateMeasuredKey([120, 60, 120], MAGENTA, '#FF00FF')).toThrow(/matte/);
+ expect(() => validateMeasuredKey([255, 0, 100], MAGENTA, '#FF00FF')).toThrow(/matte/);
+ expect(() => validateMeasuredKey([5, 250, 8], GREEN, '#00FF00')).not.toThrow();
+ // A magenta screen is not a usable green matte.
+ expect(() => validateMeasuredKey([250, 5, 252], GREEN, '#00FF00')).toThrow(/matte/);
+ });
+});
+
+describe('recoverAlphaFrame', () => {
+ const key = [255, 0, 255];
+
+ it('zeroes pure key pixels and passes character pixels through opaque', () => {
+ const frame = makeFrame(2, 1);
+ setPx(frame, 0, 0, [255, 0, 255, 255]);
+ setPx(frame, 1, 0, [30, 120, 40, 255]);
+ const out = recoverAlphaFrame(frame, key, MAGENTA);
+ expect(getPx(out, 0, 0)).toEqual([0, 0, 0, 0]);
+ expect(getPx(out, 1, 0)).toEqual([30, 120, 40, 255]);
+ });
+
+ it('unmixes an antialiased edge pixel with the alpha ramp', () => {
+ const frame = makeFrame(1, 1);
+ // 50/50 blend of black character over the key.
+ setPx(frame, 0, 0, [128, 0, 128, 255]);
+ const [r, g, b, a] = getPx(recoverAlphaFrame(frame, key, MAGENTA), 0, 0);
+ const share = 128 / 255;
+ const sourceAlpha = 1 - share;
+ const expectedAlpha = pyRound(((sourceAlpha - 0.06) * 255) / 0.94);
+ expect(a).toBe(expectedAlpha);
+ expect(r).toBe(pyRound((128 - share * 255) / sourceAlpha));
+ expect(g).toBe(0);
+ expect(b).toBe(r);
+ });
+
+ it('handles the green key symmetrically', () => {
+ const frame = makeFrame(2, 1);
+ setPx(frame, 0, 0, [0, 255, 0, 255]);
+ setPx(frame, 1, 0, [200, 40, 180, 255]);
+ const out = recoverAlphaFrame(frame, [0, 255, 0], GREEN);
+ expect(getPx(out, 0, 0)).toEqual([0, 0, 0, 0]);
+ expect(getPx(out, 1, 0)).toEqual([200, 40, 180, 255]);
+ });
+});
+
+describe('despillKeyFrame', () => {
+ it('borrows RGB from the nearest clean opaque neighbor, keeping alpha', () => {
+ const frame = makeFrame(3, 1);
+ setPx(frame, 0, 0, [40, 90, 50, 255]); // clean opaque
+ setPx(frame, 1, 0, [180, 20, 170, 130]); // key-tinted edge suspect
+ setPx(frame, 2, 0, [0, 0, 0, 0]);
+ const out = despillKeyFrame(frame, MAGENTA);
+ expect(getPx(out, 1, 0)).toEqual([40, 90, 50, 130]);
+ expect(getPx(out, 0, 0)).toEqual([40, 90, 50, 255]);
+ });
+
+ it('falls back to spill subtraction when no clean neighbor exists', () => {
+ const frame = makeFrame(1, 1);
+ setPx(frame, 0, 0, [200, 30, 190, 255]); // keyness = min(200,190)-30 = 160
+ const out = despillKeyFrame(frame, MAGENTA);
+ expect(getPx(out, 0, 0)).toEqual([40, 30, 30, 255]);
+ });
+
+ it('clears RGB under the alpha noise floor', () => {
+ const frame = makeFrame(1, 1);
+ setPx(frame, 0, 0, [90, 10, 80, 2]);
+ expect(getPx(despillKeyFrame(frame, MAGENTA), 0, 0)).toEqual([0, 0, 0, 0]);
+ });
+});
+
+describe('selectCycleIndices', () => {
+ const SIG_LEN = 48 * 48 * 3;
+ const constSig = (v) => Buffer.alloc(SIG_LEN, v);
+
+ it('finds the periodic window and resamples with banker\'s rounding', () => {
+ // Period-12 sawtooth: seam 0 at cycleLength 12, median motion 10.
+ const pattern = [0, 10, 20, 30, 40, 50, 60, 50, 40, 30, 20, 10];
+ const signatures = Array.from({ length: 25 }, (_, i) => constSig(pattern[i % 12]));
+ const { indices, cycle } = selectCycleIndices(signatures);
+ expect(cycle.windowStart).toBe(0);
+ expect(cycle.windowLength).toBe(12);
+ expect(cycle.endpointSeamScore).toBe(0);
+ expect(cycle.medianMotionScore).toBe(10);
+ // round(i*12/8) = round(i*1.5) — half-to-even: 1.5→2, 4.5→4, 7.5→8, 10.5→10.
+ expect(indices).toEqual([0, 2, 3, 4, 6, 8, 9, 10]);
+ });
+
+ it('rejects a static clip and too-few frames', () => {
+ expect(() => selectCycleIndices(Array.from({ length: 20 }, () => constSig(7))))
+ .toThrow(/no detectable moving walk cycle/i);
+ expect(() => selectCycleIndices(Array.from({ length: 8 }, () => constSig(0))))
+ .toThrow(/at least 9/);
+ });
+
+ it('imageDistance is the mean absolute channel difference', () => {
+ expect(imageDistance(constSig(10), constSig(10))).toBe(0);
+ expect(imageDistance(constSig(0), constSig(30))).toBe(30);
+ });
+});
+
+describe('alphaBbox / rootX', () => {
+ it('finds the visible bbox (exclusive right/bottom) and the hip-band pivot', () => {
+ const frame = makeFrame(40, 60);
+ fillRect(frame, 10, 5, 30, 55, [50, 50, 50, 255]);
+ const bbox = alphaBbox(frame);
+ expect(bbox).toEqual({ left: 10, top: 5, right: 30, bottom: 55 });
+ expect(rootX(frame, bbox)).toBe(19.5); // symmetric rect → center column median
+ expect(alphaBbox(makeFrame(8, 8))).toBeNull();
+ });
+});
+
+describe('alignFrames / packStrip', () => {
+ it('applies one fixed scale and pins pivot x and the feet baseline', async () => {
+ const frame = makeFrame(200, 300);
+ fillRect(frame, 50, 40, 150, 240, [80, 60, 40, 255]); // 100×200 char
+ const { frames, alignment } = await alignFrames([frame]);
+ expect(frames[0].width).toBe(WALK_CELL_SIZE);
+ expect(alignment.fixedScale).toBe(1); // fits inside 299×314 unscaled
+ expect(alignment.operation).toBe('one-fixed-scale-plus-per-frame-translation');
+ const [dx, dy] = alignment.translations[0];
+ expect(dy).toBe(352 - 200); // feet on the baseline
+ expect(dx).toBe(192 - 50); // hip median (col 99.5 abs → 49.5 rel) → pyRound(192-49.5)=142
+ // Feet row is the last opaque row; canvas is transparent below it.
+ const feetRowAlpha = frames[0].data[(351 * WALK_CELL_SIZE + 192) * 4 + 3];
+ const belowAlpha = frames[0].data[(352 * WALK_CELL_SIZE + 192) * 4 + 3];
+ expect(feetRowAlpha).toBe(255);
+ expect(belowAlpha).toBe(0);
+ });
+
+ it('downsizes an oversized character with an 8dp fixed scale', async () => {
+ const frame = makeFrame(500, 600);
+ fillRect(frame, 20, 20, 420, 520, [10, 10, 10, 255]); // 400×500
+ const { alignment } = await alignFrames([frame]);
+ expect(alignment.fixedScale).toBe(pyRoundTo(Math.min((384 * 0.78) / 400, (384 * 0.82) / 500), 8));
+ expect(alignment.fixedScale).toBeLessThan(1);
+ });
+
+ it('packs 8 cells into one 3072×384 row', () => {
+ const frames = Array.from({ length: 8 }, () => makeFrame(WALK_CELL_SIZE, WALK_CELL_SIZE));
+ const strip = packStrip(frames);
+ expect(strip.width).toBe(WALK_CELL_SIZE * 8);
+ expect(strip.height).toBe(WALK_CELL_SIZE);
+ });
+});
+
+// 8 distinct frames whose rect walks a circle — every position is unique,
+// adjacent steps are uniform, and the loop seam (frame7→frame0) matches the
+// typical adjacent step.
+function oscillatingFrames(paint = [240, 240, 240, 255]) {
+ return Array.from({ length: 8 }, (_, i) => {
+ const angle = (i * Math.PI) / 4;
+ const ox = Math.round(16 * Math.sin(angle));
+ const oy = Math.round(16 * Math.cos(angle));
+ const f = makeFrame(WALK_CELL_SIZE, WALK_CELL_SIZE);
+ fillRect(f, 100 + ox, 80 + oy, 220 + ox, 320 + oy, paint);
+ return f;
+ });
+}
+
+describe('validateFrames', () => {
+ it('accepts a clean oscillating cycle', async () => {
+ const validation = await validateFrames(oscillatingFrames(), MAGENTA);
+ expect(validation.distinctFrames).toBe(true);
+ expect(validation.adjacentDifferenceScores).toHaveLength(8);
+ expect(validation.keyDominantPixels).toEqual([0, 0, 0, 0, 0, 0, 0, 0]);
+ expect(validation.backgroundsReviewed).toEqual(['light', 'dark', 'checker']);
+ });
+
+ it('rejects duplicate frames and visible key residue', async () => {
+ const dupes = Array.from({ length: 8 }, () => makeFrame(WALK_CELL_SIZE, WALK_CELL_SIZE, [9, 9, 9, 255]));
+ await expect(validateFrames(dupes, MAGENTA)).rejects.toThrow(/duplicate/i);
+ const residue = oscillatingFrames();
+ fillRect(residue[3], 10, 10, 20, 20, [230, 20, 220, 255]);
+ await expect(validateFrames(residue, MAGENTA)).rejects.toThrow(/key color remains/i);
+ });
+
+ it('rejects a visible loop seam', async () => {
+ const frames = oscillatingFrames();
+ // Last frame teleports far from frame 0 → seam >> typical.
+ frames[7] = makeFrame(WALK_CELL_SIZE, WALK_CELL_SIZE);
+ fillRect(frames[7], 10, 10, 130, 250, [240, 240, 240, 255]);
+ await expect(validateFrames(frames, MAGENTA)).rejects.toThrow(/loop seam/i);
+ });
+});
+
+describe('buildContrastSheet', () => {
+ it('renders the 3-row 1024×384 sheet with a checkered bottom row', async () => {
+ const sheet = await buildContrastSheet(oscillatingFrames());
+ expect(sheet.width).toBe(1024);
+ expect(sheet.height).toBe(384);
+ // Transparent corner of the checker row shows the checker colors.
+ const px = (x, y) => [...sheet.data.subarray((y * 1024 + x) * 3, (y * 1024 + x) * 3 + 3)];
+ expect(px(0, 256)).toEqual([222, 227, 229]);
+ expect(px(16, 256)).toEqual([171, 181, 185]);
+ expect(px(0, 0)).toEqual([244, 241, 232]);
+ expect(px(0, 128)).toEqual([22, 28, 31]);
+ });
+});
+
+describe('prepareWalkAnchorInput', () => {
+ it('recovers a transparent despilled input from an opaque keyed anchor', async () => {
+ const w = 64; const h = 64;
+ const rgb = Buffer.alloc(w * h * 3);
+ for (let p = 0; p < w * h; p++) rgb.set([255, 0, 255], p * 3);
+ for (let y = 20; y < 50; y++) {
+ for (let x = 24; x < 40; x++) rgb.set([30, 110, 60], (y * w + x) * 3);
+ }
+ const anchorAbs = join(TEST_ROOT, 'anchor.png');
+ const destAbs = join(TEST_ROOT, 'input.png');
+ await sharp(rgb, { raw: { width: w, height: h, channels: 3 } }).png().toFile(anchorAbs);
+ const { preparation } = await prepareWalkAnchorInput(anchorAbs, destAbs, '#FF00FF');
+ expect(preparation).toBe('measured-key-alpha-recovery-plus-despill');
+ const { data, info } = await sharp(destAbs).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
+ expect(info.channels).toBe(4);
+ expect(data[3]).toBe(0); // key corner → transparent
+ const charI = ((25 * w) + 30) * 4;
+ expect(data[charI + 3]).toBe(255); // character stays opaque
+ expect([data[charI], data[charI + 1], data[charI + 2]]).toEqual([30, 110, 60]);
+ });
+});
+
+describe('constants', () => {
+ it('exposes the canonical gait phases in order', () => {
+ expect(WALK_PHASES).toEqual([
+ 'left-contact', 'left-down', 'left-passing', 'left-up',
+ 'right-contact', 'right-down', 'right-passing', 'right-up',
+ ]);
+ expect(WALK_FRAME_COUNT).toBe(8);
+ });
+});