@gobing-ai/knowledge-kit 0.1.15 → 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 (103) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/index.js +1603 -1
  3. package/package.json +1 -1
  4. package/plugins/generations/content-gen/dist/index.js +58 -52
  5. package/plugins/generations/content-gen/src/storm.ts +94 -61
  6. package/plugins/generations/core-facts-gen/dist/index.js +1 -1
  7. package/plugins/generations/daily-article-gen/dist/index.js +1 -1
  8. package/plugins/generations/dailynews-gen/dist/index.js +1 -1
  9. package/plugins/generations/episode-plan-gen/dist/index.js +1 -1
  10. package/plugins/generations/gemini-tts/dist/index.js +1 -1
  11. package/plugins/generations/image-gen/README.md +31 -10
  12. package/plugins/generations/image-gen/assets/sample/cover__quasi-news-podcast.jpg +0 -0
  13. package/plugins/generations/image-gen/assets/sample/daily-news-cover__quasi-news-podcast.jpg +0 -0
  14. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__clean-webapp-ui.jpg +0 -0
  15. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__cute.jpg +0 -0
  16. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__daily-news.jpg +0 -0
  17. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__editorial.jpg +0 -0
  18. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__fresh.jpg +0 -0
  19. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__minimalist.jpg +0 -0
  20. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__photorealistic.jpg +0 -0
  21. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__quasi-news-podcast.jpg +0 -0
  22. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__sketch.jpg +0 -0
  23. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__technical-diagram.jpg +0 -0
  24. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__vibrant.jpg +0 -0
  25. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__warm.jpg +0 -0
  26. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__xhs-knowledge.jpg +0 -0
  27. package/plugins/generations/image-gen/assets/sample/free__quasi-news-podcast.jpg +0 -0
  28. package/plugins/generations/image-gen/assets/sample/illustration__quasi-news-podcast.jpg +0 -0
  29. package/plugins/generations/image-gen/assets/sample/xhs-card__quasi-news-podcast.jpg +0 -0
  30. package/plugins/generations/image-gen/dist/index.js +1 -1
  31. package/plugins/generations/image-gen/presets/formats/daily-news-podcast-cover.yaml +18 -0
  32. package/plugins/generations/image-gen/presets/styles/quasi-news-podcast.yaml +9 -0
  33. package/plugins/generations/news-report-gen/dist/index.js +1 -1
  34. package/plugins/generations/voice-gen/dist/index.js +1 -1
  35. package/plugins/generations/voxcpm-tts/dist/index.js +1 -1
  36. package/plugins/ingestions/aihot-ingest/dist/index.js +1 -1
  37. package/plugins/ingestions/horizon-ingest/dist/index.js +1 -1
  38. package/plugins/ingestions/last30days-ingest/dist/index.js +1 -1
  39. package/plugins/ingestions/web-search/dist/index.js +1 -1
  40. package/plugins/kk/plugin.json +1 -1
  41. package/plugins/kk/publish-presets/daily-ai-voice-migration.json +12 -3
  42. package/plugins/kk/publish-presets/daily-ai-voice.json +11 -3
  43. package/plugins/kk/scripts/cover-compositor.ts +152 -0
  44. package/plugins/kk/scripts/daily-cover-mock.ts +164 -0
  45. package/plugins/kk/scripts/daily-scheduled-run.ts +188 -3
  46. package/plugins/kk/scripts/daily-stages.ts +134 -26
  47. package/plugins/kk/scripts/daily-triage-core.ts +451 -0
  48. package/plugins/kk/scripts/daily-triage.ts +74 -0
  49. package/plugins/kk/scripts/kk-workflow-stages.ts +31 -2
  50. package/plugins/kk/skills/content-safety/references/platforms/wechatmp.md +16 -10
  51. package/plugins/kk/skills/news-editorial/SKILL.md +3 -3
  52. package/plugins/kk/skills/news-editorial/references/style-contract.zh.md +2 -1
  53. package/plugins/kk/skills/publish/SKILL.md +1 -1
  54. package/plugins/kk/skills/wiki-authoring/SKILL.md +53 -0
  55. package/plugins/kk/skills/wiki-authoring/references/page-shapes.md +44 -0
  56. package/plugins/kk/workflows/kk-daily-ai-voice3.yaml +3 -3
  57. package/plugins/kk/workflows/kk-daily-safety.yaml +32 -7
  58. package/plugins/publishings/bilibili-pub/dist/index.js +1 -1
  59. package/plugins/publishings/cnblogs-pub/dist/index.js +1 -1
  60. package/plugins/publishings/csdn-pub/dist/index.js +1 -1
  61. package/plugins/publishings/csdn-pub/dist/profile-check.js +1 -1
  62. package/plugins/publishings/emdash-pub/dist/index.js +1 -1
  63. package/plugins/publishings/infoq-pub/dist/index.js +1 -1
  64. package/plugins/publishings/infoq-pub/dist/profile-check.js +1 -1
  65. package/plugins/publishings/jike-pub/dist/index.js +1 -1
  66. package/plugins/publishings/jike-pub/dist/profile-check.js +1 -1
  67. package/plugins/publishings/juejin-pub/dist/index.js +1 -1
  68. package/plugins/publishings/juejin-pub/dist/profile-check.js +1 -1
  69. package/plugins/publishings/linkedin-pub/dist/index.js +1 -1
  70. package/plugins/publishings/linkedin-pub/dist/profile-check.js +1 -1
  71. package/plugins/publishings/medium-pub/dist/index.js +1 -1
  72. package/plugins/publishings/podcast-pub/dist/index.js +1 -1
  73. package/plugins/publishings/qiita-pub/dist/index.js +1 -1
  74. package/plugins/publishings/shipinhao-pub/dist/index.js +222 -50
  75. package/plugins/publishings/shipinhao-pub/dist/profile-check.js +48 -1
  76. package/plugins/publishings/shipinhao-pub/plugin.json +2 -2
  77. package/plugins/publishings/shipinhao-pub/src/flow.ts +335 -79
  78. package/plugins/publishings/shipinhao-pub/src/index.ts +16 -8
  79. package/plugins/publishings/shipinhao-pub/src/profile-check.ts +1 -1
  80. package/plugins/publishings/shipinhao-pub/src/selectors.ts +103 -5
  81. package/plugins/publishings/sspai-pub/dist/index.js +1 -1
  82. package/plugins/publishings/substack-pub/dist/index.js +1 -1
  83. package/plugins/publishings/substack-pub/dist/profile-check.js +1 -1
  84. package/plugins/publishings/surfdash-pub/dist/index.js +235 -12
  85. package/plugins/publishings/surfdash-pub/src/index.ts +127 -6
  86. package/plugins/publishings/surfdash-pub/src/topic-claims.ts +189 -0
  87. package/plugins/publishings/threads-pub/dist/index.js +1 -1
  88. package/plugins/publishings/wechatmp-pub/dist/index.js +10 -7
  89. package/plugins/publishings/wechatmp-pub/dist/profile-check.js +1 -1
  90. package/plugins/publishings/wechatmp-pub/src/enrich.ts +10 -3
  91. package/plugins/publishings/wechatmp-pub/src/flow.ts +3 -4
  92. package/plugins/publishings/wechatmp-pub/src/page.ts +14 -0
  93. package/plugins/publishings/weibo-pub/dist/index.js +1 -1
  94. package/plugins/publishings/weibo-pub/dist/profile-check.js +1 -1
  95. package/plugins/publishings/x-pub/dist/index.js +1 -1
  96. package/plugins/publishings/x-pub/dist/profile-check.js +1 -1
  97. package/plugins/publishings/xhs-pub/dist/index.js +557 -31
  98. package/plugins/publishings/xhs-pub/dist/profile-check.js +20 -1
  99. package/plugins/publishings/xhs-pub/src/errors.ts +45 -0
  100. package/plugins/publishings/xhs-pub/src/flow.ts +773 -45
  101. package/plugins/publishings/xhs-pub/src/page.ts +33 -0
  102. package/plugins/publishings/xiaoyuzhou-pub/dist/index.js +1 -1
  103. package/plugins/publishings/zenn-pub/dist/index.js +1 -1
