@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,11 +3,22 @@ import { readFileSync, writeFileSync } from 'node:fs';
3
3
  import { readFile } from 'node:fs/promises';
4
4
  import { basename, dirname, extname, join } from 'node:path';
5
5
  import { parseArgs } from 'node:util';
6
- import { type Content, ContentSchema, DocListSchema, type Result, ResultSchema } from '@gobing-ai/kk-core';
6
+ import { type Content, ContentSchema, type Doc, DocListSchema, type Result, ResultSchema } from '@gobing-ai/kk-core';
7
7
  import { FakeFileCliTransport, type PublishTransport, type PublishTransportPayload } from '@gobing-ai/publish-harness';
8
8
  import { createNodeFileSystem } from '@gobing-ai/ts-runtime';
9
9
  import { echoError } from '@gobing-ai/ts-utils';
10
10
  import { runBackfill } from './backfill';
11
+ import {
12
+ type CorrectionDeliveryTarget,
13
+ correctionDeliveryPath,
14
+ type FrozenCorrectionSet,
15
+ planCorrectionDeliveries,
16
+ readCorrectionDeliveries,
17
+ readFrozenCorrections,
18
+ recordCorrectionDeliveries,
19
+ renderCorrectionsBlock,
20
+ writeCorrectionDeliveries,
21
+ } from './corrections';
11
22
  import { type EpisodeMapping, mapContentToEpisode } from './map';
12
23
  import {
13
24
  MicrofeedClient,
@@ -25,6 +36,7 @@ import {
25
36
  warn,
26
37
  } from './seo';
27
38
  import { renderShowNotesMarkdown, type ShowNotesRenderOptions } from './show-notes';
39
+ import { applyArticleReceipt, renderBriefShowNotes } from './show-notes-brief';
28
40
  import { buildTranscriptSegments, renderWebVtt, resolveTranscriptConfig, transcriptReferences } from './transcript';
29
41
 
30
42
  /** Result target name for this plugin. */
@@ -78,6 +90,13 @@ interface PodcastPubOptions {
78
90
  rewriteBody?: unknown;
79
91
  applySlug?: unknown;
80
92
  overrides?: unknown;
93
+ /**
94
+ * 0396 R2 — the other 0388 targets this episode's correction must reach, as the dispatch ledger
95
+ * sees them (`{target, mode, state, manualStep, blockedBy, lastError, supportsCorrections,
96
+ * capabilityReason}`). Each row yields one delivery record with an exact reason; a row that is
97
+ * manual/blocked/unsupported is recorded as such and never as `delivered`.
98
+ */
99
+ correctionTargets?: unknown;
81
100
  }
82
101
 
83
102
  /** Re-reads env each call so tests can set credentials without constructor plumbing (design D4). */
@@ -210,6 +229,44 @@ function resolveShowNotesRenderOptions(
210
229
  };
211
230
  }
212
231
 
232
+ /**
233
+ * 0396 R1 — the frozen correction projection, read from the snapshot path the stage passes in
234
+ * (`PODCAST_PUB_CORRECTIONS`, 0384's `21-plan/<date>_judgment-snapshot.json`).
235
+ *
236
+ * `null` = the caller configured no corrections for this run (the documented "no frozen judgment"
237
+ * case: no block, no heading). A configured-but-unreadable snapshot is an exact, path-naming error —
238
+ * never a silent "there is no correction", because a swallowed correction is a public error left
239
+ * unacknowledged.
240
+ */
241
+ function resolveCorrectionSet(): { set: FrozenCorrectionSet } | { error: string } | null {
242
+ const path = resolveOptionString(undefined, 'PODCAST_PUB_CORRECTIONS');
243
+ if (path === undefined) return null;
244
+ try {
245
+ const parsed: unknown = JSON.parse(readFileSync(path, 'utf-8'));
246
+ return {
247
+ set: readFrozenCorrections(parsed, {
248
+ runDate: resolveOptionString(undefined, 'PODCAST_PUB_RUN_DATE') ?? null,
249
+ }),
250
+ };
251
+ } catch (error: unknown) {
252
+ return {
253
+ error: `corrections: cannot read the frozen judgment snapshot ${path} (${error instanceof Error ? error.message : String(error)}) — the correction block is NOT carried; fix the snapshot path before publishing`,
254
+ };
255
+ }
256
+ }
257
+
258
+ /**
259
+ * Places the correction block directly under the episode title (the first markdown line), so the
260
+ * acknowledgement is the first thing a reader hears/reads under the episode identity 0385 froze. The
261
+ * block itself carries its own `## 本期更正说明` heading; with no block the markdown is byte-identical.
262
+ */
263
+ function insertCorrectionBlock(markdown: string, block: string | null): string {
264
+ if (block === null) return markdown;
265
+ const split = markdown.indexOf('\n');
266
+ if (split === -1) return `${markdown}\n\n${block}`;
267
+ return `${markdown.slice(0, split)}\n\n${block}${markdown.slice(split + 1)}`;
268
+ }
269
+
213
270
  /** Validates the plan Doc[] and renders show-notes markdown (pure render; no microfeed call). */
