@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.
Files changed (106) hide show
  1. package/MANIFEST.json +102 -40
  2. package/bin/runtime-install.mjs +92 -0
  3. package/engine/VERSION +1 -1
  4. package/engine/configs/billing-actions.json +30 -0
  5. package/engine/configs/mcp-tools.snapshot.json +47 -0
  6. package/engine/core/contracts/argent.contracts.json +2 -2
  7. package/engine/core/lib/account-token.mjs +37 -0
  8. package/engine/core/lib/redact.mjs +34 -0
  9. package/engine/core/mcp/billing-upload.mjs +77 -0
  10. package/engine/core/mcp/erp-server.mjs +300 -0
  11. package/engine/core/mcp/gateway.mjs +333 -0
  12. package/engine/core/mcp/meter.mjs +101 -0
  13. package/engine/core/mcp/server.mjs +245 -0
  14. package/engine/core/mcp/vault.mjs +78 -0
  15. package/engine/scripts/appointment-worker.mjs +456 -35
  16. package/engine/scripts/appointment_grab.py +1389 -264
  17. package/engine/scripts/appointment_rules.py +118 -0
  18. package/engine/scripts/argent-timers.mjs +227 -0
  19. package/engine/scripts/argent-web-preflight.mjs +123 -0
  20. package/engine/scripts/argent-web-verify.mjs +105 -0
  21. package/engine/scripts/billing-upload.mjs +26 -0
  22. package/engine/scripts/build-engine-package.mjs +7 -1
  23. package/engine/scripts/capability-packs.lock.json +323 -300
  24. package/engine/scripts/check-version-consistency.mjs +14 -1
  25. package/engine/scripts/collect-intel.mjs +108 -0
  26. package/engine/scripts/daily-report-timer-plist.sh +18 -4
  27. package/engine/scripts/daily-report-timers.sh +36 -3
  28. package/engine/scripts/daily-report.mjs +78 -2
  29. package/engine/scripts/dsh-web-doctor.mjs +84 -0
  30. package/engine/scripts/engine-manifest.mjs +90 -0
  31. package/engine/scripts/engine-runtime-install.mjs +92 -0
  32. package/engine/scripts/erp-ui-install.mjs +127 -0
  33. package/engine/scripts/erp-ui-preflight.mjs +104 -0
  34. package/engine/scripts/erp-ui-verify.mjs +135 -0
  35. package/engine/scripts/flow-requirements.json +122 -99
  36. package/engine/scripts/full-exec-worker.mjs +251 -0
  37. package/engine/scripts/gen-preset-rows.mjs +1 -1
  38. package/engine/scripts/invoice_lip_runner.py +1 -0
  39. package/engine/scripts/invoice_runner.py +17 -6
  40. package/engine/scripts/invoice_stageb.py +21 -4
  41. package/engine/scripts/lib/bootcheck-wiring.mjs +7 -5
  42. package/engine/scripts/lib/intel-card.mjs +43 -0
  43. package/engine/scripts/lib/invoice_names.py +23 -0
  44. package/engine/scripts/lib/ml-ads-core.mjs +100 -18
  45. package/engine/scripts/lib/ml-ads-rules.mjs +275 -0
  46. package/engine/scripts/lib/ml-bridge-auth.mjs +50 -0
  47. package/engine/scripts/lib/ml-category-core.mjs +120 -0
  48. package/engine/scripts/lib/ml-insight-core.mjs +621 -0
  49. package/engine/scripts/lib/ml-insight-facts.mjs +424 -0
  50. package/engine/scripts/lib/ml-items.mjs +40 -0
  51. package/engine/scripts/lib/ml-listing-core.mjs +342 -0
  52. package/engine/scripts/lib/ml-market-core.mjs +774 -0
  53. package/engine/scripts/lib/plugin-packages.mjs +13 -0
  54. package/engine/scripts/lib/webdriver_ipc.py +61 -1
  55. package/engine/scripts/line_pack.py +196 -0
  56. package/engine/scripts/mcp-gateway-switch.mjs +100 -0
  57. package/engine/scripts/migrate-providers.mjs +3 -3
  58. package/engine/scripts/ml-ads-advice.mjs +140 -0
  59. package/engine/scripts/ml-ads.mjs +40 -0
  60. package/engine/scripts/ml-category-baseline.mjs +174 -0
  61. package/engine/scripts/ml-insight-diagnose.mjs +247 -0
  62. package/engine/scripts/ml-insight-run.sh +183 -0
  63. package/engine/scripts/ml-insight-timers.sh +224 -0
  64. package/engine/scripts/ml-listing-audit.mjs +170 -0
  65. package/engine/scripts/ml-market-matrix.mjs +84 -0
  66. package/engine/scripts/ml-market-snapshot.mjs +261 -0
  67. package/engine/scripts/ml-messages.mjs +145 -0
  68. package/engine/scripts/npm-publish-argent.mjs +14 -0
  69. package/engine/scripts/ops-codefix-pr.mjs +87 -0
  70. package/engine/scripts/ops-codefix-queue.mjs +30 -0
  71. package/engine/scripts/ops-digest.mjs +98 -0
  72. package/engine/scripts/ops-verify.mjs +67 -0
  73. package/engine/scripts/orchestrator.py +410 -20
  74. package/engine/scripts/orchestrator_br.py +146 -4
  75. package/engine/scripts/plugin-bootcheck.mjs +50 -1
  76. package/engine/scripts/publish-engine.mjs +111 -0
  77. package/engine/scripts/restart-dsh-with-tunnel.sh +129 -0
  78. package/engine/scripts/skuflow_invoice_runner.py +43 -3
  79. package/engine/scripts/v0.9-acceptance.mjs +107 -0
  80. package/engine/scripts/vertical-lint.mjs +12 -1
  81. package/engine/scripts/web-switch.mjs +121 -0
  82. package/engine/scripts/wenyao_fill_template.py +52 -15
  83. package/engine/scripts/wenyao_run.py +2 -1
  84. package/engine/skills/README.md +3 -3
  85. package/engine/skills/bilibili-upload/SKILL.md +109 -0
  86. package/engine/skills/douyin-upload/SKILL.md +74 -0
  87. package/engine/skills/internal.json +28 -0
  88. package/engine/skills/kuaishou-upload/SKILL.md +109 -0
  89. package/engine/skills/ml-appointment-safety/SKILL.md +42 -0
  90. package/engine/skills/ml-full-appointment/SKILL.md +23 -0
  91. package/engine/skills/ml-invoice/SKILL.md +2 -2
  92. package/engine/skills/ml-invoice/references/template-fill-contract.md +1 -1
  93. package/engine/skills/ml-label-recovery/SKILL.md +43 -0
  94. package/engine/skills/ml-listing-audit/SKILL.md +66 -0
  95. package/engine/skills/ml-store-daily-report/SKILL.md +68 -0
  96. package/engine/skills/ml-store-daily-report/scripts/generate.js +35 -0
  97. package/engine/skills/ml-store-insight/SKILL.md +81 -0
  98. package/engine/skills/tencent-upload/SKILL.md +60 -0
  99. package/engine/skills/weibo-upload/SKILL.md +106 -0
  100. package/engine/skills/whyshu-social-ops/SKILL.md +136 -0
  101. package/engine/skills/xiaohongshu-upload/SKILL.md +122 -0
  102. package/engine/version.mjs +1 -1
  103. package/engine/verticals/README.md +7 -0
  104. package/engine/verticals/_engine-words.baseline.txt +27 -59
  105. package/engine/verticals/mercadolibre/manifest.json +132 -6
  106. package/package.json +5 -1