@@ -9,7 +9,23 @@ import {
9
9
  uploadFile,
10
10
  } from '@gobing-ai/publish-harness/browser';
11
11
  import type { Page } from 'playwright';
12
- import { artifactPaths, type ModeInput, PUBLISH_URL, PUBLISHED_MARKER, TARGET, type XhsOperation } from './modes';
12
+ import {
13
+ AccountRiskControlError,
14
+ ContentTooLongError,
15
+ DraftVerifyError,
16
+ PublishError,
17
+ TitleTooLongError,
18
+ } from './errors';
19
+ import {
20
+ artifactPaths,
21
+ type ModeInput,
22
+ PUBLISH_URL,
23
+ PUBLISHED_MARKER,
24
+ TARGET,
25
+ XHS_NOTE_BODY_MAX,
26
+ XHS_NOTE_TITLE_MAX,
27
+ type XhsOperation,
28
+ } from './modes';
13
29
  import { clickCreatorTab, findAttachedSelector, findSelector, POLL_MS, waitUntil, type XhsPage } from './page';
14
30
 
15
31
  /**
@@ -34,14 +50,14 @@ const NOTE_BODY = [
34
50
  ];
35
51
  // Uploaded previews carry XHS's own class spelling (`preivew`, not `preview`).
36
52
  const NOTE_THUMBNAIL = ['img.preivew-image', '.img-preview img'];
37
- // The image input is distinguishable from the video input by its accept list (`.jpg` first).
38
- const IMAGE_FILE_INPUT = [
39
- 'input[type="file"][accept*=".jpg"]',
40
- 'input[type="file"].upload-input',
41
- 'input[type="file"]',
42
- ];
43
53
  const VIDEO_FILE_INPUT = ['input[type="file"][accept*=".mp4"]', 'input[type="file"].upload-input'];
44
54
  const VIDEO_EDITOR = ['div.tiptap.ProseMirror', 'div.tiptap[contenteditable="true"]', '.ProseMirror'];
55
+ /** The image editor mounts its upload wiring lazily; measured-settle from probe-thumb-src.ts. */
56
+ const IMAGE_MODE_SETTLE_MS = 1500;
57
+ /** The console's uploader chunk mounts while the SPA idles after load (probe-thumb-src.ts slept
58
+ * 9s before touching anything). Clicking earlier leaves the editor preview-capable but mute. */
59
+ const CONSOLE_SETTLE_MS = 9000;
60
+ const CONSOLE_SETTLE_QUIET_MS = 2000;
45
61
 
46
62
  // 写长文: the landing offers 新的创作 (author in place) and 导入链接 (excluded — it is fed from a
47
63
  // 公众号 source, which would put another platform's publishing and censorship in the critical
@@ -67,6 +83,14 @@ const PODCAST_MODAL_ADVANCE = ['去发布'];
67
83
  const PODCAST_COVER_ZONE = '.d-modal div:has-text("设置封面")';
68
84
  const PODCAST_UPLOAD_ACK = '上传成功';
69
85
 
