@gobing-ai/knowledge-kit 0.1.14 → 0.1.16

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 (120) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/index.js +2399 -177
  3. package/package.json +1 -1
  4. package/plugins/generations/content-gen/dist/index.js +60 -54
  5. package/plugins/generations/content-gen/src/storm.ts +94 -61
  6. package/plugins/generations/core-facts-gen/dist/index.js +3 -3
  7. package/plugins/generations/daily-article-gen/dist/index.js +3 -3
  8. package/plugins/generations/dailynews-gen/dist/index.js +73 -10
  9. package/plugins/generations/dailynews-gen/src/index.ts +23 -1
  10. package/plugins/generations/dailynews-gen/src/script-plan.ts +103 -5
  11. package/plugins/generations/episode-plan-gen/dist/index.js +3 -3
  12. package/plugins/generations/gemini-tts/dist/index.js +3 -3
  13. package/plugins/generations/image-gen/README.md +31 -10
  14. package/plugins/generations/image-gen/assets/sample/cover__quasi-news-podcast.jpg +0 -0
  15. package/plugins/generations/image-gen/assets/sample/daily-news-cover__quasi-news-podcast.jpg +0 -0
  16. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__clean-webapp-ui.jpg +0 -0
  17. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__cute.jpg +0 -0
  18. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__daily-news.jpg +0 -0
  19. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__editorial.jpg +0 -0
  20. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__fresh.jpg +0 -0
  21. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__minimalist.jpg +0 -0
  22. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__photorealistic.jpg +0 -0
  23. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__quasi-news-podcast.jpg +0 -0
  24. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__sketch.jpg +0 -0
  25. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__technical-diagram.jpg +0 -0
  26. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__vibrant.jpg +0 -0
  27. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__warm.jpg +0 -0
  28. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__xhs-knowledge.jpg +0 -0
  29. package/plugins/generations/image-gen/assets/sample/free__quasi-news-podcast.jpg +0 -0
  30. package/plugins/generations/image-gen/assets/sample/illustration__quasi-news-podcast.jpg +0 -0
  31. package/plugins/generations/image-gen/assets/sample/xhs-card__quasi-news-podcast.jpg +0 -0
  32. package/plugins/generations/image-gen/dist/index.js +3 -3
  33. package/plugins/generations/image-gen/presets/formats/daily-news-podcast-cover.yaml +18 -0
  34. package/plugins/generations/image-gen/presets/styles/quasi-news-podcast.yaml +9 -0
  35. package/plugins/generations/news-report-gen/dist/index.js +3 -3
  36. package/plugins/generations/voice-gen/dist/index.js +3 -3
  37. package/plugins/generations/voxcpm-tts/dist/index.js +3 -3
  38. package/plugins/ingestions/aihot-ingest/dist/index.js +3 -3
  39. package/plugins/ingestions/horizon-ingest/dist/index.js +3 -3
  40. package/plugins/ingestions/last30days-ingest/dist/index.js +3 -3
  41. package/plugins/ingestions/web-search/dist/index.js +3 -3
  42. package/plugins/kk/plugin.json +1 -1
  43. package/plugins/kk/publish-presets/daily-ai-voice-migration.json +12 -3
  44. package/plugins/kk/publish-presets/daily-ai-voice.json +11 -3
  45. package/plugins/kk/scripts/cover-compositor.ts +152 -0
  46. package/plugins/kk/scripts/daily-cover-mock.ts +164 -0
  47. package/plugins/kk/scripts/daily-scheduled-run.ts +192 -3
  48. package/plugins/kk/scripts/daily-stages.ts +599 -27
  49. package/plugins/kk/scripts/daily-triage-core.ts +451 -0
  50. package/plugins/kk/scripts/daily-triage.ts +74 -0
  51. package/plugins/kk/scripts/kk-workflow-stages.ts +51 -6
  52. package/plugins/kk/skills/content-judge/SKILL.md +5 -4
  53. package/plugins/kk/skills/content-judge/references/rubrics.md +14 -0
  54. package/plugins/kk/skills/content-safety/references/platforms/wechatmp.md +16 -10
  55. package/plugins/kk/skills/news-editorial/SKILL.md +122 -0
  56. package/plugins/kk/skills/news-editorial/references/selection.md +47 -0
  57. package/plugins/kk/skills/news-editorial/references/style-contract.zh.md +100 -0
  58. package/plugins/kk/skills/publish/SKILL.md +4 -4
  59. package/plugins/kk/skills/web-automation/SKILL.md +229 -77
  60. package/plugins/kk/skills/web-automation/references/browser-launch.md +127 -36
  61. package/plugins/kk/skills/wiki-authoring/SKILL.md +53 -0
  62. package/plugins/kk/skills/wiki-authoring/references/page-shapes.md +44 -0
  63. package/plugins/kk/workflows/kk-daily-ai-voice2.yaml +4 -6
  64. package/plugins/kk/workflows/kk-daily-ai-voice3.yaml +185 -224
  65. package/plugins/kk/workflows/kk-daily-publish3.yaml +16 -8
  66. package/plugins/kk/workflows/kk-daily-safety.yaml +32 -7
  67. package/plugins/publishings/bilibili-pub/dist/index.js +6 -4
  68. package/plugins/publishings/bilibili-pub/dist/profile-check.js +3 -1
  69. package/plugins/publishings/cnblogs-pub/dist/index.js +6 -4
  70. package/plugins/publishings/cnblogs-pub/dist/profile-check.js +3 -1
  71. package/plugins/publishings/csdn-pub/dist/index.js +6 -4
  72. package/plugins/publishings/csdn-pub/dist/profile-check.js +6 -4
  73. package/plugins/publishings/emdash-pub/dist/index.js +3 -3
  74. package/plugins/publishings/infoq-pub/dist/index.js +6 -4
  75. package/plugins/publishings/infoq-pub/dist/profile-check.js +6 -4
  76. package/plugins/publishings/jike-pub/dist/index.js +6 -4
  77. package/plugins/publishings/jike-pub/dist/profile-check.js +6 -4
  78. package/plugins/publishings/juejin-pub/dist/index.js +6 -4
  79. package/plugins/publishings/juejin-pub/dist/profile-check.js +6 -4
  80. package/plugins/publishings/linkedin-pub/dist/index.js +6 -4
  81. package/plugins/publishings/linkedin-pub/dist/profile-check.js +6 -4
  82. package/plugins/publishings/medium-pub/dist/index.js +3 -3
  83. package/plugins/publishings/podcast-pub/dist/index.js +148 -5
  84. package/plugins/publishings/podcast-pub/src/index.ts +71 -2
  85. package/plugins/publishings/podcast-pub/src/map.ts +3 -0
  86. package/plugins/publishings/podcast-pub/src/transcript.ts +195 -0
  87. package/plugins/publishings/qiita-pub/dist/index.js +3 -3
  88. package/plugins/publishings/shipinhao-pub/dist/index.js +227 -53
  89. package/plugins/publishings/shipinhao-pub/dist/profile-check.js +51 -2
  90. package/plugins/publishings/shipinhao-pub/plugin.json +2 -2
  91. package/plugins/publishings/shipinhao-pub/src/flow.ts +335 -79
  92. package/plugins/publishings/shipinhao-pub/src/index.ts +16 -8
  93. package/plugins/publishings/shipinhao-pub/src/profile-check.ts +1 -1
  94. package/plugins/publishings/shipinhao-pub/src/selectors.ts +103 -5
  95. package/plugins/publishings/sspai-pub/dist/index.js +6 -4
  96. package/plugins/publishings/sspai-pub/dist/profile-check.js +3 -1
  97. package/plugins/publishings/substack-pub/dist/index.js +6 -4
  98. package/plugins/publishings/substack-pub/dist/profile-check.js +6 -4
  99. package/plugins/publishings/surfdash-pub/dist/index.js +237 -14
  100. package/plugins/publishings/surfdash-pub/src/index.ts +127 -6
  101. package/plugins/publishings/surfdash-pub/src/topic-claims.ts +189 -0
  102. package/plugins/publishings/threads-pub/dist/index.js +3 -3
  103. package/plugins/publishings/wechatmp-pub/dist/index.js +62 -40
  104. package/plugins/publishings/wechatmp-pub/dist/profile-check.js +6 -4
  105. package/plugins/publishings/wechatmp-pub/src/enrich.ts +10 -3
  106. package/plugins/publishings/wechatmp-pub/src/flow.ts +73 -37
  107. package/plugins/publishings/wechatmp-pub/src/page.ts +14 -0
  108. package/plugins/publishings/weibo-pub/dist/index.js +6 -4
  109. package/plugins/publishings/weibo-pub/dist/profile-check.js +6 -4
  110. package/plugins/publishings/x-pub/dist/index.js +6 -4
  111. package/plugins/publishings/x-pub/dist/profile-check.js +6 -4
  112. package/plugins/publishings/xhs-pub/dist/index.js +562 -34
  113. package/plugins/publishings/xhs-pub/dist/profile-check.js +25 -4
  114. package/plugins/publishings/xhs-pub/src/errors.ts +45 -0
  115. package/plugins/publishings/xhs-pub/src/flow.ts +773 -45
  116. package/plugins/publishings/xhs-pub/src/page.ts +33 -0
  117. package/plugins/publishings/xiaoyuzhou-pub/dist/index.js +6 -4
  118. package/plugins/publishings/xiaoyuzhou-pub/dist/profile-check.js +3 -1
  119. package/plugins/publishings/zenn-pub/dist/index.js +3 -3
  120. package/plugins/kk/scripts/daily-voice-style.zh.md +0 -70
