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-2769): per-output-type Creative Commissions via ability adapters

[._.]/ Adam Eivyc4f392064e50
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 5abc15ea48..0a63a107b5 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Added
+- [issue-2769] **Creative Commissions can now make more than video — pick the output type and the params follow.** A commission's editor gains a **Creative output** selector: choose Video, Image, Music, Music video, or Series, and the generation parameters change to fit (an Image commission asks for an image count and aspect ratio with no duration; Music asks for a length; Series asks for an episode count), instead of always showing video controls. Behind the scenes each type also gets its own tailored brief so the Creative Director is told exactly what to make (produce a still image, compose a music bed, start a new series) and which tools to use — rather than being handed the whole menu and left to guess from your intent. Existing video commissions are unchanged and keep running as before; a scheduled run whose type isn't recognized is skipped rather than mis-made as a video.
+
- [issue-2757] **The "set your birth date" prompt now tells you when your date is broken rather than just missing.** When your Character sheet or the CyberCity level badges can't show a level, they used to always say "set your birth date" — even if you'd already entered one that turned out to be invalid, dated in the future, or stored in a config file that couldn't be read. Now those cases show a distinct "fix your birth date" prompt (with a warning color) so you're not told to set a date you already entered, while a genuinely unset date still gets the original friendly "set" prompt. Every prompt still deep-links to the age editor where the field lives. The distinction is carried as an explicit, per-machine-derived status that's never persisted or synced between machines.
- [issue-2674] **Your Character sheet now has skills that reflect how you actually use PortOS.** Six skills — Wordsmith (universes, Writers Room works, and catalog records), Mentalist (POST), Vitalist (health logging), Strategist (goal discipline), Archivist (Brain/memory), and Auteur (media) — level up from the work you've already done, on a curve where each doubling of use earns a level, so they climb quickly at first and then ask for real commitment. Nothing new is tracked to make this work: each skill reads the stats its domain already keeps, so the skills are accurate from the moment you upgrade rather than starting everyone at zero. A domain you've never touched is honestly level 0, and a domain whose stats can't be read says "Unavailable" rather than pretending it's zero. Skills are computed fresh on every read and never saved or synced between your machines — usage differs per machine, so syncing them would let the laptop you barely open overwrite the desktop you live in.
diff --git a/client/src/components/creative-commission/CommissionConfigForm.jsx b/client/src/components/creative-commission/CommissionConfigForm.jsx
index 7b77488680..8995baa6e5 100644
--- a/client/src/components/creative-commission/CommissionConfigForm.jsx
+++ b/client/src/components/creative-commission/CommissionConfigForm.jsx
@@ -15,7 +15,10 @@ import { useEffect, useMemo, useState } from 'react';
import ProviderModelSelector from '../ProviderModelSelector';
import { isProcessProvider } from '../../utils/providers';
import { getProviders } from '../../services/api';
-import { WEEKDAYS, inputCls, labelCls, describeSchedule } from './commissionForm.js';
+import {
+ WEEKDAYS, inputCls, labelCls, describeSchedule,
+ ABILITY_OPTIONS, GENERATION_FIELDS_BY_ABILITY, mergeGenerationForAbility,
+} from './commissionForm.js';
export default function CommissionConfigForm({ form, patchForm, saving, onSave, onCancel, saveLabel = 'Save' }) {
return (
@@ -43,6 +46,31 @@ export default function CommissionConfigForm({ form, patchForm, saving, onSave,
</label>
</section>
+ {/* Output type — drives which generation params + directive the run uses */}
+ <section className="space-y-3 border-t border-port-border pt-4">
+ <div>
+ <label className={labelCls} htmlFor="commission-ability">Creative output</label>
+ <select
+ id="commission-ability"
+ className={inputCls}
+ value={form.targetAbility}
+ onChange={(e) => {
+ const next = e.target.value;
+ // Re-seed the generation params for the new type (carrying over any
+ // overlapping value) BEFORE switching the type, so the rendered
+ // fields and the payload always match the selected output.
+ patchForm(['generation'], mergeGenerationForAbility(next, form.generation));
+ patchForm(['targetAbility'], next);
+ }}
+ >
+ {ABILITY_OPTIONS.map((o) => <option key={o.id} value={o.id}>{o.label}</option>)}
+ </select>
+ <p className="text-xs text-gray-500 mt-1">
+ What each scheduled run produces. The parameters and the Creative Director&apos;s brief adapt to this type.
+ </p>
+ </div>
+ </section>
+
{/* Brief */}
<section className="space-y-3 border-t border-port-border pt-4">
<h3 className="text-sm font-semibold text-gray-200">Brief</h3>
@@ -152,50 +180,8 @@ export default function CommissionConfigForm({ form, patchForm, saving, onSave,
<p className="text-xs text-gray-500">{describeSchedule(form.schedule)}</p>
</section>
- {/* Generation */}
- <section className="space-y-3 border-t border-port-border pt-4">
- <h3 className="text-sm font-semibold text-gray-200">Generation (video)</h3>
- <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
- <div>
- <label className={labelCls} htmlFor="commission-quality">Quality</label>
- <select
- id="commission-quality"
- className={inputCls}
- value={form.generation.quality}
- onChange={(e) => patchForm(['generation', 'quality'], e.target.value)}
- >
- <option value="draft">Draft</option>
- <option value="standard">Standard</option>
- <option value="high">High</option>
- </select>
- </div>
- <div>
- <label className={labelCls} htmlFor="commission-aspect">Aspect ratio</label>
- <select
- id="commission-aspect"
- className={inputCls}
- value={form.generation.aspectRatio}
- onChange={(e) => patchForm(['generation', 'aspectRatio'], e.target.value)}
- >
- <option value="16:9">16:9</option>
- <option value="9:16">9:16</option>
- <option value="1:1">1:1</option>
- </select>
- </div>
- <div>
- <label className={labelCls} htmlFor="commission-duration">Duration (sec)</label>
- <input
- id="commission-duration"
- type="number"
- min={5}
- max={600}
- className={inputCls}
- value={form.generation.targetDurationSeconds}
- onChange={(e) => patchForm(['generation', 'targetDurationSeconds'], e.target.value)}
- />
- </div>
- </div>
- </section>
+ {/* Generation — fields adapt to the selected output type (#2769) */}
+ <GenerationSection ability={form.targetAbility} generation={form.generation} patchForm={patchForm} />
{/* AI provider & model — who processes this commission */}
<section className="space-y-2 border-t border-port-border pt-4">
@@ -246,6 +232,51 @@ export default function CommissionConfigForm({ form, patchForm, saving, onSave,
);
}
+// Generation params for the selected output type (#2769). Renders the ability's
+// field descriptors (GENERATION_FIELDS_BY_ABILITY) generically so all five types
+// share one layout — a select for enum fields, a bounded number input otherwise.
+// The label names the type so it's clear which output these knobs drive.
+function GenerationSection({ ability, generation, patchForm }) {
+ const fields = GENERATION_FIELDS_BY_ABILITY[ability] || GENERATION_FIELDS_BY_ABILITY.video;
+ const abilityLabel = (ABILITY_OPTIONS.find((o) => o.id === ability) || ABILITY_OPTIONS[0]).label;
+ return (
+ <section className="space-y-3 border-t border-port-border pt-4">
+ <h3 className="text-sm font-semibold text-gray-200">Generation ({abilityLabel})</h3>
+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
+ {fields.map((field) => {
+ const id = `commission-gen-${field.key}`;
+ const value = generation?.[field.key] ?? '';
+ return (
+ <div key={field.key}>
+ <label className={labelCls} htmlFor={id}>{field.label}</label>
+ {field.type === 'select' ? (
+ <select
+ id={id}
+ className={inputCls}
+ value={value}
+ onChange={(e) => patchForm(['generation', field.key], e.target.value)}
+ >
+ {field.options.map(([val, lbl]) => <option key={val} value={val}>{lbl}</option>)}
+ </select>
+ ) : (
+ <input
+ id={id}
+ type="number"
+ min={field.min}
+ max={field.max}
+ className={inputCls}
+ value={value}
+ onChange={(e) => patchForm(['generation', field.key], e.target.value)}
+ />
+ )}
+ </div>
+ );
+ })}
+ </div>
+ </section>
+ );
+}
+
// AI provider/model picker for the commission's CD cognitive stages (treatment +
// plan). Mirrors SeriesLlmPicker: fetches the provider list, drives the shared
// ProviderModelSelector, and reports changes up to form state via `onChange`.
diff --git a/client/src/components/creative-commission/commissionForm.js b/client/src/components/creative-commission/commissionForm.js
index 169cbd5130..5b2d840cc0 100644
--- a/client/src/components/creative-commission/commissionForm.js
+++ b/client/src/components/creative-commission/commissionForm.js
@@ -12,6 +12,89 @@ export const WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday',
export const inputCls = 'w-full bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-gray-100 focus:outline-none focus:border-port-accent';
export const labelCls = 'block text-xs font-medium text-gray-400 mb-1';
+// Creative-output types the commission can produce (#2769). Mirrors the server
+// enum CREATIVE_COMMISSION_ABILITIES; `video` stays first (the default).
+export const ABILITY_OPTIONS = [
+ { id: 'video', label: 'Video' },
+ { id: 'image', label: 'Image' },
+ { id: 'music', label: 'Music' },
+ { id: 'music-video', label: 'Music video' },
+ { id: 'series', label: 'Series' },
+];
+
+const QUALITY_FIELD = { key: 'quality', label: 'Quality', type: 'select', options: [['draft', 'Draft'], ['standard', 'Standard'], ['high', 'High']] };
+const ASPECT_FIELD = { key: 'aspectRatio', label: 'Aspect ratio', type: 'select', options: [['16:9', '16:9'], ['9:16', '9:16'], ['1:1', '1:1']] };
+const DURATION_FIELD = { key: 'targetDurationSeconds', label: 'Duration (sec)', type: 'number', min: 5, max: 600 };
+
+// Per-ability generation field descriptors — the client mirror of the server's
+// ABILITY_GENERATION_SPEC (server/lib/creativeCommissionValidation.js). The
+// config form renders exactly these fields for the selected type; keep the two in
+// sync (the mirror is asserted in commissionForm.test.js).
+export const GENERATION_FIELDS_BY_ABILITY = {
+ video: [QUALITY_FIELD, ASPECT_FIELD, DURATION_FIELD],
+ image: [QUALITY_FIELD, ASPECT_FIELD, { key: 'imageCount', label: 'Image count', type: 'number', min: 1, max: 6 }],
+ music: [{ key: 'lengthSeconds', label: 'Length (sec)', type: 'number', min: 5, max: 600 }],
+ 'music-video': [QUALITY_FIELD, ASPECT_FIELD, DURATION_FIELD],
+ series: [{ key: 'episodeCount', label: 'Episodes', type: 'number', min: 1, max: 6 }],
+};
+
+// Per-ability generation defaults (mirror of the server spec defaults). Used to
+// project a stored record into the form and to seed the fields when the user
+// switches output type.
+export const GENERATION_DEFAULTS_BY_ABILITY = {
+ video: { quality: 'standard', aspectRatio: '16:9', targetDurationSeconds: 10 },
+ image: { quality: 'standard', aspectRatio: '16:9', imageCount: 1 },
+ music: { lengthSeconds: 30 },
+ 'music-video': { quality: 'standard', aspectRatio: '16:9', targetDurationSeconds: 10 },
+ series: { episodeCount: 1 },
+};
+
+function abilityOr(ability) {
+ return GENERATION_DEFAULTS_BY_ABILITY[ability] ? ability : 'video';
+}
+
+// Project a stored generation object into the form for a given ability: fill each
+// of the ability's fields from the record, falling back to the default. Only the
+// ability's own keys appear, so switching types never carries a stale key.
+export function generationToForm(ability, generation) {
+ const a = abilityOr(ability);
+ const defaults = GENERATION_DEFAULTS_BY_ABILITY[a];
+ const out = {};
+ for (const key of Object.keys(defaults)) {
+ const v = generation?.[key];
+ out[key] = v === undefined || v === null ? defaults[key] : v;
+ }
+ return out;
+}
+
+// When the user switches output type, seed the new type's fields with the type's
+// defaults but carry over any overlapping value the user already set (e.g. keep
+// their quality/aspectRatio when going video → image).
+export function mergeGenerationForAbility(nextAbility, currentGeneration) {
+ const a = abilityOr(nextAbility);
+ const defaults = GENERATION_DEFAULTS_BY_ABILITY[a];
+ const out = {};
+ for (const key of Object.keys(defaults)) {
+ const v = currentGeneration?.[key];
+ out[key] = v === undefined || v === null ? defaults[key] : v;
+ }
+ return out;
+}
+
+// Build the API generation payload for the current ability: emit only that
+// ability's keys, coercing number fields (form <input type=number> values are
+// strings). Mirrors the server superRefine, which rejects off-type keys.
+export function generationToPayload(ability, generation) {
+ const a = abilityOr(ability);
+ const fields = GENERATION_FIELDS_BY_ABILITY[a];
+ const out = {};
+ for (const field of fields) {
+ const v = generation?.[field.key];
+ out[field.key] = field.type === 'number' ? Number(v) : v;
+ }
+ return out;
+}
+
// Human-readable cadence summary for the list card + detail header.
export function describeSchedule(schedule) {
if (!schedule) return 'No schedule';
@@ -48,11 +131,9 @@ export function toForm(c) {
weekdaysOnly: c.schedule?.weekdaysOnly === true,
cron: c.schedule?.cron || '',
},
- generation: {
- quality: c.generation?.quality || 'standard',
- aspectRatio: c.generation?.aspectRatio || '16:9',
- targetDurationSeconds: c.generation?.targetDurationSeconds || 10,
- },
+ // Per-ability generation (#2769): only the selected type's fields, filled
+ // from the record or the type's defaults.
+ generation: generationToForm(c.targetAbility || 'video', c.generation),
// Which AI provider/model processes the commission's CD stages. Empty
// providerId → the install's default AI Assignment.
assignment: {
@@ -87,11 +168,8 @@ export function toPayload(form) {
styleSpec: form.brief.styleSpec,
},
schedule: s,
- generation: {
- quality: form.generation.quality,
- aspectRatio: form.generation.aspectRatio,
- targetDurationSeconds: Number(form.generation.targetDurationSeconds),
- },
+ // Emit only the selected type's generation keys (#2769), coercing numbers.
+ generation: generationToPayload(form.targetAbility, form.generation),
// Send the full pin every save; a provider-less choice clears the model too
// (the server drops a dangling model, but keeping the payload clean avoids a
// pointless round-trip through the sanitizer's normalization).
@@ -122,5 +200,17 @@ export function validateForm(form) {
if (form.feedbackWindow === '' || !Number.isInteger(fw) || fw < 0 || fw > 50) {
return 'Feedback window must be a whole number from 0 to 50';
}
+ // Per-ability numeric fields (#2769): a cleared/out-of-range number would coerce
+ // to NaN/0 in the payload and 400 at the server — reject it here with a clear
+ // message rather than guessing intent.
+ const fields = GENERATION_FIELDS_BY_ABILITY[abilityOr(form.targetAbility)] || [];
+ for (const field of fields) {
+ if (field.type !== 'number') continue;
+ const raw = form.generation?.[field.key];
+ const n = Number(raw);
+ if (raw === '' || raw === null || raw === undefined || !Number.isInteger(n) || n < field.min || n > field.max) {
+ return `${field.label} must be a whole number from ${field.min} to ${field.max}`;
+ }
+ }
return null;
}
diff --git a/client/src/components/creative-commission/commissionForm.test.js b/client/src/components/creative-commission/commissionForm.test.js
index 8719085482..612cc87e84 100644
--- a/client/src/components/creative-commission/commissionForm.test.js
+++ b/client/src/components/creative-commission/commissionForm.test.js
@@ -2,6 +2,8 @@ import { describe, it, expect } from 'vitest';
import {
toForm, toPayload, blankForm, patchFormState, validateForm,
describeSchedule, describeAssignment,
+ ABILITY_OPTIONS, GENERATION_FIELDS_BY_ABILITY, GENERATION_DEFAULTS_BY_ABILITY,
+ generationToForm, mergeGenerationForAbility, generationToPayload,
} from './commissionForm.js';
describe('commissionForm helpers', () => {
@@ -117,4 +119,62 @@ describe('commissionForm helpers', () => {
expect(describeAssignment({ providerId: 'claude', model: 'opus' })).toBe('claude · opus');
});
});
+
+ describe('output-type generation params (#2769)', () => {
+ it('exposes every ability with a field list and defaults', () => {
+ for (const { id } of ABILITY_OPTIONS) {
+ expect(Array.isArray(GENERATION_FIELDS_BY_ABILITY[id])).toBe(true);
+ expect(GENERATION_DEFAULTS_BY_ABILITY[id]).toBeTruthy();
+ // Every declared field has a matching default key.
+ for (const field of GENERATION_FIELDS_BY_ABILITY[id]) {
+ expect(GENERATION_DEFAULTS_BY_ABILITY[id]).toHaveProperty(field.key);
+ }
+ }
+ });
+
+ it('generationToForm fills the ability defaults and keeps only that ability keys', () => {
+ expect(generationToForm('image', {})).toEqual({ quality: 'standard', aspectRatio: '16:9', imageCount: 1 });
+ // A stored video key is ignored when projecting as image.
+ expect(generationToForm('image', { imageCount: 4, targetDurationSeconds: 30 })).toEqual({ quality: 'standard', aspectRatio: '16:9', imageCount: 4 });
+ expect(generationToForm('music', { lengthSeconds: 60 })).toEqual({ lengthSeconds: 60 });
+ });
+
+ it('toForm projects a stored non-video record onto its ability fields', () => {
+ const f = toForm({ targetAbility: 'series', brief: { intent: 'noir' }, generation: { episodeCount: 3 } });
+ expect(f.targetAbility).toBe('series');
+ expect(f.generation).toEqual({ episodeCount: 3 });
+ });
+
+ it('mergeGenerationForAbility carries overlapping keys across a type switch', () => {
+ // video → image keeps quality/aspectRatio, seeds imageCount default, drops duration.
+ expect(mergeGenerationForAbility('image', { quality: 'high', aspectRatio: '9:16', targetDurationSeconds: 20 }))
+ .toEqual({ quality: 'high', aspectRatio: '9:16', imageCount: 1 });
+ // image → music keeps nothing overlapping, just the music default.
+ expect(mergeGenerationForAbility('music', { imageCount: 4 })).toEqual({ lengthSeconds: 30 });
+ });
+
+ it('generationToPayload emits only the ability keys and coerces numbers', () => {
+ // number inputs arrive as strings from the DOM.
+ expect(generationToPayload('image', { quality: 'standard', aspectRatio: '1:1', imageCount: '3' }))
+ .toEqual({ quality: 'standard', aspectRatio: '1:1', imageCount: 3 });
+ expect(generationToPayload('music', { lengthSeconds: '45' })).toEqual({ lengthSeconds: 45 });
+ });
+
+ it('toPayload round-trips a non-video commission', () => {
+ const form = toForm({ name: 'Daily Stills', targetAbility: 'image', brief: { intent: 'x' }, generation: { imageCount: 2 } });
+ const payload = toPayload(form);
+ expect(payload.targetAbility).toBe('image');
+ expect(payload.generation).toEqual({ quality: 'standard', aspectRatio: '16:9', imageCount: 2 });
+ });
+
+ it('validateForm rejects an out-of-range per-ability number', () => {
+ const base = { name: 'x', brief: { intent: 'y' }, feedbackWindow: 5 };
+ const okImage = { ...base, targetAbility: 'image', generation: { quality: 'standard', aspectRatio: '16:9', imageCount: 3 } };
+ expect(validateForm(okImage)).toBeNull();
+ const badImage = { ...base, targetAbility: 'image', generation: { quality: 'standard', aspectRatio: '16:9', imageCount: 99 } };
+ expect(validateForm(badImage)).toMatch(/Image count/);
+ const clearedMusic = { ...base, targetAbility: 'music', generation: { lengthSeconds: '' } };
+ expect(validateForm(clearedMusic)).toMatch(/Length/);
+ });
+ });
});
diff --git a/server/lib/creativeCommissionValidation.js b/server/lib/creativeCommissionValidation.js
index 391163cf52..572ace54d8 100644
--- a/server/lib/creativeCommissionValidation.js
+++ b/server/lib/creativeCommissionValidation.js
@@ -16,10 +16,37 @@ import { z } from 'zod';
// suite doesn't drag the scheduler graph along. The authoritative cron-validity
// check (isValidCron) lives in the service layer, not here.
-// Phase 1 supports `video` only. The enum is deliberately narrow so a user can't
-// create a commission that silently never runs — Phase 3/4 widen it (image,
-// universe, series, story, writers-room, music) alongside the ability adapter.
-export const CREATIVE_COMMISSION_ABILITIES = Object.freeze(['video']);
+// Supported creative-output types (#2769). Each is backed by an ability adapter
+// (server/services/creativeCommissions/abilityAdapters.js) that owns its
+// generation params, its CD directive, and its createProject mapping. `video`
+// stays first so it remains the default and pre-#2769 records (which have no
+// explicit type or default to `video`) keep running unchanged. The broader set
+// the original Phase-1 note named (`universe`, `story`, `writers-room`) stays
+// future work under epic #2657 — only the five the request enumerated ship here.
+export const CREATIVE_COMMISSION_ABILITIES = Object.freeze(['video', 'image', 'music', 'music-video', 'series']);
+
+// Per-ability generation spec — the SINGLE SOURCE OF TRUTH for which render/knob
+// keys each output type carries and their defaults. Consumed by the create-path
+// superRefine below (rejects a key that doesn't belong to the chosen type), by
+// the ability adapter's `sanitizeGeneration` (fills defaults + preserves only
+// these keys), and mirrored on the client (commissionForm.js
+// GENERATION_FIELDS_BY_ABILITY). `model` is accepted on every type (an optional
+// per-type engine/model override) and so is not repeated in each `keys` list —
+// the superset schema and the adapter both treat it as universally allowed.
+export const ABILITY_GENERATION_SPEC = Object.freeze({
+ video: { keys: ['quality', 'aspectRatio', 'targetDurationSeconds'], defaults: { quality: 'standard', aspectRatio: '16:9', targetDurationSeconds: 10 } },
+ image: { keys: ['quality', 'aspectRatio', 'imageCount'], defaults: { quality: 'standard', aspectRatio: '16:9', imageCount: 1 } },
+ music: { keys: ['lengthSeconds'], defaults: { lengthSeconds: 30 } },
+ 'music-video': { keys: ['quality', 'aspectRatio', 'targetDurationSeconds'], defaults: { quality: 'standard', aspectRatio: '16:9', targetDurationSeconds: 10 } },
+ series: { keys: ['episodeCount'], defaults: { episodeCount: 1 } },
+});
+
+// Keys allowed for a given ability (the spec keys + the universal `model`). Used
+// by the create-path superRefine to flag a param that doesn't belong to the type.
+export function generationKeysForAbility(ability) {
+ const spec = ABILITY_GENERATION_SPEC[ability] || ABILITY_GENERATION_SPEC.video;
+ return ['model', ...spec.keys];
+}
// Schedule cadence kinds. DAILY/WEEKLY are composed into a cron by the service;
// CUSTOM carries a raw 5-field cron the service validates via isValidCron.
@@ -87,33 +114,61 @@ export const creativeCommissionScheduleSchema = z.object({
}
});
-// Render knobs handed to the CD project the commission mints each fire. `model`
-// is the CD video modelId (an LTX variant); absent → the install's default video
-// model at fire time.
-// No object-level `.default({})` here: it would inject a `generation: {}` key
-// even when the caller omits generation, which makes an empty PATCH body parse
-// non-empty (defeating the update schema's "at least one field" refine) and
-// forces every update to rewrite generation. sanitizeCommission fills the
-// generation defaults instead; the per-field defaults still apply when the
-// object IS present but partial.
+// Render knobs handed to the CD project the commission mints each fire. This is
+// a SUPERSET over every output type's params (#2769) — each field is validated
+// for type/enum/range but left optional, and which fields actually apply is
+// decided per-ability by the create-path superRefine (below) and the adapter's
+// `sanitizeGeneration`. `model` is a universal optional engine/model override
+// (the CD video modelId — an LTX variant — for video; absent → the install's
+// default at fire time).
+// No object-level `.default({})` and NO per-field defaults here: a `.default({})`
+// would inject a `generation: {}` key even when the caller omits generation,
+// making an empty PATCH body parse non-empty (defeating the update schema's "at
+// least one field" refine), and field defaults would overwrite stored values on
+// a partial PATCH (the absent-vs-empty footgun). sanitizeCommission fills the
+// per-ability defaults instead. The create and update paths share the same
+// superset (the create-path per-ability strictness is added by the superRefine
+// on the create schema, not here) so a type-specific key like `imageCount` or
+// `episodeCount` is never silently stripped before it reaches sanitizeCommission.
export const creativeCommissionGenerationSchema = z.object({
- model: z.string().trim().max(64).nullable().optional(),
- quality: z.enum(CREATIVE_COMMISSION_QUALITIES).default('standard'),
- aspectRatio: z.enum(CREATIVE_COMMISSION_ASPECT_RATIOS).default('16:9'),
- 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(),
+ imageCount: z.number().int().min(1).max(6).optional(),
+ lengthSeconds: z.number().int().min(5).max(600).optional(),
+ episodeCount: z.number().int().min(1).max(6).optional(),
});
+// The UPDATE path shares the same superset — every field optional, no defaults —
+// so a partial `PATCH { generation: { quality: 'draft' } }` doesn't materialize
+// other keys that would overwrite stored values in the service merge, and a
+// type-specific key still round-trips. (A PATCH may omit `targetAbility`, so the
+// per-ability strictness the create superRefine adds can't run here; the
+// adapter's `sanitizeGeneration` is the backstop that drops off-type keys.)
+export const creativeCommissionGenerationUpdateSchema = creativeCommissionGenerationSchema;
+
+// Reusable superRefine: when `generation` is present, reject any key that does
+// not belong to the chosen `targetAbility` (per ABILITY_GENERATION_SPEC), so a
+// mistaken param (e.g. `targetDurationSeconds` on an `image` commission, or
+// `episodeCount` on a `video` one) is a 400 at the boundary rather than silently
+// dropped by the sanitizer. Runs only where the ability is known (the create
+// schema, whose `targetAbility` defaults to `video`).
+function refineGenerationForAbility(data, ctx) {
+ if (!data || typeof data.generation !== 'object' || data.generation === null) return;
+ const ability = data.targetAbility || 'video';
+ const allowed = new Set(generationKeysForAbility(ability));
+ for (const key of Object.keys(data.generation)) {
+ if (!allowed.has(key)) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ['generation', key],
+ message: `'${key}' is not a valid generation param for a '${ability}' commission`,
+ });
+ }
+ }
+}
+
// The LLM provider/model that PROCESSES the commission — i.e. the Creative
// Director cognitive stages (treatment + production plan) the scheduled fire
// runs as CoS agent tasks. `providerId`/`model` are the same shape the CD
@@ -143,7 +198,7 @@ export const creativeCommissionCreateSchema = z.object({
// run's prompt (Phase 2 populates `feedback`; kept here so the field is stable
// and editable from creation). 0 disables conditioning.
feedbackWindow: z.number().int().min(0).max(50).default(5),
-});
+}).superRefine(refineGenerationForAbility);
// Brief schema for the UPDATE path: every field optional and — critically — NO
// defaults. The create-path `creativeCommissionBriefSchema` defaults
diff --git a/server/routes/creativeCommissions.test.js b/server/routes/creativeCommissions.test.js
index a6bd7a954d..30c1e93685 100644
--- a/server/routes/creativeCommissions.test.js
+++ b/server/routes/creativeCommissions.test.js
@@ -77,8 +77,27 @@ describe('POST /api/creative-commission', () => {
expect(svc.createCommission).not.toHaveBeenCalled();
});
- it('rejects an unsupported target ability with 400 (Phase 1 is video-only)', async () => {
- const res = await request(buildApp()).post('/api/creative-commission').send({ ...validBody(), targetAbility: 'music' });
+ it('accepts a non-video output type with its own generation params (#2769)', async () => {
+ svc.createCommission.mockResolvedValue({ id: 'commission-2', name: 'Daily Stills' });
+ const res = await request(buildApp()).post('/api/creative-commission')
+ .send({ ...validBody(), targetAbility: 'image', generation: { imageCount: 3, aspectRatio: '9:16' } });
+ expect(res.status).toBe(201);
+ expect(svc.createCommission).toHaveBeenCalledWith(expect.objectContaining({
+ targetAbility: 'image',
+ generation: expect.objectContaining({ imageCount: 3 }),
+ }));
+ });
+
+ it('rejects an UNKNOWN target ability with 400 (#2769)', async () => {
+ const res = await request(buildApp()).post('/api/creative-commission').send({ ...validBody(), targetAbility: 'hologram' });
+ expect(res.status).toBe(400);
+ expect(svc.createCommission).not.toHaveBeenCalled();
+ });
+
+ it('rejects a generation param that does not belong to the chosen type with 400 (#2769)', async () => {
+ // targetDurationSeconds is a video knob, not an image one.
+ const res = await request(buildApp()).post('/api/creative-commission')
+ .send({ ...validBody(), targetAbility: 'image', generation: { targetDurationSeconds: 10 } });
expect(res.status).toBe(400);
expect(svc.createCommission).not.toHaveBeenCalled();
});
diff --git a/server/services/creativeCommissions/abilityAdapters.js b/server/services/creativeCommissions/abilityAdapters.js
new file mode 100644
index 0000000000..2627e7049d
--- /dev/null
+++ b/server/services/creativeCommissions/abilityAdapters.js
@@ -0,0 +1,258 @@
+/**
+ * Creative Commission — ability adapters (#2769).
+ *
+ * A commission's `targetAbility` picks the kind of thing it makes each fire:
+ * `video`, `image`, `music`, `music-video`, or `series`. Historically every
+ * commission was a video (the generic "Create a video piece" directive + the
+ * video-only generation params), which handed the Creative Director planner the
+ * WHOLE tool menu (declare a series, an image, …) and left it to infer intent
+ * from free text. Instead, each output type gets an adapter that owns three
+ * things, so every layer keys off `targetAbility` rather than assuming video:
+ *
+ * - `sanitizeGeneration(raw)` — fill this type's generation defaults and keep
+ * only this type's keys (the store sanitizer calls it; it is the record-shape
+ * source of truth, mirroring ABILITY_GENERATION_SPEC in the validation leaf).
+ * - `buildDirective(commission)` — a PRESCRIPTIVE CD directive that tells the
+ * planner exactly what deliverable to produce and which registry tools to use
+ * (an image directive says "produce a still image, don't plan a video"), so
+ * the planner isn't guessing. Replaces the old generic directive.
+ * - `buildProjectParams(commission, ctx)` — the arg map handed to
+ * `createProject`. The CD project always carries video "locked render
+ * settings" (the planner only forces that geometry onto media_enqueueVideoJob
+ * steps), so non-video types pass harmless defaults for the geometry and let
+ * their directive drive the non-video tools.
+ *
+ * Pure leaf, like directive.js: it imports only the pure directive helpers and
+ * the validation spec — no service graph — so it's trivially unit-testable and
+ * safe to pull into a mocked suite. It depends on directive.js one-way (directive
+ * stays ability-agnostic and never imports back).
+ */
+
+import { renderFeedbackDigest, composeDirectiveGoal } from './directive.js';
+import { ABILITY_GENERATION_SPEC, CREATIVE_COMMISSION_ABILITIES } from '../../lib/creativeCommissionValidation.js';
+
+const isStr = (v) => typeof v === 'string';
+
+// The optional per-type engine/model override, universal across abilities. Kept
+// separate from the spec's typed keys because it's a free string, not a bounded
+// enum/number.
+function pickModel(raw) {
+ return isStr(raw?.model) && raw.model.trim() ? raw.model.trim() : null;
+}
+
+// Shared: sanitize a numeric generation key against its bounds, falling back to
+// the ability default when absent/invalid (absent-vs-empty: a non-number or an
+// out-of-range value falls back rather than corrupting the record).
+function pickInt(raw, key, def, min, max) {
+ const v = raw?.[key];
+ if (Number.isInteger(v) && v >= min && v <= max) return v;
+ return def;
+}
+
+function pickEnum(raw, key, allowed, def) {
+ const v = raw?.[key];
+ return allowed.includes(v) ? v : def;
+}
+
+const QUALITIES = ['draft', 'standard', 'high'];
+const ASPECTS = ['16:9', '9:16', '1:1'];
+
+// Build the common brief lines (intent + genre/category/style) shared by every
+// adapter's directive, with a type-specific lead sentence prepended by the
+// caller. Returns { lines, digest, constraints } — the adapter assembles the
+// goal via composeDirectiveGoal.
+function briefContext(commission, leadSentence) {
+ const brief = commission?.brief || {};
+ const lines = [`${leadSentence} ${String(brief.intent || '').trim()}`.trim()];
+ if (brief.genre) lines.push(`Genre: ${brief.genre}.`);
+ if (brief.category) lines.push(`Category: ${brief.category}.`);
+ if (brief.styleSpec) lines.push(`Style: ${brief.styleSpec}.`);
+ const digest = renderFeedbackDigest(commission?.feedback, commission?.feedbackWindow ?? 5);
+ const constraints = {};
+ if (brief.constraints?.universeId) constraints.universeId = brief.constraints.universeId;
+ if (brief.constraints?.seriesId) constraints.seriesId = brief.constraints.seriesId;
+ return { lines, digest, constraints };
+}
+
+// Video geometry the CD project always carries. For non-video types the planner
+// ignores it (no media_enqueueVideoJob steps), so these are harmless defaults.
+function videoGeometry(gen, { defaultVideoModelId } = {}) {
+ return {
+ aspectRatio: gen?.aspectRatio || '16:9',
+ quality: gen?.quality || 'standard',
+ modelId: gen?.model || (typeof defaultVideoModelId === 'function' ? defaultVideoModelId() : undefined),
+ targetDurationSeconds: gen?.targetDurationSeconds || 10,
+ };
+}
+
+const videoAdapter = {
+ id: 'video',
+ label: 'Video',
+ sanitizeGeneration(raw) {
+ const d = ABILITY_GENERATION_SPEC.video.defaults;
+ return {
+ model: pickModel(raw),
+ quality: pickEnum(raw, 'quality', QUALITIES, d.quality),
+ aspectRatio: pickEnum(raw, 'aspectRatio', ASPECTS, d.aspectRatio),
+ targetDurationSeconds: pickInt(raw, 'targetDurationSeconds', d.targetDurationSeconds, 5, 600),
+ };
+ },
+ buildDirective(commission) {
+ const { lines, digest, constraints } = briefContext(commission, 'Create a short-form video piece.');
+ return {
+ goal: composeDirectiveGoal(lines, digest),
+ deliverables: ['One rendered video matching the brief'],
+ constraints,
+ };
+ },
+ buildProjectParams(commission, ctx) {
+ return videoGeometry(commission?.generation, ctx);
+ },
+};
+
+const imageAdapter = {
+ id: 'image',
+ label: 'Image',
+ sanitizeGeneration(raw) {
+ const d = ABILITY_GENERATION_SPEC.image.defaults;
+ return {
+ model: pickModel(raw),
+ quality: pickEnum(raw, 'quality', QUALITIES, d.quality),
+ aspectRatio: pickEnum(raw, 'aspectRatio', ASPECTS, d.aspectRatio),
+ imageCount: pickInt(raw, 'imageCount', d.imageCount, 1, 6),
+ };
+ },
+ buildDirective(commission) {
+ const count = pickInt(commission?.generation, 'imageCount', ABILITY_GENERATION_SPEC.image.defaults.imageCount, 1, 6);
+ const noun = count === 1 ? 'a single still image' : `${count} still images`;
+ const lead = `Produce ${noun}. Use the image / catalog generation tools; do NOT plan a video or music render.`;
+ const { lines, digest, constraints } = briefContext(commission, lead);
+ return {
+ goal: composeDirectiveGoal(lines, digest),
+ deliverables: [count === 1 ? 'One still image matching the brief' : `${count} still images matching the brief`],
+ constraints,
+ };
+ },
+ buildProjectParams(commission, ctx) {
+ // Image render carries an aspect ratio + quality; duration is irrelevant, so
+ // the geometry default (10s) rides along unused.
+ return videoGeometry(commission?.generation, ctx);
+ },
+};
+
+const musicAdapter = {
+ id: 'music',
+ label: 'Music',
+ sanitizeGeneration(raw) {
+ const d = ABILITY_GENERATION_SPEC.music.defaults;
+ return {
+ model: pickModel(raw),
+ lengthSeconds: pickInt(raw, 'lengthSeconds', d.lengthSeconds, 5, 600),
+ };
+ },
+ buildDirective(commission) {
+ const secs = pickInt(commission?.generation, 'lengthSeconds', ABILITY_GENERATION_SPEC.music.defaults.lengthSeconds, 5, 600);
+ const lead = `Compose an original ~${secs}s music / audio piece. Use the music generation tools; do NOT plan a video or image render.`;
+ const { lines, digest, constraints } = briefContext(commission, lead);
+ return {
+ goal: composeDirectiveGoal(lines, digest),
+ deliverables: [`One ~${secs}s music track matching the brief`],
+ constraints,
+ };
+ },
+ buildProjectParams(commission, ctx) {
+ // No video render — pass geometry defaults so the project record is
+ // well-formed; the directive steers the planner to the music tools.
+ return videoGeometry(commission?.generation, ctx);
+ },
+};
+
+const musicVideoAdapter = {
+ id: 'music-video',
+ label: 'Music video',
+ sanitizeGeneration(raw) {
+ const d = ABILITY_GENERATION_SPEC['music-video'].defaults;
+ return {
+ model: pickModel(raw),
+ quality: pickEnum(raw, 'quality', QUALITIES, d.quality),
+ aspectRatio: pickEnum(raw, 'aspectRatio', ASPECTS, d.aspectRatio),
+ targetDurationSeconds: pickInt(raw, 'targetDurationSeconds', d.targetDurationSeconds, 5, 600),
+ };
+ },
+ buildDirective(commission) {
+ const lead = 'Create a short-form music video: generate an original music bed AND a matching video scored to it.';
+ const { lines, digest, constraints } = briefContext(commission, lead);
+ return {
+ goal: composeDirectiveGoal(lines, digest),
+ deliverables: ['One original music bed', 'One video matching the brief, scored to the music bed'],
+ constraints,
+ };
+ },
+ buildProjectParams(commission, ctx) {
+ return videoGeometry(commission?.generation, ctx);
+ },
+};
+
+const seriesAdapter = {
+ id: 'series',
+ label: 'Series',
+ sanitizeGeneration(raw) {
+ const d = ABILITY_GENERATION_SPEC.series.defaults;
+ return {
+ model: pickModel(raw),
+ episodeCount: pickInt(raw, 'episodeCount', d.episodeCount, 1, 6),
+ };
+ },
+ buildDirective(commission) {
+ const count = pickInt(commission?.generation, 'episodeCount', ABILITY_GENERATION_SPEC.series.defaults.episodeCount, 1, 6);
+ const hasUniverse = !!commission?.brief?.constraints?.universeId;
+ const scope = hasUniverse
+ ? 'Create the series within the provided universe (see constraints).'
+ : 'Invent a fitting universe context for the series.';
+ const noun = count === 1 ? 'its opening issue/episode' : `its first ${count} issues/episodes`;
+ const lead = `Create a new episodic series and generate ${noun}. ${scope} Use the pipeline series tools.`;
+ const { lines, digest, constraints } = briefContext(commission, lead);
+ return {
+ goal: composeDirectiveGoal(lines, digest),
+ deliverables: [count === 1 ? 'A new series with its opening issue/episode started' : `A new series with its first ${count} issues/episodes started`],
+ constraints,
+ };
+ },
+ buildProjectParams(commission, ctx) {
+ // Series output is comic/prose, not a locked video render — geometry
+ // defaults ride along unused; the directive drives the series tools.
+ return videoGeometry(commission?.generation, ctx);
+ },
+};
+
+export const ABILITY_ADAPTERS = Object.freeze({
+ video: videoAdapter,
+ image: imageAdapter,
+ music: musicAdapter,
+ 'music-video': musicVideoAdapter,
+ series: seriesAdapter,
+});
+
+export const ABILITY_IDS = Object.freeze([...CREATIVE_COMMISSION_ABILITIES]);
+
+/**
+ * Resolve the adapter for an ability, or null when unknown. Callers decide the
+ * fallback: the store sanitizer clamps an unknown ability to `video`; the
+ * scheduler skips an unknown-ability fire rather than silently mis-generating.
+ */
+export function getAbilityAdapter(ability) {
+ return ABILITY_ADAPTERS[ability] || null;
+}
+
+/**
+ * Build the CD directive for a commission's next fire, dispatched by output type
+ * (#2769). Unknown ability falls back to the video adapter so a hand-edited or
+ * forward-version record still yields a well-formed directive (the scheduler
+ * separately refuses to FIRE an unknown ability — see scheduler.js). Shape matches
+ * `creativeDirectorDirectiveSchema` (goal/deliverables/constraints) so it
+ * round-trips straight into `createProject({ directive })`.
+ */
+export function buildCommissionDirective(commission) {
+ const adapter = getAbilityAdapter(commission?.targetAbility) || videoAdapter;
+ return adapter.buildDirective(commission);
+}
diff --git a/server/services/creativeCommissions/abilityAdapters.test.js b/server/services/creativeCommissions/abilityAdapters.test.js
new file mode 100644
index 0000000000..f3be1159d5
--- /dev/null
+++ b/server/services/creativeCommissions/abilityAdapters.test.js
@@ -0,0 +1,161 @@
+import { describe, it, expect } from 'vitest';
+import {
+ ABILITY_ADAPTERS, ABILITY_IDS, getAbilityAdapter, buildCommissionDirective,
+} from './abilityAdapters.js';
+import { CREATIVE_COMMISSION_ABILITIES, ABILITY_GENERATION_SPEC } from '../../lib/creativeCommissionValidation.js';
+
+describe('ability adapter registry', () => {
+ it('has an adapter for every supported ability (and no extras)', () => {
+ expect(ABILITY_IDS).toEqual([...CREATIVE_COMMISSION_ABILITIES]);
+ expect(Object.keys(ABILITY_ADAPTERS).sort()).toEqual([...CREATIVE_COMMISSION_ABILITIES].sort());
+ });
+
+ it('returns null for an unknown ability', () => {
+ expect(getAbilityAdapter('hologram')).toBeNull();
+ expect(getAbilityAdapter(undefined)).toBeNull();
+ });
+});
+
+describe('buildCommissionDirective — video (unchanged brief/feedback fold)', () => {
+ it('composes goal + deliverables + constraints from the brief', () => {
+ const directive = buildCommissionDirective({
+ name: 'Nightly Surreal',
+ targetAbility: 'video',
+ brief: {
+ intent: 'something surreal, dreamlike, unsettlingly beautiful',
+ genre: 'surrealism',
+ styleSpec: 'flat color, Magritte',
+ constraints: { universeId: 'u-123' },
+ },
+ feedbackWindow: 5,
+ });
+ expect(directive.goal).toContain('Create a short-form video piece.');
+ expect(directive.goal).toContain('something surreal');
+ expect(directive.goal).toContain('Genre: surrealism.');
+ expect(directive.goal).toContain('Style: flat color, Magritte.');
+ expect(directive.deliverables).toEqual(['One rendered video matching the brief']);
+ expect(directive.constraints).toEqual({ universeId: 'u-123' });
+ });
+
+ it('folds recent feedback into the goal', () => {
+ const directive = buildCommissionDirective({
+ targetAbility: 'video',
+ brief: { intent: 'surreal' },
+ feedback: [{ rating: 'down', note: 'less horror' }, { rating: 'up', note: 'more Magritte' }],
+ feedbackWindow: 5,
+ });
+ expect(directive.goal).toContain('Recent likes: more Magritte.');
+ expect(directive.goal).toContain('Recent dislikes: less horror.');
+ });
+
+ it('omits absent constraints', () => {
+ expect(buildCommissionDirective({ targetAbility: 'video', brief: { intent: 'x' } }).constraints).toEqual({});
+ });
+
+ it('clamps the goal under the CD 5000-char cap with a large feedback window + long notes', () => {
+ const feedback = Array.from({ length: 50 }, (_, i) => ({ rating: i % 2 === 0 ? 'up' : 'down', note: 'z'.repeat(1000) }));
+ const directive = buildCommissionDirective({ targetAbility: 'video', brief: { intent: 'surreal' }, feedback, feedbackWindow: 50 });
+ expect(directive.goal.length).toBeLessThanOrEqual(4500);
+ });
+
+ it('keeps the feedback digest even when the brief text is very long', () => {
+ const directive = buildCommissionDirective({
+ targetAbility: 'video',
+ brief: { intent: 'x'.repeat(2000), styleSpec: 'y'.repeat(3000) },
+ feedback: [{ rating: 'down', note: 'less horror' }],
+ feedbackWindow: 5,
+ });
+ expect(directive.goal.length).toBeLessThanOrEqual(4500);
+ expect(directive.goal).toContain('Recent dislikes: less horror.');
+ });
+
+ it('falls back to the video adapter for an unknown ability', () => {
+ const directive = buildCommissionDirective({ targetAbility: 'hologram', brief: { intent: 'x' } });
+ expect(directive.goal).toContain('Create a short-form video piece.');
+ });
+});
+
+describe('per-ability directives steer the planner to the right tools', () => {
+ it('image: names still-image tools and counts the stills', () => {
+ const d = buildCommissionDirective({ targetAbility: 'image', brief: { intent: 'a lighthouse' }, generation: { imageCount: 3 } });
+ expect(d.goal).toContain('Produce 3 still images');
+ expect(d.goal).toMatch(/do NOT plan a video/i);
+ expect(d.deliverables).toEqual(['3 still images matching the brief']);
+ });
+
+ it('image: singular phrasing for a single still', () => {
+ const d = buildCommissionDirective({ targetAbility: 'image', brief: { intent: 'x' }, generation: { imageCount: 1 } });
+ expect(d.goal).toContain('a single still image');
+ expect(d.deliverables).toEqual(['One still image matching the brief']);
+ });
+
+ it('music: names the music tools and the target length', () => {
+ const d = buildCommissionDirective({ targetAbility: 'music', brief: { intent: 'ambient drone' }, generation: { lengthSeconds: 45 } });
+ expect(d.goal).toContain('~45s music');
+ expect(d.goal).toMatch(/music generation tools/i);
+ expect(d.deliverables).toEqual(['One ~45s music track matching the brief']);
+ });
+
+ it('music-video: asks for both a music bed and a video scored to it', () => {
+ const d = buildCommissionDirective({ targetAbility: 'music-video', brief: { intent: 'neon drift' } });
+ expect(d.goal).toMatch(/music bed AND a matching video/i);
+ expect(d.deliverables).toHaveLength(2);
+ });
+
+ it('series: scopes to the provided universe when constrained', () => {
+ const withU = buildCommissionDirective({ targetAbility: 'series', brief: { intent: 'noir', constraints: { universeId: 'u-9' } }, generation: { episodeCount: 2 } });
+ expect(withU.goal).toContain('Create the series within the provided universe');
+ expect(withU.goal).toContain('first 2 issues/episodes');
+ expect(withU.constraints).toEqual({ universeId: 'u-9' });
+
+ const noU = buildCommissionDirective({ targetAbility: 'series', brief: { intent: 'noir' }, generation: { episodeCount: 1 } });
+ expect(noU.goal).toContain('Invent a fitting universe');
+ });
+});
+
+describe('sanitizeGeneration — fills defaults and preserves only the type keys', () => {
+ it('video keeps its keys and drops off-type ones', () => {
+ const g = getAbilityAdapter('video').sanitizeGeneration({ quality: 'high', aspectRatio: '9:16', targetDurationSeconds: 20, imageCount: 5, model: ' ltx ' });
+ expect(g).toEqual({ model: 'ltx', quality: 'high', aspectRatio: '9:16', targetDurationSeconds: 20 });
+ });
+
+ it('image fills defaults for missing keys and clamps an out-of-range count', () => {
+ expect(getAbilityAdapter('image').sanitizeGeneration({})).toEqual({ model: null, quality: 'standard', aspectRatio: '16:9', imageCount: 1 });
+ expect(getAbilityAdapter('image').sanitizeGeneration({ imageCount: 99 }).imageCount).toBe(1);
+ expect(getAbilityAdapter('image').sanitizeGeneration({ imageCount: 4 }).imageCount).toBe(4);
+ });
+
+ it('music keeps only model + lengthSeconds', () => {
+ expect(getAbilityAdapter('music').sanitizeGeneration({ lengthSeconds: 60, aspectRatio: '16:9' })).toEqual({ model: null, lengthSeconds: 60 });
+ });
+
+ it('series keeps only model + episodeCount', () => {
+ expect(getAbilityAdapter('series').sanitizeGeneration({ episodeCount: 3, quality: 'high' })).toEqual({ model: null, episodeCount: 3 });
+ });
+
+ it('every adapter default matches ABILITY_GENERATION_SPEC', () => {
+ for (const [ability, spec] of Object.entries(ABILITY_GENERATION_SPEC)) {
+ const sani = getAbilityAdapter(ability).sanitizeGeneration({});
+ for (const [k, v] of Object.entries(spec.defaults)) expect(sani[k]).toBe(v);
+ }
+ });
+});
+
+describe('buildProjectParams — every type yields well-formed render settings', () => {
+ const ctx = { defaultVideoModelId: () => 'ltx-default' };
+
+ it('video maps its generation onto the render geometry', () => {
+ const p = getAbilityAdapter('video').buildProjectParams({ generation: { aspectRatio: '1:1', quality: 'draft', targetDurationSeconds: 15 } }, ctx);
+ expect(p).toEqual({ aspectRatio: '1:1', quality: 'draft', modelId: 'ltx-default', targetDurationSeconds: 15 });
+ });
+
+ it('non-video types still carry harmless geometry defaults', () => {
+ for (const ability of ['image', 'music', 'series']) {
+ const p = getAbilityAdapter(ability).buildProjectParams({ generation: {} }, ctx);
+ expect(p.aspectRatio).toBe('16:9');
+ expect(p.quality).toBe('standard');
+ expect(p.modelId).toBe('ltx-default');
+ expect(typeof p.targetDurationSeconds).toBe('number');
+ }
+ });
+});
diff --git a/server/services/creativeCommissions/directive.js b/server/services/creativeCommissions/directive.js
index 99caf15b15..218d64962b 100644
--- a/server/services/creativeCommissions/directive.js
+++ b/server/services/creativeCommissions/directive.js
@@ -1,12 +1,16 @@
/**
- * Creative Commission — pure directive + cron composition (#2657, Phase 1).
+ * Creative Commission — pure, ability-agnostic directive + cron helpers (#2657).
*
* These are side-effect-free helpers: `commissionToCron` turns a schedule
- * descriptor into a 5-field cron string, and `buildCommissionDirective` composes
- * the CD directive (goal + deliverables + constraints) the planner turns into a
- * plan. Kept pure and dependency-free so they're trivially unit-testable and can
- * be imported anywhere without dragging the scheduler graph along. The
- * authoritative cron-VALIDITY check (isValidCron) lives in the scheduler/service.
+ * descriptor into a 5-field cron string; `renderFeedbackDigest` renders the taste
+ * feedback into a steering digest; and `composeDirectiveGoal` folds a list of
+ * brief lines + that digest into a CD directive `goal` under the 5000-char cap.
+ * The per-output-type directive assembly (which lines/deliverables each type
+ * gets) lives in abilityAdapters.js (#2769), which imports these — this module
+ * stays a dependency-free leaf and never imports back. Kept pure so they're
+ * trivially unit-testable and importable anywhere without dragging the scheduler
+ * graph along. The authoritative cron-VALIDITY check (isValidCron) lives in the
+ * scheduler/service.
*/
// The CD directive `goal` this composes is fed straight into `createProject` by
@@ -104,44 +108,25 @@ export function renderFeedbackDigest(feedback, windowSize = 5) {
}
/**
- * Build the CD directive for a commission's next fire. Folds the brief (intent +
- * genre/category/style) and the accumulated feedback digest into `goal`, and
- * maps the brief's constraints (universe/series) onto the directive constraints.
- * Shape matches `creativeDirectorDirectiveSchema` (goal/deliverables/constraints)
- * so it round-trips straight into `createProject({ directive })`.
+ * Compose a CD directive `goal` string from a list of brief lines and a feedback
+ * digest, under the CD's 5000-char cap. Ability-agnostic (#2769): each ability
+ * adapter builds its own type-specific `lines` (see abilityAdapters.js) and hands
+ * them here so the char-budget / digest-reservation logic lives in exactly one
+ * place.
+ *
+ * The scheduler feeds the result straight into `createProject({ directive })`,
+ * skipping the route's input validation, so the clamp is load-bearing. RESERVE
+ * room for the digest first, then clamp the BRIEF text into whatever remains —
+ * truncating the tail of the whole string would drop the digest (appended last)
+ * whenever a long intent/style fills the budget, silently killing the feedback
+ * signal. The digest is bounded (MAX_DIGEST_LEN) so the reservation is finite.
*/
-export function buildCommissionDirective(commission) {
- const brief = commission?.brief || {};
- const ability = commission?.targetAbility || 'video';
- const lines = [];
- lines.push(`Create a ${ability} piece. ${String(brief.intent || '').trim()}`.trim());
- if (brief.genre) lines.push(`Genre: ${brief.genre}.`);
- if (brief.category) lines.push(`Category: ${brief.category}.`);
- if (brief.styleSpec) lines.push(`Style: ${brief.styleSpec}.`);
-
- const digest = renderFeedbackDigest(commission?.feedback, commission?.feedbackWindow ?? 5);
-
- const constraints = {};
- if (brief.constraints?.universeId) constraints.universeId = brief.constraints.universeId;
- if (brief.constraints?.seriesId) constraints.seriesId = brief.constraints.seriesId;
-
- // Compose the goal under the CD's 5000-char cap (the scheduler feeds this
- // straight into createProject, skipping the route's input validation). RESERVE
- // room for the digest first, then clamp the BRIEF text into whatever remains —
- // truncating the tail of the whole string would drop the digest (appended last)
- // whenever a long intent/style fills the budget, silently killing the feedback
- // signal. The digest is bounded (MAX_DIGEST_LEN) so the reservation is finite.
- const briefText = lines.join(' ');
+export function composeDirectiveGoal(lines, digest) {
+ const briefText = (Array.isArray(lines) ? lines : []).filter(Boolean).join(' ');
const reserve = digest ? digest.length + 1 : 0; // +1 for the joining space
const briefBudget = Math.max(0, MAX_DIRECTIVE_GOAL_LEN - reserve);
const clampedBrief = clamp(briefText, briefBudget);
let goal = digest ? `${clampedBrief} ${digest}`.trim() : clampedBrief;
// Final safety net (defensive — brief+reserve already fits): clamp the whole.
- goal = clamp(goal, MAX_DIRECTIVE_GOAL_LEN);
-
- return {
- goal,
- deliverables: [`One ${ability} artifact matching the brief`],
- constraints,
- };
+ return clamp(goal, MAX_DIRECTIVE_GOAL_LEN);
}
diff --git a/server/services/creativeCommissions/directive.test.js b/server/services/creativeCommissions/directive.test.js
index ef910bdc6a..1743dea62e 100644
--- a/server/services/creativeCommissions/directive.test.js
+++ b/server/services/creativeCommissions/directive.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { commissionToCron, renderFeedbackDigest, buildCommissionDirective } from './directive.js';
+import { commissionToCron, renderFeedbackDigest, composeDirectiveGoal } from './directive.js';
describe('commissionToCron', () => {
it('composes a DAILY cron from HH:MM', () => {
@@ -102,71 +102,21 @@ describe('renderFeedbackDigest', () => {
});
});
-describe('buildCommissionDirective', () => {
- it('composes goal + deliverables + constraints from the brief', () => {
- const directive = buildCommissionDirective({
- name: 'Nightly Surreal',
- targetAbility: 'video',
- brief: {
- intent: 'something surreal, dreamlike, unsettlingly beautiful',
- genre: 'surrealism',
- styleSpec: 'flat color, Magritte',
- constraints: { universeId: 'u-123' },
- },
- feedbackWindow: 5,
- });
- expect(directive.goal).toContain('Create a video piece.');
- expect(directive.goal).toContain('something surreal');
- expect(directive.goal).toContain('Genre: surrealism.');
- expect(directive.goal).toContain('Style: flat color, Magritte.');
- expect(directive.deliverables).toEqual(['One video artifact matching the brief']);
- expect(directive.constraints).toEqual({ universeId: 'u-123' });
- });
-
- it('folds recent feedback into the goal', () => {
- const directive = buildCommissionDirective({
- targetAbility: 'video',
- brief: { intent: 'surreal' },
- feedback: [{ rating: 'down', note: 'less horror' }, { rating: 'up', note: 'more Magritte' }],
- feedbackWindow: 5,
- });
- expect(directive.goal).toContain('Recent likes: more Magritte.');
- expect(directive.goal).toContain('Recent dislikes: less horror.');
- });
-
- it('omits absent constraints', () => {
- const directive = buildCommissionDirective({ targetAbility: 'video', brief: { intent: 'x' } });
- expect(directive.constraints).toEqual({});
- });
-
- it('clamps the goal so a large feedback window + long notes stay under the CD 5000-char cap', () => {
- // 50 reactions × 1000-char notes would blow well past the CD directive goal
- // limit; the scheduler feeds this goal straight into createProject without the
- // route's validation, so the builder must bound it itself.
- const feedback = Array.from({ length: 50 }, (_, i) => ({
- rating: i % 2 === 0 ? 'up' : 'down',
- note: 'z'.repeat(1000),
- }));
- const directive = buildCommissionDirective({
- targetAbility: 'video',
- brief: { intent: 'surreal' },
- feedback,
- feedbackWindow: 50,
- });
- expect(directive.goal.length).toBeLessThanOrEqual(4500);
- });
-
- it('keeps the feedback digest even when the brief text is very long (digest is reserved, brief is clamped)', () => {
- // A 2000-char intent + 3000-char style would fill the whole 4500 budget; the
- // digest must survive (it is appended last, but reserved for) rather than
- // being truncated away — otherwise ratings stop steering the run.
- const directive = buildCommissionDirective({
- targetAbility: 'video',
- brief: { intent: 'x'.repeat(2000), styleSpec: 'y'.repeat(3000) },
- feedback: [{ rating: 'down', note: 'less horror' }],
- feedbackWindow: 5,
- });
- expect(directive.goal.length).toBeLessThanOrEqual(4500);
- expect(directive.goal).toContain('Recent dislikes: less horror.');
+describe('composeDirectiveGoal', () => {
+ it('joins brief lines and appends the digest', () => {
+ const goal = composeDirectiveGoal(['Create a video piece. surreal', 'Genre: x.'], 'Recent likes: more.');
+ expect(goal).toBe('Create a video piece. surreal Genre: x. Recent likes: more.');
+ });
+
+ it('drops falsy lines and returns just the brief when there is no digest', () => {
+ expect(composeDirectiveGoal(['A.', '', null, 'B.'], '')).toBe('A. B.');
+ });
+
+ it('reserves room for the digest and clamps the brief so the whole goal stays under the CD cap', () => {
+ // A huge brief must not truncate away the digest (appended last, but reserved
+ // for) — otherwise ratings stop steering the run.
+ const goal = composeDirectiveGoal(['x'.repeat(6000)], 'Recent dislikes: less horror.');
+ expect(goal.length).toBeLessThanOrEqual(4500);
+ expect(goal).toContain('Recent dislikes: less horror.');
});
});
diff --git a/server/services/creativeCommissions/scheduler.js b/server/services/creativeCommissions/scheduler.js
index f0e36c55fd..5d22251bbc 100644
--- a/server/services/creativeCommissions/scheduler.js
+++ b/server/services/creativeCommissions/scheduler.js
@@ -26,7 +26,8 @@ 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';
+import { commissionToCron } from './directive.js';
+import { buildCommissionDirective, getAbilityAdapter } from './abilityAdapters.js';
import { surfaceCommissionRun } from './surface.js';
const eventId = (commissionId) => `creative-commission-${commissionId}`;
@@ -207,9 +208,12 @@ async function fireCommission(commission, trigger) {
if (!budget) return skip('budget-unavailable');
if (!budget.withinBudget) return skip('budget');
- // Phase 1 supports video only. A non-video commission can't be created via
- // the UI (schema restricts the enum), but a hand-edited record is possible.
- if (commission.targetAbility !== 'video') return skip('unsupported-ability');
+ // Resolve the output-type adapter (#2769). Every supported type (video,
+ // image, music, music-video, series) has one; an unknown ability (a
+ // hand-edited or forward-version record the store sanitizer couldn't clamp)
+ // is skipped rather than mis-generated as a video.
+ const abilityAdapter = getAbilityAdapter(commission.targetAbility);
+ if (!abilityAdapter) return skip('unknown-ability');
// NOTE: we deliberately do NOT pre-charge the cos budget here. The planner
// spawns as a normal CoS agent (a `cd-` task) and is accounted by
@@ -225,7 +229,6 @@ async function fireCommission(commission, trigger) {
]);
const directive = buildCommissionDirective(commission);
- const gen = commission.generation || {};
// Fan the commission's single LLM pin onto BOTH CD cognitive stages
// (treatment + plan) as the project's `modelOverrides`, so the scheduled
// fire is processed by the provider/model the user chose rather than the
@@ -273,12 +276,14 @@ async function fireCommission(commission, trigger) {
const baseName = commission.name.length > maxBase
? `${commission.name.slice(0, maxBase - 1)}…`
: commission.name;
+ // Per-ability project params (#2769): each output type maps its generation
+ // knobs onto createProject's render settings. Non-video types pass harmless
+ // geometry defaults (the planner only forces that geometry onto video render
+ // steps) and let their directive drive the non-video tools.
+ const projectParams = abilityAdapter.buildProjectParams(commission, { defaultVideoModelId });
const project = await createProject({
name: `${baseName}${dateSuffix}`,
- aspectRatio: gen.aspectRatio || '16:9',
- quality: gen.quality || 'standard',
- modelId: gen.model || defaultVideoModelId(),
- targetDurationSeconds: gen.targetDurationSeconds || 10,
+ ...projectParams,
styleSpec: commission.brief?.styleSpec || '',
directive,
modelOverrides,
diff --git a/server/services/creativeCommissions/scheduler.test.js b/server/services/creativeCommissions/scheduler.test.js
index 99619aa84f..078d6cf388 100644
--- a/server/services/creativeCommissions/scheduler.test.js
+++ b/server/services/creativeCommissions/scheduler.test.js
@@ -275,11 +275,20 @@ describe('runScheduledCommission gates', () => {
expect(recordRunMock).not.toHaveBeenCalled();
});
- it('skips a non-video target ability (Phase 1 supports video only)', async () => {
- getCommissionMock.mockResolvedValue(videoCommission({ targetAbility: 'music' }));
+ it('creates a project for a non-video output type (#2769)', async () => {
+ getCommissionMock.mockResolvedValue(videoCommission({ targetAbility: 'music', generation: { lengthSeconds: 45 } }));
+ await runScheduledCommission('commission-1');
+ expect(createProjectMock).toHaveBeenCalledTimes(1);
+ // The directive steers the CD planner to the music tools rather than a video render.
+ expect(createProjectMock.mock.calls[0][0].directive.goal).toMatch(/music generation tools/i);
+ expect(recordRunMock).toHaveBeenCalledWith('commission-1', expect.objectContaining({ status: 'started' }));
+ });
+
+ it('skips an UNKNOWN target ability rather than mis-generating (#2769)', async () => {
+ getCommissionMock.mockResolvedValue(videoCommission({ targetAbility: 'hologram' }));
await runScheduledCommission('commission-1');
expect(createProjectMock).not.toHaveBeenCalled();
- expect(recordRunMock).toHaveBeenCalledWith('commission-1', expect.objectContaining({ status: 'skipped', reason: 'unsupported-ability' }));
+ expect(recordRunMock).toHaveBeenCalledWith('commission-1', expect.objectContaining({ status: 'skipped', reason: 'unknown-ability' }));
});
it('tags scheduled runs with trigger "schedule"', async () => {
diff --git a/server/services/creativeCommissions/store.js b/server/services/creativeCommissions/store.js
index 8bb734d049..3f333fb173 100644
--- a/server/services/creativeCommissions/store.js
+++ b/server/services/creativeCommissions/store.js
@@ -69,6 +69,8 @@ import {
} from '../../lib/conflictJournal.js';
import { emitRecordUpdated, emitRecordDeleted, autoSubscribeRecordToAllPeers } from '../sharing/recordEvents.js';
import { commissionToCron } from './directive.js';
+import { getAbilityAdapter } from './abilityAdapters.js';
+import { CREATIVE_COMMISSION_ABILITIES } from '../../lib/creativeCommissionValidation.js';
import {
recordFeedback,
listFeedbackForCommission,
@@ -135,6 +137,11 @@ export function sanitizeCommission(raw) {
const brief = raw.brief && typeof raw.brief === 'object' ? raw.brief : {};
const schedule = raw.schedule && typeof raw.schedule === 'object' ? raw.schedule : {};
const generation = raw.generation && typeof raw.generation === 'object' ? raw.generation : {};
+ // Resolve the output type up front (#2769) so the generation block can defer to
+ // the matching ability adapter — which fills that type's defaults and preserves
+ // ONLY that type's keys (an image `imageCount`, a series `episodeCount`), rather
+ // than the old video-only shape.
+ const resolvedAbility = CREATIVE_COMMISSION_ABILITIES.includes(raw.targetAbility) ? raw.targetAbility : 'video';
const assignment = raw.assignment && typeof raw.assignment === 'object' && !Array.isArray(raw.assignment)
? raw.assignment : {};
// The LLM pin that processes the commission (CD treatment + plan stages). A
@@ -149,7 +156,12 @@ export function sanitizeCommission(raw) {
id: raw.id,
name: isStr(raw.name) ? raw.name : 'Untitled Commission',
enabled: raw.enabled !== false,
- targetAbility: isStr(raw.targetAbility) ? raw.targetAbility : 'video',
+ // Clamp to a KNOWN output type (#2769). An unknown/hand-edited value would
+ // otherwise persist and make the scheduler skip the fire as `unknown-ability`;
+ // fall back to `video` (the default + pre-#2769 shape) so the record stays
+ // generatable rather than silently inert. `resolvedAbility` (above) is the
+ // clamped value, reused so the ability and its generation shape never diverge.
+ targetAbility: resolvedAbility,
brief: {
intent: isStr(brief.intent) ? brief.intent : '',
genre: isStr(brief.genre) ? brief.genre : null,
@@ -166,12 +178,10 @@ export function sanitizeCommission(raw) {
cron: isStr(schedule.cron) ? schedule.cron : null,
timezone: isStr(schedule.timezone) ? schedule.timezone : null,
},
- generation: {
- model: isStr(generation.model) ? generation.model : null,
- quality: isStr(generation.quality) ? generation.quality : 'standard',
- aspectRatio: isStr(generation.aspectRatio) ? generation.aspectRatio : '16:9',
- targetDurationSeconds: Number.isInteger(generation.targetDurationSeconds) ? generation.targetDurationSeconds : 10,
- },
+ // Per-ability generation (#2769): the adapter fills THIS type's defaults and
+ // keeps only THIS type's keys. `getAbilityAdapter` never returns null here
+ // because `resolvedAbility` is already clamped to a known ability.
+ generation: getAbilityAdapter(resolvedAbility).sanitizeGeneration(generation),
// Which AI provider/model processes this commission's CD cognitive stages.
// `providerId: null` = inherit the install's default AI Assignment.
assignment: {
diff --git a/server/services/creativeCommissions/store.test.js b/server/services/creativeCommissions/store.test.js
index 9087a805d4..bde51e68fc 100644
--- a/server/services/creativeCommissions/store.test.js
+++ b/server/services/creativeCommissions/store.test.js
@@ -56,7 +56,7 @@ const {
ERR_VALIDATION,
ERR_NOT_FOUND,
} = await import('./store.js');
-const { buildCommissionDirective } = await import('./directive.js');
+const { buildCommissionDirective } = await import('./abilityAdapters.js');
beforeEach(() => { records.clear(); feedbackRecords.clear(); });
@@ -87,6 +87,26 @@ describe('sanitizeCommission', () => {
expect(rec.feedback).toEqual([]);
});
+ it('routes generation through the ability adapter per output type (#2769)', () => {
+ const img = sanitizeCommission({ id: 'c1', targetAbility: 'image', generation: { imageCount: 4, targetDurationSeconds: 30 } });
+ expect(img.targetAbility).toBe('image');
+ // Keeps the image key; drops the off-type video duration key.
+ expect(img.generation).toEqual({ model: null, quality: 'standard', aspectRatio: '16:9', imageCount: 4 });
+
+ const music = sanitizeCommission({ id: 'c2', targetAbility: 'music', generation: { lengthSeconds: 60 } });
+ expect(music.generation).toEqual({ model: null, lengthSeconds: 60 });
+
+ const series = sanitizeCommission({ id: 'c3', targetAbility: 'series', generation: { episodeCount: 2 } });
+ expect(series.generation).toEqual({ model: null, episodeCount: 2 });
+ });
+
+ it('clamps an unknown output type back to video so the record stays generatable (#2769)', () => {
+ const rec = sanitizeCommission({ id: 'c1', targetAbility: 'hologram', generation: { imageCount: 3 } });
+ expect(rec.targetAbility).toBe('video');
+ // Video shape — the stray imageCount is dropped.
+ expect(rec.generation).toEqual({ model: null, quality: 'standard', aspectRatio: '16:9', targetDurationSeconds: 10 });
+ });
+
it('caps runs to the last MAX_PERSISTED_RUNS', () => {
const runs = Array.from({ length: 80 }, (_, i) => ({ id: `run-${i}` }));
const rec = sanitizeCommission({ id: 'c1', runs });