weflow-cli 1.8.2 → 1.10.0

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 (185) hide show
  1. package/ARCHITECTURE.md +62 -26
  2. package/CHANGELOG.md +1290 -0
  3. package/OPERATIONS.md +144 -11
  4. package/README.en.md +20 -4
  5. package/README.md +30 -5
  6. package/bin/weflow-cli-electron.cjs +2 -0
  7. package/bin/weflow-cli.ts +996 -118
  8. package/dist/bin/weflow-cli.js +1038 -146
  9. package/dist/bin/weflow-cli.js.map +1 -1
  10. package/dist/mcp-server/http.d.ts +14 -0
  11. package/dist/mcp-server/http.d.ts.map +1 -0
  12. package/dist/mcp-server/http.js +84 -0
  13. package/dist/mcp-server/http.js.map +1 -0
  14. package/dist/mcp-server/httpConfig.d.ts +50 -0
  15. package/dist/mcp-server/httpConfig.d.ts.map +1 -0
  16. package/dist/mcp-server/httpConfig.js +104 -0
  17. package/dist/mcp-server/httpConfig.js.map +1 -0
  18. package/dist/mcp-server/index.d.ts +13 -1
  19. package/dist/mcp-server/index.d.ts.map +1 -1
  20. package/dist/mcp-server/index.js +58 -374
  21. package/dist/mcp-server/index.js.map +1 -1
  22. package/dist/src/core/dbPathService.d.ts +12 -0
  23. package/dist/src/core/dbPathService.d.ts.map +1 -1
  24. package/dist/src/core/dbPathService.js +20 -3
  25. package/dist/src/core/dbPathService.js.map +1 -1
  26. package/dist/src/panel/server.d.ts.map +1 -1
  27. package/dist/src/panel/server.js +61 -1
  28. package/dist/src/panel/server.js.map +1 -1
  29. package/dist/src/services/assistantEval.d.ts +69 -0
  30. package/dist/src/services/assistantEval.d.ts.map +1 -1
  31. package/dist/src/services/assistantEval.js +270 -8
  32. package/dist/src/services/assistantEval.js.map +1 -1
  33. package/dist/src/services/assistantScenes.d.ts +81 -0
  34. package/dist/src/services/assistantScenes.d.ts.map +1 -0
  35. package/dist/src/services/assistantScenes.js +322 -0
  36. package/dist/src/services/assistantScenes.js.map +1 -0
  37. package/dist/src/services/assistantService.d.ts +33 -4
  38. package/dist/src/services/assistantService.d.ts.map +1 -1
  39. package/dist/src/services/assistantService.js +102 -6
  40. package/dist/src/services/assistantService.js.map +1 -1
  41. package/dist/src/services/assistantSkills.d.ts +94 -0
  42. package/dist/src/services/assistantSkills.d.ts.map +1 -0
  43. package/dist/src/services/assistantSkills.js +330 -0
  44. package/dist/src/services/assistantSkills.js.map +1 -0
  45. package/dist/src/services/assistantTools.d.ts +34 -1
  46. package/dist/src/services/assistantTools.d.ts.map +1 -1
  47. package/dist/src/services/assistantTools.js +931 -88
  48. package/dist/src/services/assistantTools.js.map +1 -1
  49. package/dist/src/services/assistantTrace.d.ts +4 -0
  50. package/dist/src/services/assistantTrace.d.ts.map +1 -1
  51. package/dist/src/services/assistantTrace.js +9 -0
  52. package/dist/src/services/assistantTrace.js.map +1 -1
  53. package/dist/src/services/configService.d.ts +9 -0
  54. package/dist/src/services/configService.d.ts.map +1 -1
  55. package/dist/src/services/configService.js +5 -2
  56. package/dist/src/services/configService.js.map +1 -1
  57. package/dist/src/services/messageQuery.d.ts +18 -0
  58. package/dist/src/services/messageQuery.d.ts.map +1 -1
  59. package/dist/src/services/messageQuery.js +29 -0
  60. package/dist/src/services/messageQuery.js.map +1 -1
  61. package/dist/src/services/outboundSend.d.ts +53 -0
  62. package/dist/src/services/outboundSend.d.ts.map +1 -0
  63. package/dist/src/services/outboundSend.js +90 -0
  64. package/dist/src/services/outboundSend.js.map +1 -0
  65. package/dist/src/services/pythonBridge.d.ts.map +1 -1
  66. package/dist/src/services/pythonBridge.js +1 -0
  67. package/dist/src/services/pythonBridge.js.map +1 -1
  68. package/dist/src/services/wechatClient.d.ts +125 -0
  69. package/dist/src/services/wechatClient.d.ts.map +1 -0
  70. package/dist/src/services/wechatClient.js +344 -0
  71. package/dist/src/services/wechatClient.js.map +1 -0
  72. package/dist/src/services/wechatMedia.d.ts +44 -0
  73. package/dist/src/services/wechatMedia.d.ts.map +1 -0
  74. package/dist/src/services/wechatMedia.js +155 -0
  75. package/dist/src/services/wechatMedia.js.map +1 -0
  76. package/dist/src/services/wechatMessageService.d.ts +11 -0
  77. package/dist/src/services/wechatMessageService.d.ts.map +1 -1
  78. package/dist/src/services/wechatMessageService.js +55 -11
  79. package/dist/src/services/wechatMessageService.js.map +1 -1
  80. package/dist/src/types.d.ts +4 -0
  81. package/dist/src/types.d.ts.map +1 -1
  82. package/dist/src/utils/python.js +2 -2
  83. package/dist/src/utils/python.js.map +1 -1
  84. package/docs/BRANCHES.md +37 -0
  85. package/docs/CONTACT_DB_SCHEMA.md +1085 -0
  86. package/docs/DECISIONS.md +1624 -0
  87. package/docs/EXTENDING.md +98 -10
  88. package/docs/FUNCTIONAL-IMPROVEMENT-SPEC.md +6 -0
  89. package/docs/HEALTH-CHECK.md +12 -7
  90. package/docs/JEV/345/272/224/347/224/250/346/226/275/345/267/245/346/226/207/346/241/243.md +2 -2
  91. package/docs/MCP.md +58 -4
  92. package/docs/PROJECT_STATE.md +180 -11
  93. package/docs/RELEASING.md +115 -1
  94. package/docs/images/weflow-architecture-gpt-image-2.png +0 -0
  95. package/logo.png +0 -0
  96. package/mcp-server/http.ts +108 -0
  97. package/mcp-server/httpConfig.ts +126 -0
  98. package/mcp-server/index.ts +359 -681
  99. package/package.json +5 -3
  100. package/resources/js/graph3d/NOTICE.txt +35 -0
  101. package/resources/js/graph3d/d3-binarytree.min.js +2 -0
  102. package/resources/js/graph3d/d3-dispatch.min.js +2 -0
  103. package/resources/js/graph3d/d3-force-3d.min.js +2 -0
  104. package/resources/js/graph3d/d3-octree.min.js +2 -0
  105. package/resources/js/graph3d/d3-quadtree.min.js +2 -0
  106. package/resources/js/graph3d/d3-timer.min.js +2 -0
  107. package/resources/js/graph3d/layout.mjs +63 -0
  108. package/resources/js/graph3d/three.min.js +6 -0
  109. package/resources/js/graph3d/viewer2d.js +448 -0
  110. package/resources/panel/ball-position.cjs +48 -2
  111. package/resources/panel/index.html +18 -4
  112. package/resources/panel/main.cjs +137 -5
  113. package/resources/panel/mascot-base.png +0 -0
  114. package/resources/panel/mascot-blink-1.png +0 -0
  115. package/resources/panel/mascot-blink-2.png +0 -0
  116. package/resources/panel/mascot-iris.png +0 -0
  117. package/resources/panel/mascot-lift-down-1.png +0 -0
  118. package/resources/panel/mascot-lift-down-2.png +0 -0
  119. package/resources/panel/mascot-lift-down-3.png +0 -0
  120. package/resources/panel/mascot-lift-down-4.png +0 -0
  121. package/resources/panel/mascot-lift-down-5.png +0 -0
  122. package/resources/panel/mascot-lift-down-6.png +0 -0
  123. package/resources/panel/mascot-lift-up-1.png +0 -0
  124. package/resources/panel/mascot-lift-up-2.png +0 -0
  125. package/resources/panel/mascot-lift-up-3.png +0 -0
  126. package/resources/panel/mascot-lift-up-4.png +0 -0
  127. package/resources/panel/mascot-lift-up-5.png +0 -0
  128. package/resources/panel/mascot-lift-up-6.png +0 -0
  129. package/resources/panel/mascot-peek.png +0 -0
  130. package/resources/panel/mascot-tickle-1.png +0 -0
  131. package/resources/panel/mascot-tickle-2.png +0 -0
  132. package/resources/panel/mascot-tickle-3.png +0 -0
  133. package/resources/panel/mascot-tickle-4.png +0 -0
  134. package/resources/panel/panel.css +205 -59
  135. package/resources/panel/preload.cjs +26 -0
  136. package/resources/panel/renderer.js +646 -17
  137. package/scripts/_utils.py +1203 -931
  138. package/scripts/backfill_articles.py +202 -21
  139. package/scripts/biz_daily.py +26 -34
  140. package/scripts/bonds.py +331 -0
  141. package/scripts/chat_notes.py +561 -470
  142. package/scripts/chat_stats.py +8 -7
  143. package/scripts/check_readme_commands.py +426 -0
  144. package/scripts/compile_wiki.py +187 -59
  145. package/scripts/contact_schema.py +339 -0
  146. package/scripts/data/wechat_emoji.json +225 -0
  147. package/scripts/export_chat_html.py +3 -1
  148. package/scripts/fav_notes.py +4 -1
  149. package/scripts/graph_2d.py +151 -0
  150. package/scripts/graph_3d.py +646 -0
  151. package/scripts/health_check.py +163 -26
  152. package/scripts/mcp_bridge.py +6 -7
  153. package/scripts/nt_decrypt.py +3 -3
  154. package/scripts/panel_frames.py +683 -0
  155. package/scripts/pipeline.py +21 -10
  156. package/scripts/quality_eval.py +5 -0
  157. package/scripts/rag_chat.py +33 -16
  158. package/scripts/reply_debt.py +26 -6
  159. package/scripts/semantic_search.py +130 -22
  160. package/scripts/vault_rag.py +42 -16
  161. package/scripts/vault_search.py +44 -8
  162. package/scripts/wechat_emoticon.py +6 -0
  163. package/scripts/wechat_voice.py +9 -0
  164. package/scripts/wiki_lint.py +124 -24
  165. package/src/core/dbPathService.ts +22 -4
  166. package/src/panel/server.ts +58 -1
  167. package/src/services/assistantEval.ts +323 -12
  168. package/src/services/assistantScenes.ts +342 -0
  169. package/src/services/assistantService.ts +107 -6
  170. package/src/services/assistantSkills.ts +364 -0
  171. package/src/services/assistantTools.ts +2452 -1640
  172. package/src/services/assistantTrace.ts +9 -0
  173. package/src/services/configService.ts +415 -403
  174. package/src/services/messageQuery.ts +29 -0
  175. package/src/services/outboundSend.ts +126 -0
  176. package/src/services/pythonBridge.ts +1 -0
  177. package/src/services/wechatClient.ts +380 -0
  178. package/src/services/wechatMedia.ts +166 -0
  179. package/src/services/wechatMessageService.ts +62 -11
  180. package/src/types.ts +4 -0
  181. package/src/utils/python.ts +2 -2
  182. package/dist/src/utils/wechatEmoji.d.ts +0 -5
  183. package/dist/src/utils/wechatEmoji.d.ts.map +0 -1
  184. package/dist/src/utils/wechatEmoji.js +0 -35
  185. package/dist/src/utils/wechatEmoji.js.map +0 -1
package/bin/weflow-cli.ts CHANGED
@@ -12,6 +12,7 @@ import { keyService } from '../src/core/keyService.js'
12
12
  import { NtCore } from '../src/core/ntCore.js'
13
13
  import { configService } from '../src/services/configService.js'
14
14
  import { chatService } from '../src/services/chatService.js'
15
+ import { emptyMessagesNote, looksLikeTalkerId } from '../src/services/messageQuery.js'
15
16
  import { exportService } from '../src/services/exportService.js'
16
17
  import { writeEvidencePackage } from '../src/services/evidenceService.js'
17
18
  import { resolveTalker as resolveTalkerCore } from '../src/utils/talkerUtils.js'
@@ -21,8 +22,12 @@ import { DateRangeError, parseLocalDateOrIso, resolveExportDateRange } from '../
21
22
  import { resolvePackageRoot as resolvePackageRootFrom } from '../src/utils/packageRoot.js'
22
23
  import { WechatMessageService } from '../src/services/wechatMessageService.js'
23
24
  import { whitelistService, MAX_TEXT_LENGTH } from '../src/services/whitelistService.js'
25
+ import { authorizeOutbound, parseOutboundPolicy, performOutbound } from '../src/services/outboundSend.js'
24
26
  import { applyDerivedNtKeys, enableFavorites, detectFavDbPath } from '../src/services/initKeyService.js'
25
27
  import type { ChatSession } from '../src/types.js'
28
+ import { disabledIds, describeSkill, readSkillBody, scanSkills, skillRoots, skillState } from '../src/services/assistantSkills.js'
29
+ import { assistantScenes, validateSceneId, type Scene } from '../src/services/assistantScenes.js'
30
+ import { detectWechatClient, reportedDataDirs, samePath } from '../src/services/wechatClient.js'
26
31
 
27
32
  const program = new Command()
28
33
 
@@ -63,6 +68,22 @@ function parseCliInteger(value: unknown, field: string, minimum: number, maximum
63
68
  process.exit(1)
64
69
  }
65
70
 
