#!/usr/bin/env node
import { Command } from 'commander'
import chalk from 'chalk'
import inquirer from 'inquirer'
import { basename, join } from 'path'
import { existsSync, readFileSync, statSync, writeFileSync } from 'fs'
import { homedir } from 'os'
import { SYNC_SCHEMA, SYNC_SOURCE, syncStateStore } from '../src/services/syncState.js'
import { SyncRangeRequiredError, runSync } from '../src/services/syncService.js'
import { probeCursorReadiness } from '../src/services/cursorProbe.js'
import { planSetup, runSetup } from '../src/services/setupVenv.js'
import { planImportQchat, runImportQchat, listImports, readImportedSession } from '../src/services/qchatImport.js'
import { dbPathService } from '../src/core/dbPathService.js'
import { keyService } from '../src/core/keyService.js'
import { NtCore } from '../src/core/ntCore.js'
import { configService } from '../src/services/configService.js'
import { redactForReport } from '../src/services/diagnosticReport.js'
import { renderDiagnosticReport } from '../src/services/diagnosticReport.js'
import { chatService } from '../src/services/chatService.js'
import { emptyMessagesNote, looksLikeTalkerId } from '../src/services/messageQuery.js'
import { exportService } from '../src/services/exportService.js'
import type { ExportResult } from '../src/services/exportService.js'
import { writeEvidencePackage } from '../src/services/evidenceService.js'
import { resolveTalker as resolveTalkerCore } from '../src/utils/talkerUtils.js'
import { getPythonCommand } from '../src/utils/python.js'
import { createPythonProcessEnv, safeSubprocessError } from '../src/utils/pythonProcessEnv.js'
import { DateRangeError, parseLocalDateOrIso, resolveExportDateRange } from '../src/utils/dateRange.js'
import { resolvePackageRoot as resolvePackageRootFrom } from '../src/utils/packageRoot.js'
import { resolveOutputRoot } from '../src/utils/outputRoot.js'
import { WechatMessageService } from '../src/services/wechatMessageService.js'
import { whitelistService, MAX_TEXT_LENGTH } from '../src/services/whitelistService.js'
import { authorizeOutbound, parseOutboundPolicy, performOutbound } from '../src/services/outboundSend.js'
import { applyDerivedNtKeys, enableFavorites, detectFavDbPath } from '../src/services/initKeyService.js'
import type { ChatSession } from '../src/types.js'

/**
 * 解出这一轮该用哪个 AI key。
 *
 * **必须只有这一处。** 2026-11-15 换到千问时踩过：`daily` 与另一条路径各自写了一份
 * `get('deepseekApiKey')`，只改了一处，于是 `daily` 把 DeepSeek 的 key 发去了
 * 通义端点——373 篇摘要全部 HTTP 401，而失败被主循环的兜底吞掉，产物看起来
 * "有摘要、但主题全变成默认值"。这种错法不报错，只能靠人肉对比两天的 md 才发现。
 *
 * 顺序：显式参数 > 环境变量 > （配了 aiBaseUrl 时）aiApiKey > deepseekApiKey。
 * 配了 aiBaseUrl 却没配 aiApiKey 时仍退回 deepseekApiKey——那是"换端点不换 key"
 * 的老用法，不能因为新增字段就把它弄坏。
 */
function resolveAiKey(explicit?: string): string {
  const picked = explicit || process.env.DEEPSEEK_API_KEY
    || (configService.get('aiBaseUrl') ? configService.get('aiApiKey') : '')
    || configService.get('deepseekApiKey') || ''
  return picked
}

import { disabledIds, describeSkill, readSkillBody, scanSkills, skillRoots, skillState } from '../src/services/assistantSkills.js'
import { assistantScenes, validateSceneId, type Scene } from '../src/services/assistantScenes.js'
import {
  addPlugin,
  checkPluginHealth,
  lintCards,
  listPlugins,
  pluginRoot,
  registryFile,
  removePlugin,
  runKnowledgeSource,
  setPluginFlags,
} from '../src/services/pluginService.js'
import { detectWechatClient, reportedDataDirs, samePath } from '../src/services/wechatClient.js'
import { WECHAT_VERIFIED, compareWechatVersions, describeCompatVerdict, describeUnknownVersionReason } from '../src/services/wechatCompat.js'

const program = new Command()

function resolvePackageRoot(): string {
  return resolvePackageRootFrom(import.meta.url)
}

/**
 * Version reported by `--version` and `capabilities`.
 *
 * Read from package.json instead of written here. A literal has to be updated
 * by hand on every release, and when that is forgotten `--version` lies about
 * what is installed - which is exactly what happened: the 1.6.0 package
 * shipped a hardcoded `1.5.1`, so a user's bug report could not be told apart
 * from a stale install, and diagnosing it needed a clean install to disprove.
 */
function resolveCliVersion(): string {
  try {
    const pkg = JSON.parse(readFileSync(join(resolvePackageRoot(), 'package.json'), 'utf8'))
    return String(pkg.version || '0.0.0')
  } catch {
    return '0.0.0'
  }
}

const CLI_VERSION = resolveCliVersion()

function pythonProcessEnv(apiKey?: string, variable = 'DEEPSEEK_API_KEY'): NodeJS.ProcessEnv {
  return createPythonProcessEnv(apiKey ? { [variable]: apiKey } : {})
}

function parseCliInteger(value: unknown, field: string, minimum: number, maximum: number, json = false): number {
  const parsed = Number(value)
  if (Number.isInteger(parsed) && parsed >= minimum && parsed <= maximum) return parsed
  const error = `${field} 必须是 ${minimum}-${maximum} 的整数`
  if (json) console.log(JSON.stringify({ success: false, code: 'INVALID_ARGUMENT', field, error }))
  else console.log(chalk.red(error))
  process.exit(1)
}

/** 校验一个"只能是这几个值之一"的参数。与 `parseCliInteger` / `requireCliDate` 同一约定：
 * `--json` 时错误也得是一份 JSON —— 否则机器调用方在 stdout 上拿到的是彩色散文，解析不了。
 *
 * 抽成一个是有理由的：`--line` 的校验原本在四个命令里各写了一遍，其中三处只打散文（`vault rag`、
 * 顶层 `search`、`chat`）—— 同一份判断写四遍，就有三遍漏掉了 `--json` 分支。
 * 错误文案由 choices 生成，保证与原来逐字一致（'line 必须是 wiki、chat 或 all'）。
 */
function requireCliChoice(value: unknown, choices: readonly string[], field: string, json = false): string {
  const text = String(value)
  if (choices.includes(text)) return text
  const error = `${field} 必须是 ${choices.slice(0, -1).join('、')} 或 ${choices[choices.length - 1]}`
  if (json) console.log(JSON.stringify({ success: false, code: 'INVALID_ARGUMENT', field, error }))
  else console.log(chalk.red(error))
  process.exit(1)
}

function requireCliDate(value: string, json = false): string {
  try {
    parseLocalDateOrIso(value)
    if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) throw new DateRangeError('INVALID_DATE', '日期无效')
    return value
  } catch {
    if (json) console.log(JSON.stringify({ success: false, code: 'INVALID_DATE', field: 'date' }))
    else console.log(chalk.red('date 必须是有效的 YYYY-MM-DD 日期'))
    process.exit(1)
  }
}

async function runConfirmedPythonMutation(options: {
  action: string
  script: string
  args: string[]
  cliOptions: { dryRun?: boolean; yes?: boolean; json?: boolean }
  preview: Record<string, unknown>
  confirmationMessage: string
  apiKey?: string
  apiKeyVariable?: string
  timeout?: number
}): Promise<void> {
  const preview = { success: true, dryRun: true, action: options.action, ...options.preview }
  if (options.cliOptions.dryRun) {
    if (options.cliOptions.json) console.log(JSON.stringify(preview))
    else console.log(chalk.cyan(options.confirmationMessage.replace(/^确认/, '预览：')))
    return
  }
  if (!options.cliOptions.yes) {
    if (options.cliOptions.json) {
      console.log(JSON.stringify({ ...preview, success: false, dryRun: false, code: 'CONFIRMATION_REQUIRED' }))
      process.exit(1)
    }
    const { confirmed } = await inquirer.prompt([{
      type: 'confirm',
      name: 'confirmed',
      message: options.confirmationMessage,
      default: false,
    }])
    if (!confirmed) {
      console.log(chalk.gray('已取消'))
      return
    }
  }

  const { execFile } = await import('child_process')
  const { promisify } = await import('util')
  try {
    const { stdout } = await promisify(execFile)(getPythonCommand(), [options.script, ...options.args], {
      timeout: options.timeout || 120_000,
      maxBuffer: 50 * 1024 * 1024,
      env: pythonProcessEnv(options.apiKey, options.apiKeyVariable || 'DEEPSEEK_API_KEY'),
    })
    if (options.cliOptions.json) console.log(JSON.stringify({ success: true, action: options.action }))
    else console.log(stdout)
  } catch (error) {
    if (options.cliOptions.json) {
      console.log(JSON.stringify({ success: false, code: 'PYTHON_MUTATION_FAILED', action: options.action, error: safeSubprocessError(error) }))
    } else {
      console.error(chalk.red(`\n✗ ${safeSubprocessError(error)}`))
    }
    process.exit(1)
  }
}

async function openLocalUrl(url: string): Promise<void> {
  const { spawn } = await import('child_process')
  const command = process.platform === 'win32' ? 'rundll32.exe' : process.platform === 'darwin' ? 'open' : 'xdg-open'
  const args = process.platform === 'win32' ? ['url.dll,FileProtocolHandler', url] : [url]
  const child = spawn(command, args, { detached: true, stdio: 'ignore', windowsHide: true })
  child.unref()
}

async function getDailyReaderStatus(port: number): Promise<{ running: boolean; date: string | null }> {
  try {
    const response = await fetch(`http://127.0.0.1:${port}/api/status`, { signal: AbortSignal.timeout(500) })
    const status = await response.json() as { ok?: boolean; service?: string; date?: string }
    const running = response.ok && status.ok === true && status.service === 'weflow-daily-reader'
    return { running, date: running && status.date ? status.date : null }
  } catch {
    return { running: false, date: null }
  }
}

async function startDetachedDailyReader(script: string, date: string, port: number): Promise<{
  success: boolean
  started: boolean
  alreadyRunning?: boolean
  code?: string
}> {
  const existing = await getDailyReaderStatus(port)
  if (existing.running) {
    if (existing.date === date) return { success: true, started: false, alreadyRunning: true }
    return { success: false, started: false, code: 'DAILY_READER_PORT_IN_USE' }
  }

  const dateDir = join(resolveOutputRoot(), 'biz-daily', date)
  if (!existsSync(dateDir)) return { success: false, started: false, code: 'DAILY_READER_DATE_NOT_FOUND' }

  const { spawn } = await import('child_process')
  const child = spawn(getPythonCommand(), [script, '--date', date, '--port', String(port)], {
    detached: true,
    stdio: 'ignore',
    windowsHide: true,
    env: pythonProcessEnv(),
  })
  let spawnFailed = false
  child.once('error', () => { spawnFailed = true })

  for (let attempt = 0; attempt < 30; attempt++) {
    if (spawnFailed || child.exitCode !== null) break
    const status = await getDailyReaderStatus(port)
    if (status.running && status.date === date) {
      child.unref()
      return { success: true, started: true }
    }
    await new Promise(resolve => setTimeout(resolve, 100))
  }

  if (child.exitCode === null && !child.killed) child.kill()
  return { success: false, started: false, code: 'DAILY_READER_START_FAILED' }
}

/**
 * 尝试从 WeFlow 桌面版配置中读取已保存的密钥
 */
function tryReadWeFlowKey(): string | null {
  const candidates = [
    join(homedir(), 'AppData', 'Roaming', 'WeFlow', 'WeFlow-config.json'),
    join(homedir(), 'AppData', 'Roaming', 'weflow', 'WeFlow-config.json'),
    join(homedir(), '.weflow', 'config.json'),
  ]

  for (const configPath of candidates) {
    try {
      if (!existsSync(configPath)) continue
      const raw = readFileSync(configPath, 'utf8')
      const config = JSON.parse(raw)

      // WeFlow 使用 electron-store，decryptKey 可能是明文或加密的
      let key = config.decryptKey || ''
      // 如果是 lock: 前缀，说明是加密的，无法直接使用
      if (typeof key === 'string' && key.startsWith('lock:')) {
        continue
      }
      // 如果是 safe: 前缀，说明是 safeStorage 加密的，也无法直接使用
      if (typeof key === 'string' && key.startsWith('safe:')) {
        continue
      }
      // 明文 key
      if (typeof key === 'string' && key.length === 64) {
        return key
      }

      // 检查 wxidConfigs 中的 key
      const wxidConfigs = config.wxidConfigs || {}
      for (const [_wxid, cfg] of Object.entries(wxidConfigs) as [string, any][]) {
        const cfgKey = cfg.decryptKey || ''
        if (typeof cfgKey === 'string' && cfgKey.length === 64 && !cfgKey.startsWith('lock:') && !cfgKey.startsWith('safe:')) {
          return cfgKey
        }
      }
    } catch {
      continue
    }
  }
  return null
}

/**
 * CLI 包装的 talker 解析 (wxid / 昵称 / 备注名 / 序号)。
 * 委托给 src/utils/talkerUtils 的核心实现，外加 chalk 友好输出。
 */
async function resolveTalker(input: string, quiet = false, nonInteractive = false): Promise<string> {
  try {
    const result = await resolveTalkerCore(input, { interactive: !nonInteractive })
    // 显示解析结果（已知格式跳过打印）
    if (!quiet && !input.startsWith('wxid_') && !input.includes('@chatroom') && !input.includes('@openim')) {
      const isNum = /^\[?\d+\]?$/.test(input)
      const sessions = await chatService.listSessions(undefined, 50)
      const match = sessions.find(s => s.username === result)
      if (match) {
        const prefix = isNum ? `序号[${input.replace(/[\[\]]/g, '')}] ` : ''
        console.log(chalk.gray(`  → ${prefix}${match.displayName} (${match.username})`))
      }
    }
    return result
  } catch (e: any) {
    if (quiet) {
      console.log(JSON.stringify({ success: false, code: 'TALKER_RESOLUTION_FAILED', error: e.message }))
      process.exit(1)
    }
    console.log(chalk.red(`\n❌ ${e.message}\n`))
    process.exit(1)
  }
}

/**
 * 较新微信版本派生模式: 内存中不再有 x'<key><salt>' 文本, 内存扫描匹配不到密钥。
 * 各库密钥改为从全库 passphrase 派生, 逻辑见 src/services/initKeyService.ts。
 */

program
  .name('weflow-cli')
  .description('WeFlow CLI - 微信聊天记录命令行查询与导出工具')
  .version(CLI_VERSION)

program
  .command('capabilities')
  .description('输出 AI 可调用的功能能力清单')
  .option('--json', '输出 JSON 格式')
  .action((opts) => {
    const data = {
      schema: 'weflow-capabilities/v1',
      version: CLI_VERSION,
      // D-130：本包最后用真实数据验证过的微信版本（单一事实源 wechatCompat.ts）。
      // check 的判定也从同一处读；发布清单要求 CHANGELOG 每版记录（来源就是这里）。
      compatibility: {
        wechat: {
          verifiedVersion: WECHAT_VERIFIED.version,
          verifiedAt: WECHAT_VERIFIED.verifiedAt,
        },
      },
      read: {
        sessions: { cli: 'sessions --json', mcp: 'wechat.list_sessions' },
        messages: { cli: 'messages <talker> --json', mcp: 'wechat.export_messages' },
        contacts: { cli: 'contacts --json', mcp: 'wechat.list_contacts', localIdentifiersInModelContext: false },
        exports: {
          cli: 'export <talker> <json|txt|html|excel>',
          mcp: 'wechat.export_messages',
          versionedContract: 'weflow-message/v1',
          rawContractPreserved: true,
          coverage: ['requestedFrom', 'requestedTo', 'requestedLimit', 'returned', 'mayHaveMore', 'oldestCreateTime', 'newestCreateTime'],
          incrementalRead: {
            mode: 'overlapping-time-window',
            stableCursor: false,
            // D-027 的另一半：光写 false 是句结论，这里把 false → true 的**路径**
            // 摊开。probe 指向的那条命令会实测 NT 数据侧判据（采样有界、结果里
            // 自带 exhaustive=false）；backends 里的字段是代码事实，改读取器时同步改。
            cursorReadiness: {
              probe: 'sync cursor-probe --json',
              criteria: [
                'stable-identity: 每条消息都有非零且不重复的 server_id（缺失时身份退化为按分片的 localId+createTime，不能跨分片续读）',
                'globally-comparable-order: 跨分片合并的顺序键可比（现在是 createTime+localId，localId 不跨分片可比）',
                'window-pushdown: 时间窗下推进读取（现在只有 NT 后端）',
                'coverage-report: 后端能报告本次读取是否完整（现在只有 NT 的分片报告）',
                'every-backend: 上述各项在所有消息后端同时成立（D-027 的总门）',
              ],
              backends: {
                'nt': { identity: 'server_id（退化为 localId+createTime）', windowPushdown: true, coverageReport: true, liveProbe: true },
                'raw-sqlite-4x': { identity: 'MsgSvrID 列被读取、覆盖率未实测', windowPushdown: false, coverageReport: false, liveProbe: false },
                'wcdb-4x': { identity: 'server_id 随原生 API 返回、未实测', windowPushdown: false, coverageReport: false, liveProbe: false },
                'legacy-3x': { identity: 'MsgSvrID 列被读取、覆盖率未实测', windowPushdown: false, coverageReport: false, liveProbe: false },
              },
              advertisedWhen: 'every backend reports true on every criterion above',
            },
          },
        },
        favorites: {
          cli: 'fav list --json',
          export: 'fav export <markdown|json> --json-result --output <local-file>',
          mcp: 'wechat.search_favorites',
        },
        configuration: { cli: 'config show --json', secretsIncluded: false },
        accessControl: {
          whitelist: 'whitelist list --json',
          blacklist: 'blacklist list --json',
          sensitiveLocalIdentifiers: true,
        },
        moments: {
          timeline: 'sns timeline --json',
          users: 'sns users --json',
          stats: 'sns stats --json',
        },
        daily: {
          preview: 'daily --no-ai --dry-run --json',
          execute: 'daily --no-ai --yes --json',
          confirmationRequired: true,
          logs: 'stderr',
          result: 'stdout',
        },
        dailyReader: { cli: 'daily-server --status --json' },
        dailyStats: { cli: 'daily-stats --json' },
        // 只读、纯本地、不调模型。**故意没有 mcp 那一栏**（D-062）：它给的是关于第三方的推断
        // ——谁在被冷落、你会失去谁 —— 所以不进助手、不进 MCP、不喂模型。
        bonds: { cli: 'bonds --json', mcp: null, leavesTheMachine: false },
        // `check --report` 是同一份事实的**给人版**（已脱敏、可直接贴给 AI 或 issue），
        // 所以它跟 `--json` 并列在这里：外部程序按这条能力去找"怎么拿诊断"，不该只知道 JSON 那条。
        diagnostics: { cli: 'check --json', report: 'check --report', leavesTheMachine: false },
        todos: { cli: 'todos list --json' },
        // 2026-09-29 三个界面对齐时新开的读取能力（D-058）。逐个写清它会不会出境，
        // 因为其中两个会——`fetch_article` 白名单 + 逐跳复检，`search_public` 没有任何守卫。
        review: { cli: 'review ...', mcp: 'wechat.get_review', writesReport: true },
        concepts: { cli: 'wiki ...', mcp: 'wechat.get_concepts' },
        articleFetch: {
          cli: null,   // 没有对应的 CLI 命令：它本来就是为模型准备的读取能力
          mcp: 'wechat.fetch_article',
          network: true,
          allowlist: 'https only, host must be exactly mp.weixin.qq.com',
          redirectsReValidatedPerHop: true,
          confirmationRequired: false,
        },
        publicArticleSearch: {
          mcp: 'wechat.search_public',
          network: true,
          // **这条是如实的**：搜索词由模型决定、发到第三方搜索页，没有白名单也没有预览。
          // 它在该项目的边界内是被明确接受的残余风险（D-058），这里不能写成"无出境"。
          allowlist: null,
          modelAuthoredQueryLeavesTheMachine: true,
          confirmationRequired: false,
        },
        articleFormatting: { mcp: 'wechat.format_article', cli: null, writesNothing: true, network: false },
        themes: { mcp: 'wechat.list_themes', writesNothing: true },
        wikiLint: { cli: 'wiki lint --json', mcp: 'wechat.lint_wiki', readsLocalChat: false, writesNothing: true },
        skillCheck: { cli: 'skill check --json', mcp: 'wechat.check_skills', writesNothing: true },
        awaiting: {
          cli: 'awaiting --yes',
          preview: 'awaiting --dry-run --json',
          readsLocalChat: true,
          invokesAI: true,
          writesNothing: true,
          confirmationRequired: true,
        },
        draft: {
          cli: 'draft <会话> --yes --json',
          preview: 'draft <会话> --dry-run --json',
          readsLocalChat: true,
          invokesAI: true,
          // **它不发送任何东西**：只产出候选文本，回不回由人决定。
          // 这条要能被机器读到——`sendsNothing` 比 `writesNothing` 更要紧。
          writesNothing: true,
          sendsNothing: true,
          confirmationRequired: true,
        },
        knowledge: { cli: 'search <query> --yes --json', preview: 'search <query> --dry-run --json', output: 'json', mcp: 'wechat.search_articles' },
      },
      primitives: {
        decide: {
          cli: 'decide --request <file> --yes | decide --over <glob> --ask <text> --yes',
          preview: 'decide --dry-run',
          // 两条路的读法**不一样**，所以不能只写一个 false：
          // --request 完全由调用方给，--over 会读匹配到的本地文件。
          readsLocalData: { request: false, over: true },
          invokesAI: true,
          sendsCallerProvidedState: true,
          confirmationRequired: true,
          mcpExposed: false,
          whyNotMcp: 'an MCP client must not be able to drive local outbound calls',
        },
      },
      workflows: {
        initialization: {
          preview: 'init --dry-run --json',
          execute: 'init',
          interactiveRequired: true,
          machineExecutionAllowed: false,
          previewExposesPaths: false,
        },
        evidencePackage: { cli: 'evidence <talker> --json --non-interactive', localOnly: true },
        sync: {
          preview: 'sync run <talker> --dry-run --json',
          execute: 'sync run <talker> --yes --json',
          status: 'sync status [<talker>] --json',
          verify: 'sync verify <talker> --json',
          confirmationRequired: true,
          readsLocalData: true,
          invokesAI: false,
          sideEffects: ['local-checkpoint-file'],
          stateSchema: 'weflow-sync/v1',
          jobSchema: 'weflow-job/v1',
          stateLocation: 'local-user-config-dir',
          previewResolvesTalker: false,
          previewExposesLocalPaths: false,
          // D-027: a stable cursor must be backed by every database backend
          // before it is advertised. This exposes overlapping windows only.
          stableCursor: false,
          coverageValues: ['complete', 'unverified', 'partial'],
          partialCompletesSuccessfully: false,
        },
        aiAnalysis: {
          preview: 'evidence-review <talker> --dry-run --json',
          execute: 'evidence-review <talker> --yes --json',
          explicitOptIn: true,
          cloudRequiresAllowCloud: true,
          confirmationRequired: true,
        },
        messaging: {
          preview: 'send <target> <message> --dry-run --json',
          execute: 'send <target> <message> --yes --json',
          confirmationRequired: true,
          channel: 'official-bot-existing-conversation',
        },
        todoMutations: {
          preview: 'todos <done|undone|rm> <id> --dry-run --json',
          execute: 'todos <done|undone|rm> <id> --yes --json',
          confirmationRequired: true,
        },
        skills: {
          list: 'skill list [--query <q>] --json',
          show: 'skill show <id> --json',
          check: 'skill check --json',
          readOnly: true,
          // 技能是**资料**，不是插件：助手只把它当提示词/正文读，不执行里面的脚本，
          // 也不因为装了技能就多出任何工具（P4 验收标准：扩展读不到配置与数据库）。
          installsAnything: false,
          executesSkillCode: false,
          grantsTools: false,
          directories: 'skillDirs config (default: ~/.claude/skills, ~/.weflow-cli/skills)',
          disable: 'config set skillDisabled <id,...>（技能自己也能写 enabled: false）',
        },
        scenes: {
          list: 'scene list --json',
          show: 'scene show <id> --json',
          preview: 'scene <add|remove|enable|disable|bind|unbind> … --dry-run --json',
          execute: 'scene <add|remove|enable|disable|bind|unbind> … --yes --json',
          confirmationRequired: true,
          // 场景只改**本机提示词预设**，不发消息、不读聊天、不调模型
          readsLocalChat: false,
          invokesAI: false,
          sendsNothing: true,
          stateLocation: 'local-user-config-dir',
          stateSchema: 'weflow-scenes/v1',
          modelWritable: false,
        },
        accessControlMutations: {
          preview: '<whitelist|blacklist> <add|rm> <target> --dry-run --json',
          execute: '<whitelist|blacklist> <add|rm> <target> --yes --json',
          confirmationRequired: true,
          sensitiveLocalIdentifiers: true,
        },
        secretConfiguration: {
          preview: 'config set-env <key> <environment> --dry-run --json',
          execute: 'config set-env <key> <environment> --yes --json',
          favoriteKeyPreview: 'fav set-key --from-env <environment> --dry-run --json',
          favoriteKeyExecute: 'fav set-key --from-env <environment> --yes --json',
          valuesInArguments: false,
          confirmationRequired: true,
        },
        databaseKeyReset: {
          preview: 'config forget-keys --dry-run --json',
          cli: 'config forget-keys --yes --json',
          confirmationRequired: true,
        },
        assistantDaemon: {
          status: 'assistant status --json',
          preview: 'assistant <start|stop> --dry-run --json',
          execute: 'assistant <start|stop> --yes --json',
          confirmationRequired: true,
        },
        localPanel: {
          status: 'panel --status --json',
          ask: 'panel --ask "<text>" --yes --json [--scene <id>]',
          preview: 'panel --dry-run --json',
          execute: 'panel --yes --json',
          confirmationRequired: true,
          opensLocalWindow: true,
          loopbackOnly: true,
          // 关掉窗口**不会**停掉助手——这件事必须能被机器读到，别让调用方以为退出即结束
          keepsAssistantRunningAfterClose: true,
        },
        messageChannelAuthentication: {
          loginPreview: 'login-wechat --dry-run --json',
          loginExecute: 'login-wechat --yes',
          loginInteractiveRequired: true,
          logoutPreview: 'logout-wechat --dry-run --json',
          logoutExecute: 'logout-wechat --yes --json',
          confirmationRequired: true,
        },
        interactiveKeyCapture: {
          previews: ['dbkey --dry-run --json', 'sns capture-key --dry-run --json'],
          executes: ['dbkey --yes', 'sns capture-key --yes'],
          interactiveRequired: true,
          machineExecutionAllowed: false,
        },
        foregroundMessageProcesses: {
          previews: ['listen --dry-run --json', 'assistant run --dry-run --json'],
          executes: ['listen --yes', 'assistant run --yes'],
          interactiveRequired: true,
          machineExecutionAllowed: false,
        },
        vaultSync: {
          preview: 'vault sync --dry-run --json',
          execute: 'vault sync --yes --json',
          confirmationRequired: true,
          previewExposesFileNames: false,
          resultExposesRemote: false,
        },
        vaultInitialization: {
          preview: 'vault init --path <local-directory> --dry-run --json',
          execute: 'vault init --path <local-directory> --yes --json',
          confirmationRequired: true,
          previewExposesPaths: false,
          overwritesManagedFiles: true,
        },
        semanticIndex: {
          preview: 'search-index --dry-run --json',
          execute: 'search-index --yes --json',
          fullRebuild: 'search-index --full --yes --json',
          confirmationRequired: true,
          sendsTextToEmbeddingProvider: true,
        },
        knowledgePipeline: {
          preview: 'pipeline run --no-ai --dry-run --json',
          execute: 'pipeline run --no-ai --yes --json',
          confirmationRequired: true,
          supportsSourceFilter: true,
          aiCanBeDisabled: true,
        },
        vaultContentMutations: {
          commands: ['vault enrich', 'vault notes', 'vault tag', 'vault sync-weread', 'vault promote ideas', 'vault promote all', 'wiki compile'],
          previewFlag: '--dry-run --json',
          executeFlag: '--yes --json',
          confirmationRequired: true,
          aiRequiresExplicitOptIn: true,
        },
        dailyFavoriteMutations: {
          commands: ['daily favorites sync', 'daily favorites add', 'daily favorites remove'],
          previewFlag: '--dry-run --json',
          executeFlag: '--yes --json',
          confirmationRequired: true,
          previewExposesArticleNames: false,
        },
        dailyReader: {
          status: 'daily-server --status --json',
          previewStart: 'daily-server --dry-run --json',
          executeStart: 'daily-server --yes --json',
          confirmationRequired: true,
          loopbackOnly: true,
        },
        reportGeneration: {
          commands: ['report', 'review', 'annual-report', 'chat-stats'],
          previewFlag: '--dry-run --json',
          executeFlag: '--yes --json',
          confirmationRequired: true,
          resultExposesContent: false,
        },
        todoExtraction: {
          preview: 'todos extract --days <n> --dry-run --json',
          execute: 'todos extract --days <n> --yes --json',
          confirmationRequired: true,
          sendsSelectedChatToAi: true,
          resultExposesTodoText: false,
        },
        vaultRag: {
          preview: 'vault rag <question> --dry-run --json',
          execute: 'vault rag <question> --yes --json',
          confirmationRequired: true,
          sendsSelectedKnowledgeToAi: true,
          questionInProcessArguments: false,
        },
        semanticQuery: {
          preview: 'search <query> --dry-run --json',
          execute: 'search <query> --yes --json',
          confirmationRequired: true,
          mayUseCloudEmbedding: true,
          queryInProcessArguments: false,
        },
        ragChat: {
          preview: 'chat <question> --dry-run --json',
          execute: 'chat <question> --yes --json',
          confirmationRequired: true,
          sendsSelectedKnowledgeToAi: true,
          questionInProcessArguments: false,
          interactiveModeMachineExecutionAllowed: false,
        },
        diagnostics: {
          accountScan: 'scan --json',
          assistantLogStatus: 'assistant log --json',
          sensitiveValuesInStatus: false,
        },
        mcpConfiguration: {
          read: 'mcp-config',
          previewWrite: 'mcp-config --output <file> --dry-run --json-result',
          executeWrite: 'mcp-config --output <file> --yes --json-result',
          confirmationRequired: true,
        },
        destructiveClear: {
          commands: ['config clear', 'whitelist clear', 'blacklist clear', 'audit clear'],
          previewFlag: '--dry-run --json',
          confirmationFlag: '--yes',
          confirmationRequired: true,
          previewExposesEntries: false,
        },
      },
      safety: {
        localByDefault: true,
        aiDisabledByDefaultForExport: true,
        unknownMessageTypesPreserved: true,
        nonInteractiveTalkerResolution: true,
        // **这个名字曾经是假的**：MCP 那张表不是手写的只读清单，而是**助手工具表减去
        // save_memory**，所以里面早就有写文件的 `export_chat` 和会把图片交给模型的
        // `look_at_image`。如实改成 false，并把真正有出境的几样单独列出来（下面这个对象）。
        // 读这一位的调用方按 false 走保守分支即可。
        mcpDefaultReadOnly: false,
        mcpSurface: {
          // 这句话**手工补过两回**：先是只写 save_memory，后来补上 `look_at_image`，第三次加
          // `set_todo_status` 时又漏了 —— 每次都是"表变了、这句话没变"，而且没有任何东西会红。
          // 现在名字**逐个与 `MCP_EXCLUDED` 对齐**，并由 `test/assistant-tools.test.ts` 从源码里核：
          // 那张表再加一项而这里没跟，测试就红（同下面 requiresConfirm 的处理方式）。
          derivedFrom: 'assistant tools minus save_memory, look_at_image and set_todo_status',
          writesFiles: ['export_chat'],
          // 逐个核实过（脚本里确实调云端模型的那些）：
          // who_owes_reply/search_chats → Jev；search_semantic → 阿里云百炼嵌入 + Jev 重排；draft_reply → Jev + DeepSeek。
          // `look_at_image` **不在这里**：它靠侧信道把图交给助手自己的模型，而 MCP 只取工具返回的文本，
          // 图没人接、回话却写着"你能看到它了"——所以它已经从 MCP 那张表里排除了（见 MCP_TOOL_DEFS）。
          callsCloudModels: ['who_owes_reply', 'search_chats', 'search_semantic', 'draft_reply'],
          // 机器调用**默认只给预览**、必须显式 confirm 才出境的那些（MCP 独有的边界）。
          // **这里是四个，不是"只有 draft_reply"**：逐个读 handler 才发现那四个工具里
          // 写的是同一句 `if (ctx.requiresConfirm && args.confirm !== true)`（1010/1041/1094/1170）。
          // 原先只列了 draft_reply，而测试是照着这个字段的值抄的，于是两处一起错、谁都没红。
          // 现在测试改成**从源码里数**（见 test/assistant-tools.test.ts），改一处不同步就会红。
          requiresConfirm: ['search_chats', 'who_owes_reply', 'draft_reply', 'search_semantic'],
        },
        mcpMessageLimit: { default: 100, max: 1000 },
      },
    }
    console.log(JSON.stringify(data, null, 2))
  })

// ==================== setup（自管 Python venv） ====================
// Issues 里最大的两类环境噪音（PowerShell 策略 / 商店占位 python 的 9009）里，
// 后者的根因是"没有能 import sqlcipher3 的 Python"。这条命令一次性解决：
// 在 ~/.weflow-cli/venv 建 venv 并装 requirements，之后 getPythonCommand() 优先用它。
program
  .command('setup')
  .description('创建自管 Python 虚拟环境 (~/.weflow-cli/venv) 并安装依赖；之后所有 Python 工作流优先用它')
  .option('--dry-run', '只看计划：venv 位置、用哪个 Python 建、装哪些包（不动任何东西）')
  .option('--yes', '跳过交互确认（机器执行路径）')
  .option('--recreate', '删除现有 venv 后重建（默认已存在则复用）')
  .option('--with-3x', '同时安装 requirements-3x.txt（微信 3.x 旧版密钥提取）')
  .option('--with-voice', '同时安装 requirements-voice.txt（本机语音转写）')
  .option('--non-interactive', '禁止交互提问；与 --yes 配合用于脚本')
  .option('--json', '输出 JSON 格式')
  .action(async (opts) => {
    let plan
    try {
      plan = await planSetup({ recreate: !!opts.recreate, with3x: !!opts.with3x, withVoice: !!opts.withVoice })
    } catch (error: any) {
      if (opts.json) { console.log(JSON.stringify({ success: false, code: 'SETUP_PLAN_FAILED', error: String(error?.message || error).slice(0, 200) })); process.exit(1) }
      console.error(chalk.red(`✗ 计划失败: ${error?.message || error}`))
      process.exit(1)
    }

    if (opts.dryRun || !opts.yes) {
      const preview = {
        success: true,
        dryRun: true,
        action: 'setup.venv',
        venvDir: plan.venvDir,
        venvExists: existsSync(plan.venvDir),
        creator: plan.creator,
        requirementFiles: plan.requirementFiles,
        packages: plan.packages,
        substitutions: plan.substitutions,
        recreate: plan.recreate,
        createsUnder: plan.createsUnder,
        network: plan.network,
        // 密钥/数据库一个都不碰：这条命令只写 ~/.weflow-cli/venv
        readsLocalData: false,
      }
      if (opts.dryRun) {
        if (opts.json) { console.log(JSON.stringify(preview)); return }
        console.log(chalk.cyan('\nsetup 计划（--dry-run，不执行）'))
        console.log(chalk.gray(`  venv: ${plan.venvDir}${existsSync(plan.venvDir) ? '（已存在，默认复用）' : ''}`))
        console.log(chalk.gray(`  创建者: ${plan.creator ?? '未找到可运行的 Python（先装 Python 3.10+）'}`))
        console.log(chalk.gray(`  安装: ${plan.packages.join(' ')}`))
        for (const sub of plan.substitutions) console.log(chalk.gray(`  替换: ${sub}`))
        console.log(chalk.gray('  网络请求: pip 访问 PyPI；不读聊天数据、不碰密钥\n'))
        return
      }
      if (opts.json) {
        console.log(JSON.stringify({ ...preview, success: false, dryRun: false, code: 'CONFIRMATION_REQUIRED' }))
        process.exit(1)
      }
      if (process.env.WEFLOW_NON_INTERACTIVE || opts.nonInteractive) {
        console.error(chalk.red('✗ 非交互模式需要 --yes'))
        process.exit(1)
      }
      const { confirmed } = await inquirer.prompt([{
        type: 'confirm',
        name: 'confirmed',
        message: `将在 ${plan.venvDir} 创建虚拟环境并安装 ${plan.packages.length} 个包（pip 需要访问 PyPI）。继续吗？`,
        default: false,
      }])
      if (!confirmed) {
        console.log(chalk.gray('已取消'))
        return
      }
    }

    const result = await runSetup(plan, (line) => console.log(chalk.gray(`  ${line}`)))
    if (opts.json) {
      console.log(JSON.stringify(result))
      if (!result.success) process.exit(1)
      return
    }
    console.log(chalk.cyan('\nPython 环境 setup'))
    for (const step of result.steps) {
      console.log(`  ${step.ok ? '✓' : '✗'} ${step.name}${step.detail ? chalk.gray(` — ${step.detail}`) : ''}`)
    }
    if (result.success) {
      console.log(chalk.green(`\n完成。之后的 Python 工作流会优先用: ${result.venvPython}`))
      console.log(chalk.gray('  下一步: weflow-cli check 验证环境，weflow-cli init 初始化本地数据'))
    } else {
      console.log(chalk.red(`\n失败（${result.error ?? '见上方步骤'}）。把 --json 输出贴到 issue 里最好排查。`))
      process.exit(1)
    }
  })

// ==================== import（外部 IM 数据导入，D-129） ====================
// 边界是**文件契约**：读 qchat-cli `qce export --format json` 的产物，归一化落到
// output/imports/qq/，之后 chat-notes / search-index 就能把 QQ 会话当普通聊天线处理。
const importCmd = program
  .command('import')
  .description('导入外部 IM 的聊天记录（当前支持 qchat-cli 的 JSON 导出），并入本地知识管道')

importCmd
  .command('qchat <path>')
  .description('导入 qchat-cli 的 JSON 导出（单文件或目录；按 messageId 去重，重复导入安全）')
  .option('--dry-run', '只看会导入什么：文件、会话、条数（不写任何东西）')
  .option('--yes', '确认执行（写本地存储 output/imports/qq/）')
  .option('--own-id <qq>', '可选：自己的 QQ 号，用来标 isSend（不给则该字段缺省为未知）')
  .option('--json', '输出 JSON 格式')
  .action(async (inputPath: string, opts) => {
    let plan
    try {
      plan = planImportQchat(inputPath)
    } catch (error: any) {
      if (opts.json) { console.log(JSON.stringify({ success: false, code: 'IMPORT_PLAN_FAILED', error: String(error?.message || error).slice(0, 200) })); process.exit(1) }
      console.error(chalk.red(`✗ 计划失败: ${error?.message || error}`))
      process.exit(1)
    }

    const preview = {
      success: true,
      dryRun: true,
      action: 'import.qchat',
      input: inputPath,
      files: plan.files.map(f => ({
        file: basename(f.file), ok: f.ok,
        ...(f.reason ? { reason: f.reason } : {}),
        sessions: f.sessions.map(s => ({ id: s.id, name: s.name, type: s.type, messages: s.messages })),
      })),
      sessionsFound: plan.sessionsFound,
      messagesTotal: plan.messagesTotal,
      storeRoot: plan.storeRoot,
      ownIdProvided: Boolean(opts.ownId),
      readsLocalData: true,
      writesLocalStore: true,
      invokesAI: false,
      network: false,
    }
    if (opts.dryRun) {
      if (opts.json) { console.log(JSON.stringify(preview)); return }
      console.log(chalk.cyan('\nimport qchat 计划（--dry-run，不执行）'))
      console.log(chalk.gray(`  存储: ${plan.storeRoot}`))
      for (const f of plan.files) {
        if (f.ok) {
          for (const sess of f.sessions) {
            console.log(chalk.gray(`  ✓ ${basename(f.file)} → 会话「${sess.name}」（${sess.type}，${sess.messages} 条）`))
          }
        } else {
          console.log(chalk.yellow(`  ✗ ${basename(f.file)} — ${f.reason}`))
        }
      }
      if (opts.ownId) console.log(chalk.gray(`  isSend 判定: 按自己的 QQ 号 ${String(opts.ownId).slice(0, 4)}…`))
      console.log('')
      return
    }
    if (!opts.yes) {
      if (opts.json) {
        console.log(JSON.stringify({ ...preview, success: false, dryRun: false, code: 'CONFIRMATION_REQUIRED' }))
        process.exit(1)
      }
      console.error(chalk.red(`✗ 需要确认：将把 ${plan.messagesTotal} 条消息写入本地存储 ${plan.storeRoot}。加 --yes 执行`))
      process.exit(1)
    }

    const result = runImportQchat(inputPath, opts.ownId ? String(opts.ownId) : undefined)
    if (opts.json) {
      console.log(JSON.stringify(result))
      if (!result.success) process.exit(1)
      return
    }
    if (!result.success) {
      console.error(chalk.red(`✗ 没有可导入的文件（${result.filesSkipped} 个被跳过，原因见 --dry-run）`))
      process.exit(1)
    }
    console.log(chalk.cyan('\n导入完成'))
    for (const sess of result.sessions) {
      console.log(chalk.green(`  ✓ 「${sess.name}」共 ${sess.total} 条（新增 ${sess.added}、更新 ${sess.updated}、原样 ${sess.unchanged}）`))
    }
    if (result.filesSkipped) console.log(chalk.yellow(`  ⚠ 跳过 ${result.filesSkipped} 个不认识的文件`))
    console.log(chalk.gray(`  存储: ${result.storeRoot}`))
    console.log(chalk.gray('  下一步: weflow-cli import list 查看；chat-notes --source qq 产知识卡；search-index --include-imports 进搜索'))
  })

importCmd
  .command('list')
  .description('列出已导入的会话')
  .option('--json', '输出 JSON 格式')
  .action((opts) => {
    const entries = listImports()
    if (opts.json) { console.log(JSON.stringify({ success: true, sessions: entries })); return }
    if (!entries.length) {
      console.log(chalk.gray('\n还没有导入任何会话。先跑 weflow-cli import qchat <qchat 导出文件>'))
      return
    }
    console.log(chalk.cyan(`\n已导入 ${entries.length} 个会话`))
    for (const e of entries) {
      const span = e.newestCreateTime
        ? `${new Date((e.oldestCreateTime ?? 0) * 1000).toLocaleDateString('zh-CN')} ~ ${new Date(e.newestCreateTime * 1000).toLocaleDateString('zh-CN')}`
        : '（无消息）'
      console.log(`  「${e.name}」（${e.type}，${e.messages} 条，${span}）`)
    }
    console.log('')
  })

importCmd
  .command('show <sessionId>')
  .description('读回一个已导入会话的消息（验证导入）')
  .option('-n, --limit <n>', '只看最近 N 条（0 = 全部）', '20')
  .option('--json', '输出 JSON 格式')
  .action((sessionId: string, opts) => {
    const limit = Number(opts.limit)
    if (!Number.isInteger(limit) || limit < 0) {
      if (opts.json) { console.log(JSON.stringify({ success: false, code: 'INVALID_ARGUMENT', error: 'limit 必须是 ≥ 0 的整数' })); process.exit(1) }
      console.error(chalk.red('✗ limit 必须是 ≥ 0 的整数'))
      process.exit(1)
    }
    const data = readImportedSession(sessionId, limit)
    if (!data) {
      if (opts.json) { console.log(JSON.stringify({ success: false, code: 'IMPORT_SESSION_NOT_FOUND' })); process.exit(1) }
      console.error(chalk.red(`✗ 没有会话 ${sessionId} 的导入记录`))
      process.exit(1)
    }
    if (opts.json) { console.log(JSON.stringify({ success: true, ...data })); return }
    console.log(chalk.cyan(`\n「${data.session.name}」共 ${data.messages.length} 条（存储里全部 ${listImports().find(e => e.id === sessionId)?.messages ?? '?'} 条）`))
    for (const m of data.messages) {
      const who = m.isSend === undefined ? m.senderName : (m.isSend ? '我' : m.senderName)
      console.log(chalk.gray(`[${new Date(m.createTime * 1000).toLocaleString('zh-CN')}] ${who}(${m.messageType}): `) + m.parsedContent.slice(0, 80))
    }
    console.log('')
  })

// ==================== init ====================
program
  .command('capture-passphrase')
  .description('（Linux / macOS）自动捕获微信共享口令：会等你在微信里退出登录、再重新登录')
  .option('--timeout <sec>', '等待登录的秒数', '300')
  .option('--db-dir <path>', '库目录；缺省自动找微信的默认位置')
  .option('--json', '输出机器可读结果')
  .option('--no-sudo', '提权被拒时不自动重试 sudo（不想让本工具提权时用）')
  .action(async (opts) => {
    if (process.platform !== 'linux' && process.platform !== 'darwin') {
      console.log(chalk.yellow('这条命令用于 Linux / macOS：Windows 的密钥提取由 init 自动完成。'))
      process.exit(1)
    }
    if (process.platform === 'darwin') {
      const { spawn: spawnMac } = await import('child_process')
      const macScript = join(resolvePackageRoot(), 'scripts', 'macos_capture.py')
      const macArgs = [macScript, '--timeout',
        String(parseCliInteger(opts.timeout, 'timeout', 30, 3600, !!opts.json))]
      if (opts.json) macArgs.push('--json')
      macArgs.push('--write-config')
      const macChild = spawnMac(getPythonCommand(), macArgs, { stdio: 'inherit', windowsHide: true })
      macChild.on('exit', (code) => process.exit(code || 0))
      return
    }
    const { spawn } = await import('child_process')
    const script = join(resolvePackageRoot(), 'scripts', 'linux_capture.py')
    const args = [script, '--timeout', String(parseCliInteger(opts.timeout, 'timeout', 30, 3600, !!opts.json))]
    if (opts.dbDir) args.push('--db-dir', opts.dbDir)
    if (opts.json) args.push('--json')
    if (opts.sudo === false) args.push('--no-sudo')
    args.push('--write-config')
    const child = spawn(getPythonCommand(), args, { stdio: 'inherit', windowsHide: true })
    child.on('exit', (code) => process.exit(code || 0))
  })

program
  .command('init')
  .description('自动检测微信数据目录并提取解密密钥')
  .option('-p, --path <path>', '微信数据目录、账号目录或 db_storage 目录')
  .option('--search-drives', '跨本机磁盘按标准微信目录名搜索（耗时较长）')
  .option('--full-scan', '目录名被修改时，使用深度磁盘结构扫描（耗时较长）')
  .option('--refresh', '忽略已有配置并重新初始化')
  .option('--test-missing-keys', '仅在本次运行模拟密钥缺失，不修改已保存配置')
  .option('--passphrase <hex>', '直接用这串共享口令初始化（64 位 hex），跳过自动提取；也可用环境变量 WEFLOW_PASSPHRASE')
  .option('--dry-run', '仅预览，不连接数据库、扫描磁盘、捕获密钥或修改配置')
  .option('--json', '输出机器可读预览；实际初始化必须在交互终端执行')
  .action(async (opts) => {
    const preview = {
      success: true,
      dryRun: true,
      action: 'initialize',
      interactiveRequired: true,
      configured: configService.isConfigured(),
      refreshRequested: Boolean(opts.refresh),
      explicitPathProvided: Boolean(opts.path),
      driveSearchRequested: Boolean(opts.searchDrives),
      fullScanRequested: Boolean(opts.fullScan),
      missingKeyTestRequested: Boolean(opts.testMissingKeys),
      mayScanProcessMemory: true,
      mayWriteConfiguration: true,
    }
    if (opts.dryRun) {
      if (opts.json) console.log(JSON.stringify(preview))
      else console.log(chalk.cyan('初始化预览：可能检查数据库、搜索数据目录、捕获密钥并更新本地配置。'))
      return
    }
    if (opts.json) {
      // 这条路径最容易让人误以为"已经在初始化了"：--json 只输出预览。
      // 先记账再退出，`check` 才能告诉用户"上次 init 根本没真正开始"。
      const { recordInitFailure } = await import('../src/services/initState.js')
      recordInitFailure(1, '--json 只输出预览，不会真正初始化；去掉 --json 在交互终端里运行')
      console.log(JSON.stringify({ ...preview, success: false, dryRun: false, code: 'INTERACTIVE_REQUIRED' }))
      process.exit(1)
    }
    // 从这里开始，任何非 0 退出都会把"最后一条提示"记下来（见 initState.trackInitRun）。
    {
      const { trackInitRun } = await import('../src/services/initState.js')
      trackInitRun()
    }
    console.log(chalk.cyan('🔧 WeFlow CLI 初始化\n'))

    if (opts.testMissingKeys) {
      configService.maskDatabaseKeysForTesting()
      console.log(chalk.yellow('测试模式：本次运行忽略已保存的数据库密钥。'))
      console.log(chalk.gray('测试失败不会清除磁盘上的现有密钥配置。\n'))
    }

    if (!opts.refresh && !opts.path && !opts.testMissingKeys && configService.isConfigured()) {
      const existingConnection = await chatService.connect()
      if (existingConnection.success) {
        console.log(chalk.green('✓ 已验证现有本地配置可用，跳过密钥捕获。'))
        console.log(chalk.gray('  可直接运行 weflow-cli sessions、messages 等命令。'))
        console.log(chalk.gray('  仅在微信迁移、切换账号或访问失败后运行 weflow-cli init --refresh。'))
        return
      }
      console.log(chalk.yellow('  已发现现有配置，但无法验证数据库访问；继续重新初始化。'))
    }

    // Step 0: 检测微信版本
      console.log(chalk.yellow('步骤 0/3: 检测微信版本...'))
      const version = await keyService.detectWeChatVersion()
      // detectWeChatVersion() 只回答“3.x / 4.x / null”，拿不到具体版本号；
      // 具体版本要走 detectWechatClient()（Windows 读进程，Linux 读 uh.dat）。
      const clientFacts = await detectWechatClient()
      const shownVersion = clientFacts.version

      if (shownVersion) {
        console.log(chalk.green(`✓ 检测到微信 ${shownVersion} 版本`))
      } else if (version) {
        console.log(chalk.green(`✓ 检测到微信 ${version} 版本`))
      } else {
        // 注意：null 不等于“微信没在运行”。把“探测不到”讲成“客户端没开”
        // 是 D-145 记的假错误（2026-11-01 在 Linux 上实测踩到）。
        console.log(chalk.gray(`  ${describeUnknownVersionReason({ platform: process.platform }).reason}`))
        const existingPath = configService.get('dbPath')
        if (existingPath && existsSync(existingPath)) {
          console.log(chalk.green(`  使用已配置的数据目录: ${existingPath}`))
        }
      }

    if (version === '3.x') {
      // ====== 3.x 初始化 ======
      console.log(chalk.yellow('\n步骤 1/3: 提取 3.x 数据库密钥...'))
      const result = await keyService.extract3xKey((msg) => {
        console.log(chalk.gray(`  ${msg}`))
      })

      if (!result.success || !result.key) {
        console.log(chalk.red(`\n✗ 密钥提取失败: ${result.error}`))
        console.log(chalk.gray('\n解决方案:'))
        console.log(chalk.gray('  1. 确保 WeChat 3.x (WeChat.exe) 已登录'))
        console.log(chalk.gray('  2. 确保 Python + pywxdump 已安装'))
        console.log(chalk.gray('  3. 或手动指定密钥: weflow-cli config set decryptKey3x <64位密钥>'))
        process.exit(1)
      }

      const msgDir = result.msgDir || ''
      const wxDir = result.wxDir || ''
      const wxid = result.wxid || ''

      configService.set('decryptKey3x', result.key)
      configService.set('dataVersion', '3.x')

      // 查找 MSG0.db
      const msg0Path = join(msgDir, 'Multi', 'MSG0.db')
      if (existsSync(msg0Path)) {
        configService.set('dbPath3x', msg0Path)
        console.log(chalk.green(`✓ 数据库: ${msg0Path}`))
      }

      if (wxid) configService.set('wxid', wxid)
      if (wxDir) configService.set('dbPath', wxDir)

      console.log(chalk.green('\n✓ 密钥获取成功!'))
      console.log(chalk.cyan('\n=============================='))
      console.log(chalk.cyan('初始化完成! (3.x 模式)'))
      console.log(chalk.cyan('=============================='))
      console.log(chalk.white(`数据目录: ${wxDir}`))
      console.log(chalk.white(`消息数据库: ${msg0Path}`))
      console.log(chalk.white(redactForReport(`账号: ${wxid}`)))
      console.log(chalk.white('密钥: 已安全保存'))

    } else {
      // ====== 4.x 初始化 (原有逻辑) ======
      console.log(chalk.yellow('\n步骤 1/3: 检测微信数据目录...'))
      const configuredPath = opts.path || configService.get('dbPath')
      const configuredDataRoot = configuredPath
        ? dbPathService.resolveDataRoot(configuredPath)
        : null
      if (configuredPath && !configuredDataRoot) {
        console.log(chalk.yellow('  已检查指定路径，但未识别到有效的微信数据结构；继续自动搜索...'))
      }
      if (!configuredDataRoot) {
        console.log(chalk.gray('  正在自动检查常见的微信数据目录位置...'))
      }
      if (!configuredDataRoot && opts.searchDrives) {
        console.log(chalk.gray('  将跨本机磁盘按标准目录名搜索，过程可能需要较长时间...'))
      }
      if (!configuredDataRoot && opts.fullScan) {
        console.log(chalk.gray('  目录名未命中时将继续进行深度结构扫描，过程可能需要较长时间...'))
      }
      const detected = configuredDataRoot
        ? { success: true, path: configuredDataRoot, source: 'known' as const }
        : await dbPathService.autoDetect({
            searchDrives: opts.searchDrives, fullScan: opts.fullScan,
            // **先问客户端自己**（它命令行上带着 `--wechat-files-path`）：这是唯一"来自
            // 客户端自己"的来源，其余都是按目录名猜。取不到就是空数组，走老路。
            hintedRoots: await reportedDataDirs(),
          })
      if (!detected.success || !detected.path) {
        console.log(chalk.red('✗ 未检测到微信数据目录'))
        if (!opts.searchDrives && !opts.fullScan) {
          console.log(chalk.gray('  已完成常见位置搜索。'))
          console.log(chalk.cyan('  下一步: weflow-cli init --search-drives'))
          console.log(chalk.gray('  该模式会跨本机磁盘按 xwechat_files 或 WeChat Files 名称搜索。'))
        } else if (!opts.fullScan) {
          console.log(chalk.gray('  已完成标准目录名的跨盘搜索。'))
          console.log(chalk.cyan('  下一步: weflow-cli init --full-scan'))
          console.log(chalk.gray('  此模式会继续按目录结构扫描可访问磁盘，耗时较长。'))
        } else {
          console.log(chalk.gray('  已完成深度结构扫描，仍未找到可识别的数据目录。'))
          console.log(chalk.cyan('  请指定数据根、账号目录或 db_storage 目录:'))
          console.log(chalk.cyan('  weflow-cli init --path "D:\\微信数据目录"'))
        }
        process.exit(1)
      }
      // **说清是怎么找到的**：来源不同，可信度与后续排查都不同（"客户端自己说的"最硬）
      const howFound = detected.source === 'client' ? '（客户端自己报的）'
        : detected.source === 'scan' ? '（全盘扫描找到的）' : ''
      console.log(chalk.green(redactForReport(`✓ 检测到数据目录: ${detected.path}${howFound}`)))
      configService.set('dbPath', detected.path)
      configService.set('dataVersion', '4.x')

      // Step 2: 扫描账号
      console.log(chalk.yellow('\n步骤 2/3: 扫描微信账号...'))
      const wxids = dbPathService.scanWxidCandidates(detected.path)
      if (wxids.length === 0) {
        console.log(chalk.red('✗ 未找到微信账号目录'))
        process.exit(1)
      }

      const selectedWxid = wxids[0]
      console.log(chalk.green(`✓ 找到 ${wxids.length} 个账号`))
      for (const w of wxids) {
        const marker = w === selectedWxid ? chalk.green(' → ') : '   '
        const nickname = w.nickname ? ` (${w.nickname})` : ''
        console.log(redactForReport(`${marker}${w.wxid}${nickname}`))
      }
      configService.set('wxid', selectedWxid.wxid)

      // Step 3: 提取密钥
      console.log(chalk.yellow('\n步骤 3/3: 提取数据库解密密钥...'))

      // **先看 Python 在不在**（Windows）：它决定"读库"这一整步能不能做。
      // 以前不看，于是 Python 不可用时还要先等 120 秒 hook 超时，然后把用户引向
      // "退出微信重试"——而真正的原因（商店占位程序 / 缺 sqlcipher3）一个字都没提。
      // 2026-10-19 用一台"PATH 里没有 python"的机器实测，2 分钟换来一条误导性建议。
      //
      // 2026-11-05 修：这里原本写作 `process.platform === 'win32' && !opts.testMissingKeys`，
      // 于是 `--test-missing-keys` 把探测整段跳过，而 `pythonUsable` 的初值在 Windows 上是
      // false（`process.platform !== 'win32'`）——结果这个**测试标志**在 Windows 上
      // 必然报"缺 Python"并以 exit 1 退出，看起来像环境坏了。探测本身只是跑一次
      // `python --version`，与是否屏蔽密钥无关，所以照常执行。
      let pythonUsable = process.platform !== 'win32'
      if (process.platform === 'win32') {
        try {
          const { execFileSync } = await import('node:child_process')
          execFileSync(getPythonCommand(), ['--version'], { windowsHide: true, stdio: 'ignore', timeout: 5000 })
          pythonUsable = true
        } catch {
          pythonUsable = false
          console.log(chalk.red('  ✗ 没有可用的 Python —— 读微信库这一步跑不起来'))
          console.log(chalk.gray('    NT 数据库扫描与密钥派生都靠它（需要 Python 3.10+ 且能 import sqlcipher3）。'))
          console.log(chalk.gray('    Windows 上最常见的原因是只装了应用商店的 python 占位程序：'))
          console.log(chalk.gray('    在终端里运行 `python --version`，能打出版本号才算装对。'))
          console.log(chalk.gray('    跑 `weflow-cli check --report` 可以看到完整判定（那段话可直接贴给 AI）。'))
        }
      }

      // 优先尝试从 WeFlow 配置读取
      console.log(chalk.gray('  尝试从 WeFlow 桌面版配置读取...'))
      // 口令来源优先级：显式 --passphrase > WEFLOW_PASSPHRASE > hook/已配置。
      // 为什么要有这条路：hook 在新版本上可能失败，用户此时没有任何自助入口，
      // 只能卡在"取不到密钥"（issue #9）。有了口令就能直接派生，与 Linux 的
      // `capture-passphrase` 之后那一步等价。
      const cliPassphrase = String(opts.passphrase || process.env.WEFLOW_PASSPHRASE || '').trim()
      if (cliPassphrase && !/^[0-9a-fA-F]{64}$/.test(cliPassphrase)) {
        console.log(chalk.red('  ✗ --passphrase / WEFLOW_PASSPHRASE 必须是 64 位十六进制'))
        process.exit(1)
      }
      let extractedKey = opts.testMissingKeys ? (cliPassphrase || '') : (cliPassphrase || tryReadWeFlowKey())
      if (cliPassphrase) {
        console.log(chalk.gray('  使用你提供的口令（跳过自动提取）'))
      }
      let linuxNtKey = ''
      /** 密钥是本次从 hook 捕获的, 还是沿用已有的 - 摘要要说准, 不能一律报"获取成功" */
      let keyCaptured = false

      if (extractedKey) {
        console.log(chalk.green('  ✓ 从 WeFlow 配置读取到密钥'))
      } else if (process.platform === 'linux') {
        // Linux：/proc 内存扫描提取 NT 密钥（需 root 或 CAP_SYS_PTRACE）
        console.log(chalk.gray('  Linux 模式：扫描微信进程内存提取 NT 密钥...'))
        const ntScan = await NtCore.scan(detected.path)

        if (ntScan.success && ntScan.matched && ntScan.matched.length > 0) {
          console.log(chalk.green(`  ✓ 从内存中匹配到 ${ntScan.matched.length} 个数据库密钥`))
          const primaryDb = ntScan.matched.find((db: any) => db.name === 'message/message_0.db')
            || ntScan.matched.sort((a: any, b: any) => b.size - a.size)[0]
          configService.set('ntDbPath', primaryDb.path)
          configService.set('ntKey', primaryDb.key)
          configService.set('ntSalt', primaryDb.salt)
          console.log(chalk.green(`  ✓ 主数据库: ${primaryDb.name} (${(primaryDb.size / 1024 / 1024).toFixed(1)}MB)`))

          const contactDb = ntScan.matched.find((db: any) => db.name === 'contact/contact.db')
          if (contactDb) {
            configService.set('contactDbPath', contactDb.path)
            configService.set('contactKey', contactDb.key)
            configService.set('contactSalt', contactDb.salt)
            console.log(chalk.green(`  ✓ 联系人数据库: ${contactDb.name}`))
          }
          const snsDb = ntScan.matched.find((db: any) => db.name === 'sns/sns.db')
          if (snsDb) {
            configService.set('snsDbPath', snsDb.path)
            configService.set('snsKey', snsDb.key)
            configService.set('snsSalt', snsDb.salt)
            console.log(chalk.green(`  ✓ 朋友圈数据库: ${snsDb.name}`))
          }
          linuxNtKey = primaryDb.key
        } else {
          // 较新微信版本: /proc 内存扫描同样匹配不到 x'...' 文本, 从已配置 passphrase 派生
          const favPass = configService.get('favPassphrase') || ''
          const scanDbs = (ntScan as any).databases || []
          const wxidDbs = scanDbs.filter((d: any) => d.wxid === selectedWxid.wxid)
          const deriveDbs = wxidDbs.length > 0 ? wxidDbs : scanDbs
          let derivedOk = false
          if (favPass && deriveDbs.length > 0) {
            console.log(chalk.gray('  内存扫描未发现密钥文本 (较新微信密钥体系), 尝试从 passphrase 派生...'))
            derivedOk = await applyDerivedNtKeys(favPass, deriveDbs, (l) => console.log(l))
            if (derivedOk) linuxNtKey = configService.get('ntKey') || ''
          }
          if (!derivedOk) {
            const err = ntScan.error || '未匹配到数据库密钥'
            console.log(chalk.red(`  ✗ ${err}`))
            console.log(chalk.gray('\n  Linux 密钥提取方案：'))
            if (err.includes('PERMISSION_DENIED')) {
              console.log(chalk.gray('  1. 一次性授权（推荐）: sudo setcap cap_sys_ptrace=ep $(which python3)'))
              console.log(chalk.gray('  2. 或用 sudo 运行: sudo weflow-cli init'))
              console.log(chalk.gray('     （sudo 后需修复配置属主: sudo chown -R $(id -u):$(id -g) ~/.weflow-cli）'))
            } else {
              console.log(chalk.gray('  0. 一条命令自动捕获（会等你在微信里退出登录、再重新登录）：'))
              console.log(chalk.gray('       weflow-cli capture-passphrase --write-config'))
              console.log(chalk.gray('  1. 确保微信已启动并完成登录（登录后才会在内存中缓存密钥）'))
              console.log(chalk.gray('  2. 确保以 root 或 CAP_SYS_PTRACE 运行（sudo setcap cap_sys_ptrace=ep $(which python3)）'))
                console.log(chalk.gray('  3. 较新微信版本（4.1.12.26+）改用「共享口令 + 每分片派生」，'
                  + '内存里不再有 key/salt 成对字面量，自动提取在结构上不会命中。'))
                console.log(chalk.gray('     拿到口令后先验证再配置：'))
                console.log(chalk.gray('       python3 scripts/nt_decrypt.py verify-passphrase-all --passphrase <64位hex>'))
                console.log(chalk.gray('       weflow-cli fav set-key --passphrase <64位hex> && weflow-cli init'))
                console.log(chalk.gray('  4. 不想处理密钥：直接用外部订阅源出日报'))
                console.log(chalk.gray('       python3 scripts/pipeline.py --rss-feeds-file output/rss-feeds.json'))
                console.log(chalk.gray('  5. 任何时候想知道现状: python3 scripts/nt_decrypt.py key-status'))
            }
            process.exit(1)
          }
        }
      } else if (!pythonUsable) {
        // Python 不可用时**不去等 hook**：就算 hook 抓到了密钥，Step 4 的扫描/派生照样跑不起来，
        // 而那 120 秒的等待只会把用户引向"退出微信重试"这种无效动作。
        const fallback = configService.get('favPassphrase') || configService.get('decryptKey') || ''
        if (fallback) {
          console.log(chalk.gray('  跳过 hook 等待：已配置的密钥会原样保留，但要先修好 Python 才读得动'))
          extractedKey = fallback
        } else {
          console.log(chalk.red('\n✗ 这台机器现在无法读取微信数据库（缺 Python），因此没有可用密钥'))
          console.log(chalk.gray('\n按顺序做：'))
          console.log(chalk.gray('  1) 装一个真正的 Python 3.10+，确认 `python --version` 能打出版本号'))
          console.log(chalk.gray('  2) `pip install sqlcipher3`'))
          console.log(chalk.gray('  3) 重新 `weflow-cli init`'))
          console.log(chalk.gray('  卡住时跑 `weflow-cli check --report`，那段文字可直接贴给 AI 或贴到 issue'))
          process.exit(1)
        }
      } else if (process.platform !== 'win32') {
        // macOS：自动提取不可用，引导手动提供密钥
        console.log(chalk.yellow('  ⚠ 当前平台无法自动提取密钥（自动提取支持 Windows/Linux）'))
        console.log(chalk.gray('\n  macOS 手动配置方式：'))
        console.log(chalk.gray('  1. 用第三方工具从运行中的微信进程提取密钥（如 wechat-dump-rs）'))
        console.log(chalk.gray('  2. 或从 Windows 机器上的 WeFlow 配置复制密钥'))
        console.log(chalk.gray('  3. 写入配置: weflow-cli config set decryptKey <64位密钥>'))
        console.log(chalk.gray('  4. 数据目录与账号已完成配置，设置密钥后即可使用 sessions/messages 等命令'))
        process.exit(1)
      } else {
        // hook 只在**登录那一瞬**触发。所以要不要等，取决于微信现在在不在跑：
        //   · 已在运行  → 用户早就登录了，hook 永远不会再触发，等满 2 分钟纯属浪费
        //                 （2026-10-19 用一个空配置实测：每次 init 都白等）
        //   · 没在运行  → 这正是 README「三分钟上手」第 2 步要求的姿势（关掉微信再 init，
        //                 然后按提示启动并登录）。人要打开客户端、等它起来、扫码/点确认，
        //                 30 秒根本不够，**必须留足**，否则按文档操作的人会被那句
        //                 "hook 没抓到" 误导。所以就按文档给满 120 秒。
        let keyResult: { success: boolean; key?: string; error?: string } = { success: false }
        if (version) {
          console.log(chalk.gray('  微信已在运行：hook 只在登录那一瞬触发，不再等待，直接尝试扫描/派生'))
        } else {
          console.log(chalk.cyan('\n  请现在启动微信并登录（登录那一瞬会自动抓取密钥）'))
          console.log(chalk.cyan('  最多等 2 分钟；不启动也没关系，之后会继续尝试 NT 扫描 / passphrase 派生\n'))
          keyResult = await keyService.waitForKey(120000, (msg) => {
            console.log(chalk.gray(`  ${msg}`))
          })
        }

        if (keyResult.success && keyResult.key) {
          extractedKey = keyResult.key
          keyCaptured = true
        } else {
          // hook 只在登录瞬间触发; 微信已登录时捕获不到 → 回退到已有密钥。
          // decryptKey 也必须算数: init 成功时写入的就是它, 而 favPassphrase
          // 仅在收藏库存在且验证通过时才会被设置。只看 favPassphrase 会让
          // `init --refresh` 在一把完全可用的密钥面前报「密钥提取失败」——
          // 而那正是 CLI 自己在微信迁移后建议用户执行的命令。
          const fallback = configService.get('favPassphrase') || configService.get('decryptKey') || ''
          if (fallback) {
            console.log(chalk.gray('  Hook 未捕获到密钥 (微信已登录时不再触发密钥函数)'))
            console.log(chalk.gray('  检测到已配置的密钥, 沿用它并重新验证各库...'))
            extractedKey = fallback
          } else {
            // **不退出**：hook 只在"登录那一瞬"触发，而一个正常用户装完工具时微信早就登录了，
            // 于是这条 120 秒的等待**必然**超时。以前这里 process.exit(1)，用户就被卡在
            // 「退出微信后重新运行 init」——而下一步（Step 4 的 NT 扫描 / 从 passphrase 派生）
            // 才是新版本真正能拿到密钥的地方，却永远不会被执行（2026-10-19 用空配置实测）。
            // 现在改成继续往下走：拿得到就成功，拿不到由结尾统一判"未完成"。
            console.log(chalk.yellow('\n  Hook 没抓到密钥（它只在登录那一瞬触发，已登录时不会再有）'))
            console.log(chalk.gray('  继续尝试 NT 扫描 / passphrase 派生 —— 这是新版本主要的取密钥方式...'))
          }
        }
      }

      if (extractedKey) {
        configService.set('decryptKey', extractedKey)
        if (keyCaptured) console.log(chalk.green('\n✓ 密钥获取成功!'))
        else if (pythonUsable) console.log(chalk.green('\n✓ 已沿用配置中的密钥 (本次未重新捕获)'))
        // 缺 Python 时**不能说"已沿用"**：那句话在这里会被读成"密钥没问题"，
        // 而下面紧接着就会说"密钥未就绪"，两句自相矛盾（2026-10-19 实跑看到）。
        else console.log(chalk.yellow('\n· 配置里的密钥原样保留，但**这次验证不了**（缺 Python）——它可能仍然可用'))
      } else {
        // 空密钥时不能说"配置完成"：下一句就是"密钥未就绪"，两句打架。
        console.log(chalk.yellow('\n· 本次没有拿到密钥，继续尝试 NT 扫描 / passphrase 派生'))
      }

      // Step 4: 尝试扫描 NT 格式数据库 (xwechat_files)
      // 即使检测到传统路径，也可能存在 NT 格式数据库
      // 进入这里已经确认是 4.x 初始化流程。不要依赖步骤 0 的 version：
      // 微信可能是在 init 等待期间才启动，初始 version 会保持为 null。
      // Linux 分支已在步骤 3 完成配置，跳过。
      // 这次 init 到底有没有**取得可用的密钥** —— 只有它决定结尾能不能说"初始化完成"。
      // 扫描失败 + 沿用旧密钥 = 一次看着成功、实际什么也读不到的初始化：2026-10-18 一位用户
      // 的 init 打在 "NT scan failed (exit 9009)" 上（Python 是商店占位程序），结尾照样报
      // "初始化完成！"、"密钥: 已安全保存"，然后 sessions 一条都没有。
      let ntReady = process.platform === 'linux'   // Linux 分支已在步骤 3 配好
      if (process.platform !== 'linux') {
        console.log(chalk.yellow('\n步骤 4/4: 扫描 NT 格式数据库...'))
        console.log(chalk.gray('  正在从微信内存中匹配数据库密钥...'))

        const ntScanRoot = configService.get('dbPath') || detected.path
        const ntResult = await NtCore.scan(ntScanRoot)
        if (ntResult.success && ntResult.matched && ntResult.matched.length > 0) {
          console.log(chalk.green(`  ✓ 找到 ${ntResult.matched.length} 个 NT 数据库`))

          // 优先选择 message_0.db (主聊天数据库)
          let primaryDb = ntResult.matched.find((db: any) => db.name === 'message/message_0.db')
          if (!primaryDb) {
            // 按大小降序排序，选择最大的数据库
            primaryDb = ntResult.matched.sort((a: any, b: any) => b.size - a.size)[0]
          }

          if (primaryDb) {
            ntReady = true
            configService.set('ntDbPath', primaryDb.path)
            configService.set('ntKey', primaryDb.key)
            configService.set('ntSalt', primaryDb.salt)
            console.log(chalk.green(`  ✓ 主数据库: ${primaryDb.name} (${(primaryDb.size / 1024 / 1024).toFixed(1)}MB)`))

            // 检查 contact.db 是否已匹配
            const contactDb = ntResult.matched.find((db: any) => db.name === 'contact/contact.db')
            if (contactDb) {
              configService.set('contactDbPath', contactDb.path)
              configService.set('contactKey', contactDb.key)
              configService.set('contactSalt', contactDb.salt)
              console.log(chalk.green(`  ✓ 联系人数据库: ${contactDb.name} (${(contactDb.size / 1024 / 1024).toFixed(1)}MB)`))
            }

            // 检查 sns.db (朋友圈) 是否已匹配
            const snsDb = ntResult.matched.find((db: any) => db.name === 'sns/sns.db')
            if (snsDb) {
              configService.set('snsDbPath', snsDb.path)
              configService.set('snsKey', snsDb.key)
              configService.set('snsSalt', snsDb.salt)
              console.log(chalk.green(`  ✓ 朋友圈数据库: ${snsDb.name} (${(snsDb.size / 1024 / 1024).toFixed(1)}MB)`))
            }

            // 显示所有匹配的数据库
            for (const db of ntResult.matched) {
              const marker = db === primaryDb || db === contactDb || db === snsDb ? chalk.green('  → ') : '     '
              console.log(chalk.gray(`${marker}${db.name} (${(db.size / 1024 / 1024).toFixed(1)}MB)`))
            }
          }

          // 收藏库与聊天库共用 passphrase, 顺手启用收藏功能
          const passForFav = extractedKey || configService.get('decryptKey') || ''
          if (passForFav) await enableFavorites(passForFav, ntResult.databases || [])
        } else {
          console.log(chalk.gray(`  NT 数据库扫描: ${ntResult.error || '未找到匹配的数据库'}`))

          // 较新微信版本: 内存中不再有 x'<key><salt>' 文本, 内存扫描匹配不到密钥,
          // 从 DLL hook 拿到的全库 passphrase 派生各库密钥并逐一验证
          const passphrase = extractedKey || configService.get('decryptKey') || ''
          const allDbs = ntResult.databases || []
          const wxidDbs = allDbs.filter((db: any) => db.wxid === selectedWxid.wxid)
          const deriveDbs = wxidDbs.length > 0 ? wxidDbs : allDbs
          let derivedMessage = false
          if (passphrase && deriveDbs.length > 0) {
            console.log(chalk.gray('  检测到较新微信密钥体系 (内存中无密钥文本), 从 passphrase 派生各库密钥...'))
            derivedMessage = await applyDerivedNtKeys(passphrase, deriveDbs, (l) => console.log(l))
          }

          if (derivedMessage) {
            ntReady = true
            console.log(chalk.green('  ✓ 派生模式初始化成功 (聊天/联系人/朋友圈库已配置)'))
          } else {
            // 即使密钥未匹配，仍尝试自动发现 sns.db 路径和盐值
            if (ntResult.databases && ntResult.databases.length > 0) {
              const snsDb = ntResult.databases.find((db: any) => db.name === 'sns/sns.db')
              if (snsDb) {
                configService.set('snsDbPath', snsDb.path)
                configService.set('snsSalt', snsDb.salt)
                console.log(chalk.yellow(`  ⚠ 发现朋友圈数据库: ${snsDb.name} (${(snsDb.size / 1024 / 1024).toFixed(1)}MB)`))
                console.log(chalk.gray('    密钥未匹配，请运行: weflow-cli sns capture-key'))
              }
            }
            console.log(chalk.gray('  提示: 可以稍后运行 weflow-cli init 重新扫描'))
          }
        }
      }

      console.log(chalk.cyan('\n=============================='))
      // 只有**这次真的拿到可用密钥**才叫"完成"。否则说清楚"没就绪"以及下一步做什么 ——
      // 报"完成"再让 sessions 空着，是最费用户时间的失败方式（他会以为是自己微信的问题）。
      console.log(chalk[ntReady ? 'cyan' : 'yellow'](
        ntReady ? '初始化完成! (4.x 模式)' : '初始化未完成：数据库密钥没有就绪'))
      console.log(chalk.cyan('=============================='))
      console.log(chalk.white(`数据目录: ${detected.path}`))
      console.log(chalk.white(`账号: ${selectedWxid.wxid}${selectedWxid.nickname ? ` (${selectedWxid.nickname})` : ''}`))
      console.log(chalk.white(`密钥: ${ntReady ? '已安全保存' : '未就绪（配置里的旧密钥未必能解开这个库）'}`))
      const ntDbPath = configService.get('ntDbPath')
      if (ntDbPath) {
        console.log(chalk.white(`NT 数据库: ${ntDbPath}`))
      }
      if (!ntReady) {
        console.log(chalk.yellow('\n现在 sessions / messages 会读不到数据。按顺序做这三步：'))
        console.log(chalk.yellow('  1) 在这个终端里运行 `python --version`，要能打出版本号'))
        console.log(chalk.yellow('     （Windows 上最常见的问题是只装了商店的 python 占位程序）'))
        console.log(chalk.yellow('  2) `pip install sqlcipher3`'))
        console.log(chalk.yellow('  3) 有共享口令的话，最省事的是直接用它：'))
        console.log(chalk.cyan('       weflow-cli init --passphrase <64位hex>'))
        console.log(chalk.yellow('     （或先 `weflow-cli fav set-key --passphrase <64位hex>` 再 init；'))
        console.log(chalk.yellow('      也可以用环境变量 WEFLOW_PASSPHRASE 传，避免留在 shell 历史里）'))
        console.log(chalk.yellow('  4) `weflow-cli config forget-keys`，然后重新 `weflow-cli init`'))
        // 这三步是"最常见的原因"，不是诊断结论。真卡住时让用户拿到一份**已经判定过**的事实，
        // 而不是再让他把现象口头描述一遍（那正是 issue #3/#9/#10 每次都要重来一遍的原因）。
        console.log(chalk.yellow('\n想先看清到底卡在哪一步，运行：'))
        console.log(chalk.cyan('  weflow-cli check --report'))
        console.log(chalk.gray('  它会给出结论（Python / sqlcipher3 / 密钥 / 数据目录），那段文字可以直接复制给 AI 或贴到 issue。'))
      }

      // 未就绪时说"现在可以使用"是骗人的：那几条命令都会返回空。
      console.log(chalk.gray(ntReady
        ? '\n现在可以使用以下命令:'
        : '\n修好上面那几步之后，这些命令才会返回数据:'))
      console.log(chalk.gray('  weflow-cli sessions        查看会话列表'))
      console.log(chalk.gray('  weflow-cli messages <talker> 查看消息'))
      console.log(chalk.gray('  weflow-cli contacts        查看联系人'))
      console.log(chalk.gray('  weflow-cli export <talker> <format> 导出聊天记录'))
    }
  })

// ==================== config ====================
const configCmd = program
  .command('config')
  .description('查看或修改配置')

const configurableKeys = [
  'dbPath', 'decryptKey', 'dbPath3x', 'decryptKey3x', 'dataVersion', 'wxid',
  'ntDbPath', 'ntKey', 'ntSalt', 'contactDbPath', 'contactKey', 'contactSalt',
  'vaultRepo', 'aiEngine', 'aiBaseUrl', 'aiModel', 'deepseekApiKey', 'typesafeApiKey',
  'dashscopeApiKey', 'favPassphrase',
  'judgeProvider', 'openrouterApiKey', 'openrouterJudgeModel', 'judgeLocalUrl', 'judgeEndpoint',
  'wereadApiKey',
  'assistantPrivacy', 'assistantWhitelist', 'assistantGroupWhitelist',
  'assistantGroupRequireMention', 'assistantFastRoute', 'assistantPanelUser', 'quickReplyContacts',
  'skillDirs', 'skillDisabled',
  'dailySources', 'dailySourceCategories',
  'dailyExcludeTopics', 'dailyAiEnabled', 'dailyKeepImages', 'dailyMaxFailureRate', 'dailyMailTo',
  'aiApiKey',
  'wechatMediaDownload',
  'emoticonSeed',
] as const

function setConfigValue(key: string, value: string, quiet = false): void {
  if (!configurableKeys.includes(key as typeof configurableKeys[number])) {
    console.log(chalk.red(`无效的配置项: ${key}`))
    console.log(chalk.gray(`可用: ${configurableKeys.join(', ')}`))
    process.exit(1)
  }
  const configValue = key === 'dailySourceCategories' && value.startsWith('base64:')
    ? Buffer.from(value.slice('base64:'.length), 'base64').toString('utf8')
    : value
  try {
    configService.set(key as any, configValue)
  } catch (e: any) {
    // 写盘失败时必须失败退出：以前 save() 只打日志，这里照样打印"✓ 已设置"，
    // 用户以为改成功了（2026-11-01 在只读的 ~/.weflow-cli 上实测踩到）。
    console.error(chalk.red(`\n✗ 配置没有保存成功: ${e?.message || e}`))
    console.error(chalk.gray('  常见原因：~/.weflow-cli 目录不可写（权限/只读挂载），或磁盘已满。'))
    process.exit(1)
  }
  if (!quiet) console.log(chalk.green(`✓ 已设置 ${key}`))
}

function ensureConfigurableKey(key: string, json: boolean): void {
  if (configurableKeys.includes(key as typeof configurableKeys[number])) return
  if (json) console.log(JSON.stringify({ success: false, code: 'INVALID_CONFIG_KEY', error: '配置项不可写', key }))
  else {
    console.log(chalk.red(`无效的配置项: ${key}`))
    console.log(chalk.gray(`可用: ${configurableKeys.join(', ')}`))
  }
  process.exit(1)
}

configCmd
  .command('show')
  .description('显示当前配置')
  .option('--json', '输出脱敏 JSON，不返回路径、账号或密钥')
  .action((opts) => {
    const config = configService.getAll()
    if (opts.json) {
      let sourceCategoryCount = 0
      try {
        const categories = JSON.parse(String(configService.get('dailySourceCategories') || '{}'))
        sourceCategoryCount = categories && typeof categories === 'object' && !Array.isArray(categories)
          ? Object.keys(categories).length
          : 0
      } catch {}
      const dailySources = String(configService.get('dailySources') || '')
        .split(/[,;\n]+/)
        .map(value => value.trim())
        .filter(Boolean)
      console.log(JSON.stringify({
        success: true,
        schema: 'weflow-config-status/v1',
        initialized: configService.isConfigured(),
        dataVersion: config.dataVersion || null,
        databases: {
          legacyConfigured: !!config.dbPath3x && !!config.decryptKey3x,
          messageConfigured: !!config.ntDbPath && !!config.ntKey,
          contactsConfigured: !!config.contactDbPath && !!config.contactKey,
          momentsConfigured: !!configService.get('snsDbPath') && !!configService.get('snsKey'),
          favoritesConfigured: !!configService.get('favDbPath') && (!!configService.get('favKey') || !!configService.get('favPassphrase')),
        },
        ai: {
          engine: configService.get('aiEngine') || 'deepseek',
          configured: ['ollama', 'lmstudio'].includes(String(configService.get('aiEngine') || 'deepseek')) || !!resolveAiKey(),
          dailyEnabled: configService.get('dailyAiEnabled') !== 'false',
        },
        daily: {
          restrictedSources: dailySources.length > 0,
          sourceCount: dailySources.length,
          categorizedSourceCount: sourceCategoryCount,
        },
        assistant: {
          privacyMode: configService.get('assistantPrivacy') || 'strict',
          directWhitelistConfigured: !!String(configService.get('assistantWhitelist') || '').trim(),
          groupWhitelistConfigured: !!String(configService.get('assistantGroupWhitelist') || '').trim(),
          groupMentionRequired: configService.get('assistantGroupRequireMention') !== 'false',
        },
      }, null, 2))
      return
    }
    console.log(chalk.cyan('当前配置:\n'))
    console.log(`数据版本: ${config.dataVersion || chalk.gray('(自动检测)')}`)
    console.log(`4.x 数据目录: ${config.dbPath || chalk.gray('(未设置)')}`)
    console.log(`4.x 密钥: ${config.decryptKey ? '已设置' : chalk.gray('(未设置)')}`)
    console.log(`3.x 数据库: ${config.dbPath3x || chalk.gray('(未设置)')}`)
    console.log(`3.x 密钥: ${config.decryptKey3x ? '已设置' : chalk.gray('(未设置)')}`)
    console.log(`NT 数据库: ${config.ntDbPath || chalk.gray('(未设置)')}`)
    console.log(`NT 密钥: ${config.ntKey ? '已设置' : chalk.gray('(未设置)')}`)
    console.log(`联系人DB: ${config.contactDbPath || chalk.gray('(未设置)')}`)
    console.log(`联系人DB密钥: ${config.contactKey ? '已设置' : chalk.gray('(未设置)')}`)
    console.log(`微信账号: ${config.wxid || chalk.gray('(未设置)')}`)
    console.log(`公众号日报来源: ${configService.get('dailySources') || chalk.gray('(全部公众号)')}`)
    console.log(`公众号日报 AI: ${configService.get('dailyAiEnabled') === 'false' ? '已关闭' : '已开启'}`)
    console.log(`公众号日报排除主题: ${configService.get('dailyExcludeTopics') || chalk.gray('(不排除)')}`)
  })

configCmd
  .command('set <key> <value>')
  .description('设置配置项')
  .option('--dry-run', '仅预览，不修改配置')
  .option('--yes', '确认执行')
  .option('--json', '输出 JSON 格式，不返回配置值')
  .action((key: string, value: string, opts) => {
    ensureConfigurableKey(key, !!opts.json)
    const preview = { action: 'config.set', key, source: 'argument' }
    if (opts.dryRun) {
      if (opts.json) console.log(JSON.stringify({ success: true, dryRun: true, ...preview }))
      else console.log(chalk.cyan(`将设置配置项 ${key}`))
      return
    }
    if (opts.json && !opts.yes) {
      console.log(JSON.stringify({ success: false, code: 'CONFIRMATION_REQUIRED', error: '使用 --yes 确认修改配置', ...preview }))
      process.exit(1)
    }
    setConfigValue(key, value, !!opts.json)
    if (opts.json) console.log(JSON.stringify({ success: true, changed: true, ...preview }))
  })

configCmd
  .command('set-env <key> <environment>')
  .description('从环境变量读取值并保存，避免秘密出现在命令参数中')
  .option('--dry-run', '仅预览，不修改配置')
  .option('--yes', '确认执行')
  .option('--json', '输出 JSON 格式，不返回环境变量值')
  .action((key: string, environment: string, opts) => {
    ensureConfigurableKey(key, !!opts.json)
    if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(environment)) {
      if (opts.json) console.log(JSON.stringify({ success: false, code: 'INVALID_ENVIRONMENT_NAME', error: '环境变量名称无效' }))
      else console.log(chalk.red('环境变量名称无效'))
      process.exit(1)
    }
    const value = process.env[environment]
    if (!value) {
      if (opts.json) console.log(JSON.stringify({ success: false, code: 'ENVIRONMENT_VALUE_MISSING', error: `环境变量 ${environment} 未设置或为空` }))
      else console.log(chalk.red(`环境变量 ${environment} 未设置或为空`))
      process.exit(1)
    }
    const preview = { action: 'config.set-env', key, environment }
    if (opts.dryRun) {
      if (opts.json) console.log(JSON.stringify({ success: true, dryRun: true, ...preview }))
      else console.log(chalk.cyan(`将从环境变量 ${environment} 设置配置项 ${key}`))
      return
    }
    if (opts.json && !opts.yes) {
      console.log(JSON.stringify({ success: false, code: 'CONFIRMATION_REQUIRED', error: '使用 --yes 确认修改配置', ...preview }))
      process.exit(1)
    }
    setConfigValue(key, value, !!opts.json)
    if (opts.json) console.log(JSON.stringify({ success: true, changed: true, ...preview }))
  })

configCmd
  .command('clear')
  .description('清除所有配置')
  .option('--dry-run', '仅预览，不清除配置')
  .option('--yes', '确认清除全部配置')
  .option('--json', '输出 JSON 格式')
  .action(async (opts) => {
    if (opts.dryRun) {
      const preview = { success: true, dryRun: true, action: 'config.clear', hasConfiguration: Object.keys(configService.getAll()).length > 0 }
      if (opts.json) console.log(JSON.stringify(preview))
      else console.log(chalk.cyan('配置清除预览：将删除数据库访问、AI、日报、访问控制和助手设置。'))
      return
    }
    if (!opts.yes) {
      if (opts.json) {
        console.log(JSON.stringify({ success: false, code: 'CONFIRMATION_REQUIRED', error: '使用 --yes 确认清除全部配置' }))
        process.exit(1)
      }
      const { confirmed } = await inquirer.prompt([{
        type: 'confirm',
        name: 'confirmed',
        message: '将清除数据库访问、AI、日报、白名单和机器人等全部配置。继续吗？',
        default: false,
      }])
      if (!confirmed) {
        console.log(chalk.gray('已取消，未修改配置。'))
        return
      }
    }
    configService.clear()
    if (opts.json) {
      console.log(JSON.stringify({ success: true, action: 'config.clear' }))
      return
    }
    console.log(chalk.green('✓ 配置已清除'))
  })

configCmd
  .command('forget-keys')
  .description('仅清除本机数据库访问密钥，用于重新初始化测试')
  .option('--dry-run', '仅预览，不清除数据库访问密钥')
  .option('--yes', '跳过确认')
  .option('--json', '输出 JSON 格式')
  .action(async (opts) => {
    if (opts.dryRun) {
      const preview = { success: true, dryRun: true, action: 'config.forget-keys', preservesNonDatabaseSettings: true }
      if (opts.json) console.log(JSON.stringify(preview))
      else console.log(chalk.cyan('数据库密钥清除预览：保留数据目录、AI、日报、访问控制和助手设置。'))
      return
    }
    if (!opts.yes) {
      if (opts.json) {
        console.log(JSON.stringify({ success: false, code: 'CONFIRMATION_REQUIRED', error: '使用 --yes 确认清除数据库访问密钥' }))
        process.exit(1)
      }
      const { confirmed } = await inquirer.prompt([{
        type: 'confirm',
        name: 'confirmed',
        message: '清除数据库访问密钥后，聊天读取会暂时不可用。继续吗？',
        default: false,
      }])
      if (!confirmed) {
        console.log(chalk.gray('已取消，未修改配置。'))
        return
      }
    }

    configService.clearDatabaseKeys()
    if (opts.json) {
      console.log(JSON.stringify({ success: true, action: 'config.forget-keys' }))
      return
    }
    console.log(chalk.green('✓ 已清除数据库访问密钥。'))
    console.log(chalk.gray('  数据目录、AI、日报、白名单和机器人设置均已保留。'))
    console.log(chalk.gray('  现在可运行 weflow-cli init 测试首次初始化流程。'))
  })

// ==================== sessions ====================
program
  .command('sessions')
  .description('查看会话列表')
  .option('-k, --keyword <keyword>', '搜索关键词')
  .option('-n, --limit <number>', '最大数量', '30')
  .option('--json', '输出 JSON 格式')
  .action(async (opts) => {
    const limit = parseCliInteger(opts.limit, 'limit', 1, 1000, !!opts.json)
    if (!configService.isConfigured()) {
      if (opts.json) { console.log(JSON.stringify({ success: false, error: '未完成初始化' })); process.exit(1) }
      {
        const { unconfiguredHint } = await import('../src/utils/unconfiguredHint.js')
        console.log(chalk.red(unconfiguredHint()))
      }
      process.exit(1)
    }

    // 用 `listSessionsDetailed` 而不是 `listSessions`：后者失败时返回 []，调用方分不清
    // 「读取没成功」和「确实没有会话」。issue #16 的现场就是踩在这上面——报错只在
    // 日志深处（SQLITE_NOTADB 26），用户看到的是"空"。
    const detailed = await chatService.listSessionsDetailed(opts.keyword, limit)
    const sessions = detailed.sessions
    if (sessions.length === 0) {
      if (opts.json) {
        // 失败时不再谎报 success:true —— 这正是 issue #16 建议的那条。
        console.log(JSON.stringify(detailed.failure
          ? { success: false, code: 'READ_FAILED', failure: detailed.failure, sessions: [] }
          : { success: true, sessions: [] }, null, 2))
        // JSON 模式也要有非 0 退出码：脚本用 `success` 判断是它的事，
        // 但 shell 层面 `if weflow-cli sessions --json` 同样应当能看出失败。
        if (detailed.failure) process.exit(1)
        return
      }
      if (detailed.failure) {
        // 有确切失败原因时，直接说清楚，而不是让用户去猜"是不是没会话"。
        console.error(chalk.red(`
✗ ${detailed.failure.message}
`))
        console.error(chalk.yellow(`  下一步：${detailed.failure.next}
`))
        if (detailed.failure.detail) console.error(chalk.gray(`  原始错误：${detailed.failure.detail}
`))
        process.exit(1)
        return
      }
      console.log(chalk.gray('未找到会话'))
      // "0 条"有两种完全不同的原因：真的没有会话，和**初始化/密钥坏了读不出来**。
      // 后者以前只显示这一句，用户就去猜"是不是我微信坏了 / 版本太新"（issue #3/#9/#10 的老路：
      // 同一个根因被描述成三种现象）。给一条能立刻分清的动作，比让他猜有用。
      console.log(chalk.yellow('\n如果微信里明明有聊天记录，那多半是读取这一步没成功。运行这条看结论：'))
      console.log(chalk.cyan('  weflow-cli check --report'))
      console.log(chalk.gray('  它会指出卡在哪一步（Python / sqlcipher3 / 密钥 / 数据目录），那段文字可直接复制给 AI 或贴到 issue。'))
      return
    }

    if (opts.json) {
      console.log(JSON.stringify({ success: true, sessions }, null, 2))
      return
    }
    console.log(chalk.cyan(`会话列表 (${sessions.length} 条):\n`))
    console.log(chalk.gray('序号  会话ID                昵称            最后消息'))
    console.log(chalk.gray('─'.repeat(70)))

    for (let i = 0; i < sessions.length; i++) {
      const s = sessions[i]
      const num = String(i + 1).padStart(3)
      const id = (s.username || '').padEnd(20)
      const name = (s.displayName || '').slice(0, 12).padEnd(12)
      const summary = (s.summary || '').slice(0, 30)
      console.log(`${num}  ${id} ${name} ${summary}`)
    }
  })

// ==================== messages ====================
program
  .command('messages <talker>')
  .description('查看指定会话的消息 (支持 wxid / 昵称 / 备注 / 序号)')
  .option('-n, --limit <number>', '最大数量', '50')
  .option('-o, --offset <number>', '偏移量', '0')
  .option('-s, --start <timestamp>', '开始时间戳')
  .option('-e, --end <timestamp>', '结束时间戳')
  .option('--json', '输出 JSON 格式')
  .option('--non-interactive', '禁止交互选择；匹配不唯一时返回错误')
  .action(async (talkerInput: string, opts) => {
    const limit = parseCliInteger(opts.limit, 'limit', 1, 5000, !!opts.json)
    const offset = parseCliInteger(opts.offset, 'offset', 0, 1_000_000, !!opts.json)
    const start = opts.start === undefined ? undefined : parseCliInteger(opts.start, 'start', 0, Number.MAX_SAFE_INTEGER, !!opts.json)
    const end = opts.end === undefined ? undefined : parseCliInteger(opts.end, 'end', 0, Number.MAX_SAFE_INTEGER, !!opts.json)
    if (start !== undefined && end !== undefined && start > end) {
      if (opts.json) console.log(JSON.stringify({ success: false, code: 'INVALID_ARGUMENT', field: 'start', error: 'start 不能晚于 end' }))
      else console.log(chalk.red('start 不能晚于 end'))
      process.exit(1)
    }
    if (!configService.isConfigured()) {
      if (opts.json) { console.log(JSON.stringify({ success: false, error: '未完成初始化' })); process.exit(1) }
      console.log(chalk.red('\n❌ 还没配置'))
      console.log(chalk.gray('  运行: weflow-cli init\n'))
      process.exit(1)
    }

    const talker = await resolveTalker(talkerInput, opts.json, opts.nonInteractive || opts.json)

    const detailed = start !== undefined || end !== undefined
      ? { messages: (await chatService.getMessagesInRange(talker, limit + offset, start, end)).slice(offset, offset + limit) }
      : await chatService.getMessagesDetailed(talker, limit, offset)
    const messages = detailed.messages

    if (messages.length === 0) {
      // 读失败优先于"没有消息"：这两件事以前都显示"未找到消息"，而前者需要用户去做别的事。
      if (detailed.failure) {
        if (opts.json) {
          console.log(JSON.stringify(
            { success: false, code: 'READ_FAILED', talker, failure: detailed.failure, messages: [] }, null, 2))
        } else {
          console.error(chalk.red(`\n✗ ${detailed.failure.message}\n`))
          console.error(chalk.yellow(`  下一步：${detailed.failure.next}\n`))
          if (detailed.failure.detail) console.error(chalk.gray(`  原始错误：${detailed.failure.detail}\n`))
        }
        process.exit(1)
        return
      }
      // 拼错的 ID 会被 resolveTalker 原样放行 ⇒ 取不到消息。这里补一句话把两种情况分开，
      // 但**不改退出码、也不改 success**（"没有消息"不是错误，脚本与 MCP 依赖这一点）。
      let note = ''
      if (looksLikeTalkerId(talkerInput)) {
        const [sessions, contacts] = await Promise.all([
          chatService.listSessions(talkerInput, 5),
          chatService.listContacts(talkerInput, 5),
        ])
        note = emptyMessagesNote(talkerInput, {
          sessionUsernames: sessions.map(s => s.username),
          contactUsernames: contacts.map(c => c.username),
        })
      }
      if (opts.json) {
        console.log(JSON.stringify({ success: true, talker, messages: [], ...(note ? { note } : {}) }))
        return
      }
      console.log(chalk.gray('未找到消息'))
      if (note) console.log(chalk.yellow(note))
      return
    }

    if (opts.json) {
      console.log(JSON.stringify({ success: true, talker, messages }, null, 2))
      return
    }
    console.log(chalk.cyan(`消息记录 - ${talker} (${messages.length} 条):\n`))

    for (const m of messages) {
      const time = new Date(m.createTime * 1000).toLocaleString('zh-CN')
      const senderName = m.isSend ? chalk.green('我') : chalk.blue((m as any).senderDisplay || m.senderUsername || talker)
      const content = (m.parsedContent || m.rawContent || '').replace(/\n/g, ' ').slice(0, 80)
      console.log(chalk.gray(`[${time}]`) + ` ${senderName}: ${content}`)
    }
  })

// ==================== sync ====================
// 增量同步检查点。契约见 docs/SYNC_CONTRACT.md, 边界见 D-029。
// 不宣称「稳定游标」: D-027 要求它在所有后端支持前不得对外宣称,
// 这里只做重叠时间窗 + 本地去重。
const syncCmd = program.command('sync').description('本地消息同步检查点（重叠窗口读取与覆盖报告）')

syncCmd
  .command('run <talker>')
  .description('执行一次同步并写入检查点')
  .option('--since <date>', '起始日期或 ISO 时间（首次运行需要）')
  .option('--full', '读取全部历史（首次运行需要；耗时可能较长）')
  .option('--overlap <seconds>', '重叠窗口秒数', '300')
  .option('-n, --limit <number>', '本次最多读取条数（0=不限）', '0')
  .option('--dry-run', '仅预览，不读取消息、不写状态')
  .option('--yes', '确认执行')
  .option('--json', '输出机器可读结果')
  .option('--non-interactive', '禁止交互确认')
  .action(async (talker: string, opts) => {
    const overlap = parseCliInteger(opts.overlap, 'overlap', 0, 86400, !!opts.json)
    const limit = parseCliInteger(opts.limit, 'limit', 0, 1_000_000, !!opts.json)

    let since: number | undefined
    if (opts.since) {
      try {
        since = parseLocalDateOrIso(opts.since)
      } catch (error) {
        const message = error instanceof DateRangeError ? error.message : '日期格式无效'
        if (opts.json) { console.log(JSON.stringify({ success: false, code: 'INVALID_DATE', error: message })); process.exit(1) }
        console.error(chalk.red(`✗ ${message}`))
        process.exit(1)
      }
    }
    if (opts.full && since !== undefined) {
      if (opts.json) { console.log(JSON.stringify({ success: false, code: 'INVALID_ARGUMENT', error: '--since 与 --full 不能同时使用' })); process.exit(1) }
      console.error(chalk.red('✗ --since 与 --full 不能同时使用'))
      process.exit(1)
    }

    // Preview deliberately does not resolve the talker: that reads the
    // database, and a preview must not touch local data (D-025).
    const prior = (() => {
      try { return syncStateStore.read(SYNC_SOURCE, talker) } catch { return null }
    })()
    const preview = {
      success: true,
      dryRun: true,
      action: 'sync.run',
      schema: SYNC_SCHEMA,
      source: SYNC_SOURCE,
      talkerResolved: false,
      hasCheckpoint: !!prior,
      window: {
        from: since ?? prior?.checkpoint.newestCreateTime ?? null,
        overlapSeconds: overlap,
        full: !!opts.full,
      },
      estimatedRecords: prior?.recordsRead ?? null,
      readsLocalChat: true,
      writesLocalState: true,
      stableCursor: false,
    }

    if (opts.dryRun) {
      if (opts.json) console.log(JSON.stringify(preview))
      else {
        console.log(chalk.cyan('\n同步预览'))
        console.log(chalk.gray(`  范围: ${opts.full ? '全部历史' : since ? new Date(since * 1000).toLocaleString() : '上次检查点'}`))
        console.log(chalk.gray(`  重叠窗口: ${overlap} 秒`))
        console.log(chalk.gray('  将读取本地聊天记录并写入同步检查点，不调用 AI。\n'))
      }
      return
    }

    if (!opts.yes) {
      if (opts.json) {
        console.log(JSON.stringify({ ...preview, success: false, dryRun: false, code: 'CONFIRMATION_REQUIRED' }))
        process.exit(1)
      }
      if (opts.nonInteractive) {
        console.error(chalk.red('✗ 非交互模式需要 --yes'))
        process.exit(1)
      }
      const { confirmed } = await inquirer.prompt([{
        type: 'confirm',
        name: 'confirmed',
        message: opts.full
          ? '将读取该会话的全部历史消息，可能耗时数分钟。继续吗？'
          : '将读取指定范围内的消息并写入本地同步检查点。继续吗？',
        default: false,
      }])
      if (!confirmed) {
        console.log(chalk.gray('已取消'))
        return
      }
    }

    if (!configService.isConfigured()) {
      if (opts.json) { console.log(JSON.stringify({ success: false, code: 'NOT_INITIALIZED', error: '未完成初始化' })); process.exit(1) }
      console.error(chalk.red('✗ 未完成初始化，请先运行 weflow-cli init'))
      process.exit(1)
    }

    let resolvedTalker = ''
    try {
      resolvedTalker = await resolveTalkerCore(talker, { interactive: !opts.nonInteractive })
    } catch {
      resolvedTalker = ''
    }
    if (!resolvedTalker) {
      if (opts.json) { console.log(JSON.stringify({ success: false, code: 'INVALID_ARGUMENT', error: '未找到该会话' })); process.exit(1) }
      console.error(chalk.red('✗ 未找到该会话'))
      process.exit(1)
    }
    // A display name is nicety only; the state is keyed by the resolved id.
    let displayName = resolvedTalker
    try {
      const match = (await chatService.listSessions()).find(s => s.username === resolvedTalker)
      if (match?.displayName && match.displayName !== resolvedTalker) displayName = match.displayName
    } catch { /* keep the id */ }

    try {
      const result = await runSync(resolvedTalker, {
        since, full: !!opts.full, overlapSeconds: overlap, limit,
        scope: displayName,
        read: (who, howMany, from) => chatService.getMessagesWithShards(who, howMany, 0, from),
      })
      if (opts.json) {
        console.log(JSON.stringify({
          success: result.success,
          ...(result.code ? { code: result.code } : {}),
          action: result.action,
          schema: SYNC_SCHEMA,
          source: SYNC_SOURCE,
          scope: result.scope,
          talker: resolvedTalker,
          window: result.window,
          recordsRead: result.recordsRead,
          recordsDeduplicated: result.recordsDeduplicated,
          recordsReturned: result.recordsReturned,
          shards: result.shards,
          coverage: result.coverage,
          mayHaveMore: result.mayHaveMore,
          partial: result.partial,
          warnings: result.warnings,
          jobId: result.jobId,
        }))
        if (!result.success) process.exit(1)
        return
      }
      const mark = result.coverage === 'complete' ? '✓' : result.coverage === 'unverified' ? '!' : '✗'
      console.log(chalk.green(`\n${mark} 同步完成: ${result.recordsReturned}/${result.recordsRead} 条（去重 ${result.recordsDeduplicated}）`))
      console.log(chalk.gray(`  覆盖: ${result.coverage}  ·  分片: ${result.shards?.opened ?? '?'} 读 / ${result.shards?.failed ?? 0} 失败`))
      for (const warning of result.warnings) console.log(chalk.yellow(`  ⚠ ${warning}`))
      if (result.partial) {
        console.log(chalk.yellow('  本次为部分完成，未推进成功时间；用 sync status 查看详情。'))
      }
      console.log('')
      if (!result.success) process.exit(1)
    } catch (error: any) {
      if (error instanceof SyncRangeRequiredError) {
        if (opts.json) { console.log(JSON.stringify({ success: false, code: 'SYNC_RANGE_REQUIRED', error: error.message })); process.exit(1) }
        console.error(chalk.red(`✗ ${error.message}`))
        process.exit(1)
      }
      if (opts.json) { console.log(JSON.stringify({ success: false, code: 'SYNC_FAILED', error: '同步失败' })); process.exit(1) }
      console.error(chalk.red(`✗ 同步失败: ${error?.message || error}`))
      process.exit(1)
    }
  })

syncCmd
  .command('status [talker]')
  .description('查看同步检查点与最近任务')
  .option('--json', '输出 JSON 格式')
  .action(async (talker: string | undefined, opts) => {
    // No database access: this has to work while the database is locked.
    let states: any[] = []
    try { states = syncStateStore.list() } catch { states = [] }
    const lastJob = syncStateStore.recentJobs(1)[0] ?? null

    if (talker) {
      const match = states.find(s => s.talker === talker || s.scope === talker)
      if (!match) {
        if (opts.json) { console.log(JSON.stringify({ success: false, code: 'SYNC_STATE_NOT_FOUND', error: '没有该会话的同步记录' })); process.exit(1) }
        console.error(chalk.red('✗ 没有该会话的同步记录'))
        process.exit(1)
      }
      if (opts.json) { console.log(JSON.stringify({ success: true, schema: SYNC_SCHEMA, state: match, lastJob })); return }
      console.log(chalk.cyan(`\n同步记录 — ${match.scope}`))
      console.log(chalk.gray(`  覆盖: ${match.coveredFrom || '—'} ~ ${match.coveredTo || '—'}`))
      console.log(chalk.gray(`  可信度: ${match.coverage}  ·  分片 ${match.shardsRead} 读 / ${match.shardsFailed} 失败`))
      console.log(chalk.gray(`  上次成功: ${match.lastSuccessfulRun || '—'}  ·  上次尝试: ${match.lastAttempt || '—'}\n`))
      return
    }

    if (opts.json) {
      console.log(JSON.stringify({
        success: true,
        schema: SYNC_SCHEMA,
        stableCursor: false,
        scopes: states.map(s => ({
          source: s.source, scope: s.scope, talker: s.talker,
          lastSuccessfulRun: s.lastSuccessfulRun, lastAttempt: s.lastAttempt,
          coveredFrom: s.coveredFrom, coveredTo: s.coveredTo,
          recordsRead: s.recordsRead, recordsDeduplicated: s.recordsDeduplicated,
          coverage: s.coverage, shardsRead: s.shardsRead, shardsFailed: s.shardsFailed,
          mayHaveMore: s.mayHaveMore, warnings: s.warnings,
        })),
        lastJob,
      }))
      return
    }
    if (!states.length) {
      console.log(chalk.gray('\n还没有任何同步记录。首次运行: weflow-cli sync run <会话> --since <日期>\n'))
      return
    }
    console.log(chalk.cyan(`\n同步记录 (${states.length} 个会话):\n`))
    for (const s of states) {
      const mark = s.coverage === 'complete' ? '✓' : s.coverage === 'unverified' ? '!' : '✗'
      console.log(`  ${mark} ${s.scope}  ${chalk.gray(`${s.coveredFrom || '—'} ~ ${s.coveredTo || '—'}  分片 ${s.shardsRead}/${s.shardsFailed} 失败`)}`)
    }
    console.log('')
  })

syncCmd
  .command('verify <talker>')
  .description('核对检查点与当前数据的边界')
  .option('--json', '输出 JSON 格式')
  .action(async (talker: string, opts) => {
    // Read-only: it writes nothing, so it needs no confirmation - the same
    // posture as `messages`.
    if (!configService.isConfigured()) {
      if (opts.json) { console.log(JSON.stringify({ success: false, code: 'NOT_INITIALIZED', error: '未完成初始化' })); process.exit(1) }
      console.error(chalk.red('✗ 未完成初始化'))
      process.exit(1)
    }
    let state: any = null
    try { state = syncStateStore.read(SYNC_SOURCE, talker) } catch { state = null }
    if (!state) state = syncStateStore.list().find(s => s.scope === talker) ?? null
    if (!state) {
      if (opts.json) { console.log(JSON.stringify({ success: false, code: 'SYNC_STATE_NOT_FOUND', error: '没有该会话的同步记录' })); process.exit(1) }
      console.error(chalk.red('✗ 没有该会话的同步记录'))
      process.exit(1)
    }

    const checks: Array<Record<string, unknown>> = [{ name: 'checkpoint-present', ok: true }]

    // Re-read and compare. This is the count summary of §4.4 in the absence
    // of a local index.
    const read = await chatService.getMessagesWithShards(state.talker, 0, 0)
    const fromSeconds = state.coveredFrom ? Math.floor(Date.parse(state.coveredFrom) / 1000) : null
    const inWindow = fromSeconds === null
      ? read.messages
      : read.messages.filter(m => Number(m.createTime) >= fromSeconds)
    checks.push({ name: 'window-re-readable', ok: inWindow.length > 0, returned: inWindow.length })

    const newest = read.messages.length
      ? Math.max(...read.messages.map(m => Number(m.createTime) || 0))
      : null
    checks.push({
      name: 'newest-message-present',
      ok: newest !== null && newest >= (state.checkpoint?.newestCreateTime ?? 0),
      recorded: state.checkpoint?.newestCreateTime ?? null,
      observed: newest,
    })

    if (read.shards) {
      checks.push({ name: 'shards-readable', ok: read.shards.failed === 0,
                    scanned: read.shards.scanned, failed: read.shards.failed })
    } else {
      // Neither a pass nor a failure: this backend simply cannot say.
      checks.push({ name: 'shards-readable', ok: true, skipped: true,
                    reason: 'backend-does-not-report-shards' })
    }

    const success = checks.every(c => c.ok || c.skipped)
    if (opts.json) {
      console.log(JSON.stringify({ success, schema: SYNC_SCHEMA, scope: state.scope, coverage: state.coverage, checks }))
      if (!success) process.exit(1)
      return
    }
    console.log(chalk.cyan(`\n核对 — ${state.scope}\n`))
    for (const check of checks) {
      const mark = check.skipped ? '–' : check.ok ? '✓' : '✗'
      console.log(`  ${mark} ${check.name}${check.skipped ? chalk.gray(` (跳过: ${check.reason})`) : ''}`)
    }
    console.log('')
    if (!success) process.exit(1)
  })

// 稳定游标的"路径可见"探针（D-027）。只读、本地、无确认门——与 `check` 同一副姿态：
// 它是诊断，不是副作用。`stableCursor` 的结论**不会**因为它翻 true；它做的是把
// "还差什么"逐条摊开给下游（she-love-me、MCP 客户端）看。
syncCmd
  .command('cursor-probe')
  .description('探测当前消息后端离稳定增量游标还差什么（只读，NT 后端带实测采样）')
  .option('--json', '输出 JSON 格式')
  .option('--tables-per-shard <n>', '每分片采样的会话表数量（schema 检查始终全量）', '5')
  .option('--rows-per-table <n>', '每张表两端各采样的行数', '500')
  .action(async (opts) => {
    const parseBound = (raw: string, label: string): number | undefined => {
      const n = Number(raw)
      if (!Number.isInteger(n) || n < 1 || n > 10_000) {
        if (opts.json) { console.log(JSON.stringify({ success: false, code: 'INVALID_ARGUMENT', error: `${label} 必须是 1-10000 的整数` })); process.exit(1) }
        console.error(chalk.red(`✗ ${label} 必须是 1-10000 的整数`))
        process.exit(1)
      }
      return n
    }
    let report
    try {
      report = await probeCursorReadiness({
        tablesPerShard: parseBound(opts.tablesPerShard, '--tables-per-shard'),
        rowsPerTable: parseBound(opts.rowsPerTable, '--rows-per-table'),
      })
    } catch (error: any) {
      if (opts.json) { console.log(JSON.stringify({ success: false, code: 'CURSOR_PROBE_FAILED', error: error?.message || '探测失败' })); process.exit(1) }
      console.error(chalk.red(`✗ 探测失败: ${error?.message || error}`))
      process.exit(1)
    }
    if (opts.json) { console.log(JSON.stringify(report)); return }

    console.log(chalk.cyan('\n稳定游标探针（结论不变：stableCursor = false，D-027）'))
    console.log(chalk.gray(`  后端: ${report.backend ?? '（未配置）'} — ${report.backendNote}`))
    console.log(chalk.gray(`  实测: ${report.probedLive ? `已采样（exhaustive=false）` : '未运行（该后端无实测探针或未初始化）'}`))
    for (const c of report.criteria) {
      const mark = c.met === null ? '?' : c.met ? '✓' : '✗'
      console.log(`  ${mark} ${c.id}`)
      console.log(chalk.gray(`      ${c.detail}`))
    }
    if (report.sample) {
      const sm = report.sample
      console.log(chalk.gray(`  采样: ${sm.rowsSampled} 行 / ${sm.tablesSampled} 表（共 ${sm.tablesTotal} 表，每表两端各 ${sm.rowsPerTable} 行）`))
    }
    console.log('')
  })

// ==================== ledger（资金流水：红包/转账，读 general.db） ====================
// 2026-10-26 NT 普查产物（docs/NT_DATABASES.md）。如实边界写在脚本头：红包表无
// 时间/金额列（在消息正文里，按 messageServerId 溯源是后续工作）；状态枚举语义
// 未逐值验证，原样输出不翻译。本地只读、不联网。
program
  .command('ledger')
  .description('资金流水：红包与转账（读 general.db；本地只读）')
  .option('--talker <contact>', '只看某个会话（id 或备注/昵称子串）')
  .option('--days <n>', '只看最近 N 天（按转账时间；红包无时间列不受此限）')
  .option('--json', '输出 JSON 格式')
  .action(async (opts) => {
    const { execFile } = await import('child_process')
    const { promisify } = await import('util')
    const execFileAsync = promisify(execFile)
    const script = join(resolvePackageRoot(), 'scripts', 'wechat_ledger.py')
    const args = [script, '--json']
    if (opts.days !== undefined) {
      const days = parseCliInteger(opts.days, 'days', 1, 36_500, opts.json)
      args.push('--days', String(days))
    }
    try {
      const { stdout } = await execFileAsync(getPythonCommand(), args, {
        timeout: 120_000, maxBuffer: 10 * 1024 * 1024,
        // D-020：会话标识走环境变量，不进 argv
        env: createPythonProcessEnv(opts.talker ? { WEFLOW_TALKER: String(opts.talker) } : {}),
      })
      const payload = JSON.parse(stdout.slice(stdout.indexOf('{')))
      if (opts.json) { console.log(JSON.stringify(payload)); if (!payload.success) process.exit(1); return }
      if (!payload.success) { console.error(chalk.red(`✗ ${payload.error}`)); process.exit(1) }
      console.log(chalk.cyan(`
资金流水：红包 ${payload.redEnvelopes} 笔、转账 ${payload.transfers} 笔`))
      console.log(chalk.gray('  （红包无时间/金额列——在消息正文里，按 messageServerId 看先后；状态枚举原样，语义未验证）'))
      for (const r of payload.rows.slice(0, 40)) {
        const when = r.time ? new Date(r.time * 1000).toLocaleString('zh-CN', { hour12: false }) : '（无时间列）'
        const extra = r.kind === '红包'
          ? `status=${r.hbStatus}/${r.receiveStatus}`
          : `对方=${r.counterpartyDisplay || r.counterparty || '?'}${r.invalidTime ? ` invalid=${r.invalidTime}` : ''}`
        console.log(`  [${when}] ${r.kind} · ${r.sessionDisplay} · ${r.direction} · ${extra}`)
      }
      if (payload.rows.length > 40) console.log(chalk.gray(`  …共 ${payload.rows.length} 行（--json 看全表）`))
      console.log('')
    } catch (e: any) {
      if (opts.json) { console.log(JSON.stringify({ success: false, code: 'LEDGER_FAILED', error: safeSubprocessError(e) })); process.exit(1) }
      console.error(chalk.red(`✗ ${safeSubprocessError(e)}`))
      process.exit(1)
    }
  })

// ==================== cache（数据库缓存管理） ====================
// 2026-10-27：解密数据库缓存（首次全量导出明文，后续查询无解密开销）。
// 环境变量控制：WEFLOW_CACHE_ENABLED=1 开启，未设置或其他值则关闭（默认关闭）。
// 安全警告：缓存目录包含完全明文的数据库，仅在本地开发环境使用。
const cacheProgram = program
  .command('cache')
  .description('数据库缓存管理（环境变量 WEFLOW_CACHE_ENABLED=1 开启）')

cacheProgram
  .command('status')
  .description('查看缓存状态')
  .option('--json', '输出 JSON 格式')
  .action(async (opts) => {
    const { execFile } = await import('child_process')
    const { promisify } = await import('util')
    const execFileAsync = promisify(execFile)
    const script = join(resolvePackageRoot(), 'scripts', 'manage_cache.py')
    try {
      const { stdout } = await execFileAsync(getPythonCommand(), [script, 'status', ...(opts.json ? ['--json'] : [])], {
        timeout: 30_000, maxBuffer: 1024 * 1024,
        env: createPythonProcessEnv(),
      })
      if (opts.json) {
        const result = JSON.parse(stdout)
        console.log(JSON.stringify(result))
      } else {
        console.log(stdout.trim())
      }
    } catch (e: any) {
      if (opts.json) {
        console.log(JSON.stringify({ success: false, error: safeSubprocessError(e) }))
        process.exit(1)
      }
      console.error(chalk.red(`✗ ${safeSubprocessError(e)}`))
      process.exit(1)
    }
  })

cacheProgram
  .command('enable')
  .description('开启缓存（显示安全警告与环境变量设置方法）')
  .action(async () => {
    console.log(chalk.yellow(`
⚠️  数据库缓存安全警告

开启缓存后，解密后的聊天记录会以明文形式存储在：
  %TEMP%\\weflow-cli-cache\\databases\\
  
任何能读取该目录的进程都能看到聊天内容。

建议：
  ✅ 仅在本地开发环境使用
  ❌ 不要把缓存目录同步到云盘（OneDrive / iCloud 等）
  🔒 定期清理缓存（weflow-cli cache clear）
  🔒 离开电脑时锁屏

开启方法（设置环境变量）：

  PowerShell:
    $env:WEFLOW_CACHE_ENABLED = '1'
    
  CMD:
    set WEFLOW_CACHE_ENABLED=1
    
  持久化（Windows 系统环境变量）：
    setx WEFLOW_CACHE_ENABLED 1
    
验证：
    weflow-cli cache status
`))
  })

cacheProgram
  .command('disable')
  .description('关闭缓存（显示环境变量清理方法）')
  .action(async () => {
    console.log(chalk.cyan(`
关闭缓存（清除环境变量）：

  PowerShell（当前会话）:
    $env:WEFLOW_CACHE_ENABLED = ''
    
  CMD（当前会话）:
    set WEFLOW_CACHE_ENABLED=
    
  持久化（Windows 系统环境变量）：
    reg delete HKCU\\Environment /v WEFLOW_CACHE_ENABLED /f
    
验证：
    weflow-cli cache status

注意：关闭后不会自动删除已有缓存，需要手动清理：
    weflow-cli cache clear
`))
  })

cacheProgram
  .command('clear')
  .description('清空所有缓存')
  .option('--json', '输出 JSON 格式')
  .action(async (opts) => {
    const { execFile } = await import('child_process')
    const { promisify } = await import('util')
    const execFileAsync = promisify(execFile)
    const script = join(resolvePackageRoot(), 'scripts', 'manage_cache.py')
    try {
      const { stdout } = await execFileAsync(getPythonCommand(), [script, 'clear', ...(opts.json ? ['--json'] : [])], {
        timeout: 30_000, maxBuffer: 1024 * 1024,
        env: createPythonProcessEnv(),
      })
      if (opts.json) {
        const result = JSON.parse(stdout)
        console.log(JSON.stringify(result))
      } else {
        console.log(stdout.trim())
      }
    } catch (e: any) {
      if (opts.json) {
        console.log(JSON.stringify({ success: false, error: safeSubprocessError(e) }))
        process.exit(1)
      }
      console.error(chalk.red(`✗ ${safeSubprocessError(e)}`))
      process.exit(1)
    }
  })

cacheProgram
  .command('list')
  .description('列出所有缓存文件')
  .option('--json', '输出 JSON 格式')
  .action(async (opts) => {
    const { execFile } = await import('child_process')
    const { promisify } = await import('util')
    const execFileAsync = promisify(execFile)
    const script = join(resolvePackageRoot(), 'scripts', 'manage_cache.py')
    try {
      const { stdout } = await execFileAsync(getPythonCommand(), [script, 'list', ...(opts.json ? ['--json'] : [])], {
        timeout: 30_000, maxBuffer: 1024 * 1024,
        env: createPythonProcessEnv(),
      })
      console.log(stdout.trim())
    } catch (e: any) {
      if (opts.json) {
        console.log(JSON.stringify({ success: false, error: safeSubprocessError(e) }))
        process.exit(1)
      }
      console.error(chalk.red(`✗ ${safeSubprocessError(e)}`))
      process.exit(1)
    }
  })

cacheProgram
  .command('prune <days>')
  .description('删除超过指定天数未访问的缓存')
  .option('--json', '输出 JSON 格式')
  .action(async (days: string, opts) => {
    const daysNum = parseCliInteger(days, 'days', 1, 36_500, opts.json)
    const { execFile } = await import('child_process')
    const { promisify } = await import('util')
    const execFileAsync = promisify(execFile)
    const script = join(resolvePackageRoot(), 'scripts', 'manage_cache.py')
    try {
      const { stdout } = await execFileAsync(getPythonCommand(), [script, 'prune', String(daysNum), ...(opts.json ? ['--json'] : [])], {
        timeout: 30_000, maxBuffer: 1024 * 1024,
        env: createPythonProcessEnv(),
      })
      if (opts.json) {
        const result = JSON.parse(stdout)
        console.log(JSON.stringify(result))
      } else {
        console.log(stdout.trim())
      }
    } catch (e: any) {
      if (opts.json) {
        console.log(JSON.stringify({ success: false, error: safeSubprocessError(e) }))
        process.exit(1)
      }
      console.error(chalk.red(`✗ ${safeSubprocessError(e)}`))
      process.exit(1)
    }
  })

// ==================== avatar（联系人头像，读 head_image.db） ====================
// 2026-10-26 NT 数据库普查的直接产物（docs/NT_DATABASES.md）：头像本体内嵌在
// head_image.db 里（JPEG/PNG 完整字节，按 username 键控，一人多行=变更历史），
// 比文件缓存可靠（清理不丢）。本地只读、不联网。
program
  .command('avatar [contact]')
  .description('导出联系人头像（读 head_image.db；--list 看谁有头像，--all 批量导出最新头像）')
  .option('--list', '只列出有头像的 username 与头像数')
  .option('--all', '导出所有 username 的最新头像到 --out 目录')
  .option('--out <path>', '输出文件（单联系人）或目录（--all），默认 output/avatars/')
  .option('--json', '输出 JSON 格式')
  .action(async (contact: string | undefined, opts) => {
    if (!contact && !opts.list && !opts.all) {
      if (opts.json) { console.log(JSON.stringify({ success: false, code: 'INVALID_ARGUMENT', error: '要给联系人，或用 --list / --all' })); process.exit(1) }
      console.error(chalk.red('✗ 要给联系人，或用 --list / --all'))
      process.exit(1)
    }
    if (contact && (opts.list || opts.all)) {
      if (opts.json) { console.log(JSON.stringify({ success: false, code: 'INVALID_ARGUMENT', error: '联系人与 --list/--all 互斥' })); process.exit(1) }
      console.error(chalk.red('✗ 联系人与 --list/--all 互斥'))
      process.exit(1)
    }
    const { execFile } = await import('child_process')
    const { promisify } = await import('util')
    const execFileAsync = promisify(execFile)
    const script = join(resolvePackageRoot(), 'scripts', 'wechat_avatar.py')
    const args = [script, ...(opts.list ? ['--list'] : opts.all ? ['--all'] : []), '--json']
    // D-020：联系人标识走环境变量，不进 argv；输出路径同理（脚本 --out 缺省读它）
    const env = {
      ...(contact ? { WEFLOW_TALKER: String(contact) } : {}),
      ...(opts.out ? { WEFLOW_AVATAR_OUT: String(opts.out) } : {}),
    }
    try {
      const { stdout } = await execFileAsync(getPythonCommand(), args, {
        timeout: 120_000, maxBuffer: 10 * 1024 * 1024,
        env: createPythonProcessEnv(env),
      })
      const payload = JSON.parse(stdout.slice(stdout.indexOf('{')))
      if (opts.json) { console.log(JSON.stringify(payload)); if (!payload.success) process.exit(1); return }
      if (!payload.success) { console.error(chalk.red(`✗ ${payload.error}`)); process.exit(1) }
      if (payload.action === 'avatar.export') {
        console.log(chalk.green(`✓ 已导出「${payload.username}」的最新头像（${payload.bytes} 字节，历史 ${payload.historyCount} 张）→ ${payload.out}`))
      } else if (payload.action === 'avatar.export-all') {
        console.log(chalk.green(`✓ 已导出 ${payload.written} 个最新头像 → ${payload.dir}`))
      } else {
        console.log(payload.error || `共 ${payload.users?.length ?? '?'} 个 username 有头像（用 --json 看全表）`)
      }
    } catch (e: any) {
      if (opts.json) { console.log(JSON.stringify({ success: false, code: 'AVATAR_FAILED', error: safeSubprocessError(e) })); process.exit(1) }
      console.error(chalk.red(`✗ ${safeSubprocessError(e)}`))
      process.exit(1)
    }
  })

// ==================== extras（NT 库里其余那些还没人读过的东西） ====================
// 2026-10-27 普查的第二个产物（docs/NT_DATABASES.md）：`avatar`/`media`/`ledger` 之后
// 还剩 general/session/emoticon/solitaire/bizchat 没人读。
//
// 三条取舍写在这里，因为它们看起来都像"该帮忙翻译一下"：
//   · 未验证的枚举**原样给数字**，结果里带 `unverifiedEnums`。`SessionTable.type`
//     在本机是常量 0（710/710），拿它当分类维度会得到"全中/全空"两种假象。
//   · 空表**如实报 0**。`chatbot_message.db` 四张表全 0 行、`revoke` 的 revokemessage
//     0 行——"有表无记录"不等于"没这个功能"。
//   · `emoticon.db` 的 `aes_key` **解不开**图片（带正对照验证过），所以只给元数据。
const EXTRAS_KINDS = ['overview', 'search-history', 'sessions', 'emoticons', 'fmessages',
  'solitaire', 'biz-subscribe', 'revoke', 'bizchat', 'all'] as const

program
  .command('extras [kind]')
  .description('NT 库里其余那些还没人读过的东西（general/session/emoticon/solitaire/bizchat；本地只读、不联网）')
  .option('--db <path>', 'message_0.db 路径（默认取配置 ntDbPath）')
  .option('--unread', 'sessions 额外带上未读明细（本机 2.6 万行）')
  .option('--json', '输出 JSON 格式')
  .action(async (kind: string | undefined, opts) => {
    const kindsList = EXTRAS_KINDS.join('、')
    if (!kind) {
      if (opts.json) { console.log(JSON.stringify({ success: false, code: 'INVALID_ARGUMENT', error: `要给一个 kind：${kindsList}` })); process.exit(1) }
      console.error(chalk.red(`✗ 要给一个 kind：${kindsList}`))
      console.error(chalk.gray('  例：weflow-cli extras search-history'))
      process.exit(1)
    }
    if (!(EXTRAS_KINDS as readonly string[]).includes(kind)) {
      if (opts.json) { console.log(JSON.stringify({ success: false, code: 'INVALID_ARGUMENT', field: 'kind', error: `kind 必须是 ${kindsList}` })); process.exit(1) }
      console.error(chalk.red(`✗ kind 必须是 ${kindsList}`))
      process.exit(1)
    }
    const { execFile } = await import('child_process')
    const { promisify } = await import('util')
    const execFileAsync = promisify(execFile)
    const script = join(resolvePackageRoot(), 'scripts', 'wechat_extras.py')
    const args = [script, kind, ...(opts.unread ? ['--unread'] : [])]
    try {
      const { stdout } = await execFileAsync(getPythonCommand(), args, {
        timeout: 180_000, maxBuffer: 64 * 1024 * 1024,
        // 库路径走环境变量（D-020 的规矩：不给 argv）
        env: createPythonProcessEnv(opts.db ? { WEFLOW_EXTRAS_DB: String(opts.db) } : {}),
      })
      const payload = JSON.parse(stdout.slice(stdout.indexOf('{')))
      if (opts.json) { console.log(JSON.stringify(payload)); if (!payload.success) process.exit(1); return }
      if (!payload.success && !Object.keys(payload.results || {}).length) {
        console.error(chalk.red(`✗ ${Object.values(payload.errors || {}).join('；') || '读取失败'}`))
        process.exit(1)
      }
      for (const [name, data] of Object.entries<any>(payload.results || {})) {
        printExtrasBlock(name, data)
      }
      for (const [name, error] of Object.entries<any>(payload.errors || {})) {
        console.error(chalk.yellow(`⚠ ${name}: ${error}`))
      }
    } catch (e: any) {
      if (opts.json) { console.log(JSON.stringify({ success: false, code: 'EXTRAS_FAILED', error: safeSubprocessError(e) })); process.exit(1) }
      console.error(chalk.red(`✗ ${safeSubprocessError(e)}`))
      process.exit(1)
    }
  })

/** `extras` 的人类可读摘要。JSON 才是完整数据，这里只给"有多少、长什么样"。 */
function printExtrasBlock(name: string, data: any): void {
  console.log(chalk.cyan(`\n=== ${name} ===`))
  if (data.db) console.log(chalk.gray(`  ${data.db} · ${data.dbPath}`))
  const counts = data.counts
  if (counts) {
    console.log('  ' + Object.entries(counts).map(([k, v]) => `${k}=${v}`).join('  '))
  }
  if (name === 'overview') {
    for (const lib of data.libraries || []) {
      if (!lib.exists) { console.log(chalk.gray(`  ${lib.db.padEnd(16)} 不存在`)); continue }
      const empty = (lib.tables || []).filter((t: any) => !t.rows).map((t: any) => t.name)
      const unread = (lib.tables || []).filter((t: any) => t.rows === null).length
      console.log(`  ${lib.db.padEnd(16)} tables=${String((lib.tables || []).length).padEnd(3)}`
        + ` 空表=${empty.length}${unread ? ` 读不出=${unread}` : ''}`)
    }
    console.log(chalk.gray(`  共 ${data.tableCount} 张表，其中 ${data.nonEmptyTableCount} 张有数据`))
  } else if (name === 'search-history') {
    for (const row of (data.rows || []).slice(0, 12)) {
      const when = row.time ? new Date(row.time * 1000).toLocaleString('zh-CN', { hour12: false }) : '?'
      const scene = row.scene === undefined ? '' : chalk.gray(` scene=${row.scene}`)
      console.log(`  [${when}] ${row.source.padEnd(13)} ${row.keyword || row.username || ''}${scene}`)
    }
    console.log(chalk.gray(`  ${data.note || ''}`))
  } else if (name === 'sessions') {
    for (const row of (data.sessions || []).slice(0, 10)) {
      const when = row.lastTimestamp ? new Date(row.lastTimestamp * 1000).toLocaleString('zh-CN', { hour12: false }) : '?'
      const badge = row.unreadCount ? chalk.yellow(`未读${row.unreadCount}`) : chalk.gray('已读')
      const hidden = row.isHidden ? chalk.gray(' [隐藏]') : ''
      console.log(`  [${when}] ${badge} ${row.username}${hidden}  ${row.summary || ''}`.slice(0, 120))
    }
    if ((data.deleted || []).length) {
      console.log(chalk.gray('  删过的会话（只剩这张表有痕迹）：'))
      for (const row of data.deleted) {
        const when = row.deleteTime ? new Date(row.deleteTime * 1000).toLocaleString('zh-CN', { hour12: false }) : '?'
        console.log(chalk.gray(`    [${when}] ${row.username}`))
      }
    }
    if (data.unreadJoin) {
      console.log(chalk.gray(`  未读明细：${data.unreadJoin.resolved} 条解出会话、`
        + `${data.unreadJoin.unresolved} 条解不到`))
    }
    console.log(chalk.gray(`  ${data.note || ''}`))
  } else if (name === 'emoticons') {
    for (const pkg of (data.packages || []).slice(0, 8)) {
      console.log(`  表情包 ${pkg.name || pkg.packageId}  作者=${pkg.author || '?'}`)
    }
    for (const item of (data.custom || []).slice(0, 6)) {
      console.log(`  自定义 ${item.md5.slice(0, 10)}…  ${item.caption || ''}`)
    }
    if (data.notDecryptable) {
      console.log(chalk.yellow(`  ⚠ ${data.notDecryptable.what} 拿不到：${data.notDecryptable.why}`))
    }
  } else if (name === 'fmessages') {
    for (const row of (data.rows || []).slice(0, 10)) {
      const when = row.time ? new Date(row.time * 1000).toLocaleString('zh-CN', { hour12: false }) : '?'
      console.log(`  [${when}] ${row.isSender ? '我发' : '收到'} ${row.username}  ${row.content || ''}`)
    }
  } else if (name === 'solitaire') {
    for (const g of (data.groups || [])) {
      console.log(`  ${g.session || g.sessionMd5 + '（未解出会话）'}  `
        + `主体=${g.main.length} 有效=${g.valid.length} 折叠=${g.folded.length}`)
    }
    console.log(chalk.gray(`  ${data.note || ''}`))
  } else if (name === 'revoke') {
    for (const row of (data.revokedBatches || []).slice(0, 10)) {
      const when = row.msgCreateTime ? new Date(row.msgCreateTime * 1000).toLocaleString('zh-CN', { hour12: false }) : '?'
      console.log(`  批量撤回 [${when}] ${row.session}`)
    }
    console.log(chalk.gray(`  ${data.note || ''}`))
  } else if (name === 'biz-subscribe') {
    if (data.joins) {
      console.log(chalk.gray(`  订阅 ∩ 小程序资料卡：${data.joins.subscribedWithMiniProgramCard} 有卡、`
        + `${data.joins.subscribedWithoutCard} 无卡；另 ${data.joins.miniProgrammingNotSubscribed} 个有卡未订阅`))
    }
    for (const w of (data.miniPrograms || []).filter((x: any) => x.name).slice(0, 10)) {
      console.log(`  ${w.name}  ${chalk.gray(w.englishId || '')}  ${(w.description || '').slice(0, 24)}`)
    }
    console.log(chalk.gray(`  ${data.note || ''}`))
  } else if (name === 'bizchat') {
    // counts 已经打过了，没有更细的摘要可给
  }
  if (data.readErrors) {
    for (const err of data.readErrors) {
      console.error(chalk.yellow(`  ⚠ 读失败 ${err.what}：${err.error}`))
    }
  }
  if (data.unverifiedEnums) {
    console.log(chalk.gray('  未验证的枚举（原样给数字）：'
      + Object.entries(data.unverifiedEnums).map(([k, v]) => `${k}（${v}）`).join('；')))
  }
}

// ==================== contacts ====================
// contact-schema：读 contact.db 里**群**的 ext_buffer（本地只读：不联网、不调模型）
//
// 只解**实测验证过**的那几个字段（成员 userName/displayName/status/inviter + `#5`）；
// `#5` 曾经叫"附加参与者 id"，实测是**成员 status 位 11 置位的那批 id**（本机 77/77 集合相等），
// 所以输出改用 `statusBit11Ids`、不再说"额外参与者"（见 D-070）。
// 顶层 `#3`/`#4` 的语义在本机被三次证伪（不是成员 id / 房间 id / 消息侧 id），所以脚本把它们
// 原样放进 `unrecognized`，**不猜名字** —— 拿猜出来的名字写逻辑，就是拿不确定当事实。
// 结构笔记见 `docs/CONTACT_DB_SCHEMA.md`，取舍见 D-067 / D-068 / D-070。
//
// `--contacts`（2026-10-07 加）：同一个命令改读**联系人**的 `contact.extra_buffer`，输出这一轮验证的
// 三个字段 —— `#5` 国家/地区码（ISO 3166-1 alpha-2）、`#13` = 该行 `biz_info.type`、`#41` = 资料最近更新时间。
// `#4`/`#9` 已定性为"账号自身资料文本的汇集"，是**内容**不是字段名，**故意不打印**（见 D-088）。
program
  .command('contact-schema')
  .description('读 contact.db 的 ext_buffer：默认读群（成员 + #5）；--contacts 读联系人（#5 地区码 / #13 服务类型 / #41 更新时间）—— 只解已验证字段，未识别的原样标注（本地、只读）')
  .option('-n, --limit <n>', '最多看几个（群 / 联系人）', '20')
  .option('--room <which>', '只看某个（群 / 联系人 的 username 或 id）')
  .option('--contacts', '改读联系人的 extra_buffer，而不是群')
  .option('--json', '输出机器可读结果')
  .action(async (opts) => {
    const { execFile } = await import('child_process')
    const { promisify } = await import('util')
    const execFileAsync = promisify(execFile)
    const script = join(resolvePackageRoot(), 'scripts', 'contact_schema.py')
    const limit = parseCliInteger(opts.limit, 'limit', 1, 100000, !!opts.json)
    const args = [script, '--limit', String(limit),
                  ...(opts.room ? ['--room', opts.room] : []),
                  ...(opts.contacts ? ['--contacts'] : []),
                  ...(opts.json ? ['--json'] : [])]
    try {
      const { stdout, stderr } = await execFileAsync(getPythonCommand(), args, {
        timeout: 300_000, maxBuffer: 64 * 1024 * 1024, env: pythonProcessEnv(),
      })
      process.stdout.write(stdout)
      if (stderr && !opts.json) process.stderr.write(stderr)
    } catch (error) {
      if (opts.json) {
        console.log(JSON.stringify({ success: false, code: 'CONTACT_SCHEMA_FAILED', action: 'contact-schema', error: safeSubprocessError(error) }))
      } else {
        console.error(chalk.red(`\n✗ ${safeSubprocessError(error)}`))
      }
      process.exit(1)
    }
  })

program
  .command('contacts')
  .description('查看联系人列表')
  .option('-k, --keyword <keyword>', '搜索关键词 (自动扩大搜索范围)')
  .option('-n, --limit <number>', '最大数量', '500')
  .option('--json', '输出 JSON 格式')
  .action(async (opts) => {
    const limit = parseCliInteger(opts.limit, 'limit', 1, 5000, !!opts.json)
    if (!configService.isConfigured()) {
      if (opts.json) { console.log(JSON.stringify({ success: false, error: '未完成初始化' })); process.exit(1) }
      {
        const { unconfiguredHint } = await import('../src/utils/unconfiguredHint.js')
        console.log(chalk.red(unconfiguredHint()))
      }
      process.exit(1)
    }

    const contacts = await chatService.listContacts(opts.keyword, limit)
    if (contacts.length === 0) {
      if (opts.json) { console.log(JSON.stringify({ success: true, contacts: [] })); return }
      console.log(chalk.gray('未找到联系人'))
      return
    }

    if (opts.json) {
      console.log(JSON.stringify({ success: true, contacts }, null, 2))
      return
    }
    console.log(chalk.cyan(`联系人列表 (${contacts.length} 条):\n`))
    console.log(chalk.gray('序号  用户ID                昵称/备注'))
    console.log(chalk.gray('─'.repeat(60)))

    for (let i = 0; i < contacts.length; i++) {
      const c = contacts[i]
      const num = String(i + 1).padStart(3)
      const id = (c.username || '').padEnd(20)
      const name = c.remark || c.displayName || c.nickname || ''
      console.log(`${num}  ${id} ${name}`)
    }
  })

// ==================== export ====================
program
  .command('export <talker> <format>')
  .description('导出聊天记录 (支持 wxid / 昵称 / 备注 / 序号)')
  .option('-o, --output <dir>', '输出目录', './output')
  .option('-n, --limit <number>', '最大数量（0=全量导出）', '0')
  .option('-d, --date <YYYY-MM-DD>', '仅导出指定日期的消息（本地时间）')
  .option('--from <date>', '起始日期或 ISO 时间')
  .option('--to <date>', '结束日期或 ISO 时间')
  .option('--contract <name>', 'JSON 数据契约：raw 或 weflow-v1', 'raw')
  .option('--json', '输出机器可读的导出结果，不改变导出文件格式')
  .option('--non-interactive', '禁止交互选择；匹配不唯一时返回错误')
  .option('--full-images', '使用原图而非微信缓存缩略图（更清晰，但导出慢数倍）')
  .option('--media', 'json/txt/excel 导出时一并抽出图片与文档（落盘到 <输出>/<会话>_assets，并在导出物里给出相对路径）')
  .action(async (talkerInput: string, format: string, opts) => {
    const validFormats = ['json', 'txt', 'html', 'md', 'excel']
    if (!validFormats.includes(format)) {
      if (opts.json) console.log(JSON.stringify({ success: false, code: 'INVALID_FORMAT', error: '导出格式无效', supported: validFormats }))
      else {
        console.log(chalk.red(`无效格式: ${format}`))
        console.log(chalk.gray(`可用: ${validFormats.join(', ')}`))
      }
      process.exit(1)
    }
    const limit = parseCliInteger(opts.limit, 'limit', 0, 1_000_000, !!opts.json)
    if (!configService.isConfigured()) {
      if (opts.json) console.log(JSON.stringify({ success: false, code: 'NOT_INITIALIZED', error: '未完成初始化' }))
      else {
        console.log(chalk.red('\n❌ 还没配置'))
        console.log(chalk.gray('  运行: weflow-cli init\n'))
      }
      process.exit(1)
    }

    const talker = await resolveTalker(talkerInput, !!opts.json, opts.nonInteractive || opts.json)

    if (!opts.json) console.log(chalk.cyan(`正在导出 ${talker} 的聊天记录 (${format})...\n`))

    let result
    let from: number | undefined
    let to: number | undefined
    try {
      const range = resolveExportDateRange({
        date: opts.date,
        from: opts.from,
        to: opts.to,
        preserveDateForRichHtml: format === 'html',
      })
      from = range.from
      to = range.to
    } catch (error) {
      const dateError = error instanceof DateRangeError ? error : new DateRangeError('INVALID_DATE', '导出日期无效')
      if (opts.json) console.log(JSON.stringify({ success: false, code: dateError.code, error: dateError.message }))
      else console.log(chalk.red(dateError.message))
      process.exit(1)
    }
    if (!['raw', 'weflow-v1'].includes(opts.contract)) {
      if (opts.json) console.log(JSON.stringify({ success: false, code: 'INVALID_CONTRACT', error: '数据契约无效', supported: ['raw', 'weflow-v1'] }))
      else {
        console.log(chalk.red(`不支持的数据契约: ${opts.contract}`))
        console.log(chalk.gray('可用: raw, weflow-v1'))
      }
      process.exit(1)
    }
    // 图片要靠 Python 那条路匹配（缓存缩略图、资源 md5、原图那档）。`--media` 就是"先抽一次"，
    // 抽完 json/txt/excel 各自消费同一份清单 —— 匹配只跑一遍，也不会在 TS 里重写一遍。
    // 抽取那一步的媒体摘要留在这里：`--media` 的调用者（机器调用）应当能从结果里直接读到
    // "各状态多少条、报告叫什么"，而不必去翻 Python 的 stdout。
    let extracted: ExportResult | undefined
    if (opts.media && (format === 'json' || format === 'txt' || format === 'excel')) {
      const media = await exportService.extractMedia(talker, opts.output, !!opts.json, { fullImages: opts.fullImages === true }, limit, opts.date || '')
      extracted = media
      if (!media.success) {
        if (opts.json) console.log(JSON.stringify({ success: false, code: 'MEDIA_EXPORT_FAILED', error: media.error || '媒体抽取失败' }))
        else console.log(chalk.red(`✗ 媒体抽取失败: ${media.error}`))
        process.exit(1)
      }
    } else if (opts.media && format === 'html') {
      // HTML 的用法是"单文件可分享"，所以它不写文档本体（把几 MB 的 PDF 内嵌进网页，既打不开也把文件撑大）。
      // 静默忽略这个开关会让人以为它生效了 —— 明说一句，并给出该用哪个格式。
      if (!opts.json) {
        console.error(chalk.gray('  提示：HTML 导出不含文档本体（单文件分享的用法），--media 对它不生效；'))
        console.error(chalk.gray('        要连文档一起导出请用 md，或 json|txt|excel --media。'))
      }
    }
    switch (format) {
      case 'json':
        result = await exportService.exportJson(talker, opts.output, limit, from, to, opts.contract)
        break
      case 'txt':
        result = await exportService.exportTxt(talker, opts.output, limit, from, to)
        break
      case 'html':
        result = await exportService.exportHtml(talker, opts.output, limit, opts.date || '', from, to, !!opts.json, { fullImages: opts.fullImages === true })
        break
      case 'md':
        // markdown + 图片落盘（`<输出>/<talker>_assets/`）；json/txt/excel 之后会自动带上那些图。
        result = await exportService.exportMarkdown(talker, opts.output, limit, opts.date || '', from, to, !!opts.json, { fullImages: opts.fullImages === true })
        break
      case 'excel':
        result = await exportService.exportExcel(talker, opts.output, limit, from, to)
        break
    }

    if (result?.success) {
      if (opts.json) console.log(JSON.stringify({
        success: true,
        format,
        contract: format === 'json' ? opts.contract : null,
        path: result.path,
        count: result.count ?? null,
        // 媒体摘要：html/md 那条由导出自己产出（Python 的 media_json_summary），
        // json/txt/excel 的 `--media` 则由上面那次抽取产出 —— 两条都是同一份词汇。
        media: result.media ?? extracted?.media ?? null,
      }, null, 2))
      else console.log(chalk.green(`✓ 导出成功: ${result.path}`))
    } else {
      if (opts.json) console.log(JSON.stringify({ success: false, code: 'EXPORT_FAILED', error: result?.error || '导出失败' }))
      else console.log(chalk.red(`✗ 导出失败: ${result?.error}`))
      process.exit(1)
    }
  })

// ==================== evidence ====================
program
  .command('evidence <talker>')
  .description('整理本地聊天证据包（原始消息、哈希与保全说明）')
  .option('-o, --output <dir>', '证据包输出目录', './output/evidence')
  .option('-n, --limit <number>', '最多包含消息数', '10000')
  .option('--case <note>', '案件或争议说明（仅保存在本地证据包）')
  .option('--json', '输出 JSON 格式')
  .option('--non-interactive', '禁止交互选择；匹配不唯一时返回错误')
  .action(async (talkerInput: string, opts) => {
    if (!configService.isConfigured()) {
      if (opts.json) {
        console.log(JSON.stringify({ success: false, code: 'NOT_INITIALIZED', error: '未完成初始化' }))
        process.exit(1)
      }
      console.log(chalk.red('\n❌ 还没配置'))
      console.log(chalk.gray('  运行: weflow-cli init\n'))
      process.exit(1)
    }
    const talker = await resolveTalker(talkerInput, opts.json, opts.nonInteractive || opts.json)
    const limit = parseCliInteger(opts.limit, 'limit', 1, 100000, opts.json)
    const messages = await chatService.getMessages(talker, limit)
    if (messages.length === 0) {
      if (opts.json) { console.log(JSON.stringify({ success: false, code: 'NO_MESSAGES', error: '未找到消息' })); return }
      console.log(chalk.gray('未找到消息，未创建证据包'))
      return
    }
    const result = writeEvidencePackage(opts.output, talker, messages, opts.case)
    if (opts.json) {
      console.log(JSON.stringify({ success: true, path: result.path, manifest: result.manifest }, null, 2))
      return
    }
    console.log(chalk.green(`✓ 证据包已创建: ${result.path}`))
    console.log(chalk.gray(`  消息: ${result.manifest.messageCount} 条`))
    console.log(chalk.gray(`  SHA-256: ${result.manifest.messagesSha256}`))
    console.log(chalk.yellow('  注意: 哈希用于证明文件未被改动，不等于证明内容真实或必然具有法律效力。'))
  })

program
  .command('evidence-review <talker>')
  .description('用 AI 整理聊天中的法律争议线索（不提供法律结论）')
  .option('-o, --output <dir>', '分析结果输出目录', './output/evidence-review')
  .option('-n, --limit <number>', '最多分析消息数', '500')
  .option('--allow-cloud', '明确允许将按隐私模式处理后的内容发送到云端 AI')
  .option('--dry-run', '仅预览，不读取聊天、调用 AI 或写入分析结果')
  .option('--yes', '确认读取聊天并生成分析结果')
  .option('--json', '输出机器可读结果，不返回分析正文')
  .action(async (talkerInput: string, opts) => {
    const limit = parseCliInteger(opts.limit, 'limit', 1, 5000, !!opts.json)
    const preview = {
      success: true,
      dryRun: true,
      action: 'evidence-review',
      limit,
      readsLocalChat: true,
      usesAi: true,
      cloudAllowed: Boolean(opts.allowCloud),
      writesLocalResult: true,
    }
    if (opts.dryRun) {
      if (opts.json) console.log(JSON.stringify(preview))
      else console.log(chalk.cyan(`预览：将读取最多 ${limit} 条指定会话消息，调用${opts.allowCloud ? '已授权的云端或本地' : '本地'}模型并写入分析结果。`))
      return
    }
    if (!opts.yes) {
      if (opts.json) {
        console.log(JSON.stringify({ ...preview, success: false, dryRun: false, code: 'CONFIRMATION_REQUIRED' }))
        process.exit(1)
      }
      const { confirmed } = await inquirer.prompt([{
        type: 'confirm',
        name: 'confirmed',
        message: `确认读取指定会话并使用${opts.allowCloud ? '已授权的云端或本地' : '本地'}模型生成争议线索分析吗？`,
        default: false,
      }])
      if (!confirmed) {
        console.log(chalk.gray('已取消'))
        return
      }
    }
    if (!configService.isConfigured()) {
      if (opts.json) console.log(JSON.stringify({ success: false, code: 'NOT_INITIALIZED', error: '未完成初始化' }))
      else {
        console.log(chalk.red('\n❌ 还没配置'))
        console.log(chalk.gray('  运行: weflow-cli init\n'))
      }
      process.exit(1)
    }
    const talker = await resolveTalker(talkerInput, !!opts.json, !!opts.json)
    const messages = await chatService.getMessages(talker, limit)
    if (messages.length === 0) {
      if (opts.json) console.log(JSON.stringify({ success: false, code: 'NO_MESSAGES', error: '未找到消息，未创建分析结果' }))
      else console.log(chalk.gray('未找到消息，未创建分析结果'))
      return
    }
    const { AssistantService } = await import('../src/services/assistantService.js')
    const result = await new AssistantService().reviewEvidence(talker, messages, Boolean(opts.allowCloud))
    const { mkdirSync } = await import('fs')
    mkdirSync(opts.output, { recursive: true })
    const outputPath = join(opts.output, `${Date.now()}-${talker.replace(/[^a-zA-Z0-9._-]+/g, '_').slice(0, 60)}.md`)
    writeFileSync(outputPath, [
      '# 聊天法律争议线索整理', '',
      `- 会话：${talker}`,
      `- 消息数：${messages.length}`,
      `- 推理方式：${result.localInference ? '本地模型' : '云端模型（已按隐私模式处理）'}`,
      `- 脱敏次数：${result.redactions}`,
      '', result.text, '',
      '---', '',
      '本文件仅供线索整理，不是法律意见，不代表违法认定或法院必然采信。请保留原设备、原始数据和完整上下文，并咨询专业人士。',
    ].join('\n'), 'utf8')
    if (opts.json) {
      console.log(JSON.stringify({
        success: true,
        action: 'evidence-review',
        count: messages.length,
        outputCreated: true,
        localInference: result.localInference,
        redactions: result.redactions,
        cloudAllowed: Boolean(opts.allowCloud),
      }, null, 2))
      return
    }
    console.log(chalk.green(`✓ 分析结果已保存: ${outputPath}`))
    console.log(chalk.yellow(`  ${result.localInference ? '使用本地模型，聊天正文未离开本机' : '已使用云端模型，请确认隐私模式和授权范围'}`))
  })

// ==================== dbkey ====================
program
  .command('dbkey')
  .description('从运行中的微信进程提取数据库解密密钥 (自动检测版本)')
  .option('-t, --timeout <ms>', '超时时间(毫秒)', '60000')
  .option('--force', '即使已有本地配置也执行捕获')
  .option('--dry-run', '仅预览，不扫描进程内存或捕获密钥')
  .option('--yes', '确认启动人工密钥捕获流程')
  .option('--json', '输出机器可读预览；实际捕获必须在交互终端执行')
  .action(async (opts) => {
    const configured = configService.isConfigured()
    const preview = {
      success: true,
      dryRun: true,
      action: 'dbkey.capture',
      interactiveRequired: true,
      scansProcessMemory: true,
      captureRequired: Boolean(opts.force || !configured),
      writesConfiguration: false,
    }
    if (opts.dryRun) {
      if (opts.json) console.log(JSON.stringify(preview))
      else console.log(chalk.cyan(`密钥捕获预览：${preview.captureRequired ? '将扫描运行中的微信进程' : '已有本地配置，默认不会重复捕获'}`))
      return
    }
    if (!opts.force && configured) {
      if (opts.json) {
        console.log(JSON.stringify({ success: true, action: 'dbkey.reuse', captureSkipped: true }))
        return
      }
      console.log(chalk.cyan('🔑 提取微信数据库密钥\n'))
      console.log(chalk.green('✓ 已检测到本地数据库访问配置，未重复捕获密钥。'))
      console.log(chalk.gray('  可直接运行 weflow-cli sessions 验证访问。'))
      console.log(chalk.gray('  仅在需要排障时使用 --force。'))
      return
    }
    if (opts.json) {
      console.log(JSON.stringify({ ...preview, success: false, dryRun: false, code: 'INTERACTIVE_REQUIRED' }))
      process.exit(1)
    }
    if (!opts.yes) {
      const { confirmed } = await inquirer.prompt([{
        type: 'confirm',
        name: 'confirmed',
        message: '确认启动需要人工配合的数据库密钥捕获流程吗？',
        default: false,
      }])
      if (!confirmed) {
        console.log(chalk.gray('已取消'))
        return
      }
    }
    console.log(chalk.cyan('🔑 提取微信数据库密钥\n'))
    console.log(chalk.gray('请确保微信已登录且正在运行。\n'))

    if (process.platform === 'linux') {
      // Linux：/proc 内存扫描提取 NT 密钥
      const { NtCore } = await import('../src/core/ntCore.js')
      const result = await NtCore.scan()
      if (result.success && result.matched && result.matched.length > 0) {
        for (const db of result.matched) {
          console.log(chalk.green(`✓ ${db.name} (${(db.size / 1024 / 1024).toFixed(1)}MB)`))
          console.log(chalk.white('  密钥: 已匹配，未显示'))
          console.log(chalk.white('  盐值: 已匹配，未显示'))
        }
        console.log(chalk.gray('\n提示: 运行 weflow-cli init 可自动写入配置'))
      } else if (result.error?.includes('PERMISSION_DENIED')) {
        console.log(chalk.red('✗ 需要 root 或 CAP_SYS_PTRACE 权限'))
        console.log(chalk.gray('  授权: sudo setcap cap_sys_ptrace=ep $(which python3)'))
        process.exit(1)
      } else {
        console.log(chalk.red(`✗ ${result.error || '未匹配到密钥'}`))
        process.exit(1)
      }
      return
    }

    const version = await keyService.detectWeChatVersion()
    if (!version) {
      console.log(chalk.red('未检测到微信进程 (WeChat.exe 或 Weixin.exe)'))
      process.exit(1)
    }
    console.log(chalk.gray(`检测到微信 ${version} 版本\n`))

    if (version === '3.x') {
      const result = await keyService.extract3xKey((msg) => {
        console.log(chalk.gray(`  ${msg}`))
      })
      if (result.success && result.key) {
        console.log(chalk.green('\n✓ 密钥已捕获，未显示'))
        console.log(chalk.green('  账号与消息目录: 已识别，未显示'))
      } else {
        console.log(chalk.red(`\n✗ 失败: ${result.error}`))
        process.exit(1)
      }
    } else {
      // `opts.json` 也要传：这一行在 `--json` 下**不可达**（上面就 `INTERACTIVE_REQUIRED` 退出了），
      // 但少传一个是安静的 —— 规则统一成"校验 helper 一律带上它"，判据才写得出来
      // （`test/json-error-surface.test.ts` 末尾那条静态检查）。
      const timeout = parseCliInteger(opts.timeout, 'timeout', 1000, 600000, opts.json)
      const result = await keyService.autoGetDbKey(timeout, (msg) => {
        console.log(chalk.gray(`  ${msg}`))
      })
      if (result.success && result.key) {
        console.log(chalk.green('\n✓ 密钥已捕获，未显示'))
        console.log(chalk.gray('\n提示: 运行 weflow-cli init 可自动派生并写入各库密钥配置'))
      } else {
        console.log(chalk.red(`\n✗ 失败: ${result.error}`))
        process.exit(1)
      }
    }
  })

// ==================== scan ====================
program
  .command('scan')
  .description('扫描微信数据目录中的账号')
  .option('-p, --path <path>', '数据目录路径')
  .option('--json', '输出机器可读摘要，不返回路径、账号标识或昵称')
  .action(async (opts) => {
    const path = opts.path || configService.get('dbPath') || dbPathService.getDefaultPath()
    const wxids = dbPathService.scanWxidCandidates(path)
    if (opts.json) {
      console.log(JSON.stringify({ success: wxids.length > 0, accountCount: wxids.length }))
      return
    }
    console.log(chalk.cyan(`扫描目录: ${path}\n`))
    if (wxids.length === 0) {
      console.log(chalk.gray('未找到账号'))
      return
    }

    console.log(chalk.cyan(`找到 ${wxids.length} 个账号:\n`))
    for (const w of wxids) {
      const time = new Date(w.modifiedTime).toLocaleString('zh-CN')
      const nickname = w.nickname ? ` (${w.nickname})` : ''
      console.log(`  ${w.wxid}${nickname}  ${chalk.gray(time)}`)
    }
  })

// ==================== login-wechat ====================
program
  .command('login-wechat')
  .description('微信扫码登录，获取消息收发权限')
  .option('--base-url <url>', 'ilink 服务地址')
  .option('--dry-run', '仅预览，不请求二维码或修改登录状态')
  .option('--yes', '确认启动人工扫码登录流程')
  .option('--json', '输出机器可读预览；实际登录必须在交互终端执行')
  .action(async (opts) => {
    const token = configService.get('wechatOcToken')
    const preview = {
      success: true,
      dryRun: true,
      action: 'wechat-channel.login',
      interactiveRequired: true,
      replacesExistingSession: !!token,
    }
    if (opts.dryRun) {
      if (opts.json) console.log(JSON.stringify(preview))
      else console.log(chalk.cyan(`登录预览：需要人工扫码${token ? '，成功后将替换现有消息通道登录' : ''}`))
      return
    }
    if (opts.json) {
      console.log(JSON.stringify({ ...preview, success: false, dryRun: false, code: 'INTERACTIVE_REQUIRED' }))
      process.exit(1)
    }
    if (!opts.yes) {
      // stdin 不是终端时（管道、计划任务、会话里的 `!` 前缀执行）inquirer 会抛 ExitPromptError——
      // 屏幕上是一条堆栈而不是一句话。这里把它变成解释：扫码登录必须在真实终端里跑。
      // 与守护进程那条 `--yes` 是同一类毛病：交互确认被塞进一个没人能回答的 stdin。
      let confirmed = false
      try {
        const answer = await inquirer.prompt([{
          type: 'confirm',
          name: 'confirmed',
          message: token ? '已有登录状态，确认启动重新登录吗？' : '确认启动人工扫码登录吗？',
          default: false,
        }])
        confirmed = !!answer.confirmed
      } catch (error: any) {
        if (error?.name === 'ExitPromptError' || /force closed the prompt/.test(String(error?.message))) {
          console.log(chalk.yellow('当前环境没有可交互的终端。扫码登录必须在真实终端窗口里执行，'))
          console.log(chalk.yellow('或者加 --yes 跳过这个确认（扫码那一步仍然要人来做）。'))
          process.exit(1)
        }
        throw error
      }
      if (!confirmed) {
        console.log(chalk.gray(token ? '保持当前登录状态' : '已取消'))
        return
      }
    }

    console.log(chalk.cyan('正在获取登录二维码...\n'))
    const service = new WechatMessageService({ baseUrl: opts.baseUrl })

    try {
      const { qrcodeContent } = await service.startLogin()
      console.log(chalk.green('请用微信扫描以下二维码:\n'))

      // Print QR in terminal
      try {
        const QRCode = (await import('qrcode-terminal')).default
        QRCode.generate(qrcodeContent, { small: true })
      } catch {
        console.log(chalk.yellow('(终端二维码显示失败，请安装: npm install qrcode-terminal)'))
      }

      console.log(chalk.cyan('\n等待扫码 (约2分钟有效)...'))
      const session = await service.waitForLogin()

      if (session.status === 'confirmed') {
        console.log(chalk.green('\n✓ 登录成功!'))
        console.log(chalk.gray('  消息通道登录状态已安全保存'))
        // 助手的白名单为空时**拒绝所有人**：登录完对着自己的机器人说话，什么都不会回来。
        // 所以这里必须说清"下一步该干什么"。
        // 只打在人看的这条路上——`--json` 那条路照旧不返回账号标识。
        console.log('')
        console.log(chalk.cyan('  助手默认拒绝所有人（白名单为空）。'))
        // 这里**不**替用户写白名单：登录响应给的是 ilink_user_id，而白名单要的是入站消息里
        // 那个 from_user_id（文档里写成 <@im.wechat ID>），两者是不是同一个值**没有被验证过**
        // ——猜错的后果是"白名单非空、看着配好了、却仍然拒你"。真值在第一条被拒的消息里，
        // 所以让它自己现形（见 assistant log 的 [首次配置] 那行）。
        console.log(chalk.gray('  启用方式：先 assistant start，从你的微信给机器人发一条消息，'))
        console.log(chalk.gray('  日志里会出现一行 ' + chalk.cyan('[首次配置]')
          + chalk.gray(' 带着你自己的发送者 ID 和该执行的命令。')))
        console.log(chalk.gray('  只想先看它「本来会怎么答」而不改行为：')
          + chalk.cyan('weflow-cli config set assistantFastRoute log'))
      } else {
        console.log(chalk.red(`\n✗ 登录失败: ${session.error || '超时'}`))
      }
    } catch (e: any) {
      console.log(chalk.red(`\n✗ 登录失败: ${e.message}`))
    }
  })

// ==================== logout-wechat ====================
program
  .command('logout-wechat')
  .description('退出微信消息通道登录')
  .option('--dry-run', '仅预览，不清除登录状态')
  .option('--yes', '确认退出并清除消息通道状态')
  .option('--json', '输出机器可读结果')
  .action(async (opts) => {
    const loggedIn = !!configService.get('wechatOcToken')
    const preview = {
      success: true,
      dryRun: true,
      action: 'wechat-channel.logout',
      loggedIn,
      clearsContextTokens: true,
    }
    if (opts.dryRun) {
      if (opts.json) console.log(JSON.stringify(preview))
      else console.log(chalk.cyan(`登出预览：${loggedIn ? '将清除消息通道登录和会话令牌' : '当前未登录，执行后状态不变'}`))
      return
    }
    if (!opts.yes) {
      if (opts.json) {
        console.log(JSON.stringify({ ...preview, success: false, dryRun: false, code: 'CONFIRMATION_REQUIRED' }))
        process.exit(1)
      }
      const { confirmed } = await inquirer.prompt([{
        type: 'confirm',
        name: 'confirmed',
        message: '确认退出消息通道并清除本地会话令牌？',
        default: false,
      }])
      if (!confirmed) {
        console.log(chalk.gray('已取消'))
        return
      }
    }
    configService.set('wechatOcToken', '')
    configService.set('wechatOcAccountId', '')
    configService.set('wechatOcSyncBuf', '')
    // 登出后历史 context_token 失效, 一并清空
    configService.setContextTokens({})
    if (opts.json) console.log(JSON.stringify({ success: true, action: 'wechat-channel.logout', changed: loggedIn }))
    else console.log(chalk.green('✓ 已退出登录'))
  })

// ==================== whitelist ====================
const whitelistCmd = program
  .command('whitelist')
  .description('白名单管理 (不传参数显示列表)')

whitelistCmd
  .action(() => {
    const entries = whitelistService.getWhitelistEntries()
    if (entries.length === 0) {
      console.log(chalk.gray('白名单为空'))
      console.log(chalk.gray('使用 weflow-cli whitelist add <昵称> 添加'))
      return
    }
    console.log(chalk.cyan(`白名单 (${entries.length}):\n`))
    console.log(chalk.gray('序号  wxid                          昵称              添加时间'))
    console.log(chalk.gray('─'.repeat(80)))
    for (let i = 0; i < entries.length; i++) {
      const e = entries[i]
      const num = String(i + 1).padStart(2)
      const id = (e.wxid || '').padEnd(28)
      const name = (e.displayName || '').slice(0, 16).padEnd(16)
      const ts = e.addedAt ? new Date(e.addedAt).toLocaleString('zh-CN') : '-'
      console.log(`${num}  ${id} ${name} ${ts}`)
    }
  })

whitelistCmd
  .command('add <target>')
  .description('添加白名单 (支持 wxid/昵称/备注名/序号)')
  .option('--dry-run', '仅预览，不修改白名单')
  .option('--yes', '确认执行')
  .option('--json', '输出 JSON 格式')
  .action(async (target: string, opts) => {
    // 解析目标
    let wxid: string
    let displayName = target
    if (target.startsWith('wxid_') || target.includes('@chatroom') || target.includes('@openim')) {
      wxid = target
    } else {
      try {
        wxid = await resolveTalker(target, !!opts.json, !!opts.json)
        const sessions = await chatService.listSessions(undefined, 50)
        const match = sessions.find(s => s.username === wxid)
        if (match) displayName = match.displayName || target
      } catch (e: any) {
        if (opts.json) console.log(JSON.stringify({ success: false, code: 'TALKER_RESOLUTION_FAILED', error: e.message }))
        else console.log(chalk.red(`✗ ${e.message}`))
        if (opts.json) process.exit(1)
        return
      }
    }

    // 检查是否已在名单中
    if (whitelistService.isAllowed(wxid)) {
      if (opts.json) console.log(JSON.stringify({ success: true, action: 'whitelist.add', changed: false, target: { wxid, displayName } }))
      else console.log(chalk.yellow(`"${displayName}" (${wxid}) 已在白名单中`))
      return
    }

    // 黑名单中的目标禁止加入白名单
    if (whitelistService.isBlocked(wxid)) {
      if (opts.json) {
        console.log(JSON.stringify({ success: false, code: 'TARGET_BLOCKED', error: '目标位于黑名单中', target: { wxid, displayName } }))
        process.exit(1)
      }
      console.log(chalk.red(`\n❌ "${displayName}" (${wxid}) 在黑名单中, 禁止加入白名单`))
      console.log(chalk.gray(`  先解除: weflow-cli blacklist rm ${wxid}\n`))
      return
    }

    const preview = { action: 'whitelist.add', target: { wxid, displayName } }
    if (opts.dryRun) {
      if (opts.json) console.log(JSON.stringify({ success: true, dryRun: true, ...preview }))
      else console.log(chalk.cyan(`将添加 "${displayName}" (${wxid}) 到白名单`))
      return
    }
    if (opts.json && !opts.yes) {
      console.log(JSON.stringify({ success: false, code: 'CONFIRMATION_REQUIRED', error: '使用 --yes 确认添加白名单', ...preview }))
      process.exit(1)
    }

    // 三重确认
    if (!opts.yes) {
      console.log(chalk.cyan(`\n⚠️  即将添加以下联系人到白名单:`))
      console.log(chalk.white(`  昵称: ${displayName}`))
      console.log(chalk.gray(`  wxid: ${wxid}`))
      console.log(chalk.yellow(`  添加后，该联系人可向你收发消息\n`))

      const { q1 } = await inquirer.prompt([{
        type: 'confirm',
        name: 'q1',
        message: `确认添加 "${displayName}" 到白名单？`,
        default: false,
      }])
      if (!q1) { console.log(chalk.gray('已取消')); return }

      const { q2 } = await inquirer.prompt([{
        type: 'input',
        name: 'q2',
        message: `请输入 "确认" 以继续:`,
      }])
      if (q2 !== '确认') { console.log(chalk.gray('已取消')); return }
    }

    whitelistService.addDirect(wxid, displayName)
    if (opts.json) console.log(JSON.stringify({ success: true, changed: true, ...preview }))
    else console.log(chalk.green(`\n✓ 已添加 "${displayName}" (${wxid}) 到白名单`))
  })

whitelistCmd
  .command('rm <wxid>')
  .description('移除白名单中的 wxid')
  .option('--dry-run', '仅预览，不修改白名单')
  .option('--yes', '确认执行')
  .option('--json', '输出 JSON 格式')
  .action(async (wxid: string, opts) => {
    const name = whitelistService.lookupName(wxid)
    const exists = whitelistService.isAllowed(wxid)
    const preview = { action: 'whitelist.remove', target: { wxid, displayName: name } }
    if (!exists) {
      if (opts.json) console.log(JSON.stringify({ success: false, code: 'NOT_FOUND', error: '目标不在白名单中', ...preview }))
      else console.log(chalk.yellow(`未找到: ${wxid}`))
      if (opts.json) process.exit(1)
      return
    }
    if (opts.dryRun) {
      if (opts.json) console.log(JSON.stringify({ success: true, dryRun: true, ...preview }))
      else console.log(chalk.cyan(`将从白名单移除: ${name} (${wxid})`))
      return
    }
    if (opts.json && !opts.yes) {
      console.log(JSON.stringify({ success: false, code: 'CONFIRMATION_REQUIRED', error: '使用 --yes 确认移除白名单', ...preview }))
      process.exit(1)
    }
    if (!opts.yes) {
      const { confirmed } = await inquirer.prompt([{
        type: 'confirm', name: 'confirmed', message: `确认从白名单移除 "${name}"？`, default: false,
      }])
      if (!confirmed) { console.log(chalk.gray('已取消')); return }
    }
    if (whitelistService.remove(wxid)) {
      if (opts.json) console.log(JSON.stringify({ success: true, changed: true, ...preview }))
      else console.log(chalk.green(`✓ 已移除: ${name} (${wxid})`))
    }
  })

whitelistCmd
  .command('clear')
  .description('清空白名单')
  .option('--dry-run', '仅预览，不清空白名单')
  .option('--yes', '确认清空白名单')
  .option('--json', '输出 JSON 格式')
  .action(async (opts) => {
    if (opts.dryRun) {
      const preview = { success: true, dryRun: true, action: 'whitelist.clear', entryCount: whitelistService.getWhitelistEntries().length }
      if (opts.json) console.log(JSON.stringify(preview))
      else console.log(chalk.cyan(`白名单清空预览：将移除 ${preview.entryCount} 项。`))
      return
    }
    if (!opts.yes) {
      if (opts.json) {
        console.log(JSON.stringify({ success: false, code: 'CONFIRMATION_REQUIRED', error: '使用 --yes 确认清空白名单' }))
        process.exit(1)
      }
      const { confirm } = await inquirer.prompt([{
        type: 'confirm',
        name: 'confirm',
        message: '确定要清空所有白名单吗？',
        default: false,
      }])
      if (!confirm) return
    }
    whitelistService.clear()
    if (opts.json) console.log(JSON.stringify({ success: true, action: 'whitelist.clear' }))
    else console.log(chalk.green('✓ 白名单已清空'))
  })

whitelistCmd
  .command('list')
  .description('以机器可读格式显示白名单')
  .option('--json', '输出 JSON 格式，包含本地敏感标识')
  .action((opts) => {
    const entries = whitelistService.getWhitelistEntries()
    if (opts.json) console.log(JSON.stringify({ success: true, entries }, null, 2))
    else console.log(entries.map(entry => `${entry.wxid}\t${entry.displayName || ''}`).join('\n'))
  })

// ==================== blacklist ====================
const blacklistCmd = program
  .command('blacklist')
  .description('黑名单管理 (绝对禁止收发, 优先级高于白名单; 不传参数显示列表)')

blacklistCmd
  .action(() => {
    const entries = whitelistService.getBlacklistEntries()
    if (entries.length === 0) {
      console.log(chalk.gray('黑名单为空'))
      console.log(chalk.gray('使用 weflow-cli blacklist add <昵称/wxid> 添加'))
      return
    }
    console.log(chalk.red(`黑名单 (${entries.length}):\n`))
    console.log(chalk.gray('序号  wxid                          昵称              添加时间'))
    console.log(chalk.gray('─'.repeat(80)))
    for (let i = 0; i < entries.length; i++) {
      const e = entries[i]
      const num = String(i + 1).padStart(2)
      const id = (e.wxid || '').padEnd(28)
      const name = (e.displayName || '').slice(0, 16).padEnd(16)
      const ts = e.addedAt ? new Date(e.addedAt).toLocaleString('zh-CN') : '-'
      console.log(`${num}  ${id} ${name} ${ts}`)
    }
  })

blacklistCmd
  .command('add <target>')
  .description('添加到黑名单 (自动从白名单移除)')
  .option('-r, --reason <text>', '拉黑原因 (可选)')
  .option('--dry-run', '仅预览，不修改黑名单')
  .option('--yes', '确认执行')
  .option('--json', '输出 JSON 格式')
  .action(async (target: string, opts) => {
    let wxid: string
    let displayName = target
    if (target.startsWith('wxid_') || target.includes('@chatroom') || target.includes('@openim')) {
      wxid = target
    } else {
      try {
        wxid = await resolveTalker(target, !!opts.json, !!opts.json)
        const sessions = await chatService.listSessions(undefined, 50)
        const match = sessions.find(s => s.username === wxid)
        if (match) displayName = match.displayName || target
      } catch (e: any) {
        if (opts.json) console.log(JSON.stringify({ success: false, code: 'TALKER_RESOLUTION_FAILED', error: e.message }))
        else console.log(chalk.red(`✗ ${e.message}`))
        if (opts.json) process.exit(1)
        return
      }
    }

    if (whitelistService.isBlocked(wxid)) {
      if (opts.json) console.log(JSON.stringify({ success: true, action: 'blacklist.add', changed: false, target: { wxid, displayName } }))
      else console.log(chalk.yellow(`"${displayName}" (${wxid}) 已在黑名单中`))
      return
    }

    const preview = { action: 'blacklist.add', target: { wxid, displayName }, reason: opts.reason || null }
    if (opts.dryRun) {
      if (opts.json) console.log(JSON.stringify({ success: true, dryRun: true, ...preview }))
      else console.log(chalk.cyan(`将添加 "${displayName}" (${wxid}) 到黑名单`))
      return
    }
    if (opts.json && !opts.yes) {
      console.log(JSON.stringify({ success: false, code: 'CONFIRMATION_REQUIRED', error: '使用 --yes 确认添加黑名单', ...preview }))
      process.exit(1)
    }

    if (!opts.yes) {
      console.log(chalk.cyan(`\n⚠️  即将拉黑以下联系人:`))
      console.log(chalk.white(`  昵称: ${displayName}`))
      console.log(chalk.gray(`  wxid: ${wxid}`))
      if (opts.reason) console.log(chalk.gray(`  原因: ${opts.reason}`))
      console.log(chalk.yellow(`  拉黑后, 该联系人绝对禁止收发消息 (即使误加白名单也拦截)\n`))

      const { q1 } = await inquirer.prompt([{
        type: 'confirm',
        name: 'q1',
        message: `确认拉黑 "${displayName}"？`,
        default: false,
      }])
      if (!q1) { console.log(chalk.gray('已取消')); return }
    }

    whitelistService.blockDirect(wxid, displayName, opts.reason)
    if (opts.json) console.log(JSON.stringify({ success: true, changed: true, ...preview }))
    else console.log(chalk.green(`\n✓ 已拉黑 "${displayName}" (${wxid})`))
  })

blacklistCmd
  .command('rm <wxid>')
  .description('从黑名单移除')
  .option('--dry-run', '仅预览，不修改黑名单')
  .option('--yes', '确认执行')
  .option('--json', '输出 JSON 格式')
  .action(async (wxid: string, opts) => {
    const name = whitelistService.lookupName(wxid)
    const exists = whitelistService.isBlocked(wxid)
    const preview = { action: 'blacklist.remove', target: { wxid, displayName: name } }
    if (!exists) {
      if (opts.json) console.log(JSON.stringify({ success: false, code: 'NOT_FOUND', error: '目标不在黑名单中', ...preview }))
      else console.log(chalk.yellow(`未在黑名单中找到: ${wxid}`))
      if (opts.json) process.exit(1)
      return
    }
    if (opts.dryRun) {
      if (opts.json) console.log(JSON.stringify({ success: true, dryRun: true, ...preview }))
      else console.log(chalk.cyan(`将从黑名单移除: ${name} (${wxid})`))
      return
    }
    if (opts.json && !opts.yes) {
      console.log(JSON.stringify({ success: false, code: 'CONFIRMATION_REQUIRED', error: '使用 --yes 确认移除黑名单', ...preview }))
      process.exit(1)
    }
    if (!opts.yes) {
      const { confirmed } = await inquirer.prompt([{
        type: 'confirm', name: 'confirmed', message: `确认从黑名单移除 "${name}"？`, default: false,
      }])
      if (!confirmed) { console.log(chalk.gray('已取消')); return }
    }
    if (whitelistService.unblock(wxid)) {
      if (opts.json) console.log(JSON.stringify({ success: true, changed: true, ...preview }))
      else console.log(chalk.green(`✓ 已从黑名单移除: ${name} (${wxid})`))
    }
  })

blacklistCmd
  .command('clear')
  .description('清空黑名单')
  .option('--dry-run', '仅预览，不清空黑名单')
  .option('--yes', '确认清空黑名单')
  .option('--json', '输出 JSON 格式')
  .action(async (opts) => {
    if (opts.dryRun) {
      const preview = { success: true, dryRun: true, action: 'blacklist.clear', entryCount: whitelistService.getBlacklistEntries().length }
      if (opts.json) console.log(JSON.stringify(preview))
      else console.log(chalk.cyan(`黑名单清空预览：将移除 ${preview.entryCount} 项。`))
      return
    }
    if (!opts.yes) {
      if (opts.json) {
        console.log(JSON.stringify({ success: false, code: 'CONFIRMATION_REQUIRED', error: '使用 --yes 确认清空黑名单' }))
        process.exit(1)
      }
      const { confirm } = await inquirer.prompt([{
        type: 'confirm',
        name: 'confirm',
        message: '确定要清空所有黑名单吗？',
        default: false,
      }])
      if (!confirm) return
    }
    whitelistService.clearBlacklist()
    if (opts.json) console.log(JSON.stringify({ success: true, action: 'blacklist.clear' }))
    else console.log(chalk.green('✓ 黑名单已清空'))
  })

blacklistCmd
  .command('list')
  .description('以机器可读格式显示黑名单')
  .option('--json', '输出 JSON 格式，包含本地敏感标识')
  .action((opts) => {
    const entries = whitelistService.getBlacklistEntries()
    if (opts.json) console.log(JSON.stringify({ success: true, entries }, null, 2))
    else console.log(entries.map(entry => `${entry.wxid}\t${entry.displayName || ''}`).join('\n'))
  })

// ==================== audit (发送审计日志) ====================
const auditCmd = program
  .command('audit')
  .description('发送审计日志查询 (记录所有 send 尝试)')

auditCmd
  .command('list')
  .description('查看最近发送记录 (默认最近 20 条)')
  .option('-n, --limit <number>', '最大条数', '20')
  .option('--all', '显示全部 (含失败)')
  .option('--failed', '只看失败')
  .option('--target <wxid>', '按目标 wxid 过滤')
  .option('--json', '输出 JSON 格式，不返回审计文件路径')
  .action((opts) => {
    const filter = (e: any) => {
      if (opts.target && e.targetWxid !== opts.target) return false
      if (opts.failed && e.success) return false
      if (!opts.all && !opts.failed && !e.success) {
        // 默认不显示被拦截的 (黑名单/速率/长度), 仅显示实际发送失败
        if (e.error && (e.error.includes('blacklist') || e.error.includes('rate') || e.error.includes('too long'))) return false
      }
      return true
    }
    const limit = parseCliInteger(opts.limit, 'limit', 1, 10000, opts.json)
    const entries = whitelistService.readAudit(limit, filter)
    const logPath = join(homedir(), '.weflow-cli', 'audit-send.log')
    if (opts.json) {
      console.log(JSON.stringify({ success: true, entries }, null, 2))
      return
    }
    if (entries.length === 0) {
      console.log(chalk.gray('无审计记录'))
      console.log(chalk.gray(`日志文件: ${logPath}`))
      return
    }

    console.log(chalk.cyan(`发送审计 (最近 ${entries.length} 条):\n`))
    for (const e of entries) {
      const time = new Date(e.timestamp).toLocaleString('zh-CN')
      const status = e.success ? chalk.green('✓') : chalk.red('✗')
      const name = e.targetName || e.targetWxid
      const err = e.error ? chalk.gray(` [${e.error}]`) : ''
      console.log(`${status} ${chalk.gray(`[${time}]`)} ${chalk.blue(name)} (${e.targetWxid}) <${e.kind}> ${chalk.gray(e.preview || '')}${err}`)
    }
    console.log(chalk.gray(`\n日志文件: ${logPath}`))
  })

auditCmd
  .command('stats')
  .description('审计统计 (成功/失败次数, 热门目标)')
  .option('--json', '输出 JSON 格式')
  .action((opts) => {
    const entries = whitelistService.readAudit()
    if (entries.length === 0) {
      if (opts.json) { console.log(JSON.stringify({ success: true, total: 0, succeeded: 0, failed: 0, topTargets: [] })); return }
      console.log(chalk.gray('无审计记录'))
      return
    }
    const success = entries.filter(e => e.success).length
    const failed = entries.length - success
    const byTarget = new Map<string, number>()
    for (const e of entries) {
      const key = e.targetName || e.targetWxid
      byTarget.set(key, (byTarget.get(key) || 0) + 1)
    }
    const top = [...byTarget.entries()].sort((a, b) => b[1] - a[1]).slice(0, 10)

    if (opts.json) {
      console.log(JSON.stringify({
        success: true,
        total: entries.length,
        succeeded: success,
        failed,
        topTargets: top.map(([target, count]) => ({ target, count })),
        sizeBytes: whitelistService.auditSize(),
      }, null, 2))
      return
    }

    console.log(chalk.cyan('发送审计统计:\n'))
    console.log(`  总记录: ${entries.length}`)
    console.log(`  ${chalk.green('成功')}: ${success}  ${chalk.red('失败')}: ${failed}`)
    const sizeKB = (whitelistService.auditSize() / 1024).toFixed(1)
    console.log(chalk.gray(`  日志大小: ${sizeKB} KB\n`))
    console.log(chalk.cyan('热门目标 (Top 10):'))
    for (const [name, n] of top) {
      console.log(`  ${String(n).padStart(4)}  ${name}`)
    }
  })

auditCmd
  .command('clear')
  .description('清空审计日志')
  .option('--dry-run', '仅预览，不清空审计日志')
  .option('--yes', '确认清空审计日志')
  .option('--json', '输出 JSON 格式')
  .action(async (opts) => {
    if (opts.dryRun) {
      const preview = { success: true, dryRun: true, action: 'audit.clear', entryCount: whitelistService.readAudit().length }
      if (opts.json) console.log(JSON.stringify(preview))
      else console.log(chalk.cyan(`审计日志清空预览：将移除 ${preview.entryCount} 条记录。`))
      return
    }
    if (!opts.yes) {
      if (opts.json) {
        console.log(JSON.stringify({ success: false, code: 'CONFIRMATION_REQUIRED', error: '使用 --yes 确认清空审计日志' }))
        process.exit(1)
      }
      const { confirm } = await inquirer.prompt([{
        type: 'confirm',
        name: 'confirm',
        message: '确定要清空所有审计记录吗？',
        default: false,
      }])
      if (!confirm) return
    }
    try {
      const { mkdirSync, writeFileSync } = await import('fs')
      const stateDir = join(homedir(), '.weflow-cli')
      mkdirSync(stateDir, { recursive: true })
      writeFileSync(join(stateDir, 'audit-send.log'), '', 'utf8')
      if (opts.json) console.log(JSON.stringify({ success: true, action: 'audit.clear' }))
      else console.log(chalk.green('✓ 审计日志已清空'))
    } catch (e: any) {
      if (opts.json) {
        console.log(JSON.stringify({ success: false, code: 'AUDIT_CLEAR_FAILED', error: '无法清空审计日志' }))
        process.exit(1)
      } else {
        console.log(chalk.red(`✗ 清空失败: ${e.message}`))
      }
    }
  })

// ==================== sns (朋友圈本地缓存) ====================
const snsCmd = program
  .command('sns')
  .description('朋友圈本地缓存查询 (4.x WCDB / NT 连接均支持)')

snsCmd
  .command('timeline')
  .description('查看朋友圈时间线 (本地已缓存的动态)')
  .option('-u, --user <wxid>', '过滤指定 wxid (可多次使用)', (v: string, acc: string[]) => { acc.push(v); return acc }, [] as string[])
  .option('-k, --keyword <kw>', '内容关键词')
  .option('-n, --limit <number>', '最大数量', '20')
  .option('-o, --offset <number>', '偏移量', '0')
  .option('--start <timestamp>', '开始时间戳 (秒)')
  .option('--end <timestamp>', '结束时间戳 (秒)')
  .option('--json', '输出 JSON 格式')
  .action(async (opts) => {
    if (!configService.isConfigured()) {
      if (opts.json) { console.log(JSON.stringify({ success: false, code: 'NOT_INITIALIZED', error: '未完成初始化' })); process.exit(1) }
      console.log(chalk.red('\n❌ 还没配置\n  运行: weflow-cli init\n'))
      process.exit(1)
    }

    // 先建立连接 (chatService 内部首次调用会自动 connect)
    const conn = await chatService.connect()
    if (!conn.success) {
      if (opts.json) { console.log(JSON.stringify({ success: false, code: 'DATABASE_CONNECTION_FAILED', error: '数据库连接失败' })); process.exit(1) }
      console.log(chalk.red(`\n❌ 数据库连接失败: ${conn.error}\n`))
      process.exit(1)
    }
    if (!chatService.isSnsSupported()) {
      if (opts.json) { console.log(JSON.stringify({ success: false, code: 'SNS_UNAVAILABLE', error: '当前数据通道不支持朋友圈查询' })); process.exit(1) }
      console.log(chalk.red('\n❌ 当前数据通道不支持朋友圈查询'))
      console.log(chalk.gray('  支持: 4.x + WCDB API, 或 NT 连接 + sns.db 密钥'))
      console.log(chalk.gray('  NT 用户请先运行: weflow-cli sns capture-key'))
      console.log(chalk.gray('  提示: 在微信客户端打开朋友圈让数据落盘后再查询\n'))
      process.exit(1)
    }

    const usernames = Array.isArray(opts.user) ? opts.user : (opts.user ? [opts.user] : undefined)
    const limit = parseCliInteger(opts.limit, 'limit', 1, 1000, opts.json)
    const offset = parseCliInteger(opts.offset, 'offset', 0, 1000000, opts.json)
    const startTime = opts.start ? parseCliInteger(opts.start, 'start', 0, Number.MAX_SAFE_INTEGER, opts.json) : undefined
    const endTime = opts.end ? parseCliInteger(opts.end, 'end', 0, Number.MAX_SAFE_INTEGER, opts.json) : undefined
    const result = await chatService.getSnsTimeline({
      limit,
      offset,
      usernames,
      keyword: opts.keyword,
      startTime,
      endTime,
    })

    if (!result.success || !result.timeline || result.timeline.length === 0) {
      if (opts.json) { console.log(JSON.stringify({ success: result.success, timeline: [], error: result.error || null })); return }
      console.log(chalk.gray(`未找到朋友圈动态${result.error ? `: ${result.error}` : ''}`))
      console.log(chalk.gray('提示: 在微信客户端打开朋友圈让数据落盘后再查询'))
      return
    }

    if (opts.json) {
      console.log(JSON.stringify({ success: true, timeline: result.timeline }, null, 2))
      return
    }
    console.log(chalk.cyan(`朋友圈时间线 (${result.timeline.length} 条):\n`))
    for (const item of result.timeline) {
      const ts = item.create_time || item.createTime || item.timestamp
      const time = ts ? new Date(Number(ts) * 1000).toLocaleString('zh-CN') : '未知时间'
      const author = item.username || item.user_name || item.wxid || item.nickname || '未知'
      const content = (item.content || item.text || '').replace(/\n/g, ' ').slice(0, 80)
      console.log(chalk.gray(`[${time}]`) + ` ${chalk.blue(author)}: ${content}`)
    }
  })

snsCmd
  .command('users')
  .description('列出本地缓存中有朋友圈动态的 wxid')
  .option('--json', '输出 JSON 格式')
  .action(async (opts) => {
    if (!configService.isConfigured()) {
      if (opts.json) { console.log(JSON.stringify({ success: false, code: 'NOT_INITIALIZED', error: '未完成初始化' })); process.exit(1) }
      console.log(chalk.red('\n❌ 还没配置\n  运行: weflow-cli init\n'))
      process.exit(1)
    }
    const conn = await chatService.connect()
    if (!conn.success) {
      if (opts.json) { console.log(JSON.stringify({ success: false, code: 'DATABASE_CONNECTION_FAILED', error: '数据库连接失败' })); process.exit(1) }
      console.log(chalk.red(`\n❌ 数据库连接失败: ${conn.error}\n`))
      process.exit(1)
    }
    if (!chatService.isSnsSupported()) {
      if (opts.json) { console.log(JSON.stringify({ success: false, code: 'SNS_UNAVAILABLE', error: '当前数据通道不支持朋友圈查询' })); process.exit(1) }
      console.log(chalk.red('\n❌ 当前数据通道不支持朋友圈查询\n'))
      process.exit(1)
    }

    const result = await chatService.getSnsUsernames()
    if (!result.success || !result.usernames || result.usernames.length === 0) {
      if (opts.json) { console.log(JSON.stringify({ success: result.success, usernames: [], error: result.error || null })); return }
      console.log(chalk.gray('本地缓存中无朋友圈动态'))
      return
    }

    if (opts.json) {
      console.log(JSON.stringify({ success: true, usernames: result.usernames }, null, 2))
      return
    }
    console.log(chalk.cyan(`朋友圈用户 (${result.usernames.length}):\n`))
    for (let i = 0; i < result.usernames.length; i++) {
      console.log(`  ${String(i + 1).padStart(3)}. ${result.usernames[i]}`)
    }
  })

snsCmd
  .command('stats')
  .description('朋友圈本地缓存统计')
  .option('--json', '输出 JSON 格式')
  .action(async (opts) => {
    if (!configService.isConfigured()) {
      if (opts.json) { console.log(JSON.stringify({ success: false, code: 'NOT_INITIALIZED', error: '未完成初始化' })); process.exit(1) }
      console.log(chalk.red('\n❌ 还没配置\n  运行: weflow-cli init\n'))
      process.exit(1)
    }
    const conn = await chatService.connect()
    if (!conn.success) {
      if (opts.json) { console.log(JSON.stringify({ success: false, code: 'DATABASE_CONNECTION_FAILED', error: '数据库连接失败' })); process.exit(1) }
      console.log(chalk.red(`\n❌ 数据库连接失败: ${conn.error}\n`))
      process.exit(1)
    }
    if (!chatService.isSnsSupported()) {
      if (opts.json) { console.log(JSON.stringify({ success: false, code: 'SNS_UNAVAILABLE', error: '当前数据通道不支持朋友圈查询' })); process.exit(1) }
      console.log(chalk.red('\n❌ 当前数据通道不支持朋友圈查询\n'))
      process.exit(1)
    }

    const myWxid = configService.get('wxid') || undefined
    const result = await chatService.getSnsExportStats(myWxid)
    if (!result.success || !result.data) {
      if (opts.json) { console.log(JSON.stringify({ success: false, code: 'SNS_STATS_FAILED', error: result.error || '获取统计失败' })); return }
      console.log(chalk.gray(`获取统计失败${result.error ? `: ${result.error}` : ''}`))
      return
    }

    const d = result.data
    if (opts.json) {
      console.log(JSON.stringify({ success: true, stats: d }, null, 2))
      return
    }
    console.log(chalk.cyan('朋友圈本地缓存统计:\n'))
    console.log(`  本地缓存动态总数: ${d.totalPosts}`)
    console.log(`  涉及好友数:       ${d.totalFriends}`)
    if (d.myPosts !== null) {
      console.log(`  我的动态数:       ${d.myPosts}`)
    }
    console.log(chalk.gray('\n注: 仅统计本地缓存，需在微信客户端打开朋友圈让数据落盘'))
  })

snsCmd
  .command('capture-key')
  .description('从微信进程捕获 sns.db 解密密钥 (需打开微信朋友圈触发)')
  .option('--dry-run', '仅预览，不扫描进程或修改配置')
  .option('--yes', '确认启动人工密钥捕获流程')
  .option('--json', '输出机器可读预览；实际捕获必须在交互终端执行')
  .action(async (opts) => {
    const preview = {
      success: true,
      dryRun: true,
      action: 'sns.capture-key',
      interactiveRequired: true,
      scansProcessMemory: true,
      writesEncryptedConfiguration: true,
    }
    if (opts.dryRun) {
      if (opts.json) console.log(JSON.stringify(preview))
      else console.log(chalk.cyan('捕获预览：需要管理员终端，并由用户在微信中打开朋友圈触发'))
      return
    }
    if (opts.json) {
      console.log(JSON.stringify({ ...preview, success: false, dryRun: false, code: 'INTERACTIVE_REQUIRED' }))
      process.exit(1)
    }
    console.log(chalk.cyan('\n🔑 捕获 sns.db 解密密钥\n'))
    console.log(chalk.yellow('准备工作:'))
    console.log('  1. 确保微信 4.x (Weixin.exe) 已登录运行')
    console.log('  2. 确保当前终端以管理员身份运行')
    console.log('  3. 准备好点击微信中的"朋友圈"标签\n')

    if (!opts.yes) {
      const { confirm } = await inquirer.prompt([{
        type: 'confirm',
        name: 'confirm',
        message: '准备好了吗？点击确认后请立即打开微信朋友圈',
        default: false,
      }])
      if (!confirm) {
        console.log(chalk.gray('已取消'))
        return
      }
    }

    // Check sns.db path
    let snsPath = configService.get('snsDbPath')
    if (!snsPath) {
      // Auto-detect
      try {
        const ntResult = await NtCore.scan()
        if (ntResult.databases) {
          const snsDb = ntResult.databases.find((db: any) => db.name === 'sns/sns.db')
          if (snsDb) {
            snsPath = snsDb.path
            configService.set('snsDbPath', snsDb.path)
            configService.set('snsSalt', snsDb.salt)
            console.log(chalk.green('✓ 已自动发现 sns.db'))
            console.log(chalk.gray('  数据库位置与盐值: 已识别，未显示'))
          }
        }
      } catch (e) {
        // Ignore scan errors
      }
    }
    if (!snsPath) {
      console.log(chalk.red('\n❌ 未找到 sns.db 路径，请手动设置:'))
      console.log(chalk.gray('  weflow-cli config set snsDbPath <path>'))
      console.log(chalk.gray('  weflow-cli config set snsSalt <32位hex>'))
      return
    }

    console.log(chalk.cyan('\n正在 Hook 微信进程...'))
    console.log(chalk.yellow('⚠  请立即在微信中打开"朋友圈"标签！(30 秒内)\n'))

    try {
      const result = await keyService.captureSnsKey(30000, snsPath, (msg) => {
        console.log(chalk.gray(`  ${msg}`))
      })

      if (result.success && result.key) {
        configService.set('snsKey', result.key)
        console.log(chalk.green(`\n✓ 成功捕获 sns.db 密钥!`))
        console.log(chalk.white('  密钥: 已安全保存'))
        console.log(chalk.cyan('\n现在可以使用朋友圈功能:'))
        console.log(chalk.gray('  weflow-cli sns timeline'))
        console.log(chalk.gray('  weflow-cli sns users'))
        console.log(chalk.gray('  weflow-cli sns stats'))
      } else {
        console.log(chalk.red(`\n❌ 捕获失败: ${result.error || '超时'}`))
        console.log(chalk.gray('提示:'))
        console.log(chalk.gray('  1. 确保在 30 秒内打开了朋友圈'))
        console.log(chalk.gray('  2. 如果有多个 wxid 目录，请手动设置 snsDbPath'))
        console.log(chalk.gray('  3. 或手动设置密钥: weflow-cli config set snsKey <64位hex>'))
      }
    } catch (e: any) {
      console.log(chalk.red(`\n❌ 错误: ${e.message}`))
    }
  })

// ==================== fav (微信收藏) ====================

const FAV_TYPE_IDS: Record<string, number> = {
  text: 1, image: 2, video: 4, article: 5, chatrecord: 14,
}
const FAV_TYPE_LABELS: Record<string, string> = {
  text: '文字', image: '图片', video: '视频', article: '文章', chatrecord: '聊天记录',
}

const favCmd = program
  .command('fav')
  .description('微信收藏内容查询 (4.x NT 连接)')

favCmd
  .command('list')
  .description('列出收藏内容')
  .option('-t, --type <type>', '类型过滤: text|image|video|article|chatrecord')
  .option('-k, --keyword <kw>', '关键词搜索')
  .option('-n, --limit <number>', '最大数量', '20')
  .option('-o, --offset <number>', '偏移量', '0')
  .option('--json', '输出 JSON 格式')
  .action(async (opts) => {
    const limit = parseCliInteger(opts.limit, 'limit', 1, 5000, !!opts.json)
    const offset = parseCliInteger(opts.offset, 'offset', 0, 1_000_000, !!opts.json)
    if (!configService.isConfigured()) {
      if (opts.json) console.log(JSON.stringify({ success: false, code: 'NOT_INITIALIZED', error: '未完成初始化' }))
      else console.log(chalk.red('\n❌ 还没配置\n  运行: weflow-cli init\n'))
      process.exit(1)
    }

    // 自动发现 favorite.db
    if (!configService.get('favDbPath')) {
      const favPath = detectFavDbPath()
      if (favPath) {
        configService.set('favDbPath', favPath)
        if (!opts.json) console.log(chalk.green(`✓ 自动发现收藏数据库: ${favPath}\n`))
      }
    }

    const conn = await chatService.connect()
    if (!conn.success) {
      if (opts.json) console.log(JSON.stringify({ success: false, code: 'DATABASE_CONNECTION_FAILED', error: '数据库连接失败' }))
      else console.log(chalk.red(`\n❌ 数据库连接失败: ${conn.error}\n`))
      process.exit(1)
    }
    const favReason = chatService.favUnavailableReason()
    if (favReason) {
      const detail = {
        channel: '当前数据通道不支持收藏查询 (需 4.x NT 连接)',
        path: '未找到收藏数据库 (favorite.db)，请确认微信已登录并产生过收藏',
        key: '收藏数据库已找到，但缺少密钥',
      }[favReason]
      if (opts.json) {
        console.log(JSON.stringify({ success: false, code: 'FAVORITES_UNAVAILABLE', reason: favReason, error: detail }))
        process.exit(1)
      }
      console.log(chalk.red(`\n❌ ${detail}`))
      if (favReason === 'key') {
        console.log(chalk.gray('  请先配置收藏密钥: weflow-cli fav set-key <64位hex密钥>'))
        console.log(chalk.gray('  或设置全库 passphrase: weflow-cli fav set-key --passphrase <64位hex>'))
      }
      if (favReason === 'path') {
        console.log(chalk.gray('  可手动指定: weflow-cli config set favDbPath <favorite.db 路径>'))
      }
      console.log('')
      process.exit(1)
    }

    let favType: number | undefined
    if (opts.type) {
      favType = FAV_TYPE_IDS[opts.type.toLowerCase()]
      if (!favType) {
        if (opts.json) console.log(JSON.stringify({ success: false, code: 'INVALID_FAVORITE_TYPE', error: '收藏类型无效' }))
        else {
          console.log(chalk.red(`❌ 未知类型: ${opts.type}`))
          console.log(chalk.gray('  可选: text image video article chatrecord'))
        }
        process.exit(1)
      }
    }

    const result = await chatService.getFavorites({
      limit,
      offset,
      keyword: opts.keyword,
      favType,
    })

    if (!result.success || !result.favorites || result.favorites.length === 0) {
      if (opts.json) {
        console.log(JSON.stringify({ success: result.success, favorites: [], total: result.total || 0, error: result.error || null }))
        if (!result.success) process.exit(1)
      } else console.log(chalk.gray(`未找到收藏内容${result.error ? `: ${result.error}` : ''}`))
      return
    }

    if (opts.json) {
      console.log(JSON.stringify(result, null, 2))
      return
    }

    const total = result.total ?? result.favorites.length
    console.log(chalk.cyan(`收藏列表 (共 ${total} 条, 显示 ${result.favorites.length} 条):\n`))
    for (const item of result.favorites) {
      const time = item.update_time
        ? new Date(Number(item.update_time) * 1000).toLocaleString('zh-CN')
        : '未知时间'
      const typeLabel = FAV_TYPE_LABELS[item.type_name] || item.type_name
      const title = (item.title || '(无标题)').replace(/\n/g, ' ').slice(0, 60)
      console.log(chalk.gray(`[${time}]`) + ` ${chalk.blue(`[${typeLabel}]`)} ${title}`)
      if (item.source_name) console.log(chalk.gray(`    来源: ${item.source_name}`))
      if (item.link) console.log(chalk.gray(`    ${item.link.slice(0, 90)}`))
    }
  })

favCmd
  .command('export <format>')
  .description('导出收藏内容 (markdown|json)')
  .option('-t, --type <type>', '类型过滤: text|image|video|article|chatrecord')
  .option('-k, --keyword <kw>', '关键词搜索')
  .option('-n, --limit <number>', '最大数量', '1000')
  .option('-o, --output <file>', '输出文件路径')
  .option('--json-result', '输出机器可读的导出结果，不改变文件格式')
  .action(async (format: string, opts) => {
    if (format !== 'markdown' && format !== 'json') {
      if (opts.jsonResult) console.log(JSON.stringify({ success: false, code: 'INVALID_FORMAT', error: '格式仅支持 markdown 或 json' }))
      else console.log(chalk.red('❌ 格式仅支持: markdown | json'))
      process.exit(1)
    }
    const limit = parseCliInteger(opts.limit, 'limit', 0, 1_000_000, !!opts.jsonResult)
    if (!configService.isConfigured()) {
      if (opts.jsonResult) console.log(JSON.stringify({ success: false, code: 'NOT_INITIALIZED', error: '未完成初始化' }))
      else console.log(chalk.red('\n❌ 还没配置\n  运行: weflow-cli init\n'))
      process.exit(1)
    }

    if (!configService.get('favDbPath')) {
      const favPath = detectFavDbPath()
      if (favPath) configService.set('favDbPath', favPath)
    }

    const conn = await chatService.connect()
    if (!conn.success) {
      if (opts.jsonResult) console.log(JSON.stringify({ success: false, code: 'DATABASE_CONNECTION_FAILED', error: '数据库连接失败' }))
      else console.log(chalk.red(`\n❌ 数据库连接失败: ${conn.error}\n`))
      process.exit(1)
    }
    if (!chatService.isFavSupported()) {
      if (opts.jsonResult) console.log(JSON.stringify({ success: false, code: 'FAVORITES_UNAVAILABLE', error: '当前数据通道不支持收藏查询' }))
      else {
        console.log(chalk.red('\n❌ 当前数据通道不支持收藏查询 (需 4.x NT 连接)'))
        console.log(chalk.gray('  请先配置收藏密钥: weflow-cli fav set-key <64位hex密钥>\n'))
      }
      process.exit(1)
    }

    let favType: number | undefined
    if (opts.type) {
      favType = FAV_TYPE_IDS[opts.type.toLowerCase()]
      if (!favType) {
        if (opts.jsonResult) console.log(JSON.stringify({ success: false, code: 'INVALID_FAVORITE_TYPE', error: '收藏类型无效' }))
        else console.log(chalk.red(`❌ 未知类型: ${opts.type}`))
        process.exit(1)
      }
    }

    // 全量导出: limit 为 0 时取全部
    const result = await chatService.getFavorites({
      limit,
      offset: 0,
      keyword: opts.keyword,
      favType,
    })
    if (!result.success || !result.favorites) {
      if (opts.jsonResult) console.log(JSON.stringify({ success: false, code: 'EXPORT_FAILED', error: result.error || '无内容' }))
      else console.log(chalk.red(`导出失败: ${result.error || '无内容'}`))
      process.exit(1)
    }

    const items = result.favorites
    let content: string
    if (format === 'json') {
      content = JSON.stringify(items, null, 2)
    } else {
      const lines: string[] = ['# 微信收藏导出', '', `> 共 ${items.length} 条 · 导出时间 ${new Date().toLocaleString('zh-CN')}`, '']
      for (const item of items) {
        const time = item.update_time
          ? new Date(Number(item.update_time) * 1000).toLocaleString('zh-CN')
          : '未知时间'
        const typeLabel = FAV_TYPE_LABELS[item.type_name] || item.type_name
        lines.push(`## ${item.title || '(无标题)'}`)
        lines.push('')
        lines.push(`- 类型: ${typeLabel}`)
        lines.push(`- 时间: ${time}`)
        if (item.source_name) lines.push(`- 来源: ${item.source_name}`)
        if (item.link) lines.push(`- 链接: <${item.link}>`)
        if (item.desc) lines.push(`- 摘要: ${item.desc}`)
        lines.push('')
      }
      content = lines.join('\n')
    }

    const outPath = opts.output || `favorites_${Date.now()}.${format === 'json' ? 'json' : 'md'}`
    writeFileSync(outPath, content, 'utf8')
    if (opts.jsonResult) console.log(JSON.stringify({ success: true, format, path: outPath, count: items.length }, null, 2))
    else console.log(chalk.green(`✓ 已导出 ${items.length} 条收藏到 ${outPath}`))
  })

favCmd
  .command('set-key [key]')
  .description('设置收藏数据库密钥 (默认 raw key; --passphrase 表示全库共用 passphrase)')
  .option('--passphrase', '输入的是全库共用 passphrase (自动派生 favorite.db 密钥)')
  .option('--from-env <name>', '从环境变量读取密钥，避免密钥出现在命令参数中', 'WEFLOW_FAV_KEY')
  .option('--dry-run', '仅验证输入并预览，不修改配置')
  .option('--yes', '确认执行')
  .option('--json', '输出 JSON 格式，不返回密钥或数据库路径')
  .action(async (key: string | undefined, opts) => {
    if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(opts.fromEnv)) {
      if (opts.json) console.log(JSON.stringify({ success: false, code: 'INVALID_ENVIRONMENT_NAME', error: '环境变量名称无效' }))
      else console.log(chalk.red('环境变量名称无效'))
      process.exit(1)
    }
    const resolvedKey = key || process.env[opts.fromEnv]
    if (!resolvedKey) {
      if (opts.json) console.log(JSON.stringify({ success: false, code: 'KEY_MISSING', error: `环境变量 ${opts.fromEnv} 未设置且未提供密钥` }))
      else console.log(chalk.red(`✗ 未提供密钥；请设置环境变量 ${opts.fromEnv} 或传入 key`))
      process.exit(1)
    }
    if (!/^[0-9a-fA-F]{64}$/.test(resolvedKey)) {
      if (opts.json) console.log(JSON.stringify({ success: false, code: 'INVALID_KEY_FORMAT', error: '密钥必须是 64 位十六进制字符串' }))
      else console.log(chalk.red('❌ 密钥格式错误: 需要 64 位十六进制字符串'))
      process.exit(1)
    }
    const preview = {
      action: 'favorites.set-key',
      mode: opts.passphrase ? 'passphrase' : 'raw-key',
      source: key ? 'argument' : 'environment',
      environment: key ? null : opts.fromEnv,
    }
    if (opts.dryRun) {
      if (opts.json) console.log(JSON.stringify({ success: true, dryRun: true, ...preview }))
      else console.log(chalk.cyan(`将保存收藏数据库${opts.passphrase ? '全库 passphrase' : '密钥'}`))
      return
    }
    if (opts.json && !opts.yes) {
      console.log(JSON.stringify({ success: false, code: 'CONFIRMATION_REQUIRED', error: '使用 --yes 确认保存收藏数据库密钥', ...preview }))
      process.exit(1)
    }
    if (opts.passphrase) {
      configService.set('favPassphrase', resolvedKey)
      configService.set('favKey', '') // 清空旧 raw key, 下次查询时重新派生
      if (!opts.json) console.log(chalk.green('✓ 已保存全库 passphrase'))
    } else {
      configService.set('favKey', resolvedKey)
      if (!opts.json) console.log(chalk.green('✓ 已保存 favorite.db raw key'))
    }
    let databaseDetected = !!configService.get('favDbPath')
    if (!configService.get('favDbPath')) {
      const favPath = detectFavDbPath()
      if (favPath) {
        configService.set('favDbPath', favPath)
        databaseDetected = true
        if (!opts.json) console.log(chalk.green(`✓ 自动发现收藏数据库: ${favPath}`))
      } else if (!opts.json) {
        console.log(chalk.yellow('⚠ 未自动发现 favorite.db, 请手动设置: weflow-cli config set favDbPath <path>'))
      }
    }
    if (opts.json) {
      console.log(JSON.stringify({ success: true, changed: true, databaseDetected, ...preview }))
      return
    }
    console.log(chalk.cyan('\n现在可以使用收藏功能:'))
    console.log(chalk.gray('  weflow-cli fav list'))
    console.log(chalk.gray('  weflow-cli fav export markdown'))
  })

// ==================== send ====================
program
  .command('send <target> <message>')
  .description('发送文本消息给指定联系人')
  .option('--image <path>', '发图片')
  .option('--file <path>', '发文件')
  .option('--dry-run', '仅预览不实际发送')
  .option('--yes', '确认实际发送')
  .option('--json', '输出 JSON 格式；实际发送仍需 --yes')
  .option('--rate-window <ms>', '速率窗口毫秒', '60000')
  .option('--rate-max <n>', '窗口内最大发送条数', '10')
  .action(async (target: string, message: string, opts) => {
    if (opts.image && opts.file) {
      if (opts.json) console.log(JSON.stringify({ success: false, code: 'CONFLICTING_MEDIA', error: '--image 与 --file 不能同时使用' }))
      else console.log(chalk.red('--image 与 --file 不能同时使用'))
      process.exit(1)
    }

    // Resolve target
    let wxid: string
    try {
      wxid = await resolveTalker(target, !!opts.json, !!opts.json)
    } catch (e: any) {
      if (opts.json) console.log(JSON.stringify({ success: false, code: 'TALKER_RESOLUTION_FAILED', error: e.message }))
      else console.log(chalk.red(`${e.message}`))
      process.exit(1)
    }

    // 解析 displayName 用于二次确认 (优先用名单里存的)
    let displayName = whitelistService.lookupName(wxid)
    if (displayName === wxid) {
      try {
        const sessions = await chatService.listSessions(undefined, 200)
        const match = sessions.find(s => s.username === wxid)
        if (match?.displayName) displayName = match.displayName
      } catch {}
    }

    // 类型与预览
    const kind: 'text' | 'image' | 'file' = opts.image ? 'image' : opts.file ? 'file' : 'text'
    let preview = message.slice(0, 80) + (message.length > 80 ? '...' : '')
    if (kind !== 'text') {
      const mediaPath = String(opts.image || opts.file)
      try {
        const mediaStat = statSync(mediaPath)
        if (!mediaStat.isFile() || mediaStat.size === 0) throw new Error('invalid media')
        preview = `[${kind}] ${basename(mediaPath)} (${mediaStat.size} bytes)`
      } catch {
        if (opts.json) console.log(JSON.stringify({ success: false, code: 'INVALID_MEDIA_FILE', kind }))
        else console.log(chalk.red('媒体路径必须指向可读取的非空文件'))
        process.exit(1)
      }
    }

    // 文本长度限制 (仅文本)
    if (kind === 'text' && message.length > MAX_TEXT_LENGTH) {
      if (opts.json) console.log(JSON.stringify({ success: false, code: 'MESSAGE_TOO_LONG', error: `文本上限为 ${MAX_TEXT_LENGTH} 字符` }))
      else {
        console.log(chalk.red(`\n❌ 文本过长 (${message.length} 字符), 上限 ${MAX_TEXT_LENGTH}`))
        console.log(chalk.gray('  过长内容请拆分多条或使用 --file 发送文件\n'))
      }
      whitelistService.auditSend({
        timestamp: Date.now(), action: 'send', targetWxid: wxid, targetName: displayName,
        kind, success: false, preview, error: `text too long (${message.length})`,
      })
      process.exit(1)
    }

    // 三道闸（黑名单 → 白名单 → 限速）与"每次尝试都写审计"在 `src/services/outboundSend.ts`
    // 里**只有一份**，因为 2026-10-01 起有了第二条发送路（`draft --pick N --send`，见 D-063）。
    // 两份写同一件事，分叉的后果具体是"某一条路绕过了白名单"。
    const policy = parseOutboundPolicy(Number(opts.rateWindow), Number(opts.rateMax))
    if ('code' in policy) {
      if (opts.json) console.log(JSON.stringify({ success: false, code: policy.code, error: policy.error }))
      else console.log(chalk.red('速率参数无效：rate-window 必须为 1000-3600000，rate-max 必须为 1-100'))
      process.exit(1)
    }
    const attempt = {
      wxid, displayName, kind, preview, text: message,
      mediaPath: kind === 'text' ? undefined : String(opts.image || opts.file),
    }
    const decision = authorizeOutbound(attempt, policy)
    if (!decision.ok) {
      const { refusal } = decision
      if (opts.json) {
        console.log(JSON.stringify({
          success: false, code: refusal.code, error: refusal.error,
          ...(refusal.code === 'TARGET_BLOCKED' || refusal.code === 'TARGET_NOT_ALLOWED'
            ? { target: { wxid, displayName } } : {}),
          ...(refusal.rateLimit ? { rateLimit: refusal.rateLimit } : {}),
        }))
      } else if (refusal.code === 'TARGET_BLOCKED') {
        console.log(chalk.red('\n❌ 目标在黑名单中，绝对禁止发送'))
        console.log(chalk.gray(`  wxid: ${wxid}`))
        console.log(chalk.gray(`  解除: weflow-cli blacklist rm ${wxid}\n`))
      } else if (refusal.code === 'TARGET_NOT_ALLOWED') {
        console.log(chalk.red('\n❌ 目标不在白名单中，拒绝发送'))
        console.log(chalk.gray(`  先运行: weflow-cli whitelist add ${target}`))
        console.log(chalk.gray(`  查看名单: weflow-cli whitelist\n`))
      } else {
        const rate = refusal.rateLimit!
        console.log(chalk.red(`\n❌ 触发速率限制: 最近 ${rate.windowMs / 1000}s 内已发送 ${rate.count} 条 (上限 ${rate.max})`))
        console.log(chalk.gray('  请稍后再试, 或调整 --rate-window / --rate-max\n'))
      }
      process.exit(1)
    }
    const rate = decision.rate

    // 二次确认 — 同时显示 wxid + displayName + 消息预览
    const actionPreview = {
      action: 'send',
      target: { wxid, displayName },
      kind,
      preview,
      rateLimit: { count: rate.count, max: rate.max, windowMs: rate.windowMs },
    }
    if (!opts.json) {
      console.log(chalk.cyan('\n⚠️  即将发送:'))
      console.log(chalk.white(`  目标: ${displayName}`))
      console.log(chalk.gray(`  wxid: ${wxid}`))
      console.log(chalk.gray(`  类型: ${kind}`))
      console.log(chalk.gray(`  预览: ${preview}`))
      console.log(chalk.gray(`  速率: ${rate.count}/${rate.max} (窗口 ${rate.windowMs / 1000}s)\n`))
    }

    if (opts.dryRun) {
      if (opts.json) console.log(JSON.stringify({ success: true, dryRun: true, ...actionPreview }))
      else console.log(chalk.yellow('⚠️  --dry-run 模式, 不实际发送'))
      return
    }

    if (opts.json && !opts.yes) {
      console.log(JSON.stringify({ success: false, code: 'CONFIRMATION_REQUIRED', error: '使用 --yes 确认发送', ...actionPreview }))
      process.exit(1)
    }

    if (!opts.yes) {
      const { confirm } = await inquirer.prompt([{
        type: 'confirm',
        name: 'confirm',
        message: `确认发送给 ${chalk.cyan(displayName)} (${wxid})？`,
        default: false,
      }])
      if (!confirm) {
        console.log(chalk.gray('已取消'))
        return
      }
    }

    // Login check
    const token = configService.get('wechatOcToken')
    if (!token) {
      if (opts.json) console.log(JSON.stringify({ success: false, code: 'MESSAGE_CHANNEL_NOT_LOGGED_IN', error: '消息通道未登录' }))
      else {
        console.log(chalk.red('\n❌ 未登录消息通道'))
        console.log(chalk.gray('  先运行: weflow-cli login-wechat\n'))
      }
      process.exit(1)
    }

    // 真的发 + 按结果写审计，都在共享模块里（与 `draft --send` 同一份）
    const { success, error: errorMsg } = await performOutbound(attempt)

    if (success) {
      if (opts.json) console.log(JSON.stringify({ success: true, ...actionPreview }))
      else console.log(chalk.green('✓ 发送成功'))
    } else {
      if (opts.json) console.log(JSON.stringify({ success: false, code: 'SEND_FAILED', error: errorMsg, ...actionPreview }))
      else console.log(chalk.red(`✗ 发送失败 — ${errorMsg}`))
      if (opts.json) process.exit(1)
    }
  })

// ==================== listen ====================
program
  .command('listen')
  .description('监听微信消息 (Ctrl+C 退出)')
  .option('--target <wxid>', '只显示指定用户的消息')
  .option('--dry-run', '仅预览，不连接消息通道或输出消息')
  .option('--yes', '确认启动人工前台监听')
  .option('--json', '输出机器可读预览；实际监听必须在交互终端执行')
  .action(async (opts) => {
    const preview = {
      success: true,
      dryRun: true,
      action: 'wechat-channel.listen',
      interactiveRequired: true,
      outputsMessageContent: true,
      targetRestricted: !!opts.target,
    }
    if (opts.dryRun) {
      if (opts.json) console.log(JSON.stringify(preview))
      else console.log(chalk.cyan('监听预览：将前台持续接收并显示白名单消息，需 Ctrl+C 退出'))
      return
    }
    if (opts.json) {
      console.log(JSON.stringify({ ...preview, success: false, dryRun: false, code: 'INTERACTIVE_REQUIRED' }))
      process.exit(1)
    }
    if (!opts.yes) {
      const { confirmed } = await inquirer.prompt([{
        type: 'confirm',
        name: 'confirmed',
        message: '确认在当前终端持续监听并显示白名单消息？',
        default: false,
      }])
      if (!confirmed) {
        console.log(chalk.gray('已取消'))
        return
      }
    }
    const token = configService.get('wechatOcToken')
    if (!token) {
      console.log(chalk.red('\n❌ 未登录消息通道'))
      console.log(chalk.gray('  先运行: weflow-cli login-wechat\n'))
      process.exit(1)
    }

    // Whitelist must be non-empty before listening
    const wl = whitelistService.getList()
    if (wl.length === 0) {
      console.log(chalk.red('\n❌ 白名单为空，拒绝监听'))
      console.log(chalk.gray('  为了防止收到非预期消息，必须先配置白名单'))
      console.log(chalk.gray('  运行: weflow-cli whitelist add <昵称>\n'))
      process.exit(1)
    }
    console.log(chalk.gray(`当前白名单: ${wl.length} 项`))
    const bl = whitelistService.getBlacklist()
    if (bl.length > 0) {
      console.log(chalk.gray(`当前黑名单: ${bl.length} 项 (绝对拦截)`))
    }

    const service = new WechatMessageService({ token })
    console.log(chalk.cyan('\n开始监听消息... (Ctrl+C 退出)\n'))

    service.onMessage((msg) => {
      // Whitelist filter (strict)
      if (!whitelistService.isAllowed(msg.fromUserId)) {
        return
      }
      // Target filter
      if (opts.target && msg.fromUserId !== opts.target) {
        return
      }

      const time = new Date(msg.timestampMs).toLocaleString('zh-CN')
      const kind = msg.messageKind !== 'text' ? ` [${msg.messageKind}]` : ''
      console.log(chalk.gray(`[${time}]`) + ` ${chalk.blue(msg.senderNickname || '未知发送者')}:${kind} ${msg.messageStr}`)
    })

    // Graceful shutdown：Linux 上 systemd/`kill` 用 SIGTERM，Ctrl+C 才是 SIGINT，
    // 两个都要处理，否则被 systemctl stop 时既没日志也不清理。
    for (const sig of ['SIGINT', 'SIGTERM'] as const) {
      process.on(sig, async () => {
        console.log(chalk.gray(`\n收到 ${sig}，正在停止监听...`))
        await service.stop()
        process.exit(0)
      })
    }

    await service.startPolling()
  })

// ==================== report ====================
program
  .command('report')
  .description('生成聊天月报（AI 分析任务和回复）')
  .option('--month <YYYY-MM>', '指定月份')
  .option('--talker <昵称>', '指定联系人（可多次使用）', (value: string, previous: string[]) => [...previous, value], [] as string[])
  .option('--from-whitelist', '使用白名单中的联系人')
  .option('--api-key <key>', 'DeepSeek API key')
  .option('--no-ai', '仅统计，不调用 AI')
  .option('-o, --output <dir>', '输出目录', './output')
  .option('--dry-run', '仅预览，不读取聊天、调用 AI 或写入报告')
  .option('--yes', '确认生成报告')
  .option('--json', '输出机器可读结果，不返回联系人或本地路径')
  .action(async (opts) => {
    if (opts.month && !/^\d{4}-(0[1-9]|1[0-2])$/.test(opts.month)) {
      if (opts.json) console.log(JSON.stringify({ success: false, code: 'INVALID_DATE', field: 'month' }))
      else console.log(chalk.red('month 必须是有效的 YYYY-MM 月份'))
      process.exit(1)
    }
    const talkers = opts.talker as string[]
    const noAi = opts.ai === false
    const preview = {
      success: true,
      dryRun: true,
      action: 'report.generate',
      monthSpecified: !!opts.month,
      talkerCount: talkers.length,
      fromWhitelist: !!opts.fromWhitelist,
      aiEnabled: !noAi,
    }
    if (opts.dryRun) {
      if (opts.json) console.log(JSON.stringify(preview))
      else console.log(chalk.cyan(`月报预览：${talkers.length || (opts.fromWhitelist ? '白名单' : '默认')} 个指定对象，AI ${noAi ? '关闭' : '开启'}`))
      return
    }
    if (!opts.yes) {
      if (opts.json) {
        console.log(JSON.stringify({ ...preview, success: false, dryRun: false, code: 'CONFIRMATION_REQUIRED' }))
        process.exit(1)
      }
      const { confirmed } = await inquirer.prompt([{
        type: 'confirm',
        name: 'confirmed',
        message: `确认生成聊天月报？${noAi ? '仅执行本地统计。' : '所选聊天内容将发送到已配置的 AI 服务。'}`,
        default: false,
      }])
      if (!confirmed) {
        console.log(chalk.gray('已取消'))
        return
      }
    }
    if (!configService.isConfigured()) {
      if (opts.json) console.log(JSON.stringify({ success: false, code: 'NOT_INITIALIZED' }))
      else console.log(chalk.red('\n❌ 还没配置\n  运行: weflow-cli init\n'))
      process.exit(1)
    }

    const { execFile } = await import('child_process')
    const { promisify } = await import('util')
    const execFileAsync = promisify(execFile)
    const pkgRoot = resolvePackageRoot()
    const script = join(pkgRoot, 'scripts', 'chat_report.py')

    const args: string[] = [script]
    if (opts.month) args.push('--month', opts.month)
    if (opts.fromWhitelist) args.push('--from-whitelist')
    if (noAi) args.push('--no-ai')
    if (opts.output) args.push('--output', opts.output)

    try {
      if (!opts.json) console.log(chalk.cyan('正在生成月报...\n'))
      const { stdout } = await execFileAsync(getPythonCommand(), args, {
        timeout: 600_000,
        maxBuffer: 50 * 1024 * 1024,
        env: {
          ...pythonProcessEnv(opts.apiKey),
          ...(talkers.length > 0 ? { WEFLOW_REPORT_TALKERS: JSON.stringify(talkers) } : {}),
        },
      })
      if (opts.json) console.log(JSON.stringify({ success: true, action: 'report.generate' }))
      else console.log(stdout)
    } catch (e: any) {
      if (opts.json) console.log(JSON.stringify({ success: false, code: 'REPORT_FAILED', error: safeSubprocessError(e, '生成失败') }))
      else console.error(chalk.red(`\n✗ ${safeSubprocessError(e, '生成失败')}`))
      process.exit(1)
    }
  })

  // vault init
  program
    .command('vault')
    .description('Obsidian Vault 管理')
    .addCommand(
      new Command('init')
        .description('初始化 Obsidian Vault 目录结构')
        .option('-p, --path <dir>', 'Vault 路径', join(resolveOutputRoot(), 'wechat-vault'))
        .option('--dry-run', '仅预览将创建或覆盖的项目，不修改文件')
        .option('--yes', '确认创建目录并写入模板文件')
        .option('--json', '输出 JSON 格式，不返回本地路径或文件名')
        .action(async (opts) => {
          const { mkdirSync, writeFileSync } = await import('fs')
          const { join } = await import('path')

          const vaultPath = opts.path
          const dirs = [
            '.obsidian',
            'Templates',
            'Sources/WeChat',
            '000_Inbox',
            '001_Daily',
            '002_Literature/WeChat',
            '002_Literature/WeRead',
            '003_Ideas',
            '004_Permanent',
            '005_Reference/Tools',
            '005_Reference/Methods',
            '006_Projects',
            // 这里原先还有 `007_Wiki/Concepts`：概念页实际写在下面的顶层 `Wiki/Concepts`
            // （`compile_wiki` 的 OUTPUT_ROOT）。两个都列，就建出一个永远空着的目录。
            '008_MOC',
            '999_Archive',
            '_attachments',
            // `Wiki/Concepts` 是唯一真的有人写的 Wiki 子目录（`compile_wiki` 的
            // OUTPUT_ROOT）。这里曾经还列着 `Wiki/Entities` 与 `Wiki/Topics`——没有任何
            // 代码写它们，README 里那张表却把它们当成已有的介绍给用户。**声明了就要有东西
            // 往里写**，否则就是又一个"永远空着的目录"（同 `007_Wiki`）。
            // 两个知识库各一个目录：`Wiki/Concepts` 是公众号文章线的，`Chat/Concepts` 是聊天线的
            'Wiki/Concepts',
            'Chat/Concepts',
          ]
          const files = [
            {
              relativePath: join('.obsidian', 'app.json'),
              content: JSON.stringify({
                newFileLocation: 'folder',
                newFileFolderPath: 'Sources',
                // **`_attachments`，不是 `Assets`**：布局里建的就是 `_attachments`（这个
                // 字面量以前只在这里出现一次，是个孤例），而 init 从不建 `Assets`——
                // 于是附件会被 Obsidian 放进一个不存在的目录。
                attachmentFolderPath: '_attachments',
                showInlineTitle: false,
              }, null, 2),
            },
            {
              relativePath: join('Templates', 'article.md'),
              content: [
                '---',
                'title: "{{title}}"',
                'source: ""',
                'date: {{date}}',
                'topic: AI',
                'tags: []',
                'created: {{date}}',
                '---',
                '',
                '# {{title}}',
                '',
                '> 来源：  ',
                '> 时间：{{date}}  ',
                '',
                '---',
                '',
                '## AI 摘要',
                '',
                '',
                '## 相关概念',
                '',
                '',
                '---',
                '',
                '## 正文',
                '',
              ].join('\n'),
            },
            {
              relativePath: 'README.md',
              content: [
                '# WeChat Knowledge Vault',
                '',
                '> 由 weflow-cli 自动生成，兼容 Obsidian。',
                '',
                '## 目录结构',
                '',
                '| 目录 | 说明 |',
                '|------|------|',
                '| `Sources/WeChat/<日期>/` | 原始文章（`daily` 与回填写入，连同正文图片） |',
                '| `001_Daily/<日期>.md` | 每天一页日记 |',
                '| `002_Literature/WeChat/<日期>/` | 阅读笔记（由 `Sources` 生成） |',
                // **两个知识库各写一行**：文章线（`Wiki/`）与聊天线（`Chat/`）是分开的两套，
                // 只列文章那套的话，用户在库里看到的说明与他实际拥有的东西对不上。
                '| `Wiki/Concepts/`、`Wiki/00-Overview.md` | **文章知识库**的概念页与索引（`wiki compile` 生成） |',
                '| `Chat/Concepts/`、`Chat/00-Overview.md` | **聊天知识库**的概念页与索引（`wiki compile --source output/chat-notes` 生成） |',
                '| `Sources/Chat/会话-<名字>.md` | 每个会话一张知识卡（`chat` 生成：聊了什么、有哪些人、欠着什么） |',
                '| `Templates/` | 模板文件 |',
                '| `_attachments/` | Obsidian 附件（`.obsidian/app.json` 的 `attachmentFolderPath` 指向这里） |',
                '| `000_Inbox` `003_Ideas` `004_Permanent` `005_Reference` `006_Projects` `008_MOC` `999_Archive` | **给你自己写笔记用的层**：`vault promote` 才会往里放东西，空着是设计而不是没做完 |',
                '',
                '> 阅读笔记与日记里各有一段 `dataview` 查询，所以这个 Vault 需要 **Dataview 社区插件**',
                '> （社区插件不进仓库，换机器要自己装一次）。',
                '',
                '## 快速查询',
                '',
                '使用 Obsidian Dataview 插件：',
                '',
                '```dataview',
                'TABLE date, topic, tags',
                'FROM "Sources/WeChat"',
                'WHERE topic = "AI"',
                'SORT date DESC',
                '```',
                '',
                '```dataview',
                'TABLE length(rows) as "篇数"',
                'FROM "Sources/WeChat"',
                'GROUP BY topic',
                'SORT rows.length DESC',
                '```',
                '',
                '## 每日更新',
                '',
                '```bash',
                '# 生成今日日报',
                'python scripts/biz_daily.py --api-key <key>',
                '',
                '# 后处理（广告清洗+深度摘要）',
                'python scripts/classify_daily.py --api-key <key> --interest AI',
                '',
                '# 同步到 GitHub',
                '# (见 OPERATIONS.md)',
                '```',
                '',
                '---',
                '',
                '*由 weflow-cli vault init 生成*',
              ].join('\n'),
            },
            {
              relativePath: '.gitignore',
              content: [
                '.obsidian/workspace*.json',
                '.obsidian/hotkeys.json',
                '.trash/',
                '.DS_Store',
              ].join('\n'),
            },
          ]
          const directoryCreateCount = dirs.filter(dir => !existsSync(join(vaultPath, dir))).length
          const fileCreateCount = files.filter(file => !existsSync(join(vaultPath, file.relativePath))).length
          const overwriteCount = files.length - fileCreateCount
          const preview = {
            success: true,
            dryRun: true,
            action: 'vault.init',
            directoryCreateCount,
            fileCreateCount,
            overwriteCount,
          }

          if (opts.dryRun) {
            if (opts.json) console.log(JSON.stringify(preview))
            else {
              console.log(chalk.cyan(`Vault 初始化预览：新建 ${directoryCreateCount} 个目录、${fileCreateCount} 个文件，覆盖 ${overwriteCount} 个文件`))
            }
            return
          }

          if (!opts.yes) {
            if (opts.json) {
              console.log(JSON.stringify({ ...preview, success: false, dryRun: false, code: 'CONFIRMATION_REQUIRED' }))
              process.exit(1)
            }
            const { confirmed } = await inquirer.prompt([{
              type: 'confirm',
              name: 'confirmed',
              message: `确认初始化 Vault？将新建 ${directoryCreateCount} 个目录、${fileCreateCount} 个文件，并覆盖 ${overwriteCount} 个已有文件。`,
              default: false,
            }])
            if (!confirmed) {
              console.log(chalk.gray('已取消'))
              return
            }
          }

          if (!opts.json) console.log(chalk.cyan(`\n🔧 初始化 Obsidian Vault: ${vaultPath}\n`))
          for (const dir of dirs) {
            mkdirSync(join(vaultPath, dir), { recursive: true })
            if (!opts.json) console.log(`  ✓ ${dir}/`)
          }
          for (const file of files) {
            writeFileSync(join(vaultPath, file.relativePath), file.content, 'utf8')
          }

          if (opts.json) {
            console.log(JSON.stringify({
              success: true,
              action: 'vault.init',
              directoryCreateCount,
              fileCreateCount,
              overwriteCount,
            }))
          } else {
            console.log(chalk.green(`\n✓ Vault 创建完成!`))
            console.log(`  用 Obsidian 打开: File → Open Vault → ${vaultPath}`)
          }
        })
    )

  // wiki compile
  program
    .command('wiki')
    .description('概念图谱管理')
    .addCommand(
      new Command('compile')
        .description('扫描文章 [[Wikilinks]] 聚合生成概念页')
        .option('-l, --limit <n>', '最多生成概念数', '20')
        .option('--min-refs <n>', '至少被几篇材料提到才建页（2 能滤掉新闻里的一次性实体）', '1')
        .option('--source <dir>', '材料目录（**必须含 [[概念]] — 说明 形状的链接**，否则聚合不出任何概念）', './output/biz-daily')
        .option('-o, --output <dir>', '概念页输出目录', join(resolveOutputRoot(), 'wechat-vault', 'Wiki', 'Concepts'))
        .option('--api-key <key>', 'DeepSeek API key')
        .option('--refresh-sources',
                '只把已有概念页的"来源"段补齐成当前全部来源（本地重写，**不调用模型**）')
        .option('--qualify-links',
                '把跨线同名的概念链接改成带路径的形式（本地重写，**不调用模型**）')
        .option('--cards <dir...>', '产卡目录，可写多个；默认所有 output/*-notes（与索引的引用数同一口径）')
        .option('--dry-run', '仅预览，不读取文章、调用 AI 或写入概念页')
        .option('--yes', '确认调用 AI 并生成概念页')
        .option('--json', '输出机器可读结果，不返回概念或本地路径')
        .action(async (opts) => {
          const pkgRoot = resolvePackageRoot()
          const script = join(pkgRoot, 'scripts', 'compile_wiki.py')

          if (opts.refreshSources) {
            // 本地补来源：**不调模型**，所以不传 apiKey、preview 里也不说"调用 AI"。
            // 但它会把已有页重写一遍（实测会动 358 张），照样走"先预览、再确认"那两步。
            await runConfirmedPythonMutation({
              action: 'wiki.refreshSources',
              script,
              args: ['--refresh-sources', '--output', opts.output,
                     ...(opts.cards ?? []).flatMap((c: string) => ['--cards', c])],
              cliOptions: opts,
              preview: { readsLocalCards: true, rewritesExistingPages: true, usesAi: false },
              confirmationMessage: `确认把 ${opts.output} 里已有概念页的"来源"段补齐？（本地重写，不调用 AI）`,
              apiKey: opts.apiKey,
              timeout: 300_000,
            })
            return
          }

          if (opts.qualifyLinks) {
            // 本地消歧：两条线同名的那些链接按名字带路径（`Chat/Concepts/DeepSeek|DeepSeek`），
            // 免得 Obsidian 里那条裸链接命中另一条线的那张。**不调模型**，重跑幂等。
            await runConfirmedPythonMutation({
              action: 'wiki.qualifyLinks',
              script,
              args: ['--qualify-links', '--output', opts.output],
              cliOptions: opts,
              preview: { readsLocalKnowledge: true, rewritesExistingPages: true, usesAi: false },
              confirmationMessage: `确认把 ${opts.output} 里跨线同名的概念链接改成带路径的形式？`
                + '（本地重写，不调用 AI）',
              apiKey: opts.apiKey,
              timeout: 300_000,
            })
            return
          }
          const limit = parseCliInteger(opts.limit, 'limit', 1, 1000, opts.json)
          const minRefs = parseCliInteger(opts.minRefs ?? '1', 'min-refs', 1, 50, opts.json)
          await runConfirmedPythonMutation({
            action: 'wiki.compile',
            script,
            args: ['--limit', String(limit), '--source', opts.source, '--output', opts.output,
                   '--min-refs', String(minRefs)],
            cliOptions: opts,
            preview: { limit, minRefs, readsLocalArticles: true, usesAi: true, writesConceptPages: true },
            confirmationMessage: `确认调用 AI 并生成最多 ${limit} 个概念页？`,
            apiKey: opts.apiKey,
            timeout: 300_000,
          })
        })
    )

  // pipeline run
  program
    .command('pipeline')
    .description('端到端自动化流水线')
    .addCommand(
      new Command('run')
        .description('一键运行 biz_daily → classify → wiki compile')
        .option('--date <YYYY-MM-DD>', '日期')
        .option('--api-key <key>', 'DeepSeek API key')
        .option('--engine <name>', 'AI 引擎: deepseek / claude / ollama / local', 'deepseek')
        .option('--interest <topic>', '兴趣主题', 'AI')
        .option('--wiki-limit <n>', '概念编译数', '20')
        .option('--source <name>', '仅处理指定公众号，可重复使用', (value: string, previous: string[]) => [...previous, value], [] as string[])
        .option('--skip-classify', '跳过 AI 后处理')
        // 这两个**默认不做**：Obsidian 自带的图谱视图是实时的，写一次 vault 图谱就重画一次。
        .option('--with-wiki', '把概念页写进 Obsidian Vault（默认不写：图谱只在你说了才变）')
        .option('--with-vault', '把当天内容副本同步进 Obsidian Vault（默认不写）')
        .option('--skip-html', '跳过 HTML 阅读器生成')
        .option('--skip-ai-report', '跳过 AI 深度阅读报告')
        .option('--no-ai', '关闭全部 AI 调用，保留抓取和本地输出')
  .option('--no-summary', '只判断不生成：biz_daily 不调 LLM 写摘要/标签/简报（判断仍走 Jev）')
        .option('--ai-report-range <n>', 'AI 报告覆盖最近 N 天', '1')
        .option('--dry-run', '仅预览步骤，不读取聊天数据、调用网络或写入文件')
        .option('--yes', '确认运行流水线')
        .option('--json', '输出机器可读结果，不返回本地路径')
        .action(async (opts) => {
          const allowedEngines = new Set(['deepseek', 'claude', 'ollama', 'local'])
          if (!allowedEngines.has(opts.engine)) {
            if (opts.json) console.log(JSON.stringify({ success: false, code: 'INVALID_ARGUMENT', field: 'engine' }))
            else console.log(chalk.red('engine 必须是 deepseek、claude、ollama 或 local'))
            process.exit(1)
          }
          if (opts.date) {
            try {
              parseLocalDateOrIso(opts.date)
              if (!/^\d{4}-\d{2}-\d{2}$/.test(opts.date)) throw new DateRangeError('INVALID_DATE', '日期无效')
            } catch {
              if (opts.json) console.log(JSON.stringify({ success: false, code: 'INVALID_DATE', field: 'date' }))
              else console.log(chalk.red('date 必须是有效的 YYYY-MM-DD 日期'))
              process.exit(1)
            }
          }
          const wikiLimit = parseCliInteger(opts.wikiLimit, 'wiki-limit', 1, 1000, opts.json)
          const aiReportRange = parseCliInteger(opts.aiReportRange, 'ai-report-range', 1, 365, opts.json)
          const sources = opts.source as string[]
          const noAi = opts.ai === false
          const preview = {
            success: true,
            dryRun: true,
            action: 'pipeline.run',
            dateSpecified: !!opts.date,
            sourceCount: sources.length,
            engine: opts.engine,
            aiEnabled: !noAi,
            cloudAiEnabled: !noAi && ['deepseek', 'claude'].includes(opts.engine),
            vaultSyncEnabled: !opts.skipVault,
            htmlEnabled: !opts.skipHtml,
            wikiEnabled: !opts.skipWiki && !noAi,
            classifyEnabled: !opts.skipClassify && !noAi,
            aiReportEnabled: !opts.skipAiReport && !noAi,
          }
          if (opts.dryRun) {
            if (opts.json) console.log(JSON.stringify(preview))
            else console.log(chalk.cyan(`流水线预览：${sources.length || '全部'} 个指定来源，AI ${noAi ? '关闭' : '开启'}，Vault 同步 ${opts.skipVault ? '关闭' : '开启'}`))
            return
          }
          if (!opts.yes) {
            if (opts.json) {
              console.log(JSON.stringify({ ...preview, success: false, dryRun: false, code: 'CONFIRMATION_REQUIRED' }))
              process.exit(1)
            }
            const { confirmed } = await inquirer.prompt([{
              type: 'confirm',
              name: 'confirmed',
              message: `确认运行流水线？将抓取内容并写入本地输出${opts.skipVault ? '' : '，同时替换当天 Vault 副本'}。`,
              default: false,
            }])
            if (!confirmed) {
              console.log(chalk.gray('已取消'))
              return
            }
          }
          const { execFile } = await import('child_process')
          const { promisify } = await import('util')
          const execFileAsync = promisify(execFile)
          const pkgRoot = resolvePackageRoot()
          const script = join(pkgRoot, 'scripts', 'pipeline.py')

          const args: string[] = [
            script,
            '--engine', opts.engine,
            '--interest', opts.interest,
            '--wiki-limit', String(wikiLimit),
            '--ai-report-range', String(aiReportRange),
          ]
          if (opts.date) args.push('--date', opts.date)
          for (const source of sources) args.push('--source', source)
          if (opts.skipClassify) args.push('--skip-classify')
          if (opts.withWiki) args.push('--with-wiki')
          if (opts.withVault) args.push('--with-vault')
          if (opts.skipHtml) args.push('--skip-html')
          if (opts.skipAiReport) args.push('--skip-ai-report')
          if (noAi) args.push('--no-ai')
          if (opts.noSummary && !noAi) args.push('--no-summary')

          try {
            if (!opts.json) console.log(chalk.cyan('\n启动端到端流水线...\n'))
            const { stdout } = await execFileAsync(getPythonCommand(), args, {
              timeout: 600_000,
              maxBuffer: 50 * 1024 * 1024,
              env: pythonProcessEnv(opts.apiKey),
            })
            if (opts.json) console.log(JSON.stringify({ success: true, action: 'pipeline.run' }))
            else console.log(stdout)
          } catch (e: any) {
            if (opts.json) console.log(JSON.stringify({ success: false, code: 'PIPELINE_FAILED', error: safeSubprocessError(e, '流水线失败') }))
            else console.error(chalk.red(`\n✗ ${safeSubprocessError(e, '流水线失败')}`))
            process.exit(1)
          }
        })
    )

  // vault sync — add to existing vault command
  program.commands
    .find(c => c.name() === 'vault')
    ?.addCommand(
      new Command('sync')
        .description('增量提交 Vault 并推送到远端仓库')
        .option('-r, --repo <url>', '远端 Git 仓库地址')
        .option('-b, --branch <name>', '分支名', 'main')
        .option('--dry-run', '仅预览变更数量，不提交或推送')
        .option('--yes', '确认提交并推送')
        .option('--vault <path>', 'Vault 路径', join(resolveOutputRoot(), 'wechat-vault'))
        .option('--json', '输出 JSON 格式，不返回远端地址或文件名')
        .action(async (opts) => {
          const { execFile } = await import('child_process')
          const { promisify } = await import('util')
          const execFileAsync = promisify(execFile)
          // 支持 --vault 覆盖：默认落在可写输出根下（全局安装时包目录不可写），
          // 但把 vault 放在别处的用户必须能指定——之前它写死推导，测试也只能靠 cwd 凑。
          const vaultPath = opts.vault || join(resolveOutputRoot(), 'wechat-vault')

          const repo = opts.repo || configService.get('vaultRepo')
          if (!repo) {
            if (opts.json) {
              console.log(JSON.stringify({ success: false, code: 'VAULT_REMOTE_REQUIRED' }))
              process.exit(1)
            }
            console.error(chalk.red('\n❌ 未指定远端仓库。运行: weflow-cli config set vaultRepo <url> 或使用 --repo 参数\n'))
            process.exit(1)
          }

          try {
            const gitDir = join(vaultPath, '.git')
            const { existsSync, readdirSync } = await import('fs')
            if (!existsSync(vaultPath)) {
              if (opts.json) console.log(JSON.stringify({ success: false, code: 'VAULT_NOT_FOUND' }))
              else console.error(chalk.red('Vault 不存在，请先运行 weflow-cli vault init'))
              process.exit(1)
            }

            const initialized = existsSync(gitDir)
            const countFiles = (dir: string): number => readdirSync(dir, { withFileTypes: true }).reduce((total, entry) => {
              if (entry.name === '.git') return total
              return total + (entry.isDirectory() ? countFiles(join(dir, entry.name)) : 1)
            }, 0)
            const status = initialized
              ? (await execFileAsync('git', ['status', '--porcelain'], { cwd: vaultPath })).stdout
              : ''
            const changeCount = initialized
              ? status.split(/\r?\n/).filter(Boolean).length
              : countFiles(vaultPath)
            const preview = {
              success: true,
              dryRun: true,
              action: 'vault.sync',
              branch: opts.branch,
              initialized,
              changeCount,
            }

            if (opts.dryRun) {
              if (opts.json) console.log(JSON.stringify(preview))
              else console.log(chalk.cyan(`Vault 同步预览：${changeCount} 个文件状态将被处理`))
              return
            }
            if (changeCount === 0) {
              if (opts.json) console.log(JSON.stringify({ success: true, action: 'vault.sync', changed: false, pushed: false }))
              else console.log(chalk.yellow('没有变更，跳过同步'))
              return
            }
            if (!opts.yes) {
              if (opts.json) {
                console.log(JSON.stringify({ success: false, code: 'CONFIRMATION_REQUIRED', action: 'vault.sync', changeCount }))
                process.exit(1)
              }
              const { confirmed } = await inquirer.prompt([{
                type: 'confirm',
                name: 'confirmed',
                message: `确认提交并推送 Vault 的 ${changeCount} 个文件状态？`,
                default: false,
              }])
              if (!confirmed) {
                console.log(chalk.gray('已取消'))
                return
              }
            }

            if (!existsSync(gitDir)) {
              if (!opts.json) console.log(chalk.cyan('初始化 Vault Git 仓库...'))
              await execFileAsync('git', ['init'], { cwd: vaultPath })
              await execFileAsync('git', ['remote', 'add', 'origin', repo], { cwd: vaultPath })
            } else {
              try {
                await execFileAsync('git', ['remote', 'get-url', 'origin'], { cwd: vaultPath })
              } catch {
                await execFileAsync('git', ['remote', 'add', 'origin', repo], { cwd: vaultPath })
              }
            }

            const dateStr = new Date().toISOString().slice(0, 10)
            await execFileAsync('git', ['add', '-A'], { cwd: vaultPath })
            const { stdout: statOut } = await execFileAsync('git', ['diff', '--cached', '--stat'], { cwd: vaultPath })
            if (!opts.json) console.log(chalk.cyan('提交变更...'))
            await execFileAsync('git', ['commit', '-m', `vault sync: ${dateStr} | ${statOut.split('\n').length} files`], { cwd: vaultPath })

            if (!opts.json) console.log(chalk.cyan('推送到远端...'))
            await execFileAsync('git', ['push', '-u', 'origin', opts.branch], { cwd: vaultPath, timeout: 60_000 })

            if (opts.json) console.log(JSON.stringify({ success: true, action: 'vault.sync', changed: true, pushed: true, branch: opts.branch, changeCount }))
            else console.log(chalk.green(`\n✓ Vault 已同步 (${opts.branch})`))
          } catch (e: any) {
            if (opts.json) console.log(JSON.stringify({ success: false, code: 'VAULT_SYNC_FAILED', error: safeSubprocessError(e, '同步失败') }))
            else console.error(chalk.red(`\n✗ ${safeSubprocessError(e, '同步失败')}`))
            process.exit(1)
          }
        })
    )

  // vault enrich — bidirectional backlinks
  program.commands
    .find(c => c.name() === 'vault')
    ?.addCommand(
      new Command('enrich')
        .description('增强双向链接 — 为文章添加相关阅读段落')
        .option('--date <YYYY-MM-DD>', '日期（默认今天）')
        .option('--source <dir>', '文章目录', './output/biz-daily')
        .option('--dry-run', '仅预览，不读取或修改文章')
        .option('--yes', '确认修改文章')
        .option('--json', '输出机器可读结果，不返回本地路径')
        .action(async (opts) => {
          const pkgRoot = resolvePackageRoot()
          const script = join(pkgRoot, 'scripts', 'enrich_backlinks.py')
          if (!opts.date) {
            const now = new Date()
            opts.date = `${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,'0')}-${String(now.getDate()).padStart(2,'0')}`
          }
          requireCliDate(opts.date, opts.json)
          await runConfirmedPythonMutation({
            action: 'vault.enrich',
            script,
            args: ['--date', opts.date, '--source', opts.source],
            cliOptions: opts,
            preview: { dateSpecified: true, modifiesArticles: true, usesAi: false },
            confirmationMessage: '确认向当日文章写入相关阅读链接？',
          })
        })
    )

  // vault notes — create reading notes
  program.commands
    .find(c => c.name() === 'vault')
    ?.addCommand(
      new Command('notes')
        .description('创建阅读笔记 — 为文章生成 Vault 笔记页')
        .option('--date <YYYY-MM-DD>', '日期（默认今天）')
        .option('--source <dir>', '文章目录', './output/biz-daily')
        .option('--vault <path>', 'Vault 路径', join(resolveOutputRoot(), 'wechat-vault'))
        .option('--dry-run', '仅预览，不读取文章或写入笔记')
        .option('--yes', '确认生成阅读笔记')
        .option('--json', '输出机器可读结果，不返回本地路径')
        .action(async (opts) => {
          const pkgRoot = resolvePackageRoot()
          const script = join(pkgRoot, 'scripts', 'create_reading_notes.py')
          if (!opts.date) {
            const now = new Date()
            opts.date = `${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,'0')}-${String(now.getDate()).padStart(2,'0')}`
          }
          requireCliDate(opts.date, opts.json)
          await runConfirmedPythonMutation({
            action: 'vault.notes',
            script,
            args: ['--date', opts.date, '--source', opts.source, '--vault', opts.vault],
            cliOptions: opts,
            preview: { dateSpecified: true, createsNotes: true, usesAi: false },
            confirmationMessage: '确认从当日文章生成 Vault 阅读笔记？',
          })
        })
    )

  // vault tag — auto tag
  program.commands
    .find(c => c.name() === 'vault')
    ?.addCommand(
      new Command('tag')
        .description('自动标签 — AI 为文章补充标签')
        .option('--date <YYYY-MM-DD>', '日期（默认今天）')
        .option('--source <dir>', '文章目录', './output/biz-daily')
        .option('--force', '覆盖已有标签')
        .option('--api-key <key>', 'DeepSeek API key')
        .option('--dry-run', '仅预览，不读取文章、调用 AI 或修改标签')
        .option('--yes', '确认调用 AI 并修改文章标签')
        .option('--json', '输出机器可读结果，不返回本地路径或文章名')
        .action(async (opts) => {
          const pkgRoot = resolvePackageRoot()
          const script = join(pkgRoot, 'scripts', 'auto_tag.py')
          if (!opts.date) { const n=new Date(); opts.date=`${n.getFullYear()}-${String(n.getMonth()+1).padStart(2,'0')}-${String(n.getDate()).padStart(2,'0')}` }
          requireCliDate(opts.date, opts.json)
          await runConfirmedPythonMutation({
            action: 'vault.tag',
            script,
            args: ['--date', opts.date, '--source', opts.source, ...(opts.force ? ['--force'] : [])],
            cliOptions: opts,
            preview: { dateSpecified: true, force: !!opts.force, modifiesArticles: true, usesAi: true },
            confirmationMessage: `确认调用 AI 为当日文章生成标签${opts.force ? '并覆盖已有标签' : ''}？`,
            apiKey: opts.apiKey,
          })
        })
    )

  // vault search — search across Vault
  program.commands
    .find(c => c.name() === 'vault')
    ?.addCommand(
      new Command('search')
        .description('Vault 搜索 — 文章+概念+笔记')
        .argument('<query>', '搜索关键词')
        .option('--type <type>', 'all / article / concept / note', 'all')
        .option('--line <line>', 'wiki=文章线(默认) / chat=聊天线 / all=两条都搜', 'wiki')
        .option('--top-k <n>', '返回数量', '10')
        // `vault_search.py` 一直有 `--days`（它的 docstring 自己就举 `--days 30`），CLI 从来没接 ——
        // 于是"只搜最近一周"这件事在这条路上做不到，窗口被脚本默认值（90）钉死。与 `search-index --days`
        // 同形：窗口的运行值由 CLI 说了算，默认值与脚本一致。
        .option('--days <n>', '日报文章取最近多少天（默认 90）', '90')
        // 这条 `--json` 曾经**不存在，而 JSON 又是唯一的输出**：参数里硬编码着 `'--json'`，
        // 人类模式虽然脚本里写着（`vault_search.py` 不带 `--json` 时打印带相关度的可读列表）
        // 却没有任何入口能到达，用户显式敲 `--json` 还会拿到 `unknown option` —— 与
        // `docs/EXTENDING.md` 那条"脚本或 AI 会驱动的命令都有 `--json` 模式"正相反。
        // 现在按兄弟命令（`vault rag`、顶层 `search`）的形状来：默认人类可读，`--json` 才转发。
        .option('--json', '输出 JSON 格式（含本地路径与标题，供本机脚本/AI 使用）')
        .action(async (query, opts) => {
          const pkgRoot = resolvePackageRoot()
          const script = join(pkgRoot, 'scripts', 'vault_search.py')
          // 校验分支也要认 `--json`（`requireCliChoice` 里就带着这条约定）：
          // 否则 JSON 模式下 stdout 是一行彩色散文，脚本解析不了。
          requireCliChoice(opts.type, ['all', 'article', 'concept', 'note'], 'type', opts.json)
          requireCliChoice(opts.line, ['wiki', 'chat', 'all'], 'line', opts.json)
          const topK = parseCliInteger(opts.topK, 'top-k', 1, 100, opts.json)
          const days = parseCliInteger(opts.days, 'days', 1, 3650, opts.json)
          await runPythonCmd(script, [query, '--type', opts.type, '--line', opts.line,
                                      '--top-k', String(topK), '--days', String(days),
                                      ...(opts.json ? ['--json'] : [])])
        })
    )

  // vault rag — RAG dialog over Vault
  program.commands
    .find(c => c.name() === 'vault')
    ?.addCommand(
      new Command('rag')
        .description('Vault 问答 — 基于知识库的 AI 对话')
        .argument('<question>', '问题')
        .option('--top-k <n>', '检索条数', '8')
        .option('--line <line>', 'wiki=文章线(默认) / chat=聊天线 / all=两条都搜', 'wiki')
        .option('--api-key <key>', 'DeepSeek API key')
        .option('--dry-run', '仅预览，不读取知识库或调用 AI')
        .option('--yes', '确认读取本地知识并发送筛选后的上下文到 AI')
        .option('--json', '输出机器可读结果；执行仍需 --yes')
        .action(async (question, opts) => {
          const pkgRoot = resolvePackageRoot()
          const script = join(pkgRoot, 'scripts', 'vault_rag.py')
          const topK = parseCliInteger(opts.topK, 'top-k', 1, 100, opts.json)
          requireCliChoice(opts.line, ['wiki', 'chat', 'all'], 'line', opts.json)
          const preview = {
            success: true,
            dryRun: true,
            action: 'vault.rag',
            topK,
            line: opts.line,
            readsLocalKnowledge: true,
            usesAi: true,
            sendsSelectedContextToAi: true,
          }
          if (opts.dryRun) {
            if (opts.json) console.log(JSON.stringify(preview))
            else console.log(chalk.cyan('预览：将检索本地知识库，并把最多指定条数的相关上下文发送到已配置的 AI 服务。'))
            return
          }
          if (!opts.yes) {
            if (opts.json) {
              console.log(JSON.stringify({ ...preview, success: false, dryRun: false, code: 'CONFIRMATION_REQUIRED' }))
              process.exit(1)
            }
            const { confirmed } = await inquirer.prompt([{
              type: 'confirm',
              name: 'confirmed',
              message: '确认读取本地知识库并将筛选后的上下文发送到 AI 服务吗？',
              default: false,
            }])
            if (!confirmed) {
              console.log(chalk.gray('已取消'))
              return
            }
          }
          const args = ['--top-k', String(topK), '--line', opts.line]
          if (opts.json) args.push('--json')
          const { execFile } = await import('child_process')
          const { promisify } = await import('util')
          try {
            const { stdout } = await promisify(execFile)(getPythonCommand(), [script, ...args], {
              timeout: 120_000,
              maxBuffer: 5 * 1024 * 1024,
              env: {
                ...pythonProcessEnv(opts.apiKey),
                WEFLOW_VAULT_QUESTION: question,
              },
            })
            console.log(stdout)
          } catch (error) {
            if (opts.json) console.log(JSON.stringify({ success: false, code: 'VAULT_RAG_FAILED', error: safeSubprocessError(error) }))
            else console.error(chalk.red(`\n✗ ${safeSubprocessError(error)}`))
            process.exit(1)
          }
        })
    )

  // vault sync-weread — sync WeRead to Vault
  program.commands
    .find(c => c.name() === 'vault')
    ?.addCommand(
      new Command('sync-weread')
        .description('微信读书同步到 Vault')
        .option('--type <type>', 'all / shelf / notes', 'all')
        .option('--vault <path>', 'Vault 路径', join(resolveOutputRoot(), 'wechat-vault'))
        .option('--dry-run', '仅预览，不请求微信读书或写入 Vault')
        .option('--yes', '确认同步微信读书数据')
        .option('--json', '输出机器可读结果，不返回书籍或本地路径')
        .action(async (opts) => {
          if (!['all', 'shelf', 'notes'].includes(opts.type)) {
            if (opts.json) console.log(JSON.stringify({ success: false, code: 'INVALID_ARGUMENT', field: 'type' }))
            else console.log(chalk.red('type 必须是 all、shelf 或 notes'))
            process.exit(1)
          }
          const pkgRoot = resolvePackageRoot()
          const script = join(pkgRoot, 'scripts', 'sync_weread.py')
          await runConfirmedPythonMutation({
            action: 'vault.sync-weread',
            script,
            args: ['--type', opts.type, '--vault', opts.vault],
            cliOptions: opts,
            preview: { syncType: opts.type, readsWereadCloud: true, writesVault: true },
            confirmationMessage: '确认从微信读书服务读取数据并写入本地 Vault？',
            apiKeyVariable: 'WEREAD_API_KEY',
          })
        })
    )

  const vaultPromoteCmd = new Command('promote')
    .description('从 Vault 阅读笔记生成知识索引、想法和长期笔记')

  const runVaultPromotion = async (
    scriptName: string,
    action: string,
    opts: { vault: string, withAi?: boolean, apiKey?: string, dryRun?: boolean, yes?: boolean, json?: boolean },
  ) => {
    const pkgRoot = resolvePackageRoot()
    const args = ['--vault', opts.vault]
    // 也读配置：`config set deepseekApiKey` 之后不该还要求传参或设环境变量


    const apiKey = resolveAiKey(opts.apiKey)
    if (opts.withAi && !opts.dryRun) {
      if (!apiKey) {
        if (opts.json) console.log(JSON.stringify({ success: false, code: 'AI_KEY_REQUIRED', action }))
        else console.error(chalk.red('启用 AI 升级需要 --api-key 或 DEEPSEEK_API_KEY。'))
        process.exit(1)
      }
    } else {
      args.push('--skip-ai')
    }
    await runConfirmedPythonMutation({
      action,
      script: join(pkgRoot, 'scripts', scriptName),
      args,
      cliOptions: opts,
      preview: { usesAi: !!opts.withAi, writesVault: true },
      confirmationMessage: `确认生成 Vault 知识提升内容？${opts.withAi ? '选定笔记内容将发送到已配置的 AI 服务。' : '仅执行本地确定性处理。'}`,
      apiKey: opts.withAi ? apiKey : undefined,
    })
  }

  vaultPromoteCmd
    .command('ideas')
    .description('生成主题导航和可选的研究想法')
    .option('--vault <path>', 'Vault 路径', join(resolveOutputRoot(), 'wechat-vault'))
    .option('--with-ai', '允许 AI 生成研究想法')
    .option('--api-key <key>', 'AI API key，仅与 --with-ai 一起使用')
    .option('--dry-run', '仅预览，不读取笔记、调用 AI 或写入 Vault')
    .option('--yes', '确认生成知识提升内容')
    .option('--json', '输出机器可读结果，不返回笔记或本地路径')
    .action(async (opts) => {
      await runVaultPromotion('promote_ideas.py', 'vault.promote.ideas', opts)
    })

  vaultPromoteCmd
    .command('all')
    .description('生成参考索引和可选的永久笔记、项目提案')
    .option('--vault <path>', 'Vault 路径', join(resolveOutputRoot(), 'wechat-vault'))
    .option('--with-ai', '允许 AI 生成永久笔记和项目提案')
    .option('--api-key <key>', 'AI API key，仅与 --with-ai 一起使用')
    .option('--dry-run', '仅预览，不读取笔记、调用 AI 或写入 Vault')
    .option('--yes', '确认生成知识提升内容')
    .option('--json', '输出机器可读结果，不返回笔记或本地路径')
    .action(async (opts) => {
      await runVaultPromotion('promote_all.py', 'vault.promote.all', opts)
    })

  program.commands.find(c => c.name() === 'vault')?.addCommand(vaultPromoteCmd)

  // chat-stats
  program
    .command('chat-stats')
    .description('微信个人信息消费报告（支付 + 转账）')
    .option('--period <week|month>', '报告周期', 'week')
    .option('--month <YYYY-MM>', '指定月份（覆盖 --period）')
    .option('-o, --output <path>', '输出路径')
    .option('--dry-run', '仅预览，不读取聊天或写入报告')
    .option('--yes', '确认生成消费报告')
    .option('--json', '输出机器可读结果，不返回统计正文或本地路径')
    .action(async (opts) => {
      if (!['week', 'month'].includes(opts.period)) {
        if (opts.json) console.log(JSON.stringify({ success: false, code: 'INVALID_ARGUMENT', field: 'period' }))
        else console.log(chalk.red('period 必须是 week 或 month'))
        process.exit(1)
      }
      if (opts.month && !/^\d{4}-(0[1-9]|1[0-2])$/.test(opts.month)) {
        if (opts.json) console.log(JSON.stringify({ success: false, code: 'INVALID_DATE', field: 'month' }))
        else console.log(chalk.red('month 必须是有效的 YYYY-MM 月份'))
        process.exit(1)
      }
      const pkgRoot = resolvePackageRoot()
      const script = join(pkgRoot, 'scripts', 'chat_stats.py')
      const args: string[] = ['--period', opts.period]
      if (opts.month) { args.push('--month', opts.month) }
      if (opts.output) { args.push('--output', opts.output) }
      await runConfirmedPythonMutation({
        action: 'chat-stats.generate',
        script,
        args,
        cliOptions: opts,
        preview: { period: opts.month ? 'specified-month' : opts.period, readsLocalChat: true, includesPaymentStats: true },
        confirmationMessage: '确认读取本地聊天、支付与转账数据并生成消费报告？',
        timeout: 600_000,
      })
    })

  // generate-review
  program
    .command('review')
    .description('生成 AI 学习日报')
    .option('--date <YYYY-MM-DD>', '日期')
    .option('--api-key <key>', 'DeepSeek API key')
    .option('--engine <name>', 'AI 引擎: deepseek / claude / ollama', 'deepseek')
    .option('--source <dir>', '文章目录', './output/biz-daily')
    .option('--output <dir>', '输出目录', './output/reviews')
    .option('--dry-run', '仅预览，不读取文章、调用 AI 或写入日报')
    .option('--yes', '确认生成学习日报')
    .option('--json', '输出机器可读结果，不返回本地路径')
    .action(async (opts) => {
      if (!['deepseek', 'claude', 'ollama'].includes(opts.engine)) {
        if (opts.json) console.log(JSON.stringify({ success: false, code: 'INVALID_ARGUMENT', field: 'engine' }))
        else console.log(chalk.red('engine 必须是 deepseek、claude 或 ollama'))
        process.exit(1)
      }
      if (opts.date) {
        try {
          parseLocalDateOrIso(opts.date)
          if (!/^\d{4}-\d{2}-\d{2}$/.test(opts.date)) throw new DateRangeError('INVALID_DATE', '日期无效')
        } catch {
          if (opts.json) console.log(JSON.stringify({ success: false, code: 'INVALID_DATE', field: 'date' }))
          else console.log(chalk.red('date 必须是有效的 YYYY-MM-DD 日期'))
          process.exit(1)
        }
      }
      const preview = {
        success: true,
        dryRun: true,
        action: 'review.generate',
        dateSpecified: !!opts.date,
        engine: opts.engine,
        readsLocalArticles: true,
        usesAi: true,
      }
      if (opts.dryRun) {
        if (opts.json) console.log(JSON.stringify(preview))
        else console.log(chalk.cyan(`学习日报预览：使用 ${opts.engine} 分析本地文章并写入报告`))
        return
      }
      if (!opts.yes) {
        if (opts.json) {
          console.log(JSON.stringify({ ...preview, success: false, dryRun: false, code: 'CONFIRMATION_REQUIRED' }))
          process.exit(1)
        }
        const { confirmed } = await inquirer.prompt([{
          type: 'confirm',
          name: 'confirmed',
          message: '确认生成 AI 学习日报？文章摘要将发送到已配置的 AI 服务。',
          default: false,
        }])
        if (!confirmed) {
          console.log(chalk.gray('已取消'))
          return
        }
      }
      const { execFile } = await import('child_process')
      const { promisify } = await import('util')
      const execFileAsync = promisify(execFile)
    const pkgRoot = resolvePackageRoot()
      const script = join(pkgRoot, 'scripts', 'generate_review.py')
      const args: string[] = [script, '--engine', opts.engine, '--source', opts.source, '--output', opts.output]
      if (opts.date) args.push('--date', opts.date)
      try {
        const { stdout } = await execFileAsync(getPythonCommand(), args, {
          timeout: 120_000, maxBuffer: 10 * 1024 * 1024,
          env: pythonProcessEnv(opts.apiKey),
        })
        if (opts.json) console.log(JSON.stringify({ success: true, action: 'review.generate' }))
        else console.log(stdout)
      } catch (e: any) {
        if (opts.json) console.log(JSON.stringify({ success: false, code: 'REVIEW_FAILED', error: safeSubprocessError(e) }))
        else console.error(chalk.red(`\n✗ ${safeSubprocessError(e)}`))
        process.exit(1)
      }
    })

  // fav-server
  program
    .command('fav-server')
    .description('启动收藏服务器 — daily-server 的兼容入口')
    .option('--date <YYYY-MM-DD>', '日期（默认今天）')
    .option('--port <number>', '端口', '8765')
    .option('--open', '自动打开浏览器')
    .option('--dry-run', '仅预览，不启动服务或打开浏览器')
    .option('--yes', '确认启动本地服务')
    .option('--json', '输出机器可读状态；启动仍需 --yes')
    .action(async (opts) => {
      const { spawn } = await import('child_process')
    const pkgRoot = resolvePackageRoot()
      const script = join(pkgRoot, 'scripts', 'fav_server.py')

      if (!opts.date) {
        const now = new Date()
        const yyyy = now.getFullYear()
        const mm = String(now.getMonth() + 1).padStart(2, '0')
        const dd = String(now.getDate()).padStart(2, '0')
        opts.date = `${yyyy}-${mm}-${dd}`
      }
      requireCliDate(opts.date, opts.json)

      const port = parseCliInteger(opts.port, 'port', 1, 65535, opts.json)
      const args = [script, '--date', opts.date, '--port', String(port)]
      const preview = {
        success: true,
        dryRun: true,
        action: 'daily-reader.start',
        compatibilityAlias: 'fav-server',
        date: opts.date,
        port,
        loopbackOnly: true,
        opensBrowser: Boolean(opts.open),
      }
      if (opts.dryRun) {
        if (opts.json) console.log(JSON.stringify(preview))
        else console.log(chalk.cyan(`收藏服务启动预览：${opts.date}，本机端口 ${port}${opts.open ? '，并打开浏览器' : ''}。`))
        return
      }
      if (opts.json && !opts.yes) {
        console.log(JSON.stringify({ ...preview, success: false, dryRun: false, code: 'CONFIRMATION_REQUIRED' }))
        process.exit(1)
      }
      if (opts.json) {
        const result = await startDetachedDailyReader(script, opts.date, port)
        if (result.success && opts.open) await openLocalUrl(`http://localhost:${port}`)
        console.log(JSON.stringify({
          ...result,
          action: 'daily-reader.start',
          date: opts.date,
          port,
          openedBrowser: result.success && Boolean(opts.open),
        }))
        if (!result.success) process.exit(1)
        return
      }
      console.log(chalk.cyan(`⭐ 启动收藏服务器 (${opts.date})\n`))
      console.log(chalk.gray(`  按住 Ctrl 并点击: http://localhost:${port}`))

      if (opts.open) {
        await openLocalUrl(`http://localhost:${port}`)
      }

      const child = spawn(getPythonCommand(), args, {
        windowsHide: true,
        stdio: 'inherit',
        env: pythonProcessEnv(),
      })
      await new Promise<void>((resolve) => child.on('exit', (code) => {
        if (code !== 0 && code !== null) process.exit(code)
        resolve()
      }))
    })

  // ==================== weread ====================

  /** 微信读书服务失败时的统一出口。
   *
   * 9 个调用点（shelf / stats / notes×2 / search / book / review / discover / profile）原来都是一行式
   * 分支：把彩色散文打在 stdout 上再 `process.exit(1)`，**没有** json 支，而各命令的 `if (opts.json)`
   * 分支在它后面 ⇒ `weread shelf --json` 失败时 stdout 上只有一行 `✗ …`，调用方解析不了，也不知道
   * 是哪个命令失败了。全库其余同类出口都是"机器支发 JSON + exit"。
   *
   * （这里刻意**不**把那行旧代码原样抄出来：`test/json-error-surface.test.ts` 有一条绊线在扫那个形状，
   * 而注释里留一份字面量会让判据读到它 —— 今晚已经在另一条判据上踩过这个坑。）
   *
   * 人看的那一支保持原样（`console.log`，不动它的落点）：把 CLI 的**错误**统一改走 stderr 是另一件事，
   * 现在库里两种都有（多数 `console.error`、少数 `console.log`），不在这条修复里顺手改。
   */
  function failWeread(res: { error?: string }, json = false): never {
    if (json) console.log(JSON.stringify({ success: false, code: 'WEREAD_FAILED', error: res.error }))
    else console.log(chalk.red(`✗ ${res.error}`))
    process.exit(1)
  }
  const wereadCmd = program
    .command('weread')
    .description('微信读书助手 — 书架、统计、笔记、搜索、书评、推荐')

  wereadCmd
    .command('shelf')
    .description('查看书架')
    .option('--json', 'JSON 输出')
    .action(async (opts) => {
      const weread = await getWereadService()
      const res = await weread.shelf()
      if (!res.ok) failWeread(res, !!opts.json)
      const d = res.data!
      if (opts.json) { console.log(JSON.stringify(d, null, 2)); return }

      const total = d.books.length + d.albums.length + (d.mp ? 1 : 0)
      console.log(chalk.cyan(`📚 书架 (${total} 条目):\n`))
      console.log(chalk.gray(`  电子书: ${d.books.length} 本 | 有声书: ${d.albums.length} 个 | 文章收藏: ${d.mp ? '有' : '无'}`))
      if (d.archive.length) {
        console.log(chalk.gray(`  书单: ${d.archive.map((a: any) => a.name).join(', ')}`))
      }
      console.log()
      const books = d.books.sort((a: any, b: any) => b.readUpdateTime - a.readUpdateTime)
      for (let i = 0; i < Math.min(books.length, 30); i++) {
        const b = books[i]
        const num = String(i + 1).padStart(3)
        const done = b.finishReading === 1 ? chalk.green('✓') : ' '
        console.log(`${num}. ${done} ${b.title}  ${chalk.gray(b.author)}`)
      }
      if (d.books.length > 30) console.log(chalk.gray(`  ... 共 ${d.books.length} 本`))
    })

  wereadCmd
    .command('stats')
    .description('阅读统计')
    .option('--mode <mode>', 'weekly | monthly | annually | overall', 'monthly')
    .option('--json', 'JSON 输出')
    .action(async (opts) => {
      const weread = await getWereadService()
      const res = await weread.readData(opts.mode)
      if (!res.ok) failWeread(res, !!opts.json)
      const d = res.data!
      if (opts.json) { console.log(JSON.stringify(d, null, 2)); return }

      const h = (d.totalReadTime || 0) / 3600
      console.log(chalk.cyan(`📊 阅读统计 (${opts.mode}):\n`))
      console.log(`  总时长: ${chalk.white(h.toFixed(1) + ' 小时')}`)
      console.log(`  有效天数: ${chalk.white(String(d.readDays))}`)
      if (d.dayAverageReadTime) {
        console.log(`  日均: ${chalk.white(Math.round(d.dayAverageReadTime / 60) + ' 分钟')}`)
      }
      if (d.readStat?.length) {
        console.log(`  ${d.readStat.map((s: any) => `${s.stat}: ${chalk.white(s.counts)}`).join(' | ')}`)
      }
      if (d.preferCategoryWord) console.log(`  偏好: ${chalk.white(d.preferCategoryWord)}`)
      if (d.preferTimeWord) console.log(`  时段: ${chalk.white(d.preferTimeWord)}`)

      // 偏好分类
      if (d.preferCategory?.length) {
        console.log(chalk.cyan('\n  偏好分类:'))
        for (const c of d.preferCategory.slice(0, 5)) {
          const hh = (c.readingTime / 3600).toFixed(1)
          console.log(`    ${c.categoryTitle}: ${chalk.white(hh + 'h')} (${c.readingCount}本)`)
        }
      }

      // Read longest
      if (d.readLongest?.length) {
        console.log(chalk.cyan('\n  读最久的书:'))
        for (const item of d.readLongest.slice(0, 5)) {
          const b = item.book || item.albumInfo || {}
          const hh = (item.readTime / 3600).toFixed(1)
          console.log(`    ${b.title || '(未知)'}: ${chalk.white(hh + 'h')}  ${chalk.gray(b.author || '')}`)
        }
      }
    })

  wereadCmd
    .command('notes')
    .description('笔记划线')
    .option('--book-id <id>', '指定书籍 ID')
    .option('-n, --limit <n>', '数量', '20')
    .option('--json', 'JSON 输出')
    .action(async (opts) => {
      const weread = await getWereadService()
      const limit = parseCliInteger(opts.limit, 'limit', 1, 100, opts.json)
      if (opts.bookId) {
        const res = await weread.bookmarks(opts.bookId, limit)
        if (!res.ok) failWeread(res, !!opts.json)
        const d = res.data!
        if (opts.json) { console.log(JSON.stringify(d, null, 2)); return }
        console.log(chalk.cyan(`📝 划线笔记 (${d.updated?.length || 0} 条):\n`))
        for (let i = 0; i < Math.min((d.updated || []).length, limit); i++) {
          const n = d.updated[i]
          const icon = n.type === 1 ? '💬' : '📌'
          console.log(`${chalk.gray(`  [${i + 1}]`)} ${icon} ${n.markText?.slice(0, 60) || ''}`)
          if (n.content) console.log(`${chalk.cyan('      想法:')} ${n.content.slice(0, 100)}`)
          console.log()
        }
      } else {
        const res = await weread.notebooks(50)
        if (!res.ok) failWeread(res, !!opts.json)
        const d = res.data!
        if (opts.json) { console.log(JSON.stringify(d, null, 2)); return }
        console.log(chalk.cyan(`📝 笔记本 (${d.books?.length || 0} 本有笔记):\n`))
        for (let i = 0; i < Math.min((d.books || []).length, 30); i++) {
          const b: any = d.books[i]
          const bookInfo = b.book || b
          const num = String(i + 1).padStart(3)
          console.log(`${num}. ${bookInfo.title || '(未知)'}  ${chalk.gray(`划线:${b.highlightCount || b.noteCount || 0} 想法:${b.reviewCount || 0} 书签:${b.bookmarkCount || 0}`)}`)
        }
      }
    })

  wereadCmd
    .command('search')
    .description('搜索书籍')
    .argument('<keyword>', '搜索关键词')
    .option('-n, --limit <n>', '数量', '10')
    .option('--json', 'JSON 输出')
    .action(async (keyword, opts) => {
      const weread = await getWereadService()
      const limit = parseCliInteger(opts.limit, 'limit', 1, 100, opts.json)
      const res = await weread.search(keyword, limit)
      if (!res.ok) failWeread(res, !!opts.json)
      const d = res.data!
      if (opts.json) { console.log(JSON.stringify(d, null, 2)); return }
      console.log(chalk.cyan(`🔍 搜索: "${keyword}" (${d.books?.length || 0} 条):\n`))
      for (let i = 0; i < (d.books || []).length; i++) {
        const b = d.books[i]
        const num = String(i + 1).padStart(2)
        const star = b.rating ? ` ⭐${b.rating}` : ''
        console.log(`  ${num}. ${b.title}  ${chalk.gray(b.author)}${star}`)
        if (b.intro) console.log(`     ${chalk.gray(b.intro.slice(0, 80))}`)
      }
    })

  wereadCmd
    .command('book')
    .description('书籍详情')
    .argument('<bookId>', '书籍 ID')
    .option('--json', 'JSON 输出')
    .action(async (bookId, opts) => {
      const weread = await getWereadService()
      const [infoRes, progressRes] = await Promise.all([
        weread.bookInfo(bookId),
        weread.getProgress(bookId),
      ])
      if (!infoRes.ok) failWeread(infoRes, !!opts.json)
      const b = infoRes.data!
      if (opts.json) { console.log(JSON.stringify(b, null, 2)); return }

      console.log(chalk.cyan(`📖 ${b.title}`))
      if (b.author) console.log(`  作者: ${chalk.white(b.author)}`)
      if (b.rating) console.log(`  评分: ${chalk.white('⭐' + b.rating + ' (' + (b as any).ratingCount + '评)')}`)
      if (b.category) console.log(`  分类: ${chalk.gray(b.category)}`)
      if (b.wordCount) console.log(`  字数: ${chalk.gray(b.wordCount)}`)
      if (b.publisher) console.log(`  出版: ${chalk.gray(b.publisher)}`)
      if (b.intro) console.log(`\n  ${b.intro.slice(0, 200)}`)
      if (progressRes.ok && progressRes.data) {
        console.log(`\n  📍 进度: ${chalk.white(progressRes.data.chapterTitle || '未开始')}`)
      }
    })

  wereadCmd
    .command('review')
    .description('书籍点评')
    .argument('<bookId>', '书籍 ID')
    .option('-n, --limit <n>', '数量', '10')
    .option('--json', 'JSON 输出')
    .action(async (bookId, opts) => {
      const weread = await getWereadService()
      const limit = parseCliInteger(opts.limit, 'limit', 1, 100, opts.json)
      const res = await weread.reviews(bookId, limit)
      if (!res.ok) failWeread(res, !!opts.json)
      const d = res.data!
      if (opts.json) { console.log(JSON.stringify(d, null, 2)); return }
      console.log(chalk.cyan(`💬 书评 (${d.reviews?.length || 0} 条):\n`))
      for (let i = 0; i < (d.reviews || []).length; i++) {
        const r = d.reviews[i]
        const num = String(i + 1).padStart(2)
        const star = r.rating ? ` ⭐${r.rating}` : ''
        console.log(`  ${num}. ${r.user?.name || '匿名'}${star}  ${chalk.gray(`👍${r.likeCount || 0}`)}`)
        if (r.content) console.log(`     ${r.content.slice(0, 120)}`)
        console.log()
      }
    })

  wereadCmd
    .command('discover')
    .description('推荐好书')
    .option('--book-id <id>', '基于某本书的相似推荐')
    .option('-n, --limit <n>', '数量', '10')
    .option('--json', 'JSON 输出')
    .action(async (opts) => {
      const weread = await getWereadService()
      const limit = parseCliInteger(opts.limit, 'limit', 1, 100, opts.json)
      const res = opts.bookId
        ? await weread.similar(opts.bookId, limit)
        : await weread.recommend(limit)
      if (!res.ok) failWeread(res, !!opts.json)
      const d = res.data!
      if (opts.json) { console.log(JSON.stringify(d, null, 2)); return }
      const label = opts.bookId ? '相似推荐' : '个性化推荐'
      console.log(chalk.cyan(`🎯 ${label}:\n`))
      for (let i = 0; i < (d.books || []).length; i++) {
        const b = d.books[i]
        const num = String(i + 1).padStart(2)
        const star = b.rating ? ` ⭐${b.rating}` : ''
        console.log(`  ${num}. ${b.title}  ${chalk.gray(b.author)}${star}`)
        if (b.intro) console.log(`     ${chalk.gray(b.intro.slice(0, 80))}`)
      }
    })

  wereadCmd
    .command('profile')
    .description('个人阅读概览')
    .option('--json', 'JSON 输出')
    .action(async (opts) => {
      const weread = await getWereadService()
      const res = await weread.profile()
      if (!res.ok) failWeread(res, !!opts.json)
      const p = res.data!
      if (opts.json) { console.log(JSON.stringify(p, null, 2)); return }

      const totalH = (p.totalReadTime / 3600).toFixed(1)
      console.log(chalk.cyan('📖 个人阅读概览:\n'))
      console.log(`  总时长:  ${chalk.white(totalH + ' 小时')}`)
      console.log(`  阅读天数: ${chalk.white(String(p.totalReadDays) + ' 天')}`)
      console.log(`  书架:    ${chalk.white(String(p.totalBooks) + ' 本')}`)
      console.log(`  读完:    ${chalk.white(String(p.totalFinished) + ' 本')}`)
    })

  // 辅助函数
  async function runPythonCmd(script: string, args: string[], apiKey?: string, apiKeyVariable = 'DEEPSEEK_API_KEY') {
    const { execFile } = await import('child_process')
    const { promisify } = await import('util')
    const execFileAsync = promisify(execFile)
    try {
      const { stdout } = await execFileAsync(getPythonCommand(), [script, ...args], {
        timeout: 120_000, maxBuffer: 5 * 1024 * 1024,
        env: pythonProcessEnv(apiKey, apiKeyVariable),
      })
      console.log(stdout)
    } catch (e: any) {
      console.error(chalk.red(`\n✗ ${safeSubprocessError(e)}`))
      process.exit(1)
    }
  }

  async function getWereadService() {
    // key 的两个来源与优先级见 `resolveWereadApiKey`（抽出去是为了能被测到 ——
    // 只读环境变量那版害得用户配好配置项之后 `weread shelf` 仍然报"未设置"）。
    const mod = await import('../src/services/wereadService.js')
    const key = mod.resolveWereadApiKey(process.env.WEREAD_API_KEY, configService.get('wereadApiKey'))
    return new mod.WereadService(key)
  }

  // semantic-search
  program
    .command('search')
    .description('语义搜索知识库（聊天记录 + 文章）')
    .argument('<query>', '搜索关键词')
    .option('--top-k <n>', '返回数量', '10')
    .option('--line <line>', 'wiki=文章线(默认) / chat=聊天记录 / all=两条都搜', 'wiki')
    .option('--no-rerank', '不调用决策模型重排，只按向量/关键词相似度返回（回退到引入重排之前）')
    .option('--no-hybrid', '不融合本地 BM25 名次（默认融合；门控后实测只增不减）')
    .option('--rerank-pool <n>', '重排看多少条候选（默认 100；越大越准也越贵）')
    .option('--no-dedup', '不折叠同文本的多号转载（默认折叠，结果里带 duplicateCount）')
    .option('--with-text [n]', '给每条命中挂上本地正文（fullText / sourceFile / url）；n 为每条最多多少字')
    .option('--fetch-missing [n]', '正文太薄时按 url 抓一次（最多 n 条，默认 3；复用日报缓存）')
    .option('--mmr', '对结果做 MMR 去冗余（压掉近似的同领域邻居，可能牺牲单点召回）')
    .option('--from <account>', '只查这个公众号的文章（按文件名匹配，不走语义）')
    .option('--phrase', '把这串当**原样短语**在本地定位（FTS5/trigram，不走向量、不出境、不花钱）：回答"哪个号在哪天原样写过它"')
    .option('--api-key <key>', 'DashScope embedding API key')
    .option('--dry-run', '仅预览，不读取索引或调用向量服务')
    .option('--yes', '确认执行可能调用云端向量服务的搜索')
    .option('--json', '输出机器可读结果；执行仍需 --yes')
    .action(async (query, opts) => {
      const { execFile } = await import('child_process')
      const { promisify } = await import('util')
      const execFileAsync = promisify(execFile)
    const pkgRoot = resolvePackageRoot()
      const script = join(pkgRoot, 'scripts', 'semantic_search.py')
      const topK = parseCliInteger(opts.topK, 'top-k', 1, 100, opts.json)
      // 没传就**不转发**（默认值只在 Python 侧定义一处）：commander 对未提供的选项给 undefined，
      // 直接 parseCliInteger 会被自己的校验判成非法参数 —— 实测就是这么红的。
      const rerankPool = opts.rerankPool
        ? parseCliInteger(opts.rerankPool, 'rerank-pool', 5, 500, opts.json) : null
      requireCliChoice(opts.line, ['wiki', 'chat', 'all'], 'line', opts.json)
      // `--phrase` 走的是**纯本地**那条路（FTS5）：不出境、不花钱，所以它既不需要向量 key，
      // 也不需要确认门。把它当成"向量搜索的降级"会让人以为它也花钱、也发数据。
      const phrase = opts.phrase === true
      // 下面这些旗标只属于**向量检索**那条路；`--phrase`（FTS5 原样定位）一个都用不上。
      // 以前它们会被原样转发，然后在 Python 的 phrase 分支里被**静默忽略** —— 用户以为自己在调参，
      // 实际上什么都没发生。这类"接受但不生效"的开关比报错更贵：它会让人把默认行为当成调过的结果。
      if (phrase) {
        const irrelevant: string[] = []
        if (opts.rerank === false) irrelevant.push('--no-rerank')
        if (opts.hybrid === false) irrelevant.push('--no-hybrid')
        if (rerankPool != null) irrelevant.push('--rerank-pool')
        if (opts.dedup === false) irrelevant.push('--no-dedup')
        if (opts.withText) irrelevant.push('--with-text')
        if (opts.fetchMissing) irrelevant.push('--fetch-missing')
        if (opts.mmr) irrelevant.push('--mmr')
        if (irrelevant.length) {
          const error = `--phrase 只做原样定位，不接受 ${irrelevant.join('、')}（它们只对向量检索有意义）`
          if (opts.json) console.log(JSON.stringify({ success: false, code: 'INVALID_ARGUMENT', error }))
          else console.log(chalk.red(error))
          process.exit(1)
        }
      }
      const preview = {
        success: true,
        dryRun: true,
        action: 'semantic-search.query',
        phrase,
        topK,
        line: opts.line,
        noRerank: opts.rerank === false,
        noHybrid: opts.hybrid === false,
        rerankPool,
        noDedup: opts.dedup === false,
        withText: opts.withText || null,
        fetchMissing: opts.fetchMissing || null,
        mmr: opts.mmr === true,
        from: opts.from || null,
        readsLocalIndex: true,
        mayUseCloudEmbedding: !phrase,
      }
      if (opts.dryRun) {
        if (opts.json) console.log(JSON.stringify(preview))
        else console.log(chalk.cyan(phrase
          ? '预览：原样短语定位 —— 只读本地短语索引，不联网、不花钱。'
          : '预览：将读取本地语义索引，并可能把查询发送到已配置的向量服务。'))
        return
      }
      if (!phrase && !opts.yes) {
        if (opts.json) {
          console.log(JSON.stringify({ ...preview, success: false, dryRun: false, code: 'CONFIRMATION_REQUIRED' }))
          process.exit(1)
        }
        const { confirmed } = await inquirer.prompt([{
          type: 'confirm',
          name: 'confirmed',
          message: '确认执行搜索吗？查询可能发送到已配置的云端向量服务。',
          default: false,
        }])
        if (!confirmed) {
          console.log(chalk.gray('已取消'))
          return
        }
      }
      // `--no-rerank` 是**旗标**（不是密钥）⇒ 可以走 argv；查询本身仍然只走 env（见 `privacy-paths` 那条规矩）。
      // 接这条通道之前，`OPERATIONS.md` 一直在教用户敲 `search --no-rerank`，而 CLI 会答 `unknown option`
      // —— 同一份文档里 `--line` 是通的，所以它看起来像"能用的旗标"（2026-10-11 由文档命令面那道检查发现）。
      const args: string[] = [script, 'search', '--top-k', String(topK), '--line', opts.line,
        ...(phrase ? ['--phrase'] : []),
        ...(opts.rerank === false ? ['--no-rerank'] : []),
        ...(opts.hybrid === false ? ['--no-hybrid'] : []),
        ...(opts.from ? ['--from', opts.from] : []),
        ...(rerankPool ? ['--rerank-pool', String(rerankPool)] : []),
        ...(opts.dedup === false ? ['--no-dedup'] : []),
        ...(opts.withText ? ['--with-text', opts.withText === true ? '4000' : String(opts.withText)] : []),
        ...(opts.fetchMissing ? ['--fetch-missing',
          opts.fetchMissing === true ? '3' : String(opts.fetchMissing)] : []),
        ...(opts.mmr ? ['--mmr'] : [])]
      try {
        const { stdout } = await execFileAsync(getPythonCommand(), args, {
          timeout: 60_000, maxBuffer: 10 * 1024 * 1024,
          env: {
            ...pythonProcessEnv(opts.apiKey, 'DASHSCOPE_API_KEY'),
            WEFLOW_SEARCH_QUERY: query,
          },
        })
        console.log(stdout)
      } catch (e: any) {
        console.error(chalk.red(`\n✗ ${safeSubprocessError(e, '搜索失败')}`))
        process.exit(1)
      }
    })

  program
    .command('search-index')
    .description('构建语义搜索索引')
    .option('--full', '全量重建')
    .option('--phrase', '只建**精确短语索引**（本地 FTS5/trigram，不调用向量服务、不花钱、不出境）')
    .option('--api-key <key>', 'DashScope embedding API key')
    .option('--days <n>', '聊天记录收最近多少天（默认 90）')
    .option('--article-days <n>', '日报文章收最近多少个日期目录（默认 30）')
    .option('--include-imports', '把 weflow-cli import qchat 导入的 QQ 会话也收进索引（聊天半边）')
    .option('--pdf-chunks <n>', '每个 PDF 最多收多少块（默认 0=不限）；文字来自 output/pdf-text')
  .option('--article-chunk-chars <n>', '文章按多少字符切块后分别嵌入（默认 0=不切，整篇进向量）')
  .option('--article-chunk-overlap <n>', '切块重叠字符数（默认 60）')
    .option('--no-pdf', '不收 PDF 文字（默认收）')
    .option('--dry-run', '仅预览，不读取数据库、调用网络或写入索引')
    .option('--yes', '确认构建或重建索引')
    .option('--json', '输出 JSON 格式')
    .action(async (opts) => {
      // `--phrase`：短语索引那条路完全不碰向量服务（也不碰聊天库——它从语义索引的 meta.json
      // 派生），所以它不走窗口参数、不需要确认门，也不校验 key。混进下面那条路会让用户以为
      // "建个本地的检索也要花 vector 的钱"。
      if (opts.phrase) {
        const phrasePreview = {
          success: true, dryRun: true, action: 'search-index.build-phrase',
          readsLocalData: true, usesCloudEmbedding: false, rebuildsPhraseIndex: true,
        }
        if (opts.dryRun) {
          if (opts.json) console.log(JSON.stringify(phrasePreview))
          else console.log(chalk.cyan('短语索引预览：全量重建本地 FTS5 索引（含两条线），不联网、不花钱。'))
          return
        }
        const { execFile } = await import('child_process')
        const { promisify } = await import('util')
        const execFileAsync = promisify(execFile)
        const pkgRoot = resolvePackageRoot()
        const script = join(pkgRoot, 'scripts', 'semantic_search.py')
        try {
          const { stdout } = await execFileAsync(getPythonCommand(),
            [script, 'phrase-build', '--line', 'all'],
            { timeout: 600_000, maxBuffer: 10 * 1024 * 1024, env: pythonProcessEnv() })
          console.log(opts.json ? stdout.trim() : stdout)
        } catch (e: any) {
          console.error(chalk.red(`\n✗ ${safeSubprocessError(e, '建短语索引失败')}`))
          process.exit(1)
        }
        return
      }
      // 窗口的**运行值由这里说了算**：默认值 + 校验 + 透传都在这一处，预览报的就是真跑的那些
      // （脚本文档里另有自己的默认值，只供手动直接跑脚本时用；CLI 这条路永远显式传参，
      // 所以两边万一漂了也不会影响实际行为）。
      // 上限 36500 天≈100 年：不设上限的后果是"给个 1e9 就把遍历变成一次全库穿透"。
      const chatDays = opts.days === undefined ? 90 : parseCliInteger(opts.days, 'days', 1, 36_500, opts.json)
      const articleDays = opts.articleDays === undefined
        ? 30 : parseCliInteger(opts.articleDays, 'article-days', 1, 36_500, opts.json)
      const windowText = `聊天最近 ${chatDays} 天、日报最近 ${articleDays} 个日期目录`
      const preview = {
        success: true,
        dryRun: true,
        action: 'search-index.build',
        mode: opts.full ? 'full' : 'incremental',
        chatDays,
        articleDays,
        includeImports: !!opts.includeImports,
        readsLocalData: true,
        usesCloudEmbedding: true,
        replacesExistingIndex: !!opts.full,
      }
      if (opts.dryRun) {
        if (opts.json) console.log(JSON.stringify(preview))
        else console.log(chalk.cyan(`语义索引预览：${opts.full ? '全量重建' : '增量构建'}；`
          + `窗口＝${windowText}（要改：--days / --article-days），将读取本地数据并调用向量服务`))
        return
      }
      if (!opts.yes) {
        if (opts.json) {
          console.log(JSON.stringify({ ...preview, success: false, dryRun: false, code: 'CONFIRMATION_REQUIRED' }))
          process.exit(1)
        }
        const { confirmed } = await inquirer.prompt([{
          type: 'confirm',
          name: 'confirmed',
          // 窗口是**代价的一部分**：天数越多，发给向量服务的文本越多。所以确认语里要写出来，
          // 而不是只说"本地文本将发送"。
          message: `确认${opts.full ? '全量重建' : '增量构建'}语义索引（${windowText}）？`
            + '这些文本将发送到已配置的向量服务。',
          default: false,
        }])
        if (!confirmed) {
          console.log(chalk.gray('已取消'))
          return
        }
      }
      const { execFile } = await import('child_process')
      const { promisify } = await import('util')
      const execFileAsync = promisify(execFile)
    const pkgRoot = resolvePackageRoot()
      const script = join(pkgRoot, 'scripts', 'semantic_search.py')
      const args: string[] = [script, 'build', '--days', String(chatDays),
                              '--article-days', String(articleDays),
                    ...(opts.pdfChunks ? ['--pdf-chunks', String(opts.pdfChunks)] : []),
                    ...(opts.noPdf ? ['--no-pdf'] : []),
                    ...(opts.articleChunkChars !== undefined
                      ? ['--article-chunk-chars', String(parseCliInteger(opts.articleChunkChars, 'article-chunk-chars', 1, 4000, opts.json))]
                      : []),
                    ...(opts.articleChunkOverlap !== undefined
                      ? ['--article-chunk-overlap', String(parseCliInteger(opts.articleChunkOverlap, 'article-chunk-overlap', 0, 1000, opts.json))]
                      : [])]
      if (opts.full) args.push('--full')
      if (opts.includeImports) args.push('--include-imports')
      try {
        const { stdout } = await execFileAsync(getPythonCommand(), args, {
          // 30 分钟：全量重建实测要跑二十分钟以上（16k 条 / 1500+ 批），而这里原来给的是 5 分钟 --
          // 那个值让 `--full` 在真实索引上**从来没跑完过**（超时被杀；且脚本改成了边嵌边落盘之前，
          // 中途被杀等于连已经嵌好的那部分也一起丢）。
          timeout: 1_800_000, maxBuffer: 10 * 1024 * 1024,
          env: pythonProcessEnv(opts.apiKey, 'DASHSCOPE_API_KEY'),
        })
        if (opts.json) console.log(stdout.trim())
        else console.log(stdout)
      } catch (e: any) {
        console.error(chalk.red(`\n✗ ${safeSubprocessError(e)}`))
        process.exit(1)
      }
    })

  // chat
  program
    .command('chat')
    .description('RAG 智能助手 — 基于聊天记录和公众号的对话式问答')
    .argument('[question]', '要问的问题（不传则进入交互模式）')
    .option('--top-k <n>', '检索数量', '10')
    .option('--line <line>', 'wiki=文章/文章概念(默认) / chat=聊天记录 / all=两条都搜', 'wiki')
    .option('--talker <name>', '限定联系人/群聊')
    .option('--api-key <key>', 'AI API key')
    .option('--dry-run', '仅预览，不读取知识库或调用 AI')
    .option('--yes', '确认读取本地知识并发送筛选后的上下文到 AI')
    .option('--json', 'JSON 输出；单次执行仍需 --yes，交互模式不可由机器启动')
    .action(async (question, opts) => {
      const { execFile, spawn } = await import('child_process')
      const { promisify } = await import('util')
      const execFileAsync = promisify(execFile)
    const pkgRoot = resolvePackageRoot()
      const script = join(pkgRoot, 'scripts', 'rag_chat.py')
      const topK = parseCliInteger(opts.topK, 'top-k', 1, 100, opts.json)
      requireCliChoice(opts.line, ['wiki', 'chat', 'all'], 'line', opts.json)
      const preview = {
        success: true,
        dryRun: true,
        action: 'rag-chat.query',
        topK,
        line: opts.line,
        interactiveRequired: !question,
        readsLocalKnowledge: true,
        usesCloudEmbedding: true,
        usesAi: true,
        sendsSelectedContextToAi: true,
        conversationRestricted: Boolean(opts.talker),
      }
      if (opts.dryRun) {
        if (opts.json) console.log(JSON.stringify(preview))
        else console.log(chalk.cyan(`预览：将读取本地知识并调用 AI${question ? '' : '；未提供问题时会进入人工交互模式'}。`))
        return
      }
      if (!question && opts.json) {
        console.log(JSON.stringify({ ...preview, success: false, dryRun: false, code: 'INTERACTIVE_REQUIRED' }))
        process.exit(1)
      }
      if (!opts.yes) {
        if (opts.json) {
          console.log(JSON.stringify({ ...preview, success: false, dryRun: false, code: 'CONFIRMATION_REQUIRED' }))
          process.exit(1)
        }
        const { confirmed } = await inquirer.prompt([{
          type: 'confirm',
          name: 'confirmed',
          message: '确认读取本地知识并将筛选后的上下文发送到 AI 服务吗？',
          default: false,
        }])
        if (!confirmed) {
          console.log(chalk.gray('已取消'))
          return
        }
      }
      const args: string[] = [script]
      if (question) {
        args.push('--top-k', String(topK), '--line', opts.line)
        if (opts.json) args.push('--json')
        try {
          const { stdout } = await execFileAsync(getPythonCommand(), args, {
            timeout: 120_000, maxBuffer: 10 * 1024 * 1024,
            env: {
              ...pythonProcessEnv(opts.apiKey),
              WEFLOW_RAG_QUESTION: question,
              ...(opts.talker ? { WEFLOW_RAG_TALKER: opts.talker } : {}),
            },
          })
          console.log(stdout)
        } catch (e: any) {
          console.error(chalk.red(`\n✗ ${safeSubprocessError(e, '对话失败')}`))
          process.exit(1)
        }
      } else {
        // 交互模式：使用 spawn 保持终端交互
        args.push('--interactive', '--top-k', String(topK), '--line', opts.line)
        const child = spawn(getPythonCommand(), args, {
          windowsHide: true,
          stdio: 'inherit',
          env: {
            ...pythonProcessEnv(opts.apiKey),
            ...(opts.talker ? { WEFLOW_RAG_TALKER: opts.talker } : {}),
          },
        })
        await new Promise<void>((resolve) => child.on('exit', (code) => {
          if (code !== 0) process.exit(code || 1);
          resolve();
        }))
      }
    })

  // Helper: run a Python script
  async function runPython(script: string, args: string[], apiKey?: string): Promise<void> {
    const { execFile } = await import('child_process')
    const { promisify } = await import('util')
    const execFileAsync = promisify(execFile)
    const pkgRoot = resolvePackageRoot()
    const pyArgs = [join(pkgRoot, script), ...args]
    try {
      const { stdout } = await execFileAsync(getPythonCommand(), pyArgs, {
        timeout: 120_000, maxBuffer: 5 * 1024 * 1024,
        env: pythonProcessEnv(apiKey),
      })
      console.log(stdout)
    } catch (e: any) {
      console.error(chalk.red(`\n✗ ${safeSubprocessError(e)}`))
      process.exit(1)
    }
  }

  // annual-report
  program
    .command('annual-report')
    .description('生成年度数字生活报告')
    .argument('[year]', '年份（默认今年）')
    .option('--share', '分享模式（紧凑卡片）')
    .option('--api-key <key>', 'DeepSeek API key')
    .option('--skip-ai', '跳过 AI 总结')
    .option('--output <file>', '输出文件')
    .option('--dry-run', '仅预览，不读取数据、调用 AI 或写入报告')
    .option('--yes', '确认生成年度报告')
    .option('--json', '输出机器可读结果，不返回本地路径')
    .action(async (year, opts) => {
      const reportYear = parseCliInteger(year || String(new Date().getFullYear()), 'year', 1970, 2100, opts.json)
      const preview = {
        success: true,
        dryRun: true,
        action: 'annual-report.generate',
        year: reportYear,
        shareMode: !!opts.share,
        aiEnabled: !opts.skipAi,
        readsLocalData: true,
      }
      if (opts.dryRun) {
        if (opts.json) console.log(JSON.stringify(preview))
        else console.log(chalk.cyan(`${reportYear} 年度报告预览：AI ${opts.skipAi ? '关闭' : '开启'}`))
        return
      }
      if (!opts.yes) {
        if (opts.json) {
          console.log(JSON.stringify({ ...preview, success: false, dryRun: false, code: 'CONFIRMATION_REQUIRED' }))
          process.exit(1)
        }
        const { confirmed } = await inquirer.prompt([{
          type: 'confirm',
          name: 'confirmed',
          message: `确认生成 ${reportYear} 年度报告？${opts.skipAi ? '仅执行本地统计。' : '统计摘要可能发送到已配置的 AI 服务。'}`,
          default: false,
        }])
        if (!confirmed) {
          console.log(chalk.gray('已取消'))
          return
        }
      }
      const a = [String(reportYear)]
      if (opts.share) a.push('--share')
      if (opts.skipAi) a.push('--skip-ai')
      if (opts.output) a.push('--output', opts.output)
      if (opts.json) {
        const { execFile } = await import('child_process')
        const { promisify } = await import('util')
        try {
          await promisify(execFile)(getPythonCommand(), [join(resolvePackageRoot(), 'scripts/annual_report.py'), ...a], {
            timeout: 120_000,
            maxBuffer: 5 * 1024 * 1024,
            env: pythonProcessEnv(opts.apiKey),
          })
          console.log(JSON.stringify({ success: true, action: 'annual-report.generate', year: reportYear }))
        } catch (error) {
          console.log(JSON.stringify({ success: false, code: 'ANNUAL_REPORT_FAILED', error: safeSubprocessError(error) }))
          process.exit(1)
        }
      } else {
        await runPython('scripts/annual_report.py', a, opts.apiKey)
      }
    })

  // decide —— 本机判断层。一个 state + 一批类型化问题，一次调用。
  // state 由调用方给，命令自己**不读任何本地数据**；但它是出境调用，所以照 awaiting/search
  // 的规矩：--dry-run 只校验、--yes 才真跑。这一版**不暴露成 MCP 工具**——那会变成
  // 远端 MCP 客户端能驱动本机往第三方发任意文本，属于要单独决策的出境面。
  program
    .command('decide')
    .description('本机判断层：一个 state + 一批类型化问题，一次调用返回带概率的答案')
    .option('--request <file>', '请求 JSON 的路径（含 state 与 questions）')
    .option('--over <glob>', '批量模式：对匹配到的每个文件问 --ask 里的每个问题（可重复）',
            (value: string, previous: string[]) => previous.concat([value]), [] as string[])
    .option('--ask <text>', '批量模式下的一个是非题，逐文件展开（可重复）',
            (value: string, previous: string[]) => previous.concat([value]), [] as string[])
    .option('--max-chars <n>', '批量模式下每个文件喂多少字符（默认 1500；它决定上限）', '1500')
    .option('--limit <n>', '批量模式最多取多少个文件（默认 50）', '50')
    .option('--model <name>', '模型别名，默认 jev-latest')
    .option('--dry-run', '只校验请求并回显形状，不调用决策模型')
    .option('--yes', '确认把 state 发送到已配置的决策模型服务')
    .option('--json', '输出机器可读结果（本命令的输出本来就是 JSON）')
    .action(async (opts) => {
      const { execFile } = await import('child_process')
      const { promisify } = await import('util')
      const { readFileSync } = await import('fs')
      const execFileAsync = promisify(execFile)
      const pkgRoot = resolvePackageRoot()
      const decideScript = join(pkgRoot, 'scripts', 'decide.py')

      // 预览里要报"这批几个问题"，所以在这里读一眼；**校验仍然只由脚本做**，
      // 免得两处校验逻辑各说各话。
      // 两种输入方式：--request 一个文件、或 --over 批量展开。脚本自己会拒掉
      // 两个都没给的情况，所以这里不做重复校验。
      const batch = Array.isArray(opts.over) && opts.over.length > 0
      let questionCount: number | null = null
      if (batch) {
        questionCount = opts.over.length * opts.ask.length || null
      } else if (opts.request) {
        try {
          const parsed = JSON.parse(readFileSync(opts.request, 'utf8'))
          if (parsed && typeof parsed === 'object' && parsed.questions
              && typeof parsed.questions === 'object') {
            questionCount = Object.keys(parsed.questions).length
          }
        } catch {
          // 读不到或不是 JSON：交给脚本去报一个准确得多的错误。
        }
      }
      const limit = parseCliInteger(opts.limit, 'limit', 1, 500, opts.json)
      const maxChars = parseCliInteger(opts.maxChars, 'max-chars', 1, 100000, opts.json)

      const args = [decideScript,
                    ...(batch
                      ? [...opts.over.flatMap((g: string) => ['--over', g]),
                         ...opts.ask.flatMap((a: string) => ['--ask', a]),
                         '--max-chars', String(maxChars), '--limit', String(limit)]
                      : ['--request', opts.request]),
                    ...(opts.model ? ['--model', opts.model] : [])]
      if (opts.dryRun) {
        args.push('--dry-run')
      } else if (!opts.yes) {
        const preview = {
          success: false, dryRun: false, action: 'decide',
          code: 'CONFIRMATION_REQUIRED',
          questionCount, readsLocalData: batch, invokesAI: true,
        }
        if (opts.json) {
          console.log(JSON.stringify(preview))
          process.exit(1)
        }
        const { confirmed } = await inquirer.prompt([{
          type: 'confirm',
          name: 'confirmed',
          message: `确认把请求里的 state 发送到已配置的决策模型服务吗？`
            + (questionCount === null ? '' : `（${questionCount} 个问题）`),
          default: false,
        }])
        if (!confirmed) {
          console.log(chalk.gray('已取消'))
          return
        }
      }

      try {
        const { stdout } = await execFileAsync(getPythonCommand(), args, {
          timeout: 120_000, maxBuffer: 10 * 1024 * 1024,
          env: pythonProcessEnv(),
        })
        process.stdout.write(stdout)
      } catch (error) {
        const payload = (error as { stdout?: string }).stdout
        if (payload && payload.trim()) {
          // 脚本自己已经给出了结构化的失败，原样透传比自己编一个更有用。
          process.stdout.write(payload)
        } else {
          console.log(JSON.stringify({ success: false, code: 'DECIDE_FAILED',
            action: 'decide', error: safeSubprocessError(error) }))
        }
        process.exit(1)
      }
    })

  // awaiting —— 谁在等我回话。读本地聊天并把正文发给决策模型，所以照 search 的规矩：
  // --dry-run 预览、--yes 才真跑。它**不写任何本地数据**，但仍是一次正文出境，
  // 而聊天正文比日报的文章正文敏感一档。
  program
    .command('awaiting')
    .description('谁在等我回话：逐会话判断有没有欠下的回复（读取聊天正文并调用决策模型）')
    .option('--days <n>', '只看最近多少天有动静的会话', '14')
    .option('--limit <n>', '最多判多少个会话', '40')
    .option('--min-prob <p>', 'waiting 概率低于此值不算欠账', '0.5')
    .option('--dry-run', '仅预览会判哪些会话、要发多少字符，不调用决策模型')
    .option('--yes', '确认把聊天正文发送到已配置的决策模型服务')
    .option('--json', '输出机器可读结果；执行仍需 --yes')
    .action(async (opts) => {
      const { execFile } = await import('child_process')
      const { promisify } = await import('util')
      const execFileAsync = promisify(execFile)
      const pkgRoot = resolvePackageRoot()
      const script = join(pkgRoot, 'scripts', 'reply_debt.py')
      const days = parseCliInteger(opts.days, 'days', 1, 3650, opts.json)
      const limit = parseCliInteger(opts.limit, 'limit', 1, 500, opts.json)
      const args = [script, '--days', String(days), '--limit', String(limit),
                    '--min-prob', String(opts.minProb),
                    ...(opts.json ? ['--json'] : [])]

      if (opts.dryRun) {
        // 交给脚本自己报数：它才知道要发多少字符。这一步只读本地，零出境。
        args.push('--dry-run')
      } else if (!opts.yes) {
        const preview = {
          success: false, dryRun: false, action: 'reply-debt.scan',
          code: 'CONFIRMATION_REQUIRED', days, limit,
          readsLocalChat: true, invokesAI: true, writesNothing: true,
        }
        if (opts.json) {
          console.log(JSON.stringify(preview))
          process.exit(1)
        }
        const { confirmed } = await inquirer.prompt([{
          type: 'confirm',
          name: 'confirmed',
          message: '确认把最近这些会话的聊天正文发送到已配置的决策模型服务吗？',
          default: false,
        }])
        if (!confirmed) {
          console.log(chalk.gray('已取消'))
          return
        }
      }

      try {
        const { stdout } = await execFileAsync(getPythonCommand(), args, {
          timeout: 600_000, maxBuffer: 50 * 1024 * 1024,
          env: pythonProcessEnv(),
        })
        process.stdout.write(stdout)
      } catch (error) {
        if (opts.json) {
          console.log(JSON.stringify({ success: false, code: 'AWAITING_FAILED', action: 'reply-debt.scan', error: safeSubprocessError(error) }))
        } else {
          console.error(chalk.red(`\n✗ ${safeSubprocessError(error)}`))
        }
        process.exit(1)
      }
    })

  // draft：判断在前、起草在后、**绝不发送**
  program
    .command('draft <talker>')
    .description('帮我起草回复：先判断（意图/风险/该不该给实质），再起草候选 —— **默认只产出文本；给了 --pick N --send 才会替你发送**')
    .option('--count <n>', '要几条候选', '3')
    .option('--pick <n>', '选第几条（从 1 数）；不带 --send 时只把那条的完整原文打出来')
    .option('--send', '把选中的那条发出去 —— **必须同时给 --pick**（不允许"自己挑一条发"），仍需 --yes/--dry-run')
    .option('--rate-window <ms>', '发送速率窗口毫秒（与 send 同一份策略）', '60000')
    .option('--rate-max <n>', '窗口内最大发送条数', '10')
    .option('--gate-commitment', '承诺未兑现时也拒绝起草（默认只在提示词里约束）')
    .option('--dry-run', '仅预览会发多少字符给哪两个模型，不调用')
    .option('--yes', '确认把这段对话发送到判断模型与生成模型')
    .option('--json', '输出机器可读结果；执行仍需 --yes')
    .action(async (talker: string, opts) => {
      const { execFile } = await import('child_process')
      const { promisify } = await import('util')
      const execFileAsync = promisify(execFile)
      // **用法错误先报**，而且都在调模型之前报：`--send` 少了 `--pick` 是"你没说发哪条"，
      // `--pick 9` 而只有 3 条是"那条根本不存在" —— 两者都不该先问一遍"要不要把对话发给云端模型"、
      // 更不该先花掉模型调用再拒绝。
      const count = parseCliInteger(opts.count, 'count', 1, 5, opts.json)
      if (opts.send && opts.pick === undefined) {
        const message = '--send 必须同时给 --pick <序号>：先看候选，再点名要发哪一条'
        if (opts.json) console.log(JSON.stringify({ success: false, code: 'PICK_REQUIRED', error: message }))
        else console.log(chalk.red(`
❌ ${message}`))
        process.exit(1)
      }
      const pick = opts.pick === undefined ? 0 : parseCliInteger(opts.pick, 'pick', 1, count, opts.json)
      const pkgRoot = resolvePackageRoot()
      const script = join(pkgRoot, 'scripts', 'draft_reply.py')
      // **"确认过了"只用一个变量表示**（`--yes` 或交互回答"是"），参数在确认之后才拼。
      // 原来的写法是先拼参数、再问，于是**交互确认那条路是坏的**：答了"是"，`args` 里
      // 却从没补上 `--yes`，脚本照样拒绝（用户看到的是"我确认了它却说没确认"）。
      // 两者合成一个变量之后，这种漏传在结构上不可能再发生。
      let confirmed = !!opts.yes
      if (!opts.dryRun && !confirmed) {
        const preview = {
          success: false, dryRun: false, action: 'draft-reply',
          code: 'CONFIRMATION_REQUIRED', talker, count,
          readsLocalChat: true, invokesAI: true, writesNothing: true, sendsNothing: true,
        }
        if (opts.json) {
          console.log(JSON.stringify(preview))
          process.exit(1)
        }
        const answer = await inquirer.prompt([{
          type: 'confirm',
          name: 'confirmed',
          message: '确认把这段对话发送到判断模型与生成模型吗？（只会产出候选文本，不会替你发送）',
          default: false,
        }])
        confirmed = !!answer.confirmed
        if (!confirmed) {
          console.log(chalk.gray('已取消'))
          return
        }
      }
      // ---------------- 选中并（可选）发送 ----------------
      //
      // **只有给了 `--pick` 或 `--send` 才走这条分支**；不带它们的调用与以前逐字相同（原样透传脚本输出）。
      //
      // 这条分支存在的理由：起草那一半早就有了（判断 → 候选 → 排序），缺的是"人选定之后能真的发出去"。
      // 而它的**要点是这个 `--pick`**：发送必须由人点名"第几条"。少了它，就成了"模型起草三条、
      // 模型挑一条、模型发出去" —— 那正是本仓库划掉的那件事
      // （docs/EXTENDING.md：sending is structurally unreachable from a model-driven path）。
      if (opts.pick !== undefined || opts.send) {
        // **`--dry-run` 的语义是"零出境"**，而候选必须由模型产出来 —— 两者不可兼得：不起草就没有
        // 候选，"预览某一条会发什么"这件事本身不成立。所以这里只报"会发多少字符给哪两个模型"
        // （脚本的 dry-run 本来就报这个），并把话说清楚，而不是假装预览了一条。
        if (opts.dryRun) {
          try {
            const { stdout } = await execFileAsync(getPythonCommand(),
              [script, '--talker', String(talker), '--count', String(count), '--dry-run',
               ...(opts.json ? ['--json'] : [])],
              { timeout: 120_000, maxBuffer: 20 * 1024 * 1024, env: pythonProcessEnv() })
            process.stdout.write(stdout)
          } catch (error) {
            console.error(chalk.red(`\n✗ ${safeSubprocessError(error, '预览失败')}`))
            process.exit(1)
          }
          if (!opts.json) {
            console.log(chalk.gray('\n候选要由模型产出来，所以 --dry-run 下没有候选可挑。'
              + '要预览"发第几条"：先起草一次（会调用模型），再用 --pick N --send。\n'))
          }
          return
        }
        // `--pick`/`--send` 的用法错误在 action 开头就报过了（那一段全在调模型之前）
        // 内部一律用 `--json` 拿结构化结果（用户那侧的 `--json` 管的是最终输出，两回事）
        const pickArgs = [script, '--talker', String(talker), '--count', String(count), '--json',
                          ...(confirmed ? ['--yes'] : []),
                          ...(opts.gateCommitment ? ['--gate-commitment'] : [])]
        let drafts: Array<{ text: string }> = []
        try {
          const { stdout } = await execFileAsync(getPythonCommand(), pickArgs, {
            timeout: 300_000, maxBuffer: 50 * 1024 * 1024, env: pythonProcessEnv(),
          })
          const parsed = JSON.parse(stdout)
          if (parsed.gate === 'refused') {
            // **不起草就不发**：那道闸（涉钱/风险高）拒绝时压根没有候选，这里也不能凭空发点什么
            const message = `这次不起草：${parsed.reason || '判断层拒绝了'}`
            if (opts.json) console.log(JSON.stringify({ success: false, code: 'DRAFT_REFUSED', error: message, advice: parsed.advice || [] }))
            else {
              console.log(chalk.yellow(`\n${message}`))
              for (const item of parsed.advice || []) console.log(chalk.gray(`  · ${item}`))
            }
            process.exit(1)
          }
          drafts = parsed.drafts || []
        } catch (error) {
          const message = safeSubprocessError(error, '起草失败')
          if (opts.json) console.log(JSON.stringify({ success: false, code: 'DRAFT_FAILED', error: message }))
          else console.error(chalk.red(`\n✗ ${message}`))
          process.exit(1)
        }
        const chosen = drafts[pick - 1]
        if (!chosen) {
          const message = `没有第 ${pick} 条候选（这次只有 ${drafts.length} 条）`
          if (opts.json) console.log(JSON.stringify({ success: false, code: 'PICK_OUT_OF_RANGE', error: message }))
          else console.log(chalk.red(`\n❌ ${message}`))
          process.exit(1)
        }
        if (!opts.send) {
          if (opts.json) console.log(JSON.stringify({ success: true, action: 'draft', sent: false, pick, text: chosen.text }))
          else console.log(`第 ${pick} 条：\n${chosen.text}\n\n${chalk.gray('（没有发送任何东西；要发加 --send）')}`)
          return
        }

        // 发送这一半走**与 `send` 命令完全相同的那份策略**（黑名单 → 白名单 → 限速 → 审计）
        let wxid: string
        try {
          wxid = await resolveTalker(String(talker), !!opts.json, !!opts.json)
        } catch (error: any) {
          if (opts.json) console.log(JSON.stringify({ success: false, code: 'TALKER_RESOLUTION_FAILED', error: error.message }))
          else console.log(chalk.red(`\n❌ ${error.message}`))
          process.exit(1)
        }
        let displayName = whitelistService.lookupName(wxid)
        if (displayName === wxid) {
          try {
            const sessions = await chatService.listSessions(undefined, 200)
            const match = sessions.find(s => s.username === wxid)
            if (match?.displayName) displayName = match.displayName
          } catch { /* 拿不到名字就退回 wxid */ }
        }
        const policy = parseOutboundPolicy(Number(opts.rateWindow), Number(opts.rateMax))
        if ('code' in policy) {
          if (opts.json) console.log(JSON.stringify({ success: false, code: policy.code, error: policy.error }))
          else console.log(chalk.red(`\n❌ ${policy.error}`))
          process.exit(1)
        }
        const attempt = {
          wxid, displayName, kind: 'text' as const,
          preview: chosen.text.slice(0, 80) + (chosen.text.length > 80 ? '...' : ''),
          text: chosen.text,
        }
        const decision = authorizeOutbound(attempt, policy)
        if (!decision.ok) {
          const { refusal } = decision
          if (opts.json) {
            // 这里**还没有** sendPreview（它在闸门通过之后才建），所以逐字段写
            console.log(JSON.stringify({ success: false, code: refusal.code, error: refusal.error,
              ...(refusal.rateLimit ? { rateLimit: refusal.rateLimit } : {}) }))
          } else {
            console.log(chalk.red(`\n❌ ${refusal.error}`))
            if (refusal.code === 'TARGET_NOT_ALLOWED') console.log(chalk.gray(`  先运行: weflow-cli whitelist add ${talker}\n`))
            if (refusal.code === 'TARGET_BLOCKED') console.log(chalk.gray('  这个人在黑名单里，任何一条命令行都不会发给他\n'))
            if (refusal.rateLimit) console.log(chalk.gray(`  最近 ${refusal.rateLimit.windowMs / 1000}s 内已发 ${refusal.rateLimit.count} 条\n`))
          }
          process.exit(1)
        }
        const sendPreview = { success: true, action: 'draft-send', target: { wxid, displayName },
                              pick, text: chosen.text, rateLimit: decision.rate }
        // 两段式在这里：不给 `--yes` 时，JSON 模式回 `CONFIRMATION_REQUIRED`（**带着要发的原文**），
        // 交互模式则问一句"确定把第 N 条发给 X？"。`--dry-run` 那条路在上面的分支入口就返回了
        // （它意味着零出境，与"必须由模型产出候选"不可兼得），所以这里没有第三个预览分支。
        if (opts.json && !opts.yes) {
          console.log(JSON.stringify({ ...sendPreview, success: false, code: 'CONFIRMATION_REQUIRED', error: '使用 --yes 确认发送' }))
          process.exit(1)
        }
        if (!opts.yes) {
          const answer = await inquirer.prompt([{
            type: 'confirm', name: 'send', default: false,
            message: `确定把第 ${pick} 条发给 ${displayName}？`,
          }])
          if (!answer.send) {
            console.log(chalk.gray('已取消，没有发送'))
            return
          }
        }
        const sent = await performOutbound(attempt)
        if (sent.success) {
          if (opts.json) console.log(JSON.stringify(sendPreview))
          else console.log(chalk.green('✓ 发送成功'))
          return
        }
        if (opts.json) console.log(JSON.stringify({ ...sendPreview, success: false, code: 'SEND_FAILED', error: sent.error }))
        else console.log(chalk.red(`✗ 发送失败 — ${sent.error}`))
        process.exit(1)
      }

      const args = [script, '--talker', String(talker), '--count', String(count),
                    // 脚本自己有第二道闸门（`--yes` 才真的把对话发出去），所以要透传
                    ...(confirmed ? ['--yes'] : []),
                    ...(opts.gateCommitment ? ['--gate-commitment'] : []),
                    ...(opts.json ? ['--json'] : []),
                    // dry-run 交给脚本自己报数（它才知道这段对话有多少字符），这一步只读本地、零出境
                    ...(opts.dryRun ? ['--dry-run'] : [])]

      try {
        const { stdout } = await execFileAsync(getPythonCommand(), args, {
          timeout: 300_000, maxBuffer: 50 * 1024 * 1024,
          env: pythonProcessEnv(),
        })
        process.stdout.write(stdout)
      } catch (error) {
        if (opts.json) {
          console.log(JSON.stringify({ success: false, code: 'DRAFT_FAILED', action: 'draft-reply', error: safeSubprocessError(error) }))
        } else {
          console.error(chalk.red(`\n✗ ${safeSubprocessError(error)}`))
        }
        process.exit(1)
      }
    })

  // wiki graph：把概念图谱导成一张**自包含**的 3D 页面（全本地：只读 Vault、不联网、不调用模型）
  //
  // 自包含是硬要求，不是顺手：页面用 `file://` 双击打开，那时 `fetch` 会被 CORS 挡死，
  // 所以库、数据、坐标全部内联进去 —— 也因此三个库随 npm 包发（见 resources/js/graph3d/NOTICE.txt）。
  // 布局（250 tick 实测 55 秒）在构建期用 Node 算完并缓存，打开页面即用。
  program.commands.find(c => c.name() === 'wiki')?.addCommand(
    new Command('graph')
      .description('把概念图谱导成一张自包含的图谱页面（只读本地、不联网；生成的 HTML 双击就能逛）。--flat 出 2D 版')
      .option('--vault <dir>', 'Vault 根目录（默认 output/wechat-vault）')
      .option('-o, --out <file>', '页面写到哪（默认 output/knowledge-graph-3d.html）')
      .option('--ticks <n>', '力导向迭代次数（默认 250，越多越舒展也越慢）')
      .option('--cache <dir>', '布局缓存目录（派生数据；测试/多份图分开放时用）')
      .option('--flat', '2D 版：平面图（更像 Obsidian 那种），canvas 渲染，输出默认 knowledge-graph-2d.html')
      .option('--min-degree <n>', '只画在原图里连接数 ≥N 的概念（去掉细枝看骨架；0 = 全画）')
      .option('--line <which>', '只画一条线：all / wiki / chat')
      .option('--dry-run', '只报概念与链接数：不写文件、也不算布局（本地，零改动）')
      .option('--open', '生成后用默认浏览器打开它')
      .option('--json', '输出机器可读结果')
      .action(async (opts) => {
        const { execFile } = await import('child_process')
        const { promisify } = await import('util')
        const execFileAsync = promisify(execFile)
        // 2D 与 3D 是**两个入口脚本**：图怎么建共用（graph_2d 直接 import graph_3d），
        // 换的是布局维度与渲染器 —— 两套渲染器塞一个文件就没人看得完了。
        const script = join(resolvePackageRoot(), 'scripts', opts.flat ? 'graph_2d.py' : 'graph_3d.py')
        const ticks = opts.ticks === undefined ? undefined : parseCliInteger(opts.ticks, 'ticks', 1, 100000, !!opts.json)
        // `--json` 一律要：CLI 要拿到 out 路径与计数，才决定怎么印。开关只决定**给谁看**。
        const minDegree = opts.minDegree === undefined
          ? undefined : parseCliInteger(opts.minDegree, 'min-degree', 0, 100000, !!opts.json)
        const args = [script,
                      ...(opts.vault ? ['--vault', opts.vault] : []),
                      ...(opts.out ? ['--out', opts.out] : []),
                      ...(opts.cache ? ['--cache', opts.cache] : []),
                      ...(ticks === undefined ? [] : ['--ticks', String(ticks)]),
                      ...(minDegree === undefined || minDegree === 0 ? [] : ['--min-degree', String(minDegree)]),
                      ...(opts.line ? ['--line', opts.line] : []),
                      ...(opts.dryRun ? ['--dry-run'] : []),
                      '--json']
        try {
          const { stdout } = await execFileAsync(getPythonCommand(), args, {
            timeout: 900_000, maxBuffer: 64 * 1024 * 1024, env: pythonProcessEnv(),
          })
          const body = JSON.parse(stdout.slice(stdout.indexOf('{')))
          if (opts.json) {
            console.log(JSON.stringify(body))
          } else if (body.dryRun) {
            console.log(`概念 ${body.nodes} 个、链接 ${body.links} 条（--dry-run：没有写文件）`)
          } else {
            console.log(chalk.green(`✓ 已生成 ${body.out}`))
            console.log(chalk.gray(`  概念 ${body.nodes} / 链接 ${body.links} / ${body.mb} MB · ${opts.flat ? '2D' : '3D'} · 双击就能逛，不需要服务器`))
          }
          if (!opts.dryRun && opts.open && body.out) await openLocalUrl(body.out)
        } catch (error) {
          if (opts.json) {
            console.log(JSON.stringify({ success: false, code: 'GRAPH_FAILED', action: 'graph-3d', error: safeSubprocessError(error) }))
          } else {
            console.error(chalk.red(`\n✗ ${safeSubprocessError(error)}`))
          }
          process.exit(1)
        }
      })
  )

  // wiki lint：知识库体检（全本地：不联网、不调用模型）
  program.commands.find(c => c.name() === 'wiki')?.addCommand(
    new Command('lint')
      .description('知识库体检：断链、孤儿、空页、同名（本地，不联网）')
      // 不给默认值：不传 `--dir` 时体检脚本自己的默认（清单里的**全部线**）。
      // 这里曾经默认只给文章线，而脚本默认两条线都体检 ⇒"半开半合"：命令行跑出来
      // 与脚本跑出来口径不同，而两边都不报错。
      .option('--dir <dirs...>', '概念页目录（可重复；不传则体检清单里的全部线）')
      .option('--json', '输出机器可读结果')
      .action(async (opts) => {
        const { execFile } = await import('child_process')
        const { promisify } = await import('util')
        const execFileAsync = promisify(execFile)
        const script = join(resolvePackageRoot(), 'scripts', 'wiki_lint.py')
        const dirs = Array.isArray(opts.dir) ? opts.dir : (opts.dir ? [opts.dir] : [])
        const args = [script, ...dirs.flatMap((d: string) => ['--dir', String(d)]),
          ...(opts.json ? ['--json'] : [])]
        // 超时给足：实测 4.8 万页冷缓存要 101.7 秒（2026-11-11，真实 vault），
        // 原来的 120 秒只够"刚好跑完"，再大一点或磁盘慢一点就会变成"执行超时或被终止"——
        // 而用户看到的那句话完全没提示"是页面太多"，只会以为功能坏了。
        const LINT_TIMEOUT_MS = 600_000
        try {
          const { stdout } = await execFileAsync(getPythonCommand(), args, {
            timeout: LINT_TIMEOUT_MS, maxBuffer: 20 * 1024 * 1024, env: pythonProcessEnv(),
          })
          process.stdout.write(stdout)
        } catch (error: any) {
          const timedOut = error?.killed === true || error?.signal === 'SIGTERM'
          const hint = timedOut
            ? `\n  可能是页面太多（超过 ${Math.round(LINT_TIMEOUT_MS / 1000)} 秒）。`
              + '先用 --dir 缩小到某一个目录再试；\n  或直接跑脚本看进度：python scripts/wiki_lint.py --dir <目录>'
            : ''
          if (opts.json) {
            console.log(JSON.stringify({
              success: false, code: timedOut ? 'WIKI_LINT_TIMEOUT' : 'WIKI_LINT_FAILED',
              error: safeSubprocessError(error),
            }))
          } else {
            console.error(chalk.red(`
✗ ${safeSubprocessError(error)}${hint}`))
          }
          process.exit(1)
        }
      }))

  // chat-notes：把会话整理成知识卡，喂给 wiki compile 聚成概念页
  program
    .command('chat-notes')
    .description('把最近一段时间的会话整理成知识卡（之后用 wiki compile 聚成概念页）—— **只写本地文件，不发送**')
    .option('--days <n>', '看最近多少天', '30')
    .option('--limit <n>', '最多处理几个会话', '40')
    .option('--source <source>', '聊天来源：wechat（默认）/ qq（只读 import qchat 导入的会话，不碰微信库）/ all（都要）', 'wechat')
    .option('--dry-run', '仅预览：几个会话、多少字符会发给生成模型（只读本地，零出境）')
    .option('--yes', '确认把对话发送给生成模型')
    .option('--transcribe-voice',
            '把缺转写的语音**本机**识别掉再产卡（本地 whisper，慢、吃 CPU、不出网；配合 --dry-run 就是只补转写、不调模型）')
    .option('--json', '输出机器可读结果；执行仍需 --yes')
    .action(async (opts) => {
      const { execFile } = await import('child_process')
      const { promisify } = await import('util')
      const execFileAsync = promisify(execFile)
      const pkgRoot = resolvePackageRoot()
      const script = join(pkgRoot, 'scripts', 'chat_notes.py')
      const days = parseCliInteger(opts.days, 'days', 1, 3650, opts.json)
      const limit = parseCliInteger(opts.limit, 'limit', 1, 200, opts.json)
      requireCliChoice(opts.source, ['wechat', 'qq', 'all'], 'source', opts.json)
      // 与 `draft` 同一条纪律：**"确认过了"只用一个变量**，参数在确认之后才拼
      let confirmed = !!opts.yes
      if (!opts.dryRun && !confirmed) {
        const preview = {
          success: false, dryRun: false, action: 'chat-notes',
          code: 'CONFIRMATION_REQUIRED', days, limit, source: opts.source,
          readsLocalChat: true, invokesAI: true, writesLocalFiles: true, sendsNothing: true,
        }
        if (opts.json) {
          console.log(JSON.stringify(preview))
          process.exit(1)
        }
        const answer = await inquirer.prompt([{
          type: 'confirm',
          name: 'confirmed',
          message: '确认把最近这些会话的对话发送给生成模型吗？（只会产出本地知识卡，不会替你发送任何消息）',
          default: false,
        }])
        confirmed = !!answer.confirmed
        if (!confirmed) {
          console.log(chalk.gray('已取消'))
          return
        }
      }
      const args = [script, '--days', String(days), '--limit', String(limit),
                    '--source', String(opts.source),
                    ...(confirmed ? ['--yes'] : []),
                    ...(opts.transcribeVoice ? ['--transcribe-voice'] : []),
                    ...(opts.json ? ['--json'] : []),
                    ...(opts.dryRun ? ['--dry-run'] : [])]
      try {
        const { stdout } = await execFileAsync(getPythonCommand(), args, {
          timeout: 900_000, maxBuffer: 50 * 1024 * 1024,
          env: pythonProcessEnv(),
        })
        process.stdout.write(stdout)
      } catch (error) {
        if (opts.json) {
          console.log(JSON.stringify({ success: false, code: 'CHAT_NOTES_FAILED', action: 'chat-notes', error: safeSubprocessError(error) }))
        } else {
          console.error(chalk.red(`\n✗ ${safeSubprocessError(error)}`))
        }
        process.exit(1)
      }
    })

  // user-notes：读你自己写的笔记（第四条来源，也是唯一读"人写的东西"的一条）
  program
    .command('user-notes')
    .description('读你自己写的笔记，长成知识卡（之后用 wiki compile 聚成概念页）—— **你的笔记只读，绝不修改**')
    .option('--limit <n>', '最多处理几篇笔记', '20')
    .option('--vault <dir>', '库目录', join(resolveOutputRoot(), 'wechat-vault'))
    .option('--refresh', '已有卡的也重做')
    .option('--dry-run', '仅预览：几篇笔记会发给模型（只读本地，零出境）')
    .option('--yes', '确认把笔记发给生成模型')
    .option('--json', '输出机器可读结果；执行仍需 --yes')
    .action(async (opts) => {
      const { execFile } = await import('child_process')
      const { promisify } = await import('util')
      const execFileAsync = promisify(execFile)
      const script = join(resolvePackageRoot(), 'scripts', 'user_notes.py')
      const limit = parseCliInteger(opts.limit, 'limit', 1, 500, opts.json)
      let confirmed = !!opts.yes
      if (!opts.dryRun && !confirmed) {
        const preview = {
          success: false, dryRun: false, action: 'user-notes',
          code: 'CONFIRMATION_REQUIRED', limit,
          readsLocalData: true, invokesAI: true, writesLocalFiles: true,
          modifiesYourNotes: false, sendsNothing: true,
        }
        if (opts.json) {
          console.log(JSON.stringify(preview))
          process.exit(1)
        }
        const answer = await inquirer.prompt([{
          type: 'confirm',
          name: 'confirmed',
          message: '确认把你自己写的这些笔记发给生成模型吗？（你的笔记只读，产出的卡另存；只写本地文件）',
          default: false,
        }])
        confirmed = !!answer.confirmed
        if (!confirmed) {
          console.log(chalk.gray('已取消'))
          return
        }
      }
      const args = [script, '--limit', String(limit), '--vault', String(opts.vault),
                    ...(opts.refresh ? ['--refresh'] : []),
                    ...(confirmed ? ['--yes'] : []),
                    ...(opts.json ? ['--json'] : []),
                    ...(opts.dryRun ? ['--dry-run'] : [])]
      try {
        const { stdout } = await execFileAsync(getPythonCommand(), args, {
          timeout: 1_800_000, maxBuffer: 50 * 1024 * 1024,
          env: pythonProcessEnv(),
        })
        process.stdout.write(stdout)
      } catch (error) {
        if (opts.json) {
          console.log(JSON.stringify({ success: false, code: 'USER_NOTES_FAILED', action: 'user-notes',
            error: safeSubprocessError(error), detail: String((error as any)?.stdout || '').slice(0, 2000) }))
        } else {
          console.error(chalk.red(`\n✗ ${safeSubprocessError(error)}`))
        }
        process.exit(1)
      }
    })

  // fav-notes：把微信收藏里的文章变成知识卡（第三条来源）
  program
    .command('fav-notes')
    .description('把微信收藏里的文章整理成知识卡（之后用 wiki compile 聚成概念页）—— **只写本地文件，不发送**')
    .option('--limit <n>', '最多处理几条收藏（按收藏时间倒序）', '10')
    .option('--refresh', '已有卡的也重做（默认增量：只做还没卡的）')
    .option('--dry-run', '仅预览：几条、多少要联网抓（只读本地，零出境）')
    .option('--yes', '确认把收藏的正文发给生成模型')
    .option('--json', '输出机器可读结果；执行仍需 --yes')
    .action(async (opts) => {
      const { execFile } = await import('child_process')
      const { promisify } = await import('util')
      const execFileAsync = promisify(execFile)
      const script = join(resolvePackageRoot(), 'scripts', 'fav_notes.py')
      const limit = parseCliInteger(opts.limit, 'limit', 1, 500, opts.json)
      // 与另外两条线同一条纪律：**「确认过了」只用一个变量**，参数在确认之后才拼
      let confirmed = !!opts.yes
      if (!opts.dryRun && !confirmed) {
        const preview = {
          success: false, dryRun: false, action: 'fav-notes',
          code: 'CONFIRMATION_REQUIRED', limit,
          readsLocalData: true, fetchesArticleUrls: true, invokesAI: true,
          writesLocalFiles: true, sendsNothing: true,
        }
        if (opts.json) {
          console.log(JSON.stringify(preview))
          process.exit(1)
        }
        const answer = await inquirer.prompt([{
          type: 'confirm',
          name: 'confirmed',
          message: '确认把这些收藏的正文发给生成模型吗？（只写本地知识卡；正文取不到时会去抓文章链接）',
          default: false,
        }])
        confirmed = !!answer.confirmed
        if (!confirmed) {
          console.log(chalk.gray('已取消'))
          return
        }
      }
      const args = [script, '--limit', String(limit),
                    ...(opts.refresh ? ['--refresh'] : []),
                    ...(confirmed ? ['--yes'] : []),
                    ...(opts.json ? ['--json'] : []),
                    ...(opts.dryRun ? ['--dry-run'] : [])]
      try {
        const { stdout } = await execFileAsync(getPythonCommand(), args, {
          timeout: 1_800_000, maxBuffer: 50 * 1024 * 1024,
          env: pythonProcessEnv(),
        })
        process.stdout.write(stdout)
      } catch (error) {
        if (opts.json) {
          console.log(JSON.stringify({ success: false, code: 'FAV_NOTES_FAILED', action: 'fav-notes',
            error: safeSubprocessError(error), detail: String((error as any)?.stdout || '').slice(0, 2000) }))
        } else {
          console.error(chalk.red(`\n✗ ${safeSubprocessError(error)}`))
        }
        process.exit(1)
      }
    })

  // article-notes：从文章笔记里提炼概念，喂给 wiki compile
  program
    .command('article-notes')
    .description('从 Vault 的文章笔记里提炼概念（之后用 wiki compile 聚成概念页）—— **只写本地文件，不发送**')
    .option('--source <dir>', '文章笔记目录', './output/wechat-vault/002_Literature')
    .option('--limit <n>', '最多处理几篇（按发布时间倒序）', '30')
    .option('--since <date>', '只看这个日期之后的（YYYY-MM-DD）—— 比 --limit 精确，例："9 月的都跑一遍"')
    .option('--until <date>', '只看这个日期之前的（YYYY-MM-DD）')
    .option('--topic <name>', '只做这些主题，可重复或用逗号分隔（如 --topic AI）；不传=全部',
            (value, previous: string[] = []) => [...previous, value], [])
    .option('--workers <n>', '并发问几篇（只并行"问"，写仍是串行）', '6')
    .option('--dry-run', '仅预览：几篇、多少字会发给生成模型（只读本地，零出境）')
    .option('--refresh-summaries', '只按原笔记重算已有卡片的摘要（本地，不调用模型、不必 --yes）')
    .option('--yes', '确认把文章发给生成模型')
    .option('--json', '输出机器可读结果；执行仍需 --yes')
    .action(async (opts) => {
      const { execFile } = await import('child_process')
      const { promisify } = await import('util')
      const execFileAsync = promisify(execFile)
      const pkgRoot = resolvePackageRoot()
      const script = join(pkgRoot, 'scripts', 'article_notes.py')
      const limit = parseCliInteger(opts.limit, 'limit', 1, 5000, opts.json)
      // 主题筛选：这一步是**纯花钱的**（一篇一次调用），而实测主题分布是新闻 57% /
      // AI 28% / 学术 13%，所以"只做 AI"是省掉一半以上花费的那个开关。它必须出现在
      // 确认框里——不然用户看到的是"要花 1.6 万次调用"，而不是"要花 4 千次"。
      const topics = (opts.topic as string[])
        .flatMap(value => String(value).split(','))
        .map(value => value.trim())
        .filter(Boolean)
      const workers = parseCliInteger(opts.workers, 'workers', 1, 64, opts.json)
      // 与 `chat-notes`/`draft` 同一条纪律：**"确认过了"只用一个变量**，参数在确认之后才拼
      let confirmed = !!opts.yes
      if (!opts.dryRun && !opts.refreshSummaries && !confirmed) {
        const preview = {
          success: false, dryRun: false, action: 'article-notes',
          code: 'CONFIRMATION_REQUIRED', source: opts.source, limit, topics,
          readsLocalData: true, invokesAI: true, writesLocalFiles: true, sendsNothing: true,
        }
        if (opts.json) {
          console.log(JSON.stringify(preview))
          process.exit(1)
        }
        const answer = await inquirer.prompt([{
          type: 'confirm',
          name: 'confirmed',
          message: '确认把这些文章（只问概念，摘要照抄）发给生成模型吗？（只写本地知识卡，不会发送任何消息）',
          default: false,
        }])
        confirmed = !!answer.confirmed
        if (!confirmed) {
          console.log(chalk.gray('已取消'))
          return
        }
      }
      const args = [script, '--source', String(opts.source), '--limit', String(limit),
                    ...(opts.since ? ['--since', String(opts.since)] : []),
                    ...(opts.until ? ['--until', String(opts.until)] : []),
                    ...(topics.length ? ['--topic', topics.join(',')] : []),
                    '--workers', String(workers),
                    ...(opts.refreshSummaries ? ['--refresh-summaries'] : []),
                    ...(confirmed ? ['--yes'] : []),
                    ...(opts.json ? ['--json'] : []),
                    ...(opts.dryRun ? ['--dry-run'] : [])]
      try {
        const { stdout } = await execFileAsync(getPythonCommand(), args, {
          timeout: 1_800_000, maxBuffer: 50 * 1024 * 1024,
          env: pythonProcessEnv(),
        })
        process.stdout.write(stdout)
      } catch (error) {
        if (opts.json) {
          console.log(JSON.stringify({ success: false, code: 'ARTICLE_NOTES_FAILED', action: 'article-notes', error: safeSubprocessError(error) }))
        } else {
          console.error(chalk.red(`\n✗ ${safeSubprocessError(error)}`))
        }
        process.exit(1)
      }
    })

  // pdf-notes：PDF → 本机 OCR → 摘要与概念，喂给 wiki compile
  program
    .command('pdf-notes')
    .description('把 PDF 变知识卡（本机 OCR 转文字，再问摘要与概念）—— **只写本地文件，不发送**')
    .option('--pdf <file>', '单个 PDF 路径')
    .option('--dir <dir>', 'PDF 目录（递归找 *.pdf）')
    .option('--from-chat', '从聊天记录里找别人发过的 PDF（读微信 hardlink.db，按文件时间倒序）')
    .option('--ocr-root <dir>', '本机 OCR 引擎目录（Unlimited-OCR-2）',
            'D:\\github_project\\ZhaoWen_GitHub维护\\ocr2')
    .option('--ocr <mode>', 'auto=本地在就用本地、不在就上云端、都没有才抽内嵌文本；local/cloud 强制；none 只抽内嵌文本', 'auto')
    .option('--ocr-model <name>', '云端 OCR 模型（默认 qwen3.5-ocr）')
    .option('--pages <range>', '只处理这些页（例 1-50）')
    .option('--dpi <n>', 'OCR 渲染精度（默认 200）', '200')
    .option('--window <n>', 'OCR 一次喂几页（默认 10）', '10')
    .option('--limit <n>', '最多处理几个 PDF', '5')
    .option('--dry-run', '仅预览：几个 PDF、会不会调用本机 OCR（只读本地，零出境）')
    .option('--refresh', '已有卡的也重做（默认增量：只做还没卡的）')
    .option('--no-reuse-ocr', '不复用缓存的 OCR 文字（默认复用：PDF 没改过就不重做识别，实测 30.9s → 2.3s）')
    .option('--ocr-only', '只做识别、只写文字（不调用模型、不花钱、不需要 --yes 与 API key）—— 可挂着过夜跑完，白天再出卡')
    .option('--yes', '确认把 PDF 文字发给生成模型')
    .option('--json', '输出机器可读结果；执行仍需 --yes')
    .action(async (opts) => {
      const { execFile } = await import('child_process')
      const { promisify } = await import('util')
      const execFileAsync = promisify(execFile)
      const pkgRoot = resolvePackageRoot()
      const script = join(pkgRoot, 'scripts', 'pdf_notes.py')
      const limit = parseCliInteger(opts.limit, 'limit', 1, 5000, opts.json)
      // 与其它几条线同一条纪律：**"确认过了"只用一个变量**，参数在确认之后才拼。
      // 这条线多一句提示：PDF 的**文字**会出境（PDF 本身不出境，本机 OCR）。
      let confirmed = !!opts.yes
      // `--ocr-only` 零出境、零花费，不该弹确认框（确认框是给"要发出去"那一步的）
      if (!opts.dryRun && !opts.ocrOnly && !confirmed) {
        const preview = {
          success: false, dryRun: false, action: 'pdf-notes',
          code: 'CONFIRMATION_REQUIRED', pdf: opts.pdf, dir: opts.dir, limit,
          readsLocalData: true, invokesAI: true, writesLocalFiles: true, sendsNothing: true,
          note: 'PDF 在本机 OCR（不出网）；只有 OCR 后的文字会发给模型',
        }
        if (opts.json) {
          console.log(JSON.stringify(preview))
          process.exit(1)
        }
        const answer = await inquirer.prompt([{
          type: 'confirm',
          name: 'confirmed',
          message: '确认把这些 PDF 的文字（OCR 后）发给生成模型吗？（PDF 本身在本机 OCR，不出境）',
          default: false,
        }])
        confirmed = !!answer.confirmed
        if (!confirmed) {
          console.log(chalk.gray('已取消'))
          return
        }
      }
      const args = [script,
                    ...(opts.pdf ? ['--pdf', String(opts.pdf)] : []),
                    ...(opts.dir ? ['--dir', String(opts.dir)] : []),
                    ...(opts.fromChat ? ['--from-chat'] : []),
                    '--ocr-root', String(opts.ocrRoot),
                    '--ocr', String(opts.ocr),
                    ...(opts.ocrModel ? ['--ocr-model', String(opts.ocrModel)] : []),
                    ...(opts.pages ? ['--pages', String(opts.pages)] : []),
                    '--dpi', String(opts.dpi),
                    '--window', String(opts.window),
                    '--limit', String(limit),
                    ...(opts.refresh ? ['--refresh'] : []),
                    ...(opts.reuseOcr === false ? ['--no-reuse-ocr'] : []),
                    ...(opts.ocrOnly ? ['--ocr-only'] : []),
                    ...(confirmed ? ['--yes'] : []),
                    ...(opts.json ? ['--json'] : []),
                    ...(opts.dryRun ? ['--dry-run'] : [])]
      try {
        const { stdout } = await execFileAsync(getPythonCommand(), args, {
          timeout: 7_200_000, maxBuffer: 50 * 1024 * 1024,
          env: pythonProcessEnv(),
        })
        process.stdout.write(stdout)
      } catch (error) {
        // 脚本自己在 `--json` 下会打印一条**结构化**错误（没找到 PDF、OCR 引擎缺失…）。
        // 直接透出它，比一句"子进程执行失败"有用得多——那正是这个命令最需要说清的两件事。
        const raw = String((error as { stdout?: unknown }).stdout ?? '').trim()
        const parsed = (() => {
          if (!raw) return null
          try { return JSON.parse(raw) as { success?: boolean; error?: string } } catch { return null }
        })()
        if (opts.json) {
          console.log(parsed
            ? JSON.stringify({ ...parsed, code: 'PDF_NOTES_FAILED', action: 'pdf-notes' })
            : JSON.stringify({ success: false, code: 'PDF_NOTES_FAILED', action: 'pdf-notes', error: safeSubprocessError(error) }))
        } else {
          const message = parsed?.error || safeSubprocessError(error)
          console.error(chalk.red(`\n✗ ${message}`))
        }
        process.exit(1)
      }
    })

  // todos
  const todosCmd = program
    .command('todos')
    .description('待办提取与任务追踪')

  async function runTodoMutation(action: 'done' | 'undone' | 'remove', id: string, opts: { dryRun?: boolean; yes?: boolean; json?: boolean }): Promise<void> {
    if (opts.dryRun) {
      await runPython('scripts/extract_todos.py', ['preview', id, '--action', action])
      return
    }
    if (!opts.yes) {
      if (opts.json) {
        console.log(JSON.stringify({
          success: false,
          code: 'CONFIRMATION_REQUIRED',
          error: '先使用 --dry-run --json 预览，再由用户确认后使用 --yes --json 执行',
        }))
        process.exit(1)
      }
      const { confirmed } = await inquirer.prompt([{
        type: 'confirm',
        name: 'confirmed',
        message: `确认执行待办操作 ${action} (${id})？`,
        default: false,
      }])
      if (!confirmed) {
        console.log(chalk.gray('已取消'))
        return
      }
    }
    const command = action === 'remove' ? 'rm' : action
    await runPython('scripts/extract_todos.py', [command, id, ...(opts.json ? ['--json'] : [])])
  }

  todosCmd
    .command('extract')
    .description('AI 扫描聊天记录提取待办')
    .option('--days <n>', '扫描天数', '7')
    .option('--api-key <key>', 'DeepSeek API key')
    .option('--dry-run', '仅预览，不读取聊天、调用 AI 或写入待办')
    .option('--yes', '确认提取并写入待办')
    .option('--json', '输出机器可读结果，不返回聊天或待办正文')
    .action(async (opts) => {
      const days = parseCliInteger(opts.days, 'days', 1, 365, opts.json)
      await runConfirmedPythonMutation({
        action: 'todos.extract',
        script: join(resolvePackageRoot(), 'scripts', 'extract_todos.py'),
        args: ['extract', '--days', String(days)],
        cliOptions: opts,
        preview: { days, readsLocalChat: true, usesAi: true, writesTodos: true },
        confirmationMessage: `确认读取最近 ${days} 天聊天并发送到已配置的 AI 服务以提取待办？`,
        apiKey: opts.apiKey,
      })
    })

  todosCmd
    .command('list')
    .description('列出待办')
    .option('--status <s>', 'pending / done')
    .option('--urgency <u>', '高 / 中 / 低')
    .option('--json', 'JSON 输出')
    .action(async (opts) => {
      const a = ['list']
      if (opts.status) a.push('--status', opts.status)
      if (opts.urgency) a.push('--urgency', opts.urgency)
      if (opts.json) a.push('--json')
      await runPython('scripts/extract_todos.py', a)
    })

  todosCmd
    .command('done')
    .description('标记待办为已完成')
    .argument('<id>', '待办 ID')
    .option('--dry-run', '仅预览，不修改待办')
    .option('--yes', '确认执行修改')
    .option('--json', '输出 JSON 格式')
    .action(async (id, opts) => {
      await runTodoMutation('done', id, opts)
    })

  todosCmd
    .command('undone')
    .description('取消已完成标记')
    .argument('<id>', '待办 ID')
    .option('--dry-run', '仅预览，不修改待办')
    .option('--yes', '确认执行修改')
    .option('--json', '输出 JSON 格式')
    .action(async (id, opts) => {
      await runTodoMutation('undone', id, opts)
    })

  todosCmd
    .command('rm')
    .description('删除待办')
    .argument('<id>', '待办 ID')
    .option('--dry-run', '仅预览，不删除待办')
    .option('--yes', '确认执行删除')
    .option('--json', '输出 JSON 格式')
    .action(async (id, opts) => {
      await runTodoMutation('remove', id, opts)
    })

  todosCmd
    .command('remind')
    .description('查看待办提醒')
    .option('--json', '输出 JSON 格式')
    .action(async (opts) => {
      await runPython('scripts/extract_todos.py', ['remind', ...(opts.json ? ['--json'] : [])])
    })

// ==================== daily ====================
program
  .command('daily')
  .option('--source <name>', '仅处理指定公众号，可重复或用逗号分隔', (value, previous: string[] = []) => [...previous, value], [])
  .description('一键生成公众号日报（抓取 + AI 摘要 + HTML 阅读器 + 行动建议）')
  .option('-d, --date <YYYY-MM-DD>', '日期')
  .option('--yesterday', '跑昨天（等价于 --date 昨天）。公众号发到 24:00 才停，所以当晚跑的那一天永远不全；"跑昨天"与时刻无关，计划任务用这个')
  .option('--api-key <key>', 'DeepSeek API key（或设环境变量 DEEPSEEK_API_KEY）')
  .option('--skip-classify', '跳过后处理')
  .option('--dry-run', '仅预览文章，不调用 AI 或写入日报')
  .option('--yes', '确认执行日报生成；JSON 模式需要此选项')
  .option('--no-ai', '关闭本次日报的所有 AI 处理')
  .option('--no-summary', '只判断不生成：不调 LLM 写摘要/标签/简报（主题与相关度仍由 Jev 判断），无需 DeepSeek key')
  .option('--keep-images', '保留当天的 images/ 目录（**默认删**：每天 0.6–1.3G，而日报主页与 md 都不引用它，只有单篇阅读视图用得上）。等价配置 dailyKeepImages=true')
  .option('--prefetch-bodies [n]', '抓取之前先并发把当天正文抓进缓存（n=并发数，默认 8）：抓取阶段于是全部命中缓存、不再逐篇 sleep 8-12 秒（450 篇约 75 分钟 → 秒级）。对上游的请求次数不变，只是压进更短的时间窗')
  .option('--no-prefetch-bodies', '关闭并发预取正文（默认开启）')
  .option('--json', '输出机器可读的最终结果；运行日志写入 stderr')
  .option('--email', '生成后把日报按主题（AI / 文学 / 学术）发到邮箱（每个主题附一段 AI 综述，逐篇给要点）')
  .option('--mail-to <address>', '邮件收件人；缺省用配置 dailyMailTo，再缺省发给自己')
  // Linux 上拿不到本地库密钥时，**外部订阅源是唯一的日报来源**——
  // 之前这些旗标只存在于 `scripts/pipeline.py`，主命令 `weflow-cli daily` 用不了
  // （2026-11-01 实测：`daily --articles-json` 报 unknown option）。
  .option('--articles-json <file>', '外部文章 JSON（无需本地库；可重复）', (v, prev: string[] = []) => [...prev, v], [])
  .option('--rss-feed <url>', 'RSS/Atom 订阅源地址（可重复）', (v, prev: string[] = []) => [...prev, v], [])
  .option('--rss-opml <file>', 'OPML 订阅列表文件')
  .action(async (opts) => {
    const { spawn } = await import('child_process')
    const { existsSync, statSync } = await import('fs')
    const pkgRoot = resolvePackageRoot()
    const pipeline = join(pkgRoot, 'scripts', 'pipeline.py')
    const bizDaily = join(pkgRoot, 'scripts', 'biz_daily.py')
    const dailyMail = join(pkgRoot, 'scripts', 'daily_mail.py')

    const now = new Date()
    const localDate = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`
    const isoDate = (when: Date) => `${when.getFullYear()}-${String(when.getMonth() + 1).padStart(2, '0')}-${String(when.getDate()).padStart(2, '0')}`
    if (opts.date && opts.yesterday) {
      const error = '--date 与 --yesterday 不能同时给（前者是明确的一天，后者是"昨天"）'
      if (opts.json) console.log(JSON.stringify({ success: false, code: 'INVALID_ARGUMENT', field: 'date', error }))
      else console.log(chalk.red(error))
      process.exit(1)
    }
    const date = opts.date || (opts.yesterday
      ? isoDate(new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1))
      : localDate)
    const apiKey = resolveAiKey(opts.apiKey)
    const noAi = opts.ai === false || configService.get('dailyAiEnabled') === 'false'
    const dailyLog = (...values: any[]) => opts.json ? console.error(...values) : console.log(...values)

    const artifactStatus = (targetDate: string) => {
      const outputDir = join(resolveOutputRoot(), 'biz-daily', targetDate)
      const hasFile = (file: string) => {
        const path = join(outputDir, file)
        try { return existsSync(path) && statSync(path).size > 0 } catch { return false }
      }
      return {
        readme: hasFile('README.md'),
        articleIndex: hasFile('.articles.json'),
        reader: hasFile('index.html'),
      }
    }
    const isComplete = (targetDate: string): boolean => Object.values(artifactStatus(targetDate)).every(Boolean)

    const runPipeline = (targetDate: string): Promise<number> => new Promise((resolve) => {
      const args = [pipeline, '--date', targetDate, '--engine', noAi ? 'local' : 'deepseek', '--interest', 'AI']
      if (noAi) args.push('--no-ai')
      // 与 --no-ai 不同：这一条保留判断（Jev），只关掉 LLM 的文字生成。
      if (opts.noSummary && !noAi) args.push('--no-summary')
      // 默认由 pipeline 在收尾时删掉当天的 images/；这条是"别删"的开关。
      if (opts.keepImages) args.push('--keep-images')
      for (const source of opts.source || []) args.push('--source', source)
      // 外部源直通 pipeline：无本地库时也能出完整日报（Linux 的主要路径）
      for (const file of opts.articlesJson || []) args.push('--articles-json', file)
      for (const url of opts.rssFeed || []) args.push('--rss-feed', url)
      if (opts.rssOpml) args.push('--rss-opml', opts.rssOpml)
      if (opts.skipClassify) args.push('--skip-classify')
      // 只在**给了**这个旗标时才解析数字：`--prefetch-bodies`（不带数字）是合法的，
      // 而默认并发数只在 python 侧写一份（这里再写一份迟早漂移）。
      if (opts.prefetchBodies !== undefined) {
        args.push('--prefetch-bodies')
        if (opts.prefetchBodies !== true) {
          args.push(String(parseCliInteger(opts.prefetchBodies, 'prefetch-bodies', 1, 64, !!opts.json)))
        }
      }

      dailyLog(chalk.cyan(`\n📰 正在生成 ${targetDate} 公众号日报${noAi ? '（AI 已关闭）' : ''}...\n`))
      const child = spawn(getPythonCommand(), args, {
        windowsHide: true,
        stdio: opts.json ? ['ignore', 'pipe', 'pipe'] : 'inherit',
        env: pythonProcessEnv(apiKey),
      })
      if (opts.json) {
        child.stdout?.pipe(process.stderr)
        child.stderr?.pipe(process.stderr)
      }
      child.on('error', () => resolve(1))
      child.on('exit', (code) => resolve(code || 0))
    })

    if (opts.dryRun) {
      const dryRunArgs = [bizDaily, '--date', date, '--engine', 'local', '--dry-run']
      for (const source of opts.source || []) dryRunArgs.push('--source', source)
      for (const file of opts.articlesJson || []) dryRunArgs.push('--articles-json', file)
      for (const url of opts.rssFeed || []) dryRunArgs.push('--rss-feed', url)
      if (opts.rssOpml) dryRunArgs.push('--rss-opml', opts.rssOpml)
      const child = spawn(getPythonCommand(), dryRunArgs, {
        windowsHide: true,
        stdio: opts.json ? ['ignore', 'pipe', 'pipe'] : 'inherit',
        env: pythonProcessEnv(),
      })
      if (opts.json) {
        child.stdout?.pipe(process.stderr)
        child.stderr?.pipe(process.stderr)
      }
      child.on('exit', (code) => {
        if (opts.json) console.log(JSON.stringify({ success: code === 0, dryRun: true, date, aiEnabled: false }))
        process.exit(code || 0)
      })
      return
    }

    if (opts.json && !opts.yes) {
      console.log(JSON.stringify({
        success: false,
        code: 'CONFIRMATION_REQUIRED',
        action: 'daily.generate',
        date,
        aiEnabled: !noAi,
      }))
      process.exit(1)
    }

    if (!apiKey && !noAi) {
      if (opts.json) {
        console.log(JSON.stringify({ success: false, code: 'AI_KEY_REQUIRED', error: 'AI 已启用但未配置 API key' }))
        process.exit(1)
      }
      console.log(chalk.red('\n❌ 缺少 DeepSeek API key'))
      console.log(chalk.gray('  用法: weflow-cli daily --api-key <key>'))
      console.log(chalk.gray('  或设环境变量: set DEEPSEEK_API_KEY=<key>\n'))
      process.exit(1)
    }

    if (!opts.date) {
      const previous = new Date(now)
      previous.setDate(previous.getDate() - 1)
      const previousDate = `${previous.getFullYear()}-${String(previous.getMonth() + 1).padStart(2, '0')}-${String(previous.getDate()).padStart(2, '0')}`
      if (!opts.dryRun && !isComplete(previousDate)) {
        dailyLog(chalk.yellow(`\n⚠️ 昨日报不完整，先补生成 ${previousDate}...`))
        const previousCode = await runPipeline(previousDate)
        if (previousCode !== 0 || !isComplete(previousDate)) {
          if (opts.json) {
            console.log(JSON.stringify({ success: false, code: 'PREVIOUS_DAILY_INCOMPLETE', date, previousDate }))
            process.exit(previousCode || 1)
          }
          console.log(chalk.red(`\n✗ 昨日报补生成失败或仍不完整，已停止当天日报生成。`))
          process.exit(previousCode || 1)
        }
        dailyLog(chalk.green(`\n✓ 昨日报已补齐: output/biz-daily/${previousDate}/`))
      }
    }

    const code = await runPipeline(date)
    if (code === 0) {
      const complete = isComplete(date)
      // 邮件只依赖 `.articles.json`（逐篇摘要已经由 biz_daily 写好），所以放在生成之后、
      // 与"是否完整"无关：不完整时也先把已有的发出去，用户不至于什么都收不到。
      let mail: { ok: boolean; code: number } | null = null
      if (opts.email) {
        const mailArgs = [dailyMail, '--date', date]
        if (opts.mailTo) mailArgs.push('--to', String(opts.mailTo))
        dailyLog(chalk.cyan('\n📧 正在按主题整理并发邮件...'))
        mail = await new Promise((resolve) => {
          const child = spawn(getPythonCommand(), mailArgs, {
            windowsHide: true,
            stdio: 'inherit',
            env: pythonProcessEnv(apiKey),
          })
          child.on('error', () => resolve({ ok: false, code: 1 }))
          child.on('exit', (c) => resolve({ ok: (c || 0) === 0, code: c || 0 }))
        })
        if (mail && !mail.ok) dailyLog(chalk.yellow('  ! 邮件没发出去（日报本身已生成，见上面的报错）'))
      }
      if (opts.json) {
        console.log(JSON.stringify({
          success: complete,
          code: complete ? null : 'DAILY_OUTPUT_INCOMPLETE',
          date,
          aiEnabled: !noAi,
          output: `output/biz-daily/${date}`,
          artifacts: artifactStatus(date),
          mail,
        }, null, 2))
        if (!complete) process.exit(1)
        return
      }
      console.log(chalk.green(`\n✓ 日报已生成: output/biz-daily/${date}/`))
      if (mail) console.log(chalk.green(`✓ 邮件已发送${opts.mailTo ? ` → ${opts.mailTo}` : ''}`))
      console.log(chalk.gray(`  HTML 阅读器: weflow-cli daily-server --date ${date}`))
    } else {
      if (opts.json) console.log(JSON.stringify({ success: false, code: 'DAILY_PIPELINE_FAILED', date, aiEnabled: !noAi }))
      process.exit(code || 1)
    }
  })

const dailyFavoritesCmd = new Command('favorites')
  .description('同步或调整日报阅读器中的本地收藏')

const defaultDailyDate = () => {
  const now = new Date()
  return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`
}

const runDailyFavorites = async (
  date: string,
  root: string,
  changes: string[],
  action: string,
  opts: { dryRun?: boolean; yes?: boolean; json?: boolean },
) => {
  requireCliDate(date, opts.json)
  const script = join(resolvePackageRoot(), 'scripts', 'sync_fav.py')
  const itemCount = changes.length > 0 ? Math.max(0, changes.length - 1) : 0
  await runConfirmedPythonMutation({
    action,
    script,
    args: ['--date', date, '--root', root, ...changes],
    cliOptions: opts,
    preview: { dateSpecified: true, itemCount, modifiesFavoriteState: true },
    confirmationMessage: `确认更新当日日报收藏${itemCount ? `（${itemCount} 项）` : ''}？`,
  })
}

const dailyFavoriteOptions = (command: Command, opts: Record<string, any>): Record<string, any> => {
  const dailyOpts = command.parent?.parent?.opts() || {}
  return {
    ...opts,
    date: opts.date || dailyOpts.date,
    dryRun: !!(opts.dryRun || dailyOpts.dryRun),
    json: !!(opts.json || dailyOpts.json),
  }
}

dailyFavoritesCmd
  .command('sync')
  .description('按阅读器保存的收藏状态同步本地收藏目录')
  .option('-d, --date <YYYY-MM-DD>', '日报日期')
  .option('--root <dir>', '日报输出根目录', './output/biz-daily')
  .option('--dry-run', '仅预览，不读取状态或修改收藏目录')
  .option('--yes', '确认同步收藏目录')
  .option('--json', '输出机器可读结果，不返回文章或本地路径')
  .action(async (opts, command) => {
    const merged = dailyFavoriteOptions(command, opts)
    await runDailyFavorites(merged.date || defaultDailyDate(), merged.root, [], 'daily.favorites.sync', merged)
  })

dailyFavoritesCmd
  .command('add <article>')
  .description('添加日报文章到本地收藏')
  .option('--article <path>', '额外添加一篇文章，可重复使用', (value: string, previous: string[]) => [...previous, value], [] as string[])
  .option('-d, --date <YYYY-MM-DD>', '日报日期')
  .option('--root <dir>', '日报输出根目录', './output/biz-daily')
  .option('--dry-run', '仅预览，不修改收藏')
  .option('--yes', '确认添加收藏')
  .option('--json', '输出机器可读结果，不返回文章或本地路径')
  .action(async (article, opts, command) => {
    const merged = dailyFavoriteOptions(command, opts)
    const articles = [article, ...(merged.article as string[])]
    await runDailyFavorites(merged.date || defaultDailyDate(), merged.root, ['--add', ...articles], 'daily.favorites.add', merged)
  })

dailyFavoritesCmd
  .command('remove <article>')
  .description('从本地收藏中移除日报文章')
  .option('--article <path>', '额外移除一篇文章，可重复使用', (value: string, previous: string[]) => [...previous, value], [] as string[])
  .option('-d, --date <YYYY-MM-DD>', '日报日期')
  .option('--root <dir>', '日报输出根目录', './output/biz-daily')
  .option('--dry-run', '仅预览，不修改收藏')
  .option('--yes', '确认移除收藏')
  .option('--json', '输出机器可读结果，不返回文章或本地路径')
  .action(async (article, opts, command) => {
    const merged = dailyFavoriteOptions(command, opts)
    const articles = [article, ...(merged.article as string[])]
    await runDailyFavorites(merged.date || defaultDailyDate(), merged.root, ['--remove', ...articles], 'daily.favorites.remove', merged)
  })

program.commands.find(c => c.name() === 'daily')?.addCommand(dailyFavoritesCmd)

// ==================== skill (本机技能包) ====================
// 技能就是磁盘上的 `SKILL.md`，所以这里**没有安装/卸载**：读、看、体检三件事。
// 体检（`check`）是最有用的一个 —— 它把"读不出来""不合规范""跨目录撞名"这些
// 平时完全静默的问题一次报出来（少一个技能不会报错，只会少一个技能）。
const skillCmd = program
  .command('skill')
  .description('本机技能包（SKILL.md）：列出、查看、体检')

skillCmd
  .command('list')
  .description('列出扫描到的技能')
  .option('--query <q>', '按关键词过滤（匹配 id、名称、说明、触发词）')
  .option('--json', 'JSON 输出')
  .action((opts) => {
    const scan = scanSkills()
    const disabled = disabledIds()
    const q = String(opts.query || '').trim().toLowerCase()
    const rows = scan.skills.filter(s => !q
      || [s.id, s.name, s.description, ...s.triggers].some(x => String(x).toLowerCase().includes(q)))
      .map(s => ({
        id: s.id,
        name: s.name,
        description: s.description,
        version: s.version,
        state: skillState(s, disabled),
        notes: s.notes,
        // **不给路径**：这是机器输出，路径只有在用户明确要 `show` 时才出现
      }))
    if (opts.json) {
      console.log(JSON.stringify({
        success: true,
        roots: skillRoots(),
        missingRoots: scan.missingRoots,
        total: rows.length,
        skills: rows,
      }))
      return
    }
    if (!rows.length) {
      console.log(chalk.gray(scan.skills.length ? `没有匹配「${opts.query}」的技能` : '没有扫描到技能'))
      console.log(chalk.gray(`技能目录：${skillRoots().join('、')}`))
      for (const dir of scan.missingRoots) console.log(chalk.gray(`  （不存在：${dir}）`))
      return
    }
    for (const r of rows) {
      const tag = r.state === 'disabled' ? chalk.gray('[已禁用] ') : ''
      console.log(`${tag}${chalk.cyan(r.id)}${r.version ? chalk.gray(' v' + r.version) : ''}  ${r.name}`)
      if (r.description) console.log(chalk.gray(`    ${r.description.slice(0, 100)}`))
      for (const n of r.notes) console.log(chalk.yellow(`    ⚠ ${n}`))
    }
    console.log(chalk.gray(`\n共 ${rows.length} 个。正文：weflow-cli skill show <id>`))
  })

skillCmd
  .command('show')
  .argument('<id>', '技能 id')
  .description('打印一个技能的 SKILL.md 正文')
  .option('--json', 'JSON 输出')
  .action((id, opts) => {
    const body = readSkillBody(id)
    if (!body.ok) {
      if (opts.json) {
        console.log(JSON.stringify({ success: false, code: 'SKILL_NOT_READABLE', error: body.text }))
        process.exit(1)
      }
      console.log(chalk.red(body.text))
      return
    }
    if (opts.json) {
      const scan = scanSkills()
      const info = scan.skills.find(s => s.id === id)
      console.log(JSON.stringify({
        success: true,
        id,
        name: info?.name ?? id,
        version: info?.version ?? '',
        truncated: !!body.truncated,
        body: body.text,
      }))
      return
    }
    console.log(body.text)
  })

skillCmd
  .command('check')
  .description('体检：不可读的 SKILL.md、跨目录同名、非规范 id、被禁用的技能')
  .option('--json', 'JSON 输出')
  .action((opts) => {
    const scan = scanSkills()
    const disabled = disabledIds()
    const disabledRows = scan.skills.filter(s => skillState(s, disabled) === 'disabled').map(s => s.id)
    const warned = scan.skills.filter(s => s.notes.length).map(s => ({ id: s.id, notes: s.notes }))
    const payload = {
      success: true,
      roots: skillRoots(),
      missingRoots: scan.missingRoots,
      total: scan.skills.length,
      unreadable: scan.unreadable,
      conflicts: scan.conflicts,
      warned,
      disabled: disabledRows,
    }
    if (opts.json) {
      console.log(JSON.stringify(payload))
      // 不可读 = 真出事了（有文件却读不出来），体检失败；警告与冲突只提示，不算失败
      if (scan.unreadable.length) process.exit(1)
      return
    }
    console.log(`技能目录：${skillRoots().join('、')}`)
    for (const dir of scan.missingRoots) console.log(chalk.gray(`  不存在：${dir}`))
    console.log(`扫描到 ${scan.skills.length} 个技能`)
    if (scan.unreadable.length) {
      console.log(chalk.red(`\n不可读 ${scan.unreadable.length} 个：`))
      for (const u of scan.unreadable) console.log(chalk.red(`  ✗ ${u.file}\n    ${u.reason}`))
    }
    if (scan.conflicts.length) {
      console.log(chalk.yellow(`\n跨目录同名 ${scan.conflicts.length} 个（靠前的目录胜出，不会覆盖）：`))
      for (const c of scan.conflicts) console.log(chalk.yellow(`  ! ${c.id}\n    用：${c.winner}\n    忽略：${c.loser}`))
    }
    if (warned.length) {
      console.log(chalk.yellow(`\n有提醒的 ${warned.length} 个：`))
      for (const w of warned) for (const n of w.notes) console.log(chalk.yellow(`  · ${w.id}：${n}`))
    }
    if (disabledRows.length) console.log(chalk.gray(`\n已禁用：${disabledRows.join('、')}`))
    if (!scan.unreadable.length && !scan.conflicts.length) console.log(chalk.green('\n没有不可读或撞名的技能'))
  })

// ==================== scene (会话场景) ====================
const pluginCmd = program
  .command('plugin')
  .description('MCP 工具插件：把外部 MCP server 的工具并进本项目的工具面（进程外运行，默认每次调用需确认）')

/** 三个动作共用的失败出口：`--json` 时给机器看的错误码，否则给人看的一句话。 */
function pluginFail(error: unknown, json?: boolean): never {
  const message = error instanceof Error ? error.message : String(error)
  if (json) console.log(JSON.stringify({ success: false, error: message }))
  else console.error(chalk.red(message))
  process.exit(1)
}

pluginCmd
  .command('list')
  .description('列出已注册的插件')
  .option('--json', 'JSON 输出')
  .action((opts) => {
    // **默认不打印插件目录路径**：机器输出里给路径会把本机用户名带进日志/issue。
    const rows = listPlugins().map(p => ({
      id: p.id,
      name: p.manifest.name,
      version: p.manifest.version,
      kind: p.manifest.kind,
      enabled: p.enabled,
      trusted: p.trusted,
      network: p.manifest.permissions?.network === true,
      description: p.manifest.description || '',
    }))
    if (opts.json) {
      console.log(JSON.stringify({ success: true, total: rows.length, plugins: rows }))
      return
    }
    if (!rows.length) {
      console.log(chalk.gray('还没有注册任何插件'))
      console.log(chalk.gray('装一个：weflow-cli plugin add <插件目录>'))
      return
    }
    for (const r of rows) {
      const flags = [
        r.kind === 'knowledge-source' ? '知识源' : '',
        r.enabled ? '' : '已禁用',
        r.trusted ? '已信任' : '需确认',
        r.network ? '声明联网' : '',
      ].filter(Boolean).join(' · ')
      console.log(`${chalk.cyan(r.id)} v${r.version}  ${r.name}${flags ? chalk.gray('  [' + flags + ']') : ''}`)
      if (r.description) console.log(chalk.gray(`    ${r.description.slice(0, 100)}`))
    }
  })

pluginCmd
  .command('add <dir>')
  .description('注册一个插件目录（该目录里要有 weflow-plugin.json）')
  .option('--json', 'JSON 输出')
  .action((dir, opts) => {
    try {
      const record = addPlugin(dir)
      if (opts.json) {
        console.log(JSON.stringify({ success: true, id: record.id, name: record.manifest.name, enabled: true, trusted: false }))
        return
      }
      console.log(`${chalk.green('已注册')} ${chalk.cyan(record.id)} ${record.manifest.name}`)
      console.log(chalk.gray('未信任状态：调用它的工具需要带 confirm: true。检查它能不能起来：weflow-cli plugin doctor'))
    } catch (e) {
      pluginFail(e, opts.json)
    }
  })

pluginCmd
  .command('remove <id>')
  .description('从注册表移除一个插件（不删插件目录本身）')
  .option('--yes', '跳过确认')
  .option('--json', 'JSON 输出')
  .action(async (id, opts) => {
    try {
      if (!opts.yes) {
        if (opts.json) {
          console.log(JSON.stringify({
            success: false,
            code: 'CONFIRMATION_REQUIRED',
            error: '这是本机注册表的写操作：先确认，再加 --yes 执行',
          }))
          process.exit(1)
        }
        const { confirmed } = await inquirer.prompt([{
          type: 'confirm',
          name: 'confirmed',
          message: `从注册表移除插件 ${id}？（插件目录不会被删除）`,
          default: false,
        }])
        if (!confirmed) {
          console.log(chalk.gray('已取消'))
          return
        }
      }
      const removed = removePlugin(id)
      if (!removed) {
        if (opts.json) console.log(JSON.stringify({ success: false, error: `没有这个插件：${id}` }))
        else console.error(chalk.red(`没有这个插件：${id}`))
        process.exit(1)
      }
      if (opts.json) console.log(JSON.stringify({ success: true, removed: id }))
      else console.log(chalk.green(`已移除 ${id}`))
    } catch (e) {
      pluginFail(e, opts.json)
    }
  })

for (const [name, enabled] of [['enable', true], ['disable', false]] as const) {
  pluginCmd
    .command(`${name} <id>`)
    .description(`${name === 'enable' ? '启用' : '禁用'}一个插件（${name === 'enable' ? '工具会出现在 MCP 工具表里' : '工具不再出现在 MCP 工具表里'}）`)
    .option('--json', 'JSON 输出')
    .action((id, opts) => {
      try {
        const record = setPluginFlags(id, { enabled })
        if (opts.json) console.log(JSON.stringify({ success: true, id: record.id, enabled: record.enabled }))
        else console.log(chalk.green(`${record.enabled ? '已启用' : '已禁用'} ${record.id}`))
      } catch (e) {
        pluginFail(e, opts.json)
      }
    })
}

for (const [name, trusted] of [['trust', true], ['untrust', false]] as const) {
  pluginCmd
    .command(`${name} <id>`)
    .description(trusted ? '信任该插件：调用其工具不再需要 confirm' : '取消信任：调用其工具重新需要 confirm')
    .option('--json', 'JSON 输出')
    .action((id, opts) => {
      try {
        const record = setPluginFlags(id, { trusted })
        if (opts.json) console.log(JSON.stringify({ success: true, id: record.id, trusted: record.trusted }))
        else if (record.trusted) {
          console.log(chalk.yellow(`已信任 ${record.id}：它的工具将被直接调用，不再逐次确认`))
          console.log(chalk.gray('这是你的判断，不是对插件的评估——它仍然是第三方代码。'))
        } else console.log(chalk.green(`已取消信任 ${record.id}`))
      } catch (e) {
        pluginFail(e, opts.json)
      }
    })
}

pluginCmd
  .command('doctor')
  .description('逐个启动插件并报告能否连通、有哪些工具、声明了什么')
  .option('--json', 'JSON 输出')
  .action(async (opts) => {
    const records = listPlugins()
    if (!records.length) {
      if (opts.json) console.log(JSON.stringify({ success: true, total: 0, plugins: [] }))
      else console.log(chalk.gray('还没有注册任何插件'))
      return
    }
    const results = []
    for (const record of records) results.push(await checkPluginHealth(record))
    if (opts.json) {
      console.log(JSON.stringify({ success: true, total: results.length, plugins: results }))
      return
    }
    for (const r of results) {
      const isSource = r.kind === 'knowledge-source'
      const state = !r.enabled
        ? chalk.gray('已禁用')
        : isSource
          ? chalk.green('就绪')
          : r.ok ? chalk.green('可连通') : chalk.red('连不上')
      const tail = !isSource && r.ok ? chalk.gray(`  ${r.toolCount} 个工具`) : ''
      console.log(`${chalk.cyan(r.id)} v${r.version}  ${state}${tail}`)
      if (r.error) console.log(chalk.red(`    ${r.error}`))
      for (const tool of r.tools) console.log(chalk.gray(`    · ${tool}`))
      for (const warning of r.warnings) console.log(chalk.yellow(`    ⚠ ${warning}`))
      if (r.permissions?.writes?.length) {
        console.log(chalk.gray(`    声明会写：${r.permissions.writes.join('、')}（仅为声明，宿主无法核实）`))
      }
    }
    console.log(chalk.gray(`\n注册表：${registryFile()}`))
    console.log(chalk.gray(`插件目录：${pluginRoot()}`))
  })

pluginCmd
  .command('run <id>')
  .description('跑一次知识源插件：产出卡片，并交给知识库消费端读一遍')
  .option('--since <date>', '起始日期 YYYY-MM-DD')
  .option('--until <date>', '结束日期 YYYY-MM-DD')
  .option('--input <dir>', '传给插件的输入目录')
  .option('--out <dir>', '卡片输出目录（缺省 output/<id>-notes）')
  .option('--json', 'JSON 输出')
  .action(async (id, opts) => {
    const record = listPlugins().find(p => p.id === id)
    if (!record) {
      pluginFail(new Error(`没有这个插件：${id}`), opts.json)
      return
    }
    const run = await runKnowledgeSource(record, {
      since: opts.since,
      until: opts.until,
      inputDir: opts.input,
      outDir: opts.out,
    })
    if (!run.ok) {
      const tail = run.stderr.trim().split(/\r?\n/).filter(Boolean).slice(-5).join('\n')
      if (opts.json) {
        console.log(JSON.stringify({
          success: false,
          id,
          error: run.error || '插件失败',
          stderr: tail,
        }))
        process.exit(1)
      }
      console.error(chalk.red(`采集失败：${run.error || '插件失败'}`))
      if (tail) console.error(chalk.gray(tail))
      process.exit(1)
    }

    // 卡片是给消费端读的，不是给人读的：这里真的跑一遍消费端再报结果。
    const lint = await lintCards(run.outDir)
    if (opts.json) {
      console.log(JSON.stringify({
        success: true,
        id,
        outDir: run.outDir,
        cards: lint.cards,
        readable: lint.readable,
        links: lint.links,
        skipped: lint.skipped,
        lintError: lint.error,
      }))
      return
    }
    console.log(`${chalk.green('已采集')} ${chalk.cyan(id)} → ${run.outDir}`)
    if (!lint.ok) {
      console.log(chalk.yellow(`卡片体检没跑成：${lint.error}`))
      return
    }
    console.log(`卡片 ${lint.cards} 张，消费端读出 ${lint.readable} 张（共 ${lint.links} 条概念链接）`)
    for (const skip of lint.skipped.slice(0, 8)) {
      console.log(chalk.yellow(`  ⚠ ${skip.file}：${skip.reason}`))
    }
    if (lint.skipped.length > 8) console.log(chalk.gray(`  …还有 ${lint.skipped.length - 8} 张`))
    if (lint.readable < lint.cards) {
      console.log(chalk.gray('被跳过的卡片不会产生概念页；按上面的原因改插件，然后重跑。'))
    }
  })

const sceneCmd = program
  .command('scene')
  .description('会话场景：按会话生效的提示词预设（绑定 → 关键词 → 上次用过的）')

/** 写场景是**本机文件写**，不是 python mutation：同样两段式，措辞照 todos 那条 */
async function confirmSceneWrite(
  opts: { dryRun?: boolean; yes?: boolean; json?: boolean },
  preview: Record<string, unknown>,
  message: string,
  apply: () => { ok: boolean; reason?: string },
): Promise<void> {
  if (opts.dryRun) {
    if (opts.json) console.log(JSON.stringify({ success: true, dryRun: true, ...preview }))
    else console.log(chalk.cyan('预览：') + message)
    return
  }
  if (!opts.yes) {
    if (opts.json) {
      console.log(JSON.stringify({
        success: false,
        code: 'CONFIRMATION_REQUIRED',
        error: '先使用 --dry-run --json 预览，再由用户确认后使用 --yes --json 执行',
      }))
      process.exit(1)
    }
    const { confirmed } = await inquirer.prompt([{ type: 'confirm', name: 'confirmed', message, default: false }])
    if (!confirmed) {
      console.log(chalk.gray('已取消'))
      return
    }
  }
  const result = apply()
  if (result.ok) assistantScenes.save()
  const saved = result.ok && !assistantScenes.lastSaveError
  if (opts.json) {
    if (!result.ok) {
      console.log(JSON.stringify({ success: false, code: 'SCENE_OPERATION_FAILED', error: result.reason }))
      process.exit(1)
    }
    // 写失败要说出来：`save()` 不抛异常，代价是必须有地方把它讲出来
    console.log(JSON.stringify({
      success: saved,
      ...(saved ? {} : { code: 'SCENE_SAVE_FAILED', error: assistantScenes.lastSaveError }),
      ...preview,
    }))
    if (!saved) process.exit(1)
    return
  }
  if (!result.ok) {
    console.log(chalk.red(`✗ ${result.reason}`))
    process.exit(1)
  }
  if (!saved) console.log(chalk.red(`⚠ 已改动内存，但落盘失败：${assistantScenes.lastSaveError}`))
  else console.log(chalk.green('✓ 完成'))
}

sceneCmd
  .command('list')
  .description('列出所有场景')
  .option('--json', 'JSON 输出')
  .action((opts) => {
    const scenes = assistantScenes.list()
    if (opts.json) {
      console.log(JSON.stringify({ success: true, total: scenes.length, scenes }))
      return
    }
    if (!scenes.length) {
      console.log(chalk.gray('还没有场景。加一个：'))
      console.log(chalk.gray('  weflow-cli scene add --id 日报 --keywords 日报,推文 --instruction "按主题分组" --dry-run'))
      return
    }
    for (const s of scenes) {
      console.log(`${s.enabled ? chalk.cyan(s.id) : chalk.gray(s.id + ' [已停用]')}  ${s.name}`)
      if (s.keywords.length) console.log(chalk.gray(`    关键词：${s.keywords.join('、')}`))
      if (s.instruction) console.log(chalk.gray(`    ${s.instruction.split('\n')[0].slice(0, 80)}`))
    }
  })

sceneCmd
  .command('show')
  .argument('<id>', '场景 id')
  .description('打印一个场景的全部字段')
  .option('--json', 'JSON 输出')
  .action((id, opts) => {
    const scene = assistantScenes.get(id)
    if (!scene) {
      if (opts.json) console.log(JSON.stringify({ success: false, code: 'SCENE_NOT_FOUND', error: `没有场景「${id}」` }))
      else console.log(chalk.red(`没有场景「${id}」`))
      process.exit(1)
    }
    if (opts.json) {
      console.log(JSON.stringify({ success: true, scene }))
      return
    }
    console.log(`id        ${scene.id}`)
    console.log(`名称      ${scene.name}`)
    console.log(`状态      ${scene.enabled ? '启用' : '已停用'}`)
    console.log(`关键词    ${scene.keywords.join('、') || '（无）'}`)
    console.log(`所需技能  ${scene.skills.join('、') || '（无）'}`)
    console.log(`附加指令  ${scene.instruction || '（无）'}`)
    if (scene.outputSpec) console.log(`输出规范  ${scene.outputSpec}`)
  })

sceneCmd
  .command('add')
  .description('新增一个场景')
  .requiredOption('--id <id>', '场景 id（字母数字开头，可用 . _ -）')
  .option('--name <name>', '显示名（默认用 id）')
  .option('--keywords <list>', '关键词，逗号分隔')
  .option('--instruction <text>', '附加指令（长文本用 --from-file）')
  .option('--from-file <path>', '从文件读附加指令（多行中文走这条）')
  .option('--output-spec <text>', '输出规范')
  .option('--skills <list>', '所需技能 id，逗号分隔')
  .option('--dry-run', '仅预览，不写入')
  .option('--yes', '确认写入')
  .option('--json', 'JSON 输出')
  .action(async (opts) => {
    const id = String(opts.id || '').trim()
    const idError = validateSceneId(id)
    if (idError) {
      if (opts.json) console.log(JSON.stringify({ success: false, code: 'INVALID_SCENE_ID', error: idError }))
      else console.log(chalk.red(idError))
      process.exit(1)
    }
    let instruction = String(opts.instruction || '')
    if (opts.fromFile) {
      const path = String(opts.fromFile)
      if (!existsSync(path)) {
        if (opts.json) console.log(JSON.stringify({ success: false, code: 'FILE_NOT_FOUND', error: `读不到 ${path}` }))
        else console.log(chalk.red(`读不到 ${path}`))
        process.exit(1)
      }
      instruction = readFileSync(path, 'utf8')
    }
    const splitList = (v: unknown): string[] => String(v || '').split(/[,;]/).map(s => s.trim()).filter(Boolean)
    const scene: Scene = {
      id,
      name: String(opts.name || '').trim() || id,
      keywords: splitList(opts.keywords),
      instruction,
      outputSpec: String(opts.outputSpec || ''),
      skills: splitList(opts.skills),
      enabled: true,
    }
    await confirmSceneWrite(opts, { action: 'scene.add', scene: { ...scene, instruction: `(${instruction.length} 字)` } },
      `确认新增场景「${scene.name}」？`, () => assistantScenes.add(scene))
  })

sceneCmd
  .command('remove')
  .argument('<id>', '场景 id')
  .description('删除一个场景（连同指向它的绑定）')
  .option('--dry-run', '仅预览，不删除')
  .option('--yes', '确认删除')
  .option('--json', 'JSON 输出')
  .action(async (id, opts) => {
    const scene = assistantScenes.get(id)
    if (!scene) {
      if (opts.json) console.log(JSON.stringify({ success: false, code: 'SCENE_NOT_FOUND', error: `没有场景「${id}」` }))
      else console.log(chalk.red(`没有场景「${id}」`))
      process.exit(1)
    }
    await confirmSceneWrite(opts, { action: 'scene.remove', id }, `确认删除场景「${scene.name}」？`,
      () => { assistantScenes.remove(id); return { ok: true } })
  })

const toggleScene = (on: boolean) => async (id: string, opts: { dryRun?: boolean; yes?: boolean; json?: boolean }) => {
  const scene = assistantScenes.get(id)
  if (!scene) {
    if (opts.json) console.log(JSON.stringify({ success: false, code: 'SCENE_NOT_FOUND', error: `没有场景「${id}」` }))
    else console.log(chalk.red(`没有场景「${id}」`))
    process.exit(1)
  }
  await confirmSceneWrite(opts, { action: on ? 'scene.enable' : 'scene.disable', id },
    `确认${on ? '启用' : '停用'}场景「${scene.name}」？`,
    () => ({ ok: assistantScenes.setEnabled(id, on) }))
}

sceneCmd.command('enable')
  .argument('<id>', '场景 id')
  .description('启用一个场景')
  .option('--dry-run', '仅预览').option('--yes', '确认').option('--json', 'JSON 输出')
  .action(toggleScene(true))

sceneCmd.command('disable')
  .argument('<id>', '场景 id')
  .description('停用一个场景（它不再参与匹配）')
  .option('--dry-run', '仅预览').option('--yes', '确认').option('--json', 'JSON 输出')
  .action(toggleScene(false))

sceneCmd
  .command('bind')
  .argument('<conversation>', '会话 id（微信里就是 conversationId；本机面板用它的记忆桶）')
  .requiredOption('--scene <id>', '要绑定的场景 id')
  .description('把某个场景固定绑到一个会话')
  .option('--dry-run', '仅预览').option('--yes', '确认').option('--json', 'JSON 输出')
  .action(async (conversation, opts) => {
    const id = String(opts.scene || '').trim()
    await confirmSceneWrite(opts, { action: 'scene.bind', conversation, scene: id },
      `确认把场景「${id}」绑到会话 ${conversation}？`,
      () => assistantScenes.bind(conversation, id))
  })

sceneCmd
  .command('unbind')
  .argument('<conversation>', '会话 id')
  .description('解绑：这个会话回到按关键词自动挑')
  .option('--dry-run', '仅预览').option('--yes', '确认').option('--json', 'JSON 输出')
  .action(async (conversation, opts) => {
    await confirmSceneWrite(opts, { action: 'scene.unbind', conversation },
      `确认解绑会话 ${conversation}？`,
      () => assistantScenes.bind(conversation, null))
  })

// ==================== assistant (第二大脑持久化 Agent) ====================
const assistantCmd = program
  .command('assistant')
  .description('第二大脑助手 — 微信里的持久化 AI Agent (常驻 + 记忆 + DeepSeek)')

assistantCmd
  .command('start')
  .description('后台启动守护进程 (重启电脑前持续在线)')
  .option('--dry-run', '仅预览，不启动守护进程')
  .option('--yes', '确认启动')
  .option('--json', '输出 JSON 格式；启动仍需 --yes')
  .action(async (opts) => {
    const preview = { action: 'assistant.start', sideEffects: ['background-process', 'message-processing', 'possible-ai-usage'] }
    if (opts.dryRun) {
      if (opts.json) console.log(JSON.stringify({ success: true, dryRun: true, ...preview }))
      else console.log(chalk.cyan('将后台启动第二大脑守护进程'))
      return
    }
    if (opts.json && !opts.yes) {
      console.log(JSON.stringify({ success: false, code: 'CONFIRMATION_REQUIRED', error: '使用 --yes 确认启动助手', ...preview }))
      process.exit(1)
    }
    const { startDaemon } = await import('../src/services/assistantDaemon.js')
    const r = await startDaemon()
    if (opts.json) {
      console.log(JSON.stringify(r.started
        ? { success: true, started: true, pid: r.pid, ...preview }
        : { success: false, code: 'ASSISTANT_START_FAILED', started: false, error: '助手启动失败或已经运行', ...preview }))
      if (!r.started) process.exit(1)
      return
    }
    if (r.started) {
      console.log(chalk.green(`✓ 守护进程已启动 (pid ${r.pid})`))
      console.log(chalk.gray('  在微信 ClawBot 对话里直接说话即可'))
      console.log(chalk.gray('  日志: weflow-cli assistant log'))
      console.log(chalk.gray('  停止: weflow-cli assistant stop'))
    } else {
      console.log(chalk.yellow(`⚠ ${r.error}`))
    }
  })

assistantCmd
  .command('stop')
  .description('停止守护进程')
  .option('--dry-run', '仅预览，不停止守护进程')
  .option('--yes', '确认停止')
  .option('--json', '输出 JSON 格式；停止仍需 --yes')
  .action(async (opts) => {
    const preview = { action: 'assistant.stop', sideEffects: ['background-process'] }
    if (opts.dryRun) {
      if (opts.json) console.log(JSON.stringify({ success: true, dryRun: true, ...preview }))
      else console.log(chalk.cyan('将停止第二大脑守护进程'))
      return
    }
    if (opts.json && !opts.yes) {
      console.log(JSON.stringify({ success: false, code: 'CONFIRMATION_REQUIRED', error: '使用 --yes 确认停止助手', ...preview }))
      process.exit(1)
    }
    const { stopDaemon } = await import('../src/services/assistantDaemon.js')
    const r = stopDaemon()
    if (opts.json) {
      console.log(JSON.stringify({ success: r.stopped, stopped: r.stopped, code: r.stopped ? null : 'ASSISTANT_STOP_FAILED', ...preview }))
      if (!r.stopped) process.exit(1)
      return
    }
    console.log(r.stopped ? chalk.green(`✓ ${r.message}`) : chalk.yellow(`⚠ ${r.message}`))
  })

assistantCmd
  .command('status')
  .description('查看运行状态')
  .option('--json', '输出 JSON 格式，不返回令牌、成员或日志内容')
  .action(async (opts) => {
    const { isDaemonAlive, tailLog, rotateLogIfNeeded } = await import('../src/services/assistantDaemon.js')
    const { alive, pid } = isDaemonAlive()
    const token = configService.get('wechatOcToken')
    const aiKey = resolveAiKey()
    const { privacyGate } = await import('../src/services/assistantPrivacy.js')
    const { readEndpoint } = await import('../src/panel/endpoint.js')
    const wl = String(configService.get('assistantWhitelist') || '').trim()
    const groups = String(configService.get('assistantGroupWhitelist') || '').trim()
    // 端点是**运行态**的权威来源：它由守护进程原子写出，而且读取端会探活（进程没了就当没有）。
    // 它能回答一个配置回答不了的问题：**通道到底接上了没有**。
    // `messageChannelLoggedIn` 说的只是"配了 token 吗"——token 配了而进程以本机模式跑着，
    // 这两个字段会一个 true 一个 false，今天完全没有别的办法区分。
    const endpoint = alive ? readEndpoint() : null
    if (opts.json) {
      console.log(JSON.stringify({
        success: true,
        daemonRunning: alive,
        messageChannelLoggedIn: !!token,
        channelActive: !!endpoint && endpoint.channel === 'wechat',
        mode: endpoint ? endpoint.channel : null,
        panelPort: endpoint ? endpoint.port : null,
        memoryBucket: endpoint ? endpoint.memoryBucket : null,
        aiConfigured: privacyGate.isLocalInference() || !!aiKey,
        localInference: privacyGate.isLocalInference(),
        privacyMode: privacyGate.mode(),
        whitelistCount: wl ? wl.split(/[,;\s]+/).filter(Boolean).length : 0,
        groupWhitelistCount: groups ? groups.split(/[,;\s]+/).filter(Boolean).length : 0,
        groupMentionRequired: configService.get('assistantGroupRequireMention') !== 'false',
      }, null, 2))
      return
    }
    console.log(`守护进程: ${alive ? chalk.green(`运行中 (pid ${pid})`) : chalk.gray('未运行')}`)
    console.log(`消息通道: ${token ? chalk.green('已登录') : chalk.red('未登录 (先 login-wechat)')}`)
    if (endpoint) {
      console.log(`  └ 实际接入: ${endpoint.channel === 'wechat' ? chalk.green('微信') : chalk.yellow('仅本机入口')}`
        + `｜本机入口 http://127.0.0.1:${endpoint.port}｜记忆桶 ${endpoint.memoryBucket}`)
    } else if (alive) {
      console.log(chalk.gray('  └ 本机入口未启动（看 assistant log 里的“本机入口启动失败”）'))
    }
    console.log(`LLM 大脑: ${aiKey ? chalk.green('DeepSeek 已配置') : chalk.gray('未配置 (config set deepseekApiKey)')}`)
    console.log(`隐私模式: ${chalk.cyan(privacyGate.mode())}${privacyGate.isLocalInference() ? chalk.green(' (本地推理, 数据不出境)') : chalk.gray(' (工具结果脱敏后出境)')}`)
    console.log(`白名单: ${wl ? chalk.green(`${wl.split(/[,;\s]+/).filter(Boolean).length} 人`) : chalk.red('未设置 (默认拒绝所有人; config set assistantWhitelist "<@im.wechat ID>")')}`)
    console.log(`群聊实验: ${groups ? chalk.yellow(`${groups.split(/[,;\s]+/).filter(Boolean).length} 个已配置，等待上游群事件`) : chalk.gray('未配置（默认拒绝所有群）')}`)
    console.log(`群聊 @ 门槛: ${configService.get('assistantGroupRequireMention') === 'false' ? chalk.red('已关闭') : chalk.green('已开启')}`)
    console.log(`用量护栏: ${chalk.cyan('100 条/天')} (微信内发「记忆」可查今日用量)`)
    rotateLogIfNeeded()
    console.log(chalk.cyan('\n最近日志:'))
    console.log(chalk.gray(tailLog(10)))
  })

assistantCmd
  .command('log')
  .description('查看守护进程日志 (最近 N 行)')
  .option('-n, --lines <number>', '行数', '30')
  .option('--json', '仅输出日志可用状态和行数，不返回日志内容')
  .action(async (opts) => {
    const { tailLog } = await import('../src/services/assistantDaemon.js')
    const lines = parseCliInteger(opts.lines, 'lines', 1, 1000, opts.json)
    const content = tailLog(lines)
    if (opts.json) {
      const available = !content.startsWith('(')
      console.log(JSON.stringify({
        success: true,
        available,
        requestedLines: lines,
        returnedLineCount: available ? content.split(/\r?\n/).length : 0,
      }))
      return
    }
    console.log(content)
  })

assistantCmd
  .command('trace')
  .description('看助手最近几轮是怎么走的（判断层 → 工具 → 答复），含模型返回的推理内容')
  .option('-n, --last <number>', '看最近几轮', '3')
  .option('--json', '输出结构化轨迹')
  .action(async (opts) => {
    const { readTurns, describeTurn, traceFile } = await import('../src/services/assistantTrace.js')
    const count = parseCliInteger(opts.last, 'last', 1, 50, opts.json)
    const turns = readTurns(count)
    if (opts.json) {
      console.log(JSON.stringify({ success: true, file: traceFile(), count: turns.length, turns }))
      return
    }
    if (!turns.length) {
      console.log('还没有轨迹。助手收到消息之后才会有；文件：' + traceFile())
      return
    }
    console.log(traceFile())
    for (const turn of turns) {
      for (const line of describeTurn(turn)) console.log(line)
      console.log('')
    }
  })

assistantCmd
  .command('run')
  .description('前台运行 (调试用; 常驻请用 start)')
  .option('--dry-run', '仅预览，不连接消息通道或调用 AI')
  .option('--yes', '确认启动人工前台调试')
  .option('--json', '输出机器可读预览；实际调试必须在交互终端执行')
  .action(async (opts) => {
    const preview = {
      success: true,
      dryRun: true,
      action: 'assistant.run',
      interactiveRequired: true,
      handlesMessages: true,
      mayUseAi: true,
    }
    if (opts.dryRun) {
      if (opts.json) console.log(JSON.stringify(preview))
      else console.log(chalk.cyan('前台助手预览：将持续处理消息并可能调用 AI，需 Ctrl+C 退出'))
      return
    }
    if (opts.json) {
      console.log(JSON.stringify({ ...preview, success: false, dryRun: false, code: 'INTERACTIVE_REQUIRED' }))
      process.exit(1)
    }
    if (!opts.yes) {
      const { confirmed } = await inquirer.prompt([{
        type: 'confirm',
        name: 'confirmed',
        message: '确认在当前终端运行助手调试流程？',
        default: false,
      }])
      if (!confirmed) {
        console.log(chalk.gray('已取消'))
        return
      }
    }
    const { AssistantService } = await import('../src/services/assistantService.js')
    const assistant = new AssistantService()
    console.log(chalk.cyan('第二大脑前台运行中... (Ctrl+C / systemctl stop 退出)'))
    // Linux 上 `systemctl stop` / `kill` 发的是 **SIGTERM**，默认行为是直接终止：
    // 不跑清理，日志里也没有一句"收到信号"。两个信号都走有序关闭，
    // 这样 systemd 的日志能看出"是被停掉的"，端点文件与 pid 文件也会被清掉。
    let stopping = false
    for (const sig of ['SIGINT', 'SIGTERM'] as const) {
      process.on(sig, async () => {
        if (stopping) return
        stopping = true
        console.log(chalk.gray(`\n收到 ${sig}，正在停止助手...`))
        try {
          await assistant.stop()
        } catch (e: any) {
          console.error(chalk.gray(`停止时出错（继续退出）: ${e?.message || e}`))
        }
        // 自己清理 pid / 端点文件：`assistant stop` 那条路是外部替我们删的，
        // 而 systemctl/kill 发 SIGTERM 时没有外部那一方。
        try {
          const { cleanupDaemonFiles } = await import('../src/services/assistantDaemon.js')
          cleanupDaemonFiles()
        } catch { /* 清理失败不影响退出 */ }
        process.exit(0)
      })
    }
    await assistant.start((line) => console.log(chalk.gray(line)))
  })

/**
 * 本机面板：不登录微信也能跟助手说话的入口。
 *
 * **它只是客户端**：消息走守护进程的回环端点，于是两个入口共用一个大脑
 * （同一份记忆、同一条配额、同一条串行队列）。面板自己起一个 `AssistantService` 会变成
 * 第二个大脑——那是这个功能最容易走错的一步。
 */
program
  .command('panel')
  .description('打开本机面板窗口 (Electron 悬浮球；没有 Electron 就降级用 Edge --app)')
  .option('--status', '只看状态，不打开窗口')
  .option('--ask <text>', '在命令行里问一句（面板减去像素）')
  .option('--scene <id>', '只给本次 --ask 使用的场景，不改变会话绑定')
  .option('--dry-run', '仅预览，不启动窗口或守护进程')
  .option('--yes', '确认打开')
  .option('--json', '输出 JSON 格式')
  .action(async (opts) => {
    const { readEndpoint, endpointFile } = await import('../src/panel/endpoint.js')
    const { panelStatus, panelAsk, panelPair } = await import('../src/panel/client.js')

    if (opts.scene !== undefined && opts.ask === undefined) {
      if (opts.json) console.log(JSON.stringify({ success: false, code: 'INVALID_ARGUMENT', error: '--scene 只能与 --ask 一起使用' }))
      else console.log(chalk.red('--scene 只能与 --ask 一起使用'))
      process.exit(1)
    }

    // ---------------------------------------------------------- 只读：状态
    if (opts.status) {
      const endpoint = readEndpoint()
      if (!endpoint) {
        if (opts.json) console.log(JSON.stringify({ success: false, code: 'PANEL_NOT_RUNNING', error: '本机入口没在运行（先 weflow-cli assistant start）' }))
        else console.log(chalk.gray('本机入口没在运行（先 weflow-cli assistant start）'))
        process.exit(1)
      }
      const r = await panelStatus(endpoint)
      if (opts.json) {
        console.log(JSON.stringify(r.ok
          ? { success: true, port: endpoint.port, ...r.data }
          : { success: false, code: r.code }))
        return
      }
      if (!r.ok) { console.log(chalk.yellow(`读状态失败: ${r.code}`)); return }
      const d = r.data
      console.log(`本机入口: ${chalk.green(`http://127.0.0.1:${endpoint.port}`)}`)
      console.log(`接入: ${d.channelActive ? '微信 + 本机' : '仅本机入口'}｜今日 ${d.quota.used}/${d.quota.limit}｜LLM ${d.aiConfigured ? '已配置' : '未配置'}`)
      console.log(chalk.gray(`记忆桶: ${d.memoryBucket}`))
      if (d.memoryNote) console.log(chalk.gray(`  ${d.memoryNote}`))
      return
    }

    // ---------------------------------------------------------- 在命令行里问一句
    if (opts.ask !== undefined) {
      const text = String(opts.ask || '').trim()
      if (!text) {
        if (opts.json) console.log(JSON.stringify({ success: false, code: 'INVALID_ARGUMENT', error: '--ask 不能为空' }))
        else console.log(chalk.red('--ask 不能为空'))
        process.exit(1)
      }
      const sceneId = String(opts.scene ?? '').trim()
      if (opts.scene !== undefined && !sceneId) {
        if (opts.json) console.log(JSON.stringify({ success: false, code: 'INVALID_ARGUMENT', error: '--scene 不能为空' }))
        else console.log(chalk.red('--scene 不能为空'))
        process.exit(1)
      }
      if (opts.json && !opts.yes) {
        console.log(JSON.stringify({ success: false, code: 'CONFIRMATION_REQUIRED', error: '这会真的问助手（可能调用 AI 并占用配额），用 --yes 确认' }))
        process.exit(1)
      }
      const endpoint = readEndpoint()
      if (!endpoint) {
        if (opts.json) console.log(JSON.stringify({ success: false, code: 'PANEL_NOT_RUNNING', error: '本机入口没在运行（先 weflow-cli assistant start）' }))
        else console.log(chalk.yellow('本机入口没在运行（先 weflow-cli assistant start）'))
        process.exit(1)
      }
      const r = await panelAsk(endpoint, text, sceneId || undefined)
      if (opts.json) {
        console.log(JSON.stringify(r.ok
          ? { success: true, status: r.data.status, reply: r.data.reply }
          : { success: false, code: r.code, error: r.error }))
        if (!r.ok) process.exit(1)
        return
      }
      console.log(r.ok ? r.data.reply : chalk.yellow(`没成: ${r.code}`))
      return
    }

    // ---------------------------------------------------------- 打开窗口
    const { resolveElectronBinary, resolveBrowserBinary, electronLaunchArgs,
            browserLaunchArgs, browserProfileDir } = await import('../src/panel/launch.js')
    const { isDaemonAlive, startDaemon } = await import('../src/services/assistantDaemon.js')
    const { weflowHome } = await import('../src/panel/endpoint.js')

    const electron = resolveElectronBinary({
      packageRoot: resolvePackageRoot(),
      localAppData: process.env.LOCALAPPDATA,
      programFiles: process.env.ProgramFiles,
    })
    const browser = electron.found ? { found: null } : resolveBrowserBinary({
      programFiles: process.env.ProgramFiles,
      programFilesX86: process.env['ProgramFiles(x86)'],
      localAppData: process.env.LOCALAPPDATA,
    })
    const shell: 'electron' | 'browser' | 'none' = electron.found ? 'electron' : browser.found ? 'browser' : 'none'
    const running = isDaemonAlive().alive

    const preview = {
      action: 'panel.open',
      shell,
      daemonRunning: running,
      // 明确声明后果：面板会需要一个守护进程；关掉窗口**不会**顺手把它停掉
      willStartDaemon: !running,
      keepsRunningAfterClose: true,
      endpointFile: endpointFile(),
    }
    if (opts.dryRun) {
      if (opts.json) console.log(JSON.stringify({ success: true, dryRun: true, ...preview }))
      else console.log(chalk.cyan(`将打开面板（${shell === 'none' ? '没有可用的窗口程序，只会打印地址' : shell}）`
        + `${running ? '' : '，并启动本机助手守护进程'}`))
      return
    }
    if (opts.json && !opts.yes) {
      console.log(JSON.stringify({ success: false, code: 'CONFIRMATION_REQUIRED', error: '使用 --yes 确认打开面板', ...preview }))
      process.exit(1)
    }

    // 守护进程没起来就先起，并**轮询到真的就绪**——不要相信 spawn 的返回值
    // （`startDaemon` 里没有 `child.unref()`，stdio 又是 pipe；照抄 daily-reader 的 30×100ms 循环）
    if (!running) {
      const started = await startDaemon()
      if (!started.started && !started.error?.includes('已经运行')) {
        const msg = `本机助手启动失败: ${started.error ?? '未知原因'}`
        if (opts.json) console.log(JSON.stringify({ success: false, code: 'ASSISTANT_START_FAILED', error: msg, ...preview }))
        else console.log(chalk.red(msg))
        process.exit(1)
      }
    }
    let endpoint = readEndpoint()
    for (let attempt = 0; attempt < 30 && !endpoint; attempt++) {
      await new Promise((resolve) => setTimeout(resolve, 100))
      endpoint = readEndpoint()
    }
    if (!endpoint) {
      const msg = '本机入口还没就绪（看 weflow-cli assistant log 里的“本机入口启动失败”，端口可能被占）'
      if (opts.json) console.log(JSON.stringify({ success: false, code: 'PANEL_NOT_READY', error: msg, ...preview }))
      else console.log(chalk.red(msg))
      process.exit(1)
    }

    const { spawn } = await import('child_process')
    let launched: string
    let url: string | null = null
    if (electron.found) {
      // argv 里**什么都没有**：不带 token、不带端口、不带 URL（命令行对同机任何进程可见）
      const child = spawn(electron.found, electronLaunchArgs(join(resolvePackageRoot(), 'resources', 'panel')), {
        detached: true, stdio: 'ignore', windowsHide: true,
      })
      child.unref()
      launched = 'electron'
    } else if (browser.found) {
      // 浏览器那条路只能靠一次性口令：它单次使用、60 秒过期，所以进命令行与浏览器历史都不算泄漏
      const pair = await panelPair(endpoint)
      if (!pair.ok) {
        const msg = `换一次性口令失败: ${pair.code}`
        if (opts.json) console.log(JSON.stringify({ success: false, code: 'PAIR_FAILED', error: msg, ...preview }))
        else console.log(chalk.red(msg))
        process.exit(1)
      }
      url = pair.data.url
      const child = spawn(browser.found, browserLaunchArgs({ url, profileDir: browserProfileDir(weflowHome()) }), {
        detached: true, stdio: 'ignore', windowsHide: true,
      })
      child.unref()
      launched = 'browser'
    } else {
      // 两条路都没有：**别静默什么都不做**，把地址交出去
      const pair = await panelPair(endpoint)
      url = pair.ok ? pair.data.url : `http://127.0.0.1:${endpoint.port}/panel`
      launched = 'none'
    }

    if (opts.json) {
      // 展开在前、实际结果在后：`preview.shell` 是"打算用哪个"，这里是"实际用了哪个"，
      // 两者可能不同（例如打算用 Electron 但 spawn 之后没起来）——以后者为准
      console.log(JSON.stringify({ ...preview, success: true, shell: launched, port: endpoint.port, url }))
      return
    }
    if (launched === 'electron') {
      console.log(chalk.green(`✓ 面板已启动（记忆桶 ${endpoint.memoryBucket}）`))
      console.log(chalk.gray('  关掉窗口只是隐藏；助手仍在后台跑，要停它用 weflow-cli assistant stop'))
    } else if (launched === 'browser') {
      console.log(chalk.green('✓ 已用浏览器打开面板窗口'))
      console.log(chalk.yellow('  注意：这条路给不了悬浮球——浏览器窗口不能无边框/置顶，也没有托盘与快捷键。'))
      console.log(chalk.gray('  想要真·悬浮球：npm i -g electron 之后再跑一次'))
    } else {
      console.log(chalk.yellow('没找到 Electron，也没找到 Edge/Chrome。自己打开这个地址即可：'))
      console.log(chalk.cyan(`  ${url}`))
      console.log(chalk.gray('  想要悬浮球：npm i -g electron'))
    }
  })

program
  .command('daily-stats')
  .description('统计公众号推送频率与日报处理频率')
  .option('--days <number>', '统计最近多少天', '30')
  .option('--limit <number>', '最多显示多少个公众号', '30')
  .option('--json', '输出 JSON 格式')
  .action(async (opts) => {
    const { execFile } = await import('child_process')
    const { promisify } = await import('util')
    const execFileAsync = promisify(execFile)
    const script = join(resolvePackageRoot(), 'scripts', 'daily_stats.py')
    const days = parseCliInteger(opts.days, 'days', 1, 3650, opts.json)
    const limit = parseCliInteger(opts.limit, 'limit', 1, 1000, opts.json)

    try {
      const args = [script, '--days', String(days), '--limit', String(limit)]
      if (opts.json) args.push('--json')
      const { stdout } = await execFileAsync(getPythonCommand(), args, {
        timeout: 300_000,
        maxBuffer: 10 * 1024 * 1024,
        env: pythonProcessEnv(),
      })
      console.log(stdout)
    } catch (e: any) {
      if (opts.json) {
        console.log(JSON.stringify({
          success: false,
          code: 'DAILY_STATS_FAILED',
          error: '公众号统计不可用，请运行 check --json 检查配置和依赖',
        }))
        process.exit(1)
      }
      console.error(chalk.red(`\n${safeSubprocessError(e, '统计失败')}`))
      process.exit(1)
    }
  })

// ==================== bonds ====================
program
  .command('bonds')
  .description('关系温度：谁在冷却、谁在变热、谁只有微信这一条线（只读本地库，不联网、不调模型）')
  .option('--days <number>', '看最近多少天', '365')
  .option('--limit <number>', '最多扫几个会话', '400')
  .option('--top <number>', '每组列几条', '12')
  .option('--skip <name>', '排除某个名字或 id（可重复）', (value: string, acc: string[]) => {
    acc.push(value)
    return acc
  }, [] as string[])
  .option('--json', '输出 JSON 格式')
  .action(async (opts) => {
    const { execFile } = await import('child_process')
    const { promisify } = await import('util')
    const execFileAsync = promisify(execFile)
    const script = join(resolvePackageRoot(), 'scripts', 'bonds.py')
    const days = parseCliInteger(opts.days, 'days', 1, 3650, opts.json)
    const limit = parseCliInteger(opts.limit, 'limit', 1, 5000, opts.json)
    const top = parseCliInteger(opts.top, 'top', 1, 200, opts.json)

    try {
      const args = [script, '--days', String(days), '--limit', String(limit), '--top', String(top)]
      for (const name of (opts.skip as string[]) || []) args.push('--skip', name)
      if (opts.json) args.push('--json')
      const { stdout } = await execFileAsync(getPythonCommand(), args, {
        timeout: 300_000,
        maxBuffer: 10 * 1024 * 1024,
        env: pythonProcessEnv(),
      })
      console.log(stdout)
    } catch (e: any) {
      if (opts.json) {
        console.log(JSON.stringify({
          success: false,
          code: 'BONDS_FAILED',
          error: '关系温度不可用，请运行 check --json 检查配置和依赖',
        }))
        process.exit(1)
      }
      console.error(chalk.red(`\n${safeSubprocessError(e, '统计失败')}`))
      process.exit(1)
    }
  })

// ==================== today（那年今日）====================
program
  .command('today')
  .description('那年今日：几年前的今天你在聊什么（只读本地库，不联网）')
  .option('--years <list>', '往前看几年，逗号分隔', '1,3,5')
  .option('--talker <name>', '只看某个会话（wxid 或昵称）')
  .option('--limit <number>', '每天最多列几条', '6')
  .option('--json', '输出 JSON 格式')
  .action(async (opts) => {
    const { execFile } = await import('child_process')
    const { promisify } = await import('util')
    const execFileAsync = promisify(execFile)
    const script = join(resolvePackageRoot(), 'scripts', 'on_this_day.py')
    const limit = parseCliInteger(opts.limit, 'limit', 1, 200, opts.json)

    try {
      const args = [script, '--years', String(opts.years || '1,3,5'), '--limit', String(limit)]
      if (opts.json) args.push('--json')
      // D-020：会话标识不进子进程 argv（进程列表里看得见），走 WEFLOW_TALKER。
      const { stdout } = await execFileAsync(getPythonCommand(), args, {
        timeout: 300_000,
        maxBuffer: 10 * 1024 * 1024,
        env: createPythonProcessEnv(opts.talker ? { WEFLOW_TALKER: String(opts.talker) } : {}),
      })
      console.log(stdout)
    } catch (e: any) {
      if (opts.json) {
        console.log(JSON.stringify({
          success: false,
          code: 'TODAY_FAILED',
          error: '那年今日不可用，请运行 check --json 检查配置和依赖',
        }))
        process.exit(1)
      }
      console.error(chalk.red(`\n${safeSubprocessError(e, '回溯失败')}`))
      process.exit(1)
    }
  })

// ==================== network（人脉图谱）====================
program
  .command('network')
  .description('人脉图谱：共同群、谁能做引荐人（只读 contact.db，不碰聊天内容）')
  .option('--groups', '列群概览（成员数）')
  .option('--with <name>', '我和他共同在哪些群')
  .option('--intro <name>', '谁适合把我介绍给他')
  .option('--json', '输出 JSON 格式')
  .action(async (opts) => {
    const { execFile } = await import('child_process')
    const { promisify } = await import('util')
    const execFileAsync = promisify(execFile)
    const script = join(resolvePackageRoot(), 'scripts', 'network.py')

    try {
      const args = [script]
      if (opts.groups) args.push('--groups')
      if (opts.with) args.push('--with', String(opts.with))
      if (opts.intro) args.push('--intro', String(opts.intro))
      if (opts.json) args.push('--json')
      if (args.length === 1) {
        console.error(chalk.yellow('\n用法：network --groups | --with <名字> | --intro <名字>'))
        process.exit(1)
      }
      const { stdout } = await execFileAsync(getPythonCommand(), args, {
        timeout: 300_000,
        maxBuffer: 10 * 1024 * 1024,
        env: pythonProcessEnv(),
      })
      console.log(stdout)
    } catch (e: any) {
      if (opts.json) {
        console.log(JSON.stringify({
          success: false,
          code: 'NETWORK_FAILED',
          error: '人脉图谱不可用，请运行 check --json 检查配置和依赖',
        }))
        process.exit(1)
      }
      console.error(chalk.red(`\n${safeSubprocessError(e, '查询失败')}`))
      process.exit(1)
    }
  })

// ==================== promises（欠账清单）====================
program
  .command('promises')
  .description('欠账清单：我说过要给谁做什么、后来做了没有（规则判定，带原话与后续证据）')
  .option('--days <number>', '看最近多少天', '60')
  .option('--talker <name>', '只看某个会话')
  .option('--limit <number>', '最多列几条', '30')
  .option('--json', '输出 JSON 格式')
  .action(async (opts) => {
    const { execFile } = await import('child_process')
    const { promisify } = await import('util')
    const execFileAsync = promisify(execFile)
    const script = join(resolvePackageRoot(), 'scripts', 'promises.py')
    const days = parseCliInteger(opts.days, 'days', 1, 3650, opts.json)
    const limit = parseCliInteger(opts.limit, 'limit', 1, 500, opts.json)

    try {
      const args = [script, '--days', String(days), '--limit', String(limit)]
      if (opts.json) args.push('--json')
      // D-020：同 today——会话标识走 WEFLOW_TALKER，不进 argv。
      const { stdout } = await execFileAsync(getPythonCommand(), args, {
        timeout: 300_000,
        maxBuffer: 10 * 1024 * 1024,
        env: createPythonProcessEnv(opts.talker ? { WEFLOW_TALKER: String(opts.talker) } : {}),
      })
      console.log(stdout)
    } catch (e: any) {
      if (opts.json) {
        console.log(JSON.stringify({
          success: false,
          code: 'PROMISES_FAILED',
          error: '欠账清单不可用，请运行 check --json 检查配置和依赖',
        }))
        process.exit(1)
      }
      console.error(chalk.red(`\n${safeSubprocessError(e, '统计失败')}`))
      process.exit(1)
    }
  })

// ==================== leads（线索雷达）====================
program
  .command('leads')
  .description('线索雷达：聊天里的报价/采购/合作/需求信号，带原话与跟进状态（规则判定，不调模型）')
  .option('--days <number>', '看最近多少天', '30')
  .option('--min-score <number>', '最低分，4 分以上更接近真实生意', '2')
  .option('--limit <number>', '最多列几条', '20')
  .option('--json', '输出 JSON 格式')
  .action(async (opts) => {
    const { execFile } = await import('child_process')
    const { promisify } = await import('util')
    const execFileAsync = promisify(execFile)
    const script = join(resolvePackageRoot(), 'scripts', 'leads.py')
    const days = parseCliInteger(opts.days, 'days', 1, 3650, opts.json)
    const minScore = parseCliInteger(opts.minScore, 'min-score', 1, 50, opts.json)
    const limit = parseCliInteger(opts.limit, 'limit', 1, 500, opts.json)

    try {
      const args = [script, '--days', String(days), '--min-score', String(minScore),
                    '--limit', String(limit)]
      if (opts.json) args.push('--json')
      const { stdout } = await execFileAsync(getPythonCommand(), args, {
        timeout: 300_000,
        maxBuffer: 10 * 1024 * 1024,
        env: pythonProcessEnv(),
      })
      console.log(stdout)
    } catch (e: any) {
      if (opts.json) {
        console.log(JSON.stringify({
          success: false,
          code: 'LEADS_FAILED',
          error: '线索雷达不可用，请运行 check --json 检查配置和依赖',
        }))
        process.exit(1)
      }
      console.error(chalk.red(`\n${safeSubprocessError(e, '统计失败')}`))
      process.exit(1)
    }
  })

// ==================== media（媒体精确匹配）====================
program
  .command('media')
  .description('媒体精确匹配：用 hardlink.db 把 md5 直接对到本地文件（图片/文件/视频；本地只读）')
  .option('--md5 <prefix>', '按 md5 前缀查')
  .option('--type <kind>', 'image | file | video | all', 'all')
  .option('--limit <n>', '最多列几条', '20')
  .option('--missing-only', '只列文件已不在本地的（微信会清理）')
  .option('--json', '输出 JSON 格式')
  .action(async (opts) => {
    const { execFile } = await import('child_process')
    const { promisify } = await import('util')
    const execFileAsync = promisify(execFile)
    const script = join(resolvePackageRoot(), 'scripts', 'media_index.py')
    const limit = parseCliInteger(opts.limit, 'limit', 1, 5000, opts.json)

    try {
      const args = [script, '--type', String(opts.type || 'all'), '--limit', String(limit)]
      if (opts.md5) args.push('--md5', String(opts.md5))
      if (opts.missingOnly) args.push('--missing-only')
      if (opts.json) args.push('--json')
      const { stdout } = await execFileAsync(getPythonCommand(), args, {
        timeout: 300_000,
        maxBuffer: 16 * 1024 * 1024,
        env: pythonProcessEnv(),
      })
      console.log(stdout)
    } catch (e: any) {
      if (opts.json) {
        console.log(JSON.stringify({
          success: false,
          code: 'MEDIA_FAILED',
          error: '媒体索引不可用，请运行 check --json 检查配置和依赖',
        }))
        process.exit(1)
      }
      console.error(chalk.red(`\n${safeSubprocessError(e, '查询失败')}`))
      process.exit(1)
    }
  })

// ==================== replay（关系时间重放）====================
program
  .command('replay')
  .description('关系网络时间重放：按月展开，生成可播放的单文件 HTML（本地、离线、不调模型）')
  .option('--out <file>', '输出路径', 'output/replay.html')
  .option('--min-weight <number>', '当月互动量门槛，低于此不计入', '10')
  .option('--json', '只输出聚合结果（验收用）')
  .action(async (opts) => {
    const { execFile } = await import('child_process')
    const { promisify } = await import('util')
    const execFileAsync = promisify(execFile)
    const script = join(resolvePackageRoot(), 'scripts', 'replay.py')
    const minWeight = parseCliInteger(opts.minWeight, 'min-weight', 1, 10000, opts.json)

    try {
      const args = [script, '--min-weight', String(minWeight), '--out', String(opts.out)]
      if (opts.json) args.push('--json')
      const { stdout } = await execFileAsync(getPythonCommand(), args, {
        timeout: 600_000,
        maxBuffer: 64 * 1024 * 1024,
        env: pythonProcessEnv(),
      })
      console.log(stdout)
    } catch (e: any) {
      if (opts.json) {
        console.log(JSON.stringify({
          success: false,
          code: 'REPLAY_FAILED',
          error: '时间重放不可用，请运行 check --json 检查配置和依赖',
        }))
        process.exit(1)
      }
      console.error(chalk.red(`\n${safeSubprocessError(e, '生成失败')}`))
      process.exit(1)
    }
  })

// ==================== timeline（某号观点演变）====================
program
  .command('timeline')
  .description('观点时间线：某个公众号历次文章与要点，可按时间看它说法的变化')
  .option('--source <name>', '公众号名（子串匹配）')
  .option('--list', '列出存了哪些号、各多少篇')
  .option('--limit <number>', '最多列几篇（最近的在前）', '30')
  .option('--ai', '让模型总结观点变化（需要 API key）')
  .option('--json', '输出 JSON 格式')
  .action(async (opts) => {
    const { execFile } = await import('child_process')
    const { promisify } = await import('util')
    const execFileAsync = promisify(execFile)
    const script = join(resolvePackageRoot(), 'scripts', 'opinion_timeline.py')
    const limit = parseCliInteger(opts.limit, 'limit', 1, 2000, opts.json)

    try {
      const args = [script, '--limit', String(limit)]
      if (opts.list) args.push('--list')
      if (opts.source) args.push('--source', String(opts.source))
      if (opts.ai) args.push('--ai')
      if (opts.json) args.push('--json')
      if (!opts.list && !opts.source) {
        console.error(chalk.yellow('\n用法：timeline --list | --source <公众号名>'))
        process.exit(1)
      }
      const { stdout } = await execFileAsync(getPythonCommand(), args, {
        timeout: 300_000,
        maxBuffer: 10 * 1024 * 1024,
        env: pythonProcessEnv(),
      })
      console.log(stdout)
    } catch (e: any) {
      if (opts.json) {
        console.log(JSON.stringify({
          success: false,
          code: 'TIMELINE_FAILED',
          error: '观点时间线不可用，请先运行 daily 生成日报',
        }))
        process.exit(1)
      }
      console.error(chalk.red(`\n${safeSubprocessError(e, '读取失败')}`))
      process.exit(1)
    }
  })

// ==================== daily-server ====================
program
  .command('daily-server')
  .description('启动本地日报阅读器（浏览器浏览 + 收藏 + 笔记）')
  .option('-d, --date <YYYY-MM-DD>', '日期')
  .option('-p, --port <n>', '端口', '8765')
  .option('--open', '自动打开浏览器')
  .option('--status', '仅检查阅读器状态，不启动服务')
  .option('--dry-run', '仅预览，不启动服务或打开浏览器')
  .option('--yes', '确认启动本地阅读器')
  .option('--json', '输出机器可读状态；启动仍需 --yes')
  .action(async (opts) => {
    const { spawn } = await import('child_process')
    const pkgRoot = resolvePackageRoot()
    const favServer = join(pkgRoot, 'scripts', 'fav_server.py')
    const port = parseCliInteger(opts.port, 'port', 1, 65535, opts.json)
    if (opts.date) requireCliDate(opts.date, opts.json)

    if (opts.status) {
      try {
        const response = await fetch(`http://127.0.0.1:${port}/api/status`, { signal: AbortSignal.timeout(2000) })
        const status = await response.json() as { ok?: boolean; service?: string; date?: string }
        const data = { success: response.ok && status.ok === true, running: response.ok, port, date: status.date || null }
        if (opts.json) console.log(JSON.stringify(data, null, 2))
        else console.log(data.running ? chalk.green(`阅读器正在运行 (${data.date || '日期未知'})`) : chalk.gray('阅读器未运行'))
      } catch {
        const data = { success: true, running: false, port, date: null }
        if (opts.json) console.log(JSON.stringify(data, null, 2))
        else console.log(chalk.gray('阅读器未运行'))
      }
      return
    }

    const date = opts.date || defaultDailyDate()
    const preview = {
      success: true,
      dryRun: true,
      action: 'daily-reader.start',
      date,
      port,
      loopbackOnly: true,
      opensBrowser: Boolean(opts.open),
    }
    if (opts.dryRun) {
      if (opts.json) console.log(JSON.stringify(preview))
      else console.log(chalk.cyan(`阅读器启动预览：${date}，本机端口 ${port}${opts.open ? '，并打开浏览器' : ''}。`))
      return
    }
    if (opts.json && !opts.yes) {
      console.log(JSON.stringify({ ...preview, success: false, dryRun: false, code: 'CONFIRMATION_REQUIRED' }))
      process.exit(1)
    }
    if (opts.json) {
      const result = await startDetachedDailyReader(favServer, date, port)
      if (result.success && opts.open) await openLocalUrl(`http://localhost:${port}`)
      console.log(JSON.stringify({
        ...result,
        action: 'daily-reader.start',
        date,
        port,
        openedBrowser: result.success && Boolean(opts.open),
      }))
      if (!result.success) process.exit(1)
      return
    }
    console.log(chalk.cyan(`⭐ 启动日报阅读器\n`))
    console.log(chalk.gray(`  日期: ${date}`))
    console.log(chalk.gray(`  地址: http://localhost:${port}`))
    console.log()

    if (opts.open) {
      await openLocalUrl(`http://localhost:${port}`)
    }

    const child = spawn(getPythonCommand(), [favServer, '--date', date, '--port', String(port)], {
      windowsHide: true,
      stdio: 'inherit',
      env: pythonProcessEnv(),
    })
    process.on('SIGINT', () => child.kill())
  })

// ==================== Interactive Menu (no arguments) ====================
program
  .command('mcp-config')
  .description('输出 MCP Server 配置，粘贴到 .mcp.json 即可让 AI 操作本工具')
  .option('-o, --output <file>', '写入文件', '')
  .option('--dry-run', '仅预览文件写入，不修改文件')
  .option('--yes', '确认写入配置文件')
  .option('--json-result', '写入模式输出 JSON 结果，不返回本地路径')
  .action(async (opts) => {
    const { writeFileSync } = await import('fs')
    const config = {
      mcpServers: {
        weflow: {
          command: 'npx',
          args: ['tsx', 'mcp-server/index.ts'],
          cwd: '${workspaceFolder}',
        },
      },
    }
    const json = JSON.stringify(config, null, 2)
    if (opts.output) {
      const preview = { success: true, dryRun: true, action: 'mcp-config.write', overwrite: existsSync(opts.output) }
      if (opts.dryRun) {
        if (opts.jsonResult) console.log(JSON.stringify(preview))
        else console.log(chalk.cyan(`MCP 配置写入预览：${preview.overwrite ? '将覆盖现有文件' : '将创建新文件'}`))
        return
      }
      if (!opts.yes) {
        if (opts.jsonResult) {
          console.log(JSON.stringify({ success: false, code: 'CONFIRMATION_REQUIRED', action: 'mcp-config.write', overwrite: preview.overwrite }))
          process.exit(1)
        }
        const { confirmed } = await inquirer.prompt([{
          type: 'confirm',
          name: 'confirmed',
          message: `${preview.overwrite ? '覆盖' : '创建'} MCP 配置文件？`,
          default: false,
        }])
        if (!confirmed) {
          console.log(chalk.gray('已取消'))
          return
        }
      }
      writeFileSync(opts.output, json, 'utf-8')
      if (opts.jsonResult) {
        console.log(JSON.stringify({ success: true, action: 'mcp-config.write', changed: true, overwrite: preview.overwrite }))
        return
      }
      console.log(chalk.green(`✓ 已写入 ${opts.output}`))
      console.log(chalk.gray('AI 助手现在可以使用以下工具：'))
    } else {
      console.log(json)
      // 机器模式到这里就结束：下面那段工具清单与"复制以上 JSON…"是**给人看的**，原来无条件打在
      // stdout 上 ⇒ `mcp-config --json-result | jq` 断在第 14 行（2026-10-12 由只读驱动扫描发现；
      // 写路径本来就早退发 JSON，所以只有读路径这一处漏）。
      if (opts.jsonResult) return
    }
    console.log(chalk.cyan('\n可用的 MCP 工具：'))
    const STATIC_TOOLS: Array<[string, string]> = [
      ['wechat.search_articles', '搜索知识库文章'],
      ['wechat.get_daily', '获取公众号日报(完整版)'],
      ['wechat.get_review', '获取 AI 学习日报'],
      ['wechat.get_stats', '统计概览(知识库+微信数据)'],
      ['wechat.get_concepts', '概念图谱索引'],
      ['wechat.get_concept', '读取概念 Wiki 页'],
      ['wechat.format_article', 'Markdown 转公众号排版'],
      ['wechat.list_themes', '排版主题列表'],
      ['wechat.fetch_article', '抓取公众号文章'],
      ['wechat.search_public', '搜索全网公众号文章'],
      ['wechat.export_messages', '按稳定数据契约读取会话消息'],
    ]
    const { MCP_TOOL_DEFS } = await import('../src/services/assistantTools.js')
    const all = [
      ...STATIC_TOOLS,
      ...MCP_TOOL_DEFS.filter(t => t.function.name !== 'get_stats')
        .map(t => [`wechat.${t.function.name}`, t.function.description.split(/[。(]/)[0]] as [string, string]),
    ]
    for (const [n, d] of all) {
      console.log(chalk.white('  ' + n.padEnd(28)) + chalk.gray(d))
    }
    console.log()
    if (opts.output) {
      console.log(chalk.gray(`配置已写入 ${opts.output}，重启 AI 编辑器即可生效`))
    } else {
      console.log(chalk.gray('复制以上 JSON 到你的 .mcp.json 文件即可'))
    }
  })

// ==================== check ====================
program
  .command('check')
  .description('检查运行环境（Python、pip 依赖、数据库配置）')
  .option('--json', '输出 JSON 格式，不包含数据库路径或密钥')
  .option('--report', '输出一段可直接粘贴给 AI / 贴进 issue 的诊断结论（已脱敏：用户名与 wxid 换占位符，不含密钥与聊天内容）')
  .option('--fix', '把能确定的一步替你执行（目前只处理"已找到数据目录但还没初始化/上次 init 失败"）：先打印命令再确认')
  .option('--yes', '配合 --fix：跳过确认（脚本用；手动运行时别加）')
  .action(async (opts) => {
    // 微信客户端的**版本**与它自报的**数据目录**：两个分支都要用，所以在这里算一次。
    // 判据见 `wechatClient.ts`（版本取活进程的 `--user-lib-dir`；取不到就是"未知"，不是"没问题"）。
    const client = await detectWechatClient()
    // 客户端自报的数据目录 vs 配置里那个数据库推出来的根：**只比是不是同一份**，
    // 路径本身不进机器可读输出（`wechat-check/v1` 一直是不含路径的）。
    //
    // **只在 4.x 上比**：这个根是从 `ntDbPath`（4.x 的库）推的，而客户端自报的那条来自 4.x 客户端
    // —— 只用 3.x 的用户（`dbPath3x`）比出来的"不是同一份"没有意义，而这句话**只在 false 时打印**
    // ⇒ 那就是一条假警告。判据不成立时给 null（"不知道"），不是 false。
    const { dirname } = await import('node:path')
    // **四层**：`…/xwechat_files/<wxid>/db_storage/message/message_0.db`
    // → message → db_storage → <wxid> → xwechat_files。少一层就退到 `<wxid>` 目录，
    // 于是两个路径永远不相等、永远报"不是同一份"（一个看着很合理的假警告）。
    const dbPathConfigured = String(configService.get('dataVersion') || '') === '4.x'
      ? String(configService.get('ntDbPath') || '')
      : ''
    const configuredRoot = dbPathConfigured
      ? dirname(dirname(dirname(dirname(dbPathConfigured))))
      : ''
    const dataDirMatchesConfig = (client.dataDirs.length && configuredRoot)
      ? client.dataDirs.some(dir => samePath(dir, configuredRoot))
      : null
    // `--json`（给机器）与 `--report`（给人/AI）用的是**同一份事实**，所以只探测一次：
    // 两个分支各写一份探测，迟早会出现"JSON 说 Python 可用、报告说不可用"这种自相矛盾。
    const collectCheckData = async () => {
      const { execFileSync } = await import('child_process')
      const requiredDependencies = ['sqlcipher3', 'html2text', 'zstandard', 'cryptography']
      // 可选依赖按功能分组：缺了只是对应功能不可用，不该让整个 check 变红。
    // PIL / requests / fitz 分别服务图片与头像、面板抓取、PDF 渲染。
    const optionalDependencies = ['scrapling', 'PIL', 'requests', 'fitz']
      let pythonVersion = ''
      try {
        pythonVersion = execFileSync(getPythonCommand(), ['--version'], { windowsHide: true, encoding: 'utf8', timeout: 5000 }).trim()
      } catch {}
      const dependencyStatus = (name: string): boolean => {
        if (!pythonVersion) return false
        try {
          execFileSync(getPythonCommand(), ['-c', `import ${name}`], { windowsHide: true, stdio: 'ignore', timeout: 5000 })
          return true
        } catch {
          return false
        }
      }
      let daemonAlive = false
      try {
        const { isDaemonAlive } = await import('../src/services/assistantDaemon.js')
        daemonAlive = isDaemonAlive().alive
      } catch {}
      const engine = String(configService.get('aiEngine') || 'deepseek')
      const data = {
        success: true,
        schema: 'weflow-check/v1',
        runtime: {
          node: { available: true, version: process.versions.node },
          python: { available: !!pythonVersion, version: pythonVersion },
        },
        dependencies: {
          required: Object.fromEntries(requiredDependencies.map(name => [name, dependencyStatus(name)])),
          optional: Object.fromEntries(optionalDependencies.map(name => [name, dependencyStatus(name)])),
        },
        configuration: {
          initialized: configService.isConfigured(),
          messageDatabase: !!configService.get('ntDbPath') && existsSync(configService.get('ntDbPath')),
          momentsDatabase: !!configService.get('snsDbPath') && existsSync(configService.get('snsDbPath')),
          favoritesDatabase: !!configService.get('favDbPath') && existsSync(configService.get('favDbPath')),
          // `favoritesDatabase` only says the file is there. Reading it also
          // needs a key, and a caller that took the former for "usable" would
          // attempt favorites and always fail.
          favoritesReady: !!configService.get('favDbPath')
            && existsSync(configService.get('favDbPath'))
            && (!!configService.get('favKey') || !!configService.get('favPassphrase')),
        },
        assistant: {
          engine,
          localInference: ['ollama', 'lmstudio'].includes(engine),
          aiConfigured: ['ollama', 'lmstudio'].includes(engine) || !!resolveAiKey(),
          messageChannelLoggedIn: !!configService.get('wechatOcToken'),
          daemonRunning: daemonAlive,
        },
        // `version` 只从活进程取；取不到就是 null + 一句 `note`（**不是**"没问题"）。
        // `unusableVersionDirs` 是磁盘上的残留版本目录（没有 `Weixin.dll`）—— 指向它们的加载会失败。
        wechatClient: {
          running: client.running,
          version: client.version,
          loadedDirs: client.loadedDirs,
          // 客户端自报的构建 token（并列的第二来源；**不拿它推版本号**，编码规则没解出来）
          versionTokens: client.versionTokens,
          note: client.note,
          unusableVersionDirs: client.unusableVersionDirs,
          // 客户端**自己说**数据目录在哪（与配置不一致时说明两边不是同一份库）
          dataDirs: client.dataDirs,
          // 只报结论（true/false/null），**不带路径** —— 这条 schema 一直是不含路径的
          dataDirMatchesConfig,
          // `update.data` 在场 ⇒ 加载路径可能不由命令行决定：这条不确定必须跟着版本一起出去
          updateData: client.updateData,
          // 只报条数与最近时间（不读崩溃内容）
          crashRecords: client.crashRecords,
          caveats: client.caveats,
          // D-130：本机实际加载的版本 vs 本包验证过的版本（判定只有这一份实现）
          compatibility: {
            verifiedVersion: WECHAT_VERIFIED.version,
            verifiedAt: WECHAT_VERIFIED.verifiedAt,
            verdict: compareWechatVersions(client.version, WECHAT_VERIFIED.version),
          },
        },
      }
      return data
    }

    if (opts.json) {
      console.log(JSON.stringify(await collectCheckData(), null, 2))
      return
    }

    // `--report`：一段**可整段复制**的诊断块（脱敏后）。这是"用户说不清、我们又猜不准"
    // 那个循环的出口 —— issue #3/#9/#10 与 2026-10-18 那封邮件都是同一个根因被描述成四种现象。
    if (opts.report) {
      const data = await collectCheckData()
      console.log(renderDiagnosticReport({
        cliVersion: CLI_VERSION,
        // 本地时间：用户对照日志/截图时要能直接对上，UTC 会多一步换算
        generatedAt: new Date().toLocaleString('zh-CN', { hour12: false }),
        platform: process.platform,
        arch: process.arch,
        nodeVersion: process.versions.node,
        python: {
          command: getPythonCommand(),
          available: !!data.runtime.python.available,
          version: String(data.runtime.python.version || ''),
        },
        dependencies: data.dependencies,
        configuration: data.configuration,
        keys: {
          messageKeyConfigured: !!configService.get('ntKey') || !!configService.get('decryptKey'),
          passphraseConfigured: !!configService.get('favPassphrase'),
        },
        wechatClient: {
          running: data.wechatClient.running,
          version: data.wechatClient.version,
          note: data.wechatClient.note,
          dataDirMatchesConfig: data.wechatClient.dataDirMatchesConfig,
          dataDirs: data.wechatClient.dataDirs,
          unusableVersionDirs: data.wechatClient.unusableVersionDirs,
          compatibility: data.wechatClient.compatibility,
        },
      }))
      return
    }

    console.log(chalk.cyan('🔍 WeFlow CLI 环境检查\n'))

    // 1. Node.js
    console.log(chalk.white('Node.js:'), chalk.green(`v${process.versions.node}`))

    // 2. Python
    const { execFileSync } = await import('child_process')
    const pythonCommand = getPythonCommand()
    let pythonOk = false
    try {
      const pyVer = execFileSync(pythonCommand, ['--version'], { windowsHide: true, encoding: 'utf-8', timeout: 5000 }).trim()
      console.log(chalk.white('Python: '), chalk.green(pyVer))
      pythonOk = true
    } catch {
      console.log(chalk.white('Python: '), chalk.red('✗ 未找到'))
    }

    // 3. Pip dependencies
    if (pythonOk) {
      const deps = ['sqlcipher3', 'html2text', 'zstandard', 'cryptography']
      console.log(chalk.white('\nPython 依赖:'))
      let allOk = true
      for (const dep of deps) {
        try {
          execFileSync(pythonCommand, ['-c', `import ${dep}`], { windowsHide: true, stdio: 'ignore', timeout: 5000 })
          console.log(`  ${dep.padEnd(20)} ${chalk.green('✓')}`)
        } catch {
          console.log(`  ${dep.padEnd(20)} ${chalk.red('✗ 缺失')}`)
          allOk = false
        }
      }
      if (!allOk) {
        console.log(chalk.yellow('\n⚠️  运行以下命令安装缺失依赖：'))
        if (process.platform === 'linux') {
          console.log(chalk.gray('  pip3 install --user sqlcipher3 html2text zstandard cryptography'))
          console.log(chalk.gray('  （sqlcipher3 编译需先: sudo apt install libsqlcipher-dev）'))
          // Ubuntu 23.04+ / Debian 12+ 把系统 Python 标成 externally-managed（PEP 668），
          // 上面那条 --user 会被直接拒绝；不给替代方案，用户会以为是自己环境坏了。
          console.log(chalk.gray('  若提示 externally-managed-environment（PEP 668），二选一：'))
          console.log(chalk.gray('    加 --break-system-packages，或 python3 -m venv ~/.weflow-venv'))
        } else {
          console.log(chalk.gray('  pip install sqlcipher3 html2text zstandard cryptography'))
        }
      }
      // 可选依赖
      // 与 optionalDependencies 同源：缺了只是对应功能不可用，
      // 提示里要写**这个包**的安装命令（之前写死成 scrapling，扩列表时会骗人）。
      const optDeps: Array<[string, string]> = [
        ['scrapling', 'scrapling'],
        ['PIL', 'pillow'],
        ['requests', 'requests'],
        ['fitz', 'pymupdf'],
      ]
      console.log(chalk.white('\n可选依赖（按功能需要，缺了对应命令会提示安装）:'))
      for (const [dep, pkgName] of optDeps) {
        try {
          execFileSync(pythonCommand, ['-c', `import ${dep}`], { windowsHide: true, stdio: 'ignore', timeout: 5000 })
          console.log(`  ${dep.padEnd(20)} ${chalk.green('✓')}`)
        } catch {
          console.log(`  ${dep.padEnd(20)} ${chalk.gray(`○ (pip install ${pkgName})`)}`)
        }
      }
    }

    // 3.5 微信版本兼容（D-130）：本机加载的 vs 本包验证过的
    {
      const verdict = compareWechatVersions(client.version, WECHAT_VERIFIED.version)
      const mark = verdict === 'verified' ? chalk.green('✓') : verdict === 'newer-than-verified' ? chalk.yellow('⚠') : chalk.gray('·')
      console.log(chalk.white('\n微信版本兼容:'))
        // 原因措辞的单一来源：三种“不知道”（视图隔离 / 平台不支持探测 / 客户端没开）
        // 必须分开说，否则 Linux 上会把“探测不支持”讲成“微信没在运行”（D-145）。
        const { reason: unknownReason, compatReason } =
          describeUnknownVersionReason({ platform: process.platform, viewFiltered: client.viewFiltered })
      console.log(`  ${mark} ${client.version ?? unknownReason} · ${describeCompatVerdict(verdict, WECHAT_VERIFIED.version, compatReason)}`)
    }

    // 4. Config
    console.log(chalk.white('\n配置状态:'))
    const configured = configService.isConfigured()
    const hasKey = !!configService.get('ntKey') || !!configService.get('decryptKey')
      if (configured && hasKey) {
        // "配置齐了"不等于"这台机器上能用"：从 Windows 拷过来的 config.json
        // 路径全是 C:\…，在 Linux 上一个都不存在。只报"✓ 已初始化"会让人
        // 以为一切正常（2026-11-01 实测：数据目录全不存在仍报已初始化）。
        const configuredPaths = [
          configService.get('ntDbPath'), configService.get('dbPath'), configService.get('dbPath3x'),
        ].filter((v): v is string => !!v)
        const missing = configuredPaths.filter((v) => !existsSync(v))
        if (missing.length > 0) {
          console.log(chalk.yellow('  ○ 已配置，但数据目录在本机不存在'))
          console.log(chalk.gray('    可能是从另一台机器拷来的配置（例如 Windows 的 C: 路径）。'))
          console.log(chalk.gray('    在本机重新运行: weflow-cli init'))
        } else {
          console.log(chalk.green('  ✓ 已初始化 — 可以运行 weflow-cli'))
        }
      } else {
        const { readInitFailure, describeInitFailure } = await import('../src/services/initState.js')
        const lastFailure = readInitFailure()
        const lines = describeInitFailure(lastFailure)
        if (lines) {
          // 跑到这里说明用户**试过** init 但没成功。只报"未初始化"会让人以为
          // 是密钥取不到（issue #13 就是这样被理解的）。把上次的原因摆出来。
          for (const line of lines) console.log(chalk.yellow(line))
        } else {
          console.log(chalk.yellow('  ○ 未初始化 — 运行 weflow-cli init'))
        }
        if (opts.fix) {
          // 推断能确定的那一步，但**先打印、再确认**（见 src/services/initFix.ts）。
          const { planInitFix } = await import('../src/services/initFix.js')
          const detectedRoot = (client as any)?.dataDir || configService.get('dbPath') || null
          const plan = planInitFix({
            configured,
            detectedPath: detectedRoot,
            lastInitError: lastFailure ? { message: lastFailure.message } : null,
          })
          if (!plan) {
            console.log(chalk.gray('  --fix：没有可以替你执行的一步（探测不到数据目录，或配置已可用）'))
          } else {
            console.log(chalk.cyan('\n我准备执行：'))
            console.log(chalk.gray(`  ${plan.command}`))
            console.log(chalk.gray(`  原因：${plan.reason}`))
            const { createInterface } = await import('node:readline/promises')
            let proceed = Boolean(opts.yes)
            if (!proceed) {
              const rl = createInterface({ input: process.stdin, output: process.stdout })
              const answer = (await rl.question('  继续？[y/N] ')).trim().toLowerCase()
              rl.close()
              proceed = answer === 'y' || answer === 'yes'
            }
            if (!proceed) {
              console.log(chalk.gray('  已取消，配置未改动。'))
            } else {
              const { spawn } = await import('node:child_process')
              const child = spawn(process.execPath, [process.argv[1], ...plan.args], { stdio: 'inherit', windowsHide: true })
              await new Promise<void>((resolve) => child.on('exit', (code) => { process.exitCode = code || 0; resolve() }))
            }
          }
        }
      }


      // 4.5 数据可读性：把“配置对不对”升级成“到底能读几个库”。
      // Linux 上自动提密钥走不通（4.1.12.26+ 用口令 + 每分片派生），用户最需要的
      // 就是这句话；没有凭据时安静跳过，不制造无谓的 Python 冷启动。
      // 没有凭据时**更要**说这一句：Linux 上“什么都没配”正是用户当前的处境，
      // 安静跳过会让人以为 check 通过了、只是数据没写。key-status 在无凭据时
      // 不跑 PBKDF2，代价只有一次 Python 启动。
      if (!opts.json) {
        try {
          const { execFile } = await import('child_process')
          const { promisify } = await import('util')
          const { stdout } = await promisify(execFile)(
            getPythonCommand(),
            [join(resolvePackageRoot(), 'scripts', 'nt_decrypt.py'), 'key-status', '--json'],
            { timeout: 180_000, maxBuffer: 5 * 1024 * 1024 })
          const line = (stdout || '').split('\n').filter((l) => l.trim().startsWith('{')).pop()
          if (line) {
            const st = JSON.parse(line) as { mode: string; total: number; matched: number; verdict: string }
            const label = st.mode === 'passphrase' ? '口令' : '密钥'
            if (st.mode === 'none') {
              console.log(chalk.yellow(`  数据可读性: 未配置凭据（${st.total} 个库都读不了）`))
            } else if (st.verdict === 'no-databases' || st.total === 0) {
              // 一个库都没找到 ≠ 密钥不对。混着说会让人去换口令，
              // 而真因是数据目录路径或权限（2026-11-01 在迁移配置上实测踩到）。
              console.log(chalk.yellow('  数据可读性: 没找到可读的数据库（检查数据目录路径与权限）'))
            } else if (st.verdict === 'ok') {
              console.log(chalk.green(`  数据可读性: ${label}可解开 ${st.matched}/${st.total} 个库`))
            } else {
              console.log(chalk.yellow(`  数据可读性: 只有 ${st.matched}/${st.total} 个库可读 —— ${label}可能不对`))
              console.log(chalk.gray('    先验证: python3 scripts/nt_decrypt.py key-status'))
            }
          }
        } catch {
          // 这一步属于“锦上添花”：跑不起来（没装依赖、脚本缺失）不能把 check 弄挂。
        }
      }
    // 5. Databases & extensions
    const dbRows: Array<[string, string, boolean]> = [
      ['消息数据库', configService.get('ntDbPath'), true],
      ['朋友圈数据库', configService.get('snsDbPath'), true],
      ['收藏数据库', configService.get('favDbPath'), true],
    ]
    for (const [label, path, keyRequired] of dbRows) {
      if (path && existsSync(path)) {
        const stat = (await import('fs')).statSync(path)
        const mb = (stat.size / 1024 / 1024).toFixed(0)
        console.log(chalk.white(`  ${label}: ${path} (${mb}MB)`))
        // 微信"存储位置"设到别的盘时，用户目录下那个是**junction**：显示的是 C 盘路径，
        // 数据其实在 D 盘。不点出来的话，用户会以为配置指错了地方（2026-10-19 实测：
        // `C:\Users\…\xwechat_files` → `D:\微信\xwechat_files`）。
        try {
          const { realpathSync } = await import('fs')
          const real = realpathSync(path)
          if (real.toLowerCase() !== path.toLowerCase()) {
            console.log(chalk.gray(`    ↳ 软链指向 ${real}`))
          }
        } catch { /* 解析不了就不说，别拿它当错误 */ }
      } else {
        const hint = keyRequired ? ' (可选, init 或 sns/fav 命令配置)' : ''
        console.log(chalk.gray(`  ${label}: 未配置${hint}`))
      }
    }

    // 6. 微信客户端版本（`client` / `dataDirMatchesConfig` 在 action 开头已经算过）
    console.log(chalk.white('\n微信客户端:'))
    if (client.version) {
      // 并列报上客户端自报的构建 token：这是"哪个构建"的第二个来源（**不用它推版本号**）
      const token = client.versionTokens.length ? chalk.gray(`  · 自报构建 ${client.versionTokens.join('、')}`) : ''
      // Linux 没有"已加载的版本目录"（那是 Windows 的模块扫描结果），
      // 以前这里会印出 `(undefined)`——真实输出里很难看。
      const loadedDir = client.loadedDirs[0]
      console.log(chalk.green(`  ✓ 运行时加载 ${client.version}`)
        + (loadedDir ? chalk.gray(` (${loadedDir})`) : '') + token)
    } else {
      // **说"未知"而不是"没问题"**：取不到就说取不到，别给人一个假的安心
      console.log(chalk.gray(`  ○ 版本未知 — ${client.note}`))
    }
    for (const dead of client.unusableVersionDirs) {
      console.log(chalk.yellow(`  ! 残留版本目录 ${dead.dir}：只剩 ${dead.files} 个文件（没有 Weixin.dll）`))
      console.log(chalk.gray('    指向它的加载会失败；如果客户端起不来，先看这里'))
    }
    // `update.data` 在场时上面那个版本**未必**是加载的那个 —— 这句话要跟着它一起出现
    for (const caveat of client.caveats) {
      console.log(chalk.yellow(`  ⚠ ${caveat}`))
    }
    if (client.dataDirs.length) {
      console.log(chalk.gray(`  · 客户端自报数据目录: ${client.dataDirs.join('、')}`))
      if (dataDirMatchesConfig === false) {
        // 不一致 = 两边可能不是同一份库（本机数据目录还有 D 盘软链，这条已经按真身比过）
        console.log(chalk.yellow('    ⚠ 与配置里那个数据库推出来的根**不是同一份** —— 先确认你在读的是客户端正在写的那份'))
      }
    }
    const crashes = client.crashRecords.reports + client.crashRecords.records
    if (crashes > 0) {
      const when = client.crashRecords.newest ? client.crashRecords.newest.slice(0, 16).replace('T', ' ') : '时间读不到'
      console.log(chalk.gray(`  · 客户端崩溃记录 ${crashes} 份（最近 ${when}）—— 客户端崩过时数据读不出来，先看这条`))
    }

    // 7. Assistant (第二大脑)
    console.log(chalk.white('\n第二大脑 Agent:'))
    const aiKey = resolveAiKey()
    const aiBase = configService.get('aiBaseUrl')
    const engine = String(configService.get('aiEngine') || 'deepseek')
    if (['ollama', 'lmstudio'].includes(engine)) {
      console.log(chalk.green(`  AI 引擎: ${engine} (本地推理, 数据不出网)`))
    } else if (aiKey) {
      console.log(chalk.green(`  AI 引擎: ${aiBase ? `自定义端点 (${configService.get('aiModel') || 'deepseek-chat'})` : 'DeepSeek'}`))
    } else {
      console.log(chalk.gray('  AI 引擎: 未配置 (config set deepseekApiKey <key>)'))
    }
    const ocToken = configService.get('wechatOcToken')
    console.log(ocToken
      ? chalk.green('  消息通道: 已登录 (login-wechat)')
      : chalk.gray('  消息通道: 未登录 (weflow-cli login-wechat)'))
    try {
      const { isDaemonAlive } = await import('../src/services/assistantDaemon.js')
      const { alive, pid } = isDaemonAlive()
      console.log(alive
        ? chalk.green(`  守护进程: 运行中 (pid ${pid})`)
        : chalk.gray('  守护进程: 未运行 (weflow-cli assistant start)'))
    } catch { /* daemon 模块不可用时跳过 */ }
    console.log()
  })

// ==================== Interactive Menu (no arguments) ====================
async function showInteractiveMenu() {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const configured = configService.isConfigured()
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const hasNtKey = !!configService.get('ntKey')
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const hasLogin = !!configService.get('wechatOcToken')
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const hasVault = !!configService.get('vaultRepo')

  // 首次运行：自动引导初始化
  if (!configured) {
    console.log(chalk.cyan('\n👋 欢迎使用 WeFlow CLI！'))
    console.log(chalk.gray('检测到尚未初始化，让我们开始设置...\n'))

    const { startInit } = await inquirer.prompt([{
      type: 'confirm',
      name: 'startInit',
      message: '是否现在开始初始化（检测微信数据目录并提取密钥）？',
      default: true,
    }])
    if (startInit) {
      const initCmd = program.commands.find(c => c.name() === 'init')
      if (initCmd) { await (initCmd as any).action(); return }
    }
    console.log(chalk.gray('\n稍后可运行: weflow-cli init\n'))
    return
  }

  // 构建菜单选项
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const choices: any[] = []

  choices.push(new inquirer.Separator('  📬 聊天记录'))
  choices.push({ name: '  查看会话列表', value: 'sessions' })
  choices.push({ name: '  查看聊天消息', value: 'messages' })
  choices.push({ name: '  导出聊天记录', value: 'export' })
  choices.push({ name: '  生成聊天月报', value: 'report' })

  choices.push(new inquirer.Separator('  📰 公众号日报'))
  choices.push({ name: '  生成今日日报', value: 'daily' })
  choices.push({ name: '  启动阅读器', value: 'daily-server' })

  choices.push(new inquirer.Separator('  💬 微信消息'))
  choices.push({
    name: `  扫码登录${hasLogin ? chalk.green(' (已登录)') : ''}`,
    value: 'login-wechat',
  })
  choices.push({
    name: `  监听消息${!hasLogin ? chalk.gray(' (需先登录)') : ''}`,
    value: 'listen',
    disabled: !hasLogin ? '请先扫码登录' : undefined,
  })
  choices.push({
    name: `  发送消息${!hasLogin ? chalk.gray(' (需先登录)') : ''}`,
    value: 'send',
    disabled: !hasLogin ? '请先扫码登录' : undefined,
  })

  const hasAiKey = !!configService.get('deepseekApiKey') || ['ollama', 'lmstudio'].includes(String(configService.get('aiEngine')))
  choices.push(new inquirer.Separator('  🧠 第二大脑 Agent'))
  choices.push({
    name: `  启动微信 AI 助手${hasLogin && hasAiKey ? '' : chalk.gray(' (需登录+API key)')}`,
    value: 'assistant-start',
    disabled: hasLogin && hasAiKey ? undefined : '需要消息通道登录和 AI 引擎配置',
  })
  choices.push({
    name: '  查看助手状态',
    value: 'assistant-status',
  })
  choices.push({
    name: '  停止助手',
    value: 'assistant-stop',
  })

  choices.push(new inquirer.Separator('  📚 知识库'))
  choices.push({ name: '  初始化 Obsidian Vault', value: 'vault-init' })
  choices.push({ name: '  编译概念图谱', value: 'wiki-compile' })
  choices.push({
    name: `  同步到远端${hasVault ? '' : chalk.gray(' (未配置仓库)')}`,
    value: 'vault-sync',
    disabled: !hasVault ? '请先配置 vaultRepo' : undefined,
  })

  choices.push(new inquirer.Separator('  📊 统计 & 报告'))
  choices.push({ name: '  📊 个人信息消费报告', value: 'chat-stats' })
  choices.push({ name: '  📚 微信读书统计', value: 'weread' })
  choices.push({ name: '  🧠 提取待办事项', value: 'extract-todos' })
  choices.push({ name: '  📝 AI 学习日报', value: 'generate-review' })

  choices.push(new inquirer.Separator('  ⚙️ 系统'))
  choices.push({ name: '  查看配置', value: 'config-show' })
  choices.push({ name: '  重新初始化', value: 'init' })

  // 显示状态摘要
  console.log(chalk.cyan('\n🚀 WeFlow CLI v1.5.0\n'))
  const statusParts: string[] = []
  statusParts.push(hasNtKey ? chalk.green('✓ 数据库') : chalk.yellow('○ 数据库'))
  statusParts.push(hasLogin ? chalk.green('✓ 消息通道') : chalk.gray('○ 消息通道'))
  statusParts.push(hasVault ? chalk.green('✓ Vault') : chalk.gray('○ Vault'))
  console.log(chalk.gray(`  状态: ${statusParts.join('  ')}\n`))

  const { action } = await inquirer.prompt([{
    type: 'select' as any,
    name: 'action',
    message: '请选择操作',
    choices,
    loop: false,
  }])

  // 辅助函数：执行命令
  const runCmd = async (name: string, opts: Record<string, any> = {}) => {
    const cmd = program.commands.find(c => c.name() === name)
    if (cmd) await (cmd as any).action(opts)
  }
  const runSubCmd = async (parent: string, child: string, opts: Record<string, any> = {}) => {
    const cmd = program.commands.find(c => c.name() === parent) as any
    const sub = cmd?.commands?.find((c: any) => c.name() === child)
    if (sub) await sub.action(opts)
  }
  const runPython = async (scriptName: string, label: string) => {
    const { execFile } = await import('child_process')
    const { promisify } = await import('util')
    const execFileAsync = promisify(execFile)
    const pkgRoot = resolvePackageRoot()
    const script = join(pkgRoot, 'scripts', scriptName)
    console.log(chalk.cyan(`正在${label}...\n`))
    try {
      const { stdout } = await execFileAsync(getPythonCommand(), [script], {
        timeout: 600_000, maxBuffer: 50 * 1024 * 1024,
        env: pythonProcessEnv(),
      })
      console.log(stdout)
    } catch (e: any) {
      console.error(chalk.red(safeSubprocessError(e, `${label}失败`)))
    }
  }

  switch (action) {
    case 'sessions':
      await runCmd('sessions')
      break
    case 'messages': {
      const sessions = await chatService.listSessions(undefined, 30)
      if (sessions.length === 0) { console.log(chalk.gray('无会话')); break }
      const { talker } = await inquirer.prompt([{
        type: 'select' as any, name: 'talker', message: '选择会话',
        choices: sessions.map((s, i) => ({
          name: `${String(i + 1).padStart(3)}. ${s.displayName || s.username}  ${chalk.gray((s.summary || '').slice(0, 30))}`,
          value: s.username,
        })),
        loop: false,
      }])
      await runCmd('messages', { talker, limit: '50', offset: '0' })
      break
    }
    case 'export': {
      const sessions = await chatService.listSessions(undefined, 30)
      if (sessions.length === 0) { console.log(chalk.gray('无会话')); break }
      const { talker } = await inquirer.prompt([{
        type: 'select' as any, name: 'talker', message: '选择要导出的会话',
        choices: sessions.map((s, i) => ({
          name: `${String(i + 1).padStart(3)}. ${s.displayName || s.username}`,
          value: s.username,
        })),
        loop: false,
      }])
      const { format } = await inquirer.prompt([{
        type: 'select' as any, name: 'format', message: '选择导出格式',
        choices: ['html', 'json', 'txt', 'excel'], loop: false,
      }])
      await runCmd('export', { talker, format, output: './output' })
      break
    }
    case 'report':
      await runCmd('report', {})
      break
    case 'daily': {
      const configKey = String(configService.get('deepseekApiKey') || '')
      const apiKey = process.env.DEEPSEEK_API_KEY || configKey
      if (!apiKey) {
        console.log(chalk.red('\n❌ 缺少 DeepSeek API key'))
        console.log(chalk.gray('  设置环境变量: set DEEPSEEK_API_KEY=<key>'))
        console.log(chalk.gray('  或持久化配置: weflow-cli config set deepseekApiKey <key>'))
        break
      }
      const now = new Date()
      const yyyy = now.getFullYear()
      const mm = String(now.getMonth() + 1).padStart(2, '0')
      const dd = String(now.getDate()).padStart(2, '0')
      const dateStr = `${yyyy}-${mm}-${dd}`
      const { spawn } = await import('child_process')
      const pipeline = join(resolvePackageRoot(), 'scripts', 'pipeline.py')
      console.log(chalk.cyan(`\n📰 正在生成 ${dateStr} 公众号日报...\n`))
      const child = spawn(getPythonCommand(), [pipeline, '--date', dateStr, '--interest', 'AI'], {
        windowsHide: true,
        stdio: 'inherit',
        env: pythonProcessEnv(apiKey),
      })
      await new Promise<void>((resolve) => child.on('exit', () => resolve()))
      break
    }
    case 'daily-server': {
      const now = new Date()
      const yyyy = now.getFullYear()
      const mm = String(now.getMonth() + 1).padStart(2, '0')
      const dd = String(now.getDate()).padStart(2, '0')
      const dateStr = `${yyyy}-${mm}-${dd}`
      await runCmd('fav-server', { date: dateStr, port: '8765', open: true })
      break
    }
    case 'login-wechat':
      await runCmd('login-wechat', {})
      break
    case 'assistant-start':
      await runSubCmd('assistant', 'start')
      break
    case 'assistant-status':
      await runSubCmd('assistant', 'status')
      break
    case 'assistant-stop':
      await runSubCmd('assistant', 'stop')
      break
    case 'listen':
      await runCmd('listen', {})
      break
    case 'send': {
      const sessions = await chatService.listSessions(undefined, 30)
      if (sessions.length === 0) { console.log(chalk.gray('无会话')); break }
      const { talker } = await inquirer.prompt([{
        type: 'select' as any, name: 'talker', message: '选择接收人',
        choices: sessions.map((s, i) => ({
          name: `${String(i + 1).padStart(3)}. ${s.displayName || s.username}`,
          value: s.username,
        })),
        loop: false,
      }])
      const { message } = await inquirer.prompt([{
        type: 'input', name: 'message', message: '输入消息内容',
      }])
      if (!message.trim()) { console.log(chalk.gray('已取消')); break }
      await runCmd('send', { talker, message })
      break
    }
    case 'vault-init':
      await runSubCmd('vault', 'init', {})
      break
    case 'wiki-compile':
      await runSubCmd('wiki', 'compile', {})
      break
    case 'vault-sync':
      await runSubCmd('vault', 'sync', {})
      break
    case 'config-show':
      await runSubCmd('config', 'show')
      break
    case 'chat-stats':
      await runCmd('chat-stats', { period: 'week' })
      break
    case 'weread': {
      const wCmd = program.commands.find(c => c.name() === 'weread') as any
      const statsCmd = wCmd?.commands?.find((c: any) => c.name() === 'stats')
      if (statsCmd) await statsCmd.action({ mode: 'monthly' })
      break
    }
    case 'extract-todos': {
      const sessions = await chatService.listSessions(undefined, 30)
      if (sessions.length === 0) { console.log(chalk.gray('无会话')); break }
      const { talker } = await inquirer.prompt([{
        type: 'select' as any, name: 'talker', message: '选择联系人',
        choices: sessions.map((s, i) => ({
          name: `${String(i + 1).padStart(3)}. ${s.displayName || s.username}`,
          value: s.displayName || s.username,
        })),
        loop: false,
      }])
      await runCmd('todos', { talker, days: '7' })
      break
    }
    case 'generate-review':
      await runCmd('review', {})
      break
    case 'init':
      await runCmd('init')
      break
  }
}

// 检测是否无参数启动（显示交互式菜单）
const cliArgs = process.argv.slice(2)
if (cliArgs.length === 0) {
  showInteractiveMenu().catch((e) => {
    console.error(chalk.red(`\n错误: ${e.message}`))
    process.exit(1)
  })
} else {
  program.parse()
}
