@whyshu/argent-engine 0.7.8 → 0.8.0-rc.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/MANIFEST.json +67 -45
  2. package/engine/VERSION +1 -1
  3. package/engine/core/contracts/argent.contracts.json +2 -2
  4. package/engine/core/contracts/verbs.schema.json +64 -1
  5. package/engine/core/lib/argent-datadir.mjs +6 -0
  6. package/engine/core/lib/contract.mjs +30 -0
  7. package/engine/core/mcp/server.mjs +171 -2
  8. package/engine/scripts/appointment-create.mjs +2 -2
  9. package/engine/scripts/argent-doctor.mjs +44 -3
  10. package/engine/scripts/argent-machine-setup.mjs +3 -1
  11. package/engine/scripts/argent-runner.mjs +4 -2
  12. package/engine/scripts/argent-schedule.mjs +6 -0
  13. package/engine/scripts/base-bootstrap.sh +0 -0
  14. package/engine/scripts/billing-mode-daily.sh +0 -0
  15. package/engine/scripts/build-doc-index.mjs +68 -0
  16. package/engine/scripts/build-engine-package.mjs +18 -3
  17. package/engine/scripts/capability-packs.lock.json +66 -65
  18. package/engine/scripts/check-argent-desktop.mjs +91 -0
  19. package/engine/scripts/check-billing-mode.sh +0 -0
  20. package/engine/scripts/check-docs-drift.mjs +51 -4
  21. package/engine/scripts/check-dsh-web-expose.sh +0 -0
  22. package/engine/scripts/ci-run.sh +2 -2
  23. package/engine/scripts/customer-readiness.sh +0 -0
  24. package/engine/scripts/daily-report-run.sh +68 -0
  25. package/engine/scripts/daily-report-status.mjs +130 -0
  26. package/engine/scripts/daily-report-timer-plist.sh +89 -0
  27. package/engine/scripts/daily-report-timers.sh +199 -0
  28. package/engine/scripts/daily-report.mjs +136 -7
  29. package/engine/scripts/daily-report.sh +0 -0
  30. package/engine/scripts/desktop-trial.sh +0 -0
  31. package/engine/scripts/dev-window.sh +0 -0
  32. package/engine/scripts/doc-status.mjs +212 -0
  33. package/engine/scripts/drill-clean-room.sh +0 -0
  34. package/engine/scripts/drill-handover.sh +0 -0
  35. package/engine/scripts/dsh-backup-scope.sh +0 -0
  36. package/engine/scripts/dsh-overlay-pin.sh +0 -0
  37. package/engine/scripts/dsh-release-watch-daily.sh +0 -0
  38. package/engine/scripts/dsh-remote-check.sh +0 -0
  39. package/engine/scripts/dsh-restart.sh +0 -0
  40. package/engine/scripts/dsh-restore.sh +0 -0
  41. package/engine/scripts/dsh-url.sh +0 -0
  42. package/engine/scripts/erp_invoice_shadow.py +62 -0
  43. package/engine/scripts/erp_invoice_writeback.py +93 -0
  44. package/engine/scripts/flow-requirements.json +4 -4
  45. package/engine/scripts/flow-session-retention.mjs +2 -1
  46. package/engine/scripts/flow-timers-plist.sh +0 -0
  47. package/engine/scripts/flow-timers.sh +11 -0
  48. package/engine/scripts/flow-trigger-wake.mjs +6 -3
  49. package/engine/scripts/flow-trigger.sh +0 -0
  50. package/engine/scripts/flow_config.py +16 -0
  51. package/engine/scripts/flow_failure.py +3 -0
  52. package/engine/scripts/flow_source.py +10 -1
  53. package/engine/scripts/flow_sources/__init__.py +1 -0
  54. package/engine/scripts/flow_sources/erp.py +54 -0
  55. package/engine/scripts/fulfillment_sites.py +46 -0
  56. package/engine/scripts/gen-agent-bundles.mjs +1 -1
  57. package/engine/scripts/init-ml.sh +0 -0
  58. package/engine/scripts/invoice-table.sh +0 -0
  59. package/engine/scripts/invoice_lip_runner.py +43 -0
  60. package/engine/scripts/invoice_runner.py +14 -5
  61. package/engine/scripts/invoice_stageb.py +21 -4
  62. package/engine/scripts/lib/argent-datadir.sh +0 -0
  63. package/engine/scripts/lib/argent_datadir.py +5 -0
  64. package/engine/scripts/lib/daily-report-status.mjs +227 -0
  65. package/engine/scripts/lib/plugin-packages.mjs +3 -0
  66. package/engine/scripts/lib/repo-root.sh +0 -0
  67. package/engine/scripts/migrate-skills.sh +0 -0
  68. package/engine/scripts/ml-ads.mjs +181 -0
  69. package/engine/scripts/ml-oauth-setup.mjs +1 -1
  70. package/engine/scripts/ml_hub_status.py +3 -3
  71. package/engine/scripts/npm-publish-argent.sh +0 -0
  72. package/engine/scripts/orchestrator.py +228 -31
  73. package/engine/scripts/orchestrator_br.py +14412 -0
  74. package/engine/scripts/patches/retire-check.sh +0 -0
  75. package/engine/scripts/poll-fulfillment.sh +0 -0
  76. package/engine/scripts/poll-invoice.sh +0 -0
  77. package/engine/scripts/provider-select.sh +0 -0
  78. package/engine/scripts/provider-switch.sh +0 -0
  79. package/engine/scripts/python-runtime.sh +0 -0
  80. package/engine/scripts/query_runner.py +2 -3
  81. package/engine/scripts/release-argent.sh +0 -0
  82. package/engine/scripts/release-gate-0.8.mjs +81 -0
  83. package/engine/scripts/run-tests.sh +0 -0
  84. package/engine/scripts/s1-audit.mjs +4 -1
  85. package/engine/scripts/session-handoff.mjs +2 -1
  86. package/engine/scripts/setup.sh +0 -0
  87. package/engine/scripts/skuflow_invoice_runner.py +164 -0
  88. package/engine/scripts/sync-plugins.sh +0 -0
  89. package/engine/scripts/sync-presets.sh +0 -0
  90. package/engine/scripts/sync-scripts.sh +0 -0
  91. package/engine/scripts/telemetry.py +6 -2
  92. package/engine/scripts/usage-anchor.sh +0 -0
  93. package/engine/scripts/vertical-lint.mjs +19 -0
  94. package/engine/scripts/wenyao-browser.sh +0 -0
  95. package/engine/scripts/wenyao-login.sh +0 -0
  96. package/engine/scripts/xzh-browser.sh +2 -1
  97. package/engine/scripts/xzh_browser.py +1 -1
  98. package/engine/scripts/ziniao-auth-probe.sh +67 -18
  99. package/engine/scripts/ziniao-keepalive.sh +0 -0
  100. package/engine/scripts/ziniao-post-upgrade-check.sh +0 -0
  101. package/engine/scripts/ziniao-windows.sh +0 -0
  102. package/engine/skills/ml-fulfillment-sop/SKILL.md +29 -0
  103. package/engine/skills/ml-fulfillment-sop/references/agentic-runtime-v3.md +39 -0
  104. package/engine/skills/ml-fulfillment-sop/scripts/poll-and-execute.sh +0 -0
  105. package/engine/skills/ml-store-daily-report/SKILL.md +68 -0
  106. package/engine/tools/agentic/README.md +95 -0
  107. package/engine/tools/agentic/mcp_server.py +212 -0
  108. package/engine/tools/agentic/ml_agent_tools.py +602 -0
  109. package/engine/version.mjs +1 -1
  110. package/engine/verticals/_engine-words.baseline.txt +16 -2
  111. package/engine/verticals/mercadolibre/brazil-full-sop.json +47 -0
  112. package/engine/verticals/mercadolibre/flows.json +15 -5
  113. package/engine/verticals/mercadolibre/prompts/full.failure.md +39 -1
  114. package/package.json +1 -1
