@gobing-ai/knowledge-kit 0.1.15 → 0.1.17

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 (116) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/index.js +1765 -40
  3. package/package.json +1 -1
  4. package/plugins/generations/content-gen/dist/index.js +58 -52
  5. package/plugins/generations/content-gen/src/storm.ts +94 -61
  6. package/plugins/generations/core-facts-gen/dist/index.js +1 -1
  7. package/plugins/generations/daily-article-gen/dist/index.js +1 -1
  8. package/plugins/generations/dailynews-gen/dist/index.js +1 -1
  9. package/plugins/generations/episode-plan-gen/dist/index.js +1 -1
  10. package/plugins/generations/gemini-tts/dist/index.js +1 -1
  11. package/plugins/generations/image-gen/README.md +31 -10
  12. package/plugins/generations/image-gen/assets/sample/cover__quasi-news-podcast.jpg +0 -0
  13. package/plugins/generations/image-gen/assets/sample/daily-news-cover__quasi-news-podcast.jpg +0 -0
  14. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__clean-webapp-ui.jpg +0 -0
  15. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__cute.jpg +0 -0
  16. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__daily-news.jpg +0 -0
  17. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__editorial.jpg +0 -0
  18. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__fresh.jpg +0 -0
  19. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__minimalist.jpg +0 -0
  20. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__photorealistic.jpg +0 -0
  21. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__quasi-news-podcast.jpg +0 -0
  22. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__sketch.jpg +0 -0
  23. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__technical-diagram.jpg +0 -0
  24. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__vibrant.jpg +0 -0
  25. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__warm.jpg +0 -0
  26. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__xhs-knowledge.jpg +0 -0
  27. package/plugins/generations/image-gen/assets/sample/free__quasi-news-podcast.jpg +0 -0
  28. package/plugins/generations/image-gen/assets/sample/illustration__quasi-news-podcast.jpg +0 -0
  29. package/plugins/generations/image-gen/assets/sample/xhs-card__quasi-news-podcast.jpg +0 -0
  30. package/plugins/generations/image-gen/dist/index.js +1 -1
  31. package/plugins/generations/image-gen/presets/formats/daily-news-podcast-cover.yaml +18 -0
  32. package/plugins/generations/image-gen/presets/styles/quasi-news-podcast.yaml +9 -0
  33. package/plugins/generations/news-report-gen/dist/index.js +1 -1
  34. package/plugins/generations/voice-gen/dist/index.js +1 -1
  35. package/plugins/generations/voxcpm-tts/dist/index.js +1 -1
  36. package/plugins/ingestions/aihot-ingest/dist/index.js +1 -1
  37. package/plugins/ingestions/horizon-ingest/dist/index.js +1 -1
  38. package/plugins/ingestions/last30days-ingest/dist/index.js +1 -1
  39. package/plugins/ingestions/web-search/dist/index.js +1 -1
  40. package/plugins/kk/plugin.json +1 -1
  41. package/plugins/kk/publish-presets/daily-ai-voice-migration.json +12 -3
  42. package/plugins/kk/publish-presets/daily-ai-voice.json +17 -9
  43. package/plugins/kk/publish-presets/itc-main.json +42 -0
  44. package/plugins/kk/scripts/cover-compositor.ts +198 -0
  45. package/plugins/kk/scripts/daily-cover-mock.ts +164 -0
  46. package/plugins/kk/scripts/daily-scheduled-run.ts +188 -3
  47. package/plugins/kk/scripts/daily-stages.ts +134 -26
  48. package/plugins/kk/scripts/daily-triage-core.ts +451 -0
  49. package/plugins/kk/scripts/daily-triage.ts +74 -0
  50. package/plugins/kk/scripts/itc-stages.ts +3 -2
  51. package/plugins/kk/scripts/kk-workflow-stages.ts +31 -2
  52. package/plugins/kk/scripts/voice3-publish-window.ts +5 -1
  53. package/plugins/kk/skills/content-safety/references/platforms/wechatmp.md +16 -10
  54. package/plugins/kk/skills/news-editorial/SKILL.md +3 -3
  55. package/plugins/kk/skills/news-editorial/references/style-contract.zh.md +2 -1
  56. package/plugins/kk/skills/publish/SKILL.md +1 -1
  57. package/plugins/kk/skills/wiki-authoring/SKILL.md +53 -0
  58. package/plugins/kk/skills/wiki-authoring/references/page-shapes.md +44 -0
  59. package/plugins/kk/workflows/kk-daily-ai-voice3.yaml +3 -3
  60. package/plugins/kk/workflows/kk-daily-publish3.yaml +10 -3
  61. package/plugins/kk/workflows/kk-daily-safety.yaml +32 -7
  62. package/plugins/publishings/bilibili-pub/dist/index.js +90 -17
  63. package/plugins/publishings/bilibili-pub/dist/profile-check.js +90 -16
  64. package/plugins/publishings/cnblogs-pub/dist/index.js +90 -17
  65. package/plugins/publishings/cnblogs-pub/dist/profile-check.js +90 -16
  66. package/plugins/publishings/csdn-pub/dist/index.js +90 -17
  67. package/plugins/publishings/csdn-pub/dist/profile-check.js +91 -17
  68. package/plugins/publishings/emdash-pub/dist/index.js +1 -1
  69. package/plugins/publishings/infoq-pub/dist/index.js +120 -19
  70. package/plugins/publishings/infoq-pub/dist/profile-check.js +95 -18
  71. package/plugins/publishings/infoq-pub/src/index.ts +40 -1
  72. package/plugins/publishings/jike-pub/dist/index.js +90 -17
  73. package/plugins/publishings/jike-pub/dist/profile-check.js +91 -17
  74. package/plugins/publishings/juejin-pub/dist/index.js +117 -20
  75. package/plugins/publishings/juejin-pub/dist/profile-check.js +94 -18
  76. package/plugins/publishings/juejin-pub/src/index.ts +41 -2
  77. package/plugins/publishings/linkedin-pub/dist/index.js +90 -17
  78. package/plugins/publishings/linkedin-pub/dist/profile-check.js +91 -17
  79. package/plugins/publishings/medium-pub/dist/index.js +1 -1
  80. package/plugins/publishings/podcast-pub/dist/index.js +1 -1
  81. package/plugins/publishings/qiita-pub/dist/index.js +1 -1
  82. package/plugins/publishings/shipinhao-pub/dist/index.js +311 -66
  83. package/plugins/publishings/shipinhao-pub/dist/profile-check.js +138 -17
  84. package/plugins/publishings/shipinhao-pub/plugin.json +2 -2
  85. package/plugins/publishings/shipinhao-pub/src/flow.ts +335 -79
  86. package/plugins/publishings/shipinhao-pub/src/index.ts +16 -8
  87. package/plugins/publishings/shipinhao-pub/src/profile-check.ts +1 -1
  88. package/plugins/publishings/shipinhao-pub/src/selectors.ts +103 -5
  89. package/plugins/publishings/sspai-pub/dist/index.js +90 -17
  90. package/plugins/publishings/sspai-pub/dist/profile-check.js +90 -16
  91. package/plugins/publishings/substack-pub/dist/index.js +90 -17
  92. package/plugins/publishings/substack-pub/dist/profile-check.js +91 -17
  93. package/plugins/publishings/surfdash-pub/dist/index.js +244 -13
  94. package/plugins/publishings/surfdash-pub/src/index.ts +144 -8
  95. package/plugins/publishings/surfdash-pub/src/topic-claims.ts +189 -0
  96. package/plugins/publishings/threads-pub/dist/index.js +1 -1
  97. package/plugins/publishings/wechatmp-pub/dist/index.js +186 -39
  98. package/plugins/publishings/wechatmp-pub/dist/profile-check.js +96 -19
  99. package/plugins/publishings/wechatmp-pub/src/cgi-draft.ts +14 -2
  100. package/plugins/publishings/wechatmp-pub/src/enrich.ts +10 -3
  101. package/plugins/publishings/wechatmp-pub/src/flow.ts +158 -25
  102. package/plugins/publishings/wechatmp-pub/src/page.ts +14 -0
  103. package/plugins/publishings/wechatmp-pub/src/profile-check.ts +8 -1
  104. package/plugins/publishings/weibo-pub/dist/index.js +90 -17
  105. package/plugins/publishings/weibo-pub/dist/profile-check.js +91 -17
  106. package/plugins/publishings/x-pub/dist/index.js +90 -17
  107. package/plugins/publishings/x-pub/dist/profile-check.js +91 -17
  108. package/plugins/publishings/xhs-pub/dist/index.js +646 -47
  109. package/plugins/publishings/xhs-pub/dist/profile-check.js +109 -17
  110. package/plugins/publishings/xhs-pub/src/errors.ts +45 -0
  111. package/plugins/publishings/xhs-pub/src/flow.ts +773 -45
  112. package/plugins/publishings/xhs-pub/src/page.ts +33 -0
  113. package/plugins/publishings/xiaoyuzhou-pub/dist/index.js +90 -17
  114. package/plugins/publishings/xiaoyuzhou-pub/dist/profile-check.js +90 -16
  115. package/plugins/publishings/zenn-pub/dist/index.js +94 -2
  116. package/plugins/publishings/zenn-pub/src/index.ts +134 -1
