@gobing-ai/knowledge-kit 0.1.23 → 0.1.24

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 (84) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/index.js +117 -56
  3. package/package.json +5 -5
  4. package/plugins/generations/content-gen/dist/index.js +9 -9
  5. package/plugins/generations/core-facts-gen/dist/index.js +12 -12
  6. package/plugins/generations/daily-article-gen/dist/index.js +12 -12
  7. package/plugins/generations/dailynews-gen/dist/index.js +11 -11
  8. package/plugins/generations/dailynews-gen/src/script-plan.ts +2 -2
  9. package/plugins/generations/episode-plan-gen/dist/index.js +12 -12
  10. package/plugins/generations/gemini-tts/dist/index.js +9 -9
  11. package/plugins/generations/image-gen/dist/index.js +9 -9
  12. package/plugins/generations/music-gen/dist/index.js +16 -16
  13. package/plugins/generations/news-report-gen/dist/index.js +12 -12
  14. package/plugins/generations/vibe-voice-tts/dist/index.js +9 -9
  15. package/plugins/generations/voice-gen/dist/index.js +9 -9
  16. package/plugins/generations/voxcpm-tts/dist/index.js +9 -9
  17. package/plugins/ingestions/aihot-ingest/dist/index.js +12 -12
  18. package/plugins/ingestions/horizon-ingest/dist/index.js +12 -12
  19. package/plugins/ingestions/karakeep-local/dist/index.js +13 -13
  20. package/plugins/ingestions/last30days-ingest/dist/index.js +12 -12
  21. package/plugins/ingestions/web-search/dist/index.js +10 -10
  22. package/plugins/kk/plugin.json +1 -1
  23. package/plugins/kk/publish-presets/daily-ai-voice.json +16 -16
  24. package/plugins/kk/scripts/cover-compositor.ts +104 -26
  25. package/plugins/kk/scripts/daily-stages.ts +217 -33
  26. package/plugins/kk/scripts/kk-workflow-stages.ts +144 -6
  27. package/plugins/kk/scripts/series-names.ts +16 -3
  28. package/plugins/kk/skills/news-editorial/SKILL.md +1 -1
  29. package/plugins/kk/skills/news-editorial/references/style-contract.zh.md +3 -3
  30. package/plugins/kk/workflows/kk-news-generate.yaml +3 -0
  31. package/plugins/publishings/bilibili-pub/dist/index.js +22 -22
  32. package/plugins/publishings/bilibili-pub/dist/profile-check.js +22 -22
  33. package/plugins/publishings/cnblogs-pub/dist/index.js +22 -22
  34. package/plugins/publishings/cnblogs-pub/dist/profile-check.js +22 -22
  35. package/plugins/publishings/csdn-pub/dist/index.js +22 -22
  36. package/plugins/publishings/csdn-pub/dist/profile-check.js +22 -22
  37. package/plugins/publishings/emdash-pub/dist/index.js +9 -9
  38. package/plugins/publishings/infoq-pub/dist/index.js +22 -22
  39. package/plugins/publishings/infoq-pub/dist/profile-check.js +22 -22
  40. package/plugins/publishings/jike-pub/dist/index.js +22 -22
  41. package/plugins/publishings/jike-pub/dist/profile-check.js +22 -22
  42. package/plugins/publishings/juejin-pub/dist/index.js +22 -22
  43. package/plugins/publishings/juejin-pub/dist/profile-check.js +22 -22
  44. package/plugins/publishings/linkedin-pub/dist/index.js +82 -24
  45. package/plugins/publishings/linkedin-pub/dist/profile-check.js +22 -22
  46. package/plugins/publishings/linkedin-pub/src/index.ts +93 -6
  47. package/plugins/publishings/medium-pub/dist/index.js +9 -9
  48. package/plugins/publishings/podcast-pub/dist/index.js +240 -37
  49. package/plugins/publishings/podcast-pub/src/index.ts +154 -3
  50. package/plugins/publishings/podcast-pub/src/seo.ts +25 -8
  51. package/plugins/publishings/podcast-pub/src/show-notes-brief.ts +93 -23
  52. package/plugins/publishings/podcast-pub/src/show-notes.ts +26 -6
  53. package/plugins/publishings/qiita-pub/dist/index.js +9 -9
  54. package/plugins/publishings/shipinhao-pub/dist/index.js +23 -23
  55. package/plugins/publishings/shipinhao-pub/dist/profile-check.js +23 -23
  56. package/plugins/publishings/shipinhao-pub/src/selectors.ts +2 -1
  57. package/plugins/publishings/sspai-pub/dist/index.js +22 -22
  58. package/plugins/publishings/sspai-pub/dist/profile-check.js +22 -22
  59. package/plugins/publishings/substack-pub/dist/index.js +22 -22
  60. package/plugins/publishings/substack-pub/dist/profile-check.js +22 -22
  61. package/plugins/publishings/surfdash-pub/dist/index.js +200 -92
  62. package/plugins/publishings/surfdash-pub/src/digest-check.ts +30 -1
  63. package/plugins/publishings/surfdash-pub/src/index.ts +94 -75
  64. package/plugins/publishings/surfdash-pub/src/media-upload.ts +83 -0
  65. package/plugins/publishings/surfdash-pub/src/patch.ts +28 -23
  66. package/plugins/publishings/surfdash-pub/src/topic-claims.ts +12 -4
  67. package/plugins/publishings/threads-pub/dist/index.js +36 -22
  68. package/plugins/publishings/threads-pub/dist/profile-check.js +27 -22
  69. package/plugins/publishings/threads-pub/src/post-rail.ts +20 -0
  70. package/plugins/publishings/wechatmp-pub/dist/index.js +180 -64
  71. package/plugins/publishings/wechatmp-pub/dist/profile-check.js +27 -23
  72. package/plugins/publishings/wechatmp-pub/src/enrich.ts +56 -10
  73. package/plugins/publishings/wechatmp-pub/src/flow.ts +155 -43
  74. package/plugins/publishings/wechatmp-pub/src/modes.ts +30 -12
  75. package/plugins/publishings/weibo-pub/dist/index.js +22 -22
  76. package/plugins/publishings/weibo-pub/dist/profile-check.js +22 -22
  77. package/plugins/publishings/x-pub/dist/index.js +51 -45
  78. package/plugins/publishings/x-pub/dist/profile-check.js +22 -22
  79. package/plugins/publishings/x-pub/src/post-rail.ts +40 -47
  80. package/plugins/publishings/xhs-pub/dist/index.js +22 -22
  81. package/plugins/publishings/xhs-pub/dist/profile-check.js +22 -22
  82. package/plugins/publishings/xiaoyuzhou-pub/dist/index.js +22 -22
  83. package/plugins/publishings/xiaoyuzhou-pub/dist/profile-check.js +22 -22
  84. package/plugins/publishings/zenn-pub/dist/index.js +9 -9
