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

fix: address review (claude) — serialize update, preserve brief constraints, tz re-sync

[._.]/ Adam Eivy7023ad36569f
diff --git a/server/lib/creativeCommissionValidation.js b/server/lib/creativeCommissionValidation.js
index 70f94153a4..67088c95b1 100644
--- a/server/lib/creativeCommissionValidation.js
+++ b/server/lib/creativeCommissionValidation.js
@@ -108,6 +108,25 @@ export const creativeCommissionCreateSchema = z.object({
feedbackWindow: z.number().int().min(0).max(50).default(5),
});
+// Brief schema for the UPDATE path: every field optional and — critically — NO
+// defaults. The create-path `creativeCommissionBriefSchema` defaults
+// `constraints`/`seedRefs`/`styleSpec`, which on a PATCH would inject those keys
+// even when the client omitted them, so the service's `{ ...current.brief,
+// ...patch.brief }` merge would overwrite a stored `constraints.universeId` with
+// an empty default (the absent-vs-empty footgun). With no defaults here, an
+// omitted key stays omitted and the merge preserves the stored value.
+export const creativeCommissionBriefUpdateSchema = z.object({
+ intent: z.string().trim().min(1).max(COMMISSION_INTENT_MAX).optional(),
+ genre: z.string().trim().max(120).nullable().optional(),
+ category: z.string().trim().max(120).nullable().optional(),
+ styleSpec: z.string().max(5000).optional(),
+ constraints: z.object({
+ universeId: z.string().max(120).nullable().optional(),
+ seriesId: z.string().max(120).nullable().optional(),
+ }).optional(),
+ seedRefs: z.array(z.string().trim().max(64)).max(50).optional(),
+});
+
// PATCH: every field optional; at least one must be present. `.partial()` on a
// ZodEffects (the schedule uses superRefine) isn't available, so we rebuild the
// object rather than call `.partial()` on the whole create schema.
@@ -115,7 +134,7 @@ export const creativeCommissionUpdateSchema = z.object({
name: z.string().trim().min(1).max(COMMISSION_NAME_MAX).optional(),
enabled: z.boolean().optional(),
targetAbility: z.enum(CREATIVE_COMMISSION_ABILITIES).optional(),
- brief: creativeCommissionBriefSchema.optional(),
+ brief: creativeCommissionBriefUpdateSchema.optional(),
schedule: creativeCommissionScheduleSchema.optional(),
generation: creativeCommissionGenerationSchema.optional(),
feedbackWindow: z.number().int().min(0).max(50).optional(),
diff --git a/server/services/creativeCommissions/scheduler.js b/server/services/creativeCommissions/scheduler.js
index 1c560617bd..e8d156bd91 100644
--- a/server/services/creativeCommissions/scheduler.js
+++ b/server/services/creativeCommissions/scheduler.js
@@ -24,6 +24,7 @@
import { schedule, cancel, isValidCron } from '../eventScheduler.js';
import { getUserTimezone } from '../../lib/timezone.js';
+import { settingsEvents } from '../settings.js';
import { listCommissions, getCommission, recordCommissionRun, commissionEvents } from './store.js';
import { commissionToCron, buildCommissionDirective } from './directive.js';
@@ -31,14 +32,19 @@ const eventId = (commissionId) => `creative-commission-${commissionId}`;
const registered = new Set();
let lastSignature = null;
-// Re-arm crons whenever a commission is created/updated/deleted through ANY
-// writer, not just the REST route — mirrors seriesAutopilotScheduler's
-// `settings:updated` subscription. The signature guard makes an unrelated
-// change a cheap no-op.
-commissionEvents.on('commission:changed', () => {
+function triggerResync() {
syncCommissionSchedules().catch((err) =>
console.error(`❌ Creative commission schedule re-sync failed: ${err.message}`));
-});
+}
+
+// Re-arm crons whenever a commission is created/updated/deleted through ANY
+// writer, not just the REST route — decoupled from the HTTP handler.
+commissionEvents.on('commission:changed', triggerResync);
+// Also re-sync on a settings save so a global timezone change re-registers the
+// crons of commissions that use the fallback tz (schedule.timezone == null) —
+// same reason seriesAutopilotScheduler subscribes here. The signature guard
+// makes an unrelated settings save a cheap no-op.
+settingsEvents.on('settings:updated', triggerResync);
/**
* Enabled commissions whose schedule composes into a cron the scheduler honors.
diff --git a/server/services/creativeCommissions/scheduler.test.js b/server/services/creativeCommissions/scheduler.test.js
index 098db250eb..50d07a40f1 100644
--- a/server/services/creativeCommissions/scheduler.test.js
+++ b/server/services/creativeCommissions/scheduler.test.js
@@ -12,6 +12,9 @@ vi.mock('../eventScheduler.js', () => ({
vi.mock('../../lib/timezone.js', () => ({ getUserTimezone: async () => 'UTC' }));
+const settingsEvents = new EventEmitter();
+vi.mock('../settings.js', () => ({ settingsEvents }));
+
const listCommissionsMock = vi.fn();
const getCommissionMock = vi.fn();
const recordRunMock = vi.fn(async () => ({}));
@@ -112,6 +115,14 @@ describe('startCommissionScheduler (no cold-boot generation)', () => {
id: 'creative-commission-commission-1',
})));
});
+
+ it('re-syncs on settings:updated so a global timezone change re-registers crons', async () => {
+ listCommissionsMock.mockResolvedValue([videoCommission()]);
+ settingsEvents.emit('settings:updated', {});
+ await vi.waitFor(() => expect(scheduleMock).toHaveBeenCalledWith(expect.objectContaining({
+ id: 'creative-commission-commission-1',
+ })));
+ });
});
describe('runScheduledCommission gates', () => {
diff --git a/server/services/creativeCommissions/store.js b/server/services/creativeCommissions/store.js
index 4b9882a88f..fe00839e0f 100644
--- a/server/services/creativeCommissions/store.js
+++ b/server/services/creativeCommissions/store.js
@@ -160,22 +160,31 @@ export async function createCommission(input) {
export async function updateCommission(id, patch) {
const store = commissionStore();
- const current = await store.loadOne(id);
- if (!current) throw makeErr(`Commission not found: ${id}`, ERR_NOT_FOUND);
if (patch.schedule) assertValidSchedule(patch.schedule);
- const merged = sanitizeCommission({
- ...current,
- ...patch,
- // Deep-merge the nested objects so a partial brief/generation patch doesn't
- // wipe unspecified fields.
- brief: patch.brief ? { ...current.brief, ...patch.brief } : current.brief,
- schedule: patch.schedule ? { ...current.schedule, ...patch.schedule } : current.schedule,
- generation: patch.generation ? { ...current.generation, ...patch.generation } : current.generation,
- id,
- createdAt: current.createdAt,
- updatedAt: new Date().toISOString(),
+ // Serialize the load→merge→save inside the per-id write queue so a concurrent
+ // scheduler fire (recordCommissionRun, also queued) can't have its run-history
+ // append clobbered by a stale pre-read here — the scheduler-vs-request race
+ // CLAUDE.md requires serializing at the file level.
+ const merged = await store.queueRecordWrite(id, async () => {
+ const current = await store.loadOne(id);
+ if (!current) throw makeErr(`Commission not found: ${id}`, ERR_NOT_FOUND);
+ const next = sanitizeCommission({
+ ...current,
+ ...patch,
+ // Deep-merge the nested objects so a partial brief/generation patch doesn't
+ // wipe unspecified fields. The update-path brief schema carries no defaults
+ // (unlike the create schema), so an omitted key stays omitted and is
+ // preserved here rather than overwritten with a defaulted empty.
+ brief: patch.brief ? { ...current.brief, ...patch.brief } : current.brief,
+ schedule: patch.schedule ? { ...current.schedule, ...patch.schedule } : current.schedule,
+ generation: patch.generation ? { ...current.generation, ...patch.generation } : current.generation,
+ id,
+ createdAt: current.createdAt,
+ updatedAt: new Date().toISOString(),
+ });
+ await store.saveOneNow(id, next);
+ return next;
});
- await store.saveOne(id, merged);
commissionEvents.emit('commission:changed', { id, action: 'update' });
return merged;
}
diff --git a/server/services/creativeCommissions/store.test.js b/server/services/creativeCommissions/store.test.js
index 347071466c..233b0401bd 100644
--- a/server/services/creativeCommissions/store.test.js
+++ b/server/services/creativeCommissions/store.test.js
@@ -1,4 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { creativeCommissionUpdateSchema } from '../../lib/creativeCommissionValidation.js';
// In-memory collectionStore so CRUD is exercised without touching the filesystem.
const records = new Map();
@@ -100,6 +101,16 @@ describe('updateCommission', () => {
expect(updated.createdAt).toBe(created.createdAt);
});
+ it('preserves brief.constraints when a partial brief patch omits them', async () => {
+ // Regression: the create-path brief schema defaults constraints/seedRefs, so
+ // a PATCH that omitted them used to wipe a stored universeId. The update-path
+ // schema carries no defaults, so an omitted key is preserved by the merge.
+ const created = await createCommission(validInput()); // constraints.universeId = 'u-1'
+ const parsed = creativeCommissionUpdateSchema.parse({ brief: { intent: 'reworked' } });
+ const updated = await updateCommission(created.id, parsed);
+ expect(updated.brief.constraints).toEqual({ universeId: 'u-1' });
+ });
+
it('throws NOT_FOUND for an unknown id', async () => {
try { await updateCommission('nope', { enabled: false }); }
catch (e) { expect(e.code).toBe(ERR_NOT_FOUND); }