@gobing-ai/knowledge-kit 0.1.22 → 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 (59) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/index.js +165 -91
  3. package/package.json +1 -1
  4. package/plugins/generations/gemini-tts/dist/index.js +47 -7
  5. package/plugins/generations/gemini-tts/src/gemini-client.ts +34 -6
  6. package/plugins/generations/music-gen/README.md +2 -2
  7. package/plugins/generations/music-gen/dist/index.js +46 -10
  8. package/plugins/generations/music-gen/presets/formats/song.yaml +6 -1
  9. package/plugins/generations/music-gen/presets/themes/synthwave.yaml +6 -1
  10. package/plugins/generations/music-gen/src/adapter/instance.ts +34 -11
  11. package/plugins/generations/music-gen/src/presets.ts +36 -3
  12. package/plugins/generations/omni-voice-gen/uv.toml +5 -0
  13. package/plugins/generations/vibe-voice-tts/README.md +64 -0
  14. package/plugins/generations/vibe-voice-tts/dist/index.js +14259 -0
  15. package/plugins/generations/vibe-voice-tts/package.json +16 -0
  16. package/plugins/generations/vibe-voice-tts/plugin.json +6 -0
  17. package/plugins/generations/vibe-voice-tts/profiles.json +10 -0
  18. package/plugins/generations/vibe-voice-tts/pyproject.toml +9 -0
  19. package/plugins/generations/vibe-voice-tts/python/worker.py +566 -0
  20. package/plugins/generations/vibe-voice-tts/src/index.ts +88 -0
  21. package/plugins/generations/vibe-voice-tts/src/vibevoice-client.ts +828 -0
  22. package/plugins/generations/vibe-voice-tts/tsconfig.json +8 -0
  23. package/plugins/generations/vibe-voice-tts/uv.lock +1767 -0
  24. package/plugins/generations/vibe-voice-tts/uv.toml +4 -0
  25. package/plugins/generations/voice-gen/dist/index.js +31 -1
  26. package/plugins/generations/voice-gen/src/voicebox-client.ts +50 -1
  27. package/plugins/generations/voxcpm-tts/dist/index.js +81 -9
  28. package/plugins/generations/voxcpm-tts/python/worker.py +9 -0
  29. package/plugins/generations/voxcpm-tts/src/index.ts +41 -0
  30. package/plugins/generations/voxcpm-tts/src/voxcpm-client.ts +32 -11
  31. package/plugins/generations/voxcpm-tts/uv.toml +5 -0
  32. package/plugins/kk/README.md +21 -0
  33. package/plugins/kk/decisions/kk-safety.yaml +5 -2
  34. package/plugins/kk/plugin.json +1 -1
  35. package/plugins/kk/schedules/kk-serve.launchd.plist.tmpl +12 -1
  36. package/plugins/kk/scripts/daily-stages.ts +274 -40
  37. package/plugins/kk/scripts/kk-workflow-stages.ts +74 -11
  38. package/plugins/kk/scripts/safety-artifact-check.ts +28 -5
  39. package/plugins/kk/workflows/kk-daily-ai-voice.yaml +4 -3
  40. package/plugins/kk/workflows/kk-daily-ai-voice2.yaml +6 -5
  41. package/plugins/kk/workflows/kk-daily-safety.yaml +12 -10
  42. package/plugins/kk/workflows/kk-music.yaml +20 -16
  43. package/plugins/kk/workflows/kk-news-generate.yaml +23 -3
  44. package/plugins/kk/workflows/kk-publish.yaml +4 -1
  45. package/plugins/publishings/linkedin-pub/dist/index.js +51 -9
  46. package/plugins/publishings/linkedin-pub/dist/profile-check.js +5 -0
  47. package/plugins/publishings/linkedin-pub/src/index.ts +99 -12
  48. package/plugins/publishings/surfdash-pub/dist/index.js +8 -4
  49. package/plugins/publishings/surfdash-pub/src/index.ts +7 -1
  50. package/plugins/publishings/surfdash-pub/src/patch.ts +21 -3
  51. package/plugins/publishings/threads-pub/dist/index.js +47 -5
  52. package/plugins/publishings/threads-pub/dist/profile-check.js +7 -1
  53. package/plugins/publishings/threads-pub/src/post-rail.ts +101 -4
  54. package/plugins/publishings/wechatmp-pub/dist/index.js +94 -34
  55. package/plugins/publishings/wechatmp-pub/src/cgi-draft.ts +87 -53
  56. package/plugins/publishings/wechatmp-pub/src/enrich.ts +61 -3
  57. package/plugins/publishings/wechatmp-pub/src/flow.ts +28 -0
  58. package/plugins/publishings/x-pub/dist/index.js +84 -9
  59. package/plugins/publishings/x-pub/src/post-rail.ts +154 -12
@@ -667,9 +667,22 @@ function formatWindowMs(ms: number): string {
667
667
  * and dedup), so it is an upper bound: the ladder can stop one step early, never one late.
668
668
  */
