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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor(issue-2769): single-source generation spec + preserve unknown ability
[._.]/ Adam Eivya9df41bc9353
diff --git a/client/src/components/creative-commission/commissionForm.js b/client/src/components/creative-commission/commissionForm.jsindex 5b2d840cc0..16a1cbfd63 100644--- a/client/src/components/creative-commission/commissionForm.js+++ b/client/src/components/creative-commission/commissionForm.js@@ -27,9 +27,12 @@ const ASPECT_FIELD = { key: 'aspectRatio', label: 'Aspect ratio', type: 'select'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).+// GENERATION_KEY_DEFS / ABILITY_GENERATION_SPEC (server/lib/creativeCommissionValidation.js).+// The config form renders exactly these fields for the selected type. There is no+// cross-package import, so this must be kept in sync with the server spec BY HAND+// when a key/bound/default changes; commissionForm.test.js asserts only the+// client-internal invariant (every field has a matching default), not server↔client+// parity.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 }],@@ -69,17 +72,10 @@ export function generationToForm(ability, generation) {// 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;-}+// their quality/aspectRatio when going video → image). This is exactly the+// project-a-record projection — carrying over an overlapping key IS falling back+// to the default only when absent — so it delegates to generationToForm.+export const mergeGenerationForAbility = generationToForm;// Build the API generation payload for the current ability: emit only that// ability's keys, coercing number fields (form <input type=number> values arediff --git a/server/lib/creativeCommissionValidation.js b/server/lib/creativeCommissionValidation.jsindex 572ace54d8..01231ce2ac 100644--- a/server/lib/creativeCommissionValidation.js+++ b/server/lib/creativeCommissionValidation.js@@ -25,22 +25,51 @@ import { z } from 'zod';// 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 } },+// 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.+export const CREATIVE_COMMISSION_SCHEDULE_KINDS = Object.freeze(['DAILY', 'WEEKLY', 'CUSTOM']);++export const CREATIVE_COMMISSION_QUALITIES = Object.freeze(['draft', 'standard', 'high']);+export const CREATIVE_COMMISSION_ASPECT_RATIOS = Object.freeze(['16:9', '9:16', '1:1']);++// Per-KEY generation descriptor — the SINGLE SOURCE OF TRUTH for a generation+// param's type, bounds, and default. Everything else derives from this: the Zod+// superset (`creativeCommissionGenerationSchema`), the per-ability key lists ++// defaults (`ABILITY_GENERATION_SPEC`), and the ability adapter's data-driven+// `sanitizeGeneration`. Keeping the bounds here (not re-typed in the schema AND+// the adapter AND the client) is what stops the four-way drift. The client+// (commissionForm.js) mirrors these values in its own package — kept in sync by+// hand; there is no cross-package import.+export const GENERATION_KEY_DEFS = Object.freeze({+ quality: { type: 'enum', values: CREATIVE_COMMISSION_QUALITIES, default: 'standard' },+ aspectRatio: { type: 'enum', values: CREATIVE_COMMISSION_ASPECT_RATIOS, default: '16:9' },+ targetDurationSeconds: { type: 'int', min: 5, max: 600, default: 10 },+ imageCount: { type: 'int', min: 1, max: 6, default: 1 },+ lengthSeconds: { type: 'int', min: 5, max: 600, default: 30 },+ episodeCount: { type: 'int', min: 1, max: 6, default: 1 },+});++// Which keys each output type carries (the universal `model` is added separately+// — every type accepts an optional engine/model override). The adapter fills+// these keys' defaults and preserves only them.+const ABILITY_GENERATION_KEYS = Object.freeze({+ video: ['quality', 'aspectRatio', 'targetDurationSeconds'],+ image: ['quality', 'aspectRatio', 'imageCount'],+ music: ['lengthSeconds'],+ 'music-video': ['quality', 'aspectRatio', 'targetDurationSeconds'],+ series: ['episodeCount'],});+// Derived per-ability { keys, defaults } view — the shape the store sanitizer and+// tests consume. Built from GENERATION_KEY_DEFS so a default only ever lives in+// one place.+export const ABILITY_GENERATION_SPEC = Object.freeze(+ Object.fromEntries(Object.entries(ABILITY_GENERATION_KEYS).map(([ability, keys]) => [ability, {+ keys,+ defaults: Object.fromEntries(keys.map((k) => [k, GENERATION_KEY_DEFS[k].default])),+ }])),+);+// 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) {@@ -48,12 +77,13 @@ export function generationKeysForAbility(ability) {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.-export const CREATIVE_COMMISSION_SCHEDULE_KINDS = Object.freeze(['DAILY', 'WEEKLY', 'CUSTOM']);--export const CREATIVE_COMMISSION_QUALITIES = Object.freeze(['draft', 'standard', 'high']);-export const CREATIVE_COMMISSION_ASPECT_RATIOS = Object.freeze(['16:9', '9:16', '1:1']);+// Build a Zod field for one generation-key descriptor (optional in the superset;+// per-ability strictness is applied by the create-path superRefine, not here).+function generationFieldSchema(def) {+ return def.type === 'enum'+ ? z.enum(def.values).optional()+ : z.number().int().min(def.min).max(def.max).optional();+}export const COMMISSION_NAME_MAX = 200;export const COMMISSION_INTENT_MAX = 2000;@@ -132,12 +162,9 @@ export const creativeCommissionScheduleSchema = z.object({// `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).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(),+ // Every generation key, derived from GENERATION_KEY_DEFS so the bounds live in+ // exactly one place (see the drift note there).+ ...Object.fromEntries(Object.entries(GENERATION_KEY_DEFS).map(([key, def]) => [key, generationFieldSchema(def)])),});// The UPDATE path shares the same superset — every field optional, no defaults —diff --git a/server/services/creativeCommissions/abilityAdapters.js b/server/services/creativeCommissions/abilityAdapters.jsindex 2627e7049d..f1b85ddf16 100644--- a/server/services/creativeCommissions/abilityAdapters.js+++ b/server/services/creativeCommissions/abilityAdapters.js@@ -6,12 +6,12 @@* 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:+ * from free text. Instead, each output type gets an adapter that owns:** - `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).+ * only this type's keys (the store sanitizer calls it). Data-driven from the+ * validation leaf's GENERATION_KEY_DEFS / ABILITY_GENERATION_SPEC, so the+ * keys/bounds/defaults live in exactly one place.* - `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@@ -19,8 +19,9 @@* - `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.+ * steps), so non-video types pass harmless defaults and let their directive+ * drive the non-video tools. Shared across every type today; kept as a+ * per-adapter slot so a type whose geometry genuinely diverges can override.** 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@@ -29,38 +30,42 @@*/import { renderFeedbackDigest, composeDirectiveGoal } from './directive.js';-import { ABILITY_GENERATION_SPEC, CREATIVE_COMMISSION_ABILITIES } from '../../lib/creativeCommissionValidation.js';+import {+ ABILITY_GENERATION_SPEC, GENERATION_KEY_DEFS, 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.+// The optional per-type engine/model override, universal across abilities. A free+// string, so it's handled separately from the typed/bounded spec keys.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+// Coerce one generation value against its GENERATION_KEY_DEFS descriptor, falling+// back to the default when absent/invalid (absent-vs-empty: a wrong-type or// out-of-range value falls back rather than corrupting the record).-function pickInt(raw, key, def, min, max) {+function coerceGenerationValue(key, raw) {+ const def = GENERATION_KEY_DEFS[key];const v = raw?.[key];- if (Number.isInteger(v) && v >= min && v <= max) return v;- return def;+ if (def.type === 'enum') return def.values.includes(v) ? v : def.default;+ return Number.isInteger(v) && v >= def.min && v <= def.max ? v : def.default;}-function pickEnum(raw, key, allowed, def) {- const v = raw?.[key];- return allowed.includes(v) ? v : def;+// Fill an ability's generation defaults and keep ONLY that ability's keys (+ the+// universal model). Data-driven from the spec — no per-type hand-written pick+// scaffolding.+function sanitizeGenerationFor(ability, raw) {+ const spec = ABILITY_GENERATION_SPEC[ability];+ const out = { model: pickModel(raw) };+ for (const key of spec.keys) out[key] = coerceGenerationValue(key, raw);+ return out;}-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.+// 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()];@@ -74,9 +79,17 @@ function briefContext(commission, leadSentence) {return { lines, digest, constraints };}+// Read a clamped generation value for directive text, using the same coercion the+// sanitizer applies (so the goal never quotes an out-of-range count).+function genValue(commission, key) {+ return coerceGenerationValue(key, commission?.generation);+}+// 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 } = {}) {+// Shared by every adapter's buildProjectParams today.+function buildVideoGeometryParams(commission, { defaultVideoModelId } = {}) {+ const gen = commission?.generation;return {aspectRatio: gen?.aspectRatio || '16:9',quality: gen?.quality || 'standard',@@ -88,42 +101,21 @@ function videoGeometry(gen, { defaultVideoModelId } = {}) {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),- };- },+ sanitizeGeneration: (raw) => sanitizeGenerationFor('video', raw),+ buildProjectParams: buildVideoGeometryParams,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);+ return { goal: composeDirectiveGoal(lines, digest), deliverables: ['One rendered video matching the brief'], constraints };},};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),- };- },+ sanitizeGeneration: (raw) => sanitizeGenerationFor('image', raw),+ buildProjectParams: buildVideoGeometryParams,buildDirective(commission) {- const count = pickInt(commission?.generation, 'imageCount', ABILITY_GENERATION_SPEC.image.defaults.imageCount, 1, 6);+ const count = genValue(commission, 'imageCount');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);@@ -133,52 +125,26 @@ const imageAdapter = {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),- };- },+ sanitizeGeneration: (raw) => sanitizeGenerationFor('music', raw),+ buildProjectParams: buildVideoGeometryParams,buildDirective(commission) {- const secs = pickInt(commission?.generation, 'lengthSeconds', ABILITY_GENERATION_SPEC.music.defaults.lengthSeconds, 5, 600);+ const secs = genValue(commission, 'lengthSeconds');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);+ return { goal: composeDirectiveGoal(lines, digest), deliverables: [`One ~${secs}s music track matching the brief`], constraints };},};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),- };- },+ sanitizeGeneration: (raw) => sanitizeGenerationFor('music-video', raw),+ buildProjectParams: buildVideoGeometryParams,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);@@ -188,23 +154,15 @@ const musicVideoAdapter = {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),- };- },+ sanitizeGeneration: (raw) => sanitizeGenerationFor('series', raw),+ buildProjectParams: buildVideoGeometryParams,buildDirective(commission) {- const count = pickInt(commission?.generation, 'episodeCount', ABILITY_GENERATION_SPEC.series.defaults.episodeCount, 1, 6);+ const count = genValue(commission, 'episodeCount');const hasUniverse = !!commission?.brief?.constraints?.universeId;const scope = hasUniverse? 'Create the series within the provided universe (see constraints).'@@ -218,11 +176,6 @@ const seriesAdapter = {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({@@ -233,12 +186,21 @@ export const ABILITY_ADAPTERS = Object.freeze({series: seriesAdapter,});-export const ABILITY_IDS = Object.freeze([...CREATIVE_COMMISSION_ABILITIES]);+// Fail fast if the registry and the enum ever drift (a new ability added to the+// enum with no adapter, or vice versa) — boot-time, not a runtime surprise.+{+ const missing = CREATIVE_COMMISSION_ABILITIES.filter((a) => !ABILITY_ADAPTERS[a]);+ const extra = Object.keys(ABILITY_ADAPTERS).filter((a) => !CREATIVE_COMMISSION_ABILITIES.includes(a));+ if (missing.length || extra.length) {+ throw new Error(`ability adapter registry out of sync with CREATIVE_COMMISSION_ABILITIES (missing: ${missing}, extra: ${extra})`);+ }+}/*** 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.+ * fallback: the store sanitizer PRESERVES an unknown ability (forward-compat — a+ * newer peer's output type round-trips untouched) and the scheduler skips it+ * rather than mis-generating, so the two agree that unknown = inert-but-preserved.*/export function getAbilityAdapter(ability) {return ABILITY_ADAPTERS[ability] || null;@@ -246,11 +208,11 @@ export function getAbilityAdapter(ability) {/*** 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 })`.+ * (#2769). Unknown ability falls back to the video adapter so a direct call still+ * yields a well-formed directive; in practice the scheduler skips an unknown+ * ability BEFORE reaching here (see scheduler.js), so the fallback is purely+ * defensive. Shape matches `creativeDirectorDirectiveSchema`+ * (goal/deliverables/constraints) so it round-trips into `createProject`.*/export function buildCommissionDirective(commission) {const adapter = getAbilityAdapter(commission?.targetAbility) || videoAdapter;diff --git a/server/services/creativeCommissions/abilityAdapters.test.js b/server/services/creativeCommissions/abilityAdapters.test.jsindex f3be1159d5..c2f4a56007 100644--- a/server/services/creativeCommissions/abilityAdapters.test.js+++ b/server/services/creativeCommissions/abilityAdapters.test.js@@ -1,12 +1,11 @@import { describe, it, expect } from 'vitest';import {- ABILITY_ADAPTERS, ABILITY_IDS, getAbilityAdapter, buildCommissionDirective,+ ABILITY_ADAPTERS, 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());});diff --git a/server/services/creativeCommissions/store.js b/server/services/creativeCommissions/store.jsindex 3f333fb173..4d573ad8c9 100644--- a/server/services/creativeCommissions/store.js+++ b/server/services/creativeCommissions/store.js@@ -70,7 +70,6 @@ import {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,@@ -137,11 +136,17 @@ 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';+ // Resolve the output type up front (#2769). A KNOWN type is sanitized through+ // its ability adapter (fills that type's defaults, keeps ONLY that type's keys —+ // an image `imageCount`, a series `episodeCount`). An UNKNOWN non-empty type (a+ // forward-version record synced verbatim from a newer peer) is PRESERVED, not+ // rewritten to `video`: rewriting would corrupt the newer peer's brief on read+ // and could push the downgrade back via LWW (violating the distribution model's+ // forward-compat rule). The scheduler skips an unknown ability rather than+ // mis-generating it, so unknown = inert-but-preserved. A missing/blank type+ // falls back to the default `video`.+ const resolvedAbility = isStr(raw.targetAbility) && raw.targetAbility ? raw.targetAbility : 'video';+ const abilityAdapter = getAbilityAdapter(resolvedAbility);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@@ -156,11 +161,8 @@ export function sanitizeCommission(raw) {id: raw.id,name: isStr(raw.name) ? raw.name : 'Untitled Commission',enabled: raw.enabled !== false,- // 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.+ // Preserve the resolved output type as-is (#2769) — known types pass through,+ // an unknown forward-version type round-trips untouched (see above).targetAbility: resolvedAbility,brief: {intent: isStr(brief.intent) ? brief.intent : '',@@ -178,10 +180,11 @@ export function sanitizeCommission(raw) {cron: isStr(schedule.cron) ? schedule.cron : null,timezone: isStr(schedule.timezone) ? schedule.timezone : null,},- // 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),+ // Per-ability generation (#2769): a known type's adapter fills its defaults+ // and keeps only its keys; an unknown (forward-version) type has no adapter, so+ // preserve the raw generation object verbatim — nothing is lost on round-trip+ // and the scheduler won't fire it anyway.+ generation: abilityAdapter ? abilityAdapter.sanitizeGeneration(generation) : { ...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.jsindex bde51e68fc..b309c465c7 100644--- a/server/services/creativeCommissions/store.test.js+++ b/server/services/creativeCommissions/store.test.js@@ -100,11 +100,19 @@ describe('sanitizeCommission', () => {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('preserves an unknown (forward-version) output type verbatim so a newer peer record round-trips (#2769)', () => {+ // A newer peer might sync an output type this install does not know yet.+ // Rewriting it to `video` would corrupt the newer brief on read (and could+ // push the downgrade back via LWW), so it is preserved untouched; the+ // scheduler skips it rather than mis-generating.+ const rec = sanitizeCommission({ id: 'c1', targetAbility: 'story', generation: { chapters: 5 } });+ expect(rec.targetAbility).toBe('story');+ expect(rec.generation).toEqual({ chapters: 5 });+ });++ it('falls back to video for a missing/blank output type', () => {+ expect(sanitizeCommission({ id: 'c1' }).targetAbility).toBe('video');+ expect(sanitizeCommission({ id: 'c2', targetAbility: '' }).targetAbility).toBe('video');});it('caps runs to the last MAX_PERSISTED_RUNS', () => {