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 (codex) — budget, name cap, PATCH defaults, tz, sync race

[._.]/ Adam Eivyc60a3cba311a
diff --git a/server/lib/creativeCommissionValidation.js b/server/lib/creativeCommissionValidation.js
index 67088c95b1..f584e5797d 100644
--- a/server/lib/creativeCommissionValidation.js
+++ b/server/lib/creativeCommissionValidation.js
@@ -77,6 +77,14 @@ export const creativeCommissionScheduleSchema = z.object({
if (val.kind === 'CUSTOM' && !val.cron) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['cron'], message: 'CUSTOM schedule requires a cron expression' });
}
+ // Reject an invalid IANA timezone at the request boundary — eventScheduler
+ // passes it to Intl.DateTimeFormat, which throws RangeError on a bad zone; a
+ // bad value persisted here would wedge the whole scheduler sync at register
+ // time. Intl is a global, so this keeps the module a dependency-free leaf.
+ if (val.timezone) {
+ try { new Intl.DateTimeFormat('en-US', { timeZone: val.timezone }); }
+ catch { ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['timezone'], message: 'invalid IANA timezone' }); }
+ }
});
// Render knobs handed to the CD project the commission mints each fire. `model`
@@ -95,6 +103,17 @@ export const creativeCommissionGenerationSchema = z.object({
targetDurationSeconds: z.number().int().min(5).max(600).default(10),
});
+// Generation schema for the UPDATE path: no per-field defaults, so a partial
+// `PATCH { generation: { quality: 'draft' } }` doesn't materialize `aspectRatio`
+// / `targetDurationSeconds` defaults that would overwrite stored values in the
+// service merge — same absent-vs-empty rule as the brief update schema.
+export const creativeCommissionGenerationUpdateSchema = z.object({
+ model: z.string().trim().max(64).nullable().optional(),
+ quality: z.enum(CREATIVE_COMMISSION_QUALITIES).optional(),
+ aspectRatio: z.enum(CREATIVE_COMMISSION_ASPECT_RATIOS).optional(),
+ targetDurationSeconds: z.number().int().min(5).max(600).optional(),
+});
+
export const creativeCommissionCreateSchema = z.object({
name: z.string().trim().min(1).max(COMMISSION_NAME_MAX),
enabled: z.boolean().default(true),
@@ -136,6 +155,6 @@ export const creativeCommissionUpdateSchema = z.object({
targetAbility: z.enum(CREATIVE_COMMISSION_ABILITIES).optional(),
brief: creativeCommissionBriefUpdateSchema.optional(),
schedule: creativeCommissionScheduleSchema.optional(),
- generation: creativeCommissionGenerationSchema.optional(),
+ generation: creativeCommissionGenerationUpdateSchema.optional(),
feedbackWindow: z.number().int().min(0).max(50).optional(),
}).refine((p) => Object.keys(p).length > 0, { message: 'patch must include at least one field' });
diff --git a/server/routes/creativeCommissions.test.js b/server/routes/creativeCommissions.test.js
index e09395b008..ce5e0a7454 100644
--- a/server/routes/creativeCommissions.test.js
+++ b/server/routes/creativeCommissions.test.js
@@ -75,6 +75,13 @@ describe('POST /api/creative-commission', () => {
expect(svc.createCommission).not.toHaveBeenCalled();
});
+ it('rejects an invalid IANA timezone with 400 (before it can wedge the scheduler)', async () => {
+ const res = await request(buildApp()).post('/api/creative-commission')
+ .send({ ...validBody(), schedule: { kind: 'DAILY', atLocalTime: '02:00', timezone: 'Not/AZone' } });
+ expect(res.status).toBe(400);
+ expect(svc.createCommission).not.toHaveBeenCalled();
+ });
+
it('maps a service VALIDATION_ERROR to 400', async () => {
svc.createCommission.mockRejectedValue(Object.assign(new Error('bad cron'), { code: 'VALIDATION_ERROR' }));
const res = await request(buildApp()).post('/api/creative-commission').send(validBody());
diff --git a/server/services/creativeCommissions/scheduler.js b/server/services/creativeCommissions/scheduler.js
index e8d156bd91..e50ca84cdc 100644
--- a/server/services/creativeCommissions/scheduler.js
+++ b/server/services/creativeCommissions/scheduler.js
@@ -31,6 +31,7 @@ import { commissionToCron, buildCommissionDirective } from './directive.js';
const eventId = (commissionId) => `creative-commission-${commissionId}`;
const registered = new Set();
let lastSignature = null;
+let syncTail = Promise.resolve(); // serializes concurrent re-syncs (see syncCommissionSchedules)
function triggerResync() {
syncCommissionSchedules().catch((err) =>
@@ -69,23 +70,41 @@ function signatureOf(active, fallbackTz) {
}
function registerSchedule(entry, timezone) {
- schedule({
- id: eventId(entry.id),
- type: 'cron',
- cron: entry.cron,
- timezone: entry.timezone || timezone,
- handler: () => runScheduledCommission(entry.id),
- metadata: { source: 'creativeCommissionScheduler', commissionId: entry.id },
- });
- registered.add(entry.id);
+ // Resilient: a bad stored cron/timezone (e.g. a hand-edited record) throws in
+ // eventScheduler.schedule → Intl.DateTimeFormat; swallow it per-entry so one
+ // bad commission can't abort the whole sync loop and strand the others.
+ try {
+ schedule({
+ id: eventId(entry.id),
+ type: 'cron',
+ cron: entry.cron,
+ timezone: entry.timezone || timezone,
+ handler: () => runScheduledCommission(entry.id),
+ metadata: { source: 'creativeCommissionScheduler', commissionId: entry.id },
+ });
+ registered.add(entry.id);
+ } catch (err) {
+ console.error(`❌ Creative commission ${entry.id} cron registration failed: ${err.message}`);
+ }
}
/**
* (Re)sync the registered crons to the current commission set. Idempotent and
* safe at boot and after every store mutation. The signature guard makes an
* unrelated re-sync a cheap no-op.
+ *
+ * Serialized on a single tail promise: a settings save and a commission
+ * mutation can fire concurrently, and two syncs with different snapshots
+ * interleaving their mutations of `registered`/`lastSignature` could cancel a
+ * still-enabled commission's cron. Chaining guarantees each sync sees a
+ * consistent view (a re-entrancy guard, fine under the single-user model).
*/
-export async function syncCommissionSchedules(commissions) {
+export function syncCommissionSchedules(commissions) {
+ syncTail = syncTail.then(() => doSyncCommissionSchedules(commissions), () => doSyncCommissionSchedules(commissions));
+ return syncTail;
+}
+
+async function doSyncCommissionSchedules(commissions) {
const list = commissions || await listCommissions().catch(() => []);
const active = activeCommissions(list);
const timezone = await getUserTimezone().catch(() => 'UTC');
@@ -121,6 +140,7 @@ export function stopCommissionScheduler() {
* each plan step through the gated `dispatchCreativeTool`).
*/
export async function runScheduledCommission(commissionId) {
+ let charged = false;
try {
const commission = await getCommission(commissionId).catch(() => null);
if (!commission || commission.enabled === false) return;
@@ -131,7 +151,7 @@ export async function runScheduledCommission(commissionId) {
// Gate on creative autonomy mode + daily cos budget BEFORE spawning anything
// (the planner is itself an LLM call) — honors "off ⇒ no generation" and the
// no-cold-LLM policy.
- const [{ loadState }, { getCreativeAutonomyMode }, { getDomainBudgetStatus }] = await Promise.all([
+ const [{ loadState }, { getCreativeAutonomyMode }, { getDomainBudgetStatus, recordDomainUsage }] = await Promise.all([
import('../cosState.js'),
import('../../lib/domainAutonomy.js'),
import('../domainUsage.js'),
@@ -155,6 +175,16 @@ export async function runScheduledCommission(commissionId) {
return;
}
+ // Charge the planner action against the shared daily cos budget on admission.
+ // The planner LLM call is enqueued via task:ready and bypasses
+ // dequeueNextTask's allowance check, so without this two commissions firing
+ // in the same tick could each observe the same remaining budget and overrun
+ // the user's cap. Charging here narrows that window (refunded below if the
+ // spawn fails). Not a hard reservation — the deeper fix is a shared
+ // admission gate at the planner boundary (tracked on #2657).
+ await recordDomainUsage('cos', { actions: 1 }).catch(() => {});
+ charged = true;
+
const [{ createProject }, { advanceAfterPlanStepSettled }, { defaultVideoModelId }] = await Promise.all([
import('../creativeDirector/local.js'),
import('../creativeDirector/planAdvance.js'),
@@ -163,8 +193,16 @@ export async function runScheduledCommission(commissionId) {
const directive = buildCommissionDirective(commission);
const gen = commission.generation || {};
+ // createProject prefixes "Creative Director: " (19 chars) before a
+ // mediaCollections name capped at 80, so cap our derived name at 61 — a long
+ // commission name would otherwise fail the collection create on every run.
+ const dateSuffix = ` — ${new Date().toISOString().slice(0, 10)}`; // 13 chars
+ const maxBase = 61 - dateSuffix.length;
+ const baseName = commission.name.length > maxBase
+ ? `${commission.name.slice(0, maxBase - 1)}…`
+ : commission.name;
const project = await createProject({
- name: `${commission.name} — ${new Date().toISOString().slice(0, 10)}`,
+ name: `${baseName}${dateSuffix}`,
aspectRatio: gen.aspectRatio || '16:9',
quality: gen.quality || 'standard',
modelId: gen.model || defaultVideoModelId(),
@@ -184,6 +222,11 @@ export async function runScheduledCommission(commissionId) {
await advanceAfterPlanStepSettled(project.id);
} catch (err) {
console.error(`❌ Creative commission ${commissionId} fire failed: ${err?.message || err}`);
+ // Refund the reserved planner action — the spawn threw, so it never ran.
+ if (charged) {
+ const { recordDomainUsage } = await import('../domainUsage.js').catch(() => ({}));
+ await recordDomainUsage?.('cos', { actions: -1 }).catch(() => {});
+ }
await recordCommissionRun(commissionId, { status: 'failed', error: err?.message || String(err) }).catch(() => {});
}
}
diff --git a/server/services/creativeCommissions/scheduler.test.js b/server/services/creativeCommissions/scheduler.test.js
index 50d07a40f1..21ee0f960e 100644
--- a/server/services/creativeCommissions/scheduler.test.js
+++ b/server/services/creativeCommissions/scheduler.test.js
@@ -38,7 +38,11 @@ vi.mock('../cosState.js', () => ({ loadState: (...a) => loadStateMock(...a) }));
const creativeModeMock = vi.fn(() => 'execute');
vi.mock('../../lib/domainAutonomy.js', () => ({ getCreativeAutonomyMode: (...a) => creativeModeMock(...a) }));
const budgetMock = vi.fn(async () => ({ withinBudget: true }));
-vi.mock('../domainUsage.js', () => ({ getDomainBudgetStatus: (...a) => budgetMock(...a) }));
+const recordUsageMock = vi.fn(async () => {});
+vi.mock('../domainUsage.js', () => ({
+ getDomainBudgetStatus: (...a) => budgetMock(...a),
+ recordDomainUsage: (...a) => recordUsageMock(...a),
+}));
const {
activeCommissions,
@@ -135,6 +139,24 @@ describe('runScheduledCommission gates', () => {
}));
expect(advanceMock).toHaveBeenCalledWith('cd-xyz');
expect(recordRunMock).toHaveBeenCalledWith('commission-1', expect.objectContaining({ status: 'started', projectId: 'cd-xyz' }));
+ // Reserves the planner action against the cos budget on admission.
+ expect(recordUsageMock).toHaveBeenCalledWith('cos', { actions: 1 });
+ });
+
+ it('caps the derived project name so createCollection (80-char limit) never fails', async () => {
+ getCommissionMock.mockResolvedValue(videoCommission({ name: 'X'.repeat(200) }));
+ await runScheduledCommission('commission-1');
+ const { name } = createProjectMock.mock.calls[0][0];
+ // "Creative Director: " (19) + name must be ≤ 80 → name ≤ 61.
+ expect(name.length).toBeLessThanOrEqual(61);
+ expect(name.endsWith(new Date().toISOString().slice(0, 10))).toBe(true);
+ });
+
+ it('does not charge the budget when a gate skips the fire', async () => {
+ creativeModeMock.mockReturnValue('off');
+ getCommissionMock.mockResolvedValue(videoCommission());
+ await runScheduledCommission('commission-1');
+ expect(recordUsageMock).not.toHaveBeenCalled();
});
it('skips generation (records skipped) when creative autonomy is off', async () => {
diff --git a/server/services/creativeCommissions/store.js b/server/services/creativeCommissions/store.js
index fe00839e0f..ff457a15c5 100644
--- a/server/services/creativeCommissions/store.js
+++ b/server/services/creativeCommissions/store.js
@@ -172,10 +172,18 @@ export async function updateCommission(id, patch) {
...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,
+ // wipe unspecified fields. The update-path brief/generation schemas carry
+ // no defaults (unlike the create schemas), so an omitted key stays omitted
+ // and is preserved here rather than overwritten with a defaulted empty.
+ // `constraints` is merged one level deeper too, so `{ universeId }` in a
+ // patch doesn't drop a stored `seriesId`.
+ brief: patch.brief ? {
+ ...current.brief,
+ ...patch.brief,
+ constraints: patch.brief.constraints
+ ? { ...current.brief.constraints, ...patch.brief.constraints }
+ : current.brief.constraints,
+ } : current.brief,
schedule: patch.schedule ? { ...current.schedule, ...patch.schedule } : current.schedule,
generation: patch.generation ? { ...current.generation, ...patch.generation } : current.generation,
id,
diff --git a/server/services/creativeCommissions/store.test.js b/server/services/creativeCommissions/store.test.js
index 233b0401bd..9e4ea5a6dc 100644
--- a/server/services/creativeCommissions/store.test.js
+++ b/server/services/creativeCommissions/store.test.js
@@ -111,6 +111,25 @@ describe('updateCommission', () => {
expect(updated.brief.constraints).toEqual({ universeId: 'u-1' });
});
+ it('deep-merges constraints so a partial constraints patch keeps the other key', async () => {
+ const created = await createCommission({
+ ...validInput(),
+ brief: { intent: 'x', constraints: { universeId: 'u-1', seriesId: 's-1' } },
+ });
+ const parsed = creativeCommissionUpdateSchema.parse({ brief: { constraints: { universeId: 'u-2' } } });
+ const updated = await updateCommission(created.id, parsed);
+ expect(updated.brief.constraints).toEqual({ universeId: 'u-2', seriesId: 's-1' });
+ });
+
+ it('preserves omitted generation fields on a partial generation patch', async () => {
+ const created = await createCommission(validInput()); // quality 'high', aspect '9:16', duration 20
+ const parsed = creativeCommissionUpdateSchema.parse({ generation: { quality: 'draft' } });
+ const updated = await updateCommission(created.id, parsed);
+ expect(updated.generation.quality).toBe('draft');
+ expect(updated.generation.aspectRatio).toBe('9:16'); // preserved, not defaulted to 16:9
+ expect(updated.generation.targetDurationSeconds).toBe(20); // preserved, not defaulted to 10
+ });
+
it('throws NOT_FOUND for an unknown id', async () => {
try { await updateCommission('nope', { enabled: false }); }
catch (e) { expect(e.code).toBe(ERR_NOT_FOUND); }