@gobing-ai/knowledge-kit 0.0.31 → 0.0.33

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 (79) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/index.js +32320 -15021
  3. package/package.json +4 -4
  4. package/plugins/generations/content-gen/dist/index.js +10 -9
  5. package/plugins/generations/core-facts-gen/dist/index.js +13 -12
  6. package/plugins/generations/daily-article-gen/dist/index.js +14 -13
  7. package/plugins/generations/daily-article-gen/src/index.ts +1 -1
  8. package/plugins/generations/dailynews-gen/dist/index.js +10 -9
  9. package/plugins/generations/episode-plan-gen/dist/index.js +58 -15
  10. package/plugins/generations/episode-plan-gen/src/index.ts +76 -6
  11. package/plugins/generations/gemini-tts/README.md +11 -0
  12. package/plugins/generations/gemini-tts/dist/index.js +10 -9
  13. package/plugins/generations/image-gen/dist/index.js +154 -151
  14. package/plugins/generations/image-gen/src/compose/chromium.ts +60 -42
  15. package/plugins/generations/news-report-gen/dist/index.js +13 -12
  16. package/plugins/generations/voice-gen/dist/index.js +10 -9
  17. package/plugins/ingestions/aihot-ingest/dist/index.js +13 -12
  18. package/plugins/ingestions/horizon-ingest/dist/index.js +13 -12
  19. package/plugins/ingestions/karakeep-local/dist/index.js +13 -13
  20. package/plugins/ingestions/last30days-ingest/dist/index.js +13 -12
  21. package/plugins/ingestions/web-search/dist/index.js +11 -10
  22. package/plugins/kk/README.md +38 -0
  23. package/plugins/kk/decisions/extract/ai-news.yaml +21 -0
  24. package/plugins/kk/decisions/kk-items.yaml +113 -0
  25. package/plugins/kk/plugin.json +1 -1
  26. package/plugins/kk/schedules/cron.tmpl +15 -0
  27. package/plugins/kk/schedules/launchd.plist.tmpl +77 -0
  28. package/plugins/kk/scripts/daily-stages.ts +1533 -0
  29. package/plugins/kk/scripts/kk-workflow-stages.ts +268 -1228
  30. package/plugins/kk/skills/content-judge/SKILL.md +12 -2
  31. package/plugins/kk/skills/content-judge/references/rubrics.md +8 -2
  32. package/plugins/kk/skills/content-safety/SKILL.md +60 -18
  33. package/plugins/kk/skills/web-automation/SKILL.md +100 -0
  34. package/plugins/kk/skills/web-automation/references/browser-launch.md +86 -0
  35. package/plugins/kk/workflows/kk-collect.yaml +258 -0
  36. package/plugins/kk/workflows/kk-daily-ai-voice.yaml +74 -11
  37. package/plugins/kk/workflows/kk-daily-ai-voice2.yaml +655 -0
  38. package/plugins/kk/workflows/kk-daily-safety.yaml +170 -0
  39. package/plugins/publishings/emdash-pub/dist/index.js +10 -9
  40. package/plugins/publishings/infoq-pub/dist/index.js +8695 -211
  41. package/plugins/publishings/infoq-pub/package.json +3 -1
  42. package/plugins/publishings/infoq-pub/plugin.json +2 -1
  43. package/plugins/publishings/infoq-pub/src/index.ts +358 -29
  44. package/plugins/publishings/infoq-pub/src/profile-check.ts +21 -0
  45. package/plugins/publishings/juejin-pub/dist/index.js +8746 -211
  46. package/plugins/publishings/juejin-pub/package.json +3 -1
  47. package/plugins/publishings/juejin-pub/plugin.json +2 -1
  48. package/plugins/publishings/juejin-pub/src/index.ts +345 -29
  49. package/plugins/publishings/juejin-pub/src/profile-check.ts +19 -0
  50. package/plugins/publishings/medium-pub/dist/index.js +10 -9
  51. package/plugins/publishings/podcast-pub/dist/index.js +10 -9
  52. package/plugins/publishings/qiita-pub/dist/index.js +10 -9
  53. package/plugins/publishings/substack-pub/dist/index.js +8687 -211
  54. package/plugins/publishings/substack-pub/package.json +3 -1
  55. package/plugins/publishings/substack-pub/plugin.json +2 -1
  56. package/plugins/publishings/substack-pub/src/index.ts +302 -29
  57. package/plugins/publishings/substack-pub/src/profile-check.ts +76 -0
  58. package/plugins/publishings/surfdash-pub/dist/index.js +10 -9
  59. package/plugins/publishings/wechatmp-pub/dist/index.js +1315 -352
  60. package/plugins/publishings/wechatmp-pub/plugin.json +1 -0
  61. package/plugins/publishings/wechatmp-pub/src/enrich.ts +229 -0
  62. package/plugins/publishings/wechatmp-pub/src/flow.ts +896 -0
  63. package/plugins/publishings/wechatmp-pub/src/index.ts +223 -520
  64. package/plugins/publishings/wechatmp-pub/src/modes.ts +403 -0
  65. package/plugins/publishings/wechatmp-pub/src/page.ts +260 -0
  66. package/plugins/publishings/wechatmp-pub/src/profile-check.ts +84 -38
  67. package/plugins/publishings/x-pub/dist/index.js +8707 -223
  68. package/plugins/publishings/x-pub/package.json +3 -1
  69. package/plugins/publishings/x-pub/plugin.json +2 -1
  70. package/plugins/publishings/x-pub/src/index.ts +315 -23
  71. package/plugins/publishings/x-pub/src/profile-check.ts +19 -0
  72. package/plugins/publishings/xhs-pub/dist/index.js +897 -354
  73. package/plugins/publishings/xhs-pub/plugin.json +2 -1
  74. package/plugins/publishings/xhs-pub/src/flow.ts +572 -0
  75. package/plugins/publishings/xhs-pub/src/index.ts +108 -596
  76. package/plugins/publishings/xhs-pub/src/modes.ts +300 -0
  77. package/plugins/publishings/xhs-pub/src/page.ts +254 -0
  78. package/plugins/publishings/xhs-pub/src/profile-check.ts +29 -17
  79. package/plugins/publishings/zenn-pub/dist/index.js +10 -9
