@gobing-ai/knowledge-kit 0.1.20 → 0.1.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/board/collect/index.js +1 -0
  3. package/dist/board/daily-voice/index.js +1279 -261
  4. package/dist/board/itc/index.js +1 -0
  5. package/dist/index.js +13938 -8966
  6. package/package.json +1 -1
  7. package/plugins/generations/dailynews-gen/dist/index.js +285 -16
  8. package/plugins/generations/dailynews-gen/src/editorial-claims.ts +215 -0
  9. package/plugins/generations/dailynews-gen/src/index.ts +23 -4
  10. package/plugins/generations/dailynews-gen/src/script-builder.ts +10 -3
  11. package/plugins/generations/dailynews-gen/src/script-plan.ts +74 -14
  12. package/plugins/generations/gemini-tts/dist/index.js +47 -7
  13. package/plugins/generations/gemini-tts/src/gemini-client.ts +34 -6
  14. package/plugins/generations/music-gen/README.md +277 -0
  15. package/plugins/generations/music-gen/dist/index.js +23580 -0
  16. package/plugins/generations/music-gen/package.json +24 -0
  17. package/plugins/generations/music-gen/plugin.json +23 -0
  18. package/plugins/generations/music-gen/presets/SOURCE.md +39 -0
  19. package/plugins/generations/music-gen/presets/formats/clip.yaml +21 -0
  20. package/plugins/generations/music-gen/presets/formats/jingle.yaml +22 -0
  21. package/plugins/generations/music-gen/presets/formats/loop.yaml +21 -0
  22. package/plugins/generations/music-gen/presets/formats/song.yaml +36 -0
  23. package/plugins/generations/music-gen/presets/formats/underscore.yaml +22 -0
  24. package/plugins/generations/music-gen/presets/themes/ambient-tech.yaml +30 -0
  25. package/plugins/generations/music-gen/presets/themes/cinematic.yaml +30 -0
  26. package/plugins/generations/music-gen/presets/themes/lofi.yaml +30 -0
  27. package/plugins/generations/music-gen/presets/themes/synthwave.yaml +35 -0
  28. package/plugins/generations/music-gen/scripts/gen-preset-index.ts +181 -0
  29. package/plugins/generations/music-gen/scripts/resolve-preset.ts +64 -0
  30. package/plugins/generations/music-gen/src/adapter/index.ts +35 -0
  31. package/plugins/generations/music-gen/src/adapter/instance.ts +927 -0
  32. package/plugins/generations/music-gen/src/adapter/offline.ts +124 -0
  33. package/plugins/generations/music-gen/src/artifact.ts +223 -0
  34. package/plugins/generations/music-gen/src/audio/checks.ts +618 -0
  35. package/plugins/generations/music-gen/src/audio/master.ts +267 -0
  36. package/plugins/generations/music-gen/src/audio/measure.ts +507 -0
  37. package/plugins/generations/music-gen/src/audio/profile.ts +131 -0
  38. package/plugins/generations/music-gen/src/audio.ts +122 -0
  39. package/plugins/generations/music-gen/src/brief.ts +191 -0
  40. package/plugins/generations/music-gen/src/config.ts +451 -0
  41. package/plugins/generations/music-gen/src/content.ts +199 -0
  42. package/plugins/generations/music-gen/src/digest.ts +100 -0
  43. package/plugins/generations/music-gen/src/index.ts +147 -0
  44. package/plugins/generations/music-gen/src/job.ts +131 -0
  45. package/plugins/generations/music-gen/src/plugin.ts +371 -0
  46. package/plugins/generations/music-gen/src/presets.ts +951 -0
  47. package/plugins/generations/music-gen/src/render.ts +87 -0
  48. package/plugins/generations/music-gen/src/request.ts +102 -0
  49. package/plugins/generations/music-gen/src/spend.ts +495 -0
  50. package/plugins/generations/music-gen/tsconfig.json +8 -0
  51. package/plugins/generations/omni-voice-gen/uv.toml +5 -0
  52. package/plugins/generations/vibe-voice-tts/README.md +64 -0
  53. package/plugins/generations/vibe-voice-tts/dist/index.js +14259 -0
  54. package/plugins/generations/vibe-voice-tts/package.json +16 -0
  55. package/plugins/generations/vibe-voice-tts/plugin.json +6 -0
  56. package/plugins/generations/vibe-voice-tts/profiles.json +10 -0
  57. package/plugins/generations/vibe-voice-tts/pyproject.toml +9 -0
  58. package/plugins/generations/vibe-voice-tts/python/worker.py +566 -0
  59. package/plugins/generations/vibe-voice-tts/src/index.ts +88 -0
  60. package/plugins/generations/vibe-voice-tts/src/vibevoice-client.ts +828 -0
  61. package/plugins/generations/vibe-voice-tts/tsconfig.json +8 -0
  62. package/plugins/generations/vibe-voice-tts/uv.lock +1767 -0
  63. package/plugins/generations/vibe-voice-tts/uv.toml +4 -0
  64. package/plugins/generations/voice-gen/dist/index.js +31 -1
  65. package/plugins/generations/voice-gen/src/voicebox-client.ts +50 -1
  66. package/plugins/generations/voxcpm-tts/dist/index.js +81 -9
  67. package/plugins/generations/voxcpm-tts/python/worker.py +9 -0
  68. package/plugins/generations/voxcpm-tts/src/index.ts +41 -0
  69. package/plugins/generations/voxcpm-tts/src/voxcpm-client.ts +32 -11
  70. package/plugins/generations/voxcpm-tts/uv.toml +5 -0
  71. package/plugins/kk/README.md +21 -0
  72. package/plugins/kk/decisions/kk-safety.yaml +5 -2
  73. package/plugins/kk/plugin.json +1 -1
  74. package/plugins/kk/schedules/kk-serve.launchd.plist.tmpl +14 -2
  75. package/plugins/kk/scripts/cover-compositor.ts +380 -32
  76. package/plugins/kk/scripts/daily-cover-mock.ts +40 -3
  77. package/plugins/kk/scripts/daily-stages.ts +933 -60
  78. package/plugins/kk/scripts/episode-identity.ts +180 -0
  79. package/plugins/kk/scripts/kk-workflow-stages.ts +111 -12
  80. package/plugins/kk/scripts/music-stages.ts +624 -0
  81. package/plugins/kk/scripts/news-editorial-ledger.ts +906 -0
  82. package/plugins/kk/scripts/safety-artifact-check.ts +28 -5
  83. package/plugins/kk/scripts/source-citation.ts +187 -0
  84. package/plugins/kk/scripts/topic-selection-attempts.ts +446 -0
  85. package/plugins/kk/scripts/topic-selection-calibration.ts +161 -0
  86. package/plugins/kk/skills/content-judge/SKILL.md +11 -6
  87. package/plugins/kk/skills/content-judge/references/music-quality-rubric.md +147 -0
  88. package/plugins/kk/skills/content-judge/references/rubrics.md +15 -0
  89. package/plugins/kk/skills/content-safety/SKILL.md +12 -0
  90. package/plugins/kk/skills/music-authoring/SKILL.md +276 -0
  91. package/plugins/kk/skills/music-authoring/references/judge-input.md +117 -0
  92. package/plugins/kk/skills/news-editorial/SKILL.md +102 -15
  93. package/plugins/kk/skills/news-editorial/references/selection.md +4 -0
  94. package/plugins/kk/skills/news-editorial/references/style-contract.zh.md +58 -11
  95. package/plugins/kk/workflows/kk-daily-ai-voice.yaml +12 -11
  96. package/plugins/kk/workflows/kk-daily-ai-voice2.yaml +13 -12
  97. package/plugins/kk/workflows/kk-daily-safety.yaml +12 -10
  98. package/plugins/kk/workflows/kk-music.yaml +332 -0
  99. package/plugins/kk/workflows/kk-news-generate.yaml +81 -6
  100. package/plugins/kk/workflows/kk-publish.yaml +4 -1
  101. package/plugins/publishings/bilibili-pub/dist/index.js +11 -1
  102. package/plugins/publishings/bilibili-pub/dist/profile-check.js +11 -1
  103. package/plugins/publishings/cnblogs-pub/dist/index.js +11 -1
  104. package/plugins/publishings/cnblogs-pub/dist/profile-check.js +11 -1
  105. package/plugins/publishings/csdn-pub/dist/index.js +11 -1
  106. package/plugins/publishings/csdn-pub/dist/profile-check.js +11 -1
  107. package/plugins/publishings/infoq-pub/dist/index.js +11 -1
  108. package/plugins/publishings/infoq-pub/dist/profile-check.js +11 -1
  109. package/plugins/publishings/jike-pub/dist/index.js +11 -1
  110. package/plugins/publishings/jike-pub/dist/profile-check.js +11 -1
  111. package/plugins/publishings/juejin-pub/dist/index.js +11 -1
  112. package/plugins/publishings/juejin-pub/dist/profile-check.js +11 -1
  113. package/plugins/publishings/linkedin-pub/dist/index.js +62 -10
  114. package/plugins/publishings/linkedin-pub/dist/profile-check.js +16 -1
  115. package/plugins/publishings/linkedin-pub/src/index.ts +99 -12
  116. package/plugins/publishings/podcast-pub/dist/index.js +586 -20
  117. package/plugins/publishings/podcast-pub/src/corrections.ts +509 -0
  118. package/plugins/publishings/podcast-pub/src/index.ts +257 -5
  119. package/plugins/publishings/podcast-pub/src/show-notes-brief.ts +240 -0
  120. package/plugins/publishings/podcast-pub/src/show-notes.ts +69 -13
  121. package/plugins/publishings/shipinhao-pub/dist/index.js +59 -8
  122. package/plugins/publishings/shipinhao-pub/dist/profile-check.js +11 -1
  123. package/plugins/publishings/shipinhao-pub/src/audio-flow.ts +105 -6
  124. package/plugins/publishings/sspai-pub/dist/index.js +11 -1
  125. package/plugins/publishings/sspai-pub/dist/profile-check.js +11 -1
  126. package/plugins/publishings/substack-pub/dist/index.js +11 -1
  127. package/plugins/publishings/substack-pub/dist/profile-check.js +11 -1
  128. package/plugins/publishings/surfdash-pub/dist/index.js +80 -24
  129. package/plugins/publishings/surfdash-pub/src/digest-check.ts +7 -3
  130. package/plugins/publishings/surfdash-pub/src/index.ts +107 -18
  131. package/plugins/publishings/surfdash-pub/src/patch.ts +21 -3
  132. package/plugins/publishings/surfdash-pub/src/topic-claims.ts +3 -1
  133. package/plugins/publishings/threads-pub/dist/index.js +58 -6
  134. package/plugins/publishings/threads-pub/dist/profile-check.js +18 -2
  135. package/plugins/publishings/threads-pub/src/post-rail.ts +101 -4
  136. package/plugins/publishings/wechatmp-pub/dist/index.js +105 -35
  137. package/plugins/publishings/wechatmp-pub/dist/profile-check.js +11 -1
  138. package/plugins/publishings/wechatmp-pub/src/cgi-draft.ts +87 -53
  139. package/plugins/publishings/wechatmp-pub/src/enrich.ts +61 -3
  140. package/plugins/publishings/wechatmp-pub/src/flow.ts +28 -0
  141. package/plugins/publishings/weibo-pub/dist/index.js +11 -1
  142. package/plugins/publishings/weibo-pub/dist/profile-check.js +11 -1
  143. package/plugins/publishings/x-pub/dist/index.js +95 -10
  144. package/plugins/publishings/x-pub/dist/profile-check.js +11 -1
  145. package/plugins/publishings/x-pub/src/post-rail.ts +154 -12
  146. package/plugins/publishings/xhs-pub/dist/index.js +11 -1
  147. package/plugins/publishings/xhs-pub/dist/profile-check.js +11 -1
  148. package/plugins/publishings/xiaoyuzhou-pub/dist/index.js +11 -1
  149. package/plugins/publishings/xiaoyuzhou-pub/dist/profile-check.js +11 -1