@@ -1636,10 +1636,19 @@ def wd_update_core(cfg: Config, creds: dict[str, str]) -> dict[str, Any]:
1636
1636
  return _wd_check(last_resp, "updateCore")
1637
1637
 
1638
1638
 
1639
+ _EXTRA_WD_STORES_WARNED: set[str] = set()
1640
+
1641
+
1639
1642
  def wd_list_stores(cfg: Config, creds: dict[str, str]) -> list[dict[str, Any]]:
1640
1643
  """getBrowserList → 与 stores.json 三方一致校验(storeName/storeId 逐项比对)。
1641
1644
 
1642
- 不一致 → 抛 WebDriverError 并列出差异(供人工核对/回退 bridge)。
1645
+ **只对 stores.json 登记的店做严格校验**:缺店 / storeId 不一致 ⇒ 抛 WebDriverError
1646
+ (说明客户端那边改名/删店/重建过,必须人工对齐)。
1647
+
1648
+ 客户端里**多出来**的店(Shopee/TikTok 等不归本流程管的店、或人工新建还没登记的店)是
1649
+ **正常现象,只 warn 不抛错**(2026-11-01 客户机实测:多 3 个非本流程店铺 ⇒ 授权探针把
1650
+ "名单不一致"误判成"授权链路不可用",每 12h 推两条遥测告警。改名场景仍会由"缺店"
1651
+ 一侧判红,所以这条降级不会放过真故障)。
1643
1652
  """
1644
1653
  resp = _wd_check(_wd_call(cfg.ziniao_wd_port, "getBrowserList", _wd_auth_payload(creds)),
1645
1654
  "getBrowserList")
