@whyshu/argent-engine 0.8.0-rc.9 → 0.13.28

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,261 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * ml-market-snapshot.mjs —— 市场快照采集(**只读**):自有店铺在售 item + 客户指定竞品 ID → JSONL 历史。
4
+ *
5
+ * ## 干什么
6
+ * 逐店取「自有在售 item」+「客户显式给出的竞品 item ID 清单」→ 归一化快照(价格/状态/评分/
7
+ * 分桶参考值已售与库存)→ 追加落 JSONL → 读历史算「近 N 天销量**估算**」。
8
+ *
9
+ * ## 用法
10
+ * node scripts/ml-market-snapshot.mjs # 全部已授权店铺 · 自有在售最多 50 个
11
+ * node scripts/ml-market-snapshot.mjs --store 1店 # 店铺过滤(名称子串 / user_id 全等)
12
+ * node scripts/ml-market-snapshot.mjs --items-file comp.json # 客户指定的竞品 item ID 清单
13
+ * node scripts/ml-market-snapshot.mjs --days 30 # 估算窗口(默认 30 天)
14
+ * node scripts/ml-market-snapshot.mjs --out ./snap.jsonl # 落盘路径(默认数据目录 ml-market/<店>.jsonl)
15
+ * node scripts/ml-market-snapshot.mjs --json # 结构化输出(stdout 纯 JSON)
16
+ * node scripts/ml-market-snapshot.mjs --no-reviews # 跳过评价取数(少 N 次 GET)
17
+ *
18
+ * ## 采集边界(降 ToS 风险,硬边界)
19
+ * · 只采「自有店铺在售 item」+「客户清单里的竞品 ID」;
20
+ * · ⛔ 不采搜索结果页、⛔ 不写客户任何系统;只发 GET。
21
+ *
22
+ * ## 口径(写死在 lib,输出顶部必须标注)
23
+ * 官方 `sold_quantity` / `available_quantity` 是**分桶参考值**,不是精确值(如 6–25→5、
24
+ * 26–50→25、501–5000→500)。「近 N 天销量」只能靠**连续快照差值估算**,一律标「估算」。
25
+ *
26
+ * ## 只读纪律(与 ml-listing-audit / ml-ads 同一条授权链)
27
+ * · 唯一写盘 = ① token 轮换原子回写(tmp+rename、600)② 本 CLI 的快照 JSONL(业务产物);
28
+ * · API 基址:`--api-base` → `ML_API_BASE` → 默认平台地址(lib 里⛔不含域名,只在本 CLI 注入)。
29
+ *
30
+ * ## 退出码
31
+ * 0 正常 | 1 用法/配置错误 | 2 全部店铺失败
32
+ */
33
+ import { readFileSync, writeFileSync, renameSync, existsSync, mkdirSync, appendFileSync, chmodSync } from 'node:fs'
34
+ import { join, dirname } from 'node:path'
35
+ import { resolveDataDir } from './lib/argent-datadir.mjs'
36
+ import {
37
+ loadEnvFile, refreshStoreToken, apiGet as coreApiGet,
38
+ SITE_CURRENCY, fallbackSite, matchStores, storeKey,
39
+ } from './lib/daily-report-core.mjs'
40
+ import {
41
+ CALIBER, SNAPSHOT_SCHEMA, parseItemsDoc, parseSnapshotJsonl, collectStoreSnapshot,
42
+ estimateItemMonthly, renderStoreReport,
43
+ } from './lib/ml-market-core.mjs'
44
+
45
+ const API_BASE = () => process.env.ML_API_BASE || 'https://api.mercadolibre.com'
46
+ // 引擎侧 `apiGet` 不硬编码域名(vertical 门禁)⇒ CLI 必须把基址注入进程环境,
47
+ // 否则 refreshStoreToken 这条内部路径会报「缺少 API 基址」(2026-11-28 客户机实测:竞品定时器全店失败)。
48
+ if (!process.env.ML_API_BASE) process.env.ML_API_BASE = API_BASE()
49
+
50
+ const args = process.argv.slice(2)
51
+ const argVal = (n) => { const i = args.indexOf(n); return i >= 0 && args[i + 1] ? args[i + 1] : null }
52
+ const has = (n) => args.includes(n)
53
+
54
+ if (has('-h') || has('--help')) {
55
+ console.log(`市场快照采集(只读)
56
+
57
+ 用法: node scripts/ml-market-snapshot.mjs [选项]
58
+ --store <名或uid> 店铺过滤(名称子串 / user_id 全等,与日报同一判据)
59
+ --items-file <path> 竞品 item ID 清单(JSON,可选;不给且 --items-from-erp 时从 ERP 拉)
60
+ --items-from-erp 从 ERP「竞品清单」端点取(机器令牌;客户零输入;也认 ML_MARKET_ITEMS_FROM_ERP=1)
61
+ --out <path> 快照 JSONL 落盘路径;多店时把 <path> 当目录(每店一个文件)
62
+ --days <n> 月销估算窗口天数,默认 30(历史不足则该商品显示「历史不足」)
63
+ --limit <n> 每店自有在售采样上限,默认 50(上限 200)
64
+ --no-reviews 跳过评价取数(rating/reviews_count 留空,不伪造)
65
+ --json 结构化 JSON(stdout 纯 JSON)
66
+ --api-base <url> API 基址(缺省读 ML_API_BASE,再缺省用平台地址)
67
+ --env <path> daily-report.env 路径
68
+ -h, --help 本帮助
69
+
70
+ 口径:sold_quantity / available_quantity 是官方**分桶参考值**(不是精确值;6–25→5、26–50→25、
71
+ 501–5000→500 …)。「近 N 天销量」只能靠**连续快照差值估算**,输出一律标「估算」。
72
+ 采集边界:只采自有在售 + 客户指定竞品 ID;⛔ 不采搜索结果页、⛔ 不写客户系统。
73
+ 退出码: 0 正常 | 1 用法/配置错误 | 2 全部店铺失败`)
74
+ process.exit(0)
75
+ }
76
+
77
+ const DATA_DIR = resolveDataDir({ env: process.env }).dir
78
+ const ENV_PATH = argVal('--env') || join(DATA_DIR, 'daily-report.env')
79
+ const STORES_PATH = process.env.ML_API_STORES_JSON || join(DATA_DIR, 'ml-api-stores.json')
80
+ const env = loadEnvFile(ENV_PATH)
81
+ const doc = existsSync(STORES_PATH) ? JSON.parse(readFileSync(STORES_PATH, 'utf8')) : { stores: [] }
82
+ const stores = doc.stores || []
83
+
84
+ const persistStores = () => {
85
+ try {
86
+ mkdirSync(dirname(STORES_PATH), { recursive: true })
87
+ const tmp = `${STORES_PATH}.tmp`
88
+ writeFileSync(tmp, JSON.stringify({ stores }, null, 2) + '\n', { mode: 0o600 })
89
+ renameSync(tmp, STORES_PATH)
90
+ chmodSync(STORES_PATH, 0o600)
91
+ } catch (e) { console.error(`✗ token 写回失败:${e.message}`) }
92
+ }
93
+ const apiGet = (path, token) => coreApiGet(path, token, { base: API_BASE() })
94
+
95
+ const FLAG_JSON = has('--json')
96
+ const days = Math.max(1, Math.min(365, Math.trunc(Number(argVal('--days') || env.ML_MARKET_DAYS || process.env.ML_MARKET_DAYS || CALIBER.estimateWindowDays)) || CALIBER.estimateWindowDays))
97
+ const limit = Math.max(1, Math.min(200, Math.trunc(Number(argVal('--limit') || 50)) || 50))
98
+ const withReviews = !has('--no-reviews')
99
+ const outArg = argVal('--out')
100
+
101
+ if (has('--api-base') && argVal('--api-base')) process.env.ML_API_BASE = argVal('--api-base')
102
+
103
+ // ── 竞品清单(B2,2026-11-25):优先 ERP(客户在 ERP 维护,零输入);仍支持本地文件 ──
104
+ let competitorIds = []
105
+ let erpItemsError = ''
106
+ if (!argVal('--items-file') && (has('--items-from-erp') || /^(1|true|yes)$/i.test(String(process.env.ML_MARKET_ITEMS_FROM_ERP || '')))) {
107
+ try {
108
+ const { readAgentReport, resolveBridgeAuth, assertBridgeAuth } = await import('./lib/ml-bridge-auth.mjs')
109
+ const auth = resolveBridgeAuth({ env: process.env, agentReport: readAgentReport({ file: join(DATA_DIR, 'agent-report.json') }) })
110
+ assertBridgeAuth(auth)
111
+ const url = `${auth.base.replace(/\/+$/, '')}/api/argent/v1/tenants/${encodeURIComponent(auth.tenant)}/market/competitor-items`
112
+ const headers = auth.machineToken ? { authorization: `Bearer ${auth.machineToken}` } : { 'x-appointment-secret': auth.secret }
113
+ const res = await fetch(url, { headers, signal: AbortSignal.timeout(15000) })
114
+ const body = await res.json().catch(() => ({}))
115
+ const items = body && body.data && Array.isArray(body.data.items) ? body.data.items : []
116
+ competitorIds = items.map((x) => String(x)).filter((x) => /^[A-Za-z0-9]{4,40}$/.test(x))
117
+ if (body && body.data && body.data.truncated) console.error(`⚠️ ERP 竞品清单超过 200 条已截断(取 ${competitorIds.length})`)
118
+ if (!competitorIds.length) console.error('⚠️ ERP 竞品清单为空(继续只采自有店铺)')
119
+ } catch (e) {
120
+ erpItemsError = String((e && e.message) || e)
121
+ console.error(`⚠️ 从 ERP 取竞品清单失败:${erpItemsError.slice(0, 160)}(继续只采自有店铺)`)
122
+ }
123
+ }
124
+ if (has('--items-from-erp')) process.env.ML_MARKET_ITEMS_FROM_ERP = 'true'
125
+ if (argVal('--items-file')) {
126
+ const itemsPath = argVal('--items-file')
127
+ if (!existsSync(itemsPath)) {
128
+ console.error(`✗ 竞品清单不存在:${itemsPath}`)
129
+ process.exit(1)
130
+ }
131
+ let itemsDoc = null
132
+ try {
133
+ itemsDoc = JSON.parse(readFileSync(itemsPath, 'utf8'))
134
+ } catch (e) {
135
+ console.error(`✗ 竞品清单不是合法 JSON:${String(e.message || e).slice(0, 160)}`)
136
+ process.exit(1)
137
+ }
138
+ const parsed = parseItemsDoc(itemsDoc)
139
+ competitorIds = parsed.ids
140
+ if (!competitorIds.length) console.error('⚠️ 竞品清单里没有可用的 item ID(继续只采自有店铺)')
141
+ if (parsed.skipped) console.error(`⚠️ 竞品清单跳过 ${parsed.skipped} 个空条目`)
142
+ }
143
+
144
+ const picked = matchStores(stores, (argVal('--store') || '').split(',').map((x) => x.trim()).filter(Boolean))
145
+ if (!picked.length) {
146
+ console.error(`✗ 没有匹配到店铺(已授权 ${stores.length} 家)`)
147
+ process.exit(1)
148
+ }
149
+
150
+ // ── 落盘路径:单店 = 精确文件;多店 = 目录(每店一个文件)──────────
151
+ const outForStore = (store) => {
152
+ const key = storeKey(store)
153
+ if (!outArg) return join(DATA_DIR, 'ml-market', `${key}.jsonl`)
154
+ const multi = picked.length > 1
155
+ if (!multi) return outArg
156
+ return join(outArg, `${key}.jsonl`)
157
+ }
158
+
159
+ const appendRecords = (file, records) => {
160
+ if (!records.length) return
161
+ mkdirSync(dirname(file), { recursive: true })
162
+ const text = records.map((r) => JSON.stringify(r)).join('\n') + '\n'
163
+ appendFileSync(file, text, { mode: 0o600 })
164
+ try { chmodSync(file, 0o600) } catch { /* 非本用户文件等场景:忽略权限收紧失败,不遮错 */ }
165
+ }
166
+
167
+ const runStamp = new Date().toISOString()
168
+ const result = {
169
+ schema: SNAPSHOT_SCHEMA,
170
+ generatedAt: runStamp,
171
+ caliber: CALIBER,
172
+ windowDays: days,
173
+ ownLimit: limit,
174
+ competitorIds,
175
+ stores: [],
176
+ warnings: [],
177
+ errors: [],
178
+ }
179
+
180
+ for (const store of picked) {
181
+ const site = fallbackSite(store.site)
182
+ const storeName = String(store.name || store.user_id || '')
183
+ const outFile = outForStore(store)
184
+ const row = {
185
+ store: storeName, site, uid: store.user_id, outFile,
186
+ capturedAt: runStamp, items: [], history: null, estimates: {}, warnings: [], error: '',
187
+ }
188
+ try {
189
+ const token = await refreshStoreToken(env, store, { onRotate: persistStores })
190
+ const collected = await collectStoreSnapshot({
191
+ apiGet, token, site, uid: store.user_id, store: storeName,
192
+ ownLimit: limit, competitorIds, withReviews,
193
+ capturedAt: runStamp, currency: SITE_CURRENCY[site] || '',
194
+ })
195
+ row.items = collected.items
196
+ row.warnings = collected.warnings
197
+ appendRecords(outFile, collected.items)
198
+ } catch (e) {
199
+ row.error = String((e && e.message) || e)
200
+ result.errors.push(`${storeName}:${row.error}`)
201
+ console.error(`✗ ${storeName}:${row.error}`)
202
+ result.stores.push(row)
203
+ continue
204
+ }
205
+
206
+ // ── 读历史(含本次追加)→ 每个 item 一条「近 N 天销量估算」──────────
207
+ let historyRecords = []
208
+ let historyErrors = []
209
+ try {
210
+ if (existsSync(outFile)) {
211
+ const parsed = parseSnapshotJsonl(readFileSync(outFile, 'utf8'))
212
+ historyRecords = parsed.records
213
+ historyErrors = parsed.errors
214
+ }
215
+ } catch (e) {
216
+ row.warnings.push(`历史快照读取失败:${String((e && e.message) || e).slice(0, 140)}`)
217
+ }
218
+ const byItem = new Map()
219
+ for (const rec of historyRecords) {
220
+ if (!byItem.has(rec.itemId)) byItem.set(rec.itemId, [])
221
+ byItem.get(rec.itemId).push(rec)
222
+ }
223
+ for (const it of row.items) {
224
+ row.estimates[it.itemId] = estimateItemMonthly(byItem.get(it.itemId) || [], { days })
225
+ }
226
+ const times = historyRecords.map((r) => Date.parse(String(r.capturedAt || ''))).filter((x) => Number.isFinite(x))
227
+ row.history = {
228
+ records: historyRecords.length,
229
+ errors: historyErrors.length,
230
+ firstCapturedAt: times.length ? new Date(Math.min(...times)).toISOString() : '',
231
+ lastCapturedAt: times.length ? new Date(Math.max(...times)).toISOString() : '',
232
+ }
233
+ if (historyErrors.length) row.warnings.push(`历史快照有 ${historyErrors.length} 行解析失败(已跳过,请检查文件)`)
234
+ result.stores.push(row)
235
+ }
236
+
237
+ const ok = result.stores.filter((r) => !r.error)
238
+ if (FLAG_JSON) {
239
+ console.log(JSON.stringify(result, null, 2))
240
+ if (!ok.length) process.exit(2)
241
+ process.exit(0)
242
+ }
243
+
244
+ // ── 默认:人类可读报告(每店报告顶部自带口径两行,估算一律带「估算」)────
245
+ let printed = 0
246
+ for (const r of result.stores) {
247
+ if (r.error) {
248
+ console.log(`## 🛒 市场快照 · ${r.store}(${r.site})\n✗ ${r.error}\n`)
249
+ continue
250
+ }
251
+ for (const w of r.warnings || []) console.error(`⚠️ ${r.store}:${w}`)
252
+ const lines = renderStoreReport({
253
+ store: r.store, site: r.site, outFile: r.outFile,
254
+ items: r.items, estimates: r.estimates, history: r.history, estimateWindowDays: days,
255
+ })
256
+ console.log(lines.join('\n') + '\n')
257
+ printed++
258
+ }
259
+ if (!printed) console.error('✗ 全部店铺失败')
260
+ if (result.warnings.length) for (const w of result.warnings) console.error(`⚠️ ${w}`)
261
+ process.exit(ok.length ? 0 : 2)
@@ -0,0 +1,145 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * ml-messages.mjs —— 消息只读监控 + AI 回复草稿(B,2026-12-01)。
4
+ * 只读美客多(GET):未回复提问 / 未结纠纷;输出人类可执行清单 + 中文回复草稿。
5
+ * ⛔ 绝不回复/发消息(写操作一律不做);草稿供人工复制到美客多后台。
6
+ * 数据同时可推 ERP「智能分析 → 消息与体验」:--push(机器令牌)。
7
+ */
8
+ import { readFileSync, existsSync } from 'node:fs'
9
+ import { join } from 'node:path'
10
+ import { resolveDataDir } from './lib/argent-datadir.mjs'
11
+ import { loadEnvFile, refreshStoreToken, apiGet as coreApiGet, SITE_CURRENCY, fallbackSite, matchStores } from './lib/daily-report-core.mjs'
12
+ import { resolveBridgeAuth, readAgentReport, assertBridgeAuth } from './lib/ml-bridge-auth.mjs'
13
+
14
+ const API_BASE = () => process.env.ML_API_BASE || 'https://api.mercadolibre.com'
15
+ if (!process.env.ML_API_BASE) process.env.ML_API_BASE = API_BASE()
16
+ const args = process.argv.slice(2)
17
+ const argVal = (n) => { const i = args.indexOf(n); return i >= 0 && args[i + 1] ? args[i + 1] : null }
18
+ const has = (n) => args.includes(n)
19
+ if (has('-h') || has('--help')) {
20
+ console.log(`消息只读监控 + 回复草稿(⛔ 不回复、不写客户平台)
21
+
22
+ 用法: node scripts/ml-messages.mjs [选项]
23
+ --store <名或uid> 店铺过滤(名称子串 / uid 全等)
24
+ --limit <n> 每店最多取多少条(默认 20,上限 50)
25
+ --json 结构化 JSON
26
+ --lines 中文清单(含草稿)
27
+ --push 推到 ERP「智能分析 → 消息与体验」(机器令牌;先 --dry-run 核对)
28
+ --dry-run 配 --push 时只打印 payload
29
+ 退出码: 0 正常 | 1 用法/全部失败 | 2 推送失败`)
30
+ process.exit(0)
31
+ }
32
+ const DATA_DIR = resolveDataDir({ env: process.env }).dir
33
+ const ENV_PATH = argVal('--env') || join(DATA_DIR, 'daily-report.env')
34
+ if (!existsSync(ENV_PATH)) { console.error(`✗ 未找到 env:${ENV_PATH}(先在设置页保存过一次配置)`); process.exit(1) }
35
+ const env = loadEnvFile(ENV_PATH)
36
+ const STORES_PATH = join(DATA_DIR, 'ml-api-stores.json')
37
+ const stores = existsSync(STORES_PATH) ? (JSON.parse(readFileSync(STORES_PATH, 'utf8')).stores || []) : []
38
+ const limit = Math.max(1, Math.min(50, Number(argVal('--limit') || 20)))
39
+ const queries = (argVal('--store') || '').split(',').map((x) => x.trim()).filter(Boolean)
40
+ const picked = matchStores(stores, queries)
41
+
42
+ /** 纯函数:按提问内容挑中文草稿模板(模板化,不调 LLM,避免编事实)。 */
43
+ export function draftReply(text = '') {
44
+ const t = String(text || '')
45
+ if (/发票|factura|invoice/i.test(t)) return '您好!发票可在订单详情中申请,我们会在 24 小时内为您开具电子发票。感谢您的耐心等待。'
46
+ if (/多久|几天|发货|env[ií]o|delivery|send/i.test(t)) return '您好!订单会在 1–2 个工作日内发出,发出后您会收到物流单号,可随时在订单页查看进度。谢谢!'
47
+ if (/库存|有货|stock|disponible/i.test(t)) return '您好!该商品目前有货,下单后可正常发出;如遇临时缺货我们会第一时间联系您。谢谢!'
48
+ if (/尺寸|大小|多大|型号|talla|size|medida/i.test(t)) return '您好!页面「商品规格」里有详细尺寸,也可以告诉我您平时用的尺码,我帮您参考。谢谢!'
49
+ if (/退货|退款|devolu|refund|reembolso/i.test(t)) return '您好!我们支持平台退货政策,您可在订单页发起退货申请,我们会在收到后尽快处理。给您带来不便非常抱歉。'
50
+ if (/质量|坏|破损|roto|defectuoso|quality/i.test(t)) return '您好!非常抱歉给您带来不好的体验,请拍下商品问题照片发给我们,我们会按平台政策为您补发或退款。'
51
+ if (/折扣|优惠|descuento|discount|promo/i.test(t)) return '您好!目前的价格已是活动价,关注店铺可第一时间收到优惠通知。感谢支持!'
52
+ return '您好!感谢您的咨询,我们已收到,会在 1 小时内为您详细回复。谢谢!'
53
+ }
54
+
55
+ /** 纯函数:严重度(越久未回越急)。 */
56
+ export function severityOf(ageHours) {
57
+ if (ageHours == null || ageHours === '') return 'unknown'
58
+ const h = Number(ageHours)
59
+ if (!Number.isFinite(h)) return 'unknown'
60
+ if (h >= 24) return 'red'
61
+ if (h >= 6) return 'yellow'
62
+ return 'green'
63
+ }
64
+
65
+ const results = []
66
+ for (const store of picked) {
67
+ const site = fallbackSite(store.site)
68
+ const row = { store: store.name, site, currency: SITE_CURRENCY[site] || '', items: [] }
69
+ try {
70
+ const token = await refreshStoreToken(env, store, { onRotate: () => {} })
71
+ const uid = store.user_id
72
+ const q = await coreApiGet(`/questions/search?seller_id=${encodeURIComponent(uid)}&status=UNANSWERED&limit=${limit}`, token).catch(() => null)
73
+ const qs = (q && q.questions) || []
74
+ const c = await coreApiGet('/post-purchase/v1/claims/search?role=seller&status=opened&limit=50', token).catch(() => null)
75
+ const cs = (c && (c.data || c.claims)) || []
76
+ const now = Date.now()
77
+ for (const item of qs.slice(0, limit)) {
78
+ const created = item.date_created ? Date.parse(item.date_created) : null
79
+ const ageHours = created ? Math.round(((now - created) / 3600000) * 10) / 10 : null
80
+ row.items.push({ id: `q:${item.id}`, type: 'question', itemId: String(item.item_id || ''), text: String(item.text || '').slice(0, 500), createdAt: item.date_created || '', ageHours, severity: severityOf(ageHours), answerDraft: draftReply(item.text) })
81
+ }
82
+ for (const cl of cs.slice(0, Math.max(0, limit - row.items.length))) {
83
+ const created = cl.date_created ? Date.parse(cl.date_created) : null
84
+ const ageHours = created ? Math.round(((now - created) / 3600000) * 10) / 10 : null
85
+ row.items.push({ id: `c:${cl.id}`, type: 'claim', itemId: String(cl.resource_id || cl.item_id || ''), text: String(cl.reason_id || cl.status || '纠纷').slice(0, 200), createdAt: cl.date_created || '', ageHours, severity: severityOf(ageHours), answerDraft: draftReply(String(cl.reason_id || '')) })
86
+ }
87
+ row.items.sort((a, b) => (Number(b.ageHours) || 0) - (Number(a.ageHours) || 0))
88
+ row.summary = {
89
+ unansweredQuestions: qs.length, openClaims: cs.length,
90
+ oldestQuestionHours: row.items.filter((x) => x.type === 'question').reduce((m, x) => Math.max(m, Number(x.ageHours) || 0), 0) || null,
91
+ total: row.items.length,
92
+ }
93
+ results.push(row)
94
+ } catch (e) {
95
+ row.error = String((e && e.message) || e)
96
+ results.push(row)
97
+ }
98
+ }
99
+ const okRows = results.filter((r) => !r.error)
100
+ if (!okRows.length) {
101
+ for (const r of results) console.error(`✗ ${r.store}:${r.error}`)
102
+ process.exit(1)
103
+ }
104
+
105
+ /** 纯函数:ERP bridge payload(契约字段不可改名)。 */
106
+ export function buildMessagesBridgePayload(row) {
107
+ return {
108
+ store: String(row.store || ''), site: String(row.site || ''), capturedAt: new Date().toISOString(),
109
+ summary: { ...(row.summary || {}) },
110
+ items: (row.items || []).slice(0, 50).map((x) => ({
111
+ id: String(x.id), type: x.type === 'claim' ? 'claim' : 'question', itemId: String(x.itemId || ''),
112
+ text: String(x.text || ''), createdAt: String(x.createdAt || ''), ageHours: x.ageHours ?? null,
113
+ severity: String(x.severity || 'unknown'), answerDraft: String(x.answerDraft || ''),
114
+ })),
115
+ }
116
+ }
117
+
118
+ if (has('--push')) {
119
+ const auth = resolveBridgeAuth({ env: process.env, agentReport: readAgentReport({ file: join(DATA_DIR, 'agent-report.json') }) })
120
+ assertBridgeAuth(auth)
121
+ let fail = 0
122
+ for (const r of okRows) {
123
+ const payload = buildMessagesBridgePayload(r)
124
+ if (has('--dry-run')) { console.log(JSON.stringify({ dryRun: true, authMode: auth.mode, payload }, null, 2)); continue }
125
+ const url = `${auth.base.replace(/\/+$/, '')}/api/argent/v1/tenants/${encodeURIComponent(auth.tenant)}/reports/messages/bridge`
126
+ const headers = { 'content-type': 'application/json', ...(auth.machineToken ? { authorization: `Bearer ${auth.machineToken}` } : {}), ...(auth.secret ? { 'x-appointment-secret': auth.secret } : {}) }
127
+ const res = await fetch(url, { method: 'POST', headers, body: JSON.stringify(payload), signal: AbortSignal.timeout(20000) }).catch((e) => ({ ok: false, status: 0, json: async () => ({ message: String(e.message) }) }))
128
+ const body = await res.json().catch(() => ({}))
129
+ if (res.ok) console.error(`✓ ${r.store} 消息清单已推 ERP(${payload.items.length} 条)`)
130
+ else { fail++; console.error(`✗ ${r.store} 推送失败:HTTP ${res.status} ${JSON.stringify(body).slice(0, 160)}`) }
131
+ }
132
+ if (fail) process.exit(2)
133
+ }
134
+ if (has('--json')) { console.log(JSON.stringify({ generatedAt: new Date().toISOString(), results: okRows }, null, 2)); process.exit(0) }
135
+ const lines = []
136
+ for (const r of okRows) {
137
+ lines.push(`### ${r.store}(未回复 ${r.summary.unansweredQuestions} / 未结纠纷 ${r.summary.openClaims})`)
138
+ if (!r.items.length) lines.push('✅ 没有待处理消息')
139
+ for (const x of r.items.slice(0, 10)) {
140
+ lines.push(`- [${x.severity}] ${x.type === 'question' ? '提问' : '纠纷'} · ${x.ageHours != null ? x.ageHours + 'h' : '—'} · ${x.text.slice(0, 80)}`)
141
+ lines.push(` 草稿:${x.answerDraft}`)
142
+ }
143
+ lines.push('')
144
+ }
145
+ console.log(lines.join('\n'))
@@ -459,6 +459,20 @@ async function main() {
459
459
  continue
460
460
  }
