@whyshu/argent-engine 0.8.0-rc.13 → 0.8.0-rc.15

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 (74) hide show
  1. package/MANIFEST.json +71 -36
  2. package/engine/VERSION +1 -1
  3. package/engine/configs/mcp-tools.snapshot.json +8 -1
  4. package/engine/core/contracts/argent.contracts.json +2 -2
  5. package/engine/core/mcp/erp-server.mjs +10 -6
  6. package/engine/core/mcp/gateway.mjs +3 -3
  7. package/engine/core/mcp/server.mjs +245 -0
  8. package/engine/scripts/appointment-worker.mjs +456 -35
  9. package/engine/scripts/appointment_grab.py +1329 -284
  10. package/engine/scripts/appointment_rules.py +118 -0
  11. package/engine/scripts/argent-timers.mjs +227 -0
  12. package/engine/scripts/capability-packs.lock.json +323 -300
  13. package/engine/scripts/check-version-consistency.mjs +14 -1
  14. package/engine/scripts/collect-intel.mjs +108 -0
  15. package/engine/scripts/daily-report-timer-plist.sh +18 -4
  16. package/engine/scripts/daily-report-timers.sh +1 -1
  17. package/engine/scripts/daily-report.mjs +22 -0
  18. package/engine/scripts/engine-manifest.mjs +90 -0
  19. package/engine/scripts/flow-requirements.json +122 -99
  20. package/engine/scripts/full-exec-worker.mjs +251 -0
  21. package/engine/scripts/gen-preset-rows.mjs +1 -1
  22. package/engine/scripts/invoice_lip_runner.py +1 -0
  23. package/engine/scripts/invoice_runner.py +3 -1
  24. package/engine/scripts/lib/bootcheck-wiring.mjs +7 -5
  25. package/engine/scripts/lib/intel-card.mjs +43 -0
  26. package/engine/scripts/lib/invoice_names.py +23 -0
  27. package/engine/scripts/lib/ml-ads-core.mjs +100 -18
  28. package/engine/scripts/lib/ml-ads-rules.mjs +275 -0
  29. package/engine/scripts/lib/ml-bridge-auth.mjs +50 -0
  30. package/engine/scripts/lib/ml-category-core.mjs +120 -0
  31. package/engine/scripts/lib/ml-insight-core.mjs +621 -0
  32. package/engine/scripts/lib/ml-insight-facts.mjs +424 -0
  33. package/engine/scripts/lib/ml-items.mjs +40 -0
  34. package/engine/scripts/lib/ml-listing-core.mjs +342 -0
  35. package/engine/scripts/lib/ml-market-core.mjs +774 -0
  36. package/engine/scripts/lib/webdriver_ipc.py +61 -1
  37. package/engine/scripts/line_pack.py +196 -0
  38. package/engine/scripts/ml-ads-advice.mjs +140 -0
  39. package/engine/scripts/ml-ads.mjs +40 -0
  40. package/engine/scripts/ml-category-baseline.mjs +174 -0
  41. package/engine/scripts/ml-insight-diagnose.mjs +247 -0
  42. package/engine/scripts/ml-insight-run.sh +183 -0
  43. package/engine/scripts/ml-insight-timers.sh +224 -0
  44. package/engine/scripts/ml-listing-audit.mjs +170 -0
  45. package/engine/scripts/ml-market-matrix.mjs +84 -0
  46. package/engine/scripts/ml-market-snapshot.mjs +261 -0
  47. package/engine/scripts/ml-messages.mjs +145 -0
  48. package/engine/scripts/npm-publish-argent.mjs +14 -0
  49. package/engine/scripts/ops-codefix-pr.mjs +87 -0
  50. package/engine/scripts/ops-codefix-queue.mjs +30 -0
  51. package/engine/scripts/ops-digest.mjs +98 -0
  52. package/engine/scripts/ops-verify.mjs +67 -0
  53. package/engine/scripts/orchestrator.py +410 -20
  54. package/engine/scripts/orchestrator_br.py +146 -4
  55. package/engine/scripts/plugin-bootcheck.mjs +50 -1
  56. package/engine/scripts/publish-engine.mjs +111 -0
  57. package/engine/scripts/restart-dsh-with-tunnel.sh +129 -0
  58. package/engine/scripts/skuflow_invoice_runner.py +24 -3
  59. package/engine/scripts/vertical-lint.mjs +12 -1
  60. package/engine/scripts/wenyao_fill_template.py +52 -15
  61. package/engine/scripts/wenyao_run.py +2 -1
  62. package/engine/skills/ml-appointment-safety/SKILL.md +42 -0
  63. package/engine/skills/ml-full-appointment/SKILL.md +23 -0
  64. package/engine/skills/ml-invoice/SKILL.md +2 -2
  65. package/engine/skills/ml-invoice/references/template-fill-contract.md +1 -1
  66. package/engine/skills/ml-label-recovery/SKILL.md +43 -0
  67. package/engine/skills/ml-listing-audit/SKILL.md +66 -0
  68. package/engine/skills/ml-store-daily-report/scripts/generate.js +35 -0
  69. package/engine/skills/ml-store-insight/SKILL.md +81 -0
  70. package/engine/version.mjs +1 -1
  71. package/engine/verticals/README.md +7 -0
  72. package/engine/verticals/_engine-words.baseline.txt +27 -59
  73. package/engine/verticals/mercadolibre/manifest.json +132 -6
  74. package/package.json +1 -1
