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
sprite manager: delete old assets, and store walk runs vendor-neutrally so every direction is trimmable
[._.]/ Adam Eivy819786e3d399
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex c7e110b9a9..b908d3193f 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -7,6 +7,9 @@## Sprite Manager+- **Every walk direction is trimmable now, whatever produced it** — a direction whose art came from the source pipeline's older video-first "redraw" path (pioneer's *east* being the case in the wild) showed its "approved ✓" card with no **Edit in Loop Trimmer** link, because loop trimming was wired only to grok-generated runs. The Loop Trimmer now resolves any run's geometry from the run's own manifest/strip regardless of where it was authored, so imported and redraw directions are trimmable exactly like native ones — the link appears on every direction that has a packed strip. (Saved trims stay preview-only; there's no run behind them to re-trim.)+- **Sprite runs are stored vendor-neutrally** — under the hood, PortOS used to file its own walk generations under a `grok/` directory, baking one provider into the on-disk layout. Runs now live under a neutral `runs/` tree with the provider recorded as run metadata instead, so future agent services or generation methods slot in without a storage change and nothing downstream (trimming, atlas compile, publish, backups) assumes a vendor. Existing installs are migrated automatically on upgrade: each character's `grok/<run>/` directories are renamed to `runs/<run>/`, every embedded path is rewritten, and the checksums that pin the finalized walk set + compiled atlas are recomputed so a re-compile stays a no-op — your published atlases are unaffected. Imported/redraw characters and the atlas image bytes are left untouched.+- **Delete old atlas and reference images from the asset inspector** — as you iterate a character, its `runtime/` tree fills up with superseded atlas versions (`…-animation-atlas-v10.png`, v9, v8…) and its reference/walk trees fill up with old candidate renders, with no way to prune them short of hand-editing `data/sprites/`. The asset inspector now has a **Delete** action: open any asset, click Delete, confirm in an inline Cancel/Delete row, and it's removed from disk (the library refreshes in place). Deleting an old runtime atlas removes its sidecar manifest in the same step, so a version goes cleanly. The one atlas you can't delete is the current published one — PortOS refuses it (and the pointer/publish-history bookkeeping) so you can't strand a live game or the recompiler; compile or publish a newer version first.- **Unlock a finalized walk set to revise it** — a frozen 8-direction walk set was one-way: the "walk set frozen · immutable" badge was the end of the road, and the only way to change a direction was to start a whole new character version. The Walk Cycles panel now offers an **Unlock** button beside that badge (with an inline "Re-open all directions?" confirm). Unlocking removes the frozen set and re-opens every direction back into the generate / regenerate / approve flow — your already-rendered clips are kept on disk, so you can re-approve the ones you like and re-render just the ones you don't; re-approving all eight re-freezes the set exactly as before. Walk sets imported from an external source pipeline (which have no regenerable clips behind them) still can't be unlocked and say so.- **The Loop Trimmer auto-plays when you open its tab** — switching to the Loop Trimmer now starts the loop preview animating immediately instead of waiting for a manual Play click; switching the animation source keeps it playing.- **The asset inspector is readable again** — clicking an atlas or any sprite asset opens the inspector over a solid card and a darker backdrop, so the metadata (path, dimensions, frame count, size) and the Download / Open / Copy-path buttons no longer have the page bleeding through behind them.diff --git a/client/src/components/sprites/AssetCollection.jsx b/client/src/components/sprites/AssetCollection.jsxindex 4cc43d95fc..7f0af8f603 100644--- a/client/src/components/sprites/AssetCollection.jsx+++ b/client/src/components/sprites/AssetCollection.jsx@@ -112,7 +112,7 @@ function AssetCard({ recordId, asset, actions, onInspect }) {* here in the caller: an asset whose `runId` is an approved run is promoted to* `approved` for its badge, keeping the classifier free of workflow state.*/-export default function AssetCollection({ recordId, assets, actions = null, approvedRunIds }) {+export default function AssetCollection({ recordId, assets, actions = null, approvedRunIds, onDeleted = null }) {const [inspecting, setInspecting] = useState(null);const groups = useMemo(() => {const grouped = groupSpriteAssetsByRole(assets);@@ -152,7 +152,12 @@ export default function AssetCollection({ recordId, assets, actions = null, appr</div></div>))}- <AssetInspector recordId={recordId} asset={inspecting} onClose={() => setInspecting(null)} />+ <AssetInspector+ recordId={recordId}+ asset={inspecting}+ onClose={() => setInspecting(null)}+ onDeleted={onDeleted}+ /></div>);}diff --git a/client/src/components/sprites/AssetInspector.jsx b/client/src/components/sprites/AssetInspector.jsxindex f54504239d..834db787ec 100644--- a/client/src/components/sprites/AssetInspector.jsx+++ b/client/src/components/sprites/AssetInspector.jsx@@ -9,12 +9,14 @@* handling, focus trap, and focus restore to the thumbnail that opened it.*/-import { Download, ClipboardCopy, ExternalLink, X } from 'lucide-react';+import { useEffect, useState } from 'react';+import { Download, ClipboardCopy, ExternalLink, Trash2, X } from 'lucide-react';import Modal from '../ui/Modal.jsx';import SpritePreview from './SpritePreview.jsx';import { spriteAssetUrl, hasSpritePreview, isVideoAsset } from './spriteAssets.js';import { formatBytes, timeAgo } from '../../utils/formatters.js';import { copyToClipboard } from '../../lib/clipboard.js';+import { deleteSpriteAsset } from '../../services/apiSprites.js';function Row({ label, value }) {// `frameCount: 0` is meaningful, so only null/undefined/'' are omitted.@@ -27,13 +29,35 @@ function Row({ label, value }) {);}-export default function AssetInspector({ recordId, asset, onClose }) {+export default function AssetInspector({ recordId, asset, onClose, onDeleted = null }) {+ const [confirming, setConfirming] = useState(false);+ const [deleting, setDeleting] = useState(false);+ const [deleteError, setDeleteError] = useState(null);++ // Reset per-open: switching which asset is inspected (or closing) clears any+ // half-armed confirm / stale error from the previously-inspected asset.+ const assetPath = asset?.path ?? null;+ useEffect(() => {+ setConfirming(false);+ setDeleteError(null);+ }, [assetPath]);+if (!asset) return null;const url = spriteAssetUrl(recordId, asset.path);const fileName = asset.path.split('/').pop();const previewable = hasSpritePreview(asset);+ const runDelete = () => {+ setDeleting(true);+ setDeleteError(null);+ // Custom inline error UI below → silence request()'s auto-toast.+ deleteSpriteAsset(recordId, asset.path, { silent: true })+ .then(() => { onDeleted?.(); onClose?.(); })+ .catch((err) => setDeleteError(err?.message || 'Delete failed'))+ .finally(() => setDeleting(false));+ };+return (<Modalopen@@ -119,7 +143,47 @@ export default function AssetInspector({ recordId, asset, onClose }) {><ClipboardCopy className="w-3.5 h-3.5" /> Copy path</button>+ {onDeleted && !confirming && (+ <button+ type="button"+ onClick={() => { setDeleteError(null); setConfirming(true); }}+ className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs bg-port-bg border border-port-border hover:border-port-error text-gray-300 hover:text-port-error rounded ml-auto"+ >+ <Trash2 className="w-3.5 h-3.5" /> Delete+ </button>+ )}</div>++ {onDeleted && confirming && (+ // Inline confirm row (project convention: no window.confirm, and no+ // two-click-arm — a discoverable Cancel/Delete pair instead).+ <div className="space-y-2 border border-port-error/40 bg-port-error/10 rounded p-2">+ <p className="text-xs text-gray-200">+ Delete <span className="font-semibold break-all">{fileName}</span> from disk?+ {/^runtime\/v\d+\//.test(asset.path) && ' Its sidecar manifest is removed too.'}+ {' '}This can’t be undone.+ </p>+ {deleteError && <p className="text-xs text-port-error break-all">{deleteError}</p>}+ <div className="flex items-center gap-2">+ <button+ type="button"+ onClick={runDelete}+ disabled={deleting}+ className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs bg-port-error hover:bg-red-600 text-white rounded disabled:opacity-50"+ >+ <Trash2 className="w-3.5 h-3.5" /> {deleting ? 'Deleting…' : 'Delete'}+ </button>+ <button+ type="button"+ onClick={() => { setConfirming(false); setDeleteError(null); }}+ disabled={deleting}+ className="px-2.5 py-1.5 text-xs bg-port-bg border border-port-border hover:border-port-accent text-gray-300 rounded disabled:opacity-50"+ >+ Cancel+ </button>+ </div>+ </div>+ )}</div></Modal>);diff --git a/client/src/components/sprites/AssetInspector.test.jsx b/client/src/components/sprites/AssetInspector.test.jsxindex 4e516191b8..bc0e158ce5 100644--- a/client/src/components/sprites/AssetInspector.test.jsx+++ b/client/src/components/sprites/AssetInspector.test.jsx@@ -15,6 +15,9 @@ import { hasSpritePreview } from './spriteAssets.js';const copyToClipboard = vi.fn();vi.mock('../../lib/clipboard.js', () => ({ copyToClipboard: (...a) => copyToClipboard(...a) }));+const deleteSpriteAsset = vi.fn();+vi.mock('../../services/apiSprites.js', () => ({ deleteSpriteAsset: (...a) => deleteSpriteAsset(...a) }));+const IMAGE = {path: 'reference/main.png',size: 2048,@@ -25,7 +28,7 @@ const IMAGE = {frameCount: 1,};-beforeEach(() => copyToClipboard.mockClear());+beforeEach(() => { copyToClipboard.mockClear(); deleteSpriteAsset.mockReset(); });describe('hasSpritePreview', () => {it('follows the server probe rather than the file extension', () => {@@ -126,4 +129,40 @@ describe('AssetInspector', () => {const { container } = render(<AssetInspector recordId="trail-hand" asset={null} onClose={() => {}} />);expect(container).toBeEmptyDOMElement();});++ it('offers no Delete action unless an onDeleted handler is wired', () => {+ render(<AssetInspector recordId="trail-hand" asset={IMAGE} onClose={() => {}} />);+ expect(screen.queryByRole('button', { name: /^delete$/i })).not.toBeInTheDocument();+ });++ it('deletes through a two-button confirm, then refreshes and closes', async () => {+ deleteSpriteAsset.mockResolvedValue({ deleted: true, removed: 'reference/main.png' });+ const onClose = vi.fn();+ const onDeleted = vi.fn();+ render(<AssetInspector recordId="trail-hand" asset={IMAGE} onClose={onClose} onDeleted={onDeleted} />);++ // Arming reveals a discoverable Cancel/Delete pair (no window.confirm, no+ // two-click-arm on the same button).+ await userEvent.click(screen.getByRole('button', { name: /^delete$/i }));+ expect(screen.getByRole('button', { name: /^cancel$/i })).toBeInTheDocument();+ await userEvent.click(screen.getByRole('button', { name: /^delete$/i }));++ expect(deleteSpriteAsset).toHaveBeenCalledWith('trail-hand', 'reference/main.png', { silent: true });+ expect(onDeleted).toHaveBeenCalledTimes(1);+ expect(onClose).toHaveBeenCalledTimes(1);+ });++ it('shows the server refusal inline and keeps the asset (no close)', async () => {+ deleteSpriteAsset.mockRejectedValue(Object.assign(new Error('This is the current runtime atlas'), { status: 409 }));+ const onClose = vi.fn();+ const onDeleted = vi.fn();+ render(<AssetInspector recordId="trail-hand" asset={IMAGE} onClose={onClose} onDeleted={onDeleted} />);++ await userEvent.click(screen.getByRole('button', { name: /^delete$/i }));+ await userEvent.click(screen.getByRole('button', { name: /^delete$/i }));++ expect(await screen.findByText(/current runtime atlas/i)).toBeInTheDocument();+ expect(onDeleted).not.toHaveBeenCalled();+ expect(onClose).not.toHaveBeenCalled();+ });});diff --git a/client/src/components/sprites/LoopTrimmer.jsx b/client/src/components/sprites/LoopTrimmer.jsxindex 2cdbbac64c..3db8ef2624 100644--- a/client/src/components/sprites/LoopTrimmer.jsx+++ b/client/src/components/sprites/LoopTrimmer.jsx@@ -18,8 +18,8 @@ import {// source Sprite Manager's feature set to the browser — pick an animation source,// scrub/play the loop on a checkerboarded canvas, toggle individual frames, tune// fps, name the output, and save through the existing-// `POST /api/sprites/:id/walk/trim`. Only a packaged `grok/` run is trimmable;-// imported runs and previously saved trims load read-only for review.+// `POST /api/sprites/:id/walk/trim`. Every packed-strip run is trimmable (any+// layout); previously saved trims load read-only for review.const MAIN_PX = 192;const THUMB_PX = 64;diff --git a/client/src/components/sprites/LoopTrimmer.test.jsx b/client/src/components/sprites/LoopTrimmer.test.jsxindex f027b736c3..c9e4567745 100644--- a/client/src/components/sprites/LoopTrimmer.test.jsx+++ b/client/src/components/sprites/LoopTrimmer.test.jsx@@ -89,9 +89,17 @@ describe('LoopTrimmer', () => {expect(trimSpriteWalk.mock.calls[0][1]).toMatchObject({ slug: 'east-loop-v2' });});- it('disables Save for a read-only (imported) source', () => {+ it('offers Save for an imported/redraw run (strip outside grok/ is trimmable now)', () => {renderTrimmer({- walk: { runs: [{ ...grokRun, stripPreview: { ...grokRun.stripPreview, stripPath: 'runs/import-east/generated/strip.png' } }] },+ walk: { runs: [{ ...grokRun, stripPreview: { ...grokRun.stripPreview, stripPath: 'imagegen/v19/clean-alpha.png' } }] },+ });+ expect(screen.getByRole('button', { name: /Save trim/ })).not.toBeDisabled();+ });++ it('disables Save for a read-only source (a saved trim has no run to re-trim)', () => {+ renderTrimmer({+ walk: { runs: [] },+ assets: [{ path: 'walk/trims/east-loop-v001-strip.png', width: 96 * 7, height: 96 }],});expect(screen.getByRole('button', { name: /Save trim/ })).toBeDisabled();});diff --git a/client/src/components/sprites/WalkWorkflow.jsx b/client/src/components/sprites/WalkWorkflow.jsxindex e721210610..ba6e4806b8 100644--- a/client/src/components/sprites/WalkWorkflow.jsx+++ b/client/src/components/sprites/WalkWorkflow.jsx@@ -80,11 +80,13 @@ function DirectionCard({}) {const [confirming, setConfirming] = useState(false);const candidate = run?.status === 'candidate' ? run : null;- // Only a run whose strip was packaged under `grok/` can be trimmed — the trim- // endpoint reads `grok/<runId>/animation-run.json` hard-coded (an imported- // `runs/<id>/` strip 404s). The link stands for approved and finalized runs- // too, since a trim is a non-destructive derived artifact under `walk/trims/`.- const trimmable = Boolean(run?.stripPreview?.stripPath?.startsWith('grok/'));+ // Any run that carries a packed strip preview is trimmable — the trim service+ // resolves geometry from the run's own manifest/stripPreview regardless of+ // on-disk layout (native `runs/`, legacy `grok/`, imported `runs/`, or an+ // imagegen redraw), so there's no vendor-directory coupling here anymore. The+ // link stands for approved and finalized runs too, since a trim is a+ // non-destructive derived artifact under `walk/trims/`.+ const trimmable = Boolean(run?.stripPreview?.stripPath);const statusLabel = approved ? 'approved': pending ? 'rendering…': run?.status === 'postprocessing' ? 'packaging…'diff --git a/client/src/components/sprites/WalkWorkflow.test.jsx b/client/src/components/sprites/WalkWorkflow.test.jsxindex cb16a59a8a..c7d06e5675 100644--- a/client/src/components/sprites/WalkWorkflow.test.jsx+++ b/client/src/components/sprites/WalkWorkflow.test.jsx@@ -101,8 +101,8 @@ describe('WalkWorkflow loop preview', () => {// Loop trimming moved to its own deep-linkable workspace (#2933): the inline// TrimPanel is gone and each card just links into the trimmer. The link stands// for approved/finalized directions too (a trim is a non-destructive artifact),-// and only for a run whose strip was packaged under `grok/` (the endpoint reads-// `grok/<runId>/…` hard-coded — an imported strip would 404).+// and now for ANY run that carries a packed strip — the trim service resolves+// geometry layout-agnostically, so the old `grok/`-only gate is gone.describe('WalkWorkflow loop trimmer link', () => {it('offers "Edit in Loop Trimmer" for an approved grok run and fires with its id', () => {const onOpenTrimmer = vi.fn();@@ -117,10 +117,15 @@ describe('WalkWorkflow loop trimmer link', () => {expect(screen.queryByRole('button', { name: /Save trim/ })).toBeNull();});- it('hides the link for a run whose strip is not under grok/ (not trimmable)', () => {+ it('offers the link for an imported/redraw run whose strip is not under grok/', () => {+ // The exact case that left pioneer's east without a trim button: a strip+ // outside grok/ (imported runs/ or an imagegen redraw) is now trimmable.+ const onOpenTrimmer = vi.fn();renderWalk({- stripPath: 'runs/import-east/generated/strip.png', frameCount: 8, fps: 12, cellWidth: 384, cellHeight: 384,- }, { onOpenTrimmer: vi.fn() });- expect(screen.queryByRole('button', { name: /Edit in Loop Trimmer/ })).toBeNull();+ stripPath: 'imagegen/v19/clean-alpha.png', frameCount: 12, fps: 12, cellWidth: 384, cellHeight: 384,+ }, { onOpenTrimmer });+ const link = screen.getByRole('button', { name: /Edit in Loop Trimmer/ });+ link.click();+ expect(onOpenTrimmer).toHaveBeenCalledWith('run-east');});});diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex c54b27238a..3df14f79fb 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -139,7 +139,7 @@ grep -i "what you want to do" client/src/lib/README.md| `spriteCollectionActions.js` | Gating for the Sprite Manager asset collection's inline actions (#2931). `buildCollectionActions({ detail, walkPending, referencePending, generateWalk, generateAnchor, onRequestTrim })` → `{ regenerateFor(asset), trimFor(asset) }`, each returning `null` for an asset it can't act on. Regenerate mirrors the authoritative workflow surfaces exactly — a walk direction is regenerable only when its anchor is locked, the direction isn't approved, the walk set isn't finalized and no render is in flight; a reference anchor only while it's an unlocked candidate (`south`/main is excluded, since it needs a design prompt or upload). Trim is offered only for a run that actually packed a strip (the trim endpoint 409s otherwise). Pure — takes callbacks, performs no I/O. Consumes the facets from `spriteFacets.js`. || `spriteFacets.js` | Client-side facet classifier for the Sprite Manager's asset collection (#2931), mirroring the source pipeline's `classify_asset()`. `classifySpriteAsset(path)` decodes a record-relative asset path into `{ family, status, role, direction, runId }` — `status ∈ runtime/approved/candidate/superseded/rejected/source`, `role ∈ reference/strip/animation/frame/atlas/evidence/sprite/manifest` — and is total (an unknown path degrades to `sprite`/`source` rather than throwing). `classifySpriteAssets(assets)` adds the one facet only knowable across a listing: an approved asset below the highest `-vN` of its stem becomes `superseded`. `groupSpriteAssetsByRole(assets)` returns render-ready `{ role, label, assets }` sections in `SPRITE_ASSET_ROLES` order. Also exports `SPRITE_DIRECTIONS` (mirror of `server/services/sprites/prompts.js`) — the `direction`/`runId` facets are what drive the collection's Regenerate and Edit-in-Loop-Trimmer actions. Pure — no React, no I/O. || `spriteRecordGroups.js` | Grouping + search for the Sprite Manager sidebar's record picker (#2932). `groupSpriteRecords(records)` → ordered `[{ key, label, records }]` under **Characters / Places / Objects** (`props` folded into Objects alongside `object`, no migration). `filterSpriteRecords(records, query, limit=8)` is the autocomplete filter — multi-term (AND) substring over `name`/`id`/`kind`, capped at `limit`. `groupKeyForKind(kind)` maps a kind to its group key (unknown → `objects`). `SPRITE_RECORD_GROUPS` / `NEW_SPRITE_KINDS` back the browse disclosure and the create-panel kind selector. Pure — no React, no I/O; the page owns the per-group icons. |-| `spriteTrimmer.js` | Pure geometry + source-list math behind the Sprite Manager's Loop Trimmer workspace (#2933). `buildTrimmerSources(walk, assets)` → the ordered animation sources the trimmer can load (every preview-strip run first, then saved trims read from the asset listing), each `{ id, kind: 'run'\|'trim', runId, direction, label, stripPath, frameCount, fps, trimmable }` — only a `grok/` run is `trimmable`, mirroring `spriteCollectionActions`' gate. `stripFrameGeometry(stripPreview)` → `{ frameCount, fps, cellWidth, cellHeight }` with the native 8-phase / 12fps fallback; `phaseLabelFor(index, frameCount)` names the 8 walk phases (bare `frame N` for any other length); `sanitizeTrimSlug(name)` → the server's `[a-z0-9-]+` output slug; `allColumns(n)` / `invertColumns(n, enabled)` for the frame-toggle set. `WALK_PHASES` is the shared phase-label constant (WalkWorkflow imports it here). Pure — no React, no canvas, no I/O. |+| `spriteTrimmer.js` | Pure geometry + source-list math behind the Sprite Manager's Loop Trimmer workspace (#2933). `buildTrimmerSources(walk, assets)` → the ordered animation sources the trimmer can load (every preview-strip run first, then saved trims read from the asset listing), each `{ id, kind: 'run'\|'trim', runId, direction, label, stripPath, frameCount, fps, trimmable }` — every packed-strip run is `trimmable` (layout-agnostic), while saved trims are preview-only, mirroring `spriteCollectionActions`' gate. `stripFrameGeometry(stripPreview)` → `{ frameCount, fps, cellWidth, cellHeight }` with the native 8-phase / 12fps fallback; `phaseLabelFor(index, frameCount)` names the 8 walk phases (bare `frame N` for any other length); `sanitizeTrimSlug(name)` → the server's `[a-z0-9-]+` output slug; `allColumns(n)` / `invertColumns(n, enabled)` for the frame-toggle set. `WALK_PHASES` is the shared phase-label constant (WalkWorkflow imports it here). Pure — no React, no canvas, no I/O. || `tribe.js` | Pure Tribe domain helpers shared by the Tribe page and its `TribeCircleMap` visualization: `RINGS` (support→core→tribe→village Dunbar rings + the uncapped `external` "outside the tribe" classification — caps, cadence defaults, Tailwind tones + `hex`), `TRIBE_RINGS` (the four inner rings the care queue/capacity/overdue counts operate over, excluding `external`), `ENERGY` (energy tiers + `hex`), `STATUS_HEX` (cadence-status → SVG stroke color), `contactStatus(contact)` (presentation wrapper over the shared `cadenceStatus` — attaches label/tone to the missing/overdue/soon/steady/`external` state) / `daysBetween(date)` (alias of the shared `daysSinceDate`), `ringFor` / `energyFor` lookups, `tagsToArray` / `tagsToInput`, and `initialsFor(name)` (node glyph). Ring `cadenceDays` mirror `DEFAULT_RING_CADENCE` in `server/services/tribe.js`; the cadence STATE MACHINE lives in `tribeCadence.js`. || `tribeCadence.js` | Mirror of `server/lib/tribeCadence.js` — the single authoritative Tribe care-cadence rules shared by the page, the Care dashboard widget, and the proactive alert: `cadenceStatus(entity)` → `{ state, daysRemaining, daysOverdue }`, `daysSinceDate(dateStr)`, `DEFAULT_CADENCE_DAYS`, `SOON_WINDOW_DAYS`. A cross-boundary contract test asserts it never drifts from the server copy. || `streakGlyph.js` | `streakGlyph(streak)` — the single POST streak emoji (✨ / ⚡ / 🔥 by day count) shared by the POST launcher, Morse trainer, daily widget, and dashboard streak widget. |diff --git a/client/src/lib/spriteCollectionActions.js b/client/src/lib/spriteCollectionActions.jsindex 2612743631..ddfd42e720 100644--- a/client/src/lib/spriteCollectionActions.js+++ b/client/src/lib/spriteCollectionActions.js@@ -54,14 +54,14 @@ export function buildCollectionActions({anchors.filter((a) => a.status === 'locked').map((a) => a.direction),);const knownDirections = new Set(anchors.map((a) => a.direction));- // Only a run whose postprocess packed a strip UNDER `grok/` can be trimmed:- // the trim endpoint reads `grok/<runId>/animation-run.json` hard-coded, so a- // strip from an imported `runs/<id>/` layout would 404 (`RUN_NOT_FOUND`).- // Gate on the strip path's prefix, not just its presence, so the button is- // never offered for a run the server can't trim.+ // Any run that packed a strip can be trimmed: the trim service resolves the+ // run by id and derives geometry from its own manifest/stripPreview+ // regardless of on-disk layout (native `runs/`, legacy `grok/`, imported+ // `runs/`, or an imagegen redraw), so the gate is strip PRESENCE, not a+ // vendor-directory prefix.const trimmableRunIds = new Set((walk?.runs || [])- .filter((r) => r?.stripPreview?.stripPath?.startsWith('grok/'))+ .filter((r) => r?.stripPreview?.stripPath).map((r) => r.id),);diff --git a/client/src/lib/spriteTrimmer.js b/client/src/lib/spriteTrimmer.jsindex 251d3b5fc0..c237981974 100644--- a/client/src/lib/spriteTrimmer.js+++ b/client/src/lib/spriteTrimmer.js@@ -82,11 +82,12 @@ export function sanitizeTrimSlug(name) {/*** Ordered animation sources for the trimmer's source select: every packaged* walk run that carries a preview strip, followed by the record's saved trims- * (read from the asset listing). Only a run whose strip lives under `grok/` is- * `trimmable` — the trim endpoint reads `grok/<runId>/animation-run.json`- * hard-coded, so an imported `runs/<id>/` strip or a saved trim is preview-only- * (playback + scrubbing, no re-save). This mirrors `spriteCollectionActions`'- * `trimmableRunIds` gate so the two surfaces agree on what can be trimmed.+ * (read from the asset listing). Every run with a strip is `trimmable` — the+ * trim service resolves geometry layout-agnostically (native `runs/`, legacy+ * `grok/`, imported `runs/`, or an imagegen redraw), so there's no vendor+ * coupling here anymore. A saved trim is preview-only (no run behind it to+ * re-trim). This mirrors `spriteCollectionActions`' `trimmableRunIds` gate so+ * the two surfaces agree on what can be trimmed.** Each source: `{ id, kind: 'run'|'trim', runId, direction, label, stripPath,* frameCount, fps, trimmable }`. `runId` is null for a saved-trim source.@@ -106,7 +107,9 @@ export function buildTrimmerSources(walk, assets = []) {stripPath,frameCount,fps,- trimmable: stripPath.startsWith('grok/'),+ // Any run with a packed strip can be re-trimmed — the service resolves it+ // by id regardless of on-disk layout.+ trimmable: true,});}diff --git a/client/src/lib/spriteTrimmer.test.js b/client/src/lib/spriteTrimmer.test.jsindex 52ec01213b..fbe488a8b5 100644--- a/client/src/lib/spriteTrimmer.test.js+++ b/client/src/lib/spriteTrimmer.test.js@@ -86,10 +86,13 @@ describe('buildTrimmerSources', () => {]);});- it('marks only grok/ runs trimmable; imported runs and saved trims are preview-only', () => {+ it('marks every packed-strip run trimmable regardless of layout; saved trims stay preview-only', () => {const out = buildTrimmerSources(walk, assets);expect(out.find((s) => s.id === 'run:walk-east-1').trimmable).toBe(true);- expect(out.find((s) => s.id === 'run:import-north').trimmable).toBe(false);+ // Imported/redraw runs (strip outside grok/) are now trimmable too — the+ // service resolves geometry layout-agnostically.+ expect(out.find((s) => s.id === 'run:import-north').trimmable).toBe(true);+ // A saved trim has no run behind it to re-trim.expect(out.find((s) => s.kind === 'trim').trimmable).toBe(false);});diff --git a/client/src/pages/Sprites.jsx b/client/src/pages/Sprites.jsxindex b5a073e849..59a70c38dc 100644--- a/client/src/pages/Sprites.jsx+++ b/client/src/pages/Sprites.jsx@@ -698,6 +698,7 @@ export default function Sprites() {assets={detail.assets}actions={collectionActions}approvedRunIds={approvedRunIds}+ onDeleted={onWorkflowChanged}/>)}</>diff --git a/client/src/services/apiSprites.js b/client/src/services/apiSprites.jsindex d81803191e..f1e4bc6e83 100644--- a/client/src/services/apiSprites.js+++ b/client/src/services/apiSprites.js@@ -17,6 +17,15 @@ export const updateSpriteRecord = (id, patch, options = {}) => request(`/spritesmethod: 'PATCH', body: JSON.stringify(patch), ...options,});+// Delete one on-disk asset by its record-relative path — an old runtime atlas+// version (PNG + manifest removed together) or a superseded reference /+// candidate render. Refuses the live atlas (409 ATLAS_IN_USE) and the record's+// state index files (409 PROTECTED_STATE_FILE). Returns { deleted, removed }.+export const deleteSpriteAsset = (id, path, options = {}) => request(+ `/sprites/${encodeURIComponent(id)}/assets?path=${encodeURIComponent(path)}`,+ { method: 'DELETE', ...options },+);+// Import approved production assets from a source pipeline checkout.// Returns { results: [...perSubject], totals }.export const importSprites = (body, options = {}) => request('/sprites/import', {diff --git a/scripts/migrations/202-neutral-sprite-run-dirs.js b/scripts/migrations/202-neutral-sprite-run-dirs.jsnew file mode 100644index 0000000000..d37a4ad93d--- /dev/null+++ b/scripts/migrations/202-neutral-sprite-run-dirs.js@@ -0,0 +1,223 @@+/**+ * Rename each sprite character's native animation-run storage from the+ * vendor-named `grok/<runId>/` layout to the vendor-NEUTRAL `runs/<runId>/`+ * layout, and rewrite every path that referenced it.+ *+ * Why:+ * PortOS's own walk generations were stored under `data/sprites/<id>/grok/`+ * — baking one provider (grok) into the on-disk contract. As other agent+ * services / generation methods come online, the storage layout must be+ * vendor-neutral: runs live under `runs/`, and the provider is recorded as+ * the run record's `provider` field, not encoded in the path. (The importer+ * already used `runs/` for source-pipeline runs; this unifies both.)+ *+ * What moves on disk (per character record):+ *+ * before: after:+ * data/sprites/<id>/ data/sprites/<id>/+ * └── grok/<runId>/… └── runs/<runId>/…+ *+ * What is rewritten (the embedded `grok/…` path strings become `runs/…`):+ * - runs/<runId>/animation-run.json (run records — not sha-pinned)+ * - runs/<runId>/generated/*-manifest.json (postprocess manifests)+ * - walk/<id>-walk-selection-v1.json (per-direction runPath/runManifest)+ * - walk/<id>-walk-set-v1.json (finalized selection copy)+ * - runtime/vN/ atlas manifests (compiled-atlas provenance)+ *+ * Content-sha CASCADE (the delicate part): image-byte shas never change (a+ * frame PNG is byte-identical after a directory move), but the JSON manifests+ * that EMBED paths do change, and several are sha-pinned. So after rewriting we+ * recompute, in dependency order:+ * - each rewritten postprocess manifest → its selection/walk-set entry's+ * `runManifestSha256`+ * - the rewritten selection file → the walk-set's `selectionSha256`+ * - the rewritten walk-set file → the runtime pointer's `walkSetSha256`+ * - the rewritten current atlas manifest → the pointer's `manifestSha256`+ * atlas.js's compile idempotency keys on `walkSetSha256`, so updating the+ * pointer keeps a post-migration recompile a no-op (it never re-reads the+ * immutable atlas PNG, whose bytes are unchanged).+ *+ * NOT touched: imported/redraw records (their paths are `runs/`, `art-source/`,+ * or `imagegen/`, never `grok/`); the atlas PNGs; publications.json (its paths+ * are `runtime/…`, no `grok/`); reference anchors (`reference/…`).+ *+ * Idempotency: gated per record on the presence of a `grok/` directory OR any+ * residual `grok/` string in the selection/walk-set (crash-recovery of a run+ * that moved the dirs but not the strings). A second run finds neither and+ * skips. A move-target collision (`runs/<runId>` already exists) throws for+ * that record — the run is left in `grok/` (still readable via the layout-+ * agnostic reader) and the migration stays PENDING for a retry, mirroring+ * migration 200's per-record aggregate-throw.+ */++import { readdir, readFile, writeFile, rename, rm, mkdir, 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; } };+const writeJson = (abs, obj) => writeFile(abs, `${JSON.stringify(obj, null, 2)}\n`);++// Rewrite a record-relative path VALUE that starts with `grok/`. Only the+// path prefix is matched, so provenance strings that merely CONTAIN "grok"+// (e.g. the run kind `grok-game-animation-frames-run`) are left intact.+const neutralize = (s) => (typeof s === 'string' && s.startsWith(`${LEGACY_DIR}/`) ? `${NEUTRAL_DIR}/${s.slice(LEGACY_DIR.length + 1)}` : s);+const deepNeutralize = (v) => {+ if (typeof v === 'string') return neutralize(v);+ if (Array.isArray(v)) return v.map(deepNeutralize);+ if (v && typeof v === 'object') {+ const out = {};+ for (const k of Object.keys(v)) out[k] = deepNeutralize(v[k]);+ return out;+ }+ return v;+};++// Recursively collect *.json files under `dir` (absolute paths). Missing dir → [].+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;+}++// Rewrite `grok/`→`runs/` in one JSON file, writing only when it changed.+async function neutralizeJsonFile(abs) {+ const obj = await readJson(abs);+ if (!obj) return;+ const neu = deepNeutralize(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 manifest we actually+// moved (a `grok/`-origin entry). Returns whether anything changed.+async function neutralizeDirectionEntries(recDir, directions) {+ let changed = false;+ for (const entry of Object.values(directions || {})) {+ if (!entry || typeof entry !== 'object') continue;+ const movedManifest = typeof entry.runManifest === 'string' && entry.runManifest.startsWith(`${LEGACY_DIR}/`);+ const movedPath = typeof entry.runPath === 'string' && entry.runPath.startsWith(`${LEGACY_DIR}/`);+ if (movedPath) { entry.runPath = neutralize(entry.runPath); changed = true; }+ if (movedManifest) {+ entry.runManifest = neutralize(entry.runManifest);+ // The manifest file was already moved + rewritten, so hash the new bytes.+ entry.runManifestSha256 = await sha256File(join(recDir, entry.runManifest));+ changed = true;+ }+ }+ return changed;+}++async function migrateRecord(recDir, recordId) {+ const grokDir = join(recDir, LEGACY_DIR);+ const runsDir = join(recDir, NEUTRAL_DIR);+ 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');++ const hasGrokDir = await exists(grokDir);+ const selText = await readFile(selAbs, 'utf8').catch(() => '');+ const wsText = await readFile(wsAbs, 'utf8').catch(() => '');+ if (!hasGrokDir && !selText.includes(`${LEGACY_DIR}/`) && !wsText.includes(`${LEGACY_DIR}/`)) {+ return false; // nothing native/grok here (imported/redraw-only, or already migrated)+ }++ // 1. Move every grok/<runId> directory to runs/<runId>. A collision means a+ // runs/<runId> already exists — refuse rather than merge/overwrite.+ if (hasGrokDir) {+ await mkdir(runsDir, { recursive: true });+ for (const entry of await readdir(grokDir, { withFileTypes: true })) {+ if (!entry.isDirectory()) continue;+ const dest = join(runsDir, entry.name);+ if (await exists(dest)) {+ throw new Error(`run dir collision for ${recordId}: ${NEUTRAL_DIR}/${entry.name} already exists — left ${LEGACY_DIR}/${entry.name} in place`);+ }+ await rename(join(grokDir, entry.name), dest);+ }+ await rm(grokDir, { recursive: true, force: true }); // now empty+ }++ // 2. Rewrite every run record + postprocess manifest now under runs/.+ for (const abs of await listJsonFiles(runsDir)) await neutralizeJsonFile(abs);++ // 3. Selection → recompute per-entry runManifestSha256 from the moved manifests.+ const selection = await readJson(selAbs);+ if (selection?.directions) {+ await neutralizeDirectionEntries(recDir, selection.directions);+ await writeJson(selAbs, selection);+ }+ const newSelectionSha = await exists(selAbs) ? await sha256File(selAbs) : null;++ // 4. Walk-set → same per-entry recompute, plus the selection-content sha.+ const walkSet = await readJson(wsAbs);+ if (walkSet) {+ if (walkSet.directions) await neutralizeDirectionEntries(recDir, walkSet.directions);+ if (newSelectionSha && typeof walkSet.selectionSha256 === 'string') walkSet.selectionSha256 = newSelectionSha;+ await writeJson(wsAbs, walkSet);+ }+ const newWalkSetSha = await exists(wsAbs) ? await sha256File(wsAbs) : null;++ // 5. 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(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 = [];+ // Sequential + per-record try/catch: one record's collision must not abort+ // the rest, and an aggregate throw keeps the migration PENDING for retry+ // (the healthy records already migrated become gate no-ops next boot).+ for (const rec of records) {+ if (!rec.isDirectory()) continue;+ try {+ if (await migrateRecord(join(spritesDir, rec.name), rec.name)) {+ migrated++;+ console.log(`🧭 migration 202: sprite ${rec.name} → runs/ layout`);+ }+ } catch (err) {+ failures.push(rec.name);+ console.error(`❌ migration 202 (${rec.name}): ${err.message}`);+ }+ }+ if (failures.length > 0) {+ throw new Error(`migration 202: ${failures.length} sprite record(s) failed to migrate (${failures.join(', ')}) — resolve the collision(s) and reboot to retry; the rest migrated.`);+ }+ return { ok: true, migrated };+ },+};diff --git a/scripts/migrations/202-neutral-sprite-run-dirs.test.js b/scripts/migrations/202-neutral-sprite-run-dirs.test.jsnew file mode 100644index 0000000000..c0299743d4--- /dev/null+++ b/scripts/migrations/202-neutral-sprite-run-dirs.test.js@@ -0,0 +1,229 @@+/**+ * Migration 202 — grok/ → runs/ neutral sprite run storage. Builds a fully+ * compiled character under the legacy grok/ layout and asserts the migration+ * (a) moves the run directories, (b) rewrites every embedded grok/ path, and+ * (c) recomputes the sha CASCADE so the post-migration state is internally+ * consistent (the exact invariant atlas.js's compile idempotency relies on),+ * while leaving image-byte shas and imported/redraw records untouched.+ */++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 './202-neutral-sprite-run-dirs.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-east-abcd1234';++// A self-consistent compiled character under the legacy grok/ layout: run+// record + postprocess manifest + finalized selection/walk-set + a compiled+// atlas version, with every content-sha computed exactly as the live code does.+async function buildGrokCharacter(id) {+ const recDir = join(sprites(), id);+ const runDir = join(recDir, 'grok', RUN_ID);+ const genDir = join(runDir, 'generated');+ await mkdir(join(genDir, 'frames'), { recursive: true });+ await mkdir(join(recDir, 'walk'), { recursive: true });+ await mkdir(join(recDir, 'runtime', 'v1'), { recursive: true });+ await mkdir(join(recDir, 'reference'), { recursive: true });++ // Image bytes (byte-identical after the dir move → their shas must not change).+ const framePng = Buffer.from('frame-pixels');+ const stripPng = Buffer.from('strip-pixels');+ const atlasPng = Buffer.from('atlas-pixels');+ const anchorPng = Buffer.from('anchor-pixels');+ await writeFile(join(genDir, 'frames', '00-left-contact.png'), framePng);+ await writeFile(join(genDir, `${id}-walk-east-strip.png`), stripPng);+ await writeFile(join(recDir, 'runtime', 'v1', `${id}-animation-atlas-v1.png`), atlasPng);+ await writeFile(join(recDir, 'reference', `${id}-east-v1.png`), anchorPng);++ // Postprocess manifest — embeds grok/ frame + strip paths; image shas are real.+ const ppRel = `grok/${RUN_ID}/generated/${id}-walk-east-manifest.json`;+ const ppManifest = {+ schemaVersion: 1,+ kind: 'deterministically-packaged-grok-walk-video',+ characterId: id,+ direction: 'east',+ frameRate: 12,+ frameCount: 8,+ sourceVideoPath: `grok/${RUN_ID}/generated/source-video.mp4`,+ manifestPath: ppRel,+ frames: [{ outputIndex: 0, phase: 'left-contact', path: `grok/${RUN_ID}/generated/frames/00-left-contact.png`, sha256: sha(framePng) }],+ stripPath: `grok/${RUN_ID}/generated/${id}-walk-east-strip.png`,+ stripSha256: sha(stripPng),+ };+ await writeJson(join(genDir, `${id}-walk-east-manifest.json`), ppManifest);+ const ppSha = await shaFile(join(genDir, `${id}-walk-east-manifest.json`));++ await writeJson(join(runDir, 'animation-run.json'), {+ schemaVersion: 1,+ kind: 'grok-game-animation-frames-run',+ id: RUN_ID,+ characterId: id,+ direction: 'east',+ status: 'candidate',+ animationInputPath: `grok/${RUN_ID}/generated/input-anchor-transparent.png`,+ postprocessManifest: ppRel,+ stripPreview: { stripPath: `grok/${RUN_ID}/generated/${id}-walk-east-strip.png`, frameCount: 8 },+ });++ // Selection: east approved, runManifestSha256 pins the postprocess manifest.+ 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: {+ east: { status: 'approved', runId: RUN_ID, runPath: `grok/${RUN_ID}`, runManifest: ppRel, runManifestSha256: ppSha, approvedAt: 't' },+ },+ });+ const selSha = await shaFile(join(recDir, selRel));++ // Walk-set: selectionSha256 pins the selection file.+ 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: selRel,+ selectionSha256: selSha,+ directions: {+ east: { status: 'approved', runId: RUN_ID, runPath: `grok/${RUN_ID}`, runManifest: ppRel, runManifestSha256: ppSha, approvedAt: 't' },+ },+ });+ const wsSha = await shaFile(join(recDir, wsRel));++ // Compiled atlas manifest: embeds grok/ provenance + a reference/ anchor path.+ const atlasManRel = `runtime/v1/${id}-animation-atlas-v1-manifest.json`;+ await writeJson(join(recDir, atlasManRel), {+ schemaVersion: 1,+ kind: 'reviewed-walk-set-runtime-atlas',+ characterId: id,+ version: 1,+ atlasPath: `runtime/v1/${id}-animation-atlas-v1.png`,+ directions: [{ direction: 'east', runManifestPath: ppRel, cells: [+ { column: 'idle', sourcePath: `reference/${id}-east-v1.png` },+ { column: 'left-contact', sourcePath: `grok/${RUN_ID}/generated/frames/00-left-contact.png` },+ ] }],+ });+ const atlasManSha = await shaFile(join(recDir, atlasManRel));++ await writeJson(join(recDir, 'runtime', 'current.json'), {+ schemaVersion: 1,+ kind: 'runtime-atlas-selection',+ characterId: id,+ version: 1,+ atlasPath: `runtime/v1/${id}-animation-atlas-v1.png`,+ atlasSha256: sha(atlasPng),+ manifestPath: atlasManRel,+ manifestSha256: atlasManSha,+ walkSetSha256: wsSha,+ });+ return { recDir, framePng, stripPng, atlasPng };+}++beforeEach(() => { ROOT = mkdtempSync(join(tmpdir(), 'mig-202-')); });+afterEach(() => rmSync(ROOT, { recursive: true, force: true }));++describe('migration 202 — grok/ → runs/ neutral sprite run dirs', () => {+ it('moves run dirs, rewrites every grok/ path, and keeps the sha cascade consistent', async () => {+ const id = 'walker-one';+ const { recDir, framePng, atlasPng } = await buildGrokCharacter(id);++ const res = await migration.up({ rootDir: ROOT });+ expect(res).toMatchObject({ ok: true, migrated: 1 });++ // 1. Directory moved.+ expect(await exists(join(recDir, 'grok'))).toBe(false);+ expect(await exists(join(recDir, 'runs', RUN_ID, 'animation-run.json'))).toBe(true);+ expect(await exists(join(recDir, 'runs', RUN_ID, 'generated', 'frames', '00-left-contact.png'))).toBe(true);++ // 2. No grok/ path survives anywhere in the JSON.+ const runRec = await readJson(join(recDir, 'runs', RUN_ID, 'animation-run.json'));+ expect(runRec.postprocessManifest).toBe(`runs/${RUN_ID}/generated/${id}-walk-east-manifest.json`);+ expect(runRec.stripPreview.stripPath).toBe(`runs/${RUN_ID}/generated/${id}-walk-east-strip.png`);++ const pp = await readJson(join(recDir, 'runs', RUN_ID, 'generated', `${id}-walk-east-manifest.json`));+ expect(pp.stripPath).toBe(`runs/${RUN_ID}/generated/${id}-walk-east-strip.png`);+ expect(pp.frames[0].path).toBe(`runs/${RUN_ID}/generated/frames/00-left-contact.png`);+ // Image-byte sha is preserved (the migration never re-hashes moved pixels).+ expect(pp.frames[0].sha256).toBe(sha(framePng));++ // 3. The content-sha cascade is internally consistent post-migration.+ const selAbs = join(recDir, 'walk', `${id}-walk-selection-v1.json`);+ const wsAbs = join(recDir, 'walk', `${id}-walk-set-v1.json`);+ const ptrAbs = join(recDir, 'runtime', 'current.json');+ const sel = await readJson(selAbs);+ const ws = await readJson(wsAbs);+ const ptr = await readJson(ptrAbs);+ expect(sel.directions.east.runPath).toBe(`runs/${RUN_ID}`);+ expect(sel.directions.east.runManifestSha256).toBe(await shaFile(join(recDir, 'runs', RUN_ID, 'generated', `${id}-walk-east-manifest.json`)));+ expect(ws.selectionSha256).toBe(await shaFile(selAbs));+ expect(ws.directions.east.runManifest).toBe(`runs/${RUN_ID}/generated/${id}-walk-east-manifest.json`);+ expect(ptr.walkSetSha256).toBe(await shaFile(wsAbs));+ expect(ptr.manifestSha256).toBe(await shaFile(join(recDir, ptr.manifestPath)));+ // Atlas PNG bytes (and its pinned sha) untouched.+ expect(ptr.atlasSha256).toBe(sha(atlasPng));++ // 4. Atlas manifest provenance rewritten; the reference/ anchor left alone.+ const atlasMan = await readJson(join(recDir, ptr.manifestPath));+ expect(atlasMan.directions[0].runManifestPath).toBe(`runs/${RUN_ID}/generated/${id}-walk-east-manifest.json`);+ expect(atlasMan.directions[0].cells[0].sourcePath).toBe(`reference/${id}-east-v1.png`);+ expect(atlasMan.directions[0].cells[1].sourcePath).toBe(`runs/${RUN_ID}/generated/frames/00-left-contact.png`);+ });++ it('is idempotent — a second run changes nothing and does not throw', async () => {+ const id = 'walker-two';+ const { recDir } = await buildGrokCharacter(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'),+ ptr: await readFile(join(recDir, 'runtime', 'current.json'), 'utf8'),+ });+ const before = await snapshot();+ const res = await migration.up({ rootDir: ROOT });+ expect(res).toMatchObject({ ok: true, migrated: 0 }); // gate skips the already-migrated record+ expect(await snapshot()).toEqual(before);+ });++ it('leaves an imported/redraw-only record (no grok/) untouched', async () => {+ const id = 'imported-hero';+ const recDir = join(sprites(), id);+ 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);+ });++ it('refuses a move collision (runs/<runId> already exists) and stays pending', async () => {+ const id = 'walker-collide';+ const { recDir } = await buildGrokCharacter(id);+ // A pre-existing runs/<runId> blocks the move — must not merge/overwrite.+ await mkdir(join(recDir, 'runs', RUN_ID), { recursive: true });+ await writeFile(join(recDir, 'runs', RUN_ID, 'sentinel.txt'), 'do-not-clobber');++ await expect(migration.up({ rootDir: ROOT })).rejects.toThrow(/failed to migrate/);+ // The legacy run is left in place; the sentinel is untouched.+ expect(await exists(join(recDir, 'grok', RUN_ID))).toBe(true);+ expect(await readFile(join(recDir, 'runs', RUN_ID, 'sentinel.txt'), 'utf8')).toBe('do-not-clobber');+ });+});diff --git a/server/lib/validation.js b/server/lib/validation.jsindex da4749b31a..55b3b60f48 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -964,6 +964,13 @@ export const spriteImportRequestSchema = z.object({includeProps: z.boolean().optional(),});+// Delete one on-disk asset by its record-relative `path` (the same value the+// listing and static route use). Shape gate only — confinement, the live-atlas+// refusal, and the per-record write tail are the service's job (assets.js).+export const spriteAssetDeleteSchema = z.object({+ path: z.string().min(1).max(1024),+});+export const spriteRecordUpdateSchema = z.object({name: z.string().min(1).max(200).optional(),// Reclassify an existing record between the noun kinds (#2932). `props` is@@ -1076,11 +1083,23 @@ export const spriteWalkPostprocessSchema = z.object({runId: spriteWalkRunIdSchema,});+// The trimmer targets ANY resolvable run, not just native `walk-<dir>-<hex>`+// generations: an imported run's id is its directory slug, and a redraw run's+// id is a record-relative manifest path. The trim service resolves the id+// against server-owned walk state and only ever dereferences paths the state+// itself recorded (through resolveSpriteAssetPath), so this bounds shape/length+// only — safe charset, no traversal. (Approve/postprocess stay strict because+// they only ever act on native runs.)+const spriteTrimRunIdSchema = z.string().min(1).max(1024)+ .refine((v) => /^[A-Za-z0-9._/-]+$/.test(v) && !v.split('/').includes('..'), {+ message: 'invalid run id',+ });+// Trim geometry (strip path, cell size, frame labels) derives server-side// from the run's packaged manifest — the client only names the run and// which frames stay enabled.export const spriteWalkTrimSchema = z.object({- runId: spriteWalkRunIdSchema,+ runId: spriteTrimRunIdSchema,enabledColumns: z.array(z.number().int().min(0).max(63)).min(2).max(64).refine((cols) => new Set(cols).size === cols.length, { message: 'columns must be unique' }),fps: z.number().int().min(1).max(60).optional(),diff --git a/server/routes/sprites.js b/server/routes/sprites.jsindex fbf3ffa01e..2a04b4da47 100644--- a/server/routes/sprites.js+++ b/server/routes/sprites.js@@ -26,6 +26,7 @@ import {spritePublishBindingSchema,spriteAtlasCompileSchema,spriteAtlasPublishSchema,+ spriteAssetDeleteSchema,} from '../lib/validation.js';import { z } from 'zod';import { optionalUploadFields } from '../lib/multipart.js';@@ -42,6 +43,7 @@ import {import { saveLoopTrim } from '../services/sprites/walkTrims.js';import { compileAtlas, getAtlasState } from '../services/sprites/atlas.js';import { setPublishBinding, publishAtlas } from '../services/sprites/publish.js';+import { deleteSpriteAsset } from '../services/sprites/assets.js';const router = Router();@@ -178,6 +180,15 @@ router.patch('/:id', asyncHandler(async (req, res) => {res.json(await patchSpriteRecord(req.params.id, patch));}));+// Delete one on-disk asset — an old runtime atlas version (PNG + manifest+// removed together) or a superseded reference/candidate render — by its+// record-relative `path`. Refuses the live atlas + the state index files;+// confinement and the per-record write tail live in the service.+router.delete('/:id/assets', asyncHandler(async (req, res) => {+ const { path } = validateRequest(spriteAssetDeleteSchema, req.query);+ res.json(await deleteSpriteAsset(req.params.id, path));+}));+router.delete('/:id', asyncHandler(async (req, res) => {res.json(await deleteRecord(req.params.id));}));diff --git a/server/routes/sprites.test.js b/server/routes/sprites.test.jsindex 0882c527ed..4edaa0073e 100644--- a/server/routes/sprites.test.js+++ b/server/routes/sprites.test.js@@ -42,6 +42,10 @@ vi.mock('../services/sprites/publish.js', () => ({publishAtlas: vi.fn(async () => ({ published: true, publication: { version: 1 } })),}));+vi.mock('../services/sprites/assets.js', () => ({+ deleteSpriteAsset: vi.fn(async (id, path) => ({ deleted: true, removed: path })),+}));+import * as records from '../services/sprites/records.js';import * as importer from '../services/sprites/importer.js';import * as reference from '../services/sprites/reference.js';@@ -49,6 +53,7 @@ import * as walk from '../services/sprites/walk.js';import * as walkTrims from '../services/sprites/walkTrims.js';import * as atlas from '../services/sprites/atlas.js';import * as publish from '../services/sprites/publish.js';+import * as assets from '../services/sprites/assets.js';import { errorMiddleware } from '../lib/errorHandler.js';import spriteRoutes from './sprites.js';@@ -254,6 +259,20 @@ describe('sprites routes', () => {expect(records.deleteRecord).toHaveBeenCalledWith('pioneer');});+ it('DELETE /:id/assets deletes an on-disk asset by record-relative path', async () => {+ const r = await request(app)+ .delete(`/api/sprites/pioneer/assets?path=${encodeURIComponent('runtime/v9/pioneer-animation-atlas-v9.png')}`);+ expect(r.status).toBe(200);+ expect(r.body).toEqual({ deleted: true, removed: 'runtime/v9/pioneer-animation-atlas-v9.png' });+ expect(assets.deleteSpriteAsset).toHaveBeenCalledWith('pioneer', 'runtime/v9/pioneer-animation-atlas-v9.png');+ });++ it('DELETE /:id/assets rejects a missing path at the schema', async () => {+ const r = await request(app).delete('/api/sprites/pioneer/assets');+ expect(r.status).toBe(400);+ expect(assets.deleteSpriteAsset).not.toHaveBeenCalled();+ });+it('GET /:id includes the walk state for characters only', async () => {records.getRecordWithAssets.mockResolvedValueOnce({record: { id: 'pioneer', kind: 'character' }, assets: [],diff --git a/server/services/backup.js b/server/services/backup.jsindex 173a14afbd..c002828da5 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -64,8 +64,8 @@ export const DEFAULT_EXCLUDES = [// Sprite animation-run raw intermediates: 30–96 ffmpeg-extracted PNGs per// run, byte-for-byte regenerable from the archived source video by the// deterministic postprocess (walkPostprocess.js). The source video, packaged- // frames, strips, manifests, and runtime atlases ARE backed up. `grok/` is- // the live layout; `runs/` covers imported legacy runs.+ // frames, strips, manifests, and runtime atlases ARE backed up. `runs/` is+ // the live (vendor-neutral) layout; `grok/` covers pre-migration-202 runs.{ path: '/sprites/*/grok/*/generated/raw/', reason: 'Sprite walk-run raw extracted frames — regenerable from the archived source video', overridable: true },{ path: '/sprites/*/runs/*/generated/raw/', reason: 'Imported sprite-run raw extracted frames — regenerable from the archived source video', overridable: true }// NOTE: legacy file→Postgres migration artifacts (`.imported` / `.bak-NNN`)diff --git a/server/services/spriteWalkVideoHook.js b/server/services/spriteWalkVideoHook.jsindex 5ac5b8a559..faa0e79a7e 100644--- a/server/services/spriteWalkVideoHook.js+++ b/server/services/spriteWalkVideoHook.js@@ -3,7 +3,7 @@** Subscribes to mediaJobEvents and, for each completed VIDEO job carrying* `params.spriteWalk`, copies the finished grok clip into that run's- * `grok/<runId>/generated/source-video.mp4` and runs the deterministic+ * `runs/<runId>/generated/source-video.mp4` and runs the deterministic* postprocess (frame harvest → un-key → cycle select → align → despill →* strip/manifest) server-side — a slow cloud render still packages after the* user navigated away. Runs accumulate as reviewable candidates (nodiff --git a/server/services/sprites/assets.js b/server/services/sprites/assets.jsnew file mode 100644index 0000000000..a73e1d6727--- /dev/null+++ b/server/services/sprites/assets.js@@ -0,0 +1,84 @@+/**+ * Sprites — on-disk asset deletion (#2930 follow-up).+ *+ * As a character is iterated, its runtime/ tree accumulates old atlas versions+ * (`runtime/vN/<id>-animation-atlas-vN.png` + sidecar manifest) and its+ * reference/walk trees accumulate superseded candidate renders. This prunes+ * one asset at a time by the same record-relative `path` the listing and the+ * static route already use.+ *+ * Two things are refused: the record-state index files (the mutable atlas+ * pointer + the append-only publish history — deleting those corrupts the+ * bookkeeping that still points at surviving versions), and the atlas the+ * current pointer selects (deleting the live sheet would strand any published+ * app AND loop compileAtlas's missing-PNG self-heal). Everything else is fair+ * game. A runtime version is deleted as a unit (PNG + manifest together) — a+ * stray manifest whose PNG is gone re-seeds that self-heal path (atlas.js).+ *+ * Runs inside the record's walk write tail so a delete can never interleave+ * with an in-flight compile/approve that reads the same version tree.+ */++import { join, dirname } from 'path';+import { rm } from 'fs/promises';+import { readJSONFile } from '../../lib/fileUtils.js';+import { ServerError } from '../../lib/errorHandler.js';+import {+ spriteDir, resolveSpriteAssetPath, RUNTIME_POINTER_REL, RUNTIME_PUBLICATIONS_REL,+} from './paths.js';+import { withWalkWriteTail } from './walk.js';++// Record bookkeeping, not deletable assets: the mutable current-atlas pointer+// and the append-only publish history. The versioned PNGs/manifests they name+// ARE deletable (that's the whole feature); these indices are not.+const PROTECTED_STATE = new Set([RUNTIME_POINTER_REL, RUNTIME_PUBLICATIONS_REL]);++// A record-relative path inside a runtime atlas version dir → its `runtime/vN`+// prefix, so any file in the version deletes the whole version as one unit.+const RUNTIME_VERSION_MATCH = /^(runtime\/v\d+)(?:\/|$)/;++/** Delete one on-disk asset by its record-relative path. */+export function deleteSpriteAsset(recordId, relPath) {+ return withWalkWriteTail(recordId, () => deleteSpriteAssetImpl(recordId, relPath));+}++async function deleteSpriteAssetImpl(recordId, relPath) {+ const dir = spriteDir(recordId);+ // Confinement first: resolves under the record dir, throws on traversal /+ // absolute paths (paths.js contract). resolveSpriteAssetPath permits the+ // record root itself, so refuse that explicitly — never rm -rf the record.+ const abs = resolveSpriteAssetPath(recordId, relPath);+ if (abs === dir) {+ throw new ServerError('Refusing to delete the record directory', { status: 400, code: 'INVALID_ASSET_PATH' });+ }+ const normalized = relPath.replace(/\\/g, '/').replace(/^\/+|\/+$/g, '');++ if (PROTECTED_STATE.has(normalized)) {+ throw new ServerError(+ 'That file is record state (the atlas pointer / publish history), not a deletable asset.',+ { status: 409, code: 'PROTECTED_STATE_FILE' },+ );+ }++ const versionMatch = normalized.match(RUNTIME_VERSION_MATCH);+ const current = await readJSONFile(join(dir, RUNTIME_POINTER_REL), null);+ if (current) {+ const currentVersionDir = current.atlasPath ? dirname(current.atlasPath) : null;+ const targetsCurrentVersion = Boolean(versionMatch) && versionMatch[1] === currentVersionDir;+ if (targetsCurrentVersion || normalized === current.atlasPath || normalized === current.manifestPath) {+ throw new ServerError(+ 'This is the current runtime atlas — compile or publish a newer version before deleting it.',+ { status: 409, code: 'ATLAS_IN_USE' },+ );+ }+ }++ // A runtime version deletes as a unit (PNG + sidecar manifest); every other+ // asset deletes as the single file requested. `force` swallows ENOENT so a+ // double-click / already-gone file is a no-op success, not a 500.+ const removed = versionMatch ? versionMatch[1] : normalized;+ const removeAbs = versionMatch ? join(dir, versionMatch[1]) : abs;+ await rm(removeAbs, { recursive: true, force: true });+ console.log(`🗑️ sprite asset deleted for ${recordId} → ${removed}`);+ return { deleted: true, removed };+}diff --git a/server/services/sprites/assets.test.js b/server/services/sprites/assets.test.jsnew file mode 100644index 0000000000..1a7a062306--- /dev/null+++ b/server/services/sprites/assets.test.js@@ -0,0 +1,130 @@+/**+ * On-disk asset deletion (#2930 follow-up): prune old runtime atlas versions+ * and superseded reference/candidate renders. Asserts the four guards —+ * confinement (traversal + record root), the state-index refusal, the+ * live-atlas refusal — plus the two delete shapes (a runtime version deletes+ * as a unit; every other asset deletes as the single file) and ENOENT+ * idempotency. assets.js imports the walk.js graph, so the same mocks as+ * atlas.test.js keep the import side-effect-free.+ */++import { describe, it, expect, afterAll } from 'vitest';+import { mkdtempSync, rmSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { mkdir, writeFile, access } from 'fs/promises';+import { vi } from 'vitest';++const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-assets-test-'));++vi.mock('../../lib/fileUtils.js', async (importOriginal) => {+ const actual = await importOriginal();+ Object.assign(actual.PATHS, { data: TEST_ROOT, sprites: join(TEST_ROOT, 'sprites') });+ return actual;+});+vi.mock('../settings.js', () => ({ getSettings: async () => ({ imageGen: { mode: 'codex' } }) }));+vi.mock('../mediaJobQueue/index.js', () => ({+ enqueueJob: () => ({ jobId: 'job-1', position: 0, status: 'queued' }),+ mediaJobEvents: { on: () => {}, off: () => {} },+}));++const { deleteSpriteAsset } = await import('./assets.js');++let seq = 0;+const newId = () => `assets-char-${++seq}`;+const recDir = (id) => join(TEST_ROOT, 'sprites', id);++async function writeFileAt(id, rel, contents = 'x') {+ const abs = join(recDir(id), rel);+ await mkdir(join(abs, '..'), { recursive: true });+ await writeFile(abs, contents);+ return abs;+}++const exists = (abs) => access(abs).then(() => true, () => false);++/** Seed vN with a PNG + sidecar manifest and a current.json pointing at `currentVersion`. */+async function seedRuntime(id, versions, currentVersion) {+ const stem = `${id}-animation-atlas`;+ for (const v of versions) {+ await writeFileAt(id, `runtime/v${v}/${stem}-v${v}.png`, `png-v${v}`);+ await writeFileAt(id, `runtime/v${v}/${stem}-v${v}-manifest.json`, '{}');+ }+ await writeFileAt(id, 'runtime/current.json', JSON.stringify({+ kind: 'runtime-atlas-selection',+ version: currentVersion,+ atlasPath: `runtime/v${currentVersion}/${stem}-v${currentVersion}.png`,+ manifestPath: `runtime/v${currentVersion}/${stem}-v${currentVersion}-manifest.json`,+ }));+}++afterAll(() => rmSync(TEST_ROOT, { recursive: true, force: true }));++describe('deleteSpriteAsset', () => {+ it('deletes a superseded runtime version as a unit (PNG + manifest), leaving the current one', async () => {+ const id = newId();+ await seedRuntime(id, [9, 10], 10);+ const stem = `${id}-animation-atlas`;++ const res = await deleteSpriteAsset(id, `runtime/v9/${stem}-v9.png`);+ expect(res).toMatchObject({ deleted: true, removed: 'runtime/v9' });++ expect(await exists(join(recDir(id), `runtime/v9/${stem}-v9.png`))).toBe(false);+ expect(await exists(join(recDir(id), `runtime/v9/${stem}-v9-manifest.json`))).toBe(false);+ expect(await exists(join(recDir(id), 'runtime/v9'))).toBe(false);+ // Current version and pointer untouched.+ expect(await exists(join(recDir(id), `runtime/v10/${stem}-v10.png`))).toBe(true);+ expect(await exists(join(recDir(id), 'runtime/current.json'))).toBe(true);+ });++ it('refuses to delete the atlas the current pointer selects', async () => {+ const id = newId();+ await seedRuntime(id, [10], 10);+ const stem = `${id}-animation-atlas`;++ await expect(deleteSpriteAsset(id, `runtime/v10/${stem}-v10.png`))+ .rejects.toMatchObject({ code: 'ATLAS_IN_USE', status: 409 });+ // Nothing removed.+ expect(await exists(join(recDir(id), `runtime/v10/${stem}-v10.png`))).toBe(true);+ });++ it('refuses to delete the record state index files', async () => {+ const id = newId();+ await seedRuntime(id, [1], 1);++ for (const rel of ['runtime/current.json', 'runtime/publications.json']) {+ await writeFileAt(id, rel, '{}');+ await expect(deleteSpriteAsset(id, rel))+ .rejects.toMatchObject({ code: 'PROTECTED_STATE_FILE', status: 409 });+ }+ expect(await exists(join(recDir(id), 'runtime/current.json'))).toBe(true);+ });++ it('deletes a single non-versioned asset (a superseded reference candidate)', async () => {+ const id = newId();+ const abs = await writeFileAt(id, 'reference/candidates/main-candidate-v3.png', 'png');+ await writeFileAt(id, 'reference/candidates/main-candidate-v4.png', 'png');++ const res = await deleteSpriteAsset(id, 'reference/candidates/main-candidate-v3.png');+ expect(res).toMatchObject({ deleted: true, removed: 'reference/candidates/main-candidate-v3.png' });+ expect(await exists(abs)).toBe(false);+ // Sibling untouched — a single-file delete never removes the directory.+ expect(await exists(join(recDir(id), 'reference/candidates/main-candidate-v4.png'))).toBe(true);+ });++ it('rejects traversal and the record root', async () => {+ const id = newId();+ await writeFileAt(id, 'reference/main.png', 'png');+ await expect(deleteSpriteAsset(id, '../other/secret.png'))+ .rejects.toMatchObject({ code: 'INVALID_ASSET_PATH' });+ await expect(deleteSpriteAsset(id, '.'))+ .rejects.toMatchObject({ code: 'INVALID_ASSET_PATH' });+ });++ it('is idempotent for an already-gone file (force swallows ENOENT)', async () => {+ const id = newId();+ await mkdir(recDir(id), { recursive: true });+ const res = await deleteSpriteAsset(id, 'reference/never-existed.png');+ expect(res).toMatchObject({ deleted: true });+ });+});diff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.jsindex 1e3bfa8e6f..6865dbe652 100644--- a/server/services/sprites/walk.js+++ b/server/services/sprites/walk.js@@ -8,8 +8,8 @@* optionally loop-trims, and approves per direction; when all 8 directions* are approved the finalized walk-set manifest freezes the set.*- * Disk layout mirrors the source pipeline (and phase 1's importer contract):- * grok/walk-<direction>-<runId8>/animation-run.json + generated/…+ * Disk layout (vendor-neutral runs/ tree; the provider is a run-record field):+ * runs/walk-<direction>-<runId8>/animation-run.json + generated/…* walk/<id>-walk-selection-v1.json, walk/<id>-walk-set-v1.json* walk/trims/<slug>-vNNN-{strip.png,.gif,.json}*@@ -42,7 +42,19 @@ import { GROK_VIDEO_DURATIONS } from '../videoGen/grok.js';const selectionRelPath = (id) => `walk/${id}-walk-selection-v1.json`;// Exported: atlas.js (phase 4) reads the finalized walk set as compile input.export const walkSetRelPath = (id) => `walk/${id}-walk-set-v1.json`;-const runRelPath = (runId) => `grok/${runId}`;+// Native generations store one run per directory under a VENDOR-NEUTRAL `runs/`+// tree — the provider (grok, or a future agent service) is recorded as the run+// record's `provider` field, never encoded in the path. Migration 202 renamed+// the historical `grok/<runId>/` layout into this one; the reader still scans+// `grok/` too (RUN_SCAN_DIRS) for pre-migration installs and forks, and+// RUN_DIR_MATCH (paths.js) still accepts both prefixes.+const runRelPath = (runId) => `runs/${runId}`;+// The two on-disk homes a native candidate run can be found in: the neutral+// `runs/` layout (all new generations, post-migration) and the legacy `grok/`+// layout (a straggler on an un-migrated install/fork). Approved runs resolve+// through their selection entry regardless, so this scan only has to cover+// unapproved candidates.+const RUN_SCAN_DIRS = ['runs', 'grok'];const RUN_RECORD_NAME = 'animation-run.json';// Serialize walk-state read-modify-writes per record (run records, the@@ -92,7 +104,10 @@ async function loadRunRecordAt(recordId, runDirRel) {}async function loadRunRecord(recordId, runId) {- return loadRunRecordAt(recordId, runRelPath(runId));+ // Prefer the neutral runs/ layout; fall back to legacy grok/ so approve /+ // rerun / attach still resolve a candidate on an un-migrated install or fork.+ return (await loadRunRecordAt(recordId, `runs/${runId}`))+ || loadRunRecordAt(recordId, `grok/${runId}`);}async function saveRunRecord(recordId, run) {@@ -222,8 +237,8 @@ async function loadRedrawRun(recordId, direction, entry) {* fourth layout means another branch here, not another append-and-dedupe* block in `getWalkState`:*- * grok/<run-id>/ → PortOS's own generations (animation-run.json)- * runs/<run-id>/ → the source-pipeline importer's layout (same record)+ * runs/<run-id>/ → PortOS's own generations + the importer's layout+ * grok/<run-id>/ → legacy native generations (pre-migration-202 / forks)* anything else → an imagegen/vN redraw manifest (#2924), synthesized** Every branch returns the same run-shaped object, so routes and the client@@ -249,15 +264,21 @@ async function loadRunForEntry(recordId, direction, entry) {** The selection (or the finalized walk set) is the index: each approved* direction resolves through `loadRunForEntry`, whatever layout it names.- * The `grok/` directory scan then only has to cover runs that have NO+ * The directory scan (RUN_SCAN_DIRS) then only has to cover runs that have NO* selection entry by definition — unapproved candidates and in-flight- * generations, which PortOS always writes under `grok/`.+ * generations, which PortOS writes under the neutral `runs/` tree.*/export async function getWalkState(recordId) {// The scan is independent of the index — start it first so the two reads- // overlap, as they did when the scan WAS the entry point.- const scanPromise = readdir(join(spriteDir(recordId), 'grok'), { withFileTypes: true })- .catch(() => []); // no native runs yet+ // overlap, as they did when the scan WAS the entry point. Scan both the+ // neutral runs/ tree and the legacy grok/ tree, remembering each entry's+ // parent so the run loads from where it actually lives (a name could only+ // appear in one post-migration, but a fork/un-migrated install may still+ // have grok/).+ const scanPromise = Promise.all(RUN_SCAN_DIRS.map((base) => readdir(join(spriteDir(recordId), base), { withFileTypes: true })+ .then((entries) => entries.filter((e) => e.isDirectory() && e.name.startsWith('walk-')).map((e) => ({ base, name: e.name })))+ .catch(() => []))) // dir absent → no runs there yet+ .then((lists) => lists.flat());const [selection, walkSet] = await Promise.all([loadSelection(recordId), loadWalkSet(recordId)]);const approvedDirections = walkSet?.directions || selection?.directions || {};@@ -281,13 +302,17 @@ export async function getWalkState(recordId) {const scannedRuns = (await Promise.all((await scanPromise)- .filter((e) => e.isDirectory() && e.name.startsWith('walk-') && !resolvedRunIds.has(e.name))- .map((e) => loadRunRecord(recordId, e.name)- .then((run) => (run ? normalizeRunRecord(recordId, run, runRelPath(e.name)) : null))),+ .filter(({ name }) => !resolvedRunIds.has(name))+ .map(({ base, name }) => {+ const runDirRel = `${base}/${name}`;+ return loadRunRecordAt(recordId, runDirRel)+ .then((run) => (run ? normalizeRunRecord(recordId, run, runDirRel) : null));+ }),)).filter(Boolean)// Second pass: a record whose own `id` differs from its directory name is- // already covered by an entry that named it by id.- .filter((run) => !resolvedRunIds.has(run.id));+ // already covered by an entry that named it by id. Dedupe on id too, so a+ // run that somehow exists under both scan roots surfaces once.+ .filter((run, i, all) => !resolvedRunIds.has(run.id) && all.findIndex((r) => r.id === run.id) === i);const allRuns = [...entryRuns, ...scannedRuns].sort((a, b) => runCreatedAtMs(b.createdAt) - runCreatedAtMs(a.createdAt));@@ -346,6 +371,9 @@ async function startWalkGenerationImpl(recordId, body) {const run = {schemaVersion: 1,kind: 'grok-game-animation-frames-run',+ // Vendor recorded as metadata, not baked into the storage path — a future+ // non-grok source stamps its own provider and stores under the same runs/ tree.+ provider: 'grok',status: 'queued',id: runId,jobId: null,@@ -513,7 +541,7 @@ export function approveWalkDirection(recordId, args) {* deliberate way back to the editable state (#2933 follow-up): it removes the* frozen walk-set file and resets the per-direction selection to in-progress,* so every direction returns to the generate/regenerate/approve flow with its- * already-rendered clips preserved on disk (the `grok/<runId>/` run records are+ * already-rendered clips preserved on disk (the `runs/<runId>/` run records are* never touched). Re-approving all 8 directions re-freezes the set exactly as* the original finalize did. The record status drops back to* `reference-complete` (all anchors locked, walk in progress).diff --git a/server/services/sprites/walk.test.js b/server/services/sprites/walk.test.jsindex 3f2cf1340e..7af86aa5aa 100644--- a/server/services/sprites/walk.test.js+++ b/server/services/sprites/walk.test.js@@ -85,7 +85,7 @@ async function characterWithLockedAnchors(id, directions = ['east']) {async function makeCandidateRun(recordId, direction, { stripBytes = `strip-${direction}` } = {}) {const runId = `walk-${direction}-${(seq++).toString(16).padStart(8, '0')}`;- const runDir = join(TEST_ROOT, 'sprites', recordId, 'grok', runId, 'generated');+ 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);@@ -96,12 +96,12 @@ async function makeCandidateRun(recordId, direction, { stripBytes = `strip-${dirdirection,frameRate: 12,frameCount: 8,- stripPath: `grok/${runId}/generated/${stripName}`,+ stripPath: `runs/${runId}/generated/${stripName}`,stripSha256: sha256(Buffer.from(stripBytes)),};- const manifestRel = `grok/${runId}/generated/${recordId}-walk-${direction}-manifest.json`;+ const manifestRel = `runs/${runId}/generated/${recordId}-walk-${direction}-manifest.json`;await writeFile(join(runDir, `${recordId}-walk-${direction}-manifest.json`), JSON.stringify(packaged));- await writeFile(join(TEST_ROOT, 'sprites', recordId, 'grok', runId, 'animation-run.json'), JSON.stringify({+ await writeFile(join(TEST_ROOT, 'sprites', recordId, 'runs', runId, 'animation-run.json'), JSON.stringify({schemaVersion: 1,kind: 'grok-game-animation-frames-run',status: 'candidate',@@ -145,7 +145,7 @@ describe('startWalkGeneration', () => {expect(call.params.videoMode).toBe('image');expect(call.params.grokPath).toBe('/usr/local/bin/grok');expect(call.params.sourceImagePath).toBe(- join(TEST_ROOT, 'sprites', id, 'grok', result.runId, 'generated', 'input-anchor-transparent.png'),+ join(TEST_ROOT, 'sprites', id, 'runs', result.runId, 'generated', 'input-anchor-transparent.png'),);expect(call.params.prompt).toContain('walking east');expect(call.params.prompt).toContain('magenta (#FF00FF)');@@ -187,13 +187,13 @@ describe('attachWalkVideo (completion hook)', () => {expect(result).toEqual({ runId, status: 'candidate' });expect(runWalkPostprocess).toHaveBeenCalledOnce();const ppArgs = runWalkPostprocess.mock.calls[0][0];- expect(ppArgs).toMatchObject({ recordId: id, direction: 'east', chromaKey: '#FF00FF', runRel: `grok/${runId}` });- const video = await readFile(join(TEST_ROOT, 'sprites', id, 'grok', runId, 'generated', 'source-video.mp4'), 'utf8');+ expect(ppArgs).toMatchObject({ recordId: id, direction: 'east', chromaKey: '#FF00FF', runRel: `runs/${runId}` });+ const video = await readFile(join(TEST_ROOT, 'sprites', id, 'runs', runId, 'generated', 'source-video.mp4'), 'utf8');expect(video).toBe('fake-mp4-bytes');const { runs } = await getWalkState(id);expect(runs[0]).toMatchObject({status: 'candidate',- postprocessManifest: `grok/${runId}/generated/manifest.json`,+ postprocessManifest: `runs/${runId}/generated/manifest.json`,});expect(runs[0].stripPreview.frameCount).toBe(8);expect(runs[0].sourceVideoSha256).toBe(sha256(Buffer.from('fake-mp4-bytes')));@@ -266,14 +266,14 @@ describe('rerunWalkPostprocess', () => {it('re-packages a landed video and 409s an approved run', async () => {const id = await characterWithLockedAnchors(newId(), ['east']);const { runId } = await startWalkGeneration(id, { direction: 'east' });- const videoAbs = join(TEST_ROOT, 'sprites', id, 'grok', runId, 'generated', 'source-video.mp4');+ const videoAbs = join(TEST_ROOT, 'sprites', id, 'runs', runId, 'generated', 'source-video.mp4');await writeFile(videoAbs, 'landed');const run = await rerunWalkPostprocess(id, { runId });expect(run.status).toBe('candidate');// Approve it (needs a packaged manifest + strip on disk), then rerun 409s.const { runId: approvedRun } = await makeCandidateRun(id, 'east');- await writeFile(join(TEST_ROOT, 'sprites', id, 'grok', approvedRun, 'generated', 'source-video.mp4'), 'landed');+ await writeFile(join(TEST_ROOT, 'sprites', id, 'runs', approvedRun, 'generated', 'source-video.mp4'), 'landed');await approveWalkDirection(id, { direction: 'east', runId: approvedRun });await expect(rerunWalkPostprocess(id, { runId: approvedRun })).rejects.toMatchObject({ code: 'RUN_APPROVED' });@@ -297,7 +297,7 @@ describe('approveWalkDirection', () => {const id = await characterWithLockedAnchors(newId(), ['east']);const { runId } = await makeCandidateRun(id, 'east');await writeFile(- join(TEST_ROOT, 'sprites', id, 'grok', runId, 'generated', `${id}-walk-east-strip.png`),+ join(TEST_ROOT, 'sprites', id, 'runs', runId, 'generated', `${id}-walk-east-strip.png`),'tampered',);await expect(approveWalkDirection(id, { direction: 'east', runId }))@@ -311,7 +311,7 @@ describe('approveWalkDirection', () => {expect(state.selection.kind).toBe('reviewed-directional-walk-selection');expect(state.selection.status).toBe('in-progress');expect(state.selection.directions.east).toMatchObject({- status: 'approved', runId, runPath: `grok/${runId}`, runManifest: manifestRel,+ status: 'approved', runId, runPath: `runs/${runId}`, runManifest: manifestRel,});expect(state.selection.directions.east.runManifestSha256).toMatch(/^[0-9a-f]{64}$/);expect(state.walkSet).toBeNull();diff --git a/server/services/sprites/walkPostprocess.js b/server/services/sprites/walkPostprocess.jsindex 7a22376f29..ea620c7a8f 100644--- a/server/services/sprites/walkPostprocess.js+++ b/server/services/sprites/walkPostprocess.js@@ -590,7 +590,7 @@ export async function prepareWalkAnchorInput(anchorAbs, destAbs, chromaKey) {/*** The full deterministic postprocess for one completed walk video.*- * `runRel` is the record-relative run root (`grok/walk-<dir>-<jobId>`); all+ * `runRel` is the record-relative run root (`runs/walk-<dir>-<jobId>`); all* artifacts are written under `<runAbs>/generated/` and all manifest paths* are record-relative, matching what the phase-1 importer expects.*/diff --git a/server/services/sprites/walkTrims.js b/server/services/sprites/walkTrims.jsindex 32f433175b..1b8715446f 100644--- a/server/services/sprites/walkTrims.js+++ b/server/services/sprites/walkTrims.js@@ -23,13 +23,13 @@ import {} from '../../lib/fileUtils.js';import { findFfmpeg, runFfmpegProcess } from '../../lib/ffmpeg.js';import { ServerError } from '../../lib/errorHandler.js';-import { spriteDir, resolveSpriteAssetPath } from './paths.js';+import { resolveSpriteAssetPath, spriteDir } from './paths.js';import { requireCharacter } from './reference.js';-import { withWalkWriteTail } from './walk.js';+import { withWalkWriteTail, getWalkState } from './walk.js';+import { WALK_FPS } from './walkPostprocess.js';const TRIMS_DIR = 'walk/trims';const MAX_TRIM_VERSION = 999;-const RUN_RECORD_NAME = 'animation-run.json';// First free -vNNN triple (strip + gif + json all absent), matching the// source's next_trim_prefix scan.@@ -79,31 +79,73 @@ export function saveLoopTrim(recordId, payload) {return withWalkWriteTail(recordId, () => saveLoopTrimImpl(recordId, payload));}-async function saveLoopTrimImpl(recordId, payload) {- await requireCharacter(recordId);- const { runId, enabledColumns } = payload;- const run = await readJSONFile(join(spriteDir(recordId), 'grok', runId, RUN_RECORD_NAME), null);+/**+ * Normalize a run — whatever its on-disk layout — into the geometry the trim+ * re-pack needs: `{ direction, stripPath, cellSize, allColumns, phaseByColumn,+ * defaultFps }`. The run is resolved through the single layout-agnostic+ * resolver (`getWalkState`), so a native run (`runs/`, or legacy `grok/`), an+ * imported run, and an imagegen redraw run all trim through one path — no+ * vendor directory is assumed. A native packaged run derives its geometry from+ * the authoritative postprocess manifest (per-column gait-phase labels);+ * anything else derives it from the run's own `stripPreview` (a packed row of+ * `frameCount` square cells) and labels columns numerically.+ */+async function resolveTrimSource(recordId, runId) {+ const state = await getWalkState(recordId);+ 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) {++ if (run.postprocessManifest) {+ const packaged = await readJSONFile(resolveSpriteAssetPath(recordId, run.postprocessManifest), null);+ if (!packaged?.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,+ cellSize: packaged.alignment.cellSize,+ allColumns: packaged.frames.map((f) => f.outputIndex),+ phaseByColumn: Object.fromEntries(packaged.frames.map((f) => [f.outputIndex, f.phase])),+ defaultFps: packaged.frameRate,+ };+ }++ const sp = run.stripPreview;+ const cellSize = Number(sp?.cellHeight) || Number(sp?.cellWidth);+ const frameCount = Number(sp?.frameCount);+ if (!sp?.stripPath || !Number.isInteger(frameCount) || frameCount < 2 || !(cellSize > 0)) {throw new ServerError('Run has no packaged candidate to trim', { status: 409, code: 'RUN_NOT_CANDIDATE' });}- const packaged = await readJSONFile(resolveSpriteAssetPath(recordId, run.postprocessManifest), null);- if (!packaged?.stripPath || !packaged.alignment?.cellSize || !Array.isArray(packaged.frames)) {- throw new ServerError('Packaged run manifest is missing or inconsistent', { status: 409, code: 'RUN_MANIFEST_INVALID' });+ // The re-pack crops square cells; a non-square-celled strip isn't trimmable.+ if (sp.cellWidth && sp.cellHeight && Number(sp.cellWidth) !== Number(sp.cellHeight)) {+ throw new ServerError('Non-square strip cells are not trimmable', { status: 409, code: 'RUN_STRIP_INVALID' });}- const cellSize = packaged.alignment.cellSize;- const allColumns = packaged.frames.map((f) => f.outputIndex);+ return {+ direction: run.direction,+ stripPath: sp.stripPath,+ cellSize,+ allColumns: Array.from({ length: frameCount }, (_, i) => i),+ phaseByColumn: {},+ defaultFps: Number(sp.fps) > 0 ? Number(sp.fps) : WALK_FPS,+ };+}++async function saveLoopTrimImpl(recordId, payload) {+ await requireCharacter(recordId);+ const { runId, enabledColumns } = payload;+ const source = await resolveTrimSource(recordId, runId);+ const { stripPath, cellSize, allColumns, phaseByColumn } = source;const invalid = enabledColumns.filter((c) => !allColumns.includes(c));if (invalid.length) {throw new ServerError(`Enabled frames not in the packed strip: ${invalid.join(', ')}`, { status: 400, code: 'TRIM_COLUMNS_INVALID' });}const enabled = [...enabledColumns].sort((a, b) => a - b);- const fps = payload.fps ?? packaged.frameRate;- const slug = payload.slug || `${run.direction}-loop`;+ const fps = payload.fps ?? source.defaultFps;+ const slug = payload.slug || `${source.direction}-loop`;- const atlasAbs = resolveSpriteAssetPath(recordId, packaged.stripPath);+ const atlasAbs = resolveSpriteAssetPath(recordId, stripPath);if (!await pathExists(atlasAbs)) {- throw new ServerError(`Packed strip not found: ${packaged.stripPath}`, { status: 404, code: 'ATLAS_NOT_FOUND' });+ throw new ServerError(`Packed strip not found: ${stripPath}`, { status: 404, code: 'ATLAS_NOT_FOUND' });}const { data, info } = await sharp(atlasAbs).ensureAlpha().raw().toBuffer({ resolveWithObject: true });if ((Math.max(...allColumns) + 1) * cellSize > info.width || cellSize > info.height) {@@ -144,13 +186,12 @@ async function saveLoopTrimImpl(recordId, payload) {const gifName = `${prefix}.gif`;await encodeTrimGif(frames, fps, join(trimsAbs, gifName));- const phaseByColumn = Object.fromEntries(packaged.frames.map((f) => [f.outputIndex, f.phase]));const manifest = {schemaVersion: 1,kind: 'animation-loop-trim',status: 'candidate',runId,- sourceAtlasPath: packaged.stripPath,+ sourceAtlasPath: stripPath,sourceAtlasSha256: await sha256File(atlasAbs),row: 0,cellWidth: cellSize,diff --git a/server/services/sprites/walkTrims.test.js b/server/services/sprites/walkTrims.test.jsindex 65794c9d0a..9f7a540883 100644--- a/server/services/sprites/walkTrims.test.js+++ b/server/services/sprites/walkTrims.test.js@@ -75,6 +75,40 @@ async function characterWithRun(id) {return id;}+// An imagegen redraw run (source pipeline's video-first path): a real packed+// strip under imagegen/vN plus a redraw manifest and an approved selection+// entry — no grok/ run record. getWalkState synthesizes the run from these.+const REDRAW_CELL = 8;+const REDRAW_COLORS = [+ [255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255],+ [255, 255, 0, 255], [255, 0, 255, 255], [0, 255, 255, 255],+];+async function characterWithRedrawRun(id, { frameCount = 6 } = {}) {+ await records.createRecord({ kind: 'character', name: 'Redraw' }, id);+ const width = REDRAW_CELL * frameCount;+ const buf = Buffer.alloc(width * REDRAW_CELL * 4);+ for (let y = 0; y < REDRAW_CELL; y++) {+ for (let x = 0; x < width; x++) {+ buf.set(REDRAW_COLORS[Math.floor(x / REDRAW_CELL)], (y * width + x) * 4);+ }+ }+ const igDir = join(TEST_ROOT, 'sprites', id, 'imagegen', 'v1');+ await mkdir(igDir, { recursive: true });+ await sharp(buf, { raw: { width, height: REDRAW_CELL, channels: 4 } }).png()+ .toFile(join(igDir, 'clean-alpha.png'));+ const manifestRel = 'imagegen/v1/redraw-manifest.json';+ await writeFile(join(TEST_ROOT, 'sprites', id, manifestRel), JSON.stringify({+ schemaVersion: 1, characterId: id, direction: 'east', cellSize: REDRAW_CELL,+ cycle: { frameCount, referenceFps: 10, stripAlpha: 'imagegen/v1/clean-alpha.png' },+ }));+ await mkdir(join(TEST_ROOT, 'sprites', id, 'walk'), { recursive: true });+ await writeFile(join(TEST_ROOT, 'sprites', id, 'walk', `${id}-walk-selection-v1.json`), JSON.stringify({+ schemaVersion: 1, kind: 'reviewed-directional-walk-selection', characterId: id, status: 'in-progress',+ directions: { east: { status: 'approved', runId: `${id}-redraw-east`, runManifest: manifestRel, approvedAt: 'v1' } },+ }));+ return `${id}-redraw-east`;+}+beforeEach(() => {runFfmpegProcess.mockClear();rmSync(join(TEST_ROOT, 'sprite-records.json'), { force: true });@@ -136,6 +170,40 @@ describe('saveLoopTrim', () => {expect(third.strip).toBe('walk/trims/east-loop-v002-strip.png');});+ // The whole point of the vendor-neutral trim path: a direction whose art came+ // from the source pipeline's imagegen redraw (e.g. pioneer's east) has no+ // grok/ run behind it, yet its packed strip is trimmable all the same —+ // geometry now comes from the run's stripPreview, resolved layout-agnostically.+ it('trims an imagegen-redraw run resolved by stripPreview (no grok/ dir)', async () => {+ const id = newId();+ const runId = await characterWithRedrawRun(id, { frameCount: 6 });++ const result = await saveLoopTrim(id, { runId, enabledColumns: [0, 2, 4] });+ expect(result).toMatchObject({+ strip: 'walk/trims/east-loop-v001-strip.png',+ frameCount: 3,+ disabledFrameCount: 3,+ });+ const { data, info } = await sharp(join(TEST_ROOT, 'sprites', id, result.strip))+ .raw().toBuffer({ resolveWithObject: true });+ expect(info.width).toBe(REDRAW_CELL * 3);+ const px = (x) => [...data.subarray(x * 4, x * 4 + 4)];+ expect(px(0)).toEqual(REDRAW_COLORS[0]); // column 0+ expect(px(REDRAW_CELL)).toEqual(REDRAW_COLORS[2]); // column 2+ expect(px(REDRAW_CELL * 2)).toEqual(REDRAW_COLORS[4]); // column 4++ const manifest = JSON.parse(await readFile(join(TEST_ROOT, 'sprites', id, result.manifest), 'utf8'));+ expect(manifest).toMatchObject({+ runId, // the redraw run id round-trips (not a walk-<dir>-<hex> shape)+ sourceAtlasPath: 'imagegen/v1/clean-alpha.png',+ fps: 10, // from the redraw cycle's referenceFps+ allAtlasColumns: [0, 1, 2, 3, 4, 5],+ enabledAtlasColumns: [0, 2, 4],+ });+ // No named gait phases on a redraw cycle → columns label numerically.+ expect(manifest.selectedFrames.map((f) => f.sourceFrameLabel)).toEqual(['0', '2', '4']);+ });+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] }))