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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/MANIFEST.json +109 -43
  2. package/bin/runtime-install.mjs +92 -0
  3. package/engine/VERSION +1 -1
  4. package/engine/configs/billing-actions.json +30 -0
  5. package/engine/configs/mcp-tools.snapshot.json +47 -0
  6. package/engine/core/contracts/argent.contracts.json +3 -3
  7. package/engine/core/contracts/verbs.schema.json +64 -1
  8. package/engine/core/lib/account-token.mjs +37 -0
  9. package/engine/core/lib/contract.mjs +30 -0
  10. package/engine/core/lib/redact.mjs +34 -0
  11. package/engine/core/mcp/billing-upload.mjs +77 -0
  12. package/engine/core/mcp/erp-server.mjs +300 -0
  13. package/engine/core/mcp/gateway.mjs +333 -0
  14. package/engine/core/mcp/meter.mjs +101 -0
  15. package/engine/core/mcp/server.mjs +416 -2
  16. package/engine/core/mcp/vault.mjs +78 -0
  17. package/engine/scripts/appointment-worker.mjs +456 -35
  18. package/engine/scripts/appointment_grab.py +1389 -264
  19. package/engine/scripts/appointment_rules.py +118 -0
  20. package/engine/scripts/argent-timers.mjs +227 -0
  21. package/engine/scripts/argent-web-preflight.mjs +123 -0
  22. package/engine/scripts/argent-web-verify.mjs +105 -0
  23. package/engine/scripts/billing-upload.mjs +26 -0
  24. package/engine/scripts/build-doc-index.mjs +68 -0
  25. package/engine/scripts/build-engine-package.mjs +7 -1
  26. package/engine/scripts/capability-packs.lock.json +323 -300
  27. package/engine/scripts/check-docs-drift.mjs +51 -4
  28. package/engine/scripts/check-version-consistency.mjs +14 -1
  29. package/engine/scripts/ci-run.sh +2 -2
  30. package/engine/scripts/collect-intel.mjs +108 -0
  31. package/engine/scripts/daily-report-timer-plist.sh +18 -4
  32. package/engine/scripts/daily-report-timers.sh +36 -3
  33. package/engine/scripts/daily-report.mjs +78 -2
  34. package/engine/scripts/doc-status.mjs +212 -0
  35. package/engine/scripts/dsh-web-doctor.mjs +84 -0
  36. package/engine/scripts/engine-manifest.mjs +90 -0
  37. package/engine/scripts/engine-runtime-install.mjs +92 -0
  38. package/engine/scripts/erp-ui-install.mjs +127 -0
  39. package/engine/scripts/erp-ui-preflight.mjs +104 -0
  40. package/engine/scripts/erp-ui-verify.mjs +135 -0
  41. package/engine/scripts/flow-requirements.json +122 -99
  42. package/engine/scripts/full-exec-worker.mjs +251 -0
  43. package/engine/scripts/gen-preset-rows.mjs +1 -1
  44. package/engine/scripts/invoice_lip_runner.py +1 -0
  45. package/engine/scripts/invoice_runner.py +17 -6
  46. package/engine/scripts/invoice_stageb.py +21 -4
  47. package/engine/scripts/lib/bootcheck-wiring.mjs +7 -5
  48. package/engine/scripts/lib/intel-card.mjs +43 -0
  49. package/engine/scripts/lib/invoice_names.py +23 -0
  50. package/engine/scripts/lib/ml-ads-core.mjs +100 -18
  51. package/engine/scripts/lib/ml-ads-rules.mjs +275 -0
  52. package/engine/scripts/lib/ml-bridge-auth.mjs +50 -0
  53. package/engine/scripts/lib/ml-category-core.mjs +120 -0
  54. package/engine/scripts/lib/ml-insight-core.mjs +621 -0
  55. package/engine/scripts/lib/ml-insight-facts.mjs +424 -0
  56. package/engine/scripts/lib/ml-items.mjs +40 -0
  57. package/engine/scripts/lib/ml-listing-core.mjs +342 -0
  58. package/engine/scripts/lib/ml-market-core.mjs +774 -0
  59. package/engine/scripts/lib/plugin-packages.mjs +13 -0
  60. package/engine/scripts/lib/webdriver_ipc.py +61 -1
  61. package/engine/scripts/line_pack.py +196 -0
  62. package/engine/scripts/mcp-gateway-switch.mjs +100 -0
  63. package/engine/scripts/migrate-providers.mjs +3 -3
  64. package/engine/scripts/ml-ads-advice.mjs +140 -0
  65. package/engine/scripts/ml-ads.mjs +221 -0
  66. package/engine/scripts/ml-category-baseline.mjs +174 -0
  67. package/engine/scripts/ml-insight-diagnose.mjs +247 -0
  68. package/engine/scripts/ml-insight-run.sh +183 -0
  69. package/engine/scripts/ml-insight-timers.sh +224 -0
  70. package/engine/scripts/ml-listing-audit.mjs +170 -0
  71. package/engine/scripts/ml-market-matrix.mjs +84 -0
  72. package/engine/scripts/ml-market-snapshot.mjs +261 -0
  73. package/engine/scripts/ml-messages.mjs +145 -0
  74. package/engine/scripts/ml-oauth-setup.mjs +1 -1
  75. package/engine/scripts/npm-publish-argent.mjs +14 -0
  76. package/engine/scripts/ops-codefix-pr.mjs +87 -0
  77. package/engine/scripts/ops-codefix-queue.mjs +30 -0
  78. package/engine/scripts/ops-digest.mjs +98 -0
  79. package/engine/scripts/ops-verify.mjs +67 -0
  80. package/engine/scripts/orchestrator.py +410 -20
  81. package/engine/scripts/orchestrator_br.py +146 -4
  82. package/engine/scripts/plugin-bootcheck.mjs +50 -1
  83. package/engine/scripts/publish-engine.mjs +111 -0
  84. package/engine/scripts/restart-dsh-with-tunnel.sh +129 -0
  85. package/engine/scripts/skuflow_invoice_runner.py +43 -3
  86. package/engine/scripts/v0.9-acceptance.mjs +107 -0
  87. package/engine/scripts/vertical-lint.mjs +12 -1
  88. package/engine/scripts/web-switch.mjs +121 -0
  89. package/engine/scripts/wenyao_fill_template.py +52 -15
  90. package/engine/scripts/wenyao_run.py +2 -1
  91. package/engine/skills/README.md +3 -3
  92. package/engine/skills/bilibili-upload/SKILL.md +109 -0
  93. package/engine/skills/douyin-upload/SKILL.md +74 -0
  94. package/engine/skills/internal.json +28 -0
  95. package/engine/skills/kuaishou-upload/SKILL.md +109 -0
  96. package/engine/skills/ml-appointment-safety/SKILL.md +42 -0
  97. package/engine/skills/ml-full-appointment/SKILL.md +23 -0
  98. package/engine/skills/ml-invoice/SKILL.md +2 -2
  99. package/engine/skills/ml-invoice/references/template-fill-contract.md +1 -1
  100. package/engine/skills/ml-label-recovery/SKILL.md +43 -0
  101. package/engine/skills/ml-listing-audit/SKILL.md +66 -0
  102. package/engine/skills/ml-store-daily-report/SKILL.md +68 -0
  103. package/engine/skills/ml-store-daily-report/scripts/generate.js +35 -0
  104. package/engine/skills/ml-store-insight/SKILL.md +81 -0
  105. package/engine/skills/tencent-upload/SKILL.md +60 -0
  106. package/engine/skills/weibo-upload/SKILL.md +106 -0
  107. package/engine/skills/whyshu-social-ops/SKILL.md +136 -0
  108. package/engine/skills/xiaohongshu-upload/SKILL.md +122 -0
  109. package/engine/version.mjs +1 -1
  110. package/engine/verticals/README.md +7 -0
  111. package/engine/verticals/_engine-words.baseline.txt +27 -59
  112. package/engine/verticals/mercadolibre/manifest.json +132 -6
  113. package/package.json +5 -1
