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([issue-2978]): re-anchor imported runs' art-source/ paths so loop trims save
[._.]/ Adam Eivy235c45ee2e94
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 0dd375fda4..c514ff9516 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -22,6 +22,7 @@## Sprite Manager+- **[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.- **Locking a main reference no longer leaves a colored halo around the character** — when you lock a character's main reference, PortOS re-keys the background to whichever chroma color (magenta, green, or blue) sits farthest from the character's own palette. If that swapped the background — e.g. a magenta render re-keyed onto blue — the anti-aliased pixels along the character's outline kept their old magenta tint and showed up as a faint magenta ring against the new blue backdrop. Locking now cleans those edge pixels as it re-keys, so the outline blends into the new background with no leftover halo. Already-locked references (which are immutable and can't be re-locked) are healed automatically on upgrade: each one is re-derived from its saved candidate with the fix applied, and its stored checksum is refreshed — no action needed on your part.diff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.jsindex 07df116958..54c3df3b59 100644--- a/server/services/sprites/walk.js+++ b/server/services/sprites/walk.js@@ -183,6 +183,26 @@ 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.+// 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 };+}+// A candidate/approved run's stripPreview names a packed strip PNG on disk. If// that file has since gone missing — a botched migration dropped it, a manual// cleanup nuked it — the run record still advertises the path, so the native@@ -224,7 +244,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 normalizeStripPreview(recordId, withId);+ return normalizePostprocessManifest(recordId, normalizeStripPreview(recordId, withId));}// Strip candidates on an imported redraw manifest, in preference order. The@@ -793,7 +813,14 @@ async function approveWalkDirectionImpl(recordId, { direction, runId }) {// declared frameCount must match the actual packed frames. Cross-direction// consistency (all approved directions sharing one count/fps) is enforced at// atlas-compile time, where the whole set is visible at once.- const manifestAbs = resolveSpriteAssetPath(recordId, run.postprocessManifest);+ // `loadRunRecord` deliberately returns the RAW record (its results flow into+ // saveRunRecord elsewhere, and an imported manifest's bytes are hash-pinned to+ // the source), so re-anchor the repo-anchored path here at the point of use+ // rather than in the loader — same fixup normalizeRunRecord applies to the+ // read-only view (#2978).+ const manifestRel = toRecordRelativeAssetPath(recordId, run.postprocessManifest)+ || run.postprocessManifest;+ const manifestAbs = resolveSpriteAssetPath(recordId, manifestRel);const packaged = await readJSONFile(manifestAbs, null);const frameCountValid = Number.isInteger(packaged?.frameCount)&& packaged.frameCount >= WALK_MIN_FRAME_COUNT && packaged.frameCount <= WALK_MAX_FRAME_COUNT@@ -808,7 +835,11 @@ async function approveWalkDirectionImpl(recordId, { direction, runId }) {|| packaged.direction !== direction || packaged.characterId !== recordId) {throw new ServerError('Packaged run manifest is missing or inconsistent', { status: 409, code: 'RUN_MANIFEST_INVALID' });}- const stripAbs = resolveSpriteAssetPath(recordId, packaged.stripPath);+ // An imported manifest's OWN stripPath is repo-anchored too — re-anchor before+ // resolving, or the tamper check 409s on a strip that is present and intact.+ const packagedStripRel = toRecordRelativeAssetPath(recordId, packaged.stripPath)+ || packaged.stripPath;+ const stripAbs = resolveSpriteAssetPath(recordId, packagedStripRel);if (!await pathExists(stripAbs) || await sha256File(stripAbs) !== packaged.stripSha256) {throw new ServerError('Packed strip is missing or was modified after packaging', { status: 409, code: 'RUN_STRIP_INVALID' });}@@ -818,7 +849,9 @@ async function approveWalkDirectionImpl(recordId, { direction, runId }) {status: 'approved',runId,runPath: runRelPath(runId),- runManifest: run.postprocessManifest,+ // Store the re-anchored path: the selection is PortOS-owned state (unlike the+ // hash-pinned imported manifest), and every reader already normalizes it.+ runManifest: manifestRel,runManifestSha256: await sha256File(manifestAbs),approvedAt: new Date().toISOString(),};diff --git a/server/services/sprites/walk.test.js b/server/services/sprites/walk.test.jsindex 359cb7d520..bb59ff998f 100644--- a/server/services/sprites/walk.test.js+++ b/server/services/sprites/walk.test.js@@ -95,12 +95,18 @@ async function characterWithLockedAnchors(id, directions = ['east']) {return id;}-async function makeCandidateRun(recordId, direction, { stripBytes = `strip-${direction}` } = {}) {+// `anchored: true` builds the run the way the source-pipeline importer leaves+// it (#2978): every embedded path stays anchored at the SOURCE repo root+// (`art-source/sprites/<id>/…`) because the importer copies manifests+// byte-for-byte against pinned hashes. Readers must re-anchor at read time.+async function makeCandidateRun(recordId, direction, { stripBytes = `strip-${direction}`, anchored = false } = {}) {const runId = `walk-${direction}-${(seq++).toString(16).padStart(8, '0')}`;const runDir = join(TEST_ROOT, 'sprites', recordId, 'runs', runId, 'generated');await mkdir(runDir, { recursive: true });const stripName = `${recordId}-walk-${direction}-strip.png`;await writeFile(join(runDir, stripName), stripBytes);+ const anchor = (rel) => (anchored ? `art-source/sprites/${recordId}/${rel}` : rel);+ const stripRel = `runs/${runId}/generated/${stripName}`;const packaged = {schemaVersion: 1,kind: 'deterministically-packaged-grok-walk-video',@@ -108,7 +114,7 @@ async function makeCandidateRun(recordId, direction, { stripBytes = `strip-${dirdirection,frameRate: 12,frameCount: 8,- stripPath: `runs/${runId}/generated/${stripName}`,+ stripPath: anchor(stripRel),stripSha256: sha256(Buffer.from(stripBytes)),};const manifestRel = `runs/${runId}/generated/${recordId}-walk-${direction}-manifest.json`;@@ -122,10 +128,11 @@ async function makeCandidateRun(recordId, direction, { stripBytes = `strip-${dirdirection,chromaKey: '#FF00FF',createdAt: new Date().toISOString(),- postprocessManifest: manifestRel,+ postprocessManifest: anchor(manifestRel),// Real candidate records carry the packed-strip preview the UI renders.+ // The importer stamps it as `path` (repo-anchored); PortOS uses `stripPath`.stripPreview: {- stripPath: `runs/${runId}/generated/${stripName}`,+ ...(anchored ? { path: anchor(stripRel) } : { stripPath: stripRel }),frameCount: 8, fps: 12, cellWidth: 384, cellHeight: 384, row: 0, startColumn: 0,},}));@@ -398,6 +405,22 @@ describe('approveWalkDirection', () => {expect(state.walkSet).toBeNull();});+ // #2978: an imported run's postprocessManifest and the manifest's own+ // stripPath are both anchored at the source repo root. Resolved raw they+ // produce a doubled non-existent path, so approval 409'd RUN_MANIFEST_INVALID+ // on art that is present and intact.+ it('approves an imported run whose manifest paths are art-source/-anchored', async () => {+ const id = await characterWithLockedAnchors(newId(), ['east']);+ const { runId, manifestRel } = await makeCandidateRun(id, 'east', { anchored: true });+ const state = await approveWalkDirection(id, { direction: 'east', runId });+ expect(state.selection.directions.east).toMatchObject({+ // The selection stores the RE-ANCHORED path — it's PortOS-owned state,+ // unlike the hash-pinned imported manifest it points at.+ status: 'approved', runId, runManifest: manifestRel,+ });+ expect(state.selection.directions.east.runManifestSha256).toMatch(/^[0-9a-f]{64}$/);+ });+it('finalizes the walk set on the 8th approval and freezes the record', async () => {const id = await characterWithLockedAnchors(newId(), ANCHOR_DIRECTIONS);let state;diff --git a/server/services/sprites/walkTrims.js b/server/services/sprites/walkTrims.jsindex 1b8715446f..10672d00d5 100644--- a/server/services/sprites/walkTrims.js+++ b/server/services/sprites/walkTrims.js@@ -23,7 +23,7 @@ import {} from '../../lib/fileUtils.js';import { findFfmpeg, runFfmpegProcess } from '../../lib/ffmpeg.js';import { ServerError } from '../../lib/errorHandler.js';-import { resolveSpriteAssetPath, spriteDir } from './paths.js';+import { resolveSpriteAssetPath, spriteDir, toRecordRelativeAssetPath } from './paths.js';import { requireCharacter } from './reference.js';import { withWalkWriteTail, getWalkState } from './walk.js';import { WALK_FPS } from './walkPostprocess.js';@@ -95,14 +95,27 @@ async function resolveTrimSource(recordId, runId) {const run = state.runs.find((r) => r.id === runId);if (!run) throw new ServerError(`Unknown walk run: ${runId}`, { status: 404, code: 'RUN_NOT_FOUND' });- if (run.postprocessManifest) {- const packaged = await readJSONFile(resolveSpriteAssetPath(recordId, run.postprocessManifest), null);- if (!packaged?.stripPath || !packaged.alignment?.cellSize || !Array.isArray(packaged.frames)) {+ // `getWalkState` re-anchors an imported run's `postprocessManifest` for us+ // (walk.js#normalizePostprocessManifest), 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+ // real corruption and still throws. Conflating the two either blocks trimming a+ // perfectly good strip or silently papers over a broken manifest.+ const manifestAbs = run.postprocessManifest+ ? resolveSpriteAssetPath(recordId, run.postprocessManifest)+ : null;+ if (manifestAbs && await pathExists(manifestAbs)) {+ const packaged = await readJSONFile(manifestAbs, null);+ // An imported manifest's own stripPath is repo-anchored (`art-source/…`) —+ // re-anchor it before it reaches resolveSpriteAssetPath downstream.+ const stripPath = toRecordRelativeAssetPath(recordId, packaged?.stripPath);+ if (!stripPath || !packaged.alignment?.cellSize || !Array.isArray(packaged.frames)) {throw new ServerError('Packaged run manifest is missing or inconsistent', { status: 409, code: 'RUN_MANIFEST_INVALID' });}return {direction: run.direction,- stripPath: packaged.stripPath,+ stripPath,cellSize: packaged.alignment.cellSize,allColumns: packaged.frames.map((f) => f.outputIndex),phaseByColumn: Object.fromEntries(packaged.frames.map((f) => [f.outputIndex, f.phase])),diff --git a/server/services/sprites/walkTrims.test.js b/server/services/sprites/walkTrims.test.jsindex 9f7a540883..cd5be06e02 100644--- a/server/services/sprites/walkTrims.test.js+++ b/server/services/sprites/walkTrims.test.js@@ -109,6 +109,55 @@ async function characterWithRedrawRun(id, { frameCount = 6 } = {}) {return `${id}-redraw-east`;}+// An IMPORTED source-pipeline run (#2978): the importer copies manifests+// byte-for-byte (their hashes are pinned against the source), so every embedded+// path stays anchored at the SOURCE repo root — `stripPreview.path`,+// `postprocessManifest`, and the manifest's own `stripPath`. Readers must+// re-anchor at read time; left raw they resolve to+// `data/sprites/<id>/art-source/sprites/<id>/…`, which is inside the record dir+// (so the traversal gate passes) but does not exist.+async function characterWithImportedRun(id, { manifest = 'valid' } = {}) {+ await records.createRecord({ kind: 'character', name: 'Imported' }, id);+ const width = CELL * CELL_COLORS.length;+ const buf = Buffer.alloc(width * CELL * 4);+ for (let y = 0; y < CELL; y++) {+ for (let x = 0; x < width; x++) {+ buf.set(CELL_COLORS[Math.floor(x / CELL)], (y * width + x) * 4);+ }+ }+ const runDir = join(TEST_ROOT, 'sprites', id, 'runs', RUN_ID);+ await mkdir(join(runDir, 'generated'), { recursive: true });+ await sharp(buf, { raw: { width, height: CELL, channels: 4 } }).png()+ .toFile(join(runDir, 'generated', 'strip.png'));+ const anchored = (rel) => `art-source/sprites/${id}/${rel}`;+ const stripRel = `runs/${RUN_ID}/generated/strip.png`;+ const manifestRel = `runs/${RUN_ID}/generated/manifest.json`;+ if (manifest !== 'absent') {+ await writeFile(join(runDir, 'generated', 'manifest.json'), manifest === 'malformed'+ ? JSON.stringify({ schemaVersion: 1, stripPath: anchored(stripRel) }) // no cellSize, no frames+ : JSON.stringify({+ schemaVersion: 1,+ stripPath: anchored(stripRel),+ frameRate: 12,+ frameCount: 4,+ alignment: { cellSize: CELL },+ frames: PHASES4.map((phase, outputIndex) => ({ outputIndex, phase })),+ }));+ }+ await writeFile(join(runDir, 'animation-run.json'), JSON.stringify({+ schemaVersion: 1,+ id: RUN_ID,+ status: 'candidate',+ direction: 'east',+ postprocessManifest: anchored(manifestRel),+ // The importer's shape: `path`, not `stripPath`, and repo-anchored.+ stripPreview: {+ path: anchored(stripRel), frameCount: 4, fps: 12, cellWidth: CELL, cellHeight: CELL, row: 0, startColumn: 0,+ },+ }));+ return id;+}+beforeEach(() => {runFfmpegProcess.mockClear();rmSync(join(TEST_ROOT, 'sprite-records.json'), { force: true });@@ -204,6 +253,50 @@ describe('saveLoopTrim', () => {expect(manifest.selectedFrames.map((f) => f.sourceFrameLabel)).toEqual(['0', '2', '4']);});+ // #2978: every path an imported run carries is anchored at the SOURCE repo+ // root. Before the fix, resolving `postprocessManifest` raw produced a+ // doubled non-existent path and 409'd RUN_MANIFEST_INVALID on every save —+ // the whole trim feature was dead for imported records.+ it('trims an imported run whose paths are all art-source/-anchored', async () => {+ const id = await characterWithImportedRun(newId());+ const result = await saveLoopTrim(id, { runId: RUN_ID, enabledColumns: [0, 2, 3] });+ expect(result).toMatchObject({ frameCount: 3, disabledFrameCount: 1 });++ const { data, info } = await sharp(join(TEST_ROOT, 'sprites', id, result.strip))+ .raw().toBuffer({ resolveWithObject: true });+ expect(info.width).toBe(CELL * 3);+ const px = (x) => [...data.subarray(x * 4, x * 4 + 4)];+ expect(px(0)).toEqual(CELL_COLORS[0]);+ expect(px(CELL)).toEqual(CELL_COLORS[2]);+ expect(px(CELL * 2)).toEqual(CELL_COLORS[3]);++ const manifest = JSON.parse(await readFile(join(TEST_ROOT, 'sprites', id, result.manifest), 'utf8'));+ // The trim records a RECORD-relative source path, not the source repo's.+ expect(manifest.sourceAtlasPath).toBe(`runs/${RUN_ID}/generated/strip.png`);+ // Manifest read successfully → real gait-phase labels, not numeric fallbacks.+ expect(manifest.selectedFrames.map((f) => f.sourceFrameLabel))+ .toEqual(['left-contact', 'left-passing', 'left-up']);+ });++ // Absent vs. malformed must NOT collapse: a missing manifest file is a+ // degraded-but-trimmable run (stripPreview carries the geometry), while a+ // manifest that exists but is inconsistent is real corruption.+ it('falls back to stripPreview when the packaged manifest file is absent', async () => {+ const id = await characterWithImportedRun(newId(), { manifest: 'absent' });+ const result = await saveLoopTrim(id, { runId: RUN_ID, enabledColumns: [0, 1] });+ expect(result).toMatchObject({ frameCount: 2, disabledFrameCount: 2 });+ const manifest = JSON.parse(await readFile(join(TEST_ROOT, 'sprites', id, result.manifest), 'utf8'));+ expect(manifest.sourceAtlasPath).toBe(`runs/${RUN_ID}/generated/strip.png`);+ // No manifest → no phase labels; columns label numerically.+ expect(manifest.selectedFrames.map((f) => f.sourceFrameLabel)).toEqual(['0', '1']);+ });++ it('still rejects a manifest that exists but is inconsistent', async () => {+ const id = await characterWithImportedRun(newId(), { manifest: 'malformed' });+ await expect(saveLoopTrim(id, { runId: RUN_ID, enabledColumns: [0, 1] }))+ .rejects.toMatchObject({ code: 'RUN_MANIFEST_INVALID' });+ });+it('rejects unknown runs, unpackaged runs, and out-of-strip columns', async () => {const id = await characterWithRun(newId());await expect(saveLoopTrim(id, { runId: 'walk-east-deadbeef', enabledColumns: [0, 1] }))