@@ -0,0 +1,451 @@
1
+ /**
2
+ * Triage collector for failed daily runs (0347 F2/F3, 2026-11-10).
3
+ *
4
+ * A daily-run failure used to cost a 45-call forensic session across six stores before anyone
5
+ * could name the layer (2026-11-09: two interleaved causes — a stale working-tree workflow and a
6
+ * quota-dead executor chain). This module gathers the evidence the first five minutes actually
7
+ * need, at failure time, into one structure:
8
+ *
9
+ * - which workflow bytes executed (current checkout file + sha + git dirty flag on harness paths),
10
+ * - the last failed node from the parent trace, with the executor's partial-output tail,
11
+ * - nested runs (the safety machine) found by time-window + workflow name, with per-node receipts,
12
+ * - the engine escalation decision, and rule-based suggestions that name the next action.
13
+ *
14
+ * Pure parsing helpers are exported for tests; IO helpers are thin and never throw — a triage
15
+ * that cannot collect must not mask the original failure it is describing.
16
+ */
17
+ import { spawnSync } from 'node:child_process';
18
+ import { createHash } from 'node:crypto';
19
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
20
+ import { basename, join } from 'node:path';
21
+
22
+ export interface TriageReceipt {
23
+ status?: string;
24
+ startedAt?: string;
25
+ completedAt?: string;
26
+ workDir?: string;
27
+ agent?: string;
28
+ retryAgent?: string;
29
+ exitCode?: number;
30
+ error?: string | null;
31
+ }
32
+
33
+ export interface ExecutedDefinition {
34
+ workflow: string;
35
+ path: string;
36
+ sha256: string | null;
37
+ gitDirty: string[];
38
+ }
39
+
40
+ export interface FailedNode {
41
+ id: string;
42
+ status: string;
43
+ startedAt?: string;
44
+ completedAt?: string;
45
+ stderrTail?: string;
46
+ }
47
+
48
+ export interface NestedRun {
49
+ runId: string;
50
+ workflow?: string;
51
+ status?: string;
52
+ terminalState?: string;
53
+ startedAt?: string;
54
+ finalizedAt?: string;
55
+ receipts: { node: string; ok: boolean; outcome?: string; reason?: string }[];
56
+ }
57
+
58
+ export interface TriageReport {
59
+ runId: string;
60
+ collectedAt: string;
61
+ receipt: TriageReceipt | null;
62
+ executed: ExecutedDefinition | null;
63
+ failedNode: FailedNode | null;
64
+ nestedRuns: NestedRun[];
65
+ escalation: { trigger?: string; decision?: string; reason?: string; createdAt?: string } | null;
66
+ suggestions: string[];
67
+ }
68
+
69
+ const RECEIPTS_DIR = join('.spur', 'run');
70
+ /** When the failed-node text names no nested workflow, assume the daily safety machine. */
71
+ const WORKFLOW_NESTED_FALLBACK = 'kk-daily-safety';
72
+ const RUNS_DIR = join('.spur', 'memory', 'runs');
73
+ const WORKS_FLOW_DIR = join('.works', 'kk-daily-ai-voice2');
74
+ const FAILED_RECEIPT_STATUSES = new Set(['failed', 'timed-out', 'interrupted', 'incomplete', 'preflight-refused']);
75
+ /** Receipt statuses that mean the supervisor is mid-flight, not failed. */
76
+ const ACTIVE_RECEIPT_STATUSES = new Set(['running', 'inspecting']);
77
+ const GOOD_RECEIPT_STATUSES = new Set(['done', 'no-content']);
78
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: matching the ANSI ESC control char is the point of the stripper
79
+ const ANSI = /\u001b\[[0-9;]*[A-Za-z]/g;
80
+
81
+ function readText(path: string): string | null {
82
+ try {
83
+ return readFileSync(path, 'utf-8');
84
+ } catch {
85
+ return null;
86
+ }
87
+ }
88
+
89
+ function readTriageJson(path: string): Record<string, unknown> | null {
90
+ try {
91
+ const parsed = JSON.parse(readFileSync(path, 'utf-8')) as unknown;
92
+ return parsed !== null && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : null;
93
+ } catch {
94
+ return null;
95
+ }
96
+ }
97
+
98
+ function sha256File(path: string): string | null {
99
+ try {
100
+ return createHash('sha256').update(readFileSync(path)).digest('hex');
101
+ } catch {
102
+ return null;
103
+ }
104
+ }
105
+
106
+ /** Harness paths whose dirty state invalidated the 2026-11-09 04:30 run (R1). */
107
+ export function gitDirtyPaths(repo: string): string[] {
108
+ const result = spawnSync('git', ['status', '--porcelain', '--', 'plugins/kk', '.spur/workflows'], {
109
+ cwd: repo,
110
+ encoding: 'utf-8',
111
+ timeout: 10_000,
112
+ });
113
+ if (result.status !== 0) return [];
114
+ return result.stdout
115
+ .split('\n')
116
+ .map((line) => line.slice(3).trim())
117
+ .filter(Boolean);
118
+ }
119
+
120
+ export interface ParsedTrace {
121
+ workflow?: string;
122
+ status?: string;
123
+ startedAt?: string;
124
+ finalizedAt?: string;
125
+ failedNode: FailedNode | null;
126
+ }
127
+
128
+ /** Extract the last failed action event from a `spur workflow trace --json` payload. */
129
+ export function parseTrace(stdout: string): ParsedTrace {
130
+ let parsed: Record<string, unknown>;
131
+ try {
132
+ parsed = JSON.parse(stdout) as Record<string, unknown>;
133
+ } catch {
134
+ return { failedNode: null };
135
+ }
136
+ const run = (parsed.run ?? null) as Record<string, unknown> | null;
137
+ const events = Array.isArray(parsed.events) ? (parsed.events as Record<string, unknown>[]) : [];
138
+ let failedNode: FailedNode | null = null;
139
+ for (const event of events) {
140
+ if (event.kind !== 'action') continue;
141
+ const status = String(event.status ?? '');
142
+ if (status === 'done' || status === 'succeeded' || status === 'skipped') continue;
143
+ const id = typeof event.node === 'string' ? event.node : '';
144
+ if (id === '') continue;
145
+ failedNode = {
146
+ id,
147
+ status,
148
+ ...(typeof event.startedAt === 'string' ? { startedAt: event.startedAt } : {}),
149
+ ...(typeof event.completedAt === 'string' ? { completedAt: event.completedAt } : {}),
150
+ ...(typeof event.error === 'string' ? { stderrTail: event.error.slice(-400) } : {}),
151
+ };
152
+ }
153
+ return {
154
+ ...(run !== null && typeof run.workflowName === 'string' ? { workflow: run.workflowName } : {}),
155
+ ...(run !== null && typeof run.status === 'string' ? { status: run.status } : {}),
156
+ ...(run !== null && typeof run.startedAt === 'string' ? { startedAt: run.startedAt } : {}),
157
+ ...(run !== null && typeof run.finalizedAt === 'string' ? { finalizedAt: run.finalizedAt } : {}),
158
+ failedNode,
159
+ };
160
+ }
161
+
162
+ function traceStderrTail(repo: string, runId: string, failedNode: FailedNode): string | undefined {
163
+ if (failedNode.stderrTail) return failedNode.stderrTail;
164
+ const partial = readText(join(repo, RECEIPTS_DIR, `${runId}-${failedNode.id}-partial.md`));
165
+ if (partial === null) return undefined;
166
+ return partial.replace(ANSI, '').trimEnd().slice(-400);
167
+ }
168
+
169
+ /** Nested runs overlap the parent's wall clock and are not the parent workflow itself. */
170
+ export function findNestedRuns(
171
+ runsDir: string,
172
+ parent: { runId: string; startedAt?: string; finalizedAt?: string; workflow?: string },
173
+ workflowFilter: Set<string> | null = null,
174
+ ): NestedRun[] {
175
+ let entries: string[] = [];
176
+ try {
177
+ entries = readdirSync(runsDir).filter((name) => name.endsWith('.state.json'));
178
+ } catch {
179
+ return [];
180
+ }
181
+ const start = parent.startedAt ? Date.parse(parent.startedAt) : Number.NaN;
182
+ const end = parent.finalizedAt ? Date.parse(parent.finalizedAt) : Date.now();
183
+ if (Number.isNaN(start) || Number.isNaN(end)) return [];
184
+ const nested: NestedRun[] = [];
185
+ for (const entry of entries) {
186
+ const state = readTriageJson(join(runsDir, entry));
187
+ if (state === null) continue;
188
+ const runId = String(state.runId ?? basename(entry, '.state.json'));
189
+ if (runId === '' || runId === parent.runId) continue;
190
+ if (
191
+ workflowFilter !== null &&
192
+ (typeof state.workflowName !== 'string' || !workflowFilter.has(state.workflowName))
193
+ )
194
+ continue;
195
+ const runStart = typeof state.startedAt === 'string' ? Date.parse(state.startedAt) : Number.NaN;
196
+ if (Number.isNaN(runStart) || runStart < start - 1000 || runStart > end) continue;
197
+ const receiptsDir = join(runsDir, '..', '..', '..', RECEIPTS_DIR, runId, 'receipts');
198
+ const receipts: NestedRun['receipts'] = [];
199
+ try {
200
+ for (const file of readdirSync(receiptsDir)) {
201
+ if (!file.endsWith('.json')) continue;
202
+ const receipt = readTriageJson(join(receiptsDir, file));
203
+ const outcome = receipt === null ? undefined : String(receipt.outcome ?? '');
204
+ receipts.push({
205
+ node: basename(file, '.json'),
206
+ ok: outcome === 'succeeded' || outcome === 'done',
207
+ outcome,
208
+ ...(receipt !== null && typeof receipt.reason === 'string' ? { reason: receipt.reason } : {}),
209
+ });
210
+ }
211
+ } catch {
212
+ // No receipts dir: record the run without receipt detail.
213
+ }
214
+ nested.push({
215
+ runId,
216
+ ...(typeof state.workflowName === 'string' ? { workflow: state.workflowName } : {}),
217
+ ...(typeof state.status === 'string' ? { status: state.status } : {}),
218
+ ...(typeof state.terminalState === 'string' ? { terminalState: state.terminalState } : {}),
219
+ ...(typeof state.startedAt === 'string' ? { startedAt: state.startedAt } : {}),
220
+ ...(typeof state.finalizedAt === 'string' ? { finalizedAt: state.finalizedAt } : {}),
221
+ receipts,
222
+ });
223
+ }
224
+ return nested.sort((a, b) => (a.startedAt ?? '').localeCompare(b.startedAt ?? ''));
225
+ }
226
+
227
+ /** Rule-based next actions, most specific first. Evidence: executor reasons + failed-node stderr. */
228
+ export function suggestionsFor(report: Omit<TriageReport, 'suggestions' | 'collectedAt' | 'runId'>): string[] {
229
+ const evidence = [
230
+ report.failedNode?.stderrTail ?? '',
231
+ ...report.nestedRuns.flatMap((run) => run.receipts.map((receipt) => receipt.reason ?? '')),
232
+ report.receipt?.error ?? '',
233
+ ]
234
+ .join('\n')
235
+ .toLowerCase();
236
+ const suggestions: string[] = [];
237
+ if (
238
+ /accountquotaexceeded|monthly usage quota|weekly limit|no credits remaining|invalid credential/.test(evidence)
239
+ ) {
240
+ suggestions.push(
241
+ 'executor account exhausted (quota/credits/credential) — probe healthy executors (spur agent run --agent <name> "Reply with exactly: OK"), switch the schedule entry to a healthy pair, and rerun; preflight will refuse the day otherwise',
242
+ );
243
+ } else if (/exit code 3|exhausted/.test(evidence)) {
244
+ suggestions.push(
245
+ 'agent executor outage — verify the primary/retry executors, then rerun; the 07:00 retrigger retries automatically once the receipt is failed',
246
+ );
247
+ }
248
+ if (/plan item count/.test(evidence)) {
249
+ suggestions.push(
250
+ 'script/article section divergence — move aside 21-plan/<date>_03_plan_plan.json, 21-plan/<date>_03_curate_excluded.json, 24-script/<date>_08_script-write_plan.json and 24-script/<date>_08_script_voicescript.yaml so curate re-splits consistently, then rerun',
251
+ );
252
+ }
253
+ if (report.nestedRuns.some((run) => run.terminalState === 'infra-fail')) {
254
+ suggestions.push(
255
+ 'safety reached infra-fail — the gate refused for missing evidence (executor outage), not a content verdict; recover executors and rerun',
256
+ );
257
+ } else if (report.nestedRuns.some((run) => run.terminalState === 'block')) {
258
+ suggestions.push(
259
+ 'safety verdict block — inspect the 09_safety-* artifacts (report/verdict/status) under the scope dir before any rerun',
260
+ );
261
+ }
262
+ if (report.executed !== null && report.executed.gitDirty.length > 0) {
263
+ suggestions.push(
264
+ `harness paths are dirty right now (${report.executed.gitDirty.slice(0, 3).join(', ')}) — the NEXT scheduled run executes the working tree; commit or stash first`,
265
+ );
266
+ }
267
+ if (suggestions.length === 0) {
268
+ suggestions.push('inspect the failed node stderr and nested receipts, then decide');
269
+ }
270
+ return suggestions;
271
+ }
272
+
273
+ /** Collect everything knowable about one failed run. Never throws for missing pieces. */
274
+ export function collectTriage(
275
+ repo: string,
276
+ runId: string,
277
+ opts: { receiptPath?: string; receipt?: TriageReceipt; workflow?: string; env?: NodeJS.ProcessEnv } = {},
278
+ ): TriageReport {
279
+ const report: TriageReport = {
280
+ runId,
281
+ collectedAt: new Date().toISOString(),
282
+ receipt: null,
283
+ executed: null,
284
+ failedNode: null,
285
+ nestedRuns: [],
286
+ escalation: null,
287
+ suggestions: [],
288
+ };
289
+ if (opts.receipt !== undefined) {
290
+ report.receipt = opts.receipt;
291
+ } else {
292
+ const receiptPath = opts.receiptPath ?? findReceiptByRunId(repo, runId);
293
+ if (receiptPath !== null) {
294
+ const raw = readTriageJson(receiptPath);
295
+ if (raw !== null) {
296
+ report.receipt = {
297
+ ...(typeof raw.status === 'string' ? { status: raw.status } : {}),
298
+ ...(typeof raw.startedAt === 'string' ? { startedAt: raw.startedAt } : {}),
299
+ ...(typeof raw.completedAt === 'string' ? { completedAt: raw.completedAt } : {}),
300
+ ...(typeof raw.workDir === 'string' ? { workDir: raw.workDir } : {}),
301
+ ...(typeof raw.agent === 'string' ? { agent: raw.agent } : {}),
302
+ ...(typeof raw.retryAgent === 'string' ? { retryAgent: raw.retryAgent } : {}),
303
+ ...(typeof raw.exitCode === 'number' ? { exitCode: raw.exitCode } : {}),
304
+ ...(typeof raw.error === 'string' || raw.error === null
305
+ ? { error: raw.error as string | null }
306
+ : {}),
307
+ };
308
+ }
309
+ }
310
+ }
311
+ const trace = spawnSync('spur', ['--no-logo', 'workflow', 'trace', runId, '--json'], {
312
+ cwd: repo,
313
+ encoding: 'utf-8',
314
+ timeout: 20_000,
315
+ // opts.env layers over the inherited environment (tests shim `spur` through PATH).
316
+ ...(opts.env ? { env: { ...process.env, ...opts.env } } : {}),
317
+ });
318
+ if (trace.status === 0 && trace.stdout.trim() !== '') {
319
+ const parsed = parseTrace(trace.stdout);
320
+ const workflow = opts.workflow ?? parsed.workflow ?? '';
321
+ report.failedNode = parsed.failedNode;
322
+ if (report.failedNode !== null) {
323
+ report.failedNode.stderrTail = traceStderrTail(repo, runId, report.failedNode);
324
+ }
325
+ const workflowFile = join(repo, 'plugins', 'kk', 'workflows', `${workflow}.yaml`);
326
+ if (workflow !== '' && existsSync(workflowFile)) {
327
+ report.executed = {
328
+ workflow,
329
+ path: workflowFile,
330
+ sha256: sha256File(workflowFile),
331
+ gitDirty: gitDirtyPaths(repo),
332
+ };
333
+ }
334
+ // Nested machines are the ones the parent's failing command itself names (…\.yaml); a bare
335
+ // time-window scan also catches neighbor jobs (kk-collect, wrapup pipelines) that merely
336
+ // overlapped the parent's wall clock.
337
+ const nestedNames = new Set(
338
+ (report.failedNode?.stderrTail ?? '').match(/[\w.-]+\.yaml/g)?.map((file) => file.replace(/\.yaml$/, '')) ??
339
+ [],
340
+ );
341
+ report.nestedRuns = findNestedRuns(
342
+ join(repo, RUNS_DIR),
343
+ {
344
+ runId,
345
+ startedAt: parsed.startedAt,
346
+ finalizedAt: parsed.finalizedAt,
347
+ workflow: workflow || undefined,
348
+ },
349
+ nestedNames.size > 0 ? nestedNames : new Set([WORKFLOW_NESTED_FALLBACK]),
350
+ );
351
+ }
352
+ const escalation = readTriageJson(join(repo, RECEIPTS_DIR, `${runId}-escalation.json`));
353
+ if (escalation !== null) {
354
+ const decision = (escalation.decision ?? null) as Record<string, unknown> | null;
355
+ report.escalation = {
356
+ ...(typeof escalation.trigger === 'string' ? { trigger: escalation.trigger } : {}),
357
+ ...(decision !== null && typeof decision.kind === 'string' ? { decision: decision.kind } : {}),
358
+ ...(decision !== null && typeof decision.reason === 'string' ? { reason: decision.reason } : {}),
359
+ ...(typeof escalation.createdAt === 'string' ? { createdAt: escalation.createdAt } : {}),
360
+ };
361
+ }
362
+ report.suggestions = suggestionsFor({
363
+ receipt: report.receipt,
364
+ executed: report.executed,
365
+ failedNode: report.failedNode,
366
+ nestedRuns: report.nestedRuns,
367
+ escalation: report.escalation,
368
+ });
369
+ return report;
370
+ }
371
+
372
+ /** The five lines an operator reads before deciding anything else. */
373
+ export function summarizeTriage(report: TriageReport): string[] {
374
+ const receipt = report.receipt;
375
+ const line1 =
376
+ receipt !== null
377
+ ? `trigger: ${receipt.status ?? '?'} (exit ${receipt.exitCode ?? '?'}) completedAt=${receipt.completedAt ?? '?'} agent=${receipt.agent ?? '?'}`
378
+ : `trigger: unknown (no receipt found for ${report.runId})`;
379
+ const executed = report.executed;
380
+ const line2 =
381
+ executed !== null
382
+ ? `executed: ${executed.workflow} sha256=${executed.sha256?.slice(0, 8) ?? '?'} harnessDirty=${executed.gitDirty.length}`
383
+ : 'executed: unknown (trace unavailable)';
384
+ const failed = report.failedNode;
385
+ const line3 =
386
+ failed !== null
387
+ ? `failed node: ${failed.id} (${failed.status})${
388
+ failed.stderrTail ? ` — ${failed.stderrTail.split('\n').slice(-1)[0]?.slice(0, 140) ?? ''}` : ''
389
+ }`
390
+ : 'failed node: not identified from trace';
391
+ const nested = report.nestedRuns;
392
+ const line4 =
393
+ nested.length > 0
394
+ ? nested
395
+ .map((run) => {
396
+ const bad = run.receipts.filter((receipt) => !receipt.ok).length;
397
+ return `${run.workflow ?? '?'}:${run.terminalState ?? run.status ?? '?'} receipts ${run.receipts.length - bad}/${run.receipts.length} ok (${run.runId.slice(0, 8)})`;
398
+ })
399
+ .join('; ')
400
+ : 'nested: none';
401
+ return [line1, line2, line3, line4, `suggestion: ${report.suggestions[0] ?? '?'}`];
402
+ }
403
+
404
+ /** Locate the schedule receipt for a run id across the voice2 works root (stamps newest first). */
405
+ export function findReceiptByRunId(repo: string, runId: string): string | null {
406
+ const root = join(repo, WORKS_FLOW_DIR);
407
+ let stamps: string[] = [];
408
+ try {
409
+ stamps = readdirSync(root).filter((name) => /^\d{8}$/.test(name));
410
+ } catch {
411
+ return null;
412
+ }
413
+ for (const stamp of stamps.reverse()) {
414
+ const receiptPath = join(root, stamp, 'schedule-receipt.json');
415
+ const receipt = readTriageJson(receiptPath);
416
+ if (receipt !== null && receipt.runId === runId) return receiptPath;
417
+ }
418
+ return null;
419
+ }
420
+
421
+ /** Newest failed daily-run receipt across the voice2 works root, for `daily-triage --latest`. */
422
+ export function latestFailedRun(repo: string): { runId: string; receiptPath: string } | null {
423
+ const root = join(repo, WORKS_FLOW_DIR);
424
+ let stamps: string[] = [];
425
+ try {
426
+ stamps = readdirSync(root).filter((name) => /^\d{8}$/.test(name));
427
+ } catch {
428
+ return null;
429
+ }
430
+ const candidates: { runId: string; receiptPath: string; completedAt: number }[] = [];
431
+ for (const stamp of stamps.reverse()) {
432
+ const receiptPath = join(root, stamp, 'schedule-receipt.json');
433
+ const receipt = readTriageJson(receiptPath);
434
+ if (receipt === null || typeof receipt.status !== 'string') continue;
435
+ if (!FAILED_RECEIPT_STATUSES.has(receipt.status)) continue;
436
+ const completedAt =
437
+ typeof receipt.completedAt === 'string' ? Date.parse(receipt.completedAt) : statSync(receiptPath).mtimeMs;
438
+ candidates.push({
439
+ runId: typeof receipt.runId === 'string' ? receipt.runId : `${stamp}-unknown`,
440
+ receiptPath,
441
+ completedAt: Number.isNaN(completedAt) ? 0 : completedAt,
442
+ });
443
+ }
444
+ if (candidates.length === 0) return null;
445
+ candidates.sort((a, b) => b.completedAt - a.completedAt);
446
+ return candidates[0] ?? null;
447
+ }
448
+
449
+ export const TRIAGE_FAILED_RECEIPT_STATUSES = FAILED_RECEIPT_STATUSES;
450
+ export const TRIAGE_GOOD_RECEIPT_STATUSES = GOOD_RECEIPT_STATUSES;
451
+ export const TRIAGE_ACTIVE_RECEIPT_STATUSES = ACTIVE_RECEIPT_STATUSES;
@@ -0,0 +1,74 @@
1
+ /**
2
+ * daily-triage — print the five-line triage summary for a failed daily run (0347 F3, 2026-11-10).
3
+ *
4
+ * bun plugins/kk/scripts/daily-triage.ts --run <runId> [--repo <dir>] [--json]
5
+ * bun plugins/kk/scripts/daily-triage.ts --latest [--repo <dir>] [--json]
6
+ *
7
+ * Exit codes: 0 = triage produced (even for a rerun-able outcome — this is a read-only tool);
8
+ * 1 = usage error; 2 = run receipt not found / not failed. The scheduler embeds the same summary
9
+ * in the failure receipt, so this CLI is for ad-hoc inspection and for reproducing the embedded
10
+ * triage when the receipt was written by an older supervisor build.
11
+ */
12
+ import { join } from 'node:path';
13
+ import { collectTriage, latestFailedRun, summarizeTriage } from './daily-triage-core';
14
+
15
+ interface CliValues {
16
+ run?: string;
17
+ latest?: boolean;
18
+ repo?: string;
19
+ json?: boolean;
20
+ }
21
+
22
+ function fail(code: number, message: string): never {
23
+ console.error(`daily-triage: ${message}`);
24
+ process.exit(code);
25
+ }
26
+
27
+ export function main(args: string[]): void {
28
+ const values: CliValues = {};
29
+ for (let i = 0; i < args.length; i++) {
30
+ const arg = args[i];
31
+ if (arg === '--run') values.run = args[++i];
32
+ else if (arg === '--latest') values.latest = true;
33
+ else if (arg === '--repo') values.repo = args[++i];
34
+ else if (arg === '--json') values.json = true;
35
+ else if (arg === '--help' || arg === '-h') {
36
+ console.log('usage: daily-triage.ts (--run <runId> | --latest) [--repo <dir>] [--json]');
37
+ process.exit(0);
38
+ } else fail(1, `unknown argument: ${arg}`);
39
+ }
40
+ if (values.run !== undefined && values.latest) fail(1, '--run and --latest are mutually exclusive');
41
+ if (values.run === undefined && !values.latest) fail(1, 'pass --run <runId> or --latest');
42
+
43
+ const repo = values.repo ?? process.cwd();
44
+ let runId = values.run ?? '';
45
+ let receiptPath: string | undefined;
46
+ if (values.latest) {
47
+ const found = latestFailedRun(repo);
48
+ if (found === null) {
49
+ console.log('daily-triage: no failed daily run found in .works/kk-daily-ai-voice2 — nothing to triage');
50
+ process.exit(0);
51
+ }
52
+ runId = found.runId;
53
+ receiptPath = found.receiptPath;
54
+ }
55
+ const report = collectTriage(repo, runId, { receiptPath });
56
+ if (report.receipt === null && !values.latest) {
57
+ console.log(
58
+ `daily-triage: no schedule receipt found for ${runId} (overwritten by a later attempt?) — triaging from trace only`,
59
+ );
60
+ }
61
+ if (values.json) {
62
+ console.log(JSON.stringify(report, null, 2));
63
+ return;
64
+ }
65
+ for (const line of summarizeTriage(report)) console.log(line);
66
+ const nestedRunId = report.nestedRuns[0]?.runId;
67
+ console.log(
68
+ `details: bun plugins/kk/scripts/daily-triage.ts --run ${runId} --repo ${join(repo)} --json${nestedRunId ? `; nested: spur workflow trace ${nestedRunId} --json` : ''}`,
69
+ );
70
+ }
71
+
72
+ if (import.meta.main) {
73
+ main(process.argv.slice(2));
74
+ }
@@ -56,15 +56,17 @@ import {
56
56
  } from 'node:fs';
57
57
  import { homedir } from 'node:os';
58
58
  import { basename, dirname, join, resolve } from 'node:path';
59
+ import { compositeCover } from './cover-compositor';
59
60
 
60
61
  export const SCRIPTS_DIR = import.meta.dir;
61
62
  export const VALIDATE_SIDECAR = 'validate-voicescript.ts';
62
63
  const WRAP_SIDECAR = 'wrap-voicescript-doc.ts';
63
64
  const RENDER_SIDECAR = 'render-md.ts';
64
- // F613: the zh style contract the script-write prompt reads (snapshot stage) and dailynews-gen
65
- // consumes (DAILYNEWS_STYLE_FILE); no workflow var carries an override, so the chain is
66
- // $KK_WORKFLOWS_DIR -> package copy -> $HOME.
67
- export const STYLE_SIDECAR = 'daily-voice-style.zh.md';
65
+ // ADR-045: daily-news editorial policy lives in the kk:news-editorial skill, shipped beside this
66
+ // scripts dir in the same package. Its style contract is what the `write` mode reads (via the run
67
+ // snapshot) and dailynews-gen validates against (DAILYNEWS_STYLE_FILE).
68
+ export const EDITORIAL_SKILL_DIR = join(SCRIPTS_DIR, '..', 'skills', 'news-editorial');
69
+ export const STYLE_CONTRACT = join(EDITORIAL_SKILL_DIR, 'references', 'style-contract.zh.md');
68
70
  const REVISE_COUNT = '.revise-count';
69
71
  /** Bounded draft-remediation counter for the daily safety loop (20261005). */
70
72
  export const SAFETY_REVISE_COUNT = '.safety-revise-count';
@@ -84,8 +86,8 @@ export const DEDUP_TITLE_THRESHOLD = 0.4;
84
86
  // F614: the daily cover renders through the shipped daily-news presets; the brief's subject is
85
87
  // the only per-run var. The format/style pins and the subject cap are part of the style
86
88
  // contract — changing the look means editing the preset files, not this stage.
87
- export const COVER_FORMAT = 'daily-news-cover';
88
- export const COVER_STYLE = 'daily-news';
89
+ export const COVER_FORMAT = 'daily-news-podcast-cover';
90
+ export const COVER_STYLE = 'quasi-news-podcast';
89
91
  export const COVER_SUBJECT_CAP = 240;
90
92
  // E8: the XHS card series. Format and style are pinned exactly like the cover's; only the copy is
91
93
  // model-authored. `XHS_MAX_CARDS` mirrors the format preset's own series guidance.
@@ -1015,6 +1017,20 @@ export function coverBrief(briefPath: string): { reason: string | null; subject:
1015
1017
  return { reason: null, subject: trimmed };
1016
1018
  }
1017
1019
 
1020
+ /** The 0347 cover brief's Hook headline, or '' when the brief is absent, malformed, or headline-less. */
1021
+ function briefHeadline(briefPath: string): string {
1022
+ if (!existsSync(briefPath)) return '';
1023
+ let parsed: unknown;
1024
+ try {
1025
+ parsed = JSON.parse(readFileSync(briefPath, 'utf-8'));
1026
+ } catch {
1027
+ return '';
1028
+ }
1029
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return '';
1030
+ const headline = (parsed as Record<string, unknown>).headline;
1031
+ return typeof headline === 'string' ? headline.trim() : '';
1032
+ }
1033
+
1018
1034
  export function coverNormalizeBody(workDir: string, runDate: string): void {
1019
1035
  // F614 R5: the artifact name follows the format preset (`<stem>-<format>-NN.<ext>`,
1020
1036
  // paths.ts), so normalize reads the path the plugin itself recorded in the manifest instead
@@ -1055,6 +1071,20 @@ export function coverNormalizeBody(workDir: string, runDate: string): void {
1055
1071
  // `rm -f` is silent when the file is already gone (a renamed source lands here too).
1056
1072
  }
1057
1073
  }
1074
+ // 0348: deterministic typography + branding overlay. The 0347 editorial brief carries a
1075
+ // Chinese Hook headline; when present, composite it (and the podcast emblem) onto the
1076
+ // normalized cover. Missing/invalid brief or empty headline keeps the raw background —
1077
+ // downstream stages read the same `${runDate}_07_cover_cover.png` either way.
1078
+ const briefPath = join(workDir, '23-cover', `${runDate}_07_cover-brief.json`);
1079
+ const headline = briefHeadline(briefPath);
1080
+ if (headline !== '') {
1081
+ try {
1082
+ compositeCover({ backgroundImagePath: out, headline, outputPath: out });
1083
+ } catch (error) {
1084
+ failWith(1, `cover composite: ${(error as Error).message}`);
1085
+ }
1086
+ console.error(`cover composited: headline=${headline.replaceAll('\n', ' ')}`);
1087
+ }
1058
1088
  console.error(`cover normalized: ${runDate}_07_cover_cover.png`);
1059
1089
  }