461
461
  console.log(` \x1b[32m✓\x1b[0m [PUB-J5] 回读一致(第 ${post.attempts} 次):${post.integrity}`)
462
+ // PUB-J5b:元数据可见 ≠ 包可下载。2026-11-16 实测 0.11.4 发布后 tarball 404 约 4 分钟,
463
+ // 客户端"更新插件"直接失败,而 PUB-J5 是绿的(它只读 dist.integrity)。这里必须实际取一次字节。
464
+ try {
465
+ const tarball = `https://registry.npmjs.org/${pack.name.replace('/', '%2f')}/-/${pack.name.split('/').pop()}-${pack.version}.tgz`
466
+ const r = await fetch(tarball, { method: 'GET' })
467
+ if (!r.ok) {
468
+ red('PUB-J5b', `${pack.name}@${pack.version}`, `tarball 尚不可下载(HTTP ${r.status}):${tarball} ⇒ 客户端会"更新失败",稍后重试或等分发完成`)
469
+ audit.push({ pkg: pack.name, version: pack.version, integrity: pack.integrity, action: 'published-tarball-missing' })
470
+ continue
471
+ }
472
+ console.log(' \x1b[32m✓\x1b[0m [PUB-J5b] tarball 可下载')
473
+ } catch (e) {
474
+ console.log(` \x1b[33m•\x1b[0m [PUB-J5b] tarball 探测失败(不阻断):${e?.message || e}`)
475
+ }
462
476
  plan.push({ pkg: pack.name, version: pack.version, integrity: pack.integrity, action: 'published' })
