Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-3153]): author custom sprite animation types from the Sprite Manager
[._.]/ Adam Eivy5efb8f84a30f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 42df380844..7d74a1556e 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -32,6 +32,8 @@## Sprites+- **[issue-3153] Animation types can now be created, edited, and deleted from the Sprite Manager.** Defining your own sequence — a chest opening, a flower blossoming, a jetpack burst — no longer means hand-editing a file: an **Animation types** panel lists everything registered, shows the Walk cycle as built-in, and lets you add or retune a type by naming it, choosing whether it renders once or per facing, picking which sprites (characters, places, objects) may carry it, setting its frame-count and playback-speed ranges, and writing the prompt sent to the video model. A new type immediately drives the full generate/review/approve workflow with no further setup; publishing with it takes effect after the next server restart, which the panel tells you. PortOS fills in the naming details that have to stay unique, so a type can't quietly collide with another one — and if it would, you're told which setting conflicts at the moment you save instead of at the next startup. Deleting a type that sprites have already approved renders for is refused and names them, so approved work is never silently orphaned; a type's id and facing mode are fixed once renders exist, and everything else stays free to retune.+- **[issue-3152] Animation types are now yours to define — the walk cycle is the only one PortOS builds in.** The Scanner action and Ambient loop used to be baked into the app, which meant a scanner workflow appeared on every character whether your game has a scanner mechanic or not, and adding your own sequence (a chest opening, a flower blossoming, a jetpack burst) needed a PortOS release. Both now ship as ordinary starter entries in a file you own, so you can retune their frame counts and playback speeds, reword the prompt each one sends, delete the ones your game doesn't use, or add your own — for characters and for places and objects alike. A new type gets its full generate/review/approve workflow, its atlas span, and its publish contract field automatically. Changes take effect on the next server start.- Your existing sprites are unaffected: the starter entries reproduce the previous Scanner and Ambient behavior exactly, down to the wording sent to the video model, so an already-approved scanner set or ambient loop still compiles and publishes byte for byte after upgrading. A deleted type stays deleted rather than returning on the next update, and a definition with a problem (two types claiming the same setting, a missing frame range) is reported at startup with the field named instead of surfacing as a broken render hours later.- **[issue-3158] Every registered animation type now compiles into the runtime atlas automatically.** The atlas compiler collects, verifies, places, and tracks finalized animation sets through the registry, so adding a custom sequence no longer requires another hardcoded compiler path and changing any track correctly invalidates the current atlas.diff --git a/client/src/components/sprites/AnimationTypesDrawer.jsx b/client/src/components/sprites/AnimationTypesDrawer.jsxnew file mode 100644index 0000000000..57ec47c520--- /dev/null+++ b/client/src/components/sprites/AnimationTypesDrawer.jsx@@ -0,0 +1,555 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import { useSearchParams } from 'react-router-dom';+import { AlertTriangle, Info, Lock, Pencil, Plus, RotateCcw, Trash2 } from 'lucide-react';+import Drawer from '../Drawer';+import Banner from '../ui/Banner';+import Pill from '../ui/Pill';+import ConfirmButtonPair from '../ui/ConfirmButtonPair';+import FormField from '../ui/FormField';+import toast from '../ui/Toast';+import useDrawerTab from '../../hooks/useDrawerTab';+import { NEW_SPRITE_KINDS } from '../../lib/spriteRecordGroups.js';+import {+ listSpriteAnimationTracks, createSpriteAnimationTrack,+ updateSpriteAnimationTrack, deleteSpriteAnimationTrack,+} from '../../services/apiSprites.js';++/**+ * Manage animation types (#3153) — author the user-defined half of the track+ * registry.+ *+ * #3152 made the registry a merge of the compiled `walk` row plus a JSON store, and+ * #3136 made every track's generate/review/approve workflow generic — so a new+ * animation type already renders its full workflow with no client change+ * (`TrackWorkflow.test.jsx` proves that against a synthetic `jetpack` track). This+ * drawer is the missing authoring surface: without it the store was a file the user+ * had to hand-edit.+ *+ * **The form is the row's user-facing subset, and nothing more.** The five on-disk /+ * publish-contract discriminators plus `standaloneContract` are DERIVED server-side+ * from the id, because they must be globally unique and a typo in one would hand this+ * track another's evidence chain. They're shown read-only on an existing type so a+ * collision refusal is legible rather than mysterious.+ *+ * **The server is the validator; this only front-runs it.** Bounds ordering is+ * checked here so the user sees the problem in the field, but every refusal that+ * matters (an id collision, a derived-field collision, a delete that would orphan+ * approved renders, a record kind losing its publishable baseline) comes back from+ * `assertAnimationTrackRows` as a 409 and is rendered verbatim — restating those+ * rules client-side would be a second definition that drifts.+ */++const TABS = [+ { id: 'list', label: 'Animation types' },+ { id: 'new', label: 'Add type' },+];+const TAB_IDS = TABS.map((t) => t.id);++// `NEW_SPRITE_KINDS` is the shared "kinds a user may pick" list (already excluding+// the legacy import-only `props`, for the same reason). A hand-edited store row may+// still claim `props` and renders fine in the list — this only governs the FORM.+const BLANK = {+ id: '',+ label: '',+ directional: false,+ kinds: ['object'],+ minFrameCount: 2,+ maxFrameCount: 8,+ defaultFrameCount: 4,+ minFps: 2,+ maxFps: 12,+ defaultFps: 6,+ promptTemplate: '',+};++// Mirrors the server's `TRACK_BOUND_TRIPLES` (animationTracks.js), which is the+// authoritative list — this copy exists only to name the knob in the pre-submit+// message, and the server's `assertAnimationTrackRows` is the real gate.+const BOUND_TRIPLES = [+ ['minFrameCount', 'defaultFrameCount', 'maxFrameCount', 'Frame count'],+ ['minFps', 'defaultFps', 'maxFps', 'Playback fps'],+];++// The authored subset of a registry row, as the form holds it. Mirrors the server's+// `AUTHORED_TRACK_FIELDS`; `id` rides along for the create payload and is stripped+// before a PUT (the update schema is strict and the path param owns the id).+const toForm = (row) => ({+ id: row.id,+ label: row.label,+ directional: row.directional,+ kinds: [...row.kinds],+ minFrameCount: row.minFrameCount,+ maxFrameCount: row.maxFrameCount,+ defaultFrameCount: row.defaultFrameCount,+ minFps: row.minFps,+ maxFps: row.maxFps,+ defaultFps: row.defaultFps,+ promptTemplate: row.promptTemplate || '',+});++/**+ * The first bounds violation, or `null`.+ *+ * Deliberately only the ordering rule: it's the one the user hits by typing a+ * default outside the range they just narrowed, and the only one whose message is+ * more useful before the round-trip than after.+ */+function boundsError(form) {+ for (const [min, def, max, label] of BOUND_TRIPLES) {+ if (!(Number(form[min]) <= Number(form[def]) && Number(form[def]) <= Number(form[max]))) {+ return `${label}: minimum ≤ default ≤ maximum is required.`;+ }+ }+ return null;+}++const SLUG_RE = /^[a-z0-9][a-z0-9-]*$/;++function formError(form, { isNew }) {+ if (isNew && !SLUG_RE.test(form.id)) {+ return 'Id must be lowercase letters, numbers and dashes, starting with a letter or number.';+ }+ if (!form.label.trim()) return 'Give the animation type a label.';+ if (!form.kinds.length) return 'Pick at least one sprite kind that may carry this type.';+ if (!form.promptTemplate.trim()) return 'A prompt template is required — it is what gets sent to the video model.';+ return boundsError(form);+}++// One input style for every field in this form, so a styling change is one edit.+const INPUT_CLASS = 'w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-sm text-white';+const LABEL_CLASS = 'block text-xs text-gray-400 mb-1';++// `FormField` owns the htmlFor/id pairing (via useId), so these need no hand-assigned+// ids — the tests still resolve each control through its label.+function NumberField({ label, value, onChange, min, max }) {+ return (+ <FormField label={label} labelClassName={LABEL_CLASS}>+ <input+ type="number"+ min={min}+ max={max}+ value={value}+ onChange={(e) => onChange(e.target.value === '' ? '' : Number(e.target.value))}+ className={INPUT_CLASS}+ />+ </FormField>+ );+}++/**+ * A row of mutually-exclusive or multi-select chips.+ *+ * The Facing and Applies-to groups were the same markup with a different active+ * predicate; sharing it puts `aria-pressed` on both rather than only one.+ */+function ToggleGroup({ label, options, isActive, onPick }) {+ return (+ <div>+ <span className={LABEL_CLASS}>{label}</span>+ <div className="flex flex-wrap gap-2">+ {options.map((option) => (+ <button+ key={String(option.value)}+ type="button"+ aria-pressed={isActive(option)}+ onClick={() => onPick(option)}+ className={`px-2.5 py-1.5 rounded text-xs border ${isActive(option)+ ? 'bg-port-accent border-port-accent text-white'+ : 'bg-port-bg border-port-border text-gray-300 hover:border-port-accent'}`}+ >+ {option.label}+ {option.hint && <span className="text-gray-400"> — {option.hint}</span>}+ </button>+ ))}+ </div>+ </div>+ );+}++const FACING_OPTIONS = [+ { value: false, label: 'One view', hint: 'renders once from the main reference' },+ { value: true, label: 'Per direction', hint: 'renders eight facings from the anchors' },+];++/**+ * The create/edit form. `track` is null for a new type.+ *+ * State is hoisted into this component rather than the Drawer body's children,+ * because the Drawer remounts its body on tab switch (`key={currentTab}`) — an+ * uncontrolled input inside would silently reset mid-edit.+ */+function TrackForm({ track, tracks, onSaved, onCancel }) {+ const isNew = !track;+ const [form, setForm] = useState(() => (track ? toForm(track) : BLANK));+ const [error, setError] = useState(null);+ const [saving, setSaving] = useState(false);++ // The caller remounts this component per edit target (`key`), so there is no+ // re-seed effect — the initializer above is the only place the draft is built.++ const set = (patch) => setForm((prev) => ({ ...prev, ...patch }));+ const toggleKind = (kind) => set({+ kinds: form.kinds.includes(kind) ? form.kinds.filter((k) => k !== kind) : [...form.kinds, kind],+ });++ const save = async () => {+ // Validated here rather than per render: nothing displays these, so computing+ // them on every keystroke was work for no output.+ const idTaken = isNew && form.id && tracks.some((row) => row.id === form.id);+ const problem = formError(form, { isNew })+ || (idTaken ? `'${form.id}' already exists — pick another id.` : null);+ if (problem) { setError(problem); return; }+ setSaving(true);+ setError(null);+ // Own error UI (the server's collision message is the useful one and belongs+ // beside the fields), so the API call is `{ silent: true }` per the toast+ // convention — otherwise the helper toasts and this renders it too.+ // The update schema is `.strict()` and has no `id` — the path param is the id, and+ // a rename is a delete-plus-create — so the patch must not carry one.+ const { id: _immutable, ...patch } = form;+ const result = isNew+ ? await createSpriteAnimationTrack(form, { silent: true }).catch((err) => err)+ : await updateSpriteAnimationTrack(track.id, patch, { silent: true }).catch((err) => err);+ setSaving(false);+ if (result instanceof Error) { setError(result.message || 'Save failed'); return; }+ toast.success(`${form.label} ${isNew ? 'created' : 'saved'} — restart the server to publish with it`);+ onSaved(result);+ };++ const derived = track ? {+ 'Contract field': track.contractFrameCountField,+ 'Review selection': track.selectionKind,+ 'Finalized set': track.setKind,+ } : null;++ return (+ <div className="space-y-4">+ {isNew ? (+ <FormField+ label="Id"+ hint="Names its folder on disk; cannot be changed later."+ labelClassName={LABEL_CLASS}+ >+ <input+ type="text"+ value={form.id}+ placeholder="chest-opening"+ onChange={(e) => set({ id: e.target.value.trim().toLowerCase() })}+ className={`${INPUT_CLASS} font-mono`}+ />+ </FormField>+ ) : (+ <p className="text-xs text-gray-400">+ Editing <span className="font-mono text-gray-200">{track.id}</span>. The id is fixed — it names this+ type's folder on disk and every render's record; to rename it, delete this type and add a new one.+ </p>+ )}++ <FormField label="Label" labelClassName={LABEL_CLASS}>+ <input+ type="text"+ value={form.label}+ placeholder="Chest opening"+ onChange={(e) => set({ label: e.target.value })}+ className={INPUT_CLASS}+ />+ </FormField>++ <ToggleGroup+ label="Facing"+ options={FACING_OPTIONS}+ isActive={(option) => form.directional === option.value}+ onPick={(option) => set({ directional: option.value })}+ />++ <ToggleGroup+ label="Applies to"+ options={NEW_SPRITE_KINDS}+ isActive={(option) => form.kinds.includes(option.value)}+ onPick={(option) => toggleKind(option.value)}+ />++ <div className="grid grid-cols-3 gap-2">+ <NumberField label="Min frames" min={1} max={64} value={form.minFrameCount} onChange={(v) => set({ minFrameCount: v })} />+ <NumberField label="Default frames" min={1} max={64} value={form.defaultFrameCount} onChange={(v) => set({ defaultFrameCount: v })} />+ <NumberField label="Max frames" min={1} max={64} value={form.maxFrameCount} onChange={(v) => set({ maxFrameCount: v })} />+ <NumberField label="Min fps" min={1} max={60} value={form.minFps} onChange={(v) => set({ minFps: v })} />+ <NumberField label="Default fps" min={1} max={60} value={form.defaultFps} onChange={(v) => set({ defaultFps: v })} />+ <NumberField label="Max fps" min={1} max={60} value={form.maxFps} onChange={(v) => set({ maxFps: v })} />+ </div>++ <div>+ <FormField+ label="Prompt template"+ hint="Sent to the video model for every render."+ labelClassName={LABEL_CLASS}+ >+ <textarea+ rows={6}+ value={form.promptTemplate}+ placeholder="Animate the {{kind}} {{name}} opening once, then return to the exact starting pose. Matte on {{chromaKeyPhrase}}."+ onChange={(e) => set({ promptTemplate: e.target.value })}+ className={`${INPUT_CLASS} font-mono`}+ />+ </FormField>+ <p className="text-xs text-gray-500 mt-1">+ Placeholders: <span className="font-mono">{'{{name}}'}</span> <span className="font-mono">{'{{kind}}'}</span>{' '}+ <span className="font-mono">{'{{direction}}'}</span> <span className="font-mono">{'{{chromaKey}}'}</span>{' '}+ <span className="font-mono">{'{{chromaKeyPhrase}}'}</span>. Anything else is left as written, so a typo+ shows up in the prompt instead of vanishing.+ </p>+ </div>++ {derived && (+ <div className="border border-port-border rounded p-2 space-y-1">+ <p className="text-xs text-gray-400">+ Derived from the id — these name files on disk and the publish-contract key, so PortOS owns them:+ </p>+ {Object.entries(derived).map(([name, value]) => (+ <p key={name} className="text-xs text-gray-500">+ {name}: <span className="font-mono text-gray-300">{value}</span>+ </p>+ ))}+ </div>+ )}++ {error && <Banner tone="error" icon={AlertTriangle} size="sm">{error}</Banner>}++ <div className="flex items-center gap-2">+ <button+ type="button"+ onClick={save}+ disabled={saving}+ className="px-3 py-1.5 bg-port-accent hover:bg-blue-600 disabled:opacity-50 text-white rounded text-sm"+ >+ {saving ? 'Saving…' : isNew ? 'Create type' : 'Save changes'}+ </button>+ <button+ type="button"+ onClick={onCancel}+ className="px-3 py-1.5 bg-port-bg border border-port-border hover:border-port-accent text-gray-300 rounded text-sm"+ >+ Cancel+ </button>+ </div>+ </div>+ );+}++function TrackRow({ track, onEdit, onDeleted }) {+ const [confirming, setConfirming] = useState(false);+ const [deleting, setDeleting] = useState(false);+ const [error, setError] = useState(null);++ const remove = async () => {+ setDeleting(true);+ setError(null);+ // Own error UI: the server's in-use refusal names the sprites that carry+ // approved work, which is the whole point of the 409 — so `{ silent: true }`.+ const result = await deleteSpriteAnimationTrack(track.id, { silent: true }).catch((err) => err);+ setDeleting(false);+ if (result instanceof Error) { setError(result.message || 'Delete failed'); return; }+ toast.success(`${track.label} deleted`);+ onDeleted(result);+ };++ return (+ <div className="border border-port-border rounded p-3 space-y-2">+ <div className="flex flex-wrap items-center gap-2">+ <span className="text-sm font-semibold text-white">{track.label}</span>+ <span className="text-xs font-mono text-gray-500">{track.id}</span>+ {track.builtin && <Pill tone="muted" icon={Lock}>Built-in</Pill>}+ {track.standaloneContract && <Pill tone="muted">Publish baseline</Pill>}+ {!track.builtin && !confirming && (+ <div className="flex items-center gap-2 ml-auto">+ <button+ type="button"+ onClick={() => onEdit(track)}+ className="flex items-center gap-1.5 px-2.5 py-1 text-xs bg-port-bg border border-port-border hover:border-port-accent text-gray-300 rounded"+ >+ <Pencil className="w-3.5 h-3.5" /> Edit+ </button>+ <button+ type="button"+ onClick={() => { setError(null); setConfirming(true); }}+ className="flex items-center gap-1.5 px-2.5 py-1 text-xs bg-port-bg border border-port-border hover:border-port-error text-gray-300 hover:text-port-error rounded"+ >+ <Trash2 className="w-3.5 h-3.5" /> Delete+ </button>+ </div>+ )}+ </div>+ <p className="text-xs text-gray-400">+ {track.directional ? 'Per direction' : 'One view'} · {track.kinds.join(', ')} ·{' '}+ {track.minFrameCount}–{track.maxFrameCount} frames (default {track.defaultFrameCount}) ·{' '}+ {track.minFps}–{track.maxFps} fps (default {track.defaultFps})+ </p>++ {confirming && (+ // Inline confirm row — the project convention (no window.confirm, and a+ // discoverable Cancel/Delete pair rather than a two-click arm).+ <div className="space-y-2 border border-port-error/40 bg-port-error/10 rounded p-2">+ <p className="text-xs text-gray-200">+ Delete <span className="font-semibold">{track.label}</span>? Sprites that already carry approved{' '}+ {track.id} renders keep those files, and the delete is refused until you reopen them.+ </p>+ {error && <Banner tone="error" size="sm">{error}</Banner>}+ <ConfirmButtonPair+ confirmIcon={Trash2}+ busy={deleting}+ busyText="Deleting"+ ariaLabel={`Confirm deleting ${track.label}`}+ onConfirm={remove}+ onCancel={() => { setConfirming(false); setError(null); }}+ />+ </div>+ )}+ </div>+ );+}++/**+ * `onClose(changed)` reports whether any type was created/edited/deleted while the+ * drawer was open, so the page only pays for its (expensive) record-detail refetch+ * when the registry actually moved — a peek-and-close costs nothing.+ */+export default function AnimationTypesDrawer({ open, onClose }) {+ const [activeTab, setActiveTab] = useDrawerTab('trackTab', 'list', TAB_IDS);+ const [searchParams, setSearchParams] = useSearchParams();+ // `null` = not loaded yet, `[]` = loaded and empty — the sentinel rule, so a+ // fetch failure or a pending load never renders as "you have no types".+ const [tracks, setTracks] = useState(null);+ const [loadError, setLoadError] = useState(null);+ const [origin, setOrigin] = useState(null);+ const [restartRequired, setRestartRequired] = useState(false);+ // Whether anything was mutated this session — a ref, not state, because nothing+ // renders from it; it only decides whether `onClose` asks the page to refetch.+ const mutatedRef = useRef(false);++ // WHICH type is being edited lives in the URL, not local state — the project's+ // "selection lives in the URL, never in local state" rule. It also removes the+ // parallel-state coordination the local version needed: `editing` is derived, so+ // there is one answer to "which form is open" instead of two kept in sync.+ const editingId = searchParams.get('editTrack');+ const editing = editingId ? tracks?.find((row) => row.id === editingId) || null : null;+ const setEditingId = useCallback((id) => {+ setSearchParams((prev) => {+ const params = new URLSearchParams(prev);+ if (id) params.set('editTrack', id);+ else params.delete('editTrack');+ return params;+ }, { replace: true });+ }, [setSearchParams]);++ const load = useCallback(async () => {+ setLoadError(null);+ const result = await listSpriteAnimationTracks({ silent: true }).catch((err) => err);+ if (result instanceof Error) { setLoadError(result.message || 'Could not load animation types'); return; }+ setTracks(result.tracks || []);+ setOrigin(result.origin || null);+ }, []);++ useEffect(() => { if (open) load(); }, [open, load]);++ // Every mutation returns the fresh table, so apply it directly instead of+ // refetching (the reactive-local-state convention).+ const applyMutation = useCallback((result) => {+ mutatedRef.current = true;+ setTracks(result.tracks || []);+ setOrigin('store');+ if (result.restartRequired) setRestartRequired(true);+ setEditingId(null);+ setActiveTab('list');+ }, [setActiveTab, setEditingId]);++ const close = useCallback(() => {+ setEditingId(null);+ onClose(mutatedRef.current);+ }, [onClose, setEditingId]);++ if (!open) return null;++ const body = () => {+ if (loadError) {+ return (+ <div className="space-y-3">+ <Banner tone="error" icon={AlertTriangle} size="sm">{loadError}</Banner>+ <button+ type="button"+ onClick={load}+ className="flex items-center gap-2 px-3 py-1.5 bg-port-bg border border-port-border hover:border-port-accent text-gray-300 rounded text-sm"+ >+ <RotateCcw className="w-4 h-4" /> Retry+ </button>+ </div>+ );+ }+ if (tracks === null) return <p className="text-sm text-gray-500">Loading…</p>;++ if (activeTab === 'new' || editing) {+ return (+ // Remount per edit target rather than re-seeding through an effect — same+ // "load THAT row" guarantee, without the extra render.+ <TrackForm+ key={editing?.id || 'new'}+ track={editing}+ tracks={tracks}+ onSaved={applyMutation}+ onCancel={() => { setEditingId(null); setActiveTab('list'); }}+ />+ );+ }++ return (+ <div className="space-y-3">+ {restartRequired && (+ <Banner tone="warning" icon={AlertTriangle} size="sm">+ Restart the PortOS server to publish sprites with a newly-added type — its runtime-contract+ field is registered at start-up. Generating and approving renders works right away.+ </Banner>+ )}+ {origin === 'seed' && (+ <Banner tone="info" icon={Info} size="sm">+ These are the starter types PortOS ships with. Your first change writes your own copy, after+ which updates never re-add a type you deleted.+ </Banner>+ )}+ {tracks.map((track) => (+ <TrackRow+ key={track.id}+ track={track}+ onEdit={(row) => setEditingId(row.id)}+ onDeleted={applyMutation}+ />+ ))}+ <button+ type="button"+ onClick={() => setActiveTab('new')}+ className="flex items-center gap-2 px-3 py-1.5 bg-port-accent hover:bg-blue-600 text-white rounded text-sm"+ >+ <Plus className="w-4 h-4" /> Add animation type+ </button>+ </div>+ );+ };++ return (+ <Drawer+ open+ onClose={close}+ title="Animation types"+ subtitle="The sequences your sprites can be animated through"+ size="lg"+ tabs={TABS}+ activeTab={editing ? 'new' : activeTab}+ onTabChange={(id) => { setEditingId(null); setActiveTab(id); }}+ // A half-typed prompt template is real work — an Esc keystroke or a stray+ // backdrop click must not discard it.+ closeOnEsc={false}+ closeOnBackdrop={false}+ closeLabel="Close animation types"+ >+ {body()}+ </Drawer>+ );+}diff --git a/client/src/components/sprites/AnimationTypesDrawer.test.jsx b/client/src/components/sprites/AnimationTypesDrawer.test.jsxnew file mode 100644index 0000000000..9908179f04--- /dev/null+++ b/client/src/components/sprites/AnimationTypesDrawer.test.jsx@@ -0,0 +1,293 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { MemoryRouter } from 'react-router-dom';++/**+ * Manage animation types (#3153).+ *+ * The server owns every refusal that matters (id/discriminator collisions, the+ * in-use delete, a record kind losing its baseline) and `animationTrackCrud.test.js`+ * proves those. What only this component can get wrong is:+ *+ * - the built-in row being editable/deletable at all (`walk` must be neither)+ * - sending a DERIVED field, which the server's `.strict()` schema would 400 —+ * so the form must submit the authored subset and nothing else+ * - swallowing the server's message: a 409 that names the conflicting field or the+ * sprites holding approved work is the whole value of the refusal, and a generic+ * "save failed" makes it unactionable+ * - the bounds pre-check, which exists so the user sees the problem in the field+ * - the sentinel distinction between "not loaded" and "loaded and empty"+ */++const listSpriteAnimationTracks = vi.fn();+const createSpriteAnimationTrack = vi.fn();+const updateSpriteAnimationTrack = vi.fn();+const deleteSpriteAnimationTrack = vi.fn();++vi.mock('../../services/apiSprites.js', () => ({+ listSpriteAnimationTracks: (...args) => listSpriteAnimationTracks(...args),+ createSpriteAnimationTrack: (...args) => createSpriteAnimationTrack(...args),+ updateSpriteAnimationTrack: (...args) => updateSpriteAnimationTrack(...args),+ deleteSpriteAnimationTrack: (...args) => deleteSpriteAnimationTrack(...args),+}));++vi.mock('../ui/Toast', () => ({+ default: { success: vi.fn(), error: vi.fn() },+}));++import AnimationTypesDrawer from './AnimationTypesDrawer.jsx';++const WALK = {+ id: 'walk', label: 'Walk cycle', builtin: true, directional: true, kinds: ['character'],+ minFrameCount: 6, maxFrameCount: 16, defaultFrameCount: 12, minFps: 4, maxFps: 24, defaultFps: 10,+ standaloneContract: true, contractFrameCountField: 'walkFrameCount',+ selectionKind: 'reviewed-directional-walk-selection', setKind: 'finalized-eight-direction-walk-set',+};+const CHEST = {+ id: 'chest-opening', label: 'Chest opening', builtin: false, directional: false, kinds: ['object'],+ minFrameCount: 2, maxFrameCount: 8, defaultFrameCount: 4, minFps: 2, maxFps: 12, defaultFps: 6,+ standaloneContract: true, contractFrameCountField: 'chestOpeningFrameCount',+ selectionKind: 'reviewed-chest-opening-selection', setKind: 'finalized-chest-opening-set',+ promptTemplate: 'Animate the {{kind}} {{name}} opening once.',+};++const renderDrawer = () => render(+ <MemoryRouter>+ <AnimationTypesDrawer open onClose={vi.fn()} />+ </MemoryRouter>,+);++beforeEach(() => {+ vi.clearAllMocks();+ listSpriteAnimationTracks.mockResolvedValue({ tracks: [WALK, CHEST], storePath: 'sprites/animation-tracks.json', origin: 'store' });+ createSpriteAnimationTrack.mockResolvedValue({ tracks: [WALK], restartRequired: true });+ updateSpriteAnimationTrack.mockResolvedValue({ tracks: [WALK, CHEST], restartRequired: true });+ deleteSpriteAnimationTrack.mockResolvedValue({ tracks: [WALK], restartRequired: true });+});++/** Fill the create form with a valid type; returns the values submitted. */+async function fillNewType(overrides = {}) {+ fireEvent.click(screen.getByRole('button', { name: /add animation type/i }));+ const values = {+ id: 'jetpack', label: 'Jetpack burst', promptTemplate: 'Animate {{name}} firing a jetpack.', ...overrides,+ };+ fireEvent.change(await screen.findByLabelText(/^Id/), { target: { value: values.id } });+ fireEvent.change(screen.getByLabelText(/^Label/), { target: { value: values.label } });+ fireEvent.change(screen.getByLabelText(/^Prompt template/), { target: { value: values.promptTemplate } });+ return values;+}++describe('AnimationTypesDrawer listing', () => {+ it('lists every registered type with its bounds', async () => {+ renderDrawer();+ expect(await screen.findByText('Walk cycle')).toBeInTheDocument();+ expect(screen.getByText('Chest opening')).toBeInTheDocument();+ expect(screen.getByText(/2–8 frames \(default 4\)/)).toBeInTheDocument();+ });++ it('marks the built-in as built-in and offers it no Edit or Delete', async () => {+ renderDrawer();+ await screen.findByText('Walk cycle');+ expect(screen.getByText('Built-in')).toBeInTheDocument();+ // Exactly one editable row (the stored one) — walk must not be mutable through a+ // data edit: its bounds feed the server's Zod schemas and its set gates every+ // character compile.+ expect(screen.getAllByRole('button', { name: /^Edit$/ })).toHaveLength(1);+ expect(screen.getAllByRole('button', { name: /^Delete$/ })).toHaveLength(1);+ });++ it('distinguishes "not loaded yet" from "loaded and empty"', async () => {+ let resolve;+ listSpriteAnimationTracks.mockReturnValue(new Promise((r) => { resolve = r; }));+ renderDrawer();+ // Pending: a loading note, never an empty list that reads as "you have none".+ expect(screen.getByText(/Loading…/)).toBeInTheDocument();+ resolve({ tracks: [WALK], storePath: 'p', origin: 'seed' });+ expect(await screen.findByText('Walk cycle')).toBeInTheDocument();+ });++ it('surfaces a load failure with a retry instead of an empty list', async () => {+ listSpriteAnimationTracks.mockRejectedValueOnce(new Error('animation-tracks.json is not valid JSON'));+ renderDrawer();+ expect(await screen.findByText(/not valid JSON/)).toBeInTheDocument();+ listSpriteAnimationTracks.mockResolvedValueOnce({ tracks: [WALK], storePath: 'p', origin: 'store' });+ fireEvent.click(screen.getByRole('button', { name: /retry/i }));+ expect(await screen.findByText('Walk cycle')).toBeInTheDocument();+ });++ it('says the rows are shipped starters until this install has its own copy', async () => {+ listSpriteAnimationTracks.mockResolvedValue({ tracks: [WALK, CHEST], storePath: 'p', origin: 'seed' });+ renderDrawer();+ expect(await screen.findByText(/starter types PortOS ships with/)).toBeInTheDocument();+ });+});++describe('AnimationTypesDrawer create', () => {+ it('submits the authored subset only — no derived field the server would 400', async () => {+ renderDrawer();+ await screen.findByText('Chest opening');+ const values = await fillNewType();+ fireEvent.click(screen.getByRole('button', { name: /create type/i }));++ await waitFor(() => expect(createSpriteAnimationTrack).toHaveBeenCalled());+ const [body, options] = createSpriteAnimationTrack.mock.calls[0];+ expect(body).toEqual({+ id: values.id,+ label: values.label,+ directional: false,+ kinds: ['object'],+ minFrameCount: 2,+ maxFrameCount: 8,+ defaultFrameCount: 4,+ minFps: 2,+ maxFps: 12,+ defaultFps: 6,+ promptTemplate: values.promptTemplate,+ });+ // The five on-disk/contract discriminators are PortOS's to derive; sending one+ // would be refused by the server's `.strict()` schema.+ for (const derived of ['setKind', 'selectionKind', 'contractFrameCountField', 'standaloneContract', 'builtin']) {+ expect(body).not.toHaveProperty(derived);+ }+ // The caller owns its error UI, so the helper must not also toast.+ expect(options).toEqual({ silent: true });+ });++ it('renders the server\'s collision message verbatim rather than a generic failure', async () => {+ createSpriteAnimationTrack.mockRejectedValueOnce(new Error(+ "animationTracks: contract field 'jetpackFrameCount' is claimed by both 'jetpack.contractFrameCountField' and 'jetpack.contractFpsField'",+ ));+ renderDrawer();+ await screen.findByText('Chest opening');+ await fillNewType();+ fireEvent.click(screen.getByRole('button', { name: /create type/i }));+ expect(await screen.findByText(/jetpackFrameCount/)).toBeInTheDocument();+ });++ it('blocks an out-of-order bounds triple in the field, before any request', async () => {+ renderDrawer();+ await screen.findByText('Chest opening');+ await fillNewType();+ fireEvent.change(screen.getByLabelText(/^Min frames/), { target: { value: '6' } });+ fireEvent.click(screen.getByRole('button', { name: /create type/i }));+ expect(await screen.findByText(/minimum ≤ default ≤ maximum/i)).toBeInTheDocument();+ expect(createSpriteAnimationTrack).not.toHaveBeenCalled();+ });++ it('blocks a duplicate id, a blank label, and a blank prompt locally', async () => {+ renderDrawer();+ await screen.findByText('Chest opening');+ // A duplicate id is caught here so the user isn't told "already exists" only+ // after a round-trip.+ await fillNewType({ id: 'chest-opening' });+ fireEvent.click(screen.getByRole('button', { name: /create type/i }));+ expect(await screen.findByText(/already exists/i)).toBeInTheDocument();+ expect(createSpriteAnimationTrack).not.toHaveBeenCalled();++ fireEvent.change(screen.getByLabelText(/^Id/), { target: { value: 'jetpack' } });+ fireEvent.change(screen.getByLabelText(/^Prompt template/), { target: { value: '' } });+ fireEvent.click(screen.getByRole('button', { name: /create type/i }));+ expect(await screen.findByText(/prompt template is required/i)).toBeInTheDocument();+ expect(createSpriteAnimationTrack).not.toHaveBeenCalled();+ });++ it('requires at least one sprite kind', async () => {+ renderDrawer();+ await screen.findByText('Chest opening');+ await fillNewType();+ // Deselect the default kind (labels come from the shared NEW_SPRITE_KINDS).+ fireEvent.click(screen.getByRole('button', { name: 'Object' }));+ fireEvent.click(screen.getByRole('button', { name: /create type/i }));+ expect(await screen.findByText(/at least one sprite kind/i)).toBeInTheDocument();+ expect(createSpriteAnimationTrack).not.toHaveBeenCalled();+ });++ it('warns that a restart is needed to publish with a new type', async () => {+ createSpriteAnimationTrack.mockResolvedValueOnce({ tracks: [WALK, CHEST], restartRequired: true });+ renderDrawer();+ await screen.findByText('Chest opening');+ await fillNewType();+ fireEvent.click(screen.getByRole('button', { name: /create type/i }));+ // The registry itself is live after the write; only the publish-contract field is+ // registered at start-up, and saying so is the difference between a documented+ // boundary and a field that silently does nothing.+ expect(await screen.findByText(/Restart the PortOS server to publish/)).toBeInTheDocument();+ });+});++describe('AnimationTypesDrawer edit', () => {+ it('loads the row, hides the id as immutable, and shows the derived fields', async () => {+ renderDrawer();+ await screen.findByText('Chest opening');+ fireEvent.click(screen.getByRole('button', { name: /^Edit$/ }));+ // No id input — renaming would have to migrate the on-disk directories, so it is+ // a delete-plus-create.+ expect(screen.queryByLabelText(/^Id/)).not.toBeInTheDocument();+ expect(screen.getByText(/id is fixed/i)).toBeInTheDocument();+ expect(screen.getByDisplayValue('Chest opening')).toBeInTheDocument();+ // The derivation is shown so a collision refusal naming one of these is legible.+ expect(screen.getByText('finalized-chest-opening-set')).toBeInTheDocument();+ });++ it('PUTs the authored subset for the edited id', async () => {+ renderDrawer();+ await screen.findByText('Chest opening');+ fireEvent.click(screen.getByRole('button', { name: /^Edit$/ }));+ fireEvent.change(await screen.findByLabelText(/^Label/), { target: { value: 'Chest opens' } });+ fireEvent.click(screen.getByRole('button', { name: /save changes/i }));++ await waitFor(() => expect(updateSpriteAnimationTrack).toHaveBeenCalled());+ const [trackId, patch, options] = updateSpriteAnimationTrack.mock.calls[0];+ expect(trackId).toBe('chest-opening');+ expect(patch.label).toBe('Chest opens');+ // The update schema is `.strict()` and declares no `id` — the path param owns it+ // and a rename is a delete-plus-create — so an `id` in the patch is a 400 that+ // would make every save fail. Neither it nor any derived field may ride along.+ for (const forbidden of ['id', 'setKind', 'selectionKind', 'contractFrameCountField', 'standaloneContract', 'builtin']) {+ expect(patch).not.toHaveProperty(forbidden);+ }+ expect(options).toEqual({ silent: true });+ });+});++describe('AnimationTypesDrawer delete', () => {+ // The confirm copy interleaves a <span> around the label, so match on the+ // surrounding sentence rather than a string spanning both nodes.+ const confirmPrompt = () => screen.findByText(/keep those files, and the delete is refused/);++ it('confirms inline (never window.confirm) and deletes on the second click', async () => {+ renderDrawer();+ await screen.findByText('Chest opening');+ fireEvent.click(screen.getByRole('button', { name: /^Delete$/ }));+ expect(await confirmPrompt()).toBeInTheDocument();+ // A discoverable Cancel/Delete pair, not a two-click arm.+ fireEvent.click(screen.getByRole('button', { name: /^Cancel$/ }));+ expect(deleteSpriteAnimationTrack).not.toHaveBeenCalled();++ fireEvent.click(screen.getByRole('button', { name: /^Delete$/ }));+ await confirmPrompt();+ // Two Delete buttons exist once armed (the row trigger is replaced by the+ // confirm row's pair) — the confirm row's is the last in the DOM.+ const deletes = screen.getAllByRole('button', { name: /^Delete$/ });+ fireEvent.click(deletes[deletes.length - 1]);+ await waitFor(() => expect(deleteSpriteAnimationTrack).toHaveBeenCalledWith('chest-opening', { silent: true }));+ });++ it('shows the in-use refusal, naming the sprites that hold approved work', async () => {+ deleteSpriteAnimationTrack.mockRejectedValueOnce(new Error(+ "Cannot delete 'chest-opening' — 2 sprites already carry approved chest-opening work: pioneer, crates. Reopen or unlock those sets first.",+ ));+ renderDrawer();+ await screen.findByText('Chest opening');+ fireEvent.click(screen.getByRole('button', { name: /^Delete$/ }));+ await confirmPrompt();+ const deletes = screen.getAllByRole('button', { name: /^Delete$/ });+ fireEvent.click(deletes[deletes.length - 1]);+ expect(await screen.findByText(/pioneer, crates/)).toBeInTheDocument();+ // The row survives — a refused delete must not optimistically vanish. (The+ // label appears twice while the confirm row is still open: once as the row+ // heading, once in the confirm copy.)+ expect(screen.getAllByText('Chest opening').length).toBeGreaterThan(0);+ expect(screen.getByText(/2–8 frames \(default 4\)/)).toBeInTheDocument();+ });+});diff --git a/client/src/pages/Sprites.jsx b/client/src/pages/Sprites.jsxindex f8b5de531d..18090867d7 100644--- a/client/src/pages/Sprites.jsx+++ b/client/src/pages/Sprites.jsx@@ -1,6 +1,6 @@import { useEffect, useState, useCallback, useMemo, useRef } from 'react';import { useParams, useNavigate, useSearchParams } from 'react-router-dom';-import { PersonStanding, Download, X, RefreshCw, Plus, LayoutGrid, Search, Images, Scissors } from 'lucide-react';+import { PersonStanding, Download, X, RefreshCw, Plus, LayoutGrid, Search, Images, Scissors, Film } from 'lucide-react';import toast from '../components/ui/Toast';import Modal from '../components/ui/Modal.jsx';import {@@ -15,6 +15,7 @@ import ReferenceWorkflow from '../components/sprites/ReferenceWorkflow.jsx';import WalkWorkflow from '../components/sprites/WalkWorkflow.jsx';import TrackWorkflow from '../components/sprites/TrackWorkflow.jsx';import AmbientWorkflow from '../components/sprites/AmbientWorkflow.jsx';+import AnimationTypesDrawer from '../components/sprites/AnimationTypesDrawer.jsx';import { GROK_VIDEO_DEFAULT_DURATION } from '../lib/grokVideoClip.js';import LoopTrimmer from '../components/sprites/LoopTrimmer.jsx';import PublishWorkflow from '../components/sprites/PublishWorkflow.jsx';@@ -463,6 +464,18 @@ export default function Sprites() {const [searchParams, setSearchParams] = useSearchParams();const [spriteTab, setSpriteTab] = useDrawerTab('spriteTab', 'library', ['library', 'trimmer']);const trimRunParam = searchParams.get('run');+ // The animation-types drawer (#3153) is library-wide, not per-record, so its+ // open state lives in its own search param — deep-linkable per the "URL is the+ // source of truth for what's open" rule, and independent of `spriteTab`/`run`.+ const animationTypesOpen = searchParams.get('animationTypes') === '1';+ const setAnimationTypesOpen = useCallback((next) => {+ setSearchParams((prev) => {+ const params = new URLSearchParams(prev);+ if (next) params.set('animationTypes', '1');+ else params.delete('animationTypes');+ return params;+ });+ }, [setSearchParams]);// Open the trimmer deep-linked to a run. `replace` keeps an in-trimmer source// switch out of history; the default push lets Back return to the Library.const openTrimmer = useCallback((runId, { replace = false } = {}) => {@@ -692,6 +705,15 @@ export default function Sprites() {</button>)}{records?.length > 0 && <SpriteSearch records={records} onSelect={goto} />}+ {/* Library-wide, so it sits beside create/import and is reachable from+ the bare /sprites catalog as well as an open record. */}+ <button+ type="button"+ onClick={() => setAnimationTypesOpen(true)}+ className="flex items-center gap-2 px-3 py-1.5 bg-port-card border border-port-border hover:border-port-accent text-gray-300 rounded text-sm"+ >+ <Film className="w-4 h-4" /> Animation types+ </button><NewSpritePanel onCreated={(record) => { refresh(); navigate(`/sprites/${record.id}`); }} />{/* Re-import while a sprite is open must refresh the open detail too,not just the library list. */}@@ -852,6 +874,17 @@ export default function Sprites() {)}</section></div>+ {/* Rendered last so the slide-in panel layers over the catalog/detail pane.+ A newly-authored type only reaches an OPEN record's workflow list on the+ next detail fetch — so refetch when the drawer reports a change, and skip+ the (recursive-readdir) detail fetch entirely on a peek-and-close. */}+ <AnimationTypesDrawer+ open={animationTypesOpen}+ onClose={(changed) => {+ setAnimationTypesOpen(false);+ if (changed && id) setRetryTick((t) => t + 1);+ }}+ /></div>);}diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 181d6009f3..040ca54d04 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -96,7 +96,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiCreativeDirector.js` | Creative Director (video production). || `apiCreativeCommission.js` | Creative Commissions (Autonomous Creation Engine — standing recurring briefs). || `apiMusicVideo.js` | Music Video projects + scene board + audio analysis. |-| `apiSprites.js` | Sprite Manager records, asset library, production-set import (#2895), reference workflow: create/generate/lock (#2896), directional walk and scanner-track generation/approval, trim/postprocess, and per-run source-frame listing for the Loop Trimmer's re-derive (#2980). |+| `apiSprites.js` | Sprite Manager records, asset library, production-set import (#2895), reference workflow: create/generate/lock (#2896), directional walk and per-track generation/approval, animation-type definition CRUD (#3153), trim/postprocess, and per-run source-frame listing for the Loop Trimmer's re-derive (#2980). || `apiThreejsModels.js` | Procedural Three.js model workspaces: gallery-image generation, refinement, source export, and deletion. || `apiImageTo3d.js` | Image-to-3D (`/media/3d`): selectable targets (TRELLIS.2) with host availability/install status, and per-image model records — create/list/get/generate/delete + GLB asset URL. || `apiPipeline.js` | Pipeline (issues + stages + canon). |diff --git a/client/src/services/apiSprites.js b/client/src/services/apiSprites.jsindex e762a1f929..1379451c59 100644--- a/client/src/services/apiSprites.js+++ b/client/src/services/apiSprites.js@@ -150,6 +150,30 @@ export const approveSpriteTrack = (id, trackId, body = {}, options = {}) => requ{ method: 'POST', body: JSON.stringify(body), ...options },);+// Animation-type definitions (#3153) — the registry the workflow surfaces render+// from, and the CRUD over the user-defined half of it. The list returns+// `{ tracks, storePath, origin }` (`origin: 'seed' | 'store'` — whether this+// install has saved its own copy yet); every mutation returns the same `tracks`+// plus `restartRequired`, because `spriteRuntimeContractSchema`'s per-track+// publish-contract field is built once at server start. Every caller owns its own+// error UI (the drawer shows the server's collision/in-use message inline), so+// they all pass `{ silent: true }`.+export const listSpriteAnimationTracks = (options = {}) => request('/sprites/animation-tracks', options);++export const createSpriteAnimationTrack = (body, options = {}) => request('/sprites/animation-tracks', {+ method: 'POST', body: JSON.stringify(body), ...options,+});++export const updateSpriteAnimationTrack = (trackId, patch, options = {}) => request(+ `/sprites/animation-tracks/${encodeURIComponent(trackId)}`,+ { method: 'PUT', body: JSON.stringify(patch), ...options },+);++export const deleteSpriteAnimationTrack = (trackId, options = {}) => request(+ `/sprites/animation-tracks/${encodeURIComponent(trackId)}`,+ { method: 'DELETE', ...options },+);+// Re-run the deterministic postprocess on a run whose video already landed.export const postprocessSpriteWalk = (id, body, options = {}) => request(`/sprites/${encodeURIComponent(id)}/walk/postprocess`, {method: 'POST', body: JSON.stringify(body), ...options,diff --git a/docs/features/sprite-export-contract.md b/docs/features/sprite-export-contract.mdindex 5e77afd90e..6e902979fd 100644--- a/docs/features/sprite-export-contract.md+++ b/docs/features/sprite-export-contract.md@@ -24,10 +24,10 @@ Frame-count and fps uniformity is a **within-track** rule, never a between-track**Which tracks exist is not a fixed list, and it is not fixed by PortOS either.** `walk` is the mandatory baseline for a character — the one animation every character has, the only one compiled into PortOS, and the only one this document can promise a reader will be there. Everything else, including the shipped `scanner` action and `ambient` loop, is an ordinary **row** describing its own label, facing count, frame/fps range, the locked reference its render is seeded from, the `runtimeContract` field it occupies, and its image-to-video prompt. A consuming app must therefore treat the track set as **discovered from `geometry.tracks`, never enumerated in code** (see "Resolve columns by name, not by constant" below) — the atlas it reads next year may carry a track nobody had named when it was written.-**Non-walk rows are user data, stored per install.** They live in `data/sprites/animation-tracks.json` (`server/services/sprites/animationTrackStore.js` merges them with `walk` into the effective registry). `scanner` and `ambient` ship as **seed rows** in `data.reference/sprites/animation-tracks.json` — a user may retune their bounds, reword their prompts, or delete them outright, and may add their own ("a chest opening", "a flower blossoming", "a jetpack burst") without a PortOS code change. Two consequences worth stating plainly:+**Non-walk rows are user data, stored per install, and authored from the UI.** They live in `data/sprites/animation-tracks.json` (`server/services/sprites/animationTrackStore.js` merges them with `walk` into the effective registry), and Sprite Manager's **Animation types** drawer is the CRUD surface over them (`GET/POST/PUT/DELETE /api/sprites/animation-tracks`, `server/services/sprites/animationTrackCrud.js`). `scanner` and `ambient` ship as **seed rows** in `data.reference/sprites/animation-tracks.json` — a user may retune their bounds, reword their prompts, or delete them outright, and may add their own ("a chest opening", "a flower blossoming", "a jetpack burst") without a PortOS code change. Two consequences worth stating plainly:- **Two installs can legitimately disagree about which tracks exist.** An atlas is self-describing (`geometry.tracks` + `columns`) precisely so a consumer never needs the producing install's registry.-- **A row's `selectionKind` / `setKind` are on-disk contracts, not labels.** The compiler re-verifies an approved set by those exact strings, so renaming them on a track you have already authored orphans that set. Adding, deleting, or retuning a row takes effect on the next server start.+- **A row's `selectionKind` / `setKind` are on-disk contracts, not labels.** The compiler re-verifies an approved set by those exact strings, so renaming them on a track you have already authored orphans that set. This is why the drawer never lets you type them: it derives all five discriminators (`contractFrameCountField`, `contractFpsField`, `selectionKind`, `setKind`, `finalErrorCode`) plus `standaloneContract` from the track id, carries them over verbatim when you edit an existing row, refuses a delete or a facing-mode flip while any record still holds approved work for that track (409 naming the records — there is no force flag), and treats a track's `id` as immutable after creation. Adding, deleting, or retuning a row takes effect immediately for generate/approve, but a **newly-added** track's `runtimeContract` field is registered at server start, so publishing with it needs a restart (the drawer says so).The consequence for the app side is small but load-bearing: a track's *presence* is optional and its *name* is user-chosen, so an app keys off the track ids it actually needs and ignores the rest. Nothing about the grid, cell metrics, pivot, or row semantics changes when a track is added.@@ -132,6 +132,7 @@ Two mechanisms guard that:| `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` | The one COMPILED row (`walk`) and the row contract itself — bounds, defaults, directionality, which record kinds may carry a track, its on-disk set/selection kinds, and whether it is the kind's publishable baseline (`standaloneContract`). Imports nothing: `server/lib/validation.js` builds its sprite Zod ranges from here, so the native image graph must stay out || `server/services/sprites/animationTrackStore.js` | Loads the user-defined rows from `data/sprites/animation-tracks.json` (falling back to the `data.reference/` seed) and merges them with `walk` into the effective registry every reader resolves against |+| `server/services/sprites/animationTrackCrud.js` | The WRITE side of that store (#3153): derives the discriminators from the id, refuses a built-in / colliding / in-use mutation, serializes writes and drops the registry cache. Separate from the read-side store so `validation.js`'s import graph stays clear of the record scan the in-use refusal needs || `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 — the compiled builder for `walk`, the row's own `promptTemplate` for a stored track || `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.jsindex fb86af0dfc..0fdc592059 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -5,7 +5,9 @@ import { WORK_TRACKERS } from './workTracker.js';import { SPRITE_ID_PATTERN, SPRITE_RECORD_KINDS } from '../services/sprites/recordsLogic.js';import { ANCHOR_DIRECTIONS, SPRITE_DIRECTIONS, TURNAROUND_ID } from '../services/sprites/prompts.js';import { CHROMA_KEY_HEXES } from '../services/sprites/chromaKey.js';-import { WALK_TRACK } from '../services/sprites/animationTracks.js';+import {+ WALK_TRACK, AUTHORED_TRACK_FIELDS, TRACK_BOUND_TRIPLES,+} from '../services/sprites/animationTracks.js';// #3152 — the EFFECTIVE table (compiled `walk` + the user-defined store), so a// user's track validates against its own bounds and occupies its own contract// field with no schema edit. The store reads one small JSON config synchronously@@ -1307,6 +1309,90 @@ export const spriteTrackParamsSchema = z.object({trackId: z.string().min(1).max(64).regex(/^[a-z0-9][a-z0-9-]*$/, 'invalid animation track id'),});+// Authoring a user-defined animation type (#3153) — the user-facing subset of a+// registry row, and NOTHING else. The five on-disk/contract discriminators+// (`contractFrameCountField`, `selectionKind`, `setKind`, `finalErrorCode`,+// `contractFpsField`) plus `standaloneContract` and `builtin` are DERIVED by+// `animationTrackCrud.js` and deliberately absent here: they name files on disk and+// publish-contract keys that `assertAnimationTrackRows` requires to be globally+// unique, so accepting them from a request would let a typo hand one track another's+// evidence chain. `.strict()` is what makes that a 400 the user can see rather than a+// silently-stripped field they think they set.+//+// The frame/fps bounds are NOT registry-derived (unlike every other sprite schema+// here) because this request is what DEFINES a track's bounds — there is no row to+// read them from yet. The outer envelope is the widest the pipeline can pack; the+// `min <= default <= max` ordering is the registry's own cross-field rule and is+// asserted by `assertAnimationTrackRows` at save time, restated here only so the+// form gets a per-field 400 instead of a whole-table 409.+const spriteTrackBoundSchema = z.number().int().min(1).max(64);+const spriteTrackFpsBoundSchema = z.number().int().min(1).max(60);++// Keyed off AUTHORED_TRACK_FIELDS so this shape and the service's whitelist cannot+// drift — a field in one and not the other fails silently in one direction (Zod+// strips it) and as an unrecognized key in the other. The unusual `Object.fromEntries`+// spelling is what makes that coupling mechanical: adding a key to the constant+// without a validator here is an immediate boot failure naming the field, instead of+// a value that reaches the store unvalidated.+const SPRITE_ANIMATION_TRACK_FIELD_SCHEMAS = {+ label: z.string().min(1).max(120),+ directional: z.boolean(),+ kinds: z.array(z.enum(SPRITE_RECORD_KINDS)).min(1),+ minFrameCount: spriteTrackBoundSchema,+ maxFrameCount: spriteTrackBoundSchema,+ defaultFrameCount: spriteTrackBoundSchema,+ minFps: spriteTrackFpsBoundSchema,+ maxFps: spriteTrackFpsBoundSchema,+ defaultFps: spriteTrackFpsBoundSchema,+ // The i2v instruction. A stored row MUST carry one (a user-defined track has no+ // compiled prompt builder to fall back to), so this is required on create and+ // non-empty on update — an empty template would throw out of+ // `buildTrackVideoPrompt` after the user clicked Generate.+ promptTemplate: z.string().min(1).max(4000),+};++const spriteAnimationTrackFields = Object.fromEntries(AUTHORED_TRACK_FIELDS.map((key) => {+ const schema = SPRITE_ANIMATION_TRACK_FIELD_SCHEMAS[key];+ if (!schema) throw new Error(`validation: no schema for authored animation-track field '${key}'`);+ return [key, schema];+}));++// `min <= default <= max` on both knobs (the registry's own `TRACK_BOUND_TRIPLES`,+// so the front-run check can't disagree with the assert it front-runs), reported on+// the offending field so the form can point at it.+//+// Applied to each schema rather than once to a shared base because zod 4 refuses+// `.partial()` on an object that already carries a refinement — so the shape has to+// be finished first, then refined. The partial (update) case is why each triple is+// skipped unless all three values are present: a patch that supplies only `maxFps`+// is validated against the merged row by the service, not here.+const refineTrackBounds = (schema) => schema.superRefine((value, ctx) => {+ for (const [min, def, max] of TRACK_BOUND_TRIPLES) {+ if ([value[min], value[def], value[max]].some((v) => v === undefined)) continue;+ if (value[min] <= value[def] && value[def] <= value[max]) continue;+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: [def],+ message: `${min} <= ${def} <= ${max} is required`,+ });+ }+});++export const spriteAnimationTrackCreateSchema = refineTrackBounds(z.object({+ // The id names the on-disk `<trackId>/` directory and every run's `track` field,+ // so it reuses the same slug charset the `:trackId` param enforces.+ id: spriteTrackParamsSchema.shape.trackId,+ ...spriteAnimationTrackFields,+}).strict());++// `id` is absent from the patch on purpose — renaming would have to migrate the+// on-disk directories, every run record and every manifest, so it is a+// delete-plus-create the user makes explicitly. `.strict()` turns an attempted+// rename into a 400 naming `id` rather than a silent no-op.+export const spriteAnimationTrackUpdateSchema = refineTrackBounds(+ z.object(spriteAnimationTrackFields).strict().partial(),+).refine((patch) => Object.keys(patch).length > 0, { message: 'at least one field is required' });+// Pin the walk track's cycle target at the SET level (#2985). Both knobs are// required: the target is one atomic set-level decision, and a partial write// would leave "which value did I actually pin?" ambiguous on a record everydiff --git a/server/routes/sprites.js b/server/routes/sprites.jsindex e2ce66bc14..b750d3bfda 100644--- a/server/routes/sprites.js+++ b/server/routes/sprites.js@@ -25,6 +25,8 @@ import {spriteTrackGenerateSchema,spriteTrackApproveSchema,spriteTrackParamsSchema,+ spriteAnimationTrackCreateSchema,+ spriteAnimationTrackUpdateSchema,spriteWalkGenerateSchema,spriteWalkApproveSchema,spriteWalkReopenSchema,@@ -66,6 +68,13 @@ import {unlockDirectionalAnchor, unlockMainReference, unlockTurnaroundReference,} from '../services/sprites/walk.js';import { getTrackState, startTrackGeneration, approveTrackRun } from '../services/sprites/animationTrackWorkflow.js';+// #3153 — CRUD over the user-defined store. Separate from the read-side store+// module so `validation.js`'s import graph stays free of the record scan the+// in-use refusal needs (see animationTrackCrud.js's header).+import {+ listAnimationTracks, createAnimationTrack, updateAnimationTrack, deleteAnimationTrack,+ animationTrackStoreOrigin,+} from '../services/sprites/animationTrackCrud.js';import { saveLoopTrim } from '../services/sprites/walkTrims.js';import { compileAtlas, getAtlasState } from '../services/sprites/atlas.js';import { resolveWalkFrameCount } from '../services/sprites/atlasGrid.js';@@ -150,6 +159,34 @@ router.get('/thumbnails', asyncHandler(async (_req, res) => {res.json(await listSpriteThumbnails());}));+// Authoring the user-defined animation types (#3153) — a record-INDEPENDENT+// surface, so like `/reference-sources` and `/thumbnails` it MUST precede `/:id`+// or the literal path is captured as a record id. The DELETE likewise precedes+// `DELETE /:id`; it can't collide (two segments vs. one) but the block stays+// together so the ordering rule is visible in one place.+//+// No AI call on any of these: a track definition is data. Generating anything+// FROM it stays behind the user-triggered `/tracks/:trackId/generate`.+router.get('/animation-tracks', asyncHandler(async (_req, res) => {+ res.json({ ...listAnimationTracks(), origin: await animationTrackStoreOrigin() });+}));++router.post('/animation-tracks', asyncHandler(async (req, res) => {+ const input = validateRequest(spriteAnimationTrackCreateSchema, req.body);+ res.status(201).json(await createAnimationTrack(input));+}));++router.put('/animation-tracks/:trackId', asyncHandler(async (req, res) => {+ const { trackId } = validateRequest(spriteTrackParamsSchema, req.params);+ const patch = validateRequest(spriteAnimationTrackUpdateSchema, req.body);+ res.json(await updateAnimationTrack(trackId, patch));+}));++router.delete('/animation-tracks/:trackId', asyncHandler(async (req, res) => {+ const { trackId } = validateRequest(spriteTrackParamsSchema, req.params);+ res.json(await deleteAnimationTrack(trackId));+}));+// Create a character record — the entry point of the reference workflow.// Id derivation and the kind live in the service (createCharacter).router.post('/', asyncHandler(async (req, res) => {diff --git a/server/routes/sprites.test.js b/server/routes/sprites.test.jsindex d42472cf8d..33e823bfd7 100644--- a/server/routes/sprites.test.js+++ b/server/routes/sprites.test.js@@ -82,6 +82,18 @@ vi.mock('../services/sprites/animationTrackWorkflow.js', () => ({approveTrackRun: vi.fn(async (track) => ({ track, runs: [], selection: { status: 'in-progress' }, set: null })),}));+// Animation-type CRUD (#3153). The service owns every refusal (built-in, collision,+// in-use) and the derivation; these tests are about the ROUTES — ordering ahead of+// `/:id`, which schema gates which verb, and that the id/patch reach the service+// unchanged. The refusals themselves are asserted in animationTrackCrud.test.js.+vi.mock('../services/sprites/animationTrackCrud.js', () => ({+ listAnimationTracks: vi.fn(() => ({ tracks: [{ id: 'walk', builtin: true }], storePath: 'sprites/animation-tracks.json' })),+ createAnimationTrack: vi.fn(async (input) => ({ tracks: [{ id: input.id }], restartRequired: true })),+ updateAnimationTrack: vi.fn(async () => ({ tracks: [], restartRequired: true })),+ deleteAnimationTrack: vi.fn(async () => ({ tracks: [], restartRequired: true })),+ animationTrackStoreOrigin: vi.fn(async () => 'seed'),+}));+vi.mock('../services/sprites/walkTrims.js', () => ({saveLoopTrim: vi.fn(async () => ({ strip: 'walk/trims/t-v001-strip.png', loop: 'walk/trims/t-v001.gif', manifest: 'walk/trims/t-v001.json', frameCount: 3, disabledFrameCount: 1 })),}));@@ -106,6 +118,7 @@ import * as reference from '../services/sprites/reference.js';import * as assetPrompt from '../services/sprites/assetPrompt.js';import * as walk from '../services/sprites/walk.js';import * as trackWorkflow from '../services/sprites/animationTrackWorkflow.js';+import * as trackCrud from '../services/sprites/animationTrackCrud.js';import * as walkTrims from '../services/sprites/walkTrims.js';import * as atlas from '../services/sprites/atlas.js';import * as publish from '../services/sprites/publish.js';@@ -164,6 +177,178 @@ describe('sprites routes', () => {expect(records.getRecordWithAssets).not.toHaveBeenCalled();});+ // Animation-type CRUD (#3153) — the authoring surface for the user-defined half+ // of the track registry.+ describe('animation-type CRUD', () => {+ it('GET /animation-tracks lists the registry and the store origin (before /:id)', async () => {+ const r = await request(app).get('/api/sprites/animation-tracks');+ expect(r.status).toBe(200);+ expect(r.body).toEqual({+ tracks: [{ id: 'walk', builtin: true }],+ storePath: 'sprites/animation-tracks.json',+ origin: 'seed',+ });+ // The literal path must not be captured as a record id by the /:id GET.+ expect(records.getRecordWithAssets).not.toHaveBeenCalled();+ });++ it('POST /animation-tracks validates the authored subset and 201s', async () => {+ const body = {+ id: 'chest-opening',+ label: 'Chest opening',+ directional: false,+ kinds: ['object'],+ minFrameCount: 2,+ maxFrameCount: 8,+ defaultFrameCount: 4,+ minFps: 2,+ maxFps: 12,+ defaultFps: 6,+ promptTemplate: 'Animate the {{kind}} {{name}} opening once.',+ };+ const r = await request(app).post('/api/sprites/animation-tracks').send(body);+ expect(r.status).toBe(201);+ expect(r.body.restartRequired).toBe(true);+ expect(trackCrud.createAnimationTrack).toHaveBeenCalledWith(body);+ // The literal path must not be captured by POST / (create record).+ expect(records.createCharacter).not.toHaveBeenCalled();+ });++ const validBody = {+ id: 'chest-opening',+ label: 'Chest opening',+ directional: false,+ kinds: ['object'],+ minFrameCount: 2,+ maxFrameCount: 8,+ defaultFrameCount: 4,+ minFps: 2,+ maxFps: 12,+ defaultFps: 6,+ promptTemplate: 'Animate it.',+ };++ it('POST /animation-tracks rejects a DERIVED field supplied by the request', async () => {+ // These name files on disk and the publish-contract key, and the registry+ // requires them globally unique — accepting one from a request would let a typo+ // hand this track another's evidence chain, so `.strict()` refuses it by name+ // rather than silently stripping a field the user thinks they set.+ for (const extra of [+ { setKind: 'finalized-eight-direction-walk-set' },+ { selectionKind: 'reviewed-directional-walk-selection' },+ { contractFrameCountField: 'walkFrameCount' },+ { standaloneContract: true },+ { builtin: true },+ ]) {+ const bad = await request(app).post('/api/sprites/animation-tracks').send({ ...validBody, ...extra });+ expect(bad.status).toBe(400);+ }+ expect(trackCrud.createAnimationTrack).not.toHaveBeenCalled();+ });++ it('POST /animation-tracks rejects a malformed id, an unknown kind, and a missing prompt', async () => {+ const cases = [+ { ...validBody, id: 'Not A Slug' },+ { ...validBody, kinds: ['weapon'] },+ { ...validBody, kinds: [] },+ { ...validBody, promptTemplate: '' },+ { ...validBody, label: '' },+ ];+ for (const body of cases) {+ expect((await request(app).post('/api/sprites/animation-tracks').send(body)).status).toBe(400);+ }+ expect(trackCrud.createAnimationTrack).not.toHaveBeenCalled();+ });++ it('POST /animation-tracks rejects an out-of-order bounds triple at the schema', async () => {+ // Front-runs the registry's own cross-field rule so the form gets a per-field+ // 400 naming the default, instead of a whole-table 409.+ const bad = await request(app).post('/api/sprites/animation-tracks')+ .send({ ...validBody, minFrameCount: 6, defaultFrameCount: 4, maxFrameCount: 8 });+ expect(bad.status).toBe(400);+ expect(bad.body.context.details).toEqual([+ { path: 'defaultFrameCount', message: 'minFrameCount <= defaultFrameCount <= maxFrameCount is required' },+ ]);+ const badFps = await request(app).post('/api/sprites/animation-tracks')+ .send({ ...validBody, minFps: 2, defaultFps: 20, maxFps: 12 });+ expect(badFps.status).toBe(400);+ expect(badFps.body.context.details).toEqual([+ { path: 'defaultFps', message: 'minFps <= defaultFps <= maxFps is required' },+ ]);+ expect(trackCrud.createAnimationTrack).not.toHaveBeenCalled();+ });++ it('PUT /animation-tracks/:trackId takes a partial patch and threads the id through', async () => {+ const r = await request(app).put('/api/sprites/animation-tracks/chest-opening')+ .send({ label: 'Chest opens', maxFrameCount: 12 });+ expect(r.status).toBe(200);+ expect(trackCrud.updateAnimationTrack).toHaveBeenCalledWith('chest-opening', { label: 'Chest opens', maxFrameCount: 12 });+ });++ it('PUT /animation-tracks/:trackId refuses a rename and an empty patch', async () => {+ // Renaming would have to migrate the on-disk directories, every run record and+ // every manifest — so it is a delete-plus-create, and `id` in the patch is a+ // 400 naming the field rather than a silent no-op.+ expect((await request(app).put('/api/sprites/animation-tracks/chest-opening')+ .send({ id: 'chest-opens' })).status).toBe(400);+ expect((await request(app).put('/api/sprites/animation-tracks/chest-opening').send({})).status).toBe(400);+ expect(trackCrud.updateAnimationTrack).not.toHaveBeenCalled();+ });++ it('PUT /animation-tracks/:trackId rejects a malformed track id at the shape schema', async () => {+ expect((await request(app).put('/api/sprites/animation-tracks/Bad_Id').send({ label: 'x' })).status).toBe(400);+ expect(trackCrud.updateAnimationTrack).not.toHaveBeenCalled();+ });++ // The client's own suite mocks `apiSprites.js`, so it can never see a mismatch+ // between the body the drawer builds and the schema that has to accept it — which+ // is exactly how an `id` in the PUT patch (a hard 400 on every "Save changes")+ // shipped invisibly behind two green suites. These two assert the WIRE shapes the+ // drawer sends, against the real schemas.+ it('accepts the exact POST body the Animation types drawer builds', async () => {+ // Mirrors AnimationTypesDrawer's `form` — the authored subset plus `id`.+ const r = await request(app).post('/api/sprites/animation-tracks').send({+ id: 'jetpack-burst',+ label: 'Jetpack burst',+ directional: true,+ kinds: ['character'],+ minFrameCount: 2,+ maxFrameCount: 8,+ defaultFrameCount: 4,+ minFps: 2,+ maxFps: 12,+ defaultFps: 6,+ promptTemplate: 'Animate {{name}} firing a jetpack, facing {{direction}}.',+ });+ expect(r.status).toBe(201);+ });++ it('accepts the exact PUT body the drawer builds — the form MINUS the immutable id', async () => {+ // The drawer strips `id` before a PUT; if it ever stops, this fails here rather+ // than only in the browser.+ const r = await request(app).put('/api/sprites/animation-tracks/chest-opening').send({+ label: 'Chest opens',+ directional: false,+ kinds: ['object'],+ minFrameCount: 2,+ maxFrameCount: 12,+ defaultFrameCount: 4,+ minFps: 2,+ maxFps: 12,+ defaultFps: 6,+ promptTemplate: 'Animate the {{kind}} {{name}} opening once.',+ });+ expect(r.status).toBe(200);+ });++ it('DELETE /animation-tracks/:trackId delegates (and is not captured by DELETE /:id)', async () => {+ const r = await request(app).delete('/api/sprites/animation-tracks/chest-opening');+ expect(r.status).toBe(200);+ expect(trackCrud.deleteAnimationTrack).toHaveBeenCalledWith('chest-opening');+ expect(records.deleteRecord).not.toHaveBeenCalled();+ });+ });+it('GET /:id/asset-prompt resolves an asset prompt by record-relative path', async () => {const r = await request(app).get(`/api/sprites/pioneer/asset-prompt?path=${encodeURIComponent('reference/candidates/walk-south-candidate-01.png')}`);expect(r.status).toBe(200);diff --git a/server/services/sprites/animationTrackCrud.js b/server/services/sprites/animationTrackCrud.jsnew file mode 100644index 0000000000..a6425fd7d3--- /dev/null+++ b/server/services/sprites/animationTrackCrud.js@@ -0,0 +1,359 @@+/**+ * Sprites — authoring the user-defined animation-track store (#3153).+ *+ * #3152 made the track registry a merge of compiled `walk` plus a JSON store, and+ * #3136 made every track's generate/review/approve workflow generic — so a new+ * animation type already needs no code. What it still needed was a way to *author*+ * one: the store was a file the user had to hand-edit, which is not a feature so+ * much as a documented workaround. This module is the write half of that store.+ *+ * **Why a module of its own, not writers on `animationTrackStore.js`.** That module+ * is imported by `server/lib/validation.js` (which builds its sprite Zod ranges+ * from the effective registry at module load), and `animationTrackStore.test.js`+ * plus `animationTracks.test.js` pin how narrow its import graph is allowed to be —+ * `validation.js` must not drag the native image graph into request validation.+ * Refusing to delete a track that has authored work on disk means scanning every+ * record, which reaches `records.js` and the workflow's on-disk layout, i.e. sharp.+ * So reads stay in the leaf-ish store and writes live here, where the route layer+ * (which already imports `atlas.js`) is the only consumer.+ *+ * **Five row fields are DERIVED from the id, never typed.** `assertAnimationTrackRows`+ * refuses two rows claiming the same `contractFrameCountField`, `selectionKind`, or+ * `setKind`, and those strings name on-disk files and publish-contract keys — asking+ * a user to invent globally-unique `kind` discriminators is a trap with no upside,+ * and a typo in one would surface as another track's finalized set satisfying this+ * one's evidence check. The user types the id and the derivation is total. A derived+ * value that DOES collide (id `directional-scanner` derives the seeded scanner's+ * `reviewed-directional-scanner-selection`) is refused at save time by the same+ * assert, naming the conflict — which is the point of validating the merged table+ * here rather than discovering it at the next boot.+ *+ * `standaloneContract` is derived too, for the same reason: it is a cross-row+ * invariant (`assertAnimationTrackRows` requires exactly one standalone track per+ * record kind), so the only correct value depends on what else is in the table. A+ * new row is the baseline exactly when none of the kinds it claims already has one+ * — which is what makes "delete ambient, then add your own place loop" work. A row+ * spanning a kind that has a baseline and one that doesn't has no valid answer, and+ * the assert refuses it by naming the kind.+ *+ * **The writes are serialized and the cache is invalidated.** One `data/` file, one+ * `createFileWriteQueue` tail, so a create landing while a delete is mid-flight+ * cannot read a stale pre-image (the CLAUDE.md rule for a service that owns a single+ * JSON state file). Every mutation ends in `__resetAnimationTrackStore()` so the+ * running server serves the table it just wrote instead of reporting success against+ * a cache nothing dropped.+ *+ * **A mutation still reports `restartRequired`.** Per #3136/#3152's scope the+ * registry itself is live after the cache reset, but `server/lib/validation.js`+ * builds `spriteRuntimeContractSchema`'s per-track contract fields ONCE at module+ * load — so a brand-new track's `<id>FrameCount` key is stripped by Zod until the+ * process restarts. Saying so in the response is the difference between a documented+ * boundary and a field that silently does nothing.+ */++import { atomicWrite, pathExists } from '../../lib/fileUtils.js';+import { createFileWriteQueue } from '../../lib/fileWriteQueue.js';+import { ServerError } from '../../lib/errorHandler.js';+import {+ WALK_TRACK, AUTHORED_TRACK_FIELDS, assertAnimationTrackRows, deriveTrackFields,+} from './animationTracks.js';+import {+ ANIMATION_TRACK_STORE_REL,+ ANIMATION_TRACK_STORE_SCHEMA_VERSION,+ animationTrackStorePath,+ getEffectiveAnimationTracks,+ __resetAnimationTrackStore,+} from './animationTrackStore.js';+import { recordsCarryingTrack } from './animationTrackWorkflow.js';++// One store file, so ONE tail — per CLAUDE.md's "collapse the queue to a single+// tail per shared file". A per-id queue would let two different tracks' writes+// interleave on the same JSON and lose one of them.+const queueStoreWrite = createFileWriteQueue();++/** The stored (non-builtin) rows, in registration order. */+const storedRows = (tracks) => Object.values(tracks).filter((row) => !row.builtin);+/** The compiled-in rows (`walk`) — never mutable, always first in the merged table. */+const builtinRows = (tracks) => Object.values(tracks).filter((row) => row.builtin);++/**+ * Run a registry call whose failure is a bare `Error`, as a 409 the form can show.+ *+ * Both the store's load and `assertAnimationTrackRows` throw plain Errors — correct+ * for boot, where a loud crash naming the field is the whole point, but wrong on this+ * surface: here it is a *response* to a request the user made about that very file,+ * and an unrecognized error becomes an opaque 500 that says nothing about which row+ * is broken. The registry's messages already name the field, the two claimants, or+ * the record kind, so they are surfaced verbatim with an actionable status.+ */+function asConflict(fn) {+ try {+ return fn();+ } catch (err) {+ throw new ServerError(err.message, { status: 409, code: 'ANIMATION_TRACK_CONFLICT' });+ }+}++/**+ * The user-facing subset of a row, in the shape the CRUD surface accepts.+ *+ * Whitelisted from `AUTHORED_TRACK_FIELDS` rather than spread-minus-derived, so a+ * round-trip through the editor can't carry an unknown key from a hand-edited store+ * back into a saved row and have it silently persist — and so this list and the+ * request schema's cannot drift (see that constant's header).+ */+const authoredFields = (row) => ({+ id: row.id,+ ...Object.fromEntries(AUTHORED_TRACK_FIELDS.map((key) => (+ [key, Array.isArray(row[key]) ? [...row[key]] : row[key]]+ ))),+});++/**+ * Whether a row is its record kinds' publishable baseline: true only when NONE of+ * the kinds it claims is already owned by another row in the SAME prospective table.+ *+ * `rows` is the whole post-mutation row set (not the pre-image), which is what makes+ * a promotion work: deleting `place`'s baseline must let a surviving `place` track+ * become one, and deriving against the table as it WAS would instead leave that kind+ * with zero owners and 409 on a delete that should have succeeded.+ *+ * Order-dependent by design: within one table the earlier row wins a contested kind,+ * matching the registry's `walk`-first registration order, so the answer is stable+ * across installs rather than dependent on which row happened to be recomposed+ * first.+ */+function withDerivedBaselines(rows, builtins) {+ const claimed = new Set();+ for (const row of [...builtins, ...rows]) {+ if (!row.standaloneContract) continue;+ // A builtin's claim is fixed; a stored row's is being decided below, so only+ // seed from rows whose answer is already settled.+ if (row.builtin) for (const kind of row.kinds) claimed.add(kind);+ }+ return rows.map((row) => {+ const standaloneContract = row.kinds.every((kind) => !claimed.has(kind));+ if (standaloneContract) for (const kind of row.kinds) claimed.add(kind);+ return { ...row, standaloneContract };+ });+}++/**+ * A stored row's PortOS-owned fields, minus `standaloneContract` (a cross-row answer+ * `withDerivedBaselines` fills in once the whole table is known).+ *+ * `existing` is the row already on disk, and its presence is load-bearing: when+ * there is one, the five discriminators are carried over VERBATIM rather than+ * re-derived. A row whose `setKind` was hand-edited (or seeded under different+ * wording — the shipped `scanner` row's `reviewed-directional-scanner-selection` is+ * not what `deriveTrackFields('scanner')` produces) names files an approved set on+ * this machine already carries, so re-deriving during an unrelated label edit would+ * rename the artifact the atlas compiler re-verifies and silently orphan that set.+ * Only a brand-new id derives them.+ */+const composeRow = (authored, existing = null) => ({+ ...authored,+ ...(existing ? {+ contractFrameCountField: existing.contractFrameCountField,+ contractFpsField: existing.contractFpsField,+ selectionKind: existing.selectionKind,+ setKind: existing.setKind,+ finalErrorCode: existing.finalErrorCode,+ } : deriveTrackFields(authored.id)),+ builtin: false,+});++/**+ * The prospective stored-row set for a mutation, with every row's discriminators+ * preserved and every `standaloneContract` re-derived over the RESULT.+ *+ * `added` is a brand-new authored row, `replacement` swaps in for its own id, and+ * `dropId` removes one — the three mutations expressed as one table rebuild, so+ * baseline promotion/demotion is computed the same way whichever one ran.+ */+const nextStoredRows = (tracks, { added = null, replacement = null, dropId = null } = {}) => {+ const kept = storedRows(tracks)+ .filter((row) => row.id !== dropId)+ .map((row) => composeRow(+ replacement && row.id === replacement.id ? replacement : authoredFields(row),+ row,+ ));+ const rows = added ? [...kept, composeRow(added)] : kept;+ return withDerivedBaselines(rows, builtinRows(tracks));+};++/**+ * The effective table — every read on this surface goes through this rather than the+ * store's getter, so a hand-broken store can't reach one path as a 409 and another+ * as a 500.+ */+const effectiveTracksOrThrow = () => asConflict(getEffectiveAnimationTracks);++/**+ * Every track the effective registry knows, built-in first.+ *+ * Returns the FULL rows (derived fields included), because the drawer shows the+ * user which on-disk kinds and contract field their id produced — that is how a+ * collision refusal below becomes actionable rather than mysterious.+ */+export function listAnimationTracks() {+ return {+ tracks: Object.values(effectiveTracksOrThrow()),+ storePath: ANIMATION_TRACK_STORE_REL,+ };+}++/**+ * Persist a stored-row set, then drop the registry cache.+ *+ * The seed's `_comment` is deliberately NOT carried over: once the user has saved+ * through the UI this file is theirs, and a note explaining which rows shipped as+ * seed data stops being true the moment they edit one.+ */+async function writeStoredRows(rows) {+ await atomicWrite(animationTrackStorePath(), {+ schemaVersion: ANIMATION_TRACK_STORE_SCHEMA_VERSION,+ tracks: rows,+ });+ __resetAnimationTrackStore();+}++/**+ * Validate the prospective merged table (compiled `walk` plus these stored rows)+ * through the SAME guard the store runs at load — so a row saved here can never be+ * one that bricks the next boot. That is the difference between "refused at save time+ * with a message naming the conflict" and a server that won't start.+ */+function assertTableValid(tracks, rows) {+ const byId = [...builtinRows(tracks), ...rows].map((row) => [row.id, row]);+ asConflict(() => assertAnimationTrackRows(Object.fromEntries(byId)));+}++/**+ * Refuse a mutation to a built-in track by name.+ *+ * `walk` is the one mandatory baseline: its bounds feed the Zod schemas and its+ * `setKind` gates every character compile, so editing or deleting it through a data+ * edit would brick authoring with no code change to point at. The store's loader+ * already refuses a row that shadows it; this is the same refusal at the surface+ * where the user would otherwise get a 404 for a track they can plainly see.+ */+function refuseBuiltin(trackId, tracks) {+ const row = tracks[trackId];+ if (trackId === WALK_TRACK || (row && row.builtin)) {+ throw new ServerError(+ `'${trackId}' is a built-in animation type and cannot be edited or deleted`,+ { status: 409, code: 'BUILTIN_ANIMATION_TRACK' },+ );+ }+}++/** 409 for a built-in, 404 for a well-formed id that names no stored track. */+function requireStored(trackId, tracks) {+ refuseBuiltin(trackId, tracks);+ const row = tracks[trackId];+ if (!row) {+ throw new ServerError(+ `Unknown animation type '${trackId}' — the registered types are: ${Object.keys(tracks).join(', ')}`,+ { status: 404, code: 'UNKNOWN_ANIMATION_TRACK' },+ );+ }+ return row;+}++/**+ * Refuse a mutation that would orphan authored work, listing the records.+ *+ * "In use" is any record carrying this track's finalized set OR a review selection+ * with at least one approved direction — both are renders the user approved, both+ * are keyed by the `setKind`/`selectionKind` strings a delete removes from the+ * registry, and after either mutation the atlas compiler would find on-disk+ * evidence for a track it no longer knows (or, on a directionality flip, would+ * expect a different number of rows than the set was frozen with).+ *+ * No force flag, deliberately (#3153): a force-delete that silently drops approved+ * renders is worse than a refusal the user can act on by reopening those sets+ * first. The message names the records so that action is obvious.+ */+async function refuseIfInUse(trackId, action) {+ const recordIds = await recordsCarryingTrack(trackId);+ if (!recordIds.length) return;+ throw new ServerError(+ `Cannot ${action} '${trackId}' — ${recordIds.length} sprite${recordIds.length === 1 ? '' : 's'} `+ + `already ${recordIds.length === 1 ? 'carries' : 'carry'} approved ${trackId} work: ${recordIds.join(', ')}. `+ + 'Reopen or unlock those sets first.',+ { status: 409, code: 'ANIMATION_TRACK_IN_USE', context: { records: recordIds } },+ );+}++// Every mutation answers with the fresh table plus the honest scope boundary, so+// the client never has to guess whether its write is live.+const mutationResult = () => ({ ...listAnimationTracks(), restartRequired: true });++/** Create one user-defined animation type. */+export function createAnimationTrack(input) {+ return queueStoreWrite(async () => {+ const tracks = effectiveTracksOrThrow();+ if (tracks[input.id]) {+ refuseBuiltin(input.id, tracks);+ throw new ServerError(+ `Animation type '${input.id}' already exists — edit it instead, or choose another id`,+ { status: 409, code: 'ANIMATION_TRACK_EXISTS' },+ );+ }+ const rows = nextStoredRows(tracks, { added: input });+ assertTableValid(tracks, rows);+ await writeStoredRows(rows);+ return mutationResult();+ });+}++/**+ * Update one user-defined animation type. `id` is immutable — renaming would have+ * to migrate the on-disk `<trackId>/` directories, every run's `track` field and+ * every manifest, so it is a delete-plus-create the user makes explicitly.+ *+ * A directionality FLIP on an in-use track is refused like a delete: the finalized+ * set was frozen with a `directionOrder` derived from the old value and the+ * compiler validates row counts against the new one, so the two would disagree+ * about what is on disk. Every other field (label, bounds, prompt) is safe to+ * retune with work already authored — the packer clamps into the new range.+ */+export function updateAnimationTrack(trackId, patch) {+ return queueStoreWrite(async () => {+ const tracks = effectiveTracksOrThrow();+ const existing = authoredFields(requireStored(trackId, tracks));+ const next = { ...existing, ...patch, id: trackId };+ if (next.directional !== existing.directional) {+ await refuseIfInUse(trackId, 'change the facing mode of');+ }+ const rows = nextStoredRows(tracks, { replacement: next });+ assertTableValid(tracks, rows);+ await writeStoredRows(rows);+ return mutationResult();+ });+}++/** Delete one user-defined animation type, refusing when work depends on it. */+export function deleteAnimationTrack(trackId) {+ return queueStoreWrite(async () => {+ const tracks = effectiveTracksOrThrow();+ requireStored(trackId, tracks);+ await refuseIfInUse(trackId, 'delete');+ const rows = nextStoredRows(tracks, { dropId: trackId });+ assertTableValid(tracks, rows);+ await writeStoredRows(rows);+ return mutationResult();+ });+}++/**+ * Whether this install has its own store file yet, and where the rows came from.+ *+ * Surfaced so the drawer can say "these are the shipped starter types" before the+ * first save — a user who deletes one needs to know the file is about to become+ * theirs and stop tracking the seed.+ */+export async function animationTrackStoreOrigin() {+ return (await pathExists(animationTrackStorePath())) ? 'store' : 'seed';+}diff --git a/server/services/sprites/animationTrackCrud.test.js b/server/services/sprites/animationTrackCrud.test.jsnew file mode 100644index 0000000000..6cc3f7b886--- /dev/null+++ b/server/services/sprites/animationTrackCrud.test.js@@ -0,0 +1,468 @@+/**+ * Authoring the user-defined animation-track store (#3153).+ *+ * The store's READ side is covered by `animationTrackStore.test.js` and the row+ * rules by `animationTracks.test.js`. What only this module can get wrong is the+ * write side, and specifically the three things it decides on the user's behalf:+ *+ * - the DERIVED fields (five discriminators + `standaloneContract`), because a+ * wrong derivation hands one track another's on-disk evidence chain or leaves a+ * record kind with zero/two publishable baselines — either of which is a boot+ * failure on the NEXT start, not a visible error now+ * - the REFUSALS: a built-in, a collision, a delete that would orphan approved+ * renders, a directionality flip on authored work+ * - the cache invalidation, since a write that left the cache standing reports+ * success while the running server keeps serving the old table+ *+ * `PATHS` is redirected at a temp tree (the sibling suites' idiom) so every case+ * writes and re-reads a real store file: the contract is about a file on disk, and+ * mocking the writer away would leave "did the merge round-trip?" untested.+ *+ * `records.js` is mocked rather than seeded because `recordsCarryingTrack` reaches+ * the DB/file facade — this suite is about the CRUD decisions, and the on-disk+ * evidence scan itself is asserted in `animationTrackWorkflow.test.js`.+ */++import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';+import { mkdtempSync, rmSync, existsSync, readFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { storedTrackRow, writeAnimationTrackStore } from './spriteTestFixtures.js';++const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-track-crud-test-'));++vi.mock('../../lib/fileUtils.js', async (importOriginal) => {+ const actual = await importOriginal();+ Object.assign(actual.PATHS, { data: TEST_ROOT, sprites: join(TEST_ROOT, 'sprites') });+ return actual;+});++// The record scan behind the in-use refusal. Per-test control over which records+// carry a track, so the refusal and the happy path are both exercised without+// laying down selection/set files for every case.+const recordsCarryingTrack = vi.fn(async () => []);+vi.mock('./animationTrackWorkflow.js', () => ({+ recordsCarryingTrack: (...args) => recordsCarryingTrack(...args),+}));++const {+ listAnimationTracks, createAnimationTrack, updateAnimationTrack, deleteAnimationTrack,+ animationTrackStoreOrigin,+} = await import('./animationTrackCrud.js');+// The derivation lives beside the row contract it must satisfy (#3153 review).+const { deriveTrackFields } = await import('./animationTracks.js');+const { __resetAnimationTrackStore, animationTrackStorePath } = await import('./animationTrackStore.js');++const STORE = join(TEST_ROOT, 'sprites', 'animation-tracks.json');++/** Seed the on-disk store with `rows` (or clear it) and drop the registry cache. */+async function seedStore(rows) {+ await writeAnimationTrackStore(TEST_ROOT, rows);+ __resetAnimationTrackStore();+}++const readStore = () => JSON.parse(readFileSync(STORE, 'utf-8'));+const byId = (result, id) => result.tracks.find((row) => row.id === id);++// A minimally-valid create payload — the user-facing subset the route validates,+// with none of the derived fields.+const authored = (overrides = {}) => ({+ id: 'chest-opening',+ label: 'Chest opening',+ directional: false,+ kinds: ['object'],+ minFrameCount: 2,+ maxFrameCount: 8,+ defaultFrameCount: 4,+ minFps: 2,+ maxFps: 12,+ defaultFps: 6,+ promptTemplate: 'Animate the {{kind}} {{name}} opening once.',+ ...overrides,+});++beforeEach(async () => {+ recordsCarryingTrack.mockClear();+ recordsCarryingTrack.mockImplementation(async () => []);+ // Every test starts from an empty store so `walk` is the only row and each case+ // states the rows it needs — an inherited scanner/ambient would silently satisfy+ // the standalone-baseline invariant the derivation tests are about.+ await seedStore([]);+});++afterAll(() => rmSync(TEST_ROOT, { recursive: true, force: true }));++describe('deriveTrackFields', () => {+ it('derives all five discriminators from the id, camel/snake-casing as the registry expects', () => {+ expect(deriveTrackFields('chest-opening')).toEqual({+ contractFrameCountField: 'chestOpeningFrameCount',+ contractFpsField: null,+ selectionKind: 'reviewed-chest-opening-selection',+ setKind: 'finalized-chest-opening-set',+ finalErrorCode: 'CHEST_OPENING_SET_FINAL',+ });+ });++ it('handles a single-word id without inventing separators', () => {+ expect(deriveTrackFields('jetpack')).toMatchObject({+ contractFrameCountField: 'jetpackFrameCount',+ setKind: 'finalized-jetpack-set',+ finalErrorCode: 'JETPACK_SET_FINAL',+ });+ });++ it('reproduces the seeded rows exactly, so the derivation is the same rule the seed used', () => {+ // The seed is what an upgraded install already carries; a derivation that+ // disagreed would mean re-saving scanner through the UI silently renamed the+ // on-disk files an approved set is keyed by.+ expect(deriveTrackFields('scanner')).toMatchObject({+ contractFrameCountField: 'scannerFrameCount',+ selectionKind: 'reviewed-scanner-selection',+ setKind: 'finalized-scanner-set',+ });+ });+});++// `standaloneContract` — which track is a record kind's publishable baseline — is a+// CROSS-ROW answer, so it is asserted through the mutations that recompute it rather+// than as a unit: the invariant is a property of the resulting table, and the bug it+// once had (deriving against the pre-image) was invisible to a per-row check. The+// promotion/demotion cases live with `deleteAnimationTrack`/`createAnimationTrack`+// below; these cover the two rules that decide the answer.+describe('standaloneContract derivation', () => {+ it('declines the kind a BUILT-IN already owns (a character action rides beside walk)', async () => {+ const result = await createAnimationTrack(authored({ id: 'jetpack', kinds: ['character'] }));+ expect(byId(result, 'jetpack').standaloneContract).toBe(false);+ });++ it('claims a kind nothing owns yet (the first place loop IS the baseline)', async () => {+ const result = await createAnimationTrack(authored({ id: 'shutter', kinds: ['place'] }));+ expect(byId(result, 'shutter').standaloneContract).toBe(true);+ });++ it('refuses a row spanning an owned kind AND a free one — there is no valid answer', async () => {+ // `walk` owns `character`, so the row can't be a baseline; but then nothing is+ // `place`'s baseline. Both answers are wrong, so the assert refuses rather than+ // silently picking one — the user's fix is to split it into two types.+ const err = await createAnimationTrack(authored({ id: 'combo', kinds: ['place', 'character'] }))+ .catch((e) => e);+ expect(err).toMatchObject({ status: 409, code: 'ANIMATION_TRACK_CONFLICT' });+ expect(err.message).toContain("record kind 'place'");+ });++ it('keeps a baseline row as the baseline when it is re-saved', async () => {+ await seedStore([storedTrackRow({ kinds: ['object'] })]);+ expect(byId(listAnimationTracks(), 'chest-opening').standaloneContract).toBe(true);+ const result = await updateAnimationTrack('chest-opening', { label: 'Chest opens' });+ expect(byId(result, 'chest-opening').standaloneContract).toBe(true);+ });+});++describe('listAnimationTracks', () => {+ it('lists the built-in walk row on an install with an empty store', () => {+ const result = listAnimationTracks();+ expect(result.tracks.map((row) => row.id)).toEqual(['walk']);+ expect(byId(result, 'walk').builtin).toBe(true);+ expect(result.storePath).toBe('sprites/animation-tracks.json');+ });++ it('lists stored rows after the built-in, with their derived fields visible', async () => {+ await seedStore([storedTrackRow()]);+ const result = listAnimationTracks();+ expect(result.tracks.map((row) => row.id)).toEqual(['walk', 'chest-opening']);+ expect(byId(result, 'chest-opening')).toMatchObject({+ builtin: false, setKind: 'finalized-chest-opening-set',+ });+ });+});++describe('createAnimationTrack', () => {+ it('persists the authored subset plus the derived fields and drops the cache', async () => {+ const result = await createAnimationTrack(authored());+ // The write landed on disk in the store's own shape…+ const doc = readStore();+ expect(doc.schemaVersion).toBe(1);+ expect(doc.tracks).toHaveLength(1);+ expect(doc.tracks[0]).toMatchObject({+ id: 'chest-opening',+ contractFrameCountField: 'chestOpeningFrameCount',+ setKind: 'finalized-chest-opening-set',+ builtin: false,+ });+ // …and the returned table is the FRESH one, which only holds if the cache was+ // invalidated — a stale cache would answer `['walk']` here.+ expect(result.tracks.map((row) => row.id)).toEqual(['walk', 'chest-opening']);+ expect(result.restartRequired).toBe(true);+ });++ it('does not persist an unknown field even if one reaches the service', async () => {+ // The route's `.strict()` schema rejects this first; the service whitelists+ // anyway, so a hand-edited row can't round-trip an unknown key back into a save.+ await createAnimationTrack({ ...authored(), builtin: true, setKind: 'finalized-eight-direction-walk-set' });+ const row = readStore().tracks[0];+ expect(row.builtin).toBe(false);+ expect(row.setKind).toBe('finalized-chest-opening-set');+ });++ it('refuses an id that already names a stored track', async () => {+ await createAnimationTrack(authored());+ await expect(createAnimationTrack(authored())).rejects.toMatchObject({+ status: 409, code: 'ANIMATION_TRACK_EXISTS',+ });+ });++ it('refuses an id that names the built-in walk track', async () => {+ await expect(createAnimationTrack(authored({ id: 'walk' }))).rejects.toMatchObject({+ status: 409, code: 'BUILTIN_ANIMATION_TRACK',+ });+ });++ it('refuses a row whose DERIVED discriminator collides with an existing track', async () => {+ // The user types only an id, but the id is what produces the on-disk kinds — so+ // a collision must be caught at save time, naming the conflict, rather than+ // bricking the next boot. Here a hand-edited row already claims the contract+ // field `chest-opening` derives, which the new row cannot rename away from.+ await seedStore([storedTrackRow({+ id: 'opening',+ contractFrameCountField: 'chestOpeningFrameCount',+ selectionKind: 'reviewed-other-selection',+ setKind: 'finalized-other-set',+ finalErrorCode: 'OTHER_SET_FINAL',+ })]);+ const err = await createAnimationTrack(authored()).catch((e) => e);+ expect(err).toMatchObject({ status: 409, code: 'ANIMATION_TRACK_CONFLICT' });+ expect(err.message).toContain('chestOpeningFrameCount');+ // Nothing was written — a refused save must not half-land.+ expect(readStore().tracks.map((row) => row.id)).toEqual(['opening']);+ });++ it('preserves a hand-edited row\'s discriminators when a SIBLING is created', async () => {+ // The seeded `scanner` row's `reviewed-directional-scanner-selection` is NOT what+ // `deriveTrackFields('scanner')` produces, and it names the file an approved+ // scanner set on this machine is keyed by — so an unrelated create must carry it+ // over verbatim rather than re-deriving and orphaning that set.+ await seedStore([storedTrackRow({+ id: 'scanner',+ kinds: ['character'],+ standaloneContract: false,+ contractFrameCountField: 'scannerFrameCount',+ selectionKind: 'reviewed-directional-scanner-selection',+ setKind: 'finalized-eight-direction-scanner-set',+ finalErrorCode: 'SCANNER_SET_FINAL',+ })]);+ const result = await createAnimationTrack(authored());+ expect(byId(result, 'scanner')).toMatchObject({+ selectionKind: 'reviewed-directional-scanner-selection',+ setKind: 'finalized-eight-direction-scanner-set',+ });+ });++ it('refuses every mutation while the store on disk is already invalid', async () => {+ // A hand-edited row claiming no baseline for a kind nothing else owns is refused+ // by the store's own LOAD (the same guard that runs at boot), before this surface+ // gets a table to recompose — so the user fixes the file rather than having a+ // write silently rewrite their row's flags out from under them.+ await seedStore([storedTrackRow({ id: 'lamp-flicker', kinds: ['place'], standaloneContract: false })]);+ const err = await createAnimationTrack(authored({ id: 'shutter', kinds: ['object'] })).catch((e) => e);+ expect(err).toMatchObject({ status: 409, code: 'ANIMATION_TRACK_CONFLICT' });+ expect(err.message).toContain("record kind 'place'");+ });+});++describe('an already-invalid store', () => {+ it('answers a read with a 409 naming the broken row, not an opaque 500', async () => {+ // A hand-broken file is the user's own edit to the very file this surface is+ // about, so the drawer must be able to show the message beside the rows.+ await seedStore([storedTrackRow({ minFrameCount: 'six' })]);+ const err = await Promise.resolve().then(() => listAnimationTracks()).catch((e) => e);+ expect(err).toMatchObject({ status: 409, code: 'ANIMATION_TRACK_CONFLICT' });+ expect(err.message).toContain('minFrameCount');+ });++ it('answers a mutation the same way instead of half-writing over it', async () => {+ await seedStore([storedTrackRow({ minFrameCount: 'six' })]);+ await expect(createAnimationTrack(authored({ id: 'shutter' }))).rejects.toMatchObject({+ status: 409, code: 'ANIMATION_TRACK_CONFLICT',+ });+ expect(readStore().tracks.map((row) => row.id)).toEqual(['chest-opening']);+ });+});++describe('updateAnimationTrack', () => {+ beforeEach(async () => { await seedStore([storedTrackRow()]); });++ it('applies a partial patch and leaves the rest of the row alone', async () => {+ const result = await updateAnimationTrack('chest-opening', { label: 'Chest opens', maxFrameCount: 12 });+ expect(byId(result, 'chest-opening')).toMatchObject({+ label: 'Chest opens',+ maxFrameCount: 12,+ minFrameCount: 2,+ defaultFrameCount: 4,+ promptTemplate: storedTrackRow().promptTemplate,+ setKind: 'finalized-chest-opening-set',+ });+ expect(result.restartRequired).toBe(true);+ });++ it('keeps a baseline row as the baseline when re-saved (it must not flip off against itself)', async () => {+ expect(byId(listAnimationTracks(), 'chest-opening').standaloneContract).toBe(true);+ const result = await updateAnimationTrack('chest-opening', { label: 'Chest opens' });+ expect(byId(result, 'chest-opening').standaloneContract).toBe(true);+ });++ it('refuses editing a built-in track', async () => {+ await expect(updateAnimationTrack('walk', { label: 'Stride' })).rejects.toMatchObject({+ status: 409, code: 'BUILTIN_ANIMATION_TRACK',+ });+ });++ it('404s an unknown track', async () => {+ await expect(updateAnimationTrack('nope', { label: 'x' })).rejects.toMatchObject({+ status: 404, code: 'UNKNOWN_ANIMATION_TRACK',+ });+ });++ it('refuses a bounds patch the registry would reject, without writing it', async () => {+ const err = await updateAnimationTrack('chest-opening', { minFrameCount: 6 }).catch((e) => e);+ expect(err).toMatchObject({ status: 409, code: 'ANIMATION_TRACK_CONFLICT' });+ expect(err.message).toContain('minFrameCount <= defaultFrameCount');+ expect(readStore().tracks[0].minFrameCount).toBe(2);+ });++ it('retunes bounds and the prompt on an IN-USE track (the packer clamps into the new range)', async () => {+ recordsCarryingTrack.mockImplementation(async () => ['pioneer']);+ const result = await updateAnimationTrack('chest-opening', { maxFrameCount: 12, promptTemplate: 'New wording.' });+ expect(byId(result, 'chest-opening')).toMatchObject({ maxFrameCount: 12, promptTemplate: 'New wording.' });+ });++ it('refuses a DIRECTIONALITY flip on an in-use track, naming the records', async () => {+ recordsCarryingTrack.mockImplementation(async () => ['pioneer', 'crates']);+ const err = await updateAnimationTrack('chest-opening', { directional: true }).catch((e) => e);+ expect(err).toMatchObject({ status: 409, code: 'ANIMATION_TRACK_IN_USE' });+ expect(err.message).toContain('pioneer');+ expect(err.message).toContain('crates');+ expect(readStore().tracks[0].directional).toBe(false);+ });++ it('allows a directionality flip when nothing carries the track', async () => {+ const result = await updateAnimationTrack('chest-opening', { directional: true });+ expect(byId(result, 'chest-opening').directional).toBe(true);+ expect(recordsCarryingTrack).toHaveBeenCalledWith('chest-opening');+ });+});++describe('deleteAnimationTrack', () => {+ it('removes the row and re-reads the table', async () => {+ await seedStore([storedTrackRow(), storedTrackRow({+ id: 'lamp-flicker',+ kinds: ['place'],+ contractFrameCountField: 'lampFlickerFrameCount',+ selectionKind: 'reviewed-lamp-flicker-selection',+ setKind: 'finalized-lamp-flicker-set',+ finalErrorCode: 'LAMP_FLICKER_SET_FINAL',+ })]);+ const result = await deleteAnimationTrack('lamp-flicker');+ expect(result.tracks.map((row) => row.id)).toEqual(['walk', 'chest-opening']);+ expect(readStore().tracks.map((row) => row.id)).toEqual(['chest-opening']);+ });++ it('refuses a delete that would orphan approved work, listing the records and offering no force', async () => {+ await seedStore([storedTrackRow()]);+ recordsCarryingTrack.mockImplementation(async () => ['pioneer']);+ const err = await deleteAnimationTrack('chest-opening').catch((e) => e);+ expect(err).toMatchObject({ status: 409, code: 'ANIMATION_TRACK_IN_USE' });+ expect(err.message).toContain('pioneer');+ expect(err.context?.records).toEqual(['pioneer']);+ // Still on disk — a refused delete must not have removed anything.+ expect(readStore().tracks.map((row) => row.id)).toEqual(['chest-opening']);+ });++ it('refuses deleting a built-in track', async () => {+ await expect(deleteAnimationTrack('walk')).rejects.toMatchObject({+ status: 409, code: 'BUILTIN_ANIMATION_TRACK',+ });+ });++ it('404s an unknown track', async () => {+ await expect(deleteAnimationTrack('nope')).rejects.toMatchObject({+ status: 404, code: 'UNKNOWN_ANIMATION_TRACK',+ });+ });++ it('PROMOTES a surviving same-kind track when the kind\'s baseline is deleted', async () => {+ // The regression this guards: deriving `standaloneContract` against the+ // pre-image left `place` with zero baselines and 409'd a delete that should+ // succeed — so "delete ambient, then keep your own place loop" was impossible.+ // The answer must be derived over the POST-mutation table.+ await seedStore([+ storedTrackRow({+ id: 'ambient',+ kinds: ['place'],+ contractFrameCountField: 'ambientFrameCount',+ selectionKind: 'reviewed-ambient-selection',+ setKind: 'finalized-ambient-set',+ finalErrorCode: 'AMBIENT_SET_FINAL',+ standaloneContract: true,+ }),+ storedTrackRow({ id: 'shutter', kinds: ['place'], standaloneContract: false }),+ ]);+ const result = await deleteAnimationTrack('ambient');+ expect(result.tracks.map((row) => row.id)).toEqual(['walk', 'shutter']);+ expect(byId(result, 'shutter').standaloneContract).toBe(true);+ });++ it('re-derives independent kinds without disturbing each other', async () => {+ await seedStore([+ storedTrackRow({ id: 'shutter', kinds: ['place'] }),+ storedTrackRow({+ id: 'lamp-flicker',+ kinds: ['object'],+ contractFrameCountField: 'lampFlickerFrameCount',+ selectionKind: 'reviewed-lamp-flicker-selection',+ setKind: 'finalized-lamp-flicker-set',+ finalErrorCode: 'LAMP_FLICKER_SET_FINAL',+ }),+ ]);+ const result = await deleteAnimationTrack('shutter');+ expect(byId(result, 'lamp-flicker').standaloneContract).toBe(true);+ });++ it('DEMOTES a new row\'s claim rather than giving a kind two baselines', async () => {+ // The other direction of the same derivation: `place` already has a baseline,+ // so a second place track must not claim one (the assert would refuse "has 2").+ await seedStore([storedTrackRow({ id: 'shutter', kinds: ['place'] })]);+ const result = await createAnimationTrack(authored({ id: 'awning', kinds: ['place'] }));+ expect(byId(result, 'shutter').standaloneContract).toBe(true);+ expect(byId(result, 'awning').standaloneContract).toBe(false);+ });+});++describe('animationTrackStoreOrigin', () => {+ it("reports 'seed' before this install has its own store file", async () => {+ rmSync(STORE, { force: true });+ __resetAnimationTrackStore();+ expect(await animationTrackStoreOrigin()).toBe('seed');+ });++ it("reports 'store' once a save has written the user copy", async () => {+ rmSync(STORE, { force: true });+ __resetAnimationTrackStore();+ await createAnimationTrack(authored());+ expect(existsSync(animationTrackStorePath())).toBe(true);+ expect(await animationTrackStoreOrigin()).toBe('store');+ });+});++describe('concurrent writes', () => {+ it('serializes two creates so neither read-modify-write loses the other', async () => {+ // One store file, so the queue is a single tail — without it both creates read+ // the same empty pre-image and the second write drops the first row.+ await Promise.all([+ createAnimationTrack(authored()),+ createAnimationTrack(authored({+ id: 'lamp-flicker', label: 'Lamp flicker', kinds: ['place'],+ })),+ ]);+ expect(readStore().tracks.map((row) => row.id).sort()).toEqual(['chest-opening', 'lamp-flicker']);+ });+});diff --git a/server/services/sprites/animationTrackWorkflow.js b/server/services/sprites/animationTrackWorkflow.jsindex a1eed60f76..0957254861 100644--- a/server/services/sprites/animationTrackWorkflow.js+++ b/server/services/sprites/animationTrackWorkflow.js@@ -46,7 +46,7 @@ import { executeTuiRun } from '../../lib/tuiPromptRunner.js';import { GROK_TUI_ID } from '../../lib/grok.js';import { resolveGrokDuration } from '../../lib/grokVideoClip.js';import { getSettings } from '../settings.js';-import { getRecord } from './records.js';+import { getRecord, listRecords } from './records.js';import { requireTrack, loadManifest } from './reference.js';import { anchorIdForDirection } from './prompts.js';import { buildTrackVideoPrompt } from './trackPrompts.js';@@ -141,6 +141,40 @@ export async function getTrackState(trackId, recordId) {return { track: row.id, definition: row, selection, set, runs };}+/**+ * Every record id carrying approved work for `trackId`, in library order (#3153).+ *+ * The evidence a delete or a directionality flip would orphan, as ONE question:+ * either the finalized set (the frozen `setKind` artifact the atlas compiler+ * re-verifies) or a review selection with at least one approved direction. Both+ * are renders the user approved and both are keyed by the discriminator strings+ * the mutation would remove from the registry — a set alone would miss a+ * half-approved directional track, where seven approvals exist but the eighth+ * hasn't frozen the set yet.+ *+ * Lives here rather than in the CRUD service because the on-disk layout+ * (`<track>/<id>-<track>-{selection,set}-v1.json`) is this module's contract; a+ * second reader spelling those filenames is exactly the drift the generic+ * workflow collapsed.+ *+ * Deliberately tolerant of a record whose directory is unreadable: `loadSelection`+ * and `loadSet` answer `null` for anything absent, so a record with no assets+ * simply doesn't carry the track. It never invents a false positive that would+ * block a legitimate delete.+ */+export async function recordsCarryingTrack(trackId) {+ const records = await listRecords();+ const carried = await Promise.all(records.map(async (record) => {+ const [selection, set] = await Promise.all([+ loadSelection(trackId, record.id), loadSet(trackId, record.id),+ ]);+ const approved = Object.values(selection?.directions || {})+ .some((entry) => entry?.status === 'approved');+ return set || approved ? record.id : null;+ }));+ return carried.filter(Boolean);+}+/*** Everything about the locked reference this track's render is seeded from — both* when it exists and when it doesn't.diff --git a/server/services/sprites/animationTrackWorkflow.test.js b/server/services/sprites/animationTrackWorkflow.test.jsindex c4df0411d3..7c03597399 100644--- a/server/services/sprites/animationTrackWorkflow.test.js+++ b/server/services/sprites/animationTrackWorkflow.test.js@@ -62,6 +62,7 @@ const records = await import('./records.js');const { lockReference } = await import('./reference.js');const {getTrackState, startTrackGeneration, approveTrackRun, trackAuthoringDirections, trackSetRelPath,+ recordsCarryingTrack,} = await import('./animationTrackWorkflow.js');const {getAnimationTrack, sourceReferenceFor, SCANNER_TRACK, AMBIENT_TRACK,@@ -312,3 +313,62 @@ describe('registry-derived authoring shape (#3136)', () => {await expect(getTrackState('jetpack', 'pioneer')).rejects.toThrow(/Unknown animation track 'jetpack'/);});});++describe('recordsCarryingTrack (#3153)', () => {+ // The evidence scan behind the CRUD surface's in-use refusal: deleting a track (or+ // flipping its facing mode) with approved renders on disk would orphan artifacts+ // the atlas compiler re-verifies by their `setKind`/`selectionKind`. The refusal+ // itself is asserted in animationTrackCrud.test.js; what only this module can get+ // wrong is which on-disk shapes count as "carrying" the track.+ const writeArtifact = async (recordId, relPath, doc) => {+ const abs = join(TEST_ROOT, 'sprites', recordId, relPath);+ await mkdir(join(abs, '..'), { recursive: true });+ await writeFile(abs, JSON.stringify(doc));+ };++ it('is empty when no record carries the track', async () => {+ await records.createRecord({ kind: 'character', name: 'Placeholder Hero' }, newId());+ expect(await recordsCarryingTrack(SCANNER_TRACK)).toEqual([]);+ });++ it('counts a FINALIZED set', async () => {+ const id = newId();+ await records.createRecord({ kind: 'character', name: 'Placeholder Hero' }, id);+ await writeArtifact(id, trackSetRelPath(SCANNER_TRACK, id), { kind: 'finalized-eight-direction-scanner-set' });+ expect(await recordsCarryingTrack(SCANNER_TRACK)).toEqual([id]);+ });++ it('counts a selection with at least one APPROVED direction, before the set freezes', async () => {+ // A directional track with seven approvals has no set yet — but those seven are+ // renders the user approved, so a set-only check would let the delete through and+ // orphan them.+ const id = newId();+ await records.createRecord({ kind: 'character', name: 'Placeholder Hero' }, id);+ await writeArtifact(id, `${SCANNER_TRACK}/${id}-${SCANNER_TRACK}-selection-v1.json`, {+ kind: 'reviewed-directional-scanner-selection',+ directions: { east: { status: 'approved' }, north: { status: 'candidate' } },+ });+ expect(await recordsCarryingTrack(SCANNER_TRACK)).toEqual([id]);+ });++ it('does NOT count an in-progress selection with no approvals', async () => {+ // An unapproved candidate is re-derivable work the user has not committed to, so+ // it must not block a delete — otherwise a single abandoned render permanently+ // pins the track.+ const id = newId();+ await records.createRecord({ kind: 'character', name: 'Placeholder Hero' }, id);+ await writeArtifact(id, `${SCANNER_TRACK}/${id}-${SCANNER_TRACK}-selection-v1.json`, {+ kind: 'reviewed-directional-scanner-selection',+ directions: { east: { status: 'candidate' } },+ });+ expect(await recordsCarryingTrack(SCANNER_TRACK)).toEqual([]);+ });++ it('scopes to the asked-for track, so another track\'s work never blocks this one', async () => {+ const id = newId();+ await records.createRecord({ kind: 'place', name: 'Example Willow' }, id);+ await writeArtifact(id, trackSetRelPath(AMBIENT_TRACK, id), { kind: 'finalized-single-row-ambient-set' });+ expect(await recordsCarryingTrack(AMBIENT_TRACK)).toEqual([id]);+ expect(await recordsCarryingTrack(SCANNER_TRACK)).toEqual([]);+ });+});diff --git a/server/services/sprites/animationTracks.js b/server/services/sprites/animationTracks.jsindex 6a38f3407e..fbdc355973 100644--- a/server/services/sprites/animationTracks.js+++ b/server/services/sprites/animationTracks.js@@ -196,6 +196,65 @@ export const ANIMATION_TRACKS = Object.freeze({* implementation: the whole guard could be deleted and such a test would stay* green, which is exactly the regression it exists to prevent.*/+/**+ * The min/default/max triples every row must keep in order.+ *+ * Exported because three places need this exact pairing and had each spelled their+ * own copy: the assert below, the request schemas in `server/lib/validation.js`+ * (which front-run the assert so the form gets a per-field 400), and the client's+ * pre-submit check. A fourth knob added to one copy and missed in another is the+ * drift this prevents.+ */+export const TRACK_BOUND_TRIPLES = Object.freeze([+ Object.freeze(['minFrameCount', 'defaultFrameCount', 'maxFrameCount']),+ Object.freeze(['minFps', 'defaultFps', 'maxFps']),+]);++/**+ * The fields of a row a USER authors, as opposed to the ones PortOS derives.+ *+ * The complement is deliberate and load-bearing: everything NOT listed here+ * (`contractFrameCountField`, `contractFpsField`, `selectionKind`, `setKind`,+ * `finalErrorCode`, `standaloneContract`, `builtin`) names a file on disk, a+ * publish-contract key, or a cross-row invariant that `assertAnimationTrackRows`+ * requires to be globally unique — so it is derived from the id rather than typed+ * (see `animationTrackCrud.js`). Named here, beside the assert that validates the+ * whole row, so the request schema and the service's whitelist build from ONE list+ * instead of two that fail in opposite directions when they drift: a field in the+ * schema but not the whitelist validates and is then silently dropped, and one in+ * the whitelist but not the schema is rejected as an unrecognized key.+ */+export const AUTHORED_TRACK_FIELDS = Object.freeze([+ 'label', 'directional', 'kinds',+ 'minFrameCount', 'maxFrameCount', 'defaultFrameCount',+ 'minFps', 'maxFps', 'defaultFps',+ 'promptTemplate',+]);++/**+ * The five on-disk / publish-contract discriminators a track's id determines, plus+ * the `contractFpsField` a user-defined row always declines.+ *+ * Derived rather than typed because `assertAnimationTrackRows` requires each to be+ * globally unique and they name artifacts the atlas compiler re-verifies — a typo in+ * one would hand this track another's evidence chain. Lives here, beside that+ * assert, so one module knows a row's whole shape.+ *+ * `contractFpsField` is `null` to match both seeded rows: PortOS's fps is+ * preview-only (a distance-driven consumer owns its timing), so a new track claiming+ * an fps contract key would offer the app a knob nothing reads.+ */+export function deriveTrackFields(id) {+ const camel = id.replace(/-([a-z0-9])/g, (_m, c) => c.toUpperCase());+ return {+ contractFrameCountField: `${camel}FrameCount`,+ contractFpsField: null,+ selectionKind: `reviewed-${id}-selection`,+ setKind: `finalized-${id}-set`,+ finalErrorCode: `${id.replace(/-/g, '_').toUpperCase()}_SET_FINAL`,+ };+}+export function assertAnimationTrackRows(tracks) {const claimedContractFields = new Map();const claimedOnDiskKinds = new Map();@@ -262,10 +321,7 @@ export function assertAnimationTrackRows(tracks) {}claimedOnDiskKinds.set(row[knob], { id, knob });}- for (const [min, def, max] of [- ['minFrameCount', 'defaultFrameCount', 'maxFrameCount'],- ['minFps', 'defaultFps', 'maxFps'],- ]) {+ for (const [min, def, max] of TRACK_BOUND_TRIPLES) {if (!(row[min] <= row[def] && row[def] <= row[max])) {throw new Error(`animationTracks: track '${id}' needs ${min} <= ${def} <= ${max}`);}