@@ -0,0 +1,951 @@
1
+ import { join, resolve } from 'node:path';
2
+ import { createNodeFileSystem, type FileSystem } from '@gobing-ai/ts-runtime';
3
+ import { z } from 'zod';
4
+ import {
5
+ AUDIO_FORMATS,
6
+ type AudioFormat,
7
+ durationSeconds,
8
+ LANGUAGE_PATTERN,
9
+ MAX_DURATION_SECONDS,
10
+ MIN_DURATION_SECONDS,
11
+ MMSS_PATTERN,
12
+ MUSIC_MODELS,
13
+ type MusicBrief,
14
+ type MusicModel,
15
+ type StructureEntry,
16
+ StructureEntrySchema,
17
+ } from './brief';
18
+
19
+ /**
20
+ * Preset resolution (task 0397 R4) and preset portability (R4 / 0399 R4).
21
+ *
22
+ * Resolution is pure precedence over four layers plus built-in defaults:
23
+ * `brief > workflow preset > theme preset > format preset > built-in default`.
24
+ * A field that survives every layer as `undefined` and has no built-in makes
25
+ * resolution fail loudly — the instance's own defaults (`durationTarget: '3:00'`,
26
+ * `language: 'EN'`) must never silently decide a job.
27
+ *
28
+ * Preset files are portable data: no provider, API base URL, API model id,
29
+ * credential or price may appear anywhere in them (fail closed, exit code 2).
30
+ *
31
+ * 0399 adds the data half on top of that frozen surface: the format/theme preset
32
+ * schemas with their provenance and evidence status, the loader that enforces
33
+ * both uniformly for every file under `presets/`, and the name-based entry point
34
+ * that fails loudly (exit code 1) for an unknown format or theme.
35
+ */
36
+
37
+ /** Which layer supplied a resolved value. */
38
+ export type FieldSource = 'brief' | 'workflow' | 'theme' | 'format' | 'builtin';
39
+
40
+ /** A resolved value plus the layer that won. */
41
+ export interface Sourced<T> {
42
+ value: T;
43
+ source: FieldSource;
44
+ /** Preset name for the `workflow`/`theme`/`format` sources. */
45
+ origin?: string;
46
+ }
47
+
48
+ /** The resolvable half of a brief — what any preset layer may also supply. */
49
+ export interface MusicJobOverrides {
50
+ model?: MusicModel;
51
+ duration_target?: string;
52
+ language?: string;
53
+ instrumental?: boolean;
54
+ /** Format presets declare a lyrics policy; `forbidden` resolves to `instrumental: true`. */
55
+ lyrics_policy?: 'allowed' | 'forbidden';
56
+ audio_format?: AudioFormat;
57
+ style?: string;
58
+ avoid?: string[];
59
+ structure?: StructureEntry[];
60
+ }
61
+
62
+ /** One preset layer: its name (for `explainJob`) plus the fields it supplies. */
63
+ export interface PresetLayer extends MusicJobOverrides {
64
+ name: string;
65
+ }
66
+
67
+ /** The three preset layers, in precedence order after the brief. */
68
+ export interface PresetLayers {
69
+ workflow?: PresetLayer;
70
+ theme?: PresetLayer;
71
+ format?: PresetLayer;
72
+ }
73
+
74
+ /** The fully resolved job every downstream stage consumes. */
75
+ export interface ResolvedJob {
76
+ title: string;
77
+ model: Sourced<MusicModel>;
78
+ duration_target: Sourced<string | undefined>;
79
+ language: Sourced<string>;
80
+ instrumental: Sourced<boolean>;
81
+ audio_format: Sourced<AudioFormat>;
82
+ style: Sourced<string>;
83
+ avoid: Sourced<string[]>;
84
+ structure: Sourced<StructureEntry[]>;
85
+ /** Explicit lyrics text; `undefined` lets the model write its own, `''` is the instrumental payload. */
86
+ lyrics: string | undefined;
87
+ takes: number;
88
+ images: string[];
89
+ meta: Record<string, unknown>;
90
+ }
91
+
92
+ /** Last link of every resolution chain. `duration_target` and `style` deliberately have no default. */
93
+ export const BUILTIN_DEFAULTS = {
94
+ model: 'pro',
95
+ language: 'EN',
96
+ instrumental: false,
97
+ audio_format: 'mp3',
98
+ } as const satisfies MusicJobOverrides;
99
+
100
+ /** Raised when no layer can satisfy a required job field, or when a resolved value is invalid. */
101
+ export class JobResolutionError extends Error {
102
+ /** CLI exit code the caller must surface. */
103
+ readonly exitCode = 1;
104
+
105
+ constructor(message: string) {
106
+ super(message);
107
+ this.name = 'JobResolutionError';
108
+ }
109
+ }
110
+
111
+ /** Raised when a preset file carries a non-portable key (provider, base URL, model id, credential, price). */
112
+ export class PresetContractViolation extends Error {
113
+ /** CLI exit code the loader wrapper must surface. */
114
+ readonly exitCode = 2;
115
+
116
+ /** Dotted paths of every offending key, in document order. */
117
+ readonly violations: readonly string[];
118
+
119
+ constructor(path: string, violations: readonly string[]) {
120
+ super(`${path}: preset is not portable — ${violations.join(', ')}`);
121
+ this.name = 'PresetContractViolation';
122
+ this.violations = violations;
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Keys a preset file may never carry. `model` (`pro`|`clip`) is the instance's
128
+ * own selector and stays allowed; an upstream API model id, a provider name, a
129
+ * base URL, a credential or a price is provider-specific user config (0400).
130
+ */
131
+ export const FORBIDDEN_PRESET_KEYS: readonly string[] = [
132
+ 'provider',
133
+ 'providers',
134
+ 'model_id',
135
+ 'model-id',
136
+ 'modelId',
137
+ 'api_model_id',
138
+ 'api-model-id',
139
+ 'apiModelId',
140
+ 'base_url',
141
+ 'base-url',
142
+ 'baseUrl',
143
+ 'api_base_url',
144
+ 'apiBaseUrl',
145
+ 'endpoint',
146
+ 'price',
147
+ 'prices',
148
+ 'unit_price',
149
+ 'unitPrice',
150
+ 'cost',
151
+ 'cost_usd',
152
+ 'api_key',
153
+ 'apiKey',
154
+ 'secret',
155
+ 'secrets',
156
+ 'token',
157
+ 'apiToken',
158
+ ];
159
+
160
+ interface LayerSource {
161
+ kind: FieldSource;
162
+ origin?: string;
163
+ values: MusicJobOverrides;
164
+ }
165
+
166
+ /** Human label for a layer, used in every diagnostic. */
167
+ function describeSource(sourced: { source: FieldSource; origin?: string }): string {
168
+ return sourced.origin === undefined ? sourced.source : `${sourced.source} preset "${sourced.origin}"`;
169
+ }
170
+
171
+ /** Read the resolvable half of a brief. */
172
+ function briefOverrides(brief: MusicBrief): MusicJobOverrides {
173
+ return {
174
+ model: brief.model,
175
+ duration_target: brief.duration_target,
176
+ language: brief.language,
177
+ instrumental: brief.instrumental,
178
+ audio_format: brief.audio_format,
179
+ style: brief.style,
180
+ avoid: brief.avoid,
181
+ structure: brief.structure,
182
+ };
183
+ }
184
+
185
+ /** `instrumental` from a layer, honouring a format preset's `lyrics_policy`. */
186
+ function layerInstrumental(values: MusicJobOverrides): boolean | undefined {
187
+ if (values.instrumental !== undefined) {
188
+ return values.instrumental;
189
+ }
190
+ if (values.lyrics_policy === 'forbidden') {
191
+ return true;
192
+ }
193
+ if (values.lyrics_policy === 'allowed') {
194
+ return false;
195
+ }
196
+ return undefined;
197
+ }
198
+
199
+ /** First layer that supplies a value wins, and its identity is carried through. */
200
+ function pick<T>(
201
+ layers: readonly LayerSource[],
202
+ read: (values: MusicJobOverrides) => T | undefined,
203
+ ): Sourced<T | undefined> {
204
+ for (const layer of layers) {
205
+ const value = read(layer.values);
206
+ if (value !== undefined) {
207
+ return { value, source: layer.kind, origin: layer.origin };
208
+ }
209
+ }
210
+ return { value: undefined, source: 'builtin' };
211
+ }
212
+
213
+ /** Apply a built-in default or fail loudly, naming the field. */
214
+ function requireValue<T>(field: string, sourced: Sourced<T | undefined>, builtin?: T): Sourced<T> {
215
+ if (sourced.value !== undefined) {
216
+ return { value: sourced.value, source: sourced.source, origin: sourced.origin };
217
+ }
218
+ if (builtin !== undefined) {
219
+ return { value: builtin, source: 'builtin' };
220
+ }
221
+ throw new JobResolutionError(
222
+ `${field} is unresolved: the brief, workflow preset, theme preset and format preset all leave it empty and there is no built-in default`,
223
+ );
224
+ }
225
+
226
+ /** Case-insensitive de-duplication that keeps the first spelling and its position. */
227
+ function dedupe(values: readonly string[]): string[] {
228
+ const seen = new Set<string>();
229
+ const out: string[] = [];
230
+ for (const value of values) {
231
+ const key = value.trim().toLowerCase();
232
+ if (key === '' || seen.has(key)) {
233
+ continue;
234
+ }
235
+ seen.add(key);
236
+ out.push(value.trim());
237
+ }
238
+ return out;
239
+ }
240
+
241
+ /**
242
+ * Merge the avoid lists: brief entries first, then the workflow, theme and
243
+ * format layers, de-duplicated case-insensitively. `avoid` is the one additive
244
+ * field — an authored exclusion must not switch off the theme's cliché guard.
245
+ */
246
+ function mergeAvoid(layers: readonly LayerSource[]): Sourced<string[]> {
247
+ const merged: string[] = [];
248
+ let winner: Sourced<string[]> = { value: [], source: 'builtin' };
249
+ for (const layer of layers) {
250
+ const values = layer.values.avoid ?? [];
251
+ if (values.length === 0) {
252
+ continue;
253
+ }
254
+ if (winner.source === 'builtin') {
255
+ winner = { value: [], source: layer.kind, origin: layer.origin };
256
+ }
257
+ merged.push(...values);
258
+ }
259
+ return { value: dedupe(merged), source: winner.source, origin: winner.origin };
260
+ }
261
+
262
+ /** Validate a resolved duration target — preset data is untrusted too. */
263
+ function validateDuration(value: string, source: { source: FieldSource; origin?: string }): void {
264
+ if (!MMSS_PATTERN.test(value)) {
265
+ throw new JobResolutionError(`duration_target "${value}" from ${describeSource(source)} is not m:ss`);
266
+ }
267
+ const seconds = durationSeconds(value);
268
+ if (seconds < MIN_DURATION_SECONDS || seconds > MAX_DURATION_SECONDS) {
269
+ throw new JobResolutionError(
270
+ `duration_target "${value}" from ${describeSource(source)} is outside 0:05–3:00 (the Pro ceiling)`,
271
+ );
272
+ }
273
+ }
274
+
275
+ /**
276
+ * Resolve a brief plus preset layers into the effective job (R4).
277
+ *
278
+ * Throws {@link JobResolutionError} when a Pro job has no duration target, when
279
+ * no layer supplies the technical direction, or when a resolved value is
280
+ * invalid — never by falling back to an instance default.
281
+ */
282
+ export function resolveJob(brief: MusicBrief, layers: PresetLayers = {}): ResolvedJob {
283
+ const sources: LayerSource[] = [{ kind: 'brief', values: briefOverrides(brief) }];
284
+ if (layers.workflow !== undefined) {
285
+ sources.push({ kind: 'workflow', origin: layers.workflow.name, values: layers.workflow });
286
+ }
287
+ if (layers.theme !== undefined) {
288
+ sources.push({ kind: 'theme', origin: layers.theme.name, values: layers.theme });
289
+ }
290
+ if (layers.format !== undefined) {
291
+ sources.push({ kind: 'format', origin: layers.format.name, values: layers.format });
292
+ }
293
+
294
+ const model = requireValue(
295
+ 'model',
296
+ pick(sources, (values) => values.model),
297
+ BUILTIN_DEFAULTS.model,
298
+ );
299
+ if (!MUSIC_MODELS.includes(model.value)) {
300
+ throw new JobResolutionError(`model "${String(model.value)}" is not pro|clip`);
301
+ }
302
+
303
+ const duration = pick(sources, (values) => values.duration_target);
304
+ const durationTarget = duration.value;
305
+ if (model.value === 'pro' && durationTarget === undefined) {
306
+ throw new JobResolutionError(
307
+ 'duration_target is unresolved for a Pro job: the brief, workflow preset, theme preset and format preset all leave it empty. The instance substitutes "3:00" — set duration_target or a format default',
308
+ );
309
+ }
310
+ if (durationTarget !== undefined) {
311
+ validateDuration(durationTarget, duration);
312
+ if (model.value === 'clip') {
313
+ const seconds = durationSeconds(durationTarget);
314
+ if (seconds < 25 || seconds > 35) {
315
+ throw new JobResolutionError(
316
+ `duration_target "${durationTarget}" cannot apply to a clip job: clip is fixed at about 0:30 and ignores duration. Drop duration_target or use model: pro`,
317
+ );
318
+ }
319
+ }
320
+ }
321
+
322
+ const language = requireValue(
323
+ 'language',
324
+ pick(sources, (values) => values.language),
325
+ BUILTIN_DEFAULTS.language,
326
+ );
327
+ if (!LANGUAGE_PATTERN.test(language.value)) {
328
+ throw new JobResolutionError(
329
+ `language "${language.value}" from ${describeSource(language)} is not a short tag such as EN`,
330
+ );
331
+ }
332
+
333
+ const audioFormat = requireValue(
334
+ 'audio_format',
335
+ pick(sources, (values) => values.audio_format),
336
+ BUILTIN_DEFAULTS.audio_format,
337
+ );
338
+ if (!AUDIO_FORMATS.includes(audioFormat.value)) {
339
+ throw new JobResolutionError(`audio_format "${String(audioFormat.value)}" is not mp3|wav`);
340
+ }
341
+
342
+ const style = requireValue(
343
+ 'style',
344
+ pick(sources, (values) => values.style),
345
+ );
346
+ if (style.value.trim() === '') {
347
+ throw new JobResolutionError(
348
+ `style from ${describeSource(style)} is empty; the prompt would carry no technical direction`,
349
+ );
350
+ }
351
+
352
+ const instrumental = requireValue(
353
+ 'instrumental',
354
+ pick(sources, (values) => layerInstrumental(values)),
355
+ BUILTIN_DEFAULTS.instrumental,
356
+ );
357
+ const structure = pick(sources, (values) => values.structure);
358
+
359
+ // A preset may force instrumental (a format's lyrics_policy); dropping authored
360
+ // lyrics on the floor is exactly the silent loss the total mapping forbids.
361
+ if (instrumental.value && (brief.lyrics ?? '').trim() !== '') {
362
+ throw new JobResolutionError(
363
+ `instrumental resolves to true from ${describeSource(instrumental)} but the brief carries lyrics; drop the lyrics or override instrumental: false`,
364
+ );
365
+ }
366
+
367
+ return {
368
+ title: brief.title,
369
+ model,
370
+ duration_target: { value: durationTarget, source: duration.source, origin: duration.origin },
371
+ language,
372
+ instrumental,
373
+ audio_format: audioFormat,
374
+ style: { value: style.value.trim(), source: style.source, origin: style.origin },
375
+ avoid: mergeAvoid(sources),
376
+ structure: { value: structure.value ?? [], source: structure.source, origin: structure.origin },
377
+ lyrics: instrumental.value ? '' : brief.lyrics,
378
+ takes: brief.takes ?? 1,
379
+ images: brief.images ?? [],
380
+ meta: brief.meta ?? {},
381
+ };
382
+ }
383
+
384
+ /** One line per resolved field, naming the layer that won (0399 R3 prints these). */
385
+ export function explainJob(job: ResolvedJob): string[] {
386
+ const show = (value: string | undefined): string => {
387
+ if (value === undefined) {
388
+ return '(none)';
389
+ }
390
+ const firstLine = value.split('\n')[0] ?? '';
391
+ return firstLine.length > 60 ? `${firstLine.slice(0, 57)}...` : firstLine;
392
+ };
393
+ const count = job.avoid.value.length;
394
+ return [
395
+ `title: ${job.title} (brief)`,
396
+ `model: ${job.model.value} (${describeSource(job.model)})`,
397
+ `duration_target: ${job.duration_target.value ?? '(none)'} (${describeSource(job.duration_target)})`,
398
+ `language: ${job.language.value} (${describeSource(job.language)})`,
399
+ `instrumental: ${String(job.instrumental.value)} (${describeSource(job.instrumental)})`,
400
+ `audio_format: ${job.audio_format.value} (${describeSource(job.audio_format)})`,
401
+ `style: ${show(job.style.value)} (${describeSource(job.style)})`,
402
+ `avoid: ${String(count)} entr${count === 1 ? 'y' : 'ies'} (${describeSource(job.avoid)})`,
403
+ `structure: ${String(job.structure.value.length)} section(s) (${describeSource(job.structure)})`,
404
+ `takes: ${String(job.takes)} (brief)`,
405
+ ];
406
+ }
407
+
408
+ /**
409
+ * Reject a preset document that carries a non-portable key at any depth.
410
+ * Aggregates every offending dotted path so one run reports them all.
411
+ */
412
+ export function assertPresetPortable(document: unknown, path: string): void {
413
+ const violations: string[] = [];
414
+ const walk = (node: unknown, prefix: string): void => {
415
+ if (Array.isArray(node)) {
416
+ for (const [index, item] of node.entries()) {
417
+ walk(item, `${prefix}[${index}]`);
418
+ }
419
+ return;
420
+ }
421
+ if (node === null || typeof node !== 'object') {
422
+ return;
423
+ }
424
+ for (const [key, value] of Object.entries(node as Record<string, unknown>)) {
425
+ const dotted = prefix === '' ? key : `${prefix}.${key}`;
426
+ if (FORBIDDEN_PRESET_KEYS.includes(key)) {
427
+ violations.push(dotted);
428
+ }
429
+ walk(value, dotted);
430
+ }
431
+ };
432
+ walk(document, '');
433
+ if (violations.length > 0) {
434
+ throw new PresetContractViolation(path, violations);
435
+ }
436
+ }
437
+
438
+ /** Parse preset YAML and enforce portability; throws with the file path in the message. */
439
+ export function parsePresetDocument(text: string, path: string): Record<string, unknown> {
440
+ let parsed: unknown;
441
+ try {
442
+ parsed = Bun.YAML.parse(text);
443
+ } catch (error) {
444
+ throw new PresetContractViolation(path, [`unparseable YAML: ${String(error)}`]);
445
+ }
446
+ assertPresetPortable(parsed, path);
447
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
448
+ throw new PresetContractViolation(path, ['document must be a mapping']);
449
+ }
450
+ return parsed as Record<string, unknown>;
451
+ }
452
+
453
+ /**
454
+ * Read and check one preset file. Callers (0399's loader, 0401's CLI) catch
455
+ * {@link PresetContractViolation} and exit with its `exitCode`; the portability
456
+ * check is what turns a provider/model-id/price declaration into a non-zero exit.
457
+ */
458
+ export async function loadPresetFile(path: string): Promise<Record<string, unknown>> {
459
+ const text = await Bun.file(path).text();
460
+ return parsePresetDocument(text, path);
461
+ }
462
+
463
+ // ── 0399: preset data — formats, themes, provenance and the loader ───────────
464
+
465
+ /**
466
+ * Evidence status a preset may claim. `verified` is reserved for a preset a real
467
+ * generated take has been reviewed against; a freshly authored file may only say
468
+ * `authored` or `evidence-pending` (0399 R4).
469
+ */
470
+ export const PRESET_STATUSES = ['authored', 'evidence-pending', 'verified'] as const;
471
+ export type PresetStatus = (typeof PRESET_STATUSES)[number];
472
+
473
+ /** `YYYY-MM-DD`. A provenance date is an authored fact, not a clock reading. */
474
+ export const PROVENANCE_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
475
+
476
+ /**
477
+ * Clip is fixed at about 0:30 and ignores duration, so a clip skeleton that
478
+ * reaches past it sends the model text it cannot honour. The loader rejects it
479
+ * instead (0399 Design, "Clip formats skip structure timestamps past 0:30").
480
+ */
481
+ export const CLIP_STRUCTURE_CEILING_SECONDS = 30;
482
+
483
+ /** Provenance block every preset file must carry. */
484
+ export const PresetProvenanceSchema = z
485
+ .object({
486
+ /** Where the preset was authored from — a task, a design section, a reviewed take. */
487
+ authoring_source: z.string().min(1),
488
+ /** `YYYY-MM-DD` the file was authored. */
489
+ authored_at: z.string().regex(PROVENANCE_DATE_PATTERN, 'authored_at must be YYYY-MM-DD'),
490
+ /** Evidence status; `verified` requires a real generation review. */
491
+ status: z.enum(PRESET_STATUSES),
492
+ /** Free-text evidence note (a generation id, a review date) when one exists. */
493
+ evidence: z.string().min(1).optional(),
494
+ })
495
+ .strict();
496
+
497
+ export type PresetProvenance = z.infer<typeof PresetProvenanceSchema>;
498
+
499
+ /**
500
+ * R1 — `presets/formats/<name>.yaml`: the job intent, the model, the duration
501
+ * target and the structural skeleton. The format owns the arc; the theme owns
502
+ * the sound (0399 Design). No provider, API model id or price, ever.
503
+ */
504
+ export const MusicFormatPresetSchema = z
505
+ .object({
506
+ /** Must equal the file stem; the loader rejects a mismatch. */
507
+ name: z.string().min(1),
508
+ description: z.string().min(1),
509
+ /** One line the generated README index prints as the use case. */
510
+ intended_use: z.string().min(1),
511
+ /** The instance's own selector. `pro` needs a duration target; `clip` must not declare one. */
512
+ model: z.enum(MUSIC_MODELS),
513
+ /** Default duration target — required for `pro`, forbidden for `clip`. */
514
+ duration_target: z.string().regex(MMSS_PATTERN, 'duration_target must be m:ss').optional(),
515
+ /** `forbidden` resolves `instrumental: true` through 0397's precedence. */
516
+ lyrics_policy: z.enum(['allowed', 'forbidden']),
517
+ /** Timestamped skeleton, non-decreasing, inside the format's own ceiling. */
518
+ structure: z.array(StructureEntrySchema).min(1),
519
+ /** Optional default deny-list, merged additively like every other `avoid`. */
520
+ avoid: z.array(z.string().min(1)).optional(),
521
+ provenance: PresetProvenanceSchema,
522
+ })
523
+ .strict()
524
+ .superRefine((preset, ctx) => {
525
+ let ceiling = CLIP_STRUCTURE_CEILING_SECONDS;
526
+ if (preset.model === 'pro') {
527
+ ceiling = Number.POSITIVE_INFINITY;
528
+ if (preset.duration_target === undefined) {
529
+ ctx.addIssue({
530
+ code: 'custom',
531
+ path: ['duration_target'],
532
+ message:
533
+ 'a pro format must declare a duration_target — the instance would otherwise send "3:00" and the skeleton would describe a track nobody asked for',
534
+ });
535
+ }
536
+ } else if (preset.duration_target !== undefined) {
537
+ ctx.addIssue({
538
+ code: 'custom',
539
+ path: ['duration_target'],
540
+ message:
541
+ 'a clip format must not declare a duration_target — clip is fixed at about 0:30 and the instance ignores duration',
542
+ });
543
+ }
544
+ const duration = preset.duration_target;
545
+ if (duration !== undefined && MMSS_PATTERN.test(duration)) {
546
+ const seconds = durationSeconds(duration);
547
+ if (seconds < MIN_DURATION_SECONDS || seconds > MAX_DURATION_SECONDS) {
548
+ ctx.addIssue({
549
+ code: 'custom',
550
+ path: ['duration_target'],
551
+ message: `duration_target must be between 0:05 and 3:00 (got ${duration})`,
552
+ });
553
+ }
554
+ if (preset.model === 'pro') {
555
+ ceiling = seconds;
556
+ }
557
+ }
558
+ for (const [index, entry] of preset.structure.entries()) {
559
+ if (!MMSS_PATTERN.test(entry.at)) {
560
+ continue; // the field schema already reports a malformed timestamp
561
+ }
562
+ const at = durationSeconds(entry.at);
563
+ if (at > ceiling) {
564
+ ctx.addIssue({
565
+ code: 'custom',
566
+ path: ['structure', index, 'at'],
567
+ message:
568
+ preset.model === 'clip'
569
+ ? `structure at ${entry.at} exceeds the ~0:30 clip ceiling — clip cannot honour a longer skeleton`
570
+ : `structure at ${entry.at} exceeds the format duration_target ${String(duration)}`,
571
+ });
572
+ }
573
+ const previous = preset.structure[index - 1];
574
+ if (previous !== undefined && MMSS_PATTERN.test(previous.at) && at < durationSeconds(previous.at)) {
575
+ ctx.addIssue({
576
+ code: 'custom',
577
+ path: ['structure', index, 'at'],
578
+ message: `structure must not move backwards (${entry.at} follows ${previous.at})`,
579
+ });
580
+ }
581
+ }
582
+ });
583
+
584
+ export type MusicFormatPreset = z.infer<typeof MusicFormatPresetSchema>;
585
+
586
+ /**
587
+ * R2 — `presets/themes/<name>.yaml`: the technical direction prose the model
588
+ * actually reads, its default `avoid[]`, the vocal-character guidance and the
589
+ * instrumentation palette. A theme never dictates arrangement — that is the
590
+ * format's job — and it never claims a result it has not produced.
591
+ */
592
+ export const MusicThemePresetSchema = z
593
+ .object({
594
+ name: z.string().min(1),
595
+ description: z.string().min(1),
596
+ /** One line the generated README index prints as the use case. */
597
+ intended_use: z.string().min(1),
598
+ genre: z.string().min(1),
599
+ tempo: z.string().min(1),
600
+ key: z.string().min(1),
601
+ /** Instrumentation palette; every entry must appear in `style`. */
602
+ instrumentation: z.array(z.string().min(1)).min(1),
603
+ vocal_character: z.string().min(1),
604
+ production: z.string().min(1),
605
+ /** The technical-direction prompt segment (0397 `style`), authored prose. */
606
+ style: z.string().min(1),
607
+ /** Default deny-list, rendered as one `Avoid: …` segment by the renderer. */
608
+ avoid: z.array(z.string().min(1)).min(1),
609
+ provenance: PresetProvenanceSchema,
610
+ })
611
+ .strict();
612
+
613
+ export type MusicThemePreset = z.infer<typeof MusicThemePresetSchema>;
614
+
615
+ /**
616
+ * Facets the theme declares but its prose never says. `style` is the only
617
+ * control surface the model has — a facet that is not in the prose does not
618
+ * reach the model (Lyria has no tempo/key/instrumentation parameter), so the
619
+ * loader rejects the mismatch instead of shipping a direction it cannot honour.
620
+ */
621
+ export function themeDirectionGaps(theme: MusicThemePreset): string[] {
622
+ const prose = theme.style.toLowerCase();
623
+ const gaps: string[] = [];
624
+ const require = (label: string, value: string): void => {
625
+ if (!prose.includes(value.toLowerCase())) {
626
+ gaps.push(`${label} "${value}"`);
627
+ }
628
+ };
629
+ require('genre', theme.genre);
630
+ require('tempo', theme.tempo);
631
+ require('key', theme.key);
632
+ for (const [index, entry] of theme.instrumentation.entries()) {
633
+ require(`instrumentation[${String(index)}]`, entry);
634
+ }
635
+ require('vocal character', theme.vocal_character);
636
+ require('production', theme.production);
637
+ return gaps;
638
+ }
639
+
640
+ /** One rejected preset file, with the field the rule fired on. */
641
+ export interface MusicPresetProblem {
642
+ /** Path of the offending file. */
643
+ path: string;
644
+ /** Dotted field path inside the document, or the axis for a structural problem. */
645
+ field: string;
646
+ message: string;
647
+ }
648
+
649
+ /** Message every non-portable preset key reports, so one rule reads the same everywhere. */
650
+ const PORTABILITY_MESSAGE =
651
+ 'preset is not portable — a provider, API model id, base URL, credential or price is user config (0400), never preset data';
652
+
653
+ /**
654
+ * Raised when any preset file under the root is invalid. Every problem is
655
+ * reported at once and **nothing is returned**: a partially loaded preset set
656
+ * must never reach the renderer (0399 AC4).
657
+ */
658
+ export class PresetDataError extends Error {
659
+ /** CLI exit code the loader wrapper surfaces. */
660
+ readonly exitCode = 2;
661
+
662
+ /** Every rejected file, in load order. */
663
+ readonly problems: readonly MusicPresetProblem[];
664
+
665
+ constructor(problems: readonly MusicPresetProblem[]) {
666
+ super(problems.map((problem) => `${problem.path}: ${problem.field}: ${problem.message}`).join('\n'));
667
+ this.name = 'PresetDataError';
668
+ this.problems = problems;
669
+ }
670
+ }
671
+
672
+ /**
673
+ * Shipped preset root for the source layout: `plugins/generations/music-gen/presets`.
674
+ *
675
+ * A bundled `kk` puts this module inside `<pkg>/dist/index.js`, where the sibling directory does not
676
+ * exist — the packaged copy lives at `<pkg>/plugins/generations/music-gen/presets` instead (0413).
677
+ * {@link resolveMusicPresetRoot} picks the first candidate that exists; this constant stays the
678
+ * source-layout path and the last-resort value, so a genuinely missing corpus still fails with a
679
+ * recognisable path.
680
+ */
681
+ export const MUSIC_PRESET_ROOT = join(import.meta.dir, '..', 'presets');
682
+
683
+ /**
684
+ * Preset-root candidates for one anchor directory, nearest first: the plugin-local sibling layout
685
+ * (source and any unpacked plugin dir), then the package-root layout a bundle needs, checked at
686
+ * every ancestor because a bundle's `import.meta.dir` is `<pkg>/dist`.
687
+ */
688
+ export function musicPresetRootCandidates(from: string = import.meta.dir): string[] {
689
+ const candidates: string[] = [];
690
+ let dir = resolve(from);
691
+ for (;;) {
692
+ candidates.push(join(dir, '..', 'presets'));
693
+ candidates.push(join(dir, 'plugins', 'generations', 'music-gen', 'presets'));
694
+ const parent = resolve(dir, '..');
695
+ if (parent === dir) return candidates;
696
+ dir = parent;
697
+ }
698
+ }
699
+
700
+ /** The first candidate that exists, else the source-layout path (so the failure names a real shape). */
701
+ export async function resolveMusicPresetRoot(fs: FileSystem, from?: string): Promise<string> {
702
+ for (const candidate of musicPresetRootCandidates(from)) {
703
+ if (await fs.exists(candidate)) return candidate;
704
+ }
705
+ return MUSIC_PRESET_ROOT;
706
+ }
707
+
708
+ /** The shipped inventory: one map per axis, keyed by preset name. */
709
+ export interface LoadedMusicPresets {
710
+ /** Root the two axes were read from. */
711
+ root: string;
712
+ formats: Map<string, MusicFormatPreset>;
713
+ themes: Map<string, MusicThemePreset>;
714
+ }
715
+
716
+ export interface LoadMusicPresetsOptions {
717
+ /** Preset root override — tests and probes point it at a throwaway tree, never the shipped corpus. */
718
+ root?: string;
719
+ /** File-system seam override (text IO only). */
720
+ fileSystem?: FileSystem;
721
+ }
722
+
723
+ interface PresetFile {
724
+ path: string;
725
+ stem: string;
726
+ document: Record<string, unknown>;
727
+ }
728
+
729
+ /** Read one axis directory, aggregating every unreadable or non-portable file. */
730
+ async function readPresetFiles(
731
+ dir: string,
732
+ axis: 'formats' | 'themes',
733
+ fs: FileSystem,
734
+ problems: MusicPresetProblem[],
735
+ ): Promise<PresetFile[]> {
736
+ if (!(await fs.exists(dir))) {
737
+ problems.push({ path: dir, field: axis, message: 'preset directory is missing' });
738
+ return [];
739
+ }
740
+ const entries = (await fs.readDir(dir)).filter((entry) => entry.endsWith('.yaml')).sort();
741
+ if (entries.length === 0) {
742
+ problems.push({ path: dir, field: axis, message: 'no .yaml preset files found' });
743
+ return [];
744
+ }
745
+ const files: PresetFile[] = [];
746
+ for (const entry of entries) {
747
+ const path = join(dir, entry);
748
+ try {
749
+ files.push({
750
+ path,
751
+ stem: entry.replace(/\.yaml$/, ''),
752
+ document: parsePresetDocument(await fs.readFile(path), path),
753
+ });
754
+ } catch (error) {
755
+ if (error instanceof PresetContractViolation) {
756
+ for (const violation of error.violations) {
757
+ problems.push({ path, field: violation, message: PORTABILITY_MESSAGE });
758
+ }
759
+ } else {
760
+ problems.push({
761
+ path,
762
+ field: 'document',
763
+ message: error instanceof Error ? error.message : String(error),
764
+ });
765
+ }
766
+ }
767
+ }
768
+ return files;
769
+ }
770
+
771
+ /** Parse one axis into a name → preset map, reporting every schema or identity problem. */
772
+ function collectPresets<T extends { name: string }>(args: {
773
+ axis: 'formats' | 'themes';
774
+ files: readonly PresetFile[];
775
+ schema: z.ZodType<T>;
776
+ problems: MusicPresetProblem[];
777
+ inspect?: (preset: T, path: string) => void;
778
+ }): Map<string, T> {
779
+ const byName = new Map<string, T>();
780
+ const pathsByName = new Map<string, string>();
781
+ for (const file of args.files) {
782
+ const result = args.schema.safeParse(file.document);
783
+ if (!result.success) {
784
+ for (const issue of result.error.issues) {
785
+ const field = issue.path.map((part) => String(part)).join('.');
786
+ args.problems.push({
787
+ path: file.path,
788
+ field: field === '' ? args.axis : field,
789
+ message: issue.message,
790
+ });
791
+ }
792
+ continue;
793
+ }
794
+ const preset = result.data;
795
+ if (preset.name !== file.stem) {
796
+ args.problems.push({
797
+ path: file.path,
798
+ field: 'name',
799
+ message: `declares name "${preset.name}" but the file is ${file.stem}.yaml`,
800
+ });
801
+ continue;
802
+ }
803
+ const existing = pathsByName.get(preset.name);
804
+ if (existing !== undefined) {
805
+ args.problems.push({
806
+ path: file.path,
807
+ field: 'name',
808
+ message: `duplicate preset name "${preset.name}" (already declared by ${existing})`,
809
+ });
810
+ continue;
811
+ }
812
+ args.inspect?.(preset, file.path);
813
+ byName.set(preset.name, preset);
814
+ pathsByName.set(preset.name, file.path);
815
+ }
816
+ return byName;
817
+ }
818
+
819
+ /**
820
+ * Load `presets/formats/*.yaml` and `presets/themes/*.yaml`.
821
+ *
822
+ * Fail closed (0399 R4): portability, the schema, the name/file-stem identity,
823
+ * the per-format duration and structure ceilings and the theme's prose coverage
824
+ * are all enforced here, and one problem anywhere throws
825
+ * {@link PresetDataError} with every problem listed — no partial set escapes.
826
+ */
827
+ export async function loadMusicPresets(options: LoadMusicPresetsOptions = {}): Promise<LoadedMusicPresets> {
828
+ const fs = options.fileSystem ?? createNodeFileSystem();
829
+ const root = options.root ?? (await resolveMusicPresetRoot(fs));
830
+ const problems: MusicPresetProblem[] = [];
831
+ const formatFiles = await readPresetFiles(join(root, 'formats'), 'formats', fs, problems);
832
+ const themeFiles = await readPresetFiles(join(root, 'themes'), 'themes', fs, problems);
833
+ const formats = collectPresets({
834
+ axis: 'formats',
835
+ files: formatFiles,
836
+ schema: MusicFormatPresetSchema,
837
+ problems,
838
+ });
839
+ const themes = collectPresets({
840
+ axis: 'themes',
841
+ files: themeFiles,
842
+ schema: MusicThemePresetSchema,
843
+ problems,
844
+ inspect: (preset, path) => {
845
+ for (const gap of themeDirectionGaps(preset)) {
846
+ problems.push({
847
+ path,
848
+ field: 'style',
849
+ message: `technical direction never states ${gap} — the prose is the only control surface the model has`,
850
+ });
851
+ }
852
+ },
853
+ });
854
+ if (problems.length > 0) {
855
+ throw new PresetDataError(problems);
856
+ }
857
+ return { root, formats, themes };
858
+ }
859
+
860
+ /** The resolution layer a format preset contributes (0397 precedence: format is the lowest preset layer). */
861
+ export function presetLayerForFormat(preset: MusicFormatPreset): PresetLayer {
862
+ return {
863
+ name: preset.name,
864
+ model: preset.model,
865
+ duration_target: preset.duration_target,
866
+ lyrics_policy: preset.lyrics_policy,
867
+ structure: preset.structure,
868
+ avoid: preset.avoid,
869
+ };
870
+ }
871
+
872
+ /** The resolution layer a theme preset contributes: style prose plus its default deny-list. */
873
+ export function presetLayerForTheme(preset: MusicThemePreset): PresetLayer {
874
+ return { name: preset.name, style: preset.style, avoid: [...preset.avoid] };
875
+ }
876
+
877
+ /**
878
+ * Raised when a brief names a format or theme the preset root does not ship.
879
+ * Never a silent fallback: the message lists the valid names and the resolution
880
+ * trace shows which source supplied every other field.
881
+ */
882
+ export class UnknownPresetError extends Error {
883
+ /** CLI exit code the caller must surface. */
884
+ readonly exitCode = 1;
885
+
886
+ /** Which axis the unknown name belongs to. */
887
+ readonly axis: 'format' | 'theme';
888
+
889
+ /** The name the brief asked for. */
890
+ readonly requested: string;
891
+
892
+ /** Every name that axis does ship, sorted. */
893
+ readonly validNames: readonly string[];
894
+
895
+ /** `explainJob` lines from the resolution with the layers that did exist. */
896
+ readonly trace: readonly string[];
897
+
898
+ constructor(axis: 'format' | 'theme', requested: string, validNames: readonly string[], trace: readonly string[]) {
899
+ const listed = validNames.length === 0 ? '(none shipped)' : validNames.join(', ');
900
+ super(`unknown ${axis} preset "${requested}"; valid ${axis} presets: ${listed}`);
901
+ this.name = 'UnknownPresetError';
902
+ this.axis = axis;
903
+ this.requested = requested;
904
+ this.validNames = validNames;
905
+ this.trace = trace;
906
+ }
907
+
908
+ /** The message plus the source trace, one line each — what the CLI prints to stderr. */
909
+ get report(): string {
910
+ return [this.message, ...this.trace.map((line) => ` ${line}`)].join('\n');
911
+ }
912
+ }
913
+
914
+ export interface NamedPresetOptions {
915
+ /** Highest preset layer, as 0400/0401 pass it (0397 precedence: brief > workflow > theme > format). */
916
+ workflow?: PresetLayer;
917
+ }
918
+
919
+ /**
920
+ * Resolve a brief through the presets it names (0399 R3), reusing 0397's
921
+ * `resolveJob` — the precedence itself is unchanged; this only turns two names
922
+ * into two layers and fails loudly when a name does not exist.
923
+ */
924
+ export function resolveNamedJob(
925
+ brief: MusicBrief,
926
+ presets: LoadedMusicPresets,
927
+ options: NamedPresetOptions = {},
928
+ ): ResolvedJob {
929
+ const format = presets.formats.get(brief.format);
930
+ const theme = presets.themes.get(brief.theme);
931
+ const layers: PresetLayers = {
932
+ ...(options.workflow === undefined ? {} : { workflow: options.workflow }),
933
+ ...(theme === undefined ? {} : { theme: presetLayerForTheme(theme) }),
934
+ ...(format === undefined ? {} : { format: presetLayerForFormat(format) }),
935
+ };
936
+ if (format !== undefined && theme !== undefined) {
937
+ return resolveJob(brief, layers);
938
+ }
939
+ // Report the trace the known layers already produce, so the operator sees which
940
+ // source decides every other field while the unknown name is fixed.
941
+ let trace: string[];
942
+ try {
943
+ trace = explainJob(resolveJob(brief, layers));
944
+ } catch (error) {
945
+ trace = [`resolution with the known layers failed: ${error instanceof Error ? error.message : String(error)}`];
946
+ }
947
+ if (format === undefined) {
948
+ throw new UnknownPresetError('format', brief.format, [...presets.formats.keys()].sort(), trace);
949
+ }
950
+ throw new UnknownPresetError('theme', brief.theme, [...presets.themes.keys()].sort(), trace);
951
+ }