@gobing-ai/knowledge-kit 0.1.20 → 0.1.22

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 (115) 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 +13893 -8995
  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/music-gen/README.md +277 -0
  13. package/plugins/generations/music-gen/dist/index.js +23544 -0
  14. package/plugins/generations/music-gen/package.json +24 -0
  15. package/plugins/generations/music-gen/plugin.json +23 -0
  16. package/plugins/generations/music-gen/presets/SOURCE.md +39 -0
  17. package/plugins/generations/music-gen/presets/formats/clip.yaml +21 -0
  18. package/plugins/generations/music-gen/presets/formats/jingle.yaml +22 -0
  19. package/plugins/generations/music-gen/presets/formats/loop.yaml +21 -0
  20. package/plugins/generations/music-gen/presets/formats/song.yaml +31 -0
  21. package/plugins/generations/music-gen/presets/formats/underscore.yaml +22 -0
  22. package/plugins/generations/music-gen/presets/themes/ambient-tech.yaml +30 -0
  23. package/plugins/generations/music-gen/presets/themes/cinematic.yaml +30 -0
  24. package/plugins/generations/music-gen/presets/themes/lofi.yaml +30 -0
  25. package/plugins/generations/music-gen/presets/themes/synthwave.yaml +30 -0
  26. package/plugins/generations/music-gen/scripts/gen-preset-index.ts +181 -0
  27. package/plugins/generations/music-gen/scripts/resolve-preset.ts +64 -0
  28. package/plugins/generations/music-gen/src/adapter/index.ts +35 -0
  29. package/plugins/generations/music-gen/src/adapter/instance.ts +904 -0
  30. package/plugins/generations/music-gen/src/adapter/offline.ts +124 -0
  31. package/plugins/generations/music-gen/src/artifact.ts +223 -0
  32. package/plugins/generations/music-gen/src/audio/checks.ts +618 -0
  33. package/plugins/generations/music-gen/src/audio/master.ts +267 -0
  34. package/plugins/generations/music-gen/src/audio/measure.ts +507 -0
  35. package/plugins/generations/music-gen/src/audio/profile.ts +131 -0
  36. package/plugins/generations/music-gen/src/audio.ts +122 -0
  37. package/plugins/generations/music-gen/src/brief.ts +191 -0
  38. package/plugins/generations/music-gen/src/config.ts +451 -0
  39. package/plugins/generations/music-gen/src/content.ts +199 -0
  40. package/plugins/generations/music-gen/src/digest.ts +100 -0
  41. package/plugins/generations/music-gen/src/index.ts +147 -0
  42. package/plugins/generations/music-gen/src/job.ts +131 -0
  43. package/plugins/generations/music-gen/src/plugin.ts +371 -0
  44. package/plugins/generations/music-gen/src/presets.ts +918 -0
  45. package/plugins/generations/music-gen/src/render.ts +87 -0
  46. package/plugins/generations/music-gen/src/request.ts +102 -0
  47. package/plugins/generations/music-gen/src/spend.ts +495 -0
  48. package/plugins/generations/music-gen/tsconfig.json +8 -0
  49. package/plugins/kk/plugin.json +1 -1
  50. package/plugins/kk/schedules/kk-serve.launchd.plist.tmpl +2 -1
  51. package/plugins/kk/scripts/cover-compositor.ts +380 -32
  52. package/plugins/kk/scripts/daily-cover-mock.ts +40 -3
  53. package/plugins/kk/scripts/daily-stages.ts +659 -20
  54. package/plugins/kk/scripts/episode-identity.ts +180 -0
  55. package/plugins/kk/scripts/kk-workflow-stages.ts +37 -1
  56. package/plugins/kk/scripts/music-stages.ts +624 -0
  57. package/plugins/kk/scripts/news-editorial-ledger.ts +906 -0
  58. package/plugins/kk/scripts/source-citation.ts +187 -0
  59. package/plugins/kk/scripts/topic-selection-attempts.ts +446 -0
  60. package/plugins/kk/scripts/topic-selection-calibration.ts +161 -0
  61. package/plugins/kk/skills/content-judge/SKILL.md +11 -6
  62. package/plugins/kk/skills/content-judge/references/music-quality-rubric.md +147 -0
  63. package/plugins/kk/skills/content-judge/references/rubrics.md +15 -0
  64. package/plugins/kk/skills/content-safety/SKILL.md +12 -0
  65. package/plugins/kk/skills/music-authoring/SKILL.md +276 -0
  66. package/plugins/kk/skills/music-authoring/references/judge-input.md +117 -0
  67. package/plugins/kk/skills/news-editorial/SKILL.md +102 -15
  68. package/plugins/kk/skills/news-editorial/references/selection.md +4 -0
  69. package/plugins/kk/skills/news-editorial/references/style-contract.zh.md +58 -11
  70. package/plugins/kk/workflows/kk-daily-ai-voice.yaml +8 -8
  71. package/plugins/kk/workflows/kk-daily-ai-voice2.yaml +7 -7
  72. package/plugins/kk/workflows/kk-music.yaml +328 -0
  73. package/plugins/kk/workflows/kk-news-generate.yaml +58 -3
  74. package/plugins/publishings/bilibili-pub/dist/index.js +11 -1
  75. package/plugins/publishings/bilibili-pub/dist/profile-check.js +11 -1
  76. package/plugins/publishings/cnblogs-pub/dist/index.js +11 -1
  77. package/plugins/publishings/cnblogs-pub/dist/profile-check.js +11 -1
  78. package/plugins/publishings/csdn-pub/dist/index.js +11 -1
  79. package/plugins/publishings/csdn-pub/dist/profile-check.js +11 -1
  80. package/plugins/publishings/infoq-pub/dist/index.js +11 -1
  81. package/plugins/publishings/infoq-pub/dist/profile-check.js +11 -1
  82. package/plugins/publishings/jike-pub/dist/index.js +11 -1
  83. package/plugins/publishings/jike-pub/dist/profile-check.js +11 -1
  84. package/plugins/publishings/juejin-pub/dist/index.js +11 -1
  85. package/plugins/publishings/juejin-pub/dist/profile-check.js +11 -1
  86. package/plugins/publishings/linkedin-pub/dist/index.js +11 -1
  87. package/plugins/publishings/linkedin-pub/dist/profile-check.js +11 -1
  88. package/plugins/publishings/podcast-pub/dist/index.js +586 -20
  89. package/plugins/publishings/podcast-pub/src/corrections.ts +509 -0
  90. package/plugins/publishings/podcast-pub/src/index.ts +257 -5
  91. package/plugins/publishings/podcast-pub/src/show-notes-brief.ts +240 -0
  92. package/plugins/publishings/podcast-pub/src/show-notes.ts +69 -13
  93. package/plugins/publishings/shipinhao-pub/dist/index.js +59 -8
  94. package/plugins/publishings/shipinhao-pub/dist/profile-check.js +11 -1
  95. package/plugins/publishings/shipinhao-pub/src/audio-flow.ts +105 -6
  96. package/plugins/publishings/sspai-pub/dist/index.js +11 -1
  97. package/plugins/publishings/sspai-pub/dist/profile-check.js +11 -1
  98. package/plugins/publishings/substack-pub/dist/index.js +11 -1
  99. package/plugins/publishings/substack-pub/dist/profile-check.js +11 -1
  100. package/plugins/publishings/surfdash-pub/dist/index.js +72 -20
  101. package/plugins/publishings/surfdash-pub/src/digest-check.ts +7 -3
  102. package/plugins/publishings/surfdash-pub/src/index.ts +100 -17
  103. package/plugins/publishings/surfdash-pub/src/topic-claims.ts +3 -1
  104. package/plugins/publishings/threads-pub/dist/index.js +11 -1
  105. package/plugins/publishings/threads-pub/dist/profile-check.js +11 -1
  106. package/plugins/publishings/wechatmp-pub/dist/index.js +11 -1
  107. package/plugins/publishings/wechatmp-pub/dist/profile-check.js +11 -1
  108. package/plugins/publishings/weibo-pub/dist/index.js +11 -1
  109. package/plugins/publishings/weibo-pub/dist/profile-check.js +11 -1
  110. package/plugins/publishings/x-pub/dist/index.js +11 -1
  111. package/plugins/publishings/x-pub/dist/profile-check.js +11 -1
  112. package/plugins/publishings/xhs-pub/dist/index.js +11 -1
  113. package/plugins/publishings/xhs-pub/dist/profile-check.js +11 -1
  114. package/plugins/publishings/xiaoyuzhou-pub/dist/index.js +11 -1
  115. package/plugins/publishings/xiaoyuzhou-pub/dist/profile-check.js +11 -1
