@whyshu/argent-engine 0.8.0-rc.3 → 0.8.0-rc.5

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 (39) hide show
  1. package/MANIFEST.json +36 -20
  2. package/engine/VERSION +1 -1
  3. package/engine/core/contracts/argent.contracts.json +1 -1
  4. package/engine/scripts/argent-doctor.mjs +34 -1
  5. package/engine/scripts/argent-schedule.mjs +6 -0
  6. package/engine/scripts/build-engine-package.mjs +1 -1
  7. package/engine/scripts/capability-packs.lock.json +36 -36
  8. package/engine/scripts/check-argent-desktop.mjs +91 -0
  9. package/engine/scripts/daily-report-run.sh +68 -0
  10. package/engine/scripts/daily-report-status.mjs +130 -0
  11. package/engine/scripts/daily-report-timer-plist.sh +89 -0
  12. package/engine/scripts/daily-report-timers.sh +162 -0
  13. package/engine/scripts/daily-report.mjs +79 -4
  14. package/engine/scripts/erp_invoice_shadow.py +62 -0
  15. package/engine/scripts/erp_invoice_writeback.py +93 -0
  16. package/engine/scripts/flow-requirements.json +3 -3
  17. package/engine/scripts/flow-timers.sh +11 -0
  18. package/engine/scripts/flow_config.py +14 -0
  19. package/engine/scripts/flow_source.py +10 -1
  20. package/engine/scripts/flow_sources/__init__.py +1 -0
  21. package/engine/scripts/flow_sources/erp.py +54 -0
  22. package/engine/scripts/huangwei-preflight.sh +42 -0
  23. package/engine/scripts/invoice_lip_runner.py +43 -0
  24. package/engine/scripts/lib/daily-report-status.mjs +227 -0
  25. package/engine/scripts/lib/plugin-packages.mjs +3 -0
  26. package/engine/scripts/orchestrator.py +173 -5
  27. package/engine/scripts/orchestrator_br.py +89 -1
  28. package/engine/scripts/publish-release-0.8.0-rc.4.sh +18 -0
  29. package/engine/scripts/query_runner.py +2 -3
  30. package/engine/scripts/release-gate-0.8.mjs +1 -0
  31. package/engine/scripts/skuflow_invoice_runner.py +145 -0
  32. package/engine/scripts/verify-release-0.8.0-rc.4.sh +16 -0
  33. package/engine/scripts/vertical-lint.mjs +19 -0
  34. package/engine/tools/agentic/README.md +95 -0
  35. package/engine/tools/agentic/mcp_server.py +212 -0
  36. package/engine/tools/agentic/ml_agent_tools.py +602 -0
  37. package/engine/version.mjs +1 -1
  38. package/engine/verticals/mercadolibre/flows.json +3 -1
  39. package/package.json +1 -1