@@ -1659,9 +1668,17 @@ def wd_list_stores(cfg: Config, creds: dict[str, str]) -> list[dict[str, Any]]:
1659
1668
  if str(wd.get("browserId")) != str(info.get("store_id")):
1660
1669
  diffs.append(f"店铺「{env_name}」storeId 不一致: stores.json={info.get('store_id')} "
1661
1670
  f"WebDriver={wd.get('browserId')}")
1662
- for s in wd_stores:
1663
- if s.get("browserName") not in stores:
1664
- diffs.append(f"WebDriver 有店铺「{s.get('browserName')}」但 stores.json 无")
1671
+ extra = [str(s.get("browserName") or "") for s in wd_stores
1672
+ if s.get("browserName") not in stores]
1673
+ if extra:
1674
+ # 每个进程只吵一次:这是**正常**形态,不是故障(每开一个店都会走到这里)
1675
+ fresh = [n for n in extra if n not in _EXTRA_WD_STORES_WARNED]
1676
+ if fresh:
1677
+ _EXTRA_WD_STORES_WARNED.update(fresh)
1678
+ print(f"⚠️ 客户端有 {len(extra)} 个店铺不在 stores.json(不纳入本流程,忽略):"
1679
+ + "、".join(extra)
1680
+ + "|若其中确有本流程的店 ⇒ 补 stores.json(否则该店永远不会被调度)",
1681
+ file=sys.stderr, flush=True)
1665
1682
  if diffs:
1666
1683
  raise WebDriverError("getBrowserList 三方校验", status_code=None,
1667
1684
  err=";".join(diffs), extra="请核对 stores.json 与紫鸟店铺列表")
@@ -2320,6 +2337,11 @@ BOX_LABEL_DL_ROUNDS = int(os.environ.get("BOX_LABEL_DL_ROUNDS", "") or 3)
2320
2337
  # 现在:等待按"业务信号"轮询 + 分层预算,超时才落终态;预算可调(客户机也能按现场调)。
2321
2338
  NAV_TIMEOUT_SEC = float(os.environ.get("NAV_TIMEOUT_SEC", "") or 90) # page.goto 单次
2322
2339
  URL_TRANSITION_SEC = float(os.environ.get("URL_TRANSITION_SEC", "") or 120) # 等跳转(如 hub-v2)
2340
+ # 2026-10-24:平台把 hub 落地页从 `/hub-v2` 改为 `/hub`;历史判据只认 `hub-v2`
2341
+ # ⇒ 写操作明明生效也判失败(FULL 步骤4/5 假失败、误取消预约)。统一用正则接受两种形态。
2342
+ HUB_URL_RE = re.compile(r"/inbounds/\d+/hub(?:-v2)?(?:[/?#]|$)")
2343
+ def is_hub_url(url: str) -> bool:
2344
+ return bool(HUB_URL_RE.search(str(url or "")))
2323
2345
  SLOW_GRACE_SEC = float(os.environ.get("SLOW_GRACE_SEC", "") or 60) # 慢渲染宽限(再等一轮)
2324
2346
  # 错误弹窗(Algo salió mal)自愈的**退避**(2026-09-23):
2325
2347
  # 旧行为:失败→重载→固定等 8s→再来一次,两次不成即判失败 ⇒ 平台慢时等于"连打同一页面"
@@ -2540,6 +2562,19 @@ FALLBACK_DATE_JS = r"""() => {
2540
2562
  }
2541
2563
  return {found: false, needFlip: true, mode: 'header', header: headerText};
2542
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
+ }
2543
2578
  return {found: false, needFlip: true, mode: 'header', header: headerText};
2544
2579
  }
2545
2580
  // header 不可靠:降级为「目标日数字 + 视图内该数字后的第一个可用格」(last resort)
@@ -7265,6 +7300,16 @@ class RunState:
7265
7300
  terminal_evidence: str = ""
7266
7301
 
7267
7302
 
7303
+ class NullFeishu:
7304
+ """ERP-only 记录源:不读写 lip,所有 Feishu 写操作 no-op。"""
7305
+ dry_run = True
7306
+
7307
+ def __getattr__(self, name):
7308
+ if name == "build_card":
7309
+ return lambda *a, **k: {}
7310
+ return lambda *a, **k: None
7311
+
7312
+
7268
7313
  class Orchestrator:
7269
7314
  """8 步 FULL 货件流程编排器。"""
7270
7315
 
@@ -7274,7 +7319,10 @@ class Orchestrator:
7274
7319
  self.sel = selectors
7275
7320
  self.args = args or argparse.Namespace(no_lock=False)
7276
7321
  self.browser = build_browser_client(cfg, selectors) # KB-085:ZINIAO_MODE=selenium 用 SeleniumClient
7277
- self.feishu = FeishuClient(cfg)
7322
+ if getattr(self.args, "no_lip", False) or getattr(self.args, "record_json", None):
7323
+ self.feishu = NullFeishu()
7324
+ else:
7325
+ self.feishu = FeishuClient(cfg)
7278
7326
  self.state = RunState()
7279
7327
  # 2026-09-19:点 Generar etiquetas **之前**页面是否已有「Declara al menos」提示。
7280
7328
  # 点击前就有 = 残留文案(页面流转留下的旧校验),**不能**当作"checkbox 未生效"的证据;
@@ -7455,7 +7503,7 @@ class Orchestrator:
7455
7503
  """**唯一入口**:把 `FULL状态` 置为「已完成」。
