@whyshu/argent-engine 0.7.7 → 0.8.0-rc.10

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 (114) hide show
  1. package/MANIFEST.json +67 -45
  2. package/engine/VERSION +1 -1
  3. package/engine/core/contracts/argent.contracts.json +2 -2
  4. package/engine/core/contracts/verbs.schema.json +64 -1
  5. package/engine/core/lib/argent-datadir.mjs +6 -0
  6. package/engine/core/lib/contract.mjs +30 -0
  7. package/engine/core/mcp/server.mjs +171 -2
  8. package/engine/scripts/appointment-create.mjs +2 -2
  9. package/engine/scripts/argent-doctor.mjs +44 -3
  10. package/engine/scripts/argent-machine-setup.mjs +3 -1
  11. package/engine/scripts/argent-runner.mjs +4 -2
  12. package/engine/scripts/argent-schedule.mjs +6 -0
  13. package/engine/scripts/base-bootstrap.sh +0 -0
  14. package/engine/scripts/billing-mode-daily.sh +0 -0
  15. package/engine/scripts/build-doc-index.mjs +68 -0
  16. package/engine/scripts/build-engine-package.mjs +18 -3
  17. package/engine/scripts/capability-packs.lock.json +66 -65
  18. package/engine/scripts/check-argent-desktop.mjs +91 -0
  19. package/engine/scripts/check-billing-mode.sh +0 -0
  20. package/engine/scripts/check-docs-drift.mjs +51 -4
  21. package/engine/scripts/check-dsh-web-expose.sh +0 -0
  22. package/engine/scripts/ci-run.sh +2 -2
  23. package/engine/scripts/customer-readiness.sh +0 -0
  24. package/engine/scripts/daily-report-run.sh +68 -0
  25. package/engine/scripts/daily-report-status.mjs +130 -0
  26. package/engine/scripts/daily-report-timer-plist.sh +89 -0
  27. package/engine/scripts/daily-report-timers.sh +199 -0
  28. package/engine/scripts/daily-report.mjs +136 -7
  29. package/engine/scripts/daily-report.sh +0 -0
  30. package/engine/scripts/desktop-trial.sh +0 -0
  31. package/engine/scripts/dev-window.sh +0 -0
  32. package/engine/scripts/doc-status.mjs +212 -0
  33. package/engine/scripts/drill-clean-room.sh +0 -0
  34. package/engine/scripts/drill-handover.sh +0 -0
  35. package/engine/scripts/dsh-backup-scope.sh +0 -0
  36. package/engine/scripts/dsh-overlay-pin.sh +0 -0
  37. package/engine/scripts/dsh-release-watch-daily.sh +0 -0
  38. package/engine/scripts/dsh-remote-check.sh +0 -0
  39. package/engine/scripts/dsh-restart.sh +0 -0
  40. package/engine/scripts/dsh-restore.sh +0 -0
  41. package/engine/scripts/dsh-url.sh +0 -0
  42. package/engine/scripts/erp_invoice_shadow.py +62 -0
  43. package/engine/scripts/erp_invoice_writeback.py +93 -0
  44. package/engine/scripts/flow-requirements.json +4 -4
  45. package/engine/scripts/flow-session-retention.mjs +2 -1
  46. package/engine/scripts/flow-timers-plist.sh +0 -0
  47. package/engine/scripts/flow-timers.sh +11 -0
  48. package/engine/scripts/flow-trigger-wake.mjs +6 -3
  49. package/engine/scripts/flow-trigger.sh +0 -0
  50. package/engine/scripts/flow_config.py +16 -0
  51. package/engine/scripts/flow_failure.py +3 -0
  52. package/engine/scripts/flow_source.py +10 -1
  53. package/engine/scripts/flow_sources/__init__.py +1 -0
  54. package/engine/scripts/flow_sources/erp.py +54 -0
  55. package/engine/scripts/fulfillment_sites.py +46 -0
  56. package/engine/scripts/gen-agent-bundles.mjs +1 -1
  57. package/engine/scripts/init-ml.sh +0 -0
  58. package/engine/scripts/invoice-table.sh +0 -0
  59. package/engine/scripts/invoice_lip_runner.py +43 -0
  60. package/engine/scripts/invoice_runner.py +5 -3
  61. package/engine/scripts/invoice_stageb.py +21 -4
  62. package/engine/scripts/lib/argent-datadir.sh +0 -0
  63. package/engine/scripts/lib/argent_datadir.py +5 -0
  64. package/engine/scripts/lib/daily-report-status.mjs +227 -0
  65. package/engine/scripts/lib/plugin-packages.mjs +3 -0
  66. package/engine/scripts/lib/repo-root.sh +0 -0
  67. package/engine/scripts/migrate-skills.sh +0 -0
  68. package/engine/scripts/ml-ads.mjs +181 -0
  69. package/engine/scripts/ml-oauth-setup.mjs +1 -1
  70. package/engine/scripts/ml_hub_status.py +3 -3
  71. package/engine/scripts/npm-publish-argent.sh +0 -0
  72. package/engine/scripts/orchestrator.py +228 -31
  73. package/engine/scripts/orchestrator_br.py +14412 -0
  74. package/engine/scripts/patches/retire-check.sh +0 -0
  75. package/engine/scripts/poll-fulfillment.sh +0 -0
  76. package/engine/scripts/poll-invoice.sh +0 -0
  77. package/engine/scripts/provider-select.sh +0 -0
  78. package/engine/scripts/provider-switch.sh +0 -0
  79. package/engine/scripts/python-runtime.sh +0 -0
  80. package/engine/scripts/query_runner.py +2 -3
  81. package/engine/scripts/release-argent.sh +0 -0
  82. package/engine/scripts/release-gate-0.8.mjs +81 -0
  83. package/engine/scripts/run-tests.sh +0 -0
  84. package/engine/scripts/s1-audit.mjs +4 -1
  85. package/engine/scripts/session-handoff.mjs +2 -1
  86. package/engine/scripts/setup.sh +0 -0
  87. package/engine/scripts/skuflow_invoice_runner.py +164 -0
  88. package/engine/scripts/sync-plugins.sh +0 -0
  89. package/engine/scripts/sync-presets.sh +0 -0
  90. package/engine/scripts/sync-scripts.sh +0 -0
  91. package/engine/scripts/telemetry.py +6 -2
  92. package/engine/scripts/usage-anchor.sh +0 -0
  93. package/engine/scripts/vertical-lint.mjs +19 -0
  94. package/engine/scripts/wenyao-browser.sh +0 -0
  95. package/engine/scripts/wenyao-login.sh +0 -0
  96. package/engine/scripts/xzh-browser.sh +2 -1
  97. package/engine/scripts/xzh_browser.py +1 -1
  98. package/engine/scripts/ziniao-auth-probe.sh +67 -18
  99. package/engine/scripts/ziniao-keepalive.sh +0 -0
  100. package/engine/scripts/ziniao-post-upgrade-check.sh +0 -0
  101. package/engine/scripts/ziniao-windows.sh +0 -0
  102. package/engine/skills/ml-fulfillment-sop/SKILL.md +29 -0
  103. package/engine/skills/ml-fulfillment-sop/references/agentic-runtime-v3.md +39 -0
  104. package/engine/skills/ml-fulfillment-sop/scripts/poll-and-execute.sh +0 -0
  105. package/engine/skills/ml-store-daily-report/SKILL.md +68 -0
  106. package/engine/tools/agentic/README.md +95 -0
  107. package/engine/tools/agentic/mcp_server.py +212 -0
  108. package/engine/tools/agentic/ml_agent_tools.py +602 -0
  109. package/engine/version.mjs +1 -1
  110. package/engine/verticals/_engine-words.baseline.txt +16 -2
  111. package/engine/verticals/mercadolibre/brazil-full-sop.json +47 -0
  112. package/engine/verticals/mercadolibre/flows.json +15 -5
  113. package/engine/verticals/mercadolibre/prompts/full.failure.md +39 -1
  114. package/package.json +1 -1
