@gobing-ai/knowledge-kit 0.1.24 → 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 (69) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/index.js +302 -59
  3. package/package.json +1 -1
  4. package/plugins/generations/episode-plan-gen/dist/index.js +47 -6
  5. package/plugins/generations/episode-plan-gen/src/index.ts +71 -7
  6. package/plugins/generations/music-gen/dist/index.js +17 -13
  7. package/plugins/generations/music-gen/src/audio/measure.ts +25 -20
  8. package/plugins/kk/decisions/extract/ai-news.yaml +8 -1
  9. package/plugins/kk/plugin.json +1 -1
  10. package/plugins/kk/publish-presets/daily-ai-voice.json +4 -4
  11. package/plugins/kk/publish-presets/itc-main.json +39 -23
  12. package/plugins/kk/scripts/daily-stages.ts +500 -33
  13. package/plugins/kk/scripts/kk-workflow-stages.ts +5 -0
  14. package/plugins/kk/skills/content-safety/references/platforms/apple-podcasts.md +12 -5
  15. package/plugins/kk/skills/content-safety/references/platforms/wechatmp.md +8 -0
  16. package/plugins/kk/skills/content-safety/references/platforms/xiaoyuzhou.md +5 -0
  17. package/plugins/kk/skills/daily-news-cover/SKILL.md +96 -0
  18. package/plugins/kk/skills/daily-news-illustrations/SKILL.md +123 -0
  19. package/plugins/kk/skills/news-editorial/SKILL.md +5 -3
  20. package/plugins/kk/skills/news-editorial/references/daily-visual-composition.md +150 -0
  21. package/plugins/kk/skills/news-editorial/references/style-contract.zh.md +1 -1
  22. package/plugins/kk/workflows/kk-article-generate.yaml +13 -1
  23. package/plugins/kk/workflows/kk-daily-ai-voice.yaml +6 -3
  24. package/plugins/kk/workflows/kk-daily-ai-voice2.yaml +6 -4
  25. package/plugins/kk/workflows/kk-news-generate.yaml +71 -1
  26. package/plugins/publishings/bilibili-pub/dist/index.js +3 -2
  27. package/plugins/publishings/bilibili-pub/dist/profile-check.js +3 -2
  28. package/plugins/publishings/cnblogs-pub/dist/index.js +3 -2
  29. package/plugins/publishings/cnblogs-pub/dist/profile-check.js +3 -2
  30. package/plugins/publishings/csdn-pub/dist/index.js +3 -2
  31. package/plugins/publishings/csdn-pub/dist/profile-check.js +3 -2
  32. package/plugins/publishings/infoq-pub/dist/index.js +3 -2
  33. package/plugins/publishings/infoq-pub/dist/profile-check.js +3 -2
  34. package/plugins/publishings/jike-pub/dist/index.js +3 -2
  35. package/plugins/publishings/jike-pub/dist/profile-check.js +3 -2
  36. package/plugins/publishings/juejin-pub/dist/index.js +3 -2
  37. package/plugins/publishings/juejin-pub/dist/profile-check.js +3 -2
  38. package/plugins/publishings/linkedin-pub/dist/index.js +3 -2
  39. package/plugins/publishings/linkedin-pub/dist/profile-check.js +3 -2
  40. package/plugins/publishings/medium-pub/dist/index.js +9198 -279
  41. package/plugins/publishings/medium-pub/dist/profile-check.js +21174 -0
  42. package/plugins/publishings/medium-pub/package.json +3 -1
  43. package/plugins/publishings/medium-pub/plugin.json +6 -1
  44. package/plugins/publishings/medium-pub/src/browser-rail.ts +280 -0
  45. package/plugins/publishings/medium-pub/src/index.ts +17 -1
  46. package/plugins/publishings/medium-pub/src/profile-check.ts +27 -0
  47. package/plugins/publishings/shipinhao-pub/dist/index.js +6 -3
  48. package/plugins/publishings/shipinhao-pub/dist/profile-check.js +5 -3
  49. package/plugins/publishings/shipinhao-pub/src/flow.ts +5 -0
  50. package/plugins/publishings/shipinhao-pub/src/selectors.ts +11 -4
  51. package/plugins/publishings/sspai-pub/dist/index.js +3 -2
  52. package/plugins/publishings/sspai-pub/dist/profile-check.js +3 -2
  53. package/plugins/publishings/substack-pub/dist/index.js +3 -2
  54. package/plugins/publishings/substack-pub/dist/profile-check.js +3 -2
  55. package/plugins/publishings/threads-pub/dist/index.js +3 -2
  56. package/plugins/publishings/threads-pub/dist/profile-check.js +3 -2
  57. package/plugins/publishings/wechatmp-pub/dist/index.js +262 -42
  58. package/plugins/publishings/wechatmp-pub/dist/profile-check.js +3 -2
  59. package/plugins/publishings/wechatmp-pub/src/flow.ts +447 -53
  60. package/plugins/publishings/wechatmp-pub/src/index.ts +4 -1
  61. package/plugins/publishings/wechatmp-pub/src/page.ts +8 -0
  62. package/plugins/publishings/weibo-pub/dist/index.js +3 -2
  63. package/plugins/publishings/weibo-pub/dist/profile-check.js +3 -2
  64. package/plugins/publishings/x-pub/dist/index.js +3 -2
  65. package/plugins/publishings/x-pub/dist/profile-check.js +3 -2
  66. package/plugins/publishings/xhs-pub/dist/index.js +3 -2
  67. package/plugins/publishings/xhs-pub/dist/profile-check.js +3 -2
  68. package/plugins/publishings/xiaoyuzhou-pub/dist/index.js +3 -2
  69. package/plugins/publishings/xiaoyuzhou-pub/dist/profile-check.js +3 -2