7456
7504
 
7457
7505
  2026-10-16:原先只有 `_finalize_ticket_complete`(引擎自己跑完)能置位;现在
7458
- 「运营手动完成(hub-v2 实测)」也要置位(用户口径「都要」)⇒ 抽出本入口,两条路径
7506
+ 「已完成(hub-v2 实测;来源未声明)」也要置位(用户口径「都要」)⇒ 抽出本入口,两条路径
7459
7507
  **都走这里**,保持"表状态只有一个写点"的不变量(回归见 ticket-completion-criteria /
7460
7508
  step-progress-realtime 的 AST 断言)。
7461
7509
  """
@@ -7881,7 +7929,7 @@ class Orchestrator:
7881
7929
  "shipment_id": "", "url_inbound": "", "probe_ok": False}
7882
7930
 
7883
7931
  # 需求 1a:hub 判定的**运营手动完成**在表里固定用这句话(运维与角色都按它对齐口径)
7884
- HUB_MANUAL_NOTE = "识别为运营手动完成(依据 hub-v2 实测)"
7932
+ HUB_MANUAL_NOTE = "识别为已完成(依据 hub-v2 实测;来源未声明)"
7885
7933
 
7886
7934
  def _hub_manual_complete(self, verdict: dict[str, Any], *, status: str = "") -> dict[str, Any]:
7887
7935
  """hub-v2 判定「预约已取消 ∧ 产品标签已下载 ∧ 箱唛已下载」⇒ **认定为已完成**。
@@ -7890,7 +7938,7 @@ class Orchestrator:
7890
7938
  三个派生结论**都必须是 `True`**(`None` 一律不算);只要有一个判不了 ⇒ 不是完成。
7891
7939
 
7892
7940
  ## 写什么 / ⛔ 不写什么(用户口径)
7893
- - **写**:`FULL备注` ← 「识别为运营手动完成(依据 hub-v2 实测):<逐项>」(同源同文,
7941
+ - **写**:`FULL备注` ← 「识别为已完成(依据 hub-v2 实测;来源未声明):<逐项>」(同源同文,
7894
7942
  与 `--mode hub-status` 打印、与 `failures.jsonl#hub_status` 完全一致);
7895
7943
  `当前步骤` ← **「全部完成」**(2026-10-16 用户口径:表口径与"引擎自己跑完"一致);`就绪=false`(消费掉拾取位)。
7896
7944
  **`FULL状态` ← 已完成**(2026-10-16 用户口径「都要」:认定即置位,否则票一直挂在"失败"里,
@@ -9299,7 +9347,7 @@ class Orchestrator:
9299
9347
  while time.time() < deadline:
9300
9348
  rounds += 1
9301
9349
  try:
9302
- if "hub-v2" in (self.browser.page.url or ""):
9350
+ if is_hub_url(self.browser.page.url or ""):
9303
9351
  break
9304
9352
  except Exception:
9305
9353
  pass
@@ -9605,6 +9653,52 @@ class Orchestrator:
9605
9653
  "why": (verdict.get("lift") or {}).get("reason") or "",
9606
9654
  })
9607
9655
 
9656
+ async def _open_appointment_via_hub(self) -> None:
9657
+ """从列表/hub 进入 appointment-v2(新 UI 的两跳;已在预约页则 no-op)。
9658
+
9659
+ 只读判断 + 两次点击(Completar envío / Elige cómo…),不提交预约。
9660
+ """
9661
+ sid = str(self.state.shipment_id or "")
9662
+ if not sid:
9663
+ return
9664
+ try:
9665
+ url = self.browser.page.url or ""
9666
+ except Exception: # noqa: BLE001
9667
+ url = ""
9668
+ if "appointment" in url:
9669
+ return
9670
+ if "/hub" not in url:
9671
+ try:
9672
+ clicked = await self.browser.click_button("Completar envío", "button", step=4, wait_after=0)
9673
+ except Exception: # noqa: BLE001
9674
+ clicked = "notfound"
9675
+ if clicked != "clicked":
9676
+ # 可能已经停在 hub(步骤3正常收口)⇒ 不因找不到按钮而失败
9677
+ self._log(" ℹ️ 未命中「Completar envío」按钮(可能已在 hub)⇒ 继续找预约入口")
9678
+ else:
9679
+ self._log(" ✅ 已点「Completar envío」⇒ 进入 hub")
9680
+ for _ in range(10):
9681
+ try:
9682
+ if "/hub" in (self.browser.page.url or "") or "appointment" in (self.browser.page.url or ""):
9683
+ break
9684
+ except Exception: # noqa: BLE001
9685
+ pass
9686
+ await asyncio.sleep(1)
9687
+ try:
9688
+ await self.browser.page.wait_for_selector('a[href*="/appointment"]', timeout=20000)
9689
+ await self.browser.click_selector('a[href*="/appointment"]', step=4, wait_after=3)
9690
+ self._log(" ✅ 已点「Elige cómo y cuándo…」⇒ appointment-v2")
9691
+ except Exception as exc: # noqa: BLE001
9692
+ self._log(f" ⚠️ hub 预约入口未命中({type(exc).__name__})⇒ 回退直接 URL")
9693
+ await self.browser.visit_plan_page("appointment-v2", sid, step=4)
9694
+ for _ in range(15):
9695
+ try:
9696
+ if "appointment" in (self.browser.page.url or ""):
9697
+ return
9698
+ except Exception: # noqa: BLE001
9699
+ pass
9700
+ await asyncio.sleep(1)
9701
+
9608
9702
  async def step4_appointment(self) -> None:
