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
fix: enforce creative commission run controls
[._.]/ Adam Eivy24b1e13a62c5
diff --git a/server/routes/creativeDirector.js b/server/routes/creativeDirector.jsindex d8830bfc23..a0226c416d 100644--- a/server/routes/creativeDirector.js+++ b/server/routes/creativeDirector.js@@ -239,6 +239,13 @@ router.patch('/:id/treatment', asyncHandler(async (req, res) => {// the plan advance loop so execution begins on the returned plan.router.patch('/:id/plan', asyncHandler(async (req, res) => {const plan = validateRequest(creativeDirectorPlanSchema, req.body);+ const project = await getProject(req.params.id);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const { getCommissionPlanError } = await import('../services/creative/toolRegistry.js');+ const commissionPlanError = getCommissionPlanError(plan, project.directive);+ if (commissionPlanError) {+ throw new ServerError(commissionPlanError, { status: 400, code: 'INVALID_COMMISSION_PLAN' });+ }const updated = await setPlan(req.params.id, plan);const { advanceAfterPlanStepSettled } = await import('../services/creativeDirector/planAdvance.js');advanceAfterPlanStepSettled(req.params.id)diff --git a/server/routes/creativeDirector.test.js b/server/routes/creativeDirector.test.jsindex d5243830ce..7989a7778f 100644--- a/server/routes/creativeDirector.test.js+++ b/server/routes/creativeDirector.test.js@@ -27,6 +27,7 @@ vi.mock('../services/creativeDirector/planAdvance.js', () => ({}));vi.mock('../services/creative/toolRegistry.js', () => ({getAllCreativeToolMetadata: vi.fn(() => [{ id: 'universe_create', costClass: 'free', longRunning: false, destructive: false }]),+ getCommissionPlanError: vi.fn(() => null),}));vi.mock('../lib/domainAutonomy.js', () => ({ getCreativeAutonomyMode: vi.fn(() => 'dry-run') }));vi.mock('../services/domainUsage.js', () => ({ getDomainBudgetStatus: vi.fn(async () => ({ withinBudget: false, exceeded: 'actions' })) }));@@ -59,6 +60,7 @@ import * as autoCast from '../services/creativeDirector/autoCast.js';import * as hook from '../services/creativeDirector/completionHook.js';import * as firstPass from '../services/creativeDirector/firstPassGen.js';import * as firstPassMusicBed from '../services/creativeDirector/firstPassMusicGen.js';+import * as creativeTools from '../services/creative/toolRegistry.js';import { CREATIVE_DIRECTOR_IDS_BATCH_MAX } from '../lib/creativeDirectorValidation.js';import creativeDirectorRoutes from './creativeDirector.js';@@ -667,12 +669,24 @@ describe('creativeDirector routes', () => {const validStep = { stepId: 'create-series', toolName: 'pipeline_createSeries', args: { name: 'Nova' }, dependsOn: [] };it('accepts a word/hyphen stepId', async () => {+ cdService.getProject.mockResolvedValue({ id: 'cd-1', directive: { goal: 'x', constraints: {} } });cdService.setPlan.mockResolvedValue({ id: 'cd-1', plan: { steps: [validStep] } });const r = await request(app).patch('/api/creative-director/cd-1/plan').send({ steps: [validStep] });expect(r.status).toBe(200);expect(cdService.setPlan).toHaveBeenCalled();});+ it('rejects a plan that violates commission output controls', async () => {+ cdService.getProject.mockResolvedValue({+ id: 'cd-1', directive: { goal: 'image', constraints: { targetAbility: 'image' } },+ });+ creativeTools.getCommissionPlanError.mockReturnValueOnce('Tool is not allowed for an image commission');+ const r = await request(app).patch('/api/creative-director/cd-1/plan').send({ steps: [validStep] });+ expect(r.status).toBe(400);+ expect(r.body.code).toBe('INVALID_COMMISSION_PLAN');+ expect(cdService.setPlan).not.toHaveBeenCalled();+ });+it('400s on a stepId with a dot (unreferenceable by the result-reference grammar)', async () => {const r = await request(app).patch('/api/creative-director/cd-1/plan').send({ steps: [{ ...validStep, stepId: 'create.series' }] });diff --git a/server/services/creative/toolRegistry.js b/server/services/creative/toolRegistry.jsindex c449de0207..7c328423a0 100644--- a/server/services/creative/toolRegistry.js+++ b/server/services/creative/toolRegistry.js@@ -147,12 +147,46 @@ const ABILITY_TOOL_NAMES = Object.freeze({});export const filterForTargetAbility = (tools, targetAbility) => {+ return tools.filter((tool) => isToolAllowedForTargetAbility(tool.name, targetAbility));+};++export function isToolAllowedForTargetAbility(toolName, targetAbility) {+ if (!targetAbility) return true;if (targetAbility === 'series') {- return tools.filter((tool) => tool.name.startsWith('pipeline_') || tool.name.startsWith('universe_'));+ return toolName.startsWith('pipeline_') || toolName.startsWith('universe_');}const allowed = ABILITY_TOOL_NAMES[targetAbility];- return allowed ? tools.filter((tool) => allowed.has(tool.name)) : tools;-};+ return allowed ? allowed.has(toolName) : true;+}++/**+ * Validate the production shape selected by the commission form. Tool schemas+ * still validate each step's args at dispatch; this guard locks the output lane+ * and requested artifact count before any autonomous work starts.+ */+export function getCommissionPlanError(plan, directive) {+ const targetAbility = directive?.constraints?.targetAbility;+ if (!targetAbility) return null;+ const steps = Array.isArray(plan?.steps) ? plan.steps : [];+ const disallowed = steps.find((step) => !isToolAllowedForTargetAbility(step.toolName, targetAbility));+ if (disallowed) {+ return `Tool "${disallowed.toolName}" is not allowed for commission type ${targetAbility}`;+ }+ const count = (name) => steps.filter((step) => step.toolName === name && step.status !== 'skipped').length;+ const requiredCounts = {+ video: [['media_enqueueVideoJob', 1]],+ image: [['media_enqueueImageJob', Number(directive.constraints.generation?.imageCount) || 1]],+ music: [['media_enqueueAudioJob', 1]],+ 'music-video': [['media_enqueueAudioJob', 1], ['media_enqueueVideoJob', 1]],+ }[targetAbility] || [];+ for (const [toolName, expected] of requiredCounts) {+ const actual = count(toolName);+ if (actual !== expected) {+ return `${targetAbility} commission requires exactly ${expected} ${toolName} step${expected === 1 ? '' : 's'}; received ${actual}`;+ }+ }+ return null;+}export const getToolSpecs = ({ includeDestructive = false, targetAbility = null } = {}) =>filterForTargetAbility(filterDestructive(CREATIVE_TOOLS, includeDestructive), targetAbility).map(toSpec);@@ -225,6 +259,9 @@ async function recordLedger(ctx, entry) {export async function dispatchCreativeTool(name, args = {}, ctx = {}) {const tool = byName.get(name);if (!tool) throw new Error(`Unknown creative tool: ${name}`);+ if (!isToolAllowedForTargetAbility(name, ctx.targetAbility)) {+ throw new Error(`Creative tool "${name}" is not allowed for commission type ${ctx.targetAbility}`);+ }// Validate up front — a Zod parse failure throws before any gating/side effect.const parsed = tool.schema.parse(args ?? {});diff --git a/server/services/creative/toolRegistry.test.js b/server/services/creative/toolRegistry.test.jsindex f91ed6736b..91eb52cccb 100644--- a/server/services/creative/toolRegistry.test.js+++ b/server/services/creative/toolRegistry.test.js@@ -92,6 +92,8 @@ import {getAllCreativeToolNames,getCreativeToolMetadata,filterDestructive,+ getCommissionPlanError,+ isToolAllowedForTargetAbility,assertCreativeToolIntegrity,dispatchCreativeTool,} from './toolRegistry.js';@@ -150,6 +152,27 @@ describe('registry shape', () => {s.function.name.startsWith('pipeline_') || s.function.name.startsWith('universe_'))).toBe(true);});+ it('validates a commission plan against its selected lane and artifact count', () => {+ const directive = { constraints: { targetAbility: 'image', generation: { imageCount: 2 } } };+ expect(getCommissionPlanError({ steps: [+ { toolName: 'media_enqueueImageJob' },+ { toolName: 'media_enqueueImageJob' },+ ] }, directive)).toBeNull();+ expect(getCommissionPlanError({ steps: [{ toolName: 'media_enqueueVideoJob' }] }, directive))+ .toMatch(/not allowed/);+ expect(getCommissionPlanError({ steps: [{ toolName: 'media_enqueueImageJob' }] }, directive))+ .toMatch(/exactly 2/);+ expect(isToolAllowedForTargetAbility('pipeline_createSeries', 'series')).toBe(true);+ expect(isToolAllowedForTargetAbility('media_enqueueVideoJob', 'series')).toBe(false);+ });++ it('rejects an unadvertised commission tool again at dispatch', async () => {+ await expect(dispatchCreativeTool(+ 'media_enqueueVideoJob', { params: { prompt: 'p' } }, { targetAbility: 'image' },+ )).rejects.toThrow(/not allowed for commission type image/);+ expect(enqueueJob).not.toHaveBeenCalled();+ });+it('hydrates catalog_searchIngredients from the voice tool\'s RESOLVED spec (custom types survive)', () => {const meta = getCreativeToolMetadata('catalog_searchIngredients');expect(meta.description).toBe('VOICE catalog search description');diff --git a/server/services/creative/tools/media.js b/server/services/creative/tools/media.jsindex 695845bd4f..6d1a2e3b68 100644--- a/server/services/creative/tools/media.js+++ b/server/services/creative/tools/media.js@@ -31,7 +31,8 @@ const paramsSchema = z.object({ params: z.record(z.any()).default({}), owner: z.* them deterministically here rather than trusting the LLM to reproduce them.** The planner still owns the CREATIVE params (`prompt`, `negativePrompt`,- * `style`, `durationSeconds`). Only the render geometry is enforced. An+ * `style`). Commission duration is form-locked; a general CD project may use+ * shorter per-step beats. Only render controls are enforced. An* unrecognized aspect/quality (hand-edited/legacy project) falls through to the* LLM's params untouched — best-effort, never throws.*/@@ -43,8 +44,12 @@ function enforceVideoRenderPreset(params, project) {}// The planner may legitimately ask for a shorter beat than the project target,// so a positive per-step durationSeconds wins; otherwise use the project's.+ const targetAbility = project.directive?.constraints?.targetAbility;+ const commissionLocked = targetAbility === 'video' || targetAbility === 'music-video';const stepDuration = Number(params?.durationSeconds);- const durationSeconds = stepDuration > 0 ? stepDuration : (project.targetDurationSeconds || 10);+ const durationSeconds = commissionLocked+ ? (project.targetDurationSeconds || 10)+ : (stepDuration > 0 ? stepDuration : (project.targetDurationSeconds || 10));const preset = presetToRenderParams({aspectRatio: project.aspectRatio,quality: project.quality,@@ -55,6 +60,7 @@ function enforceVideoRenderPreset(params, project) {const { aspectRatio: _ignored, ...rest } = params || {};return {...rest,+ durationSeconds,width: preset.width,height: preset.height,fps: preset.fps,@@ -64,6 +70,25 @@ function enforceVideoRenderPreset(params, project) {};}+function enforceImageRenderPreset(params, project) {+ const targetAbility = project?.directive?.constraints?.targetAbility;+ if ((targetAbility !== 'image' && targetAbility !== 'music-video')+ || !ASPECT_PRESETS[project.aspectRatio] || !QUALITY_PRESETS[project.quality]) {+ return params;+ }+ const aspect = ASPECT_PRESETS[project.aspectRatio];+ const quality = QUALITY_PRESETS[project.quality];+ const { aspectRatio: _ignored, ...rest } = params || {};+ return {+ ...rest,+ width: aspect.width,+ height: aspect.height,+ steps: quality.steps,+ guidance: quality.guidance,+ cfgScale: quality.guidance,+ };+}+export function reconcileVideoParamsWithModel(params, project, models = getVideoModels()) {const locked = enforceVideoRenderPreset(params, project);if (locked === params) return params;@@ -120,14 +145,35 @@ export function reconcileVideoParamsWithModel(params, project, models = getVideo*/async function configureMusicJob(params, ctx) {if (!ctx?.projectId) return params;+ const project = await loadOwningProject(ctx);+ if ((ctx.targetAbility === 'music' || ctx.targetAbility === 'music-video') && !project) {+ throw new Error('commission-project-unavailable');+ }const { getCommissionMusicContextForProject } = await import('../../creativeCommissions/store.js');// Do not collapse a failed local provenance lookup into "not a taste run".// That would let planner-authored renderer/prompt guesses escape onto an// opted-in commission precisely when the local store is unavailable.const context = await getCommissionMusicContextForProject(ctx.projectId);if (!context) {- if (params?.creativeDirectorMusicBed) return params;- return { ...params, creativeDirectorMusicBed: { projectId: ctx.projectId } };+ const targetAbility = project?.directive?.constraints?.targetAbility;+ if (targetAbility !== 'music' && targetAbility !== 'music-video') {+ if (params?.creativeDirectorMusicBed) return params;+ return { ...params, creativeDirectorMusicBed: { projectId: ctx.projectId } };+ }+ const {+ engine: _plannerEngine,+ modelId: _plannerModel,+ repo: _plannerRepo,+ durationSec: _plannerDuration,+ durationMode: _plannerDurationMode,+ provenance: _plannerProvenance,+ ...rest+ } = params || {};+ return {+ ...rest,+ durationSec: project.targetDurationSeconds,+ creativeDirectorMusicBed: { projectId: ctx.projectId },+ };}if (typeof context.prompt !== 'string' || !context.prompt.trim()) {throw new Error('taste-commission-prompt-unavailable');@@ -301,7 +347,9 @@ const mediaTool = (kind, label) => ({// Image + video both consult the owning project: video for its locked// geometry preset, both for a pinned render backend (#3135).const project = await loadOwningProject(ctx);+ if (ctx.targetAbility && !project) throw new Error('commission-project-unavailable');if (kind === 'video') params = enforceVideoRenderPreset(params, project);+ if (kind === 'image') params = enforceImageRenderPreset(params, project);params = await enforceRenderBackendPin(kind, params, project);// Resolve the selected local model AFTER the backend ladder has applied// project/install pins. The same model-catalog fields that drive Videodiff --git a/server/services/creative/tools/media.test.js b/server/services/creative/tools/media.test.jsindex 34f5a795ac..6235ca6812 100644--- a/server/services/creative/tools/media.test.js+++ b/server/services/creative/tools/media.test.js@@ -158,6 +158,19 @@ describe('render-backend pin — the auto/unpinned path is a strict no-op (#3135});describe('render-backend pin — image (#3135)', () => {+ it('locks an image commission to the form aspect and quality presets', async () => {+ getProject.mockResolvedValue({+ id: 'cd-1', aspectRatio: '9:16', quality: 'high',+ directive: { constraints: { targetAbility: 'image' } },+ });+ await run('media_enqueueImageJob', {+ prompt: 'p', width: 1024, height: 1024, steps: 4, cfgScale: 12,+ }, { projectId: 'cd-1' });+ expect(enqueued().params).toMatchObject({+ prompt: 'p', width: 432, height: 768, steps: 30, guidance: 3.5, cfgScale: 3.5,+ });+ });+it('forces a codex pin onto the job params, overriding the planner LLM', async () => {getSettings.mockResolvedValue({ imageGen: { codex: { enabled: true, codexPath: '/bin/codex', model: 'example-model', effort: 'low' } } });getProject.mockResolvedValue(projectWithPin({ image: { mode: 'codex' } }));@@ -216,6 +229,15 @@ describe('render-backend pin — image (#3135)', () => {});describe('render-backend pin — video (#3135)', () => {+ it('locks a video commission to the form duration instead of a planner beat', async () => {+ getProject.mockResolvedValue({+ id: 'cd-1', aspectRatio: '16:9', quality: 'standard', targetDurationSeconds: 10,+ directive: { constraints: { targetAbility: 'video' } },+ });+ await run('media_enqueueVideoJob', { prompt: 'p', durationSeconds: 5 }, { projectId: 'cd-1' });+ expect(enqueued().params.durationSeconds).toBe(10);+ });+it('forces a grok pin with the grok discriminator + the semantic in videoMode', async () => {getSettings.mockResolvedValue({ imageGen: { grok: { enabled: true, grokPath: '/bin/grok', aspectRatio: '9:16' } } });getProject.mockResolvedValue(projectWithPin({ video: { mode: 'grok' } }));@@ -355,13 +377,27 @@ describe('render-backend pin — video (#3135)', () => {});describe('audio enqueues', () => {- it('tags the music bed without reading the project or settings', async () => {+ it('tags a general project music bed without reading settings', async () => {await run('media_enqueueAudioJob', { prompt: 'a mournful synth score' }, { projectId: 'cd-1' });expect(enqueued().params.creativeDirectorMusicBed).toEqual({ projectId: 'cd-1' });- expect(getProject).not.toHaveBeenCalled();+ expect(getProject).toHaveBeenCalledTimes(1);expect(getSettings).not.toHaveBeenCalled();});+ it('locks a non-taste music commission to its form duration and install renderer', async () => {+ getProject.mockResolvedValue({+ id: 'cd-1', targetDurationSeconds: 75,+ directive: { constraints: { targetAbility: 'music', generation: { lengthSeconds: 75 } } },+ });+ await run('media_enqueueAudioJob', {+ prompt: 'a mournful synth score', engine: 'planner-engine', modelId: 'planner-model', durationSec: 5,+ }, { projectId: 'cd-1' });+ expect(enqueued().params).toEqual({+ prompt: 'a mournful synth score', durationSec: 75,+ creativeDirectorMusicBed: { projectId: 'cd-1' },+ });+ });+it('authoritatively applies a taste commission recipe and configured renderer', async () => {getCommissionMusicContextForProject.mockResolvedValue({commissionId: 'commission-example',diff --git a/server/services/creativeCommissions/abilityAdapters.js b/server/services/creativeCommissions/abilityAdapters.jsindex 3957057765..6218dfe35b 100644--- a/server/services/creativeCommissions/abilityAdapters.js+++ b/server/services/creativeCommissions/abilityAdapters.js@@ -153,7 +153,7 @@ function buildVideoGeometryParams(commission, { defaultVideoModelId } = {}) {// (lib/creativeDirectorPrompts.js) and the teaser tool inherits. Neither set// ⇒ the install default, exactly as before.modelId: gen?.videoModelId || gen?.model || (typeof defaultVideoModelId === 'function' ? defaultVideoModelId() : undefined),- targetDurationSeconds: gen?.targetDurationSeconds || 10,+ targetDurationSeconds: gen?.targetDurationSeconds || gen?.lengthSeconds || 10,// Only passed when the commission actually pinned a backend (#3135), so an// unpinned commission's createProject call is byte-identical to a hand-made// project's — both omit the arg and buildProjectRecord stores `null`, exactlydiff --git a/server/services/creativeCommissions/abilityAdapters.test.js b/server/services/creativeCommissions/abilityAdapters.test.jsindex e58a0bf8b6..687f0e5d53 100644--- a/server/services/creativeCommissions/abilityAdapters.test.js+++ b/server/services/creativeCommissions/abilityAdapters.test.js@@ -197,6 +197,11 @@ describe('buildProjectParams — every type yields well-formed render settings',expect(typeof p.targetDurationSeconds).toBe('number');}});++ it('carries the music form length onto the owning project', () => {+ const p = getAbilityAdapter('music').buildProjectParams({ generation: { lengthSeconds: 75 } }, ctx);+ expect(p.targetDurationSeconds).toBe(75);+ });});describe('buildRenderBackendPin — per-commission render backend (#3135)', () => {diff --git a/server/services/creativeDirector/planAdvance.js b/server/services/creativeDirector/planAdvance.jsindex bb3760d62d..90ac4041b5 100644--- a/server/services/creativeDirector/planAdvance.js+++ b/server/services/creativeDirector/planAdvance.js@@ -404,7 +404,11 @@ async function runPlanStep(project, step) {console.log(`▶️ CD plan ${projectId}: dispatching step "${step.stepId}" (${step.toolName})`);// Outside the request lifecycle — catch so a throw becomes a settle, never an// unhandled rejection.- const dispatch = await dispatchCreativeTool(resolvedStep.toolName, resolvedStep.args, { projectId })+ const targetAbility = project.directive?.constraints?.targetAbility;+ const dispatch = await dispatchCreativeTool(resolvedStep.toolName, resolvedStep.args, {+ projectId,+ ...(targetAbility ? { targetAbility } : {}),+ }).catch((err) => ({ ok: false, threw: true, error: err.message }));return settlePlanStepDispatch(projectId, resolvedStep, run?.runId, dispatch);}