@@ -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;
@@ -2210,8 +2261,8 @@ function wechatKeyPointLabel(title: string): string {
2210
2261
  const clean = title.replace(/^#+\s+/, '').trim();
2211
2262
  const firstClause = clean.split(/[::,,。!?!?\-—|]/)[0]?.trim() ?? clean;
2212
2263
  const chars = Array.from(firstClause);
2213
- if (chars.length > 0 && chars.length <= 18) return firstClause;
2214
- return Array.from(clean).slice(0, 18).join('');
2264
+ if (chars.length > 0 && chars.length <= 28) return firstClause;
2265
+ return Array.from(clean).slice(0, 28).join('');
2215
2266
  }
2216
2267
 
2217
2268
  function extractWechatKeyPoints(
@@ -2264,6 +2315,94 @@ function cleanWechatDigest(body: string, keyPoints?: readonly WechatKeyPoint[]):
2264
2315
  return Array.from(candidate).slice(0, 120).join('');
2265
2316
  }
2266
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
+
2267
2406
  /**
2268
2407
  * The 公众号 article payload (task 0327 R1): the article Content plus MP draft enrichment.
2269
2408
  *
@@ -2286,13 +2425,20 @@ export function buildWechatArticleContent(
2286
2425
  * carries the episode body, so it passes `false`.
2287
2426
  */
2288
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[];
2289
2433
  },
2290
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 ?? []);
2291
2438
  const wechatmp: Record<string, unknown> = {
2292
2439
  original: true,
2293
- // 2026-11-21 operator decision (A3): keep `reward: false` while the 咸话咸说 account lacks
2294
- // an authorized 赞赏账户, so WECHATMP_ALLOW_PARTIAL_ENRICH=1 is no longer needed and real
2295
- // enrichment failures (音频, 原创, 原文链接) fail loud.
2440
+ // 2026-11-22 live check: 咸话咸说 is not yet authorized in 赞赏账户小程序 -> 可收款公众号,
2441
+ // so reward stays false until the operator authorizes it there.
2296
2442
  reward: false,
2297
2443
  author: WECHAT_BRAND.author,
2298
2444
  collection: options.collection,
@@ -2300,6 +2446,19 @@ export function buildWechatArticleContent(
2300
2446
  claimSource: WECHAT_BRAND.claimSource,
2301
2447
  // 封面 comes from 图片库: the episode cover is uploaded there as the audio material's cover.
2302
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
+ : {}),
2303
2462
  ...(options.links.articleUrl !== '' ? { originalUrl: options.links.articleUrl } : {}),
2304
2463
  ...(options.coverPath === undefined ? {} : { coverPath: options.coverPath }),
2305
2464
  ...(options.audioPath === undefined
@@ -2324,17 +2483,23 @@ export function buildWechatArticleContent(
2324
2483
  },
2325
2484
  };
2326
2485
  }
2327
- let formattedBody = stripLeadingH1Heading(rawBody);
2486
+ let formattedBody = stripLeadingH1Heading(rawBody).trimStart();
2328
2487
  const keyPoints = (options.keyPoints ?? []).filter((kp) => kp.label.trim() !== '' && kp.text.trim() !== '');