9609
9703
  self._log("步骤4 货件预约时间")
9610
9704
  # 同店步骤4互斥锁(方案C,2026-08-14):**保守串行**,不是已验证的平台规则。
@@ -9645,6 +9739,10 @@ class Orchestrator:
9645
9739
  f"{(_cap.get('lift') or {}).get('reason')}")
9646
9740
  # 4a. 进入预约页(优先用货件号拼 URL,其次从 URL 提取 inbound ID)
9647
9741
  await self.browser.visit_plan_page("appointment-v2", self.state.shipment_id, step=4)
9742
+ # 4a1. 新 UI 兜底(2026-10-29):/appointment-v2 在「刚建单、尚未点 Completar envío」
9743
+ # 时会重定向回列表页(实测 80893392:列表 → Completar envío → hub → Elige cómo…)。
9744
+ # 直接 URL 只对已进入预约页的货件有效;这里补两跳,避免把“页面形态”误判成失败。
9745
+ await self._open_appointment_via_hub()
9648
9746
  # 4a2. 已有预约检测(2026-08-25 实测:预约成功后中断/重跑时,页面显示
9649
9747
  # 已预约状态(含 Cancelar reserva 按钮)而非空白表单——旧逻辑继续
9650
9748
  # 走选运输方式流程 → 日历区 Confirmar 找不到 → 误报失败。
@@ -9670,6 +9768,7 @@ class Orchestrator:
9670
9768
  self._log(f" 📅 改选更晚的日期:平台今天 +{date_offset} 天")
9671
9769
  await self.browser.visit_plan_page("appointment-v2",
9672
9770
  self.state.shipment_id, step=4)
9771
+ await self._open_appointment_via_hub()
9673
9772
  for attempt in range(3): # 同一日期内的时段重试
9674
9773
  if attempt > 0:
9675
9774
  self._log(f" 🔁 预约提交未生效,换下一时段重试(第 {attempt + 1}/3 次)")
@@ -10094,7 +10193,7 @@ class Orchestrator:
10094
10193
  for _ in range(38): # 0.4s × 38 ≈ 15s
10095
10194
  try:
10096
10195
  url = self.browser.page.url or ""
10097
- if "hub-v2" in url:
10196
+ if is_hub_url(url):
10098
10197
  submit_ok = True
10099
10198
  break
10100
10199
  hint = await self.browser.page.evaluate(
@@ -10754,7 +10853,7 @@ class Orchestrator:
10754
10853
  self._log(" ✅ 已确认重新贴标弹窗")
10755
10854
  return True
10756
10855
  # 无弹窗时快速返回:正常提交路径已跳转 hub-v2 → 零额外延迟
10757
- if "hub-v2" in (self.browser.page.url or ""):
10856
+ if is_hub_url(self.browser.page.url or ""):
10758
10857
  return False
10759
10858
  except Exception:
10760
10859
  return False
@@ -10877,12 +10976,24 @@ class Orchestrator:
10877
10976
  recovery_attempted=["checkbox_mouseevent"])
10878
10977
  await self.browser.click_with_fallback(5, "confirm_btn", "Confirmar")
10879
10978
  await asyncio.sleep(3)
10880
- # 提交后应跳转 hub-v2;未跳转说明包装确认未提交
10979
+ # 提交后应跳转 hub(平台 2026-10 已把 /hub-v2 改为 /hub);URL 判据只作快速路径。
10980
+ # 失败前必须用只读 hub 探针核验「包装确认」是否真的完成,平台慢渲染不得再判假失败。
10881
10981
  try:
10882
- await self.browser.page.wait_for_url("**/hub-v2**", timeout=15000)
10982
+ await self.browser.page.wait_for_url(
10983
+ re.compile(r".*/inbounds/\d+/hub(?:-v2)?(?:[?#].*)?$"),
10984
+ timeout=int(URL_TRANSITION_SEC * 1000),
10985
+ )
10883
10986
  except Exception:
10884
- raise StepError(5, "business", "包装确认后未跳转 hub-v2,确认可能未提交",
10885
- recovery_attempted=["check_procedures_state"])
10987
+ hub = await self._hub_truth(navigate=False, step=5)
10988
+ items = (hub or {}).get("items") or []
10989
+ packaging_done = any(
10990
+ str((it or {}).get("key") or "") == "packaging" and (it or {}).get("done") is True
10991
+ for it in items
10992
+ )
10993
+ if not packaging_done:
10994
+ raise StepError(5, "business", "包装确认后未到 hub / 未确认包装完成",
10995
+ recovery_attempted=["check_procedures_state", "hub_probe"])
10996
+ self._log(" ✅ 包装确认已由 hub 只读探针核验为完成(URL 判据未命中,按 effective 继续)")
10886
10997
  self._mark_done(5)
10887
10998
  if self.state.record_id:
10888
10999
  self.feishu.send_message(f"✅ 步骤5完成: 包装确认 - {self.state.sku}")
@@ -11590,6 +11701,14 @@ class Orchestrator:
11590
11701
 
11591
11702
  async def step7_box_labels(self) -> None:
11592
11703
  self._log("步骤7 打印箱唛")
11704
+ # 续跑/并发:hub-v2 已确认箱唛下载完成时,不再重复生成/勾 fragile;
11705
+ # 80908724 实测:agent 已生成箱唛,orchestrator 再进 volumes 找不到 fragile checkbox。
11706
+ truth = await self._hub_truth()
11707
+ truth_items = truth.get("items") if isinstance(truth, dict) else {}
11708
+ if isinstance(truth_items, dict) and truth_items.get("boxLabels") is True:
11709
+ self._log(" 🛰️ hub 已确认箱唛下载完成,跳过步骤7重复生成")
11710
+ self._mark_done(7)
11711
+ return
11593
11712
  await self.browser.visit_plan_page("volumes", self.state.shipment_id, step=7)
11594
11713
  await asyncio.sleep(3)
11595
11714
  # 7.0 页面就绪验证:确认在箱数填写页(volumes)。8/18 并发实测 visit 后被
@@ -11643,6 +11762,12 @@ class Orchestrator:
11643
11762
  r = await self.browser.click_checkboxes(
11644
11763
  '[data-testid="checkbox-fragils-consolidation"]', step=7, wait_after=1.0)
11645
11764
  if not r.startswith("checked"):
11765
+ truth2 = await self._hub_truth()
11766
+ truth2_items = truth2.get("items") if isinstance(truth2, dict) else {}
11767
+ if isinstance(truth2_items, dict) and truth2_items.get("boxLabels") is True:
11768
+ self._log(" 🛰️ 箱唛已下载完成(hub 复核),跳过 fragile 收口")
11769
+ self._mark_done(7)
11770
+ return
11646
11771
  raise StepError(7, "selector_not_found", f"未找到 fragile checkbox ({r})",
11647
11772
  recovery_attempted=["fiber_onChange"])
11648
11773
  # 7g. 等加载旋转层消失再点 Continuar(箱唛生成后约5秒loading)
@@ -11837,7 +11962,7 @@ class Orchestrator:
11837
11962
  self._log(" ✅ 取消生效(appointmentCancellationSuccess 成功标志)")
11838
11963
  return True
11839
11964
  # b. hub-v2 跳转(取消成功后的正常去向)
11840
- if "/hub-v2" in url:
11965
+ if is_hub_url(url):
11841
11966
  self._log(" ✅ 取消生效(hub-v2 跳转)")
11842
11967
  return True
11843
11968
  # c. 按钮消失 且 无错误弹窗(排除侧栏)
@@ -12689,18 +12814,13 @@ class Orchestrator:
12689
12814
  f"失败:{exc.message}"
12690
12815
  f"({_capacity_defer_tag}·预检恢复即**当日**重试,最多 "
12691
12816
  f"{_capacity_max_lift} 次)")
12692
- # 🧹 预约已成功提交(步骤4完成)→ 失败分支自动取消预约,防超时罚款。
12693
- # 放在 auto_retry 网络重置返回之前:即使走自动重置分支先 return,
12694
- # 取消也已完成(防重置后预约残留到预约时间被罚)。
12695
- # dry_run 跳过;步骤4本身失败(completed_steps 不含4)说明预约未成功
12696
- # 提交、无残留,不触发。
12817
+ # ⛔ 2026-10-24 用户口径:失败分支**不再自动取消预约**。
12818
+ # 假失败(如 /hub-v2 → /hub 改版)下自动取消会毁掉本来成功的预约;
12819
+ # 预约是稀缺资源,必须先由评估/人工确认「确实需要取消」再走步骤8。
12820
+ # dry_run 同样不取消。
12697
12821
  cancel_note = ""