86
+ // Task 0350 R4: the podcast editor's fields — measured in the 2026-11-11 discovery (智能标题 chip,
87
+ // a 0/1000 body counter, an 加入播客合集 entry in the bottom bar's closed shadow), none of them
88
+ // selector-measured. These probe chains name what they try; every apply is followed by a
89
+ // counter/verify read that fails loud when the field did not take.
90
+ const PODCAST_TITLE_SELECTORS = ['input.d-text', 'input[placeholder*="标题"]', 'textarea[placeholder*="标题"]'];
91
+ const PODCAST_COLLECTION_SELECTORS = ['button:has-text("加入播客合集")', 'text=加入播客合集', 'text=合集'];
92
+ const PODCAST_COLLECTION_DEFAULT = '咸话咸说之每日AI乱炖';
93
+
70
94
  /**
71
95
  * The `暂存离开` labels, newest first: XHS renamed the control, and the older labels stay as
72
96
  * fallbacks. The control is a `BUTTON.ce-btn.white` inside the publish bar.
@@ -196,6 +220,199 @@ interface ActionClick {
196
220
  click: string;
197
221
  }
198
222
 
223
+ /**
224
+ * Invoke the draft-save method the action bar exposes on its `xhs-publish-btn` host. The bar
225
+ * renders inside a CLOSED shadow root, so synthetic coordinate clicks from an automated context
226
+ * are no-ops (OpenCLI#1606); the host method is the reliable trigger. Returns the method name,
227
+ * or null when no visible host carries a save method (the click fallback then runs).
228
+ */
229
+ async function invokeHostSave(page: XhsPage): Promise<string | null> {
230
+ try {
231
+ const verdict = await page.evaluate(`(() => {
232
+ const hosts = Array.from(document.querySelectorAll('xhs-publish-btn')).filter((el) => {
233
+ const r = el.getBoundingClientRect();
234
+ return r.width > 0 && r.height > 0;
235
+ });
236
+ for (const el of hosts) {
237
+ for (const name of ['_onSave', '_onSaveDraft', '_onDraft']) {
238
+ const fn = el[name];
239
+ if (typeof fn === 'function') { fn.call(el); return 'kk-host-save:' + name; }
240
+ }
241
+ }
242
+ return 'kk-host-save-none';
243
+ })()`);
244
+ const called = typeof verdict === 'string' ? verdict : '';
245
+ return called.startsWith('kk-host-save:') ? called.slice('kk-host-save:'.length) : null;
246
+ } catch {
247
+ return null;
248
+ }
249
+ }
250
+
251
+ /**
252
+ * Layered server-response capture (task 0350 R1, vendor-proven from
253
+ * `vendors/xiaohongshu-skills/scripts/xhs/publish.py`): the save/publish response is the only
254
+ * truth about whether a note persisted — the console toast has lied while the API returned
255
+ * `HTTPBizError` (2026-11-09/10 runs). Four layers race for the first matching payload — XHR
256
+ * `loadend`, wrapped `fetch`, console output, and a DOM toast observer — and the first capture
257
+ * wins. Signatures are content-based, not URL-based: `HTTPBizError`, a −913x code, `note_id`,
258
+ * or a short toast naming 禁止发笔记 / 违反 / 违规 / 审核未通过 / 账号异常 / 无法发布.
259
+ * Arming is idempotent; a page that refused injection degrades to the legacy UI signals. The
260
+ * sentinel markers keep a mocked evaluate from ever reading as a real capture.
261
+ */
262
+ export const CAPTURE_INJECT_EXPR = `/* kk-capture-inject */ (() => {
263
+ const w = window;
264
+ if (w.__kkXhsArmed) return 'kk-capture-armed';
265
+ w.__kkXhsArmed = true;
266
+ w.__kkXhsOutcome = null;
267
+ const signatures = [
268
+ /HTTPBizError/,
269
+ /"code"\\s*:\\s*-913\\d/,
270
+ /禁止发笔记/,
271
+ /note_id/,
272
+ /违反|违规|审核未通过|账号异常|无法发布/,
273
+ ];
274
+ const matches = (text) => signatures.some((re) => re.test(text));
275
+ const record = (source, text) => {
276
+ if (w.__kkXhsOutcome) return;
277
+ const asString = String(text || '');
278
+ if (!asString || !matches(asString)) return;
279
+ w.__kkXhsOutcome = { source: source, text: asString.slice(0, 800) };
280
+ };
281
+ const proto = XMLHttpRequest.prototype;
282
+ if (!proto.__kkPatched) {
283
+ proto.__kkPatched = true;
284
+ const open = proto.open;
285
+ const send = proto.send;
286
+ proto.open = function (method, url) { this.__kkUrl = url; return open.apply(this, arguments); };
287
+ proto.send = function () {
288
+ this.addEventListener('loadend', () => {
289
+ try { record('xhr', (this.__kkUrl || '') + ' ' + this.responseText); } catch (e) {}
290
+ });
291
+ return send.apply(this, arguments);
292
+ };
293
+ }
294
+ if (typeof w.fetch === 'function' && !w.fetch.__kkPatched) {
295
+ const original = w.fetch;
296
+ w.fetch = function () {
297
+ return original.apply(this, arguments).then((response) => {
298
+ try {
299
+ response.clone().text().then((text) => record('fetch', (response.url || '') + ' ' + text)).catch(() => {});
300
+ } catch (e) {}
301
+ return response;
302
+ });
303
+ };
304
+ w.fetch.__kkPatched = true;
305
+ }
306
+ if (!console.__kkPatched) {
307
+ console.__kkPatched = true;
308
+ for (const key of ['error', 'warn', 'log']) {
309
+ const original = console[key].bind(console);
310
+ console[key] = function () {
311
+ try { record('console', Array.prototype.map.call(arguments, String).join(' ')); } catch (e) {}
312
+ original.apply(console, arguments);
313
+ };
314
+ }
315
+ }
316
+ if (typeof MutationObserver === 'function' && document.body && !w.__kkXhsToastObs) {
317
+ const toastRisk = /违反|违规|禁止发笔记|审核未通过|账号异常|无法发布/;
318
+ const obs = new MutationObserver((muts) => {
319
+ if (w.__kkXhsOutcome) return;
320
+ for (const m of muts) {
321
+ for (const n of m.addedNodes || []) {
322
+ if (!n || n.nodeType !== 1) continue;
323
+ const txt = String(n.textContent || '').trim();
324
+ if (txt.length === 0 || txt.length > 300) continue;
325
+ if (!toastRisk.test(txt)) continue;
326
+ record('toast', txt);
327
+ }
328
+ }
329
+ });
330
+ obs.observe(document.body, { childList: true, subtree: true });
331
+ w.__kkXhsToastObs = true;
332
+ }
333
+ return 'kk-capture-armed';
334
+ })()`;
335
+ const CAPTURE_READ_EXPR = `/* kk-capture-read */ (() => {
336
+ const captured = window.__kkXhsOutcome;
337
+ return captured ? JSON.stringify(captured) : 'kk-capture-none';
338
+ })()`;
339
+
340
+ interface OutcomeCapture {
341
+ source: string;
342
+ text: string;
343
+ }
344
+
345
+ async function armOutcomeCapture(page: XhsPage): Promise<void> {
346
+ try {
347
+ await page.evaluate(CAPTURE_INJECT_EXPR);
348
+ } catch {
349
+ // No injection, no capture: the legacy UI signals remain the only outcome evidence.
350
+ }
351
+ }
352
+
353
+ async function readOutcomeCapture(page: XhsPage): Promise<OutcomeCapture | null> {
354
+ try {
355
+ const read = await page.evaluate(CAPTURE_READ_EXPR);
356
+ if (typeof read !== 'string' || !read.startsWith('{')) return null;
357
+ const parsed = JSON.parse(read) as Partial<OutcomeCapture>;
358
+ return typeof parsed.source === 'string' && typeof parsed.text === 'string'
359
+ ? { source: parsed.source, text: parsed.text }
360
+ : null;
361
+ } catch {
362
+ return null;
363
+ }
364
+ }
365
+
366
+ const RISK_SIGNATURE = /禁止发笔记|违反|违规|审核未通过|账号异常|无法发布/;
367
+ const CODE_SIGNATURE = /"code"\s*:\s*(-?\d+)/;
368
+ const NOTE_ID_SIGNATURE = /"note_id"\s*:\s*"([^"]+)"/;
369
+
370
+ function classifyOutcome(text: string): {
371
+ verdict: 'risk' | 'biz' | 'ok';
372
+ code: string | null;
373
+ noteId: string | null;
374
+ } {
375
+ const code = CODE_SIGNATURE.exec(text)?.[1] ?? null;
376
+ const noteId = NOTE_ID_SIGNATURE.exec(text)?.[1] ?? null;
377
+ if ((code !== null && /^-913\d$/.test(code)) || RISK_SIGNATURE.test(text)) {
378
+ return { verdict: 'risk', code, noteId };
379
+ }
380
+ if (noteId !== null && (code === null || code === '0')) return { verdict: 'ok', code, noteId };
381
+ return { verdict: 'biz', code, noteId };
382
+ }
383
+
384
+ /**
385
+ * A captured refusal outranks every UI signal (vendor first-wins): risk control is a typed
386
+ * no-retry abort, a platform biz error a typed failure. Ok verdicts ride the Result metadata.
387
+ */
388
+ function assertCapturedOutcome(capture: OutcomeCapture | null): void {
389
+ if (capture === null) return;
390
+ const { verdict, code } = classifyOutcome(capture.text);
391
+ if (verdict === 'risk') {
392
+ throw new AccountRiskControlError(
393
+ `AccountRiskControlError: the ${capture.source} response matched risk-control signatures (code ${code ?? 'unknown'}, matched: ${RISK_SIGNATURE.exec(capture.text)?.[0] ?? '-913x code'}) — the account is restricted from posting on ${TARGET}; not retryable`,
394
+ );
395
+ }
396
+ if (verdict === 'biz') {
397
+ throw new PublishError(
398
+ `PublishError: the ${capture.source} response reported a platform error (code ${code ?? 'unknown'}): ${capture.text.slice(0, 200)}`,
399
+ );
400
+ }
401
+ }
402
+
403
+ function captureMetadata(capture: OutcomeCapture | null): Record<string, unknown> {
404
+ if (capture === null) return {};
405
+ const { verdict, code, noteId } = classifyOutcome(capture.text);
406
+ return {
407
+ serverCapture: {
408
+ source: capture.source,
409
+ verdict,
410
+ ...(code !== null ? { code } : {}),
411
+ ...(noteId !== null ? { noteId } : {}),
412
+ },
413
+ };
414
+ }
415
+
199
416
  /** Click an action-bar control of this mode, on the path its evidence says that bar lives on. */
