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
feat(creative-commissions): add taste-aware music recipes (#4347)
[._.]/ Adam Eivy451bec3939bf
diff --git a/.changelog/next/added-issue-4347.md b/.changelog/next/added-issue-4347.mdnew file mode 100644index 0000000000..03f743c694--- /dev/null+++ b/.changelog/next/added-issue-4347.md@@ -0,0 +1 @@+- [issue-4347] Add bounded Digital Twin taste recipes to music Creative Commissionsdiff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 33d3235d2b..525c1f6f40 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 Phase 1, #2657): 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 (brief / schedule / generation / feedback / capped `runs[]`) in `data` JSONB with `name`/`enabled`/`created_at`/`updated_at` mirrored into columns for the scheduler's "arm every enabled commission" query. **Intentionally machine-local — never federated** (a synced schedule would double-run on every peer, same rationale as `seriesAutopilotScheduler`): NO `sync_sequence` and NO `deleted`/`deleted_at` tombstone — deletes are hard deletes, mirroring `tribe`. Phase 2 will split the machine-local *schedule* from a federatable *brief/feedback* record before adding any sync hook. 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 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.mdindex c85f4940ad..04a4bc1858 100644--- a/docs/features/digital-twin.md+++ b/docs/features/digital-twin.md@@ -65,6 +65,25 @@ and can be retried. Manual JSON upload remains available as a fallback.Routes: `GET /import/sources`, `POST /import/analyze`, `POST /import/save`,`POST /import/spotify/browser/open`, and `POST /import/spotify/browser/import`.+## Taste-aware Music Commissions++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.++The commission brief carries only the non-sensitive opt-in configuration. Raw+Spotify caches, activity events, full Digital Twin responses, and the selected+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.+## Transcript & Image AnalysisMulti-modal capture works on pasted/uploaded artifacts — there is no live audio or video capture infrastructure:diff --git a/server/lib/creativeCommissionValidation.js b/server/lib/creativeCommissionValidation.jsindex dcf7556369..6d5544a62f 100644--- a/server/lib/creativeCommissionValidation.js+++ b/server/lib/creativeCommissionValidation.js@@ -149,6 +149,38 @@ function generationFieldSchema(def) {export const COMMISSION_NAME_MAX = 200;export const COMMISSION_INTENT_MAX = 2000;+export const COMMISSION_MUSIC_TASTE_ANCHOR_MAX = 5;+export const COMMISSION_MUSIC_TASTE_PERCENT_MAX = 100;+export const COMMISSION_MUSIC_TASTE_ENGINE_MAX = 64;++export const CREATIVE_COMMISSION_MUSIC_TASTE_WINDOWS = Object.freeze(['week', 'month']);++const musicTasteEngineId = z.string().trim().max(COMMISSION_MUSIC_TASTE_ENGINE_MAX).nullable().optional();++// This is deliberately configuration only. Raw Digital Twin answers, Spotify+// caches, and selected source records stay on the owning machine; the bounded+// recipe produced at fire time is local run provenance, not commission brief+// data. The brief itself can federate this non-sensitive opt-in configuration.+export const creativeCommissionMusicTasteSchema = z.object({+ source: z.literal('digital-twin').default('digital-twin'),+ window: z.enum(CREATIVE_COMMISSION_MUSIC_TASTE_WINDOWS).default('month'),+ anchorCount: z.number().int().min(1).max(COMMISSION_MUSIC_TASTE_ANCHOR_MAX).default(3),+ explorationPercent: z.number().int().min(0).max(COMMISSION_MUSIC_TASTE_PERCENT_MAX).default(20),+ musicEngineId: musicTasteEngineId,+ musicModelId: musicTasteEngineId,+});++// No defaults on PATCH: omitted fields must preserve the stored taste config,+// while null explicitly disables taste mode. The service performs the same+// absent-vs-empty merge as the other brief fields.+export const creativeCommissionMusicTasteUpdateSchema = z.object({+ source: z.literal('digital-twin').optional(),+ window: z.enum(CREATIVE_COMMISSION_MUSIC_TASTE_WINDOWS).optional(),+ anchorCount: z.number().int().min(1).max(COMMISSION_MUSIC_TASTE_ANCHOR_MAX).optional(),+ explorationPercent: z.number().int().min(0).max(COMMISSION_MUSIC_TASTE_PERCENT_MAX).optional(),+ musicEngineId: musicTasteEngineId,+ musicModelId: musicTasteEngineId,+}).nullable();// The brief the commission steers by. `intent` is the free-text core ("something// surreal, dreamlike, unsettlingly beautiful"); `genre`/`category` are optional@@ -166,6 +198,7 @@ export const creativeCommissionBriefSchema = z.object({// Catalog ingredient ids to seed future generations from (Phase 3+ folds these// into the CD cast). Accepted now so the record shape is forward-stable.seedRefs: z.array(z.string().trim().max(64)).max(50).default([]),+ musicTaste: creativeCommissionMusicTasteSchema.nullable().optional(),});// A cadence descriptor. Per-kind fields are validated in `superRefine` so a@@ -323,6 +356,7 @@ export const creativeCommissionBriefUpdateSchema = z.object({seriesId: z.string().max(120).nullable().optional(),}).optional(),seedRefs: z.array(z.string().trim().max(64)).max(50).optional(),+ musicTaste: creativeCommissionMusicTasteUpdateSchema.optional(),});// A user reaction to a specific commission run (#2657, Phase 2 — the tastediff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex fe242bce30..a31019e839 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -471,7 +471,12 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// `sanitizeGenerationFor` keeps only the keys it knows, so it would silently// strip the user's pinned backend on receive and then push the un-pinned// downgrade back via LWW.- creativeCommissions: 3,+ // v4 = opt-in Digital Twin musicTaste configuration in the federated brief+ // (#4347). The bounded config is understood by this sanitizer; a v3 peer+ // would reconstruct the brief without it and could push that downgrade back+ // through the brief-scoped LWW merge. Per-run recipes remain local because+ // syncWire already strips `runs[]`.+ creativeCommissions: 4,// v1 = standalone media-library federation (#1566). NOT a record kind — it's// the wire contract for the library-level asset manifest a full-sync peer// advertises at GET /api/peer-sync/library-manifest. The receiver-pull sweepdiff --git a/server/lib/schemaVersions.test.js b/server/lib/schemaVersions.test.jsindex 81f5cc9dcb..4b12002178 100644--- a/server/lib/schemaVersions.test.js+++ b/server/lib/schemaVersions.test.js@@ -40,6 +40,10 @@ describe('PORTOS_SCHEMA_VERSIONS', () => {it('declares mediaCollections layout version', () => {expect(PORTOS_SCHEMA_VERSIONS.mediaCollections).toBe(1);});++ it('version-gates the additive Creative Commission taste brief shape', () => {+ expect(PORTOS_SCHEMA_VERSIONS.creativeCommissions).toBe(4);+ });});describe('buildPortosMeta', () => {diff --git a/server/lib/syncWire.test.js b/server/lib/syncWire.test.jsindex 50cfa70e8e..e7bb5ba9a2 100644--- a/server/lib/syncWire.test.js+++ b/server/lib/syncWire.test.js@@ -231,6 +231,29 @@ describe('syncWire', () => {expect(JSON.stringify(withPins)).toBe(JSON.stringify(preField));});+ it('strips local commission runs, including taste recipes, 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' } }],+ schedule: { kind: 'DAILY' },+ assignment: { providerId: 'local-only' },+ feedback: [],+ enabled: true,+ updatedAt: '2026-08-16T00:00:00.000Z',+ });+ const briefOnly = sanitizeRecordForWire('creativeCommission', {+ id: 'commission-example',+ name: 'Example Commission',+ brief: { intent: 'ambient', musicTaste: { source: 'digital-twin', window: 'month' } },+ updatedAt: '2026-08-16T00:00:00.000Z',+ });++ expect(withLocalRun.runs).toBeUndefined();+ expect(JSON.stringify(withLocalRun)).toBe(JSON.stringify(briefOnly));+ });+describe('author kind', () => {it('passes through an author with canonical tail soft-delete fields', () => {const a = { id: 'auth-1', name: 'Ada', bio: 'b' };diff --git a/server/services/creativeCommissions/abilityAdapters.js b/server/services/creativeCommissions/abilityAdapters.jsindex c8547783e3..3371cb95cb 100644--- a/server/services/creativeCommissions/abilityAdapters.js+++ b/server/services/creativeCommissions/abilityAdapters.js@@ -30,6 +30,7 @@*/import { renderFeedbackDigest, composeDirectiveGoal } from './directive.js';+import { renderMusicTasteRecipePrompt } from './musicTasteRecipe.js';import {ABILITY_GENERATION_SPEC, GENERATION_KEY_DEFS, CREATIVE_COMMISSION_ABILITIES,COMMISSION_RENDER_BACKEND_AUTO,@@ -190,10 +191,12 @@ const musicAdapter = {label: 'Music',sanitizeGeneration: (raw) => sanitizeGenerationFor('music', raw),buildProjectParams: buildVideoGeometryParams,- buildDirective(commission) {+ buildDirective(commission, { tasteRecipe } = {}) {const secs = genValue(commission, 'lengthSeconds');const lead = `Compose an original ~${secs}s music / audio piece. Use the music generation tools; do NOT plan a video or image render.`;const { lines, digest, constraints } = briefContext(commission, lead);+ const tastePrompt = renderMusicTasteRecipePrompt(tasteRecipe);+ if (tastePrompt) lines.push(tastePrompt);return { goal: composeDirectiveGoal(lines, digest), deliverables: [`One ~${secs}s music track matching the brief`], constraints };},};@@ -272,7 +275,7 @@ export function getAbilityAdapter(ability) {* defensive. Shape matches `creativeDirectorDirectiveSchema`* (goal/deliverables/constraints) so it round-trips into `createProject`.*/-export function buildCommissionDirective(commission) {+export function buildCommissionDirective(commission, options = {}) {const adapter = getAbilityAdapter(commission?.targetAbility) || videoAdapter;- return adapter.buildDirective(commission);+ return adapter.buildDirective(commission, options);}diff --git a/server/services/creativeCommissions/musicTasteRecipe.js b/server/services/creativeCommissions/musicTasteRecipe.jsnew file mode 100644index 0000000000..dfb90bfc03--- /dev/null+++ b/server/services/creativeCommissions/musicTasteRecipe.js@@ -0,0 +1,254 @@+/**+ * Deterministic, bounded Digital Twin music-taste recipes (#4347).+ *+ * This module is pure. The scheduler owns the machine-local reads of the+ * stated taste profile and observed evidence, then hands those bounded source+ * projections here. No raw Spotify cache, activity event, or full Digital Twin+ * response is allowed into the recipe or the federated commission brief.+ */++import { createHash } from 'crypto';+import { canonicalStringify } from '../../lib/objects.js';+import {+ COMMISSION_MUSIC_TASTE_ANCHOR_MAX,+ COMMISSION_MUSIC_TASTE_PERCENT_MAX,+ CREATIVE_COMMISSION_MUSIC_TASTE_WINDOWS,+} from '../../lib/creativeCommissionValidation.js';++export const MUSIC_TASTE_RECIPE_VERSION = 1;+export const MUSIC_TASTE_RECIPE_MAX_CONTEXT = 500;+export const MUSIC_TASTE_RECIPE_MAX_SOURCE_VERSION = 240;+export const MUSIC_TASTE_RECIPE_MAX_CANDIDATES = 50;+export const MUSIC_TASTE_FEEDBACK_TAGS = Object.freeze([+ 'more-familiar',+ 'more-experimental',+ 'keep-anchors',+ 'change-anchors',+]);++const isObject = (value) => value && typeof value === 'object' && !Array.isArray(value);+const isString = (value) => typeof value === 'string';+const clampInt = (value, min, max, fallback) => Number.isInteger(value)+ ? Math.min(max, Math.max(min, value)) : fallback;+const clampText = (value, max) => isString(value) ? value.trim().slice(0, max) : '';++export function normalizeMusicTasteConfig(raw) {+ if (!isObject(raw) || raw.source !== 'digital-twin') return null;+ const window = CREATIVE_COMMISSION_MUSIC_TASTE_WINDOWS.includes(raw.window) ? raw.window : 'month';+ const pickId = (value) => {+ if (!isString(value) || !value.trim()) return null;+ return value.trim().slice(0, 64);+ };+ return {+ source: 'digital-twin',+ window,+ anchorCount: clampInt(raw.anchorCount, 1, COMMISSION_MUSIC_TASTE_ANCHOR_MAX, 3),+ explorationPercent: clampInt(raw.explorationPercent, 0, COMMISSION_MUSIC_TASTE_PERCENT_MAX, 20),+ musicEngineId: pickId(raw.musicEngineId),+ musicModelId: pickId(raw.musicModelId),+ };+}++function hashNumber(value) {+ let hash = 2166136261;+ for (const char of String(value)) {+ hash ^= char.charCodeAt(0);+ hash = Math.imul(hash, 16777619);+ }+ return hash >>> 0;+}++function anchorKey(anchor) {+ const artist = isString(anchor?.artist) && anchor.artist ? `:${anchor.artist}` : '';+ return `${anchor?.kind || ''}:${anchor?.name || ''}${artist}`.toLowerCase();+}++function combinationKey(anchors) {+ return (anchors || []).map(anchorKey).sort().join('|');+}++function normalizeCount(value) {+ return Number.isFinite(value) && value > 0 ? Math.min(999999, Math.floor(value)) : 1;+}++function normalizeCandidates(observedWindow) {+ const candidates = [];+ const seen = new Set();+ const add = (kind, raw) => {+ if (!isObject(raw) || !isString(raw.name) || !raw.name.trim()) return;+ const name = raw.name.trim().slice(0, 120);+ const artist = kind === 'track' && isString(raw.artist) && raw.artist.trim()+ ? raw.artist.trim().slice(0, 120) : null;+ const key = `${kind}:${name.toLowerCase()}:${artist?.toLowerCase() || ''}`;+ if (seen.has(key)) return;+ seen.add(key);+ candidates.push({ kind, name, ...(artist ? { artist } : {}), count: normalizeCount(raw.count), source: 'observed' });+ };+ for (const artist of observedWindow?.listen?.topArtists || []) add('artist', artist);+ for (const track of observedWindow?.listen?.topTracks || []) add('track', track);+ return candidates.slice(0, MUSIC_TASTE_RECIPE_MAX_CANDIDATES);+}++function orderedPool(candidates, seed, direction) {+ return [...candidates].sort((a, b) => {+ const countDelta = direction === 'familiar' ? b.count - a.count : a.count - b.count;+ return countDelta || (hashNumber(`${seed}:${anchorKey(a)}`) - hashNumber(`${seed}:${anchorKey(b)}`));+ });+}++function pickFromPool(pool, count, seed, attempt, used) {+ if (count <= 0 || pool.length === 0) return [];+ const picked = [];+ const start = (hashNumber(`${seed}:${attempt}`) + attempt) % pool.length;+ for (let i = 0; i < pool.length && picked.length < count; i += 1) {+ const candidate = pool[(start + i) % pool.length];+ const key = anchorKey(candidate);+ if (used.has(key)) continue;+ used.add(key);+ picked.push(candidate);+ }+ return picked;+}++function selectAnchors(candidates, config, seed, recentRecipes, explorationPercent) {+ if (candidates.length === 0) return [];+ const anchorCount = Math.min(config.anchorCount, candidates.length);+ const explorationCount = Math.min(anchorCount, Math.round(anchorCount * explorationPercent / 100));+ const familiarCount = anchorCount - explorationCount;+ const familiar = orderedPool(candidates, `${seed}:familiar`, 'familiar');+ const exploratory = orderedPool(candidates, `${seed}:explore`, 'explore');+ const all = orderedPool(candidates, `${seed}:all`, 'familiar');+ const recent = new Set((recentRecipes || []).map((recipe) => combinationKey(recipe?.anchors)).filter(Boolean));++ let selected = [];+ for (let attempt = 0; attempt <= candidates.length; attempt += 1) {+ const used = new Set();+ const next = [+ ...pickFromPool(familiar, familiarCount, `${seed}:familiar`, attempt, used),+ ...pickFromPool(exploratory, explorationCount, `${seed}:explore`, attempt, used),+ ...pickFromPool(all, anchorCount, `${seed}:all`, attempt, used),+ ].slice(0, anchorCount);+ selected = next;+ if (!recent.has(combinationKey(next)) || attempt === candidates.length) break;+ }+ return selected;+}++function feedbackAdjustment(feedback) {+ const recent = Array.isArray(feedback) ? feedback.slice(-5) : [];+ let adjustment = 0;+ for (const item of recent) {+ const rating = item?.rating;+ if (rating === 'down' || (typeof rating === 'number' && rating < 0)) adjustment += 10;+ if (rating === 'up' || (typeof rating === 'number' && rating > 0)) adjustment -= 5;+ for (const tag of item?.tags || []) {+ if (tag === 'more-experimental' || tag === 'change-anchors') adjustment += 15;+ if (tag === 'more-familiar' || tag === 'keep-anchors') adjustment -= 15;+ }+ }+ return adjustment;+}++function explorationDirection(base, effective) {+ if (effective >= base + 10) return 'more-experimental';+ if (effective <= base - 10) return 'more-familiar';+ return 'balanced';+}++export function sanitizeMusicTasteRecipe(raw) {+ if (!isObject(raw) || raw.version !== MUSIC_TASTE_RECIPE_VERSION || raw.source !== 'digital-twin') return null;+ const anchors = Array.isArray(raw.anchors)+ ? raw.anchors.map((anchor) => {+ if (!isObject(anchor) || !['artist', 'track'].includes(anchor.kind) || !isString(anchor.name)) return null;+ const name = anchor.name.trim().slice(0, 120);+ if (!name) return null;+ const artist = anchor.kind === 'track' && isString(anchor.artist) && anchor.artist.trim()+ ? anchor.artist.trim().slice(0, 120) : null;+ return {+ kind: anchor.kind,+ name,+ ...(artist ? { artist } : {}),+ count: normalizeCount(anchor.count),+ source: 'observed',+ };+ }).filter(Boolean).slice(0, COMMISSION_MUSIC_TASTE_ANCHOR_MAX)+ : [];+ if (anchors.length === 0) return null;+ return {+ version: MUSIC_TASTE_RECIPE_VERSION,+ source: 'digital-twin',+ window: CREATIVE_COMMISSION_MUSIC_TASTE_WINDOWS.includes(raw.window) ? raw.window : 'month',+ anchorCount: clampInt(raw.anchorCount, 1, COMMISSION_MUSIC_TASTE_ANCHOR_MAX, anchors.length),+ explorationPercent: clampInt(raw.explorationPercent, 0, COMMISSION_MUSIC_TASTE_PERCENT_MAX, 20),+ explorationCount: clampInt(raw.explorationCount, 0, COMMISSION_MUSIC_TASTE_ANCHOR_MAX, 0),+ explorationDirection: ['more-familiar', 'more-experimental', 'balanced'].includes(raw.explorationDirection)+ ? raw.explorationDirection : 'balanced',+ anchors,+ statedContext: clampText(raw.statedContext, MUSIC_TASTE_RECIPE_MAX_CONTEXT) || null,+ sourceVersion: clampText(raw.sourceVersion, MUSIC_TASTE_RECIPE_MAX_SOURCE_VERSION) || 'unknown',+ sourceHash: isString(raw.sourceHash) ? raw.sourceHash.trim().slice(0, 64) : 'unknown',+ };+}++/**+ * Build one recipe from bounded source projections. `status: unavailable` is+ * explicit so the scheduler never silently falls back to a generic track when+ * taste mode was enabled but no usable Digital Twin signal exists.+ */+export function buildMusicTasteRecipe({ commissionId, config: rawConfig, stated, observed, feedback, recentRuns, seed } = {}) {+ const config = normalizeMusicTasteConfig(rawConfig);+ if (!config) return { status: 'unavailable', reason: 'taste-source-unavailable' };+ const observedWindow = observed?.windows?.[config.window] || null;+ const statedContext = clampText(stated?.summary, MUSIC_TASTE_RECIPE_MAX_CONTEXT);+ const candidates = normalizeCandidates(observedWindow);+ // A free-text stated summary is useful prompt context, but it is not a+ // deterministic artist/track anchor. Taste mode therefore requires at least+ // one bounded observed music anchor rather than quietly generating from prose.+ if (candidates.length === 0) return { status: 'unavailable', reason: 'taste-source-unavailable' };++ const effectiveExplorationPercent = clampInt(+ config.explorationPercent + feedbackAdjustment(feedback),+ 0,+ COMMISSION_MUSIC_TASTE_PERCENT_MAX,+ config.explorationPercent,+ );+ const sourceProjection = {+ window: config.window,+ statedContext,+ statedAt: stated?.updatedAt || stated?.lastSessionAt || null,+ observedDerivedAt: observed?.derivedAt || null,+ candidates,+ };+ const sourceHash = createHash('sha256').update(canonicalStringify(sourceProjection)).digest('hex').slice(0, 32);+ const sourceVersion = `music-taste-v${MUSIC_TASTE_RECIPE_VERSION}:${stated?.updatedAt || stated?.lastSessionAt || 'none'}:${observed?.derivedAt || 'none'}`+ .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);+ return {+ status: 'ready',+ recipe: sanitizeMusicTasteRecipe({+ version: MUSIC_TASTE_RECIPE_VERSION,+ source: 'digital-twin',+ window: config.window,+ anchorCount: config.anchorCount,+ explorationPercent: effectiveExplorationPercent,+ explorationCount: Math.min(anchors.length, Math.round(anchors.length * effectiveExplorationPercent / 100)),+ explorationDirection: explorationDirection(config.explorationPercent, effectiveExplorationPercent),+ anchors,+ statedContext,+ sourceVersion,+ sourceHash,+ }),+ };+}++export function renderMusicTasteRecipePrompt(recipe) {+ const safe = sanitizeMusicTasteRecipe(recipe);+ if (!safe) return '';+ const anchors = safe.anchors.map((anchor) => anchor.kind === 'track'+ ? `${anchor.name}${anchor.artist ? ` by ${anchor.artist}` : ''}`+ : anchor.name).join(', ');+ const context = safe.statedContext ? ` Stated music preference signal: ${safe.statedContext}` : '';+ return `Digital Twin music recipe (source ${safe.sourceVersion}, hash ${safe.sourceHash}): use these liked listening anchors as high-level inspiration only: ${anchors || 'none'}. Exploration level: ${safe.explorationPercent}% (${safe.explorationDirection}).${context} Create an original work; do not reproduce source tracks, lyrics, melodies, or impersonate named artists.`;+}diff --git a/server/services/creativeCommissions/musicTasteRecipe.test.js b/server/services/creativeCommissions/musicTasteRecipe.test.jsnew file mode 100644index 0000000000..ca9a0f3d4f--- /dev/null+++ b/server/services/creativeCommissions/musicTasteRecipe.test.js@@ -0,0 +1,113 @@+import { describe, it, expect } from 'vitest';+import {+ buildMusicTasteRecipe,+ normalizeMusicTasteConfig,+ renderMusicTasteRecipePrompt,+ sanitizeMusicTasteRecipe,+} from './musicTasteRecipe.js';++const config = (overrides = {}) => ({+ source: 'digital-twin',+ window: 'month',+ anchorCount: 3,+ explorationPercent: 20,+ ...overrides,+});++const observed = {+ derivedAt: '2026-08-16T00:00:00.000Z',+ windows: {+ month: {+ listen: {+ topArtists: [+ { name: 'Example Artist A', count: 8 },+ { name: 'Example Artist B', count: 4 },+ { name: 'Example Artist C', count: 2 },+ ],+ topTracks: [+ { name: 'Example Track One', artist: 'Example Artist A', count: 6 },+ { name: 'Example Track Two', artist: 'Example Artist B', count: 3 },+ ],+ },+ },+ },+};++const sourceArgs = (overrides = {}) => ({+ commissionId: 'commission-example',+ config: config(),+ stated: { summary: 'Example stated preference', lastSessionAt: '2026-08-15T00:00:00.000Z' },+ observed,+ feedback: [],+ recentRuns: [],+ seed: 'stable-seed',+ ...overrides,+});++const combo = (recipe) => recipe.anchors.map((a) => `${a.kind}:${a.name}:${a.artist || ''}`).sort().join('|');++describe('normalizeMusicTasteConfig', () => {+ it('fills bounded defaults and treats blank engine/model ids as absent', () => {+ expect(normalizeMusicTasteConfig({ source: 'digital-twin', musicEngineId: ' ', musicModelId: 'example-model' }))+ .toEqual({+ source: 'digital-twin', window: 'month', anchorCount: 3, explorationPercent: 20,+ musicEngineId: null, musicModelId: 'example-model',+ });+ });++ it('rejects an unknown source instead of silently changing providers', () => {+ expect(normalizeMusicTasteConfig({ source: 'spotify-discovery' })).toBeNull();+ });+});++describe('buildMusicTasteRecipe', () => {+ it('is deterministic for the same bounded sources and seed', () => {+ const first = buildMusicTasteRecipe(sourceArgs());+ const second = buildMusicTasteRecipe(sourceArgs());+ expect(first).toEqual(second);+ expect(first.status).toBe('ready');+ expect(first.recipe.anchors).toHaveLength(3);+ expect(first.recipe.sourceHash).toMatch(/^[0-9a-f]{32}$/);+ });++ it('uses negative feedback to raise exploration while keeping the recipe bounded', () => {+ const result = buildMusicTasteRecipe(sourceArgs({+ config: config({ explorationPercent: 10 }),+ feedback: [{ rating: 'down', tags: ['more-experimental'] }],+ }));+ expect(result.recipe.explorationPercent).toBe(35);+ expect(result.recipe.explorationDirection).toBe('more-experimental');+ expect(result.recipe.anchors.every((anchor) => anchor.name.length <= 120)).toBe(true);+ });++ it('avoids the most recent exact anchor combination when another exists', () => {+ 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 }],+ })).recipe;+ expect(combo(next)).not.toBe(combo(first));+ });++ it('returns an explicit unavailable result without observed anchors', () => {+ expect(buildMusicTasteRecipe(sourceArgs({ observed: null })))+ .toEqual({ status: 'unavailable', reason: 'taste-source-unavailable' });+ });+});++describe('music taste provenance', () => {+ it('sanitizes recipes to a bounded local shape', () => {+ const recipe = buildMusicTasteRecipe(sourceArgs()).recipe;+ const safe = sanitizeMusicTasteRecipe({ ...recipe, anchors: [...recipe.anchors, ...recipe.anchors, ...recipe.anchors] });+ expect(safe.anchors).toHaveLength(5);+ expect(safe).not.toHaveProperty('rawSources');+ });++ it('renders original-work constraints and never asks for imitation', () => {+ const recipe = buildMusicTasteRecipe(sourceArgs()).recipe;+ const prompt = renderMusicTasteRecipePrompt(recipe);+ expect(prompt).toContain('high-level inspiration only');+ expect(prompt).toContain('Create an original work');+ expect(prompt).toContain('do not reproduce source tracks');+ });+});diff --git a/server/services/creativeCommissions/scheduler.js b/server/services/creativeCommissions/scheduler.jsindex 5d22251bbc..1996696c4b 100644--- a/server/services/creativeCommissions/scheduler.js+++ b/server/services/creativeCommissions/scheduler.js@@ -28,6 +28,7 @@ import { settingsEvents } from '../settings.js';import { listCommissions, getCommission, recordCommissionRun, commissionEvents } from './store.js';import { commissionToCron } from './directive.js';import { buildCommissionDirective, getAbilityAdapter } from './abilityAdapters.js';+import { buildMusicTasteRecipe } from './musicTasteRecipe.js';import { surfaceCommissionRun } from './surface.js';const eventId = (commissionId) => `creative-commission-${commissionId}`;@@ -168,6 +169,36 @@ export async function runCommissionNow(commissionId) {return fireCommission(commission, 'manual');}+// Source reads are intentionally lazy and machine-local. The recipe receives+// only the bounded stated summary and observed rollup; raw Digital Twin answers,+// Spotify caches, and activity events never enter a commission record or CD+// project. A source read failure is treated exactly like absent taste data so an+// opted-in commission records an explicit skip instead of generating generically.+async function resolveMusicTasteRecipe(commission) {+ const config = commission?.targetAbility === 'music' ? commission?.brief?.musicTaste : null;+ if (!config) return null;+ const [profile, observed] = await Promise.all([+ import('../taste-questionnaire.js')+ .then(({ getTasteProfile }) => getTasteProfile())+ .catch(() => null),+ import('../twinEnrichment.js')+ .then(({ getTasteEvidence }) => getTasteEvidence())+ .catch(() => null),+ ]);+ const musicSection = profile?.sections?.find((section) => section?.id === 'music');+ return buildMusicTasteRecipe({+ commissionId: commission.id,+ config,+ stated: {+ summary: musicSection?.summary || null,+ lastSessionAt: profile?.lastSessionAt || null,+ },+ observed,+ feedback: commission.feedback,+ recentRuns: commission.runs,+ });+}+/*** The shared fire core. Never throws (callers may be outside the Express* request lifecycle — a throw would crash Node). Re-reads the creative autonomy@@ -186,6 +217,7 @@ async function fireCommission(commission, trigger) {// manual caller sees a bare failure, can't find the orphaned CD project, and// a retry mints a duplicate.let startedProjectId = null;+ let startedTasteRecipe = null;const skip = async (reason) => {const run = await recordCommissionRun(commissionId, { status: 'skipped', reason, trigger }).catch(() => null);return { status: 'skipped', reason, run };@@ -215,6 +247,10 @@ async function fireCommission(commission, trigger) {const abilityAdapter = getAbilityAdapter(commission.targetAbility);if (!abilityAdapter) return skip('unknown-ability');+ const tasteResult = await resolveMusicTasteRecipe(commission);+ if (tasteResult?.status === 'unavailable') return skip(tasteResult.reason);+ startedTasteRecipe = tasteResult?.recipe || null;+// 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// `completeAgent` → `recordDomainUsage('cos', { actions: 1 })` on completion,@@ -228,7 +264,7 @@ async function fireCommission(commission, trigger) {import('../videoGen/local.js'),]);- const directive = buildCommissionDirective(commission);+ const directive = buildCommissionDirective(commission, { tasteRecipe: startedTasteRecipe });// Fan the commission's single LLM pin onto BOTH CD cognitive stages// (treatment + plan) as the project's `modelOverrides`, so the scheduled// fire is processed by the provider/model the user chose rather than the@@ -295,6 +331,7 @@ async function fireCommission(commission, trigger) {trigger,projectId: project.id,promptUsed: directive.goal,+ ...(startedTasteRecipe ? { tasteRecipe: startedTasteRecipe } : {}),}).catch(() => null);// Surface the fire (notification + brain inbox) so the user can rate the@@ -311,7 +348,10 @@ async function fireCommission(commission, trigger) {} catch (err) {console.error(`❌ Creative commission ${commissionId} ${trigger} fire failed: ${err?.message || err}`);const error = err?.message || String(err);- const run = await recordCommissionRun(commissionId, { status: 'failed', error, trigger, projectId: startedProjectId }).catch(() => null);+ const run = await recordCommissionRun(commissionId, {+ status: 'failed', error, trigger, projectId: startedProjectId,+ ...(startedTasteRecipe ? { tasteRecipe: startedTasteRecipe } : {}),+ }).catch(() => null);return { status: 'failed', error, projectId: startedProjectId, run };}}diff --git a/server/services/creativeCommissions/scheduler.test.js b/server/services/creativeCommissions/scheduler.test.jsindex 078d6cf388..7ddffbd361 100644--- a/server/services/creativeCommissions/scheduler.test.js+++ b/server/services/creativeCommissions/scheduler.test.js@@ -45,6 +45,17 @@ const getProviderByIdMock = vi.fn(async (id) => ({ id, type: 'tui' }));vi.mock('../providers.js', () => ({ getProviderById: (...a) => getProviderByIdMock(...a) }));vi.mock('../../lib/aiToolkit/constants.js', () => ({ PROVIDER_TYPES: { CLI: 'cli', TUI: 'tui', API: 'api' } }));+const tasteProfileMock = vi.fn(async () => ({ sections: [{ id: 'music', summary: 'Example stated preference' }], lastSessionAt: '2026-08-15T00:00:00.000Z' }));+const tasteEvidenceMock = vi.fn(async () => ({+ derivedAt: '2026-08-16T00:00:00.000Z',+ windows: { month: { listen: {+ topArtists: [{ name: 'Example Artist', count: 3 }],+ topTracks: [{ name: 'Example Track', artist: 'Example Artist', count: 2 }],+ } } },+}));+vi.mock('../taste-questionnaire.js', () => ({ getTasteProfile: (...a) => tasteProfileMock(...a) }));+vi.mock('../twinEnrichment.js', () => ({ getTasteEvidence: (...a) => tasteEvidenceMock(...a) }));+const loadStateMock = vi.fn(async () => ({ config: {} }));vi.mock('../cosState.js', () => ({ loadState: (...a) => loadStateMock(...a) }));const creativeModeMock = vi.fn(() => 'execute');@@ -84,6 +95,14 @@ beforeEach(() => {creativeModeMock.mockReturnValue('execute');budgetMock.mockResolvedValue({ withinBudget: true });loadStateMock.mockResolvedValue({ config: {} });+ tasteProfileMock.mockResolvedValue({ sections: [{ id: 'music', summary: 'Example stated preference' }], lastSessionAt: '2026-08-15T00:00:00.000Z' });+ tasteEvidenceMock.mockResolvedValue({+ derivedAt: '2026-08-16T00:00:00.000Z',+ windows: { month: { listen: {+ topArtists: [{ name: 'Example Artist', count: 3 }],+ topTracks: [{ name: 'Example Track', artist: 'Example Artist', count: 2 }],+ } } },+ });});describe('activeCommissions', () => {@@ -284,6 +303,34 @@ describe('runScheduledCommission gates', () => {expect(recordRunMock).toHaveBeenCalledWith('commission-1', expect.objectContaining({ status: 'started' }));});+ it('builds and persists a deterministic Digital Twin recipe for opted-in music', async () => {+ getCommissionMock.mockResolvedValue(videoCommission({+ targetAbility: 'music',+ brief: { intent: 'ambient', musicTaste: { source: 'digital-twin', window: 'month', anchorCount: 2, explorationPercent: 25 } },+ generation: { lengthSeconds: 45 },+ }));+ await runScheduledCommission('commission-1');+ expect(createProjectMock.mock.calls[0][0].directive.goal).toContain('Example Artist');+ 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) }),+ }));+ });++ it('records an explicit skip when taste mode has no usable observed anchors', async () => {+ tasteEvidenceMock.mockResolvedValueOnce({ derivedAt: '2026-08-16T00:00:00.000Z', windows: { month: { listen: { topArtists: [], topTracks: [] } } } });+ getCommissionMock.mockResolvedValue(videoCommission({+ targetAbility: 'music',+ brief: { intent: 'ambient', musicTaste: { source: 'digital-twin' } },+ generation: { lengthSeconds: 45 },+ }));+ await runScheduledCommission('commission-1');+ expect(recordRunMock).toHaveBeenCalledWith('commission-1', expect.objectContaining({+ status: 'skipped', reason: 'taste-source-unavailable', trigger: 'schedule',+ }));+ expect(createProjectMock).not.toHaveBeenCalled();+ });+it('skips an UNKNOWN target ability rather than mis-generating (#2769)', async () => {getCommissionMock.mockResolvedValue(videoCommission({ targetAbility: 'hologram' }));await runScheduledCommission('commission-1');diff --git a/server/services/creativeCommissions/store.js b/server/services/creativeCommissions/store.jsindex 58f8808eb0..3714a8fc62 100644--- a/server/services/creativeCommissions/store.js+++ b/server/services/creativeCommissions/store.js@@ -16,10 +16,10 @@* (`createRecordWriteQueue`, identical to universeBuilder), and delegates only* plain leaf I/O to the selected backend.*- * The COMMISSION stays MACHINE-LOCAL and NOT federated — the same rationale as- * `seriesAutopilotScheduler`'s settings-based schedules: a schedule that- * federated across sync peers would double-run on every machine. The DB row- * carries no sync cursor/tombstone (deletes are hard deletes, mirroring tribe).+ * The scheduled RUNNER stays MACHINE-LOCAL — schedule/runs/assignment/enabled+ * never cross peers, because a synced schedule would double-run on every+ * machine. The commission BRIEF and feedback federate separately below, with a+ * brief-scoped LWW clock and tombstone so peers converge without arming a cron.** FEEDBACK, by contrast, IS federated as of #2686 (split-record federation): the* taste reactions live in their own `commissionFeedback` record kind (see@@ -70,6 +70,7 @@ import {import { emitRecordUpdated, emitRecordDeleted, autoSubscribeRecordToAllPeers } from '../sharing/recordEvents.js';import { commissionToCron } from './directive.js';import { getAbilityAdapter } from './abilityAdapters.js';+import { normalizeMusicTasteConfig, sanitizeMusicTasteRecipe } from './musicTasteRecipe.js';import {recordFeedback,listFeedbackForCommission,@@ -124,6 +125,16 @@ export function sanitizeFeedbackEntry(raw) {};}+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;+ }+ return { ...raw, tasteRecipe };+}+/*** Normalize a raw record into the canonical stored shape. Returns null for a* non-object / id-less record (so a malformed on-disk / on-row record can't@@ -158,6 +169,7 @@ export function sanitizeCommission(raw) {? assignment.providerId.trim() : null;const assignmentModel = assignmentProviderId && isStr(assignment.model) && assignment.model.trim()? assignment.model.trim() : null;+ const musicTaste = normalizeMusicTasteConfig(brief.musicTaste);return {id: raw.id,name: isStr(raw.name) ? raw.name : 'Untitled Commission',@@ -172,6 +184,7 @@ export function sanitizeCommission(raw) {styleSpec: isStr(brief.styleSpec) ? brief.styleSpec : '',constraints: brief.constraints && typeof brief.constraints === 'object' ? brief.constraints : {},seedRefs: Array.isArray(brief.seedRefs) ? brief.seedRefs : [],+ ...(musicTaste ? { musicTaste } : {}),},schedule: {kind: isStr(schedule.kind) ? schedule.kind : 'DAILY',@@ -199,7 +212,7 @@ export function sanitizeCommission(raw) {? raw.feedback.map(sanitizeFeedbackEntry).filter(Boolean).slice(-MAX_PERSISTED_FEEDBACK): [],feedbackWindow: Number.isInteger(raw.feedbackWindow) ? raw.feedbackWindow : 5,- runs: Array.isArray(raw.runs) ? raw.runs.slice(-MAX_PERSISTED_RUNS) : [],+ runs: Array.isArray(raw.runs) ? raw.runs.slice(-MAX_PERSISTED_RUNS).map(sanitizeRunHistoryEntry) : [],createdAt: isStr(raw.createdAt) ? raw.createdAt : now,updatedAt: isStr(raw.updatedAt) ? raw.updatedAt : (isStr(raw.createdAt) ? raw.createdAt : now),// Brief-scoped LWW clock (#2686). The federation compares THIS, not `updatedAt`@@ -577,6 +590,11 @@ export async function updateCommission(id, patch) {brief: patch.brief ? {...current.brief,...patch.brief,+ musicTaste: Object.hasOwn(patch.brief, 'musicTaste')+ ? (patch.brief.musicTaste === null+ ? null+ : { ...(current.brief.musicTaste || {}), ...patch.brief.musicTaste })+ : current.brief.musicTaste,constraints: patch.brief.constraints? { ...current.brief.constraints, ...patch.brief.constraints }: current.brief.constraints,@@ -650,6 +668,7 @@ export async function recordCommissionRun(id, runEntry) {const currentRaw = await store.readRaw(id);if (!currentRaw) return null;const current = sanitizeCommission(currentRaw);+ const tasteRecipe = sanitizeMusicTasteRecipe(runEntry.tasteRecipe);const run = {id: runEntry.id || `run-${randomUUID()}`,ranAt: runEntry.ranAt || new Date().toISOString(),@@ -662,6 +681,7 @@ export async function recordCommissionRun(id, runEntry) {promptUsed: isStr(runEntry.promptUsed) ? runEntry.promptUsed : null,reason: isStr(runEntry.reason) ? runEntry.reason : null,error: isStr(runEntry.error) ? runEntry.error : null,+ ...(tasteRecipe ? { tasteRecipe } : {}),};const runs = [...(current.runs || []), run].slice(-MAX_PERSISTED_RUNS);await store.writeRaw(id, { ...current, runs, updatedAt: new Date().toISOString() });diff --git a/server/services/creativeCommissions/store.test.js b/server/services/creativeCommissions/store.test.jsindex 0bbe2e7606..04aac3255d 100644--- a/server/services/creativeCommissions/store.test.js+++ b/server/services/creativeCommissions/store.test.js@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-import { creativeCommissionUpdateSchema } from '../../lib/creativeCommissionValidation.js';+import { creativeCommissionCreateSchema, creativeCommissionUpdateSchema } from '../../lib/creativeCommissionValidation.js';// In-memory collectionStore so CRUD is exercised without touching the filesystem.// Keyed by collection `type` so the machine-local commission store and the@@ -87,6 +87,23 @@ describe('sanitizeCommission', () => {expect(rec.generation).toMatchObject({ quality: 'standard', aspectRatio: '16:9', targetDurationSeconds: 10 });expect(rec.runs).toEqual([]);expect(rec.feedback).toEqual([]);+ expect(rec.brief.musicTaste).toBeUndefined();+ });++ it('preserves bounded Digital Twin taste configuration in the federated brief', () => {+ const rec = sanitizeCommission({ id: 'c-taste', brief: {+ intent: 'ambient',+ musicTaste: { source: 'digital-twin', anchorCount: 4, explorationPercent: 40, musicEngineId: ' engine-a ' },+ } });+ expect(rec.brief.musicTaste).toEqual({+ source: 'digital-twin', window: 'month', anchorCount: 4, explorationPercent: 40,+ musicEngineId: 'engine-a', musicModelId: null,+ });+ expect(creativeCommissionCreateSchema.parse({+ name: 'Example Taste Commission',+ brief: { intent: 'ambient', musicTaste: { source: 'digital-twin' } },+ schedule: { kind: 'DAILY', atLocalTime: '02:00' },+ }).brief.musicTaste).toMatchObject({ source: 'digital-twin', anchorCount: 3, explorationPercent: 20 });});it('routes generation through the ability adapter per output type (#2769)', () => {@@ -255,6 +272,23 @@ describe('updateCommission', () => {expect(updated.generation.targetDurationSeconds).toBe(20); // preserved, not defaulted to 10});+ it('preserves or explicitly clears taste configuration on a partial brief patch', async () => {+ const created = await createCommission({+ ...validInput(),+ targetAbility: 'music',+ brief: { ...validInput().brief, musicTaste: { source: 'digital-twin', anchorCount: 2 } },+ });+ const parsed = creativeCommissionUpdateSchema.parse({ brief: { intent: 'reworked' } });+ const preserved = await updateCommission(created.id, parsed);+ expect(preserved.brief.musicTaste).toMatchObject({ source: 'digital-twin', anchorCount: 2 });+ const partiallyUpdated = await updateCommission(created.id, creativeCommissionUpdateSchema.parse({+ brief: { musicTaste: { explorationPercent: 45 } },+ }));+ expect(partiallyUpdated.brief.musicTaste).toMatchObject({ anchorCount: 2, explorationPercent: 45 });+ const cleared = await updateCommission(created.id, creativeCommissionUpdateSchema.parse({ brief: { musicTaste: null } }));+ expect(cleared.brief.musicTaste).toBeUndefined();+ });+it('throws NOT_FOUND for an unknown id', async () => {try { await updateCommission('nope', { enabled: false }); }catch (e) { expect(e.code).toBe(ERR_NOT_FOUND); }@@ -279,6 +313,27 @@ describe('recordCommissionRun', () => {const after = await getCommission(created.id);expect(after.runs.map((r) => r.trigger)).toEqual(['manual', 'schedule', 'schedule']);});++ it('persists bounded taste recipe provenance only on the local run history', async () => {+ const created = await createCommission(validInput());+ const recipe = {+ 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' }],+ statedContext: 'Example preference',+ sourceVersion: 'music-taste-v1:example',+ sourceHash: 'example-hash',+ };+ await recordCommissionRun(created.id, { status: 'started', tasteRecipe: recipe });+ const after = await getCommission(created.id);+ expect(after.runs[0].tasteRecipe).toEqual(recipe);+ expect(sanitizeCommission({ ...after, runs: after.runs }).runs[0].tasteRecipe).toEqual(recipe);+ });});describe('deleteCommission', () => {diff --git a/server/services/twinEnrichment.js b/server/services/twinEnrichment.jsindex 3755e0e0f7..a846653d1a 100644--- a/server/services/twinEnrichment.js+++ b/server/services/twinEnrichment.js@@ -114,6 +114,39 @@ export function listenGenreNames(ev) {return genres.map((g) => String((typeof g === 'string' ? g : g?.name) || '').trim()).filter(Boolean);}+// Flatten track identity across the live-sync and extended-history shapes.+// Episodes are listening activity but not music anchors, so they are excluded+// from the bounded top-track rollup. The artist is retained only as normalized+// display metadata; raw Spotify records remain outside the evidence file.+export function listenTrackEntries(ev) {+ if (ev?.metadata?.type === 'episode') return [];+ const name = String(ev?.metadata?.trackName || ev?.title || '').trim();+ if (!name) return [];+ const artists = ev?.metadata?.artists;+ const artist = Array.isArray(artists)+ ? artists.map((a) => String((typeof a === 'string' ? a : a?.name) || '').trim()).filter(Boolean).join(', ')+ : String(ev?.metadata?.artist || '').trim();+ return [{ name, artist: artist || null }];+}++// Bounded deterministic top-track rollup. Ties are sorted by track then artist+// so the evidence file remains stable across peers and recomputes.+export function topTrackCounts(entries, limit = 10) {+ const counts = new Map();+ for (const entry of entries || []) {+ const name = String(entry?.name || '').trim();+ if (!name) continue;+ const artist = String(entry?.artist || '').trim();+ const key = `${name}\u0000${artist}`;+ counts.set(key, { name, artist: artist || null, count: (counts.get(key)?.count || 0) + 1 });+ }+ return [...counts.values()]+ .sort((a, b) => (b.count - a.count)+ || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)+ || (String(a.artist || '') < String(b.artist || '') ? -1 : String(a.artist || '') > String(b.artist || '') ? 1 : 0))+ .slice(0, Math.max(0, limit));+}+// A stable per-play key for novelty counting. Track identity across both source// shapes: sync's `trackId`, import's `trackUri`, then isrc, then title —// falling to dedupeKey only as a last resort (per-play, so it never collapses@@ -132,13 +165,16 @@ export function rollupListen(events, topN = 10) {const listens = (events || []).filter((e) => e?.kind === MEDIA_LISTEN);const artistKeys = [];const genreKeys = [];+ const trackEntries = [];for (const ev of listens) {artistKeys.push(...listenArtistNames(ev));genreKeys.push(...listenGenreNames(ev));+ trackEntries.push(...listenTrackEntries(ev));}return {total: listens.length,topArtists: topCounts(artistKeys, topN),+ topTracks: topTrackCounts(trackEntries, topN),topGenres: topCounts(genreKeys, topN),novelty: noveltyRatio(listens.map(listenNoveltyKey)),};diff --git a/server/services/twinEnrichment.test.js b/server/services/twinEnrichment.test.jsindex bbdef7a4ba..4c44d0204d 100644--- a/server/services/twinEnrichment.test.js+++ b/server/services/twinEnrichment.test.js@@ -11,7 +11,9 @@ import {topCounts,noveltyRatio,listenArtistNames,+ listenTrackEntries,listenGenreNames,+ topTrackCounts,rollupListen,rollupWatch,chronotypeHistogram,@@ -81,6 +83,27 @@ describe('listenArtistNames / listenGenreNames', () => {});});+describe('listenTrackEntries / topTrackCounts', () => {+ it('normalizes live Spotify and extended-history track shapes', () => {+ expect(listenTrackEntries({ metadata: { trackName: 'Track A', artists: [{ name: 'Artist A' }] } }))+ .toEqual([{ name: 'Track A', artist: 'Artist A' }]);+ expect(listenTrackEntries({ title: 'Track B', metadata: { artist: 'Artist B', trackUri: 'spotify:track:2' } }))+ .toEqual([{ name: 'Track B', artist: 'Artist B' }]);+ expect(listenTrackEntries({ title: 'Example Episode', metadata: { type: 'episode' } })).toEqual([]);+ });++ it('counts tracks by name and artist with deterministic tie ordering', () => {+ expect(topTrackCounts([+ { name: 'Track B', artist: 'Artist B' },+ { name: 'Track A', artist: 'Artist A' },+ { name: 'Track B', artist: 'Artist B' },+ ])).toEqual([+ { name: 'Track B', artist: 'Artist B', count: 2 },+ { name: 'Track A', artist: 'Artist A', count: 1 },+ ]);+ });+});+describe('rollupListen / rollupWatch', () => {const listens = [{ kind: 'media.listen', title: 'T1', metadata: { trackId: 't1', artists: [{ name: 'A' }], genres: ['ambient'] } },@@ -92,6 +115,10 @@ describe('rollupListen / rollupWatch', () => {const r = rollupListen(listens);expect(r.total).toBe(3);expect(r.topArtists).toEqual([{ name: 'A', count: 2 }, { name: 'B', count: 1 }]);+ expect(r.topTracks).toEqual([+ { name: 'T1', artist: 'A', count: 2 },+ { name: 'T2', artist: 'B', count: 1 },+ ]);expect(r.topGenres).toEqual([{ name: 'ambient', count: 2 }]);// 3 plays, t1 twice → 2 distinct.expect(r.novelty).toEqual({ total: 3, distinct: 2, repeats: 1, noveltyRatio: 0.667 });