@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,446 @@
1
+ /**
2
+ * The versioned per-attempt selection-counts artifact (task 0392 R1/R2).
3
+ *
4
+ * Before 0392 the QC/curation path recorded exclusion evidence only when a rule actually hit
5
+ * (`${run_date}_04_quality-control-content_exclusions.json`), so a day that kept everything and a day
6
+ * whose boundary never ran produced the same files: nothing. The report could therefore only say
7
+ * "QC admitted zero" without saying how the pool shrank, and a retry overwrote the previous
8
+ * attempt's numbers instead of reconciling against them.
9
+ *
10
+ * This module owns the deterministic half: one artifact, `21-plan/topic-selection-attempts.json`,
11
+ * `version`-stamped, holding an append-only list of attempts. Each attempt captures
12
+ * - one record per selection stage that actually ran, `{stage, input, kept, dropped[]}`, so each
13
+ * stage is provable on its own (`input === kept + dropped.length`) instead of being inferred
14
+ * from a single cross-stage sum,
15
+ * - per-rule hit counts (rule hits are NOT unique IDs: one doc can be counted under several rules
16
+ * across attempts, and the UI/report must not add the two numbers together),
17
+ * - the editorial (curation) exclusions with the agent's own reason, kept apart from mechanical
18
+ * rule hits because they answer a different question,
19
+ * - the channel-admission decisions per target, which are an outcome of the run and never change
20
+ * the candidate totals,
21
+ * - which stages have observed evidence, so a stage that never ran stays `unknown` instead of
22
+ * being inferred as zero.
23
+ *
24
+ * A retry appends rather than replaces. The reconciliation block always describes the LATEST
25
+ * attempt (a retry must not inherit a stale reason from the attempt it supersedes) while the earlier
26
+ * attempts stay inspectable, marked `superseded`.
27
+ *
28
+ * Node/Bun builtins plus the sibling boundary engine only — the stage runner imports this file.
29
+ */
30
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
31
+ import { dirname, join } from 'node:path';
32
+ import type { TopicBoundaryExclusion, TopicBoundarySpec } from './kk-workflow-stages.ts';
33
+
34
+ /** Bump when the attempt/reconciliation shape changes; readers must tolerate older versions. */
35
+ export const SELECTION_ATTEMPTS_VERSION = 2;
36
+
37
+ /**
38
+ * Selection stages in pipeline order.
39
+ *
40
+ * `qc` is the raw pool entering the QC filter and its output; `topicBoundary` → `dedup` → `floor`
41
+ * run inside `daily-qc-content`; `curation` → `plan` are the agent's curated split (written by
42
+ * `daily-curate-check`); `channelAdmission` is the content-safety gate's per-target decision.
43
+ */
44
+ export const SELECTION_STAGES = [
45
+ 'qc',
46
+ 'topicBoundary',
47
+ 'dedup',
48
+ 'floor',
49
+ 'curation',
50
+ 'plan',
51
+ 'channelAdmission',
52
+ ] as const;
53
+
54
+ export type SelectionStage = (typeof SELECTION_STAGES)[number];
55
+
56
+ /** Stages that move candidates, and so carry `input = kept + dropped`. */
57
+ export const COUNT_STAGES = ['qc', 'topicBoundary', 'dedup', 'floor', 'curation', 'plan'] as const;
58
+
59
+ export type CountStage = (typeof COUNT_STAGES)[number];
60
+
61
+ /** One stage's observed arithmetic. `dropped` holds distinct candidate IDs, never rule hits. */
62
+ export interface SelectionStageCount {
63
+ stage: CountStage;
64
+ /** Candidates entering the stage. */
65
+ input: number;
66
+ /** Candidates the stage kept. */
67
+ kept: number;
68
+ /** Distinct candidate IDs the stage dropped. */
69
+ dropped: string[];
70
+ }
71
+
72
+ /**
73
+ * Counts the report totals use. Kept for shape compatibility with the v1 artifact; every field is
74
+ * derived from `stages[]` (`null` when the stage that produces it left no evidence).
75
+ */
76
+ export interface SelectionStageCounts {
77
+ /** Raw pool entering QC (`qc` stage input). */
78
+ preFilter: number | null;
79
+ /** Final kept count — the curated plan when curation ran, else the post-dedup survivors. */
80
+ kept: number | null;
81
+ /** Distinct candidate IDs dropped by a mechanical boundary rule. */
82
+ uniqueExcluded: number | null;
83
+ /** Near-duplicate drops (`null` = the dedup stage left no evidence). */
84
+ deduped: number | null;
85
+ /** Curated plan item count (`null` = curation left no evidence). */
86
+ planned: number | null;
87
+ }
88
+
89
+ /** `observed` only when a stage wrote evidence for this attempt. */
90
+ export type StageEvidence = Record<SelectionStage, 'observed' | 'unknown'>;
91
+
92
+ export interface SelectionExclusionRecord {
93
+ /** Candidate id. */
94
+ id: string;
95
+ /** Rule that excluded it in this attempt. */
96
+ rule: string;
97
+ /** The keyword/text the rule matched. */
98
+ matched: string;
99
+ }
100
+
101
+ /** An editorial (curation) exclusion: the agent's own reason, not a mechanical rule id. */
102
+ export interface CurationExclusionRecord {
103
+ id: string;
104
+ reason: string;
105
+ }
106
+
107
+ /** Per-target channel decision. A target outcome, never a candidate count. */
108
+ export interface ChannelAdmissionRecord {
109
+ /** Scope the review ran over (`drafts`, `variants`). */
110
+ scope: string;
111
+ /** Target platform → decision (`OK` | `RISK` | `BLOCK`), plus the gate's own status. */
112
+ targets: { target: string; decision: string }[];
113
+ /** The gate's classification for this scope (`pass` | `revise` | `exclude` | `escalate` | `block`). */
114
+ status: string;
115
+ }
116
+
117
+ export interface SelectionAttempt {
118
+ /** 1-based ordinal within the run day; a retry is attempt 2, 3, … */
119
+ attempt: number;
120
+ /** Run id + ordinal, so evidence binds to an attempt even when the work dir is reused. */
121
+ attemptId: string;
122
+ recordedAt: string;
123
+ /** `topic-boundary.json` version in force for this attempt. */
124
+ specVersion: number;
125
+ counts: SelectionStageCounts;
126
+ /** One record per stage that ran, in pipeline order. */
127
+ stages: SelectionStageCount[];
128
+ /** Rule id → number of hits in this attempt (a hit count, not a unique-ID count). */
129
+ perRuleHits: Record<string, number>;
130
+ /** The unique excluded candidate IDs this attempt recorded, with their rule. */
131
+ exclusions: SelectionExclusionRecord[];
132
+ /** Editorial exclusions with the agent's own reason. */
133
+ curationExcluded: CurationExclusionRecord[];
134
+ /** Candidate IDs excluded under more than one distinct rule across the run day's attempts. */
135
+ multipleHitIds: string[];
136
+ /** Kept candidate IDs (the decisions, so a loss is attributable, not just counted). */
137
+ keptIds: string[];
138
+ /** Channel-admission outcomes; `null` until the safety gate recorded a decision. */
139
+ channelAdmission: ChannelAdmissionRecord[];
140
+ stageEvidence: StageEvidence;
141
+ }
142
+
143
+ export interface SelectionReconciliation {
144
+ /**
145
+ * Every observed count stage satisfies `input === kept + dropped.length`, and consecutive
146
+ * observed stages chain (`next.input === previous.kept`). A stage with no evidence leaves the
147
+ * reconciliation unproven (reported through `skippedStages`), never violated.
148
+ */
149
+ reconciled: boolean;
150
+ /** Unique excluded IDs in the latest attempt — count distinct candidates, not rule hits. */
151
+ uniqueIds: number | null;
152
+ /** Sum of the latest attempt's per-rule hits. May exceed `uniqueIds`. */
153
+ ruleHits: number;
154
+ /** Candidate IDs the day excluded under ≥2 distinct rules. */
155
+ multipleHits: number;
156
+ /** A `kept === 0` day is a valid outcome, reported as such (never as a failure). */
157
+ zeroKept: boolean;
158
+ /** Stages with no evidence in the latest attempt — the report prints these as unknown. */
159
+ skippedStages: SelectionStage[];
160
+ /** Attempts whose numbers a later attempt supersedes (kept for history, never inherited). */
161
+ supersededAttempts: number[];
162
+ /** Human-readable contradictions found while reconciling. */
163
+ issues: string[];
164
+ }
165
+
166
+ export interface SelectionAttemptsArtifact {
167
+ version: number;
168
+ runDate: string;
169
+ specVersion: number;
170
+ attempts: SelectionAttempt[];
171
+ reconciliation: SelectionReconciliation;
172
+ }
173
+
174
+ export interface SelectionAttemptInput {
175
+ runDate: string;
176
+ attemptId: string;
177
+ recordedAt?: string;
178
+ spec: Pick<TopicBoundarySpec, 'version'>;
179
+ /** Stage observations this invocation made, in pipeline order. */
180
+ stages: SelectionStageCount[];
181
+ /** Mechanical boundary exclusions (rule-level records). */
182
+ excluded: TopicBoundaryExclusion[];
183
+ /** Candidate IDs kept by the last stage in `stages`. */
184
+ keptIds: string[];
185
+ /** Editorial exclusions, when this invocation produced them (curation). */
186
+ curationExcluded?: CurationExclusionRecord[];
187
+ /** Channel decisions, when this invocation produced them (the safety gate). */
188
+ channelAdmission?: ChannelAdmissionRecord[];
189
+ }
190
+
191
+ /** A later stage's evidence attached to the attempt already on disk. */
192
+ export interface SelectionAttemptPatch {
193
+ /** Stage observations to merge; an existing record for the same stage is replaced. */
194
+ stages?: SelectionStageCount[];
195
+ curationExcluded?: CurationExclusionRecord[];
196
+ channelAdmission?: ChannelAdmissionRecord[];
197
+ /** Overrides the attempt identity — a curation pass after a QC retry belongs to that retry. */
198
+ attemptId?: string;
199
+ }
200
+
201
+ /** Rule id → hit count. A hit is an (item, rule) event; the same item can hit one rule per attempt. */
202
+ export function countRuleHits(excluded: TopicBoundaryExclusion[]): Record<string, number> {
203
+ const hits: Record<string, number> = {};
204
+ for (const entry of excluded) hits[entry.rule] = (hits[entry.rule] ?? 0) + 1;
205
+ return hits;
206
+ }
207
+
208
+ /** Candidate IDs this run day excluded under more than one DISTINCT rule (retries included). */
209
+ export function multipleHitIds(attempts: SelectionAttempt[]): string[] {
210
+ const rulesById = new Map<string, Set<string>>();
211
+ for (const attempt of attempts) {
212
+ for (const entry of attempt.exclusions) {
213
+ const rules = rulesById.get(entry.id) ?? new Set<string>();
214
+ rules.add(entry.rule);
215
+ rulesById.set(entry.id, rules);
216
+ }
217
+ }
218
+ return [...rulesById.entries()].filter(([, rules]) => rules.size > 1).map(([id]) => id);
219
+ }
220
+
221
+ function stageMap(stages: SelectionStageCount[]): Map<CountStage, SelectionStageCount> {
222
+ return new Map(stages.map((entry) => [entry.stage, entry]));
223
+ }
224
+
225
+ /** Sort by pipeline order and drop duplicates, so `stages[]` is always canonical. */
226
+ function orderStages(stages: SelectionStageCount[]): SelectionStageCount[] {
227
+ const byStage = stageMap(stages);
228
+ return COUNT_STAGES.filter((stage) => byStage.has(stage)).map((stage) => byStage.get(stage) as SelectionStageCount);
229
+ }
230
+
231
+ function evidenceFor(attempt: Pick<SelectionAttempt, 'stages' | 'channelAdmission'>): StageEvidence {
232
+ const evidence = {} as StageEvidence;
233
+ const observed = new Set<string>(attempt.stages.map((entry) => entry.stage));
234
+ if (attempt.channelAdmission.length > 0) observed.add('channelAdmission');
235
+ for (const stage of SELECTION_STAGES) evidence[stage] = observed.has(stage) ? 'observed' : 'unknown';
236
+ return evidence;
237
+ }
238
+
239
+ /**
240
+ * Project `stages[]` onto the report totals. `kept` is the LAST count stage's kept value (the
241
+ * curated plan once curation ran), so the headline number never regresses to a pre-curation count.
242
+ */
243
+ function countsFor(stages: SelectionStageCount[], uniqueExcluded: number): SelectionStageCounts {
244
+ const byStage = stageMap(stages);
245
+ const last = stages[stages.length - 1];
246
+ const dedup = byStage.get('dedup');
247
+ const plan = byStage.get('plan');
248
+ return {
249
+ preFilter: byStage.get('qc')?.input ?? null,
250
+ kept: last === undefined ? null : last.kept,
251
+ uniqueExcluded,
252
+ deduped: dedup === undefined ? null : dedup.dropped.length,
253
+ planned: plan === undefined ? null : plan.kept,
254
+ };
255
+ }
256
+
257
+ /** Turn one stage invocation into an attempt record. Pure: no IO, no clock unless asked to stamp one. */
258
+ export function buildSelectionAttempt(input: SelectionAttemptInput, attempt = 1): SelectionAttempt {
259
+ const stages = orderStages(input.stages);
260
+ return {
261
+ attempt,
262
+ attemptId: input.attemptId,
263
+ recordedAt: input.recordedAt ?? new Date().toISOString(),
264
+ specVersion: input.spec.version,
265
+ counts: countsFor(stages, input.excluded.length),
266
+ stages,
267
+ perRuleHits: countRuleHits(input.excluded),
268
+ exclusions: input.excluded.map((entry) => ({ id: entry.id, rule: entry.rule, matched: entry.matched })),
269
+ curationExcluded: input.curationExcluded ?? [],
270
+ multipleHitIds: [],
271
+ keptIds: [...input.keptIds],
272
+ channelAdmission: input.channelAdmission ?? [],
273
+ stageEvidence: evidenceFor({ stages, channelAdmission: input.channelAdmission ?? [] }),
274
+ };
275
+ }
276
+
277
+ /**
278
+ * Reconcile one run day's attempts. The latest attempt owns every number; earlier attempts are
279
+ * history only (a retry must never inherit a stale reason), and its missing stages stay unknown.
280
+ */
281
+ export function reconcileSelectionAttempts(attempts: SelectionAttempt[]): SelectionReconciliation {
282
+ const latest = attempts[attempts.length - 1];
283
+ const issues: string[] = [];
284
+ if (latest === undefined) {
285
+ return {
286
+ reconciled: false,
287
+ uniqueIds: null,
288
+ ruleHits: 0,
289
+ multipleHits: 0,
290
+ zeroKept: false,
291
+ skippedStages: [...SELECTION_STAGES],
292
+ supersededAttempts: [],
293
+ issues: ['no selection attempt was recorded for this run day'],
294
+ };
295
+ }
296
+ // Per-stage arithmetic first: a stage that reports more or fewer drops than it actually moved
297
+ // candidates is the failure mode this artifact exists to catch.
298
+ for (const entry of latest.stages) {
299
+ const sum = entry.kept + entry.dropped.length;
300
+ if (entry.input !== sum) {
301
+ issues.push(`${entry.stage}: input ${entry.input} ≠ kept ${entry.kept} + dropped ${entry.dropped.length}`);
302
+ }
303
+ }
304
+ // Then the chain: a stage that starts from a count the previous stage did not hand over means
305
+ // the numbers were recorded across different inputs (a retry mid-pipeline, or a stale artifact).
306
+ for (let index = 1; index < latest.stages.length; index += 1) {
307
+ const previous = latest.stages[index - 1] as SelectionStageCount;
308
+ const current = latest.stages[index] as SelectionStageCount;
309
+ if (current.input !== previous.kept) {
310
+ issues.push(
311
+ `${previous.stage} → ${current.stage}: previous kept ${previous.kept} ≠ next input ${current.input}`,
312
+ );
313
+ }
314
+ }
315
+ const kept = latest.counts.kept;
316
+ const ruleHits = Object.values(latest.perRuleHits).reduce((total, hits) => total + hits, 0);
317
+ return {
318
+ reconciled: issues.length === 0 && latest.stages.length > 0,
319
+ uniqueIds: latest.counts.uniqueExcluded,
320
+ ruleHits,
321
+ multipleHits: multipleHitIds(attempts).length,
322
+ zeroKept: kept === 0,
323
+ skippedStages: SELECTION_STAGES.filter((stage) => latest.stageEvidence[stage] === 'unknown'),
324
+ supersededAttempts: attempts.slice(0, -1).map((attempt) => attempt.attempt),
325
+ issues,
326
+ };
327
+ }
328
+
329
+ function artifactFor(input: {
330
+ runDate: string;
331
+ specVersion: number;
332
+ attempts: SelectionAttempt[];
333
+ }): SelectionAttemptsArtifact {
334
+ const attempts = [...input.attempts];
335
+ const latest = attempts[attempts.length - 1] as SelectionAttempt;
336
+ attempts[attempts.length - 1] = { ...latest, multipleHitIds: multipleHitIds(attempts) };
337
+ return {
338
+ version: SELECTION_ATTEMPTS_VERSION,
339
+ runDate: input.runDate,
340
+ specVersion: input.specVersion,
341
+ attempts,
342
+ reconciliation: reconcileSelectionAttempts(attempts),
343
+ };
344
+ }
345
+
346
+ /** Append an attempt to the run day's artifact (a retry appends; nothing is overwritten). */
347
+ export function appendSelectionAttempt(
348
+ previous: SelectionArtifact | null,
349
+ input: SelectionAttemptInput,
350
+ ): SelectionArtifact {
351
+ const history = previous !== null && previous.runDate === input.runDate ? previous.attempts : [];
352
+ const attempt = buildSelectionAttempt(input, history.length + 1);
353
+ return artifactFor({
354
+ runDate: input.runDate,
355
+ specVersion: attempt.specVersion,
356
+ attempts: [...history, attempt],
357
+ });
358
+ }
359
+
360
+ /**
361
+ * Attach a later stage's evidence to the attempt already recorded for the run day.
362
+ *
363
+ * The pipeline is staged: QC writes the attempt, curation and the safety gate only run afterwards.
364
+ * Amending keeps ONE attempt per invocation (a retry is a new attempt), which is why the identity
365
+ * comes from the attempt already on disk rather than from a fresh `attemptId`. Returns `null` when
366
+ * there is no attempt to amend — the caller then leaves the stage unknown instead of inventing one.
367
+ */
368
+ export function amendSelectionAttempt(
369
+ previous: SelectionArtifact | null,
370
+ runDate: string,
371
+ patch: SelectionAttemptPatch,
372
+ ): SelectionArtifact | null {
373
+ if (previous === null || previous.runDate !== runDate) return null;
374
+ const attempts = [...previous.attempts];
375
+ const latest = attempts[attempts.length - 1];
376
+ if (latest === undefined) return null;
377
+ const merged: SelectionAttempt = {
378
+ ...latest,
379
+ attemptId: patch.attemptId ?? latest.attemptId,
380
+ stages: orderStages([...latest.stages, ...(patch.stages ?? [])]),
381
+ curationExcluded: [...latest.curationExcluded, ...(patch.curationExcluded ?? [])],
382
+ channelAdmission: mergeChannelAdmission(latest.channelAdmission, patch.channelAdmission ?? []),
383
+ };
384
+ // The boundary exclusion records live on the attempt; re-project from them so a curation
385
+ // amendment cannot discard the rule counts the QC stage recorded.
386
+ merged.counts = countsFor(merged.stages, merged.exclusions.length);
387
+ merged.stageEvidence = evidenceFor(merged);
388
+ attempts[attempts.length - 1] = merged;
389
+ return artifactFor({ runDate: previous.runDate, specVersion: merged.specVersion, attempts });
390
+ }
391
+
392
+ /** A re-run of the same scope replaces that scope's decisions; a new scope appends. */
393
+ function mergeChannelAdmission(
394
+ existing: ChannelAdmissionRecord[],
395
+ incoming: ChannelAdmissionRecord[],
396
+ ): ChannelAdmissionRecord[] {
397
+ const merged = [...existing];
398
+ for (const entry of incoming) {
399
+ const index = merged.findIndex((current) => current.scope === entry.scope);
400
+ if (index === -1) merged.push(entry);
401
+ else merged[index] = entry;
402
+ }
403
+ return merged;
404
+ }
405
+
406
+ /** `21-plan/topic-selection-attempts.json` — one artifact per run day, shared by both report paths. */
407
+ export function selectionAttemptsPath(workDir: string): string {
408
+ return join(workDir, '21-plan', 'topic-selection-attempts.json');
409
+ }
410
+
411
+ /** Tolerant read: an absent, unparsable or older artifact is `null`, never a thrown stage. */
412
+ export function readSelectionAttempts(workDir: string): SelectionArtifact | null {
413
+ try {
414
+ const parsed = JSON.parse(readFileSync(selectionAttemptsPath(workDir), 'utf-8')) as unknown;
415
+ if (parsed === null || typeof parsed !== 'object') return null;
416
+ const artifact = parsed as SelectionArtifact;
417
+ return Array.isArray(artifact.attempts) ? artifact : null;
418
+ } catch {
419
+ return null;
420
+ }
421
+ }
422
+
423
+ function persist(workDir: string, artifact: SelectionAttemptsArtifact): SelectionAttemptsArtifact {
424
+ const path = selectionAttemptsPath(workDir);
425
+ mkdirSync(dirname(path), { recursive: true });
426
+ writeFileSync(path, `${JSON.stringify(artifact, null, 2)}\n`);
427
+ return artifact;
428
+ }
429
+
430
+ /**
431
+ * Record one selection attempt for the run day. Returns the artifact it wrote; an unwritable work
432
+ * dir throws (the caller stages it through `sted`, so the write is visible in step timing).
433
+ */
434
+ export function recordSelectionAttempt(workDir: string, input: SelectionAttemptInput): SelectionArtifact {
435
+ return persist(workDir, appendSelectionAttempt(readSelectionAttempts(workDir), input));
436
+ }
437
+
438
+ /** Record a later stage's evidence onto the run day's current attempt; `null` when there is none. */
439
+ export function recordSelectionStage(
440
+ workDir: string,
441
+ runDate: string,
442
+ patch: SelectionAttemptPatch,
443
+ ): SelectionArtifact | null {
444
+ const amended = amendSelectionAttempt(readSelectionAttempts(workDir), runDate, patch);
445
+ return amended === null ? null : persist(workDir, amended);
446
+ }
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Replayable calibration harness for the daily topic/selection boundary (task 0392 R1).
3
+ *
4
+ * The problem the task names: the deterministic floor (`topic-boundary.json`, since 2026-10-22 the
5
+ * single `prc-leadership` rule) is narrow, but the editorial Agent still excluded whole
6
+ * public-affairs classes (`plugins/kk/skills/news-editorial/SKILL.md` "Topic boundary"), so the
7
+ * shipped policy excluded AI-industry mainlines — regulation, litigation, export controls,
8
+ * procurement — that the column exists to cover. Narrowing that policy by opinion is how 0189's
9
+ * five broad rules happened. This module makes the calibration evidence-based: every sample is a
10
+ * TAGGED fixture (historical exclusion / counterexample) with an expected verdict, replayed against
11
+ * the spec in force, so a rule change that re-breaks a known-good AI story fails a test.
12
+ *
13
+ * Fixtures are data (`tests/fixtures/topic-selection-cases.json`), not code, so the record of which
14
+ * historical exclusions were replayed — and under which rule they once hit — survives without
15
+ * editing a prompt.
16
+ *
17
+ * Node/Bun builtins only plus the sibling boundary engine.
18
+ */
19
+ import { applyTopicBoundary, type TopicBoundarySpec } from './kk-workflow-stages.ts';
20
+
21
+ /** `historical` = a real prior exclusion; `counterexample` = a sample the policy must NOT drop. */
22
+ export type CalibrationTag = 'historical' | 'counterexample';
23
+
24
+ export interface CalibrationCaseDoc {
25
+ id: string;
26
+ title: string;
27
+ body: string;
28
+ publishedAt?: string;
29
+ }
30
+
31
+ export interface CalibrationCase {
32
+ id: string;
33
+ tag: CalibrationTag;
34
+ /** Where the sample came from (run id, store item, date) — the audit trail. */
35
+ source: string;
36
+ /** What this case proves, in one line. */
37
+ note: string;
38
+ doc: CalibrationCaseDoc;
39
+ expect: 'kept' | 'excluded';
40
+ /** Rule id expected to exclude it; absent when `expect === 'kept'`. */
41
+ expectRule?: string;
42
+ }
43
+
44
+ export interface CalibrationCaseResult {
45
+ id: string;
46
+ tag: CalibrationTag;
47
+ note: string;
48
+ expected: 'kept' | 'excluded';
49
+ actual: 'kept' | 'excluded';
50
+ rule: string | null;
51
+ matched: string | null;
52
+ agrees: boolean;
53
+ }
54
+
55
+ export interface CalibrationSummary {
56
+ cases: number;
57
+ kept: number;
58
+ excluded: number;
59
+ /** Rule id → hits across all replayed cases. */
60
+ perRuleHits: Record<string, number>;
61
+ /** Unique candidate IDs excluded — the count the report must use, not `ruleHits`. */
62
+ uniqueIds: number;
63
+ ruleHits: number;
64
+ mismatches: CalibrationCaseResult[];
65
+ /** tag → case/mismatch counts, so a regression names which sample class broke. */
66
+ byTag: Record<CalibrationTag, { cases: number; mismatches: number }>;
67
+ passes: boolean;
68
+ }
69
+
70
+ /** Replay every fixture through the boundary spec in force, recording the verdict and the rule. */
71
+ export function replayCalibrationCases(
72
+ cases: CalibrationCase[],
73
+ spec: TopicBoundarySpec,
74
+ runDate = '20261117',
75
+ ): CalibrationCaseResult[] {
76
+ return cases.map((entry) => {
77
+ // `applyTopicBoundary` reads `publishedAt` from `metadata` (the store's Doc shape); the
78
+ // fixtures keep it flat on the sample so a reviewer can read one line per case.
79
+ const doc = {
80
+ id: entry.doc.id,
81
+ title: entry.doc.title,
82
+ body: entry.doc.body,
83
+ metadata: entry.doc.publishedAt === undefined ? {} : { publishedAt: entry.doc.publishedAt },
84
+ };
85
+ const { excluded } = applyTopicBoundary([doc], runDate, spec);
86
+ const hit = excluded[0];
87
+ const actual: 'kept' | 'excluded' = hit === undefined ? 'kept' : 'excluded';
88
+ const rule = hit?.rule ?? null;
89
+ const agrees = actual === entry.expect && (entry.expectRule === undefined || entry.expectRule === rule);
90
+ return {
91
+ id: entry.id,
92
+ tag: entry.tag,
93
+ note: entry.note,
94
+ expected: entry.expect,
95
+ actual,
96
+ rule,
97
+ matched: hit?.matched ?? null,
98
+ agrees,
99
+ };
100
+ });
101
+ }
102
+
103
+ /** Fold per-case results into the numbers the calibration record and its test assert on. */
104
+ export function summarizeCalibration(results: CalibrationCaseResult[]): CalibrationSummary {
105
+ const perRuleHits: Record<string, number> = {};
106
+ for (const result of results) {
107
+ if (result.rule !== null) perRuleHits[result.rule] = (perRuleHits[result.rule] ?? 0) + 1;
108
+ }
109
+ const mismatches = results.filter((result) => !result.agrees);
110
+ const byTag: CalibrationSummary['byTag'] = {
111
+ historical: { cases: 0, mismatches: 0 },
112
+ counterexample: { cases: 0, mismatches: 0 },
113
+ };
114
+ for (const result of results) {
115
+ byTag[result.tag].cases += 1;
116
+ if (!result.agrees) byTag[result.tag].mismatches += 1;
117
+ }
118
+ const excluded = results.filter((result) => result.actual === 'excluded');
119
+ return {
120
+ cases: results.length,
121
+ kept: results.length - excluded.length,
122
+ excluded: excluded.length,
123
+ perRuleHits,
124
+ uniqueIds: excluded.length,
125
+ ruleHits: Object.values(perRuleHits).reduce((total, hits) => total + hits, 0),
126
+ mismatches,
127
+ byTag,
128
+ passes: mismatches.length === 0,
129
+ };
130
+ }
131
+
132
+ /** Parse the fixture file's cases, rejecting a case that forgets its tag or its expectation. */
133
+ export function parseCalibrationCases(raw: unknown): CalibrationCase[] {
134
+ if (!Array.isArray(raw)) throw new Error('topic-selection fixtures: expected a case array');
135
+ return raw.map((value, index) => {
136
+ const entry = (value ?? {}) as Record<string, unknown>;
137
+ const tag = entry.tag;
138
+ if (tag !== 'historical' && tag !== 'counterexample') {
139
+ throw new Error(`topic-selection fixtures[${index}]: tag must be historical|counterexample`);
140
+ }
141
+ const expect = entry.expect;
142
+ if (expect !== 'kept' && expect !== 'excluded') {
143
+ throw new Error(`topic-selection fixtures[${index}]: expect must be kept|excluded`);
144
+ }
145
+ const doc = (entry.doc ?? {}) as Record<string, unknown>;
146
+ return {
147
+ id: String(entry.id ?? ''),
148
+ tag,
149
+ source: String(entry.source ?? ''),
150
+ note: String(entry.note ?? ''),
151
+ doc: {
152
+ id: String(doc.id ?? entry.id ?? ''),
153
+ title: String(doc.title ?? ''),
154
+ body: String(doc.body ?? ''),
155
+ ...(typeof doc.publishedAt === 'string' ? { publishedAt: doc.publishedAt } : {}),
156
+ },
157
+ expect,
158
+ ...(typeof entry.expectRule === 'string' ? { expectRule: entry.expectRule } : {}),
159
+ };
160
+ });
161
+ }
@@ -21,7 +21,8 @@ LLM-as-judge is **not** a knowledge-kit plugin kind (ADR-007 amdt 2026-08-07). I
21
21
 
