@gobing-ai/knowledge-kit 0.1.23 → 0.1.25

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 (106) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/index.js +418 -114
  3. package/package.json +5 -5
  4. package/plugins/generations/content-gen/dist/index.js +9 -9
  5. package/plugins/generations/core-facts-gen/dist/index.js +12 -12
  6. package/plugins/generations/daily-article-gen/dist/index.js +12 -12
  7. package/plugins/generations/dailynews-gen/dist/index.js +11 -11
  8. package/plugins/generations/dailynews-gen/src/script-plan.ts +2 -2
  9. package/plugins/generations/episode-plan-gen/dist/index.js +59 -18
  10. package/plugins/generations/episode-plan-gen/src/index.ts +71 -7
  11. package/plugins/generations/gemini-tts/dist/index.js +9 -9
  12. package/plugins/generations/image-gen/dist/index.js +9 -9
  13. package/plugins/generations/music-gen/dist/index.js +33 -29
  14. package/plugins/generations/music-gen/src/audio/measure.ts +25 -20
  15. package/plugins/generations/news-report-gen/dist/index.js +12 -12
  16. package/plugins/generations/vibe-voice-tts/dist/index.js +9 -9
  17. package/plugins/generations/voice-gen/dist/index.js +9 -9
  18. package/plugins/generations/voxcpm-tts/dist/index.js +9 -9
  19. package/plugins/ingestions/aihot-ingest/dist/index.js +12 -12
  20. package/plugins/ingestions/horizon-ingest/dist/index.js +12 -12
  21. package/plugins/ingestions/karakeep-local/dist/index.js +13 -13
  22. package/plugins/ingestions/last30days-ingest/dist/index.js +12 -12
  23. package/plugins/ingestions/web-search/dist/index.js +10 -10
  24. package/plugins/kk/decisions/extract/ai-news.yaml +8 -1
  25. package/plugins/kk/plugin.json +1 -1
  26. package/plugins/kk/publish-presets/daily-ai-voice.json +20 -20
  27. package/plugins/kk/publish-presets/itc-main.json +39 -23
  28. package/plugins/kk/scripts/cover-compositor.ts +104 -26
  29. package/plugins/kk/scripts/daily-stages.ts +704 -53
  30. package/plugins/kk/scripts/kk-workflow-stages.ts +149 -6
  31. package/plugins/kk/scripts/series-names.ts +16 -3
  32. package/plugins/kk/skills/content-safety/references/platforms/apple-podcasts.md +12 -5
  33. package/plugins/kk/skills/content-safety/references/platforms/wechatmp.md +8 -0
  34. package/plugins/kk/skills/content-safety/references/platforms/xiaoyuzhou.md +5 -0
  35. package/plugins/kk/skills/daily-news-cover/SKILL.md +96 -0
  36. package/plugins/kk/skills/daily-news-illustrations/SKILL.md +123 -0
  37. package/plugins/kk/skills/news-editorial/SKILL.md +5 -3
  38. package/plugins/kk/skills/news-editorial/references/daily-visual-composition.md +150 -0
  39. package/plugins/kk/skills/news-editorial/references/style-contract.zh.md +3 -3
  40. package/plugins/kk/workflows/kk-article-generate.yaml +13 -1
  41. package/plugins/kk/workflows/kk-daily-ai-voice.yaml +6 -3
  42. package/plugins/kk/workflows/kk-daily-ai-voice2.yaml +6 -4
  43. package/plugins/kk/workflows/kk-news-generate.yaml +74 -1
  44. package/plugins/publishings/bilibili-pub/dist/index.js +25 -24
  45. package/plugins/publishings/bilibili-pub/dist/profile-check.js +25 -24
  46. package/plugins/publishings/cnblogs-pub/dist/index.js +25 -24
  47. package/plugins/publishings/cnblogs-pub/dist/profile-check.js +25 -24
  48. package/plugins/publishings/csdn-pub/dist/index.js +25 -24
  49. package/plugins/publishings/csdn-pub/dist/profile-check.js +25 -24
  50. package/plugins/publishings/emdash-pub/dist/index.js +9 -9
  51. package/plugins/publishings/infoq-pub/dist/index.js +25 -24
  52. package/plugins/publishings/infoq-pub/dist/profile-check.js +25 -24
  53. package/plugins/publishings/jike-pub/dist/index.js +25 -24
  54. package/plugins/publishings/jike-pub/dist/profile-check.js +25 -24
  55. package/plugins/publishings/juejin-pub/dist/index.js +25 -24
  56. package/plugins/publishings/juejin-pub/dist/profile-check.js +25 -24
  57. package/plugins/publishings/linkedin-pub/dist/index.js +85 -26
  58. package/plugins/publishings/linkedin-pub/dist/profile-check.js +25 -24
  59. package/plugins/publishings/linkedin-pub/src/index.ts +93 -6
  60. package/plugins/publishings/medium-pub/dist/index.js +9206 -287
  61. package/plugins/publishings/medium-pub/dist/profile-check.js +21174 -0
  62. package/plugins/publishings/medium-pub/package.json +3 -1
  63. package/plugins/publishings/medium-pub/plugin.json +6 -1
  64. package/plugins/publishings/medium-pub/src/browser-rail.ts +280 -0
  65. package/plugins/publishings/medium-pub/src/index.ts +17 -1
  66. package/plugins/publishings/medium-pub/src/profile-check.ts +27 -0
  67. package/plugins/publishings/podcast-pub/dist/index.js +240 -37
  68. package/plugins/publishings/podcast-pub/src/index.ts +154 -3
  69. package/plugins/publishings/podcast-pub/src/seo.ts +25 -8
  70. package/plugins/publishings/podcast-pub/src/show-notes-brief.ts +93 -23
  71. package/plugins/publishings/podcast-pub/src/show-notes.ts +26 -6
  72. package/plugins/publishings/qiita-pub/dist/index.js +9 -9
  73. package/plugins/publishings/shipinhao-pub/dist/index.js +29 -26
  74. package/plugins/publishings/shipinhao-pub/dist/profile-check.js +28 -26
  75. package/plugins/publishings/shipinhao-pub/src/flow.ts +5 -0
  76. package/plugins/publishings/shipinhao-pub/src/selectors.ts +13 -5
  77. package/plugins/publishings/sspai-pub/dist/index.js +25 -24
  78. package/plugins/publishings/sspai-pub/dist/profile-check.js +25 -24
  79. package/plugins/publishings/substack-pub/dist/index.js +25 -24
  80. package/plugins/publishings/substack-pub/dist/profile-check.js +25 -24
  81. package/plugins/publishings/surfdash-pub/dist/index.js +200 -92
  82. package/plugins/publishings/surfdash-pub/src/digest-check.ts +30 -1
  83. package/plugins/publishings/surfdash-pub/src/index.ts +94 -75
  84. package/plugins/publishings/surfdash-pub/src/media-upload.ts +83 -0
  85. package/plugins/publishings/surfdash-pub/src/patch.ts +28 -23
  86. package/plugins/publishings/surfdash-pub/src/topic-claims.ts +12 -4
  87. package/plugins/publishings/threads-pub/dist/index.js +39 -24
  88. package/plugins/publishings/threads-pub/dist/profile-check.js +30 -24
  89. package/plugins/publishings/threads-pub/src/post-rail.ts +20 -0
  90. package/plugins/publishings/wechatmp-pub/dist/index.js +438 -102
  91. package/plugins/publishings/wechatmp-pub/dist/profile-check.js +30 -25
  92. package/plugins/publishings/wechatmp-pub/src/enrich.ts +56 -10
  93. package/plugins/publishings/wechatmp-pub/src/flow.ts +589 -83
  94. package/plugins/publishings/wechatmp-pub/src/index.ts +4 -1
  95. package/plugins/publishings/wechatmp-pub/src/modes.ts +30 -12
  96. package/plugins/publishings/wechatmp-pub/src/page.ts +8 -0
  97. package/plugins/publishings/weibo-pub/dist/index.js +25 -24
  98. package/plugins/publishings/weibo-pub/dist/profile-check.js +25 -24
  99. package/plugins/publishings/x-pub/dist/index.js +54 -47
  100. package/plugins/publishings/x-pub/dist/profile-check.js +25 -24
  101. package/plugins/publishings/x-pub/src/post-rail.ts +40 -47
  102. package/plugins/publishings/xhs-pub/dist/index.js +25 -24
  103. package/plugins/publishings/xhs-pub/dist/profile-check.js +25 -24
  104. package/plugins/publishings/xiaoyuzhou-pub/dist/index.js +25 -24
  105. package/plugins/publishings/xiaoyuzhou-pub/dist/profile-check.js +25 -24
  106. package/plugins/publishings/zenn-pub/dist/index.js +9 -9
