Skip to content

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

refactor([issue-1151]): split peer-sync, creative-director/importer, and story-builder schemas out of validation.js

[._.]/ Adam Eivy665df9146690
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 2f252e88ed..76e22b28f6 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -35,6 +35,8 @@
## Changed
+- **[issue-1151] Internal reorganization of request validation** — the peer-sync, Creative Director, importer, and Story Builder validation rules moved into their own focused files. No behavior change.
+
- **[issue-1150] Sturdier federation internals** — the machinery that auto-shares newly created universes, series, and collections with your other machines no longer depends on fragile module load ordering. No change to how syncing behaves.
- **[issue-1149] Calendar errors are now consistent everywhere** — calendar sync, discovery, and Google OAuth setup failures all come back in the same structured shape the rest of the app uses (instead of a mix of formats), and a failed Google sign-in now lands you back on the Calendar Config page with a clear error message instead of a raw error page.
diff --git a/server/lib/README.md b/server/lib/README.md
index 05b379bb5a..fb288de5dc 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -27,14 +27,17 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `appleHealthValidation.js` | Apple Health import payloads. |
| `brainValidation.js` | Brain/memory route schemas (search, ingest, edit). |
| `catalogValidation.js` | Creative ingredients catalog route schemas (scraps, ingredients, links, relations, tags, revisions, sync envelope). |
+| `creativeDirectorValidation.js` | Creative Director project/treatment/scene + Create-Suite importer schemas. |
| `digitalTwinValidation.js` | Digital twin document/category schemas. |
| `genomeValidation.js` | Genome upload + search schemas. |
| `identityValidation.js` | Identity section + chronotype + scheduling schemas. |
| `meatspaceValidation.js` | Meatspace (location/health log) schemas. |
| `memoryValidation.js` | Memory record + retrieval schemas. |
| `notesValidation.js` | Notes route schemas + safe-relative-path guard. |
+| `peerSyncValidation.js` | Federated peer-sync wire/request schemas (push payload, subscribe, sync-now, pull-metadata). |
| `postValidation.js` | Social post schemas. |
| `socketValidation.js` | Socket event payload schemas. |
+| `storyBuilderValidation.js` | Unified Story Builder session/step schemas. |
| `telegramValidation.js` | Telegram bot config + test schemas. |
## Story & narrative
diff --git a/server/lib/creativeDirectorValidation.js b/server/lib/creativeDirectorValidation.js
new file mode 100644
index 0000000000..e84f7d01bc
--- /dev/null
+++ b/server/lib/creativeDirectorValidation.js
@@ -0,0 +1,299 @@
+import { z } from 'zod';
+import { ASPECT_RATIOS, QUALITIES, PROJECT_STATUSES, SCENE_STATUSES } from './creativeDirectorPresets.js';
+import { ARC_SHAPE_IDS, ARC_ROLES } from './storyArc.js';
+import { BIBLE_LIMITS } from './storyBible.js';
+import { emptyToUndefined } from './zodCompat.js';
+
+// =============================================================================
+// CREATIVE DIRECTOR + CREATE-SUITE IMPORTER SCHEMAS
+// =============================================================================
+// Split out of validation.js (issue #1151); validation.js re-exports
+// everything here so existing deep imports keep working. The import from
+// zodCompat.js (not validation.js) supplies emptyToUndefined — ESM hoists
+// validation.js's `export * from` of this module, so importing validation.js
+// back from here would evaluate before its body runs (TDZ).
+
+
+export const creativeDirectorAspectRatioSchema = z.enum(ASPECT_RATIOS);
+export const creativeDirectorQualitySchema = z.enum(QUALITIES);
+
+// Top-level project create. modelId is required because each LTX variant
+// has a different speed/VRAM/quality profile and the project locks it at
+// creation. targetDurationSeconds is capped at 600 (10 min) per the v1 plan
+// — much beyond that and the agent's treatment quality drifts hard.
+// Strict basename: rejects path separators and the exact `.`/`..` segments.
+// Used for both startingImageFile (project create) and sourceImageFile
+// (per-scene) since both feed into `join(PATHS.images, ...)` later. The
+// downstream consumers also do a resolve+prefix-check against PATHS.images
+// (sceneRunner.js) — that's the real traversal guard; this validator just
+// catches the obvious bad values at the route boundary. Note: a substring
+// check on `..` would over-reject legitimate names like `my..image.png`,
+// so we only reject the exact dot segments and rely on prefix-checks for
+// the actual escape protection.
+const safeBasename = z.string()
+ .max(256)
+ .regex(/^[^/\\]+$/, 'must be a basename (no path separators)')
+ .refine((v) => v !== '.' && v !== '..',
+ 'must not be `.` or `..`');
+
+export const creativeDirectorProjectCreateSchema = z.object({
+ name: z.string().min(1).max(200),
+ aspectRatio: creativeDirectorAspectRatioSchema,
+ quality: creativeDirectorQualitySchema,
+ modelId: z.string().min(1).max(64),
+ targetDurationSeconds: z.number().int().min(5).max(600),
+ styleSpec: z.string().max(5000).default(''),
+ startingImageFile: safeBasename.nullable().optional(),
+ userStory: z.string().max(10000).nullable().optional(),
+ // Audio defaults OFF for CD projects — current model audio output is
+ // inconsistent across renders and the user can re-enable per-project.
+ // (videoGen one-offs still default to enabled.)
+ disableAudio: z.boolean().optional().default(true),
+ autoAcceptScenes: z.boolean().optional().default(false),
+ // Optional back-pointer to the pipeline issue that spawned this project,
+ // used by the stitch step to mix in audio-stage music. Bare CD projects
+ // (no pipeline origin) leave this null.
+ sourceIssueId: z.string().min(1).max(64).nullable().optional(),
+});
+
+// Update is restricted to a few editable fields. modelId / aspectRatio /
+// quality / targetDurationSeconds are locked at creation — changing them
+// mid-project would invalidate already-rendered segments.
+//
+// Server-managed fields (timelineProjectId, runs, treatment) are
+// intentionally NOT in this schema. timelineProjectId is set only by
+// stitchRunner.js — accepting it in PATCH payloads would let a client
+// point a CD project at an unrelated user timeline project, which the
+// next stitch would silently overwrite via updateTimelineProject.
+export const creativeDirectorProjectUpdateSchema = z.object({
+ name: z.string().min(1).max(200).optional(),
+ styleSpec: z.string().max(5000).optional(),
+ userStory: z.string().max(10000).nullable().optional(),
+ status: z.enum(PROJECT_STATUSES).optional(),
+ finalVideoId: z.string().max(64).nullable().optional(),
+ failureReason: z.string().max(500).nullable().optional(),
+ // Toggleable post-creation — only affects future scene renders.
+ disableAudio: z.boolean().optional(),
+}).strict();
+
+// One scene in the treatment, written by the agent on the treatment task.
+export const creativeDirectorSceneSchema = z.object({
+ sceneId: z.string().min(1).max(64),
+ order: z.number().int().min(0),
+ intent: z.string().min(1).max(1000),
+ prompt: z.string().min(1).max(8000),
+ negativePrompt: z.string().max(8000).optional().default(''),
+ durationSeconds: z.number().min(1).max(10),
+ useContinuationFromPrior: z.boolean().default(false),
+ sourceImageFile: safeBasename.nullable().optional(),
+ // How strongly the source image conditions the i2v render. 1.0 = preserve
+ // source closely; lower values give the model more freedom to drift.
+ // Null lets the runtime pick — `sceneRunner.js` applies 0.85 as the
+ // default for continuation scenes (anchors the next clip to the prior
+ // last-frame so renders don't drift hard), and leaves it null otherwise
+ // (mlx_video / dgrauet uses its own default).
+ imageStrength: z.number().min(0).max(1).nullable().optional(),
+ status: z.enum(SCENE_STATUSES).default('pending'),
+ retryCount: z.number().int().min(0).max(10).default(0),
+ renderedJobId: z.string().max(64).nullable().optional(),
+ evaluation: z.object({
+ score: z.number().min(0).max(1).optional(),
+ notes: z.string().max(2000).optional(),
+ accepted: z.boolean(),
+ sampledAt: z.string().optional(),
+ }).nullable().optional(),
+});
+
+// The full treatment doc the agent writes after the planning task.
+export const creativeDirectorTreatmentSchema = z.object({
+ logline: z.string().min(1).max(500),
+ synopsis: z.string().min(1).max(5000),
+ scenes: z.array(creativeDirectorSceneSchema).min(1).max(120),
+});
+
+// Used by the agent when finishing a scene render.
+export const creativeDirectorSceneUpdateSchema = z.object({
+ // Full SCENE_STATUSES — the evaluator agent flips a scene back to 'pending'
+ // (with an updated prompt + bumped retryCount) to request a re-render; see
+ // creativeDirectorPrompts.js and completionHook.js's advanceAfterSceneSettled.
+ status: z.enum(SCENE_STATUSES).optional(),
+ retryCount: z.number().int().min(0).max(10).optional(),
+ renderedJobId: z.string().max(64).nullable().optional(),
+ prompt: z.string().min(1).max(8000).optional(),
+ // Evaluator may adjust per-scene strength on retry — e.g. drop from
+ // 0.85 → 0.6 when the seed image is too dominant or raise toward 1.0
+ // when continuation drifted.
+ imageStrength: z.number().min(0).max(1).nullable().optional(),
+ evaluation: z.object({
+ score: z.number().min(0).max(1).optional(),
+ notes: z.string().max(2000).optional(),
+ accepted: z.boolean(),
+ sampledAt: z.string().optional(),
+ }).nullable().optional(),
+}).strict();
+
+// ---------------------------------------------------------------------------
+// Create Suite — Importer.
+//
+// The importer takes a finished prose/script source and reverse-engineers
+// universe canon + series arc + issue split. Zod here enforces the wire
+// shape; the heavy validation (entry-level field caps, kind-specific
+// trimming) lives in storyBible.sanitizeBibleList + storyArc.sanitizeArc so
+// commit-side mutations always run through the same sanitizers the rest of
+// the pipeline uses. The canon/arc/issue entries below therefore use
+// `.passthrough()` — we want every field the LLM picked to reach the
+// sanitizer, not get stripped at the schema gate.
+// ---------------------------------------------------------------------------
+
+export const IMPORTER_CONTENT_TYPES = Object.freeze([
+ 'short-story', 'novel', 'screenplay', 'comic-script',
+]);
+
+// Hard ceiling at the schema layer (mirrors writersRoomDraftSaveSchema). The
+// orchestrator's IMPORTER_SOURCE_CHAR_LIMIT matches this 5MB ceiling and
+// returns a friendlier error; the real operational limit is dynamic — the
+// active provider's context window.
+const importerSourceField = z.string().min(1).max(5_000_000);
+
+// Per-issue verbatim-excerpt ceiling (seeds stages.prose / stages.comicScript /
+// stages.teleplay).
+// MUST stay ≤ `STAGE_OUTPUT_MAX` in server/services/pipeline/issues.js (400_000)
+// — createIssue trims stage output to that, so a larger excerpt would be
+// SILENTLY TRUNCATED on commit despite the import being advertised as verbatim.
+// (lib can't import from services; importer.test.js pins the invariant.) Far
+// below importerSourceField's 5MB so a single bundled comic issue can't blow
+// past it silently — analyze validates against this so the failure surfaces at
+// analyze, not as a commit-time truncation/400.
+export const IMPORTER_PROSE_EXCERPT_MAX = 400_000;
+
+// Classify endpoint only sees the source — no universe/series context. The
+// LLM only consumes the head, so the schema is intentionally minimal.
+export const importerClassifySchema = z.object({
+ source: importerSourceField,
+ providerOverride: z.preprocess(emptyToUndefined, z.string().trim().max(120).optional()),
+ // Pinned model id for the chosen provider; '' from the UI ("Default model")
+ // coerces to undefined so runStagedLLM falls back to the stage/provider
+ // default model.
+ modelOverride: z.preprocess(emptyToUndefined, z.string().trim().max(200).optional()),
+}).strict();
+
+export const importerAnalyzeSchema = z.object({
+ universeName: z.string().trim().min(1).max(200),
+ seriesName: z.string().trim().min(1).max(200),
+ contentType: z.enum(IMPORTER_CONTENT_TYPES),
+ source: importerSourceField,
+ // UI sends `''` for "no override picked"; coerce to undefined so the
+ // server's `await getProviderById(undefined)` short-circuit kicks in.
+ providerOverride: z.preprocess(emptyToUndefined, z.string().trim().max(120).optional()),
+ // Pinned model id for the chosen provider; '' from the UI ("Default model")
+ // coerces to undefined so runStagedLLM falls back to the stage/provider
+ // default model.
+ modelOverride: z.preprocess(emptyToUndefined, z.string().trim().max(200).optional()),
+ targetIssueCount: z.number().int().min(1).max(50).optional(),
+}).strict();
+
+// Retry-issues endpoint — re-runs ONLY the issue split after a failed analyze
+// (canon + arc are preserved client-side). No universe/series names needed;
+// `arcSummary` (optional) lets the LLM align issue boundaries to the arc the
+// user already has in the Review panel, and `seriesName` is purely cosmetic
+// prompt context.
+export const importerRetryIssuesSchema = z.object({
+ contentType: z.enum(IMPORTER_CONTENT_TYPES),
+ source: importerSourceField,
+ seriesName: z.string().trim().max(200).optional(),
+ arcSummary: z.string().max(8000).optional(),
+ providerOverride: z.preprocess(emptyToUndefined, z.string().trim().max(120).optional()),
+ modelOverride: z.preprocess(emptyToUndefined, z.string().trim().max(200).optional()),
+ targetIssueCount: z.number().int().min(1).max(50).optional(),
+}).strict();
+
+// Single canon-entry schema — every per-kind sanitizer (character / place /
+// object) only requires a `name`; `.passthrough()` keeps every LLM-emitted
+// field (firstAppearance, slugline, palette, …) for the sanitizer.
+const importerCanonEntry = z.object({
+ name: z.string().trim().min(1).max(BIBLE_LIMITS.NAME_MAX),
+}).passthrough();
+
+// Arc shape — every field optional so a partial preview (user cleared some
+// fields in the Review step) still validates; sanitizeArc fills in the
+// shape-level defaults.
+const importerArcShape = z.object({
+ logline: z.string().max(500).optional(),
+ summary: z.string().max(8000).optional(),
+ protagonistArc: z.string().max(4000).optional(),
+ themes: z.array(z.string().max(100)).max(20).optional(),
+ shape: z.enum(ARC_SHAPE_IDS).optional(),
+}).passthrough();
+
+// Season + issue entries used inside the commit payload. Seasons stay
+// permissive (sanitizer normalizes numbers + ids + status); issues need
+// `title` for createIssue but otherwise let the orchestrator decide.
+const importerSeasonEntry = z.object({
+ number: z.number().int().min(1).max(99).optional(),
+ title: z.string().trim().max(200).optional(),
+ logline: z.string().max(500).optional(),
+ synopsis: z.string().max(4000).optional(),
+ endingHook: z.string().max(1000).optional(),
+ episodeCountTarget: z.number().int().min(0).max(999).optional(),
+}).passthrough();
+
+const importerIssueEntry = z.object({
+ title: z.string().trim().min(1).max(300),
+ // Optional — the service's commitImport auto-assigns the next free
+ // arcPosition when omitted (mirrors the season.number auto-assign).
+ // The wire previously required this, which orphaned the service-side
+ // auto-assign as dead code for HTTP callers; making it optional puts
+ // wire + service on one contract and keeps the auto-assign reachable.
+ arcPosition: z.number().int().min(1).max(9999).optional(),
+ // The LLM may legitimately omit arcRole on a B-plot-light volume; gate
+ // the enum but allow the field to be missing. Wrap with z.preprocess so
+ // an empty string from the UI's "clear" affordance maps to undefined.
+ arcRole: z.preprocess(
+ (v) => (v === '' || v == null ? undefined : v),
+ z.enum(ARC_ROLES).optional(),
+ ),
+ // Season the issue belongs to. Optional — orchestrator picks the first
+ // season when omitted on a multi-season import.
+ seasonNumber: z.number().int().min(1).max(99).optional(),
+ logline: z.string().max(500).optional(),
+ synopsis: z.string().max(4000).optional(),
+ // 500K cap matches the issue's stages.prose.output limit so a long
+ // novel chapter can land verbatim. Optional — the LLM may omit the
+ // excerpt on some issues. When present, must be non-empty + non-whitespace
+ // so it doesn't seed prose.output with whitespace and mark the stage
+ // `ready` misleadingly. Exported so the mechanical comic splitter can
+ // validate against the SAME ceiling at analyze time (a verbatim split could
+ // otherwise produce an excerpt commit would reject — a confusing dead-end).
+ proseExcerpt: z.string().min(1).max(IMPORTER_PROSE_EXCERPT_MAX).refine(
+ (s) => s.trim().length > 0,
+ { message: 'proseExcerpt must contain non-whitespace content' },
+ ).optional(),
+}).passthrough();
+
+export const importerCommitSchema = z.object({
+ universeId: z.string().trim().min(1).max(120),
+ seriesId: z.string().trim().min(1).max(120),
+ canonSelections: z.object({
+ characters: z.array(importerCanonEntry).max(BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX).default([]),
+ places: z.array(importerCanonEntry).max(BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX).default([]),
+ objects: z.array(importerCanonEntry).max(BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX).default([]),
+ }).default({ characters: [], places: [], objects: [] }),
+ arc: importerArcShape.nullable().optional(),
+ seasons: z.array(importerSeasonEntry).max(50).default([]),
+ issues: z.array(importerIssueEntry).min(1).max(50),
+ // Drives which stage each issue's verbatim excerpt seeds: a script-form
+ // import seeds its matching script stage (ready) and the pipeline never
+ // regenerates — `comic-script` → `stages.comicScript`, `screenplay` →
+ // `stages.teleplay`; prose-like types seed `stages.prose`. Optional +
+ // defaulting to prose-seed keeps older clients (which don't send it) on the
+ // prior behavior.
+ contentType: z.enum(IMPORTER_CONTENT_TYPES).optional(),
+ // Replace-mode flag — when true, every existing issue on the series is
+ // deleted before the incoming `issues` are created, and `series.arc` +
+ // `series.seasons[]` are written verbatim (not merged). Canon is still
+ // merged additively even in replace mode — universe canon is shared
+ // across series, so a per-series destructive replace would be wrong.
+ // Defaults to false to preserve the additive merge behavior.
+ replaceMode: z.boolean().optional().default(false),
+}).strict();
+
diff --git a/server/lib/index.js b/server/lib/index.js
index f6fc2915a6..13bda9da13 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -19,14 +19,17 @@
export * as appleHealthValidation from './appleHealthValidation.js';
export * as brainValidation from './brainValidation.js';
export * as catalogValidation from './catalogValidation.js';
+export * as creativeDirectorValidation from './creativeDirectorValidation.js';
export * as digitalTwinValidation from './digitalTwinValidation.js';
export * as genomeValidation from './genomeValidation.js';
export * as identityValidation from './identityValidation.js';
export * as meatspaceValidation from './meatspaceValidation.js';
export * as memoryValidation from './memoryValidation.js';
export * as notesValidation from './notesValidation.js';
+export * as peerSyncValidation from './peerSyncValidation.js';
export * as postValidation from './postValidation.js';
export * as socketValidation from './socketValidation.js';
+export * as storyBuilderValidation from './storyBuilderValidation.js';
export * as telegramValidation from './telegramValidation.js';
export * from './validation.js';
diff --git a/server/lib/peerSyncValidation.js b/server/lib/peerSyncValidation.js
new file mode 100644
index 0000000000..9da7888a6f
--- /dev/null
+++ b/server/lib/peerSyncValidation.js
@@ -0,0 +1,172 @@
+import { z } from 'zod';
+import { catalogSyncIngredientSchema, catalogSyncRefSchema } from './catalogValidation.js';
+
+// =============================================================================
+// PEER SYNC SCHEMAS
+// =============================================================================
+// Wire/request schemas for federated peer-to-peer record sync (see
+// server/services/sharing/peerSync.js). Split out of validation.js
+// (issue #1151); validation.js re-exports everything here so existing deep
+// imports keep working.
+
+// Subscribe a record (universe / series) to a federated peer for live push.
+// Sibling of share-bucket subscriptionCreateSchema; the difference is the
+// destination — share-bucket subscriptions hit a cloud-synced folder, peer
+// subscriptions target another PortOS instance over Tailnet.
+export const peerSubscribeSchema = z.object({
+ peerId: z.string().trim().min(1).max(120),
+ recordKind: z.enum(['universe', 'series', 'mediaCollection']),
+ recordId: z.string().trim().min(1).max(120),
+}).strict();
+
+// Asset manifest entry the receiver gets in a push payload. Filename gets a
+// second-pass scrub against path separators inside the service layer; this
+// schema just constrains shape + caps so a malformed manifest doesn't bypass
+// validation entirely. SHA-256 is hex-64 when present.
+//
+// Discriminated on `kind` because `sidecarSha256` (the gen-params sidecar hash)
+// is ONLY meaningful for images — image-ref/video entries carry no sidecar, so
+// `.strict()` on the non-image branch rejects a stray `sidecarSha256` instead
+// of silently accepting a malformed sender payload.
+const hex64 = z.string().regex(/^[a-f0-9]{64}$/i);
+const peerAssetManifestEntrySchema = z.discriminatedUnion('kind', [
+ z.object({
+ filename: z.string().trim().min(1).max(255),
+ kind: z.literal('image'),
+ sha256: hex64.optional(),
+ sidecarSha256: hex64.optional(),
+ }).strict(),
+ z.object({
+ filename: z.string().trim().min(1).max(255),
+ kind: z.enum(['image-ref', 'video']),
+ sha256: hex64.optional(),
+ }).strict(),
+]);
+
+// One sanitized record on the wire. Mirrors sanitizeRecordForWire's output:
+// id is required, soft-delete fields are tail-canonical, and the receiver's
+// merge*FromSync paths handle everything else by shape. We don't `.strict()`
+// because record shapes vary across kinds (universe vs series vs issue) and
+// adding new fields shouldn't require a schema bump for every PR.
+const peerWireRecordSchema = z.object({
+ id: z.string().trim().min(1).max(120),
+}).passthrough();
+
+// Push payload from a sender. Modeled as a discriminated union on `kind` so
+// only series payloads can carry `issues[]` — without the discrimination, an
+// adversarial peer could send `kind: 'universe'` with a 100k-entry `issues`
+// array and force the receiver to iterate it through `computeAckedDeletesFromPayload`
+// and the sanitizers. The series branch caps issues at 1000 (well above any
+// realistic series — most cap out at a few dozen) so neither branch is
+// unbounded. `sourceInstanceId` is required + must be a real instance id
+// (the receiver rejects "unknown" at the service layer; here we just enforce
+// non-empty + length cap).
+// `portosMeta` envelope — every outbound payload built by `buildPushPayload`
+// stamps the sender's PortOS version + schemaVersions map so the receiver
+// can detect a version mismatch before applying the record. Optional on
+// the wire so legacy peers (no portosMeta) still validate; the receiver's
+// version-gate treats absent meta as "no contract" and falls through to
+// the existing merge path.
+//
+// CRITICAL: uses `.passthrough()` (not `.strict()`). The whole point of
+// the envelope is to enable graceful version negotiation. If a future
+// PortOS adds a new field to `portosMeta` (e.g. `clientName`,
+// `capabilities`, `regionCode`), `.strict()` would 400-reject every push
+// from that version at Zod validation BEFORE the receiver's schema-version
+// gate runs — surfacing as a generic 400 with no `blockedBySchema`
+// persistence, no cooldown, no SchemaGapBadge surfacing. `.passthrough()`
+// lets unknown fields flow through to the gate, which is the actual
+// compat decision point.
+const portosMetaSchema = z.object({
+ portosVersion: z.string().trim().min(1).max(40).optional(),
+ schemaVersions: z.record(z.string().min(1).max(60), z.number().int().min(0).max(1_000_000)).optional(),
+}).passthrough().optional();
+const peerSyncPushBase = {
+ record: peerWireRecordSchema,
+ assetManifest: z.array(peerAssetManifestEntrySchema).max(2000),
+ sourceInstanceId: z.string().trim().min(1).max(120),
+ portosMeta: portosMetaSchema,
+};
+// Optional bundled media collection — Stage 5 media-collections sync attaches
+// the universe / series's linked collection so collection-only edits propagate
+// via the per-record push pipeline. Same shape as a record on the wire (id
+// required, sanitizer handles the rest). ONLY valid on universe/series pushes:
+// a mediaCollection push IS the collection, so accepting linkedCollection there
+// would let a sender smuggle an arbitrary EXTRA collection that the receiver's
+// applyIncomingPush merges — a side-channel to overwrite collections outside the
+// explicit per-record subscription. The mediaCollection branch's .strict()
+// therefore rejects it. See peerSync.js buildPushPayload (never sets it for the
+// mediaCollection kind) and applyIncomingPush.
+const linkedCollectionField = { linkedCollection: peerWireRecordSchema.optional() };
+// Optional bundled catalog rows — a universe push carries the catalog
+// ingredients + universe→ingredient ref links referenced by its embedded
+// canon, so the receiver gets the enriched catalog row (tags, embedding,
+// payload.summary) instead of re-deriving a lossy view. Same wire shapes as
+// the direct catalog-sync envelope. ONLY valid on universe pushes (series /
+// mediaCollection .strict() reject it) — series catalog refs ride their own
+// catalog-sync category; smuggling them here would be a side-channel.
+const catalogBundleField = {
+ catalogBundle: z.object({
+ ingredients: z.array(catalogSyncIngredientSchema).max(5_000).optional(),
+ refs: z.array(catalogSyncRefSchema).max(20_000).optional(),
+ }).strict().optional(),
+};
+const universePushSchema = z.object({
+ kind: z.literal('universe'),
+ ...peerSyncPushBase,
+ ...linkedCollectionField,
+ ...catalogBundleField,
+}).strict();
+// Optional bundled manuscript-review sibling doc — a series push carries the
+// "Finish the draft" comment set (data/pipeline-series/{id}/manuscript-review.json)
+// so review-only edits propagate via the per-record push pipeline. ONLY valid on
+// series pushes. `.passthrough()` on the review + each comment (same rationale as
+// portosMeta) so a newer sender that adds a comment field doesn't 400 at this
+// receiver BEFORE its merge — `sanitizeReview` clamps/drops everything on apply.
+// Comments are bounded (5000) so the array can't be used to force unbounded work.
+const manuscriptReviewField = {
+ manuscriptReview: z.object({
+ schemaVersion: z.number().int().min(0).max(1_000_000).optional(),
+ comments: z.array(z.object({
+ id: z.string().trim().min(1).max(120),
+ }).passthrough()).max(5000),
+ }).passthrough().optional(),
+};
+const seriesPushSchema = z.object({
+ kind: z.literal('series'),
+ ...peerSyncPushBase,
+ ...linkedCollectionField,
+ ...manuscriptReviewField,
+ issues: z.array(peerWireRecordSchema).max(1000).optional(),
+}).strict();
+const mediaCollectionPushSchema = z.object({
+ kind: z.literal('mediaCollection'),
+ ...peerSyncPushBase,
+}).strict();
+export const peerSyncPushSchema = z.discriminatedUnion('kind', [
+ universePushSchema,
+ seriesPushSchema,
+ mediaCollectionPushSchema,
+]);
+
+// Manual sync action schemas — used by POST /sync-record, /sync-now, /pull-metadata.
+
+export const peerSyncRecordSchema = z.object({
+ peerId: z.string().trim().min(1).max(120),
+ recordKind: z.enum(['universe', 'series', 'mediaCollection']),
+ recordId: z.string().trim().min(1).max(200),
+}).strict();
+
+export const peerSyncNowSchema = z.object({
+ peerId: z.string().trim().min(1).max(120),
+}).strict();
+
+export const peerPullMetadataSchema = z.object({
+ // Backfill tries every online peer; no per-peer scoping field today.
+ // .trim() so a stray-whitespace filename (' a.png ') normalizes to the real
+ // name instead of passing validation and then failing sanitization/disk
+ // lookup (a confusing 200 with attempted>0, recovered=0). Matches the
+ // manifest-entry filename handling.
+ filenames: z.array(z.string().trim().min(1).max(300)).max(5000),
+}).strict();
+
diff --git a/server/lib/storyBuilderValidation.js b/server/lib/storyBuilderValidation.js
new file mode 100644
index 0000000000..72e57d2810
--- /dev/null
+++ b/server/lib/storyBuilderValidation.js
@@ -0,0 +1,78 @@
+import { z } from 'zod';
+import { STEP_IDS as STORY_STEP_IDS } from './storyBuilderSteps.js';
+import { emptyToUndefined } from './zodCompat.js';
+
+// =============================================================================
+// UNIFIED STORY BUILDER SCHEMAS
+// =============================================================================
+// Split out of validation.js (issue #1151); validation.js re-exports
+// everything here so existing deep imports keep working. The import from
+// zodCompat.js (not validation.js) supplies emptyToUndefined — see
+// creativeDirectorValidation.js for the cycle rationale.
+
+const storyProviderField = z.preprocess(emptyToUndefined, z.string().trim().max(120).optional());
+const storyModelField = z.preprocess(emptyToUndefined, z.string().trim().max(200).optional());
+
+export const storySessionCreateSchema = z.object({
+ title: z.string().trim().min(1).max(200),
+ intakeMode: z.enum(['seed', 'import']).optional().default('seed'),
+ seedIdea: z.string().trim().max(4000).optional().default(''),
+ // Import mode supplies pre-created ids; seed mode mints shells server-side.
+ universeId: z.preprocess(emptyToUndefined, z.string().trim().max(64).optional()),
+ seriesId: z.preprocess(emptyToUndefined, z.string().trim().max(64).optional()),
+ // Picker choice that drives every Story Builder operation; nullable so the
+ // UI can send "use the stage default" explicitly.
+ llm: z.object({
+ provider: z.string().trim().max(80).nullable().optional(),
+ model: z.string().trim().max(200).nullable().optional(),
+ }).optional(),
+}).strict();
+
+export const storySessionUpdateSchema = z.object({
+ title: z.string().trim().min(1).max(200).optional(),
+ seedIdea: z.string().trim().max(4000).optional(),
+ // Reject removed/unknown step ids loudly — the sanitizer would otherwise
+ // silently coerce them to STEP_IDS[0], landing a stale client on the first
+ // step with no error.
+ currentStep: z.enum(STORY_STEP_IDS).optional(),
+ llm: z.object({
+ provider: z.string().trim().max(80).nullable().optional(),
+ model: z.string().trim().max(200).nullable().optional(),
+ }).optional(),
+}).strict();
+
+// Cross-machine resume opt-in toggle (#730). Sessions are local-only by
+// default; flipping this on snapshots a staleness baseline that travels with
+// the session so a peer's universe edit can't false-positive-stale it.
+export const storySessionSyncSchema = z.object({
+ sync: z.boolean(),
+}).strict();
+
+export const storyStepGenerateSchema = z.object({
+ providerId: storyProviderField,
+ model: storyModelField,
+ // Backfill toggle: synthesize this (upstream) step from the series' existing
+ // downstream issue content instead of its conventional upstream. Honored by
+ // the idea + plotArc generators (see services/storyBuilder.js generateStep).
+ fromDownstream: z.boolean().optional(),
+}).strict();
+
+export const storyStepRefineSchema = z.object({
+ feedback: z.string().trim().max(4000).optional().default(''),
+ // For per-entry refine (e.g. a single character on the characters step).
+ entryId: z.preprocess(emptyToUndefined, z.string().trim().max(64).optional()),
+ providerId: storyProviderField,
+ model: storyModelField,
+}).strict();
+
+export const storyIssueLockSchema = z.object({
+ locked: z.boolean(),
+}).strict();
+
+export const storyIssuesGenerateSchema = z.object({
+ providerId: storyProviderField,
+ model: storyModelField,
+ // Optional: scope generation to a single season; omit to cover every season
+ // on the arc.
+ seasonId: z.preprocess(emptyToUndefined, z.string().trim().max(64).optional()),
+}).strict();
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 63ec67bf73..cefe27829d 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1,13 +1,9 @@
import { z } from 'zod';
import { ServerError } from './errorHandler.js';
-import { partialWithoutDefaults } from './zodCompat.js';
-import { ASPECT_RATIOS, QUALITIES, PROJECT_STATUSES, SCENE_STATUSES } from './creativeDirectorPresets.js';
+import { partialWithoutDefaults, emptyToUndefined } from './zodCompat.js';
import { WORK_KINDS, WORK_STATUSES, ANALYSIS_KINDS } from './writersRoomPresets.js';
import { ALL_STYLE_IDS, STYLE_ID } from './writersRoomStylePresets.js';
import { BIBLE_LIMITS } from './storyBible.js';
-import { ARC_SHAPE_IDS, ARC_ROLES } from './storyArc.js';
-import { STEP_IDS as STORY_STEP_IDS } from './storyBuilderSteps.js';
-import { catalogSyncIngredientSchema, catalogSyncRefSchema } from './catalogValidation.js';
import { MIN_TIMEOUT as STAGE_TIMEOUT_MIN_MS, MAX_TIMEOUT as STAGE_TIMEOUT_MAX_MS } from './aiToolkit/constants.js';
// gpt-image-2 (codex backend) caps at 3840px per edge and 8,294,400 total
@@ -839,7 +835,9 @@ export const citySnapshotsQuerySchema = z.object({
// as "use the default" rather than a bogus id. Both the autofixer (file edits
// + pm2) and Google Calendar MCP sync require an agentic CLI provider; the
// picker resolution layer (`pickCliProvider`) enforces type 'cli'.
-export const emptyToUndefined = (v) => (v === '' ? undefined : v);
+// `emptyToUndefined` now lives in zodCompat.js (so per-domain schema files can
+// use it without a cycle through this module) — re-exported for deep imports.
+export { emptyToUndefined };
export const featureProviderConfigSchema = z.object({
providerId: z.preprocess(emptyToUndefined, z.string().optional()),
model: z.preprocess(emptyToUndefined, z.string().optional()),
@@ -1546,458 +1544,6 @@ export const subscriptionCreateSchema = z.object({
recordId: z.string().trim().min(1).max(120),
}).strict();
-// =============================================================================
-// PEER SYNC SCHEMAS
-// =============================================================================
-
-// Subscribe a record (universe / series) to a federated peer for live push.
-// Sibling of share-bucket subscriptionCreateSchema; the difference is the
-// destination — share-bucket subscriptions hit a cloud-synced folder, peer
-// subscriptions target another PortOS instance over Tailnet.
-export const peerSubscribeSchema = z.object({
- peerId: z.string().trim().min(1).max(120),
- recordKind: z.enum(['universe', 'series', 'mediaCollection']),
- recordId: z.string().trim().min(1).max(120),
-}).strict();
-
-// Asset manifest entry the receiver gets in a push payload. Filename gets a
-// second-pass scrub against path separators inside the service layer; this
-// schema just constrains shape + caps so a malformed manifest doesn't bypass
-// validation entirely. SHA-256 is hex-64 when present.
-//
-// Discriminated on `kind` because `sidecarSha256` (the gen-params sidecar hash)
-// is ONLY meaningful for images — image-ref/video entries carry no sidecar, so
-// `.strict()` on the non-image branch rejects a stray `sidecarSha256` instead
-// of silently accepting a malformed sender payload.
-const hex64 = z.string().regex(/^[a-f0-9]{64}$/i);
-const peerAssetManifestEntrySchema = z.discriminatedUnion('kind', [
- z.object({
- filename: z.string().trim().min(1).max(255),
- kind: z.literal('image'),
- sha256: hex64.optional(),
- sidecarSha256: hex64.optional(),
- }).strict(),
- z.object({
- filename: z.string().trim().min(1).max(255),
- kind: z.enum(['image-ref', 'video']),
- sha256: hex64.optional(),
- }).strict(),
-]);
-
-// One sanitized record on the wire. Mirrors sanitizeRecordForWire's output:
-// id is required, soft-delete fields are tail-canonical, and the receiver's
-// merge*FromSync paths handle everything else by shape. We don't `.strict()`
-// because record shapes vary across kinds (universe vs series vs issue) and
-// adding new fields shouldn't require a schema bump for every PR.
-const peerWireRecordSchema = z.object({
- id: z.string().trim().min(1).max(120),
-}).passthrough();
-
-// Push payload from a sender. Modeled as a discriminated union on `kind` so
-// only series payloads can carry `issues[]` — without the discrimination, an
-// adversarial peer could send `kind: 'universe'` with a 100k-entry `issues`
-// array and force the receiver to iterate it through `computeAckedDeletesFromPayload`
-// and the sanitizers. The series branch caps issues at 1000 (well above any
-// realistic series — most cap out at a few dozen) so neither branch is
-// unbounded. `sourceInstanceId` is required + must be a real instance id
-// (the receiver rejects "unknown" at the service layer; here we just enforce
-// non-empty + length cap).
-// `portosMeta` envelope — every outbound payload built by `buildPushPayload`
-// stamps the sender's PortOS version + schemaVersions map so the receiver
-// can detect a version mismatch before applying the record. Optional on
-// the wire so legacy peers (no portosMeta) still validate; the receiver's
-// version-gate treats absent meta as "no contract" and falls through to
-// the existing merge path.
-//
-// CRITICAL: uses `.passthrough()` (not `.strict()`). The whole point of
-// the envelope is to enable graceful version negotiation. If a future
-// PortOS adds a new field to `portosMeta` (e.g. `clientName`,
-// `capabilities`, `regionCode`), `.strict()` would 400-reject every push
-// from that version at Zod validation BEFORE the receiver's schema-version
-// gate runs — surfacing as a generic 400 with no `blockedBySchema`
-// persistence, no cooldown, no SchemaGapBadge surfacing. `.passthrough()`
-// lets unknown fields flow through to the gate, which is the actual
-// compat decision point.
-const portosMetaSchema = z.object({
- portosVersion: z.string().trim().min(1).max(40).optional(),
- schemaVersions: z.record(z.string().min(1).max(60), z.number().int().min(0).max(1_000_000)).optional(),
-}).passthrough().optional();
-const peerSyncPushBase = {
- record: peerWireRecordSchema,
- assetManifest: z.array(peerAssetManifestEntrySchema).max(2000),
- sourceInstanceId: z.string().trim().min(1).max(120),
- portosMeta: portosMetaSchema,
-};
-// Optional bundled media collection — Stage 5 media-collections sync attaches
-// the universe / series's linked collection so collection-only edits propagate
-// via the per-record push pipeline. Same shape as a record on the wire (id
-// required, sanitizer handles the rest). ONLY valid on universe/series pushes:
-// a mediaCollection push IS the collection, so accepting linkedCollection there
-// would let a sender smuggle an arbitrary EXTRA collection that the receiver's
-// applyIncomingPush merges — a side-channel to overwrite collections outside the
-// explicit per-record subscription. The mediaCollection branch's .strict()
-// therefore rejects it. See peerSync.js buildPushPayload (never sets it for the
-// mediaCollection kind) and applyIncomingPush.
-const linkedCollectionField = { linkedCollection: peerWireRecordSchema.optional() };
-// Optional bundled catalog rows — a universe push carries the catalog
-// ingredients + universe→ingredient ref links referenced by its embedded
-// canon, so the receiver gets the enriched catalog row (tags, embedding,
-// payload.summary) instead of re-deriving a lossy view. Same wire shapes as
-// the direct catalog-sync envelope. ONLY valid on universe pushes (series /
-// mediaCollection .strict() reject it) — series catalog refs ride their own
-// catalog-sync category; smuggling them here would be a side-channel.
-const catalogBundleField = {
- catalogBundle: z.object({
- ingredients: z.array(catalogSyncIngredientSchema).max(5_000).optional(),
- refs: z.array(catalogSyncRefSchema).max(20_000).optional(),
- }).strict().optional(),
-};
-const universePushSchema = z.object({
- kind: z.literal('universe'),
- ...peerSyncPushBase,
- ...linkedCollectionField,
- ...catalogBundleField,
-}).strict();
-// Optional bundled manuscript-review sibling doc — a series push carries the
-// "Finish the draft" comment set (data/pipeline-series/{id}/manuscript-review.json)
-// so review-only edits propagate via the per-record push pipeline. ONLY valid on
-// series pushes. `.passthrough()` on the review + each comment (same rationale as
-// portosMeta) so a newer sender that adds a comment field doesn't 400 at this
-// receiver BEFORE its merge — `sanitizeReview` clamps/drops everything on apply.
-// Comments are bounded (5000) so the array can't be used to force unbounded work.
-const manuscriptReviewField = {
- manuscriptReview: z.object({
- schemaVersion: z.number().int().min(0).max(1_000_000).optional(),
- comments: z.array(z.object({
- id: z.string().trim().min(1).max(120),
- }).passthrough()).max(5000),
- }).passthrough().optional(),
-};
-const seriesPushSchema = z.object({
- kind: z.literal('series'),
- ...peerSyncPushBase,
- ...linkedCollectionField,
- ...manuscriptReviewField,
- issues: z.array(peerWireRecordSchema).max(1000).optional(),
-}).strict();
-const mediaCollectionPushSchema = z.object({
- kind: z.literal('mediaCollection'),
- ...peerSyncPushBase,
-}).strict();
-export const peerSyncPushSchema = z.discriminatedUnion('kind', [
- universePushSchema,
- seriesPushSchema,
- mediaCollectionPushSchema,
-]);
-
-// Manual sync action schemas — used by POST /sync-record, /sync-now, /pull-metadata.
-
-export const peerSyncRecordSchema = z.object({
- peerId: z.string().trim().min(1).max(120),
- recordKind: z.enum(['universe', 'series', 'mediaCollection']),
- recordId: z.string().trim().min(1).max(200),
-}).strict();
-
-export const peerSyncNowSchema = z.object({
- peerId: z.string().trim().min(1).max(120),
-}).strict();
-
-export const peerPullMetadataSchema = z.object({
- // Backfill tries every online peer; no per-peer scoping field today.
- // .trim() so a stray-whitespace filename (' a.png ') normalizes to the real
- // name instead of passing validation and then failing sanitization/disk
- // lookup (a confusing 200 with attempted>0, recovered=0). Matches the
- // manifest-entry filename handling.
- filenames: z.array(z.string().trim().min(1).max(300)).max(5000),
-}).strict();
-
-// =============================================================================
-// CREATIVE DIRECTOR SCHEMAS
-// =============================================================================
-
-export const creativeDirectorAspectRatioSchema = z.enum(ASPECT_RATIOS);
-export const creativeDirectorQualitySchema = z.enum(QUALITIES);
-
-// Top-level project create. modelId is required because each LTX variant
-// has a different speed/VRAM/quality profile and the project locks it at
-// creation. targetDurationSeconds is capped at 600 (10 min) per the v1 plan
-// — much beyond that and the agent's treatment quality drifts hard.
-// Strict basename: rejects path separators and the exact `.`/`..` segments.
-// Used for both startingImageFile (project create) and sourceImageFile
-// (per-scene) since both feed into `join(PATHS.images, ...)` later. The
-// downstream consumers also do a resolve+prefix-check against PATHS.images
-// (sceneRunner.js) — that's the real traversal guard; this validator just
-// catches the obvious bad values at the route boundary. Note: a substring
-// check on `..` would over-reject legitimate names like `my..image.png`,
-// so we only reject the exact dot segments and rely on prefix-checks for
-// the actual escape protection.
-const safeBasename = z.string()
- .max(256)
- .regex(/^[^/\\]+$/, 'must be a basename (no path separators)')
- .refine((v) => v !== '.' && v !== '..',
- 'must not be `.` or `..`');
-
-export const creativeDirectorProjectCreateSchema = z.object({
- name: z.string().min(1).max(200),
- aspectRatio: creativeDirectorAspectRatioSchema,
- quality: creativeDirectorQualitySchema,
- modelId: z.string().min(1).max(64),
- targetDurationSeconds: z.number().int().min(5).max(600),
- styleSpec: z.string().max(5000).default(''),
- startingImageFile: safeBasename.nullable().optional(),
- userStory: z.string().max(10000).nullable().optional(),
- // Audio defaults OFF for CD projects — current model audio output is
- // inconsistent across renders and the user can re-enable per-project.
- // (videoGen one-offs still default to enabled.)
- disableAudio: z.boolean().optional().default(true),
- autoAcceptScenes: z.boolean().optional().default(false),
- // Optional back-pointer to the pipeline issue that spawned this project,
- // used by the stitch step to mix in audio-stage music. Bare CD projects
- // (no pipeline origin) leave this null.
- sourceIssueId: z.string().min(1).max(64).nullable().optional(),
-});
-
-// Update is restricted to a few editable fields. modelId / aspectRatio /
-// quality / targetDurationSeconds are locked at creation — changing them
-// mid-project would invalidate already-rendered segments.
-//
-// Server-managed fields (timelineProjectId, runs, treatment) are
-// intentionally NOT in this schema. timelineProjectId is set only by
-// stitchRunner.js — accepting it in PATCH payloads would let a client
-// point a CD project at an unrelated user timeline project, which the
-// next stitch would silently overwrite via updateTimelineProject.
-export const creativeDirectorProjectUpdateSchema = z.object({
- name: z.string().min(1).max(200).optional(),
- styleSpec: z.string().max(5000).optional(),
- userStory: z.string().max(10000).nullable().optional(),
- status: z.enum(PROJECT_STATUSES).optional(),
- finalVideoId: z.string().max(64).nullable().optional(),
- failureReason: z.string().max(500).nullable().optional(),
- // Toggleable post-creation — only affects future scene renders.
- disableAudio: z.boolean().optional(),
-}).strict();
-
-// One scene in the treatment, written by the agent on the treatment task.
-export const creativeDirectorSceneSchema = z.object({
- sceneId: z.string().min(1).max(64),
- order: z.number().int().min(0),
- intent: z.string().min(1).max(1000),
- prompt: z.string().min(1).max(8000),
- negativePrompt: z.string().max(8000).optional().default(''),
- durationSeconds: z.number().min(1).max(10),
- useContinuationFromPrior: z.boolean().default(false),
- sourceImageFile: safeBasename.nullable().optional(),
- // How strongly the source image conditions the i2v render. 1.0 = preserve
- // source closely; lower values give the model more freedom to drift.
- // Null lets the runtime pick — `sceneRunner.js` applies 0.85 as the
- // default for continuation scenes (anchors the next clip to the prior
- // last-frame so renders don't drift hard), and leaves it null otherwise
- // (mlx_video / dgrauet uses its own default).
- imageStrength: z.number().min(0).max(1).nullable().optional(),
- status: z.enum(SCENE_STATUSES).default('pending'),
- retryCount: z.number().int().min(0).max(10).default(0),
- renderedJobId: z.string().max(64).nullable().optional(),
- evaluation: z.object({
- score: z.number().min(0).max(1).optional(),
- notes: z.string().max(2000).optional(),
- accepted: z.boolean(),
- sampledAt: z.string().optional(),
- }).nullable().optional(),
-});
-
-// The full treatment doc the agent writes after the planning task.
-export const creativeDirectorTreatmentSchema = z.object({
- logline: z.string().min(1).max(500),
- synopsis: z.string().min(1).max(5000),
- scenes: z.array(creativeDirectorSceneSchema).min(1).max(120),
-});
-
-// Used by the agent when finishing a scene render.
-export const creativeDirectorSceneUpdateSchema = z.object({
- // Full SCENE_STATUSES — the evaluator agent flips a scene back to 'pending'
- // (with an updated prompt + bumped retryCount) to request a re-render; see
- // creativeDirectorPrompts.js and completionHook.js's advanceAfterSceneSettled.
- status: z.enum(SCENE_STATUSES).optional(),
- retryCount: z.number().int().min(0).max(10).optional(),
- renderedJobId: z.string().max(64).nullable().optional(),
- prompt: z.string().min(1).max(8000).optional(),
- // Evaluator may adjust per-scene strength on retry — e.g. drop from
- // 0.85 → 0.6 when the seed image is too dominant or raise toward 1.0
- // when continuation drifted.
- imageStrength: z.number().min(0).max(1).nullable().optional(),
- evaluation: z.object({
- score: z.number().min(0).max(1).optional(),
- notes: z.string().max(2000).optional(),
- accepted: z.boolean(),
- sampledAt: z.string().optional(),
- }).nullable().optional(),
-}).strict();
-
-// ---------------------------------------------------------------------------
-// Create Suite — Importer.
-//
-// The importer takes a finished prose/script source and reverse-engineers
-// universe canon + series arc + issue split. Zod here enforces the wire
-// shape; the heavy validation (entry-level field caps, kind-specific
-// trimming) lives in storyBible.sanitizeBibleList + storyArc.sanitizeArc so
-// commit-side mutations always run through the same sanitizers the rest of
-// the pipeline uses. The canon/arc/issue entries below therefore use
-// `.passthrough()` — we want every field the LLM picked to reach the
-// sanitizer, not get stripped at the schema gate.
-// ---------------------------------------------------------------------------
-
-export const IMPORTER_CONTENT_TYPES = Object.freeze([
- 'short-story', 'novel', 'screenplay', 'comic-script',
-]);
-
-// Hard ceiling at the schema layer (mirrors writersRoomDraftSaveSchema). The
-// orchestrator's IMPORTER_SOURCE_CHAR_LIMIT matches this 5MB ceiling and
-// returns a friendlier error; the real operational limit is dynamic — the
-// active provider's context window.
-const importerSourceField = z.string().min(1).max(5_000_000);
-
-// Per-issue verbatim-excerpt ceiling (seeds stages.prose / stages.comicScript /
-// stages.teleplay).
-// MUST stay ≤ `STAGE_OUTPUT_MAX` in server/services/pipeline/issues.js (400_000)
-// — createIssue trims stage output to that, so a larger excerpt would be
-// SILENTLY TRUNCATED on commit despite the import being advertised as verbatim.
-// (lib can't import from services; importer.test.js pins the invariant.) Far
-// below importerSourceField's 5MB so a single bundled comic issue can't blow
-// past it silently — analyze validates against this so the failure surfaces at
-// analyze, not as a commit-time truncation/400.
-export const IMPORTER_PROSE_EXCERPT_MAX = 400_000;
-
-// Classify endpoint only sees the source — no universe/series context. The
-// LLM only consumes the head, so the schema is intentionally minimal.
-export const importerClassifySchema = z.object({
- source: importerSourceField,
- providerOverride: z.preprocess(emptyToUndefined, z.string().trim().max(120).optional()),
- // Pinned model id for the chosen provider; '' from the UI ("Default model")
- // coerces to undefined so runStagedLLM falls back to the stage/provider
- // default model.
- modelOverride: z.preprocess(emptyToUndefined, z.string().trim().max(200).optional()),
-}).strict();
-
-export const importerAnalyzeSchema = z.object({
- universeName: z.string().trim().min(1).max(200),
- seriesName: z.string().trim().min(1).max(200),
- contentType: z.enum(IMPORTER_CONTENT_TYPES),
- source: importerSourceField,
- // UI sends `''` for "no override picked"; coerce to undefined so the
- // server's `await getProviderById(undefined)` short-circuit kicks in.
- providerOverride: z.preprocess(emptyToUndefined, z.string().trim().max(120).optional()),
- // Pinned model id for the chosen provider; '' from the UI ("Default model")
- // coerces to undefined so runStagedLLM falls back to the stage/provider
- // default model.
- modelOverride: z.preprocess(emptyToUndefined, z.string().trim().max(200).optional()),
- targetIssueCount: z.number().int().min(1).max(50).optional(),
-}).strict();
-
-// Retry-issues endpoint — re-runs ONLY the issue split after a failed analyze
-// (canon + arc are preserved client-side). No universe/series names needed;
-// `arcSummary` (optional) lets the LLM align issue boundaries to the arc the
-// user already has in the Review panel, and `seriesName` is purely cosmetic
-// prompt context.
-export const importerRetryIssuesSchema = z.object({
- contentType: z.enum(IMPORTER_CONTENT_TYPES),
- source: importerSourceField,
- seriesName: z.string().trim().max(200).optional(),
- arcSummary: z.string().max(8000).optional(),
- providerOverride: z.preprocess(emptyToUndefined, z.string().trim().max(120).optional()),
- modelOverride: z.preprocess(emptyToUndefined, z.string().trim().max(200).optional()),
- targetIssueCount: z.number().int().min(1).max(50).optional(),
-}).strict();
-
-// Single canon-entry schema — every per-kind sanitizer (character / place /
-// object) only requires a `name`; `.passthrough()` keeps every LLM-emitted
-// field (firstAppearance, slugline, palette, …) for the sanitizer.
-const importerCanonEntry = z.object({
- name: z.string().trim().min(1).max(BIBLE_LIMITS.NAME_MAX),
-}).passthrough();
-
-// Arc shape — every field optional so a partial preview (user cleared some
-// fields in the Review step) still validates; sanitizeArc fills in the
-// shape-level defaults.
-const importerArcShape = z.object({
- logline: z.string().max(500).optional(),
- summary: z.string().max(8000).optional(),
- protagonistArc: z.string().max(4000).optional(),
- themes: z.array(z.string().max(100)).max(20).optional(),
- shape: z.enum(ARC_SHAPE_IDS).optional(),
-}).passthrough();
-
-// Season + issue entries used inside the commit payload. Seasons stay
-// permissive (sanitizer normalizes numbers + ids + status); issues need
-// `title` for createIssue but otherwise let the orchestrator decide.
-const importerSeasonEntry = z.object({
- number: z.number().int().min(1).max(99).optional(),
- title: z.string().trim().max(200).optional(),
- logline: z.string().max(500).optional(),
- synopsis: z.string().max(4000).optional(),
- endingHook: z.string().max(1000).optional(),
- episodeCountTarget: z.number().int().min(0).max(999).optional(),
-}).passthrough();
-
-const importerIssueEntry = z.object({
- title: z.string().trim().min(1).max(300),
- // Optional — the service's commitImport auto-assigns the next free
- // arcPosition when omitted (mirrors the season.number auto-assign).
- // The wire previously required this, which orphaned the service-side
- // auto-assign as dead code for HTTP callers; making it optional puts
- // wire + service on one contract and keeps the auto-assign reachable.
- arcPosition: z.number().int().min(1).max(9999).optional(),
- // The LLM may legitimately omit arcRole on a B-plot-light volume; gate
- // the enum but allow the field to be missing. Wrap with z.preprocess so
- // an empty string from the UI's "clear" affordance maps to undefined.
- arcRole: z.preprocess(
- (v) => (v === '' || v == null ? undefined : v),
- z.enum(ARC_ROLES).optional(),
- ),
- // Season the issue belongs to. Optional — orchestrator picks the first
- // season when omitted on a multi-season import.
- seasonNumber: z.number().int().min(1).max(99).optional(),
- logline: z.string().max(500).optional(),
- synopsis: z.string().max(4000).optional(),
- // 500K cap matches the issue's stages.prose.output limit so a long
- // novel chapter can land verbatim. Optional — the LLM may omit the
- // excerpt on some issues. When present, must be non-empty + non-whitespace
- // so it doesn't seed prose.output with whitespace and mark the stage
- // `ready` misleadingly. Exported so the mechanical comic splitter can
- // validate against the SAME ceiling at analyze time (a verbatim split could
- // otherwise produce an excerpt commit would reject — a confusing dead-end).
- proseExcerpt: z.string().min(1).max(IMPORTER_PROSE_EXCERPT_MAX).refine(
- (s) => s.trim().length > 0,
- { message: 'proseExcerpt must contain non-whitespace content' },
- ).optional(),
-}).passthrough();
-
-export const importerCommitSchema = z.object({
- universeId: z.string().trim().min(1).max(120),
- seriesId: z.string().trim().min(1).max(120),
- canonSelections: z.object({
- characters: z.array(importerCanonEntry).max(BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX).default([]),
- places: z.array(importerCanonEntry).max(BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX).default([]),
- objects: z.array(importerCanonEntry).max(BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX).default([]),
- }).default({ characters: [], places: [], objects: [] }),
- arc: importerArcShape.nullable().optional(),
- seasons: z.array(importerSeasonEntry).max(50).default([]),
- issues: z.array(importerIssueEntry).min(1).max(50),
- // Drives which stage each issue's verbatim excerpt seeds: a script-form
- // import seeds its matching script stage (ready) and the pipeline never
- // regenerates — `comic-script` → `stages.comicScript`, `screenplay` →
- // `stages.teleplay`; prose-like types seed `stages.prose`. Optional +
- // defaulting to prose-seed keeps older clients (which don't send it) on the
- // prior behavior.
- contentType: z.enum(IMPORTER_CONTENT_TYPES).optional(),
- // Replace-mode flag — when true, every existing issue on the series is
- // deleted before the incoming `issues` are created, and `series.arc` +
- // `series.seasons[]` are written verbatim (not merged). Canon is still
- // merged additively even in replace mode — universe canon is shared
- // across series, so a per-series destructive replace would be wrong.
- // Defaults to false to preserve the additive merge behavior.
- replaceMode: z.boolean().optional().default(false),
-}).strict();
-
// =============================================================================
// PIPELINE ISSUE QUERY SCHEMAS
// =============================================================================
@@ -2010,76 +1556,6 @@ export const issuesListQuerySchema = z.object({
limit: z.preprocess((v) => (v === undefined ? 1000 : Number(v)), z.number().int().min(1).max(1000)).default(1000),
});
-// =============================================================================
-// UNIFIED STORY BUILDER SCHEMAS
-// =============================================================================
-
-const storyProviderField = z.preprocess(emptyToUndefined, z.string().trim().max(120).optional());
-const storyModelField = z.preprocess(emptyToUndefined, z.string().trim().max(200).optional());
-
-export const storySessionCreateSchema = z.object({
- title: z.string().trim().min(1).max(200),
- intakeMode: z.enum(['seed', 'import']).optional().default('seed'),
- seedIdea: z.string().trim().max(4000).optional().default(''),
- // Import mode supplies pre-created ids; seed mode mints shells server-side.
- universeId: z.preprocess(emptyToUndefined, z.string().trim().max(64).optional()),
- seriesId: z.preprocess(emptyToUndefined, z.string().trim().max(64).optional()),
- // Picker choice that drives every Story Builder operation; nullable so the
- // UI can send "use the stage default" explicitly.
- llm: z.object({
- provider: z.string().trim().max(80).nullable().optional(),
- model: z.string().trim().max(200).nullable().optional(),
- }).optional(),
-}).strict();
-
-export const storySessionUpdateSchema = z.object({
- title: z.string().trim().min(1).max(200).optional(),
- seedIdea: z.string().trim().max(4000).optional(),
- // Reject removed/unknown step ids loudly — the sanitizer would otherwise
- // silently coerce them to STEP_IDS[0], landing a stale client on the first
- // step with no error.
- currentStep: z.enum(STORY_STEP_IDS).optional(),
- llm: z.object({
- provider: z.string().trim().max(80).nullable().optional(),
- model: z.string().trim().max(200).nullable().optional(),
- }).optional(),
-}).strict();
-
-// Cross-machine resume opt-in toggle (#730). Sessions are local-only by
-// default; flipping this on snapshots a staleness baseline that travels with
-// the session so a peer's universe edit can't false-positive-stale it.
-export const storySessionSyncSchema = z.object({
- sync: z.boolean(),
-}).strict();
-
-export const storyStepGenerateSchema = z.object({
- providerId: storyProviderField,
- model: storyModelField,
- // Backfill toggle: synthesize this (upstream) step from the series' existing
- // downstream issue content instead of its conventional upstream. Honored by
- // the idea + plotArc generators (see services/storyBuilder.js generateStep).
- fromDownstream: z.boolean().optional(),
-}).strict();
-
-export const storyStepRefineSchema = z.object({
- feedback: z.string().trim().max(4000).optional().default(''),
- // For per-entry refine (e.g. a single character on the characters step).
- entryId: z.preprocess(emptyToUndefined, z.string().trim().max(64).optional()),
- providerId: storyProviderField,
- model: storyModelField,
-}).strict();
-
-export const storyIssueLockSchema = z.object({
- locked: z.boolean(),
-}).strict();
-
-export const storyIssuesGenerateSchema = z.object({
- providerId: storyProviderField,
- model: storyModelField,
- // Optional: scope generation to a single season; omit to cover every season
- // on the arc.
- seasonId: z.preprocess(emptyToUndefined, z.string().trim().max(64).optional()),
-}).strict();
// Per-request LLM provider/model override. Shared by universe-builder expand
// routes and pipeline arc-planning routes. Optional so callers that omit the
@@ -2102,3 +1578,19 @@ export const documentUpdateSchema = z.object({
content: z.string().max(500000),
commitMessage: z.string().max(200).optional()
});
+
+// =============================================================================
+// TRANSITIONAL RE-EXPORTS (issue #1151 split)
+// =============================================================================
+// These domain schema groups moved to their own per-domain files (the
+// brainValidation.js pattern); the re-exports keep every existing deep
+// `import { x } from '../lib/validation.js'` working. New code should import
+// from the domain file (or the barrel's namespace export) directly.
+//
+// Cycle note: the domain files must NOT import from this module — ESM hoists
+// `export * from`, so they evaluate before this module's body runs and any
+// value read back from here hits the TDZ. Shared zod primitives they need
+// (e.g. `emptyToUndefined`) live in zodCompat.js.
+export * from './peerSyncValidation.js';
+export * from './creativeDirectorValidation.js';
+export * from './storyBuilderValidation.js';
diff --git a/server/lib/validationSplit.test.js b/server/lib/validationSplit.test.js
new file mode 100644
index 0000000000..8ca30e35fd
--- /dev/null
+++ b/server/lib/validationSplit.test.js
@@ -0,0 +1,41 @@
+import { describe, it, expect } from 'vitest';
+import * as validation from './validation.js';
+import * as peerSyncValidation from './peerSyncValidation.js';
+import * as creativeDirectorValidation from './creativeDirectorValidation.js';
+import * as storyBuilderValidation from './storyBuilderValidation.js';
+
+// Issue #1151 split validation.js's peer-sync / creative-director / story-
+// builder schema groups into per-domain files, with validation.js re-exporting
+// them so existing deep imports keep working. This pins that transitional
+// contract: every moved export must remain reachable from validation.js AND
+// be the SAME object as the domain file's export (not a divergent copy).
+describe('validation.js transitional re-exports (issue #1151)', () => {
+ const domains = [
+ ['peerSyncValidation', peerSyncValidation],
+ ['creativeDirectorValidation', creativeDirectorValidation],
+ ['storyBuilderValidation', storyBuilderValidation],
+ ];
+
+ it.each(domains)('%s exports are all reachable from validation.js as the same objects', (_name, mod) => {
+ for (const [key, value] of Object.entries(mod)) {
+ expect(validation[key], `validation.js re-export of '${key}'`).toBe(value);
+ }
+ });
+
+ it('the moved schemas still parse through the validation.js entry', () => {
+ expect(() => validation.validateRequest(validation.peerSubscribeSchema, {
+ peerId: 'peer-1', recordKind: 'universe', recordId: 'u-1',
+ })).not.toThrow();
+ expect(() => validation.validateRequest(validation.storySessionCreateSchema, {
+ title: 'My Story',
+ })).not.toThrow();
+ expect(validation.IMPORTER_CONTENT_TYPES).toBeDefined();
+ });
+
+ it('cross-cutting primitives stayed in validation.js', () => {
+ expect(typeof validation.validateRequest).toBe('function');
+ expect(typeof validation.parsePagination).toBe('function');
+ expect(validation.llmSchema).toBeDefined();
+ expect(typeof validation.emptyToUndefined).toBe('function');
+ });
+});
diff --git a/server/lib/zodCompat.js b/server/lib/zodCompat.js
index b55e874adf..0eb2c31684 100644
--- a/server/lib/zodCompat.js
+++ b/server/lib/zodCompat.js
@@ -67,3 +67,12 @@ export function partialWithoutDefaults(objectSchema) {
// unknown-key contract.
return objectSchema.def?.catchall?.def?.type === 'never' ? rebuilt.strict() : rebuilt;
}
+
+/**
+ * Preprocess helper: treat an empty-string UI sentinel as "not sent" so an
+ * optional field's validation doesn't fire on ''. Lives here (not in
+ * validation.js) so per-domain schema files can use it without importing
+ * validation.js — which re-exports them, and ESM hoists `export * from`, so
+ * an import in the other direction would hit a TDZ cycle.
+ */
+export const emptyToUndefined = (v) => (v === '' ? undefined : v);