@@ -0,0 +1,621 @@
1
+ /**
2
+ * ml-insight-core.mjs —— 店铺诊断的**判据层**(L1,纯函数):信号 → 归因候选 → 证据 → 评分。
3
+ *
4
+ * ## 为什么是纯函数
5
+ * 「AI 分析店铺」里**算得清的部分必须确定性**:阈值、同环比、评分、证据链都在这里算完,
6
+ * LLM 只做「解释与排序」(L3/L4),⛔ 不许它产生新数字。这样同一份事实必然得到同一份结论,
7
+ * 可离线回归、可换模型、可审计。
8
+ *
9
+ * ## 输入:storeFacts(由 L1 取数层从日报分区/listing/market 组装)
10
+ * 见 `DEFAULT_THRESHOLDS` 下方注释里的字段说明;**缺的字段就是缺的**(不猜 0)。
11
+ *
12
+ * ## 输出:{ store, site, date, capturedAt, score, grade, dims, signals, missing }
13
+ * - 每条 signal 带 `id/level/confidence/metric/window/baseline/delta/evidenceRefs/attributions/actions`;
14
+ * - `missing[]` 列出"因缺数据而无法判定的维度/指标"(⛔ 不伪造、不静默)。
15
+ *
16
+ * ## 判据卡(v0.1,2026-11-24 用户确认默认口径)
17
+ * S1 转化下滑 S2 曝光下滑 S3 价格竞争力 S4 广告效率 S5 库存风险
18
+ * S6 流量结构 S7 利润侵蚀 S8 风险与体验 S9 Listing 质量 S10 竞品挤压
19
+ * O1 机会型(**不计分**,只进机会栏)
20
+ *
21
+ * 纪律:零 import、零 IO、零 Date.now(时间由调用方传入/已含在 facts 里)⇒ 逐字节可回归。
22
+ */
23
+
24
+ /** 默认阈值(业务确认后可按店覆盖;单位见注释)。 */
25
+ export const DEFAULT_THRESHOLDS = Object.freeze({
26
+ // S1 转化下滑
27
+ s1: { ordersWow: -0.15, visitsWow: -0.05, minBaselineOrders: 10 },
28
+ // S2 曝光下滑
29
+ s2: { visitsWow: -0.20, ordersWow: -0.05 },
30
+ // S3 价格竞争力
31
+ s3: { gapPct: 0.05 }, // 我方价比赢家高 5% 视为"竞争力不足"
32
+ // S4 广告效率(ACoS 单位:百分数)
33
+ s4: { acosWarn: 25, acosBad: 35, roasTargetFactor: 0.8, minSpend: 100 },
34
+ // S5 库存
35
+ s5: { leadDays: 15, bufferDays: 7 },
36
+ // S6 流量结构
37
+ s6: { zeroVisitShare: 0.30, minActive: 20, zeroVisitShareRed: 0.50 },
38
+ // S7 利润
39
+ s7: { feeRateJumpPp: 0.02, netRateFloor: 0.10 },
40
+ // S8 风险
41
+ s8: { claimRate: 0.02, unanswered: 5, unansweredRed: 10, oldestQuestionDays: 2 },
42
+ // S9 Listing 质量
43
+ s9: { avgScoreYellow: 60, avgScoreRed: 40, pendingYellow: 20, pendingRed: 40 },
44
+ // S10 竞品挤压
45
+ s10: { priceGapPct: 0.10, competitorDropPct: 0.10 },
46
+ // 评分卡
47
+ score: { a: 85, b: 70, c: 50 },
48
+ riskDimCapOnRed: 40,
49
+ })
50
+
51
+ /** 维度定义(权重之和 100;缺数据维度按剩余权重归一化)。 */
52
+ export const DIMENSIONS = Object.freeze([
53
+ { id: 'growth', label: '增长', weight: 25 },
54
+ { id: 'conversion', label: '转化与流量', weight: 20 },
55
+ { id: 'profit', label: '利润', weight: 25 },
56
+ { id: 'risk', label: '风险与体验', weight: 15 },
57
+ { id: 'quality', label: '商品质量', weight: 15 },
58
+ ])
59
+
60
+ const num = (x) => (x === null || x === undefined || x === '' ? null : (Number.isFinite(Number(x)) ? Number(x) : null))
61
+ const pctChange = (cur, prev) => {
62
+ const c = num(cur), p = num(prev)
63
+ if (c === null || p === null || p <= 0) return null
64
+ return Math.round(((c - p) / p) * 1000) / 1000
65
+ }
66
+ const round1 = (x) => Math.round(Number(x || 0) * 10) / 10
67
+
68
+ /** 内部:信号构造(统一字段,便于 L2/L3 消费)。 */
69
+ function signal({ id, level, dim, confidence = 1, metric, window, baseline, delta, evidenceRefs, attributions = [], actions = [] }) {
70
+ return { id, level, dim, confidence, metric, window, baseline, delta, evidenceRefs, attributions, actions }
71
+ }
72
+
73
+ /**
74
+ * 判据求值器。每个求值器返回 `{ signal }` / `null`(数据够但不触发)/ `{ unavailable: reason }`(缺数据)。
75
+ * `needs` 用于维度 N/A 判定:某维度的所有求值器都 unavailable ⇒ 该维度 N/A。
76
+ */
77
+ const EVALUATORS = [
78
+ // ── S1 转化下滑:订单跌、访客没跌 ─────────────────────────────
79
+ {
80
+ id: 'S1', dim: 'growth', needs: ['sales', 'traffic'],
81
+ run(f, t) {
82
+ const orders = num(f.sales && f.sales.orders)
83
+ const ordersPrev = num(f.sales && f.sales.ordersPrev)
84
+ const visits = num(f.traffic && f.traffic.visits)
85
+ const visitsPrev = num(f.traffic && f.traffic.visitsPrev)
86
+ if (orders === null || ordersPrev === null) return { unavailable: 'sales.orders/ordersPrev' }
87
+ if (visits === null || visitsPrev === null) {
88
+ // 快照模式(日报未存访客):只能判订单侧 ⇒ **低置信度黄**,⛔ 不假装"访客持平"
89
+ const ordersWowOnly = pctChange(orders, ordersPrev)
90
+ if (ordersWowOnly === null || !(ordersWowOnly <= t.s1.ordersWow)) return null
91
+ return {
92
+ signal: signal({
93
+ id: 'S1', level: 'yellow', dim: 'growth', confidence: 0.4,
94
+ metric: 'orders', window: '7d', baseline: 'prev7d', delta: ordersWowOnly,
95
+ evidenceRefs: ['sales.summary'],
96
+ attributions: [{ code: 'visits_missing', prob: 0.5, verify: 'daily-report traffic.visits(或加 --with-live)' }],
97
+ actions: [{ code: 'check_traffic', text: '先补访客数据再判转化(快照模式无访客,结论只到订单口径)', risk: 'low' }],
98
+ }),
99
+ }
100
+ }
101
+ const ordersWow = pctChange(orders, ordersPrev)
102
+ const visitsWow = pctChange(visits, visitsPrev)
103
+ if (ordersWow === null || visitsWow === null) return { unavailable: 'wow 计算(基线为 0)' }
104
+ if (!(ordersWow <= t.s1.ordersWow && visitsWow >= t.s1.visitsWow)) return null
105
+ const small = ordersPrev < t.s1.minBaselineOrders
106
+ const attributions = []
107
+ const stockout = Array.isArray(f.stock) && f.stock.some((s) => num(s.stock) === 0 && (num(s.sold7) || 0) > 0)
108
+ if (stockout) attributions.push({ code: 'stockout', prob: 0.5, verify: 'ops.restock' })
109
+ if (f.priceToWin && f.priceToWin.status === 'losing') attributions.push({ code: 'competitor_price', prob: 0.4, verify: 'traffic.priceToWin' })
110
+ if (num(f.listing && f.listing.avgScore) !== null && num(f.listing.avgScore) < t.s9.avgScoreYellow) {
111
+ attributions.push({ code: 'listing_quality', prob: 0.3, verify: 'ml-listing' })
112
+ }
113
+ if (!attributions.length) attributions.push({ code: 'conversion_unknown', prob: 0.3, verify: 'traffic.visits' })
114
+ const actions = []
115
+ if (stockout) actions.push({ code: 'restock', text: '优先补断货 SKU(见 ops.restock 建议量)', risk: 'low' })
116
+ if (f.priceToWin && f.priceToWin.status === 'losing') actions.push({ code: 'price_review', text: '评估跟价/差异化(需毛利底线)', risk: 'medium' })
117
+ if (!actions.length) actions.push({ code: 'investigate', text: '按归因顺序逐项验证(库存→竞品价→评价→Listing)', risk: 'low' })
118
+ return {
119
+ signal: signal({
120
+ id: 'S1', level: small ? 'yellow' : 'red', dim: 'growth', confidence: small ? 0.5 : 0.9,
121
+ metric: 'orders', window: '7d', baseline: 'prev7d', delta: ordersWow,
122
+ evidenceRefs: ['sales.summary', 'traffic.visits'], attributions, actions,
123
+ }),
124
+ }
125
+ },
126
+ },
127
+
128
+ // ── S2 曝光下滑:访客跌、订单没跌 ─────────────────────────────
129
+ {
130
+ id: 'S2', dim: 'growth', needs: ['traffic', 'sales'],
131
+ run(f, t) {
132
+ const visits = num(f.traffic && f.traffic.visits)
133
+ const visitsPrev = num(f.traffic && f.traffic.visitsPrev)
134
+ const orders = num(f.sales && f.sales.orders)
135
+ const ordersPrev = num(f.sales && f.sales.ordersPrev)
136
+ if (visits === null || visitsPrev === null) return { unavailable: 'traffic.visits/visitsPrev' }
137
+ if (orders === null || ordersPrev === null) return { unavailable: 'sales.orders/ordersPrev' }
138
+ const visitsWow = pctChange(visits, visitsPrev)
139
+ const ordersWow = pctChange(orders, ordersPrev)
140
+ if (visitsWow === null || ordersWow === null) return { unavailable: 'wow 计算(基线为 0)' }
141
+ if (!(visitsWow <= t.s2.visitsWow && ordersWow >= t.s2.ordersWow)) return null
142
+ const attributions = []
143
+ const ads = f.ads || {}
144
+ if (num(ads.activeCampaigns) === 0 && (num(ads.pausedCampaigns) || 0) > 0) attributions.push({ code: 'ads_stopped', prob: 0.6, verify: 'ads.summary' })
145
+ const catalog = f.catalog || {}
146
+ if ((num(catalog.paused) || 0) > 0) attributions.push({ code: 'item_paused', prob: 0.4, verify: 'items.status' })
147
+ if (!attributions.length) attributions.push({ code: 'exposure_unknown', prob: 0.3, verify: 'traffic.zombies' })
148
+ return {
149
+ signal: signal({
150
+ id: 'S2', level: 'yellow', dim: 'growth', confidence: 0.8,
151
+ metric: 'visits', window: '7d', baseline: 'prev7d', delta: visitsWow,
152
+ evidenceRefs: ['traffic.visits', 'traffic.zombies', 'ads.summary'],
153
+ attributions,
154
+ actions: [{ code: 'exposure_check', text: '查广告活动状态 / 商品是否被暂停 / 标题类目是否被改', risk: 'low' }],
155
+ }),
156
+ }
157
+ },
158
+ },
159
+
160
+ // ── S3 价格竞争力不足 ────────────────────────────────────────
161
+ {
162
+ id: 'S3', dim: 'conversion', needs: ['priceToWin'],
163
+ run(f, t) {
164
+ const pw = f.priceToWin
165
+ if (!pw || !pw.status) return { unavailable: 'traffic.priceToWin' }
166
+ const gap = num(pw.gapPct)
167
+ const losing = String(pw.status) !== 'winning'
168
+ // gap 未知(接口只给状态不给价差)⇒ 降级黄(0.5),⛔ 不凭"非 winning"直接判红
169
+ if (!losing && (gap === null || gap <= t.s3.gapPct)) return null
170
+ const level = gap === null ? 'yellow' : 'red'
171
+ return {
172
+ signal: signal({
173
+ id: 'S3', level, dim: 'conversion', confidence: gap === null ? 0.5 : 0.85,
174
+ metric: 'price_gap_pct', window: 'weekly', baseline: 'buy_box_winner',
175
+ delta: gap, evidenceRefs: ['traffic.priceToWin', 'items.price'],
176
+ attributions: [{ code: 'price_above_winner', prob: 0.7, verify: 'traffic.priceToWin' }],
177
+ actions: [{ code: 'price_review', text: '评估跟价(受毛利底线约束)或做差异化', risk: 'medium' }],
178
+ }),
179
+ }
180
+ },
181
+ },
182
+
183
+ // ── S4 广告效率恶化 ──────────────────────────────────────────
184
+ {
185
+ id: 'S4', dim: 'profit', needs: ['ads'],
186
+ run(f, t) {
187
+ const a = f.ads
188
+ if (!a) return { unavailable: 'ads.summary' }
189
+ const cost = num(a.cost) || 0
190
+ const acos = num(a.acos)
191
+ const roas = num(a.roas)
192
+ const target = num(a.targetRoas)
193
+ const zeroConv = num(a.zeroConvCampaigns) || 0
194
+ const out = []
195
+ let level = null
196
+ if (cost >= t.s4.minSpend && zeroConv > 0) { level = 'red'; out.push('zero_conversion') }
197
+ if (acos !== null) {
198
+ if (acos > t.s4.acosBad && level !== 'red') { level = 'red'; out.push('acos_bad') }
199
+ else if (acos > t.s4.acosWarn && !level) { level = 'yellow'; out.push('acos_warn') }
200
+ }
201
+ if (roas !== null && target !== null && roas < target * t.s4.roasTargetFactor) {
202
+ if (level !== 'red') level = level || 'yellow'
203
+ out.push('roas_below_target')
204
+ }
205
+ if (!level) return null
206
+ return {
207
+ signal: signal({
208
+ id: 'S4', level, dim: 'profit', confidence: 0.85,
209
+ metric: 'acos_roas', window: '7d', baseline: target ?? t.s4.acosWarn,
210
+ delta: acos, evidenceRefs: ['ads.summary'],
211
+ attributions: out.map((code) => ({ code, prob: 0.6, verify: 'ads.summary' })),
212
+ actions: [{ code: 'ads_advice_only', text: '出调预算/停活动/换 strategy 的建议单(人工执行)', risk: 'medium' }],
213
+ }),
214
+ }
215
+ },
216
+ },
217
+
218
+ // ── S5 库存风险 ────────────────────────────────────────────
219
+ {
220
+ id: 'S5', dim: 'quality', needs: ['stock'],
221
+ run(f, t) {
222
+ const stock = Array.isArray(f.stock) ? f.stock : null
223
+ if (!stock) return { unavailable: 'ops.restock' }
224
+ const bad = []
225
+ for (const s of stock) {
226
+ const q = num(s.stock), sold7 = num(s.sold7)
227
+ if (q === null || sold7 === null) continue
228
+ const daily = sold7 / 7
229
+ const days = daily > 0 ? q / daily : Infinity
230
+ if (q === 0 && sold7 > 0) bad.push({ sku: s.sku, level: 'red', days: 0, restock: Math.ceil((t.s5.leadDays + t.s5.bufferDays) * daily) })
231
+ else if (daily > 0 && days < t.s5.leadDays + t.s5.bufferDays) bad.push({ sku: s.sku, level: 'yellow', days: Math.round(days), restock: Math.ceil((t.s5.leadDays + t.s5.bufferDays) * daily - q) })
232
+ }
233
+ if (!bad.length) return null
234
+ const red = bad.some((x) => x.level === 'red')
235
+ return {
236
+ signal: signal({
237
+ id: 'S5', level: red ? 'red' : 'yellow', dim: 'quality', confidence: 0.9,
238
+ metric: 'sellable_days', window: 'now', baseline: `${t.s5.leadDays}+${t.s5.bufferDays}d`,
239
+ delta: bad.length, evidenceRefs: ['ops.restock'],
240
+ attributions: bad.slice(0, 5).map((x) => ({ code: 'stock_risk', sku: x.sku, prob: 0.8, verify: 'ops.restock' })),
241
+ actions: bad.slice(0, 5).map((x) => ({ code: 'restock', text: `${x.sku} 建议补货 ${Math.max(0, x.restock)} 件`, risk: 'low' })),
242
+ }),
243
+ }
244
+ },
245
+ },
246
+
247
+ // ── S6 流量结构病 ──────────────────────────────────────────
248
+ {
249
+ id: 'S6', dim: 'conversion', needs: ['traffic', 'catalog'],
250
+ run(f, t) {
251
+ const zero = num(f.traffic && f.traffic.zeroVisitActive)
252
+ const active = num(f.catalog && f.catalog.active)
253
+ if (zero === null || active === null || active <= 0) return { unavailable: 'traffic.zombies/catalog.active' }
254
+ if (active < t.s6.minActive) return null
255
+ const share = zero / active
256
+ if (share <= t.s6.zeroVisitShare) return null
257
+ return {
258
+ signal: signal({
259
+ id: 'S6', level: share > t.s6.zeroVisitShareRed ? 'red' : 'yellow', dim: 'conversion', confidence: 0.8,
260
+ metric: 'zero_visit_share', window: '7d', baseline: `>${Math.round(t.s6.zeroVisitShare * 100)}%`,
261
+ delta: Math.round(share * 1000) / 1000, evidenceRefs: ['traffic.zombies', 'items'],
262
+ attributions: [{ code: 'zombie_listings', prob: 0.7, verify: 'traffic.zombies' }],
263
+ actions: [{ code: 'listing_cleanup', text: '出下架/重发/换图清单(先看 Listing 质量分)', risk: 'low' }],
264
+ }),
265
+ }
266
+ },
267
+ },
268
+
269
+ // ── S7 利润侵蚀 ────────────────────────────────────────────
270
+ {
271
+ id: 'S7', dim: 'profit', needs: ['profit'],
272
+ run(f, t) {
273
+ const p = f.profit
274
+ if (!p) return { unavailable: 'profit.fees/net' }
275
+ const fee = num(p.feeRate), feePrev = num(p.feeRatePrev)
276
+ const net = num(p.netRate)
277
+ const floor = num(p.netRateFloor) ?? t.s7.netRateFloor
278
+ const feeJump = fee !== null && feePrev !== null ? Math.round((fee - feePrev) * 10000) / 10000 : null
279
+ const red = net !== null && net < floor
280
+ const yellow = feeJump !== null && feeJump >= t.s7.feeRateJumpPp
281
+ if (!red && !yellow) return null
282
+ return {
283
+ signal: signal({
284
+ id: 'S7', level: red ? 'red' : 'yellow', dim: 'profit', confidence: 0.8,
285
+ metric: 'fee_rate/net_rate', window: '7d', baseline: floor, delta: feeJump,
286
+ evidenceRefs: ['profit.fees', 'profit.net'],
287
+ attributions: [{ code: red ? 'net_below_floor' : 'fee_rate_up', prob: 0.6, verify: 'profit.fees' }],
288
+ actions: [{ code: 'margin_review', text: '查佣金/优惠/运费变化与低毛利 SKU 占比', risk: 'low' }],
289
+ }),
290
+ }
291
+ },
292
+ },
293
+
294
+ // ── S8 风险与体验 ──────────────────────────────────────────
295
+ {
296
+ id: 'S8', dim: 'risk', needs: ['risk'],
297
+ run(f, t) {
298
+ const r = f.risk
299
+ if (!r) return { unavailable: 'risk.*' }
300
+ const claim = num(r.claimRate)
301
+ const delayed = num(r.delayedShipments)
302
+ const cancel = num(r.cancelRate)
303
+ const unanswered = num(r.unansweredQuestions)
304
+ const oldest = num(r.oldestQuestionDays)
305
+ const hits = []
306
+ if (claim !== null && claim > t.s8.claimRate) hits.push({ code: 'claim_rate', red: true })
307
+ if (delayed !== null && delayed > 0) hits.push({ code: 'delayed_shipment', red: true })
308
+ if (cancel !== null && cancel > 0.03) hits.push({ code: 'cancel_rate', red: true })
309
+ if (unanswered !== null && unanswered > (t.s8.unansweredRed || 10)) hits.push({ code: 'unanswered_questions', red: true })
310
+ else if (unanswered !== null && unanswered > t.s8.unanswered) hits.push({ code: 'unanswered_questions', red: false })
311
+ if (oldest !== null && oldest > t.s8.oldestQuestionDays) hits.push({ code: 'old_question', red: false })
312
+ if (!hits.length) return null
313
+ return {
314
+ signal: signal({
315
+ id: 'S8', level: hits.some((h) => h.red) ? 'red' : 'yellow', dim: 'risk', confidence: 0.95,
316
+ metric: 'risk_set', window: 'now', baseline: '硬线', delta: hits.length,
317
+ evidenceRefs: ['risk.reputation', 'risk.todo', 'risk.sla'],
318
+ attributions: hits.map((h) => ({ code: h.code, prob: 0.9, verify: 'risk.*' })),
319
+ actions: [{ code: 'resolve_today', text: '今日必处理(平台处罚风险优先于增长)', risk: 'low' }],
320
+ }),
321
+ }
322
+ },
323
+ },
324
+
325
+ // ── S9 Listing 质量拖累 ────────────────────────────────────
326
+ {
327
+ id: 'S9', dim: 'quality', needs: ['listing'],
328
+ run(f, t) {
329
+ const l = f.listing
330
+ if (!l) return { unavailable: 'ml-listing(/performance)' }
331
+ const avg = num(l.avgScore), pending = num(l.pendingTotal)
332
+ if (avg === null && pending === null) return { unavailable: 'listing.avgScore/pendingTotal' }
333
+ const red = (avg !== null && avg < t.s9.avgScoreRed) || (pending !== null && pending >= t.s9.pendingRed)
334
+ const yellow = (avg !== null && avg < t.s9.avgScoreYellow) || (pending !== null && pending >= t.s9.pendingYellow)
335
+ if (!red && !yellow) return null
336
+ return {
337
+ signal: signal({
338
+ id: 'S9', level: red ? 'red' : 'yellow', dim: 'quality', confidence: 0.9,
339
+ metric: 'listing_score/pending', window: 'now', baseline: t.s9.avgScoreYellow,
340
+ delta: avg, evidenceRefs: ['ml-listing'],
341
+ attributions: [{ code: 'listing_quality', prob: 0.7, verify: 'ml-listing' }],
342
+ actions: [{ code: 'listing_fix', text: '按官方 rules 整改(优先 CHARACTERISTICS 桶,深链已附)', risk: 'low' }],
343
+ }),
344
+ }
345
+ },
346
+ },
347
+
348
+ // ── S10 竞品挤压 ──────────────────────────────────────────
349
+ {
350
+ id: 'S10', dim: 'quality', needs: ['market'],
351
+ run(f, t) {
352
+ const m = f.market
353
+ if (!m || !Array.isArray(m.competitors)) return { unavailable: 'ml-market 快照' }
354
+ const our = num(m.ourPrice)
355
+ if (our === null) return { unavailable: 'market.ourPrice' }
356
+ const drops = []
357
+ const gaps = []
358
+ const rated = []
359
+ for (const c of m.competitors) {
360
+ const price = num(c.price), prev = num(c.prevPrice)
361
+ if (price !== null && prev !== null && prev > 0) {
362
+ const drop = (prev - price) / prev
363
+ if (drop >= t.s10.competitorDropPct) drops.push({ id: c.id, drop: Math.round(drop * 1000) / 1000 })
364
+ }
365
+ if (price !== null && price > 0) {
366
+ const gap = (our - price) / price
367
+ if (gap >= t.s10.priceGapPct) gaps.push({ id: c.id, gap: Math.round(gap * 1000) / 1000 })
368
+ }
369
+ if (num(c.rating) !== null && num(m.ourRating) !== null && Number(c.rating) > Number(m.ourRating)) rated.push(c.id)
370
+ }
371
+ const hits = drops.length + gaps.length + (rated.length ? 1 : 0)
372
+ if (hits === 0) return null
373
+ return {
374
+ signal: signal({
375
+ id: 'S10', level: hits >= 2 ? 'red' : 'yellow', dim: 'quality', confidence: 0.75,
376
+ metric: 'competitor_price/rating', window: 'snapshot', baseline: '竞品集', delta: gaps.length,
377
+ evidenceRefs: ['ml-market'],
378
+ attributions: [
379
+ ...drops.slice(0, 2).map((d) => ({ code: 'competitor_price_drop', competitorId: d.id, prob: 0.5, verify: 'ml-market' })),
380
+ ...(rated.length ? [{ code: 'competitor_rating_overtake', prob: 0.3, verify: 'ml-market' }] : []),
381
+ ],
382
+ actions: [{ code: 'competitive_review', text: '评估价格/内容/广告应对(受毛利底线约束)', risk: 'medium' }],
383
+ }),
384
+ }
385
+ },
386
+ },
387
+
388
+ // ── O1 机会型(不计分)────────────────────────────────────
389
+ {
390
+ id: 'O1', dim: 'opportunity', needs: ['trends'],
391
+ run(f) {
392
+ const tr = f.trends
393
+ if (!tr || !Array.isArray(tr.keywords)) return { unavailable: 'trends(可选)' }
394
+ const hot = tr.keywords.filter((k) => num(k.rank) !== null && num(k.rankPrev) !== null
395
+ && (num(k.rankPrev) - num(k.rank)) >= 5)
396
+ if (!hot.length) return null
397
+ return {
398
+ signal: signal({
399
+ id: 'O1', level: 'info', dim: 'opportunity', confidence: 0.6,
400
+ metric: 'trend_rank_up', window: 'weekly', baseline: '上周排名', delta: hot.length,
401
+ evidenceRefs: ['trends'], attributions: [], actions: [{ code: 'opportunity', text: '关注热词上行品类(选品/上新参考)', risk: 'low' }],
402
+ }),
403
+ }
404
+ },
405
+ },
406
+ ]
407
+
408
+ /** 维度 → 参与的信号 id(用于扣分与 N/A 判定)。 */
409
+ export const DIM_SIGNALS = Object.freeze({
410
+ growth: ['S1', 'S2'],
411
+ conversion: ['S3', 'S6'],
412
+ profit: ['S4', 'S7'],
413
+ risk: ['S8'],
414
+ quality: ['S5', 'S9', 'S10'],
415
+ })
416
+
417
+ /**
418
+ * 主入口:店铺诊断(纯函数)。
419
+ * @param {object} facts 店铺事实(见文件头)
420
+ * @param {object} [opts] { thresholds?: 覆盖默认阈值(深合并一层), grade?: {a,b,c} }
421
+ * @returns {{store,site,date,capturedAt,score,grade,dims,signals,missing}}
422
+ */
423
+ export function assessStore(facts, opts = {}) {
424
+ const f = facts && typeof facts === 'object' ? facts : {}
425
+ const t = mergeThresholds(opts.thresholds)
426
+ const signals = []
427
+ const missing = new Set()
428
+ const dimUnavailable = {}
429
+
430
+ for (const ev of EVALUATORS) {
431
+ let r = null
432
+ try { r = ev.run(f, t) } catch (e) { r = { unavailable: `求值异常:${String(e && e.message || e).slice(0, 80)}` } }
433
+ if (!r) continue
434
+ if (r.unavailable) {
435
+ missing.add(`${ev.id}: ${r.unavailable}`)
436
+ if (ev.dim !== 'opportunity') dimUnavailable[ev.dim] = (dimUnavailable[ev.dim] || 0) + 1
437
+ continue
438
+ }
439
+ if (r.signal) signals.push(r.signal)
440
+ }
441
+ if (f.coverage && Array.isArray(f.coverage.missing)) for (const m of f.coverage.missing) missing.add(String(m))
442
+
443
+ // 维度 N/A:该维度参与信号**全部** unavailable(且至少评估过一条)
444
+ const dims = {}
445
+ let weightedSum = 0
446
+ let weightTotal = 0
447
+ for (const d of DIMENSIONS) {
448
+ const driven = DIM_SIGNALS[d.id] || []
449
+ const unavailableCount = dimUnavailable[d.id] || 0
450
+ const noData = driven.length > 0 && unavailableCount >= driven.length
451
+ if (noData) {
452
+ dims[d.id] = { label: d.label, weight: d.weight, score: null, status: 'no_data' }
453
+ continue
454
+ }
455
+ let score = 100
456
+ const hits = signals.filter((s) => s.dim === d.id)
457
+ for (const s of hits) {
458
+ if (s.level === 'red') score -= 25
459
+ else if (s.level === 'yellow') score -= 10
460
+ }
461
+ score = Math.max(0, score)
462
+ if (d.id === 'risk' && hits.some((s) => s.level === 'red')) score = Math.min(score, t.riskDimCapOnRed)
463
+ dims[d.id] = { label: d.label, weight: d.weight, score, status: hits.length ? 'ok' : 'ok', hits: hits.map((s) => s.id) }
464
+ weightedSum += score * d.weight
465
+ weightTotal += d.weight
466
+ }
467
+ const score = weightTotal > 0 ? round1(weightedSum / weightTotal) : null
468
+ const g = { a: t.score.a, b: t.score.b, c: t.score.c, ...(opts.grade || {}) }
469
+ const grade = score === null ? 'unknown' : score >= g.a ? 'A' : score >= g.b ? 'B' : score >= g.c ? 'C' : 'D'
470
+
471
+ return {
472
+ store: String(f.store || ''),
473
+ site: String(f.site || ''),
474
+ date: String(f.date || ''),
475
+ capturedAt: String(f.capturedAt || ''),
476
+ score, grade, dims,
477
+ signals: signals.sort((a, b) => levelRank(a.level) - levelRank(b.level) || String(a.id).localeCompare(String(b.id))),
478
+ missing: [...missing],
479
+ }
480
+ }
481
+
482
+ const levelRank = (lv) => ({ red: 0, yellow: 1, info: 2 }[lv] ?? 9)
483
+
484
+ /** 深合并一层(只覆盖显式给出的键;数组/对象替换)。 */
485
+ function mergeThresholds(overrides) {
486
+ const base = JSON.parse(JSON.stringify(DEFAULT_THRESHOLDS))
487
+ if (!overrides || typeof overrides !== 'object') return base
488
+ for (const [k, v] of Object.entries(overrides)) {
489
+ if (v && typeof v === 'object' && !Array.isArray(v) && base[k] && typeof base[k] === 'object') {
490
+ Object.assign(base[k], v)
491
+ } else {
492
+ base[k] = v
493
+ }
494
+ }
495
+ return base
496
+ }
497
+
498
+ /** 便捷:只取需要人看的信号(红/黄),按严重度排序( oportunidades 单独返回)。 */
499
+ export function actionableSignals(result) {
500
+ const all = (result && result.signals) || []
501
+ return { alerts: all.filter((s) => s.level === 'red' || s.level === 'yellow'), opportunities: all.filter((s) => s.level === 'info') }
502
+ }
503
+
504
+ /**
505
+ * 纯函数:诊断结果 → 中文卡片行(日报/飞书/角色回复/CLI 共用)。
506
+ * ⛔ 只渲染 L1 已有字段,不产生新数字;顺序 = 红 → 黄 → 机会 → 缺数据。
507
+ */
508
+ export function renderDiagnosisLines(result, { topN = 5, currency = '' } = {}) {
509
+ const r = result || {}
510
+ const out = []
511
+ const cur = currency ? currency + ' ' : ''
512
+ out.push(`📊 店铺健康 · ${r.store || '-'} · ${r.date || '-'} · **${r.score == null ? '—' : r.score}(${r.grade || '—'})**`)
513
+ const dims = r.dims || {}
514
+ const dimLine = DIMENSIONS.map((d) => {
515
+ const v = dims[d.id]
516
+ return `${d.label} ${v && v.score != null ? v.score : 'N/A'}`
517
+ }).join(' · ')
518
+ out.push(dimLine)
519
+ const { alerts, opportunities } = actionableSignals(r)
520
+ for (const s of alerts.slice(0, topN)) {
521
+ const flag = s.level === 'red' ? '🔴' : '🟡'
522
+ out.push(`${flag} **${s.id}** ${describeMetric(s)}(conf ${s.confidence})`)
523
+ const why = (s.attributions || []).slice(0, 3).map((a) => a.code).filter(Boolean).join(' / ')
524
+ if (why) out.push(` 归因:${why}`)
525
+ for (const a of (s.actions || []).slice(0, 2)) if (a.text) out.push(` 建议:${a.text}`)
526
+ }
527
+ if (opportunities.length) out.push(`💡 机会:${opportunities.map((s) => `${s.id}(${s.metric})`).join('、')}`)
528
+ const missing = (r.missing || []).slice(0, 4)
529
+ if (missing.length) out.push(`⚠️ 缺数据:${missing.join(';')}${(r.missing || []).length > missing.length ? ' …' : ''}`)
530
+ return out
531
+ }
532
+
533
+ /** 信号的"人话"摘要(只拼已有字段,不做解释)。 */
534
+ function describeMetric(s) {
535
+ const pct = (v) => (v == null ? '—' : `${v > 0 ? '+' : ''}${Math.round(v * 1000) / 10}%`)
536
+ switch (s.id) {
537
+ case 'S1': return `订单 ${pct(s.delta)}(访客持平)`
538
+ case 'S2': return `访客 ${pct(s.delta)}(订单持平)`
539
+ case 'S3': return `价格落后 ${pct(s.delta)}`
540
+ case 'S4': return `广告效率(ACoS ${s.delta == null ? '—' : s.delta}%)`
541
+ case 'S5': return `库存风险 ${s.delta} 个 SKU`
542
+ case 'S6': return `0 访客占比 ${s.delta == null ? '—' : Math.round(s.delta * 100) + '%'}`
543
+ case 'S7': return `利润侵蚀${s.delta == null ? '' : `(费用 +${Math.round(s.delta * 1000) / 10}pp)`}`
544
+ case 'S8': return `风险与体验 ${s.delta} 项超线`
545
+ case 'S9': return `Listing 平均 ${s.delta == null ? '—' : s.delta} 分`
546
+ case 'S10': return '竞品挤压'
547
+ case 'O1': return '热词上行'
548
+ default: return s.metric || s.id
549
+ }
550
+ }
551
+
552
+ /**
553
+ * 上报 payload(**只含诊断结论**,不含 raw facts / 不含 token):
554
+ * 给 ERP「AI 建议(诊断)」tab;字段即契约(whyshu-svr `InsightReport` 按此校验)。
555
+ */
556
+ export function buildInsightBridgePayload(result, opts = {}) {
557
+ const r = result || {}
558
+ const s = (v) => (v == null ? '' : String(v).slice(0, 120))
559
+ const dims = {}
560
+ for (const d of DIMENSIONS) {
561
+ const v = (r.dims || {})[d.id]
562
+ if (!v) continue
563
+ dims[d.id] = { label: s(v.label || d.label), weight: Number(v.weight) || d.weight, score: v.score == null ? null : Number(v.score), status: s(v.status || 'ok') }
564
+ }
565
+ return {
566
+ store: s(r.store), site: s(r.site), date: s(r.date),
567
+ capturedAt: s(opts.capturedAt) || new Date().toISOString().slice(0, 24),
568
+ generatedAt: s(opts.generatedAt) || new Date().toISOString().slice(0, 24),
569
+ score: r.score == null ? null : Number(r.score),
570
+ grade: s(r.grade),
571
+ dims,
572
+ signals: (r.signals || []).slice(0, 50).map((x) => ({
573
+ id: s(x.id), level: s(x.level), confidence: Number(x.confidence) || 0,
574
+ metric: s(x.metric), window: s(x.window), baseline: s(x.baseline),
575
+ delta: x.delta == null ? null : Number(x.delta),
576
+ evidenceRefs: (x.evidenceRefs || []).slice(0, 10).map(s),
577
+ attributions: (x.attributions || []).slice(0, 6).map((a) => ({ code: s(a && a.code), prob: Number(a && a.prob) || 0, verify: s(a && a.verify) })),
578
+ actions: (x.actions || []).slice(0, 6).map((a) => ({ code: s(a && a.code), text: s(a && a.text), risk: s(a && a.risk) })),
579
+ })),
580
+ missing: (r.missing || []).slice(0, 20).map(s),
581
+ }
582
+ }
583
+
584
+ /**
585
+ * POST 一次诊断上报。`fetchImpl` 可注入(离线测试);网络/HTTP 失败返回 `{ok:false,error}`,不抛。
586
+ * @param {object} payload buildInsightBridgePayload 的产物
587
+ * @param {{base?:string, tenant?:string, secret?:string, fetchImpl?:Function, timeoutMs?:number}} opts
588
+ */
589
+ export async function pushInsightReport(payload, opts = {}) {
590
+ const base = String(opts.base || '')
591
+ const tenant = String(opts.tenant || '')
592
+ const secret = String(opts.secret || '')
593
+ const fetchImpl = opts.fetchImpl || globalThis.fetch
594
+ const machineToken = String(opts.machineToken || '')
595
+ if (!base) throw new Error('push 需要 ERP 地址:--api 或 ARGENT_API_BASE')
596
+ if (!tenant) throw new Error('push 需要租户 appId:--tenant 或 ARGENT_TENANT')
597
+ if (!machineToken && !secret) throw new Error('push 需要机器令牌(agent-report.json#machineToken)或上报密钥 DAILY_REPORT_BRIDGE_SECRET')
598
+ if (typeof fetchImpl !== 'function') throw new Error('push 需要 fetch 实现')
599
+ const url = `${base.replace(/\/+$/, '')}/api/argent/v1/tenants/${encodeURIComponent(tenant)}/reports/insight/bridge`
600
+ const ctl = typeof AbortController === 'function' ? new AbortController() : null
601
+ const timer = ctl ? setTimeout(() => ctl.abort(), Math.max(1000, Number(opts.timeoutMs) || 15000)) : null
602
+ try {
603
+ const res = await fetchImpl(url, {
604
+ method: 'POST',
605
+ headers: {
606
+ 'content-type': 'application/json',
607
+ ...(machineToken ? { authorization: `Bearer ${machineToken}` } : {}),
608
+ ...(secret ? { 'x-appointment-secret': secret } : {}),
609
+ },
610
+ body: JSON.stringify(payload),
611
+ signal: ctl ? ctl.signal : undefined,
612
+ })
613
+ const body = await res.json().catch(() => ({}))
614
+ if (!res.ok) return { ok: false, status: res.status, error: `HTTP ${res.status} ${JSON.stringify(body).slice(0, 200)}` }
615
+ return { ok: true, status: res.status, data: body }
616
+ } catch (e) {
617
+ return { ok: false, status: 0, error: String((e && e.message) || e) }
618
+ } finally {
619
+ if (timer) clearTimeout(timer)
620
+ }
621
+ }