@@ -155,6 +155,16 @@ export function dailyQcContent(args: string[]): void {
155
155
  const exclusions = join(workDir, '21-plan', `${runDate}_04_quality-control-content_exclusions.json`);
156
156
  const planContent = join(workDir, '21-plan', `${runDate}_03_plan_content.json`);
157
157
  const cachePath = `${candidates}.cache.json`;
158
+ const floorMinutes = Number(minMinutes);
159
+ const qcMinChars =
160
+ minMinutes !== '' && Number.isFinite(floorMinutes) && floorMinutes > 0
161
+ ? String(
162
+ Math.max(
163
+ 0,
164
+ Math.ceil(((floorMinutes * 60 - 8) * spokenCharRate(vdriver)) / readKeptRatio(workDir).ratio),
165
+ ),
166
+ )
167
+ : '';
158
168
  const fingerprint = stageCacheFingerprint(planContent, {
159
169
  qcCategories,
160
170
  minQuality,
@@ -164,6 +174,7 @@ export function dailyQcContent(args: string[]): void {
164
174
  minEpisodeItems,
165
175
  minMinutes,
166
176
  vdriver,
177
+ qcMinChars,
167
178
  });
168
179
  let recomputed = false;
169
180
  timed(workDir, 'quality-control-content', () => {
@@ -211,6 +222,7 @@ export function dailyQcContent(args: string[]): void {
211
222
  QC_MIN_URGENCY: minUrgency,
212
223
  QC_MIN_IMPACT: minImpact,
213
224
  QC_MIN_EPISODE_ITEMS: minEpisodeItems,
225
+ ...(qcMinChars ? { QC_MIN_CHARS: qcMinChars } : {}),
214
226
  },
215
227
  },
216
228
  );
@@ -412,6 +424,15 @@ function readSpokenRatio(workDir: string): SpokenRatio {
412
424
  } catch {
413
425
  return { ratio: SPEAK_CHAR_EXPANSION_FLOOR, source: 'default 0.28 (no sibling runs)' };
414
426
  }
427
+ // Best-effort calibration only: a test workdir or an operator scratch dir may sit directly in a
428
+ // shared temp parent with hundreds of thousands of entries. Scanning each one took 20–40s per QC
429
+ // stage (measured 2026-11-23 on a 556k-entry tempdir), so skip the sibling calibration instead of
430
+ // blocking the run. Normal works roots have far fewer runs and keep the newest-ratio behavior.
431
+ if (entries.length > 5_000)
432
+ return {
433
+ ratio: SPEAK_CHAR_EXPANSION_FLOOR,
434
+ source: `default 0.28 (sibling scan skipped: ${entries.length} entries)`,
435
+ };
415
436
  for (const entry of entries) {
416
437
  const dir = join(base, entry, '21-plan');
417
438
  let files: string[] = [];
@@ -452,33 +473,52 @@ function readKeptRatio(workDir: string): SpokenRatio {
452
473
  let newest: { at: number; ratio: number; from: string } | null = null;
453
474
  let entries: string[] = [];
454
475
  try {
476
+ // A shared temp parent can hold hundreds of thousands of directories. Read names once and
477
+ // open only run-shaped candidates past the small-workspace threshold; opening every one took
478
+ // 20–40s per QC stage (556k entries measured 2026-11-23).
455
479
  entries = readdirSync(base);
456
480
  } catch {
457
481
  return { ratio: SPEAK_CHAR_EXPANSION_FLOOR, source: 'default 0.28 (no sibling runs)' };
458
482
  }
459
- for (const entry of entries) {
460
- const dir = join(base, entry, '21-plan');
461
- let files: string[] = [];
462
- try {
463
- files = readdirSync(dir).filter((file) => file.endsWith(SPOKEN_RATIO_SUFFIX));
464
- } catch {
465
- continue;
483
+ const ratioFiles: string[] = [];
484
+ if (entries.length > 5_000) {
485
+ // Native globbing skips the non-run directories instead of opening each of them in JS. The
486
+ // `kk-*` form measured ~2s on that same parent; a bare `*` can hit broken symlinks.
487
+ for (const pattern of [`kk-*/21-plan/*${SPOKEN_RATIO_SUFFIX}`, `20??????/21-plan/*${SPOKEN_RATIO_SUFFIX}`]) {
488
+ try {
489
+ ratioFiles.push(...new Bun.Glob(pattern).scanSync({ cwd: base, onlyFiles: true, absolute: true }));
490
+ } catch {
491
+ // Best-effort calibration: a shared temp parent holds dangling symlinks and dirs that
492
+ // vanish mid-scan (ENOENT from the glob walk), which must never fail the QC stage.
493
+ }
466
494
  }
467
- for (const file of files) {
468
- const path = join(dir, file);
495
+ } else {
496
+ for (const entry of entries) {
497
+ const dir = join(base, entry, '21-plan');
469
498
  try {
470
- const parsed = readJson(path) as Record<string, unknown> | null;
471
- // A pre-2026-11-16 record carries no kept ratio at all: skip it rather than divide by
472
- // its pool figure, which is what produced the double discount.
473
- const ratio = Number(parsed?.keptRatio);
474
- if (!Number.isFinite(ratio) || ratio <= 0) continue;
475
- const at = statSync(path).mtimeMs;
476
- if (newest === null || at > newest.at) newest = { at, ratio, from: path };
499
+ ratioFiles.push(
500
+ ...readdirSync(dir)
501
+ .filter((file) => file.endsWith(SPOKEN_RATIO_SUFFIX))
502
+ .map((file) => join(dir, file)),
503
+ );
477
504
  } catch {
478
- // A malformed record is not evidence; the next run overwrites it.
505
+ // Not every sibling is a run directory.
479
506
  }
480
507
  }
481
508
  }
509
+ for (const path of ratioFiles) {
510
+ try {
511
+ const parsed = readJson(path) as Record<string, unknown> | null;
512
+ // A pre-2026-11-16 record carries no kept ratio at all: skip it rather than divide by
513
+ // its pool figure, which is what produced the double discount.
514
+ const ratio = Number(parsed?.keptRatio);
515
+ if (!Number.isFinite(ratio) || ratio <= 0) continue;
516
+ const at = statSync(path).mtimeMs;
517
+ if (newest === null || at > newest.at) newest = { at, ratio, from: path };
518
+ } catch {
519
+ // A malformed record is not evidence; the next run overwrites it.
520
+ }
521
+ }
482
522
  if (newest === null) return { ratio: SPEAK_CHAR_EXPANSION_FLOOR, source: 'default 0.28 (no recorded kept ratio)' };
483
523
  return { ratio: clampRatio(newest.ratio), source: `${newest.from} (${newest.ratio.toFixed(2)}x)` };
484
524
  }
@@ -535,10 +575,15 @@ function rawChars(docs: unknown[]): number {
535
575
  }
536
576
 
537
577
  /**
538
- * The calibrated pre-spend estimate over a kept pool (title+body characters × the 1.4 expansion,
578
+ * The calibrated estimate over a kept pool (title+body characters × the recorded spoken/kept ratio,
539
579
  * over the driver's measured char rate, plus the 8 s intro sting) — shared by the pre-spend floor
540
580
  * gate (applyFloorGate) and the post-spend duration refusal (dailyEpisodeDuration, 0266), so both
541
581
  * artifacts report the same arithmetic. `seconds` is unrounded: the floor gate compares seconds.
582
+ *
583
+ * Both callers must pass `readKeptRatio(...).ratio`. The 1.4 default is the pre-2026-11-16
584
+ * raw-script expansion and is ~4.5x too high for the scripted writer: leaving it on the duration
585
+ * refusal made the 2026-11-24 artifact claim a "pre-spend estimate 58.2 min" beside a measured
586
+ * 12.6 min, which is the number an operator reads when deciding whether to recover the day.
542
587
  */
543
588
  function estimateSpokenMinutes(
544
589
  docs: unknown[],
@@ -1135,7 +1180,7 @@ export function dailyEpisodeDuration(args: string[]): void {
1135
1180
  console.error(`episode-duration: duration refusal already recorded (${refusal}) — nothing to do`);
1136
1181
  return;
1137
1182
  }
1138
- const estimated = estimateSpokenMinutes(docs, vdriver);
1183
+ const estimated = estimateSpokenMinutes(docs, vdriver, readKeptRatio(workDir).ratio);
1139
1184
  const measuredMinutes = Math.round(minutes * 10) / 10;
1140
1185
  sted('write', refusal, () =>
1141
1186
  writeJqText(refusal, {
@@ -2116,9 +2161,11 @@ export function dailyPlan(args: string[]): void {
2116
2161
  const deferDocs = deferPlanDocs === 'true';
2117
2162
  const target = deferDocs ? planContent : planDocs;
2118
2163
  const targetCache = `${target}.cache.json`;
2164
+ const perSourceCap = String(Math.max(5, Math.ceil((Number(planMaxItems) || 20) / 4)));
2119
2165
  const fingerprint = stageCacheFingerprint(blended, {
2120
2166
  runDate,
2121
2167
  planMaxItems,
2168
+ perSourceCap,
2122
2169
  deferPlanDocs,
2123
2170
  });
2124
2171
  timed(workDir, 'plan', () => {
@@ -2144,7 +2191,11 @@ export function dailyPlan(args: string[]): void {
2144
2191
  kk(
2145
2192
  ['executor', 'run', 'episode-plan-gen', '--in', blended, '--out', planContent, ...pluginsArgs(pluginsPath)],
2146
2193
  {
2147
- env: { EPISODE_PLAN_MAX_ITEMS: planMaxItems, EPISODE_PLAN_DATE: runDate },
2194
+ env: {
2195
+ EPISODE_PLAN_MAX_ITEMS: planMaxItems,
2196
+ EPISODE_PLAN_PER_SOURCE_CAP: perSourceCap,
2197
+ EPISODE_PLAN_DATE: runDate,
2198
+ },
2148
2199
  },
2149
2200
  );
2150
2201
  const docs = metadataOf(readJson(planContent)).docs;
@@ -2196,6 +2247,162 @@ const WECHAT_BRAND = {
2196
2247
  coverSource: 'library',
2197
2248
  } as const;
2198
2249
 
2250
+ /** A concise key-point bullet injected into the top-of-article `## 今日要点` summary for 公众号. */
2251
+ export interface WechatKeyPoint {
2252
+ label: string;
2253
+ text: string;
2254
+ }
2255
+
2256
+ function stripLeadingH1Heading(body: string): string {
2257
+ return body.replace(/^\s*# +[^\n]+\n+/, '');
2258
+ }
2259
+
2260
+ function wechatKeyPointLabel(title: string): string {
2261
+ const clean = title.replace(/^#+\s+/, '').trim();
2262
+ const firstClause = clean.split(/[::,,。!?!?\-—|]/)[0]?.trim() ?? clean;
2263
+ const chars = Array.from(firstClause);
2264
+ if (chars.length > 0 && chars.length <= 28) return firstClause;
2265
+ return Array.from(clean).slice(0, 28).join('');
2266
+ }
2267
+
2268
+ function extractWechatKeyPoints(
2269
+ planItems: ReadonlyArray<{ title: string; brief?: string }>,
2270
+ articleBody: string,
2271
+ ): WechatKeyPoint[] {
2272
+ const out: WechatKeyPoint[] = [];
2273
+ for (const item of planItems.slice(0, 5)) {
2274
+ const text = (item.brief ?? item.title).replace(/\s+/g, ' ').trim();
2275
+ const label = wechatKeyPointLabel(item.title);
2276
+ if (label !== '' && text !== '') out.push({ label, text });
2277
+ }
2278
+ if (out.length > 0) return out;
2279
+ const sections = stripLeadingH1Heading(articleBody).split(/\n(?=##\s+)/);
2280
+ for (const section of sections) {
2281
+ const match = section.match(/^##\s+(.+)\n+([\s\S]+)$/);
2282
+ if (!match?.[1] || !match[2]) continue;
2283
+ const firstPara = match[2]
2284
+ .split(/\n{2,}/)
2285
+ .map((p) => p.replace(/\s+/g, ' ').trim())
2286
+ .find((p) => p !== '' && !p.startsWith('#') && !p.startsWith('-'));
2287
+ if (!firstPara) continue;
2288
+ const firstSentence = (splitSentences(firstPara, { cjkOnly: true })[0] ?? firstPara).trim();
2289
+ const label = wechatKeyPointLabel(match[1]);
2290
+ if (label !== '' && firstSentence !== '') out.push({ label, text: firstSentence });
2291
+ if (out.length >= 5) break;
2292
+ }
2293
+ return out;
2294
+ }
2295
+
2296
+ function cleanWechatDigest(body: string, keyPoints?: readonly WechatKeyPoint[]): string {
2297
+ const stripMd = (s: string): string =>
2298
+ s
2299
+ .replace(/^#{1,6}\s+/gm, '')
2300
+ .replace(/\*\*([^*]+)\*\*/g, '$1')
2301
+ .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
2302
+ .replace(/\s+/g, ' ')
2303
+ .trim();
2304
+ const paragraphs = stripLeadingH1Heading(body)
2305
+ .split(/\n{2,}/)
2306
+ .map((p) => stripMd(p))
2307
+ .filter((p) => p !== '' && !p.startsWith('今日要点') && !p.startsWith('- '));
2308
+ const candidate =
2309
+ paragraphs[0] ??
2310
+ (keyPoints ?? [])
2311
+ .slice(0, 2)
2312
+ .map((kp) => `${kp.label}:${kp.text}`)
2313
+ .join(' ');
2314
+ if (candidate === '') return '';
2315
+ return Array.from(candidate).slice(0, 120).join('');
2316
+ }
2317
+
2318
+ /** One validated inline figure, as the WeChat variant materializes it (0426 R2). */
2319
+ export interface InlineFigureMaterial {
2320
+ id: string;
2321
+ path: string;
2322
+ sha256: string;
2323
+ altText: string;
2324
+ caption: string;
2325
+ anchor: string;
2326
+ }
2327
+
2328
+ /**
2329
+ * 0426 R2 — the figures a run may materialize into `article@wechatmp-pub`, or `[]` when the run never
2330
+ * opted in. Opt-in IS the plan the gated node writes: a work dir without
2331
+ * `22-article/illustrations/plan.json` produces byte-identical variants to before this task.
2332
+ *
2333
+ * Every figure is proved against its own receipt before a marker exists: the receipt must name the
2334
+ * same anchor and concept, its `bodySha256` must still match the reviewed article, and the image's
2335
+ * bytes must still hash to `imageSha256`. A missing receipt, an edited article or a swapped binary
2336
+ * refuses here rather than materializing a marker nothing verified.
2337
+ */
2338
+ export function inlineFigureMaterials(workDir: string, runDate: string): InlineFigureMaterial[] {
2339
+ const dir = join(workDir, '22-article', 'illustrations');
2340
+ const plan = readJson(join(dir, 'plan.json'));
2341
+ if (plan === null) return [];
2342
+ const article = readJson(join(workDir, '22-article', `${runDate}_06_article_content.json`));
2343
+ const body = typeof article?.body === 'string' ? article.body : '';
2344
+ const bodySha256 = createHash('sha256').update(body).digest('hex');
2345
+ const entries = Array.isArray(plan.figures) ? (plan.figures as Record<string, unknown>[]) : [];
2346
+ const materials: InlineFigureMaterial[] = [];
2347
+ for (const [position, entry] of entries.entries()) {
2348
+ const id = `figure-${position + 1}`;
2349
+ const receipt = readJson(join(dir, `${id}.receipt.json`));
2350
+ if (receipt === null) {
2351
+ failWith(
2352
+ 1,
2353
+ `bundle-variants: inline figure ${id} has no render receipt — render the plan (kk stage news-inline-illustrations) before materializing variants`,
2354
+ );
2355
+ }
2356
+ if (receipt.bodySha256 !== bodySha256) {
2357
+ failWith(
2358
+ 1,
2359
+ `bundle-variants: inline figure ${id} was rendered against a different article body — re-render the plan before materializing`,
2360
+ );
2361
+ }
2362
+ if (receipt.anchor !== entry.anchor || receipt.concept !== entry.concept) {
2363
+ failWith(1, `bundle-variants: inline figure ${id} receipt names a different anchor/concept than the plan`);
2364
+ }
2365
+ const artifact = firstArtifact(readJson(join(dir, `${id}.json`)));
2366
+ const path = typeof artifact?.path === 'string' ? artifact.path : '';
2367
+ if (path === '' || !isFile(path)) {
2368
+ failWith(1, `bundle-variants: inline figure ${id} image is missing at ${path || '(no artifact)'}`);
2369
+ }
2370
+ if (receipt.imageSha256 !== createHash('sha256').update(readFileSync(path)).digest('hex')) {
2371
+ failWith(1, `bundle-variants: inline figure ${id} image bytes changed after rendering — re-render it`);
2372
+ }
2373
+ materials.push({
2374
+ id,
2375
+ path,
2376
+ sha256: String(receipt.imageSha256),
2377
+ altText: String(entry.altText),
2378
+ caption: String(entry.caption),
2379
+ anchor: String(entry.anchor),
2380
+ });
2381
+ }
2382
+ return materials;
2383
+ }
2384
+
2385
+ /**
2386
+ * 0426 R2 — place each figure right after its own paragraph: the marker image + a caption
2387
+ * paragraph. Refuses an anchor that is no longer unique, which is what keeps a re-cut article from
2388
+ * receiving a figure that belonged to a paragraph it no longer has.
2389
+ */
2390
+ export function withInlineFigureMarkers(body: string, figures: readonly InlineFigureMaterial[]): string {
2391
+ let out = body;
2392
+ for (const figure of figures) {
2393
+ const occurrences = out.split(figure.anchor).length - 1;
2394
+ if (occurrences !== 1) {
2395
+ failWith(
2396
+ 1,
2397
+ `wechat article: inline figure ${figure.id} anchor is not unique in the body (found ${occurrences}) — refusing to place a figure on a changed article`,
2398
+ );
2399
+ }
2400
+ const marker = `![${figure.altText}](kk-inline:${figure.id})`;
2401
+ out = out.replace(figure.anchor, () => `${figure.anchor}\n\n${marker}\n\n${figure.caption}`);
2402
+ }
2403
+ return out;
2404
+ }
2405
+
2199
2406
  /**
2200
2407
  * The 公众号 article payload (task 0327 R1): the article Content plus MP draft enrichment.
2201
2408
  *
@@ -2211,33 +2418,47 @@ export function buildWechatArticleContent(
2211
2418
  coverPath?: string;
2212
2419
  audioPath?: string;
2213
2420
  audioTitle?: string;
2421
+ keyPoints?: readonly WechatKeyPoint[];
2214
2422
  /**
2215
2423
  * The 咸话咸说 closer is an article-only sign-post (operator request 2026-09-29: "appended
2216
2424
  * to the wechat input body only, never the master article"). An audio-first 公众号 播客 post
2217
2425
  * carries the episode body, so it passes `false`.
2218
2426
  */
2219
2427
  appendOutro?: boolean;
2428
+ /**
2429
+ * 0426 R2: figures already validated against their render receipts. Only the WeChat ARTICLE
2430
+ * variant receives them — the 播客 episode body has no article paragraphs to anchor to.
2431
+ */
2432
+ inlineFigures?: readonly InlineFigureMaterial[];
2220
2433
  },
2221
2434
  ): Record<string, unknown> {
2435
+ // 0426 R2: the 播客 episode body has no article paragraphs to anchor to, so only the article
2436
+ // path (the one that appends the closer) ever materializes figures.
2437
+ const figures = options.appendOutro === false ? [] : (options.inlineFigures ?? []);
2222
2438
  const wechatmp: Record<string, unknown> = {
2223
2439
  original: true,
2224
- // 赞赏 is NOT requested: measured 2026-11-20 on a fresh 文章 draft, this account's row renders
2225
- // `不开启 … 无法开启赞赏,因为还没有赞赏账户授权给本公众号` with a 0×0 box — the platform has not
2226
- // authorized a 赞赏 account for 咸话咸说, so no selector, probe or retry can enable it, and asking
2227
- // for it only converted a healthy draft into `ok:false` until `WECHATMP_ALLOW_PARTIAL_ENRICH=1`
2228
- // was set by hand (11-16, 11-18, 11-19). Evidence:
2229
- // `.spur/run/dogfood/2026-11-20-wechatmp-reward/survey-dom.json` (5806: reward row text + box).
2230
- // If the operator opens 赞赏 later, flip this line back together with the probe in
2231
- // `plugins/publishings/wechatmp-pub/src/enrich.ts` (`REWARD_STATE`).
2232
- // 2026-11-20 operator request: 赞赏 ON. `WECHATMP_ALLOW_PARTIAL_ENRICH=1` is set, so a
2233
- // still-unauthorized account warns once and keeps the healthy draft instead of failing it.
2234
- reward: true,
2440
+ // 2026-11-22 live check: 咸话咸说 is not yet authorized in 赞赏账户小程序 -> 可收款公众号,
2441
+ // so reward stays false until the operator authorizes it there.
2442
+ reward: false,
2235
2443
  author: WECHAT_BRAND.author,
2236
2444
  collection: options.collection,
2237
2445
  // 创作来源 is the platform's AI-declaration entry (WX-03); the label declares AI generation.
2238
2446
  claimSource: WECHAT_BRAND.claimSource,
2239
2447
  // 封面 comes from 图片库: the episode cover is uploaded there as the audio material's cover.
2240
2448
  coverSource: WECHAT_BRAND.coverSource,
2449
+ // 0426 R2: the figures this body's markers resolve to, pinned so the adapter can verify the
2450
+ // exact bytes it uploads and never a file that changed after the review.
2451
+ ...(figures.length > 0
2452
+ ? {
2453
+ inlineFigures: figures.map((figure) => ({
2454
+ id: figure.id,
2455
+ path: figure.path,
2456
+ sha256: figure.sha256,
2457
+ altText: figure.altText,
2458
+ caption: figure.caption,
2459
+ })),
2460
+ }
2461
+ : {}),
2241
2462
  ...(options.links.articleUrl !== '' ? { originalUrl: options.links.articleUrl } : {}),
2242
2463
  ...(options.coverPath === undefined ? {} : { coverPath: options.coverPath }),
2243
2464
  ...(options.audioPath === undefined
@@ -2248,12 +2469,40 @@ export function buildWechatArticleContent(
2248
2469
  audioCoverPath: options.coverPath ?? '',
2249
2470
  }),
2250
2471
  };
2251
- const body = typeof article.body === 'string' ? article.body : '';
2472
+ const rawBody = typeof article.body === 'string' ? article.body : '';
2473
+ const existingMeta = metadataOf(article);
2474
+ if (options.appendOutro === false) {
2475
+ return {
2476
+ ...article,
2477
+ body: rawBody,
2478
+ metadata: {
2479
+ ...existingMeta,
2480
+ ...(options.audioPath === undefined ? {} : { audio: options.audioPath }),
2481
+ publishStatus: options.publishStatus,
2482
+ wechatmp,
2483
+ },
2484
+ };
2485
+ }
2486
+ let formattedBody = stripLeadingH1Heading(rawBody).trimStart();
2487
+ const keyPoints = (options.keyPoints ?? []).filter((kp) => kp.label.trim() !== '' && kp.text.trim() !== '');
2488
+ if (keyPoints.length > 0 && !/今日要点/.test(formattedBody.slice(0, 200))) {
2489
+ const bullets = keyPoints.map((kp) => `- ${kp.label.trim()}`).join('\n');
2490
+ const introMatch = formattedBody.match(/^([^\n]*咸话咸说[^\n]*)\n+/);
2491
+ if (introMatch?.[1]) {
2492
+ const rest = formattedBody.slice(introMatch[0].length).trimStart();
2493
+ formattedBody = `${introMatch[1].trimEnd()}今日要点如下:\n${bullets}\n\n下面请听详细内容。\n\n${rest}`;
2494
+ } else {
2495
+ formattedBody = `今日要点如下:\n${bullets}\n\n下面请听详细内容。\n\n${formattedBody}`;
2496
+ }
2497
+ }
2498
+ const existingDigest = typeof existingMeta.digest === 'string' ? existingMeta.digest.trim() : '';
2499
+ const derivedDigest = existingDigest !== '' ? existingDigest : cleanWechatDigest(rawBody, keyPoints);
2252
2500
  return {
2253
2501
  ...article,
2254
- body: options.appendOutro === false ? body : `${body}${WECHAT_OUTRO}`,
2502
+ body: `${withInlineFigureMarkers(formattedBody, figures)}${WECHAT_OUTRO}`,
2255
2503
  metadata: {
2256
- ...metadataOf(article),
2504
+ ...existingMeta,
2505
+ ...(derivedDigest !== '' ? { digest: derivedDigest } : {}),
2257
2506
  // wechatmp-pub's 播客 operation resolves the episode mp3 through the generic media key
2258
2507
  // `metadata.audio` (`modes.ts` resolveMediaPath), while the 文章 audio-embed rail keeps
2259
2508
  // reading `wechatmp.audioPath` — carry both spellings so one variant serves both rows.
@@ -2410,19 +2659,23 @@ function weightedCharWeight(char: string): number {
2410
2659
  }
2411
2660
 
2412
2661
  /** Weighted length of `text` (code-point based, so an emoji counts once before its weight). */
2413
- function weightedLength(text: string): number {
2662
+ export function weightedLength(text: string): number {
2414
2663
  let total = 0;
2415
2664
  for (const char of text) total += weightedCharWeight(char);
2416
2665
  return total;
2417
2666
  }
2418
2667
 
2668
+ /** Platforms where attaching a native image suppresses the URL's clickable Open Graph preview card. */
2669
+ const OG_CARD_PLATFORMS = new Set(['x', 'threads', 'linkedin', 'weibo']);
2670
+
2419
2671
  /**
2420
- * One channel's short copy as a Content (task 0327 R3): the body is the authored post text and the
2421
- * episode cover rides along as `metadata.coverImage`.
2672
+ * One channel's short promo copy as a Content (task 0327 R3; task 0410 episode promo framing):
2673
+ * prepends the frozen episode title and appends the episode listen URL (`{{podcast_url}}`) when
2674
+ * supplied, reserving header/footer budget before truncating copy (X counts URLs at t.co weight 23).
2422
2675
  *
2423
- * The cap is a backstop, not the author: the prompt owns the limit, so an over-length draft is
2424
- * truncated rather than rejected, and `truncatedFrom` records what was cut. Truncation respects the
2425
- * channel's own unit — see {@link SocialLimit}.
2676
+ * Platforms in `OG_CARD_PLATFORMS` (`x`, `threads`, `linkedin`, `weibo`) omit `coverImage` when linking a
2677
+ * podcast URL so their native Open Graph card renders cleanly instead of being suppressed by an
2678
+ * attached image; image-first rails (`jike`) keep `coverImage`.
2426
2679
  */
2427
2680
  export function buildSocialContent(
2428
2681
  copy: string,
@@ -2431,35 +2684,58 @@ export function buildSocialContent(
2431
2684
  limit: SocialLimit;
2432
2685
  coverPath?: string;
2433
2686
  cardPath?: string;
2687
+ episodeTitle?: string;
2688
+ listenUrl?: string;
2434
2689
  },
2435
2690
  ): Record<string, unknown> {
2436
2691
  const trimmed = copy.trim();
2437
- const measure = (text: string): number => (options.limit.weighted === true ? weightedLength(text) : text.length);
2438
- let body = trimmed;
2439
- if (measure(trimmed) > options.limit.max) {
2440
- // Walk code points, adding while the budget holds: a slice by code units could split a
2441
- // surrogate pair or bust the weighted budget on CJK text.
2692
+ const episodeTitle = options.episodeTitle?.trim() ?? '';
2693
+ const listenUrl = options.listenUrl?.trim() ?? '';
2694
+ const header = episodeTitle !== '' && !trimmed.startsWith(episodeTitle) ? `${episodeTitle}\n\n` : '';
2695
+ const footer =
2696
+ listenUrl !== '' && !trimmed.includes(listenUrl)
2697
+ ? options.platform === 'x'
2698
+ ? `\n\n🎧 ${listenUrl}`
2699
+ : `\n\n🎧 完整节目:${listenUrl}`
2700
+ : '';
2701
+
2702
+ const measure = (text: string): number => {
2703
+ if (options.limit.weighted === true) {
2704
+ // X counts URLs via t.co (23 units); reserve 23 for placeholders and full URLs alike.
2705
+ const normalized = text.replace(/(?:https?:\/\/\S+|\{\{(?:podcast|article)_url\}\})/g, 'x'.repeat(23));
2706
+ return weightedLength(normalized);
2707
+ }
2708
+ return text.replace(/\{\{(?:podcast|article)_url\}\}/g, 'x'.repeat(60)).length;
2709
+ };
2710
+
2711
+ const fullMeasure = measure(`${header}${trimmed}${footer}`);
2712
+ let keptCopy = trimmed;
2713
+ if (fullMeasure > options.limit.max) {
2714
+ const copyBudget = Math.max(0, options.limit.max - measure(header) - measure(footer));
2442
2715
  let kept = '';
2443
2716
  let used = 0;
2444
2717
  for (const char of trimmed) {
2445
2718
  const weight = options.limit.weighted === true ? weightedCharWeight(char) : 1;
2446
- if (used + weight > options.limit.max) break;
2719
+ if (used + weight > copyBudget) break;
2447
2720
  kept += char;
2448
2721
  used += weight;
2449
2722
  }
2450
- body = kept;
2723
+ keptCopy = kept;
2451
2724
  }
2452
- const attachedImage = options.cardPath ?? options.coverPath;
2725
+
2726
+ const body = `${header}${keptCopy}${footer}`;
2727
+ const attachCover = !(listenUrl !== '' && OG_CARD_PLATFORMS.has(options.platform));
2728
+ const attachedImage = attachCover ? (options.cardPath ?? options.coverPath) : undefined;
2453
2729
  return {
2454
- title: `${options.platform} · 每日AI乱炖`,
2730
+ title: episodeTitle !== '' ? episodeTitle : `${options.platform} · 每日AI乱炖`,
2455
2731
  format: 'text',
2456
2732
  body,
2457
2733
  metadata: {
2458
2734
  platform: options.platform,
2459
- ...(body === trimmed
2735
+ ...(keptCopy === trimmed
2460
2736
  ? {}
2461
2737
  : {
2462
- truncatedFrom: measure(trimmed),
2738
+ truncatedFrom: fullMeasure,
2463
2739
  truncatedUnit: options.limit.weighted === true ? 'weighted' : 'code_units',
2464
2740
  }),
2465
2741
  ...(attachedImage === undefined ? {} : { coverImage: attachedImage }),
@@ -2500,6 +2776,35 @@ function variantFileName(key: string): string {
2500
2776
  * variant file is wiped before writing, so `30-variants/` after this stage contains only what
2501
2777
  * THIS pass produced.
2502
2778
  */
2779
+ function cardsForPodcast(
2780
+ workDir: string,
2781
+ cardsEnabled: boolean,
2782
+ ): Array<{ index: string; copy: string; status?: string; imagePath?: string }> {
2783
+ if (!cardsEnabled) return [];
2784
+ const parsed = readJson(join(workDir, '25-xhs', 'cards.json'));
2785
+ const rawCards = (parsed as { cards?: unknown } | null)?.cards;
2786
+ if (!Array.isArray(rawCards)) return [];
2787
+ const out: Array<{ index: string; copy: string; status?: string; imagePath?: string }> = [];
2788
+ for (const entry of rawCards) {
2789
+ if (entry === null || typeof entry !== 'object') continue;
2790
+ const card = entry as Record<string, unknown>;
2791
+ const index = typeof card.index === 'string' ? card.index.trim() : String(card.index ?? '').trim();
2792
+ const copy = typeof card.copy === 'string' ? card.copy.trim() : '';
2793
+ if (index === '' || copy === '') continue;
2794
+ const status = typeof card.status === 'string' ? card.status.trim() : undefined;
2795
+ const rawPath = typeof card.imagePath === 'string' ? card.imagePath.trim() : '';
2796
+ const resolvedImg = rawPath !== '' ? (rawPath.startsWith('/') ? rawPath : resolve(workDir, rawPath)) : '';
2797
+ const validImg = resolvedImg !== '' && isFile(resolvedImg) ? resolvedImg : undefined;
2798
+ out.push({
2799
+ index,
2800
+ copy,
2801
+ ...(status === undefined ? {} : { status }),
2802
+ ...(validImg === undefined ? {} : { imagePath: validImg }),
2803
+ });
2804
+ }
2805
+ return out;
2806
+ }
2807
+
2503
2808
  export function dailyBundleVariants(args: string[]): void {
2504
2809
  const [workDir = '', runDate = '', _pluginsPath = '', cardsEnabledArg = '', coverEnabledArg = ''] = args;
2505
2810
  timed(workDir, 'bundle-variants', () => {
@@ -2514,14 +2819,20 @@ export function dailyBundleVariants(args: string[]): void {
2514
2819
  const notesPath = join(workDir, '31-publish', `${runDate}_15_show-notes_show-notes.md`);
2515
2820
  const cardsPath = join(workDir, '25-xhs', 'content.json');
2516
2821
  const coverPath = join(workDir, '23-cover', `${runDate}_07_cover_cover.png`);
2822
+ const socialCoverPath = join(workDir, '23-cover', `${runDate}_07_cover_social.jpg`);
2517
2823
  const socialDir = join(workDir, '26-social');
2518
2824
  const cover = coverEnabledArg !== 'false' && isFile(coverPath) ? resolve(coverPath) : undefined;
2825
+ const socialCover =
2826
+ coverEnabledArg !== 'false' && isFile(socialCoverPath) ? resolve(socialCoverPath) : undefined;
2519
2827
  const links = PLACEHOLDER_LINKS;
2520
2828
  const written: string[] = [];
2521
2829
  const skipped: string[] = [];
2522
2830
 
2523
2831
  const article = readJson(articlePath);
2832
+ // 0426 R2: [] when the run never opted in, so a default run's variants stay byte-identical.
2833
+ const inlineFigures = inlineFigureMaterials(workDir, runDate);
2524
2834
  const prep = readJson(prepPath);
2835
+ const planItems = planItemsForPodcast(workDir, runDate);
2525
2836
  const write = (key: string, content: Record<string, unknown>): void => {
2526
2837
  const file = join(outDir, variantFileName(key));
2527
2838
  sted('write', file, () => writeJsonText(file, content));
@@ -2553,12 +2864,19 @@ export function dailyBundleVariants(args: string[]): void {
2553
2864
  prep !== null && typeof metadataOf(prep).audioFile === 'string'
2554
2865
  ? String(metadataOf(prep).audioFile)
2555
2866
  : undefined;
2867
+ const rawArticleBody =
2868
+ typeof (article as Record<string, unknown>).body === 'string'
2869
+ ? String((article as Record<string, unknown>).body)
2870
+ : '';
2871
+ const wechatKeyPoints = extractWechatKeyPoints(planItems, rawArticleBody);
2556
2872
  write(
2557
2873
  'article@wechatmp-pub',
2558
2874
  buildWechatArticleContent(article, {
2559
2875
  links,
2560
2876
  publishStatus: 'draft',
2561
2877
  collection: '每日AI资讯',
2878
+ keyPoints: wechatKeyPoints,
2879
+ inlineFigures,
2562
2880
  ...(cover === undefined ? {} : { coverPath: cover }),
2563
2881
  ...(articleAudio === undefined ? {} : { audioPath: articleAudio, audioTitle: firstArticleLine }),
2564
2882
  }),
@@ -2568,8 +2886,16 @@ export function dailyBundleVariants(args: string[]): void {
2568
2886
  if (prep === null) skipped.push('episode (no publish-prep content)');
2569
2887
  else {
2570
2888
  const showNotes = isFile(notesPath) ? readFileSync(notesPath, 'utf-8') : '';
2571
- write('episode', buildPodcastContent(prep, { showNotes }));
2572
- write('episode@podcast-pub', buildPodcastContent(prep, { showNotes }));
2889
+ const podcastCards = cardsForPodcast(workDir, cardsEnabledArg !== 'false');
2890
+ const podcastMeta: Record<string, unknown> = {
2891
+ ...(planItems.length > 0 ? { planItems } : {}),
2892
+ ...(podcastCards.length > 0 ? { cards: podcastCards } : {}),
2893
+ ...(socialCover === undefined ? {} : { socialImage: socialCover, socialImageEnabled: true }),
2894
+ };
2895
+ const podcastOpts =
2896
+ Object.keys(podcastMeta).length > 0 ? { showNotes, podcast: podcastMeta } : { showNotes };
2897
+ write('episode', buildPodcastContent(prep, podcastOpts));
2898
+ write('episode@podcast-pub', buildPodcastContent(prep, podcastOpts));
2573
2899
  write('episode@xhs-pub', buildXhsEpisodeContent(prep, { publishStatus: 'draft', links }));
2574
2900
  // 公众号 播客 shares the episode with podcast-pub: same audio, same cover, no article body.
2575
2901
  write(
@@ -2620,6 +2946,8 @@ export function dailyBundleVariants(args: string[]): void {
2620
2946
  limit,
2621
2947
  ...(cover === undefined ? {} : { coverPath: cover }),
2622
2948
  ...(cardImage === undefined ? {} : { cardPath: cardImage }),
2949
+ ...(firstArticleLine !== '' ? { episodeTitle: firstArticleLine } : {}),
2950
+ ...(prep !== null ? { listenUrl: links.podcastUrl } : {}),
2623
2951
  }),
2624
2952
  );
2625
2953
  }
@@ -2871,6 +3199,286 @@ export function dailyPublishPodcast(args: string[]): void {
2871
3199
  });
2872
3200
  }
2873
3201
 
3202
+ /** 0426 R2: one pinned `illustration` request per figure — the look is not per-run drivable. */
3203
+ export const INLINE_FIGURE_FORMAT = 'illustration';
3204
+ export const INLINE_FIGURE_STYLE = 'technical-diagram';
3205
+ export const INLINE_FIGURE_MAX = 2;
3206
+
3207
+ interface InlineFigurePlanEntry {
3208
+ anchor: string;
3209
+ sourceId: string;
3210
+ concept: string;
3211
+ caption: string;
3212
+ altText: string;
3213
+ }
3214
+
3215
+ interface InlineFigurePlan {
3216
+ version: 1;
3217
+ figures: InlineFigurePlanEntry[];
3218
+ }
3219
+
3220
+ /** One article paragraph, and whether a figure may anchor to it. */
3221
+ interface ArticleBlock {
3222
+ text: string;
3223
+ index: number;
3224
+ eligible: boolean;
3225
+ }
3226
+
3227
+ /**
3228
+ * 0426 R1 — split the body into blank-line-separated blocks and mark the prose ones: a fenced code
3229
+ * block, a heading, a quotation, a list item and an existing image are all ineligible, so a figure
3230
+ * can never land inside code or between a heading and its section.
3231
+ */
3232
+ export function articleBlocks(body: string): ArticleBlock[] {
3233
+ const blocks: ArticleBlock[] = [];
3234
+ let fence = false;
3235
+ for (const raw of body.split(/\n{2,}/)) {
3236
+ const text = raw.trim();
3237
+ if (text === '') continue;
3238
+ if (text.startsWith('```')) {
3239
+ fence = !fence;
3240
+ blocks.push({ text, index: blocks.length, eligible: false });
3241
+ continue;
3242
+ }
3243
+ const eligible =
3244
+ !fence &&
3245
+ !text.startsWith('#') &&
3246
+ !text.startsWith('>') &&
3247
+ !text.startsWith('![') &&
3248
+ !text.startsWith('- ') &&
3249
+ !text.startsWith('* ') &&
3250
+ !/^\d+\.\s/.test(text);
3251
+ blocks.push({ text, index: blocks.length, eligible });
3252
+ }
3253
+ return blocks;
3254
+ }
3255
+
3256
+ /** 0426 R1 — validate the whole plan before any provider call: shape, anchors, order, sources. */
3257
+ export function validateInlineFigurePlan(
3258
+ raw: unknown,
3259
+ body: string,
3260
+ admittedIds: ReadonlySet<string>,
3261
+ ): InlineFigurePlan {
3262
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
3263
+ failWith(1, 'inline illustrations: plan.json must be a JSON object {version, figures}');
3264
+ }
3265
+ const plan = raw as Record<string, unknown>;
3266
+ if (plan.version !== 1) failWith(1, `inline illustrations: plan version must be 1, got ${String(plan.version)}`);
3267
+ if (!Array.isArray(plan.figures) || plan.figures.length === 0) {
3268
+ failWith(1, 'inline illustrations: plan.figures must hold 1 or 2 figures');
3269
+ }
3270
+ if (plan.figures.length > INLINE_FIGURE_MAX) {
3271
+ failWith(
3272
+ 1,
3273
+ `inline illustrations: at most ${INLINE_FIGURE_MAX} figures per article, got ${plan.figures.length}`,
3274
+ );
3275
+ }
3276
+ const blocks = articleBlocks(body);
3277
+ const figures: InlineFigurePlanEntry[] = [];
3278
+ const usedAnchors = new Set<string>();
3279
+ let lastBlock = -1;
3280
+ for (const [position, entry] of plan.figures.entries()) {
3281
+ const figure = (entry ?? {}) as Record<string, unknown>;
3282
+ const label = `figure ${position + 1}`;
3283
+ for (const field of ['anchor', 'sourceId', 'concept', 'caption', 'altText'] as const) {
3284
+ const value = figure[field];
3285
+ if (typeof value !== 'string' || value.trim() === '') {
3286
+ failWith(1, `inline illustrations: ${label} has no ${field}`);
3287
+ }
3288
+ }
3289
+ const anchor = String(figure.anchor).trim();
3290
+ const sourceId = String(figure.sourceId).trim();
3291
+ if (!admittedIds.has(sourceId)) {
3292
+ failWith(1, `inline illustrations: ${label} cites source '${sourceId}', not an admitted plan item`);
3293
+ }
3294
+ const occurrences = body.split(anchor).length - 1;
3295
+ if (occurrences !== 1) {
3296
+ failWith(
3297
+ 1,
3298
+ `inline illustrations: ${label} anchor must be one unique whole paragraph of the reviewed article (found ${occurrences})`,
3299
+ );
3300
+ }
3301
+ if (usedAnchors.has(anchor)) {
3302
+ failWith(
3303
+ 1,
3304
+ `inline illustrations: ${label} duplicates an earlier figure's anchor — each figure needs its own paragraph`,
3305
+ );
3306
+ }
3307
+ usedAnchors.add(anchor);
3308
+ const block = blocks.find((candidate) => candidate.eligible && candidate.text === anchor);
3309
+ if (block === undefined) {
3310
+ failWith(
3311
+ 1,
3312
+ `inline illustrations: ${label} anchor is not a whole prose paragraph (code, heading, quotation, list and image blocks are ineligible): '${anchor.slice(0, 60)}'`,
3313
+ );
3314
+ }
3315
+ if (block.index <= lastBlock) {
3316
+ failWith(1, `inline illustrations: ${label} is out of body order — figures follow their paragraphs`);
3317
+ }
3318
+ lastBlock = block.index;
3319
+ figures.push({
3320
+ anchor,
3321
+ sourceId,
3322
+ concept: String(figure.concept).trim(),
3323
+ caption: String(figure.caption).trim(),
3324
+ altText: String(figure.altText).trim(),
3325
+ });
3326
+ }
3327
+ return { version: 1, figures };
3328
+ }
3329
+
3330
+ /**
3331
+ * 0426 R1 — the draft-verdict gate `dailyPublishPrep` applies, reused BEFORE any figure is billed:
3332
+ * no stamp, a stamp on different bytes (edited after review) or a WeChat-excluded target never spends.
3333
+ */
3334
+ export function assertInlineFigureDrafts(workDir: string, runDate: string): void {
3335
+ const stamp = readJson(safetyPath(workDir, runDate, 'safety-judge_stamp.json'));
3336
+ if (stamp === null) {
3337
+ failWith(1, 'inline illustrations: no content-safety verdict stamp for this run — not rendering figures');
3338
+ }
3339
+ if (stamp.status !== 'pass' && stamp.status !== 'escalate' && stamp.status !== 'exclude') {
3340
+ failWith(1, `inline illustrations: content-safety status ${String(stamp.status)} does not publish`);
3341
+ }
3342
+ if (stamp.digest !== safetyDigest(workDir, runDate)) {
3343
+ failWith(1, 'inline illustrations: drafts changed after the content-safety verdict — re-run the review');
3344
+ }
3345
+ const excluded = Array.isArray(stamp.excludedPlatforms) ? (stamp.excludedPlatforms as string[]) : [];
3346
+ if (excluded.includes('wechatmp')) {
3347
+ failWith(
3348
+ 1,
3349
+ 'inline illustrations: content-safety excluded wechatmp for this run — no article carries the figures',
3350
+ );
3351
+ }
3352
+ }
3353
+
3354
+ /** 0426 R1 — the preset row that can carry a figure: the enabled WeChat ARTICLE row, not 播客. */
3355
+ export function assertInlineFigureTarget(presetPath: string): void {
3356
+ const preset = readJson(presetPath);
3357
+ const targets = Array.isArray(preset?.targets) ? (preset.targets as Record<string, unknown>[]) : [];
3358
+ const enabled = targets.filter(
3359
+ (target) =>
3360
+ target.plugin === 'wechatmp-pub' &&
3361
+ target.operation === '文章' &&
3362
+ target.variant === 'article' &&
3363
+ typeof target.mode === 'string' &&
3364
+ target.mode !== 'off',
3365
+ );
3366
+ if (enabled.length === 0) {
3367
+ failWith(
3368
+ 1,
3369
+ `inline illustrations: preset ${basename(presetPath)} has no enabled wechatmp-pub 文章 (article) target — no article could carry the figures`,
3370
+ );
3371
+ }
3372
+ }
3373
+
3374
+ function sha256File(path: string): string {
3375
+ return createHash('sha256').update(readFileSync(path)).digest('hex');
3376
+ }
3377
+
3378
+ /**
3379
+ * 0426 R1/R2 — `kk stage news-inline-illustrations <work_dir> <run_date> <plugins_path> <provider>
3380
+ * <model> <preset_path>`.
3381
+ *
3382
+ * Validate the whole plan, then render or resume one figure at a time. A figure is reused only when
3383
+ * its receipt matches the current body hash, anchor, concept and settings AND the file on disk still
3384
+ * hashes to the recorded SHA-256; anything else re-renders. Each receipt is written as soon as its
3385
+ * figure lands, so a partial provider failure keeps the completed figures for the resume run.
3386
+ */
3387
+ export function dailyInlineIllustrations(args: string[]): void {
3388
+ const [workDir = '', runDate = '', pluginsPath = '', provider = '', model = '', presetPath = ''] = args;
3389
+ const dir = join(workDir, '22-article', 'illustrations');
3390
+ const articlePath = join(workDir, '22-article', `${runDate}_06_article_content.json`);
3391
+ const planDocsPath = join(workDir, '21-plan', `${runDate}_03_plan_plan.json`);
3392
+ timed(workDir, 'inline-illustrations', () => {
3393
+ if (presetPath === '') {
3394
+ failWith(1, 'inline illustrations: no publish-preset path was passed for target admission');
3395
+ }
3396
+ // Admission first: an unsupported target must never reach validation, let alone a provider.
3397
+ assertInlineFigureTarget(presetPath);
3398
+ const article = requireJson(articlePath, 'inline-illustrations');
3399
+ const body = typeof article.body === 'string' ? article.body : '';
3400
+ if (body.trim() === '') failWith(1, `inline illustrations: ${articlePath} has no article body to anchor to`);
3401
+ const planDocs = readJson(planDocsPath);
3402
+ const admittedIds = new Set(
3403
+ (Array.isArray(planDocs) ? planDocs : [])
3404
+ .map((doc) =>
3405
+ doc !== null && typeof doc === 'object' ? (doc as Record<string, unknown>).id : undefined,
3406
+ )
3407
+ .filter((id): id is string => typeof id === 'string' && id !== ''),
3408
+ );
3409
+ assertInlineFigureDrafts(workDir, runDate);
3410
+ const plan = validateInlineFigurePlan(
3411
+ requireJson(join(dir, 'plan.json'), 'inline-illustrations'),
3412
+ body,
3413
+ admittedIds,
3414
+ );
3415
+ const bodySha256 = createHash('sha256').update(body).digest('hex');
3416
+ const settings = { format: INLINE_FIGURE_FORMAT, style: INLINE_FIGURE_STYLE, provider, model };
3417
+ sted('mkdir', dir, () => mkdirSync(dir, { recursive: true }));
3418
+ for (const [position, figure] of plan.figures.entries()) {
3419
+ const id = `figure-${position + 1}`;
3420
+ const contentPath = join(dir, `${id}.json`);
3421
+ const receiptPath = join(dir, `${id}.receipt.json`);
3422
+ const receipt = readJson(receiptPath);
3423
+ const previous = firstArtifact(readJson(contentPath));
3424
+ const previousPath = typeof previous?.path === 'string' ? previous.path : '';
3425
+ const reusable =
3426
+ receipt !== null &&
3427
+ receipt.id === id &&
3428
+ receipt.bodySha256 === bodySha256 &&
3429
+ receipt.anchor === figure.anchor &&
3430
+ receipt.concept === figure.concept &&
3431
+ JSON.stringify(receipt.settings) === JSON.stringify(settings) &&
3432
+ previousPath !== '' &&
3433
+ isFile(previousPath) &&
3434
+ receipt.imageSha256 === sha256File(previousPath);
3435
+ if (reusable) {
3436
+ console.log(`inline illustrations: ${id} reused (verified bytes ${previousPath})`);
3437
+ continue;
3438
+ }
3439
+ const envPath = join(dir, `${id}.in.json`);
3440
+ const imageGen: Record<string, unknown> = {
3441
+ job: 'illustration',
3442
+ format: INLINE_FIGURE_FORMAT,
3443
+ style: INLINE_FIGURE_STYLE,
3444
+ count: 1,
3445
+ maxImages: 1,
3446
+ positions: [figure.anchor],
3447
+ vars: { concept: figure.concept, title: figure.sourceId },
3448
+ };
3449
+ if (provider !== '') imageGen.provider = provider;
3450
+ if (model !== '') imageGen.model = model;
3451
+ sted('write', envPath, () =>
3452
+ writeJsonText(envPath, [{ id, title: runDate, body: '', metadata: { imageGen } }]),
3453
+ );
3454
+ kk(['executor', 'run', 'image-gen', '--in', envPath, '--out', contentPath, ...pluginsArgs(pluginsPath)]);
3455
+ const artifact = firstArtifact(readJson(contentPath));
3456
+ const artifactPath = typeof artifact?.path === 'string' ? artifact.path : '';
3457
+ if (artifactPath === '' || !isFile(artifactPath)) {
3458
+ failWith(
3459
+ 1,
3460
+ `inline illustrations: ${id} produced no image file (image-gen wrote ${contentPath}); figures before it keep their receipts`,
3461
+ );
3462
+ }
3463
+ sted('write', receiptPath, () =>
3464
+ writeJsonText(receiptPath, {
3465
+ version: 1,
3466
+ id,
3467
+ anchor: figure.anchor,
3468
+ sourceId: figure.sourceId,
3469
+ concept: figure.concept,
3470
+ caption: figure.caption,
3471
+ altText: figure.altText,
3472
+ bodySha256,
3473
+ settings,
3474
+ imageSha256: sha256File(artifactPath),
3475
+ }),
3476
+ );
3477
+ }
3478
+ console.log(`inline illustrations: ${plan.figures.length} figure(s) ready in ${dir}`);
3479
+ });
3480
+ }
3481
+
2874
3482
  export function dailyPublishPrep(args: string[]): void {
2875
3483
  const [workDir = '', runDate = '', artist = '', album = ''] = args;
2876
3484
  const articlePath = join(workDir, '22-article', `${runDate}_06_article_content.json`);
@@ -2940,6 +3548,11 @@ export function dailyPublishPrep(args: string[]): void {
2940
3548
  : {}),
2941
3549
  ...(hasCover ? { coverImage: resolvedCover } : {}),
2942
3550
  ...(episode > 0 ? { itunes: { season, episode } } : {}),
3551
+ ...(typeof audioMeta.duration === 'number' &&
3552
+ Number.isFinite(audioMeta.duration) &&
3553
+ audioMeta.duration > 0
3554
+ ? { durationSeconds: audioMeta.duration }
3555
+ : {}),
2943
3556
  },
2944
3557
  options: {
2945
3558
  audioFile,
@@ -6119,6 +6732,25 @@ export function newsLocalizeValidate(args: string[]): void {
6119
6732
  );
6120
6733
  continue;
6121
6734
  }
6735
+ // Rewrite safe compound retired/wrong-locale series brands before freezing and refuse
6736
+ // any unrewritable retired brand or wrong-language show name that check:seo rejects.
6737
+ const normalized = normalizeSeriesNames(raw, locale);
6738
+ const activeText = normalized.markdown;
6739
+ if (activeText !== raw) {
6740
+ sted('write', file, () => writeRaw(file, activeText));
6741
+ }
6742
+ if (normalized.remaining.length > 0) {
6743
+ problems.push(`${locale}: retired series name (${normalized.remaining.join(', ')})`);
6744
+ continue;
6745
+ }
6746
+ if (locale === 'ja' && /ごった煮|寄せ鍋|咸话咸说|Salty Talk/i.test(activeText)) {
6747
+ problems.push(`${locale}: retired series or wrong-language show name in translated body`);
6748
+ continue;
6749
+ }
6750
+ if (locale === 'en' && /咸话咸说|咸話咸説/.test(activeText)) {
6751
+ problems.push(`${locale}: wrong-language show name in translated body`);
6752
+ continue;
6753
+ }
6122
6754
  accepted.push(locale);
6123
6755
  }
6124
6756
  if (problems.length > 0) {
@@ -6280,6 +6912,25 @@ export function reduceOverflowingPoints(points: string[], named: readonly number
6280
6912
  changed = true;
6281
6913
  }
6282
6914
  }
6915
+ // When a long earlier point pushes a short trailing point out of the safe area, the composer
6916
+ // names the trailing index. Shorten the longest shrinkable point so the block fits.
6917
+ if (!changed) {
6918
+ let bestIndex = -1;
6919
+ let bestLen = 0;
6920
+ for (let i = 0; i < points.length; i++) {
6921
+ const point = points[i] ?? '';
6922
+ const next = shortenOverflowedPoint(point);
6923
+ if (next !== point && point.length > bestLen) {
6924
+ bestIndex = i;
6925
+ bestLen = point.length;
6926
+ }
6927
+ }
6928
+ if (bestIndex >= 0) {
6929
+ const point = points[bestIndex] ?? '';
6930
+ points[bestIndex] = shortenOverflowedPoint(point);
6931
+ changed = true;
6932
+ }
6933
+ }
6283
6934
  if (!changed && points.length > XHS_MIN_POINTS) {
6284
6935
  points.pop();
6285
6936
  changed = true;