@gobing-ai/knowledge-kit 0.1.14 → 0.1.16

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 (120) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/index.js +2399 -177
  3. package/package.json +1 -1
  4. package/plugins/generations/content-gen/dist/index.js +60 -54
  5. package/plugins/generations/content-gen/src/storm.ts +94 -61
  6. package/plugins/generations/core-facts-gen/dist/index.js +3 -3
  7. package/plugins/generations/daily-article-gen/dist/index.js +3 -3
  8. package/plugins/generations/dailynews-gen/dist/index.js +73 -10
  9. package/plugins/generations/dailynews-gen/src/index.ts +23 -1
  10. package/plugins/generations/dailynews-gen/src/script-plan.ts +103 -5
  11. package/plugins/generations/episode-plan-gen/dist/index.js +3 -3
  12. package/plugins/generations/gemini-tts/dist/index.js +3 -3
  13. package/plugins/generations/image-gen/README.md +31 -10
  14. package/plugins/generations/image-gen/assets/sample/cover__quasi-news-podcast.jpg +0 -0
  15. package/plugins/generations/image-gen/assets/sample/daily-news-cover__quasi-news-podcast.jpg +0 -0
  16. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__clean-webapp-ui.jpg +0 -0
  17. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__cute.jpg +0 -0
  18. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__daily-news.jpg +0 -0
  19. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__editorial.jpg +0 -0
  20. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__fresh.jpg +0 -0
  21. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__minimalist.jpg +0 -0
  22. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__photorealistic.jpg +0 -0
  23. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__quasi-news-podcast.jpg +0 -0
  24. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__sketch.jpg +0 -0
  25. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__technical-diagram.jpg +0 -0
  26. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__vibrant.jpg +0 -0
  27. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__warm.jpg +0 -0
  28. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__xhs-knowledge.jpg +0 -0
  29. package/plugins/generations/image-gen/assets/sample/free__quasi-news-podcast.jpg +0 -0
  30. package/plugins/generations/image-gen/assets/sample/illustration__quasi-news-podcast.jpg +0 -0
  31. package/plugins/generations/image-gen/assets/sample/xhs-card__quasi-news-podcast.jpg +0 -0
  32. package/plugins/generations/image-gen/dist/index.js +3 -3
  33. package/plugins/generations/image-gen/presets/formats/daily-news-podcast-cover.yaml +18 -0
  34. package/plugins/generations/image-gen/presets/styles/quasi-news-podcast.yaml +9 -0
  35. package/plugins/generations/news-report-gen/dist/index.js +3 -3
  36. package/plugins/generations/voice-gen/dist/index.js +3 -3
  37. package/plugins/generations/voxcpm-tts/dist/index.js +3 -3
  38. package/plugins/ingestions/aihot-ingest/dist/index.js +3 -3
  39. package/plugins/ingestions/horizon-ingest/dist/index.js +3 -3
  40. package/plugins/ingestions/last30days-ingest/dist/index.js +3 -3
  41. package/plugins/ingestions/web-search/dist/index.js +3 -3
  42. package/plugins/kk/plugin.json +1 -1
  43. package/plugins/kk/publish-presets/daily-ai-voice-migration.json +12 -3
  44. package/plugins/kk/publish-presets/daily-ai-voice.json +11 -3
  45. package/plugins/kk/scripts/cover-compositor.ts +152 -0
  46. package/plugins/kk/scripts/daily-cover-mock.ts +164 -0
  47. package/plugins/kk/scripts/daily-scheduled-run.ts +192 -3
  48. package/plugins/kk/scripts/daily-stages.ts +599 -27
  49. package/plugins/kk/scripts/daily-triage-core.ts +451 -0
  50. package/plugins/kk/scripts/daily-triage.ts +74 -0
  51. package/plugins/kk/scripts/kk-workflow-stages.ts +51 -6
  52. package/plugins/kk/skills/content-judge/SKILL.md +5 -4
  53. package/plugins/kk/skills/content-judge/references/rubrics.md +14 -0
  54. package/plugins/kk/skills/content-safety/references/platforms/wechatmp.md +16 -10
  55. package/plugins/kk/skills/news-editorial/SKILL.md +122 -0
  56. package/plugins/kk/skills/news-editorial/references/selection.md +47 -0
  57. package/plugins/kk/skills/news-editorial/references/style-contract.zh.md +100 -0
  58. package/plugins/kk/skills/publish/SKILL.md +4 -4
  59. package/plugins/kk/skills/web-automation/SKILL.md +229 -77
  60. package/plugins/kk/skills/web-automation/references/browser-launch.md +127 -36
  61. package/plugins/kk/skills/wiki-authoring/SKILL.md +53 -0
  62. package/plugins/kk/skills/wiki-authoring/references/page-shapes.md +44 -0
  63. package/plugins/kk/workflows/kk-daily-ai-voice2.yaml +4 -6
  64. package/plugins/kk/workflows/kk-daily-ai-voice3.yaml +185 -224
  65. package/plugins/kk/workflows/kk-daily-publish3.yaml +16 -8
  66. package/plugins/kk/workflows/kk-daily-safety.yaml +32 -7
  67. package/plugins/publishings/bilibili-pub/dist/index.js +6 -4
  68. package/plugins/publishings/bilibili-pub/dist/profile-check.js +3 -1
  69. package/plugins/publishings/cnblogs-pub/dist/index.js +6 -4
  70. package/plugins/publishings/cnblogs-pub/dist/profile-check.js +3 -1
  71. package/plugins/publishings/csdn-pub/dist/index.js +6 -4
  72. package/plugins/publishings/csdn-pub/dist/profile-check.js +6 -4
  73. package/plugins/publishings/emdash-pub/dist/index.js +3 -3
  74. package/plugins/publishings/infoq-pub/dist/index.js +6 -4
  75. package/plugins/publishings/infoq-pub/dist/profile-check.js +6 -4
  76. package/plugins/publishings/jike-pub/dist/index.js +6 -4
  77. package/plugins/publishings/jike-pub/dist/profile-check.js +6 -4
  78. package/plugins/publishings/juejin-pub/dist/index.js +6 -4
  79. package/plugins/publishings/juejin-pub/dist/profile-check.js +6 -4
  80. package/plugins/publishings/linkedin-pub/dist/index.js +6 -4
  81. package/plugins/publishings/linkedin-pub/dist/profile-check.js +6 -4
  82. package/plugins/publishings/medium-pub/dist/index.js +3 -3
  83. package/plugins/publishings/podcast-pub/dist/index.js +148 -5
  84. package/plugins/publishings/podcast-pub/src/index.ts +71 -2
  85. package/plugins/publishings/podcast-pub/src/map.ts +3 -0
  86. package/plugins/publishings/podcast-pub/src/transcript.ts +195 -0
  87. package/plugins/publishings/qiita-pub/dist/index.js +3 -3
  88. package/plugins/publishings/shipinhao-pub/dist/index.js +227 -53
  89. package/plugins/publishings/shipinhao-pub/dist/profile-check.js +51 -2
  90. package/plugins/publishings/shipinhao-pub/plugin.json +2 -2
  91. package/plugins/publishings/shipinhao-pub/src/flow.ts +335 -79
  92. package/plugins/publishings/shipinhao-pub/src/index.ts +16 -8
  93. package/plugins/publishings/shipinhao-pub/src/profile-check.ts +1 -1
  94. package/plugins/publishings/shipinhao-pub/src/selectors.ts +103 -5
  95. package/plugins/publishings/sspai-pub/dist/index.js +6 -4
  96. package/plugins/publishings/sspai-pub/dist/profile-check.js +3 -1
  97. package/plugins/publishings/substack-pub/dist/index.js +6 -4
  98. package/plugins/publishings/substack-pub/dist/profile-check.js +6 -4
  99. package/plugins/publishings/surfdash-pub/dist/index.js +237 -14
  100. package/plugins/publishings/surfdash-pub/src/index.ts +127 -6
  101. package/plugins/publishings/surfdash-pub/src/topic-claims.ts +189 -0
  102. package/plugins/publishings/threads-pub/dist/index.js +3 -3
  103. package/plugins/publishings/wechatmp-pub/dist/index.js +62 -40
  104. package/plugins/publishings/wechatmp-pub/dist/profile-check.js +6 -4
  105. package/plugins/publishings/wechatmp-pub/src/enrich.ts +10 -3
  106. package/plugins/publishings/wechatmp-pub/src/flow.ts +73 -37
  107. package/plugins/publishings/wechatmp-pub/src/page.ts +14 -0
  108. package/plugins/publishings/weibo-pub/dist/index.js +6 -4
  109. package/plugins/publishings/weibo-pub/dist/profile-check.js +6 -4
  110. package/plugins/publishings/x-pub/dist/index.js +6 -4
  111. package/plugins/publishings/x-pub/dist/profile-check.js +6 -4
  112. package/plugins/publishings/xhs-pub/dist/index.js +562 -34
  113. package/plugins/publishings/xhs-pub/dist/profile-check.js +25 -4
  114. package/plugins/publishings/xhs-pub/src/errors.ts +45 -0
  115. package/plugins/publishings/xhs-pub/src/flow.ts +773 -45
  116. package/plugins/publishings/xhs-pub/src/page.ts +33 -0
  117. package/plugins/publishings/xiaoyuzhou-pub/dist/index.js +6 -4
  118. package/plugins/publishings/xiaoyuzhou-pub/dist/profile-check.js +3 -1
  119. package/plugins/publishings/zenn-pub/dist/index.js +3 -3
  120. package/plugins/kk/scripts/daily-voice-style.zh.md +0 -70
