Skip to content

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

feat([issue-907]): upgrade server to Zod 4

Adam Eivy54841f449e53
diff --git a/server/lib/README.md b/server/lib/README.md
index 2a733e0162..0b005ff670 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -203,6 +203,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `singleFlight.js` | `createSingleFlight()` → `run(key, fn)` — keyed in-flight coalescer: concurrent calls for the same key share one `fn()` execution and result; the slot auto-clears on settle. Minimal by design (no TTL/result cache layered on top, doesn't reject concurrent callers). Used by `promptRunner.js`'s fallback mark-and-pick. |
| `sseUtils.js` | Per-job SSE stream helpers (imageGen + others). |
| `uuid.js` | `v4()` thin wrapper over `crypto.randomUUID()`. |
+| `zodCompat.js` | Zod 4 compatibility helpers. `partialWithoutDefaults(objectSchema)` — like `.partial()` but strips inner field defaults first, so a PATCH/update schema doesn't inject (and clobber) the stored values of fields the caller didn't send. Use for any update schema derived from a defaulted base. |
## Test support
diff --git a/server/lib/aiToolkit/validation.js b/server/lib/aiToolkit/validation.js
index 91b4fdedc8..337d9e98a2 100644
--- a/server/lib/aiToolkit/validation.js
+++ b/server/lib/aiToolkit/validation.js
@@ -62,7 +62,7 @@ export function validate(schema, data) {
}
return {
success: false,
- errors: result.error.errors.map(e => ({
+ errors: result.error.issues.map(e => ({
path: e.path.join('.'),
message: e.message
}))
diff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.js
index c73d4d97b2..c750a253d0 100644
--- a/server/lib/brainValidation.js
+++ b/server/lib/brainValidation.js
@@ -1,4 +1,5 @@
import { z } from 'zod';
+import { partialWithoutDefaults } from './zodCompat.js';
// Destination enum
export const destinationEnum = z.enum(['people', 'projects', 'ideas', 'admin', 'memories', 'unknown']);
@@ -38,7 +39,7 @@ export const classificationSchema = z.object({
// Filed info schema
export const filedSchema = z.object({
destination: destinationEnum.exclude(['unknown']),
- destinationId: z.string().uuid()
+ destinationId: z.string().guid()
});
// Correction schema
@@ -57,7 +58,7 @@ export const errorSchema = z.object({
// Inbox Log Record schema
export const inboxLogRecordSchema = z.object({
- id: z.string().uuid(),
+ id: z.string().guid(),
capturedText: z.string().min(1).max(10000),
capturedAt: z.string().datetime(),
source: z.literal('brain_ui'),
@@ -71,7 +72,7 @@ export const inboxLogRecordSchema = z.object({
// People Record schema
export const peopleRecordSchema = z.object({
- id: z.string().uuid(),
+ id: z.string().guid(),
name: z.string().min(1).max(200),
context: z.string().max(2000).optional().default(''),
followUps: z.array(z.string().max(500)).optional().default([]),
@@ -83,7 +84,7 @@ export const peopleRecordSchema = z.object({
// Project Record schema
export const projectRecordSchema = z.object({
- id: z.string().uuid(),
+ id: z.string().guid(),
name: z.string().min(1).max(200),
status: projectStatusEnum,
nextAction: z.string().min(1).max(500),
@@ -95,7 +96,7 @@ export const projectRecordSchema = z.object({
// Idea Record schema
export const ideaRecordSchema = z.object({
- id: z.string().uuid(),
+ id: z.string().guid(),
title: z.string().min(1).max(200),
status: ideaStatusEnum.default('active'),
oneLiner: z.string().min(1).max(500),
@@ -107,7 +108,7 @@ export const ideaRecordSchema = z.object({
// Admin Record schema
export const adminRecordSchema = z.object({
- id: z.string().uuid(),
+ id: z.string().guid(),
title: z.string().min(1).max(200),
status: adminStatusEnum,
dueDate: z.string().datetime().optional(),
@@ -119,7 +120,7 @@ export const adminRecordSchema = z.object({
// Memory Record schema (journal entries, daily notes, personal memories)
export const memoryRecordSchema = z.object({
- id: z.string().uuid(),
+ id: z.string().guid(),
title: z.string().min(1).max(200),
content: z.string().max(10000).optional().default(''),
mood: z.string().max(50).optional(),
@@ -143,7 +144,7 @@ export const brainSettingsSchema = z.object({
// Digest Record schema
export const digestRecordSchema = z.object({
- id: z.string().uuid(),
+ id: z.string().guid(),
generatedAt: z.string().datetime(),
digestText: z.string().max(2000),
topActions: z.array(z.string().max(200)).max(3),
@@ -154,7 +155,7 @@ export const digestRecordSchema = z.object({
// Weekly Review Record schema
export const reviewRecordSchema = z.object({
- id: z.string().uuid(),
+ id: z.string().guid(),
generatedAt: z.string().datetime(),
reviewText: z.string().max(3000),
whatHappened: z.array(z.string().max(200)).max(5),
@@ -175,14 +176,14 @@ export const captureInputSchema = z.object({
// Resolve review input schema
export const resolveReviewInputSchema = z.object({
- inboxLogId: z.string().uuid(),
+ inboxLogId: z.string().guid(),
destination: destinationEnum.exclude(['unknown']),
editedExtracted: z.record(z.unknown()).optional()
});
// Fix classification input schema
export const fixInputSchema = z.object({
- inboxLogId: z.string().uuid(),
+ inboxLogId: z.string().guid(),
newDestination: destinationEnum.exclude(['unknown']),
updatedFields: z.record(z.unknown()).optional(),
note: z.string().max(500).optional()
@@ -238,7 +239,11 @@ export const memoryInputSchema = z.object({
});
// Settings update input schema
-export const settingsUpdateInputSchema = brainSettingsSchema.partial().omit({ version: true, lastDailyDigest: true, lastWeeklyReview: true });
+// partialWithoutDefaults (not .partial()) so a PATCH that touches only one
+// setting doesn't inject the other fields' defaults (e.g. defaultProvider:
+// 'lmstudio') and overwrite the stored values — Zod 4's .partial() keeps inner
+// defaults (see zodCompat.js).
+export const settingsUpdateInputSchema = partialWithoutDefaults(brainSettingsSchema).omit({ version: true, lastDailyDigest: true, lastWeeklyReview: true });
// Inbox query schema
export const inboxQuerySchema = z.object({
@@ -330,7 +335,7 @@ export const linkTypeEnum = z.enum(['github', 'article', 'documentation', 'tool'
// Link Record schema
export const linkRecordSchema = z.object({
- id: z.string().uuid(),
+ id: z.string().guid(),
url: z.string().url(),
title: z.string().min(1).max(500),
description: z.string().max(2000).optional().default(''),
@@ -344,7 +349,7 @@ export const linkRecordSchema = z.object({
cloneStatus: z.enum(['pending', 'cloning', 'cloned', 'failed', 'none']).default('none'),
cloneError: z.string().max(500).optional(),
// Bucket grouping (nullable = ungrouped)
- bucketId: z.string().uuid().nullable().optional(),
+ bucketId: z.string().guid().nullable().optional(),
bucketOrder: z.number().int().optional(),
// Metadata
createdAt: z.string().datetime(),
@@ -358,7 +363,7 @@ export const linkInputSchema = z.object({
description: z.string().max(2000).optional(),
linkType: linkTypeEnum.optional(),
tags: z.array(z.string().max(50)).optional(),
- bucketId: z.string().uuid().nullable().optional(),
+ bucketId: z.string().guid().nullable().optional(),
bucketOrder: z.number().int().optional(),
autoClone: z.boolean().optional().default(true)
});
@@ -370,7 +375,7 @@ export const linkUpdateInputSchema = z.object({
description: z.string().max(2000).optional(),
linkType: linkTypeEnum.optional(),
tags: z.array(z.string().max(50)).optional(),
- bucketId: z.string().uuid().nullable().optional(),
+ bucketId: z.string().guid().nullable().optional(),
bucketOrder: z.number().int().optional()
});
@@ -402,7 +407,7 @@ export const bucketColorEnum = z.enum([
// Bucket Record schema
export const bucketRecordSchema = z.object({
- id: z.string().uuid(),
+ id: z.string().guid(),
name: z.string().min(1).max(100),
color: bucketColorEnum.default('accent'),
icon: z.string().max(50).optional().default(''),
@@ -428,7 +433,7 @@ export const bucketUpdateInputSchema = z.object({
// Reorder buckets input schema (ordered list of bucket ids)
export const bucketReorderSchema = z.object({
- ids: z.array(z.string().uuid()).min(1)
+ ids: z.array(z.string().guid()).min(1)
});
// Batch link reorder (POST /api/brain/links/reorder) — applies a dense
@@ -437,8 +442,8 @@ export const bucketReorderSchema = z.object({
// concurrent single-record PUTs can.
export const linkReorderSchema = z.object({
updates: z.array(z.object({
- id: z.string().uuid(),
- bucketId: z.string().uuid().nullable(),
+ id: z.string().guid(),
+ bucketId: z.string().guid().nullable(),
bucketOrder: z.number().int()
})).min(1)
});
diff --git a/server/lib/digitalTwinValidation.js b/server/lib/digitalTwinValidation.js
index eff9aecab4..7e6fb05734 100644
--- a/server/lib/digitalTwinValidation.js
+++ b/server/lib/digitalTwinValidation.js
@@ -6,6 +6,7 @@ import {
BIG_FIVE_DELTA_MAX,
EMOJI_USAGE_VALUES
} from './personaTraitBlend.js';
+import { partialWithoutDefaults } from './zodCompat.js';
// Document category enum
export const documentCategoryEnum = z.enum([
@@ -67,10 +68,10 @@ export const documentMetaSchema = z.object({
// optional — Zod strips unknown keys, so they MUST be declared here or they'd
// be silently dropped on the next loadMeta.
export const testHistoryEntrySchema = z.object({
- runId: z.string().uuid(),
+ runId: z.string().guid(),
providerId: z.string(),
model: z.string(),
- personaId: z.string().uuid().optional(),
+ personaId: z.string().guid().optional(),
personaName: z.string().optional(),
score: z.number().min(0).max(1),
passed: z.number().int().min(0),
@@ -82,10 +83,10 @@ export const testHistoryEntrySchema = z.object({
// Values-alignment run history entry (M34 P6). Same persona fields as above.
export const valuesTestHistoryEntrySchema = z.object({
- runId: z.string().uuid(),
+ runId: z.string().guid(),
providerId: z.string(),
model: z.string(),
- personaId: z.string().uuid().optional(),
+ personaId: z.string().guid().optional(),
personaName: z.string().optional(),
score: z.number().min(0).max(1),
aligned: z.number().int().min(0),
@@ -97,10 +98,10 @@ export const valuesTestHistoryEntrySchema = z.object({
// Adversarial-boundary run history entry (M34 P6). Same persona fields as above.
export const adversarialTestHistoryEntrySchema = z.object({
- runId: z.string().uuid(),
+ runId: z.string().guid(),
providerId: z.string(),
model: z.string(),
- personaId: z.string().uuid().optional(),
+ personaId: z.string().guid().optional(),
personaName: z.string().optional(),
score: z.number().min(0).max(1),
held: z.number().int().min(0),
@@ -112,10 +113,10 @@ export const adversarialTestHistoryEntrySchema = z.object({
// Multi-turn conversation run history entry (M34 P6). Same persona fields as above.
export const multiTurnTestHistoryEntrySchema = z.object({
- runId: z.string().uuid(),
+ runId: z.string().guid(),
providerId: z.string(),
model: z.string(),
- personaId: z.string().uuid().optional(),
+ personaId: z.string().guid().optional(),
personaName: z.string().optional(),
score: z.number().min(0).max(1),
consistent: z.number().int().min(0),
@@ -151,7 +152,7 @@ export const digitalTwinSettingsSchema = z.object({
maxContextTokens: z.number().int().min(1000).max(100000).default(4000),
// The persona currently driving the embodied-twin context (CoS agents, etc.).
// null/absent = no persona (base twin). Tolerate the UI sentinel for "deactivate".
- activePersonaId: z.string().uuid().nullable().optional()
+ activePersonaId: z.string().guid().nullable().optional()
});
export const soulSettingsSchema = digitalTwinSettingsSchema; // Alias for backwards compatibility
@@ -184,7 +185,7 @@ export const personaTraitAdjustmentsSchema = z.object({
// twin context so the embodied twin modulates voice/behavior for a context
// (Professional, Casual, Family, …) without forking the underlying documents.
export const personaSchema = z.object({
- id: z.string().uuid(),
+ id: z.string().guid(),
name: z.string().min(1).max(100),
description: z.string().max(500).optional(),
instructions: z.string().min(1).max(5000),
@@ -209,7 +210,7 @@ export const updatePersonaInputSchema = z.object({
});
export const setActivePersonaInputSchema = z.object({
- personaId: z.string().uuid().nullable()
+ personaId: z.string().guid().nullable()
});
// --- Phase 1: Quantitative Personality Modeling Schemas ---
@@ -326,7 +327,7 @@ const optionalTestIds = z.preprocess(
// so a base-twin run validates instead of 400-ing on the sentinel.
const optionalPersonaId = z.preprocess(
v => (v == null || v === '') ? undefined : v,
- z.string().uuid().optional()
+ z.string().guid().optional()
);
// Run tests input
@@ -357,7 +358,7 @@ export const enrichmentQuestionInputSchema = z.object({
// Enrichment answer input
export const enrichmentAnswerInputSchema = z.object({
- questionId: z.string().uuid(),
+ questionId: z.string().guid(),
category: enrichmentCategoryEnum,
question: z.string().min(1),
answer: z.string().min(1).max(10000).optional(),
@@ -383,7 +384,7 @@ export const exportInputSchema = z.object({
});
// Settings update input
-export const settingsUpdateInputSchema = soulSettingsSchema.partial();
+export const settingsUpdateInputSchema = partialWithoutDefaults(soulSettingsSchema);
// Test history query
export const testHistoryQuerySchema = z.object({
@@ -476,7 +477,7 @@ export const analyzeTraitsInputSchema = z.object({
export const updateTraitsInputSchema = z.object({
bigFive: bigFiveSchema.partial().optional(),
valuesHierarchy: z.array(valuedTraitSchema).max(20).optional(),
- communicationProfile: communicationProfileSchema.partial().optional()
+ communicationProfile: partialWithoutDefaults(communicationProfileSchema).optional()
});
// Calculate confidence input
@@ -629,6 +630,6 @@ export const createSnapshotInputSchema = z.object({
});
export const compareSnapshotsInputSchema = z.object({
- id1: z.string().uuid(),
- id2: z.string().uuid()
+ id1: z.string().guid(),
+ id2: z.string().guid()
});
diff --git a/server/lib/index.js b/server/lib/index.js
index b0f26f0fc6..f12bca5497 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -170,6 +170,7 @@ export * from './objects.js';
export * from './singleFlight.js';
export * from './sseUtils.js';
export * from './uuid.js';
+export * from './zodCompat.js';
// === Test support (consumed by *.test.js files) ===
export * from './mockPathsDataRoot.js';
diff --git a/server/lib/meatspaceValidation.js b/server/lib/meatspaceValidation.js
index d90842094a..bf93e8769f 100644
--- a/server/lib/meatspaceValidation.js
+++ b/server/lib/meatspaceValidation.js
@@ -1,4 +1,5 @@
import { z } from 'zod';
+import { partialWithoutDefaults } from './zodCompat.js';
// =============================================================================
// LIFE CALENDAR ACTIVITIES
@@ -11,7 +12,7 @@ export const activitySchema = z.object({
icon: z.string().max(50).optional().default('circle'),
});
-export const activityUpdateSchema = activitySchema.partial();
+export const activityUpdateSchema = partialWithoutDefaults(activitySchema);
// =============================================================================
// LIFE CALENDAR EVENTS
@@ -28,7 +29,7 @@ export const lifeEventSchema = z.object({
enabled: z.boolean().optional().default(true),
});
-export const lifeEventUpdateSchema = lifeEventSchema.partial();
+export const lifeEventUpdateSchema = partialWithoutDefaults(lifeEventSchema);
// =============================================================================
// MEATSPACE CONFIG & LIFESTYLE
@@ -56,7 +57,7 @@ export const configSchema = z.object({
});
export const configUpdateSchema = configSchema.partial();
-export const lifestyleUpdateSchema = lifestyleSchema.partial();
+export const lifestyleUpdateSchema = partialWithoutDefaults(lifestyleSchema);
// =============================================================================
// ALCOHOL
diff --git a/server/lib/memoryValidation.js b/server/lib/memoryValidation.js
index f2deca56b9..6c21a323b9 100644
--- a/server/lib/memoryValidation.js
+++ b/server/lib/memoryValidation.js
@@ -1,4 +1,5 @@
import { z } from 'zod';
+import { partialWithoutDefaults } from './zodCompat.js';
// Memory types enum
export const memoryTypeEnum = z.enum([
@@ -36,7 +37,7 @@ export const memoryCreateSchema = z.object({
tags: z.array(z.string().max(50)).max(20).optional().default([]),
confidence: z.number().min(0).max(1).optional().default(0.8),
importance: z.number().min(0).max(1).optional().default(0.5),
- relatedMemories: z.array(z.string().uuid()).optional().default([]),
+ relatedMemories: z.array(z.string().guid()).optional().default([]),
sourceTaskId: z.string().optional(),
sourceAgentId: z.string().optional(),
sourceAppId: z.string().nullable().optional()
@@ -44,7 +45,7 @@ export const memoryCreateSchema = z.object({
// Full memory schema (includes system-generated fields)
export const memorySchema = memoryCreateSchema.extend({
- id: z.string().uuid(),
+ id: z.string().guid(),
embedding: z.array(z.number()).optional(),
embeddingModel: z.string().optional(),
accessCount: z.number().int().min(0).default(0),
@@ -56,7 +57,7 @@ export const memorySchema = memoryCreateSchema.extend({
});
// Partial schema for updates
-export const memoryUpdateSchema = memoryCreateSchema.partial().extend({
+export const memoryUpdateSchema = partialWithoutDefaults(memoryCreateSchema).extend({
status: memoryStatusEnum.optional()
});
@@ -109,13 +110,13 @@ export const memoryConsolidateSchema = z.object({
// Link memories request schema
export const memoryLinkSchema = z.object({
- sourceId: z.string().uuid(),
- targetId: z.string().uuid()
+ sourceId: z.string().guid(),
+ targetId: z.string().guid()
});
// Single sync memory item schema (incoming from remote peer)
const syncMemoryItemSchema = z.object({
- id: z.string().uuid(),
+ id: z.string().guid(),
type: memoryTypeEnum,
content: z.string().min(1).max(10240),
summary: z.string().max(500).nullable().optional(),
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 36de31ffdf..04b6eb7782 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1,5 +1,6 @@
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 { WORK_KINDS, WORK_STATUSES, ANALYSIS_KINDS } from './writersRoomPresets.js';
import { ALL_STYLE_IDS, STYLE_ID } from './writersRoomStylePresets.js';
@@ -96,7 +97,7 @@ export const agentSchema = z.object({
aiConfig: agentAiConfigSchema
});
-export const agentUpdateSchema = agentSchema.partial();
+export const agentUpdateSchema = partialWithoutDefaults(agentSchema);
// =============================================================================
// PLATFORM ACCOUNT SCHEMAS
@@ -120,7 +121,7 @@ export const platformAccountSchema = z.object({
platformData: z.record(z.unknown()).optional().default({})
});
-export const platformAccountUpdateSchema = platformAccountSchema.partial();
+export const platformAccountUpdateSchema = partialWithoutDefaults(platformAccountSchema);
// Account registration (when creating new Moltbook account)
export const accountRegistrationSchema = z.object({
@@ -178,7 +179,7 @@ export const automationScheduleSchema = z.object({
enabled: z.boolean().default(true)
});
-export const automationScheduleUpdateSchema = automationScheduleSchema.partial();
+export const automationScheduleUpdateSchema = partialWithoutDefaults(automationScheduleSchema);
// =============================================================================
// EXISTING SCHEMAS
@@ -316,7 +317,7 @@ export const referenceRepoUpdateSchema = z.object({
// Partial schema for updates. referenceRepos is intentionally absent
// from appSchema (see comment there) so it can't sneak in via PUT
// either — all ref CRUD goes through /api/apps/:appId/reference-repos.
-export const appUpdateSchema = appSchema.partial();
+export const appUpdateSchema = partialWithoutDefaults(appSchema);
// Provider schema
export const providerSchema = z.object({
@@ -368,7 +369,7 @@ export const socialAccountSchema = z.object({
notes: z.string().max(2000).optional().default('')
});
-export const socialAccountUpdateSchema = socialAccountSchema.partial();
+export const socialAccountUpdateSchema = partialWithoutDefaults(socialAccountSchema);
// =============================================================================
// AGENT TOOLS SCHEMAS
@@ -876,7 +877,10 @@ export const writersRoomWorkUpdateSchema = z.object({
status: writersRoomWorkStatusSchema.optional(),
folderId: wrIdNullable.optional(),
imageStyle: writersRoomImageStyleSchema.optional(),
- liveMode: writersRoomLiveModeSchema.partial().optional(),
+ // partialWithoutDefaults (not .partial()) so a single-knob PATCH doesn't inject
+ // the other knobs' defaults and clobber their stored values (Zod 4 .partial()
+ // keeps inner defaults — see zodCompat.js). The service field-merges each knob.
+ liveMode: partialWithoutDefaults(writersRoomLiveModeSchema).optional(),
}).strict();
// Cursor-context payload for the live continuation suggest route. The three
@@ -1058,11 +1062,14 @@ export const featureAgentSchema = z.object({
description: z.string().min(1).max(2000),
persona: z.string().max(5000).optional().default(''),
appId: z.string().min(1),
+ // .prefault({}) (not .default({})) so the nested field defaults still apply
+ // when `schedule` is omitted — Zod 4's .default() no longer re-parses its
+ // value, so a bare .default({}) would yield {} instead of the filled object.
schedule: z.object({
mode: featureAgentScheduleModeSchema.default('continuous'),
intervalMs: z.number().int().min(30000).optional(),
pauseBetweenRunsMs: z.number().int().min(0).default(60000)
- }).default({}),
+ }).prefault({}),
goals: z.array(z.string()).default([]),
constraints: z.array(z.string()).default([]),
providerId: z.string().optional().nullable(),
@@ -1101,7 +1108,7 @@ export function validate(schema, data) {
}
return {
success: false,
- errors: result.error.errors.map(e => ({
+ errors: result.error.issues.map(e => ({
path: e.path.join('.'),
message: e.message
}))
@@ -1220,7 +1227,7 @@ export const localLlmCompareSchema = z.object({
export function validateRequest(schema, data) {
const result = schema.safeParse(data);
if (result.success) return result.data;
- const errors = result.error.errors.map(e => ({
+ const errors = result.error.issues.map(e => ({
path: e.path.join('.'),
message: e.message
}));
diff --git a/server/lib/zodCompat.js b/server/lib/zodCompat.js
new file mode 100644
index 0000000000..216f6c4e9d
--- /dev/null
+++ b/server/lib/zodCompat.js
@@ -0,0 +1,54 @@
+import { z } from 'zod';
+
+/**
+ * Zod 4 compatibility helpers.
+ *
+ * Zod 4 changed two default-related behaviors that matter for PortOS's
+ * "PATCH only the fields you send" update schemas:
+ *
+ * 1. `.default()` no longer re-parses its input, so a `z.object({...}).default({})`
+ * yields `{}` instead of an object with the nested field defaults filled in.
+ * Use `.prefault({})` (Zod 4) when you want the old "parse the default" behavior.
+ *
+ * 2. `.partial()` now ONLY marks fields optional — it no longer strips the inner
+ * `.default()`s. In Zod 3, `base.partial()` produced a schema where an omitted
+ * field stayed omitted; in Zod 4 the field's `.default()` still fires, so the
+ * parsed patch is populated with default values for keys the caller never sent.
+ * For an update/PATCH route that merges the parsed patch onto a stored record,
+ * that silently clobbers the stored value of every untouched defaulted field.
+ *
+ * `partialWithoutDefaults` restores the Zod 3 `.partial()` semantics for case 2:
+ * it rebuilds the object shape with every field's default removed, then partials
+ * it — so an omitted field is genuinely absent from the parsed result and the
+ * merge layer can tell "not sent" from "sent". Field bounds/refinements are
+ * preserved; only the default wrapper is unwound.
+ */
+
+/**
+ * Unwrap a field's default/prefault wrapper(s) while preserving any
+ * optional/nullable wrappers (re-applied in their original order) and the inner
+ * type's validation rules.
+ */
+function stripDefault(schema) {
+ const type = schema?.def?.type;
+ if (type === 'default' || type === 'prefault') return stripDefault(schema.def.innerType);
+ if (type === 'optional') return stripDefault(schema.def.innerType).optional();
+ if (type === 'nullable') return stripDefault(schema.def.innerType).nullable();
+ return schema;
+}
+
+/**
+ * Like `objectSchema.partial()`, but with every field's `.default()` removed
+ * first — so the parsed result contains only the keys the caller actually sent.
+ * Use for any PATCH/update schema derived from a base that carries field defaults.
+ *
+ * @param {import('zod').ZodObject} objectSchema
+ * @returns {import('zod').ZodObject} partial schema with defaults stripped
+ */
+export function partialWithoutDefaults(objectSchema) {
+ const shape = objectSchema.shape;
+ const stripped = Object.fromEntries(
+ Object.entries(shape).map(([key, field]) => [key, stripDefault(field)]),
+ );
+ return z.object(stripped).partial();
+}
diff --git a/server/lib/zodCompat.test.js b/server/lib/zodCompat.test.js
new file mode 100644
index 0000000000..c67954bf9d
--- /dev/null
+++ b/server/lib/zodCompat.test.js
@@ -0,0 +1,49 @@
+import { describe, it, expect } from 'vitest';
+import { z } from 'zod';
+import { partialWithoutDefaults } from './zodCompat.js';
+
+describe('partialWithoutDefaults', () => {
+ const base = z.object({
+ enabled: z.boolean().default(false),
+ debounceMs: z.number().int().min(800).max(30_000).default(2500),
+ note: z.string().optional().default(''),
+ nick: z.string().nullable().default('anon'),
+ name: z.string().min(1), // no default
+ });
+
+ it('omits keys the caller did not send (no injected defaults)', () => {
+ const schema = partialWithoutDefaults(base);
+ expect(schema.parse({})).toEqual({});
+ expect(schema.parse({ debounceMs: 3000 })).toEqual({ debounceMs: 3000 });
+ });
+
+ it('preserves field bounds/refinements after stripping the default', () => {
+ const schema = partialWithoutDefaults(base);
+ expect(schema.safeParse({ debounceMs: 100 }).success).toBe(false); // < min
+ expect(schema.safeParse({ enabled: 'yes' }).success).toBe(false); // not boolean
+ expect(schema.safeParse({ name: '' }).success).toBe(false); // min(1)
+ });
+
+ it('keeps optional/nullable wrappers while removing the default', () => {
+ const schema = partialWithoutDefaults(base);
+ // optional() field: sending null is rejected (not nullable), absent is fine
+ expect(schema.safeParse({ note: 'hi' }).success).toBe(true);
+ // nullable() field: explicit null is accepted, but no default is injected
+ expect(schema.parse({ nick: null })).toEqual({ nick: null });
+ expect(schema.parse({})).toEqual({});
+ });
+
+ it('makes every field optional (like .partial())', () => {
+ const schema = partialWithoutDefaults(base);
+ // `name` has no default and no .optional() on the base, but partial makes it optional
+ expect(schema.safeParse({}).success).toBe(true);
+ });
+
+ it('contrasts with Zod 4 .partial(), which keeps inner defaults', () => {
+ // Documents the behavior this helper exists to avoid: stock .partial()
+ // still injects the defaults for omitted fields in Zod 4.
+ expect(base.partial().parse({})).toMatchObject({ enabled: false, debounceMs: 2500 });
+ // The helper does not:
+ expect(partialWithoutDefaults(base).parse({})).toEqual({});
+ });
+});
diff --git a/server/package.json b/server/package.json
index 07d95df272..e0035bdb6a 100644
--- a/server/package.json
+++ b/server/package.json
@@ -24,7 +24,7 @@
"socket.io": "4.8.3",
"socket.io-client": "4.8.3",
"ws": "8.20.1",
- "zod": "3.24.1"
+ "zod": "^4.4.3"
},
"devDependencies": {
"@vitest/coverage-v8": "4.1.8",
diff --git a/server/routes/brain.js b/server/routes/brain.js
index a7bf44fd3a..45ed5e00c6 100644
--- a/server/routes/brain.js
+++ b/server/routes/brain.js
@@ -15,6 +15,7 @@ import * as brainService from '../services/brain.js';
import { getProviderById } from '../services/providers.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
+import { partialWithoutDefaults } from '../lib/zodCompat.js';
import {
captureInputSchema,
resolveReviewInputSchema,
@@ -219,7 +220,7 @@ router.post('/projects', asyncHandler(async (req, res) => {
}));
router.put('/projects/:id', asyncHandler(async (req, res) => {
- const data = validateRequest(projectInputSchema.partial(), req.body);
+ const data = validateRequest(partialWithoutDefaults(projectInputSchema), req.body);
const project = await brainService.updateProject(req.params.id, data);
if (!project) {
throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
@@ -261,7 +262,7 @@ router.post('/ideas', asyncHandler(async (req, res) => {
}));
router.put('/ideas/:id', asyncHandler(async (req, res) => {
- const data = validateRequest(ideaInputSchema.partial(), req.body);
+ const data = validateRequest(partialWithoutDefaults(ideaInputSchema), req.body);
const idea = await brainService.updateIdea(req.params.id, data);
if (!idea) {
throw new ServerError('Idea not found', { status: 404, code: 'NOT_FOUND' });
@@ -303,7 +304,7 @@ router.post('/admin', asyncHandler(async (req, res) => {
}));
router.put('/admin/:id', asyncHandler(async (req, res) => {
- const data = validateRequest(adminInputSchema.partial(), req.body);
+ const data = validateRequest(partialWithoutDefaults(adminInputSchema), req.body);
const item = await brainService.updateAdminItem(req.params.id, data);
if (!item) {
throw new ServerError('Admin item not found', { status: 404, code: 'NOT_FOUND' });
diff --git a/server/routes/catalog.js b/server/routes/catalog.js
index 3a10a5bf89..c99dd6a60c 100644
--- a/server/routes/catalog.js
+++ b/server/routes/catalog.js
@@ -487,7 +487,7 @@ router.post('/bulk-import', asyncHandler(async (req, res) => {
const mergedTags = Array.from(new Set([...(entry.tags || []), ...defaultTags]));
const result = catalogIngredientCreateSchema.safeParse({ ...entry, tags: mergedTags });
if (!result.success) {
- const msg = result.error.errors?.[0]?.message || result.error.message;
+ const msg = result.error.issues?.[0]?.message || result.error.message;
throw new ServerError(`Bulk import entry ${i} invalid: ${msg}`, { status: 400 });
}
entries.push(result.data);
diff --git a/server/routes/instances.js b/server/routes/instances.js
index 3ff48fb93a..534544e5d4 100644
--- a/server/routes/instances.js
+++ b/server/routes/instances.js
@@ -82,7 +82,7 @@ const updatePeerSchema = z.object({
const announceSchema = z.object({
port: z.number().int().min(1).max(65535),
- instanceId: z.string().uuid(),
+ instanceId: z.string().guid(),
name: z.string().optional(),
// Tailscale-issued DNS name announcing peer reaches itself at; receiver
// stores it on the peer record so callbacks use https://<host>:<port>.
diff --git a/server/routes/messages.js b/server/routes/messages.js
index 89fd7bf968..4078640b35 100644
--- a/server/routes/messages.js
+++ b/server/routes/messages.js
@@ -39,7 +39,7 @@ const updateAccountSchema = z.object({
});
const createDraftSchema = z.object({
- accountId: z.string().uuid(),
+ accountId: z.string().guid(),
replyToMessageId: z.string().nullish(),
threadId: z.string().nullish(),
to: z.array(z.string()).optional().default([]),
@@ -59,7 +59,7 @@ const updateDraftSchema = z.object({
});
const generateDraftSchema = z.object({
- accountId: z.string().uuid(),
+ accountId: z.string().guid(),
replyToMessageId: z.string().nullish(),
threadId: z.string().nullish(),
context: z.string().optional().default(''),
@@ -364,7 +364,7 @@ router.get('/thread/:accountId/:threadId', asyncHandler(async (req, res) => {
// === Message params schema (shared by detail + refresh routes) ===
const messageParamsSchema = z.object({
- accountId: z.string().uuid(),
+ accountId: z.string().guid(),
messageId: z.string().min(1)
});
diff --git a/server/routes/telegram.js b/server/routes/telegram.js
index b5c4169a90..27ec4ba42a 100644
--- a/server/routes/telegram.js
+++ b/server/routes/telegram.js
@@ -48,7 +48,7 @@ router.put('/method', asyncHandler(async (req, res) => {
throw new ServerError('Validation failed', {
status: 400,
code: 'VALIDATION_ERROR',
- context: { details: result.error.errors }
+ context: { details: result.error.issues }
});
}
@@ -103,7 +103,7 @@ router.put('/config', asyncHandler(async (req, res) => {
throw new ServerError('Validation failed', {
status: 400,
code: 'VALIDATION_ERROR',
- context: { details: result.error.errors }
+ context: { details: result.error.issues }
});
}
@@ -173,7 +173,7 @@ router.post('/test', asyncHandler(async (req, res) => {
throw new ServerError('Validation failed', {
status: 400,
code: 'VALIDATION_ERROR',
- context: { details: result.error.errors }
+ context: { details: result.error.issues }
});
}
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index 39c570920b..65fda11c85 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -132,7 +132,7 @@ const generateBodySchema = z.object({
// routes through ExtendPipeline.extend_from_video which conditions on
// the entire source video's latent rather than a single last frame).
// The legacy chained-i2v path keeps using sourceImageFile.
- extendFromVideoId: z.string().uuid().optional(),
+ extendFromVideoId: z.string().guid().optional(),
// Multi-keyframe interpolation (ltx2 + mode='fflf'). Each entry pins one
// gallery image at a specific pixel-frame index. Indices must be strictly
// ascending and within [0, numFrames-1]. When set, overrides the legacy
@@ -837,10 +837,11 @@ router.post('/last-frame/:id', asyncHandler(async (req, res) => {
}));
// History ids are produced by crypto.randomUUID(), so validate them as
-// proper UUIDs rather than the looser /^[a-f0-9-]{36}$/ pattern (which
-// happily accepts e.g. 36 hyphens). Matches the .uuid() usage in the
-// other route schemas.
-const historyIdSchema = z.string().uuid('invalid history id');
+// UUIDs rather than the looser /^[a-f0-9-]{36}$/ pattern (which happily
+// accepts e.g. 36 hyphens). `.guid()` is Zod 4's name for the 8-4-4-4-12
+// hex-group check Zod 3's `.uuid()` performed (version-agnostic); matches
+// the .guid() usage in the other route schemas.
+const historyIdSchema = z.string().guid('invalid history id');
router.post('/upscale/:id', asyncHandler(async (req, res) => {
const parsed = historyIdSchema.safeParse(req.params.id);
diff --git a/server/routes/videoTimeline.js b/server/routes/videoTimeline.js
index b94fb15928..cb6ac130cb 100644
--- a/server/routes/videoTimeline.js
+++ b/server/routes/videoTimeline.js
@@ -24,7 +24,7 @@ import {
const router = Router();
const clipSchema = z.object({
- clipId: z.string().uuid(),
+ clipId: z.string().guid(),
inSec: z.number().min(0),
outSec: z.number().min(0),
}).refine((c) => c.outSec > c.inSec, { message: 'outSec must be > inSec', path: ['outSec'] });
diff --git a/server/services/brain.js b/server/services/brain.js
index e7eb9ce111..77cd7cd09d 100644
--- a/server/services/brain.js
+++ b/server/services/brain.js
@@ -211,7 +211,7 @@ async function classifyInBackground(entryId, text, meta, providerOverride, model
if (validationResult.success) {
classification = validationResult.data;
} else {
- console.error(`🧠 Classification validation failed: ${validationResult.error.errors.length} issues, first: ${validationResult.error.errors[0]?.message}`);
+ console.error(`🧠 Classification validation failed: ${validationResult.error.issues.length} issues, first: ${validationResult.error.issues[0]?.message}`);
aiError = new Error('Invalid classification output from AI');
}
} else {
@@ -508,7 +508,7 @@ export async function runDailyDigest(providerOverride, modelOverride) {
const validationResult = digestOutputSchema.safeParse(parsed);
if (!validationResult.success) {
- throw new Error(`Invalid digest output: ${JSON.stringify(validationResult.error.errors)}`);
+ throw new Error(`Invalid digest output: ${JSON.stringify(validationResult.error.issues)}`);
}
const digestData = validationResult.data;
@@ -570,7 +570,7 @@ export async function runWeeklyReview(providerOverride, modelOverride) {
const validationResult = reviewOutputSchema.safeParse(parsed);
if (!validationResult.success) {
- throw new Error(`Invalid review output: ${JSON.stringify(validationResult.error.errors)}`);
+ throw new Error(`Invalid review output: ${JSON.stringify(validationResult.error.issues)}`);
}
const reviewData = validationResult.data;