@@ -0,0 +1,227 @@
1
+ /**
2
+ * 日报定时器状态 —— **唯一读写实现**(引擎写、桌宠 / CLI / doctor 读)。
3
+ *
4
+ * 为什么要有这个文件(2026-10-30 事故):
5
+ * 日报此前走「launchd 唤醒 LLM 会话」的投递方式。客户机切到 dsh Desktop 后宿主
6
+ * (`dsh --profile argent --port 3080`)被停,定时器每 5 分钟照常认领、照常唤醒失败,
7
+ * 而 **没有任何一处能让人看见"定时器还在不在跑"** —— launchctl 显示最后 exit 0(无票那一轮),
8
+ * 失败只落在日志 + 台账里,客户侧完全静默。
9
+ * ⇒ 日报改成「launchd 直跑确定性脚本」后,必须有一个**人可读、机器可读**的状态面。
10
+ *
11
+ * 纪律:
12
+ * · 纯 node 内建(fs/path)+ 同层 L1(`daily-report-core.mjs`),零第三方、零宿主 import;
13
+ * · 写侧只有 `writeStatus()` 一个入口(tmp + rename 原子写),⛔ 别处不许直接写这个文件;
14
+ * · 状态文件是**派生事实**,删了不会丢数据(下次运行自动重建);⛔ 不当台账用。
15
+ *
16
+ * 文件:`<ARGENT_DATA_DIR>/daily-report-timer-status.json`
17
+ */
18
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs'
19
+ import { dirname, join } from 'node:path'
20
+ import { SITE_TZ, fallbackSite, localDateStr, storeKey, tzOffsetMs } from './daily-report-core.mjs'
21
+
22
+ export const STATUS_SCHEMA = 1
23
+ export const STATUS_FILE = 'daily-report-timer-status.json'
24
+ export const TIMER_LABEL = 'com.whyshu.daily-report-timer'
25
+ export const DEFAULT_REPORT_TIME = '00:05'
26
+
27
+ export const statusPath = (dataHome) => join(dataHome, STATUS_FILE)
28
+
29
+ /** 读状态文件;缺失/损坏 ⇒ `{}`(⛔ 不抛:桌宠每 5s 读一次,坏文件不许把页面搞崩)。 */
30
+ export function readStatus(dataHome) {
31
+ try {
32
+ const raw = JSON.parse(readFileSync(statusPath(dataHome), 'utf8'))
33
+ if (!raw || typeof raw !== 'object') return {}
34
+ return raw
35
+ } catch {
36
+ return {}
37
+ }
38
+ }
39
+
40
+ /** 原子写(tmp + rename)。返回落盘对象,便于调用方打日志。 */
41
+ export function writeStatus(dataHome, status) {
42
+ const next = { ...status, schema: STATUS_SCHEMA }
43
+ mkdirSync(dataHome, { recursive: true })
44
+ const file = statusPath(dataHome)
45
+ const tmp = `${file}.tmp`
46
+ writeFileSync(tmp, JSON.stringify(next, null, 1) + '\n')
47
+ renameSync(tmp, file)
48
+ return next
49
+ }
50
+
51
+ /**
52
+ * 合并语义(**关键**):一次运行只更新它知道的字段。
53
+ * · 顶层字段:patch 覆盖 prev;
54
+ * · `stores`:按 storeKey 浅合并(本轮没跑到的店保留上次事实);
55
+ * · `lastPushed` / `pending` / `stores` 之外的数组:整段替换(它们描述"本轮")。
56
+ * 为什么:定时器每小时跑一次,绝大多数轮次是「未到点、零动作」;
57
+ * 若 no-op 轮次把 `lastPushAt` / 每个店的状态冲掉,桌宠就会一直显示"从未推送"。
58
+ */
59
+ export function mergeStatus(prev = {}, patch = {}) {
60
+ const out = { ...prev, ...patch }
61
+ if (patch.stores || prev.stores) {
62
+ const merged = { ...(prev.stores || {}) }
63
+ for (const [k, v] of Object.entries(patch.stores || {})) merged[k] = { ...(merged[k] || {}), ...v }
64
+ out.stores = merged
65
+ }
66
+ return out
67
+ }
68
+
69
+ /** `HH:MM` / `HH:MM:SS` → `{ h, m }`;非法 ⇒ 默认 00:05(与文档默认口径一致,⛔ 不抛)。 */
70
+ export function parseHHMM(text, fallback = DEFAULT_REPORT_TIME) {
71
+ const m = /^(\d{1,2}):(\d{2})(?::\d{2})?$/.exec(String(text ?? '').trim())
72
+ if (m) {
73
+ const h = Number(m[1])
74
+ const mi = Number(m[2])
75
+ if (h >= 0 && h <= 23 && mi >= 0 && mi <= 59) return { h, m: mi }
76
+ }
77
+ const f = /^(\d{1,2}):(\d{2})/.exec(String(fallback)) || [0, '0', '5']
78
+ return { h: Number(f[1]) || 0, m: Number(f[2]) || 0 }
79
+ }
80
+
81
+ /** 本地墙钟(某时区的 y/m/d/h/mi)→ UTC Date;两次迭代吸收 DST 偏移变化。 */
82
+ function wallToUtc(tz, y, mo, d, h, mi) {
83
+ const naive = Date.UTC(y, mo - 1, d, h, mi)
84
+ let t = naive - tzOffsetMs(tz, new Date(naive))
85
+ t = naive - tzOffsetMs(tz, new Date(t))
86
+ return new Date(t)
87
+ }
88
+
89
+ /**
90
+ * 某站点本地的**下一次** `HH:MM`(严格晚于 now)→ Date(UTC 表示)。
91
+ * 例:墨西哥 `00:05`、北京 13:00 ⇒ 返回北京时间 14:05。
92
+ */
93
+ export function nextLocalOccurrence(tz, now, reportTime = DEFAULT_REPORT_TIME) {
94
+ const { h, m } = parseHHMM(reportTime)
95
+ const [y, mo, d] = localDateStr(tz, now).split('-').map(Number)
96
+ let cand = wallToUtc(tz, y, mo, d, h, m)
97
+ if (cand.getTime() <= now.getTime()) {
98
+ const next = new Date(Date.UTC(y, mo - 1, d) + 86400000) // 墙钟加一天(不做 tz 运算)
99
+ cand = wallToUtc(tz, next.getUTCFullYear(), next.getUTCMonth() + 1, next.getUTCDate(), h, m)
100
+ }
101
+ return cand
102
+ }
103
+
104
+ /** 下一次发生时"该推哪一天"的日报:站点本地的前一天(D 日数据在 D+1 00:05 推)。 */
105
+ export function pendingDateFor(tz, occurrence, dayMs = 86400000) {
106
+ return localDateStr(tz, new Date(occurrence.getTime() - dayMs))
107
+ }
108
+
109
+ /** 扫 `daily-report-cache/` 里某店最新的幂等标记 → `{ date, at }`;没有 ⇒ `null`。 */
110
+ export function latestPushed(cacheDir, key) {
111
+ const suffix = `-${key}`
112
+ let names = []
113
+ try {
114
+ names = readdirSync(cacheDir)
115
+ } catch {
116
+ return null
117
+ }
118
+ let best = null
119
+ for (const name of names) {
120
+ if (!name.startsWith('.pushed-') || !name.endsWith(suffix)) continue
121
+ const date = name.slice('.pushed-'.length, name.length - suffix.length)
122
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) continue
123
+ if (!best || date > best.date) {
124
+ let at = null
125
+ try { at = new Date(statSync(join(cacheDir, name)).mtimeMs).toISOString() } catch { /* noop */ }
126
+ best = { date, at }
127
+ }
128
+ }
129
+ return best
130
+ }
131
+
132
+ /** `YYYY-MM-DD` 加减天数(纯日历运算,不涉时区)。 */
133
+ export function addDays(dateStr, n) {
134
+ const d = new Date(`${dateStr}T00:00:00Z`)
135
+ d.setUTCDate(d.getUTCDate() + n)
136
+ return d.toISOString().slice(0, 10)
137
+ }
138
+
139
+ /**
140
+ * 每店事实 + 下一次应推时点(纯函数;`cacheDir` 只用于读标记)。
141
+ *
142
+ * 三个日期要分清(UI 上最容易混):
143
+ * · `dueDate` = **下一次**时点会推哪一天(= 下一次发生的站点本地日期前一天);
144
+ * · `expectedLast` = **到此刻为止最后该推**的那一天(= dueDate 前一天);
145
+ * · `missed` = `lastDate+1 … expectedLast` 里缺的天(上限 7,避免 UI 刷屏)。
146
+ * 2026-10-30 事故的教训:只报"下一次几点"会让"昨天那一份根本没推"这件事看不见。
147
+ */
148
+ export function computeStoreStates({ stores = [], cacheDir = '', now = new Date(), reportTime = DEFAULT_REPORT_TIME, lookaheadDays = 3 } = {}) {
149
+ return stores.map((store) => {
150
+ const site = fallbackSite(store.site)
151
+ const tz = SITE_TZ[site]
152
+ const key = storeKey(store)
153
+ const last = cacheDir ? latestPushed(cacheDir, key) : null
154
+ let occurrence = nextLocalOccurrence(tz, now, reportTime)
155
+ let dueDate = pendingDateFor(tz, occurrence)
156
+ // 已推过这一天的(例如手动 --force 补推过)⇒ 下一次时点顺延,别显示"要推一个已推过的日期"
157
+ for (let i = 0; i < lookaheadDays; i += 1) {
158
+ if (!last || last.date < dueDate) break
159
+ occurrence = new Date(occurrence.getTime() + 86400000)
160
+ dueDate = pendingDateFor(tz, occurrence)
161
+ }
162
+ const expectedLast = addDays(dueDate, -1)
163
+ const missed = []
164
+ if (!last || last.date < expectedLast) {
165
+ let d = last ? addDays(last.date, 1) : addDays(expectedLast, -6)
166
+ while (d <= expectedLast && missed.length < 7) {
167
+ missed.push(d)
168
+ d = addDays(d, 1)
169
+ }
170
+ }
171
+ return {
172
+ key,
173
+ store: String(store.name ?? ''),
174
+ site,
175
+ tz,
176
+ lastDate: last?.date || '',
177
+ lastPushAt: last?.at || '',
178
+ dueDate,
179
+ expectedLast,
180
+ missed,
181
+ nextDueAt: occurrence.toISOString(),
182
+ }
183
+ })
184
+ }
185
+
186
+ /** 由每店事实汇总出状态文件里那几段(纯函数)。 */
187
+ export function summarizeStates(states = []) {
188
+ const pending = states.filter((s) => s.missed.length > 0).map((s) => ({
189
+ store: s.store, site: s.site, dueDate: s.dueDate, missed: s.missed,
190
+ }))
191
+ const nextDueAt = states.reduce((min, s) => (!min || s.nextDueAt < min ? s.nextDueAt : min), '')
192
+ const lastPushAt = states.reduce((max, s) => (s.lastPushAt > max ? s.lastPushAt : max), '')
193
+ const missedTotal = states.reduce((n, s) => n + s.missed.length, 0)
194
+ return {
195
+ nextDueAt,
196
+ lastPushAt,
197
+ missedTotal,
198
+ pending,
199
+ stores: Object.fromEntries(states.map((s) => [s.key, {
200
+ store: s.store, site: s.site, tz: s.tz,
201
+ lastDate: s.lastDate, lastPushAt: s.lastPushAt,
202
+ dueDate: s.dueDate, expectedLast: s.expectedLast, missed: s.missed,
203
+ nextDueAt: s.nextDueAt,
204
+ }])),
205
+ }
206
+ }
207
+
208
+ /**
209
+ * 人读一行(CLI / doctor 共用;⛔ 桌宠客户端不复制这句,UI 自己排版)。
210
+ * @param {object} status 状态文件内容
211
+ * @param {{now?:Date, locale?:(d:Date)=>string}} [opts]
212
+ */
213
+ export function describeStatus(status = {}, { now = new Date(), fmt = (d) => d.toISOString() } = {}) {
214
+ if (!status || !status.lastRunAt) return '定时器尚未运行过(无状态文件)'
215
+ const parts = []
216
+ parts.push(status.lastExit ? `上次运行失败(exit ${status.lastExit})` : '上次运行正常')
217
+ if (status.lastPushAt) {
218
+ const age = now.getTime() - Date.parse(status.lastPushAt)
219
+ parts.push(`上次推送 ${Number.isFinite(age) ? fmt(new Date(status.lastPushAt)) : status.lastPushAt}`)
220
+ } else {
221
+ parts.push('还没有成功推送记录')
222
+ }
223
+ if (status.nextDueAt) parts.push(`下次 ${fmt(new Date(status.nextDueAt))}`)
224
+ if (status.missedTotal) parts.push(`缺 ${status.missedTotal} 天日报`)
225
+ if (status.lastError) parts.push(`错误:${String(status.lastError).slice(0, 120)}`)
226
+ return parts.join(' · ')
227
+ }
@@ -59,6 +59,9 @@ export const PLUGIN_PACKAGES = [
59
59
  // · 发布流水线(`scripts/npm-publish-argent.mjs --only argent-shell`)按本清单认包
60
60
  // —— 不登记 ⇒ Lead 用**官方**发布脚本发不出它。
61
61
  { id: 'argent-shell', npm: `${NPM_SCOPE}/argent-shell` },
62
+ // Desktop 端 ERP 连接器(2026-10-29):单 bundle + 单 insert,只做 office/ERP 通道
63
+ // (快照/对话/建会话/本地任务),不装 core/skin/flow/gateway ⇒ 与 web 端套装解耦。
64
+ { id: 'argent-desktop', npm: `${NPM_SCOPE}/argent-desktop` },
62
65
  ]
