@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
@@ -55,6 +55,7 @@ import { spawnSync } from 'node:child_process';
55
55
  import { createHash } from 'node:crypto';
56
56
  import {
57
57
  copyFileSync,
58
+ cpSync,
58
59
  existsSync,
59
60
  mkdirSync,
60
61
  readdirSync,
@@ -75,6 +76,7 @@ import {
75
76
  coverBrief,
76
77
  coverNormalizeBody,
77
78
  dedupPlanByTitle,
79
+ EDITORIAL_SKILL_DIR,
78
80
  expandHome,
79
81
  fail,
80
82
  failWith,
@@ -91,12 +93,10 @@ import {
91
93
  readJson,
92
94
  readTopicBoundary,
93
95
  requireJson,
94
- requireSidecar,
95
- resolveSidecar,
96
96
  resultPublishStatus,
97
97
  SAFETY_PLATFORM_DECISIONS,
98
98
  SAFETY_REVISE_COUNT,
99
- STYLE_SIDECAR,
99
+ STYLE_CONTRACT,
100
100
  StageFailure,
101
101
  safetyDigest,
102
102
  safetyDraftPaths,
@@ -430,6 +430,21 @@ export function dailyExtract(args: string[]): void {
430
430
  }
431
431
  timed(workDir, 'extract', () => {
432
432
  mkdirSync(join(workDir, '10-collect'), { recursive: true });
433
+ // 0347 F6 (2026-11-10): extract re-reads the store on every rerun, so a next-day retry of a
434
+ // failed episode saw overnight collects invalidate the plan fingerprint and the plan stage
435
+ // fail-closed ("refusing to pair a new plan with stale outputs"). Once the plan has
436
+ // authored its output, the episode is frozen: keep the pool byte-for-byte so a rerun
437
+ // resumes the same material (work dirs are per-run-date, so the 21-plan prefix glob is
438
+ // unambiguous). Removing the pool or the plan files re-extracts deliberately.
439
+ const planAuthored = existsSync(join(workDir, '21-plan'))
440
+ ? readdirSync(join(workDir, '21-plan')).some(
441
+ (entry) => entry.endsWith('_03_plan_content.json') || entry.endsWith('_03_plan_plan.json'),
442
+ )
443
+ : false;
444
+ if (planAuthored && isFile(poolPath)) {
445
+ console.error(`extract: plan already authored — keeping the frozen pool (${poolPath})`);
446
+ return;
447
+ }
433
448
  let chosen: { window: string; docs: unknown[] } | null = null;
434
449
  for (const ms of windows) {
435
450
  const label = formatWindowMs(ms);
@@ -511,14 +526,24 @@ export function dailyArticle(args: string[]): void {
511
526
  // half-ran (or the json was pruned), and returning here starves every downstream stage
512
527
  // that reads content.json — publish-prep refuses to merge a draft it cannot read. Requiring
513
528
  // both artifacts makes the pair self-healing instead of permanently stuck.
514
- if (isFile(articleMd) && isFile(articleContent)) {
529
+ // The prose body is the generator's INPUT: when it is newer than content.json the pair
530
+ // is stale (an operator or a retry edited the headings after the render), and serving it
531
+ // ships last round's body to surfdash. Re-derive instead of returning.
532
+ const proseBody = join(workDir, '22-article', `${runDate}_06_article-write_body.md`);
533
+ const proseStale =
534
+ isFile(proseBody) &&
535
+ isFile(articleContent) &&
536
+ statSync(proseBody).mtimeMs > statSync(articleContent).mtimeMs;
537
+ if (isFile(articleMd) && isFile(articleContent) && !proseStale) {
515
538
  console.log(`article cached: ${articleMd}`);
516
539
  return;
517
540
  }
541
+ if (proseStale) {
542
+ console.error(`article: stale pair — ${proseBody} is newer than ${articleContent}, re-deriving`);
543
+ }
518
544
  // Agent-written prose body (workflow `article-write` state) replaces the mechanical
519
545
  // per-item render when present — the 3-format split: surfdash gets an article,
520
546
  // not a news list (2026-09-16 feedback).
521
- const proseBody = join(workDir, '22-article', `${runDate}_06_article-write_body.md`);
522
547
  kk(
523
548
  [
524
549
  'executor',
@@ -1027,9 +1052,9 @@ export function dailyGenerate(args: string[]): void {
1027
1052
  // Pre-spend script floor gate (2026-10-22). QC's candidate-text estimate does not predict the
1028
1053
  // spoken length — 20261020 planned 3968 chars and rendered 8.4 min, 20261021 planned 4548 and
1029
1054
  // rendered 17.9 — but the authored VoiceScript IS the spoken text, and 14 measured episodes
1030
- // deliver it at 5.24-5.94 chars/s. Reusing `spokenCharRate` (the slowest measured band) makes the
1031
- // estimate over-predict slightly, which is the safe direction here: a thin day is refused before
1032
- // the 1-2 h synthesis, and one that would have cleared the floor is never refused.
1055
+ // deliver it at 5.24-5.94 chars/s. The floor estimate uses `scriptFloorCharRate`, NOT
1056
+ // `spokenCharRate`: the fit rate's slow calibration over-predicts minutes and passes a thin
1057
+ // script into the full synthesis, which the measured gate then refuses (20261111).
1033
1058
  const minMinutes = episodeMinMinutes === '' ? 0 : Number(episodeMinMinutes);
1034
1059
  if (!Number.isFinite(minMinutes) || minMinutes < 0) {
1035
1060
  failWith(1, `generate: invalid episode_min_minutes: ${episodeMinMinutes}`);
@@ -1045,7 +1070,7 @@ export function dailyGenerate(args: string[]): void {
1045
1070
  (sum, segment) => sum + (typeof segment.text === 'string' ? segment.text.length : 0),
1046
1071
  0,
1047
1072
  );
1048
- const charRate = spokenCharRate(vdriver);
1073
+ const charRate = scriptFloorCharRate(vdriver);
1049
1074
  const seconds = 8 + chars / charRate;
1050
1075
  if (seconds < minMinutes * 60) {
1051
1076
  refuseScriptBelowFloor(workDir, runDate, { chars, charRate, seconds, minMinutes });
@@ -1621,10 +1646,15 @@ export function dailyPlan(args: string[]): void {
1621
1646
  if (isFile(target)) {
1622
1647
  const descendants = authoredPlanDescendants(workDir, runDate);
1623
1648
  if (descendants.length > 0) {
1624
- failWith(
1625
- 1,
1626
- `plan cache changed after downstream artifacts were authored; refusing to pair a new plan with stale outputs (${descendants.join(', ')})`,
1649
+ // 0347 F6 (2026-11-10): the pool can drift between the authoring day and a rerun
1650
+ // (overnight collects grow the store; extract-overwrite used to break the
1651
+ // fingerprint). Keeping the existing plan pairs old artifacts with the plan that
1652
+ // actually produced them — the pairing the old refusal guarded. Rebuilding from
1653
+ // the current pool is explicit: delete the 21-plan outputs and the descendants.
1654
+ console.error(
1655
+ `plan: pool changed after authoring — keeping the existing plan and its ${descendants.length} downstream artifact(s) (delete 21-plan/${runDate}_03_plan_*.* and the descendants to rebuild)`,
1627
1656
  );
1657
+ return;
1628
1658
  }
1629
1659
  console.log(`plan cache stale: ${target}`);
1630
1660
  }
@@ -1875,7 +1905,12 @@ function weightedLength(text: string): number {
1875
1905
  */
1876
1906
  export function buildSocialContent(
1877
1907
  copy: string,
1878
- options: { platform: string; coverPath?: string; limit: SocialLimit },
1908
+ options: {
1909
+ platform: string;
1910
+ limit: SocialLimit;
1911
+ coverPath?: string;
1912
+ cardPath?: string;
1913
+ },
1879
1914
  ): Record<string, unknown> {
1880
1915
  const trimmed = copy.trim();
1881
1916
  const measure = (text: string): number => (options.limit.weighted === true ? weightedLength(text) : text.length);
@@ -1893,6 +1928,7 @@ export function buildSocialContent(
1893
1928
  }
1894
1929
  body = kept;
1895
1930
  }
1931
+ const attachedImage = options.cardPath ?? options.coverPath;
1896
1932
  return {
1897
1933
  title: `${options.platform} · 每日AI乱炖`,
1898
1934
  format: 'text',
@@ -1905,7 +1941,7 @@ export function buildSocialContent(
1905
1941
  truncatedFrom: measure(trimmed),
1906
1942
  truncatedUnit: options.limit.weighted === true ? 'weighted' : 'code_units',
1907
1943
  }),
1908
- ...(options.coverPath === undefined ? {} : { coverImage: options.coverPath }),
1944
+ ...(attachedImage === undefined ? {} : { coverImage: attachedImage }),
1909
1945
  },
1910
1946
  };
1911
1947
  }
@@ -2010,11 +2046,22 @@ export function dailyBundleVariants(args: string[]): void {
2010
2046
  );
2011
2047
  }
2012
2048
 
2049
+ const cards = cardsEnabledArg !== 'false' ? readJson(cardsPath) : null;
2050
+ let cardImage: string | undefined;
2051
+ if (cards !== null && Array.isArray((cards.metadata as Record<string, unknown> | undefined)?.images)) {
2052
+ const rawImages = (cards.metadata as Record<string, unknown>).images as Array<{ path?: string }>;
2053
+ if (rawImages.length > 0 && typeof rawImages[0]?.path === 'string' && isFile(rawImages[0].path)) {
2054
+ cardImage = resolve(rawImages[0].path);
2055
+ }
2056
+ }
2057
+
2013
2058
  if (cardsEnabledArg === 'false') skipped.push('cards (cards_enabled=false)');
2014
2059
  else {
2015
- const cards = readJson(cardsPath);
2016
2060
  if (cards === null) skipped.push('cards (no rendered card series)');
2017
- else write('cards@xhs-pub', buildXhsCardsContent(cards, { publishStatus: 'draft' }));
2061
+ else {
2062
+ write('cards', buildXhsCardsContent(cards, { publishStatus: 'draft' }));
2063
+ write('cards@xhs-pub', buildXhsCardsContent(cards, { publishStatus: 'draft' }));
2064
+ }
2018
2065
  }
2019
2066
 
2020
2067
  for (const platform of Object.keys(SOCIAL_LIMITS)) {
@@ -2030,6 +2077,7 @@ export function dailyBundleVariants(args: string[]): void {
2030
2077
  platform,
2031
2078
  limit,
2032
2079
  ...(cover === undefined ? {} : { coverPath: cover }),
2080
+ ...(cardImage === undefined ? {} : { cardPath: cardImage }),
2033
2081
  }),
2034
2082
  );
2035
2083
  }
@@ -3320,10 +3368,20 @@ export function dailySafetyGate(args: string[]): void {
3320
3368
  status = 'exclude';
3321
3369
  reason = 'RISK decisions carry only gap/note/fix dispositions — recorded, publishing at recorded risk';
3322
3370
  } else status = 'pass';
3323
- if (status === 'pass' || status === 'escalate' || status === 'exclude') {
3324
- sted('write', stampFile, () => writeJsonText(stampFile, { digest, status, excludedPlatforms }));
3325
- }
3326
- if (status === 'block' && drafts && !edited) {
3371
+ // 0347 F4 (2026-11-10): an executor outage must not masquerade as a content verdict. When
3372
+ // the final classification is block AND the evidence the gate grades is missing entirely
3373
+ // (request/report/verdict never appeared because a reviewer or judge agent died), record an
3374
+ // infra marker the `judge -> infra-fail` transition reads; `block` stays reserved for real
3375
+ // content verdicts. The caller contract is unchanged — both terminals are failureStates, so
3376
+ // "non-zero = never publish" holds; infra-fail only makes the death retryable-by-machine and
3377
+ // legible to daily-triage.
3378
+ const infraMarker = scopeArtifact(workDir, scopeDir, runDate, 'safety-infra.json');
3379
+ const infraMissing = [
3380
+ ...(request === null ? ['review-request'] : []),
3381
+ ...(report === null ? ['review-report'] : []),
3382
+ ...(verdict === null ? ['judge-verdict'] : []),
3383
+ ];
3384
+ if (status === 'block' && drafts && !edited && infraMissing.length === 0) {
3327
3385
  // A quality block poisons the isFile() draft cache: every same-day retry would
3328
3386
  // re-fail on unchanged bytes (20261002 dogfood — two judge-fail runs replayed until
3329
3387
  // the drafts were moved by hand). Quarantine (mv, never rm) so the next run
@@ -3338,6 +3396,24 @@ export function dailySafetyGate(args: string[]): void {
3338
3396
  renameSync(path, dest);
3339
3397
  }
3340
3398
  }
3399
+ if (status === 'pass' || status === 'escalate' || status === 'exclude') {
3400
+ sted('write', stampFile, () => writeJsonText(stampFile, { digest, status, excludedPlatforms }));
3401
+ }
3402
+ if (status === 'block' && infraMissing.length > 0) {
3403
+ sted('write', infraMarker, () =>
3404
+ writeJsonText(infraMarker, {
3405
+ infra: true,
3406
+ missing: infraMissing,
3407
+ reason,
3408
+ classifiedAt: new Date().toISOString(),
3409
+ }),
3410
+ );
3411
+ console.error(
3412
+ `safety: infra — refusal is due to missing evidence (${infraMissing.join(', ')}), not a content verdict`,
3413
+ );
3414
+ } else if (isFile(infraMarker)) {
3415
+ unlinkSync(infraMarker);
3416
+ }
3341
3417
  sted('write', statusFile, () => writeRaw(statusFile, status));
3342
3418
  console.log(`safety: status=${status} (${reason}); routing is transition-owned`);
3343
3419
  });
@@ -3867,6 +3943,22 @@ function voicescriptToBlockYaml(script: Record<string, unknown>): string {
3867
3943
  return lines.join('\n');
3868
3944
  }
3869
3945
 
3946
+ /**
3947
+ * Floor-gate char rate — deliberately separate from `spokenCharRate` because the two consumers
3948
+ * need opposite safe directions. The fit/ceiling budget wants the slow rate (a too-big fit renders
3949
+ * an episode the ceiling then rejects — why gemini was recalibrated to 4.95 on 2026-10-15). The
3950
+ * pre-spend script floor gate wants the opposite: a slow rate over-predicts minutes and passes a
3951
+ * thin script into the 1-2 h synthesis, which the measured gate refuses after the spend
3952
+ * (20261111 a17: 4,805-char script estimated 16.3 min at 4.95, rendered 14.2 min at a measured
3953
+ * 5.64 chars/s; band 5.33-5.88 across 20261004/07 + the 0237 live dry run). 5.6 — the band center
3954
+ * and the voicebox default — refuses a17-class days before any spend; slow-mix days near the
3955
+ * floor may be refused early, the cheaper error per the ceiling gate's own economics.
3956
+ */
3957
+ function scriptFloorCharRate(vdriver: string): number {
3958
+ if (vdriver === 'gemini') return 5.6;
3959
+ return spokenCharRate(vdriver);
3960
+ }
3961
+
3870
3962
  /** Measured driver rates from dailyGenerate. Unknown drivers reuse the voicebox rate. */
3871
3963
  function spokenCharRate(vdriver: string): number {
3872
3964
  // Recalibrated 2026-10-15: episode measured 7,395 spoken chars / 1,490.9 s across 12 sections
@@ -3999,7 +4091,8 @@ export function dailyScript(args: string[]): void {
3999
4091
  // cwd = the plugin package dir, so a relative workDir would silently miss the
4000
4092
  // plan; a plan file absent at build time reports missing-plan (template fallback).
4001
4093
  DAILYNEWS_SCRIPT_PLAN: resolve(join(workDir, '24-script', `${runDate}_08_script-write_plan.json`)),
4002
- DAILYNEWS_STYLE_FILE: resolve(resolveSidecar('', STYLE_SIDECAR)),
4094
+ DAILYNEWS_STYLE_FILE: resolve(STYLE_CONTRACT),
4095
+ DAILYNEWS_CURATE_EXCLUDED: resolve(join(workDir, '21-plan', `${runDate}_03_curate_excluded.json`)),
4003
4096
  },
4004
4097
  });
4005
4098
  const body = readJson(contentOut)?.body;
@@ -4021,25 +4114,504 @@ export function dailyScript(args: string[]): void {
4021
4114
 
4022
4115
  /** Task 0189 R10 artifacts of the content-safety verdict gate (24-script, step 09). */
4023
4116
  /**
4024
- * F613 R1: snapshot the shipped style contract into the run's work dir. Spur workflows have no
4025
- * workflow-dir var, so the script-write prompt reads this copy — and the snapshot freezes the
4026
- * exact contract the run's plan was written against. Idempotent (an existing snapshot is kept);
4027
- * a missing sidecar is a broken install, so `requireSidecar` fails loud.
4117
+ * F613 R1 / ADR-045: snapshot the shipped kk:news-editorial skill into the run's work dir. Spur
4118
+ * workflows have no workflow-dir var and kk skills are not installed for every executor, so the
4119
+ * writer prompts read this copy by path — and the snapshot freezes the exact policy the run's plan
4120
+ * was written against. `20-editorial/news-editorial/` holds SKILL.md + references; the
4121
+ * `_08_script-write_style.md` copy of the style contract stays the run's audit record.
4122
+ * Idempotent per artifact (an existing snapshot is kept); a missing skill is a broken install.
4028
4123
  */
4029
4124
  export function dailyScriptStyle(args: string[]): void {
4030
4125
  const [workDir = '', runDate = ''] = args;
4126
+ if (!isFile(STYLE_CONTRACT)) {
4127
+ failWith(
4128
+ 1,
4129
+ `news-editorial skill not found — no ${STYLE_CONTRACT}; install or refresh the kk package (bun link in a checkout)`,
4130
+ );
4131
+ }
4132
+ const skillSnapshot = join(workDir, '20-editorial', 'news-editorial');
4133
+ if (isFile(join(skillSnapshot, 'SKILL.md'))) {
4134
+ console.log(`editorial skill cached: ${skillSnapshot}`);
4135
+ } else {
4136
+ sted('cp', skillSnapshot, () => cpSync(EDITORIAL_SKILL_DIR, skillSnapshot, { recursive: true }));
4137
+ console.log(`editorial skill snapshot: ${skillSnapshot}`);
4138
+ }
4031
4139
  const snapshot = join(workDir, '24-script', `${runDate}_08_script-write_style.md`);
4032
4140
  if (isFile(snapshot)) {
4033
4141
  console.log(`script style cached: ${snapshot}`);
4034
4142
  return;
4035
4143
  }
4036
- const sidecar = requireSidecar('', STYLE_SIDECAR, 'daily-voice-style');
4037
4144
  const scriptDir = join(workDir, '24-script');
4038
4145
  sted('mkdir', scriptDir, () => mkdirSync(scriptDir, { recursive: true }));
4039
- sted('cp', snapshot, () => copyFileSync(sidecar, snapshot));
4146
+ sted('cp', snapshot, () => copyFileSync(STYLE_CONTRACT, snapshot));
4040
4147
  console.log(`script style snapshot: ${snapshot}`);
4041
4148
  }
4042
4149
 
4150
+ /**
4151
+ * 0345 R4: dry-run the dailynews-gen validator on the authored script plan so a rejected plan gets
4152
+ * one targeted `script-write-fix` pass instead of silently shipping the template fallback. Writes
4153
+ * `24-script/<date>_08_script-write_errors.json` ([{itemId, rule}]) when the plan is absent or
4154
+ * rejected, and removes it when the plan is accepted. The trial build goes to a scratch path so the
4155
+ * `script` stage's isFile cache is never primed by a check.
4156
+ */
4157
+ export function dailyScriptCheck(args: string[]): void {
4158
+ const [workDir = '', runDate = '', pluginsPath = ''] = args;
4159
+ const planOut = join(workDir, '24-script', `${runDate}_08_script-write_plan.json`);
4160
+ const errorsOut = join(workDir, '24-script', `${runDate}_08_script-write_errors.json`);
4161
+ const writeErrors = (errors: unknown[]) => {
4162
+ sted('write', errorsOut, () => writeJsonText(errorsOut, errors));
4163
+ console.log(`script plan rejected (${errors.length} error(s)): ${errorsOut}`);
4164
+ };
4165
+ if (!isFile(planOut)) {
4166
+ writeErrors([{ itemId: 'episode', rule: 'missing-plan' }]);
4167
+ return;
4168
+ }
4169
+ const trialOut = join(workDir, '24-script', `.${runDate}_08_script-check_content.json`);
4170
+ const planIn = join(workDir, '21-plan', `${runDate}_03_plan_plan.json`);
4171
+ try {
4172
+ kk(['executor', 'run', 'dailynews-gen', '--in', planIn, '--out', trialOut, ...pluginsArgs(pluginsPath)], {
4173
+ env: {
4174
+ DAILYNEWS_LANGUAGE: 'zh',
4175
+ DAILYNEWS_DATE: runDate,
4176
+ DAILYNEWS_SCRIPT_PLAN: resolve(planOut),
4177
+ DAILYNEWS_STYLE_FILE: resolve(STYLE_CONTRACT),
4178
+ DAILYNEWS_CURATE_EXCLUDED: resolve(join(workDir, '21-plan', `${runDate}_03_curate_excluded.json`)),
4179
+ },
4180
+ });
4181
+ const metadata = readJson(trialOut)?.metadata;
4182
+ const source = metadata?.scriptSource;
4183
+ if (source !== 'plan' && source !== 'template') {
4184
+ failWith(1, `script-check: ${trialOut} carries no scriptSource stamp`);
4185
+ }
4186
+ if (source === 'plan') {
4187
+ if (isFile(errorsOut)) unlinkSync(errorsOut);
4188
+ console.log('script plan accepted by the validator');
4189
+ return;
4190
+ }
4191
+ writeErrors(Array.isArray(metadata.scriptPlanErrors) ? metadata.scriptPlanErrors : []);
4192
+ } finally {
4193
+ if (isFile(trialOut)) unlinkSync(trialOut);
4194
+ }
4195
+ }
4196
+
4197
+ /**
4198
+ * 0345 R8: validate the `curate` agent output (`21-plan/<date>_03_plan_plan.json` +
4199
+ * `21-plan/<date>_03_curate_excluded.json`) against the QC candidates
4200
+ * (`21-plan/<date>_04_quality-control-content_candidates.json`). Unwraps a `Content` envelope and
4201
+ * dedups near-duplicate titles in place before `write` reads the plan. Writes
4202
+ * `21-plan/<date>_03_curate_errors.json` (`[{itemId, rule}]`) on failure and removes it on success.
4203
+ * With `--final`, falls back to the untranslated candidates and `[]` exclusions on failure.
4204
+ */
4205
+ export function dailyCurateCheck(args: string[]): void {
4206
+ const [workDir = '', runDate = '', flag = ''] = args;
4207
+ if (!workDir) fail('missing work_dir');
4208
+ if (!runDate) fail('missing run_date');
4209
+ const isFinal = flag === '--final';
4210
+ const candidatesFile = join(workDir, '21-plan', `${runDate}_04_quality-control-content_candidates.json`);
4211
+ const planFile = join(workDir, '21-plan', `${runDate}_03_plan_plan.json`);
4212
+ const excludedFile = join(workDir, '21-plan', `${runDate}_03_curate_excluded.json`);
4213
+ const errFile = join(workDir, '21-plan', `${runDate}_03_curate_errors.json`);
4214
+
4215
+ const candRaw = readJson(candidatesFile);
4216
+ const candidateDocs: Record<string, unknown>[] = Array.isArray(candRaw)
4217
+ ? (candRaw as Record<string, unknown>[])
4218
+ : Array.isArray(metadataOf(candRaw).docs)
4219
+ ? (metadataOf(candRaw).docs as Record<string, unknown>[])
4220
+ : [];
4221
+ const candidateIds = candidateDocs.map((doc) => (typeof doc?.id === 'string' ? doc.id.trim() : '')).filter(Boolean);
4222
+ const candidateIdSet = new Set(candidateIds);
4223
+
4224
+ const handleErrors = (errors: { itemId: string; rule: string }[]): void => {
4225
+ if (isFinal) {
4226
+ const reason = errors.map((e) => `${e.itemId}:${e.rule}`).join(', ');
4227
+ console.error(
4228
+ `curate-check: final check failed (${reason}) — falling back to ${candidateDocs.length} untranslated candidate(s)`,
4229
+ );
4230
+ sted('write', planFile, () => writeJsonText(planFile, candidateDocs));
4231
+ sted('write', excludedFile, () => writeJsonText(excludedFile, []));
4232
+ if (isFile(errFile)) unlinkSync(errFile);
4233
+ return;
4234
+ }
4235
+ sted('write', errFile, () => writeJsonText(errFile, errors));
4236
+ console.log(`curate-check: rejected (${errors.length} error(s)): ${errFile}`);
4237
+ };
4238
+
4239
+ if (!isFile(planFile)) {
4240
+ handleErrors([{ itemId: 'episode', rule: 'missing-plan' }]);
4241
+ return;
4242
+ }
4243
+
4244
+ let planParsed: unknown;
4245
+ try {
4246
+ planParsed = JSON.parse(readFileSync(planFile, 'utf-8'));
4247
+ } catch {
4248
+ handleErrors([{ itemId: 'episode', rule: 'invalid-json' }]);
4249
+ return;
4250
+ }
4251
+
4252
+ let planDocs: Record<string, unknown>[];
4253
+ if (Array.isArray(planParsed)) {
4254
+ planDocs = planParsed as Record<string, unknown>[];
4255
+ } else if (
4256
+ planParsed !== null &&
4257
+ typeof planParsed === 'object' &&
4258
+ Array.isArray(metadataOf(planParsed as Record<string, unknown>).docs)
4259
+ ) {
4260
+ planDocs = metadataOf(planParsed as Record<string, unknown>).docs as Record<string, unknown>[];
4261
+ sted('write', planFile, () => writeJsonText(planFile, planDocs));
4262
+ console.log(`curate-check: unwrapped Content envelope (${planDocs.length} doc(s)) in ${planFile}`);
4263
+ } else {
4264
+ handleErrors([{ itemId: 'episode', rule: 'invalid-json' }]);
4265
+ return;
4266
+ }
4267
+
4268
+ for (const entry of planDocs) {
4269
+ if (entry === null || typeof entry !== 'object' || typeof entry.id !== 'string' || entry.id.trim() === '') {
4270
+ handleErrors([{ itemId: 'episode', rule: 'invalid-json' }]);
4271
+ return;
4272
+ }
4273
+ }
4274
+
4275
+ const excludedItems: { id: string; reason: string }[] = [];
4276
+ if (isFile(excludedFile)) {
4277
+ let exParsed: unknown;
4278
+ try {
4279
+ exParsed = JSON.parse(readFileSync(excludedFile, 'utf-8'));
4280
+ } catch {
4281
+ handleErrors([{ itemId: 'episode', rule: 'invalid-json' }]);
4282
+ return;
4283
+ }
4284
+ if (!Array.isArray(exParsed)) {
4285
+ handleErrors([{ itemId: 'episode', rule: 'invalid-json' }]);
4286
+ return;
4287
+ }
4288
+ for (const entry of exParsed) {
4289
+ if (
4290
+ entry === null ||
4291
+ typeof entry !== 'object' ||
4292
+ typeof (entry as { id?: unknown }).id !== 'string' ||
4293
+ (entry as { id: string }).id.trim() === '' ||
4294
+ typeof (entry as { reason?: unknown }).reason !== 'string' ||
4295
+ (entry as { reason: string }).reason.trim() === ''
4296
+ ) {
4297
+ handleErrors([{ itemId: 'episode', rule: 'invalid-json' }]);
4298
+ return;
4299
+ }
4300
+ excludedItems.push({
4301
+ id: (entry as { id: string }).id.trim(),
4302
+ reason: (entry as { reason: string }).reason.trim(),
4303
+ });
4304
+ }
4305
+ }
4306
+
4307
+ const errors: { itemId: string; rule: string }[] = [];
4308
+ if (planDocs.length === 0) {
4309
+ errors.push({ itemId: 'episode', rule: 'empty-plan' });
4310
+ }
4311
+
4312
+ const keptIds = new Set<string>();
4313
+ for (const doc of planDocs) {
4314
+ const id = (doc.id as string).trim();
4315
+ keptIds.add(id);
4316
+ if (candidateIdSet.size > 0 && !candidateIdSet.has(id)) {
4317
+ errors.push({ itemId: id, rule: 'unknown-id' });
4318
+ }
4319
+ }
4320
+
4321
+ const excludedIds = new Set<string>();
4322
+ for (const ex of excludedItems) {
4323
+ excludedIds.add(ex.id);
4324
+ if (candidateIdSet.size > 0 && !candidateIdSet.has(ex.id)) {
4325
+ errors.push({ itemId: ex.id, rule: 'unknown-id' });
4326
+ }
4327
+ if (keptIds.has(ex.id)) {
4328
+ errors.push({ itemId: ex.id, rule: 'conflict-id' });
4329
+ }
4330
+ }
4331
+
4332
+ for (const cid of candidateIds) {
4333
+ if (!keptIds.has(cid) && !excludedIds.has(cid)) {
4334
+ errors.push({ itemId: cid, rule: 'missing-item' });
4335
+ }
4336
+ }
4337
+
4338
+ if (errors.length > 0) {
4339
+ handleErrors(errors);
4340
+ return;
4341
+ }
4342
+
4343
+ const { kept, dropped } = dedupPlanByTitle(planDocs);
4344
+ if (dropped.length > 0) {
4345
+ sted('write', planFile, () => writeJsonText(planFile, kept));
4346
+ console.error(`curate-check: dropped ${dropped.length} near-duplicate plan item(s): ${dropped.join(', ')}`);
4347
+ for (const droppedId of dropped) {
4348
+ if (!excludedIds.has(droppedId)) {
4349
+ excludedIds.add(droppedId);
4350
+ excludedItems.push({ id: droppedId, reason: '标题近似重复自动去重' });
4351
+ }
4352
+ }
4353
+ sted('write', excludedFile, () => writeJsonText(excludedFile, excludedItems));
4354
+ } else if (!isFile(excludedFile)) {
4355
+ sted('write', excludedFile, () => writeJsonText(excludedFile, excludedItems));
4356
+ }
4357
+
4358
+ if (isFile(errFile)) unlinkSync(errFile);
4359
+ console.log(`curate-check: accepted (${kept.length} kept, ${excludedItems.length} excluded)`);
4360
+ }
4361
+
4362
+ function sourceLabelForDoc(doc: Record<string, unknown>, sourceUri: string): string {
4363
+ const meta = metadataOf(doc);
4364
+ if (typeof meta.source === 'string' && meta.source.trim() !== '') {
4365
+ return meta.source.trim();
4366
+ }
4367
+ try {
4368
+ return new URL(sourceUri).hostname.replace(/^www\./, '') || '原文';
4369
+ } catch {
4370
+ return '原文';
4371
+ }
4372
+ }
4373
+
4374
+ /** Fixed column opening line of the rendered article body: house copy, not editorial judgement (0345). */
4375
+ const EDITORIAL_ARTICLE_OPENING = '这里是由Robin为你带来的咸话咸说之每日AI乱炖。';
4376
+
4377
+ /**
4378
+ * 0345 R10: deterministically render the five sibling editorial artifacts from the master script
4379
+ * plan (`24-script/<date>_08_script-write_plan.json`) and the curated plan
4380
+ * (`21-plan/<date>_03_plan_plan.json`):
4381
+ * 1. `22-article/<date>_06_article-write_body.md`
4382
+ * 2. `23-cover/<date>_07_cover-brief.json`
4383
+ * 3. `25-xhs/<date>_18_xhs_plan.json` (only when `cards_enabled === 'true'`)
4384
+ * 4. `26-social/{x,threads}.md` (`social.short`)
4385
+ * 5. `26-social/{weibo,linkedin}.md` (`social.long`)
4386
+ * Missing master field -> skip that one artifact with a logged reason, write the others.
4387
+ */
4388
+ export function dailyEditorialRender(args: string[]): void {
4389
+ const [workDir = '', runDate = '', cardsEnabled = 'false', cardsRaw = '6'] = args;
4390
+ if (!workDir) fail('missing work_dir');
4391
+ if (!runDate) fail('missing run_date');
4392
+ const cardsCount = Math.max(2, Number.parseInt(cardsRaw, 10) || 6);
4393
+ const planFile = join(workDir, '21-plan', `${runDate}_03_plan_plan.json`);
4394
+ const masterFile = join(workDir, '24-script', `${runDate}_08_script-write_plan.json`);
4395
+
4396
+ const master = readJson(masterFile);
4397
+ if (master === null) {
4398
+ console.log(`editorial-render: no master script plan at ${masterFile} — skipping all renders`);
4399
+ return;
4400
+ }
4401
+
4402
+ const planRaw = readJson(planFile);
4403
+ const planDocs: Record<string, unknown>[] = Array.isArray(planRaw)
4404
+ ? (planRaw as Record<string, unknown>[])
4405
+ : Array.isArray(metadataOf(planRaw).docs)
4406
+ ? (metadataOf(planRaw).docs as Record<string, unknown>[])
4407
+ : [];
4408
+ const docById = new Map<string, Record<string, unknown>>();
4409
+ for (const doc of planDocs) {
4410
+ if (typeof doc?.id === 'string' && doc.id.trim() !== '') {
4411
+ docById.set(doc.id.trim(), doc);
4412
+ }
4413
+ }
4414
+
4415
+ const rawItems = Array.isArray(master.items) ? (master.items as Record<string, unknown>[]) : [];
4416
+ const itemById = new Map<string, Record<string, unknown>>();
4417
+ for (const item of rawItems) {
4418
+ if (item !== null && typeof item === 'object' && typeof item.id === 'string' && item.id.trim() !== '') {
4419
+ itemById.set(item.id.trim(), item);
4420
+ }
4421
+ }
4422
+ const orderedIds =
4423
+ planDocs.length > 0
4424
+ ? planDocs
4425
+ .map((d) => (typeof d.id === 'string' ? d.id.trim() : ''))
4426
+ .filter((id) => id !== '' && itemById.has(id))
4427
+ : [...itemById.keys()];
4428
+
4429
+ // 1. Article body: 22-article/<date>_06_article-write_body.md
4430
+ const outro = typeof master.outro === 'string' ? master.outro.trim() : '';
4431
+ const articleSections: string[] = [];
4432
+ for (const id of orderedIds) {
4433
+ const doc = docById.get(id);
4434
+ const item = itemById.get(id);
4435
+ const title = typeof doc?.title === 'string' ? doc.title.trim() : '';
4436
+ const body = typeof doc?.body === 'string' ? doc.body.trim() : '';
4437
+ const lead = typeof item?.lead === 'string' ? item.lead.trim() : '';
4438
+ const insight = typeof item?.insight === 'string' ? item.insight.trim() : '';
4439
+ if (!title || !body || !lead || !insight) continue;
4440
+ const sourceUri = typeof doc?.sourceUri === 'string' ? doc.sourceUri.trim() : '';
4441
+ const sourceLine = sourceUri ? `[来源:${sourceLabelForDoc(doc ?? {}, sourceUri)}](${sourceUri})` : '';
4442
+ const parts = [`## ${title}`, lead, body, insight, ...(sourceLine ? [sourceLine] : [])];
4443
+ articleSections.push(parts.join('\n\n'));
4444
+ }
4445
+ if (articleSections.length > 0 && outro !== '') {
4446
+ const articleDir = join(workDir, '22-article');
4447
+ sted('mkdir', articleDir, () => mkdirSync(articleDir, { recursive: true }));
4448
+ const articleOut = join(articleDir, `${runDate}_06_article-write_body.md`);
4449
+ const articleText = `${[EDITORIAL_ARTICLE_OPENING, ...articleSections, outro].join('\n\n')}\n`;
4450
+ sted('write', articleOut, () => writeRaw(articleOut, articleText));
4451
+ console.log(`editorial-render: wrote article body (${articleSections.length} item(s)): ${articleOut}`);
4452
+ } else {
4453
+ console.log('editorial-render: skipping article body (missing items/doc fields or outro)');
4454
+ }
4455
+
4456
+ // 2. Cover brief: 23-cover/<date>_07_cover-brief.json
4457
+ // 0347 R5: cover may be a legacy string (subject only) or `{ scene, headline }` — the
4458
+ // headline falls back to the lead story's title either way.
4459
+ const rawCover = master.cover;
4460
+ let coverSubject = '';
4461
+ let coverHeadline = '';
4462
+ if (typeof rawCover === 'string') {
4463
+ coverSubject = rawCover.trim();
4464
+ } else if (rawCover !== null && typeof rawCover === 'object') {
4465
+ const coverObj = rawCover as Record<string, unknown>;
4466
+ coverSubject = typeof coverObj.scene === 'string' ? coverObj.scene.trim() : '';
4467
+ coverHeadline = typeof coverObj.headline === 'string' ? coverObj.headline.trim() : '';
4468
+ }
4469
+ const leadId = orderedIds[0];
4470
+ const leadDoc = leadId !== undefined ? docById.get(leadId) : undefined;
4471
+ const leadStoryTitle = typeof leadDoc?.title === 'string' ? leadDoc.title.trim() : '';
4472
+ if (coverSubject !== '') {
4473
+ if (coverHeadline === '' && leadStoryTitle !== '') {
4474
+ coverHeadline = leadStoryTitle;
4475
+ }
4476
+ const coverDir = join(workDir, '23-cover');
4477
+ sted('mkdir', coverDir, () => mkdirSync(coverDir, { recursive: true }));
4478
+ const coverOut = join(coverDir, `${runDate}_07_cover-brief.json`);
4479
+ sted('write', coverOut, () =>
4480
+ writeJsonText(coverOut, {
4481
+ subject: coverSubject,
4482
+ headline: coverHeadline,
4483
+ leadStoryTitle,
4484
+ }),
4485
+ );
4486
+ console.log(`editorial-render: wrote cover brief: ${coverOut}`);
4487
+ } else {
4488
+ console.log('editorial-render: skipping cover brief (missing cover in script plan)');
4489
+ }
4490
+
4491
+ // 3. XHS card plan: 25-xhs/<date>_18_xhs_plan.json (only when cards_enabled === 'true')
4492
+ if (cardsEnabled === 'true') {
4493
+ const cardsMeta =
4494
+ master.cards !== null && typeof master.cards === 'object'
4495
+ ? (master.cards as Record<string, unknown>)
4496
+ : null;
4497
+ const cardTitle = typeof cardsMeta?.title === 'string' ? cardsMeta.title.trim() : '';
4498
+ const cardBody = typeof cardsMeta?.body === 'string' ? cardsMeta.body.trim() : '';
4499
+ const contentItems = orderedIds
4500
+ .map((id) => ({ id, item: itemById.get(id), doc: docById.get(id) }))
4501
+ .filter(({ item }) => {
4502
+ const c = item?.card as Record<string, unknown> | undefined;
4503
+ return (
4504
+ c !== null &&
4505
+ typeof c === 'object' &&
4506
+ typeof c.copy === 'string' &&
4507
+ c.copy.trim() !== '' &&
4508
+ Array.isArray(c.points) &&
4509
+ c.points.length >= 1 &&
4510
+ typeof c.subject === 'string' &&
4511
+ c.subject.trim() !== ''
4512
+ );
4513
+ });
4514
+ const maxContent = Math.max(1, cardsCount - 2);
4515
+ const chosenContent = contentItems.slice(0, maxContent);
4516
+ if (cardTitle !== '' && cardBody !== '' && chosenContent.length > 0) {
4517
+ const firstSubject =
4518
+ coverSubject ||
4519
+ ((chosenContent[0]?.item?.card as { subject?: string } | undefined)?.subject ?? '').trim() ||
4520
+ 'Minimalist geometric light sculpture on a dark studio table';
4521
+ const introText =
4522
+ typeof master.intro === 'string' && master.intro.trim() !== '' ? master.intro.trim() : cardTitle;
4523
+ const coverPoints = chosenContent
4524
+ .slice(0, 4)
4525
+ .map(({ item }) => ((item?.card as { copy?: string } | undefined)?.copy || '').trim())
4526
+ .filter(Boolean);
4527
+ const renderedCards: Record<string, unknown>[] = [
4528
+ {
4529
+ role: 'cover',
4530
+ copy: cardTitle.slice(0, 12),
4531
+ points: coverPoints.length >= 2 ? coverPoints : [cardTitle, introText.slice(0, 36)],
4532
+ layout: 'hero',
4533
+ subject: firstSubject,
4534
+ sourcePoint: introText,
4535
+ },
4536
+ ...chosenContent.map(({ id, item, doc }) => {
4537
+ const card = item?.card as { copy: string; points: string[]; subject: string };
4538
+ const lead = typeof item?.lead === 'string' && item.lead.trim() !== '' ? item.lead.trim() : '';
4539
+ const docTitle = typeof doc?.title === 'string' && doc.title.trim() !== '' ? doc.title.trim() : id;
4540
+ return {
4541
+ role: 'content',
4542
+ copy: card.copy.trim(),
4543
+ points: card.points
4544
+ .map((p) => String(p).trim())
4545
+ .filter(Boolean)
4546
+ .slice(0, 4),
4547
+ layout: 'split',
4548
+ subject: card.subject.trim(),
4549
+ sourcePoint: lead || docTitle,
4550
+ itemId: id,
4551
+ };
4552
+ }),
4553
+ ];
4554
+ // Pad content cards if chosenContent.length < maxContent so total length equals cardsCount
4555
+ while (renderedCards.length < cardsCount - 1) {
4556
+ const seed = renderedCards[renderedCards.length - 1] as Record<string, unknown>;
4557
+ renderedCards.push({ ...seed });
4558
+ }
4559
+ const closingPoints = [outro || introText, cardTitle].filter(Boolean);
4560
+ renderedCards.push({
4561
+ role: 'closing',
4562
+ copy: '本期小结',
4563
+ points: closingPoints.length >= 2 ? closingPoints : [outro || cardTitle, '感谢关注每日AI乱炖'],
4564
+ layout: 'summary',
4565
+ subject: firstSubject,
4566
+ sourcePoint: outro || introText,
4567
+ });
4568
+ const xhsDir = join(workDir, '25-xhs');
4569
+ sted('mkdir', xhsDir, () => mkdirSync(xhsDir, { recursive: true }));
4570
+ const xhsOut = join(xhsDir, `${runDate}_18_xhs_plan.json`);
4571
+ sted('write', xhsOut, () =>
4572
+ writeJsonText(xhsOut, {
4573
+ title: cardTitle,
4574
+ body: cardBody,
4575
+ cards: renderedCards,
4576
+ }),
4577
+ );
4578
+ console.log(`editorial-render: wrote xhs card plan (${renderedCards.length} card(s)): ${xhsOut}`);
4579
+ } else {
4580
+ console.log('editorial-render: skipping xhs card plan (missing cards.title/body or items[].card)');
4581
+ }
4582
+ }
4583
+
4584
+ // 4 & 5. Social posts: unified short notice for 26-social/{x,threads,weibo}.md; linkedin.md (and weibo fallback) long
4585
+ const social =
4586
+ master.social !== null && typeof master.social === 'object' ? (master.social as Record<string, unknown>) : null;
4587
+ const socialShort = typeof social?.short === 'string' ? social.short.trim() : '';
4588
+ const socialLong = typeof social?.long === 'string' ? social.long.trim() : '';
4589
+ const socialDir = join(workDir, '26-social');
4590
+ if (socialShort !== '') {
4591
+ sted('mkdir', socialDir, () => mkdirSync(socialDir, { recursive: true }));
4592
+ for (const name of ['x.md', 'threads.md', 'weibo.md']) {
4593
+ const out = join(socialDir, name);
4594
+ sted('write', out, () => writeRaw(out, `${socialShort}\n`));
4595
+ }
4596
+ console.log('editorial-render: wrote 26-social/{x,threads,weibo}.md');
4597
+ } else if (socialLong !== '') {
4598
+ sted('mkdir', socialDir, () => mkdirSync(socialDir, { recursive: true }));
4599
+ const out = join(socialDir, 'weibo.md');
4600
+ sted('write', out, () => writeRaw(out, `${socialLong}\n`));
4601
+ console.log('editorial-render: wrote 26-social/weibo.md from social.long');
4602
+ } else {
4603
+ console.log('editorial-render: skipping social short posts (missing social.short in script plan)');
4604
+ }
4605
+ if (socialLong !== '') {
4606
+ sted('mkdir', socialDir, () => mkdirSync(socialDir, { recursive: true }));
4607
+ const out = join(socialDir, 'linkedin.md');
4608
+ sted('write', out, () => writeRaw(out, `${socialLong}\n`));
4609
+ console.log('editorial-render: wrote 26-social/linkedin.md');
4610
+ } else {
4611
+ console.log('editorial-render: skipping social long posts (missing social.long in script plan)');
4612
+ }
4613
+ }
4614
+
4043
4615
  export function dailyShowNotes(args: string[]): void {
4044
4616
  const [workDir = '', runDate = '', pluginsPath = '', title = ''] = args;
4045
4617
  const article = join(workDir, '22-article', `${runDate}_06_article_content.json`);