669
669
  export function dailyExtract(args: string[]): void {
670
- const [workDir = '', topic = '', window = '', minMinutes = '', vdriver = ''] = args;
670
+ const [workDir = '', topic = '', window = '', minMinutes = '', vdriver = '', limitArg = ''] = args;
671
671
  if (!workDir) fail('missing work_dir');
672
672
  if (!topic) fail('missing topic');
673
+ // 2026-11-20: `kk store extract --limit` defaults to the profile's cap (else 20), and this stage
674
+ // passed no `--limit` at all — so the plan cap (`plan_max_items`, 40) never reached the store and
675
+ // the pool was pre-trimmed to the default before the quota existed. Measured on the production
676
+ // store: 56 category-allowed, importance>=3, unpublished items sat in the 168h window, the
677
+ // extract returned 24, QC admitted 13, the writer kept 3 and the day refused at the TTS gate;
678
+ // at `--limit 40` the same window yields 30 items and 23 survive QC. The extract bound must be
679
+ // at least the plan bound or the plan can never fill.
680
+ const extractedLimit = Number(limitArg);
681
+ const limit =
682
+ limitArg !== '' && Number.isInteger(extractedLimit) && extractedLimit > 0
683
+ ? ['--limit', String(extractedLimit)]
684
+ : [];
685
+ if (limitArg !== '' && limit.length === 0) fail(`extract: invalid limit: ${limitArg}`);
673
686
  const poolPath = join(workDir, '10-collect', 'pool.json');
674
687
  const base = parseWindowMs(window === '' ? '24h' : window);
675
688
  if (base === null) fail(`extract: invalid window: ${window || '(empty)'}`);
@@ -706,7 +719,7 @@ export function dailyExtract(args: string[]): void {
706
719
  for (const ms of windows) {
707
720
  const label = formatWindowMs(ms);
708
721
  const attempt = join(workDir, '10-collect', `.pool-${label}.json`);
709
- kk(['store', 'extract', '--topic', topic, '--window', label, '--out', attempt]);
722
+ kk(['store', 'extract', '--topic', topic, '--window', label, '--out', attempt, ...limit]);
710
723
  const parsed = readJson(attempt);
711
724
  const docs = Array.isArray(parsed) ? (parsed as unknown[]) : [];
712
725
  const estimate = estimateSpokenMinutes(docs, vdriver, ratio.ratio);
@@ -1366,6 +1379,8 @@ export function dailyGenerate(args: string[]): void {
1366
1379
  voicebox: 'voice-gen',
1367
1380
  gemini: 'gemini-tts',
1368
1381
  voxcpm: 'voxcpm-tts',
1382
+ 'vibe-voice': 'vibe-voice-tts',
1383
+ vibevoice: 'vibe-voice-tts',
1369
1384
  };
1370
1385
  let voiceGenerator = VOICE_DRIVERS[vdriver];
1371
1386
  if (!voiceGenerator) {
@@ -1687,13 +1702,18 @@ export function dailyGenerate(args: string[]): void {
1687
1702
  plans = computePlans(voiceGenerator);
1688
1703
  }
1689
1704
 
1690
- // Synthesize sections sequentially (concurrency 1)
1691
- for (const plan of plans) {
1692
- if (!plan.needsSynthesis) {
1693
- console.log(`generate: section cached: ${plan.def.stem}`);
1694
- continue;
1695
- }
1696
- console.log(`generate: synthesizing section: ${plan.def.stem}`);
1705
+ const stampSidecarHash = (plan: (typeof plans)[number]): void => {
1706
+ try {
1707
+ const sidecar = readJson(plan.jsonPath) as Record<string, unknown>;
1708
+ sidecar.hash = plan.hash;
1709
+ if (sidecar.metadata && typeof sidecar.metadata === 'object') {
1710
+ (sidecar.metadata as Record<string, unknown>).hash = plan.hash;
1711
+ }
1712
+ writeJsonText(plan.jsonPath, sidecar);
1713
+ } catch {}
1714
+ };
1715
+
1716
+ const buildSectionDocIn = (plan: (typeof plans)[number]): string => {
1697
1717
  const secScript = { ...script, segments: plan.def.segments };
1698
1718
  const secDocIn = join(secDir, `.${plan.def.stem}_in.json`);
1699
1719
  const doc = {
@@ -1705,40 +1725,111 @@ export function dailyGenerate(args: string[]): void {
1705
1725
  metadata: { voiceProfile },
1706
1726
  };
1707
1727
  writeJsonText(secDocIn, [doc]);
1708
- try {
1709
- // 0269-shaped hardening (20261012): one retry for a failed section. The design already
1710
- // bounds the episode's risk with the pre-flight quota probe and the per-section cache,
1711
- // but a failure that arrives MID-render (a 429 once the window drains, a network blip)
1712
- // still cost the whole episode — the one step nothing can publish without. The retry is
1713
- // cheap and bounded: the successful sections are cache hits, so at most one extra
1714
- // request per failed section is issued, and a persistent failure still fails loud.
1715
- let status = kk(voiceExecutorArgs(voiceGenerator, secDocIn, plan.jsonPath, pluginsPath), {
1716
- env: { VOICE_GEN_MP3: transcodeMp3 },
1728
+ return secDocIn;
1729
+ };
1730
+
1731
+ const BATCH_MANIFEST_CONFIG: Record<string, { envKey: string; filename: string; label: string }> = {
1732
+ 'voxcpm-tts': { envKey: 'VOXCPM_BATCH_MANIFEST', filename: '.voxcpm_batch.json', label: 'voxcpm' },
1733
+ 'vibe-voice-tts': {
1734
+ envKey: 'VIBEVOICE_BATCH_MANIFEST',
1735
+ filename: '.vibe-voice_batch.json',
1736
+ label: 'vibe-voice',
1737
+ },
1738
+ };
1739
+ const batchConfig = BATCH_MANIFEST_CONFIG[voiceGenerator];
1740
+ if (batchConfig && anySynthesisNeeded) {
1741
+ const pendingPlans = plans.filter((p) => p.needsSynthesis);
1742
+ for (const plan of plans) {
1743
+ if (!plan.needsSynthesis) {
1744
+ console.log(`generate: section cached: ${plan.def.stem}`);
1745
+ }
1746
+ }
1747
+ const secInputs = pendingPlans.map((p) => ({ plan: p, inPath: buildSectionDocIn(p) }));
1748
+ const batchManifestPath = join(secDir, batchConfig.filename);
1749
+ const runBatch = (items: typeof secInputs): number => {
1750
+ writeJsonText(
1751
+ batchManifestPath,
1752
+ items.map((item) => ({ in: item.inPath, out: item.plan.jsonPath })),
1753
+ );
1754
+ return kk(voiceExecutorArgs(voiceGenerator, items[0].inPath, items[0].plan.jsonPath, pluginsPath), {
1755
+ env: { VOICE_GEN_MP3: transcodeMp3, [batchConfig.envKey]: batchManifestPath },
1717
1756
  soft: true,
1718
1757
  });
1758
+ };
1759
+ try {
1760
+ console.log(
1761
+ `generate: synthesizing ${secInputs.length} ${batchConfig.label} section(s) in single-worker batch: ${secInputs.map((i) => i.plan.def.stem).join(', ')}`,
1762
+ );
1763
+ let status = runBatch(secInputs);
1764
+ for (const item of secInputs) {
1765
+ if (existsSync(item.plan.jsonPath) && validNativeAudio(item.plan.wavPath)) {
1766
+ stampSidecarHash(item.plan);
1767
+ }
1768
+ }
1719
1769
  if (status !== 0) {
1720
- console.log(
1721
- `generate: section ${plan.def.stem} synthesis failed (exit ${status}) — retrying it once`,
1770
+ const remaining = secInputs.filter(
1771
+ (item) => !existsSync(item.plan.jsonPath) || !validNativeAudio(item.plan.wavPath),
1722
1772
  );
1723
- status = kk(voiceExecutorArgs(voiceGenerator, secDocIn, plan.jsonPath, pluginsPath), {
1724
- env: { VOICE_GEN_MP3: transcodeMp3 },
1725
- soft: true,
1726
- });
1773
+ if (remaining.length > 0) {
1774
+ console.log(
1775
+ `generate: ${batchConfig.label} batch failed (exit ${status}) — retrying ${remaining.length} remaining section(s) once`,
1776
+ );
1777
+ status = runBatch(remaining);
1778
+ for (const item of remaining) {
1779
+ if (existsSync(item.plan.jsonPath) && validNativeAudio(item.plan.wavPath)) {
1780
+ stampSidecarHash(item.plan);
1781
+ }
1782
+ }
1783
+ } else {
1784
+ status = 0;
1785
+ }
1727
1786
  }
1728
1787
  if (status !== 0) {
1729
- failWith(status, `generate: section synthesis failed for ${plan.def.stem}`);
1788
+ failWith(status, `generate: ${batchConfig.label} batch section synthesis failed`);
1730
1789
  }
1731
1790
  } finally {
1732
- rmSync(secDocIn, { force: true });
1791
+ rmSync(batchManifestPath, { force: true });
1792
+ for (const item of secInputs) {
1793
+ rmSync(item.inPath, { force: true });
1794
+ }
1733
1795
  }
1734
- try {
1735
- const sidecar = readJson(plan.jsonPath) as Record<string, unknown>;
1736
- sidecar.hash = plan.hash;
1737
- if (sidecar.metadata && typeof sidecar.metadata === 'object') {
1738
- (sidecar.metadata as Record<string, unknown>).hash = plan.hash;
1796
+ } else {
1797
+ // Synthesize sections sequentially (concurrency 1)
1798
+ for (const plan of plans) {
1799
+ if (!plan.needsSynthesis) {
1800
+ console.log(`generate: section cached: ${plan.def.stem}`);
1801
+ continue;
1739
1802
  }
1740
- writeJsonText(plan.jsonPath, sidecar);
1741
- } catch {}
1803
+ console.log(`generate: synthesizing section: ${plan.def.stem}`);
1804
+ const secDocIn = buildSectionDocIn(plan);
1805
+ try {
1806
+ // 0269-shaped hardening (20261012): one retry for a failed section. The design already
1807
+ // bounds the episode's risk with the pre-flight quota probe and the per-section cache,
1808
+ // but a failure that arrives MID-render (a 429 once the window drains, a network blip)
1809
+ // still cost the whole episode — the one step nothing can publish without. The retry is
1810
+ // cheap and bounded: the successful sections are cache hits, so at most one extra
1811
+ // request per failed section is issued, and a persistent failure still fails loud.
1812
+ let status = kk(voiceExecutorArgs(voiceGenerator, secDocIn, plan.jsonPath, pluginsPath), {
1813
+ env: { VOICE_GEN_MP3: transcodeMp3 },
1814
+ soft: true,
1815
+ });
1816
+ if (status !== 0) {
1817
+ console.log(
1818
+ `generate: section ${plan.def.stem} synthesis failed (exit ${status}) — retrying it once`,
1819
+ );
1820
+ status = kk(voiceExecutorArgs(voiceGenerator, secDocIn, plan.jsonPath, pluginsPath), {
1821
+ env: { VOICE_GEN_MP3: transcodeMp3 },
1822
+ soft: true,
1823
+ });
1824
+ }
1825
+ if (status !== 0) {
1826
+ failWith(status, `generate: section synthesis failed for ${plan.def.stem}`);
1827
+ }
1828
+ } finally {
1829
+ rmSync(secDocIn, { force: true });
1830
+ }
1831
+ stampSidecarHash(plan);
1832
+ }
1742
1833
  }
1743
1834
 
1744
1835
  // Join sections with ffmpeg
@@ -1832,6 +1923,62 @@ export function dailyGenerate(args: string[]): void {
1832
1923
  });
1833
1924
  }
1834
1925
 
1926
+ /**
1927
+ * Delete a published episode's lossless audio intermediates: every section render (the synthesis
1928
+ * cache `dailyGenerate` reads), the joined final, and the `<stem>.intro.wav` merge output.
1929
+ *
1930
+ * Measured 2026-11-20: 987 MB of WAV across six daily runs — 80% of `.works/kk-news-generate` — for
1931
+ * 13–20 MB of MP3 per day. Nothing outside the run reads them: the podcast enclosure, `publish-prep`
1932
+ * and every retry window read the MP3, and `daily-intro` merged its copy inside the run.
1933
+ *
1934
+ * Guarded on the delivered artifact, never on a run status: a missing MP3 means the transcode
1935
+ * failed, and pruning then would turn the rebuild into a paid re-synthesis. Re-entering
1936
+ * `daily-generate` after a prune re-synthesizes the sections — the intended trade, since a
1937
+ * published day is not regenerated.
1938
+ */
1939
+ export function dailyAudioPrune(args: string[]): void {
1940
+ const [workDir = ''] = args;
1941
+ if (!workDir) fail('missing work_dir');
1942
+ const audioDir = join(workDir, '30-audio');
1943
+ if (!existsSync(audioDir)) {
1944
+ console.log(`audio-prune: no ${audioDir} — nothing to prune`);
1945
+ return;
1946
+ }
1947
+ const contentName = readdirSync(audioDir)
1948
+ .filter((entry) => /^\d{8}_11_generate_content\.json$/.test(entry))
1949
+ .sort()
1950
+ .at(-1);
1951
+ if (contentName === undefined) {
1952
+ console.log('audio-prune: no episode content in 30-audio — nothing to prune');
1953
+ return;
1954
+ }
1955
+ const content = readJson(join(audioDir, contentName));
1956
+ const recorded = [metadataOf(content).mp3Path, content?.mp3Path].find(
1957
+ (candidate): candidate is string => typeof candidate === 'string' && candidate !== '',
1958
+ );
1959
+ if (recorded === undefined || !isFile(resolve(recorded))) {
1960
+ console.log('audio-prune: publish MP3 not on disk — keeping the WAV intermediates');
1961
+ return;
1962
+ }
1963
+ const wavs: string[] = [];
1964
+ const collect = (dir: string): void => {
1965
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
1966
+ const path = join(dir, entry.name);
1967
+ if (entry.isDirectory()) collect(path);
1968
+ else if (entry.name.endsWith('.wav')) wavs.push(path);
1969
+ }
1970
+ };
1971
+ collect(audioDir);
1972
+ let freed = 0;
1973
+ for (const wav of wavs) {
1974
+ freed += statSync(wav).size;
1975
+ sted('remove', wav, () => rmSync(wav, { force: true }));
1976
+ }
1977
+ console.log(
1978
+ `audio-prune: removed ${wavs.length} WAV intermediate${wavs.length === 1 ? '' : 's'} (${(freed / 1048576).toFixed(1)} MB), kept ${basename(resolve(recorded))}`,
1979
+ );
1980
+ }
1981
+
1835
1982
  /**
1836
1983
  * 20260917 review #7: prepend the show's 8s intro sting to the generated audio.
1837
1984
  * `intro_music` empty -> skip. Writes `<stem>.intro.wav` (original render kept), points
@@ -2074,8 +2221,16 @@ export function buildWechatArticleContent(
2074
2221
  ): Record<string, unknown> {
2075
2222
  const wechatmp: Record<string, unknown> = {
2076
2223
  original: true,
2077
- // 赞赏 is enabled per episode; the plugin fills the 赞赏账户 only when the platform leaves it
2078
- // empty (it defaults from 作者, operator walk 2026-10-10).
2224
+ // 赞赏 is NOT requested: measured 2026-11-20 on a fresh 文章 draft, this account's row renders
2225
+ // `不开启 … 无法开启赞赏,因为还没有赞赏账户授权给本公众号` with a 0×0 box — the platform has not
2226
+ // authorized a 赞赏 account for 咸话咸说, so no selector, probe or retry can enable it, and asking
2227
+ // for it only converted a healthy draft into `ok:false` until `WECHATMP_ALLOW_PARTIAL_ENRICH=1`
2228
+ // was set by hand (11-16, 11-18, 11-19). Evidence:
2229
+ // `.spur/run/dogfood/2026-11-20-wechatmp-reward/survey-dom.json` (5806: reward row text + box).
2230
+ // If the operator opens 赞赏 later, flip this line back together with the probe in
2231
+ // `plugins/publishings/wechatmp-pub/src/enrich.ts` (`REWARD_STATE`).
2232
+ // 2026-11-20 operator request: 赞赏 ON. `WECHATMP_ALLOW_PARTIAL_ENRICH=1` is set, so a
2233
+ // still-unauthorized account warns once and keeps the healthy draft instead of failing it.
2079
2234
  reward: true,
2080
2235
  author: WECHAT_BRAND.author,
2081
2236
  collection: options.collection,
@@ -3986,8 +4141,9 @@ export function dailyPreflight(args: string[]): void {
3986
4141
  *
3987
4142
  * The gate stays authoritative on `block`/`revise`; the decision can only refuse an outcome the gate
3988
4143
  * already admitted. The decision replaced the judge's self-reported `confidence` field, which the
3989
- * accept guard used to re-parse in shell: its fallback is `escalate`, so missing or garbled evidence
3990
- * lands on a recorded human decision instead of a silent publish.
4144
+ * accept guard used to re-parse in shell: a JUDGED `escalate` now needs a human (the accept guard
4145
+ * refuses it for an unattended run), while an ABSTAINED row (`source: "default"` — the maker failed
4146
+ * and nothing was judged) is named on stderr and leaves the gate's own verdict in charge.
3991
4147
  *
3992
4148
  * Writes `24-script/<date>_09_safety-verdict.status` = `accept`, or `refuse` after naming the
3993
4149
  * offending value on stderr. Never exits non-zero: routing belongs to the transitions.
@@ -4006,9 +4162,22 @@ export function dailySafetyVerdict(args: string[]): void {
4006
4162
  // A missing/unreadable decision row is a refusal, never an approval: `onError: continue` on
4007
4163
  // the decide action is what can leave it absent.
4008
4164
  let verdict = '';
4165
+ // A maker that cannot answer does not silently vanish: it lands on the catalog fallback with
4166
+ // `source: "default"`, so name the abstention where the run report and triage can see it.
4167
+ // (2026-11-20: fm-local refuses safety-report text, so this is the caveat, not an edge case.)
4168
+ let abstention = '';
4009
4169
  if (isFile(decisionFile)) {
4010
- const row = JSON.parse(readFileSync(decisionFile, 'utf-8')) as { value?: unknown };
4170
+ const row = JSON.parse(readFileSync(decisionFile, 'utf-8')) as {
4171
+ value?: unknown;
4172
+ source?: unknown;
4173
+ degraded?: unknown;
4174
+ backend?: unknown;
4175
+ reason?: unknown;
4176
+ };
4011
4177
  verdict = String(row.value ?? '');
4178
+ if (row.source === 'default' || row.degraded === true) {
4179
+ abstention = `kk-daily-safety.judge.decision-abstained: kk-safety-verdict fell back to [${verdict}] (${String(row.backend ?? 'maker')}: ${String(row.reason ?? 'unknown')}) — nothing was judged, so the gate's [${status}] verdict stands alone`;
4180
+ }
4012
4181
  }
4013
4182
  let refusal = '';
4014
4183
  if (!ADMITTED.has(status)) {
@@ -4057,6 +4226,7 @@ export function dailySafetyVerdict(args: string[]): void {
4057
4226
  }
4058
4227
  }
4059
4228
  if (refusal !== '') console.error(refusal);
4229
+ else if (abstention !== '') console.error(abstention);
4060
4230
  sted('write', token, () => writeRaw(token, refusal === '' ? 'accept' : 'refuse'));
4061
4231
  if (evidence !== null) {
4062
4232
  const evidencePath = join(scopeDirOf(workDir, scopeDir), 'safety.json');
@@ -4196,6 +4366,63 @@ export function dailySafetyManifest(args: string[]): void {
4196
4366
  * skill's reference files, never here. 0331: an optional trailing scope_dir re-roots the whole
4197
4367
  * artifact set for the variants review (see the scope machinery above).
4198
4368
  */
4369
+ function buildSafetyDigest(
4370
+ workDir: string,
4371
+ scopeDir: string,
4372
+ runDate: string,
4373
+ targets: string[],
4374
+ digest: string,
4375
+ content: unknown[],
4376
+ ): string {
4377
+ const drafts = isDraftsScope(scopeDir);
4378
+ const lines: string[] = [
4379
+ `# Safety Review Digest (${runDate})`,
4380
+ '',
4381
+ `- Scope: ${drafts ? 'drafts' : 'variants'}`,
4382
+ `- Platforms: ${targets.join(', ')}`,
4383
+ `- Digest: \`${digest}\``,
4384
+ '',
4385
+ ];
4386
+ const maxCharsPerItem = 4000;
4387
+ for (const entry of content) {
4388
+ if (typeof entry === 'string') {
4389
+ if (!isFile(entry)) continue;
4390
+ const raw = readFileSync(entry, 'utf-8');
4391
+ let body = raw;
4392
+ if (entry.endsWith('.yaml') || entry.endsWith('.yml')) {
4393
+ try {
4394
+ const parsed = Bun.YAML.parse(raw) as {
4395
+ title?: string;
4396
+ segments?: Array<{ text?: string; speaker?: string }>;
4397
+ };
4398
+ const segs = Array.isArray(parsed?.segments)
4399
+ ? parsed.segments.map((s, idx) => `${idx + 1}. ${s.text ?? ''}`).join('\n')
4400
+ : raw;
4401
+ body = `${parsed?.title ? `Title: ${parsed.title}\n\n` : ''}${segs}`;
4402
+ } catch {}
4403
+ }
4404
+ const truncated = body.length > maxCharsPerItem ? `${body.slice(0, maxCharsPerItem)}\n…[truncated]` : body;
4405
+ lines.push(`## ${entry} (${raw.length} chars)`, '', truncated, '');
4406
+ } else if (entry && typeof entry === 'object') {
4407
+ const item = entry as { key?: string; path?: string };
4408
+ const rel = item.path ?? '';
4409
+ const abs = rel ? join(workDir, rel) : '';
4410
+ if (!abs || !isFile(abs)) continue;
4411
+ const raw = readFileSync(abs, 'utf-8');
4412
+ let summary = raw;
4413
+ try {
4414
+ const parsed = JSON.parse(raw) as { title?: string; body?: string; format?: string };
4415
+ const text = typeof parsed.body === 'string' ? parsed.body : raw;
4416
+ summary = `Title: ${parsed.title ?? ''}\nFormat: ${parsed.format ?? ''}\n\n${text}`;
4417
+ } catch {}
4418
+ const truncated =
4419
+ summary.length > maxCharsPerItem ? `${summary.slice(0, maxCharsPerItem)}\n…[truncated]` : summary;
4420
+ lines.push(`## ${item.key ?? rel} (${rel}, ${raw.length} chars)`, '', truncated, '');
4421
+ }
4422
+ }
4423
+ return lines.join('\n');
4424
+ }
4425
+
4199
4426
  export function dailySafetyPrep(args: string[]): void {
4200
4427
  const [workDir = '', runDate = '', platforms = '', scopeDir = ''] = args;
4201
4428
  const drafts = isDraftsScope(scopeDir);
@@ -4224,6 +4451,7 @@ export function dailySafetyPrep(args: string[]): void {
4224
4451
  }
4225
4452
  for (const name of [
4226
4453
  'safety-review_report.json',
4454
+ 'safety-review_digest.md',
4227
4455
  'safety-judge_verdict.json',
4228
4456
  'safety-judge_status.txt',
4229
4457
  'safety-judge_stamp.json',
@@ -4241,17 +4469,23 @@ export function dailySafetyPrep(args: string[]): void {
4241
4469
  if (isFile(stale)) unlinkSync(stale);
4242
4470
  }
4243
4471
  const request = scopeArtifact(workDir, scopeDir, runDate, 'safety-review_request.json');
4472
+ const digestFile = scopeArtifact(workDir, scopeDir, runDate, 'safety-review_digest.md');
4244
4473
  const targets = platforms
4245
4474
  .split(',')
4246
4475
  .map((platform) => platform.trim())
4247
4476
  .filter(Boolean);
4477
+ const content = scopeContent(workDir, scopeDir, runDate);
4478
+ sted('write', digestFile, () =>
4479
+ writeRaw(digestFile, buildSafetyDigest(workDir, scopeDir, runDate, targets, digest, content)),
4480
+ );
4248
4481
  sted('write', request, () =>
4249
4482
  writeJsonText(request, {
4250
4483
  digest,
4484
+ digestFile,
4251
4485
  platforms: targets,
4252
4486
  mode: 'detect-only',
4253
4487
  scope: drafts ? 'drafts' : 'variants',
4254
- content: scopeContent(workDir, scopeDir, runDate),
4488
+ content,
4255
4489
  }),
4256
4490
  );
4257
4491
  });
@@ -4465,7 +4699,7 @@ function spokenCharRate(vdriver: string): number {
4465
4699
  // voxcpm measured the same day on a 12-section zh+en episode: 6,772 chars / 1,297.7 s speech
4466
4700
  // (5.19 字/秒). The provisional 5.6 borrowed from voicebox let the fit budget reach 7,683 chars
4467
4701
  // — 24.6 min of audio, 18 s inside the 25-min gate. 5.2 puts a full-budget script at ~22.9 min.
4468
- if (vdriver === 'voxcpm') return 5.2;
4702
+ if (vdriver === 'voxcpm' || vdriver === 'vibe-voice' || vdriver === 'vibevoice') return 5.2;
4469
4703
  return 5.6;
4470
4704
  }
4471
4705
 
@@ -57,7 +57,7 @@ import {
57
57
  writeFileSync,
58
58
  } from 'node:fs';
59
59
  import { homedir } from 'node:os';
60
- import { basename, dirname, join, resolve } from 'node:path';
60
+ import { basename, dirname, join, relative, resolve } from 'node:path';
61
61
  import { compositeCover } from './cover-compositor';
62
62
 
63
63
  export const SCRIPTS_DIR = import.meta.dir;
@@ -1661,6 +1661,35 @@ function publishMatrixPatchSurfdash(args: string[]): void {
1661
1661
  });
1662
1662
  }
1663
1663
 
1664
+ /**
1665
+ * The day's zh post path when this run's content sits uncommitted in the surfdash checkout.
1666
+ *
1667
+ * `surfdash-pub` writes the post and its `assets/` into the checkout before it syncs the CMS, and the
1668
+ * daily patch stage is the only step that commits them. A publish that fails, or a window whose plan
1669
+ * excludes the surfdash target, leaves the write behind with no commit, so the deploy never sees the
1670
+ * post — its `./assets/cover.png` 404s on the live site while the run reports only a warning. This
1671
+ * finds that state (untracked or modified paths under `content/posts` whose slug starts with the run
1672
+ * date) so the patch can heal it instead of looking at a missing receipt and skipping.
1673
+ */
1674
+ function strandedSurfdashPost(root: string, runDate: string): string | undefined {
1675
+ const listed = spawnSync('git', ['-C', root, 'status', '--porcelain', '-z', '--', 'content/posts'], {
1676
+ encoding: 'utf-8',
1677
+ });
1678
+ if (listed.status !== 0) return undefined;
1679
+ const slugs = new Set<string>();
1680
+ // `-z` entries are `XY <path>` NUL-separated, so the status prefix plus its space is 3 chars.
1681
+ for (const entry of (listed.stdout ?? '').split('\u0000')) {
1682
+ const match = /content\/posts\/articles\/(?:zh|en|ja)\/([^/]+)/.exec(entry.slice(3));
1683
+ const slug = match?.[1];
1684
+ if (slug?.startsWith(runDate)) slugs.add(slug);
1685
+ }
1686
+ for (const slug of slugs) {
1687
+ const zh = join(root, 'content', 'posts', 'articles', 'zh', slug, 'index.md');
1688
+ if (isFile(zh)) return zh;
1689
+ }
1690
+ return undefined;
1691
+ }
1692
+
1664
1693
  function dailyPatchSurfdash(args: string[]): void {
1665
1694
  const [workDir = '', runDate = '', surfdashRoot = '', pluginsPath = ''] = args;
1666
1695
  if (!surfdashRoot || !existsSync(surfdashRoot)) {
@@ -1683,20 +1712,30 @@ function dailyPatchSurfdash(args: string[]): void {
1683
1712
  )
1684
1713
  );
1685
1714
  };
1686
- if (invalidReceipt(sdResult) || invalidReceipt(podcastResult)) {
1687
- const error = 'patch-surfdash: malformed surfdash/podcast publish receipt — nothing to patch';
1688
- sted('write', resultPath, () => writeJqText(resultPath, { ok: false, target: 'surfdash-pub', error }));
1689
- console.error(error);
1690
- return;
1691
- }
1715
+ const sdUsable = !invalidReceipt(sdResult);
1716
+ const podUsable = !invalidReceipt(podcastResult);
1692
1717
  const targetOf = (path: string): Record<string, unknown> => {
1693
1718
  const parsed = readJson(path) as { targets?: Array<Record<string, unknown>> };
1694
1719
  return parsed.targets?.[0] ?? {};
1695
1720
  };
1696
- const sd = targetOf(sdResult);
1697
- const pod = targetOf(podcastResult);
1698
- const postPath = (sd.metadata as Record<string, unknown> | undefined)?.postPath;
1699
- if (typeof postPath !== 'string' || postPath === '') {
1721
+ const sd = sdUsable ? targetOf(sdResult) : {};
1722
+ const pod = podUsable ? targetOf(podcastResult) : {};
1723
+ const receiptPath = (sd.metadata as Record<string, unknown> | undefined)?.postPath;
1724
+ const fromReceipt = typeof receiptPath === 'string' && receiptPath !== '' ? receiptPath : undefined;
1725
+ // The publisher writes the post and its `assets/` into the checkout *before* it syncs the CMS,
1726
+ // and only this stage commits them. A publish that fails — or a window whose plan excludes the
1727
+ // surfdash target (2026-11-20: `not in --channels list`) — leaves that write behind with no
1728
+ // commit, so the deploy never sees the post and its `./assets/cover.png` 404s while the run
1729
+ // reports nothing worse than a warning. Heal that state instead of skipping it.
1730
+ const stranded = fromReceipt === undefined ? strandedSurfdashPost(surfdashRoot, runDate) : undefined;
1731
+ const postPath = fromReceipt ?? stranded;
1732
+ if (postPath === undefined) {
1733
+ if (!sdUsable || !podUsable) {
1734
+ const error = 'patch-surfdash: malformed surfdash/podcast publish receipt — nothing to patch';
1735
+ sted('write', resultPath, () => writeJqText(resultPath, { ok: false, target: 'surfdash-pub', error }));
1736
+ console.error(error);
1737
+ return;
1738
+ }
1700
1739
  // A surfdash publish that never landed (2026-10-21: its `git push` was rejected with
1701
1740
  // `fetch first`) leaves no postPath to patch. `publish-classify` has already recorded the
1702
1741
  // run as `partial`, and failing here turned a published podcast episode into a `failed`
@@ -1704,6 +1743,11 @@ function dailyPatchSurfdash(args: string[]): void {
1704
1743
  console.error('patch-surfdash: surfdash result carries no postPath — nothing to patch, skip');
1705
1744
  return;
1706
1745
  }
1746
+ if (fromReceipt === undefined) {
1747
+ console.error(
1748
+ `patch-surfdash: no surfdash publish receipt, but ${relative(surfdashRoot, postPath)} is uncommitted in the checkout — patching it so the deploy ships the post and its cover`,
1749
+ );
1750
+ }
1707
1751
  if (process.env.KK_SURFDASH_PATCH_OFFLINE === '1') {
1708
1752
  // The marker keeps the completeness report's cms-resync row honest in offline runs.
1709
1753
  const skipMarker = join(workDir, '31-publish', `${runDate}_23_patch-surfdash_emdash-resync.txt`);
@@ -1713,6 +1757,19 @@ function dailyPatchSurfdash(args: string[]): void {
1713
1757
  }
1714
1758
  const payload = join(workDir, '31-publish', `${runDate}_23_patch-surfdash_patch.json`);
1715
1759
  const podcastMeta = (pod.metadata ?? {}) as Record<string, unknown>;
1760
+ // 0385 R4: the episode's frozen identity title is what the podcast ships (`第<issue>期 · <headline>`).
1761
+ // The article states the same identity — the site renders it under its own SEO title, and the
1762
+ // zh cross-link names it — so the two surfaces cannot carry different episode names.
1763
+ const identity = readJson(join(workDir, '21-plan', `${runDate}_05_script_identity.json`)) as {
1764
+ title?: unknown;
1765
+ status?: unknown;
1766
+ } | null;
1767
+ const episodeTitle = identity?.status === 'frozen' && typeof identity.title === 'string' ? identity.title : '';
1768
+ if (episodeTitle === '') {
1769
+ console.error(
1770
+ `patch-surfdash: no frozen episode identity in 21-plan/${runDate}_05_script_identity.json — the article keeps the series · date wording`,
1771
+ );
1772
+ }
1716
1773
  sted('write', payload, () =>
1717
1774
  writeJqText(payload, {
1718
1775
  body: '',
@@ -1723,6 +1780,7 @@ function dailyPatchSurfdash(args: string[]): void {
1723
1780
  showNotesUrl: typeof pod.url === 'string' ? pod.url : '',
1724
1781
  dateIso: `${runDate.slice(0, 4)}-${runDate.slice(4, 6)}-${runDate.slice(6, 8)}`,
1725
1782
  localCover: join(workDir, '23-cover', `${runDate}_07_cover_cover.png`),
1783
+ episodeTitle,
1726
1784
  },
1727
1785
  }),
1728
1786
  );
@@ -2064,6 +2122,11 @@ if (import.meta.main)
2064
2122
  case 'daily-publish-completeness':
2065
2123
  dailyPublishCompleteness(rest);
2066
2124
  break;
2125
+ case 'audio-prune': {
2126
+ const { dailyAudioPrune } = await loadDailyStages();
2127
+ dailyAudioPrune(rest);
2128
+ break;
2129
+ }
2067
2130
  case 'daily-patch-surfdash':
2068
2131
  dailyPatchSurfdash(rest);
2069
2132
  break;
@@ -8,7 +8,8 @@ import { spawnSync } from 'node:child_process';
8
8
  * missing or malformed artifact takes the bounded retry edge. The revision predicate also uses the
9
9
  * safety request digest rather than Spur's Git working-tree `requireDiff` contract because daily
10
10
  * drafts live under the ignored `.works` tree. The publish predicate keeps a real safety escalation
11
- * out of unattended publication without mistaking a catalog fallback value for one.
11
+ * out of unattended publication, from either classifier, without mistaking an ABSTAINED decision
12
+ * (the maker failed, nothing was judged) for one.
12
13
  */
13
14
  import { createHash } from 'node:crypto';
14
15
  import { readFileSync } from 'node:fs';
@@ -147,9 +148,24 @@ function judgeValid(workDir: string, scopeDir: string, runDate: string): string
147
148
  }
148
149
 
149
150
  /**
150
- * The catalog decision may fall back to `escalate` even when the gate admitted `pass` or `exclude`.
151
- * Only the gate's persisted status represents a real content-safety escalation, so unattended mode
152
- * rejects that status while attended mode leaves it for the caller's pause node.
151
+ * The final publish contract for unattended publication, over the fold token, the gate's status and
152
+ * the catalog decision row.
153
+ *
154
+ * Two independent classifiers share one `pass|escalate|exclude` vocabulary, and an `escalate` from
155
+ * either means a human has to look:
156
+ *
157
+ * - **the gate's persisted status** (report + judge verdict + contract checks) — the authority on
158
+ * `block`/`revise`, and a real `escalate` there refuses unattended publication;
159
+ * - **the `kk-safety-verdict` catalog decision** — its `escalate` is a judged verdict ("the evidence
160
+ * cannot settle this"), so an unattended run refuses it too. 0317 R6 admitted every escalate here,
161
+ * which let a judged escalation publish under `--skip-review` with no human anywhere.
162
+ *
163
+ * The SAME row is also where a maker failure lands: `source: "default"` + `degraded: true` means the
164
+ * decision ABSTAINED and nothing was judged (measured 2026-11-20 on fm-local, whose guardrails refuse
165
+ * safety-report text — 9 asks since 11-05, every one "The model refused to answer"). An abstention is
166
+ * not a verdict, so the gate's own verdict stands and the run publishes; `daily-safety-verdict`
167
+ * records it on stderr. A row that names no provenance is treated the same way: absent evidence of a
168
+ * judgement is not evidence of one.
153
169
  */
154
170
  function publishValid(workDir: string, scopeDir: string, runDate: string, unattendedArg: string): string | null {
155
171
  if (unattendedArg !== 'true' && unattendedArg !== 'false') return 'unattended must be true or false';
@@ -167,8 +183,15 @@ function publishValid(workDir: string, scopeDir: string, runDate: string, unatte
167
183
  if (!new Set(['pass', 'exclude', 'escalate']).has(gateStatus)) {
168
184
  return `gate status ${gateStatus || 'missing'} is not publish-valid`;
169
185
  }
170
- if (unattendedArg === 'true' && gateStatus === 'escalate') {
186
+ if (unattendedArg !== 'true') return null;
187
+ if (gateStatus === 'escalate')
171
188
  return 'unattended run refuses a real safety escalation; attended review is required';
189
+ const decision = readJson(safetyPath(workDir, scopeDir, runDate, 'safety-verdict.decision'));
190
+ const judgedEscalate =
191
+ String(decision?.value ?? '') === 'escalate' && decision?.source === 'model' && decision?.degraded !== true;
192
+ if (judgedEscalate) {
193
+ const confidence = String(decision?.confidenceLevel ?? 'unstated');
194
+ return `kk-safety-verdict escalated on the evidence (confidence ${confidence}) — the decision requires a human, so an unattended run must not publish`;
172
195
  }
173
196
  return null;
174
197
  }
@@ -22,8 +22,9 @@ vars:
22
22
  language: "zh"
23
23
  voice_profile: "robin-news"
24
24
  # Voice driver switch — voicebox (voice-gen) | ominivoice (omni-voice-gen) | gemini (gemini-tts)
25
- # | voxcpm (voxcpm-tts, opt-in; ADR-036). VoxCPM never probes Gemini and never falls back; its
26
- # 5.6 字/秒 spoken-rate estimate is PROVISIONAL until 0258 measures a real render.
25
+ # | voxcpm (voxcpm-tts, opt-in; ADR-036) | vibe-voice / vibevoice (vibe-voice-tts, opt-in; ADR-055).
26
+ # VoxCPM and VibeVoice never probe Gemini and never fall back; their
27
+ # 5.6 字/秒 spoken-rate estimate is PROVISIONAL until measured on live episodes.
27
28
  # 20260917 introduced the switch; 20260920 flipped default to voicebox after an operator A/B;
28
29
  # 20260929 operator override: gemini-tts is the default again (verified live on this machine —
29
30
  # robin-news replicated profile, GEMINI_API_KEY + GEMINI_TTS_MODEL via ~/.config/kk/config.yaml
@@ -405,7 +406,7 @@ states:
405
406
  kk stage daily-wrap-docs "${vars.work_dir}" "${vars.run_date}" "${vars.voice_profile}"
406
407
 
407
408
  - id: generate
408
- description: "Invoke voice driver plugin (vdriver var: ominivoice -> omni-voice-gen, voicebox -> voice-gen, gemini -> gemini-tts, voxcpm -> voxcpm-tts) to generate audio"
409
+ description: "Invoke voice driver plugin (vdriver var: ominivoice -> omni-voice-gen, voicebox -> voice-gen, gemini -> gemini-tts, voxcpm -> voxcpm-tts, vibe-voice/vibevoice -> vibe-voice-tts) to generate audio"
409
410
  onEnter:
410
411
  - kind: shell
411
412
  options: