@gobing-ai/knowledge-kit 0.1.25 → 0.1.28

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 (62) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/board/collect/index.js +10 -0
  3. package/dist/board/daily-voice/index.js +1327 -2168
  4. package/dist/board/itc/index.js +10 -0
  5. package/dist/index.js +6043 -4620
  6. package/package.json +1 -1
  7. package/plugins/ingestions/aihot-ingest/dist/index.js +4 -1
  8. package/plugins/ingestions/aihot-ingest/src/rss.ts +22 -11
  9. package/plugins/kk/plugin.json +1 -1
  10. package/plugins/kk/scripts/cn-lead-gate.ts +494 -0
  11. package/plugins/kk/scripts/daily-stages.ts +423 -141
  12. package/plugins/kk/scripts/kk-workflow-stages.ts +53 -3
  13. package/plugins/kk/skills/news-editorial/SKILL.md +20 -3
  14. package/plugins/kk/skills/news-editorial/references/selection.md +42 -0
  15. package/plugins/kk/workflows/kk-news-generate.yaml +1 -1
  16. package/plugins/publishings/bilibili-pub/dist/index.js +114 -82
  17. package/plugins/publishings/bilibili-pub/dist/profile-check.js +34 -3
  18. package/plugins/publishings/cnblogs-pub/dist/index.js +114 -82
  19. package/plugins/publishings/cnblogs-pub/dist/profile-check.js +34 -3
  20. package/plugins/publishings/csdn-pub/dist/index.js +114 -82
  21. package/plugins/publishings/csdn-pub/dist/profile-check.js +34 -3
  22. package/plugins/publishings/infoq-pub/dist/index.js +114 -82
  23. package/plugins/publishings/infoq-pub/dist/profile-check.js +34 -3
  24. package/plugins/publishings/jike-pub/dist/index.js +114 -82
  25. package/plugins/publishings/jike-pub/dist/profile-check.js +34 -3
  26. package/plugins/publishings/juejin-pub/dist/index.js +114 -82
  27. package/plugins/publishings/juejin-pub/dist/profile-check.js +34 -3
  28. package/plugins/publishings/linkedin-pub/dist/index.js +165 -93
  29. package/plugins/publishings/linkedin-pub/dist/profile-check.js +51 -6
  30. package/plugins/publishings/linkedin-pub/src/index.ts +126 -9
  31. package/plugins/publishings/medium-pub/dist/index.js +114 -82
  32. package/plugins/publishings/medium-pub/dist/profile-check.js +34 -3
  33. package/plugins/publishings/shipinhao-pub/dist/index.js +305 -87
  34. package/plugins/publishings/shipinhao-pub/dist/profile-check.js +145 -5
  35. package/plugins/publishings/shipinhao-pub/src/cover-crop.ts +60 -0
  36. package/plugins/publishings/shipinhao-pub/src/flow.ts +15 -2
  37. package/plugins/publishings/shipinhao-pub/src/profile-check.ts +15 -12
  38. package/plugins/publishings/shipinhao-pub/src/selectors.ts +22 -1
  39. package/plugins/publishings/sspai-pub/dist/index.js +114 -82
  40. package/plugins/publishings/sspai-pub/dist/profile-check.js +34 -3
  41. package/plugins/publishings/substack-pub/dist/index.js +114 -82
  42. package/plugins/publishings/substack-pub/dist/profile-check.js +34 -3
  43. package/plugins/publishings/surfdash-pub/dist/index.js +96 -20
  44. package/plugins/publishings/surfdash-pub/src/index.ts +31 -4
  45. package/plugins/publishings/surfdash-pub/src/patch.ts +81 -12
  46. package/plugins/publishings/threads-pub/dist/index.js +119 -83
  47. package/plugins/publishings/threads-pub/dist/profile-check.js +34 -3
  48. package/plugins/publishings/threads-pub/src/index.ts +10 -0
  49. package/plugins/publishings/wechatmp-pub/dist/index.js +149 -86
  50. package/plugins/publishings/wechatmp-pub/dist/profile-check.js +68 -4
  51. package/plugins/publishings/wechatmp-pub/src/index.ts +64 -1
  52. package/plugins/publishings/weibo-pub/dist/index.js +273 -91
  53. package/plugins/publishings/weibo-pub/dist/profile-check.js +178 -11
  54. package/plugins/publishings/weibo-pub/plugin.json +1 -1
  55. package/plugins/publishings/weibo-pub/src/index.ts +136 -10
  56. package/plugins/publishings/weibo-pub/src/profile-check.ts +4 -2
  57. package/plugins/publishings/x-pub/dist/index.js +114 -82
  58. package/plugins/publishings/x-pub/dist/profile-check.js +34 -3
  59. package/plugins/publishings/xhs-pub/dist/index.js +114 -82
  60. package/plugins/publishings/xhs-pub/dist/profile-check.js +34 -3
  61. package/plugins/publishings/xiaoyuzhou-pub/dist/index.js +114 -82
  62. package/plugins/publishings/xiaoyuzhou-pub/dist/profile-check.js +34 -3