12698
12822
  if not dry_run and 4 in self.state.completed_steps:
12699
- self._log(" 🧹 预约已成功,失败分支自动取消预约…")
12700
- if await self._safe_cancel_appointment():
12701
- cancel_note = "\n✅ 预约已自动取消,无超时罚款风险"
12702
- else:
12703
- cancel_note = "\n⚠️ 预约取消失败!请立即人工取消预约,避免超时罚款"
12823
+ self._log(" ⏸ 失败分支不自动取消预约:先核实 hub/门户真实状态;确认需要取消时再走步骤8")
12704
12824
  if self.state.record_id:
12705
12825
  if auto_retry is None and auto_reset_fail is None:
12706
12826
  # 人工类 / 未触发自动恢复:客户群失败卡片(红底 ❌),失败降级文字
@@ -12858,7 +12978,7 @@ class Orchestrator:
12858
12978
  dry_run = mode == "dry-run"
12859
12979
  # ⑧:dry-run 期间所有字段写入在 update_field 里被拦(唯一写入口)
12860
12980
  try:
12861
- self.feishu.dry_run = bool(dry_run)
12981
+ self.feishu.dry_run = bool(dry_run) or bool(getattr(self.args, "no_lip", False) or getattr(self.args, "record_json", ""))
12862
12982
  except Exception: # noqa: BLE001
12863
12983
  pass
12864
12984
  record_ids = [r.strip() for r in str(self.args.records).split(",") if r.strip()]
@@ -13072,7 +13192,58 @@ class Orchestrator:
13072
13192
  # 定向重跑),店铺从记录字段取(store_name),无需 --store-name;若同时给
13073
13193
  # --store-name 且不匹配则报错提示;
13074
13194
  # --store-name:过滤查询第一条店铺名匹配的 Pending+就绪;缺省:第一条 Pending+就绪
13075
- if record_id:
13195
+ _record_json = getattr(self.args, "record_json", "") or ""
13196
+ if _record_json:
13197
+ try:
13198
+ _raw = json.loads(_record_json)
13199
+ except Exception as exc: # noqa: BLE001
13200
+ return {"status": "failed", "record_id": None, "shipment_id": None,
13201
+ "sku": None, "completed_steps": [], "failed_step": None,
13202
+ "error": {"step": None, "type": "business",
13203
+ "message": f"--record-json 解析失败: {exc}",
13204
+ "recovery_attempted": []},
13205
+ "files_uploaded": {}, "dry_run": mode == "dry-run",
13206
+ "write_steps": list(WRITE_STEPS)}
13207
+
13208
+ def _s(*keys):
13209
+ for _k in keys:
13210
+ if _raw.get(_k) not in (None, ""):
13211
+ return str(_raw.get(_k))
13212
+ return ""
13213
+
13214
+ rec = {
13215
+ "record_id": _s("record_id", "sourceRecordId") or "erp-record",
13216
+ "sku": _s("sku"),
13217
+ "qty": _s("qty", "quantity"),
13218
+ "box": _s("box", "boxCount"),
13219
+ "name": _s("name", "productName") or _s("sku"),
13220
+ "store_name": _s("store_name", "store") or (store_name or ""),
13221
+ "shipment_id": _s("shipment_id", "shipmentNo"),
13222
+ }
13223
+ _missing = [k for k in ("sku", "qty", "box", "store_name") if not rec[k]]
13224
+ if _missing:
13225
+ return {"status": "failed", "record_id": rec["record_id"], "shipment_id": None,
13226
+ "sku": rec["sku"], "completed_steps": [], "failed_step": None,
13227
+ "error": {"step": None, "type": "business",
13228
+ "message": f"--record-json 缺字段: {_missing}",
13229
+ "recovery_attempted": []},
13230
+ "files_uploaded": {}, "dry_run": mode == "dry-run",
13231
+ "write_steps": list(WRITE_STEPS)}
13232
+ if store_name and rec["store_name"] != store_name:
13233
+ raise StepError(0, "business",
13234
+ f"--record-json 的店铺 {rec['store_name']} "
13235
+ f"与 --store-name {store_name} 不匹配")
13236
+ self._log(f"🎯 ERP-only 记录 {rec['record_id']}(店铺:{rec['store_name']})")
13237
+ self.state.record_id = rec["record_id"]
13238
+ self.state.name = rec["name"]
13239
+ self.state.store_name = rec["store_name"]
13240
+ self.state.sku = rec["sku"]
13241
+ self.state.qty = rec["qty"]
13242
+ self.state.box = rec["box"]
13243
+ if rec["shipment_id"] and rec["shipment_id"] not in ("None", "null"):
13244
+ self.state.shipment_id = rec["shipment_id"]
13245
+ self._log(f" 已有货件号 {rec['shipment_id']},从步骤4继续")
13246
+ elif record_id:
13076
13247
  rec = self.feishu.get_record(record_id)