@@ -0,0 +1,275 @@
1
+ /**
2
+ * ml-ads-rules.mjs —— **广告诊断规则**(P2a,L1 纯函数,2026-11-25)
3
+ *
4
+ * 定位:`ml-ads-core` 负责"取数 + 聚合 + 降级告警";本文件负责**可执行建议单**:
5
+ * 每条规则回答「哪里不对(指标 vs 阈值)→ 为什么(口径)→ 先动什么(动作+风险)→ 能省多少(仅公式可算时)」。
6
+ *
7
+ * ⛔ 纪律:
8
+ * · **只读诊断**:输出建议,任何预算/暂停/调价都由人执行(P4 前不写客户广告账户);
9
+ * · 阈值可配:目标 ACoS 优先按**毛利结构**算(毛利率 − 佣金率 − 物流率),缺毛利数据时用平台默认并标注;
10
+ * · 估算只给可解释公式(如 `cost × (1 − targetACoS/acos)`),标注 `estimated:true`,⛔ 不预测 GMV;
11
+ * · 样本门槛:小花费/小点击不报警(避免训练人忽略告警)。
12
+ */
13
+
14
+ export const ADS_RULE_DEFAULTS = Object.freeze({
15
+ targetAcos: 25, // %:缺毛利数据时的默认目标 ACoS
16
+ marginRate: null, // 0-1:毛利率(客户提供后算可承受 ACoS)
17
+ commissionRate: 0.15, // 0-1:平台佣金(默认按常见 15%)
18
+ shippingRate: 0.10, // 0-1:物流/履约成本率
19
+ minSpend: 100, // 本币:账户级显著花费
20
+ campaignMinSpend: 100, // 本币:活动级显著花费(低于它不判活动规则)
21
+ zeroConvMinSpend: 50, // 本币:零转化活动的最小花费(小钱也报,但更低不报免噪声)
22
+ minClicks: 30, // CTR/CVR 判据最小样本
23
+ minPrints: 500,
24
+ acosRedFactor: 1.5, // 目标 × 1.5 ⇒ 红
25
+ concentrationShare: 0.6, // 单活动花费占比 ≥ 60% ⇒ 过度依赖
26
+ ctrLow: 0.5, // %:CTR 低于它 ⇒ 创意/关键词问题
27
+ cvrLow: 1.0, // %:CVR 低于它 ⇒ 落地/价格/listing 问题
28
+ maxFindings: 8,
29
+ })
30
+
31
+ const num = (x) => (x === null || x === undefined || x === '' ? null : (Number.isFinite(Number(x)) ? Number(x) : null))
32
+ const round2 = (x) => Math.round((Number(x) || 0) * 100) / 100
33
+
34
+ /**
35
+ * 可承受 ACoS(%):毛利结构可算则用毛利,否则回退默认目标并标 `source='fallback'`。
36
+ * 公式:ACoS_max = (marginRate − commissionRate − shippingRate) × 100
37
+ */
38
+ export function tolerableAcos(cfg = {}) {
39
+ const margin = num(cfg.marginRate)
40
+ const commission = num(cfg.commissionRate) ?? ADS_RULE_DEFAULTS.commissionRate * 100
41
+ const shipping = num(cfg.shippingRate) ?? ADS_RULE_DEFAULTS.shippingRate * 100
42
+ // 兼容:marginRate 允许传 0-1 或百分数(>1 视为百分数)
43
+ let marginPct = margin == null ? null : (margin > 1 ? margin : margin * 100)
44
+ const commissionPct = commission > 1 ? commission : commission * 100
45
+ const shippingPct = shipping > 1 ? shipping : shipping * 100
46
+ if (marginPct != null) {
47
+ const v = round2(marginPct - commissionPct - shippingPct)
48
+ // 毛利不足以覆盖佣金+物流 ⇒ 目标不可算(⛔ 不能拿 0/负值去比 ACoS,否则所有活动都被判"超标")
49
+ return v > 0
50
+ ? { value: v, source: 'margin', formula: `毛利率 ${marginPct} − 佣金 ${commissionPct} − 物流 ${shippingPct}` }
51
+ : { value: null, source: 'margin', formula: `毛利率 ${marginPct} − 佣金 ${commissionPct} − 物流 ${shippingPct}`, warning: '毛利不足以覆盖佣金+物流,无法给目标 ACoS' }
52
+ }
53
+ return { value: num(cfg.targetAcos) ?? ADS_RULE_DEFAULTS.targetAcos, source: 'fallback', formula: '默认目标 ACoS(未提供毛利数据)' }
54
+ }
55
+
56
+ /** 活动级索引:跨广告主摊平(一个店铺可能多个 advertiser)。 */
57
+ function allCampaigns(report) {
58
+ const out = []
59
+ for (const a of report?.advertisers || []) {
60
+ for (const c of a.campaigns || []) out.push({ ...c, advertiserId: a.advertiserId, site: a.site })
61
+ }
62
+ return out
63
+ }
64
+
65
+ /**
66
+ * 主入口:广告诊断规则。
67
+ * @param {object} report fetchAdsReport 的返回
68
+ * @param {object} [config] ADS_RULE_DEFAULTS 覆盖
69
+ * @returns {{ summary, target, findings, missing }}
70
+ */
71
+ export function diagnoseAds(report, config = {}) {
72
+ const cfg = { ...ADS_RULE_DEFAULTS, ...config }
73
+ const t = report?.totals || {}
74
+ const target = tolerableAcos(cfg)
75
+ const findings = []
76
+ const missing = []
77
+ const cost = num(t.cost) || 0
78
+ const amount = num(t.amount) || 0
79
+ const acos = num(t.acos) ?? (amount > 0 ? round2((cost / amount) * 100) : 0)
80
+ const roas = num(t.roas) ?? (cost > 0 ? round2(amount / cost) : 0)
81
+ const campaigns = allCampaigns(report)
82
+ const active = campaigns.filter((c) => String(c.status).toLowerCase() === 'active')
83
+ const top = [...campaigns].sort((a, b) => (num(b.cost) || 0) - (num(a.cost) || 0))[0] || null
84
+ const concentration = top && cost > 0 ? round2(((num(top.cost) || 0) / cost) * 100) / 100 : null
85
+
86
+ const push = (f) => { if (findings.length < cfg.maxFindings) findings.push(f) }
87
+
88
+ // R1 账户级零转化(最严重)
89
+ if (cost > 0 && amount <= 0 && cost >= cfg.minSpend) {
90
+ push({
91
+ ruleId: 'R1', level: 'red', scope: 'account',
92
+ metric: 'ad_amount', value: round2(amount), threshold: '>0',
93
+ evidence: { cost: round2(cost), campaigns: campaigns.length },
94
+ action: { code: 'pause_and_audit', text: '广告花费但销售额为 0:先暂停投放并排查(落地页/出价/商品状态)', risk: 'medium' },
95
+ })
96
+ missing.push('ad_amount=0:无法算 ACoS/ROAS 的目标偏离(先解决零转化)')
97
+ } else if (cost > 0 && target.value == null) {
98
+ missing.push(`${target.warning || '目标 ACoS 不可算'}(已跳过 ACoS/ROAS/活动超标类判断;请核对毛利率/佣金/物流成本)`)
99
+ } else if (cost > 0) {
100
+ // R2 账户 ACoS 超目标
101
+ if (acos > target.value * cfg.acosRedFactor) {
102
+ const saving = round2(cost * (1 - target.value / acos))
103
+ push({
104
+ ruleId: 'R2', level: 'red', scope: 'account',
105
+ metric: 'acos', value: acos, threshold: target.value,
106
+ evidence: { formula: target.formula, targetSource: target.source, cost: round2(cost), amount: round2(amount) },
107
+ estimated: { saving, note: '按"花费降到目标 ACoS"估算,实际取决于出价/预算调整' },
108
+ action: { code: 'lower_bids_or_pause_bad', text: `ACoS ${acos}% 超目标 ${target.value}%:先降出价/暂停高 ACoS 活动(预计可省 ${saving} 本币/期)`, risk: 'medium' },
109
+ })
110
+ } else if (acos > target.value) {
111
+ push({
112
+ ruleId: 'R2', level: 'yellow', scope: 'account',
113
+ metric: 'acos', value: acos, threshold: target.value,
114
+ evidence: { formula: target.formula, targetSource: target.source },
115
+ action: { code: 'watch_acos', text: `ACoS ${acos}% 略高于目标 ${target.value}%:观察一周,优先优化转化而非砍预算`, risk: 'low' },
116
+ })
117
+ }
118
+ // R3 ROAS 低于目标(目标 ROAS = 100/targetACoS)
119
+ const targetRoas = target.value > 0 ? round2(100 / target.value) : null
120
+ if (targetRoas && roas > 0 && roas < targetRoas) {
121
+ push({
122
+ ruleId: 'R3', level: roas < targetRoas * 0.7 ? 'red' : 'yellow', scope: 'account',
123
+ metric: 'roas', value: roas, threshold: targetRoas,
124
+ evidence: { targetAcos: target.value },
125
+ action: { code: 'review_targeting', text: `ROAS ${roas} 低于目标 ${targetRoas}:检查关键词/人群与商品转化`, risk: 'medium' },
126
+ })
127
+ }
128
+ }
129
+
130
+ // R4 活动级零转化(花钱不出单)
131
+ const zero = campaigns.filter((c) => (num(c.cost) || 0) >= cfg.zeroConvMinSpend && (num(c.amount) || 0) <= 0)
132
+ .sort((a, b) => (num(b.cost) || 0) - (num(a.cost) || 0))
133
+ for (const c of zero.slice(0, 3)) {
134
+ push({
135
+ ruleId: 'R4', level: 'red', scope: 'campaign', campaignId: c.id, campaignName: c.name,
136
+ metric: 'amount', value: 0, threshold: `花费 ≥ ${cfg.zeroConvMinSpend}`,
137
+ evidence: { cost: c.cost, clicks: c.clicks, prints: c.prints, status: c.status },
138
+ action: { code: 'pause_campaign', text: `活动「${c.name || c.id}」花费 ${c.cost} 零转化:暂停或重做关键词/创意`, risk: 'medium' },
139
+ })
140
+ }
141
+
142
+ // R5 活动级 ACoS 严重超标(按浪费额排序)
143
+ const badAcos = target.value == null ? [] : campaigns
144
+ .filter((c) => (num(c.cost) || 0) >= cfg.campaignMinSpend && (num(c.amount) || 0) > 0 && (num(c.acos) || 0) > target.value * cfg.acosRedFactor)
145
+ .sort((a, b) => ((num(b.cost) || 0) - (num(b.cost) || 0) * (target.value / (num(b.acos) || 1))) - ((num(a.cost) || 0) - (num(a.cost) || 0) * (target.value / (num(a.acos) || 1))))
146
+ for (const c of badAcos.slice(0, 2)) {
147
+ const waste = round2((num(c.cost) || 0) * (1 - target.value / (num(c.acos) || 1)))
148
+ push({
149
+ ruleId: 'R5', level: 'red', scope: 'campaign', campaignId: c.id, campaignName: c.name,
150
+ metric: 'acos', value: c.acos, threshold: target.value,
151
+ evidence: { cost: c.cost, amount: c.amount, clicks: c.clicks },
152
+ estimated: { saving: waste, note: '该活动超出目标 ACoS 的估算浪费额' },
153
+ action: { code: 'reduce_campaign_bid', text: `活动「${c.name || c.id}」ACoS ${c.acos}%:降出价或缩预算(可省约 ${waste})`, risk: 'medium' },
154
+ })
155
+ }
156
+
157
+ // R6 花费集中度(过度依赖单一活动)
158
+ if (concentration != null && concentration >= cfg.concentrationShare && cost >= cfg.minSpend) {
159
+ push({
160
+ ruleId: 'R6', level: 'yellow', scope: 'account',
161
+ metric: 'top_campaign_cost_share', value: concentration, threshold: cfg.concentrationShare,
162
+ evidence: { campaignId: top.id, campaignName: top.name, campaignCost: top.cost, cost: round2(cost) },
163
+ action: { code: 'diversify_budget', text: `单个活动占花费 ${Math.round(concentration * 100)}%:预算过于集中,暂停/异常会直接打崩销量`, risk: 'low' },
164
+ })
165
+ }
166
+
167
+ // R7/R8 漏斗(样本足够才判)
168
+ const prints = num(t.prints) || 0
169
+ const clicks = num(t.clicks) || 0
170
+ const ctr = num(t.ctr) ?? (prints > 0 ? round2((clicks / prints) * 100) : 0)
171
+ const units = num(t.units) || 0
172
+ const cvr = num(t.cvr) ?? (clicks > 0 ? round2((units / clicks) * 100) : 0)
173
+ if (prints >= cfg.minPrints && ctr < cfg.ctrLow && cost >= cfg.minSpend) {
174
+ push({
175
+ ruleId: 'R7', level: 'yellow', scope: 'account', metric: 'ctr', value: ctr, threshold: cfg.ctrLow,
176
+ evidence: { prints, clicks },
177
+ action: { code: 'improve_creative', text: `CTR ${ctr}% 偏低(曝光 ${prints}):先换主图/标题再调出价`, risk: 'low' },
178
+ })
179
+ }
180
+ if (clicks >= cfg.minClicks && cvr < cfg.cvrLow && cost >= cfg.minSpend) {
181
+ push({
182
+ ruleId: 'R8', level: 'yellow', scope: 'account', metric: 'cvr', value: cvr, threshold: cfg.cvrLow,
183
+ evidence: { clicks, units },
184
+ action: { code: 'fix_landing_or_price', text: `广告点击转化 ${cvr}% 偏低(点击 ${clicks}):查价格/库存/listing 质量,别加预算`, risk: 'low' },
185
+ })
186
+ }
187
+
188
+ if (cost <= 0) missing.push('本期无广告花费(可能未开权限/未投放/日期窗口无数据)')
189
+ const levels = { red: findings.filter((f) => f.level === 'red').length, yellow: findings.filter((f) => f.level === 'yellow').length }
190
+
191
+ return {
192
+ summary: {
193
+ cost: round2(cost), amount: round2(amount), amountDerived: Boolean(t.amountDerived),
194
+ acos, roas, clicks, prints, units, ctr, cvr,
195
+ campaigns: campaigns.length, activeCampaigns: active.length,
196
+ topCampaignShare: concentration,
197
+ red: levels.red, yellow: levels.yellow,
198
+ },
199
+ target,
200
+ findings: findings.sort((a, b) => (a.level === b.level ? 0 : a.level === 'red' ? -1 : 1)),
201
+ missing,
202
+ }
203
+ }
204
+
205
+ /** 纯函数:渲染建议单(CLI/角色回复共用;⛔ 只渲染已有字段)。 */
206
+ export function adsAdviceLines(result, { currency = '' } = {}) {
207
+ const r = result || {}
208
+ const s = r.summary || {}
209
+ const cur = currency ? `${currency} ` : ''
210
+ const out = []
211
+ out.push(`📣 广告诊断 · 花费 ${cur}${s.cost ?? 0} · 销售额 ${cur}${s.amount ?? 0}${s.amountDerived ? '(roas×cost 反推)' : ''} · ACoS ${s.acos ?? 0}% · ROAS ${s.roas ?? 0}`)
212
+ out.push(`目标 ACoS ${r.target?.value ?? '—'}%(${r.target?.source === 'margin' ? '按毛利结构' : '默认值'})· 活动 ${s.activeCampaigns ?? 0}/${s.campaigns ?? 0} 在投 · 单活动占比 ${s.topCampaignShare == null ? '—' : Math.round(s.topCampaignShare * 100) + '%'}`)
213
+ for (const f of r.findings || []) {
214
+ const flag = f.level === 'red' ? '🔴' : '🟡'
215
+ out.push(`${flag} **${f.ruleId}** ${f.action?.text || ''}`)
216
+ if (f.estimated?.saving) out.push(` 估算节省:${cur}${f.estimated.saving}(${f.estimated.note})`)
217
+ }
218
+ if (!(r.findings || []).length) out.push('✅ 未发现需要动的广告问题(本期)')
219
+ if ((r.missing || []).length) out.push(`⚠️ ${r.missing.join(';')}`)
220
+ return out
221
+ }
222
+
223
+ /**
224
+ * A:广告建议单 → ERP bridge payload(2026-12-01,只读建议单;⛔ 不改任何广告设置)。
225
+ * 字段契约见 whyshu-svr `POST /reports/ads/bridge`(不可改名)。
226
+ * 注意单位:ACoS/CTR 在规则层是**百分数**(7.3 = 7.3%),bridge 用**小数**(0.073)。
227
+ */
228
+ export function buildAdsBridgePayload(result, { store = '', site = '', currency = '', days = 7 } = {}) {
229
+ const r = result || {}
230
+ const s = r.summary || {}
231
+ const target = r.target || {}
232
+ const findings = Array.isArray(r.findings) ? r.findings : []
233
+ const pct2frac = (v) => (Number.isFinite(Number(v)) ? Math.round((Number(v) / 100) * 10000) / 10000 : null)
234
+ const num = (v) => (Number.isFinite(Number(v)) ? Number(v) : null)
235
+
236
+ const items = findings.slice(0, 60).map((f) => {
237
+ const isCampaign = f.scope === 'campaign' && f.campaignId
238
+ return {
239
+ id: (isCampaign ? String(f.campaignId) : 'account') + ':' + f.ruleId,
240
+ name: isCampaign ? String(f.campaignName || f.campaignId) : '账户整体',
241
+ level: isCampaign ? 'campaign' : 'account',
242
+ cost: num(f.evidence && f.evidence.cost),
243
+ clicks: num(f.evidence && f.evidence.clicks),
244
+ impressions: num(f.evidence && f.evidence.prints),
245
+ ctr: null,
246
+ acos: pct2frac(f.metric === 'acos' ? f.value : null),
247
+ conversions: f.ruleId === 'R4' ? 0 : null,
248
+ zeroConversion: f.ruleId === 'R4',
249
+ signals: [{ rule: String(f.ruleId || ''), level: f.level === 'red' ? 'red' : 'yellow', text: String(f.action && f.action.text || '') }],
250
+ suggestions: [{
251
+ action: String((f.action && f.action.code) || 'review'),
252
+ text: String((f.action && f.action.text) || ''),
253
+ risk: String((f.action && f.action.risk) || 'low'),
254
+ estimatedSaving: num(f.estimated && f.estimated.saving),
255
+ }],
256
+ }
257
+ })
258
+
259
+ const estimatedSaving = items.reduce((acc, it) => acc + (it.suggestions[0].estimatedSaving || 0), 0)
260
+ const red = findings.filter((f) => f.level === 'red').length
261
+ const yellow = findings.filter((f) => f.level === 'yellow').length
262
+ return {
263
+ store: String(store || ''), site: String(site || ''), capturedAt: new Date().toISOString(),
264
+ days: Math.max(1, Math.min(90, Number(days) || 7)), currency: String(currency || ''),
265
+ summary: {
266
+ cost: num(s.cost), adSales: num(s.amount), acos: pct2frac(s.acos), roas: num(s.roas),
267
+ clicks: num(s.clicks), impressions: num(s.prints), ctr: pct2frac(s.ctr),
268
+ targetAcos: target.value != null && target.value !== '' ? pct2frac(target.value) : null,
269
+ marginRate: null,
270
+ tone: red ? 'bad' : yellow ? 'warn' : 'good',
271
+ estimatedSaving: Math.round(estimatedSaving * 100) / 100,
272
+ },
273
+ items,
274
+ }
275
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Bridge 上报鉴权解析(L1,纯函数 + 一次只读文件)。
3
+ *
4
+ * 2026-11-25 起服务端 bridge 支持两种鉴权(见 whyshu-svr `middleware/bridgeAuth.js`):
5
+ * ① **机器令牌**(推荐):客户机 `agent-report.json` 里已有 `machineToken`(绑定租户+机器、可吊销);
6
+ * ② 共享密钥(过渡兼容):`DAILY_REPORT_BRIDGE_SECRET`。
7
+ *
8
+ * 本文件只回答"用哪把钥匙、往哪发",⛔ 不做判断、不联网:
9
+ * 优先级:环境变量 > agent-report.json(base/tenant/machineToken)> 无。
10
+ */
11
+ import { readFileSync } from 'node:fs'
12
+
13
+ const str = (x) => (x == null ? '' : String(x).trim())
14
+
15
+ /**
16
+ * @param {object} p
17
+ * @param {Record<string,string>} [p.env] 环境变量(默认 process.env)
18
+ * @param {object|null} [p.agentReport] `~/.dsh/argent/agent-report.json` 解析结果
19
+ * @returns {{base:string, tenant:string, machineToken:string, secret:string, mode:'machine'|'secret'|'none'}}
20
+ */
21
+ export function resolveBridgeAuth({ env = process.env, agentReport = null } = {}) {
22
+ const r = agentReport || {}
23
+ const base = str(env.ARGENT_API_BASE) || str(r.serverUrl)
24
+ const tenant = str(env.ARGENT_TENANT) || str(r.tenantAppId)
25
+ const machineToken = str(env.ARGENT_MACHINE_TOKEN) || str(r.machineToken)
26
+ const secret = str(env.DAILY_REPORT_BRIDGE_SECRET) || str(env.APPOINTMENT_BRIDGE_SECRET)
27
+ const mode = machineToken ? 'machine' : (secret ? 'secret' : 'none')
28
+ return { base, tenant, machineToken, secret, mode }
29
+ }
30
+
31
+ /**
32
+ * 读 agent-report.json(机器配置)。坏文件/不存在 ⇒ null(调用方继续走环境变量/共享密钥)。
33
+ * ⛔ 只读,不打印、不外传 token。
34
+ */
35
+ export function readAgentReport({ file } = {}) {
36
+ if (!file) return null
37
+ try {
38
+ const j = JSON.parse(readFileSync(file, 'utf8'))
39
+ return j && typeof j === 'object' ? j : null
40
+ } catch { return null }
41
+ }
42
+
43
+ /** 上报前判据:缺 base/tenant/钥匙 ⇒ 明确报错(不静默回退)。 */
44
+ export function assertBridgeAuth(auth) {
45
+ if (!auth || !auth.base) throw new Error('push 需要 ERP 地址:--api / ARGENT_API_BASE / agent-report.json#serverUrl')
46
+ if (!auth.tenant) throw new Error('push 需要租户 appId:--tenant / ARGENT_TENANT / agent-report.json#tenantAppId')
47
+ if (!auth.machineToken && !auth.secret) {
48
+ throw new Error('push 需要机器令牌(agent-report.json#machineToken)或共享密钥(DAILY_REPORT_BRIDGE_SECRET)')
49
+ }
50
+ }
@@ -0,0 +1,120 @@
1
+ /**
2
+ * 类目基线(C,2026-12-01,纯函数):官方搜索结果的只读统计。
3
+ * ⚠️ 口径:`paging.total` = 该类目在售商品数(平台返回,抽样无关);价格/评分为**搜索结果样本**统计,
4
+ * 页面必须标"样本"与"N 件";⛔ 不推断销量、不抓页面(ToS)。
5
+ */
6
+
7
+ const num = (v) => (v === null || v === undefined || v === '' || Number.isNaN(Number(v)) ? null : Number(v))
8
+ const round2 = (v) => (v == null ? null : Math.round(v * 100) / 100)
9
+
10
+ /** 分位数(线性插值;空数组 ⇒ null)。 */
11
+ export function quantile(values, q) {
12
+ const arr = (values || []).map(Number).filter((n) => Number.isFinite(n)).sort((a, b) => a - b)
13
+ if (!arr.length) return null
14
+ const pos = (arr.length - 1) * Math.max(0, Math.min(1, q))
15
+ const lo = Math.floor(pos), hi = Math.ceil(pos)
16
+ if (lo === hi) return arr[lo]
17
+ return round2(arr[lo] + (arr[hi] - arr[lo]) * (pos - lo))
18
+ }
19
+
20
+ /**
21
+ * @param {{categoryId:string, total:number|null, results:Array<{price:number, rating:number|null, sold:number}>}} input
22
+ * @param {{ourPrice?:number|null}} [opts]
23
+ */
24
+ export function categoryBaseline(input = {}, opts = {}) {
25
+ const results = Array.isArray(input.results) ? input.results : []
26
+ const prices = results.map((r) => num(r.price)).filter((n) => n != null && n > 0)
27
+ const ratings = results.map((r) => num(r.rating)).filter((n) => n != null && n > 0)
28
+ const median = quantile(prices, 0.5)
29
+ const ourPrice = num(opts.ourPrice)
30
+ // 样本太小(<4)时不给"贵/便宜"结论:否则 1 个样本会算出 100% ⇒ 误报"偏贵"(2026-12-01 实测)
31
+ const enough = prices.length >= 4
32
+ const pricePercentile = ourPrice != null && enough
33
+ ? round2(prices.filter((p) => p <= ourPrice).length / prices.length)
34
+ : null
35
+ const position = pricePercentile == null ? null
36
+ : pricePercentile <= 0.25 ? 'cheaper' : pricePercentile <= 0.75 ? 'mid' : 'pricier'
37
+ return {
38
+ categoryId: String(input.categoryId || ''),
39
+ totalItems: num(input.total),
40
+ sampleSize: results.length,
41
+ price: { min: prices.length ? round2(Math.min(...prices)) : null, p25: quantile(prices, 0.25), median, p75: quantile(prices, 0.75), max: prices.length ? round2(Math.max(...prices)) : null },
42
+ rating: { avg: ratings.length ? round2(ratings.reduce((a, b) => a + b, 0) / ratings.length) : null, count: ratings.length },
43
+ ours: { price: ourPrice, percentile: pricePercentile, position },
44
+ sample: true,
45
+ enoughSample: enough,
46
+ note: '价格为搜索结果样本统计;在售总数=平台 paging.total(不是销量)',
47
+ }
48
+ }
49
+
50
+ /** 纯函数:渲染中文基线卡。 */
51
+ export function categoryBaselineLines(cat = {}, { currency = '' } = {}) {
52
+ const cur = currency ? currency + ' ' : ''
53
+ const p = cat.price || {}
54
+ const out = [`📊 类目 ${cat.categoryId || '—'} · 在售 ${cat.totalItems ?? '—'} 件 · 样本 ${cat.sampleSize || 0} 件`]
55
+ out.push(`价格:最低 ${cur}${p.min ?? '—'} / 25分位 ${cur}${p.p25 ?? '—'} / 中位 ${cur}${p.median ?? '—'} / 75分位 ${cur}${p.p75 ?? '—'} / 最高 ${cur}${p.max ?? '—'}`)
56
+ if (cat.rating && cat.rating.avg != null) out.push(`样本评分均值 ${cat.rating.avg}(${cat.rating.count} 个有评分)`)
57
+ if (cat.ours && cat.ours.price != null) {
58
+ const pos = { cheaper: '低于多数竞品(偏便宜)', mid: '处于中间价位', pricier: '高于多数竞品(偏贵)' }[cat.ours.position] || '—'
59
+ out.push(`我方价格 ${cur}${cat.ours.price} · 价格分位 ${Math.round((cat.ours.percentile || 0) * 100)}% ⇒ ${pos}`)
60
+ }
61
+ if (cat.enoughSample === false) out.push('⚠️ 样本不足 4 件 ⇒ 不给「偏贵/偏便宜」结论(需要竞品清单或更多商品)')
62
+ out.push('ℹ️ 样本口径:只统计客户指定/自有商品样本;不推断销量、不抓页面。')
63
+ return out
64
+ }
65
+
66
+
67
+ /**
68
+ * 行业简版(同一份搜索结果,零额外请求):
69
+ * · 集中度:前 5 卖家在样本中的占比、有品牌信息的样本集中度;
70
+ * · 选品候选:样本内按**已售分桶参考值**排序的前 N(⛔ 不是真实销量,标注"估算")。
71
+ */
72
+ export function industryFromResults(results = []) {
73
+ const rows = (Array.isArray(results) ? results : []).filter((r) => r && (r.sellerId || r.brand || r.sold != null))
74
+ const total = rows.length
75
+ const bySeller = new Map()
76
+ for (const r of rows) { const k = r.sellerId ? String(r.sellerId) : ''; if (!k) continue; bySeller.set(k, (bySeller.get(k) || 0) + 1) }
77
+ const sellerShares = [...bySeller.values()].sort((a, b) => b - a).map((n) => Math.round((n / Math.max(1, total)) * 1000) / 1000)
78
+ const top5SellerShare = sellerShares.slice(0, 5).reduce((a, b) => a + b, 0)
79
+ const byBrand = new Map()
80
+ for (const r of rows) { const k = r.brand ? String(r.brand).trim() : ''; if (!k) continue; byBrand.set(k, (byBrand.get(k) || 0) + 1) }
81
+ const brandCount = byBrand.size
82
+ const brandShares = [...byBrand.values()].sort((a, b) => b - a).map((n) => Math.round((n / Math.max(1, total)) * 1000) / 1000)
83
+ return {
84
+ sellerCount: bySeller.size,
85
+ top5SellerShare: total ? Math.round(top5SellerShare * 1000) / 1000 : null,
86
+ brandCount,
87
+ top5BrandShare: total ? Math.round(brandShares.slice(0, 5).reduce((a, b) => a + b, 0) * 1000) / 1000 : null,
88
+ sampleSize: total,
89
+ }
90
+ }
91
+
92
+ /** 选品候选(零额外请求;⛔ 已售=平台分桶参考值,不是真实销量)。 */
93
+ export function selectionCandidates(results = [], { limit = 10, minRating = 0 } = {}) {
94
+ return (Array.isArray(results) ? results : [])
95
+ .filter((r) => r && Number.isFinite(Number(r.price)) && Number(r.price) > 0)
96
+ .filter((r) => (Number(r.rating) || 0) >= minRating)
97
+ .sort((a, b) => (Number(b.sold) || 0) - (Number(a.sold) || 0) || (Number(b.rating) || 0) - (Number(a.rating) || 0))
98
+ .slice(0, Math.max(1, Math.min(50, limit)))
99
+ .map((r, i) => ({
100
+ rank: i + 1,
101
+ itemId: String(r.itemId || ''),
102
+ title: String(r.title || '').slice(0, 80),
103
+ price: round2(r.price),
104
+ rating: Number.isFinite(Number(r.rating)) ? round2(r.rating) : null,
105
+ soldRef: Number.isFinite(Number(r.sold)) ? Number(r.sold) : null,
106
+ sellerId: r.sellerId ? String(r.sellerId) : '',
107
+ note: '已售为平台分桶参考值(估算),不是真实销量',
108
+ }))
109
+ }
110
+
111
+ /** 纯函数:行业卡渲染。 */
112
+ export function industryLines(ind = {}) {
113
+ const pct = (v) => (v == null ? '—' : Math.round(v * 100) + '%')
114
+ return [
115
+ `🏭 行业简版(样本 ${ind.sampleSize || 0} 件)`,
116
+ `卖家集中度:前 5 卖家占样本 ${pct(ind.top5SellerShare)}(共 ${ind.sellerCount ?? '—'} 个卖家)`,
117
+ `品牌集中度:前 5 品牌占样本 ${pct(ind.top5BrandShare)}(共 ${ind.brandCount ?? '—'} 个品牌)`,
118
+ 'ℹ️ 集中度=搜索结果样本分布;⛔ 不代表全类目份额。',
119
+ ]
120
+ }