@whyshu/argent-engine 0.8.0-rc.9 → 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.
- package/MANIFEST.json +102 -40
- package/bin/runtime-install.mjs +92 -0
- package/engine/VERSION +1 -1
- package/engine/configs/billing-actions.json +30 -0
- package/engine/configs/mcp-tools.snapshot.json +47 -0
- package/engine/core/contracts/argent.contracts.json +2 -2
- package/engine/core/lib/account-token.mjs +37 -0
- package/engine/core/lib/redact.mjs +34 -0
- package/engine/core/mcp/billing-upload.mjs +77 -0
- package/engine/core/mcp/erp-server.mjs +300 -0
- package/engine/core/mcp/gateway.mjs +333 -0
- package/engine/core/mcp/meter.mjs +101 -0
- package/engine/core/mcp/server.mjs +245 -0
- package/engine/core/mcp/vault.mjs +78 -0
- package/engine/scripts/appointment-worker.mjs +456 -35
- package/engine/scripts/appointment_grab.py +1389 -264
- package/engine/scripts/appointment_rules.py +118 -0
- package/engine/scripts/argent-timers.mjs +227 -0
- package/engine/scripts/argent-web-preflight.mjs +123 -0
- package/engine/scripts/argent-web-verify.mjs +105 -0
- package/engine/scripts/billing-upload.mjs +26 -0
- package/engine/scripts/build-engine-package.mjs +7 -1
- package/engine/scripts/capability-packs.lock.json +323 -300
- package/engine/scripts/check-version-consistency.mjs +14 -1
- package/engine/scripts/collect-intel.mjs +108 -0
- package/engine/scripts/daily-report-timer-plist.sh +18 -4
- package/engine/scripts/daily-report-timers.sh +36 -3
- package/engine/scripts/daily-report.mjs +78 -2
- package/engine/scripts/dsh-web-doctor.mjs +84 -0
- package/engine/scripts/engine-manifest.mjs +90 -0
- package/engine/scripts/engine-runtime-install.mjs +92 -0
- package/engine/scripts/erp-ui-install.mjs +127 -0
- package/engine/scripts/erp-ui-preflight.mjs +104 -0
- package/engine/scripts/erp-ui-verify.mjs +135 -0
- package/engine/scripts/flow-requirements.json +122 -99
- package/engine/scripts/full-exec-worker.mjs +251 -0
- package/engine/scripts/gen-preset-rows.mjs +1 -1
- package/engine/scripts/invoice_lip_runner.py +1 -0
- package/engine/scripts/invoice_runner.py +17 -6
- package/engine/scripts/invoice_stageb.py +21 -4
- package/engine/scripts/lib/bootcheck-wiring.mjs +7 -5
- package/engine/scripts/lib/intel-card.mjs +43 -0
- package/engine/scripts/lib/invoice_names.py +23 -0
- package/engine/scripts/lib/ml-ads-core.mjs +100 -18
- package/engine/scripts/lib/ml-ads-rules.mjs +275 -0
- package/engine/scripts/lib/ml-bridge-auth.mjs +50 -0
- package/engine/scripts/lib/ml-category-core.mjs +120 -0
- package/engine/scripts/lib/ml-insight-core.mjs +621 -0
- package/engine/scripts/lib/ml-insight-facts.mjs +424 -0
- package/engine/scripts/lib/ml-items.mjs +40 -0
- package/engine/scripts/lib/ml-listing-core.mjs +342 -0
- package/engine/scripts/lib/ml-market-core.mjs +774 -0
- package/engine/scripts/lib/plugin-packages.mjs +13 -0
- package/engine/scripts/lib/webdriver_ipc.py +61 -1
- package/engine/scripts/line_pack.py +196 -0
- package/engine/scripts/mcp-gateway-switch.mjs +100 -0
- package/engine/scripts/migrate-providers.mjs +3 -3
- package/engine/scripts/ml-ads-advice.mjs +140 -0
- package/engine/scripts/ml-ads.mjs +40 -0
- package/engine/scripts/ml-category-baseline.mjs +174 -0
- package/engine/scripts/ml-insight-diagnose.mjs +247 -0
- package/engine/scripts/ml-insight-run.sh +183 -0
- package/engine/scripts/ml-insight-timers.sh +224 -0
- package/engine/scripts/ml-listing-audit.mjs +170 -0
- package/engine/scripts/ml-market-matrix.mjs +84 -0
- package/engine/scripts/ml-market-snapshot.mjs +261 -0
- package/engine/scripts/ml-messages.mjs +145 -0
- package/engine/scripts/npm-publish-argent.mjs +14 -0
- package/engine/scripts/ops-codefix-pr.mjs +87 -0
- package/engine/scripts/ops-codefix-queue.mjs +30 -0
- package/engine/scripts/ops-digest.mjs +98 -0
- package/engine/scripts/ops-verify.mjs +67 -0
- package/engine/scripts/orchestrator.py +410 -20
- package/engine/scripts/orchestrator_br.py +146 -4
- package/engine/scripts/plugin-bootcheck.mjs +50 -1
- package/engine/scripts/publish-engine.mjs +111 -0
- package/engine/scripts/restart-dsh-with-tunnel.sh +129 -0
- package/engine/scripts/skuflow_invoice_runner.py +43 -3
- package/engine/scripts/v0.9-acceptance.mjs +107 -0
- package/engine/scripts/vertical-lint.mjs +12 -1
- package/engine/scripts/web-switch.mjs +121 -0
- package/engine/scripts/wenyao_fill_template.py +52 -15
- package/engine/scripts/wenyao_run.py +2 -1
- package/engine/skills/README.md +3 -3
- package/engine/skills/bilibili-upload/SKILL.md +109 -0
- package/engine/skills/douyin-upload/SKILL.md +74 -0
- package/engine/skills/internal.json +28 -0
- package/engine/skills/kuaishou-upload/SKILL.md +109 -0
- package/engine/skills/ml-appointment-safety/SKILL.md +42 -0
- package/engine/skills/ml-full-appointment/SKILL.md +23 -0
- package/engine/skills/ml-invoice/SKILL.md +2 -2
- package/engine/skills/ml-invoice/references/template-fill-contract.md +1 -1
- package/engine/skills/ml-label-recovery/SKILL.md +43 -0
- package/engine/skills/ml-listing-audit/SKILL.md +66 -0
- package/engine/skills/ml-store-daily-report/SKILL.md +68 -0
- package/engine/skills/ml-store-daily-report/scripts/generate.js +35 -0
- package/engine/skills/ml-store-insight/SKILL.md +81 -0
- package/engine/skills/tencent-upload/SKILL.md +60 -0
- package/engine/skills/weibo-upload/SKILL.md +106 -0
- package/engine/skills/whyshu-social-ops/SKILL.md +136 -0
- package/engine/skills/xiaohongshu-upload/SKILL.md +122 -0
- package/engine/version.mjs +1 -1
- package/engine/verticals/README.md +7 -0
- package/engine/verticals/_engine-words.baseline.txt +27 -59
- package/engine/verticals/mercadolibre/manifest.json +132 -6
- package/package.json +5 -1
|
@@ -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)
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
#!/bin/bash
|
|
2
|
+
# ml-insight-run.sh —— **Listing 体检 / 竞品快照**的定时器入口(launchd 直跑,⛔ 不唤醒任何 LLM 会话)。
|
|
3
|
+
#
|
|
4
|
+
# 用法:bash scripts/ml-insight-run.sh <listing|market>
|
|
5
|
+
# · listing:`ml-listing-audit.mjs --push`(体检结果推 ERP「刊登优化」页)
|
|
6
|
+
# · market :`ml-market-snapshot.mjs`(自有在售 + 客户竞品快照,滚历史)
|
|
7
|
+
# · diagnose:`ml-insight-diagnose.mjs --push`(店铺诊断结论推 ERP「AI 建议(诊断)」tab)
|
|
8
|
+
#
|
|
9
|
+
# 零命令化(2026-11-20):客户不敲命令 —— 定时器由 ml-insight-timers.sh 装一次,
|
|
10
|
+
# 开关/时间/抽样数来自设置页(`daily-report.env` 的 ML_LISTING_* / ML_MARKET_*)。
|
|
11
|
+
# 本脚本只做「读配置 → 判断启用 → 调用确定性 CLI → 落日志」,不写客户数据。
|
|
12
|
+
set -uo pipefail
|
|
13
|
+
|
|
14
|
+
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
|
15
|
+
. "$SCRIPT_DIR/lib/argent-datadir.sh" # 数据根唯一判据
|
|
16
|
+
|
|
17
|
+
JOB="${1:-}"
|
|
18
|
+
case "$JOB" in
|
|
19
|
+
listing|market|diagnose|ads|messages|category) ;;
|
|
20
|
+
*) echo "用法: bash scripts/ml-insight-run.sh <listing|market|diagnose|ads|messages|category>" >&2; exit 2 ;;
|
|
21
|
+
esac
|
|
22
|
+
|
|
23
|
+
# 隔离守卫:没有 argent runtime(脚本不在 ~/.argent-dsh/scripts)就不是本机的事
|
|
24
|
+
PROFILE_HOME="${ARGENT_PROFILE_HOME:-$HOME/.argent-dsh}"
|
|
25
|
+
if [ ! -d "$PROFILE_HOME" ]; then
|
|
26
|
+
echo "[ml-insight-run] 未安装 argent-dsh(${PROFILE_HOME}),跳过(隔离守卫)" >&2
|
|
27
|
+
exit 0
|
|
28
|
+
fi
|
|
29
|
+
|
|
30
|
+
DATA_HOME="${ARGENT_DATA_HOME:-$ARGENT_DATA_DIR_RESOLVED}"
|
|
31
|
+
LOG_DIR="$DATA_HOME/ml-insight-logs"
|
|
32
|
+
mkdir -p "$LOG_DIR" 2>/dev/null || true
|
|
33
|
+
LOG="$LOG_DIR/$JOB.log"
|
|
34
|
+
now() { date '+%F %T'; }
|
|
35
|
+
|
|
36
|
+
NODE_BIN="$(command -v node || true)"
|
|
37
|
+
if [ -z "$NODE_BIN" ]; then
|
|
38
|
+
echo "[$(now)] ❌ 未找到 node(PATH 缺 node 目录)⇒ 定时器无法运行" >> "$LOG"
|
|
39
|
+
exit 1
|
|
40
|
+
fi
|
|
41
|
+
|
|
42
|
+
ENV_FILE=""
|
|
43
|
+
for cand in "${ML_INSIGHT_ENV_FILE:-}" "$DATA_HOME/daily-report.env"; do
|
|
44
|
+
if [ -n "$cand" ] && [ -f "$cand" ]; then ENV_FILE="$cand"; break; fi
|
|
45
|
+
done
|
|
46
|
+
if [ -z "$ENV_FILE" ]; then
|
|
47
|
+
echo "[$(now)] ❌ 未找到 daily-report.env ⇒ 跳过(先在设置页保存过一次配置)" >> "$LOG"
|
|
48
|
+
exit 0
|
|
49
|
+
fi
|
|
50
|
+
|
|
51
|
+
# 只读解析 env(不 source:避免把客户脚本当配置执行)
|
|
52
|
+
env_get() { grep -E "^[[:space:]]*$1=" "$ENV_FILE" 2>/dev/null | tail -1 | cut -d= -f2- | tr -d '"' | tr -d "'" | sed 's/[[:space:]]*$//'; }
|
|
53
|
+
|
|
54
|
+
# 上报通道(2026-11-25 起设置页可配;⛔ 不回显):
|
|
55
|
+
# · 机器令牌:默认自动读 ~/.dsh/argent/agent-report.json(推荐,零配置)
|
|
56
|
+
# · 共享密钥:仅过渡兼容,三个变量来自设置页写入的 daily-report.env
|
|
57
|
+
export ARGENT_API_BASE="$(env_get ARGENT_API_BASE)"
|
|
58
|
+
export ARGENT_TENANT="$(env_get ARGENT_TENANT)"
|
|
59
|
+
export DAILY_REPORT_BRIDGE_SECRET="$(env_get DAILY_REPORT_BRIDGE_SECRET)"
|
|
60
|
+
export APPOINTMENT_BRIDGE_SECRET="$(env_get APPOINTMENT_BRIDGE_SECRET)"
|
|
61
|
+
|
|
62
|
+
# 有 agent-report.json(机器令牌)或设置页配了地址+租户+密钥 ⇒ 带 --push
|
|
63
|
+
push_ready() {
|
|
64
|
+
[ -f "$DATA_HOME/agent-report.json" ] && return 0
|
|
65
|
+
[ -n "$ARGENT_API_BASE" ] && [ -n "$ARGENT_TENANT" ] && { [ -n "$DAILY_REPORT_BRIDGE_SECRET" ] || [ -n "$APPOINTMENT_BRIDGE_SECRET" ]; } && return 0
|
|
66
|
+
return 1
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
echo "[$(now)] ▶ 开始(job=$JOB env=${ENV_FILE})" >> "$LOG"
|
|
70
|
+
|
|
71
|
+
# 状态文件(2026-11-20):给 `argent_timers` / ERP 看板一个"上次跑/上次退出码"的只读出口;
|
|
72
|
+
# 与 daily-report-timer-status.json 同一模式(每轮覆盖,不写业务数据)。
|
|
73
|
+
STATUS_FILE="$DATA_HOME/ml-insight-$JOB-status.json"
|
|
74
|
+
status_write() { # $1 = JSON 片段
|
|
75
|
+
"$NODE_BIN" -e '
|
|
76
|
+
const fs = require("fs")
|
|
77
|
+
const p = process.argv[1]
|
|
78
|
+
const add = JSON.parse(process.argv[2])
|
|
79
|
+
let j = {}
|
|
80
|
+
try { j = JSON.parse(fs.readFileSync(p, "utf8")) } catch {}
|
|
81
|
+
Object.assign(j, add)
|
|
82
|
+
fs.writeFileSync(p, JSON.stringify(j, null, 2))
|
|
83
|
+
' "$STATUS_FILE" "$1" 2>/dev/null || true
|
|
84
|
+
}
|
|
85
|
+
status_write "{\"job\":\"$JOB\",\"lastRunAt\":\"$(date -u +%FT%TZ)\",\"lastExit\":null,\"lastError\":\"\",\"skipped\":\"\"}"
|
|
86
|
+
code=1
|
|
87
|
+
if [ "$JOB" = "diagnose" ]; then
|
|
88
|
+
if [ "$(env_get ML_INSIGHT_ENABLED)" != "true" ]; then
|
|
89
|
+
echo "[$(now)] ⏭ ML_INSIGHT_ENABLED 未开 ⇒ 跳过" >> "$LOG"
|
|
90
|
+
status_write "{\"job\":\"$JOB\",\"lastFinishAt\":\"$(date -u +%FT%TZ)\",\"lastExit\":0,\"lastError\":\"未启用(设置页「启用店铺诊断」开关)\",\"skipped\":\"disabled\"}"
|
|
91
|
+
exit 0
|
|
92
|
+
fi
|
|
93
|
+
VISIT_LIMIT="$(env_get ML_INSIGHT_VISIT_LIMIT)"; VISIT_LIMIT="${VISIT_LIMIT:-10}"
|
|
94
|
+
PRICE_LIMIT="$(env_get ML_INSIGHT_PRICE_LIMIT)"; PRICE_LIMIT="${PRICE_LIMIT:-5}"
|
|
95
|
+
LISTING_LIMIT="$(env_get ML_INSIGHT_LISTING_LIMIT)"; LISTING_LIMIT="${LISTING_LIMIT:-10}"
|
|
96
|
+
# 2026-11-25:默认**只用日报快照(零请求)**,且只诊断 ≤6h 内新写的快照;没有就跳过(⛔ 不回退全量现拉)
|
|
97
|
+
D_ARGS=(--env "$ENV_FILE" --json --source auto --snapshot-max-age-hours 6 --allow-empty)
|
|
98
|
+
if push_ready; then
|
|
99
|
+
D_ARGS+=(--push)
|
|
100
|
+
else
|
|
101
|
+
echo "[$(now)] ⚠ 无机器令牌(agent-report.json)也无可设置页上报配置 ⇒ 本轮只诊断、不推 ERP" >> "$LOG"
|
|
102
|
+
fi
|
|
103
|
+
"$NODE_BIN" "$SCRIPT_DIR/ml-insight-diagnose.mjs" "${D_ARGS[@]}" >> "$LOG" 2>&1
|
|
104
|
+
code=$?
|
|
105
|
+
elif [ "$JOB" = "listing" ]; then
|
|
106
|
+
if [ "$(env_get ML_LISTING_ENABLED)" != "true" ]; then
|
|
107
|
+
echo "[$(now)] ⏭ ML_LISTING_ENABLED 未开 ⇒ 跳过" >> "$LOG"
|
|
108
|
+
status_write "{\"job\":\"$JOB\",\"lastFinishAt\":\"$(date -u +%FT%TZ)\",\"lastExit\":0,\"lastError\":\"未启用(设置页「启用 Listing 体检」开关)\",\"skipped\":\"disabled\"}"
|
|
109
|
+
exit 0
|
|
110
|
+
fi
|
|
111
|
+
LIMIT="$(env_get ML_LISTING_LIMIT)"; LIMIT="${LIMIT:-20}"
|
|
112
|
+
PUSH_ARGS=()
|
|
113
|
+
# 只有配了 bridge(ERP 地址/租户/密钥)才推送;否则仍出一份只读报告,不阻断
|
|
114
|
+
if push_ready; then
|
|
115
|
+
PUSH_ARGS=(--push)
|
|
116
|
+
else
|
|
117
|
+
echo "[$(now)] ⚠ 无机器令牌(agent-report.json)也无可设置页上报配置 ⇒ 本轮只读、不推 ERP" >> "$LOG"
|
|
118
|
+
fi
|
|
119
|
+
# 同时把结构化结果落缓存:诊断(snapshot 模式)可**零请求**复用 Listing 质量分
|
|
120
|
+
CACHE_DIR="$DATA_HOME/ml-listing-cache"
|
|
121
|
+
mkdir -p "$CACHE_DIR" 2>/dev/null || true
|
|
122
|
+
"$NODE_BIN" "$SCRIPT_DIR/ml-listing-audit.mjs" --env "$ENV_FILE" --limit "$LIMIT" --json "${PUSH_ARGS[@]}" \
|
|
123
|
+
> "$CACHE_DIR/latest.json" 2>> "$LOG"
|
|
124
|
+
code=$?
|
|
125
|
+
elif [ "$JOB" = "category" ]; then
|
|
126
|
+
# C(2026-12-01):类目基线/行业简版(只读官方搜索;⛔ 不推断销量、不抓页面)
|
|
127
|
+
if [ "$(env_get ML_CATEGORY_ENABLED)" != "true" ]; then
|
|
128
|
+
echo "[$(now)] ⏭ ML_CATEGORY_ENABLED 未开 ⇒ 跳过" >> "$LOG"
|
|
129
|
+
status_write "{\"job\":\"$JOB\",\"lastFinishAt\":\"$(date -u +%FT%TZ)\",\"lastExit\":0,\"lastError\":\"未启用(设置页「启用类目基线」开关)\",\"skipped\":\"disabled\"}"
|
|
130
|
+
exit 0
|
|
131
|
+
fi
|
|
132
|
+
C_LIMIT="$(env_get ML_CATEGORY_LIMIT)"; C_LIMIT="${C_LIMIT:-50}"
|
|
133
|
+
C_ARGS=(--env "$ENV_FILE" --limit "$C_LIMIT")
|
|
134
|
+
if push_ready; then C_ARGS+=(--push); else echo "[$(now)] ⚠ 无上报配置 ⇒ 本轮只做本地类目基线、不推 ERP" >> "$LOG"; fi
|
|
135
|
+
"$NODE_BIN" "$SCRIPT_DIR/ml-category-baseline.mjs" "${C_ARGS[@]}" >> "$LOG" 2>&1
|
|
136
|
+
code=$?
|
|
137
|
+
elif [ "$JOB" = "messages" ]; then
|
|
138
|
+
# B(2026-12-01):消息只读监控 + 回复草稿(⛔ 不回复客户)
|
|
139
|
+
if [ "$(env_get ML_MESSAGES_ENABLED)" != "true" ]; then
|
|
140
|
+
echo "[$(now)] ⏭ ML_MESSAGES_ENABLED 未开 ⇒ 跳过" >> "$LOG"
|
|
141
|
+
status_write "{\"job\":\"$JOB\",\"lastFinishAt\":\"$(date -u +%FT%TZ)\",\"lastExit\":0,\"lastError\":\"未启用(设置页「启用消息监控」开关)\",\"skipped\":\"disabled\"}"
|
|
142
|
+
exit 0
|
|
143
|
+
fi
|
|
144
|
+
M_LIMIT="$(env_get ML_MESSAGES_LIMIT)"; M_LIMIT="${M_LIMIT:-20}"
|
|
145
|
+
M_ARGS=(--env "$ENV_FILE" --limit "$M_LIMIT")
|
|
146
|
+
if push_ready; then M_ARGS+=(--push); else echo "[$(now)] ⚠ 无上报配置 ⇒ 本轮只读消息、不推 ERP" >> "$LOG"; fi
|
|
147
|
+
"$NODE_BIN" "$SCRIPT_DIR/ml-messages.mjs" "${M_ARGS[@]}" >> "$LOG" 2>&1
|
|
148
|
+
code=$?
|
|
149
|
+
elif [ "$JOB" = "ads" ]; then
|
|
150
|
+
# A(2026-12-01):广告建议单 → ERP「智能分析 → 广告诊断」(只读;⛔ 不改预算/出价/暂停)
|
|
151
|
+
if [ "$(env_get ML_ADS_ENABLED)" != "true" ]; then
|
|
152
|
+
echo "[$(now)] ⏭ ML_ADS_ENABLED 未开 ⇒ 跳过" >> "$LOG"
|
|
153
|
+
status_write "{\"job\":\"$JOB\",\"lastFinishAt\":\"$(date -u +%FT%TZ)\",\"lastExit\":0,\"lastError\":\"未启用(设置页「启用广告诊断」开关)\",\"skipped\":\"disabled\"}"
|
|
154
|
+
exit 0
|
|
155
|
+
fi
|
|
156
|
+
A_DAYS="$(env_get ML_ADS_DAYS)"; A_DAYS="${A_DAYS:-7}"
|
|
157
|
+
A_ARGS=(--env "$ENV_FILE" --days "$A_DAYS")
|
|
158
|
+
if push_ready; then A_ARGS+=(--push); else echo "[$(now)] ⚠ 无上报配置 ⇒ 本轮只读广告诊断、不推 ERP" >> "$LOG"; fi
|
|
159
|
+
"$NODE_BIN" "$SCRIPT_DIR/ml-ads-advice.mjs" "${A_ARGS[@]}" >> "$LOG" 2>&1
|
|
160
|
+
code=$?
|
|
161
|
+
else
|
|
162
|
+
if [ "$(env_get ML_MARKET_ENABLED)" != "true" ]; then
|
|
163
|
+
echo "[$(now)] ⏭ ML_MARKET_ENABLED 未开 ⇒ 跳过" >> "$LOG"
|
|
164
|
+
status_write "{\"job\":\"$JOB\",\"lastFinishAt\":\"$(date -u +%FT%TZ)\",\"lastExit\":0,\"lastError\":\"未启用(设置页「启用竞品快照」开关)\",\"skipped\":\"disabled\"}"
|
|
165
|
+
exit 0
|
|
166
|
+
fi
|
|
167
|
+
DAYS="$(env_get ML_MARKET_DAYS)"; DAYS="${DAYS:-30}"
|
|
168
|
+
"$NODE_BIN" "$SCRIPT_DIR/ml-market-snapshot.mjs" --env "$ENV_FILE" --days "$DAYS" --items-from-erp >> "$LOG" 2>&1
|
|
169
|
+
code=$?
|
|
170
|
+
# 采完即推矩阵(P2b):快照是本地事实,矩阵推 ERP「智能分析→竞品矩阵」;推送失败不覆盖采样退出码
|
|
171
|
+
if [ "$code" -eq 0 ] && push_ready; then
|
|
172
|
+
"$NODE_BIN" "$SCRIPT_DIR/ml-market-matrix.mjs" --env "$ENV_FILE" --days "$DAYS" --push >> "$LOG" 2>&1 || echo "[$(now)] ⚠ 竞品矩阵推送失败(采样成功,下轮重试)" >> "$LOG"
|
|
173
|
+
fi
|
|
174
|
+
fi
|
|
175
|
+
|
|
176
|
+
if [ "$code" -eq 0 ]; then echo "[$(now)] ✅ 结束(job=$JOB exit=0)" >> "$LOG"
|
|
177
|
+
else echo "[$(now)] ❌ 结束(job=$JOB exit=${code})—— 尾巴见 $LOG" >> "$LOG"; fi
|
|
178
|
+
if [ "$code" -eq 0 ]; then
|
|
179
|
+
status_write "{\"job\":\"$JOB\",\"lastFinishAt\":\"$(date -u +%FT%TZ)\",\"lastExit\":0,\"lastError\":\"\"}"
|
|
180
|
+
else
|
|
181
|
+
status_write "{\"job\":\"$JOB\",\"lastFinishAt\":\"$(date -u +%FT%TZ)\",\"lastExit\":$code,\"lastError\":\"见 $LOG\"}"
|
|
182
|
+
fi
|
|
183
|
+
exit "$code"
|