22
22
  - A spur workflow needs a quality gate between `generate` and `publish`.
23
23
  - A user asks to "judge", "evaluate", "quality-check", or "gate" generated content.
24
- - A workflow or skill names a rubric (`tech-accuracy` / `brand-tone` / `compliance` / `news-balance` / `general`).
24
+ - A workflow or skill names a rubric (`tech-accuracy` / `brand-tone` / `compliance` / `news-balance` /
25
+ `music-quality` / `general`).
25
26
 
26
27
  ## Verdict output contract
27
28
 
@@ -99,7 +100,7 @@ and `escalate` flag; treat `LOW` as a signal to demand human review before publi
99
100
  1. **Read the Content** from the path given in the evaluation request (the `content.json` written
100
101
  by the preceding `kk executor run <generator>` step).
101
102
  2. **Select the rubric** — named in the request (`tech-accuracy`, `brand-tone`,
102
- `compliance`, `news-balance`, `general`). Default: `general`.
103
+ `compliance`, `news-balance`, `music-quality`, `general`). Default: `general`.
103
104
  3. **Evaluate each criterion** in the rubric. For each, produce a `pass` / `fail` / `warn` status
104
105
  backed by a specific, quotable evidence reference (quote, section, claim).
105
106
  4. **Score** — weighted aggregate per the rubric's scoring rules. `score` is 0.0–1.0.