214
271
  function renderShowNotesFromOptions(
215
272
  options: ShowNotesOpOptions,
@@ -222,7 +279,85 @@ function renderShowNotesFromOptions(
222
279
  const renderOptions = resolveShowNotesRenderOptions(options);
223
280
  if ('error' in renderOptions) return { error: renderOptions.error };
224
281
  const warnings: string[] = [];
225
- return { markdown: renderShowNotesMarkdown(docs.data, renderOptions.renderOptions, warnings), warnings };
282
+ const corrections = resolveCorrectionSet();
283
+ if (corrections !== null && 'error' in corrections) return { error: corrections.error };
284
+ const block = corrections === null ? null : renderCorrectionsBlock(corrections.set);
285
+ if (corrections !== null) {
286
+ // Malformed/duplicate frozen entries are reported, never silently dropped (R1: an owed
287
+ // correction must be visible in the run log even when the block carries the valid ones).
288
+ for (const diagnostic of corrections.set.diagnostics) {
289
+ warnings.push(`WARN podcast-pub: correction ${diagnostic}`);
290
+ }
291
+ }
292
+ const withCorrections = (markdown: string): string => insertCorrectionBlock(markdown, block);
293
+ const brief = resolveBriefNotes(docs.data, renderOptions.renderOptions, warnings);
294
+ if (brief !== null) return { markdown: withCorrections(brief.markdown), warnings };
295
+ return {
296
+ markdown: withCorrections(renderShowNotesMarkdown(docs.data, renderOptions.renderOptions, warnings)),
297
+ warnings,
298
+ };
299
+ }
300
+
301
+ /**
302
+ * 0386 R1 — the brief notes path: cards, or the explicit no-receipt review mode, switch the render
303
+ * from the legacy layout to the brief/timeline/card renderer ({@link renderBriefShowNotes}). The
304
+ * article link still comes **only** from the publish receipt's `postPath` (never from the title);
305
+ * a missing receipt leaves a text placeholder the notes can be reviewed with. Card problems go to
306
+ * the separate diagnostics file (`PODCAST_PUB_CARDS_DIAGNOSTICS`) and the warning channel, never
307
+ * into the markdown. Returns `null` when this is not a brief-notes render.
308
+ */
309
+ function resolveBriefNotes(
310
+ docs: Doc[],
311
+ renderOptions: ShowNotesRenderOptions,
312
+ warnings: string[],
313
+ ): { markdown: string; warnings: string[] } | null {
314
+ const cardsPath = resolveOptionString(undefined, 'PODCAST_PUB_CARDS');
315
+ const reviewMode = process.env.PODCAST_PUB_BRIEF_WITHOUT_RECEIPT === 'true';
316
+ if (renderOptions.briefMode !== true || (cardsPath === undefined && !reviewMode)) return null;
317
+ let cards: unknown;
318
+ if (cardsPath !== undefined) {
319
+ try {
320
+ cards = JSON.parse(readFileSync(cardsPath, 'utf-8'));
321
+ } catch (error) {
322
+ warnings.push(`WARN podcast-pub: unreadable card manifest ${cardsPath}: ${(error as Error).message}`);
323
+ }
324
+ }
325
+ const rendered = renderBriefShowNotes({
326
+ docs,
327
+ ...(renderOptions.title !== undefined ? { title: renderOptions.title } : {}),
328
+ ...(renderOptions.audioSegments !== undefined ? { audioSegments: renderOptions.audioSegments } : {}),
329
+ ...(cards !== undefined ? { cards } : {}),
330
+ });
331
+ for (const diagnostic of rendered.diagnostics) {
332
+ warnings.push(`WARN podcast-pub: card ${diagnostic.index} ${diagnostic.reason}: ${diagnostic.detail}`);
333
+ }
334
+ const diagnosticsPath = resolveOptionString(undefined, 'PODCAST_PUB_CARDS_DIAGNOSTICS');
335
+ if (diagnosticsPath !== undefined) {
336
+ try {
337
+ writeFileSync(
338
+ diagnosticsPath,
339
+ `${JSON.stringify({ runDate: renderOptions.runDate, cards: rendered.diagnostics }, null, 2)}\n`,
340
+ 'utf-8',
341
+ );
342
+ } catch (error) {
343
+ warnings.push(`WARN podcast-pub: cannot write card diagnostics: ${(error as Error).message}`);
344
+ }
345
+ }
346
+ // The receipt's postPath is the only link source; absent ⇒ the placeholder stays (R1).
347
+ const postPath = renderOptions.articlePostPath ?? '';
348
+ const enriched =
349
+ postPath === ''
350
+ ? { markdown: rendered.markdown, enriched: false }
351
+ : applyArticleReceipt(
352
+ rendered.markdown,
353
+ { ok: true, target: TARGET, metadata: { postPath } },
354
+ renderOptions.articleBaseUrl,
355
+ );
356
+ if (postPath === '') {
357
+ warnings.push('WARN podcast-pub: no article receipt yet — notes rendered without an article link');
358
+ }
359
+ const footer = renderOptions.footerNote !== undefined ? `\n${renderOptions.footerNote}\n` : '';
360
+ return { markdown: `${enriched.markdown}${footer}`, warnings };
226
361
  }
227
362
 
228
363
  /** Episode-assembly options (R2): present keys make the plugin merge article + audio + cover itself. */
@@ -516,6 +651,101 @@ function mappedValidateInput(content: Content): MicrofeedItemInput {
516
651
  };
517
652
  }
