Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: normalize imported sprite run layouts (#3047)
[._.]/ Adam Eivyc557e151c340
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 710bbeb682..78a99fd86c 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -59,6 +59,8 @@## Sprite Manager+- **[issue-3047] Re-importing a character now keeps its walk cycles intact** — source pipelines may still name animation runs under `grok/`, but PortOS now always stores imported runs under its neutral `runs/` layout and rewrites the copied manifest paths to match. Re-importing to recover a source clip can no longer turn approved walk cards blank; the importer also refreshes the affected run, selection, and walk-set checksums so those records remain internally consistent.+- **[issue-3045] Places and objects can now export a compact ambient loop** — generate and freeze one at-rest main reference, explicitly request one image-to-video loop, review and approve its locally packed 2–6 frames, then compile the result into an atlas whose idle and ambient cells live on row 0 while rows 1–7 remain transparent. The published layout names the single-row `ambient` span and carries `ambientFrameCount`, so a consuming app can sample row 0 at its own timing without assuming a character-facing walk cycle.- **[issue-3018] The scanner action is now a real named animation track, from direct render through publish** — characters can generate a short directional scanner sweep only when you press **Generate** in Sprite Manager; the Grok clip is then deterministically unpacked into a 2–8-frame scanner strip (4 frames at 6fps by default), reviewed and approved per facing into an independent finalized scanner set. Atlas compilation verifies that set's selection, manifests, and frame checksums alongside the unchanged walk evidence, and writes its `scanner-00…` span beside the walk span into the published layout. A walk remains a walk: its routes, bounds, storage, legacy layouts, and distance-driven runtime behavior are unchanged, while consumers can now resolve the scanner by its named span instead of guessing a trailing column.diff --git a/scripts/migrations/203-heal-imported-grok-run-paths.js b/scripts/migrations/203-heal-imported-grok-run-paths.jsindex bd41920fc6..f6607dfd71 100644--- a/scripts/migrations/203-heal-imported-grok-run-paths.js+++ b/scripts/migrations/203-heal-imported-grok-run-paths.js@@ -10,9 +10,9 @@* runs, whose embedded paths are record-relative (`grok/<runId>/…`).** But source-pipeline IMPORTS (#2895) embed their paths anchored at the- * source repo root — `art-source/sprites/<id>/grok/<runId>/…` — and the- * importer copies those manifests byte-for-byte. When 202 ran on an install- * that had already imported such a record, it PHYSICALLY moved the run+ * source repo root — `art-source/sprites/<id>/grok/<runId>/…`. Before the+ * importer learned to normalize this layout on write, 202 ran on installs+ * that had already imported such a record and PHYSICALLY moved the run* directories (`grok/` → `runs/`, gated on the `grok/` dir existing) but its* `startsWith('grok/')` neutralizer never matched the repo-anchored strings,* so every `art-source/sprites/<id>/grok/…` reference was left dangling.@@ -59,6 +59,7 @@import { readdir, readFile, writeFile, rename, stat } from 'fs/promises';import { join } from 'path';import { createHash } from 'crypto';+import { canonicalizeImportedRunPathValue, deepCanonicalizeImportedRunPaths } from '../../server/services/sprites/paths.js';const LEGACY_DIR = 'grok';const NEUTRAL_DIR = 'runs';@@ -74,30 +75,6 @@ const writeJson = async (abs, obj) => {await rename(tmp, abs);};-// Rewrite the leftover run-directory segment in one path VALUE. Two forms:-// - repo-anchored: …/sprites/<id>/grok/… → …/sprites/<id>/runs/…-// - record-relative bare prefix: grok/… → runs/… (belt-and-suspenders;-// 202 already handled this form, but a crash-recovered record could retain-// a stray one).-// Both are path-shaped: they can only appear in a real asset/run path, never in-// the `grok-…` / `…-grok-…` provenance/kind/skill strings the record also holds.-const neutralize = (id, s) => {- if (typeof s !== 'string') return s;- let out = s.split(`sprites/${id}/${LEGACY_DIR}/`).join(`sprites/${id}/${NEUTRAL_DIR}/`);- if (out.startsWith(`${LEGACY_DIR}/`)) out = `${NEUTRAL_DIR}/${out.slice(LEGACY_DIR.length + 1)}`;- return out;-};-const deepNeutralize = (id, v) => {- if (typeof v === 'string') return neutralize(id, v);- if (Array.isArray(v)) return v.map((x) => deepNeutralize(id, x));- if (v && typeof v === 'object') {- const out = {};- for (const k of Object.keys(v)) out[k] = deepNeutralize(id, v[k]);- return out;- }- return v;-};-// Resolve a possibly repo-anchored path VALUE to the record-relative form used// to locate the file on disk (mirrors server's toRecordRelativeAssetPath, kept// inline so the migration keeps its minimal fs+crypto surface). Returns null@@ -131,7 +108,7 @@ async function listJsonFiles(dir) {async function neutralizeJsonFile(id, abs) {const obj = await readJson(abs);if (!obj) return;- const neu = deepNeutralize(id, obj);+ const neu = deepCanonicalizeImportedRunPaths(id, obj);if (JSON.stringify(neu) !== JSON.stringify(obj)) await writeJson(abs, neu);}@@ -145,9 +122,9 @@ async function neutralizeJsonFile(id, abs) {async function neutralizeDirectionEntries(recDir, id, directions) {for (const entry of Object.values(directions || {})) {if (!entry || typeof entry !== 'object') continue;- if (typeof entry.runPath === 'string') entry.runPath = neutralize(id, entry.runPath);+ if (typeof entry.runPath === 'string') entry.runPath = canonicalizeImportedRunPathValue(id, entry.runPath);if (typeof entry.runManifest === 'string') {- entry.runManifest = neutralize(id, entry.runManifest);+ entry.runManifest = canonicalizeImportedRunPathValue(id, entry.runManifest);const rel = recordRelative(id, entry.runManifest);// eslint-disable-next-line no-await-in-loop -- sequential per-direction is fine (≤8 entries)if (rel && await exists(join(recDir, rel))) entry.runManifestSha256 = await sha256File(join(recDir, rel));diff --git a/server/services/sprites/importer.js b/server/services/sprites/importer.jsindex 7da0473623..8031375ff7 100644--- a/server/services/sprites/importer.js+++ b/server/services/sprites/importer.js@@ -28,7 +28,15 @@ import { PATHS, ensureDir, sha256File, atomicWrite, pathExists, readJSONFile, eximport { ServerError } from '../../lib/errorHandler.js';import { upsertImportedRecord } from './records.js';import {- spriteDir, RUN_DIR_MATCH, altRunLayoutPath, resolveDriftTolerantRel, SOURCE_CLIP_NAME,+ spriteDir,+ RUN_DIR_MATCH,+ altRunLayoutPath,+ canonicalizeImportedRunPath,+ canonicalizeImportedRunPathValue,+ deepCanonicalizeImportedRunPaths,+ resolveDriftTolerantRel,+ SOURCE_CLIP_NAME,+ toRecordRelativeAssetPath,} from './paths.js';import { isValidSpriteId } from './recordsLogic.js';@@ -172,7 +180,7 @@ const NOISE_KEYS = /tail$|^stdout|^stderr|^log$/i;function importableRel(value, characterId) {const rel = relToCharacterDir(value, characterId);if (!rel || EXCLUDED_RUN_SEGMENTS.test(rel)) return null;- return ASSET_REF.test(rel) || SOURCE_CLIP_REF.test(rel) ? rel : null;+ return ASSET_REF.test(rel) || SOURCE_CLIP_REF.test(rel) ? canonicalizeImportedRunPath(rel) : null;}/**@@ -219,18 +227,100 @@ async function readCharJson(srcCharDir, rel) {return alt ? readJson(join(srcCharDir, alt)) : 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.+// Copy one character-dir file into PortOS's neutral imported-run layout. The+// source lookup remains drift-tolerant, while every local write maps a legacy+// `grok/` run prefix to `runs/` so a re-import cannot recreate the residue+// migration 203 healed on earlier installs.async function copyCharFile(srcCharDir, destDir, rel) {const srcRel = await resolveDriftTolerantRel(srcCharDir, rel);- if (!srcRel) return false;- const dest = join(destDir, rel);+ if (!srcRel) return null;+ const destRel = canonicalizeImportedRunPath(rel);+ const dest = join(destDir, destRel);await ensureDir(dirname(dest));await copyFile(join(srcCharDir, srcRel), dest);- return true;+ return destRel;+}++// Recursively collect JSON manifests in one imported tree. A missing optional+// subtree is an empty list; the importer only calls this after copying an+// approved direction, so a non-directory is not an error worth surfacing.+async function listJsonFiles(dir) {+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);+ const files = [];+ for (const entry of entries) {+ const abs = join(dir, entry.name);+ if (entry.isDirectory()) files.push(...await listJsonFiles(abs));+ else if (entry.isFile() && entry.name.endsWith('.json')) files.push(abs);+ }+ return files;+}++async function normalizeImportedJsonFile(characterId, abs) {+ const current = await readJson(abs);+ if (current === null) return null;+ const normalized = deepCanonicalizeImportedRunPaths(characterId, current);+ if (JSON.stringify(normalized) !== JSON.stringify(current)) await atomicWrite(abs, normalized);+ return normalized;+}++// A rewritten run record gets new bytes, so the selection and walk-set must+// repin it just as migration 203 does. The path helper accepts both imported+// source provenance and PortOS-relative forms, keeping the write-side layout+// rule in one place.+async function repinDirectionRunManifests(destDir, characterId, directions) {+ for (const entry of Object.values(directions || {})) {+ if (!entry || typeof entry !== 'object') continue;+ if (typeof entry.runPath === 'string') entry.runPath = canonicalizeImportedRunPathValue(characterId, entry.runPath);+ if (typeof entry.runManifest !== 'string') continue;+ entry.runManifest = canonicalizeImportedRunPathValue(characterId, entry.runManifest);+ const rel = toRecordRelativeAssetPath(characterId, entry.runManifest);+ // eslint-disable-next-line no-await-in-loop -- an imported set has at most eight directions.+ if (rel && await pathExists(join(destDir, rel))) {+ // eslint-disable-next-line no-await-in-loop -- each hash reads one small run record.+ entry.runManifestSha256 = await sha256File(join(destDir, rel));+ }+ }+}++async function normalizeImportedDirections({ destDir, characterId, abs, repin = false }) {+ const current = await readJson(abs);+ if (current === null) return null;+ const normalized = deepCanonicalizeImportedRunPaths(characterId, current);+ if (repin && normalized?.directions) await repinDirectionRunManifests(destDir, characterId, normalized.directions);+ if (JSON.stringify(normalized) !== JSON.stringify(current)) await atomicWrite(abs, normalized);+ return normalized;+}++// Imported manifests initially retain source bytes so all source sha256 pins+// can be verified. Normalize only after that verification completes, then+// rebuild the local run-manifest → selection → walk-set checksum cascade.+async function normalizeImportedRunLayout(destDir, characterId) {+ const runsDir = join(destDir, 'runs');+ for (const abs of await listJsonFiles(runsDir)) await normalizeImportedJsonFile(characterId, abs);++ const walkDir = join(destDir, 'walk');+ const selectionAbs = join(walkDir, `${characterId}-walk-selection-v1.json`);+ const walkSetAbs = join(walkDir, `${characterId}-walk-set-v1.json`);+ const selection = await normalizeImportedDirections({ destDir, characterId, abs: selectionAbs, repin: true });+ const selectionSha256 = selection && await pathExists(selectionAbs) ? await sha256File(selectionAbs) : null;+ const walkSet = await normalizeImportedDirections({ destDir, characterId, abs: walkSetAbs, repin: true });+ if (walkSet && selectionSha256 && typeof walkSet.selectionSha256 === 'string') {+ walkSet.selectionSha256 = selectionSha256;+ await atomicWrite(walkSetAbs, walkSet);+ }++ for (const abs of await listJsonFiles(join(destDir, 'runtime'))) await normalizeImportedJsonFile(characterId, abs);+ const walkSetSha256 = walkSet && await pathExists(walkSetAbs) ? await sha256File(walkSetAbs) : null;+ const pointerAbs = join(destDir, 'runtime', 'current.json');+ const pointer = await readJson(pointerAbs);+ if (!pointer) return;+ const normalizedPointer = deepCanonicalizeImportedRunPaths(characterId, pointer);+ if (walkSetSha256 && typeof normalizedPointer.walkSetSha256 === 'string') normalizedPointer.walkSetSha256 = walkSetSha256;+ const manifestRel = toRecordRelativeAssetPath(characterId, normalizedPointer.manifestPath) || normalizedPointer.manifestPath;+ if (typeof manifestRel === 'string' && await pathExists(join(destDir, manifestRel))) {+ normalizedPointer.manifestSha256 = await sha256File(join(destDir, manifestRel));+ }+ if (JSON.stringify(normalizedPointer) !== JSON.stringify(pointer)) await atomicWrite(pointerAbs, normalizedPointer);}/**@@ -243,25 +333,26 @@ async function copyCharFile(srcCharDir, destDir, rel) {* stay behind).*/async function importApprovedDirection({ srcCharDir, destDir, characterId, direction, dir, result, hashExpectations, copiedThisRun }) {- const manifestRel = relToCharacterDir(dir.runManifest, characterId);+ const manifestRel = canonicalizeImportedRunPath(relToCharacterDir(dir.runManifest, characterId));if (!manifestRel) {result.errors.push(`walk set ${direction}: unsafe run path rejected: ${dir.runManifest || dir.runPath}`);return;}- if (!(await copyCharFile(srcCharDir, destDir, manifestRel))) {+ const copiedManifestRel = await copyCharFile(srcCharDir, destDir, manifestRel);+ if (!copiedManifestRel) {result.errors.push(`walk set ${direction}: run manifest missing: ${manifestRel}`);return;}result.files += 1;- copiedThisRun.add(manifestRel);- if (dir.runManifestSha256) hashExpectations.push({ relPath: manifestRel, sha256: dir.runManifestSha256 });+ copiedThisRun.add(copiedManifestRel);+ if (dir.runManifestSha256) hashExpectations.push({ relPath: copiedManifestRel, sha256: dir.runManifestSha256 });const refs = new Set();// Read the copy just made rather than the source: same bytes, one fewer// resolution + read, and it matches how the reference/ and walk/ loops below// expand their manifests.- collectManifestRefs(await readJson(join(destDir, manifestRel)), characterId, refs, hashExpectations);- const runRel = relToCharacterDir(dir.runPath, characterId);+ collectManifestRefs(await readJson(join(destDir, copiedManifestRel)), characterId, refs, hashExpectations);+ const runRel = canonicalizeImportedRunPath(relToCharacterDir(dir.runPath, characterId));if (runRel && (await resolveDriftTolerantRel(srcCharDir, `${runRel}/generated/review-preview.json`))) {refs.add(`${runRel}/generated/review-preview.json`);}@@ -407,6 +498,7 @@ async function importCharacter({ sourceRoot, characterId, spec, specPath, selectconst { verified, dropped } = await verifyHashes(destDir, hashExpectations, result.errors, copiedThisRun);result.verified = verified;result.files -= dropped;+ await normalizeImportedRunLayout(destDir, characterId);const record = await upsertImportedRecord(characterId, {kind: 'character',diff --git a/server/services/sprites/importer.test.js b/server/services/sprites/importer.test.jsindex ef8a906316..d60f597778 100644--- a/server/services/sprites/importer.test.js+++ b/server/services/sprites/importer.test.js@@ -205,23 +205,24 @@ describe('importFromSource', () => {// walk manifests copy as provenanceexpect(existsSync(join(heroDir, 'walk/hero-walk-set-v1.json'))).toBe(true);expect(existsSync(join(heroDir, 'walk/hero-walk-selection-v1.json'))).toBe(true);- // approved grok run: record + manifest-declared assets, never intermediates- expect(existsSync(join(heroDir, 'grok/run-1/animation-run.json'))).toBe(true);- 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);+ // approved source-grok run: record + manifest-declared assets land under+ // PortOS's neutral runs/ layout, never intermediates+ expect(existsSync(join(heroDir, 'runs/run-1/animation-run.json'))).toBe(true);+ expect(existsSync(join(heroDir, 'runs/run-1/generated/south-manifest.json'))).toBe(true);+ expect(existsSync(join(heroDir, 'runs/run-1/generated/south-strip.png'))).toBe(true);+ expect(existsSync(join(heroDir, 'runs/run-1/generated/review-preview.json'))).toBe(true);// 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);+ expect(existsSync(join(heroDir, 'runs/run-1/generated/source-video.mp4'))).toBe(true);+ expect(existsSync(join(heroDir, 'runs/run-1/generated/raw/frame-000.png'))).toBe(false);+ expect(existsSync(join(heroDir, 'runs/run-1/generated/frames/f0.png'))).toBe(false);// approved imagegen run: manifest + selected strip onlyexpect(existsSync(join(heroDir, 'imagegen/v2/east-manifest.json'))).toBe(true);expect(existsSync(join(heroDir, 'imagegen/v2/east-strip.png'))).toBe(true);expect(existsSync(join(heroDir, 'imagegen/v2/east-candidate-02.png'))).toBe(false);// pending direction and non-final manifest contribute nothing- expect(existsSync(join(heroDir, 'grok/run-3/animation-run.json'))).toBe(false);- expect(existsSync(join(heroDir, 'grok/run-decoy'))).toBe(false);+ expect(existsSync(join(heroDir, 'runs/run-3/animation-run.json'))).toBe(false);+ expect(existsSync(join(heroDir, 'runs/run-decoy'))).toBe(false);// published artifacts: immutable archive + keyed source + selection copyexpect(existsSync(join(heroDir, 'runtime/v1/hero-animation-atlas-v1.png'))).toBe(true);expect(existsSync(join(heroDir, 'hero-atlas-keyed.png'))).toBe(true);@@ -260,6 +261,24 @@ describe('importFromSource', () => {expect(record.chromaKey).toBe('#00FF00');});+ it('re-imports source-grok runs into the neutral layout and repins the walk set', async () => {+ await importFromSource({ sourceRoot: SOURCE_ROOT, characters: ['hero'], includeProps: false });+ const heroDir = join(SPRITES_ROOT, 'hero');+ const runRecord = join(heroDir, 'runs/run-1/animation-run.json');+ const selection = JSON.parse(readFileSync(join(heroDir, 'walk/hero-walk-selection-v1.json'), 'utf8'));+ const walkSet = JSON.parse(readFileSync(join(heroDir, 'walk/hero-walk-set-v1.json'), 'utf8'));+ const packaged = JSON.parse(readFileSync(join(heroDir, 'runs/run-1/generated/south-manifest.json'), 'utf8'));++ expect(existsSync(join(heroDir, 'grok/run-1'))).toBe(false);+ expect(selection.directions.south.runPath).toBe('art-source/sprites/hero/runs/run-decoy');+ expect(selection.directions.south.runManifest).toBe('art-source/sprites/hero/runs/run-decoy/animation-run.json');+ expect(walkSet.directions.south.runPath).toBe('art-source/sprites/hero/runs/run-1');+ expect(walkSet.directions.south.runManifest).toBe('art-source/sprites/hero/runs/run-1/animation-run.json');+ expect(walkSet.directions.south.runManifestSha256).toBe(sha256(readFileSync(runRecord)));+ expect(walkSet.selectionSha256).toBe(sha256(readFileSync(join(heroDir, 'walk/hero-walk-selection-v1.json'))));+ expect(packaged.sourceVideoPath).toBe('art-source/sprites/hero/runs/run-1/generated/source-video.mp4');+ });+it('re-import errors when a hash-pinned file disappears from the source (stale dest copy must not vouch)', async () => {rmSync(join(SOURCE_ROOT, 'art-source/sprites/hero/reference/hero-anchor-south.png'));const { results } = await importFromSource({ sourceRoot: SOURCE_ROOT, characters: ['hero'], includeProps: false });@@ -399,11 +418,10 @@ describe('walk-run source clips', () => {it('imports a manifest-declared clip exactly once when the manifest and the walk-set entry disagree on layout', () => {// run-c's manifest declares the clip under grok/ while its entry says- // runs/. The bytes land at the DECLARED (manifest) path — the value the- // read layer re-anchors — and the run-dir probe must not add a second copy- // under the entry's layout.- expect(readFileSync(join(drifterDir(), 'grok/run-c/generated/source-video.mp4'), 'utf8')).toBe(CLIP_BYTES);- expect(existsSync(join(drifterDir(), 'runs/run-c/generated/source-video.mp4'))).toBe(false);+ // runs/. The bytes land once in the local neutral layout rather than+ // recreating the source's grok/ spelling.+ expect(readFileSync(join(drifterDir(), 'runs/run-c/generated/source-video.mp4'), 'utf8')).toBe(CLIP_BYTES);+ expect(existsSync(join(drifterDir(), 'grok/run-c/generated/source-video.mp4'))).toBe(false);});it('refuses a clip whose bytes disagree with the manifest\'s sourceVideoSha256, naming the run', () => {@@ -429,7 +447,7 @@ describe('paths confinement', () => {expect(abs.startsWith(join(SPRITES_ROOT, 'hero'))).toBe(true);const assets = await listSpriteAssets('hero');expect(assets.some((a) => a.path === 'reference/hero-main.png')).toBe(true);- expect(assets.some((a) => a.path === 'grok/run-1/generated/south-strip.png')).toBe(true);+ expect(assets.some((a) => a.path === 'runs/run-1/generated/south-strip.png')).toBe(true);});it('getRecordWithAssets pairs the record with its disk listing', async () => {diff --git a/server/services/sprites/paths.js b/server/services/sprites/paths.jsindex f655fcdd67..1266556130 100644--- a/server/services/sprites/paths.js+++ b/server/services/sprites/paths.js@@ -53,12 +53,10 @@ export const SOURCE_CLIP_NAME = 'source-video.mp4';* Normalize an asset-path field read out of an imported manifest to the* record-relative form `spriteAssetUrl`/`resolveSpriteAssetPath` expect. The* source pipeline embeds paths anchored at ITS repo root- * (`art-source/sprites/<recordId>/...`) inside every manifest, and the- * importer copies those manifests byte-for-byte — their hashes are pinned- * and verified against the source, so importer.js never rewrites the copied- * JSON content. Readers that treat an embedded path as record-relative (the- * convention every PortOS-generated manifest already follows) must strip- * that source-repo prefix at read time instead. Returns null for a path+ * (`art-source/sprites/<recordId>/...`) inside every manifest. Readers that+ * treat an embedded path as record-relative (the convention every+ * PortOS-generated manifest already follows) must strip that source-repo+ * prefix at read time instead. Returns null for a path* that isn't inside this record (repo-anchored provenance, e.g. a pipeline* script path) or for missing/empty/traversal-shaped input. A path with no* repo-anchor segment is assumed already record-relative and passed through@@ -105,6 +103,47 @@ const RUN_DIR_PREFIXES = ['grok', 'runs'];export const RUN_DIR_MATCH = new RegExp(`^(${RUN_DIR_PREFIXES.join('|')})/[^/]+`);const RUN_DIR_SPLIT = new RegExp(`^(${RUN_DIR_PREFIXES.join('|')})(/.+)$`);+/**+ * The neutral run-layout spelling PortOS uses for imported source trees.+ * PortOS-native render jobs may retain their `grok/` location; imports always+ * land under `runs/` so a later source re-import cannot recreate migration+ * 203's legacy path residue.+ */+export const CANONICAL_IMPORTED_RUN_DIR = 'runs';++/** Normalize a record-relative imported run path to its local `runs/` spelling. */+export function canonicalizeImportedRunPath(rel) {+ return typeof rel === 'string' && rel.startsWith('grok/')+ ? `${CANONICAL_IMPORTED_RUN_DIR}/${rel.slice('grok/'.length)}`+ : rel;+}++/**+ * Rewrite one embedded sprite-run path to its local imported spelling.+ *+ * Handles both record-relative `grok/<run-id>/…` values and source-anchored+ * `…/sprites/<id>/grok/<run-id>/…` values, without touching free-text values+ * that merely contain the word "grok".+ */+export function canonicalizeImportedRunPathValue(recordId, value) {+ if (typeof value !== 'string') return value;+ return canonicalizeImportedRunPath(+ value.split(`sprites/${recordId}/grok/`).join(`sprites/${recordId}/${CANONICAL_IMPORTED_RUN_DIR}/`),+ );+}++/** Recursively normalize embedded imported run paths while preserving all other values. */+export function deepCanonicalizeImportedRunPaths(recordId, value) {+ if (typeof value === 'string') return canonicalizeImportedRunPathValue(recordId, value);+ if (Array.isArray(value)) return value.map((entry) => deepCanonicalizeImportedRunPaths(recordId, entry));+ if (value && typeof value === 'object') {+ return Object.fromEntries(+ Object.entries(value).map(([key, entry]) => [key, deepCanonicalizeImportedRunPaths(recordId, entry)]),+ );+ }+ return value;+}+/*** The same run path under the OTHER run-dir prefix (the pair has exactly two* members), or null for a path that isn't inside a run directory. Source treesdiff --git a/server/services/sprites/paths.test.js b/server/services/sprites/paths.test.jsindex f19a7be36f..52dab76740 100644--- a/server/services/sprites/paths.test.js+++ b/server/services/sprites/paths.test.js@@ -7,7 +7,12 @@*/import { describe, it, expect } from 'vitest';-import { toRecordRelativeAssetPath } from './paths.js';+import {+ canonicalizeImportedRunPath,+ canonicalizeImportedRunPathValue,+ deepCanonicalizeImportedRunPaths,+ toRecordRelativeAssetPath,+} from './paths.js';describe('toRecordRelativeAssetPath', () => {it('strips the source-repo marker for this record', () => {@@ -50,3 +55,28 @@ describe('toRecordRelativeAssetPath', () => {expect(toRecordRelativeAssetPath('pioneer', 42)).toBeNull();});});++describe('imported run-layout normalization', () => {+ it('uses runs/ for record-relative imported run destinations', () => {+ expect(canonicalizeImportedRunPath('grok/walk-east-abc/generated/source-video.mp4'))+ .toBe('runs/walk-east-abc/generated/source-video.mp4');+ expect(canonicalizeImportedRunPath('runs/walk-east-abc/generated/source-video.mp4'))+ .toBe('runs/walk-east-abc/generated/source-video.mp4');+ expect(canonicalizeImportedRunPath('imagegen/v19/strip.png')).toBe('imagegen/v19/strip.png');+ });++ it('rewrites only path-shaped values, including nested source-anchored paths', () => {+ const id = 'pioneer';+ expect(canonicalizeImportedRunPathValue(id, `art-source/sprites/${id}/grok/walk-east-abc/animation-run.json`))+ .toBe(`art-source/sprites/${id}/runs/walk-east-abc/animation-run.json`);+ expect(deepCanonicalizeImportedRunPaths(id, {+ runPath: `art-source/sprites/${id}/grok/walk-east-abc`,+ nested: ['grok/walk-south-def/generated/strip.png'],+ kind: 'grok-game-animation-frames-run',+ })).toEqual({+ runPath: `art-source/sprites/${id}/runs/walk-east-abc`,+ nested: ['runs/walk-south-def/generated/strip.png'],+ kind: 'grok-game-animation-frames-run',+ });+ });+});