@@ -3,6 +3,7 @@ import { parseArgs } from 'node:util';
3
3
  import { type Content, ContentSchema, type Doc, DocListSchema } from '@gobing-ai/kk-core';
4
4
  import { createNodeFileSystem, type FileSystem } from '@gobing-ai/ts-runtime';
5
5
  import { echoError } from '@gobing-ai/ts-utils';
6
+ import { analyzeEditorialClaims, type EditorialFinding } from './editorial-claims';
6
7
  import { buildNewsVoiceScript, formatVoiceScriptToYaml, type ScriptBuilderOptions } from './script-builder';
7
8
  import {
8
9
  parseStyleContract,
@@ -12,6 +13,7 @@ import {
12
13
  validateScriptPlan,
13
14
  } from './script-plan';
14
15
 
16
+ export * from './editorial-claims';
15
17
  export * from './script-builder';
16
18
  export * from './script-plan';
17
19
 
@@ -25,6 +27,8 @@ interface ScriptPlanOutcome {
25
27
  scriptPlan?: ScriptPlan;
26
28
  scriptSource: 'plan' | 'template';
27
29
  scriptPlanErrors: ScriptPlanError[];
30
+ /** 0385 AC R2/R3 advisory findings — reported, never a rejection (see `editorial-claims.ts`). */
31
+ scriptPlanAdvisories: EditorialFinding[];
28
32
  }
29
33
 
30
34
  /**
@@ -37,12 +41,12 @@ interface ScriptPlanOutcome {
37
41
  async function resolveScriptPlan(fs: FileSystem, docs: Doc[]): Promise<ScriptPlanOutcome> {
38
42
  const planPath = process.env.DAILYNEWS_SCRIPT_PLAN;
39
43
  if (!planPath) {
40
- return { scriptSource: 'template', scriptPlanErrors: [] };
44
+ return { scriptSource: 'template', scriptPlanErrors: [], scriptPlanAdvisories: [] };
41
45
  }
42
46
  const fallback = (errors: ScriptPlanError[]): ScriptPlanOutcome => {
43
47
  const reason = errors.map((error) => `${error.itemId}:${error.rule}`).join(', ');
44
48
  echoError(`dailynews-gen: script plan rejected, falling back to templates (${reason})`);
45
- return { scriptSource: 'template', scriptPlanErrors: errors };
49
+ return { scriptSource: 'template', scriptPlanErrors: errors, scriptPlanAdvisories: [] };
46
50
  };
47
51
  if (!(await fs.exists(planPath))) {
48
52
  return fallback([{ itemId: 'episode', rule: 'missing-plan' }]);
@@ -85,7 +89,17 @@ async function resolveScriptPlan(fs: FileSystem, docs: Doc[]): Promise<ScriptPla
85
89
  if (!validated.ok) {
86
90
  return fallback(validated.errors);
87
91
  }
88
- return { scriptPlan: validated.plan, scriptSource: 'plan', scriptPlanErrors: [] };
92
+ // 0385 AC R2/R3: the editorial findings ride alongside an ACCEPTED plan. They are stamped, not
93
+ // turned into rejections — a plan that validates today must keep validating.
94
+ const advisories = analyzeEditorialClaims(validated.plan);
95
+ if (advisories.length > 0) {
96
+ echoError(
97
+ `dailynews-gen: script plan accepted with ${advisories.length} advisory finding(s) (${advisories
98
+ .map((finding) => `${finding.itemId}:${finding.code}`)
99
+ .join(', ')})`,
100
+ );
101
+ }
102
+ return { scriptPlan: validated.plan, scriptSource: 'plan', scriptPlanErrors: [], scriptPlanAdvisories: advisories };
89
103
  }
90
104
 
91
105
  /**
@@ -148,7 +162,11 @@ export async function processGeneratorIO(
148
162
  const isZh = (options?.language || 'zh').toLowerCase() === 'zh';
149
163
  const planOutcome = isZh
150
164
  ? await resolveScriptPlan(fs, docs)
151
- : { scriptSource: 'template' as const, scriptPlanErrors: [] as ScriptPlanError[] };
165
+ : {
166
+ scriptSource: 'template' as const,
167
+ scriptPlanErrors: [] as ScriptPlanError[],
168
+ scriptPlanAdvisories: [] as EditorialFinding[],
169
+ };
152
170
  // Topic boundary (task 0189): docs the plan declares excluded are not spoken, not counted,
153
171
  // and not referenced — title, storyCount, and references must match what is actually said.
154
172
  const excludedIds = new Set(planOutcome.scriptPlan?.excluded?.map((ex) => ex.id) ?? []);
@@ -183,6 +201,7 @@ export async function processGeneratorIO(
183
201
  })),
184
202
  scriptSource: planOutcome.scriptSource,
185
203
  scriptPlanErrors: planOutcome.scriptPlanErrors,
204
+ scriptPlanAdvisories: planOutcome.scriptPlanAdvisories,
186
205
  },
187
206
  };
188
207
 
@@ -428,9 +428,16 @@ export function buildNewsVoiceScript(docs: Doc[], options?: ScriptBuilderOptions
428
428
 
429
429
  const normalizedLead = normalizeBroadcastText(lead, isZh);
430
430
  const normalizedBody = cleanBody === '' ? '' : normalizeBroadcastText(cleanBody, isZh);
431
- // F613: the plan insight is grounded in this item and always spoken; the keyword-bucket
432
- // synthesizer (and its uniqueness set) only runs on the template path.
433
- const insight = planItem?.insight ?? synthesizePersonalUnderstanding(cleanTitle, cleanBody, isZh, usedInsights);
431
+ // F613: the plan insight is spoken when it carries comment; 0385 R3 makes it optional, so a
432
+ // plan item with a blank insight speaks the item's facts and no comment sentence (never a
433
+ // bare 「。」 segment), and the keyword-bucket synthesizer only runs on the template path.
434
+ const plannedInsight = planItem?.insight?.trim() ?? '';
435
+ const insight =
436
+ planItem !== undefined
437
+ ? plannedInsight === ''
438
+ ? null
439
+ : plannedInsight
440
+ : synthesizePersonalUnderstanding(cleanTitle, cleanBody, isZh, usedInsights);
434
441
  const normalizedInsight = insight === null ? null : normalizeBroadcastText(insight, isZh);
435
442
 
436
443
  const factText = isZh ? `${normalizedLead}${normalizedBody}` : `${normalizedLead} ${normalizedBody}`;
@@ -23,11 +23,33 @@ export interface ScriptPlanSocial {
23
23
  long: string;
24
24
  }
25
25
 
26
+ /**
27
+ * The cover slot has two legal forms (0347 R4, widened by 0385 R4):
28
+ * - a plain string = the English visual scene (the pre-0347 shape), unchanged;
29
+ * - an object = `{ scene?, headline, sourceIds? }`, where `headline` is the Chinese 当日要点 the
30
+ * episode identity freezes (0385 R4) and `sourceIds` names the plan items the point rests on,
31
+ * so admission dropping them can withhold the point instead of publishing it unsupported.
32
+ */
33
+ export interface ScriptPlanCoverObject {
34
+ /** English visual scene for image generation (≤ `caps.cover`); optional so a point-only cover validates. */
35
+ scene?: string;
36
+ /** The frozen 当日要点 — the one point the title and the cover share (≤ `caps.coverHeadline`). */
37
+ headline: string;
38
+ /** Plan item ids the headline rests on; withheld when admission drops every one of them. */
39
+ sourceIds?: string[];
40
+ }
41
+
42
+ export type ScriptPlanCover = string | ScriptPlanCoverObject;
43
+
26
44
  export interface ScriptPlan {
27
45
  version: 1;
28
46
  intro: string;
29
47
  outro: string;
30
- items: { id: string; lead: string; insight: string; card?: ScriptPlanItemCard }[];
48
+ /**
49
+ * `insight` is optional (0385 R3): a comment-free item is legal, and an empty string means the
50
+ * same thing as omission — the builder skips the insight sentence, never the item.
51
+ */
52
+ items: { id: string; lead: string; insight?: string; card?: ScriptPlanItemCard }[];
31
53
  /**
32
54
  * Docs deliberately not spoken (topic-boundary exclusions, task 0189). An id here is
33
55
  * exempt from `missing-item`; listing an id in both `items` and `excluded` is a
@@ -35,7 +57,7 @@ export interface ScriptPlan {
35
57
  */
36
58
  excluded?: { id: string; reason: string }[];
37
59
  /** Optional master-artifact fields rendered deterministically by `daily-editorial-render` (0345 R10). */
38
- cover?: string;
60
+ cover?: ScriptPlanCover;
39
61
  cards?: ScriptPlanCards;
40
62
  social?: ScriptPlanSocial;
41
63
  }
@@ -51,6 +73,7 @@ export interface StyleContract {
51
73
  lead: number;
52
74
  insight: number;
53
75
  cover?: number;
76
+ coverHeadline?: number;
54
77
  cardCopy?: number;
55
78
  cardTitle?: number;
56
79
  socialShort?: number;
@@ -74,16 +97,29 @@ const ScriptPlanItemCardSchema = z.object({
74
97
  });
75
98
 
76
99
  /**
77
- * Empty spoken text is a shape error (`schema`), not a cap/banned case: an empty intro or insight
78
- * would normalize to a bare 「。」 segment, which no valid episode contains.
100
+ * `insight` is optional (0385 R3): the contract lets an item carry no comment, so omitting it — or
101
+ * sending `""` — must validate. A blank insight is skipped by the builder (no bare 「。」 segment)
102
+ * and by the editorial render (the item still renders, only the comment sentence is dropped).
79
103
  */
80
104
  const ScriptPlanItemSchema = z.object({
81
105
  id: z.string().min(1),
82
106
  lead: z.string().min(1),
83
- insight: z.string().min(1),
107
+ insight: z.string().optional(),
84
108
  card: ScriptPlanItemCardSchema.optional(),
85
109
  });
86
110
 
111
+ /**
112
+ * 0385 R4: the object form is what carries the episode's 当日要点, so the schema has to accept it —
113
+ * a string-only cover made the canonical `第<issue>期 · <headline>` title unreachable.
114
+ */
115
+ const ScriptPlanCoverObjectSchema = z.object({
116
+ scene: z.string().min(1).optional(),
117
+ headline: z.string().min(1),
118
+ sourceIds: z.array(z.string().min(1)).optional(),
119
+ });
120
+
121
+ const ScriptPlanCoverSchema = z.union([z.string().min(1), ScriptPlanCoverObjectSchema]);
122
+
87
123
  const ScriptPlanExclusionSchema = z.object({
88
124
  id: z.string().min(1),
89
125
  reason: z.string().min(1),
@@ -105,7 +141,7 @@ const ScriptPlanSchema = z.object({
105
141
  outro: z.string().min(1),
106
142
  items: z.array(ScriptPlanItemSchema),
107
143
  excluded: z.array(ScriptPlanExclusionSchema).optional(),
108
- cover: z.string().min(1).optional(),
144
+ cover: ScriptPlanCoverSchema.optional(),
109
145
  cards: ScriptPlanCardsSchema.optional(),
110
146
  social: ScriptPlanSocialSchema.optional(),
111
147
  });
@@ -117,6 +153,7 @@ const StyleContractSchema = z.object({
117
153
  lead: z.number().int().positive(),
118
154
  insight: z.number().int().positive(),
119
155
  cover: z.number().int().positive().optional(),
156
+ coverHeadline: z.number().int().positive().optional(),
120
157
  cardCopy: z.number().int().positive().optional(),
121
158
  cardTitle: z.number().int().positive().optional(),
122
159
  socialShort: z.number().int().positive().optional(),
@@ -217,8 +254,17 @@ export function validateScriptPlan(
217
254
 
218
255
  if (valid.intro.length > style.caps.intro) errors.push({ itemId: 'episode', rule: 'cap:intro' });
219
256
  if (valid.outro.length > style.caps.outro) errors.push({ itemId: 'episode', rule: 'cap:outro' });
220
- if (valid.cover !== undefined && valid.cover.length > (style.caps.cover ?? 240)) {
221
- errors.push({ itemId: 'episode', rule: 'cap:cover' });
257
+ // 0385 R4: both cover forms are capped. The string form is one scene (the pre-0347 shape); the
258
+ // object form caps its scene at the same place and its 当日要点 at the (much tighter) headline cap.
259
+ if (typeof valid.cover === 'string') {
260
+ if (valid.cover.length > (style.caps.cover ?? 240)) errors.push({ itemId: 'episode', rule: 'cap:cover' });
261
+ } else if (valid.cover !== undefined) {
262
+ if (valid.cover.scene !== undefined && valid.cover.scene.length > (style.caps.cover ?? 240)) {
263
+ errors.push({ itemId: 'episode', rule: 'cap:cover' });
264
+ }
265
+ if (valid.cover.headline.length > (style.caps.coverHeadline ?? 25)) {
266
+ errors.push({ itemId: 'episode', rule: 'cap:coverHeadline' });
267
+ }
222
268
  }
223
269
  if (valid.cards !== undefined && valid.cards.title.length > (style.caps.cardTitle ?? 20)) {
224
270
  errors.push({ itemId: 'episode', rule: 'cap:cardTitle' });
@@ -233,7 +279,10 @@ export function validateScriptPlan(
233
279
  }
234
280
  for (const item of valid.items) {
235
281
  if (item.lead.length > style.caps.lead) errors.push({ itemId: item.id, rule: 'cap:lead' });
236
- if (item.insight.length > style.caps.insight) errors.push({ itemId: item.id, rule: 'cap:insight' });
282
+ // 0385 R3: an omitted/blank insight is legal (the item still renders), so it has no cap,
283
+ // no banned-phrase and no duplicate rule to break.
284
+ const insight = item.insight?.trim() ?? '';
285
+ if (insight.length > style.caps.insight) errors.push({ itemId: item.id, rule: 'cap:insight' });
237
286
  if (item.card !== undefined && item.card.copy.length > (style.caps.cardCopy ?? 12)) {
238
287
  errors.push({ itemId: item.id, rule: 'cap:cardCopy' });
239
288
  }
@@ -241,7 +290,8 @@ export function validateScriptPlan(
241
290
  // unknown-id is already reported above; skip the redundancy check rather than double-report.
242
291
  if (
243
292
  doc !== undefined &&
244
- redundantInsightClauses(item.insight, `${item.lead}${doc.body}`) >= REDUNDANT_INSIGHT_CLAUSE_LIMIT
293
+ insight !== '' &&
294
+ redundantInsightClauses(insight, `${item.lead}${doc.body}`) >= REDUNDANT_INSIGHT_CLAUSE_LIMIT
245
295
  ) {
246
296
  errors.push({ itemId: item.id, rule: 'redundant-insight' });
247
297
  }
@@ -250,7 +300,14 @@ export function validateScriptPlan(
250
300
  const fields: { itemId: string; text: string }[] = [
251
301
  { itemId: 'episode', text: valid.intro },
252
302
  { itemId: 'episode', text: valid.outro },
253
- ...(valid.cover !== undefined ? [{ itemId: 'episode', text: valid.cover }] : []),
303
+ ...(typeof valid.cover === 'string'
304
+ ? [{ itemId: 'episode', text: valid.cover }]
305
+ : valid.cover !== undefined
306
+ ? [
307
+ { itemId: 'episode', text: valid.cover.headline },
308
+ ...(valid.cover.scene !== undefined ? [{ itemId: 'episode', text: valid.cover.scene }] : []),
309
+ ]
310
+ : []),
254
311
  ...(valid.cards !== undefined
255
312
  ? [
256
313
  { itemId: 'episode', text: valid.cards.title },
@@ -265,7 +322,7 @@ export function validateScriptPlan(
265
322
  : []),
266
323
  ...valid.items.flatMap((item) => [
267
324
  { itemId: item.id, text: item.lead },
268
- { itemId: item.id, text: item.insight },
325
+ ...((item.insight?.trim() ?? '') !== '' ? [{ itemId: item.id, text: item.insight as string }] : []),
269
326
  ...(item.card !== undefined
270
327
  ? [
271
328
  { itemId: item.id, text: item.card.copy },
@@ -280,10 +337,13 @@ export function validateScriptPlan(
280
337
  }
281
338
  }
282
339
 
340
+ // Two comment-free items are not "the same insight" — only real comment text can collide.
283
341
  const seenInsights = new Set<string>();
284
342
  for (const item of valid.items) {
285
- if (seenInsights.has(item.insight)) errors.push({ itemId: item.id, rule: 'duplicate-insight' });
286
- else seenInsights.add(item.insight);
343
+ const insight = item.insight?.trim() ?? '';
344
+ if (insight === '') continue;
345
+ if (seenInsights.has(insight)) errors.push({ itemId: item.id, rule: 'duplicate-insight' });
346
+ else seenInsights.add(insight);
287
347
  }
288
348
 
289
349
  return errors.length > 0 ? { ok: false, errors } : { ok: true, plan: valid };
@@ -0,0 +1,277 @@
1
+ # music-gen
2
+
3
+ Music generation over the homelab Lyria 3 instance (`POST /api/lyria/generate`), as a
4
+ `kind: generator` plugin.
5
+
6
+ **Status: the plugin ships (task 0398).** The 0397 contract — the `MusicBrief` Zod schema, the
7
+ deterministic prompt renderer, the instance request mapping, preset resolution and the canonical
8
+ digest input — plus the plugin itself: `plugin.json`, the live instance adapter with the
9
+ non-idempotent paid-call policy, the cache-first analyse, the offline adapter
10
+ (`KK_MUSIC_DRY_RUN=1`), the artifact + take sidecar and the `Content` mapping. The format × theme
11
+ presets ship in 0399 (`presets/`, indexed below by a generator). The spend guard lands in 0400, the
12
+ `kk music` noun in 0401, the workflow in 0403 and measurement in 0405.
13
+
14
+ Contract authority: [`docs/design/music-gen.md`](../../../docs/design/music-gen.md). That document
15
+ owns the wire contract, the render order, preset precedence, the adapter contract, the paid-call
16
+ failure table, the environment variables and the artifact record. This README owns the **authoring
17
+ form** — the YAML a person writes — the preset index and how to run the plugin.
18
+
19
+ ```text
20
+ plugins/generations/music-gen/
21
+ plugin.json # kind: generator, entry ./src/index.ts, runtime.requires
22
+ src/brief.ts # MusicBrief schema + m:ss helpers + the field→target table
23
+ src/render.ts # kk-owned PROMPT text, frozen segment order
24
+ src/request.ts # POST /api/lyria/generate body, no instance defaults
25
+ src/presets.ts # brief > workflow > theme > format > built-in, portability guard
26
+ src/digest.ts # canonical digest input for 0400 dedupe / 0398 provenance
27
+ src/job.ts # the --in envelope: brief from docs[0].body, knobs from metadata
28
+ src/config.ts # music.instance.* / music.prices.* + KK_MUSIC_* overrides
29
+ src/adapter/instance.ts # the live HTTP adapter and the paid-call policy
30
+ src/adapter/offline.ts # KK_MUSIC_DRY_RUN=1: silent WAV, synthetic manifest, zero network
31
+ src/adapter/index.ts # adapter selection (dry run → offline)
32
+ src/audio.ts # delivered-container detection + the deterministic silent WAV
33
+ src/artifact.ts # <slug>-<model>-<instanceId>.<ext> naming + the take sidecar
34
+ src/content.ts # Content mapping: format audio, liner notes, references, echoes
35
+ src/plugin.ts # the take loop: read → generate → persist → map
36
+ src/index.ts # the published contract surface + the plugin entry
37
+ presets/formats/*.yaml # 0399: job intent, model, duration target, section skeleton, lyrics policy
38
+ presets/themes/*.yaml # 0399: technical direction prose, avoid[], instrumentation palette
39
+ presets/SOURCE.md # 0399: provenance + evidence-promotion rules
40
+ scripts/gen-preset-index.ts # 0399: README index generator (--check fails on drift)
41
+ scripts/resolve-preset.ts # 0399: resolve a brief through the presets and print the trace
42
+ tests/ # bun:test; fixtures/<name>/{brief.yaml,prompt.txt,request.json}
43
+ ```
44
+
45
+ Nothing outside `src/adapter/` opens a socket, and nothing in the plugin (or its tests) ever makes a
46
+ paid call: the adapter takes an injected `fetch` seam and every test supplies its own.
47
+
48
+ ## 1. Authoring a brief
49
+
50
+ The brief is the only input document. `src/brief.ts` is the only schema — this file is the authoring
51
+ form, not a second definition. Unknown keys are rejected, so a typo fails at parse time instead of
52
+ being silently dropped.
53
+
54
+ ```yaml
55
+ # midnight-cable-car.yaml
56
+ title: Midnight Cable Car # required — the instance's library title (request: title)
57
+ format: song # required — format preset name (resolution input)
58
+ theme: synthwave # required — theme preset name (resolution input)
59
+ model: pro # optional — pro | clip (default: format preset, then pro)
60
+ duration_target: "0:30" # optional — m:ss, 0:05–3:00; required somewhere for Pro
61
+ language: EN # optional — short tag (default: EN, always sent)
62
+ instrumental: false # optional — true sends lyrics: "" and appends the directive
63
+ audio_format: mp3 # optional — mp3 | wav (request: format)
64
+ style: |- # optional — technical direction, the first prompt segment
65
+ Warm analog synthwave at 92 BPM in A minor: detuned pad, gated snare, round sub bass.
66
+ Vocal: intimate female alto, close-mic, no reverb tail.
67
+ avoid: # optional — prompt deny-list, merged with the preset lists
68
+ - trap hi-hats
69
+ - EDM riser clichés
70
+ structure: # optional — timestamped sections, non-decreasing `at`
71
+ - at: "0:00"
72
+ section: Intro
73
+ note: filtered pad, no drums for four bars
74
+ - at: "0:20"
75
+ section: Chorus
76
+ note: hook lyric repeated, gated snare opens up
77
+ lyrics: |- # optional — song text; omitted → the model writes its own
78
+ [Verse]
79
+ Last tram humming through the rain
80
+ [Chorus]
81
+ Midnight cable car, carry me home
82
+ images: [] # optional — up to 10 reference image paths, in order
83
+ takes: 1 # optional — 1..4 sequential requests (batchCount is always 1)
84
+ meta: # optional — recorded in the take sidecar only, never sent
85
+ author: operator
86
+ ```
87
+
88
+ Field rules that bite:
89
+
90
+ | Field | Rule |
91
+ | --- | --- |
92
+ | `format` / `theme` | Must name a preset; an unknown name is a resolution error, never a silent fallback. |
93
+ | `duration_target` | `m:ss`, `0:05`–`3:00`. Required for `model: pro` from some layer (the instance would otherwise send `3:00`). Ignored for `clip` and must stay near `0:30` if you write it. |
94
+ | `language` | Always sent. kk never renders a `Lyrics (sing in …)` line — the instance appends that block itself. |
95
+ | `style` | Required from some layer. It is the technical direction segment — the only control surface the model has. kk never writes duration prose. |
96
+ | `avoid` | Rendered as one `Avoid: a, b` segment, omitted when empty. Additive across layers. |
97
+ | `structure` | Rendered as `[m:ss] Section — note` lines, in authored order. Replaced (not merged) by a higher-precedence layer. |
98
+ | `lyrics` | Sent as the request field. An `instrumental: true` brief may not also carry lyrics. |
99
+ | `takes` | N sequential, separately billed requests — never one batched call. |
100
+ | `meta` | Never sent to the instance; it lands in the take sidecar. |
101
+
102
+ Presets are portable data. A preset file may not declare a provider, API base URL, API model id,
103
+ credential or price — `assertPresetPortable` rejects the file with exit code 2. Prices live in user
104
+ config (`music.prices`, 0400); `model: pro|clip` is the instance's own selector and stays allowed.
105
+
106
+ ## 2. Preset index
107
+
108
+ `formats/` and `themes/` ship as data (task 0399). Any format pairs with any theme: the **format**
109
+ owns the arc (model, default duration target, section skeleton, lyrics policy) and the **theme** owns
110
+ the sound (the technical-direction prose the model reads, plus its default `avoid[]`). The table
111
+ below is generated from those files, so the index cannot drift from the data.
112
+
113
+ <!-- preset-index:start -->
114
+ `formats/`: 5 · `themes/`: 4. Regenerate with
115
+ `bun plugins/generations/music-gen/scripts/gen-preset-index.ts`; `--check` fails on drift.
116
+
117
+ ### Formats
118
+
119
+ A format fixes the job intent, the instance selector (`pro|clip`), the default duration target and the
120
+ timestamped section skeleton. `lyrics` is the format’s policy: `forbidden` resolves `instrumental: true`.
121
+
122
+ | Format | Model | Default duration | Lyrics | Intended use | Status |
123
+ | --- | --- | --- | --- | --- | --- |
124
+ | `clip` | `clip` | — (clip is fixed at ~0:30) | allowed | Quick preview, a direction check before a pro run, or a short social cut. | `authored` |
125
+ | `jingle` | `pro` | `0:20` | allowed | Product or station ident — the hook states the name once and resolves fast. | `authored` |
126
+ | `loop` | `clip` | — (clip is fixed at ~0:30) | forbidden | Background bed for a talk-through, demo or menu loop; no vocals by design. | `authored` |
127
+ | `song` | `pro` | `2:30` | allowed | A complete track with a sung hook; the default for lyrical pieces. | `authored` |
128
+ | `underscore` | `pro` | `0:45` | forbidden | Underscore under spoken narration or a video essay; no hook or vocal required. | `authored` |
129
+
130
+ ### Themes
131
+
132
+ A theme supplies the technical-direction prose the model reads — genre, tempo, key, instrumentation,
133
+ vocal character and production — plus its default `avoid[]`, rendered as one `Avoid: …` segment.
134
+
135
+ | Theme | Technical direction | Default avoid | Intended use | Status |
136
+ | --- | --- | --- | --- | --- |
137
+ | `ambient-tech` | glassy ambient techno; 100-115 BPM, steady and unaccented; C# minor | hard drops, talkbox vocals, pop hooks, vocal chops | Product walkthroughs, conference holds, editorial beds that must stay out of the way. | `authored` |
138
+ | `cinematic` | cinematic orchestral hybrid score; 60-90 BPM with rubato swells; D minor | horror stingers, orchestral hits on every downbeat, distorted electric guitar, pop chorus stacks | Trailer-style openings, story intros, a track that must feel like a scene. | `authored` |
139
+ | `lofi` | dusty sampled lo-fi hip-hop; 70-85 BPM, swung and unhurried; A minor | trap hi-hat rolls, hard drops, EDM riser clichés, over-compressed loudness | Study/focus background, calm narration bed, unhurried social cuts. | `authored` |
140
+ | `synthwave` | analog synthwave revival; 90-110 BPM, straight four-on-the-floor; A minor | festival supersaws, EDM risers, distorted djent guitars, modern trap percussion | Retro-tech explainers, night-drive montages, upbeat product stings. | `authored` |
141
+ <!-- preset-index:end -->
142
+
143
+ Evidence status: `authored` means written from the design contract with no generated take judged
144
+ against it yet, `evidence-pending` means queued for a real generation round, and `verified` means a
145
+ reviewed take exists — the rules live in [`presets/SOURCE.md`](presets/SOURCE.md). `corporate-tech`
146
+ and `xhs-pop` are deliberately not shipped: no generated track has produced evidence for them yet.
147
+
148
+ ## 3. Running the plugin
149
+
150
+ The plugin is invoked the way every generator is — a `DocList` in, a `Content` out:
151
+
152
+ ```bash
153
+ bun plugins/generations/music-gen/src/index.ts --in docs.json --out content.json
154
+ ```
155
+
156
+ `docs[0].body` carries the brief in the YAML authoring form above. `docs[0].metadata.musicGen` carries
157
+ only what is *not* the brief, and is strict (an unknown key is an error, never silently dropped):
158
+
159
+ ```yaml
160
+ metadata:
161
+ musicGen:
162
+ presets: # 0399 loads these from disk; accepted inline here
163
+ format: { name: loop, style: "Glassy texture at 110 BPM." }
164
+ theme: { name: ambient-tech }
165
+ outputStem: midnight-cable-car # overrides the artifact slug (default: the brief title)
166
+ force: true # a paid re-send the operator accepted (0400 records it)
167
+ reason: "the first take was unusable"
168
+ ```
169
+
170
+ ### 3.1 Configuration
171
+
172
+ One reader, three layers: **environment override > `music:` config key > documented default**. The
173
+ config file is the existing kk user config (`KK_CONFIG`, else `~/.config/kk/config.yaml`).
174
+
175
+ | Setting | Environment | Config key | Default |
176
+ | --- | --- | --- | --- |
177
+ | Instance base URL | `KK_MUSIC_INSTANCE_URL` | `music.instance.url` (alias `music.baseUrl`) | `http://127.0.0.1:3000` |
178
+ | Generate timeout (ms) | `KK_MUSIC_TIMEOUT_MS` | `music.instance.timeoutMs` (alias `music.timeoutMs`) | `180000` |
179
+ | Connect timeout (ms) | — | `music.instance.connectTimeoutMs` | `5000` |
180
+ | Offline adapter | `KK_MUSIC_DRY_RUN=1` | — | unset (live) |
181
+ | Unit prices | — (0400) | `music.prices.{pro,clip,analyze}` | `pro 0.08`, `clip 0.04`, `analyze` unpriced |
182
+ | Take cap | — (0400) | `music.takesCap` | `2`, never above `4` |
183
+ | Workflow run id | `KK_MUSIC_RUN_ID` | — | unset (recorded in the sidecar when present) |
184
+
185
+ A key that is *present* but of the wrong type throws, naming the key — a silently defaulted endpoint
186
+ or timeout would send a paid request somewhere unexpected. The default base URL is provisional: it
187
+ assumes the instance listens on loopback port 3000, and 0404's dogfood pins the real value.
188
+
189
+ ### 3.1.1 The spend guard (task 0400)
190
+
191
+ One enforcement point, `src/spend.ts`, runs before the adapter exists — so a refused run prints its
192
+ estimate and stops without opening a socket:
193
+
194
+ | Step | Rule | Refusal names |
195
+ | --- | --- | --- |
196
+ | Estimate | prompt, resolved model, takes, unit price, total from `music.prices`; `analyze` has no default and renders `unpriced` | — |
197
+ | Confirmation | no paid call without `--yes` (or the workflow var the HITL gate sets); an unpriced call still needs it | `--yes` |
198
+ | Dedupe | the 0397 per-take digest is compared with the sidecars in the **run directory**; a match prints the existing artifact path and digest | `--force --reason <text>` |
199
+ | Takes cap | `music.takesCap` (default 2, hard max 4); over the cap is refused, never trimmed | `--takes` (and the cap) |
200
+
201
+ ```bash
202
+ # print the cost and stop: no socket, no artifact (exit 0)
203
+ bun plugins/generations/music-gen/src/index.ts --in docs.json --out content.json --estimate-only
204
+
205
+ # a paid run needs --yes; a deliberate re-roll needs --force --reason
206
+ bun plugins/generations/music-gen/src/index.ts --in docs.json --out content.json --yes
207
+ bun plugins/generations/music-gen/src/index.ts --in docs.json --out content.json --yes --force --reason "first take was unusable"
208
+ ```
209
+
210
+ The dedupe scope is the run directory, not the digest: the same brief in another topic's run
211
+ directory is a legitimate re-roll. A resumed run that re-requests an already-paid take is therefore
212
+ refused by default — resume it with `--force --reason` so the re-spend is recorded, never repeated
213
+ silently.
214
+
215
+ ### 3.2 The paid-call policy
216
+
217
+ `POST /api/lyria/generate` and `POST /api/ai/analyze` are **non-idempotent**: the instance may have
218
+ billed and persisted a take even when kk never saw the response. The adapter therefore:
219
+
220
+ - **retries only connect-phase failures** (`ECONNREFUSED`, `ENOTFOUND`, `EAI_AGAIN`,
221
+ `EHOSTUNREACH`, `ENETUNREACH`, a connect timeout), bounded to 3 attempts — the request provably
222
+ never reached the instance;
223
+ - treats `401`, `402`, `403`, `404`, `429` and the all-keys-rejected `502` as **terminal**: one
224
+ request sent, no retry, the instance's own error text plus a remediation;
225
+ - **never re-sends after an ambiguous outcome** (a timeout after send, `ECONNRESET`, any other `5xx`,
226
+ an unparseable `200`, a `200` with no audio). It reconciles against `GET /api/generations` and
227
+ adopts the earliest take whose `prompt` is byte-equal to what kk sent, whose `model` matches and
228
+ whose `generatedAt` is at or after the request start — flagging it `adoptedByReconciliation` and
229
+ listing any later matches as `unclaimed`. No match fails naming the endpoint, the elapsed time and
230
+ the `--force` remediation.
231
+
232
+ `analyze` is **cache-first**: the instance caches analysis per generation, so the manifest is read
233
+ first and the paid `POST /api/ai/analyze` is issued only when no analysis is cached. An ambiguous
234
+ analyse re-reads the manifest — it never pays twice.
235
+
236
+ ### 3.3 Artifacts and sidecars
237
+
238
+ One artifact per take, in the `--out` directory:
239
+
240
+ ```text
241
+ <slug>-<model>-<instanceId>.<ext> # e.g. midnight-cable-car-clip-gen_01.mp3
242
+ <slug>-<model>-<instanceId>.<ext>.take.json
243
+ ```
244
+
245
+ The delivered container (`ext`) is detected from the returned bytes, never assumed from the request's
246
+ `audio_format`. The sidecar carries the 0397 digest and digest input, the instance id, the model, the
247
+ unit price charged, the adoption flag, the unclaimed extra takes, the exact request body and
248
+ `language` / `durationTarget` / `batchCount` **exactly as the instance recorded them** (absent when the
249
+ manifest lacked them, never defaulted). The instance's `generations/` library is never mirrored into a
250
+ kk workspace.
251
+
252
+ `takes: N` is N sequential single-take requests. A failure on take k leaves takes 1..k-1 on disk — a
253
+ resume reaches them through 0400's dedupe, which refuses to pay for a take the run already owns unless
254
+ the operator passes `--force --reason` — and writes no `--out` file.
255
+
256
+ ### 3.4 Offline
257
+
258
+ ```bash
259
+ KK_MUSIC_DRY_RUN=1 bun plugins/generations/music-gen/src/index.ts --in docs.json --out content.json
260
+ ```
261
+
262
+ The offline adapter emits a deterministic 1-second silent WAV, a synthetic manifest (`offline-take-<n>`)
263
+ and a synthetic analysis, with **zero network calls by construction** — it holds no fetch seam. It is
264
+ the default for this plugin's whole test suite, so no test can spend money.
265
+
266
+ ## 4. Tests
267
+
268
+ ```bash
269
+ bun test plugins/generations/music-gen
270
+ ```
271
+
272
+ Fully offline. The four golden fixtures pin the prompt text and request JSON byte for byte; the
273
+ preset-portability test spawns a loader to prove the non-zero exit; and every adapter test runs
274
+ against an injected `fetch` stub, covering success, format detection, manifest mapping, cache-first
275
+ analyse, each terminal status, the connect-retry bound, timeout → reconciliation adopt,
276
+ timeout → miss → fail, and malformed JSON. The discoverability test runs kk-core's own registry over
277
+ `plugins/` and compares `plugin.json`'s `runtime.requires` against the modules `src/` imports.