@@ -20174,6 +20174,89 @@ var ATTACHED_CLOSERS = new Set(["\u201D", "\u2019", "\u300D", "\u300F", "\uFF09"
20174
20174
  import { homedir } from "os";
20175
20175
  import { join, resolve } from "path";
20176
20176
 
20177
+ // ../../packages/publish-harness/src/bot-fs.ts
20178
+ import {
20179
+ chmodSync,
20180
+ closeSync,
20181
+ copyFileSync,
20182
+ lstatSync,
20183
+ mkdirSync as mkdirSync2,
20184
+ openSync,
20185
+ readdirSync as readdirSync2,
20186
+ readlinkSync,
20187
+ realpathSync as realpathSync2,
20188
+ renameSync as renameSync2,
20189
+ rmdirSync,
20190
+ unlinkSync
20191
+ } from "fs";
20192
+ function lstat(path) {
20193
+ try {
20194
+ return lstatSync(path);
20195
+ } catch (error) {
20196
+ if (error.code === "ENOENT")
20197
+ return null;
20198
+ throw error;
20199
+ }
20200
+ }
20201
+ function realpath(path) {
20202
+ return realpathSync2(path);
20203
+ }
20204
+ function mkdirExclusive(path, mode = 448) {
20205
+ try {
20206
+ mkdirSync2(path, { mode });
20207
+ return true;
20208
+ } catch (error) {
20209
+ if (error.code === "EEXIST")
20210
+ return false;
20211
+ throw error;
20212
+ }
20213
+ }
20214
+ function rmdir(path) {
20215
+ try {
20216
+ rmdirSync(path);
20217
+ return true;
20218
+ } catch (error) {
20219
+ const code = error.code;
20220
+ if (code === "ENOENT" || code === "ENOTEMPTY" || code === "EEXIST")
20221
+ return false;
20222
+ throw error;
20223
+ }
20224
+ }
20225
+ function readlink(path) {
20226
+ try {
20227
+ return readlinkSync(path);
20228
+ } catch {
20229
+ return null;
20230
+ }
20231
+ }
20232
+ function unlink(path) {
20233
+ try {
20234
+ unlinkSync(path);
20235
+ return true;
20236
+ } catch (error) {
20237
+ if (error.code === "ENOENT")
20238
+ return false;
20239
+ throw error;
20240
+ }
20241
+ }
20242
+ function rename(from, to) {
20243
+ try {
20244
+ renameSync2(from, to);
20245
+ return true;
20246
+ } catch (error) {
20247
+ if (error.code === "ENOENT")
20248
+ return false;
20249
+ throw error;
20250
+ }
20251
+ }
20252
+ function chmod(path, mode) {
20253
+ chmodSync(path, mode);
20254
+ }
20255
+ function createExclusiveFile(path) {
20256
+ closeSync(openSync(path, "wx", 384));
20257
+ }
20258
+
20259
+ // ../../packages/publish-harness/src/index.ts
20177
20260
  class FakeTransportCore {
20178
20261
  callLogs = [];
20179
20262
  nextResult;
@@ -20476,88 +20559,6 @@ init_dist();
20476
20559
  import { homedir as homedir4 } from "os";
20477
20560
  import { isAbsolute, join as join4, relative, resolve as resolve4, sep } from "path";
20478
20561
 
20479
- // ../../packages/publish-harness/src/bot-fs.ts
20480
- import {
20481
- chmodSync,
20482
- closeSync,
20483
- copyFileSync,
20484
- lstatSync,
20485
- mkdirSync as mkdirSync2,
20486
- openSync,
20487
- readdirSync as readdirSync2,
20488
- readlinkSync,
20489
- realpathSync as realpathSync2,
20490
- renameSync as renameSync2,
20491
- rmdirSync,
20492
- unlinkSync
20493
- } from "fs";
20494
- function lstat(path) {
20495
- try {
20496
- return lstatSync(path);
20497
- } catch (error) {
20498
- if (error.code === "ENOENT")
20499
- return null;
20500
- throw error;
20501
- }
20502
- }
20503
- function realpath(path) {
20504
- return realpathSync2(path);
20505
- }
20506
- function mkdirExclusive(path, mode = 448) {
20507
- try {
20508
- mkdirSync2(path, { mode });
20509
- return true;
20510
- } catch (error) {
20511
- if (error.code === "EEXIST")
20512
- return false;
20513
- throw error;
20514
- }
20515
- }
20516
- function rmdir(path) {
20517
- try {
20518
- rmdirSync(path);
20519
- return true;
20520
- } catch (error) {
20521
- const code = error.code;
20522
- if (code === "ENOENT" || code === "ENOTEMPTY" || code === "EEXIST")
20523
- return false;
20524
- throw error;
20525
- }
20526
- }
20527
- function readlink(path) {
20528
- try {
20529
- return readlinkSync(path);
20530
- } catch {
20531
- return null;
20532
- }
20533
- }
20534
- function unlink(path) {
20535
- try {
20536
- unlinkSync(path);
20537
- return true;
20538
- } catch (error) {
20539
- if (error.code === "ENOENT")
20540
- return false;
20541
- throw error;
20542
- }
20543
- }
20544
- function rename(from, to) {
20545
- try {
20546
- renameSync2(from, to);
20547
- return true;
20548
- } catch (error) {
20549
- if (error.code === "ENOENT")
20550
- return false;
20551
- throw error;
20552
- }
20553
- }
20554
- function chmod(path, mode) {
20555
- chmodSync(path, mode);
20556
- }
20557
- function createExclusiveFile(path) {
20558
- closeSync(openSync(path, "wx", 384));
20559
- }
20560
-
20561
20562
  // ../../packages/publish-harness/src/bot-transaction.ts
20562
20563
  import { homedir as homedir2 } from "os";
20563
20564
  import { dirname as dirname2, join as join2, resolve as resolve2 } from "path";
@@ -20582,7 +20583,12 @@ async function acquireProfileLease(profileDir, options = {}) {
20582
20583
  const leaseDir = join3(leaseRoot, id);
20583
20584
  await fileSystem.ensureDir(leaseRoot);
20584
20585
  if (!mkdirExclusive(leaseDir, 448)) {
20585
- throw new BotError("busy", await busyGuidance(fileSystem, leaseDir));
20586
+ if (!await reclaimDeadOwnerLease(fileSystem, leaseDir)) {
20587
+ throw new BotError("busy", await busyGuidance(fileSystem, leaseDir));
20588
+ }
20589
+ if (!mkdirExclusive(leaseDir, 448)) {
20590
+ throw new BotError("busy", await busyGuidance(fileSystem, leaseDir));
20591
+ }
20586
20592
  }
20587
20593
  const token = randomBytes(16).toString("hex");
20588
20594
  const owner = {
@@ -20698,9 +20704,35 @@ async function busyGuidance(fileSystem, leaseDir) {
20698
20704
  }
20699
20705
  return `browser lease ${leaseDir} already exists with no owner record \u2014 a previous run may have crashed mid-acquire; confirm no kk browser still uses this profile, then remove ${leaseDir} manually`;
20700
20706
  }
20701
- const suffix = isProcessAlive(owner.pid) ? "confirm that process and any browser for this profile have stopped; stale ownership is never auto-removed" : `pid ${owner.pid} is no longer running \u2014 confirm no browser for this profile is open, then remove the stale lease with: rm -rf ${leaseDir}`;
20707
+ const live = isProcessAlive(owner.pid) ? [] : await liveChildHolders(fileSystem, leaseDir);
20708
+ const suffix = live.length > 0 ? `pid ${owner.pid} is gone but child holders ${live.join(", ")} are still running \u2014 stop those processes before retrying` : isProcessAlive(owner.pid) ? "confirm that process and any browser for this profile have stopped; stale ownership is never auto-removed" : `pid ${owner.pid} is no longer running and the lease could not be reclassified \u2014 confirm no browser for this profile is open, then remove the stale lease with: rm -rf ${leaseDir}`;
20702
20709
  return `browser lease ${leaseDir} is held by pid ${owner.pid} (logical ${owner.logicalPath}) \u2014 ${suffix}`;
20703
20710
  }
20711
+ async function reclaimDeadOwnerLease(fileSystem, leaseDir) {
20712
+ const owner = await readOwner(fileSystem, leaseDir);
20713
+ if (owner === null || isProcessAlive(owner.pid))
20714
+ return false;
20715
+ if ((await liveChildHolders(fileSystem, leaseDir)).length > 0)
20716
+ return false;
20717
+ const target = staleLeaseDir(leaseDir);
20718
+ try {
20719
+ rename(leaseDir, target);
20720
+ } catch {
20721
+ return false;
20722
+ }
20723
+ const moved = await readOwner(fileSystem, target);
20724
+ if (moved !== null && moved.token !== owner.token) {
20725
+ try {
20726
+ rename(target, leaseDir);
20727
+ } catch {}
20728
+ return false;
20729
+ }
20730
+ return true;
20731
+ }
20732
+ function staleLeaseDir(leaseDir) {
20733
+ const stamp = new Date().toISOString().replace(/[:.]/g, "").slice(0, 15);
20734
+ return `${leaseDir}.stale-${stamp}-${process.pid}-${randomBytes(3).toString("hex")}`;
20735
+ }
20704
20736
  async function holderResidue(fileSystem, leaseDir) {
20705
20737
  try {
20706
20738
  const entries = await fileSystem.readDir(leaseDir);
@@ -20836,7 +20868,7 @@ function quarantineProfileSyncData(profileDir) {
20836
20868
  const syncData = join5(profileDir, "Default", "Sync Data");
20837
20869
  if (lstat(syncData) === null)
20838
20870
  return false;
20839
- return rename(syncData, `${syncData}.broken-${new Date().toISOString().replace(/[:.]/g, "").slice(0, 15)}`);
20871
+ return rename(syncData, `${syncData}.broken-${new Date().toISOString().replace(/[:.]/g, "").slice(0, 17)}`);
20840
20872
  }
20841
20873
  function createKkBrowserLauncher(loadPlaywright = () => import("playwright"), ownership, leaseOptions = {}) {
20842
20874
  return {
@@ -25389,6 +25421,30 @@ async function openWithState(profileDir, headless, url = CONSOLE_URL) {
25389
25421
  throw error;
25390
25422
  }
25391
25423
  }
25424
+ function cookieIdentity(cookie) {
25425
+ return `${cookie.domain ?? ""}\x00${cookie.path ?? "/"}\x00${cookie.name}`;
25426
+ }
25427
+ function isLiveCookie(cookie, nowMs) {
25428
+ return cookie.expires === undefined || cookie.expires <= 0 || cookie.expires * 1000 > nowMs;
25429
+ }
25430
+ function selectRestoreCookies(saved, profile, nowMs = Date.now()) {
25431
+ const live = new Set(profile.filter((cookie) => isLiveCookie(cookie, nowMs)).map(cookieIdentity));
25432
+ const inject = [];
25433
+ let shadowed = 0;
25434
+ let expired = 0;
25435
+ for (const cookie of saved) {
25436
+ if (!isLiveCookie(cookie, nowMs)) {
25437
+ expired += 1;
25438
+ continue;
25439
+ }
25440
+ if (live.has(cookieIdentity(cookie))) {
25441
+ shadowed += 1;
25442
+ continue;
25443
+ }
25444
+ inject.push(cookie);
25445
+ }
25446
+ return { inject, shadowed, expired };
25447
+ }
25392
25448
  async function restoreWechatSessionState(context, page, profileDir) {
25393
25449
  const stateFile = storageStatePath(profileDir);
25394
25450
  let state;
@@ -25401,7 +25457,13 @@ async function restoreWechatSessionState(context, page, profileDir) {
25401
25457
  if (!cookies || cookies.length === 0) {
25402
25458
  throw new BrowserProfileMissingError(`no saved console session state (${stateFile}) \u2014 run \`bun src/profile-check.ts login\` once`);
25403
25459
  }
25404
- await context.addCookies(cookies);
25460
+ const profileCookies = await context.cookies().catch(() => []);
25461
+ const selection = selectRestoreCookies(cookies, profileCookies);
25462
+ if (selection.shadowed > 0 || selection.expired > 0) {
25463
+ echoError(`wechatmp-pub: kept ${selection.shadowed} session cookie(s) from the profile itself and skipped ` + `${selection.expired} expired saved cookie(s) \u2014 the saved state is older than this profile`);
25464
+ }
25465
+ if (selection.inject.length > 0)
25466
+ await context.addCookies(selection.inject);
25405
25467
  for (const entry of state?.origins ?? []) {
25406
25468
  const items = entry.localStorage ?? [];
25407
25469
  if (entry.origin === undefined || entry.origin.length === 0 || items.length === 0)
@@ -25591,6 +25653,7 @@ export {
25591
25653
  processPublishIO,
25592
25654
  restoreWechatSessionState,
25593
25655
  runMode,
25656
+ selectRestoreCookies,
25594
25657
  storageStatePath,
25595
25658
  wechatBrowserLauncher,
25596
25659
  wechatSessionConfig,
@@ -20231,7 +20231,12 @@ async function acquireProfileLease(profileDir, options = {}) {
20231
20231
  const leaseDir = join2(leaseRoot, id);
20232
20232
  await fileSystem.ensureDir(leaseRoot);
20233
20233
  if (!mkdirExclusive(leaseDir, 448)) {
20234
- throw new BotError("busy", await busyGuidance(fileSystem, leaseDir));
20234
+ if (!await reclaimDeadOwnerLease(fileSystem, leaseDir)) {
20235
+ throw new BotError("busy", await busyGuidance(fileSystem, leaseDir));
20236
+ }
20237
+ if (!mkdirExclusive(leaseDir, 448)) {
20238
+ throw new BotError("busy", await busyGuidance(fileSystem, leaseDir));
20239
+ }
20235
20240
  }
20236
20241
  const token = randomBytes(16).toString("hex");
20237
20242
  const owner = {
@@ -20347,9 +20352,35 @@ async function busyGuidance(fileSystem, leaseDir) {
20347
20352
  }
20348
20353
  return `browser lease ${leaseDir} already exists with no owner record \u2014 a previous run may have crashed mid-acquire; confirm no kk browser still uses this profile, then remove ${leaseDir} manually`;
20349
20354
  }
20350
- const suffix = isProcessAlive(owner.pid) ? "confirm that process and any browser for this profile have stopped; stale ownership is never auto-removed" : `pid ${owner.pid} is no longer running \u2014 confirm no browser for this profile is open, then remove the stale lease with: rm -rf ${leaseDir}`;
20355
+ const live = isProcessAlive(owner.pid) ? [] : await liveChildHolders(fileSystem, leaseDir);
20356
+ const suffix = live.length > 0 ? `pid ${owner.pid} is gone but child holders ${live.join(", ")} are still running \u2014 stop those processes before retrying` : isProcessAlive(owner.pid) ? "confirm that process and any browser for this profile have stopped; stale ownership is never auto-removed" : `pid ${owner.pid} is no longer running and the lease could not be reclassified \u2014 confirm no browser for this profile is open, then remove the stale lease with: rm -rf ${leaseDir}`;
20351
20357
  return `browser lease ${leaseDir} is held by pid ${owner.pid} (logical ${owner.logicalPath}) \u2014 ${suffix}`;
20352
20358
  }
20359
+ async function reclaimDeadOwnerLease(fileSystem, leaseDir) {
20360
+ const owner = await readOwner(fileSystem, leaseDir);
20361
+ if (owner === null || isProcessAlive(owner.pid))
20362
+ return false;
20363
+ if ((await liveChildHolders(fileSystem, leaseDir)).length > 0)
20364
+ return false;
20365
+ const target = staleLeaseDir(leaseDir);
20366
+ try {
20367
+ rename(leaseDir, target);
20368
+ } catch {
20369
+ return false;
20370
+ }
20371
+ const moved = await readOwner(fileSystem, target);
20372
+ if (moved !== null && moved.token !== owner.token) {
20373
+ try {
20374
+ rename(target, leaseDir);
20375
+ } catch {}
20376
+ return false;
20377
+ }
20378
+ return true;
20379
+ }
20380
+ function staleLeaseDir(leaseDir) {
20381
+ const stamp = new Date().toISOString().replace(/[:.]/g, "").slice(0, 15);
20382
+ return `${leaseDir}.stale-${stamp}-${process.pid}-${randomBytes(3).toString("hex")}`;
20383
+ }
20353
20384
  async function holderResidue(fileSystem, leaseDir) {
20354
20385
  try {
20355
20386
  const entries = await fileSystem.readDir(leaseDir);
@@ -20497,7 +20528,7 @@ function quarantineProfileSyncData(profileDir) {
20497
20528
  const syncData = join5(profileDir, "Default", "Sync Data");
20498
20529
  if (lstat(syncData) === null)
20499
20530
  return false;
20500
- return rename(syncData, `${syncData}.broken-${new Date().toISOString().replace(/[:.]/g, "").slice(0, 15)}`);
20531
+ return rename(syncData, `${syncData}.broken-${new Date().toISOString().replace(/[:.]/g, "").slice(0, 17)}`);
20501
20532
  }
20502
20533
  function createKkBrowserLauncher(loadPlaywright = () => import("playwright"), ownership, leaseOptions = {}) {
20503
20534
  return {
@@ -21114,6 +21145,9 @@ if (false) {}
21114
21145
  var CJK_TERMINATORS = new Set(["\u3002", "\uFF01", "\uFF1F"]);
21115
21146
  var LATIN_TERMINATORS = new Set([".", "!", "?"]);
21116
21147
  var ATTACHED_CLOSERS = new Set(["\u201D", "\u2019", "\u300D", "\u300F", "\uFF09", ")", '"', "'"]);
21148
+ // ../../plugins/publishings/wechatmp-pub/src/index.ts
21149
+ init_dist();
21150
+
21117
21151
  // ../../plugins/publishings/wechatmp-pub/src/cgi.ts
21118
21152
  var MP_ORIGIN = "https://mp.weixin.qq.com";
21119
21153
  var FILETRANSFER_URL = `${MP_ORIGIN}/cgi-bin/filetransfer`;
@@ -21245,6 +21279,30 @@ async function openWithState(profileDir, headless, url = CONSOLE_URL) {
21245
21279
  throw error;
21246
21280
  }
21247
21281
  }
21282
+ function cookieIdentity(cookie) {
21283
+ return `${cookie.domain ?? ""}\x00${cookie.path ?? "/"}\x00${cookie.name}`;
21284
+ }
21285
+ function isLiveCookie(cookie, nowMs) {
21286
+ return cookie.expires === undefined || cookie.expires <= 0 || cookie.expires * 1000 > nowMs;
21287
+ }
21288
+ function selectRestoreCookies(saved, profile, nowMs = Date.now()) {
21289
+ const live = new Set(profile.filter((cookie) => isLiveCookie(cookie, nowMs)).map(cookieIdentity));
21290
+ const inject = [];
21291
+ let shadowed = 0;
21292
+ let expired = 0;
21293
+ for (const cookie of saved) {
21294
+ if (!isLiveCookie(cookie, nowMs)) {
21295
+ expired += 1;
21296
+ continue;
21297
+ }
21298
+ if (live.has(cookieIdentity(cookie))) {
21299
+ shadowed += 1;
21300
+ continue;
21301
+ }
21302
+ inject.push(cookie);
21303
+ }
21304
+ return { inject, shadowed, expired };
21305
+ }
21248
21306
  async function restoreWechatSessionState(context, page, profileDir) {
21249
21307
  const stateFile = storageStatePath(profileDir);
21250
21308
  let state;
@@ -21257,7 +21315,13 @@ async function restoreWechatSessionState(context, page, profileDir) {
21257
21315
  if (!cookies || cookies.length === 0) {
21258
21316
  throw new BrowserProfileMissingError(`no saved console session state (${stateFile}) \u2014 run \`bun src/profile-check.ts login\` once`);
21259
21317
  }
21260
- await context.addCookies(cookies);
21318
+ const profileCookies = await context.cookies().catch(() => []);
21319
+ const selection = selectRestoreCookies(cookies, profileCookies);
21320
+ if (selection.shadowed > 0 || selection.expired > 0) {
21321
+ echoError(`wechatmp-pub: kept ${selection.shadowed} session cookie(s) from the profile itself and skipped ` + `${selection.expired} expired saved cookie(s) \u2014 the saved state is older than this profile`);
21322
+ }
21323
+ if (selection.inject.length > 0)
21324
+ await context.addCookies(selection.inject);
21261
21325
  for (const entry of state?.origins ?? []) {
21262
21326
  const items = entry.localStorage ?? [];
21263
21327
  if (entry.origin === undefined || entry.origin.length === 0 || items.length === 0)
@@ -208,6 +208,56 @@ async function openWithState(
208
208
  }
209
209
  }
210
210
 
211
+ /**
212
+ * Identity of one cookie inside a browser store: the trio the browser itself keys on. Values are
213
+ * never compared, printed or returned — only used as the payload of an `addCookies` call.
214
+ */
215
+ function cookieIdentity(cookie: { name: string; domain?: string; path?: string }): string {
216
+ return `${cookie.domain ?? ''}\u0000${cookie.path ?? '/'}\u0000${cookie.name}`;
217
+ }
218
+
219
+ /** `true` while the browser would still send it (Playwright reports a session cookie as `expires: -1`). */
220
+ function isLiveCookie(cookie: { expires?: number }, nowMs: number): boolean {
221
+ return cookie.expires === undefined || cookie.expires <= 0 || cookie.expires * 1000 > nowMs;
222
+ }
223
+
224
+ /**
225
+ * What a restore may actually inject (0436 R2, AC2). The saved `storage-state.json` is a fallback
226
+ * for what the profile's own store LOST, never an override of what it still holds:
227
+ *
228
+ * 1. a saved cookie the profile still holds live is dropped — the 2026-11-24 measurement was
229
+ * exactly this shape (state dated 11-23 17:33, profile `wxuin` fresh from a 21:03 sign-in), and
230
+ * replaying the older snapshot over the live one is what made every later `check` refuse a
231
+ * session the browser actually had;
232
+ * 2. a saved cookie that has itself expired is dropped — it can only produce a signed-out console;
233
+ * 3. everything else is injected, which is the reason the file exists: mp.weixin.qq.com grant
234
+ * cookies do not survive a Chromium restart although the store keeps the session id.
235
+ *
236
+ * Counts come back so the operator gets one bounded line; names and values never do.
237
+ */
238
+ export function selectRestoreCookies(
239
+ saved: readonly Cookie[],
240
+ profile: readonly Cookie[],
241
+ nowMs: number = Date.now(),
242
+ ): { inject: Cookie[]; shadowed: number; expired: number } {
243
+ const live = new Set(profile.filter((cookie) => isLiveCookie(cookie, nowMs)).map(cookieIdentity));
244
+ const inject: Cookie[] = [];
245
+ let shadowed = 0;
246
+ let expired = 0;
247
+ for (const cookie of saved) {
248
+ if (!isLiveCookie(cookie, nowMs)) {
249
+ expired += 1;
250
+ continue;
251
+ }
252
+ if (live.has(cookieIdentity(cookie))) {
253
+ shadowed += 1;
254
+ continue;
255
+ }
256
+ inject.push(cookie);
257
+ }
258
+ return { inject, shadowed, expired };
259
+ }
260
+
211
261
  /**
212
262
  * Re-inject the durable login captured at login time onto a freshly launched context. A missing or
213
263
  * corrupt `storage-state.json` refuses with `BrowserProfileMissingError` — nothing is fabricated.
@@ -216,6 +266,10 @@ async function openWithState(
216
266
  * mp.weixin.qq.com (its `origins` half), and discarding it lands the console on its login page even
217
267
  * though every cookie was accepted — observed live 2026-10-05, where `check` reported OK while the
218
268
  * flow sat on a QR page. Replay each origin's storage before the caller navigates.
269
+ *
270
+ * 0436 R2: only the cookies {@link selectRestoreCookies} selects are replayed, so a state file older
271
+ * than the profile's own cookies can no longer mask a fresh console session. An unreadable jar is
272
+ * treated as empty — the saved state is then the only source, which is the pre-0436 behaviour.
219
273
  */
220
274
  export async function restoreWechatSessionState(
221
275
  context: BrowserContext,
@@ -237,7 +291,16 @@ export async function restoreWechatSessionState(
237
291
  `no saved console session state (${stateFile}) — run \`bun src/profile-check.ts login\` once`,
238
292
  );
239
293
  }
240
- await context.addCookies(cookies);
294
+ const profileCookies = await context.cookies().catch(() => [] as Cookie[]);
295
+ const selection = selectRestoreCookies(cookies, profileCookies);
296
+ if (selection.shadowed > 0 || selection.expired > 0) {
297
+ // Bounded and name-free: the operator sees WHY the snapshot was not replayed in full.
298
+ echoError(
299
+ `wechatmp-pub: kept ${selection.shadowed} session cookie(s) from the profile itself and skipped ` +
300
+ `${selection.expired} expired saved cookie(s) — the saved state is older than this profile`,
301
+ );
302
+ }
303
+ if (selection.inject.length > 0) await context.addCookies(selection.inject);
241
304
  for (const entry of state?.origins ?? []) {
242
305
  const items = entry.localStorage ?? [];
243
306
  if (entry.origin === undefined || entry.origin.length === 0 || items.length === 0) continue;