@@ -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
  });
@@ -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 = [
@@ -12736,7 +12873,15 @@ function fail(error) {
12736
12873
  return ResultSchema.parse({ ok: false, target: TARGET, error });
12737
12874
  }
12738
12875
  function failWithDeliveryState(error, deliveryState) {
12739
- return ResultSchema.parse({ ok: false, target: TARGET, error, metadata: { deliveryState } });
12876
+ return ResultSchema.parse({
12877
+ ok: false,
12878
+ target: TARGET,
12879
+ error,
12880
+ metadata: {
12881
+ deliveryState,
12882
+ itcDelivery: { schemaVersion: 1, effect: deliveryState === "not-sent" ? "none" : "unknown" }
12883
+ }
12884
+ });
12740
12885
  }
12741
12886
  function failNotSent(error) {
12742
12887
  return failWithDeliveryState(error, "not-sent");
@@ -12745,7 +12890,7 @@ function failUncertain(error) {
12745
12890
  return failWithDeliveryState(error, "uncertain");
12746
12891
  }
12747
12892
  async function writePublishResult(outputPath, result) {
12748
- const outDir = dirname3(outputPath);
12893
+ const outDir = dirname4(outputPath);
12749
12894
  if (outDir && outDir !== ".") {
12750
12895
  await createNodeFileSystem().ensureDir(outDir);
12751
12896
  }
@@ -12795,7 +12940,7 @@ function deriveLocaleDraftPath(postPath, locale) {
12795
12940
  }
12796
12941
  function resolveSurfdashRoot() {
12797
12942
  const postsurfingBin = process.env.POSTSURFING_BIN ?? "postsurfing";
12798
- return process.env.SURFDASH_ROOT ?? (postsurfingBin.includes("/") ? resolve(dirname3(dirname3(postsurfingBin))) : undefined);
12943
+ return process.env.SURFDASH_ROOT ?? (postsurfingBin.includes("/") ? resolve(dirname4(dirname4(postsurfingBin))) : undefined);
12799
12944
  }
12800
12945
  async function spawnCli(cmd, cwd) {
12801
12946
  const env = { ...process.env };
@@ -12889,6 +13034,61 @@ async function runListenLinkBackfill(surfdashRoot) {
12889
13034
  const afterPaths = parsePorcelainPaths(after.stdout);
12890
13035
  return [...new Set(afterPaths.filter((p) => !beforePaths.has(p)))];
12891
13036
  }
13037
+ var DAILY_TOPICS_GIT_PATHS = ["scripts/seo/daily-topics.json", "content/posts"];
13038
+ async function runDailyTopicsSync(surfdashRoot, zhPostPath) {
13039
+ const enPath = localeIndexPath(zhPostPath, "en");
13040
+ const jaPath = localeIndexPath(zhPostPath, "ja");
13041
+ if (enPath === undefined || jaPath === undefined) {
13042
+ echoError(`daily-topics sync: skipped \u2014 ${zhPostPath} is not a zh locale post path`);
13043
+ return { ok: true, paths: [] };
13044
+ }
13045
+ if (!existsSync2(zhPostPath)) {
13046
+ echoError(`daily-topics sync: skipped \u2014 zh post is missing: ${zhPostPath}`);
13047
+ return { ok: true, paths: [] };
13048
+ }
13049
+ const zhPost = readFileSync2(zhPostPath, "utf-8");
13050
+ if (!isDigestMarkdown(zhPost)) {
13051
+ echoError(`daily-topics sync: skipped \u2014 not a digest post (no ${DIGEST_TAG} tag): ${zhPostPath}`);
13052
+ return { ok: true, paths: [] };
13053
+ }
13054
+ if (!existsSync2(enPath) || !existsSync2(jaPath)) {
13055
+ echoError(`daily-topics sync: skipped \u2014 locale index.md missing (en=${existsSync2(enPath)} ja=${existsSync2(jaPath)}): ${zhPostPath}`);
13056
+ return { ok: true, paths: [] };
13057
+ }
13058
+ const slug = slugFromPostPath(zhPostPath);
13059
+ if (slug === undefined) {
13060
+ return { ok: false, error: `daily-topics sync failed: cannot derive slug from ${zhPostPath}` };
13061
+ }
13062
+ const built = buildDailyTopicsEntry({
13063
+ zh: zhPost,
13064
+ en: readFileSync2(enPath, "utf-8"),
13065
+ ja: readFileSync2(jaPath, "utf-8")
13066
+ });
13067
+ if (!built.ok) {
13068
+ return { ok: false, error: `daily-topics sync failed: ${built.error}` };
13069
+ }
13070
+ const mapPath = join2(surfdashRoot, "scripts", "seo", "daily-topics.json");
13071
+ const before = await spawnCli(["git", "status", "--porcelain", "--", ...DAILY_TOPICS_GIT_PATHS], surfdashRoot);
13072
+ const beforePaths = new Set(parsePorcelainPaths(before.stdout));
13073
+ try {
13074
+ await upsertDailyTopicsEntry(mapPath, slug, built.entry);
13075
+ } catch (error) {
13076
+ return {
13077
+ ok: false,
13078
+ error: `daily-topics sync failed: ${error instanceof Error ? error.message : String(error)}`
13079
+ };
13080
+ }
13081
+ const retitle = await spawnCli(["bun", "run", "sd", "seo", "retitle", "--write", "--stamp-claims"], surfdashRoot);
13082
+ if (retitle.exitCode !== 0) {
13083
+ return {
13084
+ ok: false,
13085
+ error: `daily-topics sync failed: bun run sd seo retitle --write --stamp-claims (exit ${retitle.exitCode}): ${cliErrorText(retitle)}`
13086
+ };
13087
+ }
13088
+ const after = await spawnCli(["git", "status", "--porcelain", "--", ...DAILY_TOPICS_GIT_PATHS], surfdashRoot);
13089
+ const changed = parsePorcelainPaths(after.stdout).filter((p) => !beforePaths.has(p));
13090
+ return { ok: true, paths: [...new Set([relative(surfdashRoot, mapPath), ...changed])] };
13091
+ }
12892
13092
  var SITE_GATE_COMMANDS = [
12893
13093
  ["bun", "run", "sd", "check", "digest"],
12894
13094
  ["bun", "run", "check:content"]
@@ -12922,9 +13122,18 @@ function isUnrelatedDatePostFailure(output, ownedPaths) {
12922
13122
  }
12923
13123
  return true;
12924
13124
  }
13125
+ async function checkoutBranch(surfdashRoot) {
13126
+ const branch = await spawnCli(["git", "rev-parse", "--abbrev-ref", "HEAD"], surfdashRoot);
13127
+ return branch.exitCode === 0 ? branch.stdout.trim() : "";
13128
+ }
12925
13129
  async function runSiteGate(surfdashRoot, ownedPaths = []) {
13130
+ const pushingToMain = process.env.SURFDASH_AUTO_PUSH !== "0" && await checkoutBranch(surfdashRoot) === "main";
12926
13131
  if (process.env.SURFDASH_DIGEST_CHECK === "off") {
12927
- return { ok: true };
13132
+ if (pushingToMain) {
13133
+ echoError("site gate: SURFDASH_DIGEST_CHECK=off ignored \u2014 this run pushes to surfdash main, so the gate runs fail-closed");
13134
+ } else {
13135
+ return { ok: true };
13136
+ }
12928
13137
  }
12929
13138
  for (const cmd of SITE_GATE_COMMANDS) {
12930
13139
  const spawned = await spawnCli([...cmd], surfdashRoot);
@@ -12933,7 +13142,16 @@ async function runSiteGate(surfdashRoot, ownedPaths = []) {
12933
13142
  const postHint = extractFailingPostHint(output);
12934
13143
  const hint = postHint ? ` [failing post: ${postHint}]` : "";
12935
13144
  const error = `site gate failed: ${cmd.join(" ")} (exit ${spawned.exitCode})${hint}: ${output}`;
12936
- if (process.env.SURFDASH_DIGEST_CHECK === "warn" || isUnrelatedDatePostFailure(output, ownedPaths)) {
13145
+ const escapable = process.env.SURFDASH_DIGEST_CHECK === "warn" || isUnrelatedDatePostFailure(output, ownedPaths);
13146
+ if (escapable && pushingToMain) {
13147
+ 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)");
13148
+ for (const line of error.split(`
13149
+ `)) {
13150
+ echoError(`site gate (blocked): ${line}`);
13151
+ }
13152
+ return { ok: false, error };
13153
+ }
13154
+ if (escapable) {
12937
13155
  for (const line of error.split(`
12938
13156
  `)) {
12939
13157
  echoError(`site gate (warn): ${line}`);
@@ -13083,9 +13301,9 @@ async function scaffoldLocale(options) {
13083
13301
  if (!existsSync2(draftPath)) {
13084
13302
  return fail(`sd translate reported success but the draft is missing: ${draftPath}`);
13085
13303
  }
13086
- const assetsDir = join2(dirname3(postPath.postPath), "assets");
13304
+ const assetsDir = join2(dirname4(postPath.postPath), "assets");
13087
13305
  if (existsSync2(assetsDir)) {
13088
- await cp(assetsDir, join2(dirname3(draftPath), "assets"), { recursive: true });
13306
+ await cp(assetsDir, join2(dirname4(draftPath), "assets"), { recursive: true });
13089
13307
  }
13090
13308
  return ResultSchema.parse({
13091
13309
  ok: true,
@@ -13183,13 +13401,18 @@ async function patchPost(options) {
13183
13401
  }
13184
13402
  if (outcome.changed === 0)
13185
13403
  echoError(`patch: no post bytes changed for ${outcome.slug}`);
13404
+ const topics = await runDailyTopicsSync(surfdashRoot, postPath.postPath);
13405
+ if (!topics.ok)
13406
+ return fail(topics.error);
13186
13407
  const synced = await syncPost({ postPath: postPath.postPath });
13187
13408
  const commitPaths = new Set(outcome.written.map((path) => relative(surfdashRoot, path)));
13409
+ for (const p of topics.paths)
13410
+ commitPaths.add(p);
13188
13411
  for (const locale of PATCH_LOCALES) {
13189
13412
  const indexMd = localeIndexPath(postPath.postPath, locale);
13190
13413
  if (!indexMd)
13191
13414
  continue;
13192
- const assetsDir = join2(dirname3(indexMd), "assets");
13415
+ const assetsDir = join2(dirname4(indexMd), "assets");
13193
13416
  if (existsSync2(assetsDir)) {
13194
13417
  commitPaths.add(relative(surfdashRoot, assetsDir));
13195
13418
  }
@@ -13374,7 +13597,7 @@ async function preparePost(payload) {
13374
13597
  const articlesRoot = resolve(surfdashRoot, "content", "posts", "articles");
13375
13598
  const localeRoot = resolve(articlesRoot, locale);
13376
13599
  const postDir = resolve(localeRoot, slug);
13377
- if (dirname3(localeRoot) !== articlesRoot || dirname3(postDir) !== localeRoot) {
13600
+ if (dirname4(localeRoot) !== articlesRoot || dirname4(postDir) !== localeRoot) {
13378
13601
  return { ok: false, result: failNotSent(`post path escapes ${articlesRoot}`) };
13379
13602
  }
13380
13603
  const coverPath = payload.content.metadata?.coverImage;
@@ -13489,13 +13712,16 @@ async function publishPreparedFile(prepared, identity) {
13489
13712
  }
13490
13713
  });
13491
13714
  }
13715
+ const topics = await runDailyTopicsSync(surfdashRoot, filePath);
13716
+ if (!topics.ok)
13717
+ return failUncertain(topics.error);
13492
13718
  const backfilled = await runListenLinkBackfill(surfdashRoot);
13493
13719
  const commitPaths = relPostDirs ?? [relPostDir];
13494
- const gate = await runSiteGate(surfdashRoot, [...commitPaths, ...backfilled]);
13720
+ const gate = await runSiteGate(surfdashRoot, [...commitPaths, ...backfilled, ...topics.paths]);
13495
13721
  if (!gate.ok)
13496
13722
  return failUncertain(gate.error);
13497
13723
  const commitLocales = relPostDirs === undefined ? [locale] : ["zh", "en", "ja"];
13498
- const pushed = await pushPostGit(surfdashRoot, commitPaths, `content: daily AI news ${dateStamp} (${commitLocales.join(", ")})`, backfilled);
13724
+ const pushed = await pushPostGit(surfdashRoot, commitPaths, `content: daily AI news ${dateStamp} (${commitLocales.join(", ")})`, [...backfilled, ...topics.paths]);
13499
13725
  if (!pushed.ok)
13500
13726
  return failUncertain(pushed.error);
13501
13727
  const live = await awaitArticleLive(articleUrl);
@@ -13652,6 +13878,7 @@ export {
13652
13878
  DIGEST_TAG,
13653
13879
  PostsurfingFileCliTransport,
13654
13880
  awaitArticleLive,
13881
+ buildDailyTopicsEntry,
13655
13882
  checkDigestFrontmatter,
13656
13883
  commitPostPaths,
13657
13884
  contentTags,
@@ -13659,6 +13886,7 @@ export {
13659
13886
  extractFailingPostHint,
13660
13887
  fastForwardToOrigin,
13661
13888
  getPublishTransport,
13889
+ isDigestMarkdown,
13662
13890
  main2 as main,
13663
13891
  mapContentToSurfingMarkdown,
13664
13892
  normalizeLocaleFrontmatter,
@@ -13667,8 +13895,11 @@ export {
13667
13895
  pushPostGit,
13668
13896
  readRefinedSnapshot,
13669
13897
  requireRefined,
13898
+ runDailyTopicsSync,
13670
13899
  runListenLinkBackfill,
13671
13900
  runSiteGate,
13901
+ slugFromPostPath,
13672
13902
  slugify2 as slugify,
13903
+ upsertDailyTopicsEntry,
13673
13904
  withEmdashTokenHint
13674
13905
  };
@@ -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';
@@ -206,9 +218,24 @@ function fail(error: string): Result {
206
218
 
207
219
  type DeliveryState = 'not-sent' | 'uncertain';
208
220
 
209
- /** A failed publish is replay-safe only when it was rejected before postsurfing was invoked. */
221
+ /**
222
+ * A failed publish is replay-safe only when it was rejected before postsurfing was invoked.
223
+ *
224
+ * Both keys are emitted on purpose: the voice2 daily stages read `deliveryState`, while the publish
225
+ * matrix receipts only accept the reserved `metadata.itcDelivery` evidence (task 0302, docs/04 §itc).
226
+ * Without the second key a pre-dispatch refusal was recorded as `effect: unknown`, so the row could
227
+ * never be retried even after the operator fixed the cause (2026-11-12 daily publish dogfood).
228
+ */
210
229
  function failWithDeliveryState(error: string, deliveryState: DeliveryState): Result {
211
- return ResultSchema.parse({ ok: false, target: TARGET, error, metadata: { deliveryState } });
230
+ return ResultSchema.parse({
231
+ ok: false,
232
+ target: TARGET,
233
+ error,
234
+ metadata: {
235
+ deliveryState,
236
+ itcDelivery: { schemaVersion: 1, effect: deliveryState === 'not-sent' ? 'none' : 'unknown' },
237
+ },
238
+ });
212
239
  }
213
240
 
214
241
  function failNotSent(error: string): Result {
@@ -458,6 +485,78 @@ export async function runListenLinkBackfill(surfdashRoot: string): Promise<strin
458
485
  return [...new Set(afterPaths.filter((p) => !beforePaths.has(p)))];
459
486
  }
460
487
 
488
+ /** Outcome of {@link runDailyTopicsSync} — `paths` are checkout-relative for the commit pathspec. */
489
+ export type DailyTopicsSyncOutcome = { ok: true; paths: string[] } | { ok: false; error: string };
490
+
491
+ /** Paths the sync's git diff watches: the map file plus everything the retitle may rewrite. */
492
+ const DAILY_TOPICS_GIT_PATHS = ['scripts/seo/daily-topics.json', 'content/posts'] as const;
493
+
494
+ /**
495
+ * Maps a digest post's three refined locale posts into the site's daily-topics map and runs
496
+ * the site's retitle over them (`bun run sd seo retitle --write --stamp-claims`).
497
+ *
498
+ * Skips (ok, no paths, logged) when the post is not a digest or not all of zh/en/ja `index.md`
499
+ * exist — the site gate still validates whatever the posts already carry. A failing entry build
500
+ * or retitle run returns `{ ok: false }` so the caller never commits or pushes. Returns the map
501
+ * file plus every path the retitle changed, for the commit pathspec.
502
+ */
503
+ export async function runDailyTopicsSync(surfdashRoot: string, zhPostPath: string): Promise<DailyTopicsSyncOutcome> {
504
+ const enPath = localeIndexPath(zhPostPath, 'en');
505
+ const jaPath = localeIndexPath(zhPostPath, 'ja');
506
+ if (enPath === undefined || jaPath === undefined) {
507
+ echoError(`daily-topics sync: skipped — ${zhPostPath} is not a zh locale post path`);
508
+ return { ok: true, paths: [] };
509
+ }
510
+ if (!existsSync(zhPostPath)) {
511
+ echoError(`daily-topics sync: skipped — zh post is missing: ${zhPostPath}`);
512
+ return { ok: true, paths: [] };
513
+ }
514
+ const zhPost = readFileSync(zhPostPath, 'utf-8');
515
+ if (!isDigestMarkdown(zhPost)) {
516
+ echoError(`daily-topics sync: skipped — not a digest post (no ${DIGEST_TAG} tag): ${zhPostPath}`);
517
+ return { ok: true, paths: [] };
518
+ }
519
+ if (!existsSync(enPath) || !existsSync(jaPath)) {
520
+ echoError(
521
+ `daily-topics sync: skipped — locale index.md missing (en=${existsSync(enPath)} ja=${existsSync(jaPath)}): ${zhPostPath}`,
522
+ );
523
+ return { ok: true, paths: [] };
524
+ }
525
+ const slug = slugFromPostPath(zhPostPath);
526
+ if (slug === undefined) {
527
+ return { ok: false, error: `daily-topics sync failed: cannot derive slug from ${zhPostPath}` };
528
+ }
529
+ const built = buildDailyTopicsEntry({
530
+ zh: zhPost,
531
+ en: readFileSync(enPath, 'utf-8'),
532
+ ja: readFileSync(jaPath, 'utf-8'),
533
+ });
534
+ if (!built.ok) {
535
+ return { ok: false, error: `daily-topics sync failed: ${built.error}` };
536
+ }
537
+ const mapPath = join(surfdashRoot, 'scripts', 'seo', 'daily-topics.json');
538
+ const before = await spawnCli(['git', 'status', '--porcelain', '--', ...DAILY_TOPICS_GIT_PATHS], surfdashRoot);
539
+ const beforePaths = new Set(parsePorcelainPaths(before.stdout));
540
+ try {
541
+ await upsertDailyTopicsEntry(mapPath, slug, built.entry);
542
+ } catch (error: unknown) {
543
+ return {
544
+ ok: false,
545
+ error: `daily-topics sync failed: ${error instanceof Error ? error.message : String(error)}`,
546
+ };
547
+ }
548
+ const retitle = await spawnCli(['bun', 'run', 'sd', 'seo', 'retitle', '--write', '--stamp-claims'], surfdashRoot);
549
+ if (retitle.exitCode !== 0) {
550
+ return {
551
+ ok: false,
552
+ error: `daily-topics sync failed: bun run sd seo retitle --write --stamp-claims (exit ${retitle.exitCode}): ${cliErrorText(retitle)}`,
553
+ };
554
+ }
555
+ const after = await spawnCli(['git', 'status', '--porcelain', '--', ...DAILY_TOPICS_GIT_PATHS], surfdashRoot);
556
+ const changed = parsePorcelainPaths(after.stdout).filter((p) => !beforePaths.has(p));
557
+ return { ok: true, paths: [...new Set([relative(surfdashRoot, mapPath), ...changed])] };
558
+ }
559
+
461
560
  /** Outcome of {@link runSiteGate}. */
462
561
  export type SiteGateOutcome = { ok: true } | { ok: false; error: string };
463
562
 
@@ -499,11 +598,23 @@ function isUnrelatedDatePostFailure(output: string, ownedPaths: readonly string[
499
598
  return true;
500
599
  }
501
600
 
601
+ /** The checkout's current branch name, or '' when git fails (the caller keeps its existing behavior). */
602
+ async function checkoutBranch(surfdashRoot: string): Promise<string> {
603
+ const branch = await spawnCli(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], surfdashRoot);
604
+ return branch.exitCode === 0 ? branch.stdout.trim() : '';
605
+ }
606
+
502
607
  /**
503
608
  * Runs the surfdash site gates (`bun run sd check digest` then `bun run check:content`)
504
609
  * with cwd = `surfdashRoot` via `spawnCli`.
505
610
  *
506
- * If either command exits non-zero:
611
+ * Fail-closed on main pushes: when the checkout is on `main` and this run will push
612
+ * (`SURFDASH_AUTO_PUSH !== '0'`), a failing gate ALWAYS returns `{ ok: false }` — the
613
+ * `warn` / unrelated-date escape hatch logs that it was ignored (this is a push to main)
614
+ * plus the gate output and failing-post hint, and `off` still runs the gate instead of
615
+ * skipping it.
616
+ *
617
+ * Otherwise:
507
618
  * - With `SURFDASH_DIGEST_CHECK=warn` (or when every failing post belongs to an unrelated date
508
619
  * outside `ownedPaths`): echoes each line of the failure via `echoError` prefixed with
509
620
  * `site gate (warn):` and continues.
@@ -511,8 +622,15 @@ function isUnrelatedDatePostFailure(output: string, ownedPaths: readonly string[
511
622
  * - Default (unset or any other value): fails loud with command, trimmed output, and post hint.
512
623
  */
513
624
  export async function runSiteGate(surfdashRoot: string, ownedPaths: readonly string[] = []): Promise<SiteGateOutcome> {
625
+ const pushingToMain = process.env.SURFDASH_AUTO_PUSH !== '0' && (await checkoutBranch(surfdashRoot)) === 'main';
514
626
  if (process.env.SURFDASH_DIGEST_CHECK === 'off') {
515
- return { ok: true };
627
+ if (pushingToMain) {
628
+ echoError(
629
+ 'site gate: SURFDASH_DIGEST_CHECK=off ignored — this run pushes to surfdash main, so the gate runs fail-closed',
630
+ );
631
+ } else {
632
+ return { ok: true };
633
+ }
516
634
  }
517
635
 
518
636
  for (const cmd of SITE_GATE_COMMANDS) {
@@ -522,7 +640,18 @@ export async function runSiteGate(surfdashRoot: string, ownedPaths: readonly str
522
640
  const postHint = extractFailingPostHint(output);
523
641
  const hint = postHint ? ` [failing post: ${postHint}]` : '';
524
642
  const error = `site gate failed: ${cmd.join(' ')} (exit ${spawned.exitCode})${hint}: ${output}`;
525
- if (process.env.SURFDASH_DIGEST_CHECK === 'warn' || isUnrelatedDatePostFailure(output, ownedPaths)) {
643
+ const escapable =
644
+ process.env.SURFDASH_DIGEST_CHECK === 'warn' || isUnrelatedDatePostFailure(output, ownedPaths);
645
+ if (escapable && pushingToMain) {
646
+ echoError(
647
+ '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)',
648
+ );
649
+ for (const line of error.split('\n')) {
650
+ echoError(`site gate (blocked): ${line}`);
651
+ }
652
+ return { ok: false, error };
653
+ }
654
+ if (escapable) {
526
655
  for (const line of error.split('\n')) {
527
656
  echoError(`site gate (warn): ${line}`);
528
657
  }
@@ -862,8 +991,13 @@ async function patchPost(options: SurfdashPubOptions): Promise<Result> {
862
991
  return fail(`patch error: ${error instanceof Error ? error.message : String(error)}`);
863
992
  }
864
993
  if (outcome.changed === 0) echoError(`patch: no post bytes changed for ${outcome.slug}`);
994
+ // Daily-topics map + retitle run before the CMS sync so the synced rows carry the retitled
995
+ // frontmatter; a failure here must not commit or push a half-synced post.
996
+ const topics = await runDailyTopicsSync(surfdashRoot, postPath.postPath);
997
+ if (!topics.ok) return fail(topics.error);
865
998
  const synced = await syncPost({ postPath: postPath.postPath });
866
999
  const commitPaths = new Set(outcome.written.map((path) => relative(surfdashRoot, path)));
1000
+ for (const p of topics.paths) commitPaths.add(p);
867
1001
  for (const locale of PATCH_LOCALES) {
868
1002
  const indexMd = localeIndexPath(postPath.postPath, locale);
869
1003
  if (!indexMd) continue;
@@ -1282,16 +1416,18 @@ async function publishPreparedFile(
1282
1416
  },
1283
1417
  });
1284
1418
  }
1419
+ const topics = await runDailyTopicsSync(surfdashRoot, filePath);
1420
+ if (!topics.ok) return failUncertain(topics.error);
1285
1421
  const backfilled = await runListenLinkBackfill(surfdashRoot);
1286
1422
  const commitPaths = relPostDirs ?? [relPostDir];
1287
- const gate = await runSiteGate(surfdashRoot, [...commitPaths, ...backfilled]);
1423
+ const gate = await runSiteGate(surfdashRoot, [...commitPaths, ...backfilled, ...topics.paths]);
1288
1424
  if (!gate.ok) return failUncertain(gate.error);
1289
1425
  const commitLocales: SupportedLocale[] = relPostDirs === undefined ? [locale] : ['zh', 'en', 'ja'];
1290
1426
  const pushed = await pushPostGit(
1291
1427
  surfdashRoot,
1292
1428
  commitPaths,
1293
1429
  `content: daily AI news ${dateStamp} (${commitLocales.join(', ')})`,
1294
- backfilled,
1430
+ [...backfilled, ...topics.paths],
1295
1431
  );
1296
1432
  if (!pushed.ok) return failUncertain(pushed.error);
1297
1433
  const live = await awaitArticleLive(articleUrl);