@whyshu/argent-engine 0.8.0-rc.8 → 0.13.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/MANIFEST.json +109 -43
  2. package/bin/runtime-install.mjs +92 -0
  3. package/engine/VERSION +1 -1
  4. package/engine/configs/billing-actions.json +30 -0
  5. package/engine/configs/mcp-tools.snapshot.json +47 -0
  6. package/engine/core/contracts/argent.contracts.json +3 -3
  7. package/engine/core/contracts/verbs.schema.json +64 -1
  8. package/engine/core/lib/account-token.mjs +37 -0
  9. package/engine/core/lib/contract.mjs +30 -0
  10. package/engine/core/lib/redact.mjs +34 -0
  11. package/engine/core/mcp/billing-upload.mjs +77 -0
  12. package/engine/core/mcp/erp-server.mjs +300 -0
  13. package/engine/core/mcp/gateway.mjs +333 -0
  14. package/engine/core/mcp/meter.mjs +101 -0
  15. package/engine/core/mcp/server.mjs +416 -2
  16. package/engine/core/mcp/vault.mjs +78 -0
  17. package/engine/scripts/appointment-worker.mjs +456 -35
  18. package/engine/scripts/appointment_grab.py +1389 -264
  19. package/engine/scripts/appointment_rules.py +118 -0
  20. package/engine/scripts/argent-timers.mjs +227 -0
  21. package/engine/scripts/argent-web-preflight.mjs +123 -0
  22. package/engine/scripts/argent-web-verify.mjs +105 -0
  23. package/engine/scripts/billing-upload.mjs +26 -0
  24. package/engine/scripts/build-doc-index.mjs +68 -0
  25. package/engine/scripts/build-engine-package.mjs +7 -1
  26. package/engine/scripts/capability-packs.lock.json +323 -300
  27. package/engine/scripts/check-docs-drift.mjs +51 -4
  28. package/engine/scripts/check-version-consistency.mjs +14 -1
  29. package/engine/scripts/ci-run.sh +2 -2
  30. package/engine/scripts/collect-intel.mjs +108 -0
  31. package/engine/scripts/daily-report-timer-plist.sh +18 -4
  32. package/engine/scripts/daily-report-timers.sh +36 -3
  33. package/engine/scripts/daily-report.mjs +78 -2
  34. package/engine/scripts/doc-status.mjs +212 -0
  35. package/engine/scripts/dsh-web-doctor.mjs +84 -0
  36. package/engine/scripts/engine-manifest.mjs +90 -0
  37. package/engine/scripts/engine-runtime-install.mjs +92 -0
  38. package/engine/scripts/erp-ui-install.mjs +127 -0
  39. package/engine/scripts/erp-ui-preflight.mjs +104 -0
  40. package/engine/scripts/erp-ui-verify.mjs +135 -0
  41. package/engine/scripts/flow-requirements.json +122 -99
  42. package/engine/scripts/full-exec-worker.mjs +251 -0
  43. package/engine/scripts/gen-preset-rows.mjs +1 -1
  44. package/engine/scripts/invoice_lip_runner.py +1 -0
  45. package/engine/scripts/invoice_runner.py +17 -6
  46. package/engine/scripts/invoice_stageb.py +21 -4
  47. package/engine/scripts/lib/bootcheck-wiring.mjs +7 -5
  48. package/engine/scripts/lib/intel-card.mjs +43 -0
  49. package/engine/scripts/lib/invoice_names.py +23 -0
  50. package/engine/scripts/lib/ml-ads-core.mjs +100 -18
  51. package/engine/scripts/lib/ml-ads-rules.mjs +275 -0
  52. package/engine/scripts/lib/ml-bridge-auth.mjs +50 -0
  53. package/engine/scripts/lib/ml-category-core.mjs +120 -0
  54. package/engine/scripts/lib/ml-insight-core.mjs +621 -0
  55. package/engine/scripts/lib/ml-insight-facts.mjs +424 -0
  56. package/engine/scripts/lib/ml-items.mjs +40 -0
  57. package/engine/scripts/lib/ml-listing-core.mjs +342 -0
  58. package/engine/scripts/lib/ml-market-core.mjs +774 -0
  59. package/engine/scripts/lib/plugin-packages.mjs +13 -0
  60. package/engine/scripts/lib/webdriver_ipc.py +61 -1
  61. package/engine/scripts/line_pack.py +196 -0
  62. package/engine/scripts/mcp-gateway-switch.mjs +100 -0
  63. package/engine/scripts/migrate-providers.mjs +3 -3
  64. package/engine/scripts/ml-ads-advice.mjs +140 -0
  65. package/engine/scripts/ml-ads.mjs +221 -0
  66. package/engine/scripts/ml-category-baseline.mjs +174 -0
  67. package/engine/scripts/ml-insight-diagnose.mjs +247 -0
  68. package/engine/scripts/ml-insight-run.sh +183 -0
  69. package/engine/scripts/ml-insight-timers.sh +224 -0
  70. package/engine/scripts/ml-listing-audit.mjs +170 -0
  71. package/engine/scripts/ml-market-matrix.mjs +84 -0
  72. package/engine/scripts/ml-market-snapshot.mjs +261 -0
  73. package/engine/scripts/ml-messages.mjs +145 -0
  74. package/engine/scripts/ml-oauth-setup.mjs +1 -1
  75. package/engine/scripts/npm-publish-argent.mjs +14 -0
  76. package/engine/scripts/ops-codefix-pr.mjs +87 -0
  77. package/engine/scripts/ops-codefix-queue.mjs +30 -0
  78. package/engine/scripts/ops-digest.mjs +98 -0
  79. package/engine/scripts/ops-verify.mjs +67 -0
  80. package/engine/scripts/orchestrator.py +410 -20
  81. package/engine/scripts/orchestrator_br.py +146 -4
  82. package/engine/scripts/plugin-bootcheck.mjs +50 -1
  83. package/engine/scripts/publish-engine.mjs +111 -0
  84. package/engine/scripts/restart-dsh-with-tunnel.sh +129 -0
  85. package/engine/scripts/skuflow_invoice_runner.py +43 -3
  86. package/engine/scripts/v0.9-acceptance.mjs +107 -0
  87. package/engine/scripts/vertical-lint.mjs +12 -1
  88. package/engine/scripts/web-switch.mjs +121 -0
  89. package/engine/scripts/wenyao_fill_template.py +52 -15
  90. package/engine/scripts/wenyao_run.py +2 -1
  91. package/engine/skills/README.md +3 -3
  92. package/engine/skills/bilibili-upload/SKILL.md +109 -0
  93. package/engine/skills/douyin-upload/SKILL.md +74 -0
  94. package/engine/skills/internal.json +28 -0
  95. package/engine/skills/kuaishou-upload/SKILL.md +109 -0
  96. package/engine/skills/ml-appointment-safety/SKILL.md +42 -0
  97. package/engine/skills/ml-full-appointment/SKILL.md +23 -0
  98. package/engine/skills/ml-invoice/SKILL.md +2 -2
  99. package/engine/skills/ml-invoice/references/template-fill-contract.md +1 -1
  100. package/engine/skills/ml-label-recovery/SKILL.md +43 -0
  101. package/engine/skills/ml-listing-audit/SKILL.md +66 -0
  102. package/engine/skills/ml-store-daily-report/SKILL.md +68 -0
  103. package/engine/skills/ml-store-daily-report/scripts/generate.js +35 -0
  104. package/engine/skills/ml-store-insight/SKILL.md +81 -0
  105. package/engine/skills/tencent-upload/SKILL.md +60 -0
  106. package/engine/skills/weibo-upload/SKILL.md +106 -0
  107. package/engine/skills/whyshu-social-ops/SKILL.md +136 -0
  108. package/engine/skills/xiaohongshu-upload/SKILL.md +122 -0
  109. package/engine/version.mjs +1 -1
  110. package/engine/verticals/README.md +7 -0
  111. package/engine/verticals/_engine-words.baseline.txt +27 -59
  112. package/engine/verticals/mercadolibre/manifest.json +132 -6
  113. package/package.json +5 -1