13077
13248
  if rec is None:
13078
13249
  self._log(f"记录 {record_id} 不存在或无法读取,本轮退出。")
@@ -13155,7 +13326,7 @@ class Orchestrator:
13155
13326
 
13156
13327
  dry_run = mode == "dry-run"
13157
13328
  try: # ⑧:dry-run 写闸门
13158
- self.feishu.dry_run = bool(dry_run)
13329
+ self.feishu.dry_run = bool(dry_run) or bool(getattr(self.args, "no_lip", False) or getattr(self.args, "record_json", ""))
13159
13330
  except Exception: # noqa: BLE001
13160
13331
  pass
13161
13332
  # 启动标记(状态=运行中)必须与打开店铺在同一 protected 区域:后续任何异常
@@ -13218,7 +13389,31 @@ class Orchestrator:
13218
13389
  return self._result("failed", failed_step=step_filter or 1, error=env_exc.to_dict(),
13219
13390
  step_summaries={}, dry_run=dry_run)
13220
13391
 
13221
- steps = [step_filter] if step_filter else list(range(1, 9))
13392
+ if self.state.shipment_id and not step_filter:
13393
+ # 已有货件号:先用 hub 只读状态判断真实进度;跳过 1-3 的重复打开/建单。
13394
+ # 实测:每次 full 都从步骤1 重开一遍,既慢又会让用户看到“明明有档期却重开”。
13395
+ try:
13396
+ _hub = await self.hub_status(self.state.shipment_id, step=0)
13397
+ _v = self._hub_verdict_of(_hub)
13398
+ self._log(f" 🛰️ 已有货件 #{self.state.shipment_id} hub 状态:"
13399
+ f"{_v.get('reason') or '不可用'}")
13400
+ if _v.get("operationally_complete"):
13401
+ self._log(" ✅ hub 判定已完成 ⇒ 不再重复步骤")
13402
+ for _s in range(1, 9):
13403
+ self._mark_done(_s)
13404
+ steps = []
13405
+ else:
13406
+ for _s in (1, 2, 3):
13407
+ self._mark_done(_s)
13408
+ steps = [4, 5, 6, 7, 8]
13409
+ except Exception as exc: # noqa: BLE001
13410
+ self._log(f" ⚠️ hub 状态探测失败,按已有货件从步骤4续跑: "
13411
+ f"{type(exc).__name__}: {exc}")
13412
+ for _s in (1, 2, 3):
13413
+ self._mark_done(_s)
13414
+ steps = [4, 5, 6, 7, 8]
13415
+ else:
13416
+ steps = [step_filter] if step_filter else list(range(1, 9))
13222
13417
  step_summaries: dict[int, Any] = {}
13223
13418
 
13224
13419
  result = await self._execute_steps(steps, allow_write, dry_run, step_summaries)
@@ -13801,7 +13996,7 @@ def build_parser() -> argparse.ArgumentParser:
13801
13996
  "三态;⛔ 不点按钮、不写表、不改 defer 状态;需 --store-name)")
13802
13997
  p.add_argument("--hub-write-note", action="store_true",
13803
13998
  help="hub-status 模式:当 hub 判定为「运营手动完成」时,**只**写 FULL备注/当前步骤"
13804
- "(识别为运营手动完成(依据 hub-v2 实测));⛔ 仍不改写 FULL状态")
13999
+ "(识别为已完成(依据 hub-v2 实测;来源未声明));⛔ 仍不改写 FULL状态")
13805
14000
  p.add_argument("--no-heal", action="store_true",
13806
14001
  help="cdp-preflight 模式:只检查不自愈(不重连/不重开店铺窗口,纯只读)")
13807
14002
  p.add_argument("--step", type=int, choices=list(range(1, 9)),
@@ -13809,6 +14004,8 @@ def build_parser() -> argparse.ArgumentParser:
13809
14004
  p.add_argument("--allow-write", action="store_true",
13810
14005
  help="批准写步骤(3/4/5/7/8)执行(默认拒绝)")
13811
14006
  p.add_argument("--record-id", help="指定飞书记录 ID 定向处理(店铺从记录字段读取,忽略 --store-name 取第一条逻辑;供并发调度/定向重跑)")
14007
+ p.add_argument("--record-json", help="ERP-only:合成记录 JSON(record_id/sourceRecordId、sku、qty/quantity、box/boxCount、name、store_name/store、shipment_id/shipmentNo)")
14008
+ p.add_argument("--no-lip", action="store_true", help="不读写 lip(Feishu 写操作 no-op);常与 --record-json 使用")
13812
14009
  p.add_argument("--sku", help="SKU(配合 --record-id 使用)")
13813
14010
  p.add_argument("--qty", help="数量(配合 --record-id 使用)")
13814
14011
  p.add_argument("--box", help="箱数(配合 --record-id 使用)")