@@ -12073,7 +12073,7 @@ var init_src = () => {};
12073
12073
  import { createHash } from "crypto";
12074
12074
  import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
12075
12075
  import { copyFile, cp, writeFile } from "fs/promises";
12076
- import { dirname as dirname3, extname, isAbsolute, join as join2, relative, resolve, sep as sep2 } from "path";
12076
+ import { dirname as dirname4, extname, isAbsolute, join as join2, relative, resolve, sep as sep2 } from "path";
12077
12077
  import { parseArgs } from "util";
12078
12078
 
12079
12079
  // ../../packages/kk-core/src/content-limits.ts
@@ -12149,7 +12149,7 @@ var PLATFORM_CONTENT_LIMITS = Object.freeze({
12149
12149
  shortVideo: Object.freeze({
12150
12150
  douyin: Object.freeze({ max: 1000, unit: "unicode_code_points" }),
12151
12151
  kuaishou: Object.freeze({ max: 1000, unit: "unicode_code_points" }),
12152
- shipinhao: Object.freeze({ max: 1000, unit: "unicode_code_points" })
12152
+ shipinhao: Object.freeze({ max: 100, unit: "unicode_code_points" })
12153
12153
  })
12154
12154
  })
12155
12155
  });
@@ -12317,11 +12317,11 @@ var PluginManifestSchemaBase = looseObject({
12317
12317
  });
