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

refactor([issue-3136]): derive what can be derived instead of declaring it on each track row

[._.]/ Adam Eivy3440410820ac
diff --git a/client/src/components/sprites/CorrectionNote.jsx b/client/src/components/sprites/CorrectionNote.jsx
index 4dea6ebbd1..f9c9a2b1da 100644
--- a/client/src/components/sprites/CorrectionNote.jsx
+++ b/client/src/components/sprites/CorrectionNote.jsx
@@ -23,8 +23,8 @@ import { useState } from 'react';
import { NotebookPen } from 'lucide-react';
export {
- anchorCorrectionKey, walkCorrectionKey, scannerCorrectionKey, trackCorrectionKey,
- MAIN_CORRECTION_KEY, AMBIENT_REFERENCE_CORRECTION_KEY, AMBIENT_LOOP_CORRECTION_KEY,
+ anchorCorrectionKey, walkCorrectionKey, trackCorrectionKey,
+ MAIN_CORRECTION_KEY, AMBIENT_REFERENCE_CORRECTION_KEY,
correctionPromptPayload,
} from '../../lib/spriteCorrections.js';
diff --git a/client/src/components/sprites/CorrectionNote.test.jsx b/client/src/components/sprites/CorrectionNote.test.jsx
index 5c57edb366..b60db1f562 100644
--- a/client/src/components/sprites/CorrectionNote.test.jsx
+++ b/client/src/components/sprites/CorrectionNote.test.jsx
@@ -4,8 +4,8 @@ import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import CorrectionNote, {
CorrectionNoteToggle, correctionPromptPayload,
- anchorCorrectionKey, walkCorrectionKey, scannerCorrectionKey,
- MAIN_CORRECTION_KEY, AMBIENT_REFERENCE_CORRECTION_KEY, AMBIENT_LOOP_CORRECTION_KEY,
+ anchorCorrectionKey, walkCorrectionKey, trackCorrectionKey,
+ MAIN_CORRECTION_KEY, AMBIENT_REFERENCE_CORRECTION_KEY,
} from './CorrectionNote.jsx';
// The shared anchor-correction module (#2964). `correctionPromptPayload` is the
@@ -49,10 +49,14 @@ describe('correction keys are namespaced per surface (#3134)', () => {
const keys = [
anchorCorrectionKey('east'),
walkCorrectionKey('east'),
- scannerCorrectionKey('east'),
+ // Any non-walk track's clip, for any facing (#3136) — one generic key
+ // replacing the per-track spellings.
+ trackCorrectionKey('scanner', 'east'),
+ trackCorrectionKey('ambient', 'south'),
+ // …and a track this build has never heard of gets a distinct key too.
+ trackCorrectionKey('jetpack', 'east'),
MAIN_CORRECTION_KEY,
AMBIENT_REFERENCE_CORRECTION_KEY,
- AMBIENT_LOOP_CORRECTION_KEY,
];
expect(new Set(keys).size).toBe(keys.length);
});
@@ -62,7 +66,7 @@ describe('correction keys are namespaced per surface (#3134)', () => {
expect(correctionPromptPayload(corrections, anchorCorrectionKey('east')))
.toEqual({ correctionPrompt: 'no pocket on the right sleeve' });
expect(correctionPromptPayload(corrections, walkCorrectionKey('east'))).toEqual({});
- expect(correctionPromptPayload(corrections, scannerCorrectionKey('east'))).toEqual({});
+ expect(correctionPromptPayload(corrections, trackCorrectionKey('scanner', 'east'))).toEqual({});
});
it('keeps each direction\'s walk note separate', () => {
diff --git a/client/src/components/sprites/PublishWorkflow.jsx b/client/src/components/sprites/PublishWorkflow.jsx
index 15ddc65d1c..37fac2d864 100644
--- a/client/src/components/sprites/PublishWorkflow.jsx
+++ b/client/src/components/sprites/PublishWorkflow.jsx
@@ -60,11 +60,9 @@ function ambientFrameCountOf(geometry) {
export default function PublishWorkflow({ record, walk, ambient, atlas, onChanged }) {
// `ambient` is the generic track state since #3136, whose finalized set is
- // `set` (the per-track `ambientSet` key went away with the clone). The old key
- // is still accepted so a caller that hasn't been updated — and any cached
- // pre-upgrade payload in flight — still reads as finalized rather than
- // silently re-offering an approve on a frozen loop.
- const finalized = Boolean(walk?.walkSet || ambient?.set || ambient?.ambientSet);
+ // `set` for every track (the per-track `ambientSet` key went away with the
+ // clone, and the client ships with the server that produces it).
+ const finalized = Boolean(walk?.walkSet || ambient?.set);
const current = atlas?.current || null;
const publications = atlas?.publications || [];
const saved = record.publishBinding || null;
diff --git a/client/src/components/sprites/PublishWorkflow.test.jsx b/client/src/components/sprites/PublishWorkflow.test.jsx
index 1054611bb1..f3240f0330 100644
--- a/client/src/components/sprites/PublishWorkflow.test.jsx
+++ b/client/src/components/sprites/PublishWorkflow.test.jsx
@@ -190,7 +190,7 @@ describe('PublishWorkflow runtime contract', () => {
<MemoryRouter>
<PublishWorkflow
record={{ id: 'example-tree', publishBinding: { appId: 'app-1', atlasDestPath: 'assets/tree.png', codeBinding: null } }}
- ambient={{ ambientSet: {} }}
+ ambient={{ set: {} }}
atlas={ambientAtlas}
onChanged={vi.fn()}
/>
diff --git a/client/src/components/sprites/TrackWorkflow.jsx b/client/src/components/sprites/TrackWorkflow.jsx
index a6fe2d306a..5ba44800f2 100644
--- a/client/src/components/sprites/TrackWorkflow.jsx
+++ b/client/src/components/sprites/TrackWorkflow.jsx
@@ -33,11 +33,12 @@ export default function TrackWorkflow({
const runs = state?.runs || [];
const selection = state?.selection || null;
const finalized = Boolean(state?.set);
+ const directional = Boolean(definition?.directional);
// A directional track fills one card per facing; a non-directional one is the
// single row 0. Derived from the row, not from the track's id.
const directions = useMemo(
- () => (definition?.directional ? SPRITE_DIRECTIONS : [SPRITE_DIRECTIONS[0]]),
- [definition?.directional],
+ () => (directional ? SPRITE_DIRECTIONS : [SPRITE_DIRECTIONS[0]]),
+ [directional],
);
const latestByDirection = useMemo(() => Object.fromEntries(directions.map((direction) => [
direction,
@@ -53,7 +54,7 @@ export default function TrackWorkflow({
const [approve, approving] = useAsyncAction(async (direction, runId) => {
await approveSpriteTrack(record.id, definition.id, { direction, runId }, { silent: true });
- toast.success(`${definition.label} ${directions.length > 1 ? `${direction} ` : ''}approved`);
+ toast.success(`${definition.label} ${directional ? `${direction} ` : ''}approved`);
onChanged();
}, { errorMessage: `${definition?.label || 'Track'} approval failed` });
@@ -66,8 +67,7 @@ export default function TrackWorkflow({
if (!definition || !reference?.manifest?.mainReference?.locked) return null;
const approvedCount = Object.values(selection?.directions || {})
.filter((entry) => entry?.status === 'approved').length;
- // The row's own bounds, so the summary can't drift from what the server clamps.
- const Icon = definition.directional ? Radio : Wind;
+ const Icon = directional ? Radio : Wind;
return (
<section className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">
@@ -81,14 +81,17 @@ export default function TrackWorkflow({
</h3>
<span className="text-[11px] text-gray-500">directly requested Grok render; local deterministic packing</span>
</div>
- <div className={`grid gap-2 ${directions.length > 1 ? 'sm:grid-cols-2 xl:grid-cols-4' : ''}`}>
+ <div className={`grid gap-2 ${directional ? 'sm:grid-cols-2 xl:grid-cols-4' : ''}`}>
{directions.map((direction) => {
const run = latestByDirection[direction];
const approved = selection?.directions?.[direction]?.status === 'approved';
const busy = ['rendering', 'postprocessing'].includes(run?.status);
const candidate = run?.status === 'candidate';
const preview = run?.stripPreview;
- const cardLabel = directions.length > 1 ? direction : `${definition.label} row 0`;
+ const cardLabel = directional ? direction : `${definition.label} row 0`;
+ // The shared page-owned corrections map's key for THIS card (#3134,
+ // generalized per track+facing in #3136).
+ const correctionKey = trackCorrectionKey(definition.id, direction);
return (
<article key={direction} className="rounded border border-port-border bg-port-bg p-2 space-y-2">
<div className="flex items-center justify-between gap-2">
@@ -116,7 +119,7 @@ export default function TrackWorkflow({
keyed per track+facing (#3136). */}
{onCorrectionChange && (
<CorrectionNoteToggle
- noteKey={trackCorrectionKey(definition.id, direction)}
+ noteKey={correctionKey}
label={`${cardLabel} ${definition.label.toLowerCase()}`}
corrections={corrections}
onChange={onCorrectionChange}
@@ -127,7 +130,16 @@ export default function TrackWorkflow({
<button
type="button"
disabled={busy}
- onClick={() => onGenerate(definition.id, direction)}
+ // Both the request `direction` (only a directional track
+ // sends one — a single-row track's facing is derived
+ // server-side) and the note key are decided HERE, where the
+ // definition and the facing already are, so the page's
+ // handler needs no per-track lookup and stays stable across
+ // the 4s poll that replaces `detail` wholesale.
+ onClick={() => onGenerate(definition.id, {
+ direction: directional ? direction : undefined,
+ correctionKey,
+ })}
className="flex-1 rounded border border-port-border px-2 py-1 text-xs text-gray-300 hover:border-port-accent disabled:opacity-50"
>
{busy ? <RefreshCw className="mx-auto w-3 h-3 animate-spin" /> : run?.status === 'error' ? 'Retry' : 'Generate'}
diff --git a/client/src/components/sprites/TrackWorkflow.test.jsx b/client/src/components/sprites/TrackWorkflow.test.jsx
index 397a9bd511..6d92048bab 100644
--- a/client/src/components/sprites/TrackWorkflow.test.jsx
+++ b/client/src/components/sprites/TrackWorkflow.test.jsx
@@ -56,6 +56,7 @@ const TRACKS = [
describe.each(TRACKS)('TrackWorkflow renders the $definition.id track from its definition', (track) => {
const { definition, facing, cardLabel } = track;
+ const { directional } = definition;
const candidateRun = {
id: `${definition.id}-${facing}-12345678`,
direction: facing,
@@ -83,8 +84,13 @@ describe.each(TRACKS)('TrackWorkflow renders the $definition.id track from its d
renderTrack(definition, {}, { onGenerate });
fireEvent.click(screen.getAllByRole('button', { name: 'Generate' })[0]);
// The track id rides along, which is what lets ONE page handler serve every
- // track — including one added after this build shipped.
- expect(onGenerate).toHaveBeenCalledWith(definition.id, 'south');
+ // track — including one added after this build shipped. So do the two things
+ // that need the definition: the request facing (omitted for a single-row
+ // track, whose row the server derives) and the correction-note key.
+ expect(onGenerate).toHaveBeenCalledWith(definition.id, {
+ direction: directional ? 'south' : undefined,
+ correctionKey: `${definition.id}:south`,
+ });
});
it('reviews a packaged candidate strip', () => {
@@ -169,7 +175,9 @@ describe('a track this client build has never heard of (#3136)', () => {
expect(screen.getByText('Jetpack burst')).toBeInTheDocument();
expect(screen.getByText(/0\/8 approved · 5f @ 8fps/)).toBeInTheDocument();
fireEvent.click(screen.getAllByRole('button', { name: 'Generate' })[0]);
- expect(onGenerate).toHaveBeenCalledWith('jetpack', 'south');
+ expect(onGenerate).toHaveBeenCalledWith('jetpack', {
+ direction: 'south', correctionKey: 'jetpack:south',
+ });
fireEvent.click(screen.getByRole('button', { name: 'Approve Jetpack burst east' }));
await waitFor(() => expect(approveSpriteTrack).toHaveBeenCalledWith(
'example-walker', 'jetpack', { direction: 'east', runId: 'jetpack-east-12345678' }, { silent: true },
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 9f0669c409..e87150cd12 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -143,7 +143,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `songPlayback.js` | `createLayeredPlayer(takes)` — decode N recorded vocal takes and start them together on one shared `AudioContext` so they stack into a layered a cappella performance (sample-aligned, per-layer mute). Used by the Song editor's recording mixer. |
| `songProgress.js` | Pure training-progress core for the song system's memorize/learn/track mode. `deriveTrainingSections(score, lyricSections?)` slices a lead-sheet score into blank-line-separated trainable sections (each a self-contained header+block score, positional stable id, lyric-matched label); `recordAttempt(progress, scope, summary)` appends a graded take to a scope's bounded rolling history (drops zero-note takes); `scopeStats(progress, scope)`/`wholeSongStats` derive `{ attempts, best, average, last, streak, learned }` (learned = streak of ≥`LEARNED_PERCENT` takes ≥`LEARNED_STREAK`); `weakestSections(progress, sections)` ranks weak/un-attempted sections for spaced-repetition; `memorizationPercent` is the learned-section share; `hideLevelFor(average)` maps a rolling average to a progressive lyric/note-hiding level (`show`/`dim`/`hide`/`blind`). No React/audio — `useSongTraining` drives it. |
| `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). Each actionable regenerate also names the `correctionKey` (#3134) the card binds its inline correction note to — `walk:<dir>` for a walk output, the bare direction for an anchor — so the card can never write a still-image note into a video re-roll. Pure — takes callbacks, performs no I/O. Consumes the facets from `spriteFacets.js` and the key vocabulary from `spriteCorrections.js`. |
-| `spriteCorrections.js` | The Sprite Manager's correction-note key vocabulary + request fragment (#2964, extended to every regeneration surface by #3134). Every re-roll surface writes into ONE page-owned `corrections` map (`Sprites.jsx`); this module owns its keys so the pure gating layer (`spriteCollectionActions.js`) and the React surfaces (`CorrectionNote.jsx` + hosts) agree without the pure layer importing a component. Keys are namespaced per SURFACE, not per direction — `anchorCorrectionKey(dir)` keeps the bare direction (pre-#3134 state untouched) while `walkCorrectionKey(dir)` / `MAIN_CORRECTION_KEY` / `AMBIENT_REFERENCE_CORRECTION_KEY` prefix, so a still-image anchor note can never ride a walk-VIDEO re-roll. `trackCorrectionKey(trackId, dir)` (#3136) generalizes what the scanner/ambient keys each spelled by hand, so a user-defined animation track gets a namespaced key with nothing to add here; `scannerCorrectionKey(dir)` and `AMBIENT_LOOP_CORRECTION_KEY` are readability aliases over it. `correctionPromptPayload(corrections, key)` → `{ correctionPrompt }` only when the note is non-empty after trimming, else `{}` — the guarantee that a blank note leaves the server prompt byte-identical to a blind regenerate. Pure — no React, no I/O. |
+| `spriteCorrections.js` | The Sprite Manager's correction-note key vocabulary + request fragment (#2964, extended to every regeneration surface by #3134). Every re-roll surface writes into ONE page-owned `corrections` map (`Sprites.jsx`); this module owns its keys so the pure gating layer (`spriteCollectionActions.js`) and the React surfaces (`CorrectionNote.jsx` + hosts) agree without the pure layer importing a component. Keys are namespaced per SURFACE, not per direction — `anchorCorrectionKey(dir)` keeps the bare direction (pre-#3134 state untouched) while `walkCorrectionKey(dir)` / `MAIN_CORRECTION_KEY` / `AMBIENT_REFERENCE_CORRECTION_KEY` prefix, so a still-image anchor note can never ride a walk-VIDEO re-roll. `trackCorrectionKey(trackId, dir)` (#3136) replaces the per-track keys the scanner/ambient surfaces each spelled by hand, so a user-defined animation track gets a namespaced key with nothing to add here. `correctionPromptPayload(corrections, key)` → `{ correctionPrompt }` only when the note is non-empty after trimming, else `{}` — the guarantee that a blank note leaves the server prompt byte-identical to a blind regenerate. Pure — no React, no I/O. |
| `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 — it does NOT render a `manifest` group: each runtime atlas's sidecar manifest is folded onto its atlas row as `row.manifest`, and other behind-the-scenes JSON is omitted. `runtimeVersionDir(path)` / `isRuntimeVersionPath(path)` / `isRuntimeSidecarManifest(path)` expose the `runtime/vN` grammar (the sidecar-pairing key and the "is this a build manifest" predicate) so callers like `AssetInspector` reuse one definition instead of re-regexing. 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 }` — 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). Also holds the walk-cycle authoring knobs mirrored from `walkBounds.js` — `WALK_DEFAULT_FRAME_COUNT` / `WALK_DEFAULT_FPS`, the `WALK_FRAME_COUNT_OPTIONS` list and `walkFpsOptionsFor(fps)` (splices a current odd fps into the even-step list so the `<select>` never lies) — feeding the shared `CycleTarget` control used by both the walk workflow and the trimmer's re-derive panel (#2980). Pure — no React, no canvas, no I/O. |
diff --git a/client/src/lib/spriteCorrections.js b/client/src/lib/spriteCorrections.js
index ed406b1063..d697e1238e 100644
--- a/client/src/lib/spriteCorrections.js
+++ b/client/src/lib/spriteCorrections.js
@@ -30,27 +30,20 @@ export const walkCorrectionKey = (direction) => `walk:${direction}`;
/**
* Any non-walk animation track's clip, for one facing (#3136).
*
- * Generalizes what `scanner:<dir>`/`ambient-loop` each spelled by hand, so a
- * user-defined track's note gets a namespaced key with nothing to add here. The
- * facing is part of the key for the same reason it is for walk: a directional
- * track's eight clips are eight separate re-rolls, and a note about one must not
- * ride the next.
+ * Replaces the per-track keys (`scanner:<dir>`, `ambient-loop`) each surface used
+ * to spell by hand, so a user-defined track's note gets a namespaced key with
+ * nothing to add here. The facing is part of the key for the same reason it is
+ * for walk: a directional track's clips are separate re-rolls, and a note about
+ * one must not ride the next; a non-directional track's single row resolves to
+ * one value.
*
* Deliberately NOT byte-compatible with the two old keys — `corrections` is
* transient page state (typed in this session, never persisted), so there is no
- * stored note to migrate; the aliases below exist for call-site readability, not
- * for on-disk compatibility.
+ * stored note to migrate.
*/
export const trackCorrectionKey = (trackId, direction) => `${trackId}:${direction}`;
-/** The scanner action video for a direction. */
-export const scannerCorrectionKey = (direction) => trackCorrectionKey('scanner', direction);
/** A place/object's at-rest identity still. */
export const AMBIENT_REFERENCE_CORRECTION_KEY = 'ambient-reference';
-/**
- * A place/object's image-to-video ambient loop. Its facing is the single row 0,
- * so the generic key resolves to one value rather than eight.
- */
-export const AMBIENT_LOOP_CORRECTION_KEY = trackCorrectionKey('ambient', 'south');
/**
* Build the re-roll request fragment for one correction key. Returns
diff --git a/client/src/pages/Sprites.jsx b/client/src/pages/Sprites.jsx
index 56e2bbe6b4..77ba31d182 100644
--- a/client/src/pages/Sprites.jsx
+++ b/client/src/pages/Sprites.jsx
@@ -20,7 +20,7 @@ import LoopTrimmer from '../components/sprites/LoopTrimmer.jsx';
import PublishWorkflow from '../components/sprites/PublishWorkflow.jsx';
import AssetCollection from '../components/sprites/AssetCollection.jsx';
import {
- correctionPromptPayload, anchorCorrectionKey, walkCorrectionKey, trackCorrectionKey,
+ correctionPromptPayload, anchorCorrectionKey, walkCorrectionKey,
AMBIENT_REFERENCE_CORRECTION_KEY,
} from '../components/sprites/CorrectionNote.jsx';
import SpriteCatalog from '../components/sprites/SpriteCatalog.jsx';
@@ -586,19 +586,23 @@ export default function Sprites() {
// reservation (both can legitimately be authored at once), and each owns its
// short default source clip rather than inheriting the walk duration picker.
// The immediate refetch persists the observable TUI run for polling.
- const generateTrack = useCallback(async (trackId, direction) => {
+ // The caller supplies both the request `direction` (present only for a
+ // directional track) and the `correctionKey` for the card that was clicked —
+ // TrackWorkflow already holds the definition and the facing, so deciding both
+ // there keeps this handler dependency-light and therefore stable across the 4s
+ // detail poll, which replaces `detail` wholesale and would otherwise churn
+ // every memoized track section.
+ const generateTrack = useCallback(async (trackId, { direction, correctionKey }) => {
try {
await generateSpriteTrack(id, trackId, {
- // A non-directional track derives row 0 server-side; sending its facing
- // anyway would be a value the server must then agree with.
- ...(direction && detail?.tracks?.[trackId]?.definition?.directional ? { direction } : {}),
- ...correctionPromptPayload(corrections, trackCorrectionKey(trackId, direction)),
+ ...(direction ? { direction } : {}),
+ ...correctionPromptPayload(corrections, correctionKey),
}, { silent: true });
onWorkflowChanged();
} catch (err) {
toast.error(err?.message || `Failed to queue the ${trackId} render`);
}
- }, [id, corrections, onWorkflowChanged, detail?.tracks]);
+ }, [id, corrections, onWorkflowChanged]);
// The ambient main takes BOTH inputs: `designPrompt` replaces the design
// outright, while the correction (#3134) keeps it and fixes one thing about
diff --git a/docs/features/sprite-export-contract.md b/docs/features/sprite-export-contract.md
index 7dfc1aeb95..5f9539aace 100644
--- a/docs/features/sprite-export-contract.md
+++ b/docs/features/sprite-export-contract.md
@@ -112,7 +112,7 @@ Column layout is the one thing an app genuinely has to agree with PortOS about.
Two mechanisms guard that:
-- **`publishBinding.runtimeContract`** (optional): `{ walkFrameCount?, scannerFrameCount?, ambientFrameCount?, cellSize?, columnCount? }` — the grid the app was built against. A contract names either `walkFrameCount` or `ambientFrameCount` (and may include the other spans); set it from the **Runtime contract** group in the publish binding form or via `PUT /api/sprites/:id/publish-binding` directly. Publishing an atlas whose compiled geometry disagrees fails with a **409** naming both the actual and expected numbers and both resolutions (change the app's constant, or reprocess the relevant set). A binding with no contract publishes unchecked, exactly as before the field existed.
+- **`publishBinding.runtimeContract`** (optional): `{ <track>FrameCount?…, cellSize?, columnCount? }` — the grid the app was built against, with one optional key per registered animation track (`walkFrameCount`, `scannerFrameCount`, `ambientFrameCount` today). A contract must name the record kind's **baseline** track — `walkFrameCount` for a character, `ambientFrameCount` for a place/object — since that is the set the compiler requires before it emits an atlas at all; other tracks' spans are optional additions. set it from the **Runtime contract** group in the publish binding form or via `PUT /api/sprites/:id/publish-binding` directly. Publishing an atlas whose compiled geometry disagrees fails with a **409** naming both the actual and expected numbers and both resolutions (change the app's constant, or reprocess the relevant set). A binding with no contract publishes unchecked, exactly as before the field existed.
- **The sidecar**, so an app that reads it can fail loudly on its own terms instead of relying on PortOS to have been asked.
`runtimeContract` follows absent-vs-null semantics: a saved binding that omits the key inherits the stored contract (saving the form with the contract group untouched omits it, so the stored contract survives an unrelated edit), while an explicit `null` — what the form's "Clear" sends — clears it. The inheritance is scoped to the same `appId` — re-pointing a character at a different app drops the old app's contract rather than holding the new one to it.
@@ -125,7 +125,7 @@ Two mechanisms guard that:
|---|---|
| `server/services/sprites/atlas.js` | Compiles the atlas; owns the geometry block and the pre-pixel up-to-date check |
| `server/services/sprites/atlasGrid.js` | The grid itself: column spans and row spans per track, within-track uniformity, reading a persisted (or legacy) grid back |
-| `server/services/sprites/animationTracks.js` | One row per animation track — its bounds, defaults, directionality, which record kinds may carry it, and the workflow shape (source reference, on-disk set/selection kinds) |
+| `server/services/sprites/animationTracks.js` | One row per animation track — its bounds, defaults, directionality, which record kinds may carry it, its on-disk set/selection kinds, and whether it is the kind's publishable baseline (`standaloneContract`) |
| `server/services/sprites/animationTrackWorkflow.js` | The ONE generate/package/review/approve implementation every non-walk track runs, parameterized by its registry row |
| `server/services/sprites/trackPrompts.js` | Resolves a track id to its image-to-video prompt builder |
| `server/services/sprites/reference.js` | The two animation gates: `requireCharacter` (walk workflow) and `requireAnimatable` (compile/publish) |
diff --git a/server/lib/validation.js b/server/lib/validation.js
index c0df476e95..28939a03fe 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -6,7 +6,7 @@ import { SPRITE_ID_PATTERN, SPRITE_RECORD_KINDS } from '../services/sprites/reco
import { ANCHOR_DIRECTIONS, SPRITE_DIRECTIONS, TURNAROUND_ID } from '../services/sprites/prompts.js';
import { CHROMA_KEY_HEXES } from '../services/sprites/chromaKey.js';
import {
- WALK_TRACK, ANIMATION_TRACK_IDS, getAnimationTrack, tracksForKind,
+ WALK_TRACK, ANIMATION_TRACK_IDS, getAnimationTrack,
} from '../services/sprites/animationTracks.js';
import { QUEUEABLE_IMAGE_MODES } from '../services/imageGen/modes.js';
import { GROK_VIDEO_DURATIONS } from './grokVideoClip.js';
@@ -1061,23 +1061,13 @@ const spriteTrackContractFields = Object.fromEntries(
// The tracks whose frame count is enough ON ITS OWN to make a contract
// meaningful — a record can't be published without one of these authored, so a
-// contract that pins none of them describes no atlas that could ever exist.
-//
-// The discriminator is PRIMACY: a track is primary when it is the first
-// registered track for at least one record kind it supports. Walk is a
-// character's primary (`tracksForKind('character')` leads with it) and ambient is
-// a place/object's; scanner is a character's SECOND track — a short action that
-// always rides beside the walk it shares a row with, so `scannerFrameCount`
-// alone was never a publishable contract. That reproduces the historical
-// "walkFrameCount or ambientFrameCount" rule exactly while staying true for a
-// user-defined track: one that unlocks a new record kind becomes that kind's
-// primary and joins this set, and a second action on an existing kind doesn't.
-//
-// It also matches the compile side, which requires the primary track's finalized
-// set before it will emit an atlas at all (`atlas.js` — a walk set for a
-// character, an ambient set for a place).
+// contract that pins none of them describes no atlas that could ever exist. The
+// registry DECLARES this per row (`standaloneContract`), which reproduces the
+// historical "walkFrameCount or ambientFrameCount" rule and stays correct for a
+// user-defined track. It is the same field `atlas.js` dispatches its compile
+// evidence chain on, so publish validation and compile can't disagree.
const SPRITE_STANDALONE_CONTRACT_FIELDS = ANIMATION_TRACK_IDS
- .filter((id) => getAnimationTrack(id).kinds.some((kind) => tracksForKind(kind)[0]?.id === id))
+ .filter((id) => getAnimationTrack(id).standaloneContract)
.map((id) => getAnimationTrack(id).contractFrameCountField);
export const spriteRuntimeContractSchema = z.object({
@@ -1259,14 +1249,29 @@ export const spriteWalkGenerateSchema = z.object({
// through without a facing — that check reads the same registry the bounds
// came from, rather than being restated as a second enum.
// - the remaining knobs are already registry-derived.
+const buildSpriteTrackGenerateSchema = (track) => z.object({
+ direction: spriteWalkDirectionSchema.optional(),
+ duration: grokVideoDurationSchema.optional(),
+ frameCount: spriteTrackFrameCountSchema(track).optional(),
+ fps: spriteTrackFpsSchema(track).optional(),
+ correctionPrompt: z.string().max(4000).optional(),
+});
+
+// One schema per registered track, built at module load — the same
+// derive-from-the-registry idiom `spriteTrackContractFields` uses, rather than
+// re-allocating six Zod objects on every generate request.
+const SPRITE_TRACK_GENERATE_SCHEMAS = Object.fromEntries(
+ ANIMATION_TRACK_IDS.map((id) => [id, buildSpriteTrackGenerateSchema(id)]),
+);
+
+/**
+ * The generate schema for one track. Unregistered ids build on demand so the
+ * unknown-track error still comes from `getAnimationTrack` (naming the known
+ * tracks) rather than reading as "no schema" — though the route validates
+ * `trackId` against the registry first, so that path is defense in depth.
+ */
export function spriteTrackGenerateSchema(track) {
- return z.object({
- direction: spriteWalkDirectionSchema.optional(),
- duration: grokVideoDurationSchema.optional(),
- frameCount: spriteTrackFrameCountSchema(track).optional(),
- fps: spriteTrackFpsSchema(track).optional(),
- correctionPrompt: z.string().max(4000).optional(),
- });
+ return SPRITE_TRACK_GENERATE_SCHEMAS[track] || buildSpriteTrackGenerateSchema(track);
}
export const spriteTrackApproveSchema = z.object({
diff --git a/server/routes/sprites.js b/server/routes/sprites.js
index 557217771b..f00552f003 100644
--- a/server/routes/sprites.js
+++ b/server/routes/sprites.js
@@ -169,23 +169,22 @@ router.get('/:id', asyncHandler(async (req, res) => {
// as `kind === 'character'` would have left the UI blank for exactly the
// records the registry had just admitted.
const { kind } = detail.record;
+ const kindTracks = tracksForKind(kind);
const runsWalk = kindSupportsTrack(kind, WALK_TRACK);
// Every non-walk track this record's kind may carry, resolved from the registry
// (#3136) instead of one hand-written `runsScanner`/`runsAmbient` flag per
- // track. `definition` rides along so the client renders a track's label and
- // bounds from the row rather than mirroring them as component copy — which is
- // what lets ONE workflow component serve a track the client has never heard of.
- const genericTracks = tracksForKind(kind).filter((row) => row.id !== WALK_TRACK);
+ // track. Each state carries its own `definition` (the registry row), so the
+ // client renders a track's label, facing count and bounds from data rather than
+ // mirroring them as component copy — which is what lets ONE workflow component
+ // serve a track the client has never heard of.
+ const genericTracks = kindTracks.filter((row) => row.id !== WALK_TRACK);
const [reference, walk, atlas, ...trackStates] = await Promise.all([
- tracksForKind(kind).length ? getReferenceSet(req.params.id) : null,
+ kindTracks.length ? getReferenceSet(req.params.id) : null,
runsWalk ? getWalkState(req.params.id) : null,
- tracksForKind(kind).length ? getAtlasState(req.params.id) : null,
+ kindTracks.length ? getAtlasState(req.params.id) : null,
...genericTracks.map((row) => getTrackState(row.id, req.params.id)),
]);
- const tracks = Object.fromEntries(genericTracks.map((row, index) => [
- row.id,
- { ...trackStates[index], definition: row },
- ]));
+ const tracks = Object.fromEntries(genericTracks.map((row, index) => [row.id, trackStates[index]]));
res.json({ ...detail, reference, walk, tracks, atlas });
}));
diff --git a/server/routes/sprites.test.js b/server/routes/sprites.test.js
index 397274bd23..715f434401 100644
--- a/server/routes/sprites.test.js
+++ b/server/routes/sprites.test.js
@@ -72,7 +72,12 @@ vi.mock('../services/sprites/walk.js', () => ({
// `/:id/tracks/:trackId/*` routes drive, echoing the track it was asked for so a
// test can assert the route resolved the right one.
vi.mock('../services/sprites/animationTrackWorkflow.js', () => ({
- getTrackState: vi.fn(async (track) => ({ track, runs: [], selection: null, set: null })),
+ // The service owns `definition` (the registry row it resolved), so the mock
+ // supplies a stand-in rather than the route re-attaching it — that split is
+ // what the GET assertion below is checking.
+ getTrackState: vi.fn(async (track) => ({
+ track, definition: { id: track, directional: track === 'scanner' }, runs: [], selection: null, set: null,
+ })),
startTrackGeneration: vi.fn(async (track) => ({ runId: `${track}-east-0a1b2c3d`, direction: 'east', duration: 6 })),
approveTrackRun: vi.fn(async (track) => ({ track, runs: [], selection: { status: 'in-progress' }, set: null })),
}));
@@ -453,12 +458,13 @@ describe('sprites routes', () => {
expect(r.body.walk).toEqual({ runs: [], selection: null, walkSet: null });
expect(walk.getWalkState).toHaveBeenCalledWith('pioneer');
// A character carries scanner but NOT ambient, so only scanner is keyed —
- // and the payload carries the registry row so the client renders the track's
- // label/bounds from data rather than mirroring them.
+ // and each state passes through with the `definition` (registry row) the
+ // service resolved, so the client renders the track's label/bounds from data
+ // rather than mirroring them.
expect(Object.keys(r.body.tracks)).toEqual(['scanner']);
expect(r.body.tracks.scanner).toMatchObject({
track: 'scanner', runs: [], selection: null, set: null,
- definition: { id: 'scanner', label: 'Scanner action', directional: true },
+ definition: { id: 'scanner', directional: true },
});
expect(trackWorkflow.getTrackState).toHaveBeenCalledWith('scanner', 'pioneer');
diff --git a/server/services/sprites/animationTrackWorkflow.js b/server/services/sprites/animationTrackWorkflow.js
index 2bad994e71..37b108424c 100644
--- a/server/services/sprites/animationTrackWorkflow.js
+++ b/server/services/sprites/animationTrackWorkflow.js
@@ -22,6 +22,10 @@
* and set-level targets that no other track has, and folding those in would make
* this module the union of every track's features rather than their intersection.
*
+ * Note `sourceReference` is DERIVED (`sourceReferenceFor`) rather than a row
+ * field: only one pairing with `directional` can work, so declaring it would let
+ * a row claim a combination that renders the same clip for every facing.
+ *
* **On-disk compatibility is exact, not approximate.** Every path, `kind`
* string, run field, error code and message this writes is byte-identical to
* what the two clones wrote, because installs already hold approved scanner sets
@@ -45,40 +49,38 @@ import { resolveGrokDuration } from '../../lib/grokVideoClip.js';
import { getSettings } from '../settings.js';
import { getRecord } from './records.js';
import { requireTrack, loadManifest } from './reference.js';
-import { SPRITE_DIRECTIONS, anchorIdForDirection } from './prompts.js';
+import { anchorIdForDirection } from './prompts.js';
import { buildTrackVideoPrompt } from './trackPrompts.js';
-import { clampTrackFrameCount, clampTrackFps, getAnimationTrack } from './animationTracks.js';
+import { clampTrackFrameCount, clampTrackFps, getAnimationTrack, sourceReferenceFor } from './animationTracks.js';
+import { trackDirections } from './atlasGrid.js';
import { spriteDir, resolveSpriteAssetPath, SOURCE_CLIP_NAME } from './paths.js';
import { prepareWalkAnchorChromaInput, runWalkPostprocess } from './walkPostprocess.js';
import { verifyPackagedFrames } from './walkFrames.js';
-import { resolveChromaKey, withAnimationWriteTail } from './animationWorkflow.js';
+import {
+ resolveChromaKey, withAnimationWriteTail, lockedAnchorFor, lockedMainFor,
+ GROK_TUI_IDLE_MS, GROK_TUI_TIMEOUT_MS, grokTuiProvider, buildGrokI2vTask,
+} from './animationWorkflow.js';
const RUN_RECORD_NAME = 'animation-run.json';
-const TUI_IDLE_MS = 90_000;
-const TUI_TIMEOUT_MS = 30 * 60_000;
/**
- * The single atlas row a non-directional track occupies.
+ * The facings a track is authored across: every direction for a directional
+ * track, the single row 0 for a non-directional one.
*
- * Row 0 of the grid is `SPRITE_DIRECTIONS[0]`, and `trackDirections()` already
- * slices exactly that entry for a non-directional track — so this reads the
- * facing list rather than restating `'south'`, keeping the authoring side and
- * the compile side derived from one list. The ambient clone hardcoded the
- * literal; the value is identical.
+ * `trackDirections` (atlasGrid) is the ONE definition of that slice, shared with
+ * the compiler — which matters because the count decides both when a set freezes
+ * (and what `directionOrder` it writes) and how many rows the compiler will
+ * accept. Two derivations of one registry field is exactly the drift
+ * `trackDirections`'s own header says it exists to prevent.
*/
-const nonDirectionalRow = () => SPRITE_DIRECTIONS[0];
+export const trackAuthoringDirections = (trackId) => trackDirections(trackId);
/**
- * The facings a track is authored across: every direction for a directional
- * track, the single row 0 for a non-directional one. This is the authoring twin
- * of `atlasGrid.trackDirections` — kept here rather than imported because
- * atlasGrid reaches the grid/compile layer, and the authoring side needs only
- * the registry's `directional` flag.
+ * The one facing a non-directional track is authored at — its own single row,
+ * read off the same slice rather than restated as `'south'`, so the authoring
+ * side and the compiled grid can never disagree about which row that is.
*/
-export function trackAuthoringDirections(trackId) {
- const row = getAnimationTrack(trackId);
- return row.directional ? [...SPRITE_DIRECTIONS] : [nonDirectionalRow()];
-}
+const soleDirectionOf = (trackId) => trackAuthoringDirections(trackId)[0];
// The on-disk layout, per track. `<track>/` subdirectory and `-<track>-` infix,
// which is exactly what scanner.js and ambient.js each spelled for themselves.
@@ -127,52 +129,62 @@ async function trackRuns(trackId, recordId) {
}
/**
- * The track's authoring state: `{ track, bounds, selection, set, runs }`.
+ * The track's authoring state: `{ track, definition, selection, set, runs }`.
*
- * `set` is the generic key. The route layer additionally aliases it to the
- * historical per-track key (`scannerSet` / `ambientSet`) so an existing client
- * keeps reading the field it always did — see `routes/sprites.js`.
+ * `definition` is the registry row, shipped so the client renders the track's
+ * label, facing count, and bounds from data instead of mirroring them as
+ * component copy — that is what lets one component serve a track it has never
+ * heard of. `set` is the finalized-set key for every track; the old per-track
+ * spellings (`scannerSet`/`ambientSet`) went away with the clones.
*/
export async function getTrackState(trackId, recordId) {
const row = getAnimationTrack(trackId);
const [selection, set, runs] = await Promise.all([
loadSelection(row.id, recordId), loadSet(row.id, recordId), trackRuns(row.id, recordId),
]);
- return { track: row.id, bounds: row, selection, set, runs };
+ return { track: row.id, definition: row, selection, set, runs };
}
/**
- * The locked reference image this track's render is seeded from, or null.
+ * Everything about the locked reference this track's render is seeded from — both
+ * when it exists and when it doesn't.
+ *
+ * ONE resolver so no caller ever branches on the source shape again. It returns
+ * the artifact's `label`, the error `code`s to use when it isn't locked or has
+ * vanished from disk, and — when it IS locked — its `path`/`sha256`/`inputName`.
+ * Returning the label and codes unconditionally is the point: the "lock it first"
+ * 409 and the "missing on disk" 500 both need to name the artifact the row asked
+ * for, and re-deriving that name at each throw site is how three of them ended up
+ * spelling the anchor's name three different ways.
*
- * Two shapes behind one resolver so the caller never branches on
- * `sourceReference`: a directional track reads THIS facing's locked anchor, a
- * non-directional one reads the single locked main. `label` is what the
- * "lock it first" 409 names, so the message points at the artifact the row
- * actually asked for.
+ * `locked` is the sentinel: absent means nothing is frozen yet, which is a
+ * different answer from "frozen but gone", handled by the caller's disk check.
*/
-function lockedSourceFor(row, manifest, direction) {
- if (row.sourceReference === 'main') {
- const main = manifest?.mainReference;
- return main?.locked && main.path
- ? { path: main.path, sha256: main.sha256 || null, label: 'main reference', inputName: 'input-main-chroma.png' }
- : null;
+function trackSourceFor(row, manifest, direction) {
+ if (sourceReferenceFor(row.id) === 'main') {
+ const main = lockedMainFor(manifest);
+ return {
+ label: 'main reference',
+ notLockedCode: 'MAIN_NOT_LOCKED',
+ missingCode: 'MAIN_REFERENCE_MISSING',
+ inputName: 'input-main-chroma.png',
+ locked: main ? { path: main.path, sha256: main.sha256 || null } : null,
+ };
}
- const anchor = manifest?.anchors?.find((item) => item.direction === direction);
- return anchor?.status === 'locked' && anchor.path
- ? {
- path: anchor.path,
- sha256: anchor.sha256 || null,
- label: `${anchorIdForDirection(direction)} anchor`,
- inputName: 'input-anchor-chroma.png',
- }
- : null;
+ const anchor = lockedAnchorFor(manifest, direction);
+ return {
+ label: `${anchorIdForDirection(direction)} anchor`,
+ notLockedCode: 'ANCHOR_NOT_LOCKED',
+ missingCode: 'ANCHOR_MISSING',
+ inputName: 'input-anchor-chroma.png',
+ locked: anchor ? { path: anchor.path, sha256: anchor.sha256 || null } : null,
+ };
}
-// The provider task wrapper — identical in both clones, verbatim.
-const trackTask = ({ prompt, inputAbs, videoAbs, duration }) => (
- `${prompt}\n\nUse your built-in image_to_video tool to animate this exact image for ${duration} seconds:\n${inputAbs}\n\n`
- + `Save the resulting animation as an MP4 file at exactly this path:\n${videoAbs}\n\n`
- + 'Do not create or modify any other files, and do not run any tools beyond what is needed to render and save that MP4.'
+/** The 409 for a render/approval whose source reference isn't frozen yet. */
+const notLockedError = (source, row, verb) => new ServerError(
+ `Lock the ${source.label} before ${verb} its ${row.label.toLowerCase()}`,
+ { status: 409, code: source.notLockedCode },
);
export function startTrackGeneration(trackId, recordId, body) {
@@ -188,14 +200,9 @@ async function startTrackGenerationImpl(trackId, recordId, body) {
// A non-directional track occupies exactly row 0, so its facing is derived
// from the registry rather than accepted from the request — no user-supplied
// direction can drift from what `trackDirections()` will later compile.
- const direction = row.directional ? body.direction : nonDirectionalRow();
- const source = lockedSourceFor(row, reference, direction);
- if (!source) {
- throw new ServerError(
- `Lock the ${source?.label || (row.sourceReference === 'main' ? 'main reference' : `${anchorIdForDirection(direction)} anchor`)} before generating its ${row.label.toLowerCase()}`,
- { status: 409, code: row.sourceReference === 'main' ? 'MAIN_NOT_LOCKED' : 'ANCHOR_NOT_LOCKED' },
- );
- }
+ const direction = row.directional ? body.direction : soleDirectionOf(row.id);
+ const source = trackSourceFor(row, reference, direction);
+ if (!source.locked) throw notLockedError(source, row, 'generating');
const chromaKey = resolveChromaKey({ manifest: reference, record });
if (!chromaKey) throw new ServerError('No frozen chroma key is available for this sprite', { status: 409, code: 'CHROMA_KEY_REQUIRED' });
// In-flight guard, per facing for a directional track and per record for a
@@ -225,11 +232,11 @@ async function startTrackGenerationImpl(trackId, recordId, body) {
const runRel = runRelPath(runId);
const generatedAbs = join(spriteDir(recordId), runRel, 'generated');
await ensureDir(generatedAbs);
- const sourceAbs = resolveSpriteAssetPath(recordId, source.path);
+ const sourceAbs = resolveSpriteAssetPath(recordId, source.locked.path);
if (!await pathExists(sourceAbs)) {
throw new ServerError(
`Locked ${source.label} file is missing on disk`,
- { status: 500, code: row.sourceReference === 'main' ? 'MAIN_REFERENCE_MISSING' : 'ANCHOR_MISSING' },
+ { status: 500, code: source.missingCode },
);
}
const inputAbs = join(generatedAbs, source.inputName);
@@ -255,8 +262,8 @@ async function startTrackGenerationImpl(trackId, recordId, body) {
// `anchorPath`/`anchorSha256` name the SOURCE reference whatever it was —
// the ambient clone already used these keys for the main reference, and the
// approve gate's staleness check reads them, so the spelling stays.
- anchorPath: source.path,
- anchorSha256: source.sha256 || await sha256File(sourceAbs),
+ anchorPath: source.locked.path,
+ anchorSha256: source.locked.sha256 || await sha256File(sourceAbs),
animationInputPath: `${runRel}/generated/${source.inputName}`,
animationInputSha256: inputSha256,
animationInputPreparation: preparation,
@@ -270,7 +277,7 @@ async function startTrackGenerationImpl(trackId, recordId, body) {
generatedAbs,
videoAbs,
grokPath: settings.imageGen?.grok?.grokPath,
- task: trackTask({
+ task: buildGrokI2vTask({
prompt: buildTrackVideoPrompt(row.id, {
name: record.name, kind: record.kind, direction, chromaKey, correctionPrompt,
}),
@@ -288,11 +295,11 @@ async function startTrackGenerationImpl(trackId, recordId, body) {
async function runTrackTuiRender(row, recordId, { runId, direction, generatedAbs, videoAbs, grokPath, task }) {
await executeTuiRun({
runId,
- provider: { id: GROK_TUI_ID, type: 'tui', command: grokPath || 'grok', args: [] },
+ provider: grokTuiProvider(grokPath),
prompt: task,
workspacePath: generatedAbs,
- idleMs: TUI_IDLE_MS,
- timeout: TUI_TIMEOUT_MS,
+ idleMs: GROK_TUI_IDLE_MS,
+ timeout: GROK_TUI_TIMEOUT_MS,
label: row.directional ? `sprite ${row.id} ${recordId}/${direction}` : `sprite ${row.id} ${recordId}`,
}).catch((err) => console.error(`❌ sprite ${row.id} grok-tui run failed ${recordId}/${runId}: ${err?.message || err}`));
await withAnimationWriteTail(recordId, () => attachTrackTuiResult(row.id, recordId, runId, videoAbs));
@@ -324,8 +331,8 @@ async function packageTrackRun(row, recordId, run) {
// hence the try/catch, per the CLAUDE.md boundary exception.
try {
const [reference, record] = await Promise.all([loadManifest(recordId), getRecord(recordId)]);
- const source = lockedSourceFor(row, reference, run.direction);
- if (!source) throw new Error(`No locked ${row.sourceReference === 'main' ? 'main reference' : `${run.direction} anchor`} in the reference manifest`);
+ const source = trackSourceFor(row, reference, run.direction);
+ if (!source.locked) throw new Error(`No locked ${source.label} in the reference manifest`);
const chromaKey = resolveChromaKey({ manifest: reference, record, run });
if (!chromaKey) throw new Error(`No chroma key is available for the ${row.label.toLowerCase()} matte`);
const runRel = runRelPath(run.id);
@@ -336,8 +343,8 @@ async function packageTrackRun(row, recordId, run) {
chromaKey,
runAbs: join(spriteDir(recordId), runRel),
runRel,
- anchorRel: source.path,
- anchorAbs: resolveSpriteAssetPath(recordId, source.path),
+ anchorRel: source.locked.path,
+ anchorAbs: resolveSpriteAssetPath(recordId, source.locked.path),
videoAbs: resolveSpriteAssetPath(recordId, run.sourceVideoPath),
frameCount: clampTrackFrameCount(run.frameCount, row.id),
fps: clampTrackFps(run.fps, row.id),
@@ -364,7 +371,7 @@ async function approveTrackRunImpl(trackId, recordId, { direction: requested, ru
const row = getAnimationTrack(trackId);
await requireTrack(recordId, row.id);
if (await loadSet(row.id, recordId)) throw setFinalError(row);
- const direction = row.directional ? requested : nonDirectionalRow();
+ const direction = row.directional ? requested : soleDirectionOf(row.id);
const label = row.label.toLowerCase();
const run = await loadRun(recordId, runId);
if (!run || run.track !== row.id) throw new ServerError(`Unknown ${label} run: ${runId}`, { status: 404, code: 'RUN_NOT_FOUND' });
@@ -373,15 +380,11 @@ async function approveTrackRunImpl(trackId, recordId, { direction: requested, ru
const [reference, packaged] = await Promise.all([
loadManifest(recordId), readJSONFile(resolveSpriteAssetPath(recordId, run.postprocessManifest), null),
]);
- const source = lockedSourceFor(row, reference, direction);
- if (!source) {
- throw new ServerError(
- `Lock the ${row.sourceReference === 'main' ? 'main reference' : `${anchorIdForDirection(direction)} anchor`} before approving its ${label}`,
- { status: 409, code: row.sourceReference === 'main' ? 'MAIN_NOT_LOCKED' : 'ANCHOR_NOT_LOCKED' },
- );
- }
+ const source = trackSourceFor(row, reference, direction);
+ if (!source.locked) throw notLockedError(source, row, 'approving');
if (run.anchorSha256) {
- const currentSha256 = source.sha256 || await sha256File(resolveSpriteAssetPath(recordId, source.path));
+ const currentSha256 = source.locked.sha256
+ || await sha256File(resolveSpriteAssetPath(recordId, source.locked.path));
if (run.anchorSha256 !== currentSha256) {
throw new ServerError(
`This ${label} was rendered from an older ${source.label} — generate it again from the current reference`,
diff --git a/server/services/sprites/animationTrackWorkflow.test.js b/server/services/sprites/animationTrackWorkflow.test.js
index 9984c9392d..7ddf6c9027 100644
--- a/server/services/sprites/animationTrackWorkflow.test.js
+++ b/server/services/sprites/animationTrackWorkflow.test.js
@@ -63,7 +63,9 @@ const { lockReference } = await import('./reference.js');
const {
getTrackState, startTrackGeneration, approveTrackRun, trackAuthoringDirections, trackSetRelPath,
} = await import('./animationTrackWorkflow.js');
-const { getAnimationTrack, SCANNER_TRACK, AMBIENT_TRACK } = await import('./animationTracks.js');
+const {
+ getAnimationTrack, sourceReferenceFor, SCANNER_TRACK, AMBIENT_TRACK,
+} = await import('./animationTracks.js');
let sequence = 0;
const newId = () => `track-${++sequence}`;
@@ -129,7 +131,9 @@ describe.each(TRACKS)('the generic workflow drives the $id track', (track) => {
const initial = await getTrackState(track.id, id);
expect(initial).toMatchObject({
track: track.id,
- bounds: {
+ // The row itself rides along so the client renders label/bounds/facing
+ // count from data rather than mirroring them.
+ definition: {
minFrameCount: row().minFrameCount,
maxFrameCount: row().maxFrameCount,
defaultFrameCount: row().defaultFrameCount,
@@ -238,7 +242,7 @@ describe.each(TRACKS)('the generic workflow drives the $id track', (track) => {
);
await expect(startTrackGeneration(track.id, id, track.body)).rejects.toMatchObject({
status: 409,
- code: row().sourceReference === 'main' ? 'MAIN_NOT_LOCKED' : 'ANCHOR_NOT_LOCKED',
+ code: sourceReferenceFor(track.id) === 'main' ? 'MAIN_NOT_LOCKED' : 'ANCHOR_NOT_LOCKED',
});
expect(executeTuiRun).not.toHaveBeenCalled();
});
diff --git a/server/services/sprites/animationTracks.js b/server/services/sprites/animationTracks.js
index 99bead3779..3dac8e7892 100644
--- a/server/services/sprites/animationTracks.js
+++ b/server/services/sprites/animationTracks.js
@@ -43,11 +43,12 @@
* `ambient` each shipped as a ~300-line clone of walk's state/start/package/
* approve/invalidate stack — identical control flow differing only in which
* reference image seeds the render, what the on-disk selection/set files are
- * called, and which prompt text goes to the provider. Those three differences
- * are now FIELDS on the row (`sourceReference`, `selectionKind`/`setKind`, and
- * the workflow's prompt builder key), and `animationTrackWorkflow.js` is the one
- * implementation both drive. A user-defined track is therefore a row plus a
- * prompt template — no new service module, no new routes.
+ * called, and which prompt text goes to the provider. Those differences are now
+ * either FIELDS on the row (`selectionKind`/`setKind`) or derived from one
+ * (`directional` decides both the facing count and which locked reference seeds
+ * the render), and `animationTrackWorkflow.js` is the one implementation both
+ * drive. A user-defined track is therefore a row plus a prompt template — no new
+ * service module, no new routes.
*/
/** The default track — the only one that exists today. */
@@ -57,15 +58,6 @@ export const SCANNER_TRACK = 'scanner';
/** The first non-directional environment loop (#3045). */
export const AMBIENT_TRACK = 'ambient';
-/**
- * The locked reference artifacts a track's image-to-video render may be seeded
- * from (#3136). A closed set: the generic workflow dispatches on it to decide
- * which lock to require and which file to hand the provider, so an unrecognized
- * spelling is a boot failure rather than a render that 409s on an artifact
- * nothing declared.
- */
-export const SOURCE_REFERENCES = Object.freeze(['anchor', 'main']);
-
/**
* Every known animation track.
*
@@ -85,11 +77,6 @@ export const SOURCE_REFERENCES = Object.freeze(['anchor', 'main']);
* the app rung of the precedence chain is track-driven rather than hard-coded
* to `walkFrameCount`. `contractFpsField` may be `null` for a track whose
* speed an app has no say in.
- * - `sourceReference` (#3136) — which locked reference image the i2v render is
- * seeded from: `'anchor'` (this facing's locked directional anchor) or
- * `'main'` (the one locked main reference). A directional track needs a per
- * facing anchor; a non-directional one has only the main to work from, which
- * is why the two clones differed on this line and nowhere else structurally.
* - `selectionKind` / `setKind` (#3136) — the `kind` discriminators the track's
* on-disk review selection and finalized set carry. Registry data because the
* atlas compiler VALIDATES them (`atlas.js`), so a track's on-disk contract
@@ -97,10 +84,20 @@ export const SOURCE_REFERENCES = Object.freeze(['anchor', 'main']);
* - `finalErrorCode` (#3136) — the `code` on the 409 a finalized set answers
* generate/approve with. Named per row so an existing client that matches on
* `SCANNER_SET_FINAL` keeps working after the clone collapsed.
- * - `builtin` (#3136) — true for a row compiled into this module. `walk` is the
- * mandatory character baseline and can never be removed or edited; the other
- * rows are ordinary registry data that a later phase moves into a
- * user-editable store (see #3136's remaining children).
+ * - `standaloneContract` (#3136) — true when this track's frame count is enough
+ * ON ITS OWN to describe a publishable atlas, because a record can be
+ * published with only this track authored. Walk (a character's baseline) and
+ * ambient (a place's) qualify; a short ACTION like scanner always rides beside
+ * the walk it shares rows with, so pinning only its span describes no atlas
+ * that could exist. DECLARED rather than inferred from registration order: it
+ * is a load-bearing publish-validation rule, and #3152 merges rows from a
+ * user-ordered store where "first row for this kind" would silently change.
+ *
+ * Which locked reference an i2v render is seeded from is DERIVED, not declared:
+ * a directional track renders one clip per facing and so must seed from that
+ * facing's own anchor (`sourceReferenceFor` below), while a non-directional one
+ * has no per-facing anchor and seeds from the single locked main. Stating it as
+ * a field would let a row claim a pairing that cannot work.
*/
export const ANIMATION_TRACKS = Object.freeze({
[WALK_TRACK]: Object.freeze({
@@ -128,11 +125,12 @@ export const ANIMATION_TRACKS = Object.freeze({
// (walk.js — reprocess, trims, per-direction reopen, source-frame
// extraction, set-level targets), so these describe its on-disk contract
// for the compiler's benefit without routing it through the generic module.
- sourceReference: 'anchor',
selectionKind: 'reviewed-directional-walk-selection',
setKind: 'finalized-eight-direction-walk-set',
finalErrorCode: 'WALK_SET_FINAL',
- builtin: true,
+ // A character publishes off its walk — the compile path requires a finalized
+ // walk set before it emits anything at all.
+ standaloneContract: true,
}),
[SCANNER_TRACK]: Object.freeze({
id: SCANNER_TRACK,
@@ -150,16 +148,16 @@ export const ANIMATION_TRACKS = Object.freeze({
contractFrameCountField: 'scannerFrameCount',
// The game owns action timing; PortOS carries fps as preview provenance.
contractFpsField: null,
- // Every facing renders from its own locked anchor, so the run is seeded per
- // direction exactly like walk's.
- sourceReference: 'anchor',
// The historical on-disk spellings, kept verbatim: an already-approved
// scanner set on any install must keep validating after the clone collapsed
// into the generic workflow, and the compiler matches these exact strings.
selectionKind: 'reviewed-directional-scanner-selection',
setKind: 'finalized-eight-direction-scanner-set',
finalErrorCode: 'SCANNER_SET_FINAL',
- builtin: true,
+ // A scanner action rides beside the walk it shares atlas rows with — it is
+ // never the only thing a character publishes, so its span alone doesn't
+ // describe an atlas.
+ standaloneContract: false,
}),
[AMBIENT_TRACK]: Object.freeze({
id: AMBIENT_TRACK,
@@ -178,14 +176,12 @@ export const ANIMATION_TRACKS = Object.freeze({
// Ambient cadence belongs to the consuming app. PortOS keeps fps only as
// authoring-preview provenance, like scanner.
contractFpsField: null,
- // A place has no facing and therefore no directional anchor — its one
- // locked main reference is both the idle cell and the i2v source. This ONE
- // field is the whole structural difference the ambient clone existed for.
- sourceReference: 'main',
selectionKind: 'reviewed-single-row-ambient-selection',
setKind: 'finalized-single-row-ambient-set',
finalErrorCode: 'AMBIENT_SET_FINAL',
- builtin: true,
+ // A place publishes off its ambient loop — it has no walk, so this IS its
+ // baseline and the compile path requires its finalized set.
+ standaloneContract: true,
}),
});
@@ -232,33 +228,15 @@ export function assertAnimationTrackRows(tracks) {
if (row.contractFpsField !== null && (typeof row.contractFpsField !== 'string' || !row.contractFpsField)) {
throw new Error(`animationTracks: track '${id}' needs a contractFpsField (or null)`);
}
- // #3136 — the workflow shape. `sourceReference` is a closed set because the
- // generic workflow dispatches on it: a third spelling would silently resolve
- // to no reference at all and every render would 409 "not locked" naming an
- // artifact the row never asked for.
- if (!SOURCE_REFERENCES.includes(row.sourceReference)) {
- throw new Error(
- `animationTracks: track '${id}' needs a sourceReference of ${SOURCE_REFERENCES.join(' or ')}, got '${String(row.sourceReference)}'`,
- );
- }
- // A directional track renders one clip per facing, so it must seed from that
- // facing's own anchor — seeding eight directional rows from the single main
- // reference would render the same south-facing clip eight times and pass
- // every later check, since the packer never sees which facing it was asked
- // for. The inverse (a non-directional track pointed at 'anchor') has no
- // anchor to read: a place record never generates directional anchors at all.
- const expectedSource = row.directional ? 'anchor' : 'main';
- if (row.sourceReference !== expectedSource) {
- throw new Error(
- `animationTracks: ${row.directional ? 'directional' : 'non-directional'} track '${id}' must seed from the ${expectedSource} reference, not '${row.sourceReference}'`,
- );
- }
+ // #3136 — the workflow shape.
for (const field of ['selectionKind', 'setKind', 'finalErrorCode']) {
if (typeof row[field] !== 'string' || !row[field]) {
throw new Error(`animationTracks: track '${id}' needs a non-empty '${field}'`);
}
}
- if (typeof row.builtin !== 'boolean') throw new Error(`animationTracks: track '${id}' needs a boolean 'builtin'`);
+ if (typeof row.standaloneContract !== 'boolean') {
+ throw new Error(`animationTracks: track '${id}' needs a boolean 'standaloneContract'`);
+ }
// Two tracks sharing a selection/set `kind` is the same class of bug as two
// sharing a contract field: the compiler validates a set by its `kind`, so a
// duplicate would let one track's finalized set satisfy the other's evidence
@@ -300,10 +278,64 @@ export function assertAnimationTrackRows(tracks) {
claimedContractFields.set(field, { id, knob });
}
}
+ // Every record kind any row admits must have EXACTLY ONE standalone track —
+ // the baseline it publishes off. Zero means a record of that kind can be
+ // authored but never publish (its runtime contract could name no required
+ // field, and the compiler has no evidence chain to require); more than one
+ // means "which set must be finalized before compiling?" has two answers. This
+ // is a cross-row invariant, so it runs after the per-row loop.
+ const standaloneByKind = new Map();
+ for (const id of Object.keys(tracks)) {
+ if (!tracks[id].standaloneContract) continue;
+ for (const kind of tracks[id].kinds) {
+ standaloneByKind.set(kind, [...(standaloneByKind.get(kind) || []), id]);
+ }
+ }
+ for (const id of Object.keys(tracks)) {
+ for (const kind of tracks[id].kinds) {
+ const owners = standaloneByKind.get(kind) || [];
+ if (owners.length !== 1) {
+ throw new Error(
+ `animationTracks: record kind '${kind}' needs exactly one standaloneContract track, has ${owners.length}${owners.length ? ` (${owners.join(', ')})` : ''}`,
+ );
+ }
+ }
+ }
}
assertAnimationTrackRows(ANIMATION_TRACKS);
+/**
+ * The locked reference artifact a track's image-to-video render is seeded from:
+ * `'anchor'` (this facing's own locked directional anchor) or `'main'` (the one
+ * locked main reference).
+ *
+ * DERIVED from `directional` rather than declared, because only one pairing can
+ * work. A directional track renders one clip per facing, so seeding all eight
+ * rows from the single main would render the same south-facing clip eight times
+ * and pass every later check — nothing downstream re-reads which facing was
+ * asked for. The inverse has no anchor to read at all: a place record never
+ * generates directional anchors.
+ */
+export function sourceReferenceFor(id, tracks = ANIMATION_TRACKS) {
+ return getAnimationTrack(id, tracks).directional ? 'anchor' : 'main';
+}
+
+/**
+ * The one track a record of `kind` publishes off — its baseline, whose finalized
+ * set the compile path requires and whose frame count alone is a valid runtime
+ * contract. `null` for a kind no row admits.
+ *
+ * One definition, asked by the publish-contract schema (which field is required)
+ * and the compile dispatch (which evidence chain to validate). Those two used to
+ * answer it separately — one by registration order, one as
+ * `ambient-and-not-walk` — and agreed only by coincidence.
+ */
+export function primaryTrackForKind(kind, tracks = ANIMATION_TRACKS) {
+ if (typeof kind !== 'string' || !kind) return null;
+ return Object.values(tracks).find((row) => row.standaloneContract && row.kinds.includes(kind)) || null;
+}
+
/** True when `id` names a track in `tracks` (the shipped registry by default). */
export function isAnimationTrack(id, tracks = ANIMATION_TRACKS) {
return typeof id === 'string' && Object.prototype.hasOwnProperty.call(tracks, id);
diff --git a/server/services/sprites/animationTracks.test.js b/server/services/sprites/animationTracks.test.js
index 0871fb350b..ab1755af7f 100644
--- a/server/services/sprites/animationTracks.test.js
+++ b/server/services/sprites/animationTracks.test.js
@@ -16,6 +16,7 @@ import {
WALK_TRACK, SCANNER_TRACK, AMBIENT_TRACK, ANIMATION_TRACKS, ANIMATION_TRACK_IDS,
isAnimationTrack, getAnimationTrack, clampTrackFrameCount, clampTrackFps,
assertAnimationTrackRows, trackRowCount, tracksForKind, kindSupportsTrack,
+ sourceReferenceFor, primaryTrackForKind,
} from './animationTracks.js';
import { SPRITE_RECORD_KINDS } from './recordsLogic.js';
import { AMBIENT_TRACK_ROW } from './spriteTestFixtures.js';
@@ -136,6 +137,9 @@ describe('the module-load row guard', () => {
selectionKind: 'reviewed-directional-scanner-selection',
setKind: 'finalized-eight-direction-scanner-set',
finalErrorCode: 'SCANNER_SET_FINAL',
+ // Walk is `character`'s standalone baseline, so a SECOND character track must
+ // not also claim it — exactly one per record kind (asserted below).
+ standaloneContract: false,
};
const twoRows = (overrides = {}) => ({ walk, scanner: { ...second, ...overrides } });
@@ -181,16 +185,27 @@ describe('the module-load row guard', () => {
['an empty contract frame-count field', { contractFrameCountField: '' }, /needs a contractFrameCountField/],
['an undefined contract fps field', { contractFpsField: undefined }, /contractFpsField \(or null\)/],
// #3136 — the workflow shape the generic track service dispatches on.
- ['an unrecognized sourceReference', { sourceReference: 'turnaround' }, /sourceReference of anchor or main/],
- ['a missing sourceReference', { sourceReference: undefined }, /sourceReference of anchor or main/],
['a missing selectionKind', { selectionKind: '' }, /needs a non-empty 'selectionKind'/],
['a missing setKind', { setKind: undefined }, /needs a non-empty 'setKind'/],
['a missing finalErrorCode', { finalErrorCode: '' }, /needs a non-empty 'finalErrorCode'/],
- ['a non-boolean builtin', { builtin: 'yes' }, /boolean 'builtin'/],
+ ['a non-boolean standaloneContract', { standaloneContract: 'yes' }, /boolean 'standaloneContract'/],
])('rejects %s', (_label, overrides, message) => {
expect(() => assertAnimationTrackRows(twoRows(overrides))).toThrow(message);
});
+ it('requires exactly one standaloneContract track per record kind (#3136)', () => {
+ // Zero means a record of that kind can be authored but never published: the
+ // publish contract would require no field and the compiler would have no
+ // evidence chain to demand. Two means "which set must be finalized before
+ // compiling?" has two answers — and the publish schema would accept either
+ // track's frame count alone as describing the atlas.
+ expect(() => assertAnimationTrackRows(twoRows({ standaloneContract: true })))
+ .toThrow(/record kind 'character' needs exactly one standaloneContract track, has 2 \(walk, scanner\)/);
+ expect(() => assertAnimationTrackRows({
+ walk: { ...walk, standaloneContract: false }, scanner: second,
+ })).toThrow(/record kind 'character' needs exactly one standaloneContract track, has 0/);
+ });
+
it('rejects a second row that copy-pastes walk\'s on-disk set kind (#3136)', () => {
// The mirror of the contract-field collision, one layer down: the atlas
// compiler validates a finalized set by its `kind`, so two tracks sharing
@@ -202,17 +217,37 @@ describe('the module-load row guard', () => {
.toThrow(/claimed by both 'walk\.selectionKind' and 'scanner\.selectionKind'/);
});
- it('binds sourceReference to directionality (#3136)', () => {
- // A directional track seeded from the single `main` would render the SAME
- // south-facing clip for all eight facings and pass every later check, since
- // nothing downstream re-reads which facing was asked for. The inverse has no
- // anchor to read at all — a place record never generates directional anchors.
- expect(() => assertAnimationTrackRows(twoRows({ sourceReference: 'main' })))
- .toThrow(/directional track 'scanner' must seed from the anchor reference/);
- expect(() => assertAnimationTrackRows(twoRows({ directional: false, sourceReference: 'anchor' })))
- .toThrow(/non-directional track 'scanner' must seed from the main reference/);
- // …and the well-formed non-directional pairing is accepted.
- expect(() => assertAnimationTrackRows(twoRows({ directional: false, sourceReference: 'main' }))).not.toThrow();
+});
+
+describe('registry-derived source reference and primacy (#3136)', () => {
+ it('derives the seeding reference from directionality, never declaring it', () => {
+ // Only one pairing can work, which is why this is derived rather than a row
+ // field: a directional track seeded from the single `main` would render the
+ // SAME south-facing clip for all eight facings and pass every later check
+ // (nothing downstream re-reads which facing was asked for), and a
+ // non-directional one has no anchor to read at all — a place record never
+ // generates directional anchors.
+ expect(sourceReferenceFor(WALK_TRACK)).toBe('anchor');
+ expect(sourceReferenceFor(SCANNER_TRACK)).toBe('anchor');
+ expect(sourceReferenceFor(AMBIENT_TRACK)).toBe('main');
+ // Reads the row it's HANDED, not the shipped table.
+ expect(sourceReferenceFor('ambient', { ambient: AMBIENT_TRACK_ROW })).toBe('main');
+ expect(() => sourceReferenceFor('unknown')).toThrow(/Unknown animation track/);
+ });
+
+ it('answers which track a record kind publishes off', () => {
+ // ONE definition, shared by the publish-contract schema (which field is
+ // required) and the compile dispatch (which evidence chain to validate).
+ expect(primaryTrackForKind('character')?.id).toBe(WALK_TRACK);
+ expect(primaryTrackForKind('place')?.id).toBe(AMBIENT_TRACK);
+ expect(primaryTrackForKind('object')?.id).toBe(AMBIENT_TRACK);
+ expect(primaryTrackForKind('props')?.id).toBe(AMBIENT_TRACK);
+ // A short action a record can't publish off alone is never the primary.
+ expect(primaryTrackForKind('character')?.id).not.toBe(SCANNER_TRACK);
+ // Absent/unknown answers null rather than defaulting to a kind.
+ expect(primaryTrackForKind('nope')).toBeNull();
+ expect(primaryTrackForKind('')).toBeNull();
+ expect(primaryTrackForKind(undefined)).toBeNull();
});
});
diff --git a/server/services/sprites/animationWorkflow.js b/server/services/sprites/animationWorkflow.js
index 5bf54259e7..37b455b72a 100644
--- a/server/services/sprites/animationWorkflow.js
+++ b/server/services/sprites/animationWorkflow.js
@@ -1,6 +1,16 @@
-/** Shared per-record animation serialization and reference-key resolution. */
+/**
+ * Shared animation-render plumbing: per-record write serialization, chroma-key
+ * precedence, the grok-TUI invocation, and the i2v task wrapper.
+ *
+ * Everything here is a fact about "how PortOS renders a sprite animation" rather
+ * than about any one track, so both animation services (`walk.js`'s bespoke
+ * pipeline and the generic `animationTrackWorkflow.js`) read it from here. The
+ * two used to hold independent copies of the TUI thresholds, the provider
+ * literal, and the task text — and the task text had already drifted by a clause.
+ */
import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';
+import { GROK_TUI_ID } from '../../lib/grok.js';
const animationWriteTail = createKeyCachedQueue();
@@ -13,3 +23,59 @@ export const withAnimationWriteTail = (recordId, fn) => animationWriteTail(recor
export const resolveChromaKey = ({ manifest, record, run } = {}) => (
run?.chromaKey || manifest?.chromaKey || record?.chromaKey || null
);
+
+/**
+ * The locked directional anchor for one facing, or null.
+ *
+ * Fourth copy of this `.find` + locked/path pair when it was hoisted here (walk's
+ * generate, walk's approve, its regenerability probe, and now every non-walk
+ * track's render gate all ask the same question). The definition of "usable
+ * anchor" drifting between them is how a gate ends up promising a render the
+ * render path then refuses.
+ */
+export const lockedAnchorFor = (manifest, direction) => {
+ const anchor = manifest?.anchors?.find((a) => a.direction === direction);
+ return anchor?.status === 'locked' && anchor.path ? anchor : null;
+};
+
+/** The locked main reference, or null — the non-directional counterpart. */
+export const lockedMainFor = (manifest) => {
+ const main = manifest?.mainReference;
+ return main?.locked && main.path ? main : null;
+};
+
+// Every sprite animation renders as an OBSERVABLE grok TUI session (the user
+// wants to watch/course-correct grok in the Shell) rather than a headless
+// mediaJobQueue spawn. The idle threshold must be long enough that grok's
+// narration lulls during the multi-minute image_to_video render aren't mistaken
+// for completion; the hard cap mirrors the old headless GROK_VIDEO_TIMEOUT_MS.
+// Shared so raising the lull tolerance can't fix one track and leave the others
+// reaping at 90s.
+export const GROK_TUI_IDLE_MS = 90_000;
+export const GROK_TUI_TIMEOUT_MS = 30 * 60_000;
+
+/**
+ * The grok-TUI provider descriptor for an animation render.
+ *
+ * `args: []` is intentional — buildTuiInvocation → applyCommandDefaults routes a
+ * grok command through ensureGrokTuiArgs (which adds
+ * `--permission-mode bypassPermissions`).
+ */
+export const grokTuiProvider = (grokPath) => ({
+ id: GROK_TUI_ID, type: 'tui', command: grokPath || 'grok', args: [],
+});
+
+/**
+ * The single-turn TUI task: the track's own motion/matte prompt, then the
+ * concrete input path and the exact MP4 output path.
+ *
+ * `executeTuiRun` wraps this with its "write your final response to the response
+ * file when done" instruction, so grok saves the MP4 first and its completion
+ * signal is the response file (with the long idle threshold as a backstop).
+ */
+export const buildGrokI2vTask = ({ prompt, inputAbs, videoAbs, duration }) => (
+ `${prompt}\n\n`
+ + `Use your built-in image_to_video tool to animate the image at this exact path for ${duration} seconds:\n${inputAbs}\n\n`
+ + `Save the resulting animation as an MP4 file at exactly this path:\n${videoAbs}\n\n`
+ + 'Do not create or modify any other files, and do not run any tools beyond what is needed to render and save that MP4.'
+);
diff --git a/server/services/sprites/atlas.js b/server/services/sprites/atlas.js
index 9ffea83ea3..447aab45c9 100644
--- a/server/services/sprites/atlas.js
+++ b/server/services/sprites/atlas.js
@@ -51,7 +51,8 @@ import {
} from './walkPostprocess.js';
import { ATLAS_IDLE_COLUMN } from './walkBounds.js';
import {
- WALK_TRACK, SCANNER_TRACK, AMBIENT_TRACK, ANIMATION_TRACK_IDS, kindSupportsTrack, getAnimationTrack,
+ WALK_TRACK, SCANNER_TRACK, AMBIENT_TRACK, ANIMATION_TRACK_IDS,
+ kindSupportsTrack, getAnimationTrack, primaryTrackForKind,
} from './animationTracks.js';
import {
buildAtlasGrid, resolveTrackUniformity, compiledGridUpToDate, trackDirections,
@@ -266,8 +267,12 @@ function sharedRowPasteX(anchoredX, boundsList, geometry) {
*/
export async function validateForCompile(recordId) {
const recordForTrack = await getRecord(recordId);
- if (recordForTrack && kindSupportsTrack(recordForTrack.kind, AMBIENT_TRACK)
- && !kindSupportsTrack(recordForTrack.kind, WALK_TRACK)) {
+ // Which evidence chain a record compiles through follows its PRIMARY track —
+ // the one whose finalized set it can't publish without. Asked of the registry
+ // (`primaryTrackForKind`) rather than spelled as "ambient-and-not-walk", so it
+ // is the same definition `spriteRuntimeContractSchema` requires a frame count
+ // for; the two used to agree only by coincidence.
+ if (recordForTrack && primaryTrackForKind(recordForTrack.kind)?.id === AMBIENT_TRACK) {
return validateAmbientForCompile(recordId, recordForTrack);
}
// Every hashed input is read exactly once: verify the bytes in memory and
diff --git a/server/services/sprites/spriteTestFixtures.js b/server/services/sprites/spriteTestFixtures.js
index 720568ef19..d9dd844714 100644
--- a/server/services/sprites/spriteTestFixtures.js
+++ b/server/services/sprites/spriteTestFixtures.js
@@ -107,12 +107,11 @@ export const AMBIENT_TRACK_ROW = Object.freeze({
defaultFps: 4,
contractFrameCountField: 'ambientFrameCount',
contractFpsField: null,
- // #3136 workflow shape. A non-directional row must seed from the main
- // reference (it has no per-facing anchor to read), and its on-disk kinds must
- // not collide with any other row this fixture is combined with.
- sourceReference: 'main',
+ // #3136 workflow shape. Its on-disk kinds must not collide with any other row
+ // this fixture is combined with, and it is `place`/`object`'s standalone
+ // baseline — those kinds have no walk, so this is what they publish off.
selectionKind: 'reviewed-single-row-ambient-selection',
setKind: 'finalized-single-row-ambient-set',
finalErrorCode: 'AMBIENT_SET_FINAL',
- builtin: true,
+ standaloneContract: true,
});
diff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.js
index 4c3a724f2d..b69aaca0ff 100644
--- a/server/services/sprites/walk.js
+++ b/server/services/sprites/walk.js
@@ -54,19 +54,25 @@ import {
import { verifyPackagedFrames } from './walkFrames.js';
import { probeVideoDuration } from '../../lib/ffmpeg.js';
import { resolveGrokDuration } from '../../lib/grokVideoClip.js';
-import { withAnimationWriteTail, resolveChromaKey } from './animationWorkflow.js';
-import { SCANNER_TRACK } from './animationTracks.js';
+import {
+ withAnimationWriteTail, resolveChromaKey, lockedAnchorFor,
+ GROK_TUI_IDLE_MS, GROK_TUI_TIMEOUT_MS, grokTuiProvider, buildGrokI2vTask,
+} from './animationWorkflow.js';
+import {
+ ANIMATION_TRACKS, SCANNER_TRACK, sourceReferenceFor,
+} from './animationTracks.js';
import {
invalidateTrackDirectionForAnchorRevision, invalidateTrackForTurnaroundRevision,
} from './animationTrackWorkflow.js';
// grok's walk render runs as an OBSERVABLE TUI session (issue: user wants to
// watch/course-correct grok in the Shell) rather than a headless mediaJobQueue
-// spawn. The idle threshold must be long enough that grok's narration lulls
-// during the multi-minute image_to_video render aren't mistaken for completion;
-// the hard cap mirrors the old headless GROK_VIDEO_TIMEOUT_MS.
-const WALK_TUI_IDLE_MS = 90_000;
-const WALK_TUI_TIMEOUT_MS = 30 * 60_000;
+// spawn. The thresholds and their rationale live in animationWorkflow.js, shared
+// with every other animation track, so raising the lull tolerance can't fix one
+// render path and leave the rest reaping early. Local aliases keep the ~6 call
+// sites (including RENDER_STALE_MS below) reading as walk's own.
+const WALK_TUI_IDLE_MS = GROK_TUI_IDLE_MS;
+const WALK_TUI_TIMEOUT_MS = GROK_TUI_TIMEOUT_MS;
const selectionRelPath = (id) => `walk/${id}-walk-selection-v1.json`;
// Exported: atlas.js (phase 4) reads the finalized walk set as compile input.
@@ -899,17 +905,6 @@ async function setWalkTargetImpl(recordId, { frameCount, fps }) {
*/
export { resolveChromaKey } from './animationWorkflow.js';
-/**
- * The locked directional anchor for a direction, or null. Third copy of this
- * `.find` + locked/path pair when it was extracted (generate, approve, and the
- * regenerability probe below all ask the same question), and the definition of
- * "usable anchor" drifting between them is how a gate ends up promising a render
- * the render path then refuses.
- */
-const lockedAnchorFor = (manifest, direction) => {
- const anchor = manifest?.anchors?.find((a) => a.direction === direction);
- return anchor?.status === 'locked' && anchor.path ? anchor : null;
-};
/**
* Whether a fresh walk render is possible for ONE direction: its anchor must be
@@ -1069,7 +1064,7 @@ async function startWalkGenerationImpl(recordId, body) {
// Completion re-enters the tail via attachTuiWalkResult; errors are captured
// onto the run record (no request lifecycle to bubble to).
runWalkTuiRender(recordId, {
- runId, direction, grokPath, task: buildWalkTuiTask({ prompt, inputAbs, videoAbs, duration }),
+ runId, direction, grokPath, task: buildGrokI2vTask({ prompt, inputAbs, videoAbs, duration }),
generatedAbs, videoAbs,
}).catch((err) => console.error(`❌ sprite walk grok-tui render crashed ${recordId}/${runId}: ${err?.message || err}`));
@@ -1077,18 +1072,6 @@ async function startWalkGenerationImpl(recordId, body) {
return { runId, direction, duration, shellSession: runId };
}
-// The single-turn TUI task: reuse the shared motion/matte prompt, then point
-// grok at the concrete input path and the exact MP4 output path. executeTuiRun
-// wraps this with its "write your final response to the response file when done"
-// instruction, so grok saves the MP4 first and its completion signal is the
-// response file (with the long idle threshold as a backstop).
-function buildWalkTuiTask({ prompt, inputAbs, videoAbs, duration }) {
- return `${prompt}\n\n`
- + `Use your built-in image_to_video tool to animate the image at this exact path for ${duration} seconds:\n${inputAbs}\n\n`
- + `Save the resulting animation as an MP4 file at exactly this path:\n${videoAbs}\n\n`
- + 'Do not create or modify any other files, and do not run any tools beyond what is needed to render and save that MP4.';
-}
-
/**
* Drive the observable grok-tui render to completion, then attach its result.
* executeTuiRun spawns grok in a PTY and registers it as a Shell session under
@@ -1096,9 +1079,7 @@ function buildWalkTuiTask({ prompt, inputAbs, videoAbs, duration }) {
* outcome from whether the directed MP4 actually landed on disk.
*/
async function runWalkTuiRender(recordId, { runId, direction, grokPath, task, generatedAbs, videoAbs }) {
- // args:[] is intentional — buildTuiInvocation → applyCommandDefaults routes a
- // grok command through ensureGrokTuiArgs (adds --permission-mode bypassPermissions).
- const provider = { id: GROK_TUI_ID, type: 'tui', command: grokPath || 'grok', args: [] };
+ const provider = grokTuiProvider(grokPath);
await executeTuiRun({
runId,
provider,
@@ -1884,11 +1865,41 @@ export function invalidateWalkDirectionForAnchorRevision(recordId, { direction }
export async function unlockDirectionalAnchor(recordId, { direction }) {
await assertReferenceAnchorUnlockable(recordId, { direction });
const walkInvalidated = await invalidateWalkDirectionForAnchorRevision(recordId, { direction });
- const scannerInvalidated = await invalidateTrackDirectionForAnchorRevision(SCANNER_TRACK, recordId, { direction });
+ const tracksInvalidated = await invalidateAnchorDependentTracks(recordId, direction);
const reference = await unlockReferenceAnchor(recordId, { direction });
- return { ...reference, walkInvalidated, scannerInvalidated };
+ return { ...reference, walkInvalidated, ...tracksInvalidated };
+}
+
+/**
+ * Drop every non-walk track's approval for one facing, because the anchor those
+ * clips were rendered from is being reopened.
+ *
+ * Iterates the registry rather than naming `scanner`: a stale approved clip whose
+ * source image no longer exists would let the atlas compile frames drawn from it,
+ * so leaving a second anchor-seeded track out of this loop is silent bad pixels
+ * in a published atlas with no error anywhere. Only anchor-seeded tracks are
+ * affected — a main-seeded one has no dependency on a directional anchor.
+ *
+ * Returns `{ tracksInvalidated: { <trackId>: bool }, scannerInvalidated }`; the
+ * scalar is kept because `ReferenceWorkflow.jsx` and the route tests read it.
+ */
+async function invalidateAnchorDependentTracks(recordId, direction) {
+ const tracksInvalidated = {};
+ for (const row of anchorSeededTracks()) {
+ // eslint-disable-next-line no-await-in-loop -- ordered: each track's selection write settles before the next
+ tracksInvalidated[row.id] = await invalidateTrackDirectionForAnchorRevision(row.id, recordId, { direction });
+ }
+ return { tracksInvalidated, scannerInvalidated: tracksInvalidated[SCANNER_TRACK] ?? false };
}
+/**
+ * Every non-walk track seeded from a directional anchor — the ones a reference
+ * anchor revision invalidates. Walk is excluded because it owns its own
+ * invalidation path above.
+ */
+const anchorSeededTracks = () => Object.values(ANIMATION_TRACKS)
+ .filter((row) => row.id !== WALK_TRACK && sourceReferenceFor(row.id) === 'anchor');
+
/**
* Reopen the main (south) reference and invalidate only animations conditioned
* on it. The locked turnaround and every non-south anchor remain usable.
@@ -1897,9 +1908,9 @@ export async function unlockMainReference(recordId) {
await assertReferenceMainUnlockable(recordId);
const direction = 'south';
const walkInvalidated = await invalidateWalkDirectionForAnchorRevision(recordId, { direction });
- const scannerInvalidated = await invalidateTrackDirectionForAnchorRevision(SCANNER_TRACK, recordId, { direction });
+ const tracksInvalidated = await invalidateAnchorDependentTracks(recordId, direction);
const reference = await unlockReferenceMain(recordId);
- return { ...reference, walkInvalidated, scannerInvalidated };
+ return { ...reference, walkInvalidated, ...tracksInvalidated };
}
/**
@@ -1913,9 +1924,21 @@ export async function unlockMainReference(recordId) {
export async function unlockTurnaroundReference(recordId) {
await assertReferenceTurnaroundUnlockable(recordId);
const walkInvalidatedDirections = await invalidateWalkForTurnaroundRevision(recordId);
- const scannerInvalidatedDirections = await invalidateTrackForTurnaroundRevision(SCANNER_TRACK, recordId);
+ // Same registry sweep as the per-anchor path, across every facing: a
+ // regenerated turnaround resets the whole identity chain, so no anchor-seeded
+ // track may keep an approval descended from the old sheet.
+ const tracksInvalidatedDirections = {};
+ for (const row of anchorSeededTracks()) {
+ // eslint-disable-next-line no-await-in-loop -- ordered: each track's selection write settles before the next
+ tracksInvalidatedDirections[row.id] = await invalidateTrackForTurnaroundRevision(row.id, recordId);
+ }
const reference = await unlockReferenceTurnaround(recordId);
- return { ...reference, walkInvalidatedDirections, scannerInvalidatedDirections };
+ return {
+ ...reference,
+ walkInvalidatedDirections,
+ tracksInvalidatedDirections,
+ scannerInvalidatedDirections: tracksInvalidatedDirections[SCANNER_TRACK] ?? [],
+ };
}
function invalidateWalkForTurnaroundRevision(recordId) {