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
feat([issue-2897]): walk workflow orchestration — grok i2v runs, completion-hook packaging, approval, loop trims
[._.]/ Adam Eivy6361db32cce3
diff --git a/server/index.js b/server/index.jsindex 8214211082..cc000b0756 100644--- a/server/index.js+++ b/server/index.js@@ -136,6 +136,7 @@ import { initCatalogImageAttachHook } from './services/catalogImageAttachHook.jsimport { initWritersRoomSceneImageHook } from './services/writersRoomSceneImageHook.js';import { initMusicVideoSceneImageHook } from './services/musicVideoSceneImageHook.js';import { initSpriteReferenceImageHook } from './services/spriteReferenceImageHook.js';+import { initSpriteWalkVideoHook } from './services/spriteWalkVideoHook.js';import { initMusicVideoSceneVideoHook } from './services/musicVideoSceneVideoHook.js';import { initCreativeDirectorMusicBedHook } from './services/creativeDirectorMusicBedHook.js';import { initCreativeDirectorSceneImageHook } from './services/creativeDirectorSceneImageHook.js';@@ -867,6 +868,7 @@ ensureSelf()// render into the sprite record's reference/candidates/ with a generation// sidecar (#2896). Also depends on the queue being loaded.initSpriteReferenceImageHook();+ initSpriteWalkVideoHook();// Creative Director scene-frame hook — durably files a queued first-pass// reference-frame render onto its project scene's `sourceImageFile` on// completion, even if no client is watching (#1867). Also depends on thediff --git a/server/lib/validation.js b/server/lib/validation.jsindex 46289b823f..d086e74845 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -3,7 +3,7 @@ import { ServerError } from './errorHandler.js';import { partialWithoutDefaults, emptyToUndefined, emptyToNull } from './zodCompat.js';import { WORK_TRACKERS } from './workTracker.js';import { SPRITE_ID_PATTERN } from '../services/sprites/recordsLogic.js';-import { ANCHOR_DIRECTIONS } from '../services/sprites/prompts.js';+import { ANCHOR_DIRECTIONS, SPRITE_DIRECTIONS } from '../services/sprites/prompts.js';import { CHROMA_KEY_HEXES } from '../services/sprites/chromaKey.js';import { QUEUEABLE_IMAGE_MODES } from '../services/imageGen/modes.js';@@ -1009,6 +1009,44 @@ export const spriteReferenceLockSchema = z.object({acceptClipRisk: z.boolean().optional(),});+// Phase 3 (issue #2897): walk-animation workflow. All 8 directions are+// animatable (south's anchor is the frozen main itself).+const spriteWalkDirectionSchema = z.enum(SPRITE_DIRECTIONS);++const spriteWalkRunIdSchema = z.string().regex(/^walk-[a-z-]+-[0-9a-f]{8}$/);++export const spriteWalkGenerateSchema = z.object({+ direction: spriteWalkDirectionSchema,+ // Grok image_to_video accepts exactly these lengths; the service defaults+ // to the shorter clip when omitted.+ duration: z.union([z.literal(6), z.literal(10)]).optional(),+});++export const spriteWalkApproveSchema = z.object({+ direction: spriteWalkDirectionSchema,+ runId: spriteWalkRunIdSchema,+});++export const spriteWalkPostprocessSchema = z.object({+ runId: spriteWalkRunIdSchema,+});++const trimColumnsSchema = z.array(z.number().int().min(0).max(255)).min(2).max(256)+ .refine((cols) => new Set(cols).size === cols.length, { message: 'columns must be unique' });++export const spriteWalkTrimSchema = z.object({+ slug: z.string().regex(/^[a-z0-9][a-z0-9-]{0,79}$/),+ atlasPath: z.string().min(1).max(500),+ row: z.number().int().min(0).max(63),+ cellWidth: z.number().int().min(1).max(4096),+ cellHeight: z.number().int().min(1).max(4096),+ fps: z.number().int().min(1).max(60),+ allColumns: trimColumnsSchema,+ enabledColumns: trimColumnsSchema,+ sourceFrameIndices: z.array(z.number().int().min(0)).max(256).optional(),+ sourceFrameLabels: z.array(z.string().max(200)).max(256).optional(),+});+// =============================================================================// TRANSITIONAL RE-EXPORTS (issue #1151 split)// =============================================================================diff --git a/server/routes/mediaJobs.js b/server/routes/mediaJobs.jsindex dd1059d232..e143ae2c40 100644--- a/server/routes/mediaJobs.js+++ b/server/routes/mediaJobs.js@@ -91,6 +91,9 @@ const PARAM_ALLOWLIST = new Set([// UI correlates queued/running renders by it to rehydrate its in-flight// guard after a reload.'spriteRef',+ // Sprite walk-video destination tag (#2897) — record id, direction, run id,+ // key hex; same rehydration contract as spriteRef, for kind:'video' jobs.+ 'spriteWalk',]);function sanitizeJob(job) {if (!job) return job;diff --git a/server/routes/sprites.js b/server/routes/sprites.jsindex ee84c82830..0660e9a25e 100644--- a/server/routes/sprites.js+++ b/server/routes/sprites.js@@ -19,6 +19,10 @@ import {spriteCreateSchema,spriteReferenceGenerateSchema,spriteReferenceLockSchema,+ spriteWalkGenerateSchema,+ spriteWalkApproveSchema,+ spriteWalkPostprocessSchema,+ spriteWalkTrimSchema,} from '../lib/validation.js';import { optionalUploadFields } from '../lib/multipart.js';import {@@ -28,6 +32,10 @@ import { importFromSource } from '../services/sprites/importer.js';import {getReferenceSet, startReferenceGeneration, lockReference, patchSpriteRecord,} from '../services/sprites/reference.js';+import {+ getWalkState, startWalkGeneration, approveWalkDirection, rerunWalkPostprocess,+} from '../services/sprites/walk.js';+import { saveLoopTrim } from '../services/sprites/walkTrims.js';const router = Router();@@ -63,8 +71,10 @@ router.post('/import', asyncHandler(async (req, res) => {router.get('/:id', asyncHandler(async (req, res) => {const detail = await getRecordWithAssets(req.params.id);if (!detail) throw new ServerError('Sprite record not found', { status: 404, code: 'NOT_FOUND' });- const reference = detail.record.kind === 'character' ? await getReferenceSet(req.params.id) : null;- res.json({ ...detail, reference });+ const isCharacter = detail.record.kind === 'character';+ const reference = isCharacter ? await getReferenceSet(req.params.id) : null;+ const walk = isCharacter ? await getWalkState(req.params.id) : null;+ res.json({ ...detail, reference, walk });}));// Queue one reference candidate render (main or a directional anchor).@@ -92,6 +102,35 @@ router.post('/:id/reference/lock', asyncHandler(async (req, res) => {res.json(await lockReference(req.params.id, body));}));+// Phase 3 (#2897): queue one grok walk video for a locked directional+// anchor. User-triggered per the AI-provider policy; everything after the+// clip is deterministic local postprocessing.+router.post('/:id/walk/generate', asyncHandler(async (req, res) => {+ const body = validateRequest(spriteWalkGenerateSchema, req.body);+ res.json(await startWalkGeneration(req.params.id, body));+}));++// Approve one direction's packaged candidate; the 8th approval freezes the+// finalized walk set (immutable — 409 on later generate/approve).+router.post('/:id/walk/approve', asyncHandler(async (req, res) => {+ const body = validateRequest(spriteWalkApproveSchema, req.body);+ res.json(await approveWalkDirection(req.params.id, body));+}));++// Re-run the deterministic postprocess for a run whose video already landed+// (crash recovery / determinism verification). No AI call involved.+router.post('/:id/walk/postprocess', asyncHandler(async (req, res) => {+ const body = validateRequest(spriteWalkPostprocessSchema, req.body);+ res.json(await rerunWalkPostprocess(req.params.id, body));+}));++// Non-destructive loop trim: re-pack enabled frames from a packed strip into+// a versioned trimmed strip + preview GIF. Never mutates the source atlas.+router.post('/:id/walk/trim', asyncHandler(async (req, res) => {+ const body = validateRequest(spriteWalkTrimSchema, req.body);+ res.status(201).json(await saveLoopTrim(req.params.id, body));+}));+// Chroma-key changes route through patchSpriteRecord, which re-checks the// lock state inside the same per-record write tail as `/reference/lock`// (409 CHROMA_KEY_LOCKED after the main freezes).diff --git a/server/routes/sprites.test.js b/server/routes/sprites.test.jsindex 0a0da49ed2..e5b2dd1fa8 100644--- a/server/routes/sprites.test.js+++ b/server/routes/sprites.test.js@@ -21,9 +21,22 @@ vi.mock('../services/sprites/reference.js', () => ({patchSpriteRecord: vi.fn(async (id, patch) => ({ id, ...patch })),}));+vi.mock('../services/sprites/walk.js', () => ({+ getWalkState: vi.fn(async () => ({ runs: [], selection: null, walkSet: null })),+ startWalkGeneration: vi.fn(async () => ({ jobId: 'v1', runId: 'walk-east-0a1b2c3d', direction: 'east', duration: 6 })),+ approveWalkDirection: vi.fn(async () => ({ runs: [], selection: { status: 'in-progress' }, walkSet: null })),+ rerunWalkPostprocess: vi.fn(async () => ({ id: 'walk-east-0a1b2c3d', status: 'candidate' })),+}));++vi.mock('../services/sprites/walkTrims.js', () => ({+ saveLoopTrim: vi.fn(async () => ({ strip: 'walk/trims/t-v001-strip.png', loop: 'walk/trims/t-v001.gif', manifest: 'walk/trims/t-v001.json', frameCount: 3, disabledFrameCount: 1 })),+}));+import * as records from '../services/sprites/records.js';import * as importer from '../services/sprites/importer.js';import * as reference from '../services/sprites/reference.js';+import * as walk from '../services/sprites/walk.js';+import * as walkTrims from '../services/sprites/walkTrims.js';import { errorMiddleware } from '../lib/errorHandler.js';import spriteRoutes from './sprites.js';@@ -216,4 +229,72 @@ describe('sprites routes', () => {expect(r.status).toBe(200);expect(records.deleteRecord).toHaveBeenCalledWith('pioneer');});++ it('GET /:id includes the walk state for characters only', async () => {+ records.getRecordWithAssets.mockResolvedValueOnce({+ record: { id: 'pioneer', kind: 'character' }, assets: [],+ });+ const r = await request(app).get('/api/sprites/pioneer');+ expect(r.body.walk).toEqual({ runs: [], selection: null, walkSet: null });+ expect(walk.getWalkState).toHaveBeenCalledWith('pioneer');++ records.getRecordWithAssets.mockResolvedValueOnce({+ record: { id: 'crates', kind: 'props' }, assets: [],+ });+ const props = await request(app).get('/api/sprites/crates');+ expect(props.body.walk).toBeNull();+ });++ it('POST /:id/walk/generate validates direction and duration', async () => {+ const r = await request(app).post('/api/sprites/pioneer/walk/generate')+ .send({ direction: 'east', duration: 10 });+ expect(r.status).toBe(200);+ expect(walk.startWalkGeneration).toHaveBeenCalledWith('pioneer', { direction: 'east', duration: 10 });++ expect((await request(app).post('/api/sprites/pioneer/walk/generate')+ .send({ direction: 'up' })).status).toBe(400);+ expect((await request(app).post('/api/sprites/pioneer/walk/generate')+ .send({ direction: 'east', duration: 7 })).status).toBe(400);+ // south is animatable (its anchor is the frozen main).+ expect((await request(app).post('/api/sprites/pioneer/walk/generate')+ .send({ direction: 'south' })).status).toBe(200);+ });++ it('POST /:id/walk/approve validates the run id shape', async () => {+ const r = await request(app).post('/api/sprites/pioneer/walk/approve')+ .send({ direction: 'east', runId: 'walk-east-0a1b2c3d' });+ expect(r.status).toBe(200);+ expect(walk.approveWalkDirection).toHaveBeenCalledWith('pioneer', { direction: 'east', runId: 'walk-east-0a1b2c3d' });++ expect((await request(app).post('/api/sprites/pioneer/walk/approve')+ .send({ direction: 'east', runId: '../escape' })).status).toBe(400);+ expect(walk.approveWalkDirection).toHaveBeenCalledOnce();+ });++ it('POST /:id/walk/postprocess delegates the rerun', async () => {+ const r = await request(app).post('/api/sprites/pioneer/walk/postprocess')+ .send({ runId: 'walk-east-0a1b2c3d' });+ expect(r.status).toBe(200);+ expect(walk.rerunWalkPostprocess).toHaveBeenCalledWith('pioneer', { runId: 'walk-east-0a1b2c3d' });+ });++ it('POST /:id/walk/trim validates and 201s', async () => {+ const payload = {+ slug: 'east-loop',+ atlasPath: 'grok/walk-east-0a1b2c3d/generated/strip.png',+ row: 0, cellWidth: 384, cellHeight: 384, fps: 12,+ allColumns: [0, 1, 2, 3], enabledColumns: [0, 2],+ };+ const r = await request(app).post('/api/sprites/pioneer/walk/trim').send(payload);+ expect(r.status).toBe(201);+ expect(walkTrims.saveLoopTrim).toHaveBeenCalledWith('pioneer', payload);++ expect((await request(app).post('/api/sprites/pioneer/walk/trim')+ .send({ ...payload, slug: 'Bad Slug!' })).status).toBe(400);+ expect((await request(app).post('/api/sprites/pioneer/walk/trim')+ .send({ ...payload, enabledColumns: [0] })).status).toBe(400);+ expect((await request(app).post('/api/sprites/pioneer/walk/trim')+ .send({ ...payload, allColumns: [0, 0, 1, 2] })).status).toBe(400);+ expect(walkTrims.saveLoopTrim).toHaveBeenCalledOnce();+ });});diff --git a/server/services/spriteWalkVideoHook.js b/server/services/spriteWalkVideoHook.jsnew file mode 100644index 0000000000..5ac5b8a559--- /dev/null+++ b/server/services/spriteWalkVideoHook.js@@ -0,0 +1,45 @@+/**+ * Sprite walk-video attach hook (issue #2897, phase 3).+ *+ * Subscribes to mediaJobEvents and, for each completed VIDEO job carrying+ * `params.spriteWalk`, copies the finished grok clip into that run's+ * `grok/<runId>/generated/source-video.mp4` and runs the deterministic+ * postprocess (frame harvest → un-key → cycle select → align → despill →+ * strip/manifest) server-side — a slow cloud render still packages after the+ * user navigated away. Runs accumulate as reviewable candidates (no+ * newest-wins guard); per-record serialization lives in walk.js's write tail.+ */++import { createMediaJobImageHook } from './mediaJobImageHook.js';+import { attachWalkVideo } from './sprites/walk.js';++const hook = createMediaJobImageHook({+ label: 'sprite walk-video',+ initLog: '🚶 Sprite walk-video hook initialized',+ kind: 'video',+ tagKey: 'spriteWalk',+ // Grok video filenames are always `<jobId>.mp4`; the completed payload+ // echoes it, with the job id as fallback (same contract as the+ // music-video scene hook).+ extractResult: (job) => {+ const filename = (typeof job.result?.filename === 'string' && job.result.filename)+ || (typeof job.id === 'string' ? `${job.id}.mp4` : null);+ return filename ? { filename } : null;+ },+ identify: (tag, job) => (tag?.recordId && tag.direction && tag.runId+ ? { ...tag, jobId: job?.id || null }+ : null),+ serializeKey: ({ recordId }) => recordId,+ describe: ({ recordId, runId }) => `${recordId}/${runId}`,+ attach: attachWalkVideo,+ onAttached: ({ recordId, runId }, result) => {+ console.log(`🚶 sprite walk run ${recordId}/${runId} → ${result?.status || 'attached'}`);+ },+});++export function initSpriteWalkVideoHook() {+ hook.init();+}++// Test-only reset so suites that re-init can do so cleanly.+export const __testing = hook.__testing;diff --git a/server/services/sprites/reference.js b/server/services/sprites/reference.jsindex 749aa4c8dc..351b9b37b4 100644--- a/server/services/sprites/reference.js+++ b/server/services/sprites/reference.js@@ -64,7 +64,7 @@ function rebaseLegacyPath(p, recordId) {return typeof p === 'string' && p.startsWith(marker) ? p.slice(marker.length) : p;}-async function loadManifest(recordId) {+export async function loadManifest(recordId) {const manifest = await readJSONFile(join(spriteDir(recordId), manifestRelPath(recordId)), null);if (!manifest) return null;if (manifest.mainReference) {@@ -105,7 +105,7 @@ function seedManifest(recordId) {};}-async function requireCharacter(recordId) {+export async function requireCharacter(recordId) {const record = await getRecord(recordId);if (!record) throw new ServerError('Sprite record not found', { status: 404, code: 'NOT_FOUND' });if (record.kind !== 'character') {diff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.jsnew file mode 100644index 0000000000..3e6233c042--- /dev/null+++ b/server/services/sprites/walk.js@@ -0,0 +1,380 @@+/**+ * Sprites — walk-animation workflow orchestration (issue #2897, phase 3).+ *+ * Per-direction lifecycle on top of the locked reference set (#2896):+ * generate ONE grok image_to_video walk clip per direction (user-triggered,+ * cloud lane), then the completion hook runs the fully deterministic Node+ * postprocess (walkPostprocess.js) into a candidate run. The user reviews,+ * optionally loop-trims, and approves per direction; when all 8 directions+ * are approved the finalized walk-set manifest freezes the set.+ *+ * Disk layout mirrors the source pipeline (and phase 1's importer contract):+ * grok/walk-<direction>-<runId8>/animation-run.json + generated/…+ * walk/<id>-walk-selection-v1.json, walk/<id>-walk-set-v1.json+ * walk/trims/<slug>-vNNN-{strip.png,.gif,.json}+ *+ * Immutability: a finalized walk set 409s generation/approval/postprocess —+ * revisions require a new character version, matching the reference contract.+ */++import { join } from 'path';+import { copyFile, readdir } from 'fs/promises';+import { randomUUID } from 'crypto';+import {+ PATHS, ensureDir, atomicWrite, readJSONFile, pathExists, sha256File,+} from '../../lib/fileUtils.js';+import { ServerError } from '../../lib/errorHandler.js';+import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';+import { enqueueJob } from '../mediaJobQueue/index.js';+import { IMAGE_GEN_MODE } from '../imageGen/modes.js';+import { getSettings } from '../settings.js';+import { updateRecord } from './records.js';+import { spriteDir, resolveSpriteAssetPath } from './paths.js';+import { requireCharacter, loadManifest } from './reference.js';+import { SPRITE_DIRECTIONS, anchorIdForDirection, buildWalkVideoPrompt } from './prompts.js';+import {+ prepareWalkAnchorInput, runWalkPostprocess, WALK_FPS, WALK_CELL_SIZE, WALK_FRAME_COUNT,+} from './walkPostprocess.js';+import { GROK_VIDEO_DURATIONS } from '../videoGen/grok.js';++const selectionRelPath = (id) => `walk/${id}-walk-selection-v1.json`;+const walkSetRelPath = (id) => `walk/${id}-walk-set-v1.json`;+const runRelPath = (runId) => `grok/${runId}`;+const RUN_RECORD_NAME = 'animation-run.json';++// Serialize walk-state read-modify-writes per record (run records, the+// selection file, and the walk set share one lifecycle) — same convention as+// reference.js's manifestWriteTail.+const walkWriteTail = createKeyCachedQueue();++async function loadWalkSet(recordId) {+ return readJSONFile(join(spriteDir(recordId), walkSetRelPath(recordId)), null);+}++async function loadSelection(recordId) {+ return readJSONFile(join(spriteDir(recordId), selectionRelPath(recordId)), null);+}++function seedSelection(recordId) {+ return {+ schemaVersion: 1,+ kind: 'reviewed-directional-walk-selection',+ characterId: recordId,+ status: 'in-progress',+ directions: {},+ };+}++async function loadRunRecord(recordId, runId) {+ return readJSONFile(join(spriteDir(recordId), runRelPath(runId), RUN_RECORD_NAME), null);+}++async function saveRunRecord(recordId, run) {+ const dir = join(spriteDir(recordId), runRelPath(run.id));+ await ensureDir(dir);+ await atomicWrite(join(dir, RUN_RECORD_NAME), run);+}++async function requireUnfinalized(recordId) {+ if (await loadWalkSet(recordId)) {+ throw new ServerError('Walk set is finalized — revisions require a new character version', { status: 409, code: 'WALK_SET_FINAL' });+ }+}++/**+ * Walk-workflow view for the detail endpoint: every animation run (newest+ * first), the per-direction selection, and the finalized set when present.+ */+export async function getWalkState(recordId) {+ const grokDir = join(spriteDir(recordId), 'grok');+ let entries = [];+ try {+ entries = await readdir(grokDir, { withFileTypes: true });+ } catch {+ // no runs yet+ }+ const runs = (await Promise.all(+ entries+ .filter((e) => e.isDirectory() && e.name.startsWith('walk-'))+ .map((e) => loadRunRecord(recordId, e.name)),+ ))+ .filter(Boolean)+ .sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''));+ return {+ runs,+ selection: await loadSelection(recordId),+ walkSet: await loadWalkSet(recordId),+ };+}++/**+ * Queue one grok walk video for a direction whose anchor is locked.+ * User-triggered only (route-invoked); exactly one image_to_video call per+ * run — all derivatives are deterministic local work.+ */+export function startWalkGeneration(recordId, body) {+ return walkWriteTail(recordId, () => startWalkGenerationImpl(recordId, body));+}++async function startWalkGenerationImpl(recordId, body) {+ const record = await requireCharacter(recordId);+ await requireUnfinalized(recordId);+ const direction = body.direction;+ const manifest = await loadManifest(recordId);+ const anchor = manifest?.anchors?.find((a) => a.direction === direction);+ if (!anchor || anchor.status !== 'locked' || !anchor.path) {+ throw new ServerError(`Lock the ${anchorIdForDirection(direction)} anchor before animating it`, { status: 409, code: 'ANCHOR_NOT_LOCKED' });+ }+ const chromaKey = manifest.chromaKey;+ if (!chromaKey) {+ throw new ServerError('Reference set has no frozen chroma key', { status: 409, code: 'MAIN_NOT_LOCKED' });+ }+ const anchorAbs = resolveSpriteAssetPath(recordId, anchor.path);+ if (!await pathExists(anchorAbs)) {+ throw new ServerError('Locked anchor file is missing on disk', { status: 500, code: 'ANCHOR_MISSING' });+ }++ const runId = `walk-${direction}-${randomUUID().slice(0, 8)}`;+ const runRel = runRelPath(runId);+ const runAbs = join(spriteDir(recordId), runRel);+ const generatedAbs = join(runAbs, 'generated');+ await ensureDir(generatedAbs);++ // Transparent i2v motion input derived from the locked anchor without+ // mutating it (measured-key alpha recovery + despill).+ const inputAbs = join(generatedAbs, 'input-anchor-transparent.png');+ const { preparation } = await prepareWalkAnchorInput(anchorAbs, inputAbs, chromaKey);++ const settings = await getSettings();+ const duration = GROK_VIDEO_DURATIONS.includes(Number(body.duration)) ? Number(body.duration) : GROK_VIDEO_DURATIONS[0];+ const prompt = buildWalkVideoPrompt({ name: record.name, direction, chromaKey });++ // Run record BEFORE enqueue: a crash between the two leaves an inert+ // 'queued' run (harmless, regenerable) rather than a completed job the+ // hook can't file.+ const now = new Date().toISOString();+ const run = {+ schemaVersion: 1,+ kind: 'grok-game-animation-frames-run',+ status: 'queued',+ id: runId,+ jobId: null,+ characterId: recordId,+ direction,+ chromaKey,+ anchorPath: anchor.path,+ anchorSha256: anchor.sha256 || await sha256File(anchorAbs),+ animationInputPath: `${runRel}/generated/input-anchor-transparent.png`,+ animationInputSha256: await sha256File(inputAbs),+ animationInputPreparation: preparation,+ createdAt: now,+ };+ await saveRunRecord(recordId, run);++ const { jobId } = enqueueJob({+ kind: 'video',+ params: {+ mode: IMAGE_GEN_MODE.GROK,+ videoMode: 'image',+ grokPath: settings.imageGen?.grok?.grokPath,+ prompt,+ sourceImagePath: inputAbs,+ duration,+ // Destination tag the completion hook files the video by.+ spriteWalk: { recordId, direction, runId, chromaKey },+ },+ owner: 'sprites',+ });+ run.jobId = jobId;+ await saveRunRecord(recordId, run);+ console.log(`🚶 sprite walk video queued ${recordId}/${runId} jobId=${jobId.slice(0, 8)}`);+ return { jobId, runId, direction, duration };+}++/**+ * Completion-hook attach: copy the finished grok video into the run root and+ * run the deterministic postprocess. Errors are captured onto the run record+ * (status 'error') so the UI can surface them — the hook context has no+ * request to bubble to.+ */+export function attachWalkVideo(ctx) {+ return walkWriteTail(ctx.recordId, () => attachWalkVideoImpl(ctx));+}++async function attachWalkVideoImpl({ recordId, direction, runId, filename, jobId }) {+ const run = await loadRunRecord(recordId, runId);+ if (!run) {+ console.error(`❌ sprite walk run record missing for ${recordId}/${runId} — skipping attach`);+ return null;+ }+ const src = join(PATHS.videos, filename);+ if (!await pathExists(src)) return null;+ const runRel = runRelPath(runId);+ const runAbs = join(spriteDir(recordId), runRel);+ const videoAbs = join(runAbs, 'generated', 'source-video.mp4');+ await ensureDir(join(runAbs, 'generated'));+ await copyFile(src, videoAbs);+ run.jobId = run.jobId || jobId || null;+ run.sourceVideoSha256 = await sha256File(videoAbs);+ run.status = 'postprocessing';+ await saveRunRecord(recordId, run);++ try {+ const manifest = await loadManifest(recordId);+ const anchor = manifest?.anchors?.find((a) => a.direction === direction);+ if (!anchor?.path) throw new Error(`No locked ${direction} anchor in the reference manifest`);+ const result = await runWalkPostprocess({+ recordId,+ direction,+ chromaKey: run.chromaKey || manifest.chromaKey,+ runAbs,+ runRel,+ anchorRel: anchor.path,+ anchorAbs: resolveSpriteAssetPath(recordId, anchor.path),+ videoAbs,+ });+ run.status = 'candidate';+ run.completedAt = new Date().toISOString();+ run.postprocessManifest = result.manifestPath;+ run.stripPreview = result.stripPreview;+ delete run.postprocessError;+ } catch (err) {+ // Outside the request lifecycle — capture instead of crashing the hook.+ run.status = 'error';+ run.completedAt = new Date().toISOString();+ run.postprocessError = err.message;+ console.error(`❌ sprite walk postprocess failed ${recordId}/${runId}: ${err.message}`);+ }+ await saveRunRecord(recordId, run);+ return { runId, status: run.status };+}++/**+ * Re-run the deterministic postprocess for a run whose source video already+ * landed (crash recovery, or determinism verification). Approved/finalized+ * runs are immutable.+ */+export function rerunWalkPostprocess(recordId, { runId }) {+ return walkWriteTail(recordId, () => rerunWalkPostprocessImpl(recordId, runId));+}++async function rerunWalkPostprocessImpl(recordId, runId) {+ await requireCharacter(recordId);+ await requireUnfinalized(recordId);+ const run = await loadRunRecord(recordId, runId);+ if (!run) throw new ServerError(`Unknown walk run: ${runId}`, { status: 404, code: 'RUN_NOT_FOUND' });+ const selection = await loadSelection(recordId);+ if (selection?.directions?.[run.direction]?.runId === runId) {+ throw new ServerError('Run is approved — approved runs are immutable', { status: 409, code: 'RUN_APPROVED' });+ }+ const runRel = runRelPath(runId);+ const runAbs = join(spriteDir(recordId), runRel);+ const videoAbs = join(runAbs, 'generated', 'source-video.mp4');+ if (!await pathExists(videoAbs)) {+ throw new ServerError('Run has no source video yet', { status: 409, code: 'VIDEO_NOT_READY' });+ }+ const manifest = await loadManifest(recordId);+ const anchor = manifest?.anchors?.find((a) => a.direction === run.direction);+ if (!anchor?.path) {+ throw new ServerError(`No locked ${run.direction} anchor in the reference manifest`, { status: 409, code: 'ANCHOR_NOT_LOCKED' });+ }+ try {+ const result = await runWalkPostprocess({+ recordId,+ direction: run.direction,+ chromaKey: run.chromaKey || manifest.chromaKey,+ runAbs,+ runRel,+ anchorRel: anchor.path,+ anchorAbs: resolveSpriteAssetPath(recordId, anchor.path),+ videoAbs,+ });+ run.status = 'candidate';+ run.completedAt = new Date().toISOString();+ run.postprocessManifest = result.manifestPath;+ run.stripPreview = result.stripPreview;+ delete run.postprocessError;+ } catch (err) {+ run.status = 'error';+ run.postprocessError = err.message;+ }+ await saveRunRecord(recordId, run);+ if (run.status === 'error') {+ throw new ServerError(`Postprocess failed: ${run.postprocessError}`, { status: 422, code: 'POSTPROCESS_FAILED' });+ }+ return run;+}++/**+ * Approve one direction's candidate run. When all 8 directions are approved+ * the finalized walk-set manifest is written and the record advances to+ * walk-complete — after which the set is immutable.+ */+export function approveWalkDirection(recordId, args) {+ return walkWriteTail(recordId, () => approveWalkDirectionImpl(recordId, args));+}++async function approveWalkDirectionImpl(recordId, { direction, runId }) {+ await requireCharacter(recordId);+ await requireUnfinalized(recordId);+ const run = await loadRunRecord(recordId, runId);+ if (!run) throw new ServerError(`Unknown walk run: ${runId}`, { status: 404, code: 'RUN_NOT_FOUND' });+ if (run.direction !== direction) {+ throw new ServerError(`Run ${runId} animates "${run.direction}", not "${direction}"`, { status: 400, code: 'RUN_DIRECTION_MISMATCH' });+ }+ if (run.status !== 'candidate' || !run.postprocessManifest) {+ throw new ServerError('Run has no packaged candidate to approve', { status: 409, code: 'RUN_NOT_CANDIDATE' });+ }+ // Tamper check: the packaged manifest and strip must still be on disk with+ // the packaged geometry before their approval is frozen into the selection.+ const manifestAbs = resolveSpriteAssetPath(recordId, run.postprocessManifest);+ const packaged = await readJSONFile(manifestAbs, null);+ if (!packaged || packaged.frameCount !== WALK_FRAME_COUNT || packaged.frameRate !== WALK_FPS+ || packaged.direction !== direction || packaged.characterId !== recordId) {+ throw new ServerError('Packaged run manifest is missing or inconsistent', { status: 409, code: 'RUN_MANIFEST_INVALID' });+ }+ const stripAbs = resolveSpriteAssetPath(recordId, packaged.stripPath);+ if (!await pathExists(stripAbs) || await sha256File(stripAbs) !== packaged.stripSha256) {+ throw new ServerError('Packed strip is missing or was modified after packaging', { status: 409, code: 'RUN_STRIP_INVALID' });+ }++ const selection = (await loadSelection(recordId)) || seedSelection(recordId);+ selection.directions[direction] = {+ status: 'approved',+ runId,+ runPath: runRelPath(runId),+ runManifest: run.postprocessManifest,+ runManifestSha256: await sha256File(manifestAbs),+ approvedAt: new Date().toISOString(),+ };+ const allApproved = SPRITE_DIRECTIONS.every((d) => selection.directions[d]?.status === 'approved');+ selection.status = allApproved ? 'complete' : 'in-progress';+ const selectionAbs = join(spriteDir(recordId), selectionRelPath(recordId));+ await ensureDir(join(spriteDir(recordId), 'walk'));+ await atomicWrite(selectionAbs, selection);++ if (allApproved) {+ const walkSet = {+ schemaVersion: 1,+ kind: 'finalized-eight-direction-walk-set',+ characterId: recordId,+ status: 'final',+ directionOrder: SPRITE_DIRECTIONS,+ selectionPath: selectionRelPath(recordId),+ selectionSha256: await sha256File(selectionAbs),+ directions: selection.directions,+ finalizedAt: new Date().toISOString(),+ };+ await atomicWrite(join(spriteDir(recordId), walkSetRelPath(recordId)), walkSet);+ // Walk-set before record: the walk-set file is the canonical "finalized"+ // signal (requireUnfinalized and the UI key off it), so a crash between+ // the two leaves only a cosmetic stale record status — the reverse order+ // would advertise walk-complete with no frozen set behind it.+ await updateRecord(recordId, { status: 'walk-complete' });+ console.log(`🏁 sprite walk set finalized for ${recordId}`);+ }+ console.log(`✅ sprite walk ${recordId}/${direction} approved from ${runId}`);+ return getWalkState(recordId);+}++export { WALK_CELL_SIZE, WALK_FPS, WALK_FRAME_COUNT };diff --git a/server/services/sprites/walk.test.js b/server/services/sprites/walk.test.jsnew file mode 100644index 0000000000..2fb7cdf986--- /dev/null+++ b/server/services/sprites/walk.test.js@@ -0,0 +1,346 @@+/**+ * Walk-animation workflow orchestration (#2897): generation gating on locked+ * anchors, run-record lifecycle through the video completion hook, approval+ * with tamper checks, walk-set finalization + immutability, and the loop+ * trimmer. The queue and the deterministic postprocess are mocked — the+ * postprocess itself is covered by walkPostprocess.test.js.+ */++import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';+import { mkdtempSync, rmSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import sharp from 'sharp';+import { mkdir, writeFile, readFile } from 'fs/promises';+import { createHash } from 'crypto';++const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-walk-test-'));++vi.mock('../../lib/fileUtils.js', async (importOriginal) => {+ const actual = await importOriginal();+ Object.assign(actual.PATHS, {+ data: TEST_ROOT,+ sprites: join(TEST_ROOT, 'sprites'),+ images: join(TEST_ROOT, 'images'),+ videos: join(TEST_ROOT, 'videos'),+ });+ return actual;+});++const enqueueJob = vi.fn(() => ({ jobId: 'vid-job-1234567890', position: 0, status: 'queued' }));+vi.mock('../mediaJobQueue/index.js', () => ({+ enqueueJob: (...args) => enqueueJob(...args),+ mediaJobEvents: { on: () => {}, off: () => {} },+}));++vi.mock('../imageGen/index.js', () => ({+ resolveImageCleaners: () => ({ cleanC2PA: false, denoise: false }),+}));++vi.mock('../settings.js', () => ({+ getSettings: async () => ({+ imageGen: { mode: 'grok', grok: { enabled: true, grokPath: '/usr/local/bin/grok' } },+ }),+}));++// Keep the videoGen graph out of this mocked suite — only the duration+// contract is consumed.+vi.mock('../videoGen/grok.js', () => ({ GROK_VIDEO_DURATIONS: [6, 10] }));++const prepareWalkAnchorInput = vi.fn(async (_anchorAbs, destAbs) => {+ await mkdir(join(destAbs, '..'), { recursive: true });+ await writeFile(destAbs, 'stub-transparent-anchor');+ return { preparation: 'measured-key-alpha-recovery-plus-despill' };+});+const runWalkPostprocess = vi.fn(async ({ runRel }) => ({+ manifestPath: `${runRel}/generated/manifest.json`,+ stripPreview: { stripPath: `${runRel}/generated/strip.png`, frameCount: 8, fps: 12, cellWidth: 384, cellHeight: 384, row: 0, startColumn: 0 },+}));+vi.mock('./walkPostprocess.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ prepareWalkAnchorInput: (...args) => prepareWalkAnchorInput(...args),+ runWalkPostprocess: (...args) => runWalkPostprocess(...args),+ };+});++const records = await import('./records.js');+const { lockReference } = await import('./reference.js');+const {+ getWalkState, startWalkGeneration, attachWalkVideo, approveWalkDirection, rerunWalkPostprocess,+} = await import('./walk.js');+const { SPRITE_DIRECTIONS, ANCHOR_DIRECTIONS } = await import('./prompts.js');++let seq = 0;+const newId = () => `walker-${++seq}`;+const sha256 = (buf) => createHash('sha256').update(buf).digest('hex');++async function writeCandidatePng(path) {+ const w = 64; const h = 64;+ 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 = 10; y < 40; y++) for (let x = 20; x < 30; x++) buf.set([23, 107, 101], (y * w + x) * 3);+ await mkdir(join(path, '..'), { recursive: true });+ await sharp(buf, { raw: { width: w, height: h, channels: 3 } }).png().toFile(path);+}++async function placeCandidate(recordId, target, name) {+ const candDir = join(TEST_ROOT, 'sprites', recordId, 'reference', 'candidates');+ await writeCandidatePng(join(candDir, name));+ await writeFile(join(candDir, `${name.replace(/\.png$/, '')}.generation.json`), JSON.stringify({+ schemaVersion: 1, target, chromaKey: '#FF00FF',+ }));+ return `reference/candidates/${name}`;+}++async function characterWithLockedAnchors(id, directions = ['east']) {+ await records.createRecord({ kind: 'character', name: 'Walker' }, id);+ await lockReference(id, { target: 'main', candidate: await placeCandidate(id, 'main', 'walk-south-candidate-01.png') });+ for (const dir of directions.filter((d) => d !== 'south')) {+ await lockReference(id, { target: dir, candidate: await placeCandidate(id, dir, `walk-${dir}-candidate-01.png`) });+ }+ return id;+}++async function makeCandidateRun(recordId, direction, { stripBytes = `strip-${direction}` } = {}) {+ const runId = `walk-${direction}-${(seq++).toString(16).padStart(8, '0')}`;+ const runDir = join(TEST_ROOT, 'sprites', recordId, 'grok', runId, 'generated');+ await mkdir(runDir, { recursive: true });+ const stripName = `${recordId}-walk-${direction}-strip.png`;+ await writeFile(join(runDir, stripName), stripBytes);+ const packaged = {+ schemaVersion: 1,+ kind: 'deterministically-packaged-grok-walk-video',+ characterId: recordId,+ direction,+ frameRate: 12,+ frameCount: 8,+ stripPath: `grok/${runId}/generated/${stripName}`,+ stripSha256: sha256(Buffer.from(stripBytes)),+ };+ const manifestRel = `grok/${runId}/generated/${recordId}-walk-${direction}-manifest.json`;+ await writeFile(join(runDir, `${recordId}-walk-${direction}-manifest.json`), JSON.stringify(packaged));+ await writeFile(join(TEST_ROOT, 'sprites', recordId, 'grok', runId, 'animation-run.json'), JSON.stringify({+ schemaVersion: 1,+ kind: 'grok-game-animation-frames-run',+ status: 'candidate',+ id: runId,+ characterId: recordId,+ direction,+ chromaKey: '#FF00FF',+ createdAt: new Date().toISOString(),+ postprocessManifest: manifestRel,+ }));+ return { runId, manifestRel };+}++beforeEach(() => {+ enqueueJob.mockClear();+ prepareWalkAnchorInput.mockClear();+ runWalkPostprocess.mockClear();+ rmSync(join(TEST_ROOT, 'sprite-records.json'), { force: true });+});+afterAll(() => rmSync(TEST_ROOT, { recursive: true, force: true }));++describe('startWalkGeneration', () => {+ it('409s when the direction anchor is not locked', async () => {+ const id = newId();+ await records.createRecord({ kind: 'character', name: 'Walker' }, id);+ await expect(startWalkGeneration(id, { direction: 'east' }))+ .rejects.toMatchObject({ code: 'ANCHOR_NOT_LOCKED' });+ });++ it('queues a grok i2v job with the spriteWalk tag off a locked anchor', async () => {+ const id = await characterWithLockedAnchors(newId(), ['east']);+ const result = await startWalkGeneration(id, { direction: 'east' });+ expect(result.jobId).toBe('vid-job-1234567890');+ expect(result.runId).toMatch(/^walk-east-[0-9a-f]{8}$/);+ expect(result.duration).toBe(6);++ const call = enqueueJob.mock.calls[0][0];+ expect(call.kind).toBe('video');+ expect(call.owner).toBe('sprites');+ expect(call.params.mode).toBe('grok');+ expect(call.params.videoMode).toBe('image');+ expect(call.params.grokPath).toBe('/usr/local/bin/grok');+ expect(call.params.sourceImagePath).toBe(+ join(TEST_ROOT, 'sprites', id, 'grok', result.runId, 'generated', 'input-anchor-transparent.png'),+ );+ expect(call.params.prompt).toContain('walking east');+ expect(call.params.prompt).toContain('magenta (#FF00FF)');+ expect(call.params.spriteWalk).toEqual({ recordId: id, direction: 'east', runId: result.runId, chromaKey: '#FF00FF' });++ // Transparent input was prepared from the locked anchor, and the run+ // record persisted with the queue job id.+ expect(prepareWalkAnchorInput).toHaveBeenCalledOnce();+ const { runs } = await getWalkState(id);+ expect(runs).toHaveLength(1);+ expect(runs[0]).toMatchObject({+ id: result.runId, status: 'queued', jobId: 'vid-job-1234567890', direction: 'east', chromaKey: '#FF00FF',+ });+ expect(runs[0].animationInputPreparation).toBe('measured-key-alpha-recovery-plus-despill');+ });++ it('animates south straight off the frozen main and honors duration 10', async () => {+ const id = await characterWithLockedAnchors(newId(), []);+ const result = await startWalkGeneration(id, { direction: 'south', duration: 10 });+ expect(result.duration).toBe(10);+ expect(enqueueJob.mock.calls[0][0].params.duration).toBe(10);+ });+});++describe('attachWalkVideo (completion hook)', () => {+ async function queuedRun(id) {+ const { runId } = await startWalkGeneration(id, { direction: 'east' });+ await mkdir(join(TEST_ROOT, 'videos'), { recursive: true });+ await writeFile(join(TEST_ROOT, 'videos', 'vid-job-1234567890.mp4'), 'fake-mp4-bytes');+ return runId;+ }++ it('copies the video into the run and records the packaged candidate', async () => {+ const id = await characterWithLockedAnchors(newId(), ['east']);+ const runId = await queuedRun(id);+ const result = await attachWalkVideo({+ recordId: id, direction: 'east', runId, filename: 'vid-job-1234567890.mp4', jobId: 'vid-job-1234567890',+ });+ expect(result).toEqual({ runId, status: 'candidate' });+ expect(runWalkPostprocess).toHaveBeenCalledOnce();+ const ppArgs = runWalkPostprocess.mock.calls[0][0];+ expect(ppArgs).toMatchObject({ recordId: id, direction: 'east', chromaKey: '#FF00FF', runRel: `grok/${runId}` });+ const video = await readFile(join(TEST_ROOT, 'sprites', id, 'grok', runId, 'generated', 'source-video.mp4'), 'utf8');+ expect(video).toBe('fake-mp4-bytes');+ const { runs } = await getWalkState(id);+ expect(runs[0]).toMatchObject({+ status: 'candidate',+ postprocessManifest: `grok/${runId}/generated/manifest.json`,+ });+ expect(runs[0].stripPreview.frameCount).toBe(8);+ expect(runs[0].sourceVideoSha256).toBe(sha256(Buffer.from('fake-mp4-bytes')));+ });++ it('captures a postprocess failure on the run record instead of throwing', async () => {+ const id = await characterWithLockedAnchors(newId(), ['east']);+ const runId = await queuedRun(id);+ runWalkPostprocess.mockRejectedValueOnce(new Error('no detectable moving walk cycle'));+ const result = await attachWalkVideo({+ recordId: id, direction: 'east', runId, filename: 'vid-job-1234567890.mp4',+ });+ expect(result.status).toBe('error');+ const { runs } = await getWalkState(id);+ expect(runs[0].status).toBe('error');+ expect(runs[0].postprocessError).toMatch(/walk cycle/);+ });++ it('skips silently when the run record or video is missing', async () => {+ const id = await characterWithLockedAnchors(newId(), ['east']);+ expect(await attachWalkVideo({ recordId: id, direction: 'east', runId: 'walk-east-deadbeef', filename: 'x.mp4' })).toBeNull();+ const runId = await queuedRun(id);+ expect(await attachWalkVideo({ recordId: id, direction: 'east', runId, filename: 'not-there.mp4' })).toBeNull();+ });+});++describe('rerunWalkPostprocess', () => {+ it('404s an unknown run and 409s a run with no video', async () => {+ const id = await characterWithLockedAnchors(newId(), ['east']);+ await expect(rerunWalkPostprocess(id, { runId: 'walk-east-deadbeef' }))+ .rejects.toMatchObject({ code: 'RUN_NOT_FOUND' });+ const { runId } = await startWalkGeneration(id, { direction: 'east' });+ await expect(rerunWalkPostprocess(id, { runId }))+ .rejects.toMatchObject({ code: 'VIDEO_NOT_READY' });+ });++ it('re-packages a landed video and 409s an approved run', async () => {+ const id = await characterWithLockedAnchors(newId(), ['east']);+ const { runId } = await startWalkGeneration(id, { direction: 'east' });+ const videoAbs = join(TEST_ROOT, 'sprites', id, 'grok', runId, 'generated', 'source-video.mp4');+ await writeFile(videoAbs, 'landed');+ const run = await rerunWalkPostprocess(id, { runId });+ expect(run.status).toBe('candidate');++ // Approve it (needs a packaged manifest + strip on disk), then rerun 409s.+ const { runId: approvedRun } = await makeCandidateRun(id, 'east');+ await writeFile(join(TEST_ROOT, 'sprites', id, 'grok', approvedRun, 'generated', 'source-video.mp4'), 'landed');+ await approveWalkDirection(id, { direction: 'east', runId: approvedRun });+ await expect(rerunWalkPostprocess(id, { runId: approvedRun }))+ .rejects.toMatchObject({ code: 'RUN_APPROVED' });+ });+});++describe('approveWalkDirection', () => {+ it('validates run existence, direction, and candidate status', async () => {+ const id = await characterWithLockedAnchors(newId(), ['east']);+ await expect(approveWalkDirection(id, { direction: 'east', runId: 'walk-east-deadbeef' }))+ .rejects.toMatchObject({ code: 'RUN_NOT_FOUND' });+ const { runId } = await makeCandidateRun(id, 'east');+ await expect(approveWalkDirection(id, { direction: 'west', runId }))+ .rejects.toMatchObject({ code: 'RUN_DIRECTION_MISMATCH' });+ const { runId: queuedId } = await startWalkGeneration(id, { direction: 'east' });+ await expect(approveWalkDirection(id, { direction: 'east', runId: queuedId }))+ .rejects.toMatchObject({ code: 'RUN_NOT_CANDIDATE' });+ });++ it('rejects a strip modified after packaging', async () => {+ const id = await characterWithLockedAnchors(newId(), ['east']);+ const { runId } = await makeCandidateRun(id, 'east');+ await writeFile(+ join(TEST_ROOT, 'sprites', id, 'grok', runId, 'generated', `${id}-walk-east-strip.png`),+ 'tampered',+ );+ await expect(approveWalkDirection(id, { direction: 'east', runId }))+ .rejects.toMatchObject({ code: 'RUN_STRIP_INVALID' });+ });++ it('records the approval in the selection', async () => {+ const id = await characterWithLockedAnchors(newId(), ['east']);+ const { runId, manifestRel } = await makeCandidateRun(id, 'east');+ const state = await approveWalkDirection(id, { direction: 'east', runId });+ expect(state.selection.kind).toBe('reviewed-directional-walk-selection');+ expect(state.selection.status).toBe('in-progress');+ expect(state.selection.directions.east).toMatchObject({+ status: 'approved', runId, runPath: `grok/${runId}`, runManifest: manifestRel,+ });+ expect(state.selection.directions.east.runManifestSha256).toMatch(/^[0-9a-f]{64}$/);+ expect(state.walkSet).toBeNull();+ });++ it('finalizes the walk set on the 8th approval and freezes the record', async () => {+ const id = await characterWithLockedAnchors(newId(), ANCHOR_DIRECTIONS);+ let state;+ for (const direction of SPRITE_DIRECTIONS) {+ const { runId } = await makeCandidateRun(id, direction);+ state = await approveWalkDirection(id, { direction, runId });+ }+ expect(state.selection.status).toBe('complete');+ expect(state.walkSet).toMatchObject({+ kind: 'finalized-eight-direction-walk-set',+ status: 'final',+ characterId: id,+ directionOrder: SPRITE_DIRECTIONS,+ });+ expect(Object.keys(state.walkSet.directions)).toHaveLength(8);+ expect((await records.getRecord(id)).status).toBe('walk-complete');++ // The finalized set is immutable: no new generation, approval, or rerun.+ await expect(startWalkGeneration(id, { direction: 'east' }))+ .rejects.toMatchObject({ code: 'WALK_SET_FINAL' });+ const eastRun = state.walkSet.directions.east.runId;+ await expect(approveWalkDirection(id, { direction: 'east', runId: eastRun }))+ .rejects.toMatchObject({ code: 'WALK_SET_FINAL' });+ await expect(rerunWalkPostprocess(id, { runId: eastRun }))+ .rejects.toMatchObject({ code: 'WALK_SET_FINAL' });+ });+});++describe('getWalkState', () => {+ it('returns empty state for a fresh character and newest-first runs', async () => {+ const id = await characterWithLockedAnchors(newId(), ['east', 'west']);+ expect(await getWalkState(id)).toEqual({ runs: [], selection: null, walkSet: null });+ await startWalkGeneration(id, { direction: 'east' });+ await new Promise((r) => { setTimeout(r, 5); });+ const second = await startWalkGeneration(id, { direction: 'west' });+ const { runs } = await getWalkState(id);+ expect(runs).toHaveLength(2);+ expect(runs[0].id).toBe(second.runId);+ });+});diff --git a/server/services/sprites/walkTrims.js b/server/services/sprites/walkTrims.jsnew file mode 100644index 0000000000..3634ed05b1--- /dev/null+++ b/server/services/sprites/walkTrims.js@@ -0,0 +1,160 @@+/**+ * Sprites — non-destructive loop trimmer (issue #2897, phase 3).+ *+ * Port of the source pipeline's `loop_trims.save_loop_trim`: crop the+ * enabled cells out of a packed atlas row (never mutating the atlas),+ * re-pack them as a trimmed strip + preview GIF + manifest, versioned+ * `<slug>-vNNN` so every trim is additive evidence. PortOS scopes trims to+ * the record (`walk/trims/`) instead of the source's global debug-captures+ * root, and encodes the GIF with ffmpeg (palettegen/paletteuse with+ * transparency) since PIL's GIF writer has no Node sibling.+ */++import { join } from 'path';+import { mkdtemp, rm } from 'fs/promises';+import { tmpdir } from 'os';+import sharp from 'sharp';+import { ensureDir, atomicWrite, pathExists, sha256File } from '../../lib/fileUtils.js';+import { findFfmpeg, runFfmpegProcess } from '../../lib/ffmpeg.js';+import { ServerError } from '../../lib/errorHandler.js';+import { spriteDir, resolveSpriteAssetPath } from './paths.js';+import { requireCharacter } from './reference.js';++const TRIMS_DIR = 'walk/trims';+const MAX_TRIM_VERSION = 999;++// First free -vNNN triple (strip + gif + json all absent), matching the+// source's next_trim_prefix scan.+async function nextTrimPrefix(trimsAbs, slug) {+ for (let n = 1; n <= MAX_TRIM_VERSION; n++) {+ const prefix = `${slug}-v${String(n).padStart(3, '0')}`;+ const taken = await Promise.all(+ [`${prefix}-strip.png`, `${prefix}.gif`, `${prefix}.json`].map((f) => pathExists(join(trimsAbs, f))),+ );+ if (!taken.some(Boolean)) return prefix;+ }+ throw new ServerError(`No free trim version left for ${slug}`, { status: 409, code: 'TRIM_VERSIONS_EXHAUSTED' });+}++async function encodeTrimGif(frames, fps, destAbs) {+ const ffmpeg = await findFfmpeg();+ if (!ffmpeg) throw new ServerError('ffmpeg not found — install ffmpeg to render trim GIFs', { status: 503, code: 'FFMPEG_MISSING' });+ const scratch = await mkdtemp(join(tmpdir(), 'portos-sprite-trim-'));+ for (let i = 0; i < frames.length; i++) {+ await sharp(frames[i].data, { raw: { width: frames[i].width, height: frames[i].height, channels: 4 } })+ .png()+ .toFile(join(scratch, `frame-${String(i).padStart(3, '0')}.png`));+ }+ const result = await runFfmpegProcess({+ bin: ffmpeg,+ args: [+ '-y', '-framerate', String(fps),+ '-i', join(scratch, 'frame-%03d.png'),+ '-filter_complex', '[0:v]split[a][b];[a]palettegen=reserve_transparent=1[p];[b][p]paletteuse=alpha_threshold=128',+ '-loop', '0',+ destAbs,+ ],+ });+ await rm(scratch, { recursive: true, force: true }).catch(() => {});+ if (!result.ok) throw new ServerError(`GIF encode failed: ${result.reason}`, { status: 500, code: 'GIF_ENCODE_FAILED' });+}++/**+ * Save one loop trim. `payload` is route-validated (spriteWalkTrimSchema):+ * slug, atlasPath (record-relative), row, cellWidth/cellHeight, fps,+ * allColumns, enabledColumns (subset), optional sourceFrameIndices/Labels.+ */+export async function saveLoopTrim(recordId, payload) {+ await requireCharacter(recordId);+ const {+ slug, atlasPath, row, cellWidth, cellHeight, fps, allColumns, enabledColumns,+ } = payload;+ if (!enabledColumns.every((c) => allColumns.includes(c))) {+ throw new ServerError('enabledColumns must be a subset of allColumns', { status: 400, code: 'TRIM_COLUMNS_INVALID' });+ }+ const sourceFrameIndices = payload.sourceFrameIndices ?? enabledColumns;+ if (sourceFrameIndices.length !== enabledColumns.length) {+ throw new ServerError('sourceFrameIndices must match enabledColumns length', { status: 400, code: 'TRIM_COLUMNS_INVALID' });+ }+ const sourceFrameLabels = (payload.sourceFrameLabels ?? sourceFrameIndices.map(String))+ .map((l) => String(l).slice(0, 80));+ if (sourceFrameLabels.length !== enabledColumns.length) {+ throw new ServerError('sourceFrameLabels must match enabledColumns length', { status: 400, code: 'TRIM_COLUMNS_INVALID' });+ }++ const atlasAbs = resolveSpriteAssetPath(recordId, atlasPath);+ if (!await pathExists(atlasAbs)) {+ throw new ServerError(`Atlas not found: ${atlasPath}`, { status: 404, code: 'ATLAS_NOT_FOUND' });+ }+ const { data, info } = await sharp(atlasAbs).ensureAlpha().raw().toBuffer({ resolveWithObject: true });+ const maxColumn = Math.max(...allColumns);+ if ((maxColumn + 1) * cellWidth > info.width || (row + 1) * cellHeight > info.height) {+ throw new ServerError('Requested cells fall outside the atlas', { status: 400, code: 'TRIM_BOUNDS_INVALID' });+ }++ // Crop the enabled cells — straight pixel copies, no resampling.+ const frames = enabledColumns.map((col) => {+ const out = Buffer.alloc(cellWidth * cellHeight * 4);+ for (let y = 0; y < cellHeight; y++) {+ const srcStart = (((row * cellHeight) + y) * info.width + col * cellWidth) * 4;+ data.copy(out, y * cellWidth * 4, srcStart, srcStart + cellWidth * 4);+ }+ return { data: out, width: cellWidth, height: cellHeight };+ });++ const trimsAbs = join(spriteDir(recordId), TRIMS_DIR);+ await ensureDir(trimsAbs);+ const prefix = await nextTrimPrefix(trimsAbs, slug);++ const strip = Buffer.alloc(cellWidth * frames.length * cellHeight * 4);+ frames.forEach((frame, i) => {+ for (let y = 0; y < cellHeight; y++) {+ frame.data.copy(+ strip,+ (y * cellWidth * frames.length + i * cellWidth) * 4,+ y * cellWidth * 4,+ (y + 1) * cellWidth * 4,+ );+ }+ });+ const stripName = `${prefix}-strip.png`;+ const stripAbs = join(trimsAbs, stripName);+ await sharp(strip, { raw: { width: cellWidth * frames.length, height: cellHeight, channels: 4 } })+ .png()+ .toFile(stripAbs);++ const gifName = `${prefix}.gif`;+ await encodeTrimGif(frames, fps, join(trimsAbs, gifName));++ const manifest = {+ schemaVersion: 1,+ kind: 'animation-loop-trim',+ status: 'candidate',+ sourceAtlasPath: atlasPath,+ sourceAtlasSha256: await sha256File(atlasAbs),+ row,+ cellWidth,+ cellHeight,+ fps,+ allAtlasColumns: allColumns,+ enabledAtlasColumns: enabledColumns,+ disabledAtlasColumns: allColumns.filter((c) => !enabledColumns.includes(c)),+ selectedFrames: enabledColumns.map((atlasColumn, outputIndex) => ({+ outputIndex,+ atlasColumn,+ sourceFrameIndex: sourceFrameIndices[outputIndex],+ sourceFrameLabel: sourceFrameLabels[outputIndex],+ })),+ stripPath: `${TRIMS_DIR}/${stripName}`,+ gifPath: `${TRIMS_DIR}/${gifName}`,+ };+ await atomicWrite(join(trimsAbs, `${prefix}.json`), manifest);+ console.log(`✂️ sprite loop trim saved ${recordId}/${prefix} (${frames.length}/${allColumns.length} frames)`);+ return {+ strip: manifest.stripPath,+ loop: manifest.gifPath,+ manifest: `${TRIMS_DIR}/${prefix}.json`,+ frameCount: frames.length,+ disabledFrameCount: manifest.disabledAtlasColumns.length,+ };+}diff --git a/server/services/sprites/walkTrims.test.js b/server/services/sprites/walkTrims.test.jsnew file mode 100644index 0000000000..6b0a3ea0cc--- /dev/null+++ b/server/services/sprites/walkTrims.test.js@@ -0,0 +1,139 @@+/**+ * Loop trimmer (#2897): non-destructive re-pack of enabled atlas cells into+ * versioned strip + GIF + manifest. ffmpeg is mocked (the GIF encode is a+ * spawn); the pixel re-pack is asserted for real via sharp.+ */++import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';+import { mkdtempSync, rmSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import sharp from 'sharp';+import { writeFile, mkdir, readFile } from 'fs/promises';++const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-trim-test-'));++vi.mock('../../lib/fileUtils.js', async (importOriginal) => {+ const actual = await importOriginal();+ Object.assign(actual.PATHS, {+ data: TEST_ROOT,+ sprites: join(TEST_ROOT, 'sprites'),+ });+ return actual;+});++const runFfmpegProcess = vi.fn(async ({ args }) => {+ await writeFile(args[args.length - 1], 'GIF89a-stub');+ return { ok: true };+});+vi.mock('../../lib/ffmpeg.js', () => ({+ findFfmpeg: async () => '/fake/ffmpeg',+ runFfmpegProcess: (...args) => runFfmpegProcess(...args),+}));++const records = await import('./records.js');+const { saveLoopTrim } = await import('./walkTrims.js');++const CELL = 8;+// Four 8×8 cells with distinct solid colors in one row.+const CELL_COLORS = [+ [255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255, 255, 0, 255],+];++let seq = 0;+const newId = () => `trimmer-${++seq}`;++async function characterWithAtlas(id) {+ await records.createRecord({ kind: 'character', name: 'Trimmer' }, id);+ const width = CELL * CELL_COLORS.length;+ const buf = Buffer.alloc(width * CELL * 4);+ for (let y = 0; y < CELL; y++) {+ for (let x = 0; x < width; x++) {+ buf.set(CELL_COLORS[Math.floor(x / CELL)], (y * width + x) * 4);+ }+ }+ const dir = join(TEST_ROOT, 'sprites', id, 'grok', 'walk-east-00000000', 'generated');+ await mkdir(dir, { recursive: true });+ await sharp(buf, { raw: { width, height: CELL, channels: 4 } }).png().toFile(join(dir, 'strip.png'));+ return { id, atlasPath: 'grok/walk-east-00000000/generated/strip.png' };+}++const basePayload = (atlasPath) => ({+ slug: 'east-loop',+ atlasPath,+ row: 0,+ cellWidth: CELL,+ cellHeight: CELL,+ fps: 12,+ allColumns: [0, 1, 2, 3],+ enabledColumns: [0, 2, 3],+});++beforeEach(() => {+ runFfmpegProcess.mockClear();+ rmSync(join(TEST_ROOT, 'sprite-records.json'), { force: true });+});+afterAll(() => rmSync(TEST_ROOT, { recursive: true, force: true }));++describe('saveLoopTrim', () => {+ it('re-packs only the enabled cells, in order, without resampling', async () => {+ const { id, atlasPath } = await characterWithAtlas(newId());+ const result = await saveLoopTrim(id, basePayload(atlasPath));+ expect(result).toMatchObject({+ strip: 'walk/trims/east-loop-v001-strip.png',+ loop: 'walk/trims/east-loop-v001.gif',+ manifest: 'walk/trims/east-loop-v001.json',+ frameCount: 3,+ disabledFrameCount: 1,+ });+ const { data, info } = await sharp(join(TEST_ROOT, 'sprites', id, result.strip))+ .raw().toBuffer({ resolveWithObject: true });+ expect(info.width).toBe(CELL * 3);+ expect(info.height).toBe(CELL);+ const px = (x) => [...data.subarray(x * 4, x * 4 + 4)];+ expect(px(0)).toEqual(CELL_COLORS[0]); // column 0+ expect(px(CELL)).toEqual(CELL_COLORS[2]); // column 2 (1 disabled)+ expect(px(CELL * 2)).toEqual(CELL_COLORS[3]); // column 3++ const manifest = JSON.parse(await readFile(join(TEST_ROOT, 'sprites', id, result.manifest), 'utf8'));+ expect(manifest).toMatchObject({+ kind: 'animation-loop-trim',+ status: 'candidate',+ sourceAtlasPath: atlasPath,+ row: 0,+ fps: 12,+ allAtlasColumns: [0, 1, 2, 3],+ enabledAtlasColumns: [0, 2, 3],+ disabledAtlasColumns: [1],+ });+ expect(manifest.selectedFrames).toEqual([+ { outputIndex: 0, atlasColumn: 0, sourceFrameIndex: 0, sourceFrameLabel: '0' },+ { outputIndex: 1, atlasColumn: 2, sourceFrameIndex: 2, sourceFrameLabel: '2' },+ { outputIndex: 2, atlasColumn: 3, sourceFrameIndex: 3, sourceFrameLabel: '3' },+ ]);+ expect(manifest.sourceAtlasSha256).toMatch(/^[0-9a-f]{64}$/);+ // GIF encoded through the ffmpeg primitive with the requested fps.+ const gifArgs = runFfmpegProcess.mock.calls[0][0].args;+ expect(gifArgs).toContain('-framerate');+ expect(gifArgs[gifArgs.indexOf('-framerate') + 1]).toBe('12');+ });++ it('versions successive trims of the same slug', async () => {+ const { id, atlasPath } = await characterWithAtlas(newId());+ await saveLoopTrim(id, basePayload(atlasPath));+ const second = await saveLoopTrim(id, basePayload(atlasPath));+ expect(second.strip).toBe('walk/trims/east-loop-v002-strip.png');+ });++ it('rejects a non-subset, mismatched labels, and out-of-bounds cells', async () => {+ const { id, atlasPath } = await characterWithAtlas(newId());+ await expect(saveLoopTrim(id, { ...basePayload(atlasPath), enabledColumns: [0, 9] }))+ .rejects.toMatchObject({ code: 'TRIM_COLUMNS_INVALID' });+ await expect(saveLoopTrim(id, { ...basePayload(atlasPath), sourceFrameLabels: ['only-one'] }))+ .rejects.toMatchObject({ code: 'TRIM_COLUMNS_INVALID' });+ await expect(saveLoopTrim(id, { ...basePayload(atlasPath), allColumns: [0, 1, 2, 3, 4], enabledColumns: [0, 4] }))+ .rejects.toMatchObject({ code: 'TRIM_BOUNDS_INVALID' });+ await expect(saveLoopTrim(id, { ...basePayload(atlasPath), atlasPath: 'grok/nope.png' }))+ .rejects.toMatchObject({ code: 'ATLAS_NOT_FOUND' });+ });+});