Skip to content

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

feat([issue-2993]): gate imported walk re-derive on the clip, not the import label

[._.]/ Adam Eivya4e4c44c47f1
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 5f93b91f0e..06801eb38b 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -25,6 +25,7 @@
## Sprite Manager
+- **[issue-2993] Imported characters can finally be re-derived — smoother walks, and an atlas you can compile here** — a character brought over from a source art pipeline was frozen the moment it arrived: Unlock, Reopen and Compile all refused it outright, so an imported 8-frame walk could never be brought up to 12 and its atlas could only ever be re-published, never rebuilt. That refusal was written when the import genuinely left nothing behind to work from — but the importer now copies each direction's source clip, so it had become a lie. Those actions are now gated on whether the clip is actually there: a direction with its clip on disk reopens and reprocesses at any frame count and speed, with no new render and no new spend, and the buttons appear instead of being hidden. A direction with no clip is still refused, but now says so plainly and tells you to re-import the character. Compiling is likewise per-direction: the atlas names the directions still packaged by the source pipeline instead of refusing the whole set, so an imported character becomes compilable one direction at a time as you re-derive them — and approving a direction whose packaged frames were never imported is now caught up front, rather than surfacing much later as an unexplained compile error.
- **[issue-2996] A character you'd started but not locked now begins at the turnaround sheet too** — when turnaround sheets landed, characters already in progress kept the old flow: they'd still ask for a main reference first, and only pick up sheets afterward. Now a character that hasn't frozen anything yet simply starts at step 1 like a new one — nothing of yours is lost, because nothing was locked. Characters that *have* frozen a main reference are untouched: their locked artwork stays exactly as it is, and they still backfill a sheet from it. Uploading a design image is now accepted only on the turnaround step, since that's the render it actually seeds — the main reference and every anchor are drawn from the sheet, so attaching a separate image to them has nowhere to go and is rejected with a clear message.
- **[issue-2982] Publishing an atlas your game can't read now stops instead of silently breaking it** — the atlas PNG used to be the *entire* export: nothing described how many walk frames were in it, so a game with an 8-frame walk baked in as a constant would happily accept a 12-frame publish and then draw the wrong frames from the wrong columns forever, with no crash and no log. Two things fix that. A publish target can now declare the grid it was built against (`runtimeContract`: walk frame count, cell size, column count), and a publish whose compiled atlas disagrees is refused with a message naming both numbers — "Atlas has 14 columns (12 walk frames) but Example App expects 10 (8 walk frames)" — plus the two ways to resolve it. And every publish now writes a small `….layout.json` file beside the atlas describing the grid PortOS actually produced: cell size, ordered column names, per-track column spans (so a future multi-frame scanner or ambient action is additive, not a rewrite), row order, and the atlas checksum — so the game can resolve columns by name and verify what it loaded instead of trusting a constant. Targets with no declared contract publish exactly as before. Also documented: playback **fps in PortOS is preview-only**. It ships in the sidecar labeled as authoring metadata, because the consuming game drives its walk from movement distance and has no frame-rate concept at all — a 6 fps preview and a 24 fps preview export byte-identical atlases. See `docs/features/sprite-export-contract.md`.
- **[issue-2986] Compiled atlases no longer waste a column on a duplicate of the idle pose** — every atlas used to end with an extra "scanner" column that was a pixel-for-pixel copy of the idle cell, left over from an early render and never drawn by anything. It's gone: an 8-frame walk now compiles to 9 columns instead of 10, and a 12-frame walk to 13 instead of 14 — a smaller sprite sheet with nothing lost. The `layout.json` file published beside the atlas drops the matching entry, so it keeps describing exactly what's in the image. Atlases you already published are untouched until you republish, and imported or previously compiled sheets that still carry the column keep loading and displaying normally. Recompiling a character produces a new atlas version, as any change does. (A real scanner *action*, when there is one, will be its own animation track with its own frame count rather than a column bolted onto the walk cycle.)
diff --git a/client/src/components/sprites/PublishWorkflow.jsx b/client/src/components/sprites/PublishWorkflow.jsx
index 6d4991413a..b268af71d5 100644
--- a/client/src/components/sprites/PublishWorkflow.jsx
+++ b/client/src/components/sprites/PublishWorkflow.jsx
@@ -101,19 +101,23 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {
if (!finalized) return null;
- // Phase-1 imported walk sets carry source-pipeline paths and no packaged
- // frames — the server refuses to recompile them (LEGACY_IMPORTED_WALK_SET).
- // Show why instead of offering a button that always fails.
- if (walk.walkSet.selectionPath?.includes('art-source/sprites/')) {
+ // A direction still packaged by the source pipeline has no per-frame images
+ // here, so the server refuses to compile from it (LEGACY_IMPORTED_WALK_SET).
+ // Show why instead of offering a button that always fails. Read the
+ // server-stamped flag rather than re-deriving the path convention: it is
+ // per-direction, so it clears on its own as each direction is re-derived from
+ // its imported clip — which is what makes an imported set compilable at all.
+ if (walk.walkSet.imported) {
return (
<div className="bg-port-card border border-port-border rounded-lg p-4 space-y-1">
<h3 className="text-sm font-medium text-gray-200 flex items-center gap-2">
<Package size={16} className="text-port-accent" /> Runtime Atlas
</h3>
<p className="text-xs text-gray-500">
- This walk set was imported from the source pipeline, which kept its packaged frames —
- PortOS cannot recompile it. The imported runtime atlases remain in the asset library
- below; to compile and publish from PortOS, run the walk workflow on a new character.
+ Some directions are still packaged by the source pipeline, which kept their per-frame
+ images — PortOS cannot compile from those. Reopen each one above and reprocess it from
+ its imported clip to re-derive the frames here, then compile. The imported runtime
+ atlases remain in the asset library below.
</p>
</div>
);
diff --git a/client/src/components/sprites/WalkWorkflow.jsx b/client/src/components/sprites/WalkWorkflow.jsx
index a5df098c60..0c7808aa4e 100644
--- a/client/src/components/sprites/WalkWorkflow.jsx
+++ b/client/src/components/sprites/WalkWorkflow.jsx
@@ -145,15 +145,18 @@ function StripLoop({ recordId, stripPreview }) {
// behind it. Named rather than inlined as a nested ternary so the three cases
// read as the decision they are.
const driftRemedy = ({ approved, hasSourceClip, imported }) => {
- // A source-pipeline import has no regenerable clips, so the server refuses
- // BOTH reopen and unlock on it — pointing there would advise an action that
- // always 409s, and imported sets are the population most likely to drift
- // (they never passed the queue-time gate).
- if (imported) return 'create a new character version to revise it';
- if (approved) return 'reopen this direction to re-derive it';
- return hasSourceClip
- ? 'reprocess it from its clip'
- : 'import this direction\'s source clip to re-derive it';
+ // Evidence, not provenance: the server gates re-derivation on whether the
+ // direction's clip is actually on disk, so an imported direction whose clip
+ // came across re-derives exactly like a native one. Only a direction with no
+ // clip behind it is a dead end — and for an import the fix is re-importing the
+ // character, not authoring a new version by hand.
+ if (!hasSourceClip) {
+ return imported
+ ? 're-import this character to bring its source clip across'
+ : 'import this direction\'s source clip to re-derive it';
+ }
+ if (approved) return 'reopen this direction to re-derive it from its clip';
+ return 'reprocess it from its clip';
};
/**
@@ -257,6 +260,11 @@ function DirectionCard({
// 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);
+ // Whether this direction can be re-derived without a new render: the server
+ // resolves `sourceVideoPath` against disk and flags `sourceClipMissing` when
+ // the clip the record names isn't there, so declaring a clip and having one
+ // never read the same. Every reopen/reprocess affordance below gates on this.
+ const hasSourceClip = Boolean(run?.sourceVideoPath) && !run?.sourceClipMissing;
const statusLabel = approved ? 'approved'
: (pending || rendering) ? 'rendering…'
: run?.status === 'postprocessing' ? 'packaging…'
@@ -287,7 +295,7 @@ function DirectionCard({
{[drift.frameCountDrifts && `${drift.frameCount}f`, drift.fpsDrifts && `${drift.fps}fps`]
.filter(Boolean).join(' · ')} · re-derive to {cycleLabel}
<span className="block text-gray-400">
- {driftRemedy({ approved, hasSourceClip: Boolean(run?.sourceVideoPath), imported })}
+ {driftRemedy({ approved, hasSourceClip, imported })}
</span>
</p>
)}
@@ -301,10 +309,12 @@ function DirectionCard({
"Retry postprocess" that 409s for a finalized/approved run. */}
{(approved || candidate) && run?.stripMissing && (
<p className="text-[10px] text-port-error border border-port-error/60 rounded px-1.5 py-1 leading-tight">
- {/* An import is always finalized AND refuses unlock, so naming unlock
- here would advise the same guaranteed-409 the drift badge and the
- hidden Reopen/Unlock buttons already avoid. */}
- Walk strip missing on disk — {imported ? 'create a new character version to revise it'
+ {/* An import with no clip behind it still refuses unlock/reopen, so
+ naming them there would advise a guaranteed-409 the drift badge and
+ the hidden Reopen/Unlock buttons already avoid. With a clip it
+ recovers exactly like a native direction. */}
+ Walk strip missing on disk — {imported && !hasSourceClip
+ ? 're-import this character to bring its source clip across'
: finalized ? 'unlock the set to regenerate this direction' : 'regenerate to repack it'}.
</p>
)}
@@ -330,7 +340,7 @@ function DirectionCard({
{/* Even when packaging failed, grok still produced a clip — show it so
the render isn't a dead end. The raw clip carries its own magenta
matte (not transparent), so no checkerboard behind it. */}
- {run.status === 'error' && run.sourceVideoPath && (
+ {run.status === 'error' && hasSourceClip && (
<video
src={spriteAssetUrl(recordId, run.sourceVideoPath)}
className="w-full rounded border border-port-border"
@@ -417,11 +427,12 @@ function DirectionCard({
the rest are fine. Un-freezes a finalized set but keeps the other seven
approvals; the rendered clip is preserved, so re-approval is one click.
Inline confirm (not a hidden two-click arm) per the repo's UX.
- Hidden for a source-pipeline import, whose set has no regenerable clips
- behind it — the server refuses reopen there (LEGACY_IMPORTED_WALK_SET)
- exactly as it refuses unlock, so offering the button would guarantee a
- 409 on click. Mirrors how the header hides Unlock for imports. */}
- {approved && !imported && (
+ Hidden only for an imported direction with NO clip on disk — there the
+ server refuses reopen (LEGACY_IMPORTED_WALK_SET) exactly as it refuses
+ unlock, so offering the button would guarantee a 409 on click. An
+ imported direction whose clip came across reopens like any other.
+ Mirrors how the header gates Unlock. */}
+ {approved && (!imported || hasSourceClip) && (
reopening ? (
<ConfirmButtonPair
prompt={finalized ? 'Reopen (un-freezes set)?' : 'Reopen this direction?'}
@@ -484,11 +495,17 @@ export default function WalkWorkflow({
const runs = walk?.runs || [];
const selection = walk?.selection || null;
const finalized = Boolean(walk?.walkSet);
- // A source-pipeline import (#2895) has no regenerable grok clips behind its
- // frozen set, so the server refuses to unlock it — hide the affordance and
- // show why rather than offering a button that always 409s. The server stamps
- // this flag on the walk state so the client doesn't re-derive the path convention.
+ // A source-pipeline import (#2895) still carries directions PortOS cannot
+ // compile from. The server stamps this flag on the walk state so the client
+ // doesn't re-derive the path convention itself.
const importedWalkSet = Boolean(walk?.walkSet?.imported);
+ // …but since #2984 imports each run's clip, such a set is only a dead end when
+ // NOTHING behind it can be re-derived — which is exactly when the server
+ // refuses to unlock it. Gate the affordance on that, not on the import label,
+ // so an import with its clips intact gets the real Unlock button instead of a
+ // "new version to revise" note that is no longer true.
+ const unlockBlocked = importedWalkSet
+ && !(walk?.runs || []).some((run) => run.sourceVideoPath && !run.sourceClipMissing);
// direction → jobId for in-flight video renders. The hook instance is owned
// by the Sprites page and shared with the asset collection (#2931) so both
@@ -617,9 +634,9 @@ export default function WalkWorkflow({
<p className="text-xs text-port-success flex items-center gap-1">
<Lock className="w-3 h-3" /> walk set frozen · immutable
</p>
- {importedWalkSet ? (
- <span className="text-[10px] text-gray-500" title="Imported from the source pipeline — no regenerable clips">
- imported · new version to revise
+ {unlockBlocked ? (
+ <span className="text-[10px] text-gray-500" title="Imported from the source pipeline with no source clips on disk — re-import the character to bring them across">
+ imported · no clips to re-derive
</span>
) : unlockConfirm ? (
<ConfirmButtonPair
diff --git a/client/src/components/sprites/WalkWorkflow.test.jsx b/client/src/components/sprites/WalkWorkflow.test.jsx
index 617d2db0c1..9d1afcfb63 100644
--- a/client/src/components/sprites/WalkWorkflow.test.jsx
+++ b/client/src/components/sprites/WalkWorkflow.test.jsx
@@ -459,10 +459,10 @@ describe('WalkWorkflow reprocess + reopen', () => {
expect(reopenSpriteWalk).toHaveBeenCalledWith('example-walker', { direction: 'east' }, { silent: true });
});
- it('hides Reopen on a source-pipeline import, whose server refuses it', async () => {
- // An imported set has no regenerable clips behind it, so reopen (like
- // unlock) always 409s LEGACY_IMPORTED_WALK_SET — offering the button would
- // guarantee an error on click. The remedy is a new character version.
+ it('hides Reopen on an import whose clip is not on disk, whose server refuses it', async () => {
+ // An imported direction with no clip behind it has nothing to re-derive
+ // from, so reopen (like unlock) 409s LEGACY_IMPORTED_WALK_SET — offering the
+ // button would guarantee an error on click. The remedy is re-importing.
render(
<MemoryRouter>
<WalkWorkflow
@@ -485,6 +485,45 @@ describe('WalkWorkflow reprocess + reopen', () => {
</MemoryRouter>,
);
expect(screen.queryByRole('button', { name: /^Reopen$/ })).toBeNull();
- expect(screen.getByText(/imported · new version to revise/)).toBeTruthy();
+ expect(screen.getByText(/imported · no clips to re-derive/)).toBeTruthy();
+ });
+
+ // #2993: since the importer brings each run's clip across, an imported
+ // direction with its clip on disk is re-derivable exactly like a native one —
+ // the server allows reopen/unlock there, so the affordances must be offered.
+ // The gate is the clip, not the import label.
+ it('offers Reopen and Unlock on an import whose clip IS on disk', async () => {
+ render(
+ <MemoryRouter>
+ <WalkWorkflow
+ record={{ id: 'example-walker' }}
+ reference={{ manifest: { mainReference: { locked: true }, anchors: [{ direction: 'east', status: 'locked' }] } }}
+ walk={{
+ runs: [{
+ id: 'run-east',
+ direction: 'east',
+ status: 'approved',
+ sourceVideoPath: 'grok/run-east/generated/source-video.mp4',
+ stripPreview: {
+ stripPath: 'grok/run-east/generated/strip.png', frameCount: 12, fps: 10, cellWidth: 384, cellHeight: 384,
+ },
+ }],
+ selection: { directions: { east: { status: 'approved', runId: 'run-east' } } },
+ walkSet: { imported: true, directions: { east: { status: 'approved' } } },
+ walkTarget: {
+ frameCount: 12, fps: 10, source: 'derived', sourceLabel: 'from the first approved direction', drift: [],
+ },
+ }}
+ renders={noRenders()}
+ duration={6}
+ onDurationChange={vi.fn()}
+ onGenerate={vi.fn()}
+ onChanged={vi.fn()}
+ />
+ </MemoryRouter>,
+ );
+ expect(screen.getByRole('button', { name: /^Reopen$/ })).toBeTruthy();
+ expect(screen.getByRole('button', { name: /^Unlock$/ })).toBeTruthy();
+ expect(screen.queryByText(/no clips to re-derive/)).toBeNull();
});
});
diff --git a/server/services/sprites/atlas.js b/server/services/sprites/atlas.js
index 42904d8dc5..b7f4c82892 100644
--- a/server/services/sprites/atlas.js
+++ b/server/services/sprites/atlas.js
@@ -46,7 +46,9 @@ import {
alphaBbox, compositeOnto, sha256Buffer,
} from './walkPostprocess.js';
import { ATLAS_IDLE_COLUMN } from './walkBounds.js';
-import { withWalkWriteTail, walkSetRelPath, isImportedWalkSet } from './walk.js';
+import {
+ withWalkWriteTail, walkSetRelPath, isImportedWalkSet, importedWalkDirections,
+} from './walk.js';
// Player atlas contract (source pipeline runtime_publish.py): 96px cells,
// pivot (48,88) — silhouette centered on x=48, feet on the y=88 ground line —
@@ -203,17 +205,26 @@ export async function validateForCompile(recordId) {
throw compileError('Walk set manifest is not a finalized eight-direction walk set');
}
if (walkSet.characterId !== recordId) throw compileError('Walk set characterId mismatch');
- // Phase-1 imported walk sets are copied verbatim from the source pipeline:
- // their paths are repo-root (`art-source/sprites/<id>/…`) and — decisively —
- // the packaged per-frame PNGs were never imported (the importer skips
- // frames/ to minimize copies). Recompiling them here is structurally
- // impossible; say so plainly instead of a misleading tamper error. Their
+ // A direction still packaged by the source pipeline is copied verbatim: its
+ // paths are repo-root (`art-source/sprites/<id>/…`) and — decisively — its
+ // per-frame PNGs were never imported (the importer skips frames/ to minimize
+ // copies). Compiling from it is structurally impossible; say so plainly
+ // instead of the misleading tamper error the sha check below would produce.
+ //
+ // Unlike the original guard this is per-direction (#2993), because a direction
+ // CAN now leave that state: re-deriving it from its imported clip regenerates
+ // the frames here and re-approving rewrites its entry record-relative, so a set
+ // whose directions have all been re-derived compiles like any native one. Only
+ // the directions still carrying source-pipeline provenance block the compile,
+ // and the message names them so the remedy is per-direction too. Their
// already-published runtime atlases were imported and remain browsable.
- // Shared predicate (walk.js) so this recompile guard and unlockWalkSet's
- // stay in lockstep on what counts as a legacy import.
if (isImportedWalkSet(walkSet)) {
+ const stale = importedWalkDirections(walkSet);
+ const which = stale.length ? `${stale.join(', ')} ${stale.length === 1 ? 'is' : 'are'}` : 'This walk set is';
throw new ServerError(
- 'This walk set was imported from the source pipeline — its packaged frames were not imported, so PortOS cannot recompile it. Imported runtime atlases remain available in the asset library; to compile here, run the walk workflow on a new character.',
+ `${which} still packaged by the source pipeline, whose per-frame images were not imported — PortOS cannot compile from them. `
+ + 'Reopen each such direction and reprocess it from its imported clip to re-derive the frames here, then compile. '
+ + 'The imported runtime atlases remain available in the asset library.',
{ status: 409, code: 'LEGACY_IMPORTED_WALK_SET' },
);
}
diff --git a/server/services/sprites/atlas.test.js b/server/services/sprites/atlas.test.js
index 3b911178da..1f2ca37a72 100644
--- a/server/services/sprites/atlas.test.js
+++ b/server/services/sprites/atlas.test.js
@@ -319,6 +319,24 @@ describe('compileAtlas', () => {
await expect(compileAtlas(id)).rejects.toMatchObject({ status: 409, code: 'LEGACY_IMPORTED_WALK_SET' });
});
+ // #2993: the refusal is per-direction, because a direction can now leave the
+ // imported state (reopen → reprocess from its imported clip → re-approve
+ // rewrites its entry record-relative). A set that is otherwise fully native
+ // must still be refused for the directions that have NOT been re-derived —
+ // and must name them, since the remedy is applied one direction at a time.
+ it('names the directions still packaged by the source pipeline', async () => {
+ const id = await finalizedCharacter();
+ const setAbs = join(TEST_ROOT, 'sprites', id, `walk/${id}-walk-set-v1.json`);
+ const walkSet = JSON.parse(await readFile(setAbs, 'utf8'));
+ walkSet.directions.north.runManifest = `art-source/sprites/${id}/${walkSet.directions.north.runManifest}`;
+ await writeFile(setAbs, JSON.stringify(walkSet));
+ await expect(compileAtlas(id)).rejects.toMatchObject({
+ status: 409,
+ code: 'LEGACY_IMPORTED_WALK_SET',
+ message: expect.stringContaining('north is still packaged by the source pipeline'),
+ });
+ });
+
it('self-heals a deleted versioned atlas instead of returning a dangling pointer', async () => {
const id = await finalizedCharacter();
const first = await compileAtlas(id);
diff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.js
index 4fbe50d197..5b164bd0ba 100644
--- a/server/services/sprites/walk.js
+++ b/server/services/sprites/walk.js
@@ -30,7 +30,7 @@ import { GROK_TUI_ID } from '../../lib/grok.js';
import { getSettings } from '../settings.js';
import { getRecord, updateRecord } from './records.js';
import {
- spriteDir, resolveSpriteAssetPath, toRecordRelativeAssetPath, RUN_DIR_MATCH,
+ spriteDir, resolveSpriteAssetPath, toRecordRelativeAssetPath, RUN_DIR_MATCH, altRunLayoutPath,
} from './paths.js';
import { requireCharacter, loadManifest } from './reference.js';
import { SPRITE_DIRECTIONS, anchorIdForDirection, buildWalkVideoPrompt } from './prompts.js';
@@ -69,11 +69,13 @@ export const walkSetRelPath = (id) => `walk/${id}-walk-set-v1.json`;
// `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.
+// The two on-disk homes a run can be found in: the neutral `runs/` layout (all
+// new generations, post-migration) and `grok/` — both a straggler on an
+// un-migrated install/fork AND where a source-pipeline import lands whenever its
+// own manifests declare that layout (migration 202 is one-shot per install, so it
+// never re-runs for an import that arrives afterwards). Approved runs resolve
+// through their selection entry, so the scan covers unapproved candidates plus
+// any run whose entry has been dropped by an unlock/reopen.
const RUN_SCAN_DIRS = ['runs', 'grok'];
const RUN_RECORD_NAME = 'animation-run.json';
@@ -91,16 +93,37 @@ async function loadWalkSet(recordId) {
}
// A phase-1 imported walk set (#2895) is copied verbatim from the source
-// pipeline: its selectionPath is repo-root-anchored (`art-source/sprites/…`)
-// and its packaged per-frame PNGs were never imported. Such a set has no
-// regenerable clips behind it, so it can neither be recompiled (atlas.js) nor
-// unlocked (unlockWalkSet) — both surface `LEGACY_IMPORTED_WALK_SET`. Single
-// source of truth for the marker so the three call sites (here, atlas.js, and
-// the client via the getWalkState flag) can't drift. The marker can sit at any
-// index (absolute/repo-prefixed variants), matching the importer's own
+// pipeline: every embedded path is repo-root-anchored (`art-source/sprites/…`)
+// and its packaged per-frame PNGs were never imported. The marker can sit at
+// any index (absolute/repo-prefixed variants), matching the importer's own
// relToCharacterDir recognition — hence `includes`, not a prefix test.
+const SOURCE_PIPELINE_MARKER = 'art-source/sprites/';
+const isSourcePipelinePath = (p) => typeof p === 'string' && p.includes(SOURCE_PIPELINE_MARKER);
+
+/**
+ * The directions of a walk set that are STILL packaged by the source pipeline —
+ * their approved entry names the source tree, so their per-frame PNGs are not on
+ * disk here and only the source pipeline could have produced them.
+ *
+ * This is the precise, per-direction form of "imported" (#2993). Re-deriving a
+ * direction inside PortOS rewrites its entry through `approveWalkDirection`,
+ * which stores record-relative paths — so a re-derived direction drops out of
+ * this list and the set converges on compilable as the user works through it.
+ * A blanket set-level refusal could not express that partial state.
+ */
+export function importedWalkDirections(walkSet) {
+ return Object.entries(walkSet?.directions || {})
+ .filter(([, entry]) => isSourcePipelinePath(entry?.runPath) || isSourcePipelinePath(entry?.runManifest))
+ .map(([direction]) => direction);
+}
+
+// Whether a walk set carries ANY un-re-derived source-pipeline provenance:
+// either the set-level selection pointer or at least one direction entry. Single
+// source of truth for the marker so its call sites (atlas.js's recompile guard,
+// the un-finalize evidence gate below, and the client via the getWalkState flag)
+// can't drift.
export const isImportedWalkSet = (walkSet) => (
- typeof walkSet?.selectionPath === 'string' && walkSet.selectionPath.includes('art-source/sprites/')
+ isSourcePipelinePath(walkSet?.selectionPath) || importedWalkDirections(walkSet).length > 0
);
async function loadSelection(recordId) {
@@ -129,24 +152,97 @@ async function loadRunRecordAt(recordId, runDirRel) {
}
async function loadRunRecord(recordId, runId) {
- // Runs the write-actions (generate/attach/rerun/approve) touch always live
- // under the neutral runs/ layout: new generations write there, and migration
- // 202 moves every legacy grok/ run there at boot before the first request.
- // So resolve runs/ only — do NOT fall back to grok/ here. A grok/ straggler
- // (un-migrated fork, or a record migration 202 skipped on a collision) is
- // still DISPLAYED via getWalkState's dual-dir scan, but a mutation would need
- // its files where the persisted runPath (runs/) and packageRun's output dir
- // point, so acting on it before migration completes returns RUN_NOT_FOUND
- // rather than silently splitting the run across two directories.
+ // Runs PortOS itself just wrote (generate → attach) always live under the
+ // neutral runs/ layout, so this straight lookup is exact for that path.
+ // Callers that may act on a run PortOS did not create (rerun, approve) go
+ // through `resolveRunById` instead — see there.
return loadRunRecordAt(recordId, runRelPath(runId));
}
-async function saveRunRecord(recordId, run) {
- const dir = join(spriteDir(recordId), runRelPath(run.id));
+/**
+ * Locate a run under EITHER on-disk layout, returning the record together with
+ * the directory it ACTUALLY lives in.
+ *
+ * Migration 202 renamed pre-existing native `grok/<run-id>/` runs into the
+ * neutral `runs/` tree, but it is a one-shot per install: a source-pipeline
+ * import landing afterwards writes its runs wherever its own (hash-pinned)
+ * manifests declare — commonly `grok/<run-id>/` — so `runs/`-only resolution
+ * reports RUN_NOT_FOUND for a run that is right there on disk (#2993). Probing
+ * both layouts is only half the fix; the resolved directory has to be threaded
+ * into every subsequent write, which is why this returns it rather than just the
+ * record. That is what keeps a re-derive from splitting one run across two
+ * directories — the hazard the old `runs/`-only rule avoided by refusing outright.
+ */
+async function resolveRunAt(recordId, runDirRel) {
+ const candidates = [runDirRel, altRunLayoutPath(runDirRel)].filter(Boolean);
+ for (const rel of candidates) {
+ // eslint-disable-next-line no-await-in-loop -- ordered preference: stop at the layout that exists
+ const run = await loadRunRecordAt(recordId, rel);
+ if (run) return { run, runDirRel: rel };
+ }
+ return null;
+}
+
+const resolveRunById = (recordId, runId) => resolveRunAt(recordId, runRelPath(runId));
+
+async function saveRunRecordAt(recordId, run, runDirRel) {
+ const dir = join(spriteDir(recordId), runDirRel);
await ensureDir(dir);
await atomicWrite(join(dir, RUN_RECORD_NAME), run);
}
+const saveRunRecord = (recordId, run) => saveRunRecordAt(recordId, run, runRelPath(run.id));
+
+// The run directory a record-relative run path names, under either layout.
+const runDirOfPath = (rel) => (typeof rel === 'string' ? RUN_DIR_MATCH.exec(rel)?.[0] || null : null);
+
+// The run directory a selection / walk-set entry names — `runPath` first, then
+// the manifest it declares. Null for an imagegen redraw entry, which names a
+// version directory rather than a run (and so has no i2v clip behind it).
+function runDirRelForEntry(recordId, entry) {
+ const layoutPath = toRecordRelativeAssetPath(recordId, entry?.runPath)
+ || toRecordRelativeAssetPath(recordId, entry?.runManifest);
+ return runDirOfPath(layoutPath);
+}
+
+// The run directory a loaded run record implies, for a caller that has the
+// record but not the directory it came from. Every candidate field is
+// record-relative by the time a read-path consumer sees it (normalizeRunAssetPaths
+// / normalizeStripPreview), and any one of them pins the run dir.
+const runDirRelOf = (run) => runDirOfPath(run?.sourceVideoPath)
+ || runDirOfPath(run?.postprocessManifest)
+ || runDirOfPath(run?.stripPreview?.stripPath);
+
+const SOURCE_CLIP_NAME = 'source-video.mp4';
+
+/**
+ * The record-relative i2v clip a run can be re-derived from, or null when none
+ * is on disk.
+ *
+ * Four candidates, in evidence order: the clip the record declares (re-anchored,
+ * since an imported record declares it against the SOURCE repo root), that path
+ * under the other run layout, then the conventional `<run-dir>/generated/` name
+ * and ITS twin. The layout twins matter because source trees drift — a manifest
+ * can name `runs/<id>/…` for a file stored under `grok/<id>/…` and both spellings
+ * denote the same clip (paths.js#altRunLayoutPath); the importer resolves source
+ * reads the same way, so a drifted tree that imported successfully must also be
+ * re-derivable here.
+ */
+async function resolveRunClipRel(recordId, run, runDirRel) {
+ const declared = toRecordRelativeAssetPath(recordId, run?.sourceVideoPath);
+ const conventional = runDirRel ? `${runDirRel}/generated/${SOURCE_CLIP_NAME}` : null;
+ const candidates = [];
+ for (const rel of [declared, conventional]) {
+ if (!rel) continue;
+ candidates.push(rel, altRunLayoutPath(rel));
+ }
+ for (const rel of [...new Set(candidates.filter(Boolean))]) {
+ // eslint-disable-next-line no-await-in-loop -- ordered preference: stop at the first clip that exists
+ if (await pathExists(join(spriteDir(recordId), rel))) return rel;
+ }
+ return null;
+}
+
async function requireUnfinalized(recordId) {
if (await loadWalkSet(recordId)) {
throw new ServerError('Walk set is finalized — revisions require a new character version', { status: 409, code: 'WALK_SET_FINAL' });
@@ -246,6 +342,31 @@ async function normalizeMissingStrip(recordId, run) {
return { ...run, stripMissing: true, stripPreview: stripPreviewRest };
}
+/**
+ * Resolve the run's i2v source clip against DISK, so "can this direction be
+ * re-derived?" is answered by evidence rather than by whether the record happens
+ * to name a clip (#2993).
+ *
+ * Three distinct outcomes, deliberately not collapsed: the clip is found (and
+ * `sourceVideoPath` is rewritten to where it actually is, healing a layout-drift
+ * mismatch for the player, the trimmer, and the re-derive); the record declares a
+ * clip that is NOT on disk, or names none while its run directory has none
+ * either (`sourceClipMissing: true`, the same read-time flag shape as
+ * `stripMissing`); or the run is an imagegen redraw cycle, which never had an
+ * i2v clip and is left untouched.
+ *
+ * The declared path is kept alongside the flag rather than dropped — it is the
+ * record's own provenance, and consumers gate on the flag. In memory only; the
+ * hash-pinned record on disk is never rewritten here.
+ */
+async function normalizeSourceClip(recordId, run) {
+ const runDirRel = runDirRelOf(run);
+ const clipRel = await resolveRunClipRel(recordId, run, runDirRel);
+ if (clipRel) return clipRel === run.sourceVideoPath ? run : { ...run, sourceVideoPath: clipRel };
+ if (!runDirRel && !run?.sourceVideoPath) return run;
+ return { ...run, sourceClipMissing: true };
+}
+
// PortOS stamps `id` on every run record it writes; imported source-pipeline
// records don't carry one at all (see importer.test.js's fixtures). The run
// DIRECTORY is the run id under both layouts, so fall back to it. Two
@@ -346,18 +467,30 @@ async function loadRedrawRun(recordId, direction, entry) {
*/
async function loadRunForEntry(recordId, direction, entry) {
// The run directory names the layout; fall back to the manifest's own path
- // for an entry that carries only a manifest.
- const layoutPath = toRecordRelativeAssetPath(recordId, entry.runPath)
- || toRecordRelativeAssetPath(recordId, entry.runManifest);
- if (!layoutPath) return null;
- const runDirRel = RUN_DIR_MATCH.exec(layoutPath)?.[0];
+ // for an entry that carries only a manifest. An entry that declares one layout
+ // for a run stored under the other still resolves (`resolveRunAt`), and the
+ // directory it really came from is what the record is normalized against.
+ const runDirRel = runDirRelForEntry(recordId, entry);
if (runDirRel) {
- const run = await loadRunRecordAt(recordId, runDirRel);
- return run ? normalizeRunRecord(recordId, run, runDirRel) : null;
+ const found = await resolveRunAt(recordId, runDirRel);
+ return found ? normalizeRunRecord(recordId, found.run, found.runDirRel) : null;
}
+ if (!toRecordRelativeAssetPath(recordId, entry.runPath)
+ && !toRecordRelativeAssetPath(recordId, entry.runManifest)) return null;
return loadRedrawRun(recordId, direction, entry);
}
+/**
+ * The clip behind ONE approved direction, or null when that direction has
+ * nothing to re-derive from — the evidence the un-finalize gate below keys on.
+ */
+async function directionClipRel(recordId, entry) {
+ const runDirRel = runDirRelForEntry(recordId, entry);
+ if (!runDirRel) return null;
+ const found = await resolveRunAt(recordId, runDirRel);
+ return resolveRunClipRel(recordId, found?.run, found?.runDirRel || runDirRel);
+}
+
/**
* The packed geometry of each direction that actually carries one, in ATLAS
* order (SPRITE_DIRECTIONS) so "the first packaged direction" means the same
@@ -440,8 +573,15 @@ export async function getWalkState(recordId) {
// 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/).
+ // Any directory, not just PortOS's own `walk-<direction>-<id8>` naming: the
+ // source pipeline names its run directories freely (`run-1`, …), and those runs
+ // are reachable ONLY through a selection entry — so the moment unlock or reopen
+ // drops that entry (which is exactly when the user is about to re-derive them)
+ // a name-prefix scan made them vanish from the workflow. A directory with no
+ // `animation-run.json` loads as null and is filtered out below, so widening the
+ // scan costs one absent-file read per non-run directory and admits nothing new.
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 })))
+ .then((entries) => entries.filter((e) => e.isDirectory() && !e.name.startsWith('.')).map((e) => ({ base, name: e.name })))
.catch(() => []))) // dir absent → no runs there yet
.then((lists) => lists.flat());
// The record read (for the publish binding's runtime contract) is independent
@@ -486,7 +626,7 @@ export async function getWalkState(recordId) {
const allRuns = (await Promise.all(
[...entryRuns, ...scannedRuns]
.map(normalizeStaleRendering)
- .map((run) => normalizeMissingStrip(recordId, run)),
+ .map(async (run) => normalizeSourceClip(recordId, await normalizeMissingStrip(recordId, run))),
)).sort((a, b) => runCreatedAtMs(b.createdAt) - runCreatedAtMs(a.createdAt));
// Stamp the imported flag so the client reads intent (`walkSet.imported`)
// instead of re-deriving the source-pipeline path convention itself.
@@ -812,9 +952,14 @@ export async function attachTuiWalkResult(recordId, runId, videoAbs) {
* run record (candidate on success, captured error otherwise) — shared by
* the completion-hook attach and the manual rerun so the two can't drift.
* The caller persists the mutated record.
+ *
+ * `location` pins WHERE the run lives and which clip to read: the attach path
+ * omits it (PortOS just wrote the run under `runs/<id>/`), while a rerun that
+ * resolved the run under the other layout passes both, so the regenerated frames
+ * land beside the clip they came from instead of in a phantom twin directory.
*/
-async function packageRun(recordId, run, overrides = {}) {
- const runRel = runRelPath(run.id);
+async function packageRun(recordId, run, overrides = {}, location = {}) {
+ const runRel = location.runDirRel || runRelPath(run.id);
const runAbs = join(spriteDir(recordId), runRel);
// Frame count + playback fps: an explicit reprocess override wins, else the
// values stored at generate time, else the current defaults (older runs
@@ -824,11 +969,14 @@ async function packageRun(recordId, run, overrides = {}) {
const fps = clampFps(overrides.fps ?? run.fps ?? WALK_DEFAULT_FPS);
run.frameCount = frameCount;
run.fps = fps;
- // Record-relative path to grok's raw clip, stamped BEFORE the (possibly
- // failing) postprocess so a run that errors in packaging still surfaces the
- // video grok actually produced in the UI, not just the error text. Set here
- // (shared by attach + rerun) so a retry backfills it onto an older run too.
- run.sourceVideoPath = `${runRel}/generated/source-video.mp4`;
+ // Record-relative path to the raw clip, stamped BEFORE the (possibly failing)
+ // postprocess so a run that errors in packaging still surfaces the video grok
+ // actually produced in the UI, not just the error text. Set here (shared by
+ // attach + rerun) so a retry backfills it onto an older run too — and for an
+ // imported run that means persisting the record-relative form in place of the
+ // source-repo anchor its manifest was copied with.
+ run.sourceVideoPath = location.clipRel || `${runRel}/generated/${SOURCE_CLIP_NAME}`;
+ const videoAbs = resolveSpriteAssetPath(recordId, run.sourceVideoPath);
try {
const manifest = await loadManifest(recordId);
const anchor = manifest?.anchors?.find((a) => a.direction === run.direction);
@@ -841,7 +989,7 @@ async function packageRun(recordId, run, overrides = {}) {
runRel,
anchorRel: anchor.path,
anchorAbs: resolveSpriteAssetPath(recordId, anchor.path),
- videoAbs: join(runAbs, 'generated', 'source-video.mp4'),
+ videoAbs,
frameCount,
fps,
});
@@ -870,25 +1018,32 @@ export function rerunWalkPostprocess(recordId, { runId, frameCount, fps }) {
async function rerunWalkPostprocessImpl(recordId, runId, overrides) {
await requireCharacter(recordId);
await requireUnfinalized(recordId);
- const run = await loadRunRecord(recordId, runId);
- if (!run) throw new ServerError(`Unknown walk run: ${runId}`, { status: 404, code: 'RUN_NOT_FOUND' });
+ // Layout-aware (#2993): an imported run commonly lives under `grok/<run-id>/`,
+ // and its regenerated frames + record must go back to that same directory.
+ const found = await resolveRunById(recordId, runId);
+ if (!found) throw new ServerError(`Unknown walk run: ${runId}`, { status: 404, code: 'RUN_NOT_FOUND' });
+ const { run, runDirRel } = found;
// One state read serves both the immutability check and the target below.
const { walkTarget, selection } = await getWalkState(recordId);
if (selection?.directions?.[run.direction]?.runId === runId) {
throw new ServerError('Run is approved — approved runs are immutable', { status: 409, code: 'RUN_APPROVED' });
}
- const videoAbs = join(spriteDir(recordId), runRelPath(runId), 'generated', 'source-video.mp4');
- if (!await pathExists(videoAbs)) {
+ const clipRel = await resolveRunClipRel(recordId, run, runDirRel);
+ if (!clipRel) {
throw new ServerError('Run has no source video yet', { status: 409, code: 'VIDEO_NOT_READY' });
}
// Same set-level gate as generation (#2985): a reprocess is exactly how a
// drifted direction is brought INTO line with the target, so it must land on
// the target — not somewhere new. An omitted override adopts the target.
const geometry = await resolveRenderGeometry(recordId, { walkTarget, selection }, overrides);
+ // An imported record carries no `id` at all; stamp the run directory's name
+ // (what every reader already falls back to) so the re-derived record is
+ // self-describing from here on.
+ if (!run.id) run.id = runId;
// Reprocess the SAME on-disk clip at the pinned frame count / playback speed —
// no grok call, no regeneration.
- await packageRun(recordId, run, geometry);
- await saveRunRecord(recordId, run);
+ await packageRun(recordId, run, geometry, { runDirRel, clipRel });
+ await saveRunRecordAt(recordId, run, runDirRel);
if (run.status === 'error') {
throw new ServerError(`Postprocess failed: ${run.postprocessError}`, { status: 422, code: 'POSTPROCESS_FAILED' });
}
@@ -918,26 +1073,41 @@ export function approveWalkDirection(recordId, args) {
* the original finalize did. The record status drops back to
* `reference-complete` (all anchors locked, walk in progress).
*
- * Legacy source-pipeline imports (#2895) are refused: their walk set was copied
- * byte-for-byte from `art-source/sprites/` with no `grok/` candidate runs behind
- * it, so unlocking would strand the record with nothing to regenerate from —
- * the same reason atlas.js refuses to recompile them (#2918).
+ * A source-pipeline import (#2895) is refused only when it genuinely has nothing
+ * to re-derive from — see `assertReDerivable`.
*/
export function unlockWalkSet(recordId) {
return walkWriteTail(recordId, () => unlockWalkSetImpl(recordId));
}
-// Imported source-pipeline sets carry no regenerable clips, so unlocking or
-// reopening would strand the record with nothing to regenerate from — refuse
-// both through one shared message (the `verb` is the only difference). No-op for
-// a native set (or no set at all).
-function assertNotImportedWalkSet(walkSet, verb) {
- if (walkSet && isImportedWalkSet(walkSet)) {
- throw new ServerError(
- `This walk set was imported from the source pipeline and has no regenerable clips — ${verb} is not supported. Create a new character version to revise it.`,
- { status: 409, code: 'LEGACY_IMPORTED_WALK_SET' },
- );
+/**
+ * Refuse un-finalizing an imported walk set that has no clip to re-derive from.
+ *
+ * The original guard refused EVERY imported set, on the stated grounds that it
+ * "has no regenerable clips behind it" — true when it was written, and false
+ * since #2984 taught the importer to copy each run's `source-video.mp4`. So the
+ * gate now keys on the evidence the justification always named: is a clip
+ * actually on disk for the directions being re-opened? (#2993)
+ *
+ * Provenance still selects WHO gets examined, and only that: a native set is
+ * never gated, exactly as before — a user who cleaned up their own rendered
+ * clips must not suddenly find Unlock refused. Among imported sets, `directions`
+ * is the scope — one direction for `reopen`, all of them for `unlock` — and one
+ * clip anywhere in scope is enough, because that is one direction the user can
+ * genuinely bring onto a new target. A set with none is still a dead end, and
+ * still says so.
+ */
+async function assertReDerivable(recordId, walkSet, directions, verb) {
+ if (!isImportedWalkSet(walkSet)) return;
+ for (const direction of directions) {
+ // eslint-disable-next-line no-await-in-loop -- stop at the first re-derivable direction
+ if (await directionClipRel(recordId, walkSet.directions?.[direction])) return;
}
+ const scope = directions.length === 1 ? `the ${directions[0]} direction has` : 'its directions have';
+ throw new ServerError(
+ `This walk set was imported from the source pipeline and ${scope} no source clip on disk — ${verb} is not supported, because there would be nothing to re-derive from. Re-import this character to bring its walk clips across, or create a new character version to revise it.`,
+ { status: 409, code: 'LEGACY_IMPORTED_WALK_SET' },
+ );
}
// Un-finalize: drop the canonical "finalized" signal (the walk-set file) FIRST,
@@ -956,7 +1126,7 @@ async function unlockWalkSetImpl(recordId) {
if (!walkSet) {
throw new ServerError('No finalized walk set to unlock', { status: 409, code: 'WALK_SET_NOT_FINAL' });
}
- assertNotImportedWalkSet(walkSet, 'unlocking');
+ await assertReDerivable(recordId, walkSet, Object.keys(walkSet.directions || {}), 'unlocking');
await dropFinalizedWalkSet(recordId);
// Seed a fresh (empty) selection so EVERY direction re-opens: with the walk
// set gone each direction would still read `approved` from the old selection
@@ -986,8 +1156,8 @@ async function unlockWalkSetImpl(recordId) {
* every OTHER direction's selection entry intact, so re-freezing is a single
* re-approval of the one direction rather than all eight. The rendered clip is
* preserved on disk, so the reopened direction can be reprocessed at a new
- * speed/frame-count with no regeneration. Imported sets have no regenerable
- * clips and are refused (mirrors unlock).
+ * speed/frame-count with no regeneration. An imported direction is refused only
+ * when its clip is genuinely absent (mirrors unlock — see `assertReDerivable`).
*/
export function reopenWalkDirection(recordId, { direction }) {
return walkWriteTail(recordId, () => reopenWalkDirectionImpl(recordId, direction));
@@ -996,7 +1166,7 @@ export function reopenWalkDirection(recordId, { direction }) {
async function reopenWalkDirectionImpl(recordId, direction) {
await requireCharacter(recordId);
const walkSet = await loadWalkSet(recordId);
- assertNotImportedWalkSet(walkSet, 'reopening');
+ await assertReDerivable(recordId, walkSet, [direction], 'reopening');
const selection = (await loadSelection(recordId)) || seedSelection(recordId);
if (selection.directions?.[direction]?.status !== 'approved') {
throw new ServerError(`Direction ${direction} is not approved`, { status: 409, code: 'DIRECTION_NOT_APPROVED' });
@@ -1016,8 +1186,11 @@ async function reopenWalkDirectionImpl(recordId, direction) {
async function approveWalkDirectionImpl(recordId, { direction, runId }) {
await requireCharacter(recordId);
await requireUnfinalized(recordId);
- const run = await loadRunRecord(recordId, runId);
- if (!run) throw new ServerError(`Unknown walk run: ${runId}`, { status: 404, code: 'RUN_NOT_FOUND' });
+ // Layout-aware, like the rerun above: a re-derived import stays in the run
+ // directory it was imported into, and its approval must record THAT path.
+ const found = await resolveRunById(recordId, runId);
+ if (!found) throw new ServerError(`Unknown walk run: ${runId}`, { status: 404, code: 'RUN_NOT_FOUND' });
+ const { run, runDirRel } = found;
if (run.direction !== direction) {
throw new ServerError(`Run ${runId} animates "${run.direction}", not "${direction}"`, { status: 400, code: 'RUN_DIRECTION_MISMATCH' });
}
@@ -1031,9 +1204,9 @@ async function approveWalkDirectionImpl(recordId, { direction, runId }) {
// declared frameCount must match the actual packed frames. Cross-direction
// consistency against the SET target is enforced below (#2985); atlas.js keeps
// its own compile-time check as the backstop for imported/legacy sets.
- // `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
+ // `resolveRunById` deliberately returns the RAW record (its results flow into
+ // saveRunRecordAt 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)
@@ -1061,6 +1234,26 @@ async function approveWalkDirectionImpl(recordId, { direction, runId }) {
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' });
}
+ // The per-frame images the manifest declares must be on disk too. Approval is
+ // what freezes this direction into the set the compiler reads, and the compiler
+ // verifies every frame's BYTES — so a manifest whose frames were never written
+ // here (exactly the shape a source-pipeline import has: its manifest was copied,
+ // its frames/ was not) would sail through the strip check above and surface at
+ // compile time as an unexplained sha mismatch. Refuse it where the cause is
+ // still legible, and name the remedy. A minimal manifest that declares no
+ // frames[] is unchanged — the strip sha stays the primary tamper check. (#2993)
+ const framePaths = (Array.isArray(packaged.frames) ? packaged.frames : [])
+ .map((frame) => toRecordRelativeAssetPath(recordId, typeof frame === 'string' ? frame : frame?.path))
+ .filter(Boolean);
+ const framesOnDisk = await Promise.all(framePaths
+ .map((rel) => pathExists(join(spriteDir(recordId), rel))));
+ const missingFrames = framesOnDisk.filter((present) => !present).length;
+ if (missingFrames) {
+ throw new ServerError(
+ `${missingFrames} of this run's ${framePaths.length} packaged frames are missing on disk — reprocess the direction from its source clip to re-derive them before approving.`,
+ { status: 409, code: 'RUN_FRAMES_MISSING' },
+ );
+ }
// Approval — not generation — is the moment a direction's geometry gets frozen
// into the set the compiler will read, so the target has to hold HERE too. The
@@ -1080,7 +1273,7 @@ async function approveWalkDirectionImpl(recordId, { direction, runId }) {
selection.directions[direction] = {
status: 'approved',
runId,
- runPath: runRelPath(runId),
+ runPath: runDirRel,
// 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,
diff --git a/server/services/sprites/walk.test.js b/server/services/sprites/walk.test.js
index ae30f45f64..213c68dbb3 100644
--- a/server/services/sprites/walk.test.js
+++ b/server/services/sprites/walk.test.js
@@ -7,7 +7,7 @@
*/
import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
-import { mkdtempSync, rmSync } from 'fs';
+import { existsSync, mkdtempSync, rmSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { mkdir, writeFile, readFile, rm } from 'fs/promises';
@@ -56,15 +56,32 @@ const prepareWalkAnchorChromaInput = vi.fn(async (_anchorAbs, destAbs) => {
await writeFile(destAbs, 'stub-chroma-anchor');
return { preparation: 'composited-over-solid-chroma-matte' };
});
-const runWalkPostprocess = vi.fn(async ({ runRel, runAbs }) => {
- // Faithfully land the packed strip on disk (the real postprocess writes it) —
- // getWalkState's missing-strip guard now flips a candidate whose strip is
- // absent to an error, so a mock that only returns the path would look broken.
+const runWalkPostprocess = vi.fn(async ({
+ runRel, runAbs, recordId, direction, frameCount = 8, fps = 12,
+}) => {
+ // Faithfully land the packed strip AND the packaged manifest on disk (the real
+ // postprocess writes both) — getWalkState's missing-strip guard flips a
+ // candidate whose strip is absent to an error, and approveWalkDirection
+ // re-validates the manifest, so a mock that only returned paths would make a
+ // re-derived run look broken and un-approvable.
+ const stripBytes = 'packaged-strip-bytes';
await mkdir(join(runAbs, 'generated'), { recursive: true });
- await writeFile(join(runAbs, 'generated', 'strip.png'), 'packaged-strip-bytes');
+ await writeFile(join(runAbs, 'generated', 'strip.png'), stripBytes);
+ await writeFile(join(runAbs, 'generated', 'manifest.json'), JSON.stringify({
+ schemaVersion: 1,
+ kind: 'deterministically-packaged-grok-walk-video',
+ characterId: recordId,
+ direction,
+ frameCount,
+ frameRate: fps,
+ stripPath: `${runRel}/generated/strip.png`,
+ stripSha256: createHash('sha256').update(Buffer.from(stripBytes)).digest('hex'),
+ }));
return {
manifestPath: `${runRel}/generated/manifest.json`,
- stripPreview: { stripPath: `${runRel}/generated/strip.png`, frameCount: 8, fps: 12, cellWidth: 384, cellHeight: 384, row: 0, startColumn: 0 },
+ stripPreview: {
+ stripPath: `${runRel}/generated/strip.png`, frameCount, fps, cellWidth: 384, cellHeight: 384, row: 0, startColumn: 0,
+ },
};
});
vi.mock('./walkPostprocess.js', async (importOriginal) => {
@@ -81,7 +98,7 @@ const { listSpriteAssets } = await import('./paths.js');
const { lockReference } = await import('./reference.js');
const {
getWalkState, startWalkGeneration, attachTuiWalkResult, approveWalkDirection, rerunWalkPostprocess, unlockWalkSet,
- reopenWalkDirection, setWalkTarget,
+ reopenWalkDirection, setWalkTarget, importedWalkDirections,
} = await import('./walk.js');
const { SPRITE_DIRECTIONS, ANCHOR_DIRECTIONS } = await import('./prompts.js');
@@ -144,6 +161,90 @@ async function makeCandidateRun(recordId, direction, {
return { runId, manifestRel };
}
+/**
+ * Build ONE approved direction the way the source-pipeline importer leaves it
+ * (#2895/#2984): the run under `<base>/<runId>/` with every embedded path
+ * anchored at the SOURCE repo root, no `id` field at all, and — unless
+ * `clip: false` — the `source-video.mp4` the importer now copies across.
+ *
+ * `declaredBase` differs from `base` to reproduce source-tree layout drift: the
+ * manifests say one run layout while the files sit under the other, and both
+ * spellings denote the same run.
+ */
+async function makeImportedDirection(recordId, direction, {
+ base = 'grok', declaredBase = base, clip = true, frameCount = 8, fps = 12,
+} = {}) {
+ const runId = `run-${(seq++).toString(16)}`;
+ const spriteRoot = join(TEST_ROOT, 'sprites', recordId);
+ const genAbs = join(spriteRoot, base, runId, 'generated');
+ await mkdir(genAbs, { recursive: true });
+ const anchor = (rel) => `art-source/sprites/${recordId}/${rel}`;
+ const declaredRun = `${declaredBase}/${runId}`;
+ const stripRel = `${declaredRun}/generated/${direction}-strip.png`;
+ const manifestRel = `${declaredRun}/generated/${direction}-manifest.json`;
+ const stripBytes = `imported-strip-${direction}`;
+ await writeFile(join(genAbs, `${direction}-strip.png`), stripBytes);
+ await writeFile(join(genAbs, `${direction}-manifest.json`), JSON.stringify({
+ schemaVersion: 1,
+ kind: 'deterministically-packaged-grok-walk-video',
+ characterId: recordId,
+ direction,
+ frameRate: fps,
+ frameCount,
+ stripPath: anchor(stripRel),
+ stripSha256: sha256(Buffer.from(stripBytes)),
+ }));
+ if (clip) await writeFile(join(genAbs, 'source-video.mp4'), 'IMPORTED-CLIP');
+ await writeFile(join(spriteRoot, base, runId, 'animation-run.json'), JSON.stringify({
+ kind: 'grok-walk-animation-run',
+ status: 'candidate',
+ characterId: recordId,
+ direction,
+ postprocessManifest: anchor(manifestRel),
+ sourceVideoPath: anchor(`${declaredRun}/generated/source-video.mp4`),
+ stripPreview: {
+ path: anchor(stripRel), frameCount, fps, cellWidth: 384, cellHeight: 384, row: 0, startColumn: 0,
+ },
+ }));
+ return {
+ runId,
+ entry: { status: 'approved', runPath: anchor(declaredRun), runManifest: anchor(manifestRel) },
+ };
+}
+
+// A finalized, imported character: `perDirection` maps each direction to its
+// makeImportedDirection options. Both the selection and the frozen walk set are
+// copied source-anchored, exactly as the importer leaves them.
+async function importedCharacter(id, perDirection) {
+ const walkDir = join(TEST_ROOT, 'sprites', id, 'walk');
+ await mkdir(walkDir, { recursive: true });
+ const directions = {};
+ const runIds = {};
+ for (const [direction, options] of Object.entries(perDirection)) {
+ const made = await makeImportedDirection(id, direction, options);
+ directions[direction] = made.entry;
+ runIds[direction] = made.runId;
+ }
+ await writeFile(join(walkDir, `${id}-walk-selection-v1.json`), JSON.stringify({
+ schemaVersion: 1,
+ kind: 'reviewed-directional-walk-selection',
+ characterId: id,
+ status: 'complete',
+ animationTargets: {},
+ directions,
+ }));
+ await writeFile(join(walkDir, `${id}-walk-set-v1.json`), JSON.stringify({
+ schemaVersion: 1,
+ kind: 'finalized-eight-direction-walk-set',
+ characterId: id,
+ status: 'final',
+ selectionPath: `art-source/sprites/${id}/walk/${id}-walk-selection-v1.json`,
+ directionOrder: SPRITE_DIRECTIONS,
+ directions,
+ }));
+ return runIds;
+}
+
beforeEach(() => {
executeTuiRun.mockClear();
executeTuiRun.mockImplementation(() => new Promise(() => {}));
@@ -775,6 +876,148 @@ describe('reopenWalkDirection', () => {
});
});
+/**
+ * #2993 — the un-finalize gate keys on EVIDENCE (is a clip on disk?), not on the
+ * set's imported-looking provenance. #2984 made the importer copy each run's
+ * source-video.mp4, so an imported direction with its clip present is exactly as
+ * re-derivable as a native one; only a direction with nothing behind it is the
+ * dead end the original blanket refusal was written for.
+ */
+describe('imported walk sets — evidence-based re-derive', () => {
+ it('unlocks an imported set whose direction still has its clip on disk', async () => {
+ const id = await characterWithLockedAnchors(newId(), ['east']);
+ const runIds = await importedCharacter(id, { east: {} });
+
+ const state = await unlockWalkSet(id);
+ expect(state.walkSet).toBeNull();
+ expect((await records.getRecord(id)).status).toBe('reference-complete');
+ // The imported run must survive losing its index entry — it lives in a
+ // directory the source pipeline named freely (`run-…`, not `walk-…`), so a
+ // name-prefix scan would have made it vanish exactly when it is needed.
+ const run = state.runs.find((r) => r.id === runIds.east);
+ expect(run.direction).toBe('east');
+ expect(run.sourceVideoPath).toBe(`grok/${runIds.east}/generated/source-video.mp4`);
+ expect(run.sourceClipMissing).toBeUndefined();
+ });
+
+ it('still refuses to unlock an imported set with no clip behind any direction', async () => {
+ const id = await characterWithLockedAnchors(newId(), ['east']);
+ await importedCharacter(id, { east: { clip: false } });
+ await expect(unlockWalkSet(id)).rejects.toMatchObject({
+ status: 409,
+ code: 'LEGACY_IMPORTED_WALK_SET',
+ message: expect.stringContaining('no source clip on disk'),
+ });
+ });
+
+ it('reopens the imported direction that has a clip and refuses the one that does not', async () => {
+ const id = await characterWithLockedAnchors(newId(), ['east']);
+ await importedCharacter(id, { east: {}, north: { clip: false } });
+
+ await expect(reopenWalkDirection(id, { direction: 'north' }))
+ .rejects.toMatchObject({ code: 'LEGACY_IMPORTED_WALK_SET' });
+
+ const state = await reopenWalkDirection(id, { direction: 'east' });
+ expect(state.walkSet).toBeNull();
+ expect(state.selection.directions.east).toBeUndefined();
+ expect(state.selection.directions.north.status).toBe('approved');
+ });
+
+ // The acceptance case: an imported 8-frame direction brought up to 12 with no
+ // new render call — and, because the run lives under `grok/`, without the
+ // regenerated frames or the rewritten record landing in a phantom `runs/` twin.
+ it('re-derives a grok/-layout imported run in place at the new set target', async () => {
+ const id = await characterWithLockedAnchors(newId(), ['east']);
+ const runIds = await importedCharacter(id, { east: {} });
+ await unlockWalkSet(id);
+ await setWalkTarget(id, { frameCount: 12, fps: 12 });
+
+ runWalkPostprocess.mockClear();
+ const run = await rerunWalkPostprocess(id, { runId: runIds.east });
+
+ expect(executeTuiRun).not.toHaveBeenCalled();
+ expect(runWalkPostprocess).toHaveBeenCalledWith(expect.objectContaining({
+ frameCount: 12,
+ runRel: `grok/${runIds.east}`,
+ videoAbs: join(TEST_ROOT, 'sprites', id, 'grok', runIds.east, 'generated', 'source-video.mp4'),
+ }));
+ expect(run.status).toBe('candidate');
+ expect(run.frameCount).toBe(12);
+ // The source anchor is replaced by the record-relative form on the way back
+ // to disk, in the directory the run actually came from.
+ expect(run.sourceVideoPath).toBe(`grok/${runIds.east}/generated/source-video.mp4`);
+ const savedAbs = join(TEST_ROOT, 'sprites', id, 'grok', runIds.east, 'animation-run.json');
+ expect(JSON.parse(await readFile(savedAbs, 'utf8'))).toMatchObject({ status: 'candidate', frameCount: 12 });
+ expect(existsSync(join(TEST_ROOT, 'sprites', id, 'runs'))).toBe(false);
+ });
+
+ // Source trees drift: a manifest can name `runs/<id>/…` for a clip stored under
+ // `grok/<id>/…`. Both spellings denote the same file, so the reader heals the
+ // path and the re-derive finds it — the importer already tolerates the same drift.
+ it('resolves a clip whose declared run layout differs from where it is stored', async () => {
+ const id = await characterWithLockedAnchors(newId(), ['east']);
+ const runIds = await importedCharacter(id, { east: { base: 'grok', declaredBase: 'runs' } });
+
+ const { runs } = await getWalkState(id);
+ expect(runs[0].sourceVideoPath).toBe(`grok/${runIds.east}/generated/source-video.mp4`);
+ expect(runs[0].sourceClipMissing).toBeUndefined();
+ await expect(reopenWalkDirection(id, { direction: 'east' })).resolves.toBeTruthy();
+ });
+
+ // "Declares a clip" and "has a clip" must not read the same: the flag is what
+ // lets the client offer reopen/reprocess only where they can actually work.
+ // The linkage to the atlas: re-deriving a direction and re-approving it
+ // rewrites its entry through PortOS's own approve path, which stores
+ // record-relative paths — so the direction stops being "still packaged by the
+ // source pipeline" and stops blocking the compile. That is what makes an
+ // imported set reachable at all: the refusal clears direction by direction as
+ // the user works through them, rather than only for a brand-new character.
+ it('drops a re-derived direction out of the set\'s imported provenance', async () => {
+ const id = await characterWithLockedAnchors(newId(), ['east']);
+ const runIds = await importedCharacter(id, { east: {} });
+ await unlockWalkSet(id);
+ await rerunWalkPostprocess(id, { runId: runIds.east });
+
+ const state = await approveWalkDirection(id, { direction: 'east', runId: runIds.east });
+ const entry = state.selection.directions.east;
+ expect(entry.runPath).toBe(`grok/${runIds.east}`);
+ expect(entry.runManifest).toBe(`grok/${runIds.east}/generated/manifest.json`);
+ expect(importedWalkDirections({ directions: state.selection.directions })).toEqual([]);
+ });
+
+ // The complement of the test above: re-approving an imported direction WITHOUT
+ // re-deriving it would launder the provenance (approve re-anchors the path it
+ // stores), leaving a set the atlas refuses with an unexplained sha mismatch.
+ // Approve refuses it up front instead, naming the reprocess as the remedy.
+ it('refuses to approve a run whose packaged frames were never written here', async () => {
+ const id = await characterWithLockedAnchors(newId(), ['east']);
+ const runIds = await importedCharacter(id, { east: {} });
+ const manifestAbs = join(
+ TEST_ROOT, 'sprites', id, 'grok', runIds.east, 'generated', 'east-manifest.json',
+ );
+ const manifest = JSON.parse(await readFile(manifestAbs, 'utf8'));
+ // The source pipeline's manifest lists its frames; the importer never copied
+ // the images themselves (it skips frames/ to minimize cross-machine copies).
+ manifest.frames = Array.from({ length: manifest.frameCount }, (_, i) => ({
+ path: `art-source/sprites/${id}/grok/${runIds.east}/generated/frames/f${i}.png`,
+ }));
+ await writeFile(manifestAbs, JSON.stringify(manifest));
+ await unlockWalkSet(id);
+
+ await expect(approveWalkDirection(id, { direction: 'east', runId: runIds.east }))
+ .rejects.toMatchObject({ status: 409, code: 'RUN_FRAMES_MISSING' });
+ });
+
+ it('flags a run whose declared clip is not on disk without dropping the path', async () => {
+ const id = await characterWithLockedAnchors(newId(), ['east']);
+ const runIds = await importedCharacter(id, { east: { clip: false } });
+
+ const { runs } = await getWalkState(id);
+ expect(runs[0].sourceClipMissing).toBe(true);
+ expect(runs[0].sourceVideoPath).toBe(`grok/${runIds.east}/generated/source-video.mp4`);
+ });
+});
+
describe('listSpriteAssets run-intermediate exclusion', () => {
it('omits raw extraction frames but keeps packaged frames and the review sheet', async () => {
const id = await characterWithLockedAnchors(newId(), []);