@@ -0,0 +1,1533 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * daily-* stage bodies for the kk-daily-ai-voice2 DAG (task 0211, R7).
4
+ *
5
+ * Moved out of kk-workflow-stages.ts: every stage the voice2 graph touches is owned here so the
6
+ * plugin ships its stages beside the runner. kk-workflow-stages.ts lazy-loads this module through
7
+ * loadDailyStages() and keeps the same `kk stage <name>` surface; the old-voice-only stages stay
8
+ * in the runner until the legacy workflow retires.
9
+ *
10
+ * Shared helpers, sidecar paths and constants still live in kk-workflow-stages.ts and are
11
+ * imported from there — the lazy load keeps the module cycle safe.
12
+ */
13
+ /**
14
+ * Deterministic stage runner shared by the kk product workflows (ADR-115 composition owner).
15
+ *
16
+ * Each YAML action keeps one short package-root resolution block and delegates its multi-command
17
+ * body here, so a shell action stays a single logical call:
18
+ *
19
+ * prepare-itc <work_dir> <topic> <input_file> <force>
20
+ * prepare-solo <work_dir> <topic> <input_file> <voice_profile> <force>
21
+ * prepare-storm <work_dir> <topic> <input_file> <max_results> <fixture>
22
+ * validate [<override>] --in <voicescript.yaml>
23
+ * wrap [<override>] --in <voicescript.yaml> --out <docs.json> [--profile <name>]
24
+ * duration <work_dir> <target_duration_min>
25
+ * render-storm [<override>] --in <content.json> --out <content.md>
26
+ * itc-outline-pick <work_dir> (0149, body in the sibling itc-stages.ts)
27
+ * itc-report <work_dir> [max_revisions] (0149, body in the sibling itc-stages.ts)
28
+ * itc-materialize <work_dir> <publish_live> (0150, sibling)
29
+ * itc-publish-plan <work_dir> <targets> <source_locale> <publish_live> (0150, sibling)
30
+ * itc-publish-fanout <work_dir> [--retry] (0151, sibling)
31
+ * itc-publish-next <work_dir> (0151, sibling)
32
+ *
33
+ * `validate` / `wrap` / `render-storm` resolve the shipped sibling sidecars and delegate to them;
34
+ * nothing about those sidecars changed. The `prepare-*` verbs and `duration` keep the logic that
35
+ * used to live inline in `plugins/kk/workflows/*.yaml`, message-for-message.
36
+ *
37
+ * Node/Bun builtins only — no @gobing-ai/* and no cross-directory relative imports (the file is
38
+ * resolved from the installed package or from a checkout). The itc-* stages delegate to their
39
+ * same-directory sibling `itc-stages.ts`, imported lazily so a runner copy without the sibling
40
+ * still loads and fails loud with the remediation path.
41
+ *
42
+ * The YAML prelude resolves this file as `$pkg/plugins/kk/scripts/kk-workflow-stages.ts` where `pkg`
43
+ * comes from `realpath "$(command -v kk)"` (the installed package root), and falls back to the
44
+ * cwd-relative `plugins/kk/scripts/kk-workflow-stages.ts` when that copy is absent — the checkout
45
+ * tier kk-storm-research's render has always relied on, preserved on purpose. The daily-voice
46
+ * workflow reaches the same script through `kk stage` (apps/cli/src/stage.ts), which resolves a
47
+ * recognized checkout entry to this checked-in copy (never a stale `apps/cli/plugins/` stage) and an
48
+ * installed entry to its own package-shipped copy.
49
+ *
50
+ * SYNC: plugins/kk/workflows/{kk-solo-podcast,kk-itc,kk-storm-research}.yaml shell this script
51
+ * (kk-daily-ai-voice goes through `kk stage`). Keep message substrings stable —
52
+ * apps/cli/tests/kk-workflow-stages.test.ts and the four workflow static tests match them.
53
+ */
54
+ import { spawnSync } from 'node:child_process';
55
+ import { createHash } from 'node:crypto';
56
+ import {
57
+ copyFileSync,
58
+ existsSync,
59
+ mkdirSync,
60
+ readFileSync,
61
+ renameSync,
62
+ rmSync,
63
+ unlinkSync,
64
+ writeFileSync,
65
+ } from 'node:fs';
66
+ import { basename, join, resolve } from 'node:path';
67
+ import {
68
+ ADMISSION_CRITERIA,
69
+ applyTopicBoundary,
70
+ assertScriptContent,
71
+ COVER_FORMAT,
72
+ COVER_STYLE,
73
+ coverBrief,
74
+ coverNormalizeBody,
75
+ dedupPlanByTitle,
76
+ fail,
77
+ failWith,
78
+ firstArtifact,
79
+ firstPostPath,
80
+ isFile,
81
+ kk,
82
+ metadataOf,
83
+ NESTED_SPUR_UNSET,
84
+ PII_FINDING_CATEGORY,
85
+ pluginsArgs,
86
+ readJson,
87
+ readSafetyReviseCount,
88
+ readTopicBoundary,
89
+ requireJson,
90
+ requireSidecar,
91
+ resolveSidecar,
92
+ resultPublishStatus,
93
+ SAFETY_PLATFORM_DECISIONS,
94
+ SAFETY_REVISE_COUNT,
95
+ STYLE_SIDECAR,
96
+ StageFailure,
97
+ safetyDigest,
98
+ safetyDraftPaths,
99
+ safetyPath,
100
+ stampId3Tags,
101
+ sted,
102
+ targetPublished,
103
+ timed,
104
+ writeJqText,
105
+ writeJsonText,
106
+ writeRaw,
107
+ XHS_FORMAT,
108
+ XHS_MAX_CARDS,
109
+ xhsPlan,
110
+ } from './kk-workflow-stages.ts';
111
+
112
+ export function dailyQcContent(args: string[]): void {
113
+ const [
114
+ workDir = '',
115
+ runDate = '',
116
+ pluginsPath = '',
117
+ qcCategories = '',
118
+ minQuality = '',
119
+ minImportance = '',
120
+ minUrgency = '',
121
+ minImpact = '',
122
+ minEpisodeItems = '',
123
+ ] = args;
124
+ const candidates = join(workDir, '21-plan', `${runDate}_04_quality-control-content_candidates.json`);
125
+ const annotated = join(workDir, '21-plan', `${runDate}_04_quality-control-content_annotated.json`);
126
+ const exclusions = join(workDir, '21-plan', `${runDate}_04_quality-control-content_exclusions.json`);
127
+ const planContent = join(workDir, '21-plan', `${runDate}_03_plan_content.json`);
128
+ timed(workDir, 'quality-control-content', () => {
129
+ if (isFile(candidates)) {
130
+ console.log(`candidates cached: ${candidates}`);
131
+ return;
132
+ }
133
+ sted('write', annotated, () => writeJqText(annotated, metadataOf(readJson(planContent)).docs ?? null));
134
+ kk(
135
+ [
136
+ 'executor',
137
+ 'run',
138
+ 'episode-plan-gen',
139
+ '--in',
140
+ annotated,
141
+ '--out',
142
+ candidates,
143
+ ...pluginsArgs(pluginsPath),
144
+ ],
145
+ {
146
+ env: {
147
+ EPISODE_PLAN_MODE: 'filter',
148
+ QC_CATEGORIES: qcCategories,
149
+ QC_MIN_QUALITY: minQuality,
150
+ QC_MIN_IMPORTANCE: minImportance,
151
+ QC_MIN_URGENCY: minUrgency,
152
+ QC_MIN_IMPACT: minImpact,
153
+ QC_MIN_EPISODE_ITEMS: minEpisodeItems,
154
+ },
155
+ },
156
+ );
157
+ });
158
+ // Topic boundary (task 0189 R2) runs on every invocation — re-applying to already-filtered
159
+ // candidates is a no-op, so cached reruns stay idempotent while a crash between the candidates
160
+ // write and the exclusions write still converges on the next run. Zero kept docs leaves the
161
+ // candidates file empty for the workflow's existing done-no-content edge.
162
+ const boundaryDocs = metadataOf(readJson(candidates)).docs;
163
+ if (!Array.isArray(boundaryDocs)) return;
164
+ const { kept, excluded } = applyTopicBoundary(boundaryDocs, runDate, readTopicBoundary());
165
+ if (excluded.length === 0) return;
166
+ sted('write', exclusions, () =>
167
+ writeJsonText(exclusions, {
168
+ version: 1,
169
+ runDate,
170
+ excluded,
171
+ kept: kept.map((doc) => (doc as { id: string }).id),
172
+ }),
173
+ );
174
+ const content = requireJson(candidates, 'topic-boundary');
175
+ const meta = content.metadata;
176
+ if (meta === null || typeof meta !== 'object') {
177
+ failWith(1, 'topic-boundary: candidates content carries no metadata object');
178
+ }
179
+ (meta as Record<string, unknown>).docs = kept;
180
+ sted('write', candidates, () => writeJsonText(candidates, content));
181
+ console.log(
182
+ `topic-boundary: excluded ${excluded.length} item(s): ${excluded.map((entry) => `${entry.id}(${entry.rule})`).join(', ')}`,
183
+ );
184
+ }
185
+
186
+ /**
187
+ * Character-bigram Jaccard over whitespace-normalized, lowercased titles — the twin of
188
+ * episode-plan-gen's `titleSimilarity`. Duplicated on purpose: this file is node-builtins-only
189
+ * (no workspace imports), so it cannot reach that module.
190
+ */
191
+ export function dailyArticle(args: string[]): void {
192
+ const [workDir = '', runDate = '', pluginsPath = ''] = args;
193
+ const articleMd = join(workDir, '22-article', `${runDate}_06_article_article.md`);
194
+ const articleContent = join(workDir, '22-article', `${runDate}_06_article_content.json`);
195
+ const planIn = join(workDir, '21-plan', `${runDate}_03_plan_plan.json`);
196
+ const candidates = join(workDir, '21-plan', `${runDate}_04_quality-control-content_candidates.json`);
197
+ timed(workDir, 'article', () => {
198
+ let planUsable = true;
199
+ const raw = isFile(planIn) ? readFileSync(planIn, 'utf-8') : '';
200
+ try {
201
+ JSON.parse(raw);
202
+ } catch (error) {
203
+ console.error(
204
+ `article: plan.json invalid JSON — replacing with untranslated plan (downstream states read this file): ${(error as Error).message}`,
205
+ );
206
+ const docs = metadataOf(readJson(candidates)).docs;
207
+ if (!Array.isArray(docs) || docs.length === 0) {
208
+ console.error('article: candidates.json metadata.docs missing');
209
+ planUsable = false;
210
+ } else {
211
+ sted('write', planIn, () => writeJsonText(planIn, docs));
212
+ }
213
+ }
214
+ if (!planUsable) failWith(1, 'article: no usable plan input');
215
+ // R3 (task 0138): dedup runs BEFORE the cache early-return — the script stage reads this same
216
+ // plan.json and must see one survivor even when the article is already cached. Idempotent:
217
+ // a no-op once the plan is deduped.
218
+ const planParsed: unknown = readJson(planIn);
219
+ if (Array.isArray(planParsed)) {
220
+ const { kept, dropped } = dedupPlanByTitle(planParsed as Record<string, unknown>[]);
221
+ if (dropped.length > 0) {
222
+ sted('write', planIn, () => writeJsonText(planIn, kept));
223
+ console.error(`article: dropped ${dropped.length} near-duplicate plan item(s): ${dropped.join(', ')}`);
224
+ }
225
+ }
226
+ // The cache pair must be COMPLETE: markdown without its content.json means the generator
227
+ // half-ran (or the json was pruned), and returning here starves every downstream stage
228
+ // that reads content.json — publish-prep refuses to merge a draft it cannot read. Requiring
229
+ // both artifacts makes the pair self-healing instead of permanently stuck.
230
+ if (isFile(articleMd) && isFile(articleContent)) {
231
+ console.log(`article cached: ${articleMd}`);
232
+ return;
233
+ }
234
+ // Agent-written prose body (workflow `article-write` state) replaces the mechanical
235
+ // per-item render when present — the 3-format split: surfdash gets an article,
236
+ // not a news list (2026-09-16 feedback).
237
+ const proseBody = join(workDir, '22-article', `${runDate}_06_article-write_body.md`);
238
+ kk(
239
+ [
240
+ 'executor',
241
+ 'run',
242
+ 'daily-article-gen',
243
+ '--in',
244
+ planIn,
245
+ '--out',
246
+ articleContent,
247
+ ...pluginsArgs(pluginsPath),
248
+ ],
249
+ {
250
+ env: {
251
+ ARTICLE_DATE: runDate,
252
+ // Plugin entries run with cwd = plugin dir (invoke.ts), so relative
253
+ // paths in env must be resolved or the plugin sees ENOENT.
254
+ ...(isFile(proseBody) ? { ARTICLE_BODY_FILE: resolve(proseBody) } : {}),
255
+ },
256
+ },
257
+ );
258
+ const body = readJson(articleContent)?.body;
259
+ if (typeof body !== 'string') failWith(1, `article: ${articleContent} has no string body`);
260
+ sted('write', articleMd, () => writeRaw(articleMd, body));
261
+ });
262
+ }
263
+
264
+ // Shared opt-in fallback parse (D6 0166 R7; 0219 R1): '' keeps strict fail-fast (the caller
265
+ // omits the key), 'true' retries down image-gen's AUTO_ORDER, anything else is a comma-split,
266
+ // trimmed candidate list. Unknown names are rejected by image-gen, not here.
267
+ function imageFallback(fallback: string): true | string[] {
268
+ return fallback === 'true'
269
+ ? true
270
+ : fallback
271
+ .split(',')
272
+ .map((s) => s.trim())
273
+ .filter(Boolean);
274
+ }
275
+
276
+ /**
277
+ * F614 R2/R4: validate the agent-written cover brief in the order R4 names — the first failing
278
+ * check is the fallback reason; `reason: null` carries the trimmed subject.
279
+ */
280
+ /**
281
+ * F614 R3: build the image-gen envelope from the day's cover brief and render it. The subject is
282
+ * the only model-authored input (the workflow's brief agent.run wrote it); format, style,
283
+ * provider and model are pinned by this stage so no caller can drift the look. A missing or
284
+ * invalid brief degrades to the format's default subject (R4) — a plugin failure still fails
285
+ * the stage, matching the pre-F614 cover behavior.
286
+ */
287
+ export function dailyCover(args: string[]): void {
288
+ const [workDir = '', runDate = '', pluginsPath = '', provider = '', model = '', fallback = ''] = args;
289
+ const briefPath = join(workDir, '23-cover', `${runDate}_07_cover-brief.json`);
290
+ const envPath = join(workDir, '23-cover', `${runDate}_07_cover_image-gen-in.json`);
291
+ const contentOut = join(workDir, '23-cover', 'content.json');
292
+ timed(workDir, 'cover', () => {
293
+ const brief = coverBrief(briefPath);
294
+ const vars: Record<string, string> = {};
295
+ if (brief.reason !== null) {
296
+ console.error(`cover brief: fallback (${brief.reason})`);
297
+ } else {
298
+ vars.subject = brief.subject;
299
+ }
300
+ const imageGen: Record<string, unknown> = {
301
+ job: 'cover',
302
+ format: COVER_FORMAT,
303
+ style: COVER_STYLE,
304
+ vars,
305
+ maxImages: 1,
306
+ };
307
+ if (provider !== '') imageGen.provider = provider;
308
+ if (model !== '') imageGen.model = model;
309
+ // D6 0166 R7: runtime-fallback opt-in. '' (the shipped var default) keeps strict fail-fast —
310
+ // F614's pinned look stays the default; 'true' = retry down AUTO_ORDER; anything else is a
311
+ // comma-split, trimmed candidate list. Unknown names are rejected by image-gen, not here.
312
+ if (fallback !== '') imageGen.fallback = imageFallback(fallback);
313
+ sted('write', envPath, () =>
314
+ writeJsonText(envPath, [{ id: 'daily-cover', title: runDate, body: '', metadata: { imageGen } }]),
315
+ );
316
+ kk(['executor', 'run', 'image-gen', '--in', envPath, '--out', contentOut, ...pluginsArgs(pluginsPath)]);
317
+ });
318
+ }
319
+
320
+ export function dailyCoverNormalize(args: string[]): void {
321
+ const [workDir = '', runDate = ''] = args;
322
+ // The pre-0133 shell had no timing trap, so this stage is not `timed`; it still fails through
323
+ // `failWith`, which needs the named-failure handling `timed` gives the other stages.
324
+ try {
325
+ coverNormalizeBody(workDir, runDate);
326
+ } catch (error) {
327
+ if (error instanceof StageFailure) {
328
+ if (error.named) console.error(error.message);
329
+ process.exit(error.status);
330
+ }
331
+ console.error((error as Error).message);
332
+ process.exit(1);
333
+ }
334
+ }
335
+
336
+ /**
337
+ * 20260917 review #7: prepend the show's 8s intro sting to the generated audio.
338
+ * `intro_music` empty -> skip. Writes `<stem>.intro.wav` (original render kept), points
339
+ * `audioPath` at the merged file, extends `duration`, marks `introMerged` (idempotent).
340
+ */
341
+ /**
342
+ * Episode duration gate (standing requirement, 20261002): a daily episode must run 15–20 minutes
343
+ * (duration is authoritative; the 8–10-item figure is only an estimate). Reads the final audio
344
+ * content's `metadata.duration` — after the intro sting merged, this is the true episode length —
345
+ * and fails loud outside `[min, max]` seconds-worth of minutes. A missing duration is a failure,
346
+ * not a pass: the gate must never silently let an under-length episode through again.
347
+ */
348
+ export function dailyEpisodeDuration(args: string[]): void {
349
+ const [workDir = '', runDate = '', minArg = '', maxArg = ''] = args;
350
+ if (!workDir) fail('missing work_dir');
351
+ if (!runDate) fail('missing run_date');
352
+ const minMinutes = Number(minArg);
353
+ const maxMinutes = Number(maxArg);
354
+ if (!Number.isFinite(minMinutes) || minMinutes <= 0) fail(`invalid min_minutes: ${minArg || '(empty)'}`);
355
+ if (!Number.isFinite(maxMinutes) || maxMinutes < minMinutes) fail(`invalid max_minutes: ${maxArg || '(empty)'}`);
356
+ const contentPath = join(workDir, '30-audio', `${runDate}_11_generate_content.json`);
357
+ if (!isFile(contentPath)) failWith(1, `episode-duration: audio content not found: ${contentPath}`);
358
+ let raw: unknown;
359
+ try {
360
+ const parsed = JSON.parse(readFileSync(contentPath, 'utf-8')) as { metadata?: { duration?: unknown } };
361
+ raw = parsed.metadata?.duration;
362
+ } catch (error) {
363
+ if ((error as { code?: string }).code !== undefined) {
364
+ sted('read', contentPath, () => readFileSync(contentPath, 'utf-8'));
365
+ }
366
+ raw = undefined;
367
+ }
368
+ const seconds = typeof raw === 'number' ? raw : typeof raw === 'string' && raw.trim() !== '' ? Number(raw) : NaN;
369
+ if (!Number.isFinite(seconds) || seconds <= 0) {
370
+ failWith(1, `episode-duration: audio metadata.duration missing or not a number in ${contentPath}`);
371
+ }
372
+ const minutes = seconds / 60;
373
+ const shown = minutes.toFixed(1);
374
+ if (minutes < minMinutes) {
375
+ failWith(
376
+ 1,
377
+ `episode-duration: episode runs ${shown} min, below the ${minMinutes}–${maxMinutes} min requirement (duration is authoritative). The candidate pool is too thin — deepen per-item treatment or add items; do not ship a short episode silently.`,
378
+ );
379
+ }
380
+ if (minutes > maxMinutes) {
381
+ failWith(
382
+ 1,
383
+ `episode-duration: episode runs ${shown} min, above the ${minMinutes}–${maxMinutes} min requirement. Trim items or per-item treatment.`,
384
+ );
385
+ }
386
+ console.log(`episode-duration ok: ${shown} min within ${minMinutes}–${maxMinutes} min`);
387
+ }
388
+
389
+ export function dailyGenerate(args: string[]): void {
390
+ const [workDir = '', runDate = '', pluginsPath = '', transcodeMp3 = '', vdriver = ''] = args;
391
+ // 20260917 review: the workflow picks a voice driver by short name; both drivers' envs are
392
+ // passed unconditionally so switching `vdriver` needs no shell changes. Unknown -> fail loud.
393
+ const VOICE_DRIVERS: Record<string, string> = {
394
+ ominivoice: 'omni-voice-gen',
395
+ voicebox: 'voice-gen',
396
+ gemini: 'gemini-tts',
397
+ };
398
+ let voiceGenerator = VOICE_DRIVERS[vdriver];
399
+ if (!voiceGenerator) {
400
+ failWith(
401
+ 1,
402
+ `generate: unknown vdriver '${vdriver}' (expected one of: ${Object.keys(VOICE_DRIVERS).join(', ')})`,
403
+ );
404
+ }
405
+ const docs = join(workDir, '30-audio', `${runDate}_10_wrap-docs_docs.json`);
406
+ const content = join(workDir, '30-audio', `${runDate}_11_generate_content.json`);
407
+ timed(workDir, 'generate', () => {
408
+ if (isFile(content) && metadataOf(readJson(content)).qc !== undefined) {
409
+ const qc = metadataOf(readJson(content)).qc as Record<string, unknown> | undefined;
410
+ if (qc?.passed === true) {
411
+ console.log(`audio cached: ${content} (QC passed)`);
412
+ return;
413
+ }
414
+ }
415
+ // Gemini quota probe (20261006): the 06:00 cron hit gemini-3.8-flash-tts 429 with a
416
+ // multi-hour retry-after after the shared key's window drained overnight. One tiny
417
+ // render (~1 request) before the real episode; ANY probe failure (quota, key, network)
418
+ // flips this run to the local voicebox driver instead of dying mid-episode — voicebox
419
+ // needs no key. Operator decision 20261006: keep the gemini default + auto-fallback.
420
+ if (vdriver === 'gemini') {
421
+ const probeDir = join(workDir, '30-audio');
422
+ const probeIn = join(probeDir, '.gemini-probe-in.json');
423
+ const probeOut = join(probeDir, '.gemini-probe-out.json');
424
+ const docsList = readJson(docs) as Array<Record<string, unknown>>;
425
+ if (docsList.length > 0) {
426
+ writeJsonText(probeIn, [{ ...docsList[0], body: 'Hello.' }]);
427
+ const probe = spawnSync(
428
+ 'kk',
429
+ ['executor', 'run', 'gemini-tts', '--in', probeIn, '--out', probeOut, ...pluginsArgs(pluginsPath)],
430
+ { encoding: 'utf8', timeout: 120_000, env: { ...process.env, VOICE_GEN_MP3: transcodeMp3 } },
431
+ );
432
+ for (const stale of [
433
+ probeIn,
434
+ probeOut,
435
+ probeOut.replace(/\.json$/, '.wav'),
436
+ probeOut.replace(/\.json$/, '.mp3'),
437
+ ])
438
+ rmSync(stale, { force: true });
439
+ if (probe.status !== 0) {
440
+ const reason = (probe.stderr ?? '').trim().split('\n').slice(-1)[0] || `exit ${probe.status}`;
441
+ console.log(
442
+ `generate: gemini quota probe failed (${reason}) — falling back to voicebox for this run`,
443
+ );
444
+ voiceGenerator = VOICE_DRIVERS.voicebox;
445
+ } else {
446
+ console.log('generate: gemini quota probe ok');
447
+ }
448
+ }
449
+ }
450
+ kk(['executor', 'run', voiceGenerator, '--in', docs, '--out', content, ...pluginsArgs(pluginsPath)], {
451
+ env: { VOICE_GEN_MP3: transcodeMp3 },
452
+ });
453
+ });
454
+ }
455
+
456
+ /**
457
+ * 20260917 review #7: prepend the show's 8s intro sting to the generated audio.
458
+ * `intro_music` empty -> skip. Writes `<stem>.intro.wav` (original render kept), points
459
+ * `audioPath` at the merged file, extends `duration`, marks `introMerged` (idempotent).
460
+ */
461
+ /**
462
+ * Episode duration gate (standing requirement, 20261002): a daily episode must run 15–20 minutes
463
+ * (duration is authoritative; the 8–10-item figure is only an estimate). Reads the final audio
464
+ * content's `metadata.duration` — after the intro sting merged, this is the true episode length —
465
+ * and fails loud outside `[min, max]` seconds-worth of minutes. A missing duration is a failure,
466
+ * not a pass: the gate must never silently let an under-length episode through again.
467
+ */
468
+ export function dailyIntro(args: string[]): void {
469
+ const [workDir = '', runDate = '', introSrc = ''] = args;
470
+ if (!introSrc || introSrc.trim() === '') {
471
+ console.log('intro-music: intro_music var empty — skip');
472
+ return;
473
+ }
474
+ const contentPath = join(workDir, '30-audio', `${runDate}_11_generate_content.json`);
475
+ timed(workDir, 'intro-music', () => {
476
+ const content = requireJson(contentPath, 'intro-music');
477
+ const meta = metadataOf(content);
478
+ if (meta.introMerged === true) {
479
+ console.log(`intro-music cached: ${contentPath}`);
480
+ return;
481
+ }
482
+ // Merge from the raw lossless render; mp3Path is the derived publish artifact.
483
+ // Preferring mp3Path here made `<stem>.mp3` the concat input while the output
484
+ // suffix rewrite (`.wav` -> `.intro.wav`) no longer matched, so ffmpeg saw one
485
+ // path as both input #1 and output and aborted with "same as Input #1".
486
+ const candidates = [meta.audioPath, meta.mp3Path].filter(
487
+ (candidate): candidate is string => typeof candidate === 'string' && candidate !== '',
488
+ );
489
+ const rawFile = candidates.find((candidate) => existsSync(resolve(candidate))) ?? candidates[0];
490
+ if (rawFile === undefined) {
491
+ failWith(1, 'intro-music: voice content carries no mp3Path/audioPath');
492
+ }
493
+ const introPath = resolve(introSrc);
494
+ if (!existsSync(introPath)) failWith(1, `intro-music: intro file not found: ${introPath}`);
495
+ const mainPath = resolve(rawFile);
496
+ if (!existsSync(mainPath)) failWith(1, `intro-music: generated audio not found: ${mainPath}`);
497
+ const mergedPath = `${mainPath.replace(/\.(wav|mp3)$/i, '')}.intro.wav`;
498
+ const probe = (file: string, entries: string): string =>
499
+ spawnSync('ffprobe', [
500
+ '-v',
501
+ 'error',
502
+ '-select_streams',
503
+ 'a:0',
504
+ '-show_entries',
505
+ entries,
506
+ '-of',
507
+ 'csv=p=0',
508
+ file,
509
+ ])
510
+ .stdout?.toString()
511
+ .trim() ?? '';
512
+ const mainDur = Number.parseFloat(probe(mainPath, 'format=duration'));
513
+ const introDur = Number.parseFloat(probe(introPath, 'format=duration'));
514
+ if (!Number.isFinite(mainDur) || !Number.isFinite(introDur)) {
515
+ failWith(1, `intro-music: ffprobe could not read durations (main=${mainDur} intro=${introDur})`);
516
+ }
517
+ const rate = probe(mainPath, 'stream=sample_rate') || '24000'; // match the generated audio's rate; mono s16 both sides
518
+ const norm = (label: string): string =>
519
+ `[${label}:a]aresample=${rate},aformat=sample_fmts=s16:channel_layouts=mono[${label}]`;
520
+ const fc = `${norm('0')};${norm('1')};[0][1]concat=n=2:v=0:a=1[out]`;
521
+ const conv = spawnSync('ffmpeg', [
522
+ '-y',
523
+ '-hide_banner',
524
+ '-loglevel',
525
+ 'error',
526
+ '-i',
527
+ introPath,
528
+ '-i',
529
+ mainPath,
530
+ '-filter_complex',
531
+ fc,
532
+ '-map',
533
+ '[out]',
534
+ '-c:a',
535
+ 'pcm_s16le',
536
+ mergedPath,
537
+ ]);
538
+ if (conv.status !== 0 || !existsSync(mergedPath)) {
539
+ failWith(1, `intro-music: ffmpeg concat failed: ${conv.stderr?.toString().trim()}`);
540
+ }
541
+ if (meta.mp3Path && typeof meta.mp3Path === 'string') {
542
+ // transcode_mp3=true: keep the mp3 path honest by re-transcoding the merged wav.
543
+ const mp3 = spawnSync('ffmpeg', [
544
+ '-y',
545
+ '-hide_banner',
546
+ '-loglevel',
547
+ 'error',
548
+ '-i',
549
+ mergedPath,
550
+ '-codec:a',
551
+ 'libmp3lame',
552
+ '-qscale:a',
553
+ '2',
554
+ resolve(meta.mp3Path),
555
+ ]);
556
+ if (mp3.status !== 0) failWith(1, `intro-music: mp3 re-transcode failed: ${mp3.stderr?.toString().trim()}`);
557
+ }
558
+ const mergedDur = Number.parseFloat(probe(mergedPath, 'format=duration')) || mainDur + introDur;
559
+ const updated = {
560
+ ...content,
561
+ metadata: {
562
+ ...meta,
563
+ audioPath: mergedPath,
564
+ duration: mergedDur,
565
+ introMerged: true,
566
+ },
567
+ };
568
+ sted('write', contentPath, () => writeJsonText(contentPath, updated));
569
+ console.log(
570
+ `intro-music: merged ${introDur.toFixed(1)}s intro -> ${mergedPath} (${mergedDur.toFixed(1)}s total)`,
571
+ );
572
+ });
573
+ }
574
+
575
+ export function dailyPlan(args: string[]): void {
576
+ const [workDir = '', runDate = '', pluginsPath = '', planMaxItems = ''] = args;
577
+ const planContent = join(workDir, '21-plan', `${runDate}_03_plan_content.json`);
578
+ const planDocs = join(workDir, '21-plan', `${runDate}_03_plan_plan.json`);
579
+ // voice2's extract node writes 10-collect/pool.json; voice1's fan-in still writes the blended
580
+ // file. Prefer the pool when it exists so both DAGs share this stage (0212 dogfood finding).
581
+ const pool = join(workDir, '10-collect', 'pool.json');
582
+ const blended = isFile(pool) ? pool : join(workDir, '10-ingest', `${runDate}_02_collect_blended.json`);
583
+ timed(workDir, 'plan', () => {
584
+ if (isFile(planDocs)) {
585
+ console.log(`plan cached: ${planDocs}`);
586
+ return;
587
+ }
588
+ kk(
589
+ ['executor', 'run', 'episode-plan-gen', '--in', blended, '--out', planContent, ...pluginsArgs(pluginsPath)],
590
+ {
591
+ env: { EPISODE_PLAN_MAX_ITEMS: planMaxItems, EPISODE_PLAN_DATE: runDate },
592
+ },
593
+ );
594
+ const docs = metadataOf(readJson(planContent)).docs;
595
+ if (!Array.isArray(docs) || docs.length === 0) failWith(1, 'plan: content.metadata.docs missing or empty');
596
+ sted('write', planDocs, () => writeJsonText(planDocs, docs));
597
+ if (!isFile(planDocs)) failWith(1, `plan: ${planDocs} not written after episode-plan-gen`);
598
+ });
599
+ }
600
+
601
+ /**
602
+ * Topic-boundary sidecar (task 0189 R2). Sibling of this file; node-builtins-only read.
603
+ */
604
+ export function dailyPublishPodcast(args: string[]): void {
605
+ const [workDir = '', runDate = '', pluginsPath = ''] = args;
606
+ const prep = join(workDir, '31-publish', `${runDate}_13_publish-prep_content.json`);
607
+ const notes = join(workDir, '31-publish', `${runDate}_15_show-notes_show-notes.md`);
608
+ const result = join(workDir, '31-publish', `${runDate}_16_publish-podcast_result.json`);
609
+ timed(workDir, 'publish-podcast', () => {
610
+ if (targetPublished(result, 'podcast-pub')) {
611
+ console.log(`publish-podcast cached: podcast target ok in ${result}`);
612
+ return;
613
+ }
614
+ try {
615
+ const content = requireJson(prep, 'publish-podcast');
616
+ const showNotes = readFileSync(notes, 'utf-8');
617
+ const merged = { ...content, metadata: { ...metadataOf(content), showNotes } };
618
+ sted('write', prep, () => writeJsonText(prep, merged));
619
+ kk(
620
+ [
621
+ 'executor',
622
+ 'fan-out',
623
+ '--content',
624
+ prep,
625
+ '--target',
626
+ 'podcast-pub',
627
+ '--out',
628
+ result,
629
+ ...pluginsArgs(pluginsPath),
630
+ ],
631
+ {
632
+ unset: ['SPUR_WORKFLOW_RUN_ACTIVE'],
633
+ soft: true,
634
+ },
635
+ );
636
+ } catch (error) {
637
+ // The shell's `… && … || true` swallowed both steps' failures — but an unusable `kk`
638
+ // (exit 127) is an environment failure, not a tolerated plugin failure.
639
+ if (error instanceof StageFailure && error.status === 127) throw error;
640
+ console.error((error as Error).message);
641
+ }
642
+ console.log('publish-podcast: podcast target dispatched');
643
+ });
644
+ }
645
+
646
+ export function dailyPublishPrep(args: string[]): void {
647
+ const [workDir = '', runDate = '', artist = '', album = ''] = args;
648
+ const articlePath = join(workDir, '22-article', `${runDate}_06_article_content.json`);
649
+ const audioPath = join(workDir, '30-audio', `${runDate}_11_generate_content.json`);
650
+ const prepPath = join(workDir, '31-publish', `${runDate}_13_publish-prep_content.json`);
651
+ const coverPath = join(workDir, '23-cover', `${runDate}_07_cover_cover.png`);
652
+ timed(workDir, 'publish-prep', () => {
653
+ const article = requireJson(articlePath, 'publish-prep');
654
+ const audioMeta = metadataOf(readJson(audioPath));
655
+ const rawFile = audioMeta.mp3Path ?? audioMeta.audioPath;
656
+ if (typeof rawFile !== 'string' || rawFile === '') {
657
+ failWith(1, 'publish-prep: voice content carries no mp3Path/audioPath');
658
+ }
659
+ const audioFile = resolve(rawFile);
660
+ // 0171 R2: publish-prep publishes metadata.mp3Path ?? audioPath, so a WAV here means
661
+ // transcode_mp3 was turned off — the run would ship an enclosure Apple Podcasts rejects.
662
+ if (!audioFile.endsWith('.mp3')) {
663
+ failWith(1, `publish-prep: resolved audio is not an MP3 (transcode_mp3 must be "true"): ${audioFile}`);
664
+ }
665
+ stampId3Tags(audioFile, typeof article.title === 'string' ? article.title : '', runDate, artist, album);
666
+ const resolvedCover = resolve(coverPath);
667
+ const hasCover = existsSync(resolvedCover);
668
+ // Daily-show itunes convention: season = year, episode = day-of-year. run_date arrives
669
+ // dashed (`$(date +%F)`) or digits-only (formatRunDate); map.ts forwards numbers only,
670
+ // so a malformed run_date omits both tags instead of failing the publish.
671
+ const digits = runDate.replaceAll(/\D/g, '');
672
+ const season = Number(digits.slice(0, 4));
673
+ const month = Number(digits.slice(4, 6));
674
+ const day = Number(digits.slice(6, 8));
675
+ const episode =
676
+ digits.length === 8 && month >= 1 && month <= 12 && day >= 1 && day <= 31
677
+ ? Math.round((Date.UTC(season, month - 1, day) - Date.UTC(season, 0, 1)) / 86_400_000) + 1
678
+ : 0;
679
+ // podcast-pub's documented contract reads metadata.coverImage (map.ts); options.coverPath
680
+ // alone was silently dropped by the mapper — episodes published without a cover.
681
+ const merged = {
682
+ ...article,
683
+ metadata: {
684
+ ...metadataOf(article),
685
+ audioFile,
686
+ runDate,
687
+ ...(hasCover ? { coverImage: resolvedCover } : {}),
688
+ ...(episode > 0 ? { itunes: { season, episode } } : {}),
689
+ },
690
+ options: {
691
+ audioFile,
692
+ durationSec: audioMeta.duration,
693
+ coverPath: hasCover ? resolvedCover : undefined,
694
+ },
695
+ };
696
+ // Task 0189 R10: the last program seam before anything is dispatched. No stamp, or a
697
+ // stamp issued on different bytes (edited after PASS, or an older draft), never publishes.
698
+ const stamp = readJson(safetyPath(workDir, runDate, 'safety-judge_stamp.json'));
699
+ if (stamp === null) failWith(1, 'publish-prep: no content-safety verdict stamp for this run — not publishing');
700
+ // 20261005: pass/escalate/exclude all stamp the drafts as publishable; only `block` (draft
701
+ // integrity) has no stamp. An `exclude` stamp carries the admission-blocked platforms so
702
+ // the per-target stages can skip those targets instead of failing the run.
703
+ if (stamp.status !== 'pass' && stamp.status !== 'escalate' && stamp.status !== 'exclude') {
704
+ failWith(1, `publish-prep: content-safety status ${String(stamp.status)} does not publish`);
705
+ }
706
+ if (stamp.digest !== safetyDigest(workDir, runDate)) {
707
+ failWith(1, 'publish-prep: drafts changed after the content-safety verdict — re-run the review');
708
+ }
709
+ const excludedPlatforms = Array.isArray(stamp.excludedPlatforms) ? (stamp.excludedPlatforms as string[]) : [];
710
+ if (excludedPlatforms.length > 0) {
711
+ console.log(`publish-prep: content-safety excluded platforms: ${excludedPlatforms.join(', ')}`);
712
+ }
713
+ sted('write', prepPath, () =>
714
+ writeJsonText(prepPath, {
715
+ ...merged,
716
+ metadata: { ...metadataOf(merged), safetyExcludedPlatforms: excludedPlatforms },
717
+ }),
718
+ );
719
+ });
720
+ }
721
+
722
+ export function dailyPublishSurfdash(args: string[]): void {
723
+ const [workDir = '', runDate = '', pluginsPath = ''] = args;
724
+ const prep = join(workDir, '31-publish', `${runDate}_13_publish-prep_content.json`);
725
+ const result = join(workDir, '31-publish', `${runDate}_14_publish-surfdash_result.json`);
726
+ timed(workDir, 'publish-surfdash', () => {
727
+ if (targetPublished(result, 'surfdash-pub')) {
728
+ console.log(`publish-surfdash cached: surfdash target ok in ${result}`);
729
+ return;
730
+ }
731
+ kk(
732
+ [
733
+ 'executor',
734
+ 'fan-out',
735
+ '--content',
736
+ prep,
737
+ '--target',
738
+ 'surfdash-pub',
739
+ '--out',
740
+ result,
741
+ ...pluginsArgs(pluginsPath),
742
+ ],
743
+ {
744
+ unset: NESTED_SPUR_UNSET,
745
+ soft: true,
746
+ },
747
+ );
748
+ console.log('publish-surfdash: surfdash target dispatched; classification happens after podcast publish');
749
+ });
750
+ }
751
+
752
+ /**
753
+ * WeChat MP: drive the console via `wechatmp-pub`'s browser transport and save the article to the
754
+ * draft box (草稿箱). Draft by default; the 发表 flow runs only on an explicit launch-time
755
+ * `wechat_live=true` (ADR-022 rail, same as xhs). Independent and non-blocking like XHS: the
756
+ * outcome never enters `publish_status` (surfdash + podcast remain the publication contract).
757
+ */
758
+ export function dailyPublishWechat(args: string[]): void {
759
+ const [workDirRaw = '', runDate = '', pluginsPath = '', live = 'false', collectionArg = ''] = args;
760
+ // Metadata carries file paths consumed by the plugin child process (cwd = plugin dir) - never emit relatives.
761
+ const workDir = resolve(workDirRaw);
762
+ const article = join(workDir, '22-article', `${runDate}_06_article_content.json`);
763
+ const input = join(workDir, '31-publish', `${runDate}_20_publish-wechat_content.json`);
764
+ const result = join(workDir, '31-publish', `${runDate}_20_publish-wechat_result.json`);
765
+ const want = live === 'true' ? 'public' : 'draft';
766
+ timed(workDir, 'publish-wechat', () => {
767
+ // Cache on the *requested* status: a cached draft must not silently satisfy a later
768
+ // wechat_live=true re-run (that would report a live post that never happened).
769
+ if (resultPublishStatus(result) === want) {
770
+ console.log(`publish-wechat cached: ${want} already recorded in ${result}`);
771
+ return;
772
+ }
773
+ // 20261005: a platform the content-safety gate excluded never gets a draft. Skipping here
774
+ // keeps the run alive for the targets that did pass, which is the point of the gate.
775
+ const safety = readJson(safetyPath(workDir, runDate, 'safety-judge_stamp.json'));
776
+ const excluded = Array.isArray(safety?.excludedPlatforms) ? (safety.excludedPlatforms as string[]) : [];
777
+ if (excluded.includes('wechatmp')) {
778
+ console.log(`publish-wechat: SKIPPED — content-safety excluded wechatmp for this run`);
779
+ return;
780
+ }
781
+ if (!isFile(article)) {
782
+ console.log(`publish-wechat: no article at ${article} — skip`);
783
+ return;
784
+ }
785
+ const packaged = requireJson(article, 'publish-wechat');
786
+ // MP draft enrichment (operator preference 2026-09-29): 原创+作者, 赞赏, 合集, 原文链接
787
+ // (the surfdash post), AI 生成声明, cover. The brand strings are this daily show's constants.
788
+ const cover = join(workDir, '23-cover', `${runDate}_07_cover_cover.png`);
789
+ const audio = join(workDir, '30-audio', `${runDate}_11_generate_content.mp3`);
790
+ const wechatmp: Record<string, unknown> = {
791
+ original: true,
792
+ aiGenerated: true,
793
+ author: '冰原奔狼',
794
+ collection: collectionArg || 'AI 乱炖',
795
+ ...(isFile(cover) ? { coverPath: cover } : {}),
796
+ // Audio block at the article top (operator request 2026-09-29): the daily MP3 goes to
797
+ // the 素材库 under the article title; the plugin reuses an existing same-title material.
798
+ ...(isFile(audio)
799
+ ? {
800
+ audioPath: audio,
801
+ audioTitle: typeof packaged.title === 'string' ? packaged.title : '',
802
+ audioCoverPath: isFile(cover) ? cover : '',
803
+ }
804
+ : {}),
805
+ };
806
+ // WeChat-only closing line (operator request 2026-09-29): point readers/listeners back to
807
+ // the show's platforms. Appended to the wechat input body only, never the master article.
808
+ const outro = '\n\n欲听往期节目,可至小宇宙、Apple Podcast、YouTube 等平台搜索【咸话咸说】。';
809
+ sted('write', input, () =>
810
+ writeJsonText(input, {
811
+ ...packaged,
812
+ body: `${typeof packaged.body === 'string' ? packaged.body : ''}${outro}`,
813
+ metadata: { ...metadataOf(packaged), publishStatus: want, wechatmp },
814
+ }),
815
+ );
816
+ // `soft` keeps the WeChat target non-blocking: the plugin still writes its own failed Result
817
+ // and prints the failing step (session preflight, editor paste, save control), which is what
818
+ // the operator needs to re-run — never a silent skip.
819
+ const status = kk(
820
+ ['executor', 'run', 'wechatmp-pub', '--in', input, '--out', result, ...pluginsArgs(pluginsPath)],
821
+ {
822
+ soft: true,
823
+ },
824
+ );
825
+ console.log(
826
+ status === 0
827
+ ? `publish-wechat: ${want} dispatched; outcome recorded in ${result}`
828
+ : `WARNING: publish-wechat — wechatmp-pub exited ${status}; WeChat target skipped (run continues, see ${result})`,
829
+ );
830
+ });
831
+ }
832
+
833
+ /**
834
+ * F613 R1: snapshot the shipped style contract into the run's work dir. Spur workflows have no
835
+ * workflow-dir var, so the script-write prompt reads this copy — and the snapshot freezes the
836
+ * exact contract the run's plan was written against. Idempotent (an existing snapshot is kept);
837
+ * a missing sidecar is a broken install, so `requireSidecar` fails loud.
838
+ */
839
+ /**
840
+ * E8: publish the packaged card series through `xhs-pub`'s script driver. Draft by default; live
841
+ * only on an explicit launch-time `xhs_live=true` (ADR-022 — an unattended run never posts live on
842
+ * its own). Non-blocking by operator decision: a missing/expired XHS session or a changed console
843
+ * logs a loud failure and leaves the run alive, and the outcome never enters `publish_status`
844
+ * (surfdash + podcast remain the episode's publication contract).
845
+ */
846
+ export function dailyPublishXhs(args: string[]): void {
847
+ const [workDir = '', runDate = '', pluginsPath = '', live = 'false'] = args;
848
+ const content = join(workDir, '25-xhs', 'content.json');
849
+ const input = join(workDir, '31-publish', `${runDate}_19_publish-xhs_content.json`);
850
+ const result = join(workDir, '31-publish', `${runDate}_19_publish-xhs_result.json`);
851
+ const want = live === 'true' ? 'public' : 'draft';
852
+ timed(workDir, 'publish-xhs', () => {
853
+ // Cache on the *requested* status: a cached draft must not silently satisfy a later
854
+ // xhs_live=true re-run (that would report a live post that never happened).
855
+ if (resultPublishStatus(result) === want) {
856
+ console.log(`publish-xhs cached: ${want} already recorded in ${result}`);
857
+ return;
858
+ }
859
+ if (!isFile(content)) {
860
+ console.log(`publish-xhs: no card series at ${content} (render packaged none) — skip`);
861
+ return;
862
+ }
863
+ const packaged = requireJson(content, 'publish-xhs');
864
+ sted('write', input, () =>
865
+ writeJsonText(input, { ...packaged, metadata: { ...metadataOf(packaged), publishStatus: want } }),
866
+ );
867
+ // `soft` keeps the XHS target non-blocking: the plugin still writes its own failed Result
868
+ // and prints the failing step (login gate, upload, body, submit control), which is what the
869
+ // operator needs to re-run — never a silent skip.
870
+ const status = kk(['executor', 'run', 'xhs-pub', '--in', input, '--out', result, ...pluginsArgs(pluginsPath)], {
871
+ soft: true,
872
+ });
873
+ console.log(
874
+ status === 0
875
+ ? `publish-xhs: ${want} dispatched; outcome recorded in ${result}`
876
+ : `WARNING: publish-xhs — xhs-pub exited ${status}; XHS target skipped (run continues, see ${result})`,
877
+ );
878
+ });
879
+ }
880
+
881
+ /**
882
+ * WeChat MP: drive the console via `wechatmp-pub`'s browser transport and save the article to the
883
+ * draft box (草稿箱). Draft by default; the 发表 flow runs only on an explicit launch-time
884
+ * `wechat_live=true` (ADR-022 rail, same as xhs). Independent and non-blocking like XHS: the
885
+ * outcome never enters `publish_status` (surfdash + podcast remain the publication contract).
886
+ */
887
+ export function dailyQualityReport(args: string[]): void {
888
+ const [workDir = '', runDate = ''] = args;
889
+ const content = join(workDir, '30-audio', `${runDate}_11_generate_content.json`);
890
+ timed(workDir, 'quality-control', () => {
891
+ const qc = metadataOf(readJson(content)).qc as Record<string, unknown> | undefined;
892
+ console.log('=== Voice Quality Control Report ===');
893
+ console.log(`Overall Score: ${qc ? qc.overallScore : 100}/100 | Passed: ${qc ? qc.passed : true}`);
894
+ const issues = qc?.criticalIssues;
895
+ if (Array.isArray(issues) && issues.length > 0) {
896
+ console.warn(`QC Issues:\n${issues.map((issue) => ` - ${issue}`).join('\n')}`);
897
+ } else {
898
+ console.log('All audio segments passed quality control checks cleanly.');
899
+ }
900
+ });
901
+ }
902
+
903
+ /**
904
+ * 0171 R3: Apple Podcasts reads the enclosure's ID3 tags, so the published MP3 carries
905
+ * title/artist/album/date. `-c copy` moves the audio frames without a re-encode, and the temp
906
+ * file + rename keeps a failed ffmpeg from truncating the episode in place. An empty value
907
+ * omits that tag rather than failing. The caller runs this after intro-music, whose mp3
908
+ * re-transcode would otherwise strip tags stamped earlier.
909
+ */
910
+ /**
911
+ * Consume the content-safety report and the content-judge verdict into a publish decision (exit 0 in
912
+ * every case — routing is transition-owned). The gate's job is to *adjust*, not to kill the run
913
+ * (20261005 operator decision): a non-PASS verdict first routes back through one bounded
914
+ * draft-remediation loop (`revise`), and what survives the loop is classified by what it is:
915
+ *
916
+ * - `revise` — non-PASS and the remediation budget is not spent: re-review after the drafts change.
917
+ * - `exclude` — admission-only residue (the CN 资质口径 / 播报形态 findings): the platforms that
918
+ * BLOCKed are dropped from this run and every other target publishes normally. Also
919
+ * the 20261007 narrowing: RISK whose findings are all gap/note/fix publishes at
920
+ * recorded risk with nothing dropped (empty `excludedPlatforms`).
921
+ * - `escalate` — a finding the reviewer marked `disposition: "escalate"` on an otherwise clean
922
+ * pass: human review. Legacy reports (no `disposition` field anywhere) keep the old
923
+ * rule — any RISK decision or report-level `escalate: true` pauses (20261007 ADR).
924
+ * - `pass` — explicit PASS verdict, unchanged drafts, no BLOCK and no RISK finding at all.
925
+ * - `block` — draft integrity: PII reported on a blocked platform, or a judge must-pass `fail`
926
+ * outside `jurisdictional-rules` (prohibited claims / disclosure / data-handling);
927
+ * also an unreadable or out-of-contract report/verdict, a non-PASS that documents
928
+ * nothing, or drafts edited after the review. Never published.
929
+ *
930
+ * Fail-closed where it matters: a missing report, verdict or confidence still blocks.
931
+ */
932
+ export function dailySafetyGate(args: string[]): void {
933
+ const [workDir = '', runDate = '', maxReviseArg = '0'] = args;
934
+ const maxRevise = Number.parseInt(maxReviseArg, 10);
935
+ const statusFile = safetyPath(workDir, runDate, 'safety-judge_status.txt');
936
+ const stampFile = safetyPath(workDir, runDate, 'safety-judge_stamp.json');
937
+ timed(workDir, 'safety-judge', () => {
938
+ const request = readJson(safetyPath(workDir, runDate, 'safety-review_request.json'));
939
+ const report = readJson(safetyPath(workDir, runDate, 'safety-review_report.json'));
940
+ const verdict = readJson(safetyPath(workDir, runDate, 'safety-judge_verdict.json'));
941
+ const platforms = Array.isArray(report?.platforms) ? (report.platforms as Record<string, unknown>[]) : [];
942
+ const decisions = platforms.map((platform) => platform?.decision);
943
+ const digest = safetyDigest(workDir, runDate);
944
+ const revisions = readSafetyReviseCount(workDir);
945
+ const platformFindings = (platform: Record<string, unknown>): Record<string, unknown>[] =>
946
+ Array.isArray(platform?.findings) ? (platform.findings as Record<string, unknown>[]) : [];
947
+ // 20261007 narrowing (operator decision): on a clean pass, only a finding the reviewer
948
+ // explicitly marked `disposition: "escalate"` is a human decision. Evidence gaps, note-class
949
+ // and fix-class RISK are recorded but route to `exclude` at recorded risk instead of pausing
950
+ // an unattended run. Back-compat, fail-closed: a report with no `disposition` field keeps the
951
+ // legacy rule — any RISK decision or report-level escalate pauses.
952
+ const allFindings = platforms.flatMap(platformFindings);
953
+ const usesDisposition = allFindings.some((finding) => typeof finding?.disposition === 'string');
954
+ const escalatedFindings = allFindings.filter((finding) => finding?.disposition === 'escalate');
955
+ const risky = usesDisposition
956
+ ? escalatedFindings.length > 0
957
+ : decisions.includes('RISK') || report?.escalate === true;
958
+ // 20261007 amendment: a report that self-classifies with dispositions must also self-grade
959
+ // its confidence (HIGH|MEDIUM|LOW), mirroring the 20261003 verdict-confidence hardening.
960
+ // Legacy reports (no disposition field) stay exempt — R3 back-compat unchanged.
961
+ const reportConfidence = report?.confidence;
962
+ const reportConfidenceOk =
963
+ reportConfidence === 'HIGH' || reportConfidence === 'MEDIUM' || reportConfidence === 'LOW';
964
+ const verdictFindings = Array.isArray(verdict?.findings) ? (verdict.findings as Record<string, unknown>[]) : [];
965
+ const verdictFails = verdictFindings.filter((finding) => finding?.status === 'fail');
966
+ // What a BLOCK *is* decides who can answer it. Dropping a blocked platform answers the
967
+ // platform's own admission rules (资质口径/播报形态 …) — but the drafts' bytes ship to every
968
+ // other target too, so a *draft* defect reported on that platform survives the drop. The
969
+ // one finding class that is unambiguously a draft property is category 3 (可识别个人信息):
970
+ // PII cannot be answered by choosing targets. The rest of the draft-integrity class is owned
971
+ // by the judge's must-pass criteria below (no-prohibited-claims / disclosure-presence /
972
+ // data-handling), which is where an independent reviewer can grade it.
973
+ const blockedPlatforms = platforms.filter((platform) => platform?.decision === 'BLOCK');
974
+ const excludedPlatforms = blockedPlatforms.map((platform) => String(platform?.platform ?? '')).filter(Boolean);
975
+ const piiBlock = blockedPlatforms.some((platform) =>
976
+ platformFindings(platform).some((finding) => Number(finding?.category) === PII_FINDING_CATEGORY),
977
+ );
978
+ // A BLOCK that names no finding is a contract violation, not a signal: there is nothing to
979
+ // remediate and nothing to exclude, so it blocks (fail-closed).
980
+ const unnamedBlock =
981
+ blockedPlatforms.length > 0 && blockedPlatforms.every((p) => platformFindings(p).length === 0);
982
+ const malformed =
983
+ decisions.length === 0 || decisions.some((decision) => !SAFETY_PLATFORM_DECISIONS.has(String(decision)));
984
+ const confidence = verdict?.confidence;
985
+ const confidenceOk = confidence === 'HIGH' || confidence === 'MEDIUM' || confidence === 'LOW';
986
+ const verdictValue = String(verdict?.verdict ?? '');
987
+ const outOfContract =
988
+ (verdictValue !== 'PASS' && verdictValue !== 'FAIL' && verdictValue !== 'NEEDS_REVISION') ||
989
+ !confidenceOk ||
990
+ (usesDisposition && !reportConfidenceOk);
991
+ const nonPass = verdictValue !== 'PASS' || !confidenceOk;
992
+ // Integrity = the finding survives any target choice: PII reported on a blocked platform, an
993
+ // out-of-contract verdict, a non-PASS that documents nothing, or a `fail` outside the
994
+ // admission criteria.
995
+ const integrity =
996
+ piiBlock ||
997
+ unnamedBlock ||
998
+ (nonPass && verdictFindings.length === 0) ||
999
+ verdictFails.some((finding) => !ADMISSION_CRITERIA.has(String(finding?.criterion ?? '')));
1000
+ let status = 'block';
1001
+ let reason = 'verdict PASS on unchanged drafts, no BLOCK/RISK';
1002
+ // A digest-mismatch block means the drafts were deliberately edited (HITL): keep them so
1003
+ // a re-run of safety-prep re-reviews the edited version. Any other block means the
1004
+ // content itself is rejected — quarantine the drafts below.
1005
+ let edited = false;
1006
+ if (request?.digest !== digest) {
1007
+ reason = 'drafts changed after the review was requested';
1008
+ edited = true;
1009
+ } else if (malformed) {
1010
+ reason = 'content-safety report missing or malformed';
1011
+ } else if (outOfContract) {
1012
+ // 20261003 hardening (verdict) + 20261007 amendment (report): a verdict outside
1013
+ // PASS|FAIL|NEEDS_REVISION, any verdict without a HIGH/MEDIUM/LOW confidence, or a
1014
+ // disposition-contract report without one, is not reviewable — block, never revise
1015
+ // against it (there is no contract to read findings from).
1016
+ reason = `content contract violation: ${[
1017
+ verdictValue !== 'PASS' && verdictValue !== 'FAIL' && verdictValue !== 'NEEDS_REVISION'
1018
+ ? `verdict ${verdictValue || 'missing'}`
1019
+ : '',
1020
+ !confidenceOk
1021
+ ? `verdict confidence ${String(confidence ?? 'missing')} (no confidence contract: need HIGH/MEDIUM/LOW)`
1022
+ : '',
1023
+ usesDisposition && !reportConfidenceOk
1024
+ ? `report confidence ${String(reportConfidence ?? 'missing')} (need HIGH/MEDIUM/LOW)`
1025
+ : '',
1026
+ ]
1027
+ .filter(Boolean)
1028
+ .join(', ')}`;
1029
+ } else if (nonPass || blockedPlatforms.length > 0) {
1030
+ const trigger =
1031
+ blockedPlatforms.length > 0
1032
+ ? `content-safety BLOCK on ${blockedPlatforms.map((p) => String(p?.platform ?? '')).join(', ')}`
1033
+ : `content-judge verdict ${verdictValue}`;
1034
+ if (revisions < maxRevise) {
1035
+ status = 'revise';
1036
+ reason = `${trigger} — remediation pass ${revisions + 1}/${maxRevise} (drafts re-reviewed after the edit)`;
1037
+ } else if (integrity) {
1038
+ status = 'block';
1039
+ const named = blockedPlatforms
1040
+ .flatMap((platform) => platformFindings(platform))
1041
+ .filter((finding) => Number(finding?.category) === PII_FINDING_CATEGORY)
1042
+ .map((finding) => `${String(finding?.item ?? '?')}(category ${String(finding?.category)})`)
1043
+ .join(', ');
1044
+ const criteria = verdictFails.map((finding) => String(finding?.criterion)).join(', ');
1045
+ reason = `${trigger} — draft-integrity findings survive ${revisions} remediation passes (${named || criteria || 'the verdict names no criterion'}); exclusion cannot fix these`;
1046
+ } else {
1047
+ status = 'exclude';
1048
+ reason =
1049
+ excludedPlatforms.length > 0
1050
+ ? `${trigger} — admission-only, ${revisions} remediation passes spent: ${excludedPlatforms.join(', ')} dropped from this run, other targets publish${risky ? ' (RISK/escalation recorded)' : ''}`
1051
+ : `${trigger} — admission-only, no platform BLOCK: submitting to the remaining targets at recorded risk`;
1052
+ }
1053
+ } else if (risky) {
1054
+ status = 'escalate';
1055
+ reason = usesDisposition
1056
+ ? `a finding is marked disposition:"escalate" (${escalatedFindings.map((f) => String(f?.item ?? '?')).join(', ')}) — human review required`
1057
+ : 'RISK decision or escalation — human review required';
1058
+ } else if (usesDisposition && decisions.includes('RISK')) {
1059
+ // 20261007 narrowing: RISK whose findings are all gap/note/fix publishes at recorded
1060
+ // risk instead of pausing an unattended run; the exclude stamp keeps the residual-risk
1061
+ // record and the FSM routes it to wrap-docs like any admission-only exclusion.
1062
+ status = 'exclude';
1063
+ reason = 'RISK decisions carry only gap/note/fix dispositions — recorded, publishing at recorded risk';
1064
+ } else status = 'pass';
1065
+ if (status === 'pass' || status === 'escalate' || status === 'exclude') {
1066
+ sted('write', stampFile, () => writeJsonText(stampFile, { digest, status, excludedPlatforms }));
1067
+ }
1068
+ if (status === 'block' && !edited) {
1069
+ // A quality block poisons the isFile() draft cache: every same-day retry would
1070
+ // re-fail on unchanged bytes (20261002 dogfood — two judge-fail runs replayed until
1071
+ // the drafts were moved by hand). Quarantine (mv, never rm) so the next run
1072
+ // regenerates from scratch; the 09_* verdict artifacts stay in 24-script for audit.
1073
+ const q = join(workDir, '24-script', `.quarantine-${runDate}-judge-block`);
1074
+ mkdirSync(q, { recursive: true });
1075
+ for (const path of safetyDraftPaths(workDir, runDate)) {
1076
+ if (!isFile(path)) continue;
1077
+ let dest = join(q, basename(path));
1078
+ for (let n = 2; isFile(dest); n += 1) dest = join(q, `${n}-${basename(path)}`);
1079
+ renameSync(path, dest);
1080
+ }
1081
+ }
1082
+ sted('write', statusFile, () => writeRaw(statusFile, status));
1083
+ console.log(`safety: status=${status} (${reason}); routing is transition-owned`);
1084
+ });
1085
+ }
1086
+
1087
+ /**
1088
+ * Post-remediation bookkeeping for the `safety-revise` state: the agent edited the drafts, this
1089
+ * stage checks they are still the artifacts the rest of the pipeline consumes and spends one unit
1090
+ * of the remediation budget (`daily-safety-gate` reads it to choose revise-vs-exclude). Validating
1091
+ * here fails inside the loop instead of at `wrap-docs`, after the run has moved on. A broken
1092
+ * revision spends the budget too: an unparsable draft must not be retried forever.
1093
+ */
1094
+ /**
1095
+ * Open a content-safety review of the current drafts: drop every artifact of an earlier review
1096
+ * (a retry must be re-reviewed on its final version) and write the request the two agent.run
1097
+ * steps read. The program passes context only — platform policy lives in the kk:content-safety
1098
+ * skill's reference files, never here.
1099
+ */
1100
+ export function dailySafetyPrep(args: string[]): void {
1101
+ const [workDir = '', runDate = '', platforms = ''] = args;
1102
+ timed(workDir, 'safety-review', () => {
1103
+ const digest = safetyDigest(workDir, runDate);
1104
+ for (const name of [
1105
+ 'safety-review_report.json',
1106
+ 'safety-judge_verdict.json',
1107
+ 'safety-judge_status.txt',
1108
+ 'safety-judge_stamp.json',
1109
+ ]) {
1110
+ const stale = safetyPath(workDir, runDate, name);
1111
+ if (isFile(stale)) unlinkSync(stale);
1112
+ }
1113
+ const request = safetyPath(workDir, runDate, 'safety-review_request.json');
1114
+ const targets = platforms
1115
+ .split(',')
1116
+ .map((platform) => platform.trim())
1117
+ .filter(Boolean);
1118
+ sted('write', request, () => writeJsonText(request, { digest, platforms: targets, mode: 'detect-only' }));
1119
+ });
1120
+ }
1121
+
1122
+ /**
1123
+ * Consume the content-safety report and the content-judge verdict into a publish decision (exit 0 in
1124
+ * every case — routing is transition-owned). The gate's job is to *adjust*, not to kill the run
1125
+ * (20261005 operator decision): a non-PASS verdict first routes back through one bounded
1126
+ * draft-remediation loop (`revise`), and what survives the loop is classified by what it is:
1127
+ *
1128
+ * - `revise` — non-PASS and the remediation budget is not spent: re-review after the drafts change.
1129
+ * - `exclude` — admission-only residue (the CN 资质口径 / 播报形态 findings): the platforms that
1130
+ * BLOCKed are dropped from this run and every other target publishes normally. Also
1131
+ * the 20261007 narrowing: RISK whose findings are all gap/note/fix publishes at
1132
+ * recorded risk with nothing dropped (empty `excludedPlatforms`).
1133
+ * - `escalate` — a finding the reviewer marked `disposition: "escalate"` on an otherwise clean
1134
+ * pass: human review. Legacy reports (no `disposition` field anywhere) keep the old
1135
+ * rule — any RISK decision or report-level `escalate: true` pauses (20261007 ADR).
1136
+ * - `pass` — explicit PASS verdict, unchanged drafts, no BLOCK and no RISK finding at all.
1137
+ * - `block` — draft integrity: PII reported on a blocked platform, or a judge must-pass `fail`
1138
+ * outside `jurisdictional-rules` (prohibited claims / disclosure / data-handling);
1139
+ * also an unreadable or out-of-contract report/verdict, a non-PASS that documents
1140
+ * nothing, or drafts edited after the review. Never published.
1141
+ *
1142
+ * Fail-closed where it matters: a missing report, verdict or confidence still blocks.
1143
+ */
1144
+ /**
1145
+ * Post-remediation bookkeeping for the `safety-revise` state: the agent edited the drafts, this
1146
+ * stage checks they are still the artifacts the rest of the pipeline consumes and spends one unit
1147
+ * of the remediation budget (`daily-safety-gate` reads it to choose revise-vs-exclude). Validating
1148
+ * here fails inside the loop instead of at `wrap-docs`, after the run has moved on. A broken
1149
+ * revision spends the budget too: an unparsable draft must not be retried forever.
1150
+ */
1151
+ export function dailySafetyRevise(args: string[]): void {
1152
+ const [workDir = '', runDate = ''] = args;
1153
+ timed(workDir, 'safety-revise', () => {
1154
+ const [articlePath, scriptPath] = safetyDraftPaths(workDir, runDate);
1155
+ const article = requireJson(articlePath, 'safety-revise');
1156
+ for (const field of ['title', 'body'] as const) {
1157
+ const value = article[field];
1158
+ if (typeof value !== 'string' || value.trim() === '') {
1159
+ failWith(1, `safety-revise: article ${field} must be a non-empty string in ${articlePath}`);
1160
+ }
1161
+ }
1162
+ assertScriptContent(scriptPath);
1163
+ const path = join(workDir, SAFETY_REVISE_COUNT);
1164
+ const next = readSafetyReviseCount(workDir) + 1;
1165
+ sted('write', path, () => writeFileSync(path, `${next}\n`));
1166
+ console.log(`safety-revise: remediation pass ${next} applied; drafts re-validated`);
1167
+ });
1168
+ }
1169
+
1170
+ export function dailyScript(args: string[]): void {
1171
+ const [workDir = '', runDate = '', pluginsPath = '', language = '', title = '', voiceProfile = ''] = args;
1172
+ const yamlOut = join(workDir, '24-script', `${runDate}_08_script_voicescript.yaml`);
1173
+ const contentOut = join(workDir, '24-script', `${runDate}_08_script_content.json`);
1174
+ const planIn = join(workDir, '21-plan', `${runDate}_03_plan_plan.json`);
1175
+ timed(workDir, 'script', () => {
1176
+ if (isFile(yamlOut)) {
1177
+ console.log(`voicescript capped by plan: ${yamlOut}`);
1178
+ return;
1179
+ }
1180
+ kk(['executor', 'run', 'dailynews-gen', '--in', planIn, '--out', contentOut, ...pluginsArgs(pluginsPath)], {
1181
+ env: {
1182
+ DAILYNEWS_LANGUAGE: language,
1183
+ DAILYNEWS_TITLE: title,
1184
+ // Task 0189: the broadcast greeting carries the episode's run date, not the render
1185
+ // date — a backfilled/retried run must not greet "today".
1186
+ DAILYNEWS_DATE: runDate,
1187
+ VOICEBOX_DEFAULT_PROFILE: voiceProfile,
1188
+ // F613 R4: always passed as absolute paths — spawnPluginEntry runs plugins with
1189
+ // cwd = the plugin package dir, so a relative workDir would silently miss the
1190
+ // plan; a plan file absent at build time reports missing-plan (template fallback).
1191
+ DAILYNEWS_SCRIPT_PLAN: resolve(join(workDir, '24-script', `${runDate}_08_script-write_plan.json`)),
1192
+ DAILYNEWS_STYLE_FILE: resolve(resolveSidecar('', STYLE_SIDECAR)),
1193
+ },
1194
+ });
1195
+ const body = readJson(contentOut)?.body;
1196
+ if (typeof body !== 'string') failWith(1, `script: ${contentOut} has no string body`);
1197
+ sted('write', yamlOut, () => writeRaw(yamlOut, body));
1198
+ // R3 (task 0139): fresh writes are validated here; the script cache path is covered by
1199
+ // wrap-docs, which runs on every path that reaches audio.
1200
+ try {
1201
+ assertScriptContent(yamlOut);
1202
+ } catch (err) {
1203
+ // A rejected fresh write would otherwise poison the isFile(yamlOut) cache: every
1204
+ // resume skips regeneration and re-fails at wrap-docs. Drop it so retry regenerates.
1205
+ unlinkSync(yamlOut);
1206
+ throw err;
1207
+ }
1208
+ });
1209
+ }
1210
+
1211
+ /** Task 0189 R10 artifacts of the content-safety verdict gate (24-script, step 09). */
1212
+ /**
1213
+ * F613 R1: snapshot the shipped style contract into the run's work dir. Spur workflows have no
1214
+ * workflow-dir var, so the script-write prompt reads this copy — and the snapshot freezes the
1215
+ * exact contract the run's plan was written against. Idempotent (an existing snapshot is kept);
1216
+ * a missing sidecar is a broken install, so `requireSidecar` fails loud.
1217
+ */
1218
+ export function dailyScriptStyle(args: string[]): void {
1219
+ const [workDir = '', runDate = ''] = args;
1220
+ const snapshot = join(workDir, '24-script', `${runDate}_08_script-write_style.md`);
1221
+ if (isFile(snapshot)) {
1222
+ console.log(`script style cached: ${snapshot}`);
1223
+ return;
1224
+ }
1225
+ const sidecar = requireSidecar('', STYLE_SIDECAR, 'daily-voice-style');
1226
+ const scriptDir = join(workDir, '24-script');
1227
+ sted('mkdir', scriptDir, () => mkdirSync(scriptDir, { recursive: true }));
1228
+ sted('cp', snapshot, () => copyFileSync(sidecar, snapshot));
1229
+ console.log(`script style snapshot: ${snapshot}`);
1230
+ }
1231
+
1232
+ export function dailyShowNotes(args: string[]): void {
1233
+ const [workDir = '', runDate = '', pluginsPath = '', title = ''] = args;
1234
+ const article = join(workDir, '22-article', `${runDate}_06_article_content.json`);
1235
+ // The preceding `publish-surfdash` state writes this artifact; `_17_publish_result.json` does
1236
+ // not exist yet at `show-notes` time (the later `publish` state merges it), so reading it left
1237
+ // PODCAST_PUB_ARTICLE_POST_PATH permanently empty (task 0137).
1238
+ const result = join(workDir, '31-publish', `${runDate}_14_publish-surfdash_result.json`);
1239
+ const out = join(workDir, '31-publish', `${runDate}_15_show-notes_show-notes.md`);
1240
+ const plan = join(workDir, '21-plan', `${runDate}_03_plan_plan.json`);
1241
+ // Generated-episode content carries `metadata.segments[]` — the source of real
1242
+ // audio offsets for the show-notes timeline (jump-to-item timestamps).
1243
+ const audioContent = join(workDir, '30-audio', `${runDate}_11_generate_content.json`);
1244
+ timed(workDir, 'show-notes', () => {
1245
+ const effective = readJson(article)?.title;
1246
+ const titleArg = title !== '' ? title : typeof effective === 'string' ? effective : '';
1247
+ // Boundary-excluded docs must not render into show notes (judge finding 2026-10-02): the
1248
+ // article body's 未写入 note names the dropped ids; filter the plan copy podcast-pub sees.
1249
+ // Inlined parse — this file must not import @gobing-ai/* (header contract); the same note
1250
+ // grammar lives in daily-article-gen's excludedIdsFromNote.
1251
+ const postPath = firstPostPath(readJson(result), 'surfdash-pub');
1252
+ const articleBody = readJson(article)?.body;
1253
+ const excluded = new Set<string>();
1254
+ if (typeof articleBody === 'string') {
1255
+ for (const note of articleBody.matchAll(/未写入[::](.*)/g)) {
1256
+ for (const id of note[1].matchAll(/(?:[a-zA-Z0-9_-]+:)?[0-9a-f]{16,64}/g)) {
1257
+ excluded.add(id[0]);
1258
+ const colon = id[0].indexOf(':');
1259
+ if (colon !== -1) excluded.add(id[0].slice(colon + 1));
1260
+ }
1261
+ }
1262
+ }
1263
+ let planIn = plan;
1264
+ if (excluded.size > 0) {
1265
+ const parsed: unknown = readJson(plan);
1266
+ if (Array.isArray(parsed)) {
1267
+ const kept = parsed.filter(
1268
+ (d) =>
1269
+ !(
1270
+ d !== null &&
1271
+ typeof d === 'object' &&
1272
+ (excluded.has(String((d as Record<string, unknown>).id)) ||
1273
+ (String((d as Record<string, unknown>).id).includes(':') &&
1274
+ excluded.has(
1275
+ String((d as Record<string, unknown>).id).slice(
1276
+ String((d as Record<string, unknown>).id).indexOf(':') + 1,
1277
+ ),
1278
+ )))
1279
+ ),
1280
+ );
1281
+ if (kept.length !== parsed.length) {
1282
+ planIn = plan.replace(/\.json$/, '-shownotes.json');
1283
+ writeJsonText(planIn, kept);
1284
+ }
1285
+ }
1286
+ }
1287
+ kk(['executor', 'run', 'podcast-pub', '--in', planIn, '--out', out, ...pluginsArgs(pluginsPath)], {
1288
+ env: {
1289
+ PODCAST_PUB_TITLE: titleArg,
1290
+ PODCAST_PUB_RUN_DATE: runDate,
1291
+ PODCAST_PUB_BRIEF_MODE: 'true',
1292
+ PODCAST_PUB_ARTICLE_POST_PATH: postPath,
1293
+ // Task 0189 R1 / Apple §1.11: AI-voice disclosure in the episode metadata, not only
1294
+ // in the audio sign-off and the article footer.
1295
+ PODCAST_PUB_FOOTER_NOTE: '本期文字由 AI 辅助整理,音频为 AI 合成配音。',
1296
+ ...(isFile(audioContent) ? { PODCAST_PUB_AUDIO_CONTENT: audioContent } : {}),
1297
+ },
1298
+ });
1299
+ });
1300
+ }
1301
+
1302
+ /** `jq -r '[…select(.target == t and .ok == true) | .metadata.postPath // empty] | first // ""'`. */
1303
+ /**
1304
+ * Collapsed translate scaffolding (2026-09-16 feedback): surfdash-pub owns the
1305
+ * deterministic mechanics — `scaffold-locale` for both target locales — while the
1306
+ * workflow `translate` state's agent step owns the LLM translation of the drafts.
1307
+ * Writes one marker file per locale (zh post path + en/ja draft paths); empty
1308
+ * marker = locale absent (callers skip). Reuses an existing on-disk draft as the
1309
+ * cache across run retries — re-scaffolding would erase the agent's translation.
1310
+ */
1311
+ export function dailyTranslateLocalize(args: string[]): void {
1312
+ const [workDir = '', runDate = '', pluginsPath = ''] = args;
1313
+ const result = join(workDir, '31-publish', `${runDate}_17_publish_result.json`);
1314
+ const zhFile = join(workDir, '31-publish', `${runDate}_20_translate-localize_zh-post-path.txt`);
1315
+ timed(workDir, 'translate-localize', () => {
1316
+ const postPath = firstPostPath(readJson(result), 'surfdash-pub');
1317
+ const zh = postPath.endsWith('index.md') ? postPath : '';
1318
+ sted('write', zhFile, () => writeRaw(zhFile, zh));
1319
+ if (zh === '') {
1320
+ for (const target of ['en', 'ja'] as const) {
1321
+ sted(
1322
+ 'write',
1323
+ join(workDir, '31-publish', `${runDate}_20_translate-localize_${target}-post-path.txt`),
1324
+ () =>
1325
+ writeRaw(
1326
+ join(workDir, '31-publish', `${runDate}_20_translate-localize_${target}-post-path.txt`),
1327
+ '',
1328
+ ),
1329
+ );
1330
+ }
1331
+ console.log('no zh post path — skip localize');
1332
+ return;
1333
+ }
1334
+ for (const target of ['en', 'ja'] as const) {
1335
+ const markerFile = join(workDir, '31-publish', `${runDate}_20_translate-localize_${target}-post-path.txt`);
1336
+ const existing = zh.replace('/zh/', `/${target}/`);
1337
+ if (isFile(existing)) {
1338
+ sted('write', markerFile, () => writeRaw(markerFile, existing));
1339
+ console.log(`${target} draft cached: ${existing}`);
1340
+ continue;
1341
+ }
1342
+ const scaffold = join(workDir, '31-publish', `${runDate}_20_translate-localize_scaffold-${target}.json`);
1343
+ const scaffoldResult = join(
1344
+ workDir,
1345
+ '31-publish',
1346
+ `${runDate}_20_translate-localize_scaffold-${target}-result.json`,
1347
+ );
1348
+ sted('write', scaffold, () =>
1349
+ writeJqText(scaffold, { body: '', options: { operation: 'scaffold-locale', postPath: zh, target } }),
1350
+ );
1351
+ kk([
1352
+ 'executor',
1353
+ 'run',
1354
+ 'surfdash-pub',
1355
+ '--in',
1356
+ scaffold,
1357
+ '--out',
1358
+ scaffoldResult,
1359
+ ...pluginsArgs(pluginsPath),
1360
+ ]);
1361
+ const draftPath = metadataOf(readJson(scaffoldResult)).draftPath;
1362
+ sted('write', markerFile, () => writeRaw(markerFile, typeof draftPath === 'string' ? draftPath : ''));
1363
+ }
1364
+ });
1365
+ }
1366
+
1367
+ export function dailyTranslateSync(args: string[]): void {
1368
+ const [workDir = '', runDate = '', pluginsPath = '', zhPathFile = ''] = args;
1369
+ const sync = join(workDir, '31-publish', `${runDate}_24_translate-sync_sync.json`);
1370
+ const syncResult = join(workDir, '31-publish', `${runDate}_24_translate-sync_sync-result.json`);
1371
+ timed(workDir, 'translate-sync', () => {
1372
+ // Reads the marker file itself — the collapsed `translate` state has no
1373
+ // cross-state var to hand the path through.
1374
+ const zhPostPath = isFile(zhPathFile) ? readFileSync(zhPathFile, 'utf-8') : '';
1375
+ if (zhPostPath === '') {
1376
+ console.log('no zh post path — skip translate-sync');
1377
+ return;
1378
+ }
1379
+ sted('write', sync, () =>
1380
+ writeJqText(sync, { body: '', options: { operation: 'sync', postPath: zhPostPath } }),
1381
+ );
1382
+ kk(['executor', 'run', 'surfdash-pub', '--in', sync, '--out', syncResult, ...pluginsArgs(pluginsPath)], {
1383
+ unset: NESTED_SPUR_UNSET,
1384
+ });
1385
+ });
1386
+ }
1387
+
1388
+ export function dailyWrapDocs(args: string[]): void {
1389
+ const [workDir = '', runDate = '', voiceProfile = ''] = args;
1390
+ const scriptPath = join(workDir, '24-script', `${runDate}_08_script_voicescript.yaml`);
1391
+ const docsPath = join(workDir, '30-audio', `${runDate}_10_wrap-docs_docs.json`);
1392
+ timed(workDir, 'wrap-docs', () => {
1393
+ // R3 (task 0139): the second validator placement — covers a HITL-edited YAML and the
1394
+ // script-stage cache path, neither of which re-enters dailyScript's fresh-write branch.
1395
+ assertScriptContent(scriptPath);
1396
+ const url = new URL(scriptPath, `file://${process.cwd()}/`);
1397
+ const body = readFileSync(decodeURIComponent(url.pathname), 'utf-8');
1398
+ const profile = voiceProfile || process.env.VOICEBOX_DEFAULT_PROFILE || 'robin-news';
1399
+ const doc = {
1400
+ id: createHash('sha256').update(url.href).digest('hex').slice(0, 16),
1401
+ title: 'Daily AI News VoiceScript',
1402
+ sourceUri: url.href,
1403
+ body,
1404
+ mediaType: 'application/yaml',
1405
+ metadata: { voiceProfile: profile },
1406
+ };
1407
+ sted('write', docsPath, () => writeJsonText(docsPath, [doc]));
1408
+ });
1409
+ }
1410
+
1411
+ /**
1412
+ * E8: build one `image-gen` envelope per planned card, render them sequentially, and package the
1413
+ * ordered card manifest + `Content` that `xhs-pub` consumes. Format, style, provider and model
1414
+ * are pinned here (never model-authored), so the series cannot drift from its preset. Card copy
1415
+ * is typeset by image-gen's composer; the provider prompt stays text-free (0181). Resume-safe:
1416
+ * a card whose recorded artifact is still on disk is not re-rendered — and not re-billed.
1417
+ */
1418
+ export function dailyXhsRender(args: string[]): void {
1419
+ const [
1420
+ workDir = '',
1421
+ runDate = '',
1422
+ pluginsPath = '',
1423
+ countArg = '',
1424
+ style = '',
1425
+ provider = '',
1426
+ model = '',
1427
+ fallback = '',
1428
+ ] = args;
1429
+ const count = Number.parseInt(countArg, 10);
1430
+ const planPath = join(workDir, '25-xhs', `${runDate}_18_xhs_plan.json`);
1431
+ const cardsDir = join(workDir, '25-xhs', 'cards');
1432
+ const manifestPath = join(workDir, '25-xhs', 'cards.json');
1433
+ const contentPath = join(workDir, '25-xhs', 'content.json');
1434
+ timed(workDir, 'xhs-render', () => {
1435
+ if (!Number.isInteger(count) || count < 1 || count > XHS_MAX_CARDS) {
1436
+ failWith(1, `xhs render: xhs_cards must be 1..${XHS_MAX_CARDS}, got '${countArg}'`);
1437
+ }
1438
+ const plan = xhsPlan(planPath, count);
1439
+ sted('mkdir', cardsDir, () => mkdirSync(cardsDir, { recursive: true }));
1440
+ const images: Record<string, unknown>[] = [];
1441
+ const cards: Record<string, unknown>[] = [];
1442
+ for (const card of plan.cards) {
1443
+ const out = join(cardsDir, `card-${card.index}.json`);
1444
+ const promptPath = join(cardsDir, `card-${card.index}.prompt.txt`);
1445
+ let artifact = firstArtifact(readJson(out));
1446
+ if (artifact === null || !isFile(typeof artifact.path === 'string' ? artifact.path : '')) {
1447
+ const envPath = join(cardsDir, `card-${card.index}.in.json`);
1448
+ const imageGen: Record<string, unknown> = {
1449
+ job: 'free',
1450
+ format: XHS_FORMAT,
1451
+ style,
1452
+ vars: {
1453
+ role: card.role,
1454
+ layout: card.layout,
1455
+ headline: card.copy,
1456
+ points: card.points.join('\n'),
1457
+ subject: card.subject,
1458
+ index: card.index,
1459
+ },
1460
+ maxImages: 1,
1461
+ };
1462
+ if (provider !== '') imageGen.provider = provider;
1463
+ if (model !== '') imageGen.model = model;
1464
+ // 0219 R1: same opt-in as the cover stage — '' keeps strict fail-fast.
1465
+ if (fallback !== '') imageGen.fallback = imageFallback(fallback);
1466
+ sted('write', envPath, () =>
1467
+ writeJsonText(envPath, [
1468
+ { id: `xhs-card-${card.index}`, title: runDate, body: '', metadata: { imageGen } },
1469
+ ]),
1470
+ );
1471
+ // Sequential on purpose: one provider call per card (illustration only —
1472
+ // card copy is typeset by image-gen's composer, never prompted), and the
1473
+ // first failure stops the spend — later cards stay unrendered for a resume
1474
+ // run to pick up.
1475
+ const status = kk(
1476
+ ['executor', 'run', 'image-gen', '--in', envPath, '--out', out, ...pluginsArgs(pluginsPath)],
1477
+ { soft: true },
1478
+ );
1479
+ // 0219 R2: name the failed card so a hand re-run resumes without re-billing.
1480
+ if (status !== 0) {
1481
+ failWith(
1482
+ status,
1483
+ `xhs render: card ${card.index} failed (image-gen exit ${status}); cards before it are kept — re-run daily-xhs-render to resume from card ${card.index}`,
1484
+ );
1485
+ }
1486
+ artifact = firstArtifact(requireJson(out, 'xhs render'));
1487
+ }
1488
+ if (artifact === null) failWith(1, `xhs render: card ${card.index} recorded no image artifact (${out})`);
1489
+ const recorded = artifact.path;
1490
+ if (typeof recorded !== 'string' || !isFile(recorded)) {
1491
+ failWith(1, `xhs render: card ${card.index} image artifact is not on disk: '${String(recorded)}'`);
1492
+ }
1493
+ // `image-gen` writes the artifact beside `--out`; the publisher requires absolute paths.
1494
+ const imagePath = resolve(recorded);
1495
+ // 0181: a composed card may also carry the text-free illustration layer; keep
1496
+ // its recorded path so the manifest shows both layers.
1497
+ const rawIllustration: unknown = artifact.illustration;
1498
+ const illustrationPath =
1499
+ typeof rawIllustration === 'object' &&
1500
+ rawIllustration !== null &&
1501
+ typeof (rawIllustration as Record<string, unknown>).path === 'string'
1502
+ ? resolve((rawIllustration as Record<string, unknown>).path as string)
1503
+ : undefined;
1504
+ sted('write', promptPath, () =>
1505
+ writeRaw(promptPath, typeof artifact.prompt === 'string' ? artifact.prompt : ''),
1506
+ );
1507
+ images.push({ ...artifact, path: imagePath });
1508
+ cards.push({
1509
+ index: card.index,
1510
+ role: card.role,
1511
+ sourcePoint: card.sourcePoint,
1512
+ copy: card.copy,
1513
+ layout: card.layout,
1514
+ promptPath,
1515
+ imagePath,
1516
+ illustrationPath,
1517
+ status: 'rendered',
1518
+ });
1519
+ }
1520
+ sted('write', manifestPath, () => writeJsonText(manifestPath, { source: planPath, cards }));
1521
+ sted('write', contentPath, () =>
1522
+ writeJsonText(contentPath, {
1523
+ title: plan.title,
1524
+ body: plan.body,
1525
+ format: 'text',
1526
+ metadata: { images, publishStatus: 'draft' },
1527
+ }),
1528
+ );
1529
+ console.log(`xhs render: ${cards.length} cards packaged in card order (${contentPath})`);
1530
+ });
1531
+ }
1532
+
1533
+ /** A single-target publish Result, not the fan-out aggregate: `ok` plus `metadata.publishStatus`. */