1060
1090
 
@@ -1877,6 +1907,21 @@ if (import.meta.main)
1877
1907
  dailyScriptStyle(rest);
1878
1908
  break;
1879
1909
  }
1910
+ case 'daily-script-check': {
1911
+ const { dailyScriptCheck } = await loadDailyStages();
1912
+ dailyScriptCheck(rest);
1913
+ break;
1914
+ }
1915
+ case 'daily-curate-check': {
1916
+ const { dailyCurateCheck } = await loadDailyStages();
1917
+ dailyCurateCheck(rest);
1918
+ break;
1919
+ }
1920
+ case 'daily-editorial-render': {
1921
+ const { dailyEditorialRender } = await loadDailyStages();
1922
+ dailyEditorialRender(rest);
1923
+ break;
1924
+ }
1880
1925
  case 'daily-script': {
1881
1926
  const { dailyScript } = await loadDailyStages();
1882
1927
  dailyScript(rest);
@@ -21,7 +21,7 @@ LLM-as-judge is **not** a knowledge-kit plugin kind (ADR-007 amdt 2026-08-07). I
21
21
 
22
22
  - A spur workflow needs a quality gate between `generate` and `publish`.
23
23
  - A user asks to "judge", "evaluate", "quality-check", or "gate" generated content.
24
- - A workflow or skill names a rubric (`tech-accuracy` / `brand-tone` / `compliance` / `general`).
24
+ - A workflow or skill names a rubric (`tech-accuracy` / `brand-tone` / `compliance` / `news-balance` / `general`).
25
25
 
26
26
  ## Verdict output contract
27
27
 
@@ -99,7 +99,7 @@ and `escalate` flag; treat `LOW` as a signal to demand human review before publi
99
99
  1. **Read the Content** from the path given in the evaluation request (the `content.json` written
100
100
  by the preceding `kk executor run <generator>` step).
101
101
  2. **Select the rubric** — named in the request (`tech-accuracy`, `brand-tone`,
102
- `compliance`, `general`). Default: `general`.
102
+ `compliance`, `news-balance`, `general`). Default: `general`.
103
103
  3. **Evaluate each criterion** in the rubric. For each, produce a `pass` / `fail` / `warn` status
