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: heal grok/ run-path residue that blanked imported sprite walk cycles
[._.]/ Adam Eivyeb377ec69cdd
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex e76aea2ff9..34177ab060 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -106,3 +106,4 @@- **Pick the sprite import source from the managed-apps list instead of typing a path** — the Sprites import panel replaced its free-text "Source root path" input with the shared `AppContextPicker`, loading `GET /api/apps` on open and filtering to non-archived apps that declare a `repoPath`; the selected app's `repoPath` becomes the importer's `sourceRoot`. Sprite pipelines always live in a repo PortOS already manages, so the typed path was a transcription hazard with no upside, and the picker sets up the eventual sync-from-app flow. `AppContextPicker` gains an `emptyRepoText` prop — its hardcoded "using default PortOS context" empty state would be wrong here, since sprite import has no PortOS fallback; the default is unchanged for existing callers.- **Fix two cross-schema breaks in the sprite detail endpoint that were hiding imported walk data** — `GET /api/sprites/:id` 500'd for every imported character because `getWalkState()`'s run-sort called `.localeCompare()` on `createdAt`, which the ElsewhereAcres source pipeline stamps as a Python epoch-seconds number rather than PortOS's own ISO string; the comparator now normalizes both shapes to milliseconds. Separately, each run's `stripPreview` field is now normalized through the existing `toRecordRelativeAssetPath()` helper (`server/services/sprites/paths.js`, mirroring the same rebase-on-read convention `reference.js` already uses for anchor paths): the source pipeline names the field `stripPreview.path` and anchors it at its own repo root, so PortOS's `stripPreview.stripPath`-reading client 404'd on every animated walk-loop thumbnail even once the 500 was fixed. Neither fix rewrites the imported files on disk — normalization happens in memory at read time, so the importer's hash-verified provenance is untouched. New regression coverage in `walk.test.js`. Filed #2924 to cover the one remaining gap: `pioneer`'s `east` direction was approved from an imagegen-redraw pipeline the grok-video-only walk viewer doesn't model, so it shows "approved" but no animated thumbnail.- **Accessibility audit pass: switches, icon-only buttons, focus rings, and the media lightbox** — four hand-rolled toggle switches (CoS Dynamic Avatar, Digital Twin ingestion, scheduled backups, Sharing import mode) were announced as plain unlabeled buttons with no on/off state; they now carry `role="switch"` + `aria-checked` + a name. A dozen icon-only buttons gained accessible names (cron cancel, folder "go up", rapid-reader chunk size, JIRA project clear, writing-sample remove, memory-practice mark correct/incorrect, calendar icon picker) and the process/agent expand carets gained `aria-expanded`. Six inputs that set `focus:outline-none` inside an unstyled wrapper were invisible when focused — their containers now carry `focus-within:border-port-accent`, and four standalone selects/buttons gained a `focus-visible` ring. The Sprites asset preview moved from a click-to-dismiss overlay to the shared `<Modal>` (Esc, focus trap, focus restore), and `MediaLightbox` — which deliberately opts out of `<Modal>` — now supplies its own `role="dialog"`/`aria-modal` and focus trap instead of letting Tab walk out into the page behind it. ~20 unlabeled toolbar controls on the highest-traffic pages (Runner, Review, Wiki, Tribe, Loras, Media History, Media Collections, Prompt Manager) gained labels. A new `client/src/a11yConventions.test.js` guard fails the suite if a new hand-rolled full-screen backdrop or an unlabeled toggle-switch button is introduced; the remaining unlabeled-control backlog is tracked in `PLAN.md`.+- **Heal the `grok/` run-path residue that blanked imported sprite walk cycles (migration 203)** — imported characters whose source pipeline anchored run paths at `art-source/sprites/<id>/grok/…` rendered every walk direction's "approved" badge over an empty cell (observed on `pioneer`: 7 of 8 directions blank, only the imagegen-redraw `east` — which never carried a `grok/` segment — animated). Migration 202 physically relocated those runs `grok/` → `runs/` but its `startsWith('grok/')` neutralizer only matched record-relative paths, so it left every repo-anchored `…/sprites/<id>/grok/…` string pointing at the now-nonexistent directory — the read layer stripped the `art-source/…` prefix to `grok/…`, which no longer resolved, so `getWalkState` couldn't find the run behind each direction and the strip-loop preview URL 404'd. New migration `203-heal-imported-grok-run-paths.js` rewrites the leftover `sprites/<id>/grok/` segment to `runs/` (preserving the `art-source/…` provenance prefix and image-byte shas, exactly as 202 preserved its anchoring) across the selection, walk-set, run records, and postprocess manifests, then recomputes the same `runManifestSha256`/`selectionSha256`/`walkSetSha256` cascade so the healed state is internally consistent. Gated to records 202 already moved (`runs/` present, `grok/` gone) that still carry the residue — a self-consistent `grok/`-layout record is left untouched. Non-path strings that merely contain "grok" (`grok-game-animation-frames-run`, `local-postprocess-of-existing-grok-session-video`) are unaffected.diff --git a/scripts/migrations/203-heal-imported-grok-run-paths.js b/scripts/migrations/203-heal-imported-grok-run-paths.jsnew file mode 100644index 0000000000..bd41920fc6--- /dev/null+++ b/scripts/migrations/203-heal-imported-grok-run-paths.js@@ -0,0 +1,253 @@+/**+ * Migration 203 — heal the `grok/` path residue that migration 202 left behind+ * on IMPORTED sprite records.+ *+ * Background:+ * Migration 202 renamed each character's native run storage from the+ * vendor-named `grok/<runId>/` layout to the neutral `runs/<runId>/` layout+ * and rewrote every embedded `grok/…` path string. Its `neutralize()` only+ * matched path VALUES that START with `grok/` — correct for PortOS-native+ * 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+ * 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.+ *+ * Result on such a record: the run bytes live under `runs/…`, but the+ * selection / walk-set / run-record / postprocess-manifest all still point at+ * `…/grok/…`. The read layer (`toRecordRelativeAssetPath`) strips the+ * `art-source/sprites/<id>/` prefix and yields `grok/…`, which no longer+ * exists — so `getWalkState` can't resolve the run behind each direction and+ * the strip-loop preview URL 404s. Every imported walk direction renders its+ * "approved" badge over an empty (transparent) cell. (Observed: the `pioneer`+ * character — 7 grok-run directions blank, only the imagegen-redraw `east`+ * direction, which never carried a `grok/` segment, animated.)+ *+ * What this migration does (per affected record):+ * Rewrite the leftover `sprites/<id>/grok/` segment → `sprites/<id>/runs/`+ * (preserving the `art-source/…` provenance prefix, exactly as 202 preserved+ * record-relative anchoring — only the vendor dir that 202 relocated is+ * corrected) across the selection, walk-set, every JSON under `runs/`, and+ * the compiled-atlas manifests, then recompute the same content-sha cascade+ * 202 does so the post-migration state is internally consistent.+ *+ * Scope gate (per record): the record has a `runs/` dir, NO `grok/` dir (i.e.+ * 202 already performed the physical move), AND a residual `sprites/<id>/grok/`+ * reference. A record still holding a `grok/` dir is 202's unfinished business+ * — where the dir and the strings agree, the layout is self-consistent and must+ * NOT be touched — so 203 skips it and lets 202 own the move.+ *+ * NOT touched: image-byte shas (a moved PNG is byte-identical — never+ * re-hashed); the `art-source/sprites/<id>/walk/…` selectionPath and other+ * non-`grok/` provenance; strings that merely CONTAIN "grok" but aren't run+ * paths (`grok-game-animation-frames-run`, `grokResponsibility`,+ * `local-postprocess-of-existing-grok-session-video` — none contain the+ * `sprites/<id>/grok/` or leading `grok/` path forms this rewrites).+ *+ * Idempotency: after a successful pass no `sprites/<id>/grok/` reference+ * survives and the `runs/` dir is present with no `grok/` dir, so the gate+ * skips the record on every subsequent boot. A new import onto an install where+ * 202 has already applied leaves its runs under `grok/` (202 never re-runs), a+ * self-consistent layout the read layer serves directly — so 203's gate+ * correctly skips it too.+ */++import { readdir, readFile, writeFile, rename, stat } from 'fs/promises';+import { join } from 'path';+import { createHash } from 'crypto';++const LEGACY_DIR = 'grok';+const NEUTRAL_DIR = 'runs';++const exists = (abs) => stat(abs).then(() => true, () => false);+const sha256File = async (abs) => createHash('sha256').update(await readFile(abs)).digest('hex');+const readJson = async (abs) => { try { return JSON.parse(await readFile(abs, 'utf8')); } catch { return null; } };+// Atomic write (temp + rename) so a crash mid-migration can't leave a torn,+// unparseable state file behind — mirrors migration 202's writer.+const writeJson = async (abs, obj) => {+ const tmp = `${abs}.203.tmp`;+ await writeFile(tmp, `${JSON.stringify(obj, null, 2)}\n`);+ 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+// 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 (!rel || rel.split(/[\\/]/).some((seg) => seg === '..' || seg === '')) return null;+ return rel;+};++// Recursively collect *.json files under `dir` (absolute paths). Missing → [].+async function listJsonFiles(dir) {+ let entries;+ try {+ entries = await readdir(dir, { withFileTypes: true });+ } catch {+ return [];+ }+ const out = [];+ for (const entry of entries) {+ const abs = join(dir, entry.name);+ if (entry.isDirectory()) out.push(...await listJsonFiles(abs));+ else if (entry.isFile() && entry.name.endsWith('.json')) out.push(abs);+ }+ return out;+}++async function neutralizeJsonFile(id, abs) {+ const obj = await readJson(abs);+ if (!obj) return;+ const neu = deepNeutralize(id, obj);+ if (JSON.stringify(neu) !== JSON.stringify(obj)) await writeJson(abs, neu);+}++// Rewrite the per-direction entries of a selection/walk-set object in place,+// recomputing `runManifestSha256` for every entry whose runManifest we moved+// (the file bytes changed when its embedded paths were rewritten). Resolves the+// (repo-anchored) runManifest to a record-relative disk path first; a manifest+// missing on disk keeps its old sha rather than throwing — the imported set is+// frozen/immutable and nothing verifies these pins at read time, so a best-+// effort recompute is strictly safer than aborting the whole heal.+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.runManifest === 'string') {+ entry.runManifest = neutralize(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));+ }+ }+}++// True when any JSON state under the record still names `sprites/<id>/grok/`.+async function hasGrokResidue(recDir, id) {+ const selAbs = join(recDir, 'walk', `${id}-walk-selection-v1.json`);+ const wsAbs = join(recDir, 'walk', `${id}-walk-set-v1.json`);+ const marker = `sprites/${id}/${LEGACY_DIR}/`;+ const sel = await readFile(selAbs, 'utf8').catch(() => '');+ if (sel.includes(marker)) return true;+ const ws = await readFile(wsAbs, 'utf8').catch(() => '');+ if (ws.includes(marker)) return true;+ for (const abs of await listJsonFiles(join(recDir, NEUTRAL_DIR))) {+ // eslint-disable-next-line no-await-in-loop -- short-circuits on first hit+ if ((await readFile(abs, 'utf8').catch(() => '')).includes(marker)) return true;+ }+ return false;+}++async function migrateRecord(recDir, recordId) {+ const hasRunsDir = await exists(join(recDir, NEUTRAL_DIR));+ const hasGrokDir = await exists(join(recDir, LEGACY_DIR));+ // Only heal records 202 already MOVED (runs/ present, grok/ gone) that still+ // carry the repo-anchored grok/ residue. A record still holding a grok/ dir+ // is self-consistent (or 202's pending work) — leave it to 202.+ if (!hasRunsDir || hasGrokDir) return false;+ if (!await hasGrokResidue(recDir, recordId)) return false;++ const selAbs = join(recDir, 'walk', `${recordId}-walk-selection-v1.json`);+ const wsAbs = join(recDir, 'walk', `${recordId}-walk-set-v1.json`);+ const ptrAbs = join(recDir, 'runtime', 'current.json');+ const runtimeDir = join(recDir, 'runtime');++ // 1. Rewrite every run record + postprocess manifest now under runs/.+ for (const abs of await listJsonFiles(join(recDir, NEUTRAL_DIR))) await neutralizeJsonFile(recordId, abs);++ // 2. Selection → recompute per-entry runManifestSha256 from the rewritten runs.+ const selection = await readJson(selAbs);+ if (selection?.directions) {+ await neutralizeDirectionEntries(recDir, recordId, selection.directions);+ await writeJson(selAbs, selection);+ }+ const newSelectionSha = await exists(selAbs) ? await sha256File(selAbs) : null;++ // 3. Walk-set → same per-entry recompute, plus the selection-content sha.+ const walkSet = await readJson(wsAbs);+ if (walkSet) {+ if (walkSet.directions) await neutralizeDirectionEntries(recDir, recordId, walkSet.directions);+ if (newSelectionSha && typeof walkSet.selectionSha256 === 'string') walkSet.selectionSha256 = newSelectionSha;+ await writeJson(wsAbs, walkSet);+ }+ const newWalkSetSha = await exists(wsAbs) ? await sha256File(wsAbs) : null;++ // 4. Compiled-atlas manifests (provenance) + the runtime pointer's shas.+ for (const vDir of await readdir(runtimeDir, { withFileTypes: true }).catch(() => [])) {+ if (!vDir.isDirectory() || !/^v\d+$/.test(vDir.name)) continue;+ for (const abs of await listJsonFiles(join(runtimeDir, vDir.name))) await neutralizeJsonFile(recordId, abs);+ }+ const pointer = await readJson(ptrAbs);+ if (pointer) {+ if (newWalkSetSha && typeof pointer.walkSetSha256 === 'string') pointer.walkSetSha256 = newWalkSetSha;+ if (typeof pointer.manifestPath === 'string' && await exists(join(recDir, pointer.manifestPath))) {+ pointer.manifestSha256 = await sha256File(join(recDir, pointer.manifestPath));+ }+ await writeJson(ptrAbs, pointer);+ }+ return true;+}++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 migrated = 0;+ const failures = [];+ for (const rec of records) {+ if (!rec.isDirectory()) continue;+ try {+ if (await migrateRecord(join(spritesDir, rec.name), rec.name)) {+ migrated++;+ console.log(`🧭 migration 203: healed imported grok/ run paths for sprite ${rec.name}`);+ }+ } catch (err) {+ failures.push(rec.name);+ console.error(`❌ migration 203 (${rec.name}): ${err.message}`);+ }+ }+ if (failures.length > 0) {+ throw new Error(`migration 203: ${failures.length} sprite record(s) failed to heal (${failures.join(', ')}) — the rest healed; reboot to retry.`);+ }+ return { ok: true, migrated };+ },+};diff --git a/scripts/migrations/203-heal-imported-grok-run-paths.test.js b/scripts/migrations/203-heal-imported-grok-run-paths.test.jsnew file mode 100644index 0000000000..e799d785b9--- /dev/null+++ b/scripts/migrations/203-heal-imported-grok-run-paths.test.js@@ -0,0 +1,199 @@+/**+ * Migration 203 — heal the repo-anchored `art-source/sprites/<id>/grok/…` path+ * residue that migration 202 left dangling on IMPORTED sprite records (the run+ * bytes already moved to runs/, but 202's `startsWith('grok/')` neutralizer+ * never matched the source-anchored strings). Builds a record in exactly that+ * post-202 state — files under runs/, every embedded path still `…/grok/…` —+ * and asserts the migration rewrites the vendor segment to `runs/`, recomputes+ * the sha cascade, preserves the `art-source/…` provenance prefix and image+ * shas, and never touches self-consistent or non-run-path data.+ */++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 { join } from 'path';+import { createHash } from 'crypto';+import migration from './203-heal-imported-grok-run-paths.js';++let ROOT;+const sprites = () => join(ROOT, 'data', 'sprites');+const sha = (buf) => createHash('sha256').update(buf).digest('hex');+const shaFile = async (abs) => sha(await readFile(abs));+const readJson = async (abs) => JSON.parse(await readFile(abs, 'utf8'));+const exists = (abs) => stat(abs).then(() => true, () => false);+const writeJson = (abs, obj) => writeFile(abs, JSON.stringify(obj));++const RUN_ID = 'walk-south-east-0ae1f1e496bc';++// A record in the broken post-202 state: run DIRECTORY already lives under+// runs/, but every embedded path is still the source-anchored+// `art-source/sprites/<id>/grok/…` form 202 failed to rewrite. runManifest+// points at the run record (animation-run.json) — the imported pin structure,+// distinct from 202's own tests where it points at the postprocess manifest.+async function buildBrokenImport(id) {+ const recDir = join(sprites(), id);+ const runDir = join(recDir, 'runs', RUN_ID);+ const genDir = join(runDir, 'generated');+ await mkdir(join(genDir, 'frames'), { recursive: true });+ await mkdir(join(recDir, 'walk'), { recursive: true });++ const framePng = Buffer.from('frame-pixels');+ const stripPng = Buffer.from('strip-pixels');+ await writeFile(join(genDir, 'frames', '00-left-contact.png'), framePng);+ await writeFile(join(genDir, `${id}-walk-south-east-strip.png`), stripPng);++ const anchor = (p) => `art-source/sprites/${id}/grok/${p}`;++ // Postprocess manifest — embeds source-anchored grok/ frame + strip paths.+ await writeJson(join(genDir, `${id}-walk-south-east-manifest.json`), {+ schemaVersion: 1,+ kind: 'deterministically-packaged-grok-walk-video',+ characterId: id,+ direction: 'south-east',+ frames: [{ outputIndex: 0, path: anchor(`${RUN_ID}/generated/frames/00-left-contact.png`), sha256: sha(framePng) }],+ stripPath: anchor(`${RUN_ID}/generated/${id}-walk-south-east-strip.png`),+ stripSha256: sha(stripPng),+ });++ // Run record — the frozen-imported run. Note kind/skill strings that CONTAIN+ // "grok" but are NOT paths: they must survive verbatim.+ const runRecAbs = join(runDir, 'animation-run.json');+ await writeJson(runRecAbs, {+ schemaVersion: 1,+ kind: 'grok-game-animation-frames-run',+ id: RUN_ID,+ characterId: id,+ direction: 'south-east',+ status: 'candidate',+ skill: 'local-postprocess-of-existing-grok-session-video',+ outputRoot: anchor(RUN_ID),+ postprocessManifest: anchor(`${RUN_ID}/generated/${id}-walk-south-east-manifest.json`),+ stripPreview: { path: anchor(`${RUN_ID}/generated/${id}-walk-south-east-strip.png`), frameCount: 8, fps: 12 },+ });+ const runRecSha = await shaFile(runRecAbs);++ const dirEntry = {+ status: 'approved',+ runId: RUN_ID,+ runPath: anchor(RUN_ID),+ runManifest: anchor(`${RUN_ID}/animation-run.json`),+ runManifestSha256: runRecSha,+ approvedAt: 't',+ };++ const selRel = `walk/${id}-walk-selection-v1.json`;+ await writeJson(join(recDir, selRel), {+ schemaVersion: 1,+ kind: 'reviewed-directional-walk-selection',+ characterId: id,+ status: 'complete',+ directions: { 'south-east': { ...dirEntry } },+ });+ const selSha = await shaFile(join(recDir, selRel));++ const wsRel = `walk/${id}-walk-set-v1.json`;+ await writeJson(join(recDir, wsRel), {+ schemaVersion: 1,+ kind: 'finalized-eight-direction-walk-set',+ characterId: id,+ status: 'final',+ selectionPath: `art-source/sprites/${id}/walk/${id}-walk-selection-v1.json`,+ selectionSha256: selSha,+ directions: { 'south-east': { ...dirEntry } },+ });++ return { recDir, runDir, framePng, stripPng };+}++beforeEach(() => { ROOT = mkdtempSync(join(tmpdir(), 'mig-203-')); });+afterEach(() => rmSync(ROOT, { recursive: true, force: true }));++describe('migration 203 — heal imported grok/ run paths', () => {+ it('rewrites the source-anchored grok/ segment to runs/ and rebuilds the sha cascade', async () => {+ const id = 'pioneer-fixture';+ const { recDir, runDir, framePng } = await buildBrokenImport(id);++ const res = await migration.up({ rootDir: ROOT });+ expect(res).toMatchObject({ ok: true, migrated: 1 });++ // Run record — grok/ segment healed, provenance prefix + non-path grok+ // strings preserved.+ const runRec = await readJson(join(runDir, 'animation-run.json'));+ expect(runRec.stripPreview.path).toBe(`art-source/sprites/${id}/runs/${RUN_ID}/generated/${id}-walk-south-east-strip.png`);+ expect(runRec.outputRoot).toBe(`art-source/sprites/${id}/runs/${RUN_ID}`);+ expect(runRec.postprocessManifest).toBe(`art-source/sprites/${id}/runs/${RUN_ID}/generated/${id}-walk-south-east-manifest.json`);+ expect(runRec.kind).toBe('grok-game-animation-frames-run'); // NOT a path — untouched+ expect(runRec.skill).toBe('local-postprocess-of-existing-grok-session-video'); // untouched++ // Postprocess manifest — paths healed, image sha preserved.+ const pp = await readJson(join(runDir, 'generated', `${id}-walk-south-east-manifest.json`));+ expect(pp.stripPath).toBe(`art-source/sprites/${id}/runs/${RUN_ID}/generated/${id}-walk-south-east-strip.png`);+ expect(pp.frames[0].path).toBe(`art-source/sprites/${id}/runs/${RUN_ID}/generated/frames/00-left-contact.png`);+ expect(pp.frames[0].sha256).toBe(sha(framePng));++ // Selection + walk-set — entries healed, sha cascade internally consistent.+ const selAbs = join(recDir, 'walk', `${id}-walk-selection-v1.json`);+ const wsAbs = join(recDir, 'walk', `${id}-walk-set-v1.json`);+ const sel = await readJson(selAbs);+ const ws = await readJson(wsAbs);+ expect(sel.directions['south-east'].runPath).toBe(`art-source/sprites/${id}/runs/${RUN_ID}`);+ expect(sel.directions['south-east'].runManifest).toBe(`art-source/sprites/${id}/runs/${RUN_ID}/animation-run.json`);+ // runManifestSha256 re-pins the rewritten run record's new bytes.+ expect(sel.directions['south-east'].runManifestSha256).toBe(await shaFile(join(runDir, 'animation-run.json')));+ expect(ws.directions['south-east'].runManifestSha256).toBe(await shaFile(join(runDir, 'animation-run.json')));+ expect(ws.selectionSha256).toBe(await shaFile(selAbs));+ // The non-grok selectionPath provenance is left intact (keeps the walk set+ // recognizable as imported).+ expect(ws.selectionPath).toBe(`art-source/sprites/${id}/walk/${id}-walk-selection-v1.json`);+ });++ it('is idempotent — a second run changes nothing and reports migrated: 0', async () => {+ const id = 'pioneer-idem';+ const { recDir } = await buildBrokenImport(id);+ await migration.up({ rootDir: ROOT });++ const snapshot = async () => ({+ sel: await readFile(join(recDir, 'walk', `${id}-walk-selection-v1.json`), 'utf8'),+ ws: await readFile(join(recDir, 'walk', `${id}-walk-set-v1.json`), 'utf8'),+ run: await readFile(join(recDir, 'runs', RUN_ID, 'animation-run.json'), 'utf8'),+ });+ const before = await snapshot();+ const res = await migration.up({ rootDir: ROOT });+ expect(res).toMatchObject({ ok: true, migrated: 0 });+ expect(await snapshot()).toEqual(before);+ });++ it('leaves a self-consistent grok/-layout record (grok/ dir present) untouched', async () => {+ // A record whose runs still live under grok/ AND whose paths say grok/ is+ // internally consistent (or 202's pending move) — 203 must not touch it.+ const id = 'still-grok';+ const recDir = join(sprites(), id);+ await mkdir(join(recDir, 'grok', RUN_ID), { recursive: true });+ await mkdir(join(recDir, 'walk'), { recursive: true });+ const sel = {+ schemaVersion: 1, characterId: id, status: 'complete',+ directions: { 'south-east': { status: 'approved', runPath: `art-source/sprites/${id}/grok/${RUN_ID}`, approvedAt: 't' } },+ };+ await writeJson(join(recDir, 'walk', `${id}-walk-selection-v1.json`), sel);+ const res = await migration.up({ rootDir: ROOT });+ expect(res).toMatchObject({ ok: true, migrated: 0 });+ expect(await readJson(join(recDir, 'walk', `${id}-walk-selection-v1.json`))).toEqual(sel);+ });++ it('leaves an already-neutral imported record (no grok/ residue) untouched', async () => {+ const id = 'clean-import';+ const recDir = join(sprites(), id);+ await mkdir(join(recDir, 'runs', RUN_ID), { recursive: true });+ await mkdir(join(recDir, 'walk'), { recursive: true });+ const sel = {+ schemaVersion: 1, characterId: id, status: 'complete',+ directions: { east: { status: 'approved', runManifest: `art-source/sprites/${id}/imagegen/v19/x-manifest.json`, approvedAt: 't' } },+ };+ await writeJson(join(recDir, 'walk', `${id}-walk-selection-v1.json`), sel);+ const res = await migration.up({ rootDir: ROOT });+ expect(res).toMatchObject({ ok: true, migrated: 0 });+ expect(await readJson(join(recDir, 'walk', `${id}-walk-selection-v1.json`))).toEqual(sel);+ });+});