@@ -12,38 +12,24 @@
12
12
  * `bun run check:content` in the surfdash checkout. The surfdash site gate is the authoritative
13
13
  * validation suite before deployment.
14
14
  *
15
- * Daily-topics sync:
16
- * Before the site gate and commit, digest posts with all three locale files are mapped into
17
- * the surfdash site's `scripts/seo/daily-topics.json` (from the posts' own refined frontmatter,
18
- * no new prose), then `bun run sd seo retitle --write --stamp-claims` runs in the checkout.
19
- * A build/retitle failure fails the run before anything is committed or pushed. See
20
- * `./topic-claims` for the file work.
21
- *
22
- * Environment variables:
23
- * - `SURFDASH_LISTEN_BACKFILL`:
24
- * - `off`: skips the listen-link backfill command.
25
- * - `SURFDASH_DIGEST_CHECK`:
26
- * - unset / default: fail-loud on gate failure; commit and push are blocked.
27
- * - `warn`: echoes gate failures via `echoError` prefixed with `site gate (warn):` and continues.
28
- * - `off`: bypasses the gate check.
29
- * - Both escape hatches are IGNORED while this run pushes to surfdash `main`
30
- * (`SURFDASH_AUTO_PUSH !== '0'` and the checkout is on `main`): a failing gate always
31
- * blocks there, and `off` still runs the gate.
32
- * - `SURFDASH_AUTO_PUSH`:
33
- * - '0': disables auto-commit and push (used in tests and offline runs).
15
+ * Cover hosting:
16
+ * Digests share remote `https://podcast-media.salty.vip/...` covers rather than committing
17
+ * `assets/cover.png` binaries into git. Local fallback covers upload to Microfeed via
18
+ * `./media-upload` before frontmatter is written.
34
19
  */
35
20
  import { createHash } from 'node:crypto';
36
21
  import { existsSync, readFileSync } from 'node:fs';