104
104
  backed by a specific, quotable evidence reference (quote, section, claim).
105
105
  4. **Score** — weighted aggregate per the rubric's scoring rules. `score` is 0.0–1.0.
@@ -127,7 +127,7 @@ and `escalate` flag; treat `LOW` as a signal to demand human review before publi
127
127
 
128
128
  ## Rubrics
129
129
 
130
- Four built-in rubrics. Full definitions, weights, and thresholds live in
130
+ Five built-in rubrics. Full definitions, weights, and thresholds live in
131
131
  `references/rubrics.md`. The skill body intentionally stays lean — load the reference when
132
132
  evaluating.
133
133
 
@@ -137,6 +137,7 @@ evaluating.
137
137
  | `tech-accuracy` | Technical content | factual correctness vs. sources, no fabricated citations, code correctness |
138
138
  | `brand-tone` | Published voice | tone consistency, banned-phrase compliance, audience fit |
139
139
  | `compliance` | Sensitive content | no prohibited claims, disclosure presence, jurisdictional rules |
140
+ | `news-balance` | Daily news script plan | news-first, commentary-share, no-restatement |
140
141
 
141
142
  ## Prompt template
142
143
 
@@ -147,7 +148,7 @@ Use this template when the skill is invoked by an `agent.run` step. The workflow
147
148
  You are an LLM-as-judge evaluating generated content for the knowledge-kit pipeline.
148
149
 
149
150
  Content to evaluate: {{content_path}}
150
- Rubric: {{rubric}} # general | tech-accuracy | brand-tone | compliance
151
+ Rubric: {{rubric}} # general | tech-accuracy | brand-tone | compliance | news-balance
151
152
  Output verdict to: {{verdict_path}}
152
153
 
153
154
  Load the rubric definition from plugins/kk/skills/content-judge/references/rubrics.md (section: {{rubric}}).