463
477
  audit.push({ pkg: pack.name, version: pack.version, integrity: pack.integrity, action: 'published' })
464
478
  }
@@ -0,0 +1,87 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 运维代码修复 → 分支 + PR(问述内部;P3)。
4
+ * ⛔ 只开 PR,不合并、不发布、不碰客户机。
5
+ * 用法:
6
+ * node scripts/ops-codefix-pr.mjs --incident <incidentId> --title "fix: ..." [--repo <path>] [--body-file <path>] [--dry-run]
7
+ * 前置(由 agent 完成):在 dsh/ops-fix-<incident> 分支上改代码并跑通测试。
8
+ * 守卫:当前分支必须 dsh/ops-fix-*、不能是 main/master、必须有未提交改动(或已提交但未推送)。
9
+ */
10
+ import { execFileSync } from 'node:child_process'
11
+ import { existsSync, readFileSync } from 'node:fs'
12
+ import { homedir } from 'node:os'
13
+ import { join, resolve } from 'node:path'
14
+
15
+ const args = process.argv.slice(2)
16
+ const opt = (name, dft = '') => {
17
+ const i = args.indexOf(`--${name}`)
18
+ return i >= 0 ? String(args[i + 1] || '') : dft
19
+ }
20
+ const flag = (name) => args.includes(`--${name}`)
21
+ const incidentId = opt('incident')
22
+ const title = opt('title') || `fix(ops): incident ${incidentId}`
23
+ const repo = resolve(opt('repo', join(homedir(), 'Code', 'argent-dsh')))
24
+ const bodyFile = opt('body-file')
25
+ const dry = flag('dry-run')
26
+ if (!incidentId) { console.error('缺少 --incident'); process.exit(2) }
27
+
28
+ function git(cmd, argv) {
29
+ return execFileSync('git', [cmd, ...argv], { cwd: repo, encoding: 'utf8' }).trim()
30
+ }
31
+ function sh(cmd, argv) {
32
+ return execFileSync(cmd, argv, { cwd: repo, encoding: 'utf8' }).trim()
33
+ }
34
+ function opsToken() {
35
+ if (process.env.OPS_TOKEN) return process.env.OPS_TOKEN
36
+ try {
37
+ const p = join(homedir(), '.dsh', 'argent', 'ops-token.env')
38
+ const m = readFileSync(p, 'utf8').match(/^OPS_TOKEN=(.+)$/m)
39
+ return m ? m[1].trim() : ''
40
+ } catch { return '' }
41
+ }
42
+ async function incidentContext() {
43
+ const tk = opsToken()
44
+ if (!tk) return null
45
+ try {
46
+ const res = await fetch(`https://whyshu.com/api/ops/v1/internal/incidents?status=all&limit=500`, { headers: { 'x-ops-token': tk }, signal: AbortSignal.timeout(10000) })
47
+ const j = await res.json()
48
+ return (j?.data?.incidents || []).find((x) => String(x._id) === String(incidentId)) || null
49
+ } catch { return null }
50
+ }
51
+
52
+ const branch = git('rev-parse', ['--abbrev-ref', 'HEAD'])
53
+ const guardErrors = []
54
+ if (!/^dsh\/ops-fix-/.test(branch)) guardErrors.push(`分支必须以 dsh/ops-fix- 开头(当前 ${branch})`)
55
+ if (['main', 'master'].includes(branch)) guardErrors.push('禁止在 main/master 上直接提交')
56
+ const dirty = git('status', ['--porcelain'])
57
+ if (guardErrors.length) { console.error(`守卫未通过:\n- ${guardErrors.join('\n- ')}`); process.exit(3) }
58
+
59
+ const inc = await incidentContext()
60
+ const body = [
61
+ `## 运维 incident`,
62
+ `- incidentId: \`${incidentId}\``,
63
+ inc ? `- 规则: \`${inc.rule}\` / 级别: \`${inc.level}\` / 机器: \`${inc.machineId}\` / 店铺: \`${inc.store || '-'}\`` : '- (未取到 incident 上下文)',
64
+ inc && inc.detail ? `- detail: \n\`\`\`json\n${JSON.stringify(inc.detail, null, 2).slice(0, 3000)}\n\`\`\`` : '',
65
+ '',
66
+ bodyFile && existsSync(bodyFile) ? readFileSync(bodyFile, 'utf8') : '## 修复说明\n(agent 在此补充根因/改法/测试)',
67
+ '',
68
+ '> 本 PR 由运维自动化流程生成,**必须人工 review 后再合并**;未经审查不得发布。',
69
+ ].filter(Boolean).join('\n')
70
+
71
+ if (dry) {
72
+ console.log(JSON.stringify({ ok: true, dry: true, repo, branch, title, dirty: Boolean(dirty), incident: inc ? { id: incidentId, rule: inc.rule } : null, bodyPreview: body.slice(0, 400) }, null, 2))
73
+ process.exit(0)
74
+ }
75
+
76
+ // 提交(若有未提交改动)
77
+ if (dirty) {
78
+ git('add', ['-A'])
79
+ git('commit', ['-m', `${title}\n\nIncident: ${incidentId}`])
80
+ } else {
81
+ // 允许已提交未推送:检查 ahead
82
+ const ahead = git('rev-list', ['--count', `origin/main..${branch}`])
83
+ if (Number(ahead) <= 0) { console.error('守卫未通过:分支没有改动(工作树干净且无领先提交)'); process.exit(3) }
84
+ }
85
+ git('push', ['-u', 'origin', branch])
86
+ const prUrl = sh('gh', ['pr', 'create', '--base', 'main', '--head', branch, '--title', title, '--body', body])
87
+ console.log(JSON.stringify({ ok: true, pr: prUrl, branch, incidentId }, null, 2))
@@ -0,0 +1,30 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 代码修复候选队列(问述内部):把需要代码修复的 incident 汇总为 JSON,供开发机 agent 处理。
4
+ * 需要代码修复的规则(窗口/任务数/卡死等基础设施问题由 L1/L2 自愈,不在此列):
5
+ * duplicate_shipment_task / version_drift / 以及 OpsIncident.detail 中出现 needsCodeFix=true 的;
6
+ * 输出:{ at, items:[{incidentId, tenantId, machineId, store, rule, level, count, lastSeenAt, detail}] }
7
+ */
8
+ import { readFileSync } from 'node:fs'
9
+ import { homedir } from 'node:os'
10
+ import { join } from 'node:path'
11
+
12
+ const BASE = process.env.OPS_BASE || 'https://whyshu.com'
13
+ const CODE_RULES = new Set(['duplicate_shipment_task', 'version_drift'])
14
+ function opsToken() {
15
+ if (process.env.OPS_TOKEN) return process.env.OPS_TOKEN
16
+ try {
17
+ const raw = readFileSync(join(homedir(), '.dsh', 'argent', 'ops-token.env'), 'utf8')
18
+ const m = raw.match(/^OPS_TOKEN=(.+)$/m)
19
+ return m ? m[1].trim() : ''
20
+ } catch { return '' }
21
+ }
22
+ async function get(path) {
23
+ const res = await fetch(`${BASE}${path}`, { headers: { 'x-ops-token': opsToken() }, signal: AbortSignal.timeout(15000) })
24
+ const json = await res.json().catch(() => ({}))
25
+ if (!res.ok) throw new Error(json?.error?.message || `HTTP ${res.status}`)
26
+ return json.data ?? json
27
+ }
28
+ const data = await get('/api/ops/v1/internal/incidents?status=open&limit=200')
29
+ const items = (data.incidents || []).filter((x) => CODE_RULES.has(x.rule) || x.detail?.needsCodeFix === true)
30
+ console.log(JSON.stringify({ at: new Date().toISOString(), count: items.length, items }, null, 2))
@@ -0,0 +1,98 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 运维日报(问述内部):拉取运维层 overview/incidents,输出 Markdown。
4
+ * 用法:node scripts/ops-digest.mjs [--json]
5
+ * 凭据:OPS_TOKEN 环境变量 或 ~/.dsh/argent/ops-token.env(600,仅本机)
6
+ * 设计:docs/Argent-运维层-客户机健康与自愈-设计与操作方案.md §8
7
+ */
8
+ import { readFileSync, mkdirSync, writeFileSync } from 'node:fs'
9
+ import { homedir } from 'node:os'
10
+ import { join } from 'node:path'
11
+
12
+ const BASE = process.env.OPS_BASE || 'https://whyshu.com'
13
+ const RULE_LABEL = {
14
+ task_tab_mismatch: '任务数 > 预约标签页', store_over_concurrency: '同店超并发',
15
+ task_stalled: '任务卡死', window_missing: '窗口缺失/不可用',
16
+ noise_tab_present: '噪音标签', duplicate_shipment_task: '同货件重复任务',
17
+ machine_offline: '客户机离线', version_drift: '版本落后',
18
+ platform_no_slot: '平台无号(黑五常态)',
19
+ }
20
+
21
+ function opsToken() {
22
+ if (process.env.OPS_TOKEN) return process.env.OPS_TOKEN
23
+ try {
24
+ const raw = readFileSync(join(homedir(), '.dsh', 'argent', 'ops-token.env'), 'utf8')
25
+ const m = raw.match(/^OPS_TOKEN=(.+)$/m)
26
+ return m ? m[1].trim() : ''
27
+ } catch { return '' }
28
+ }
29
+
30
+ async function get(path) {
31
+ const token = opsToken()
32
+ if (!token) throw new Error('缺少 OPS_TOKEN(~/.dsh/argent/ops-token.env)')
33
+ const res = await fetch(`${BASE}${path}`, { headers: { 'x-ops-token': token }, signal: AbortSignal.timeout(15000) })
34
+ const json = await res.json().catch(() => ({}))
35
+ if (!res.ok) throw new Error(json?.error?.message || `HTTP ${res.status}`)
36
+ return json.data ?? json
37
+ }
38
+
39
+ const jsonMode = process.argv.includes('--json')
40
+ const [overview, incs, logsResp] = await Promise.all([
41
+ get('/api/ops/v1/internal/overview'),
42
+ get('/api/ops/v1/internal/incidents?status=open&limit=200'),
43
+ get('/api/ops/v1/internal/remediation-logs?limit=50').catch(() => ({ logs: [] })),
44
+ ])
45
+ const machines = overview.machines || []
46
+ const incidents = incs.incidents || []
47
+ const logs = (logsResp && logsResp.logs) || []
48
+ const dayAgo = Date.now() - 24 * 3600 * 1000
49
+ const recentLogs = logs.filter((x) => x.createdAt && new Date(x.createdAt).getTime() >= dayAgo)
50
+ const logCount = {}
51
+ for (const x of recentLogs) logCount[x.action] = (logCount[x.action] || 0) + 1
52
+ const now = new Date()
53
+ const online = machines.filter((m) => m.online).length
54
+
55
+ if (jsonMode) {
56
+ console.log(JSON.stringify({ at: now.toISOString(), overview, incidents }, null, 2))
57
+ process.exit(0)
58
+ }
59
+
60
+ const lines = []
61
+ lines.push(`# 运维日报 ${now.toLocaleString('zh-CN', { hour12: false })}`)
62
+ lines.push('')
63
+ lines.push(`## 概览`)
64
+ lines.push(`- 客户机:${online}/${machines.length} 在线`)
65
+ lines.push(`- 未闭环 incident:${incidents.length}(critical ${incidents.filter((x) => x.level === 'critical').length} / warning ${incidents.filter((x) => x.level === 'warning').length})`)
66
+ for (const m of machines) {
67
+ const stores = m.storeDetail || []
68
+ const mismatch = stores.filter((s) => (s.claimed || 0) > (s.appointmentTabs || 0)).length
69
+ lines.push(`- ${m.tenantId} / ${m.machineId}:${m.online ? '在线' : `离线 ${m.offlineFor ?? '?'} 分钟`},插件 ${m.pluginVersion || '-'} / 引擎 ${m.engineVersion || '-'},店铺 ${stores.length}${mismatch ? `,**${mismatch} 个店铺任务数>标签页数**` : ''}`)
70
+ }
71
+ lines.push('')
72
+ lines.push(`## 最近 24h 自愈审计`)
73
+ lines.push(recentLogs.length ? Object.entries(logCount).map(([k, n]) => `- ${k} ×${n}`).join('\n') : '- 无')
74
+ lines.push('')
75
+ lines.push(`## 未闭环 incident`)
76
+ if (!incidents.length) lines.push('- 无')
77
+ else {
78
+ for (const x of incidents.slice(0, 30)) {
79
+ lines.push(`- [${x.level}] ${x.tenantId} / ${x.machineId} / ${x.store || '-'}:${RULE_LABEL[x.rule] || x.rule} ×${x.count ?? 1}(${new Date(x.lastSeenAt).toLocaleString('zh-CN', { hour12: false })})`)
80
+ }
81
+ if (incidents.length > 30) lines.push(`- … 其余 ${incidents.length - 30} 条`)
82
+ }
83
+ const md = lines.join('\n') + '\n'
84
+ // 写入运维层(看板展示最新日报;--no-push 可跳过)
85
+ if (!process.argv.includes('--no-push')) {
86
+ try {
87
+ const res = await fetch(`${BASE}/api/ops/v1/internal/digest`, {
88
+ method: 'POST',
89
+ headers: { 'content-type': 'application/json', 'x-ops-token': opsToken() },
90
+ body: JSON.stringify({ markdown: md, summary: { machines: machines.length, online, incidents: incidents.length, at: now.toISOString() } }),
91
+ signal: AbortSignal.timeout(10000),
92
+ })
93
+ if (!res.ok) console.error('日报写入运维层失败:', res.status)
94
+ } catch (e) { console.error('日报写入运维层失败:', e.message) }
95
+ }
96
+ const dir = join(homedir(), '.dsh', 'argent', 'ops-digests')
97
+ try { mkdirSync(dir, { recursive: true }); writeFileSync(join(dir, `${now.toISOString().slice(0, 10)}.md`), md) } catch { /* noop */ }
98
+ console.log(md)