37
- import { copyFile, cp, writeFile } from 'node:fs/promises';
38
- import { dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
22
+ import { writeFile } from 'node:fs/promises';
23
+ import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
39
24
  import { parseArgs } from 'node:util';
40
25
  import { type Content, ContentSchema, type Result, ResultSchema } from '@gobing-ai/kk-core';
41
26
  import type { PublishTransport, PublishTransportPayload } from '@gobing-ai/publish-harness';
42
27
  import { createNodeFileSystem } from '@gobing-ai/ts-runtime';
43
28
  import { echoError } from '@gobing-ai/ts-utils';
44
29
  // The plugin's public digest-contract surface (2026-10-24).
45
- import { checkDigestFrontmatter, DIGEST_TAG, type DigestLocale } from './digest-check';
46
- import { localeIndexPath, PATCH_LOCALES, type PatchPostOutcome, patchPostFiles } from './patch';
30
+ import { checkDigestFrontmatter, DIGEST_TAG, type DigestLocale, isEpisodeIdentityTitle } from './digest-check';
31
+ import { uploadCoverToMicrofeed } from './media-upload';
32
+ import { crossLinkFor, localeIndexPath, PATCH_LOCALES, type PatchPostOutcome, patchPostFiles } from './patch';
47
33
  import { buildDailyTopicsEntry, isDigestMarkdown, slugFromPostPath, upsertDailyTopicsEntry } from './topic-claims';
48
34
 
49
35
  export { checkDigestFrontmatter, DIGEST_TAG, type DigestLocale } from './digest-check';
@@ -107,10 +93,12 @@ interface SurfdashPubOptions {
107
93
  export interface MapContentOptions {
108
94
  /** Target publishing site name or base URL. Defaults to 'surfdash'. */
109
95
  targetName?: string;
110
- /** Frontmatter image value (e.g. `./assets/cover.png`); written to `image` and `og_image`. */
96
+ /** Frontmatter remote cover URL (`https://podcast-media.salty.vip/...`); written to `image` and `og_image`. */
111
97
  image?: string;
112
98
  /** ISO date for publishDate; defaults to today. */
113
99
  publishDate?: string;
100
+ /** Locale directory this post belongs to (`zh` / `en` / `ja`). Defaults to `zh`. */
101
+ locale?: SupportedLocale;
114
102
  }
115
103
 
116
104
  /**
@@ -195,6 +183,25 @@ export function mapContentToSurfingMarkdown(content: Content, options: MapConten
195
183
  // source and would have dropped the post out of the sitemap if surfdash's refine step had
196
184
  // not overwritten it. See docs/00_ADR.md ADR-008: the generator supplies content, the site
197
185
  // supplies identity.
186
+ const postLocale = options.locale ?? 'zh';
187
+ const rawEpisodeTitle =
188
+ typeof content.metadata?.episodeTitle === 'string' && content.metadata.episodeTitle.trim() !== ''
189
+ ? content.metadata.episodeTitle.trim()
190
+ : typeof content.metadata?.episode_title === 'string' && content.metadata.episode_title.trim() !== ''
191
+ ? content.metadata.episode_title.trim()
192
+ : '';
193
+ const podcastUrl =
194
+ typeof content.metadata?.podcastUrl === 'string' && /^https:\/\//.test(content.metadata.podcastUrl)
195
+ ? content.metadata.podcastUrl
196
+ : '';
197
+
198
+ const episodeTitleForLocale =
199
+ postLocale === 'zh'
200
+ ? rawEpisodeTitle || (isEpisodeIdentityTitle(title, 'zh') ? title : '')
201
+ : isEpisodeIdentityTitle(title, postLocale)
202
+ ? title
203
+ : '';
204
+
198
205
  const frontmatterObj: Record<string, unknown> = {
199
206
  title,
200
207
  description,
@@ -202,10 +209,15 @@ export function mapContentToSurfingMarkdown(content: Content, options: MapConten
202
209
  publishDate: isoDate,
203
210
  draft,
204
211
  ...(options.image ? { image: options.image, og_image: options.image } : {}),
212
+ ...(episodeTitleForLocale !== '' ? { episode_title: episodeTitleForLocale } : {}),
205
213
  };
206
214
 
207
215
  const yamlLines = ['---', ...Object.entries(frontmatterObj).map(([k, v]) => `${k}: ${JSON.stringify(v)}`), '---'];
208
- return `${yamlLines.join('\n')}\n\n${content.body.trim()}\n`;
216
+ let bodyText = content.body.trim();
217
+ if (podcastUrl !== '' && !bodyText.includes(podcastUrl)) {
218
+ bodyText = `${bodyText}\n\n${crossLinkFor(postLocale, isoDate, podcastUrl, rawEpisodeTitle)}`;
219
+ }
220
+ return `${yamlLines.join('\n')}\n\n${bodyText}\n`;
209
221
  }
210
222
 
211
223
  /** True when the content's tag sources (contentTags) mark it as a daily digest post. */
@@ -906,10 +918,6 @@ async function scaffoldLocale(options: SurfdashPubOptions): Promise<Result> {
906
918
  if (!existsSync(draftPath)) {
907
919
  return fail(`sd translate reported success but the draft is missing: ${draftPath}`);
908
920
  }
909
- const assetsDir = join(dirname(postPath.postPath), 'assets');
910
- if (existsSync(assetsDir)) {
911
- await cp(assetsDir, join(dirname(draftPath), 'assets'), { recursive: true });
912
- }
913
921
  return ResultSchema.parse({
914
922
  ok: true,
915
923
  target: TARGET,
@@ -1042,26 +1050,14 @@ async function patchPost(options: SurfdashPubOptions): Promise<Result> {
1042
1050
  localCover: strOption(options, 'localCover'),
1043
1051
  dateIso: strOption(options, 'dateIso'),
1044
1052
  episodeTitle: strOption(options, 'episodeTitle'),
1053
+ uploadLocalCover: uploadCoverToMicrofeed,
1045
1054
  });
1046
1055
  } catch (error: unknown) {
1047
1056
  return fail(`patch error: ${error instanceof Error ? error.message : String(error)}`);
1048
1057
  }
1049
1058
  if (outcome.changed === 0) echoError(`patch: no post bytes changed for ${outcome.slug}`);
1050
- // Daily-topics map + retitle run before the CMS sync so the synced rows carry the retitled
1051
- // frontmatter; a failure here must not commit or push a half-synced post.
1052
- const topics = await runDailyTopicsSync(surfdashRoot, postPath.postPath);
1053
- if (!topics.ok) return fail(topics.error);
1054
1059
  const synced = await syncPost({ postPath: postPath.postPath });
1055
1060
  const commitPaths = new Set(outcome.written.map((path) => relative(surfdashRoot, path)));
1056
- for (const p of topics.paths) commitPaths.add(p);
1057
- for (const locale of PATCH_LOCALES) {
1058
- const indexMd = localeIndexPath(postPath.postPath, locale);
1059
- if (!indexMd) continue;
1060
- const assetsDir = join(dirname(indexMd), 'assets');
1061
- if (existsSync(assetsDir)) {
1062
- commitPaths.add(relative(surfdashRoot, assetsDir));
1063
- }
1064
- }
1065
1061
  if (process.env.SURFDASH_AUTO_PUSH !== '0') {
1066
1062
  const backfilled = await runListenLinkBackfill(surfdashRoot);
1067
1063
  for (const p of backfilled) commitPaths.add(p);
@@ -1319,7 +1315,8 @@ function readLocaleDrafts(content: Content): Partial<Record<(typeof LOCAL_DRAFTS
1319
1315
  async function mintLocalePost(options: {
1320
1316
  postDir: string;
1321
1317
  content: Content;
1322
- coverPath?: string;
1318
+ coverUrl?: string;
1319
+ locale?: SupportedLocale;
1323
1320
  publishDate?: string;
1324
1321
  }): Promise<void> {
1325
1322
  const filePath = join(options.postDir, 'index.md');
@@ -1328,16 +1325,9 @@ async function mintLocalePost(options: {
1328
1325
  return;
1329
1326
  }
1330
1327
  await createNodeFileSystem().ensureDir(options.postDir);
1331
- let imageFrontmatter: string | undefined;
1332
- if (options.coverPath !== undefined) {
1333
- const assetsDir = join(options.postDir, 'assets');
1334
- await createNodeFileSystem().ensureDir(assetsDir);
1335
- const coverName = `cover${extname(options.coverPath).toLowerCase()}`;
1336
- await copyFile(options.coverPath, join(assetsDir, coverName));
1337
- imageFrontmatter = `./assets/${coverName}`;
1338
- }
1339
1328
  const markdown = mapContentToSurfingMarkdown(options.content, {
1340
- image: imageFrontmatter,
1329
+ image: options.coverUrl,
1330
+ locale: options.locale,
1341
1331
  publishDate: options.publishDate,
1342
1332
  });
1343
1333
  await createNodeFileSystem().writeFile(filePath, markdown);
@@ -1386,17 +1376,44 @@ async function preparePost(payload: PublishTransportPayload): Promise<PrepareOut
1386
1376
  return { ok: false, result: failNotSent(`post path escapes ${articlesRoot}`) };
1387
1377
  }
1388
1378
 
1389
- const coverPath = payload.content.metadata?.coverImage;
1390
- if (typeof coverPath === 'string' && !existsSync(coverPath)) {
1391
- return { ok: false, result: failNotSent(`metadata.coverImage not found: ${coverPath}`) };
1392
- }
1393
- if (typeof coverPath === 'string' && !COVER_EXTS.has(extname(coverPath).toLowerCase())) {
1394
- return {
1395
- ok: false,
1396
- result: failNotSent(`metadata.coverImage must be one of ${[...COVER_EXTS].join(', ')}`),
1397
- };
1398
- }
1399
- if (isDigestContent(payload.content) && typeof coverPath !== 'string') {
1379
+ const rawCover = payload.content.metadata?.coverImage;
1380
+ let coverUrl: string | undefined;
1381
+ if (typeof rawCover === 'string' && rawCover.trim() !== '') {
1382
+ const trimmedCover = rawCover.trim();
1383
+ if (/^https:\/\//.test(trimmedCover)) {
1384
+ coverUrl = trimmedCover;
1385
+ } else {
1386
+ if (!existsSync(trimmedCover)) {
1387
+ return { ok: false, result: failNotSent(`metadata.coverImage not found: ${trimmedCover}`) };
1388
+ }
1389
+ if (!COVER_EXTS.has(extname(trimmedCover).toLowerCase())) {
1390
+ return {
1391
+ ok: false,
1392
+ result: failNotSent(`metadata.coverImage must be one of ${[...COVER_EXTS].join(', ')}`),
1393
+ };
1394
+ }
1395
+ const optsObj =
1396
+ payload.options !== undefined && typeof payload.options === 'object' && payload.options !== null
1397
+ ? (payload.options as Record<string, unknown>)
1398
+ : {};
1399
+ const isDryRun = optsObj.dryRun === true || process.env.KNOWLEDGE_KIT_PUBLISH_TRANSPORT === 'fake';
1400
+ if (isDryRun) {
1401
+ const safeName = basename(trimmedCover).replace(/[^a-zA-Z0-9._-]/g, '_') || 'cover.png';
1402
+ coverUrl = `https://podcast-media.salty.vip/production/images/dry-run-${safeName}`;
1403
+ } else {
1404
+ try {
1405
+ coverUrl = await uploadCoverToMicrofeed(trimmedCover);
1406
+ } catch (err: unknown) {
1407
+ return {
1408
+ ok: false,
1409
+ result: failNotSent(
1410
+ `Failed to upload cover image to podcast-media: ${err instanceof Error ? err.message : String(err)}`,
1411
+ ),
1412
+ };
1413
+ }
1414
+ }
1415
+ }
1416
+ } else if (isDigestContent(payload.content)) {
1400
1417
  return { ok: false, result: failNotSent('digest post has no cover image (metadata.coverImage)') };
1401
1418
  }
1402
1419
 
@@ -1419,18 +1436,18 @@ async function preparePost(payload: PublishTransportPayload): Promise<PrepareOut
1419
1436
 
1420
1437
  const filePath = join(postDir, 'index.md');
1421
1438
  const publishDate = runDate ? `${runDate.slice(0, 4)}-${runDate.slice(4, 6)}-${runDate.slice(6, 8)}` : undefined;
1422
- const cover = typeof coverPath === 'string' ? coverPath : undefined;
1439
+ const mintedDirs = [join('content', 'posts', 'articles', locale, slug)];
1423
1440
  try {
1424
1441
  // A post the site's own refine step already marked is not ours to clobber: re-minting it
1425
1442
  // replaces the refined canonical frontmatter (refine owns `refined`, `seo_title`, …) with
1426
1443
  // generator defaults and flips an already-published day back to a draft. Keep the file and
1427
1444
  // reuse it; only genuinely fresh days (no marker) get minted (2026-11-05 tier-0 rerun).
1428
- await mintLocalePost({ postDir, content: payload.content, coverPath: cover, publishDate });
1429
- for (const locale of LOCAL_DRAFTS) {
1430
- const draft = drafts[locale];
1445
+ await mintLocalePost({ postDir, content: payload.content, coverUrl, locale, publishDate });
1446
+ for (const draftLocale of LOCAL_DRAFTS) {
1447
+ const draft = drafts[draftLocale];
1431
1448
  if (draft === undefined) continue;
1432
- const siblingDir = resolve(articlesRoot, locale, slug);
1433
- if (dirname(resolve(siblingDir)) !== resolve(articlesRoot, locale)) {
1449
+ const siblingDir = resolve(articlesRoot, draftLocale, slug);
1450
+ if (dirname(resolve(siblingDir)) !== resolve(articlesRoot, draftLocale)) {
1434
1451
  return { ok: false, result: failNotSent(`post path escapes ${articlesRoot}`) };
1435
1452
  }
1436
1453
  // The zh Body and title are replaced by the translation; the frontmatter fields the
@@ -1439,9 +1456,11 @@ async function preparePost(payload: PublishTransportPayload): Promise<PrepareOut
1439
1456
  await mintLocalePost({
1440
1457
  postDir: siblingDir,
1441
1458
  content: { ...payload.content, title: draft.title, body: draft.body },
1442
- coverPath: cover,
1459
+ coverUrl,
1460
+ locale: draftLocale,
1443
1461
  publishDate,
1444
1462
  });
1463
+ mintedDirs.push(join('content', 'posts', 'articles', draftLocale, slug));
1445
1464
  }
1446
1465
  } catch (err: unknown) {
1447
1466
  return {
@@ -1463,6 +1482,7 @@ async function preparePost(payload: PublishTransportPayload): Promise<PrepareOut
1463
1482
  slug,
1464
1483
  filePath,
1465
1484
  relPostDir: join('content', 'posts', 'articles', locale, slug),
1485
+ relPostDirs: mintedDirs,
1466
1486
  articleUrl,
1467
1487
  },
1468
1488
  };
@@ -1556,18 +1576,17 @@ async function publishPreparedFile(
1556
1576
  },
1557
1577
  });
1558
1578
  }
1559
- const topics = await runDailyTopicsSync(surfdashRoot, filePath);
1560
- if (!topics.ok) return failUncertain(topics.error);
1561
1579
  const backfilled = await runListenLinkBackfill(surfdashRoot);
1562
1580
  const commitPaths = relPostDirs ?? [relPostDir];
1563
- const gate = await runSiteGate(surfdashRoot, [...commitPaths, ...backfilled, ...topics.paths]);
1581
+ const gate = await runSiteGate(surfdashRoot, [...commitPaths, ...backfilled]);
1564
1582
  if (!gate.ok) return failUncertain(gate.error);
1565
- const commitLocales: SupportedLocale[] = relPostDirs === undefined ? [locale] : ['zh', 'en', 'ja'];
1583
+ const commitLocales: SupportedLocale[] =
1584
+ relPostDirs !== undefined && relPostDirs.length > 1 ? ['zh', 'en', 'ja'] : [locale];
1566
1585
  const pushed = await pushPostGit(
1567
1586
  surfdashRoot,
1568
1587
  commitPaths,
1569
1588
  `content: daily AI news ${dateStamp} (${commitLocales.join(', ')})`,
1570
- [...backfilled, ...topics.paths],
1589
+ backfilled,
1571
1590
  );
1572
1591
  if (!pushed.ok) return failUncertain(pushed.error);
1573
1592
  const live = await awaitArticleLive(articleUrl);
@@ -0,0 +1,83 @@
1
+ import { basename, extname } from 'node:path';
2
+
3
+ export type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
4
+
5
+ export interface MicrofeedUploadOptions {
6
+ baseUrl?: string;
7
+ apiKey?: string;
8
+ fetchImpl?: FetchLike;
9
+ }
10
+
11
+ function contentTypeForImage(filePath: string): string {
12
+ const ext = extname(filePath).toLowerCase();
13
+ if (ext === '.jpg' || ext === '.jpeg') return 'image/jpeg';
14
+ if (ext === '.webp') return 'image/webp';
15
+ return 'image/png';
16
+ }
17
+
18
+ async function readErrorBody(res: Response): Promise<string> {
19
+ try {
20
+ return (await res.text()).slice(0, 200);
21
+ } catch {
22
+ return '';
23
+ }
24
+ }
25
+
26
+ /**
27
+ * Upload a local cover image to Microfeed's media bucket (`podcast-media.salty.vip`) via its
28
+ * presigned URL endpoint and return the public `https://` `media_url`.
29
+ *
30
+ * Used by `surfdash-pub` only as a fallback when a caller supplies a local cover path rather than a
31
+ * pre-published podcast `imageUrl`, so `surfdash` never commits cover binaries to git.
32
+ */
33
+ export async function uploadCoverToMicrofeed(filePath: string, options: MicrofeedUploadOptions = {}): Promise<string> {
34
+ const baseUrl = (options.baseUrl ?? process.env.MICROFEED_BASE_URL ?? '').trim().replace(/\/$/, '');
35
+ const apiKey = (options.apiKey ?? process.env.MICROFEED_API_KEY ?? '').trim();
36
+ if (!baseUrl) {
37
+ throw new Error('MICROFEED_BASE_URL is required to upload a local cover image to podcast-media');
38
+ }
39
+ if (!apiKey) {
40
+ throw new Error('MICROFEED_API_KEY is required to upload a local cover image to podcast-media');
41
+ }
42
+
43
+ const mime = contentTypeForImage(filePath);
44
+ const bytes = await Bun.file(filePath).arrayBuffer();
45
+ const doFetch = options.fetchImpl ?? fetch;
46
+
47
+ const presignRes = await doFetch(`${baseUrl}/api/v1/media_files/presigned_urls`, {
48
+ method: 'POST',
49
+ headers: {
50
+ Authorization: `Bearer ${apiKey}`,
51
+ Origin: baseUrl,
52
+ 'Content-Type': 'application/json',
53
+ },
54
+ body: JSON.stringify({
55
+ category: 'image',
56
+ full_local_file_path: basename(filePath),
57
+ size: bytes.byteLength,
58
+ type: mime,
59
+ }),
60
+ });
61
+ if (!presignRes.ok) {
62
+ const body = await readErrorBody(presignRes);
63
+ throw new Error(`Microfeed cover presign failed (${presignRes.status}): ${body}`);
64
+ }
65
+ const { presigned_url, media_url } = (await presignRes.json()) as {
66
+ presigned_url?: string;
67
+ media_url?: string;
68
+ };
69
+ if (!presigned_url || !media_url || !/^https:\/\//.test(media_url)) {
70
+ throw new Error(`Microfeed cover presign returned incomplete media_url: ${String(media_url)}`);
71
+ }
72
+
73
+ const putRes = await doFetch(presigned_url, {
74
+ method: 'PUT',
75
+ headers: { 'Content-Type': mime },
76
+ body: bytes,
77
+ });
78
+ if (!putRes.ok) {
79
+ const body = await readErrorBody(putRes);
80
+ throw new Error(`Microfeed cover PUT upload failed (${putRes.status}): ${body}`);
81
+ }
82
+ return media_url;
83
+ }
@@ -11,7 +11,7 @@
11
11
  * This module owns only the file work (deterministic, no network); the caller (`./index`) owns the
12
12
  * branch guard, the CMS re-sync and the git commit, in that order.
13
13
  */
14
- import { basename, dirname, join, sep } from 'node:path';
14
+ import { basename, dirname, sep } from 'node:path';
15
15
  import { createNodeFileSystem } from '@gobing-ai/ts-runtime';
16
16
 
17
17
  /** The locales a daily post carries; zh is the primary whose directory anchors the other two. */
@@ -22,11 +22,11 @@ export type PatchLocale = (typeof PATCH_LOCALES)[number];
22
22
  export interface PatchPostRequest {
23
23
  /** Absolute `<root>/content/posts/articles/zh/<slug>/index.md` — the primary post. */
24
24
  postPath: string;
25
- /** Podcast-hosted cover URL; empty → the local cover is copied into `assets/` instead. */
25
+ /** Podcast-hosted cover URL (`https://...`); empty preserves an existing `https://` `image:` or uses {@link uploadLocalCover}. */
26
26
  coverUrl: string;
27
27
  /** Podcast episode URL for the cross-link line; empty → no cross-link. */
28
28
  showNotesUrl: string;
29
- /** This run's rendered cover, the fallback when `coverUrl` is empty. */
29
+ /** Optional local cover path uploaded via {@link uploadLocalCover} when no `https://` cover exists yet. */
30
30
  localCover: string;
31
31
  /** `YYYY-MM-DD` episode date used in the cross-link text. */
32
32
  dateIso: string;
@@ -37,6 +37,8 @@ export interface PatchPostRequest {
37
37
  * wording, which is what pre-0385 bundles carry.
38
38
  */
39
39
  episodeTitle?: string;
40
+ /** Optional uploader converting a local cover into an `https://` remote URL (e.g. Microfeed R2). */
41
+ uploadLocalCover?: (filePath: string) => Promise<string>;
40
42
  }
41
43
 
42
44
  /** What the file pass changed; the caller commits exactly {@link PatchPostOutcome.written}. */
@@ -129,17 +131,18 @@ export async function patchPostFiles(request: PatchPostRequest): Promise<PatchPo
129
131
  const absent: PatchLocale[] = [];
130
132
  const images: Record<string, string> = {};
131
133
  let changed = 0;
134
+ let uploadedFallbackCover: string | undefined;
132
135
  for (const locale of PATCH_LOCALES) {
133
136
  const indexMd = localeIndexPath(request.postPath, locale);
134
137
  if (indexMd === undefined || !(await fs.exists(indexMd))) {
135
138
  absent.push(locale);
136
139
  continue;
137
140
  }
138
- const dir = dirname(indexMd);
139
141
  const before = await fs.readFile(indexMd);
140
142
  let md = before;
141
143
  const end = frontmatterEnd(md);
142
144
  const fm = end < 0 ? md : md.slice(0, end);
145
+ const existingImage = /^image:\s*['"]?([^'"\n]+)['"]?/m.exec(fm)?.[1]?.trim() ?? '';
143
146
  if (request.coverUrl !== '') {
144
147
  // A relative or http:// cover would ship an unservable OG card — the deployed worker
145
148
  // only serves absolute https URLs (prod feedback 2026-09-29).
@@ -149,22 +152,28 @@ export async function patchPostFiles(request: PatchPostRequest): Promise<PatchPo
149
152
  md = upsertFrontmatterKey(md, 'image', request.coverUrl);
150
153
  md = upsertFrontmatterKey(md, 'og_image', request.coverUrl);
151
154
  images[locale] = request.coverUrl;
152
- } else if (!/^image:/m.test(fm)) {
153
- // Fallback for a run without a podcast cover: ship the rendered cover with the post.
154
- // A locale with no cover anywhere must fail naming the locale, not silently skip —
155
- // the CMS card would carry no servable image at all.
156
- if (!(await fs.exists(request.localCover))) {
157
- throw new Error(
158
- `${locale} post has no cover: coverUrl is empty, the frontmatter has no image key, and localCover does not exist (${request.localCover})`,
159
- );
155
+ } else if (/^https:\/\//.test(existingImage)) {
156
+ md = upsertFrontmatterKey(md, 'og_image', existingImage);
157
+ images[locale] = existingImage;
158
+ } else if (
159
+ request.uploadLocalCover !== undefined &&
160
+ request.localCover !== '' &&
161
+ (await fs.exists(request.localCover))
162
+ ) {
163
+ if (uploadedFallbackCover === undefined) {
164
+ const uploaded = await request.uploadLocalCover(request.localCover);
165
+ if (!/^https:\/\//.test(uploaded)) {
166
+ throw new Error(`uploaded cover must be an absolute https:// URL, got: ${uploaded}`);
167
+ }
168
+ uploadedFallbackCover = uploaded;
160
169
  }
161
- const asset = join(dir, 'assets', 'cover.png');
162
- await fs.ensureDir(dirname(asset));
163
- await fs.copy(request.localCover, asset);
164
- written.push(asset);
165
- md = upsertFrontmatterKey(md, 'image', './assets/cover.png');
166
- md = upsertFrontmatterKey(md, 'og_image', './assets/cover.png');
167
- images[locale] = './assets/cover.png';
170
+ md = upsertFrontmatterKey(md, 'image', uploadedFallbackCover);
171
+ md = upsertFrontmatterKey(md, 'og_image', uploadedFallbackCover);
172
+ images[locale] = uploadedFallbackCover;
173
+ } else {
174
+ throw new Error(
175
+ `${locale} post has no remote https:// cover: coverUrl is empty and frontmatter has no https:// image key`,
176
+ );
168
177
  }
169
178
  if (locale === 'zh' && (request.episodeTitle ?? '') !== '') {
170
179
  // The article states the episode identity the podcast ships (0385). The site renders it
@@ -192,10 +201,6 @@ export async function patchPostFiles(request: PatchPostRequest): Promise<PatchPo
192
201
  if (md !== before) {
193
202
  await fs.writeFile(indexMd, md);
194
203
  written.push(indexMd);
195
- const assetsDir = join(dir, 'assets');
196
- if ((await fs.exists(assetsDir)) && !written.includes(join(assetsDir, 'cover.png'))) {
197
- written.push(assetsDir);
198
- }
199
204
  changed += 1;
200
205
  }
201
206
  }
@@ -10,7 +10,7 @@
10
10
 
11
11
  import { dirname } from 'node:path';
12
12
  import { createNodeFileSystem, type FileSystem } from '@gobing-ai/ts-runtime';
13
- import { DIGEST_TAG, parseFrontmatterScalars } from './digest-check';
13
+ import { DIGEST_TAG, isEpisodeIdentityTitle, parseFrontmatterScalars } from './digest-check';
14
14
  import { PATCH_LOCALES, type PatchLocale, SERIES_NAMES } from './patch';
15
15
 
16
16
  /** One locale's topic-map fields. `claim_basis` is stamped later by retitle. */
@@ -106,8 +106,9 @@ function buildLocaleEntry(markdown: string, locale: PatchLocale): DailyTopicsLoc
106
106
  }
107
107
  const frontmatter = parseFrontmatterScalars(markdown);
108
108
  const title = scalar(frontmatter, 'title') ?? '';
109
- const headlines = parseTitleHeadlines(title, locale);
110
- if (!headlines) {
109
+ const episodeIdentity = isEpisodeIdentityTitle(title, locale);
110
+ const parsedHeadlines = episodeIdentity ? undefined : parseTitleHeadlines(title, locale);
111
+ if (!episodeIdentity && !parsedHeadlines) {
111
112
  return `${locale}: title is not "<series> · YYYY-MM-DD${titleSepFor(locale)}h1${listSepFor(locale)}h2"`;
112
113
  }
113
114
  const description = (scalar(frontmatter, 'description') ?? scalar(frontmatter, 'seo_description') ?? '').trim();
@@ -122,11 +123,18 @@ function buildLocaleEntry(markdown: string, locale: PatchLocale): DailyTopicsLoc
122
123
  if (!parts) {
123
124
  return `${locale}: key_points must be "label — sentence"`;
124
125
  }
126
+ const headlines = episodeIdentity ? parts.labels.slice(0, 2) : (parsedHeadlines ?? []);
127
+ if (headlines.length === 0) {
128
+ return `${locale}: key_points has no labels to derive headlines`;
129
+ }
125
130
  // The title names the TOP stories; the key-point box carries up to four. The site's own
126
131
  // generator emits exactly that shape (`scripts/commands/seo/retitle.ts`: title = "top story 1,
127
132
  // story 2", key_points = up to four bullets), so demanding a one-to-one match made every
128
133
  // crefitable digest fail the sync. The title must be the leading labels, in order.
129
- if (headlines.length > parts.labels.length || headlines.some((headline, i) => headline !== parts.labels[i])) {
134
+ if (
135
+ !episodeIdentity &&
136
+ (headlines.length > parts.labels.length || headlines.some((headline, i) => headline !== parts.labels[i]))
137
+ ) {
130
138
  return `${locale}: title headlines do not match the leading key_points labels`;
131
139
  }
132
140
  const claims = parts.sentences;