12318
12318
  var PluginManifestSchema = PluginManifestSchemaBase.superRefine((manifest, ctx) => {
12319
12319
  if (manifest.browserSession !== undefined) {
12320
- if (manifest.kind !== "publish") {
12320
+ if (manifest.kind !== "publish" && manifest.kind !== "ingestion") {
12321
12321
  ctx.addIssue({
12322
12322
  code: "custom",
12323
12323
  path: ["browserSession"],
12324
- message: `browserSession requires kind "publish", not "${manifest.kind}"`
12324
+ message: `browserSession requires kind "publish" or "ingestion", not "${manifest.kind}"`
12325
12325
  });
12326
12326
  }
12327
12327
  if (manifest.check === undefined) {
@@ -12670,6 +12670,143 @@ function checkDigestFrontmatter(markdown, locale) {
12670
12670
  return problems;
12671
12671
  }
12672
12672
 
12673
+ // ../../plugins/publishings/surfdash-pub/src/topic-claims.ts
12674
+ import { dirname as dirname3 } from "path";
12675
+ var escapeRe2 = (token) => token.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
12676
+ var titleSepFor = (locale) => locale === "en" ? ": " : "\uFF1A";
12677
+ var listSepFor = (locale) => locale === "en" ? ", " : "\u3001";
12678
+ function slugFromPostPath(postPath) {
12679
+ const normalized = postPath.replaceAll("\\", "/");
12680
+ const match = normalized.match(/(?:^|\/)posts\/articles\/(?:zh|en|ja)\/([^/]+)/);
12681
+ return match?.[1];
12682
+ }
12683
+ function tagList(frontmatter) {
12684
+ const tags = frontmatter.get("tags");
12685
+ if (Array.isArray(tags))
12686
+ return tags;
12687
+ if (typeof tags === "string" && tags !== "")
12688
+ return [tags];
12689
+ return [];
12690
+ }
12691
+ function isDigestMarkdown(markdown) {
12692
+ return tagList(parseFrontmatterScalars(markdown)).some((tag) => tag.includes(DIGEST_TAG));
12693
+ }
12694
+ function scalar2(frontmatter, key) {
12695
+ const value = frontmatter.get(key);
12696
+ if (value === undefined)
12697
+ return;
12698
+ return Array.isArray(value) ? value.join(" ") : value;
12699
+ }
12700
+ function parseTitleHeadlines(title, locale) {
12701
+ const series = SERIES_NAMES[locale];
12702
+ const titleSep = titleSepFor(locale);
12703
+ const listSep = listSepFor(locale);
12704
+ const match = title.match(new RegExp(`^${escapeRe2(series)} \xB7 (\\d{4}-\\d{2}-\\d{2})${escapeRe2(titleSep)}(.+)$`));
12705
+ if (!match?.[2])
12706
+ return;
12707
+ const heads = match[2].split(listSep).map((head) => head.trim());
12708
+ if (heads.length < 2 || heads.some((head) => head === ""))
12709
+ return;
12710
+ return heads;
12711
+ }
12712
+ function parseKeyPointParts(points) {
12713
+ const labels = [];
12714
+ const sentences = [];
12715
+ for (const point of points) {
12716
+ const sep = point.indexOf(" \u2014 ");
12717
+ if (sep < 0)
12718
+ return;
12719
+ const label = point.slice(0, sep).trim();
12720
+ const sentence = point.slice(sep + 3).trim();
12721
+ if (label === "" || sentence === "")
12722
+ return;
12723
+ labels.push(label);
12724
+ sentences.push(sentence);
12725
+ }
12726
+ return { labels, sentences };
12727
+ }
12728
+ function splitDescriptionParts(description, count) {
12729
+ for (const pattern of [/\uFF1B|; /, /\uFF1B|;/]) {
12730
+ const parts = description.split(pattern).map((part) => part.trim()).filter((part) => part !== "");
12731
+ if (parts.length === count)
12732
+ return parts;
12733
+ }
12734
+ return;
12735
+ }
12736
+ function buildLocaleEntry(markdown, locale) {
12737
+ if (!isDigestMarkdown(markdown)) {
12738
+ return `${locale}: missing ${DIGEST_TAG} tag`;
12739
+ }
12740
+ const frontmatter = parseFrontmatterScalars(markdown);
12741
+ const title = scalar2(frontmatter, "title") ?? "";
12742
+ const headlines = parseTitleHeadlines(title, locale);
12743
+ if (!headlines) {
12744
+ return `${locale}: title is not "<series> \xB7 YYYY-MM-DD${titleSepFor(locale)}h1${listSepFor(locale)}h2"`;
12745
+ }
12746
+ const description = (scalar2(frontmatter, "description") ?? scalar2(frontmatter, "seo_description") ?? "").trim();
12747
+ if (description === "") {
12748
+ return `${locale}: description is empty`;
12749
+ }
12750
+ const rawPoints = frontmatter.get("key_points");
12751
+ if (!Array.isArray(rawPoints) || rawPoints.length === 0) {
12752
+ return `${locale}: key_points is missing`;
12753
+ }
12754
+ const parts = parseKeyPointParts(rawPoints);
12755
+ if (!parts) {
12756
+ return `${locale}: key_points must be "label \u2014 sentence"`;
12757
+ }
12758
+ if (parts.labels.length !== headlines.length || parts.labels.some((label, i) => label !== headlines[i])) {
12759
+ return `${locale}: title headlines do not match key_points labels`;
12760
+ }
12761
+ const claims = parts.sentences;
12762
+ const shortClaims = splitDescriptionParts(description, headlines.length) ?? claims;
12763
+ return {
12764
+ headlines,
12765
+ description,
12766
+ key_points: headlines,
12767
+ claims,
12768
+ short_claims: shortClaims
12769
+ };
12770
+ }
12771
+ function buildDailyTopicsEntry(posts) {
12772
+ const entry = {};
12773
+ for (const locale of PATCH_LOCALES) {
12774
+ const markdown = posts[locale];
12775
+ if (typeof markdown !== "string" || markdown.trim() === "") {
12776
+ return { ok: false, error: `${locale}: post markdown is empty` };
12777
+ }
12778
+ const built = buildLocaleEntry(markdown, locale);
12779
+ if (typeof built === "string")
12780
+ return { ok: false, error: built };
12781
+ entry[locale] = built;
12782
+ }
12783
+ return { ok: true, entry };
12784
+ }
12785
+ async function upsertDailyTopicsEntry(mapPath, slug, entry, fileSystem = createNodeFileSystem()) {
12786
+ if (slug.trim() === "")
12787
+ throw new Error("daily-topics upsert: empty slug");
12788
+ let existing = {};
12789
+ if (await fileSystem.exists(mapPath)) {
12790
+ const raw = (await fileSystem.readFile(mapPath)).trim();
12791
+ if (raw !== "") {
12792
+ let parsed;
12793
+ try {
12794
+ parsed = JSON.parse(raw);
12795
+ } catch (error) {
12796
+ throw new Error(`daily-topics upsert: invalid JSON in ${mapPath}: ${error instanceof Error ? error.message : String(error)}`);
12797
+ }
12798
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
12799
+ throw new Error(`daily-topics upsert: ${mapPath} is not a JSON object`);
12800
+ }
12801
+ existing = parsed;
12802
+ }
12803
+ }
12804
+ existing[slug] = entry;
12805
+ await fileSystem.ensureDir(dirname3(mapPath));
12806
+ await fileSystem.writeFile(mapPath, `${JSON.stringify(existing, null, "\t")}
12807
+ `);
12808
+ }
12809
+
12673
12810
  // ../../plugins/publishings/surfdash-pub/src/index.ts
12674
12811
  var TARGET = "surfdash";
12675
12812
  var OPERATIONS = [
@@ -12745,7 +12882,7 @@ function failUncertain(error) {
12745
12882
  return failWithDeliveryState(error, "uncertain");
12746
12883
  }
12747
12884
  async function writePublishResult(outputPath, result) {
12748
- const outDir = dirname3(outputPath);
12885
+ const outDir = dirname4(outputPath);
12749
12886
  if (outDir && outDir !== ".") {
12750
12887
  await createNodeFileSystem().ensureDir(outDir);
12751
12888
  }
@@ -12795,7 +12932,7 @@ function deriveLocaleDraftPath(postPath, locale) {
12795
12932
  }
12796
12933
  function resolveSurfdashRoot() {
12797
12934
  const postsurfingBin = process.env.POSTSURFING_BIN ?? "postsurfing";
12798
- return process.env.SURFDASH_ROOT ?? (postsurfingBin.includes("/") ? resolve(dirname3(dirname3(postsurfingBin))) : undefined);
12935
+ return process.env.SURFDASH_ROOT ?? (postsurfingBin.includes("/") ? resolve(dirname4(dirname4(postsurfingBin))) : undefined);
12799
12936
  }
12800
12937
  async function spawnCli(cmd, cwd) {
12801
12938
  const env = { ...process.env };
@@ -12889,6 +13026,61 @@ async function runListenLinkBackfill(surfdashRoot) {
12889
13026
  const afterPaths = parsePorcelainPaths(after.stdout);
12890
13027
  return [...new Set(afterPaths.filter((p) => !beforePaths.has(p)))];
12891
13028
  }
13029
+ var DAILY_TOPICS_GIT_PATHS = ["scripts/seo/daily-topics.json", "content/posts"];
13030
+ async function runDailyTopicsSync(surfdashRoot, zhPostPath) {
13031
+ const enPath = localeIndexPath(zhPostPath, "en");
13032
+ const jaPath = localeIndexPath(zhPostPath, "ja");
13033
+ if (enPath === undefined || jaPath === undefined) {
13034
+ echoError(`daily-topics sync: skipped \u2014 ${zhPostPath} is not a zh locale post path`);
13035
+ return { ok: true, paths: [] };
13036
+ }
13037
+ if (!existsSync2(zhPostPath)) {
13038
+ echoError(`daily-topics sync: skipped \u2014 zh post is missing: ${zhPostPath}`);
13039
+ return { ok: true, paths: [] };
13040
+ }
13041
+ const zhPost = readFileSync2(zhPostPath, "utf-8");
13042
+ if (!isDigestMarkdown(zhPost)) {
13043
+ echoError(`daily-topics sync: skipped \u2014 not a digest post (no ${DIGEST_TAG} tag): ${zhPostPath}`);
13044
+ return { ok: true, paths: [] };
13045
+ }
13046
+ if (!existsSync2(enPath) || !existsSync2(jaPath)) {
13047
+ echoError(`daily-topics sync: skipped \u2014 locale index.md missing (en=${existsSync2(enPath)} ja=${existsSync2(jaPath)}): ${zhPostPath}`);
13048
+ return { ok: true, paths: [] };
13049
+ }
13050
+ const slug = slugFromPostPath(zhPostPath);
13051
+ if (slug === undefined) {
13052
+ return { ok: false, error: `daily-topics sync failed: cannot derive slug from ${zhPostPath}` };
13053
+ }
13054
+ const built = buildDailyTopicsEntry({
13055
+ zh: zhPost,
13056
+ en: readFileSync2(enPath, "utf-8"),
13057
+ ja: readFileSync2(jaPath, "utf-8")
13058
+ });
13059
+ if (!built.ok) {
13060
+ return { ok: false, error: `daily-topics sync failed: ${built.error}` };
13061
+ }
13062
+ const mapPath = join2(surfdashRoot, "scripts", "seo", "daily-topics.json");
13063
+ const before = await spawnCli(["git", "status", "--porcelain", "--", ...DAILY_TOPICS_GIT_PATHS], surfdashRoot);
13064
+ const beforePaths = new Set(parsePorcelainPaths(before.stdout));
13065
+ try {
13066
+ await upsertDailyTopicsEntry(mapPath, slug, built.entry);
13067
+ } catch (error) {
13068
+ return {
13069
+ ok: false,
13070
+ error: `daily-topics sync failed: ${error instanceof Error ? error.message : String(error)}`
13071
+ };
13072
+ }
13073
+ const retitle = await spawnCli(["bun", "run", "sd", "seo", "retitle", "--write", "--stamp-claims"], surfdashRoot);
13074
+ if (retitle.exitCode !== 0) {
13075
+ return {
13076
+ ok: false,
13077
+ error: `daily-topics sync failed: bun run sd seo retitle --write --stamp-claims (exit ${retitle.exitCode}): ${cliErrorText(retitle)}`
13078
+ };
13079
+ }
13080
+ const after = await spawnCli(["git", "status", "--porcelain", "--", ...DAILY_TOPICS_GIT_PATHS], surfdashRoot);
13081
+ const changed = parsePorcelainPaths(after.stdout).filter((p) => !beforePaths.has(p));
13082
+ return { ok: true, paths: [...new Set([relative(surfdashRoot, mapPath), ...changed])] };
13083
+ }
12892
13084
  var SITE_GATE_COMMANDS = [
12893
13085
  ["bun", "run", "sd", "check", "digest"],
12894
13086
  ["bun", "run", "check:content"]
@@ -12922,9 +13114,18 @@ function isUnrelatedDatePostFailure(output, ownedPaths) {
12922
13114
  }
12923
13115
  return true;
12924
13116
  }
13117
+ async function checkoutBranch(surfdashRoot) {
13118
+ const branch = await spawnCli(["git", "rev-parse", "--abbrev-ref", "HEAD"], surfdashRoot);
13119
+ return branch.exitCode === 0 ? branch.stdout.trim() : "";
13120
+ }
12925
13121
  async function runSiteGate(surfdashRoot, ownedPaths = []) {
13122
+ const pushingToMain = process.env.SURFDASH_AUTO_PUSH !== "0" && await checkoutBranch(surfdashRoot) === "main";
12926
13123
  if (process.env.SURFDASH_DIGEST_CHECK === "off") {
12927
- return { ok: true };
13124
+ if (pushingToMain) {
13125
+ echoError("site gate: SURFDASH_DIGEST_CHECK=off ignored \u2014 this run pushes to surfdash main, so the gate runs fail-closed");
13126
+ } else {
13127
+ return { ok: true };
13128
+ }
12928
13129
  }
12929
13130
  for (const cmd of SITE_GATE_COMMANDS) {
12930
13131
  const spawned = await spawnCli([...cmd], surfdashRoot);
@@ -12933,7 +13134,16 @@ async function runSiteGate(surfdashRoot, ownedPaths = []) {
12933
13134
  const postHint = extractFailingPostHint(output);
12934
13135
  const hint = postHint ? ` [failing post: ${postHint}]` : "";
12935
13136
  const error = `site gate failed: ${cmd.join(" ")} (exit ${spawned.exitCode})${hint}: ${output}`;
12936
- if (process.env.SURFDASH_DIGEST_CHECK === "warn" || isUnrelatedDatePostFailure(output, ownedPaths)) {
13137
+ const escapable = process.env.SURFDASH_DIGEST_CHECK === "warn" || isUnrelatedDatePostFailure(output, ownedPaths);
13138
+ if (escapable && pushingToMain) {
13139
+ echoError("site gate: warn/unrelated-date escape hatch ignored because this run pushes to surfdash main \u2014 failing closed (set SURFDASH_AUTO_PUSH=0 to skip the push entirely)");
13140
+ for (const line of error.split(`
13141
+ `)) {
13142
+ echoError(`site gate (blocked): ${line}`);
13143
+ }
13144
+ return { ok: false, error };
13145
+ }
13146
+ if (escapable) {
12937
13147
  for (const line of error.split(`
12938
13148
  `)) {
12939
13149
  echoError(`site gate (warn): ${line}`);
@@ -13083,9 +13293,9 @@ async function scaffoldLocale(options) {
13083
13293
  if (!existsSync2(draftPath)) {
13084
13294
  return fail(`sd translate reported success but the draft is missing: ${draftPath}`);
13085
13295
  }
13086
- const assetsDir = join2(dirname3(postPath.postPath), "assets");
13296
+ const assetsDir = join2(dirname4(postPath.postPath), "assets");
13087
13297
  if (existsSync2(assetsDir)) {
13088
- await cp(assetsDir, join2(dirname3(draftPath), "assets"), { recursive: true });
13298
+ await cp(assetsDir, join2(dirname4(draftPath), "assets"), { recursive: true });
13089
13299
  }
13090
13300
  return ResultSchema.parse({
13091
13301
  ok: true,
@@ -13183,13 +13393,18 @@ async function patchPost(options) {
13183
13393
  }
13184
13394
  if (outcome.changed === 0)
13185
13395
  echoError(`patch: no post bytes changed for ${outcome.slug}`);
13396
+ const topics = await runDailyTopicsSync(surfdashRoot, postPath.postPath);
13397
+ if (!topics.ok)
13398
+ return fail(topics.error);
13186
13399
  const synced = await syncPost({ postPath: postPath.postPath });
13187
13400
  const commitPaths = new Set(outcome.written.map((path) => relative(surfdashRoot, path)));
13401
+ for (const p of topics.paths)
13402
+ commitPaths.add(p);
13188
13403
  for (const locale of PATCH_LOCALES) {
13189
13404
  const indexMd = localeIndexPath(postPath.postPath, locale);
13190
13405
  if (!indexMd)
13191
13406
  continue;
13192
- const assetsDir = join2(dirname3(indexMd), "assets");
13407
+ const assetsDir = join2(dirname4(indexMd), "assets");
13193
13408
  if (existsSync2(assetsDir)) {
13194
13409
  commitPaths.add(relative(surfdashRoot, assetsDir));
13195
13410
  }
@@ -13374,7 +13589,7 @@ async function preparePost(payload) {
13374
13589
  const articlesRoot = resolve(surfdashRoot, "content", "posts", "articles");
13375
13590
  const localeRoot = resolve(articlesRoot, locale);
13376
13591
  const postDir = resolve(localeRoot, slug);
13377
- if (dirname3(localeRoot) !== articlesRoot || dirname3(postDir) !== localeRoot) {
13592
+ if (dirname4(localeRoot) !== articlesRoot || dirname4(postDir) !== localeRoot) {
13378
13593
  return { ok: false, result: failNotSent(`post path escapes ${articlesRoot}`) };
13379
13594
  }
13380
13595
  const coverPath = payload.content.metadata?.coverImage;
@@ -13489,13 +13704,16 @@ async function publishPreparedFile(prepared, identity) {
13489
13704
  }
13490
13705
  });
13491
13706
  }
13707
+ const topics = await runDailyTopicsSync(surfdashRoot, filePath);
13708
+ if (!topics.ok)
13709
+ return failUncertain(topics.error);
13492
13710
  const backfilled = await runListenLinkBackfill(surfdashRoot);
13493
13711
  const commitPaths = relPostDirs ?? [relPostDir];
13494
- const gate = await runSiteGate(surfdashRoot, [...commitPaths, ...backfilled]);
13712
+ const gate = await runSiteGate(surfdashRoot, [...commitPaths, ...backfilled, ...topics.paths]);
13495
13713
  if (!gate.ok)
13496
13714
  return failUncertain(gate.error);
13497
13715
  const commitLocales = relPostDirs === undefined ? [locale] : ["zh", "en", "ja"];
13498
- const pushed = await pushPostGit(surfdashRoot, commitPaths, `content: daily AI news ${dateStamp} (${commitLocales.join(", ")})`, backfilled);
13716
+ const pushed = await pushPostGit(surfdashRoot, commitPaths, `content: daily AI news ${dateStamp} (${commitLocales.join(", ")})`, [...backfilled, ...topics.paths]);
13499
13717
  if (!pushed.ok)
13500
13718
  return failUncertain(pushed.error);
13501
13719
  const live = await awaitArticleLive(articleUrl);
@@ -13652,6 +13870,7 @@ export {
13652
13870
  DIGEST_TAG,
13653
13871
  PostsurfingFileCliTransport,
13654
13872
  awaitArticleLive,
13873
+ buildDailyTopicsEntry,
13655
13874
  checkDigestFrontmatter,
13656
13875
  commitPostPaths,
13657
13876
  contentTags,
@@ -13659,6 +13878,7 @@ export {
13659
13878
  extractFailingPostHint,
13660
13879
  fastForwardToOrigin,
13661
13880
  getPublishTransport,
13881
+ isDigestMarkdown,
13662
13882
  main2 as main,
13663
13883
  mapContentToSurfingMarkdown,
13664
13884
  normalizeLocaleFrontmatter,
@@ -13667,8 +13887,11 @@ export {
13667
13887
  pushPostGit,
13668
13888
  readRefinedSnapshot,
13669
13889
  requireRefined,
13890
+ runDailyTopicsSync,
13670
13891
  runListenLinkBackfill,
13671
13892
  runSiteGate,
13893
+ slugFromPostPath,
13672
13894
  slugify2 as slugify,
13895
+ upsertDailyTopicsEntry,
13673
13896
  withEmdashTokenHint
13674
13897
  };
@@ -12,13 +12,23 @@
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
+ *
15
22
  * Environment variables:
16
23
  * - `SURFDASH_LISTEN_BACKFILL`:
17
24
  * - `off`: skips the listen-link backfill command.
18
25
  * - `SURFDASH_DIGEST_CHECK`:
19
26
  * - unset / default: fail-loud on gate failure; commit and push are blocked.
20
- * - `warn`: echoes gate failures via `echoError` prefixed with `site gate (warn):` and continues to push.
27
+ * - `warn`: echoes gate failures via `echoError` prefixed with `site gate (warn):` and continues.
21
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.
22
32
  * - `SURFDASH_AUTO_PUSH`:
23
33
  * - '0': disables auto-commit and push (used in tests and offline runs).
24
34
  */
@@ -34,8 +44,10 @@ import { echoError } from '@gobing-ai/ts-utils';
34
44
  // The plugin's public digest-contract surface (2026-10-24).
35
45
  import { checkDigestFrontmatter, DIGEST_TAG, type DigestLocale } from './digest-check';
36
46
  import { localeIndexPath, PATCH_LOCALES, type PatchPostOutcome, patchPostFiles } from './patch';
47
+ import { buildDailyTopicsEntry, isDigestMarkdown, slugFromPostPath, upsertDailyTopicsEntry } from './topic-claims';
37
48
 
38
49
  export { checkDigestFrontmatter, DIGEST_TAG, type DigestLocale } from './digest-check';
50
+ export { buildDailyTopicsEntry, isDigestMarkdown, slugFromPostPath, upsertDailyTopicsEntry } from './topic-claims';
39
51
 
40
52
  /** Result target name for this plugin. */
41
53
  const TARGET = 'surfdash';
@@ -458,6 +470,78 @@ export async function runListenLinkBackfill(surfdashRoot: string): Promise<strin
458
470
  return [...new Set(afterPaths.filter((p) => !beforePaths.has(p)))];
459
471
  }
460
472
 
473
+ /** Outcome of {@link runDailyTopicsSync} — `paths` are checkout-relative for the commit pathspec. */
474
+ export type DailyTopicsSyncOutcome = { ok: true; paths: string[] } | { ok: false; error: string };
475
+
476
+ /** Paths the sync's git diff watches: the map file plus everything the retitle may rewrite. */
477
+ const DAILY_TOPICS_GIT_PATHS = ['scripts/seo/daily-topics.json', 'content/posts'] as const;
478
+
479
+ /**
480
+ * Maps a digest post's three refined locale posts into the site's daily-topics map and runs
481
+ * the site's retitle over them (`bun run sd seo retitle --write --stamp-claims`).
482
+ *
483
+ * Skips (ok, no paths, logged) when the post is not a digest or not all of zh/en/ja `index.md`
484
+ * exist — the site gate still validates whatever the posts already carry. A failing entry build
485
+ * or retitle run returns `{ ok: false }` so the caller never commits or pushes. Returns the map
486
+ * file plus every path the retitle changed, for the commit pathspec.
487
+ */
488
+ export async function runDailyTopicsSync(surfdashRoot: string, zhPostPath: string): Promise<DailyTopicsSyncOutcome> {
489
+ const enPath = localeIndexPath(zhPostPath, 'en');
490
+ const jaPath = localeIndexPath(zhPostPath, 'ja');
491
+ if (enPath === undefined || jaPath === undefined) {
492
+ echoError(`daily-topics sync: skipped — ${zhPostPath} is not a zh locale post path`);
493
+ return { ok: true, paths: [] };
494
+ }
495
+ if (!existsSync(zhPostPath)) {
496
+ echoError(`daily-topics sync: skipped — zh post is missing: ${zhPostPath}`);
497
+ return { ok: true, paths: [] };
498
+ }
499
+ const zhPost = readFileSync(zhPostPath, 'utf-8');
500
+ if (!isDigestMarkdown(zhPost)) {
501
+ echoError(`daily-topics sync: skipped — not a digest post (no ${DIGEST_TAG} tag): ${zhPostPath}`);
502
+ return { ok: true, paths: [] };
503
+ }
504
+ if (!existsSync(enPath) || !existsSync(jaPath)) {
505
+ echoError(
506
+ `daily-topics sync: skipped — locale index.md missing (en=${existsSync(enPath)} ja=${existsSync(jaPath)}): ${zhPostPath}`,
507
+ );
508
+ return { ok: true, paths: [] };
509
+ }
510
+ const slug = slugFromPostPath(zhPostPath);
511
+ if (slug === undefined) {
512
+ return { ok: false, error: `daily-topics sync failed: cannot derive slug from ${zhPostPath}` };
513
+ }
514
+ const built = buildDailyTopicsEntry({
515
+ zh: zhPost,
516
+ en: readFileSync(enPath, 'utf-8'),
517
+ ja: readFileSync(jaPath, 'utf-8'),
518
+ });
519
+ if (!built.ok) {
520
+ return { ok: false, error: `daily-topics sync failed: ${built.error}` };
521
+ }
522
+ const mapPath = join(surfdashRoot, 'scripts', 'seo', 'daily-topics.json');
523
+ const before = await spawnCli(['git', 'status', '--porcelain', '--', ...DAILY_TOPICS_GIT_PATHS], surfdashRoot);
524
+ const beforePaths = new Set(parsePorcelainPaths(before.stdout));
525
+ try {
526
+ await upsertDailyTopicsEntry(mapPath, slug, built.entry);
527
+ } catch (error: unknown) {
528
+ return {
529
+ ok: false,
530
+ error: `daily-topics sync failed: ${error instanceof Error ? error.message : String(error)}`,
531
+ };
532
+ }
533
+ const retitle = await spawnCli(['bun', 'run', 'sd', 'seo', 'retitle', '--write', '--stamp-claims'], surfdashRoot);
534
+ if (retitle.exitCode !== 0) {
535
+ return {
536
+ ok: false,
537
+ error: `daily-topics sync failed: bun run sd seo retitle --write --stamp-claims (exit ${retitle.exitCode}): ${cliErrorText(retitle)}`,
538
+ };
539
+ }
540
+ const after = await spawnCli(['git', 'status', '--porcelain', '--', ...DAILY_TOPICS_GIT_PATHS], surfdashRoot);
541
+ const changed = parsePorcelainPaths(after.stdout).filter((p) => !beforePaths.has(p));
542
+ return { ok: true, paths: [...new Set([relative(surfdashRoot, mapPath), ...changed])] };
543
+ }
544
+
461
545
  /** Outcome of {@link runSiteGate}. */
462
546
  export type SiteGateOutcome = { ok: true } | { ok: false; error: string };
463
547
 
@@ -499,11 +583,23 @@ function isUnrelatedDatePostFailure(output: string, ownedPaths: readonly string[
499
583
  return true;
500
584
  }
501
585
 
586
+ /** The checkout's current branch name, or '' when git fails (the caller keeps its existing behavior). */
587
+ async function checkoutBranch(surfdashRoot: string): Promise<string> {
588
+ const branch = await spawnCli(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], surfdashRoot);
589
+ return branch.exitCode === 0 ? branch.stdout.trim() : '';
590
+ }
591
+
502
592
  /**
503
593
  * Runs the surfdash site gates (`bun run sd check digest` then `bun run check:content`)
504
594
  * with cwd = `surfdashRoot` via `spawnCli`.
505
595
  *
506
- * If either command exits non-zero:
596
+ * Fail-closed on main pushes: when the checkout is on `main` and this run will push
597
+ * (`SURFDASH_AUTO_PUSH !== '0'`), a failing gate ALWAYS returns `{ ok: false }` — the
598
+ * `warn` / unrelated-date escape hatch logs that it was ignored (this is a push to main)
599
+ * plus the gate output and failing-post hint, and `off` still runs the gate instead of
600
+ * skipping it.
601
+ *
602
+ * Otherwise:
507
603
  * - With `SURFDASH_DIGEST_CHECK=warn` (or when every failing post belongs to an unrelated date
508
604
  * outside `ownedPaths`): echoes each line of the failure via `echoError` prefixed with
509
605
  * `site gate (warn):` and continues.
@@ -511,8 +607,15 @@ function isUnrelatedDatePostFailure(output: string, ownedPaths: readonly string[
511
607
  * - Default (unset or any other value): fails loud with command, trimmed output, and post hint.
512
608
  */
513
609
  export async function runSiteGate(surfdashRoot: string, ownedPaths: readonly string[] = []): Promise<SiteGateOutcome> {
610
+ const pushingToMain = process.env.SURFDASH_AUTO_PUSH !== '0' && (await checkoutBranch(surfdashRoot)) === 'main';
514
611
  if (process.env.SURFDASH_DIGEST_CHECK === 'off') {
515
- return { ok: true };
612
+ if (pushingToMain) {
613
+ echoError(
614
+ 'site gate: SURFDASH_DIGEST_CHECK=off ignored — this run pushes to surfdash main, so the gate runs fail-closed',
615
+ );
616
+ } else {
617
+ return { ok: true };
618
+ }
516
619
  }
517
620
 
518
621
  for (const cmd of SITE_GATE_COMMANDS) {
@@ -522,7 +625,18 @@ export async function runSiteGate(surfdashRoot: string, ownedPaths: readonly str
522
625
  const postHint = extractFailingPostHint(output);
523
626
  const hint = postHint ? ` [failing post: ${postHint}]` : '';
524
627
  const error = `site gate failed: ${cmd.join(' ')} (exit ${spawned.exitCode})${hint}: ${output}`;
525
- if (process.env.SURFDASH_DIGEST_CHECK === 'warn' || isUnrelatedDatePostFailure(output, ownedPaths)) {
628
+ const escapable =
629
+ process.env.SURFDASH_DIGEST_CHECK === 'warn' || isUnrelatedDatePostFailure(output, ownedPaths);
630
+ if (escapable && pushingToMain) {
631
+ echoError(
632
+ 'site gate: warn/unrelated-date escape hatch ignored because this run pushes to surfdash main — failing closed (set SURFDASH_AUTO_PUSH=0 to skip the push entirely)',
633
+ );
634
+ for (const line of error.split('\n')) {
635
+ echoError(`site gate (blocked): ${line}`);
636
+ }
637
+ return { ok: false, error };
638
+ }
639
+ if (escapable) {
526
640
  for (const line of error.split('\n')) {
527
641
  echoError(`site gate (warn): ${line}`);
528
642
  }
@@ -862,8 +976,13 @@ async function patchPost(options: SurfdashPubOptions): Promise<Result> {
862
976
  return fail(`patch error: ${error instanceof Error ? error.message : String(error)}`);
863
977
  }
864
978
  if (outcome.changed === 0) echoError(`patch: no post bytes changed for ${outcome.slug}`);
979
+ // Daily-topics map + retitle run before the CMS sync so the synced rows carry the retitled
980
+ // frontmatter; a failure here must not commit or push a half-synced post.
981
+ const topics = await runDailyTopicsSync(surfdashRoot, postPath.postPath);
982
+ if (!topics.ok) return fail(topics.error);
865
983
  const synced = await syncPost({ postPath: postPath.postPath });
866
984
  const commitPaths = new Set(outcome.written.map((path) => relative(surfdashRoot, path)));
985
+ for (const p of topics.paths) commitPaths.add(p);
867
986
  for (const locale of PATCH_LOCALES) {
868
987
  const indexMd = localeIndexPath(postPath.postPath, locale);
869
988
  if (!indexMd) continue;
@@ -1282,16 +1401,18 @@ async function publishPreparedFile(
1282
1401
  },
1283
1402
  });
1284
1403
  }
1404
+ const topics = await runDailyTopicsSync(surfdashRoot, filePath);
1405
+ if (!topics.ok) return failUncertain(topics.error);
1285
1406
  const backfilled = await runListenLinkBackfill(surfdashRoot);
1286
1407
  const commitPaths = relPostDirs ?? [relPostDir];
1287
- const gate = await runSiteGate(surfdashRoot, [...commitPaths, ...backfilled]);
1408
+ const gate = await runSiteGate(surfdashRoot, [...commitPaths, ...backfilled, ...topics.paths]);
1288
1409
  if (!gate.ok) return failUncertain(gate.error);
1289
1410
  const commitLocales: SupportedLocale[] = relPostDirs === undefined ? [locale] : ['zh', 'en', 'ja'];
1290
1411
  const pushed = await pushPostGit(
1291
1412
  surfdashRoot,
1292
1413
  commitPaths,
1293
1414
  `content: daily AI news ${dateStamp} (${commitLocales.join(', ')})`,
1294
- backfilled,
1415
+ [...backfilled, ...topics.paths],
1295
1416
  );
1296
1417
  if (!pushed.ok) return failUncertain(pushed.error);
1297
1418
  const live = await awaitArticleLive(articleUrl);