63
66
 
64
67
  /**
File without changes
File without changes
@@ -0,0 +1,181 @@
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
+ } from './lib/ml-ads-core.mjs'
38
+
39
+ const API_BASE = () => process.env.ML_API_BASE || 'https://api.mercadolibre.com'
40
+
41
+ const args = process.argv.slice(2)
42
+ const argVal = (n) => { const i = args.indexOf(n); return i >= 0 && args[i + 1] ? args[i + 1] : null }
43
+ const has = (n) => args.includes(n)
44
+
45
+ if (has('-h') || has('--help')) {
46
+ console.log(`Mercado Ads 只读报告
47
+
48
+ 用法: node scripts/ml-ads.mjs [选项]
49
+ --store <名或uid> 店铺过滤(名称子串 / uid 全等,与日报同一判据)
50
+ --days <n> 回溯天数,默认 7(MELI 上限 90)
51
+ --to <YYYY-MM-DD> 结束日(站点本地),默认「昨天」
52
+ --detail 附活动级下钻(花钱最多 + ACoS 超标)
53
+ --list 只列出每店广告主(1 请求/店)
54
+ --json 结构化 JSON(stdout)
55
+ --lines 中文卡片行(给日报分区/角色回复复用)
56
+ --acos-warn <n> ACoS 黄色阈值,默认 ${ADS_ALERT_DEFAULTS.acosWarn}
57
+ --acos-bad <n> ACoS 红色阈值,默认 ${ADS_ALERT_DEFAULTS.acosBad}
58
+ --min-spend <n> 告警最小花费(本币),默认 ${ADS_ALERT_DEFAULTS.minSpend}
59
+ --env <path> daily-report.env 路径
60
+ 退出码: 0 正常 | 1 用法/取数失败 | 2 全部店铺失败`)
61
+ process.exit(0)
62
+ }
63
+
64
+ const DATA_DIR = resolveDataDir({ env: process.env }).dir
65
+ const ENV_PATH = argVal('--env') || join(DATA_DIR, 'daily-report.env')
66
+ const STORES_PATH = process.env.ML_API_STORES_JSON || join(DATA_DIR, 'ml-api-stores.json')
67
+ const env = loadEnvFile(ENV_PATH)
68
+ const doc = existsSync(STORES_PATH) ? JSON.parse(readFileSync(STORES_PATH, 'utf8')) : { stores: [] }
69
+ const stores = doc.stores || []
70
+
71
+ const persistStores = () => {
72
+ try {
73
+ mkdirSync(dirname(STORES_PATH), { recursive: true })
74
+ const tmp = `${STORES_PATH}.tmp`
75
+ writeFileSync(tmp, JSON.stringify({ stores }, null, 2) + '\n', { mode: 0o600 })
76
+ renameSync(tmp, STORES_PATH)
77
+ chmodSync(STORES_PATH, 0o600)
78
+ } catch (e) { console.error(`✗ token 写回失败:${e.message}`) }
79
+ }
80
+ const apiGet = (path, token) => coreApiGet(path, token, { base: API_BASE() })
81
+
82
+ const alertOpts = {
83
+ acosWarn: Number(argVal('--acos-warn') || ADS_ALERT_DEFAULTS.acosWarn),
84
+ acosBad: Number(argVal('--acos-bad') || ADS_ALERT_DEFAULTS.acosBad),
85
+ minSpend: Number(argVal('--min-spend') || ADS_ALERT_DEFAULTS.minSpend),
86
+ minRoas: ADS_ALERT_DEFAULTS.minRoas,
87
+ }
88
+
89
+ const FLAG_JSON = has('--json')
90
+ const FLAG_LINES = has('--lines')
91
+ const FLAG_DETAIL = has('--detail')
92
+ const FLAG_LIST = has('--list')
93
+ const days = Math.max(1, Math.min(90, Number(argVal('--days') || 7)))
94
+ const toArg = argVal('--to')
95
+
96
+ const now = new Date()
97
+ const picked = matchStores(stores, (argVal('--store') || '').split(',').map((x) => x.trim()).filter(Boolean))
98
+ if (!picked.length) {
99
+ console.error(`✗ 没有匹配到店铺(已授权 ${stores.length} 家)`)
100
+ process.exit(1)
101
+ }
102
+
103
+ const results = []
104
+ for (const store of picked) {
105
+ const site = fallbackSite(store.site)
106
+ const tz = SITE_TZ[site]
107
+ const todayStart = startOfLocalDayUTC(tz, now)
108
+ const toMs = toArg ? startOfLocalDayUTC(tz, new Date(`${toArg}T12:00:00Z`)) : todayStart - 86400000
109
+ const fromMs = toMs - (days - 1) * 86400000
110
+ const dateFrom = localDateStr(tz, new Date(fromMs))
111
+ const dateTo = localDateStr(tz, new Date(toMs))
112
+ const row = { store: store.name, site, uid: store.user_id, currency: SITE_CURRENCY[site] || '', dateFrom, dateTo }
113
+ try {
114
+ const token = await refreshStoreToken(env, store, { onRotate: persistStores })
115
+ if (FLAG_LIST) {
116
+ const adv = await apiGet('/advertising/advertisers?product_id=PADS', token)
117
+ row.advertisers = (adv.advertisers || []).map((a) => ({ advertiser_id: a.advertiser_id, site: a.site_id, name: a.advertiser_name }))
118
+ results.push(row)
119
+ continue
120
+ }
121
+ const report = await fetchAdsReport({ apiGet, token, site, dateFrom, dateTo })
122
+ row.report = report
123
+ row.alerts = classifyAdsAlerts(report.totals, alertOpts)
124
+ results.push(row)
125
+ } catch (e) {
126
+ row.error = String(e.message || e)
127
+ results.push(row)
128
+ }
129
+ }
130
+
131
+ // ── 输出 ───────────────────────────────────────────────────
132
+ const ok = results.filter((r) => !r.error)
133
+ if (!ok.length) {
134
+ if (FLAG_JSON) console.log(JSON.stringify({ results }, null, 2))
135
+ else for (const r of results) console.error(`✗ ${r.store}:${r.error}`)
136
+ process.exit(2)
137
+ }
138
+ if (FLAG_JSON) { console.log(JSON.stringify({ generatedAt: now.toISOString(), days, results }, null, 2)); process.exit(0) }
139
+
140
+ if (FLAG_LINES) {
141
+ for (const r of ok) {
142
+ const lines = adsCardLines(r.report, { currency: r.currency, alertOpts })
143
+ console.log(`### ${r.store}`)
144
+ console.log(lines.join('\n'))
145
+ }
146
+ process.exit(0)
147
+ }
148
+
149
+ if (FLAG_LIST) {
150
+ for (const r of results) {
151
+ if (r.error) { console.log(`${r.store}: ✗ ${r.error}`); continue }
152
+ console.log(`${r.store}(${r.site}):` + (r.advertisers.length ? r.advertisers.map((a) => `${a.advertiser_id}(${a.site})`).join(', ') : '无广告主'))
153
+ }
154
+ process.exit(0)
155
+ }
156
+
157
+ const hdr = ['店铺', '站点', '花费', '销售额', 'ROAS', 'ACoS', '点击', 'CTR', '广告单量', '活动']
158
+ let text = `## 📣 Mercado Ads · ${ok[0].dateFrom} ~ ${ok[0].dateTo}(近 ${days} 天)\n\n`
159
+ text += '| ' + hdr.join(' | ') + ' |\n|' + hdr.map(() => '---').join('|') + '|\n'
160
+ const allAlerts = []
161
+ for (const r of results) {
162
+ if (r.error) { text += `| ${r.store} | ${r.site} | — | — | — | — | — | — | — | ✗ ${r.error.slice(0, 40)} |\n`; continue }
163
+ const t = r.report.totals
164
+ const c = r.currency ? r.currency + ' ' : ''
165
+ 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`
166
+ for (const a of r.alerts) allAlerts.push({ store: r.store, ...a })
167
+ if (FLAG_DETAIL) {
168
+ for (const a of r.report.advertisers) {
169
+ const top = [...(a.topCampaigns.top || [])]
170
+ 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`
171
+ }
172
+ }
173
+ }
174
+ text += '\n'
175
+ if (allAlerts.length) {
176
+ text += '### ⚠️ 告警\n'
177
+ for (const a of allAlerts) text += `- ${a.level === 'red' ? '🔴' : '🟡'} **${a.store}**:${a.text}\n`
178
+ } else {
179
+ text += '✅ 无告警(ACoS 与 ROAS 均在阈值内)\n'
180
+ }
181
+ console.log(text)
@@ -49,7 +49,7 @@ const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url))
49
49
  // 其他站点域名实测被拦(403),后续逐个站点验证后更新此表。
50
50
  const AUTH_HOSTS = {
51
51
  MLM: 'auth.mercadolibre.com.mx',
52
- MLB: 'auth.mercadolibre.com.br',
52
+ MLB: 'auth.mercadolivre.com.br', // 2026-10-17 实测修正:巴西站点域名是 mercadolivre(auth.mercadolibre.com.br 无 DNS)
53
53
  MLA: 'auth.mercadolibre.com.ar',
54
54
  MLC: 'auth.mercadolibre.cl',
55
55
  MCO: 'auth.mercadolibre.com.co',
@@ -88,7 +88,7 @@ units 页上都会出现 ⇒ 单凭它会把正常票判成尺寸阻塞。空间
88
88
  本样本**不依赖它**(仅凭 hub 即可判 `true`)。
89
89
 
90
90
  ⚠️ `operationally_complete=True` ⇒ 货件**被视为已完成**(无论表里写什么),但
91
- **⛔ 绝不是让引擎去改写 `FULL状态`** —— 改写权在运营/用户;引擎只写「识别为运营手动完成(依据 hub-v2 实测)」的备注。
91
+ **⛔ 绝不是让引擎去改写 `FULL状态`** —— 改写权在运营/用户;引擎只写「识别为已完成(依据 hub-v2 实测;来源未声明)」的备注。
92
92
 
93
93
  ## 容错(平台改版是常态)
94
94
 
@@ -1305,14 +1305,14 @@ def summary_zh(state: dict) -> str:
1305
1305
  def completion_verdict(state: dict) -> dict:
1306
1306
  """完成度裁定(**确定性规则**,供收口/前置校验/失败现场三处共用)。
1307
1307
 
1308
- `operationally_complete=True` ⇒ 「识别为运营手动完成(依据 hub-v2 实测)」。
1308
+ `operationally_complete=True` ⇒ 「识别为已完成(依据 hub-v2 实测;来源未声明)」。
1309
1309
  ⛔ 本函数**不改任何数据**:它只给结论,写表与否由调用方按各自白名单决定。
1310
1310
  """
1311
1311
  ok = bool(state.get("operationally_complete"))
1312
1312
  return {
1313
1313
  "operationally_complete": ok,
1314
1314
  "identified_as": "manual-completion-by-hub" if ok else "",
1315
- "note_zh": ("识别为运营手动完成(依据 hub-v2 实测):" + summary_zh(state)) if ok else "",
1315
+ "note_zh": ("识别为已完成(依据 hub-v2 实测;来源未声明):" + summary_zh(state)) if ok else "",
1316
1316
  "reason": state.get("complete_reason") or "",
1317
1317
  "items": item_lines(state),
1318
1318
  "shipment_id": state.get("shipment_id") or "",
File without changes