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-2984]): import a walk run's source clip so imported directions stay re-derivable

[._.]/ Adam Eivy97381c6b0a29
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index aa01a10f10..9ff3c4a6b9 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -24,6 +24,7 @@
## Sprite Manager
+- **[issue-2984] Imported walk cycles now bring their source clip along, so they can be re-derived at a new frame count** — importing a character used to copy the finished walk strips but leave behind the video clip each one was extracted from. Since the packer can only ever resample *down*, that permanently froze every imported direction at the frame count it arrived with: a character imported at 8 frames could never be brought up to 12 to match a direction generated here, and PortOS couldn't compile its atlas at all while the two disagreed. The importer now copies each run's source clip (resolving it whichever folder layout the source tree uses), so imported directions become re-derivable — while the bulky extracted frame folders are still skipped, since they're re-extracted from the clip on demand. A clip whose contents don't match the checksum its manifest declares is refused with a message naming the run rather than silently imported. Characters imported before this upgrade are checked on startup and healed where the clip is already somewhere in their folder; where it isn't, PortOS logs plainly that re-running the import against the original source tree is what brings it across.
- **[issue-2978] Saving a loop trim now works on imported characters** — for a character whose walk cycles came in through the source-pipeline import, the Loop Trimmer would load, scrub, and play the animation perfectly, then fail on **Save trim** with "Packaged run manifest is missing or inconsistent" — after you'd already picked your frames, and with nothing saved. The imported artwork was never damaged; PortOS was simply looking for the packaged manifest under the wrong folder and giving up. Trims now save on imported characters, keep the real gait-phase labels (left-contact, left-passing, …) for each kept frame, and record the correct source strip. A run whose manifest went missing entirely now falls back to the strip's own geometry and still trims, while a manifest that's genuinely corrupt still refuses loudly instead of quietly guessing. The same lookup fixed approving an imported walk direction, which would have failed the same way.
- **Steer a directional-anchor re-roll with a correction note** — when a directional anchor comes out wrong (say the north-east pose grew a pocket on the arm that has none in every other view), re-rolling it with the same inputs tended to just reproduce the same mistake. Each unlocked anchor tile now has a small **Correction (optional)** box: type what to fix ("no pocket on the right sleeve") and hit **Regenerate**, and the note is appended to that pose's prompt as an explicit override so the new render actually diverges. The button reads **Generate** on the first render and **Regenerate** once candidates exist, the correction is per-direction (so eight different fixes don't collide), and it rides into the candidate's saved prompt so the image preview shows exactly what was asked for. Main-reference iteration is unchanged — it already has its own design-prompt box.
- **[issue-2964] The same correction note now steers a re-roll from the asset card too** — the correction box used to live only on the Reference Set's anchor grid, so re-rolling a directional-anchor candidate from its card in the Assets library ignored any fix you'd typed. Each anchor candidate card now carries the same correction affordance: click its note icon to type ("no pocket on the right sleeve") and hit **Regenerate**, and that guidance is appended to the pose's prompt exactly as it is from the grid. The two surfaces share one correction per direction, so a note you type in either place shows up in the other, and both re-rolls send the identical instruction.
diff --git a/scripts/migrations/205-backfill-imported-walk-source-clips.js b/scripts/migrations/205-backfill-imported-walk-source-clips.js
new file mode 100644
index 0000000000..ced5524f9e
--- /dev/null
+++ b/scripts/migrations/205-backfill-imported-walk-source-clips.js
@@ -0,0 +1,132 @@
+/**
+ * Migration 205 — backfill the source clip (`generated/source-video.mp4`) for
+ * walk runs that were IMPORTED before the importer started copying it (#2984).
+ *
+ * Background:
+ * The source-pipeline importer (#2895) deliberately left every run's i2v
+ * clip behind — with the frame count fixed at 8 it was a spent intermediate.
+ * Authorable frame counts (#2970) changed that: the packer only ever
+ * resamples DOWN, so re-deriving a direction at a HIGHER frame count means
+ * re-extracting frames from the clip. An imported run with no clip is
+ * permanently stuck at whatever count it arrived with. The importer now
+ * brings the clip across; runs already on disk need this one-time backfill.
+ *
+ * What it does (per imported run record under data/sprites/<id>/):
+ * Determine where the clip belongs — the run record's `sourceVideoPath`
+ * re-anchored to record-relative, else `<runDir>/generated/source-video.mp4`
+ * — and, when nothing is there, look for it under the run's twin directory
+ * prefix (`runs/` ⇄ `grok/`, the same dual-root tolerance the read layer
+ * applies) INSIDE the record's own directory, copying it into place if found.
+ *
+ * The common outcome is "not found": the clip usually only exists in the
+ * external source tree the record was imported from, which a migration cannot
+ * reach (it must stay inside data/). That is not a bug, and the summary log
+ * says so plainly — re-running the sprite import against that source tree, now
+ * that the importer copies clips, is the actual remedy.
+ *
+ * NOT touched: run records and manifests (never rewritten — they are
+ * hash-pinned and the read layer re-anchors their paths in memory); native
+ * PortOS runs (their clip already sits beside the run); raw frame directories
+ * (~5× the bytes, re-extracted on demand from the clip).
+ *
+ * Idempotency: a run that already has its clip is skipped, so a second pass
+ * copies nothing.
+ */
+
+import { readdir, readFile, copyFile, mkdir, stat } from 'fs/promises';
+import { dirname, join } from 'path';
+
+const RUN_DIRS = ['runs', 'grok'];
+const CLIP_NAME = 'source-video.mp4';
+const RUN_RECORD_NAME = 'animation-run.json';
+
+const exists = (abs) => stat(abs).then(() => true, () => false);
+const readJson = async (abs) => { try { return JSON.parse(await readFile(abs, 'utf8')); } catch { return null; } };
+
+// Mirrors server's toRecordRelativeAssetPath, kept inline so the migration
+// keeps its minimal fs-only dependency surface. Returns null for a value that
+// doesn't resolve inside this record.
+const recordRelative = (id, p) => {
+ if (typeof p !== 'string' || !p) return null;
+ const marker = `art-source/sprites/${id}/`;
+ const idx = p.indexOf(marker);
+ const rel = idx >= 0 ? p.slice(idx + marker.length) : p.replace(/^\/+/, '');
+ if (idx < 0 && /^(art-pipeline|art-source|game)\//.test(rel)) return null;
+ if (!rel || rel.split(/[\\/]/).some((seg) => seg === '..' || seg === '')) return null;
+ return rel;
+};
+
+// The twin of a record-relative run path under the other run-dir prefix.
+const altRunLayoutRel = (rel) => {
+ const match = /^(grok|runs)(\/.+)$/.exec(rel);
+ return match ? `${match[1] === 'grok' ? 'runs' : 'grok'}${match[2]}` : null;
+};
+
+/**
+ * Backfill one run. Returns 'copied' when the clip was placed, 'present' when
+ * it already was, 'missing' when it is not reachable inside the record, or
+ * 'skip' for a directory that holds no run record at all (so a leftover twin
+ * directory can't inflate the "needs a re-import" count).
+ */
+async function backfillRun(recDir, recordId, runDirRel) {
+ const record = await readJson(join(recDir, runDirRel, RUN_RECORD_NAME));
+ if (!record) return 'skip';
+ // Where the clip belongs: what the record declares (re-anchored), else the
+ // conventional spot inside the run directory.
+ const destRel = recordRelative(recordId, record.sourceVideoPath) || `${runDirRel}/generated/${CLIP_NAME}`;
+ if (await exists(join(recDir, destRel))) return 'present';
+
+ const candidates = [`${runDirRel}/generated/${CLIP_NAME}`, altRunLayoutRel(destRel), altRunLayoutRel(`${runDirRel}/generated/${CLIP_NAME}`)]
+ .filter((rel) => rel && rel !== destRel);
+ for (const rel of candidates) {
+ // eslint-disable-next-line no-await-in-loop -- ordered probe, stops at the first hit
+ if (!await exists(join(recDir, rel))) continue;
+ // eslint-disable-next-line no-await-in-loop
+ await mkdir(dirname(join(recDir, destRel)), { recursive: true });
+ // eslint-disable-next-line no-await-in-loop
+ await copyFile(join(recDir, rel), join(recDir, destRel));
+ return 'copied';
+ }
+ return 'missing';
+}
+
+async function migrateRecord(recDir, recordId) {
+ const tally = { copied: 0, missing: 0 };
+ for (const base of RUN_DIRS) {
+ const entries = await readdir(join(recDir, base), { withFileTypes: true }).catch(() => []);
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue;
+ // eslint-disable-next-line no-await-in-loop -- per-run sequential is fine (≤8 runs/record)
+ const outcome = await backfillRun(recDir, recordId, `${base}/${entry.name}`);
+ if (outcome === 'copied' || outcome === 'missing') tally[outcome] += 1;
+ }
+ }
+ return tally;
+}
+
+export default {
+ up: async ({ rootDir }) => {
+ const spritesDir = join(rootDir, 'data', 'sprites');
+ let records;
+ try {
+ records = await readdir(spritesDir, { withFileTypes: true });
+ } catch {
+ return { ok: true, migrated: 0 }; // no sprites tree on this install
+ }
+
+ let copied = 0;
+ let missing = 0;
+ for (const rec of records) {
+ if (!rec.isDirectory()) continue;
+ // eslint-disable-next-line no-await-in-loop -- sequential per record, small N
+ const tally = await migrateRecord(join(spritesDir, rec.name), rec.name);
+ if (tally.copied > 0) console.log(`🧭 migration 205: backfilled ${tally.copied} source clip(s) for sprite ${rec.name}`);
+ copied += tally.copied;
+ missing += tally.missing;
+ }
+ if (missing > 0) {
+ console.log(`🎞️ migration 205: ${missing} walk run(s) still have no source clip on disk — their clips only exist in the source tree they were imported from. Re-run the sprite import against that tree to bring them across (the importer now copies clips); until then those directions cannot be re-derived at a new frame count.`);
+ }
+ return { ok: true, migrated: copied };
+ },
+};
diff --git a/scripts/migrations/205-backfill-imported-walk-source-clips.test.js b/scripts/migrations/205-backfill-imported-walk-source-clips.test.js
new file mode 100644
index 0000000000..684494cd92
--- /dev/null
+++ b/scripts/migrations/205-backfill-imported-walk-source-clips.test.js
@@ -0,0 +1,94 @@
+/**
+ * Migration 205 — backfill the source clip for walk runs imported before the
+ * importer copied it (#2984). Builds a sprite record holding three runs in the
+ * three states the migration must distinguish — clip reachable only under the
+ * twin run-dir layout, clip already in place, clip nowhere inside the record —
+ * and asserts it copies exactly the first, leaves the second untouched, and
+ * treats the third as a silent skip rather than a failure.
+ */
+
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync } from 'fs';
+import { mkdir, writeFile, readFile, stat } from 'fs/promises';
+import { tmpdir } from 'os';
+import { dirname, join } from 'path';
+import migration from './205-backfill-imported-walk-source-clips.js';
+
+let ROOT;
+const sprites = () => join(ROOT, 'data', 'sprites');
+const exists = (abs) => stat(abs).then(() => true, () => false);
+
+const ID = 'example-walker';
+const CLIP_BYTES = 'CLIP-BYTES';
+
+// One run record in the shape the importer leaves behind: no `id`, every
+// embedded path anchored at the SOURCE repo root.
+async function writeRun(base, runId, { sourceVideoPath, clipAt } = {}) {
+ const runDir = join(sprites(), ID, base, runId);
+ await mkdir(join(runDir, 'generated'), { recursive: true });
+ await writeFile(join(runDir, 'animation-run.json'), JSON.stringify({
+ kind: 'grok-walk-animation-run',
+ status: 'approved',
+ characterId: ID,
+ direction: 'south',
+ ...(sourceVideoPath ? { sourceVideoPath } : {}),
+ }));
+ if (clipAt) {
+ const clipAbs = join(sprites(), ID, clipAt);
+ await mkdir(dirname(clipAbs), { recursive: true });
+ await writeFile(clipAbs, CLIP_BYTES);
+ }
+}
+
+beforeEach(async () => {
+ ROOT = mkdtempSync(join(tmpdir(), 'migration-205-'));
+ await mkdir(sprites(), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(ROOT, { recursive: true, force: true });
+});
+
+describe('migration 205 — backfill imported walk source clips', () => {
+ it('copies a clip reachable under the twin run layout, skips one already present, and leaves an unreachable run alone', async () => {
+ // Run A: record + manifest under runs/, clip only under the grok/ twin.
+ await writeRun('runs', 'walk-south-aaaa1111', {
+ sourceVideoPath: `art-source/sprites/${ID}/runs/walk-south-aaaa1111/generated/source-video.mp4`,
+ clipAt: 'grok/walk-south-aaaa1111/generated/source-video.mp4',
+ });
+ // Run B: clip already sitting where it belongs.
+ await writeRun('runs', 'walk-east-bbbb2222', {
+ clipAt: 'runs/walk-east-bbbb2222/generated/source-video.mp4',
+ });
+ // Run C: no clip anywhere inside the record — a re-import is the remedy.
+ await writeRun('runs', 'walk-west-cccc3333', {});
+
+ const result = await migration.up({ rootDir: ROOT });
+ expect(result).toEqual({ ok: true, migrated: 1 });
+
+ const clipA = join(sprites(), ID, 'runs/walk-south-aaaa1111/generated/source-video.mp4');
+ expect(await readFile(clipA, 'utf8')).toBe(CLIP_BYTES);
+ // The twin copy is left in place — the migration never moves/removes bytes.
+ expect(await exists(join(sprites(), ID, 'grok/walk-south-aaaa1111/generated/source-video.mp4'))).toBe(true);
+ expect(await readFile(join(sprites(), ID, 'runs/walk-east-bbbb2222/generated/source-video.mp4'), 'utf8')).toBe(CLIP_BYTES);
+ expect(await exists(join(sprites(), ID, 'runs/walk-west-cccc3333/generated/source-video.mp4'))).toBe(false);
+
+ // Run records are never rewritten — they are hash-pinned and the read
+ // layer re-anchors their paths in memory.
+ const record = JSON.parse(await readFile(join(sprites(), ID, 'runs/walk-south-aaaa1111/animation-run.json'), 'utf8'));
+ expect(record.sourceVideoPath).toBe(`art-source/sprites/${ID}/runs/walk-south-aaaa1111/generated/source-video.mp4`);
+ });
+
+ it('is idempotent — a second pass copies nothing', async () => {
+ await writeRun('runs', 'walk-south-aaaa1111', {
+ clipAt: 'grok/walk-south-aaaa1111/generated/source-video.mp4',
+ });
+ expect(await migration.up({ rootDir: ROOT })).toEqual({ ok: true, migrated: 1 });
+ expect(await migration.up({ rootDir: ROOT })).toEqual({ ok: true, migrated: 0 });
+ });
+
+ it('no-ops on an install with no sprites tree', async () => {
+ rmSync(join(ROOT, 'data'), { recursive: true, force: true });
+ expect(await migration.up({ rootDir: ROOT })).toEqual({ ok: true, migrated: 0 });
+ });
+});
diff --git a/server/services/sprites/importer.js b/server/services/sprites/importer.js
index b69769a310..0692750ebc 100644
--- a/server/services/sprites/importer.js
+++ b/server/services/sprites/importer.js
@@ -14,19 +14,23 @@
* art-pipeline/catalog/runtime-selection.json current published-atlas pointer
* game/assets/sprites/<family>/ props atlas families (PNG + README)
*
- * Only approved/final artifacts import: reference candidates, raw video, and
- * extracted frame intermediates stay behind. Where a source manifest carries a
+ * Only approved/final artifacts import: reference candidates and extracted
+ * frame intermediates stay behind. A run's `generated/source-video.mp4` DOES
+ * import (#2984) — with authorable frame counts (#2970) it is the input to
+ * re-deriving a walk cycle, not a spent intermediate.
+ *
+ * Where a source manifest carries a
* sha256 for a file, the copied bytes are verified against it — a mismatch is
* recorded per-item (the import continues) so one corrupt file can't abort a
* whole tree. Runs on demand only (a user action) — never at boot.
*/
import { join, basename, dirname } from 'path';
-import { readdir, copyFile } from 'fs/promises';
+import { readdir, copyFile, rm } from 'fs/promises';
import { PATHS, ensureDir, sha256File, atomicWrite, pathExists, readJSONFile, expandHome } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
import { upsertImportedRecord } from './records.js';
-import { spriteDir } from './paths.js';
+import { spriteDir, RUN_DIR_MATCH } from './paths.js';
import { isValidSpriteId } from './recordsLogic.js';
// The source pipeline keys everything on magenta; imported characters carry it
@@ -95,9 +99,18 @@ async function verifyHashes(destDir, expectations, errors, copiedThisRun) {
const outcomes = await Promise.all(
unique.map(async ({ relPath, sha256 }) => {
if (!copiedThisRun.has(relPath)) return { error: `missing from source: ${relPath}` };
- return (await sha256File(join(destDir, relPath))) === sha256
- ? { verified: true }
- : { error: `sha256 mismatch: ${relPath}` };
+ if ((await sha256File(join(destDir, relPath))) === sha256) return { verified: true };
+ // A still that fails its pin stays on disk with an error recorded — the
+ // record is still browsable and the mismatch is visible. A source CLIP
+ // is different: it is the INPUT to re-deriving a cycle (#2984), so bytes
+ // the manifest disowns would let a later re-derive silently emit frames
+ // nobody approved. Drop it — that run just stays non-re-derivable until
+ // a clean re-import.
+ if (SOURCE_CLIP_REF.test(relPath)) {
+ await rm(join(destDir, relPath), { force: true });
+ return { error: `run ${relPath.split('/')[1]}: source clip failed sha256 verification — not imported` };
+ }
+ return { error: `sha256 mismatch: ${relPath}` };
}),
);
for (const o of outcomes) if (o.error) errors.push(o.error);
@@ -129,8 +142,18 @@ function relToCharacterDir(manifestPath, characterId) {
}
// Asset references worth importing from a run's manifests: images, previews,
-// and packaged manifests — never raw/extracted intermediates or source video.
+// and packaged manifests — never raw/extracted intermediates.
const ASSET_REF = /\.(png|gif|json)$/i;
+// A run's i2v source clip — the ONE video that imports (#2984). Frame counts
+// became authorable in #2970 and the packer only ever resamples DOWN, so
+// without the clip an imported direction is permanently stuck at whatever
+// frame count it arrived with: re-deriving it needs the clip re-extracted.
+// Matched by exact shape rather than a blanket `.mp4` rule so unrelated videos
+// in the source tree still stay behind. `raw/` frames deliberately remain
+// excluded below — ~5× the bytes of the clip they were extracted from, and
+// re-derivation re-extracts them on demand.
+const SOURCE_CLIP_NAME = 'source-video.mp4';
+const SOURCE_CLIP_REF = new RegExp(`${RUN_DIR_MATCH.source}/generated/${SOURCE_CLIP_NAME.replace(/\./g, '\\.')}$`);
const EXCLUDED_RUN_SEGMENTS = /(^|\/)(raw|frames|review)\//;
// Free-text log fields in run records can contain path-looking strings that
// were never assets — don't traverse them.
@@ -138,7 +161,19 @@ const NOISE_KEYS = /tail$|^stdout|^stderr|^log$/i;
function importableRel(value, characterId) {
const rel = relToCharacterDir(value, characterId);
- return rel && ASSET_REF.test(rel) && !EXCLUDED_RUN_SEGMENTS.test(rel) ? rel : null;
+ if (!rel || EXCLUDED_RUN_SEGMENTS.test(rel)) return null;
+ return ASSET_REF.test(rel) || SOURCE_CLIP_REF.test(rel) ? rel : null;
+}
+
+// Source-tree layout drift: a run's files can sit under `grok/<run-id>/` while
+// the manifests naming them say `runs/<run-id>/` (or the reverse) — the two
+// trees are the same run under two prefixes, which is exactly the dual-root
+// tolerance `getWalkState` already applies on read (walk.js RUN_SCAN_DIRS).
+// Returns the twin path under the other run-dir prefix, or null for a path
+// that isn't inside a run dir at all.
+function altRunLayoutRel(rel) {
+ const match = /^(grok|runs)(\/.+)$/.exec(rel);
+ return match ? `${match[1] === 'grok' ? 'runs' : 'grok'}${match[2]}` : null;
}
/**
@@ -173,19 +208,42 @@ function collectManifestRefs(node, characterId, refs, expectations) {
}
}
+// Resolve a declared path against the SOURCE tree, tolerating run-layout
+// drift: returns whichever path actually exists (the declared one, or its twin
+// under the other run-dir prefix), or null when neither does.
+async function resolveSourceRel(srcCharDir, rel) {
+ if (await pathExists(join(srcCharDir, rel))) return rel;
+ const alt = altRunLayoutRel(rel);
+ return alt && (await pathExists(join(srcCharDir, alt))) ? alt : null;
+}
+
+// Read a character-dir JSON through the same drift tolerance, so a manifest
+// naming `runs/<run-id>/…` still expands when the source stores that run under
+// `grok/<run-id>/`. Absent/corrupt → null, like every other manifest read here.
+async function readCharJson(srcCharDir, rel) {
+ const srcRel = await resolveSourceRel(srcCharDir, rel);
+ return srcRel ? readJson(join(srcCharDir, srcRel)) : null;
+}
+
+// Copy one character-dir file, always landing it at the DECLARED path: the
+// manifests that name it are copied byte-for-byte (their hashes are pinned),
+// so readers re-anchor those same declared paths — putting the bytes anywhere
+// else would import a file nothing can find. Only the source lookup tolerates
+// drift.
async function copyCharFile(srcCharDir, destDir, rel) {
- const src = join(srcCharDir, rel);
- if (!(await pathExists(src))) return false;
+ const srcRel = await resolveSourceRel(srcCharDir, rel);
+ if (!srcRel) return false;
const dest = join(destDir, rel);
await ensureDir(dirname(dest));
- await copyFile(src, dest);
+ await copyFile(join(srcCharDir, srcRel), dest);
return true;
}
/**
* Import one APPROVED direction of a finalized walk set: the run manifest
* (hash-verified), then only the assets the run's manifests declare — packed
- * strips, packaged manifests, previews. Works for both grok runs (record at
+ * strips, packaged manifests, previews, and the run's source clip. Works for
+ * both grok runs (record at
* run root, assets under generated/) and imagegen redraw runs (manifest +
* strips at the version root, surrounded by unselected candidates that must
* stay behind).
@@ -205,15 +263,28 @@ async function importApprovedDirection({ srcCharDir, destDir, characterId, direc
if (dir.runManifestSha256) hashExpectations.push({ relPath: manifestRel, sha256: dir.runManifestSha256 });
const refs = new Set();
- collectManifestRefs(await readJson(join(srcCharDir, manifestRel)), characterId, refs, hashExpectations);
+ collectManifestRefs(await readCharJson(srcCharDir, manifestRel), characterId, refs, hashExpectations);
const runRel = relToCharacterDir(dir.runPath, characterId);
- if (runRel && (await pathExists(join(srcCharDir, `${runRel}/generated/review-preview.json`)))) {
+ if (runRel && (await resolveSourceRel(srcCharDir, `${runRel}/generated/review-preview.json`))) {
refs.add(`${runRel}/generated/review-preview.json`);
}
+ // The source clip (#2984). Most packaged manifests name it (so the generic
+ // collector already has it, hash pin included), but an older imported
+ // manifest may not — and a direction with no clip can never be re-derived at
+ // a different frame count. Probe the run dir under both layouts, keeping the
+ // ENTRY's layout as the reference so the clip lands beside the rest of this
+ // run's files.
+ const clipRel = runRel ? `${runRel}/generated/${SOURCE_CLIP_NAME}` : null;
+ // SOURCE_CLIP_REF re-gates the probe so this stays the same narrow rule the
+ // manifest collector applies — an imagegen redraw entry (no run dir) never
+ // acquires a clip through the back door.
+ if (clipRel && SOURCE_CLIP_REF.test(clipRel) && !refs.has(clipRel) && (await resolveSourceRel(srcCharDir, clipRel))) {
+ refs.add(clipRel);
+ }
// One extra expansion level: packaged manifests / previews the run record
// names in turn declare the strip files (and their hash pins).
for (const rel of [...refs]) {
- if (rel.endsWith('.json')) collectManifestRefs(await readJson(join(srcCharDir, rel)), characterId, refs, hashExpectations);
+ if (rel.endsWith('.json')) collectManifestRefs(await readCharJson(srcCharDir, rel), characterId, refs, hashExpectations);
}
refs.delete(manifestRel);
for (const rel of [...refs].sort()) {
diff --git a/server/services/sprites/importer.test.js b/server/services/sprites/importer.test.js
index d2b231a8e7..e251e91fe8 100644
--- a/server/services/sprites/importer.test.js
+++ b/server/services/sprites/importer.test.js
@@ -48,7 +48,10 @@ const southRunRecord = JSON.stringify({
}, null, 2);
const southPackagedManifest = JSON.stringify({
kind: 'deterministically-packaged-grok-walk-video', direction: 'south',
+ // Hash-pinned via the <base>Path/<base>Sha256 sibling convention: the clip
+ // imports (#2984) and its copied bytes must verify against this.
sourceVideoPath: 'art-source/sprites/hero/grok/run-1/generated/source-video.mp4',
+ sourceVideoSha256: sha256('FAKE-VIDEO'),
frames: [{ path: 'art-source/sprites/hero/grok/run-1/generated/frames/f0.png' }],
// Hash-pinned asset record: the copied strip must verify against this.
assets: [{ path: 'art-source/sprites/hero/grok/run-1/generated/south-strip.png', sha256: sha256('FAKE-STRIP') }],
@@ -186,8 +189,8 @@ describe('importFromSource', () => {
const hero = results.find((r) => r.id === 'hero');
expect(hero.kind).toBe('character');
// south anchor + pinned walk selection + south run record + pinned south
- // strip + east manifest + hash-pinned runtime atlas
- expect(hero.verified).toBe(6);
+ // strip + south source clip + east manifest + hash-pinned runtime atlas
+ expect(hero.verified).toBe(7);
expect(hero.errors).toEqual([
'walk set east: referenced asset missing: imagegen/v2/gone.png',
'walk set west: not approved (pending) — skipped',
@@ -207,7 +210,9 @@ describe('importFromSource', () => {
expect(existsSync(join(heroDir, 'grok/run-1/generated/south-manifest.json'))).toBe(true);
expect(existsSync(join(heroDir, 'grok/run-1/generated/south-strip.png'))).toBe(true);
expect(existsSync(join(heroDir, 'grok/run-1/generated/review-preview.json'))).toBe(true);
- expect(existsSync(join(heroDir, 'grok/run-1/generated/source-video.mp4'))).toBe(false);
+ // the source clip imports (#2984 — the input to re-deriving the cycle at a
+ // new frame count); its raw extracted frames still don't
+ expect(existsSync(join(heroDir, 'grok/run-1/generated/source-video.mp4'))).toBe(true);
expect(existsSync(join(heroDir, 'grok/run-1/generated/raw/frame-000.png'))).toBe(false);
expect(existsSync(join(heroDir, 'grok/run-1/generated/frames/f0.png'))).toBe(false);
// approved imagegen run: manifest + selected strip only
@@ -286,6 +291,104 @@ describe('importFromSource', () => {
});
});
+/**
+ * #2984 — the run's source clip is the input to re-deriving a walk cycle at a
+ * different frame count, so it imports. This fixture is the shape that makes
+ * that non-trivial: a walk set whose entries name `runs/<run-id>` beside a
+ * source tree that actually stores one of those runs under `grok/<run-id>`,
+ * plus a run whose clip bytes disagree with the hash its manifest pins, plus a
+ * stale run directory no walk-set entry names.
+ */
+describe('walk-run source clips', () => {
+ const CLIP_BYTES = 'DRIFTER-CLIP';
+ const drifterSouthRun = JSON.stringify({
+ kind: 'grok-walk-animation-run', status: 'candidate', characterId: 'drifter', direction: 'south',
+ postprocessManifest: 'art-source/sprites/drifter/runs/run-a/generated/south-manifest.json',
+ }, null, 2);
+ const drifterEastRun = JSON.stringify({
+ kind: 'grok-walk-animation-run', status: 'candidate', characterId: 'drifter', direction: 'east',
+ postprocessManifest: 'art-source/sprites/drifter/runs/run-b/generated/east-manifest.json',
+ }, null, 2);
+ let drifter;
+
+ beforeAll(async () => {
+ writeTree(SOURCE_ROOT, {
+ 'art-pipeline/characters/drifter.json': {
+ schemaVersion: 1, characterId: 'drifter', displayName: 'Drifter', archetype: 'adult-humanoid-v1',
+ },
+ 'art-source/sprites/drifter/walk/drifter-walk-set-v1.json': {
+ schemaVersion: 1, kind: 'finalized-eight-direction-walk-set', characterId: 'drifter', status: 'final',
+ directions: {
+ // Both entries name the neutral runs/ layout; run-a is only on disk
+ // under grok/ — the layout drift the importer must tolerate.
+ south: {
+ status: 'approved',
+ runPath: 'art-source/sprites/drifter/runs/run-a',
+ runManifest: 'art-source/sprites/drifter/runs/run-a/animation-run.json',
+ runManifestSha256: sha256(drifterSouthRun),
+ },
+ east: {
+ status: 'approved',
+ runPath: 'art-source/sprites/drifter/runs/run-b',
+ runManifest: 'art-source/sprites/drifter/runs/run-b/animation-run.json',
+ runManifestSha256: sha256(drifterEastRun),
+ },
+ },
+ },
+ 'art-source/sprites/drifter/grok/run-a/animation-run.json': drifterSouthRun,
+ 'art-source/sprites/drifter/grok/run-a/generated/south-manifest.json': {
+ kind: 'deterministically-packaged-grok-walk-video', direction: 'south',
+ stripPath: 'art-source/sprites/drifter/runs/run-a/generated/south-strip.png',
+ sourceVideoPath: 'art-source/sprites/drifter/runs/run-a/generated/source-video.mp4',
+ sourceVideoSha256: sha256(CLIP_BYTES),
+ },
+ 'art-source/sprites/drifter/grok/run-a/generated/south-strip.png': 'DRIFTER-STRIP',
+ 'art-source/sprites/drifter/grok/run-a/generated/source-video.mp4': CLIP_BYTES,
+ 'art-source/sprites/drifter/grok/run-a/generated/raw/frame-000.png': 'RAW-INTERMEDIATE',
+ 'art-source/sprites/drifter/runs/run-b/animation-run.json': drifterEastRun,
+ 'art-source/sprites/drifter/runs/run-b/generated/east-manifest.json': {
+ kind: 'deterministically-packaged-grok-walk-video', direction: 'east',
+ sourceVideoPath: 'art-source/sprites/drifter/runs/run-b/generated/source-video.mp4',
+ // Pins bytes the on-disk clip does not have.
+ sourceVideoSha256: sha256('THE-CLIP-THE-MANIFEST-EXPECTS'),
+ },
+ 'art-source/sprites/drifter/runs/run-b/generated/source-video.mp4': 'TAMPERED-CLIP',
+ // Never named by the walk set — must contribute nothing, silently.
+ 'art-source/sprites/drifter/runs/run-stale/animation-run.json': '{"status":"orphan"}',
+ 'art-source/sprites/drifter/runs/run-stale/generated/source-video.mp4': 'ORPHAN-CLIP',
+ });
+ const { results } = await importFromSource({ sourceRoot: SOURCE_ROOT, characters: ['drifter'], includeProps: false });
+ drifter = results.find((r) => r.id === 'drifter');
+ });
+
+ const drifterDir = () => join(SPRITES_ROOT, 'drifter');
+
+ it('imports a run\'s clip whichever run layout the source stores it under, and still leaves raw frames behind', async () => {
+ // Declared as runs/, found under grok/ — landed at the DECLARED path so
+ // the manifest value that names it resolves after import.
+ expect(readFileSync(join(drifterDir(), 'runs/run-a/generated/source-video.mp4'), 'utf8')).toBe(CLIP_BYTES);
+ expect(existsSync(join(drifterDir(), 'runs/run-a/animation-run.json'))).toBe(true);
+ expect(existsSync(join(drifterDir(), 'runs/run-a/generated/south-strip.png'))).toBe(true);
+ expect(existsSync(join(drifterDir(), 'grok'))).toBe(false);
+ // ~5× the clip's bytes and re-extractable on demand — still excluded.
+ expect(existsSync(join(drifterDir(), 'runs/run-a/generated/raw/frame-000.png'))).toBe(false);
+ // south run record + south clip + east run record verify; the east clip doesn't.
+ expect(drifter.verified).toBe(3);
+ });
+
+ it('refuses a clip whose bytes disagree with the manifest\'s sourceVideoSha256, naming the run', () => {
+ expect(drifter.errors).toContain('run run-b: source clip failed sha256 verification — not imported');
+ expect(existsSync(join(drifterDir(), 'runs/run-b/generated/source-video.mp4'))).toBe(false);
+ // The rest of that run still imported — one bad clip isn't a run-wide abort.
+ expect(existsSync(join(drifterDir(), 'runs/run-b/animation-run.json'))).toBe(true);
+ });
+
+ it('skips a source run directory no walk-set entry names, without an error', () => {
+ expect(existsSync(join(drifterDir(), 'runs/run-stale'))).toBe(false);
+ expect(drifter.errors.some((e) => e.includes('run-stale'))).toBe(false);
+ });
+});
+
describe('paths confinement', () => {
it('resolves inside the record dir and lists imported assets', async () => {
const abs = resolveSpriteAssetPath('hero', 'reference/hero-main.png');
diff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.js
index 54c3df3b59..9bc2754c4f 100644
--- a/server/services/sprites/walk.js
+++ b/server/services/sprites/walk.js
@@ -183,24 +183,31 @@ function normalizeStripPreview(recordId, run) {
return { ...run, stripPreview: { ...run.stripPreview, stripPath } };
}
-// Same fixup as normalizeStripPreview, for the OTHER repo-anchored field an
-// imported run record carries: `postprocessManifest` names the packaged
-// manifest as `art-source/sprites/<id>/runs/<run-id>/generated/…json`. Left
-// raw, `resolveSpriteAssetPath` appends it whole to the record dir — producing
-// `data/sprites/<id>/art-source/sprites/<id>/…`, which is still INSIDE the
-// record (so the traversal gate passes) but does not exist. That 409'd every
-// loop-trim save on an imported record (#2978) and would have failed
-// approveRun the same way. Normalizing here — the one choke point every run
-// reader passes through — fixes both consumers at once. In memory only.
+// Same fixup as normalizeStripPreview, for the OTHER repo-anchored path fields
+// an imported run record carries. `postprocessManifest` names the packaged
+// manifest as `art-source/sprites/<id>/runs/<run-id>/generated/…json`, and
+// `sourceVideoPath` names the run's i2v clip the same way. Left raw,
+// `resolveSpriteAssetPath` appends the value whole to the record dir —
+// producing `data/sprites/<id>/art-source/sprites/<id>/…`, which is still
+// INSIDE the record (so the traversal gate passes) but does not exist. That
+// 409'd every loop-trim save on an imported record (#2978), would have failed
+// approveRun the same way, and would leave an imported run's freshly-imported
+// clip (#2984) unfindable — so re-derivation could never see it. Normalizing
+// here — the one choke point every run reader passes through — fixes every
+// consumer at once, and stays a single helper so the two fields can't drift.
+// In memory only, never written back to the hash-pinned record.
// A path toRecordRelativeAssetPath can't re-anchor (it returns null for a
// repo-anchored path belonging to some OTHER record, e.g. pipeline provenance)
// is left untouched rather than blanked, so a genuinely foreign pointer stays
// readable instead of being rewritten into a bogus record-relative one.
-function normalizePostprocessManifest(recordId, run) {
- if (!run?.postprocessManifest) return run;
- const rel = toRecordRelativeAssetPath(recordId, run.postprocessManifest);
- if (!rel || rel === run.postprocessManifest) return run;
- return { ...run, postprocessManifest: rel };
+const REPO_ANCHORED_RUN_FIELDS = ['postprocessManifest', 'sourceVideoPath'];
+
+function normalizeRunAssetPaths(recordId, run) {
+ return REPO_ANCHORED_RUN_FIELDS.reduce((acc, field) => {
+ if (!acc?.[field]) return acc;
+ const rel = toRecordRelativeAssetPath(recordId, acc[field]);
+ return !rel || rel === acc[field] ? acc : { ...acc, [field]: rel };
+ }, run);
}
// A candidate/approved run's stripPreview names a packed strip PNG on disk. If
@@ -244,7 +251,7 @@ async function normalizeMissingStrip(recordId, run) {
// In-memory only, like normalizeStripPreview — never written back to disk.
function normalizeRunRecord(recordId, run, runDirRel) {
const withId = run.id ? run : { ...run, id: runDirRel.split('/')[1] };
- return normalizePostprocessManifest(recordId, normalizeStripPreview(recordId, withId));
+ return normalizeRunAssetPaths(recordId, normalizeStripPreview(recordId, withId));
}
// Strip candidates on an imported redraw manifest, in preference order. The
diff --git a/server/services/sprites/walk.test.js b/server/services/sprites/walk.test.js
index c74089b638..3ff4dcff45 100644
--- a/server/services/sprites/walk.test.js
+++ b/server/services/sprites/walk.test.js
@@ -129,6 +129,9 @@ async function makeCandidateRun(recordId, direction, { stripBytes = `strip-${dir
chromaKey: '#FF00FF',
createdAt: new Date().toISOString(),
postprocessManifest: anchor(manifestRel),
+ // The run's i2v clip — imported alongside the run since #2984, and
+ // anchored the same way every other imported path is.
+ sourceVideoPath: anchor(`runs/${runId}/generated/source-video.mp4`),
// Real candidate records carry the packed-strip preview the UI renders.
// The importer stamps it as `path` (repo-anchored); PortOS uses `stripPath`.
stripPreview: {
@@ -592,6 +595,34 @@ describe('getWalkState', () => {
expect(runs[0].id).toBe(second.runId);
});
+ // #2984: an imported run's `sourceVideoPath` is anchored at the SOURCE repo
+ // root, like every other path the importer copies byte-for-byte. Left raw it
+ // resolves to `data/sprites/<id>/art-source/sprites/<id>/…` — inside the
+ // record (so the traversal gate passes) but non-existent — which would make
+ // the freshly-imported clip unfindable and re-derivation impossible. It is
+ // re-anchored at read time, alongside postprocessManifest, never on disk.
+ it('re-anchors an imported run\'s sourceVideoPath to record-relative at read time', async () => {
+ const id = await characterWithLockedAnchors(newId(), ['east']);
+ const { runId } = await makeCandidateRun(id, 'east', { anchored: true });
+ const runRecordPath = join(TEST_ROOT, 'sprites', id, 'runs', runId, 'animation-run.json');
+ const bytesBefore = await readFile(runRecordPath);
+
+ const { runs } = await getWalkState(id);
+ const run = runs.find((r) => r.id === runId);
+ expect(run.sourceVideoPath).toBe(`runs/${runId}/generated/source-video.mp4`);
+ // In memory only — the hash-pinned record on disk keeps its source anchor.
+ expect(await readFile(runRecordPath)).toEqual(bytesBefore);
+ });
+
+ // A PortOS-native run already stamps the record-relative form, so the
+ // re-anchor is a no-op there — it must not mangle a path it doesn't own.
+ it('leaves a native run\'s already record-relative sourceVideoPath alone', async () => {
+ const id = await characterWithLockedAnchors(newId(), ['east']);
+ const { runId } = await makeCandidateRun(id, 'east');
+ const { runs } = await getWalkState(id);
+ expect(runs.find((r) => r.id === runId).sourceVideoPath).toBe(`runs/${runId}/generated/source-video.mp4`);
+ });
+
// A candidate/approved run whose packed strip PNG has gone missing on disk
// (a botched migration or manual cleanup dropped it — how pioneer's north/west
// strips silently vanished) must NOT surface as a healthy run: the native
diff --git a/server/services/sprites/walkTrims.js b/server/services/sprites/walkTrims.js
index 10672d00d5..5d2812468d 100644
--- a/server/services/sprites/walkTrims.js
+++ b/server/services/sprites/walkTrims.js
@@ -96,7 +96,7 @@ async function resolveTrimSource(recordId, runId) {
if (!run) throw new ServerError(`Unknown walk run: ${runId}`, { status: 404, code: 'RUN_NOT_FOUND' });
// `getWalkState` re-anchors an imported run's `postprocessManifest` for us
- // (walk.js#normalizePostprocessManifest), so this is already record-relative.
+ // (walk.js#normalizeRunAssetPaths), so this is already record-relative.
// Absent vs. malformed are deliberately NOT collapsed (#2978): a manifest file
// that simply isn't there falls through to the stripPreview branch below, which
// carries everything a trim needs; a manifest that EXISTS but is malformed is