518
653
 
654
+ /** Untrusted `options.correctionTargets` rows → the classifier's target shape (unknown keys dropped). */
655
+ function readCorrectionTargets(raw: unknown): CorrectionDeliveryTarget[] {
656
+ if (!Array.isArray(raw)) return [];
657
+ const targets: CorrectionDeliveryTarget[] = [];
658
+ for (const entry of raw) {
659
+ if (entry === null || typeof entry !== 'object') continue;
660
+ const row = entry as Record<string, unknown>;
661
+ const target = typeof row.target === 'string' ? row.target.trim() : '';
662
+ if (target === '') continue;
663
+ const blockedBy = Array.isArray(row.blockedBy) ? row.blockedBy.filter((id) => typeof id === 'string') : [];
664
+ targets.push({
665
+ target,
666
+ ...(typeof row.mode === 'string' ? { mode: row.mode } : {}),
667
+ ...(typeof row.state === 'string' ? { state: row.state } : {}),
668
+ ...(typeof row.manualStep === 'string' ? { manualStep: row.manualStep } : {}),
669
+ ...(typeof row.lastError === 'string' ? { lastError: row.lastError } : {}),
670
+ ...(blockedBy.length > 0 ? { blockedBy: blockedBy as string[] } : {}),
671
+ // Absent capability facts mean "unknown" and are treated as unsupported on purpose: a
672
+ // correction is never recorded as delivered to a target whose surface we cannot name.
673
+ supportsCorrections: row.supportsCorrections === true,
674
+ ...(typeof row.capabilityReason === 'string' ? { capabilityReason: row.capabilityReason } : {}),
675
+ ...(typeof row.deliveryEvidence === 'string' ? { deliveryEvidence: row.deliveryEvidence } : {}),
676
+ });
677
+ }
678
+ return targets;
679
+ }
680
+
681
+ /**
682
+ * 0396 R1/R2 — record where this episode's correction was delivered.
683
+ *
684
+ * The podcast target is classified from the publish that just happened (`dispatched` when the item
685
+ * went live, `pending` while it is a draft), the other targets from the 0388 dispatch rows the stage
686
+ * forwards. The ledger lands at `PODCAST_PUB_CORRECTION_DELIVERY` (defaulted by the stage to
687
+ * `31-publish/<date>_16_corrections-delivery.json`); every non-delivered row prints its EXACT
688
+ * target-level reason into the warning channel instead of being folded into a generic failure.
689
+ * Returns the delivered rows for the publish result's metadata.
690
+ */
691
+ async function recordCorrectionDelivery(
692
+ options: PodcastPubOptions,
693
+ episodeStatus: string,
694
+ delivery: { itemId?: string; url?: string },
695
+ warnings: string[],
696
+ ): Promise<{ correctionIds: string[]; delivered: string[] } | null> {
697
+ const corrections = resolveCorrectionSet();
698
+ if (corrections === null || 'error' in corrections) {
699
+ if (corrections !== null && 'error' in corrections) warnings.push(`WARN podcast-pub: ${corrections.error}`);
700
+ return null;
701
+ }
702
+ if (corrections.set.corrections.length === 0) return null;
703
+ const runDate = corrections.set.runDate;
704
+ const path = resolveOptionString(undefined, 'PODCAST_PUB_CORRECTION_DELIVERY');
705
+ const targets: CorrectionDeliveryTarget[] = [
706
+ {
707
+ target: TARGET,
708
+ state: episodeStatus === 'published' ? 'dispatched' : 'pending',
709
+ supportsCorrections: true,
710
+ },
711
+ ...readCorrectionTargets(options.correctionTargets),
712
+ ];
713
+ const ledgerPath = path ?? (runDate === null ? undefined : correctionDeliveryPath(process.cwd(), runDate));
714
+ const ledger = ledgerPath === undefined ? null : await readCorrectionDeliveries(ledgerPath, runDate);
715
+ const planned = planCorrectionDeliveries(corrections.set, targets, {
716
+ runDate,
717
+ prior: ledger?.deliveries ?? [],
718
+ }).map((entry) =>
719
+ // The published item is the traceable address of a delivery to this target.
720
+ entry.state === 'delivered' && entry.target === TARGET
721
+ ? {
722
+ ...entry,
723
+ ...(delivery.itemId === undefined ? {} : { itemId: delivery.itemId }),
724
+ ...(delivery.url === undefined ? {} : { url: delivery.url }),
725
+ }
726
+ : entry,
727
+ );
728
+ for (const entry of planned) {
729
+ if (entry.state === 'delivered') continue;
730
+ warnings.push(
731
+ `WARN podcast-pub: correction ${entry.correctionId} not delivered to target "${entry.target}" — ${entry.reason}`,
732
+ );
733
+ }
734
+ if (ledger !== null && ledgerPath !== undefined) {
735
+ const { ledger: next, skipped } = recordCorrectionDeliveries(ledger, planned);
736
+ await writeCorrectionDeliveries(ledgerPath, next);
737
+ for (const entry of skipped) {
738
+ warnings.push(
739
+ `WARN podcast-pub: correction ${entry.correctionId} already delivered to target "${entry.target}" — not re-sent`,
740
+ );
741
+ }
742
+ }
743
+ return {
744
+ correctionIds: corrections.set.corrections.map((entry) => entry.correctionId),
745
+ delivered: planned.filter((entry) => entry.state === 'delivered').map((entry) => entry.target),
746
+ };
747
+ }
748
+
519
749
  /**
520
750
  * Two-phase publish (design D2, the only legal order): create a draft item →
521
751
  * presign with `item_id` → PUT bytes → PUT item with attachment + target status.
@@ -608,13 +838,27 @@ async function publishEpisode(
608
838
  } catch {
609
839
  hostedItem = undefined;
610
840
  }
841
+ const hostedUrl = publicItemUrl(hostedItem, itemId, client);
842
+ const corrections = await recordCorrectionDelivery(
843
+ options,
844
+ String(episode.status),
845
+ { itemId, url: hostedUrl },
846
+ fields.warnings,
847
+ );
611
848
  return ResultSchema.parse({
612
849
  ok: true,
613
850
  target: TARGET,
614
- url: publicItemUrl(hostedItem, itemId, client),
851
+ url: hostedUrl,
615
852
  id: itemId,
616
853
  message: 'Published successfully to microfeed (hosted audio, single-call create)',
617
- ...(fields.warnings.length > 0 ? { metadata: { warnings: fields.warnings } } : {}),
854
+ ...(fields.warnings.length > 0 || corrections !== null
855
+ ? {
856
+ metadata: {
857
+ ...(corrections !== null ? { corrections } : {}),
858
+ ...(fields.warnings.length > 0 ? { warnings: fields.warnings } : {}),
859
+ },
860
+ }
861
+ : {}),
618
862
  });
619
863
  }
620
864
 
@@ -672,10 +916,17 @@ async function publishEpisode(
672
916
  ...episodeExtras(episode, seo),
673
917
  });
674
918
 
919
+ const publishedUrl = publicItemUrl(item, itemId, client);
920
+ const corrections = await recordCorrectionDelivery(
921
+ options,
922
+ String(episode.status),
923
+ { itemId, url: publishedUrl },
924
+ fields.warnings,
925
+ );
675
926
  return ResultSchema.parse({
676
927
  ok: true,
677
928
  target: TARGET,
678
- url: publicItemUrl(item, itemId, client),
929
+ url: publishedUrl,
679
930
  id: itemId,
680
931
  message: 'Published successfully to microfeed (two-phase upload + publish)',
681
932
  // 20260917 review #6: downstream surfdash patch reuses the podcast-hosted cover URL
@@ -683,6 +934,7 @@ async function publishEpisode(
683
934
  metadata: {
684
935
  itemId,
685
936
  imageUrl: imageUrl ?? null,
937
+ ...(corrections !== null ? { corrections } : {}),
686
938
  ...(fields.warnings.length > 0 ? { warnings: fields.warnings } : {}),
687
939
  },
688
940
  });
@@ -0,0 +1,240 @@
1
+ /**
2
+ * 0386 R1 — the brief, sourced, measured-timeline, card-bearing show notes rendered from the
3
+ * frozen episode artifacts (final spoken items, 0394 citation provenance, measured audio offsets,
4
+ * the published card order). Design D6.1 / L3 §单一标题、备注与封面:
5
+ *
6
+ * - the article link appears **only** with a real publish receipt ({@link applyArticleReceipt});
7
+ * {@link renderBriefShowNotes} never derives a URL from the title, it renders a text-only
8
+ * placeholder instead, so the notes can be reviewed before the article exists;
9
+ * - a missing card asset (or a failed card upload) never blocks or abbreviates the render — the
10
+ * card degrades to its plain text and the failure is reported through the separate
11
+ * {@link CardDiagnostic} channel;
12
+ * - the notes stay a distinct reading surface: bullets + sources + timeline + cards, never the
13
+ * article body (the pre-0386 fallback repeated the body).
14
+ *
15
+ * Output dialect matches {@link renderShowNotesHtml}: markdown paragraphs plus two validated
16
+ * marker blocks (`<!--kk:timeline-->`, `<!--kk:cards-->`) whose HTML is built here from escaped
17
+ * values only.
18
+ */
19
+
20
+ import type { Doc } from '@gobing-ai/kk-core';
21
+ import { computeAudioOffsets, escapeHtml, formatOffset, itemBrief, sourceLabelFor } from './show-notes';
22
+
23
+ /** Placeholder paragraph {@link applyArticleReceipt} rewrites once the article receipt exists. */
24
+ const ARTICLE_PLACEHOLDER = '<p class="kk-tl-more">完整图文版:待文章发布回执</p>';
25
+
26
+ /** The exact `<style>` block {@link renderCardsRegion} emits (reused by the marker validator). */
27
+ export const CARDS_STYLE = `<style>
28
+ .kk-cards{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:12px;margin:1em 0}
29
+ .kk-card{margin:0;border:1px solid rgba(128,128,128,.25);border-radius:10px;overflow:hidden}
30
+ .kk-card img{display:block;width:100%;height:auto}
31
+ .kk-card figcaption{padding:8px 10px;font-size:.9em;color:#444}
32
+ .kk-card-n{font-weight:700;color:#0969da;margin-right:6px}
33
+ @media (max-width:420px){.kk-cards{grid-template-columns:1fr}}
34
+ </style>`;
35
+
36
+ /** One rendered card, already reduced to host-safe values. */
37
+ export interface PlannedCard {
38
+ /** Position in the published card order (1-based). */
39
+ index: number;
40
+ /** Always non-empty (a card without readable alt gets a positional description). */
41
+ alt: string;
42
+ /** Hosted image URL from the upload receipt, or `''` when no asset is available. */
43
+ imageUrl: string;
44
+ /** Plain-text degradation: the card's copy (or its source point). */
45
+ text: string;
46
+ }
47
+
48
+ /** A card problem, recorded separately from the render (never thrown, never fatal). */
49
+ export interface CardDiagnostic {
50
+ index: number;
51
+ reason: 'asset-missing' | 'upload-failed' | 'malformed';
52
+ detail: string;
53
+ }
54
+
55
+ const isHttpUrl = (value: unknown): value is string => typeof value === 'string' && /^https?:\/\//i.test(value.trim());
56
+
57
+ function textOf(value: unknown): string {
58
+ return typeof value === 'string' ? value.trim() : '';
59
+ }
60
+
61
+ /**
62
+ * Reads the published card order (`25-xhs/cards.json`: `{cards:[{index, copy, sourcePoint, status,
63
+ * imagePath, …}]}`, or the bare array) into render-safe cards plus the diagnostics for the ones
64
+ * whose asset is missing or whose upload failed. Order is the manifest's; nothing is invented — a
65
+ * card without a hosted URL renders text-only.
66
+ */
67
+ export function planCards(raw: unknown): { cards: PlannedCard[]; diagnostics: CardDiagnostic[] } {
68
+ const entries = Array.isArray(raw)
69
+ ? raw
70
+ : raw !== null && typeof raw === 'object' && Array.isArray((raw as { cards?: unknown }).cards)
71
+ ? ((raw as { cards: unknown[] }).cards as unknown[])
72
+ : [];
73
+ const cards: PlannedCard[] = [];
74
+ const diagnostics: CardDiagnostic[] = [];
75
+ entries.forEach((entry, position) => {
76
+ if (entry === null || typeof entry !== 'object') {
77
+ diagnostics.push({ index: position + 1, reason: 'malformed', detail: 'card entry is not an object' });
78
+ return;
79
+ }
80
+ const card = entry as Record<string, unknown>;
81
+ const index =
82
+ typeof card.index === 'number' && Number.isFinite(card.index) && card.index > 0
83
+ ? Math.trunc(card.index)
84
+ : position + 1;
85
+ const uploadStatus = textOf(card.uploadStatus);
86
+ const uploadError = textOf(card.uploadError);
87
+ const url = isHttpUrl(card.url)
88
+ ? (card.url as string).trim()
89
+ : isHttpUrl(card.imageUrl)
90
+ ? (card.imageUrl as string).trim()
91
+ : '';
92
+ if (uploadStatus === 'failed' || uploadError !== '') {
93
+ diagnostics.push({ index, reason: 'upload-failed', detail: uploadError || 'upload reported failed' });
94
+ } else if (textOf(card.status) !== 'rendered') {
95
+ diagnostics.push({
96
+ index,
97
+ reason: 'asset-missing',
98
+ detail: `card status is "${textOf(card.status) || 'unknown'}"`,
99
+ });
100
+ }
101
+ const copy = textOf(card.copy);
102
+ const sourcePoint = textOf(card.sourcePoint);
103
+ const alt = textOf(card.alt) || copy || sourcePoint || `本期卡片 ${index}`;
104
+ cards.push({ index, alt, imageUrl: uploadStatus === 'failed' ? '' : url, text: copy || sourcePoint || alt });
105
+ });
106
+ return { cards, diagnostics };
107
+ }
108
+
109
+ /**
110
+ * The responsive card region: preserved order, readable alt on every `<img>`, plain-text caption
111
+ * always. No card at all (or no manifest) ⇒ `''`, so the notes carry no empty block.
112
+ */
113
+ export function renderCardsRegion(cards: PlannedCard[]): string {
114
+ if (cards.length === 0) return '';
115
+ const figures = cards
116
+ .map((card) => {
117
+ const img =
118
+ card.imageUrl === ''
119
+ ? ''
120
+ : `<img src="${escapeHtml(card.imageUrl)}" alt="${escapeHtml(card.alt)}" loading="lazy">`;
121
+ return `
122
+ <figure class="kk-card">${img}<figcaption><span class="kk-card-n">${card.index}</span>${escapeHtml(card.text)}</figcaption></figure>`;
123
+ })
124
+ .join('');
125
+ return `<!--kk:cards-->
126
+ ${CARDS_STYLE}
127
+ <div class="kk-cards">${figures}
128
+ </div>
129
+ <!--/kk:cards-->`;
130
+ }
131
+
132
+ /** Inputs for {@link renderBriefShowNotes}: the frozen artifacts, nothing inferred. */
133
+ export interface BriefShowNotesInput {
134
+ /** Episode heading (the 0385 frozen title); the page theme also renders it, so it is not repeated. */
135
+ title?: string;
136
+ /** Final spoken items in spoken order (plan ∩ script plan, exclusions already dropped). */
137
+ docs: Doc[];
138
+ /** Verified article URL **only** — pass `''` (or omit) until a real receipt exists. */
139
+ articleUrl?: string;
140
+ /** Measured segment metadata (`metadata.segments[]`): the source of real timeline offsets. */
141
+ audioSegments?: Array<{ duration?: number; transcription?: string }>;
142
+ /** `25-xhs/cards.json` contents; absent ⇒ no card region at all. */
143
+ cards?: unknown;
144
+ }
145
+
146
+ /**
147
+ * Renders the brief notes markdown: per-item bullets with the 0394 source citation, the measured
148
+ * timeline (real offsets, `--:--` when a measurement is genuinely absent — never a fabricated
149
+ * timestamp), the article entry (linked only when `articleUrl` is verified), the card region and
150
+ * the footer. Card problems come back as {@link CardDiagnostic}s beside the markdown.
151
+ */
152
+ export function renderBriefShowNotes(input: BriefShowNotesInput): { markdown: string; diagnostics: CardDiagnostic[] } {
153
+ const { cards, diagnostics } = planCards(input.cards);
154
+ const offsets = computeAudioOffsets(input.docs, input.audioSegments);
155
+ const rows = input.docs
156
+ .map((doc, i) => {
157
+ const title = escapeHtml(doc.title ?? `条目 ${i + 1}`);
158
+ const brief = escapeHtml(itemBrief(doc));
159
+ const at = formatOffset(offsets[i] ?? Number.NaN);
160
+ const label = escapeHtml(sourceLabelFor(doc));
161
+ const link = isHttpUrl(doc.sourceUri)
162
+ ? ` <a href="${escapeHtml(doc.sourceUri)}" target="_blank" rel="noopener">来源:${label}</a>`
163
+ : ` <span class="kk-tl-src">来源:${label}</span>`;
164
+ return `
165
+ <div class="kk-tl-row"><div class="kk-tl-t">${at}</div><div class="kk-tl-body"><div class="kk-tl-title">${i + 1}. ${title}${link}</div><p class="kk-tl-brief">${brief}</p></div></div>`;
166
+ })
167
+ .join('');
168
+ const articleEntry =
169
+ input.articleUrl !== undefined && isHttpUrl(input.articleUrl)
170
+ ? `<p class="kk-tl-more">完整图文版:<a href="${escapeHtml(input.articleUrl.trim())}" target="_blank" rel="noopener">本期完整文章</a></p>`
171
+ : ARTICLE_PLACEHOLDER;
172
+ const lines: string[] = [];
173
+ if (input.title !== undefined && input.title !== '') lines.push(`# ${input.title}`, '');
174
+ if (input.docs.length > 0) {
175
+ lines.push(
176
+ `<!--kk:timeline-->
177
+ <div class="kk-tl">${rows}
178
+ </div>
179
+ ${articleEntry}
180
+ <!--/kk:timeline-->`,
181
+ '',
182
+ );
183
+ }
184
+ const cardRegion = renderCardsRegion(cards);
185
+ if (cardRegion !== '') lines.push(cardRegion, '');
186
+ return { markdown: lines.join('\n'), diagnostics };
187
+ }
188
+
189
+ /** The hosted article slug a publish receipt proves, or `''` when the receipt proves nothing. */
190
+ function receiptSlug(receipt: unknown): string {
191
+ const entries = Array.isArray(receipt)
192
+ ? receipt
193
+ : receipt !== null && typeof receipt === 'object' && Array.isArray((receipt as { targets?: unknown }).targets)
194
+ ? ((receipt as { targets: unknown[] }).targets as unknown[])
195
+ : receipt !== null && typeof receipt === 'object'
196
+ ? [receipt]
197
+ : [];
198
+ for (const entry of entries) {
199
+ if (entry === null || typeof entry !== 'object') continue;
200
+ const record = entry as Record<string, unknown>;
201
+ if (record.ok === false) continue;
202
+ const metadata =
203
+ record.metadata !== null && typeof record.metadata === 'object'
204
+ ? (record.metadata as Record<string, unknown>)
205
+ : record;
206
+ const postPath = textOf(metadata.postPath);
207
+ if (postPath === '') continue;
208
+ const segments = postPath.split(/[\\/]/).filter((s) => s.length > 0);
209
+ // `<…>/posts/<locale>/<slug>/index.md` — the slug is the path segment before the file.
210
+ const slug = segments.length >= 2 ? (segments[segments.length - 2] ?? '') : '';
211
+ if (slug !== '' && slug !== 'posts')
212
+ return `${slug}\u0000${segments.find((s) => ['zh', 'en', 'ja'].includes(s)) ?? 'zh'}`;
213
+ }
214
+ return '';
215
+ }
216
+
217
+ /**
218
+ * Enriches already-rendered notes with the article link **once a real receipt exists**: the
219
+ * placeholder paragraph is replaced by the linked one derived from the receipt's `postPath`
220
+ * (never from the title/date). A receipt that proves no post leaves the markdown byte-identical.
221
+ */
222
+ export function applyArticleReceipt(
223
+ markdown: string,
224
+ receipt: unknown,
225
+ articleBaseUrl = 'https://surfing.salty.vip',
226
+ ): { markdown: string; enriched: boolean } {
227
+ const proven = receiptSlug(receipt);
228
+ if (proven === '' || !markdown.includes(ARTICLE_PLACEHOLDER)) return { markdown, enriched: false };
229
+ const [slug = '', locale = 'zh'] = proven.split('\u0000');
230
+ // surfdash serves `en` at the root; zh/ja carry the locale prefix (surfdash/src/lib/seo.ts).
231
+ const prefix = locale === 'en' ? '' : `/${locale}`;
232
+ const url = `${articleBaseUrl.replace(/\/+$/, '')}${prefix}/posts/${slug}`;
233
+ return {
234
+ markdown: markdown.replace(
235
+ ARTICLE_PLACEHOLDER,
236
+ `<p class="kk-tl-more">完整图文版:<a href="${escapeHtml(url)}" target="_blank" rel="noopener">本期完整文章</a></p>`,
237
+ ),
238
+ enriched: true,
239
+ };
240
+ }