@@ -0,0 +1,221 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * ml-ads.mjs —— Mercado Ads(Product Ads)**只读**效果报告 CLI。
4
+ *
5
+ * ## 干什么
6
+ * 用与日报同一条授权链(`~/.dsh/argent/ml-api-stores.json`)逐店拉广告数据,输出:
7
+ * 花费 / 广告销售额 / ROAS / ACoS / 点击 / CTR / CPC / 广告单量,
8
+ * 外加**告警**(ACoS 超标、烧钱零转化、ROAS 过低)和活动级下钻。
9
+ *
10
+ * ## 用法
11
+ * node scripts/ml-ads.mjs # 全部已授权店铺 · 近 7 个完整自然日
12
+ * node scripts/ml-ads.mjs --store 1店 # 店铺子串过滤
13
+ * node scripts/ml-ads.mjs --days 30 # 回溯天数(MELI 上限 90)
14
+ * node scripts/ml-ads.mjs --to 2026-10-16 # 指定结束日(站点本地)
15
+ * node scripts/ml-ads.mjs --detail # 附「花钱最多 / ACoS 超标」活动
16
+ * node scripts/ml-ads.mjs --json # 结构化输出(stdout 纯 JSON)
17
+ * node scripts/ml-ads.mjs --lines # 只输出中文卡片行(给日报/角色回复用)
18
+ * node scripts/ml-ads.mjs --list # 只列每店广告主,不拉活动
19
+ * node scripts/ml-ads.mjs --acos-bad 30 --min-spend 200 # 告警阈值
20
+ *
21
+ * ## 只读纪律
22
+ * · 只发 GET(`/advertising/...`);⛔ 不改预算/暂停/调价,也不写任何客户数据;
23
+ * · 唯一写盘 = token 轮换回写(MELI refresh_token 是轮换制,不写回下次必 429):
24
+ * 原子写(tmp + rename)、保持 600;
25
+ * · API 基址:`ML_API_BASE` → 默认平台地址(引擎 lib 里⛔不含域名,只在本 CLI 注入)。
26
+ */
27
+ import { readFileSync, writeFileSync, renameSync, existsSync, mkdirSync, chmodSync } from 'node:fs'
28
+ import { join, dirname } from 'node:path'
29
+ import { fileURLToPath } from 'node:url'
30
+ import { resolveDataDir } from './lib/argent-datadir.mjs'
31
+ import {
32
+ loadEnvFile, refreshStoreToken, apiGet as coreApiGet,
33
+ SITE_TZ, SITE_CURRENCY, fallbackSite, startOfLocalDayUTC, localDateStr, matchStores,
34
+ } from './lib/daily-report-core.mjs'
35
+ import {
36
+ fetchAdsReport, classifyAdsAlerts, adsCardLines, fmtMoney, ADS_ALERT_DEFAULTS,
37
+ ADS_METRICS_OFFICIAL, ADS_METRICS_LEGACY,
38
+ } from './lib/ml-ads-core.mjs'
39
+
40
+ const API_BASE = () => process.env.ML_API_BASE || 'https://api.mercadolibre.com'
41
+ // 引擎侧 `apiGet` 不硬编码域名(vertical 门禁)⇒ CLI 必须把基址注入进程环境,
42
+ // 否则 `refreshStoreToken` 这条内部路径会报「缺少 API 基址」(2026-11-25 实测)。
43
+ if (!process.env.ML_API_BASE) process.env.ML_API_BASE = API_BASE()
44
+
45
+ const args = process.argv.slice(2)
46
+ const argVal = (n) => { const i = args.indexOf(n); return i >= 0 && args[i + 1] ? args[i + 1] : null }
47
+ const has = (n) => args.includes(n)
48
+
49
+ if (has('-h') || has('--help')) {
50
+ console.log(`Mercado Ads 只读报告
51
+
52
+ 用法: node scripts/ml-ads.mjs [选项]
53
+ --store <名或uid> 店铺过滤(名称子串 / uid 全等,与日报同一判据)
54
+ --days <n> 回溯天数,默认 7(MELI 上限 90)
55
+ --to <YYYY-MM-DD> 结束日(站点本地),默认「昨天」
56
+ --detail 附活动级下钻(花钱最多 + ACoS 超标)
57
+ --list 只列出每店广告主(1 请求/店)
58
+ --probe-metrics 实测指标名:分别用「官方现行名」和「旧名」各拉 1 条,报告谁被接受(只读)
59
+ --json 结构化 JSON(stdout)
60
+ --lines 中文卡片行(给日报分区/角色回复复用)
61
+ --acos-warn <n> ACoS 黄色阈值,默认 ${ADS_ALERT_DEFAULTS.acosWarn}
62
+ --acos-bad <n> ACoS 红色阈值,默认 ${ADS_ALERT_DEFAULTS.acosBad}
63
+ --min-spend <n> 告警最小花费(本币),默认 ${ADS_ALERT_DEFAULTS.minSpend}
64
+ --env <path> daily-report.env 路径
65
+ 退出码: 0 正常 | 1 用法/取数失败 | 2 全部店铺失败`)
66
+ process.exit(0)
67
+ }
68
+
69
+ const DATA_DIR = resolveDataDir({ env: process.env }).dir
70
+ const ENV_PATH = argVal('--env') || join(DATA_DIR, 'daily-report.env')
71
+ const STORES_PATH = process.env.ML_API_STORES_JSON || join(DATA_DIR, 'ml-api-stores.json')
72
+ const env = loadEnvFile(ENV_PATH)
73
+ const doc = existsSync(STORES_PATH) ? JSON.parse(readFileSync(STORES_PATH, 'utf8')) : { stores: [] }
74
+ const stores = doc.stores || []
75
+
76
+ const persistStores = () => {
77
+ try {
78
+ mkdirSync(dirname(STORES_PATH), { recursive: true })
79
+ const tmp = `${STORES_PATH}.tmp`
80
+ writeFileSync(tmp, JSON.stringify({ stores }, null, 2) + '\n', { mode: 0o600 })
81
+ renameSync(tmp, STORES_PATH)
82
+ chmodSync(STORES_PATH, 0o600)
83
+ } catch (e) { console.error(`✗ token 写回失败:${e.message}`) }
84
+ }
85
+ const apiGet = (path, token) => coreApiGet(path, token, { base: API_BASE() })
86
+
87
+ const alertOpts = {
88
+ acosWarn: Number(argVal('--acos-warn') || ADS_ALERT_DEFAULTS.acosWarn),
89
+ acosBad: Number(argVal('--acos-bad') || ADS_ALERT_DEFAULTS.acosBad),
90
+ minSpend: Number(argVal('--min-spend') || ADS_ALERT_DEFAULTS.minSpend),
91
+ minRoas: ADS_ALERT_DEFAULTS.minRoas,
92
+ }
93
+
94
+ const FLAG_JSON = has('--json')
95
+ const FLAG_LINES = has('--lines')
96
+ const FLAG_DETAIL = has('--detail')
97
+ const FLAG_LIST = has('--list')
98
+ const FLAG_PROBE = has('--probe-metrics') // 客户机实测:官方现行 metrics 名 vs 旧名,谁被接受
99
+ const days = Math.max(1, Math.min(90, Number(argVal('--days') || 7)))
100
+ const toArg = argVal('--to')
101
+
102
+ const now = new Date()
103
+ const picked = matchStores(stores, (argVal('--store') || '').split(',').map((x) => x.trim()).filter(Boolean))
104
+ if (!picked.length) {
105
+ console.error(`✗ 没有匹配到店铺(已授权 ${stores.length} 家)`)
106
+ process.exit(1)
107
+ }
108
+
109
+ const results = []
110
+ for (const store of picked) {
111
+ const site = fallbackSite(store.site)
112
+ const tz = SITE_TZ[site]
113
+ const todayStart = startOfLocalDayUTC(tz, now)
114
+ const toMs = toArg ? startOfLocalDayUTC(tz, new Date(`${toArg}T12:00:00Z`)) : todayStart - 86400000
115
+ const fromMs = toMs - (days - 1) * 86400000
116
+ const dateFrom = localDateStr(tz, new Date(fromMs))
117
+ const dateTo = localDateStr(tz, new Date(toMs))
118
+ const row = { store: store.name, site, uid: store.user_id, currency: SITE_CURRENCY[site] || '', dateFrom, dateTo }
119
+ try {
120
+ const token = await refreshStoreToken(env, store, { onRotate: persistStores })
121
+ if (FLAG_PROBE) {
122
+ const adv = await apiGet('/advertising/advertisers?product_id=PADS', token)
123
+ const a0 = (adv.advertisers || [])[0]
124
+ if (!a0) { row.probe = { error: 'no_advertiser' }; results.push(row); continue }
125
+ const advSite = a0.site_id || site
126
+ const probe = {}
127
+ for (const [name, list] of [['official', ADS_METRICS_OFFICIAL], ['legacy', ADS_METRICS_LEGACY]]) {
128
+ const metrics = list.join(',')
129
+ try {
130
+ const q = new URLSearchParams({ limit: '1', offset: '0', date_from: dateFrom, date_to: dateTo, metrics })
131
+ const r = await apiGet(`/advertising/${advSite}/advertisers/${a0.advertiser_id}/product_ads/campaigns/search?${q}`, token)
132
+ const first = ((r && r.results) || [])[0] || {}
133
+ probe[name] = { ok: true, metrics, sampleKeys: Object.keys(first.metrics || {}).slice(0, 24) }
134
+ } catch (e) {
135
+ probe[name] = { ok: false, metrics, error: String(e.message || e).slice(0, 200) }
136
+ }
137
+ }
138
+ row.probe = probe
139
+ results.push(row)
140
+ continue
141
+ }
142
+ if (FLAG_LIST) {
143
+ const adv = await apiGet('/advertising/advertisers?product_id=PADS', token)
144
+ row.advertisers = (adv.advertisers || []).map((a) => ({ advertiser_id: a.advertiser_id, site: a.site_id, name: a.advertiser_name }))
145
+ results.push(row)
146
+ continue
147
+ }
148
+ const report = await fetchAdsReport({ apiGet, token, site, dateFrom, dateTo })
149
+ row.report = report
150
+ row.alerts = classifyAdsAlerts(report.totals, alertOpts)
151
+ results.push(row)
152
+ } catch (e) {
153
+ row.error = String(e.message || e)
154
+ results.push(row)
155
+ }
156
+ }
157
+
158
+ // ── 输出 ───────────────────────────────────────────────────
159
+ const ok = results.filter((r) => !r.error)
160
+ if (!ok.length) {
161
+ if (FLAG_JSON) console.log(JSON.stringify({ results }, null, 2))
162
+ else for (const r of results) console.error(`✗ ${r.store}:${r.error}`)
163
+ process.exit(2)
164
+ }
165
+ if (FLAG_PROBE) {
166
+ if (FLAG_JSON) { console.log(JSON.stringify({ generatedAt: now.toISOString(), results }, null, 2)); process.exit(0) }
167
+ for (const r of results) {
168
+ if (r.error) { console.log(`${r.store}: ✗ ${r.error}`); continue }
169
+ console.log(`### ${r.store}(${r.site})`)
170
+ for (const [k, p] of Object.entries(r.probe || {})) {
171
+ console.log(`- ${k}:${p.ok ? '✅ 被接受' : '❌ ' + p.error}`)
172
+ if (p.ok && p.sampleKeys && p.sampleKeys.length) console.log(` metrics 返回字段:${p.sampleKeys.join(', ')}`)
173
+ }
174
+ }
175
+ process.exit(0)
176
+ }
177
+
178
+ if (FLAG_JSON) { console.log(JSON.stringify({ generatedAt: now.toISOString(), days, results }, null, 2)); process.exit(0) }
179
+
180
+ if (FLAG_LINES) {
181
+ for (const r of ok) {
182
+ const lines = adsCardLines(r.report, { currency: r.currency, alertOpts })
183
+ console.log(`### ${r.store}`)
184
+ console.log(lines.join('\n'))
185
+ }
186
+ process.exit(0)
187
+ }
188
+
189
+ if (FLAG_LIST) {
190
+ for (const r of results) {
191
+ if (r.error) { console.log(`${r.store}: ✗ ${r.error}`); continue }
192
+ console.log(`${r.store}(${r.site}):` + (r.advertisers.length ? r.advertisers.map((a) => `${a.advertiser_id}(${a.site})`).join(', ') : '无广告主'))
193
+ }
194
+ process.exit(0)
195
+ }
196
+
197
+ const hdr = ['店铺', '站点', '花费', '销售额', 'ROAS', 'ACoS', '点击', 'CTR', '广告单量', '活动']
198
+ let text = `## 📣 Mercado Ads · ${ok[0].dateFrom} ~ ${ok[0].dateTo}(近 ${days} 天)\n\n`
199
+ text += '| ' + hdr.join(' | ') + ' |\n|' + hdr.map(() => '---').join('|') + '|\n'
200
+ const allAlerts = []
201
+ for (const r of results) {
202
+ if (r.error) { text += `| ${r.store} | ${r.site} | — | — | — | — | — | — | — | ✗ ${r.error.slice(0, 40)} |\n`; continue }
203
+ const t = r.report.totals
204
+ const c = r.currency ? r.currency + ' ' : ''
205
+ text += `| ${r.store} | ${r.site} | ${c}${fmtMoney(t.cost)} | ${c}${fmtMoney(t.amount)} | ${t.roas} | ${t.acos}% | ${t.clicks} | ${t.ctr}% | ${t.units} | ${t.campaigns} |\n`
206
+ for (const a of r.alerts) allAlerts.push({ store: r.store, ...a })
207
+ if (FLAG_DETAIL) {
208
+ for (const a of r.report.advertisers) {
209
+ const top = [...(a.topCampaigns.top || [])]
210
+ for (const cp of top) text += `| ↳ ${r.store}·${cp.name.slice(0, 24)} | ${a.advertiserId} | ${c}${fmtMoney(cp.cost)} | ${c}${fmtMoney(cp.amount)} | ${cp.roas} | ${cp.acos}% | ${cp.clicks} | — | ${cp.units} | — |\n`
211
+ }
212
+ }
213
+ }
214
+ text += '\n'
215
+ if (allAlerts.length) {
216
+ text += '### ⚠️ 告警\n'
217
+ for (const a of allAlerts) text += `- ${a.level === 'red' ? '🔴' : '🟡'} **${a.store}**:${a.text}\n`
218
+ } else {
219
+ text += '✅ 无告警(ACoS 与 ROAS 均在阈值内)\n'
220
+ }
221
+ console.log(text)
@@ -0,0 +1,174 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * ml-category-baseline.mjs —— 类目基线 / 行业简版 / 选品候选 / 热词雷达(C,只读)。
4
+ *
5
+ * 数据来源(**官方允许的只读端点**;2026-12-01 实测 `/sites/{site}/search` 对第三方不可用、`/items?ids=` 对部分 app 已弃用):
6
+ * · 自有商品:/users/{uid}/items/search(列 id)→ /items/{id}(单条详情,含 category_id/price/sold)
7
+ * · 竞品样本:ERP 竞品清单(机器令牌读 /market/competitor-items)→ /items/{id} 单条
8
+ * · 热词:/trends/{site}(L1:只有词,无搜索量)
9
+ * 口径:**基于客户指定竞品样本**(L2 窄版),不是全类目;已售=平台分桶参考值(估算,不是真实销量)。
10
+ * ⛔ 不抓页面、不推断真实销量、不写客户平台。
11
+ */
12
+ import { readFileSync, writeFileSync, renameSync, existsSync, mkdirSync } from 'node:fs'
13
+ import { join } from 'node:path'
14
+ import { resolveDataDir } from './lib/argent-datadir.mjs'
15
+ import { loadEnvFile, refreshStoreToken, apiGet as coreApiGet, SITE_CURRENCY, fallbackSite, matchStores } from './lib/daily-report-core.mjs'
16
+ import { bucketOfQuantity } from './lib/ml-market-core.mjs'
17
+ import { categoryBaseline, categoryBaselineLines, industryFromResults, selectionCandidates, industryLines } from './lib/ml-category-core.mjs'
18
+ import { resolveBridgeAuth, readAgentReport, assertBridgeAuth } from './lib/ml-bridge-auth.mjs'
19
+
20
+ const API_BASE = () => process.env.ML_API_BASE || 'https://api.mercadolibre.com'
21
+ if (!process.env.ML_API_BASE) process.env.ML_API_BASE = API_BASE()
22
+ const args = process.argv.slice(2)
23
+ const argVal = (n) => { const i = args.indexOf(n); return i >= 0 && args[i + 1] ? args[i + 1] : null }
24
+ const has = (n) => args.includes(n)
25
+ if (has('-h') || has('--help')) {
26
+ console.log(`类目基线 / 行业简版 / 选品候选 / 热词雷达(只读;L2 窄版口径)
27
+
28
+ 用法: node scripts/ml-category-baseline.mjs [选项]
29
+ --store <名或uid> 店铺(默认全部授权店)
30
+ --comps <n> 每店竞品样本上限(默认 30,上限 60;来源=ERP 竞品清单)
31
+ --json / --lines 输出格式
32
+ --push / --dry-run 推 ERP「智能分析 → 类目基线」(机器令牌)
33
+ 退出码: 0 正常 | 1 用法/无数据 | 2 推送失败`)
34
+ process.exit(0)
35
+ }
36
+ const DATA_DIR = resolveDataDir({ env: process.env }).dir
37
+ const ENV_PATH = argVal('--env') || join(DATA_DIR, 'daily-report.env')
38
+ if (!existsSync(ENV_PATH)) { console.error(`✗ 未找到 env:${ENV_PATH}`); process.exit(1) }
39
+ const env = loadEnvFile(ENV_PATH)
40
+ const STORES_PATH = join(DATA_DIR, 'ml-api-stores.json')
41
+ const stores = existsSync(STORES_PATH) ? (JSON.parse(readFileSync(STORES_PATH, 'utf8')).stores || []) : []
42
+ const compLimit = Math.max(1, Math.min(60, Number(argVal('--comps') || 30)))
43
+ const queries = (argVal('--store') || '').split(',').map((x) => x.trim()).filter(Boolean)
44
+ const picked = matchStores(stores, queries)
45
+ if (!picked.length) { console.error(`✗ 没有匹配到店铺(已授权 ${stores.length} 家)`); process.exit(1) }
46
+
47
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
48
+ const safeGet = async (path, token, tries = 2) => {
49
+ for (let i = 0; i < tries; i++) {
50
+ try { return await coreApiGet(path, token) } catch (e) {
51
+ const msg = String((e && e.message) || e)
52
+ if (/HTTP 40[34]/.test(msg)) throw e
53
+ if (i === tries - 1) throw e
54
+ await sleep(1200)
55
+ }
56
+ }
57
+ }
58
+ const itemInfo = async (id, token) => {
59
+ const r = await safeGet(`/items/${encodeURIComponent(id)}`, token)
60
+ return {
61
+ itemId: String(r.id || id), title: String(r.title || ''), price: r.price,
62
+ categoryId: String(r.category_id || ''),
63
+ sellerId: r.seller_id ? String(r.seller_id) : '',
64
+ sold: r.sold_quantity ?? null,
65
+ rating: null,
66
+ permalink: String(r.permalink || ''),
67
+ }
68
+ }
69
+
70
+ /** 读 ERP 竞品清单(机器令牌;失败 ⇒ 空数组,不影响自有类目基线)。 */
71
+ async function fetchErpCompetitors(auth) {
72
+ try {
73
+ const url = `${auth.base.replace(/\/+$/, '')}/api/argent/v1/tenants/${encodeURIComponent(auth.tenant)}/market/competitor-items`
74
+ const headers = auth.machineToken ? { authorization: `Bearer ${auth.machineToken}` } : { 'x-appointment-secret': auth.secret }
75
+ const res = await fetch(url, { headers, signal: AbortSignal.timeout(15000) })
76
+ const body = await res.json().catch(() => ({}))
77
+ const items = body && body.data && Array.isArray(body.data.items) ? body.data.items : []
78
+ return items.map((x) => String(x)).filter((x) => /^[A-Za-z0-9]{4,40}$/.test(x))
79
+ } catch { return [] }
80
+ }
81
+
82
+ const auth = has('--push') ? resolveBridgeAuth({ env: process.env, agentReport: readAgentReport({ file: join(DATA_DIR, 'agent-report.json') }) }) : null
83
+ if (has('--push')) assertBridgeAuth(auth)
84
+ const erpComps = auth ? await fetchErpCompetitors(auth) : []
85
+ if (auth && !erpComps.length) console.error('⚠ ERP 竞品清单为空 ⇒ 行业/选品仅基于自有商品(去 ERP「智能分析 → 竞品设置」维护)')
86
+
87
+ const results = []
88
+ for (const store of picked) {
89
+ const site = fallbackSite(store.site)
90
+ const row = { store: store.name, site, currency: SITE_CURRENCY[site] || '', categories: [], trends: [] }
91
+ try {
92
+ const token = await refreshStoreToken(env, store, { onRotate: () => {} })
93
+ // 热词雷达(L1:只有词,无搜索量)
94
+ try {
95
+ const tr = await safeGet(`/trends/${site}`, token)
96
+ row.trends = (Array.isArray(tr) ? tr : []).slice(0, 12).map((x) => String(x && (x.keyword || x) || '')).filter(Boolean)
97
+ } catch (e) { row.warn = '热词不可用:' + String((e && e.message) || e).slice(0, 80) }
98
+ // 自有商品:列 id(最多 20)→ 单条详情
99
+ const own = []
100
+ const list = await safeGet(`/users/${encodeURIComponent(store.user_id)}/items/search?status=active&limit=20`, token).catch(() => null)
101
+ for (const id of ((list && list.results) || []).slice(0, 20)) {
102
+ try { own.push({ ...(await itemInfo(id, token)), role: 'own' }); await sleep(120) } catch {}
103
+ }
104
+ // 竞品样本:ERP 清单(≤60)→ 单条详情
105
+ const comps = []
106
+ for (const id of erpComps.slice(0, compLimit)) {
107
+ try { comps.push({ ...(await itemInfo(id, token)), role: 'competitor' }); await sleep(120) } catch {}
108
+ }
109
+ const all = [...own, ...comps]
110
+ const byCat = new Map()
111
+ for (const it of all) {
112
+ const cat = it.categoryId || 'unknown'
113
+ if (!byCat.has(cat)) byCat.set(cat, [])
114
+ byCat.get(cat).push(it)
115
+ }
116
+ for (const [catId, items] of [...byCat.entries()].slice(0, 8)) {
117
+ const prices = items.map((x) => x.price).filter((p) => Number(p) > 0)
118
+ const ownItem = items.find((x) => x.role === 'own' && Number(x.price) > 0)
119
+ const rowsSample = items.map((x) => ({ itemId: x.itemId, title: x.title, price: x.price, rating: null, sold: x.sold, sellerId: x.sellerId, brand: '' }))
120
+ const base = categoryBaseline({ categoryId: catId, total: null, results: rowsSample }, { ourPrice: ownItem ? ownItem.price : null })
121
+ base.industry = industryFromResults(rowsSample)
122
+ base.candidates = selectionCandidates(rowsSample, { limit: 10 })
123
+ base.source = '客户指定竞品样本(ERP 竞品设置)'
124
+ base.note = '口径:客户指定竞品样本,不是全类目;在售总数不可得(官方搜索对本 app 不可用);已售=平台分桶参考值(估算)'
125
+ base.sample = true
126
+ results.length // noop
127
+ if (!prices.length) continue
128
+ row.categories.push(base)
129
+ }
130
+ if (!row.categories.length) row.error = '没有可统计的类目(自有/竞品商品都没有 category_id)'
131
+ results.push(row)
132
+ } catch (e) { row.error = String((e && e.message) || e); results.push(row) }
133
+ }
134
+ const okRows = results.filter((r) => !r.error && r.categories.length)
135
+ if (!okRows.length) { for (const r of results) console.error(`✗ ${r.store}:${r.error || '无类目数据'}`); process.exit(1) }
136
+
137
+ if (has('--push')) {
138
+ let fail = 0
139
+ for (const r of okRows) {
140
+ const payload = {
141
+ store: r.store, site: r.site, capturedAt: new Date().toISOString(), currency: r.currency,
142
+ categories: r.categories, trends: r.trends,
143
+ }
144
+ if (has('--dry-run')) { console.log(JSON.stringify({ dryRun: true, authMode: auth.mode, payload }, null, 2)); continue }
145
+ const url = `${auth.base.replace(/\/+$/, '')}/api/argent/v1/tenants/${encodeURIComponent(auth.tenant)}/reports/category/bridge`
146
+ const headers = { 'content-type': 'application/json', ...(auth.machineToken ? { authorization: `Bearer ${auth.machineToken}` } : {}), ...(auth.secret ? { 'x-appointment-secret': auth.secret } : {}) }
147
+ const res = await fetch(url, { method: 'POST', headers, body: JSON.stringify(payload), signal: AbortSignal.timeout(20000) }).catch((e) => ({ ok: false, status: 0, json: async () => ({ message: String(e.message) }) }))
148
+ const body = await res.json().catch(() => ({}))
149
+ if (res.ok) console.error(`✓ ${r.store} 类目基线已推 ERP(${payload.categories.length} 类目)`)
150
+ else { fail++; console.error(`✗ ${r.store} 推送失败:HTTP ${res.status} ${JSON.stringify(body).slice(0, 160)}`) }
151
+ }
152
+ if (fail) process.exit(2)
153
+ }
154
+ const CACHE = join(DATA_DIR, 'ml-category-cache', 'latest.json')
155
+ mkdirSync(join(DATA_DIR, 'ml-category-cache'), { recursive: true, mode: 0o700 })
156
+ const doc = { generatedAt: new Date().toISOString(), rows: okRows }
157
+ writeFileSync(CACHE + '.tmp', JSON.stringify(doc, null, 2), { mode: 0o600 })
158
+ renameSync(CACHE + '.tmp', CACHE)
159
+ if (has('--json')) { console.log(JSON.stringify(doc, null, 2)); process.exit(0) }
160
+ const lines = []
161
+ for (const r of okRows) {
162
+ lines.push(`### ${r.store}(${r.site})`)
163
+ if (r.trends.length) lines.push(`热词雷达(L1,无搜索量):${r.trends.slice(0, 10).join(' / ')}`)
164
+ for (const c of r.categories) {
165
+ lines.push(...categoryBaselineLines(c, { currency: r.currency }))
166
+ if (c.industry) lines.push(...industryLines(c.industry))
167
+ if (Array.isArray(c.candidates) && c.candidates.length) {
168
+ lines.push('选品候选(已售≈档位,估算):')
169
+ for (const x of c.candidates.slice(0, 5)) lines.push(` ${x.rank}. ${x.title || x.itemId} · ${r.currency} ${x.price} · 已售≈${x.soldRef ?? '—'}`)
170
+ }
171
+ lines.push(` ⚠ ${c.source};${c.note}`, '')
172
+ }
173
+ }
174
+ console.log(lines.join('\n'))
@@ -0,0 +1,247 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * ml-insight-diagnose.mjs —— 店铺诊断(P1 L2,**只读**):facts 取数 → 判据/评分 → 结构化诊断。
4
+ *
5
+ * ## 干什么
6
+ * 逐店取「销售/流量/广告/风险/库存/Listing/竞品」事实 → `assessStore()`(纯函数)→
7
+ * 输出健康分、五维评分、信号(含归因/建议/证据链)与缺数据清单。
8
+ *
9
+ * ## 用法
10
+ * node scripts/ml-insight-diagnose.mjs # 全部已授权店铺(近 7 天)
11
+ * node scripts/ml-insight-diagnose.mjs --store 1店 # 店铺过滤(名称子串 / user_id)
12
+ * node scripts/ml-insight-diagnose.mjs --json # 结构化(MCP/ERP 复用)
13
+ * node scripts/ml-insight-diagnose.mjs --lines # 中文卡片行
14
+ * node scripts/ml-insight-diagnose.mjs --facts ./facts.json # 跳过取数,直接诊断一份事实(回放/排障)
15
+ * node scripts/ml-insight-diagnose.mjs --market-file ./x.jsonl # 指定竞品快照(默认数据目录 ml-market/<store>.jsonl)
16
+ * node scripts/ml-insight-diagnose.mjs --no-ads --no-listing # 跳过某些数据源(降配额)
17
+ *
18
+ * ## 只读纪律(同 ml-listing/ml-ads/ml-market)
19
+ * · 只发 GET;⛔ 不改商品/价格/广告,不写客户任何系统;唯一写盘 = token 轮换回写(原子 600);
20
+ * · API 基址:`ML_API_BASE`(引擎 lib 不含域名,只在本 CLI 注入)。
21
+ */
22
+ import { readFileSync, writeFileSync, renameSync, existsSync, mkdirSync, chmodSync, readdirSync, statSync } from 'node:fs'
23
+ import { join, dirname } from 'node:path'
24
+ import { resolveDataDir } from './lib/argent-datadir.mjs'
25
+ import {
26
+ loadEnvFile, refreshStoreToken, apiGet as coreApiGet,
27
+ SITE_CURRENCY, fallbackSite, matchStores, storeKey,
28
+ } from './lib/daily-report-core.mjs'
29
+ import { collectFacts, factsFromDailySnapshot, factsFromMarketLines } from './lib/ml-insight-facts.mjs'
30
+ import { resolveBridgeAuth, readAgentReport, assertBridgeAuth } from './lib/ml-bridge-auth.mjs'
31
+ import { assessStore, renderDiagnosisLines, buildInsightBridgePayload, pushInsightReport, DEFAULT_THRESHOLDS } from './lib/ml-insight-core.mjs'
32
+
33
+ const API_BASE = () => process.env.ML_API_BASE || 'https://api.mercadolibre.com'
34
+ // 引擎侧 `apiGet` 不硬编码域名(vertical 门禁)⇒ CLI 负责把基址显式注入进程环境,
35
+ // 否则 `refreshStoreToken` 这条内部路径会报「缺少 API 基址」。
36
+ if (!process.env.ML_API_BASE) process.env.ML_API_BASE = API_BASE()
37
+ const args = process.argv.slice(2)
38
+ const argVal = (n) => { const i = args.indexOf(n); return i >= 0 && args[i + 1] ? args[i + 1] : null }
39
+ const has = (n) => args.includes(n)
40
+
41
+ if (has('-h') || has('--help')) {
42
+ console.log(`店铺诊断(只读)
43
+
44
+ 用法: node scripts/ml-insight-diagnose.mjs [选项]
45
+ --store <名或uid> 店铺过滤(名称子串 / user_id 全等)
46
+ --days <n> 观测窗口天数,默认 7
47
+ --visit-limit <n> 访客抽样商品数,默认 20(1~2 请求/商品)
48
+ --price-limit <n> price_to_win 抽样商品数,默认 10
49
+ --listing-limit <n> Listing 体检抽样数,默认 20
50
+ --market-file <path> 竞品快照 JSONL(默认数据目录 ml-market/<storeKey>.jsonl)
51
+ --facts <path> 跳过取数,直接诊断一份 facts JSON(回放/排障)
52
+ --source <auto|snapshot|api>
53
+ 事实来源:auto=只用日报快照(**零请求**;无快照⇒该店跳过,⛔ 不回退全量现拉);
54
+ api=全量现拉(≈230 请求/店,仅排障);默认 auto
55
+ --snapshot-max-age-hours <n>
56
+ 快照最老小时数(默认 72;定时器用 6 ⇒ 只诊断刚由日报写出的快照)
57
+ --allow-empty 全部店铺都没有新快照时退出码 0(定时器用;不当作失败)
58
+ --snapshot <path> 指定日报快照文件(默认自动找 daily-report-cache 里最近一份,≤3 天)
59
+ --with-live 强制现拉(访客/广告/价格/to_win 只有现拉才有)
60
+ --no-ads / --no-listing / --no-traffic / --no-price / --no-risk 跳过对应数据源
61
+ --json 结构化 JSON(stdout)
62
+ --lines 中文卡片行
63
+ --push 把诊断结论上报 ERP(POST /reports/insight/bridge;只报结论,不改商品)
64
+ 鉴权优先用机器令牌(agent-report.json#machineToken,推荐);共享密钥仅过渡兼容
65
+ --dry-run 配 --push 时只打印上报 body(不联网),用于核对契约
66
+ --api <url> ERP 地址(缺省读 ARGENT_API_BASE)
67
+ --tenant <appId> 租户 appId(缺省读 ARGENT_TENANT)
68
+ --env <path> daily-report.env 路径
69
+ 退出码: 0 正常 | 1 用法/取数失败 | 2 全部店铺失败`)
70
+ process.exit(0)
71
+ }
72
+
73
+ const DATA_DIR = resolveDataDir({ env: process.env }).dir
74
+ const ENV_PATH = argVal('--env') || join(DATA_DIR, 'daily-report.env')
75
+ const STORES_PATH = process.env.ML_API_STORES_JSON || join(DATA_DIR, 'ml-api-stores.json')
76
+ const env = loadEnvFile(ENV_PATH)
77
+ const doc = existsSync(STORES_PATH) ? JSON.parse(readFileSync(STORES_PATH, 'utf8')) : { stores: [] }
78
+ const stores = doc.stores || []
79
+ const persistStores = () => {
80
+ try {
81
+ mkdirSync(dirname(STORES_PATH), { recursive: true })
82
+ const tmp = `${STORES_PATH}.tmp`
83
+ writeFileSync(tmp, JSON.stringify({ stores }, null, 2) + '\n', { mode: 0o600 })
84
+ renameSync(tmp, STORES_PATH)
85
+ chmodSync(STORES_PATH, 0o600)
86
+ } catch (e) { console.error(`✗ token 写回失败:${e.message}`) }
87
+ }
88
+ const apiGet = (path, token) => {
89
+ if (process.env.ML_INSIGHT_DEBUG) console.error(`[api] ${String(path).slice(0, 160)}`)
90
+ return coreApiGet(path, token, { base: API_BASE() })
91
+ }
92
+
93
+ const FLAG_JSON = has('--json')
94
+ const FLAG_LINES = has('--lines')
95
+ const days = Math.max(1, Math.min(28, Number(argVal('--days') || 7)))
96
+ const factsFile = argVal('--facts')
97
+ const SOURCE = (argVal('--source') || (has('--with-live') ? 'api' : 'auto')).toLowerCase()
98
+ const SNAPSHOT_ARG = argVal('--snapshot')
99
+ const SNAPSHOT_MAX_AGE_HOURS = Math.max(1, Number(argVal('--snapshot-max-age-hours') || 72))
100
+ const ALLOW_EMPTY = has('--allow-empty')
101
+
102
+ /** 找最近一份日报快照(`<DATA_HOME>/daily-report-cache/<date>-store-<uid>.json`)。 */
103
+ function findDailySnapshot(store) {
104
+ if (SNAPSHOT_ARG) return existsSync(SNAPSHOT_ARG) ? SNAPSHOT_ARG : null
105
+ const dir = join(DATA_DIR, 'daily-report-cache')
106
+ if (!existsSync(dir)) return null
107
+ const suffix = `-store-${store.user_id}.json`
108
+ let best = null
109
+ for (const fn of readdirSync(dir)) {
110
+ if (!fn.endsWith(suffix)) continue
111
+ const date = fn.slice(0, 10)
112
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) continue
113
+ // 2026-11-29 修复:新鲜度按**文件 mtime**算,⛔ 不能按文件名日期当 00:00(否则下午必然>6h,
114
+ // 诊断定时器整天跳过 ⇒ ERP 诊断数据停在旧日期,客户以为"没效果")。
115
+ const file = join(dir, fn)
116
+ let mtimeMs = 0
117
+ try { mtimeMs = statSync(file).mtimeMs } catch { continue }
118
+ const ageHours = (Date.now() - mtimeMs) / 3600000
119
+ if (ageHours > SNAPSHOT_MAX_AGE_HOURS) continue
120
+ if (!best || mtimeMs > best.mtimeMs) best = { date, file, mtimeMs }
121
+ }
122
+ return best ? best.file : null
123
+ }
124
+
125
+ /** 读日检缓存(ml-listing 定时器落的 latest.json),零请求拿到 Listing 质量分。 */
126
+ function readListingCache(storeName) {
127
+ const f = join(DATA_DIR, 'ml-listing-cache', 'latest.json')
128
+ if (!existsSync(f)) return null
129
+ try {
130
+ const j = JSON.parse(readFileSync(f, 'utf8'))
131
+ const row = (j.results || []).find((x) => x && x.store === storeName)
132
+ const sum = row && row.summary
133
+ if (!sum || sum.scored == null) return null
134
+ return { avgScore: sum.avg, pendingTotal: sum.pendingTotal, count: sum.count, scored: sum.scored, cachedAt: String(j.generatedAt || '') }
135
+ } catch { return null }
136
+ }
137
+ const marketFileArg = argVal('--market-file')
138
+ const opts = {
139
+ days,
140
+ visitsLimit: Math.max(1, Math.min(50, Number(argVal('--visit-limit') || 20))),
141
+ priceLimit: Math.max(1, Math.min(50, Number(argVal('--price-limit') || 10))),
142
+ listingLimit: Math.max(1, Math.min(50, Number(argVal('--listing-limit') || 20))),
143
+ ads: !has('--no-ads'), listing: !has('--no-listing'), traffic: !has('--no-traffic'),
144
+ priceToWin: !has('--no-price'), risk: !has('--no-risk'),
145
+ }
146
+
147
+ const results = []
148
+ if (factsFile) {
149
+ // 回放模式:只诊断,不取数(不读 token、不联网)
150
+ try {
151
+ const facts = JSON.parse(readFileSync(factsFile, 'utf8'))
152
+ results.push({ store: facts.store, site: facts.site, factsSummary: undefined, diagnosis: assessStore(facts) })
153
+ } catch (e) {
154
+ console.error(`✗ 读 facts 失败:${e.message}`)
155
+ process.exit(1)
156
+ }
157
+ } else {
158
+ const picked = matchStores(stores, (argVal('--store') || '').split(',').map((x) => x.trim()).filter(Boolean))
159
+ if (!picked.length) { console.error(`✗ 没有匹配到店铺(已授权 ${stores.length} 家)`); process.exit(1) }
160
+ for (const store of picked) {
161
+ const site = fallbackSite(store.site)
162
+ const row = { store: store.name, site, currency: SITE_CURRENCY[site] || '' }
163
+ try {
164
+ const mf = marketFileArg || join(DATA_DIR, 'ml-market', `${storeKey(store)}.jsonl`)
165
+ const marketLines = existsSync(mf) ? readFileSync(mf, 'utf8').split('\n').filter(Boolean) : []
166
+ let facts = null
167
+ if (SOURCE !== 'api') {
168
+ const snapFile = findDailySnapshot(store)
169
+ if (snapFile) {
170
+ const snap = JSON.parse(readFileSync(snapFile, 'utf8'))
171
+ const itemPrices = Object.values(snap.itemById || {}).map((x) => Number(x && x.price)).filter((x) => Number.isFinite(x) && x > 0).sort((a, b) => a - b)
172
+ const ourPrice = itemPrices.length ? itemPrices[Math.floor(itemPrices.length / 2)] : null
173
+ facts = factsFromDailySnapshot({
174
+ snapshot: snap,
175
+ facts: {
176
+ market: factsFromMarketLines({ marketLines, ourPrice }),
177
+ listing: readListingCache(store.name),
178
+ },
179
+ })
180
+ row.snapshot = snapFile
181
+ } else if (SOURCE === 'snapshot') {
182
+ throw new Error('没有可用的日报快照(≤3 天);先跑一次日报,或用 --source api')
183
+ }
184
+ }
185
+ if (!facts) {
186
+ // auto/snapshot 模式都**不**回退全量现拉(防封控):没有 ≤N 小时的日报快照就跳过该店
187
+ if (SOURCE !== 'api') throw new Error(`没有 ${SNAPSHOT_MAX_AGE_HOURS}h 内的日报快照(先跑日报,或用 --with-live / --source api)`)
188
+ const token = await refreshStoreToken(env, store, { onRotate: persistStores })
189
+ facts = await collectFacts({ apiGet, token, store, opts, marketLines })
190
+ }
191
+ row.diagnosis = assessStore(facts)
192
+ row.coverage = facts.coverage
193
+ results.push(row)
194
+ } catch (e) {
195
+ row.error = String((e && e.message) || e)
196
+ results.push(row)
197
+ }
198
+ }
199
+ }
200
+
201
+ // ── 上报 ERP(--push):只上报诊断结论(⛔ 不含 raw facts / token)────────────
202
+ let PUSH_FAIL = 0
203
+ if (has('--push')) {
204
+ const report = readAgentReport({ file: join(DATA_DIR, 'agent-report.json') })
205
+ const auth = resolveBridgeAuth({ env: { ...process.env, ...(argVal('--api') ? { ARGENT_API_BASE: argVal('--api') } : {}), ...(argVal('--tenant') ? { ARGENT_TENANT: argVal('--tenant') } : {}) }, agentReport: report })
206
+ assertBridgeAuth(auth)
207
+ const dry = has('--dry-run')
208
+ if (auth.mode !== 'machine') console.error('⚠ 未找到机器令牌,回退共享密钥模式(建议在 ERP「机器管理」签发 machine token)')
209
+ for (const r of results) {
210
+ if (r.error || !r.diagnosis) continue
211
+ let payload
212
+ try { payload = buildInsightBridgePayload(r.diagnosis) } catch (e) { r.pushError = String((e && e.message) || e); PUSH_FAIL++; continue }
213
+ if (dry) {
214
+ const url = `${auth.base.replace(/\/+$/, '')}/api/argent/v1/tenants/${encodeURIComponent(auth.tenant)}/reports/insight/bridge`
215
+ console.log(JSON.stringify({ dryRun: true, authMode: auth.mode, url, payload }, null, 2)); r.pushOk = true; r.dryRun = true; continue
216
+ }
217
+ try {
218
+ const res = await pushInsightReport(payload, { base: auth.base, tenant: auth.tenant, secret: auth.secret, machineToken: auth.machineToken })
219
+ if (res.ok) { r.pushOk = true; r.pushStatus = res.status } else { r.pushOk = false; r.pushError = res.error; PUSH_FAIL++ }
220
+ } catch (e) { r.pushOk = false; r.pushError = String((e && e.message) || e); PUSH_FAIL++ }
221
+ }
222
+ if (!dry && PUSH_FAIL) console.error(`✗ ${PUSH_FAIL} 店诊断上报失败`)
223
+ }
224
+
225
+ const ok = results.filter((r) => !r.error)
226
+ if (!ok.length) {
227
+ if (FLAG_JSON) console.log(JSON.stringify({ results }, null, 2))
228
+ else for (const r of results) console.error(`✗ ${r.store}:${r.error}`)
229
+ process.exit(ALLOW_EMPTY ? 0 : 2)
230
+ }
231
+ if (FLAG_JSON) {
232
+ console.log(JSON.stringify({ generatedAt: new Date().toISOString(), days, thresholds: DEFAULT_THRESHOLDS, results }, null, 2))
233
+ process.exit(PUSH_FAIL ? 1 : 0)
234
+ }
235
+ if (FLAG_LINES) {
236
+ for (const r of ok) { console.log(`### ${r.store}`); console.log(renderDiagnosisLines(r.diagnosis, { currency: r.currency }).join('\n')) }
237
+ process.exit(PUSH_FAIL ? 1 : 0)
238
+ }
239
+ let text = `## 🩺 店铺诊断(近 ${days} 天)\n\n`
240
+ for (const r of results) {
241
+ if (r.error) { text += `### ${r.store}(${r.site})\n✗ ${r.error}\n\n`; continue }
242
+ text += renderDiagnosisLines(r.diagnosis, { currency: r.currency }).join('\n') + '\n\n'
243
+ if (r.coverage && r.coverage.missing && r.coverage.missing.length) {
244
+ text += `> 缺数据:${r.coverage.missing.slice(0, 6).join(';')}\n\n`
245
+ }
246
+ }
247
+ console.log(text)