@gobing-ai/knowledge-kit 0.1.19 → 0.1.20

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 (54) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/board/daily-voice/index.js +40 -7
  3. package/dist/index.js +1379 -378
  4. package/package.json +1 -1
  5. package/plugins/generations/image-gen/README.md +31 -31
  6. package/plugins/generations/image-gen/assets/sample/provenance.json +314 -0
  7. package/plugins/generations/image-gen/config.example.yaml +3 -0
  8. package/plugins/generations/image-gen/dist/index.js +154 -14
  9. package/plugins/generations/image-gen/presets/SOURCE.md +65 -0
  10. package/plugins/generations/image-gen/scripts/eval-style-presets.ts +513 -0
  11. package/plugins/generations/image-gen/scripts/gen-samples.ts +57 -7
  12. package/plugins/generations/image-gen/src/presets.ts +6 -5
  13. package/plugins/generations/image-gen/src/providers/h3-local.ts +196 -0
  14. package/plugins/generations/image-gen/src/providers/types.ts +11 -1
  15. package/plugins/kk/config.example.yaml +3 -0
  16. package/plugins/kk/decisions/extract/ai-news.yaml +5 -2
  17. package/plugins/kk/plugin.json +1 -1
  18. package/plugins/kk/publish-presets/daily-ai-voice.json +48 -7
  19. package/plugins/kk/scripts/daily-stages.ts +238 -14
  20. package/plugins/kk/skills/image-authoring/SKILL.md +7 -3
  21. package/plugins/kk/skills/image-authoring/references/providers.md +27 -0
  22. package/plugins/kk/skills/image-authoring/references/style-extraction.md +1 -1
  23. package/plugins/kk/skills/publish/SKILL.md +11 -0
  24. package/plugins/kk/skills/web-automation/SKILL.md +31 -1
  25. package/plugins/kk/workflows/kk-collect.yaml +8 -4
  26. package/plugins/kk/workflows/kk-daily-ai-voice.yaml +2 -1
  27. package/plugins/kk/workflows/kk-daily-ai-voice2.yaml +4 -2
  28. package/plugins/publishings/linkedin-pub/dist/index.js +43 -6
  29. package/plugins/publishings/linkedin-pub/dist/profile-check.js +32 -5
  30. package/plugins/publishings/linkedin-pub/src/index.ts +52 -6
  31. package/plugins/publishings/shipinhao-pub/dist/index.js +385 -31
  32. package/plugins/publishings/shipinhao-pub/dist/profile-check.js +3 -1
  33. package/plugins/publishings/shipinhao-pub/plugin.json +1 -1
  34. package/plugins/publishings/shipinhao-pub/src/audio-flow.ts +393 -0
  35. package/plugins/publishings/shipinhao-pub/src/flow.ts +227 -12
  36. package/plugins/publishings/shipinhao-pub/src/selectors.ts +13 -0
  37. package/plugins/publishings/surfdash-pub/dist/index.js +50 -8
  38. package/plugins/publishings/surfdash-pub/src/index.ts +59 -8
  39. package/plugins/publishings/surfdash-pub/src/topic-claims.ts +34 -3
  40. package/plugins/publishings/threads-pub/dist/index.js +9196 -296
  41. package/plugins/publishings/threads-pub/dist/profile-check.js +21139 -0
  42. package/plugins/publishings/threads-pub/package.json +3 -1
  43. package/plugins/publishings/threads-pub/plugin.json +6 -1
  44. package/plugins/publishings/threads-pub/src/index.ts +8 -1
  45. package/plugins/publishings/threads-pub/src/post-rail.ts +357 -0
  46. package/plugins/publishings/threads-pub/src/profile-check.ts +17 -0
  47. package/plugins/publishings/wechatmp-pub/dist/index.js +7 -0
  48. package/plugins/publishings/wechatmp-pub/src/flow.ts +13 -0
  49. package/plugins/publishings/weibo-pub/dist/index.js +46 -2
  50. package/plugins/publishings/weibo-pub/src/index.ts +74 -2
  51. package/plugins/publishings/x-pub/dist/index.js +263 -43
  52. package/plugins/publishings/x-pub/dist/profile-check.js +3 -1
  53. package/plugins/publishings/x-pub/src/index.ts +15 -1
  54. package/plugins/publishings/x-pub/src/post-rail.ts +334 -0
