@gobing-ai/knowledge-kit 0.1.24 → 0.1.27
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.
- package/.claude-plugin/marketplace.json +1 -1
- package/dist/index.js +416 -79
- package/package.json +1 -1
- package/plugins/generations/episode-plan-gen/dist/index.js +47 -6
- package/plugins/generations/episode-plan-gen/src/index.ts +71 -7
- package/plugins/generations/music-gen/dist/index.js +17 -13
- package/plugins/generations/music-gen/src/audio/measure.ts +25 -20
- package/plugins/kk/decisions/extract/ai-news.yaml +8 -1
- package/plugins/kk/plugin.json +1 -1
- package/plugins/kk/publish-presets/daily-ai-voice.json +4 -4
- package/plugins/kk/publish-presets/itc-main.json +39 -23
- package/plugins/kk/scripts/cn-lead-gate.ts +494 -0
- package/plugins/kk/scripts/daily-stages.ts +880 -131
- package/plugins/kk/scripts/kk-workflow-stages.ts +58 -3
- package/plugins/kk/skills/content-safety/references/platforms/apple-podcasts.md +12 -5
- package/plugins/kk/skills/content-safety/references/platforms/wechatmp.md +8 -0
- package/plugins/kk/skills/content-safety/references/platforms/xiaoyuzhou.md +5 -0
- package/plugins/kk/skills/daily-news-cover/SKILL.md +96 -0
- package/plugins/kk/skills/daily-news-illustrations/SKILL.md +123 -0
- package/plugins/kk/skills/news-editorial/SKILL.md +25 -6
- package/plugins/kk/skills/news-editorial/references/daily-visual-composition.md +150 -0
- package/plugins/kk/skills/news-editorial/references/selection.md +42 -0
- package/plugins/kk/skills/news-editorial/references/style-contract.zh.md +1 -1
- package/plugins/kk/workflows/kk-article-generate.yaml +13 -1
- package/plugins/kk/workflows/kk-daily-ai-voice.yaml +6 -3
- package/plugins/kk/workflows/kk-daily-ai-voice2.yaml +6 -4
- package/plugins/kk/workflows/kk-news-generate.yaml +71 -1
- package/plugins/publishings/bilibili-pub/dist/index.js +35 -3
- package/plugins/publishings/bilibili-pub/dist/profile-check.js +35 -3
- package/plugins/publishings/cnblogs-pub/dist/index.js +35 -3
- package/plugins/publishings/cnblogs-pub/dist/profile-check.js +35 -3
- package/plugins/publishings/csdn-pub/dist/index.js +35 -3
- package/plugins/publishings/csdn-pub/dist/profile-check.js +35 -3
- package/plugins/publishings/infoq-pub/dist/index.js +35 -3
- package/plugins/publishings/infoq-pub/dist/profile-check.js +35 -3
- package/plugins/publishings/jike-pub/dist/index.js +35 -3
- package/plugins/publishings/jike-pub/dist/profile-check.js +35 -3
- package/plugins/publishings/juejin-pub/dist/index.js +35 -3
- package/plugins/publishings/juejin-pub/dist/profile-check.js +35 -3
- package/plugins/publishings/linkedin-pub/dist/index.js +86 -14
- package/plugins/publishings/linkedin-pub/dist/profile-check.js +52 -6
- package/plugins/publishings/linkedin-pub/src/index.ts +126 -9
- package/plugins/publishings/medium-pub/dist/index.js +9229 -279
- package/plugins/publishings/medium-pub/dist/profile-check.js +21205 -0
- package/plugins/publishings/medium-pub/package.json +3 -1
- package/plugins/publishings/medium-pub/plugin.json +6 -1
- package/plugins/publishings/medium-pub/src/browser-rail.ts +280 -0
- package/plugins/publishings/medium-pub/src/index.ts +17 -1
- package/plugins/publishings/medium-pub/src/profile-check.ts +27 -0
- package/plugins/publishings/shipinhao-pub/dist/index.js +38 -4
- package/plugins/publishings/shipinhao-pub/dist/profile-check.js +37 -4
- package/plugins/publishings/shipinhao-pub/src/flow.ts +5 -0
- package/plugins/publishings/shipinhao-pub/src/selectors.ts +11 -4
- package/plugins/publishings/sspai-pub/dist/index.js +35 -3
- package/plugins/publishings/sspai-pub/dist/profile-check.js +35 -3
- package/plugins/publishings/substack-pub/dist/index.js +35 -3
- package/plugins/publishings/substack-pub/dist/profile-check.js +35 -3
- package/plugins/publishings/surfdash-pub/dist/index.js +53 -15
- package/plugins/publishings/surfdash-pub/src/index.ts +31 -4
- package/plugins/publishings/surfdash-pub/src/patch.ts +81 -12
- package/plugins/publishings/threads-pub/dist/index.js +35 -3
- package/plugins/publishings/threads-pub/dist/profile-check.js +35 -3
- package/plugins/publishings/wechatmp-pub/dist/index.js +326 -44
- package/plugins/publishings/wechatmp-pub/dist/profile-check.js +69 -4
- package/plugins/publishings/wechatmp-pub/src/flow.ts +447 -53
- package/plugins/publishings/wechatmp-pub/src/index.ts +68 -2
- package/plugins/publishings/wechatmp-pub/src/page.ts +8 -0
- package/plugins/publishings/weibo-pub/dist/index.js +58 -9
- package/plugins/publishings/weibo-pub/dist/profile-check.js +57 -9
- package/plugins/publishings/weibo-pub/plugin.json +1 -1
- package/plugins/publishings/weibo-pub/src/index.ts +76 -8
- package/plugins/publishings/x-pub/dist/index.js +35 -3
- package/plugins/publishings/x-pub/dist/profile-check.js +35 -3
- package/plugins/publishings/xhs-pub/dist/index.js +35 -3
- package/plugins/publishings/xhs-pub/dist/profile-check.js +35 -3
- package/plugins/publishings/xiaoyuzhou-pub/dist/index.js +35 -3
- package/plugins/publishings/xiaoyuzhou-pub/dist/profile-check.js +35 -3
|
@@ -67,6 +67,7 @@ import {
|
|
|
67
67
|
writeFileSync,
|
|
68
68
|
} from 'node:fs';
|
|
69
69
|
import { basename, isAbsolute, join, resolve } from 'node:path';
|
|
70
|
+
import { checkCnLeadPlan, enforceCnLead } from './cn-lead-gate.ts';
|
|
70
71
|
import {
|
|
71
72
|
EPISODE_IDENTITY_KEY,
|
|
72
73
|
type EpisodeIdentity,
|
|
@@ -155,6 +156,19 @@ export function dailyQcContent(args: string[]): void {
|
|
|
155
156
|
const exclusions = join(workDir, '21-plan', `${runDate}_04_quality-control-content_exclusions.json`);
|
|
156
157
|
const planContent = join(workDir, '21-plan', `${runDate}_03_plan_content.json`);
|
|
157
158
|
const cachePath = `${candidates}.cache.json`;
|
|
159
|
+
const floorMinutes = Number(minMinutes);
|
|
160
|
+
const qcMinChars =
|
|
161
|
+
minMinutes !== '' && Number.isFinite(floorMinutes) && floorMinutes > 0
|
|
162
|
+
? String(
|
|
163
|
+
Math.max(
|
|
164
|
+
0,
|
|
165
|
+
Math.ceil(
|
|
166
|
+
((floorMinutes * 60 - 8) * spokenCharRate(vdriver)) /
|
|
167
|
+
readSpokenCalibration(workDir).keptRatio,
|
|
168
|
+
),
|
|
169
|
+
),
|
|
170
|
+
)
|
|
171
|
+
: '';
|
|
158
172
|
const fingerprint = stageCacheFingerprint(planContent, {
|
|
159
173
|
qcCategories,
|
|
160
174
|
minQuality,
|
|
@@ -164,6 +178,7 @@ export function dailyQcContent(args: string[]): void {
|
|
|
164
178
|
minEpisodeItems,
|
|
165
179
|
minMinutes,
|
|
166
180
|
vdriver,
|
|
181
|
+
qcMinChars,
|
|
167
182
|
});
|
|
168
183
|
let recomputed = false;
|
|
169
184
|
timed(workDir, 'quality-control-content', () => {
|
|
@@ -211,6 +226,7 @@ export function dailyQcContent(args: string[]): void {
|
|
|
211
226
|
QC_MIN_URGENCY: minUrgency,
|
|
212
227
|
QC_MIN_IMPACT: minImpact,
|
|
213
228
|
QC_MIN_EPISODE_ITEMS: minEpisodeItems,
|
|
229
|
+
...(qcMinChars ? { QC_MIN_CHARS: qcMinChars } : {}),
|
|
214
230
|
},
|
|
215
231
|
},
|
|
216
232
|
);
|
|
@@ -372,121 +388,280 @@ const SPEAK_CHAR_EXPANSION = 1.4;
|
|
|
372
388
|
* (0377).
|
|
373
389
|
*
|
|
374
390
|
* This constant is only the fallback: both gates prefer the ratio a previous run recorded, and the
|
|
375
|
-
* two records carry DIFFERENT denominators (see `
|
|
376
|
-
* 2026-11-16 refusal of a 23-min episode).
|
|
391
|
+
* two records carry DIFFERENT denominators (see `readSpokenCalibration` — using one ratio for both
|
|
392
|
+
* was the 2026-11-16 refusal of a 23-min episode).
|
|
377
393
|
*/
|
|
378
394
|
const SPEAK_CHAR_EXPANSION_FLOOR = 0.28;
|
|
379
395
|
|
|
380
396
|
/**
|
|
381
|
-
* Where a run records the
|
|
382
|
-
* two pre-spend consumers measure different sets
|
|
383
|
-
*
|
|
384
|
-
*
|
|
385
|
-
* directories, so they judge today's material
|
|
386
|
-
* of a constant that was calibrated once.
|
|
397
|
+
* Where a run records the measures it actually delivered (0377 R2/R3, extended by 0434). Three
|
|
398
|
+
* numbers, because the two pre-spend consumers measure different sets and the ladder has to bridge
|
|
399
|
+
* them: `ratio` is spoken/pool, `keptRatio` is spoken/kept-candidate chars (the floor gate's
|
|
400
|
+
* denominator), and `keepRate` is kept/pool — the admission rate that converts one into the other.
|
|
401
|
+
* The gates read the newest record from the sibling run directories, so they judge today's material
|
|
402
|
+
* by what the writer really produced last time instead of a constant that was calibrated once.
|
|
387
403
|
*/
|
|
388
404
|
const SPOKEN_RATIO_SUFFIX = '_09_spoken-ratio.json';
|
|
389
405
|
|
|
390
|
-
/**
|
|
391
|
-
|
|
392
|
-
|
|
406
|
+
/**
|
|
407
|
+
* The cold-start QC admission rate — kept-candidate chars over raw pool chars — the widen ladder
|
|
408
|
+
* projects with when no run has recorded one (0434).
|
|
409
|
+
*
|
|
410
|
+
* Measured: 2026-11-16 13,963/38,241 kept = 0.37, 2026-11-24 12,937/42,925 = 0.30. The LOW end, by
|
|
411
|
+
* the same "worst measured" argument the ratio constants make above: the ladder's cheap error is a
|
|
412
|
+
* rung too many, and its expensive one is an authoring pass the floor gate then refuses because the
|
|
413
|
+
* admitted set was never as large as the pool suggested.
|
|
414
|
+
*/
|
|
415
|
+
const KEEP_RATE_FLOOR = 0.3;
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* How far today's QC admission rate may move from the rate the estimate projected with before the
|
|
419
|
+
* run reports it (0434 R3). The 2026-11-24 run moved 22 points below its recorded day and nothing
|
|
420
|
+
* said so: the ladder's 22.8 min estimate was absorbed as if it were still calibrated.
|
|
421
|
+
*/
|
|
422
|
+
const KEEP_RATE_DRIFT_BOUND = 0.05;
|
|
423
|
+
|
|
424
|
+
/** One measured rate and where it came from — every artifact prints the pair (0434 R2). */
|
|
425
|
+
interface KeepRate {
|
|
426
|
+
rate: number;
|
|
393
427
|
source: string;
|
|
394
428
|
}
|
|
395
429
|
|
|
430
|
+
/**
|
|
431
|
+
* A run's recorded calibration, read in one scan: both denominators the gates multiply by, and the
|
|
432
|
+
* admission rate that converts a raw pool into the set the floor gate measures (0434 R1).
|
|
433
|
+
*
|
|
434
|
+
* `poolRatio` is spoken/raw pool chars, `keptRatio` is spoken/kept-candidate chars, and `keepRate` is
|
|
435
|
+
* kept-candidate/raw pool chars, so `poolRatio === keepRate × keptRatio` for a self-consistent
|
|
436
|
+
* record. The ladder projects `poolChars × keepRate` and multiplies by `keptRatio`; the floor gate
|
|
437
|
+
* multiplies the chars it actually sees by `keptRatio`. One arithmetic, one denominator.
|
|
438
|
+
*/
|
|
439
|
+
interface SpokenCalibration {
|
|
440
|
+
/** spoken / raw pool chars. */
|
|
441
|
+
poolRatio: number;
|
|
442
|
+
/** spoken / kept-candidate chars — what every kept-set estimate multiplies by. */
|
|
443
|
+
keptRatio: number;
|
|
444
|
+
/** kept-candidate chars / raw pool chars. */
|
|
445
|
+
keepRate: number;
|
|
446
|
+
poolRatioSource: string;
|
|
447
|
+
keptRatioSource: string;
|
|
448
|
+
keepRateSource: string;
|
|
449
|
+
}
|
|
450
|
+
|
|
396
451
|
/** Clamp a recorded ratio into a plausible band: a corrupt file must not freeze or flood the ladder. */
|
|
397
452
|
function clampRatio(value: number): number {
|
|
398
453
|
return Math.min(2, Math.max(0.05, value));
|
|
399
454
|
}
|
|
400
455
|
|
|
456
|
+
/** Clamp a recorded admission rate: zero admits nothing, and >1 is not an admission rate. */
|
|
457
|
+
function clampKeepRate(value: number): number {
|
|
458
|
+
return Math.min(1, Math.max(0.01, value));
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/** One recorded ratio file, parsed into the three measures the gates need. Null fields are absent. */
|
|
462
|
+
interface RatioRecord {
|
|
463
|
+
path: string;
|
|
464
|
+
at: number;
|
|
465
|
+
poolRatio: number | null;
|
|
466
|
+
keptRatio: number | null;
|
|
467
|
+
keepRate: number | null;
|
|
468
|
+
}
|
|
469
|
+
|
|
401
470
|
/**
|
|
402
|
-
* The newest recorded spoken
|
|
403
|
-
*
|
|
404
|
-
*
|
|
471
|
+
* The newest recorded spoken-ratio artifacts across this workflow's sibling run directories.
|
|
472
|
+
*
|
|
473
|
+
* One scan serves all three measures (0434): the two ratio readers it replaces used to walk the
|
|
474
|
+
* same directories separately with two different size guards, so a large workspace could calibrate
|
|
475
|
+
* the ladder from one run and the floor gate from another.
|
|
405
476
|
*/
|
|
406
|
-
function
|
|
477
|
+
function ratioRecords(workDir: string): RatioRecord[] {
|
|
478
|
+
// `workDir` is one run directory, so its parent is the workflow directory the siblings live in.
|
|
407
479
|
const base = resolve(workDir, '..');
|
|
408
|
-
let newest: { at: number; ratio: number; from: string } | null = null;
|
|
409
480
|
let entries: string[] = [];
|
|
410
481
|
try {
|
|
411
482
|
entries = readdirSync(base);
|
|
412
483
|
} catch {
|
|
413
|
-
return
|
|
484
|
+
return [];
|
|
414
485
|
}
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
486
|
+
const paths: string[] = [];
|
|
487
|
+
if (entries.length > 5_000) {
|
|
488
|
+
// A shared temp parent can hold hundreds of thousands of directories. Read names once and
|
|
489
|
+
// let native globbing skip the non-run ones instead of opening each in JS; the `kk-*` form
|
|
490
|
+
// measured ~2s on a 556k-entry parent while opening every entry took 20–40s per stage
|
|
491
|
+
// (2026-11-23). A bare `*` can hit broken symlinks, so the two run-shaped patterns are it.
|
|
492
|
+
for (const pattern of [`kk-*/21-plan/*${SPOKEN_RATIO_SUFFIX}`, `20??????/21-plan/*${SPOKEN_RATIO_SUFFIX}`]) {
|
|
493
|
+
try {
|
|
494
|
+
paths.push(...new Bun.Glob(pattern).scanSync({ cwd: base, onlyFiles: true, absolute: true }));
|
|
495
|
+
} catch {
|
|
496
|
+
// Best-effort calibration: a shared temp parent holds dangling symlinks and dirs that
|
|
497
|
+
// vanish mid-scan (ENOENT from the glob walk), which must never fail a stage.
|
|
498
|
+
}
|
|
422
499
|
}
|
|
423
|
-
|
|
424
|
-
|
|
500
|
+
} else {
|
|
501
|
+
for (const entry of entries) {
|
|
502
|
+
const dir = join(base, entry, '21-plan');
|
|
425
503
|
try {
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
504
|
+
paths.push(
|
|
505
|
+
...readdirSync(dir)
|
|
506
|
+
.filter((file) => file.endsWith(SPOKEN_RATIO_SUFFIX))
|
|
507
|
+
.map((file) => join(dir, file)),
|
|
508
|
+
);
|
|
431
509
|
} catch {
|
|
432
|
-
//
|
|
510
|
+
// Not every sibling is a run directory.
|
|
433
511
|
}
|
|
434
512
|
}
|
|
435
513
|
}
|
|
436
|
-
|
|
437
|
-
|
|
514
|
+
const records: RatioRecord[] = [];
|
|
515
|
+
for (const path of paths) {
|
|
516
|
+
try {
|
|
517
|
+
const parsed = readJson(path) as Record<string, unknown> | null;
|
|
518
|
+
if (parsed === null || typeof parsed !== 'object') continue;
|
|
519
|
+
const positive = (value: unknown): number | null => {
|
|
520
|
+
const number = Number(value);
|
|
521
|
+
return Number.isFinite(number) && number > 0 ? number : null;
|
|
522
|
+
};
|
|
523
|
+
const poolChars = positive(parsed.poolChars);
|
|
524
|
+
const keptChars = positive(parsed.keptChars);
|
|
525
|
+
const poolRatio = positive(parsed.ratio);
|
|
526
|
+
const keptRatio = positive(parsed.keptRatio);
|
|
527
|
+
records.push({
|
|
528
|
+
path,
|
|
529
|
+
at: statSync(path).mtimeMs,
|
|
530
|
+
poolRatio,
|
|
531
|
+
keptRatio,
|
|
532
|
+
keepRate: recordKeepRate(parsed, poolChars, keptChars, poolRatio, keptRatio),
|
|
533
|
+
});
|
|
534
|
+
} catch {
|
|
535
|
+
// A malformed record is not evidence; the next run overwrites it.
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
return records;
|
|
438
539
|
}
|
|
439
540
|
|
|
440
541
|
/**
|
|
441
|
-
* The
|
|
542
|
+
* The QC admission rate one record implies: kept/pool when both char counts were recorded, else the
|
|
543
|
+
* quotient of the two ratios (`spoken/pool ÷ spoken/kept`), else a rate a later writer stamped.
|
|
544
|
+
* A pre-2026-11-16 record carries only the pool ratio, so it yields no admission rate — which is
|
|
545
|
+
* exactly right: it never measured one (the double discount of 2026-11-16).
|
|
546
|
+
*/
|
|
547
|
+
function recordKeepRate(
|
|
548
|
+
parsed: Record<string, unknown>,
|
|
549
|
+
poolChars: number | null,
|
|
550
|
+
keptChars: number | null,
|
|
551
|
+
poolRatio: number | null,
|
|
552
|
+
keptRatio: number | null,
|
|
553
|
+
): number | null {
|
|
554
|
+
if (poolChars !== null && keptChars !== null) return clampKeepRate(keptChars / poolChars);
|
|
555
|
+
if (poolRatio !== null && keptRatio !== null) return clampKeepRate(poolRatio / keptRatio);
|
|
556
|
+
const stamped = Number(parsed.keepRate);
|
|
557
|
+
return Number.isFinite(stamped) && stamped > 0 ? clampKeepRate(stamped) : null;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
/**
|
|
561
|
+
* The calibration the pre-spend estimates use, each measure taken from the newest record that
|
|
562
|
+
* carries it and each falling back to its cold-start constant with a `default …` provenance.
|
|
442
563
|
*
|
|
443
|
-
* WHY
|
|
444
|
-
*
|
|
445
|
-
*
|
|
446
|
-
*
|
|
447
|
-
*
|
|
448
|
-
* the refusal discounted the planning shrink twice. `keptRatio` for that run is 0.515.
|
|
564
|
+
* WHY one record for all three (0434): the ladder and the floor gate must multiply the SAME
|
|
565
|
+
* denominator. A pool-denominated ratio applied to the admitted set discounted planning's shrink
|
|
566
|
+
* twice (2026-11-16: gate said 12.7 min, the writer delivered 23); a pool ratio the ladder reads
|
|
567
|
+
* alone is only the gate's arithmetic when today's admission rate matches the recorded day
|
|
568
|
+
* (2026-11-24: ladder 22.8 min, gate 13.1, delivered 12.6).
|
|
449
569
|
*/
|
|
450
|
-
function
|
|
451
|
-
const
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
570
|
+
function readSpokenCalibration(workDir: string): SpokenCalibration {
|
|
571
|
+
const records = ratioRecords(workDir);
|
|
572
|
+
/** The value and path of the newest record that measured `field`, or null when none did. */
|
|
573
|
+
const newestWith = (field: 'poolRatio' | 'keptRatio' | 'keepRate'): { value: number; path: string } | null => {
|
|
574
|
+
let newest: RatioRecord | null = null;
|
|
575
|
+
for (const record of records) {
|
|
576
|
+
if (record[field] === null) continue;
|
|
577
|
+
if (newest === null || record.at > newest.at) newest = record;
|
|
578
|
+
}
|
|
579
|
+
if (newest === null) return null;
|
|
580
|
+
const value = newest[field];
|
|
581
|
+
return value === null ? null : { value, path: newest.path };
|
|
582
|
+
};
|
|
583
|
+
const pool = newestWith('poolRatio');
|
|
584
|
+
const kept = newestWith('keptRatio');
|
|
585
|
+
const rate = newestWith('keepRate');
|
|
586
|
+
const fallback = SPEAK_CHAR_EXPANSION_FLOOR.toFixed(2);
|
|
587
|
+
return {
|
|
588
|
+
poolRatio: pool === null ? SPEAK_CHAR_EXPANSION_FLOOR : clampRatio(pool.value),
|
|
589
|
+
poolRatioSource:
|
|
590
|
+
pool === null ? `default ${fallback} (no recorded pool ratio)` : `${pool.path} (${pool.value.toFixed(2)}x)`,
|
|
591
|
+
keptRatio: kept === null ? SPEAK_CHAR_EXPANSION_FLOOR : clampRatio(kept.value),
|
|
592
|
+
keptRatioSource:
|
|
593
|
+
kept === null ? `default ${fallback} (no recorded kept ratio)` : `${kept.path} (${kept.value.toFixed(2)}x)`,
|
|
594
|
+
keepRate: rate === null ? KEEP_RATE_FLOOR : rate.value,
|
|
595
|
+
keepRateSource:
|
|
596
|
+
rate === null
|
|
597
|
+
? `default ${KEEP_RATE_FLOOR.toFixed(2)} (no recorded keep rate)`
|
|
598
|
+
: `${rate.path} (kept ${rate.value.toFixed(2)} of pool)`,
|
|
599
|
+
};
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
/**
|
|
603
|
+
* The keep rate the widen ladder projected today's admitted set from — the assumption every
|
|
604
|
+
* downstream estimate inherits. Read from the ladder artifact itself (what actually ran), falling
|
|
605
|
+
* back to the recorded calibration when the extract stage left no ladder behind.
|
|
606
|
+
*/
|
|
607
|
+
function assumedKeepRate(workDir: string, calibration: SpokenCalibration): KeepRate {
|
|
608
|
+
const ladder = readJson(join(workDir, '10-collect', 'ladder.json')) as Record<string, unknown> | null;
|
|
609
|
+
const rate = Number(ladder?.keepRate);
|
|
610
|
+
if (Number.isFinite(rate) && rate > 0) {
|
|
611
|
+
const source = typeof ladder?.keepRateSource === 'string' ? ladder.keepRateSource : 'ladder.json';
|
|
612
|
+
return { rate: clampKeepRate(rate), source };
|
|
458
613
|
}
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
614
|
+
return { rate: calibration.keepRate, source: calibration.keepRateSource };
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/**
|
|
618
|
+
* The admission rate this run achieved, measured from the pool it extracted and the set QC admitted
|
|
619
|
+
* — null when either artifact is missing (a workspace that never ran extract has no pool to divide).
|
|
620
|
+
*/
|
|
621
|
+
function observedKeepRate(workDir: string, keptChars: number): KeepRate | null {
|
|
622
|
+
const poolPath = join(workDir, '10-collect', 'pool.json');
|
|
623
|
+
if (!isFile(poolPath) || keptChars <= 0) return null;
|
|
624
|
+
const pool = readJson(poolPath);
|
|
625
|
+
const poolChars = rawChars(Array.isArray(pool) ? pool : []);
|
|
626
|
+
if (poolChars <= 0) return null;
|
|
627
|
+
return { rate: keptChars / poolChars, source: `${poolPath} (${keptChars} kept of ${poolChars})` };
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
/** A measured admission rate, the rate an estimate assumed, and how far apart they are (0434 R3). */
|
|
631
|
+
interface KeepRateDrift {
|
|
632
|
+
observed: KeepRate;
|
|
633
|
+
assumed: KeepRate;
|
|
634
|
+
/** observed − assumed: negative means QC admitted less than the estimate believed. */
|
|
635
|
+
delta: number;
|
|
636
|
+
beyondBound: boolean;
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
/**
|
|
640
|
+
* Compare the keep rate an estimate assumed against the one this run measured, and REPORT the
|
|
641
|
+
* difference beyond `KEEP_RATE_DRIFT_BOUND` instead of letting the estimate absorb it (0434 R3).
|
|
642
|
+
*
|
|
643
|
+
* A silently absorbed drift is what made the 2026-11-24 recovery decision impossible: 63 pool items
|
|
644
|
+
* forecast 22.8 min, the admitted 18 could make 13.1, and the run measured 12.6 — three numbers a
|
|
645
|
+
* human had to reconcile by hand.
|
|
646
|
+
*/
|
|
647
|
+
function keepRateDrift(assumed: KeepRate, observed: KeepRate | null, label: string): KeepRateDrift | null {
|
|
648
|
+
if (observed === null) return null;
|
|
649
|
+
const delta = observed.rate - assumed.rate;
|
|
650
|
+
const beyondBound = Math.abs(delta) > KEEP_RATE_DRIFT_BOUND;
|
|
651
|
+
if (beyondBound) {
|
|
652
|
+
const direction = delta < 0 ? 'over-predicts' : 'under-predicts';
|
|
653
|
+
console.error(
|
|
654
|
+
`keep rate drifted: QC admitted ${Math.round(observed.rate * 100)}% of the pool, the ${label} estimate assumed ${Math.round(assumed.rate * 100)}% (${assumed.source}) — the estimate ${direction} the episode by ~${Math.round((Math.abs(delta) / assumed.rate) * 100)}%; re-read it before trusting it`,
|
|
655
|
+
);
|
|
481
656
|
}
|
|
482
|
-
|
|
483
|
-
return { ratio: clampRatio(newest.ratio), source: `${newest.from} (${newest.ratio.toFixed(2)}x)` };
|
|
657
|
+
return { observed, assumed, delta, beyondBound };
|
|
484
658
|
}
|
|
485
659
|
|
|
486
660
|
/**
|
|
487
|
-
* Record what this run delivered — spoken script chars over raw pool chars,
|
|
488
|
-
* candidates — and warn when it drifted from the
|
|
489
|
-
* records too: a thin day teaches the ladder even though it
|
|
661
|
+
* Record what this run delivered — spoken script chars over raw pool chars, over the kept
|
|
662
|
+
* candidates, and the admission rate between them — and warn when it drifted from the estimate the
|
|
663
|
+
* widen decision used. A refused script records too: a thin day teaches the ladder even though it
|
|
664
|
+
* produced no episode.
|
|
490
665
|
*/
|
|
491
666
|
function recordSpokenRatio(workDir: string, runDate: string, spokenChars: number): void {
|
|
492
667
|
const poolPath = join(workDir, '10-collect', 'pool.json');
|
|
@@ -505,23 +680,34 @@ function recordSpokenRatio(workDir: string, runDate: string, spokenChars: number
|
|
|
505
680
|
writeJsonText(out, {
|
|
506
681
|
runDate,
|
|
507
682
|
poolChars,
|
|
508
|
-
|
|
683
|
+
// The admission rate is recorded explicitly (0434) so the next day's ladder projects the
|
|
684
|
+
// admitted set from a measured number instead of re-deriving it from the two ratios.
|
|
685
|
+
...(keptChars > 0
|
|
686
|
+
? { keptChars, keptRatio: round3(spokenChars / keptChars), keepRate: round3(keptChars / poolChars) }
|
|
687
|
+
: {}),
|
|
509
688
|
spokenChars,
|
|
510
689
|
ratio,
|
|
511
690
|
});
|
|
512
|
-
// Drift warning: the ladder
|
|
513
|
-
// different one. A wide gap means the next run's ladder is working from a stale
|
|
691
|
+
// Drift warning: the ladder projected this pool at some spoken-chars-per-pool-char; the writer
|
|
692
|
+
// just delivered a different one. A wide gap means the next run's ladder is working from a stale
|
|
693
|
+
// measure. Compare against the projection the ladder actually made (keep rate × kept ratio) and
|
|
694
|
+
// fall back to the pool ratio a pre-0434 ladder recorded.
|
|
514
695
|
let used: number | null = null;
|
|
515
696
|
try {
|
|
516
697
|
const ladder = readJson(join(workDir, '10-collect', 'ladder.json')) as Record<string, unknown> | null;
|
|
517
|
-
const
|
|
518
|
-
|
|
698
|
+
for (const key of ['spokenPerPoolChar', 'ratioUsed']) {
|
|
699
|
+
const candidate = Number(ladder?.[key]);
|
|
700
|
+
if (Number.isFinite(candidate) && candidate > 0) {
|
|
701
|
+
used = candidate;
|
|
702
|
+
break;
|
|
703
|
+
}
|
|
704
|
+
}
|
|
519
705
|
} catch {
|
|
520
706
|
used = null;
|
|
521
707
|
}
|
|
522
708
|
if (used !== null && Math.abs(ratio / used - 1) > 0.25) {
|
|
523
709
|
console.error(
|
|
524
|
-
`spoken ratio drifted: this run delivered ${ratio.toFixed(2)}x of the pool, the ladder
|
|
710
|
+
`spoken ratio drifted: this run delivered ${ratio.toFixed(2)}x of the pool, the ladder projected ${used.toFixed(2)}x (see ${out})`,
|
|
525
711
|
);
|
|
526
712
|
}
|
|
527
713
|
}
|
|
@@ -535,19 +721,47 @@ function rawChars(docs: unknown[]): number {
|
|
|
535
721
|
}
|
|
536
722
|
|
|
537
723
|
/**
|
|
538
|
-
*
|
|
539
|
-
* over the driver's measured char rate, plus the 8 s intro sting
|
|
540
|
-
* gate
|
|
541
|
-
*
|
|
724
|
+
* THE spoken-length arithmetic (0434): a spoken-char count × the ratio that set is denominated in,
|
|
725
|
+
* over the driver's measured char rate, plus the 8 s intro sting. Every estimate in this file is
|
|
726
|
+
* this one function — the floor gate and the post-spend refusal hand it the chars QC admitted, the
|
|
727
|
+
* ladder hands it the chars it projects QC will admit. `seconds` is unrounded: the floor gate
|
|
728
|
+
* compares seconds, the artifacts report minutes.
|
|
729
|
+
*/
|
|
730
|
+
function spokenLength(
|
|
731
|
+
chars: number,
|
|
732
|
+
expansion: number,
|
|
733
|
+
vdriver: string,
|
|
734
|
+
): { minutes: number; seconds: number; chars: number } {
|
|
735
|
+
const seconds = 8 + (chars * expansion) / spokenCharRate(vdriver);
|
|
736
|
+
return { minutes: Math.round((seconds / 60) * 10) / 10, seconds, chars };
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
/**
|
|
740
|
+
* The calibrated estimate over a kept pool (title+body characters × the recorded spoken/kept ratio)
|
|
741
|
+
* — shared by the pre-spend floor gate (applyFloorGate) and the post-spend duration refusal
|
|
742
|
+
* (dailyEpisodeDuration, 0266), so both artifacts report the same arithmetic.
|
|
743
|
+
*
|
|
744
|
+
* Both callers must pass `readSpokenCalibration(...).keptRatio`: this measures the ADMITTED set,
|
|
745
|
+
* which is what the kept ratio was measured on. The 1.4 default is the pre-2026-11-16 raw-script
|
|
746
|
+
* expansion and is ~4.5x too high for the scripted writer: leaving it on the duration refusal made
|
|
747
|
+
* the 2026-11-24 artifact claim a "pre-spend estimate 58.2 min" beside a measured 12.6 min, which is
|
|
748
|
+
* the number an operator reads when deciding whether to recover the day.
|
|
542
749
|
*/
|
|
543
750
|
function estimateSpokenMinutes(
|
|
544
751
|
docs: unknown[],
|
|
545
752
|
vdriver: string,
|
|
546
753
|
expansion: number = SPEAK_CHAR_EXPANSION,
|
|
547
754
|
): { minutes: number; seconds: number; chars: number } {
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
755
|
+
return spokenLength(rawChars(docs), expansion, vdriver);
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
/**
|
|
759
|
+
* The admitted set a raw pool should yield (0434 R1): the ladder's denominator bridge. A pool is not
|
|
760
|
+
* an episode — QC admits a share of it, and multiplying the whole pool by a spoken/pool ratio only
|
|
761
|
+
* matches the floor gate's arithmetic on the day the admission rate was recorded.
|
|
762
|
+
*/
|
|
763
|
+
function projectKeptChars(poolChars: number, keepRate: number): number {
|
|
764
|
+
return Math.round(poolChars * keepRate);
|
|
551
765
|
}
|
|
552
766
|
|
|
553
767
|
/**
|
|
@@ -561,9 +775,12 @@ function estimateSpokenMinutes(
|
|
|
561
775
|
* closes through run-report and the ledger exactly like an empty pool. The estimate and its inputs
|
|
562
776
|
* land in a refusal artifact next to the candidates.
|
|
563
777
|
*
|
|
564
|
-
* The ratio comes from `
|
|
565
|
-
* measures the admitted set, and applying the pool ratio to it discounted the planning shrink
|
|
566
|
-
* (2026-11-16: estimated 12.7 min, the writer delivered 23).
|
|
778
|
+
* The ratio comes from `readSpokenCalibration(...).keptRatio`, NOT the pool-denominated one: this
|
|
779
|
+
* gate measures the admitted set, and applying the pool ratio to it discounted the planning shrink
|
|
780
|
+
* twice (2026-11-16: estimated 12.7 min, the writer delivered 23). The extraction ladder projects
|
|
781
|
+
* that same admitted set with the same ratio (0434), so the two artifacts agree by construction; the
|
|
782
|
+
* one number the projection cannot know is today's admission rate, which this gate measures and
|
|
783
|
+
* reports when it drifts past `KEEP_RATE_DRIFT_BOUND`.
|
|
567
784
|
*/
|
|
568
785
|
function applyFloorGate(
|
|
569
786
|
candidates: string,
|
|
@@ -585,12 +802,20 @@ function applyFloorGate(
|
|
|
585
802
|
if (clearStaleRefusal && isFile(refusal)) unlinkSync(refusal);
|
|
586
803
|
return;
|
|
587
804
|
}
|
|
588
|
-
const
|
|
805
|
+
const calibration = readSpokenCalibration(workDir);
|
|
589
806
|
const {
|
|
590
807
|
minutes: estimatedMinutes,
|
|
591
808
|
seconds: estimatedSeconds,
|
|
592
809
|
chars,
|
|
593
|
-
} = estimateSpokenMinutes(docs, vdriver, keptRatio
|
|
810
|
+
} = estimateSpokenMinutes(docs, vdriver, calibration.keptRatio);
|
|
811
|
+
// 0434 R3: today's admitted share of the pool is measurable here for the first time — the ladder
|
|
812
|
+
// projected it from the recorded day. A drift beyond the bound is reported, never absorbed.
|
|
813
|
+
const assumed = assumedKeepRate(workDir, calibration);
|
|
814
|
+
const observed = observedKeepRate(workDir, chars);
|
|
815
|
+
const drift = keepRateDrift(assumed, observed, 'ladder');
|
|
816
|
+
// 0434 R2: one line an operator can compare against the ladder artifact without recomputing —
|
|
817
|
+
// the ratio, the path it came from, and the admission rate the estimate was built on.
|
|
818
|
+
const basis = `${calibration.keptRatio.toFixed(2)}x kept ratio (${calibration.keptRatioSource}), keep rate ${Math.round((observed?.rate ?? assumed.rate) * 100)}%`;
|
|
594
819
|
if (estimatedSeconds >= floor * 60) {
|
|
595
820
|
if (clearStaleRefusal && isFile(refusal)) unlinkSync(refusal);
|
|
596
821
|
// Task 0392 R2: the floor gate observed this pool and admitted it — a stage that ran and
|
|
@@ -598,7 +823,9 @@ function applyFloorGate(
|
|
|
598
823
|
recordSelectionStage(workDir, runDate, {
|
|
599
824
|
stages: [{ stage: 'floor', input: docs.length, kept: docs.length, dropped: [] }],
|
|
600
825
|
});
|
|
601
|
-
console.log(
|
|
826
|
+
console.log(
|
|
827
|
+
`floor gate: estimated ${estimatedMinutes} min from ${chars} chars at ${basis} — above the ${floor} min floor`,
|
|
828
|
+
);
|
|
602
829
|
return;
|
|
603
830
|
}
|
|
604
831
|
const ids = docs.map((doc) => String((doc as Record<string, unknown> | null)?.id ?? ''));
|
|
@@ -614,18 +841,25 @@ function applyFloorGate(
|
|
|
614
841
|
candidateChars: chars,
|
|
615
842
|
// The ratio this refusal actually used, and where it came from (0377; 2026-11-16): the
|
|
616
843
|
// gate measures the KEPT set, so a pool-denominated ratio under-predicts it badly.
|
|
617
|
-
expansion: keptRatio
|
|
618
|
-
expansionSource:
|
|
844
|
+
expansion: calibration.keptRatio,
|
|
845
|
+
expansionSource: calibration.keptRatioSource,
|
|
846
|
+
// 0434 R2/R3: the admission rate this run achieved, the rate the ladder projected with,
|
|
847
|
+
// and the gap — so the refusal and the ladder artifact explain each other.
|
|
848
|
+
keepRate: observed?.rate ?? null,
|
|
849
|
+
keepRateSource: observed?.source ?? null,
|
|
850
|
+
keepRateAssumed: assumed.rate,
|
|
851
|
+
keepRateAssumedSource: assumed.source,
|
|
852
|
+
keepRateDrift: drift?.delta ?? null,
|
|
619
853
|
charRate: spokenCharRate(vdriver),
|
|
620
854
|
ids,
|
|
621
|
-
reason: `a ${docs.length}-item pool estimates ${estimatedMinutes} min of speech, below the ${floor} min floor — refusing before any TTS spend`,
|
|
855
|
+
reason: `a ${docs.length}-item pool estimates ${estimatedMinutes} min of speech at ${basis}, below the ${floor} min floor — refusing before any TTS spend`,
|
|
622
856
|
}),
|
|
623
857
|
);
|
|
624
858
|
sted('write', candidates, () =>
|
|
625
859
|
writeJsonText(candidates, { ...(content ?? {}), metadata: { ...metadataOf(content), docs: [] } }),
|
|
626
860
|
);
|
|
627
861
|
console.error(
|
|
628
|
-
`floor gate: ${docs.length} candidates estimate ${estimatedMinutes} min < ${floor} min — candidates emptied, the run closes as no-content (see ${refusal})`,
|
|
862
|
+
`floor gate: ${docs.length} candidates estimate ${estimatedMinutes} min at ${basis} < ${floor} min — candidates emptied, the run closes as no-content (see ${refusal})`,
|
|
629
863
|
);
|
|
630
864
|
}
|
|
631
865
|
|
|
@@ -711,36 +945,68 @@ export function dailyExtract(args: string[]): void {
|
|
|
711
945
|
console.error(`extract: plan already authored — keeping the frozen pool (${poolPath})`);
|
|
712
946
|
return;
|
|
713
947
|
}
|
|
714
|
-
// 0377 R2: judge the pool by what the writer actually delivered last time
|
|
715
|
-
//
|
|
716
|
-
|
|
948
|
+
// 0377 R2 + 0434 R1: judge the pool by what the writer actually delivered last time, in the
|
|
949
|
+
// denominator the floor gate measures. The calibrated constants are only the fallback for a
|
|
950
|
+
// workflow that has never recorded either ratio.
|
|
951
|
+
const calibration = readSpokenCalibration(workDir);
|
|
717
952
|
let chosen: { window: string; docs: unknown[] } | null = null;
|
|
718
|
-
const rungs: Array<{
|
|
953
|
+
const rungs: Array<{
|
|
954
|
+
window: string;
|
|
955
|
+
items: number;
|
|
956
|
+
chars: number;
|
|
957
|
+
keptChars: number;
|
|
958
|
+
minutes: number;
|
|
959
|
+
clears: boolean;
|
|
960
|
+
}> = [];
|
|
719
961
|
for (const ms of windows) {
|
|
720
962
|
const label = formatWindowMs(ms);
|
|
721
963
|
const attempt = join(workDir, '10-collect', `.pool-${label}.json`);
|
|
722
964
|
kk(['store', 'extract', '--topic', topic, '--window', label, '--out', attempt, ...limit]);
|
|
723
965
|
const parsed = readJson(attempt);
|
|
724
966
|
const docs = Array.isArray(parsed) ? (parsed as unknown[]) : [];
|
|
725
|
-
|
|
967
|
+
// 0434 R1: a pool is not an episode. Estimate the set QC will ADMIT — the pool projected
|
|
968
|
+
// through the recording run's admission rate — and convert it at the spoken/kept ratio,
|
|
969
|
+
// which is the same arithmetic the floor gate applies to the set it actually receives.
|
|
970
|
+
// Multiplying the whole pool by a spoken/pool ratio only agrees with the gate on a day
|
|
971
|
+
// whose admission rate matches the recorded one: 2026-11-24 forecast 22.8 min off a
|
|
972
|
+
// 42,925-char pool while the admitted 12,937 chars could make 13.1 and the run measured
|
|
973
|
+
// 12.6, a "clears" that was already under the floor.
|
|
974
|
+
const poolChars = rawChars(docs);
|
|
975
|
+
const keptChars = projectKeptChars(poolChars, calibration.keepRate);
|
|
976
|
+
const estimate = spokenLength(keptChars, calibration.keptRatio, vdriver);
|
|
726
977
|
const clears = estimate.seconds >= floor * 60;
|
|
727
|
-
rungs.push({
|
|
978
|
+
rungs.push({
|
|
979
|
+
window: label,
|
|
980
|
+
items: docs.length,
|
|
981
|
+
chars: poolChars,
|
|
982
|
+
keptChars,
|
|
983
|
+
minutes: estimate.minutes,
|
|
984
|
+
clears,
|
|
985
|
+
});
|
|
728
986
|
chosen = { window: label, docs };
|
|
729
987
|
const verdict = gated
|
|
730
|
-
? `estimated ${estimate.minutes} min at ${
|
|
988
|
+
? `estimated ${estimate.minutes} min from ${keptChars} projected kept chars of ${poolChars} at ${calibration.keptRatio.toFixed(2)}x kept ratio, keep rate ${Math.round(calibration.keepRate * 100)}% (${calibration.keepRateSource}) — ${clears ? 'clears' : 'below'} the ${floor} min floor`
|
|
731
989
|
: 'floor gate off';
|
|
732
990
|
console.error(`extract: ${label} pool ${docs.length} item(s), ${verdict}`);
|
|
733
991
|
if (!gated || clears) break;
|
|
734
992
|
rmSync(attempt, { force: true });
|
|
735
993
|
}
|
|
736
994
|
const picked = chosen ?? { window: formatWindowMs(base), docs: [] as unknown[] };
|
|
737
|
-
// 0377 R3: the decision is an artifact, not just a stderr line — the run report and
|
|
738
|
-
// `kk news status` read which measure drove it, the rung chosen and the estimate at each rung
|
|
995
|
+
// 0377 R3 + 0434 R2: the decision is an artifact, not just a stderr line — the run report and
|
|
996
|
+
// `kk news status` read which measure drove it, the rung chosen and the estimate at each rung,
|
|
997
|
+
// and every measure prints the path it came from so two artifacts compare without recomputing.
|
|
998
|
+
// `ratioUsed`/`ratioSource` stay as the recorded spoken/pool ratio (the writer's drift
|
|
999
|
+
// anchor); `spokenPerPoolChar` is the pool-denominated number the rung minutes actually used.
|
|
739
1000
|
sted('write', join(workDir, '10-collect', 'ladder.json'), () =>
|
|
740
1001
|
writeJsonText(join(workDir, '10-collect', 'ladder.json'), {
|
|
741
1002
|
floorMinutes: gated ? floor : null,
|
|
742
|
-
ratioUsed:
|
|
743
|
-
ratioSource:
|
|
1003
|
+
ratioUsed: calibration.poolRatio,
|
|
1004
|
+
ratioSource: calibration.poolRatioSource,
|
|
1005
|
+
keptRatio: calibration.keptRatio,
|
|
1006
|
+
keptRatioSource: calibration.keptRatioSource,
|
|
1007
|
+
keepRate: calibration.keepRate,
|
|
1008
|
+
keepRateSource: calibration.keepRateSource,
|
|
1009
|
+
spokenPerPoolChar: Math.round(calibration.keepRate * calibration.keptRatio * 1000) / 1000,
|
|
744
1010
|
chosen: picked.window,
|
|
745
1011
|
rungs,
|
|
746
1012
|
}),
|
|
@@ -1135,8 +1401,11 @@ export function dailyEpisodeDuration(args: string[]): void {
|
|
|
1135
1401
|
console.error(`episode-duration: duration refusal already recorded (${refusal}) — nothing to do`);
|
|
1136
1402
|
return;
|
|
1137
1403
|
}
|
|
1138
|
-
const
|
|
1404
|
+
const calibration = readSpokenCalibration(workDir);
|
|
1405
|
+
const estimated = estimateSpokenMinutes(docs, vdriver, calibration.keptRatio);
|
|
1139
1406
|
const measuredMinutes = Math.round(minutes * 10) / 10;
|
|
1407
|
+
const observed = observedKeepRate(workDir, estimated.chars);
|
|
1408
|
+
const assumed = assumedKeepRate(workDir, calibration);
|
|
1140
1409
|
sted('write', refusal, () =>
|
|
1141
1410
|
writeJqText(refusal, {
|
|
1142
1411
|
measuredMinutes,
|
|
@@ -1144,7 +1413,15 @@ export function dailyEpisodeDuration(args: string[]): void {
|
|
|
1144
1413
|
minMinutes,
|
|
1145
1414
|
keptCount: docs.length,
|
|
1146
1415
|
candidateChars: estimated.chars,
|
|
1147
|
-
|
|
1416
|
+
// 0434 R2: same three measures the floor gate and the ladder print, so all three
|
|
1417
|
+
// artifacts for one episode compare without recomputation.
|
|
1418
|
+
expansion: calibration.keptRatio,
|
|
1419
|
+
expansionSource: calibration.keptRatioSource,
|
|
1420
|
+
keepRate: observed?.rate ?? null,
|
|
1421
|
+
keepRateSource: observed?.source ?? null,
|
|
1422
|
+
keepRateAssumed: assumed.rate,
|
|
1423
|
+
keepRateAssumedSource: assumed.source,
|
|
1424
|
+
reason: `the episode ran ${shown} min of speech, below the ${minMinutes} min floor (pre-spend estimate ${estimated.minutes} min at ${calibration.keptRatio.toFixed(2)}x kept ratio) — refusing after synthesis`,
|
|
1148
1425
|
}),
|
|
1149
1426
|
);
|
|
1150
1427
|
emptyCandidates(workDir, runDate);
|
|
@@ -2116,9 +2393,11 @@ export function dailyPlan(args: string[]): void {
|
|
|
2116
2393
|
const deferDocs = deferPlanDocs === 'true';
|
|
2117
2394
|
const target = deferDocs ? planContent : planDocs;
|
|
2118
2395
|
const targetCache = `${target}.cache.json`;
|
|
2396
|
+
const perSourceCap = String(Math.max(5, Math.ceil((Number(planMaxItems) || 20) / 4)));
|
|
2119
2397
|
const fingerprint = stageCacheFingerprint(blended, {
|
|
2120
2398
|
runDate,
|
|
2121
2399
|
planMaxItems,
|
|
2400
|
+
perSourceCap,
|
|
2122
2401
|
deferPlanDocs,
|
|
2123
2402
|
});
|
|
2124
2403
|
timed(workDir, 'plan', () => {
|
|
@@ -2144,7 +2423,11 @@ export function dailyPlan(args: string[]): void {
|
|
|
2144
2423
|
kk(
|
|
2145
2424
|
['executor', 'run', 'episode-plan-gen', '--in', blended, '--out', planContent, ...pluginsArgs(pluginsPath)],
|
|
2146
2425
|
{
|
|
2147
|
-
env: {
|
|
2426
|
+
env: {
|
|
2427
|
+
EPISODE_PLAN_MAX_ITEMS: planMaxItems,
|
|
2428
|
+
EPISODE_PLAN_PER_SOURCE_CAP: perSourceCap,
|
|
2429
|
+
EPISODE_PLAN_DATE: runDate,
|
|
2430
|
+
},
|
|
2148
2431
|
},
|
|
2149
2432
|
);
|
|
2150
2433
|
const docs = metadataOf(readJson(planContent)).docs;
|
|
@@ -2210,8 +2493,8 @@ function wechatKeyPointLabel(title: string): string {
|
|
|
2210
2493
|
const clean = title.replace(/^#+\s+/, '').trim();
|
|
2211
2494
|
const firstClause = clean.split(/[::,,。!?!?\-—|]/)[0]?.trim() ?? clean;
|
|
2212
2495
|
const chars = Array.from(firstClause);
|
|
2213
|
-
if (chars.length > 0 && chars.length <=
|
|
2214
|
-
return Array.from(clean).slice(0,
|
|
2496
|
+
if (chars.length > 0 && chars.length <= 28) return firstClause;
|
|
2497
|
+
return Array.from(clean).slice(0, 28).join('');
|
|
2215
2498
|
}
|
|
2216
2499
|
|
|
2217
2500
|
function extractWechatKeyPoints(
|
|
@@ -2264,6 +2547,94 @@ function cleanWechatDigest(body: string, keyPoints?: readonly WechatKeyPoint[]):
|
|
|
2264
2547
|
return Array.from(candidate).slice(0, 120).join('');
|
|
2265
2548
|
}
|
|
2266
2549
|
|
|
2550
|
+
/** One validated inline figure, as the WeChat variant materializes it (0426 R2). */
|
|
2551
|
+
export interface InlineFigureMaterial {
|
|
2552
|
+
id: string;
|
|
2553
|
+
path: string;
|
|
2554
|
+
sha256: string;
|
|
2555
|
+
altText: string;
|
|
2556
|
+
caption: string;
|
|
2557
|
+
anchor: string;
|
|
2558
|
+
}
|
|
2559
|
+
|
|
2560
|
+
/**
|
|
2561
|
+
* 0426 R2 — the figures a run may materialize into `article@wechatmp-pub`, or `[]` when the run never
|
|
2562
|
+
* opted in. Opt-in IS the plan the gated node writes: a work dir without
|
|
2563
|
+
* `22-article/illustrations/plan.json` produces byte-identical variants to before this task.
|
|
2564
|
+
*
|
|
2565
|
+
* Every figure is proved against its own receipt before a marker exists: the receipt must name the
|
|
2566
|
+
* same anchor and concept, its `bodySha256` must still match the reviewed article, and the image's
|
|
2567
|
+
* bytes must still hash to `imageSha256`. A missing receipt, an edited article or a swapped binary
|
|
2568
|
+
* refuses here rather than materializing a marker nothing verified.
|
|
2569
|
+
*/
|
|
2570
|
+
export function inlineFigureMaterials(workDir: string, runDate: string): InlineFigureMaterial[] {
|
|
2571
|
+
const dir = join(workDir, '22-article', 'illustrations');
|
|
2572
|
+
const plan = readJson(join(dir, 'plan.json'));
|
|
2573
|
+
if (plan === null) return [];
|
|
2574
|
+
const article = readJson(join(workDir, '22-article', `${runDate}_06_article_content.json`));
|
|
2575
|
+
const body = typeof article?.body === 'string' ? article.body : '';
|
|
2576
|
+
const bodySha256 = createHash('sha256').update(body).digest('hex');
|
|
2577
|
+
const entries = Array.isArray(plan.figures) ? (plan.figures as Record<string, unknown>[]) : [];
|
|
2578
|
+
const materials: InlineFigureMaterial[] = [];
|
|
2579
|
+
for (const [position, entry] of entries.entries()) {
|
|
2580
|
+
const id = `figure-${position + 1}`;
|
|
2581
|
+
const receipt = readJson(join(dir, `${id}.receipt.json`));
|
|
2582
|
+
if (receipt === null) {
|
|
2583
|
+
failWith(
|
|
2584
|
+
1,
|
|
2585
|
+
`bundle-variants: inline figure ${id} has no render receipt — render the plan (kk stage news-inline-illustrations) before materializing variants`,
|
|
2586
|
+
);
|
|
2587
|
+
}
|
|
2588
|
+
if (receipt.bodySha256 !== bodySha256) {
|
|
2589
|
+
failWith(
|
|
2590
|
+
1,
|
|
2591
|
+
`bundle-variants: inline figure ${id} was rendered against a different article body — re-render the plan before materializing`,
|
|
2592
|
+
);
|
|
2593
|
+
}
|
|
2594
|
+
if (receipt.anchor !== entry.anchor || receipt.concept !== entry.concept) {
|
|
2595
|
+
failWith(1, `bundle-variants: inline figure ${id} receipt names a different anchor/concept than the plan`);
|
|
2596
|
+
}
|
|
2597
|
+
const artifact = firstArtifact(readJson(join(dir, `${id}.json`)));
|
|
2598
|
+
const path = typeof artifact?.path === 'string' ? artifact.path : '';
|
|
2599
|
+
if (path === '' || !isFile(path)) {
|
|
2600
|
+
failWith(1, `bundle-variants: inline figure ${id} image is missing at ${path || '(no artifact)'}`);
|
|
2601
|
+
}
|
|
2602
|
+
if (receipt.imageSha256 !== createHash('sha256').update(readFileSync(path)).digest('hex')) {
|
|
2603
|
+
failWith(1, `bundle-variants: inline figure ${id} image bytes changed after rendering — re-render it`);
|
|
2604
|
+
}
|
|
2605
|
+
materials.push({
|
|
2606
|
+
id,
|
|
2607
|
+
path,
|
|
2608
|
+
sha256: String(receipt.imageSha256),
|
|
2609
|
+
altText: String(entry.altText),
|
|
2610
|
+
caption: String(entry.caption),
|
|
2611
|
+
anchor: String(entry.anchor),
|
|
2612
|
+
});
|
|
2613
|
+
}
|
|
2614
|
+
return materials;
|
|
2615
|
+
}
|
|
2616
|
+
|
|
2617
|
+
/**
|
|
2618
|
+
* 0426 R2 — place each figure right after its own paragraph: the marker image + a caption
|
|
2619
|
+
* paragraph. Refuses an anchor that is no longer unique, which is what keeps a re-cut article from
|
|
2620
|
+
* receiving a figure that belonged to a paragraph it no longer has.
|
|
2621
|
+
*/
|
|
2622
|
+
export function withInlineFigureMarkers(body: string, figures: readonly InlineFigureMaterial[]): string {
|
|
2623
|
+
let out = body;
|
|
2624
|
+
for (const figure of figures) {
|
|
2625
|
+
const occurrences = out.split(figure.anchor).length - 1;
|
|
2626
|
+
if (occurrences !== 1) {
|
|
2627
|
+
failWith(
|
|
2628
|
+
1,
|
|
2629
|
+
`wechat article: inline figure ${figure.id} anchor is not unique in the body (found ${occurrences}) — refusing to place a figure on a changed article`,
|
|
2630
|
+
);
|
|
2631
|
+
}
|
|
2632
|
+
const marker = ``;
|
|
2633
|
+
out = out.replace(figure.anchor, () => `${figure.anchor}\n\n${marker}\n\n${figure.caption}`);
|
|
2634
|
+
}
|
|
2635
|
+
return out;
|
|
2636
|
+
}
|
|
2637
|
+
|
|
2267
2638
|
/**
|
|
2268
2639
|
* The 公众号 article payload (task 0327 R1): the article Content plus MP draft enrichment.
|
|
2269
2640
|
*
|
|
@@ -2286,13 +2657,20 @@ export function buildWechatArticleContent(
|
|
|
2286
2657
|
* carries the episode body, so it passes `false`.
|
|
2287
2658
|
*/
|
|
2288
2659
|
appendOutro?: boolean;
|
|
2660
|
+
/**
|
|
2661
|
+
* 0426 R2: figures already validated against their render receipts. Only the WeChat ARTICLE
|
|
2662
|
+
* variant receives them — the 播客 episode body has no article paragraphs to anchor to.
|
|
2663
|
+
*/
|
|
2664
|
+
inlineFigures?: readonly InlineFigureMaterial[];
|
|
2289
2665
|
},
|
|
2290
2666
|
): Record<string, unknown> {
|
|
2667
|
+
// 0426 R2: the 播客 episode body has no article paragraphs to anchor to, so only the article
|
|
2668
|
+
// path (the one that appends the closer) ever materializes figures.
|
|
2669
|
+
const figures = options.appendOutro === false ? [] : (options.inlineFigures ?? []);
|
|
2291
2670
|
const wechatmp: Record<string, unknown> = {
|
|
2292
2671
|
original: true,
|
|
2293
|
-
// 2026-11-
|
|
2294
|
-
//
|
|
2295
|
-
// enrichment failures (音频, 原创, 原文链接) fail loud.
|
|
2672
|
+
// 2026-11-22 live check: 咸话咸说 is not yet authorized in 赞赏账户小程序 -> 可收款公众号,
|
|
2673
|
+
// so reward stays false until the operator authorizes it there.
|
|
2296
2674
|
reward: false,
|
|
2297
2675
|
author: WECHAT_BRAND.author,
|
|
2298
2676
|
collection: options.collection,
|
|
@@ -2300,6 +2678,19 @@ export function buildWechatArticleContent(
|
|
|
2300
2678
|
claimSource: WECHAT_BRAND.claimSource,
|
|
2301
2679
|
// 封面 comes from 图片库: the episode cover is uploaded there as the audio material's cover.
|
|
2302
2680
|
coverSource: WECHAT_BRAND.coverSource,
|
|
2681
|
+
// 0426 R2: the figures this body's markers resolve to, pinned so the adapter can verify the
|
|
2682
|
+
// exact bytes it uploads and never a file that changed after the review.
|
|
2683
|
+
...(figures.length > 0
|
|
2684
|
+
? {
|
|
2685
|
+
inlineFigures: figures.map((figure) => ({
|
|
2686
|
+
id: figure.id,
|
|
2687
|
+
path: figure.path,
|
|
2688
|
+
sha256: figure.sha256,
|
|
2689
|
+
altText: figure.altText,
|
|
2690
|
+
caption: figure.caption,
|
|
2691
|
+
})),
|
|
2692
|
+
}
|
|
2693
|
+
: {}),
|
|
2303
2694
|
...(options.links.articleUrl !== '' ? { originalUrl: options.links.articleUrl } : {}),
|
|
2304
2695
|
...(options.coverPath === undefined ? {} : { coverPath: options.coverPath }),
|
|
2305
2696
|
...(options.audioPath === undefined
|
|
@@ -2324,17 +2715,23 @@ export function buildWechatArticleContent(
|
|
|
2324
2715
|
},
|
|
2325
2716
|
};
|
|
2326
2717
|
}
|
|
2327
|
-
let formattedBody = stripLeadingH1Heading(rawBody);
|
|
2718
|
+
let formattedBody = stripLeadingH1Heading(rawBody).trimStart();
|
|
2328
2719
|
const keyPoints = (options.keyPoints ?? []).filter((kp) => kp.label.trim() !== '' && kp.text.trim() !== '');
|
|
2329
|
-
if (keyPoints.length > 0 &&
|
|
2330
|
-
const bullets = keyPoints.map((kp) => `-
|
|
2331
|
-
|
|
2720
|
+
if (keyPoints.length > 0 && !/今日要点/.test(formattedBody.slice(0, 200))) {
|
|
2721
|
+
const bullets = keyPoints.map((kp) => `- ${kp.label.trim()}`).join('\n');
|
|
2722
|
+
const introMatch = formattedBody.match(/^([^\n]*咸话咸说[^\n]*)\n+/);
|
|
2723
|
+
if (introMatch?.[1]) {
|
|
2724
|
+
const rest = formattedBody.slice(introMatch[0].length).trimStart();
|
|
2725
|
+
formattedBody = `${introMatch[1].trimEnd()}今日要点如下:\n${bullets}\n\n下面请听详细内容。\n\n${rest}`;
|
|
2726
|
+
} else {
|
|
2727
|
+
formattedBody = `今日要点如下:\n${bullets}\n\n下面请听详细内容。\n\n${formattedBody}`;
|
|
2728
|
+
}
|
|
2332
2729
|
}
|
|
2333
2730
|
const existingDigest = typeof existingMeta.digest === 'string' ? existingMeta.digest.trim() : '';
|
|
2334
2731
|
const derivedDigest = existingDigest !== '' ? existingDigest : cleanWechatDigest(rawBody, keyPoints);
|
|
2335
2732
|
return {
|
|
2336
2733
|
...article,
|
|
2337
|
-
body: `${formattedBody}${WECHAT_OUTRO}`,
|
|
2734
|
+
body: `${withInlineFigureMarkers(formattedBody, figures)}${WECHAT_OUTRO}`,
|
|
2338
2735
|
metadata: {
|
|
2339
2736
|
...existingMeta,
|
|
2340
2737
|
...(derivedDigest !== '' ? { digest: derivedDigest } : {}),
|
|
@@ -2501,16 +2898,16 @@ export function weightedLength(text: string): number {
|
|
|
2501
2898
|
}
|
|
2502
2899
|
|
|
2503
2900
|
/** 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']);
|
|
2901
|
+
const OG_CARD_PLATFORMS = new Set(['x', 'threads', 'linkedin', 'weibo']);
|
|
2505
2902
|
|
|
2506
2903
|
/**
|
|
2507
2904
|
* One channel's short promo copy as a Content (task 0327 R3; task 0410 episode promo framing):
|
|
2508
2905
|
* prepends the frozen episode title and appends the episode listen URL (`{{podcast_url}}`) when
|
|
2509
2906
|
* supplied, reserving header/footer budget before truncating copy (X counts URLs at t.co weight 23).
|
|
2510
2907
|
*
|
|
2511
|
-
* Platforms in `OG_CARD_PLATFORMS` (`x`, `threads`, `linkedin`) omit `coverImage` when linking a
|
|
2908
|
+
* Platforms in `OG_CARD_PLATFORMS` (`x`, `threads`, `linkedin`, `weibo`) omit `coverImage` when linking a
|
|
2512
2909
|
* podcast URL so their native Open Graph card renders cleanly instead of being suppressed by an
|
|
2513
|
-
* attached image; image-first rails (`
|
|
2910
|
+
* attached image; image-first rails (`jike`) keep `coverImage`.
|
|
2514
2911
|
*/
|
|
2515
2912
|
export function buildSocialContent(
|
|
2516
2913
|
copy: string,
|
|
@@ -2664,6 +3061,8 @@ export function dailyBundleVariants(args: string[]): void {
|
|
|
2664
3061
|
const skipped: string[] = [];
|
|
2665
3062
|
|
|
2666
3063
|
const article = readJson(articlePath);
|
|
3064
|
+
// 0426 R2: [] when the run never opted in, so a default run's variants stay byte-identical.
|
|
3065
|
+
const inlineFigures = inlineFigureMaterials(workDir, runDate);
|
|
2667
3066
|
const prep = readJson(prepPath);
|
|
2668
3067
|
const planItems = planItemsForPodcast(workDir, runDate);
|
|
2669
3068
|
const write = (key: string, content: Record<string, unknown>): void => {
|
|
@@ -2709,6 +3108,7 @@ export function dailyBundleVariants(args: string[]): void {
|
|
|
2709
3108
|
publishStatus: 'draft',
|
|
2710
3109
|
collection: '每日AI资讯',
|
|
2711
3110
|
keyPoints: wechatKeyPoints,
|
|
3111
|
+
inlineFigures,
|
|
2712
3112
|
...(cover === undefined ? {} : { coverPath: cover }),
|
|
2713
3113
|
...(articleAudio === undefined ? {} : { audioPath: articleAudio, audioTitle: firstArticleLine }),
|
|
2714
3114
|
}),
|
|
@@ -3031,6 +3431,286 @@ export function dailyPublishPodcast(args: string[]): void {
|
|
|
3031
3431
|
});
|
|
3032
3432
|
}
|
|
3033
3433
|
|
|
3434
|
+
/** 0426 R2: one pinned `illustration` request per figure — the look is not per-run drivable. */
|
|
3435
|
+
export const INLINE_FIGURE_FORMAT = 'illustration';
|
|
3436
|
+
export const INLINE_FIGURE_STYLE = 'technical-diagram';
|
|
3437
|
+
export const INLINE_FIGURE_MAX = 2;
|
|
3438
|
+
|
|
3439
|
+
interface InlineFigurePlanEntry {
|
|
3440
|
+
anchor: string;
|
|
3441
|
+
sourceId: string;
|
|
3442
|
+
concept: string;
|
|
3443
|
+
caption: string;
|
|
3444
|
+
altText: string;
|
|
3445
|
+
}
|
|
3446
|
+
|
|
3447
|
+
interface InlineFigurePlan {
|
|
3448
|
+
version: 1;
|
|
3449
|
+
figures: InlineFigurePlanEntry[];
|
|
3450
|
+
}
|
|
3451
|
+
|
|
3452
|
+
/** One article paragraph, and whether a figure may anchor to it. */
|
|
3453
|
+
interface ArticleBlock {
|
|
3454
|
+
text: string;
|
|
3455
|
+
index: number;
|
|
3456
|
+
eligible: boolean;
|
|
3457
|
+
}
|
|
3458
|
+
|
|
3459
|
+
/**
|
|
3460
|
+
* 0426 R1 — split the body into blank-line-separated blocks and mark the prose ones: a fenced code
|
|
3461
|
+
* block, a heading, a quotation, a list item and an existing image are all ineligible, so a figure
|
|
3462
|
+
* can never land inside code or between a heading and its section.
|
|
3463
|
+
*/
|
|
3464
|
+
export function articleBlocks(body: string): ArticleBlock[] {
|
|
3465
|
+
const blocks: ArticleBlock[] = [];
|
|
3466
|
+
let fence = false;
|
|
3467
|
+
for (const raw of body.split(/\n{2,}/)) {
|
|
3468
|
+
const text = raw.trim();
|
|
3469
|
+
if (text === '') continue;
|
|
3470
|
+
if (text.startsWith('```')) {
|
|
3471
|
+
fence = !fence;
|
|
3472
|
+
blocks.push({ text, index: blocks.length, eligible: false });
|
|
3473
|
+
continue;
|
|
3474
|
+
}
|
|
3475
|
+
const eligible =
|
|
3476
|
+
!fence &&
|
|
3477
|
+
!text.startsWith('#') &&
|
|
3478
|
+
!text.startsWith('>') &&
|
|
3479
|
+
!text.startsWith('![') &&
|
|
3480
|
+
!text.startsWith('- ') &&
|
|
3481
|
+
!text.startsWith('* ') &&
|
|
3482
|
+
!/^\d+\.\s/.test(text);
|
|
3483
|
+
blocks.push({ text, index: blocks.length, eligible });
|
|
3484
|
+
}
|
|
3485
|
+
return blocks;
|
|
3486
|
+
}
|
|
3487
|
+
|
|
3488
|
+
/** 0426 R1 — validate the whole plan before any provider call: shape, anchors, order, sources. */
|
|
3489
|
+
export function validateInlineFigurePlan(
|
|
3490
|
+
raw: unknown,
|
|
3491
|
+
body: string,
|
|
3492
|
+
admittedIds: ReadonlySet<string>,
|
|
3493
|
+
): InlineFigurePlan {
|
|
3494
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
3495
|
+
failWith(1, 'inline illustrations: plan.json must be a JSON object {version, figures}');
|
|
3496
|
+
}
|
|
3497
|
+
const plan = raw as Record<string, unknown>;
|
|
3498
|
+
if (plan.version !== 1) failWith(1, `inline illustrations: plan version must be 1, got ${String(plan.version)}`);
|
|
3499
|
+
if (!Array.isArray(plan.figures) || plan.figures.length === 0) {
|
|
3500
|
+
failWith(1, 'inline illustrations: plan.figures must hold 1 or 2 figures');
|
|
3501
|
+
}
|
|
3502
|
+
if (plan.figures.length > INLINE_FIGURE_MAX) {
|
|
3503
|
+
failWith(
|
|
3504
|
+
1,
|
|
3505
|
+
`inline illustrations: at most ${INLINE_FIGURE_MAX} figures per article, got ${plan.figures.length}`,
|
|
3506
|
+
);
|
|
3507
|
+
}
|
|
3508
|
+
const blocks = articleBlocks(body);
|
|
3509
|
+
const figures: InlineFigurePlanEntry[] = [];
|
|
3510
|
+
const usedAnchors = new Set<string>();
|
|
3511
|
+
let lastBlock = -1;
|
|
3512
|
+
for (const [position, entry] of plan.figures.entries()) {
|
|
3513
|
+
const figure = (entry ?? {}) as Record<string, unknown>;
|
|
3514
|
+
const label = `figure ${position + 1}`;
|
|
3515
|
+
for (const field of ['anchor', 'sourceId', 'concept', 'caption', 'altText'] as const) {
|
|
3516
|
+
const value = figure[field];
|
|
3517
|
+
if (typeof value !== 'string' || value.trim() === '') {
|
|
3518
|
+
failWith(1, `inline illustrations: ${label} has no ${field}`);
|
|
3519
|
+
}
|
|
3520
|
+
}
|
|
3521
|
+
const anchor = String(figure.anchor).trim();
|
|
3522
|
+
const sourceId = String(figure.sourceId).trim();
|
|
3523
|
+
if (!admittedIds.has(sourceId)) {
|
|
3524
|
+
failWith(1, `inline illustrations: ${label} cites source '${sourceId}', not an admitted plan item`);
|
|
3525
|
+
}
|
|
3526
|
+
const occurrences = body.split(anchor).length - 1;
|
|
3527
|
+
if (occurrences !== 1) {
|
|
3528
|
+
failWith(
|
|
3529
|
+
1,
|
|
3530
|
+
`inline illustrations: ${label} anchor must be one unique whole paragraph of the reviewed article (found ${occurrences})`,
|
|
3531
|
+
);
|
|
3532
|
+
}
|
|
3533
|
+
if (usedAnchors.has(anchor)) {
|
|
3534
|
+
failWith(
|
|
3535
|
+
1,
|
|
3536
|
+
`inline illustrations: ${label} duplicates an earlier figure's anchor — each figure needs its own paragraph`,
|
|
3537
|
+
);
|
|
3538
|
+
}
|
|
3539
|
+
usedAnchors.add(anchor);
|
|
3540
|
+
const block = blocks.find((candidate) => candidate.eligible && candidate.text === anchor);
|
|
3541
|
+
if (block === undefined) {
|
|
3542
|
+
failWith(
|
|
3543
|
+
1,
|
|
3544
|
+
`inline illustrations: ${label} anchor is not a whole prose paragraph (code, heading, quotation, list and image blocks are ineligible): '${anchor.slice(0, 60)}'`,
|
|
3545
|
+
);
|
|
3546
|
+
}
|
|
3547
|
+
if (block.index <= lastBlock) {
|
|
3548
|
+
failWith(1, `inline illustrations: ${label} is out of body order — figures follow their paragraphs`);
|
|
3549
|
+
}
|
|
3550
|
+
lastBlock = block.index;
|
|
3551
|
+
figures.push({
|
|
3552
|
+
anchor,
|
|
3553
|
+
sourceId,
|
|
3554
|
+
concept: String(figure.concept).trim(),
|
|
3555
|
+
caption: String(figure.caption).trim(),
|
|
3556
|
+
altText: String(figure.altText).trim(),
|
|
3557
|
+
});
|
|
3558
|
+
}
|
|
3559
|
+
return { version: 1, figures };
|
|
3560
|
+
}
|
|
3561
|
+
|
|
3562
|
+
/**
|
|
3563
|
+
* 0426 R1 — the draft-verdict gate `dailyPublishPrep` applies, reused BEFORE any figure is billed:
|
|
3564
|
+
* no stamp, a stamp on different bytes (edited after review) or a WeChat-excluded target never spends.
|
|
3565
|
+
*/
|
|
3566
|
+
export function assertInlineFigureDrafts(workDir: string, runDate: string): void {
|
|
3567
|
+
const stamp = readJson(safetyPath(workDir, runDate, 'safety-judge_stamp.json'));
|
|
3568
|
+
if (stamp === null) {
|
|
3569
|
+
failWith(1, 'inline illustrations: no content-safety verdict stamp for this run — not rendering figures');
|
|
3570
|
+
}
|
|
3571
|
+
if (stamp.status !== 'pass' && stamp.status !== 'escalate' && stamp.status !== 'exclude') {
|
|
3572
|
+
failWith(1, `inline illustrations: content-safety status ${String(stamp.status)} does not publish`);
|
|
3573
|
+
}
|
|
3574
|
+
if (stamp.digest !== safetyDigest(workDir, runDate)) {
|
|
3575
|
+
failWith(1, 'inline illustrations: drafts changed after the content-safety verdict — re-run the review');
|
|
3576
|
+
}
|
|
3577
|
+
const excluded = Array.isArray(stamp.excludedPlatforms) ? (stamp.excludedPlatforms as string[]) : [];
|
|
3578
|
+
if (excluded.includes('wechatmp')) {
|
|
3579
|
+
failWith(
|
|
3580
|
+
1,
|
|
3581
|
+
'inline illustrations: content-safety excluded wechatmp for this run — no article carries the figures',
|
|
3582
|
+
);
|
|
3583
|
+
}
|
|
3584
|
+
}
|
|
3585
|
+
|
|
3586
|
+
/** 0426 R1 — the preset row that can carry a figure: the enabled WeChat ARTICLE row, not 播客. */
|
|
3587
|
+
export function assertInlineFigureTarget(presetPath: string): void {
|
|
3588
|
+
const preset = readJson(presetPath);
|
|
3589
|
+
const targets = Array.isArray(preset?.targets) ? (preset.targets as Record<string, unknown>[]) : [];
|
|
3590
|
+
const enabled = targets.filter(
|
|
3591
|
+
(target) =>
|
|
3592
|
+
target.plugin === 'wechatmp-pub' &&
|
|
3593
|
+
target.operation === '文章' &&
|
|
3594
|
+
target.variant === 'article' &&
|
|
3595
|
+
typeof target.mode === 'string' &&
|
|
3596
|
+
target.mode !== 'off',
|
|
3597
|
+
);
|
|
3598
|
+
if (enabled.length === 0) {
|
|
3599
|
+
failWith(
|
|
3600
|
+
1,
|
|
3601
|
+
`inline illustrations: preset ${basename(presetPath)} has no enabled wechatmp-pub 文章 (article) target — no article could carry the figures`,
|
|
3602
|
+
);
|
|
3603
|
+
}
|
|
3604
|
+
}
|
|
3605
|
+
|
|
3606
|
+
function sha256File(path: string): string {
|
|
3607
|
+
return createHash('sha256').update(readFileSync(path)).digest('hex');
|
|
3608
|
+
}
|
|
3609
|
+
|
|
3610
|
+
/**
|
|
3611
|
+
* 0426 R1/R2 — `kk stage news-inline-illustrations <work_dir> <run_date> <plugins_path> <provider>
|
|
3612
|
+
* <model> <preset_path>`.
|
|
3613
|
+
*
|
|
3614
|
+
* Validate the whole plan, then render or resume one figure at a time. A figure is reused only when
|
|
3615
|
+
* its receipt matches the current body hash, anchor, concept and settings AND the file on disk still
|
|
3616
|
+
* hashes to the recorded SHA-256; anything else re-renders. Each receipt is written as soon as its
|
|
3617
|
+
* figure lands, so a partial provider failure keeps the completed figures for the resume run.
|
|
3618
|
+
*/
|
|
3619
|
+
export function dailyInlineIllustrations(args: string[]): void {
|
|
3620
|
+
const [workDir = '', runDate = '', pluginsPath = '', provider = '', model = '', presetPath = ''] = args;
|
|
3621
|
+
const dir = join(workDir, '22-article', 'illustrations');
|
|
3622
|
+
const articlePath = join(workDir, '22-article', `${runDate}_06_article_content.json`);
|
|
3623
|
+
const planDocsPath = join(workDir, '21-plan', `${runDate}_03_plan_plan.json`);
|
|
3624
|
+
timed(workDir, 'inline-illustrations', () => {
|
|
3625
|
+
if (presetPath === '') {
|
|
3626
|
+
failWith(1, 'inline illustrations: no publish-preset path was passed for target admission');
|
|
3627
|
+
}
|
|
3628
|
+
// Admission first: an unsupported target must never reach validation, let alone a provider.
|
|
3629
|
+
assertInlineFigureTarget(presetPath);
|
|
3630
|
+
const article = requireJson(articlePath, 'inline-illustrations');
|
|
3631
|
+
const body = typeof article.body === 'string' ? article.body : '';
|
|
3632
|
+
if (body.trim() === '') failWith(1, `inline illustrations: ${articlePath} has no article body to anchor to`);
|
|
3633
|
+
const planDocs = readJson(planDocsPath);
|
|
3634
|
+
const admittedIds = new Set(
|
|
3635
|
+
(Array.isArray(planDocs) ? planDocs : [])
|
|
3636
|
+
.map((doc) =>
|
|
3637
|
+
doc !== null && typeof doc === 'object' ? (doc as Record<string, unknown>).id : undefined,
|
|
3638
|
+
)
|
|
3639
|
+
.filter((id): id is string => typeof id === 'string' && id !== ''),
|
|
3640
|
+
);
|
|
3641
|
+
assertInlineFigureDrafts(workDir, runDate);
|
|
3642
|
+
const plan = validateInlineFigurePlan(
|
|
3643
|
+
requireJson(join(dir, 'plan.json'), 'inline-illustrations'),
|
|
3644
|
+
body,
|
|
3645
|
+
admittedIds,
|
|
3646
|
+
);
|
|
3647
|
+
const bodySha256 = createHash('sha256').update(body).digest('hex');
|
|
3648
|
+
const settings = { format: INLINE_FIGURE_FORMAT, style: INLINE_FIGURE_STYLE, provider, model };
|
|
3649
|
+
sted('mkdir', dir, () => mkdirSync(dir, { recursive: true }));
|
|
3650
|
+
for (const [position, figure] of plan.figures.entries()) {
|
|
3651
|
+
const id = `figure-${position + 1}`;
|
|
3652
|
+
const contentPath = join(dir, `${id}.json`);
|
|
3653
|
+
const receiptPath = join(dir, `${id}.receipt.json`);
|
|
3654
|
+
const receipt = readJson(receiptPath);
|
|
3655
|
+
const previous = firstArtifact(readJson(contentPath));
|
|
3656
|
+
const previousPath = typeof previous?.path === 'string' ? previous.path : '';
|
|
3657
|
+
const reusable =
|
|
3658
|
+
receipt !== null &&
|
|
3659
|
+
receipt.id === id &&
|
|
3660
|
+
receipt.bodySha256 === bodySha256 &&
|
|
3661
|
+
receipt.anchor === figure.anchor &&
|
|
3662
|
+
receipt.concept === figure.concept &&
|
|
3663
|
+
JSON.stringify(receipt.settings) === JSON.stringify(settings) &&
|
|
3664
|
+
previousPath !== '' &&
|
|
3665
|
+
isFile(previousPath) &&
|
|
3666
|
+
receipt.imageSha256 === sha256File(previousPath);
|
|
3667
|
+
if (reusable) {
|
|
3668
|
+
console.log(`inline illustrations: ${id} reused (verified bytes ${previousPath})`);
|
|
3669
|
+
continue;
|
|
3670
|
+
}
|
|
3671
|
+
const envPath = join(dir, `${id}.in.json`);
|
|
3672
|
+
const imageGen: Record<string, unknown> = {
|
|
3673
|
+
job: 'illustration',
|
|
3674
|
+
format: INLINE_FIGURE_FORMAT,
|
|
3675
|
+
style: INLINE_FIGURE_STYLE,
|
|
3676
|
+
count: 1,
|
|
3677
|
+
maxImages: 1,
|
|
3678
|
+
positions: [figure.anchor],
|
|
3679
|
+
vars: { concept: figure.concept, title: figure.sourceId },
|
|
3680
|
+
};
|
|
3681
|
+
if (provider !== '') imageGen.provider = provider;
|
|
3682
|
+
if (model !== '') imageGen.model = model;
|
|
3683
|
+
sted('write', envPath, () =>
|
|
3684
|
+
writeJsonText(envPath, [{ id, title: runDate, body: '', metadata: { imageGen } }]),
|
|
3685
|
+
);
|
|
3686
|
+
kk(['executor', 'run', 'image-gen', '--in', envPath, '--out', contentPath, ...pluginsArgs(pluginsPath)]);
|
|
3687
|
+
const artifact = firstArtifact(readJson(contentPath));
|
|
3688
|
+
const artifactPath = typeof artifact?.path === 'string' ? artifact.path : '';
|
|
3689
|
+
if (artifactPath === '' || !isFile(artifactPath)) {
|
|
3690
|
+
failWith(
|
|
3691
|
+
1,
|
|
3692
|
+
`inline illustrations: ${id} produced no image file (image-gen wrote ${contentPath}); figures before it keep their receipts`,
|
|
3693
|
+
);
|
|
3694
|
+
}
|
|
3695
|
+
sted('write', receiptPath, () =>
|
|
3696
|
+
writeJsonText(receiptPath, {
|
|
3697
|
+
version: 1,
|
|
3698
|
+
id,
|
|
3699
|
+
anchor: figure.anchor,
|
|
3700
|
+
sourceId: figure.sourceId,
|
|
3701
|
+
concept: figure.concept,
|
|
3702
|
+
caption: figure.caption,
|
|
3703
|
+
altText: figure.altText,
|
|
3704
|
+
bodySha256,
|
|
3705
|
+
settings,
|
|
3706
|
+
imageSha256: sha256File(artifactPath),
|
|
3707
|
+
}),
|
|
3708
|
+
);
|
|
3709
|
+
}
|
|
3710
|
+
console.log(`inline illustrations: ${plan.figures.length} figure(s) ready in ${dir}`);
|
|
3711
|
+
});
|
|
3712
|
+
}
|
|
3713
|
+
|
|
3034
3714
|
export function dailyPublishPrep(args: string[]): void {
|
|
3035
3715
|
const [workDir = '', runDate = '', artist = '', album = ''] = args;
|
|
3036
3716
|
const articlePath = join(workDir, '22-article', `${runDate}_06_article_content.json`);
|
|
@@ -5112,8 +5792,13 @@ export function dailyScriptCheck(args: string[]): void {
|
|
|
5112
5792
|
* `21-plan/<date>_03_curate_excluded.json`) against the QC candidates
|
|
5113
5793
|
* (`21-plan/<date>_04_quality-control-content_candidates.json`). Unwraps a `Content` envelope and
|
|
5114
5794
|
* dedups near-duplicate titles in place before `write` reads the plan. Writes
|
|
5115
|
-
* `21-plan/<date>_03_curate_errors.json` (`[{itemId, rule}]`) on failure and removes it on
|
|
5116
|
-
* With `--final`, falls back to the untranslated candidates and `[]` exclusions on failure.
|
|
5795
|
+
* `21-plan/<date>_03_curate_errors.json` (`[{itemId, rule, detail?}]`) on failure and removes it on
|
|
5796
|
+
* success. With `--final`, falls back to the untranslated candidates and `[]` exclusions on failure.
|
|
5797
|
+
*
|
|
5798
|
+
* 0433 R3/R4 adds one rule to that set: `cn-lead:XY-02` — the lead may not carry a 时政/贸易管制/
|
|
5799
|
+
* 公共安全审查 mainline on a CN-distributed cut (see `./cn-lead-gate.ts`). It is checked here, in the
|
|
5800
|
+
* plan stage, because here is the last place before the TTS spend that reads the order the episode will
|
|
5801
|
+
* be spoken and titled in.
|
|
5117
5802
|
*/
|
|
5118
5803
|
export function dailyCurateCheck(args: string[]): void {
|
|
5119
5804
|
const [workDir = '', runDate = '', flag = ''] = args;
|
|
@@ -5124,6 +5809,8 @@ export function dailyCurateCheck(args: string[]): void {
|
|
|
5124
5809
|
const planFile = join(workDir, '21-plan', `${runDate}_03_plan_plan.json`);
|
|
5125
5810
|
const excludedFile = join(workDir, '21-plan', `${runDate}_03_curate_excluded.json`);
|
|
5126
5811
|
const errFile = join(workDir, '21-plan', `${runDate}_03_curate_errors.json`);
|
|
5812
|
+
// 0433 R3/R4: the CN-lead refusal record — written only when no candidate can lead a CN cut.
|
|
5813
|
+
const cnLeadRefusal = join(workDir, '21-plan', `${runDate}_03_cn-lead-refusal.json`);
|
|
5127
5814
|
|
|
5128
5815
|
const candRaw = readJson(candidatesFile);
|
|
5129
5816
|
const candidateDocs: Record<string, unknown>[] = Array.isArray(candRaw)
|
|
@@ -5134,13 +5821,45 @@ export function dailyCurateCheck(args: string[]): void {
|
|
|
5134
5821
|
const candidateIds = candidateDocs.map((doc) => (typeof doc?.id === 'string' ? doc.id.trim() : '')).filter(Boolean);
|
|
5135
5822
|
const candidateIdSet = new Set(candidateIds);
|
|
5136
5823
|
|
|
5137
|
-
const handleErrors = (errors: { itemId: string; rule: string }[]): void => {
|
|
5824
|
+
const handleErrors = (errors: { itemId: string; rule: string; detail?: string }[]): void => {
|
|
5138
5825
|
if (isFinal) {
|
|
5139
5826
|
const reason = errors.map((e) => `${e.itemId}:${e.rule}`).join(', ');
|
|
5140
5827
|
console.error(
|
|
5141
5828
|
`curate-check: final check failed (${reason}) — falling back to ${candidateDocs.length} untranslated candidate(s)`,
|
|
5142
5829
|
);
|
|
5143
|
-
|
|
5830
|
+
// 0433 R2/R4: this path has no agent left — the `curate --fix` pass either never ran or did
|
|
5831
|
+
// not deliver, so the plan falls back to the raw candidates and nobody would remove a
|
|
5832
|
+
// CN-blocked lead from it. Apply the same demotion deterministically. A pool where EVERY
|
|
5833
|
+
// candidate trips has no lead this cut may carry: refuse here, before the TTS spend, instead
|
|
5834
|
+
// of paying for an episode the CN rows would drop (2026-11-24: 12.6 min of audio, two rows
|
|
5835
|
+
// excluded afterwards — the exact cost R4 exists to remove).
|
|
5836
|
+
const enforced = enforceCnLead(candidateDocs);
|
|
5837
|
+
const blocked = enforced.blocked;
|
|
5838
|
+
if (blocked !== null) {
|
|
5839
|
+
sted('write', cnLeadRefusal, () =>
|
|
5840
|
+
writeJqText(cnLeadRefusal, {
|
|
5841
|
+
rule: 'cn-lead:XY-02',
|
|
5842
|
+
ruleIds: ['XY-02', 'WX-01'],
|
|
5843
|
+
leadId: blocked.id,
|
|
5844
|
+
candidateIds,
|
|
5845
|
+
message: blocked.message,
|
|
5846
|
+
reason: `every one of the ${candidateDocs.length} candidate(s) trips the CN-blocked mainline vocabulary on the lead surface — refusing before any TTS spend, because no lead this cut may carry exists`,
|
|
5847
|
+
}),
|
|
5848
|
+
);
|
|
5849
|
+
if (isFile(errFile)) unlinkSync(errFile);
|
|
5850
|
+
failWith(1, blocked.message);
|
|
5851
|
+
}
|
|
5852
|
+
if (enforced.demoted !== null) {
|
|
5853
|
+
console.error(
|
|
5854
|
+
`curate-check: ${enforced.demoted.id} demoted from lead to position ${enforced.demoted.to} — the CN-blocked lead this cut may not carry (see cn-lead-gate.ts)`,
|
|
5855
|
+
);
|
|
5856
|
+
}
|
|
5857
|
+
if (enforced.weakLead !== null) {
|
|
5858
|
+
console.error(
|
|
5859
|
+
`curate-check: weak lead ${enforced.weakLead.id} (${enforced.weakLead.terms.join(', ')}) — no clean candidate, and it trips only the two-signal heuristic, so it leads instead of refusing the day (0438 R4)`,
|
|
5860
|
+
);
|
|
5861
|
+
}
|
|
5862
|
+
sted('write', planFile, () => writeJsonText(planFile, enforced.docs));
|
|
5144
5863
|
sted('write', excludedFile, () => writeJsonText(excludedFile, []));
|
|
5145
5864
|
if (isFile(errFile)) unlinkSync(errFile);
|
|
5146
5865
|
// Task 0392 R2: the recorded fallback IS the curation evidence for this attempt — the
|
|
@@ -5225,7 +5944,7 @@ export function dailyCurateCheck(args: string[]): void {
|
|
|
5225
5944
|
}
|
|
5226
5945
|
}
|
|
5227
5946
|
|
|
5228
|
-
const errors: { itemId: string; rule: string }[] = [];
|
|
5947
|
+
const errors: { itemId: string; rule: string; detail?: string }[] = [];
|
|
5229
5948
|
if (planDocs.length === 0) {
|
|
5230
5949
|
errors.push({ itemId: 'episode', rule: 'empty-plan' });
|
|
5231
5950
|
}
|
|
@@ -5256,7 +5975,18 @@ export function dailyCurateCheck(args: string[]): void {
|
|
|
5256
5975
|
}
|
|
5257
5976
|
}
|
|
5258
5977
|
|
|
5978
|
+
// 0433 R3/R4: the CN-platform lead constraint, enforced deterministically BEFORE the TTS spend.
|
|
5979
|
+
// The curator's biggest story can be the one `XY-02`/`WX-01` block, and the post-spend variants
|
|
5980
|
+
// review is where that used to surface (2026-11-24: 12.6 min of audio, two CN rows excluded).
|
|
5981
|
+
// Only the lead position is gated — the same story stays in scope as a body item (SKILL.md
|
|
5982
|
+
// shared rule 2), which is what the `curate --fix` pass does with this rule.
|
|
5983
|
+
const cnLead = checkCnLeadPlan(planDocs);
|
|
5984
|
+
if (!cnLead.ok) {
|
|
5985
|
+
errors.push({ itemId: cnLead.leadId ?? 'episode', rule: 'cn-lead:XY-02', detail: cnLead.message });
|
|
5986
|
+
}
|
|
5987
|
+
|
|
5259
5988
|
if (errors.length > 0) {
|
|
5989
|
+
if (!cnLead.ok) console.error(`curate-check: ${cnLead.message}`);
|
|
5260
5990
|
handleErrors(errors);
|
|
5261
5991
|
return;
|
|
5262
5992
|
}
|
|
@@ -6464,6 +7194,25 @@ export function reduceOverflowingPoints(points: string[], named: readonly number
|
|
|
6464
7194
|
changed = true;
|
|
6465
7195
|
}
|
|
6466
7196
|
}
|
|
7197
|
+
// When a long earlier point pushes a short trailing point out of the safe area, the composer
|
|
7198
|
+
// names the trailing index. Shorten the longest shrinkable point so the block fits.
|
|
7199
|
+
if (!changed) {
|
|
7200
|
+
let bestIndex = -1;
|
|
7201
|
+
let bestLen = 0;
|
|
7202
|
+
for (let i = 0; i < points.length; i++) {
|
|
7203
|
+
const point = points[i] ?? '';
|
|
7204
|
+
const next = shortenOverflowedPoint(point);
|
|
7205
|
+
if (next !== point && point.length > bestLen) {
|
|
7206
|
+
bestIndex = i;
|
|
7207
|
+
bestLen = point.length;
|
|
7208
|
+
}
|
|
7209
|
+
}
|
|
7210
|
+
if (bestIndex >= 0) {
|
|
7211
|
+
const point = points[bestIndex] ?? '';
|
|
7212
|
+
points[bestIndex] = shortenOverflowedPoint(point);
|
|
7213
|
+
changed = true;
|
|
7214
|
+
}
|
|
7215
|
+
}
|
|
6467
7216
|
if (!changed && points.length > XHS_MIN_POINTS) {
|
|
6468
7217
|
points.pop();
|
|
6469
7218
|
changed = true;
|