71
+ /** 校验一个"只能是这几个值之一"的参数。与 `parseCliInteger` / `requireCliDate` 同一约定:
72
+ * `--json` 时错误也得是一份 JSON —— 否则机器调用方在 stdout 上拿到的是彩色散文,解析不了。
73
+ *
74
+ * 抽成一个是有理由的:`--line` 的校验原本在四个命令里各写了一遍,其中三处只打散文(`vault rag`、
75
+ * 顶层 `search`、`chat`)—— 同一份判断写四遍,就有三遍漏掉了 `--json` 分支。
76
+ * 错误文案由 choices 生成,保证与原来逐字一致('line 必须是 wiki、chat 或 all')。
77
+ */
78
+ function requireCliChoice(value: unknown, choices: readonly string[], field: string, json = false): string {
79
+ const text = String(value)
80
+ if (choices.includes(text)) return text
81
+ const error = `${field} 必须是 ${choices.slice(0, -1).join('、')} 或 ${choices[choices.length - 1]}`
82
+ if (json) console.log(JSON.stringify({ success: false, code: 'INVALID_ARGUMENT', field, error }))
83
+ else console.log(chalk.red(error))
84
+ process.exit(1)
85
+ }
86
+
66
87
  function requireCliDate(value: string, json = false): string {
67
88
  try {
68
89
  parseLocalDateOrIso(value)
@@ -282,7 +303,7 @@ program
282
303
  read: {
283
304
  sessions: { cli: 'sessions --json', mcp: 'wechat.list_sessions' },
284
305
  messages: { cli: 'messages <talker> --json', mcp: 'wechat.export_messages' },
285
- contacts: { cli: 'contacts --json' },
306
+ contacts: { cli: 'contacts --json', mcp: 'wechat.list_contacts', localIdentifiersInModelContext: false },
286
307
  exports: {
287
308
  cli: 'export <talker> <json|txt|html|excel>',
288
309
  mcp: 'wechat.export_messages',
@@ -316,8 +337,36 @@ program
316
337
  },
317
338
  dailyReader: { cli: 'daily-server --status --json' },
318
339
  dailyStats: { cli: 'daily-stats --json' },
340
+ // 只读、纯本地、不调模型。**故意没有 mcp 那一栏**(D-062):它给的是关于第三方的推断
341
+ // ——谁在被冷落、你会失去谁 —— 所以不进助手、不进 MCP、不喂模型。
342
+ bonds: { cli: 'bonds --json', mcp: null, leavesTheMachine: false },
319
343
  diagnostics: { cli: 'check --json' },
320
344
  todos: { cli: 'todos list --json' },
345
+ // 2026-09-29 三个界面对齐时新开的读取能力(D-058)。逐个写清它会不会出境,
346
+ // 因为其中两个会——`fetch_article` 白名单 + 逐跳复检,`search_public` 没有任何守卫。
347
+ review: { cli: 'review ...', mcp: 'wechat.get_review', writesReport: true },
348
+ concepts: { cli: 'wiki ...', mcp: 'wechat.get_concepts' },
349
+ articleFetch: {
350
+ cli: null, // 没有对应的 CLI 命令:它本来就是为模型准备的读取能力
351
+ mcp: 'wechat.fetch_article',
352
+ network: true,
353
+ allowlist: 'https only, host must be exactly mp.weixin.qq.com',
354
+ redirectsReValidatedPerHop: true,
355
+ confirmationRequired: false,
356
+ },
357
+ publicArticleSearch: {
358
+ mcp: 'wechat.search_public',
359
+ network: true,
360
+ // **这条是如实的**:搜索词由模型决定、发到第三方搜索页,没有白名单也没有预览。
361
+ // 它在该项目的边界内是被明确接受的残余风险(D-058),这里不能写成"无出境"。
362
+ allowlist: null,
363
+ modelAuthoredQueryLeavesTheMachine: true,
364
+ confirmationRequired: false,
365
+ },
366
+ articleFormatting: { mcp: 'wechat.format_article', cli: null, writesNothing: true, network: false },
367
+ themes: { mcp: 'wechat.list_themes', writesNothing: true },
368
+ wikiLint: { cli: 'wiki lint --json', mcp: 'wechat.lint_wiki', readsLocalChat: false, writesNothing: true },
369
+ skillCheck: { cli: 'skill check --json', mcp: 'wechat.check_skills', writesNothing: true },
321
370
  awaiting: {
322
371
  cli: 'awaiting --yes',
323
372
  preview: 'awaiting --dry-run --json',
@@ -400,6 +449,33 @@ program
400
449
  execute: 'todos <done|undone|rm> <id> --yes --json',
401
450
  confirmationRequired: true,
402
451
  },
452
+ skills: {
453
+ list: 'skill list [--query <q>] --json',
454
+ show: 'skill show <id> --json',
455
+ check: 'skill check --json',
456
+ readOnly: true,
457
+ // 技能是**资料**,不是插件:助手只把它当提示词/正文读,不执行里面的脚本,
458
+ // 也不因为装了技能就多出任何工具(P4 验收标准:扩展读不到配置与数据库)。
459
+ installsAnything: false,
460
+ executesSkillCode: false,
461
+ grantsTools: false,
462
+ directories: 'skillDirs config (default: ~/.claude/skills, ~/.weflow-cli/skills)',
463
+ disable: 'config set skillDisabled <id,...>(技能自己也能写 enabled: false)',
464
+ },
465
+ scenes: {
466
+ list: 'scene list --json',
467
+ show: 'scene show <id> --json',
468
+ preview: 'scene <add|remove|enable|disable|bind|unbind> … --dry-run --json',
469
+ execute: 'scene <add|remove|enable|disable|bind|unbind> … --yes --json',
470
+ confirmationRequired: true,
471
+ // 场景只改**本机提示词预设**,不发消息、不读聊天、不调模型
472
+ readsLocalChat: false,
473
+ invokesAI: false,
474
+ sendsNothing: true,
475
+ stateLocation: 'local-user-config-dir',
476
+ stateSchema: 'weflow-scenes/v1',
477
+ modelWritable: false,
478
+ },
403
479
  accessControlMutations: {
404
480
  preview: '<whitelist|blacklist> <add|rm> <target> --dry-run --json',
405
481
  execute: '<whitelist|blacklist> <add|rm> <target> --yes --json',
@@ -571,9 +647,11 @@ program
571
647
  // 读这一位的调用方按 false 走保守分支即可。
572
648
  mcpDefaultReadOnly: false,
573
649
  mcpSurface: {
574
- // 原文只写了 "minus save_memory" —— 而那张表也排除了 `look_at_image`(MCP 只取文本,
575
- // 它挂进侧信道的图没人接)。机器可读字段少说一句同样算不准,如实写全。
576
- derivedFrom: 'assistant tools minus save_memory and look_at_image',
650
+ // 这句话**手工补过两回**:先是只写 save_memory,后来补上 `look_at_image`,第三次加
651
+ // `set_todo_status` 时又漏了 —— 每次都是"表变了、这句话没变",而且没有任何东西会红。
652
+ // 现在名字**逐个与 `MCP_EXCLUDED` 对齐**,并由 `test/assistant-tools.test.ts` 从源码里核:
653
+ // 那张表再加一项而这里没跟,测试就红(同下面 requiresConfirm 的处理方式)。
654
+ derivedFrom: 'assistant tools minus save_memory, look_at_image and set_todo_status',
577
655
  writesFiles: ['export_chat'],
578
656
  // 逐个核实过(脚本里确实调云端模型的那些):
579
657
  // who_owes_reply/search_chats → Jev;search_semantic → 阿里云百炼嵌入 + Jev 重排;draft_reply → Jev + DeepSeek。
@@ -725,8 +803,13 @@ program
725
803
  console.log(chalk.gray(' 目录名未命中时将继续进行深度结构扫描,过程可能需要较长时间...'))
726
804
  }
727
805
  const detected = configuredDataRoot
728
- ? { success: true, path: configuredDataRoot }
729
- : await dbPathService.autoDetect({ searchDrives: opts.searchDrives, fullScan: opts.fullScan })
806
+ ? { success: true, path: configuredDataRoot, source: 'known' as const }
807
+ : await dbPathService.autoDetect({
808
+ searchDrives: opts.searchDrives, fullScan: opts.fullScan,
809
+ // **先问客户端自己**(它命令行上带着 `--wechat-files-path`):这是唯一"来自
810
+ // 客户端自己"的来源,其余都是按目录名猜。取不到就是空数组,走老路。
811
+ hintedRoots: await reportedDataDirs(),
812
+ })
730
813
  if (!detected.success || !detected.path) {
731
814
  console.log(chalk.red('✗ 未检测到微信数据目录'))
732
815
  if (!opts.searchDrives && !opts.fullScan) {
@@ -744,7 +827,10 @@ program
744
827
  }
745
828
  process.exit(1)
746
829
  }
747
- console.log(chalk.green(`✓ 检测到数据目录: ${detected.path}`))
830
+ // **说清是怎么找到的**:来源不同,可信度与后续排查都不同("客户端自己说的"最硬)
831
+ const howFound = detected.source === 'client' ? '(客户端自己报的)'
832
+ : detected.source === 'scan' ? '(全盘扫描找到的)' : ''
833
+ console.log(chalk.green(`✓ 检测到数据目录: ${detected.path}${howFound}`))
748
834
  configService.set('dbPath', detected.path)
749
835
  configService.set('dataVersion', '4.x')
750
836
 
@@ -1011,8 +1097,10 @@ const configurableKeys = [
1011
1097
  'wereadApiKey',
1012
1098
  'assistantPrivacy', 'assistantWhitelist', 'assistantGroupWhitelist',
1013
1099
  'assistantGroupRequireMention', 'assistantFastRoute', 'assistantPanelUser', 'quickReplyContacts',
1100
+ 'skillDirs', 'skillDisabled',
1014
1101
  'dailySources', 'dailySourceCategories',
1015
1102
  'dailyExcludeTopics', 'dailyAiEnabled',
1103
+ 'wechatMediaDownload',
1016
1104
  'emoticonSeed',
1017
1105
  ] as const
1018
1106
 
@@ -1310,8 +1398,25 @@ program
1310
1398
  : await chatService.getMessages(talker, limit, offset)
1311
1399
 
1312
1400
  if (messages.length === 0) {
1313
- if (opts.json) { console.log(JSON.stringify({ success: true, talker, messages: [] })); return }
1401
+ // 拼错的 ID 会被 resolveTalker 原样放行 ⇒ 取不到消息。这里补一句话把两种情况分开,
1402
+ // 但**不改退出码、也不改 success**("没有消息"不是错误,脚本与 MCP 依赖这一点)。
1403
+ let note = ''
1404
+ if (looksLikeTalkerId(talkerInput)) {
1405
+ const [sessions, contacts] = await Promise.all([
1406
+ chatService.listSessions(talkerInput, 5),
1407
+ chatService.listContacts(talkerInput, 5),
1408
+ ])
1409
+ note = emptyMessagesNote(talkerInput, {
1410
+ sessionUsernames: sessions.map(s => s.username),
1411
+ contactUsernames: contacts.map(c => c.username),
1412
+ })
1413
+ }
1414
+ if (opts.json) {
1415
+ console.log(JSON.stringify({ success: true, talker, messages: [], ...(note ? { note } : {}) }))
1416
+ return
1417
+ }
1314
1418
  console.log(chalk.gray('未找到消息'))
1419
+ if (note) console.log(chalk.yellow(note))
1315
1420
  return
1316
1421
  }
1317
1422
 
@@ -1620,6 +1725,51 @@ syncCmd
1620
1725
  })
1621
1726
 
1622
1727
  // ==================== contacts ====================
1728
+ // contact-schema:读 contact.db 里**群**的 ext_buffer(本地只读:不联网、不调模型)
1729
+ //
1730
+ // 只解**实测验证过**的那几个字段(成员 userName/displayName/status/inviter + `#5`);
1731
+ // `#5` 曾经叫"附加参与者 id",实测是**成员 status 位 11 置位的那批 id**(本机 77/77 集合相等),
1732
+ // 所以输出改用 `statusBit11Ids`、不再说"额外参与者"(见 D-070)。
1733
+ // 顶层 `#3`/`#4` 的语义在本机被三次证伪(不是成员 id / 房间 id / 消息侧 id),所以脚本把它们
1734
+ // 原样放进 `unrecognized`,**不猜名字** —— 拿猜出来的名字写逻辑,就是拿不确定当事实。
1735
+ // 结构笔记见 `docs/CONTACT_DB_SCHEMA.md`,取舍见 D-067 / D-068 / D-070。
1736
+ //
1737
+ // `--contacts`(2026-10-07 加):同一个命令改读**联系人**的 `contact.extra_buffer`,输出这一轮验证的
1738
+ // 三个字段 —— `#5` 国家/地区码(ISO 3166-1 alpha-2)、`#13` = 该行 `biz_info.type`、`#41` = 资料最近更新时间。
1739
+ // `#4`/`#9` 已定性为"账号自身资料文本的汇集",是**内容**不是字段名,**故意不打印**(见 D-088)。
1740
+ program
1741
+ .command('contact-schema')
1742
+ .description('读 contact.db 的 ext_buffer:默认读群(成员 + #5);--contacts 读联系人(#5 地区码 / #13 服务类型 / #41 更新时间)—— 只解已验证字段,未识别的原样标注(本地、只读)')
1743
+ .option('-n, --limit <n>', '最多看几个(群 / 联系人)', '20')
1744
+ .option('--room <which>', '只看某个(群 / 联系人 的 username 或 id)')
1745
+ .option('--contacts', '改读联系人的 extra_buffer,而不是群')
1746
+ .option('--json', '输出机器可读结果')
1747
+ .action(async (opts) => {
1748
+ const { execFile } = await import('child_process')
1749
+ const { promisify } = await import('util')
1750
+ const execFileAsync = promisify(execFile)
1751
+ const script = join(resolvePackageRoot(), 'scripts', 'contact_schema.py')
1752
+ const limit = parseCliInteger(opts.limit, 'limit', 1, 100000, !!opts.json)
1753
+ const args = [script, '--limit', String(limit),
1754
+ ...(opts.room ? ['--room', opts.room] : []),
1755
+ ...(opts.contacts ? ['--contacts'] : []),
1756
+ ...(opts.json ? ['--json'] : [])]
1757
+ try {
1758
+ const { stdout, stderr } = await execFileAsync(getPythonCommand(), args, {
1759
+ timeout: 300_000, maxBuffer: 64 * 1024 * 1024, env: pythonProcessEnv(),
1760
+ })
1761
+ process.stdout.write(stdout)
1762
+ if (stderr && !opts.json) process.stderr.write(stderr)
1763
+ } catch (error) {
1764
+ if (opts.json) {
1765
+ console.log(JSON.stringify({ success: false, code: 'CONTACT_SCHEMA_FAILED', action: 'contact-schema', error: safeSubprocessError(error) }))
1766
+ } else {
1767
+ console.error(chalk.red(`\n✗ ${safeSubprocessError(error)}`))
1768
+ }
1769
+ process.exit(1)
1770
+ }
1771
+ })
1772
+
1623
1773
  program
1624
1774
  .command('contacts')
1625
1775
  .description('查看联系人列表')
@@ -1968,7 +2118,10 @@ program
1968
2118
  process.exit(1)
1969
2119
  }
1970
2120
  } else {
1971
- const timeout = parseCliInteger(opts.timeout, 'timeout', 1000, 600000)
2121
+ // `opts.json` 也要传:这一行在 `--json` 下**不可达**(上面就 `INTERACTIVE_REQUIRED` 退出了),
2122
+ // 但少传一个是安静的 —— 规则统一成"校验 helper 一律带上它",判据才写得出来
2123
+ // (`test/json-error-surface.test.ts` 末尾那条静态检查)。
2124
+ const timeout = parseCliInteger(opts.timeout, 'timeout', 1000, 600000, opts.json)
1972
2125
  const result = await keyService.autoGetDbKey(timeout, (msg) => {
1973
2126
  console.log(chalk.gray(` ${msg}`))
1974
2127
  })
@@ -2191,7 +2344,7 @@ whitelistCmd
2191
2344
  wxid = target
2192
2345
  } else {
2193
2346
  try {
2194
- wxid = await resolveTalker(target)
2347
+ wxid = await resolveTalker(target, !!opts.json, !!opts.json)
2195
2348
  const sessions = await chatService.listSessions(undefined, 50)
2196
2349
  const match = sessions.find(s => s.username === wxid)
2197
2350
  if (match) displayName = match.displayName || target
@@ -2378,7 +2531,7 @@ blacklistCmd
2378
2531
  wxid = target
2379
2532
  } else {
2380
2533
  try {
2381
- wxid = await resolveTalker(target)
2534
+ wxid = await resolveTalker(target, !!opts.json, !!opts.json)
2382
2535
  const sessions = await chatService.listSessions(undefined, 50)
2383
2536
  const match = sessions.find(s => s.username === wxid)
2384
2537
  if (match) displayName = match.displayName || target
@@ -3237,54 +3390,45 @@ program
3237
3390
  process.exit(1)
3238
3391
  }
3239
3392
 
3240
- // 黑名单优先拦截
3241
- if (whitelistService.isBlocked(wxid)) {
3242
- if (opts.json) console.log(JSON.stringify({ success: false, code: 'TARGET_BLOCKED', error: '目标在黑名单中', target: { wxid, displayName } }))
3243
- else {
3393
+ // 三道闸(黑名单 → 白名单 → 限速)与"每次尝试都写审计"在 `src/services/outboundSend.ts`
3394
+ // 里**只有一份**,因为 2026-10-01 起有了第二条发送路(`draft --pick N --send`,见 D-063)。
3395
+ // 两份写同一件事,分叉的后果具体是"某一条路绕过了白名单"。
3396
+ const policy = parseOutboundPolicy(Number(opts.rateWindow), Number(opts.rateMax))
3397
+ if ('code' in policy) {
3398
+ if (opts.json) console.log(JSON.stringify({ success: false, code: policy.code, error: policy.error }))
3399
+ else console.log(chalk.red('速率参数无效:rate-window 必须为 1000-3600000,rate-max 必须为 1-100'))
3400
+ process.exit(1)
3401
+ }
3402
+ const attempt = {
3403
+ wxid, displayName, kind, preview, text: message,
3404
+ mediaPath: kind === 'text' ? undefined : String(opts.image || opts.file),
3405
+ }
3406
+ const decision = authorizeOutbound(attempt, policy)
3407
+ if (!decision.ok) {
3408
+ const { refusal } = decision
3409
+ if (opts.json) {
3410
+ console.log(JSON.stringify({
3411
+ success: false, code: refusal.code, error: refusal.error,
3412
+ ...(refusal.code === 'TARGET_BLOCKED' || refusal.code === 'TARGET_NOT_ALLOWED'
3413
+ ? { target: { wxid, displayName } } : {}),
3414
+ ...(refusal.rateLimit ? { rateLimit: refusal.rateLimit } : {}),
3415
+ }))
3416
+ } else if (refusal.code === 'TARGET_BLOCKED') {
3244
3417
  console.log(chalk.red('\n❌ 目标在黑名单中,绝对禁止发送'))
3245
3418
  console.log(chalk.gray(` wxid: ${wxid}`))
3246
3419
  console.log(chalk.gray(` 解除: weflow-cli blacklist rm ${wxid}\n`))
3247
- }
3248
- whitelistService.auditSend({
3249
- timestamp: Date.now(), action: 'send', targetWxid: wxid, targetName: displayName,
3250
- kind, success: false, preview, error: 'blocked by blacklist',
3251
- })
3252
- process.exit(1)
3253
- }
3254
-
3255
- // Whitelist check
3256
- if (!whitelistService.isAllowed(wxid)) {
3257
- if (opts.json) console.log(JSON.stringify({ success: false, code: 'TARGET_NOT_ALLOWED', error: '目标不在白名单中', target: { wxid, displayName } }))
3258
- else {
3420
+ } else if (refusal.code === 'TARGET_NOT_ALLOWED') {
3259
3421
  console.log(chalk.red('\n❌ 目标不在白名单中,拒绝发送'))
3260
3422
  console.log(chalk.gray(` 先运行: weflow-cli whitelist add ${target}`))
3261
3423
  console.log(chalk.gray(` 查看名单: weflow-cli whitelist\n`))
3262
- }
3263
- process.exit(1)
3264
- }
3265
-
3266
- // 速率限制 (dry-run 不计入, 不检查也行, 但保持一致检查)
3267
- const windowMs = Number(opts.rateWindow)
3268
- const max = Number(opts.rateMax)
3269
- if (!Number.isInteger(windowMs) || windowMs < 1000 || windowMs > 3_600_000 ||
3270
- !Number.isInteger(max) || max < 1 || max > 100) {
3271
- if (opts.json) console.log(JSON.stringify({ success: false, code: 'INVALID_RATE_LIMIT', error: 'rate-window 必须为 1000-3600000,rate-max 必须为 1-100' }))
3272
- else console.log(chalk.red('速率参数无效:rate-window 必须为 1000-3600000,rate-max 必须为 1-100'))
3273
- process.exit(1)
3274
- }
3275
- const rate = whitelistService.checkRateLimit(windowMs, max)
3276
- if (!rate.allowed) {
3277
- if (opts.json) console.log(JSON.stringify({ success: false, code: 'RATE_LIMITED', error: '触发发送速率限制', rateLimit: rate }))
3278
- else {
3424
+ } else {
3425
+ const rate = refusal.rateLimit!
3279
3426
  console.log(chalk.red(`\n❌ 触发速率限制: 最近 ${rate.windowMs / 1000}s 内已发送 ${rate.count} 条 (上限 ${rate.max})`))
3280
3427
  console.log(chalk.gray(' 请稍后再试, 或调整 --rate-window / --rate-max\n'))
3281
3428
  }
3282
- whitelistService.auditSend({
3283
- timestamp: Date.now(), action: 'send', targetWxid: wxid, targetName: displayName,
3284
- kind, success: false, preview, error: `rate limited (${rate.count}/${rate.max})`,
3285
- })
3286
3429
  process.exit(1)
3287
3430
  }
3431
+ const rate = decision.rate
3288
3432
 
3289
3433
  // 二次确认 — 同时显示 wxid + displayName + 消息预览
3290
3434
  const actionPreview = {
@@ -3338,41 +3482,8 @@ program
3338
3482
  process.exit(1)
3339
3483
  }
3340
3484
 
3341
- const service = new WechatMessageService({ token })
3342
-
3343
- let success = false
3344
- let errorMsg: string | undefined
3345
- try {
3346
- if (opts.image) {
3347
- success = await service.sendImage(wxid, opts.image)
3348
- } else if (opts.file) {
3349
- success = await service.sendFile(wxid, opts.file)
3350
- } else {
3351
- success = await service.sendText(wxid, message)
3352
- }
3353
- } catch {
3354
- errorMsg = '消息通道调用失败'
3355
- }
3356
-
3357
- if (!success && !errorMsg) {
3358
- // 检查是否因缺少 context_token
3359
- const hasToken = !!(configService.getContextTokens()[wxid])
3360
- errorMsg = hasToken
3361
- ? '发送失败 (接口返回错误, 可能 token 过期)'
3362
- : '缺少 context_token — 需先收到对方一条消息 (或运行 weflow-cli listen 等待对方消息)'
3363
- }
3364
-
3365
- // 审计日志
3366
- whitelistService.auditSend({
3367
- timestamp: Date.now(),
3368
- action: 'send',
3369
- targetWxid: wxid,
3370
- targetName: displayName,
3371
- kind,
3372
- success,
3373
- preview,
3374
- error: success ? undefined : errorMsg,
3375
- })
3485
+ // 真的发 + 按结果写审计,都在共享模块里(与 `draft --send` 同一份)
3486
+ const { success, error: errorMsg } = await performOutbound(attempt)
3376
3487
 
3377
3488
  if (success) {
3378
3489
  if (opts.json) console.log(JSON.stringify({ success: true, ...actionPreview }))
@@ -3792,6 +3903,8 @@ program
3792
3903
  .option('--api-key <key>', 'DeepSeek API key')
3793
3904
  .option('--refresh-sources',
3794
3905
  '只把已有概念页的"来源"段补齐成当前全部来源(本地重写,**不调用模型**)')
3906
+ .option('--qualify-links',
3907
+ '把跨线同名的概念链接改成带路径的形式(本地重写,**不调用模型**)')
3795
3908
  .option('--cards <dir...>', '产卡目录,可写多个;默认所有 output/*-notes(与索引的引用数同一口径)')
3796
3909
  .option('--dry-run', '仅预览,不读取文章、调用 AI 或写入概念页')
3797
3910
  .option('--yes', '确认调用 AI 并生成概念页')
@@ -3817,6 +3930,22 @@ program
3817
3930
  return
3818
3931
  }
3819
3932
 
3933
+ if (opts.qualifyLinks) {
3934
+ // 本地消歧:两条线同名的那些链接按名字带路径(`Chat/Concepts/DeepSeek|DeepSeek`),
3935
+ // 免得 Obsidian 里那条裸链接命中另一条线的那张。**不调模型**,重跑幂等。
3936
+ await runConfirmedPythonMutation({
3937
+ action: 'wiki.qualifyLinks',
3938
+ script,
3939
+ args: ['--qualify-links', '--output', opts.output],
3940
+ cliOptions: opts,
3941
+ preview: { readsLocalKnowledge: true, rewritesExistingPages: true, usesAi: false },
3942
+ confirmationMessage: `确认把 ${opts.output} 里跨线同名的概念链接改成带路径的形式?`
3943
+ + '(本地重写,不调用 AI)',
3944
+ apiKey: opts.apiKey,
3945
+ timeout: 300_000,
3946
+ })
3947
+ return
3948
+ }
3820
3949
  const limit = parseCliInteger(opts.limit, 'limit', 1, 1000, opts.json)
3821
3950
  const minRefs = parseCliInteger(opts.minRefs ?? '1', 'min-refs', 1, 50, opts.json)
3822
3951
  await runConfirmedPythonMutation({
@@ -3847,8 +3976,9 @@ program
3847
3976
  .option('--wiki-limit <n>', '概念编译数', '20')
3848
3977
  .option('--source <name>', '仅处理指定公众号,可重复使用', (value: string, previous: string[]) => [...previous, value], [] as string[])
3849
3978
  .option('--skip-classify', '跳过 AI 后处理')
3850
- .option('--skip-wiki', '跳过概念编译')
3851
- .option('--skip-vault', '跳过 Vault 副本同步')
3979
+ // 这两个**默认不做**:Obsidian 自带的图谱视图是实时的,写一次 vault 图谱就重画一次。
3980
+ .option('--with-wiki', '把概念页写进 Obsidian Vault(默认不写:图谱只在你说了才变)')
3981
+ .option('--with-vault', '把当天内容副本同步进 Obsidian Vault(默认不写)')
3852
3982
  .option('--skip-html', '跳过 HTML 阅读器生成')
3853
3983
  .option('--skip-ai-report', '跳过 AI 深度阅读报告')
3854
3984
  .option('--no-ai', '关闭全部 AI 调用,保留抓取和本地输出')
@@ -3930,8 +4060,8 @@ program
3930
4060
  if (opts.date) args.push('--date', opts.date)
3931
4061
  for (const source of sources) args.push('--source', source)
3932
4062
  if (opts.skipClassify) args.push('--skip-classify')
3933
- if (opts.skipWiki) args.push('--skip-wiki')
3934
- if (opts.skipVault) args.push('--skip-vault')
4063
+ if (opts.withWiki) args.push('--with-wiki')
4064
+ if (opts.withVault) args.push('--with-vault')
3935
4065
  if (opts.skipHtml) args.push('--skip-html')
3936
4066
  if (opts.skipAiReport) args.push('--skip-ai-report')
3937
4067
  if (noAi) args.push('--no-ai')
@@ -4167,16 +4297,30 @@ program
4167
4297
  .description('Vault 搜索 — 文章+概念+笔记')
4168
4298
  .argument('<query>', '搜索关键词')
4169
4299
  .option('--type <type>', 'all / article / concept / note', 'all')
4300
+ .option('--line <line>', 'wiki=文章线(默认) / chat=聊天线 / all=两条都搜', 'wiki')
4170
4301
  .option('--top-k <n>', '返回数量', '10')
4302
+ // `vault_search.py` 一直有 `--days`(它的 docstring 自己就举 `--days 30`),CLI 从来没接 ——
4303
+ // 于是"只搜最近一周"这件事在这条路上做不到,窗口被脚本默认值(90)钉死。与 `search-index --days`
4304
+ // 同形:窗口的运行值由 CLI 说了算,默认值与脚本一致。
4305
+ .option('--days <n>', '日报文章取最近多少天(默认 90)', '90')
4306
+ // 这条 `--json` 曾经**不存在,而 JSON 又是唯一的输出**:参数里硬编码着 `'--json'`,
4307
+ // 人类模式虽然脚本里写着(`vault_search.py` 不带 `--json` 时打印带相关度的可读列表)
4308
+ // 却没有任何入口能到达,用户显式敲 `--json` 还会拿到 `unknown option` —— 与
4309
+ // `docs/EXTENDING.md` 那条"脚本或 AI 会驱动的命令都有 `--json` 模式"正相反。
4310
+ // 现在按兄弟命令(`vault rag`、顶层 `search`)的形状来:默认人类可读,`--json` 才转发。
4311
+ .option('--json', '输出 JSON 格式(含本地路径与标题,供本机脚本/AI 使用)')
4171
4312
  .action(async (query, opts) => {
4172
4313
  const pkgRoot = resolvePackageRoot()
4173
4314
  const script = join(pkgRoot, 'scripts', 'vault_search.py')
4174
- if (!['all', 'article', 'concept', 'note'].includes(opts.type)) {
4175
- console.log(chalk.red('type 必须是 all、article、concept 或 note'))
4176
- process.exit(1)
4177
- }
4178
- const topK = parseCliInteger(opts.topK, 'top-k', 1, 100)
4179
- await runPythonCmd(script, [query, '--type', opts.type, '--top-k', String(topK), '--json'])
4315
+ // 校验分支也要认 `--json`(`requireCliChoice` 里就带着这条约定):
4316
+ // 否则 JSON 模式下 stdout 是一行彩色散文,脚本解析不了。
4317
+ requireCliChoice(opts.type, ['all', 'article', 'concept', 'note'], 'type', opts.json)
4318
+ requireCliChoice(opts.line, ['wiki', 'chat', 'all'], 'line', opts.json)
4319
+ const topK = parseCliInteger(opts.topK, 'top-k', 1, 100, opts.json)
4320
+ const days = parseCliInteger(opts.days, 'days', 1, 3650, opts.json)
4321
+ await runPythonCmd(script, [query, '--type', opts.type, '--line', opts.line,
4322
+ '--top-k', String(topK), '--days', String(days),
4323
+ ...(opts.json ? ['--json'] : [])])
4180
4324
  })
4181
4325
  )
4182
4326
 
@@ -4188,6 +4332,7 @@ program
4188
4332
  .description('Vault 问答 — 基于知识库的 AI 对话')
4189
4333
  .argument('<question>', '问题')
4190
4334
  .option('--top-k <n>', '检索条数', '8')
4335
+ .option('--line <line>', 'wiki=文章线(默认) / chat=聊天线 / all=两条都搜', 'wiki')
4191
4336
  .option('--api-key <key>', 'DeepSeek API key')
4192
4337
  .option('--dry-run', '仅预览,不读取知识库或调用 AI')
4193
4338
  .option('--yes', '确认读取本地知识并发送筛选后的上下文到 AI')
@@ -4196,11 +4341,13 @@ program
4196
4341
  const pkgRoot = resolvePackageRoot()
4197
4342
  const script = join(pkgRoot, 'scripts', 'vault_rag.py')
4198
4343
  const topK = parseCliInteger(opts.topK, 'top-k', 1, 100, opts.json)
4344
+ requireCliChoice(opts.line, ['wiki', 'chat', 'all'], 'line', opts.json)
4199
4345
  const preview = {
4200
4346
  success: true,
4201
4347
  dryRun: true,
4202
4348
  action: 'vault.rag',
4203
4349
  topK,
4350
+ line: opts.line,
4204
4351
  readsLocalKnowledge: true,
4205
4352
  usesAi: true,
4206
4353
  sendsSelectedContextToAi: true,
@@ -4226,7 +4373,7 @@ program
4226
4373
  return
4227
4374
  }
4228
4375
  }
4229
- const args = ['--top-k', String(topK)]
4376
+ const args = ['--top-k', String(topK), '--line', opts.line]
4230
4377
  if (opts.json) args.push('--json')
4231
4378
  const { execFile } = await import('child_process')
4232
4379
  const { promisify } = await import('util')
@@ -4520,6 +4667,7 @@ program
4520
4667
  }
4521
4668
 
4522
4669
  const child = spawn(getPythonCommand(), args, {
4670
+ windowsHide: true,
4523
4671
  stdio: 'inherit',
4524
4672
  env: pythonProcessEnv(),
4525
4673
  })
@@ -4530,6 +4678,25 @@ program
4530
4678
  })
4531
4679
 
4532
4680
  // ==================== weread ====================
4681
+
4682
+ /** 微信读书服务失败时的统一出口。
4683
+ *
4684
+ * 9 个调用点(shelf / stats / notes×2 / search / book / review / discover / profile)原来都是一行式
4685
+ * 分支:把彩色散文打在 stdout 上再 `process.exit(1)`,**没有** json 支,而各命令的 `if (opts.json)`
4686
+ * 分支在它后面 ⇒ `weread shelf --json` 失败时 stdout 上只有一行 `✗ …`,调用方解析不了,也不知道
4687
+ * 是哪个命令失败了。全库其余同类出口都是"机器支发 JSON + exit"。
4688
+ *
4689
+ * (这里刻意**不**把那行旧代码原样抄出来:`test/json-error-surface.test.ts` 有一条绊线在扫那个形状,
4690
+ * 而注释里留一份字面量会让判据读到它 —— 今晚已经在另一条判据上踩过这个坑。)
4691
+ *
4692
+ * 人看的那一支保持原样(`console.log`,不动它的落点):把 CLI 的**错误**统一改走 stderr 是另一件事,
4693
+ * 现在库里两种都有(多数 `console.error`、少数 `console.log`),不在这条修复里顺手改。
4694
+ */
4695
+ function failWeread(res: { error?: string }, json = false): never {
4696
+ if (json) console.log(JSON.stringify({ success: false, code: 'WEREAD_FAILED', error: res.error }))
4697
+ else console.log(chalk.red(`✗ ${res.error}`))
4698
+ process.exit(1)
4699
+ }
4533
4700
  const wereadCmd = program
4534
4701
  .command('weread')
4535
4702
  .description('微信读书助手 — 书架、统计、笔记、搜索、书评、推荐')
@@ -4541,7 +4708,7 @@ program
4541
4708
  .action(async (opts) => {
4542
4709
  const weread = await getWereadService()
4543
4710
  const res = await weread.shelf()
4544
- if (!res.ok) { console.log(chalk.red(`✗ ${res.error}`)); process.exit(1) }
4711
+ if (!res.ok) failWeread(res, !!opts.json)
4545
4712
  const d = res.data!
4546
4713
  if (opts.json) { console.log(JSON.stringify(d, null, 2)); return }
4547
4714
 
@@ -4570,7 +4737,7 @@ program
4570
4737
  .action(async (opts) => {
4571
4738
  const weread = await getWereadService()
4572
4739
  const res = await weread.readData(opts.mode)
4573
- if (!res.ok) { console.log(chalk.red(`✗ ${res.error}`)); process.exit(1) }
4740
+ if (!res.ok) failWeread(res, !!opts.json)
4574
4741
  const d = res.data!
4575
4742
  if (opts.json) { console.log(JSON.stringify(d, null, 2)); return }
4576
4743
 
@@ -4618,7 +4785,7 @@ program
4618
4785
  const limit = parseCliInteger(opts.limit, 'limit', 1, 100, opts.json)
4619
4786
  if (opts.bookId) {
4620
4787
  const res = await weread.bookmarks(opts.bookId, limit)
4621
- if (!res.ok) { console.log(chalk.red(`✗ ${res.error}`)); process.exit(1) }
4788
+ if (!res.ok) failWeread(res, !!opts.json)
4622
4789
  const d = res.data!
4623
4790
  if (opts.json) { console.log(JSON.stringify(d, null, 2)); return }
4624
4791
  console.log(chalk.cyan(`📝 划线笔记 (${d.updated?.length || 0} 条):\n`))
@@ -4631,7 +4798,7 @@ program
4631
4798
  }
4632
4799
  } else {
4633
4800
  const res = await weread.notebooks(50)
4634
- if (!res.ok) { console.log(chalk.red(`✗ ${res.error}`)); process.exit(1) }
4801
+ if (!res.ok) failWeread(res, !!opts.json)
4635
4802
  const d = res.data!
4636
4803
  if (opts.json) { console.log(JSON.stringify(d, null, 2)); return }
4637
4804
  console.log(chalk.cyan(`📝 笔记本 (${d.books?.length || 0} 本有笔记):\n`))
@@ -4654,7 +4821,7 @@ program
4654
4821
  const weread = await getWereadService()
4655
4822
  const limit = parseCliInteger(opts.limit, 'limit', 1, 100, opts.json)
4656
4823
  const res = await weread.search(keyword, limit)
4657
- if (!res.ok) { console.log(chalk.red(`✗ ${res.error}`)); process.exit(1) }
4824
+ if (!res.ok) failWeread(res, !!opts.json)
4658
4825
  const d = res.data!
4659
4826
  if (opts.json) { console.log(JSON.stringify(d, null, 2)); return }
4660
4827
  console.log(chalk.cyan(`🔍 搜索: "${keyword}" (${d.books?.length || 0} 条):\n`))
@@ -4678,7 +4845,7 @@ program
4678
4845
  weread.bookInfo(bookId),
4679
4846
  weread.getProgress(bookId),
4680
4847
  ])
4681
- if (!infoRes.ok) { console.log(chalk.red(`✗ ${infoRes.error}`)); process.exit(1) }
4848
+ if (!infoRes.ok) failWeread(infoRes, !!opts.json)
4682
4849
  const b = infoRes.data!
4683
4850
  if (opts.json) { console.log(JSON.stringify(b, null, 2)); return }
4684
4851
 
@@ -4704,7 +4871,7 @@ program
4704
4871
  const weread = await getWereadService()
4705
4872
  const limit = parseCliInteger(opts.limit, 'limit', 1, 100, opts.json)
4706
4873
  const res = await weread.reviews(bookId, limit)
4707
- if (!res.ok) { console.log(chalk.red(`✗ ${res.error}`)); process.exit(1) }
4874
+ if (!res.ok) failWeread(res, !!opts.json)
4708
4875
  const d = res.data!
4709
4876
  if (opts.json) { console.log(JSON.stringify(d, null, 2)); return }
4710
4877
  console.log(chalk.cyan(`💬 书评 (${d.reviews?.length || 0} 条):\n`))
@@ -4730,7 +4897,7 @@ program
4730
4897
  const res = opts.bookId
4731
4898
  ? await weread.similar(opts.bookId, limit)
4732
4899
  : await weread.recommend(limit)
4733
- if (!res.ok) { console.log(chalk.red(`✗ ${res.error}`)); process.exit(1) }
4900
+ if (!res.ok) failWeread(res, !!opts.json)
4734
4901
  const d = res.data!
4735
4902
  if (opts.json) { console.log(JSON.stringify(d, null, 2)); return }
4736
4903
  const label = opts.bookId ? '相似推荐' : '个性化推荐'
@@ -4751,7 +4918,7 @@ program
4751
4918
  .action(async (opts) => {
4752
4919
  const weread = await getWereadService()
4753
4920
  const res = await weread.profile()
4754
- if (!res.ok) { console.log(chalk.red(`✗ ${res.error}`)); process.exit(1) }
4921
+ if (!res.ok) failWeread(res, !!opts.json)
4755
4922
  const p = res.data!
4756
4923
  if (opts.json) { console.log(JSON.stringify(p, null, 2)); return }
4757
4924
 
@@ -4794,6 +4961,8 @@ program
4794
4961
  .description('语义搜索知识库(聊天记录 + 文章)')
4795
4962
  .argument('<query>', '搜索关键词')
4796
4963
  .option('--top-k <n>', '返回数量', '10')
4964
+ .option('--line <line>', 'wiki=文章线(默认) / chat=聊天记录 / all=两条都搜', 'wiki')
4965
+ .option('--no-rerank', '不调用决策模型重排,只按向量/关键词相似度返回(回退到引入重排之前)')
4797
4966
  .option('--api-key <key>', 'DashScope embedding API key')
4798
4967
  .option('--dry-run', '仅预览,不读取索引或调用向量服务')
4799
4968
  .option('--yes', '确认执行可能调用云端向量服务的搜索')
@@ -4805,11 +4974,14 @@ program
4805
4974
  const pkgRoot = resolvePackageRoot()
4806
4975
  const script = join(pkgRoot, 'scripts', 'semantic_search.py')
4807
4976
  const topK = parseCliInteger(opts.topK, 'top-k', 1, 100, opts.json)
4977
+ requireCliChoice(opts.line, ['wiki', 'chat', 'all'], 'line', opts.json)
4808
4978
  const preview = {
4809
4979
  success: true,
4810
4980
  dryRun: true,
4811
4981
  action: 'semantic-search.query',
4812
4982
  topK,
4983
+ line: opts.line,
4984
+ noRerank: opts.rerank === false,
4813
4985
  readsLocalIndex: true,
4814
4986
  mayUseCloudEmbedding: true,
4815
4987
  }
@@ -4834,7 +5006,11 @@ program
4834
5006
  return
4835
5007
  }
4836
5008
  }
4837
- const args: string[] = [script, 'search', '--top-k', String(topK)]
5009
+ // `--no-rerank` 是**旗标**(不是密钥)⇒ 可以走 argv;查询本身仍然只走 env(见 `privacy-paths` 那条规矩)。
5010
+ // 接这条通道之前,`OPERATIONS.md` 一直在教用户敲 `search --no-rerank`,而 CLI 会答 `unknown option`
5011
+ // —— 同一份文档里 `--line` 是通的,所以它看起来像"能用的旗标"(2026-10-11 由文档命令面那道检查发现)。
5012
+ const args: string[] = [script, 'search', '--top-k', String(topK), '--line', opts.line,
5013
+ ...(opts.rerank === false ? ['--no-rerank'] : [])]
4838
5014
  try {
4839
5015
  const { stdout } = await execFileAsync(getPythonCommand(), args, {
4840
5016
  timeout: 60_000, maxBuffer: 10 * 1024 * 1024,
@@ -4932,6 +5108,7 @@ program
4932
5108
  .description('RAG 智能助手 — 基于聊天记录和公众号的对话式问答')
4933
5109
  .argument('[question]', '要问的问题(不传则进入交互模式)')
4934
5110
  .option('--top-k <n>', '检索数量', '10')
5111
+ .option('--line <line>', 'wiki=文章/文章概念(默认) / chat=聊天记录 / all=两条都搜', 'wiki')
4935
5112
  .option('--talker <name>', '限定联系人/群聊')
4936
5113
  .option('--api-key <key>', 'AI API key')
4937
5114
  .option('--dry-run', '仅预览,不读取知识库或调用 AI')
@@ -4944,11 +5121,13 @@ program
4944
5121
  const pkgRoot = resolvePackageRoot()
4945
5122
  const script = join(pkgRoot, 'scripts', 'rag_chat.py')
4946
5123
  const topK = parseCliInteger(opts.topK, 'top-k', 1, 100, opts.json)
5124
+ requireCliChoice(opts.line, ['wiki', 'chat', 'all'], 'line', opts.json)
4947
5125
  const preview = {
4948
5126
  success: true,
4949
5127
  dryRun: true,
4950
5128
  action: 'rag-chat.query',
4951
5129
  topK,
5130
+ line: opts.line,
4952
5131
  interactiveRequired: !question,
4953
5132
  readsLocalKnowledge: true,
4954
5133
  usesCloudEmbedding: true,
@@ -4983,7 +5162,7 @@ program
4983
5162
  }
4984
5163
  const args: string[] = [script]
4985
5164
  if (question) {
4986
- args.push('--top-k', String(topK))
5165
+ args.push('--top-k', String(topK), '--line', opts.line)
4987
5166
  if (opts.json) args.push('--json')
4988
5167
  try {
4989
5168
  const { stdout } = await execFileAsync(getPythonCommand(), args, {
@@ -5001,8 +5180,9 @@ program
5001
5180
  }
5002
5181
  } else {
5003
5182
  // 交互模式:使用 spawn 保持终端交互
5004
- args.push('--interactive', '--top-k', String(topK))
5183
+ args.push('--interactive', '--top-k', String(topK), '--line', opts.line)
5005
5184
  const child = spawn(getPythonCommand(), args, {
5185
+ windowsHide: true,
5006
5186
  stdio: 'inherit',
5007
5187
  env: {
5008
5188
  ...pythonProcessEnv(opts.apiKey),
@@ -5269,8 +5449,12 @@ program
5269
5449
  // draft:判断在前、起草在后、**绝不发送**
5270
5450
  program
5271
5451
  .command('draft <talker>')
5272
- .description('帮我起草回复:先判断(意图/风险/该不该给实质),再起草候选 —— **只产出文本,不发送**')
5452
+ .description('帮我起草回复:先判断(意图/风险/该不该给实质),再起草候选 —— **默认只产出文本;给了 --pick N --send 才会替你发送**')
5273
5453
  .option('--count <n>', '要几条候选', '3')
5454
+ .option('--pick <n>', '选第几条(从 1 数);不带 --send 时只把那条的完整原文打出来')
5455
+ .option('--send', '把选中的那条发出去 —— **必须同时给 --pick**(不允许"自己挑一条发"),仍需 --yes/--dry-run')
5456
+ .option('--rate-window <ms>', '发送速率窗口毫秒(与 send 同一份策略)', '60000')
5457
+ .option('--rate-max <n>', '窗口内最大发送条数', '10')
5274
5458
  .option('--gate-commitment', '承诺未兑现时也拒绝起草(默认只在提示词里约束)')
5275
5459
  .option('--dry-run', '仅预览会发多少字符给哪两个模型,不调用')
5276
5460
  .option('--yes', '确认把这段对话发送到判断模型与生成模型')
@@ -5279,9 +5463,20 @@ program
5279
5463
  const { execFile } = await import('child_process')
5280
5464
  const { promisify } = await import('util')
5281
5465
  const execFileAsync = promisify(execFile)
5466
+ // **用法错误先报**,而且都在调模型之前报:`--send` 少了 `--pick` 是"你没说发哪条",
5467
+ // `--pick 9` 而只有 3 条是"那条根本不存在" —— 两者都不该先问一遍"要不要把对话发给云端模型"、
5468
+ // 更不该先花掉模型调用再拒绝。
5469
+ const count = parseCliInteger(opts.count, 'count', 1, 5, opts.json)
5470
+ if (opts.send && opts.pick === undefined) {
5471
+ const message = '--send 必须同时给 --pick <序号>:先看候选,再点名要发哪一条'
5472
+ if (opts.json) console.log(JSON.stringify({ success: false, code: 'PICK_REQUIRED', error: message }))
5473
+ else console.log(chalk.red(`
5474
+ ❌ ${message}`))
5475
+ process.exit(1)
5476
+ }
5477
+ const pick = opts.pick === undefined ? 0 : parseCliInteger(opts.pick, 'pick', 1, count, opts.json)
5282
5478
  const pkgRoot = resolvePackageRoot()
5283
5479
  const script = join(pkgRoot, 'scripts', 'draft_reply.py')
5284
- const count = parseCliInteger(opts.count, 'count', 1, 5, opts.json)
5285
5480
  // **"确认过了"只用一个变量表示**(`--yes` 或交互回答"是"),参数在确认之后才拼。
5286
5481
  // 原来的写法是先拼参数、再问,于是**交互确认那条路是坏的**:答了"是",`args` 里
5287
5482
  // 却从没补上 `--yes`,脚本照样拒绝(用户看到的是"我确认了它却说没确认")。
@@ -5309,6 +5504,149 @@ program
5309
5504
  return
5310
5505
  }
5311
5506
  }
5507
+ // ---------------- 选中并(可选)发送 ----------------
5508
+ //
5509
+ // **只有给了 `--pick` 或 `--send` 才走这条分支**;不带它们的调用与以前逐字相同(原样透传脚本输出)。
5510
+ //
5511
+ // 这条分支存在的理由:起草那一半早就有了(判断 → 候选 → 排序),缺的是"人选定之后能真的发出去"。
5512
+ // 而它的**要点是这个 `--pick`**:发送必须由人点名"第几条"。少了它,就成了"模型起草三条、
5513
+ // 模型挑一条、模型发出去" —— 那正是本仓库划掉的那件事
5514
+ // (docs/EXTENDING.md:sending is structurally unreachable from a model-driven path)。
5515
+ if (opts.pick !== undefined || opts.send) {
5516
+ // **`--dry-run` 的语义是"零出境"**,而候选必须由模型产出来 —— 两者不可兼得:不起草就没有
5517
+ // 候选,"预览某一条会发什么"这件事本身不成立。所以这里只报"会发多少字符给哪两个模型"
5518
+ // (脚本的 dry-run 本来就报这个),并把话说清楚,而不是假装预览了一条。
5519
+ if (opts.dryRun) {
5520
+ try {
5521
+ const { stdout } = await execFileAsync(getPythonCommand(),
5522
+ [script, '--talker', String(talker), '--count', String(count), '--dry-run',
5523
+ ...(opts.json ? ['--json'] : [])],
5524
+ { timeout: 120_000, maxBuffer: 20 * 1024 * 1024, env: pythonProcessEnv() })
5525
+ process.stdout.write(stdout)
5526
+ } catch (error) {
5527
+ console.error(chalk.red(`\n✗ ${safeSubprocessError(error, '预览失败')}`))
5528
+ process.exit(1)
5529
+ }
5530
+ if (!opts.json) {
5531
+ console.log(chalk.gray('\n候选要由模型产出来,所以 --dry-run 下没有候选可挑。'
5532
+ + '要预览"发第几条":先起草一次(会调用模型),再用 --pick N --send。\n'))
5533
+ }
5534
+ return
5535
+ }
5536
+ // `--pick`/`--send` 的用法错误在 action 开头就报过了(那一段全在调模型之前)
5537
+ // 内部一律用 `--json` 拿结构化结果(用户那侧的 `--json` 管的是最终输出,两回事)
5538
+ const pickArgs = [script, '--talker', String(talker), '--count', String(count), '--json',
5539
+ ...(confirmed ? ['--yes'] : []),
5540
+ ...(opts.gateCommitment ? ['--gate-commitment'] : [])]
5541
+ let drafts: Array<{ text: string }> = []
5542
+ try {
5543
+ const { stdout } = await execFileAsync(getPythonCommand(), pickArgs, {
5544
+ timeout: 300_000, maxBuffer: 50 * 1024 * 1024, env: pythonProcessEnv(),
5545
+ })
5546
+ const parsed = JSON.parse(stdout)
5547
+ if (parsed.gate === 'refused') {
5548
+ // **不起草就不发**:那道闸(涉钱/风险高)拒绝时压根没有候选,这里也不能凭空发点什么
5549
+ const message = `这次不起草:${parsed.reason || '判断层拒绝了'}`
5550
+ if (opts.json) console.log(JSON.stringify({ success: false, code: 'DRAFT_REFUSED', error: message, advice: parsed.advice || [] }))
5551
+ else {
5552
+ console.log(chalk.yellow(`\n${message}`))
5553
+ for (const item of parsed.advice || []) console.log(chalk.gray(` · ${item}`))
5554
+ }
5555
+ process.exit(1)
5556
+ }
5557
+ drafts = parsed.drafts || []
5558
+ } catch (error) {
5559
+ const message = safeSubprocessError(error, '起草失败')
5560
+ if (opts.json) console.log(JSON.stringify({ success: false, code: 'DRAFT_FAILED', error: message }))
5561
+ else console.error(chalk.red(`\n✗ ${message}`))
5562
+ process.exit(1)
5563
+ }
5564
+ const chosen = drafts[pick - 1]
5565
+ if (!chosen) {
5566
+ const message = `没有第 ${pick} 条候选(这次只有 ${drafts.length} 条)`
5567
+ if (opts.json) console.log(JSON.stringify({ success: false, code: 'PICK_OUT_OF_RANGE', error: message }))
5568
+ else console.log(chalk.red(`\n❌ ${message}`))
5569
+ process.exit(1)
5570
+ }
5571
+ if (!opts.send) {
5572
+ if (opts.json) console.log(JSON.stringify({ success: true, action: 'draft', sent: false, pick, text: chosen.text }))
5573
+ else console.log(`第 ${pick} 条:\n${chosen.text}\n\n${chalk.gray('(没有发送任何东西;要发加 --send)')}`)
5574
+ return
5575
+ }
5576
+
5577
+ // 发送这一半走**与 `send` 命令完全相同的那份策略**(黑名单 → 白名单 → 限速 → 审计)
5578
+ let wxid: string
5579
+ try {
5580
+ wxid = await resolveTalker(String(talker), !!opts.json, !!opts.json)
5581
+ } catch (error: any) {
5582
+ if (opts.json) console.log(JSON.stringify({ success: false, code: 'TALKER_RESOLUTION_FAILED', error: error.message }))
5583
+ else console.log(chalk.red(`\n❌ ${error.message}`))
5584
+ process.exit(1)
5585
+ }
5586
+ let displayName = whitelistService.lookupName(wxid)
5587
+ if (displayName === wxid) {
5588
+ try {
5589
+ const sessions = await chatService.listSessions(undefined, 200)
5590
+ const match = sessions.find(s => s.username === wxid)
5591
+ if (match?.displayName) displayName = match.displayName
5592
+ } catch { /* 拿不到名字就退回 wxid */ }
5593
+ }
5594
+ const policy = parseOutboundPolicy(Number(opts.rateWindow), Number(opts.rateMax))
5595
+ if ('code' in policy) {
5596
+ if (opts.json) console.log(JSON.stringify({ success: false, code: policy.code, error: policy.error }))
5597
+ else console.log(chalk.red(`\n❌ ${policy.error}`))
5598
+ process.exit(1)
5599
+ }
5600
+ const attempt = {
5601
+ wxid, displayName, kind: 'text' as const,
5602
+ preview: chosen.text.slice(0, 80) + (chosen.text.length > 80 ? '...' : ''),
5603
+ text: chosen.text,
5604
+ }
5605
+ const decision = authorizeOutbound(attempt, policy)
5606
+ if (!decision.ok) {
5607
+ const { refusal } = decision
5608
+ if (opts.json) {
5609
+ // 这里**还没有** sendPreview(它在闸门通过之后才建),所以逐字段写
5610
+ console.log(JSON.stringify({ success: false, code: refusal.code, error: refusal.error,
5611
+ ...(refusal.rateLimit ? { rateLimit: refusal.rateLimit } : {}) }))
5612
+ } else {
5613
+ console.log(chalk.red(`\n❌ ${refusal.error}`))
5614
+ if (refusal.code === 'TARGET_NOT_ALLOWED') console.log(chalk.gray(` 先运行: weflow-cli whitelist add ${talker}\n`))
5615
+ if (refusal.code === 'TARGET_BLOCKED') console.log(chalk.gray(' 这个人在黑名单里,任何一条命令行都不会发给他\n'))
5616
+ if (refusal.rateLimit) console.log(chalk.gray(` 最近 ${refusal.rateLimit.windowMs / 1000}s 内已发 ${refusal.rateLimit.count} 条\n`))
5617
+ }
5618
+ process.exit(1)
5619
+ }
5620
+ const sendPreview = { success: true, action: 'draft-send', target: { wxid, displayName },
5621
+ pick, text: chosen.text, rateLimit: decision.rate }
5622
+ // 两段式在这里:不给 `--yes` 时,JSON 模式回 `CONFIRMATION_REQUIRED`(**带着要发的原文**),
5623
+ // 交互模式则问一句"确定把第 N 条发给 X?"。`--dry-run` 那条路在上面的分支入口就返回了
5624
+ // (它意味着零出境,与"必须由模型产出候选"不可兼得),所以这里没有第三个预览分支。
5625
+ if (opts.json && !opts.yes) {
5626
+ console.log(JSON.stringify({ ...sendPreview, success: false, code: 'CONFIRMATION_REQUIRED', error: '使用 --yes 确认发送' }))
5627
+ process.exit(1)
5628
+ }
5629
+ if (!opts.yes) {
5630
+ const answer = await inquirer.prompt([{
5631
+ type: 'confirm', name: 'send', default: false,
5632
+ message: `确定把第 ${pick} 条发给 ${displayName}?`,
5633
+ }])
5634
+ if (!answer.send) {
5635
+ console.log(chalk.gray('已取消,没有发送'))
5636
+ return
5637
+ }
5638
+ }
5639
+ const sent = await performOutbound(attempt)
5640
+ if (sent.success) {
5641
+ if (opts.json) console.log(JSON.stringify(sendPreview))
5642
+ else console.log(chalk.green('✓ 发送成功'))
5643
+ return
5644
+ }
5645
+ if (opts.json) console.log(JSON.stringify({ ...sendPreview, success: false, code: 'SEND_FAILED', error: sent.error }))
5646
+ else console.log(chalk.red(`✗ 发送失败 — ${sent.error}`))
5647
+ process.exit(1)
5648
+ }
5649
+
5312
5650
  const args = [script, '--talker', String(talker), '--count', String(count),
5313
5651
  // 脚本自己有第二道闸门(`--yes` 才真的把对话发出去),所以要透传
5314
5652
  ...(confirmed ? ['--yes'] : []),
@@ -5333,18 +5671,86 @@ program
5333
5671
  }
5334
5672
  })
5335
5673
 
5674
+ // wiki graph:把概念图谱导成一张**自包含**的 3D 页面(全本地:只读 Vault、不联网、不调用模型)
5675
+ //
5676
+ // 自包含是硬要求,不是顺手:页面用 `file://` 双击打开,那时 `fetch` 会被 CORS 挡死,
5677
+ // 所以库、数据、坐标全部内联进去 —— 也因此三个库随 npm 包发(见 resources/js/graph3d/NOTICE.txt)。
5678
+ // 布局(250 tick 实测 55 秒)在构建期用 Node 算完并缓存,打开页面即用。
5679
+ program.commands.find(c => c.name() === 'wiki')?.addCommand(
5680
+ new Command('graph')
5681
+ .description('把概念图谱导成一张自包含的图谱页面(只读本地、不联网;生成的 HTML 双击就能逛)。--flat 出 2D 版')
5682
+ .option('--vault <dir>', 'Vault 根目录(默认 output/wechat-vault)')
5683
+ .option('-o, --out <file>', '页面写到哪(默认 output/knowledge-graph-3d.html)')
5684
+ .option('--ticks <n>', '力导向迭代次数(默认 250,越多越舒展也越慢)')
5685
+ .option('--cache <dir>', '布局缓存目录(派生数据;测试/多份图分开放时用)')
5686
+ .option('--flat', '2D 版:平面图(更像 Obsidian 那种),canvas 渲染,输出默认 knowledge-graph-2d.html')
5687
+ .option('--min-degree <n>', '只画在原图里连接数 ≥N 的概念(去掉细枝看骨架;0 = 全画)')
5688
+ .option('--line <which>', '只画一条线:all / wiki / chat')
5689
+ .option('--dry-run', '只报概念与链接数:不写文件、也不算布局(本地,零改动)')
5690
+ .option('--open', '生成后用默认浏览器打开它')
5691
+ .option('--json', '输出机器可读结果')
5692
+ .action(async (opts) => {
5693
+ const { execFile } = await import('child_process')
5694
+ const { promisify } = await import('util')
5695
+ const execFileAsync = promisify(execFile)
5696
+ // 2D 与 3D 是**两个入口脚本**:图怎么建共用(graph_2d 直接 import graph_3d),
5697
+ // 换的是布局维度与渲染器 —— 两套渲染器塞一个文件就没人看得完了。
5698
+ const script = join(resolvePackageRoot(), 'scripts', opts.flat ? 'graph_2d.py' : 'graph_3d.py')
5699
+ const ticks = opts.ticks === undefined ? undefined : parseCliInteger(opts.ticks, 'ticks', 1, 100000, !!opts.json)
5700
+ // `--json` 一律要:CLI 要拿到 out 路径与计数,才决定怎么印。开关只决定**给谁看**。
5701
+ const minDegree = opts.minDegree === undefined
5702
+ ? undefined : parseCliInteger(opts.minDegree, 'min-degree', 0, 100000, !!opts.json)
5703
+ const args = [script,
5704
+ ...(opts.vault ? ['--vault', opts.vault] : []),
5705
+ ...(opts.out ? ['--out', opts.out] : []),
5706
+ ...(opts.cache ? ['--cache', opts.cache] : []),
5707
+ ...(ticks === undefined ? [] : ['--ticks', String(ticks)]),
5708
+ ...(minDegree === undefined || minDegree === 0 ? [] : ['--min-degree', String(minDegree)]),
5709
+ ...(opts.line ? ['--line', opts.line] : []),
5710
+ ...(opts.dryRun ? ['--dry-run'] : []),
5711
+ '--json']
5712
+ try {
5713
+ const { stdout } = await execFileAsync(getPythonCommand(), args, {
5714
+ timeout: 900_000, maxBuffer: 64 * 1024 * 1024, env: pythonProcessEnv(),
5715
+ })
5716
+ const body = JSON.parse(stdout.slice(stdout.indexOf('{')))
5717
+ if (opts.json) {
5718
+ console.log(JSON.stringify(body))
5719
+ } else if (body.dryRun) {
5720
+ console.log(`概念 ${body.nodes} 个、链接 ${body.links} 条(--dry-run:没有写文件)`)
5721
+ } else {
5722
+ console.log(chalk.green(`✓ 已生成 ${body.out}`))
5723
+ console.log(chalk.gray(` 概念 ${body.nodes} / 链接 ${body.links} / ${body.mb} MB · ${opts.flat ? '2D' : '3D'} · 双击就能逛,不需要服务器`))
5724
+ }
5725
+ if (!opts.dryRun && opts.open && body.out) await openLocalUrl(body.out)
5726
+ } catch (error) {
5727
+ if (opts.json) {
5728
+ console.log(JSON.stringify({ success: false, code: 'GRAPH_FAILED', action: 'graph-3d', error: safeSubprocessError(error) }))
5729
+ } else {
5730
+ console.error(chalk.red(`\n✗ ${safeSubprocessError(error)}`))
5731
+ }
5732
+ process.exit(1)
5733
+ }
5734
+ })
5735
+ )
5736
+
5336
5737
  // wiki lint:知识库体检(全本地:不联网、不调用模型)
5337
5738
  program.commands.find(c => c.name() === 'wiki')?.addCommand(
5338
5739
  new Command('lint')
5339
5740
  .description('知识库体检:断链、孤儿、空页、同名(本地,不联网)')
5340
- .option('--dir <dir>', '概念页目录', './output/wechat-vault/Wiki/Concepts')
5741
+ // 不给默认值:不传 `--dir` 时体检脚本自己的默认(清单里的**全部线**)。
5742
+ // 这里曾经默认只给文章线,而脚本默认两条线都体检 ⇒"半开半合":命令行跑出来
5743
+ // 与脚本跑出来口径不同,而两边都不报错。
5744
+ .option('--dir <dirs...>', '概念页目录(可重复;不传则体检清单里的全部线)')
5341
5745
  .option('--json', '输出机器可读结果')
5342
5746
  .action(async (opts) => {
5343
5747
  const { execFile } = await import('child_process')
5344
5748
  const { promisify } = await import('util')
5345
5749
  const execFileAsync = promisify(execFile)
5346
5750
  const script = join(resolvePackageRoot(), 'scripts', 'wiki_lint.py')
5347
- const args = [script, '--dir', String(opts.dir), ...(opts.json ? ['--json'] : [])]
5751
+ const dirs = Array.isArray(opts.dir) ? opts.dir : (opts.dir ? [opts.dir] : [])
5752
+ const args = [script, ...dirs.flatMap((d: string) => ['--dir', String(d)]),
5753
+ ...(opts.json ? ['--json'] : [])]
5348
5754
  try {
5349
5755
  const { stdout } = await execFileAsync(getPythonCommand(), args, {
5350
5756
  timeout: 120_000, maxBuffer: 20 * 1024 * 1024, env: pythonProcessEnv(),
@@ -5366,6 +5772,8 @@ program
5366
5772
  .option('--limit <n>', '最多处理几个会话', '40')
5367
5773
  .option('--dry-run', '仅预览:几个会话、多少字符会发给生成模型(只读本地,零出境)')
5368
5774
  .option('--yes', '确认把对话发送给生成模型')
5775
+ .option('--transcribe-voice',
5776
+ '把缺转写的语音**本机**识别掉再产卡(本地 whisper,慢、吃 CPU、不出网;配合 --dry-run 就是只补转写、不调模型)')
5369
5777
  .option('--json', '输出机器可读结果;执行仍需 --yes')
5370
5778
  .action(async (opts) => {
5371
5779
  const { execFile } = await import('child_process')
@@ -5401,6 +5809,7 @@ program
5401
5809
  }
5402
5810
  const args = [script, '--days', String(days), '--limit', String(limit),
5403
5811
  ...(confirmed ? ['--yes'] : []),
5812
+ ...(opts.transcribeVoice ? ['--transcribe-voice'] : []),
5404
5813
  ...(opts.json ? ['--json'] : []),
5405
5814
  ...(opts.dryRun ? ['--dry-run'] : [])]
5406
5815
  try {
@@ -5774,7 +6183,7 @@ program
5774
6183
  const isComplete = (targetDate: string): boolean => Object.values(artifactStatus(targetDate)).every(Boolean)
5775
6184
 
5776
6185
  const runPipeline = (targetDate: string): Promise<number> => new Promise((resolve) => {
5777
- const args = [pipeline, '--date', targetDate, '--engine', noAi ? 'local' : 'deepseek', '--interest', 'AI', '--skip-wiki']
6186
+ const args = [pipeline, '--date', targetDate, '--engine', noAi ? 'local' : 'deepseek', '--interest', 'AI']
5778
6187
  if (noAi) args.push('--no-ai')
5779
6188
  // 与 --no-ai 不同:这一条保留判断(Jev),只关掉 LLM 的文字生成。
5780
6189
  if (opts.noSummary && !noAi) args.push('--no-summary')
@@ -5783,6 +6192,7 @@ program
5783
6192
 
5784
6193
  dailyLog(chalk.cyan(`\n📰 正在生成 ${targetDate} 公众号日报${noAi ? '(AI 已关闭)' : ''}...\n`))
5785
6194
  const child = spawn(getPythonCommand(), args, {
6195
+ windowsHide: true,
5786
6196
  stdio: opts.json ? ['ignore', 'pipe', 'pipe'] : 'inherit',
5787
6197
  env: pythonProcessEnv(apiKey),
5788
6198
  })
@@ -5798,6 +6208,7 @@ program
5798
6208
  const dryRunArgs = [bizDaily, '--date', date, '--engine', 'local', '--dry-run']
5799
6209
  for (const source of opts.source || []) dryRunArgs.push('--source', source)
5800
6210
  const child = spawn(getPythonCommand(), dryRunArgs, {
6211
+ windowsHide: true,
5801
6212
  stdio: opts.json ? ['ignore', 'pipe', 'pipe'] : 'inherit',
5802
6213
  env: pythonProcessEnv(),
5803
6214
  })
@@ -5959,6 +6370,349 @@ dailyFavoritesCmd
5959
6370
 
5960
6371
  program.commands.find(c => c.name() === 'daily')?.addCommand(dailyFavoritesCmd)
5961
6372
 
6373
+ // ==================== skill (本机技能包) ====================
6374
+ // 技能就是磁盘上的 `SKILL.md`,所以这里**没有安装/卸载**:读、看、体检三件事。
6375
+ // 体检(`check`)是最有用的一个 —— 它把"读不出来""不合规范""跨目录撞名"这些
6376
+ // 平时完全静默的问题一次报出来(少一个技能不会报错,只会少一个技能)。
6377
+ const skillCmd = program
6378
+ .command('skill')
6379
+ .description('本机技能包(SKILL.md):列出、查看、体检')
6380
+
6381
+ skillCmd
6382
+ .command('list')
6383
+ .description('列出扫描到的技能')
6384
+ .option('--query <q>', '按关键词过滤(匹配 id、名称、说明、触发词)')
6385
+ .option('--json', 'JSON 输出')
6386
+ .action((opts) => {
6387
+ const scan = scanSkills()
6388
+ const disabled = disabledIds()
6389
+ const q = String(opts.query || '').trim().toLowerCase()
6390
+ const rows = scan.skills.filter(s => !q
6391
+ || [s.id, s.name, s.description, ...s.triggers].some(x => String(x).toLowerCase().includes(q)))
6392
+ .map(s => ({
6393
+ id: s.id,
6394
+ name: s.name,
6395
+ description: s.description,
6396
+ version: s.version,
6397
+ state: skillState(s, disabled),
6398
+ notes: s.notes,
6399
+ // **不给路径**:这是机器输出,路径只有在用户明确要 `show` 时才出现
6400
+ }))
6401
+ if (opts.json) {
6402
+ console.log(JSON.stringify({
6403
+ success: true,
6404
+ roots: skillRoots(),
6405
+ missingRoots: scan.missingRoots,
6406
+ total: rows.length,
6407
+ skills: rows,
6408
+ }))
6409
+ return
6410
+ }
6411
+ if (!rows.length) {
6412
+ console.log(chalk.gray(scan.skills.length ? `没有匹配「${opts.query}」的技能` : '没有扫描到技能'))
6413
+ console.log(chalk.gray(`技能目录:${skillRoots().join('、')}`))
6414
+ for (const dir of scan.missingRoots) console.log(chalk.gray(` (不存在:${dir})`))
6415
+ return
6416
+ }
6417
+ for (const r of rows) {
6418
+ const tag = r.state === 'disabled' ? chalk.gray('[已禁用] ') : ''
6419
+ console.log(`${tag}${chalk.cyan(r.id)}${r.version ? chalk.gray(' v' + r.version) : ''} ${r.name}`)
6420
+ if (r.description) console.log(chalk.gray(` ${r.description.slice(0, 100)}`))
6421
+ for (const n of r.notes) console.log(chalk.yellow(` ⚠ ${n}`))
6422
+ }
6423
+ console.log(chalk.gray(`\n共 ${rows.length} 个。正文:weflow-cli skill show <id>`))
6424
+ })
6425
+
6426
+ skillCmd
6427
+ .command('show')
6428
+ .argument('<id>', '技能 id')
6429
+ .description('打印一个技能的 SKILL.md 正文')
6430
+ .option('--json', 'JSON 输出')
6431
+ .action((id, opts) => {
6432
+ const body = readSkillBody(id)
6433
+ if (!body.ok) {
6434
+ if (opts.json) {
6435
+ console.log(JSON.stringify({ success: false, code: 'SKILL_NOT_READABLE', error: body.text }))
6436
+ process.exit(1)
6437
+ }
6438
+ console.log(chalk.red(body.text))
6439
+ return
6440
+ }
6441
+ if (opts.json) {
6442
+ const scan = scanSkills()
6443
+ const info = scan.skills.find(s => s.id === id)
6444
+ console.log(JSON.stringify({
6445
+ success: true,
6446
+ id,
6447
+ name: info?.name ?? id,
6448
+ version: info?.version ?? '',
6449
+ truncated: !!body.truncated,
6450
+ body: body.text,
6451
+ }))
6452
+ return
6453
+ }
6454
+ console.log(body.text)
6455
+ })
6456
+
6457
+ skillCmd
6458
+ .command('check')
6459
+ .description('体检:不可读的 SKILL.md、跨目录同名、非规范 id、被禁用的技能')
6460
+ .option('--json', 'JSON 输出')
6461
+ .action((opts) => {
6462
+ const scan = scanSkills()
6463
+ const disabled = disabledIds()
6464
+ const disabledRows = scan.skills.filter(s => skillState(s, disabled) === 'disabled').map(s => s.id)
6465
+ const warned = scan.skills.filter(s => s.notes.length).map(s => ({ id: s.id, notes: s.notes }))
6466
+ const payload = {
6467
+ success: true,
6468
+ roots: skillRoots(),
6469
+ missingRoots: scan.missingRoots,
6470
+ total: scan.skills.length,
6471
+ unreadable: scan.unreadable,
6472
+ conflicts: scan.conflicts,
6473
+ warned,
6474
+ disabled: disabledRows,
6475
+ }
6476
+ if (opts.json) {
6477
+ console.log(JSON.stringify(payload))
6478
+ // 不可读 = 真出事了(有文件却读不出来),体检失败;警告与冲突只提示,不算失败
6479
+ if (scan.unreadable.length) process.exit(1)
6480
+ return
6481
+ }
6482
+ console.log(`技能目录:${skillRoots().join('、')}`)
6483
+ for (const dir of scan.missingRoots) console.log(chalk.gray(` 不存在:${dir}`))
6484
+ console.log(`扫描到 ${scan.skills.length} 个技能`)
6485
+ if (scan.unreadable.length) {
6486
+ console.log(chalk.red(`\n不可读 ${scan.unreadable.length} 个:`))
6487
+ for (const u of scan.unreadable) console.log(chalk.red(` ✗ ${u.file}\n ${u.reason}`))
6488
+ }
6489
+ if (scan.conflicts.length) {
6490
+ console.log(chalk.yellow(`\n跨目录同名 ${scan.conflicts.length} 个(靠前的目录胜出,不会覆盖):`))
6491
+ for (const c of scan.conflicts) console.log(chalk.yellow(` ! ${c.id}\n 用:${c.winner}\n 忽略:${c.loser}`))
6492
+ }
6493
+ if (warned.length) {
6494
+ console.log(chalk.yellow(`\n有提醒的 ${warned.length} 个:`))
6495
+ for (const w of warned) for (const n of w.notes) console.log(chalk.yellow(` · ${w.id}:${n}`))
6496
+ }
6497
+ if (disabledRows.length) console.log(chalk.gray(`\n已禁用:${disabledRows.join('、')}`))
6498
+ if (!scan.unreadable.length && !scan.conflicts.length) console.log(chalk.green('\n没有不可读或撞名的技能'))
6499
+ })
6500
+
6501
+ // ==================== scene (会话场景) ====================
6502
+ const sceneCmd = program
6503
+ .command('scene')
6504
+ .description('会话场景:按会话生效的提示词预设(绑定 → 关键词 → 上次用过的)')
6505
+
6506
+ /** 写场景是**本机文件写**,不是 python mutation:同样两段式,措辞照 todos 那条 */
6507
+ async function confirmSceneWrite(
6508
+ opts: { dryRun?: boolean; yes?: boolean; json?: boolean },
6509
+ preview: Record<string, unknown>,
6510
+ message: string,
6511
+ apply: () => { ok: boolean; reason?: string },
6512
+ ): Promise<void> {
6513
+ if (opts.dryRun) {
6514
+ if (opts.json) console.log(JSON.stringify({ success: true, dryRun: true, ...preview }))
6515
+ else console.log(chalk.cyan('预览:') + message)
6516
+ return
6517
+ }
6518
+ if (!opts.yes) {
6519
+ if (opts.json) {
6520
+ console.log(JSON.stringify({
6521
+ success: false,
6522
+ code: 'CONFIRMATION_REQUIRED',
6523
+ error: '先使用 --dry-run --json 预览,再由用户确认后使用 --yes --json 执行',
6524
+ }))
6525
+ process.exit(1)
6526
+ }
6527
+ const { confirmed } = await inquirer.prompt([{ type: 'confirm', name: 'confirmed', message, default: false }])
6528
+ if (!confirmed) {
6529
+ console.log(chalk.gray('已取消'))
6530
+ return
6531
+ }
6532
+ }
6533
+ const result = apply()
6534
+ if (result.ok) assistantScenes.save()
6535
+ const saved = result.ok && !assistantScenes.lastSaveError
6536
+ if (opts.json) {
6537
+ if (!result.ok) {
6538
+ console.log(JSON.stringify({ success: false, code: 'SCENE_OPERATION_FAILED', error: result.reason }))
6539
+ process.exit(1)
6540
+ }
6541
+ // 写失败要说出来:`save()` 不抛异常,代价是必须有地方把它讲出来
6542
+ console.log(JSON.stringify({
6543
+ success: saved,
6544
+ ...(saved ? {} : { code: 'SCENE_SAVE_FAILED', error: assistantScenes.lastSaveError }),
6545
+ ...preview,
6546
+ }))
6547
+ if (!saved) process.exit(1)
6548
+ return
6549
+ }
6550
+ if (!result.ok) {
6551
+ console.log(chalk.red(`✗ ${result.reason}`))
6552
+ process.exit(1)
6553
+ }
6554
+ if (!saved) console.log(chalk.red(`⚠ 已改动内存,但落盘失败:${assistantScenes.lastSaveError}`))
6555
+ else console.log(chalk.green('✓ 完成'))
6556
+ }
6557
+
6558
+ sceneCmd
6559
+ .command('list')
6560
+ .description('列出所有场景')
6561
+ .option('--json', 'JSON 输出')
6562
+ .action((opts) => {
6563
+ const scenes = assistantScenes.list()
6564
+ if (opts.json) {
6565
+ console.log(JSON.stringify({ success: true, total: scenes.length, scenes }))
6566
+ return
6567
+ }
6568
+ if (!scenes.length) {
6569
+ console.log(chalk.gray('还没有场景。加一个:'))
6570
+ console.log(chalk.gray(' weflow-cli scene add --id 日报 --keywords 日报,推文 --instruction "按主题分组" --dry-run'))
6571
+ return
6572
+ }
6573
+ for (const s of scenes) {
6574
+ console.log(`${s.enabled ? chalk.cyan(s.id) : chalk.gray(s.id + ' [已停用]')} ${s.name}`)
6575
+ if (s.keywords.length) console.log(chalk.gray(` 关键词:${s.keywords.join('、')}`))
6576
+ if (s.instruction) console.log(chalk.gray(` ${s.instruction.split('\n')[0].slice(0, 80)}`))
6577
+ }
6578
+ })
6579
+
6580
+ sceneCmd
6581
+ .command('show')
6582
+ .argument('<id>', '场景 id')
6583
+ .description('打印一个场景的全部字段')
6584
+ .option('--json', 'JSON 输出')
6585
+ .action((id, opts) => {
6586
+ const scene = assistantScenes.get(id)
6587
+ if (!scene) {
6588
+ if (opts.json) console.log(JSON.stringify({ success: false, code: 'SCENE_NOT_FOUND', error: `没有场景「${id}」` }))
6589
+ else console.log(chalk.red(`没有场景「${id}」`))
6590
+ process.exit(1)
6591
+ }
6592
+ if (opts.json) {
6593
+ console.log(JSON.stringify({ success: true, scene }))
6594
+ return
6595
+ }
6596
+ console.log(`id ${scene.id}`)
6597
+ console.log(`名称 ${scene.name}`)
6598
+ console.log(`状态 ${scene.enabled ? '启用' : '已停用'}`)
6599
+ console.log(`关键词 ${scene.keywords.join('、') || '(无)'}`)
6600
+ console.log(`所需技能 ${scene.skills.join('、') || '(无)'}`)
6601
+ console.log(`附加指令 ${scene.instruction || '(无)'}`)
6602
+ if (scene.outputSpec) console.log(`输出规范 ${scene.outputSpec}`)
6603
+ })
6604
+
6605
+ sceneCmd
6606
+ .command('add')
6607
+ .description('新增一个场景')
6608
+ .requiredOption('--id <id>', '场景 id(字母数字开头,可用 . _ -)')
6609
+ .option('--name <name>', '显示名(默认用 id)')
6610
+ .option('--keywords <list>', '关键词,逗号分隔')
6611
+ .option('--instruction <text>', '附加指令(长文本用 --from-file)')
6612
+ .option('--from-file <path>', '从文件读附加指令(多行中文走这条)')
6613
+ .option('--output-spec <text>', '输出规范')
6614
+ .option('--skills <list>', '所需技能 id,逗号分隔')
6615
+ .option('--dry-run', '仅预览,不写入')
6616
+ .option('--yes', '确认写入')
6617
+ .option('--json', 'JSON 输出')
6618
+ .action(async (opts) => {
6619
+ const id = String(opts.id || '').trim()
6620
+ const idError = validateSceneId(id)
6621
+ if (idError) {
6622
+ if (opts.json) console.log(JSON.stringify({ success: false, code: 'INVALID_SCENE_ID', error: idError }))
6623
+ else console.log(chalk.red(idError))
6624
+ process.exit(1)
6625
+ }
6626
+ let instruction = String(opts.instruction || '')
6627
+ if (opts.fromFile) {
6628
+ const path = String(opts.fromFile)
6629
+ if (!existsSync(path)) {
6630
+ if (opts.json) console.log(JSON.stringify({ success: false, code: 'FILE_NOT_FOUND', error: `读不到 ${path}` }))
6631
+ else console.log(chalk.red(`读不到 ${path}`))
6632
+ process.exit(1)
6633
+ }
6634
+ instruction = readFileSync(path, 'utf8')
6635
+ }
6636
+ const splitList = (v: unknown): string[] => String(v || '').split(/[,;]/).map(s => s.trim()).filter(Boolean)
6637
+ const scene: Scene = {
6638
+ id,
6639
+ name: String(opts.name || '').trim() || id,
6640
+ keywords: splitList(opts.keywords),
6641
+ instruction,
6642
+ outputSpec: String(opts.outputSpec || ''),
6643
+ skills: splitList(opts.skills),
6644
+ enabled: true,
6645
+ }
6646
+ await confirmSceneWrite(opts, { action: 'scene.add', scene: { ...scene, instruction: `(${instruction.length} 字)` } },
6647
+ `确认新增场景「${scene.name}」?`, () => assistantScenes.add(scene))
6648
+ })
6649
+
6650
+ sceneCmd
6651
+ .command('remove')
6652
+ .argument('<id>', '场景 id')
6653
+ .description('删除一个场景(连同指向它的绑定)')
6654
+ .option('--dry-run', '仅预览,不删除')
6655
+ .option('--yes', '确认删除')
6656
+ .option('--json', 'JSON 输出')
6657
+ .action(async (id, opts) => {
6658
+ const scene = assistantScenes.get(id)
6659
+ if (!scene) {
6660
+ if (opts.json) console.log(JSON.stringify({ success: false, code: 'SCENE_NOT_FOUND', error: `没有场景「${id}」` }))
6661
+ else console.log(chalk.red(`没有场景「${id}」`))
6662
+ process.exit(1)
6663
+ }
6664
+ await confirmSceneWrite(opts, { action: 'scene.remove', id }, `确认删除场景「${scene.name}」?`,
6665
+ () => { assistantScenes.remove(id); return { ok: true } })
6666
+ })
6667
+
6668
+ const toggleScene = (on: boolean) => async (id: string, opts: { dryRun?: boolean; yes?: boolean; json?: boolean }) => {
6669
+ const scene = assistantScenes.get(id)
6670
+ if (!scene) {
6671
+ if (opts.json) console.log(JSON.stringify({ success: false, code: 'SCENE_NOT_FOUND', error: `没有场景「${id}」` }))
6672
+ else console.log(chalk.red(`没有场景「${id}」`))
6673
+ process.exit(1)
6674
+ }
6675
+ await confirmSceneWrite(opts, { action: on ? 'scene.enable' : 'scene.disable', id },
6676
+ `确认${on ? '启用' : '停用'}场景「${scene.name}」?`,
6677
+ () => ({ ok: assistantScenes.setEnabled(id, on) }))
6678
+ }
6679
+
6680
+ sceneCmd.command('enable')
6681
+ .argument('<id>', '场景 id')
6682
+ .description('启用一个场景')
6683
+ .option('--dry-run', '仅预览').option('--yes', '确认').option('--json', 'JSON 输出')
6684
+ .action(toggleScene(true))
6685
+
6686
+ sceneCmd.command('disable')
6687
+ .argument('<id>', '场景 id')
6688
+ .description('停用一个场景(它不再参与匹配)')
6689
+ .option('--dry-run', '仅预览').option('--yes', '确认').option('--json', 'JSON 输出')
6690
+ .action(toggleScene(false))
6691
+
6692
+ sceneCmd
6693
+ .command('bind')
6694
+ .argument('<conversation>', '会话 id(微信里就是 conversationId;本机面板用它的记忆桶)')
6695
+ .requiredOption('--scene <id>', '要绑定的场景 id')
6696
+ .description('把某个场景固定绑到一个会话')
6697
+ .option('--dry-run', '仅预览').option('--yes', '确认').option('--json', 'JSON 输出')
6698
+ .action(async (conversation, opts) => {
6699
+ const id = String(opts.scene || '').trim()
6700
+ await confirmSceneWrite(opts, { action: 'scene.bind', conversation, scene: id },
6701
+ `确认把场景「${id}」绑到会话 ${conversation}?`,
6702
+ () => assistantScenes.bind(conversation, id))
6703
+ })
6704
+
6705
+ sceneCmd
6706
+ .command('unbind')
6707
+ .argument('<conversation>', '会话 id')
6708
+ .description('解绑:这个会话回到按关键词自动挑')
6709
+ .option('--dry-run', '仅预览').option('--yes', '确认').option('--json', 'JSON 输出')
6710
+ .action(async (conversation, opts) => {
6711
+ await confirmSceneWrite(opts, { action: 'scene.unbind', conversation },
6712
+ `确认解绑会话 ${conversation}?`,
6713
+ () => assistantScenes.bind(conversation, null))
6714
+ })
6715
+
5962
6716
  // ==================== assistant (第二大脑持久化 Agent) ====================
5963
6717
  const assistantCmd = program
5964
6718
  .command('assistant')
@@ -6394,6 +7148,51 @@ program
6394
7148
  }
6395
7149
  })
6396
7150
 
7151
+ // ==================== bonds ====================
7152
+ program
7153
+ .command('bonds')
7154
+ .description('关系温度:谁在冷却、谁在变热、谁只有微信这一条线(只读本地库,不联网、不调模型)')
7155
+ .option('--days <number>', '看最近多少天', '365')
7156
+ .option('--limit <number>', '最多扫几个会话', '400')
7157
+ .option('--top <number>', '每组列几条', '12')
7158
+ .option('--skip <name>', '排除某个名字或 id(可重复)', (value: string, acc: string[]) => {
7159
+ acc.push(value)
7160
+ return acc
7161
+ }, [] as string[])
7162
+ .option('--json', '输出 JSON 格式')
7163
+ .action(async (opts) => {
7164
+ const { execFile } = await import('child_process')
7165
+ const { promisify } = await import('util')
7166
+ const execFileAsync = promisify(execFile)
7167
+ const script = join(resolvePackageRoot(), 'scripts', 'bonds.py')
7168
+ const days = parseCliInteger(opts.days, 'days', 1, 3650, opts.json)
7169
+ const limit = parseCliInteger(opts.limit, 'limit', 1, 5000, opts.json)
7170
+ const top = parseCliInteger(opts.top, 'top', 1, 200, opts.json)
7171
+
7172
+ try {
7173
+ const args = [script, '--days', String(days), '--limit', String(limit), '--top', String(top)]
7174
+ for (const name of (opts.skip as string[]) || []) args.push('--skip', name)
7175
+ if (opts.json) args.push('--json')
7176
+ const { stdout } = await execFileAsync(getPythonCommand(), args, {
7177
+ timeout: 300_000,
7178
+ maxBuffer: 10 * 1024 * 1024,
7179
+ env: pythonProcessEnv(),
7180
+ })
7181
+ console.log(stdout)
7182
+ } catch (e: any) {
7183
+ if (opts.json) {
7184
+ console.log(JSON.stringify({
7185
+ success: false,
7186
+ code: 'BONDS_FAILED',
7187
+ error: '关系温度不可用,请运行 check --json 检查配置和依赖',
7188
+ }))
7189
+ process.exit(1)
7190
+ }
7191
+ console.error(chalk.red(`\n${safeSubprocessError(e, '统计失败')}`))
7192
+ process.exit(1)
7193
+ }
7194
+ })
7195
+
6397
7196
  // ==================== daily-server ====================
6398
7197
  program
6399
7198
  .command('daily-server')
@@ -6469,6 +7268,7 @@ program
6469
7268
  }
6470
7269
 
6471
7270
  const child = spawn(getPythonCommand(), [favServer, '--date', date, '--port', String(port)], {
7271
+ windowsHide: true,
6472
7272
  stdio: 'inherit',
6473
7273
  env: pythonProcessEnv(),
6474
7274
  })
@@ -6527,6 +7327,10 @@ program
6527
7327
  console.log(chalk.gray('AI 助手现在可以使用以下工具:'))
6528
7328
  } else {
6529
7329
  console.log(json)
7330
+ // 机器模式到这里就结束:下面那段工具清单与"复制以上 JSON…"是**给人看的**,原来无条件打在
7331
+ // stdout 上 ⇒ `mcp-config --json-result | jq` 断在第 14 行(2026-10-12 由只读驱动扫描发现;
7332
+ // 写路径本来就早退发 JSON,所以只有读路径这一处漏)。
7333
+ if (opts.jsonResult) return
6530
7334
  }
6531
7335
  console.log(chalk.cyan('\n可用的 MCP 工具:'))
6532
7336
  const STATIC_TOOLS: Array<[string, string]> = [
@@ -6565,18 +7369,40 @@ program
6565
7369
  .description('检查运行环境(Python、pip 依赖、数据库配置)')
6566
7370
  .option('--json', '输出 JSON 格式,不包含数据库路径或密钥')
6567
7371
  .action(async (opts) => {
7372
+ // 微信客户端的**版本**与它自报的**数据目录**:两个分支都要用,所以在这里算一次。
7373
+ // 判据见 `wechatClient.ts`(版本取活进程的 `--user-lib-dir`;取不到就是"未知",不是"没问题")。
7374
+ const client = await detectWechatClient()
7375
+ // 客户端自报的数据目录 vs 配置里那个数据库推出来的根:**只比是不是同一份**,
7376
+ // 路径本身不进机器可读输出(`wechat-check/v1` 一直是不含路径的)。
7377
+ //
7378
+ // **只在 4.x 上比**:这个根是从 `ntDbPath`(4.x 的库)推的,而客户端自报的那条来自 4.x 客户端
7379
+ // —— 只用 3.x 的用户(`dbPath3x`)比出来的"不是同一份"没有意义,而这句话**只在 false 时打印**
7380
+ // ⇒ 那就是一条假警告。判据不成立时给 null("不知道"),不是 false。
7381
+ const { dirname } = await import('node:path')
7382
+ // **四层**:`…/xwechat_files/<wxid>/db_storage/message/message_0.db`
7383
+ // → message → db_storage → <wxid> → xwechat_files。少一层就退到 `<wxid>` 目录,
7384
+ // 于是两个路径永远不相等、永远报"不是同一份"(一个看着很合理的假警告)。
7385
+ const dbPathConfigured = String(configService.get('dataVersion') || '') === '4.x'
7386
+ ? String(configService.get('ntDbPath') || '')
7387
+ : ''
7388
+ const configuredRoot = dbPathConfigured
7389
+ ? dirname(dirname(dirname(dirname(dbPathConfigured))))
7390
+ : ''
7391
+ const dataDirMatchesConfig = (client.dataDirs.length && configuredRoot)
7392
+ ? client.dataDirs.some(dir => samePath(dir, configuredRoot))
7393
+ : null
6568
7394
  if (opts.json) {
6569
7395
  const { execFileSync } = await import('child_process')
6570
7396
  const requiredDependencies = ['sqlcipher3', 'html2text', 'zstandard', 'cryptography']
6571
7397
  const optionalDependencies = ['scrapling']
6572
7398
  let pythonVersion = ''
6573
7399
  try {
6574
- pythonVersion = execFileSync(getPythonCommand(), ['--version'], { encoding: 'utf8', timeout: 5000 }).trim()
7400
+ pythonVersion = execFileSync(getPythonCommand(), ['--version'], { windowsHide: true, encoding: 'utf8', timeout: 5000 }).trim()
6575
7401
  } catch {}
6576
7402
  const dependencyStatus = (name: string): boolean => {
6577
7403
  if (!pythonVersion) return false
6578
7404
  try {
6579
- execFileSync(getPythonCommand(), ['-c', `import ${name}`], { stdio: 'ignore', timeout: 5000 })
7405
+ execFileSync(getPythonCommand(), ['-c', `import ${name}`], { windowsHide: true, stdio: 'ignore', timeout: 5000 })
6580
7406
  return true
6581
7407
  } catch {
6582
7408
  return false
@@ -6618,6 +7444,26 @@ program
6618
7444
  messageChannelLoggedIn: !!configService.get('wechatOcToken'),
6619
7445
  daemonRunning: daemonAlive,
6620
7446
  },
7447
+ // `version` 只从活进程取;取不到就是 null + 一句 `note`(**不是**"没问题")。
7448
+ // `unusableVersionDirs` 是磁盘上的残留版本目录(没有 `Weixin.dll`)—— 指向它们的加载会失败。
7449
+ wechatClient: {
7450
+ running: client.running,
7451
+ version: client.version,
7452
+ loadedDirs: client.loadedDirs,
7453
+ // 客户端自报的构建 token(并列的第二来源;**不拿它推版本号**,编码规则没解出来)
7454
+ versionTokens: client.versionTokens,
7455
+ note: client.note,
7456
+ unusableVersionDirs: client.unusableVersionDirs,
7457
+ // 客户端**自己说**数据目录在哪(与配置不一致时说明两边不是同一份库)
7458
+ dataDirs: client.dataDirs,
7459
+ // 只报结论(true/false/null),**不带路径** —— 这条 schema 一直是不含路径的
7460
+ dataDirMatchesConfig,
7461
+ // `update.data` 在场 ⇒ 加载路径可能不由命令行决定:这条不确定必须跟着版本一起出去
7462
+ updateData: client.updateData,
7463
+ // 只报条数与最近时间(不读崩溃内容)
7464
+ crashRecords: client.crashRecords,
7465
+ caveats: client.caveats,
7466
+ },
6621
7467
  }
6622
7468
  console.log(JSON.stringify(data, null, 2))
6623
7469
  return
@@ -6632,7 +7478,7 @@ program
6632
7478
  const pythonCommand = getPythonCommand()
6633
7479
  let pythonOk = false
6634
7480
  try {
6635
- const pyVer = execFileSync(pythonCommand, ['--version'], { encoding: 'utf-8', timeout: 5000 }).trim()
7481
+ const pyVer = execFileSync(pythonCommand, ['--version'], { windowsHide: true, encoding: 'utf-8', timeout: 5000 }).trim()
6636
7482
  console.log(chalk.white('Python: '), chalk.green(pyVer))
6637
7483
  pythonOk = true
6638
7484
  } catch {
@@ -6646,7 +7492,7 @@ program
6646
7492
  let allOk = true
6647
7493
  for (const dep of deps) {
6648
7494
  try {
6649
- execFileSync(pythonCommand, ['-c', `import ${dep}`], { stdio: 'ignore', timeout: 5000 })
7495
+ execFileSync(pythonCommand, ['-c', `import ${dep}`], { windowsHide: true, stdio: 'ignore', timeout: 5000 })
6650
7496
  console.log(` ${dep.padEnd(20)} ${chalk.green('✓')}`)
6651
7497
  } catch {
6652
7498
  console.log(` ${dep.padEnd(20)} ${chalk.red('✗ 缺失')}`)
@@ -6667,7 +7513,7 @@ program
6667
7513
  console.log(chalk.white('\n可选依赖(提升抓取成功率):'))
6668
7514
  for (const dep of optDeps) {
6669
7515
  try {
6670
- execFileSync(pythonCommand, ['-c', `import ${dep}`], { stdio: 'ignore', timeout: 5000 })
7516
+ execFileSync(pythonCommand, ['-c', `import ${dep}`], { windowsHide: true, stdio: 'ignore', timeout: 5000 })
6671
7517
  console.log(` ${dep.padEnd(20)} ${chalk.green('✓')}`)
6672
7518
  } catch {
6673
7519
  console.log(` ${dep.padEnd(20)} ${chalk.gray('○ (pip install scrapling)')}`)
@@ -6702,7 +7548,38 @@ program
6702
7548
  }
6703
7549
  }
6704
7550
 
6705
- // 6. Assistant (第二大脑)
7551
+ // 6. 微信客户端版本(`client` / `dataDirMatchesConfig` 在 action 开头已经算过)
7552
+ console.log(chalk.white('\n微信客户端:'))
7553
+ if (client.version) {
7554
+ // 并列报上客户端自报的构建 token:这是"哪个构建"的第二个来源(**不用它推版本号**)
7555
+ const token = client.versionTokens.length ? chalk.gray(` · 自报构建 ${client.versionTokens.join('、')}`) : ''
7556
+ console.log(chalk.green(` ✓ 运行时加载 ${client.version}`) + chalk.gray(` (${client.loadedDirs[0]})`) + token)
7557
+ } else {
7558
+ // **说"未知"而不是"没问题"**:取不到就说取不到,别给人一个假的安心
7559
+ console.log(chalk.gray(` ○ 版本未知 — ${client.note}`))
7560
+ }
7561
+ for (const dead of client.unusableVersionDirs) {
7562
+ console.log(chalk.yellow(` ! 残留版本目录 ${dead.dir}:只剩 ${dead.files} 个文件(没有 Weixin.dll)`))
7563
+ console.log(chalk.gray(' 指向它的加载会失败;如果客户端起不来,先看这里'))
7564
+ }
7565
+ // `update.data` 在场时上面那个版本**未必**是加载的那个 —— 这句话要跟着它一起出现
7566
+ for (const caveat of client.caveats) {
7567
+ console.log(chalk.yellow(` ⚠ ${caveat}`))
7568
+ }
7569
+ if (client.dataDirs.length) {
7570
+ console.log(chalk.gray(` · 客户端自报数据目录: ${client.dataDirs.join('、')}`))
7571
+ if (dataDirMatchesConfig === false) {
7572
+ // 不一致 = 两边可能不是同一份库(本机数据目录还有 D 盘软链,这条已经按真身比过)
7573
+ console.log(chalk.yellow(' ⚠ 与配置里那个数据库推出来的根**不是同一份** —— 先确认你在读的是客户端正在写的那份'))
7574
+ }
7575
+ }
7576
+ const crashes = client.crashRecords.reports + client.crashRecords.records
7577
+ if (crashes > 0) {
7578
+ const when = client.crashRecords.newest ? client.crashRecords.newest.slice(0, 16).replace('T', ' ') : '时间读不到'
7579
+ console.log(chalk.gray(` · 客户端崩溃记录 ${crashes} 份(最近 ${when})—— 客户端崩过时数据读不出来,先看这条`))
7580
+ }
7581
+
7582
+ // 7. Assistant (第二大脑)
6706
7583
  console.log(chalk.white('\n第二大脑 Agent:'))
6707
7584
  const aiKey = configService.get('deepseekApiKey')
6708
7585
  const aiBase = configService.get('aiBaseUrl')
@@ -6923,7 +7800,8 @@ async function showInteractiveMenu() {
6923
7800
  const { spawn } = await import('child_process')
6924
7801
  const pipeline = join(resolvePackageRoot(), 'scripts', 'pipeline.py')
6925
7802
  console.log(chalk.cyan(`\n📰 正在生成 ${dateStr} 公众号日报...\n`))
6926
- const child = spawn(getPythonCommand(), [pipeline, '--date', dateStr, '--interest', 'AI', '--skip-wiki'], {
7803
+ const child = spawn(getPythonCommand(), [pipeline, '--date', dateStr, '--interest', 'AI'], {
7804
+ windowsHide: true,
6927
7805
  stdio: 'inherit',
6928
7806
  env: pythonProcessEnv(apiKey),
6929
7807
  })