@@ -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"
@@ -0,0 +1,224 @@
1
+ #!/usr/bin/env bash
2
+ # ml-insight-timers.sh —— **Listing 体检 / 竞品快照**的确定性定时器(安装/卸载/状态,2026-11-20)。
3
+ #
4
+ # 目的(零命令化):客户不敲命令 —— 装一次定时器,之后每天自动跑:
5
+ # · com.whyshu.ml-listing-timer → ml-insight-run.sh listing(体检 + 推 ERP「刊登优化」页)
6
+ # · com.whyshu.ml-market-timer → ml-insight-run.sh market (自有在售 + 客户竞品快照)
7
+ # · com.whyshu.ml-insight-timer → ml-insight-run.sh diagnose(店铺诊断 + 推 ERP「AI 建议」tab)
8
+ #
9
+ # 开关与时间来自设置页写入的 `daily-report.env`:
10
+ # ML_LISTING_ENABLED / ML_LISTING_TIME(默认 09:40)/ ML_LISTING_LIMIT(默认 20)
11
+ # ML_MARKET_ENABLED / ML_MARKET_TIME(默认 10:10)/ ML_MARKET_DAYS(默认 30)
12
+ # ML_ADS_ENABLED / ML_ADS_TIME(默认 11:00)/ ML_ADS_DAYS(默认 7)
13
+ # ML_MESSAGES_ENABLED / ML_MESSAGES_TIME(默认 11:30)/ ML_MESSAGES_LIMIT(默认 20)
14
+ # ML_CATEGORY_ENABLED / ML_CATEGORY_TIME(默认 12:00)/ ML_CATEGORY_LIMIT(默认 50)
15
+ # ML_INSIGHT_ENABLED(开关;小时 :20 跑,只处理 ≤6h 新日报快照,零请求;无新快照自动跳过)
16
+ # ⚠️ 时间是**客户机本地时区**(当前=北京时间);改时间后需重跑 install 让 plist 生效。
17
+ #
18
+ # 用法:
19
+ # bash scripts/ml-insight-timers.sh status
20
+ # bash scripts/ml-insight-timers.sh print-plist [listing|market|diagnose]
21
+ # bash scripts/ml-insight-timers.sh install [--dry-run] [--force] [--allow-non-production]
22
+ # bash scripts/ml-insight-timers.sh uninstall
23
+ # bash scripts/ml-insight-timers.sh run-now <listing|market|diagnose>
24
+ #
25
+ # ⛔ 开发机默认拒绝 install(生产姿态门禁);真装必须在客户机(本机 bootstrap 生产型调度器是红线)。
26
+ set -euo pipefail
27
+
28
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
29
+ . "$SCRIPT_DIR/lib/argent-datadir.sh"
30
+
31
+ LABEL_LISTING="com.whyshu.ml-listing-timer"
32
+ LABEL_MARKET="com.whyshu.ml-market-timer"
33
+ LABEL_DIAGNOSE="com.whyshu.ml-insight-timer"
34
+ LABEL_ADS="com.whyshu.ml-ads-timer"
35
+ LABEL_MESSAGES="com.whyshu.ml-messages-timer"
36
+ LABEL_CATEGORY="com.whyshu.ml-category-timer"
37
+ AGENTS="$HOME/Library/LaunchAgents"
38
+ DATA_HOME="${ARGENT_DATA_DIR_RESOLVED:?数据根解析失败:请显式给 ARGENT_DATA_DIR}"
39
+ LOG_DIR="$DATA_HOME/ml-insight-logs"
40
+ RUNNER="$SCRIPT_DIR/ml-insight-run.sh"
41
+ GEN="$SCRIPT_DIR/daily-report-timer-plist.sh"
42
+ ENV_FILE="$DATA_HOME/daily-report.env"
43
+
44
+ usage() { sed -n '2,22p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; }
45
+ now() { date '+%F %T'; }
46
+
47
+ find_bin_dir() { # $1=可执行名;$2..=回退候选目录
48
+ local name="$1"; shift
49
+ local hit; hit="$(command -v "$name" 2>/dev/null || true)"
50
+ if [ -n "$hit" ]; then dirname "$hit"; return 0; fi
51
+ local d
52
+ for d in "$@"; do [ -x "$d/$name" ] && { printf '%s' "$d"; return 0; }; done
53
+ printf '/usr/local/bin'
54
+ }
55
+ node_dir() { find_bin_dir node "$HOME/.local/node/bin" "$HOME/node/bin" /opt/homebrew/bin /usr/local/bin; }
56
+ lark_dir() { find_bin_dir lark-cli "$HOME/.local/bin" "$HOME/.local/node/bin" /opt/homebrew/bin /usr/local/bin; }
57
+
58
+ env_get() {
59
+ [ -f "$ENV_FILE" ] || return 0
60
+ grep -E "^[[:space:]]*$1=" "$ENV_FILE" 2>/dev/null | tail -1 | cut -d= -f2- | tr -d '"' | tr -d "'" | sed 's/[[:space:]]*$//'
61
+ }
62
+
63
+ # "HH:MM" → HOUR MINUTE(缺省 09:40 / 10:10;非法值回落缺省并显式告警)
64
+ split_hhmm() { # $1=值 $2=缺省
65
+ local v="${1:-}"; local def="$2"
66
+ [ -n "$v" ] || v="$def"
67
+ case "$v" in
68
+ [0-2][0-9]:[0-5][0-9]) ;;
69
+ *) echo "⚠ $v 不是 HH:MM,回落缺省 $def" >&2; v="$def" ;;
70
+ esac
71
+ HOUR="${v%%:*}"; MINUTE="${v##*:}"
72
+ # 去掉前导 0 供 launchd integer
73
+ HOUR="$((10#$HOUR))"; MINUTE="$((10#$MINUTE))"
74
+ }
75
+
76
+ gen() { # $1=listing|market(纯 stdout)
77
+ local job="$1" hour minute label logname
78
+ if [ "$job" = "listing" ]; then
79
+ split_hhmm "$(env_get ML_LISTING_TIME)" "09:40"; label="$LABEL_LISTING"; logname="ml-listing-timer"
80
+ elif [ "$job" = "category" ]; then
81
+ split_hhmm "$(env_get ML_CATEGORY_TIME)" "12:00"; label="$LABEL_CATEGORY"; logname="ml-category-timer"
82
+ elif [ "$job" = "messages" ]; then
83
+ split_hhmm "$(env_get ML_MESSAGES_TIME)" "11:30"; label="$LABEL_MESSAGES"; logname="ml-messages-timer"
84
+ elif [ "$job" = "ads" ]; then
85
+ split_hhmm "$(env_get ML_ADS_TIME)" "11:00"; label="$LABEL_ADS"; logname="ml-ads-timer"
86
+ elif [ "$job" = "diagnose" ]; then
87
+ # 2026-11-25:诊断跟日报节拍(日报每小时 :05 按站点本地时间门控)⇒ 诊断每小时 :20 跑,
88
+ # 脚本内只处理"≤6h 新快照"的店;没有新快照就跳过(零请求)。
89
+ HOUR=""; MINUTE="20"; label="$LABEL_DIAGNOSE"; logname="ml-insight-timer"
90
+ else
91
+ split_hhmm "$(env_get ML_MARKET_TIME)" "10:10"; label="$LABEL_MARKET"; logname="ml-market-timer"
92
+ fi
93
+ # ⚠️ macOS bash 3.2 + `set -u`:**空数组展开会报 unbound variable**(2026-11-29 客户机实测),
94
+ # 所以有/无 --hour 两条分支各写一遍,⛔ 不要用 "${arr[@]}" 展开可能为空的数组。
95
+ if [ -n "$HOUR" ]; then
96
+ bash "$GEN" --label "$label" --script "$RUNNER" \
97
+ --data-dir "$DATA_HOME" --log-dir "$LOG_DIR" \
98
+ --node-dir "$(node_dir)" --lark-dir "$(lark_dir)" \
99
+ --log-name "$logname" --arg "$job" --hour "$HOUR" --minute "$MINUTE"
100
+ else
101
+ bash "$GEN" --label "$label" --script "$RUNNER" \
102
+ --data-dir "$DATA_HOME" --log-dir "$LOG_DIR" \
103
+ --node-dir "$(node_dir)" --lark-dir "$(lark_dir)" \
104
+ --log-name "$logname" --arg "$job" --minute "$MINUTE"
105
+ fi
106
+ }
107
+
108
+ is_production() {
109
+ # 放行条件(任一):config.json dailyReport.role=production | allowedChatIds 非空 | --allow-non-production
110
+ local role allow
111
+ role="$(/usr/bin/python3 - "$DATA_HOME/config.json" <<'PYEOF' 2>/dev/null || true
112
+ import json, sys
113
+ try:
114
+ d = json.load(open(sys.argv[1]))
115
+ print((d.get('dailyReport') or {}).get('role', ''))
116
+ except Exception:
117
+ print('')
118
+ PYEOF
119
+ )"
120
+ allow="$(/usr/bin/python3 - "$DATA_HOME/config.json" <<'PYEOF' 2>/dev/null || true
121
+ import json, sys
122
+ try:
123
+ d = json.load(open(sys.argv[1]))
124
+ print(len((d.get('dailyReport') or {}).get('allowedChatIds') or []))
125
+ except Exception:
126
+ print('0')
127
+ PYEOF
128
+ )"
129
+ [ "$role" = "production" ] && return 0
130
+ [ "${allow:-0}" -gt 0 ] && return 0
131
+ return 1
132
+ }
133
+
134
+ label_for_job() {
135
+ case "$1" in
136
+ listing) echo "$LABEL_LISTING" ;;
137
+ market) echo "$LABEL_MARKET" ;;
138
+ ads) echo "$LABEL_ADS" ;;
139
+ messages) echo "$LABEL_MESSAGES" ;;
140
+ category) echo "$LABEL_CATEGORY" ;;
141
+ *) echo "$LABEL_DIAGNOSE" ;;
142
+ esac
143
+ }
144
+
145
+ do_install() {
146
+ local dry=0 force=0 allow_np=0
147
+ for a in "$@"; do
148
+ case "$a" in
149
+ --dry-run) dry=1 ;;
150
+ --force) force=1 ;;
151
+ --allow-non-production) allow_np=1 ;;
152
+ *) echo "未知参数: $a" >&2; exit 2 ;;
153
+ esac
154
+ done
155
+ if [ "$allow_np" = "0" ] && ! is_production; then
156
+ cat >&2 <<MSG
157
+ ❌ 拒绝安装:本机不是「Listing 体检/竞品快照」生产机(dailyReport.role=$(/usr/bin/python3 - "$DATA_HOME/config.json" <<'PY' 2>/dev/null || true
158
+ import json,sys
159
+ try: print((json.load(open(sys.argv[1])).get('dailyReport') or {}).get('role',''))
160
+ except Exception: print('')
161
+ PY
162
+ ),allowedChatIds 见 config.json)
163
+ 这条定时器会定时打平台 API 并推客户 ERP ⇒ 开发机装它 = 双跑。
164
+ 要在客户机装:在客户的 ~/.dsh/argent/config.json 设
165
+ "dailyReport": { "role": "production" }
166
+ 或显式加 --allow-non-production(自己承担后果)。
167
+ MSG
168
+ exit 3
169
+ fi
170
+ [ -n "$(env_get ML_LISTING_ENABLED)$(env_get ML_MARKET_ENABLED)$(env_get ML_INSIGHT_ENABLED)" ] || echo "⚠ daily-report.env 里没有 ML_LISTING_ENABLED/ML_MARKET_ENABLED/ML_INSIGHT_ENABLED;定时器会每小时空跑(脚本内判断启用)" >&2
171
+ mkdir -p "$AGENTS" "$LOG_DIR"
172
+ # ⚠️ 新增任务必须同时加进这个循环(2026-12-01 客户机实测:漏了 ads/messages/category ⇒
173
+ # "安装"显示成功但新定时器没装上)。
174
+ # ⚠️ 标签用独立函数取:multi-line case 放进 $( ) 在 macOS bash 3.2 会被拆错
175
+ # (客户机 0.13.25 实测:filename "esac ).plist: File name too long")。
176
+ for job in listing market diagnose ads messages category; do
177
+ local plist="$AGENTS/$(label_for_job "$job").plist"
178
+ gen "$job" > /tmp/ml-insight-$job.plist
179
+ if [ "$dry" = "1" ]; then
180
+ echo "── 将写入 ${plist}:"; cat /tmp/ml-insight-$job.plist
181
+ continue
182
+ fi
183
+ cp /tmp/ml-insight-$job.plist "$plist"
184
+ chmod 644 "$plist"
185
+ launchctl bootout "gui/$(id -u)" "$plist" 2>/dev/null || true
186
+ launchctl bootstrap "gui/$(id -u)" "$plist"
187
+ echo "✅ 已安装 $plist"
188
+ done
189
+ [ "$dry" = "1" ] || { chmod +x "$RUNNER" 2>/dev/null || true; echo "✅ 入口脚本可执行:$RUNNER"; }
190
+ }
191
+
192
+ do_status() {
193
+ echo "数据根:$DATA_HOME"
194
+ [ -f "$ENV_FILE" ] && echo "env:$ENV_FILE" || echo "env:(缺)"
195
+ echo "开关:ML_LISTING_ENABLED=$(env_get ML_LISTING_ENABLED || true) ML_MARKET_ENABLED=$(env_get ML_MARKET_ENABLED || true) ML_INSIGHT_ENABLED=$(env_get ML_INSIGHT_ENABLED || true)"
196
+ echo "时间:ML_LISTING_TIME=$(env_get ML_LISTING_TIME || true) ML_MARKET_TIME=$(env_get ML_MARKET_TIME || true) ML_ADS_TIME=$(env_get ML_ADS_TIME || true) insight=每小时 :20(跟随日报快照) (客户机本地时区)"
197
+ for l in "$LABEL_LISTING" "$LABEL_MARKET" "$LABEL_DIAGNOSE" "$LABEL_ADS" "$LABEL_MESSAGES" "$LABEL_CATEGORY"; do
198
+ if launchctl list 2>/dev/null | grep -q "[[:space:]]$l\$"; then echo "launchd:$l ✅ 已加载"; else echo "launchd:$l ❌ 未加载"; fi
199
+ done
200
+ ls -1 "$LOG_DIR"/*.log 2>/dev/null | sed 's/^/日志:/' || true
201
+ }
202
+
203
+ do_uninstall() {
204
+ for l in "$LABEL_LISTING" "$LABEL_MARKET" "$LABEL_DIAGNOSE" "$LABEL_ADS" "$LABEL_MESSAGES" "$LABEL_CATEGORY"; do
205
+ local plist="$AGENTS/$l.plist"
206
+ if [ -f "$plist" ]; then
207
+ launchctl bootout "gui/$(id -u)" "$plist" 2>/dev/null || true
208
+ rm -f "$plist"; echo "✅ 已卸载 $l"
209
+ else
210
+ echo "(未安装)$l"
211
+ fi
212
+ done
213
+ }
214
+
215
+ cmd="${1:-}"; shift || true
216
+ case "$cmd" in
217
+ status) do_status ;;
218
+ print-plist) job="${1:-listing}"; case "$job" in listing|market|diagnose|ads|messages|category) gen "$job" ;; *) echo "print-plist 只接受 listing|market|diagnose|ads|messages|category" >&2; exit 2 ;; esac ;;
219
+ install) do_install "$@" ;;
220
+ uninstall) do_uninstall ;;
221
+ run-now) job="${1:-}"; case "$job" in listing|market|diagnose|ads|messages|category) bash "$RUNNER" "$job" ;; *) echo "run-now 只接受 listing|market|diagnose|ads|messages|category" >&2; exit 2 ;; esac ;;
222
+ -h|--help|'') usage ;;
223
+ *) echo "未知命令: $cmd" >&2; usage; exit 2 ;;
224
+ esac