Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor: move the sprite schemas into spriteValidation.js, via a shared leaf module (#3873)

[._.]/ Adam Eivy57d269e5ca4f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 6287d52853..15153be74c 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -47,3 +47,4 @@
- The Pipeline's Reverse Outline map now keeps the selected scene in the URL (`?scene=<id>`) instead of component state, so the open scene detail survives a reload and can be linked to or shared. A stale id — after regenerating the outline, say — falls back to the "click a marker" placeholder rather than a blank card, and regenerating clears the selection outright.
- The six "file too large" toasts — album covers, artist portraits, tracks, author headshots, reference audio and OpenClaw attachments — now render their size cap through the shared `formatBytes` helper instead of each dividing by 1024 twice and gluing on "MB". The rendered text gains a space before the unit (`12 MB` rather than `12MB`), which is what the rest of PortOS already shows and what the reference-audio toast already read. The OpenClaw combined-attachment message picked up the same treatment for its decoded-size estimate, so the two limits it can report no longer print their units two different ways.
- The post-restart agent-recovery path is now its own function instead of a 65-line branch inlined at the top of `handleAgentCompletion`, so a change to either it or the live in-memory completion path no longer means reading past the other. The pause guard that path sits behind — the one keeping a stray completion event from cleaning the worktree out from under a later resume — is now pinned by tests that call the real function rather than by a source-text assertion that broke the moment the code moved.
+- The ~460-line Sprite Manager block in `server/lib/validation.js` now lives in its own `server/lib/spriteValidation.js`, matching the eleven other per-domain validation files. A straight lift wasn't possible: the block leans on four fragments (`recordRenderPinFields`, `cloudModelIdString`, `grokVideoDurationSchema`, `isSafeSubdirFilter`) that music video, universe builder, series, video gen and backup also use, and a domain file can't read them back out of `validation.js` — ESM hoists its `export * from` re-exports, so the read lands in the temporal dead zone. Those four moved to a new leaf `server/lib/sharedSchemas.js` first, with `validation.js` still re-exporting them, so every existing deep import keeps working unchanged.
diff --git a/server/lib/README.md b/server/lib/README.md
index 1b1cae822a..bf80bac9bd 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -24,6 +24,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| Module | Purpose |
|---|---|
| `validation.js` | Catch-all Zod schemas (app/process/provider, social accounts, GitHub, backup/sharing, document/legacy-export) + the `validateRequest` middleware + shared helpers (`optionalBooleanMap`, `isSafeRecordId`, `parsePagination`). Re-exports the per-domain validation files below so existing deep imports keep working. |
+| `sharedSchemas.js` | Cross-domain Zod fragments that `validation.js` and the per-domain `*Validation.js` files both need, kept in a leaf module so the domain files never import back through `validation.js` (its hoisted `export * from` lines would TDZ). `grokVideoDurationSchema` (grok clip-length union), `cloudModelIdString(message)` (cloud-CLI model-id charset/bounds), `recordRenderPinFields` (the `imageMode`/`imageModelId` per-record render pin pair), and `isSafeSubdirFilter(v)` (relative path with no wildcard, `..` segment, or leading `/`). |
| `agentOutputMarkers.js` | Status lines PortOS itself appends to an agent's output buffer: `SENTINEL_COMPLETION_MARKER` (the line `ingestDoneSentinel` writes just before the agent's `.agent-done` summary) plus `isAgentLifecycleLine(line)`/`stripLifecycleLines(lines)`, which match PortOS's telemetry on its actual message shapes rather than on a leading emoji (an agent's own summary may well start a line with `✅`). Pure — shared by the emitter (`services/agentTuiSpawning.js`) and by readers that must show only the agent's own words (notably the generated PR description). |
| `agentSentinel.js` | The `.agent-done` completion sentinel: `DONE_SENTINEL_NAME` + pure `parseSentinelPayload(contents)` → `{ summary, payload }`. Back-compat — a plain-markdown sentinel yields `payload: null`; a JSON object yields its structured `payload` for a programmatic-I/O task type's `processTaskOutput` hook. `salvageSentinelPayload(contents)` (async) is the lenient second tier — runs `jsonExtract` over a fenced/prose-trailed/control-char-corrupted envelope so a less-capable model's near-valid output still surfaces its `payload` instead of being dropped. `extractSentinelPayloadFromTranscript(transcript, isPayload)` (async) is the third tier for programmatic-I/O types ONLY — scans the ANSI-stripped PTY transcript, newest balanced JSON block first, for a payload the model PRINTED instead of writing, and adopts it only if the owning hook's shape predicate accepts it (#3640). |
| `agentValidation.js` | Social-bot agent schemas (personality, Moltbook/Moltworld accounts, automation schedules, agent tools + Moltworld payloads) and CoS Feature Agent definitions. |
@@ -54,6 +55,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `privacyValidation.js` | Privacy Center schemas — PII Vault (issue #2140): vault record create/update (partial PUT), list query, UUID params; the vault type/status vocabularies + the sensitive-type (`ssn`/`passport`/`drivers_license`/`financial_account`) `useForScans` hard-false rule and per-type scan defaults. Trusted Organizations registry (issue #2141): org create/update (partial PUT), list query, UUID params, and the replace-set holdings schema. Data-broker database + case ledger (issue #2144): broker list/case-list query filters, the scan-start + refresh action bodies, and the `PRIVACY_BROKER_CASE_STATES` vocabulary. |
| `roundsValidation.js` | Rounds workbench shape bounds + pure record sanitizers (sections, layers, recordings, pitch analysis, references, progress) — `sanitizeRound(raw, builtinIds)` and the length/count limits shared with routes/rounds.js. |
| `socketValidation.js` | Socket event payload schemas. |
+| `spriteValidation.js` | Sprite Manager Zod schemas — record import/create/update, reference generate/lock/unlock + fork, walk-cycle generate/approve/reopen/trim, per-track generate/approve schemas built from the animation-track registry, publish binding + runtime contract, atlas publish/compile, and user-defined animation-track create/update. Split out of `validation.js` (#3873), which re-exports it. |
| `storyBuilderValidation.js` | Unified Story Builder session/step schemas. |
| `telegramValidation.js` | Telegram bot config + test schemas. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 0a9bbfc46f..931918ea90 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -39,9 +39,14 @@ export * as postValidation from './postValidation.js';
export * as privacyValidation from './privacyValidation.js';
export * as roundsValidation from './roundsValidation.js';
export * as socketValidation from './socketValidation.js';
+export * as spriteValidation from './spriteValidation.js';
export * as storyBuilderValidation from './storyBuilderValidation.js';
export * as telegramValidation from './telegramValidation.js';
export * from './validation.js';
+// Cross-domain Zod fragments both `validation.js` and the per-domain files
+// import (leaf module, no cycle). Flat because `validation.js` re-exports the
+// same objects — same identity, so the collision detector is satisfied.
+export * from './sharedSchemas.js';
export * from './threejsModel.js';
export * from './threejsModelCoverage.js';
export * from './threejsModelFamilies.js';
diff --git a/server/lib/sharedSchemas.js b/server/lib/sharedSchemas.js
new file mode 100644
index 0000000000..08b9e1eb94
--- /dev/null
+++ b/server/lib/sharedSchemas.js
@@ -0,0 +1,71 @@
+import { z } from 'zod';
+import { RENDER_TARGET_BACKEND_AUTO, RECORD_RENDER_MODEL_MAX } from './renderTargets.js';
+import { QUEUEABLE_IMAGE_MODES } from '../services/imageGen/modes.js';
+import { GROK_VIDEO_DURATIONS } from './grokVideoClip.js';
+
+/**
+ * Cross-domain Zod primitives — the schema fragments that more than one
+ * validation domain needs.
+ *
+ * Lives here (a leaf module) rather than in `validation.js` for the same
+ * TDZ-cycle reason `zodCompat.js` exists: `validation.js` re-exports every
+ * per-domain `*Validation.js` file with `export * from`, and ESM hoists those
+ * re-exports above the module body — so a domain file that imported a value
+ * back from `validation.js` would read it before it was initialized. Anything
+ * both `validation.js` and a domain file need has to sit below both.
+ *
+ * `zodCompat.js` holds the *Zod-version* compatibility helpers (`.partial()`
+ * semantics, empty-string sentinels); this module holds *PortOS-domain*
+ * fragments that carry real business vocabulary (render pins, model-id
+ * charset, clip lengths, path safety). Keeping them apart is what stops
+ * zodCompat from accumulating imports on renderTargets/imageGen/grok modules.
+ */
+
+// Clip lengths grok's image_to_video delivers, as a Zod union built from the
+// single shared list (see grokVideoClip.js). `z.literal` per value rather than
+// `z.number().refine()` keeps the "expected 6 | 10" error message the
+// hand-written union produced. Shared so routes/videoGen.js and the sprite
+// animation schemas validate `duration` against this same union instead of
+// rebuilding it.
+export const grokVideoDurationSchema = z.union(
+ GROK_VIDEO_DURATIONS.map((d) => z.literal(d)),
+);
+
+// Shared "valid model id" base — one definition of the shape a cloud-CLI
+// model id may take (bounds + charset), derived per consumer so a future
+// tweak (e.g. allowing `@`) lands everywhere at once. Used by settings
+// schemas, the universe render route's one-off override, and the sprite
+// fork/render pins.
+export const cloudModelIdString = (message) => z.string().trim().max(200)
+ .regex(/^[A-Za-z0-9][A-Za-z0-9._:/-]*$/, message);
+
+// Per-RECORD render pin (#3231 Phase 3) — the flat `imageMode`/`imageModelId`
+// field pair persisted on universe / series / sprite records, following the
+// creative-commission shape. Spread into a record's create + patch schemas.
+// Absent preserves; `'auto'`/`''`/null clears (the sanitizers collapse all
+// three to "no pin"). The model id keeps the shared cloud-model charset so a
+// pinned id can safely reach a CLI argv.
+export const recordRenderPinFields = {
+ imageMode: z.preprocess(
+ (v) => (v === '' ? null : v),
+ z.enum([RENDER_TARGET_BACKEND_AUTO, ...QUEUEABLE_IMAGE_MODES]).nullable().optional(),
+ ),
+ imageModelId: z.preprocess(
+ (v) => (v === '' ? null : v),
+ cloudModelIdString('model must be a valid model id').max(RECORD_RENDER_MODEL_MAX).nullable().optional(),
+ ),
+};
+
+// subdirFilter is interpolated into an rsync `--include=${subdirFilter}/***`
+// arg (rsync runs shell:false, so this is not shell injection — but `*` would
+// expand to `--include=*/***` and defeat the filter chain, and `../foo` would
+// traverse out of the snapshot subdir). Restrict to a relative path of safe
+// characters with no wildcard, traversal, or absolute segments. Exported as a
+// predicate so the restoreSnapshot service guard and the sprite run-id schemas
+// reuse the exact same rule (mirrors isSafeRecordId in validation.js) — see
+// issue #1822.
+export const isSafeSubdirFilter = (v) =>
+ typeof v === 'string'
+ && /^[a-z0-9._/-]+$/i.test(v)
+ && !v.split('/').includes('..')
+ && !v.startsWith('/');
diff --git a/server/lib/spriteValidation.js b/server/lib/spriteValidation.js
new file mode 100644
index 0000000000..cd4fd5e989
--- /dev/null
+++ b/server/lib/spriteValidation.js
@@ -0,0 +1,526 @@
+import { z } from 'zod';
+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, 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
+// (see its header for why sync is the right answer here), which is what lets the
+// schemas below stay module-load constants rather than becoming lazily-built.
+import {
+ effectiveTrack, getEffectiveAnimationTracks, getEffectiveAnimationTrackIds,
+} from '../services/sprites/animationTrackStore.js';
+import { QUEUEABLE_IMAGE_MODES } from '../services/imageGen/modes.js';
+import { RECORD_RENDER_MODEL_MAX } from './renderTargets.js';
+import {
+ cloudModelIdString, grokVideoDurationSchema, isSafeSubdirFilter, recordRenderPinFields,
+} from './sharedSchemas.js';
+
+/**
+ * Sprite Manager Zod schemas (issues #2895–#2898, #2979–#2985, #3015, #3136,
+ * #3153). Split out of `validation.js` (issue #3873), which re-exports this
+ * module so every existing `import { spriteXSchema } from '../lib/validation.js'`
+ * keeps working.
+ *
+ * Cycle note: like every other per-domain `*Validation.js` file, this module
+ * must NOT import from `validation.js` — ESM hoists its `export * from` lines,
+ * so this file evaluates before that module's body runs and any value read back
+ * would hit the TDZ. The cross-domain fragments this domain needs
+ * (`cloudModelIdString`, `grokVideoDurationSchema`, `isSafeSubdirFilter`,
+ * `recordRenderPinFields`) therefore live in the leaf `sharedSchemas.js`.
+ */
+
+// Animation-track-aware bounds (#3015). Frame-count / fps ranges are per track,
+// not global, so the factories below take a track id and build the range from
+// that track's registry row. An absent id is the default (walk) track, which is
+// what keeps every pre-#3015 schema identical; an unrecognized one throws out of
+// `getAnimationTrack` at schema-CONSTRUCTION time, so a mis-keyed track is a
+// boot failure naming the known tracks rather than a range that silently
+// validates a scanner action against walk's 6–16.
+//
+// There is deliberately no exported `track` field schema yet: no request shape
+// carries a track id until the first second track lands, and an exported-but-
+// unwired validator is false confidence.
+export function spriteTrackFrameCountSchema(track) {
+ const row = effectiveTrack(track);
+ return z.number().int().min(row.minFrameCount).max(row.maxFrameCount);
+}
+
+export function spriteTrackFpsSchema(track) {
+ const row = effectiveTrack(track);
+ return z.number().int().min(row.minFps).max(row.maxFps);
+}
+
+// Sprite Manager (issue #2895, phase 1). Import runs against a local
+// filesystem path the user supplies (the source pipeline checkout); the
+// importer validates the tree shape server-side. The id pattern is owned by
+// recordsLogic.js (ids double as data/sprites/ directory names) — a pure,
+// dependency-free module, so importing it here can't disturb mocked suites.
+export const spriteImportRequestSchema = z.object({
+ sourceRoot: z.string().min(1).max(1024),
+ characters: z.array(z.string().regex(SPRITE_ID_PATTERN)).optional(),
+ includeProps: z.boolean().optional(),
+});
+
+// Delete one on-disk asset by its record-relative `path` (the same value the
+// listing and static route use). Shape gate only — confinement, the live-atlas
+// refusal, and the per-record write tail are the service's job (assets.js).
+export const spriteAssetDeleteSchema = z.object({
+ path: z.string().min(1).max(1024),
+});
+
+export const spriteRecordUpdateSchema = z.object({
+ name: z.string().min(1).max(200).optional(),
+ // Reclassify an existing record between the noun kinds (#2932). `props` is
+ // accepted so an imported family round-trips without a 400, but the UI never
+ // creates one. Schema-parity with spriteCreateSchema below.
+ kind: z.enum(SPRITE_RECORD_KINDS).optional(),
+ notes: z.string().max(10000).nullable().optional(),
+ // Fixed three-key set (#2895 decision) — manual override is limited to the
+ // same keys the auto-selection picks from. Imported legacy records keep
+ // whatever hex they carried (the importer writes via upsert, not this
+ // schema); null clears back to auto-select-on-lock.
+ chromaKey: z.enum(CHROMA_KEY_HEXES).nullable().optional(),
+ // Per-record render pin (#3231 Phase 3) — this sprite's default image
+ // backend + cloud model for reference renders.
+ ...recordRenderPinFields,
+});
+
+// Phase 4 (issue #2898): publish binding — the shape check only; app
+// existence and repo path anchoring are the publish service's job (they need
+// filesystem + apps access). Repo-relative paths, no traversal, no absolutes.
+const spriteRepoRelativePath = z.string().min(1).max(1024)
+ .refine((p) => !p.startsWith('/') && !p.includes('\\') && !p.split('/').includes('..'), {
+ message: 'must be a repo-relative path with no traversal',
+ });
+
+// The grid the consuming app was built against (#2982). Optional: an absent
+// contract publishes unchecked, exactly as bindings did before it existed.
+// A directional consumer names `walkFrameCount`; an ambient-only consumer names
+// `ambientFrameCount`. Playback speed is deliberately absent: consumers own
+// timing, so PortOS's fps is preview-only and never part of the contract.
+//
+// The per-track frame-count keys are BUILT from the registry (#3136) rather than
+// named one by one: each row already declares the `contractFrameCountField` it
+// occupies, and `assertAnimationTrackRows` refuses two rows claiming the same
+// one, so deriving the schema from those declarations is what lets a
+// user-defined track's contract field validate against ITS bounds with no schema
+// edit. Before this, adding a track meant remembering to add a fourth literal
+// here — and forgetting meant the field was silently stripped by Zod and the
+// app rung of the target-precedence chain went dead for that track.
+const spriteTrackContractFields = Object.fromEntries(
+ Object.values(getEffectiveAnimationTracks())
+ .map((row) => [row.contractFrameCountField, spriteTrackFrameCountSchema(row.id).optional()]),
+);
+
+// The tracks whose frame count is enough ON ITS OWN to make a contract
+// meaningful — a record can't be published without one of these authored, so a
+// contract that pins none of them describes no atlas that could ever exist. The
+// registry DECLARES this per row (`standaloneContract`), which reproduces the
+// historical "walkFrameCount or ambientFrameCount" rule and stays correct for a
+// user-defined track. It is the same field `atlas.js` dispatches its compile
+// evidence chain on, so publish validation and compile can't disagree.
+const SPRITE_STANDALONE_CONTRACT_FIELDS = Object.values(getEffectiveAnimationTracks())
+ .filter((row) => row.standaloneContract)
+ .map((row) => row.contractFrameCountField);
+
+export const spriteRuntimeContractSchema = z.object({
+ // Ranges come from each track's registry row (#3015/#3136). `walkFrameCount`
+ // and its siblings are spread in from `spriteTrackContractFields` above —
+ // `grep walkFrameCount` finds the row in animationTracks.js that names it.
+ ...spriteTrackContractFields,
+ cellSize: z.number().int().min(16).max(1024).nullable().optional(),
+ columnCount: z.number().int().min(1).max(256).nullable().optional(),
+}).superRefine((value, ctx) => {
+ // An empty set means no registered track is a publishable baseline. The boot
+ // guard in `assertAnimationTrackRows` makes that unreachable today (it
+ // requires exactly one per record kind), but this schema must not silently
+ // become "any contract passes" if that ever changes — with `[0]` undefined,
+ // `path: [undefined]` and an empty message would report a rejection nothing
+ // could act on. Refuse the whole contract with a message naming the cause.
+ if (!SPRITE_STANDALONE_CONTRACT_FIELDS.length) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: [],
+ message: 'No animation track declares itself a publishable baseline (standaloneContract) — a runtime contract cannot be validated',
+ });
+ return;
+ }
+ if (SPRITE_STANDALONE_CONTRACT_FIELDS.every((field) => value[field] === undefined)) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: [SPRITE_STANDALONE_CONTRACT_FIELDS[0]],
+ message: `${SPRITE_STANDALONE_CONTRACT_FIELDS.join(' or ')} is required for a runtime contract`,
+ });
+ }
+});
+
+export const spritePublishBindingSchema = z.object({
+ appId: z.string().min(1).max(200),
+ atlasDestPath: spriteRepoRelativePath.refine((p) => p.toLowerCase().endsWith('.png'), {
+ message: 'atlasDestPath must point at a .png atlas file',
+ }),
+ portraitDestPath: spriteRepoRelativePath.refine((p) => p.toLowerCase().endsWith('.png'), {
+ message: 'portraitDestPath must point at a .png image file',
+ }).nullable().optional(),
+ presentationIdleDestPath: spriteRepoRelativePath.refine((p) => p.toLowerCase().endsWith('.png'), {
+ message: 'presentationIdleDestPath must point at a .png sprite strip',
+ }).nullable().optional(),
+ codeBinding: z.object({
+ path: spriteRepoRelativePath,
+ resourcePath: z.string().min(1).max(1024),
+ requiredOccurrenceCount: z.number().int().min(1).max(1000).optional(),
+ }).nullable().optional(),
+ // Absent (key omitted) inherits the stored contract; explicit null clears it
+ // — see setPublishBinding. Keep the two distinguishable: `.optional()` must
+ // stay separate from `.nullable()` here.
+ runtimeContract: spriteRuntimeContractSchema.nullable().optional(),
+}).nullable();
+
+// acknowledgeOverwrite: explicit consent to replace a destination atlas
+// PortOS never published (409 PUBLISH_DEST_OCCUPIED otherwise).
+export const spriteAtlasPublishSchema = z.object({
+ acknowledgeOverwrite: z.boolean().optional(),
+});
+
+// Optional per-compile geometry overrides (player default: 96px cells,
+// pivot (48,88), 86×74 content bounds). Columns/rows are the fixed contract.
+export const spriteAtlasCompileSchema = z.object({
+ geometry: z.object({
+ cellSize: z.number().int().min(16).max(1024).optional(),
+ pivot: z.tuple([z.number().int().min(0), z.number().int().min(0)]).optional(),
+ targetMaxHeight: z.number().int().min(8).max(1024).optional(),
+ targetMaxWidth: z.number().int().min(8).max(1024).optional(),
+ }).optional(),
+});
+
+// Phase 2 (issue #2896): reference workflow. prompts.js / chromaKey.js are
+// pure sprite modules (like recordsLogic.js) so importing their constants
+// here can't disturb mocked suites; modes.js is the dependency-free image-gen
+// enum module.
+export const spriteCreateSchema = z.object({
+ id: z.string().regex(SPRITE_ID_PATTERN).optional(),
+ name: z.string().trim().min(1).max(200),
+ // Noun taxonomy (#2932): the UI's New Sprite panel picks character/place/
+ // object. `props` is accepted for parity with the enum but stays import-only
+ // in practice. Absent → the service defaults to 'character'.
+ kind: z.enum(SPRITE_RECORD_KINDS).optional(),
+ spec: z.record(z.string(), z.unknown()).nullable().optional(),
+ // Per-record render pin (#3231 Phase 3) — seedable at create time (fork).
+ ...recordRenderPinFields,
+});
+
+// 'turnaround' is the identity root of the turnaround-first workflow (#2979) —
+// generated and locked before the main, which the anchors then descend from.
+const spriteReferenceTargetSchema = z.enum([TURNAROUND_ID, 'main', ...ANCHOR_DIRECTIONS]);
+
+// Multipart callers send numbers as form-field strings — coerce before range
+// checks ('' → undefined so an empty field doesn't become 0).
+const optionalUnitNumber = z.preprocess(
+ (v) => (v === '' || v === undefined || v === null ? undefined : Number(v)),
+ z.number().min(0).max(1).optional(),
+);
+
+export const spriteReferenceGenerateSchema = z.object({
+ target: spriteReferenceTargetSchema,
+ mode: z.enum(QUEUEABLE_IMAGE_MODES).optional(),
+ model: z.string().trim().max(64).optional(),
+ effort: z.string().trim().max(32).optional(),
+ designPrompt: z.string().max(4000).optional(),
+ // Extra free-text guidance appended to a turnaround or anchor re-roll (e.g.
+ // "no pocket on the right sleeve") so regenerating diverges from the
+ // previous render instead of reproducing the same mistake.
+ correctionPrompt: z.string().max(4000).optional(),
+ // Re-process one existing turnaround candidate with a correction note. The
+ // service validates that this is a real turnaround candidate owned by the
+ // record before using it as the i2i seed.
+ initImageCandidate: z.string().trim().max(500).optional(),
+ initImageStrength: optionalUnitNumber,
+ // Alternative i2i seed sources for the main target — resolved server-side and
+ // mutually exclusive with an uploaded `referenceImage` file (which the route
+ // handles separately). `initImageGalleryFile` is a render-history gallery
+ // basename; `initImageSpriteId` is another sprite whose locked main reference
+ // seeds this one (the "fork"/derive-from case). Ignored for anchor targets.
+ initImageGalleryFile: z.string().trim().max(300).optional(),
+ initImageSpriteId: z.string().trim().max(200).optional(),
+});
+
+// Fork a new character from an existing sprite's locked main reference: create
+// the record, then image+text→image its main from the source reference. The
+// design prompt is REQUIRED here (unlike a from-scratch generate) — a fork with
+// no instructions is just a duplicate.
+export const spriteForkSchema = z.object({
+ name: z.string().trim().min(1).max(200),
+ id: z.string().trim().max(200).optional(),
+ designPrompt: z.string().trim().min(1).max(4000),
+ mode: z.enum(QUEUEABLE_IMAGE_MODES).optional(),
+ model: cloudModelIdString('model must be a valid model id').max(RECORD_RENDER_MODEL_MAX).optional(),
+ effort: z.string().trim().max(32).optional(),
+ initImageStrength: optionalUnitNumber,
+});
+
+export const spriteReferenceLockSchema = z.object({
+ target: spriteReferenceTargetSchema,
+ candidate: z.string().min(1).max(500),
+ // Confirm-through for a clip-risk main lock (409 CHROMA_CLIP_RISK otherwise).
+ acceptClipRisk: z.boolean().optional(),
+});
+
+// Only the seven turnaround-derived anchors can be revised in place. The
+// turnaround and main remain frozen identity evidence, and south is the main.
+export const spriteReferenceUnlockSchema = z.object({
+ direction: z.enum(ANCHOR_DIRECTIONS),
+});
+
+// Phase 3 (issue #2897): walk-animation workflow. All 8 directions are
+// animatable (south's anchor is the frozen main itself).
+const spriteWalkDirectionSchema = z.enum(SPRITE_DIRECTIONS);
+
+// Any run the walk state can resolve — which is every run id PortOS actually
+// hands the client, not just the native `walk-<dir>-<hex>` shape: an imported
+// run's id is its source-named directory slug (`run-3`), and a redraw run's id
+// is a record-relative manifest path. Every service behind this resolves the id
+// against server-owned walk state and dereferences only paths that state itself
+// recorded (through resolveSpriteAssetPath), so the schema bounds shape and
+// length only — the shared `isSafeSubdirFilter` predicate (safe charset, no `..`
+// segment, no leading `/`), so a hardening tweak there reaches these routes too.
+const spriteResolvableRunIdSchema = z.string().min(1).max(1024)
+ .refine(isSafeSubdirFilter, { message: 'invalid run id' });
+
+// Walk-cycle authoring bounds — built from the walk row of the sharp-free
+// animation-track registry so the request schema and the server-side clamp
+// share ONE range definition (a bounds change can't silently diverge).
+// animationTracks pulls in no deps at all, native or otherwise.
+const spriteWalkFrameCountSchema = spriteTrackFrameCountSchema(WALK_TRACK);
+const spriteWalkFpsSchema = spriteTrackFpsSchema(WALK_TRACK);
+
+export const spriteWalkGenerateSchema = z.object({
+ direction: spriteWalkDirectionSchema,
+ // Clip length in seconds; the service defaults to 6s when omitted. Only
+ // affects how much source footage the packer can choose from — the cycle's
+ // look is set by frameCount/fps below.
+ duration: grokVideoDurationSchema.optional(),
+ // Deterministic-postprocess knobs (not grok's): how many frames the packed
+ // cycle holds and how fast it plays back. Omitted → the set's pinned cycle
+ // target; a value that DISAGREES with that target is refused with 409
+ // WALK_TARGET_MISMATCH (#2985), since every direction in one atlas must share
+ // the geometry.
+ frameCount: spriteWalkFrameCountSchema.optional(),
+ fps: spriteWalkFpsSchema.optional(),
+ // Free-text guidance appended to a re-roll's motion prompt (#3134) — the same
+ // additive correction the reference/anchor renders take. Absent or blank
+ // leaves the prompt byte-identical to a blind regenerate.
+ correctionPrompt: z.string().max(4000).optional(),
+});
+
+// Non-walk animation tracks share ONE generate/approve request shape, built per
+// track from its registry row (#3136) — `scanner` gets 2–8 frames / 2–12fps and
+// `ambient` gets 2–6 / 2–12 from the same factory, so a user-defined track needs
+// no schema edit at all. Two facts make one shape work for both:
+//
+// - `direction` is OPTIONAL here even for a directional track, because the
+// route builds the schema for the track it resolved and a non-directional
+// one derives row 0 server-side. The route requires it (below) exactly when
+// the resolved row is directional, so a directional generate can't slip
+// through without a facing — that check reads the same registry the bounds
+// came from, rather than being restated as a second enum.
+// - the remaining knobs are already registry-derived.
+const buildSpriteTrackGenerateSchema = (track) => z.object({
+ direction: spriteWalkDirectionSchema.optional(),
+ duration: grokVideoDurationSchema.optional(),
+ frameCount: spriteTrackFrameCountSchema(track).optional(),
+ fps: spriteTrackFpsSchema(track).optional(),
+ correctionPrompt: z.string().max(4000).optional(),
+});
+
+// One schema per registered track, built at module load — the same
+// derive-from-the-registry idiom `spriteTrackContractFields` uses, rather than
+// re-allocating six Zod objects on every generate request.
+const SPRITE_TRACK_GENERATE_SCHEMAS = Object.fromEntries(
+ getEffectiveAnimationTrackIds().map((id) => [id, buildSpriteTrackGenerateSchema(id)]),
+);
+
+/**
+ * The generate schema for one track. Unregistered ids build on demand so the
+ * unknown-track error still comes from `getAnimationTrack` (naming the known
+ * tracks) rather than reading as "no schema" — though the route validates
+ * `trackId` against the registry first, so that path is defense in depth.
+ */
+export function spriteTrackGenerateSchema(track) {
+ return SPRITE_TRACK_GENERATE_SCHEMAS[track] || buildSpriteTrackGenerateSchema(track);
+}
+
+export const spriteTrackApproveSchema = z.object({
+ direction: spriteWalkDirectionSchema.optional(),
+ runId: spriteResolvableRunIdSchema,
+});
+
+export const spriteTrackReopenSchema = z.object({
+ direction: spriteWalkDirectionSchema.optional(),
+});
+
+// The `:trackId` path param. Shape gate only — whether the id names a REGISTERED
+// track (and whether this record's kind may carry it) is the service's job, so
+// the 404/400 names the known tracks instead of a regex failure. The charset
+// matches the registry's slug ids and, load-bearingly, can never contain a `/`
+// or `.` that would let the id widen the route's path.
+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 every
+// later render is gated against.
+export const spriteWalkTargetSchema = z.object({
+ frameCount: spriteWalkFrameCountSchema,
+ fps: spriteWalkFpsSchema,
+});
+
+export const spriteWalkApproveSchema = z.object({
+ direction: spriteWalkDirectionSchema,
+ // Also the resolvable shape (#2980): approve has been layout-aware since
+ // #2993 — "a re-derived import stays in the run directory it was imported
+ // into, and its approval must record THAT path" — so the native-only regex
+ // dead-ended the reopen → re-derive → re-approve flow at its last click for
+ // exactly the imported runs that work was for. What makes an approval safe is
+ // approveWalkDirectionImpl's candidate/manifest/strip/frame tamper checks, not
+ // a charset that encodes an obsolete provenance assumption.
+ runId: spriteResolvableRunIdSchema,
+});
+
+// The optional acknowledgement is shared by both ways to re-open imported walk
+// work. Defaulted rather than `.optional()` so the service's own default and the
+// wire shape agree, and an older client's body still means "do not override".
+const spriteWalkAcknowledgeNoClipsSchema = z.boolean().default(false);
+
+export const spriteWalkReopenSchema = z.object({
+ direction: spriteWalkDirectionSchema,
+ acknowledgeNoClips: spriteWalkAcknowledgeNoClipsSchema,
+});
+
+export const spriteWalkUnlockSchema = z.object({
+ acknowledgeNoClips: spriteWalkAcknowledgeNoClipsSchema,
+});
+
+export const spriteWalkPostprocessSchema = z.object({
+ // Resolvable, not native-only (#2980): since #2993 the reprocess is
+ // layout-aware and re-derives an IMPORTED run in the directory it was imported
+ // into — which the strict shape rejected at the door, leaving the one path
+ // back onto the set's target unreachable for exactly the population that
+ // needs it.
+ runId: spriteResolvableRunIdSchema,
+ // Reprocess the on-disk clip without regenerating. Omitted fields adopt the
+ // set's pinned cycle target (#2985) — NOT the run's stored values, since a
+ // reprocess is how a drifted direction is brought back onto the target. A
+ // supplied value that disagrees with the target is refused with 409
+ // WALK_TARGET_MISMATCH.
+ frameCount: spriteWalkFrameCountSchema.optional(),
+ fps: spriteWalkFpsSchema.optional(),
+});
+
+// The raw ffmpeg frames behind one run (#2980) — a read-only enumeration of the
+// directory `listSpriteAssets` deliberately skips. Path params, so the run id
+// arrives as a URL segment; the trimmer can select an imported or redraw run, so
+// it takes the resolvable shape rather than the native one.
+export const spriteWalkSourceFramesParamsSchema = z.object({
+ runId: spriteResolvableRunIdSchema,
+});
+
+// Trim geometry (strip path, cell size, frame labels) derives server-side
+// from the run's packaged manifest — the client only names the run and
+// which frames stay enabled.
+export const spriteWalkTrimSchema = z.object({
+ runId: spriteResolvableRunIdSchema,
+ enabledColumns: z.array(z.number().int().min(0).max(63)).min(2).max(64)
+ .refine((cols) => new Set(cols).size === cols.length, { message: 'columns must be unique' }),
+ fps: z.number().int().min(1).max(60).optional(),
+ slug: z.string().regex(/^[a-z0-9][a-z0-9-]{0,79}$/).optional(),
+});
diff --git a/server/lib/validation.js b/server/lib/validation.js
index f3b693118d..18af784bc1 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -4,37 +4,16 @@ import { partialWithoutDefaults, emptyToUndefined, emptyToNull, optionalBooleanM
import { WORK_TRACKERS } from './workTracker.js';
import { PROVIDER_FAMILY_IDS } from './providerFamilies.js';
import { MAX_MONTHLY_COST } from './subscriptionSavings.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, 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
-// (see its header for why sync is the right answer here), which is what lets the
-// schemas below stay module-load constants rather than becoming lazily-built.
-import {
- effectiveTrack, getEffectiveAnimationTracks, getEffectiveAnimationTrackIds,
-} from '../services/sprites/animationTrackStore.js';
import { QUEUEABLE_IMAGE_MODES } from '../services/imageGen/modes.js';
import { VIDEO_GEN_MODES } from '../services/videoGen/modes.js';
-import { RENDER_TARGETS, RENDER_TARGET_BACKEND_AUTO, RECORD_RENDER_MODEL_MAX } from './renderTargets.js';
-import { GROK_VIDEO_DURATIONS } from './grokVideoClip.js';
+import { RENDER_TARGETS, RENDER_TARGET_BACKEND_AUTO } from './renderTargets.js';
+import {
+ grokVideoDurationSchema, cloudModelIdString, recordRenderPinFields, isSafeSubdirFilter,
+} from './sharedSchemas.js';
import { PR_COMPLETION_VALUES } from './prDisposition.js';
import { EFFORT_LEVELS } from './providerModels.js';
import { MAX_TIMEOUT as AI_RUN_TIMEOUT_MAX_MS, MIN_TIMEOUT as AI_RUN_TIMEOUT_MIN_MS } from './aiToolkit/constants.js';
-// Clip lengths grok's image_to_video delivers, as a Zod union built from the
-// single shared list (see grokVideoClip.js). `z.literal` per value rather than
-// `z.number().refine()` keeps the "expected 6 | 10" error message the
-// hand-written union produced. Exported so routes/videoGen.js validates
-// `grokDuration` against this same schema instead of rebuilding the union.
-export const grokVideoDurationSchema = z.union(
- GROK_VIDEO_DURATIONS.map((d) => z.literal(d)),
-);
-
// gpt-image-2 (codex backend) caps at 3840px per edge and 8,294,400 total
// pixels. Mirror the ceiling for every image-gen route. Local mflux can
// render up to 3840 in principle but is impractically slow past ~2048 — the
@@ -64,6 +43,14 @@ export const isSafeRecordId = (id) =>
// use it without a cycle through this module) — re-exported for deep imports.
export { optionalBooleanMap };
+// Cross-domain Zod fragments now live in sharedSchemas.js for the same
+// no-cycle reason (spriteValidation.js and this module both need them) —
+// re-exported so every existing `import { … } from '../lib/validation.js'`
+// keeps working unchanged.
+export {
+ grokVideoDurationSchema, cloudModelIdString, recordRenderPinFields, isSafeSubdirFilter,
+};
+
// =============================================================================
// EXISTING SCHEMAS
// =============================================================================
@@ -646,19 +633,6 @@ export const apiAccessSettingsSchema = z.object({
sdapi: apiAccessEntrySchema.optional(),
}).strict();
-// subdirFilter is interpolated into an rsync `--include=${subdirFilter}/***` arg
-// (rsync runs shell:false, so this is not shell injection — but `*` would expand
-// to `--include=*/***` and defeat the filter chain, and `../foo` would traverse
-// out of the snapshot subdir). Restrict to a relative path of safe characters
-// with no wildcard, traversal, or absolute segments. Exported as a predicate so
-// the restoreSnapshot service guard reuses the exact same rule (mirrors
-// isSafeRecordId above) — see issue #1822.
-export const isSafeSubdirFilter = (v) =>
- typeof v === 'string'
- && /^[a-z0-9._/-]+$/i.test(v)
- && !v.split('/').includes('..')
- && !v.startsWith('/');
-
export const subdirFilterSchema = z.string()
.refine(isSafeSubdirFilter, 'subdirFilter must be a relative path with no wildcard, ".." , or leading "/" segments');
@@ -1095,13 +1069,6 @@ export const imageGenGrokSettingsSchema = z.object({
denoise: z.boolean().optional(),
});
-// Shared "valid model id" base — one definition of the shape a cloud-CLI
-// model id may take (bounds + charset), derived per consumer below so a
-// future tweak (e.g. allowing `@`) lands everywhere at once. Exported for
-// route schemas that carry a one-off model override (universe renderSchema).
-export const cloudModelIdString = (message) => z.string().trim().max(200)
- .regex(/^[A-Za-z0-9][A-Za-z0-9._:/-]*$/, message);
-
const agyImageModelSchema = z.preprocess(
(v) => (v === '' ? undefined : v),
cloudModelIdString('model must be a valid Agy model id').optional(),
@@ -1163,23 +1130,6 @@ export const videoModelTermsSchema = z.object({
accepted: z.boolean(),
});
-// Per-RECORD render pin (#3231 Phase 3) — the flat `imageMode`/`imageModelId`
-// field pair persisted on universe / series / sprite records, following the
-// creative-commission shape. Spread into a record's create + patch schemas.
-// Absent preserves; `'auto'`/`''`/null clears (the sanitizers collapse all
-// three to "no pin"). The model id keeps the shared cloud-model charset so a
-// pinned id can safely reach a CLI argv.
-export const recordRenderPinFields = {
- imageMode: z.preprocess(
- (v) => (v === '' ? null : v),
- z.enum([RENDER_TARGET_BACKEND_AUTO, ...QUEUEABLE_IMAGE_MODES]).nullable().optional(),
- ),
- imageModelId: z.preprocess(
- (v) => (v === '' ? null : v),
- cloudModelIdString('model must be a valid model id').max(RECORD_RENDER_MODEL_MAX).nullable().optional(),
- ),
-};
-
export const imageGenAgySettingsSchema = z.object({
enabled: z.boolean().optional(),
agyPath: z.preprocess((v) => (v === '' ? undefined : v), z.string().trim().max(500).optional()),
@@ -1294,498 +1244,6 @@ export const videoDownloadSchema = z.object({
url: z.string().url().max(2048)
});
-// Animation-track-aware bounds (#3015). Frame-count / fps ranges are per track,
-// not global, so the factories below take a track id and build the range from
-// that track's registry row. An absent id is the default (walk) track, which is
-// what keeps every pre-#3015 schema identical; an unrecognized one throws out of
-// `getAnimationTrack` at schema-CONSTRUCTION time, so a mis-keyed track is a
-// boot failure naming the known tracks rather than a range that silently
-// validates a scanner action against walk's 6–16.
-//
-// There is deliberately no exported `track` field schema yet: no request shape
-// carries a track id until the first second track lands, and an exported-but-
-// unwired validator is false confidence.
-export function spriteTrackFrameCountSchema(track) {
- const row = effectiveTrack(track);
- return z.number().int().min(row.minFrameCount).max(row.maxFrameCount);
-}
-
-export function spriteTrackFpsSchema(track) {
- const row = effectiveTrack(track);
- return z.number().int().min(row.minFps).max(row.maxFps);
-}
-
-// Sprite Manager (issue #2895, phase 1). Import runs against a local
-// filesystem path the user supplies (the source pipeline checkout); the
-// importer validates the tree shape server-side. The id pattern is owned by
-// recordsLogic.js (ids double as data/sprites/ directory names) — a pure,
-// dependency-free module, so importing it here can't disturb mocked suites.
-export const spriteImportRequestSchema = z.object({
- sourceRoot: z.string().min(1).max(1024),
- characters: z.array(z.string().regex(SPRITE_ID_PATTERN)).optional(),
- includeProps: z.boolean().optional(),
-});
-
-// Delete one on-disk asset by its record-relative `path` (the same value the
-// listing and static route use). Shape gate only — confinement, the live-atlas
-// refusal, and the per-record write tail are the service's job (assets.js).
-export const spriteAssetDeleteSchema = z.object({
- path: z.string().min(1).max(1024),
-});
-
-export const spriteRecordUpdateSchema = z.object({
- name: z.string().min(1).max(200).optional(),
- // Reclassify an existing record between the noun kinds (#2932). `props` is
- // accepted so an imported family round-trips without a 400, but the UI never
- // creates one. Schema-parity with spriteCreateSchema below.
- kind: z.enum(SPRITE_RECORD_KINDS).optional(),
- notes: z.string().max(10000).nullable().optional(),
- // Fixed three-key set (#2895 decision) — manual override is limited to the
- // same keys the auto-selection picks from. Imported legacy records keep
- // whatever hex they carried (the importer writes via upsert, not this
- // schema); null clears back to auto-select-on-lock.
- chromaKey: z.enum(CHROMA_KEY_HEXES).nullable().optional(),
- // Per-record render pin (#3231 Phase 3) — this sprite's default image
- // backend + cloud model for reference renders.
- ...recordRenderPinFields,
-});
-
-// Phase 4 (issue #2898): publish binding — the shape check only; app
-// existence and repo path anchoring are the publish service's job (they need
-// filesystem + apps access). Repo-relative paths, no traversal, no absolutes.
-const spriteRepoRelativePath = z.string().min(1).max(1024)
- .refine((p) => !p.startsWith('/') && !p.includes('\\') && !p.split('/').includes('..'), {
- message: 'must be a repo-relative path with no traversal',
- });
-
-// The grid the consuming app was built against (#2982). Optional: an absent
-// contract publishes unchecked, exactly as bindings did before it existed.
-// A directional consumer names `walkFrameCount`; an ambient-only consumer names
-// `ambientFrameCount`. Playback speed is deliberately absent: consumers own
-// timing, so PortOS's fps is preview-only and never part of the contract.
-//
-// The per-track frame-count keys are BUILT from the registry (#3136) rather than
-// named one by one: each row already declares the `contractFrameCountField` it
-// occupies, and `assertAnimationTrackRows` refuses two rows claiming the same
-// one, so deriving the schema from those declarations is what lets a
-// user-defined track's contract field validate against ITS bounds with no schema
-// edit. Before this, adding a track meant remembering to add a fourth literal
-// here — and forgetting meant the field was silently stripped by Zod and the
-// app rung of the target-precedence chain went dead for that track.
-const spriteTrackContractFields = Object.fromEntries(
- Object.values(getEffectiveAnimationTracks())
- .map((row) => [row.contractFrameCountField, spriteTrackFrameCountSchema(row.id).optional()]),
-);
-
-// The tracks whose frame count is enough ON ITS OWN to make a contract
-// meaningful — a record can't be published without one of these authored, so a
-// contract that pins none of them describes no atlas that could ever exist. The
-// registry DECLARES this per row (`standaloneContract`), which reproduces the
-// historical "walkFrameCount or ambientFrameCount" rule and stays correct for a
-// user-defined track. It is the same field `atlas.js` dispatches its compile
-// evidence chain on, so publish validation and compile can't disagree.
-const SPRITE_STANDALONE_CONTRACT_FIELDS = Object.values(getEffectiveAnimationTracks())
- .filter((row) => row.standaloneContract)
- .map((row) => row.contractFrameCountField);
-
-export const spriteRuntimeContractSchema = z.object({
- // Ranges come from each track's registry row (#3015/#3136). `walkFrameCount`
- // and its siblings are spread in from `spriteTrackContractFields` above —
- // `grep walkFrameCount` finds the row in animationTracks.js that names it.
- ...spriteTrackContractFields,
- cellSize: z.number().int().min(16).max(1024).nullable().optional(),
- columnCount: z.number().int().min(1).max(256).nullable().optional(),
-}).superRefine((value, ctx) => {
- // An empty set means no registered track is a publishable baseline. The boot
- // guard in `assertAnimationTrackRows` makes that unreachable today (it
- // requires exactly one per record kind), but this schema must not silently
- // become "any contract passes" if that ever changes — with `[0]` undefined,
- // `path: [undefined]` and an empty message would report a rejection nothing
- // could act on. Refuse the whole contract with a message naming the cause.
- if (!SPRITE_STANDALONE_CONTRACT_FIELDS.length) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- path: [],
- message: 'No animation track declares itself a publishable baseline (standaloneContract) — a runtime contract cannot be validated',
- });
- return;
- }
- if (SPRITE_STANDALONE_CONTRACT_FIELDS.every((field) => value[field] === undefined)) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- path: [SPRITE_STANDALONE_CONTRACT_FIELDS[0]],
- message: `${SPRITE_STANDALONE_CONTRACT_FIELDS.join(' or ')} is required for a runtime contract`,
- });
- }
-});
-
-export const spritePublishBindingSchema = z.object({
- appId: z.string().min(1).max(200),
- atlasDestPath: spriteRepoRelativePath.refine((p) => p.toLowerCase().endsWith('.png'), {
- message: 'atlasDestPath must point at a .png atlas file',
- }),
- portraitDestPath: spriteRepoRelativePath.refine((p) => p.toLowerCase().endsWith('.png'), {
- message: 'portraitDestPath must point at a .png image file',
- }).nullable().optional(),
- presentationIdleDestPath: spriteRepoRelativePath.refine((p) => p.toLowerCase().endsWith('.png'), {
- message: 'presentationIdleDestPath must point at a .png sprite strip',
- }).nullable().optional(),
- codeBinding: z.object({
- path: spriteRepoRelativePath,
- resourcePath: z.string().min(1).max(1024),
- requiredOccurrenceCount: z.number().int().min(1).max(1000).optional(),
- }).nullable().optional(),
- // Absent (key omitted) inherits the stored contract; explicit null clears it
- // — see setPublishBinding. Keep the two distinguishable: `.optional()` must
- // stay separate from `.nullable()` here.
- runtimeContract: spriteRuntimeContractSchema.nullable().optional(),
-}).nullable();
-
-// acknowledgeOverwrite: explicit consent to replace a destination atlas
-// PortOS never published (409 PUBLISH_DEST_OCCUPIED otherwise).
-export const spriteAtlasPublishSchema = z.object({
- acknowledgeOverwrite: z.boolean().optional(),
-});
-
-// Optional per-compile geometry overrides (player default: 96px cells,
-// pivot (48,88), 86×74 content bounds). Columns/rows are the fixed contract.
-export const spriteAtlasCompileSchema = z.object({
- geometry: z.object({
- cellSize: z.number().int().min(16).max(1024).optional(),
- pivot: z.tuple([z.number().int().min(0), z.number().int().min(0)]).optional(),
- targetMaxHeight: z.number().int().min(8).max(1024).optional(),
- targetMaxWidth: z.number().int().min(8).max(1024).optional(),
- }).optional(),
-});
-
-// Phase 2 (issue #2896): reference workflow. prompts.js / chromaKey.js are
-// pure sprite modules (like recordsLogic.js) so importing their constants
-// here can't disturb mocked suites; modes.js is the dependency-free image-gen
-// enum module.
-export const spriteCreateSchema = z.object({
- id: z.string().regex(SPRITE_ID_PATTERN).optional(),
- name: z.string().trim().min(1).max(200),
- // Noun taxonomy (#2932): the UI's New Sprite panel picks character/place/
- // object. `props` is accepted for parity with the enum but stays import-only
- // in practice. Absent → the service defaults to 'character'.
- kind: z.enum(SPRITE_RECORD_KINDS).optional(),
- spec: z.record(z.string(), z.unknown()).nullable().optional(),
- // Per-record render pin (#3231 Phase 3) — seedable at create time (fork).
- ...recordRenderPinFields,
-});
-
-// 'turnaround' is the identity root of the turnaround-first workflow (#2979) —
-// generated and locked before the main, which the anchors then descend from.
-const spriteReferenceTargetSchema = z.enum([TURNAROUND_ID, 'main', ...ANCHOR_DIRECTIONS]);
-
-// Multipart callers send numbers as form-field strings — coerce before range
-// checks ('' → undefined so an empty field doesn't become 0).
-const optionalUnitNumber = z.preprocess(
- (v) => (v === '' || v === undefined || v === null ? undefined : Number(v)),
- z.number().min(0).max(1).optional(),
-);
-
-export const spriteReferenceGenerateSchema = z.object({
- target: spriteReferenceTargetSchema,
- mode: z.enum(QUEUEABLE_IMAGE_MODES).optional(),
- model: z.string().trim().max(64).optional(),
- effort: z.string().trim().max(32).optional(),
- designPrompt: z.string().max(4000).optional(),
- // Extra free-text guidance appended to a turnaround or anchor re-roll (e.g.
- // "no pocket on the right sleeve") so regenerating diverges from the
- // previous render instead of reproducing the same mistake.
- correctionPrompt: z.string().max(4000).optional(),
- // Re-process one existing turnaround candidate with a correction note. The
- // service validates that this is a real turnaround candidate owned by the
- // record before using it as the i2i seed.
- initImageCandidate: z.string().trim().max(500).optional(),
- initImageStrength: optionalUnitNumber,
- // Alternative i2i seed sources for the main target — resolved server-side and
- // mutually exclusive with an uploaded `referenceImage` file (which the route
- // handles separately). `initImageGalleryFile` is a render-history gallery
- // basename; `initImageSpriteId` is another sprite whose locked main reference
- // seeds this one (the "fork"/derive-from case). Ignored for anchor targets.
- initImageGalleryFile: z.string().trim().max(300).optional(),
- initImageSpriteId: z.string().trim().max(200).optional(),
-});
-
-// Fork a new character from an existing sprite's locked main reference: create
-// the record, then image+text→image its main from the source reference. The
-// design prompt is REQUIRED here (unlike a from-scratch generate) — a fork with
-// no instructions is just a duplicate.
-export const spriteForkSchema = z.object({
- name: z.string().trim().min(1).max(200),
- id: z.string().trim().max(200).optional(),
- designPrompt: z.string().trim().min(1).max(4000),
- mode: z.enum(QUEUEABLE_IMAGE_MODES).optional(),
- model: cloudModelIdString('model must be a valid model id').max(RECORD_RENDER_MODEL_MAX).optional(),
- effort: z.string().trim().max(32).optional(),
- initImageStrength: optionalUnitNumber,
-});
-
-export const spriteReferenceLockSchema = z.object({
- target: spriteReferenceTargetSchema,
- candidate: z.string().min(1).max(500),
- // Confirm-through for a clip-risk main lock (409 CHROMA_CLIP_RISK otherwise).
- acceptClipRisk: z.boolean().optional(),
-});
-
-// Only the seven turnaround-derived anchors can be revised in place. The
-// turnaround and main remain frozen identity evidence, and south is the main.
-export const spriteReferenceUnlockSchema = z.object({
- direction: z.enum(ANCHOR_DIRECTIONS),
-});
-
-// Phase 3 (issue #2897): walk-animation workflow. All 8 directions are
-// animatable (south's anchor is the frozen main itself).
-const spriteWalkDirectionSchema = z.enum(SPRITE_DIRECTIONS);
-
-// Any run the walk state can resolve — which is every run id PortOS actually
-// hands the client, not just the native `walk-<dir>-<hex>` shape: an imported
-// run's id is its source-named directory slug (`run-3`), and a redraw run's id
-// is a record-relative manifest path. Every service behind this resolves the id
-// against server-owned walk state and dereferences only paths that state itself
-// recorded (through resolveSpriteAssetPath), so the schema bounds shape and
-// length only — the shared `isSafeSubdirFilter` predicate (safe charset, no `..`
-// segment, no leading `/`), so a hardening tweak there reaches these routes too.
-const spriteResolvableRunIdSchema = z.string().min(1).max(1024)
- .refine(isSafeSubdirFilter, { message: 'invalid run id' });
-
-// Walk-cycle authoring bounds — built from the walk row of the sharp-free
-// animation-track registry so the request schema and the server-side clamp
-// share ONE range definition (a bounds change can't silently diverge).
-// animationTracks pulls in no deps at all, native or otherwise.
-const spriteWalkFrameCountSchema = spriteTrackFrameCountSchema(WALK_TRACK);
-const spriteWalkFpsSchema = spriteTrackFpsSchema(WALK_TRACK);
-
-export const spriteWalkGenerateSchema = z.object({
- direction: spriteWalkDirectionSchema,
- // Clip length in seconds; the service defaults to 6s when omitted. Only
- // affects how much source footage the packer can choose from — the cycle's
- // look is set by frameCount/fps below.
- duration: grokVideoDurationSchema.optional(),
- // Deterministic-postprocess knobs (not grok's): how many frames the packed
- // cycle holds and how fast it plays back. Omitted → the set's pinned cycle
- // target; a value that DISAGREES with that target is refused with 409
- // WALK_TARGET_MISMATCH (#2985), since every direction in one atlas must share
- // the geometry.
- frameCount: spriteWalkFrameCountSchema.optional(),
- fps: spriteWalkFpsSchema.optional(),
- // Free-text guidance appended to a re-roll's motion prompt (#3134) — the same
- // additive correction the reference/anchor renders take. Absent or blank
- // leaves the prompt byte-identical to a blind regenerate.
- correctionPrompt: z.string().max(4000).optional(),
-});
-
-// Non-walk animation tracks share ONE generate/approve request shape, built per
-// track from its registry row (#3136) — `scanner` gets 2–8 frames / 2–12fps and
-// `ambient` gets 2–6 / 2–12 from the same factory, so a user-defined track needs
-// no schema edit at all. Two facts make one shape work for both:
-//
-// - `direction` is OPTIONAL here even for a directional track, because the
-// route builds the schema for the track it resolved and a non-directional
-// one derives row 0 server-side. The route requires it (below) exactly when
-// the resolved row is directional, so a directional generate can't slip
-// through without a facing — that check reads the same registry the bounds
-// came from, rather than being restated as a second enum.
-// - the remaining knobs are already registry-derived.
-const buildSpriteTrackGenerateSchema = (track) => z.object({
- direction: spriteWalkDirectionSchema.optional(),
- duration: grokVideoDurationSchema.optional(),
- frameCount: spriteTrackFrameCountSchema(track).optional(),
- fps: spriteTrackFpsSchema(track).optional(),
- correctionPrompt: z.string().max(4000).optional(),
-});
-
-// One schema per registered track, built at module load — the same
-// derive-from-the-registry idiom `spriteTrackContractFields` uses, rather than
-// re-allocating six Zod objects on every generate request.
-const SPRITE_TRACK_GENERATE_SCHEMAS = Object.fromEntries(
- getEffectiveAnimationTrackIds().map((id) => [id, buildSpriteTrackGenerateSchema(id)]),
-);
-
-/**
- * The generate schema for one track. Unregistered ids build on demand so the
- * unknown-track error still comes from `getAnimationTrack` (naming the known
- * tracks) rather than reading as "no schema" — though the route validates
- * `trackId` against the registry first, so that path is defense in depth.
- */
-export function spriteTrackGenerateSchema(track) {
- return SPRITE_TRACK_GENERATE_SCHEMAS[track] || buildSpriteTrackGenerateSchema(track);
-}
-
-export const spriteTrackApproveSchema = z.object({
- direction: spriteWalkDirectionSchema.optional(),
- runId: spriteResolvableRunIdSchema,
-});
-
-export const spriteTrackReopenSchema = z.object({
- direction: spriteWalkDirectionSchema.optional(),
-});
-
-// The `:trackId` path param. Shape gate only — whether the id names a REGISTERED
-// track (and whether this record's kind may carry it) is the service's job, so
-// the 404/400 names the known tracks instead of a regex failure. The charset
-// matches the registry's slug ids and, load-bearingly, can never contain a `/`
-// or `.` that would let the id widen the route's path.
-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 every
-// later render is gated against.
-export const spriteWalkTargetSchema = z.object({
- frameCount: spriteWalkFrameCountSchema,
- fps: spriteWalkFpsSchema,
-});
-
-export const spriteWalkApproveSchema = z.object({
- direction: spriteWalkDirectionSchema,
- // Also the resolvable shape (#2980): approve has been layout-aware since
- // #2993 — "a re-derived import stays in the run directory it was imported
- // into, and its approval must record THAT path" — so the native-only regex
- // dead-ended the reopen → re-derive → re-approve flow at its last click for
- // exactly the imported runs that work was for. What makes an approval safe is
- // approveWalkDirectionImpl's candidate/manifest/strip/frame tamper checks, not
- // a charset that encodes an obsolete provenance assumption.
- runId: spriteResolvableRunIdSchema,
-});
-
-// The optional acknowledgement is shared by both ways to re-open imported walk
-// work. Defaulted rather than `.optional()` so the service's own default and the
-// wire shape agree, and an older client's body still means "do not override".
-const spriteWalkAcknowledgeNoClipsSchema = z.boolean().default(false);
-
-export const spriteWalkReopenSchema = z.object({
- direction: spriteWalkDirectionSchema,
- acknowledgeNoClips: spriteWalkAcknowledgeNoClipsSchema,
-});
-
-export const spriteWalkUnlockSchema = z.object({
- acknowledgeNoClips: spriteWalkAcknowledgeNoClipsSchema,
-});
-
-export const spriteWalkPostprocessSchema = z.object({
- // Resolvable, not native-only (#2980): since #2993 the reprocess is
- // layout-aware and re-derives an IMPORTED run in the directory it was imported
- // into — which the strict shape rejected at the door, leaving the one path
- // back onto the set's target unreachable for exactly the population that
- // needs it.
- runId: spriteResolvableRunIdSchema,
- // Reprocess the on-disk clip without regenerating. Omitted fields adopt the
- // set's pinned cycle target (#2985) — NOT the run's stored values, since a
- // reprocess is how a drifted direction is brought back onto the target. A
- // supplied value that disagrees with the target is refused with 409
- // WALK_TARGET_MISMATCH.
- frameCount: spriteWalkFrameCountSchema.optional(),
- fps: spriteWalkFpsSchema.optional(),
-});
-
-// The raw ffmpeg frames behind one run (#2980) — a read-only enumeration of the
-// directory `listSpriteAssets` deliberately skips. Path params, so the run id
-// arrives as a URL segment; the trimmer can select an imported or redraw run, so
-// it takes the resolvable shape rather than the native one.
-export const spriteWalkSourceFramesParamsSchema = z.object({
- runId: spriteResolvableRunIdSchema,
-});
-
-// Trim geometry (strip path, cell size, frame labels) derives server-side
-// from the run's packaged manifest — the client only names the run and
-// which frames stay enabled.
-export const spriteWalkTrimSchema = z.object({
- runId: spriteResolvableRunIdSchema,
- enabledColumns: z.array(z.number().int().min(0).max(63)).min(2).max(64)
- .refine((cols) => new Set(cols).size === cols.length, { message: 'columns must be unique' }),
- fps: z.number().int().min(1).max(60).optional(),
- slug: z.string().regex(/^[a-z0-9][a-z0-9-]{0,79}$/).optional(),
-});
-
// =============================================================================
// TRANSITIONAL RE-EXPORTS (issue #1151 split)
// =============================================================================
@@ -1810,3 +1268,4 @@ export * from './cosValidation.js';
export * from './mediaValidation.js';
export * from './pipelineValidation.js';
export * from './quotaBurnValidation.js';
+export * from './spriteValidation.js';
diff --git a/server/lib/validationSplit.test.js b/server/lib/validationSplit.test.js
index af5eefe0d8..c7404fbc54 100644
--- a/server/lib/validationSplit.test.js
+++ b/server/lib/validationSplit.test.js
@@ -7,6 +7,8 @@ import * as agentValidation from './agentValidation.js';
import * as cosValidation from './cosValidation.js';
import * as mediaValidation from './mediaValidation.js';
import * as pipelineValidation from './pipelineValidation.js';
+import * as spriteValidation from './spriteValidation.js';
+import * as sharedSchemas from './sharedSchemas.js';
// Issues #1151 and #1831 split validation.js's domain schema groups into per-
// domain files, with validation.js re-exporting them so existing deep imports
@@ -24,6 +26,8 @@ describe('validation.js transitional re-exports (issues #1151, #1831)', () => {
['cosValidation', cosValidation],
['mediaValidation', mediaValidation],
['pipelineValidation', pipelineValidation],
+ // #3873
+ ['spriteValidation', spriteValidation],
];
it.each(domains)('%s exports are all reachable from validation.js as the same objects', (_name, mod) => {
@@ -74,8 +78,29 @@ describe('validation.js transitional re-exports (issues #1151, #1831)', () => {
expect(typeof validation.emptyToUndefined).toBe('function');
});
+ it('#3873: the sprite split kept its shared helpers reachable and its schemas usable', () => {
+ // The four cross-domain fragments the sprite block depends on moved to the
+ // leaf sharedSchemas.js. validation.js must still export the SAME objects
+ // (deep imports across six non-sprite call sites relied on it), and the
+ // sprite schemas must still parse through the validation.js entry.
+ for (const key of ['grokVideoDurationSchema', 'cloudModelIdString', 'recordRenderPinFields', 'isSafeSubdirFilter']) {
+ expect(validation[key], `validation.js re-export of '${key}'`).toBe(sharedSchemas[key]);
+ }
+ expect(() => validation.validateRequest(validation.spriteCreateSchema, {
+ name: 'Example Sprite', imageMode: '', imageModelId: '',
+ })).not.toThrow();
+ expect(() => validation.validateRequest(validation.spriteWalkTrimSchema, {
+ runId: 'run-3', enabledColumns: [0, 1, 2],
+ })).not.toThrow();
+ // The `recordRenderPinFields` spread must still be live inside the moved
+ // schemas — a bad model id is a rejection, not a stripped field.
+ expect(validation.spriteCreateSchema.safeParse({
+ name: 'Example Sprite', imageModelId: '../etc/passwd',
+ }).success).toBe(false);
+ });
+
it('the new #1831 domain files do NOT import back from validation.js (cycle guard)', () => {
- for (const mod of [agentValidation, cosValidation, mediaValidation, pipelineValidation]) {
+ for (const mod of [agentValidation, cosValidation, mediaValidation, pipelineValidation, spriteValidation]) {
// validateRequest / parsePagination live only in validation.js — if a
// domain file re-imported the barrel they'd leak through `export *`.
expect(mod.validateRequest).toBeUndefined();
diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.js
index 6388f1dc24..e2a9a1e416 100644
--- a/server/routes/musicVideo.js
+++ b/server/routes/musicVideo.js
@@ -21,10 +21,10 @@ import {
musicVideoPlanRequestSchema,
musicVideoManualAnalysisSchema,
musicVideoTranscribeMidiRequestSchema,
- recordRenderPinFields,
isPaginationRequested,
paginateArray,
} from '../lib/validation.js';
+import { recordRenderPinFields } from '../lib/sharedSchemas.js';
import { PATHS } from '../lib/fileUtils.js';
import { safeUnder } from '../lib/ffmpeg.js';
import {
@@ -57,8 +57,11 @@ const router = Router();
// the shared universe/series/sprite field pair) on Music Video projects: scene
// reference-frame renders resolve through it (imageGen/prepareParams.js).
// Extended at the route layer — the same pattern as routes/universeBuilder/ —
-// because musicVideoValidation.js can't import recordRenderPinFields from
-// validation.js without a circular import (validation.js re-exports it).
+// so the pin stays a route-level concern and musicVideoProjectCreateSchema keeps
+// the shape peers sync against. (Since #3873 the fragment lives in the leaf
+// sharedSchemas.js, so musicVideoValidation.js COULD import it without the
+// TDZ cycle that re-exporting through validation.js used to cause — the route
+// layer is now a choice, not a workaround.)
const projectCreateSchema = musicVideoProjectCreateSchema.extend(recordRenderPinFields);
const projectUpdateSchema = musicVideoProjectUpdateSchema.extend(recordRenderPinFields);
diff --git a/server/routes/pipeline/series.js b/server/routes/pipeline/series.js
index e761508509..a615bf9542 100644
--- a/server/routes/pipeline/series.js
+++ b/server/routes/pipeline/series.js
@@ -7,7 +7,8 @@
import { Router } from 'express';
import { z } from 'zod';
import { asyncHandler, ServerError } from '../../lib/errorHandler.js';
-import { validateRequest, optionalBooleanMap, llmSchema, recordRenderPinFields } from '../../lib/validation.js';
+import { validateRequest, optionalBooleanMap, llmSchema } from '../../lib/validation.js';
+import { recordRenderPinFields } from '../../lib/sharedSchemas.js';
import * as seriesSvc from '../../services/pipeline/series.js';
import { TRIM_SIZES, INTERIOR_FONTS } from '../../lib/proseExportSettings.js';
import * as issuesSvc from '../../services/pipeline/issues.js';
diff --git a/server/routes/universeBuilder/crud.js b/server/routes/universeBuilder/crud.js
index 0701c6d41d..6513c3ee79 100644
--- a/server/routes/universeBuilder/crud.js
+++ b/server/routes/universeBuilder/crud.js
@@ -10,7 +10,8 @@
import { Router } from 'express';
import { z } from 'zod';
import { asyncHandler } from '../../lib/errorHandler.js';
-import { validateRequest, llmSchema, isPaginationRequested, paginateArray, recordRenderPinFields } from '../../lib/validation.js';
+import { validateRequest, llmSchema, isPaginationRequested, paginateArray } from '../../lib/validation.js';
+import { recordRenderPinFields } from '../../lib/sharedSchemas.js';
import { pruneStaleReferenceSheets } from '../../lib/storyBible.js';
import * as svc from '../../services/universeBuilder.js';
import { findSameNameUniverses } from '../../services/duplicateDetection.js';
diff --git a/server/routes/universeBuilder/render.js b/server/routes/universeBuilder/render.js
index fd715ab6f4..093e20103a 100644
--- a/server/routes/universeBuilder/render.js
+++ b/server/routes/universeBuilder/render.js
@@ -8,7 +8,8 @@
import { Router } from 'express';
import { z } from 'zod';
import { asyncHandler } from '../../lib/errorHandler.js';
-import { validateRequest, cloudModelIdString } from '../../lib/validation.js';
+import { validateRequest } from '../../lib/validation.js';
+import { cloudModelIdString } from '../../lib/sharedSchemas.js';
import { RECORD_RENDER_MODEL_MAX } from '../../lib/renderTargets.js';
import { BIBLE_LIMITS } from '../../lib/storyBible.js';
import * as svc from '../../services/universeBuilder.js';
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index 22d23cf4c6..5f83d05107 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -15,7 +15,8 @@ import { z } from 'zod';
import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.js';
import { uploadFields } from '../lib/multipart.js';
import { PATHS } from '../lib/fileUtils.js';
-import { grokVideoDurationSchema, videoModelTermsSchema } from '../lib/validation.js';
+import { videoModelTermsSchema } from '../lib/validation.js';
+import { grokVideoDurationSchema } from '../lib/sharedSchemas.js';
import { MIN_CONTEXT_FRAMES, MAX_CONTEXT_FRAMES } from '../lib/videoContinuity.js';
import {
VIDEO_BACKEND_DISCLOSURES, isVideoModelTermsAccepted, acceptedVideoModelTerms,
diff --git a/server/services/backup.js b/server/services/backup.js
index 1c8b008ba4..1d4b9259d3 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -17,7 +17,7 @@ import { checkHealth, getServerMajorVersion } from '../lib/db.js';
import { resolvePgDumpBinary } from '../lib/pgTools.js';
import { getBackendName } from './memoryBackend.js';
import { emitErrorEvent, ServerError } from '../lib/errorHandler.js';
-import { isSafeSubdirFilter } from '../lib/validation.js';
+import { isSafeSubdirFilter } from '../lib/sharedSchemas.js';
import { getIo } from './socket.js';
import { reloadSettings } from './settings.js';