@gobing-ai/knowledge-kit 0.1.17 → 0.1.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/board/daily-voice/index.js +40 -7
  3. package/dist/index.js +8428 -4448
  4. package/package.json +1 -1
  5. package/plugins/generations/image-gen/README.md +31 -31
  6. package/plugins/generations/image-gen/assets/sample/provenance.json +314 -0
  7. package/plugins/generations/image-gen/config.example.yaml +3 -0
  8. package/plugins/generations/image-gen/dist/index.js +154 -14
  9. package/plugins/generations/image-gen/presets/SOURCE.md +65 -0
  10. package/plugins/generations/image-gen/scripts/eval-style-presets.ts +513 -0
  11. package/plugins/generations/image-gen/scripts/gen-samples.ts +57 -7
  12. package/plugins/generations/image-gen/src/presets.ts +6 -5
  13. package/plugins/generations/image-gen/src/providers/h3-local.ts +196 -0
  14. package/plugins/generations/image-gen/src/providers/types.ts +11 -1
  15. package/plugins/kk/config.example.yaml +7 -2
  16. package/plugins/kk/decisions/extract/ai-news.yaml +5 -2
  17. package/plugins/kk/plugin.json +1 -1
  18. package/plugins/kk/publish-presets/chinese-article.json +8 -2
  19. package/plugins/kk/publish-presets/daily-ai-voice-migration.json +1 -1
  20. package/plugins/kk/publish-presets/daily-ai-voice.json +57 -16
  21. package/plugins/kk/publish-presets/itc-main.json +36 -9
  22. package/plugins/kk/publish-presets/technical-article.json +8 -2
  23. package/plugins/kk/schedules/kk-daily-ai-voice3.cron.tmpl +8 -9
  24. package/plugins/kk/schedules/kk-daily-publish3-cn-peak.cron.tmpl +13 -19
  25. package/plugins/kk/schedules/kk-daily-publish3-overseas.cron.tmpl +11 -9
  26. package/plugins/kk/scripts/daily-stages.ts +238 -14
  27. package/plugins/kk/scripts/daily-triage-core.ts +43 -25
  28. package/plugins/kk/scripts/daily-triage.ts +1 -1
  29. package/plugins/kk/skills/image-authoring/SKILL.md +7 -3
  30. package/plugins/kk/skills/image-authoring/references/providers.md +27 -0
  31. package/plugins/kk/skills/image-authoring/references/style-extraction.md +1 -1
  32. package/plugins/kk/skills/publish/SKILL.md +15 -2
  33. package/plugins/kk/skills/web-automation/SKILL.md +31 -1
  34. package/plugins/kk/workflows/kk-article-generate.yaml +485 -0
  35. package/plugins/kk/workflows/kk-collect.yaml +8 -4
  36. package/plugins/kk/workflows/kk-daily-ai-voice.yaml +2 -1
  37. package/plugins/kk/workflows/kk-daily-ai-voice2.yaml +4 -2
  38. package/plugins/kk/workflows/kk-daily-safety.yaml +5 -7
  39. package/plugins/kk/workflows/kk-news-generate.yaml +410 -0
  40. package/plugins/kk/workflows/kk-publish.yaml +236 -0
  41. package/plugins/publishings/bilibili-pub/dist/profile-check.js +49 -10
  42. package/plugins/publishings/cnblogs-pub/dist/profile-check.js +60 -10
  43. package/plugins/publishings/csdn-pub/dist/profile-check.js +60 -10
  44. package/plugins/publishings/infoq-pub/dist/profile-check.js +60 -10
  45. package/plugins/publishings/jike-pub/dist/profile-check.js +60 -10
  46. package/plugins/publishings/juejin-pub/dist/profile-check.js +60 -10
  47. package/plugins/publishings/linkedin-pub/dist/index.js +43 -6
  48. package/plugins/publishings/linkedin-pub/dist/profile-check.js +92 -15
  49. package/plugins/publishings/linkedin-pub/src/index.ts +52 -6
  50. package/plugins/publishings/shipinhao-pub/dist/index.js +391 -32
  51. package/plugins/publishings/shipinhao-pub/dist/profile-check.js +52 -11
  52. package/plugins/publishings/shipinhao-pub/plugin.json +1 -1
  53. package/plugins/publishings/shipinhao-pub/src/audio-flow.ts +393 -0
  54. package/plugins/publishings/shipinhao-pub/src/flow.ts +243 -14
  55. package/plugins/publishings/shipinhao-pub/src/selectors.ts +13 -0
  56. package/plugins/publishings/sspai-pub/dist/profile-check.js +60 -10
  57. package/plugins/publishings/substack-pub/dist/profile-check.js +60 -10
  58. package/plugins/publishings/surfdash-pub/dist/index.js +50 -8
  59. package/plugins/publishings/surfdash-pub/src/index.ts +59 -8
  60. package/plugins/publishings/surfdash-pub/src/topic-claims.ts +34 -3
  61. package/plugins/publishings/threads-pub/dist/index.js +9196 -296
  62. package/plugins/publishings/threads-pub/dist/profile-check.js +21139 -0
  63. package/plugins/publishings/threads-pub/package.json +3 -1
  64. package/plugins/publishings/threads-pub/plugin.json +6 -1
  65. package/plugins/publishings/threads-pub/src/index.ts +8 -1
  66. package/plugins/publishings/threads-pub/src/post-rail.ts +357 -0
  67. package/plugins/publishings/threads-pub/src/profile-check.ts +17 -0
  68. package/plugins/publishings/wechatmp-pub/dist/index.js +454 -81
  69. package/plugins/publishings/wechatmp-pub/dist/profile-check.js +401 -102
  70. package/plugins/publishings/wechatmp-pub/src/flow.ts +42 -4
  71. package/plugins/publishings/wechatmp-pub/src/index.ts +142 -102
  72. package/plugins/publishings/wechatmp-pub/src/profile-check.ts +36 -58
  73. package/plugins/publishings/weibo-pub/dist/index.js +136 -22
  74. package/plugins/publishings/weibo-pub/dist/profile-check.js +61 -11
  75. package/plugins/publishings/weibo-pub/src/index.ts +208 -22
  76. package/plugins/publishings/x-pub/dist/index.js +263 -43
  77. package/plugins/publishings/x-pub/dist/profile-check.js +63 -11
  78. package/plugins/publishings/x-pub/src/index.ts +15 -1
  79. package/plugins/publishings/x-pub/src/post-rail.ts +334 -0
  80. package/plugins/publishings/xhs-pub/dist/index.js +193 -201
  81. package/plugins/publishings/xhs-pub/dist/profile-check.js +380 -85
  82. package/plugins/publishings/xhs-pub/src/automation-guard.ts +2 -3
  83. package/plugins/publishings/xhs-pub/src/flow.ts +177 -205
  84. package/plugins/publishings/xhs-pub/src/index.ts +65 -59
  85. package/plugins/publishings/xhs-pub/src/modes.ts +1 -1
  86. package/plugins/publishings/xhs-pub/src/page.ts +2 -2
  87. package/plugins/publishings/xhs-pub/src/profile-check.ts +86 -150
  88. package/plugins/publishings/xiaoyuzhou-pub/dist/profile-check.js +60 -10
  89. package/plugins/kk/scripts/daily-scheduled-run.ts +0 -581
  90. package/plugins/kk/scripts/voice3-publish-window.ts +0 -206
  91. package/plugins/kk/workflows/kk-daily-ai-voice3.yaml +0 -903
  92. package/plugins/kk/workflows/kk-daily-publish3.yaml +0 -353
  93. package/plugins/kk/workflows/kk-itc-author.yaml +0 -484
  94. package/plugins/kk/workflows/kk-itc-publish-tail.yaml +0 -112
  95. package/plugins/kk/workflows/kk-itc.yaml +0 -291