@@ -0,0 +1,227 @@
1
+ /**
2
+ * 日报定时器状态 —— **唯一读写实现**(引擎写、桌宠 / CLI / doctor 读)。
3
+ *
4
+ * 为什么要有这个文件(2026-10-30 事故):
5
+ * 日报此前走「launchd 唤醒 LLM 会话」的投递方式。客户机切到 dsh Desktop 后宿主
6
+ * (`dsh --profile argent --port 3080`)被停,定时器每 5 分钟照常认领、照常唤醒失败,
7
+ * 而 **没有任何一处能让人看见"定时器还在不在跑"** —— launchctl 显示最后 exit 0(无票那一轮),
8
+ * 失败只落在日志 + 台账里,客户侧完全静默。
9
+ * ⇒ 日报改成「launchd 直跑确定性脚本」后,必须有一个**人可读、机器可读**的状态面。
10
+ *
11
+ * 纪律:
12
+ * · 纯 node 内建(fs/path)+ 同层 L1(`daily-report-core.mjs`),零第三方、零宿主 import;
13
+ * · 写侧只有 `writeStatus()` 一个入口(tmp + rename 原子写),⛔ 别处不许直接写这个文件;
14
+ * · 状态文件是**派生事实**,删了不会丢数据(下次运行自动重建);⛔ 不当台账用。
15
+ *
16
+ * 文件:`<ARGENT_DATA_DIR>/daily-report-timer-status.json`
17
+ */
18
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs'
19
+ import { dirname, join } from 'node:path'
20
+ import { SITE_TZ, fallbackSite, localDateStr, storeKey, tzOffsetMs } from './daily-report-core.mjs'
21
+
22
+ export const STATUS_SCHEMA = 1
23
+ export const STATUS_FILE = 'daily-report-timer-status.json'
24
+ export const TIMER_LABEL = 'com.whyshu.daily-report-timer'
25
+ export const DEFAULT_REPORT_TIME = '00:05'
26
+
27
+ export const statusPath = (dataHome) => join(dataHome, STATUS_FILE)
28
+
29
+ /** 读状态文件;缺失/损坏 ⇒ `{}`(⛔ 不抛:桌宠每 5s 读一次,坏文件不许把页面搞崩)。 */
30
+ export function readStatus(dataHome) {
31
+ try {
32
+ const raw = JSON.parse(readFileSync(statusPath(dataHome), 'utf8'))
33
+ if (!raw || typeof raw !== 'object') return {}
34
+ return raw
35
+ } catch {
36
+ return {}
37
+ }
38
+ }
39
+
40
+ /** 原子写(tmp + rename)。返回落盘对象,便于调用方打日志。 */
41
+ export function writeStatus(dataHome, status) {
42
+ const next = { ...status, schema: STATUS_SCHEMA }
43
+ mkdirSync(dataHome, { recursive: true })
44
+ const file = statusPath(dataHome)
45
+ const tmp = `${file}.tmp`
46
+ writeFileSync(tmp, JSON.stringify(next, null, 1) + '\n')
47
+ renameSync(tmp, file)
48
+ return next
49
+ }
50
+
51
+ /**
52
+ * 合并语义(**关键**):一次运行只更新它知道的字段。
53
+ * · 顶层字段:patch 覆盖 prev;
54
+ * · `stores`:按 storeKey 浅合并(本轮没跑到的店保留上次事实);
55
+ * · `lastPushed` / `pending` / `stores` 之外的数组:整段替换(它们描述"本轮")。
56
+ * 为什么:定时器每小时跑一次,绝大多数轮次是「未到点、零动作」;
57
+ * 若 no-op 轮次把 `lastPushAt` / 每个店的状态冲掉,桌宠就会一直显示"从未推送"。
58
+ */
59
+ export function mergeStatus(prev = {}, patch = {}) {
60
+ const out = { ...prev, ...patch }
61
+ if (patch.stores || prev.stores) {
62
+ const merged = { ...(prev.stores || {}) }
63
+ for (const [k, v] of Object.entries(patch.stores || {})) merged[k] = { ...(merged[k] || {}), ...v }
64
+ out.stores = merged
65
+ }
66
+ return out
67
+ }
68
+
69
+ /** `HH:MM` / `HH:MM:SS` → `{ h, m }`;非法 ⇒ 默认 00:05(与文档默认口径一致,⛔ 不抛)。 */
70
+ export function parseHHMM(text, fallback = DEFAULT_REPORT_TIME) {
71
+ const m = /^(\d{1,2}):(\d{2})(?::\d{2})?$/.exec(String(text ?? '').trim())
72
+ if (m) {
73
+ const h = Number(m[1])
74
+ const mi = Number(m[2])
75
+ if (h >= 0 && h <= 23 && mi >= 0 && mi <= 59) return { h, m: mi }
76
+ }
77
+ const f = /^(\d{1,2}):(\d{2})/.exec(String(fallback)) || [0, '0', '5']
78
+ return { h: Number(f[1]) || 0, m: Number(f[2]) || 0 }
79
+ }
80
+
81
+ /** 本地墙钟(某时区的 y/m/d/h/mi)→ UTC Date;两次迭代吸收 DST 偏移变化。 */
82
+ function wallToUtc(tz, y, mo, d, h, mi) {
83
+ const naive = Date.UTC(y, mo - 1, d, h, mi)
84
+ let t = naive - tzOffsetMs(tz, new Date(naive))
85
+ t = naive - tzOffsetMs(tz, new Date(t))
86
+ return new Date(t)
87
+ }
88
+
89
+ /**
90
+ * 某站点本地的**下一次** `HH:MM`(严格晚于 now)→ Date(UTC 表示)。
91
+ * 例:墨西哥 `00:05`、北京 13:00 ⇒ 返回北京时间 14:05。
92
+ */
93
+ export function nextLocalOccurrence(tz, now, reportTime = DEFAULT_REPORT_TIME) {
94
+ const { h, m } = parseHHMM(reportTime)
95
+ const [y, mo, d] = localDateStr(tz, now).split('-').map(Number)
96
+ let cand = wallToUtc(tz, y, mo, d, h, m)
97
+ if (cand.getTime() <= now.getTime()) {
98
+ const next = new Date(Date.UTC(y, mo - 1, d) + 86400000) // 墙钟加一天(不做 tz 运算)
99
+ cand = wallToUtc(tz, next.getUTCFullYear(), next.getUTCMonth() + 1, next.getUTCDate(), h, m)
100
+ }
101
+ return cand
102
+ }
103
+
104
+ /** 下一次发生时"该推哪一天"的日报:站点本地的前一天(D 日数据在 D+1 00:05 推)。 */
105
+ export function pendingDateFor(tz, occurrence, dayMs = 86400000) {
106
+ return localDateStr(tz, new Date(occurrence.getTime() - dayMs))
107
+ }
108
+
109
+ /** 扫 `daily-report-cache/` 里某店最新的幂等标记 → `{ date, at }`;没有 ⇒ `null`。 */
110
+ export function latestPushed(cacheDir, key) {
111
+ const suffix = `-${key}`
112
+ let names = []
113
+ try {
114
+ names = readdirSync(cacheDir)
115
+ } catch {
116
+ return null
117
+ }
118
+ let best = null
119
+ for (const name of names) {
120
+ if (!name.startsWith('.pushed-') || !name.endsWith(suffix)) continue
121
+ const date = name.slice('.pushed-'.length, name.length - suffix.length)
122
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) continue
123
+ if (!best || date > best.date) {
124
+ let at = null
125
+ try { at = new Date(statSync(join(cacheDir, name)).mtimeMs).toISOString() } catch { /* noop */ }
126
+ best = { date, at }
127
+ }
128
+ }
129
+ return best
130
+ }
131
+
132
+ /** `YYYY-MM-DD` 加减天数(纯日历运算,不涉时区)。 */
133
+ export function addDays(dateStr, n) {
134
+ const d = new Date(`${dateStr}T00:00:00Z`)
135
+ d.setUTCDate(d.getUTCDate() + n)
136
+ return d.toISOString().slice(0, 10)
137
+ }
138
+
139
+ /**
140
+ * 每店事实 + 下一次应推时点(纯函数;`cacheDir` 只用于读标记)。
141
+ *
142
+ * 三个日期要分清(UI 上最容易混):
143
+ * · `dueDate` = **下一次**时点会推哪一天(= 下一次发生的站点本地日期前一天);
144
+ * · `expectedLast` = **到此刻为止最后该推**的那一天(= dueDate 前一天);
145
+ * · `missed` = `lastDate+1 … expectedLast` 里缺的天(上限 7,避免 UI 刷屏)。
146
+ * 2026-10-30 事故的教训:只报"下一次几点"会让"昨天那一份根本没推"这件事看不见。
147
+ */
148
+ export function computeStoreStates({ stores = [], cacheDir = '', now = new Date(), reportTime = DEFAULT_REPORT_TIME, lookaheadDays = 3 } = {}) {
149
+ return stores.map((store) => {
150
+ const site = fallbackSite(store.site)
151
+ const tz = SITE_TZ[site]
152
+ const key = storeKey(store)
153
+ const last = cacheDir ? latestPushed(cacheDir, key) : null
154
+ let occurrence = nextLocalOccurrence(tz, now, reportTime)
155
+ let dueDate = pendingDateFor(tz, occurrence)
156
+ // 已推过这一天的(例如手动 --force 补推过)⇒ 下一次时点顺延,别显示"要推一个已推过的日期"
157
+ for (let i = 0; i < lookaheadDays; i += 1) {
158
+ if (!last || last.date < dueDate) break
159
+ occurrence = new Date(occurrence.getTime() + 86400000)
160
+ dueDate = pendingDateFor(tz, occurrence)
161
+ }
162
+ const expectedLast = addDays(dueDate, -1)
163
+ const missed = []
164
+ if (!last || last.date < expectedLast) {
165
+ let d = last ? addDays(last.date, 1) : addDays(expectedLast, -6)
166
+ while (d <= expectedLast && missed.length < 7) {
167
+ missed.push(d)
168
+ d = addDays(d, 1)
169
+ }
170
+ }
171
+ return {
172
+ key,
173
+ store: String(store.name ?? ''),
174
+ site,
175
+ tz,
176
+ lastDate: last?.date || '',
177
+ lastPushAt: last?.at || '',
178
+ dueDate,
179
+ expectedLast,
180
+ missed,
181
+ nextDueAt: occurrence.toISOString(),
182
+ }
183
+ })
184
+ }
185
+
186
+ /** 由每店事实汇总出状态文件里那几段(纯函数)。 */
187
+ export function summarizeStates(states = []) {
188
+ const pending = states.filter((s) => s.missed.length > 0).map((s) => ({
189
+ store: s.store, site: s.site, dueDate: s.dueDate, missed: s.missed,
190
+ }))
191
+ const nextDueAt = states.reduce((min, s) => (!min || s.nextDueAt < min ? s.nextDueAt : min), '')
192
+ const lastPushAt = states.reduce((max, s) => (s.lastPushAt > max ? s.lastPushAt : max), '')
193
+ const missedTotal = states.reduce((n, s) => n + s.missed.length, 0)
194
+ return {
195
+ nextDueAt,
196
+ lastPushAt,
197
+ missedTotal,
198
+ pending,
199
+ stores: Object.fromEntries(states.map((s) => [s.key, {
200
+ store: s.store, site: s.site, tz: s.tz,
201
+ lastDate: s.lastDate, lastPushAt: s.lastPushAt,
202
+ dueDate: s.dueDate, expectedLast: s.expectedLast, missed: s.missed,
203
+ nextDueAt: s.nextDueAt,
204
+ }])),
205
+ }
206
+ }
207
+
208
+ /**
209
+ * 人读一行(CLI / doctor 共用;⛔ 桌宠客户端不复制这句,UI 自己排版)。
210
+ * @param {object} status 状态文件内容
211
+ * @param {{now?:Date, locale?:(d:Date)=>string}} [opts]
212
+ */
213
+ export function describeStatus(status = {}, { now = new Date(), fmt = (d) => d.toISOString() } = {}) {
214
+ if (!status || !status.lastRunAt) return '定时器尚未运行过(无状态文件)'
215
+ const parts = []
216
+ parts.push(status.lastExit ? `上次运行失败(exit ${status.lastExit})` : '上次运行正常')
217
+ if (status.lastPushAt) {
218
+ const age = now.getTime() - Date.parse(status.lastPushAt)
219
+ parts.push(`上次推送 ${Number.isFinite(age) ? fmt(new Date(status.lastPushAt)) : status.lastPushAt}`)
220
+ } else {
221
+ parts.push('还没有成功推送记录')
222
+ }
223
+ if (status.nextDueAt) parts.push(`下次 ${fmt(new Date(status.nextDueAt))}`)
224
+ if (status.missedTotal) parts.push(`缺 ${status.missedTotal} 天日报`)
225
+ if (status.lastError) parts.push(`错误:${String(status.lastError).slice(0, 120)}`)
226
+ return parts.join(' · ')
227
+ }
@@ -59,6 +59,9 @@ export const PLUGIN_PACKAGES = [
59
59
  // · 发布流水线(`scripts/npm-publish-argent.mjs --only argent-shell`)按本清单认包
60
60
  // —— 不登记 ⇒ Lead 用**官方**发布脚本发不出它。
61
61
  { id: 'argent-shell', npm: `${NPM_SCOPE}/argent-shell` },
62
+ // Desktop 端 ERP 连接器(2026-10-29):单 bundle + 单 insert,只做 office/ERP 通道
63
+ // (快照/对话/建会话/本地任务),不装 core/skin/flow/gateway ⇒ 与 web 端套装解耦。
64
+ { id: 'argent-desktop', npm: `${NPM_SCOPE}/argent-desktop` },
62
65
  ]