@@ -127,9 +128,10 @@ and `escalate` flag; treat `LOW` as a signal to demand human review before publi
127
128
 
128
129
  ## Rubrics
129
130
 
130
- Five built-in rubrics. Full definitions, weights, and thresholds live in
131
- `references/rubrics.md`. The skill body intentionally stays lean — load the reference when
132
- evaluating.
131
+ Six built-in rubrics. Full definitions, weights, and thresholds live in
132
+ `references/rubrics.md`, except `music-quality`, whose measurement-discipline rules live in
133
+ `references/music-quality-rubric.md`. The skill body intentionally stays lean — load the reference
134
+ when evaluating.
133
135
 
134
136
  | Rubric | Use when | Key must-pass criteria |
135
137
  |--------|----------|------------------------|
@@ -138,6 +140,7 @@ evaluating.
138
140
  | `brand-tone` | Published voice | tone consistency, banned-phrase compliance, audience fit |
139
141
  | `compliance` | Sensitive content | no prohibited claims, disclosure presence, jurisdictional rules |
140
142
  | `news-balance` | Daily news script plan | news-first, commentary-share, no-restatement |
143
+ | `music-quality` | Generated music takes (`kk-music`) | checks.clean — every measured take check passes |
141
144
 
142
145
  ## Prompt template
143
146
 
@@ -148,7 +151,7 @@ Use this template when the skill is invoked by an `agent.run` step. The workflow
148
151
  You are an LLM-as-judge evaluating generated content for the knowledge-kit pipeline.
149
152
 
150
153
  Content to evaluate: {{content_path}}
151
- Rubric: {{rubric}} # general | tech-accuracy | brand-tone | compliance | news-balance
154
+ Rubric: {{rubric}} # general | tech-accuracy | brand-tone | compliance | news-balance | music-quality
152
155
  Output verdict to: {{verdict_path}}
153
156
 
154
157
  Load the rubric definition from plugins/kk/skills/content-judge/references/rubrics.md (section: {{rubric}}).
@@ -173,4 +176,6 @@ section in `references/rubrics.md` and name it from the prompt — do not add a
173
176
  ## Additional resources
174
177
 
175
178
  - **`references/rubrics.md`** — full rubric definitions, criterion weights, and verdict thresholds
179
+ - **`references/music-quality-rubric.md`** — the `music-quality` rubric: craft dimensions, the
180
+ `checks.clean` must-pass, and the rule that measured facts are quoted from `checks.json`
176
181
  - **`references/workflow-integration.md`** — `agent.run` step shape, shell/`jq` guard, retry topology