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: add taste-aware music commissions (#4347)

[._.]/ Adam Eivy13a48344b8c1
diff --git a/.changelog/next/added-issue-4347.md b/.changelog/next/added-issue-4347.md
index 03f743c694..1d88d00f65 100644
--- a/.changelog/next/added-issue-4347.md
+++ b/.changelog/next/added-issue-4347.md
@@ -1 +1,2 @@
- [issue-4347] Add bounded Digital Twin taste recipes to music Creative Commissions
+- Taste-aware music Creative Commissions can now choose Digital Twin exploration controls and installed renderers, preserve local run provenance, and accept structured steering feedback.
diff --git a/client/src/components/creative-commission/CommissionConfigForm.jsx b/client/src/components/creative-commission/CommissionConfigForm.jsx
index eb20474717..69e42b5bb7 100644
--- a/client/src/components/creative-commission/CommissionConfigForm.jsx
+++ b/client/src/components/creative-commission/CommissionConfigForm.jsx
@@ -14,7 +14,7 @@
import { useEffect, useMemo, useState } from 'react';
import ProviderModelSelector from '../ProviderModelSelector';
import { isProcessProvider } from '../../utils/providers';
-import { getProviders, getSettings, listImageModels, listVideoModels } from '../../services/api';
+import { getProviders, getSettings, listImageModels, listVideoModels, listMusicEngines } from '../../services/api';
import { deriveAvailableBackends } from '../../lib/imageGenBackends';
import {
WEEKDAYS, inputCls, labelCls, describeSchedule,
@@ -185,6 +185,10 @@ export default function CommissionConfigForm({ form, patchForm, saving, onSave,
{/* Generation — fields adapt to the selected output type (#2769) */}
<GenerationSection ability={form.targetAbility} generation={form.generation} patchForm={patchForm} />
+ {form.targetAbility === 'music' && (
+ <MusicTasteSection musicTaste={form.musicTaste} patchForm={patchForm} />
+ )}
+
{/* Render backend — which image/video backend actually renders (#3135) */}
<RenderBackendSection ability={form.targetAbility} generation={form.generation} patchForm={patchForm} />
@@ -286,6 +290,121 @@ function GenerationSection({ ability, generation, patchForm }) {
);
}
+function MusicTasteSection({ musicTaste, patchForm }) {
+ const [catalog, setCatalog] = useState(null);
+
+ useEffect(() => {
+ let cancelled = false;
+ listMusicEngines({ silent: true })
+ .then((value) => { if (!cancelled) setCatalog(value); })
+ .catch(() => { if (!cancelled) setCatalog({ engines: [], defaultEngine: null, error: true }); });
+ return () => { cancelled = true; };
+ }, []);
+
+ const selectedEngineId = musicTaste.musicEngineId || catalog?.defaultEngine || '';
+ const selectedEngine = catalog?.engines?.find((engine) => engine.id === selectedEngineId) || null;
+ let readiness = null;
+ if (catalog?.error) readiness = 'Music engine readiness could not be checked. Open Music → Generate before enabling this commission.';
+ else if (catalog && !selectedEngine) readiness = 'The configured music engine is no longer available. Choose an installed engine before enabling this commission.';
+ else if (selectedEngine && !selectedEngine.platformSupported) readiness = `${selectedEngine.name} requires ${selectedEngine.platformLabel} on this machine.`;
+ else if (selectedEngine?.cudaRequired && selectedEngine.cudaState !== 'available') readiness = `${selectedEngine.name} requires an available NVIDIA CUDA GPU.`;
+ else if (selectedEngine && !selectedEngine.runtimeReady) readiness = `${selectedEngine.name} is not installed. Install its runtime from Music → Generate.`;
+ else if (selectedEngine && !selectedEngine.modelReady) readiness = `${selectedEngine.name} model weights are not installed. Install them from Music → Generate.`;
+ else if (musicTaste.musicModelId && !selectedEngine?.models?.some((model) => model.id === musicTaste.musicModelId)) readiness = 'The configured music model is no longer available. Choose an installed model before enabling this commission.';
+
+ return (
+ <section className="space-y-3 border-t border-port-border pt-4">
+ <h3 className="text-sm font-semibold text-gray-200">Digital Twin taste exploration</h3>
+ <label className="flex items-center gap-2 text-sm text-gray-300" htmlFor="commission-music-taste-enabled">
+ <input
+ id="commission-music-taste-enabled"
+ type="checkbox"
+ checked={musicTaste.enabled}
+ onChange={(e) => patchForm(['musicTaste', 'enabled'], e.target.checked)}
+ />
+ Use my Digital Twin music taste for each scheduled original track
+ </label>
+ <p className="text-xs text-gray-500">
+ Each run combines bounded listening anchors with a controlled amount of exploration. Raw listening history stays on this machine.
+ </p>
+ {musicTaste.enabled && (
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
+ <div>
+ <label className={labelCls} htmlFor="commission-music-taste-source">Taste source</label>
+ <select id="commission-music-taste-source" className={inputCls} value="digital-twin" disabled>
+ <option value="digital-twin">Digital Twin profile</option>
+ </select>
+ </div>
+ <div>
+ <label className={labelCls} htmlFor="commission-music-taste-window">Listening window</label>
+ <select
+ id="commission-music-taste-window"
+ className={inputCls}
+ value={musicTaste.window}
+ onChange={(e) => patchForm(['musicTaste', 'window'], e.target.value)}
+ >
+ <option value="week">Past week</option>
+ <option value="month">Past month</option>
+ </select>
+ </div>
+ <div>
+ <label className={labelCls} htmlFor="commission-music-taste-anchors">Anchors per run</label>
+ <input
+ id="commission-music-taste-anchors"
+ type="number"
+ min={1}
+ max={5}
+ className={inputCls}
+ value={musicTaste.anchorCount}
+ onChange={(e) => patchForm(['musicTaste', 'anchorCount'], e.target.value)}
+ />
+ </div>
+ <div>
+ <label className={labelCls} htmlFor="commission-music-taste-exploration">Exploration (%)</label>
+ <input
+ id="commission-music-taste-exploration"
+ type="number"
+ min={0}
+ max={100}
+ className={inputCls}
+ value={musicTaste.explorationPercent}
+ onChange={(e) => patchForm(['musicTaste', 'explorationPercent'], e.target.value)}
+ />
+ </div>
+ <div>
+ <label className={labelCls} htmlFor="commission-music-taste-engine">Music engine</label>
+ <select
+ id="commission-music-taste-engine"
+ className={inputCls}
+ value={musicTaste.musicEngineId}
+ onChange={(e) => {
+ patchForm(['musicTaste', 'musicEngineId'], e.target.value);
+ patchForm(['musicTaste', 'musicModelId'], '');
+ }}
+ >
+ <option value="">Default music engine</option>
+ {(catalog?.engines || []).map((engine) => <option key={engine.id} value={engine.id}>{engine.name}</option>)}
+ </select>
+ </div>
+ <div>
+ <label className={labelCls} htmlFor="commission-music-taste-model">Music model</label>
+ <select
+ id="commission-music-taste-model"
+ className={inputCls}
+ value={musicTaste.musicModelId}
+ onChange={(e) => patchForm(['musicTaste', 'musicModelId'], e.target.value)}
+ >
+ <option value="">Default model{selectedEngine?.defaultModelId ? ` (${selectedEngine.defaultModelId})` : ''}</option>
+ {(selectedEngine?.models || []).map((model) => <option key={model.id} value={model.id}>{model.name || model.id}</option>)}
+ </select>
+ </div>
+ </div>
+ )}
+ {musicTaste.enabled && readiness && <p className="text-xs text-port-warning">{readiness}</p>}
+ </section>
+ );
+}
+
// Which backend a mode's model picker reads its catalog from.
const MODEL_LOADERS = { image: listImageModels, video: listVideoModels };
diff --git a/client/src/components/creative-commission/CommissionConfigForm.test.jsx b/client/src/components/creative-commission/CommissionConfigForm.test.jsx
new file mode 100644
index 0000000000..80b6bb183c
--- /dev/null
+++ b/client/src/components/creative-commission/CommissionConfigForm.test.jsx
@@ -0,0 +1,102 @@
+import { useState } from 'react';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import CommissionConfigForm from './CommissionConfigForm.jsx';
+import { patchFormState, toForm } from './commissionForm.js';
+
+const api = vi.hoisted(() => ({
+ listMusicEngines: vi.fn(), getProviders: vi.fn(), getSettings: vi.fn(),
+ listImageModels: vi.fn(), listVideoModels: vi.fn(),
+}));
+vi.mock('../../services/api', () => api);
+vi.mock('../ProviderModelSelector', () => ({ default: () => <div data-testid="provider-model-selector" /> }));
+
+function Harness() {
+ const [form, setForm] = useState(toForm({
+ targetAbility: 'music',
+ brief: { intent: 'original ambient track', musicTaste: { source: 'digital-twin' } },
+ generation: { lengthSeconds: 45 },
+ }));
+ return (
+ <CommissionConfigForm
+ form={form}
+ patchForm={(path, value) => setForm((prev) => patchFormState(prev, path, value))}
+ saving={false}
+ onSave={() => {}}
+ />
+ );
+}
+
+beforeEach(() => {
+ api.getProviders.mockResolvedValue({ providers: [] });
+ api.getSettings.mockResolvedValue({});
+ api.listImageModels.mockResolvedValue([]);
+ api.listVideoModels.mockResolvedValue([]);
+ api.listMusicEngines.mockResolvedValue({
+ defaultEngine: 'musicgen',
+ engines: [{
+ id: 'musicgen', name: 'MusicGen', ready: true, runtimeReady: true, modelReady: true,
+ platformSupported: true, cudaRequired: false, defaultModelId: 'default-model',
+ models: [{ id: 'default-model', name: 'Default model' }],
+ }],
+ });
+});
+
+describe('CommissionConfigForm music taste controls', () => {
+ it('exposes the source, window, anchors, exploration, engine, and model', async () => {
+ render(<Harness />);
+ expect(screen.getByRole('checkbox', { name: /use my digital twin music taste/i })).toBeChecked();
+ expect(screen.getByLabelText('Taste source')).toHaveValue('digital-twin');
+ expect(screen.getByLabelText('Listening window')).toHaveValue('month');
+ expect(screen.getByLabelText('Anchors per run')).toHaveValue(3);
+ expect(screen.getByLabelText('Exploration (%)')).toHaveValue(20);
+ await waitFor(() => expect(screen.getByLabelText('Music engine')).toContainHTML('MusicGen'));
+ expect(screen.getByLabelText('Music model')).toContainHTML('Default model');
+ expect(api.listMusicEngines).toHaveBeenCalledWith({ silent: true });
+ });
+
+ it('shows an actionable warning when the selected default runtime is unavailable', async () => {
+ api.listMusicEngines.mockResolvedValueOnce({
+ defaultEngine: 'musicgen',
+ engines: [{
+ id: 'musicgen', name: 'MusicGen', ready: false, runtimeReady: false, modelReady: true,
+ platformSupported: true, cudaRequired: false, defaultModelId: 'default-model', models: [],
+ }],
+ });
+ render(<Harness />);
+ expect(await screen.findByText(/install its runtime from music/i)).toBeInTheDocument();
+ });
+
+ it('warns when a configured model disappeared from the live engine catalog', async () => {
+ function MissingModelHarness() {
+ const [form, setForm] = useState(toForm({
+ targetAbility: 'music', brief: {
+ intent: 'original ambient track',
+ musicTaste: { source: 'digital-twin', musicEngineId: 'musicgen', musicModelId: 'removed-model' },
+ },
+ }));
+ return (
+ <CommissionConfigForm
+ form={form}
+ patchForm={(path, value) => setForm((prev) => patchFormState(prev, path, value))}
+ saving={false}
+ onSave={() => {}}
+ />
+ );
+ }
+ render(<MissingModelHarness />);
+ expect(await screen.findByText(/configured music model is no longer available/i)).toBeInTheDocument();
+ });
+
+ it('lets the user disable taste mode without losing the music commission', async () => {
+ render(<Harness />);
+ await waitFor(() => {
+ expect(api.listMusicEngines).toHaveBeenCalled();
+ expect(api.getProviders).toHaveBeenCalled();
+ expect(api.getSettings).toHaveBeenCalled();
+ });
+ fireEvent.click(screen.getByRole('checkbox', { name: /use my digital twin music taste/i }));
+ expect(screen.queryByLabelText('Listening window')).not.toBeInTheDocument();
+ expect(screen.getByLabelText('Creative output')).toHaveValue('music');
+ });
+});
diff --git a/client/src/components/creative-commission/RenderHistory.jsx b/client/src/components/creative-commission/RenderHistory.jsx
index 22d02c5eb1..d8e46a2d4f 100644
--- a/client/src/components/creative-commission/RenderHistory.jsx
+++ b/client/src/components/creative-commission/RenderHistory.jsx
@@ -28,6 +28,20 @@ const STATUS_CLASS = {
failed: 'text-port-error',
};
+const TASTE_FEEDBACK_OPTIONS = [
+ ['more-familiar', 'More familiar'],
+ ['more-experimental', 'More experimental'],
+ ['keep-anchors', 'Keep anchors'],
+ ['change-anchors', 'Change anchors'],
+];
+
+const TASTE_FEEDBACK_OPPOSITES = {
+ 'more-familiar': 'more-experimental',
+ 'more-experimental': 'more-familiar',
+ 'keep-anchors': 'change-anchors',
+ 'change-anchors': 'keep-anchors',
+};
+
export default function RenderHistory({ runs, feedback, projectsById, projectsLoading, focusRunId, onRate }) {
// Newest-first, memoized so the copy+reverse doesn't run on every render.
const orderedRuns = useMemo(() => [...(runs || [])].reverse(), [runs]);
@@ -118,6 +132,10 @@ export default function RenderHistory({ runs, feedback, projectsById, projectsLo
</Link>
)}
+ {r.tasteRecipe && (
+ <TasteRecipeSummary recipe={r.tasteRecipe} output={r.musicOutput || project?.musicBed} />
+ )}
+
{/* Rate/annotate — pushed to the bottom of the card so cards align.
Keyed on the persisted reaction's timestamp so an externally-changed
note (a federated rating from another machine, arriving via a refetch)
@@ -130,6 +148,7 @@ export default function RenderHistory({ runs, feedback, projectsById, projectsLo
runId={r.id}
current={feedbackByRun[r.id]}
onRate={onRate}
+ tasteAware={!!r.tasteRecipe}
/>
</div>
)}
@@ -141,6 +160,31 @@ export default function RenderHistory({ runs, feedback, projectsById, projectsLo
);
}
+function TasteRecipeSummary({ recipe, output }) {
+ return (
+ <div className="rounded border border-port-border bg-port-bg/60 p-2 space-y-1.5 text-xs">
+ <div className="flex flex-wrap gap-1">
+ {(recipe.anchors || []).map((anchor, index) => (
+ <span key={`${anchor.kind}-${anchor.name}-${index}`} className="rounded bg-port-accent/15 px-1.5 py-0.5 text-blue-300">
+ {anchor.name}{anchor.artist ? ` · ${anchor.artist}` : ''}
+ </span>
+ ))}
+ </div>
+ <p className="text-gray-400">
+ {recipe.explorationPercent}% exploration · {recipe.window} window · recipe v{recipe.version}
+ </p>
+ <p className="text-gray-500 truncate" title={recipe.sourceVersion}>
+ Source {recipe.sourceHash || 'unknown'}
+ </p>
+ {output && (
+ <p className="text-gray-400">
+ Rendered with {output.engine || 'default engine'}{output.modelId ? ` · ${output.modelId}` : ''}
+ </p>
+ )}
+ </div>
+ );
+}
+
// Per-run rate/annotate control (#2657, Phase 2). Thumbs submit immediately,
// carrying whatever note is in the field; the current rating (if any) is shown
// highlighted. Note state is local so typing doesn't re-render the whole gallery.
@@ -152,8 +196,9 @@ export default function RenderHistory({ runs, feedback, projectsById, projectsLo
// dirty) makes the unsaved state obvious and unambiguous, and Enter is a
// shortcut for the same action. A note can't be saved before a rating exists (a
// rating is required), so the affordance only appears once the run is thumbed.
-export function RunFeedback({ runId, current, onRate }) {
+export function RunFeedback({ runId, current, onRate, tasteAware = false }) {
const [note, setNote] = useState(current?.note || '');
+ const [tags, setTags] = useState(current?.tags || []);
const [busy, setBusy] = useState(false);
const rating = current?.rating;
const isUp = rating === 'up' || (typeof rating === 'number' && rating > 0);
@@ -161,17 +206,45 @@ export function RunFeedback({ runId, current, onRate }) {
const submit = async (value) => {
setBusy(true);
- try { await onRate(runId, value, note.trim()); }
+ try { await onRate(runId, value, note.trim(), tags); }
finally { setBusy(false); }
};
// A note edited after the run was rated is "dirty" until re-saved under the
// existing rating. The Save button/Enter shortcut is gated on this.
const noteDirty = !!rating && note.trim() !== (current?.note || '');
- const saveNote = () => { if (noteDirty && !busy) submit(rating); };
+ const currentTags = current?.tags || [];
+ const tagsDirty = !!rating && JSON.stringify([...tags].sort()) !== JSON.stringify([...currentTags].sort());
+ const feedbackDirty = noteDirty || tagsDirty;
+ const saveNote = () => { if (feedbackDirty && !busy) submit(rating); };
+
+ const toggleTag = (tag) => {
+ setTags((value) => {
+ if (value.includes(tag)) return value.filter((entry) => entry !== tag);
+ const opposite = TASTE_FEEDBACK_OPPOSITES[tag];
+ return [...value.filter((entry) => entry !== opposite), tag];
+ });
+ };
return (
- <div className="flex items-center gap-1.5">
+ <div className="space-y-2">
+ {tasteAware && (
+ <div className="flex flex-wrap gap-1" aria-label={`Taste steering for run ${runId}`}>
+ {TASTE_FEEDBACK_OPTIONS.map(([tag, label]) => (
+ <button
+ key={tag}
+ type="button"
+ disabled={busy}
+ aria-pressed={tags.includes(tag)}
+ onClick={() => toggleTag(tag)}
+ className={`rounded border px-1.5 py-0.5 text-[10px] disabled:opacity-50 ${tags.includes(tag) ? 'border-port-accent text-blue-300 bg-port-accent/15' : 'border-port-border text-gray-500'}`}
+ >
+ {label}
+ </button>
+ ))}
+ </div>
+ )}
+ <div className="flex items-center gap-1.5">
<button
type="button"
disabled={busy}
@@ -203,17 +276,18 @@ export function RunFeedback({ runId, current, onRate }) {
onChange={(e) => setNote(e.target.value)}
onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); saveNote(); } }}
/>
- {noteDirty && (
+ {feedbackDirty && (
<button
type="button"
disabled={busy}
onClick={saveNote}
- aria-label={`Save note for run ${runId}`}
+ aria-label={`Save feedback for run ${runId}`}
className="text-xs text-port-accent hover:text-blue-400 disabled:opacity-50 px-1.5 py-1 whitespace-nowrap"
>
Save
</button>
)}
+ </div>
</div>
);
}
diff --git a/client/src/components/creative-commission/RenderHistory.test.jsx b/client/src/components/creative-commission/RenderHistory.test.jsx
new file mode 100644
index 0000000000..26eb7abec8
--- /dev/null
+++ b/client/src/components/creative-commission/RenderHistory.test.jsx
@@ -0,0 +1,44 @@
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { MemoryRouter } from 'react-router';
+import { describe, expect, it, vi } from 'vitest';
+import RenderHistory from './RenderHistory.jsx';
+
+vi.mock('../creative-director/ProjectPreview.jsx', () => ({ default: () => <div>project preview</div> }));
+
+const recipe = {
+ version: 1,
+ source: 'digital-twin',
+ window: 'month',
+ explorationPercent: 35,
+ sourceVersion: 'music-taste-v1:example',
+ sourceHash: 'example-hash',
+ anchors: [{ kind: 'artist', name: 'Example Artist' }],
+};
+
+describe('RenderHistory taste-aware runs', () => {
+ it('shows bounded recipe/render provenance and submits structured steering tags', async () => {
+ const onRate = vi.fn(async () => {});
+ render(
+ <MemoryRouter>
+ <RenderHistory
+ runs={[{
+ id: 'run-example', ranAt: new Date().toISOString(), status: 'started', projectId: 'cd-example',
+ tasteRecipe: recipe,
+ }]}
+ feedback={[]}
+ projectsById={new Map([['cd-example', { id: 'cd-example', musicBed: { engine: 'musicgen', modelId: 'example-model' } }]])}
+ projectsLoading={false}
+ onRate={onRate}
+ />
+ </MemoryRouter>,
+ );
+ expect(screen.getByText('Example Artist')).toBeInTheDocument();
+ expect(screen.getByText(/35% exploration/)).toBeInTheDocument();
+ expect(screen.getByText(/rendered with musicgen · example-model/i)).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'More familiar' }));
+ fireEvent.click(screen.getByRole('button', { name: 'More experimental' }));
+ expect(screen.getByRole('button', { name: 'More familiar' })).toHaveAttribute('aria-pressed', 'false');
+ fireEvent.click(screen.getByRole('button', { name: 'Like this result' }));
+ await waitFor(() => expect(onRate).toHaveBeenCalledWith('run-example', 'up', '', ['more-experimental']));
+ });
+});
diff --git a/client/src/components/creative-commission/commissionForm.js b/client/src/components/creative-commission/commissionForm.js
index 408f79012b..189f78eaa7 100644
--- a/client/src/components/creative-commission/commissionForm.js
+++ b/client/src/components/creative-commission/commissionForm.js
@@ -94,6 +94,16 @@ export const GENERATION_DEFAULTS_BY_ABILITY = {
series: { episodeCount: 1 },
};
+export const MUSIC_TASTE_DEFAULTS = Object.freeze({
+ enabled: false,
+ source: 'digital-twin',
+ window: 'month',
+ anchorCount: 3,
+ explorationPercent: 20,
+ musicEngineId: '',
+ musicModelId: '',
+});
+
// The render-backend descriptors for an ability, in field order. Drives the
// dedicated backend section; the generic field grid skips `type: 'backend'`.
export function backendFieldsForAbility(ability) {
@@ -181,6 +191,15 @@ export function toForm(c) {
genre: c.brief?.genre || '',
styleSpec: c.brief?.styleSpec || '',
},
+ musicTaste: c.brief?.musicTaste ? {
+ enabled: true,
+ source: 'digital-twin',
+ window: c.brief.musicTaste.window || MUSIC_TASTE_DEFAULTS.window,
+ anchorCount: c.brief.musicTaste.anchorCount ?? MUSIC_TASTE_DEFAULTS.anchorCount,
+ explorationPercent: c.brief.musicTaste.explorationPercent ?? MUSIC_TASTE_DEFAULTS.explorationPercent,
+ musicEngineId: c.brief.musicTaste.musicEngineId || '',
+ musicModelId: c.brief.musicTaste.musicModelId || '',
+ } : { ...MUSIC_TASTE_DEFAULTS },
schedule: {
kind: c.schedule?.kind || 'DAILY',
atLocalTime: c.schedule?.atLocalTime || '02:00',
@@ -223,6 +242,14 @@ export function toPayload(form) {
intent: form.brief.intent.trim(),
genre: form.brief.genre.trim() || null,
styleSpec: form.brief.styleSpec,
+ musicTaste: form.targetAbility === 'music' && form.musicTaste.enabled ? {
+ source: 'digital-twin',
+ window: form.musicTaste.window,
+ anchorCount: Number(form.musicTaste.anchorCount),
+ explorationPercent: Number(form.musicTaste.explorationPercent),
+ musicEngineId: form.musicTaste.musicEngineId || null,
+ musicModelId: form.musicTaste.musicModelId || null,
+ } : null,
},
schedule: s,
// Emit only the selected type's generation keys (#2769), coercing numbers.
@@ -269,5 +296,15 @@ export function validateForm(form) {
return `${field.label} must be a whole number from ${field.min} to ${field.max}`;
}
}
+ if (form.targetAbility === 'music' && form.musicTaste?.enabled) {
+ const anchorCount = Number(form.musicTaste.anchorCount);
+ if (form.musicTaste.anchorCount === '' || !Number.isInteger(anchorCount) || anchorCount < 1 || anchorCount > 5) {
+ return 'Taste anchor count must be a whole number from 1 to 5';
+ }
+ const exploration = Number(form.musicTaste.explorationPercent);
+ if (form.musicTaste.explorationPercent === '' || !Number.isInteger(exploration) || exploration < 0 || exploration > 100) {
+ return 'Taste exploration must be a whole percentage from 0 to 100';
+ }
+ }
return null;
}
diff --git a/client/src/components/creative-commission/commissionForm.test.js b/client/src/components/creative-commission/commissionForm.test.js
index 70df515048..f6a703ff19 100644
--- a/client/src/components/creative-commission/commissionForm.test.js
+++ b/client/src/components/creative-commission/commissionForm.test.js
@@ -22,6 +22,10 @@ describe('commissionForm helpers', () => {
videoMode: 'auto', videoModelId: null,
});
expect(f.assignment).toEqual({ providerId: '', model: '' });
+ expect(f.musicTaste).toEqual({
+ enabled: false, source: 'digital-twin', window: 'month', anchorCount: 3,
+ explorationPercent: 20, musicEngineId: '', musicModelId: '',
+ });
expect(f.feedbackWindow).toBe(5);
});
@@ -62,6 +66,25 @@ describe('commissionForm helpers', () => {
const form = { ...blankForm(), brief: { intent: 'x', genre: ' ', styleSpec: '' } };
expect(toPayload(form).brief.genre).toBeNull();
});
+
+ it('round-trips taste controls only for an opted-in music commission', () => {
+ const form = toForm({
+ name: 'Taste study', targetAbility: 'music', brief: {
+ intent: 'original ambient track',
+ musicTaste: {
+ source: 'digital-twin', window: 'week', anchorCount: 4, explorationPercent: 35,
+ musicEngineId: 'acestep', musicModelId: 'example-model',
+ },
+ },
+ });
+ expect(form.musicTaste).toMatchObject({ enabled: true, anchorCount: 4, explorationPercent: 35 });
+ expect(toPayload(form).brief.musicTaste).toEqual({
+ source: 'digital-twin', window: 'week', anchorCount: 4, explorationPercent: 35,
+ musicEngineId: 'acestep', musicModelId: 'example-model',
+ });
+ form.musicTaste.enabled = false;
+ expect(toPayload(form).brief.musicTaste).toBeNull();
+ });
});
describe('validateForm', () => {
@@ -84,6 +107,14 @@ describe('commissionForm helpers', () => {
it('rejects an out-of-range feedback window', () => {
expect(validateForm({ ...base(), feedbackWindow: 99 })).toMatch(/feedback window/i);
});
+ it('validates bounded taste controls when enabled', () => {
+ const form = toForm({ name: 'Taste', targetAbility: 'music', brief: { intent: 'x', musicTaste: { source: 'digital-twin' } } });
+ form.musicTaste.anchorCount = 0;
+ expect(validateForm(form)).toMatch(/anchor count/i);
+ form.musicTaste.anchorCount = 3;
+ form.musicTaste.explorationPercent = 101;
+ expect(validateForm(form)).toMatch(/exploration/i);
+ });
});
describe('patchFormState', () => {
diff --git a/client/src/pages/CreativeCommissionDetail.jsx b/client/src/pages/CreativeCommissionDetail.jsx
index 1c018d8642..9958561603 100644
--- a/client/src/pages/CreativeCommissionDetail.jsx
+++ b/client/src/pages/CreativeCommissionDetail.jsx
@@ -238,9 +238,9 @@ export default function CreativeCommissionDetail() {
};
// Rate/annotate a run's output — folds into the next scheduled run's directive.
- const handleRate = useCallback(async (runId, rating, note) => {
+ const handleRate = useCallback(async (runId, rating, note, tags = []) => {
try {
- const updated = await submitCommissionFeedback(id, { runId, rating, note: note || '' }, { silent: true });
+ const updated = await submitCommissionFeedback(id, { runId, rating, note: note || '', tags }, { silent: true });
setCommission(updated);
toast.success('Feedback saved — it steers the next run');
} catch (e) {
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 525c1f6f40..066acf7446 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -35,7 +35,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
- `catalog_user_types` — user-defined ingredient types (the registry that defines catalog row semantics), one row per type (`id` PK, the definition in `data` JSONB, `updated_at`/`deleted_at` mirroring the federation LWW clock + tombstone). Migrated from the `data/settings.json` `catalogUserTypes` slice in Phase 4 lead-in (#1001) so type evolution versions/syncs alongside the catalog data it governs. Federates via the catalog sync `catalogTypes` envelope block (wire shape unchanged by the move). Adapter: `server/services/catalogUserTypes/db.js`, dispatched via `store.js`.
- `universes` / `universe_runs` — Universe Builder records (canon bibles, categories, composite sheets, locks, influences) one row per universe with the full sanitized record in `data` JSONB and `name`/`schema_version`/`ephemeral`/`updated_at`/`deleted`/`deleted_at` mirrored into columns; render-run history one row per run (local-only, capped 200, never federated). Migrated from `data/universes/{id}/index.json` (collectionStore) in Phase 3 Create slice 1 (#1014). **NO `sync_sequence`** — universes federate via the EXISTING `dataSync` snapshot/push model (LWW on the body's `updatedAt`), so the storage swap is invisible to peers (no schema-version bump). The store bumps an in-process mutation epoch on every write that `dataSync` folds into its checksum fingerprint, since a DB edit no longer changes the `data/universes/` directory the fingerprint used to watch. **`universe_runs` is intentionally never federated** — a regenerable render cache under a 200-row *global* cap that two producers would mutually evict, while the durable universe record already syncs (ADR [tribe + universe-runs local](./decisions/2026-06-26-tribe-and-universe-runs-local.md), #1724). Adapter: `server/services/universeBuilder/db.js`, dispatched via `store.js`.
- `tribe_people` / `tribe_touchpoints` / `tribe_memory_links` — the Tribe relationship/CRM graph (people + their care cadence, contact touchpoints, and cross-links into brain `memories`). **Intentionally machine-local — never federated** (ADR [tribe + universe-runs local](./decisions/2026-06-26-tribe-and-universe-runs-local.md), #1724): it is relationship-graph data, mirroring the deliberate "memory_links are instance-local" boundary in `memorySync.js` (memory *nodes* federate, the link graph does not), and is coupled to machine-local domains — `tribe_memory_links` extends the non-federated `memory_links` layer and `tribe_touchpoints` carry per-machine calendar-account refs. NO `sync_sequence`, no peer-sync record kind, no `dataSync` category. Adapter: `server/services/tribe.js`.
-- `creative_commissions` — Creative Commissions (Autonomous Creation Engine, #2657/#2686): standing recurring creative briefs that fire on a cron cadence and drive the Creative Director directive pipeline unattended. One row per commission, the full sanitized record in `data` JSONB with `name`/`enabled`/`created_at`/`updated_at` mirrored into columns for the scheduler's "arm every enabled commission" query. The **brief** (including bounded `brief.musicTaste` configuration) and feedback federate; the machine-local `schedule`, `runs[]`, `assignment`, and `enabled` fields never cross peers, so only the owning machine fires a cron and keeps local taste-recipe provenance. Brief updates use a `briefUpdatedAt` LWW clock, with `deleted`/`deleted_at` tombstones for brief federation. Raw Digital Twin/Spotify records and full responses remain machine-local. Adapter: `server/services/creativeCommissions/db.js`, selected pg-vs-file by `server/services/creativeCommissions/store.js` (file backend is the `NODE_ENV=test`/`MEMORY_BACKEND=file` escape hatch only).
+- `creative_commissions` — Creative Commissions (Autonomous Creation Engine, #2657/#2686): standing recurring creative briefs that fire on a cron cadence and drive the Creative Director directive pipeline unattended. One row per commission, the full sanitized record in `data` JSONB with `name`/`enabled`/`created_at`/`updated_at` mirrored into columns for the scheduler's "arm every enabled commission" query. The **brief** (including bounded `brief.musicTaste` configuration) and feedback federate; the machine-local `schedule`, `runs[]`, `assignment`, and `enabled` fields never cross peers, so only the owning machine fires a cron and keeps local taste-recipe, selected renderer, and completed-audio provenance. Brief updates use a `briefUpdatedAt` LWW clock, with `deleted`/`deleted_at` tombstones for brief federation. Raw Digital Twin/Spotify records and full responses remain machine-local. Adapter: `server/services/creativeCommissions/db.js`, selected pg-vs-file by `server/services/creativeCommissions/store.js` (file backend is the `NODE_ENV=test`/`MEMORY_BACKEND=file` escape hatch only).
- `games` — Game studio workspaces (#3177): one row per managed-app asset plan, with the full reusable sprite/music binding set, current compiled-manifest pointer, compile history, and user-requested AI feedback history in `data` JSONB; `app_id`/`name`/`updated_at` are mirrored for list and relationship queries. The record is **machine-local** because managed-app registration, sprite atlases, and music-library bytes are machine-local; there is no peer-sync cursor or tombstone, and deletes are hard deletes. Compiled manifests are immutable, SHA-256-addressed artifacts under `data/games/{id}/manifests/`; their pointers and hashes live in the DB record. Adapter: `server/services/games/db.js`, selected pg-vs-collectionStore by `server/services/games/store.js` (collectionStore is test/unsupported file escape hatch only).
- `threejs_models` — generated procedural 3D-model workspaces: one row per model with gallery-image lineage, provider/model attribution, generation/refinement status, and the validated declarative scene spec in `data` JSONB. The referenced image bytes remain under `data/images/`; deterministic Three.js source is derived from the stored spec rather than persisted as a second mutable artifact. The table is local-only in this first slice, with soft-delete columns retained so federation can be added without a record-shape migration.
- `privacy_subjects` / `privacy_vault_records` / `privacy_consents` / `privacy_orgs` / `privacy_org_holdings` / `privacy_change_events` / `privacy_brokers` / `privacy_broker_cases` — the Privacy Center (epic #2138): the household subjects the suite works on behalf of (`self` plus consenting partners/children/parents — every other table carries a `subject_id` FK defaulted to the seeded `self` row, #3658), the encrypted PII vault, the trusted-organization registry with per-field holdings, the change-of-address inventory, and the data-broker opt-out ledger. Relational by nature (org ↔ holdings ↔ vault records ↔ change events ↔ broker cases), which is why they are `db-primary`. Vault *values* are AES-256-GCM ciphertext (`v1:<iv>:<tag>:<ct>`, key from `PRIVACY_VAULT_KEY`) — the DB holds bytes of ciphertext, never plaintext PII, and plaintext never appears in logs (`server/lib/vaultCrypto.js`). **Intentionally machine-local — never federated**, and this is a product *guarantee*, not a deferred feature (ADR [privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md), #2148). NO `sync_sequence`, NO peer-sync record kind, NO `dataSync` category, NO `PORTOS_SCHEMA_VERSIONS` entry, and no `deleted`/`deleted_at` tombstones — deletes are hard deletes, mirroring `tribe`. The reasoning is the same class as the Tribe graph but stronger: the peer-sync **pull** path (`GET /api/peer-sync/record`) carries no peer identity, `masked_value` is plaintext by design so even ciphertext-only sync would leak a PII fingerprint, and a shared `PRIVACY_VAULT_KEY` would widen the at-rest blast radius to every peer's `.env`. A second machine gets the vault by restoring a backup and copying the key by hand — a deliberate act, not continuous replication. Enforced by `server/services/sharing/privacyNeverFederates.test.js`. Adapters: `server/services/privacySubjects.js`, `privacyVault.js`, `privacyOrgs.js`, `privacyChanges.js`, `privacyBrokers.js`, `privacyOptOut.js`.
diff --git a/docs/features/digital-twin.md b/docs/features/digital-twin.md
index 04a4bc1858..7de7a322d1 100644
--- a/docs/features/digital-twin.md
+++ b/docs/features/digital-twin.md
@@ -70,8 +70,12 @@ Routes: `GET /import/sources`, `POST /import/analyze`, `POST /import/save`,
Music Creative Commissions can opt into a bounded Digital Twin recipe. The
scheduled fire reads the stated music summary and the selected observed rollup
window, then deterministically chooses a small set of artist/track anchors and
-an exploration level. Ratings and the existing feedback tags adjust the next
-recipe; no provider call is made to build the recipe.
+an exploration level. The commission editor exposes the source, week/month
+window, anchor count, exploration percentage, and installed music engine/model.
+It also reports an unavailable runtime, platform, GPU, or model before a user
+depends on the schedule. Creating and enabling the commission is the explicit
+consent step for this scheduled automation; merely starting PortOS makes no AI
+or music-generation calls.
The commission brief carries only the non-sensitive opt-in configuration. Raw
Spotify caches, activity events, full Digital Twin responses, and the selected
@@ -79,10 +83,17 @@ recipe remain machine-local. Recipes are recorded as bounded run provenance and
are removed by the Creative Commission wire projection along with all local run
history. If taste mode has no usable observed anchors, the run records
`taste-source-unavailable` instead of silently generating a generic track.
-
-This slice does not yet expose taste controls in the Creative Commission UI or
-propagate engine/model pins through the audio job and completion-hook path; those
-are follow-up work for issue #4347.
+At fire time, PortOS revalidates the configured renderer and records an explicit
+engine/model-unavailable skip if it changed. The bounded directive, renderer,
+and duration then override planner guesses on the actual audio job. Completion
+records the rendered engine/model and recipe version/hash on the local run while
+the federated Creative Director project receives only ordinary audio metadata.
+
+Run history shows the bounded anchors, exploration level, source hash, and
+actual renderer. In addition to thumbs and notes, taste-aware runs offer
+`more familiar`, `more experimental`, `keep anchors`, and `change anchors`
+feedback. These structured reactions federate with the existing feedback record
+and deterministically steer later recipes without exposing raw listening data.
## Transcript & Image Analysis
diff --git a/server/lib/syncWire.test.js b/server/lib/syncWire.test.js
index e7bb5ba9a2..16732e40b0 100644
--- a/server/lib/syncWire.test.js
+++ b/server/lib/syncWire.test.js
@@ -231,12 +231,17 @@ describe('syncWire', () => {
expect(JSON.stringify(withPins)).toBe(JSON.stringify(preField));
});
- it('strips local commission runs, including taste recipes, from the brief wire form (#4347)', () => {
+ it('strips local commission runs, including taste and audio provenance, from the brief wire form (#4347)', () => {
const withLocalRun = sanitizeRecordForWire('creativeCommission', {
id: 'commission-example',
name: 'Example Commission',
brief: { intent: 'ambient', musicTaste: { source: 'digital-twin', window: 'month' } },
- runs: [{ id: 'run-example', tasteRecipe: { source: 'digital-twin', sourceHash: 'private-local' } }],
+ runs: [{
+ id: 'run-example',
+ tasteRecipe: { source: 'digital-twin', sourceHash: 'private-local' },
+ musicGeneration: { engine: 'musicgen', modelId: 'example-model', durationSec: 45 },
+ musicOutput: { filename: 'example.wav', sourceHash: 'private-local' },
+ }],
schedule: { kind: 'DAILY' },
assignment: { providerId: 'local-only' },
feedback: [],
diff --git a/server/services/audioGen/local.js b/server/services/audioGen/local.js
index 3bb6dd65a2..66acea7322 100644
--- a/server/services/audioGen/local.js
+++ b/server/services/audioGen/local.js
@@ -24,7 +24,7 @@ import { audioGenEvents } from './events.js';
// jobId → AbortController, so cancelJob() can interrupt an in-flight render.
const controllers = new Map();
-export async function generateAudio({ jobId, prompt, lyrics, engine, durationSec, durationMode, modelId, repo }) {
+export async function generateAudio({ jobId, prompt, lyrics, engine, durationSec, durationMode, modelId, repo, provenance }) {
const controller = new AbortController();
controllers.set(jobId, controller);
try {
@@ -36,6 +36,7 @@ export async function generateAudio({ jobId, prompt, lyrics, engine, durationSec
durationMode,
modelId,
repo,
+ provenance,
signal: controller.signal,
onActivity: () => audioGenEvents.emit('activity', { generationId: jobId }),
});
diff --git a/server/services/creative/tools/media.js b/server/services/creative/tools/media.js
index 47c211ed38..f41cc1632a 100644
--- a/server/services/creative/tools/media.js
+++ b/server/services/creative/tools/media.js
@@ -78,10 +78,42 @@ async function enforceVideoRenderPreset(params, project) {
* `creativeDirectorMusicBed` already on the params (a caller that set its own
* destination) wins and is left as-is.
*/
-function attachMusicBedTag(params, ctx) {
+async function configureMusicJob(params, ctx) {
if (!ctx?.projectId) return params;
- if (params?.creativeDirectorMusicBed) return params;
- return { ...params, creativeDirectorMusicBed: { projectId: ctx.projectId } };
+ 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 } };
+ }
+ if (typeof context.prompt !== 'string' || !context.prompt.trim()) {
+ throw new Error('taste-commission-prompt-unavailable');
+ }
+ const {
+ engine: _plannerEngine,
+ modelId: _plannerModel,
+ repo: _plannerRepo,
+ durationSec: _plannerDuration,
+ durationMode: _plannerDurationMode,
+ provenance: _plannerProvenance,
+ ...rest
+ } = params || {};
+ return {
+ ...rest,
+ prompt: context.prompt,
+ ...context.musicGeneration,
+ creativeDirectorMusicBed: { projectId: ctx.projectId },
+ provenance: {
+ kind: 'creative-commission-music-taste',
+ commissionId: context.commissionId,
+ runId: context.runId,
+ recipeVersion: context.tasteRecipe.version,
+ sourceHash: context.tasteRecipe.sourceHash,
+ },
+ };
}
/**
@@ -224,7 +256,7 @@ const mediaTool = (kind, label) => ({
execute: async (args, ctx) => {
let params = args.params || {};
if (kind === 'audio') {
- params = attachMusicBedTag(params, ctx);
+ params = await configureMusicJob(params, ctx);
} else {
// Image + video both consult the owning project: video for its locked
// geometry preset, both for a pinned render backend (#3135).
diff --git a/server/services/creative/tools/media.test.js b/server/services/creative/tools/media.test.js
index b955072926..cdc35dbe1b 100644
--- a/server/services/creative/tools/media.test.js
+++ b/server/services/creative/tools/media.test.js
@@ -6,6 +6,10 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../mediaJobQueue/index.js', () => ({ enqueueJob: vi.fn(() => ({ jobId: 'mj-test' })) }));
vi.mock('../../settings.js', () => ({ getSettings: vi.fn(async () => ({})) }));
vi.mock('../../creativeDirector/local.js', () => ({ getProject: vi.fn(async () => null) }));
+const getCommissionMusicContextForProject = vi.fn(async () => null);
+vi.mock('../../creativeCommissions/store.js', () => ({
+ getCommissionMusicContextForProject: (...args) => getCommissionMusicContextForProject(...args),
+}));
import { enqueueJob } from '../../mediaJobQueue/index.js';
import { getSettings } from '../../settings.js';
@@ -24,6 +28,7 @@ beforeEach(() => {
vi.clearAllMocks();
getSettings.mockResolvedValue({});
getProject.mockResolvedValue(null);
+ getCommissionMusicContextForProject.mockResolvedValue(null);
});
describe('render-backend pin — the auto/unpinned path is a strict no-op (#3135)', () => {
@@ -316,11 +321,52 @@ describe('render-backend pin — video (#3135)', () => {
});
});
-describe('audio enqueues never consult the render-backend pin', () => {
+describe('audio enqueues', () => {
it('tags the music bed without reading the project or 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(getSettings).not.toHaveBeenCalled();
});
+
+ it('authoritatively applies a taste commission recipe and configured renderer', async () => {
+ getCommissionMusicContextForProject.mockResolvedValue({
+ commissionId: 'commission-example',
+ runId: 'run-example',
+ prompt: 'Bounded taste directive with original-work constraints',
+ tasteRecipe: { version: 1, sourceHash: 'example-hash' },
+ musicGeneration: { engine: 'acestep', modelId: 'example-model', repo: 'example/model', durationSec: 45 },
+ });
+ await run('media_enqueueAudioJob', {
+ prompt: 'planner guess', engine: 'musicgen', modelId: 'wrong', durationSec: 5, durationMode: 'auto',
+ }, { projectId: 'cd-1' });
+ expect(enqueued().params).toEqual({
+ prompt: 'Bounded taste directive with original-work constraints',
+ engine: 'acestep', modelId: 'example-model', repo: 'example/model', durationSec: 45,
+ creativeDirectorMusicBed: { projectId: 'cd-1' },
+ provenance: {
+ kind: 'creative-commission-music-taste', commissionId: 'commission-example', runId: 'run-example',
+ recipeVersion: 1, sourceHash: 'example-hash',
+ },
+ });
+ });
+
+ it('fails closed when local taste provenance cannot be resolved', async () => {
+ getCommissionMusicContextForProject.mockRejectedValueOnce(new Error('commission store unavailable'));
+ await expect(run('media_enqueueAudioJob', {
+ prompt: 'planner guess', engine: 'musicgen', modelId: 'planner-model', durationSec: 5,
+ }, { projectId: 'cd-1' })).rejects.toThrow('commission store unavailable');
+ expect(enqueueJob).not.toHaveBeenCalled();
+ });
+
+ it('fails closed when a taste run lost its bounded authoritative prompt', async () => {
+ getCommissionMusicContextForProject.mockResolvedValueOnce({
+ commissionId: 'commission-example', runId: 'run-example', prompt: null,
+ tasteRecipe: { version: 1, sourceHash: 'example-hash' },
+ musicGeneration: { engine: 'acestep', modelId: 'example-model', durationSec: 45 },
+ });
+ await expect(run('media_enqueueAudioJob', { prompt: 'planner guess' }, { projectId: 'cd-1' }))
+ .rejects.toThrow('taste-commission-prompt-unavailable');
+ expect(enqueueJob).not.toHaveBeenCalled();
+ });
});
diff --git a/server/services/creativeCommissions/abilityAdapters.js b/server/services/creativeCommissions/abilityAdapters.js
index 3371cb95cb..f62b080c9b 100644
--- a/server/services/creativeCommissions/abilityAdapters.js
+++ b/server/services/creativeCommissions/abilityAdapters.js
@@ -196,7 +196,11 @@ const musicAdapter = {
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);
const tastePrompt = renderMusicTasteRecipePrompt(tasteRecipe);
- if (tastePrompt) lines.push(tastePrompt);
+ // Keep the bounded recipe + original-work constraint ahead of user-authored
+ // brief fields. composeDirectiveGoal truncates only the tail when the brief
+ // reaches its cap, so appending this would silently drop the authoritative
+ // taste prompt on long intents/styles before the audio job ever sees it.
+ if (tastePrompt) lines.splice(1, 0, tastePrompt);
return { goal: composeDirectiveGoal(lines, digest), deliverables: [`One ~${secs}s music track matching the brief`], constraints };
},
};
diff --git a/server/services/creativeCommissions/abilityAdapters.test.js b/server/services/creativeCommissions/abilityAdapters.test.js
index ad675d510a..22e790453e 100644
--- a/server/services/creativeCommissions/abilityAdapters.test.js
+++ b/server/services/creativeCommissions/abilityAdapters.test.js
@@ -95,6 +95,25 @@ describe('per-ability directives steer the planner to the right tools', () => {
expect(d.deliverables).toEqual(['One ~45s music track matching the brief']);
});
+ it('music: preserves taste anchors and original-work constraints under the goal cap', () => {
+ const d = buildCommissionDirective({
+ targetAbility: 'music',
+ brief: { intent: 'x'.repeat(2000), styleSpec: 'y'.repeat(5000) },
+ generation: { lengthSeconds: 45 },
+ }, {
+ tasteRecipe: {
+ version: 1, source: 'digital-twin', window: 'month', anchorCount: 1,
+ explorationPercent: 20, explorationCount: 0, explorationDirection: 'balanced',
+ anchors: [{ kind: 'artist', name: 'Example Artist', count: 3, source: 'observed' }],
+ sourceVersion: 'music-taste-v1:example', sourceHash: 'example-hash',
+ },
+ });
+ expect(d.goal.length).toBeLessThanOrEqual(4500);
+ expect(d.goal).toContain('Example Artist');
+ expect(d.goal).toContain('Create an original work');
+ expect(d.goal).toContain('do not reproduce source tracks');
+ });
+
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);
diff --git a/server/services/creativeCommissions/feedbackLogic.test.js b/server/services/creativeCommissions/feedbackLogic.test.js
index a25ca56870..5d1c000df2 100644
--- a/server/services/creativeCommissions/feedbackLogic.test.js
+++ b/server/services/creativeCommissions/feedbackLogic.test.js
@@ -52,6 +52,19 @@ describe('sanitizeCommissionFeedbackForSync', () => {
expect(rec.deleted).toBe(true);
expect(rec.deletedAt).toBe('2026-02-02T00:00:00.000Z');
});
+
+ it('preserves structured taste tags while remaining compatible with older untagged reactions', () => {
+ const tagged = sanitizeCommissionFeedbackForSync({
+ id: 'cfeedback-tagged', commissionId: 'commission-x', runId: 'run-tagged', rating: 'up',
+ tags: ['more-familiar', 'keep-anchors'], updatedAt: '2026-08-16T00:00:00.000Z',
+ });
+ const legacy = sanitizeCommissionFeedbackForSync({
+ id: 'cfeedback-legacy', commissionId: 'commission-x', runId: 'run-legacy', rating: 'down',
+ updatedAt: '2026-08-15T00:00:00.000Z',
+ });
+ expect(tagged.tags).toEqual(['more-familiar', 'keep-anchors']);
+ expect(legacy.tags).toEqual([]);
+ });
});
describe('mergeCommissionFeedbackRecord (LWW)', () => {
@@ -73,6 +86,17 @@ describe('mergeCommissionFeedbackRecord (LWW)', () => {
expect(next.rating).toBe('down');
});
+ it('lets a newer tagged re-rating win over an older peer that omitted tags', () => {
+ const local = { ...base, tags: [] };
+ const remote = {
+ ...base, rating: 'up', tags: ['more-experimental', 'change-anchors'],
+ updatedAt: '2026-03-03T00:00:00.000Z',
+ };
+ const { next, remoteWins } = mergeCommissionFeedbackRecord(local, remote);
+ expect(remoteWins).toBe(true);
+ expect(next.tags).toEqual(['more-experimental', 'change-anchors']);
+ });
+
it('older remote loses to a newer local (LWW, no clobber)', () => {
const local = { ...base, rating: 'down', updatedAt: '2026-03-03T00:00:00.000Z' };
const remote = { ...base, rating: 'up', updatedAt: '2026-01-01T00:00:00.000Z' };
diff --git a/server/services/creativeCommissions/musicTasteRecipe.js b/server/services/creativeCommissions/musicTasteRecipe.js
index add2cb4713..4029e51653 100644
--- a/server/services/creativeCommissions/musicTasteRecipe.js
+++ b/server/services/creativeCommissions/musicTasteRecipe.js
@@ -114,7 +114,7 @@ function pickFromPool(pool, count, seed, attempt, used) {
return picked;
}
-function selectAnchors(candidates, config, seed, recentRecipes, explorationPercent) {
+function selectAnchors(candidates, config, seed, recentRecipes, explorationPercent, keepRecipe = null) {
if (candidates.length === 0) return [];
const anchorCount = Math.min(config.anchorCount, candidates.length);
const explorationCount = Math.min(anchorCount, Math.round(anchorCount * explorationPercent / 100));
@@ -124,6 +124,29 @@ function selectAnchors(candidates, config, seed, recentRecipes, explorationPerce
const all = orderedPool(candidates, `${seed}:all`, 'familiar');
const recent = new Set((recentRecipes || []).map((recipe) => combinationKey(recipe?.anchors)).filter(Boolean));
+ // `keep-anchors` is a literal steering command, not merely a request to lower
+ // exploration. Reuse every still-available anchor from the rated run, then
+ // deterministically fill any gaps if the observed window has changed.
+ if (keepRecipe?.anchors?.length) {
+ const candidatesByKey = new Map(candidates.map((candidate) => [anchorKey(candidate), candidate]));
+ const retained = [];
+ const used = new Set();
+ for (const anchor of keepRecipe.anchors) {
+ const candidate = candidatesByKey.get(anchorKey(anchor));
+ const key = candidate && anchorKey(candidate);
+ if (!candidate || used.has(key)) continue;
+ used.add(key);
+ retained.push(candidate);
+ if (retained.length === anchorCount) return retained;
+ }
+ if (retained.length > 0) {
+ return [
+ ...retained,
+ ...pickFromPool(all, anchorCount - retained.length, `${seed}:keep`, 0, used),
+ ];
+ }
+ }
+
let selected = [];
for (let attempt = 0; attempt <= candidates.length; attempt += 1) {
const used = new Set();
@@ -138,6 +161,23 @@ function selectAnchors(candidates, config, seed, recentRecipes, explorationPerce
return selected;
}
+function anchorFeedbackPreference(feedback, recentRuns) {
+ const reactions = Array.isArray(feedback) ? feedback.slice(-5) : [];
+ const runs = Array.isArray(recentRuns) ? recentRuns : [];
+ for (let index = reactions.length - 1; index >= 0; index -= 1) {
+ const reaction = reactions[index];
+ const tags = Array.isArray(reaction?.tags) ? reaction.tags : [];
+ const keep = tags.includes('keep-anchors');
+ const change = tags.includes('change-anchors');
+ if (keep === change) continue; // neither, or a contradictory legacy record
+ if (change) return { mode: 'change', recipe: null };
+ const ratedRun = runs.find((run) => run?.id === reaction?.runId);
+ const fallbackRun = runs.length ? runs[runs.length - 1] : null;
+ return { mode: 'keep', recipe: ratedRun?.tasteRecipe || fallbackRun?.tasteRecipe || null };
+ }
+ return { mode: null, recipe: null };
+}
+
function feedbackAdjustment(feedback) {
const recent = Array.isArray(feedback) ? feedback.slice(-5) : [];
let adjustment = 0;
@@ -228,7 +268,15 @@ export function buildMusicTasteRecipe({ commissionId, config: rawConfig, stated,
.slice(0, MUSIC_TASTE_RECIPE_MAX_SOURCE_VERSION);
const stableSeed = seed || `${commissionId || 'commission'}:${sourceHash}:${(recentRuns || []).map((run) => run?.id || '').join(',')}`;
const recentRecipes = (recentRuns || []).map((run) => run?.tasteRecipe).filter(Boolean);
- const anchors = selectAnchors(candidates, config, stableSeed, recentRecipes, effectiveExplorationPercent);
+ const anchorPreference = anchorFeedbackPreference(feedback, recentRuns);
+ const anchors = selectAnchors(
+ candidates,
+ config,
+ stableSeed,
+ recentRecipes,
+ effectiveExplorationPercent,
+ anchorPreference.mode === 'keep' ? anchorPreference.recipe : null,
+ );
return {
status: 'ready',
recipe: sanitizeMusicTasteRecipe({
diff --git a/server/services/creativeCommissions/musicTasteRecipe.test.js b/server/services/creativeCommissions/musicTasteRecipe.test.js
index ca9a0f3d4f..4616a071df 100644
--- a/server/services/creativeCommissions/musicTasteRecipe.test.js
+++ b/server/services/creativeCommissions/musicTasteRecipe.test.js
@@ -80,15 +80,26 @@ describe('buildMusicTasteRecipe', () => {
expect(result.recipe.anchors.every((anchor) => anchor.name.length <= 120)).toBe(true);
});
- it('avoids the most recent exact anchor combination when another exists', () => {
+ it('changes the rated anchor combination when feedback asks for new anchors', () => {
const first = buildMusicTasteRecipe(sourceArgs({ config: config({ anchorCount: 2, explorationPercent: 0 }) })).recipe;
const next = buildMusicTasteRecipe(sourceArgs({
config: config({ anchorCount: 2, explorationPercent: 0 }),
recentRuns: [{ id: 'run-previous', tasteRecipe: first }],
+ feedback: [{ runId: 'run-previous', rating: 'down', tags: ['change-anchors'] }],
})).recipe;
expect(combo(next)).not.toBe(combo(first));
});
+ it('reuses the rated combination when feedback asks to keep its anchors', () => {
+ const first = buildMusicTasteRecipe(sourceArgs({ config: config({ anchorCount: 2, explorationPercent: 20 }) })).recipe;
+ const next = buildMusicTasteRecipe(sourceArgs({
+ config: config({ anchorCount: 2, explorationPercent: 20 }),
+ recentRuns: [{ id: 'run-previous', tasteRecipe: first }],
+ feedback: [{ runId: 'run-previous', rating: 'up', tags: ['keep-anchors'] }],
+ })).recipe;
+ expect(combo(next)).toBe(combo(first));
+ });
+
it('returns an explicit unavailable result without observed anchors', () => {
expect(buildMusicTasteRecipe(sourceArgs({ observed: null })))
.toEqual({ status: 'unavailable', reason: 'taste-source-unavailable' });
diff --git a/server/services/creativeCommissions/scheduler.js b/server/services/creativeCommissions/scheduler.js
index 1996696c4b..aa9df7537e 100644
--- a/server/services/creativeCommissions/scheduler.js
+++ b/server/services/creativeCommissions/scheduler.js
@@ -218,6 +218,7 @@ async function fireCommission(commission, trigger) {
// a retry mints a duplicate.
let startedProjectId = null;
let startedTasteRecipe = null;
+ let startedMusicGeneration = null;
const skip = async (reason) => {
const run = await recordCommissionRun(commissionId, { status: 'skipped', reason, trigger }).catch(() => null);
return { status: 'skipped', reason, run };
@@ -250,6 +251,18 @@ async function fireCommission(commission, trigger) {
const tasteResult = await resolveMusicTasteRecipe(commission);
if (tasteResult?.status === 'unavailable') return skip(tasteResult.reason);
startedTasteRecipe = tasteResult?.recipe || null;
+ if (startedTasteRecipe) {
+ const { resolveMusicEngineSelection } = await import('../musicEngineCatalog.js');
+ const engineResult = await resolveMusicEngineSelection({
+ engineId: commission.brief.musicTaste.musicEngineId,
+ modelId: commission.brief.musicTaste.musicModelId,
+ }).catch(() => ({ status: 'unavailable', reason: 'music-engine-unavailable' }));
+ if (engineResult.status !== 'ready') return skip(engineResult.reason);
+ startedMusicGeneration = {
+ ...engineResult.selection,
+ durationSec: commission.generation.lengthSeconds,
+ };
+ }
// 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
@@ -332,7 +345,12 @@ async function fireCommission(commission, trigger) {
projectId: project.id,
promptUsed: directive.goal,
...(startedTasteRecipe ? { tasteRecipe: startedTasteRecipe } : {}),
+ ...(startedMusicGeneration ? { musicGeneration: startedMusicGeneration } : {}),
}).catch(() => null);
+ // A taste-aware audio enqueue resolves its authoritative prompt/renderer
+ // from this local run. If the write failed, advancing would make that lookup
+ // look legitimately absent and silently release planner defaults instead.
+ if (startedTasteRecipe && !run) throw new Error('taste-run-persistence-unavailable');
// Surface the fire (notification + brain inbox) so the user can rate the
// result once it lands — the reaction feeds the next run via
@@ -351,6 +369,7 @@ async function fireCommission(commission, trigger) {
const run = await recordCommissionRun(commissionId, {
status: 'failed', error, trigger, projectId: startedProjectId,
...(startedTasteRecipe ? { tasteRecipe: startedTasteRecipe } : {}),
+ ...(startedMusicGeneration ? { musicGeneration: startedMusicGeneration } : {}),
}).catch(() => null);
return { status: 'failed', error, projectId: startedProjectId, run };
}
diff --git a/server/services/creativeCommissions/scheduler.test.js b/server/services/creativeCommissions/scheduler.test.js
index 7ddffbd361..c8b64ec503 100644
--- a/server/services/creativeCommissions/scheduler.test.js
+++ b/server/services/creativeCommissions/scheduler.test.js
@@ -55,6 +55,12 @@ const tasteEvidenceMock = vi.fn(async () => ({
}));
vi.mock('../taste-questionnaire.js', () => ({ getTasteProfile: (...a) => tasteProfileMock(...a) }));
vi.mock('../twinEnrichment.js', () => ({ getTasteEvidence: (...a) => tasteEvidenceMock(...a) }));
+const resolveMusicEngineSelectionMock = vi.fn(async () => ({
+ status: 'ready', selection: { engine: 'musicgen', modelId: 'musicgen-medium', repo: 'example/musicgen-medium' },
+}));
+vi.mock('../musicEngineCatalog.js', () => ({
+ resolveMusicEngineSelection: (...a) => resolveMusicEngineSelectionMock(...a),
+}));
const loadStateMock = vi.fn(async () => ({ config: {} }));
vi.mock('../cosState.js', () => ({ loadState: (...a) => loadStateMock(...a) }));
@@ -103,6 +109,9 @@ beforeEach(() => {
topTracks: [{ name: 'Example Track', artist: 'Example Artist', count: 2 }],
} } },
});
+ resolveMusicEngineSelectionMock.mockResolvedValue({
+ status: 'ready', selection: { engine: 'musicgen', modelId: 'musicgen-medium', repo: 'example/musicgen-medium' },
+ });
});
describe('activeCommissions', () => {
@@ -314,7 +323,37 @@ describe('runScheduledCommission gates', () => {
expect(createProjectMock.mock.calls[0][0].directive.goal).toContain('Create an original work');
expect(recordRunMock).toHaveBeenCalledWith('commission-1', expect.objectContaining({
status: 'started', tasteRecipe: expect.objectContaining({ source: 'digital-twin', anchors: expect.any(Array) }),
+ musicGeneration: {
+ engine: 'musicgen', modelId: 'musicgen-medium', repo: 'example/musicgen-medium', durationSec: 45,
+ },
+ }));
+ });
+
+ it('records an explicit skip when the configured music renderer is unavailable', async () => {
+ resolveMusicEngineSelectionMock.mockResolvedValueOnce({ status: 'unavailable', reason: 'music-model-unavailable' });
+ getCommissionMock.mockResolvedValue(videoCommission({
+ targetAbility: 'music',
+ brief: { intent: 'ambient', musicTaste: { source: 'digital-twin', musicEngineId: 'acestep', musicModelId: 'removed-model' } },
+ generation: { lengthSeconds: 45 },
+ }));
+ await runScheduledCommission('commission-1');
+ expect(recordRunMock).toHaveBeenCalledWith('commission-1', expect.objectContaining({
+ status: 'skipped', reason: 'music-model-unavailable',
}));
+ expect(createProjectMock).not.toHaveBeenCalled();
+ });
+
+ it('does not advance a taste project when its authoritative local run failed to persist', async () => {
+ recordRunMock.mockResolvedValueOnce(null);
+ getCommissionMock.mockResolvedValue(videoCommission({
+ targetAbility: 'music',
+ brief: { intent: 'ambient', musicTaste: { source: 'digital-twin' } },
+ generation: { lengthSeconds: 45 },
+ }));
+ const outcome = await runCommissionNow('commission-1');
+ expect(outcome).toMatchObject({ status: 'failed', error: 'taste-run-persistence-unavailable' });
+ expect(createProjectMock).toHaveBeenCalledTimes(1);
+ expect(advanceMock).not.toHaveBeenCalled();
});
it('records an explicit skip when taste mode has no usable observed anchors', async () => {
diff --git a/server/services/creativeCommissions/store.js b/server/services/creativeCommissions/store.js
index 3714a8fc62..02ebbee20d 100644
--- a/server/services/creativeCommissions/store.js
+++ b/server/services/creativeCommissions/store.js
@@ -125,14 +125,50 @@ export function sanitizeFeedbackEntry(raw) {
};
}
+function sanitizeMusicGeneration(raw) {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ const engine = isStr(raw.engine) ? raw.engine.trim().slice(0, 64) : '';
+ const modelId = isStr(raw.modelId) ? raw.modelId.trim().slice(0, 200) : '';
+ const repo = isStr(raw.repo) ? raw.repo.trim().slice(0, 200) : '';
+ const durationSec = Number(raw.durationSec);
+ if (!engine || !modelId || !Number.isInteger(durationSec) || durationSec < 1 || durationSec > 600) return null;
+ return { engine, modelId, ...(repo ? { repo } : {}), durationSec };
+}
+
+function sanitizeMusicOutput(raw) {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ const filename = isStr(raw.filename) ? raw.filename.trim().slice(0, 240) : '';
+ if (!filename) return null;
+ return {
+ filename,
+ durationSec: Number.isFinite(raw.durationSec) ? raw.durationSec : null,
+ engine: isStr(raw.engine) ? raw.engine.trim().slice(0, 64) : null,
+ modelId: isStr(raw.modelId) ? raw.modelId.trim().slice(0, 200) : null,
+ recipeVersion: Number.isInteger(raw.recipeVersion) ? raw.recipeVersion : null,
+ sourceHash: isStr(raw.sourceHash) ? raw.sourceHash.trim().slice(0, 64) : null,
+ completedAt: isStr(raw.completedAt) ? raw.completedAt : new Date().toISOString(),
+ };
+}
+
function sanitizeRunHistoryEntry(raw) {
- if (!raw || typeof raw !== 'object' || Array.isArray(raw) || !('tasteRecipe' in raw)) return raw;
- const tasteRecipe = sanitizeMusicTasteRecipe(raw.tasteRecipe);
- if (!tasteRecipe) {
- const { tasteRecipe: _discarded, ...withoutRecipe } = raw;
- return withoutRecipe;
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return raw;
+ const next = { ...raw };
+ if ('tasteRecipe' in raw) {
+ const tasteRecipe = sanitizeMusicTasteRecipe(raw.tasteRecipe);
+ if (tasteRecipe) next.tasteRecipe = tasteRecipe;
+ else delete next.tasteRecipe;
+ }
+ if ('musicGeneration' in raw) {
+ const musicGeneration = sanitizeMusicGeneration(raw.musicGeneration);
+ if (musicGeneration) next.musicGeneration = musicGeneration;
+ else delete next.musicGeneration;
+ }
+ if ('musicOutput' in raw) {
+ const musicOutput = sanitizeMusicOutput(raw.musicOutput);
+ if (musicOutput) next.musicOutput = musicOutput;
+ else delete next.musicOutput;
}
- return { ...raw, tasteRecipe };
+ return next;
}
/**
@@ -669,6 +705,7 @@ export async function recordCommissionRun(id, runEntry) {
if (!currentRaw) return null;
const current = sanitizeCommission(currentRaw);
const tasteRecipe = sanitizeMusicTasteRecipe(runEntry.tasteRecipe);
+ const musicGeneration = sanitizeMusicGeneration(runEntry.musicGeneration);
const run = {
id: runEntry.id || `run-${randomUUID()}`,
ranAt: runEntry.ranAt || new Date().toISOString(),
@@ -682,6 +719,7 @@ export async function recordCommissionRun(id, runEntry) {
reason: isStr(runEntry.reason) ? runEntry.reason : null,
error: isStr(runEntry.error) ? runEntry.error : null,
...(tasteRecipe ? { tasteRecipe } : {}),
+ ...(musicGeneration ? { musicGeneration } : {}),
};
const runs = [...(current.runs || []), run].slice(-MAX_PERSISTED_RUNS);
await store.writeRaw(id, { ...current, runs, updatedAt: new Date().toISOString() });
@@ -689,6 +727,49 @@ export async function recordCommissionRun(id, runEntry) {
});
}
+/**
+ * Resolve the machine-local taste run that owns a Creative Director project.
+ * The caller uses this to override planner-authored audio params; raw Digital
+ * Twin evidence never leaves the commission store.
+ */
+export async function getCommissionMusicContextForProject(projectId) {
+ if (!isStr(projectId) || !projectId) return null;
+ const raw = await commissionStore().listRaw();
+ for (const value of raw) {
+ const commission = sanitizeCommission(value);
+ if (!commission || commission.targetAbility !== 'music') continue;
+ const run = [...commission.runs].reverse().find((entry) => entry?.projectId === projectId);
+ if (!run?.tasteRecipe || !run?.musicGeneration) continue;
+ return {
+ commissionId: commission.id,
+ runId: run.id,
+ prompt: run.promptUsed,
+ tasteRecipe: run.tasteRecipe,
+ musicGeneration: run.musicGeneration,
+ };
+ }
+ return null;
+}
+
+/** Persist completed render provenance on the local run without syncing it. */
+export async function recordCommissionMusicOutput(id, runId, output) {
+ const musicOutput = sanitizeMusicOutput(output);
+ if (!musicOutput || !isStr(runId) || !runId) return null;
+ const store = commissionStore();
+ return store.queueRecordWrite(id, async () => {
+ const currentRaw = await store.readRaw(id);
+ if (!currentRaw) return null;
+ const current = sanitizeCommission(currentRaw);
+ const index = current.runs.findIndex((entry) => entry?.id === runId);
+ if (index < 0) return null;
+ if (!current.runs[index]?.tasteRecipe || !current.runs[index]?.musicGeneration) return null;
+ const runs = [...current.runs];
+ runs[index] = { ...runs[index], musicOutput };
+ await store.writeRaw(id, { ...current, runs, updatedAt: new Date().toISOString() });
+ return runs[index];
+ });
+}
+
/**
* Record a user reaction to a commission run (#2657, Phase 2 — the taste
* feedback loop). Appends a sanitized `CommissionFeedback` entry onto the
diff --git a/server/services/creativeCommissions/store.test.js b/server/services/creativeCommissions/store.test.js
index 04aac3255d..58213eca9e 100644
--- a/server/services/creativeCommissions/store.test.js
+++ b/server/services/creativeCommissions/store.test.js
@@ -47,6 +47,8 @@ const {
getCommission,
listCommissions,
recordCommissionRun,
+ getCommissionMusicContextForProject,
+ recordCommissionMusicOutput,
submitCommissionFeedback,
backfillAllCommissionFeedback,
sanitizeCommissionForSync,
@@ -315,7 +317,12 @@ describe('recordCommissionRun', () => {
});
it('persists bounded taste recipe provenance only on the local run history', async () => {
- const created = await createCommission(validInput());
+ const created = await createCommission({
+ ...validInput(),
+ targetAbility: 'music',
+ brief: { intent: 'ambient', musicTaste: { source: 'digital-twin' } },
+ generation: { lengthSeconds: 45 },
+ });
const recipe = {
version: 1,
source: 'digital-twin',
@@ -329,10 +336,27 @@ describe('recordCommissionRun', () => {
sourceVersion: 'music-taste-v1:example',
sourceHash: 'example-hash',
};
- await recordCommissionRun(created.id, { status: 'started', tasteRecipe: recipe });
+ const run = await recordCommissionRun(created.id, {
+ status: 'started', projectId: 'cd-taste', promptUsed: 'Original bounded directive', tasteRecipe: recipe,
+ musicGeneration: { engine: 'musicgen', modelId: 'example-model', repo: 'example/model', durationSec: 45 },
+ });
const after = await getCommission(created.id);
expect(after.runs[0].tasteRecipe).toEqual(recipe);
+ expect(after.runs[0].musicGeneration).toEqual({
+ engine: 'musicgen', modelId: 'example-model', repo: 'example/model', durationSec: 45,
+ });
expect(sanitizeCommission({ ...after, runs: after.runs }).runs[0].tasteRecipe).toEqual(recipe);
+ expect(await getCommissionMusicContextForProject('cd-taste')).toMatchObject({
+ commissionId: created.id, runId: run.id, prompt: 'Original bounded directive',
+ });
+ await recordCommissionMusicOutput(created.id, run.id, {
+ filename: 'music-gen-example.wav', durationSec: 45, engine: 'musicgen', modelId: 'example-model',
+ recipeVersion: 1, sourceHash: 'example-hash', completedAt: '2026-08-16T00:00:00.000Z',
+ });
+ const completed = await getCommission(created.id);
+ expect(completed.runs[0].musicOutput).toMatchObject({
+ filename: 'music-gen-example.wav', engine: 'musicgen', modelId: 'example-model', sourceHash: 'example-hash',
+ });
});
});
diff --git a/server/services/creativeDirectorMusicBedHook.js b/server/services/creativeDirectorMusicBedHook.js
index 1de9ff3a86..52d2dd0442 100644
--- a/server/services/creativeDirectorMusicBedHook.js
+++ b/server/services/creativeDirectorMusicBedHook.js
@@ -37,11 +37,24 @@ const hook = createMediaJobImageHook({
extractResult: (job) => {
const filename = job.result?.filename;
if (typeof filename !== 'string' || !filename) return null;
+ const rawProvenance = job.result?.provenance;
+ const provenance = rawProvenance?.kind === 'creative-commission-music-taste'
+ && typeof rawProvenance.commissionId === 'string'
+ && typeof rawProvenance.runId === 'string'
+ ? {
+ kind: rawProvenance.kind,
+ commissionId: rawProvenance.commissionId,
+ runId: rawProvenance.runId,
+ recipeVersion: Number.isInteger(rawProvenance.recipeVersion) ? rawProvenance.recipeVersion : null,
+ sourceHash: typeof rawProvenance.sourceHash === 'string' ? rawProvenance.sourceHash.slice(0, 64) : null,
+ }
+ : null;
return {
filename,
durationSec: Number.isFinite(job.result?.durationSec) ? job.result.durationSec : null,
engine: typeof job.result?.engine === 'string' ? job.result.engine : null,
modelId: typeof job.result?.modelId === 'string' ? job.result.modelId : null,
+ provenance,
};
},
// The project may have been deleted between enqueue and completion —
@@ -53,12 +66,22 @@ const hook = createMediaJobImageHook({
// the first completion to attach wins and this later one must not clobber
// it (return null — the factory's "nothing applied" signal — instead of
// overwriting the existing musicBed).
- attach: async ({ projectId, filename, durationSec, engine, modelId }) => {
+ attach: async ({ projectId, filename, durationSec, engine, modelId, provenance }) => {
const current = await getProject(projectId);
if (current?.musicBed?.filename) return null;
+ const generatedAt = new Date().toISOString();
await updateProject(projectId, {
- musicBed: { filename, durationSec, engine, modelId, generatedAt: new Date().toISOString() },
+ musicBed: { filename, durationSec, engine, modelId, generatedAt },
});
+ if (provenance) {
+ const { recordCommissionMusicOutput } = await import('./creativeCommissions/store.js');
+ await recordCommissionMusicOutput(provenance.commissionId, provenance.runId, {
+ filename, durationSec, engine, modelId,
+ recipeVersion: provenance.recipeVersion,
+ sourceHash: provenance.sourceHash,
+ completedAt: generatedAt,
+ }).catch(() => null);
+ }
return 'attached';
},
onAttached: ({ projectId, filename }) => {
diff --git a/server/services/creativeDirectorMusicBedHook.test.js b/server/services/creativeDirectorMusicBedHook.test.js
index 073af039a7..927c8e67c4 100644
--- a/server/services/creativeDirectorMusicBedHook.test.js
+++ b/server/services/creativeDirectorMusicBedHook.test.js
@@ -7,6 +7,10 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
const updateProject = vi.fn(async (id, patch) => ({ id, ...patch }));
const getProject = vi.fn(async () => ({ id: 'proj-1' }));
vi.mock('./creativeDirector/local.js', () => ({ updateProject, getProject }));
+const recordCommissionMusicOutput = vi.fn(async () => ({}));
+vi.mock('./creativeCommissions/store.js', () => ({
+ recordCommissionMusicOutput: (...args) => recordCommissionMusicOutput(...args),
+}));
const { mediaJobEvents } = await import('./mediaJobQueue/index.js');
const hook = await import('./creativeDirectorMusicBedHook.js');
@@ -37,6 +41,7 @@ describe('creativeDirectorMusicBedHook', () => {
updateProject.mockImplementation(async (id, patch) => ({ id, ...patch }));
getProject.mockReset();
getProject.mockImplementation(async (id) => ({ id }));
+ recordCommissionMusicOutput.mockClear();
});
afterEach(() => {
@@ -54,6 +59,22 @@ describe('creativeDirectorMusicBedHook', () => {
});
});
+ it('records bounded taste provenance on the machine-local commission run', async () => {
+ mediaJobEvents.emit('completed', completedAudioJob({
+ params: { creativeDirectorMusicBed: tag() },
+ result: { provenance: {
+ kind: 'creative-commission-music-taste', commissionId: 'commission-example', runId: 'run-example',
+ recipeVersion: 1, sourceHash: 'example-hash',
+ } },
+ }));
+ await waitFor(() => recordCommissionMusicOutput.mock.calls.length > 0);
+ expect(recordCommissionMusicOutput).toHaveBeenCalledWith('commission-example', 'run-example', expect.objectContaining({
+ filename: 'music-gen-x.wav', engine: 'musicgen', modelId: 'musicgen-medium',
+ recipeVersion: 1, sourceHash: 'example-hash', completedAt: expect.any(String),
+ }));
+ expect(updateProject.mock.calls[0][1].musicBed).not.toHaveProperty('provenance');
+ });
+
it('ignores a completed job with no creativeDirectorMusicBed tag', async () => {
mediaJobEvents.emit('completed', completedAudioJob({ params: { prompt: 'plain audio render' } }));
await new Promise((r) => setTimeout(r, 20));
diff --git a/server/services/musicEngineCatalog.js b/server/services/musicEngineCatalog.js
new file mode 100644
index 0000000000..751cb873e9
--- /dev/null
+++ b/server/services/musicEngineCatalog.js
@@ -0,0 +1,68 @@
+/**
+ * Live music-engine catalog shared by the Music UI and scheduled commissions.
+ * A commission resolves its configured engine/model at fire time so a runtime
+ * removed after configuration records an explicit skip instead of silently
+ * falling back to a different renderer.
+ */
+
+import {
+ ENGINES, DEFAULT_ENGINE_ID, getEngineModel, isEngineHealthy,
+ isEnginePlatformSupported, enginePlatformLabel,
+} from './pipeline/musicGen.js';
+import { listEngineModels } from './audioModels.js';
+import { inspectModelCache } from '../lib/hfCache.js';
+import { getCudaCapability } from '../lib/cudaCapability.js';
+
+export async function listMusicEngineCatalog() {
+ const cuda = await getCudaCapability();
+ const engines = await Promise.all(Object.values(ENGINES).map(async (engine) => {
+ const fixedModel = engine.fixedModelInstall ? getEngineModel(engine.id, engine.defaultModelId) : null;
+ const modelCache = fixedModel ? await inspectModelCache(fixedModel.repo).catch(() => ({ cached: false })) : null;
+ const runtimeReady = await isEngineHealthy(engine.id);
+ const platformSupported = isEnginePlatformSupported(engine.id);
+ return {
+ id: engine.id,
+ name: engine.name,
+ models: await listEngineModels(engine.id),
+ defaultModelId: engine.defaultModelId,
+ minDurationSec: engine.minDurationSec,
+ maxDurationSec: engine.maxDurationSec,
+ defaultDurationSec: engine.defaultDurationSec,
+ lyrics: engine.lyrics === true,
+ autoDuration: engine.autoDuration === true,
+ customModels: engine.customModels === true,
+ fixedModelInstall: engine.fixedModelInstall === true,
+ modelReady: modelCache ? modelCache.cached === true : true,
+ modelSizeGb: fixedModel?.downloadSizeGb ?? null,
+ runtimeReady,
+ cudaRequired: engine.cudaRequired === true,
+ platformSupported,
+ platformLabel: enginePlatformLabel(engine.id),
+ cudaState: engine.cudaRequired ? cuda.status : 'available',
+ ready: platformSupported && runtimeReady && (!engine.cudaRequired || cuda.status === 'available') && (!modelCache || modelCache.cached === true),
+ installEnv: engine.installEnv,
+ venvDefault: engine.venvDefault,
+ };
+ }));
+ return { engines, defaultEngine: DEFAULT_ENGINE_ID };
+}
+
+export async function resolveMusicEngineSelection({ engineId, modelId } = {}) {
+ const catalog = await listMusicEngineCatalog();
+ const selectedEngineId = engineId || catalog.defaultEngine;
+ const engine = catalog.engines.find((entry) => entry.id === selectedEngineId);
+ if (!engine || !engine.ready) {
+ return { status: 'unavailable', reason: 'music-engine-unavailable' };
+ }
+ const selectedModelId = modelId || engine.defaultModelId;
+ const model = engine.models.find((entry) => entry.id === selectedModelId);
+ if (!model) return { status: 'unavailable', reason: 'music-model-unavailable' };
+ return {
+ status: 'ready',
+ selection: {
+ engine: engine.id,
+ modelId: model.id,
+ repo: model.repo,
+ },
+ };
+}
diff --git a/server/services/musicEngineCatalog.test.js b/server/services/musicEngineCatalog.test.js
new file mode 100644
index 0000000000..3ff8413875
--- /dev/null
+++ b/server/services/musicEngineCatalog.test.js
@@ -0,0 +1,65 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const state = vi.hoisted(() => ({ healthy: true, platformSupported: true, cuda: 'available', cached: true }));
+vi.mock('./pipeline/musicGen.js', () => ({
+ DEFAULT_ENGINE_ID: 'musicgen',
+ ENGINES: {
+ musicgen: {
+ id: 'musicgen', name: 'MusicGen', models: [{ id: 'default-model', name: 'Default', repo: 'example/default' }],
+ defaultModelId: 'default-model', minDurationSec: 5, maxDurationSec: 60, defaultDurationSec: 30,
+ customModels: true, fixedModelInstall: false, cudaRequired: false,
+ installEnv: 'INSTALL_MUSICGEN', venvDefault: '/example/venv',
+ },
+ },
+ getEngineModel: () => null,
+ isEngineHealthy: async () => state.healthy,
+ isEnginePlatformSupported: () => state.platformSupported,
+ enginePlatformLabel: () => 'supported platform',
+}));
+vi.mock('./audioModels.js', () => ({
+ listEngineModels: async () => [{ id: 'default-model', name: 'Default', repo: 'example/default', userAdded: false }],
+}));
+vi.mock('../lib/hfCache.js', () => ({ inspectModelCache: async () => ({ cached: state.cached }) }));
+vi.mock('../lib/cudaCapability.js', () => ({ getCudaCapability: async () => ({ status: state.cuda }) }));
+
+const { listMusicEngineCatalog, resolveMusicEngineSelection } = await import('./musicEngineCatalog.js');
+
+beforeEach(() => {
+ state.healthy = true;
+ state.platformSupported = true;
+ state.cuda = 'available';
+ state.cached = true;
+});
+
+describe('musicEngineCatalog', () => {
+ it('returns the live catalog used by both the UI and commissions', async () => {
+ await expect(listMusicEngineCatalog()).resolves.toMatchObject({
+ defaultEngine: 'musicgen',
+ engines: [{ id: 'musicgen', ready: true, defaultModelId: 'default-model' }],
+ });
+ });
+
+ it('resolves omitted values to the installed defaults', async () => {
+ await expect(resolveMusicEngineSelection()).resolves.toEqual({
+ status: 'ready',
+ selection: { engine: 'musicgen', modelId: 'default-model', repo: 'example/default' },
+ });
+ });
+
+ it('fails closed for a removed model or unavailable runtime', async () => {
+ await expect(resolveMusicEngineSelection({ modelId: 'removed' })).resolves.toEqual({
+ status: 'unavailable', reason: 'music-model-unavailable',
+ });
+ state.healthy = false;
+ await expect(resolveMusicEngineSelection()).resolves.toEqual({
+ status: 'unavailable', reason: 'music-engine-unavailable',
+ });
+ });
+
+ it('fails closed on an unsupported platform even if a stale runtime looks healthy', async () => {
+ state.platformSupported = false;
+ await expect(resolveMusicEngineSelection()).resolves.toEqual({
+ status: 'unavailable', reason: 'music-engine-unavailable',
+ });
+ });
+});
diff --git a/server/services/pipeline/musicGen.js b/server/services/pipeline/musicGen.js
index e97f1a21f7..8817221d28 100644
--- a/server/services/pipeline/musicGen.js
+++ b/server/services/pipeline/musicGen.js
@@ -549,7 +549,7 @@ export function buildMusicGenArgs({ pythonPath, scriptPath = SIDECAR_SCRIPT, run
* flat timeout. Callers outside the queue (the Pipeline Audio routes) omit it
* and behave exactly as before.
*/
-export async function generateMusic({ prompt, lyrics, engine: engineId = DEFAULT_ENGINE_ID, durationSec, durationMode, modelId, repo, signal, onActivity } = {}) {
+export async function generateMusic({ prompt, lyrics, engine: engineId = DEFAULT_ENGINE_ID, durationSec, durationMode, modelId, repo, provenance, signal, onActivity } = {}) {
const text = (prompt || '').trim();
if (!text) {
throw new ServerError('prompt is required', { status: 400, code: 'PIPELINE_MUSIC_EMPTY_PROMPT' });
@@ -641,5 +641,6 @@ export async function generateMusic({ prompt, lyrics, engine: engineId = DEFAULT
modelId: model.id,
model: model.name,
engine: engine.id,
+ ...(provenance ? { provenance } : {}),
};
}