2329
- if (keyPoints.length > 0 && !/^\s*##\s+今日要点\b/m.test(formattedBody)) {
2330
- const bullets = keyPoints.map((kp) => `- **${kp.label.trim()}** — ${kp.text.trim()}`).join('\n');
2331
- formattedBody = `## 今日要点\n\n${bullets}\n\n${formattedBody.trimStart()}`;
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
+ }
2332
2497
  }
2333
2498
  const existingDigest = typeof existingMeta.digest === 'string' ? existingMeta.digest.trim() : '';
2334
2499
  const derivedDigest = existingDigest !== '' ? existingDigest : cleanWechatDigest(rawBody, keyPoints);
2335
2500
  return {
2336
2501
  ...article,
2337
- body: `${formattedBody}${WECHAT_OUTRO}`,
2502
+ body: `${withInlineFigureMarkers(formattedBody, figures)}${WECHAT_OUTRO}`,
2338
2503
  metadata: {
2339
2504
  ...existingMeta,
2340
2505
  ...(derivedDigest !== '' ? { digest: derivedDigest } : {}),
@@ -2501,16 +2666,16 @@ export function weightedLength(text: string): number {
2501
2666
  }
2502
2667
 
2503
2668
  /** Platforms where attaching a native image suppresses the URL's clickable Open Graph preview card. */
2504
- const OG_CARD_PLATFORMS = new Set(['x', 'threads', 'linkedin']);
2669
+ const OG_CARD_PLATFORMS = new Set(['x', 'threads', 'linkedin', 'weibo']);
2505
2670
 
2506
2671
  /**
2507
2672
  * One channel's short promo copy as a Content (task 0327 R3; task 0410 episode promo framing):
2508
2673
  * prepends the frozen episode title and appends the episode listen URL (`{{podcast_url}}`) when
2509
2674
  * supplied, reserving header/footer budget before truncating copy (X counts URLs at t.co weight 23).
2510
2675
  *
2511
- * Platforms in `OG_CARD_PLATFORMS` (`x`, `threads`, `linkedin`) omit `coverImage` when linking a
2676
+ * Platforms in `OG_CARD_PLATFORMS` (`x`, `threads`, `linkedin`, `weibo`) omit `coverImage` when linking a
2512
2677
  * podcast URL so their native Open Graph card renders cleanly instead of being suppressed by an
2513
- * attached image; image-first rails (`weibo`, `jike`) keep `coverImage`.
2678
+ * attached image; image-first rails (`jike`) keep `coverImage`.
2514
2679
  */
2515
2680
  export function buildSocialContent(
2516
2681
  copy: string,
@@ -2664,6 +2829,8 @@ export function dailyBundleVariants(args: string[]): void {
2664
2829
  const skipped: string[] = [];
2665
2830
 
2666
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);
2667
2834
  const prep = readJson(prepPath);
2668
2835
  const planItems = planItemsForPodcast(workDir, runDate);
2669
2836
  const write = (key: string, content: Record<string, unknown>): void => {
@@ -2709,6 +2876,7 @@ export function dailyBundleVariants(args: string[]): void {
2709
2876
  publishStatus: 'draft',
2710
2877
  collection: '每日AI资讯',
2711
2878
  keyPoints: wechatKeyPoints,
2879
+ inlineFigures,
2712
2880
  ...(cover === undefined ? {} : { coverPath: cover }),
2713
2881
  ...(articleAudio === undefined ? {} : { audioPath: articleAudio, audioTitle: firstArticleLine }),
2714
2882
  }),
@@ -3031,6 +3199,286 @@ export function dailyPublishPodcast(args: string[]): void {
3031
3199
  });
3032
3200
  }
3033
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
+
3034
3482
  export function dailyPublishPrep(args: string[]): void {
3035
3483
  const [workDir = '', runDate = '', artist = '', album = ''] = args;
3036
3484
  const articlePath = join(workDir, '22-article', `${runDate}_06_article_content.json`);
@@ -6464,6 +6912,25 @@ export function reduceOverflowingPoints(points: string[], named: readonly number
6464
6912
  changed = true;
6465
6913
  }
6466
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
+ }
6467
6934
  if (!changed && points.length > XHS_MIN_POINTS) {
6468
6935
  points.pop();
6469
6936
  changed = true;