200
417
  async function clickActionControl(
201
418
  operation: XhsOperation,
@@ -311,52 +528,254 @@ async function applyNoteTitle(deps: ModeRunDeps): Promise<void> {
311
528
  .locator(selector)
312
529
  .first()
313
530
  .fill(deps.content.title ?? '');
531
+ // Task 0350 R2: counter-verified in the editor before any save.
532
+ await assertPlatformCounter(deps.page, TITLE_COUNTER_EXPR, XHS_NOTE_TITLE_MAX, 'title');
314
533
  }
315
534
 
316
- async function typeNoteBody(deps: ModeRunDeps, selectors: readonly string[], what: string): Promise<void> {
535
+ async function typeNoteBody(
536
+ deps: ModeRunDeps,
537
+ selectors: readonly string[],
538
+ what: string,
539
+ text?: string,
540
+ ): Promise<void> {
317
541
  const selector = await findSelector(deps.page, selectors, what, deps.stepTimeoutMs);
318
542
  const body = deps.page.locator(selector).first();
319
- const text = deps.content.body ?? '';
543
+ const value = text ?? deps.content.body ?? '';
320
544
  // Type rather than fill: TipTap ignores a synthetic value set, so a filled body leaves the
321
545
  // note unsaved and the draft never becomes observable.
322
546
  if (typeof body.type === 'function') {
323
547
  await body.click();
324
- await body.type(text, { delay: 5 });
325
- return;
548
+ await body.type(value, { delay: 5 });
549
+ } else {
550
+ await body.fill(value);
551
+ }
552
+ // Task 0350 R2: the platform counter is ground truth once the text is in the editor — the
553
+ // client-side cap below cannot see xhs's 2-half-width-chars-per-unit counting.
554
+ await assertPlatformCounter(deps.page, BODY_COUNTER_EXPR, XHS_NOTE_BODY_MAX, 'body');
555
+ }
556
+
557
+ /**
558
+ * Platform-counter probes (task 0350 R2). Measured: the note title counter is
559
+ * `div.title-container div.max_suffix` reading `N/20`. The body counter is observed as `0/1000`
560
+ * but not selector-measured — the read scans the edit container for a leaf `N/M` element and
561
+ * `kk-counter-none` means unreadable (the client-side caps in modes.ts stay the only gate).
562
+ * The title container is excluded: its `N/20` leaf would otherwise satisfy a missing body counter.
563
+ * xhs counts units, not JS chars: 2 half-width chars = 1 unit.
564
+ */
565
+ const TITLE_COUNTER_EXPR = `/* kk-counter-title */ (() => {
566
+ const el = document.querySelector('div.title-container div.max_suffix');
567
+ if (el && el.textContent && el.textContent.trim()) return el.textContent.trim();
568
+ for (const node of document.querySelectorAll('div.title-container *')) {
569
+ const t = (node.textContent || '').trim();
570
+ if (/^\\d+\\/\\d+$/.test(t) && node.children.length === 0) return t;
571
+ }
572
+ return 'kk-counter-none';
573
+ })()`;
574
+ export const BODY_COUNTER_EXPR = `/* kk-counter-body */ (() => {
575
+ const err = document.querySelector('div.edit-container div.length-error');
576
+ if (err && err.textContent && err.textContent.trim()) return err.textContent.trim();
577
+ for (const node of document.querySelectorAll('div.edit-container *')) {
578
+ const t = (node.textContent || '').trim();
579
+ if (/^\\d+\\/\\d+$/.test(t) && node.children.length === 0) return t;
580
+ }
581
+ return 'kk-counter-none';
582
+ })()`;
583
+
584
+ /** The counter's current value in units; null when it does not read `N/M`. */
585
+ function counterUnits(counter: string): number | null {
586
+ const current = Number.parseInt(counter.split('/')[0] ?? '', 10);
587
+ return Number.isFinite(current) ? current : null;
588
+ }
589
+
590
+ async function readPlatformCounter(page: XhsPage, expression: string): Promise<string | null> {
591
+ try {
592
+ const read = await page.evaluate(expression);
593
+ if (typeof read !== 'string' || read.includes('kk-counter-none')) return null;
594
+ return read.trim();
595
+ } catch {
596
+ return null;
326
597
  }
327
- await body.fill(text);
328
598
  }
329
599
 
330
- /** The uploaded-preview count must match the payload: it is how a wrong input is caught. */
331
- async function confirmThumbnails(deps: ModeRunDeps, expected: number): Promise<void> {
600
+ /**
601
+ * Reject before any save when the platform's own counter says the field is over its limit
602
+ * (task 0350 R2). Unreadable counters return silently — the client-side caps in modes.ts remain
603
+ * the only gate, and a real overflow then surfaces in verifyDraft instead.
604
+ */
605
+ async function assertPlatformCounter(
606
+ page: XhsPage,
607
+ expression: string,
608
+ max: number,
609
+ what: 'title' | 'body',
610
+ ): Promise<void> {
611
+ const counter = await readPlatformCounter(page, expression);
612
+ if (counter === null) return;
613
+ const units = counterUnits(counter);
614
+ if (units === null || units <= max) return;
615
+ const message = `the ${what} counter reads '${counter}' — ${units} units over the platform limit of ${max}; shorten the ${what} before saving (xhs counts units: 2 half-width chars = 1 unit)`;
616
+ throw what === 'title'
617
+ ? new TitleTooLongError(`TitleTooLongError: ${message}`)
618
+ : new ContentTooLongError(`ContentTooLongError: ${message}`);
619
+ }
620
+
621
+ /**
622
+ * A `blob:`/`data:` src is the instant local preview — it proves nothing about the server-side
623
+ * copy. The durable https src appears only after the upload round-trip; saving while any
624
+ * thumbnail still showed a blob src persisted a draft whose images were gone (2026-11-10 run).
625
+ * Note the durable src itself can be a geo-fenced CDN host (sns-creator-preview.xhscdn.com):
626
+ * from a non-CN egress the preview may render dead even when the ref is valid, so naturalWidth
627
+ * is NOT a reliable completion signal cross-region — the src scheme is.
628
+ *
629
+ * Drift (measured 2026-11-10 late, probe-thumb-src): the console stopped swapping preview srcs
630
+ * off `blob:` — uploads DO complete (permit + one 200 per file to ros-upload.xiaohongshu.com/spectrum)
631
+ * but the DOM keeps the local preview indefinitely. So network completion is an accepted
632
+ * durability signal alongside the src scheme.
633
+ */
634
+
635
+ /** Count successful image-upload round-trips (ros-upload/spectrum 200s) from page load on. */
636
+ function trackSpectrumUploads(page: XhsPage): { completions(): Promise<number>; seen(): number; dispose(): void } {
637
+ let count = 0;
638
+ // Capability-optional: a driver without response events (the test fake) degrades to 0 and the
639
+ // src scheme stays the only durability signal — the old strictness is preserved there.
640
+ let anySeen = 0;
641
+ const handler = (payload: unknown): void => {
642
+ anySeen += 1;
643
+ const response = payload as { status(): number; url(): string };
644
+ if (response.status() === 200 && /ros-upload\.xiaohongshu\.com\/spectrum\//.test(response.url())) {
645
+ count += 1;
646
+ }
647
+ };
648
+ page.onContextResponse?.(handler);
649
+ return {
650
+ completions: async () => count,
651
+ seen: () => anySeen,
652
+ dispose: () => page.offContextResponse?.(handler),
653
+ };
654
+ }
655
+
656
+ /** The uploaded-preview count must match the payload, and every src must be durable (uploaded). */
657
+ async function confirmThumbnails(
658
+ deps: ModeRunDeps,
659
+ expected: number,
660
+ uploads: { completions(): Promise<number>; seen(): number },
661
+ ): Promise<{ completions: number }> {
332
662
  const selector = await findSelector(deps.page, NOTE_THUMBNAIL, 'thumbnail wait', deps.stepTimeoutMs);
333
- const matches = await waitUntil(
334
- () =>
335
- deps.page
336
- .locator(selector)
337
- .count()
338
- .then((count) => count >= expected),
339
- deps.stepTimeoutMs,
340
- );
663
+ const allDurable = async (): Promise<boolean> => {
664
+ // Sentinel strings, not booleans: a generic mocked evaluate must never read as a real
665
+ // DOM verdict — a false positive would let the save run before uploads finish.
666
+ const verdict = await deps.page.evaluate(`(() => {
667
+ const imgs = Array.from(document.querySelectorAll("${selector}"));
668
+ if (imgs.length < ${expected}) return 'kk-thumb-pending';
669
+ return imgs.every((img) => /^https?:/.test(img.getAttribute("src") || ""))
670
+ ? 'kk-thumb-all-durable'
671
+ : 'kk-thumb-pending';
672
+ })()`);
673
+ if (verdict === 'kk-thumb-all-durable') return true;
674
+ // DOM-drift path (2026-11-10): previews stay on blob: after upload, so the network
675
+ // round-trips are the completion evidence instead.
676
+ return (await uploads.completions()) >= expected;
677
+ };
678
+ const matches = await waitUntil(allDurable, deps.stepTimeoutMs);
341
679
  const observed = await deps.page.locator(selector).count();
342
680
  if (!matches || observed !== expected) {
343
- throw new Error(`thumbnail count: expected ${expected}, observed ${observed}`);
681
+ const pending = await deps.page.evaluate(`/* kk-count-local-srcs */ (() => {
682
+ return Array.from(document.querySelectorAll("${selector}"))
683
+ .filter((img) => !/^https?:/.test(img.getAttribute("src") || "")).length;
684
+ })()`);
685
+ throw new Error(
686
+ `thumbnail count: expected ${expected} durable previews, observed ${observed} previews with ${String(pending)} still on a local (blob/data) src, wire completions ${await uploads.completions()} [flow-20261110b] — the ${deps.stepTimeoutMs}ms window expired before the console finished uploading`,
687
+ );
344
688
  }
689
+ return { completions: await uploads.completions() };
345
690
  }
346
691
 
347
- async function composeImageText(input: { operation: '上传图文'; images: string[] }, deps: ModeRunDeps): Promise<void> {
348
- await enterMode(deps, input.operation);
692
+ /**
693
+ * Image mode entry uses a raw coordinate click at the tab's centre. The console renders each tab
694
+ * bar three times and locator clicks (forced included) land on overlay clones — measured
695
+ * 2026-11-10 (probe-thumb-src.ts) where a viewport-centred mouse click was the only click that
696
+ * activated the editor, after which the file input began uploading immediately.
697
+ */
698
+ async function enterImageMode(deps: ModeRunDeps, label: string): Promise<void> {
699
+ if (!deps.page.clickAt || !deps.page.boundingBoxesOnScreen) {
700
+ throw new Error('mode entry (image): this driver cannot read viewport boxes or click coordinates');
701
+ }
702
+ // Let the console finish mounting (uploader chunk included) BEFORE entering the tab; a drop
703
+ // into a half-mounted editor renders previews but never uploads (2026-11-10 incident).
704
+ await settleConsole(deps);
705
+ const selector = `text=${label}`;
706
+ const deadline = Date.now() + deps.stepTimeoutMs;
707
+ while (Date.now() < deadline) {
708
+ const boxes = await deps.page.boundingBoxesOnScreen(selector).catch(() => []);
709
+ const box = boxes[0];
710
+ if (box) {
711
+ await deps.page.clickAt(box.x + box.width / 2, box.y + box.height / 2);
712
+ // The proven probe cadence (2026-11-10): the image editor's upload wiring is a lazy
713
+ // chunk — files dropped before it mounts render previews but never upload. Settle for
714
+ // the editor headline, then the probe's 1.5s.
715
+ await findSelector(
716
+ deps.page,
717
+ ['text=上传图片,或写文字生成图片'],
718
+ 'image editor settle',
719
+ deps.stepTimeoutMs,
720
+ );
721
+ await new Promise((resolve) => setTimeout(resolve, IMAGE_MODE_SETTLE_MS));
722
+ return;
723
+ }
724
+ await new Promise((resolve) => setTimeout(resolve, POLL_MS));
725
+ }
726
+ throw new Error(
727
+ `mode entry: no on-screen '${label}' tab found within ${deps.stepTimeoutMs}ms — the mode was not entered`,
728
+ );
729
+ }
730
+
731
+ /**
732
+ * Wait until the console goes network-quiet (no context responses for CONSOLE_SETTLE_QUIET_MS) or
733
+ * CONSOLE_SETTLE_MS elapses — whichever first. Mirrors the proven probe cadence of sleeping out
734
+ * the SPA's post-load churn before interacting.
735
+ */
736
+ async function settleConsole(deps: ModeRunDeps): Promise<void> {
737
+ let lastResponseAt = Date.now();
738
+ deps.page.onContextResponse?.(() => {
739
+ lastResponseAt = Date.now();
740
+ });
741
+ try {
742
+ const start = Date.now();
743
+ while (Date.now() - start < CONSOLE_SETTLE_MS) {
744
+ if (Date.now() - lastResponseAt >= CONSOLE_SETTLE_QUIET_MS) return;
745
+ await new Promise((resolve) => setTimeout(resolve, POLL_MS));
746
+ }
747
+ } finally {
748
+ deps.page.offContextResponse?.(() => {
749
+ lastResponseAt = Date.now();
750
+ });
751
+ }
752
+ }
753
+
754
+ async function composeImageText(
755
+ input: { operation: '上传图文'; images: string[] },
756
+ deps: ModeRunDeps,
757
+ ): Promise<number> {
758
+ await enterImageMode(deps, input.operation);
759
+ // VISIBLE, not merely attached: the 2026-11-10 console rewired its upload widget — several
760
+ // stale hidden inputs stay attached while only the active tab's input actually ingests
761
+ // files (measured: files on the first attached input never started an upload).
349
762
  const fileSelector = await findAttachedSelector(
350
763
  deps.page,
351
- IMAGE_FILE_INPUT,
764
+ ['input[type="file"]'],
352
765
  'image file input',
353
766
  deps.stepTimeoutMs,
354
767
  );
355
768
  // One ordered call: the console keeps the batch in payload order, and that order is the post.
356
- await deps.page.setInputFiles(fileSelector, input.images);
357
- await confirmThumbnails(deps, input.images.length);
358
- await applyNoteTitle(deps);
359
- await typeNoteBody(deps, NOTE_BODY, 'note body');
769
+ const uploads = trackSpectrumUploads(deps.page);
770
+ try {
771
+ await deps.page.setInputFiles(fileSelector, input.images);
772
+ const confirmed = await confirmThumbnails(deps, input.images.length, uploads);
773
+ await applyNoteTitle(deps);
774
+ await typeNoteBody(deps, NOTE_BODY, 'note body');
775
+ return confirmed.completions;
776
+ } finally {
777
+ uploads.dispose();
778
+ }
360
779
  }
361
780
 
362
781
  async function composeVideo(input: { operation: '上传视频'; video: string }, deps: ModeRunDeps): Promise<void> {
@@ -522,6 +941,79 @@ async function composePodcast(
522
941
  await uploadPodcastCover(deps, input.cover);
523
942
  await podcastAdvanceReady(deps);
524
943
  await leavePodcastModal(deps);
944
+ // Task 0350 R4: fill the podcast editor's fields — title, derived ≤1000-unit body, 合集 chip.
945
+ await applyPodcastFields(deps);
946
+ }
947
+
948
+ /** The 合集 the episode joins: the content's declared collection, else the daily show's. */
949
+ function podcastCollection(content: Content): string {
950
+ const declared = content.metadata?.collection;
951
+ return typeof declared === 'string' && declared.trim().length > 0 ? declared.trim() : PODCAST_COLLECTION_DEFAULT;
952
+ }
953
+
954
+ function clipLine(text: string, cap: number): string {
955
+ return text.length > cap ? `${text.slice(0, cap - 1)}…` : text;
956
+ }
957
+
958
+ /**
959
+ * The podcast editor's body is derived, never the raw article: the episode content carries the
960
+ * full multi-thousand-char markdown while the field caps at 1000 counter units — a raw
961
+ * pass-through overflows every save (the manual-repair failure mode task 0350 closes). Mechanical
962
+ * derivation: the intro line, one `· ` bullet per `## ` headline, and the closing line. Headlines
963
+ * drop first when the budget runs out; intro/closing are clipped; the final slice is the hard
964
+ * guarantee. The platform counter re-verifies after typing.
965
+ */
966
+ export function derivePodcastBody(content: Content, max = XHS_NOTE_BODY_MAX): string {
967
+ const lines = (content.body ?? '')
968
+ .split('\n')
969
+ .map((line) => line.trim())
970
+ .filter((line) => line.length > 0);
971
+ const prose = lines.filter((line) => !line.startsWith('#'));
972
+ const introSource = prose[0] ?? content.title ?? '';
973
+ const intro = clipLine(introSource, 80);
974
+ const closing = prose.length > 1 ? clipLine(prose[prose.length - 1] ?? '', 60) : '';
975
+ const budget = max - (closing.length > 0 ? closing.length + 1 : 0);
976
+ const parts: string[] = [intro];
977
+ let used = intro.length;
978
+ for (const line of lines.filter((line) => line.startsWith('## '))) {
979
+ const bullet = `· ${line.slice(3).trim()}`;
980
+ if (used + bullet.length + 1 > budget) break;
981
+ parts.push(bullet);
982
+ used += bullet.length + 1;
983
+ }
984
+ if (closing.length > 0) parts.push(closing);
985
+ return parts.join('\n').slice(0, max);
986
+ }
987
+
988
+ /**
989
+ * Fill the podcast editor's fields (task 0350 R4). The title input, the 0/1000 body counter and
990
+ * the 加入播客合集 chip were measured in the 2026-11-11 discovery but not selector-measured —
991
+ * the probe chains name what they try, and the platform counters plus verifyDraft fail loud when
992
+ * a field did not take.
993
+ */
994
+ async function applyPodcastFields(deps: ModeRunDeps): Promise<void> {
995
+ const title = deps.content.title ?? '';
996
+ if (title.length > 0) {
997
+ const selector = await findSelector(
998
+ deps.page,
999
+ PODCAST_TITLE_SELECTORS,
1000
+ 'podcast title input',
1001
+ deps.stepTimeoutMs,
1002
+ );
1003
+ await deps.page.locator(selector).first().fill(title);
1004
+ }
1005
+ await assertPlatformCounter(deps.page, TITLE_COUNTER_EXPR, XHS_NOTE_TITLE_MAX, 'title');
1006
+ const body = derivePodcastBody(deps.content, XHS_NOTE_BODY_MAX);
1007
+ await typeNoteBody(deps, NOTE_BODY, 'podcast body', body);
1008
+ const collection = podcastCollection(deps.content);
1009
+ const chip = await findSelector(
1010
+ deps.page,
1011
+ PODCAST_COLLECTION_SELECTORS,
1012
+ '加入播客合集 control',
1013
+ deps.stepTimeoutMs,
1014
+ );
1015
+ await deps.page.locator(chip).first().click({ timeout: deps.stepTimeoutMs });
1016
+ await deps.page.locator(`text=${collection}`).first().click({ timeout: deps.stepTimeoutMs });
525
1017
  }
526
1018
 
527
1019
  async function uploadPodcastCover(deps: ModeRunDeps, cover: string): Promise<void> {
@@ -627,20 +1119,19 @@ async function podcastAdvanceReady(deps: ModeRunDeps): Promise<void> {
627
1119
  }
628
1120
 
629
1121
  /** Compose the requested mode's post. Exhaustive over {@link ModeInput}. */
630
- async function compose(input: ModeInput, deps: ModeRunDeps): Promise<void> {
1122
+ async function compose(input: ModeInput, deps: ModeRunDeps): Promise<{ wireCompletions?: number }> {
631
1123
  switch (input.operation) {
632
1124
  case '上传图文':
633
- await composeImageText(input, deps);
634
- return;
1125
+ return { wireCompletions: await composeImageText(input, deps) };
635
1126
  case '上传视频':
636
1127
  await composeVideo(input, deps);
637
- return;
1128
+ return {};
638
1129
  case '写长文':
639
1130
  await composeArticle(deps);
640
- return;
1131
+ return {};
641
1132
  case '发播客':
642
1133
  await composePodcast(input, deps);
643
- return;
1134
+ return {};
644
1135
  }
645
1136
  }
646
1137
 
@@ -664,19 +1155,43 @@ async function saveDraft(input: ModeInput, deps: ModeRunDeps): Promise<Result> {
664
1155
  let clicked: ActionClick | null = null;
665
1156
  let signal: string | null = null;
666
1157
  let attempts = 0;
1158
+ let capture: OutcomeCapture | null = null;
1159
+ await armOutcomeCapture(deps.page);
667
1160
  while (signal === null && attempts < deps.submitAttempts) {
668
1161
  attempts += 1;
669
1162
  await sleep(deps.submitSettleMs);
670
- const control = await clickActionControl(input.operation, deps, DRAFT_LABELS, 'draft control');
1163
+ // Host-method save first: the closed-shadow bar swallows synthetic coordinate clicks.
1164
+ const method = await invokeHostSave(deps.page);
1165
+ const control: Awaited<ReturnType<typeof clickActionControl>> =
1166
+ method !== null
1167
+ ? { ok: true, path: 'shadow', label: `_onSave:${method}`, click: 'shadow-host-method' }
1168
+ : await clickActionControl(input.operation, deps, DRAFT_LABELS, 'draft control');
671
1169
  if (!control.ok) return fail(control.error);
672
1170
  clicked = control;
673
- const outcome = await expectOutcome(() => draftSignalEvidence(deps.page, deps.draftBaseline), {
674
- timeoutMs: deps.submitSettleMs,
675
- label: `draft confirmation '${control.label}'`,
676
- pollMs: POLL_MS,
677
- });
1171
+ // The capture is refreshed inside the probe (expectOutcome swallows probe throws by
1172
+ // design — the refusal is classified OUTSIDE, so it propagates as a typed error).
1173
+ const outcome = await expectOutcome(
1174
+ async () => {
1175
+ if (capture === null) capture = await readOutcomeCapture(deps.page);
1176
+ return draftSignalEvidence(deps.page, deps.draftBaseline);
1177
+ },
1178
+ {
1179
+ timeoutMs: deps.submitSettleMs,
1180
+ label: `draft confirmation '${control.label}'`,
1181
+ pollMs: POLL_MS,
1182
+ },
1183
+ );
678
1184
  if (outcome.ok) signal = outcome.evidence;
1185
+ else {
1186
+ // A captured refusal must not be retried: refresh and re-check before another click.
1187
+ capture = capture ?? (await readOutcomeCapture(deps.page));
1188
+ assertCapturedOutcome(capture);
1189
+ }
679
1190
  }
1191
+ if (capture === null) capture = await readOutcomeCapture(deps.page);
1192
+ // The captured server response outranks every UI signal — a toast can lie while the API
1193
+ // refused (2026-11-09/10 runs) — so it is classified before any success is reported.
1194
+ assertCapturedOutcome(capture);
680
1195
  const draftCountAfter = await readDraftCount(deps.page);
681
1196
  if (signal === null || clicked === null) {
682
1197
  return fail(
@@ -696,6 +1211,7 @@ async function saveDraft(input: ModeInput, deps: ModeRunDeps): Promise<Result> {
696
1211
  draftSignal: signal,
697
1212
  draftCountBefore: deps.draftBaseline.count,
698
1213
  draftCountAfter,
1214
+ ...captureMetadata(capture),
699
1215
  },
700
1216
  });
701
1217
  }
@@ -708,17 +1224,26 @@ async function saveDraft(input: ModeInput, deps: ModeRunDeps): Promise<Result> {
708
1224
  */
709
1225
  async function publishNote(input: ModeInput, deps: ModeRunDeps): Promise<Result> {
710
1226
  await sleep(deps.submitSettleMs);
1227
+ let capture: OutcomeCapture | null = null;
1228
+ await armOutcomeCapture(deps.page);
711
1229
  const submitted = await clickActionControl(input.operation, deps, PUBLISH_LABELS, 'publish control');
712
1230
  if (!submitted.ok) return fail(submitted.error);
713
1231
 
714
1232
  const urlBeforeSubmit = deps.page.url();
715
1233
  const confirmed = await waitUntil(async () => {
1234
+ // The captured refusal aborts immediately — waitUntil propagates the typed throw, and a
1235
+ // publish click is never retried (unlike the draft loop there is no next attempt).
1236
+ if (capture === null) capture = await readOutcomeCapture(deps.page);
1237
+ assertCapturedOutcome(capture);
716
1238
  // The console rewrites its URL to `…published=true` once the post is accepted; the toast is
717
1239
  // the fallback, read scoped (never from the document at large).
718
1240
  if (deps.page.url().includes(PUBLISHED_MARKER)) return true;
719
1241
  return (await readScopedSignal(asPlaywrightPage(deps.page), PUBLISH_CONFIRM)) !== null;
720
1242
  }, deps.stepTimeoutMs);
721
1243
  if (!confirmed) {
1244
+ // A refusal that lands late still outranks the "state unknown" timeout message.
1245
+ capture = capture ?? (await readOutcomeCapture(deps.page));
1246
+ assertCapturedOutcome(capture);
722
1247
  return fail(
723
1248
  `publish submission: state unknown — the '${submitted.label}' click (${submitted.click}) was sent from ${urlBeforeSubmit} but no success state was observed (now ${deps.page.url()}). Check the ${TARGET} creator note manager before retrying: a retry could duplicate the post.`,
724
1249
  );
@@ -735,15 +1260,218 @@ async function publishNote(input: ModeInput, deps: ModeRunDeps): Promise<Result>
735
1260
  publishPath: submitted.path,
736
1261
  publishClick: submitted.click,
737
1262
  publishSignal: url.includes(PUBLISHED_MARKER) ? `url:${PUBLISHED_MARKER}` : 'toast',
1263
+ ...captureMetadata(capture),
738
1264
  },
739
1265
  });
740
1266
  }
741
1267
 
1268
+ /** What the reopened draft must show for the save to count as server-side complete (R3). */
1269
+ interface DraftExpectation {
1270
+ slots: number | null;
1271
+ title: boolean;
1272
+ body: boolean;
1273
+ collection: string | null;
1274
+ }
1275
+
1276
+ function draftExpectation(input: ModeInput, deps: ModeRunDeps): DraftExpectation {
1277
+ switch (input.operation) {
1278
+ case '上传图文':
1279
+ return {
1280
+ slots: input.images.length,
1281
+ title: true,
1282
+ body: (deps.content.body ?? '').trim().length > 0,
1283
+ collection: null,
1284
+ };
1285
+ case '上传视频':
1286
+ return { slots: null, title: true, body: (deps.content.body ?? '').trim().length > 0, collection: null };
1287
+ case '写长文':
1288
+ return { slots: null, title: false, body: true, collection: null };
1289
+ case '发播客':
1290
+ return { slots: null, title: true, body: true, collection: podcastCollection(deps.content) };
1291
+ }
1292
+ }
1293
+
1294
+ const DRAFT_NAV_SELECTOR = 'text=草稿箱';
1295
+ const DRAFT_EDIT_SELECTOR = 'text=编辑';
1296
+ const VERIFY_SLOTS_EXPR = `/* kk-verify-slots */ (() => JSON.stringify({ count: document.querySelectorAll('img.preivew-image').length }))()`;
1297
+ const VERIFY_SRCS_EXPR = `/* kk-verify-srcs */ (() => JSON.stringify(Array.from(document.querySelectorAll('img.preivew-image')).map((img) => img.getAttribute('src') || '')))()`;
1298
+ const VERIFY_TITLE_EXPR = `/* kk-verify-title */ (() => {
1299
+ const input = document.querySelector('input.d-text') || document.querySelector('textarea[placeholder*="标题"]');
1300
+ return input ? (input.value || '') : '';
1301
+ })()`;
1302
+ export const VERIFY_BODY_EXPR = `/* kk-verify-body */ (() => {
1303
+ for (const node of document.querySelectorAll('div.edit-container *')) {
1304
+ const t = (node.textContent || '').trim();
1305
+ if (/^\\d+\\/\\d+$/.test(t) && node.children.length === 0) return JSON.stringify({ counter: t });
1306
+ }
1307
+ const editor = document.querySelector('div.tiptap, .ProseMirror, .ql-editor');
1308
+ return JSON.stringify({ textLen: (editor?.textContent || '').trim().length });
1309
+ })()`;
1310
+
1311
+ /** Reopen probe for 合集 membership. The name is a JSON string literal so a quote cannot escape the page script. */
1312
+ export function collectionProbeExpr(collection: string): string {
1313
+ const literal = JSON.stringify(collection);
1314
+ return `/* kk-verify-collection */ (() => (document.body.innerText.includes(${literal}) ? 'kk-verify-collection:yes' : 'kk-verify-collection:no'))()`;
1315
+ }
1316
+
1317
+ /**
1318
+ * Task 0350 R3 — verifyDraft: the save click proves nothing about the SERVER-side copy (the
1319
+ * 2026-11-09/10 incidents: drafts whose images were blob-only, fields never persisted). The flow
1320
+ * reopens the saved draft (草稿箱 → the list's 编辑) and asserts what must have persisted: the
1321
+ * exact slot count with every src durable https, the title/body/合集 fields. A violated assertion
1322
+ * is a typed failure — the draft stays in the box for a manual pass, but the run reports failure.
1323
+ *
1324
+ * Evidence note (2026-11-11 discovery): the 草稿箱 counter is measured; the draft LIST and its
1325
+ * 编辑 control are not selector-measured — these probes say so by naming what they try.
1326
+ */
1327
+ async function verifyDraft(
1328
+ input: ModeInput,
1329
+ deps: ModeRunDeps,
1330
+ wired?: { wireCompletions?: number },
1331
+ ): Promise<Record<string, unknown>> {
1332
+ const expectation = draftExpectation(input, deps);
1333
+ const nav = deps.page.locator(DRAFT_NAV_SELECTOR);
1334
+ // The save click leaves a success modal / in-flight navigation; the sidebar nav re-appears
1335
+ // once both settle (2026-11-10 incident: an instant count raced the modal and failed a save
1336
+ // the captured server response had already confirmed). Poll for it inside the step window.
1337
+ const navAppeared = await waitUntil(
1338
+ async () => (await nav.count().catch(() => 0)) > 0,
1339
+ deps.stepTimeoutMs,
1340
+ POLL_MS,
1341
+ );
1342
+ if (!navAppeared) {
1343
+ throw new DraftVerifyError(
1344
+ `DraftVerifyError: could not reopen the saved draft — '${DRAFT_NAV_SELECTOR}' matched nothing within ${deps.stepTimeoutMs}ms after the save; verify the draft box manually in profile ${deps.profileDir}`,
1345
+ );
1346
+ }
1347
+ // Locator clicks hang on this console wherever an overlay intercepts pointer events (the tab
1348
+ // bar clones measured 2026-11-10; the same overlay class intercepted the 草稿箱 nav on the
1349
+ // 2026-11-11 daily run — locator resolved, click never dispatched). Aim raw coordinates at
1350
+ // the first on-screen match, with the locator click as the fallback for other drivers.
1351
+ const navBox = (await deps.page.boundingBoxesOnScreen?.(DRAFT_NAV_SELECTOR).catch(() => []))?.[0];
1352
+ if (navBox && deps.page.clickAt) {
1353
+ await deps.page.clickAt(navBox.x + navBox.width / 2, navBox.y + navBox.height / 2);
1354
+ } else {
1355
+ await nav.first().click({ timeout: deps.stepTimeoutMs });
1356
+ }
1357
+ const edit = deps.page.locator(DRAFT_EDIT_SELECTOR);
1358
+ if ((await edit.count().catch(() => 0)) === 0) {
1359
+ throw new DraftVerifyError(
1360
+ `DraftVerifyError: the draft list shows no '${DRAFT_EDIT_SELECTOR}' control to reopen the saved note (2026-11-11 evidence: 编辑 1/18 on the draft list)`,
1361
+ );
1362
+ }
1363
+ const editBox = (await deps.page.boundingBoxesOnScreen?.(DRAFT_EDIT_SELECTOR).catch(() => []))?.[0];
1364
+ if (editBox && deps.page.clickAt) {
1365
+ await deps.page.clickAt(editBox.x + editBox.width / 2, editBox.y + editBox.height / 2);
1366
+ } else {
1367
+ await edit.first().click({ timeout: deps.stepTimeoutMs });
1368
+ }
1369
+ // The reopened editor mounts asynchronously (TipTap hydrates after the route lands); reading
1370
+ // it instantly returned 0 slots / empty title on the 2026-11-11 daily run. Poll until the
1371
+ // editor answers with any content before judging the persisted state.
1372
+ const editorReady = await waitUntil(
1373
+ async () => {
1374
+ const slotsRead = await deps.page.evaluate(VERIFY_SLOTS_EXPR).catch(() => null);
1375
+ const titleRead = await deps.page.evaluate(VERIFY_TITLE_EXPR).catch(() => null);
1376
+ const bodyRead = await deps.page.evaluate(VERIFY_BODY_EXPR).catch(() => null);
1377
+ const count = typeof slotsRead === 'string' ? (JSON.parse(slotsRead) as { count?: number }).count : 0;
1378
+ const title = typeof titleRead === 'string' ? titleRead : '';
1379
+ const body =
1380
+ typeof bodyRead === 'string' ? (JSON.parse(bodyRead) as { counter?: string; textLen?: number }) : {};
1381
+ const slotsVisible = expectation.slots !== null && (count ?? 0) > 0;
1382
+ const titleVisible = expectation.title && title.length > 0;
1383
+ const bodyVisible = expectation.body && (body.counter !== undefined || (body.textLen ?? 0) > 0);
1384
+ return Boolean(slotsVisible || titleVisible || bodyVisible);
1385
+ },
1386
+ deps.stepTimeoutMs,
1387
+ POLL_MS,
1388
+ );
1389
+ const problems: string[] = [];
1390
+ if (!editorReady) {
1391
+ problems.push('the reopened editor never rendered content within the step window (0 thumbnails, empty title)');
1392
+ }
1393
+ if (expectation.slots !== null) {
1394
+ const slotsRead = await deps.page.evaluate(VERIFY_SLOTS_EXPR);
1395
+ const count = typeof slotsRead === 'string' ? (JSON.parse(slotsRead) as { count?: number }).count : null;
1396
+ if (count !== expectation.slots) {
1397
+ problems.push(
1398
+ `expected ${expectation.slots} thumbnails on the reopened draft, the editor shows ${String(count)}`,
1399
+ );
1400
+ } else {
1401
+ const srcsRead = await deps.page.evaluate(VERIFY_SRCS_EXPR);
1402
+ const srcs = typeof srcsRead === 'string' ? (JSON.parse(srcsRead) as string[]) : [];
1403
+ const local = srcs
1404
+ .map((src, index) => (src.startsWith('https://') ? null : index + 1))
1405
+ .filter((slot) => slot !== null);
1406
+ // On the REOPENED editor the console re-hosts its own CDN images as blob: object URLs
1407
+ // (measured 2026-11-11: 7 slots all blob: after the wire had completed every upload),
1408
+ // so the src scheme is not a persistence signal here. When the wire completed every
1409
+ // upload before the save, the slot count is the persistence evidence; without wire
1410
+ // completions a local src still means the server-side copy may be missing.
1411
+ const wireDone =
1412
+ expectation.slots !== null &&
1413
+ (wired?.wireCompletions ?? 0) >= expectation.slots &&
1414
+ count === expectation.slots;
1415
+ if (local.length > 0 && !wireDone) {
1416
+ problems.push(
1417
+ `slots ${local.join(', ')} still carry a non-https (blob/data/local) src — the server-side copy is missing`,
1418
+ );
1419
+ }
1420
+ }
1421
+ }
1422
+ if (expectation.title) {
1423
+ const editorTitle = String((await deps.page.evaluate(VERIFY_TITLE_EXPR)) ?? '');
1424
+ if (editorTitle !== (deps.content.title ?? '')) {
1425
+ problems.push(`title mismatch: content '${deps.content.title ?? ''}' vs reopened draft '${editorTitle}'`);
1426
+ }
1427
+ }
1428
+ if (expectation.body) {
1429
+ const bodyRead = await deps.page.evaluate(VERIFY_BODY_EXPR);
1430
+ const parsed =
1431
+ typeof bodyRead === 'string' ? (JSON.parse(bodyRead) as { counter?: string; textLen?: number }) : {};
1432
+ const units = parsed.counter !== undefined ? counterUnits(parsed.counter) : null;
1433
+ if (!((units ?? 0) > 0) && !((parsed.textLen ?? 0) > 0)) {
1434
+ problems.push('body: the reopened draft shows neither a readable N/M counter nor editor text');
1435
+ }
1436
+ }
1437
+ if (expectation.collection !== null) {
1438
+ const verdict = await deps.page.evaluate(collectionProbeExpr(expectation.collection));
1439
+ if (verdict !== 'kk-verify-collection:yes') {
1440
+ problems.push(`collection: the reopened podcast draft does not show '${expectation.collection}'`);
1441
+ }
1442
+ }
1443
+ // Leave the reopened editor WITHOUT saving: a 暂存离开 here would re-save and move the draft
1444
+ // counter the next run baselines against. Navigating away is the exit that touches nothing.
1445
+ await deps.page.goto(PUBLISH_URL);
1446
+ if (problems.length > 0) {
1447
+ throw new DraftVerifyError(
1448
+ `DraftVerifyError: the saved draft does not verify after reopen — ${problems.join('; ')}`,
1449
+ );
1450
+ }
1451
+ return {
1452
+ ...(expectation.slots !== null ? { slots: expectation.slots } : {}),
1453
+ ...(expectation.title ? { titleChecked: true } : {}),
1454
+ ...(expectation.body ? { bodyChecked: true } : {}),
1455
+ ...(expectation.collection !== null ? { collection: expectation.collection } : {}),
1456
+ };
1457
+ }
1458
+
742
1459
  /**
743
1460
  * Run one validated operation end to end: compose the post, then take it to a draft or (only on an
744
- * explicit live request) publish it.
1461
+ * explicit live request) publish it. A draft only counts when the REOPENED copy verifies
1462
+ * (task 0350 R3) — a save that cannot survive its own reopen fails the run.
745
1463
  */
746
1464
  export async function runMode(input: ModeInput, deps: ModeRunDeps): Promise<Result> {
747
- await compose(input, deps);
748
- return deps.publishStatus === 'public' ? publishNote(input, deps) : saveDraft(input, deps);
1465
+ const wired = await compose(input, deps);
1466
+ if (deps.publishStatus === 'public') return publishNote(input, deps);
1467
+ const saved = await saveDraft(input, deps);
1468
+ if (!saved.ok) return saved;
1469
+ let verified: Record<string, unknown>;
1470
+ try {
1471
+ verified = await verifyDraft(input, deps, wired);
1472
+ } catch (error) {
1473
+ const reason = error instanceof Error ? error.message : String(error);
1474
+ return fail(`draft saved but the reopen verification failed: ${reason}`);
1475
+ }
1476
+ return ResultSchema.parse({ ...saved, metadata: { ...saved.metadata, draftVerified: verified } });
749
1477
  }