63
66
 
64
67
  /**
@@ -2545,6 +2545,19 @@ FALLBACK_DATE_JS = r"""() => {
2545
2545
  }
2546
2546
  return {found: false, needFlip: true, mode: 'header', header: headerText};
2547
2547
  }
2548
+ // 目标月不在视图:若视图已是**更晚的月份**(目标 10/30、日历已翻到 11 月),
2549
+ // 直接选视图内第一个可用日(>= 目标);⛔ 不再为了“精确目标日”继续翻到 12 月。
2550
+ const viewMonth = viewMonths[0];
2551
+ const viewDate = new Date(viewYear, viewMonth, 1);
2552
+ const targetMonthDate = new Date(target.getFullYear(), target.getMonth(), 1);
2553
+ if (viewDate > targetMonthDate) {
2554
+ for (let i = 0; i < n; i++) {
2555
+ const t = (days[i].textContent || '').trim();
2556
+ if (/^\d+$/.test(t) && !days[i].classList.contains('day--disabled')) {
2557
+ return {found: true, idx: i, mode: 'next_available', header: headerText};
2558
+ }
2559
+ }
2560
+ }
2548
2561
  return {found: false, needFlip: true, mode: 'header', header: headerText};
2549
2562
  }
2550
2563
  // header 不可靠:降级为「目标日数字 + 视图内该数字后的第一个可用格」(last resort)
@@ -7270,6 +7283,16 @@ class RunState:
7270
7283
  terminal_evidence: str = ""
7271
7284
 
7272
7285
 
7286
+ class NullFeishu:
7287
+ """ERP-only 记录源:不读写 lip,所有 Feishu 写操作 no-op。"""
7288
+ dry_run = True
7289
+
7290
+ def __getattr__(self, name):
7291
+ if name == "build_card":
7292
+ return lambda *a, **k: {}
7293
+ return lambda *a, **k: None
7294
+
7295
+
7273
7296
  class Orchestrator:
7274
7297
  """8 步 FULL 货件流程编排器。"""
7275
7298
 
@@ -7279,7 +7302,10 @@ class Orchestrator:
7279
7302
  self.sel = selectors
7280
7303
  self.args = args or argparse.Namespace(no_lock=False)
7281
7304
  self.browser = build_browser_client(cfg, selectors) # KB-085:ZINIAO_MODE=selenium 用 SeleniumClient
7282
- self.feishu = FeishuClient(cfg)
7305
+ if getattr(self.args, "no_lip", False) or getattr(self.args, "record_json", None):
7306
+ self.feishu = NullFeishu()
7307
+ else:
7308
+ self.feishu = FeishuClient(cfg)
7283
7309
  self.state = RunState()
7284
7310
  # 2026-09-19:点 Generar etiquetas **之前**页面是否已有「Declara al menos」提示。
7285
7311
  # 点击前就有 = 残留文案(页面流转留下的旧校验),**不能**当作"checkbox 未生效"的证据;
@@ -9610,6 +9636,52 @@ class Orchestrator:
9610
9636
  "why": (verdict.get("lift") or {}).get("reason") or "",
9611
9637
  })
9612
9638
 
9639
+ async def _open_appointment_via_hub(self) -> None:
9640
+ """从列表/hub 进入 appointment-v2(新 UI 的两跳;已在预约页则 no-op)。
9641
+
9642
+ 只读判断 + 两次点击(Completar envío / Elige cómo…),不提交预约。
9643
+ """
9644
+ sid = str(self.state.shipment_id or "")
9645
+ if not sid:
9646
+ return
9647
+ try:
9648
+ url = self.browser.page.url or ""
9649
+ except Exception: # noqa: BLE001
9650
+ url = ""
9651
+ if "appointment" in url:
9652
+ return
9653
+ if "/hub" not in url:
9654
+ try:
9655
+ clicked = await self.browser.click_button("Completar envío", "button", step=4, wait_after=0)
9656
+ except Exception: # noqa: BLE001
9657
+ clicked = "notfound"
9658
+ if clicked != "clicked":
9659
+ # 可能已经停在 hub(步骤3正常收口)⇒ 不因找不到按钮而失败
9660
+ self._log(" ℹ️ 未命中「Completar envío」按钮(可能已在 hub)⇒ 继续找预约入口")
9661
+ else:
9662
+ self._log(" ✅ 已点「Completar envío」⇒ 进入 hub")
9663
+ for _ in range(10):
9664
+ try:
9665
+ if "/hub" in (self.browser.page.url or "") or "appointment" in (self.browser.page.url or ""):
9666
+ break
9667
+ except Exception: # noqa: BLE001
9668
+ pass
9669
+ await asyncio.sleep(1)
9670
+ try:
9671
+ await self.browser.page.wait_for_selector('a[href*="/appointment"]', timeout=20000)
9672
+ await self.browser.click_selector('a[href*="/appointment"]', step=4, wait_after=3)
9673
+ self._log(" ✅ 已点「Elige cómo y cuándo…」⇒ appointment-v2")
9674
+ except Exception as exc: # noqa: BLE001
9675
+ self._log(f" ⚠️ hub 预约入口未命中({type(exc).__name__})⇒ 回退直接 URL")
9676
+ await self.browser.visit_plan_page("appointment-v2", sid, step=4)
9677
+ for _ in range(15):
9678
+ try:
9679
+ if "appointment" in (self.browser.page.url or ""):
9680
+ return
9681
+ except Exception: # noqa: BLE001
9682
+ pass
9683
+ await asyncio.sleep(1)
9684
+
9613
9685
  async def step4_appointment(self) -> None:
9614
9686
  self._log("步骤4 货件预约时间")
9615
9687
  # 同店步骤4互斥锁(方案C,2026-08-14):**保守串行**,不是已验证的平台规则。
@@ -9650,6 +9722,10 @@ class Orchestrator:
9650
9722
  f"{(_cap.get('lift') or {}).get('reason')}")
9651
9723
  # 4a. 进入预约页(优先用货件号拼 URL,其次从 URL 提取 inbound ID)
9652
9724
  await self.browser.visit_plan_page("appointment-v2", self.state.shipment_id, step=4)
9725
+ # 4a1. 新 UI 兜底(2026-10-29):/appointment-v2 在「刚建单、尚未点 Completar envío」
9726
+ # 时会重定向回列表页(实测 80893392:列表 → Completar envío → hub → Elige cómo…)。
9727
+ # 直接 URL 只对已进入预约页的货件有效;这里补两跳,避免把“页面形态”误判成失败。
9728
+ await self._open_appointment_via_hub()
9653
9729
  # 4a2. 已有预约检测(2026-08-25 实测:预约成功后中断/重跑时,页面显示
9654
9730
  # 已预约状态(含 Cancelar reserva 按钮)而非空白表单——旧逻辑继续
9655
9731
  # 走选运输方式流程 → 日历区 Confirmar 找不到 → 误报失败。
@@ -9675,6 +9751,7 @@ class Orchestrator:
9675
9751
  self._log(f" 📅 改选更晚的日期:平台今天 +{date_offset} 天")
9676
9752
  await self.browser.visit_plan_page("appointment-v2",
9677
9753
  self.state.shipment_id, step=4)
9754
+ await self._open_appointment_via_hub()
9678
9755
  for attempt in range(3): # 同一日期内的时段重试
9679
9756
  if attempt > 0:
9680
9757
  self._log(f" 🔁 预约提交未生效,换下一时段重试(第 {attempt + 1}/3 次)")
@@ -11607,6 +11684,14 @@ class Orchestrator:
11607
11684
 
11608
11685
  async def step7_box_labels(self) -> None:
11609
11686
  self._log("步骤7 打印箱唛")
11687
+ # 续跑/并发:hub-v2 已确认箱唛下载完成时,不再重复生成/勾 fragile;
11688
+ # 80908724 实测:agent 已生成箱唛,orchestrator 再进 volumes 找不到 fragile checkbox。
11689
+ truth = await self._hub_truth()
11690
+ truth_items = truth.get("items") if isinstance(truth, dict) else {}
11691
+ if isinstance(truth_items, dict) and truth_items.get("boxLabels") is True:
11692
+ self._log(" 🛰️ hub 已确认箱唛下载完成,跳过步骤7重复生成")
11693
+ self._mark_done(7)
11694
+ return
11610
11695
  await self.browser.visit_plan_page("volumes", self.state.shipment_id, step=7)
11611
11696
  await asyncio.sleep(3)
11612
11697
  # 7.0 页面就绪验证:确认在箱数填写页(volumes)。8/18 并发实测 visit 后被
@@ -11660,6 +11745,12 @@ class Orchestrator:
11660
11745
  r = await self.browser.click_checkboxes(
11661
11746
  '[data-testid="checkbox-fragils-consolidation"]', step=7, wait_after=1.0)
11662
11747
  if not r.startswith("checked"):
11748
+ truth2 = await self._hub_truth()
11749
+ truth2_items = truth2.get("items") if isinstance(truth2, dict) else {}
11750
+ if isinstance(truth2_items, dict) and truth2_items.get("boxLabels") is True:
11751
+ self._log(" 🛰️ 箱唛已下载完成(hub 复核),跳过 fragile 收口")
11752
+ self._mark_done(7)
11753
+ return
11663
11754
  raise StepError(7, "selector_not_found", f"未找到 fragile checkbox ({r})",
11664
11755
  recovery_attempted=["fiber_onChange"])
11665
11756
  # 7g. 等加载旋转层消失再点 Continuar(箱唛生成后约5秒loading)
@@ -12870,7 +12961,7 @@ class Orchestrator:
12870
12961
  dry_run = mode == "dry-run"
12871
12962
  # ⑧:dry-run 期间所有字段写入在 update_field 里被拦(唯一写入口)
12872
12963
  try:
12873
- self.feishu.dry_run = bool(dry_run)
12964
+ self.feishu.dry_run = bool(dry_run) or bool(getattr(self.args, "no_lip", False) or getattr(self.args, "record_json", ""))
12874
12965
  except Exception: # noqa: BLE001
12875
12966
  pass
12876
12967
  record_ids = [r.strip() for r in str(self.args.records).split(",") if r.strip()]
@@ -13084,7 +13175,58 @@ class Orchestrator:
13084
13175
  # 定向重跑),店铺从记录字段取(store_name),无需 --store-name;若同时给
13085
13176
  # --store-name 且不匹配则报错提示;
13086
13177
  # --store-name:过滤查询第一条店铺名匹配的 Pending+就绪;缺省:第一条 Pending+就绪
13087
- if record_id:
13178
+ _record_json = getattr(self.args, "record_json", "") or ""
13179
+ if _record_json:
13180
+ try:
13181
+ _raw = json.loads(_record_json)
13182
+ except Exception as exc: # noqa: BLE001
13183
+ return {"status": "failed", "record_id": None, "shipment_id": None,
13184
+ "sku": None, "completed_steps": [], "failed_step": None,
13185
+ "error": {"step": None, "type": "business",
13186
+ "message": f"--record-json 解析失败: {exc}",
13187
+ "recovery_attempted": []},
13188
+ "files_uploaded": {}, "dry_run": mode == "dry-run",
13189
+ "write_steps": list(WRITE_STEPS)}
13190
+
13191
+ def _s(*keys):
13192
+ for _k in keys:
13193
+ if _raw.get(_k) not in (None, ""):
13194
+ return str(_raw.get(_k))
13195
+ return ""
13196
+
13197
+ rec = {
13198
+ "record_id": _s("record_id", "sourceRecordId") or "erp-record",
13199
+ "sku": _s("sku"),
13200
+ "qty": _s("qty", "quantity"),
13201
+ "box": _s("box", "boxCount"),
13202
+ "name": _s("name", "productName") or _s("sku"),
13203
+ "store_name": _s("store_name", "store") or (store_name or ""),
13204
+ "shipment_id": _s("shipment_id", "shipmentNo"),
13205
+ }
13206
+ _missing = [k for k in ("sku", "qty", "box", "store_name") if not rec[k]]
13207
+ if _missing:
13208
+ return {"status": "failed", "record_id": rec["record_id"], "shipment_id": None,
13209
+ "sku": rec["sku"], "completed_steps": [], "failed_step": None,
13210
+ "error": {"step": None, "type": "business",
13211
+ "message": f"--record-json 缺字段: {_missing}",
13212
+ "recovery_attempted": []},
13213
+ "files_uploaded": {}, "dry_run": mode == "dry-run",
13214
+ "write_steps": list(WRITE_STEPS)}
13215
+ if store_name and rec["store_name"] != store_name:
13216
+ raise StepError(0, "business",
13217
+ f"--record-json 的店铺 {rec['store_name']} "
13218
+ f"与 --store-name {store_name} 不匹配")
13219
+ self._log(f"🎯 ERP-only 记录 {rec['record_id']}(店铺:{rec['store_name']})")
13220
+ self.state.record_id = rec["record_id"]
13221
+ self.state.name = rec["name"]
13222
+ self.state.store_name = rec["store_name"]
13223
+ self.state.sku = rec["sku"]
13224
+ self.state.qty = rec["qty"]
13225
+ self.state.box = rec["box"]
13226
+ if rec["shipment_id"] and rec["shipment_id"] not in ("None", "null"):
13227
+ self.state.shipment_id = rec["shipment_id"]
13228
+ self._log(f" 已有货件号 {rec['shipment_id']},从步骤4继续")
13229
+ elif record_id:
13088
13230
  rec = self.feishu.get_record(record_id)
13089
13231
  if rec is None:
13090
13232
  self._log(f"记录 {record_id} 不存在或无法读取,本轮退出。")
@@ -13167,7 +13309,7 @@ class Orchestrator:
13167
13309
 
13168
13310
  dry_run = mode == "dry-run"
13169
13311
  try: # ⑧:dry-run 写闸门
13170
- self.feishu.dry_run = bool(dry_run)
13312
+ self.feishu.dry_run = bool(dry_run) or bool(getattr(self.args, "no_lip", False) or getattr(self.args, "record_json", ""))
13171
13313
  except Exception: # noqa: BLE001
13172
13314
  pass
13173
13315
  # 启动标记(状态=运行中)必须与打开店铺在同一 protected 区域:后续任何异常
@@ -13230,7 +13372,31 @@ class Orchestrator:
13230
13372
  return self._result("failed", failed_step=step_filter or 1, error=env_exc.to_dict(),
13231
13373
  step_summaries={}, dry_run=dry_run)
13232
13374
 
13233
- steps = [step_filter] if step_filter else list(range(1, 9))
13375
+ if self.state.shipment_id and not step_filter:
13376
+ # 已有货件号:先用 hub 只读状态判断真实进度;跳过 1-3 的重复打开/建单。
13377
+ # 实测:每次 full 都从步骤1 重开一遍,既慢又会让用户看到“明明有档期却重开”。
13378
+ try:
13379
+ _hub = await self.hub_status(self.state.shipment_id, step=0)
13380
+ _v = self._hub_verdict_of(_hub)
13381
+ self._log(f" 🛰️ 已有货件 #{self.state.shipment_id} hub 状态:"
13382
+ f"{_v.get('reason') or '不可用'}")
13383
+ if _v.get("operationally_complete"):
13384
+ self._log(" ✅ hub 判定已完成 ⇒ 不再重复步骤")
13385
+ for _s in range(1, 9):
13386
+ self._mark_done(_s)
13387
+ steps = []
13388
+ else:
13389
+ for _s in (1, 2, 3):
13390
+ self._mark_done(_s)
13391
+ steps = [4, 5, 6, 7, 8]
13392
+ except Exception as exc: # noqa: BLE001
13393
+ self._log(f" ⚠️ hub 状态探测失败,按已有货件从步骤4续跑: "
13394
+ f"{type(exc).__name__}: {exc}")
13395
+ for _s in (1, 2, 3):
13396
+ self._mark_done(_s)
13397
+ steps = [4, 5, 6, 7, 8]
13398
+ else:
13399
+ steps = [step_filter] if step_filter else list(range(1, 9))
13234
13400
  step_summaries: dict[int, Any] = {}
13235
13401
 
13236
13402
  result = await self._execute_steps(steps, allow_write, dry_run, step_summaries)
@@ -13821,6 +13987,8 @@ def build_parser() -> argparse.ArgumentParser:
13821
13987
  p.add_argument("--allow-write", action="store_true",
13822
13988
  help="批准写步骤(3/4/5/7/8)执行(默认拒绝)")
13823
13989
  p.add_argument("--record-id", help="指定飞书记录 ID 定向处理(店铺从记录字段读取,忽略 --store-name 取第一条逻辑;供并发调度/定向重跑)")
13990
+ p.add_argument("--record-json", help="ERP-only:合成记录 JSON(record_id/sourceRecordId、sku、qty/quantity、box/boxCount、name、store_name/store、shipment_id/shipmentNo)")
13991
+ p.add_argument("--no-lip", action="store_true", help="不读写 lip(Feishu 写操作 no-op);常与 --record-json 使用")
13824
13992
  p.add_argument("--sku", help="SKU(配合 --record-id 使用)")
13825
13993
  p.add_argument("--qty", help="数量(配合 --record-id 使用)")
13826
13994
  p.add_argument("--box", help="箱数(配合 --record-id 使用)")
@@ -2562,6 +2562,19 @@ FALLBACK_DATE_JS = r"""() => {
2562
2562
  }
2563
2563
  return {found: false, needFlip: true, mode: 'header', header: headerText};
2564
2564
  }
2565
+ // 目标月不在视图:若视图已是**更晚的月份**(目标 10/30、日历已翻到 11 月),
2566
+ // 直接选视图内第一个可用日(>= 目标);⛔ 不再为了“精确目标日”继续翻到 12 月。
2567
+ const viewMonth = viewMonths[0];
2568
+ const viewDate = new Date(viewYear, viewMonth, 1);
2569
+ const targetMonthDate = new Date(target.getFullYear(), target.getMonth(), 1);
2570
+ if (viewDate > targetMonthDate) {
2571
+ for (let i = 0; i < n; i++) {
2572
+ const t = (days[i].textContent || '').trim();
2573
+ if (/^\d+$/.test(t) && !days[i].classList.contains('day--disabled')) {
2574
+ return {found: true, idx: i, mode: 'next_available', header: headerText};
2575
+ }
2576
+ }
2577
+ }
2565
2578
  return {found: false, needFlip: true, mode: 'header', header: headerText};
2566
2579
  }
2567
2580
  // header 不可靠:降级为「目标日数字 + 视图内该数字后的第一个可用格」(last resort)
@@ -9627,6 +9640,52 @@ class Orchestrator:
9627
9640
  "why": (verdict.get("lift") or {}).get("reason") or "",
9628
9641
  })
9629
9642
 
9643
+ async def _open_appointment_via_hub(self) -> None:
9644
+ """从列表/hub 进入 appointment-v2(新 UI 的两跳;已在预约页则 no-op)。
9645
+
9646
+ 只读判断 + 两次点击(Completar envío / Elige cómo…),不提交预约。
9647
+ """
9648
+ sid = str(self.state.shipment_id or "")
9649
+ if not sid:
9650
+ return
9651
+ try:
9652
+ url = self.browser.page.url or ""
9653
+ except Exception: # noqa: BLE001
9654
+ url = ""
9655
+ if "appointment" in url:
9656
+ return
9657
+ if "/hub" not in url:
9658
+ try:
9659
+ clicked = await self.browser.click_button("Completar envío", "button", step=4, wait_after=0)
9660
+ except Exception: # noqa: BLE001
9661
+ clicked = "notfound"
9662
+ if clicked != "clicked":
9663
+ # 可能已经停在 hub(步骤3正常收口)⇒ 不因找不到按钮而失败
9664
+ self._log(" ℹ️ 未命中「Completar envío」按钮(可能已在 hub)⇒ 继续找预约入口")
9665
+ else:
9666
+ self._log(" ✅ 已点「Completar envío」⇒ 进入 hub")
9667
+ for _ in range(10):
9668
+ try:
9669
+ if "/hub" in (self.browser.page.url or "") or "appointment" in (self.browser.page.url or ""):
9670
+ break
9671
+ except Exception: # noqa: BLE001
9672
+ pass
9673
+ await asyncio.sleep(1)
9674
+ try:
9675
+ await self.browser.page.wait_for_selector('a[href*="/appointment"]', timeout=20000)
9676
+ await self.browser.click_selector('a[href*="/appointment"]', step=4, wait_after=3)
9677
+ self._log(" ✅ 已点「Elige cómo y cuándo…」⇒ appointment-v2")
9678
+ except Exception as exc: # noqa: BLE001
9679
+ self._log(f" ⚠️ hub 预约入口未命中({type(exc).__name__})⇒ 回退直接 URL")
9680
+ await self.browser.visit_plan_page("appointment-v2", sid, step=4)
9681
+ for _ in range(15):
9682
+ try:
9683
+ if "appointment" in (self.browser.page.url or ""):
9684
+ return
9685
+ except Exception: # noqa: BLE001
9686
+ pass
9687
+ await asyncio.sleep(1)
9688
+
9630
9689
  async def step4_appointment(self) -> None:
9631
9690
  self._log("步骤4 货件预约时间")
9632
9691
  # 同店步骤4互斥锁(方案C,2026-08-14):**保守串行**,不是已验证的平台规则。
@@ -9667,6 +9726,10 @@ class Orchestrator:
9667
9726
  f"{(_cap.get('lift') or {}).get('reason')}")
9668
9727
  # 4a. 进入预约页(优先用货件号拼 URL,其次从 URL 提取 inbound ID)
9669
9728
  await self.browser.visit_plan_page("appointment-v2", self.state.shipment_id, step=4)
9729
+ # 4a1. 新 UI 兜底(2026-10-29):/appointment-v2 在「刚建单、尚未点 Completar envío」
9730
+ # 时会重定向回列表页(实测 80893392:列表 → Completar envío → hub → Elige cómo…)。
9731
+ # 直接 URL 只对已进入预约页的货件有效;这里补两跳,避免把“页面形态”误判成失败。
9732
+ await self._open_appointment_via_hub()
9670
9733
  # 4a2. 已有预约检测(2026-08-25 实测:预约成功后中断/重跑时,页面显示
9671
9734
  # 已预约状态(含 Cancelar reserva 按钮)而非空白表单——旧逻辑继续
9672
9735
  # 走选运输方式流程 → 日历区 Confirmar 找不到 → 误报失败。
@@ -9692,6 +9755,7 @@ class Orchestrator:
9692
9755
  self._log(f" 📅 改选更晚的日期:平台今天 +{date_offset} 天")
9693
9756
  await self.browser.visit_plan_page("appointment-v2",
9694
9757
  self.state.shipment_id, step=4)
9758
+ await self._open_appointment_via_hub()
9695
9759
  for attempt in range(3): # 同一日期内的时段重试
9696
9760
  if attempt > 0:
9697
9761
  self._log(f" 🔁 预约提交未生效,换下一时段重试(第 {attempt + 1}/3 次)")
@@ -13247,7 +13311,31 @@ class Orchestrator:
13247
13311
  return self._result("failed", failed_step=step_filter or 1, error=env_exc.to_dict(),
13248
13312
  step_summaries={}, dry_run=dry_run)
13249
13313
 
13250
- steps = [step_filter] if step_filter else list(range(1, 9))
13314
+ if self.state.shipment_id and not step_filter:
13315
+ # 已有货件号:先用 hub 只读状态判断真实进度;跳过 1-3 的重复打开/建单。
13316
+ # 实测:每次 full 都从步骤1 重开一遍,既慢又会让用户看到“明明有档期却重开”。
13317
+ try:
13318
+ _hub = await self.hub_status(self.state.shipment_id, step=0)
13319
+ _v = self._hub_verdict_of(_hub)
13320
+ self._log(f" 🛰️ 已有货件 #{self.state.shipment_id} hub 状态:"
13321
+ f"{_v.get('reason') or '不可用'}")
13322
+ if _v.get("operationally_complete"):
13323
+ self._log(" ✅ hub 判定已完成 ⇒ 不再重复步骤")
13324
+ for _s in range(1, 9):
13325
+ self._mark_done(_s)
13326
+ steps = []
13327
+ else:
13328
+ for _s in (1, 2, 3):
13329
+ self._mark_done(_s)
13330
+ steps = [4, 5, 6, 7, 8]
13331
+ except Exception as exc: # noqa: BLE001
13332
+ self._log(f" ⚠️ hub 状态探测失败,按已有货件从步骤4续跑: "
13333
+ f"{type(exc).__name__}: {exc}")
13334
+ for _s in (1, 2, 3):
13335
+ self._mark_done(_s)
13336
+ steps = [4, 5, 6, 7, 8]
13337
+ else:
13338
+ steps = [step_filter] if step_filter else list(range(1, 9))
13251
13339
  step_summaries: dict[int, Any] = {}
13252
13340
 
13253
13341
  result = await self._execute_steps(steps, allow_write, dry_run, step_summaries)
@@ -0,0 +1,18 @@
1
+ #!/bin/bash
2
+ # 发布 0.8.0-rc.4 / desktop 0.2.2 / launcher 0.1.17
3
+ # 前置:npm login(有 @whyshu publish 权限);本脚本不会登录/读取 token。
4
+ set -euo pipefail
5
+ DIR="${1:-/tmp/argent-release-0.8.0-rc.4}"
6
+ cd "$DIR"
7
+ shasum -a 256 -c <<'SUMS'
8
+ 892652d5e43deb1cba6539dc81b3ed2f0cf4e8f081d70a084b40796041a9dbaf whyshu-argent-engine-0.8.0-rc.4.tgz
9
+ 9333fa9255cd93ef5821d58858a63172374b63f8071dd27f723521b14cdfe826 whyshu-argent-desktop-0.2.2.tgz
10
+ 3a0501f16882535208a7f56ef49c4e57b3fccc59661d8facf61b323d3270cec5 whyshu-argent-0.1.17.tgz
11
+ SUMS
12
+ npm whoami >/dev/null
13
+ npm publish whyshu-argent-engine-0.8.0-rc.4.tgz --access public
14
+ npm publish whyshu-argent-desktop-0.2.2.tgz --access public
15
+ npm publish whyshu-argent-0.1.17.tgz --access public
16
+ npm view @whyshu/argent-engine version
17
+ npm view @whyshu/argent-desktop version
18
+ npm view @whyshu/argent version
@@ -50,9 +50,8 @@ def _default_orchestrator() -> Path:
50
50
  profile_home / "scripts/orchestrator.py",
51
51
  profile_home / "roles/ml-fulfillment/scripts/orchestrator.py",
52
52
  profile_home / "skills/mercadolibre/ml-fulfillment-sop/scripts/fulfillment_orchestrator.py",
53
- Path.home() / "Code/argent-ml-seller/scripts/orchestrator.py",
54
- Path.home() / "Code/argent-ml/roles/ml-fulfillment/scripts/orchestrator.py",
55
- Path.home() / "Code/argent-ml/skills/mercadolibre/ml-fulfillment-sop/scripts/fulfillment_orchestrator.py",
53
+ # 2026-10-29:legacy 仓(argent-ml / argent-ml-seller)已归档;只认当前主线仓
54
+ Path.home() / "Code/argent-dsh/scripts/orchestrator.py",
56
55
  ]
57
56
  for c in candidates:
58
57
  if c.is_file():