@@ -304,18 +304,196 @@ function authoredPlanDescendants(workDir: string, runDate: string): string[] {
304
304
  */
305
305
  const SPEAK_CHAR_EXPANSION = 1.4;
306
306
 
307
+ /**
308
+ * The cold-start ratio the PRE-SPEND widen decision uses, and it is deliberately not 1.4.
309
+ *
310
+ * The consumers need opposite safe directions (the same argument `scriptFloorCharRate` makes about
311
+ * the char rate): the reported arithmetic wants the typical ratio, while the pre-spend gates want
312
+ * the *worst measured* ratio, because a cheap error is a rung too many and the expensive one is an
313
+ * authoring pass the TTS gate then refuses.
314
+ *
315
+ * Measured spoken/kept-candidate ratios: 2026-10-11 1,270/1,800 = 0.71 and 5,925/4,300 = 1.38;
316
+ * 2026-11-15 run `kk-news-generate-20261115-1794773860762` 2,053/7,244 = 0.28. Treating 1.4 as the
317
+ * floor ratio let that day pass the gate at 32.6 min, spend a full authoring pass, then refuse at
318
+ * 6.2 min — and the ladder that exists to fill a thin day from the backlog never climbed a rung
319
+ * (0377).
320
+ *
321
+ * This constant is only the fallback: both gates prefer the ratio a previous run recorded, and the
322
+ * two records carry DIFFERENT denominators (see `readKeptRatio` — using one ratio for both was the
323
+ * 2026-11-16 refusal of a 23-min episode).
324
+ */
325
+ const SPEAK_CHAR_EXPANSION_FLOOR = 0.28;
326
+
327
+ /**
328
+ * Where a run records the ratios it actually delivered (0377 R2/R3). Two denominators, because the
329
+ * two pre-spend consumers measure different sets: `ratio` is spoken/pool (the ladder, which judges
330
+ * the raw extracted pool) and `keptRatio` is spoken/kept-candidate chars (the floor gate, which
331
+ * judges what QC actually admitted). The gates read the newest record from the sibling run
332
+ * directories, so they judge today's material by what the writer really produced last time instead
333
+ * of a constant that was calibrated once.
334
+ */
335
+ const SPOKEN_RATIO_SUFFIX = '_09_spoken-ratio.json';
336
+
337
+ /** The measured ratio one run delivered, and where it came from. */
338
+ interface SpokenRatio {
339
+ ratio: number;
340
+ source: string;
341
+ }
342
+
343
+ /** Clamp a recorded ratio into a plausible band: a corrupt file must not freeze or flood the ladder. */
344
+ function clampRatio(value: number): number {
345
+ return Math.min(2, Math.max(0.05, value));
346
+ }
347
+
348
+ /**
349
+ * The newest recorded spoken/raw ratio across this workflow's run directories, or the calibrated
350
+ * floor constant when no run has recorded one yet. `workDir` is one run directory, so its parent is
351
+ * the workflow directory the sibling runs live in.
352
+ */
353
+ function readSpokenRatio(workDir: string): SpokenRatio {
354
+ const base = resolve(workDir, '..');
355
+ let newest: { at: number; ratio: number; from: string } | null = null;
356
+ let entries: string[] = [];
357
+ try {
358
+ entries = readdirSync(base);
359
+ } catch {
360
+ return { ratio: SPEAK_CHAR_EXPANSION_FLOOR, source: 'default 0.28 (no sibling runs)' };
361
+ }
362
+ for (const entry of entries) {
363
+ const dir = join(base, entry, '21-plan');
364
+ let files: string[] = [];
365
+ try {
366
+ files = readdirSync(dir).filter((file) => file.endsWith(SPOKEN_RATIO_SUFFIX));
367
+ } catch {
368
+ continue;
369
+ }
370
+ for (const file of files) {
371
+ const path = join(dir, file);
372
+ try {
373
+ const parsed = readJson(path) as Record<string, unknown> | null;
374
+ const ratio = Number(parsed?.ratio);
375
+ if (!Number.isFinite(ratio) || ratio <= 0) continue;
376
+ const at = statSync(path).mtimeMs;
377
+ if (newest === null || at > newest.at) newest = { at, ratio, from: path };
378
+ } catch {
379
+ // A malformed record is not evidence; the next run overwrites it.
380
+ }
381
+ }
382
+ }
383
+ if (newest === null) return { ratio: SPEAK_CHAR_EXPANSION_FLOOR, source: 'default 0.28 (no recorded run)' };
384
+ return { ratio: clampRatio(newest.ratio), source: `${newest.from} (${newest.ratio.toFixed(2)}x)` };
385
+ }
386
+
387
+ /**
388
+ * The newest recorded spoken/KEPT ratio across sibling runs, or the cold-start constant.
389
+ *
390
+ * WHY this is separate from `readSpokenRatio` (2026-11-16): one constant was applied to two
391
+ * different denominators. The ladder multiplies the raw pool (38,241 chars that day) while this gate
392
+ * multiplies the kept candidates (13,963 chars — planning admitted 37% of the pool), so the same
393
+ * 0.28 read as a 34.5 min "clears" in the ladder and a 12.7 min "refusing" at the gate, and the run
394
+ * paid for the planning pass to discover it. The writer then delivered 7,194 spoken chars ≈ 23 min:
395
+ * the refusal discounted the planning shrink twice. `keptRatio` for that run is 0.515.
396
+ */
397
+ function readKeptRatio(workDir: string): SpokenRatio {
398
+ const base = resolve(workDir, '..');
399
+ let newest: { at: number; ratio: number; from: string } | null = null;
400
+ let entries: string[] = [];
401
+ try {
402
+ entries = readdirSync(base);
403
+ } catch {
404
+ return { ratio: SPEAK_CHAR_EXPANSION_FLOOR, source: 'default 0.28 (no sibling runs)' };
405
+ }
406
+ for (const entry of entries) {
407
+ const dir = join(base, entry, '21-plan');
408
+ let files: string[] = [];
409
+ try {
410
+ files = readdirSync(dir).filter((file) => file.endsWith(SPOKEN_RATIO_SUFFIX));
411
+ } catch {
412
+ continue;
413
+ }
414
+ for (const file of files) {
415
+ const path = join(dir, file);
416
+ try {
417
+ const parsed = readJson(path) as Record<string, unknown> | null;
418
+ // A pre-2026-11-16 record carries no kept ratio at all: skip it rather than divide by
419
+ // its pool figure, which is what produced the double discount.
420
+ const ratio = Number(parsed?.keptRatio);
421
+ if (!Number.isFinite(ratio) || ratio <= 0) continue;
422
+ const at = statSync(path).mtimeMs;
423
+ if (newest === null || at > newest.at) newest = { at, ratio, from: path };
424
+ } catch {
425
+ // A malformed record is not evidence; the next run overwrites it.
426
+ }
427
+ }
428
+ }
429
+ if (newest === null) return { ratio: SPEAK_CHAR_EXPANSION_FLOOR, source: 'default 0.28 (no recorded kept ratio)' };
430
+ return { ratio: clampRatio(newest.ratio), source: `${newest.from} (${newest.ratio.toFixed(2)}x)` };
431
+ }
432
+
433
+ /**
434
+ * Record what this run delivered — spoken script chars over raw pool chars, and over the kept
435
+ * candidates — and warn when it drifted from the ratio the widen decision used. A refused script
436
+ * records too: a thin day teaches the ladder even though it produced no episode.
437
+ */
438
+ function recordSpokenRatio(workDir: string, runDate: string, spokenChars: number): void {
439
+ const poolPath = join(workDir, '10-collect', 'pool.json');
440
+ if (!isFile(poolPath)) return;
441
+ const pool = readJson(poolPath);
442
+ const poolChars = rawChars(Array.isArray(pool) ? pool : []);
443
+ if (poolChars <= 0) return;
444
+ // The admitted set the floor gate measures, so the next pre-spend estimate discounts the planning
445
+ // shrink once instead of twice (2026-11-16).
446
+ const keptPath = join(workDir, '21-plan', `${runDate}_04_quality-control-content_candidates.json`);
447
+ const keptChars = isFile(keptPath) ? rawChars(metadataOf(readJson(keptPath)).docs ?? []) : 0;
448
+ const round3 = (value: number): number => Math.round(value * 1000) / 1000;
449
+ const ratio = round3(spokenChars / poolChars);
450
+ const out = join(workDir, '21-plan', `${runDate}${SPOKEN_RATIO_SUFFIX}`);
451
+ mkdirSync(join(workDir, '21-plan'), { recursive: true });
452
+ writeJsonText(out, {
453
+ runDate,
454
+ poolChars,
455
+ ...(keptChars > 0 ? { keptChars, keptRatio: round3(spokenChars / keptChars) } : {}),
456
+ spokenChars,
457
+ ratio,
458
+ });
459
+ // Drift warning: the ladder judged this pool with some ratio; the writer just delivered a
460
+ // different one. A wide gap means the next run's ladder is working from a stale measure.
461
+ let used: number | null = null;
462
+ try {
463
+ const ladder = readJson(join(workDir, '10-collect', 'ladder.json')) as Record<string, unknown> | null;
464
+ const candidate = Number(ladder?.ratioUsed);
465
+ if (Number.isFinite(candidate) && candidate > 0) used = candidate;
466
+ } catch {
467
+ used = null;
468
+ }
469
+ if (used !== null && Math.abs(ratio / used - 1) > 0.25) {
470
+ console.error(
471
+ `spoken ratio drifted: this run delivered ${ratio.toFixed(2)}x of the pool, the ladder widened on ${used.toFixed(2)}x (see ${out})`,
472
+ );
473
+ }
474
+ }
475
+
476
+ /** Title+body characters of a Doc[] — the raw measure every spoken ratio here divides into. */
477
+ function rawChars(docs: unknown[]): number {
478
+ return docs.reduce((sum, doc) => {
479
+ const entry = (doc ?? {}) as Record<string, unknown>;
480
+ return sum + `${String(entry.title ?? '')}`.length + String(entry.body ?? '').length;
481
+ }, 0);
482
+ }
483
+
307
484
  /**
308
485
  * The calibrated pre-spend estimate over a kept pool (title+body characters × the 1.4 expansion,
309
486
  * over the driver's measured char rate, plus the 8 s intro sting) — shared by the pre-spend floor
310
487
  * gate (applyFloorGate) and the post-spend duration refusal (dailyEpisodeDuration, 0266), so both
311
488
  * artifacts report the same arithmetic. `seconds` is unrounded: the floor gate compares seconds.
312
489
  */
313
- function estimateSpokenMinutes(docs: unknown[], vdriver: string): { minutes: number; seconds: number; chars: number } {
314
- const chars = docs.reduce((sum, doc) => {
315
- const entry = (doc ?? {}) as Record<string, unknown>;
316
- return sum + `${String(entry.title ?? '')}`.length + String(entry.body ?? '').length;
317
- }, 0);
318
- const seconds = 8 + (chars * SPEAK_CHAR_EXPANSION) / spokenCharRate(vdriver);
490
+ function estimateSpokenMinutes(
491
+ docs: unknown[],
492
+ vdriver: string,
493
+ expansion: number = SPEAK_CHAR_EXPANSION,
494
+ ): { minutes: number; seconds: number; chars: number } {
495
+ const chars = rawChars(docs);
496
+ const seconds = 8 + (chars * expansion) / spokenCharRate(vdriver);
319
497
  return { minutes: Math.round((seconds / 60) * 10) / 10, seconds, chars };
320
498
  }
321
499
 
@@ -329,6 +507,10 @@ function estimateSpokenMinutes(docs: unknown[], vdriver: string): { minutes: num
329
507
  * `pool-count --min 1` guard then skips the content, audio, publish and XHS subtrees, and the run
330
508
  * closes through run-report and the ledger exactly like an empty pool. The estimate and its inputs
331
509
  * land in a refusal artifact next to the candidates.
510
+ *
511
+ * The ratio comes from `readKeptRatio`, NOT the pool-denominated one the ladder uses: this gate
512
+ * measures the admitted set, and applying the pool ratio to it discounted the planning shrink twice
513
+ * (2026-11-16: estimated 12.7 min, the writer delivered 23).
332
514
  */
333
515
  function applyFloorGate(
334
516
  candidates: string,
@@ -350,7 +532,12 @@ function applyFloorGate(
350
532
  if (clearStaleRefusal && isFile(refusal)) unlinkSync(refusal);
351
533
  return;
352
534
  }
353
- const { minutes: estimatedMinutes, seconds: estimatedSeconds, chars } = estimateSpokenMinutes(docs, vdriver);
535
+ const keptRatio = readKeptRatio(workDir);
536
+ const {
537
+ minutes: estimatedMinutes,
538
+ seconds: estimatedSeconds,
539
+ chars,
540
+ } = estimateSpokenMinutes(docs, vdriver, keptRatio.ratio);
354
541
  if (estimatedSeconds >= floor * 60) {
355
542
  if (clearStaleRefusal && isFile(refusal)) unlinkSync(refusal);
356
543
  console.log(`floor gate: estimated ${estimatedMinutes} min from ${chars} chars — above the ${floor} min floor`);
@@ -362,7 +549,10 @@ function applyFloorGate(
362
549
  estimatedMinutes,
363
550
  minMinutes: floor,
364
551
  candidateChars: chars,
365
- expansion: SPEAK_CHAR_EXPANSION,
552
+ // The ratio this refusal actually used, and where it came from (0377; 2026-11-16): the
553
+ // gate measures the KEPT set, so a pool-denominated ratio under-predicts it badly.
554
+ expansion: keptRatio.ratio,
555
+ expansionSource: keptRatio.source,
366
556
  charRate: spokenCharRate(vdriver),
367
557
  ids,
368
558
  reason: `a ${docs.length}-item pool estimates ${estimatedMinutes} min of speech, below the ${floor} min floor — refusing before any TTS spend`,
@@ -445,23 +635,40 @@ export function dailyExtract(args: string[]): void {
445
635
  console.error(`extract: plan already authored — keeping the frozen pool (${poolPath})`);
446
636
  return;
447
637
  }
638
+ // 0377 R2: judge the pool by what the writer actually delivered last time. The calibrated
639
+ // 0.28 constant is only the fallback for a workflow that has never recorded a ratio.
640
+ const ratio = readSpokenRatio(workDir);
448
641
  let chosen: { window: string; docs: unknown[] } | null = null;
642
+ const rungs: Array<{ window: string; items: number; chars: number; minutes: number; clears: boolean }> = [];
449
643
  for (const ms of windows) {
450
644
  const label = formatWindowMs(ms);
451
645
  const attempt = join(workDir, '10-collect', `.pool-${label}.json`);
452
646
  kk(['store', 'extract', '--topic', topic, '--window', label, '--out', attempt]);
453
647
  const parsed = readJson(attempt);
454
648
  const docs = Array.isArray(parsed) ? (parsed as unknown[]) : [];
455
- const estimate = estimateSpokenMinutes(docs, vdriver);
649
+ const estimate = estimateSpokenMinutes(docs, vdriver, ratio.ratio);
650
+ const clears = estimate.seconds >= floor * 60;
651
+ rungs.push({ window: label, items: docs.length, chars: estimate.chars, minutes: estimate.minutes, clears });
456
652
  chosen = { window: label, docs };
457
653
  const verdict = gated
458
- ? `estimated ${estimate.minutes} min — ${estimate.seconds >= floor * 60 ? 'clears' : 'below'} the ${floor} min floor`
654
+ ? `estimated ${estimate.minutes} min at ${ratio.ratio.toFixed(2)}x — ${clears ? 'clears' : 'below'} the ${floor} min floor`
459
655
  : 'floor gate off';
460
656
  console.error(`extract: ${label} pool ${docs.length} item(s), ${verdict}`);
461
- if (!gated || estimate.seconds >= floor * 60) break;
657
+ if (!gated || clears) break;
462
658
  rmSync(attempt, { force: true });
463
659
  }
464
660
  const picked = chosen ?? { window: formatWindowMs(base), docs: [] as unknown[] };
661
+ // 0377 R3: the decision is an artifact, not just a stderr line — the run report and
662
+ // `kk news status` read which measure drove it, the rung chosen and the estimate at each rung.
663
+ sted('write', join(workDir, '10-collect', 'ladder.json'), () =>
664
+ writeJsonText(join(workDir, '10-collect', 'ladder.json'), {
665
+ floorMinutes: gated ? floor : null,
666
+ ratioUsed: ratio.ratio,
667
+ ratioSource: ratio.source,
668
+ chosen: picked.window,
669
+ rungs,
670
+ }),
671
+ );
465
672
  sted('write', poolPath, () => writeJsonText(poolPath, picked.docs));
466
673
  for (const ms of windows)
467
674
  rmSync(join(workDir, '10-collect', `.pool-${formatWindowMs(ms)}.json`), { force: true });
@@ -1072,6 +1279,9 @@ export function dailyGenerate(args: string[]): void {
1072
1279
  );
1073
1280
  const charRate = scriptFloorCharRate(vdriver);
1074
1281
  const seconds = 8 + chars / charRate;
1282
+ // Record what the writer delivered before judging it: a refused day still teaches the
1283
+ // next run's ladder what this pool really yielded (0377 R2/R3).
1284
+ recordSpokenRatio(workDir, runDate, chars);
1075
1285
  if (seconds < minMinutes * 60) {
1076
1286
  refuseScriptBelowFloor(workDir, runDate, { chars, charRate, seconds, minMinutes });
1077
1287
  return;
@@ -1954,6 +2164,8 @@ const SOCIAL_LIMITS: Record<string, SocialLimit> = {
1954
2164
  x: { max: 280, weighted: true },
1955
2165
  weibo: { max: 2000 },
1956
2166
  threads: { max: 500 },
2167
+ // 即刻's 动态 composer accepts long text; the shared short notice fits far below this.
2168
+ jike: { max: 2000 },
1957
2169
  linkedin: { max: 3000 },
1958
2170
  };
1959
2171
 
@@ -2007,11 +2219,22 @@ export function dailyBundleVariants(args: string[]): void {
2007
2219
 
2008
2220
  // Generic variants first: a channel-specific variant wins over the shared one, so the
2009
2221
  // shared copy must exist for the channels the preset does not specialise.
2222
+ const firstArticleLine =
2223
+ article !== null && typeof (article as Record<string, unknown>).title === 'string'
2224
+ ? String((article as Record<string, unknown>).title)
2225
+ : '';
2010
2226
  if (article === null) skipped.push('article (no 22-article content)');
2011
2227
  else {
2012
2228
  write('article', buildSurfdashContent(article, links, { coverPath: cover }));
2013
2229
  write('article@surfdash-pub', buildSurfdashContent(article, links, { coverPath: cover }));
2014
2230
  write('article@xhs-pub', buildXhsArticleContent(article, { publishStatus: 'draft' }));
2231
+ // The article carries the episode audio at the top (operator request 2026-11-15): the
2232
+ // 公众号 播客 row is off, so without this the MP draft had no player at all. Same source
2233
+ // as the episode variant — `publish-prep`'s rendered mp3 — so one episode has one audio.
2234
+ const articleAudio =
2235
+ prep !== null && typeof metadataOf(prep).audioFile === 'string'
2236
+ ? String(metadataOf(prep).audioFile)
2237
+ : undefined;
2015
2238
  write(
2016
2239
  'article@wechatmp-pub',
2017
2240
  buildWechatArticleContent(article, {
@@ -2019,6 +2242,7 @@ export function dailyBundleVariants(args: string[]): void {
2019
2242
  publishStatus: 'draft',
2020
2243
  collection: '每日AI资讯',
2021
2244
  ...(cover === undefined ? {} : { coverPath: cover }),
2245
+ ...(articleAudio === undefined ? {} : { audioPath: articleAudio, audioTitle: firstArticleLine }),
2022
2246
  }),
2023
2247
  );
2024
2248
  }
@@ -4381,7 +4605,7 @@ const EDITORIAL_ARTICLE_OPENING = '这里是由Robin为你带来的咸话咸说
4381
4605
  * 1. `22-article/<date>_06_article-write_body.md`
4382
4606
  * 2. `23-cover/<date>_07_cover-brief.json`
4383
4607
  * 3. `25-xhs/<date>_18_xhs_plan.json` (only when `cards_enabled === 'true'`)
4384
- * 4. `26-social/{x,threads}.md` (`social.short`)
4608
+ * 4. `26-social/{x,threads,jike}.md` (`social.short`)
4385
4609
  * 5. `26-social/{weibo,linkedin}.md` (`social.long`)
4386
4610
  * Missing master field -> skip that one artifact with a logged reason, write the others.
4387
4611
  */
@@ -4589,11 +4813,11 @@ export function dailyEditorialRender(args: string[]): void {
4589
4813
  const socialDir = join(workDir, '26-social');
4590
4814
  if (socialShort !== '') {
4591
4815
  sted('mkdir', socialDir, () => mkdirSync(socialDir, { recursive: true }));
4592
- for (const name of ['x.md', 'threads.md', 'weibo.md']) {
4816
+ for (const name of ['x.md', 'threads.md', 'weibo.md', 'jike.md']) {
4593
4817
  const out = join(socialDir, name);
4594
4818
  sted('write', out, () => writeRaw(out, `${socialShort}\n`));
4595
4819
  }
4596
- console.log('editorial-render: wrote 26-social/{x,threads,weibo}.md');
4820
+ console.log('editorial-render: wrote 26-social/{x,threads,weibo,jike}.md');
4597
4821
  } else if (socialLong !== '') {
4598
4822
  sted('mkdir', socialDir, () => mkdirSync(socialDir, { recursive: true }));
4599
4823
  const out = join(socialDir, 'weibo.md');
@@ -69,9 +69,13 @@ Sequence: **resolve preferences** (Preference chain) → **resolve the format**
69
69
  - `illustration` — detect insertion positions and author captions per
70
70
  [references/illustration-positions.md](references/illustration-positions.md);
71
71
  the chosen anchors cross as `metadata.positions`, one image per anchor.
72
- 3. Resolve the style: `--style`, else the preference `image.style`, else the format's
73
- `defaultStyle`. Without an explicit choice the skill may propose an auto-detected
74
- style — taste, this skill's — shown in the preview for approval.
72
+ 3. Resolve the visual direction before locking the style: `--style`, else the preference `image.style`, else the format's
73
+ `defaultStyle`. Use each preset's `description` and `bestFor` as routing evidence. If the direction is unclear,
74
+ offer **two or three visibly different styles** with one-sentence tradeoffs — do not force a weak third — and wait
75
+ for the user's choice before writing a long prompt. Commit to **one primary style**; never blend style presets or
76
+ mixed reference bundles automatically. Explicit user constraints (subject, aspect ratio, text, people, brand,
77
+ forbidden content) override preset defaults. When the direction is clear or the user delegates the choice, the
78
+ skill may auto-detect one style — taste, this skill's — shown in the preview for approval.
75
79
  4. Resolve the provider and model per Preference chain; the credential and
76
80
  reference-image facts per provider live in
77
81
  [references/providers.md](references/providers.md).
@@ -18,6 +18,32 @@ are read by `invoke.ts` at spawn, never by this skill.
18
18
  `--provider` outranks it.
19
19
  - **`codex-cli` is never auto-selected.** Its readiness (the `codex` CLI on
20
20
  PATH with an active login) is not env-expressible; pin it explicitly.
21
+ - **`h3-local` is never auto-selected either.** It drives Robin's local Apple
22
+ Silicon MLX runtime through `h3gen.sh`, and one render costs minutes of wall
23
+ time (3 min floor, ~7 min for 1024², up to ~28 min for a two-reference edit).
24
+ Pin it with `--provider h3-local`; the cloud defaults stay until the K2
25
+ rollout gates pass. H3 has no native negative-prompt parameter, so a style's
26
+ `negative` travels as the composed `avoid: …` segment like every other
27
+ provider; seeds cannot be set (the wrapper's default 42 applies); and only
28
+ multiples of 32 in 256–4096 are accepted per edge — every other preset falls
29
+ back to an aspect-only canvas (0379).
30
+ - **Running or verifying it locally.** `H3_IMAGE_MLX_BIN` can live in
31
+ `plugins.generations.image-gen.env` in `~/.config/kk/config.yaml`, so no shell
32
+ export is needed. `KK_IMAGE_DRY_RUN=1` proves prompt composition and provider
33
+ selection in about a second; one real `free` render is ~6 min because model
34
+ load dominates (a smaller canvas saves nothing). `scripts/gen-samples.ts` and
35
+ `scripts/eval-style-presets.ts` both accept `--provider h3-local` (the model
36
+ defaults to `h3`) and need `--concurrency 1` — three concurrent model loads
37
+ thrash a 16 GB machine. A reference edit costs ~28 min: never use one as a
38
+ smoke test.
39
+ - **H3 paints prompt tags as text unless the style declares a `negative`.** Same
40
+ subject, canvas and format at 1024²: with `editorial` (no `negative`) the model
41
+ rendered "8K, high-quality, masterpiece…" as gibberish lettering in the frame;
42
+ with `daily-news` (whose `avoid: text, letters, words, …` segment K3 now
43
+ appends) the identical request came back clean. When rendering locally, use a
44
+ style that declares `negative` (`daily-news`, `quasi-news-podcast`,
45
+ `xhs-knowledge`, `clean-webapp-ui`) or add one — never compare a local sample
46
+ against a cloud one from a style that leaves text unconstrained.
21
47
  - **Reference images** ride `--ref` only when `supportsReferenceImages(model)`
22
48
  is true for the resolved model — a substring test over the registry's
23
49
  `refModels` fragments (no `refModels` = every model; empty list = none).
@@ -33,6 +59,7 @@ are read by `invoke.ts` at spawn, never by this skill.
33
59
  | codex-cli | not env-expressible — `codex` CLI + login | `codex-image-gen` | never auto-selected |
34
60
  | dashscope | `DASHSCOPE_API_KEY` | `qwen-image-2.0-pro` | only `wan2.7` models |
35
61
  | google | `GOOGLE_API_KEY` or `GEMINI_API_KEY` | `gemini-3-pro-image` | the gemini image models (`gemini-3-pro-image`, `*-flash-image`, previews) |
62
+ | h3-local | `H3_IMAGE_MLX_BIN` (path to the local `h3gen.sh`) | `h3` | yes (up to 16, `<Picture N>` in prompt order) — never auto-selected |
36
63
  | jimeng | `JIMENG_ACCESS_KEY_ID` **and** `JIMENG_SECRET_ACCESS_KEY` (both halves) | `jimeng_t2i_v40` | yes |
37
64
  | minimax | `MINIMAX_API_KEY` | `image-01` | yes (jpg/png <10MB, subject reference) |
38
65
  | openai | `OPENAI_API_KEY` | `gpt-image-2` | `gpt-image` models |
@@ -52,7 +52,7 @@ enhancement.** Field-by-field:
52
52
  | `typography` | no | Only when the image evidences it. Omit rather than guess. |
53
53
  | `visualElements` | no | Array of strings naming recurring visual devices (borders, banding, grain, iconography). Only what the image shows. |
54
54
  | `bestFor` | no | The content types this look suits. Inferred from the image's own subject matter. |
55
- | `negative` | no | What this look must avoid — inferred from what is conspicuously absent. |
55
+ | `negative` | no | What this look must avoid — inferred from what is conspicuously absent. Rendered as one `avoid: …` segment after `modifiers` in the composed provider prompt (K3). |
56
56
  | `source` | yes for extraction | `kind: extracted`, `refImages` = the absolute input paths **in the order given**, `extractedAt` = ISO-8601 timestamp, `confidence` = the judgement below. |
57
57
 
58
58
  ### The `confidence` decision rule (human-judged, not computed)
@@ -108,3 +108,14 @@ the confirmed live status; otherwise fail naming the switch.
108
108
  | weibo-pub | none — its session lives in the browser profile (`WEIBO_PROFILE_DIR` overrides the dir; tier: `--profile` > `WEIBO_PROFILE_DIR` > `KK_BROWSER_PROFILE_DIR` > `~/.config/kk/browser-profiles/weibo`) |
109
109
 
110
110
  Missing env → plugin exit 1, `Result.ok false`, error names the variable.
111
+
112
+ ## Authoring or repairing a browser rail
113
+
114
+ Do not guess a selector. A browser rail (`plugins/publishings/<plugin>/src/*rail*.ts`,
115
+ `*flow*.ts`) is measured: `kk bot record <bot>` → `kk bot replay <bot> <transcript>` →
116
+ `kk bot codegen <transcript> --plugin <plugin> --operation <op>`, then promote by hand. The receipt
117
+ must come from the recorded submit response, and the rail carries a `// transcript:` header (the
118
+ `rail-transcript-header` rule enforces it). The playbook is
119
+ `plugins/kk/skills/web-automation/SKILL.md` § Scenario E; the contract is
120
+ `docs/design/kk-bot-record-codegen.md`. This skill stays transport-free — it shells these verbs, it
121
+ does not own them.
@@ -23,7 +23,7 @@ and never report an outcome that was not observed.
23
23
  | Operation | When | Tier & Substrate | Output |
24
24
  | --- | --- | --- | --- |
25
25
  | **discover** | New/changed site; "figure out this UI", inspect selectors/shadow roots | **Tier 3** (`kk bot open` + CDP/Playwright) | Evidence dir (`frames/`, `signals.json`) + drift list (`docs/design/<channel>-ui-discovery.md`) |
26
- | **enhance** | Selectors drifted; a plugin or collection plan fails on a live console | **Tier 2 / 3** (`kk bot exec`, probe script) | Root-cause fix in plugin + updated discovery doc in same commit |
26
+ | **enhance** | Selectors drifted; a plugin or collection plan fails on a live console | **Tier 2 / 3** (`kk bot exec`, `kk bot record`/`replay`, probe script) | Root-cause fix in plugin + updated discovery doc in same commit; a rail change names its transcript |
27
27
  | **automate** | Repeatable web task (data collection, form fill, draft save, health audit) | **Tier 1 / 2** (`kk bot exec`, `runBotCollection`) | Bounded Result + captured artifacts (draft-safe by default, fail-closed) |
28
28
 
29
29
  This skill owns **method**. It does not own transport (that belongs to `kind: publish` / `ingestion` plugins) or orchestration
@@ -239,6 +239,36 @@ await withProfileLease(profileName, async () => {
239
239
  3. If selector changed, launch `kk bot open <channel>`, observe the updated DOM element.
240
240
  4. Update selector in shared helper, re-verify with probe script, commit alongside discovery doc.
241
241
 
242
+ ### Scenario E: Measured Rail Authoring — record → replay → codegen (`enhance`)
243
+ A rail whose selectors were guessed is a rail that will fail live. Measure the session instead.
244
+
245
+ 1. **Record** — `kk bot record <bot> -o <file>` opens the bot's saved page headed. Perform the flow
246
+ by hand *up to but not including* the final submit (the transcript is evidence, not a publish).
247
+ Close the window to finish. Typed text is a length marker unless `--include-text`; the transcript
248
+ is 0600 and its URL queries are dropped.
249
+ 2. **Read the recording, not the prose** — each step carries a ranked selector
250
+ (`data-testid` > `name` > exact `aria-label` > `role`+exact text > exact text > structural path) or
251
+ an explicit `ambiguous` marker. An `ambiguous` step is a real finding: the site has two visible
252
+ nodes with that attribute, so the flow needs a stronger landmark — re-record after the console is
253
+ in the right state.
254
+ 3. **Replay before generating** — `kk bot replay <bot> <transcript>` stops before the submit click
255
+ unless `--submit`, and writes one screenshot plus a `replay.json` row per step. A step that does
256
+ not resolve exactly one visible node fails the run: fix the recording, not the assertion. Cite
257
+ `.spur/run/bot-replay-<bot>/` as evidence in the repair task.
258
+ 4. **Generate** — `kk bot codegen <transcript> --plugin <name> --operation <op>` prints a rail
259
+ skeleton; `--apply` writes `<op>-rail.generated.ts` beside the plugin. The receipt is a
260
+ `page.waitForResponse` matcher over the recorded submit response with the id's dot path — never a
261
+ DOM-text comparison. No response in the transcript ⇒ an explicit `TODO receipt` warning, because a
262
+ rail with no receipt reports a publish it cannot prove.
263
+ 5. **Promote by hand** — read the generated file against the recording, then move what you accept into
264
+ the live rail. Never ship the generated file as the live rail.
265
+ 6. **Name the recording** — the live rail keeps a `// transcript: <repo path>` (or
266
+ `// transcript: none — <reason>`) header; the `rail-transcript-header` rule fails the tree without
267
+ it. Fixtures for offline tests live under
268
+ `packages/publish-harness/tests/fixtures/bot-record/`.
269
+
270
+ Contract detail: `docs/design/kk-bot-record-codegen.md`.
271
+
242
272
  ---
243
273
 
244
274
  ## Safety Rails (Non-Negotiable)
@@ -71,12 +71,16 @@ states:
71
71
  - kind: shell
72
72
  options:
73
73
  # The claim is re-entrant for the same run and is stolen once its TTL has
74
- # passed, so a crashed holder costs at most one tick (the TTL below covers the
75
- # 6 h cadence and every plausible collect duration, so a slow run is never overtaken). stdout
76
- # IS the lock contract, and the guard below reads it back:
74
+ # passed. The TTL must stay BELOW the 6 h tick cadence (incident 2026-11-15): a run
75
+ # killed between `lock` and `release` — a `spur serve` restart aborts the tick in the
76
+ # queue, so `release-failed` never runs — leaves its claim behind, and a cadence-sized
77
+ # TTL made the very next tick skip instead of steal: the 16:05 tick was killed at
78
+ # 16:16 and the 22:05 tick reported `{"skipped":"locked"}`, costing 12 h of collection
79
+ # instead of one tick. 4 h is still ~20x the observed collect (12-15 min), so a live run
80
+ # is never overtaken. stdout IS the lock contract, and the guard below reads it back:
77
81
  # `{"acquired":true}` or `{"skipped":"locked","holder":<run>}` (R1).
78
82
  command: >-
79
- kk lock acquire --name collect --run "${vars.__runId}" --ttl 21600000 > "${vars.work_dir}/lock.json"
83
+ kk lock acquire --name collect --run "${vars.__runId}" --ttl 14400000 > "${vars.work_dir}/lock.json"
80
84
 
81
85
  - id: collect
82
86
  description: >-
@@ -70,7 +70,8 @@ vars:
70
70
  xhs_cards: "4"
71
71
  xhs_style: "xhs-knowledge"
72
72
  # Same credential surface as the cover pin: the provider/model must be one this machine can
73
- # actually reach, and each provider renders its own look.
73
+ # actually reach, and each provider renders its own look. This retired workflow stays frozen;
74
+ # the 0379 H3 XHS opt-in lives in kk-daily-ai-voice2 and the consolidated kk news config.
74
75
  xhs_provider: "minimax"
75
76
  xhs_model: "image-01"
76
77
  # ADR-022 rail: draft-box only. "true" posts live and stays a launch-time opt-in.
@@ -55,8 +55,10 @@ vars:
55
55
  xhs_enabled: "true"
56
56
  xhs_cards: "4"
57
57
  xhs_style: "xhs-knowledge"
58
- xhs_provider: "minimax"
59
- xhs_model: "image-01"
58
+ # 0379 K2: the local text-free/composition rehearsal passed; H3 remains an explicit XHS opt-in.
59
+ # Rollback: xhs_provider=minimax, xhs_model=image-01. The cover pin above is unchanged.
60
+ xhs_provider: "h3-local"
61
+ xhs_model: "h3"
60
62
  # ADR-022 rail: draft-box only. "true" posts live and stays a launch-time opt-in.
61
63
  xhs_live: "false"
62
64
  wechat_enabled: "true"
@@ -20997,10 +20997,30 @@ var MAX_TEXT_CHARS = 3000;
20997
20997
  var MAX_IMAGES = 1;
20998
20998
  var IMAGE_EXTS = new Set([".png", ".jpg", ".jpeg", ".webp", ".gif"]);
20999
20999
  var LINKEDIN_POST_SELECTORS = {
21000
- shareTrigger: ["button.share-box-feed-entry__trigger", 'button[aria-label*="Start a post" i]'],
21001
- composer: ['div.editor-content[contenteditable="true"]', 'div[role="textbox"][contenteditable="true"]'],
21002
- fileInput: ['[role="dialog"] input[type="file"]'],
21003
- send: ['[role="dialog"] button.share-actions__primary-action', '[role="dialog"] button:has-text("Post")']
21000
+ shareTrigger: [
21001
+ 'text="Start a post"',
21002
+ "button.share-box-feed-entry__trigger",
21003
+ 'button[aria-label*="Start a post" i]'
21004
+ ],
21005
+ composer: [
21006
+ '.tiptap.ProseMirror div[role="textbox"]',
21007
+ 'div[role="textbox"].tiptap',
21008
+ ".tiptap.ProseMirror",
21009
+ '[role="dialog"] div[role="textbox"]',
21010
+ 'div.editor-content[contenteditable="true"]',
21011
+ 'div[role="textbox"][contenteditable="true"]'
21012
+ ],
21013
+ mediaButton: [
21014
+ 'button[aria-label="Media"]',
21015
+ 'button[aria-label*="Media" i]',
21016
+ '[role="dialog"] button[aria-label*="Media" i]'
21017
+ ],
21018
+ fileInput: ['input[type="file"][accept*="image"]', 'input[type="file"]', '[role="dialog"] input[type="file"]'],
21019
+ send: [
21020
+ 'button:text-is("Post")',
21021
+ '[role="dialog"] button:text-is("Post")',
21022
+ '[role="dialog"] button.share-actions__primary-action'
21023
+ ]
21004
21024
  };
21005
21025
  var FAILURE_TOAST_RE = /post failed|couldn't post|something went wrong/i;
21006
21026
  var SUCCESS_TOAST_RE = /post successful/i;
@@ -21059,7 +21079,14 @@ function resolveDriver(options) {
21059
21079
  var isLinkedinAuthenticated = async (page) => {
21060
21080
  if (LINKEDIN_LOGIN_URL_RE.test(page.url()))
21061
21081
  return false;
21062
- return (await trySelectors(page, LINKEDIN_POST_SELECTORS.shareTrigger, { visible: false })).found;
21082
+ if ((await trySelectors(page, LINKEDIN_POST_SELECTORS.shareTrigger.slice(1), { visible: false })).found) {
21083
+ return true;
21084
+ }
21085
+ try {
21086
+ return await page.getByText("Start a post", { exact: true }).count() > 0;
21087
+ } catch {
21088
+ return false;
21089
+ }
21063
21090
  };
21064
21091
  var LINKEDIN_CONFIG = {
21065
21092
  channel: TARGET,
@@ -21175,7 +21202,13 @@ class LinkedinBrowserTransport {
21175
21202
  } catch {
21176
21203
  return stageFail(`linkedin composer did not open after the share box (selector drift) \u2014 run: ${LINKEDIN_LOGIN_INSTRUCTION}`, "composer", metadata);
21177
21204
  }
21178
- await page.locator(composerSelector).first().fill(text);
21205
+ const composer = page.locator(composerSelector).first();
21206
+ if (typeof composer.pressSequentially === "function") {
21207
+ await composer.click();
21208
+ await composer.pressSequentially(text, { delay: 3 });
21209
+ } else {
21210
+ await composer.fill(text);
21211
+ }
21179
21212
  const readback = await this.requireReadback(page, composerSelector, text);
21180
21213
  if (!readback.ok)
21181
21214
  return stageFail(readback.error, "text-readback", metadata);
@@ -21229,6 +21262,10 @@ class LinkedinBrowserTransport {
21229
21262
  }
21230
21263
  async uploadImage(page, image) {
21231
21264
  try {
21265
+ const media = await trySelectors(page, LINKEDIN_POST_SELECTORS.mediaButton);
21266
+ if (media.found) {
21267
+ await page.locator(media.selector ?? LINKEDIN_POST_SELECTORS.mediaButton[0]).first().click();
21268
+ }
21232
21269
  const inputSelector = await resolveSelector(page, LINKEDIN_POST_SELECTORS.fileInput, {
21233
21270
  timeoutMs: this.stepTimeoutMs,
21234
21271
  label: "linkedin file input"