@@ -1,581 +0,0 @@
1
- #!/usr/bin/env bun
2
- /** Supervise one scheduled daily run and persist its terminal outcome even after a deadline. */
3
- import { spawn, spawnSync } from 'node:child_process';
4
- import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
5
- import { tmpdir } from 'node:os';
6
- import { dirname, join, resolve } from 'node:path';
7
- import { parseArgs } from 'node:util';
8
- import type { TriageReceipt, TriageReport } from './daily-triage-core';
9
- import { collectTriage, summarizeTriage } from './daily-triage-core';
10
-
11
- const { values } = parseArgs({
12
- options: {
13
- repo: { type: 'string', default: process.cwd() },
14
- 'works-dir': { type: 'string' },
15
- 'run-id': { type: 'string' },
16
- 'timeout-ms': { type: 'string', default: '13500000' },
17
- receipt: { type: 'string' },
18
- agent: { type: 'string', default: 'inline' },
19
- 'retry-agent': { type: 'string', default: 'claude' },
20
- 'required-channels': { type: 'string', default: 'wechat,locales,cms-resync' },
21
- 'wechat-live': { type: 'boolean', default: false },
22
- workflow: { type: 'string', default: 'kk-daily-ai-voice2' },
23
- 'generate-only': { type: 'boolean', default: false },
24
- window: { type: 'string' },
25
- 'publish-preset': { type: 'string' },
26
- 'publish-live-channels': { type: 'string' },
27
- 'allow-dirty': { type: 'boolean', default: false },
28
- 'skip-probe': { type: 'boolean', default: false },
29
- },
30
- });
31
- const timeoutMs = Number(values['timeout-ms']);
32
- if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) {
33
- console.error('daily-scheduled-run: --timeout-ms must be a positive integer');
34
- process.exit(2);
35
- }
36
- const repo = resolve(values.repo);
37
- const now = new Date();
38
- const stamp = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`;
39
- const runId = values['run-id'] ?? `daily-ai-voice-${stamp}-${now.getTime()}`;
40
- const workDir = join(resolve(values['works-dir'] ?? join(repo, '.works')), 'kk-daily-ai-voice2', stamp);
41
- const receiptPath = resolve(values.receipt ?? join(workDir, 'schedule-receipt.json'));
42
- const startedAt = now.toISOString();
43
- mkdirSync(workDir, { recursive: true });
44
- mkdirSync(dirname(receiptPath), { recursive: true });
45
- // voice3 shares the voice2 workspace (F08); only the vars and the publish seam differ.
46
- const isVoice3 = values.workflow === 'kk-daily-ai-voice3';
47
- const generateOnly = values['generate-only'] === true;
48
- if (generateOnly && !isVoice3) {
49
- console.error('daily-scheduled-run: --generate-only requires --workflow kk-daily-ai-voice3');
50
- process.exit(2);
51
- }
52
- const vars = isVoice3
53
- ? {
54
- auto_publish: generateOnly ? 'false' : 'true',
55
- ...(values['publish-preset'] !== undefined ? { publish_preset: values['publish-preset'] } : {}),
56
- ...(values['publish-live-channels'] !== undefined
57
- ? { publish_live_channels: values['publish-live-channels'] }
58
- : {}),
59
- ...(values.window ? { window: values.window } : {}),
60
- skip_review: 'true',
61
- agent: values.agent,
62
- agent_retry: values['retry-agent'],
63
- work_dir: workDir,
64
- run_date: stamp,
65
- }
66
- : {
67
- publish_enabled: 'true',
68
- skip_review: 'true',
69
- agent: values.agent,
70
- agent_retry: values['retry-agent'],
71
- wechat_live: values['wechat-live'] === true ? 'true' : 'false',
72
- work_dir: workDir,
73
- run_date: stamp,
74
- };
75
- // ------------------------------------------------------------------
76
- // Preflight (0347 F1, 2026-11-10). Fail fast at minute one with named
77
- // reasons instead of burning the window on a doomed run (2026-11-09: 80
78
- // minutes died on a quota-dead executor chain a probe would have refused,
79
- // on workflow bytes that had already diverged from the installed kk).
80
- // ------------------------------------------------------------------
81
-
82
- interface Preflight {
83
- ok: boolean;
84
- reasons: string[];
85
- warnings: string[];
86
- }
87
-
88
- const ANSI_RE = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*[A-Za-z]`, 'g');
89
-
90
- function harnessDirtyPaths(): string[] {
91
- const git = spawnSync('git', ['status', '--porcelain', '--', 'plugins/kk', '.spur/workflows'], {
92
- cwd: repo,
93
- encoding: 'utf-8',
94
- timeout: 10_000,
95
- });
96
- if (git.status !== 0) return [];
97
- // Keep the full porcelain line (XY + path): the refusal must show whether a byte is staged,
98
- // unstaged or untracked — 20261111 a16 spent a fix loop guessing that from bare paths.
99
- return git.stdout
100
- .split('\n')
101
- .map((line) => line.trimEnd())
102
- .filter(Boolean);
103
- }
104
-
105
- /** Package root of the kk binary this machine resolves `kk` to, or null. */
106
- function kkPackageRoot(): string | null {
107
- const which = spawnSync('sh', ['-c', 'command -v kk'], { encoding: 'utf-8', timeout: 5_000 });
108
- const bin = which.stdout.trim();
109
- if (which.status !== 0 || bin === '') return null;
110
- try {
111
- const real = realpathSync(bin);
112
- // <pkg>/dist/index.js -> <pkg>
113
- return dirname(dirname(real));
114
- } catch {
115
- return null;
116
- }
117
- }
118
-
119
- function diffDirs(a: string, b: string): string[] {
120
- if (!existsSync(a) || !existsSync(b)) return [];
121
- const diff = spawnSync('diff', ['-rq', a, b], { encoding: 'utf-8', timeout: 20_000 });
122
- if (diff.status === 0) return [];
123
- if (diff.error || (diff.status !== 1 && diff.status !== null)) return []; // unavailable: warn elsewhere, never false-refuse
124
- return diff.stdout
125
- .split('\n')
126
- .filter((line) => line.trim() !== '')
127
- .map((line) => line.replace(a, 'checkout').replace(b, 'install'))
128
- .slice(0, 5);
129
- }
130
-
131
- /**
132
- * One minimal real agent round-trip. `spur agent doctor` reports usable:true for accounts whose
133
- * quota is exhausted (2026-11-09 R3), so executor health must be proven with traffic, not probes.
134
- */
135
- function executorProbe(agentName: string): { ok: boolean; detail: string } {
136
- const probeCwd = mkdtempSync(join(tmpdir(), 'kk-preflight-'));
137
- try {
138
- const probe = spawnSync(
139
- 'spur',
140
- ['agent', 'run', '--agent', agentName, '--mode', 'text', '--json', 'Reply with exactly: OK'],
141
- { cwd: probeCwd, encoding: 'utf-8', timeout: 120_000 },
142
- );
143
- if (probe.status === 0) return { ok: true, detail: 'ok' };
144
- const text = `${probe.stderr ?? ''}${probe.stdout ?? ''}`.replace(ANSI_RE, '').trim();
145
- const named = text
146
- .split('\n')
147
- .filter((line) => line.trim() !== '')
148
- .slice(-2)
149
- .join(' | ')
150
- .slice(-240);
151
- return { ok: false, detail: named !== '' ? named : `exit ${probe.status ?? '?'}` };
152
- } finally {
153
- rmSync(probeCwd, { recursive: true, force: true });
154
- }
155
- }
156
-
157
- function runPreflight(): Preflight {
158
- const reasons: string[] = [];
159
- const warnings: string[] = [];
160
- const dirty = harnessDirtyPaths();
161
- if (dirty.length > 0 && values['allow-dirty'] !== true) {
162
- reasons.push(
163
- `working tree dirty on harness paths (git status --porcelain):\n ${dirty.slice(0, 10).join('\n ')}`,
164
- );
165
- }
166
- const install = kkPackageRoot();
167
- if (install === null) {
168
- warnings.push('kk binary not found on PATH; executed-vs-installed sync not checked');
169
- } else {
170
- const diffs = [
171
- ...diffDirs(join(repo, 'plugins', 'kk', 'workflows'), join(install, 'plugins', 'kk', 'workflows')),
172
- ...diffDirs(join(repo, 'plugins', 'kk', 'scripts'), join(install, 'plugins', 'kk', 'scripts')),
173
- ];
174
- if (diffs.length > 0) {
175
- reasons.push(`checkout diverges from installed kk (${install}): ${diffs.join('; ')}`);
176
- }
177
- }
178
- if (values['skip-probe'] !== true) {
179
- if (values.agent !== 'inline') {
180
- const probe = executorProbe(values.agent);
181
- if (!probe.ok) reasons.push(`executor probe failed for primary '${values.agent}': ${probe.detail}`);
182
- }
183
- const retry = values['retry-agent'];
184
- if (retry !== undefined && retry !== 'inline') {
185
- const retryProbe = executorProbe(retry);
186
- if (!retryProbe.ok) {
187
- warnings.push(`executor probe failed for retry '${retry}': ${retryProbe.detail}`);
188
- }
189
- }
190
- }
191
- return { ok: reasons.length === 0, reasons, warnings };
192
- }
193
-
194
- const preflight = runPreflight();
195
- if (!preflight.ok) {
196
- const refused = {
197
- runId,
198
- startedAt,
199
- completedAt: new Date().toISOString(),
200
- status: 'preflight-refused',
201
- exitCode: 5,
202
- agent: values.agent,
203
- retryAgent: values['retry-agent'],
204
- workDir,
205
- preflight: { reasons: preflight.reasons, warnings: preflight.warnings },
206
- error: preflight.reasons[0] ?? 'preflight refused',
207
- };
208
- writeFileSync(receiptPath, `${JSON.stringify(refused, null, 2)}\n`);
209
- console.error(`daily-scheduled-run: preflight refused run ${runId}`);
210
- for (const reason of preflight.reasons) console.error(` ! ${reason}`);
211
- for (const warning of preflight.warnings) console.error(` ~ ${warning}`);
212
- process.exit(5);
213
- }
214
- writeFileSync(
215
- receiptPath,
216
- JSON.stringify(
217
- {
218
- runId,
219
- startedAt,
220
- status: 'running',
221
- workDir,
222
- preflight: { warnings: preflight.warnings, probes: values['skip-probe'] === true ? 'skipped' : 'passed' },
223
- },
224
- null,
225
- 2,
226
- ),
227
- );
228
- let interrupted = false;
229
- let timedOut = false;
230
- let spawnError = '';
231
- let forceKill: ReturnType<typeof setTimeout> | undefined;
232
- const child = spawn(
233
- 'spur',
234
- [
235
- '--no-logo',
236
- 'workflow',
237
- 'run',
238
- `plugins/kk/workflows/${values.workflow}.yaml`,
239
- '--run-id',
240
- runId,
241
- '--vars',
242
- JSON.stringify(vars),
243
- '--quiet',
244
- ],
245
- { cwd: repo, detached: true, stdio: 'inherit' },
246
- );
247
-
248
- const ownedPids = new Set<number>();
249
- /** Snapshot descendants before the root exits, including workers that created their own groups. */
250
- function rememberDescendants(): void {
251
- if (child.pid === undefined) return;
252
- ownedPids.add(child.pid);
253
- const snapshot = spawnSync('ps', ['-axo', 'pid=,ppid='], { encoding: 'utf-8', timeout: 5000 });
254
- const rows = snapshot.stdout
255
- .trim()
256
- .split('\n')
257
- .map((line) => line.trim().split(/\s+/).map(Number));
258
- const descendants = new Set([child.pid]);
259
- let added = true;
260
- while (added) {
261
- added = false;
262
- for (const [pid, parent] of rows) {
263
- if (pid !== undefined && parent !== undefined && descendants.has(parent) && !descendants.has(pid)) {
264
- descendants.add(pid);
265
- added = true;
266
- }
267
- }
268
- }
269
- for (const pid of descendants) ownedPids.add(pid);
270
- }
271
-
272
- /** Stop only the recorded owned tree; process-group signals also catch late same-group forks. */
273
- function signalOwned(signal: NodeJS.Signals): void {
274
- if (child.pid === undefined) return;
275
- rememberDescendants();
276
- for (const pid of [...ownedPids].reverse()) {
277
- try {
278
- process.kill(-pid, signal);
279
- } catch {}
280
- try {
281
- process.kill(pid, signal);
282
- } catch {}
283
- }
284
- }
285
-
286
- function terminate(): void {
287
- signalOwned('SIGTERM');
288
- if (forceKill === undefined) {
289
- forceKill = setTimeout(() => {
290
- signalOwned('SIGKILL');
291
- }, 300);
292
- }
293
- }
294
- const onSignal = (): void => {
295
- interrupted = true;
296
- terminate();
297
- };
298
- process.once('SIGTERM', onSignal);
299
- process.once('SIGINT', onSignal);
300
- const deadline = setTimeout(() => {
301
- timedOut = true;
302
- terminate();
303
- }, timeoutMs);
304
- const exitCode = await new Promise<number>((done) => {
305
- child.once('error', (error) => {
306
- spawnError = error.message;
307
- done(1);
308
- });
309
- child.once('close', (code) => done(code ?? 1));
310
- });
311
- clearTimeout(deadline);
312
- if (forceKill !== undefined) clearTimeout(forceKill);
313
- // A killed shell can leave owned descendants that ignore TERM. Always finish the group before
314
- // recording a terminal outcome; no detached grandchild may continue to publish after a timeout.
315
- if (child.pid !== undefined && (timedOut || interrupted || exitCode !== 0)) {
316
- terminate();
317
- await Bun.sleep(300);
318
- signalOwned('SIGKILL');
319
- await Bun.sleep(100);
320
- }
321
- const workflowStatus = timedOut ? 'timed-out' : interrupted ? 'interrupted' : exitCode === 0 ? 'done' : 'failed';
322
- const primaryPublishStatus = isVoice3
323
- ? readOptional(join(workDir, '4-publish', 'publish-status.after-generate.txt'))
324
- : readOptional(join(workDir, '31-publish', `${stamp}_17_publish_publish-status.txt`));
325
- const runSummary = readOptional(join(workDir, 'run-report.summary.txt'));
326
- const cleanup: { command: string; exitCode: number | null }[] = [];
327
- let reservationRecovery: { status: string; reason: string; released?: number } = {
328
- status: 'retained',
329
- reason: 'workflow completed; publication settlement owns its reservations',
330
- };
331
- if (workflowStatus !== 'done' || runSummary?.startsWith('no-content:')) {
332
- // The caller gives the nested safety run this exact id. Unknown/already-terminal ids are
333
- // harmless cleanup failures; they never override the original workflow failure.
334
- if (workflowStatus !== 'done') {
335
- for (const id of [`${runId}-safety`, runId]) {
336
- const result = spawnSync('spur', ['workflow', 'cancel', id, '--json'], {
337
- cwd: repo,
338
- encoding: 'utf-8',
339
- timeout: 20000,
340
- });
341
- cleanup.push({ command: `spur workflow cancel ${id}`, exitCode: result.status });
342
- }
343
- }
344
- // Only a complete trace proving no channel send began permits recycling reservations. A
345
- // missing receipt alone is insufficient: a remote send may have succeeded before it crashed.
346
- const trace = spawnSync('spur', ['workflow', 'trace', runId, '--json'], {
347
- cwd: repo,
348
- encoding: 'utf-8',
349
- timeout: 20000,
350
- });
351
- reservationRecovery = { status: 'retained', reason: 'publication state could not be established' };
352
- try {
353
- const parsed = JSON.parse(trace.stdout) as {
354
- run?: { runId?: string; workflowName?: string; status?: string; startedAt?: string };
355
- events?: { kind?: string; node?: string; status?: string }[];
356
- };
357
- const sendNodes = isVoice3
358
- ? new Set(['publish', 'send', 'send-retry', 'repair', 'send-confirm'])
359
- : new Set([
360
- 'publish-surfdash',
361
- 'publish-podcast',
362
- 'xhs-publish',
363
- 'wechat-publish',
364
- 'translate-localize',
365
- 'translate',
366
- 'translate-retry',
367
- 'translate-sync',
368
- 'publish-classify',
369
- ]);
370
- const validTrace =
371
- trace.status === 0 &&
372
- parsed.run?.runId === runId &&
373
- parsed.run?.workflowName === values.workflow &&
374
- parsed.run?.status === (workflowStatus === 'done' ? 'done' : 'failed') &&
375
- Date.parse(parsed.run.startedAt ?? '') >= Date.parse(startedAt) - 1000 &&
376
- Date.parse(parsed.run.startedAt ?? '') <= Date.now() &&
377
- Array.isArray(parsed.events) &&
378
- parsed.events.length > 0;
379
- const sendStarted = parsed.events?.some(
380
- (event) => event.kind === 'action' && sendNodes.has(event.node ?? '') && event.status !== 'skipped',
381
- );
382
- if (validTrace && !sendStarted) {
383
- // Cancellation is durable before reuse. Require a second stable snapshot after the
384
- // owned processes are gone, so an in-flight or partially finalized row cannot pass.
385
- await Bun.sleep(200);
386
- const secondTrace = spawnSync('spur', ['workflow', 'trace', runId, '--json'], {
387
- cwd: repo,
388
- encoding: 'utf-8',
389
- timeout: 20000,
390
- });
391
- const second = JSON.parse(secondTrace.stdout) as typeof parsed;
392
- if (
393
- secondTrace.status !== 0 ||
394
- JSON.stringify(second.run) !== JSON.stringify(parsed.run) ||
395
- JSON.stringify(second.events) !== JSON.stringify(parsed.events)
396
- ) {
397
- throw new Error('failed-run trace is not stable after cancellation');
398
- }
399
- const release = spawnSync('kk', ['store', 'release', '--topic', 'ai-news', '--run', runId], {
400
- cwd: repo,
401
- encoding: 'utf-8',
402
- timeout: 20000,
403
- });
404
- cleanup.push({ command: 'kk store release (verified pre-publication failure)', exitCode: release.status });
405
- const result = release.status === 0 ? (JSON.parse(release.stdout) as { released?: unknown }) : null;
406
- reservationRecovery =
407
- result !== null && typeof result.released === 'number'
408
- ? { status: 'released', reason: 'trace proves no channel send began', released: result.released }
409
- : { status: 'retained', reason: 'reservation release did not produce a valid receipt' };
410
- } else if (sendStarted) {
411
- reservationRecovery = { status: 'retained', reason: 'a channel send began; preserve uncertain delivery' };
412
- }
413
- } catch {
414
- // Unreadable/truncated evidence or an unexpected CLI shape must never cause reuse of a
415
- // potentially aired story. Keep the reservation and the original failure visible.
416
- }
417
- }
418
- const ledger = spawnSync('kk', ['ledger', 'sync', '--workflow', values.workflow, '--work-dir', workDir], {
419
- cwd: repo,
420
- encoding: 'utf-8',
421
- timeout: 20000,
422
- });
423
- cleanup.push({ command: 'kk ledger sync', exitCode: ledger.status });
424
- function readOptional(path: string): string | null {
425
- try {
426
- return readFileSync(path, 'utf-8').trim();
427
- } catch {
428
- return null;
429
- }
430
- }
431
- const requiredChannels = values['required-channels']
432
- .split(',')
433
- .map((channel) => channel.trim())
434
- .filter(Boolean);
435
- let channelCompleteness: { channel: string; state: string; detail?: string; required?: boolean; dummy?: boolean }[] =
436
- [];
437
- try {
438
- if (isVoice3) {
439
- const outcome = JSON.parse(
440
- readOptional(join(workDir, '4-publish', 'outcome.after-generate.json')) ?? 'null',
441
- ) as { rows?: unknown } | null;
442
- if (Array.isArray(outcome?.rows)) {
443
- channelCompleteness = outcome.rows.flatMap(
444
- (row): { channel: string; state: string; required: boolean; dummy: boolean }[] => {
445
- if (row === null || typeof row !== 'object') return [];
446
- const r = row as { id?: unknown; required?: unknown; dummy?: unknown; status?: unknown };
447
- if (typeof r.id !== 'string' || typeof r.status !== 'string') return [];
448
- return [
449
- {
450
- channel: r.id,
451
- state: r.status === 'succeeded' ? 'done' : r.status,
452
- required: r.required === true,
453
- dummy: r.dummy === true,
454
- },
455
- ];
456
- },
457
- );
458
- }
459
- } else {
460
- const parsed = JSON.parse(
461
- readOptional(join(workDir, '31-publish', `${stamp}_17_publish_completeness.json`)) ?? 'null',
462
- ) as { rows?: unknown } | null;
463
- if (Array.isArray(parsed?.rows)) {
464
- channelCompleteness = parsed.rows.filter(
465
- (row): row is { channel: string; state: string; detail?: string } =>
466
- row !== null &&
467
- typeof row === 'object' &&
468
- typeof row.channel === 'string' &&
469
- typeof row.state === 'string',
470
- );
471
- }
472
- }
473
- } catch {}
474
- const missingRequiredChannels = isVoice3
475
- ? channelCompleteness
476
- .filter((row) => row.required === true && row.dummy !== true)
477
- .filter((row) => row.state !== 'done')
478
- .map((row) => row.channel)
479
- : requiredChannels.filter((channel) => {
480
- const rows = channelCompleteness.filter((row) => row.channel === channel);
481
- return rows.length !== 1 || rows[0]?.state !== 'done';
482
- });
483
- /** Generate-only receipts use the same fail-closed bundle admission as posting and validation. */
484
- function inspectGenerationOnly(): { status: string; reason: string } {
485
- const inspector = join(repo, 'scripts/daily-ai-news.ts');
486
- if (!existsSync(inspector)) return { status: 'incomplete', reason: `bundle inspector not found: ${inspector}` };
487
- // The child is terminal, but our initial receipt still says running. Mark the inspection phase so
488
- // the shared admission check does not mistake this supervisor for a concurrent active run.
489
- writeFileSync(receiptPath, JSON.stringify({ runId, startedAt, status: 'inspecting', workDir }, null, 2));
490
- const probe = spawnSync(process.execPath, [inspector, 'inspect', '--work-dir', workDir, '--run-date', stamp], {
491
- cwd: repo,
492
- encoding: 'utf-8',
493
- timeout: 30000,
494
- maxBuffer: 1024 * 1024,
495
- });
496
- try {
497
- const parsed = JSON.parse(probe.stdout) as { status?: unknown; reason?: unknown };
498
- if (typeof parsed.status === 'string') {
499
- return {
500
- status: probe.status === 0 && parsed.status === 'complete' ? 'complete' : 'incomplete',
501
- reason: typeof parsed.reason === 'string' ? parsed.reason : `inspector exited ${probe.status ?? 1}`,
502
- };
503
- }
504
- } catch {}
505
- return {
506
- status: 'incomplete',
507
- reason: probe.stderr.trim() || probe.error?.message || `bundle inspector exited ${probe.status ?? 1}`,
508
- };
509
- }
510
- const generationInspection =
511
- generateOnly && workflowStatus === 'done' && !runSummary?.startsWith('no-content:')
512
- ? inspectGenerationOnly()
513
- : null;
514
- // A terminal green workflow can mean "no content" or failed delivery. Make that observable to
515
- // the scheduler instead of equating the workflow's process exit with a published edition.
516
- // A voice3 outcome classified 'full' already proves every non-dummy row succeeded (0326 R2).
517
- const status =
518
- workflowStatus !== 'done'
519
- ? workflowStatus
520
- : runSummary?.startsWith('no-content:')
521
- ? 'no-content'
522
- : generateOnly
523
- ? generationInspection?.status === 'complete'
524
- ? 'done'
525
- : 'incomplete'
526
- : primaryPublishStatus === 'full' && !(!isVoice3 && missingRequiredChannels.length > 0)
527
- ? 'done'
528
- : 'incomplete';
529
- function buildTriage(finalStatus: string, exitCode: number): TriageReport | null {
530
- try {
531
- const inlineReceipt: TriageReceipt = {
532
- status: finalStatus,
533
- startedAt,
534
- completedAt: new Date().toISOString(),
535
- workDir,
536
- agent: values.agent,
537
- retryAgent: values['retry-agent'],
538
- exitCode,
539
- error: spawnError || null,
540
- };
541
- const report = collectTriage(repo, runId, { receipt: inlineReceipt, workflow: values.workflow });
542
- console.error('daily-scheduled-run: triage summary');
543
- for (const line of summarizeTriage(report)) console.error(` ${line}`);
544
- return report;
545
- } catch (error) {
546
- console.error(`daily-scheduled-run: triage collection failed: ${String(error)}`);
547
- return null;
548
- }
549
- }
550
-
551
- const terminalExitCode = timedOut ? 124 : interrupted ? 143 : exitCode !== 0 ? exitCode : status === 'done' ? 0 : 4;
552
- const triage =
553
- status === 'failed' || status === 'timed-out' || status === 'interrupted' || status === 'incomplete'
554
- ? buildTriage(status, terminalExitCode)
555
- : null;
556
- const receipt = {
557
- runId,
558
- startedAt,
559
- completedAt: new Date().toISOString(),
560
- status,
561
- generateOnly,
562
- generationInspection,
563
- exitCode: terminalExitCode,
564
- workDir,
565
- timeoutMs,
566
- agent: values.agent,
567
- retryAgent: values['retry-agent'],
568
- error: spawnError || null,
569
- primaryPublishStatus,
570
- channelCompleteness,
571
- missingRequiredChannels,
572
- runSummary,
573
- reservationRecovery,
574
- cleanup,
575
- triage,
576
- };
577
- writeFileSync(receiptPath, `${JSON.stringify(receipt, null, 2)}\n`);
578
- console.log(JSON.stringify(receipt));
579
- process.removeListener('SIGTERM', onSignal);
580
- process.removeListener('SIGINT', onSignal);
581
- process.exit(receipt.exitCode);