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
refactor([issue-2984]): hoist the run-layout twin into paths.js and trim the import path
[._.]/ Adam Eivyc640326c1a2d
diff --git a/scripts/migrations/205-backfill-imported-walk-source-clips.js b/scripts/migrations/205-backfill-imported-walk-source-clips.jsindex ced5524f9e..30f06003e3 100644--- a/scripts/migrations/205-backfill-imported-walk-source-clips.js+++ b/scripts/migrations/205-backfill-imported-walk-source-clips.js@@ -63,20 +63,23 @@ const altRunLayoutRel = (rel) => {};/**- * 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).+ * Backfill one run. Returns 'copied' when the clip was placed, 'missing' when+ * it is not reachable inside the record, or null when there is nothing to do+ * (the clip is already in place, or the directory holds no run record at all —+ * neither should 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';+ if (!record) return null;// 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 conventionalRel = `${runDirRel}/generated/${CLIP_NAME}`;+ const destRel = recordRelative(recordId, record.sourceVideoPath) || conventionalRel;+ if (await exists(join(recDir, destRel))) return null;- const candidates = [`${runDirRel}/generated/${CLIP_NAME}`, altRunLayoutRel(destRel), altRunLayoutRel(`${runDirRel}/generated/${CLIP_NAME}`)]+ // Everywhere the clip could still be sitting inside this record: the+ // conventional spot, and either path's twin under the other run layout.+ const candidates = [...new Set([conventionalRel, altRunLayoutRel(destRel), altRunLayoutRel(conventionalRel)])].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@@ -98,7 +101,7 @@ async function migrateRecord(recDir, recordId) {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;+ if (outcome) tally[outcome] += 1;}}return tally;diff --git a/scripts/migrations/205-backfill-imported-walk-source-clips.test.js b/scripts/migrations/205-backfill-imported-walk-source-clips.test.jsindex 684494cd92..ab9661cd95 100644--- a/scripts/migrations/205-backfill-imported-walk-source-clips.test.js+++ b/scripts/migrations/205-backfill-imported-walk-source-clips.test.js@@ -62,6 +62,13 @@ describe('migration 205 — backfill imported walk source clips', () => {});// Run C: no clip anywhere inside the record — a re-import is the remedy.await writeRun('runs', 'walk-west-cccc3333', {});+ // Run D: stored under the legacy grok/ layout (so the scan must cover both+ // dirs), with the record naming a clip that is already exactly there — the+ // record's declared path wins over the conventional one.+ await writeRun('grok', 'walk-north-dddd4444', {+ sourceVideoPath: `art-source/sprites/${ID}/runs/walk-north-dddd4444/generated/source-video.mp4`,+ clipAt: 'runs/walk-north-dddd4444/generated/source-video.mp4',+ });const result = await migration.up({ rootDir: ROOT });expect(result).toEqual({ ok: true, migrated: 1 });@@ -72,6 +79,9 @@ describe('migration 205 — backfill imported walk source clips', () => {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 D was already satisfied at its DECLARED path — nothing copied into+ // the grok/ directory the run record itself lives in.+ expect(await exists(join(sprites(), ID, 'grok/walk-north-dddd4444/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.diff --git a/server/services/sprites/importer.js b/server/services/sprites/importer.jsindex 0692750ebc..465d2370f9 100644--- a/server/services/sprites/importer.js+++ b/server/services/sprites/importer.js@@ -15,11 +15,8 @@* game/assets/sprites/<family>/ props atlas families (PNG + README)** 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+ * frame intermediates stay behind, while a run's source clip does come across+ * (#2984 — see SOURCE_CLIP_REF). 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.@@ -30,7 +27,7 @@ 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, RUN_DIR_MATCH } from './paths.js';+import { spriteDir, RUN_DIR_MATCH, altRunLayoutPath } from './paths.js';import { isValidSpriteId } from './recordsLogic.js';// The source pipeline keys everything on magenta; imported characters carry it@@ -153,7 +150,7 @@ const ASSET_REF = /\.(png|gif|json)$/i;// 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 SOURCE_CLIP_REF = new RegExp(`${RUN_DIR_MATCH.source}/generated/source-video\\.mp4$`);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.@@ -165,17 +162,6 @@ function importableRel(value, characterId) {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;-}-/*** Recursively collect importable asset paths referenced anywhere in a* manifest's JSON — and, when a manifest hash-pins a referenced file (a@@ -208,21 +194,25 @@ 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.+// Resolve a declared path against the SOURCE tree, tolerating run-layout drift+// (`altRunLayoutPath`): returns whichever path actually exists — the declared+// one or its twin — or null when neither does.async function resolveSourceRel(srcCharDir, rel) {if (await pathExists(join(srcCharDir, rel))) return rel;- const alt = altRunLayoutRel(rel);+ const alt = altRunLayoutPath(rel);return alt && (await pathExists(join(srcCharDir, alt))) ? alt : null;}-// Read a character-dir JSON through the same drift tolerance, so a manifest+// Read a character-dir JSON with 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.+// `grok/<run-id>/`. Read-then-fall-back rather than probe-then-read: readJson+// already collapses a missing/corrupt file to null, so the twin costs a+// syscall only when the declared path really isn't there.async function readCharJson(srcCharDir, rel) {- const srcRel = await resolveSourceRel(srcCharDir, rel);- return srcRel ? readJson(join(srcCharDir, srcRel)) : null;+ const direct = await readJson(join(srcCharDir, rel));+ if (direct) return direct;+ const alt = altRunLayoutPath(rel);+ return alt ? readJson(join(srcCharDir, alt)) : null;}// Copy one character-dir file, always landing it at the DECLARED path: the@@ -263,7 +253,10 @@ async function importApprovedDirection({ srcCharDir, destDir, characterId, direcif (dir.runManifestSha256) hashExpectations.push({ relPath: manifestRel, sha256: dir.runManifestSha256 });const refs = new Set();- collectManifestRefs(await readCharJson(srcCharDir, manifestRel), characterId, refs, hashExpectations);+ // 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);if (runRel && (await resolveSourceRel(srcCharDir, `${runRel}/generated/review-preview.json`))) {refs.add(`${runRel}/generated/review-preview.json`);@@ -271,14 +264,13 @@ async function importApprovedDirection({ srcCharDir, destDir, characterId, direc// 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))) {+ // a different frame count. The RUN_DIR_MATCH gate keeps this to real run+ // entries (an imagegen redraw entry has no run dir and no clip), and the+ // twin check keeps a manifest that named the clip under the OTHER layout+ // from copying the same bytes to two destinations.+ const clipRel = runRel && `${runRel}/generated/${SOURCE_CLIP_NAME}`;+ if (clipRel && RUN_DIR_MATCH.test(runRel) && !refs.has(clipRel) && !refs.has(altRunLayoutPath(clipRel))+ && (await resolveSourceRel(srcCharDir, clipRel))) {refs.add(clipRel);}// One extra expansion level: packaged manifests / previews the run recorddiff --git a/server/services/sprites/paths.js b/server/services/sprites/paths.jsindex e9893315e4..52cf876625 100644--- a/server/services/sprites/paths.js+++ b/server/services/sprites/paths.js@@ -85,7 +85,22 @@ export function resolveSpriteAssetPath(recordId, relPath) {* (#2928) dispatches on it, and the raw-intermediate exclusion below extends* it, so the prefix set is stated exactly once.*/-export const RUN_DIR_MATCH = /^(grok|runs)\/[^/]+/;+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 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 trees+ * drift — a run's files can sit under `grok/<run-id>/` while the manifests+ * naming them say `runs/<run-id>/` — and both spellings denote the same run,+ * which is why `getWalkState` scans both (walk.js `RUN_SCAN_DIRS`). The+ * importer resolves source reads through this so a drifted tree still imports.+ */+export function altRunLayoutPath(rel) {+ const match = RUN_DIR_SPLIT.exec(rel || '');+ return match ? `${RUN_DIR_PREFIXES.find((p) => p !== match[1])}${match[2]}` : null;+}// Raw ffmpeg-extracted frame intermediates inside an animation run (30–96// near-identical PNGs per run, `grok|runs/<run>/generated/raw/`). Kept ondiff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.jsindex 9bc2754c4f..2fee7459c1 100644--- a/server/services/sprites/walk.js+++ b/server/services/sprites/walk.js@@ -192,10 +192,9 @@ function normalizeStripPreview(recordId, run) {// 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.+// clip (#2984) unfindable. Normalizing here — the one choke point every run+// reader passes through — fixes every consumer at once. 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@@ -203,11 +202,12 @@ function normalizeStripPreview(recordId, run) {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);+ let out = run;+ for (const field of REPO_ANCHORED_RUN_FIELDS) {+ const rel = out[field] && toRecordRelativeAssetPath(recordId, out[field]);+ if (rel && rel !== out[field]) out = { ...out, [field]: rel };+ }+ return out;}// A candidate/approved run's stripPreview names a packed strip PNG on disk. If