Compare commits
10
Commits
ad25d5b403
...
a9b5f73552
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a9b5f73552 | ||
|
|
69b59e18dd | ||
|
|
7ca2ee13e3 | ||
|
|
d79a1c8131 | ||
|
|
9f3945a717 | ||
|
|
bbdf578c87 | ||
|
|
7845751cf6 | ||
|
|
cfce3e0bc5 | ||
|
|
048be71ed1 | ||
|
|
296653d8d3 |
@@ -7,6 +7,7 @@ on:
|
|||||||
paths:
|
paths:
|
||||||
- ranch_web/**
|
- ranch_web/**
|
||||||
- ranch_assistant/**
|
- ranch_assistant/**
|
||||||
|
- tools/check_progression_support.py
|
||||||
- deploy/web/**
|
- deploy/web/**
|
||||||
- Dockerfile
|
- Dockerfile
|
||||||
- .dockerignore
|
- .dockerignore
|
||||||
@@ -56,16 +57,53 @@ jobs:
|
|||||||
print(f"publish={'true' if publish else 'false'}", file=output)
|
print(f"publish={'true' if publish else 'false'}", file=output)
|
||||||
print(f"tag={tag if publish else ''}", file=output)
|
print(f"tag={tag if publish else ''}", file=output)
|
||||||
PY
|
PY
|
||||||
- name: Install Web dependencies only
|
- name: Install Web runtime and test dependencies
|
||||||
run: python -m pip install -r ranch_web/requirements.txt
|
run: python -m pip install -r ranch_web/requirements-test.txt
|
||||||
|
- name: Offline sweep hidden handoff, battles, and engine regression
|
||||||
|
timeout-minutes: 3
|
||||||
|
run: |
|
||||||
|
python -B -m unittest \
|
||||||
|
ranch_assistant.tests.test_sweep_hidden_handoff \
|
||||||
|
ranch_assistant.tests.test_sweep_hidden_battles \
|
||||||
|
ranch_assistant.tests.test_sweep_hidden_engine -v
|
||||||
- name: Offline primary cultivation and resource admission regression
|
- name: Offline primary cultivation and resource admission regression
|
||||||
run: |
|
run: |
|
||||||
python -B -m unittest \
|
python -B -m unittest \
|
||||||
ranch_assistant.tests.test_species_retention_limits \
|
ranch_assistant.tests.test_species_retention_limits \
|
||||||
ranch_assistant.tests.test_primary_cultivation \
|
ranch_assistant.tests.test_primary_cultivation \
|
||||||
ranch_assistant.tests.test_primary_resource_admission -v
|
ranch_assistant.tests.test_primary_resource_admission -v
|
||||||
|
- name: Offline commission history and priority regression
|
||||||
|
run: |
|
||||||
|
python -B -m unittest \
|
||||||
|
ranch_assistant.tests.test_commission_history \
|
||||||
|
ranch_assistant.tests.test_commission_history_review \
|
||||||
|
ranch_assistant.tests.test_commission_priority \
|
||||||
|
ranch_web.tests.test_commission_history -v
|
||||||
|
- name: Offline quick battle and commission input regression
|
||||||
|
timeout-minutes: 3
|
||||||
|
run: |
|
||||||
|
python -B -m unittest \
|
||||||
|
ranch_assistant.tests.test_battle_quick \
|
||||||
|
ranch_assistant.tests.test_commission_procurement \
|
||||||
|
ranch_assistant.tests.test_snapshot_potential_anomalies \
|
||||||
|
ranch_assistant.tests.test_progression_support \
|
||||||
|
ranch_web.tests.test_commission_procurement_views -v
|
||||||
- name: Offline updater and task log regression
|
- name: Offline updater and task log regression
|
||||||
run: python -B -m unittest ranch_web.tests.test_updates ranch_web.tests.test_web_updater ranch_web.tests.test_private_updates ranch_web.tests.test_web_updater_package ranch_web.tests.test_activity ranch_web.tests.test_task_logs -v
|
run: python -B -m unittest ranch_web.tests.test_updates ranch_web.tests.test_web_updater ranch_web.tests.test_private_updates ranch_web.tests.test_web_updater_package ranch_web.tests.test_activity ranch_web.tests.test_task_logs -v
|
||||||
|
- name: Offline battle transport, recovery, and capability regression
|
||||||
|
timeout-minutes: 3
|
||||||
|
run: |
|
||||||
|
python -B -m unittest \
|
||||||
|
ranch_assistant.tests.test_battle_worker_transport \
|
||||||
|
ranch_assistant.tests.test_battle_recovery \
|
||||||
|
ranch_assistant.tests.test_battle_capability_presentation \
|
||||||
|
ranch_web.tests.test_lifecycle_recovery -v
|
||||||
|
- name: Offline Web battle recovery contract and status API regression
|
||||||
|
timeout-minutes: 3
|
||||||
|
run: |
|
||||||
|
python -B -m unittest \
|
||||||
|
ranch_web.tests.test_battle_recovery_contract \
|
||||||
|
ranch_web.tests.test_status_recovery_api -v
|
||||||
- name: Offline account recovery regression
|
- name: Offline account recovery regression
|
||||||
run: python -B -m unittest ranch_web.tests.test_run_intent ranch_web.tests.test_scheduler_recovery ranch_web.tests.test_auto_relogin ranch_web.tests.test_connection_state -v
|
run: python -B -m unittest ranch_web.tests.test_run_intent ranch_web.tests.test_scheduler_recovery ranch_web.tests.test_auto_relogin ranch_web.tests.test_connection_state -v
|
||||||
- name: Build image
|
- name: Build image
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
FROM python:3.12-slim-bookworm
|
FROM python:3.12-slim-bookworm
|
||||||
|
|
||||||
ARG WEB_VERSION=2.0.7
|
ARG WEB_VERSION=2.0.12
|
||||||
ARG VCS_REF=unknown
|
ARG VCS_REF=unknown
|
||||||
LABEL org.opencontainers.image.source="https://github.com/attilanet/myrzx_bot" \
|
LABEL org.opencontainers.image.source="https://github.com/attilanet/myrzx_bot" \
|
||||||
org.opencontainers.image.title="myrzx_bot Web" \
|
org.opencontainers.image.title="myrzx_bot Web" \
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
# 牧羊人之心Bot
|
# 牧羊人之心Bot
|
||||||
|
|
||||||
本轮 Web 发布目标 **2.0.7**,源码入口为 `main`;原生 PySide6 桌面正式版本保留 **1.2.0**(`v1.2.0`)。两者的适配资料基线均为《牧羊人之心》Android **1.9.68**。
|
Web **2.0.12**,源码发布入口为 `main`;原生 PySide6 桌面正式版本保留 **1.2.0**(`v1.2.0`)。两者的适配资料基线均为《牧羊人之心》Android **1.9.68**。
|
||||||
支持多账号独立运行、牧场培养、每日事务、主线与委托推进、近似战斗模拟、探险、扫荡及本地掉落分析,能力与验证限制见下文。
|
支持多账号独立运行、牧场培养、每日事务、主线与委托推进、近似战斗模拟、探险、扫荡及本地掉落分析,能力与验证限制见下文。
|
||||||
|
|
||||||
## 运行指引
|
## 运行指引
|
||||||
|
|
||||||
### Web 2.0.7(main)
|
### Web 2.0.12(源码发布入口 main)
|
||||||
|
|
||||||
Windows 使用 Python 3.12+,在项目根目录执行:
|
Windows 使用 Python 3.12+,在项目根目录执行:
|
||||||
|
|
||||||
@@ -19,7 +19,19 @@ py -3 -m venv .venv-web
|
|||||||
|
|
||||||
Web 无需 Node/npm 或 PySide6,数据独立保存在 `local_state/ranch_web`。Linux Python 启动、离线演示与环境配置见 [Web 运行说明](ranch_web/README.md);单服务 Docker、`/data` 持久化、子路径反代与宿主机受控更新见 [Web 部署说明](deploy/web/README.md)。
|
Web 无需 Node/npm 或 PySide6,数据独立保存在 `local_state/ranch_web`。Linux Python 启动、离线演示与环境配置见 [Web 运行说明](ranch_web/README.md);单服务 Docker、`/data` 持久化、子路径反代与宿主机受控更新见 [Web 部署说明](deploy/web/README.md)。
|
||||||
|
|
||||||
**2.0.7** 修复同种重复魔物被继续喂养的问题:主培养固定为已养成的高等级魔物,更优资质只作备用;自动喂养、赠礼、潜能突破仅作用于主培养。已启用孵蛋规则按主培养1只、严格更优备用最多1只整理。通过“帮助 → 检查版本更新…”安装,详见 [发布说明](analysis/RELEASE_2_0_7.md)。
|
**2.0.12** 修复自动扫荡触发隐藏关卡后的战斗接续。完整入场响应与原始队伍快照等原始输入均已保存且可验证时,新记录或可恢复旧记录才自动续打:按 `stageEvent.hideStageId` 构建隐藏关卡难度1的战斗,结束扫荡并自动战斗,无需手动确认,不再次请求入场;战后结算使用隐藏关卡 ID。旧记录即使能从 trace 找回隐藏 ID,缺少原始队伍也保留中文待核对状态,不用当前属性替代原始属性,不发送游戏写请求。
|
||||||
|
|
||||||
|
现场旧 pending 仅保留 `0211 / 3`、提示与 `sampleId`,原始响应已被日志轮转覆盖,无法还原隐藏关卡 ID。仅对符合精确四字段 legacy 形态、严格确认已入场且未结算的这类旧阶段,本版保留证据,在本地归档为未完成并放弃,不提交胜利或失败、不重发入场,让后续策略继续;这不表示当前生产战斗已经打通。
|
||||||
|
|
||||||
|
本版共 **491 项唯一仓库测试:489 通过、2 项 Windows 预期跳过,0 失败 / 错误**;历史测试不计入本版。正式镜像与稳定 Release 就绪后,由用户通过“帮助 → 检查版本更新…”在线升级,详情见 [本版发布说明](analysis/RELEASE_2_0_12.md)。
|
||||||
|
|
||||||
|
沿用 2.0.11 的 Linux 战斗输入传输与按证据恢复修复。手动停止继续阻止提交,来源策略关闭时等待启用,未知已发送写请求不重放,见 [2.0.11 发布说明](analysis/RELEASE_2_0_11.md)。
|
||||||
|
|
||||||
|
沿用 2.0.9 的快速数值模型、伤害配置、委托备料与潜能误报修复;模型按双方属性、血量、伤害、时间及关卡目标估算胜负,逐帧实现仅供研发。2.0.9 的配置预检与历史验证见 [历史发布说明](analysis/RELEASE_2_0_9.md)。
|
||||||
|
|
||||||
|
**2.0.8** 自动委托提供“当前委托 / 每日记录”,跨城市按合格候选的预计氪金 **20→15→10** 排序并说明回退原因;按角色、北京时间自然日持久记录接取、推进和领奖,保留最近90天、每角色最多5000条事件。静态预计奖励与领奖回包确认金额分开,缺失金额保持未确认;旧历史仅从本地任务 journal 可证实的部分回填。详见 [2.0.8 发布说明](analysis/RELEASE_2_0_8.md)。
|
||||||
|
|
||||||
|
沿用 **2.0.7** 的主培养修复:主培养固定为已养成的高等级魔物,更优资质只作备用;自动喂养、赠礼、潜能突破仅作用于主培养。已启用孵蛋规则按主培养1只、严格更优备用最多1只整理,详见 [2.0.7 发布说明](analysis/RELEASE_2_0_7.md)。
|
||||||
|
|
||||||
### 桌面 1.2.0
|
### 桌面 1.2.0
|
||||||
|
|
||||||
@@ -36,7 +48,7 @@ Web 无需 Node/npm 或 PySide6,数据独立保存在 `local_state/ranch_web`
|
|||||||
|
|
||||||
| 组件与版本 | 《牧羊人之心》Android 基线 | 入口与状态 |
|
| 组件与版本 | 《牧羊人之心》Android 基线 | 入口与状态 |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| Web 2.0.7 | 1.9.68 | 本轮发布目标;源码入口 `main`,`Start_Ranch_Web.cmd` / `sh start-web.sh` |
|
| Web 2.0.12 | 1.9.68 | 源码发布入口 `main`,`Start_Ranch_Web.cmd` / `sh start-web.sh` |
|
||||||
| 桌面 1.2.0(`v1.2.0`) | 1.9.68 | 当前桌面版本;`Start_Ranch_Helper.cmd` / `python -m ranch_assistant` |
|
| 桌面 1.2.0(`v1.2.0`) | 1.9.68 | 当前桌面版本;`Start_Ranch_Helper.cmd` / `python -m ranch_assistant` |
|
||||||
| 桌面 1.1.1(`v1.1.1`) | 1.9.68 | 历史正式版本,1.1 系列修复与界面更新 |
|
| 桌面 1.1.1(`v1.1.1`) | 1.9.68 | 历史正式版本,1.1 系列修复与界面更新 |
|
||||||
| 桌面 1.1.0(`v1.1.0`) | 1.9.68 | 历史已发布版本 |
|
| 桌面 1.1.0(`v1.1.0`) | 1.9.68 | 历史已发布版本 |
|
||||||
@@ -44,23 +56,24 @@ Web 无需 Node/npm 或 PySide6,数据独立保存在 `local_state/ranch_web`
|
|||||||
|
|
||||||
本表记录适配资料基线,不代表其他客户端版本兼容或全部功能已完成实机验收。Docker 镜像以标签流水线成功结果为准,在线更新依赖对应 GitHub Release 条目;详见 [部署说明](deploy/web/README.md)。
|
本表记录适配资料基线,不代表其他客户端版本兼容或全部功能已完成实机验收。Docker 镜像以标签流水线成功结果为准,在线更新依赖对应 GitHub Release 条目;详见 [部署说明](deploy/web/README.md)。
|
||||||
|
|
||||||
## Web 2.0.7 主要功能与分类日志
|
## Web 2.0.8 主要功能与分类日志
|
||||||
|
|
||||||
2.0.7 保留自 2.0.3 起的单一底部日志区,切换页签只显示当前账号、当前功能的日志,不提供总日志或页内日志框。本版重点修复同种重复培养,详见 [2.0.7 发布说明](analysis/RELEASE_2_0_7.md)。
|
2.0.8 沿用 2.0.7 的主培养修复与现有界面,并保留自 2.0.3 起的单一底部日志区,切换页签只显示当前账号、当前功能的日志,不提供总日志或页内日志框。自动委托行为与验证状态见 [2.0.8 发布说明](analysis/RELEASE_2_0_8.md)。
|
||||||
|
|
||||||
- **原布局与15页**:沿用桌面页面顺序、账号页签、顶部玩家数值与统一启停、可调整日志区。
|
- **原布局与15页**:沿用桌面页面顺序、账号页签、顶部玩家数值与统一启停、可调整日志区。
|
||||||
- **多账号与独立后台**:各账号隔离并行、同账号请求串行;关闭网页或退出管理登录后,服务端继续监控及已开启的策略。
|
- **多账号与独立后台**:各账号隔离并行、同账号请求串行;关闭网页或退出管理登录后,服务端继续监控及已开启的策略。
|
||||||
- **管理登录与子路径**:独立管理登录页、HttpOnly / SameSite cookie、写请求来源校验;支持 `/ranch` 等反代子路径,游戏凭据保存在服务端。
|
- **管理登录与子路径**:独立管理登录页、HttpOnly / SameSite cookie、写请求来源校验;支持 `/ranch` 等反代子路径,游戏凭据保存在服务端。
|
||||||
- **策略与数据**:复用孵蛋、牧场、喂养、突破、赠礼、每日、主线、委托、探险和扫荡策略,支持自动保存、导入导出、执行计划及掉落分析。
|
- **策略与数据**:复用孵蛋、牧场、喂养、突破、赠礼、每日、主线、委托、探险和扫荡策略,支持自动保存、导入导出、执行计划及掉落分析。
|
||||||
|
- **自动委托(2.0.8)**:当前委托与每日记录分栏;符合条件的候选跨城市按20→15→10排序,说明高档回退原因,城市锁定候选显示不可接取。历史按角色、北京时间保存,预计奖励与领奖确认金额分开。运行详情使用原单一底部“自动委托”分类日志。
|
||||||
- **底部分类日志**:保留原底部日志区及工具栏,顶部右侧是唯一显示/隐藏入口。整页刷新或重新进入工作台默认收起,即使旧配置为显示也不自动展开;配置/状态刷新及调试模式不展开日志。手动显隐按账号保留至刷新,同账号切换功能页保持显隐并更新日志范围。
|
- **底部分类日志**:保留原底部日志区及工具栏,顶部右侧是唯一显示/隐藏入口。整页刷新或重新进入工作台默认收起,即使旧配置为显示也不自动展开;配置/状态刷新及调试模式不展开日志。手动显隐按账号保留至刷新,同账号切换功能页保持显隐并更新日志范围。
|
||||||
- **日志操作与隔离**:搜索、清空显示、下载、跟随/暂停及滚动位置按账号与页签隔离;清空不删除服务端历史,下载遵循当前范围与搜索条件,不串入其他账号或功能。日志共用同一账号拉取,浏览器缓存最多 1200 条,底部最多显示最近 600 条。
|
- **日志操作与隔离**:搜索、清空显示、下载、跟随/暂停及滚动位置按账号与页签隔离;清空不删除服务端历史,下载遵循当前范围与搜索条件,不串入其他账号或功能。日志共用同一账号拉取,浏览器缓存最多 1200 条,底部最多显示最近 600 条。
|
||||||
- **日志归属**:培育室查看孵蛋日志,其他功能页查看对应执行日志;没有匹配记录时为空,不回退到全部日志。登录仅显示登录日志,排除常规、混合旧记录及赠礼日志。已有分类及保守旧记录推断沿用原实现。
|
- **日志归属**:培育室查看孵蛋日志,其他功能页查看对应执行日志;没有匹配记录时为空,不回退到全部日志。登录仅显示登录日志,排除常规、混合旧记录及赠礼日志。已有分类及保守旧记录推断沿用原实现。
|
||||||
- **手动刷新反馈**:刷新成功仅显示简短状态,详细日志只在原底部日志区查看,不弹出诊断提示或大段浮动消息,也不自动展开日志;错误与登录认证反馈沿用原有行为。
|
- **手动刷新反馈**:刷新成功仅显示简短状态,详细日志只在原底部日志区查看,不弹出诊断提示或大段浮动消息,也不自动展开日志;错误与登录认证反馈沿用原有行为。
|
||||||
- **日志保存与更新**:普通日志按账号限量持久保存,调试详情按进程缓存;仅检查官方稳定 2.x Release,未配置执行器时仅检查,受控安装与备份/回滚由宿主机执行,自动安装默认关闭。
|
- **日志保存与更新**:普通日志按账号限量持久保存,调试详情按进程缓存;仅检查官方稳定 2.x Release,未配置执行器时仅检查,受控安装与备份/回滚由宿主机执行,自动安装默认关闭。
|
||||||
|
|
||||||
连接状态区分在线、临时故障重试、游戏会话失效与未连接,显示最后成功通信及下次重试时间,旧快照标注为缓存。临时故障先停止策略,再退避执行只读探测;会话失效时停止游戏轮询,按自动重登设置等待,或手动恢复、重新登录。手动选服、恢复会话及自动重登成功后,均自动执行已勾选功能,可在顶部停止。获取区服候选或登录失败不视为成功;未确认的写操作不自动重发,页面轮询不会清除游戏连接错误。
|
连接状态区分在线、临时故障重试、游戏会话失效与未连接,显示最后成功通信及下次重试时间,旧快照标注为缓存。临时故障先停止策略,再退避执行只读探测;会话失效时停止游戏轮询,按自动重登设置等待,或手动恢复、重新登录。未手动停止时,手动选服、恢复会话及自动重登成功后自动执行已勾选功能;已保存的手动暂停继续生效,可在顶部开启。获取区服候选或登录失败不视为成功;未确认的写操作不自动重发,页面轮询不会清除游戏连接错误。
|
||||||
|
|
||||||
战斗模拟仍为近似模型,特殊关卡并非全部支持。本版验证结果统一见 [发布说明](analysis/RELEASE_2_0_7.md#验证),历史记录见 [Web 验证说明](ranch_web/README.md#离线验证);离线验证不代表真实游戏 API 或生产升级/回滚验收。
|
战斗模拟仍为近似模型,特殊关卡并非全部支持。2.0.8 共验证739项独立测试:736通过、3项 Windows 跳过;其中非浏览器662项(659通过、3跳过),浏览器77项全部验证通过,详见 [发布说明](analysis/RELEASE_2_0_8.md#验证);2.0.7 结果保留在 [历史发布说明](analysis/RELEASE_2_0_7.md#验证),其他历史记录见 [Web 验证说明](ranch_web/README.md#离线验证)。历史结果不计入 2.0.8,离线验证不代表真实游戏 API 或生产升级/回滚验收。
|
||||||
|
|
||||||
## 桌面 1.2.0 功能基线
|
## 桌面 1.2.0 功能基线
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# Web 2.0.10 发布说明
|
||||||
|
|
||||||
|
Web **2.0.10** 基于 **2.0.9**;游戏资料 **1.9.68**,桌面正式版 **1.2.0**。
|
||||||
|
|
||||||
|
## 本版范围
|
||||||
|
|
||||||
|
- **Linux 输入传输**:战斗子进程从匿名临时文件一次读取完整 stdin,修复 Python 3.12 管道重试丢失剩余输入导致的技术超时,保留取消与大小限制。
|
||||||
|
- **旧战斗失败退出**:升级后,旧委托备料记录若已确认入场、未发送结算且符合技术失败条件,按原客户端协议发送 `recordBattleResult`、`result=0` 退出一次;兼容来源任务与步骤均为0的记录,不重新入场、不提交胜利。
|
||||||
|
- **按证据恢复**:保存的原始战斗输入最多用于一次本地恢复;完整战果校验通过后按战斗时钟续交尚未发送的结果。未知已发送写请求不重放。
|
||||||
|
- **停止与等待**:停止检查覆盖恢复提交;内部暂停保留用户运行意愿,来源策略关闭时明确等待启用,不自动开启策略。
|
||||||
|
- **状态与能力展示**:接口透出5个安全策略状态字段,区分运行意愿、实际执行与等待原因;包含 2.0.9 后的导航能力误报修正,真实输入不支持、资源不足及失败原因继续保留。
|
||||||
|
|
||||||
|
沿用现有快速 HP/DPS 模型、伤害配置与工作台布局。
|
||||||
|
|
||||||
|
## 验证
|
||||||
|
|
||||||
|
后端、模型与更新器共 **550 项唯一测试:548 通过、2 项 Windows 预期跳过**;另有 **14 项全新浏览器测试全部通过**,8组独立探针复核通过。
|
||||||
|
|
||||||
|
本轮验证未写入真实游戏 API、未手动部署、未修改生产 journal。升级后依据持久化证据及策略授权恢复。
|
||||||
|
|
||||||
|
## 发布与升级
|
||||||
|
|
||||||
|
正式镜像与稳定 Release 就绪后,由用户在“帮助 → 检查版本更新…”发起在线升级,见 [部署说明](../deploy/web/README.md)。
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# Web 2.0.11 发布说明
|
||||||
|
|
||||||
|
Web **2.0.11** 基于 **2.0.9**;游戏资料 **1.9.68**,桌面正式版 **1.2.0**。
|
||||||
|
|
||||||
|
## 本版范围
|
||||||
|
|
||||||
|
- **Linux 输入传输**:战斗子进程从匿名临时文件一次读取完整 stdin,修复 Python 3.12 管道重试丢失剩余输入导致的技术超时,保留取消与大小限制。
|
||||||
|
- **旧战斗失败退出**:升级后,旧委托备料记录若已确认入场、未发送结算且符合技术失败条件,按原客户端协议发送 `recordBattleResult`、`result=0` 退出一次;兼容来源任务与步骤均为0的记录,不重新入场、不提交胜利。
|
||||||
|
- **按证据恢复**:保存的原始战斗输入最多用于一次本地恢复;完整战果校验通过后按战斗时钟续交尚未发送的结果。未知已发送写请求不重放。
|
||||||
|
- **停止与等待**:停止检查覆盖恢复提交;内部暂停保留用户运行意愿,来源策略关闭时明确等待启用,不自动开启策略。
|
||||||
|
- **状态与能力展示**:接口透出5个安全策略状态字段,区分运行意愿、实际执行与等待原因;包含 2.0.9 后的导航能力误报修正,真实输入不支持、资源不足及失败原因继续保留。
|
||||||
|
|
||||||
|
沿用现有快速 HP/DPS 模型、伤害配置与工作台布局。
|
||||||
|
|
||||||
|
补齐 CI 专用 HTTPX 测试依赖;生产镜像继续只安装运行依赖。
|
||||||
|
|
||||||
|
## 验证
|
||||||
|
|
||||||
|
后端、模型与更新器共 **550 项唯一测试:548 通过、2 项 Windows 预期跳过**;另有 **14 项全新浏览器测试全部通过**,8组独立探针复核通过。
|
||||||
|
|
||||||
|
本轮验证未写入真实游戏 API、未手动部署、未修改生产 journal。升级后依据持久化证据及策略授权恢复。
|
||||||
|
|
||||||
|
## 发布与升级
|
||||||
|
|
||||||
|
正式镜像与稳定 Release 就绪后,由用户在“帮助 → 检查版本更新…”发起在线升级,见 [部署说明](../deploy/web/README.md)。
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
# Web 2.0.12 发布说明
|
||||||
|
|
||||||
|
Web **2.0.12** 基于 **2.0.11**;游戏资料 **1.9.68**,桌面正式版 **1.2.0**。
|
||||||
|
|
||||||
|
## 本版范围
|
||||||
|
|
||||||
|
- **隐藏关卡自动接续**:自动扫荡遇到隐藏事件,且完整入场响应与原始队伍快照等原始输入均已保存、可验证时,沿用原客户端流程关闭扫荡,直接用 `stageEvent.hideStageId` 构建隐藏关卡难度1(`stageLevel='1'`)的战斗。无需手动确认,不再发送第二次 `stageStart`。
|
||||||
|
- **使用真实隐藏关卡结算**:后续 `battleEnd` / `recordBattleResult` 使用隐藏关卡 ID;普通关卡 ID、原扫荡等级及 `sampleId` 不作为隐藏关卡 ID 的替代值。
|
||||||
|
- **完整入场与原始输入可验证才续打**:新记录或可恢复旧记录只有在完整入场响应、原始队伍快照等原始战斗输入均可验证时,才按保存证据继续战斗。用户停止、来源策略授权和未知已发送请求的核对约束继续生效。
|
||||||
|
- **缺原始队伍时保留待核对**:旧记录即使能从 trace 找回隐藏 ID,缺少原始队伍快照也不能拿当前属性当原始属性重新计算;保留具体中文待核对原因,不发送游戏写请求。仅有隐藏 ID 不构成自动续打依据。
|
||||||
|
- **缺失隐藏 ID 的精确旧记录本地归档**:仅对符合精确四字段 legacy 形态、已确认入场且未结算的隐藏阶段,保留原始证据,本地归档为未完成并放弃,让后续策略继续;不提交虚构胜利或失败,不重发入场。
|
||||||
|
- **中文战斗记录**:隐藏战斗显示“隐藏关卡战斗”,本地归档或取消显示“未完成,已放弃”或“未完成,已取消”;具体原因继续保留在原有详情中。
|
||||||
|
|
||||||
|
## 历史现场限制
|
||||||
|
|
||||||
|
本次现场旧 pending 只有普通关卡 `0211`、难度 `3`、隐藏提示与 `sampleId`。包含真实隐藏关卡 ID 的原始响应已被 **8 MB × 2** 的日志轮转覆盖,现有证据无法还原 `stageEvent.hideStageId`。
|
||||||
|
|
||||||
|
该旧记录只能按上述严格条件本地归档,无法据此恢复或证明服务端当前战斗已完成。**本版未在生产打通当前这场战斗**;归档不等于游戏服务端已结算或退出。新记录或可恢复旧记录只有完整入场响应、原始队伍快照等原始输入均可验证时,才具备自动续打依据;仅找回隐藏 ID 的旧记录仍保留待核对。
|
||||||
|
|
||||||
|
## 验证
|
||||||
|
|
||||||
|
本版共 **491 项唯一仓库测试:489 通过、2 项 Windows 预期跳过,0 失败 / 错误**,按实际测试 ID 去重,覆盖50项隐藏关卡专项及74项受影响引擎回归。各阶段复验不重复相加,2.0.11 及更早版本的历史测试结果不计入本版。
|
||||||
|
|
||||||
|
另有 **2 项 Web 离线探针通过**,验证隐藏入场恢复、启停、账号隔离与禁止重复请求,单独统计,不计入上述491项仓库测试。
|
||||||
|
|
||||||
|
静态离线模型另以现有两支队伍分别组合 `hd01`–`hd08`,共16种代表性配置,均在模型支持范围内;32次重复运行结果可复现。其中13种配置得到模型胜利、3种得到模型失败,单次离线模型计算约0.4–14毫秒。此项仅代表静态配置,现场实际隐藏 ID 仍未知,不代表真实通关,不计入 unittest 测试总数。
|
||||||
|
|
||||||
|
本轮验证仅使用离线 fake / 临时目录,不实际调用游戏 API,不部署生产,不修改真实用户策略或生产 journal。
|
||||||
|
|
||||||
|
CI 保留通过 `ranch_web/requirements-test.txt` 安装 HTTPX 测试依赖的修复;生产镜像继续只安装运行依赖。镜像工作流在安装测试依赖后,独立执行隐藏关卡 handoff、battles、engine 三个专用回归模块。
|
||||||
|
|
||||||
|
## 发布与升级
|
||||||
|
|
||||||
|
正式镜像及非草稿、非预发布的稳定 Release 核验就绪后,由用户在“帮助 → 检查版本更新…”发起在线升级,见 [部署说明](../deploy/web/README.md)。
|
||||||
|
|
||||||
|
随版提供与源码一致的 `updater.pyz` 及 ASCII、LF 结尾的 `SHA256SUMS`,下载后核对校验值再使用。v2.0.11 Release、资产、refs 与 Git bundle 已独立备份并校验。
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
# Web 2.0.8 发布说明
|
||||||
|
|
||||||
|
Web **2.0.8** 以 **2.0.7** 为基线,游戏资料 **1.9.68**,桌面正式版 **1.2.0**。
|
||||||
|
|
||||||
|
## 自动委托与每日记录
|
||||||
|
|
||||||
|
- “自动委托”分为**当前委托 / 每日记录**。当前页显示任务、原始候选、标注奖励及选择 / 阻塞原因;城市锁定的原始候选显示为不可接取,不计入可执行候选。
|
||||||
|
- 在策略允许、城市已解锁且满足次数、资源和步骤支持条件的候选中,跨城市按静态标注氪金 **20→15→10** 全局排序。选择低档时,日志记录高档缺失或不可执行的实际原因;不保证每次都有可接取的20档。
|
||||||
|
- 每日记录按账号、区服和角色隔离,以**北京时间(UTC+8)自然日**归档接取、推进、领奖及结果待核对事件,支持日期查询、刷新和服务重启后查看。每角色保留最近 **90 天、最多 5000 条事件**,任一上限达到即裁剪旧事件。
|
||||||
|
- **预计氪金**来自任务静态配置;**已确认氪金**仅取已确认的 `taskComplete` 领奖回包 `response.reward.ke`。缺失或无效金额显示“未确认”,不以预计值、余额变化或旧完成标记补算。接取和推进不计为奖励到账。
|
||||||
|
- 旧历史仅从本地任务 journal 中可证实的操作部分回填;仅有当前任务或旧完成标记不足以推定历史接取、领奖时间或金额。无本地记录不表示当天未做过委托。
|
||||||
|
- 运行详情沿用原有**单一底部“自动委托”分类日志**;每日记录是业务历史,沿用现有账号隔离、日志显隐与筛选。
|
||||||
|
|
||||||
|
## 保留的行为
|
||||||
|
|
||||||
|
沿用 [2.0.7 主培养与资质备用修复](RELEASE_2_0_7.md):已养成的高等级魔物保持主培养,更优资质只作备用;自动经验喂养、同种突破、赠礼及潜能材料仅用于主培养,满级、到上限、冷却或忙碌时等待。已启用种类保留主培养1只与严格更优备用最多1只,锁定、在队、装备、探索、委托等硬保护继续生效。
|
||||||
|
|
||||||
|
保留15页结构、账号页签、统一启停、居中加载反馈和紧凑表单。登录、恢复会话及重登成功后默认执行已勾选策略;用户手动“停止”跨掉线、重登和服务重启保留,点击“开启”恢复,导入配置保留启停意图。
|
||||||
|
|
||||||
|
## 验证
|
||||||
|
|
||||||
|
独立离线验证报告:`test-artifacts/commission-history-review-20261113/final-report.txt`(2026-11-13)。
|
||||||
|
|
||||||
|
| 范围 | 运行 | 通过 | 跳过 | 失败 / 错误 |
|
||||||
|
| --- | --- | --- | --- | --- |
|
||||||
|
| 纯核心 | 215 | 215 | 0 | 0 / 0 |
|
||||||
|
| 主培养回归 | 87 | 87 | 0 | 0 / 0 |
|
||||||
|
| Web 非浏览器 | 353 | 350 | 3 | 0 / 0 |
|
||||||
|
| 独立 Qt 任务状态 | 7 | 7 | 0 | 0 / 0 |
|
||||||
|
| 非浏览器小计 | 662 | 659 | 3 | 0 / 0 |
|
||||||
|
| 浏览器独立用例 | 77 | 77 | 0 | 0 / 0 |
|
||||||
|
| **合计** | **739** | **736** | **3** | **0 / 0** |
|
||||||
|
|
||||||
|
核心215项包含新增历史27项、独立评审23项及优先级7项,均已计入合计。3项跳过源于 Windows 的 POSIX 权限或符号链接限制。独立非浏览器验证前后170个源文件 / 测试 / CI文件哈希一致;纯核心、主培养与 Web 非浏览器组隔离 Qt,游戏操作使用合成客户端或本地 HTTP mock,未访问真实游戏 API。
|
||||||
|
|
||||||
|
浏览器77个独立用例全部验证通过:全量运行76项通过,加载模块在仅修正测试 fixture 的被动轮询竞态后3/3通过,重叠用例不重复计数。测试修复保留全部原断言,产品源码未变。浏览器证据:`test-artifacts/commission-history/final-browser-20261113T013148Z/loading-fixture-fix.report.json` 与 `fixture-race-proof.json`。
|
||||||
|
|
||||||
|
离线结果不代表真实账号奖励到账、镜像构建或生产升级 / 回滚验收。历史版本测试不计入本版。
|
||||||
|
|
||||||
|
## 更新包与发布条件
|
||||||
|
|
||||||
|
本地更新器由 `tools/build_web_updater.py` 生成:`test-artifacts/releases/v2.0.8/updater.pyz`,同目录 `SHA256SUMS` 使用 LF 换行。包内3份源文件与版本库源文件逐字节一致;构建结果可复现,版本、帮助与离线升级计划检查通过。
|
||||||
|
|
||||||
|
版本标签 `v2.0.8`,镜像 `ghcr.io/attilanet/myrzx_bot-web:v2.0.8`。在线更新以对应稳定 Release 与镜像均就绪为前提。
|
||||||
|
|
||||||
|
已有部署须等稳定 Release、正式镜像就绪且宿主机心跳有效后,通过“帮助 → 检查版本更新…”升级,完成后刷新网页;详见 [部署说明](../deploy/web/README.md)。
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
# Web 2.0.9 发布说明
|
||||||
|
|
||||||
|
Web **2.0.9** 基于 **2.0.8**;游戏资料 **1.9.68**,桌面正式版 **1.2.0**。
|
||||||
|
|
||||||
|
- **界面清理**:移除设置页重复运行提示,保留简短状态、错误、业务表格、配置表单与原单一底部分类日志。
|
||||||
|
- **委托原因与备料**:明确中文未接取原因,成熟魔物需求联动购蛋/孵化,先备齐资源再接取;保护锁定、培养、优质备份等魔物,遵守耗用预算与孵蛋缺口限制。
|
||||||
|
- **快速数值战斗**:正常执行默认使用现有实验运行时入口的快速 HP/DPS 模型,保留现有伤害配置,无需选择新模式;逐帧实现仅供研发。按双方属性、有效血量、伤害、时间和关卡目标估算胜利、战败或超时。
|
||||||
|
- **潜能误报修复**:按合法的 `PotentialPanel` 上限识别正常潜能,避免误报为异常。
|
||||||
|
|
||||||
|
## 验证
|
||||||
|
|
||||||
|
617项唯一回归用例中615项通过,2项因Windows环境跳过;另有8项界面浏览器测试通过。多步骤委托的采购范围不一致问题已修复,并通过独立复核。
|
||||||
|
|
||||||
|
快速模型的输入预检覆盖由147/358提升至358/358份主线与委托战斗配置,表示配置可计算,实际仍可能打不过。“猫狗的恩怨”的真实账号离线样本预计战斗5秒,直接计算约1.2毫秒,含隔离进程启动与检查约0.21秒;8个20氪金委托战斗样本为5胜3败。
|
||||||
|
|
||||||
|
本轮未在线提交游戏结算或手动部署X99。模型结果可能与客户端不同;发布后通过在线更新升级,见 [部署说明](../deploy/web/README.md)。
|
||||||
+2
-2
@@ -1,11 +1,11 @@
|
|||||||
name: ranch-web
|
name: ranch-web
|
||||||
services:
|
services:
|
||||||
web:
|
web:
|
||||||
image: ${RANCH_WEB_IMAGE:-ghcr.io/attilanet/myrzx_bot-web:v2.0.7}
|
image: ${RANCH_WEB_IMAGE:-ghcr.io/attilanet/myrzx_bot-web:v2.0.12}
|
||||||
build:
|
build:
|
||||||
context: .
|
context: .
|
||||||
args:
|
args:
|
||||||
WEB_VERSION: ${RANCH_WEB_BUILD_VERSION:-2.0.7}
|
WEB_VERSION: ${RANCH_WEB_BUILD_VERSION:-2.0.12}
|
||||||
user: "10001:10001"
|
user: "10001:10001"
|
||||||
init: true
|
init: true
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|||||||
+19
-13
@@ -1,8 +1,12 @@
|
|||||||
# Web 2 Linux Docker 部署与更新
|
# Web 2 Linux Docker 部署与更新
|
||||||
|
|
||||||
当前更新示例以 `v2.0.7` 为目标;下文 2.0.1 首次初始化步骤保留历史版本。游戏资料基线为 `1.9.68`,桌面版保留 `1.2.0`。镜像流水线成功、Git tag 与 GitHub Release 是不同的发布步骤:在线更新必须等对应镜像及非草稿、非预发布的 Release 均发布后才能使用。私有仓库未获授权返回 404 属于访问失败,不代表没有版本;只有成功读取列表且没有稳定 2.x 时才显示“暂无正式版”。
|
当前应用及更新示例为 `v2.0.12`。下文首次初始化章节保留 2.0.1 流程及历史版本示例。游戏资料基线为 `1.9.68`,桌面版保留 `1.2.0`。镜像流水线成功、Git tag 与 GitHub Release 是不同的发布步骤:在线更新必须等对应镜像及非草稿、非预发布的 Release 均发布后才能使用。私有仓库未获授权返回 404 属于访问失败,不代表没有版本;只有成功读取列表且没有稳定 2.x 时才显示“暂无正式版”。
|
||||||
|
|
||||||
已在 2.0.1 完成私有仓库和 GHCR 认证的部署,可在 2.0.7 稳定 Release 与正式镜像就绪后直接通过“帮助 → 检查版本更新…”升级,无需先安装 2.0.2、重复初始化或替换宿主机更新器。尚未接入私有在线更新的宿主机才需参考下文“已有宿主机首次初始化”。
|
2.0.12 修复扫荡隐藏事件的自动战斗接续:完整入场响应与原始队伍快照等原始输入均已保存且可验证时,才按 `stageEvent.hideStageId` 直接构建隐藏关卡难度1的战斗,不再请求入场,战后使用隐藏 ID 结算。旧记录即使能从 trace 找回隐藏 ID,缺少原始队伍也保留中文待核对状态,不以当前属性重算,不发送游戏写请求。现场旧 `0211 / 3` 记录的原始响应已被日志轮转覆盖,无法还原隐藏 ID;仅对符合精确四字段 legacy 形态、严格确认已入场且未结算的这类旧阶段,保留证据并在本地归档为未完成、放弃,不提交胜负或重发入场。归档不等于服务端已结算,也不表示当前生产战斗已打通,见 [本版发布说明](../../analysis/RELEASE_2_0_12.md)。
|
||||||
|
|
||||||
|
已在 2.0.1 完成私有仓库和 GHCR 认证的部署,稳定 Release 与正式镜像发布后,可直接通过“帮助 → 检查版本更新…”升级,无需先安装 2.0.2、重复初始化或替换宿主机更新器。尚未接入私有在线更新的宿主机才需参考下文“已有宿主机首次初始化”。
|
||||||
|
|
||||||
|
2.0.8 自动委托提供“当前委托 / 每日记录”,合格候选跨城市按20→15→10排序并说明回退原因;历史按角色、北京时间自然日持久保存,最近90天、每角色最多5000条事件。静态预计奖励与领奖回包确认金额分开,旧历史仅回填本地任务 journal 可证实的部分;运行详情使用原单一底部分类日志。2.0.7 高等级主培养与资质备用修复继续生效,详见 [2.0.8 发布说明](../../analysis/RELEASE_2_0_8.md)。
|
||||||
|
|
||||||
## 容器与持久化
|
## 容器与持久化
|
||||||
|
|
||||||
@@ -19,9 +23,9 @@ sudo install -m 0600 -o root -g root deploy/web/image.env.example .image.env
|
|||||||
sudoedit .env .image.env
|
sudoedit .env .image.env
|
||||||
```
|
```
|
||||||
|
|
||||||
在 `.env` 填入独立的 `RANCH_WEB_PASSWORD`,这是 Web 管理密码,不是游戏密码;`.image.env` 选择 `RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:v2.0.7`,需确认对应镜像已发布后再 pull。Compose 默认只发布到宿主机 `127.0.0.1:8765`,容器内监听 `0.0.0.0:8765` 并强制管理密码。使用域名反代时,同时配置 `RANCH_WEB_ALLOWED_HOSTS` 与 `RANCH_WEB_ALLOWED_ORIGINS`;TLS 入口设置 `RANCH_WEB_SECURE_COOKIE=true`。代理保留正确的 Host,写请求依赖来源校验。
|
在 `.env` 填入独立的 `RANCH_WEB_PASSWORD`,这是 Web 管理密码,不是游戏密码;`.image.env` 的目标示例为 `RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:v2.0.12`,需确认对应镜像已发布后再 pull。Compose 默认只发布到宿主机 `127.0.0.1:8765`,容器内监听 `0.0.0.0:8765` 并强制管理密码。使用域名反代时,同时配置 `RANCH_WEB_ALLOWED_HOSTS` 与 `RANCH_WEB_ALLOWED_ORIGINS`;TLS 入口设置 `RANCH_WEB_SECURE_COOKIE=true`。代理保留正确的 Host,写请求依赖来源校验。
|
||||||
|
|
||||||
`/opt/ranch-web/data` 挂到容器 `/data`,包括账号、加密会话与密钥、配置、SQLite 统计和更新请求;独立于桌面数据。心跳控制目录独立只读挂到 `/run/ranch-updater`。使用 bind mount 的目录必须预先创建,Compose 不会悄悄创建 root 所有、容器无法写入的目录。默认容器用户 `10001:10001`,根文件系统只读,临时文件写到 `/tmp`。不要对现有账号目录重新初始化密钥。
|
`/opt/ranch-web/data` 挂到容器 `/data`,包括账号、加密会话与密钥、配置、委托历史、SQLite 统计和更新请求;独立于桌面数据。心跳控制目录独立只读挂到 `/run/ranch-updater`。使用 bind mount 的目录必须预先创建,Compose 不会悄悄创建 root 所有、容器无法写入的目录。默认容器用户 `10001:10001`,根文件系统只读,临时文件写到 `/tmp`。不要对现有账号目录重新初始化密钥。
|
||||||
|
|
||||||
正式版本启动:
|
正式版本启动:
|
||||||
|
|
||||||
@@ -51,9 +55,9 @@ Web 只读检查官方 GitHub Releases;默认只接受 `v2.MINOR.PATCH`,跳
|
|||||||
|
|
||||||
### 已完成 2.0.1 初始化的宿主机
|
### 已完成 2.0.1 初始化的宿主机
|
||||||
|
|
||||||
`v2.0.7` 稳定 Release 与正式镜像发布后,用户打开“帮助 → 检查版本更新…”,检查到 2.0.7 后手动提交更新请求,可从 2.0.1 直接安装。现有私有仓库认证、GHCR 登录与宿主机更新器继续使用;Web 按钮仍要求有效心跳及 `accept_web_requests=true`。请求显示 `pending` 只表示已提交,宿主机完成备份、安装及健康检查后才确认成功;升级完成后刷新网页以加载新版界面,底部日志默认收起。Windows 或未启用执行器时仍仅可检查版本。自动安装默认关闭。
|
稳定 Release 与正式镜像发布后,用户打开“帮助 → 检查版本更新…”,检查到 2.0.12 后手动提交更新请求,可从 2.0.1 直接安装。现有私有仓库认证、GHCR 登录与宿主机更新器继续使用;Web 按钮仍要求有效心跳及 `accept_web_requests=true`。请求显示 `pending` 只表示已提交,宿主机完成备份、安装及健康检查后才确认成功;升级完成后刷新网页以加载新版界面,底部日志默认收起。Windows 或未启用执行器时仍仅可检查版本。自动安装默认关闭。
|
||||||
|
|
||||||
### 全新宿主机准备
|
### 全新宿主机安装
|
||||||
|
|
||||||
全新安装时,先安装 root 持有的配置,并准备独立更新器(示例的自动化开关默认关闭):
|
全新安装时,先安装 root 持有的配置,并准备独立更新器(示例的自动化开关默认关闭):
|
||||||
|
|
||||||
@@ -68,11 +72,11 @@ python3 -B /opt/ranch-web/updater.pyz --version
|
|||||||
|
|
||||||
### 已有宿主机首次初始化(用户自行执行)
|
### 已有宿主机首次初始化(用户自行执行)
|
||||||
|
|
||||||
以下保留 2.0.1 引入私有在线更新时的初始化步骤与 Release 链接,仅供尚未初始化的宿主机参考;已完成私有仓库和 GHCR 认证的部署无需重做。步骤中的 `v2.0.1` 是首次初始化的历史目标,当前应用更新目标为 `v2.0.7`。
|
以下保留 2.0.1 引入私有在线更新时的初始化流程,仅供尚未初始化的宿主机参考;已完成私有仓库和 GHCR 认证的部署无需重做。本节的历史资产示例为 `v2.0.7`,第4步的 `v2.0.1` 是首次初始化的历史应用目标。当前应用升级须确认对应发布物就绪,再按上文步骤执行。
|
||||||
|
|
||||||
前提是原有 `/opt/ranch-web` Compose 部署、数据目录及 `/etc/ranch-web-updater.toml` 均已存在,配置仍由 root 持有。保留原有数据和配置,不重新初始化密钥;数据目录由 `10001:10001` 持有。以下仅初始化在线更新器,不需要复制项目源码或 Compose。
|
前提是原有 `/opt/ranch-web` Compose 部署、数据目录及 `/etc/ranch-web-updater.toml` 均已存在,配置仍由 root 持有。保留原有数据和配置,不重新初始化密钥;数据目录由 `10001:10001` 持有。以下仅初始化在线更新器,不需要复制项目源码或 Compose。
|
||||||
|
|
||||||
1. 用户登录有私有仓库读取权限的 GitHub 账号,从 [当前正式 Release](https://github.com/attilanet/myrzx_bot/releases/tag/v2.0.7) 下载 `updater.pyz` 和 `SHA256SUMS`,放到宿主机临时目录。确认 Release 已发布且镜像可读取,在下载目录执行 `sha256sum -c SHA256SUMS` 后安装:
|
1. 用户登录有私有仓库读取权限的 GitHub 账号,历史资产示例从 [2.0.7 Release](https://github.com/attilanet/myrzx_bot/releases/tag/v2.0.7) 下载 `updater.pyz` 和 `SHA256SUMS`,放到宿主机临时目录。确认 Release 已发布且镜像可读取,在下载目录执行 `sha256sum -c SHA256SUMS` 后安装:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
sudo install -m 0644 -o root -g root updater.pyz /opt/ranch-web/updater.pyz
|
sudo install -m 0644 -o root -g root updater.pyz /opt/ranch-web/updater.pyz
|
||||||
@@ -106,7 +110,7 @@ python3 -B /opt/ranch-web/updater.pyz --version
|
|||||||
|
|
||||||
Docker 保存的宿主机登录配置供更新器拉镜像使用;不要复制开发机的 Git/registry 凭据,也不要把 Docker 凭据放进 GitHub Token 文件或 Web 容器。[GHCR 官方认证说明](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry)
|
Docker 保存的宿主机登录配置供更新器拉镜像使用;不要复制开发机的 Git/registry 凭据,也不要把 Docker 凭据放进 GitHub Token 文件或 Web 容器。[GHCR 官方认证说明](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry)
|
||||||
|
|
||||||
4. 使用新包先检查再由用户明确发起在线更新:
|
4. 使用新包先检查再由用户明确发起在线更新。以下 `--apply v2.0.1` 仅保留首次初始化的历史示例,不是本轮 2.0.12 升级命令:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
sudo python3 -B /opt/ranch-web/updater.pyz --config /etc/ranch-web-updater.toml --check
|
sudo python3 -B /opt/ranch-web/updater.pyz --config /etc/ranch-web-updater.toml --check
|
||||||
@@ -161,12 +165,14 @@ Windows 或未安装执行器的 Docker 部署仍能检查版本,但按钮会
|
|||||||
|
|
||||||
[web-image.yml](../../.github/workflows/web-image.yml) 仅对官方仓库的严格稳定 `v2.x.y` tag 推送 `ghcr.io/attilanet/myrzx_bot-web:v2.x.y`;校验 `ranch_web.__version__` 必须与 tag 一致,不能只改变镜像 label。PR 与手动运行只测试、构建,不推送。开发分支 push 不触发正式镜像发布,也没有 `latest` 滚动升级通道。CI 执行更新器、私有凭据和独立包回归,并在无外网容器中检查 healthcheck、非 root 数据写权限、无 Qt 和正常停止;镜像发布状态以对应 tag 的工作流结果为准。
|
[web-image.yml](../../.github/workflows/web-image.yml) 仅对官方仓库的严格稳定 `v2.x.y` tag 推送 `ghcr.io/attilanet/myrzx_bot-web:v2.x.y`;校验 `ranch_web.__version__` 必须与 tag 一致,不能只改变镜像 label。PR 与手动运行只测试、构建,不推送。开发分支 push 不触发正式镜像发布,也没有 `latest` 滚动升级通道。CI 执行更新器、私有凭据和独立包回归,并在无外网容器中检查 healthcheck、非 root 数据写权限、无 Qt 和正常停止;镜像发布状态以对应 tag 的工作流结果为准。
|
||||||
|
|
||||||
2.0.7 验证结果统一见 [发布说明](../../analysis/RELEASE_2_0_7.md#验证)。以下命令用于更新器离线验证;历史 Windows 离线验证与 Linux 部署烟测见 [Web 运行说明](../../ranch_web/README.md#离线验证),不计入本版验收。可在无 Docker 的机器上构建临时更新器资产并打印计划;`--dry-run` 不联网、不读取凭据、不调用 Docker,也不写文件:
|
本版共 **491 项唯一仓库测试:489 通过、2 项 Windows 预期跳过,0 失败 / 错误**,见 [2.0.12 发布说明](../../analysis/RELEASE_2_0_12.md#验证)。本轮不实际调用游戏 API、不部署生产、不修改真实用户策略或生产 journal。2.0.11 的测试结果见 [历史发布说明](../../analysis/RELEASE_2_0_11.md#验证),不计入本版。CI 保留通过 `ranch_web/requirements-test.txt` 安装 HTTPX 的修复。
|
||||||
|
|
||||||
|
2.0.8 共验证739项独立测试:736通过、3项 Windows 跳过;其中非浏览器662项(659通过、3跳过),浏览器77项全部验证通过,详见 [发布说明](../../analysis/RELEASE_2_0_8.md#验证)。2.0.7 结果保留在 [历史发布说明](../../analysis/RELEASE_2_0_7.md#验证)。以下命令可复现本地更新器构建与离线检查;历史 Windows 离线验证与 Linux 部署烟测见 [Web 运行说明](../../ranch_web/README.md#离线验证),不计入本版验收。可在无 Docker 的机器上构建临时更新器资产并打印计划;`--dry-run` 不联网、不读取凭据、不调用 Docker,也不写文件:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
python -B tools/build_web_updater.py --output test-artifacts/updater.pyz
|
python -B tools/build_web_updater.py --output test-artifacts/releases/v2.0.12/updater.pyz
|
||||||
python -B test-artifacts/updater.pyz --version
|
python -B test-artifacts/releases/v2.0.12/updater.pyz --version
|
||||||
python -B test-artifacts/updater.pyz --config deploy/web/updater.example.toml --apply v2.0.7 --dry-run
|
python -B test-artifacts/releases/v2.0.12/updater.pyz --config deploy/web/updater.example.toml --apply v2.0.12 --dry-run
|
||||||
python -B -m unittest ranch_web.tests.test_updates ranch_web.tests.test_web_updater ranch_web.tests.test_private_updates ranch_web.tests.test_web_updater_package -v
|
python -B -m unittest ranch_web.tests.test_updates ranch_web.tests.test_web_updater ranch_web.tests.test_private_updates ranch_web.tests.test_web_updater_package -v
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -1,2 +1,2 @@
|
|||||||
# Pull only after the v2.0.7 image publishing workflow succeeds and the image is available.
|
# Pull only after the v2.0.12 image publishing workflow succeeds and the image is available.
|
||||||
RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:v2.0.7
|
RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:v2.0.12
|
||||||
|
|||||||
@@ -0,0 +1,370 @@
|
|||||||
|
"""Fast, approximate HP/DPS budgets; no movement, animation or skill replay.
|
||||||
|
|
||||||
|
Inputs and the experimental result/settlement contract come from the existing
|
||||||
|
simulator. One-second simultaneous damage budgets are not original-engine hits.
|
||||||
|
"""
|
||||||
|
from collections import Counter
|
||||||
|
from dataclasses import replace
|
||||||
|
import math
|
||||||
|
import time
|
||||||
|
|
||||||
|
from . import battle_simulator as sim
|
||||||
|
|
||||||
|
|
||||||
|
ASSUMPTIONS = (
|
||||||
|
"Aggregate model: one-second simultaneous HP/DPS budgets, without movement or animation.",
|
||||||
|
"Expected damage uses original attack, defense, dexterity, element and critical-hit formulas.",
|
||||||
|
"Damage is shared equally among eligible opposing targets; explicit target locks take precedence.",
|
||||||
|
"Team capacity, ordered waves, join times and death/time reinforcement gates use coarse numeric steps.",
|
||||||
|
"Makers generate original-stat units at an averaged rate, bounded by 128 generated units per battle.",
|
||||||
|
"Skills use bounded expected damage/healing contributions; other skill effects are omitted.",
|
||||||
|
"HP controllers use averaged healing/damage rates; other control, movement and buff effects are omitted.",
|
||||||
|
"This approximate model has not been validated against original AIR battle outcomes.",
|
||||||
|
)
|
||||||
|
MAX_GENERATED = 128
|
||||||
|
MAX_STEPS = 7200
|
||||||
|
|
||||||
|
|
||||||
|
class _MeanRoll:
|
||||||
|
@staticmethod
|
||||||
|
def uniform(low, high):
|
||||||
|
return (low + high) / 2
|
||||||
|
|
||||||
|
|
||||||
|
def prepare(request, tables=None):
|
||||||
|
tables = tables if tables is not None else sim.combat_tables()
|
||||||
|
scenario, report = sim._prepare(request, tables, quick=True)
|
||||||
|
report.update(model="quick-v1-hp-dps", approximate=True, faithful=False,
|
||||||
|
simulation_method="aggregate_hp_dps", implemented_skills=[],
|
||||||
|
assumptions=list(ASSUMPTIONS), ignored_mechanics=list(ASSUMPTIONS))
|
||||||
|
for d in report["diagnostics"]:
|
||||||
|
if d["code"] == "unsupported_skill":
|
||||||
|
d["code"] = "aggregate_skill"
|
||||||
|
d["message"] = d["message"].replace("is omitted", "uses a bounded aggregate expectation where numeric parameters exist")
|
||||||
|
elif d["code"] == "aggregate_approximation":
|
||||||
|
d["message"] = d["message"].replace("unsupported", "approximated").replace("Unsupported", "Approximated")
|
||||||
|
if scenario is not None:
|
||||||
|
battle = sim._get(sim._get(request, "original_data", {}), "battle", {})
|
||||||
|
kinds = sorted({str(c.get("type", "unknown")) for c in battle.get("controller", ()) or ()}
|
||||||
|
| {str(c.get("type", "unknown")) for t in battle.get("teams", ()) for m in t.get("mons", ()) if m
|
||||||
|
for c in m.get("controller", ()) or ()})
|
||||||
|
report["aggregate_controllers"] = kinds
|
||||||
|
report["assumptions"].append("Configured controllers: " + (", ".join(kinds) or "none") + "; only makers, HP rates and numeric target gates affect this model.")
|
||||||
|
report["objective"] = {1: "elimination", 2: "survive_until_time", 3: "destroy_any", 4: "destroy_all"}.get(
|
||||||
|
scenario.win_types[0] if scenario.win_types else 1, "elimination_approximation")
|
||||||
|
for c in list(battle.get("controller", ()) or ()) + [c for t in battle.get("teams", ())
|
||||||
|
for m in t.get("mons", ()) if m for c in m.get("controller", ()) or ()]:
|
||||||
|
if c.get("type") == "monMaker":
|
||||||
|
p = c.get("para", {})
|
||||||
|
try:
|
||||||
|
if str(sim._int(p.get("monType", 0))) not in tables["monster_info"]:
|
||||||
|
raise sim.SimulationInputError("Generated monster species has no original attributes")
|
||||||
|
if sim._int(p.get("team", 2)) not in scenario.teams:
|
||||||
|
# Standalone controllers can be the only source of enemies.
|
||||||
|
scenario.teams[sim._int(p.get("team", 2))] = {"capacity": 4, "initial": 0, "max": 0}
|
||||||
|
for name in ("interval", "hp", "hpMax", "atk", "level"):
|
||||||
|
if p.get(name) is not None:
|
||||||
|
sim._number(p[name])
|
||||||
|
except sim.SimulationInputError as exc:
|
||||||
|
report["reasons"].append(str(exc))
|
||||||
|
report["supported"] = False
|
||||||
|
report["teams"] = sim._plain(scenario.teams)
|
||||||
|
return scenario, report
|
||||||
|
|
||||||
|
|
||||||
|
class _QuickBattle(sim._Battle):
|
||||||
|
def __init__(self, scenario, report, tables, request):
|
||||||
|
super().__init__(scenario, report, tables)
|
||||||
|
self.pending_triggers = [] # Triggers below affect budgets, never a detailed replay.
|
||||||
|
self.raw = sim._get(sim._get(request, "original_data", {}), "battle", {})
|
||||||
|
self.raw_mons = {f"configured-{ti + 1}-{mi + 1}": m for ti, t in enumerate(self.raw.get("teams", ()))
|
||||||
|
for mi, m in enumerate(t.get("mons", ())) if m}
|
||||||
|
roster = sim._get(request, "roster", sim._get(request, "snapshot", {}))
|
||||||
|
roster = sim._get(roster, "raw", roster)
|
||||||
|
players = {str(m["id"]): m for m in roster.get("monsters", ())}
|
||||||
|
self.raw_mons.update({a.unit.key: players[a.unit.source_id] for a in self.actors
|
||||||
|
if a.unit.key.startswith("player-")})
|
||||||
|
self.triggers = list(self.raw.get("triggers", ()) or ())
|
||||||
|
self.gated = set()
|
||||||
|
self.join_gates = set()
|
||||||
|
for t in self.triggers:
|
||||||
|
for e in t.get("effects", ()):
|
||||||
|
p = e.get("para", {})
|
||||||
|
if e.get("type") == "unlockWave":
|
||||||
|
self.gated.add((sim._int(p.get("team", 2)), sim._int(p.get("wave", 1))))
|
||||||
|
if e.get("type") == "monJoin":
|
||||||
|
self.join_gates.add(str(p.get("mid", "")))
|
||||||
|
self.next_wave = {}
|
||||||
|
self.generated = 0
|
||||||
|
self.damage_checks = set()
|
||||||
|
self.peak_dps = Counter()
|
||||||
|
self.expectations = {}
|
||||||
|
self.hp_rates = {}
|
||||||
|
self.makers = []
|
||||||
|
for a in self.actors:
|
||||||
|
self.configure(a, self.raw_mons.get(a.unit.key, {}))
|
||||||
|
for c in self.raw.get("controller", ()) or ():
|
||||||
|
if c.get("type") == "monMaker":
|
||||||
|
self.makers.append({"vo": c, "owner": None, "credit": 0.,
|
||||||
|
"active": c.get("para", {}).get("activited", True) is not False})
|
||||||
|
|
||||||
|
def configure(self, actor, mon):
|
||||||
|
u, row = actor.unit, self.tables["monster_info"][str(actor.unit.species)]
|
||||||
|
damage, healing = 1., 0.
|
||||||
|
player = u.key.startswith("player-")
|
||||||
|
for slot in (1, 2):
|
||||||
|
sid = sim._int(mon.get(f"skill_{slot}", -1)) if not player else -1
|
||||||
|
sid = sim._int(row.get(f"skill_{slot}", 0)) if sid == -1 else sid
|
||||||
|
if player and sim._int(mon.get("upStar", 0)) > 0:
|
||||||
|
sid = sim._int(self.tables["upstar_info"].get(str(u.species), {}).get("skill", {}).get(str(slot), sid))
|
||||||
|
tp = min(4, sim._int(mon.get("tpLevel", 0)))
|
||||||
|
level = sim._int(mon.get(f"skill_{slot}_lv", -1))
|
||||||
|
level = max(1, tp + 1 if slot == 1 and not sim._int(row.get("skill_2", 0)) else 1) if level < 1 else level
|
||||||
|
skill = self.tables["monster_skill"].get(str(sid), {}).get(f"lv{level}", {})
|
||||||
|
p = skill.get("para", {})
|
||||||
|
cooldown = max(1., sim._number(skill.get("cd", 10000)) / 1000)
|
||||||
|
# At most 25% total expected damage gain, never a stat multiplier.
|
||||||
|
extra = max(0., sim._number(p.get("damage", p.get("hurt", 1))) - 1)
|
||||||
|
damage += min(.125, extra / cooldown)
|
||||||
|
healing += max(0., sim._number(p.get("cure", 0)) + u.stats.atk * sim._number(p.get("cureAtkAdd", 0))) / cooldown
|
||||||
|
self.expectations[u.key] = (min(1.25, damage), healing)
|
||||||
|
rates = []
|
||||||
|
for c in mon.get("controller", ()) or ():
|
||||||
|
kind, p = c.get("type"), c.get("para", {})
|
||||||
|
if kind == "monMaker":
|
||||||
|
self.makers.append({"vo": c, "owner": u.key, "credit": 0., "active": True})
|
||||||
|
if kind in ("hp", "hpArea"):
|
||||||
|
rates.append((kind, sim._number(p.get("hp", 0)) / max(1., sim._number(p.get("interval", 1000)) / 1000),
|
||||||
|
str(p.get("mid", -1))))
|
||||||
|
for name, kind in (("selfCure", "hp"), ("sunFire", "enemy"), ("moonHeal", "hpArea")):
|
||||||
|
amount = u.effects.get(name, 0)
|
||||||
|
if amount:
|
||||||
|
rates.append((kind, (-amount if name == "sunFire" else amount) / 5, "-1"))
|
||||||
|
self.hp_rates[u.key] = rates
|
||||||
|
|
||||||
|
def gates(self):
|
||||||
|
for trigger in list(self.triggers):
|
||||||
|
p, kind = trigger.get("para", {}), trigger.get("type")
|
||||||
|
source = self.by_source_id.get(str(p.get("mid", "")))
|
||||||
|
ready = kind == "time" and self.now >= sim._number(p.get("time", 0)) * 1000
|
||||||
|
ready |= kind == "monDead" and source is not None and source.state == "dead"
|
||||||
|
ready |= kind == "waveStart" and self.wave.get(sim._int(p.get("team", 2)), 1) >= sim._int(p.get("wave", 1))
|
||||||
|
if not ready:
|
||||||
|
continue
|
||||||
|
self.triggers.remove(trigger)
|
||||||
|
self.event("aggregate_trigger", trigger_kind=kind)
|
||||||
|
for effect in trigger.get("effects", ()):
|
||||||
|
ep, ek = effect.get("para", {}), effect.get("type")
|
||||||
|
if ek == "unlockWave":
|
||||||
|
self.unlocked_waves[sim._int(ep.get("team", 2))].add(sim._int(ep.get("wave", 1)))
|
||||||
|
elif ek == "monJoin":
|
||||||
|
a = self.by_source_id.get(str(ep.get("mid", "")))
|
||||||
|
if a:
|
||||||
|
a.force_join = True
|
||||||
|
elif ek in ("startController", "stopController"):
|
||||||
|
for maker in self.makers:
|
||||||
|
if str(maker["vo"].get("id", "")) == str(ep.get("id", "")):
|
||||||
|
maker["active"] = ek == "startController"
|
||||||
|
|
||||||
|
def recruit(self):
|
||||||
|
self.gates()
|
||||||
|
for team in self.s.teams:
|
||||||
|
waiting = [a for a in self.actors if a.unit.team == team and a.state == "waiting"]
|
||||||
|
active = [a for a in self.actors if a.unit.team == team and a.state == "active" and not a.unit.is_object]
|
||||||
|
if waiting and not active:
|
||||||
|
wave = min(a.unit.wave for a in waiting)
|
||||||
|
if (team, wave) not in self.gated:
|
||||||
|
due = self.next_wave.setdefault((team, wave), self.now + (0 if wave <= 1 else 700))
|
||||||
|
if self.now >= due:
|
||||||
|
self.unlocked_waves[team].add(wave)
|
||||||
|
self.wave[team] = wave
|
||||||
|
counts = Counter(a.unit.team for a in self.active() if a.unit.count_unit)
|
||||||
|
for a in self.actors:
|
||||||
|
u = a.unit
|
||||||
|
if a.state != "waiting" or (not a.force_join and (
|
||||||
|
u.wave not in self.unlocked_waves[u.team] or self.now < max(0, u.join_time) * 1000
|
||||||
|
or u.source_id in self.join_gates)):
|
||||||
|
continue
|
||||||
|
if u.count_unit and counts[u.team] >= self.s.teams[u.team]["capacity"]:
|
||||||
|
continue
|
||||||
|
a.state, a.joined_ms = "active", self.now
|
||||||
|
counts[u.team] += int(u.count_unit)
|
||||||
|
self.event("deploy", actor=u.key, team=u.team, wave=u.wave, count_unit=u.count_unit, ap_charged=0)
|
||||||
|
|
||||||
|
def generate(self, seconds):
|
||||||
|
for maker in self.makers:
|
||||||
|
p = maker["vo"].get("para", {})
|
||||||
|
parent = self.by_key.get(maker["owner"])
|
||||||
|
if not maker["active"] or parent is not None and parent.state != "active":
|
||||||
|
continue
|
||||||
|
after = sim._number(p.get("afterTime", 0))
|
||||||
|
before = sim._number(p.get("beforeTime", 0))
|
||||||
|
after = after * 1000 if after < 1000 else after
|
||||||
|
before = before * 1000 if before < 1000 else before
|
||||||
|
if self.now < after or before > 0 and self.now > before:
|
||||||
|
continue
|
||||||
|
maker["credit"] += seconds / max(1., sim._number(p.get("interval", 1000)) / 1000)
|
||||||
|
count = min(int(maker["credit"]), MAX_GENERATED - self.generated)
|
||||||
|
maker["credit"] -= count
|
||||||
|
for _ in range(count):
|
||||||
|
if len(self.actors) >= sim.MAX_UNITS:
|
||||||
|
self.resource_limited = True
|
||||||
|
return
|
||||||
|
spec = {"type": p.get("monType"), "autoValue": True, "level": p.get("level", 1),
|
||||||
|
"team": p.get("team", parent.unit.team if parent else 2), "mode": p.get("mode", 2),
|
||||||
|
"skill_1": 0, "skill_2": 0, "countUnit": False}
|
||||||
|
unit = sim._enemy(spec, {"team": spec["team"]}, self.tables, f"generated-{self.generated + 1}",
|
||||||
|
{}, lambda *a, **k: None, {})
|
||||||
|
hp = sim._int(p.get("hpMax") if p.get("hpMax") is not None else p.get("hp") if p.get("hp") is not None else unit.stats.hp)
|
||||||
|
unit = replace(unit, stats=replace(unit.stats, hp=hp, atk=sim._int(p.get("atk") if p.get("atk") is not None else unit.stats.atk)),
|
||||||
|
is_object=p.get("isObject", False) is True, source_id=f"-{self.generated + 1}")
|
||||||
|
if hp <= 0 or unit.stats.atk < 0 or unit.team not in self.s.teams:
|
||||||
|
raise sim.SimulationInputError("Generated monster attributes/team are invalid")
|
||||||
|
a = sim.Actor(unit, min(hp, sim._int(p.get("hp") if p.get("hp") is not None else hp)), state="active", joined_ms=self.now)
|
||||||
|
self.actors.append(a)
|
||||||
|
self.by_key[unit.key], self.by_source_id[unit.source_id] = a, a
|
||||||
|
self.expectations[unit.key], self.hp_rates[unit.key] = (1., 0.), []
|
||||||
|
self.generated += 1
|
||||||
|
self.event("aggregate_spawn", actor=unit.key, team=unit.team, hp=a.hp)
|
||||||
|
|
||||||
|
def budgets(self, seconds):
|
||||||
|
active = self.active()
|
||||||
|
damage, healing, dealt = Counter(), Counter(), Counter()
|
||||||
|
team_rates = Counter()
|
||||||
|
for a in active:
|
||||||
|
u = a.unit
|
||||||
|
locked = self.by_source_id.get(u.lock_target)
|
||||||
|
targets = [locked] if locked and locked.state == "active" else [b for b in active if b.unit.team != u.team]
|
||||||
|
if not locked:
|
||||||
|
targets = [b for b in targets if b.unit.auto_target] or targets
|
||||||
|
if not u.is_object and targets and u.ai_search != 0:
|
||||||
|
for b in targets:
|
||||||
|
attack = u.stats.atk
|
||||||
|
counter = self.tables["monster_setting"]["element"].get(str(u.stats.element), {}).get("counter")
|
||||||
|
if counter == b.unit.stats.element:
|
||||||
|
attack = int(attack * self.game["counterAdd"])
|
||||||
|
hit = sim.damage_roll(attack, u.stats.dex, b.unit.stats, self.game, _MeanRoll())
|
||||||
|
quarter = int((u.stats.dex - b.unit.stats.dex) / 4)
|
||||||
|
crit = min(1., .02 + u.stats.crit / 100 + (quarter / (quarter + 120) if quarter >= 0 else 0))
|
||||||
|
hit *= 1 + crit * (self.game["critAdd"] - 1)
|
||||||
|
element = str(u.stats.element)
|
||||||
|
if element in b.unit.hurt_types and element in b.unit.hurt_elements:
|
||||||
|
hit *= b.unit.hurt_elements[element]
|
||||||
|
elif str(u.species) in b.unit.hurt_types:
|
||||||
|
hit *= b.unit.hurt_types[str(u.species)]
|
||||||
|
hit = max(0, int(hit * (1 - b.unit.stats.damage_reduction) * self.expectations[u.key][0]))
|
||||||
|
hit = self.final_damage(hit, a, b)
|
||||||
|
# Apply the desktop cap per expected hit, before summing DPS.
|
||||||
|
amount = hit * 1000 / u.stats.attack_ms * seconds / len(targets)
|
||||||
|
damage[b.unit.key] += amount
|
||||||
|
dealt[u.key] += amount
|
||||||
|
team_rates[u.team] += amount / seconds
|
||||||
|
if hit > 80000 and (u.key, b.unit.key) not in self.damage_checks:
|
||||||
|
self.damage_checks.add((u.key, b.unit.key))
|
||||||
|
self.anomaly("+10overdamage", points=10, damage=hit, hurt_team=b.unit.team,
|
||||||
|
actor=u.key, target=b.unit.key, approximate=True)
|
||||||
|
healing[u.key] += self.expectations[u.key][1] * seconds
|
||||||
|
for kind, rate, mid in self.hp_rates[u.key]:
|
||||||
|
if kind == "hp":
|
||||||
|
target = a if mid == "-1" else self.by_source_id.get(mid)
|
||||||
|
targets = [target] if target and target.state == "active" else []
|
||||||
|
else:
|
||||||
|
targets = [b for b in active if (b.unit.team == u.team) == (rate >= 0)]
|
||||||
|
for b in targets:
|
||||||
|
(healing if rate >= 0 else damage)[b.unit.key] += abs(rate) * seconds
|
||||||
|
for team, rate in team_rates.items():
|
||||||
|
self.peak_dps[team] = max(self.peak_dps[team], rate)
|
||||||
|
self.now += int(seconds * 1000)
|
||||||
|
for a in active:
|
||||||
|
key = a.unit.key
|
||||||
|
lost = min(a.hp, damage[key])
|
||||||
|
a.hp -= lost
|
||||||
|
a.total_hurt += damage[key]
|
||||||
|
self.hp_lost[a.unit.team] += lost
|
||||||
|
a.damage_dealt += dealt[key]
|
||||||
|
if a.unit.boss_point == -1:
|
||||||
|
self.boss_points += int(lost)
|
||||||
|
if lost:
|
||||||
|
self.event("damage", actor=None, target=key, damage=round(damage[key], 3),
|
||||||
|
hp_lost=round(lost, 3), hp=round(a.hp, 3), reason="aggregate_dps")
|
||||||
|
# Healing is a simultaneous sustain budget; it cannot resurrect.
|
||||||
|
if a.hp > 0:
|
||||||
|
gained = min(a.unit.stats.hp - a.hp, healing[key])
|
||||||
|
a.hp += gained
|
||||||
|
a.healed += gained
|
||||||
|
if gained:
|
||||||
|
self.event("heal", actor=key, amount=round(gained, 3), hp=round(a.hp, 3), reason="aggregate_sustain")
|
||||||
|
else:
|
||||||
|
a.hp = 0
|
||||||
|
self.finish_death(a)
|
||||||
|
|
||||||
|
def objectives(self):
|
||||||
|
if self.now >= self.s.duration_ms:
|
||||||
|
return "win" if 2 in self.s.win_types else "loss"
|
||||||
|
if not any(a.unit.team == 1 and a.state != "dead" for a in self.actors):
|
||||||
|
return "loss"
|
||||||
|
# A still-running generator represents a future enemy HP/DPS budget,
|
||||||
|
# including when its effective population bound has been reached.
|
||||||
|
future = any(m["active"] and (m["owner"] is None or self.by_key[m["owner"]].state != "dead")
|
||||||
|
and sim._int(m["vo"].get("para", {}).get("team", 2)) != 1
|
||||||
|
and (not sim._number(m["vo"].get("para", {}).get("beforeTime", 0)) or
|
||||||
|
self.now < (sim._number(m["vo"]["para"]["beforeTime"]) *
|
||||||
|
(1000 if sim._number(m["vo"]["para"]["beforeTime"]) < 1000 else 1)))
|
||||||
|
for m in self.makers)
|
||||||
|
if 1 in self.s.win_types and not future and not any(a.unit.team != 1 and a.state != "dead"
|
||||||
|
and (a.state == "active" or not a.unit.is_object) for a in self.actors):
|
||||||
|
return "win"
|
||||||
|
protected = [a for a in self.actors if a.unit.protect_target]
|
||||||
|
destroyed = [a for a in self.actors if a.unit.destroy_target]
|
||||||
|
if protected and (3 in self.s.lose_types and any(a.state == "dead" for a in protected)
|
||||||
|
or 4 in self.s.lose_types and all(a.state == "dead" for a in protected)):
|
||||||
|
return "loss"
|
||||||
|
if destroyed and (3 in self.s.win_types and any(a.state == "dead" for a in destroyed)
|
||||||
|
or 4 in self.s.win_types and all(a.state == "dead" for a in destroyed)):
|
||||||
|
return "win"
|
||||||
|
return None
|
||||||
|
|
||||||
|
def result(self, outcome, timeout_kind=None):
|
||||||
|
result = super().result(outcome, timeout_kind)
|
||||||
|
result["team_budgets"] = {str(team): {
|
||||||
|
"initial_hp": sum(u.stats.hp for u in self.s.units if u.team == team),
|
||||||
|
"remaining_hp": round(sum(a.hp for a in self.actors if a.unit.team == team), 3),
|
||||||
|
"peak_expected_dps": round(self.peak_dps[team], 3)} for team in self.s.teams}
|
||||||
|
result["generated_units"] = self.generated
|
||||||
|
result["spawn_bound_reached"] = self.generated >= MAX_GENERATED
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def simulate_quick(request, *, cancel_event=None, timeout=30., tables=None):
|
||||||
|
started = time.monotonic()
|
||||||
|
timeout = sim._number(timeout, "timeout")
|
||||||
|
if timeout < 0:
|
||||||
|
raise sim.SimulationInputError("timeout must be nonnegative")
|
||||||
|
tables = tables if tables is not None else sim.combat_tables()
|
||||||
|
scenario, report = prepare(request, tables)
|
||||||
|
if not report["supported"]:
|
||||||
|
return dict(report, outcome="unsupported", execution_status="unsupported", terminal=False,
|
||||||
|
terminal_reason="unsupported_scenario", elapsed_ms=0, elapsed_seconds=0, events=[])
|
||||||
|
try:
|
||||||
|
battle = _QuickBattle(scenario, report, tables, request)
|
||||||
|
for step in range(min(MAX_STEPS, scenario.duration_ms // 1000 + 1)):
|
||||||
|
if cancel_event is not None and cancel_event.is_set():
|
||||||
|
return battle.result("cancelled")
|
||||||
|
if time.monotonic() - started >= timeout:
|
||||||
|
return battle.result("timeout", "wall_clock")
|
||||||
|
battle.recruit()
|
||||||
|
battle.generate(min(1., (scenario.duration_ms - battle.now) / 1000))
|
||||||
|
outcome = battle.objectives()
|
||||||
|
if outcome:
|
||||||
|
reason = "battle_time_limit" if battle.now >= scenario.duration_ms else "elimination" if 1 in scenario.win_types else "objective"
|
||||||
|
battle.event("complete", outcome=outcome, reason=reason)
|
||||||
|
return dict(battle.result(outcome), terminal_reason=reason)
|
||||||
|
if battle.resource_limited:
|
||||||
|
return battle.result("timeout", "resource_limit")
|
||||||
|
battle.budgets(min(1., (scenario.duration_ms - battle.now) / 1000))
|
||||||
|
return battle.result("timeout", "resource_limit")
|
||||||
|
except (sim.SimulationInputError, KeyError, TypeError, ValueError, ZeroDivisionError):
|
||||||
|
# Do not include account material or arbitrary parameter values in errors.
|
||||||
|
return dict(report, supported=False, outcome="unsupported", execution_status="unsupported", terminal=False,
|
||||||
|
terminal_reason="invalid_numeric_battle_data", elapsed_ms=0, elapsed_seconds=0, events=[],
|
||||||
|
reasons=list(report["reasons"]) + ["Missing or invalid original numeric combat/controller data"])
|
||||||
@@ -419,11 +419,17 @@ class Scenario:
|
|||||||
triggers: tuple = ()
|
triggers: tuple = ()
|
||||||
|
|
||||||
|
|
||||||
def _prepare(request, tables):
|
def _prepare(request, tables, *, quick=False):
|
||||||
report = _envelope()
|
report = _envelope()
|
||||||
report.update(supported=False, reasons=[], implemented_skills=sorted(KNOWN_SKILLS))
|
report.update(supported=False, reasons=[], implemented_skills=sorted(KNOWN_SKILLS))
|
||||||
|
|
||||||
def diagnostic(code, message, *, ignored=False, blocking=False):
|
def diagnostic(code, message, *, ignored=False, blocking=False):
|
||||||
|
if quick and code in ("objective", "controller", "triggers", "unit_controller",
|
||||||
|
"unit_objective", "field_effect", "cosmetic_controller"):
|
||||||
|
record = {"code": "aggregate_approximation", "mechanic": code, "message": message}
|
||||||
|
if record not in report["diagnostics"]:
|
||||||
|
report["diagnostics"].append(record)
|
||||||
|
return
|
||||||
record = {"code": code, "message": message}
|
record = {"code": code, "message": message}
|
||||||
if record not in report["diagnostics"]:
|
if record not in report["diagnostics"]:
|
||||||
report["diagnostics"].append(record)
|
report["diagnostics"].append(record)
|
||||||
@@ -498,7 +504,9 @@ def _prepare(request, tables):
|
|||||||
units = [] # BattleCenter empties the master team before adding authored allies.
|
units = [] # BattleCenter empties the master team before adding authored allies.
|
||||||
configured_mons = [(team, mon) for team in battle.get("teams", ())
|
configured_mons = [(team, mon) for team in battle.get("teams", ())
|
||||||
for mon in team.get("mons", ()) if mon is not None]
|
for mon in team.get("mons", ()) if mon is not None]
|
||||||
unit_mids = {_int(mon.get("mid", -1)) for _, mon in configured_mons}
|
# AS3 int('') is zero for an authored default mid; keep stat parsing strict.
|
||||||
|
unit_mids = {_int(0 if mon.get("mid") == "" else mon.get("mid", -1))
|
||||||
|
for _, mon in configured_mons}
|
||||||
triggers = []
|
triggers = []
|
||||||
for entry in battle.get("triggers", ()) or ():
|
for entry in battle.get("triggers", ()) or ():
|
||||||
if mining:
|
if mining:
|
||||||
@@ -549,24 +557,26 @@ def _prepare(request, tables):
|
|||||||
if mining:
|
if mining:
|
||||||
if not any(u.destroy_target for u in units) or not any(u.protect_target for u in units):
|
if not any(u.destroy_target for u in units) or not any(u.protect_target for u in units):
|
||||||
diagnostic("unit_objective", "Mining requires actual destroy and protect target units", blocking=True)
|
diagnostic("unit_objective", "Mining requires actual destroy and protect target units", blocking=True)
|
||||||
elif not any(u.team != 1 and not u.is_object for u in units):
|
elif not quick and not any(u.team != 1 and not u.is_object for u in units):
|
||||||
raise SimulationInputError("Elimination battle must contain configured enemies")
|
raise SimulationInputError("Elimination battle must contain configured enemies")
|
||||||
for team in teams.values():
|
for team in teams.values():
|
||||||
if team["capacity"] <= 0 or team["initial"] < 0:
|
if (team["capacity"] < 0 if quick else team["capacity"] <= 0) or team["initial"] < 0:
|
||||||
raise SimulationInputError("Original team capacity/AP is invalid")
|
raise SimulationInputError("Original team capacity/AP is invalid")
|
||||||
field_config = battle.get("battleField")
|
field_config = battle.get("battleField")
|
||||||
|
if quick and not isinstance(field_config, Mapping):
|
||||||
|
field_config = {}
|
||||||
if not isinstance(field_config, Mapping):
|
if not isinstance(field_config, Mapping):
|
||||||
raise SimulationInputError("Full original battleField configuration is required")
|
raise SimulationInputError("Full original battleField configuration is required")
|
||||||
if field_config.get("fieldMode"):
|
if field_config.get("fieldMode"):
|
||||||
name = field_config.get("fieldName", "default")
|
name = field_config.get("fieldName", "default")
|
||||||
original_field = tables["setting"]["defaultField"].get(name)
|
original_field = tables["setting"]["defaultField"].get(name)
|
||||||
if original_field is None:
|
if original_field is None and not quick:
|
||||||
raise SimulationInputError("Unknown original default battlefield")
|
raise SimulationInputError("Unknown original default battlefield")
|
||||||
field_config = dict(original_field, mapObjects=field_config.get("mapObjects", ()),
|
field_config = dict(original_field or {}, mapObjects=field_config.get("mapObjects", ()),
|
||||||
mapAreas=tuple(original_field.get("mapAreas", ())) + tuple(field_config.get("mapAreas", ())))
|
mapAreas=tuple((original_field or {}).get("mapAreas", ())) + tuple(field_config.get("mapAreas", ())))
|
||||||
points = {p["id"]: p for p in field_config.get("mapPoints", ())}
|
points = {p["id"]: p for p in field_config.get("mapPoints", ())}
|
||||||
areas = {a["id"]: a for a in field_config.get("mapAreas", ())}
|
areas = {a["id"]: a for a in field_config.get("mapAreas", ())}
|
||||||
if "area_battlefield" not in areas or not points:
|
if not quick and ("area_battlefield" not in areas or not points):
|
||||||
raise SimulationInputError("Battlefield needs original points and area_battlefield")
|
raise SimulationInputError("Battlefield needs original points and area_battlefield")
|
||||||
for area in areas.values():
|
for area in areas.values():
|
||||||
if area.get("type", "none") not in (("none", "pow") if mining else ("none",)):
|
if area.get("type", "none") not in (("none", "pow") if mining else ("none",)):
|
||||||
@@ -582,11 +592,11 @@ def _prepare(request, tables):
|
|||||||
diagnostic("attack_profile", f"Attack {u.attack_type} has no bundled source profile; original default AttackType1 is approximated", ignored=True)
|
diagnostic("attack_profile", f"Attack {u.attack_type} has no bundled source profile; original default AttackType1 is approximated", ignored=True)
|
||||||
if u.effects.get("sunFire") or u.effects.get("moonHeal") or u.effects.get("deadBoom"):
|
if u.effects.get("sunFire") or u.effects.get("moonHeal") or u.effects.get("deadBoom"):
|
||||||
diagnostic("unimplemented_effect", "sunFire, moonHeal and deadBoom effects are omitted where present", ignored=True)
|
diagnostic("unimplemented_effect", "sunFire, moonHeal and deadBoom effects are omitted where present", ignored=True)
|
||||||
if u.attack_area and u.attack_area not in areas:
|
if not quick and u.attack_area and u.attack_area not in areas:
|
||||||
raise SimulationInputError("Configured attackArea is absent from original battlefield")
|
raise SimulationInputError("Configured attackArea is absent from original battlefield")
|
||||||
if u.join_point and not u.join_point.startswith("mon_") and u.join_point not in points:
|
if not quick and u.join_point and not u.join_point.startswith("mon_") and u.join_point not in points:
|
||||||
raise SimulationInputError("Configured joinPoint is absent from original battlefield")
|
raise SimulationInputError("Configured joinPoint is absent from original battlefield")
|
||||||
if not u.join_point:
|
if not quick and not u.join_point:
|
||||||
default_point = f"point_team{u.team}_{'fore' if u.position < 3 else 'back'}{u.position + 1 if u.position < 3 else u.position - 2}"
|
default_point = f"point_team{u.team}_{'fore' if u.position < 3 else 'back'}{u.position + 1 if u.position < 3 else u.position - 2}"
|
||||||
if (u.position >= 6 or default_point not in points) and not any(
|
if (u.position >= 6 or default_point not in points) and not any(
|
||||||
p.startswith(f"point_team{u.team}_wait") for p in points):
|
p.startswith(f"point_team{u.team}_wait") for p in points):
|
||||||
@@ -629,7 +639,7 @@ def _unit_preview(unit):
|
|||||||
|
|
||||||
|
|
||||||
def _snapshot_anomalies(mon, unit, tables):
|
def _snapshot_anomalies(mon, unit, tables):
|
||||||
"""Port the observable input checks from BattlePanel.cheatCheck.
|
"""Check source input bounds, using the cultivation potential cap.
|
||||||
|
|
||||||
These are a subset of the final original checks, not a claim to have run
|
These are a subset of the final original checks, not a claim to have run
|
||||||
them all. Keep raw input values; never repair them to make checks pass.
|
them all. Keep raw input values; never repair them to make checks pass.
|
||||||
@@ -644,7 +654,6 @@ def _snapshot_anomalies(mon, unit, tables):
|
|||||||
|
|
||||||
row = tables["monster_info"][str(unit.species)]
|
row = tables["monster_info"][str(unit.species)]
|
||||||
potential_level = _int(mon.get("potentialLevel", 1))
|
potential_level = _int(mon.get("potentialLevel", 1))
|
||||||
tp = min(4, _int(mon.get("tpLevel", 0)))
|
|
||||||
if _number(mon.get("feel", 0)) > 200:
|
if _number(mon.get("feel", 0)) > 200:
|
||||||
add("+15overfeel", 50, feel=mon["feel"])
|
add("+15overfeel", 50, feel=mon["feel"])
|
||||||
potential = tables["potential_info"]["potential"].get(str(row["job"]), {}).get(str(row["star"]), {})
|
potential = tables["potential_info"]["potential"].get(str(row["job"]), {}).get(str(row["star"]), {})
|
||||||
@@ -653,7 +662,9 @@ def _snapshot_anomalies(mon, unit, tables):
|
|||||||
maximum = row[stat] + row[stat + "_grow_max"] * (_int(mon["level"]) + potential_level) * 4
|
maximum = row[stat] + row[stat + "_grow_max"] * (_int(mon["level"]) + potential_level) * 4
|
||||||
if value > maximum:
|
if value > maximum:
|
||||||
add("+15overgrow", 25, stat=stat, value=value, source_maximum=maximum)
|
add("+15overgrow", 25, stat=stat, value=value, source_maximum=maximum)
|
||||||
max_potential = potential.get(stat, 0) + potential.get(stat + "TpAdd", 0) * tp
|
# PotentialPanel.as:102,245 uses cultivation, not TP level. The old
|
||||||
|
# BattlePanel.cheatCheck bound can reject normally cultivated values.
|
||||||
|
max_potential = potential.get(stat, 0) + potential.get(stat + "TpAdd", 0) * (potential_level - 1)
|
||||||
value_potential = _number(mon.get("p" + stat.capitalize(), 0))
|
value_potential = _number(mon.get("p" + stat.capitalize(), 0))
|
||||||
if potential and value_potential > max_potential * 1.5:
|
if potential and value_potential > max_potential * 1.5:
|
||||||
add("+15overpoten", 30, stat=stat, value=value_potential, source_maximum=max_potential * 1.5)
|
add("+15overpoten", 30, stat=stat, value=value_potential, source_maximum=max_potential * 1.5)
|
||||||
@@ -1335,7 +1346,7 @@ def _execution_failure(outcome, reason, *, supported=True):
|
|||||||
|
|
||||||
|
|
||||||
class ExperimentalBattleRuntime:
|
class ExperimentalBattleRuntime:
|
||||||
"""Offline experimental adapter. run always executes a fixed worker module.
|
"""Fast aggregate adapter. run always executes a fixed offline worker module.
|
||||||
|
|
||||||
supported means this approximate model is runnable, not server settlement
|
supported means this approximate model is runnable, not server settlement
|
||||||
eligibility. Calls do not mutate the request, cache, or input snapshot.
|
eligibility. Calls do not mutate the request, cache, or input snapshot.
|
||||||
@@ -1343,7 +1354,8 @@ class ExperimentalBattleRuntime:
|
|||||||
|
|
||||||
def inspect(self, request):
|
def inspect(self, request):
|
||||||
try:
|
try:
|
||||||
_, report = _prepare(request, combat_tables())
|
from .battle_quick import prepare
|
||||||
|
_, report = prepare(request, combat_tables())
|
||||||
return report
|
return report
|
||||||
except SimulationInputError as exc:
|
except SimulationInputError as exc:
|
||||||
result = _envelope()
|
result = _envelope()
|
||||||
@@ -1351,6 +1363,8 @@ class ExperimentalBattleRuntime:
|
|||||||
diagnostics=[{"code": "static_data", "message": str(exc)}])
|
diagnostics=[{"code": "static_data", "message": str(exc)}])
|
||||||
|
|
||||||
def run(self, request, *, cancel_event=None, timeout=30.0):
|
def run(self, request, *, cancel_event=None, timeout=30.0):
|
||||||
|
import tempfile
|
||||||
|
|
||||||
timeout = _number(timeout, "timeout")
|
timeout = _number(timeout, "timeout")
|
||||||
if timeout < 0:
|
if timeout < 0:
|
||||||
raise SimulationInputError("timeout must be nonnegative")
|
raise SimulationInputError("timeout must be nonnegative")
|
||||||
@@ -1368,13 +1382,18 @@ class ExperimentalBattleRuntime:
|
|||||||
started = time.monotonic()
|
started = time.monotonic()
|
||||||
process = None
|
process = None
|
||||||
try:
|
try:
|
||||||
|
# POSIX communicate(None) retries do not resume a partial stdin write.
|
||||||
|
# A bounded, rewound file gives the child all input and EOF once;
|
||||||
|
# its inherited handle remains valid after the parent closes its copy.
|
||||||
|
with tempfile.TemporaryFile(mode="w+b") as input_stream:
|
||||||
|
input_stream.write(wire)
|
||||||
|
input_stream.seek(0)
|
||||||
process = subprocess.Popen(
|
process = subprocess.Popen(
|
||||||
[sys.executable, "-m", "ranch_assistant.battle_simulator", "--worker"],
|
[sys.executable, "-m", "ranch_assistant.battle_simulator", "--worker"],
|
||||||
cwd=str(Path(__file__).resolve().parent.parent),
|
cwd=str(Path(__file__).resolve().parent.parent),
|
||||||
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
stdin=input_stream, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||||
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
|
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
|
||||||
)
|
)
|
||||||
pending_input = wire
|
|
||||||
while True:
|
while True:
|
||||||
if cancel_event is not None and cancel_event.is_set():
|
if cancel_event is not None and cancel_event.is_set():
|
||||||
return _execution_failure("cancelled", "worker_cancelled")
|
return _execution_failure("cancelled", "worker_cancelled")
|
||||||
@@ -1382,10 +1401,10 @@ class ExperimentalBattleRuntime:
|
|||||||
if left <= 0:
|
if left <= 0:
|
||||||
return _execution_failure("timeout", "worker_wall_clock_limit")
|
return _execution_failure("timeout", "worker_wall_clock_limit")
|
||||||
try:
|
try:
|
||||||
stdout, stderr = process.communicate(input=pending_input, timeout=min(.05, left))
|
stdout, stderr = process.communicate(timeout=min(.05, left))
|
||||||
break
|
break
|
||||||
except subprocess.TimeoutExpired:
|
except subprocess.TimeoutExpired:
|
||||||
pending_input = None
|
pass
|
||||||
if len(stdout) > MAX_WIRE_BYTES or len(stderr) > 65536:
|
if len(stdout) > MAX_WIRE_BYTES or len(stderr) > 65536:
|
||||||
return _execution_failure("error", "worker_output_exceeds_limit")
|
return _execution_failure("error", "worker_output_exceeds_limit")
|
||||||
result = json.loads(stdout)
|
result = json.loads(stdout)
|
||||||
@@ -1418,7 +1437,8 @@ def _worker():
|
|||||||
if len(wire) > MAX_WIRE_BYTES:
|
if len(wire) > MAX_WIRE_BYTES:
|
||||||
raise SimulationInputError("Worker input exceeds limit")
|
raise SimulationInputError("Worker input exceeds limit")
|
||||||
payload = json.loads(wire)
|
payload = json.loads(wire)
|
||||||
result = simulate(payload["request"], timeout=payload.get("timeout", 30.0))
|
from .battle_quick import simulate_quick
|
||||||
|
result = simulate_quick(payload["request"], timeout=payload.get("timeout", 30.0))
|
||||||
if result.get("outcome") == "unsupported":
|
if result.get("outcome") == "unsupported":
|
||||||
result.update(execution_status="unsupported", terminal=False, terminal_reason="unsupported_scenario")
|
result.update(execution_status="unsupported", terminal=False, terminal_reason="unsupported_scenario")
|
||||||
encoded = json.dumps(result, ensure_ascii=True, allow_nan=False,
|
encoded = json.dumps(result, ensure_ascii=True, allow_nan=False,
|
||||||
|
|||||||
+499
-61
@@ -30,7 +30,7 @@ from .drop_statistics import event_reward
|
|||||||
from .maps import stages
|
from .maps import stages
|
||||||
from .resource_stages import resource_entry_reason, item_requirements, available_item_count
|
from .resource_stages import resource_entry_reason, item_requirements, available_item_count
|
||||||
from .quests import indexed, stage_has_level
|
from .quests import indexed, stage_has_level
|
||||||
from .sweeping import SweepPolicy
|
from .sweeping import SweepPolicy, hidden_stage_id
|
||||||
from .team_availability import team_availability_reason
|
from .team_availability import team_availability_reason
|
||||||
|
|
||||||
|
|
||||||
@@ -87,6 +87,8 @@ def gameplay_response(response):
|
|||||||
|
|
||||||
_locks_guard = threading.Lock()
|
_locks_guard = threading.Lock()
|
||||||
_locks = {}
|
_locks = {}
|
||||||
|
SWEEP_KINDS = ("map_sweep", "sweep", "progression_sweep", "progression_farm_sweep", "progression_map_sweep")
|
||||||
|
COMBAT_KINDS = ("progression_battle", "map_battle", "stage_battle", "battle", "task_battle") + SWEEP_KINDS
|
||||||
|
|
||||||
|
|
||||||
def account_lock(path):
|
def account_lock(path):
|
||||||
@@ -155,7 +157,7 @@ class BattleJournal:
|
|||||||
self.reload()
|
self.reload()
|
||||||
return deepcopy(list(reversed(self.role(snapshot)["records"])))
|
return deepcopy(list(reversed(self.role(snapshot)["records"])))
|
||||||
|
|
||||||
def begin(self, snapshot, intent, *, kind=None):
|
def begin(self, snapshot, intent, *, kind=None, sweep_entry=None, sweep_phase=None):
|
||||||
if self.pending(snapshot):
|
if self.pending(snapshot):
|
||||||
raise ValueError("有待核对的任务 / 战斗,禁止重复开始")
|
raise ValueError("有待核对的任务 / 战斗,禁止重复开始")
|
||||||
record = {name: public_data(value(intent, name)) for name in (
|
record = {name: public_data(value(intent, name)) for name in (
|
||||||
@@ -170,8 +172,17 @@ class BattleJournal:
|
|||||||
"loop_time": snapshot.raw.get("history", {}).get("loopTaskTime"),
|
"loop_time": snapshot.raw.get("history", {}).get("loopTaskTime"),
|
||||||
"passed": stage_has_level(snapshot.raw.get("history", {}), "passStage",
|
"passed": stage_has_level(snapshot.raw.get("history", {}), "passStage",
|
||||||
value(intent, "stage_id", ""), value(intent, "difficulty", "1"))})
|
value(intent, "stage_id", ""), value(intent, "difficulty", "1"))})
|
||||||
|
if sweep_entry is not None:
|
||||||
|
legacy_archive = sweep_phase == "legacy_hidden_archived" and sweep_entry.get("role_id") is None
|
||||||
|
if (not legacy_archive and str(sweep_entry.get("role_id")) != role_id(snapshot)) or not sweep_entry.get("sampleId"):
|
||||||
|
raise ValueError("扫荡交接角色或原始编号缺失")
|
||||||
|
record.update(sweep_sample_id=sweep_entry["sampleId"], sweep_entry=public_data(sweep_entry),
|
||||||
|
sweep_entry_digest=digest(public_data(sweep_entry)), phase=sweep_phase or record["phase"])
|
||||||
if value(intent, "token") and value(intent, "account_key"):
|
if value(intent, "token") and value(intent, "account_key"):
|
||||||
record.update(intent_id=value(intent, "token"), account_key=value(intent, "account_key"))
|
record.update(intent_id=value(intent, "token"), account_key=value(intent, "account_key"))
|
||||||
|
if record.get("source_task_type_id") and not record.get("source_task_id"):
|
||||||
|
from .progression import ProgressionPlanner
|
||||||
|
record["source_offer_day"] = ProgressionPlanner._loop_day(snapshot, snapshot.now - 10)
|
||||||
state = self.role(snapshot)
|
state = self.role(snapshot)
|
||||||
state["records"].append(record)
|
state["records"].append(record)
|
||||||
state["pending"] = record["attempt_id"]
|
state["pending"] = record["attempt_id"]
|
||||||
@@ -187,9 +198,10 @@ class BattleJournal:
|
|||||||
record.update(phase="done", outcome=outcome, message=message, finished_at=time.time())
|
record.update(phase="done", outcome=outcome, message=message, finished_at=time.time())
|
||||||
if state["pending"] == record["attempt_id"]:
|
if state["pending"] == record["attempt_id"]:
|
||||||
state["pending"] = None
|
state["pending"] = None
|
||||||
if outcome == "loss" and record.get("kind") != "map_battle":
|
shared_loss_budget = record.get("kind") != "map_battle" and not record.get("sweep_sample_id")
|
||||||
|
if outcome == "loss" and shared_loss_budget:
|
||||||
state["losses"] += 1
|
state["losses"] += 1
|
||||||
elif outcome == "win" and record.get("kind") != "map_battle":
|
elif outcome == "win" and shared_loss_budget:
|
||||||
state["losses"] = 0
|
state["losses"] = 0
|
||||||
self.save()
|
self.save()
|
||||||
|
|
||||||
@@ -427,7 +439,9 @@ class BattleOrchestrator:
|
|||||||
"requires_realtime_wait", "wall_time_ms", "trace_path", "resource_identity", "terminal_reason", "settlement_eligible",
|
"requires_realtime_wait", "wall_time_ms", "trace_path", "resource_identity", "terminal_reason", "settlement_eligible",
|
||||||
"experimental_settlement_eligible", "execution_mode", "execution_status", "terminal", "diagnostics",
|
"experimental_settlement_eligible", "execution_mode", "execution_status", "terminal", "diagnostics",
|
||||||
"ignored_mechanics", "anomalies", "assumptions", "experimental_eligibility_reasons", "omitted_events",
|
"ignored_mechanics", "anomalies", "assumptions", "experimental_eligibility_reasons", "omitted_events",
|
||||||
"damage_profile", "damage_multiplier", "damage_cap", "damage_profile_digest", "damage_profile_scope")}}
|
"model", "simulation_method", "team_budgets", "generated_units", "spawn_bound_reached",
|
||||||
|
"damage_profile", "damage_multiplier", "damage_cap", "damage_profile_digest", "damage_profile_scope",
|
||||||
|
"supported", "timeout_kind")}}
|
||||||
trace = value(result, "trace")
|
trace = value(result, "trace")
|
||||||
if trace is None:
|
if trace is None:
|
||||||
trace = value(result, "events")
|
trace = value(result, "events")
|
||||||
@@ -440,8 +454,92 @@ class BattleOrchestrator:
|
|||||||
evidence["trace"] = public_data(trace)
|
evidence["trace"] = public_data(trace)
|
||||||
return evidence
|
return evidence
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def combat_resource_digest():
|
||||||
|
# Bind retries to the same combat tables and quick-model mathematics.
|
||||||
|
# Worker transport changes do not alter this contract.
|
||||||
|
root = Path(__file__).parent
|
||||||
|
return digest([hashlib.sha256(path.read_bytes()).hexdigest() for path in
|
||||||
|
(root / "data" / "combat_manifest.json", root / "battle_quick.py")])
|
||||||
|
|
||||||
|
def save_combat_request(self, record, request):
|
||||||
|
if request.get("battle_mode") != "experimental":
|
||||||
|
if request.get("battle_kind") != "hidden":
|
||||||
|
return {}
|
||||||
|
combat = public_data(request)
|
||||||
|
return {"combat_request": combat, "combat_request_digest": digest(combat),
|
||||||
|
"combat_resource_digest": self.combat_resource_digest()}
|
||||||
|
from .battle_simulator import _transport_request
|
||||||
|
combat = public_data(_transport_request(request))
|
||||||
|
raw = combat.get("roster")
|
||||||
|
if isinstance(raw, dict):
|
||||||
|
teams = [{key: row[key] for key in ("teamName", "teamType", "monsters") if key in row}
|
||||||
|
for row in raw.get("teams", []) if row.get("teamName") == combat["team"]]
|
||||||
|
for row in teams:
|
||||||
|
members = row.get("monsters") or []
|
||||||
|
if isinstance(members, str):
|
||||||
|
members = members.split(",")
|
||||||
|
# Preserve lineup order and empty slots; exploration helpers
|
||||||
|
# discard those slots and therefore cannot normalize combat.
|
||||||
|
row["monsters"] = [int(mid) if str(mid).strip() else 0 for mid in members]
|
||||||
|
ids = {str(mid) for row in teams for mid in row["monsters"]}
|
||||||
|
if not teams:
|
||||||
|
ids = set(combat["team"].split(","))
|
||||||
|
fields = {"id", "typeId", "level", "mode", "tpLevel", "feel", "upStar", "potentialLevel", "skin", "controller",
|
||||||
|
"skill_1", "skill_2", "skill_1_lv", "skill_2_lv", *["equip" + str(i) for i in range(1, 6)],
|
||||||
|
*[prefix + stat for prefix in ("g", "p") for stat in ("Atk", "Def", "Hp", "Dex")]}
|
||||||
|
raw["teams"] = teams
|
||||||
|
raw["monsters"] = [{key: val for key, val in row.items() if key in fields}
|
||||||
|
for row in raw.get("monsters", []) if str(row.get("id")) in ids]
|
||||||
|
raw["monsterAttributes"] = [row for row in raw.get("monsterAttributes", []) or [] if str(row.get("monsterId")) in ids]
|
||||||
|
combat["battle_mode"] = "experimental"
|
||||||
|
return {"combat_request": combat, "combat_request_digest": digest(combat),
|
||||||
|
"combat_resource_digest": self.combat_resource_digest()}
|
||||||
|
|
||||||
|
def accept_runtime_result(self, record, request, result, started, cancel):
|
||||||
|
mode = request.get("battle_mode", "original")
|
||||||
|
evidence = self.runtime_evidence(result, mode)
|
||||||
|
for key in ("damage_profile", "damage_multiplier", "damage_cap", "damage_profile_digest", "damage_profile_scope"):
|
||||||
|
if evidence.get(key) is None:
|
||||||
|
evidence.pop(key, None)
|
||||||
|
self.journal.update(record, "runtime_returned", runtime_outcome=value(result, "outcome"), **evidence)
|
||||||
|
outcome, data = value(result, "outcome"), value(result, "battle_data")
|
||||||
|
eligible = outcome in ("win", "loss")
|
||||||
|
if mode == "experimental":
|
||||||
|
eligible = (eligible and value(result, "experimental_settlement_eligible") is True
|
||||||
|
and value(result, "execution_mode") == "experimental" and value(result, "execution_status") == "completed"
|
||||||
|
and value(result, "supported") is True and value(result, "terminal") is True
|
||||||
|
and value(result, "approximate") is True and value(result, "faithful") is False
|
||||||
|
and not value(result, "anomalies") and not any(row.get("blocking") is True
|
||||||
|
for row in value(result, "diagnostics", []) or [] if isinstance(row, dict)))
|
||||||
|
else:
|
||||||
|
eligible = (eligible and value(result, "settlement_eligible") is True
|
||||||
|
and value(result, "faithful") is True and value(result, "approximate") is not True)
|
||||||
|
if not eligible or not isinstance(data, dict) or type(data.get("win")) is not bool:
|
||||||
|
message = ("本地战斗运行超时,已入场但尚无战果,等待恢复核对" if value(result, "execution_status") == "timed_out"
|
||||||
|
else "战斗已取消、超时或结果不确定,等待核对")
|
||||||
|
self._unknown(record, message)
|
||||||
|
return False
|
||||||
|
if data["win"] != (outcome == "win"):
|
||||||
|
self._unknown(record, "运行结果与战果胜负不一致,未提交结算")
|
||||||
|
return False
|
||||||
|
position = data.get("battlePosition")
|
||||||
|
if (not isinstance(position, dict) or {k: v for k, v in position.items() if v is not None}
|
||||||
|
!= {k: v for k, v in request["battle_position"].items() if v is not None}):
|
||||||
|
self._unknown(record, "运行时战果定位不匹配,未提交结算")
|
||||||
|
return False
|
||||||
|
# A generation cancellation does not invalidate an already computed result.
|
||||||
|
self.journal.update(record, "runtime_complete", battle_data=data)
|
||||||
|
ready = self.wait_for_battle_clock(record, request, result, data, started, cancel)
|
||||||
|
if cancel.is_set():
|
||||||
|
self._unknown(record, "等待战斗时钟期间已取消,开战记录保留待核对")
|
||||||
|
return False
|
||||||
|
return ready
|
||||||
|
|
||||||
def wait_for_battle_clock(self, record, request, result, data, started, cancel):
|
def wait_for_battle_clock(self, record, request, result, data, started, cancel):
|
||||||
if value(result, "requires_realtime_wait") is not True:
|
if value(result, "requires_realtime_wait") is not True:
|
||||||
|
self.journal.update(record, "waiting_for_battle_clock", battle_clock_seconds=0,
|
||||||
|
battle_ready_at=time.time(), resume_clock_ready=True)
|
||||||
return True
|
return True
|
||||||
duration = None
|
duration = None
|
||||||
for field, scale in (("model_elapsed_ms", .001), ("battle_elapsed_ms", .001), ("elapsed_ms", .001),
|
for field, scale in (("model_elapsed_ms", .001), ("battle_elapsed_ms", .001), ("elapsed_ms", .001),
|
||||||
@@ -470,39 +568,161 @@ class BattleOrchestrator:
|
|||||||
self._unknown(record, "等待战斗时钟期间已取消,开战记录保留待核对")
|
self._unknown(record, "等待战斗时钟期间已取消,开战记录保留待核对")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def confirmed_start(record):
|
||||||
|
response = record.get("start_response")
|
||||||
|
task = bool(record.get("task_id"))
|
||||||
|
path = "battleService/battleStart" if task else "stageService/stageStart"
|
||||||
|
hidden = hidden_stage_id(response)
|
||||||
|
confirmed_hidden = (not task and hidden is not None and record.get("battle_kind") == "hidden"
|
||||||
|
and hidden == str(record.get("stage_id")) and str(record.get("difficulty")) == "1")
|
||||||
|
return (record.get("start_path") == path and isinstance(response, dict)
|
||||||
|
and response.get("resCode", 0) in (0, "0") and (task or response.get("triggerEvent") is False
|
||||||
|
or type(response.get("triggerEvent")) is int and response["triggerEvent"] == 0 or confirmed_hidden))
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def source_matches(record, snapshot):
|
||||||
|
if not record.get("source_task_type_id"):
|
||||||
|
return True
|
||||||
|
if not record.get("source_task_id") and not record.get("source_step_number"):
|
||||||
|
from .progression import ProgressionPlanner
|
||||||
|
history = snapshot.raw.get("history", {})
|
||||||
|
offers = history.get("loopTask") or {}
|
||||||
|
today = ProgressionPlanner._loop_day(snapshot, snapshot.now - 10)
|
||||||
|
return (record.get("source_offer_day") == today and history.get("loopTaskTime") is not None
|
||||||
|
and ProgressionPlanner._loop_day(snapshot, history["loopTaskTime"]) == today
|
||||||
|
and isinstance(offers, dict) and any(str(key) == str(record["source_task_type_id"])
|
||||||
|
for rows in offers.values() if isinstance(rows, (list, tuple)) for key in rows)
|
||||||
|
and not any(str(task.get("typeId")) == str(record["source_task_type_id"])
|
||||||
|
for task in snapshot.raw.get("currentTasks", [])))
|
||||||
|
return any(str(task.get("id")) == str(record.get("source_task_id"))
|
||||||
|
and str(task.get("typeId")) == str(record["source_task_type_id"])
|
||||||
|
and str(task.get("curStep")) == str(record.get("source_step_number"))
|
||||||
|
for task in snapshot.raw.get("currentTasks", []))
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def legacy_stage_failure(record):
|
||||||
|
return (record.get("kind") == "stage_battle" and not record.get("task_id")
|
||||||
|
and not record.get("task_type_id") and record.get("battle_kind") == "ordinary_stage"
|
||||||
|
and record.get("stage_category") in (None, "", "ordinary") and record.get("source_task_type_id")
|
||||||
|
and record.get("execution_mode") == "experimental" and record.get("terminal") is False
|
||||||
|
and record.get("terminal_reason") in ("worker_wall_clock_limit", "worker_cancelled", "worker_interrupted")
|
||||||
|
and record.get("execution_status") in ("cancelled", "timed_out") and not record.get("battle_data"))
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def resumable_task_clock(record):
|
def resumable_task_clock(record):
|
||||||
common = bool(record and ((record.get("kind") == "progression_battle" and record.get("task_id"))
|
common = bool(record and record.get("kind") in COMBAT_KINDS
|
||||||
or (record.get("kind") == "map_battle" and not record.get("task_id")))
|
and ((record.get("execution_mode") == "experimental" and record.get("execution_status") == "completed"
|
||||||
and record.get("execution_mode") == "experimental" and record.get("execution_status") == "completed"
|
|
||||||
and record.get("experimental_settlement_eligible") is True and record.get("terminal") is True
|
and record.get("experimental_settlement_eligible") is True and record.get("terminal") is True
|
||||||
and record.get("approximate") is True and record.get("faithful") is False
|
and record.get("approximate") is True and record.get("faithful") is False)
|
||||||
|
or (record.get("battle_mode") == "original" and record.get("settlement_eligible") is True
|
||||||
|
and record.get("faithful") is True and record.get("approximate") is not True))
|
||||||
and not record.get("anomalies") and not any(row.get("blocking") is True
|
and not record.get("anomalies") and not any(row.get("blocking") is True
|
||||||
for row in record.get("diagnostics") or [] if isinstance(row, dict))
|
for row in record.get("diagnostics") or [] if isinstance(row, dict))
|
||||||
and isinstance(record.get("battle_data"), dict) and type(record["battle_data"].get("win")) is bool)
|
and isinstance(record.get("battle_data"), dict) and type(record["battle_data"].get("win")) is bool)
|
||||||
if not common:
|
if not common:
|
||||||
return False
|
return False
|
||||||
if (record.get("kind") == "map_battle" and record.get("phase") == "settlement_acknowledged"
|
if record.get("phase") in ("record_pending", "record_unknown"):
|
||||||
and record.get("settlement_confirmed") is True):
|
return False
|
||||||
|
if not record.get("task_id") and record.get("settlement_confirmed") is True:
|
||||||
return (record["battle_data"]["win"] is True and isinstance(record.get("response"), dict)
|
return (record["battle_data"]["win"] is True and isinstance(record.get("response"), dict)
|
||||||
and record["response"].get("resCode", 0) in (0, "0"))
|
and record["response"].get("resCode", 0) in (0, "0")
|
||||||
return (record.get("phase") in ("unknown", "waiting_for_battle_clock")
|
and (not record.get("record_dispatched") or record.get("record_confirmed") is True))
|
||||||
|
return (record.get("phase") in ("unknown", "runtime_complete", "waiting_for_battle_clock", "record_acknowledged")
|
||||||
and record.get("path") in ("", "battleService/battleStart", "stageService/stageStart")
|
and record.get("path") in ("", "battleService/battleStart", "stageService/stageStart")
|
||||||
and not record.get("settlement_confirmed") and not record.get("settlement_dispatched")
|
and not record.get("settlement_confirmed") and not record.get("settlement_dispatched")
|
||||||
|
and (not record.get("record_dispatched") or record.get("record_confirmed") is True)
|
||||||
and (record.get("resume_clock_ready") is True or
|
and (record.get("resume_clock_ready") is True or
|
||||||
|
record.get("phase") == "runtime_complete" or
|
||||||
record.get("message") == "等待战斗时钟期间已取消,开战记录保留待核对"))
|
record.get("message") == "等待战斗时钟期间已取消,开战记录保留待核对"))
|
||||||
|
|
||||||
|
def recovery_status(self, record, *, snapshot=None):
|
||||||
|
"""Read-only classification. Resumable never grants permission to write."""
|
||||||
|
def status(state, message=""):
|
||||||
|
return {"state": state, "resumable": state not in ("none", "blocked"), "message": message}
|
||||||
|
if not record:
|
||||||
|
return status("none")
|
||||||
|
if isinstance(snapshot, dict):
|
||||||
|
snapshot = SimpleNamespace(raw=snapshot, now=time.time())
|
||||||
|
if record.get("kind") not in COMBAT_KINDS:
|
||||||
|
return status("blocked", record.get("message") or "任务请求待核对,不能按战斗恢复")
|
||||||
|
if snapshot and str(record.get("role_id")) != role_id(snapshot):
|
||||||
|
return status("blocked", "角色与原入场记录不匹配,保留待核对记录")
|
||||||
|
preaccept = not record.get("source_task_id") and not record.get("source_step_number")
|
||||||
|
source_matches = snapshot is None or self.source_matches(record, snapshot)
|
||||||
|
if (not source_matches
|
||||||
|
and not (preaccept and self.legacy_stage_failure(record))):
|
||||||
|
return status("blocked", "角色或来源委托步骤已变化,保留原战斗记录等待核对")
|
||||||
|
if record.get("abandon_requested") and record.get("record_confirmed") is True and record.get("record_result") is False:
|
||||||
|
return status("finish_abandonment", "失败退出已确认,等待完成本地记录")
|
||||||
|
if self.resumable_task_clock(record):
|
||||||
|
return status("resume_result", "完整战果已保存,可续交尚未发送的结果")
|
||||||
|
if record.get("phase") in ("record_pending", "record_unknown") or record.get("record_dispatched"):
|
||||||
|
return status("blocked", "战果记录请求已发送但结果未确认,禁止重复发送")
|
||||||
|
if record.get("settlement_dispatched") or record.get("settlement_confirmed") or record.get("path") not in (
|
||||||
|
"", None, "stageService/stageStart", "battleService/battleStart"):
|
||||||
|
return status("blocked", "结算请求可能已发送,等待服务器证据,禁止重复结算")
|
||||||
|
if record.get("phase") == "prepared" and record.get("start_dispatched") is False and not record.get("start_response"):
|
||||||
|
return status("unsent", "开战请求尚未发送,可取消本地准备记录")
|
||||||
|
if not self.confirmed_start(record):
|
||||||
|
return status("blocked", "开战请求结果未确认,禁止重新入场或自动退出")
|
||||||
|
if (record.get("sweep_sample_id") and record.get("runtime_not_started") is True
|
||||||
|
and not record.get("combat_request") and self.hidden_sweep_inputs(record)):
|
||||||
|
return status("prepare_hidden_sweep", "隐藏入场及原始队伍已保存,可继续本次战斗")
|
||||||
|
interrupted = (record.get("runtime_not_started") is True or record.get("phase") in ("started", "running", "hidden_started") or
|
||||||
|
record.get("execution_status") in ("cancelled", "timed_out", "error"))
|
||||||
|
if not interrupted or record.get("battle_data"):
|
||||||
|
return status("blocked", "没有可验证的完整战果或安全恢复证据,保留待核对记录")
|
||||||
|
combat = record.get("combat_request")
|
||||||
|
if not isinstance(combat, dict):
|
||||||
|
# Original AIR: BattlePausePanel.yesEscapeHandler -> checkGameOver
|
||||||
|
# (run=True, winnerTeam=2) -> BattlePanel.showLose -> battleResult(false).
|
||||||
|
if self.legacy_stage_failure(record):
|
||||||
|
return status("abandon_stage", "旧记录缺少原始战斗输入,本地计算已超时或取消;开启后按原客户端退出协议记录失败,不推进任务")
|
||||||
|
return status("blocked", "旧记录缺少原始战斗输入,不能用当前属性重算;需要权威记录或原客户端退出核对")
|
||||||
|
if self.legacy_stage_failure(record) and (not source_matches or record.get("runtime_recovery_attempts", 0) >= 1):
|
||||||
|
return status("abandon_stage", "本地战斗未完成且来源委托已变化或恢复已用尽;开启后按原客户端退出协议记录失败")
|
||||||
|
if record.get("runtime_recovery_attempts", 0) >= 1:
|
||||||
|
return status("blocked", "本地战斗恢复已尝试一次仍未完成,保留入场记录等待核对")
|
||||||
|
if (record.get("battle_mode") != "experimental" and record.get("battle_kind") != "hidden"
|
||||||
|
or digest(combat) != record.get("combat_request_digest")
|
||||||
|
or self.combat_resource_digest() != record.get("combat_resource_digest")):
|
||||||
|
return status("blocked", "保存的原始战斗输入或资源校验不匹配,禁止改用当前属性重算")
|
||||||
|
return status("retry_local_runtime", "入场已确认且结算未发送,可用保存的原始输入恢复一次本地战斗")
|
||||||
|
|
||||||
def resume_task_clock(self, client, snapshot, intent, policy, *, cancel):
|
def resume_task_clock(self, client, snapshot, intent, policy, *, cancel):
|
||||||
"""Resume an unsent result, or finish recording a confirmed map settlement."""
|
"""Recover this entry only; never replay start or an uncertain server write."""
|
||||||
with self.journal.lock:
|
with self.journal.lock:
|
||||||
|
self.journal.reload()
|
||||||
record = self.journal.pending(snapshot)
|
record = self.journal.pending(snapshot)
|
||||||
if not policy.enabled or cancel.is_set() or not self.resumable_task_clock(record):
|
recovery = self.recovery_status(record, snapshot=snapshot)
|
||||||
|
if not policy.enabled or cancel.is_set() or not recovery["resumable"]:
|
||||||
return ""
|
return ""
|
||||||
if str(record.get("role_id")) != str(role_id(snapshot)):
|
if str(record.get("role_id")) != str(role_id(snapshot)):
|
||||||
return ""
|
return ""
|
||||||
if any(str(record.get(key)) != str(value(intent, key)) for key in
|
if any(str(record.get(key)) != str(value(intent, key)) for key in
|
||||||
("kind", "task_id", "task_type_id", "step_number")):
|
("kind", "task_id", "task_type_id", "step_number")):
|
||||||
return ""
|
return ""
|
||||||
|
if not record.get("task_id") and any(str(record.get(key)) != str(value(intent, key)) for key in
|
||||||
|
("stage_id", "difficulty", "battle_kind", "source_task_id", "source_task_type_id", "source_step_number")):
|
||||||
|
return ""
|
||||||
|
if recovery["state"] == "unsent":
|
||||||
|
if self.observer and (record.get("task_id") or record.get("map_roster_signature")):
|
||||||
|
self.observer("cancelled_before_start", intent, None)
|
||||||
|
self.journal.finish(snapshot, record, "cancelled", "已取消尚未发送的开战准备记录;未重新入场")
|
||||||
|
return record["message"]
|
||||||
|
if recovery["state"] in ("abandon_stage", "finish_abandonment"):
|
||||||
|
try:
|
||||||
|
if recovery["state"] == "abandon_stage":
|
||||||
|
self.journal.update(record, "abandon_pending", abandon_requested=True)
|
||||||
|
self._record(client, record, record["stage_id"], False, cancel=cancel)
|
||||||
|
self.journal.finish(snapshot, record, "abandoned", "已按原客户端退出协议确认失败;未提交胜利战果或推进来源委托")
|
||||||
|
return record["message"]
|
||||||
|
except CancelledBeforeDispatch:
|
||||||
|
return "策略已停止,失败退出请求尚未发送,保留原入场记录"
|
||||||
|
except Exception as error:
|
||||||
|
self._unknown(record, "失败退出请求结果未确认,禁止重复发送", error_type=type(error).__name__)
|
||||||
|
raise
|
||||||
task_battle = bool(record.get("task_id"))
|
task_battle = bool(record.get("task_id"))
|
||||||
if task_battle:
|
if task_battle:
|
||||||
task = next((row for row in snapshot.raw.get("currentTasks", [])
|
task = next((row for row in snapshot.raw.get("currentTasks", [])
|
||||||
@@ -515,6 +735,25 @@ class BattleOrchestrator:
|
|||||||
"stageLevel": None if task_battle else str(record.get("difficulty")),
|
"stageLevel": None if task_battle else str(record.get("difficulty")),
|
||||||
"taskTypeId": str(record["task_type_id"]) if task_battle else None,
|
"taskTypeId": str(record["task_type_id"]) if task_battle else None,
|
||||||
"taskStep": int(record["step_number"]) - 1 if task_battle else 0}
|
"taskStep": int(record["step_number"]) - 1 if task_battle else 0}
|
||||||
|
if recovery["state"] == "retry_local_runtime":
|
||||||
|
request = deepcopy(record["combat_request"])
|
||||||
|
position = request.get("battle_position")
|
||||||
|
if (not isinstance(position, dict) or {k: v for k, v in position.items() if v is not None}
|
||||||
|
!= {k: v for k, v in expected.items() if v is not None}
|
||||||
|
or request.get("team") != record.get("team")):
|
||||||
|
return "保存的原始战斗输入与入场定位不匹配,保留待核对记录"
|
||||||
|
supported, reason = self.inspect(request)
|
||||||
|
if not supported:
|
||||||
|
return "保存的原始战斗输入当前无法执行:" + reason
|
||||||
|
self.journal.update(record, "running", runtime_recovery_attempts=1, runtime_not_started=False)
|
||||||
|
try:
|
||||||
|
started = self.clock()
|
||||||
|
result = self.runtime.run(request.get("runtime_request", request), cancel_event=cancel)
|
||||||
|
if not self.accept_runtime_result(record, request, result, started, cancel):
|
||||||
|
return record["message"]
|
||||||
|
except Exception as error:
|
||||||
|
self._unknown(record, "本地战斗恢复未完成,保留原入场记录", error_type=type(error).__name__)
|
||||||
|
raise
|
||||||
data = record["battle_data"]
|
data = record["battle_data"]
|
||||||
position = data.get("battlePosition")
|
position = data.get("battlePosition")
|
||||||
if not isinstance(position, dict) or {key: val for key, val in position.items() if val is not None} != {
|
if not isinstance(position, dict) or {key: val for key, val in position.items() if val is not None} != {
|
||||||
@@ -523,6 +762,10 @@ class BattleOrchestrator:
|
|||||||
ready = 0 if record.get("settlement_confirmed") else record.get("battle_ready_at")
|
ready = 0 if record.get("settlement_confirmed") else record.get("battle_ready_at")
|
||||||
if ready is None:
|
if ready is None:
|
||||||
duration = record.get("battle_clock_seconds")
|
duration = record.get("battle_clock_seconds")
|
||||||
|
if duration is None and record.get("requires_realtime_wait") is not True:
|
||||||
|
duration = 0
|
||||||
|
if duration is None and type(record.get("elapsed_ms")) in (int, float):
|
||||||
|
duration = record["elapsed_ms"] / 1000
|
||||||
stamp = record.get("updated_at")
|
stamp = record.get("updated_at")
|
||||||
if any(type(number) not in (int, float) or not math.isfinite(number) or number < 0
|
if any(type(number) not in (int, float) or not math.isfinite(number) or number < 0
|
||||||
for number in (duration, stamp)):
|
for number in (duration, stamp)):
|
||||||
@@ -535,11 +778,12 @@ class BattleOrchestrator:
|
|||||||
return "已核对保存的战果;尚未到结算时间,2分钟内自动复查"
|
return "已核对保存的战果;尚未到结算时间,2分钟内自动复查"
|
||||||
try:
|
try:
|
||||||
if not data["win"]:
|
if not data["win"]:
|
||||||
if not task_battle or record.get("battle_kind") == "passStage":
|
if (not task_battle or record.get("battle_kind") == "passStage") and not record.get("record_confirmed"):
|
||||||
self._record(client, record, record["stage_id"], False, cancel=cancel)
|
self._record(client, record, record["stage_id"], False, cancel=cancel)
|
||||||
if self.observer:
|
if self.observer:
|
||||||
self.observer("loss", intent, None)
|
self.observer("loss", intent, None)
|
||||||
self.journal.finish(snapshot, record, "loss", "打不过(保存的模拟结果);未提交胜利结算")
|
self.journal.finish(snapshot, record, "loss", "打不过(保存的模拟结果);未提交胜利结算")
|
||||||
|
self._finish_hidden_sweep(snapshot, record)
|
||||||
return record["message"]
|
return record["message"]
|
||||||
response = record.get("response") if record.get("settlement_confirmed") else None
|
response = record.get("response") if record.get("settlement_confirmed") else None
|
||||||
if response is None:
|
if response is None:
|
||||||
@@ -548,18 +792,21 @@ class BattleOrchestrator:
|
|||||||
if task_battle:
|
if task_battle:
|
||||||
payload.update(taskId=int(record["task_id"]), taskTypeId=str(record["task_type_id"]), removeIds=None)
|
payload.update(taskId=int(record["task_id"]), taskTypeId=str(record["task_type_id"]), removeIds=None)
|
||||||
self.journal.update(record, "settlement_pending", path=path, settlement_dispatched=True)
|
self.journal.update(record, "settlement_pending", path=path, settlement_dispatched=True)
|
||||||
response = self._call(client, path, payload, cancel=cancel)
|
response = self._call(client, path, payload, cancel=cancel, require_code=record.get("battle_kind") == "hidden")
|
||||||
self.journal.update(record, "settlement_acknowledged", response=gameplay_response(response),
|
self.journal.update(record, "settlement_acknowledged", response=gameplay_response(response),
|
||||||
settlement_confirmed=True, reward=response["stageReward"] if response.get("stageReward") is not None else response.get("reward"))
|
settlement_confirmed=True, reward=response["stageReward"] if response.get("stageReward") is not None else response.get("reward"))
|
||||||
if not task_battle:
|
self._remember_hidden_sweep(snapshot, record)
|
||||||
self._record(client, record, record["stage_id"], True)
|
if not task_battle and not record.get("record_confirmed"):
|
||||||
|
self._record(client, record, record["stage_id"], True, cancel=cancel)
|
||||||
if self.observer:
|
if self.observer:
|
||||||
self.observer("settled", intent, response)
|
self.observer("settled", intent, response)
|
||||||
elif task_battle:
|
elif task_battle:
|
||||||
self.journal.checkpoint(snapshot, intent, response)
|
self.journal.checkpoint(snapshot, intent, response)
|
||||||
self.journal.finish(snapshot, record, "win", "已自动续交保存的战果;未重新开战或重新模拟")
|
self.journal.finish(snapshot, record, "win", "已恢复此入场的战果并确认结算;未重新开战")
|
||||||
|
self._finish_hidden_sweep(snapshot, record)
|
||||||
return record["message"]
|
return record["message"]
|
||||||
except CancelledBeforeDispatch:
|
except CancelledBeforeDispatch:
|
||||||
|
if not record.get("settlement_confirmed"):
|
||||||
self.journal.update(record, "waiting_for_battle_clock", path="battleService/battleStart" if task_battle else "stageService/stageStart",
|
self.journal.update(record, "waiting_for_battle_clock", path="battleService/battleStart" if task_battle else "stageService/stageStart",
|
||||||
settlement_dispatched=False, resume_clock_ready=True)
|
settlement_dispatched=False, resume_clock_ready=True)
|
||||||
return "策略已停止,保存的战果将在重新开启后续交"
|
return "策略已停止,保存的战果将在重新开启后续交"
|
||||||
@@ -600,24 +847,31 @@ class BattleOrchestrator:
|
|||||||
return "任务 / 战斗已取消,未开始"
|
return "任务 / 战斗已取消,未开始"
|
||||||
record = self.journal.begin(snapshot, intent)
|
record = self.journal.begin(snapshot, intent)
|
||||||
try:
|
try:
|
||||||
|
self.journal.update(record, "prepared", start_dispatched=False)
|
||||||
if self.observer:
|
if self.observer:
|
||||||
self.observer("started", intent, None)
|
self.observer("started", intent, None)
|
||||||
if value(intent, "task_id"):
|
if value(intent, "task_id"):
|
||||||
path, payload = "battleService/battleStart", {"battleType": "task", "taskTypeId": str(value(intent, "task_type_id"))}
|
path, payload = "battleService/battleStart", {"battleType": "task", "taskTypeId": str(value(intent, "task_type_id"))}
|
||||||
else:
|
else:
|
||||||
path, payload = "stageService/stageStart", {"stageTypeId": str(value(intent, "stage_id")), "stageLevel": str(value(intent, "difficulty", "1"))}
|
path, payload = "stageService/stageStart", {"stageTypeId": str(value(intent, "stage_id")), "stageLevel": str(value(intent, "difficulty", "1"))}
|
||||||
self.journal.update(record, "start_pending", start_path=path, input_digest=digest(public_data(request)),
|
self.journal.update(record, "start_pending",
|
||||||
|
**{key: val for key, val in self._inspection_evidence.items() if key not in ("battle_mode", "resource_identity")},
|
||||||
|
**self.save_combat_request(record, request),
|
||||||
|
path=path, start_path=path, start_dispatched=True, settlement_dispatched=False, record_dispatched=False,
|
||||||
|
input_digest=digest(public_data(request)),
|
||||||
team=policy.team, battle_mode=mode,
|
team=policy.team, battle_mode=mode,
|
||||||
resource_identity=(request.get("original_data") or {}).get("manifest", {}).get("source"))
|
resource_identity=(request.get("original_data") or {}).get("manifest", {}).get("source"))
|
||||||
try:
|
try:
|
||||||
started = self._call(client, path, payload, cancel=cancel)
|
started = self._call(client, path, payload, cancel=cancel)
|
||||||
except CancelledBeforeDispatch:
|
except CancelledBeforeDispatch:
|
||||||
|
self.journal.update(record, "start_pending", start_dispatched=False)
|
||||||
if self.observer:
|
if self.observer:
|
||||||
self.observer("cancelled_before_start", intent, None)
|
self.observer("cancelled_before_start", intent, None)
|
||||||
self.journal.finish(snapshot, record, "cancelled", "开战请求尚未发送,已取消;未消耗入场资源")
|
self.journal.finish(snapshot, record, "cancelled", "开战请求尚未发送,已取消;未消耗入场资源")
|
||||||
return record["message"]
|
return record["message"]
|
||||||
battle_started = self.clock()
|
battle_started = self.clock()
|
||||||
self.journal.update(record, "started", start_response=gameplay_response(started))
|
self.journal.update(record, "started", start_confirmed=True, start_confirmed_at=time.time(),
|
||||||
|
runtime_not_started=True, start_response=gameplay_response(started))
|
||||||
if not value(intent, "task_id"):
|
if not value(intent, "task_id"):
|
||||||
reward = event_reward(started)
|
reward = event_reward(started)
|
||||||
if reward is not None:
|
if reward is not None:
|
||||||
@@ -630,45 +884,209 @@ class BattleOrchestrator:
|
|||||||
if flag is not False and not (type(flag) is int and flag == 0):
|
if flag is not False and not (type(flag) is int and flag == 0):
|
||||||
event = started.get("stageEvent")
|
event = started.get("stageEvent")
|
||||||
if isinstance(event, dict) and event.get("hideStageId") is not None:
|
if isinstance(event, dict) and event.get("hideStageId") is not None:
|
||||||
hidden = str(event["hideStageId"])
|
request = self._hidden_request(record, snapshot, intent, policy, started)
|
||||||
fields = asdict(intent) if is_dataclass(intent) else dict(intent) if isinstance(intent, dict) else vars(intent).copy()
|
if request is None:
|
||||||
fields.update(stage_id=hidden, difficulty="1", battle_kind="hidden")
|
return self._unknown(record, "隐藏关卡编号或原入场证据无效,等待核对")
|
||||||
request = self.request(snapshot, fields, policy)
|
|
||||||
supported, reason = self.inspect(request)
|
supported, reason = self.inspect(request)
|
||||||
if not supported:
|
if not supported:
|
||||||
return self._unknown(record, "隐藏关卡待处理:" + reason)
|
return self._unknown(record, "隐藏关卡待处理:" + reason)
|
||||||
self.journal.update(record, "hidden_started", stage_id=hidden, difficulty="1")
|
|
||||||
else:
|
else:
|
||||||
return self._unknown(record, "探索事件或开战状态未知,等待核对")
|
return self._unknown(record, "探索事件或开战状态未知,等待核对")
|
||||||
|
return self._fight(client, snapshot, intent, request, record, battle_started, cancel)
|
||||||
|
except CancelledBeforeDispatch:
|
||||||
|
if not record.get("settlement_confirmed"):
|
||||||
|
self.journal.update(record, "waiting_for_battle_clock", path=record["start_path"],
|
||||||
|
settlement_dispatched=False, resume_clock_ready=True)
|
||||||
|
return "策略已停止,保存的战果将在重新开启后续交"
|
||||||
|
except Exception as error:
|
||||||
|
self._unknown(record, "任务 / 战斗请求或运行未确认;禁止自动重试", error_type=type(error).__name__)
|
||||||
|
raise
|
||||||
|
|
||||||
|
def _hidden_request(self, record, snapshot, intent, policy, started):
|
||||||
|
hidden = hidden_stage_id(started)
|
||||||
|
if hidden is None:
|
||||||
|
return None
|
||||||
|
fields = asdict(intent) if is_dataclass(intent) else dict(intent) if isinstance(intent, dict) else vars(intent).copy()
|
||||||
|
fields.update(stage_id=hidden, difficulty="1", battle_kind="hidden")
|
||||||
|
# Preserve the source intent for policies/observers, and the actual
|
||||||
|
# hidden BattlePosition for every runtime/settlement/recovery path.
|
||||||
|
self.journal.update(record, "hidden_started",
|
||||||
|
parent_stage_id=record.get("parent_stage_id") or record["stage_id"],
|
||||||
|
parent_difficulty=record.get("parent_difficulty") or record["difficulty"],
|
||||||
|
stage_id=hidden, difficulty="1", battle_kind="hidden", runtime_not_started=True)
|
||||||
|
request = self.request(snapshot, fields, policy)
|
||||||
|
self.journal.update(record, "hidden_started", **self.save_combat_request(record, request),
|
||||||
|
team=policy.team, battle_mode=request.get("battle_mode", "original"))
|
||||||
|
return request
|
||||||
|
|
||||||
|
def _remember_hidden_sweep(self, snapshot, record):
|
||||||
|
if (self.sweeper is not None and record.get("sweep_sample_id")
|
||||||
|
and record.get("settlement_confirmed") is True):
|
||||||
|
self.sweeper.remember_map_reward(snapshot, record, record.get("response"))
|
||||||
|
self.sweeper.last_outcome = "hidden_win"
|
||||||
|
|
||||||
|
def _finish_hidden_sweep(self, snapshot, record):
|
||||||
|
if not self.sweeper or not record.get("sweep_sample_id") or record.get("outcome") not in ("win", "loss"):
|
||||||
|
return
|
||||||
|
if str(record.get("role_id")) != role_id(snapshot):
|
||||||
|
return
|
||||||
|
self._remember_hidden_sweep(snapshot, record)
|
||||||
|
self.sweeper.last_outcome = "hidden_" + record["outcome"]
|
||||||
|
|
||||||
|
def handoff_sweep(self, snapshot):
|
||||||
|
"""Move a confirmed hidden entry into the journal without a game write."""
|
||||||
|
if self.sweeper is None:
|
||||||
|
return None
|
||||||
|
with self.journal.lock:
|
||||||
|
self.journal.reload()
|
||||||
|
pending = self.sweeper.state.get("pending")
|
||||||
|
if not isinstance(pending, dict):
|
||||||
|
return None
|
||||||
|
hidden = hidden_stage_id(pending.get("start_response"))
|
||||||
|
if (not hidden or pending.get("hidden_stage_id") not in (None, hidden)
|
||||||
|
or str(pending.get("role_id")) != role_id(snapshot)
|
||||||
|
or pending.get("start_confirmed") is not True
|
||||||
|
or pending.get("start_path") != "stageService/stageStart"
|
||||||
|
or pending.get("phase") not in ("hidden_started", "开始请求待确认") or not pending.get("sampleId")):
|
||||||
|
return None
|
||||||
|
if pending.get("phase") != "hidden_started" or pending.get("hidden_stage_id") is None:
|
||||||
|
pending.update(phase="hidden_started", hidden_stage_id=hidden)
|
||||||
|
self.sweeper.save()
|
||||||
|
record = self.journal.pending(snapshot)
|
||||||
|
completed = next((row for row in self.journal.role(snapshot)["records"]
|
||||||
|
if row.get("sweep_sample_id") == pending["sampleId"] and row.get("phase") == "done"), None)
|
||||||
|
if completed:
|
||||||
|
if (record or completed.get("sweep_entry") != pending or completed.get("outcome") not in ("win", "loss")
|
||||||
|
or completed.get("record_confirmed") is not True
|
||||||
|
or completed.get("outcome") == "win" and completed.get("settlement_confirmed") is not True):
|
||||||
|
return None
|
||||||
|
self._finish_hidden_sweep(snapshot, completed)
|
||||||
|
self.sweeper.state["pending"] = None
|
||||||
|
self.sweeper.save()
|
||||||
|
return completed
|
||||||
|
install = not record or record.get("sweep_sample_id") != pending["sampleId"]
|
||||||
|
origin = pending.get("origin") or ({name: record.get(name) for name in ("kind", "stage_id", "difficulty",
|
||||||
|
"battle_kind", "task_id", "task_type_id", "step_number", "source_task_id", "source_task_type_id", "source_step_number",
|
||||||
|
"battle_mode")} if record else {"kind": "map_sweep", "stage_id": pending["stage"],
|
||||||
|
"difficulty": str(pending["level"]), "battle_kind": "sweep"})
|
||||||
|
if record and record.get("sweep_sample_id") == pending["sampleId"]:
|
||||||
|
if record.get("sweep_entry") != pending:
|
||||||
|
return None
|
||||||
|
install = record.get("phase") == "prepared" and not record.get("start_dispatched")
|
||||||
|
else:
|
||||||
|
if record:
|
||||||
|
if (record.get("kind") not in SWEEP_KINDS or record.get("sweep_sample_id")
|
||||||
|
or str(record.get("stage_id")) != str(pending["stage"])
|
||||||
|
or str(record.get("difficulty")) != str(pending["level"])
|
||||||
|
or record.get("phase") not in ("prepared", "sweep_pending", "unknown")
|
||||||
|
or record.get("start_dispatched") or record.get("settlement_dispatched") or record.get("record_dispatched")):
|
||||||
|
return None
|
||||||
|
else:
|
||||||
|
record = self.journal.begin(snapshot, origin, sweep_entry=pending)
|
||||||
|
if install:
|
||||||
|
self.journal.update(record, "hidden_started", sweep_sample_id=pending["sampleId"],
|
||||||
|
sweep_entry=deepcopy(pending), parent_stage_id=str(pending["stage"]), parent_difficulty=str(pending["level"]),
|
||||||
|
stage_id=hidden, difficulty="1", battle_kind="hidden", team=pending.get("team") or "teamA",
|
||||||
|
battle_mode=origin.get("battle_mode", "experimental"), start_path=pending["start_path"],
|
||||||
|
path=pending["start_path"], start_response=pending["start_response"], start_confirmed=True,
|
||||||
|
start_confirmed_at=pending.get("start_confirmed_at"), start_dispatched=True,
|
||||||
|
runtime_not_started=True, settlement_dispatched=False, record_dispatched=False,
|
||||||
|
sweep_entry_digest=digest(pending))
|
||||||
|
# The journal now owns both the response and original inputs. This
|
||||||
|
# also lets the existing Web Start gate use battle recovery.
|
||||||
|
self.sweeper.state["pending"] = None
|
||||||
|
self.sweeper.save()
|
||||||
|
return record
|
||||||
|
|
||||||
|
def archive_cancelled_sweep(self, snapshot):
|
||||||
|
"""Release only an explicitly cancelled, never-settled sweep entry."""
|
||||||
|
pending = self.sweeper.state.get("pending") if self.sweeper else None
|
||||||
|
if not isinstance(pending, dict) or pending.get("phase") != "cancelled_before_sweep_settlement":
|
||||||
|
return ""
|
||||||
|
response = pending.get("start_response") or {}
|
||||||
|
flag = response.get("triggerEvent")
|
||||||
|
if (pending.get("role_id") != role_id(snapshot) or pending.get("start_confirmed") is not True
|
||||||
|
or pending.get("start_path") != "stageService/stageStart" or pending.get("settlement_dispatched") is not False
|
||||||
|
or pending.get("record_dispatched") is not False or hidden_stage_id(response) is not None
|
||||||
|
or not (flag is False or type(flag) is int and flag == 0)
|
||||||
|
or response.get("resCode", 0) not in (0, "0") or not pending.get("sampleId")):
|
||||||
|
return ""
|
||||||
|
with self.journal.lock:
|
||||||
|
self.journal.reload()
|
||||||
|
record = self.journal.pending(snapshot)
|
||||||
|
if record and (record.get("kind") not in SWEEP_KINDS
|
||||||
|
or str(record.get("stage_id")) != str(pending["stage"])
|
||||||
|
or str(record.get("difficulty")) != str(pending["level"])
|
||||||
|
or record.get("settlement_dispatched") or record.get("record_dispatched")
|
||||||
|
or record.get("phase") not in ("sweep_pending", "unknown", "cancelled_sweep_archived")):
|
||||||
|
return ""
|
||||||
|
done = next((row for row in self.journal.role(snapshot)["records"]
|
||||||
|
if row.get("sweep_sample_id") == pending["sampleId"] and row.get("sweep_entry") == pending
|
||||||
|
and row.get("outcome") == "abandoned_cancelled_sweep"), None)
|
||||||
|
message = "扫荡入场已确认,结算尚未发送,停止后已本地放弃;未结算奖励"
|
||||||
|
if done is None:
|
||||||
|
record = record or self.journal.begin(snapshot, pending.get("origin") or {
|
||||||
|
"kind": "map_sweep", "stage_id": pending["stage"], "difficulty": pending["level"]},
|
||||||
|
sweep_entry=pending, sweep_phase="cancelled_sweep_archived")
|
||||||
|
self.journal.update(record, "cancelled_sweep_archived", sweep_sample_id=pending["sampleId"],
|
||||||
|
sweep_entry=deepcopy(pending), archival_evidence={"role_id": role_id(snapshot), "snapshot_read_at": time.time(),
|
||||||
|
"settlement_never_dispatched": True})
|
||||||
|
self.journal.finish(snapshot, record, "abandoned_cancelled_sweep", message)
|
||||||
|
self.sweeper.state["pending"] = None
|
||||||
|
self.sweeper.save()
|
||||||
|
return message
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def hidden_sweep_inputs(record):
|
||||||
|
entry = record.get("sweep_entry") or {}
|
||||||
|
raw = entry.get("entry_snapshot")
|
||||||
|
return (record.get("sweep_sample_id") and entry.get("sampleId") == record["sweep_sample_id"]
|
||||||
|
and digest(entry) == record.get("sweep_entry_digest") and isinstance(raw, dict)
|
||||||
|
and str((raw.get("master") or {}).get("id")) == str(record.get("role_id"))
|
||||||
|
and entry.get("team") == record.get("team") and hidden_stage_id(entry.get("start_response")) == record.get("stage_id"))
|
||||||
|
|
||||||
|
def continue_sweep(self, client, snapshot, policy, *, cancel=None):
|
||||||
|
"""Complete an already entered hidden sweep; never dispatch stageStart."""
|
||||||
|
cancel = cancel or threading.Event()
|
||||||
|
with self.journal.lock:
|
||||||
|
self.handoff_sweep(snapshot)
|
||||||
|
record = self.journal.pending(snapshot)
|
||||||
|
if not record or not record.get("sweep_sample_id") or not policy.enabled or cancel.is_set():
|
||||||
|
return ""
|
||||||
|
status = self.recovery_status(record, snapshot=snapshot)
|
||||||
|
if not status["resumable"]:
|
||||||
|
return status["message"]
|
||||||
|
intent = {key: record.get(key) for key in ("kind", "task_id", "task_type_id", "step_number", "stage_category",
|
||||||
|
"stage_id", "difficulty", "battle_kind", "team", "source_task_id", "source_task_type_id", "source_step_number")}
|
||||||
|
if status["state"] != "prepare_hidden_sweep":
|
||||||
|
return self.resume_task_clock(client, snapshot, intent, policy, cancel=cancel)
|
||||||
|
entry = record["sweep_entry"]
|
||||||
|
original = SimpleNamespace(raw=deepcopy(entry["entry_snapshot"]), now=entry.get("entry_snapshot_now", snapshot.now))
|
||||||
|
chosen = SimpleNamespace(**(vars(policy) | {"team": record["team"], "battle_mode": record["battle_mode"]}))
|
||||||
|
try:
|
||||||
|
request = self._hidden_request(record, original, intent, chosen, record["start_response"])
|
||||||
|
supported, reason = self.inspect(request)
|
||||||
|
if not supported:
|
||||||
|
return self._unknown(record, "隐藏关卡待处理:" + reason)
|
||||||
|
return self._fight(client, snapshot, intent, request, record, self.clock(), cancel)
|
||||||
|
except CancelledBeforeDispatch:
|
||||||
|
if not record.get("settlement_confirmed"):
|
||||||
|
self.journal.update(record, "waiting_for_battle_clock", path=record["start_path"],
|
||||||
|
settlement_dispatched=False, resume_clock_ready=True)
|
||||||
|
return "策略已停止,隐藏战果已保存,等待重新开启来源策略"
|
||||||
|
except Exception as error:
|
||||||
|
self._unknown(record, "隐藏关卡结果未确认,保留原入场且禁止重发写请求", error_type=type(error).__name__)
|
||||||
|
raise
|
||||||
|
|
||||||
|
def _fight(self, client, snapshot, intent, request, record, battle_started, cancel):
|
||||||
if cancel.is_set():
|
if cancel.is_set():
|
||||||
return self._unknown(record, "开战后已取消,等待服务器状态核对")
|
return self._unknown(record, "开战后已取消,等待服务器状态核对")
|
||||||
self.journal.update(record, "running")
|
self.journal.update(record, "running", runtime_not_started=False)
|
||||||
result = self.runtime.run(request.get("runtime_request", request), cancel_event=cancel)
|
result = self.runtime.run(request.get("runtime_request", request), cancel_event=cancel)
|
||||||
evidence = self.runtime_evidence(result, mode)
|
if not self.accept_runtime_result(record, request, result, battle_started, cancel):
|
||||||
self.journal.update(record, "runtime_returned", **evidence)
|
|
||||||
if cancel.is_set() or value(result, "outcome") in ("cancelled", "cancel", "timeout", "unknown", "unsupported"):
|
|
||||||
return self._unknown(record, "战斗已取消、超时或结果不确定,等待核对")
|
|
||||||
data = value(result, "battle_data")
|
|
||||||
eligible = value(result, "outcome") in ("win", "loss")
|
|
||||||
if mode == "experimental":
|
|
||||||
eligible = (eligible and value(result, "experimental_settlement_eligible") is True
|
|
||||||
and value(result, "execution_mode") == "experimental" and value(result, "execution_status") == "completed"
|
|
||||||
and value(result, "supported") is True and value(result, "terminal") is True
|
|
||||||
and value(result, "approximate") is True and value(result, "faithful") is False and not value(result, "anomalies"))
|
|
||||||
else:
|
|
||||||
eligible = eligible and value(result, "settlement_eligible") is True and value(result, "faithful") is True and value(result, "approximate") is not True
|
|
||||||
if not eligible or not isinstance(data, dict) or type(data.get("win")) is not bool:
|
|
||||||
return self._unknown(record, "所选运行时未提供可结算的实际执行结果,未提交结算")
|
|
||||||
if data["win"] != (value(result, "outcome") == "win"):
|
|
||||||
return self._unknown(record, "运行结果与战果胜负不一致,未提交结算")
|
|
||||||
position = data.get("battlePosition")
|
|
||||||
if (not isinstance(position, dict) or {k: v for k, v in position.items() if v is not None}
|
|
||||||
!= {k: v for k, v in request["battle_position"].items() if v is not None}):
|
|
||||||
return self._unknown(record, "运行时战果定位不匹配,未提交结算")
|
|
||||||
# Keep all statistics and integrity records exactly as supplied.
|
|
||||||
self.journal.update(record, "runtime_complete", battle_data=data)
|
|
||||||
if not self.wait_for_battle_clock(record, request, result, data, battle_started, cancel):
|
|
||||||
return record["message"]
|
return record["message"]
|
||||||
|
data = record["battle_data"]
|
||||||
|
mode = request.get("battle_mode", "original")
|
||||||
if not data["win"]:
|
if not data["win"]:
|
||||||
if not value(intent, "task_id") or value(intent, "battle_kind") == "passStage":
|
if not value(intent, "task_id") or value(intent, "battle_kind") == "passStage":
|
||||||
self._record(client, record, request["stage_id"], False, cancel=cancel)
|
self._record(client, record, request["stage_id"], False, cancel=cancel)
|
||||||
@@ -676,16 +1094,18 @@ class BattleOrchestrator:
|
|||||||
self.observer("loss", intent, None)
|
self.observer("loss", intent, None)
|
||||||
label = "实验模型战败(近似)" if mode == "experimental" else "实际战败"
|
label = "实验模型战败(近似)" if mode == "experimental" else "实际战败"
|
||||||
self.journal.finish(snapshot, record, "loss", label + ";未提交胜利结算或推进任务")
|
self.journal.finish(snapshot, record, "loss", label + ";未提交胜利结算或推进任务")
|
||||||
|
self._finish_hidden_sweep(snapshot, record)
|
||||||
return label + ";已停止此轮任务推进"
|
return label + ";已停止此轮任务推进"
|
||||||
if value(intent, "task_id"):
|
if value(intent, "task_id"):
|
||||||
path, payload = "taskService/taskCompleteStep", {"taskId": int(value(intent, "task_id")),
|
path, payload = "taskService/taskCompleteStep", {"taskId": int(value(intent, "task_id")),
|
||||||
"taskTypeId": str(value(intent, "task_type_id")), "removeIds": None, "battleData": data}
|
"taskTypeId": str(value(intent, "task_type_id")), "removeIds": None, "battleData": data}
|
||||||
else:
|
else:
|
||||||
path, payload = "battleService/battleEnd", {"battleData": data}
|
path, payload = "battleService/battleEnd", {"battleData": data}
|
||||||
self.journal.update(record, "settlement_pending", path=path)
|
self.journal.update(record, "settlement_pending", path=path, settlement_dispatched=True)
|
||||||
response = self._call(client, path, payload, cancel=cancel)
|
response = self._call(client, path, payload, cancel=cancel, require_code=record.get("battle_kind") == "hidden")
|
||||||
self.journal.update(record, "settlement_acknowledged", response=gameplay_response(response), settlement_confirmed=True,
|
self.journal.update(record, "settlement_acknowledged", response=gameplay_response(response), settlement_confirmed=True,
|
||||||
reward=response["stageReward"] if response.get("stageReward") is not None else response.get("reward"))
|
reward=response["stageReward"] if response.get("stageReward") is not None else response.get("reward"))
|
||||||
|
self._remember_hidden_sweep(snapshot, record)
|
||||||
if value(intent, "task_id"):
|
if value(intent, "task_id"):
|
||||||
if self.observer:
|
if self.observer:
|
||||||
self.observer("settled", intent, response)
|
self.observer("settled", intent, response)
|
||||||
@@ -698,10 +1118,8 @@ class BattleOrchestrator:
|
|||||||
self.observer("settled", intent, response)
|
self.observer("settled", intent, response)
|
||||||
label = "实验模型胜利(近似)" if mode == "experimental" else "实际胜利"
|
label = "实验模型胜利(近似)" if mode == "experimental" else "实际胜利"
|
||||||
self.journal.finish(snapshot, record, "win", label + ",结算接口已确认;后续进度以服务器快照核对")
|
self.journal.finish(snapshot, record, "win", label + ",结算接口已确认;后续进度以服务器快照核对")
|
||||||
|
self._finish_hidden_sweep(snapshot, record)
|
||||||
return label + ",已确认对应结算"
|
return label + ",已确认对应结算"
|
||||||
except Exception as error:
|
|
||||||
self._unknown(record, "任务 / 战斗请求或运行未确认;禁止自动重试", error_type=type(error).__name__)
|
|
||||||
raise
|
|
||||||
|
|
||||||
def _sweep(self, client, snapshot, intent, policy, cancel):
|
def _sweep(self, client, snapshot, intent, policy, cancel):
|
||||||
if not policy.allow_sweep or self.sweeper is None or value(intent, "task_id"):
|
if not policy.allow_sweep or self.sweeper is None or value(intent, "task_id"):
|
||||||
@@ -712,6 +1130,10 @@ class BattleOrchestrator:
|
|||||||
return "仅三个难度全通且客户端允许的普通关卡可扫荡"
|
return "仅三个难度全通且客户端允许的普通关卡可扫荡"
|
||||||
if cancel.is_set():
|
if cancel.is_set():
|
||||||
return "扫荡已取消,未开始"
|
return "扫荡已取消,未开始"
|
||||||
|
origin = {name: public_data(value(intent, name)) for name in ("kind", "task_id", "task_type_id", "step_number",
|
||||||
|
"stage_id", "difficulty", "battle_kind", "source_task_id", "source_task_type_id", "source_step_number")}
|
||||||
|
origin["battle_mode"] = value(policy, "battle_mode", "experimental")
|
||||||
|
battle_policy = policy
|
||||||
policy = SweepPolicy(enabled=True, team=policy.team, keep_stamina=policy.reserve_ti,
|
policy = SweepPolicy(enabled=True, team=policy.team, keep_stamina=policy.reserve_ti,
|
||||||
rules={stage.stage_id: {"enabled": True, "level": stage.level, "limit": self.sweeper.used(snapshot, stage) + 1}})
|
rules={stage.stage_id: {"enabled": True, "level": stage.level, "limit": self.sweeper.used(snapshot, stage) + 1}})
|
||||||
record = self.journal.begin(snapshot, intent)
|
record = self.journal.begin(snapshot, intent)
|
||||||
@@ -719,31 +1141,47 @@ class BattleOrchestrator:
|
|||||||
try:
|
try:
|
||||||
if self.observer:
|
if self.observer:
|
||||||
self.observer("started", intent, None)
|
self.observer("started", intent, None)
|
||||||
response = self.sweeper.run(client, snapshot, stage, policy)
|
response = self.sweeper.run(client, snapshot, stage, policy, cancel=cancel, origin=origin)
|
||||||
|
if self.sweeper.last_outcome == "hidden":
|
||||||
|
return self.continue_sweep(client, snapshot, battle_policy, cancel=cancel)
|
||||||
if self.observer:
|
if self.observer:
|
||||||
self.observer("event" if self.sweeper.last_outcome == "event" else "settled", intent, response)
|
self.observer("event" if self.sweeper.last_outcome == "event" else "settled", intent, response)
|
||||||
self.journal.finish(snapshot, record, "event" if self.sweeper.last_outcome == "event" else "sweep", "复用客户端已有扫荡路径")
|
self.journal.finish(snapshot, record, "event" if self.sweeper.last_outcome == "event" else "sweep", "复用客户端已有扫荡路径")
|
||||||
return "探索奖励事件已结算" if self.sweeper.last_outcome == "event" else "扫荡已完成"
|
return "探索奖励事件已结算" if self.sweeper.last_outcome == "event" else "扫荡已完成"
|
||||||
|
except CancelledBeforeDispatch:
|
||||||
|
if self.sweeper.state.get("pending") is None:
|
||||||
|
self.journal.finish(snapshot, record, "cancelled", "扫荡入场尚未发送,已取消")
|
||||||
|
return "扫荡已停止,已保留未确认记录"
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
|
record = self.journal.pending(snapshot) or record
|
||||||
self._unknown(record, "扫荡结果未确认,禁止自动重试", error_type=type(error).__name__)
|
self._unknown(record, "扫荡结果未确认,禁止自动重试", error_type=type(error).__name__)
|
||||||
raise
|
raise
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _call(client, path, payload, *, cancel=None):
|
def _call(client, path, payload, *, cancel=None, require_code=False):
|
||||||
if cancel is not None and cancel.is_set():
|
if cancel is not None and cancel.is_set():
|
||||||
raise CancelledBeforeDispatch()
|
raise CancelledBeforeDispatch()
|
||||||
response = client.call(path, payload)
|
response = client.call(path, payload)
|
||||||
if not isinstance(response, dict) or response.get("resCode", 0) not in (0, "0"):
|
if not isinstance(response, dict) or response.get("resCode", 0) not in (0, "0"):
|
||||||
raise ValueError("游戏接口未返回可信的成功响应")
|
raise ValueError("游戏接口未返回可信的成功响应")
|
||||||
|
if require_code and not (type(response.get("resCode")) is int and response["resCode"] == 0
|
||||||
|
or type(response.get("resCode")) is str and response["resCode"] == "0"):
|
||||||
|
raise ValueError("隐藏关卡写请求缺少明确成功回包,保留待核对且禁止重发")
|
||||||
return response
|
return response
|
||||||
|
|
||||||
def _record(self, client, record, stage, win, *, cancel=None):
|
def _record(self, client, record, stage, win, *, cancel=None):
|
||||||
self.journal.update(record, "record_pending")
|
phase = record["phase"]
|
||||||
|
self.journal.update(record, "record_pending", record_dispatched=True, record_result=win)
|
||||||
try:
|
try:
|
||||||
self._call(client, "battleService/recordBattleResult", {"stageId": str(stage), "cityId": str(stage)[1:2], "result": int(win)}, cancel=cancel)
|
response = self._call(client, "battleService/recordBattleResult", {"stageId": str(stage), "cityId": str(stage)[1:2], "result": int(win)},
|
||||||
|
cancel=cancel, require_code=record.get("battle_kind") == "hidden")
|
||||||
|
except CancelledBeforeDispatch:
|
||||||
|
self.journal.update(record, phase, record_dispatched=False)
|
||||||
|
raise
|
||||||
except Exception:
|
except Exception:
|
||||||
self.journal.update(record, "record_unknown", message="战果记录未确认,不能重放战斗")
|
self.journal.update(record, "record_unknown", message="战果记录未确认,不能重放战斗")
|
||||||
raise
|
raise
|
||||||
|
self.journal.update(record, "record_acknowledged", record_confirmed=True, record_response=gameplay_response(response))
|
||||||
|
|
||||||
def _unknown(self, record, message, **fields):
|
def _unknown(self, record, message, **fields):
|
||||||
phase = "record_unknown" if record["phase"] == "record_unknown" else "unknown"
|
phase = "record_unknown" if record["phase"] == "record_unknown" else "unknown"
|
||||||
|
|||||||
@@ -0,0 +1,305 @@
|
|||||||
|
"""Bounded, per-role commission receipts, independent of rolling activity logs.
|
||||||
|
|
||||||
|
Only journaled operations enter this ledger. A current task or passTask flag
|
||||||
|
alone proves neither its acceptance date nor that its reward was collected.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from copy import deepcopy
|
||||||
|
from datetime import date, datetime, timedelta
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
from .quests import CN, commission_priority
|
||||||
|
|
||||||
|
|
||||||
|
def beijing_day(timestamp=None):
|
||||||
|
return datetime.fromtimestamp(time.time() if timestamp is None else timestamp, CN).date().isoformat()
|
||||||
|
|
||||||
|
|
||||||
|
def confirmed_reward(response):
|
||||||
|
"""NetTask.finishTaskHandler -> RewardCenter -> MasterCenter.addKe: delta."""
|
||||||
|
reward = response.get("reward") if isinstance(response, dict) else None
|
||||||
|
value = reward.get("ke") if isinstance(reward, dict) else None
|
||||||
|
if type(value) not in (int, float) or not math.isfinite(value) or value < 0 or int(value) != value:
|
||||||
|
return None
|
||||||
|
return int(value)
|
||||||
|
|
||||||
|
|
||||||
|
def positive_id(value):
|
||||||
|
if isinstance(value, bool):
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
number = float(value)
|
||||||
|
return int(number) if math.isfinite(number) and number.is_integer() and number > 0 else None
|
||||||
|
except (ValueError, TypeError, OverflowError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def valid_stored_event(event):
|
||||||
|
required = {"id", "journal_id", "time", "date", "kind", "status", "description", "task_id", "task_type_id",
|
||||||
|
"name", "city", "expected_ke", "confirmed_ke", "selection_code", "selection_reason", "higher_reward_blockers"}
|
||||||
|
if not isinstance(event, dict) or not required <= event.keys():
|
||||||
|
return False
|
||||||
|
if any(not isinstance(event[key], str) for key in
|
||||||
|
("id", "journal_id", "date", "kind", "status", "description", "task_type_id", "name", "selection_code", "selection_reason")):
|
||||||
|
return False
|
||||||
|
if (type(event["time"]) not in (int, float) or not math.isfinite(event["time"])
|
||||||
|
or event["date"] != beijing_day(event["time"])):
|
||||||
|
return False
|
||||||
|
if event["task_id"] is not None and (type(event["task_id"]) is not int or event["task_id"] <= 0):
|
||||||
|
return False
|
||||||
|
if type(event["expected_ke"]) is not int or event["expected_ke"] < 0:
|
||||||
|
return False
|
||||||
|
if event["confirmed_ke"] is not None and (type(event["confirmed_ke"]) is not int or event["confirmed_ke"] < 0):
|
||||||
|
return False
|
||||||
|
return (bool(event["id"]) and bool(event["journal_id"]) and isinstance(event["higher_reward_blockers"], list)
|
||||||
|
and event["kind"] in ("accept", "complete", "reset", "step", "navigate", "dialogue", "battle", "farm", "local_step")
|
||||||
|
and event["status"] in ("confirmed", "pending", "unknown", "cancelled", "failed"))
|
||||||
|
|
||||||
|
|
||||||
|
def reconciled_accept_task(record, snapshot, today):
|
||||||
|
"""Recheck only a journal-proven acceptance from the current Beijing day."""
|
||||||
|
if (snapshot is None or record.get("outcome") != "reconciled"
|
||||||
|
or not (record.get("path") or "").endswith("taskLoopReceive")
|
||||||
|
or str(snapshot.raw.get("master", {}).get("id")) != str(record.get("role_id"))):
|
||||||
|
return None
|
||||||
|
timestamp = record.get("finished_at") or record.get("updated_at") or record.get("timestamp")
|
||||||
|
if type(timestamp) not in (int, float) or not math.isfinite(timestamp) or beijing_day(timestamp) != today:
|
||||||
|
return None
|
||||||
|
old = {str(task.get("id")) for task in (record.get("baseline") or {}).get("tasks", [])}
|
||||||
|
expected_id = positive_id(record.get("task_id"))
|
||||||
|
matches = [task for task in snapshot.raw.get("currentTasks", [])
|
||||||
|
if str(task.get("typeId")) == str(record.get("task_type_id")) and str(task.get("id")) not in old
|
||||||
|
and positive_id(task.get("id")) and positive_id(task.get("curStep"))
|
||||||
|
and (expected_id is None or positive_id(task["id"]) == expected_id)]
|
||||||
|
return {key: matches[0][key] for key in ("id", "typeId", "curStep")} if len(matches) == 1 else None
|
||||||
|
|
||||||
|
|
||||||
|
def journal_event(record, info, snapshot=None):
|
||||||
|
meta = record.get("commission") or {}
|
||||||
|
path, original = record.get("path") or "", record.get("kind") or ""
|
||||||
|
farming = bool(record.get("source_task_type_id"))
|
||||||
|
type_id = str(record.get("source_task_type_id") or record.get("task_type_id") or "")
|
||||||
|
if not (meta or (info or {}).get("type") == 4 or original.startswith("quest_")
|
||||||
|
or original in ("progression_loop_accept", "progression_loop_reset")):
|
||||||
|
return None
|
||||||
|
kind = ("farm" if farming else "accept" if path.endswith("taskLoopReceive") else
|
||||||
|
"complete" if path.endswith("taskComplete") else "reset" if path.endswith("taskLoopFlush") else
|
||||||
|
"navigate" if original == "progression_navigate" else "dialogue" if original == "progression_dialogue" else
|
||||||
|
"battle" if original == "progression_battle" else "local_step" if original == "progression_local_step" else "step")
|
||||||
|
response = record.get("response")
|
||||||
|
response_ok = isinstance(response, dict) and response.get("resCode", 0) in (0, "0")
|
||||||
|
action_response = record.get("commission_action_response")
|
||||||
|
action_receipt = record.get("commission_action_confirmed") is True and isinstance(action_response, dict) and action_response.get("resCode", 0) in (0, "0")
|
||||||
|
receipt = response_ok and (record.get("response_confirmed") is True or record.get("settlement_confirmed") is True
|
||||||
|
or record.get("phase") in ("acknowledged", "settlement_acknowledged")
|
||||||
|
or record.get("phase") == "done" and record.get("outcome") in ("task", "win"))
|
||||||
|
task_id = record.get("source_task_id") if farming else record.get("task_id")
|
||||||
|
phase, outcome = record.get("phase"), record.get("outcome")
|
||||||
|
status = "unknown" if "unknown" in str(phase) or outcome == "reconciled" else "pending"
|
||||||
|
if kind == "accept":
|
||||||
|
task = response.get("task") if receipt else None
|
||||||
|
if not isinstance(task, dict) and outcome == "reconciled":
|
||||||
|
# Bind only the snapshot that resolved this pending attempt. A
|
||||||
|
# later currentTasks entry may be another day's same-type task.
|
||||||
|
task = record.get("commission_task")
|
||||||
|
if (isinstance(task, dict) and str(task.get("typeId")) == type_id
|
||||||
|
and positive_id(task.get("id")) and positive_id(task.get("curStep"))):
|
||||||
|
task_id, status = positive_id(task["id"]), "confirmed"
|
||||||
|
elif receipt:
|
||||||
|
status = "unknown"
|
||||||
|
elif kind == "complete":
|
||||||
|
# passTask is type-level history: it cannot prove this instance's claim.
|
||||||
|
if receipt:
|
||||||
|
status = "confirmed"
|
||||||
|
elif receipt or action_receipt or phase == "done" and outcome in ("local", "win", "sweep", "event"):
|
||||||
|
status = "confirmed"
|
||||||
|
elif outcome == "reconciled" and kind in ("step", "battle", "reset"):
|
||||||
|
status = "confirmed"
|
||||||
|
if outcome in ("cancelled", "unsupported"):
|
||||||
|
status = "cancelled"
|
||||||
|
elif outcome == "loss":
|
||||||
|
status = "failed"
|
||||||
|
timestamp = (record.get("finished_at") or record.get("updated_at") or record.get("timestamp")) if status == "confirmed" else record.get("timestamp")
|
||||||
|
if type(timestamp) not in (int, float) or not math.isfinite(timestamp):
|
||||||
|
return None
|
||||||
|
name = str(meta.get("name") or (info or {}).get("name") or type_id or "每日委托")
|
||||||
|
expected = meta.get("expected_ke", -commission_priority(info or {}))
|
||||||
|
actual = confirmed_reward(response) if kind == "complete" and receipt else None
|
||||||
|
labels = {"accept": "接取委托", "complete": "领取委托奖励", "reset": "刷新每日委托",
|
||||||
|
"step": "提交委托步骤", "navigate": "委托导航", "dialogue": "委托对话", "battle": "委托战斗",
|
||||||
|
"farm": "收集委托材料", "local_step": "完成委托步骤本地收尾"}
|
||||||
|
detail = record.get("description") or ""
|
||||||
|
description = f"{labels[kind]}:{name}(预计{expected}氪金)"
|
||||||
|
if kind in ("step", "battle", "local_step") and record.get("step_number"):
|
||||||
|
description += f",第{record['step_number']}步"
|
||||||
|
if kind in ("navigate", "dialogue", "farm") and detail:
|
||||||
|
description += ";" + detail
|
||||||
|
if status == "confirmed":
|
||||||
|
if kind in ("step", "battle") and meta.get("operation_detail"):
|
||||||
|
description += ";" + meta["operation_detail"]
|
||||||
|
description += ";本地操作已完成" if outcome == "local" else ";快照已核对" if outcome == "reconciled" and not receipt else ";已确认"
|
||||||
|
if kind == "complete":
|
||||||
|
description += f",实际获得{actual}氪金" if actual is not None else ",实际氪金奖励未记录"
|
||||||
|
if kind == "accept" and meta.get("selection_reason"):
|
||||||
|
description += ";" + meta["selection_reason"]
|
||||||
|
else:
|
||||||
|
description += {"pending": ";请求待确认", "unknown": ";结果未知,等待核对,禁止重发",
|
||||||
|
"cancelled": ";未执行", "failed": ";战斗失败,未推进委托"}[status]
|
||||||
|
return {"id": str(record["attempt_id"]), "journal_id": str(record["attempt_id"]),
|
||||||
|
"time": timestamp, "date": beijing_day(timestamp), "kind": kind, "status": status,
|
||||||
|
"description": description, "task_id": positive_id(task_id), "task_type_id": type_id,
|
||||||
|
"name": name, "city": meta.get("city", (record.get("payload") or {}).get("city")),
|
||||||
|
"expected_ke": expected, "confirmed_ke": actual,
|
||||||
|
"operation_detail": meta.get("operation_detail", ""),
|
||||||
|
"confirmation": "receipt" if receipt or action_receipt else "local" if outcome == "local" else "snapshot" if outcome == "reconciled" and status == "confirmed" else "",
|
||||||
|
"selection_code": meta.get("selection_code", "unknown" if kind == "accept" else "already_accepted"),
|
||||||
|
"selection_reason": meta.get("selection_reason") or (("历史接取已确认,当时选择原因未记录" if status == "confirmed"
|
||||||
|
else "接取已取消,当时选择原因未记录" if status == "cancelled" else "接取结果待核对,当时选择原因未记录") if kind == "accept"
|
||||||
|
else "已有委托继续处理,接取时间及当时选择原因未记录"),
|
||||||
|
"higher_reward_blockers": deepcopy(meta.get("higher_reward_blockers") or [])}
|
||||||
|
|
||||||
|
|
||||||
|
class CommissionHistory:
|
||||||
|
def __init__(self, path=None, *, retention_days=90, max_events=5000, clock=None):
|
||||||
|
self.path = Path(path) if path else None
|
||||||
|
self.retention_days, self.max_events = retention_days, max_events
|
||||||
|
self.clock = clock or time.time
|
||||||
|
self.lock = threading.RLock()
|
||||||
|
self.state = {"version": 1, "roles": {}}
|
||||||
|
self.error = ""
|
||||||
|
self.warning = ""
|
||||||
|
self._dirty = False
|
||||||
|
self._seen = {}
|
||||||
|
if self.path and self.path.exists():
|
||||||
|
try:
|
||||||
|
state = json.loads(self.path.read_text(encoding="utf-8"))
|
||||||
|
if state.get("version") != 1 or not isinstance(state.get("roles"), dict):
|
||||||
|
raise ValueError("unsupported history")
|
||||||
|
for events in state["roles"].values():
|
||||||
|
if not isinstance(events, dict) or any(not valid_stored_event(event) for event in events.values()):
|
||||||
|
raise ValueError("invalid history")
|
||||||
|
self.state = state
|
||||||
|
except (OSError, ValueError, AttributeError, OverflowError) as error:
|
||||||
|
self.error = "委托历史无法读取,原文件已保留:" + type(error).__name__
|
||||||
|
|
||||||
|
def _prune(self):
|
||||||
|
cutoff = (datetime.fromtimestamp(self.clock(), CN).date() - timedelta(days=self.retention_days - 1)).isoformat()
|
||||||
|
for role, events in self.state["roles"].items():
|
||||||
|
keep = sorted((event for event in events.values() if event["date"] >= cutoff),
|
||||||
|
key=lambda event: (event["time"], event["id"]))[-self.max_events:]
|
||||||
|
self.state["roles"][role] = {event["id"]: event for event in keep}
|
||||||
|
|
||||||
|
def _save(self):
|
||||||
|
self._prune()
|
||||||
|
if self.path:
|
||||||
|
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
temporary = self.path.with_name(self.path.name + "." + uuid.uuid4().hex + ".tmp")
|
||||||
|
try:
|
||||||
|
with temporary.open("w", encoding="utf-8") as stream:
|
||||||
|
json.dump(self.state, stream, ensure_ascii=False, allow_nan=False)
|
||||||
|
stream.flush()
|
||||||
|
os.fsync(stream.fileno())
|
||||||
|
temporary.replace(self.path)
|
||||||
|
finally:
|
||||||
|
temporary.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
def ingest(self, role_id, records, info_for, snapshot=None):
|
||||||
|
"""Upsert by existing attempt ID; never read traces or dispatch requests."""
|
||||||
|
if self.error:
|
||||||
|
return
|
||||||
|
with self.lock:
|
||||||
|
role_id = str(role_id)
|
||||||
|
events = self.state["roles"].setdefault(role_id, {})
|
||||||
|
seen = self._seen.setdefault(role_id, {})
|
||||||
|
changed = False
|
||||||
|
for record in records:
|
||||||
|
if str(record.get("role_id")) != role_id or not record.get("attempt_id"):
|
||||||
|
continue
|
||||||
|
key = str(record["attempt_id"])
|
||||||
|
acceptance = reconciled_accept_task(record, snapshot, beijing_day(self.clock()))
|
||||||
|
revision = (record.get("phase"), record.get("outcome"), record.get("updated_at"), record.get("finished_at"),
|
||||||
|
json.dumps([record.get("commission") or {}, record.get("commission_task"), acceptance], sort_keys=True, ensure_ascii=False))
|
||||||
|
if seen.get(key) == revision:
|
||||||
|
continue
|
||||||
|
info = info_for(str(record.get("source_task_type_id") or record.get("task_type_id") or ""))
|
||||||
|
evidence = record | {"commission_task": acceptance} if acceptance and not record.get("commission_task") else record
|
||||||
|
event = journal_event(evidence, info, snapshot)
|
||||||
|
if event:
|
||||||
|
previous = events.get(key)
|
||||||
|
# A previously captured receipt stays known after restart,
|
||||||
|
# even if a reconciled acceptance has left the snapshot.
|
||||||
|
if previous and previous["status"] == "confirmed" and event["status"] != "confirmed":
|
||||||
|
event = previous
|
||||||
|
if previous != event:
|
||||||
|
events[key] = event
|
||||||
|
changed = True
|
||||||
|
seen[key] = revision
|
||||||
|
current_ids = {str(record.get("attempt_id")) for record in records}
|
||||||
|
self._seen[role_id] = {key: revision for key, revision in seen.items() if key in current_ids}
|
||||||
|
self._dirty = self._dirty or changed
|
||||||
|
if self._dirty:
|
||||||
|
self._save()
|
||||||
|
self._dirty = False
|
||||||
|
self.warning = ""
|
||||||
|
|
||||||
|
def query(self, role_id, day=None):
|
||||||
|
today = beijing_day(self.clock())
|
||||||
|
if day is None:
|
||||||
|
day = today
|
||||||
|
if not isinstance(day, str):
|
||||||
|
raise ValueError("委托历史日期须为 YYYY-MM-DD")
|
||||||
|
try:
|
||||||
|
if date.fromisoformat(day).isoformat() != day:
|
||||||
|
raise ValueError(day)
|
||||||
|
except ValueError as error:
|
||||||
|
raise ValueError("委托历史日期须为 YYYY-MM-DD") from error
|
||||||
|
with self.lock:
|
||||||
|
events = sorted(self.state["roles"].get(str(role_id), {}).values(), key=lambda event: (event["time"], event["id"]))
|
||||||
|
dates = sorted({today, day, *(event["date"] for event in events)}, reverse=True)
|
||||||
|
daily = [event for event in events if event["date"] == day]
|
||||||
|
groups = {}
|
||||||
|
for event in events:
|
||||||
|
if event["date"] > day or not event["task_type_id"]:
|
||||||
|
continue
|
||||||
|
identity = f"{role_id}:{event['task_type_id']}:{event['task_id']}" if event["task_id"] else f"{role_id}:attempt:{event['id']}"
|
||||||
|
groups.setdefault(identity, []).append(event)
|
||||||
|
rows = []
|
||||||
|
for identity, timeline in groups.items():
|
||||||
|
selected = [event for event in timeline if event["date"] == day]
|
||||||
|
if not selected:
|
||||||
|
continue
|
||||||
|
accepted = next((event for event in timeline if event["kind"] == "accept" and event["status"] == "confirmed"), None)
|
||||||
|
completed = next((event for event in timeline if event["kind"] == "complete" and event["status"] == "confirmed"), None)
|
||||||
|
latest, first = timeline[-1], accepted or timeline[0]
|
||||||
|
status = (latest["status"] if latest["status"] in ("pending", "unknown", "failed", "cancelled") else "completed" if completed else
|
||||||
|
"accepted" if latest["kind"] == "accept" and accepted else "in_progress")
|
||||||
|
rows.append({"id": identity, "task_id": first["task_id"], "task_type_id": first["task_type_id"],
|
||||||
|
"name": first["name"], "city": first["city"], "status": status,
|
||||||
|
"accepted_at": accepted["time"] if accepted else None, "completed_at": completed["time"] if completed else None,
|
||||||
|
"expected_ke": first["expected_ke"], "confirmed_ke": completed["confirmed_ke"] if completed else None,
|
||||||
|
"selection_reason": first["selection_reason"], "selection_code": first["selection_code"],
|
||||||
|
"higher_reward_blockers": first["higher_reward_blockers"], "last_action": latest["description"], "events": selected})
|
||||||
|
receipts = {"accept": {}, "complete": {}}
|
||||||
|
for event in events:
|
||||||
|
if event["kind"] not in receipts or event["status"] != "confirmed":
|
||||||
|
continue
|
||||||
|
identity = (event["task_type_id"], event["task_id"]) if event["task_id"] else ("attempt", event["id"])
|
||||||
|
receipts[event["kind"]].setdefault(identity, event)
|
||||||
|
accepts = [event for event in receipts["accept"].values() if event["date"] == day]
|
||||||
|
completes = [event for event in receipts["complete"].values() if event["date"] == day]
|
||||||
|
result = {"date": day, "dates": dates, "timezone": "Asia/Shanghai", "role_id": str(role_id),
|
||||||
|
"summary": {"accepted_count": len(accepts), "completed_count": len(completes),
|
||||||
|
"pending_count": sum(row["status"] in ("pending", "unknown") for row in rows),
|
||||||
|
"expected_ke": sum(event["expected_ke"] for event in accepts),
|
||||||
|
"confirmed_ke": sum(event["confirmed_ke"] for event in completes if event["confirmed_ke"] is not None),
|
||||||
|
"unknown_reward_count": sum(event["confirmed_ke"] is None for event in completes)},
|
||||||
|
"rows": list(reversed(rows)), "events": list(reversed(daily)), "retention_days": self.retention_days,
|
||||||
|
"notice": "仅展示已记录的委托操作;缺失的旧历史未记录,不补推接取、完成或奖励。", "error": self.error or self.warning}
|
||||||
|
return deepcopy(result)
|
||||||
+485
-29
@@ -12,7 +12,9 @@ from types import SimpleNamespace
|
|||||||
from .model import Action, Catalog, Planner, Policy, Snapshot, seconds
|
from .model import Action, Catalog, Planner, Policy, Snapshot, seconds
|
||||||
from .daily import DailyLedger, DailyPolicy, selected_entries
|
from .daily import DailyLedger, DailyPolicy, selected_entries
|
||||||
from .sweeping import SweepPolicy, SweepRunner
|
from .sweeping import SweepPolicy, SweepRunner
|
||||||
from .quests import QuestPolicy, TaskPlanner
|
from .quests import QuestPolicy, TaskPlanner, commission_priority, commission_reason_kind
|
||||||
|
from .procurement import resource_kind
|
||||||
|
from .commission_history import CommissionHistory
|
||||||
from .market import PurchaseBudget
|
from .market import PurchaseBudget
|
||||||
from .management import expansion_quote, manual_monster_actions
|
from .management import expansion_quote, manual_monster_actions
|
||||||
from .gifts import GiftPlanner
|
from .gifts import GiftPlanner
|
||||||
@@ -104,6 +106,10 @@ class Engine:
|
|||||||
self._progression_state_loaded = False
|
self._progression_state_loaded = False
|
||||||
self._battle_catalog_ready = False
|
self._battle_catalog_ready = False
|
||||||
self.battle_journal = BattleJournal(folder / "progression" / "journal.json" if folder else None)
|
self.battle_journal = BattleJournal(folder / "progression" / "journal.json" if folder else None)
|
||||||
|
self._commission_history = CommissionHistory(folder / "progression" / "commission_history.json" if folder else None)
|
||||||
|
self._commission_history_roles = set()
|
||||||
|
self._commission_offer_diagnostics = []
|
||||||
|
self._commission_diagnostics_key = None
|
||||||
self.battles = BattleOrchestrator(catalog, self.battle_journal, battle_runtime, self.sweeper,
|
self.battles = BattleOrchestrator(catalog, self.battle_journal, battle_runtime, self.sweeper,
|
||||||
request_builder=self._battle_request, observer=self._battle_observer)
|
request_builder=self._battle_request, observer=self._battle_observer)
|
||||||
self._progression_cancel = threading.Event()
|
self._progression_cancel = threading.Event()
|
||||||
@@ -128,6 +134,8 @@ class Engine:
|
|||||||
self._battle_roster = None
|
self._battle_roster = None
|
||||||
self._battle_runtimes = {"original": battle_runtime, "experimental": experimental_runtime}
|
self._battle_runtimes = {"original": battle_runtime, "experimental": experimental_runtime}
|
||||||
self._selected_battle_mode = "original"
|
self._selected_battle_mode = "original"
|
||||||
|
self._sweep_recovery_cache = {}
|
||||||
|
self._sweep_recovery_message = ""
|
||||||
|
|
||||||
def _map_catalog(self):
|
def _map_catalog(self):
|
||||||
if self.resource_catalog is None:
|
if self.resource_catalog is None:
|
||||||
@@ -384,6 +392,8 @@ class Engine:
|
|||||||
self.game_data = load_progression_data()
|
self.game_data = load_progression_data()
|
||||||
if self.progression_planner is None:
|
if self.progression_planner is None:
|
||||||
self.progression_planner = ProgressionPlanner(self.catalog, self.game_data, account_key=self._progression_namespace)
|
self.progression_planner = ProgressionPlanner(self.catalog, self.game_data, account_key=self._progression_namespace)
|
||||||
|
self.progression_planner.guard.cultivation = self.cultivation
|
||||||
|
self.progression_planner.procurement_daily_left = self.purchase_budget.remaining(self.snapshot.now, self.policy.daily_buy_money) if self.snapshot else 0
|
||||||
# This is a read-only preflight; the same check must precede navigation
|
# This is a read-only preflight; the same check must precede navigation
|
||||||
# and dialogue, not just the battle action they lead to.
|
# and dialogue, not just the battle action they lead to.
|
||||||
self.progression_planner.battle_capability = self._battle_capability
|
self.progression_planner.battle_capability = self._battle_capability
|
||||||
@@ -454,6 +464,10 @@ class Engine:
|
|||||||
self.battle_journal.save()
|
self.battle_journal.save()
|
||||||
|
|
||||||
def _battle_observer(self, event, intent, response):
|
def _battle_observer(self, event, intent, response):
|
||||||
|
if event == "started" and self._is_commission(intent):
|
||||||
|
record = self.battle_journal.pending(self.snapshot)
|
||||||
|
if record is not None:
|
||||||
|
self._journal_commission(record, intent)
|
||||||
if value(intent, "kind") == "map_battle":
|
if value(intent, "kind") == "map_battle":
|
||||||
stage = SimpleNamespace(stage_id=str(value(intent, "stage_id")), level=str(value(intent, "difficulty")))
|
stage = SimpleNamespace(stage_id=str(value(intent, "stage_id")), level=str(value(intent, "difficulty")))
|
||||||
key = self.sweeper.key(self.snapshot, stage)
|
key = self.sweeper.key(self.snapshot, stage)
|
||||||
@@ -487,6 +501,11 @@ class Engine:
|
|||||||
if farming:
|
if farming:
|
||||||
if event == "started":
|
if event == "started":
|
||||||
planner.mark_started(self.snapshot, intent) # validates the issued ordinary intent only
|
planner.mark_started(self.snapshot, intent) # validates the issued ordinary intent only
|
||||||
|
elif event in ("settled", "event"):
|
||||||
|
record = self.battle_journal.pending(self.snapshot)
|
||||||
|
if record is not None:
|
||||||
|
self.battle_journal.update(record, record["phase"],
|
||||||
|
commission_action_response=gameplay_response(response), commission_action_confirmed=True)
|
||||||
# Farming is a normal map action. Its journal and fresh server
|
# Farming is a normal map action. Its journal and fresh server
|
||||||
# snapshot govern the result; it never acknowledges a task step.
|
# snapshot govern the result; it never acknowledges a task step.
|
||||||
return None
|
return None
|
||||||
@@ -517,6 +536,7 @@ class Engine:
|
|||||||
|
|
||||||
def _recover_confirmed_progression(self):
|
def _recover_confirmed_progression(self):
|
||||||
"""Replay only local acknowledgement of a durably received success."""
|
"""Replay only local acknowledgement of a durably received success."""
|
||||||
|
self._reconcile_procurement()
|
||||||
record = self.battle_journal.pending(self.snapshot)
|
record = self.battle_journal.pending(self.snapshot)
|
||||||
if (not record or str(record.get("role_id")) != str(self.snapshot.raw["master"].get("id"))
|
if (not record or str(record.get("role_id")) != str(self.snapshot.raw["master"].get("id"))
|
||||||
or not str(record.get("kind", "")).startswith("progression_")):
|
or not str(record.get("kind", "")).startswith("progression_")):
|
||||||
@@ -570,14 +590,46 @@ class Engine:
|
|||||||
or self._breakthrough_pending and now - self._breakthrough_pending_last_check >= 120))
|
or self._breakthrough_pending and now - self._breakthrough_pending_last_check >= 120))
|
||||||
return not self.demo and bool(automation or self._progression_pending() and now - self.last_pending_check >= 120)
|
return not self.demo and bool(automation or self._progression_pending() and now - self.last_pending_check >= 120)
|
||||||
|
|
||||||
def _resume_pending_task_clock(self):
|
def pending_battle_recovery(self):
|
||||||
|
"""Read-only recovery contract for desktop/Web pending guards."""
|
||||||
|
record = self.battle_journal.pending(self.snapshot) if self.snapshot is not None else None
|
||||||
|
status = self.battles.recovery_status(record, snapshot=self.snapshot)
|
||||||
|
if status["resumable"]:
|
||||||
|
if self.game_data is None and (record.get("source_task_type_id") or record.get("task_type_id")):
|
||||||
|
from .game_data import load_progression_data
|
||||||
|
self.game_data = load_progression_data()
|
||||||
|
if not self._intent_policy(record).enabled:
|
||||||
|
origin = ("自动扫荡" if record.get("kind") in ("map_battle", "map_sweep") else
|
||||||
|
"自动委托" if self._is_commission(record) else "自动主线")
|
||||||
|
return {"state": "blocked_policy", "resumable": False,
|
||||||
|
"message": "等待启用" + origin + "来源策略;已保留待核对战斗"}
|
||||||
|
return status
|
||||||
|
|
||||||
|
def _resume_pending_task_clock(self, *, running=None, generation=None):
|
||||||
record = self.battle_journal.pending(self.snapshot)
|
record = self.battle_journal.pending(self.snapshot)
|
||||||
if not self.auto or self._progression_cancel.is_set() or not self.battles.resumable_task_clock(record):
|
if not self.pending_battle_recovery()["resumable"]:
|
||||||
return ""
|
return ""
|
||||||
if record.get("kind") == "map_battle":
|
with self._progression_cancel_lock:
|
||||||
|
if (not (self.auto if running is None else running is True)
|
||||||
|
or generation is not None and generation != self._progression_cancel_generation):
|
||||||
|
return ""
|
||||||
|
# Web deliberately keeps auto=False. Only its current running intent
|
||||||
|
# may rearm an older cancellation; a newer Stop always wins.
|
||||||
|
if running is True and self._progression_cancel.is_set():
|
||||||
|
self._progression_cancel = threading.Event()
|
||||||
|
cancel = self._progression_cancel
|
||||||
|
if cancel.is_set():
|
||||||
|
return ""
|
||||||
|
if not record.get("task_id"):
|
||||||
intent = {key: record.get(key) for key in ("kind", "task_id", "task_type_id", "step_number", "stage_category",
|
intent = {key: record.get(key) for key in ("kind", "task_id", "task_type_id", "step_number", "stage_category",
|
||||||
"stage_id", "difficulty", "battle_kind", "team", "path")}
|
"stage_id", "difficulty", "battle_kind", "team", "path", "source_task_id", "source_task_type_id", "source_step_number")}
|
||||||
return self.battles.resume_task_clock(self.client, self.snapshot, intent, self._map_policy(), cancel=self._progression_cancel)
|
policy = self._intent_policy(intent)
|
||||||
|
if record.get("sweep_sample_id"):
|
||||||
|
self._select_battle_runtime(record["battle_mode"])
|
||||||
|
return self.battles.continue_sweep(self.client, self.snapshot, policy, cancel=cancel)
|
||||||
|
if self.pending_battle_recovery()["state"] == "retry_local_runtime":
|
||||||
|
self._select_battle_runtime(record["battle_mode"])
|
||||||
|
return self.battles.resume_task_clock(self.client, self.snapshot, intent, policy, cancel=cancel)
|
||||||
pending = self.progression_planner.pending(self.snapshot) if self.progression_planner else None
|
pending = self.progression_planner.pending(self.snapshot) if self.progression_planner else None
|
||||||
if not pending or not isinstance(pending.get("intent"), dict):
|
if not pending or not isinstance(pending.get("intent"), dict):
|
||||||
return ""
|
return ""
|
||||||
@@ -589,8 +641,10 @@ class Engine:
|
|||||||
if intent.token in issued and issued[intent.token] != intent.to_dict():
|
if intent.token in issued and issued[intent.token] != intent.to_dict():
|
||||||
return ""
|
return ""
|
||||||
issued[intent.token] = intent.to_dict()
|
issued[intent.token] = intent.to_dict()
|
||||||
|
if self.pending_battle_recovery()["state"] == "retry_local_runtime":
|
||||||
|
self._select_battle_runtime(record["battle_mode"])
|
||||||
return self.battles.resume_task_clock(self.client, self.snapshot, intent, self._intent_policy(intent),
|
return self.battles.resume_task_clock(self.client, self.snapshot, intent, self._intent_policy(intent),
|
||||||
cancel=self._progression_cancel)
|
cancel=cancel)
|
||||||
|
|
||||||
def _battle_capability(self, intent):
|
def _battle_capability(self, intent):
|
||||||
try:
|
try:
|
||||||
@@ -630,7 +684,11 @@ class Engine:
|
|||||||
supported, reason = self._commission_offer_checks[key]
|
supported, reason = self._commission_offer_checks[key]
|
||||||
if not supported:
|
if not supported:
|
||||||
intent = replace(intent, block_reason=reason)
|
intent = replace(intent, block_reason=reason)
|
||||||
if (value(intent, "kind") in ("progression_battle", "battle", "task_battle", "stage_battle", "map_battle")
|
# Local battle preludes share the planner's cached input preflight.
|
||||||
|
prelude = value(intent, "task_id") and value(intent, "battle_kind") in battle_kinds and (
|
||||||
|
value(intent, "kind") == "progression_navigate" or
|
||||||
|
value(intent, "kind") == "progression_dialogue" and value(intent, "phase") == "before")
|
||||||
|
if (prelude or value(intent, "kind") in ("progression_battle", "battle", "task_battle", "stage_battle", "map_battle")
|
||||||
or self._is_farm(intent) and not self._is_sweep_intent(intent)) and not value(intent, "block_reason"):
|
or self._is_farm(intent) and not self._is_sweep_intent(intent)) and not value(intent, "block_reason"):
|
||||||
supported, reason = self._battle_capability(intent)
|
supported, reason = self._battle_capability(intent)
|
||||||
reasons[str(value(intent, "source_task_type_id") or value(intent, "task_type_id"))] = (supported, reason)
|
reasons[str(value(intent, "source_task_type_id") or value(intent, "task_type_id"))] = (supported, reason)
|
||||||
@@ -643,7 +701,8 @@ class Engine:
|
|||||||
source_supported = row.get("supported") is not False
|
source_supported = row.get("supported") is not False
|
||||||
check = self._commission_offer_checks.get(str(row.get("task_type_id")))
|
check = self._commission_offer_checks.get(str(row.get("task_type_id")))
|
||||||
if row.get("category") == "commission" and row.get("state") == "offered" and check is not None:
|
if row.get("category") == "commission" and row.get("state") == "offered" and check is not None:
|
||||||
row.update(block_reason=check[1], next_action="接取城市委托" if check[0] else "暂不接取:" + check[1])
|
if not check[0]:
|
||||||
|
row.update(block_reason=check[1], next_action="暂不接取:" + check[1])
|
||||||
commission = commissions.get(str(row.get("task_type_id")))
|
commission = commissions.get(str(row.get("task_type_id")))
|
||||||
if commission is not None:
|
if commission is not None:
|
||||||
row.update(next_action=value(commission, "description"), block_reason=value(commission, "block_reason", ""))
|
row.update(next_action=value(commission, "description"), block_reason=value(commission, "block_reason", ""))
|
||||||
@@ -654,13 +713,15 @@ class Engine:
|
|||||||
stage_id=value(farm, "stage_id"), difficulty=value(farm, "difficulty"))
|
stage_id=value(farm, "stage_id"), difficulty=value(farm, "difficulty"))
|
||||||
reason = row.get("block_reason") or row.get("blocked_reason") or ""
|
reason = row.get("block_reason") or row.get("blocked_reason") or ""
|
||||||
if row.get("battle_kind") in battle_kinds:
|
if row.get("battle_kind") in battle_kinds:
|
||||||
supported, runtime_reason = reasons.get(str(row.get("task_type_id")),
|
supported, runtime_reason = reasons.get(str(row.get("task_type_id")), (None, ""))
|
||||||
(False, "战斗运行时能力尚未核对;配置存在不代表已支持实战"))
|
|
||||||
row["supported"] = bool(source_supported and supported and not reason)
|
|
||||||
reason = reason or runtime_reason
|
reason = reason or runtime_reason
|
||||||
|
row["supported"] = False if not source_supported or reason else supported
|
||||||
else:
|
else:
|
||||||
row["supported"] = bool(source_supported and not reason)
|
row["supported"] = bool(source_supported and not reason)
|
||||||
row["block_reason"] = row["blocked_reason"] = reason
|
row["block_reason"] = row["blocked_reason"] = reason
|
||||||
|
row["reason_kind"] = "unchecked" if row["supported"] is None else commission_reason_kind(reason)
|
||||||
|
if row["supported"] is None and row.get("category") == "mainline" and not self.progression_policy.enabled:
|
||||||
|
row.setdefault("status", "自动主线策略未启用")
|
||||||
return rows, adjusted
|
return rows, adjusted
|
||||||
|
|
||||||
def _battle_request(self, snapshot, intent, policy, request):
|
def _battle_request(self, snapshot, intent, policy, request):
|
||||||
@@ -701,6 +762,108 @@ class Engine:
|
|||||||
info = self.game_data.task(value(intent, "source_task_type_id") or value(intent, "task_type_id")) if self.game_data else None
|
info = self.game_data.task(value(intent, "source_task_type_id") or value(intent, "task_type_id")) if self.game_data else None
|
||||||
return bool(info and info.get("type") == 4)
|
return bool(info and info.get("type") == 4)
|
||||||
|
|
||||||
|
def _commission_info(self, type_id):
|
||||||
|
info = self.game_data.task(type_id) if self.game_data and type_id else None
|
||||||
|
return info or self.catalog.data.get("task_info", {}).get(str(type_id)) or {}
|
||||||
|
|
||||||
|
def _sync_commission_history(self):
|
||||||
|
"""Use the already loaded, bounded journal; ledger failures never retry a game write."""
|
||||||
|
if self.snapshot is None or self.snapshot.raw.get("master", {}).get("id") is None:
|
||||||
|
return
|
||||||
|
role = str(self.snapshot.raw["master"]["id"])
|
||||||
|
try:
|
||||||
|
records = self.battle_journal.role(self.snapshot)["records"]
|
||||||
|
self._commission_history.ingest(role, records, self._commission_info, self.snapshot)
|
||||||
|
self._commission_history_roles.add(role)
|
||||||
|
except (OSError, ValueError, TypeError, KeyError, AttributeError):
|
||||||
|
self._commission_history.warning = "委托历史暂未写入磁盘;任务回包仍保存在原日志,稍后核对导入,请勿重发"
|
||||||
|
|
||||||
|
@account_serial
|
||||||
|
def commission_history(self, day=None):
|
||||||
|
"""Independent plain DTO; day is YYYY-MM-DD in Beijing, default wall-clock today.
|
||||||
|
|
||||||
|
summary: accepted_count/completed_count/pending_count/expected_ke/
|
||||||
|
confirmed_ke/unknown_reward_count. Unknown row rewards are None.
|
||||||
|
Only events on the selected day contribute to daily counts and rewards.
|
||||||
|
"""
|
||||||
|
role = str(self.snapshot.raw.get("master", {}).get("id", "")) if self.snapshot else ""
|
||||||
|
if role and (role not in self._commission_history_roles or self._commission_history._dirty):
|
||||||
|
self._sync_commission_history()
|
||||||
|
return self._commission_history.query(role, day)
|
||||||
|
|
||||||
|
@account_serial
|
||||||
|
def commission_offer_diagnostics(self):
|
||||||
|
"""Cached offline eligibility; no journal reload, game calls or runtime inspection."""
|
||||||
|
if self.snapshot is None:
|
||||||
|
return []
|
||||||
|
self._ensure_commission_diagnostics()
|
||||||
|
return deepcopy(self._commission_offer_diagnostics)
|
||||||
|
|
||||||
|
def _ensure_commission_diagnostics(self):
|
||||||
|
key = (id(self.snapshot), digest({"quest": vars(self.quest_policy), "ranch": vars(self.policy),
|
||||||
|
"progression": vars(self.progression_policy), "checks": self._commission_offer_checks,
|
||||||
|
"budget": self.purchase_budget.remaining(self.snapshot.now, self.policy.daily_buy_money),
|
||||||
|
"state": self.progression_planner.state_signature(self.snapshot) if self.progression_planner else ""}))
|
||||||
|
if key == self._commission_diagnostics_key:
|
||||||
|
return
|
||||||
|
if self.progression_planner is None:
|
||||||
|
self._ensure_progression()
|
||||||
|
# Reuse model checks from the worker's last planning pass. A missing
|
||||||
|
# check remains explicitly unverified until that worker runs.
|
||||||
|
self._commission_offer_diagnostics = self.progression_planner.commission_offers(
|
||||||
|
self.snapshot, self.quest_policy, self.policy, battle_policy=self.progression_policy,
|
||||||
|
accept_supported=lambda key: self._commission_offer_checks.get(str(key),
|
||||||
|
(False, "后续步骤或战斗能力尚未验证,等待后台检查")))
|
||||||
|
self._commission_diagnostics_key = key
|
||||||
|
|
||||||
|
def _journal_commission(self, record, intent, *, legacy=False):
|
||||||
|
type_id = str(value(intent, "source_task_type_id") or value(intent, "task_type_id") or "")
|
||||||
|
info = self._commission_info(type_id)
|
||||||
|
if info.get("type", 4 if legacy else None) != 4 and value(intent, "kind") not in ("progression_loop_reset", "quest_reset"):
|
||||||
|
return
|
||||||
|
selected = getattr(self.tasks if legacy else self.progression_planner, "commission_selection", {}) or {}
|
||||||
|
accepting = (record.get("path") or "").endswith("taskLoopReceive")
|
||||||
|
meta = {"name": info.get("name", type_id or "每日委托"), "expected_ke": -commission_priority(info),
|
||||||
|
"city": (record.get("payload") or {}).get("city")}
|
||||||
|
number = value(intent, "source_step_number") or value(intent, "step_number") or 0
|
||||||
|
steps = info.get("steps") or []
|
||||||
|
if 1 <= number <= len(steps):
|
||||||
|
step = steps[number - 1]
|
||||||
|
kind, required = step.get("statusType"), step.get("statusValue") or {}
|
||||||
|
remove = required.get("remove") is True
|
||||||
|
prefix = "提交" if remove else "核对持有"
|
||||||
|
type_key, count = str(required.get("type", "")), required.get("num", 0)
|
||||||
|
if kind == "getMoney":
|
||||||
|
detail = f"{prefix}金币×{required.get('money', 0)}"
|
||||||
|
elif kind == "getItem" or kind == "getMonster" and required.get("mode") == 0:
|
||||||
|
name = self.catalog.monster(type_key).get("name", type_key) + "蛋" if type_key in self.catalog.monsters else self.catalog.data.get("item_names", {}).get(type_key, f"道具#{type_key}")
|
||||||
|
detail = f"{prefix}{name}×{count}"
|
||||||
|
elif kind == "getMonster":
|
||||||
|
detail = f"{prefix}{self.catalog.monster(type_key).get('name', '魔物#' + type_key)}×{count}"
|
||||||
|
elif kind == "passStage":
|
||||||
|
stage = self.game_data.stage(required.get("stage")) if self.game_data else None
|
||||||
|
detail = f"通关{(stage or {}).get('name', required.get('stage', '指定关卡'))},难度{required.get('level', 1)}"
|
||||||
|
elif kind == "battle":
|
||||||
|
detail = "完成委托专用战斗"
|
||||||
|
elif kind == "none":
|
||||||
|
detail = "完成对话条件"
|
||||||
|
elif kind == "killMonster":
|
||||||
|
detail = f"核对{self.catalog.monster(type_key).get('name', '魔物#' + type_key)}累计击杀数量"
|
||||||
|
elif kind == "passLevel":
|
||||||
|
detail = f"核对角色等级达到{required.get('level', 0)}级"
|
||||||
|
else:
|
||||||
|
detail = str(value(intent, "description", ""))
|
||||||
|
meta["operation_detail"] = detail
|
||||||
|
if accepting and selected.get("task_type_id") == type_id:
|
||||||
|
meta.update(deepcopy(selected))
|
||||||
|
self.battle_journal.update(record, record["phase"], commission=meta)
|
||||||
|
|
||||||
|
def _commission_message(self, record, default):
|
||||||
|
self._sync_commission_history()
|
||||||
|
role = str(self.snapshot.raw["master"].get("id", ""))
|
||||||
|
event = self._commission_history.state["roles"].get(role, {}).get(str(record.get("attempt_id")))
|
||||||
|
return event["description"] if event else default
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _is_farm(intent):
|
def _is_farm(intent):
|
||||||
return bool(value(intent, "source_task_type_id")) and not value(intent, "task_id") and bool(value(intent, "stage_id"))
|
return bool(value(intent, "source_task_type_id")) and not value(intent, "task_id") and bool(value(intent, "stage_id"))
|
||||||
@@ -710,6 +873,8 @@ class Engine:
|
|||||||
return value(intent, "kind") in ("sweep", "progression_sweep", "progression_farm_sweep", "progression_map_sweep") or value(intent, "battle_kind") == "sweep"
|
return value(intent, "kind") in ("sweep", "progression_sweep", "progression_farm_sweep", "progression_map_sweep") or value(intent, "battle_kind") == "sweep"
|
||||||
|
|
||||||
def _intent_policy(self, intent):
|
def _intent_policy(self, intent):
|
||||||
|
if value(intent, "kind") == "map_sweep":
|
||||||
|
return SimpleNamespace(**(vars(self._map_policy()) | {"enabled": self.sweep_policy.enabled}))
|
||||||
if value(intent, "kind") == "map_battle":
|
if value(intent, "kind") == "map_battle":
|
||||||
return self._map_policy()
|
return self._map_policy()
|
||||||
if not self._is_commission(intent):
|
if not self._is_commission(intent):
|
||||||
@@ -725,18 +890,26 @@ class Engine:
|
|||||||
"" if supported else self._commission_offer_reason or "委托后续步骤当前无法自动完成")
|
"" if supported else self._commission_offer_reason or "委托后续步骤当前无法自动完成")
|
||||||
return supported
|
return supported
|
||||||
|
|
||||||
|
def _commission_offer_eligibility(self, type_id):
|
||||||
|
self._check_commission_offer(type_id)
|
||||||
|
return self._commission_offer_checks[str(type_id)]
|
||||||
|
|
||||||
def _commission_offer_supported(self, type_id):
|
def _commission_offer_supported(self, type_id):
|
||||||
self._commission_offer_reason = "委托后续条件、剧情或战斗未验证支持,未消耗接取次数"
|
self._commission_offer_reason = "委托后续条件、剧情或战斗未验证支持,未消耗接取次数"
|
||||||
info = self.game_data.task(type_id)
|
info = self.game_data.task(type_id)
|
||||||
if not info or info.get("type") != 4:
|
if not info or info.get("type") != 4:
|
||||||
|
self._commission_offer_reason = "委托配置缺失或类型不符"
|
||||||
return False
|
return False
|
||||||
for number, step in enumerate(info.get("steps", []), 1):
|
for number, step in enumerate(info.get("steps", []), 1):
|
||||||
for name in (step.get("story"), step.get("afterStory")):
|
for name in (step.get("story"), step.get("afterStory")):
|
||||||
if name and (self.game_data.script(name) or {}).get("supported") is not True:
|
if name and (self.game_data.script(name) or {}).get("supported") is not True:
|
||||||
|
script = self.game_data.script(name) or {}
|
||||||
|
self._commission_offer_reason = f"第{number}步剧情 {name} 未验证支持" + (":" + ";".join(script.get("block_reasons") or []) if script.get("block_reasons") else "")
|
||||||
return False
|
return False
|
||||||
kind = step.get("statusType")
|
kind = step.get("statusType")
|
||||||
if kind in ("battle", "passStage"):
|
if kind in ("battle", "passStage"):
|
||||||
if not self.quest_policy.battle_tasks:
|
if not self.quest_policy.battle_tasks:
|
||||||
|
self._commission_offer_reason = "委托战斗开关未启用"
|
||||||
return False
|
return False
|
||||||
intent = {"kind": "progression_battle", "task_type_id": str(type_id), "task_id": 0,
|
intent = {"kind": "progression_battle", "task_type_id": str(type_id), "task_id": 0,
|
||||||
"step_number": number, "battle_kind": "passStage" if kind == "passStage" else "task",
|
"step_number": number, "battle_kind": "passStage" if kind == "passStage" else "task",
|
||||||
@@ -748,12 +921,31 @@ class Engine:
|
|||||||
return False
|
return False
|
||||||
else:
|
else:
|
||||||
policy = self._intent_policy({"task_type_id": str(type_id)})
|
policy = self._intent_policy({"task_type_id": str(type_id)})
|
||||||
ready, _, _ = self.progression_planner.requirement(self.snapshot, step, {}, policy, self.policy)
|
ready, _, requirement_reason = self.progression_planner.requirement(self.snapshot, step, {}, policy, self.policy)
|
||||||
if not ready:
|
if not ready:
|
||||||
|
if resource_kind(step) and isinstance(self.progression_planner, ProgressionPlanner):
|
||||||
|
supply = self.progression_planner.resource_plan(self.snapshot, info.get("steps") or [],
|
||||||
|
{"id": 0, "typeId": str(type_id), "curStep": number}, policy, self.policy)
|
||||||
|
if supply.feasible:
|
||||||
|
continue
|
||||||
|
self._commission_offer_reason = supply.reason
|
||||||
|
return False
|
||||||
sources = self.progression_planner.farming_intents(self.snapshot, step,
|
sources = self.progression_planner.farming_intents(self.snapshot, step,
|
||||||
{"id": 0, "typeId": str(type_id), "curStep": number}, policy, self.policy)
|
{"id": 0, "typeId": str(type_id), "curStep": number}, policy, self.policy)
|
||||||
if not any(self._is_sweep_intent(source) or self._battle_capability(source)[0] for source in sources):
|
source_reasons = []
|
||||||
|
feasible = False
|
||||||
|
for source in sources:
|
||||||
|
supported, reason = (True, "") if self._is_sweep_intent(source) else self._battle_capability(source)
|
||||||
|
if supported:
|
||||||
|
feasible = True
|
||||||
|
break
|
||||||
|
if reason:
|
||||||
|
source_reasons.append(reason)
|
||||||
|
if not feasible:
|
||||||
|
self._commission_offer_reason = f"第{number}步:{requirement_reason}" + (";材料来源:" + ";".join(source_reasons) if source_reasons else ";没有当前可用的自动收集来源")
|
||||||
return False
|
return False
|
||||||
|
if not info.get("steps"):
|
||||||
|
self._commission_offer_reason = "委托没有有效步骤"
|
||||||
return bool(info.get("steps"))
|
return bool(info.get("steps"))
|
||||||
|
|
||||||
def _refresh_progression_cache(self, *, force=False):
|
def _refresh_progression_cache(self, *, force=False):
|
||||||
@@ -770,28 +962,43 @@ class Engine:
|
|||||||
"snapshot": self._battle_snapshot_digest, "runtime": id(self.battles.runtime)})
|
"snapshot": self._battle_snapshot_digest, "runtime": id(self.battles.runtime)})
|
||||||
key = digest({"snapshot": self._battle_snapshot_digest, "policy": vars(self.progression_policy),
|
key = digest({"snapshot": self._battle_snapshot_digest, "policy": vars(self.progression_policy),
|
||||||
"quests": vars(self.quest_policy), "ranch": vars(self.policy), "local_state": self.progression_planner.state_signature(self.snapshot),
|
"quests": vars(self.quest_policy), "ranch": vars(self.policy), "local_state": self.progression_planner.state_signature(self.snapshot),
|
||||||
"pending": self._progression_pending(), "runtime": id(self.battles.runtime), "day": int(self.snapshot.now // 86400)})
|
"purchase_left": self.progression_planner.procurement_daily_left,
|
||||||
|
"pending": self._progression_pending(), "runtime": id(self.battles.runtime),
|
||||||
|
"day": ProgressionPlanner._loop_day(self.snapshot, self.snapshot.now - 10)})
|
||||||
if force or key != self._progression_cache_key:
|
if force or key != self._progression_cache_key:
|
||||||
self._commission_offer_checks = {}
|
self._commission_offer_checks = {}
|
||||||
|
self._commission_diagnostics_key = None
|
||||||
rows = self.progression_planner.rows(self.snapshot, self.progression_policy, self.policy, quest_policy=self.quest_policy)
|
rows = self.progression_planner.rows(self.snapshot, self.progression_policy, self.policy, quest_policy=self.quest_policy)
|
||||||
intents = self.progression_planner.plan(self.snapshot, self.progression_policy, self.policy)
|
intents = self.progression_planner.plan(self.snapshot, self.progression_policy, self.policy)
|
||||||
commission_plan = getattr(self.progression_planner, "commission_plan", None)
|
commission_plan = getattr(self.progression_planner, "commission_plan", None)
|
||||||
self._commission_planner_available = callable(commission_plan)
|
self._commission_planner_available = callable(commission_plan)
|
||||||
if self._commission_planner_available:
|
if self._commission_planner_available:
|
||||||
intents += commission_plan(self.snapshot, self.quest_policy, self.policy,
|
intents += commission_plan(self.snapshot, self.quest_policy, self.policy,
|
||||||
battle_policy=self.progression_policy, accept_supported=self._check_commission_offer)
|
battle_policy=self.progression_policy, accept_supported=self._commission_offer_eligibility)
|
||||||
|
self._commission_offer_diagnostics = deepcopy(self.progression_planner.commission_offer_rows)
|
||||||
intents.sort(key=lambda intent: not self._is_commission(intent))
|
intents.sort(key=lambda intent: not self._is_commission(intent))
|
||||||
self._progression_rows, self._progression_intents = self._overlay_battle_capabilities(rows, intents)
|
self._progression_rows, self._progression_intents = self._overlay_battle_capabilities(rows, intents)
|
||||||
|
for row in self._progression_rows:
|
||||||
|
if row.get("category") == "commission" and row.get("state") == "offered":
|
||||||
|
offer = next((r for r in self._commission_offer_diagnostics if r["task_type_id"] == row["task_type_id"]), None)
|
||||||
|
if offer:
|
||||||
|
row.update(reason_kind=offer["reason_kind"], resources=offer["resources"],
|
||||||
|
progress_plan=offer["progress_plan"], next_action=offer["next_step"],
|
||||||
|
block_reason="" if offer["eligible"] else offer["reason"],
|
||||||
|
blocked_reason="" if offer["eligible"] else offer["reason"], supported=offer["eligible"])
|
||||||
self._persist_progression()
|
self._persist_progression()
|
||||||
self._progression_cache_key = digest({"snapshot": self._battle_snapshot_digest, "policy": vars(self.progression_policy),
|
self._progression_cache_key = digest({"snapshot": self._battle_snapshot_digest, "policy": vars(self.progression_policy),
|
||||||
"quests": vars(self.quest_policy), "ranch": vars(self.policy), "local_state": self.progression_planner.state_signature(self.snapshot),
|
"quests": vars(self.quest_policy), "ranch": vars(self.policy), "local_state": self.progression_planner.state_signature(self.snapshot),
|
||||||
"pending": self._progression_pending(), "runtime": id(self.battles.runtime), "day": int(self.snapshot.now // 86400)})
|
"purchase_left": self.progression_planner.procurement_daily_left,
|
||||||
|
"pending": self._progression_pending(), "runtime": id(self.battles.runtime),
|
||||||
|
"day": ProgressionPlanner._loop_day(self.snapshot, self.snapshot.now - 10)})
|
||||||
self._progression_error = ""
|
self._progression_error = ""
|
||||||
except (ImportError, OSError, ValueError, TypeError, KeyError, AttributeError) as error:
|
except (ImportError, OSError, ValueError, TypeError, KeyError, AttributeError) as error:
|
||||||
self._progression_error = "任务规划暂不可用:" + str(error)
|
self._progression_error = "任务规划暂不可用:" + str(error)
|
||||||
self._progression_rows = [{"state": "unsupported", "supported": False, "blocked_reason": self._progression_error}]
|
self._progression_rows = [{"state": "unsupported", "supported": False, "blocked_reason": self._progression_error}]
|
||||||
self._progression_intents = []
|
self._progression_intents = []
|
||||||
self._progression_records = self.battle_journal.records(self.snapshot)
|
self._progression_records = self.battle_journal.records(self.snapshot)
|
||||||
|
self._sync_commission_history()
|
||||||
|
|
||||||
@account_serial
|
@account_serial
|
||||||
def refresh_progression(self):
|
def refresh_progression(self):
|
||||||
@@ -838,9 +1045,17 @@ class Engine:
|
|||||||
try:
|
try:
|
||||||
self.last_executed = True
|
self.last_executed = True
|
||||||
kind = value(intent, "kind")
|
kind = value(intent, "kind")
|
||||||
|
self._sync_commission_history()
|
||||||
if kind in ("progression_battle", "battle", "task_battle", "stage_battle", "map_battle", "sweep") or self._is_farm(intent):
|
if kind in ("progression_battle", "battle", "task_battle", "stage_battle", "map_battle", "sweep") or self._is_farm(intent):
|
||||||
|
previous_attempts = {record["attempt_id"] for record in self.battle_journal.role(self.snapshot)["records"]}
|
||||||
message = self.battles.run(self.client, self.snapshot, intent, effective_policy,
|
message = self.battles.run(self.client, self.snapshot, intent, effective_policy,
|
||||||
cancel=self._progression_cancel, ranch=self.policy)
|
cancel=self._progression_cancel, ranch=self.policy)
|
||||||
|
records = [record for record in self.battle_journal.role(self.snapshot)["records"]
|
||||||
|
if record["attempt_id"] not in previous_attempts]
|
||||||
|
if records:
|
||||||
|
message = self._commission_message(records[-1], message)
|
||||||
|
elif kind == "progression_procure":
|
||||||
|
message = self._execute_procurement(intent)
|
||||||
else:
|
else:
|
||||||
message = self._execute_task_intent(intent)
|
message = self._execute_task_intent(intent)
|
||||||
if self.battle_journal.pending(self.snapshot) and kind == "progression_battle":
|
if self.battle_journal.pending(self.snapshot) and kind == "progression_battle":
|
||||||
@@ -853,13 +1068,125 @@ class Engine:
|
|||||||
self.read_snapshot(sync_master=False)
|
self.read_snapshot(sync_master=False)
|
||||||
return self.snapshot, self.plans(), message
|
return self.snapshot, self.plans(), message
|
||||||
except Exception:
|
except Exception:
|
||||||
if self.battle_journal.pending(self.snapshot) and not self._is_farm(intent) and value(intent, "kind", "").startswith("progression_"):
|
if self.battle_journal.pending(self.snapshot) and not self._is_farm(intent) and value(intent, "kind") != "progression_procure" and value(intent, "kind", "").startswith("progression_"):
|
||||||
self.progression_planner.mark_uncertain(self.snapshot, intent, "任务 / 战斗结果待核对,禁止重放")
|
self.progression_planner.mark_uncertain(self.snapshot, intent, "任务 / 战斗结果待核对,禁止重放")
|
||||||
self._persist_progression()
|
self._persist_progression()
|
||||||
raise
|
raise
|
||||||
finally:
|
finally:
|
||||||
|
self._sync_commission_history()
|
||||||
self._refresh_progression_cache(force=True)
|
self._refresh_progression_cache(force=True)
|
||||||
|
|
||||||
|
def _execute_procurement(self, intent):
|
||||||
|
"""Journal resource writes separately; never advance a task cursor."""
|
||||||
|
if self._progression_cancel.is_set() or self._progression_pending():
|
||||||
|
return "补资源已取消或有待核对请求;未发送"
|
||||||
|
planner = self.progression_planner
|
||||||
|
planner.mark_started(self.snapshot, intent) # validates account and issued payload only
|
||||||
|
key = str(value(intent, "source_task_type_id"))
|
||||||
|
policy = self._intent_policy(intent)
|
||||||
|
source_id = int(value(intent, "source_task_id", 0) or 0)
|
||||||
|
info = self._commission_info(key)
|
||||||
|
if source_id:
|
||||||
|
source = next((t for t in self.snapshot.raw.get("currentTasks", [])
|
||||||
|
if int(t.get("id", 0)) == source_id and str(t.get("typeId")) == key), None)
|
||||||
|
if source is None:
|
||||||
|
return "资源来源任务已变化,等待重新规划;未发送"
|
||||||
|
else:
|
||||||
|
offers = planner.commission_offers(self.snapshot, self.quest_policy, self.policy,
|
||||||
|
battle_policy=self.progression_policy, accept_supported=self._commission_offer_eligibility)
|
||||||
|
if not any(row["task_type_id"] == key and row.get("preparable") for row in offers):
|
||||||
|
return "委托额度、城市或资源条件已变化,未采购、未消耗接取次数"
|
||||||
|
source = {"id": 0, "typeId": key}
|
||||||
|
planner.procurement_daily_left = self.purchase_budget.remaining(self.snapshot.now, self.policy.daily_buy_money)
|
||||||
|
supply = planner.remaining_resource_plan(self.snapshot, info, source, policy, self.policy)
|
||||||
|
action = supply.action
|
||||||
|
if not supply.feasible or action is None or action.path != value(intent, "path") or action.payload != value(intent, "payload"):
|
||||||
|
return "资源缺口或保护状态已变化,等待重新规划;未发送"
|
||||||
|
allowed = {"gachaService/gachaGetEggs": {"id", "num", "voucherNum", "traceInfo"},
|
||||||
|
"stackService/stackAddMonster": {"eggs"}, "stackService/stackTransferMonster": {"datas"}}
|
||||||
|
if action.path not in allowed or set(action.payload) != allowed[action.path]:
|
||||||
|
return "补资源请求未验证,未发送"
|
||||||
|
def admission_signature():
|
||||||
|
return digest({"snapshot": self.snapshot.raw, "quest": vars(self.quest_policy), "ranch": vars(self.policy),
|
||||||
|
"progression": vars(self.progression_policy), "task": self._commission_info(key),
|
||||||
|
"day": planner._loop_day(self.snapshot, self.snapshot.now - 10)})
|
||||||
|
admitted = admission_signature()
|
||||||
|
self._sync_commission_history()
|
||||||
|
record = self.battle_journal.begin(self.snapshot, intent)
|
||||||
|
self._journal_commission(record, intent)
|
||||||
|
baseline = {str(i["typeId"]): 0 for i in self.snapshot.raw["items"]}
|
||||||
|
for item in self.snapshot.raw["items"]:
|
||||||
|
baseline[str(item["typeId"])] += max(0, int(item.get("num", 0)))
|
||||||
|
self.battle_journal.update(record, "prepared", procurement_baseline=baseline)
|
||||||
|
dispatched = False
|
||||||
|
try:
|
||||||
|
if self._progression_cancel.is_set() or admission_signature() != admitted:
|
||||||
|
raise CancelledBeforeDispatch()
|
||||||
|
if action.kind == "buy":
|
||||||
|
self.purchase_budget.record(self.snapshot.now, supply.purchase_cost, self.policy.daily_buy_money)
|
||||||
|
self.battle_journal.update(record, "request_pending")
|
||||||
|
if admission_signature() != admitted:
|
||||||
|
raise CancelledBeforeDispatch()
|
||||||
|
dispatched = True
|
||||||
|
response = self.battles._call(self.client, action.path, deepcopy(action.payload), cancel=self._progression_cancel)
|
||||||
|
receipt = gameplay_response(response)
|
||||||
|
if action.kind == "buy" and isinstance(response.get("eggs"), list):
|
||||||
|
receipt["eggs"] = [{k: egg[k] for k in ("typeId", "num") if k in egg}
|
||||||
|
for egg in response["eggs"] if isinstance(egg, dict)]
|
||||||
|
self.battle_journal.update(record, "acknowledged", response=receipt, response_confirmed=True,
|
||||||
|
message="补资源请求已返回,等待权威背包/孵化位核对;不重复发送")
|
||||||
|
if action.kind == "buy":
|
||||||
|
self.record_draw(response.get("eggs") or [])
|
||||||
|
return record["message"]
|
||||||
|
except CancelledBeforeDispatch:
|
||||||
|
self.battle_journal.finish(self.snapshot, record, "cancelled", "补资源请求尚未发送,已取消")
|
||||||
|
return record["message"]
|
||||||
|
except Exception as error:
|
||||||
|
if dispatched:
|
||||||
|
self.battle_journal.update(record, "unknown", message="补资源请求结果未知,禁止重购或重复装填", error_type=type(error).__name__)
|
||||||
|
else:
|
||||||
|
self.battle_journal.finish(self.snapshot, record, "cancelled", "补资源准备未完成,未发送")
|
||||||
|
raise
|
||||||
|
finally:
|
||||||
|
self._sync_commission_history()
|
||||||
|
|
||||||
|
def _reconcile_procurement(self):
|
||||||
|
if self.snapshot is None:
|
||||||
|
return
|
||||||
|
record = self.battle_journal.pending(self.snapshot)
|
||||||
|
if not record or record.get("kind") != "progression_procure" or record.get("response_confirmed") is not True:
|
||||||
|
return
|
||||||
|
payload, response = record.get("payload") or {}, record.get("response") or {}
|
||||||
|
if str(record.get("role_id")) != str(self.snapshot.raw["master"].get("id")) or response.get("resCode", 0) not in (0, "0"):
|
||||||
|
return
|
||||||
|
path, confirmed = record.get("path"), False
|
||||||
|
if path == "gachaService/gachaGetEggs":
|
||||||
|
eggs, expected = response.get("eggs"), {}
|
||||||
|
if isinstance(eggs, list):
|
||||||
|
for egg in eggs:
|
||||||
|
if isinstance(egg, dict) and str(egg.get("typeId")) in self.catalog.monsters and int(egg.get("num", 0)) > 0:
|
||||||
|
key = str(egg["typeId"])
|
||||||
|
expected[key] = expected.get(key, 0) + int(egg["num"])
|
||||||
|
totals = {}
|
||||||
|
for item in self.snapshot.raw["items"]:
|
||||||
|
key = str(item.get("typeId"))
|
||||||
|
totals[key] = totals.get(key, 0) + int(item.get("num", 0))
|
||||||
|
baseline = record.get("procurement_baseline") or {}
|
||||||
|
confirmed = bool(expected) and sum(expected.values()) >= int(payload.get("num", 0)) and all(
|
||||||
|
totals.get(k, 0) >= baseline.get(k, 0) + n for k, n in expected.items())
|
||||||
|
elif path == "stackService/stackAddMonster":
|
||||||
|
confirmed = bool(payload.get("eggs")) and all(any(int(s["id"]) == int(egg["stackId"])
|
||||||
|
and int(s.get("monsterId") or 0) in self.snapshot.monsters for s in self.snapshot.raw["stacks"])
|
||||||
|
for egg in payload["eggs"])
|
||||||
|
elif path == "stackService/stackTransferMonster":
|
||||||
|
confirmed = bool(payload.get("datas")) and all(
|
||||||
|
(self.snapshot.monsters.get(int(mid)) or {}).get("process") == 3
|
||||||
|
and int((self.snapshot.monsters.get(int(mid)) or {}).get("roomId") or 0) == int(data["roomId"])
|
||||||
|
for data in payload["datas"] for mid in data["monsterId"])
|
||||||
|
if confirmed:
|
||||||
|
self.battle_journal.finish(self.snapshot, record, "task", "已按服务器背包/孵化位确认补资源;任务步骤仍需独立核对提交")
|
||||||
|
self._sync_commission_history()
|
||||||
|
|
||||||
def _execute_task_intent(self, intent):
|
def _execute_task_intent(self, intent):
|
||||||
path, kind = value(intent, "path", "") or "", value(intent, "kind")
|
path, kind = value(intent, "path", "") or "", value(intent, "kind")
|
||||||
payload = deepcopy(value(intent, "payload", {}) or {})
|
payload = deepcopy(value(intent, "payload", {}) or {})
|
||||||
@@ -875,12 +1202,14 @@ class Engine:
|
|||||||
return "任务补链必须提供计算后的三个数组;未发送查询或空补链"
|
return "任务补链必须提供计算后的三个数组;未发送查询或空补链"
|
||||||
if self._progression_cancel.is_set():
|
if self._progression_cancel.is_set():
|
||||||
return "任务推进已取消"
|
return "任务推进已取消"
|
||||||
|
self._sync_commission_history()
|
||||||
record = self.battle_journal.begin(self.snapshot, intent)
|
record = self.battle_journal.begin(self.snapshot, intent)
|
||||||
|
self._journal_commission(record, intent)
|
||||||
if local:
|
if local:
|
||||||
self.progression_planner.acknowledge(self.snapshot, intent)
|
self.progression_planner.acknowledge(self.snapshot, intent)
|
||||||
self._persist_progression(save=False)
|
self._persist_progression(save=False)
|
||||||
self.battle_journal.finish(self.snapshot, record, "local", "已保存普通剧情的本地检查点")
|
self.battle_journal.finish(self.snapshot, record, "local", "已保存普通剧情的本地检查点")
|
||||||
return "已推进普通剧情并保存本地检查点"
|
return self._commission_message(record, "已推进普通剧情并保存本地检查点")
|
||||||
try:
|
try:
|
||||||
self.progression_planner.mark_started(self.snapshot, intent)
|
self.progression_planner.mark_started(self.snapshot, intent)
|
||||||
self._persist_progression(save=False)
|
self._persist_progression(save=False)
|
||||||
@@ -890,7 +1219,7 @@ class Engine:
|
|||||||
except CancelledBeforeDispatch:
|
except CancelledBeforeDispatch:
|
||||||
self._cancel_unsent_progression(intent)
|
self._cancel_unsent_progression(intent)
|
||||||
self.battle_journal.finish(self.snapshot, record, "cancelled", "任务请求尚未发送,已取消")
|
self.battle_journal.finish(self.snapshot, record, "cancelled", "任务请求尚未发送,已取消")
|
||||||
return record["message"]
|
return self._commission_message(record, record["message"])
|
||||||
self.battle_journal.update(record, "acknowledged", response=gameplay_response(response), response_confirmed=True)
|
self.battle_journal.update(record, "acknowledged", response=gameplay_response(response), response_confirmed=True)
|
||||||
acknowledged = self.progression_planner.acknowledge(self.snapshot, intent, gameplay_response(response))
|
acknowledged = self.progression_planner.acknowledge(self.snapshot, intent, gameplay_response(response))
|
||||||
self._persist_progression(save=False)
|
self._persist_progression(save=False)
|
||||||
@@ -898,17 +1227,104 @@ class Engine:
|
|||||||
self.battle_journal.finish(self.snapshot, record, "task", "服务器已确认任务请求,已保存本地检查点")
|
self.battle_journal.finish(self.snapshot, record, "task", "服务器已确认任务请求,已保存本地检查点")
|
||||||
else:
|
else:
|
||||||
self.battle_journal.update(record, "unknown", message="任务成功回包缺少有效状态,等待核对")
|
self.battle_journal.update(record, "unknown", message="任务成功回包缺少有效状态,等待核对")
|
||||||
return value(intent, "description", "任务请求已确认")
|
return self._commission_message(record, value(intent, "description", "任务请求已确认") if acknowledged else "任务成功回包缺少有效状态,等待核对,禁止重发")
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
self.battle_journal.update(record, "unknown", message="任务请求结果未确认,禁止自动重试", error_type=type(error).__name__)
|
self.battle_journal.update(record, "unknown", message="任务请求结果未确认,禁止自动重试", error_type=type(error).__name__)
|
||||||
raise
|
raise
|
||||||
|
finally:
|
||||||
|
self._sync_commission_history()
|
||||||
|
|
||||||
|
def _recover_sweep_entry(self):
|
||||||
|
"""Worker-only local migration, immediately after a successful read."""
|
||||||
|
pending = self.sweeper.state.get("pending")
|
||||||
|
if not isinstance(pending, dict):
|
||||||
|
return
|
||||||
|
message = self.battles.archive_cancelled_sweep(self.snapshot)
|
||||||
|
if message:
|
||||||
|
self._sweep_recovery_message = message
|
||||||
|
return
|
||||||
|
if self.battles.handoff_sweep(self.snapshot):
|
||||||
|
return
|
||||||
|
phases = ("遭遇隐藏关卡,请在游戏内手动战斗", "遇到事件或响应缺少事件状态,请在游戏内处理", "开始请求待确认")
|
||||||
|
if pending.get("phase") not in phases or pending.get("start_response"):
|
||||||
|
return
|
||||||
|
from .sweep_recovery import scan_trace, role_path_matches
|
||||||
|
owner = str(self.snapshot.raw["master"]["id"])
|
||||||
|
path = getattr(getattr(self.client, "trace", None), "path", None)
|
||||||
|
key = owner + ":" + digest(pending)
|
||||||
|
if key not in self._sweep_recovery_cache:
|
||||||
|
evidence = scan_trace(path, owner)
|
||||||
|
recovered = (evidence["valid"] and (pending.get("role_id") is not None
|
||||||
|
or role_path_matches(self.sweeper.path, getattr(self.client, "session", None), owner, path))
|
||||||
|
and self.sweeper.recover_hidden_start(self.snapshot, path, events=evidence["events"]))
|
||||||
|
# Keep only bounded evidence after the one scan. Presentation and
|
||||||
|
# subsequent snapshots never rescan the 16 MB rotated logs.
|
||||||
|
evidence.pop("events", None)
|
||||||
|
self._sweep_recovery_cache[key] = evidence
|
||||||
|
if recovered:
|
||||||
|
self.battles.handoff_sweep(self.snapshot)
|
||||||
|
return
|
||||||
|
else:
|
||||||
|
# An unsuccessful legacy proof is not retried on every refresh.
|
||||||
|
# A completed archive still repairs a crash before sweep.save.
|
||||||
|
if not any(row.get("sweep_sample_id") == pending.get("sampleId")
|
||||||
|
and (row.get("outcome") == "abandoned_missing_hidden_id" or row.get("phase") == "legacy_hidden_archived")
|
||||||
|
and row.get("sweep_entry") == pending
|
||||||
|
for row in self.battle_journal.role(self.snapshot)["records"]):
|
||||||
|
return
|
||||||
|
evidence = self._sweep_recovery_cache[key]
|
||||||
|
if (pending.get("phase") != phases[0] or set(pending) != {"stage", "level", "phase", "sampleId"}
|
||||||
|
or not all(isinstance(pending.get(field), str) and pending[field] for field in ("stage", "level", "sampleId"))
|
||||||
|
or not evidence["valid"] or not evidence["owner_read"] or not evidence["no_consumption"]
|
||||||
|
or self.snapshot.raw.get("masterCurrentEvent")
|
||||||
|
or not role_path_matches(self.sweeper.path, getattr(self.client, "session", None), owner, path)
|
||||||
|
or any(state.get("pending") and not any(row.get("attempt_id") == state["pending"]
|
||||||
|
and row.get("phase") == "legacy_hidden_archived" and row.get("sweep_entry") == pending
|
||||||
|
and row.get("sweep_sample_id") == pending["sampleId"]
|
||||||
|
and str(row.get("role_id")) == owner
|
||||||
|
for row in state.get("records", [])) for state in self.battle_journal.state["roles"].values())):
|
||||||
|
return
|
||||||
|
reservations = [str(key).split(":") for key, count in self.sweeper.state.get("counts", {}).items()
|
||||||
|
if type(count) is int and count > 0 and str(key).split(":")[-2:] == [pending["stage"], pending["level"]]]
|
||||||
|
if not reservations or any(len(parts) != 4 or parts[0] != owner for parts in reservations):
|
||||||
|
return
|
||||||
|
# Archive before releasing the guard. A crash between these two atomic
|
||||||
|
# saves is repaired by the sample ID on the next trusted read.
|
||||||
|
existing = next((row for row in self.battle_journal.role(self.snapshot)["records"]
|
||||||
|
if row.get("sweep_sample_id") == pending["sampleId"]
|
||||||
|
and row.get("outcome") == "abandoned_missing_hidden_id" and row.get("sweep_entry") == pending), None)
|
||||||
|
message = "旧版未保存隐藏关卡编号,本次未完成已放弃;未结算奖励"
|
||||||
|
if existing is None:
|
||||||
|
record = self.battle_journal.pending(self.snapshot) or self.battle_journal.begin(self.snapshot,
|
||||||
|
{"kind": "map_sweep", "stage_id": pending["stage"], "difficulty": pending["level"], "battle_kind": "sweep"},
|
||||||
|
sweep_entry=pending, sweep_phase="legacy_hidden_archived")
|
||||||
|
self.battle_journal.update(record, "legacy_hidden_archived", sweep_sample_id=pending["sampleId"],
|
||||||
|
sweep_entry=deepcopy(pending), archival_evidence={"role_id": owner, "snapshot_read_at": time.time(),
|
||||||
|
"role_path_bound": True, "trace_files": evidence["files"], "no_later_consumption": True})
|
||||||
|
self.battle_journal.finish(self.snapshot, record, "abandoned_missing_hidden_id", message)
|
||||||
|
self.sweeper.state["pending"] = None
|
||||||
|
self.sweeper.save()
|
||||||
|
self._sweep_recovery_message = message
|
||||||
|
|
||||||
@account_serial
|
@account_serial
|
||||||
def read_snapshot(self, *, sync_master=True):
|
def read_snapshot(self, *, sync_master=True):
|
||||||
if self._progression_pending():
|
if self._progression_pending():
|
||||||
self.last_pending_check = time.monotonic()
|
self.last_pending_check = time.monotonic()
|
||||||
self.snapshot = self.client.snapshot()
|
self.snapshot = self.client.snapshot()
|
||||||
self.battle_journal.reconcile(self.snapshot, trusted=True)
|
self._recover_sweep_entry()
|
||||||
|
self._reconcile_procurement()
|
||||||
|
pending = self.battle_journal.pending(self.snapshot)
|
||||||
|
pending_id = pending.get("attempt_id") if pending else None
|
||||||
|
if self.battle_journal.reconcile(self.snapshot, trusted=True) and pending_id:
|
||||||
|
record = next((row for row in self.battle_journal.role(self.snapshot)["records"]
|
||||||
|
if row["attempt_id"] == pending_id), None)
|
||||||
|
if record and (record.get("path") or "").endswith("taskLoopReceive"):
|
||||||
|
old = {str(task.get("id")) for task in record.get("baseline", {}).get("tasks", [])}
|
||||||
|
task = next((task for task in self.snapshot.raw.get("currentTasks", [])
|
||||||
|
if str(task.get("typeId")) == str(record.get("task_type_id")) and str(task.get("id")) not in old), None)
|
||||||
|
if task:
|
||||||
|
record["commission_task"] = {key: task[key] for key in ("id", "typeId", "curStep") if key in task}
|
||||||
|
self._sync_commission_history()
|
||||||
self.master_sync.apply(self.snapshot)
|
self.master_sync.apply(self.snapshot)
|
||||||
if sync_master and not self._progression_pending():
|
if sync_master and not self._progression_pending():
|
||||||
self.master_sync.settle(self.client, self.snapshot)
|
self.master_sync.settle(self.client, self.snapshot)
|
||||||
@@ -1031,7 +1447,10 @@ class Engine:
|
|||||||
|
|
||||||
@single_flight
|
@single_flight
|
||||||
@account_serial
|
@account_serial
|
||||||
def poll(self, *, hatch_only=False, defer_hatch=False):
|
def poll(self, *, hatch_only=False, defer_hatch=False, resume_pending=None):
|
||||||
|
if resume_pending is not None and type(resume_pending) is not bool:
|
||||||
|
raise ValueError("resume_pending must be a boolean or None")
|
||||||
|
recovery_generation = self._progression_cancel_generation
|
||||||
self.last_executed = False
|
self.last_executed = False
|
||||||
settled = False
|
settled = False
|
||||||
if self.demo:
|
if self.demo:
|
||||||
@@ -1045,6 +1464,9 @@ class Engine:
|
|||||||
if not hatch_only:
|
if not hatch_only:
|
||||||
settled = self.settle_pending_growth()
|
settled = self.settle_pending_growth()
|
||||||
message = "状态已刷新" + (";已请求孵化 / 成长结算" if settled else "")
|
message = "状态已刷新" + (";已请求孵化 / 成长结算" if settled else "")
|
||||||
|
if self._sweep_recovery_message:
|
||||||
|
message += ";" + self._sweep_recovery_message
|
||||||
|
self._sweep_recovery_message = ""
|
||||||
if self.sweeper.recovered_event:
|
if self.sweeper.recovered_event:
|
||||||
message += ";已解除旧版对已结算奖励事件的误阻塞"
|
message += ";已解除旧版对已结算奖励事件的误阻塞"
|
||||||
self.sweeper.recovered_event = False
|
self.sweeper.recovered_event = False
|
||||||
@@ -1055,7 +1477,7 @@ class Engine:
|
|||||||
if self._progression_pending():
|
if self._progression_pending():
|
||||||
self.pending_hatches = []
|
self.pending_hatches = []
|
||||||
pending_map = (self.battle_journal.pending(self.snapshot) or {}).get("kind") == "map_battle"
|
pending_map = (self.battle_journal.pending(self.snapshot) or {}).get("kind") == "map_battle"
|
||||||
recovered = self._resume_pending_task_clock() if not self.demo else ""
|
recovered = self._resume_pending_task_clock(running=resume_pending, generation=recovery_generation) if not self.demo else ""
|
||||||
if recovered:
|
if recovered:
|
||||||
self.last_executed = True
|
self.last_executed = True
|
||||||
if not self.battle_journal.pending(self.snapshot):
|
if not self.battle_journal.pending(self.snapshot):
|
||||||
@@ -1064,7 +1486,9 @@ class Engine:
|
|||||||
self.stage_cache.get(self.snapshot, refresh=True)
|
self.stage_cache.get(self.snapshot, refresh=True)
|
||||||
return self.snapshot, self.plans(), recovered
|
return self.snapshot, self.plans(), recovered
|
||||||
pending = self.battle_journal.pending(self.snapshot) or {}
|
pending = self.battle_journal.pending(self.snapshot) or {}
|
||||||
return self.snapshot, [], message + ";" + (pending.get("message") or "有待核对的任务 / 战斗,已暂停冲突操作") + ";后台每2分钟自动核对"
|
recovery = self.pending_battle_recovery()
|
||||||
|
detail = recovery["message"] or pending.get("message") or "有待核对的任务 / 战斗,已暂停冲突操作"
|
||||||
|
return self.snapshot, [], message + ";" + detail
|
||||||
explore_pending = self.explore_planner.pending(self.snapshot)
|
explore_pending = self.explore_planner.pending(self.snapshot)
|
||||||
if explore_pending or self._breakthrough_pending:
|
if explore_pending or self._breakthrough_pending:
|
||||||
self.pending_hatches = []
|
self.pending_hatches = []
|
||||||
@@ -1110,7 +1534,21 @@ class Engine:
|
|||||||
stage = self.sweeper.next(self.snapshot, self.sweep_policy)
|
stage = self.sweeper.next(self.snapshot, self.sweep_policy)
|
||||||
if self.demo:
|
if self.demo:
|
||||||
return self.snapshot, plans, "扫荡需要登录真实账号;演示不会提交战斗"
|
return self.snapshot, plans, "扫荡需要登录真实账号;演示不会提交战斗"
|
||||||
result = self.sweeper.run(self.client, self.snapshot, stage, self.sweep_policy)
|
origin = {"kind": "map_sweep", "stage_id": stage.stage_id, "difficulty": stage.level,
|
||||||
|
"battle_kind": "sweep", "battle_mode": "experimental"}
|
||||||
|
try:
|
||||||
|
result = self.sweeper.run(self.client, self.snapshot, stage, self.sweep_policy,
|
||||||
|
cancel=self._progression_cancel, origin=origin)
|
||||||
|
except CancelledBeforeDispatch:
|
||||||
|
return self.snapshot, [], "扫荡已停止,未确认的入场已保留"
|
||||||
|
if self.sweeper.last_outcome == "hidden":
|
||||||
|
self.battles.handoff_sweep(self.snapshot)
|
||||||
|
self._select_battle_runtime("experimental")
|
||||||
|
message = self.battles.continue_sweep(self.client, self.snapshot, self._intent_policy(origin),
|
||||||
|
cancel=self._progression_cancel)
|
||||||
|
if not self._progression_cancel.is_set():
|
||||||
|
self.read_snapshot(sync_master=False)
|
||||||
|
return self.snapshot, self.plans(), "扫荡遭遇隐藏关卡;" + (message or "隐藏入场已保存,等待来源策略开启后继续")
|
||||||
self.read_snapshot()
|
self.read_snapshot()
|
||||||
label = "探索奖励事件已结算" if self.sweeper.last_outcome == "event" else "扫荡完成"
|
label = "探索奖励事件已结算" if self.sweeper.last_outcome == "event" else "扫荡完成"
|
||||||
message = f"{label}:{stage.number} {stage.name} / 难度{stage.level};" + reward_text(self.sweeper.last_reward)
|
message = f"{label}:{stage.number} {stage.name} / 难度{stage.level};" + reward_text(self.sweeper.last_reward)
|
||||||
@@ -1223,15 +1661,20 @@ class Engine:
|
|||||||
if str(task.get("id")) == str(payload.get("taskId"))), {})
|
if str(task.get("id")) == str(payload.get("taskId"))), {})
|
||||||
intent = {"kind": action.kind, "description": action.description, "path": action.path, "payload": payload,
|
intent = {"kind": action.kind, "description": action.description, "path": action.path, "payload": payload,
|
||||||
"task_id": payload.get("taskId"), "task_type_id": payload.get("taskTypeId"), "step_number": task.get("curStep")}
|
"task_id": payload.get("taskId"), "task_type_id": payload.get("taskTypeId"), "step_number": task.get("curStep")}
|
||||||
|
self._sync_commission_history()
|
||||||
record = self.battle_journal.begin(self.snapshot, intent)
|
record = self.battle_journal.begin(self.snapshot, intent)
|
||||||
|
self._journal_commission(record, intent, legacy=True)
|
||||||
try:
|
try:
|
||||||
self.battle_journal.update(record, "request_pending")
|
self.battle_journal.update(record, "request_pending")
|
||||||
response = self.battles._call(self.client, action.path, payload)
|
response = self.battles._call(self.client, action.path, payload)
|
||||||
self.battle_journal.update(record, "acknowledged", response=gameplay_response(response))
|
self.battle_journal.update(record, "acknowledged", response=gameplay_response(response), response_confirmed=True)
|
||||||
|
action.description = self._commission_message(record, action.description)
|
||||||
return response
|
return response
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
self.battle_journal.update(record, "unknown", message="委托请求结果未确认,禁止自动重试", error_type=type(error).__name__)
|
self.battle_journal.update(record, "unknown", message="委托请求结果未确认,禁止自动重试", error_type=type(error).__name__)
|
||||||
raise
|
raise
|
||||||
|
finally:
|
||||||
|
self._sync_commission_history()
|
||||||
|
|
||||||
def _map_policy(self):
|
def _map_policy(self):
|
||||||
return SimpleNamespace(enabled=self.sweep_policy.enabled and (self.sweep_policy.allow_challenge or self.sweep_policy.allow_special),
|
return SimpleNamespace(enabled=self.sweep_policy.enabled and (self.sweep_policy.allow_challenge or self.sweep_policy.allow_special),
|
||||||
@@ -1346,10 +1789,23 @@ class Engine:
|
|||||||
# One owner for commission writes; never accept the same offer through
|
# One owner for commission writes; never accept the same offer through
|
||||||
# both the legacy planner and the full progression planner.
|
# both the legacy planner and the full progression planner.
|
||||||
quests = [] if self._commission_planner_available else self.tasks.plan(self.snapshot, self.quest_policy, self.policy)
|
quests = [] if self._commission_planner_available else self.tasks.plan(self.snapshot, self.quest_policy, self.policy)
|
||||||
types, eggs = self.tasks.reservations(self.snapshot)
|
preparing = []
|
||||||
|
for intent in self._progression_intents:
|
||||||
|
key = str(value(intent, "source_task_type_id") or value(intent, "task_type_id") or "")
|
||||||
|
if self._is_commission(intent) and key and not value(intent, "source_task_id") and not value(intent, "task_id"):
|
||||||
|
info = self._commission_info(key)
|
||||||
|
if any(r.get("task_type_id") == key and r.get("preparable") for r in self._commission_offer_diagnostics):
|
||||||
|
preparing.append({"typeId": key, "curStep": 1, "info": info})
|
||||||
|
types, eggs = self.tasks.reservations(self.snapshot, extra_tasks=preparing)
|
||||||
reserved = dict(self.policy.reserved_eggs)
|
reserved = dict(self.policy.reserved_eggs)
|
||||||
for key, count in eggs.items():
|
for key, count in eggs.items():
|
||||||
reserved[key] = max(reserved.get(key, 0), count)
|
reserved[key] = max(reserved.get(key, 0), count)
|
||||||
|
# The task supply planner owns these eggs, including when it is waiting
|
||||||
|
# for one already growing. Generic hatch/refill must not overproduce.
|
||||||
|
for type_id in types:
|
||||||
|
key = str(type_id)
|
||||||
|
reserved[key] = max(reserved.get(key, 0), sum(int(i.get("num", 0)) for i in self.snapshot.raw["items"]
|
||||||
|
if str(i.get("typeId")) == key))
|
||||||
policy = replace(self.policy, reserved_types=list(set(self.policy.reserved_types) | types), reserved_eggs=reserved)
|
policy = replace(self.policy, reserved_types=list(set(self.policy.reserved_types) | types), reserved_eggs=reserved)
|
||||||
self.hatch_planner.notes = []
|
self.hatch_planner.notes = []
|
||||||
self.pending_hatches = self.hatch_planner.hatch_actions(self.snapshot, policy)
|
self.pending_hatches = self.hatch_planner.hatch_actions(self.snapshot, policy)
|
||||||
@@ -1358,7 +1814,7 @@ class Engine:
|
|||||||
map_action = self._next_map_action()
|
map_action = self._next_map_action()
|
||||||
sweep_actions = [map_action] if map_action else []
|
sweep_actions = [map_action] if map_action else []
|
||||||
gifts = self.gift_planner.plan(self.snapshot, policy, self.quest_policy)
|
gifts = self.gift_planner.plan(self.snapshot, policy, self.quest_policy)
|
||||||
ranch = self.planner.plan(self.snapshot, policy, left)
|
ranch = self.planner.plan(self.snapshot, replace(policy, buy=False) if types or eggs else policy, left)
|
||||||
explore = self.explore_planner.plan(self.snapshot, self.explore_policy, policy)
|
explore = self.explore_planner.plan(self.snapshot, self.explore_policy, policy)
|
||||||
breakthrough_policy = SimpleNamespace(**(asdict(policy) | {"item_reserves": dict(self.quest_policy.item_reserves)}))
|
breakthrough_policy = SimpleNamespace(**(asdict(policy) | {"item_reserves": dict(self.quest_policy.item_reserves)}))
|
||||||
self.breakthrough_planner.notes = []
|
self.breakthrough_planner.notes = []
|
||||||
|
|||||||
@@ -0,0 +1,306 @@
|
|||||||
|
"""Offline resource accounting and bounded gold-only task procurement.
|
||||||
|
|
||||||
|
Task reservations belong to the scheduler. Only explicit user reserves enter
|
||||||
|
this accounting, so a task never reserves its own eggs away from itself.
|
||||||
|
"""
|
||||||
|
from collections import Counter
|
||||||
|
from dataclasses import dataclass, field, replace
|
||||||
|
|
||||||
|
from .model import Planner, seconds
|
||||||
|
|
||||||
|
|
||||||
|
def integer(value, default=0):
|
||||||
|
try:
|
||||||
|
return int(value)
|
||||||
|
except (TypeError, ValueError, OverflowError):
|
||||||
|
return default
|
||||||
|
|
||||||
|
|
||||||
|
def resource_kind(step):
|
||||||
|
kind, value = step.get("statusType"), step.get("statusValue") or {}
|
||||||
|
if kind == "getItem" or kind == "getMonster" and integer(value.get("mode"), -1) == 0:
|
||||||
|
return "items"
|
||||||
|
return "monsters" if kind == "getMonster" else ""
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class ResourcePlan:
|
||||||
|
feasible: bool = True
|
||||||
|
ready: bool = True
|
||||||
|
reason_kind: str = "ready"
|
||||||
|
reason: str = "资源已齐备"
|
||||||
|
resources: list = field(default_factory=list)
|
||||||
|
progress_plan: list = field(default_factory=list)
|
||||||
|
next_step: str = "提交已满足的任务条件"
|
||||||
|
action: object = None
|
||||||
|
farm_step: dict = field(default_factory=dict)
|
||||||
|
purchase_cost: int = 0
|
||||||
|
sources: list = field(default_factory=list)
|
||||||
|
|
||||||
|
def diagnostic(self):
|
||||||
|
return {key: getattr(self, key) for key in
|
||||||
|
("reason_kind", "resources", "progress_plan", "next_step")}
|
||||||
|
|
||||||
|
|
||||||
|
class ResourceProcurement:
|
||||||
|
def __init__(self, catalog, guard=None):
|
||||||
|
self.catalog = catalog
|
||||||
|
self.guard = guard or Planner(catalog)
|
||||||
|
|
||||||
|
def reserve(self, key, policy, ranch):
|
||||||
|
return max(0, integer(policy.item_reserves.get(key)), integer(ranch.reserved_eggs.get(key)),
|
||||||
|
integer(ranch.gift_items.get(key, {}).get("reserve")))
|
||||||
|
|
||||||
|
def inventory(self, snapshot, step, policy, ranch):
|
||||||
|
"""The same exact counts/IDs drive submission, preflight and the UI."""
|
||||||
|
kind, value = resource_kind(step), step.get("statusValue") or {}
|
||||||
|
key, needed = str(value.get("type", "")), integer(value.get("num"), -1)
|
||||||
|
remove = value.get("remove") is True
|
||||||
|
row = {"kind": kind, "type_id": key, "name": self.catalog.item_name(key), "needed": needed,
|
||||||
|
"available": 0, "total": 0, "reserved": 0, "protected": 0, "protections": {}, "ids": []}
|
||||||
|
if not key.isdigit() or needed < 0:
|
||||||
|
return row | {"ready": False, "reason": "资源条件缺少有效类型或数量"}
|
||||||
|
if kind == "items":
|
||||||
|
items = [i for i in snapshot.raw.get("items", []) if str(i.get("typeId")) == key
|
||||||
|
and integer(i.get("id")) > 0 and integer(i.get("num")) > 0]
|
||||||
|
free = [i for i in items if not any(i.get(f) for f in ("lock", "sysLock", "feedLock"))]
|
||||||
|
row["total"] = sum(integer(i.get("num")) for i in items)
|
||||||
|
unlocked = sum(integer(i.get("num")) for i in free)
|
||||||
|
row["reserved"] = self.reserve(key, policy, ranch) if remove else 0
|
||||||
|
row["protected"] = row["total"] - unlocked
|
||||||
|
row["available"] = max(0, unlocked - row["reserved"])
|
||||||
|
used = 0
|
||||||
|
for item in free:
|
||||||
|
if used >= needed:
|
||||||
|
break
|
||||||
|
row["ids"].append(integer(item["id"]))
|
||||||
|
used += integer(item["num"])
|
||||||
|
allowed = not remove or not needed or policy.allow_items
|
||||||
|
row["reason"] = (f"{row['name']}:需{needed},可用{row['available']},背包{row['total']},"
|
||||||
|
f"锁定{row['protected']},保留{row['reserved']}")
|
||||||
|
if not allowed:
|
||||||
|
row["reason"] += ";提交道具未启用"
|
||||||
|
elif kind == "monsters":
|
||||||
|
if integer(value.get("mode"), -2) not in (2, -1):
|
||||||
|
return row | {"ready": False, "reason": "未支持的魔物条件或形态"}
|
||||||
|
monsters = [m for m in snapshot.raw.get("monsters", []) if str(m.get("typeId")) == key]
|
||||||
|
protections, free = Counter(), []
|
||||||
|
for monster in monsters:
|
||||||
|
reason = self.monster_protection(monster, snapshot, ranch)
|
||||||
|
mature = (integer(monster.get("mode"), -1) == 2 and integer(monster.get("process")) >= 2
|
||||||
|
and integer(monster.get("level"), 1) == 1)
|
||||||
|
if reason:
|
||||||
|
protections[reason] += 1
|
||||||
|
elif mature:
|
||||||
|
free.append(monster)
|
||||||
|
elif integer(monster.get("level"), 1) != 1:
|
||||||
|
protections["等级不是1级"] += 1
|
||||||
|
free.sort(key=lambda m: (sum(self.catalog.quality(m)), integer(m["id"])))
|
||||||
|
row.update(total=len(monsters), available=len(free), protected=sum(protections.values()),
|
||||||
|
protections=dict(protections), ids=[integer(m["id"]) for m in free[:needed]])
|
||||||
|
allowed = not remove or not needed or policy.allow_monsters
|
||||||
|
row["reason"] = f"{row['name']}:需{needed}只1级成熟魔物,可提交{len(free)},同种共{len(monsters)},保护{row['protected']}"
|
||||||
|
if protections:
|
||||||
|
row["reason"] += "(" + "、".join(f"{r} {n}只" for r, n in protections.items()) + ")"
|
||||||
|
if not allowed:
|
||||||
|
row["reason"] += ";提交魔物未启用"
|
||||||
|
else:
|
||||||
|
return row | {"ready": False, "reason": "未支持的资源条件"}
|
||||||
|
row["ready"] = allowed and row["available"] >= needed
|
||||||
|
return row
|
||||||
|
|
||||||
|
def monster_protection(self, monster, snapshot, ranch):
|
||||||
|
# Cultivation targets stay protected even when a species rule is enabled.
|
||||||
|
mid = str(monster.get("id"))
|
||||||
|
if monster.get("inteam") or integer(monster.get("id")) in snapshot.team_ids:
|
||||||
|
return "在队魔物"
|
||||||
|
if integer(monster.get("id")) == ranch.feed_target or any(mid in targets for targets in
|
||||||
|
(ranch.feed_targets, ranch.gift_targets, ranch.breakthrough_targets)):
|
||||||
|
return "主培养或已选培养目标"
|
||||||
|
return self.guard.protection_reason(monster, snapshot, ranch) or ""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def demands(steps):
|
||||||
|
"""Sum removals and retain observation peaks; shared eggs are counted once."""
|
||||||
|
spent, needed, templates = Counter(), Counter(), {}
|
||||||
|
for step in steps:
|
||||||
|
kind, value = resource_kind(step), step.get("statusValue") or {}
|
||||||
|
if not kind:
|
||||||
|
continue
|
||||||
|
key = (kind, str(value.get("type", "")))
|
||||||
|
count = max(0, integer(value.get("num")))
|
||||||
|
needed[key] = max(needed[key], spent[key] + count)
|
||||||
|
templates[key] = step
|
||||||
|
if value.get("remove") is True:
|
||||||
|
spent[key] += count
|
||||||
|
return needed, templates
|
||||||
|
|
||||||
|
def plan(self, snapshot, steps, policy, ranch, *, daily_left=None, farm_sources=None):
|
||||||
|
for step in steps:
|
||||||
|
if resource_kind(step):
|
||||||
|
value = step.get("statusValue") or {}
|
||||||
|
if (not str(value.get("type", "")).isdigit() or integer(value.get("num"), -1) < 0
|
||||||
|
or resource_kind(step) == "monsters" and integer(value.get("mode"), -2) not in (2, -1)):
|
||||||
|
return ResourcePlan(feasible=False, ready=False, reason_kind="model_unsupported",
|
||||||
|
reason="资源条件的类型、数量或魔物形态未验证", next_step="等待有效任务配置")
|
||||||
|
needed, templates = self.demands(steps)
|
||||||
|
plan = ResourcePlan()
|
||||||
|
item_demands = {key: count for (kind, key), count in needed.items() if kind == "items"}
|
||||||
|
evaluations = []
|
||||||
|
for (kind, key), count in needed.items():
|
||||||
|
template = templates[kind, key]
|
||||||
|
# Any consuming step must retain permission/reserve checks, even if
|
||||||
|
# a later observation uses the same resource without remove=True.
|
||||||
|
remove = any(resource_kind(s) == kind and str((s.get("statusValue") or {}).get("type")) == key
|
||||||
|
and (s.get("statusValue") or {}).get("remove") is True for s in steps)
|
||||||
|
trial = dict(template, statusValue=dict(template.get("statusValue") or {}, num=count, remove=remove))
|
||||||
|
row = self.inventory(snapshot, trial, policy, ranch)
|
||||||
|
plan.resources.append({k: v for k, v in row.items() if k not in ("ids", "ready", "reason")})
|
||||||
|
if not row["ready"]:
|
||||||
|
result = self._missing(snapshot, trial, row, policy, ranch, item_demands, daily_left)
|
||||||
|
if result.feasible and result.farm_step and callable(farm_sources):
|
||||||
|
result.sources, reason = farm_sources(result.farm_step)
|
||||||
|
if not result.sources:
|
||||||
|
result.feasible = False
|
||||||
|
result.reason_kind = "model_unsupported" if reason else "temp_resource"
|
||||||
|
result.reason += ";" + (reason or "没有满足解锁、资源保护与批次规则的已验证收集来源")
|
||||||
|
result.next_step = result.reason
|
||||||
|
evaluations.append(result)
|
||||||
|
if not evaluations:
|
||||||
|
return plan
|
||||||
|
plan.ready = False
|
||||||
|
plan.feasible = all(result.feasible for result in evaluations)
|
||||||
|
selected = next((r for r in evaluations if not r.feasible), None)
|
||||||
|
selected = selected or next((r for r in evaluations if r.action or r.farm_step), evaluations[0])
|
||||||
|
plan.reason_kind, plan.next_step = selected.reason_kind, selected.next_step
|
||||||
|
plan.reason = ";".join(r.reason for r in evaluations)
|
||||||
|
plan.progress_plan = [text for result in evaluations for text in result.progress_plan]
|
||||||
|
if plan.feasible:
|
||||||
|
plan.action, plan.farm_step = selected.action, selected.farm_step
|
||||||
|
plan.sources = selected.sources
|
||||||
|
plan.purchase_cost = selected.purchase_cost
|
||||||
|
total_cost = sum(r.purchase_cost for r in evaluations)
|
||||||
|
budget = ranch.daily_buy_money if daily_left is None else min(daily_left, ranch.daily_buy_money)
|
||||||
|
if total_cost > min(budget, max(0, integer(snapshot.raw["master"].get("money")) - ranch.keep_money)):
|
||||||
|
plan.feasible = False
|
||||||
|
plan.reason += f";整份任务当前采购至少{total_cost}金币,超过保留金币或今日剩余额度{budget}"
|
||||||
|
plan.next_step = "等待金币或次日预算恢复,再核对整份任务采购成本"
|
||||||
|
plan.action, plan.sources = None, []
|
||||||
|
return plan
|
||||||
|
|
||||||
|
def _missing(self, snapshot, step, row, policy, ranch, item_demands, daily_left):
|
||||||
|
key, deficit = row["type_id"], row["needed"] - row["available"]
|
||||||
|
plan = ResourcePlan(ready=False, reason_kind="temp_resource", reason=row["reason"])
|
||||||
|
fail = lambda text, kind="protection": replace(plan, feasible=False, reason_kind=kind,
|
||||||
|
reason=plan.reason + ";" + text, next_step=text)
|
||||||
|
if (step.get("statusValue") or {}).get("remove") is True and not getattr(policy, "allow_" + row["kind"]):
|
||||||
|
return fail("按现有提交权限等待处理", "policy")
|
||||||
|
if row["kind"] == "monsters":
|
||||||
|
species = self.catalog.monster(key)
|
||||||
|
rule = self.guard.species_rule({"typeId": key}, ranch)
|
||||||
|
if (integer(key) in ranch.reserved_types or not species or
|
||||||
|
not rule and (integer(species.get("star"), 99) >= ranch.protect_star or ranch.protect_quality <= 1)):
|
||||||
|
return fail("该种新孵魔物也受保留种类、星级或资质保护,无法自动取得可提交副本")
|
||||||
|
if not policy.auto_farm or not ranch.enabled or not ranch.fill:
|
||||||
|
return fail("自动补齐需要已启用牧场与装填孵化", "policy")
|
||||||
|
growing = [m for m in snapshot.raw.get("monsters", []) if str(m.get("typeId")) == key
|
||||||
|
and integer(m.get("process")) == 2 and integer(m.get("level"), 1) == 1
|
||||||
|
and (integer(m.get("mode"), -1) in (0, 1) or integer(m.get("mode"), -1) == 2
|
||||||
|
and any(q is None for q in self.catalog.quality(m)))
|
||||||
|
and not (m.get("inteam") or integer(m.get("id")) in snapshot.team_ids
|
||||||
|
or integer(m.get("id")) == ranch.feed_target
|
||||||
|
or any(str(m.get("id")) in targets for targets in (ranch.feed_targets, ranch.gift_targets, ranch.breakthrough_targets))
|
||||||
|
or any(m.get(f) for f in ("lock", "sysLock", "entangle", "inExploreTeam", "inBuild")))]
|
||||||
|
eggs = self.inventory(snapshot, {"statusType": "getItem", "statusValue":
|
||||||
|
{"type": key, "num": 0, "remove": True}}, replace(policy, allow_items=True), ranch)
|
||||||
|
egg_available = max(0, eggs["available"] - item_demands.get(key, 0))
|
||||||
|
plan.reason += f";孵化中{len(growing)},可孵蛋{egg_available}(另留提交蛋{item_demands.get(key, 0)}、用户保留{eggs['reserved']})"
|
||||||
|
outstanding = max(0, deficit - len(growing))
|
||||||
|
if outstanding and egg_available:
|
||||||
|
# Reuse the normal hatch API, but select only this task's type.
|
||||||
|
hatch_policy = replace(ranch, manual_eggs=False, reserved_eggs={key: eggs["reserved"] + item_demands.get(key, 0)},
|
||||||
|
hatch_max_star=99, min_gold_per_hour=0, min_exp_per_hour=0)
|
||||||
|
from .model import Snapshot
|
||||||
|
remaining = outstanding + eggs["reserved"] + item_demands.get(key, 0)
|
||||||
|
hatch_items = []
|
||||||
|
for item in snapshot.raw["items"]:
|
||||||
|
if (str(item.get("typeId")) != key or any(item.get(f) for f in ("lock", "sysLock", "feedLock"))
|
||||||
|
or integer(item.get("id")) <= 0 or remaining <= 0):
|
||||||
|
continue
|
||||||
|
count = min(remaining, max(0, integer(item.get("num"))))
|
||||||
|
hatch_items.append(dict(item, num=count))
|
||||||
|
remaining -= count
|
||||||
|
scoped = Snapshot(dict(snapshot.raw, items=hatch_items),
|
||||||
|
received_at=snapshot.received_at, server_offset=snapshot.server_offset)
|
||||||
|
actions = self.guard.hatch_actions(scoped, hatch_policy)
|
||||||
|
if actions:
|
||||||
|
plan.action = actions[0]
|
||||||
|
plan.next_step = f"先装填已有{row['name']}蛋,等待服务器确认成熟后再提交"
|
||||||
|
plan.progress_plan = [plan.next_step]
|
||||||
|
return plan
|
||||||
|
# Mature protected incubator occupants can be collected safely.
|
||||||
|
slots = {integer(s.get("monsterId")) for s in snapshot.raw.get("stacks", [])}
|
||||||
|
for mon in snapshot.raw.get("monsters", []):
|
||||||
|
if (integer(mon.get("id")) in slots and integer(mon.get("mode"), -1) == 2
|
||||||
|
and integer(mon.get("process")) == 2
|
||||||
|
and all(q is not None for q in self.catalog.quality(mon))):
|
||||||
|
room = snapshot.room_available(self.catalog, ranch.room_id)
|
||||||
|
if room is not None and ranch.collect:
|
||||||
|
from .model import Action
|
||||||
|
plan.action = Action("collect", "收取成熟魔物以空出委托孵化位", "stackService/stackTransferMonster",
|
||||||
|
{"datas": [{"monsterId": [integer(mon['id'])], "roomId": room}]})
|
||||||
|
plan.next_step = "先收取成熟魔物到空闲牧场,再装填委托蛋"
|
||||||
|
plan.progress_plan = [plan.next_step]
|
||||||
|
return plan
|
||||||
|
plan.reason_kind = "busy"
|
||||||
|
plan.next_step = "孵化位已占用;等待成长或可收取牧场空位,不再购蛋"
|
||||||
|
plan.progress_plan = [plan.next_step]
|
||||||
|
return plan
|
||||||
|
if outstanding <= 0:
|
||||||
|
waits = [snapshot.remaining(m, self.catalog) for m in growing]
|
||||||
|
wait = max((w for w in waits if w is not None), default=None)
|
||||||
|
plan.reason_kind = "cooldown"
|
||||||
|
plan.next_step = "已有足量同种魔物孵化/成长中,等待" + (f"约{int(wait) + 1}秒并同步成熟" if wait is not None else "服务器同步成熟") + ";不重复购蛋"
|
||||||
|
plan.progress_plan = [plan.next_step, "成熟后重新核对资质及保护,只提交未保护副本"]
|
||||||
|
return plan
|
||||||
|
deficit = max(0, outstanding - egg_available)
|
||||||
|
plan.progress_plan.append("保留受保护副本,补孵缺少的1级成熟魔物,成熟后重新核对保护")
|
||||||
|
elif not policy.auto_farm:
|
||||||
|
return fail("自动补资源未启用", "policy")
|
||||||
|
if key not in self.catalog.monsters:
|
||||||
|
plan.farm_step = step
|
||||||
|
plan.next_step = "从已解锁且通过实战能力核对的普通关卡收集缺少材料"
|
||||||
|
plan.progress_plan.append(plan.next_step)
|
||||||
|
return plan
|
||||||
|
# Prefer verified farming when buying is unavailable. The caller checks
|
||||||
|
# map unlocks, team, costs, model support and actual drops separately.
|
||||||
|
trial = {"statusType": "getItem", "statusValue": {"type": key,
|
||||||
|
"num": (row["needed"] if row["kind"] == "items" else deficit + eggs["available"] + eggs["reserved"]),
|
||||||
|
"remove": row["kind"] == "items"}}
|
||||||
|
plan.farm_step = trial
|
||||||
|
if not ranch.enabled or not ranch.buy:
|
||||||
|
plan.next_step = "购蛋开关未启用;检查已验证地图掉蛋来源"
|
||||||
|
return plan
|
||||||
|
markets = self.catalog.data.get("markets", {})
|
||||||
|
candidates = [mid for mid in self.catalog.markets_for(key) if mid.startswith("sc_city")
|
||||||
|
and integer(markets[mid].get("ke"), -1) == 0 and integer(markets[mid].get("money")) > 0
|
||||||
|
and snapshot.city_unlocked(markets[mid].get("city"))]
|
||||||
|
candidates.sort(key=lambda mid: (mid != ranch.egg_rules.get(key, {}).get("market_id"),
|
||||||
|
mid != ranch.market_id, integer(markets[mid]["money"]), mid))
|
||||||
|
failures = []
|
||||||
|
for mid in candidates:
|
||||||
|
buying = replace(ranch, manual_eggs=False, market_id=mid, egg_stock=deficit)
|
||||||
|
self.guard.notes = []
|
||||||
|
actions = self.guard.purchase(snapshot, buying, daily_left, stock=0)
|
||||||
|
if actions:
|
||||||
|
plan.action = actions[0]
|
||||||
|
plan.action.description = f"为任务补齐{row['name']}(缺{deficit}):" + plan.action.description
|
||||||
|
plan.purchase_cost = integer(markets[mid]["money"]) * integer(plan.action.payload["num"])
|
||||||
|
plan.farm_step = {}
|
||||||
|
plan.next_step = f"在{markets[mid]['name']}金币市场补抽,单次最多{deficit}枚;蛋池随机,每次按实际回包重算缺口"
|
||||||
|
plan.progress_plan.append(plan.next_step)
|
||||||
|
return plan
|
||||||
|
failures.extend(self.guard.notes)
|
||||||
|
plan.next_step = ";".join(dict.fromkeys(failures)) or "没有已解锁且包含目标蛋的金币市场,检查地图掉蛋来源"
|
||||||
|
plan.reason += ";" + plan.next_step
|
||||||
|
return plan
|
||||||
+172
-75
@@ -45,7 +45,8 @@ import uuid
|
|||||||
|
|
||||||
from .game_data import ProgressionData, load_progression_data
|
from .game_data import ProgressionData, load_progression_data
|
||||||
from .model import Planner, seconds
|
from .model import Planner, seconds
|
||||||
from .quests import commission_priority, indexed, stage_has_level
|
from .quests import commission_priority, commission_selection, commission_reason_kind, indexed, stage_has_level
|
||||||
|
from .procurement import ResourceProcurement, resource_kind
|
||||||
|
|
||||||
|
|
||||||
CATEGORIES = {1: ("mainline", "主线"), 2: ("sidequest", "支线"),
|
CATEGORIES = {1: ("mainline", "主线"), 2: ("sidequest", "支线"),
|
||||||
@@ -180,10 +181,14 @@ class ProgressionPlanner:
|
|||||||
self.catalog = catalog
|
self.catalog = catalog
|
||||||
self.data = data if isinstance(data, ProgressionData) else ProgressionData(data) if data is not None else load_progression_data()
|
self.data = data if isinstance(data, ProgressionData) else ProgressionData(data) if data is not None else load_progression_data()
|
||||||
self.guard = Planner(catalog)
|
self.guard = Planner(catalog)
|
||||||
|
self.procurement = ResourceProcurement(catalog, self.guard)
|
||||||
|
self.procurement_daily_left = None
|
||||||
self._namespace = str(account_key) if account_key is not None else ""
|
self._namespace = str(account_key) if account_key is not None else ""
|
||||||
self._anonymous = uuid.uuid4().hex
|
self._anonymous = uuid.uuid4().hex
|
||||||
self._accounts = {}
|
self._accounts = {}
|
||||||
self._issued = {}
|
self._issued = {}
|
||||||
|
self.commission_selection = {}
|
||||||
|
self.commission_offer_rows = []
|
||||||
|
|
||||||
def _scope(self, snapshot):
|
def _scope(self, snapshot):
|
||||||
raw, master = snapshot.raw, snapshot.raw.get("master") or {}
|
raw, master = snapshot.raw, snapshot.raw.get("master") or {}
|
||||||
@@ -326,6 +331,18 @@ class ProgressionPlanner:
|
|||||||
"bar": "酒馆", "shop": "商店", "wild": "野外", "mine": "矿洞", "pve": "挑战"}
|
"bar": "酒馆", "shop": "商店", "wild": "野外", "mine": "矿洞", "pve": "挑战"}
|
||||||
return city_name + (" · " + labels.get(tail, tail) if tail else "")
|
return city_name + (" · " + labels.get(tail, tail) if tail else "")
|
||||||
|
|
||||||
|
def city_diagnostic(self, city, snapshot):
|
||||||
|
info = (self.data.game_setting.get("cityInfo") or {}).get(str(city), {})
|
||||||
|
name = info.get("name") or f"城市 {city}"
|
||||||
|
key = str(info.get("openTask") or "")
|
||||||
|
task = self.data.task(key) or {}
|
||||||
|
_, account = self._account(snapshot)
|
||||||
|
unlocked = snapshot.city_unlocked(city) or str(city) in account["city_unlocks"]
|
||||||
|
condition = f"完成{CATEGORIES.get(task.get('type'), ('', '任务'))[1]}《{task.get('name') or key}》({key})" if key else "等待服务器确认城市解锁"
|
||||||
|
reason = "" if unlocked else f"{name}(城市{city})城市尚未解锁;解锁条件:{condition}" if info else "城市尚未解锁"
|
||||||
|
return {"city_name": name, "unlock_task_id": key, "unlock_condition": condition,
|
||||||
|
"city_unlocked": unlocked, "city_reason": reason}
|
||||||
|
|
||||||
def _location_gate(self, position, snapshot, account):
|
def _location_gate(self, position, snapshot, account):
|
||||||
if not position or position in ("farm", "stackGround"):
|
if not position or position in ("farm", "stackGround"):
|
||||||
return ""
|
return ""
|
||||||
@@ -339,7 +356,7 @@ class ProgressionPlanner:
|
|||||||
if city_info.get("hide") is True:
|
if city_info.get("hide") is True:
|
||||||
return "城市已隐藏"
|
return "城市已隐藏"
|
||||||
if not (snapshot.city_unlocked(int(city)) or city in account["city_unlocks"]):
|
if not (snapshot.city_unlocked(int(city)) or city in account["city_unlocks"]):
|
||||||
return "目标城市尚未解锁"
|
return self.city_diagnostic(int(city), snapshot)["city_reason"]
|
||||||
if tail is None or tail in {"market", "xiehui", "alchemy", "bar", "shop", "wild", "mine", "pve"}:
|
if tail is None or tail in {"market", "xiehui", "alchemy", "bar", "shop", "wild", "mine", "pve"}:
|
||||||
if tail == "mine" and (snapshot.raw.get("history") or {}).get("openMine") is not True:
|
if tail == "mine" and (snapshot.raw.get("history") or {}).get("openMine") is not True:
|
||||||
return "矿洞功能尚未开放"
|
return "矿洞功能尚未开放"
|
||||||
@@ -457,47 +474,9 @@ class ProgressionPlanner:
|
|||||||
if money - amount < ranch_policy.keep_money:
|
if money - amount < ranch_policy.keep_money:
|
||||||
return False, None, "提交后低于牧场金币保留量"
|
return False, None, "提交后低于牧场金币保留量"
|
||||||
return money >= amount, None, f"金币 {money}/{amount}"
|
return money >= amount, None, f"金币 {money}/{amount}"
|
||||||
if kind == "getItem" or kind == "getMonster" and _integer(value.get("mode"), -2) == 0:
|
if resource_kind(step):
|
||||||
key, count = str(value.get("type", "")), _integer(value.get("num"), -1)
|
row = self.procurement.inventory(snapshot, step, policy, ranch_policy)
|
||||||
if not key.isdigit() or count < 0:
|
return row["ready"], row["ids"] if row["ready"] else None, row["reason"]
|
||||||
return False, None, "道具条件缺少有效类型或数量"
|
|
||||||
remove = value.get("remove") is True
|
|
||||||
reserve = max(policy.item_reserves.get(key, 0), _integer(ranch_policy.reserved_eggs.get(key)))
|
|
||||||
gift = ranch_policy.gift_items.get(key, {})
|
|
||||||
reserve = max(reserve, _integer(gift.get("reserve")))
|
|
||||||
items = [item for item in snapshot.raw.get("items", []) if str(item.get("typeId")) == key
|
|
||||||
and not item.get("lock") and not item.get("sysLock") and not item.get("feedLock")
|
|
||||||
and _integer(item.get("id")) > 0 and _integer(item.get("num")) > 0]
|
|
||||||
total = sum(_integer(item.get("num")) for item in items)
|
|
||||||
if total - (reserve if remove else 0) < count:
|
|
||||||
return False, None, f"道具 {self.catalog.item_name(key)} {total}/{count},需保留 {reserve}"
|
|
||||||
if remove and count and not policy.allow_items:
|
|
||||||
return False, None, "提交道具未启用"
|
|
||||||
ids, used = [], 0
|
|
||||||
for item in items:
|
|
||||||
if used >= count:
|
|
||||||
break
|
|
||||||
ids.append(_integer(item["id"]))
|
|
||||||
used += _integer(item["num"])
|
|
||||||
# AS3 supplies IDs for observation-only getItem as well.
|
|
||||||
return True, ids, f"道具 {self.catalog.item_name(key)} ×{count}"
|
|
||||||
if kind == "getMonster":
|
|
||||||
key, count, mode = str(value.get("type", "")), _integer(value.get("num"), -1), _integer(value.get("mode"), -2)
|
|
||||||
if not key.isdigit() or count < 0 or mode not in (2, -1):
|
|
||||||
return False, None, "未支持的魔物条件或形态"
|
|
||||||
remove = value.get("remove") is True
|
|
||||||
if remove and count and not policy.allow_monsters:
|
|
||||||
return False, None, "提交魔物未启用"
|
|
||||||
candidates = []
|
|
||||||
for monster in snapshot.raw.get("monsters", []):
|
|
||||||
if (str(monster.get("typeId")) != key or _integer(monster.get("level"), 1) != 1
|
|
||||||
or _integer(monster.get("mode"), -2) != 2 or _integer(monster.get("process"), 2) < 2
|
|
||||||
or monster.get("inteam") or self.guard.protected(monster, snapshot, ranch_policy)):
|
|
||||||
continue
|
|
||||||
candidates.append(monster)
|
|
||||||
candidates.sort(key=lambda monster: (sum(self.catalog.quality(monster)), _integer(monster["id"])))
|
|
||||||
return (len(candidates) >= count, [_integer(monster["id"]) for monster in candidates[:count]],
|
|
||||||
f"未保护的1级成熟魔物 {self.catalog.item_name(key)} {len(candidates)}/{count}")
|
|
||||||
if kind == "killMonster":
|
if kind == "killMonster":
|
||||||
target = task.get("stepValue")
|
target = task.get("stepValue")
|
||||||
kills = indexed(history.get("numKillMonsters"), value.get("type"))
|
kills = indexed(history.get("numKillMonsters"), value.get("type"))
|
||||||
@@ -598,6 +577,13 @@ class ProgressionPlanner:
|
|||||||
reason = self._script_gate(step.get("afterStory"))
|
reason = self._script_gate(step.get("afterStory"))
|
||||||
if reason or step.get("afterStory") and not policy.auto_dialogue:
|
if reason or step.get("afterStory") and not policy.auto_dialogue:
|
||||||
return block(reason or "自动后续对话未启用")
|
return block(reason or "自动后续对话未启用")
|
||||||
|
if resource_kind(step):
|
||||||
|
supply = self.remaining_resource_plan(snapshot, info, task, policy, ranch)
|
||||||
|
if supply.feasible:
|
||||||
|
action = self._resource_intent(snapshot, supply, effective_task, number, step, policy)
|
||||||
|
if action is not None:
|
||||||
|
return action
|
||||||
|
return block(supply.reason + ";" + supply.next_step)
|
||||||
farming = self.farming_intents(snapshot, step, effective_task, policy, ranch)
|
farming = self.farming_intents(snapshot, step, effective_task, policy, ranch)
|
||||||
if farming:
|
if farming:
|
||||||
return farming[0]
|
return farming[0]
|
||||||
@@ -836,6 +822,54 @@ class ProgressionPlanner:
|
|||||||
return self._intent(scope, task, number, steps[number - 1], "progression_blocked", reason, policy, block_reason=reason)
|
return self._intent(scope, task, number, steps[number - 1], "progression_blocked", reason, policy, block_reason=reason)
|
||||||
return self._next(snapshot, policy, ranch, scope, account, task, info)
|
return self._next(snapshot, policy, ranch, scope, account, task, info)
|
||||||
|
|
||||||
|
def remaining_resource_plan(self, snapshot, info, task, policy, ranch):
|
||||||
|
"""One remaining-step/coin-reserve calculation for planning and dispatch."""
|
||||||
|
effective_task = dict(task)
|
||||||
|
number = 1
|
||||||
|
if _integer(task.get("id")) > 0:
|
||||||
|
_, account = self._account(snapshot)
|
||||||
|
record = self._record(task, account)
|
||||||
|
number = record["cursor"]
|
||||||
|
if number != _integer(task.get("curStep")):
|
||||||
|
effective_task["stepValue"] = record["next_value"]
|
||||||
|
effective_task["curStep"] = number
|
||||||
|
steps = (info.get("steps") or [])[max(0, number - 1):]
|
||||||
|
money = sum(_integer((step.get("statusValue") or {}).get("money")) for step in steps
|
||||||
|
if step.get("statusType") == "getMoney" and (step.get("statusValue") or {}).get("remove") is True)
|
||||||
|
return self.resource_plan(snapshot, steps, effective_task, policy,
|
||||||
|
replace(ranch, keep_money=ranch.keep_money + money))
|
||||||
|
|
||||||
|
def resource_plan(self, snapshot, steps, task, policy, ranch):
|
||||||
|
def sources(trial):
|
||||||
|
actions = self.farming_intents(snapshot, trial, task, policy, ranch)
|
||||||
|
check = getattr(self, "battle_capability", None)
|
||||||
|
supported, reasons = [], []
|
||||||
|
for action in actions:
|
||||||
|
ok, reason = (True, "") if action.kind == "sweep" or not callable(check) else check(action)
|
||||||
|
if ok:
|
||||||
|
supported.append(action)
|
||||||
|
elif reason:
|
||||||
|
reasons.append(reason)
|
||||||
|
return supported, ";".join(dict.fromkeys(reasons))
|
||||||
|
return self.procurement.plan(snapshot, steps, policy, ranch,
|
||||||
|
daily_left=self.procurement_daily_left, farm_sources=sources)
|
||||||
|
|
||||||
|
def _resource_intent(self, snapshot, supply, task, number, step, policy):
|
||||||
|
if supply.sources:
|
||||||
|
return supply.sources[0]
|
||||||
|
scope, _ = self._account(snapshot)
|
||||||
|
if supply.action:
|
||||||
|
action = supply.action
|
||||||
|
note = ";先补资源,未提交任务步骤" if _integer(task.get("id")) else ";先补资源,尚未接取委托,未消耗接取次数"
|
||||||
|
return self._intent(scope, {}, 0, {}, "progression_procure", action.description + note, policy,
|
||||||
|
path=action.path, payload=deepcopy(action.payload), phase=action.kind,
|
||||||
|
source_task_id=_integer(task.get("id")), source_task_type_id=str(task.get("typeId", "")),
|
||||||
|
source_step_number=number)
|
||||||
|
if not supply.ready:
|
||||||
|
reason = supply.reason + ";" + supply.next_step
|
||||||
|
return self._intent(scope, task, number, step, "progression_blocked", reason, policy, block_reason=reason)
|
||||||
|
return None
|
||||||
|
|
||||||
def _commission_offer_ready(self, snapshot, quest_policy, policy, ranch, info):
|
def _commission_offer_ready(self, snapshot, quest_policy, policy, ranch, info):
|
||||||
if info.get("closed"):
|
if info.get("closed"):
|
||||||
return False, "委托已关闭"
|
return False, "委托已关闭"
|
||||||
@@ -845,9 +879,14 @@ class ProgressionPlanner:
|
|||||||
# Acceptance spends a daily slot. Keep the old scheduler's conservative
|
# Acceptance spends a daily slot. Keep the old scheduler's conservative
|
||||||
# resource preflight, now allowing verified linear story completion.
|
# resource preflight, now allowing verified linear story completion.
|
||||||
money = 0
|
money = 0
|
||||||
item_costs = {}
|
scope, account = self._account(snapshot)
|
||||||
monster_costs = {}
|
|
||||||
for number, step in enumerate(info.get("steps") or [], 1):
|
for number, step in enumerate(info.get("steps") or [], 1):
|
||||||
|
ok, reason = self.condition(step.get("condition"), snapshot)
|
||||||
|
reason = reason if not ok else self._location_gate(str(step.get("position") or ""), snapshot, account)
|
||||||
|
if not reason and step.get("passGuide") and indexed((snapshot.raw.get("history") or {}).get("guide_record"), step["passGuide"]) is not True:
|
||||||
|
reason = "等待引导记录:" + str(step["passGuide"])
|
||||||
|
if reason:
|
||||||
|
return False, f"第{number}步:{reason}"
|
||||||
for script in (step.get("story"), step.get("afterStory")):
|
for script in (step.get("story"), step.get("afterStory")):
|
||||||
reason = self._script_gate(script)
|
reason = self._script_gate(script)
|
||||||
if reason or script and not policy.auto_dialogue:
|
if reason or script and not policy.auto_dialogue:
|
||||||
@@ -860,7 +899,7 @@ class ProgressionPlanner:
|
|||||||
return False, "委托战斗配置缺失"
|
return False, "委托战斗配置缺失"
|
||||||
if kind == "passStage" and not self.data.stage(value.get("stage")):
|
if kind == "passStage" and not self.data.stage(value.get("stage")):
|
||||||
return False, "委托关卡配置缺失"
|
return False, "委托关卡配置缺失"
|
||||||
else:
|
elif not resource_kind(step):
|
||||||
ready, _, reason = self.requirement(snapshot, step, {}, policy, ranch)
|
ready, _, reason = self.requirement(snapshot, step, {}, policy, ranch)
|
||||||
if not ready:
|
if not ready:
|
||||||
preview = {"id": 0, "typeId": str(info.get("id", "")), "curStep": number}
|
preview = {"id": 0, "typeId": str(info.get("id", "")), "curStep": number}
|
||||||
@@ -869,23 +908,12 @@ class ProgressionPlanner:
|
|||||||
if value.get("remove") is True:
|
if value.get("remove") is True:
|
||||||
if kind == "getMoney":
|
if kind == "getMoney":
|
||||||
money += _integer(value.get("money"))
|
money += _integer(value.get("money"))
|
||||||
elif kind == "getItem" or kind == "getMonster" and _integer(value.get("mode"), -1) == 0:
|
|
||||||
key = str(value.get("type"))
|
|
||||||
item_costs[key] = item_costs.get(key, 0) + _integer(value.get("num"))
|
|
||||||
elif kind == "getMonster":
|
|
||||||
key = str(value.get("type"))
|
|
||||||
monster_costs[key] = monster_costs.get(key, 0) + _integer(value.get("num"))
|
|
||||||
if money and (money > policy.max_money or _integer(snapshot.raw["master"].get("money")) - money < ranch.keep_money):
|
if money and (money > policy.max_money or _integer(snapshot.raw["master"].get("money")) - money < ranch.keep_money):
|
||||||
return False, "整份委托提交金币超过设置或保留量"
|
return False, "整份委托提交金币超过设置或保留量"
|
||||||
for key, count in item_costs.items():
|
supply = self.resource_plan(snapshot, info.get("steps") or [], {"id": 0, "typeId": str(info.get("id", ""))},
|
||||||
trial = {"statusType": "getItem", "statusValue": {"type": key, "num": count, "remove": True}}
|
policy, replace(ranch, keep_money=ranch.keep_money + money))
|
||||||
if not self.requirement(snapshot, trial, {}, policy, ranch)[0]:
|
if not supply.feasible:
|
||||||
if not self.farming_intents(snapshot, trial, {"id": 0}, policy, ranch):
|
return False, supply.reason
|
||||||
return False, "整份委托提交道具不足或受保留保护"
|
|
||||||
for key, count in monster_costs.items():
|
|
||||||
trial = {"statusType": "getMonster", "statusValue": {"type": key, "num": count, "mode": 2, "remove": True}}
|
|
||||||
if not self.requirement(snapshot, trial, {}, policy, ranch)[0]:
|
|
||||||
return False, "整份委托提交魔物不足或受保留保护"
|
|
||||||
return (True, "可接取") if info.get("steps") else (False, "委托没有有效步骤")
|
return (True, "可接取") if info.get("steps") else (False, "委托没有有效步骤")
|
||||||
|
|
||||||
def commission_plan(self, snapshot, quest_policy, ranch_policy, *, battle_policy=None, accept_supported=None):
|
def commission_plan(self, snapshot, quest_policy, ranch_policy, *, battle_policy=None, accept_supported=None):
|
||||||
@@ -896,11 +924,16 @@ class ProgressionPlanner:
|
|||||||
taskLoopReceive:{taskTypeId,city}; quotas decrement only on acceptance
|
taskLoopReceive:{taskTypeId,city}; quotas decrement only on acceptance
|
||||||
acknowledgement. Current battle/passStage never become sweep intents.
|
acknowledgement. Current battle/passStage never become sweep intents.
|
||||||
"""
|
"""
|
||||||
|
self.commission_selection = {}
|
||||||
|
self.commission_offer_rows = []
|
||||||
if not quest_policy.enabled:
|
if not quest_policy.enabled:
|
||||||
return []
|
return []
|
||||||
policy = self._commission_policy(quest_policy, battle_policy)
|
policy = self._commission_policy(quest_policy, battle_policy)
|
||||||
scope, account = self._account(snapshot)
|
scope, account = self._account(snapshot)
|
||||||
self.reconcile(snapshot)
|
self.reconcile(snapshot)
|
||||||
|
candidates = self.commission_offers(snapshot, quest_policy, ranch_policy,
|
||||||
|
battle_policy=battle_policy, accept_supported=accept_supported)
|
||||||
|
self.commission_offer_rows = candidates
|
||||||
if account["pending"]:
|
if account["pending"]:
|
||||||
reason = "存在未确认请求,委托等待核对,禁止重发"
|
reason = "存在未确认请求,委托等待核对,禁止重发"
|
||||||
return [self._intent(scope, {}, 0, {}, "progression_blocked", reason, policy, block_reason=reason)]
|
return [self._intent(scope, {}, 0, {}, "progression_blocked", reason, policy, block_reason=reason)]
|
||||||
@@ -925,30 +958,94 @@ class ProgressionPlanner:
|
|||||||
blocked.append(action)
|
blocked.append(action)
|
||||||
if blocked or not quest_policy.accept or remaining <= 0:
|
if blocked or not quest_policy.accept or remaining <= 0:
|
||||||
return blocked
|
return blocked
|
||||||
ranked_offers = sorted(((city, key) for city, values in offers.items() for key in _values(values)),
|
rejected = []
|
||||||
key=lambda pair: commission_priority(self.data.task(str(pair[1])) or {}))
|
for candidate in candidates:
|
||||||
for city, offered_key in ranked_offers:
|
city, key = candidate["city"], candidate["task_type_id"]
|
||||||
city = _integer(city)
|
info = self.data.task(key)
|
||||||
if city <= 0 or quest_policy.city and city != quest_policy.city or not snapshot.city_unlocked(city):
|
if candidate.get("preparable"):
|
||||||
continue
|
money = sum(_integer((s.get("statusValue") or {}).get("money")) for s in info.get("steps") or []
|
||||||
key, info = str(offered_key), self.data.task(offered_key)
|
if s.get("statusType") == "getMoney" and (s.get("statusValue") or {}).get("remove") is True)
|
||||||
if key in active or key in finished or not info or info.get("type") != 4:
|
supply = self.resource_plan(snapshot, info.get("steps") or [], {"id": 0, "typeId": key}, policy,
|
||||||
continue
|
replace(ranch_policy, keep_money=ranch_policy.keep_money + money))
|
||||||
if not self._commission_offer_ready(snapshot, quest_policy, policy, ranch_policy, info)[0]:
|
action = self._resource_intent(snapshot, supply, {"id": 0, "typeId": key}, 0, {}, policy)
|
||||||
continue
|
if action is not None:
|
||||||
if accept_supported is not None and not accept_supported(key):
|
if not action.blocked:
|
||||||
|
self._issued[action.token] = action.to_dict()
|
||||||
|
return [action]
|
||||||
|
if not candidate["eligible"]:
|
||||||
|
rejected.append(candidate)
|
||||||
|
if candidate["blocked_by_support"]:
|
||||||
blocked.append(self._intent(scope, {"id": 0, "typeId": key}, 0, info.get("startStep") or {},
|
blocked.append(self._intent(scope, {"id": 0, "typeId": key}, 0, info.get("startStep") or {},
|
||||||
"progression_loop_accept", "暂不接取:" + info.get("name", key), policy,
|
"progression_loop_accept", "暂不接取:" + info.get("name", key), policy,
|
||||||
path="taskService/taskLoopReceive", payload={"taskTypeId": key, "city": city}, phase=str(today),
|
path="taskService/taskLoopReceive", payload={"taskTypeId": key, "city": city}, phase=str(today),
|
||||||
block_reason="委托后续战斗或条件当前无法自动完成"))
|
block_reason=candidate["reason"]))
|
||||||
continue
|
continue
|
||||||
|
self.commission_selection = {"task_type_id": key, "city": city,
|
||||||
|
**commission_selection(info, candidates, rejected)}
|
||||||
action = self._intent(scope, {"id": 0, "typeId": key}, 0, info.get("startStep") or {},
|
action = self._intent(scope, {"id": 0, "typeId": key}, 0, info.get("startStep") or {},
|
||||||
"progression_loop_accept", "接取城市委托:" + info.get("name", key), policy,
|
"progression_loop_accept", f"接取城市委托:{info.get('name', key)}(预计{candidate['expected_ke']}氪金);" + self.commission_selection["selection_reason"], policy,
|
||||||
path="taskService/taskLoopReceive", payload={"taskTypeId": key, "city": city}, phase=str(today))
|
path="taskService/taskLoopReceive", payload={"taskTypeId": key, "city": city}, phase=str(today))
|
||||||
self._issued[action.token] = action.to_dict()
|
self._issued[action.token] = action.to_dict()
|
||||||
return [action]
|
return [action]
|
||||||
return blocked
|
return blocked
|
||||||
|
|
||||||
|
def commission_offers(self, snapshot, quest_policy, ranch_policy, *, battle_policy=None, accept_supported=None):
|
||||||
|
"""Offline eligibility for every offer; raw presence never means receivable."""
|
||||||
|
policy = self._commission_policy(quest_policy, battle_policy)
|
||||||
|
_, account = self._account(snapshot)
|
||||||
|
today, recorded, remaining, offers = self._loop_view(snapshot, account)
|
||||||
|
active, _, finished = self._tasks(snapshot, account)
|
||||||
|
has_active = any((self.data.task(key) or {}).get("type") == 4 and key not in finished for key in active)
|
||||||
|
rows = []
|
||||||
|
ranked = sorted(((city, key) for city, values in offers.items() for key in _values(values)),
|
||||||
|
key=lambda pair: commission_priority(self.data.task(str(pair[1])) or {}))
|
||||||
|
for offered_city, offered_key in ranked:
|
||||||
|
city, key = _integer(offered_city), str(offered_key)
|
||||||
|
info = self.data.task(key) or {}
|
||||||
|
if info.get("type") != 4:
|
||||||
|
continue
|
||||||
|
support_blocked = False
|
||||||
|
city_info = self.city_diagnostic(city, snapshot)
|
||||||
|
supply = None
|
||||||
|
reason = ("城市编号无效" if city <= 0 else
|
||||||
|
"当日接取次数已用完(剩余0次),等待次日刷新" if remaining <= 0 else
|
||||||
|
f"策略限定城市 {quest_policy.city}" if quest_policy.city and city != quest_policy.city else
|
||||||
|
city_info["city_reason"] if not city_info["city_unlocked"] else
|
||||||
|
"委托列表已跨日,等待刷新确认" if recorded is not None and recorded != today and account["commissions"]["day"] != today else
|
||||||
|
"自动委托未启用" if not quest_policy.enabled else "自动接取未启用" if not quest_policy.accept else
|
||||||
|
"存在未确认请求,等待核对" if account["pending"] else
|
||||||
|
"该委托已接取或已完成" if key in active or key in finished else
|
||||||
|
"已有委托优先完成" if has_active else "")
|
||||||
|
if not reason:
|
||||||
|
ready, reason = self._commission_offer_ready(snapshot, quest_policy, policy, ranch_policy, info)
|
||||||
|
if ready:
|
||||||
|
reason = ""
|
||||||
|
if accept_supported is not None:
|
||||||
|
result = accept_supported(key)
|
||||||
|
supported, detail = result if isinstance(result, tuple) else (result, "")
|
||||||
|
if not supported:
|
||||||
|
reason = detail or "委托后续战斗或条件当前无法自动完成"
|
||||||
|
support_blocked = True
|
||||||
|
if not reason:
|
||||||
|
money = sum(_integer((s.get("statusValue") or {}).get("money")) for s in info.get("steps") or []
|
||||||
|
if s.get("statusType") == "getMoney" and (s.get("statusValue") or {}).get("remove") is True)
|
||||||
|
supply = self.resource_plan(snapshot, info.get("steps") or [], {"id": 0, "typeId": key},
|
||||||
|
policy, replace(ranch_policy, keep_money=ranch_policy.keep_money + money))
|
||||||
|
if not supply.ready:
|
||||||
|
reason = supply.reason + ";" + supply.next_step + ";补齐并核对后再接取,不消耗接取次数"
|
||||||
|
elif any(resource_kind(s) for s in info.get("steps") or []):
|
||||||
|
supply = self.resource_plan(snapshot, info.get("steps") or [], {"id": 0, "typeId": key}, policy, ranch_policy)
|
||||||
|
if supply.feasible:
|
||||||
|
supply = None # A hard prerequisite failed; procurement cannot bypass it.
|
||||||
|
rows.append({"task_type_id": key, "name": info.get("name", key), "city": city,
|
||||||
|
"expected_ke": -commission_priority(info), "eligible": not reason, "reason": reason or "可接取",
|
||||||
|
"blocked_by_support": support_blocked, "preparable": bool(supply and supply.feasible and not supply.ready and not support_blocked),
|
||||||
|
**city_info, "remaining_quota": remaining,
|
||||||
|
"reason_kind": supply.reason_kind if supply and not supply.ready and not support_blocked else commission_reason_kind(reason),
|
||||||
|
"resources": supply.resources if supply else [], "progress_plan": supply.progress_plan if supply else [],
|
||||||
|
"next_step": supply.next_step if supply and not supply.ready else reason or "按奖励优先接取城市委托"})
|
||||||
|
return rows
|
||||||
|
|
||||||
def commission_rows(self, snapshot, quest_policy, ranch_policy, *, battle_policy=None):
|
def commission_rows(self, snapshot, quest_policy, ranch_policy, *, battle_policy=None):
|
||||||
policy = self._commission_policy(quest_policy, battle_policy)
|
policy = self._commission_policy(quest_policy, battle_policy)
|
||||||
return [row for row in self.rows(snapshot, policy, ranch_policy, quest_policy=quest_policy)
|
return [row for row in self.rows(snapshot, policy, ranch_policy, quest_policy=quest_policy)
|
||||||
|
|||||||
@@ -16,10 +16,10 @@ from .battle_messages import battle_message
|
|||||||
CATEGORIES = {"mainline": "主线", "sidequest": "支线", "commission": "委托", "event": "活动(暂不自动)",
|
CATEGORIES = {"mainline": "主线", "sidequest": "支线", "commission": "委托", "event": "活动(暂不自动)",
|
||||||
"bond": "羁绊(暂不自动)", "unknown": "其他 / 未知"}
|
"bond": "羁绊(暂不自动)", "unknown": "其他 / 未知"}
|
||||||
BATTLE_KINDS = {"mainline": "主线战斗", "sidequest": "支线战斗", "commission": "委托战斗",
|
BATTLE_KINDS = {"mainline": "主线战斗", "sidequest": "支线战斗", "commission": "委托战斗",
|
||||||
"battle": "普通战斗", "map_battle": "地图战斗", "sweep": "扫荡", "map_reward_event": "地图奖励事件",
|
"battle": "普通战斗", "map_battle": "地图战斗", "sweep": "扫荡", "hidden": "隐藏关卡战斗", "map_reward_event": "地图奖励事件",
|
||||||
"ordinary_stage": "普通关卡战斗", "task_battle": "任务战斗", "task_pass_stage": "任务通关战斗", "unknown": "其他 / 未知"}
|
"ordinary_stage": "普通关卡战斗", "task_battle": "任务战斗", "task_pass_stage": "任务通关战斗", "unknown": "其他 / 未知"}
|
||||||
BATTLE_ALIASES = {"task": "task_battle", "passStage": "task_pass_stage", "event": "map_reward_event",
|
BATTLE_ALIASES = {"task": "task_battle", "passStage": "task_pass_stage", "event": "map_reward_event",
|
||||||
"reward_event": "map_reward_event", "normal": "battle"}
|
"reward_event": "map_reward_event", "normal": "battle", "map_sweep": "sweep"}
|
||||||
BATTLE_MODES = {"original": "原版运行时(以能力检查为准)", "experimental": "实验模拟(近似,未完整验证)"}
|
BATTLE_MODES = {"original": "原版运行时(以能力检查为准)", "experimental": "实验模拟(近似,未完整验证)"}
|
||||||
STATES = {"available": "可接取", "unaccepted": "未接取", "active": "进行中", "in_progress": "进行中",
|
STATES = {"available": "可接取", "unaccepted": "未接取", "active": "进行中", "in_progress": "进行中",
|
||||||
"ready": "待交付", "completed": "已完成", "complete": "已完成", "claimed": "已领奖",
|
"ready": "待交付", "completed": "已完成", "complete": "已完成", "claimed": "已领奖",
|
||||||
@@ -32,7 +32,8 @@ STATE_ALIASES = {"active": "received", "in_progress": "received", "available": "
|
|||||||
"ready": "ready_to_reward", "completed": "finished", "complete": "finished", "claimed": "finished", "blocked": "received"}
|
"ready": "ready_to_reward", "completed": "finished", "complete": "finished", "claimed": "finished", "blocked": "received"}
|
||||||
CURRENT_STATES = {"received", "unlocked", "ready_to_reward"}
|
CURRENT_STATES = {"received", "unlocked", "ready_to_reward"}
|
||||||
OUTCOMES = {"win": "胜利", "loss": "打不过", "unsupported": "暂不支持", "event": "地图奖励事件",
|
OUTCOMES = {"win": "胜利", "loss": "打不过", "unsupported": "暂不支持", "event": "地图奖励事件",
|
||||||
"completed": "已完成", "cancelled": "已取消", "timeout": "超时", "unknown": "结果待核对"}
|
"completed": "已完成", "cancelled": "已取消", "timeout": "超时", "unknown": "结果待核对",
|
||||||
|
"abandoned_missing_hidden_id": "未完成,已放弃", "abandoned_unsettled_sweep": "未完成,已放弃", "cancelled_unsent_sweep": "未完成,已取消"}
|
||||||
|
|
||||||
|
|
||||||
def category(value):
|
def category(value):
|
||||||
@@ -99,7 +100,7 @@ def prepare_progression_views(engine, *, tasks=True, records=True):
|
|||||||
kind = "map_reward_event"
|
kind = "map_reward_event"
|
||||||
elif row.get("task_id") and kind == "battle":
|
elif row.get("task_id") and kind == "battle":
|
||||||
kind = "task_battle"
|
kind = "task_battle"
|
||||||
elif row.get("kind") == "sweep":
|
elif row.get("kind") in ("sweep", "map_sweep") and kind != "hidden":
|
||||||
kind = "sweep"
|
kind = "sweep"
|
||||||
stamp = row.get("finished_at") or row.get("started_at") or row.get("timestamp", row.get("time", row.get("at")))
|
stamp = row.get("finished_at") or row.get("started_at") or row.get("timestamp", row.get("time", row.get("at")))
|
||||||
if type(stamp) in (int, float) and 0 <= stamp <= 253402271999:
|
if type(stamp) in (int, float) and 0 <= stamp <= 253402271999:
|
||||||
|
|||||||
@@ -7,6 +7,26 @@ from .model import Action, Planner, seconds
|
|||||||
CN = timezone(timedelta(hours=8))
|
CN = timezone(timedelta(hours=8))
|
||||||
|
|
||||||
|
|
||||||
|
def commission_reason_kind(reason):
|
||||||
|
text = str(reason or "")
|
||||||
|
for kind, words in (
|
||||||
|
("quota", ("次数已用完", "次数已耗尽", "额度已用完")),
|
||||||
|
("city_locked", ("城市尚未解锁", "城市未解锁", "城市仍未解锁", "城市还未解锁")),
|
||||||
|
("offline", ("离线", "未登录", "登录失效", "offline")),
|
||||||
|
("uncertain_write", ("未确认请求", "待核对", "结果不明", "禁止重发")),
|
||||||
|
("cooldown", ("冷却", "孵化/成长中", "开放时段", "开放日期", "开放星期", "跨日")),
|
||||||
|
("busy", ("已有委托", "正在探索", "占用", "忙碌", "busy")),
|
||||||
|
("protection", ("保护", "保留种类", "锁定")),
|
||||||
|
("temp_resource", ("不足", "金币", "体力", "可提交", "可用", "缺口")),
|
||||||
|
("prerequisite", ("前置", "前提", "引导", "图鉴", "角色等级", "关卡尚未", "入口关卡")),
|
||||||
|
("policy", ("未启用", "策略限定", "未开启", "限定城市")),
|
||||||
|
("model_unsupported", ("未支持", "尚不支持", "未验证", "尚未验证", "Unsupported", "运行时", "模拟器", "配置缺失")),
|
||||||
|
):
|
||||||
|
if any(word in text for word in words):
|
||||||
|
return kind
|
||||||
|
return "ready" if not text or text in ("可接取", "资源已齐备") else "prerequisite"
|
||||||
|
|
||||||
|
|
||||||
def commission_priority(info):
|
def commission_priority(info):
|
||||||
try:
|
try:
|
||||||
reward = int((info.get("reward") or {}).get("ke") or 0)
|
reward = int((info.get("reward") or {}).get("ke") or 0)
|
||||||
@@ -15,6 +35,24 @@ def commission_priority(info):
|
|||||||
return -reward
|
return -reward
|
||||||
|
|
||||||
|
|
||||||
|
def commission_selection(info, offers, rejected):
|
||||||
|
"""Explain this selection using the offers actually examined, across cities."""
|
||||||
|
reward = -commission_priority(info)
|
||||||
|
higher = [row for row in rejected if row["expected_ke"] > reward]
|
||||||
|
has_twenty = any(row["expected_ke"] == 20 for row in offers)
|
||||||
|
if reward >= 20:
|
||||||
|
code, reason = "highest_reward", f"按氪金奖励优先,选择当前可处理的 {reward} 氪金委托"
|
||||||
|
elif not has_twenty:
|
||||||
|
code, reason = "no_20_offered", f"本次候选未提供20氪金委托,按奖励优先选择 {reward} 氪金委托"
|
||||||
|
if higher:
|
||||||
|
reason += ";" + ";".join(f"{row['name']}({row['expected_ke']}氪金):{row['reason']}" for row in higher)
|
||||||
|
else:
|
||||||
|
code = "20_ineligible"
|
||||||
|
details = ";".join(f"{row['name']}({row['expected_ke']}氪金):{row['reason']}" for row in higher)
|
||||||
|
reason = f"较高奖励委托当前不可接取,选择 {reward} 氪金委托" + (";" + details if details else "")
|
||||||
|
return {"selection_code": code, "selection_reason": reason, "higher_reward_blockers": higher}
|
||||||
|
|
||||||
|
|
||||||
def indexed(value, key, default=None):
|
def indexed(value, key, default=None):
|
||||||
if isinstance(value, dict):
|
if isinstance(value, dict):
|
||||||
return value.get(str(key), value.get(key, default))
|
return value.get(str(key), value.get(key, default))
|
||||||
@@ -84,6 +122,7 @@ class TaskPlanner:
|
|||||||
def __init__(self, catalog):
|
def __init__(self, catalog):
|
||||||
self.catalog = catalog
|
self.catalog = catalog
|
||||||
self.guard = Planner(catalog)
|
self.guard = Planner(catalog)
|
||||||
|
self.commission_selection = {}
|
||||||
|
|
||||||
def current(self, snapshot):
|
def current(self, snapshot):
|
||||||
infos = self.catalog.data.get("task_info", {})
|
infos = self.catalog.data.get("task_info", {})
|
||||||
@@ -161,6 +200,7 @@ class TaskPlanner:
|
|||||||
return rows
|
return rows
|
||||||
|
|
||||||
def plan(self, snapshot, policy, ranch, *, include_active=True, accept_supported=None):
|
def plan(self, snapshot, policy, ranch, *, include_active=True, accept_supported=None):
|
||||||
|
self.commission_selection = {}
|
||||||
if not policy.enabled:
|
if not policy.enabled:
|
||||||
return []
|
return []
|
||||||
history = snapshot.raw.get("history", {})
|
history = snapshot.raw.get("history", {})
|
||||||
@@ -176,37 +216,48 @@ class TaskPlanner:
|
|||||||
index, steps = int(task.get("curStep", 1)) - 1, info.get("steps", [])
|
index, steps = int(task.get("curStep", 1)) - 1, info.get("steps", [])
|
||||||
payload = {"taskId": int(task["id"]), "taskTypeId": str(task["typeId"])}
|
payload = {"taskId": int(task["id"]), "taskTypeId": str(task["typeId"])}
|
||||||
if steps and index >= len(steps):
|
if steps and index >= len(steps):
|
||||||
return [Action("quest_complete", f"领取委托奖励:{info['name']}", "taskService/taskComplete", payload)]
|
return [Action("quest_complete", f"领取委托奖励:{info['name']}(预计{-commission_priority(info)}氪金)", "taskService/taskComplete", payload)]
|
||||||
if 0 <= index < len(steps):
|
if 0 <= index < len(steps):
|
||||||
ready, ids, _ = self.requirement(snapshot, steps[index], task, policy, ranch)
|
ready, ids, _ = self.requirement(snapshot, steps[index], task, policy, ranch)
|
||||||
if ready:
|
if ready:
|
||||||
return [Action("quest_step", f"推进委托:{info['name']}", "taskService/taskCompleteStep", payload | {"removeIds": ids or None})]
|
return [Action("quest_step", f"推进委托:{info['name']}(预计{-commission_priority(info)}氪金)", "taskService/taskCompleteStep", payload | {"removeIds": ids or None})]
|
||||||
if current_tasks or not policy.accept or int(history.get("loopTaskNum", 0)) <= 0:
|
if current_tasks or not policy.accept or int(history.get("loopTaskNum", 0)) <= 0:
|
||||||
return []
|
return []
|
||||||
current = {str(t["typeId"]) for t in self.current(snapshot)}
|
current = {str(t["typeId"]) for t in self.current(snapshot)}
|
||||||
offers = sorted(self.rows(snapshot, policy, ranch), key=lambda row: commission_priority(
|
offers = sorted(self.rows(snapshot, policy, ranch), key=lambda row: commission_priority(
|
||||||
self.catalog.data["task_info"][row[0]]))
|
self.catalog.data["task_info"][row[0]]))
|
||||||
|
candidates, rejected = [], []
|
||||||
for type_id, name, state, _, meta in offers:
|
for type_id, name, state, _, meta in offers:
|
||||||
if "city" not in meta or type_id in current:
|
if "city" not in meta or type_id in current:
|
||||||
continue
|
continue
|
||||||
city = meta["city"]
|
city = meta["city"]
|
||||||
if policy.city and city != policy.city or not snapshot.city_unlocked(city):
|
|
||||||
continue
|
|
||||||
info = self.catalog.data["task_info"][type_id]
|
info = self.catalog.data["task_info"][type_id]
|
||||||
if info.get("closed") or not condition_ok((info.get("startStep") or {}).get("condition"), snapshot):
|
candidate = {"task_type_id": type_id, "name": name, "city": city, "expected_ke": -commission_priority(info)}
|
||||||
|
candidates.append(candidate)
|
||||||
|
reason = (f"策略限定城市 {policy.city}" if policy.city and city != policy.city else
|
||||||
|
"城市尚未解锁" if not snapshot.city_unlocked(city) else "委托已关闭" if info.get("closed") else
|
||||||
|
"接取前置条件未满足" if not condition_ok((info.get("startStep") or {}).get("condition"), snapshot) else "")
|
||||||
|
if reason:
|
||||||
|
rejected.append(candidate | {"reason": reason})
|
||||||
continue
|
continue
|
||||||
steps = info.get("steps", [])
|
steps = info.get("steps", [])
|
||||||
supported = accept_supported(type_id) if accept_supported else all(
|
supported = accept_supported(type_id) if accept_supported else all(
|
||||||
(s.get("statusType") in ("passStage", "battle") and policy.battle_tasks)
|
(s.get("statusType") in ("passStage", "battle") and policy.battle_tasks)
|
||||||
or self.requirement(snapshot, s, {}, policy, ranch)[0] for s in steps)
|
or self.requirement(snapshot, s, {}, policy, ranch)[0] for s in steps)
|
||||||
if supported:
|
if supported:
|
||||||
return [Action("quest_accept", f"接取委托:{name}", "taskService/taskLoopReceive", {"taskTypeId": type_id, "city": city})]
|
self.commission_selection = {"task_type_id": type_id, "city": city,
|
||||||
|
**commission_selection(info, candidates, rejected)}
|
||||||
|
return [Action("quest_accept", f"接取委托:{name}(预计{-commission_priority(info)}氪金);" + self.commission_selection["selection_reason"],
|
||||||
|
"taskService/taskLoopReceive", {"taskTypeId": type_id, "city": city})]
|
||||||
|
reason = next((self.requirement(snapshot, step, {}, policy, ranch)[2] for step in steps
|
||||||
|
if not self.requirement(snapshot, step, {}, policy, ranch)[0]), "委托后续步骤当前无法自动完成")
|
||||||
|
rejected.append(candidate | {"reason": reason})
|
||||||
return []
|
return []
|
||||||
|
|
||||||
def reservations(self, snapshot):
|
def reservations(self, snapshot, *, extra_tasks=()):
|
||||||
types, eggs = set(), {}
|
types, eggs = set(), {}
|
||||||
for task in self.current(snapshot):
|
for task in [*self.current(snapshot), *extra_tasks]:
|
||||||
info = self.catalog.data["task_info"][str(task["typeId"])]
|
info = task.get("info") or self.catalog.data["task_info"][str(task["typeId"])]
|
||||||
for step in info.get("steps", [])[max(0, int(task.get("curStep", 1)) - 1):]:
|
for step in info.get("steps", [])[max(0, int(task.get("curStep", 1)) - 1):]:
|
||||||
value = step.get("statusValue") or {}
|
value = step.get("statusValue") or {}
|
||||||
key = str(value.get("type", ""))
|
key = str(value.get("type", ""))
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
"""Read-only evidence shared by hidden-entry migration and legacy archival."""
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def scan_trace(path, owner):
|
||||||
|
"""Called once per pending by the account worker, never by presentation."""
|
||||||
|
evidence = {"events": [], "files": [], "valid": False, "owner_read": False, "no_consumption": True}
|
||||||
|
if not isinstance(path, (str, Path)):
|
||||||
|
return evidence
|
||||||
|
path = Path(path)
|
||||||
|
role = None
|
||||||
|
safe = {"读取角色", "masterService/masterQueryDetail", "heartBeatService/keepAlive",
|
||||||
|
"渠道账号验证", "获取官方区服", "进入选中区服", "本地区服整理"}
|
||||||
|
def unique(pairs):
|
||||||
|
result = {}
|
||||||
|
for key, item in pairs:
|
||||||
|
if key in result:
|
||||||
|
raise ValueError("调试记录字段重复")
|
||||||
|
result[key] = item
|
||||||
|
return result
|
||||||
|
try:
|
||||||
|
for file in (path.with_name("network_debug.previous.jsonl"), path):
|
||||||
|
if not file.exists():
|
||||||
|
continue
|
||||||
|
raw = file.read_bytes()
|
||||||
|
evidence["files"].append({"name": file.name, "sha256": hashlib.sha256(raw).hexdigest()})
|
||||||
|
for line in raw.decode("utf-8").splitlines():
|
||||||
|
if not line.strip():
|
||||||
|
continue
|
||||||
|
event = json.loads(line, object_pairs_hook=unique)
|
||||||
|
if not isinstance(event, dict):
|
||||||
|
return evidence
|
||||||
|
# Client.enter_server emits this local signature diagnostic
|
||||||
|
# before entering the server; it dispatches no game request.
|
||||||
|
if (event.get("kind") == "info" and event.get("operation") == "进入参数检查"
|
||||||
|
and event.get("scope") == "local"):
|
||||||
|
continue
|
||||||
|
if event.get("kind") not in ("request", "response", "error"):
|
||||||
|
return evidence
|
||||||
|
evidence["events"].append(event)
|
||||||
|
operation, kind, body = event.get("operation"), event.get("kind"), event.get("body")
|
||||||
|
if operation in ("读取角色", "masterService/masterQueryDetail") and kind == "response":
|
||||||
|
role = str((body.get("master") or {}).get("id")) if isinstance(body, dict) else None
|
||||||
|
if role != owner or event.get("http_status", 200) != 200 or body.get("resCode", 0) not in (0, "0"):
|
||||||
|
evidence["no_consumption"] = False
|
||||||
|
else:
|
||||||
|
evidence["owner_read"] = True
|
||||||
|
elif operation not in safe:
|
||||||
|
# A missing role or an unrecognised operation cannot prove
|
||||||
|
# that no later consuming request was dispatched.
|
||||||
|
evidence["no_consumption"] = False
|
||||||
|
evidence["valid"] = bool(evidence["files"]) and role == owner
|
||||||
|
except (OSError, ValueError, TypeError, AttributeError):
|
||||||
|
pass
|
||||||
|
return evidence
|
||||||
|
|
||||||
|
|
||||||
|
def role_path_matches(sweep_path, session, owner, trace_path):
|
||||||
|
from .api import Session
|
||||||
|
from .sessions import identity
|
||||||
|
if not isinstance(session, Session) or str(session.role_id) != owner or not sweep_path:
|
||||||
|
return False
|
||||||
|
root = Path(sweep_path).parent
|
||||||
|
return (root.parent.name == "roles" and root.name == identity(session)
|
||||||
|
and root.resolve() == root.absolute() and isinstance(trace_path, (str, Path))
|
||||||
|
and Path(trace_path).parent.resolve() == root.parent.parent.resolve())
|
||||||
+209
-2
@@ -1,9 +1,13 @@
|
|||||||
"""The built-in three-difficulty-cleared sweep path from StageStartPanel."""
|
"""The built-in three-difficulty-cleared sweep path from StageStartPanel."""
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
|
from contextlib import nullcontext
|
||||||
|
from datetime import datetime
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
import json
|
import json
|
||||||
|
import math
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import sqlite3
|
import sqlite3
|
||||||
|
import time
|
||||||
import uuid
|
import uuid
|
||||||
|
|
||||||
from .daily import day
|
from .daily import day
|
||||||
@@ -17,6 +21,34 @@ def settled_reward_event(response):
|
|||||||
return event_reward(response) is not None
|
return event_reward(response) is not None
|
||||||
|
|
||||||
|
|
||||||
|
def successful_response(response):
|
||||||
|
if not isinstance(response, dict):
|
||||||
|
return False
|
||||||
|
if "resCode" not in response:
|
||||||
|
# Existing in-process adapters may already have checked resCode.
|
||||||
|
return (type(response.get("triggerEvent")) is bool
|
||||||
|
or type(response.get("triggerEvent")) is int and response["triggerEvent"] in (0, 1)
|
||||||
|
or isinstance(response.get("reward"), dict))
|
||||||
|
return (type(response["resCode"]) is int and response["resCode"] == 0
|
||||||
|
or type(response["resCode"]) is str and response["resCode"] == "0")
|
||||||
|
|
||||||
|
|
||||||
|
def hidden_stage_id(response):
|
||||||
|
"""Return the original hidden ID only for an explicit hidden event."""
|
||||||
|
if not isinstance(response, dict):
|
||||||
|
return None
|
||||||
|
flag = response.get("triggerEvent")
|
||||||
|
event = response.get("stageEvent")
|
||||||
|
if not (flag is True or type(flag) is int and flag == 1) or not isinstance(event, dict):
|
||||||
|
return None
|
||||||
|
identifier = event.get("hideStageId")
|
||||||
|
if isinstance(identifier, str) and identifier.strip():
|
||||||
|
return identifier
|
||||||
|
if type(identifier) is int and identifier > 0:
|
||||||
|
return str(identifier)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class SweepPolicy:
|
class SweepPolicy:
|
||||||
enabled: bool = False
|
enabled: bool = False
|
||||||
@@ -133,6 +165,140 @@ class SweepRunner:
|
|||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
def recover_hidden_start(self, snapshot, trace_path, *, events=None):
|
||||||
|
"""Recover entry evidence only; never replay entry or infer settlement.
|
||||||
|
|
||||||
|
Old journals lack entry snapshots. Trace proof deliberately does not
|
||||||
|
manufacture runtime inputs from the current, post-entry snapshot.
|
||||||
|
"""
|
||||||
|
from .battles import gameplay_response
|
||||||
|
|
||||||
|
pending = self.state.get("pending")
|
||||||
|
old_phases = {"遭遇隐藏关卡,请在游戏内手动战斗", "遇到事件或响应缺少事件状态,请在游戏内处理"}
|
||||||
|
if not isinstance(pending, dict) or not trace_path:
|
||||||
|
return False
|
||||||
|
if (pending.get("phase") not in old_phases
|
||||||
|
and not (pending.get("phase") == "开始请求待确认" and "start_response" not in pending)):
|
||||||
|
return False
|
||||||
|
owner = snapshot.raw.get("master", {}).get("id")
|
||||||
|
if owner is None or (pending.get("role_id") is not None and str(pending["role_id"]) != str(owner)):
|
||||||
|
return False
|
||||||
|
owner = str(owner)
|
||||||
|
parent, level = pending.get("stage"), pending.get("level")
|
||||||
|
if parent is None or level is None:
|
||||||
|
return False
|
||||||
|
reservation = pending.get("counts_key")
|
||||||
|
if pending.get("role_id") is None:
|
||||||
|
# Multiple dates or roles cannot identify which entry this block owns.
|
||||||
|
reservations = [(key, count) for key, count in self.state.get("counts", {}).items()
|
||||||
|
if isinstance(key, str) and len(key.split(":")) == 4
|
||||||
|
and key.split(":")[2:] == [str(parent), str(level)] and count != 0]
|
||||||
|
if (len(reservations) != 1 or reservations[0][0].split(":")[0] != owner
|
||||||
|
or type(reservations[0][1]) is not int or reservations[0][1] <= 0):
|
||||||
|
return False
|
||||||
|
reservation = reservations[0][0]
|
||||||
|
if reservation is not None:
|
||||||
|
parts = reservation.split(":") if isinstance(reservation, str) else []
|
||||||
|
if len(parts) != 4 or parts[0] != owner or parts[2:] != [str(parent), str(level)]:
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
datetime.strptime(parts[1], "%Y-%m-%d")
|
||||||
|
except ValueError:
|
||||||
|
return False
|
||||||
|
role, latest, candidate = None, None, None
|
||||||
|
requests, responses = {}, set()
|
||||||
|
# Everything outside these explicit reads is an uncertain write.
|
||||||
|
reads = {"读取角色", "masterService/masterQueryDetail"}
|
||||||
|
def unambiguous_object(pairs):
|
||||||
|
result = {}
|
||||||
|
for key, value in pairs:
|
||||||
|
if key in result:
|
||||||
|
raise ValueError("Duplicate trace field")
|
||||||
|
result[key] = value
|
||||||
|
return result
|
||||||
|
path = Path(trace_path)
|
||||||
|
try:
|
||||||
|
for file in ((None,) if events is not None else (path.with_name("network_debug.previous.jsonl"), path)):
|
||||||
|
if file is not None and not file.exists():
|
||||||
|
continue
|
||||||
|
with (nullcontext(events) if file is None else file.open(encoding="utf-8")) as stream:
|
||||||
|
for line in stream:
|
||||||
|
if isinstance(line, str) and not line.strip():
|
||||||
|
continue
|
||||||
|
event = line if isinstance(line, dict) else json.loads(line, object_pairs_hook=unambiguous_object)
|
||||||
|
if not isinstance(event, dict):
|
||||||
|
return False
|
||||||
|
operation, kind = event.get("operation"), event.get("kind")
|
||||||
|
body, identifier = event.get("body"), event.get("request_id")
|
||||||
|
if not isinstance(operation, str) or kind not in ("request", "response", "error"):
|
||||||
|
return False
|
||||||
|
if operation in reads:
|
||||||
|
if kind == "response":
|
||||||
|
master = body.get("master") if isinstance(body, dict) else None
|
||||||
|
observed = master.get("id") if isinstance(master, dict) else None
|
||||||
|
if (type(observed) not in (int, str) or not str(observed).strip()
|
||||||
|
or event.get("http_status", 200) != 200
|
||||||
|
or "resCode" in body and not successful_response(body)):
|
||||||
|
observed = None
|
||||||
|
observed = str(observed) if observed is not None else None
|
||||||
|
if role != observed:
|
||||||
|
latest, candidate = None, None
|
||||||
|
role = observed
|
||||||
|
elif kind == "error":
|
||||||
|
role, latest, candidate = None, None, None
|
||||||
|
continue
|
||||||
|
if not isinstance(identifier, str) or not identifier or not isinstance(body, dict):
|
||||||
|
return False
|
||||||
|
if kind == "request":
|
||||||
|
if identifier in requests:
|
||||||
|
return False
|
||||||
|
requests[identifier] = (operation, role)
|
||||||
|
if role is None or role == owner:
|
||||||
|
latest, candidate = None, None
|
||||||
|
if (role == owner and operation == "stageService/stageStart"
|
||||||
|
and str(body.get("stageTypeId")) == str(parent)
|
||||||
|
and str(body.get("stageLevel")) == str(level)):
|
||||||
|
latest = identifier
|
||||||
|
elif kind == "response":
|
||||||
|
if identifier in responses:
|
||||||
|
return False
|
||||||
|
responses.add(identifier)
|
||||||
|
if (identifier == latest and requests.get(identifier) == (operation, owner)
|
||||||
|
and role == owner and operation == "stageService/stageStart"
|
||||||
|
and event.get("http_status") == 200 and body.get("resCode") in (0, "0") and successful_response(body)
|
||||||
|
and hidden_stage_id(body) is not None and not settled_reward_event(body)):
|
||||||
|
candidate = event
|
||||||
|
elif role is None or role == owner:
|
||||||
|
latest, candidate = None, None
|
||||||
|
elif role is None or role == owner:
|
||||||
|
latest, candidate = None, None
|
||||||
|
except (OSError, ValueError, TypeError, AttributeError):
|
||||||
|
return False
|
||||||
|
if candidate is None or role != owner:
|
||||||
|
return False
|
||||||
|
confirmed_at = None
|
||||||
|
try:
|
||||||
|
stamp = candidate.get("time")
|
||||||
|
parsed = datetime.fromisoformat(stamp) if isinstance(stamp, str) else None
|
||||||
|
if parsed is not None and parsed.tzinfo is not None:
|
||||||
|
confirmed_at = parsed.timestamp()
|
||||||
|
if confirmed_at is not None and (not math.isfinite(confirmed_at) or confirmed_at <= 0):
|
||||||
|
confirmed_at = None
|
||||||
|
except (ValueError, OverflowError, OSError):
|
||||||
|
pass
|
||||||
|
update = {"role_id": owner, "phase": "hidden_started", "start_path": "stageService/stageStart",
|
||||||
|
"start_dispatched": True, "start_confirmed": True,
|
||||||
|
"start_response": gameplay_response(candidate["body"]),
|
||||||
|
"hidden_stage_id": hidden_stage_id(candidate["body"]),
|
||||||
|
"start_request_id": candidate["request_id"], "evidence_status": "trace_confirmed_hidden_start"}
|
||||||
|
if reservation is not None:
|
||||||
|
update["counts_key"] = reservation
|
||||||
|
if confirmed_at is not None:
|
||||||
|
update["start_confirmed_at"] = confirmed_at
|
||||||
|
pending.update(update)
|
||||||
|
self.save()
|
||||||
|
return True
|
||||||
|
|
||||||
def save(self):
|
def save(self):
|
||||||
if self.path:
|
if self.path:
|
||||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
@@ -202,7 +368,9 @@ class SweepRunner:
|
|||||||
return stage
|
return stage
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def run(self, client, snapshot, stage, policy):
|
def run(self, client, snapshot, stage, policy, *, cancel=None, origin=None):
|
||||||
|
from .battles import CancelledBeforeDispatch, gameplay_response, public_data
|
||||||
|
|
||||||
self.last_outcome = ""
|
self.last_outcome = ""
|
||||||
self.last_reward = None
|
self.last_reward = None
|
||||||
rule = policy.rules.get(stage.stage_id) or {}
|
rule = policy.rules.get(stage.stage_id) or {}
|
||||||
@@ -212,10 +380,42 @@ class SweepRunner:
|
|||||||
if reason:
|
if reason:
|
||||||
raise ValueError(reason)
|
raise ValueError(reason)
|
||||||
key = self.key(snapshot, stage)
|
key = self.key(snapshot, stage)
|
||||||
|
previous_count = self.state["counts"].get(key)
|
||||||
self.state["counts"][key] = self.used(snapshot, stage) + 1
|
self.state["counts"][key] = self.used(snapshot, stage) + 1
|
||||||
self.state["pending"] = {"stage": stage.stage_id, "level": stage.level, "phase": "开始请求待确认", "sampleId": uuid.uuid4().hex}
|
self.state["pending"] = {"stage": stage.stage_id, "level": stage.level,
|
||||||
|
"phase": "开始请求待确认", "sampleId": uuid.uuid4().hex,
|
||||||
|
"role_id": str(snapshot.raw["master"]["id"]), "team": policy.team, "counts_key": key,
|
||||||
|
"entry_snapshot": public_data(snapshot.raw), "entry_snapshot_now": snapshot.now,
|
||||||
|
"origin": public_data(origin) if isinstance(origin, dict) else {},
|
||||||
|
"start_path": "stageService/stageStart", "start_dispatched": False, "start_confirmed": False,
|
||||||
|
"settlement_dispatched": False, "record_dispatched": False}
|
||||||
self.save() # Reserve before the first non-retryable write, including timeouts.
|
self.save() # Reserve before the first non-retryable write, including timeouts.
|
||||||
|
self.state["pending"]["start_dispatched"] = True
|
||||||
|
self.save()
|
||||||
|
if cancel is not None and cancel.is_set():
|
||||||
|
if previous_count is None:
|
||||||
|
self.state["counts"].pop(key, None)
|
||||||
|
else:
|
||||||
|
self.state["counts"][key] = previous_count
|
||||||
|
self.state["pending"] = None
|
||||||
|
self.save()
|
||||||
|
raise CancelledBeforeDispatch()
|
||||||
started = client.call("stageService/stageStart", {"stageTypeId": stage.stage_id, "stageLevel": stage.level})
|
started = client.call("stageService/stageStart", {"stageTypeId": stage.stage_id, "stageLevel": stage.level})
|
||||||
|
if not successful_response(started):
|
||||||
|
raise ValueError("扫荡开始未返回可信的成功响应,禁止自动重试")
|
||||||
|
self.state["pending"].update(start_response=gameplay_response(started),
|
||||||
|
start_confirmed=True, start_confirmed_at=time.time())
|
||||||
|
self.save()
|
||||||
|
hidden = hidden_stage_id(started)
|
||||||
|
if hidden is not None and not settled_reward_event(started):
|
||||||
|
self.state["pending"].update(phase="hidden_started", hidden_stage_id=hidden)
|
||||||
|
self.save()
|
||||||
|
self.last_outcome = "hidden"
|
||||||
|
if origin is None:
|
||||||
|
# Callers without the orchestrator handoff must retain the
|
||||||
|
# historical stop signal, while preserving the new evidence.
|
||||||
|
raise ValueError("隐藏关卡已入场,等待战斗接续")
|
||||||
|
return started
|
||||||
if settled_reward_event(started):
|
if settled_reward_event(started):
|
||||||
# StageCenter.startStageHandler applies stageEvent.result directly;
|
# StageCenter.startStageHandler applies stageEvent.result directly;
|
||||||
# StageStartPanel shows it and returns, without battleEnd.
|
# StageStartPanel shows it and returns, without battleEnd.
|
||||||
@@ -239,8 +439,15 @@ class SweepRunner:
|
|||||||
"win": True, "cheatNum": 0, "cheatRecords": "", "killMonster": {}, "battleMonIds": self.team_ids(snapshot, policy),
|
"win": True, "cheatNum": 0, "cheatRecords": "", "killMonster": {}, "battleMonIds": self.team_ids(snapshot, policy),
|
||||||
**{name: 0 for name in ("leftTime", "killNum", "totalDamage", "bossDamage", "deadNum", "aliveNum", "apLeft")}}
|
**{name: 0 for name in ("leftTime", "killNum", "totalDamage", "bossDamage", "deadNum", "aliveNum", "apLeft")}}
|
||||||
self.state["pending"]["phase"] = "扫荡结算待确认"
|
self.state["pending"]["phase"] = "扫荡结算待确认"
|
||||||
|
self.state["pending"].update(settlement_dispatched=True, sweep_battle_data=battle)
|
||||||
self.save()
|
self.save()
|
||||||
|
if cancel is not None and cancel.is_set():
|
||||||
|
self.state["pending"].update(phase="cancelled_before_sweep_settlement", settlement_dispatched=False)
|
||||||
|
self.save()
|
||||||
|
raise CancelledBeforeDispatch()
|
||||||
result = client.call("battleService/battleEnd", {"battleData": battle})
|
result = client.call("battleService/battleEnd", {"battleData": battle})
|
||||||
|
if not successful_response(result):
|
||||||
|
raise ValueError("扫荡结算未返回可信的成功响应,禁止自动重试")
|
||||||
self.remember_reward(client, snapshot, stage, "sweep", result.get("reward"), result)
|
self.remember_reward(client, snapshot, stage, "sweep", result.get("reward"), result)
|
||||||
self.state["pending"] = None
|
self.state["pending"] = None
|
||||||
self.save()
|
self.save()
|
||||||
|
|||||||
@@ -0,0 +1,139 @@
|
|||||||
|
"""Offline presentation regressions: input support never predicts a victory."""
|
||||||
|
from copy import deepcopy
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import Mock, patch
|
||||||
|
|
||||||
|
from ranch_assistant.engine import Engine
|
||||||
|
from ranch_assistant.game_data import ProgressionData
|
||||||
|
from ranch_assistant.model import Catalog, Policy, Snapshot
|
||||||
|
from ranch_assistant.progression import ProgressionPolicy
|
||||||
|
from ranch_web.policies import default_config
|
||||||
|
from ranch_web.views import build_view
|
||||||
|
|
||||||
|
|
||||||
|
class BattleCapabilityPresentationTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.runtime = Mock()
|
||||||
|
self.runtime.inspect.return_value = {"supported": True, "settlement_eligible": True,
|
||||||
|
"faithful": True, "approximate": False}
|
||||||
|
self.runtime.run.side_effect = AssertionError("presentation must not simulate")
|
||||||
|
self.client = Mock()
|
||||||
|
self.client.call.side_effect = AssertionError("offline: no game calls")
|
||||||
|
self.client.snapshot.side_effect = AssertionError("offline: no snapshot requests")
|
||||||
|
self.step = {"statusType": "passStage", "statusValue": {"stage": "0216", "level": "1"},
|
||||||
|
"position": "city1_wild_stage0216_level1", "story": "before", "afterStory": "after"}
|
||||||
|
self.data = ProgressionData({"task_info": {"1002013": {"type": 1, "name": "offline mainline",
|
||||||
|
"steps": [self.step]}}, "scripts": {"before": {"supported": True}, "after": {"supported": True}},
|
||||||
|
"game_setting": {"cityInfo": {"1": {"name": "offline city"}}},
|
||||||
|
"stage_info": {"0216": {"city": 1, "cost": {"ti": 6},
|
||||||
|
"level": {"1": {"cost": 0, "battle": {"fixture": True}}}}}})
|
||||||
|
self.engine = Engine(Catalog(), self.client, game_data=self.data, battle_runtime=self.runtime)
|
||||||
|
self.engine.progression_policy = ProgressionPolicy(enabled=True)
|
||||||
|
self.engine.policy = Policy(enabled=False, gift_enabled=False, fill=False)
|
||||||
|
self.engine.snapshot = Snapshot({"master": {"id": 1, "level": 20, "ti": 100, "money": 1000},
|
||||||
|
"currentTasks": [{"id": 11, "typeId": "1002013", "curStep": 1, "stepValue": 0}],
|
||||||
|
"monsters": [{"id": 101, "typeId": 1001010, "mode": 2, "process": 3, "level": 20}],
|
||||||
|
"teams": [{"teamName": "teamA", "teamType": "battleTeam", "monsters": [101]}],
|
||||||
|
"items": [], "stacks": [], "rooms": [],
|
||||||
|
"history": {"unlockCity": {"1": True}, "unlockStage": {"0216": [1]}}})
|
||||||
|
self.addCleanup(self.assert_read_only)
|
||||||
|
|
||||||
|
def assert_read_only(self):
|
||||||
|
self.client.call.assert_not_called()
|
||||||
|
self.client.snapshot.assert_not_called()
|
||||||
|
self.runtime.run.assert_not_called()
|
||||||
|
|
||||||
|
def refresh(self):
|
||||||
|
self.engine._refresh_progression_cache(force=True)
|
||||||
|
self.assertEqual(self.engine._progression_error, "")
|
||||||
|
return next(row for row in self.engine.progression_rows() if row["task_type_id"] == "1002013")
|
||||||
|
|
||||||
|
def mainline_view(self):
|
||||||
|
# Rendering consumes prepared DTOs; it must never inspect or plan.
|
||||||
|
with patch.object(self.engine, "_battle_capability", side_effect=AssertionError("view inspection")), \
|
||||||
|
patch.object(self.engine, "_refresh_progression_cache", side_effect=AssertionError("view planning")):
|
||||||
|
return build_view(self.engine, "mainline", default_config())
|
||||||
|
|
||||||
|
def test_navigation_and_before_story_reuse_positive_preflight_without_a_false_block(self):
|
||||||
|
row = self.refresh()
|
||||||
|
self.assertEqual(self.engine._progression_intents[0].kind, "progression_navigate")
|
||||||
|
self.assertTrue(row["supported"])
|
||||||
|
self.assertEqual((row["block_reason"], row["blocked_reason"], row["reason_kind"]), ("", "", "ready"))
|
||||||
|
self.assertIn("前往任务位置", row["next_action"])
|
||||||
|
self.refresh()
|
||||||
|
self.runtime.inspect.assert_called_once()
|
||||||
|
self.assertEqual(self.mainline_view()["rows"][0]["support"], "已支持")
|
||||||
|
_, account = self.engine.progression_planner._account(self.engine.snapshot)
|
||||||
|
account["position"] = self.step["position"]
|
||||||
|
row = self.refresh()
|
||||||
|
action = self.engine._progression_intents[0]
|
||||||
|
self.assertEqual((action.kind, action.phase), ("progression_dialogue", "before"))
|
||||||
|
self.assertIs(row["supported"], True)
|
||||||
|
self.assertEqual(row["blocked_reason"], "")
|
||||||
|
self.runtime.inspect.assert_called_once()
|
||||||
|
|
||||||
|
def test_disabled_mainline_is_neutral_without_execution_intents(self):
|
||||||
|
self.engine.progression_policy.enabled = False
|
||||||
|
row = self.refresh()
|
||||||
|
self.assertEqual(self.engine._progression_intents, [])
|
||||||
|
self.assertIsNone(row["supported"])
|
||||||
|
self.assertEqual((row["blocked_reason"], row["reason_kind"]), ("", "unchecked"))
|
||||||
|
self.assertEqual(row["status"], "自动主线策略未启用")
|
||||||
|
self.assertIn("前往任务位置", row["next_action"])
|
||||||
|
view = self.mainline_view()
|
||||||
|
self.assertEqual(view["rows"][0]["support"], "支持状态未确认")
|
||||||
|
self.assertNotIn("模型尚未支持", str(view))
|
||||||
|
self.engine.progression_policy.enabled = True
|
||||||
|
self.assertIs(self.refresh()["supported"], True)
|
||||||
|
self.runtime.inspect.assert_called_once()
|
||||||
|
|
||||||
|
def test_real_unsupported_inputs_keep_their_reason_even_while_paused(self):
|
||||||
|
reason = "Unsupported monster controller: fixture"
|
||||||
|
self.runtime.inspect.return_value.update(supported=False, reasons=[reason])
|
||||||
|
for enabled in (True, False):
|
||||||
|
with self.subTest(enabled=enabled):
|
||||||
|
self.engine.progression_policy.enabled = enabled
|
||||||
|
row = self.refresh()
|
||||||
|
self.assertIs(row["supported"], False)
|
||||||
|
self.assertEqual((row["blocked_reason"], row["reason_kind"]), (reason, "model_unsupported"))
|
||||||
|
self.runtime.inspect.assert_called_once()
|
||||||
|
|
||||||
|
def test_resource_policy_and_unchecked_rows_keep_truthful_reasons_without_inspections(self):
|
||||||
|
for field, invalid, word in (("teams", [], "队"), ("ti", 0, "体力")):
|
||||||
|
with self.subTest(field=field):
|
||||||
|
target = self.engine.snapshot.raw if field == "teams" else self.engine.snapshot.raw["master"]
|
||||||
|
original = target[field]
|
||||||
|
target[field] = invalid
|
||||||
|
row = self.refresh()
|
||||||
|
self.assertIs(row["supported"], False)
|
||||||
|
self.assertIn(word, row["blocked_reason"])
|
||||||
|
self.assertNotEqual(row["reason_kind"], "model_unsupported")
|
||||||
|
target[field] = original
|
||||||
|
source = [{"task_type_id": str(i), "battle_kind": "passStage", "supported": supported,
|
||||||
|
"block_reason": reason} for i, (supported, reason) in enumerate((
|
||||||
|
(False, ""), (True, "自动对话未启用"), (False, "前置任务尚未完成")))]
|
||||||
|
rows, _ = self.engine._overlay_battle_capabilities(deepcopy(source), [])
|
||||||
|
self.assertTrue(all(row["supported"] is False for row in rows))
|
||||||
|
self.assertEqual([row["blocked_reason"] for row in rows], [row["block_reason"] for row in source])
|
||||||
|
rows = [{"task_type_id": str(i), "state": state, "category": "mainline", "battle_kind": "passStage",
|
||||||
|
"supported": state == "received"} for i, state in enumerate(["finished", "locked", "received"] * 400)]
|
||||||
|
rows, _ = self.engine._overlay_battle_capabilities(rows, [])
|
||||||
|
self.assertTrue(all(row["block_reason"] == "" and row["reason_kind"] != "model_unsupported" for row in rows))
|
||||||
|
self.assertTrue(all(row["supported"] is None and row["reason_kind"] == "unchecked"
|
||||||
|
for row in rows if row["state"] == "received"))
|
||||||
|
self.runtime.inspect.assert_not_called()
|
||||||
|
|
||||||
|
def test_inspect_support_does_not_relabel_a_recorded_loss_as_unsupported_or_win(self):
|
||||||
|
row = self.refresh()
|
||||||
|
self.assertIs(row["supported"], True)
|
||||||
|
self.engine._progression_records = [{"task_type_id": "1002013", "task_id": 11,
|
||||||
|
"battle_kind": "passStage", "battle_mode": "experimental", "outcome": "loss"}]
|
||||||
|
before = deepcopy(self.engine._progression_records)
|
||||||
|
view = build_view(self.engine, "battles", default_config())
|
||||||
|
self.assertEqual(view["rows"][0]["outcome"], "loss")
|
||||||
|
self.assertIn("打不过", view["rows"][0]["outcome_label"])
|
||||||
|
self.assertEqual(self.engine._progression_records, before)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
"""Aggregate contract tests; synthetic rosters and public original task data."""
|
||||||
|
from copy import deepcopy
|
||||||
|
import threading
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from ranch_assistant.battle_quick import MAX_GENERATED, prepare, simulate_quick
|
||||||
|
from ranch_assistant.battle_simulator import (
|
||||||
|
DESKTOP_DAMAGE_PROFILE, ExperimentalBattleRuntime, _prepare, combat_tables, simulate,
|
||||||
|
)
|
||||||
|
from ranch_assistant.battles import BattleOrchestrator
|
||||||
|
from ranch_assistant.game_data import ProgressionData
|
||||||
|
from ranch_assistant.tests.test_battle_simulator import battle_of, enemy, monster, request
|
||||||
|
|
||||||
|
|
||||||
|
class QuickBattleTests(unittest.TestCase):
|
||||||
|
def test_default_worker_matches_aggregate_and_preserves_detailed_entrypoint(self):
|
||||||
|
req = request()
|
||||||
|
result = ExperimentalBattleRuntime().run(req)
|
||||||
|
self.assertEqual(result, simulate_quick(req))
|
||||||
|
self.assertEqual(result["simulation_method"], "aggregate_hp_dps")
|
||||||
|
self.assertNotEqual(result["model"], simulate(req)["model"])
|
||||||
|
self.assertTrue(result["approximate"])
|
||||||
|
self.assertFalse(result["faithful"])
|
||||||
|
self.assertFalse(result["settlement_eligible"])
|
||||||
|
|
||||||
|
def test_original_player_and_authored_enemy_stats_are_preserved(self):
|
||||||
|
req = request(enemies=[enemy(atk=31, hp=101, dex=7)])
|
||||||
|
battle_of(req).update(scaleAbility=1.2, scaleHp=1.5)
|
||||||
|
detailed, _ = _prepare(req, combat_tables())
|
||||||
|
quick, report = prepare(req)
|
||||||
|
self.assertEqual([u.stats for u in quick.units], [u.stats for u in detailed.units])
|
||||||
|
self.assertEqual(report["units"][1]["stats"]["hp"], 151)
|
||||||
|
|
||||||
|
def test_unknown_controllers_skills_and_path_data_are_warnings(self):
|
||||||
|
req = request(players=[monster(species=1001020)], enemies=[enemy(controller=[
|
||||||
|
{"type": "unmodeled", "para": {}}, {"type": "monSteps", "para": {"points": ["absent"]}}])])
|
||||||
|
battle_of(req)["controller"] = [{"type": "other_effect", "para": {}}]
|
||||||
|
battle_of(req).pop("battleField")
|
||||||
|
report = ExperimentalBattleRuntime().inspect(req)
|
||||||
|
self.assertTrue(report["supported"], report["reasons"])
|
||||||
|
self.assertTrue(report["assumptions"])
|
||||||
|
self.assertIn("unmodeled", report["aggregate_controllers"])
|
||||||
|
self.assertTrue(any(d["code"] == "aggregate_skill" for d in report["diagnostics"]))
|
||||||
|
self.assertEqual(simulate_quick(req)["execution_status"], "completed")
|
||||||
|
|
||||||
|
def test_missing_growth_or_original_species_still_refuses(self):
|
||||||
|
req = request()
|
||||||
|
req["roster"]["monsters"][0].pop("gAtk")
|
||||||
|
self.assertFalse(ExperimentalBattleRuntime().inspect(req)["supported"])
|
||||||
|
req = request(enemies=[enemy(type="unknown")])
|
||||||
|
self.assertFalse(ExperimentalBattleRuntime().inspect(req)["supported"])
|
||||||
|
|
||||||
|
def test_empty_survival_battle_runs_until_original_clock(self):
|
||||||
|
req = request(seconds=3, enemies=[])
|
||||||
|
battle_of(req)["winType"] = ["2"]
|
||||||
|
result = simulate_quick(req)
|
||||||
|
self.assertEqual(result["outcome"], "win")
|
||||||
|
self.assertEqual(result["elapsed_ms"], 3000)
|
||||||
|
self.assertEqual(result["battle_data"]["leftTime"], 0)
|
||||||
|
self.assertEqual(result["terminal_reason"], "battle_time_limit")
|
||||||
|
|
||||||
|
def test_standalone_maker_has_a_bounded_real_numeric_enemy_budget(self):
|
||||||
|
req = request(seconds=140, enemies=[])
|
||||||
|
battle_of(req)["winType"] = ["2"]
|
||||||
|
battle_of(req)["controller"] = [{"type": "monMaker", "para": {
|
||||||
|
"monType": 1001010, "team": 2, "hp": 1, "atk": 0, "interval": 1}}]
|
||||||
|
result = simulate_quick(req)
|
||||||
|
self.assertEqual(result["outcome"], "win")
|
||||||
|
self.assertEqual(result["generated_units"], MAX_GENERATED)
|
||||||
|
self.assertTrue(result["spawn_bound_reached"])
|
||||||
|
self.assertGreater(result["damage_hp_lost"]["2"], 0)
|
||||||
|
self.assertEqual(result["elapsed_ms"], 140000)
|
||||||
|
|
||||||
|
def test_unknown_generated_species_is_missing_numeric_data(self):
|
||||||
|
req = request(enemies=[])
|
||||||
|
battle_of(req)["controller"] = [{"type": "monMaker", "para": {"monType": 999999999}}]
|
||||||
|
self.assertFalse(ExperimentalBattleRuntime().inspect(req)["supported"])
|
||||||
|
|
||||||
|
def test_zero_capacity_team_can_deploy_uncounted_authored_enemies(self):
|
||||||
|
req = request(enemies=[enemy(countUnit=False)])
|
||||||
|
battle_of(req)["teams"][0]["numMax"] = 0
|
||||||
|
result = simulate_quick(req)
|
||||||
|
self.assertTrue(result["supported"], result["reasons"])
|
||||||
|
self.assertIsNotNone(result["units"][1]["joined_ms"])
|
||||||
|
self.assertEqual(result["execution_status"], "completed")
|
||||||
|
|
||||||
|
def test_weak_team_loses_without_assigned_victory(self):
|
||||||
|
result = simulate_quick(request(players=[monster(level=1)], enemies=[enemy(hp=10000, atk=10000)]))
|
||||||
|
self.assertEqual(result["outcome"], "loss")
|
||||||
|
self.assertEqual(result["alive_num"], 0)
|
||||||
|
self.assertFalse(result["battle_data"]["win"])
|
||||||
|
|
||||||
|
def test_protect_any_and_protect_all_use_actual_remaining_hp(self):
|
||||||
|
req = request(seconds=3, players=[monster(level=1)], enemies=[
|
||||||
|
enemy(mid=11, team=1, protectTarget=True, hp=1, atk=0),
|
||||||
|
enemy(mid=12, team=1, protectTarget=True, hp=10000, atk=0),
|
||||||
|
enemy(mid=13, hp=100000, atk=20)])
|
||||||
|
battle_of(req).update(winType=["2"], loseType=["3", "2"])
|
||||||
|
result = simulate_quick(req)
|
||||||
|
self.assertEqual(result["outcome"], "loss")
|
||||||
|
self.assertLess(result["elapsed_ms"], 3000)
|
||||||
|
battle_of(req)["loseType"] = ["4", "2"]
|
||||||
|
result = simulate_quick(req)
|
||||||
|
self.assertEqual(result["outcome"], "win")
|
||||||
|
self.assertEqual(result["elapsed_ms"], 3000)
|
||||||
|
protected = [u for u in result["units"] if u["protect_target"]]
|
||||||
|
self.assertEqual(sum(u["hp"] > 0 for u in protected), 1)
|
||||||
|
|
||||||
|
def test_destroy_any_and_destroy_all_are_distinct(self):
|
||||||
|
req = request(seconds=3, enemies=[enemy(mid=11, destroyTarget=True, hp=1, atk=0),
|
||||||
|
enemy(mid=12, destroyTarget=True, hp=100000, atk=0)])
|
||||||
|
battle_of(req)["winType"] = ["3"]
|
||||||
|
self.assertEqual(simulate_quick(req)["outcome"], "win")
|
||||||
|
battle_of(req)["winType"] = ["4"]
|
||||||
|
result = simulate_quick(req)
|
||||||
|
self.assertEqual(result["outcome"], "loss")
|
||||||
|
self.assertGreater(next(u for u in result["units"] if u["source_id"] == "12")["hp"], 0)
|
||||||
|
|
||||||
|
def test_task_1002013_public_configuration_runs_without_changing_inputs(self):
|
||||||
|
req = request(context="task_pass_stage", damage_profile=DESKTOP_DAMAGE_PROFILE,
|
||||||
|
players=[monster(level=20), monster(102, level=20), monster(103, level=20)])
|
||||||
|
req["original_data"]["battle"] = ProgressionData().task_battle("1002013", 1)
|
||||||
|
before = deepcopy(req)
|
||||||
|
result = simulate_quick(req)
|
||||||
|
self.assertTrue(result["supported"], result["reasons"])
|
||||||
|
self.assertIn(result["outcome"], ("win", "loss"))
|
||||||
|
self.assertEqual(req, before)
|
||||||
|
boss = next(u for u in result["units"] if u["species"] == 3012010)
|
||||||
|
nest = next(u for u in result["units"] if u["species"] == 9998002)
|
||||||
|
if boss["joined_ms"] is not None:
|
||||||
|
self.assertIsNotNone(nest["died_ms"])
|
||||||
|
self.assertGreaterEqual(boss["joined_ms"], nest["died_ms"])
|
||||||
|
|
||||||
|
def test_task_1001001_blank_default_mids_preserve_original_stats(self):
|
||||||
|
req = request(context="task_battle")
|
||||||
|
req["original_data"]["battle"] = ProgressionData().task_battle("1001001", 1)
|
||||||
|
self.assertTrue(any(m.get("mid") == "" for t in battle_of(req)["teams"] for m in t["mons"] if m))
|
||||||
|
before = deepcopy(req)
|
||||||
|
detailed, _ = _prepare(req, combat_tables())
|
||||||
|
quick, report = prepare(req)
|
||||||
|
self.assertTrue(report["supported"], report["reasons"])
|
||||||
|
self.assertEqual([u.stats for u in quick.units], [u.stats for u in detailed.units])
|
||||||
|
result = simulate_quick(req)
|
||||||
|
self.assertEqual(result["execution_status"], "completed")
|
||||||
|
self.assertIn(result["outcome"], ("win", "loss"))
|
||||||
|
self.assertEqual(req, before)
|
||||||
|
|
||||||
|
def test_cap_applies_per_hit_after_expected_skill_gain(self):
|
||||||
|
req = request(players=[monster(pAtk=10000)], enemies=[enemy(hp=1000000, atk=0)],
|
||||||
|
seconds=1, damage_profile=DESKTOP_DAMAGE_PROFILE)
|
||||||
|
result = simulate_quick(req)
|
||||||
|
attack_ms = result["units"][0]["stats"]["attack_ms"]
|
||||||
|
self.assertLessEqual(result["team_budgets"]["1"]["peak_expected_dps"], round(50000 * 1000 / attack_ms, 3))
|
||||||
|
self.assertEqual(result["damage_multiplier"], 10)
|
||||||
|
self.assertEqual(result["damage_cap"], 50000)
|
||||||
|
|
||||||
|
def test_anomaly_records_and_trace_bounds_are_preserved(self):
|
||||||
|
req = request(players=[monster(mid=100001, feel=201)], trace_limit=0)
|
||||||
|
report = ExperimentalBattleRuntime().inspect(req)
|
||||||
|
result = simulate_quick(req)
|
||||||
|
for anomaly in report["anomalies"]:
|
||||||
|
self.assertIn(anomaly, result["anomalies"])
|
||||||
|
self.assertEqual(result["battle_data"]["cheatRecords"], result["anomalies"])
|
||||||
|
self.assertFalse(result["experimental_settlement_eligible"])
|
||||||
|
self.assertEqual(result["events"], [])
|
||||||
|
|
||||||
|
def test_cancel_and_technical_timeout_have_no_settlement_data(self):
|
||||||
|
event = threading.Event()
|
||||||
|
event.set()
|
||||||
|
for result in (simulate_quick(request(), cancel_event=event), simulate_quick(request(), timeout=0)):
|
||||||
|
self.assertIn(result["outcome"], ("cancelled", "timeout"))
|
||||||
|
self.assertFalse(result["terminal"])
|
||||||
|
self.assertIsNone(result["battle_data"])
|
||||||
|
|
||||||
|
def test_local_runtime_evidence_retains_model_and_hp_dps(self):
|
||||||
|
result = simulate_quick(request())
|
||||||
|
evidence = BattleOrchestrator.runtime_evidence(result, "experimental")
|
||||||
|
for name in ("model", "simulation_method", "team_budgets", "generated_units", "spawn_bound_reached"):
|
||||||
|
self.assertEqual(evidence[name], result[name])
|
||||||
|
self.assertNotIn(name, result["battle_data"])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,492 @@
|
|||||||
|
"""Interrupted combat recovery; all server calls and worker results are offline fakes."""
|
||||||
|
from copy import deepcopy
|
||||||
|
import json
|
||||||
|
import threading
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import Mock, patch
|
||||||
|
|
||||||
|
from ranch_assistant.battles import BattleJournal, BattleOrchestrator
|
||||||
|
from ranch_assistant.tests.test_battle_orchestration import ExperimentalRuntime, fixture, intent, policy
|
||||||
|
from ranch_assistant.tests.test_core import workspace_temp
|
||||||
|
|
||||||
|
|
||||||
|
class BattleRecoveryTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.folder = self.enterContext(workspace_temp())
|
||||||
|
self.path = self.folder / "journal.json"
|
||||||
|
self.catalog, self.snapshot = fixture()
|
||||||
|
self.snapshot.raw["currentTasks"] = [{"id": 51, "typeId": "1002013", "curStep": 1}]
|
||||||
|
self.runtime = ExperimentalRuntime()
|
||||||
|
self.client = Mock()
|
||||||
|
self.client.call.side_effect = lambda path, payload: {"resCode": 0, "triggerEvent": False, "reward": {}}
|
||||||
|
self.runner = BattleOrchestrator(self.catalog, BattleJournal(self.path), self.runtime)
|
||||||
|
self.action = intent(kind="stage_battle", source_task_id=51, source_task_type_id="1002013", source_step_number=1)
|
||||||
|
self.policy = policy(battle_mode="experimental")
|
||||||
|
|
||||||
|
def paths(self):
|
||||||
|
return [call.args[0] for call in self.client.call.call_args_list]
|
||||||
|
|
||||||
|
def restart(self):
|
||||||
|
self.runner = BattleOrchestrator(self.catalog, BattleJournal(self.path), self.runtime)
|
||||||
|
|
||||||
|
def test_generation_cancel_inside_worker_retries_saved_combat_without_second_entry(self):
|
||||||
|
cancel = threading.Event()
|
||||||
|
original = self.runtime._run
|
||||||
|
captured = []
|
||||||
|
def interrupted(request, *, cancel_event):
|
||||||
|
captured.append(deepcopy(request))
|
||||||
|
cancel_event.set()
|
||||||
|
return {"outcome": "cancelled", "execution_mode": "experimental", "execution_status": "cancelled",
|
||||||
|
"faithful": False, "approximate": True, "terminal": False, "terminal_reason": "worker_cancelled"}
|
||||||
|
self.runtime.run.side_effect = interrupted
|
||||||
|
self.runner.run(self.client, self.snapshot, self.action, self.policy, cancel=cancel)
|
||||||
|
self.assertEqual(self.paths(), ["stageService/stageStart"])
|
||||||
|
self.restart()
|
||||||
|
record = self.runner.pending(self.snapshot)
|
||||||
|
self.assertEqual(self.runner.recovery_status(record)["state"], "retry_local_runtime")
|
||||||
|
self.snapshot.raw["monsters"][0]["level"] = 999
|
||||||
|
retried = []
|
||||||
|
def complete(request, *, cancel_event):
|
||||||
|
retried.append(deepcopy(request))
|
||||||
|
return original(request, cancel_event=cancel_event)
|
||||||
|
self.runtime.run.side_effect = complete
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.assertEqual(retried[0], record["combat_request"])
|
||||||
|
self.assertNotIn("level", retried[0]["roster"]["monsters"][0])
|
||||||
|
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd", "battleService/recordBattleResult"])
|
||||||
|
self.assertIsNone(self.runner.pending(self.snapshot))
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.assertEqual(len(self.paths()), 3)
|
||||||
|
|
||||||
|
def test_cancel_at_completed_result_preserves_it_without_resimulation(self):
|
||||||
|
cancel = threading.Event()
|
||||||
|
def complete(request, *, cancel_event):
|
||||||
|
result = self.runtime._run(request, cancel_event=cancel_event)
|
||||||
|
cancel_event.set()
|
||||||
|
return result
|
||||||
|
self.runtime.run.side_effect = complete
|
||||||
|
self.runner.run(self.client, self.snapshot, self.action, self.policy, cancel=cancel)
|
||||||
|
self.restart()
|
||||||
|
record = self.runner.pending(self.snapshot)
|
||||||
|
self.assertTrue(record["battle_data"]["win"])
|
||||||
|
self.assertTrue(self.runner.resumable_task_clock(record))
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.assertEqual(self.runtime.run.call_count, 1)
|
||||||
|
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd", "battleService/recordBattleResult"])
|
||||||
|
|
||||||
|
def test_cancel_during_wait_resumes_saved_stage_battle_without_new_worker(self):
|
||||||
|
self.runner.clock = lambda: 0
|
||||||
|
cancel = threading.Event()
|
||||||
|
cancel.wait = Mock(side_effect=lambda timeout: cancel.set() or True)
|
||||||
|
self.runtime.run.side_effect = lambda request, cancel_event: self.runtime._run(request, cancel_event=cancel_event) | {
|
||||||
|
"requires_realtime_wait": True, "model_elapsed_ms": 10000}
|
||||||
|
self.runner.run(self.client, self.snapshot, self.action, self.policy, cancel=cancel)
|
||||||
|
self.restart()
|
||||||
|
record = self.runner.pending(self.snapshot)
|
||||||
|
self.assertEqual(self.runner.recovery_status(record)["state"], "resume_result")
|
||||||
|
self.runner.journal.update(record, record["phase"], battle_ready_at=1)
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.assertEqual(self.runtime.run.call_count, 1)
|
||||||
|
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd", "battleService/recordBattleResult"])
|
||||||
|
|
||||||
|
def test_save_combat_request_normalizes_comma_lineup_without_losing_slots_or_inputs(self):
|
||||||
|
from ranch_assistant.battle_quick import simulate_quick
|
||||||
|
from ranch_assistant.tests.test_battle_simulator import monster, request
|
||||||
|
for members in ([100001, 0, 100002], "100001,0,100002"):
|
||||||
|
with self.subTest(members=members):
|
||||||
|
combat = request(players=[monster(mid=100001), monster(mid=100002)], master_level=62,
|
||||||
|
battle_mode="experimental")
|
||||||
|
combat["roster"]["teams"][0]["monsters"] = members
|
||||||
|
combat["roster"]["master"]["sessionKey"] = "credential-canary"
|
||||||
|
combat["roster"]["monsters"][0]["nicName"] = "nickname-canary"
|
||||||
|
combat["roster"]["monsters"][0]["token"] = "credential-canary"
|
||||||
|
before = deepcopy(combat)
|
||||||
|
saved = self.runner.save_combat_request({}, combat)["combat_request"]
|
||||||
|
self.assertEqual(saved["roster"]["teams"][0]["monsters"], [100001, 0, 100002])
|
||||||
|
self.assertEqual([row["id"] for row in saved["roster"]["monsters"]], [100001, 100002])
|
||||||
|
normalized = deepcopy(before)
|
||||||
|
normalized["roster"]["teams"][0]["monsters"] = [100001, 0, 100002]
|
||||||
|
self.assertEqual(simulate_quick(saved), simulate_quick(normalized))
|
||||||
|
self.assertNotIn("canary", json.dumps(saved))
|
||||||
|
self.assertEqual(combat, before)
|
||||||
|
|
||||||
|
def test_combat_input_is_durable_before_start_and_original_profile_survives_timeout(self):
|
||||||
|
self.runner.request_builder = lambda snapshot, action, chosen, request: request | {"damage_profile": "client_v4_x10"}
|
||||||
|
original = self.client.call.side_effect
|
||||||
|
def call(path, payload):
|
||||||
|
if path.endswith("stageStart"):
|
||||||
|
pending = BattleJournal(self.path).pending(self.snapshot)
|
||||||
|
self.assertEqual(pending["combat_request"]["damage_profile"], "client_v4_x10")
|
||||||
|
self.assertFalse(pending["settlement_dispatched"])
|
||||||
|
return original(path, payload)
|
||||||
|
self.client.call.side_effect = call
|
||||||
|
self.runtime.run.side_effect = lambda *args, **kwargs: {"outcome": "timeout", "execution_mode": "experimental",
|
||||||
|
"execution_status": "timed_out", "terminal": False, "terminal_reason": "worker_wall_clock_limit",
|
||||||
|
"faithful": False, "approximate": True, "damage_profile": None}
|
||||||
|
self.runner.run(self.client, self.snapshot, self.action, self.policy)
|
||||||
|
self.restart()
|
||||||
|
self.assertEqual(self.runner.pending(self.snapshot)["combat_request"]["damage_profile"], "client_v4_x10")
|
||||||
|
self.assertEqual(self.runner.recovery_status(self.runner.pending(self.snapshot))["state"], "retry_local_runtime")
|
||||||
|
|
||||||
|
def test_settlement_lost_reply_is_never_replayed_even_with_saved_inputs(self):
|
||||||
|
def call(path, payload):
|
||||||
|
if path.endswith("battleEnd"):
|
||||||
|
raise TimeoutError()
|
||||||
|
return {"resCode": 0, "triggerEvent": False}
|
||||||
|
self.client.call.side_effect = call
|
||||||
|
with self.assertRaises(TimeoutError):
|
||||||
|
self.runner.run(self.client, self.snapshot, self.action, self.policy)
|
||||||
|
self.restart()
|
||||||
|
self.assertEqual(self.runner.recovery_status(self.runner.pending(self.snapshot))["state"], "blocked")
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd"])
|
||||||
|
|
||||||
|
def test_cancel_before_settlement_dispatch_remains_resumable(self):
|
||||||
|
cancel = threading.Event()
|
||||||
|
update = self.runner.journal.update
|
||||||
|
def stop(record, phase, **fields):
|
||||||
|
update(record, phase, **fields)
|
||||||
|
if phase == "settlement_pending":
|
||||||
|
cancel.set()
|
||||||
|
self.runner.journal.update = stop
|
||||||
|
self.runner.run(self.client, self.snapshot, self.action, self.policy, cancel=cancel)
|
||||||
|
self.restart()
|
||||||
|
record = self.runner.pending(self.snapshot)
|
||||||
|
self.assertFalse(record["settlement_dispatched"])
|
||||||
|
self.assertEqual(self.runner.recovery_status(record)["state"], "resume_result")
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd", "battleService/recordBattleResult"])
|
||||||
|
|
||||||
|
def test_preaccept_retry_requires_current_offer_day_and_never_reopens_entry(self):
|
||||||
|
self.action.update(source_task_id=0, source_task_type_id="4001004", source_step_number=0)
|
||||||
|
self.snapshot.raw["history"].update(loopTask={"1": ["4001004"]}, loopTaskTime=self.snapshot.now)
|
||||||
|
self.runtime.run.side_effect = lambda *args, **kwargs: {"outcome": "timeout", "execution_mode": "experimental",
|
||||||
|
"execution_status": "timed_out", "terminal": False, "terminal_reason": "worker_wall_clock_limit",
|
||||||
|
"faithful": False, "approximate": True}
|
||||||
|
self.runner.run(self.client, self.snapshot, self.action, self.policy)
|
||||||
|
self.restart()
|
||||||
|
record = self.runner.pending(self.snapshot)
|
||||||
|
self.assertEqual(self.runner.recovery_status(record, snapshot=self.snapshot)["state"], "retry_local_runtime")
|
||||||
|
self.snapshot.raw["history"]["loopTaskTime"] -= 86400
|
||||||
|
self.assertEqual(self.runner.recovery_status(record, snapshot=self.snapshot)["state"], "abandon_stage")
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.assertEqual(self.runtime.run.call_count, 1)
|
||||||
|
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/recordBattleResult"])
|
||||||
|
self.assertEqual(self.client.call.call_args.args[1]["result"], 0)
|
||||||
|
|
||||||
|
def test_local_retry_is_bounded_then_uses_failure_exit_without_another_worker(self):
|
||||||
|
self.runtime.run.side_effect = lambda *args, **kwargs: {"outcome": "timeout", "execution_mode": "experimental",
|
||||||
|
"execution_status": "timed_out", "terminal": False, "terminal_reason": "worker_wall_clock_limit",
|
||||||
|
"faithful": False, "approximate": True}
|
||||||
|
self.runner.run(self.client, self.snapshot, self.action, self.policy)
|
||||||
|
self.restart()
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.restart()
|
||||||
|
self.assertEqual(self.runner.pending(self.snapshot)["runtime_recovery_attempts"], 1)
|
||||||
|
self.assertEqual(self.runner.recovery_status(self.runner.pending(self.snapshot))["state"], "abandon_stage")
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.assertEqual(self.runtime.run.call_count, 2)
|
||||||
|
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/recordBattleResult"])
|
||||||
|
|
||||||
|
def test_stage_battle_with_confirmed_settlement_restart_only_finishes_record(self):
|
||||||
|
with patch.object(self.runner, "_record", side_effect=SystemExit("crash after durable settlement reply")):
|
||||||
|
with self.assertRaises(SystemExit):
|
||||||
|
self.runner.run(self.client, self.snapshot, self.action, self.policy)
|
||||||
|
self.restart()
|
||||||
|
self.assertEqual(self.runner.recovery_status(self.runner.pending(self.snapshot))["state"], "resume_result")
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.assertEqual(self.runtime.run.call_count, 1)
|
||||||
|
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd", "battleService/recordBattleResult"])
|
||||||
|
|
||||||
|
def test_stop_during_recovery_settlement_keeps_ack_and_resumes_only_optional_record(self):
|
||||||
|
initial_cancel = threading.Event()
|
||||||
|
def complete(request, *, cancel_event):
|
||||||
|
result = self.runtime._run(request, cancel_event=cancel_event)
|
||||||
|
cancel_event.set()
|
||||||
|
return result
|
||||||
|
self.runtime.run.side_effect = complete
|
||||||
|
self.runner.run(self.client, self.snapshot, self.action, self.policy, cancel=initial_cancel)
|
||||||
|
self.restart()
|
||||||
|
self.assertEqual(self.paths(), ["stageService/stageStart"])
|
||||||
|
recovery_cancel = threading.Event()
|
||||||
|
def settlement_ack_after_stop(path, payload):
|
||||||
|
if path == "battleService/battleEnd":
|
||||||
|
recovery_cancel.set()
|
||||||
|
return {"resCode": 0, "reward": {"money": 11}}
|
||||||
|
self.client.call.side_effect = settlement_ack_after_stop
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=recovery_cancel)
|
||||||
|
self.assertTrue(recovery_cancel.is_set())
|
||||||
|
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd"])
|
||||||
|
self.restart()
|
||||||
|
record = self.runner.pending(self.snapshot)
|
||||||
|
self.assertEqual(record["phase"], "settlement_acknowledged")
|
||||||
|
self.assertTrue(record["settlement_confirmed"])
|
||||||
|
self.assertFalse(record["record_dispatched"])
|
||||||
|
self.assertIsNot(record.get("record_confirmed"), True)
|
||||||
|
self.assertEqual(record["response"], {"resCode": 0, "reward": {"money": 11}})
|
||||||
|
self.assertEqual(self.runner.recovery_status(record)["state"], "resume_result")
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=recovery_cancel)
|
||||||
|
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd"])
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd", "battleService/recordBattleResult"])
|
||||||
|
self.assertIsNone(self.runner.pending(self.snapshot))
|
||||||
|
self.assertEqual(self.runtime.run.call_count, 1)
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.assertEqual(len(self.paths()), 3)
|
||||||
|
|
||||||
|
def legacy_timeout(self, **changes):
|
||||||
|
record = self.runner.journal.begin(self.snapshot, self.action)
|
||||||
|
self.runner.journal.update(record, "unknown", path="stageService/stageStart", start_path="stageService/stageStart",
|
||||||
|
start_response={"resCode": 0, "stageEvent": None, "triggerEvent": False},
|
||||||
|
battle_mode="experimental", execution_mode="experimental", execution_status="timed_out", terminal=False,
|
||||||
|
terminal_reason="worker_wall_clock_limit", message="战斗已取消、超时或结果不确定,等待核对")
|
||||||
|
self.runner.journal.update(record, "unknown", **changes)
|
||||||
|
return record
|
||||||
|
|
||||||
|
def test_legacy_worker_timeout_uses_original_failure_exit_once(self):
|
||||||
|
self.legacy_timeout()
|
||||||
|
before = deepcopy(self.snapshot.raw)
|
||||||
|
self.restart()
|
||||||
|
status = self.runner.recovery_status(self.runner.pending(self.snapshot), snapshot=self.snapshot)
|
||||||
|
self.assertEqual(status["state"], "abandon_stage")
|
||||||
|
self.assertIn("原始战斗输入", status["message"])
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.assertEqual(self.paths(), ["battleService/recordBattleResult"])
|
||||||
|
self.assertEqual(self.client.call.call_args.args[1], {"stageId": "0101", "cityId": "1", "result": 0})
|
||||||
|
self.assertIsNone(self.runner.pending(self.snapshot))
|
||||||
|
done = self.runner.journal.records(self.snapshot)[0]
|
||||||
|
self.assertEqual(done["outcome"], "abandoned")
|
||||||
|
self.assertTrue(done["record_confirmed"])
|
||||||
|
self.assertNotIn("battle_data", done)
|
||||||
|
self.assertEqual(self.snapshot.raw, before)
|
||||||
|
self.runtime.run.assert_not_called()
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.assertEqual(len(self.paths()), 1)
|
||||||
|
|
||||||
|
def test_lost_failure_response_stays_pending_and_is_never_replayed(self):
|
||||||
|
self.legacy_timeout()
|
||||||
|
self.client.call.side_effect = TimeoutError("lost failure acknowledgement")
|
||||||
|
with self.assertRaises(TimeoutError):
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.restart()
|
||||||
|
record = self.runner.pending(self.snapshot)
|
||||||
|
self.assertEqual(record["phase"], "record_unknown")
|
||||||
|
self.assertTrue(record["record_dispatched"])
|
||||||
|
self.assertEqual(self.runner.recovery_status(record)["state"], "blocked")
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.assertEqual(self.paths(), ["battleService/recordBattleResult"])
|
||||||
|
|
||||||
|
def test_real_preaccept_source_zero_legacy_timeout_exits_without_task_or_offer(self):
|
||||||
|
self.action.update(stage_id="0102", task_type_id="", source_task_id=0,
|
||||||
|
source_task_type_id="4001004", source_step_number=0, stage_category=None)
|
||||||
|
self.legacy_timeout()
|
||||||
|
before = deepcopy(self.snapshot.raw)
|
||||||
|
self.restart()
|
||||||
|
status = self.runner.recovery_status(self.runner.pending(self.snapshot), snapshot=self.snapshot.raw)
|
||||||
|
self.assertEqual(status["state"], "abandon_stage")
|
||||||
|
self.assertIn("旧记录缺少原始战斗输入", status["message"])
|
||||||
|
self.assertNotIn("来源委托已变化", status["message"])
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.assertEqual(self.paths(), ["battleService/recordBattleResult"])
|
||||||
|
self.assertEqual(self.client.call.call_args.args[1], {"stageId": "0102", "cityId": "1", "result": 0})
|
||||||
|
self.assertIsNone(self.runner.pending(self.snapshot))
|
||||||
|
self.assertEqual(self.snapshot.raw, before)
|
||||||
|
self.assertEqual(self.runner.journal.role(self.snapshot)["losses"], 0)
|
||||||
|
self.assertEqual(self.runner.journal.records(self.snapshot)[0]["outcome"], "abandoned")
|
||||||
|
|
||||||
|
def test_failure_acknowledged_before_crash_finishes_locally_without_second_record(self):
|
||||||
|
self.legacy_timeout()
|
||||||
|
finish = self.runner.journal.finish
|
||||||
|
self.runner.journal.finish = Mock(side_effect=SystemExit("crash after durable failure reply"))
|
||||||
|
with self.assertRaises(SystemExit):
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.runner.journal.finish = finish
|
||||||
|
self.restart()
|
||||||
|
self.assertEqual(self.runner.recovery_status(self.runner.pending(self.snapshot))["state"], "finish_abandonment")
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.assertIsNone(self.runner.pending(self.snapshot))
|
||||||
|
self.assertEqual(self.paths(), ["battleService/recordBattleResult"])
|
||||||
|
|
||||||
|
def test_unconfirmed_start_or_changed_source_or_settlement_attempt_blocks_failure_exit(self):
|
||||||
|
self.legacy_timeout()
|
||||||
|
for changes in ({"start_response": None}, {"settlement_dispatched": True},
|
||||||
|
{"path": "battleService/battleEnd"}, {"source_task_id": 999},
|
||||||
|
{"terminal_reason": "unclassified_failure"}):
|
||||||
|
with self.subTest(changes=changes):
|
||||||
|
original = deepcopy(self.runner.pending(self.snapshot))
|
||||||
|
self.runner.journal.update(self.runner.pending(self.snapshot), "unknown", **changes)
|
||||||
|
status = self.runner.recovery_status(self.runner.pending(self.snapshot), snapshot=self.snapshot)
|
||||||
|
self.assertEqual(status["state"], "blocked")
|
||||||
|
self.runner.resume_task_clock(self.client, self.snapshot, self.action, self.policy, cancel=threading.Event())
|
||||||
|
self.runner.journal.role(self.snapshot)["records"][-1] = original
|
||||||
|
self.runner.journal.save()
|
||||||
|
self.assertIsNotNone(self.runner.pending(self.snapshot))
|
||||||
|
self.client.call.assert_not_called()
|
||||||
|
self.runtime.run.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
class EngineBattleRecoveryTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
from ranch_assistant.engine import Engine, demo_snapshot
|
||||||
|
from ranch_assistant.game_data import ProgressionData
|
||||||
|
from ranch_assistant.model import Catalog, Policy, Snapshot
|
||||||
|
from ranch_assistant.progression import ProgressionPolicy
|
||||||
|
self.folder = self.enterContext(workspace_temp())
|
||||||
|
self.catalog = Catalog()
|
||||||
|
self.raw = deepcopy(demo_snapshot(self.catalog).raw)
|
||||||
|
self.raw["currentTasks"] = [{"id": 71, "typeId": "1002013", "curStep": 1}]
|
||||||
|
self.client = Mock()
|
||||||
|
self.client.snapshot.side_effect = lambda: Snapshot(deepcopy(self.raw))
|
||||||
|
self.client.call.return_value = {"resCode": 0, "triggerEvent": False}
|
||||||
|
self.engine = Engine(self.catalog, self.client, self.folder / "purchase.json",
|
||||||
|
game_data=ProgressionData({"task_info": {}, "stage_info": {}, "game_setting": {}}),
|
||||||
|
experimental_runtime=ExperimentalRuntime())
|
||||||
|
self.engine.policy = Policy(enabled=False, gift_enabled=False, fill=False)
|
||||||
|
self.engine.progression_policy = ProgressionPolicy(enabled=True, battle_mode="experimental")
|
||||||
|
self.engine.snapshot = Snapshot(deepcopy(self.raw))
|
||||||
|
self.engine.master_sync.settle = Mock()
|
||||||
|
self.action = intent(kind="stage_battle", stage_id="0102", task_type_id="", source_task_id=0,
|
||||||
|
source_task_type_id="4001004", source_step_number=0)
|
||||||
|
self.record = self.engine.battle_journal.begin(self.engine.snapshot, self.action)
|
||||||
|
self.engine.battle_journal.update(self.record, "unknown", path="stageService/stageStart", start_path="stageService/stageStart",
|
||||||
|
start_response={"resCode": 0, "stageEvent": None, "triggerEvent": False},
|
||||||
|
battle_mode="experimental", execution_mode="experimental", execution_status="timed_out", terminal=False,
|
||||||
|
terminal_reason="worker_wall_clock_limit")
|
||||||
|
self.engine.auto = False
|
||||||
|
|
||||||
|
def test_disabled_cold_commission_origin_blocks_until_quest_policy_is_enabled(self):
|
||||||
|
self.engine.game_data = None
|
||||||
|
self.engine.quest_policy.enabled = False
|
||||||
|
self.engine.daily_policy.enabled = True
|
||||||
|
before = self.engine.battle_journal.path.read_bytes()
|
||||||
|
record = deepcopy(self.record)
|
||||||
|
status = self.engine.pending_battle_recovery()
|
||||||
|
self.assertEqual(status["state"], "blocked_policy")
|
||||||
|
self.assertFalse(status["resumable"])
|
||||||
|
self.assertIn("等待启用自动委托来源策略", status["message"])
|
||||||
|
self.assertEqual(self.engine.battle_journal.path.read_bytes(), before)
|
||||||
|
self.engine.poll(resume_pending=True)
|
||||||
|
self.assertEqual(self.engine.battle_journal.pending(self.engine.snapshot), record)
|
||||||
|
self.client.call.assert_not_called()
|
||||||
|
self.assertFalse(self.engine.quest_policy.enabled)
|
||||||
|
self.assertTrue(self.engine.daily_policy.enabled)
|
||||||
|
self.engine.quest_policy.enabled = True
|
||||||
|
self.assertTrue(self.engine.pending_battle_recovery()["resumable"])
|
||||||
|
self.engine.poll(resume_pending=True)
|
||||||
|
self.assertIsNone(self.engine.battle_journal.pending(self.engine.snapshot))
|
||||||
|
self.assertEqual(self.client.call.call_count, 1)
|
||||||
|
self.assertEqual(self.client.call.call_args.args[0], "battleService/recordBattleResult")
|
||||||
|
|
||||||
|
def test_enabled_cold_commission_origin_does_not_require_mainline_policy(self):
|
||||||
|
self.engine.game_data = None
|
||||||
|
self.engine.progression_policy.enabled = False
|
||||||
|
self.engine.quest_policy.enabled = True
|
||||||
|
status = self.engine.pending_battle_recovery()
|
||||||
|
self.assertEqual(status["state"], "abandon_stage")
|
||||||
|
self.assertTrue(status["resumable"])
|
||||||
|
self.assertIsNotNone(self.engine.game_data)
|
||||||
|
self.assertTrue(self.engine._is_commission(self.record))
|
||||||
|
self.assertFalse(self.engine.progression_policy.enabled)
|
||||||
|
self.client.call.assert_not_called()
|
||||||
|
|
||||||
|
def test_disabled_map_and_mainline_origins_name_their_policies(self):
|
||||||
|
self.engine.progression_policy.enabled = False
|
||||||
|
self.engine.sweep_policy.enabled = False
|
||||||
|
for kind, source_id, source_type, source_step, label in (
|
||||||
|
("map_battle", 0, "", 0, "自动扫荡"),
|
||||||
|
("stage_battle", 71, "1002013", 1, "自动主线")):
|
||||||
|
with self.subTest(kind=kind):
|
||||||
|
self.engine.game_data = None
|
||||||
|
self.engine.battle_journal.update(self.record, "waiting_for_battle_clock", kind=kind,
|
||||||
|
source_task_id=source_id, source_task_type_id=source_type, source_step_number=source_step,
|
||||||
|
battle_data={"win": True}, execution_status="completed", terminal=True,
|
||||||
|
experimental_settlement_eligible=True, approximate=True, faithful=False, resume_clock_ready=True)
|
||||||
|
self.assertTrue(self.engine.battles.recovery_status(self.record, snapshot=self.engine.snapshot)["resumable"])
|
||||||
|
status = self.engine.pending_battle_recovery()
|
||||||
|
self.assertEqual(status["state"], "blocked_policy")
|
||||||
|
self.assertFalse(status["resumable"])
|
||||||
|
self.assertIn("等待启用" + label + "来源策略", status["message"])
|
||||||
|
self.client.call.assert_not_called()
|
||||||
|
|
||||||
|
def test_web_explicit_running_resumes_preaccept_failure_while_auto_stays_false(self):
|
||||||
|
self.engine.cancel_progression()
|
||||||
|
self.engine.poll(resume_pending=False)
|
||||||
|
self.client.call.assert_not_called()
|
||||||
|
self.assertTrue(self.engine.pending_battle_recovery()["resumable"])
|
||||||
|
self.engine.poll(resume_pending=True)
|
||||||
|
self.assertFalse(self.engine.auto)
|
||||||
|
self.assertIsNone(self.engine.battle_journal.pending(self.engine.snapshot))
|
||||||
|
self.assertEqual(self.client.call.call_count, 1)
|
||||||
|
self.assertEqual(self.client.call.call_args.args, ("battleService/recordBattleResult", {"stageId": "0102", "cityId": "1", "result": 0}))
|
||||||
|
self.assertEqual(self.engine.snapshot.raw["currentTasks"], self.raw["currentTasks"])
|
||||||
|
self.assertFalse(self.engine._progression_pending())
|
||||||
|
self.engine._require_no_battle() # Other selected strategies are no longer blocked.
|
||||||
|
self.engine.poll(resume_pending=True)
|
||||||
|
self.assertEqual(self.client.call.call_count, 1)
|
||||||
|
|
||||||
|
def test_new_stop_during_snapshot_read_wins_over_old_running_argument(self):
|
||||||
|
read = self.client.snapshot.side_effect
|
||||||
|
def read_then_stop():
|
||||||
|
result = read()
|
||||||
|
self.engine.cancel_progression()
|
||||||
|
return result
|
||||||
|
self.client.snapshot.side_effect = read_then_stop
|
||||||
|
self.engine.poll(resume_pending=True)
|
||||||
|
self.assertTrue(self.engine._progression_cancel.is_set())
|
||||||
|
self.assertIsNotNone(self.engine.battle_journal.pending(self.engine.snapshot))
|
||||||
|
self.client.call.assert_not_called()
|
||||||
|
self.client.snapshot.side_effect = read
|
||||||
|
self.engine.poll(resume_pending=True)
|
||||||
|
self.assertEqual(self.client.call.call_count, 1)
|
||||||
|
|
||||||
|
def test_guard_is_read_only_and_unknown_settlement_is_blocked(self):
|
||||||
|
self.engine.battle_journal.update(self.record, "unknown", path="battleService/battleEnd", settlement_dispatched=True)
|
||||||
|
before = self.engine.battle_journal.path.read_bytes()
|
||||||
|
status = self.engine.pending_battle_recovery()
|
||||||
|
self.assertEqual(status["state"], "blocked")
|
||||||
|
self.assertFalse(status["resumable"])
|
||||||
|
self.assertEqual(self.engine.battle_journal.path.read_bytes(), before)
|
||||||
|
record = deepcopy(self.engine.battle_journal.pending(self.engine.snapshot))
|
||||||
|
self.engine.poll(resume_pending=True)
|
||||||
|
self.assertEqual(self.engine.battle_journal.pending(self.engine.snapshot), record)
|
||||||
|
self.client.call.assert_not_called()
|
||||||
|
self.assertIsNotNone(self.engine.battle_journal.pending(self.engine.snapshot))
|
||||||
|
|
||||||
|
def test_engine_generation_cancel_in_worker_resumes_single_started_entry(self):
|
||||||
|
from ranch_assistant.model import Snapshot
|
||||||
|
from ranch_assistant.progression import ProgressionIntent
|
||||||
|
self.engine.battle_journal.finish(self.engine.snapshot, self.record, "cancelled")
|
||||||
|
self.raw["teams"] = [{"teamName": "teamA", "teamType": "battleTeam", "monsters": [900]}]
|
||||||
|
self.raw["history"]["unlockStage"] = {"0102": [1]}
|
||||||
|
self.raw["history"].update(loopTask={"1": ["4001004"]}, loopTaskTime=self.engine.snapshot.now)
|
||||||
|
self.engine.snapshot = Snapshot(deepcopy(self.raw))
|
||||||
|
self.engine.battles.catalog = fixture()[0]
|
||||||
|
self.engine.game_data.stages["0102"] = {"level": {"1": {"battle": {"fixture": True}}}}
|
||||||
|
self.engine._battle_catalog_ready = True
|
||||||
|
self.engine._ensure_progression()
|
||||||
|
scope, _ = self.engine.progression_planner._account(self.engine.snapshot)
|
||||||
|
action = ProgressionIntent(kind="stage_battle", description="offline preaccept farming", stage_id="0102",
|
||||||
|
difficulty=1, battle_kind="ordinary_stage", path="stageService/stageStart", team="teamA",
|
||||||
|
battle_mode="experimental", account_key=scope, token="offline-fixture", source_task_type_id="4001004")
|
||||||
|
self.engine.progression_planner._issued[action.token] = action.to_dict()
|
||||||
|
self.engine._select_battle_runtime("experimental")
|
||||||
|
runtime = self.engine.battles.runtime
|
||||||
|
def interrupted(request, *, cancel_event):
|
||||||
|
self.engine.cancel_progression()
|
||||||
|
return {"outcome": "cancelled", "execution_mode": "experimental", "execution_status": "cancelled",
|
||||||
|
"faithful": False, "approximate": True, "terminal": False, "terminal_reason": "worker_cancelled"}
|
||||||
|
runtime.run.side_effect = interrupted
|
||||||
|
self.engine.battles.run(self.client, self.engine.snapshot, action,
|
||||||
|
self.engine.progression_policy, cancel=self.engine._progression_cancel)
|
||||||
|
self.assertEqual(self.engine._progression_cancel_generation, 1)
|
||||||
|
self.assertEqual(self.engine.pending_battle_recovery()["state"], "retry_local_runtime")
|
||||||
|
runtime.run.side_effect = runtime._run
|
||||||
|
self.engine.poll(resume_pending=True)
|
||||||
|
self.assertIsNone(self.engine.battle_journal.pending(self.engine.snapshot))
|
||||||
|
self.assertEqual([call.args[0] for call in self.client.call.call_args_list],
|
||||||
|
["stageService/stageStart", "battleService/battleEnd", "battleService/recordBattleResult"])
|
||||||
|
self.assertEqual(runtime.run.call_count, 2)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -415,8 +415,9 @@ class SimulatorTests(unittest.TestCase):
|
|||||||
req = request(players=[monster(species=1001020)]) # actual skill 10
|
req = request(players=[monster(species=1001020)]) # actual skill 10
|
||||||
report = ExperimentalBattleRuntime().inspect(req)
|
report = ExperimentalBattleRuntime().inspect(req)
|
||||||
self.assertTrue(report["supported"])
|
self.assertTrue(report["supported"])
|
||||||
self.assertTrue(any(d["code"] == "unsupported_skill" and "10" in d["message"] for d in report["diagnostics"]))
|
self.assertTrue(any(d["code"] == "aggregate_skill" and "10" in d["message"] for d in report["diagnostics"]))
|
||||||
self.assertTrue(any("Skill 10" in x for x in report["ignored_mechanics"]))
|
self.assertTrue(any("bounded expected" in x for x in report["assumptions"]))
|
||||||
|
self.assertTrue(any(d["code"] == "unsupported_skill" for d in simulate(req)["diagnostics"]))
|
||||||
|
|
||||||
def test_controllers_triggers_and_non_elimination_are_rejected(self):
|
def test_controllers_triggers_and_non_elimination_are_rejected(self):
|
||||||
for key, value in (("controller", [{"type": "monMaker"}]),
|
for key, value in (("controller", [{"type": "monMaker"}]),
|
||||||
@@ -476,11 +477,13 @@ class WorkerTests(unittest.TestCase):
|
|||||||
self.assertEqual(result["outcome"], "win")
|
self.assertEqual(result["outcome"], "win")
|
||||||
self.assertEqual(result["battle_data"]["battlePosition"], req["battle_position"])
|
self.assertEqual(result["battle_data"]["battlePosition"], req["battle_position"])
|
||||||
|
|
||||||
def test_fixed_module_subprocess_equals_direct_model(self):
|
def test_fixed_module_subprocess_uses_quick_model_by_default(self):
|
||||||
|
from ranch_assistant.battle_quick import simulate_quick
|
||||||
req = request()
|
req = request()
|
||||||
with patch("socket.socket", side_effect=AssertionError("No network")):
|
with patch("socket.socket", side_effect=AssertionError("No network")):
|
||||||
result = ExperimentalBattleRuntime().run(req)
|
result = ExperimentalBattleRuntime().run(req)
|
||||||
self.assertEqual(result, simulate(req))
|
self.assertEqual(result, simulate_quick(req))
|
||||||
|
self.assertEqual(result["simulation_method"], "aggregate_hp_dps")
|
||||||
|
|
||||||
def test_worker_entrypoint_does_not_import_gui_or_production_engine(self):
|
def test_worker_entrypoint_does_not_import_gui_or_production_engine(self):
|
||||||
completed = subprocess.run([sys.executable, "-c",
|
completed = subprocess.run([sys.executable, "-c",
|
||||||
|
|||||||
@@ -0,0 +1,146 @@
|
|||||||
|
"""Bounded, offline regressions for the fixed battle worker's stdin transport."""
|
||||||
|
import json
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from ranch_assistant import battle_simulator as simulator
|
||||||
|
from ranch_assistant.battle_quick import simulate_quick
|
||||||
|
from ranch_assistant.tests.test_battle_simulator import request
|
||||||
|
|
||||||
|
|
||||||
|
# Delay the real worker's first read past several parent polling quanta.
|
||||||
|
SLOW_WORKER = """
|
||||||
|
import runpy, sys, time
|
||||||
|
time.sleep(.2)
|
||||||
|
sys.argv = ['ranch_assistant.battle_simulator', '--worker']
|
||||||
|
runpy.run_module('ranch_assistant.battle_simulator', run_name='__main__')
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class PartialFirstWrite:
|
||||||
|
"""Reproduce POSIX's partial-write/None-retry behavior on every platform.
|
||||||
|
|
||||||
|
The child and its pipes are real. A tiny first write followed by a timeout
|
||||||
|
leaves stdin open; a retry without input never resumes that write. No
|
||||||
|
background writer is needed, so killed children cannot leave writer threads.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, process):
|
||||||
|
self.process = process
|
||||||
|
self.partial_write = False
|
||||||
|
self.timeouts = 0
|
||||||
|
|
||||||
|
def __getattr__(self, name):
|
||||||
|
return getattr(self.process, name)
|
||||||
|
|
||||||
|
def communicate(self, input=None, timeout=None):
|
||||||
|
if self.process.stdin is not None and self.process.poll() is None:
|
||||||
|
if input is not None:
|
||||||
|
self.process.stdin.write(input[:512])
|
||||||
|
self.process.stdin.flush()
|
||||||
|
self.partial_write = True
|
||||||
|
try:
|
||||||
|
self.process.wait(timeout=timeout)
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
self.timeouts += 1
|
||||||
|
raise
|
||||||
|
try:
|
||||||
|
return self.process.communicate(input=input, timeout=timeout)
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
self.timeouts += 1
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
class BattleWorkerTransportTests(unittest.TestCase):
|
||||||
|
def large_request(self):
|
||||||
|
payload = request()
|
||||||
|
# A valid snapshot field retained by the combat-only serializer.
|
||||||
|
payload['roster']['monsters'][0]['nicName'] = 'x' * (128 * 1024)
|
||||||
|
return payload
|
||||||
|
|
||||||
|
def launch_slow_worker(self, *, partial=False, cancel_event=None):
|
||||||
|
real_popen = subprocess.Popen
|
||||||
|
launched = []
|
||||||
|
streams = []
|
||||||
|
|
||||||
|
def launch(command, **kwargs):
|
||||||
|
self.assertEqual(command, [sys.executable, '-m',
|
||||||
|
'ranch_assistant.battle_simulator', '--worker'])
|
||||||
|
self.assertNotIn('shell', kwargs)
|
||||||
|
stream = kwargs['stdin']
|
||||||
|
if stream != subprocess.PIPE:
|
||||||
|
streams.append(stream)
|
||||||
|
wire = stream.read()
|
||||||
|
self.assertGreater(len(wire), 128 * 1024)
|
||||||
|
self.assertLessEqual(len(wire), simulator.MAX_WIRE_BYTES)
|
||||||
|
self.assertNotIn(b'account-secret', wire)
|
||||||
|
self.assertEqual(json.loads(wire)['request']['roster']['monsters'][0]['nicName'],
|
||||||
|
'x' * (128 * 1024))
|
||||||
|
stream.seek(0)
|
||||||
|
process = real_popen([sys.executable, '-c', SLOW_WORKER], **kwargs)
|
||||||
|
observed = PartialFirstWrite(process) if partial else process
|
||||||
|
launched.append(observed)
|
||||||
|
if cancel_event is not None:
|
||||||
|
cancel_event.set()
|
||||||
|
return observed
|
||||||
|
|
||||||
|
return launch, launched, streams
|
||||||
|
|
||||||
|
def assert_cleaned_up(self, processes, streams):
|
||||||
|
self.assertEqual(len(processes), 1)
|
||||||
|
self.assertIsNotNone(processes[0].poll())
|
||||||
|
self.assertTrue(processes[0].stdout.closed)
|
||||||
|
self.assertTrue(processes[0].stderr.closed)
|
||||||
|
for stream in streams:
|
||||||
|
self.assertTrue(stream.closed)
|
||||||
|
|
||||||
|
def test_partial_first_quantum_delivers_one_complete_request(self):
|
||||||
|
payload = self.large_request()
|
||||||
|
expected = simulate_quick(payload)
|
||||||
|
self.assertIn(expected['outcome'], ('win', 'loss'))
|
||||||
|
launch, processes, streams = self.launch_slow_worker(partial=True)
|
||||||
|
with patch.object(simulator.subprocess, 'Popen', side_effect=launch):
|
||||||
|
actual = simulator.ExperimentalBattleRuntime().run(payload, timeout=1.5)
|
||||||
|
self.assert_cleaned_up(processes, streams)
|
||||||
|
self.assertGreaterEqual(processes[0].timeouts, 2)
|
||||||
|
self.assertEqual(actual, expected)
|
||||||
|
|
||||||
|
def test_native_slow_reader_preserves_result_and_omits_credentials(self):
|
||||||
|
payload = self.large_request()
|
||||||
|
expected = simulate_quick(payload)
|
||||||
|
payload['credentials'] = 'account-secret'
|
||||||
|
payload['roster']['master']['token'] = 'account-secret'
|
||||||
|
launch, processes, streams = self.launch_slow_worker()
|
||||||
|
with patch.object(simulator.subprocess, 'Popen', side_effect=launch):
|
||||||
|
actual = simulator.ExperimentalBattleRuntime().run(payload, timeout=1.5)
|
||||||
|
self.assert_cleaned_up(processes, streams)
|
||||||
|
self.assertEqual(actual, expected)
|
||||||
|
|
||||||
|
def test_cancel_and_deadline_reap_slow_reader_and_close_input(self):
|
||||||
|
for cancelled in (False, True):
|
||||||
|
with self.subTest(cancelled=cancelled):
|
||||||
|
event = threading.Event()
|
||||||
|
launch, processes, streams = self.launch_slow_worker(
|
||||||
|
cancel_event=event if cancelled else None)
|
||||||
|
with patch.object(simulator.subprocess, 'Popen', side_effect=launch):
|
||||||
|
result = simulator.ExperimentalBattleRuntime().run(
|
||||||
|
self.large_request(), cancel_event=event,
|
||||||
|
timeout=1.5 if cancelled else .1)
|
||||||
|
self.assertEqual(result['outcome'], 'cancelled' if cancelled else 'timeout')
|
||||||
|
self.assertFalse(result['terminal'])
|
||||||
|
self.assertIsNone(result['battle_data'])
|
||||||
|
self.assert_cleaned_up(processes, streams)
|
||||||
|
|
||||||
|
def test_oversize_input_never_launches_worker(self):
|
||||||
|
with patch.object(simulator, 'MAX_WIRE_BYTES', 1024), \
|
||||||
|
patch.object(simulator.subprocess, 'Popen') as launch:
|
||||||
|
result = simulator.ExperimentalBattleRuntime().run(self.large_request())
|
||||||
|
launch.assert_not_called()
|
||||||
|
self.assertEqual(result['terminal_reason'], 'request_exceeds_worker_input_limit')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,405 @@
|
|||||||
|
"""Offline commission observability; every game transport is a fake."""
|
||||||
|
from copy import deepcopy
|
||||||
|
from datetime import datetime
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import Mock, patch
|
||||||
|
|
||||||
|
from ranch_assistant.commission_history import CommissionHistory, beijing_day
|
||||||
|
from ranch_assistant.engine import Engine
|
||||||
|
from ranch_assistant.game_data import ProgressionData
|
||||||
|
from ranch_assistant.model import Catalog, Snapshot
|
||||||
|
from ranch_assistant.quests import CN, QuestPolicy, TaskPlanner
|
||||||
|
from ranch_assistant.progression import ProgressionPlanner
|
||||||
|
from ranch_assistant.tests.test_progression import config, snapshot, step, task
|
||||||
|
|
||||||
|
|
||||||
|
class CommissionHistoryTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.folder = Path(self.enterContext(tempfile.TemporaryDirectory(prefix="commission-offline-")))
|
||||||
|
self.catalog = Catalog()
|
||||||
|
self.tasks = {str(400 + number): task(str(400 + number), type=4,
|
||||||
|
name=name, reward={"ke": reward}) for number, (name, reward) in
|
||||||
|
enumerate((("低奖励委托", 10), ("中等奖励委托", 15), ("高奖励委托", 20)))}
|
||||||
|
self.data = ProgressionData(config(self.tasks))
|
||||||
|
self.snapshot = snapshot(currentTasks=[])
|
||||||
|
self.snapshot.raw["history"].update(loopTaskTime=self.snapshot.now, loopTaskNum=6,
|
||||||
|
loopTask={"1": ["400", "401"], "2": ["402"]}, unlockCity={"1": True, "2": True})
|
||||||
|
self.client = Mock()
|
||||||
|
self.client.call.side_effect = AssertionError("unexpected offline game operation")
|
||||||
|
self.client.snapshot.side_effect = lambda: Snapshot(deepcopy(self.snapshot.raw), self.snapshot.now)
|
||||||
|
|
||||||
|
def engine(self):
|
||||||
|
engine = Engine(self.catalog, self.client, self.folder / "purchase.json", game_data=self.data)
|
||||||
|
engine.snapshot = self.snapshot
|
||||||
|
engine.quest_policy = QuestPolicy(enabled=True)
|
||||||
|
return engine
|
||||||
|
|
||||||
|
def record(self, engine, *, kind="progression_complete", path="taskService/taskComplete",
|
||||||
|
task_id=51, type_id="402", response=None, outcome="task"):
|
||||||
|
record = engine.battle_journal.begin(engine.snapshot, {"kind": kind, "description": "旧任务操作",
|
||||||
|
"path": path, "payload": {}, "task_id": task_id, "task_type_id": type_id, "step_number": 1})
|
||||||
|
if response is not None:
|
||||||
|
engine.battle_journal.update(record, "acknowledged", response=response, response_confirmed=True)
|
||||||
|
if outcome is not None:
|
||||||
|
engine.battle_journal.finish(engine.snapshot, record, outcome)
|
||||||
|
return record
|
||||||
|
|
||||||
|
def receipt(self, attempt, *, kind="complete", task_id=51, type_id="402", when=None, role=1,
|
||||||
|
response=None, outcome="task", phase="done", **extra):
|
||||||
|
when = self.snapshot.now if when is None else when
|
||||||
|
paths = {"accept": "taskService/taskLoopReceive", "complete": "taskService/taskComplete",
|
||||||
|
"step": "taskService/taskCompleteStep", "navigate": "", "dialogue": "", "farm": "battleService/battleEnd"}
|
||||||
|
originals = {"accept": "progression_loop_accept", "complete": "progression_complete",
|
||||||
|
"step": "progression_step", "navigate": "progression_navigate", "dialogue": "progression_dialogue", "farm": "map_battle"}
|
||||||
|
return {"attempt_id": attempt, "role_id": str(role), "kind": originals[kind], "path": paths[kind],
|
||||||
|
"task_type_id": type_id, "task_id": task_id, "step_number": 1, "phase": phase, "outcome": outcome,
|
||||||
|
"timestamp": when, "finished_at": when if phase == "done" else None, "updated_at": when,
|
||||||
|
"response": {"resCode": 0} if response is None else response,
|
||||||
|
"response_confirmed": phase == "done" and outcome == "task", "payload": {},
|
||||||
|
"baseline": {"tasks": []}, **extra}
|
||||||
|
|
||||||
|
def ledger(self, records, *, now=None, role=1, **options):
|
||||||
|
ledger = CommissionHistory(self.folder / "history.json", clock=lambda: now or self.snapshot.now, **options)
|
||||||
|
ledger.ingest(role, records, lambda key: self.tasks.get(key), self.snapshot)
|
||||||
|
return ledger
|
||||||
|
|
||||||
|
def test_early_battle_return_never_relogs_previous_commission_claim(self):
|
||||||
|
engine = self.engine()
|
||||||
|
self.record(engine, response={"resCode": 0, "reward": {"ke": 20}})
|
||||||
|
engine.battles.run = Mock(return_value="体力不足,未开始战斗")
|
||||||
|
intent = {"kind": "progression_battle", "task_type_id": "402", "task_id": 52,
|
||||||
|
"step_number": 1, "description": "下一份委托战斗"}
|
||||||
|
with patch.object(engine, "read_snapshot"), patch.object(engine, "_refresh_progression_cache"):
|
||||||
|
_, _, message = engine._run_progression_intent(intent)
|
||||||
|
self.assertEqual(message, "体力不足,未开始战斗")
|
||||||
|
self.client.call.assert_not_called()
|
||||||
|
|
||||||
|
def test_receipts_persist_instance_and_expected_reward_separately_from_actual(self):
|
||||||
|
records = [self.receipt("a", kind="accept", task_id=0, type_id="401",
|
||||||
|
response={"resCode": 0, "task": {"id": 51, "typeId": "401", "curStep": 1}}),
|
||||||
|
self.receipt("c", type_id="401", response={"resCode": 0, "reward": {"ke": 7}})]
|
||||||
|
ledger = self.ledger(records)
|
||||||
|
dto = ledger.query(1)
|
||||||
|
self.assertEqual(dto["summary"], {"accepted_count": 1, "completed_count": 1, "pending_count": 0,
|
||||||
|
"expected_ke": 15, "confirmed_ke": 7, "unknown_reward_count": 0})
|
||||||
|
self.assertEqual(len(dto["rows"]), 1)
|
||||||
|
self.assertEqual((dto["rows"][0]["expected_ke"], dto["rows"][0]["confirmed_ke"]), (15, 7))
|
||||||
|
restored = CommissionHistory(self.folder / "history.json")
|
||||||
|
restored.ingest(1, records, self.tasks.get)
|
||||||
|
self.assertEqual(restored.query(1)["summary"], dto["summary"])
|
||||||
|
self.assertIn("实际获得7氪金", dto["rows"][0]["last_action"])
|
||||||
|
|
||||||
|
def test_wallet_total_and_missing_reward_never_become_confirmed_delta(self):
|
||||||
|
self.snapshot.raw["master"]["ke"] = 9000
|
||||||
|
records = [self.receipt("c", response={"resCode": 0, "ke": 9000, "master": {"ke": 9000}})]
|
||||||
|
dto = self.ledger(records).query(1)
|
||||||
|
self.assertEqual(dto["summary"]["completed_count"], 1)
|
||||||
|
self.assertEqual(dto["summary"]["confirmed_ke"], 0)
|
||||||
|
self.assertEqual(dto["summary"]["unknown_reward_count"], 1)
|
||||||
|
self.assertIsNone(dto["rows"][0]["confirmed_ke"])
|
||||||
|
|
||||||
|
def test_step_and_farming_loot_never_count_as_final_commission_reward(self):
|
||||||
|
records = [self.receipt("s", kind="step", response={"resCode": 0, "reward": {"ke": 5}}),
|
||||||
|
self.receipt("f", kind="farm", task_id=0, type_id="", outcome="win", source_task_id=51,
|
||||||
|
source_task_type_id="402", settlement_confirmed=True,
|
||||||
|
response={"resCode": 0, "stageReward": {"ke": 20}, "reward": {"ke": 20}})]
|
||||||
|
dto = self.ledger(records).query(1)
|
||||||
|
self.assertEqual(dto["summary"]["completed_count"], 0)
|
||||||
|
self.assertEqual(dto["summary"]["confirmed_ke"], 0)
|
||||||
|
self.assertEqual({event["kind"] for event in dto["events"]}, {"step", "farm"})
|
||||||
|
self.assertEqual(len(dto["rows"]), 1)
|
||||||
|
|
||||||
|
def test_snapshot_presence_and_pass_task_flag_create_no_history(self):
|
||||||
|
self.snapshot.raw["currentTasks"] = [{"id": 51, "typeId": "402", "curStep": 2}]
|
||||||
|
self.snapshot.raw["history"]["passTask"] = {"402": True}
|
||||||
|
engine = self.engine()
|
||||||
|
dto = engine.commission_history()
|
||||||
|
self.assertEqual(dto["rows"], [])
|
||||||
|
self.assertEqual(dto["summary"]["accepted_count"], 0)
|
||||||
|
self.assertEqual(dto["summary"]["completed_count"], 0)
|
||||||
|
self.client.call.assert_not_called()
|
||||||
|
|
||||||
|
def test_reconciled_claim_without_receipt_remains_unknown(self):
|
||||||
|
self.snapshot.raw["history"]["passTask"] = {"402": True}
|
||||||
|
dto = self.ledger([self.receipt("c", phase="done", outcome="reconciled", response=None)]).query(1)
|
||||||
|
self.assertEqual(dto["summary"]["completed_count"], 0)
|
||||||
|
self.assertEqual(dto["rows"][0]["status"], "unknown")
|
||||||
|
self.assertIsNone(dto["rows"][0]["confirmed_ke"])
|
||||||
|
|
||||||
|
def test_reconciled_acceptance_needs_new_instance_and_does_not_invent_reason(self):
|
||||||
|
self.snapshot.raw["currentTasks"] = [{"id": 52, "typeId": "402", "curStep": 1}]
|
||||||
|
record = self.receipt("a", kind="accept", task_id=0, outcome="reconciled", response=None,
|
||||||
|
baseline={"tasks": [{"id": 51, "typeId": "402"}]},
|
||||||
|
commission_task={"id": 52, "typeId": "402", "curStep": 1})
|
||||||
|
ledger = self.ledger([record])
|
||||||
|
dto = ledger.query(1)
|
||||||
|
self.assertEqual(dto["summary"]["accepted_count"], 1)
|
||||||
|
self.assertEqual(dto["rows"][0]["task_id"], 52)
|
||||||
|
self.assertEqual(dto["rows"][0]["selection_code"], "unknown")
|
||||||
|
self.snapshot.raw["currentTasks"] = []
|
||||||
|
restored = CommissionHistory(self.folder / "history.json")
|
||||||
|
restored.ingest(1, [record], self.tasks.get, self.snapshot)
|
||||||
|
self.assertEqual(restored.query(1)["summary"]["accepted_count"], 1)
|
||||||
|
|
||||||
|
def test_old_reconciled_acceptance_cannot_bind_to_unrelated_current_instance(self):
|
||||||
|
self.snapshot.raw["currentTasks"] = [{"id": 99, "typeId": "402", "curStep": 1}]
|
||||||
|
stamp = self.snapshot.now - 2 * 86400
|
||||||
|
ledger = self.ledger([self.receipt("old-a", kind="accept", task_id=0,
|
||||||
|
when=stamp, outcome="reconciled", response=None)])
|
||||||
|
dto = ledger.query(1, beijing_day(stamp))
|
||||||
|
self.assertIsNone(dto["rows"][0]["task_id"])
|
||||||
|
self.assertEqual(dto["summary"]["accepted_count"], 0)
|
||||||
|
|
||||||
|
def test_fresh_snapshot_reconciliation_captures_exact_new_acceptance_instance(self):
|
||||||
|
engine = self.engine()
|
||||||
|
record = self.record(engine, kind="progression_loop_accept", path="taskService/taskLoopReceive",
|
||||||
|
task_id=0, outcome=None)
|
||||||
|
engine.battle_journal.update(record, "unknown")
|
||||||
|
self.snapshot.raw["currentTasks"] = [{"id": 52, "typeId": "402", "curStep": 1}]
|
||||||
|
engine.read_snapshot(sync_master=False)
|
||||||
|
dto = engine.commission_history()
|
||||||
|
self.assertEqual(dto["summary"]["accepted_count"], 1)
|
||||||
|
self.assertEqual(dto["rows"][0]["task_id"], 52)
|
||||||
|
self.client.call.assert_not_called()
|
||||||
|
|
||||||
|
def test_acceptance_validates_numeric_ids_and_instance_identity(self):
|
||||||
|
for identifier, valid in (("51", True), (True, False), (51.5, False), ("bad", False)):
|
||||||
|
with self.subTest(identifier=identifier):
|
||||||
|
ledger = CommissionHistory()
|
||||||
|
ledger.ingest(1, [self.receipt(str(identifier), kind="accept", task_id=0,
|
||||||
|
response={"task": {"id": identifier, "typeId": "402", "curStep": "1"}})], self.tasks.get)
|
||||||
|
self.assertEqual(ledger.query(1)["summary"]["accepted_count"], int(valid))
|
||||||
|
ledger = CommissionHistory()
|
||||||
|
ledger.ingest(1, [self.receipt("wrong", kind="accept", task_id=0,
|
||||||
|
response={"resCode": 0, "task": {"id": 52, "typeId": "401", "curStep": 1}})], self.tasks.get)
|
||||||
|
self.assertEqual(ledger.query(1)["summary"]["accepted_count"], 0)
|
||||||
|
|
||||||
|
def test_duplicate_attempts_and_receipts_deduplicate_daily_counts_by_instance(self):
|
||||||
|
records = [self.receipt("a1", kind="accept", task_id=0,
|
||||||
|
response={"task": {"id": 51, "typeId": "402", "curStep": 1}}),
|
||||||
|
self.receipt("a2", kind="accept", task_id=0,
|
||||||
|
response={"task": {"id": "51", "typeId": "402", "curStep": 1}}),
|
||||||
|
self.receipt("c1", response={"reward": {"ke": 20}}),
|
||||||
|
self.receipt("c2", task_id="51", response={"reward": {"ke": 20}})]
|
||||||
|
ledger = self.ledger(records)
|
||||||
|
ledger.ingest(1, records, self.tasks.get)
|
||||||
|
dto = ledger.query(1)
|
||||||
|
self.assertEqual(len(dto["events"]), 4)
|
||||||
|
self.assertEqual(len(dto["rows"]), 1)
|
||||||
|
self.assertEqual(dto["summary"]["accepted_count"], 1)
|
||||||
|
self.assertEqual(dto["summary"]["completed_count"], 1)
|
||||||
|
self.assertEqual(dto["summary"]["expected_ke"], 20)
|
||||||
|
self.assertEqual(dto["summary"]["confirmed_ke"], 20)
|
||||||
|
|
||||||
|
def test_beijing_midnight_repeat_types_and_cross_day_duplicate_claims(self):
|
||||||
|
midnight = datetime(2026, 11, 13, tzinfo=CN).timestamp()
|
||||||
|
records = [self.receipt("old", when=midnight - 1, response={"reward": {"ke": 20}}),
|
||||||
|
self.receipt("duplicate", when=midnight + 1, response={"reward": {"ke": 20}}),
|
||||||
|
self.receipt("new", task_id=52, when=midnight + 2, response={"reward": {"ke": 20}})]
|
||||||
|
ledger = self.ledger(records, now=midnight + 10)
|
||||||
|
self.assertEqual(beijing_day(midnight - 1), "2026-11-12")
|
||||||
|
self.assertEqual(ledger.query(1)["date"], "2026-11-13")
|
||||||
|
self.assertEqual(ledger.query(1, "2026-11-12")["summary"]["confirmed_ke"], 20)
|
||||||
|
dto = ledger.query(1)
|
||||||
|
self.assertEqual(len(dto["rows"]), 2)
|
||||||
|
self.assertEqual(dto["summary"]["completed_count"], 1)
|
||||||
|
self.assertEqual(dto["summary"]["confirmed_ke"], 20)
|
||||||
|
self.assertEqual(len({row["id"] for row in dto["rows"]}), 2)
|
||||||
|
self.assertEqual(dto["dates"], ["2026-11-13", "2026-11-12"])
|
||||||
|
|
||||||
|
def test_pending_and_failure_states_never_claim_success(self):
|
||||||
|
for phase, outcome, expected in (("request_pending", "", "pending"), ("unknown", "", "unknown"),
|
||||||
|
("done", "cancelled", "cancelled"), ("done", "loss", "failed")):
|
||||||
|
with self.subTest(expected=expected):
|
||||||
|
ledger = CommissionHistory()
|
||||||
|
ledger.ingest(1, [self.receipt(expected, kind="step", phase=phase, outcome=outcome)], self.tasks.get)
|
||||||
|
dto = ledger.query(1)
|
||||||
|
self.assertEqual(dto["rows"][0]["status"], expected)
|
||||||
|
self.assertEqual(dto["summary"]["completed_count"], 0)
|
||||||
|
self.assertNotIn(";已确认", dto["events"][0]["description"])
|
||||||
|
|
||||||
|
def test_existing_task_action_is_not_counted_as_accepted_today(self):
|
||||||
|
dto = self.ledger([self.receipt("s", kind="step")]).query(1)
|
||||||
|
self.assertEqual(dto["summary"]["accepted_count"], 0)
|
||||||
|
self.assertIsNone(dto["rows"][0]["accepted_at"])
|
||||||
|
self.assertEqual(dto["rows"][0]["selection_code"], "already_accepted")
|
||||||
|
|
||||||
|
def test_role_isolation_and_dto_mutation_cannot_change_history(self):
|
||||||
|
ledger = self.ledger([self.receipt("c", response={"reward": {"ke": 20}})])
|
||||||
|
self.assertEqual(ledger.query(2)["rows"], [])
|
||||||
|
dto = ledger.query(1)
|
||||||
|
dto["rows"][0]["events"][0]["description"] = "changed"
|
||||||
|
dto["summary"]["confirmed_ke"] = 10000
|
||||||
|
self.assertEqual(ledger.query(1)["summary"]["confirmed_ke"], 20)
|
||||||
|
self.assertNotEqual(ledger.query(1)["events"][0]["description"], "changed")
|
||||||
|
|
||||||
|
def test_bounded_retention_and_journal_rollover_preserve_imported_receipts(self):
|
||||||
|
now = self.snapshot.now
|
||||||
|
records = [self.receipt(str(number), task_id=number + 1, when=now - number,
|
||||||
|
response={"reward": {"ke": 20}}) for number in range(8)]
|
||||||
|
records.append(self.receipt("ancient", task_id=99, when=now - 91 * 86400, response={"reward": {"ke": 20}}))
|
||||||
|
ledger = self.ledger(records, max_events=4)
|
||||||
|
self.assertEqual(len(ledger.query(1)["events"]), 4)
|
||||||
|
ledger.ingest(1, [], self.tasks.get)
|
||||||
|
restored = CommissionHistory(self.folder / "history.json", max_events=4)
|
||||||
|
self.assertEqual(restored.query(1)["summary"]["completed_count"], 4)
|
||||||
|
|
||||||
|
def test_history_reads_do_not_reload_journal_or_load_full_progression(self):
|
||||||
|
engine = self.engine()
|
||||||
|
engine.game_data = None
|
||||||
|
self.record(engine, type_id="100", response={"reward": {"ke": 20}})
|
||||||
|
with patch("ranch_assistant.game_data.load_progression_data", side_effect=AssertionError("unexpected full load")), \
|
||||||
|
patch.object(engine.battle_journal, "records", side_effect=AssertionError("unexpected payload copy")), \
|
||||||
|
patch.object(engine.battle_journal, "reload", side_effect=AssertionError("unexpected journal reload")):
|
||||||
|
engine.commission_history()
|
||||||
|
engine.commission_history()
|
||||||
|
self.client.call.assert_not_called()
|
||||||
|
|
||||||
|
def test_history_write_failure_preserves_success_and_recovers_without_game_retry(self):
|
||||||
|
engine = self.engine()
|
||||||
|
engine._ensure_progression()
|
||||||
|
intent = engine.progression_planner.commission_plan(self.snapshot, engine.quest_policy, engine.policy)[0]
|
||||||
|
self.client.call.side_effect = lambda *args: {"resCode": 0, "task": {"id": 51, "typeId": "402", "curStep": 1}}
|
||||||
|
with patch.object(engine._commission_history, "_save", side_effect=OSError("fixture disk full")):
|
||||||
|
message = engine._execute_task_intent(intent)
|
||||||
|
self.assertIn("已确认", message)
|
||||||
|
dto = engine.commission_history()
|
||||||
|
self.assertEqual(dto["summary"]["accepted_count"], 1)
|
||||||
|
self.assertIn("暂未写入磁盘", dto["error"])
|
||||||
|
self.assertEqual(self.client.call.call_count, 1)
|
||||||
|
self.assertIsNone(engine.battle_journal.pending(self.snapshot))
|
||||||
|
recovered = engine.commission_history()
|
||||||
|
self.assertEqual(recovered["error"], "")
|
||||||
|
self.assertTrue(engine._commission_history.path.exists())
|
||||||
|
self.assertEqual(self.client.call.call_count, 1)
|
||||||
|
|
||||||
|
def test_acceptance_timeout_stays_unknown_and_restart_never_replays(self):
|
||||||
|
engine = self.engine()
|
||||||
|
engine._ensure_progression()
|
||||||
|
intent = engine.progression_planner.commission_plan(self.snapshot, engine.quest_policy, engine.policy)[0]
|
||||||
|
self.client.call.side_effect = TimeoutError("offline timeout")
|
||||||
|
with self.assertRaises(TimeoutError):
|
||||||
|
engine._execute_task_intent(intent)
|
||||||
|
self.assertEqual(engine.commission_history()["rows"][0]["status"], "unknown")
|
||||||
|
restored = self.engine()
|
||||||
|
restored._refresh_progression_cache(force=True)
|
||||||
|
_, _, message = restored._run_progression_intent()
|
||||||
|
self.assertIn("待核对", message)
|
||||||
|
self.assertEqual(self.client.call.call_count, 1)
|
||||||
|
self.assertEqual(restored.commission_history()["summary"]["accepted_count"], 0)
|
||||||
|
|
||||||
|
def test_accepted_reply_without_task_is_unknown_in_both_log_and_history(self):
|
||||||
|
engine = self.engine()
|
||||||
|
engine._ensure_progression()
|
||||||
|
intent = engine.progression_planner.commission_plan(self.snapshot, engine.quest_policy, engine.policy)[0]
|
||||||
|
self.client.call.side_effect = lambda *args: {"resCode": 0}
|
||||||
|
message = engine._execute_task_intent(intent)
|
||||||
|
self.assertIn("结果未知", message)
|
||||||
|
self.assertNotIn(";已确认", message)
|
||||||
|
self.assertEqual(engine.commission_history()["summary"]["accepted_count"], 0)
|
||||||
|
self.assertIsNotNone(engine.battle_journal.pending(self.snapshot))
|
||||||
|
|
||||||
|
def test_offer_diagnostics_and_selection_explain_locked_city_and_runtime(self):
|
||||||
|
engine = self.engine()
|
||||||
|
self.snapshot.raw["history"]["unlockCity"]["2"] = False
|
||||||
|
engine._refresh_progression_cache(force=True)
|
||||||
|
selected = engine.progression_planner.commission_selection
|
||||||
|
self.assertEqual(selected["task_type_id"], "401")
|
||||||
|
self.assertEqual(selected["selection_code"], "20_ineligible")
|
||||||
|
self.assertIn("城市尚未解锁", selected["selection_reason"])
|
||||||
|
with patch.object(engine, "_battle_capability", side_effect=AssertionError("UI must not inspect runtime")):
|
||||||
|
for _ in range(3):
|
||||||
|
rows = engine.commission_offer_diagnostics()
|
||||||
|
high = next(row for row in rows if row["task_type_id"] == "402")
|
||||||
|
self.assertFalse(high["eligible"])
|
||||||
|
self.assertEqual(high["reason"], "城市尚未解锁")
|
||||||
|
self.client.call.assert_not_called()
|
||||||
|
engine._commission_offer_supported = Mock(side_effect=lambda key: str(key) != "402")
|
||||||
|
engine._commission_offer_reason = "保护目标规则暂不支持"
|
||||||
|
self.snapshot.raw["history"]["unlockCity"]["2"] = True
|
||||||
|
engine._refresh_progression_cache(force=True)
|
||||||
|
self.assertIn("保护目标规则暂不支持", engine.progression_planner.commission_selection["selection_reason"])
|
||||||
|
|
||||||
|
def test_quota_and_city_filter_diagnostics_do_not_claim_receivable(self):
|
||||||
|
engine = self.engine()
|
||||||
|
engine.quest_policy.city = 1
|
||||||
|
engine._refresh_progression_cache(force=True)
|
||||||
|
high = next(row for row in engine.commission_offer_diagnostics() if row["task_type_id"] == "402")
|
||||||
|
self.assertFalse(high["eligible"])
|
||||||
|
self.assertIn("策略限定城市", high["reason"])
|
||||||
|
self.snapshot.raw["history"]["loopTaskNum"] = 0
|
||||||
|
engine._refresh_progression_cache(force=True)
|
||||||
|
rows = engine.commission_offer_diagnostics()
|
||||||
|
self.assertTrue(all(not row["eligible"] for row in rows))
|
||||||
|
self.assertIn("当日接取次数已用完", next(row for row in rows if row["city"] == 1)["reason"])
|
||||||
|
|
||||||
|
def test_unchanged_snapshot_replans_after_beijing_midnight_grace(self):
|
||||||
|
engine = self.engine()
|
||||||
|
before = datetime(2026, 11, 13, 23, 59, 59, tzinfo=CN).timestamp()
|
||||||
|
self.snapshot.raw["history"].update(loopTaskTime=before, loopTaskNum=0)
|
||||||
|
original = deepcopy(self.snapshot.raw)
|
||||||
|
with patch("ranch_assistant.model.time.time", return_value=before):
|
||||||
|
engine._refresh_progression_cache(force=True)
|
||||||
|
self.assertFalse(any(intent.kind == "progression_loop_reset" for intent in engine._progression_intents))
|
||||||
|
with patch("ranch_assistant.model.time.time", return_value=before + 12):
|
||||||
|
engine._refresh_progression_cache()
|
||||||
|
self.assertEqual(self.snapshot.raw, original)
|
||||||
|
self.assertTrue(any(intent.kind == "progression_loop_reset" for intent in engine._progression_intents))
|
||||||
|
|
||||||
|
def test_no_twenty_fallback_still_explains_rejected_fifteen(self):
|
||||||
|
self.snapshot.raw["history"]["loopTask"] = {"1": ["400", "401"]}
|
||||||
|
self.tasks["401"]["closed"] = True
|
||||||
|
for planner in (ProgressionPlanner(self.catalog, config(self.tasks)), TaskPlanner(self.catalog)):
|
||||||
|
self.catalog.data["task_info"] = self.tasks
|
||||||
|
if isinstance(planner, TaskPlanner):
|
||||||
|
action = planner.plan(self.snapshot, QuestPolicy(enabled=True), self.engine().policy)[0]
|
||||||
|
self.assertEqual(action.payload["taskTypeId"], "400")
|
||||||
|
else:
|
||||||
|
self.assertEqual(planner.commission_plan(self.snapshot, QuestPolicy(enabled=True), self.engine().policy)[0].task_type_id, "400")
|
||||||
|
self.assertEqual(planner.commission_selection["selection_code"], "no_20_offered")
|
||||||
|
self.assertIn("未提供20", planner.commission_selection["selection_reason"])
|
||||||
|
self.assertIn("委托已关闭", planner.commission_selection["selection_reason"])
|
||||||
|
|
||||||
|
def test_step_log_names_consumed_and_only_checked_items(self):
|
||||||
|
self.catalog.data.setdefault("item_names", {})["30001"] = "石块"
|
||||||
|
for remove, expected in ((True, "提交石块×5"), (False, "核对持有石块×5")):
|
||||||
|
with self.subTest(remove=remove):
|
||||||
|
engine = Engine(self.catalog, self.client, game_data=ProgressionData(config({"402": task("402", type=4,
|
||||||
|
reward={"ke": 20}, steps=[step("getItem", statusValue={"type": "30001", "num": 5, "remove": remove})])})))
|
||||||
|
engine.snapshot = self.snapshot
|
||||||
|
intent = {"kind": "quest_step", "task_id": 51, "task_type_id": "402", "step_number": 1,
|
||||||
|
"path": "taskService/taskCompleteStep", "payload": {}, "description": "提交步骤"}
|
||||||
|
record = engine.battle_journal.begin(self.snapshot, intent)
|
||||||
|
engine._journal_commission(record, intent, legacy=True)
|
||||||
|
engine.battle_journal.update(record, "acknowledged", response={"resCode": 0}, response_confirmed=True)
|
||||||
|
engine.battle_journal.finish(self.snapshot, record, "task")
|
||||||
|
dto = engine.commission_history()
|
||||||
|
self.assertIn(expected, dto["events"][0]["description"])
|
||||||
|
self.assertIn("20氪金", dto["events"][0]["description"])
|
||||||
|
|
||||||
|
def test_navigation_and_dialogue_are_local_evidence_with_honest_labels(self):
|
||||||
|
records = [self.receipt("n", kind="navigate", outcome="local", description="前往王城市场"),
|
||||||
|
self.receipt("d", kind="dialogue", outcome="local", description="与妮娜对话")]
|
||||||
|
dto = self.ledger(records).query(1)
|
||||||
|
self.assertEqual({event["kind"] for event in dto["events"]}, {"navigate", "dialogue"})
|
||||||
|
self.assertTrue(all(event["confirmation"] == "local" for event in dto["events"]))
|
||||||
|
self.assertEqual(dto["summary"]["accepted_count"], 0)
|
||||||
|
|
||||||
|
def test_invalid_day_and_corrupt_history_preserve_file(self):
|
||||||
|
ledger = self.ledger([])
|
||||||
|
for day in ("20261113", "2026-02-30", "2026-1-1", 20261113):
|
||||||
|
with self.subTest(day=day), self.assertRaises(ValueError):
|
||||||
|
ledger.query(1, day)
|
||||||
|
damaged = self.folder / "damaged.json"
|
||||||
|
damaged.write_text("not-json", encoding="utf-8")
|
||||||
|
ledger = CommissionHistory(damaged)
|
||||||
|
ledger.ingest(1, [self.receipt("c", response={"reward": {"ke": 20}})], self.tasks.get)
|
||||||
|
self.assertIn("无法读取", ledger.query(1)["error"])
|
||||||
|
self.assertEqual(damaged.read_text(encoding="utf-8"), "not-json")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,369 @@
|
|||||||
|
"""Independent offline review repros; all records and accounts are synthetic."""
|
||||||
|
from copy import deepcopy
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import tempfile
|
||||||
|
from types import SimpleNamespace
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import Mock, patch
|
||||||
|
|
||||||
|
from ranch_assistant.battles import BattleJournal
|
||||||
|
from ranch_assistant.commission_history import CommissionHistory, journal_event
|
||||||
|
from ranch_assistant.engine import Engine
|
||||||
|
from ranch_assistant.game_data import ProgressionData
|
||||||
|
from ranch_assistant.model import Catalog, Policy, Snapshot
|
||||||
|
from ranch_assistant.progression import ProgressionPlanner
|
||||||
|
from ranch_assistant.quests import QuestPolicy
|
||||||
|
|
||||||
|
|
||||||
|
NOW = datetime(2026, 11, 13, 4, tzinfo=timezone.utc).timestamp()
|
||||||
|
DAY = "2026-11-13"
|
||||||
|
INFO = {"id": "review20", "type": 4, "name": "Review commission", "reward": {"ke": 20},
|
||||||
|
"startStep": {"condition": {}}, "steps": [{"statusType": "none", "statusValue": {}}]}
|
||||||
|
|
||||||
|
|
||||||
|
def review_snapshot(role=71, tasks=()):
|
||||||
|
return Snapshot({"master": {"id": role, "level": 20, "money": 2000, "ti": 50, "ke": 99999},
|
||||||
|
"currentTasks": deepcopy(list(tasks)), "history": {"unlockCity": {"1": True}},
|
||||||
|
"items": [], "monsters": [], "stacks": [], "rooms": [], "teams": []})
|
||||||
|
|
||||||
|
|
||||||
|
def review_record(attempt="review-claim", *, kind="complete", task_id=81, timestamp=NOW, **changes):
|
||||||
|
record = {"attempt_id": attempt, "role_id": "71", "task_id": task_id, "task_type_id": "review20",
|
||||||
|
"kind": {"accept": "progression_loop_accept", "complete": "progression_reward",
|
||||||
|
"step": "progression_step", "battle": "progression_battle"}[kind],
|
||||||
|
"path": {"accept": "taskService/taskLoopReceive", "complete": "taskService/taskComplete",
|
||||||
|
"step": "taskService/taskCompleteStep", "battle": ""}[kind],
|
||||||
|
"timestamp": timestamp, "updated_at": timestamp, "finished_at": timestamp,
|
||||||
|
"phase": "done", "outcome": "task", "payload": {},
|
||||||
|
"commission": {"name": INFO["name"], "expected_ke": 20, "city": 1,
|
||||||
|
"selection_code": "highest_reward", "selection_reason": "review-selected"},
|
||||||
|
"baseline": {"tasks": []}, "response_confirmed": True,
|
||||||
|
"response": {"resCode": 0, "reward": {"ke": 20}}}
|
||||||
|
if kind == "accept":
|
||||||
|
record.update(task_id=None, response={"resCode": 0,
|
||||||
|
"task": {"id": task_id, "typeId": "review20", "curStep": 1}})
|
||||||
|
record.update(changes)
|
||||||
|
return record
|
||||||
|
|
||||||
|
|
||||||
|
class CommissionHistoryIndependentReviewTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.folder = Path(self.enterContext(tempfile.TemporaryDirectory(prefix="commission-independent-review-")))
|
||||||
|
self.enterContext(patch("socket.socket.connect", side_effect=AssertionError("offline review forbids network")))
|
||||||
|
self.history = CommissionHistory(self.folder / "history.json", clock=lambda: NOW)
|
||||||
|
|
||||||
|
def ingest(self, records, snapshot=None, history=None, role="71"):
|
||||||
|
target = history if history is not None else self.history
|
||||||
|
target.ingest(role, records, lambda key: INFO, snapshot)
|
||||||
|
return target.query(role, DAY)
|
||||||
|
|
||||||
|
def test_cancelled_accept_with_task_body_is_never_confirmed(self):
|
||||||
|
record = review_record(kind="accept", outcome="cancelled")
|
||||||
|
event = journal_event(record, INFO, review_snapshot())
|
||||||
|
self.assertEqual(event["status"], "cancelled")
|
||||||
|
result = self.ingest([record])
|
||||||
|
self.assertEqual(result["summary"]["accepted_count"], 0)
|
||||||
|
self.assertEqual(result["summary"]["expected_ke"], 0)
|
||||||
|
self.assertIsNone(result["rows"][0]["accepted_at"])
|
||||||
|
|
||||||
|
def test_pending_receipt_body_does_not_count_as_a_claim(self):
|
||||||
|
record = review_record(phase="request_pending", outcome="", response_confirmed=False)
|
||||||
|
result = self.ingest([record])
|
||||||
|
self.assertEqual(result["summary"]["completed_count"], 0)
|
||||||
|
self.assertEqual(result["summary"]["confirmed_ke"], 0)
|
||||||
|
self.assertEqual(result["summary"]["pending_count"], 1)
|
||||||
|
self.assertIsNone(result["rows"][0]["confirmed_ke"])
|
||||||
|
|
||||||
|
def test_cancelled_and_failed_outcomes_stay_terminal_in_aggregate(self):
|
||||||
|
for outcome, status in (("cancelled", "cancelled"), ("unsupported", "cancelled"), ("loss", "failed")):
|
||||||
|
with self.subTest(outcome=outcome):
|
||||||
|
ledger = CommissionHistory(clock=lambda: NOW)
|
||||||
|
result = self.ingest([review_record(kind="battle", outcome=outcome)], history=ledger)
|
||||||
|
self.assertEqual(result["events"][0]["status"], status)
|
||||||
|
self.assertEqual(result["rows"][0]["status"], status)
|
||||||
|
self.assertEqual(result["summary"]["pending_count"], 0)
|
||||||
|
self.assertEqual(result["summary"]["completed_count"], 0)
|
||||||
|
|
||||||
|
def test_unknown_result_stays_unknown_and_pending_in_summary(self):
|
||||||
|
result = self.ingest([review_record(phase="task_unknown", outcome="", response=None,
|
||||||
|
response_confirmed=False)])
|
||||||
|
self.assertEqual(result["rows"][0]["status"], "unknown")
|
||||||
|
self.assertEqual(result["summary"]["pending_count"], 1)
|
||||||
|
self.assertEqual(result["summary"]["completed_count"], 0)
|
||||||
|
|
||||||
|
def test_duplicate_claim_attempts_count_one_instance_once(self):
|
||||||
|
result = self.ingest([review_record("claim-one"), review_record("claim-two", timestamp=NOW + 1)])
|
||||||
|
self.assertEqual(len(result["events"]), 2, "retain both attempts as evidence")
|
||||||
|
self.assertEqual(len(result["rows"]), 1)
|
||||||
|
self.assertEqual(result["summary"]["completed_count"], 1)
|
||||||
|
self.assertEqual(result["summary"]["confirmed_ke"], 20)
|
||||||
|
|
||||||
|
def test_duplicate_claim_on_later_day_does_not_create_new_reward(self):
|
||||||
|
before = datetime(2026, 11, 12, 15, 59, tzinfo=timezone.utc).timestamp()
|
||||||
|
after = before + 120
|
||||||
|
result = self.ingest([review_record("claim-before", timestamp=before),
|
||||||
|
review_record("claim-after", timestamp=after)])
|
||||||
|
self.assertEqual(result["summary"]["completed_count"], 0)
|
||||||
|
self.assertEqual(result["summary"]["confirmed_ke"], 0)
|
||||||
|
self.assertEqual(self.history.query("71", "2026-11-12")["summary"]["confirmed_ke"], 20)
|
||||||
|
|
||||||
|
def test_same_type_different_instances_are_counted_separately(self):
|
||||||
|
result = self.ingest([review_record("claim-one", task_id=81),
|
||||||
|
review_record("claim-two", task_id=82, timestamp=NOW + 1)])
|
||||||
|
self.assertEqual(len(result["rows"]), 2)
|
||||||
|
self.assertEqual(result["summary"]["completed_count"], 2)
|
||||||
|
self.assertEqual(result["summary"]["confirmed_ke"], 40)
|
||||||
|
|
||||||
|
def test_reconciled_accept_is_reconsidered_when_snapshot_changes(self):
|
||||||
|
record = review_record(kind="accept", task_id=81, response=None,
|
||||||
|
response_confirmed=False, outcome="reconciled")
|
||||||
|
first = self.ingest([record], review_snapshot())
|
||||||
|
self.assertEqual(first["summary"]["accepted_count"], 0)
|
||||||
|
second = self.ingest([record], review_snapshot(tasks=[{"id": 81, "typeId": "review20", "curStep": 1}]))
|
||||||
|
self.assertEqual(second["summary"]["accepted_count"], 1)
|
||||||
|
self.assertEqual(second["rows"][0]["task_id"], 81)
|
||||||
|
|
||||||
|
def test_old_accept_today_claim_uses_beijing_day_for_each_count(self):
|
||||||
|
before = datetime(2026, 11, 12, 15, 59, tzinfo=timezone.utc).timestamp()
|
||||||
|
after = before + 120
|
||||||
|
today = self.ingest([review_record("accept-old", kind="accept", timestamp=before),
|
||||||
|
review_record("claim-today", timestamp=after)])
|
||||||
|
yesterday = self.history.query("71", "2026-11-12")
|
||||||
|
self.assertEqual(today["summary"]["accepted_count"], 0)
|
||||||
|
self.assertEqual(today["summary"]["expected_ke"], 0)
|
||||||
|
self.assertEqual(today["summary"]["completed_count"], 1)
|
||||||
|
self.assertEqual(today["summary"]["confirmed_ke"], 20)
|
||||||
|
self.assertEqual(yesterday["summary"]["accepted_count"], 1)
|
||||||
|
self.assertEqual(yesterday["summary"]["completed_count"], 0)
|
||||||
|
self.assertEqual(today["rows"][0]["accepted_at"], before)
|
||||||
|
|
||||||
|
def test_missing_historical_metadata_never_invents_reason_or_reward(self):
|
||||||
|
record = review_record(commission={}, response={"resCode": 0, "ke": 99999})
|
||||||
|
result = self.ingest([record], review_snapshot())
|
||||||
|
row = result["rows"][0]
|
||||||
|
self.assertIsNone(row["accepted_at"])
|
||||||
|
self.assertIsNone(row["confirmed_ke"])
|
||||||
|
self.assertNotIn("review-selected", row["selection_reason"])
|
||||||
|
self.assertEqual(result["summary"]["confirmed_ke"], 0)
|
||||||
|
self.assertEqual(result["summary"]["unknown_reward_count"], 1)
|
||||||
|
|
||||||
|
def test_unconfirmed_historical_accept_does_not_describe_itself_as_confirmed(self):
|
||||||
|
result = self.ingest([review_record(kind="accept", commission={}, phase="request_pending",
|
||||||
|
outcome="", response=None, response_confirmed=False)])
|
||||||
|
self.assertEqual(result["summary"]["accepted_count"], 0)
|
||||||
|
self.assertNotIn("已确认", result["rows"][0]["selection_reason"])
|
||||||
|
|
||||||
|
def test_invalid_reward_values_are_unknown_not_catalog_or_wallet_amounts(self):
|
||||||
|
for value in (None, True, "20", -1, 1.5, float("nan"), float("inf")):
|
||||||
|
with self.subTest(value=value):
|
||||||
|
ledger = CommissionHistory(clock=lambda: NOW)
|
||||||
|
result = self.ingest([review_record(response={"resCode": 0, "reward": {"ke": value}})],
|
||||||
|
history=ledger)
|
||||||
|
self.assertEqual(result["summary"]["completed_count"], 1)
|
||||||
|
self.assertEqual(result["summary"]["confirmed_ke"], 0)
|
||||||
|
self.assertIsNone(result["rows"][0]["confirmed_ke"])
|
||||||
|
|
||||||
|
def test_read_and_restart_are_idempotent_and_return_detached_data(self):
|
||||||
|
records = [review_record()]
|
||||||
|
expected = self.ingest(records)
|
||||||
|
before = self.history.path.read_bytes()
|
||||||
|
for _ in range(3):
|
||||||
|
self.assertEqual(self.ingest(records), expected)
|
||||||
|
self.assertEqual(self.history.query("71", DAY), expected)
|
||||||
|
self.assertEqual(self.history.path.read_bytes(), before)
|
||||||
|
restored = CommissionHistory(self.history.path, clock=lambda: NOW)
|
||||||
|
self.assertEqual(self.ingest(records, history=restored), expected)
|
||||||
|
copy = restored.query("71", DAY)
|
||||||
|
copy["rows"][0]["name"] = "caller mutation"
|
||||||
|
self.assertEqual(restored.query("71", DAY), expected)
|
||||||
|
|
||||||
|
def test_role_and_separate_account_paths_are_isolated(self):
|
||||||
|
self.ingest([review_record()])
|
||||||
|
other = review_record(role_id="72", response={"resCode": 0, "reward": {"ke": 15}})
|
||||||
|
self.ingest([other], role="72")
|
||||||
|
self.assertEqual(self.history.query("71", DAY)["summary"]["confirmed_ke"], 20)
|
||||||
|
self.assertEqual(self.history.query("72", DAY)["summary"]["confirmed_ke"], 15)
|
||||||
|
separate = CommissionHistory(self.folder / "other-account" / "history.json", clock=lambda: NOW)
|
||||||
|
self.assertEqual(separate.query("71", DAY)["events"], [])
|
||||||
|
|
||||||
|
def test_ledger_survives_rolling_journal_eviction_and_restart(self):
|
||||||
|
snapshot = review_snapshot()
|
||||||
|
journal = BattleJournal(self.folder / "journal.json")
|
||||||
|
journal.role(snapshot)["records"].append(review_record())
|
||||||
|
journal.save()
|
||||||
|
self.ingest(journal.role(snapshot)["records"])
|
||||||
|
journal.role(snapshot)["records"].extend({"attempt_id": f"other-{i}", "role_id": "71"}
|
||||||
|
for i in range(501))
|
||||||
|
journal.save()
|
||||||
|
self.assertEqual(len(journal.role(snapshot)["records"]), 500)
|
||||||
|
self.assertNotIn("review-claim", {r["attempt_id"] for r in journal.role(snapshot)["records"]})
|
||||||
|
self.ingest(journal.role(snapshot)["records"])
|
||||||
|
restored = CommissionHistory(self.history.path, clock=lambda: NOW)
|
||||||
|
result = restored.query("71", DAY)
|
||||||
|
self.assertEqual(result["summary"]["completed_count"], 1)
|
||||||
|
self.assertEqual(result["summary"]["confirmed_ke"], 20)
|
||||||
|
|
||||||
|
def test_event_cap_and_retention_preserve_newest_events_on_restart(self):
|
||||||
|
ledger = CommissionHistory(self.folder / "bounded.json", max_events=2, retention_days=2, clock=lambda: NOW)
|
||||||
|
self.ingest([review_record(f"event-{i}", task_id=81 + i, timestamp=NOW + i)
|
||||||
|
for i in (-3 * 86400, 0, 1, 2)], history=ledger)
|
||||||
|
restored = CommissionHistory(ledger.path, max_events=2, retention_days=2, clock=lambda: NOW)
|
||||||
|
result = restored.query("71", DAY)
|
||||||
|
self.assertEqual({e["id"] for e in result["events"]}, {"event-1", "event-2"})
|
||||||
|
|
||||||
|
def test_corrupt_history_is_reported_and_original_bytes_preserved(self):
|
||||||
|
path = self.folder / "corrupt.json"
|
||||||
|
path.write_text('{"broken":', encoding="utf-8")
|
||||||
|
before = path.read_bytes()
|
||||||
|
ledger = CommissionHistory(path, clock=lambda: NOW)
|
||||||
|
result = self.ingest([review_record()], history=ledger)
|
||||||
|
self.assertTrue(result["error"])
|
||||||
|
self.assertEqual(result["events"], [])
|
||||||
|
self.assertEqual(path.read_bytes(), before)
|
||||||
|
|
||||||
|
def test_incomplete_persisted_event_reports_error_instead_of_crashing_read(self):
|
||||||
|
path = self.folder / "incomplete-event.json"
|
||||||
|
path.write_text(json.dumps({"version": 1, "roles": {"71": {"bad-event": {
|
||||||
|
"id": "bad-event", "time": NOW, "date": DAY, "kind": "complete", "status": "confirmed"}}}}),
|
||||||
|
encoding="utf-8")
|
||||||
|
before = path.read_bytes()
|
||||||
|
ledger = CommissionHistory(path, clock=lambda: NOW)
|
||||||
|
result = ledger.query("71", DAY)
|
||||||
|
self.assertTrue(result["error"])
|
||||||
|
self.assertEqual(path.read_bytes(), before)
|
||||||
|
|
||||||
|
def test_cancelled_history_row_is_labelled_cancelled_by_web(self):
|
||||||
|
from ranch_web.policies import default_config
|
||||||
|
from ranch_web.views import build_view
|
||||||
|
|
||||||
|
history = self.ingest([review_record(kind="accept", outcome="cancelled")])
|
||||||
|
engine = Engine(Catalog())
|
||||||
|
engine.snapshot = review_snapshot()
|
||||||
|
engine.commission_history = Mock(return_value=history)
|
||||||
|
dto = build_view(engine, "commissions", default_config(), {"tab": "history", "date": DAY})
|
||||||
|
self.assertEqual(dto["rows"][0]["status_label"], "已取消")
|
||||||
|
self.assertIn("已取消", dto["details"][dto["rows"][0]["id"]]["行动记录"])
|
||||||
|
|
||||||
|
|
||||||
|
class CommissionRunMessageIndependentReviewTests(unittest.TestCase):
|
||||||
|
def test_uncertain_accept_is_not_resent_after_engine_restart(self):
|
||||||
|
with tempfile.TemporaryDirectory(prefix="commission-uncertain-review-") as directory:
|
||||||
|
client = Mock()
|
||||||
|
client.call.side_effect = TimeoutError("synthetic uncertain write")
|
||||||
|
path = Path(directory) / "budget.json"
|
||||||
|
data = ProgressionData({"task_info": {"review20": deepcopy(INFO)}, "scripts": {},
|
||||||
|
"stage_info": {}, "game_setting": {"cityInfo": {"1": {}}}})
|
||||||
|
engine = Engine(Catalog(), client, path, game_data=data)
|
||||||
|
engine.snapshot = review_snapshot()
|
||||||
|
engine.snapshot.raw["history"].update(loopTaskTime=engine.snapshot.now, loopTaskNum=6,
|
||||||
|
loopTask={"1": ["review20"]})
|
||||||
|
engine.quest_policy.enabled = True
|
||||||
|
engine._refresh_progression_cache(force=True)
|
||||||
|
intent = next(i for i in engine._progression_intents if not i.blocked)
|
||||||
|
self.assertEqual(intent.kind, "progression_loop_accept")
|
||||||
|
with self.assertRaises(TimeoutError):
|
||||||
|
engine._run_progression_intent(intent)
|
||||||
|
self.assertEqual(client.call.call_count, 1)
|
||||||
|
self.assertIsNotNone(engine.battle_journal.pending(engine.snapshot))
|
||||||
|
restored = Engine(Catalog(), client, path, game_data=data)
|
||||||
|
restored.snapshot = review_snapshot()
|
||||||
|
restored.quest_policy.enabled = True
|
||||||
|
for _ in range(3):
|
||||||
|
_, _, message = restored._run_progression_intent(intent)
|
||||||
|
self.assertIn("核对", message)
|
||||||
|
self.assertEqual(restored.commission_history()["summary"]["accepted_count"], 0)
|
||||||
|
self.assertEqual(restored.commission_history()["summary"]["completed_count"], 0)
|
||||||
|
self.assertEqual(client.call.call_count, 1)
|
||||||
|
|
||||||
|
def test_history_save_failure_recovers_without_replaying_game_request(self):
|
||||||
|
with tempfile.TemporaryDirectory(prefix="commission-storage-review-") as directory:
|
||||||
|
client = Mock()
|
||||||
|
client.call.side_effect = AssertionError("history must never replay a game write")
|
||||||
|
engine = Engine(Catalog(), client, Path(directory) / "budget.json",
|
||||||
|
game_data=ProgressionData({"task_info": {"review20": deepcopy(INFO)}}))
|
||||||
|
engine.snapshot = review_snapshot()
|
||||||
|
engine._commission_history.clock = lambda: NOW
|
||||||
|
engine.battle_journal.role(engine.snapshot)["records"].append(review_record())
|
||||||
|
engine.battle_journal.save()
|
||||||
|
with patch.object(engine._commission_history, "_save", side_effect=PermissionError("synthetic disk error")):
|
||||||
|
engine._sync_commission_history()
|
||||||
|
result = engine.commission_history(DAY)
|
||||||
|
self.assertTrue(result["error"])
|
||||||
|
self.assertEqual(result["summary"]["completed_count"], 1)
|
||||||
|
engine._sync_commission_history()
|
||||||
|
self.assertFalse(engine.commission_history(DAY)["error"])
|
||||||
|
restored = CommissionHistory(engine._commission_history.path, clock=lambda: NOW)
|
||||||
|
self.assertEqual(restored.query("71", DAY)["summary"]["completed_count"], 1)
|
||||||
|
client.call.assert_not_called()
|
||||||
|
|
||||||
|
def test_battle_early_return_cannot_replay_old_commission_success(self):
|
||||||
|
for early_return in ("resources", "cancelled", "lock"):
|
||||||
|
with self.subTest(early_return=early_return), tempfile.TemporaryDirectory(
|
||||||
|
prefix="commission-message-review-") as directory:
|
||||||
|
client = Mock()
|
||||||
|
client.call.side_effect = AssertionError("offline review forbids game writes")
|
||||||
|
client.snapshot.side_effect = AssertionError("offline review forbids game reads")
|
||||||
|
engine = Engine(Catalog(), client, Path(directory) / "budget.json",
|
||||||
|
game_data=ProgressionData({"task_info": {"review20": deepcopy(INFO)}}))
|
||||||
|
engine.snapshot = review_snapshot()
|
||||||
|
engine.quest_policy.enabled = True
|
||||||
|
engine._commission_history.clock = lambda: NOW
|
||||||
|
state = engine.battle_journal.role(engine.snapshot)
|
||||||
|
state["records"].append(review_record())
|
||||||
|
engine.battle_journal.save()
|
||||||
|
engine._sync_commission_history()
|
||||||
|
history_before = engine.commission_history(DAY)
|
||||||
|
journal_before = deepcopy(state["records"])
|
||||||
|
engine.plans = Mock(return_value=[])
|
||||||
|
engine.read_snapshot = Mock(return_value=engine.snapshot)
|
||||||
|
engine._refresh_progression_cache = Mock()
|
||||||
|
engine._intent_policy = Mock(return_value=SimpleNamespace(enabled=True, team="teamA"))
|
||||||
|
intent = {"kind": "progression_battle", "task_id": 82, "task_type_id": "review20",
|
||||||
|
"step_number": 1, "block_reason": ""}
|
||||||
|
if early_return == "resources":
|
||||||
|
expected = "review-resource-shortage"
|
||||||
|
engine.battles.resource_reason = Mock(return_value=expected)
|
||||||
|
elif early_return == "cancelled":
|
||||||
|
expected = "任务 / 战斗已取消,未开始"
|
||||||
|
def cancel_during_preflight(*args):
|
||||||
|
engine._progression_cancel.set()
|
||||||
|
return ""
|
||||||
|
engine.battles.resource_reason = Mock(side_effect=cancel_during_preflight)
|
||||||
|
else:
|
||||||
|
expected = "同账号已有任务 / 战斗正在执行"
|
||||||
|
engine.battles.run = Mock(return_value=expected)
|
||||||
|
with patch.object(engine.battle_journal, "begin", wraps=engine.battle_journal.begin) as begin:
|
||||||
|
_, _, message = engine._run_progression_intent(intent)
|
||||||
|
begin.assert_not_called()
|
||||||
|
client.call.assert_not_called()
|
||||||
|
client.snapshot.assert_not_called()
|
||||||
|
self.assertEqual(state["records"], journal_before)
|
||||||
|
self.assertEqual(engine.commission_history(DAY), history_before)
|
||||||
|
self.assertEqual(message, expected, "a previous confirmed claim must not replace the new blocked message")
|
||||||
|
|
||||||
|
|
||||||
|
class CommissionSelectionIndependentReviewTests(unittest.TestCase):
|
||||||
|
def test_fallback_to_ten_explains_rejected_fifteen_when_twenty_absent(self):
|
||||||
|
tasks = {}
|
||||||
|
for amount in (10, 15):
|
||||||
|
tasks[str(amount)] = deepcopy(INFO) | {"id": str(amount), "name": f"review-{amount}",
|
||||||
|
"closed": amount == 15, "reward": {"ke": amount}}
|
||||||
|
data = {"task_info": tasks, "scripts": {}, "stage_info": {},
|
||||||
|
"game_setting": {"cityInfo": {"1": {}, "2": {}}}}
|
||||||
|
snapshot = review_snapshot()
|
||||||
|
snapshot.raw["history"].update(loopTaskTime=snapshot.now, loopTaskNum=6,
|
||||||
|
loopTask={"1": ["10"], "2": ["15"]}, unlockCity={"1": True, "2": True})
|
||||||
|
planner = ProgressionPlanner(Catalog(), data)
|
||||||
|
actions = planner.commission_plan(snapshot, QuestPolicy(enabled=True), Policy())
|
||||||
|
self.assertEqual(actions[0].task_type_id, "10")
|
||||||
|
self.assertEqual([b["task_type_id"] for b in planner.commission_selection["higher_reward_blockers"]], ["15"])
|
||||||
|
reason = planner.commission_selection["selection_reason"]
|
||||||
|
self.assertIn("review-15", reason)
|
||||||
|
self.assertIn("关闭", reason)
|
||||||
|
self.assertIn("20", reason)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,393 @@
|
|||||||
|
"""Offline task procurement replay: all writes go to the fake below."""
|
||||||
|
from copy import deepcopy
|
||||||
|
from pathlib import Path
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from ranch_assistant.engine import Engine
|
||||||
|
from ranch_assistant.game_data import ProgressionData
|
||||||
|
from ranch_assistant.model import Catalog, Policy, Snapshot
|
||||||
|
from ranch_assistant.progression import ProgressionPlanner, ProgressionPolicy
|
||||||
|
from ranch_assistant.quests import QuestPolicy
|
||||||
|
from ranch_assistant.tests.test_progression import config, snapshot, step, task
|
||||||
|
|
||||||
|
|
||||||
|
EGG = "1030010"
|
||||||
|
|
||||||
|
|
||||||
|
def requirement(kind="getMonster", count=1, key=EGG):
|
||||||
|
return step(kind, statusValue={"type": key, "num": count, "mode": 2 if kind == "getMonster" else 0, "remove": True})
|
||||||
|
|
||||||
|
|
||||||
|
def monster(catalog, mid, **changes):
|
||||||
|
row = catalog.monster(EGG)
|
||||||
|
return {"id": mid, "typeId": int(EGG), "mode": 2, "process": 3, "level": 1, "roomId": 1,
|
||||||
|
**{"g" + stat.capitalize(): row[stat + "_grow_min"] for stat in ("atk", "def", "hp", "dex")}, **changes}
|
||||||
|
|
||||||
|
|
||||||
|
class OfflineProcurementClient:
|
||||||
|
def __init__(self, raw, catalog):
|
||||||
|
self.raw, self.catalog, self.writes = deepcopy(raw), catalog, []
|
||||||
|
self.timeout = False
|
||||||
|
|
||||||
|
def snapshot(self):
|
||||||
|
return Snapshot(deepcopy(self.raw))
|
||||||
|
|
||||||
|
def call(self, path, payload):
|
||||||
|
self.writes.append((path, deepcopy(payload)))
|
||||||
|
if self.timeout:
|
||||||
|
raise TimeoutError("offline fake lost reply")
|
||||||
|
if path == "gachaService/gachaGetEggs":
|
||||||
|
count = payload["num"]
|
||||||
|
self.raw["master"]["money"] -= self.catalog.data["markets"][payload["id"]]["money"] * count
|
||||||
|
existing = next((i for i in self.raw["items"] if str(i["typeId"]) == EGG), None)
|
||||||
|
if existing:
|
||||||
|
existing["num"] += count
|
||||||
|
else:
|
||||||
|
self.raw["items"].append({"id": 500, "typeId": int(EGG), "num": count})
|
||||||
|
return {"resCode": 0, "eggs": [{"typeId": int(EGG), "num": count}]}
|
||||||
|
if path == "stackService/stackAddMonster":
|
||||||
|
for egg in payload["eggs"]:
|
||||||
|
item = next(i for i in self.raw["items"] if i["id"] == egg["itemId"])
|
||||||
|
item["num"] -= 1
|
||||||
|
mid = max([m["id"] for m in self.raw["monsters"]] + [900]) + 1
|
||||||
|
self.raw["monsters"].append(monster(self.catalog, mid, mode=0, process=2,
|
||||||
|
timeStart=self.snapshot().now * 1000, roomId=0))
|
||||||
|
next(s for s in self.raw["stacks"] if s["id"] == egg["stackId"])["monsterId"] = mid
|
||||||
|
return {"resCode": 0}
|
||||||
|
if path == "stackService/stackTransferMonster":
|
||||||
|
for data in payload["datas"]:
|
||||||
|
for mid in data["monsterId"]:
|
||||||
|
next(m for m in self.raw["monsters"] if m["id"] == mid).update(process=3, roomId=data["roomId"])
|
||||||
|
for stack in self.raw["stacks"]:
|
||||||
|
if stack["monsterId"] == mid:
|
||||||
|
stack["monsterId"] = 0
|
||||||
|
return {"resCode": 0}
|
||||||
|
if path == "taskService/taskLoopReceive":
|
||||||
|
received = {"id": 51, "typeId": payload["taskTypeId"], "curStep": 1}
|
||||||
|
self.raw["currentTasks"].append(received)
|
||||||
|
self.raw["history"]["loopTaskNum"] -= 1
|
||||||
|
return {"resCode": 0, "task": deepcopy(received)}
|
||||||
|
if path == "taskService/taskCompleteStep":
|
||||||
|
for mid in payload.get("removeIds") or []:
|
||||||
|
self.raw["monsters"] = [m for m in self.raw["monsters"] if m["id"] != mid]
|
||||||
|
for stack in self.raw["stacks"]:
|
||||||
|
if stack["monsterId"] == mid:
|
||||||
|
stack["monsterId"] = 0
|
||||||
|
next(t for t in self.raw["currentTasks"] if t["id"] == payload["taskId"])["curStep"] += 1
|
||||||
|
return {"resCode": 0, "taskStepValue": None}
|
||||||
|
if path == "taskService/taskComplete":
|
||||||
|
self.raw["currentTasks"] = [t for t in self.raw["currentTasks"] if t["id"] != payload["taskId"]]
|
||||||
|
return {"resCode": 0, "reward": {"ke": 20}}
|
||||||
|
raise AssertionError("Unexpected fake write: " + path)
|
||||||
|
|
||||||
|
|
||||||
|
class CommissionProcurementTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.catalog = Catalog()
|
||||||
|
# Keep a real gold market and real growth/protection rules; make the
|
||||||
|
# offline draw deterministic without asserting real RNG outcomes.
|
||||||
|
self.catalog.data["markets"]["sc_city1"]["eggs"] = {"2": [int(EGG)]}
|
||||||
|
self.tasks = {"400": task("400", type=4, reward={"ke": 20}, steps=[requirement()]),
|
||||||
|
"401": task("401", type=4, reward={"ke": 15})}
|
||||||
|
self.data = ProgressionData(config(self.tasks))
|
||||||
|
self.raw = snapshot(currentTasks=[]).raw
|
||||||
|
self.raw["master"]["money"] = 10000
|
||||||
|
self.raw["history"].update(loopTaskTime=snapshot().now, loopTaskNum=4, loopTask={"2": ["400"], "1": ["401"]}, unlockCity={"1": True, "2": True})
|
||||||
|
self.raw["stacks"] = [{"id": i + 1, "position": i % 3, "monsterId": 0} for i in range(10)]
|
||||||
|
self.quest = QuestPolicy(enabled=True, allow_monsters=True, allow_items=True)
|
||||||
|
self.ranch = Policy(buy=True, allow_single_draw=True, buy_batch=5)
|
||||||
|
self.folder = tempfile.TemporaryDirectory()
|
||||||
|
self.addCleanup(self.folder.cleanup)
|
||||||
|
|
||||||
|
def engine(self, *, raw=None, folder=None):
|
||||||
|
client = OfflineProcurementClient(raw or self.raw, self.catalog)
|
||||||
|
engine = Engine(self.catalog, client, Path(folder or self.folder.name) / "budget.json", game_data=self.data)
|
||||||
|
engine.snapshot = client.snapshot()
|
||||||
|
engine.policy, engine.quest_policy = deepcopy(self.ranch), deepcopy(self.quest)
|
||||||
|
engine._refresh_progression_cache(force=True)
|
||||||
|
self.assertEqual(engine._progression_error, "")
|
||||||
|
return engine, client
|
||||||
|
|
||||||
|
def sync(self, engine, client):
|
||||||
|
engine.snapshot = client.snapshot()
|
||||||
|
engine._refresh_progression_cache(force=True)
|
||||||
|
|
||||||
|
def intent(self, engine):
|
||||||
|
return next(i for i in engine._progression_intents if not i.block_reason)
|
||||||
|
|
||||||
|
def test_cross_city_twenty_buy_hatch_wait_submit_complete_replay(self):
|
||||||
|
engine, client = self.engine()
|
||||||
|
buy = self.intent(engine)
|
||||||
|
self.assertEqual((buy.kind, buy.phase, buy.source_task_type_id), ("progression_procure", "buy", "400"))
|
||||||
|
self.assertEqual(buy.payload["num"], 1)
|
||||||
|
offer = next(r for r in engine.commission_offer_diagnostics() if r["task_type_id"] == "400")
|
||||||
|
self.assertFalse(offer["eligible"])
|
||||||
|
self.assertTrue(offer["preparable"])
|
||||||
|
self.assertEqual(offer["resources"][0]["available"], 0)
|
||||||
|
engine._run_progression_intent(buy)
|
||||||
|
self.assertIsNone(engine.battle_journal.pending(engine.snapshot))
|
||||||
|
hatch = self.intent(engine)
|
||||||
|
self.assertEqual(hatch.phase, "hatch")
|
||||||
|
engine._run_progression_intent(hatch)
|
||||||
|
self.assertEqual(engine.snapshot.raw["history"]["loopTaskNum"], 4)
|
||||||
|
self.assertFalse(any(not i.block_reason for i in engine._progression_intents))
|
||||||
|
for _ in range(3):
|
||||||
|
self.sync(engine, client)
|
||||||
|
self.assertEqual([p for p, _ in client.writes], ["gachaService/gachaGetEggs", "stackService/stackAddMonster"])
|
||||||
|
client.raw["monsters"][0].update(mode=2)
|
||||||
|
self.sync(engine, client)
|
||||||
|
accept = self.intent(engine)
|
||||||
|
self.assertEqual((accept.kind, accept.payload["city"]), ("progression_loop_accept", 2))
|
||||||
|
engine._run_progression_intent(accept)
|
||||||
|
for _ in range(3):
|
||||||
|
engine._run_progression_intent(self.intent(engine))
|
||||||
|
self.assertEqual(engine.commission_history()["summary"]["confirmed_ke"], 20)
|
||||||
|
self.assertEqual(client.raw["history"]["loopTaskNum"], 3)
|
||||||
|
|
||||||
|
def test_one_missing_ten_empty_slots_thousand_eggs_hatches_only_one(self):
|
||||||
|
self.raw["items"] = [{"id": 500, "typeId": int(EGG), "num": 1000}]
|
||||||
|
engine, client = self.engine()
|
||||||
|
intent = self.intent(engine)
|
||||||
|
self.assertEqual(len(intent.payload["eggs"]), 1)
|
||||||
|
engine._run_progression_intent(intent)
|
||||||
|
self.assertEqual(sum(bool(s["monsterId"]) for s in client.raw["stacks"]), 1)
|
||||||
|
self.assertEqual(client.raw["items"][0]["num"], 999)
|
||||||
|
self.assertFalse(any(not i.block_reason for i in engine._progression_intents))
|
||||||
|
self.assertFalse(any(a.kind in ("buy", "hatch") for a in engine.plans()))
|
||||||
|
self.assertEqual(engine.pending_hatches, [])
|
||||||
|
|
||||||
|
def test_quota_zero_never_procures_or_accepts(self):
|
||||||
|
self.raw["history"]["loopTaskNum"] = 0
|
||||||
|
engine, client = self.engine()
|
||||||
|
engine._run_progression_intent()
|
||||||
|
self.assertEqual(client.writes, [])
|
||||||
|
self.assertTrue(all(r["reason_kind"] == "quota" and not r["preparable"] for r in engine.commission_offer_diagnostics()))
|
||||||
|
|
||||||
|
def test_existing_eggs_and_incubator_count_before_buy(self):
|
||||||
|
self.tasks["400"]["steps"] = [requirement(count=3)]
|
||||||
|
self.raw["items"] = [{"id": 500, "typeId": int(EGG), "num": 1}]
|
||||||
|
self.raw["monsters"] = [monster(self.catalog, 901, mode=0, process=2, timeStart=snapshot().now * 1000)]
|
||||||
|
self.raw["stacks"][0]["monsterId"] = 901
|
||||||
|
engine, client = self.engine()
|
||||||
|
engine._run_progression_intent(self.intent(engine)) # reuse the egg
|
||||||
|
buy = self.intent(engine)
|
||||||
|
self.assertEqual(buy.phase, "buy")
|
||||||
|
self.assertEqual(buy.payload["num"], 1)
|
||||||
|
engine._run_progression_intent(buy)
|
||||||
|
self.assertEqual(sum(p == "gachaService/gachaGetEggs" for p, _ in client.writes), 1)
|
||||||
|
|
||||||
|
def test_shared_eggs_user_reserve_and_multistep_demands_are_not_double_counted(self):
|
||||||
|
self.tasks["400"]["steps"] = [requirement("getItem", 1), requirement("getItem", 1), requirement(count=1)]
|
||||||
|
self.raw["items"] = [{"id": 500, "typeId": int(EGG), "num": 5}]
|
||||||
|
self.ranch.reserved_eggs = {EGG: 2}
|
||||||
|
engine, client = self.engine()
|
||||||
|
self.assertEqual(self.intent(engine).phase, "hatch")
|
||||||
|
engine._run_progression_intent(self.intent(engine))
|
||||||
|
self.assertEqual(client.raw["items"][0]["num"], 4) # 2 task eggs + 2 user reserve
|
||||||
|
self.assertFalse(any(not i.block_reason for i in engine._progression_intents))
|
||||||
|
self.assertFalse(any(path == "gachaService/gachaGetEggs" for path, _ in client.writes))
|
||||||
|
|
||||||
|
def test_multistep_adult_removals_cannot_reuse_one_monster(self):
|
||||||
|
self.tasks["400"]["steps"] = [requirement(), requirement()]
|
||||||
|
self.raw["monsters"] = [monster(self.catalog, 901)]
|
||||||
|
engine, _ = self.engine()
|
||||||
|
buy = self.intent(engine)
|
||||||
|
self.assertEqual(buy.payload["num"], 1)
|
||||||
|
self.assertEqual(engine.commission_offer_diagnostics()[0]["resources"][0]["needed"], 2)
|
||||||
|
|
||||||
|
def test_active_same_species_steps_buy_remaining_deficit_and_advance(self):
|
||||||
|
self.tasks["400"]["steps"] = [requirement(), requirement()]
|
||||||
|
for cursor in (1, 2):
|
||||||
|
with self.subTest(cursor=cursor), tempfile.TemporaryDirectory(dir=self.folder.name) as folder:
|
||||||
|
raw = deepcopy(self.raw)
|
||||||
|
raw["currentTasks"] = [{"id": 51, "typeId": "400", "curStep": cursor}]
|
||||||
|
engine, client = self.engine(raw=raw, folder=folder)
|
||||||
|
deficit = 3 - cursor
|
||||||
|
buy = self.intent(engine)
|
||||||
|
self.assertEqual((buy.kind, buy.phase, buy.source_task_id), ("progression_procure", "buy", 51))
|
||||||
|
self.assertEqual(buy.payload["num"], deficit)
|
||||||
|
engine._run_progression_intent(buy)
|
||||||
|
self.assertEqual(client.writes, [("gachaService/gachaGetEggs", buy.payload)])
|
||||||
|
self.assertIsNone(engine.battle_journal.pending(engine.snapshot))
|
||||||
|
for _ in range(deficit):
|
||||||
|
hatch = self.intent(engine)
|
||||||
|
self.assertEqual((hatch.kind, hatch.phase), ("progression_procure", "hatch"))
|
||||||
|
engine._run_progression_intent(hatch)
|
||||||
|
self.assertIsNone(engine.battle_journal.pending(engine.snapshot))
|
||||||
|
for _ in range(3):
|
||||||
|
engine._run_progression_intent()
|
||||||
|
self.assertEqual(len(client.writes), 1 + deficit)
|
||||||
|
self.assertEqual(client.raw["currentTasks"][0]["curStep"], cursor)
|
||||||
|
for growing in client.raw["monsters"]:
|
||||||
|
growing["mode"] = 2
|
||||||
|
self.sync(engine, client)
|
||||||
|
submitted = []
|
||||||
|
for number in range(cursor, 3):
|
||||||
|
submit = self.intent(engine)
|
||||||
|
self.assertEqual((submit.kind, submit.step_number), ("progression_step", number))
|
||||||
|
submitted.extend(submit.payload["removeIds"])
|
||||||
|
engine._run_progression_intent(submit)
|
||||||
|
self.assertEqual(client.raw["currentTasks"][0]["curStep"], number + 1)
|
||||||
|
local = self.intent(engine)
|
||||||
|
self.assertEqual(local.kind, "progression_local_step")
|
||||||
|
engine._run_progression_intent(local)
|
||||||
|
self.assertEqual(len(set(submitted)), deficit)
|
||||||
|
complete = self.intent(engine)
|
||||||
|
self.assertEqual(complete.kind, "progression_complete")
|
||||||
|
engine._run_progression_intent(complete)
|
||||||
|
purchases = [payload["num"] for path, payload in client.writes if path == "gachaService/gachaGetEggs"]
|
||||||
|
self.assertEqual(purchases, [deficit])
|
||||||
|
self.assertEqual(client.raw["currentTasks"], [])
|
||||||
|
self.assertEqual(client.raw["history"]["loopTaskNum"], 4)
|
||||||
|
self.assertEqual(engine.commission_history()["summary"]["confirmed_ke"], 20)
|
||||||
|
|
||||||
|
def test_active_procurement_keeps_future_handin_money_in_both_checks(self):
|
||||||
|
handin = 500
|
||||||
|
self.tasks["400"]["steps"] = [requirement(count=2),
|
||||||
|
step("getMoney", statusValue={"money": handin, "remove": True})]
|
||||||
|
self.raw["currentTasks"] = [{"id": 51, "typeId": "400", "curStep": 1}]
|
||||||
|
self.quest.max_money = handin
|
||||||
|
price = self.catalog.data["markets"]["sc_city1"]["money"]
|
||||||
|
self.raw["master"]["money"] = self.ranch.keep_money + handin + price
|
||||||
|
engine, client = self.engine()
|
||||||
|
buy = self.intent(engine)
|
||||||
|
self.assertEqual((buy.kind, buy.phase, buy.payload["num"]), ("progression_procure", "buy", 1))
|
||||||
|
engine._run_progression_intent(buy)
|
||||||
|
self.assertEqual(client.writes, [("gachaService/gachaGetEggs", buy.payload)])
|
||||||
|
self.assertEqual(client.raw["master"]["money"], self.ranch.keep_money + handin)
|
||||||
|
self.assertIsNone(engine.battle_journal.pending(engine.snapshot))
|
||||||
|
self.assertEqual(client.raw["currentTasks"][0]["curStep"], 1)
|
||||||
|
|
||||||
|
def test_protected_duplicates_are_reported_and_not_submitted(self):
|
||||||
|
self.raw["monsters"] = [monster(self.catalog, 1, lock=True), monster(self.catalog, 2),
|
||||||
|
monster(self.catalog, 3), monster(self.catalog, 4)]
|
||||||
|
self.raw["teams"] = [{"name": "teamA", "monsters": [2]}]
|
||||||
|
self.ranch.feed_targets = {"3": 1}
|
||||||
|
engine, client = self.engine()
|
||||||
|
info = self.data.task("400")
|
||||||
|
ready, ids, reason = engine.progression_planner.requirement(engine.snapshot, info["steps"][0], {},
|
||||||
|
engine._intent_policy({"task_type_id": "400"}), engine.policy)
|
||||||
|
self.assertTrue(ready)
|
||||||
|
self.assertEqual(ids, [4])
|
||||||
|
self.assertIn("保护3", reason)
|
||||||
|
self.assertIn("已锁定", reason)
|
||||||
|
engine._run_progression_intent(self.intent(engine))
|
||||||
|
engine._run_progression_intent(self.intent(engine))
|
||||||
|
self.assertEqual({m["id"] for m in client.raw["monsters"]}, {1, 2, 3})
|
||||||
|
|
||||||
|
def test_protected_star_species_cannot_be_procured_by_unprotecting(self):
|
||||||
|
self.ranch.protect_star = 2
|
||||||
|
engine, client = self.engine()
|
||||||
|
row = engine.commission_offer_diagnostics()[0]
|
||||||
|
self.assertFalse(row["eligible"] or row["preparable"])
|
||||||
|
self.assertIn("新孵魔物也受", row["reason"])
|
||||||
|
self.assertFalse(any(i.kind == "progression_procure" for i in engine._progression_intents))
|
||||||
|
self.assertEqual(client.writes, [])
|
||||||
|
|
||||||
|
def test_coin_reserve_daily_budget_and_ten_draw_rule_remain_enforced(self):
|
||||||
|
for changes in ({"daily_buy_money": 0}, {"keep_money": 10000}, {"allow_single_draw": False}):
|
||||||
|
with self.subTest(changes=changes):
|
||||||
|
self.ranch = Policy(buy=True, allow_single_draw=True, **{k: v for k, v in changes.items() if k != "allow_single_draw"})
|
||||||
|
if "allow_single_draw" in changes:
|
||||||
|
self.ranch.allow_single_draw = False
|
||||||
|
engine, client = self.engine()
|
||||||
|
self.assertFalse(any(i.kind == "progression_procure" for i in engine._progression_intents))
|
||||||
|
self.assertEqual(client.writes, [])
|
||||||
|
|
||||||
|
def test_stop_and_changed_offer_cancel_before_dispatch(self):
|
||||||
|
for change in (lambda e: e.cancel_progression(), lambda e: e.snapshot.raw["history"].update(loopTaskNum=0),
|
||||||
|
lambda e: e.snapshot.raw["history"].update(loopTask={}),
|
||||||
|
lambda e: e.snapshot.raw["currentTasks"].append({"id": 52, "typeId": "401", "curStep": 1})):
|
||||||
|
with self.subTest(change=change):
|
||||||
|
engine, client = self.engine()
|
||||||
|
intent = self.intent(engine)
|
||||||
|
original = engine._journal_commission
|
||||||
|
def change_before_dispatch(record, incoming):
|
||||||
|
original(record, incoming)
|
||||||
|
change(engine)
|
||||||
|
with patch.object(engine, "_journal_commission", side_effect=change_before_dispatch):
|
||||||
|
engine._execute_procurement(intent)
|
||||||
|
self.assertEqual(client.writes, [])
|
||||||
|
self.assertIsNone(engine.battle_journal.pending(engine.snapshot))
|
||||||
|
|
||||||
|
def test_active_task_changed_before_dispatch_is_cancelled(self):
|
||||||
|
self.raw["currentTasks"] = [{"id": 51, "typeId": "400", "curStep": 1}]
|
||||||
|
engine, client = self.engine()
|
||||||
|
intent = self.intent(engine)
|
||||||
|
original = engine._journal_commission
|
||||||
|
def replace_task(record, incoming):
|
||||||
|
original(record, incoming)
|
||||||
|
engine.snapshot.raw["currentTasks"] = [{"id": 52, "typeId": "400", "curStep": 1}]
|
||||||
|
with patch.object(engine, "_journal_commission", side_effect=replace_task):
|
||||||
|
engine._execute_procurement(intent)
|
||||||
|
self.assertEqual(client.writes, [])
|
||||||
|
self.assertIsNone(engine.battle_journal.pending(engine.snapshot))
|
||||||
|
|
||||||
|
def test_hard_prerequisite_is_not_misreported_as_preparable(self):
|
||||||
|
self.tasks["400"]["steps"][0]["condition"] = {"finishTask": ["999"]}
|
||||||
|
engine, client = self.engine()
|
||||||
|
row = engine.commission_offer_diagnostics()[0]
|
||||||
|
self.assertFalse(row["eligible"] or row["preparable"])
|
||||||
|
self.assertEqual(row["reason_kind"], "prerequisite")
|
||||||
|
self.assertFalse(any(i.kind == "progression_procure" for i in engine._progression_intents))
|
||||||
|
self.assertEqual(client.writes, [])
|
||||||
|
|
||||||
|
def test_ten_draw_cost_uses_verified_unit_price_without_fictitious_discount(self):
|
||||||
|
self.tasks["400"]["steps"] = [requirement(count=10)]
|
||||||
|
price = self.catalog.data["markets"]["sc_city1"]["money"]
|
||||||
|
self.ranch.daily_buy_money = price * 10
|
||||||
|
self.raw["master"]["money"] = self.ranch.keep_money + price * 10
|
||||||
|
engine, _ = self.engine()
|
||||||
|
buy = self.intent(engine)
|
||||||
|
self.assertEqual(buy.payload["num"], 10)
|
||||||
|
engine._run_progression_intent(buy)
|
||||||
|
self.assertEqual(engine.purchase_budget.spent(engine.snapshot.now), price * 10)
|
||||||
|
|
||||||
|
def test_unknown_buy_survives_restart_and_account_isolation(self):
|
||||||
|
engine, client = self.engine()
|
||||||
|
client.timeout = True
|
||||||
|
with self.assertRaises(TimeoutError):
|
||||||
|
engine._execute_procurement(self.intent(engine))
|
||||||
|
self.assertEqual(len(client.writes), 1)
|
||||||
|
restored, second = self.engine()
|
||||||
|
restored._run_progression_intent()
|
||||||
|
self.assertEqual(second.writes, [])
|
||||||
|
self.assertIsNotNone(restored.battle_journal.pending(restored.snapshot))
|
||||||
|
other = deepcopy(self.raw)
|
||||||
|
other["master"]["id"] = 2
|
||||||
|
isolated, _ = self.engine(raw=other)
|
||||||
|
self.assertIsNone(isolated.battle_journal.pending(isolated.snapshot))
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
isolated._execute_procurement(self.intent(engine))
|
||||||
|
|
||||||
|
def test_mainline_confirmed_unlock_changes_offer_eligibility(self):
|
||||||
|
self.tasks["100"] = task("100", steps=[step()])
|
||||||
|
data = config(self.tasks)
|
||||||
|
data["game_setting"]["cityInfo"]["2"] = {"name": "测试城", "openTask": "100"}
|
||||||
|
planner = ProgressionPlanner(self.catalog, data)
|
||||||
|
raw = deepcopy(self.raw)
|
||||||
|
raw["history"]["unlockCity"]["2"] = False
|
||||||
|
raw["currentTasks"] = [{"id": 11, "typeId": "100", "curStep": 2}]
|
||||||
|
raw["monsters"] = [monster(self.catalog, 901)]
|
||||||
|
snap = Snapshot(raw)
|
||||||
|
before = planner.commission_offers(snap, self.quest, self.ranch)[0]
|
||||||
|
self.assertEqual(before["reason_kind"], "city_locked")
|
||||||
|
self.assertIn("测试城", before["reason"])
|
||||||
|
finish = planner.plan(snap, ProgressionPolicy(enabled=True), self.ranch)[0]
|
||||||
|
planner.acknowledge(snap, finish, {"reward": {}})
|
||||||
|
self.assertTrue(planner.commission_offers(snap, self.quest, self.ranch)[0]["eligible"])
|
||||||
|
|
||||||
|
def test_material_shortage_uses_real_supported_sweep_source(self):
|
||||||
|
self.tasks["400"]["steps"] = [requirement("getItem", 3, "30054")]
|
||||||
|
data = config(self.tasks, farming={"items": {"30054": [{"stage_id": "0101", "difficulty": 1}]}})
|
||||||
|
self.raw["history"]["passStage"] = {"0101": [1, 2, 3]}
|
||||||
|
planner = ProgressionPlanner(self.catalog, data)
|
||||||
|
actions = planner.commission_plan(Snapshot(self.raw), self.quest, self.ranch)
|
||||||
|
self.assertEqual(actions[0].kind, "sweep")
|
||||||
|
self.assertEqual(actions[0].source_task_type_id, "400")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
"""Offline coverage-tool regressions against the packaged original task data."""
|
||||||
|
from copy import deepcopy
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import tempfile
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
import sys
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from ranch_assistant.game_data import load_progression_data
|
||||||
|
from tools import check_progression_support as support
|
||||||
|
|
||||||
|
|
||||||
|
class ProgressionSupportTests(unittest.TestCase):
|
||||||
|
@classmethod
|
||||||
|
def setUpClass(cls):
|
||||||
|
cls.data = load_progression_data()
|
||||||
|
cls.cases = support.collect_cases(cls.data)
|
||||||
|
cls.priority = next(case for case in cls.cases if case.task == "1002013")
|
||||||
|
|
||||||
|
def test_every_mainline_and_commission_battle_step_is_resolved(self):
|
||||||
|
expected = {(str(key), number, step["statusType"])
|
||||||
|
for key, task in self.data.tasks.items() if task.get("type") in (1, 4)
|
||||||
|
for number, step in enumerate(task.get("steps") or (), 1)
|
||||||
|
if step.get("statusType") in ("battle", "passStage")}
|
||||||
|
self.assertEqual({(case.task, case.step, case.step_type) for case in self.cases}, expected)
|
||||||
|
self.assertEqual(len(self.cases), len(expected))
|
||||||
|
self.assertEqual({(case.task_type, case.step_type) for case in self.cases},
|
||||||
|
{(1, "battle"), (1, "passStage"), (4, "battle"), (4, "passStage")})
|
||||||
|
self.assertTrue(all(isinstance(case.battle, dict) and case.battle for case in self.cases))
|
||||||
|
|
||||||
|
def test_priority_task_uses_original_0216_level_one_configuration(self):
|
||||||
|
self.assertEqual((self.priority.task_type, self.priority.step, self.priority.step_type), (1, 1, "passStage"))
|
||||||
|
step = self.data.task("1002013")["steps"][0]
|
||||||
|
self.assertEqual(step["statusValue"], {"stage": "0216", "level": "1"})
|
||||||
|
self.assertEqual(self.priority.battle, self.data.stage_battle("0216", "1"))
|
||||||
|
self.assertEqual(self.priority.battle, self.data.task_battle("1002013", 1))
|
||||||
|
features = support.mechanics(self.priority.battle)
|
||||||
|
for reason in ("trigger:monDead", "trigger_effect:unlockWave", "unit_controller:monMaker",
|
||||||
|
"unit_controller:monSteps", "unit_controller:skill"):
|
||||||
|
self.assertGreater(features[reason], 0)
|
||||||
|
|
||||||
|
def test_structural_hotspots_count_configurations_separately_from_occurrences(self):
|
||||||
|
report = support.source_scan(self.cases)
|
||||||
|
self.assertEqual(report["count"], len(self.cases))
|
||||||
|
self.assertEqual(sum(row["count"] for row in report["counts"]), len(self.cases))
|
||||||
|
affected = {row["reason"]: row["count"] for row in report["mechanics"]}
|
||||||
|
occurrences = {row["reason"]: row["count"] for row in report["occurrences"]}
|
||||||
|
self.assertGreater(affected["unit_controller:hpArea"], 0)
|
||||||
|
self.assertGreater(occurrences["unit_controller:hpArea"], affected["unit_controller:hpArea"])
|
||||||
|
# Source mechanics are descriptive; they cannot themselves deny quick input.
|
||||||
|
self.assertNotIn("support", report)
|
||||||
|
|
||||||
|
def test_fixture_and_requests_preserve_original_source_and_roster(self):
|
||||||
|
roster = support.fixture_roster()
|
||||||
|
before = deepcopy((roster, self.priority.battle))
|
||||||
|
request = support.make_request(self.priority, roster)
|
||||||
|
self.assertEqual(request["context"], "task_pass_stage")
|
||||||
|
self.assertEqual(request["battle_position"], {"battleType": "task", "taskTypeId": "1002013", "taskStep": 0})
|
||||||
|
self.assertEqual(request["damage_profile"], "client_v4_x10")
|
||||||
|
self.assertEqual(support.make_request(self.priority, roster, damage_profile="original_1x")["damage_profile"],
|
||||||
|
"original_1x")
|
||||||
|
self.assertEqual(request["trace_limit"], 0)
|
||||||
|
self.assertIs(request["original_data"]["battle"], self.priority.battle)
|
||||||
|
self.assertEqual(roster["monsters"][0]["level"], 20)
|
||||||
|
self.assertEqual((roster, self.priority.battle), before)
|
||||||
|
|
||||||
|
def test_bounded_case_selection_includes_actual_protection_and_commission(self):
|
||||||
|
cases = support.representative_cases(self.cases, support.MAX_RUNS)
|
||||||
|
self.assertEqual(cases[0], self.priority)
|
||||||
|
self.assertEqual(len(cases), len({(case.task, case.step) for case in cases}))
|
||||||
|
self.assertTrue(any("objective:protectTarget" in support.mechanics(case.battle) for case in cases))
|
||||||
|
self.assertTrue(any(case.task_type == 4 and case.step_type == "battle" for case in cases))
|
||||||
|
self.assertTrue(any(case.task_type == 4 and case.step_type == "passStage" for case in cases))
|
||||||
|
self.assertEqual(support.representative_cases(self.cases, 0), [])
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
support.representative_cases(self.cases, support.MAX_RUNS + 1)
|
||||||
|
|
||||||
|
def test_snapshot_loader_drops_identity_envelope_and_sanitizes_failures(self):
|
||||||
|
raw = support.fixture_roster()
|
||||||
|
raw.update(token="private-token-canary", account="private-account-canary")
|
||||||
|
raw["master"].update(id=987654321, nickname="private-nickname-canary")
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
path = Path(directory) / "private-path-canary.json"
|
||||||
|
path.write_text(json.dumps({"raw": raw}), encoding="utf-8")
|
||||||
|
loaded = support.load_snapshot(path)
|
||||||
|
self.assertEqual(loaded, support.fixture_roster())
|
||||||
|
path.write_text('{"token":"private-token-canary",broken', encoding="utf-8")
|
||||||
|
with self.assertRaisesRegex(ValueError, "^snapshot_load_failed$"):
|
||||||
|
support.load_snapshot(path)
|
||||||
|
with self.assertRaisesRegex(ValueError, "^snapshot_load_failed$"):
|
||||||
|
support.load_snapshot(path.with_suffix(".missing"))
|
||||||
|
|
||||||
|
def test_reports_keep_anomaly_counts_separate_from_input_support(self):
|
||||||
|
private = "private-result-canary"
|
||||||
|
raw = {"supported": True, "outcome": "loss", "elapsed_ms": 420,
|
||||||
|
"reasons": [], "units": [{"id": private}], "battle_data": {"monsterIds": [private]},
|
||||||
|
"anomalies": [{"code": "+15overpoten", "monsterId": private}] * 4,
|
||||||
|
"token": private, "events": [{"message": private}]}
|
||||||
|
result = support.result_summary(raw)
|
||||||
|
self.assertTrue(result["support"])
|
||||||
|
self.assertEqual(result["outcome"], "loss")
|
||||||
|
self.assertEqual(result["counts"], [{"reason": "anomaly:+15overpoten", "count": 4}])
|
||||||
|
self.assertNotIn(private, json.dumps(result))
|
||||||
|
raw.update(supported=False, reasons=[private], outcome=private)
|
||||||
|
raw["anomalies"] = [{"code": private}]
|
||||||
|
result = support.result_summary(raw)
|
||||||
|
self.assertNotIn(private, json.dumps(result))
|
||||||
|
self.assertEqual(result["reason"], ["input_or_model_failure"])
|
||||||
|
self.assertEqual(result["outcome"], "error")
|
||||||
|
|
||||||
|
def test_inspection_cancellation_and_deadline_do_not_run_the_model(self):
|
||||||
|
runtime = unittest.mock.Mock()
|
||||||
|
stop = threading.Event()
|
||||||
|
stop.set()
|
||||||
|
cancelled = support.inspect_inputs(self.cases, runtime, cancel_event=stop)
|
||||||
|
self.assertEqual(cancelled["reason"], ["cancelled"])
|
||||||
|
expired = support.inspect_inputs(self.cases, runtime, deadline=time.monotonic() - 1)
|
||||||
|
self.assertEqual(expired["reason"], ["budget_exhausted"])
|
||||||
|
runtime.inspect.assert_not_called()
|
||||||
|
runtime.run.assert_not_called()
|
||||||
|
|
||||||
|
def test_private_model_output_and_exceptions_are_not_logged(self):
|
||||||
|
private = "private-runtime-canary"
|
||||||
|
runtime = unittest.mock.Mock()
|
||||||
|
|
||||||
|
def run(request, **kwargs):
|
||||||
|
print(private)
|
||||||
|
print(private, file=sys.stderr)
|
||||||
|
raise ValueError(private)
|
||||||
|
|
||||||
|
runtime.run.side_effect = run
|
||||||
|
stdout, stderr = io.StringIO(), io.StringIO()
|
||||||
|
with patch.object(sys, "stdout", stdout), patch.object(sys, "stderr", stderr):
|
||||||
|
rows = support.replay_cases([self.priority], runtime, support.fixture_roster())
|
||||||
|
self.assertEqual((stdout.getvalue(), stderr.getvalue()), ("", ""))
|
||||||
|
self.assertNotIn(private, json.dumps(rows))
|
||||||
|
self.assertEqual(rows[0]["outcome"], "error")
|
||||||
|
self.assertEqual(rows[0]["reason"], ["model_execution_failed"])
|
||||||
|
|
||||||
|
def test_replay_uses_web_profile_and_wire_step_without_changing_a_loss(self):
|
||||||
|
runtime = unittest.mock.Mock()
|
||||||
|
runtime.run.return_value = {"supported": True, "outcome": "loss", "elapsed_ms": 1000,
|
||||||
|
"reasons": [], "anomalies": []}
|
||||||
|
rows = support.replay_cases([self.priority], runtime, support.fixture_roster())
|
||||||
|
self.assertEqual(rows[0]["outcome"], "loss")
|
||||||
|
request = runtime.run.call_args.args[0]
|
||||||
|
self.assertEqual(request["damage_profile"], "client_v4_x10")
|
||||||
|
self.assertEqual(request["battle_position"]["taskStep"], 0)
|
||||||
|
self.assertLessEqual(runtime.run.call_args.kwargs["timeout"], 1)
|
||||||
|
|
||||||
|
def test_structure_only_cli_never_imports_or_runs_a_model(self):
|
||||||
|
stdout = io.StringIO()
|
||||||
|
with patch.object(support, "collect_cases", return_value=self.cases), \
|
||||||
|
patch.object(sys, "stdout", stdout), \
|
||||||
|
patch.object(support.importlib, "import_module", side_effect=AssertionError("model import")):
|
||||||
|
self.assertEqual(support.main(["--structure-only"]), 0)
|
||||||
|
report = json.loads(stdout.getvalue())
|
||||||
|
self.assertEqual(report["source"]["count"], len(self.cases))
|
||||||
|
self.assertLessEqual(len(report["source"]["mechanics"]), support.TOP)
|
||||||
|
|
||||||
|
def test_quick_input_counts_follow_current_model_over_the_original_corpus(self):
|
||||||
|
from ranch_assistant import battle_simulator
|
||||||
|
runtime = support.quick_runtime()
|
||||||
|
with patch.object(battle_simulator, "simulate", side_effect=AssertionError("detailed model")):
|
||||||
|
report = support.inspect_inputs(self.cases, runtime)
|
||||||
|
self.assertEqual(report["reason"], [])
|
||||||
|
self.assertEqual(report["count"], len(self.cases))
|
||||||
|
self.assertEqual(sum(row["count"] for row in report["counts"]), len(self.cases))
|
||||||
|
self.assertTrue(report["priority"][0]["support"])
|
||||||
|
# Numeric inputs can remain unsupported. Never freeze an all-supported total.
|
||||||
|
blocked = [row for row in report["rows"] if not row["support"]]
|
||||||
|
self.assertTrue(all(row["reason"] for row in blocked))
|
||||||
|
self.assertEqual(len(blocked), sum(row["count"] for row in report["counts"] if not row["support"]))
|
||||||
|
|
||||||
|
def test_original_priority_and_protection_cases_have_fast_natural_results(self):
|
||||||
|
from ranch_assistant import battle_simulator
|
||||||
|
protection = next(case for case in self.cases if case.task == "1002002" and case.step == 2)
|
||||||
|
roster = support.fixture_roster()
|
||||||
|
before = deepcopy((roster, self.priority.battle, protection.battle))
|
||||||
|
with patch.object(battle_simulator, "simulate", side_effect=AssertionError("detailed model")):
|
||||||
|
rows = support.replay_cases([self.priority, protection], support.quick_runtime(), roster)
|
||||||
|
self.assertEqual([row["outcome"] for row in rows], ["loss", "win"])
|
||||||
|
self.assertTrue(all(row["support"] for row in rows))
|
||||||
|
self.assertTrue(all(0 < row["wall_ms"] < 1000 for row in rows))
|
||||||
|
self.assertTrue(all(row["elapsed_ms"] > 0 for row in rows))
|
||||||
|
self.assertEqual((roster, self.priority.battle, protection.battle), before)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
"""Offline cultivation-bound checks using public tables and synthetic monsters."""
|
||||||
|
from copy import deepcopy
|
||||||
|
from types import SimpleNamespace
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from ranch_assistant.battle_simulator import _snapshot_anomalies, combat_tables
|
||||||
|
|
||||||
|
|
||||||
|
class SnapshotPotentialAnomalyTests(unittest.TestCase):
|
||||||
|
def snapshot(self, *, species=5208010, **changes):
|
||||||
|
tables = combat_tables()
|
||||||
|
row = tables["monster_info"][str(species)]
|
||||||
|
mon = {"id": 100001, "typeId": species, "level": 1, "potentialLevel": 3,
|
||||||
|
"tpLevel": 0, "feel": 0, "upStar": 0,
|
||||||
|
"pAtk": 0, "pDef": 0, "pHp": 0, "pDex": 0}
|
||||||
|
mon.update(changes)
|
||||||
|
unit = SimpleNamespace(key="player-1", species=species,
|
||||||
|
stats=SimpleNamespace(atk=row["atk"], defense=row["def"],
|
||||||
|
hp=row["hp"], dex=row["dex"]))
|
||||||
|
return mon, unit, tables
|
||||||
|
|
||||||
|
def test_cultivated_potential_at_zero_tp_is_valid(self):
|
||||||
|
# PotentialPanel.as:102,245: job=1, star=5, potentialLevel=3
|
||||||
|
# permits atk=64, def=58, hp=510, dex=22, independently of tpLevel.
|
||||||
|
mon, unit, tables = self.snapshot(pAtk=38, pDef=44, pHp=300, pDex=22)
|
||||||
|
before = deepcopy((mon, unit))
|
||||||
|
self.assertEqual(_snapshot_anomalies(mon, unit, tables), [])
|
||||||
|
self.assertEqual((mon, unit), before)
|
||||||
|
|
||||||
|
def test_all_four_excesses_keep_blocking_records(self):
|
||||||
|
# Preserve the existing strict > 1.5 * cultivation-cap check.
|
||||||
|
mon, unit, tables = self.snapshot(pAtk=97, pDef=88, pHp=766, pDex=34)
|
||||||
|
before = deepcopy((mon, unit))
|
||||||
|
records = _snapshot_anomalies(mon, unit, tables)
|
||||||
|
self.assertEqual([r["code"] for r in records], ["+15overpoten"] * 4)
|
||||||
|
self.assertEqual({r["stat"]: (r["value"], r["source_maximum"]) for r in records},
|
||||||
|
{"atk": (97, 96), "def": (88, 87),
|
||||||
|
"hp": (766, 765), "dex": (34, 33)})
|
||||||
|
self.assertTrue(all(r["source_cheat_points"] == 30 for r in records))
|
||||||
|
self.assertEqual((mon, unit), before)
|
||||||
|
|
||||||
|
def test_tp_and_display_star_cannot_hide_uncultivated_excess(self):
|
||||||
|
for tp in (0, 4, 8):
|
||||||
|
with self.subTest(tp=tp):
|
||||||
|
mon, unit, tables = self.snapshot(potentialLevel=1, tpLevel=tp,
|
||||||
|
upStar=2, pAtk=19)
|
||||||
|
records = _snapshot_anomalies(mon, unit, tables)
|
||||||
|
self.assertEqual(len(records), 1)
|
||||||
|
self.assertEqual(records[0]["code"], "+15overpoten")
|
||||||
|
self.assertEqual(records[0]["source_maximum"], 18)
|
||||||
|
|
||||||
|
def test_existing_tolerance_boundary_is_preserved(self):
|
||||||
|
mon, unit, tables = self.snapshot(pAtk=96, pDef=87, pHp=765, pDex=33)
|
||||||
|
self.assertEqual(_snapshot_anomalies(mon, unit, tables), [])
|
||||||
|
mon["pDex"] = 33.25
|
||||||
|
records = _snapshot_anomalies(mon, unit, tables)
|
||||||
|
self.assertEqual(len(records), 1)
|
||||||
|
self.assertEqual(records[0]["value"], 33.25)
|
||||||
|
|
||||||
|
def test_other_source_anomalies_and_temporary_id_exemption_remain(self):
|
||||||
|
mon, unit, tables = self.snapshot(level=31, feel=201, pAtk=1000000)
|
||||||
|
unit.stats.atk = 1000000
|
||||||
|
before = deepcopy((mon, unit))
|
||||||
|
records = _snapshot_anomalies(mon, unit, tables)
|
||||||
|
self.assertEqual({r["code"] for r in records},
|
||||||
|
{"+15overfeel", "+15overgrow", "+15overpoten", "+50overlv"})
|
||||||
|
self.assertEqual((mon, unit), before)
|
||||||
|
mon["id"] = 99998
|
||||||
|
self.assertEqual(_snapshot_anomalies(mon, unit, tables), [])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,291 @@
|
|||||||
|
"""Hidden sweep handoff/recovery regressions; every game operation is mocked."""
|
||||||
|
from copy import deepcopy
|
||||||
|
import threading
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import Mock
|
||||||
|
|
||||||
|
from ranch_assistant.battles import BattleJournal, BattleOrchestrator
|
||||||
|
from ranch_assistant.sweeping import SweepRunner
|
||||||
|
from ranch_assistant.tests.test_battle_orchestration import ExperimentalRuntime, fixture, intent, policy
|
||||||
|
from ranch_assistant.tests.test_core import workspace_temp
|
||||||
|
|
||||||
|
|
||||||
|
class HiddenSweepBattleTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.folder = self.enterContext(workspace_temp())
|
||||||
|
self.catalog, self.snapshot = fixture()
|
||||||
|
self.snapshot.raw["history"]["passStage"] = {"0101": [1, 2, 3]}
|
||||||
|
self.runtime = ExperimentalRuntime()
|
||||||
|
self.client = Mock()
|
||||||
|
self.start = {"resCode": 0, "triggerEvent": True,
|
||||||
|
"stageEvent": {"hideStageId": "0102", "result": {"money": 999}, "costTi": 99}}
|
||||||
|
self.client.call.side_effect = lambda path, payload: deepcopy(self.start) if path.endswith("stageStart") else {
|
||||||
|
"resCode": 0, "reward": {"money": 17}, "costTi": 6}
|
||||||
|
self.chosen = policy(battle_mode="experimental")
|
||||||
|
self.action = intent(kind="sweep", battle_kind="sweep", difficulty="3")
|
||||||
|
self.restart()
|
||||||
|
|
||||||
|
def restart(self):
|
||||||
|
self.sweeper = SweepRunner(self.catalog, self.folder / "sweep_runs.json")
|
||||||
|
self.runner = BattleOrchestrator(self.catalog, BattleJournal(self.folder / "journal.json"),
|
||||||
|
self.runtime, self.sweeper)
|
||||||
|
|
||||||
|
def run_sweep(self, cancel=None):
|
||||||
|
return self.runner.run(self.client, self.snapshot, self.action, self.chosen, cancel=cancel)
|
||||||
|
|
||||||
|
def paths(self):
|
||||||
|
return [call.args[0] for call in self.client.call.call_args_list]
|
||||||
|
|
||||||
|
def test_hidden_win_uses_hidden_inputs_metadata_and_record_with_one_entry(self):
|
||||||
|
self.run_sweep()
|
||||||
|
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd", "battleService/recordBattleResult"])
|
||||||
|
request = self.runtime.run.call_args.args[0]
|
||||||
|
self.assertEqual((request["stage_id"], request["difficulty"], request["battle_kind"]), ("0102", "1", "hidden"))
|
||||||
|
data = self.client.call.call_args_list[1].args[1]["battleData"]
|
||||||
|
self.assertEqual(data["battlePosition"]["stageId"], "0102")
|
||||||
|
self.assertEqual(data["totalDamage"], 47)
|
||||||
|
self.assertEqual(self.client.call.call_args_list[2].args[1], {"stageId": "0102", "cityId": "1", "result": 1})
|
||||||
|
record = self.runner.journal.records(self.snapshot)[0]
|
||||||
|
self.assertEqual((record["stage_id"], record["difficulty"], record["battle_kind"]), ("0102", "1", "hidden"))
|
||||||
|
self.assertEqual((record["parent_stage_id"], record["parent_difficulty"], record["outcome"]), ("0101", "3", "win"))
|
||||||
|
self.assertEqual(sum(self.sweeper.state["counts"].values()), 1)
|
||||||
|
self.assertIsNone(self.sweeper.state["pending"])
|
||||||
|
totals = self.sweeper.statistics.snapshot(7)["totals"]
|
||||||
|
self.assertEqual(totals["0102:1:sweep"]["n"], 1)
|
||||||
|
self.assertNotIn("0101:3:event", totals)
|
||||||
|
self.assertEqual(self.sweeper.last_reward["money"], 17)
|
||||||
|
|
||||||
|
def test_hidden_loss_records_hidden_id_without_victory_settlement(self):
|
||||||
|
self.runtime.win = False
|
||||||
|
self.run_sweep()
|
||||||
|
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/recordBattleResult"])
|
||||||
|
self.assertEqual(self.client.call.call_args.args[1], {"stageId": "0102", "cityId": "1", "result": 0})
|
||||||
|
self.assertIsNone(self.sweeper.state["pending"])
|
||||||
|
self.assertEqual(self.runner.journal.records(self.snapshot)[0]["outcome"], "loss")
|
||||||
|
self.assertEqual(self.runner.journal.role(self.snapshot)["losses"], 0)
|
||||||
|
self.assertEqual(self.sweeper.statistics.snapshot(7)["totals"], {})
|
||||||
|
|
||||||
|
def test_stop_during_computation_resumes_saved_result_without_second_worker_or_entry(self):
|
||||||
|
cancel = threading.Event()
|
||||||
|
def complete(request, *, cancel_event):
|
||||||
|
result = self.runtime._run(request, cancel_event=cancel_event)
|
||||||
|
cancel_event.set()
|
||||||
|
return result
|
||||||
|
self.runtime.run.side_effect = complete
|
||||||
|
self.run_sweep(cancel)
|
||||||
|
self.assertEqual(self.paths(), ["stageService/stageStart"])
|
||||||
|
self.restart()
|
||||||
|
self.runner.continue_sweep(self.client, self.snapshot, self.chosen, cancel=threading.Event())
|
||||||
|
self.assertEqual(self.runtime.run.call_count, 1)
|
||||||
|
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd", "battleService/recordBattleResult"])
|
||||||
|
self.assertIsNone(self.sweeper.state["pending"])
|
||||||
|
self.assertEqual(sum(self.sweeper.state["counts"].values()), 1)
|
||||||
|
|
||||||
|
def test_stop_after_start_keeps_original_inputs_for_restart(self):
|
||||||
|
cancel = threading.Event()
|
||||||
|
def start(path, payload):
|
||||||
|
cancel.set()
|
||||||
|
return deepcopy(self.start)
|
||||||
|
self.client.call.side_effect = start
|
||||||
|
self.run_sweep(cancel)
|
||||||
|
self.runtime.run.assert_not_called()
|
||||||
|
self.snapshot.raw["monsters"][0]["level"] = 999
|
||||||
|
self.restart()
|
||||||
|
self.client.call.side_effect = lambda path, payload: {"resCode": 0, "reward": {}}
|
||||||
|
self.runner.continue_sweep(self.client, self.snapshot, self.chosen, cancel=threading.Event())
|
||||||
|
request = self.runtime.run.call_args.args[0]
|
||||||
|
self.assertNotIn("level", request.get("roster", request["snapshot"])["monsters"][0])
|
||||||
|
self.assertEqual(self.paths().count("stageService/stageStart"), 1)
|
||||||
|
self.assertIsNone(self.sweeper.state["pending"])
|
||||||
|
|
||||||
|
def test_unknown_settlement_is_never_replayed_or_cleared(self):
|
||||||
|
def call(path, payload):
|
||||||
|
if path.endswith("battleEnd"):
|
||||||
|
raise TimeoutError("offline lost settlement response")
|
||||||
|
return deepcopy(self.start)
|
||||||
|
self.client.call.side_effect = call
|
||||||
|
with self.assertRaises(TimeoutError):
|
||||||
|
self.run_sweep()
|
||||||
|
self.restart()
|
||||||
|
before = deepcopy(self.sweeper.state)
|
||||||
|
self.runner.continue_sweep(self.client, self.snapshot, self.chosen, cancel=threading.Event())
|
||||||
|
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd"])
|
||||||
|
self.assertEqual(self.sweeper.state, before)
|
||||||
|
self.assertIsNotNone(self.runner.pending(self.snapshot))
|
||||||
|
|
||||||
|
def test_unknown_record_keeps_confirmed_rewards_and_never_replays(self):
|
||||||
|
def call(path, payload):
|
||||||
|
if path.endswith("recordBattleResult"):
|
||||||
|
raise TimeoutError("offline lost record response")
|
||||||
|
return deepcopy(self.start) if path.endswith("stageStart") else {"resCode": 0, "reward": {"money": 17}}
|
||||||
|
self.client.call.side_effect = call
|
||||||
|
with self.assertRaises(TimeoutError):
|
||||||
|
self.run_sweep()
|
||||||
|
self.restart()
|
||||||
|
self.runner.continue_sweep(self.client, self.snapshot, self.chosen, cancel=threading.Event())
|
||||||
|
self.assertEqual(len(self.paths()), 3)
|
||||||
|
self.assertIsNotNone(self.runner.pending(self.snapshot)["sweep_entry"])
|
||||||
|
self.assertEqual(self.sweeper.statistics.snapshot(7)["totals"]["0102:1:sweep"]["n"], 1)
|
||||||
|
|
||||||
|
def test_role_mismatch_cannot_adopt_hidden_sweep(self):
|
||||||
|
cancel = threading.Event()
|
||||||
|
self.client.call.side_effect = lambda *args: cancel.set() or deepcopy(self.start)
|
||||||
|
self.run_sweep(cancel)
|
||||||
|
self.restart()
|
||||||
|
self.snapshot.raw["master"]["id"] = 8
|
||||||
|
before = deepcopy(self.sweeper.state)
|
||||||
|
self.runner.continue_sweep(self.client, self.snapshot, self.chosen, cancel=threading.Event())
|
||||||
|
self.assertEqual(self.sweeper.state, before)
|
||||||
|
self.assertEqual(len(self.paths()), 1)
|
||||||
|
self.runtime.run.assert_not_called()
|
||||||
|
|
||||||
|
def test_no_hidden_evidence_keeps_legacy_pending_and_journal(self):
|
||||||
|
self.sweeper.state["pending"] = {"stage": "0101", "level": "3", "sampleId": "old",
|
||||||
|
"phase": "遭遇隐藏关卡,请在游戏内手动战斗"}
|
||||||
|
self.sweeper.save()
|
||||||
|
before = deepcopy(self.sweeper.state)
|
||||||
|
self.runner.continue_sweep(self.client, self.snapshot, self.chosen, cancel=threading.Event())
|
||||||
|
self.assertEqual(self.sweeper.state, before)
|
||||||
|
self.client.call.assert_not_called()
|
||||||
|
self.runtime.run.assert_not_called()
|
||||||
|
|
||||||
|
def test_cross_day_handoff_and_completed_journal_cleanup_keep_original_reservation(self):
|
||||||
|
cancel = threading.Event()
|
||||||
|
self.client.call.side_effect = lambda *args: cancel.set() or deepcopy(self.start)
|
||||||
|
self.run_sweep(cancel)
|
||||||
|
record = self.runner.pending(self.snapshot)
|
||||||
|
entry = deepcopy(record["sweep_entry"])
|
||||||
|
counts = deepcopy(self.sweeper.state["counts"])
|
||||||
|
# Emulate a crash after journal.save but before sweep.save.
|
||||||
|
self.sweeper.state["pending"] = deepcopy(entry)
|
||||||
|
self.sweeper.save()
|
||||||
|
self.snapshot.server_offset += 86400
|
||||||
|
self.restart()
|
||||||
|
self.runner.handoff_sweep(self.snapshot)
|
||||||
|
self.assertIsNone(self.sweeper.state["pending"])
|
||||||
|
self.assertEqual(self.sweeper.state["counts"], counts)
|
||||||
|
self.client.call.side_effect = lambda *args: {"resCode": 0, "reward": {"money": 17}}
|
||||||
|
self.runner.continue_sweep(self.client, self.snapshot, self.chosen)
|
||||||
|
self.assertEqual(self.paths().count("stageService/stageStart"), 1)
|
||||||
|
self.sweeper.state["pending"] = deepcopy(entry)
|
||||||
|
self.sweeper.save()
|
||||||
|
self.restart()
|
||||||
|
self.runner.handoff_sweep(self.snapshot)
|
||||||
|
self.assertIsNone(self.sweeper.state["pending"])
|
||||||
|
self.assertEqual(self.sweeper.state["counts"], counts)
|
||||||
|
self.assertEqual(len(self.runner.journal.records(self.snapshot)), 1)
|
||||||
|
self.assertEqual(self.sweeper.statistics.snapshot(7)["totals"]["0102:1:sweep"]["n"], 1)
|
||||||
|
|
||||||
|
def test_runtime_clock_stop_and_resume_does_not_resimulate_or_enter(self):
|
||||||
|
cancel = threading.Event()
|
||||||
|
cancel.wait = Mock(side_effect=lambda timeout: cancel.set() or True)
|
||||||
|
self.runner.clock = lambda: 0
|
||||||
|
self.runtime.run.side_effect = lambda request, cancel_event: self.runtime._run(request, cancel_event=cancel_event) | {
|
||||||
|
"requires_realtime_wait": True, "model_elapsed_ms": 10000}
|
||||||
|
self.run_sweep(cancel)
|
||||||
|
self.assertEqual(self.paths(), ["stageService/stageStart"])
|
||||||
|
self.restart()
|
||||||
|
record = self.runner.pending(self.snapshot)
|
||||||
|
self.assertEqual(record["battle_clock_seconds"], 10)
|
||||||
|
self.assertEqual(self.runner.recovery_status(record)["state"], "resume_result")
|
||||||
|
self.runner.journal.update(record, record["phase"], battle_ready_at=1)
|
||||||
|
self.runner.continue_sweep(self.client, self.snapshot, self.chosen)
|
||||||
|
self.assertEqual(self.runtime.run.call_count, 1)
|
||||||
|
self.assertEqual(len(self.paths()), 3)
|
||||||
|
|
||||||
|
def test_confirmed_hidden_start_does_not_recover_with_wrong_hidden_id(self):
|
||||||
|
cancel = threading.Event()
|
||||||
|
self.client.call.side_effect = lambda *args: cancel.set() or deepcopy(self.start)
|
||||||
|
self.run_sweep(cancel)
|
||||||
|
record = self.runner.pending(self.snapshot)
|
||||||
|
self.runner.journal.update(record, record["phase"], stage_id="0101")
|
||||||
|
self.runner.continue_sweep(self.client, self.snapshot, self.chosen)
|
||||||
|
self.assertEqual(self.paths(), ["stageService/stageStart"])
|
||||||
|
self.runtime.run.assert_not_called()
|
||||||
|
|
||||||
|
def test_empty_settlement_or_record_response_never_confirms_or_retries_hidden_write(self):
|
||||||
|
for target in ("battleEnd", "recordBattleResult"):
|
||||||
|
with self.subTest(target=target):
|
||||||
|
self.setUp()
|
||||||
|
def call(path, payload):
|
||||||
|
if path.endswith(target):
|
||||||
|
return {}
|
||||||
|
return deepcopy(self.start) if path.endswith("stageStart") else {"resCode": 0, "reward": {}}
|
||||||
|
self.client.call.side_effect = call
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
self.run_sweep()
|
||||||
|
count = len(self.paths())
|
||||||
|
self.restart()
|
||||||
|
record = self.runner.pending(self.snapshot)
|
||||||
|
self.assertFalse(self.runner.recovery_status(record)["resumable"])
|
||||||
|
self.runner.continue_sweep(self.client, self.snapshot, self.chosen)
|
||||||
|
self.assertEqual(len(self.paths()), count)
|
||||||
|
|
||||||
|
def test_crash_after_trusted_response_save_derives_hidden_only_from_response(self):
|
||||||
|
cancel = threading.Event()
|
||||||
|
self.client.call.side_effect = lambda *args: cancel.set() or deepcopy(self.start)
|
||||||
|
self.run_sweep(cancel)
|
||||||
|
entry = deepcopy(self.runner.pending(self.snapshot)["sweep_entry"])
|
||||||
|
self.runner.journal.state = {"version": 1, "roles": {}}
|
||||||
|
self.runner.journal.save()
|
||||||
|
entry.pop("hidden_stage_id")
|
||||||
|
entry["phase"] = "开始请求待确认"
|
||||||
|
self.sweeper.state["pending"] = entry
|
||||||
|
self.sweeper.save()
|
||||||
|
self.restart()
|
||||||
|
self.client.call.side_effect = lambda *args: {"resCode": 0, "reward": {}}
|
||||||
|
self.runner.continue_sweep(self.client, self.snapshot, self.chosen)
|
||||||
|
self.assertEqual(self.paths().count("stageService/stageStart"), 1)
|
||||||
|
self.assertEqual(self.runner.journal.records(self.snapshot)[0]["stage_id"], "0102")
|
||||||
|
|
||||||
|
def test_crash_after_new_journal_begin_keeps_sample_role_and_recovers_same_record(self):
|
||||||
|
cancel = threading.Event()
|
||||||
|
self.client.call.side_effect = lambda *args: cancel.set() or deepcopy(self.start)
|
||||||
|
self.run_sweep(cancel)
|
||||||
|
entry = deepcopy(self.runner.pending(self.snapshot)["sweep_entry"])
|
||||||
|
self.runner.journal.state = {"version": 1, "roles": {}}
|
||||||
|
self.runner.journal.save()
|
||||||
|
self.sweeper.state["pending"] = entry
|
||||||
|
self.sweeper.save()
|
||||||
|
begin = self.runner.journal.begin
|
||||||
|
def crash(*args, **kwargs):
|
||||||
|
record = begin(*args, **kwargs)
|
||||||
|
self.assertEqual((record["sweep_sample_id"], record["role_id"]), (entry["sampleId"], "7"))
|
||||||
|
raise OSError("offline crash after durable begin")
|
||||||
|
self.runner.journal.begin = crash
|
||||||
|
with self.assertRaises(OSError):
|
||||||
|
self.runner.handoff_sweep(self.snapshot)
|
||||||
|
self.restart()
|
||||||
|
self.client.call.side_effect = lambda *args: {"resCode": 0, "reward": {}}
|
||||||
|
self.runner.continue_sweep(self.client, self.snapshot, self.chosen)
|
||||||
|
self.assertIsNone(self.runner.pending(self.snapshot))
|
||||||
|
self.assertEqual(len(self.runner.journal.records(self.snapshot)), 1)
|
||||||
|
self.assertEqual(self.paths().count("stageService/stageStart"), 1)
|
||||||
|
|
||||||
|
def test_commission_farming_sweep_keeps_source_and_single_entry_during_resume(self):
|
||||||
|
self.action.update(kind="progression_farm_sweep", task_id=0, task_type_id="", step_number=0,
|
||||||
|
source_task_id=51, source_task_type_id="400", source_step_number=1)
|
||||||
|
self.snapshot.raw["currentTasks"] = [{"id": 51, "typeId": "400", "curStep": 1}]
|
||||||
|
cancel = threading.Event()
|
||||||
|
def complete(request, *, cancel_event):
|
||||||
|
result = self.runtime._run(request, cancel_event=cancel_event)
|
||||||
|
cancel_event.set()
|
||||||
|
return result
|
||||||
|
self.runtime.run.side_effect = complete
|
||||||
|
self.run_sweep(cancel)
|
||||||
|
self.restart()
|
||||||
|
record = self.runner.pending(self.snapshot)
|
||||||
|
self.assertEqual((record["kind"], record["source_task_id"], record["source_task_type_id"]),
|
||||||
|
("progression_farm_sweep", 51, "400"))
|
||||||
|
self.runner.continue_sweep(self.client, self.snapshot, policy(enabled=False, battle_mode="experimental"))
|
||||||
|
self.assertEqual(len(self.paths()), 1)
|
||||||
|
self.runner.continue_sweep(self.client, self.snapshot, self.chosen)
|
||||||
|
self.assertEqual(self.runtime.run.call_count, 1)
|
||||||
|
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd", "battleService/recordBattleResult"])
|
||||||
|
self.assertEqual(sum(self.sweeper.state["counts"].values()), 1)
|
||||||
|
self.assertEqual(self.sweeper.statistics.snapshot(7)["totals"]["0102:1:sweep"]["n"], 1)
|
||||||
|
self.assertEqual(self.runner.journal.role(self.snapshot)["losses"], 0)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,331 @@
|
|||||||
|
"""Account-worker sweep recovery, with local files and mocked transport only."""
|
||||||
|
from copy import deepcopy
|
||||||
|
import json
|
||||||
|
import threading
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import Mock, patch
|
||||||
|
|
||||||
|
from ranch_assistant.api import Session
|
||||||
|
from ranch_assistant.engine import Engine
|
||||||
|
from ranch_assistant.game_data import ProgressionData
|
||||||
|
from ranch_assistant.model import Policy, Snapshot
|
||||||
|
from ranch_assistant.sessions import identity
|
||||||
|
from ranch_assistant.sweeping import SweepPolicy
|
||||||
|
from ranch_assistant.maps import stages
|
||||||
|
from ranch_assistant.tests.test_activities import scenario
|
||||||
|
from ranch_assistant.tests.test_battle_orchestration import ExperimentalRuntime
|
||||||
|
from ranch_assistant.tests.test_core import workspace_temp
|
||||||
|
|
||||||
|
|
||||||
|
class HiddenSweepEngineTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.folder = self.enterContext(workspace_temp())
|
||||||
|
self.catalog, self.snapshot = scenario()
|
||||||
|
self.raw = deepcopy(self.snapshot.raw)
|
||||||
|
self.raw["master"].update(id=7, ti=100, timeTi=0)
|
||||||
|
self.raw["currentTasks"] = []
|
||||||
|
self.session = Session(account_id="offline", role_id=7, server_id=1)
|
||||||
|
self.root = self.folder / "roles" / identity(self.session)
|
||||||
|
self.trace = self.folder / "network_debug.jsonl"
|
||||||
|
self.client = Mock()
|
||||||
|
self.client.session = self.session
|
||||||
|
self.client.trace = Mock(path=self.trace, events=[])
|
||||||
|
self.client.snapshot.side_effect = lambda: Snapshot(deepcopy(self.raw))
|
||||||
|
self.runtime = ExperimentalRuntime()
|
||||||
|
data = {"stage_info": deepcopy(self.catalog.data["stage_info"]), "game_setting": self.catalog.data["game_setting"],
|
||||||
|
"task_info": {}, "stage_battles": {}}
|
||||||
|
data["stage_info"]["0102"]["level"]["1"]["battle"] = {"fixture_hidden": True}
|
||||||
|
self.engine = Engine(self.catalog, self.client, self.root / "purchase.json",
|
||||||
|
game_data=ProgressionData(data), experimental_runtime=self.runtime)
|
||||||
|
self.engine.policy = Policy(enabled=False, gift_enabled=False, fill=False)
|
||||||
|
self.engine.progression_policy.enabled = False
|
||||||
|
self.engine.sweep_policy = SweepPolicy(True, {"0101": {"enabled": True, "level": "3", "limit": 3}}, allow_challenge=False)
|
||||||
|
self.engine.master_sync.settle = Mock()
|
||||||
|
self.engine.snapshot = Snapshot(deepcopy(self.raw))
|
||||||
|
|
||||||
|
def legacy(self, phase="遭遇隐藏关卡,请在游戏内手动战斗"):
|
||||||
|
pending = {"stage": "0101", "level": "3", "phase": phase, "sampleId": "legacy-entry"}
|
||||||
|
self.engine.sweeper.state = {"counts": {"7:2026-11-13:0101:3": 1}, "pending": pending}
|
||||||
|
self.engine.sweeper.save()
|
||||||
|
events = [{"kind": "response", "operation": "读取角色", "http_status": 200,
|
||||||
|
"body": {"resCode": 0, "master": {"id": 7}}}]
|
||||||
|
self.trace.write_text("\n".join(json.dumps(row) for row in events) + "\n", encoding="utf-8")
|
||||||
|
return deepcopy(pending)
|
||||||
|
|
||||||
|
def test_exact_legacy_missing_id_is_archived_after_trusted_read_without_reward_or_write(self):
|
||||||
|
original = self.legacy()
|
||||||
|
self.engine.sweep_policy.enabled = False
|
||||||
|
self.engine.cancel_progression()
|
||||||
|
self.engine.read_snapshot(sync_master=False)
|
||||||
|
self.assertIsNone(self.engine.sweeper.state["pending"])
|
||||||
|
record = self.engine.battle_journal.records(self.engine.snapshot)[0]
|
||||||
|
self.assertEqual(record["outcome"], "abandoned_missing_hidden_id")
|
||||||
|
self.assertEqual(record["sweep_entry"], original)
|
||||||
|
self.assertIn("旧版未保存隐藏关卡编号,本次未完成已放弃;未结算奖励", record["message"])
|
||||||
|
self.assertEqual(self.engine.sweeper.state["counts"], {"7:2026-11-13:0101:3": 1})
|
||||||
|
self.client.call.assert_not_called()
|
||||||
|
self.assertEqual(self.engine.sweeper.statistics.snapshot(7)["totals"], {})
|
||||||
|
self.engine.read_snapshot(sync_master=False)
|
||||||
|
self.assertEqual(len(self.engine.battle_journal.records(self.engine.snapshot)), 1)
|
||||||
|
|
||||||
|
def test_legacy_archive_accepts_exact_local_login_info_then_role_read_and_heartbeat(self):
|
||||||
|
original = self.legacy()
|
||||||
|
events = [{"kind": "info", "operation": "进入参数检查", "scope": "local",
|
||||||
|
"sign_date": "20261114", "date_format": "yyyyMMdd", "signature_rule": "2|2|1|2|3",
|
||||||
|
"tj_channel": "unknow", "platform": "ANDROID", "channel": "DYD", "uid_length": 7, "token_length": 16},
|
||||||
|
{"kind": "response", "operation": "读取角色", "http_status": 200,
|
||||||
|
"body": {"resCode": 0, "master": {"id": 7}}},
|
||||||
|
{"kind": "request", "operation": "heartBeatService/keepAlive", "request_id": "heartbeat", "body": {}},
|
||||||
|
{"kind": "response", "operation": "heartBeatService/keepAlive", "request_id": "heartbeat",
|
||||||
|
"http_status": 200, "body": {"resCode": 0}}]
|
||||||
|
self.trace.write_text("\n".join(json.dumps(row) for row in events) + "\n", encoding="utf-8")
|
||||||
|
self.engine.read_snapshot(sync_master=False)
|
||||||
|
self.assertIsNone(self.engine.sweeper.state["pending"])
|
||||||
|
record = self.engine.battle_journal.records(self.engine.snapshot)[0]
|
||||||
|
self.assertEqual(record["outcome"], "abandoned_missing_hidden_id")
|
||||||
|
self.assertEqual(record["sweep_entry"], original)
|
||||||
|
self.assertEqual(self.engine.sweeper.state["counts"], {"7:2026-11-13:0101:3": 1})
|
||||||
|
self.assertTrue(next(iter(self.engine._sweep_recovery_cache.values()))["valid"])
|
||||||
|
self.client.call.assert_not_called()
|
||||||
|
self.runtime.run.assert_not_called()
|
||||||
|
self.assertEqual(self.engine.sweeper.statistics.snapshot(7)["totals"], {})
|
||||||
|
|
||||||
|
def test_unknown_info_or_login_info_without_local_scope_blocks_legacy_archive(self):
|
||||||
|
for info in ({"kind": "info", "operation": "未知信息", "scope": "local"},
|
||||||
|
{"kind": "info", "operation": "进入参数检查", "scope": "network"},
|
||||||
|
{"kind": "info", "operation": "进入参数检查"}):
|
||||||
|
with self.subTest(info=info):
|
||||||
|
original = self.legacy()
|
||||||
|
self.engine._sweep_recovery_cache.clear()
|
||||||
|
events = [info, {"kind": "response", "operation": "读取角色", "http_status": 200,
|
||||||
|
"body": {"resCode": 0, "master": {"id": 7}}}]
|
||||||
|
self.trace.write_text("\n".join(json.dumps(row) for row in events) + "\n", encoding="utf-8")
|
||||||
|
self.engine.read_snapshot(sync_master=False)
|
||||||
|
self.assertEqual(self.engine.sweeper.state["pending"], original)
|
||||||
|
self.assertFalse(next(iter(self.engine._sweep_recovery_cache.values()))["valid"])
|
||||||
|
self.assertEqual(self.engine.battle_journal.records(self.engine.snapshot), [])
|
||||||
|
self.client.call.assert_not_called()
|
||||||
|
self.runtime.run.assert_not_called()
|
||||||
|
|
||||||
|
def test_uncertain_phases_are_never_archived(self):
|
||||||
|
for phase in ("开始请求待确认", "扫荡结算待确认", "start_pending", "settlement_pending"):
|
||||||
|
original = self.legacy(phase)
|
||||||
|
self.engine.read_snapshot(sync_master=False)
|
||||||
|
self.assertEqual(self.engine.sweeper.state["pending"], original)
|
||||||
|
self.client.call.assert_not_called()
|
||||||
|
|
||||||
|
def test_archive_requires_role_path_binding_and_fresh_read(self):
|
||||||
|
original = self.legacy()
|
||||||
|
self.engine.sweeper.path = self.folder / "other" / "sweep_runs.json"
|
||||||
|
self.engine.read_snapshot(sync_master=False)
|
||||||
|
self.assertEqual(self.engine.sweeper.state["pending"], original)
|
||||||
|
self.client.snapshot.side_effect = TimeoutError("offline read failed")
|
||||||
|
with self.assertRaises(TimeoutError):
|
||||||
|
self.engine.read_snapshot(sync_master=False)
|
||||||
|
self.assertEqual(self.engine.sweeper.state["pending"], original)
|
||||||
|
|
||||||
|
def test_later_consumption_or_conflicting_journal_blocks_archive(self):
|
||||||
|
original = self.legacy()
|
||||||
|
with self.trace.open("a", encoding="utf-8") as stream:
|
||||||
|
stream.write(json.dumps({"kind": "request", "operation": "battleService/battleEnd",
|
||||||
|
"request_id": "later", "body": {"battleData": {}}}) + "\n")
|
||||||
|
self.engine.read_snapshot(sync_master=False)
|
||||||
|
self.assertEqual(self.engine.sweeper.state["pending"], original)
|
||||||
|
self.legacy()
|
||||||
|
self.engine.battle_journal.begin(self.engine.snapshot, {"kind": "battle", "stage_id": "0102", "difficulty": "1"})
|
||||||
|
self.engine.read_snapshot(sync_master=False)
|
||||||
|
self.assertEqual(self.engine.sweeper.state["pending"], original)
|
||||||
|
self.client.call.assert_not_called()
|
||||||
|
|
||||||
|
def test_map_sweep_origin_uses_enabled_sweep_with_challenges_disabled(self):
|
||||||
|
self.assertTrue(self.engine._intent_policy({"kind": "map_sweep"}).enabled)
|
||||||
|
self.engine.sweep_policy.enabled = False
|
||||||
|
self.assertFalse(self.engine._intent_policy({"kind": "map_sweep"}).enabled)
|
||||||
|
|
||||||
|
def test_commission_farming_origin_uses_quest_policy(self):
|
||||||
|
self.engine.game_data.tasks["400"] = {"type": 4}
|
||||||
|
self.engine.quest_policy.enabled = True
|
||||||
|
origin = {"kind": "progression_farm_sweep", "source_task_type_id": "400"}
|
||||||
|
self.assertTrue(self.engine._intent_policy(origin).enabled)
|
||||||
|
self.engine.quest_policy.enabled = False
|
||||||
|
self.engine.progression_policy.enabled = True
|
||||||
|
self.assertFalse(self.engine._intent_policy(origin).enabled)
|
||||||
|
|
||||||
|
def prepare_hidden(self):
|
||||||
|
response = {"resCode": 0, "triggerEvent": True, "stageEvent": {"hideStageId": "0102", "result": {"money": 999}}}
|
||||||
|
self.client.call.side_effect = lambda path, payload: deepcopy(response) if path.endswith("stageStart") else {
|
||||||
|
"resCode": 0, "reward": {"money": 17}}
|
||||||
|
stage = next(s for s in stages(self.catalog, self.engine.snapshot) if s.stage_id == "0101" and s.level == "3")
|
||||||
|
self.engine.sweeper.run(self.client, self.engine.snapshot, stage, self.engine.sweep_policy,
|
||||||
|
origin={"kind": "map_sweep", "stage_id": "0101", "difficulty": "3", "battle_kind": "sweep", "battle_mode": "experimental"})
|
||||||
|
self.engine.read_snapshot(sync_master=False)
|
||||||
|
|
||||||
|
def test_worker_migrates_before_web_start_and_resumes_without_challenge_or_mainline(self):
|
||||||
|
self.prepare_hidden()
|
||||||
|
self.assertIsNone(self.engine.sweeper.state["pending"])
|
||||||
|
self.assertEqual(self.engine.pending_battle_recovery()["state"], "prepare_hidden_sweep")
|
||||||
|
self.engine.poll(resume_pending=True)
|
||||||
|
self.assertFalse(self.engine.auto)
|
||||||
|
self.assertIsNone(self.engine.battle_journal.pending(self.engine.snapshot))
|
||||||
|
self.assertEqual([call.args[0] for call in self.client.call.call_args_list], [
|
||||||
|
"stageService/stageStart", "battleService/battleEnd", "battleService/recordBattleResult"])
|
||||||
|
request = self.runtime.run.call_args.args[0]
|
||||||
|
self.assertEqual((request["stage_id"], request["difficulty"]), ("0102", "1"))
|
||||||
|
self.assertEqual(request["roster"]["teams"][0]["monsters"], [900, 0])
|
||||||
|
self.assertEqual(sum(self.engine.sweeper.state["counts"].values()), 1)
|
||||||
|
totals = self.engine.sweeper.statistics.snapshot(7)["totals"]
|
||||||
|
self.assertEqual(totals["0102:1:sweep"]["n"], 1)
|
||||||
|
self.assertNotIn("0101:3:sweep", totals)
|
||||||
|
|
||||||
|
def test_stop_disabled_source_and_stale_generation_do_not_resume_consumption(self):
|
||||||
|
self.prepare_hidden()
|
||||||
|
self.engine.cancel_progression()
|
||||||
|
self.engine.poll(resume_pending=False)
|
||||||
|
self.engine.sweep_policy.enabled = False
|
||||||
|
self.assertEqual(self.engine.pending_battle_recovery()["state"], "blocked_policy")
|
||||||
|
self.engine.poll(resume_pending=True)
|
||||||
|
self.engine.sweep_policy.enabled = True
|
||||||
|
self.assertEqual(self.engine._resume_pending_task_clock(running=True,
|
||||||
|
generation=self.engine._progression_cancel_generation - 1), "")
|
||||||
|
self.runtime.run.assert_not_called()
|
||||||
|
self.assertEqual(self.client.call.call_count, 1)
|
||||||
|
self.engine.poll(resume_pending=True)
|
||||||
|
self.assertEqual(self.client.call.call_count, 3)
|
||||||
|
|
||||||
|
def test_legacy_scan_is_cached_and_never_runs_in_recovery_presentation(self):
|
||||||
|
self.legacy()
|
||||||
|
with patch("ranch_assistant.sweep_recovery.scan_trace", wraps=__import__(
|
||||||
|
"ranch_assistant.sweep_recovery", fromlist=["scan_trace"]).scan_trace) as scan:
|
||||||
|
for _ in range(3):
|
||||||
|
self.engine.pending_battle_recovery()
|
||||||
|
self.assertEqual(scan.call_count, 0)
|
||||||
|
self.engine.read_snapshot(sync_master=False)
|
||||||
|
self.engine.read_snapshot(sync_master=False)
|
||||||
|
self.assertEqual(scan.call_count, 1)
|
||||||
|
|
||||||
|
def test_archive_crash_after_journal_finish_repairs_without_second_record(self):
|
||||||
|
original = self.legacy()
|
||||||
|
self.engine.read_snapshot(sync_master=False)
|
||||||
|
self.engine.sweeper.state["pending"] = original
|
||||||
|
self.engine.sweeper.save()
|
||||||
|
self.engine.read_snapshot(sync_master=False)
|
||||||
|
self.assertIsNone(self.engine.sweeper.state["pending"])
|
||||||
|
self.assertEqual(len(self.engine.battle_journal.records(self.engine.snapshot)), 1)
|
||||||
|
self.client.call.assert_not_called()
|
||||||
|
|
||||||
|
def test_archive_crash_after_begin_recovers_same_sample_without_generic_prepared_record(self):
|
||||||
|
original = self.legacy()
|
||||||
|
begin = self.engine.battle_journal.begin
|
||||||
|
def crash(*args, **kwargs):
|
||||||
|
begin(*args, **kwargs)
|
||||||
|
raise OSError("offline interrupted archive")
|
||||||
|
self.engine.battle_journal.begin = crash
|
||||||
|
with self.assertRaises(OSError):
|
||||||
|
self.engine.read_snapshot(sync_master=False)
|
||||||
|
self.engine.battle_journal.begin = begin
|
||||||
|
self.engine.read_snapshot(sync_master=False)
|
||||||
|
self.assertIsNone(self.engine.sweeper.state["pending"])
|
||||||
|
records = self.engine.battle_journal.records(self.engine.snapshot)
|
||||||
|
self.assertEqual(len(records), 1)
|
||||||
|
self.assertEqual(records[0]["sweep_entry"], original)
|
||||||
|
self.assertEqual(records[0]["outcome"], "abandoned_missing_hidden_id")
|
||||||
|
|
||||||
|
def test_normal_sweep_stop_before_dispatch_archives_but_unknown_dispatch_stays_pending(self):
|
||||||
|
cancel = threading.Event()
|
||||||
|
stage = next(s for s in stages(self.catalog, self.engine.snapshot) if s.stage_id == "0101" and s.level == "3")
|
||||||
|
def start(path, payload):
|
||||||
|
cancel.set()
|
||||||
|
return {"resCode": 0, "triggerEvent": False}
|
||||||
|
self.client.call.side_effect = start
|
||||||
|
from ranch_assistant.battles import CancelledBeforeDispatch
|
||||||
|
with self.assertRaises(CancelledBeforeDispatch):
|
||||||
|
self.engine.sweeper.run(self.client, self.engine.snapshot, stage, self.engine.sweep_policy,
|
||||||
|
cancel=cancel, origin={"kind": "map_sweep"})
|
||||||
|
pending = deepcopy(self.engine.sweeper.state["pending"])
|
||||||
|
self.assertIs(pending["settlement_dispatched"], False)
|
||||||
|
self.engine.read_snapshot(sync_master=False)
|
||||||
|
self.assertIsNone(self.engine.sweeper.state["pending"])
|
||||||
|
self.assertEqual(self.engine.battle_journal.records(self.engine.snapshot)[0]["outcome"], "abandoned_cancelled_sweep")
|
||||||
|
self.assertEqual(self.client.call.call_count, 1)
|
||||||
|
for dispatched in (True, None):
|
||||||
|
unknown = dict(pending, phase="扫荡结算待确认")
|
||||||
|
unknown.pop("settlement_dispatched")
|
||||||
|
if dispatched is not None:
|
||||||
|
unknown["settlement_dispatched"] = dispatched
|
||||||
|
self.engine.sweeper.state["pending"] = unknown
|
||||||
|
self.engine.sweeper.save()
|
||||||
|
self.engine.read_snapshot(sync_master=False)
|
||||||
|
self.assertEqual(self.engine.sweeper.state["pending"], unknown)
|
||||||
|
|
||||||
|
def test_ordinary_automatic_entry_runs_hidden_battle_and_counts_once(self):
|
||||||
|
self.client.call.side_effect = lambda path, payload=None: {"resCode": 0, "triggerEvent": True,
|
||||||
|
"stageEvent": {"hideStageId": "0102", "result": {"money": 999}}} if path.endswith("stageStart") else {
|
||||||
|
"resCode": 0, "reward": {"money": 17}}
|
||||||
|
self.engine.auto = True
|
||||||
|
_, _, message = self.engine.poll()
|
||||||
|
self.assertIn("隐藏关卡", message)
|
||||||
|
self.assertEqual([call.args[0] for call in self.client.call.call_args_list], [
|
||||||
|
"stageService/stageStart", "battleService/battleEnd", "battleService/recordBattleResult"])
|
||||||
|
self.assertEqual(sum(self.engine.sweeper.state["counts"].values()), 1)
|
||||||
|
|
||||||
|
def test_trace_proven_legacy_hidden_id_runs_first_computation_without_new_entry(self):
|
||||||
|
self.legacy()
|
||||||
|
original_roster = deepcopy(self.raw)
|
||||||
|
self.engine.sweeper.state["pending"].update(entry_snapshot=original_roster,
|
||||||
|
entry_snapshot_now=self.engine.snapshot.now, team="teamA")
|
||||||
|
self.engine.sweeper.save()
|
||||||
|
next(mon for mon in self.raw["monsters"] if mon["id"] == 900)["level"] = 999
|
||||||
|
events = [{"kind": "response", "operation": "读取角色", "http_status": 200,
|
||||||
|
"body": {"resCode": 0, "master": {"id": 7}}},
|
||||||
|
{"kind": "request", "operation": "stageService/stageStart", "request_id": "old-start",
|
||||||
|
"body": {"stageTypeId": "0101", "stageLevel": "3"}},
|
||||||
|
{"kind": "response", "operation": "stageService/stageStart", "request_id": "old-start", "http_status": 200,
|
||||||
|
"body": {"resCode": 0, "triggerEvent": True, "stageEvent": {"hideStageId": "0102"}}}]
|
||||||
|
self.trace.write_text("\n".join(json.dumps(row) for row in events) + "\n", encoding="utf-8")
|
||||||
|
self.client.call.return_value = {"resCode": 0, "reward": {"money": 17}}
|
||||||
|
self.engine.read_snapshot(sync_master=False)
|
||||||
|
self.assertEqual(self.engine.pending_battle_recovery()["state"], "prepare_hidden_sweep")
|
||||||
|
self.engine.poll(resume_pending=True)
|
||||||
|
self.assertEqual([call.args[0] for call in self.client.call.call_args_list], [
|
||||||
|
"battleService/battleEnd", "battleService/recordBattleResult"])
|
||||||
|
self.assertEqual(self.engine.sweeper.state["counts"], {"7:2026-11-13:0101:3": 1})
|
||||||
|
saved = self.engine.battle_journal.records(self.engine.snapshot)[0]["sweep_entry"]
|
||||||
|
self.assertEqual(saved["entry_snapshot"], original_roster)
|
||||||
|
runtime_roster = self.runtime.run.call_args.args[0]["roster"]
|
||||||
|
self.assertEqual(next(mon for mon in runtime_roster["monsters"] if mon["id"] == 900)["level"], 20)
|
||||||
|
|
||||||
|
def test_legacy_hidden_id_without_original_inputs_blocks_changed_current_roster(self):
|
||||||
|
self.legacy()
|
||||||
|
next(mon for mon in self.raw["monsters"] if mon["id"] == 900)["level"] = 999
|
||||||
|
events = [{"kind": "response", "operation": "读取角色", "http_status": 200,
|
||||||
|
"body": {"resCode": 0, "master": {"id": 7}}},
|
||||||
|
{"kind": "request", "operation": "stageService/stageStart", "request_id": "old-start",
|
||||||
|
"body": {"stageTypeId": "0101", "stageLevel": "3"}},
|
||||||
|
{"kind": "response", "operation": "stageService/stageStart", "request_id": "old-start", "http_status": 200,
|
||||||
|
"body": {"resCode": 0, "triggerEvent": True, "stageEvent": {"hideStageId": "0102"}}}]
|
||||||
|
self.trace.write_text("\n".join(json.dumps(row) for row in events) + "\n", encoding="utf-8")
|
||||||
|
self.engine.read_snapshot(sync_master=False)
|
||||||
|
record = self.engine.battle_journal.pending(self.engine.snapshot)
|
||||||
|
self.assertEqual(record["stage_id"], "0102")
|
||||||
|
self.assertEqual(record["sweep_sample_id"], "legacy-entry")
|
||||||
|
self.assertNotIn("entry_snapshot", record["sweep_entry"])
|
||||||
|
self.assertNotIn("entry_snapshot_now", record["sweep_entry"])
|
||||||
|
self.assertNotIn("input_evidence", record["sweep_entry"])
|
||||||
|
self.assertNotIn("combat_request", record)
|
||||||
|
self.assertNotIn("combat_request_digest", record)
|
||||||
|
recovery = self.engine.pending_battle_recovery()
|
||||||
|
self.assertEqual(recovery["state"], "blocked")
|
||||||
|
self.assertFalse(recovery["resumable"])
|
||||||
|
self.assertIn("缺少原始战斗输入", recovery["message"])
|
||||||
|
for _ in range(2):
|
||||||
|
self.engine.poll(resume_pending=True)
|
||||||
|
self.runtime.inspect.assert_not_called()
|
||||||
|
self.runtime.run.assert_not_called()
|
||||||
|
self.client.call.assert_not_called()
|
||||||
|
self.assertEqual(self.engine.sweeper.state["counts"], {"7:2026-11-13:0101:3": 1})
|
||||||
|
self.assertEqual(self.engine.sweeper.statistics.snapshot(7)["totals"], {})
|
||||||
|
self.assertEqual(self.engine.battle_journal.pending(self.engine.snapshot), record)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,322 @@
|
|||||||
|
"""Offline coverage for the durable sweep-to-hidden-battle handoff."""
|
||||||
|
from copy import deepcopy
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
from tempfile import TemporaryDirectory
|
||||||
|
from threading import Event
|
||||||
|
from types import SimpleNamespace
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import Mock
|
||||||
|
|
||||||
|
from ranch_assistant.battles import CancelledBeforeDispatch
|
||||||
|
from ranch_assistant.sweeping import SweepPolicy, SweepRunner, hidden_stage_id
|
||||||
|
|
||||||
|
|
||||||
|
class HiddenSweepHandoffTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.temp = TemporaryDirectory()
|
||||||
|
self.addCleanup(self.temp.cleanup)
|
||||||
|
self.folder = Path(self.temp.name)
|
||||||
|
self.catalog = SimpleNamespace(data={})
|
||||||
|
self.snapshot = SimpleNamespace(now=1794618000, monsters={9: {}}, raw={
|
||||||
|
"master": {"id": 17, "sessionKey": "never-save"},
|
||||||
|
"teams": [{"teamName": "teamA", "teamType": "battleTeam", "monsters": [9]}],
|
||||||
|
"nested": {"token": "never-save", "safe": 1}})
|
||||||
|
self.stage = SimpleNamespace(stage_id="0101", level="3")
|
||||||
|
self.policy = SweepPolicy(True, {"0101": {"enabled": True, "level": "3", "limit": 4}})
|
||||||
|
self.runner = SweepRunner(self.catalog, self.folder / "sweeps.json")
|
||||||
|
self.runner.reason = Mock(return_value="")
|
||||||
|
self.response = {"resCode": 0, "triggerEvent": True, "stageEvent": {
|
||||||
|
"hideStageId": "00109", "costTi": 16, "result": {"money": 999}}}
|
||||||
|
self.client = Mock()
|
||||||
|
self.client.call.return_value = self.response
|
||||||
|
|
||||||
|
def test_hidden_handoff_counts_once_without_settlement_or_reward(self):
|
||||||
|
result = self.runner.run(self.client, self.snapshot, self.stage, self.policy, origin={"kind": "map_sweep"})
|
||||||
|
self.assertIs(result, self.response)
|
||||||
|
self.client.call.assert_called_once_with("stageService/stageStart", {
|
||||||
|
"stageTypeId": "0101", "stageLevel": "3"})
|
||||||
|
self.assertEqual(self.runner.used(self.snapshot, self.stage), 1)
|
||||||
|
self.assertEqual(self.runner.last_outcome, "hidden")
|
||||||
|
self.assertIsNone(self.runner.last_reward)
|
||||||
|
self.assertEqual(self.runner.statistics.snapshot(17)["totals"], {})
|
||||||
|
pending = self.runner.state["pending"]
|
||||||
|
self.assertEqual((pending["phase"], pending["hidden_stage_id"]), ("hidden_started", "00109"))
|
||||||
|
|
||||||
|
def test_restart_has_sanitized_entry_and_trusted_start_evidence(self):
|
||||||
|
self.response["sessionKey"] = "never-save"
|
||||||
|
self.runner.run(self.client, self.snapshot, self.stage, self.policy,
|
||||||
|
origin={"kind": "sweep", "secret": "never-save"})
|
||||||
|
restored = SweepRunner(self.catalog, self.runner.path)
|
||||||
|
pending = restored.state["pending"]
|
||||||
|
self.assertEqual(pending["role_id"], "17")
|
||||||
|
self.assertEqual((pending["stage"], pending["level"], pending["team"]), ("0101", "3", "teamA"))
|
||||||
|
self.assertEqual(pending["counts_key"], self.runner.key(self.snapshot, self.stage))
|
||||||
|
self.assertTrue(pending["sampleId"])
|
||||||
|
self.assertEqual(pending["entry_snapshot_now"], self.snapshot.now)
|
||||||
|
self.assertEqual(pending["entry_snapshot"]["nested"], {"safe": 1})
|
||||||
|
self.assertEqual(pending["origin"], {"kind": "sweep"})
|
||||||
|
self.assertEqual(pending["start_path"], "stageService/stageStart")
|
||||||
|
self.assertTrue(pending["start_dispatched"])
|
||||||
|
self.assertTrue(pending["start_confirmed"])
|
||||||
|
self.assertGreater(pending["start_confirmed_at"], 0)
|
||||||
|
self.assertNotIn("sessionKey", pending["start_response"])
|
||||||
|
self.assertNotIn("never-save", restored.path.read_text(encoding="utf-8"))
|
||||||
|
|
||||||
|
def test_hidden_ids_and_trigger_require_exact_protocol_types(self):
|
||||||
|
for identifier, expected in (("00109", "00109"), (109, "109"), (" hidden ", " hidden "),
|
||||||
|
(None, None), ("", None), (" ", None), (0, None), (-1, None),
|
||||||
|
(True, None), (1.0, None), ({}, None), ([], None)):
|
||||||
|
with self.subTest(identifier=identifier):
|
||||||
|
response = dict(self.response, stageEvent={"hideStageId": identifier})
|
||||||
|
self.assertEqual(hidden_stage_id(response), expected)
|
||||||
|
for flag in (False, 0, "1", 1.0, None):
|
||||||
|
self.assertIsNone(hidden_stage_id(dict(self.response, triggerEvent=flag)))
|
||||||
|
self.assertEqual(hidden_stage_id(dict(self.response, triggerEvent=1)), "00109")
|
||||||
|
|
||||||
|
def test_ordinary_and_settled_event_paths_still_complete(self):
|
||||||
|
self.client.call.side_effect = [{"resCode": 0, "triggerEvent": False},
|
||||||
|
{"resCode": 0, "reward": {"money": 1}}, {"resCode": 0}]
|
||||||
|
self.runner.run(self.client, self.snapshot, self.stage, self.policy)
|
||||||
|
self.assertEqual([call.args[0] for call in self.client.call.call_args_list], [
|
||||||
|
"stageService/stageStart", "battleService/battleEnd", "battleService/recordBattleResult"])
|
||||||
|
self.assertEqual(self.runner.last_outcome, "sweep")
|
||||||
|
self.assertIsNone(self.runner.state["pending"])
|
||||||
|
self.client.reset_mock(side_effect=True)
|
||||||
|
self.client.call.return_value = {"resCode": 0, "triggerEvent": True,
|
||||||
|
"stageEvent": {"hideStageId": None, "result": {"money": 2}}}
|
||||||
|
self.runner.run(self.client, self.snapshot, self.stage, self.policy)
|
||||||
|
self.assertEqual(self.client.call.call_count, 1)
|
||||||
|
self.assertEqual(self.runner.last_outcome, "event")
|
||||||
|
self.assertIsNone(self.runner.state["pending"])
|
||||||
|
self.assertEqual(self.runner.used(self.snapshot, self.stage), 2)
|
||||||
|
|
||||||
|
def test_timeout_preserves_dispatched_pending_and_cannot_reenter(self):
|
||||||
|
self.client.call.side_effect = TimeoutError("entry not confirmed")
|
||||||
|
with self.assertRaises(TimeoutError):
|
||||||
|
self.runner.run(self.client, self.snapshot, self.stage, self.policy)
|
||||||
|
restored = SweepRunner(self.catalog, self.runner.path)
|
||||||
|
self.assertTrue(restored.state["pending"]["start_dispatched"])
|
||||||
|
self.assertFalse(restored.state["pending"]["start_confirmed"])
|
||||||
|
self.assertNotIn("start_response", restored.state["pending"])
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
restored.run(self.client, self.snapshot, self.stage, self.policy)
|
||||||
|
self.assertEqual(self.client.call.call_count, 1)
|
||||||
|
|
||||||
|
def test_malformed_and_unsuccessful_start_keeps_pending(self):
|
||||||
|
for response in (None, [], {}, {"resCode": False, "triggerEvent": False},
|
||||||
|
{"resCode": 9, "triggerEvent": False}, {"resCode": 0, "triggerEvent": "1"},
|
||||||
|
{"resCode": 0, "triggerEvent": True, "stageEvent": {"hideStageId": []}}):
|
||||||
|
with self.subTest(response=response):
|
||||||
|
self.runner.state = {"counts": {}, "pending": None}
|
||||||
|
self.client.reset_mock()
|
||||||
|
self.client.call.return_value = response
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
self.runner.run(self.client, self.snapshot, self.stage, self.policy)
|
||||||
|
self.assertIsNotNone(SweepRunner(self.catalog, self.runner.path).state["pending"])
|
||||||
|
self.assertEqual(self.runner.used(self.snapshot, self.stage), 1)
|
||||||
|
self.assertEqual(self.client.call.call_count, 1)
|
||||||
|
|
||||||
|
def test_cancel_after_reservation_rolls_back_only_unissued_entry(self):
|
||||||
|
cancel = Event()
|
||||||
|
original_save = self.runner.save
|
||||||
|
def save_and_stop():
|
||||||
|
original_save()
|
||||||
|
cancel.set()
|
||||||
|
self.runner.save = save_and_stop
|
||||||
|
before = deepcopy(self.runner.state)
|
||||||
|
with self.assertRaises(CancelledBeforeDispatch):
|
||||||
|
self.runner.run(self.client, self.snapshot, self.stage, self.policy, cancel=cancel)
|
||||||
|
self.client.call.assert_not_called()
|
||||||
|
self.assertEqual(self.runner.state, before)
|
||||||
|
self.assertEqual(SweepRunner(self.catalog, self.runner.path).state, before)
|
||||||
|
|
||||||
|
def test_cancel_after_start_preserves_pending_without_settlement(self):
|
||||||
|
cancel = Event()
|
||||||
|
def start(*args):
|
||||||
|
cancel.set()
|
||||||
|
return {"resCode": 0, "triggerEvent": False}
|
||||||
|
self.client.call.side_effect = start
|
||||||
|
with self.assertRaises(CancelledBeforeDispatch):
|
||||||
|
self.runner.run(self.client, self.snapshot, self.stage, self.policy, cancel=cancel)
|
||||||
|
self.assertEqual(self.client.call.call_count, 1)
|
||||||
|
self.assertTrue(self.runner.state["pending"]["start_confirmed"])
|
||||||
|
self.assertEqual(self.runner.used(self.snapshot, self.stage), 1)
|
||||||
|
|
||||||
|
def test_cancel_at_dispatch_boundary_restores_existing_quota(self):
|
||||||
|
key = self.runner.key(self.snapshot, self.stage)
|
||||||
|
self.runner.state["counts"][key] = 2
|
||||||
|
before = deepcopy(self.runner.state)
|
||||||
|
cancel = Event()
|
||||||
|
original_save = self.runner.save
|
||||||
|
def save_and_stop():
|
||||||
|
original_save()
|
||||||
|
if (self.runner.state.get("pending") or {}).get("start_dispatched"):
|
||||||
|
cancel.set()
|
||||||
|
self.runner.save = save_and_stop
|
||||||
|
with self.assertRaises(CancelledBeforeDispatch):
|
||||||
|
self.runner.run(self.client, self.snapshot, self.stage, self.policy, cancel=cancel)
|
||||||
|
self.client.call.assert_not_called()
|
||||||
|
self.assertEqual(self.runner.state, before)
|
||||||
|
|
||||||
|
def test_stop_at_settlement_boundary_keeps_entry_reserved(self):
|
||||||
|
cancel = Event()
|
||||||
|
self.client.call.return_value = {"resCode": 0, "triggerEvent": False}
|
||||||
|
original_save = self.runner.save
|
||||||
|
def save_and_stop():
|
||||||
|
original_save()
|
||||||
|
if self.runner.state["pending"]["phase"] == "扫荡结算待确认":
|
||||||
|
cancel.set()
|
||||||
|
self.runner.save = save_and_stop
|
||||||
|
with self.assertRaises(CancelledBeforeDispatch):
|
||||||
|
self.runner.run(self.client, self.snapshot, self.stage, self.policy, cancel=cancel)
|
||||||
|
self.assertEqual(self.client.call.call_count, 1)
|
||||||
|
self.assertEqual(self.runner.used(self.snapshot, self.stage), 1)
|
||||||
|
|
||||||
|
def test_invalid_or_failed_settlement_remains_pending(self):
|
||||||
|
for result in (None, [], {}, {"resCode": 7}):
|
||||||
|
with self.subTest(result=result):
|
||||||
|
self.runner.state = {"counts": {}, "pending": None}
|
||||||
|
self.client.reset_mock()
|
||||||
|
self.client.call.side_effect = [{"resCode": 0, "triggerEvent": False}, result]
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
self.runner.run(self.client, self.snapshot, self.stage, self.policy)
|
||||||
|
self.assertIsNotNone(self.runner.state["pending"])
|
||||||
|
self.assertEqual(self.client.call.call_count, 2)
|
||||||
|
|
||||||
|
def trace_rows(self):
|
||||||
|
return [{"kind": "response", "operation": "读取角色", "body": {"master": {"id": 17}}},
|
||||||
|
{"kind": "request", "operation": "stageService/stageStart", "request_id": "start-1",
|
||||||
|
"body": {"stageTypeId": "0101", "stageLevel": "3"}},
|
||||||
|
{"kind": "response", "operation": "stageService/stageStart", "request_id": "start-1",
|
||||||
|
"http_status": 200, "time": "2026-11-14T09:00:00+08:00", "body": deepcopy(self.response)}]
|
||||||
|
|
||||||
|
def legacy_pending(self, phase="遭遇隐藏关卡,请在游戏内手动战斗"):
|
||||||
|
self.runner.state = {"counts": {self.runner.key(self.snapshot, self.stage): 1}, "pending": {
|
||||||
|
"stage": "0101", "level": "3", "phase": phase, "sampleId": "old"}}
|
||||||
|
self.runner.save()
|
||||||
|
|
||||||
|
def write_trace(self, rows):
|
||||||
|
trace = self.folder / "network_debug.jsonl"
|
||||||
|
trace.write_text("\n".join(json.dumps(row) for row in rows), encoding="utf-8")
|
||||||
|
return trace
|
||||||
|
|
||||||
|
def test_valid_rotated_trace_recovers_without_new_write_or_count(self):
|
||||||
|
self.legacy_pending()
|
||||||
|
rows = self.trace_rows()
|
||||||
|
trace = self.write_trace(rows[2:])
|
||||||
|
trace.with_name("network_debug.previous.jsonl").write_text(
|
||||||
|
"\n".join(json.dumps(row) for row in rows[:2]), encoding="utf-8")
|
||||||
|
counts = deepcopy(self.runner.state["counts"])
|
||||||
|
self.assertTrue(self.runner.recover_hidden_start(self.snapshot, trace))
|
||||||
|
pending = SweepRunner(self.catalog, self.runner.path).state["pending"]
|
||||||
|
self.assertEqual((pending["role_id"], pending["hidden_stage_id"]), ("17", "00109"))
|
||||||
|
self.assertEqual(pending["phase"], "hidden_started")
|
||||||
|
self.assertEqual(pending["start_request_id"], "start-1")
|
||||||
|
self.assertTrue(pending["start_confirmed"])
|
||||||
|
self.assertEqual(pending["start_confirmed_at"], self.snapshot.now)
|
||||||
|
self.assertEqual(self.runner.state["counts"], counts)
|
||||||
|
self.assertNotIn("entry_snapshot", pending)
|
||||||
|
self.assertNotIn("entry_snapshot_now", pending)
|
||||||
|
self.client.call.assert_not_called()
|
||||||
|
|
||||||
|
def test_unknown_entry_and_old_event_phase_can_recover(self):
|
||||||
|
for phase in ("开始请求待确认", "遇到事件或响应缺少事件状态,请在游戏内处理"):
|
||||||
|
with self.subTest(phase=phase):
|
||||||
|
self.legacy_pending(phase)
|
||||||
|
self.assertTrue(self.runner.recover_hidden_start(self.snapshot, self.write_trace(self.trace_rows())))
|
||||||
|
|
||||||
|
def test_only_latest_matching_start_can_supply_recovery_id(self):
|
||||||
|
self.legacy_pending()
|
||||||
|
rows = self.trace_rows()
|
||||||
|
newer = deepcopy(rows[1:])
|
||||||
|
for row in newer:
|
||||||
|
row["request_id"] = "latest"
|
||||||
|
newer[1]["body"]["stageEvent"]["hideStageId"] = "new-hidden"
|
||||||
|
self.assertTrue(self.runner.recover_hidden_start(self.snapshot, self.write_trace(rows + newer)))
|
||||||
|
self.assertEqual(self.runner.state["pending"]["hidden_stage_id"], "new-hidden")
|
||||||
|
self.assertEqual(self.runner.state["pending"]["start_request_id"], "latest")
|
||||||
|
|
||||||
|
def test_bound_pending_role_must_match_snapshot(self):
|
||||||
|
self.legacy_pending()
|
||||||
|
self.runner.state["pending"]["role_id"] = "18"
|
||||||
|
before = deepcopy(self.runner.state)
|
||||||
|
self.assertFalse(self.runner.recover_hidden_start(self.snapshot, self.write_trace(self.trace_rows())))
|
||||||
|
self.assertEqual(self.runner.state, before)
|
||||||
|
|
||||||
|
def test_nonlegacy_or_persisted_unknown_response_is_not_recovered(self):
|
||||||
|
for phase in ("hidden_started", "扫荡结算待确认", "开始请求待确认"):
|
||||||
|
with self.subTest(phase=phase):
|
||||||
|
self.legacy_pending(phase)
|
||||||
|
if phase == "开始请求待确认":
|
||||||
|
self.runner.state["pending"]["start_response"] = {}
|
||||||
|
before = deepcopy(self.runner.state)
|
||||||
|
self.assertFalse(self.runner.recover_hidden_start(self.snapshot, self.write_trace(self.trace_rows())))
|
||||||
|
self.assertEqual(self.runner.state, before)
|
||||||
|
|
||||||
|
def test_subsequent_combat_and_task_writes_always_prevent_recovery(self):
|
||||||
|
for operation in ("stageService/stageStart", "battleService/battleStart", "battleService/battleEnd",
|
||||||
|
"battleService/recordBattleResult", "taskService/taskCompleteStep"):
|
||||||
|
with self.subTest(operation=operation):
|
||||||
|
self.legacy_pending()
|
||||||
|
rows = self.trace_rows() + [{"kind": "request", "operation": operation,
|
||||||
|
"request_id": "later", "body": {}}]
|
||||||
|
before = deepcopy(self.runner.state)
|
||||||
|
self.assertFalse(self.runner.recover_hidden_start(self.snapshot, self.write_trace(rows)))
|
||||||
|
self.assertEqual(self.runner.state, before)
|
||||||
|
|
||||||
|
def test_insufficient_trace_proof_never_mutates_journal(self):
|
||||||
|
for problem in ("role", "request_id", "later_settlement", "uncertain_write", "ambiguous_owner",
|
||||||
|
"second_reservation", "role_switch", "missing_role", "failed_http", "failed_code",
|
||||||
|
"wrong_level", "duplicate_response", "newer_unknown_start", "corrupt", "duplicate_field",
|
||||||
|
"invalid_reservation", "corrupt_other_owner_reservation"):
|
||||||
|
with self.subTest(problem=problem):
|
||||||
|
self.legacy_pending()
|
||||||
|
rows = self.trace_rows()
|
||||||
|
if problem == "role":
|
||||||
|
rows[0]["body"]["master"]["id"] = 18
|
||||||
|
elif problem == "request_id":
|
||||||
|
rows[2]["request_id"] = "different"
|
||||||
|
elif problem in ("later_settlement", "uncertain_write"):
|
||||||
|
rows.append({"kind": "request", "request_id": "later", "body": {}, "operation":
|
||||||
|
"battleService/battleEnd" if problem == "later_settlement" else "unknownService/doSomething"})
|
||||||
|
elif problem == "ambiguous_owner":
|
||||||
|
self.runner.state["counts"][self.runner.key(self.snapshot, self.stage).replace("17:", "18:", 1)] = 1
|
||||||
|
elif problem == "second_reservation":
|
||||||
|
self.runner.state["counts"]["17:2026-11-13:0101:3"] = 1
|
||||||
|
elif problem == "invalid_reservation":
|
||||||
|
self.runner.state["counts"] = {"17:invalid:0101:3": 1}
|
||||||
|
elif problem == "corrupt_other_owner_reservation":
|
||||||
|
self.runner.state["counts"]["18:2026-11-14:0101:3"] = "1"
|
||||||
|
elif problem == "role_switch":
|
||||||
|
rows.insert(2, {"kind": "response", "operation": "读取角色", "body": {"master": {"id": 18}}})
|
||||||
|
elif problem == "missing_role":
|
||||||
|
rows.pop(0)
|
||||||
|
elif problem == "failed_http":
|
||||||
|
rows[2]["http_status"] = 500
|
||||||
|
elif problem == "failed_code":
|
||||||
|
rows[2]["body"]["resCode"] = 2
|
||||||
|
elif problem == "wrong_level":
|
||||||
|
rows[1]["body"]["stageLevel"] = "1"
|
||||||
|
elif problem == "duplicate_response":
|
||||||
|
rows.append(deepcopy(rows[2]))
|
||||||
|
rows[-1]["body"]["stageEvent"]["hideStageId"] = "another"
|
||||||
|
elif problem == "newer_unknown_start":
|
||||||
|
rows.append(dict(rows[1], request_id="newer"))
|
||||||
|
self.runner.save()
|
||||||
|
before = deepcopy(self.runner.state)
|
||||||
|
disk = self.runner.path.read_bytes()
|
||||||
|
trace = self.write_trace(rows)
|
||||||
|
if problem == "corrupt":
|
||||||
|
with trace.open("a", encoding="utf-8") as stream:
|
||||||
|
stream.write("\n{broken")
|
||||||
|
elif problem == "duplicate_field":
|
||||||
|
trace.write_text(trace.read_text(encoding="utf-8").replace(
|
||||||
|
'"request_id": "start-1"', '"request_id": "other", "request_id": "start-1"'), encoding="utf-8")
|
||||||
|
self.assertFalse(self.runner.recover_hidden_start(self.snapshot, trace))
|
||||||
|
self.assertEqual(self.runner.state, before)
|
||||||
|
self.assertEqual(self.runner.path.read_bytes(), disk)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
+38
-4
@@ -1,8 +1,10 @@
|
|||||||
# 牧羊人之心牧场助手 · Web 2.0.7
|
# 牧羊人之心牧场助手 · Web 2.0.12
|
||||||
|
|
||||||
## 产品约束
|
## 产品约束
|
||||||
|
|
||||||
把现有桌面助手的功能和操作结构迁移至单管理员 Web 工作台。桌面版是页面顺序、信息密度、业务名称、保护条件与交互的依据,保留桌面兼容。本轮 Web 发布目标为 `2.0.7`,源码入口 `main`,游戏数据版本 `1.9.68`;桌面正式版保留 `1.2.0`。启动与配置见 [运行说明](README.md),Docker 与更新条件见 [部署说明](../deploy/web/README.md)。
|
把现有桌面助手的功能和操作结构迁移至单管理员 Web 工作台。桌面版是页面顺序、信息密度、业务名称、保护条件与交互的依据,保留桌面兼容。Web `2.0.12`,源码发布入口 `main`,游戏数据版本 `1.9.68`;桌面正式版保留 `1.2.0`。启动与配置见 [运行说明](README.md),Docker 与更新条件见 [部署说明](../deploy/web/README.md),既有功能与历史验证见 [2.0.8 发布说明](../analysis/RELEASE_2_0_8.md)。
|
||||||
|
|
||||||
|
2.0.12 聚焦扫荡隐藏事件的自动战斗接续与旧缺失响应记录的本地归档;保留账号简短状态、错误、表格、表单与原单一底部分类日志,见 [本版发布说明](../analysis/RELEASE_2_0_12.md)。
|
||||||
|
|
||||||
使用者在 Windows 本机配置、验证,随后可在 Linux Docker 常驻运行。多个浏览器访问同一个管理员工作台;账号互相隔离,各账号串行执行,账号之间可以并行。
|
使用者在 Windows 本机配置、验证,随后可在 Linux Docker 常驻运行。多个浏览器访问同一个管理员工作台;账号互相隔离,各账号串行执行,账号之间可以并行。
|
||||||
|
|
||||||
@@ -17,19 +19,45 @@
|
|||||||
## 核心操作
|
## 核心操作
|
||||||
|
|
||||||
- 账号密码登录后选择区服进入;恢复已保存会话;退出与清除登录记录。游戏凭据仅交给同源服务端,不进入浏览器持久存储或 URL。
|
- 账号密码登录后选择区服进入;恢复已保存会话;退出与清除登录记录。游戏凭据仅交给同源服务端,不进入浏览器持久存储或 URL。
|
||||||
- 手动选服、恢复会话和自动重登成功读取角色后,均默认开启策略,自动执行已配置且已勾选的功能,可在顶部停止;不改变各子功能的勾选。获取区服候选及失败候选不视为登录成功,界面以服务端在线与运行状态为准。导入配置只替换规则并停止执行,下次成功登录仍自动开启;服务重启后未成功登录时不直接执行。
|
- 手动选服、恢复会话和自动重登成功读取角色后,默认执行已配置且已勾选的功能,不改变各子功能勾选。用户手动“停止”跨掉线、重登和服务重启保留,点击“开启”恢复;导入配置只替换规则,保留用户启停意图。获取区服候选及失败候选不视为登录成功,服务重启后未成功登录时不执行策略,界面以服务端状态为准。
|
||||||
- 配置通过中文 schema 生成原生控件;逐蛋孵化/补货规则、物品赠礼保留量、逐魔物培养目标、关卡规则等直接在对应页面编辑。自动保存显示待保存、保存中、失败与已保存状态。
|
- 配置通过中文 schema 生成原生控件;逐蛋孵化/补货规则、物品赠礼保留量、逐魔物培养目标、关卡规则等直接在对应页面编辑。自动保存显示待保存、保存中、失败与已保存状态。
|
||||||
- 培育室扩建、牧场锁定/解锁、批量派遣/喂养、上下文菜单和费用二次确认沿用核心行为。切换功能页只读取视图,不触发游戏写操作。
|
- 培育室扩建、牧场锁定/解锁、批量派遣/喂养、上下文菜单和费用二次确认沿用核心行为。切换功能页只读取视图,不触发游戏写操作。
|
||||||
- 主线默认当前主线,可切换筛选。地图按地区默认折叠,展示普通关卡、矿洞、难度、次数和工具库存。探险支持队员手选/自动与完成后自动领奖说明。
|
- 主线默认当前主线,可切换筛选。地图按地区默认折叠,展示普通关卡、矿洞、难度、次数和工具库存。探险支持队员手选/自动与完成后自动领奖说明。
|
||||||
- 数据分析用真实 DTO 绘制 SVG 条形图,保留来源筛选、体力效率、样本和不确定性说明。没有样本时明确说明。
|
- 数据分析用真实 DTO 绘制 SVG 条形图,保留来源筛选、体力效率、样本和不确定性说明。没有样本时明确说明。
|
||||||
- 策略统一导入导出;收益 CSV/XLSX 导入与可用数据下载。错误展示具体原因,不把不支持的任务伪装成可执行任务。
|
- 策略统一导入导出;收益 CSV/XLSX 导入与可用数据下载。错误展示具体原因,不把不支持的任务伪装成可执行任务。
|
||||||
- 帮助可检查 GitHub 正式版本并提交受控更新请求。未配置部署器时明确显示原因,更新提交不表示更新成功。
|
- 帮助可检查 GitHub 正式版本并提交受控更新请求。未配置部署器时明确显示原因,更新提交不表示更新成功。
|
||||||
- 已在 2.0.1 完成私有仓库和 GHCR 认证的部署,可在 2.0.7 发布就绪后直接通过“帮助 → 检查版本更新…”升级,无需先安装 2.0.2、重复初始化或替换宿主机更新器;升级完成后刷新网页以加载新版界面,安装结果以宿主机健康检查为准。
|
- 已在 2.0.1 完成私有仓库和 GHCR 认证的部署,稳定 Release 与正式镜像发布后,可直接通过“帮助 → 检查版本更新…”升级,无需先安装 2.0.2、重复初始化或替换宿主机更新器;升级完成后刷新网页以加载新版界面,安装结果以宿主机健康检查为准。
|
||||||
|
|
||||||
|
## 2.0.12 本轮范围
|
||||||
|
|
||||||
|
- 完整入场响应与原始队伍快照等原始输入均已保存且可验证时,隐藏事件才按 `stageEvent.hideStageId` 直接构建隐藏关卡难度1的战斗,关闭扫荡并自动战斗,无需手动确认,不再发送第二次 `stageStart`;`battleEnd` / `recordBattleResult` 使用隐藏 ID。
|
||||||
|
- 新记录或可恢复旧记录仅在完整入场及原始输入可验证时自动续打,保留用户停止、来源策略及未知已发送请求的核对约束。旧记录即使能从 trace 找回隐藏 ID,缺少原始队伍也保留中文待核对状态,不用当前属性替代原始属性,不发送游戏写请求。
|
||||||
|
- 现场旧 `0211 / 3` pending 的原始响应已被日志轮转覆盖,隐藏 ID 无法还原。仅对符合精确四字段 legacy 形态、严格确认已入场且未结算的这类旧阶段,保留证据,本地归档为未完成并放弃,不提交胜负、不重发入场,让后续策略继续。归档不表示服务端已结算,本版未在生产打通当前这场战斗。
|
||||||
|
|
||||||
|
## 2.0.11 沿用修复
|
||||||
|
|
||||||
|
- Linux 战斗子进程从匿名临时文件一次读取完整 stdin,保留取消、超时及输入大小检查。
|
||||||
|
- 升级后,旧委托备料记录若已确认入场、未发送结算且符合技术失败条件,按原客户端协议记录失败并退出一次;兼容来源任务与步骤均为0的记录,不重新入场或提交胜利。
|
||||||
|
- 保存的原始战斗输入最多用于一次本地恢复;完整战果校验通过后按战斗时钟续交尚未发送的结果。未知已发送写请求不重放。
|
||||||
|
- 手动停止阻止恢复提交;内部暂停保留用户运行意愿,来源策略关闭时明确等待启用,不自动开启策略。
|
||||||
|
- 状态接口透出5个安全策略状态字段,区分运行意愿、实际执行与等待原因;修复导航及策略关闭时的能力误报,保留真实不支持、资源不足及失败原因。具体行为见 [发布说明](../analysis/RELEASE_2_0_11.md)。
|
||||||
|
|
||||||
|
沿用 2.0.9 的快速 HP/DPS 模型、伤害配置、按剩余步骤计算的委托备料及正常潜能误报修复,历史范围见 [2.0.9 发布说明](../analysis/RELEASE_2_0_9.md)。
|
||||||
|
|
||||||
|
## 2.0.8 自动委托与每日历史
|
||||||
|
|
||||||
|
- 自动委托包含“当前委托 / 每日记录”。当前页展示原始候选、任务状态、标注奖励及选择 / 回退原因;城市锁定候选显示不可接取。
|
||||||
|
- 策略允许且满足城市、次数、资源与步骤支持条件的候选,跨城市按静态预计氪金20→15→10全局排序。高档不可用时日志说明原因,再选择可执行的低档,不保证全部接取20档。
|
||||||
|
- 每日记录按账号、区服、角色隔离,以北京时间(UTC+8)自然日查询接取、推进、领奖和待核对事件,刷新和服务重启后可查。每角色保留最近90天、最多5000条事件。
|
||||||
|
- 预计奖励与已确认实际奖励分别展示;实际氪金仅来自确认成功的 `taskComplete` 领奖回包 `response.reward.ke`,缺失金额显示“未确认”。接取、推进、预计奖励及旧完成标记不作为到账证据。
|
||||||
|
- 旧历史仅从本地任务 journal 可证实的操作部分回填,不推造缺失记录。每日历史用于业务进度,运行详情继续使用原单一底部“自动委托”分类日志。
|
||||||
|
|
||||||
## 2.0.7 主培养与资质备用
|
## 2.0.7 主培养与资质备用
|
||||||
|
|
||||||
同种只自动培养已养成的高等级主培养;新资质更好的魔物只作为备用保留,不分配经验、礼物或潜能材料。已启用种类按主培养1只、更优备用最多1只整理,新备用严格更优才替换,同分保留已有备用。主培养到上限或冷却时等待,不向同种备用转移资源。硬保护保留,未勾选种类不扩大自动整理范围。
|
同种只自动培养已养成的高等级主培养;新资质更好的魔物只作为备用保留,不分配经验、礼物或潜能材料。已启用种类按主培养1只、更优备用最多1只整理,新备用严格更优才替换,同分保留已有备用。主培养到上限或冷却时等待,不向同种备用转移资源。硬保护保留,未勾选种类不扩大自动整理范围。
|
||||||
|
|
||||||
|
2.0.8 沿用上述修复及现有界面,历史功能与验证记录见 [2.0.7 发布说明](../analysis/RELEASE_2_0_7.md)。
|
||||||
|
|
||||||
## 表单布局(2.0.6 起)
|
## 表单布局(2.0.6 起)
|
||||||
|
|
||||||
勾选框与右侧文字组成一组;数字、文本与下拉框采用标签在上、控件在下的布局。设置区限定合理宽度,并按可用空间排为多列,每日领取项目在单独分组中排列。界面尺寸变化不改变配置路径、自动保存或策略执行规则。
|
勾选框与右侧文字组成一组;数字、文本与下拉框采用标签在上、控件在下的布局。设置区限定合理宽度,并按可用空间排为多列,每日领取项目在单独分组中排列。界面尺寸变化不改变配置路径、自动保存或策略执行规则。
|
||||||
@@ -69,6 +97,12 @@
|
|||||||
|
|
||||||
## 安全与验证
|
## 安全与验证
|
||||||
|
|
||||||
|
本版共 **491 项唯一仓库测试:489 通过、2 项 Windows 预期跳过,0 失败 / 错误**,见 [2.0.12 发布说明](../analysis/RELEASE_2_0_12.md#验证)。2.0.11 的测试结果见 [历史发布说明](../analysis/RELEASE_2_0_11.md#验证),不计入本版;战斗模型仍为近似实现。
|
||||||
|
|
||||||
|
2.0.9 的历史验证见 [历史发布说明](../analysis/RELEASE_2_0_9.md#验证),不计入本版。
|
||||||
|
|
||||||
|
2.0.8 共验证739项独立测试:736通过、3项 Windows 跳过;其中非浏览器662项(659通过、3跳过),浏览器77项全部验证通过。证据与发布门禁见 [发布说明](../analysis/RELEASE_2_0_8.md#验证);历史版本结果不计入本版。
|
||||||
|
|
||||||
不发真实游戏 API 测试,不读取或更改私人 `local_state` 账号。浏览器测试仅使用临时目录、fake 后端或服务端离线演示。所有游戏文本用 `textContent` 呈现;日志使用服务端脱敏数据。管理登录、同源校验与 cookie 由 API 负责。
|
不发真实游戏 API 测试,不读取或更改私人 `local_state` 账号。浏览器测试仅使用临时目录、fake 后端或服务端离线演示。所有游戏文本用 `textContent` 呈现;日志使用服务端脱敏数据。管理登录、同源校验与 cookie 由 API 负责。
|
||||||
|
|
||||||
## 技术默认假设
|
## 技术默认假设
|
||||||
|
|||||||
+29
-10
@@ -1,19 +1,30 @@
|
|||||||
# Web 2.0.7 运行说明
|
# Web 2.0.12 运行说明
|
||||||
|
|
||||||
本轮 Web 发布目标 **2.0.7**,源码入口 `main`,游戏资料基线 **1.9.68**。桌面正式版保留 **1.2.0**,入口为 `python -m ranch_assistant`;Web 使用独立依赖与数据根。
|
Web **2.0.12**,源码发布入口 `main`,游戏资料基线 **1.9.68**。桌面正式版保留 **1.2.0**,入口为 `python -m ranch_assistant`;Web 使用独立依赖与数据根。自动委托提供当前委托与每日记录,功能和历史验证状态见 [2.0.8 发布说明](../analysis/RELEASE_2_0_8.md)。
|
||||||
|
|
||||||
|
2.0.12 修复扫荡触发隐藏关卡后的接续:完整入场响应与原始队伍快照等原始输入均已保存且可验证时,新记录或可恢复旧记录才按 `stageEvent.hideStageId` 构建隐藏关卡难度1的战斗,自动战斗且无需手动确认,不再发送第二次 `stageStart`,战后使用隐藏 ID 结算。旧记录即使能从 trace 找回隐藏 ID,缺少原始队伍也保留中文待核对状态,不用当前属性替代原始属性,不发送游戏写请求。现场旧 `0211 / 3` pending 的原始响应已被日志轮转覆盖,隐藏 ID 无法还原;仅对符合精确四字段 legacy 形态、严格确认已入场且未结算的这类旧阶段,保留证据、本地归档为未完成并放弃,不提交胜负或重发入场,让后续策略继续。归档不等于服务端已结算,本版未在生产打通当前这场战斗,见 [本版发布说明](../analysis/RELEASE_2_0_12.md)。
|
||||||
|
|
||||||
|
正常执行默认使用现有内置实验运行时入口的快速 HP/DPS 模型,保留现有伤害配置,无需选择新模式;逐帧实现仅供研发。模型按双方属性、血量、每秒伤害、时间与目标估算胜利、战败或超时,仍有机制简化,不保证全部关卡可通关或与客户端结果一致。
|
||||||
|
|
||||||
Web 采用 FastAPI / Uvicorn 和原生 HTML/CSS/ES 模块,无 Node、npm 或前端编译步骤,不安装 PySide6。页面和策略能力沿用现有核心,详细业务范围与原有限制见 [桌面使用说明](../ranch_assistant/README.md)。多浏览器连接同一个管理员工作台;一个服务实例内,各账号独立线程并行,同一账号操作串行。
|
Web 采用 FastAPI / Uvicorn 和原生 HTML/CSS/ES 模块,无 Node、npm 或前端编译步骤,不安装 PySide6。页面和策略能力沿用现有核心,详细业务范围与原有限制见 [桌面使用说明](../ranch_assistant/README.md)。多浏览器连接同一个管理员工作台;一个服务实例内,各账号独立线程并行,同一账号操作串行。
|
||||||
|
|
||||||
## 迁移清单
|
## 迁移清单
|
||||||
|
|
||||||
- [x] 原15页:登录、培育室、背包、牧场、每日事务、自动孵蛋、自动主线、战斗记录、自动赠礼、自动委托、自动探险、自动扫荡、数据分析、执行计划、收益资料。
|
- [x] 原15页:登录、培育室、背包、牧场、每日事务、自动孵蛋、自动主线、战斗记录、自动赠礼、自动委托、自动探险、自动扫荡、数据分析、执行计划、收益资料。
|
||||||
- [x] 保留账号页签、顶部数值与统一启停、可调日志;规则自动保存,配置与统计按账号/角色隔离,每次成功登录后自动执行已配置且已勾选的功能,可在顶部停止。
|
- [x] 保留账号页签、顶部数值与统一启停、可调日志;规则自动保存,配置与统计按账号/角色隔离,未手动停止时,成功登录后自动执行已配置且已勾选的功能;手动暂停跨重登保留,可在顶部开启。
|
||||||
- [x] Windows Python 启动与离线演示;Web 导入链和依赖不使用 Qt,无 Node 构建步骤。
|
- [x] Windows Python 启动与离线演示;Web 导入链和依赖不使用 Qt,无 Node 构建步骤。
|
||||||
- [x] 提供 Linux Docker 与稳定 2.x 受控更新、停机备份及失败回滚脚本;历史 Linux Docker 部署、持久化权限、健康检查和定时更新检查烟测见下文。
|
- [x] 提供 Linux Docker 与稳定 2.x 受控更新、停机备份及失败回滚脚本;历史 Linux Docker 部署、持久化权限、健康检查和定时更新检查烟测见下文。
|
||||||
- [x] 本轮发布目标为 `2.0.7`,保留桌面兼容;战斗模拟为近似模型,特殊关卡并非全部支持,真实游戏 API 验收范围不因版本号变更而扩大。
|
- [x] `2.0.8` 自动委托当前 / 每日记录、持久化历史及奖励证据区分;739项独立测试中736通过、3项 Windows 跳过,浏览器77项全部验证通过。战斗模拟仍为近似模型,特殊关卡并非全部支持。
|
||||||
- 2.0.7 修复同种重复培养:主培养与资质备用分离,自动喂养、赠礼和潜能突破仅作用于主培养,启用种类固定主培养1只与更优备用最多1只。详见 [本版发布说明](../analysis/RELEASE_2_0_7.md)。
|
- 沿用 2.0.7 的同种重复培养修复:主培养与资质备用分离,自动喂养、赠礼和潜能突破仅作用于主培养,启用种类固定主培养1只与更优备用最多1只。详见 [2.0.7 发布说明](../analysis/RELEASE_2_0_7.md)。
|
||||||
- 2.0.3 修复 2.0.2 日志布局:所有页签复用原有底部日志区,按当前账号与功能筛选,默认收起;操作约定见 [产品说明](PRODUCT.md#203-底部分类日志),验收结果见 [发布说明](../analysis/RELEASE_2_0_3.md#验证)。
|
- 2.0.3 修复 2.0.2 日志布局:所有页签复用原有底部日志区,按当前账号与功能筛选,默认收起;操作约定见 [产品说明](PRODUCT.md#203-底部分类日志),验收结果见 [发布说明](../analysis/RELEASE_2_0_3.md#验证)。
|
||||||
|
|
||||||
|
## 自动委托(2.0.8)
|
||||||
|
|
||||||
|
- “当前委托”查看任务、原始候选和选择 / 回退原因;城市锁定候选显示不可接取。策略允许且满足城市、次数、资源和步骤条件的候选,跨城市按预计氪金20→15→10排序,日志说明高档不可用的原因。
|
||||||
|
- “每日记录”按账号、区服、角色及北京时间(UTC+8)自然日查询接取、推进、领奖与待核对事件。历史持久保存,刷新或重启后可查;每角色保留最近90天、最多5000条事件。
|
||||||
|
- 预计氪金来自静态任务配置,已确认氪金仅取确认成功的领奖回包 `response.reward.ke`;金额缺失显示“未确认”。接取、推进、旧完成标记和预计数额不作为实际奖励证据。
|
||||||
|
- 旧历史仅从本地任务 journal 可证实的操作部分回填,不推造缺失的过去。业务历史之外的运行详情继续使用原单一底部“自动委托”分类日志。完整行为见 [发布说明](../analysis/RELEASE_2_0_8.md)。
|
||||||
|
|
||||||
## Windows 本地运行
|
## Windows 本地运行
|
||||||
|
|
||||||
使用 Python 3.12+,在项目根目录执行(本机已安装 3.13):
|
使用 Python 3.12+,在项目根目录执行(本机已安装 3.13):
|
||||||
@@ -32,13 +43,13 @@ py -3 -m venv .venv-web
|
|||||||
.\Start_Ranch_Web.cmd --demo --data-dir "$env:TEMP\ranch-web-demo-new" --no-browser
|
.\Start_Ranch_Web.cmd --demo --data-dir "$env:TEMP\ranch-web-demo-new" --no-browser
|
||||||
```
|
```
|
||||||
|
|
||||||
健康检查 `GET /api/health` 不访问游戏 API。关闭终端时使用 Ctrl+C,让应用正常关闭账号队列。手动选服、恢复会话及自动重登成功读取角色后,均默认开启策略,只执行已勾选的功能,子功能不会全选。顶部“停止”暂停策略,仍保留状态监控;可用“开启”继续。登录后默认执行已勾选策略;只有手动“停止”才暂停,手动“开启”恢复。启停选择跨掉线、重新登录和服务重启保存,导入策略不会改变这个选择。
|
健康检查 `GET /api/health` 不访问游戏 API。关闭终端时使用 Ctrl+C,让应用正常关闭账号队列。手动选服、恢复会话及自动重登成功读取角色后,默认执行已勾选功能,子功能不会全选;用户手动“停止”则继续保持暂停,点击“开启”恢复。启停选择跨掉线、重登和服务重启保存,导入策略保留该选择;停止策略后仍保留状态监控。
|
||||||
|
|
||||||
### 后台运行与断线处理
|
### 后台运行与断线处理
|
||||||
|
|
||||||
关闭网页或退出 Web 管理登录不会停止服务器上的账号监控和已开启策略。账号监控、重登及策略执行都由服务端管理。手动“停止”只暂停策略,连接监控与掉线重登继续;该暂停在重新登录和服务重启后仍保留,点击“开启”恢复。
|
关闭网页或退出 Web 管理登录不会停止服务器上的账号监控和已开启策略。账号监控、重登及策略执行都由服务端管理。手动“停止”只暂停策略,连接监控与掉线重登继续;该暂停在重新登录和服务重启后仍保留,点击“开启”恢复。
|
||||||
|
|
||||||
临时网络故障采用退避后的只读状态检查,确认角色连接恢复后自动继续原先启用的策略。会话失效时按登录页等待时长自动重新登录。账号状态区分用户暂停、临时恢复和请求待核对,心跳成功不等于策略已经运行;日志保留失败原因及恢复结果。未确认的消耗请求仍保留核对记录,不自动重复提交。
|
临时网络故障采用退避后的只读状态检查,确认角色连接恢复后自动继续原先启用的策略。会话失效时按登录页等待时长自动重新登录。账号状态区分用户暂停、临时恢复和请求待核对,心跳成功不等于策略已经运行;日志保留失败原因及恢复结果。内部暂停保留用户运行意愿;来源策略关闭时明确等待启用,不自动勾选。已保存的完整战果仅在用户允许运行、来源策略已启用、原入场及来源校验通过且战斗时钟满足时续交尚未发送的结果;手动停止阻止恢复提交,未知已发送写请求保留核对记录,不自动重发。
|
||||||
|
|
||||||
服务重启会保留配置、加密会话及启停选择,并自动恢复有登录记录的账号。只有清除登录记录或移除账号才取消持续自动登录;缺少密码、区服或原角色信息时显示具体原因。运行日志按账号限量持久保存,旧角色数据会标注缓存状态。
|
服务重启会保留配置、加密会话及启停选择,并自动恢复有登录记录的账号。只有清除登录记录或移除账号才取消持续自动登录;缺少密码、区服或原角色信息时显示具体原因。运行日志按账号限量持久保存,旧角色数据会标注缓存状态。
|
||||||
|
|
||||||
@@ -97,13 +108,21 @@ sh start-web.sh --no-browser
|
|||||||
|
|
||||||
Web 检查固定官方 GitHub Releases 的稳定 `v2.x.y`,跳过桌面 1.x、未来 3.x、草稿和预发布。开发版本 `2.0.0.dev1` 可升级至同数字的正式 `v2.0.0`;没有正式 Web 2 发布时明确显示暂无更新。Windows 默认仅检查;Web “更新”按钮仅在宿主机显式启用并有有效只读心跳时可提交 `pending` 请求,安装、备份和回滚由宿主机执行。默认定时检查只通知,自动安装需操作者 opt-in。
|
Web 检查固定官方 GitHub Releases 的稳定 `v2.x.y`,跳过桌面 1.x、未来 3.x、草稿和预发布。开发版本 `2.0.0.dev1` 可升级至同数字的正式 `v2.0.0`;没有正式 Web 2 发布时明确显示暂无更新。Windows 默认仅检查;Web “更新”按钮仅在宿主机显式启用并有有效只读心跳时可提交 `pending` 请求,安装、备份和回滚由宿主机执行。默认定时检查只通知,自动安装需操作者 opt-in。
|
||||||
|
|
||||||
已在 **2.0.1** 完成私有仓库和 GHCR 认证的部署,可在 2.0.7 稳定 Release 和正式镜像就绪、宿主机心跳有效后,直接通过“帮助 → 检查版本更新…”升级 **2.0.7**,无需先安装 2.0.2、重复初始化或替换宿主机更新器。升级完成后刷新网页以加载新版界面,底部日志默认收起。安装结果以宿主机健康检查为准;首次配置仅供尚未初始化的宿主机参考。
|
已在 **2.0.1** 完成私有仓库和 GHCR 认证的部署,稳定 Release 和正式镜像就绪、宿主机心跳有效后,可直接通过“帮助 → 检查版本更新…”升级 **2.0.12**,无需先安装 2.0.2、重复初始化或替换宿主机更新器。升级完成后刷新网页以加载新版界面,底部日志默认收起。安装结果以宿主机健康检查为准;首次配置仅供尚未初始化的宿主机参考。
|
||||||
|
|
||||||
## 离线验证
|
## 离线验证
|
||||||
|
|
||||||
2.0.7 验证结果统一见 [发布说明](../analysis/RELEASE_2_0_7.md#验证),以下历史记录不计入本版验收。
|
本版共 **491 项唯一仓库测试:489 通过、2 项 Windows 预期跳过,0 失败 / 错误**,见 [2.0.12 发布说明](../analysis/RELEASE_2_0_12.md#验证)。镜像工作流在安装测试依赖后,独立执行隐藏关卡 handoff、battles、engine 三个专用回归模块;通过 `ranch_web/requirements-test.txt` 安装 HTTPX 的修复继续保留。2.0.11 的测试结果见 [历史发布说明](../analysis/RELEASE_2_0_11.md#验证),不计入本版。以下为继续保留的子进程传输、战斗恢复、能力展示、Web 生命周期、恢复契约及状态 API 回归命令:
|
||||||
|
|
||||||
### 历史验证记录(不计入 2.0.7)
|
```console
|
||||||
|
python -B -m unittest ranch_assistant.tests.test_battle_worker_transport ranch_assistant.tests.test_battle_recovery ranch_assistant.tests.test_battle_capability_presentation ranch_web.tests.test_lifecycle_recovery ranch_web.tests.test_battle_recovery_contract ranch_web.tests.test_status_recovery_api -v
|
||||||
|
```
|
||||||
|
|
||||||
|
2.0.9 的历史验证见 [历史发布说明](../analysis/RELEASE_2_0_9.md#验证),不计入本版。
|
||||||
|
|
||||||
|
2.0.8 共验证739项独立测试:736通过、3项 Windows 跳过;其中非浏览器662项(659通过、3跳过),浏览器77项全部验证通过。分组结果与证据见 [发布说明](../analysis/RELEASE_2_0_8.md#验证)。2.0.7 的结果保留在 [历史发布说明](../analysis/RELEASE_2_0_7.md#验证),以下历史记录也不计入本版验收。
|
||||||
|
|
||||||
|
### 历史验证记录(不计入 2.0.8)
|
||||||
|
|
||||||
2.0.2 验证记录见 [历史发布说明](../analysis/RELEASE_2_0_2.md#验证)。
|
2.0.2 验证记录见 [历史发布说明](../analysis/RELEASE_2_0_2.md#验证)。
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
"""Headless Web workspace for the ranch assistant."""
|
"""Headless Web workspace for the ranch assistant."""
|
||||||
|
|
||||||
__version__ = "2.0.7"
|
__version__ = "2.0.12"
|
||||||
GAME_VERSION = "1.9.68"
|
GAME_VERSION = "1.9.68"
|
||||||
|
|
||||||
__all__ = ["__version__", "GAME_VERSION"]
|
__all__ = ["__version__", "GAME_VERSION"]
|
||||||
|
|||||||
+3
-1
@@ -577,9 +577,11 @@ def create_app(data_dir=None, manager=None, config=None, updates=None) -> FastAP
|
|||||||
if not isinstance(value, dict):
|
if not isinstance(value, dict):
|
||||||
raise HTTPException(500, "账号状态返回格式不正确")
|
raise HTTPException(500, "账号状态返回格式不正确")
|
||||||
result = {field: value.get(field) for field in ("id", "label", "connected", "demo", "running", "busy", "revision", "error",
|
result = {field: value.get(field) for field in ("id", "label", "connected", "demo", "running", "busy", "revision", "error",
|
||||||
"connection_state", "connection_message", "last_game_success_at", "next_retry_at")}
|
"connection_state", "connection_message", "last_game_success_at", "next_retry_at",
|
||||||
|
"strategy_requested", "manual_stop", "strategy_state", "strategy_message", "strategy_retry_at")}
|
||||||
result["error"] = public_error(result["error"])
|
result["error"] = public_error(result["error"])
|
||||||
result["connection_message"] = public_error(result["connection_message"])
|
result["connection_message"] = public_error(result["connection_message"])
|
||||||
|
result["strategy_message"] = public_error(result["strategy_message"])
|
||||||
auto = value.get("auto_relogin_status")
|
auto = value.get("auto_relogin_status")
|
||||||
result["auto_relogin_status"] = ({field: auto.get(field) for field in ("state", "message", "next_attempt_at")}
|
result["auto_relogin_status"] = ({field: auto.get(field) for field in ("state", "message", "next_attempt_at")}
|
||||||
if isinstance(auto, dict) else None)
|
if isinstance(auto, dict) else None)
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
-r requirements.txt
|
||||||
|
httpx>=0.28,<1
|
||||||
+109
-15
@@ -101,6 +101,7 @@ class _Job:
|
|||||||
workspace: str = ""
|
workspace: str = ""
|
||||||
category: str = "general"
|
category: str = "general"
|
||||||
due_kind: str | None = None
|
due_kind: str | None = None
|
||||||
|
commission_failure: str = ""
|
||||||
|
|
||||||
def public(self):
|
def public(self):
|
||||||
operation = {"__config": "set_config", "__view": "view"}.get(self.operation, self.operation)
|
operation = {"__config": "set_config", "__view": "view"}.get(self.operation, self.operation)
|
||||||
@@ -334,12 +335,54 @@ class AccountWorker:
|
|||||||
self._legacy_pending.pop(identity)
|
self._legacy_pending.pop(identity)
|
||||||
self._save_run_intents()
|
self._save_run_intents()
|
||||||
|
|
||||||
|
def _pending_battle_recovery(self):
|
||||||
|
classify = getattr(self.engine, "pending_battle_recovery", None)
|
||||||
|
if callable(classify):
|
||||||
|
status = classify()
|
||||||
|
return status if isinstance(status, dict) else {}
|
||||||
|
# Compatibility for older Engine test doubles without the public API.
|
||||||
|
if self.engine.snapshot is not None:
|
||||||
|
record = self.engine.battle_journal.pending(self.engine.snapshot)
|
||||||
|
if record:
|
||||||
|
if self.engine.battles.resumable_task_clock(record) is True:
|
||||||
|
return {"resumable": True, "message": "战果已保存;等待结算时间及对应策略启用后续交"}
|
||||||
|
return {}
|
||||||
|
|
||||||
def _pending_execution_reason(self):
|
def _pending_execution_reason(self):
|
||||||
|
suffix = ";禁止自动重发,请在游戏内核对结果"
|
||||||
if self.active_identity in self._legacy_pending:
|
if self.active_identity in self._legacy_pending:
|
||||||
return "赠礼、装填或喂养请求结果待核对,禁止自动重发;后台继续读取游戏状态,确认后自动恢复已勾选策略"
|
kind = self._legacy_pending[self.active_identity]["kind"]
|
||||||
if self.engine.snapshot is not None and (self.engine._progression_pending()
|
return {"gift": "赠礼", "hatch": "装填", "feed": "喂养"}[kind] + "请求结果待核对" + suffix
|
||||||
or self.engine.explore_planner.pending(self.engine.snapshot) or self.engine._breakthrough_pending):
|
if self.engine.snapshot is None:
|
||||||
return "存在未确认的任务、战斗、探险或突破请求,禁止自动重发;后台继续核对,核对完成后恢复已勾选策略"
|
return ""
|
||||||
|
if self.engine._progression_pending():
|
||||||
|
sweep = self.engine.sweeper.state.get("pending")
|
||||||
|
if sweep:
|
||||||
|
return f"扫荡(关卡 {sweep.get('stage', '')}):{sweep.get('phase') or '请求结果待核对'}" + suffix
|
||||||
|
recovery = self._pending_battle_recovery()
|
||||||
|
if recovery.get("state") == "blocked_policy":
|
||||||
|
return recovery.get("message") or "等待启用本次战斗的来源策略后恢复"
|
||||||
|
if recovery.get("resumable") is not True:
|
||||||
|
record = self.engine.battle_journal.pending(self.engine.snapshot) or {}
|
||||||
|
label = record.get("description") or ("战斗" if record.get("stage_id") else "任务")
|
||||||
|
if record.get("stage_id"):
|
||||||
|
label += f"(关卡 {record['stage_id']},难度 {record.get('difficulty') or 1})"
|
||||||
|
detail = record.get("message") or "请求结果待核对"
|
||||||
|
if record.get("execution_status") == "timed_out" or record.get("terminal_reason") == "worker_wall_clock_limit":
|
||||||
|
detail = "本地战斗计算超时"
|
||||||
|
if (not record.get("battle_data") and not record.get("settlement_dispatched")
|
||||||
|
and not record.get("settlement_confirmed")
|
||||||
|
and record.get("path") in ("", "battleService/battleStart", "stageService/stageStart")):
|
||||||
|
detail += ",尚未提交结算"
|
||||||
|
return label + ":" + detail + suffix
|
||||||
|
explore = self.engine.explore_planner.pending(self.engine.snapshot)
|
||||||
|
if explore:
|
||||||
|
label = "探险出发" if explore.get("kind") == "explore_start" else "探险领奖"
|
||||||
|
return f"{label}(队伍 {explore.get('team_id', '')}):{explore.get('message') or '请求结果待核对'}" + suffix
|
||||||
|
if self.engine._breakthrough_pending:
|
||||||
|
record = self.engine._breakthrough_pending
|
||||||
|
label = "潜能提升" if record.get("kind") == "potential" else "突破"
|
||||||
|
return label + ":" + (record.get("message") or "请求结果待核对") + suffix
|
||||||
return ""
|
return ""
|
||||||
|
|
||||||
def _refresh_execution(self):
|
def _refresh_execution(self):
|
||||||
@@ -371,6 +414,9 @@ class AccountWorker:
|
|||||||
state, message = "recovering", self.connection_message
|
state, message = "recovering", self.connection_message
|
||||||
elif not self._running:
|
elif not self._running:
|
||||||
state, message = "offline", self.connection_message
|
state, message = "offline", self.connection_message
|
||||||
|
elif (recovery := self._pending_battle_recovery()).get("resumable") is True:
|
||||||
|
state = "recovering"
|
||||||
|
message = recovery.get("message") or "等待对应策略允许恢复"
|
||||||
else:
|
else:
|
||||||
state, message = "running", "已勾选的策略将自动执行"
|
state, message = "running", "已勾选的策略将自动执行"
|
||||||
return {"strategy_requested": requested, "manual_stop": not requested,
|
return {"strategy_requested": requested, "manual_stop": not requested,
|
||||||
@@ -450,10 +496,41 @@ class AccountWorker:
|
|||||||
# Attribution must not prevent an otherwise valid action.
|
# Attribution must not prevent an otherwise valid action.
|
||||||
category = "general"
|
category = "general"
|
||||||
self._attribute_task(category)
|
self._attribute_task(category)
|
||||||
|
try:
|
||||||
return _method(*args, **kwargs)
|
return _method(*args, **kwargs)
|
||||||
|
except CancelledBeforeDispatch:
|
||||||
|
raise
|
||||||
|
except Exception:
|
||||||
|
if category == "commissions":
|
||||||
|
# Enrich the existing error entry, preserving the original
|
||||||
|
# exception and its one-time reporting on the worker.
|
||||||
|
try:
|
||||||
|
source = args[0] if args else kwargs.get("intent", kwargs.get("action"))
|
||||||
|
if source is None and _name == "_run_progression_intent":
|
||||||
|
source = intent
|
||||||
|
self._commission_failure_context(engine, source)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
raise
|
||||||
|
|
||||||
setattr(engine, name, routed)
|
setattr(engine, name, routed)
|
||||||
|
|
||||||
|
def _commission_failure_context(self, engine, source):
|
||||||
|
if self._execution is None or threading.current_thread() is not getattr(self, "thread", None):
|
||||||
|
return
|
||||||
|
field = lambda key, default=None: source.get(key, default) if isinstance(source, dict) else getattr(source, key, default)
|
||||||
|
payload = field("payload") or {}
|
||||||
|
type_id = field("source_task_type_id") or field("task_type_id") or payload.get("taskTypeId")
|
||||||
|
info = engine._commission_info(type_id)
|
||||||
|
name = info.get("name") or type_id or "名称未记录"
|
||||||
|
reward = (info.get("reward") or {}).get("ke")
|
||||||
|
expected = f"标注{reward}氪金" if type(reward) in (int, float) else "标注氪金未记录"
|
||||||
|
path = field("path", "") or ""
|
||||||
|
kind = field("kind", "")
|
||||||
|
action = "接取" if path.endswith("taskLoopReceive") or kind in {"quest_accept", "progression_loop_accept"} else (
|
||||||
|
"领奖" if path.endswith("taskComplete") or kind in {"quest_complete", "progression_complete"} else "推进")
|
||||||
|
self._execution.commission_failure = f"委托「{name}」({expected}){action}异常,结果待核对"
|
||||||
|
|
||||||
def remember(self, value):
|
def remember(self, value):
|
||||||
with self._secret_lock:
|
with self._secret_lock:
|
||||||
if isinstance(value, dict):
|
if isinstance(value, dict):
|
||||||
@@ -544,7 +621,13 @@ class AccountWorker:
|
|||||||
notes = getattr(getattr(self.engine, name, None), "notes", ())
|
notes = getattr(getattr(self.engine, name, None), "notes", ())
|
||||||
sources.append((category, [self.safe_text(note) for note in notes[:512]]))
|
sources.append((category, [self.safe_text(note) for note in notes[:512]]))
|
||||||
for category, text in route_message(self.safe_text(message), context=self._task_category(), hints=note_hints(sources)):
|
for category, text in route_message(self.safe_text(message), context=self._task_category(), hints=note_hints(sources)):
|
||||||
self.log(text, category=category)
|
level = "info"
|
||||||
|
if category == "commissions":
|
||||||
|
if "战斗失败" in text:
|
||||||
|
level = "error"
|
||||||
|
elif any(marker in text for marker in ("结果未知", "未确认", "待确认", "等待核对", "奖励未记录")):
|
||||||
|
level = "warning"
|
||||||
|
self.log(text, category=category, level=level)
|
||||||
|
|
||||||
def _trace_event(self, event):
|
def _trace_event(self, event):
|
||||||
fields = [event.get("operation", "网络"), event.get("kind", "")]
|
fields = [event.get("operation", "网络"), event.get("kind", "")]
|
||||||
@@ -844,7 +927,7 @@ class AccountWorker:
|
|||||||
if (job.consuming and job.operation != "start"
|
if (job.consuming and job.operation != "start"
|
||||||
and failure_sequence == self._game_failure_sequence):
|
and failure_sequence == self._game_failure_sequence):
|
||||||
self._execution_failed(error)
|
self._execution_failed(error)
|
||||||
self.log(message, category=job.category, level="error")
|
self.log((job.commission_failure + ";" if job.commission_failure else "") + message, category=job.category, level="error")
|
||||||
finally:
|
finally:
|
||||||
job.payload = {}
|
job.payload = {}
|
||||||
try:
|
try:
|
||||||
@@ -1079,14 +1162,23 @@ class AccountWorker:
|
|||||||
self.schedule.next_fast[kind] = math.inf
|
self.schedule.next_fast[kind] = math.inf
|
||||||
auto = True
|
auto = True
|
||||||
value = self.engine.poll_automation(kind)
|
value = self.engine.poll_automation(kind)
|
||||||
elif kind == "poll":
|
elif kind in ("poll", "reconcile"):
|
||||||
auto = self._set_auto(self._running)
|
recovering = self._pending_battle_recovery().get("resumable") is True
|
||||||
value = self.engine.poll(defer_hatch=True)
|
with self.lock:
|
||||||
self.schedule.poll_finished(self.config)
|
# Recover only the original entry, with general automation
|
||||||
elif kind == "reconcile":
|
# disabled. Stop/config changes still revoke this job.
|
||||||
self._set_auto(False)
|
auto = self._set_auto(self._running and kind == "poll" and not recovering)
|
||||||
# Engine's durable pending barriers reconcile before planning.
|
resume_pending = bool(recovering and self._running and self.strategy_requested
|
||||||
# A check never silently replays an uncertain write.
|
and not self._closing and not self.manager._closing and job.generation == self._generation)
|
||||||
|
if resume_pending:
|
||||||
|
job.consuming = True
|
||||||
|
self.check_intent()
|
||||||
|
if callable(getattr(self.engine, "pending_battle_recovery", None)):
|
||||||
|
value = self.engine.poll(defer_hatch=True, resume_pending=resume_pending)
|
||||||
|
else:
|
||||||
|
# Older Engine doubles use auto to authorize saved results.
|
||||||
|
if resume_pending:
|
||||||
|
auto = self._set_auto(True)
|
||||||
value = self.engine.poll(defer_hatch=True)
|
value = self.engine.poll(defer_hatch=True)
|
||||||
self.schedule.poll_finished(self.config)
|
self.schedule.poll_finished(self.config)
|
||||||
else:
|
else:
|
||||||
@@ -1102,7 +1194,9 @@ class AccountWorker:
|
|||||||
# by the current Engine generation turns that switch off.
|
# by the current Engine generation turns that switch off.
|
||||||
if auto and job.generation == self._generation and not self.engine.auto:
|
if auto and job.generation == self._generation and not self.engine.auto:
|
||||||
if self._pending_execution_reason():
|
if self._pending_execution_reason():
|
||||||
self.stop()
|
# A pending barrier pauses execution, not user intent
|
||||||
|
# or the generation of other queued local edits.
|
||||||
|
self._refresh_execution()
|
||||||
else:
|
else:
|
||||||
self._execution_failed(ValueError(value[2] or "策略暂不可用"))
|
self._execution_failed(ValueError(value[2] or "策略暂不可用"))
|
||||||
elif auto and job.generation == self._generation:
|
elif auto and job.generation == self._generation:
|
||||||
|
|||||||
@@ -415,7 +415,7 @@ async function exportYields(account=current()) {
|
|||||||
async function command(name,account=current()) {
|
async function command(name,account=current()) {
|
||||||
try {
|
try {
|
||||||
if(name==='add-account'||name==='add-demo')return await addAccount(name==='add-demo');
|
if(name==='add-account'||name==='add-demo')return await addAccount(name==='add-demo');
|
||||||
if(name==='about')return dialog('关于牧场助手',el('div',{},el('p',{text:`牧羊人之心牧场助手 Web ${state.meta?.version || '2.0.7'}`}),el('p',{text:`游戏数据版本 ${state.meta?.gameVersion || '1.9.68'}`})),{info:true});
|
if(name==='about')return dialog('关于牧场助手',el('div',{},el('p',{text:`牧羊人之心牧场助手 Web ${state.meta?.version || '2.0.12'}`}),el('p',{text:`游戏数据版本 ${state.meta?.gameVersion || '1.9.68'}`})),{info:true});
|
||||||
if(name==='updates')return await showUpdates();
|
if(name==='updates')return await showUpdates();
|
||||||
if(name==='admin-logout'){hideWorkbench();try{await api.logout();}finally{requireAuth();}return;}
|
if(name==='admin-logout'){hideWorkbench();try{await api.logout();}finally{requireAuth();}return;}
|
||||||
if(!account)throw new Error('请先新增或选择账号。');
|
if(!account)throw new Error('请先新增或选择账号。');
|
||||||
@@ -640,7 +640,7 @@ async function bootstrap() {
|
|||||||
$('#app').hidden=false;
|
$('#app').hidden=false;
|
||||||
const [meta,schema]=await Promise.all([api.meta(),api.schema()]);state.meta=meta;state.schema=schema;
|
const [meta,schema]=await Promise.all([api.meta(),api.schema()]);state.meta=meta;state.schema=schema;
|
||||||
if(state.redirecting)return;
|
if(state.redirecting)return;
|
||||||
$('#app-version').textContent=meta.version || '2.0.7';$('#game-version').textContent=meta.gameVersion || '1.9.68';$('#access-mode').textContent=auth.access_mode==='local'||auth.access_mode==='loopback'?'本机工作台':auth.required?'管理工作台':'本机工作台';
|
$('#app-version').textContent=meta.version || '2.0.12';$('#game-version').textContent=meta.gameVersion || '1.9.68';$('#access-mode').textContent=auth.access_mode==='local'||auth.access_mode==='loopback'?'本机工作台':auth.required?'管理工作台':'本机工作台';
|
||||||
await syncAccounts();if(state.redirecting)return;state.ready=true;setStatus('工作台已连接');
|
await syncAccounts();if(state.redirecting)return;state.ready=true;setStatus('工作台已连接');
|
||||||
}catch(failure){if(failure.status===401||$('#app').hidden){requireAuth();return;}if(state.redirecting)return;setStatus(failure.message);$('#page-host').replaceChildren(el('div',{class:'initial-state'},el('p',{text:failure.message}),el('button',{text:'重新连接',onClick:bootstrap})));}
|
}catch(failure){if(failure.status===401||$('#app').hidden){requireAuth();return;}if(state.redirecting)return;setStatus(failure.message);$('#page-host').replaceChildren(el('div',{class:'initial-state'},el('p',{text:failure.message}),el('button',{text:'重新连接',onClick:bootstrap})));}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,7 +26,7 @@
|
|||||||
</div></details>
|
</div></details>
|
||||||
<details class="menu"><summary accesskey="h">帮助<span class="access-key">(H)</span></summary><div class="menu-popup"><button data-command="updates">检查版本更新…</button><button data-command="debug">调试日志</button><button data-command="about">关于…</button></div></details>
|
<details class="menu"><summary accesskey="h">帮助<span class="access-key">(H)</span></summary><div class="menu-popup"><button data-command="updates">检查版本更新…</button><button data-command="debug">调试日志</button><button data-command="about">关于…</button></div></details>
|
||||||
</nav>
|
</nav>
|
||||||
<span class="window-title">牧羊人之心牧场助手 <span id="app-version">2.0.7</span></span>
|
<span class="window-title">牧羊人之心牧场助手 <span id="app-version">2.0.12</span></span>
|
||||||
<span id="access-mode" class="muted"></span>
|
<span id="access-mode" class="muted"></span>
|
||||||
</header>
|
</header>
|
||||||
<div class="account-bar"><div id="account-tabs" class="account-tabs" role="tablist" aria-label="账号"></div><button id="add-account" class="compact" title="新增账号">+ 新增账号</button></div>
|
<div class="account-bar"><div id="account-tabs" class="account-tabs" role="tablist" aria-label="账号"></div><button id="add-account" class="compact" title="新增账号">+ 新增账号</button></div>
|
||||||
|
|||||||
+15
-32
@@ -9,7 +9,7 @@ export const PAGES = [
|
|||||||
['commissions', '自动委托'], ['exploration', '自动探险'], ['maps', '自动扫荡'], ['statistics', '数据分析'], ['plans', '执行计划'], ['yields', '收益资料'],
|
['commissions', '自动委托'], ['exploration', '自动探险'], ['maps', '自动扫荡'], ['statistics', '数据分析'], ['plans', '执行计划'], ['yields', '收益资料'],
|
||||||
];
|
];
|
||||||
|
|
||||||
export const initialQuery = page => page === 'bag' ? {category: 'eggs'} : page === 'mainline' ? {category: 'mainline', state: 'current'} : page === 'ranch' ? {grouped: false} : page === 'maps' ? {category: 'all', only_unlocked: true} : {};
|
export const initialQuery = page => page === 'bag' ? {category: 'eggs'} : page === 'mainline' ? {category: 'mainline', state: 'current'} : page === 'commissions' ? {tab: 'current'} : page === 'ranch' ? {grouped: false} : page === 'maps' ? {category: 'all', only_unlocked: true} : {};
|
||||||
|
|
||||||
class LoginPage {
|
class LoginPage {
|
||||||
constructor(host, page) {
|
constructor(host, page) {
|
||||||
@@ -116,7 +116,6 @@ export class PageView {
|
|||||||
this.subtabs = el('div', {class: 'subtabs', role: 'tablist', 'aria-label': '子页面', hidden: true});
|
this.subtabs = el('div', {class: 'subtabs', role: 'tablist', 'aria-label': '子页面', hidden: true});
|
||||||
this.filterHost = el('div', {class: 'filter-bar'});
|
this.filterHost = el('div', {class: 'filter-bar'});
|
||||||
this.summary = el('p', {class: 'page-summary'});
|
this.summary = el('p', {class: 'page-summary'});
|
||||||
this.runtimeStatus=el('div',{class:'page-summary',hidden:true});
|
|
||||||
this.formHost = el('div', {class: 'policy-form'});
|
this.formHost = el('div', {class: 'policy-form'});
|
||||||
this.actionsHost = el('div', {class: 'page-toolbar'});
|
this.actionsHost = el('div', {class: 'page-toolbar'});
|
||||||
this.content = el('div', {class: 'page-content'});
|
this.content = el('div', {class: 'page-content'});
|
||||||
@@ -124,7 +123,7 @@ export class PageView {
|
|||||||
dirty: path => account.edits.has(pathKey(path)), onError: this.error, onSelection: () => this.syncActions(),
|
dirty: path => account.edits.has(pathKey(path)), onError: this.error, onSelection: () => this.syncActions(),
|
||||||
onContext: (event, selected, row) => this.openContext(event, selected, row), onDetail: row => this.showDetail(row)};
|
onContext: (event, selected, row) => this.openContext(event, selected, row), onDetail: row => this.showDetail(row)};
|
||||||
this.form = new PolicyForm(this.formHost, this.context);
|
this.form = new PolicyForm(this.formHost, this.context);
|
||||||
this.surface = el('div', {class: 'page-surface'}, this.errorBox, this.subtabs, this.filterHost, this.summary, this.runtimeStatus, this.formHost, this.actionsHost, this.content);
|
this.surface = el('div', {class: 'page-surface'}, this.errorBox, this.subtabs, this.filterHost, this.summary, this.formHost, this.actionsHost, this.content);
|
||||||
this.body = el('div', {class: 'page-body'}, this.surface, this.loading);
|
this.body = el('div', {class: 'page-body'}, this.surface, this.loading);
|
||||||
this.root.append(this.header, this.body);
|
this.root.append(this.header, this.body);
|
||||||
if (key === 'login') this.login = new LoginPage(this.content, this);
|
if (key === 'login') this.login = new LoginPage(this.content, this);
|
||||||
@@ -161,7 +160,7 @@ export class PageView {
|
|||||||
filters.forEach(field => {
|
filters.forEach(field => {
|
||||||
if (this.key === 'bag' && field.key === 'category') return;
|
if (this.key === 'bag' && field.key === 'category') return;
|
||||||
included.add(field.key);
|
included.add(field.key);
|
||||||
if (!Object.hasOwn(this.query, field.key)) this.query[field.key] = field.value;
|
if (!Object.hasOwn(this.query, field.key) || field.type === 'date' && !this.query[field.key]) this.query[field.key] = field.value;
|
||||||
let item = this.filters.get(field.key);
|
let item = this.filters.get(field.key);
|
||||||
const signature = JSON.stringify({...field, value: undefined});
|
const signature = JSON.stringify({...field, value: undefined});
|
||||||
if (!item || item.signature !== signature && !item.root.contains(document.activeElement)) {
|
if (!item || item.signature !== signature && !item.root.contains(document.activeElement)) {
|
||||||
@@ -170,6 +169,7 @@ export class PageView {
|
|||||||
set: (_, value) => this.setQuery(field.key, value), onError: this.error,
|
set: (_, value) => this.setQuery(field.key, value), onError: this.error,
|
||||||
});
|
});
|
||||||
if (field.key === 'search') { entry.root.type = 'search'; entry.root.placeholder = this.key === 'maps' ? '关卡、名称或掉落物品' : '按名称或编号筛选'; }
|
if (field.key === 'search') { entry.root.type = 'search'; entry.root.placeholder = this.key === 'maps' ? '关卡、名称或掉落物品' : '按名称或编号筛选'; }
|
||||||
|
if (field.type === 'date') entry.root.type = 'date';
|
||||||
const root = el('label', {}, el('span', {text: field.label}), entry.root);
|
const root = el('label', {}, el('span', {text: field.label}), entry.root);
|
||||||
item?.root.remove();
|
item?.root.remove();
|
||||||
item = {root, entry, signature};
|
item = {root, entry, signature};
|
||||||
@@ -187,11 +187,17 @@ export class PageView {
|
|||||||
if (this.key === 'bag') tabs = [{key:'eggs',title:'魔物蛋'}, {key:'usable',title:'可使用'}, {key:'consumables',title:'消耗品'}, {key:'materials',title:'材料'}, {key:'other',title:'其他'}, {key:'equipment',title:'装备'}];
|
if (this.key === 'bag') tabs = [{key:'eggs',title:'魔物蛋'}, {key:'usable',title:'可使用'}, {key:'consumables',title:'消耗品'}, {key:'materials',title:'材料'}, {key:'other',title:'其他'}, {key:'equipment',title:'装备'}];
|
||||||
if (!tabs.length && this.key === 'hatching') tabs = ['孵蛋策略','牧场策略','喂养策略'].map(title => ({key:title,title}));
|
if (!tabs.length && this.key === 'hatching') tabs = ['孵蛋策略','牧场策略','喂养策略'].map(title => ({key:title,title}));
|
||||||
if (!tabs.length && this.key === 'mainline') tabs = [{key:'tasks',title:'任务状态'}, {key:'policy',title:'推进策略'}];
|
if (!tabs.length && this.key === 'mainline') tabs = [{key:'tasks',title:'任务状态'}, {key:'policy',title:'推进策略'}];
|
||||||
|
if (this.key === 'commissions') this.activeSubtab = this.query.tab || 'current';
|
||||||
const signature = JSON.stringify(tabs);
|
const signature = JSON.stringify(tabs);
|
||||||
if (this.tabSignature !== signature) {
|
if (this.tabSignature !== signature) {
|
||||||
if (!this.activeSubtab || !tabs.some(tab => tab.key === this.activeSubtab)) this.activeSubtab = this.key === 'bag' ? this.query.category || tabs[0]?.key : tabs[0]?.key;
|
if (!this.activeSubtab || !tabs.some(tab => tab.key === this.activeSubtab)) this.activeSubtab = this.key === 'bag' ? this.query.category || tabs[0]?.key : tabs[0]?.key;
|
||||||
this.subtabs.replaceChildren(...tabs.map(tab => el('button', {type: 'button', class: 'subtab', role: 'tab', 'data-key': tab.key, text: tab.title || tab.label,
|
this.subtabs.replaceChildren(...tabs.map(tab => el('button', {type: 'button', class: 'subtab', role: 'tab', 'data-key': tab.key, text: tab.title || tab.label,
|
||||||
onClick: () => { this.activeSubtab = tab.key; if (this.key === 'bag') this.setQuery('category', tab.key); this.render(this.data || data); }})));
|
onClick: () => {
|
||||||
|
this.activeSubtab = tab.key;
|
||||||
|
if (this.key === 'commissions') { this.setQuery('tab', tab.key); this.updateSubtabs(data); return; }
|
||||||
|
if (this.key === 'bag') this.setQuery('category', tab.key);
|
||||||
|
this.render(this.data || data);
|
||||||
|
}})));
|
||||||
this.tabSignature = signature;
|
this.tabSignature = signature;
|
||||||
}
|
}
|
||||||
$$('.subtab', this.subtabs).forEach(button => { const selected = button.dataset.key === this.activeSubtab; button.setAttribute('aria-selected', selected); button.tabIndex = selected ? 0 : -1; });
|
$$('.subtab', this.subtabs).forEach(button => { const selected = button.dataset.key === this.activeSubtab; button.setAttribute('aria-selected', selected); button.tabIndex = selected ? 0 : -1; });
|
||||||
@@ -220,7 +226,7 @@ export class PageView {
|
|||||||
const currencies = action.currencies ? optionsList(action.currencies) : [null];
|
const currencies = action.currencies ? optionsList(action.currencies) : [null];
|
||||||
currencies.forEach(currency => {
|
currencies.forEach(currency => {
|
||||||
const button = el('button', {type: 'button', text: `${action.label}${currency ? `(${currency.label})` : ''}`, 'data-operation': action.operation,
|
const button = el('button', {type: 'button', text: `${action.label}${currency ? `(${currency.label})` : ''}`, 'data-operation': action.operation,
|
||||||
'data-selection': action.selection, onClick: () => this.options.action(this, action, currency?.value).catch(this.error)});
|
'data-selection': action.selection, onClick: () => action.operation === 'reload_view' ? this.options.load(this, true).catch(this.error) : this.options.action(this, action, currency?.value).catch(this.error)});
|
||||||
this.actionsHost.append(button);
|
this.actionsHost.append(button);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -241,7 +247,7 @@ export class PageView {
|
|||||||
this.updateFilters(data.filters || []);
|
this.updateFilters(data.filters || []);
|
||||||
this.summary.textContent = typeof data.summary === 'string' ? data.summary : textValue(data.summary || '');
|
this.summary.textContent = typeof data.summary === 'string' ? data.summary : textValue(data.summary || '');
|
||||||
this.summary.hidden = !data.summary;
|
this.summary.hidden = !data.summary;
|
||||||
this.updateRuntimeStatus(data.details || {}, data.battle_mode);
|
if (data.details?.statistics_error) this.showError(textValue(data.details.statistics_error));
|
||||||
let fields = data.form || this.options.schema(this.key);
|
let fields = data.form || this.options.schema(this.key);
|
||||||
if (this.key === 'login') fields = fields.filter(field => !(field.path?.[0] === 'auto_relogin' && field.path[1] === 'enabled'));
|
if (this.key === 'login') fields = fields.filter(field => !(field.path?.[0] === 'auto_relogin' && field.path[1] === 'enabled'));
|
||||||
fields=fields.map(field=>field.path?.[0]==='policy'&&field.path[1]==='buy_ten'?{...field,disabled:!this.account.config?.policy?.allow_single_draw}:field);
|
fields=fields.map(field=>field.path?.[0]==='policy'&&field.path[1]==='buy_ten'?{...field,disabled:!this.account.config?.policy?.allow_single_draw}:field);
|
||||||
@@ -269,39 +275,16 @@ export class PageView {
|
|||||||
} else this.table.update(data.columns || [], data.rows || []);
|
} else this.table.update(data.columns || [], data.rows || []);
|
||||||
}
|
}
|
||||||
|
|
||||||
updateRuntimeStatus(details, battleMode) {
|
|
||||||
const lines=[];
|
|
||||||
if(this.key==='hatching'){
|
|
||||||
if(this.activeSubtab==='喂养策略' && Array.isArray(details.feed_status))lines.push(['feed_status','当前喂养状态:'+textValue(details.feed_status[1])]);
|
|
||||||
if(this.activeSubtab==='孵蛋策略' && details.last_draw!==undefined)lines.push(['last_draw','最近抽蛋:'+textValue(details.last_draw)]);
|
|
||||||
}
|
|
||||||
if(this.key==='gifts' && Object.hasOwn(details,'next_ready_at')){
|
|
||||||
const ready=details.next_ready_at;
|
|
||||||
lines.push(['next_ready_at',ready===null?'下次赠礼:当前没有符合条件的目标或物品,等待状态更新':'下次可赠礼:'+chinaTime(ready,{date:true})+'(北京时间)']);
|
|
||||||
}
|
|
||||||
// Planner notes are current execution/wait reasons, unlike DTO help text.
|
|
||||||
const notes = Array.isArray(details.notes) ? [...new Set(details.notes.filter(note => typeof note === 'string' && note.trim()))] : [];
|
|
||||||
if(notes.length)lines.push(['planner_notes',notes.join('\n')]);
|
|
||||||
if(details.statistics_error)lines.push(['statistics_error',textValue(details.statistics_error)]);
|
|
||||||
if(battleMode?.label)lines.push(['battle_mode',battleMode.label]);
|
|
||||||
const signature=JSON.stringify(lines);
|
|
||||||
if(signature!==this.runtimeSignature){
|
|
||||||
this.runtimeStatus.replaceChildren(...lines.map(([key,text])=>el('p',{'data-view-status':key,text})));
|
|
||||||
this.runtimeSignature=signature;
|
|
||||||
}
|
|
||||||
this.runtimeStatus.hidden=!lines.length;
|
|
||||||
}
|
|
||||||
|
|
||||||
showDetail(row) {
|
showDetail(row) {
|
||||||
const data = this.data.details?.[row.id] || row.details;
|
const data = this.data.details?.[row.id] || row.details;
|
||||||
if (!data) return;
|
if (!data) return;
|
||||||
const labels = {name:'名称',species:'种类',id:'魔物ID',level:'等级 / 当前上限',quality:'资质 攻/防/血/敏',reference_stats:'参考攻击 / 防御 / 生命 / 敏捷',growth:'成长数值',likes:'喜欢的物品',feel:'好感 / 上限',feed_exp:'喂养经验',scope:'管理范围'};
|
const labels = {name:'名称',species:'种类',id:'魔物ID',level:'等级 / 当前上限',quality:'资质 攻/防/血/敏',reference_stats:'参考攻击 / 防御 / 生命 / 敏捷',growth:'成长数值',likes:'喜欢的物品',feel:'好感 / 上限',feed_exp:'喂养经验',scope:'管理范围'};
|
||||||
const title=this.key==='ranch'?'魔物详情':this.key==='mainline'?'任务详情':this.key==='battles'?'战斗详情':'详情';
|
const title=this.key==='ranch'?'魔物详情':this.key==='mainline'?'任务详情':this.key==='battles'?'战斗详情':this.key==='commissions'?'委托详情':'详情';
|
||||||
dialog(title, el('div', {class:'detail-sections'}, detailsList(data, labels)), {info:true});
|
dialog(title, el('div', {class:'detail-sections'}, detailsList(data, labels)), {info:true});
|
||||||
}
|
}
|
||||||
|
|
||||||
openContext(event, selected, row) {
|
openContext(event, selected, row) {
|
||||||
const items = [{label:'刷新本页',run:()=>this.perform('refresh',{page:this.key})}];
|
const items = [{label:'刷新本页',run:()=>this.key === 'commissions' && this.query.tab === 'history' ? this.options.load(this, true) : this.perform('refresh',{page:this.key})}];
|
||||||
if (this.key === 'ranch') {
|
if (this.key === 'ranch') {
|
||||||
items.push({label:'查看魔物详情',run:()=>this.showDetail(row)});
|
items.push({label:'查看魔物详情',run:()=>this.showDetail(row)});
|
||||||
(this.data.actions || []).filter(action => ['lock','unlock','sell','feed'].includes(action.operation)).forEach(action => items.push({label:action.label,disabled:!selected.length,run:()=>this.options.action(this,action)}));
|
(this.data.actions || []).filter(action => ['lock','unlock','sell','feed'].includes(action.operation)).forEach(action => items.push({label:action.label,disabled:!selected.length,run:()=>this.options.action(this,action)}));
|
||||||
|
|||||||
@@ -0,0 +1,218 @@
|
|||||||
|
"""Commission subtabs, local reads and the original log region over loopback only."""
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import time
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import Mock, patch
|
||||||
|
from urllib.parse import parse_qs, urlsplit
|
||||||
|
|
||||||
|
from ranch_assistant.engine import Engine, demo_snapshot
|
||||||
|
from ranch_assistant.model import Catalog
|
||||||
|
from ranch_web.tests.test_commission_history import history_fixture
|
||||||
|
from ranch_web.views import build_view
|
||||||
|
from . import test_workbench_browser as fixtures
|
||||||
|
|
||||||
|
if fixtures.AVAILABLE:
|
||||||
|
from playwright.sync_api import expect
|
||||||
|
|
||||||
|
|
||||||
|
@unittest.skipUnless(fixtures.AVAILABLE, "Python Playwright and a system Chromium browser are required")
|
||||||
|
class CommissionHistoryBrowserTests(unittest.TestCase):
|
||||||
|
setUpClass = classmethod(fixtures.WorkbenchBrowserTests.setUpClass.__func__)
|
||||||
|
tearDownClass = classmethod(fixtures.WorkbenchBrowserTests.tearDownClass.__func__)
|
||||||
|
await_job = fixtures.WorkbenchBrowserTests.await_job
|
||||||
|
open = fixtures.WorkbenchBrowserTests.open
|
||||||
|
go = fixtures.WorkbenchBrowserTests.go
|
||||||
|
fulfill = staticmethod(fixtures.WorkbenchBrowserTests.fulfill)
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
self.enterContext(patch("requests.sessions.Session.request", side_effect=AssertionError("Live HTTP forbidden")))
|
||||||
|
fixtures.WorkbenchBrowserTests.setUp(self)
|
||||||
|
self.context.set_default_timeout(6000)
|
||||||
|
self.today = datetime.now(timezone(timedelta(hours=8))).date()
|
||||||
|
self.external, self.writes, self.reads, self.pending = [], [], [], []
|
||||||
|
self.hold = self.fail_reads = False
|
||||||
|
self.engines = {}
|
||||||
|
for identifier, label in ((self.first, "账号一"), (self.second, "账号二")):
|
||||||
|
engine = Engine(Catalog(), budget_path=Path(self.temp.name) / identifier / "fixture-budget.json")
|
||||||
|
engine.snapshot = demo_snapshot(engine.catalog)
|
||||||
|
engine.catalog.data["task_info"] = {"test20": {"name": label + "高额候选", "reward": {"money": 123, "ke": 20}},
|
||||||
|
"test15": {"name": label + "回退候选", "reward": {"money": 456, "ke": 15}}}
|
||||||
|
engine.tasks.rows = Mock(return_value=[("test20", label + "高额候选", "城市 4 可接", "", {"city": 4}),
|
||||||
|
("test15", label + "回退候选", "城市 1 可接", "", {"city": 1})])
|
||||||
|
engine.tasks.current = Mock(return_value=[])
|
||||||
|
engine.commission_offer_diagnostics = Mock(return_value=[])
|
||||||
|
engine.progression_rows = Mock(return_value=[{"category": "commission", "task_type_id": "test20", "block_reason": "城市尚未解锁"},
|
||||||
|
{"category": "commission", "task_type_id": "test15", "selection_reason": "20氪金候选未解锁,回退15氪金"}])
|
||||||
|
engine.commission_history = lambda day=None, label=label: self.history(day, label)
|
||||||
|
engine.client = Mock()
|
||||||
|
self.engines[identifier] = engine
|
||||||
|
|
||||||
|
def local_only(route):
|
||||||
|
if route.request.url.startswith(self.base + "/"):
|
||||||
|
route.continue_()
|
||||||
|
else:
|
||||||
|
self.external.append(route.request.url)
|
||||||
|
route.abort()
|
||||||
|
|
||||||
|
self.context.route("**/*", local_only)
|
||||||
|
self.page.on("request", lambda request: self.writes.append(request) if request.method in ("POST", "PUT", "PATCH", "DELETE") else None)
|
||||||
|
|
||||||
|
def view(route):
|
||||||
|
parsed = urlsplit(route.request.url)
|
||||||
|
identifier = parsed.path.split("/")[-3]
|
||||||
|
params = parse_qs(parsed.query)
|
||||||
|
query = json.loads(params["query"][0]) if "query" in params else {key: value[0] for key, value in params.items()}
|
||||||
|
self.reads.append((identifier, query))
|
||||||
|
dto = build_view(self.engines[identifier], "commissions", self.manager.get_config(identifier)["config"], query)
|
||||||
|
if self.hold:
|
||||||
|
self.pending.append((route, dto))
|
||||||
|
elif self.fail_reads:
|
||||||
|
route.fulfill(status=503, content_type="application/json", body='{"detail":"本地记录读取失败"}')
|
||||||
|
else:
|
||||||
|
self.fulfill(route, {"loading": False, "data": dto})
|
||||||
|
|
||||||
|
self.page.route("**/api/accounts/*/views/commissions?*", view)
|
||||||
|
|
||||||
|
def history(self, day, label):
|
||||||
|
fixture = history_fixture(day)
|
||||||
|
fixture["rows"][0]["name"] = label + day + "提交魔物与道具"
|
||||||
|
return fixture
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
try:
|
||||||
|
self.assertEqual(self.external, [])
|
||||||
|
self.assertEqual(self.errors, [])
|
||||||
|
for engine in self.engines.values():
|
||||||
|
engine.client.call.assert_not_called()
|
||||||
|
finally:
|
||||||
|
self.context.unroute_all(behavior="ignoreErrors")
|
||||||
|
self.context.close()
|
||||||
|
|
||||||
|
def records(self):
|
||||||
|
panel = self.go("commissions")
|
||||||
|
panel.get_by_role("tab", name="每日记录", exact=True).click()
|
||||||
|
expect(panel.locator('input[type="date"]')).to_have_value(self.today.isoformat())
|
||||||
|
expect(panel.locator("tbody tr")).to_have_count(2)
|
||||||
|
expect(panel).to_have_attribute("aria-busy", "false")
|
||||||
|
return panel
|
||||||
|
|
||||||
|
def test_history_refresh_is_get_only_and_original_single_log_stays_collapsed(self):
|
||||||
|
self.open()
|
||||||
|
expect(self.page.locator("#page-tabs [role=tab]")).to_have_count(15)
|
||||||
|
panel = self.records()
|
||||||
|
expect(panel.get_by_role("tab", name="每日记录")).to_have_attribute("aria-selected", "true")
|
||||||
|
expect(panel.locator(".policy-form")).to_be_hidden()
|
||||||
|
expect(panel.locator(".page-surface > p.page-summary")).to_contain_text("已记录接取 2 · 已记录完成 1")
|
||||||
|
expect(panel.locator(".page-surface > p.page-summary")).to_contain_text("当日领奖确认氪金 15 · 当日接取标注氪金 35")
|
||||||
|
expect(panel.locator('td[data-column="confirmed_ke"]')).to_have_text(["15", "未确认"])
|
||||||
|
expect(self.page.locator("#log-panel")).to_have_count(1)
|
||||||
|
expect(self.page.locator("#log-panel")).to_be_hidden()
|
||||||
|
before = len(self.writes)
|
||||||
|
with self.page.expect_request(lambda request: "/views/commissions?" in request.url) as seen:
|
||||||
|
panel.get_by_role("button", name="刷新记录", exact=True).click()
|
||||||
|
self.assertEqual(seen.value.method, "GET")
|
||||||
|
expect(panel).to_have_attribute("aria-busy", "false")
|
||||||
|
self.assertEqual(len(self.writes), before)
|
||||||
|
expect(self.page.locator("#log-panel")).to_be_hidden()
|
||||||
|
self.assertEqual(self.page.locator('[role="log"]').count(), 1)
|
||||||
|
|
||||||
|
panel.locator("tbody tr").first.click(button="right")
|
||||||
|
with self.page.expect_request(lambda request: "/views/commissions?" in request.url) as seen:
|
||||||
|
self.page.get_by_role("menuitem", name="刷新本页", exact=True).click()
|
||||||
|
self.assertEqual(seen.value.method, "GET")
|
||||||
|
expect(panel).to_have_attribute("aria-busy", "false")
|
||||||
|
self.assertEqual(len(self.writes), before)
|
||||||
|
artifact = Path(__file__).resolve().parents[3] / "test-artifacts" / "commission-history"
|
||||||
|
artifact.mkdir(parents=True, exist_ok=True)
|
||||||
|
self.page.screenshot(path=str(artifact / "desktop-daily-records.png"))
|
||||||
|
|
||||||
|
panel.locator("tbody tr").first.dblclick()
|
||||||
|
detail = self.page.get_by_role("dialog")
|
||||||
|
expect(detail).to_contain_text("委托详情")
|
||||||
|
for value in ("铁矿石 ×2", "1级史莱姆 ×1", "城镇守卫", "战斗胜利", "回退15氪金"):
|
||||||
|
expect(detail).to_contain_text(value)
|
||||||
|
expect(self.page.locator("#log-panel")).to_be_hidden()
|
||||||
|
|
||||||
|
def test_current_policy_autosave_and_original_log_filters_commissions_in_both_subtabs(self):
|
||||||
|
worker = self.manager._worker(self.first)
|
||||||
|
worker.log("接取委托:仅委托可见(预计20氪金);已确认", category="commissions")
|
||||||
|
worker.log("其他分类不可见", category="login")
|
||||||
|
self.open()
|
||||||
|
panel = self.go("commissions")
|
||||||
|
with self.page.expect_request(lambda request: request.method == "PUT" and "/config" in request.url):
|
||||||
|
panel.get_by_role("checkbox", name="允许提交道具(遵守保留数量)", exact=True).check()
|
||||||
|
expect(self.page.locator("#save-status")).to_have_text("策略已自动保存")
|
||||||
|
self.assertTrue(self.manager.get_config(self.first)["config"]["quest_policy"]["allow_items"])
|
||||||
|
expect(self.page.locator("#log-panel")).to_be_hidden()
|
||||||
|
self.page.locator("#log-toggle").click()
|
||||||
|
expect(self.page.locator("#log-heading")).to_have_text("自动委托日志")
|
||||||
|
expect(self.page.locator("#log-lines")).to_contain_text("仅委托可见")
|
||||||
|
expect(self.page.locator("#log-lines")).not_to_contain_text("其他分类不可见")
|
||||||
|
panel.get_by_role("tab", name="每日记录").click()
|
||||||
|
expect(panel.get_by_label("记录日期(北京时间)")).to_be_visible()
|
||||||
|
expect(self.page.locator("#log-panel")).to_be_visible()
|
||||||
|
expect(self.page.locator("#log-panel")).to_have_count(1)
|
||||||
|
expect(self.page.locator("#log-heading")).to_have_text("自动委托日志")
|
||||||
|
expect(self.page.locator("#log-lines")).not_to_contain_text("其他分类不可见")
|
||||||
|
|
||||||
|
def test_date_account_isolation_and_keyboard_subtabs(self):
|
||||||
|
self.open()
|
||||||
|
panel = self.records()
|
||||||
|
yesterday = (self.today - timedelta(days=1)).isoformat()
|
||||||
|
panel.get_by_label("记录日期(北京时间)").fill(yesterday)
|
||||||
|
expect(panel.locator("tbody tr").first).to_contain_text("账号一" + yesterday)
|
||||||
|
self.page.locator(f'.account-tab[data-account="{self.second}"]').click()
|
||||||
|
panel = self.records()
|
||||||
|
expect(panel.get_by_label("记录日期(北京时间)")).to_have_value(self.today.isoformat())
|
||||||
|
expect(panel.locator("tbody tr").first).to_contain_text("账号二" + self.today.isoformat())
|
||||||
|
self.page.locator(f'.account-tab[data-account="{self.first}"]').click()
|
||||||
|
panel = self.page.locator('.page-panel[data-page="commissions"]:not([hidden])')
|
||||||
|
expect(panel.get_by_label("记录日期(北京时间)")).to_have_value(yesterday)
|
||||||
|
expect(panel.locator("tbody tr").first).to_contain_text("账号一" + yesterday)
|
||||||
|
current = panel.get_by_role("tab", name="每日记录")
|
||||||
|
current.focus()
|
||||||
|
current.press("Home")
|
||||||
|
expect(panel.get_by_role("tab", name="当前委托")).to_have_attribute("aria-selected", "true")
|
||||||
|
expect(panel.locator('th[data-column="reward_ke"]')).to_have_text("标注氪金")
|
||||||
|
expect(panel.locator("tbody tr").first).to_contain_text("城市尚未解锁")
|
||||||
|
expect(panel.locator('td[data-column="status"]')).to_have_text(["暂不接取", "候选 / 条件待核对"])
|
||||||
|
expect(self.page.locator("#log-panel")).to_be_hidden()
|
||||||
|
|
||||||
|
def test_loading_error_and_mobile_history_keep_original_layout(self):
|
||||||
|
self.open()
|
||||||
|
panel = self.records()
|
||||||
|
self.hold = True
|
||||||
|
panel.get_by_label("记录日期(北京时间)").fill((self.today - timedelta(days=2)).isoformat())
|
||||||
|
expect(panel).to_have_attribute("aria-busy", "true")
|
||||||
|
expect(panel.locator(".page-loading")).to_be_visible()
|
||||||
|
expect(self.page.locator("#log-panel")).to_be_hidden()
|
||||||
|
deadline = time.monotonic() + 5
|
||||||
|
while not self.pending and time.monotonic() < deadline:
|
||||||
|
self.page.wait_for_timeout(30)
|
||||||
|
self.assertTrue(self.pending)
|
||||||
|
self.hold = False
|
||||||
|
route, dto = self.pending.pop(0)
|
||||||
|
self.fulfill(route, {"loading": False, "data": dto})
|
||||||
|
expect(panel).to_have_attribute("aria-busy", "false")
|
||||||
|
expect(panel.locator(".page-loading")).to_be_hidden()
|
||||||
|
self.fail_reads = True
|
||||||
|
panel.get_by_role("button", name="刷新记录").click()
|
||||||
|
expect(panel.locator(".page-error")).to_be_visible()
|
||||||
|
expect(panel).to_have_attribute("aria-busy", "false")
|
||||||
|
expect(self.page.locator("#log-panel")).to_be_hidden()
|
||||||
|
self.fail_reads = False
|
||||||
|
self.errors[:] = [error for error in self.errors if "503 (Service Unavailable)" not in error]
|
||||||
|
panel.get_by_role("button", name="重新读取").click()
|
||||||
|
expect(panel.locator(".page-error")).to_be_hidden()
|
||||||
|
self.page.set_viewport_size({"width": 390, "height": 844})
|
||||||
|
expect(panel.get_by_label("记录日期(北京时间)")).to_be_visible()
|
||||||
|
self.assertLessEqual(self.page.evaluate("document.documentElement.scrollWidth"), 391)
|
||||||
|
artifact = Path(__file__).resolve().parents[3] / "test-artifacts" / "commission-history"
|
||||||
|
artifact.mkdir(parents=True, exist_ok=True)
|
||||||
|
self.page.screenshot(path=str(artifact / "mobile-daily-records.png"))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -51,8 +51,22 @@ class PageLoadingBrowserTests(unittest.TestCase):
|
|||||||
"details": {"help": "STATIC_HELP_SENTINEL", "note": "STATIC_NOTE_SENTINEL",
|
"details": {"help": "STATIC_HELP_SENTINEL", "note": "STATIC_NOTE_SENTINEL",
|
||||||
"notes": ["金币不足,等待补货"]}}}
|
"notes": ["金币不足,等待补货"]}}}
|
||||||
self.hold, self.fail = False, False
|
self.hold, self.fail = False, False
|
||||||
|
self.hold_after_real_retry_click = False
|
||||||
|
self.page.add_init_script("""(() => {
|
||||||
|
window.__loadingRetryClicked = false;
|
||||||
|
document.addEventListener('click', event => {
|
||||||
|
if (event.target instanceof Element && event.target.closest('.page-panel[data-page="bag"] .page-error button')) {
|
||||||
|
window.__loadingRetryClicked = true;
|
||||||
|
}
|
||||||
|
}, true);
|
||||||
|
})();""")
|
||||||
|
|
||||||
def view(route):
|
def view(route):
|
||||||
|
if self.hold_after_real_retry_click:
|
||||||
|
if not self.page.evaluate("window.__loadingRetryClicked"):
|
||||||
|
route.fulfill(status=503, content_type="application/json", body='{"detail":"读取失败"}')
|
||||||
|
return
|
||||||
|
self.hold_after_real_retry_click = False
|
||||||
if self.hold:
|
if self.hold:
|
||||||
self.pending.append(route)
|
self.pending.append(route)
|
||||||
elif self.fail:
|
elif self.fail:
|
||||||
@@ -117,11 +131,12 @@ class PageLoadingBrowserTests(unittest.TestCase):
|
|||||||
expect(panel.locator("tbody tr")).to_have_count(32)
|
expect(panel.locator("tbody tr")).to_have_count(32)
|
||||||
self.page.screenshot(path=str(artifacts / "settled-dense.png"))
|
self.page.screenshot(path=str(artifacts / "settled-dense.png"))
|
||||||
|
|
||||||
def test_passive_refresh_preserves_editing_table_and_business_reasons(self):
|
def test_passive_refresh_preserves_editing_table_without_inline_notes(self):
|
||||||
self.open()
|
self.open()
|
||||||
panel = self.bag()
|
panel = self.bag()
|
||||||
expect(panel.locator("tbody tr")).to_have_count(32)
|
expect(panel.locator("tbody tr")).to_have_count(32)
|
||||||
expect(panel.locator('[data-view-status="planner_notes"]')).to_have_text("金币不足,等待补货")
|
expect(panel.locator('[data-view-status="planner_notes"]')).to_have_count(0)
|
||||||
|
expect(panel).not_to_contain_text("金币不足,等待补货")
|
||||||
self.assertNotIn("STATIC_HELP_SENTINEL", panel.inner_text())
|
self.assertNotIn("STATIC_HELP_SENTINEL", panel.inner_text())
|
||||||
self.assertNotIn("STATIC_NOTE_SENTINEL", panel.inner_text())
|
self.assertNotIn("STATIC_NOTE_SENTINEL", panel.inner_text())
|
||||||
self.assertEqual(panel.locator(".info-note, .field-help").count(), 0)
|
self.assertEqual(panel.locator(".info-note, .field-help").count(), 0)
|
||||||
@@ -142,6 +157,7 @@ class PageLoadingBrowserTests(unittest.TestCase):
|
|||||||
expect(field).to_be_focused()
|
expect(field).to_be_focused()
|
||||||
expect(field).to_have_value("")
|
expect(field).to_have_value("")
|
||||||
self.assertTrue(field.evaluate("node => node === window.loadingField && window.loadingTable.isConnected && node.closest('.page-panel').querySelector('table') === window.loadingTable"))
|
self.assertTrue(field.evaluate("node => node === window.loadingField && window.loadingTable.isConnected && node.closest('.page-panel').querySelector('table') === window.loadingTable"))
|
||||||
|
expect(panel).not_to_contain_text("金币不足,等待补货")
|
||||||
expect(self.page.locator("#log-panel")).to_be_hidden()
|
expect(self.page.locator("#log-panel")).to_be_hidden()
|
||||||
self.assertEqual(self.page.locator("#log-panel").count(), 1)
|
self.assertEqual(self.page.locator("#log-panel").count(), 1)
|
||||||
|
|
||||||
@@ -156,8 +172,16 @@ class PageLoadingBrowserTests(unittest.TestCase):
|
|||||||
expect(panel.locator(".page-error")).to_be_visible()
|
expect(panel.locator(".page-error")).to_be_visible()
|
||||||
expect(panel).to_have_attribute("aria-busy", "false")
|
expect(panel).to_have_attribute("aria-busy", "false")
|
||||||
expect(panel.locator(".page-loading")).to_be_hidden()
|
expect(panel.locator(".page-loading")).to_be_hidden()
|
||||||
|
# Passive polling must keep returning the error until the native click.
|
||||||
|
# Holding a passive request here would hide the button before it can click.
|
||||||
|
self.hold_after_real_retry_click = True
|
||||||
self.hold, self.fail = True, False
|
self.hold, self.fail = True, False
|
||||||
|
with self.page.expect_response(lambda response: "/views/bag?" in response.url and response.status == 503):
|
||||||
|
pass # Exercise a real passive refresh during this transition.
|
||||||
|
expect(panel.locator(".page-error")).to_be_visible()
|
||||||
|
self.assertEqual(self.pending, [], "Passive errors must not park a request before the retry click")
|
||||||
panel.get_by_role("button", name="重新读取").click()
|
panel.get_by_role("button", name="重新读取").click()
|
||||||
|
self.assertTrue(self.page.evaluate("window.__loadingRetryClicked"))
|
||||||
route = self.wait_request()
|
route = self.wait_request()
|
||||||
self.assert_centered(panel)
|
self.assert_centered(panel)
|
||||||
self.summary.update(connection_state="offline", connected=False, connection_message="连接已中断")
|
self.summary.update(connection_state="offline", connected=False, connection_message="连接已中断")
|
||||||
|
|||||||
@@ -148,7 +148,7 @@ class WorkbenchBrowserTests(unittest.TestCase):
|
|||||||
expect(panel.locator('.form-section legend')).to_have_text('孵蛋策略')
|
expect(panel.locator('.form-section legend')).to_have_text('孵蛋策略')
|
||||||
panel.locator('.subtab[data-key="喂养策略"]').click()
|
panel.locator('.subtab[data-key="喂养策略"]').click()
|
||||||
expect(panel.locator('.form-section legend')).to_have_text('喂养策略')
|
expect(panel.locator('.form-section legend')).to_have_text('喂养策略')
|
||||||
expect(panel.locator('[data-view-status="feed_status"]')).to_be_visible()
|
expect(panel.locator('[data-view-status="feed_status"]')).to_have_count(0)
|
||||||
if key=='mainline':
|
if key=='mainline':
|
||||||
expect(panel.locator('.subtab[data-key="policy"]')).to_be_visible()
|
expect(panel.locator('.subtab[data-key="policy"]')).to_be_visible()
|
||||||
panel.locator('.subtab[data-key="policy"]').click()
|
panel.locator('.subtab[data-key="policy"]').click()
|
||||||
@@ -444,17 +444,20 @@ class WorkbenchBrowserTests(unittest.TestCase):
|
|||||||
expect(panel.locator('td[data-column="per_stamina"]')).to_have_attribute('title','0.001')
|
expect(panel.locator('td[data-column="per_stamina"]')).to_have_attribute('title','0.001')
|
||||||
self.assertEqual(self.errors,[])
|
self.assertEqual(self.errors,[])
|
||||||
|
|
||||||
def test_runtime_statuses_and_preset_without_confirmation(self):
|
def test_settings_omit_runtime_statuses_and_preset_without_confirmation(self):
|
||||||
def gifts_view(route):
|
def gifts_view(route):
|
||||||
self.fulfill(route,{'data':{'page':'gifts','title':'自动赠礼','summary':'离线状态','form':[],'filters':[],'columns':[],'rows':[],'actions':[],
|
self.fulfill(route,{'data':{'page':'gifts','title':'自动赠礼','summary':'离线状态','form':[],'filters':[],'columns':[],'rows':[],'actions':[],
|
||||||
'details':{'next_ready_at':1794294489}},'loading':False})
|
'details':{'next_ready_at':1794294489}},'loading':False})
|
||||||
self.page.route(f'**/api/accounts/{self.first}/views/gifts?*',gifts_view)
|
self.page.route(f'**/api/accounts/{self.first}/views/gifts?*',gifts_view)
|
||||||
self.open()
|
self.open()
|
||||||
panel=self.go('hatching')
|
panel=self.go('hatching')
|
||||||
expect(panel.locator('[data-view-status="last_draw"]')).to_contain_text('最近抽蛋:')
|
expect(panel.locator('.form-section legend')).to_have_text('孵蛋策略')
|
||||||
|
expect(panel.locator('[data-view-status="last_draw"]')).to_have_count(0)
|
||||||
|
expect(panel).not_to_contain_text('最近抽蛋:')
|
||||||
panel.locator('.subtab[data-key="喂养策略"]').click()
|
panel.locator('.subtab[data-key="喂养策略"]').click()
|
||||||
data=self.manager.view(self.first,'hatching',{})['data']
|
expect(panel.locator('.form-section legend')).to_have_text('喂养策略')
|
||||||
expect(panel.locator('[data-view-status="feed_status"]')).to_contain_text(data['details']['feed_status'][1])
|
expect(panel.locator('[data-view-status="feed_status"]')).to_have_count(0)
|
||||||
|
expect(panel).not_to_contain_text('当前喂养状态:')
|
||||||
panel.locator('button[data-operation="apply_preset"]').click()
|
panel.locator('button[data-operation="apply_preset"]').click()
|
||||||
expect(self.page.locator('#action-dialog')).not_to_be_visible()
|
expect(self.page.locator('#action-dialog')).not_to_be_visible()
|
||||||
self.page.wait_for_timeout(1400)
|
self.page.wait_for_timeout(1400)
|
||||||
@@ -462,7 +465,70 @@ class WorkbenchBrowserTests(unittest.TestCase):
|
|||||||
self.assertTrue(self.manager.get_config(self.first)['config']['policy']['egg_rules']['1001010']['enabled'])
|
self.assertTrue(self.manager.get_config(self.first)['config']['policy']['egg_rules']['1001010']['enabled'])
|
||||||
self.assertFalse(self.manager.status(self.first)['running'])
|
self.assertFalse(self.manager.status(self.first)['running'])
|
||||||
panel=self.go('gifts')
|
panel=self.go('gifts')
|
||||||
expect(panel.locator('[data-view-status="next_ready_at"]')).to_contain_text('北京时间')
|
expect(panel.locator('[data-view-status="next_ready_at"]')).to_have_count(0)
|
||||||
|
expect(panel).not_to_contain_text('下次可赠礼:')
|
||||||
|
expect(panel.locator('button[data-operation="configure_bag"]')).to_be_visible()
|
||||||
|
self.assertEqual(self.errors,[])
|
||||||
|
|
||||||
|
def test_bulk_runtime_notes_stay_out_of_settings_and_statistics_errors_retry(self):
|
||||||
|
keys = ('hatching', 'mainline', 'gifts', 'commissions', 'exploration', 'maps', 'ranch', 'daily', 'plans')
|
||||||
|
statistics_error = '本地统计读取失败,请查看服务器日志'
|
||||||
|
|
||||||
|
def diagnostics_view(route):
|
||||||
|
response = route.fetch().json() # Disposable loopback server and demo data only.
|
||||||
|
data = response.get('data')
|
||||||
|
if data is not None:
|
||||||
|
data.setdefault('details', {}).update({
|
||||||
|
'notes': [f'INLINE_RUNTIME_ONLY_{i}: retained primary / gift / potential / waiting' for i in range(40)],
|
||||||
|
'last_draw': 'INLINE_DRAW_ONLY', 'feed_status': ['waiting', 'INLINE_FEED_ONLY'],
|
||||||
|
'next_ready_at': 1794294489,
|
||||||
|
})
|
||||||
|
data['battle_mode'] = {'label': 'INLINE_BATTLE_MODE_ONLY'}
|
||||||
|
if data['page'] == 'statistics':
|
||||||
|
data['details']['statistics_error'] = statistics_error
|
||||||
|
self.fulfill(route, response)
|
||||||
|
|
||||||
|
self.page.route(f'**/api/accounts/{self.first}/views/*', diagnostics_view)
|
||||||
|
self.open()
|
||||||
|
for key in keys:
|
||||||
|
with self.subTest(page=key):
|
||||||
|
panel = self.go(key)
|
||||||
|
expect(panel.locator('[data-view-status]')).to_have_count(0)
|
||||||
|
self.assertNotIn('INLINE_', panel.evaluate('node => node.outerHTML'))
|
||||||
|
expect(panel.locator('.page-error')).to_be_hidden()
|
||||||
|
panel = self.go('hatching')
|
||||||
|
artifacts = Path(__file__).resolve().parents[3] / 'test-artifacts' / 'ui209'
|
||||||
|
artifacts.mkdir(parents=True, exist_ok=True)
|
||||||
|
for width, height in ((1280, 800), (390, 844)):
|
||||||
|
self.page.set_viewport_size({'width': width, 'height': height})
|
||||||
|
for tab in ('孵蛋策略', '牧场策略', '喂养策略'):
|
||||||
|
panel.locator(f'.subtab[data-key="{tab}"]').click()
|
||||||
|
expect(panel.locator('.form-section legend')).to_have_text(tab)
|
||||||
|
self.assertNotIn('INLINE_', panel.evaluate('node => node.outerHTML'))
|
||||||
|
panel.locator('.subtab[data-key="孵蛋策略"]').click()
|
||||||
|
first_control = panel.locator('.form-section input').first
|
||||||
|
expect(first_control).to_be_visible()
|
||||||
|
self.assertTrue(first_control.evaluate('''node => {
|
||||||
|
const r = node.getBoundingClientRect(), panel = node.closest('.page-panel').getBoundingClientRect();
|
||||||
|
return r.top >= panel.top && r.bottom <= Math.min(panel.bottom, innerHeight);
|
||||||
|
}'''), 'Settings must begin inside the visible workbench')
|
||||||
|
self.assertLessEqual(self.page.evaluate('document.documentElement.scrollWidth'), width)
|
||||||
|
self.page.screenshot(path=str(artifacts / f'hatching-{width}x{height}.png'))
|
||||||
|
expect(self.page.locator('#strategy-toggle')).to_be_visible()
|
||||||
|
expect(self.page.locator('#log-panel')).to_have_count(1)
|
||||||
|
expect(self.page.locator('#log-panel')).to_be_hidden()
|
||||||
|
self.page.locator('#log-toggle').click()
|
||||||
|
expect(self.page.locator('#log-panel')).to_be_visible()
|
||||||
|
self.page.locator('#log-toggle').click()
|
||||||
|
expect(self.page.locator('#log-panel')).to_be_hidden()
|
||||||
|
panel = self.go('statistics')
|
||||||
|
expect(panel.get_by_role('alert')).to_contain_text('本地统计读取失败,请查看服务器日志')
|
||||||
|
expect(panel.locator('.page-loading')).to_be_hidden()
|
||||||
|
statistics_error = ''
|
||||||
|
with self.page.expect_response(lambda response: '/views/statistics?' in response.url):
|
||||||
|
panel.get_by_role('button', name='重新读取', exact=True).click()
|
||||||
|
expect(panel.get_by_role('alert')).to_be_hidden()
|
||||||
|
expect(panel.locator('.statistics-table-host table')).to_be_visible()
|
||||||
self.assertEqual(self.errors, [])
|
self.assertEqual(self.errors, [])
|
||||||
|
|
||||||
def test_update_dialog_polls_host_progress_recovers_and_stops_on_close(self):
|
def test_update_dialog_polls_host_progress_recovers_and_stops_on_close(self):
|
||||||
|
|||||||
@@ -0,0 +1,247 @@
|
|||||||
|
"""Web authorization of Engine-classified recovery, using offline clients only."""
|
||||||
|
from copy import deepcopy
|
||||||
|
import math
|
||||||
|
import time
|
||||||
|
from types import SimpleNamespace
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import Mock, patch
|
||||||
|
|
||||||
|
from ranch_assistant.game_data import ProgressionData
|
||||||
|
from ranch_assistant.model import Snapshot
|
||||||
|
from ranch_web.service import AccountWorker
|
||||||
|
from ranch_web.tests import test_lifecycle_recovery as lifecycle
|
||||||
|
from ranch_web.tests import test_service as fixtures
|
||||||
|
from ranch_web.views import build_view
|
||||||
|
|
||||||
|
|
||||||
|
class RecoveryGuardContractTests(unittest.TestCase):
|
||||||
|
def worker(self, runtime):
|
||||||
|
worker = AccountWorker.__new__(AccountWorker)
|
||||||
|
worker.active_identity, worker._legacy_pending = None, {}
|
||||||
|
record = {"kind": "stage_battle", "stage_id": "0102", "phase": "unknown",
|
||||||
|
"execution_status": "timed_out", "terminal_reason": "worker_wall_clock_limit",
|
||||||
|
"path": "stageService/stageStart"}
|
||||||
|
worker.engine = SimpleNamespace(snapshot=object(), battles=runtime,
|
||||||
|
battle_journal=SimpleNamespace(pending=lambda snapshot: record),
|
||||||
|
_progression_pending=lambda: record, sweeper=SimpleNamespace(state={}),
|
||||||
|
explore_planner=SimpleNamespace(pending=lambda snapshot: None), _breakthrough_pending=None)
|
||||||
|
return worker, record
|
||||||
|
|
||||||
|
def test_engine_recovery_contract_overrides_old_clock_predicate(self):
|
||||||
|
for allowed in (False, True):
|
||||||
|
with self.subTest(allowed=allowed):
|
||||||
|
runtime = SimpleNamespace(recovery_status=Mock(return_value={
|
||||||
|
"state": "abandon_stage" if allowed else "blocked", "resumable": allowed,
|
||||||
|
"message": "已确认开战,按原客户端协议退出"}),
|
||||||
|
resumable_task_clock=Mock(return_value=not allowed))
|
||||||
|
worker, record = self.worker(runtime)
|
||||||
|
worker.engine.pending_battle_recovery = Mock(return_value=runtime.recovery_status.return_value)
|
||||||
|
self.assertEqual(worker._pending_execution_reason() == "", allowed)
|
||||||
|
worker.engine.pending_battle_recovery.assert_called_once_with()
|
||||||
|
runtime.recovery_status.assert_not_called()
|
||||||
|
runtime.resumable_task_clock.assert_not_called()
|
||||||
|
|
||||||
|
def test_truthy_recovery_flag_does_not_grant_write_permission(self):
|
||||||
|
for flag in (1, "true", None):
|
||||||
|
with self.subTest(flag=flag):
|
||||||
|
worker, _ = self.worker(SimpleNamespace(recovery_status=lambda *args, **kwargs: {
|
||||||
|
"state": "abandon_stage", "resumable": flag, "message": ""},
|
||||||
|
resumable_task_clock=lambda record: True))
|
||||||
|
worker.engine.pending_battle_recovery = lambda: {"state": "abandon_stage", "resumable": flag, "message": ""}
|
||||||
|
self.assertTrue(worker._pending_execution_reason())
|
||||||
|
|
||||||
|
def test_runtime_without_recovery_helper_keeps_old_clock_fallback(self):
|
||||||
|
for allowed in (False, True):
|
||||||
|
with self.subTest(allowed=allowed):
|
||||||
|
worker, _ = self.worker(SimpleNamespace(resumable_task_clock=lambda record: allowed))
|
||||||
|
self.assertEqual(worker._pending_execution_reason() == "", allowed)
|
||||||
|
|
||||||
|
def test_disabled_origin_uses_specific_engine_policy_message(self):
|
||||||
|
worker, _ = self.worker(SimpleNamespace(resumable_task_clock=lambda record: True))
|
||||||
|
message = "对应委托策略已关闭,等待启用委托策略后恢复原战斗"
|
||||||
|
worker.engine.pending_battle_recovery = lambda: {
|
||||||
|
"state": "blocked_policy", "resumable": False, "message": message}
|
||||||
|
self.assertEqual(worker._pending_execution_reason(), message)
|
||||||
|
|
||||||
|
|
||||||
|
class LegacyBattleRecoveryTests(unittest.TestCase):
|
||||||
|
setUp = fixtures.ServiceTests.setUp
|
||||||
|
account = fixtures.ServiceTests.account
|
||||||
|
idle = fixtures.ServiceTests.idle
|
||||||
|
job = fixtures.ServiceTests.job
|
||||||
|
connected = lifecycle.LifecycleRecoveryTests.connected
|
||||||
|
tick = lifecycle.LifecycleRecoveryTests.tick
|
||||||
|
paths = lifecycle.LifecycleRecoveryTests.paths
|
||||||
|
|
||||||
|
def login(self, identifier):
|
||||||
|
return fixtures.ServiceTests.login(self, identifier, account="recovery-" + identifier)
|
||||||
|
|
||||||
|
def legacy_timeout(self, *, unaccepted=False):
|
||||||
|
identifier, worker = self.connected()
|
||||||
|
engine = worker.engine
|
||||||
|
source_id, source_type, source_step = (0, "4001004", 0) if unaccepted else (51, "1002013", 1)
|
||||||
|
engine.client.raw["currentTasks"] = ([] if unaccepted else [
|
||||||
|
{"id": source_id, "typeId": source_type, "curStep": source_step, "stepValue": 0}])
|
||||||
|
engine.snapshot = Snapshot(deepcopy(engine.client.raw))
|
||||||
|
engine.game_data = ProgressionData({"task_info": {source_type: {"type": 4, "name": "离线材料委托",
|
||||||
|
"steps": [{"statusType": "none", "statusValue": {}}]}}})
|
||||||
|
config = self.manager.get_config(identifier)
|
||||||
|
config["config"]["quest_policy"]["enabled"] = True
|
||||||
|
self.job(identifier, self.manager.set_config(identifier, config["config"], config["revision"])["job"])
|
||||||
|
journal = engine.battle_journal
|
||||||
|
record = journal.begin(engine.snapshot, {"kind": "stage_battle", "stage_id": "0102", "difficulty": 1,
|
||||||
|
"battle_kind": "ordinary_stage", "description": "离线委托材料关卡", "task_id": None,
|
||||||
|
"task_type_id": None, "source_task_id": source_id,
|
||||||
|
"source_task_type_id": source_type, "source_step_number": source_step})
|
||||||
|
journal.update(record, "unknown", path="stageService/stageStart", start_path="stageService/stageStart",
|
||||||
|
start_response={"resCode": 0, "triggerEvent": False, "stageEvent": None},
|
||||||
|
battle_mode="experimental", execution_mode="experimental", execution_status="timed_out", terminal=False,
|
||||||
|
terminal_reason="worker_wall_clock_limit", message="战斗已取消、超时或结果不确定,等待核对")
|
||||||
|
self.assertEqual(engine.battles.recovery_status(record, snapshot=engine.snapshot)["state"], "abandon_stage")
|
||||||
|
engine.last_pending_check = time.monotonic() - 121
|
||||||
|
worker.schedule.next_poll = math.inf
|
||||||
|
return identifier, worker
|
||||||
|
|
||||||
|
def test_legacy_timeout_blocked_by_default_when_engine_denies_recovery(self):
|
||||||
|
identifier, worker = self.legacy_timeout()
|
||||||
|
evidence = deepcopy(worker.engine.battle_journal.pending(worker.engine.snapshot))
|
||||||
|
before = len(fixtures.FakeClient.calls)
|
||||||
|
with patch.object(worker.engine, "pending_battle_recovery", return_value={
|
||||||
|
"state": "blocked", "resumable": False, "message": "尚无可验证的安全恢复证据"}):
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "start"), status="failed")
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertFalse(worker.running)
|
||||||
|
self.assertTrue(worker.strategy_requested)
|
||||||
|
self.assertTrue(all(path == "masterService/masterQueryDetail" for path in self.paths(before)))
|
||||||
|
self.assertEqual(worker.engine.battle_journal.pending(worker.engine.snapshot), evidence)
|
||||||
|
|
||||||
|
def test_strict_safe_legacy_timeout_starts_then_exits_on_reconcile_without_reentry(self):
|
||||||
|
identifier, worker = self.legacy_timeout()
|
||||||
|
self.assert_failure_exit(identifier, worker)
|
||||||
|
|
||||||
|
def test_unaccepted_commission_legacy_timeout_exits_without_reentry_or_reward(self):
|
||||||
|
identifier, worker = self.legacy_timeout(unaccepted=True)
|
||||||
|
self.assert_failure_exit(identifier, worker)
|
||||||
|
|
||||||
|
def assert_failure_exit(self, identifier, worker):
|
||||||
|
before = len(fixtures.FakeClient.calls)
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "start"))
|
||||||
|
self.assertTrue(worker.running)
|
||||||
|
self.assertFalse(worker.engine.auto, "Start must not dispatch recovery inline")
|
||||||
|
self.assertEqual(len(fixtures.FakeClient.calls), before)
|
||||||
|
state = self.manager.status(identifier)
|
||||||
|
self.assertEqual(state["strategy_state"], "recovering")
|
||||||
|
self.assertIn("退出", state["strategy_message"])
|
||||||
|
self.assertNotIn("战果已保存", state["strategy_message"])
|
||||||
|
worker.schedule.next_poll = math.inf
|
||||||
|
after = self.manager.logs(identifier)["next"]
|
||||||
|
poll = worker.engine.poll
|
||||||
|
|
||||||
|
def recovery_poll(**kwargs):
|
||||||
|
self.assertFalse(worker.engine.auto, "Recovery must not enable other strategies")
|
||||||
|
self.assertIs(kwargs.get("resume_pending"), True)
|
||||||
|
return poll(**kwargs)
|
||||||
|
|
||||||
|
with patch.object(worker.engine, "poll", side_effect=recovery_poll):
|
||||||
|
self.assertEqual(self.tick(identifier, worker)["result"]["kind"], "reconcile")
|
||||||
|
writes = [("/".join(url.rsplit("/", 2)[-2:]),
|
||||||
|
{key: value for key, value in payload.items() if key not in {"token", "reqid", "reqsid"}})
|
||||||
|
for _, url, payload in fixtures.FakeClient.calls[before:]
|
||||||
|
if not url.endswith("masterService/masterQueryDetail")]
|
||||||
|
self.assertEqual(writes, [("battleService/recordBattleResult", {"stageId": "0102", "cityId": "1", "result": 0})])
|
||||||
|
self.assertIsNone(worker.engine.battle_journal.pending(worker.engine.snapshot))
|
||||||
|
self.assertTrue(worker.running)
|
||||||
|
self.assertTrue(worker.strategy_requested)
|
||||||
|
record = worker.engine.battle_journal.records(worker.engine.snapshot)[0]
|
||||||
|
self.assertEqual(record["outcome"], "abandoned")
|
||||||
|
self.assertNotIn("battle_data", record)
|
||||||
|
rows = build_view(worker.engine, "battles", worker.config)["rows"]
|
||||||
|
row = next(row for row in rows if row["outcome"] == "abandoned")
|
||||||
|
self.assertIn("已放弃(本地计算失败)", row["outcome_label"])
|
||||||
|
self.assertNotIn("打不过", row["outcome_label"])
|
||||||
|
logs = self.manager.logs(identifier, after=after)["entries"]
|
||||||
|
self.assertTrue(any("退出" in row["message"] for row in logs))
|
||||||
|
self.assertFalse(any("打不过" in row["message"] for row in logs))
|
||||||
|
|
||||||
|
def test_manual_refresh_never_authorizes_safe_source_zero_recovery(self):
|
||||||
|
identifier, worker = self.legacy_timeout(unaccepted=True)
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "start"))
|
||||||
|
before = len(fixtures.FakeClient.calls)
|
||||||
|
evidence = deepcopy(worker.engine.battle_journal.pending(worker.engine.snapshot))
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "refresh"))
|
||||||
|
self.assertTrue(worker.running)
|
||||||
|
self.assertFalse(worker.engine.auto)
|
||||||
|
self.assertEqual(worker.engine.battle_journal.pending(worker.engine.snapshot), evidence)
|
||||||
|
self.assertTrue(all(path == "masterService/masterQueryDetail" for path in self.paths(before)))
|
||||||
|
|
||||||
|
def test_manual_stop_prevents_safe_legacy_failure_exit(self):
|
||||||
|
identifier, worker = self.legacy_timeout()
|
||||||
|
self.manager.submit(identifier, "stop")
|
||||||
|
before = len(fixtures.FakeClient.calls)
|
||||||
|
evidence = deepcopy(worker.engine.battle_journal.pending(worker.engine.snapshot))
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertTrue(self.manager.status(identifier)["manual_stop"])
|
||||||
|
self.assertFalse(worker.running)
|
||||||
|
self.assertEqual(worker.engine.battle_journal.pending(worker.engine.snapshot), evidence)
|
||||||
|
self.assertTrue(all(path == "masterService/masterQueryDetail" for path in self.paths(before)))
|
||||||
|
|
||||||
|
def test_disabled_source_policy_prevents_safe_legacy_failure_exit(self):
|
||||||
|
identifier, worker = self.legacy_timeout(unaccepted=True)
|
||||||
|
config = self.manager.get_config(identifier)
|
||||||
|
config["config"]["quest_policy"]["enabled"] = False
|
||||||
|
config["config"]["daily_policy"].update(enabled=True, selected=["gift"])
|
||||||
|
self.job(identifier, self.manager.set_config(identifier, config["config"], config["revision"])["job"])
|
||||||
|
worker.schedule.next_poll = math.inf
|
||||||
|
before = len(fixtures.FakeClient.calls)
|
||||||
|
evidence = deepcopy(worker.engine.battle_journal.pending(worker.engine.snapshot))
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "start"), status="failed")
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertEqual(worker.engine.battle_journal.pending(worker.engine.snapshot), evidence)
|
||||||
|
self.assertTrue(all(path == "masterService/masterQueryDetail" for path in self.paths(before)))
|
||||||
|
state = self.manager.status(identifier)
|
||||||
|
self.assertFalse(state["running"])
|
||||||
|
self.assertEqual(state["strategy_state"], "blocked")
|
||||||
|
self.assertTrue(state["strategy_requested"])
|
||||||
|
self.assertFalse(state["manual_stop"])
|
||||||
|
recovery = worker.engine.pending_battle_recovery()
|
||||||
|
self.assertEqual(recovery["state"], "blocked_policy")
|
||||||
|
self.assertEqual(state["strategy_message"], recovery["message"])
|
||||||
|
self.assertIn("委托", state["strategy_message"])
|
||||||
|
self.assertIn("启用", state["strategy_message"])
|
||||||
|
self.assertFalse(worker.engine.quest_policy.enabled)
|
||||||
|
self.assertTrue(worker.engine.daily_policy.enabled)
|
||||||
|
|
||||||
|
config = self.manager.get_config(identifier)
|
||||||
|
config["config"]["quest_policy"]["enabled"] = True
|
||||||
|
self.job(identifier, self.manager.set_config(identifier, config["config"], config["revision"])["job"])
|
||||||
|
self.assertEqual(worker.engine.battle_journal.pending(worker.engine.snapshot), evidence)
|
||||||
|
worker.engine.last_pending_check = time.monotonic() - 121
|
||||||
|
worker.schedule.next_poll = math.inf
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
writes = [("/".join(url.rsplit("/", 2)[-2:]), payload.get("result"))
|
||||||
|
for _, url, payload in fixtures.FakeClient.calls[before:]
|
||||||
|
if not url.endswith("masterService/masterQueryDetail")]
|
||||||
|
self.assertEqual(writes, [("battleService/recordBattleResult", 0)])
|
||||||
|
self.assertIsNone(worker.engine.battle_journal.pending(worker.engine.snapshot))
|
||||||
|
self.assertTrue(worker.running)
|
||||||
|
self.assertTrue(worker.strategy_requested)
|
||||||
|
|
||||||
|
def test_unknown_start_settlement_or_failure_reply_never_grants_recovery(self):
|
||||||
|
for changes in ({"start_response": None}, {"settlement_dispatched": True, "path": "battleService/battleEnd"},
|
||||||
|
{"record_dispatched": True}):
|
||||||
|
with self.subTest(changes=changes):
|
||||||
|
identifier, worker = self.legacy_timeout()
|
||||||
|
journal = worker.engine.battle_journal
|
||||||
|
journal.update(journal.pending(worker.engine.snapshot), "unknown", **changes)
|
||||||
|
evidence = deepcopy(journal.pending(worker.engine.snapshot))
|
||||||
|
before = len(fixtures.FakeClient.calls)
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "start"), status="failed")
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertFalse(worker.running)
|
||||||
|
self.assertTrue(worker.strategy_requested)
|
||||||
|
self.assertEqual(journal.pending(worker.engine.snapshot), evidence)
|
||||||
|
self.assertTrue(all(path == "masterService/masterQueryDetail" for path in self.paths(before)))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,196 @@
|
|||||||
|
"""Commission DTO regressions with temporary engines and synthetic local history."""
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import Mock, patch
|
||||||
|
|
||||||
|
from ranch_assistant.engine import Engine, demo_snapshot
|
||||||
|
from ranch_assistant.model import Catalog
|
||||||
|
from ranch_web.policies import default_config
|
||||||
|
from ranch_web.views import build_view
|
||||||
|
|
||||||
|
|
||||||
|
def history_fixture(day):
|
||||||
|
return {"date": day, "dates": [day], "summary": {
|
||||||
|
"accepted_count": 2, "completed_count": 1, "expected_ke": 35, "confirmed_ke": 15, "pending_count": 1, "unknown_reward_count": 0},
|
||||||
|
"rows": [{"id": "local-15", "task_id": 71, "task_type_id": "test15", "name": "提交魔物与道具",
|
||||||
|
"status": "completed", "accepted_at": day + "T01:02:03+00:00", "completed_at": day + "T02:03:04+00:00",
|
||||||
|
"expected_ke": 15, "confirmed_ke": 15, "selection_reason": "20氪金候选城市尚未解锁,回退15氪金",
|
||||||
|
"last_action": "服务器已确认领取15氪金", "events": [
|
||||||
|
{"time": day + "T01:02:03+00:00", "kind": "accept", "status": "confirmed", "description": "接取委托,预计15氪金"},
|
||||||
|
{"time": day + "T01:03:03+00:00", "kind": "handin_items", "status": "confirmed", "description": "已提交铁矿石 ×2"},
|
||||||
|
{"time": day + "T01:04:03+00:00", "kind": "handin_monsters", "status": "confirmed", "description": "已提交1级史莱姆 ×1"},
|
||||||
|
{"time": day + "T01:05:03+00:00", "kind": "dialogue", "status": "confirmed", "description": "已与城镇守卫对话"},
|
||||||
|
{"time": day + "T01:06:03+00:00", "kind": "battle", "status": "confirmed", "description": "委托战斗胜利,推进第4步"},
|
||||||
|
{"time": day + "T02:03:04+00:00", "kind": "claim", "status": "confirmed", "description": "服务器奖励回包确认氪金15"}]},
|
||||||
|
{"id": "local-20", "task_id": 72, "task_type_id": "test20", "name": "奖励待核对的委托",
|
||||||
|
"status": "unknown", "accepted_at": day + "T03:02:03+08:00", "completed_at": None,
|
||||||
|
"expected_ke": 20, "confirmed_ke": None, "last_action": "领奖请求超时,等待核对",
|
||||||
|
"events": [{"time": day + "T03:03:04+08:00", "kind": "claim", "status": "unknown", "description": "领奖回包未知"}]}]}
|
||||||
|
|
||||||
|
|
||||||
|
class CommissionHistoryViewTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
root = self.enterContext(tempfile.TemporaryDirectory(prefix="commission-web-history-"))
|
||||||
|
self.engine = Engine(Catalog(), budget_path=Path(root) / "budget.json")
|
||||||
|
self.engine.snapshot = demo_snapshot(self.engine.catalog)
|
||||||
|
self.engine.demo = False
|
||||||
|
self.engine.client = Mock()
|
||||||
|
self.engine.client.call.side_effect = AssertionError("Game calls forbidden in history views")
|
||||||
|
self.config = default_config()
|
||||||
|
self.history = history_fixture("2026-11-12")
|
||||||
|
self.engine.commission_history = Mock(return_value=self.history)
|
||||||
|
self.engine.commission_offer_diagnostics = Mock(return_value=[])
|
||||||
|
|
||||||
|
def view(self, **query):
|
||||||
|
return build_view(self.engine, "commissions", self.config, {"tab": "history", **query})
|
||||||
|
|
||||||
|
def test_history_reads_only_local_helper_and_separates_confirmed_rewards(self):
|
||||||
|
self.engine.tasks.rows = Mock(side_effect=AssertionError("Current tasks are not history"))
|
||||||
|
self.engine.progression_rows = Mock(side_effect=AssertionError("Do not plan game actions in history"))
|
||||||
|
self.engine.commission_offer_diagnostics.side_effect = AssertionError("History must not inspect current offers")
|
||||||
|
self.engine.plans = Mock(side_effect=AssertionError("Do not plan in history"))
|
||||||
|
dto = self.view(date="2026-11-12")
|
||||||
|
self.engine.commission_history.assert_called_once_with(day="2026-11-12")
|
||||||
|
self.engine.client.call.assert_not_called()
|
||||||
|
self.assertEqual([tab["title"] for tab in dto["tabs"]], ["当前委托", "每日记录"])
|
||||||
|
self.assertEqual(dto["form"], [])
|
||||||
|
self.assertEqual(dto["actions"], [{"operation": "reload_view", "label": "刷新记录"}])
|
||||||
|
self.assertIn("已记录接取 2", dto["summary"])
|
||||||
|
self.assertIn("已记录完成 1", dto["summary"])
|
||||||
|
self.assertIn("仅有本地已保存记录", dto["summary"])
|
||||||
|
self.assertIn("当日领奖确认氪金 15", dto["summary"])
|
||||||
|
self.assertIn("当日接取标注氪金 35", dto["summary"])
|
||||||
|
self.assertIn("操作待核对 1", dto["summary"])
|
||||||
|
self.assertIn("领奖金额未记录 0", dto["summary"])
|
||||||
|
self.assertEqual(dto["rows"][1]["confirmed_ke"], "未确认")
|
||||||
|
self.assertEqual(dto["rows"][1]["status_label"], "结果待核对")
|
||||||
|
self.assertEqual(dto["rows"][0]["accepted_at"], "2026-11-12 09:02:03")
|
||||||
|
self.assertEqual(dto["rows"][1]["completed_at"], "—")
|
||||||
|
json.dumps(dto, ensure_ascii=False, allow_nan=False)
|
||||||
|
|
||||||
|
def test_details_show_actual_handins_dialogue_battle_and_claim_evidence(self):
|
||||||
|
dto = self.view(date="2026-11-12")
|
||||||
|
detail = dto["details"]["local-15"]
|
||||||
|
for text in ("铁矿石 ×2", "1级史莱姆 ×1", "城镇守卫", "战斗胜利", "氪金15"):
|
||||||
|
self.assertIn(text, detail["行动记录"])
|
||||||
|
self.assertIn("回退15氪金", detail["选择 / 回退原因"])
|
||||||
|
self.assertIn("结果待核对", dto["details"]["local-20"]["行动记录"])
|
||||||
|
self.assertNotIn("已确认", dto["details"]["local-20"]["行动记录"])
|
||||||
|
|
||||||
|
def test_search_can_find_action_details_without_changing_daily_totals(self):
|
||||||
|
dto = self.view(date="2026-11-12", search="铁矿石")
|
||||||
|
self.assertEqual([row["id"] for row in dto["rows"]], ["local-15"])
|
||||||
|
self.assertIn("已记录接取 2", dto["summary"])
|
||||||
|
self.assertEqual(set(dto["details"]), {"local-15"})
|
||||||
|
|
||||||
|
def test_empty_history_does_not_invent_old_acceptance_from_current_tasks(self):
|
||||||
|
self.engine.snapshot.raw["currentTasks"] = [{"id": 3, "typeId": "test20", "curStep": 1}]
|
||||||
|
self.engine.commission_history.return_value = {"date": "2026-11-11", "summary": {}, "rows": []}
|
||||||
|
dto = self.view(date="2026-11-11")
|
||||||
|
self.assertEqual(dto["rows"], [])
|
||||||
|
self.assertIn("已记录接取 0", dto["summary"])
|
||||||
|
self.assertIn("历史接取与奖励未追溯", dto["summary"])
|
||||||
|
|
||||||
|
def test_history_available_without_snapshot(self):
|
||||||
|
self.engine.snapshot = None
|
||||||
|
dto = self.view(date="2026-11-12")
|
||||||
|
self.assertEqual(len(dto["rows"]), 2)
|
||||||
|
self.engine.client.call.assert_not_called()
|
||||||
|
current = build_view(self.engine, "commissions", self.config)
|
||||||
|
self.assertIn("请先登录", current["summary"])
|
||||||
|
self.assertEqual(len(current["tabs"]), 2)
|
||||||
|
|
||||||
|
def test_default_date_is_beijing_today_at_utc_day_boundary(self):
|
||||||
|
class FixedDatetime(datetime):
|
||||||
|
@classmethod
|
||||||
|
def now(cls, tz=None):
|
||||||
|
return cls(2026, 11, 12, 17, tzinfo=timezone.utc).astimezone(tz)
|
||||||
|
|
||||||
|
with patch("ranch_web.views.datetime", FixedDatetime):
|
||||||
|
dto = self.view()
|
||||||
|
self.engine.commission_history.assert_called_once_with(day="2026-11-13")
|
||||||
|
self.assertEqual(dto["filters"][0]["value"], "2026-11-13")
|
||||||
|
self.assertEqual(dto["filters"][0]["type"], "date")
|
||||||
|
|
||||||
|
def test_invalid_date_never_calls_history_helper(self):
|
||||||
|
for day in ("2026-11-31", "2026-1-1", "../2026-11-12", ["2026-11-12"]):
|
||||||
|
with self.subTest(day=day), self.assertRaisesRegex(ValueError, "记录日期"):
|
||||||
|
self.view(date=day)
|
||||||
|
self.engine.commission_history.assert_not_called()
|
||||||
|
|
||||||
|
def test_raw_history_fields_never_reach_public_view(self):
|
||||||
|
row = self.history["rows"][0]
|
||||||
|
row["raw_response"] = {"token": "private-response"}
|
||||||
|
row["events"][0].update(raw={"password": "private-event"}, payload={"removeIds": [1234567]})
|
||||||
|
wire = json.dumps(self.view(date="2026-11-12"), ensure_ascii=False)
|
||||||
|
for value in ("private-response", "private-event", "1234567", "raw_response", "removeIds"):
|
||||||
|
self.assertNotIn(value, wire)
|
||||||
|
|
||||||
|
def test_current_offer_presence_never_implies_receivable(self):
|
||||||
|
self.engine.catalog.data["task_info"] = {
|
||||||
|
"test20": {"name": "高额候选", "reward": {"money": 123, "ke": 20}},
|
||||||
|
"test15": {"name": "回退候选", "reward": {"money": 456, "ke": 15}}}
|
||||||
|
self.engine.tasks.rows = Mock(return_value=[
|
||||||
|
("test20", "高额候选", "城市 4 可接", "提交物品", {"city": 4}),
|
||||||
|
("test15", "回退候选", "城市 1 可接", "提交金币", {"city": 1})])
|
||||||
|
self.engine.tasks.current = Mock(return_value=[])
|
||||||
|
self.engine.progression_rows = Mock(return_value=[
|
||||||
|
{"category": "commission", "task_type_id": "test20", "block_reason": "城市尚未解锁"},
|
||||||
|
{"category": "commission", "task_type_id": "test15", "selection_reason": "20氪金候选未解锁,回退15氪金"}])
|
||||||
|
dto = build_view(self.engine, "commissions", self.config)
|
||||||
|
high, fallback = dto["rows"]
|
||||||
|
self.assertEqual(high["reward_ke"], 20)
|
||||||
|
self.assertEqual(high["reward_money"], 123)
|
||||||
|
self.assertEqual(high["status"], "暂不接取")
|
||||||
|
self.assertEqual(high["reason"], "城市尚未解锁")
|
||||||
|
self.assertNotIn("可接", fallback["status"])
|
||||||
|
self.assertIn("回退15氪金", fallback["selection_reason"])
|
||||||
|
self.assertIn("20 → 15 → 10", dto["details"][fallback["id"]]["接取优先级"])
|
||||||
|
|
||||||
|
def test_authoritative_offer_diagnostics_match_city_and_explain_fallback(self):
|
||||||
|
self.engine.catalog.data["task_info"] = {
|
||||||
|
"test20": {"name": "高额候选", "reward": {"money": 123, "ke": 20}},
|
||||||
|
"test15": {"name": "回退候选", "reward": {"money": 456, "ke": 15}}}
|
||||||
|
self.engine.tasks.rows = Mock(return_value=[
|
||||||
|
("test20", "高额候选", "城市 4 可接", "", {"city": 4}),
|
||||||
|
("test15", "回退候选", "城市 1 可接", "", {"city": 1}),
|
||||||
|
("test15", "回退候选", "城市 9 可接", "", {"city": 9})])
|
||||||
|
self.engine.tasks.current = Mock(return_value=[])
|
||||||
|
self.engine.progression_rows = Mock(return_value=[
|
||||||
|
{"category": "commission", "task_type_id": "test15", "block_reason": "错误城市的阻塞原因"}])
|
||||||
|
self.engine.commission_offer_diagnostics.return_value = [
|
||||||
|
{"task_type_id": "test20", "name": "高额候选", "city": 4, "expected_ke": 20, "eligible": False, "reason": "城市尚未解锁"},
|
||||||
|
{"task_type_id": "test15", "name": "回退候选", "city": 1, "expected_ke": 15, "eligible": True, "reason": "可接取"},
|
||||||
|
{"task_type_id": "test15", "name": "回退候选", "city": 9, "expected_ke": 15, "eligible": False, "reason": "提交魔物受保留保护"}]
|
||||||
|
dto = build_view(self.engine, "commissions", self.config)
|
||||||
|
self.assertEqual([row["status"] for row in dto["rows"]], ["暂不接取", "可接取", "暂不接取"])
|
||||||
|
self.assertIn("选择 15 氪金", dto["rows"][1]["selection_reason"])
|
||||||
|
self.assertIn("城市尚未解锁", dto["rows"][1]["selection_reason"])
|
||||||
|
self.assertNotIn("错误城市", dto["rows"][1]["reason"])
|
||||||
|
self.assertEqual(dto["rows"][2]["reason"], "提交魔物受保留保护")
|
||||||
|
self.engine.client.call.assert_not_called()
|
||||||
|
|
||||||
|
def test_pending_zero_reward_and_cross_day_totals_remain_distinct(self):
|
||||||
|
self.history["rows"][0].update(expected_ke=20, confirmed_ke=0, accepted_at="2026-11-11T01:02:03+08:00")
|
||||||
|
self.history["rows"][1]["status"] = "pending"
|
||||||
|
self.history["summary"].update(accepted_count=0, expected_ke=0, confirmed_ke=0)
|
||||||
|
dto = self.view(date="2026-11-12")
|
||||||
|
self.assertEqual(dto["rows"][0]["confirmed_ke"], 0)
|
||||||
|
self.assertEqual(dto["rows"][0]["expected_ke"], 20)
|
||||||
|
self.assertEqual(dto["rows"][1]["confirmed_ke"], "未确认")
|
||||||
|
self.assertEqual(dto["rows"][1]["status_label"], "等待核对")
|
||||||
|
self.assertIn("当日接取标注氪金 0", dto["summary"])
|
||||||
|
self.assertNotIn("损失", dto["summary"])
|
||||||
|
|
||||||
|
def test_backend_read_error_visible_without_exposing_private_fields(self):
|
||||||
|
self.history.update(error="委托历史无法读取,原文件已保留", notice="仅展示本地已保存记录")
|
||||||
|
dto = self.view(date="2026-11-12")
|
||||||
|
self.assertIn("委托历史无法读取,原文件已保留", dto["summary"])
|
||||||
|
self.assertIn("仅有本地已保存记录", dto["summary"])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
"""Real worker/local ledger integration; game transports are always offline fakes."""
|
||||||
|
from copy import deepcopy
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
from types import SimpleNamespace
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import Mock, patch
|
||||||
|
|
||||||
|
from ranch_assistant.engine import Engine
|
||||||
|
from ranch_web.tests import test_service as fixtures
|
||||||
|
|
||||||
|
|
||||||
|
class CommissionHistoryServiceTests(unittest.TestCase):
|
||||||
|
setUp = fixtures.ServiceTests.setUp
|
||||||
|
account = fixtures.ServiceTests.account
|
||||||
|
idle = fixtures.ServiceTests.idle
|
||||||
|
job = fixtures.ServiceTests.job
|
||||||
|
|
||||||
|
def view(self, identifier, day):
|
||||||
|
response = self.manager.view(identifier, "commissions", {"tab": "history", "date": day})
|
||||||
|
if response["loading"]:
|
||||||
|
self.job(identifier, {"id": response["job_id"]})
|
||||||
|
response = self.manager.view(identifier, "commissions", {"tab": "history", "date": day})
|
||||||
|
self.assertFalse(response["loading"])
|
||||||
|
return response["data"]
|
||||||
|
|
||||||
|
def tick(self, identifier, *, failed=False):
|
||||||
|
worker = self.manager._worker(identifier)
|
||||||
|
with patch.object(worker.schedule, "due", return_value="poll"):
|
||||||
|
self.job(identifier, worker.enqueue("__tick"), status="failed" if failed else "succeeded")
|
||||||
|
|
||||||
|
def test_real_local_ledger_history_is_account_role_day_isolated_without_game_calls(self):
|
||||||
|
first, second = self.account(), self.account()
|
||||||
|
worker = self.manager._worker(first)
|
||||||
|
engine = worker.engine
|
||||||
|
role = str(engine.snapshot.raw["master"]["id"])
|
||||||
|
today = datetime.now(timezone(timedelta(hours=8))).date()
|
||||||
|
stamp = datetime.combine(today, datetime.min.time(), timezone(timedelta(hours=8))).timestamp() + 3600
|
||||||
|
info = {"type": 4, "name": "已保存的20氪金委托", "reward": {"ke": 20}}
|
||||||
|
record = {"attempt_id": "synthetic-accept", "role_id": role, "task_type_id": "test20", "task_id": 71,
|
||||||
|
"kind": "quest_accept", "path": "taskService/taskLoopReceive", "timestamp": stamp,
|
||||||
|
"finished_at": stamp, "phase": "done", "outcome": "task", "response_confirmed": True,
|
||||||
|
"response": {"resCode": 0, "task": {"id": 71, "typeId": "test20", "curStep": 1}},
|
||||||
|
"commission": {"name": info["name"], "expected_ke": 20}}
|
||||||
|
engine._commission_history.ingest(role, [record], lambda _: info, engine.snapshot)
|
||||||
|
after = self.manager.logs(first)["next"]
|
||||||
|
with patch.object(engine, "read_snapshot", side_effect=AssertionError("history must stay local")), \
|
||||||
|
patch.object(engine, "poll", side_effect=AssertionError("history must not poll")):
|
||||||
|
dto = self.view(first, today.isoformat())
|
||||||
|
self.assertIn("已记录接取 1", dto["summary"])
|
||||||
|
self.assertEqual(dto["rows"][0]["confirmed_ke"], "未确认")
|
||||||
|
self.assertEqual(self.view(second, today.isoformat())["rows"], [])
|
||||||
|
self.assertEqual(self.view(first, (today - timedelta(days=1)).isoformat())["rows"], [])
|
||||||
|
original = engine.snapshot
|
||||||
|
engine.snapshot = deepcopy(original)
|
||||||
|
engine.snapshot.raw["master"]["id"] = "other-local-role"
|
||||||
|
worker._invalidate_views()
|
||||||
|
self.assertEqual(self.view(first, today.isoformat())["rows"], [])
|
||||||
|
engine.snapshot = original
|
||||||
|
worker._invalidate_views()
|
||||||
|
self.assertEqual(len(self.view(first, today.isoformat())["rows"]), 1)
|
||||||
|
self.assertEqual(fixtures.FakeClient.calls, [])
|
||||||
|
self.assertEqual(self.manager.logs(first, after=after)["entries"], [], "Reading history must not create activity logs")
|
||||||
|
|
||||||
|
def test_accept_step_claim_and_unknown_messages_are_chinese_categorized_and_redacted(self):
|
||||||
|
def action(engine, intent):
|
||||||
|
return engine.snapshot, [], intent["message"]
|
||||||
|
|
||||||
|
with patch.object(Engine, "_run_progression_intent", action):
|
||||||
|
identifier = self.account()
|
||||||
|
worker = self.manager._worker(identifier)
|
||||||
|
worker.engine.game_data = SimpleNamespace(task=lambda _: {"type": 4})
|
||||||
|
messages = [
|
||||||
|
("接取委托:本地测试(预计20氪金);已确认", "info"),
|
||||||
|
("提交委托步骤:本地测试(预计20氪金);已提交铁矿石 ×2", "info"),
|
||||||
|
("领取委托奖励:本地测试(预计20氪金);已确认,实际获得20氪金", "info"),
|
||||||
|
("领取委托奖励:本地测试(预计20氪金);结果未知,等待核对,禁止重发", "warning"),
|
||||||
|
("委托战斗:本地测试(预计20氪金);战斗失败,未推进委托", "error")]
|
||||||
|
for message, level in messages:
|
||||||
|
with self.subTest(message=message):
|
||||||
|
before = self.manager.logs(identifier)["next"]
|
||||||
|
intent = {"kind": "progression_complete", "task_type_id": "test20", "message": message + ";password=synthetic-password"}
|
||||||
|
with patch.object(worker.engine, "poll", side_effect=lambda **_: worker.engine._run_progression_intent(intent)):
|
||||||
|
self.tick(identifier)
|
||||||
|
entries = self.manager.logs(identifier, after=before)["entries"]
|
||||||
|
self.assertEqual(len(entries), 1)
|
||||||
|
self.assertEqual((entries[0]["category"], entries[0]["level"]), ("commissions", level))
|
||||||
|
self.assertIn("本地测试", entries[0]["message"])
|
||||||
|
self.assertIn("20氪金", entries[0]["message"])
|
||||||
|
self.assertNotIn("synthetic-password", entries[0]["message"])
|
||||||
|
|
||||||
|
def test_failed_commission_keeps_one_error_with_name_reward_and_no_success(self):
|
||||||
|
def action(engine, intent):
|
||||||
|
raise TimeoutError("token=synthetic-token 请求超时")
|
||||||
|
|
||||||
|
with patch.object(Engine, "_run_progression_intent", action):
|
||||||
|
identifier = self.account()
|
||||||
|
worker = self.manager._worker(identifier)
|
||||||
|
worker.engine.game_data = SimpleNamespace(task=lambda _: {"type": 4, "name": "受保护的提交委托", "reward": {"ke": 20}})
|
||||||
|
before = self.manager.logs(identifier)["next"]
|
||||||
|
intent = {"kind": "progression_loop_accept", "task_type_id": "test20"}
|
||||||
|
with patch.object(worker.engine, "poll", side_effect=lambda **_: worker.engine._run_progression_intent(intent)):
|
||||||
|
self.tick(identifier, failed=True)
|
||||||
|
entries = self.manager.logs(identifier, after=before)["entries"]
|
||||||
|
self.assertEqual(len(entries), 1)
|
||||||
|
self.assertEqual((entries[0]["category"], entries[0]["level"]), ("commissions", "error"))
|
||||||
|
for value in ("受保护的提交委托", "标注20氪金", "接取异常", "结果待核对"):
|
||||||
|
self.assertIn(value, entries[0]["message"])
|
||||||
|
self.assertNotIn("synthetic-token", entries[0]["message"])
|
||||||
|
self.assertNotIn("已确认", entries[0]["message"])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
"""Commission diagnostics use offline fake clients and source-derived cities."""
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from ranch_assistant.engine import Engine
|
||||||
|
from ranch_assistant.game_data import load_progression_data
|
||||||
|
from ranch_assistant.model import Catalog, Policy, Snapshot
|
||||||
|
from ranch_assistant.progression import ProgressionPlanner
|
||||||
|
from ranch_assistant.quests import QuestPolicy
|
||||||
|
from ranch_assistant.tests import test_commission_procurement as fixtures
|
||||||
|
from ranch_assistant.tests.test_progression import snapshot
|
||||||
|
from ranch_web.policies import default_config
|
||||||
|
from ranch_web.views import build_view
|
||||||
|
|
||||||
|
|
||||||
|
class CommissionProcurementViewTests(unittest.TestCase):
|
||||||
|
def test_preparable_is_distinct_from_receivable_and_has_exact_counts(self):
|
||||||
|
fixture = fixtures.CommissionProcurementTests()
|
||||||
|
fixture.setUp()
|
||||||
|
self.addCleanup(fixture.doCleanups)
|
||||||
|
fixture.catalog.data["task_info"] = fixture.tasks
|
||||||
|
engine, client = fixture.engine()
|
||||||
|
dto = build_view(engine, "commissions", default_config())
|
||||||
|
high = next(r for r in dto["rows"] if r["task_type_id"] == "400")
|
||||||
|
self.assertEqual(high["status"], "补齐后接取")
|
||||||
|
self.assertEqual(high["reason_kind"], "temp_resource")
|
||||||
|
self.assertEqual((high["resources"][0]["needed"], high["resources"][0]["available"]), (1, 0))
|
||||||
|
self.assertTrue(high["progress_plan"])
|
||||||
|
self.assertIn("不消耗接取次数", high["reason"])
|
||||||
|
self.assertEqual(client.writes, [])
|
||||||
|
engine._run_progression_intent(fixture.intent(engine))
|
||||||
|
self.assertEqual(engine.commission_history()["summary"]["accepted_count"], 0)
|
||||||
|
self.assertIn("未消耗接取次数", engine.commission_history()["events"][0]["description"])
|
||||||
|
|
||||||
|
def test_packaged_offers_replay_quota_and_city_gates(self):
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
data, catalog = load_progression_data(), Catalog()
|
||||||
|
cities = (4, 5, 8, 9)
|
||||||
|
offers = {str(city): [key for key, info in sorted(data.task_info.items())
|
||||||
|
if info.get("type") == 4 and (info.get("reward") or {}).get("ke") == 20
|
||||||
|
and any(str(step.get("position") or "").split("_", 1)[0] == f"city{city}"
|
||||||
|
for step in info.get("steps") or [])] for city in cities}
|
||||||
|
self.assertTrue(all(offers.values()))
|
||||||
|
for quota in (0, 4):
|
||||||
|
with self.subTest(quota=quota), patch("ranch_assistant.model.time.time", return_value=1700000000):
|
||||||
|
snap = snapshot(currentTasks=[])
|
||||||
|
snap.raw["history"].update(loopTask=offers, loopTaskNum=quota, loopTaskTime=snap.now,
|
||||||
|
unlockCity={str(city): False for city in cities})
|
||||||
|
planner = ProgressionPlanner(catalog, data)
|
||||||
|
diagnostics = planner.commission_offers(snap, QuestPolicy(enabled=True, allow_items=True, allow_monsters=True),
|
||||||
|
Policy())
|
||||||
|
twenty = [row for row in diagnostics if row["expected_ke"] == 20]
|
||||||
|
self.assertEqual(len(twenty), sum(map(len, offers.values())))
|
||||||
|
self.assertEqual({row["city"] for row in twenty}, set(cities))
|
||||||
|
self.assertTrue(all(row["remaining_quota"] == quota for row in diagnostics))
|
||||||
|
if quota == 0:
|
||||||
|
self.assertTrue(all(row["reason_kind"] == "quota" and not row["eligible"] and not row["preparable"]
|
||||||
|
for row in diagnostics))
|
||||||
|
self.assertEqual(planner.commission_plan(snap, QuestPolicy(enabled=True), Policy()), [])
|
||||||
|
else:
|
||||||
|
for row in twenty:
|
||||||
|
city_info = data.game_setting["cityInfo"][str(row["city"])]
|
||||||
|
self.assertEqual(row["reason_kind"], "city_locked")
|
||||||
|
self.assertFalse(row["eligible"] or row["preparable"])
|
||||||
|
self.assertEqual(row["city_name"], city_info["name"])
|
||||||
|
self.assertEqual(row["unlock_task_id"], city_info["openTask"])
|
||||||
|
self.assertTrue(row["unlock_task_id"])
|
||||||
|
self.assertIn(row["city_name"], row["reason"])
|
||||||
|
self.assertIn(row["unlock_task_id"], row["reason"])
|
||||||
|
|
||||||
|
def test_mainline_controller_reason_is_chinese_and_does_not_claim_victory(self):
|
||||||
|
engine = Engine(Catalog())
|
||||||
|
engine.snapshot = snapshot()
|
||||||
|
engine._progression_rows = [{"task_type_id": "1002013", "name": "猫狗的恩怨", "state": "received", "category": "mainline",
|
||||||
|
"step_number": 1, "total_steps": 1, "supported": False, "battle_kind": "task",
|
||||||
|
"block_reason": "Unsupported battle triggers: monDead; Unsupported monster controller: monMaker; Unsupported monster controller: monSteps"}]
|
||||||
|
dto = build_view(engine, "mainline", default_config())
|
||||||
|
reason = dto["rows"][0]["support"]
|
||||||
|
self.assertIn("魔物死亡事件", reason)
|
||||||
|
self.assertIn("生成魔物", reason)
|
||||||
|
self.assertIn("脚本行动", reason)
|
||||||
|
self.assertNotIn("Unsupported", reason)
|
||||||
|
self.assertNotIn("胜利", reason)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,345 @@
|
|||||||
|
"""Web recovery through real Engine barriers, temporary stores and offline HTTP."""
|
||||||
|
from copy import deepcopy
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import requests
|
||||||
|
|
||||||
|
from ranch_assistant.game_data import ProgressionData
|
||||||
|
from ranch_assistant.model import Snapshot
|
||||||
|
from ranch_assistant.tests.test_battle_orchestration import ExperimentalRuntime
|
||||||
|
from ranch_web.service import WebManager
|
||||||
|
from ranch_web.tests import test_service as fixtures
|
||||||
|
|
||||||
|
|
||||||
|
class LifecycleRecoveryTests(unittest.TestCase):
|
||||||
|
setUp = fixtures.ServiceTests.setUp
|
||||||
|
account = fixtures.ServiceTests.account
|
||||||
|
idle = fixtures.ServiceTests.idle
|
||||||
|
job = fixtures.ServiceTests.job
|
||||||
|
login = fixtures.ServiceTests.login
|
||||||
|
|
||||||
|
def connected(self):
|
||||||
|
identifier = self.account(False)
|
||||||
|
self.login(identifier)
|
||||||
|
worker = self.manager._worker(identifier)
|
||||||
|
self.now = 1000.0
|
||||||
|
worker.schedule.clock = lambda: self.now
|
||||||
|
worker.schedule.uniform = lambda low, high: high
|
||||||
|
worker.engine.last_heartbeat = self.now
|
||||||
|
self.enterContext(patch.object(worker.engine, "master_sync_due", return_value=False))
|
||||||
|
self.enterContext(patch.object(worker.engine, "growth_sync_due", return_value=False))
|
||||||
|
return identifier, worker
|
||||||
|
|
||||||
|
def battle(self, identifier, worker, *, timed_out=False):
|
||||||
|
"""Small task fixture already used by Engine's orchestration regressions."""
|
||||||
|
engine = worker.engine
|
||||||
|
raw = engine.client.raw
|
||||||
|
raw["master"].update(ti=1000, money=1000, timeTi=0)
|
||||||
|
raw["currentTasks"] = [{"id": 51, "typeId": "100", "curStep": 1, "stepValue": 0}]
|
||||||
|
raw["history"] = {"unlockCity": {"1": True}, "unlockStage": {"0101": [1, 2, 3]}}
|
||||||
|
raw["teams"] = [{"teamName": "teamA", "teamType": "battleTeam", "monsters": [raw["monsters"][0]["id"]]}]
|
||||||
|
raw["taskStepValue"] = 0
|
||||||
|
engine.snapshot = Snapshot(deepcopy(raw))
|
||||||
|
engine.game_data = ProgressionData({
|
||||||
|
"task_info": {"100": {"type": 1, "name": "离线任务", "steps": [
|
||||||
|
{"statusType": "passStage", "statusValue": {"stage": "0101", "level": 1}}]}},
|
||||||
|
"game_setting": {"cityInfo": {"1": {"name": "离线城市"}}},
|
||||||
|
"stage_info": {"0101": {"city": 1, "cost": {"ti": 6}, "level": {
|
||||||
|
str(n): {"cost": 0, "battle": {"fixture": True}} for n in (1, 2, 3)}}}})
|
||||||
|
runtime = ExperimentalRuntime()
|
||||||
|
original = runtime._run
|
||||||
|
if timed_out:
|
||||||
|
runtime.run.return_value = {"outcome": "timeout", "execution_mode": "experimental",
|
||||||
|
"execution_status": "timed_out", "terminal_reason": "worker_wall_clock_limit"}
|
||||||
|
runtime.run.side_effect = None
|
||||||
|
else:
|
||||||
|
runtime.run.side_effect = lambda request, cancel_event: original(request, cancel_event=cancel_event) | {
|
||||||
|
"requires_realtime_wait": True, "model_elapsed_ms": 10000}
|
||||||
|
engine._battle_runtimes["experimental"] = runtime
|
||||||
|
engine.battles.request_builder = None
|
||||||
|
config = self.manager.get_config(identifier)
|
||||||
|
config["config"]["progression_policy"].update(enabled=True, battle_mode="experimental", reserve_ti=0)
|
||||||
|
self.job(identifier, self.manager.set_config(identifier, config["config"], config["revision"])["job"])
|
||||||
|
worker.schedule.next_poll = 0
|
||||||
|
return runtime
|
||||||
|
|
||||||
|
def tick(self, identifier, worker):
|
||||||
|
return self.job(identifier, worker.enqueue("__tick"))
|
||||||
|
|
||||||
|
def paths(self, start=0):
|
||||||
|
return ["/".join(url.rsplit("/", 2)[-2:]) for _, url, _ in fixtures.FakeClient.calls[start:]]
|
||||||
|
|
||||||
|
def interrupted_clock(self):
|
||||||
|
identifier, worker = self.connected()
|
||||||
|
runtime = self.battle(identifier, worker)
|
||||||
|
entered = threading.Event()
|
||||||
|
original = worker.engine.battles.wait_for_battle_clock
|
||||||
|
|
||||||
|
def computed_wait(record, request, result, data, started, cancel):
|
||||||
|
wait = cancel.wait
|
||||||
|
|
||||||
|
def clock_wait(timeout):
|
||||||
|
entered.set()
|
||||||
|
return wait(timeout)
|
||||||
|
|
||||||
|
with patch.object(cancel, "wait", side_effect=clock_wait):
|
||||||
|
return original(record, request, result, data, started, cancel)
|
||||||
|
|
||||||
|
with patch.object(worker.engine.battles, "wait_for_battle_clock", side_effect=computed_wait):
|
||||||
|
tick = worker.enqueue("__tick")
|
||||||
|
self.assertTrue(entered.wait(3), "Offline battle never entered the computed clock wait")
|
||||||
|
config = self.manager.get_config(identifier)
|
||||||
|
config["config"]["policy"]["keep_money"] += 1
|
||||||
|
changed = self.manager.set_config(identifier, config["config"], config["revision"])
|
||||||
|
self.job(identifier, tick)
|
||||||
|
self.job(identifier, changed["job"])
|
||||||
|
record = worker.engine.battle_journal.pending(worker.engine.snapshot)
|
||||||
|
self.assertTrue(worker.engine.battles.resumable_task_clock(record), record)
|
||||||
|
self.assertTrue(worker.engine._progression_cancel.is_set())
|
||||||
|
return identifier, worker, runtime, record
|
||||||
|
|
||||||
|
def ready(self, worker):
|
||||||
|
journal = worker.engine.battle_journal
|
||||||
|
record = journal.pending(worker.engine.snapshot)
|
||||||
|
journal.update(record, record["phase"], battle_ready_at=1)
|
||||||
|
worker.engine.last_pending_check = time.monotonic() - 121
|
||||||
|
worker.schedule.next_poll = math.inf
|
||||||
|
|
||||||
|
def test_config_cancelled_computed_clock_resumes_on_reconcile_without_new_start(self):
|
||||||
|
identifier, worker, runtime, record = self.interrupted_clock()
|
||||||
|
saved = deepcopy(record["battle_data"])
|
||||||
|
self.ready(worker)
|
||||||
|
before = len(fixtures.FakeClient.calls)
|
||||||
|
self.assertEqual(self.tick(identifier, worker)["result"]["kind"], "reconcile")
|
||||||
|
self.assertIsNone(worker.engine.battle_journal.pending(worker.engine.snapshot))
|
||||||
|
writes = [path for path in self.paths(before) if path != "masterService/masterQueryDetail"]
|
||||||
|
self.assertEqual(writes, ["taskService/taskCompleteStep"])
|
||||||
|
payload = next(payload for _, url, payload in fixtures.FakeClient.calls[before:]
|
||||||
|
if url.endswith("taskService/taskCompleteStep"))
|
||||||
|
self.assertEqual(payload["battleData"], saved)
|
||||||
|
self.assertEqual(runtime.run.call_count, 1)
|
||||||
|
self.assertEqual(self.paths().count("battleService/battleStart"), 1)
|
||||||
|
self.assertTrue(self.manager.status(identifier)["strategy_requested"])
|
||||||
|
self.assertTrue(worker.running)
|
||||||
|
|
||||||
|
def test_start_accepts_saved_computed_result_but_does_not_settle_inline(self):
|
||||||
|
identifier, worker, _, _ = self.interrupted_clock()
|
||||||
|
self.manager.submit(identifier, "stop")
|
||||||
|
before = len(fixtures.FakeClient.calls)
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "start"))
|
||||||
|
self.assertTrue(worker.running)
|
||||||
|
self.assertFalse(worker.engine.auto)
|
||||||
|
self.assertEqual(len(fixtures.FakeClient.calls), before)
|
||||||
|
self.assertEqual(self.manager.status(identifier)["strategy_state"], "recovering")
|
||||||
|
|
||||||
|
def test_computed_result_waits_for_deadline_and_manual_refresh_stays_read_only(self):
|
||||||
|
identifier, worker, runtime, _ = self.interrupted_clock()
|
||||||
|
journal = worker.engine.battle_journal
|
||||||
|
record = journal.pending(worker.engine.snapshot)
|
||||||
|
journal.update(record, record["phase"], battle_ready_at=time.time() + 3600)
|
||||||
|
worker.engine.last_pending_check = time.monotonic() - 121
|
||||||
|
worker.schedule.next_poll = math.inf
|
||||||
|
before = len(fixtures.FakeClient.calls)
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "refresh"))
|
||||||
|
self.assertTrue(all(path == "masterService/masterQueryDetail" for path in self.paths(before)))
|
||||||
|
self.assertIsNotNone(journal.pending(worker.engine.snapshot))
|
||||||
|
self.assertEqual(runtime.run.call_count, 1)
|
||||||
|
self.assertTrue(worker.running)
|
||||||
|
self.assertFalse(worker.engine.auto)
|
||||||
|
self.assertEqual(self.manager.status(identifier)["strategy_state"], "recovering")
|
||||||
|
|
||||||
|
def test_lost_resumed_settlement_reply_becomes_query_only_without_replay(self):
|
||||||
|
identifier, worker, runtime, _ = self.interrupted_clock()
|
||||||
|
self.ready(worker)
|
||||||
|
post = worker.engine.client.http.post
|
||||||
|
attempted = []
|
||||||
|
|
||||||
|
def lost_reply(url, *args, **kwargs):
|
||||||
|
if url.endswith("taskService/taskCompleteStep"):
|
||||||
|
attempted.append(url)
|
||||||
|
raise requests.ReadTimeout("offline lost settlement reply")
|
||||||
|
return post(url, *args, **kwargs)
|
||||||
|
|
||||||
|
with patch.object(worker.engine.client.http, "post", side_effect=lost_reply):
|
||||||
|
self.job(identifier, worker.enqueue("__tick"), status="failed")
|
||||||
|
record = worker.engine.battle_journal.pending(worker.engine.snapshot)
|
||||||
|
self.assertTrue(record["settlement_dispatched"])
|
||||||
|
self.assertFalse(worker.engine.battles.resumable_task_clock(record))
|
||||||
|
for _ in range(3):
|
||||||
|
self.now += 121
|
||||||
|
worker.engine.last_heartbeat = self.now
|
||||||
|
worker.engine.last_pending_check = time.monotonic() - 121
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertEqual(len(attempted), 1)
|
||||||
|
self.assertEqual(runtime.run.call_count, 1)
|
||||||
|
self.assertEqual(self.paths().count("battleService/battleStart"), 1)
|
||||||
|
self.assertFalse(worker.running)
|
||||||
|
self.assertTrue(worker.strategy_requested)
|
||||||
|
|
||||||
|
def test_manual_stop_keeps_computed_result_unsent_through_config_and_restart(self):
|
||||||
|
identifier, worker, _, _ = self.interrupted_clock()
|
||||||
|
self.manager.submit(identifier, "stop")
|
||||||
|
self.ready(worker)
|
||||||
|
journal_path = worker.engine.battle_journal.path
|
||||||
|
evidence = journal_path.read_bytes()
|
||||||
|
config = self.manager.get_config(identifier)
|
||||||
|
config["config"]["policy"]["keep_money"] += 1
|
||||||
|
self.job(identifier, self.manager.set_config(identifier, config["config"], config["revision"])["job"])
|
||||||
|
before = len(fixtures.FakeClient.calls)
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertEqual(journal_path.read_bytes(), evidence)
|
||||||
|
self.assertTrue(all(path == "masterService/masterQueryDetail" for path in self.paths(before)))
|
||||||
|
self.assertTrue(self.manager.status(identifier)["manual_stop"])
|
||||||
|
self.manager.close()
|
||||||
|
self.manager = WebManager(self.root, start_scheduler=False, login_factory=fixtures.FakeLogin)
|
||||||
|
self.addCleanup(self.manager.close)
|
||||||
|
self.idle(identifier)
|
||||||
|
self.assertTrue(self.manager.status(identifier)["manual_stop"])
|
||||||
|
self.assertEqual(journal_path.read_bytes(), evidence)
|
||||||
|
|
||||||
|
def test_stop_racing_authorized_reconcile_cancels_settlement_before_dispatch(self):
|
||||||
|
identifier, worker, _, _ = self.interrupted_clock()
|
||||||
|
self.ready(worker)
|
||||||
|
entered, release = threading.Event(), threading.Event()
|
||||||
|
poll = worker.engine.poll
|
||||||
|
journal_path = worker.engine.battle_journal.path
|
||||||
|
evidence = journal_path.read_bytes()
|
||||||
|
|
||||||
|
def held_poll(**kwargs):
|
||||||
|
self.assertFalse(worker.engine.auto)
|
||||||
|
self.assertIs(kwargs.get("resume_pending"), True)
|
||||||
|
entered.set()
|
||||||
|
self.assertTrue(release.wait(3))
|
||||||
|
return poll(**kwargs)
|
||||||
|
|
||||||
|
before = len(fixtures.FakeClient.calls)
|
||||||
|
with patch.object(worker.engine, "poll", side_effect=held_poll):
|
||||||
|
tick = worker.enqueue("__tick")
|
||||||
|
try:
|
||||||
|
self.assertTrue(entered.wait(3), self.manager.job(identifier, tick["id"]))
|
||||||
|
self.manager.submit(identifier, "stop")
|
||||||
|
finally:
|
||||||
|
release.set()
|
||||||
|
self.job(identifier, tick, status="cancelled")
|
||||||
|
self.assertEqual(len(fixtures.FakeClient.calls), before)
|
||||||
|
self.assertEqual(journal_path.read_bytes(), evidence)
|
||||||
|
self.assertFalse(worker.running)
|
||||||
|
self.assertTrue(self.manager.status(identifier)["manual_stop"])
|
||||||
|
|
||||||
|
def test_runtime_recovery_timeout_stays_blocked_after_single_local_retry(self):
|
||||||
|
identifier, worker = self.connected()
|
||||||
|
runtime = self.battle(identifier, worker, timed_out=True)
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
record = worker.engine.battle_journal.pending(worker.engine.snapshot)
|
||||||
|
self.assertEqual(record["execution_status"], "timed_out")
|
||||||
|
self.assertFalse(worker.engine.battles.resumable_task_clock(record))
|
||||||
|
self.assertNotIn("battle_data", record)
|
||||||
|
self.assertTrue(worker.engine.pending_battle_recovery()["resumable"])
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "start"))
|
||||||
|
worker.engine.last_pending_check = time.monotonic() - 121
|
||||||
|
worker.schedule.next_poll = math.inf
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
record = worker.engine.battle_journal.pending(worker.engine.snapshot)
|
||||||
|
self.assertEqual(record["runtime_recovery_attempts"], 1)
|
||||||
|
self.assertFalse(worker.engine.pending_battle_recovery()["resumable"])
|
||||||
|
evidence = worker.engine.battle_journal.path.read_bytes()
|
||||||
|
before = len(fixtures.FakeClient.calls)
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "start"), status="failed")
|
||||||
|
for _ in range(3):
|
||||||
|
self.now += 121
|
||||||
|
worker.engine.last_heartbeat = self.now
|
||||||
|
worker.engine.last_pending_check = time.monotonic() - 121
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertTrue(all(path == "masterService/masterQueryDetail" for path in self.paths(before)))
|
||||||
|
self.assertEqual(worker.engine.battle_journal.path.read_bytes(), evidence)
|
||||||
|
self.assertEqual(runtime.run.call_count, 2)
|
||||||
|
self.assertEqual(self.paths().count("battleService/battleStart"), 1)
|
||||||
|
state = self.manager.status(identifier)
|
||||||
|
self.assertFalse(state["running"])
|
||||||
|
self.assertTrue(state["strategy_requested"])
|
||||||
|
self.assertFalse(state["manual_stop"])
|
||||||
|
self.assertIn("本地战斗计算超时", state["strategy_message"])
|
||||||
|
self.assertIn("尚未提交结算", state["strategy_message"])
|
||||||
|
|
||||||
|
def test_stage_farming_timeout_reports_its_operation_without_promising_resolution(self):
|
||||||
|
identifier, worker = self.connected()
|
||||||
|
fixtures.ServiceTests.enable(self, identifier)
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "start"))
|
||||||
|
journal = worker.engine.battle_journal
|
||||||
|
record = journal.begin(worker.engine.snapshot, {"kind": "stage_battle", "stage_id": "0102",
|
||||||
|
"difficulty": 1, "path": "stageService/stageStart", "task_id": 0})
|
||||||
|
journal.update(record, "unknown", start_response={"resCode": 0, "triggerEvent": False, "stageEvent": None},
|
||||||
|
execution_status="timed_out", terminal_reason="worker_wall_clock_limit",
|
||||||
|
message="战斗已取消、超时或结果不确定,等待核对")
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
state = self.manager.status(identifier)
|
||||||
|
self.assertTrue(state["connected"])
|
||||||
|
self.assertFalse(state["running"])
|
||||||
|
self.assertIn("0102", state["strategy_message"])
|
||||||
|
self.assertIn("本地战斗计算超时", state["strategy_message"])
|
||||||
|
worker.schedule.monitor(False)
|
||||||
|
reason = worker._pending_execution_reason()
|
||||||
|
self.assertNotIn("后台继续", reason)
|
||||||
|
self.assertNotIn("自动恢复", reason)
|
||||||
|
config = self.manager.get_config(identifier)
|
||||||
|
config["config"]["policy"]["keep_money"] += 1
|
||||||
|
self.job(identifier, self.manager.set_config(identifier, config["config"], config["revision"])["job"])
|
||||||
|
self.assertEqual(worker.config["policy"]["keep_money"], config["config"]["policy"]["keep_money"])
|
||||||
|
self.assertTrue(worker.strategy_requested)
|
||||||
|
intent = json.loads((worker.profile_root / "run_intent.json").read_text(encoding="utf-8"))
|
||||||
|
self.assertTrue(intent["roles"][worker.active_identity])
|
||||||
|
|
||||||
|
def test_config_cancellation_before_start_dispatch_replans_without_unknown_barrier(self):
|
||||||
|
identifier, worker = self.connected()
|
||||||
|
runtime = self.battle(identifier, worker, timed_out=True)
|
||||||
|
update = worker.engine.battle_journal.update
|
||||||
|
changed = []
|
||||||
|
|
||||||
|
def cancel_before_send(record, phase, **fields):
|
||||||
|
update(record, phase, **fields)
|
||||||
|
if phase == "start_pending":
|
||||||
|
config = self.manager.get_config(identifier)
|
||||||
|
config["config"]["policy"]["keep_money"] += 1
|
||||||
|
changed.append(self.manager.set_config(identifier, config["config"], config["revision"])["job"])
|
||||||
|
|
||||||
|
with patch.object(worker.engine.battle_journal, "update", side_effect=cancel_before_send):
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.job(identifier, changed[0])
|
||||||
|
self.assertNotIn("battleService/battleStart", self.paths())
|
||||||
|
self.assertFalse(worker.engine._progression_pending())
|
||||||
|
self.assertIsNone(worker.engine.battle_journal.pending(worker.engine.snapshot))
|
||||||
|
self.assertIsNone(worker.engine.progression_planner.pending(worker.engine.snapshot))
|
||||||
|
runtime.run.assert_not_called()
|
||||||
|
self.assertTrue(worker.running)
|
||||||
|
self.assertTrue(worker.strategy_requested)
|
||||||
|
worker.schedule.next_poll = 0
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertEqual(self.paths().count("battleService/battleStart"), 1)
|
||||||
|
|
||||||
|
def test_internal_pending_pause_does_not_revoke_generation_or_persist_manual_stop(self):
|
||||||
|
identifier, worker = self.connected()
|
||||||
|
worker.schedule.next_poll = 0
|
||||||
|
generation = worker._generation
|
||||||
|
|
||||||
|
def paused(**kwargs):
|
||||||
|
journal = worker.engine.battle_journal
|
||||||
|
record = journal.begin(worker.engine.snapshot, {"kind": "stage_battle", "stage_id": "0102"})
|
||||||
|
journal.update(record, "unknown", message="请求结果未知")
|
||||||
|
worker.engine.auto = False
|
||||||
|
return worker.engine.snapshot, [], "请求结果未知"
|
||||||
|
|
||||||
|
with patch.object(worker.engine, "poll", side_effect=paused):
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertEqual(worker._generation, generation)
|
||||||
|
self.assertTrue(worker.strategy_requested)
|
||||||
|
self.assertFalse(self.manager.status(identifier)["manual_stop"])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
"""Public account summaries preserve execution intent without private recovery data."""
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from ranch_web.tests import test_api as fixtures
|
||||||
|
|
||||||
|
|
||||||
|
class RecoveryStatusApiTests(unittest.TestCase):
|
||||||
|
setUp = fixtures.ApiTests.setUp
|
||||||
|
|
||||||
|
def test_accounts_and_status_preserve_blocked_intent_and_explicit_stop(self):
|
||||||
|
source = self.manager.accounts[self.account_id]
|
||||||
|
fields = {"strategy_requested": True, "manual_stop": False, "strategy_state": "blocked",
|
||||||
|
"strategy_message": "本地战斗计算超时,尚未提交结算", "strategy_retry_at": None}
|
||||||
|
source.update(fields, running=False, journal={"payload": "PRIVATE_RECOVERY"})
|
||||||
|
for values in (fields, fields | {"strategy_requested": False, "manual_stop": True,
|
||||||
|
"strategy_state": "stopped", "strategy_message": "已按用户选择停止策略"}):
|
||||||
|
source.update(values)
|
||||||
|
for url in ("/api/accounts", self.url + "/status"):
|
||||||
|
with self.subTest(url=url, state=values["strategy_state"]):
|
||||||
|
response = self.client.get(url)
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
body = response.json()
|
||||||
|
summary = body[0] if isinstance(body, list) else body
|
||||||
|
for field, expected in values.items():
|
||||||
|
self.assertEqual(summary.get(field), expected, field)
|
||||||
|
self.assertFalse(summary["running"])
|
||||||
|
self.assertNotIn("journal", summary)
|
||||||
|
self.assertNotIn("PRIVATE_RECOVERY", response.text)
|
||||||
|
|
||||||
|
def test_strategy_message_uses_the_connection_error_redactor(self):
|
||||||
|
source = self.manager.accounts[self.account_id]
|
||||||
|
for message in ("本地计算失败 token=STATUS_PRIVATE C:/private/battle.json", "Traceback: STATUS_PRIVATE"):
|
||||||
|
source.update(strategy_message=message, connection_message=message)
|
||||||
|
response = self.client.get(self.url + "/status")
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
body = response.json()
|
||||||
|
self.assertIsInstance(body.get("strategy_message"), str)
|
||||||
|
self.assertEqual(body["strategy_message"], body["connection_message"])
|
||||||
|
self.assertNotIn("STATUS_PRIVATE", response.text)
|
||||||
|
self.assertNotIn("C:/private", response.text)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -790,14 +790,15 @@ class FreshProcessIntegrationTests(unittest.TestCase):
|
|||||||
|
|
||||||
def test_real_engine_battle_worker_subprocess_still_runs_after_web_imports(self):
|
def test_real_engine_battle_worker_subprocess_still_runs_after_web_imports(self):
|
||||||
result = self.child('''
|
result = self.child('''
|
||||||
import json, tempfile
|
import json, sys, tempfile
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
import subprocess
|
import subprocess
|
||||||
from ranch_web.app import create_app
|
from ranch_web.app import create_app
|
||||||
from ranch_web.service import WebManager
|
from ranch_web.service import WebManager
|
||||||
from ranch_web.tests.test_web_integration import NoExternalSockets, real_engine_factory
|
from ranch_web.tests.test_web_integration import NoExternalSockets, real_engine_factory
|
||||||
from ranch_assistant.battle_simulator import combat_tables, simulate
|
from ranch_assistant.battle_simulator import combat_tables
|
||||||
|
from ranch_assistant.battle_quick import simulate_quick
|
||||||
row = combat_tables()['monster_info']['1001010']
|
row = combat_tables()['monster_info']['1001010']
|
||||||
mon = {'id': 101, 'typeId': 1001010, 'level': 20, 'mode': 2, 'tpLevel': 0, 'feel': 0, 'upStar': 0, 'pAtk': 0, 'pDef': 0, 'pHp': 0, 'pDex': 0}
|
mon = {'id': 101, 'typeId': 1001010, 'level': 20, 'mode': 2, 'tpLevel': 0, 'feel': 0, 'upStar': 0, 'pAtk': 0, 'pDef': 0, 'pHp': 0, 'pDex': 0}
|
||||||
for name in ('Atk', 'Def', 'Hp', 'Dex'):
|
for name in ('Atk', 'Def', 'Hp', 'Dex'):
|
||||||
@@ -819,15 +820,20 @@ class FreshProcessIntegrationTests(unittest.TestCase):
|
|||||||
result = engine.battles.runtime.run(request, timeout=15)
|
result = engine.battles.runtime.run(request, timeout=15)
|
||||||
assert launch.call_count == 1
|
assert launch.call_count == 1
|
||||||
assert 'ranch_assistant.battle_simulator' in launch.call_args.args[0]
|
assert 'ranch_assistant.battle_simulator' in launch.call_args.args[0]
|
||||||
assert result == simulate(request), result
|
expected = simulate_quick(request)
|
||||||
|
assert {k: v for k, v in result.items() if k != 'wall_time_ms'} == {
|
||||||
|
k: v for k, v in expected.items() if k != 'wall_time_ms'}, result
|
||||||
|
assert result['simulation_method'] == 'aggregate_hp_dps', result
|
||||||
assert result['outcome'] == 'win', result
|
assert result['outcome'] == 'win', result
|
||||||
|
assert not any(n.startswith('PySide6') or n == 'ranch_assistant.gui' or n.endswith('_gui') for n in sys.modules)
|
||||||
assert not network.attempts
|
assert not network.attempts
|
||||||
print(json.dumps({'outcome': result['outcome'], 'execution_mode': result['execution_mode'], 'real_worker_processes': launch.call_count}))
|
print(json.dumps({'outcome': result['outcome'], 'execution_mode': result['execution_mode'], 'simulation_method': result['simulation_method'], 'real_worker_processes': launch.call_count}))
|
||||||
finally:
|
finally:
|
||||||
manager.close()
|
manager.close()
|
||||||
''')
|
''')
|
||||||
self.assertEqual(result["real_worker_processes"], 1)
|
self.assertEqual(result["real_worker_processes"], 1)
|
||||||
self.assertEqual(result["outcome"], "win")
|
self.assertEqual(result["outcome"], "win")
|
||||||
|
self.assertEqual(result["simulation_method"], "aggregate_hp_dps")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
+146
-18
@@ -13,6 +13,7 @@ from ranch_assistant.drop_statistics import analyze
|
|||||||
from ranch_assistant.presentation import monster_rows
|
from ranch_assistant.presentation import monster_rows
|
||||||
from ranch_assistant.battle_messages import battle_message
|
from ranch_assistant.battle_messages import battle_message
|
||||||
from ranch_assistant.resource_stages import available_item_count, item_requirements, with_resource_data
|
from ranch_assistant.resource_stages import available_item_count, item_requirements, with_resource_data
|
||||||
|
from ranch_assistant.quests import commission_priority, commission_selection, commission_reason_kind
|
||||||
from .policies import default_config, validate_config
|
from .policies import default_config, validate_config
|
||||||
|
|
||||||
|
|
||||||
@@ -126,7 +127,10 @@ def build_view(engine, page, config, query=None):
|
|||||||
"form": [field | {"value": _value(config, field["path"])} for field in fields],
|
"form": [field | {"value": _value(config, field["path"])} for field in fields],
|
||||||
"filters": [], "details": {}, "actions": [{"operation": "refresh", "label": "刷新本页", "payload": {"page": page}}]}
|
"filters": [], "details": {}, "actions": [{"operation": "refresh", "label": "刷新本页", "payload": {"page": page}}]}
|
||||||
builder = _BUILDERS.get(page)
|
builder = _BUILDERS.get(page)
|
||||||
if engine.snapshot is None and page not in ("login", "yields", "statistics"):
|
if page == "commissions":
|
||||||
|
dto["tabs"] = [{"key": "current", "title": "当前委托"}, {"key": "history", "title": "每日记录"}]
|
||||||
|
local_history = page == "commissions" and (query or {}).get("tab") == "history"
|
||||||
|
if engine.snapshot is None and page not in ("login", "yields", "statistics") and not local_history:
|
||||||
dto["summary"] = "请先登录或打开离线演示"
|
dto["summary"] = "请先登录或打开离线演示"
|
||||||
return dto
|
return dto
|
||||||
if builder is not None:
|
if builder is not None:
|
||||||
@@ -451,15 +455,16 @@ def _gifts(dto, engine, config, query):
|
|||||||
|
|
||||||
CATEGORIES = {"mainline": "主线", "sidequest": "支线", "commission": "委托", "event": "活动(暂不自动)", "bond": "羁绊(暂不自动)", "unknown": "其他 / 未知"}
|
CATEGORIES = {"mainline": "主线", "sidequest": "支线", "commission": "委托", "event": "活动(暂不自动)", "bond": "羁绊(暂不自动)", "unknown": "其他 / 未知"}
|
||||||
BATTLE_KINDS = {"mainline": "主线战斗", "sidequest": "支线战斗", "commission": "委托战斗", "battle": "普通战斗", "map_battle": "地图战斗",
|
BATTLE_KINDS = {"mainline": "主线战斗", "sidequest": "支线战斗", "commission": "委托战斗", "battle": "普通战斗", "map_battle": "地图战斗",
|
||||||
"sweep": "扫荡", "map_reward_event": "地图奖励事件", "ordinary_stage": "普通关卡战斗", "resource_stage": "资源关卡战斗", "task_battle": "任务战斗", "task_pass_stage": "任务通关战斗", "unknown": "其他 / 未知"}
|
"sweep": "扫荡", "hidden": "隐藏关卡战斗", "map_reward_event": "地图奖励事件", "ordinary_stage": "普通关卡战斗", "resource_stage": "资源关卡战斗", "task_battle": "任务战斗", "task_pass_stage": "任务通关战斗", "unknown": "其他 / 未知"}
|
||||||
BATTLE_ALIASES = {"task": "task_battle", "passStage": "task_pass_stage", "event": "map_reward_event", "reward_event": "map_reward_event", "normal": "battle"}
|
BATTLE_ALIASES = {"task": "task_battle", "passStage": "task_pass_stage", "event": "map_reward_event", "reward_event": "map_reward_event", "normal": "battle", "map_sweep": "sweep"}
|
||||||
STATES = {"available": "可接取", "unaccepted": "未接取", "active": "进行中", "in_progress": "进行中", "ready": "待交付", "completed": "已完成", "complete": "已完成",
|
STATES = {"available": "可接取", "unaccepted": "未接取", "active": "进行中", "in_progress": "进行中", "ready": "待交付", "completed": "已完成", "complete": "已完成",
|
||||||
"claimed": "已领奖", "received": "进行中", "unlocked": "已解锁 / 待接取", "offered": "待接取", "locked": "未解锁", "finished": "已完成", "ready_to_reward": "待领取任务奖励",
|
"claimed": "已领奖", "received": "进行中", "unlocked": "已解锁 / 待接取", "offered": "待接取", "locked": "未解锁", "finished": "已完成", "ready_to_reward": "待领取任务奖励",
|
||||||
"blocked": "受阻", "unsupported": "暂不支持", "unknown": "未知"}
|
"blocked": "受阻", "unsupported": "暂不支持", "unknown": "未知"}
|
||||||
STATE_ALIASES = {"active": "received", "in_progress": "received", "available": "unlocked", "unaccepted": "unlocked", "offered": "unlocked", "ready": "ready_to_reward",
|
STATE_ALIASES = {"active": "received", "in_progress": "received", "available": "unlocked", "unaccepted": "unlocked", "offered": "unlocked", "ready": "ready_to_reward",
|
||||||
"completed": "finished", "complete": "finished", "claimed": "finished", "blocked": "received"}
|
"completed": "finished", "complete": "finished", "claimed": "finished", "blocked": "received"}
|
||||||
STATE_FILTERS = [("current", "当前(进行中 + 待接取 + 待领奖)"), ("received", "进行中"), ("unlocked", "待接取"), ("ready_to_reward", "待领奖"), ("finished", "已完成"), ("locked", "未解锁"), ("", "全部状态")]
|
STATE_FILTERS = [("current", "当前(进行中 + 待接取 + 待领奖)"), ("received", "进行中"), ("unlocked", "待接取"), ("ready_to_reward", "待领奖"), ("finished", "已完成"), ("locked", "未解锁"), ("", "全部状态")]
|
||||||
OUTCOMES = {"win": "胜利", "loss": "打不过", "unsupported": "暂不支持", "event": "地图奖励事件", "completed": "已完成", "cancelled": "已取消", "timeout": "超时", "unknown": "结果待核对"}
|
OUTCOMES = {"win": "胜利", "loss": "打不过", "unsupported": "暂不支持", "event": "地图奖励事件", "completed": "已完成", "cancelled": "已取消", "abandoned": "已放弃(本地计算失败)", "timeout": "超时", "unknown": "结果待核对",
|
||||||
|
"abandoned_missing_hidden_id": "未完成,已放弃", "abandoned_unsettled_sweep": "未完成,已放弃", "cancelled_unsent_sweep": "未完成,已取消"}
|
||||||
CHINA_TIME = timezone(timedelta(hours=8))
|
CHINA_TIME = timezone(timedelta(hours=8))
|
||||||
|
|
||||||
|
|
||||||
@@ -474,6 +479,26 @@ def _category(value):
|
|||||||
return value if value in CATEGORIES else "unknown"
|
return value if value in CATEGORIES else "unknown"
|
||||||
|
|
||||||
|
|
||||||
|
def _task_diagnostic_reason(reason):
|
||||||
|
# Keep concrete mechanism names visible while presenting Chinese reasons.
|
||||||
|
text = str(reason or "")
|
||||||
|
import re
|
||||||
|
labels = {"monMaker": "生成魔物", "monSteps": "脚本行动", "skill": "脚本技能", "monDead": "魔物死亡事件"}
|
||||||
|
for source, label in (("Unsupported monster controller", "当前模型尚未支持的魔物行为"),
|
||||||
|
("Unsupported battle controller", "当前模型尚未支持的战斗机制"),
|
||||||
|
("Unsupported battle triggers", "当前模型尚未支持的战斗触发事件")):
|
||||||
|
text = re.sub(re.escape(source) + r":\s*([^;;\n]+)",
|
||||||
|
lambda match: label + ":" + "、".join(labels.get(k.strip(), k.strip()) for k in match[1].split(",")), text)
|
||||||
|
text = text.replace("+15overpoten", "潜能字段(+15overpoten)尚未兼容")
|
||||||
|
return battle_message(text)
|
||||||
|
|
||||||
|
|
||||||
|
REASON_KINDS = {"ready": "条件齐备", "city_locked": "城市未解锁", "prerequisite": "前置条件", "quota": "次数用尽",
|
||||||
|
"offline": "账号离线", "busy": "当前占用", "cooldown": "等待时间", "temp_resource": "资源暂缺",
|
||||||
|
"protection": "保护限制", "model_unsupported": "模型尚未支持", "policy": "策略限制",
|
||||||
|
"uncertain_write": "请求待核对", "priority": "奖励排序"}
|
||||||
|
|
||||||
|
|
||||||
def _mainline(dto, engine, config, query):
|
def _mainline(dto, engine, config, query):
|
||||||
selected, state = str(query.get("category", "mainline")), str(query.get("state", "current"))
|
selected, state = str(query.get("category", "mainline")), str(query.get("state", "current"))
|
||||||
dto["filters"] = [_filter("category", "任务类别", selected, [("", "全部类别"), *CATEGORIES.items()]),
|
dto["filters"] = [_filter("category", "任务类别", selected, [("", "全部类别"), *CATEGORIES.items()]),
|
||||||
@@ -488,7 +513,8 @@ def _mainline(dto, engine, config, query):
|
|||||||
lifecycle = STATE_ALIASES.get(raw_state, raw_state)
|
lifecycle = STATE_ALIASES.get(raw_state, raw_state)
|
||||||
if selected and category != selected or state == "current" and lifecycle not in ("received", "unlocked", "ready_to_reward") or state not in ("", "current") and lifecycle != state:
|
if selected and category != selected or state == "current" and lifecycle not in ("received", "unlocked", "ready_to_reward") or state not in ("", "current") and lifecycle != state:
|
||||||
continue
|
continue
|
||||||
reason = battle_message(source.get("blocked_reason") or source.get("block_reason") or source.get("reason") or "")
|
raw_reason = source.get("blocked_reason") or source.get("block_reason") or source.get("reason") or ""
|
||||||
|
reason = _task_diagnostic_reason(raw_reason)
|
||||||
support = "受阻:" + reason if reason else "已支持" if source.get("supported") is True else "暂不支持" if source.get("supported") is False else "支持状态未确认"
|
support = "受阻:" + reason if reason else "已支持" if source.get("supported") is True else "暂不支持" if source.get("supported") is False else "支持状态未确认"
|
||||||
battle = _text(source.get("battle_kind"), "未确认")
|
battle = _text(source.get("battle_kind"), "未确认")
|
||||||
battle = BATTLE_ALIASES.get(battle, battle)
|
battle = BATTLE_ALIASES.get(battle, battle)
|
||||||
@@ -496,11 +522,15 @@ def _mainline(dto, engine, config, query):
|
|||||||
"category_label": CATEGORIES[category], "name": _text(source.get("name")), "state": raw_state, "lifecycle_state": lifecycle,
|
"category_label": CATEGORIES[category], "name": _text(source.get("name")), "state": raw_state, "lifecycle_state": lifecycle,
|
||||||
"state_label": STATES.get(raw_state, raw_state), "step": _text(source.get("step_number")) + " / " + _text(source.get("total_steps")),
|
"state_label": STATES.get(raw_state, raw_state), "step": _text(source.get("step_number")) + " / " + _text(source.get("total_steps")),
|
||||||
"location": _text(source.get("location_text") or source.get("location") or source.get("position")), "requirement": _text(source.get("requirement")),
|
"location": _text(source.get("location_text") or source.get("location") or source.get("position")), "requirement": _text(source.get("requirement")),
|
||||||
"next_action": _text(source.get("next_action")), "battle": BATTLE_KINDS.get(battle, battle), "support": support}
|
"next_action": _task_diagnostic_reason(_text(source.get("next_action"))), "battle": BATTLE_KINDS.get(battle, battle), "support": support,
|
||||||
|
"reason_kind": source.get("reason_kind") or commission_reason_kind(raw_reason),
|
||||||
|
"resources": source.get("resources") or [], "progress_plan": source.get("progress_plan") or []}
|
||||||
detail = {"任务": row["name"], "类别": row["category_label"], "状态": row["state_label"], "步骤": row["step"],
|
detail = {"任务": row["name"], "类别": row["category_label"], "状态": row["state_label"], "步骤": row["step"],
|
||||||
"目标 / 位置": row["location"], "NPC": _text(source.get("npc_name")), "需求": row["requirement"],
|
"目标 / 位置": row["location"], "NPC": _text(source.get("npc_name")), "需求": row["requirement"],
|
||||||
"对话": _text(source.get("dialogue") or source.get("dialogue_text") or source.get("dialogue_status"), "当前未提供对话内容"),
|
"对话": _text(source.get("dialogue") or source.get("dialogue_text") or source.get("dialogue_status"), "当前未提供对话内容"),
|
||||||
"下一步": row["next_action"], "战斗": row["battle"], "运行状态": _text(source.get("status"), row["state_label"]), "支持状态 / 阻塞原因": support}
|
"下一步": row["next_action"], "战斗": row["battle"], "运行状态": _text(source.get("status"), row["state_label"]), "支持状态 / 阻塞原因": support,
|
||||||
|
"原因类型": REASON_KINDS.get(row["reason_kind"], "条件待核对"), "资源需求与可用量": row["resources"],
|
||||||
|
"补齐计划": ";".join(row["progress_plan"])}
|
||||||
if search and search not in " ".join(map(str, [*row.values(), *detail.values()])).casefold():
|
if search and search not in " ".join(map(str, [*row.values(), *detail.values()])).casefold():
|
||||||
continue
|
continue
|
||||||
dto["rows"].append(row)
|
dto["rows"].append(row)
|
||||||
@@ -525,7 +555,7 @@ def _battles(dto, engine, config, query):
|
|||||||
kind = "map_reward_event"
|
kind = "map_reward_event"
|
||||||
elif source.get("task_id") and kind == "battle":
|
elif source.get("task_id") and kind == "battle":
|
||||||
kind = "task_battle"
|
kind = "task_battle"
|
||||||
elif source.get("kind") == "sweep":
|
elif source.get("kind") in ("sweep", "map_sweep") and kind != "hidden":
|
||||||
kind = "sweep"
|
kind = "sweep"
|
||||||
if selected and selected != kind:
|
if selected and selected != kind:
|
||||||
continue
|
continue
|
||||||
@@ -562,33 +592,131 @@ def _battles(dto, engine, config, query):
|
|||||||
dto["actions"] = [{"operation": "refresh_tasks", "label": "刷新战斗记录", "payload": {}}]
|
dto["actions"] = [{"operation": "refresh_tasks", "label": "刷新战斗记录", "payload": {}}]
|
||||||
|
|
||||||
|
|
||||||
|
COMMISSION_STATES = {"accepted": "已接取", "active": "进行中", "in_progress": "进行中", "completed": "已完成", "pending": "等待核对",
|
||||||
|
"claimed": "已领奖", "confirmed": "已确认", "unknown": "结果待核对", "failed": "失败", "cancelled": "已取消", "observed": "仅观察到任务", "blocked": "等待条件"}
|
||||||
|
COMMISSION_EVENTS = {"accept": "接取", "step": "推进步骤", "claim": "领取奖励", "complete": "领取奖励", "dialogue": "对话", "battle": "战斗",
|
||||||
|
"navigate": "前往任务地点", "farm": "收集委托材料", "local_step": "步骤收尾", "reset": "刷新每日委托",
|
||||||
|
"handin": "交付", "handin_items": "提交道具", "handin_monsters": "提交魔物", "handin_money": "提交金币",
|
||||||
|
"quest_accept": "接取", "quest_step": "推进步骤", "quest_complete": "领取奖励", "observe": "观察到任务"}
|
||||||
|
|
||||||
|
|
||||||
|
def _commission_time(value):
|
||||||
|
if value is None or value == "":
|
||||||
|
return "—"
|
||||||
|
try:
|
||||||
|
if type(value) in (int, float):
|
||||||
|
stamp = datetime.fromtimestamp(value / 1000 if value >= 1e12 else value, CHINA_TIME)
|
||||||
|
elif isinstance(value, str):
|
||||||
|
stamp = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||||
|
if stamp.tzinfo is None:
|
||||||
|
stamp = stamp.replace(tzinfo=CHINA_TIME)
|
||||||
|
else:
|
||||||
|
return "—"
|
||||||
|
return stamp.astimezone(CHINA_TIME).strftime("%Y-%m-%d %H:%M:%S")
|
||||||
|
except (ValueError, OverflowError, OSError):
|
||||||
|
return "时间未确认"
|
||||||
|
|
||||||
|
|
||||||
|
def _commission_history(dto, engine, query):
|
||||||
|
selected = query.get("date") or datetime.now(CHINA_TIME).date().isoformat()
|
||||||
|
try:
|
||||||
|
if not isinstance(selected, str) or datetime.strptime(selected, "%Y-%m-%d").date().isoformat() != selected:
|
||||||
|
raise ValueError
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
raise ValueError("记录日期须为 YYYY-MM-DD") from None
|
||||||
|
history = engine.commission_history(day=selected)
|
||||||
|
totals = history.get("summary") or {}
|
||||||
|
dto["form"] = []
|
||||||
|
dto["actions"] = [{"operation": "reload_view", "label": "刷新记录"}]
|
||||||
|
dto["filters"] = [_filter("date", "记录日期(北京时间)", selected, kind="date")]
|
||||||
|
search = _search(dto, query)
|
||||||
|
dto["columns"] = [_column(key, label) for key, label in (("name", "委托"), ("status_label", "状态"),
|
||||||
|
("expected_ke", "预计氪金"), ("confirmed_ke", "已确认氪金"), ("accepted_at", "接取时间(北京时间)"),
|
||||||
|
("completed_at", "完成时间(北京时间)"), ("last_action", "最近行动"))]
|
||||||
|
sources = history.get("rows") or []
|
||||||
|
for index, source in enumerate(sources):
|
||||||
|
status = _text(source.get("status"), "unknown")
|
||||||
|
row = {"id": _text(source.get("id"), str(index)), "task_type_id": _text(source.get("task_type_id")),
|
||||||
|
"name": _text(source.get("name")), "status_label": COMMISSION_STATES.get(status, "结果待核对"),
|
||||||
|
"expected_ke": source.get("expected_ke") if type(source.get("expected_ke")) in (int, float) else "未记录",
|
||||||
|
"confirmed_ke": source.get("confirmed_ke") if type(source.get("confirmed_ke")) in (int, float) else "未确认",
|
||||||
|
"accepted_at": _commission_time(source.get("accepted_at")), "completed_at": _commission_time(source.get("completed_at")),
|
||||||
|
"last_action": _text(source.get("last_action"), "暂无行动记录")}
|
||||||
|
events = []
|
||||||
|
for event in source.get("events") or []:
|
||||||
|
kind, outcome = _text(event.get("kind"), "unknown"), _text(event.get("status"), "unknown")
|
||||||
|
label = {"success": "已确认", "succeeded": "已确认", "confirmed": "已确认", "completed": "已确认",
|
||||||
|
"failed": "失败", "unknown": "结果待核对", "pending": "等待核对", "cancelled": "已取消"}.get(outcome, "结果待核对")
|
||||||
|
events.append(f"{_commission_time(event.get('time'))} · {COMMISSION_EVENTS.get(kind, '委托行动')} · {label} · {_text(event.get('description'))}")
|
||||||
|
detail = {"委托": row["name"], "任务编号": row["task_type_id"], "状态": row["status_label"],
|
||||||
|
"预计氪金": row["expected_ke"], "已确认氪金": row["confirmed_ke"], "接取时间(北京时间)": row["accepted_at"],
|
||||||
|
"完成时间(北京时间)": row["completed_at"], "选择 / 回退原因": _text(source.get("selection_reason"), "未记录"),
|
||||||
|
"行动记录": "\n".join(events) or "暂无行动记录"}
|
||||||
|
if search and search not in " ".join(map(str, [*row.values(), *detail.values()])).casefold():
|
||||||
|
continue
|
||||||
|
dto["rows"].append(row)
|
||||||
|
dto["details"][row["id"]] = detail
|
||||||
|
dto["summary"] = (f"{selected} · 已记录接取 {totals.get('accepted_count', 0)} · 已记录完成 {totals.get('completed_count', 0)}"
|
||||||
|
f" · 当日领奖确认氪金 {totals.get('confirmed_ke', 0)} · 当日接取标注氪金 {totals.get('expected_ke', 0)}"
|
||||||
|
f" · 操作待核对 {totals.get('pending_count', 0)} · 领奖金额未记录 {totals.get('unknown_reward_count', 0)}")
|
||||||
|
dto["summary"] += ";仅有本地已保存记录" if sources else ";当日暂无本地记录,历史接取与奖励未追溯"
|
||||||
|
if history.get("error"):
|
||||||
|
dto["summary"] += ";" + _text(history["error"])
|
||||||
|
|
||||||
|
|
||||||
def _commissions(dto, engine, config, query):
|
def _commissions(dto, engine, config, query):
|
||||||
|
if query.get("tab") == "history":
|
||||||
|
_commission_history(dto, engine, query)
|
||||||
|
return
|
||||||
snapshot, catalog = engine.snapshot, engine.catalog
|
snapshot, catalog = engine.snapshot, engine.catalog
|
||||||
search = _search(dto, query)
|
search = _search(dto, query)
|
||||||
dto["columns"] = [_column(key, label) for key, label in (("task_type_id", "编号"), ("name", "委托"), ("status", "状态"),
|
dto["columns"] = [_column(key, label) for key, label in (("task_type_id", "编号"), ("name", "委托"), ("city", "城市"), ("status", "状态"),
|
||||||
("reward_money", "金币奖励"), ("reward_ke", "氪金奖励"), ("reason", "需求 / 下一步 / 阻塞原因"))]
|
("reward_money", "标注金币"), ("reward_ke", "标注氪金"), ("reason_type", "原因类型"), ("selection_reason", "选择 / 回退原因"), ("reason", "需求 / 下一步 / 阻塞原因"))]
|
||||||
diagnostics = {str(row.get("task_type_id")): row for row in engine.progression_rows() if _category(row.get("category")) == "commission"}
|
diagnostics = {str(row.get("task_type_id")): row for row in engine.progression_rows() if _category(row.get("category")) == "commission"}
|
||||||
source = engine.tasks.rows(snapshot, engine.quest_policy, engine.policy)
|
offer_rows = engine.commission_offer_diagnostics()
|
||||||
|
offers = {(str(row.get("task_type_id")), str(row.get("city"))): row for row in offer_rows}
|
||||||
|
selected = next((row for row in offer_rows if row.get("eligible") is True or row.get("preparable")), {})
|
||||||
|
selection = commission_selection({"reward": {"ke": selected.get("expected_ke", 0)}}, offer_rows,
|
||||||
|
[row for row in offer_rows if row.get("eligible") is False]) if selected else {}
|
||||||
|
source = sorted(engine.tasks.rows(snapshot, engine.quest_policy, engine.policy), key=lambda row: (
|
||||||
|
"city" in row[4], commission_priority(catalog.data.get("task_info", {}).get(str(row[0]), {}))))
|
||||||
for index, (key, name, status, text, meta) in enumerate(source):
|
for index, (key, name, status, text, meta) in enumerate(source):
|
||||||
diagnostic = diagnostics.get(str(key), {})
|
diagnostic = diagnostics.get(str(key), {})
|
||||||
reason = diagnostic.get("block_reason") or diagnostic.get("blocked_reason")
|
offer = offers.get((str(key), str(meta.get("city"))), {}) if "city" in meta else {}
|
||||||
|
if "city" in meta:
|
||||||
|
status = "可接取" if offer.get("eligible") is True else "候选 / 条件待核对"
|
||||||
|
reason = (offer.get("reason") if offer.get("eligible") is False else None) if offer else diagnostic.get("block_reason") or diagnostic.get("blocked_reason")
|
||||||
if reason:
|
if reason:
|
||||||
status = "暂不接取" if "city" in meta else "等待条件"
|
status = "补齐后接取" if offer.get("preparable") else "暂不接取" if "city" in meta else "等待条件"
|
||||||
text = reason
|
text = reason
|
||||||
elif diagnostic.get("next_action"):
|
elif not offer and diagnostic.get("next_action"):
|
||||||
text = diagnostic["next_action"]
|
text = diagnostic["next_action"]
|
||||||
info = catalog.data.get("task_info", {}).get(str(key), {})
|
info = catalog.data.get("task_info", {}).get(str(key), {})
|
||||||
reward = info.get("reward") or {}
|
reward = info.get("reward") or {}
|
||||||
|
reason_kind = offer.get("reason_kind") or diagnostic.get("reason_kind") or commission_reason_kind(reason)
|
||||||
|
if offer and offer != selected and offer.get("eligible"):
|
||||||
|
reason_kind = "priority"
|
||||||
|
text = f"当前优先处理《{selected.get('name')}》({selected.get('expected_ke')}氪金);本委托条件齐备,排队等待"
|
||||||
row = {"id": f"{key}:{index}", "task_type_id": str(key), "name": name, "status": status,
|
row = {"id": f"{key}:{index}", "task_type_id": str(key), "name": name, "status": status,
|
||||||
"reward_money": reward.get("money", 0), "reward_ke": reward.get("ke", 0), "reason": battle_message(text),
|
"reward_money": reward.get("money", 0), "reward_ke": reward.get("ke", 0), "reason": _task_diagnostic_reason(text),
|
||||||
"city": meta.get("city"), "active": "city" not in meta}
|
"city": offer.get("city_name") or meta.get("city"), "city_id": meta.get("city"), "active": "city" not in meta,
|
||||||
|
"reason_kind": reason_kind, "reason_type": REASON_KINDS.get(reason_kind, "条件待核对"),
|
||||||
|
"resources": offer.get("resources") or diagnostic.get("resources") or [],
|
||||||
|
"progress_plan": offer.get("progress_plan") or diagnostic.get("progress_plan") or [],
|
||||||
|
"next_step": _task_diagnostic_reason(offer.get("next_step") or diagnostic.get("next_action") or text),
|
||||||
|
"selection_reason": _text(offer.get("selection_reason") or (selection.get("selection_reason") if offer and offer == selected else None)
|
||||||
|
or diagnostic.get("selection_reason") or meta.get("selection_reason") or (reason if "city" in meta else None),
|
||||||
|
"较高氪金的可执行委托优先" if offer.get("eligible") is True else "接取条件待核对" if "city" in meta else "已接取,优先推进当前委托")}
|
||||||
if search and search not in " ".join(map(str, row.values())).casefold():
|
if search and search not in " ".join(map(str, row.values())).casefold():
|
||||||
continue
|
continue
|
||||||
dto["rows"].append(row)
|
dto["rows"].append(row)
|
||||||
dto["details"][row["id"]] = {"描述": info.get("des", ""), "需求 / 下一步": row["reason"],
|
dto["details"][row["id"]] = {"描述": info.get("des", ""), "标注奖励": reward_summary(catalog, reward),
|
||||||
|
"城市": _text(row["city"]), "城市解锁条件": offer.get("unlock_condition", ""),
|
||||||
|
"原因类型": row["reason_type"], "资源需求与可用量": row["resources"], "补齐计划": ";".join(row["progress_plan"]),
|
||||||
|
"下一步": row["next_step"], "选择 / 回退原因": row["selection_reason"], "需求 / 下一步": row["reason"],
|
||||||
"交付限制": {"允许物品": engine.quest_policy.allow_items, "允许魔物": engine.quest_policy.allow_monsters,
|
"交付限制": {"允许物品": engine.quest_policy.allow_items, "允许魔物": engine.quest_policy.allow_monsters,
|
||||||
"单次金币上限": engine.quest_policy.max_money, "允许已支持战斗": engine.quest_policy.battle_tasks},
|
"单次金币上限": engine.quest_policy.max_money, "允许已支持战斗": engine.quest_policy.battle_tasks},
|
||||||
"接取优先级": "氪金奖励较高的委托优先;仅接取原规划器确认可支持的委托"}
|
"接取优先级": "跨城市按标注氪金 20 → 15 → 10 优先;20 氪金均不可用时回退到可执行的 15 / 10 氪金委托"}
|
||||||
dto["summary"] = f"今日剩余可接次数:{snapshot.raw.get('history', {}).get('loopTaskNum', '未知')};当前委托:{len(engine.tasks.current(snapshot))}"
|
dto["summary"] = f"今日剩余可接次数:{snapshot.raw.get('history', {}).get('loopTaskNum', '未知')};当前委托:{len(engine.tasks.current(snapshot))}"
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,402 @@
|
|||||||
|
"""Bounded offline input coverage for the packaged mainline/commission corpus.
|
||||||
|
|
||||||
|
Source mechanics describe original configurations, not quick-model blockers.
|
||||||
|
No game client, account service, GUI, APK, or network is needed. Private
|
||||||
|
snapshots stay in memory; only counts and task-level model results are reported.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
from collections import Counter
|
||||||
|
from collections.abc import Mapping
|
||||||
|
from contextlib import redirect_stderr, redirect_stdout
|
||||||
|
from dataclasses import dataclass
|
||||||
|
import gzip
|
||||||
|
import hashlib
|
||||||
|
import importlib
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
import types
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
if str(ROOT) not in sys.path:
|
||||||
|
sys.path.insert(0, str(ROOT))
|
||||||
|
|
||||||
|
PRIORITY_TASK = "1002013"
|
||||||
|
DEFAULT_DAMAGE_PROFILE = "client_v4_x10"
|
||||||
|
DAMAGE_PROFILES = (DEFAULT_DAMAGE_PROFILE, "original_1x")
|
||||||
|
MAX_SNAPSHOT_BYTES = 16 * 1024 * 1024
|
||||||
|
MAX_RUNS = 5
|
||||||
|
TOP = 10
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Case:
|
||||||
|
task: str
|
||||||
|
task_type: int
|
||||||
|
step: int
|
||||||
|
step_type: str
|
||||||
|
battle: Mapping
|
||||||
|
|
||||||
|
def identity(self):
|
||||||
|
return {"task": self.task, "type": self.task_type, "step": self.step,
|
||||||
|
"step_type": self.step_type}
|
||||||
|
|
||||||
|
|
||||||
|
def collect_cases(data=None):
|
||||||
|
"""Resolve actual inline battles and one-based passStage references."""
|
||||||
|
if data is None:
|
||||||
|
from ranch_assistant.game_data import load_progression_data
|
||||||
|
data = load_progression_data()
|
||||||
|
stages = {}
|
||||||
|
cases = []
|
||||||
|
for task_id, task in sorted(data.tasks.items()):
|
||||||
|
if task.get("type") not in (1, 4):
|
||||||
|
continue
|
||||||
|
for number, step in enumerate(task.get("steps") or (), 1):
|
||||||
|
kind = step.get("statusType")
|
||||||
|
if kind not in ("battle", "passStage"):
|
||||||
|
continue
|
||||||
|
if kind == "passStage":
|
||||||
|
value = step.get("statusValue") or {}
|
||||||
|
key = (str(value["stage"]), str(value.get("level", 1)))
|
||||||
|
if key not in stages:
|
||||||
|
stages[key] = data.task_battle(task_id, number)
|
||||||
|
battle = stages[key]
|
||||||
|
else:
|
||||||
|
battle = data.task_battle(task_id, number)
|
||||||
|
cases.append(Case(str(task_id), task["type"], number, kind, battle))
|
||||||
|
return cases
|
||||||
|
|
||||||
|
|
||||||
|
def _token(value):
|
||||||
|
value = str(value)
|
||||||
|
return value if re.fullmatch(r"[A-Za-z0-9_]{1,40}", value) else "unknown"
|
||||||
|
|
||||||
|
|
||||||
|
def mechanics(battle):
|
||||||
|
"""Count source occurrences; callers count affected configurations once."""
|
||||||
|
result = Counter()
|
||||||
|
if not isinstance(battle, Mapping):
|
||||||
|
result["missing_battle"] += 1
|
||||||
|
return result
|
||||||
|
for entry in battle.get("controller") or ():
|
||||||
|
result["controller:" + _token(entry.get("type"))] += 1
|
||||||
|
for entry in battle.get("triggers") or ():
|
||||||
|
result["trigger:" + _token(entry.get("type"))] += 1
|
||||||
|
for effect in entry.get("effects") or ():
|
||||||
|
result["trigger_effect:" + _token(effect.get("type"))] += 1
|
||||||
|
for team in battle.get("teams") or ():
|
||||||
|
for unit in team.get("mons") or ():
|
||||||
|
if not isinstance(unit, Mapping):
|
||||||
|
continue
|
||||||
|
for entry in unit.get("controller") or ():
|
||||||
|
result["unit_controller:" + _token(entry.get("type"))] += 1
|
||||||
|
for name in ("protectTarget", "destroyTarget"):
|
||||||
|
if unit.get(name):
|
||||||
|
result["objective:" + name] += 1
|
||||||
|
for kind in ("winType", "loseType"):
|
||||||
|
for value in battle.get(kind) or ():
|
||||||
|
if str(value) not in (("1",) if kind == "winType" else ("1", "2")):
|
||||||
|
result["objective:" + kind + ":" + _token(value)] += 1
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _rank(counts, limit=None):
|
||||||
|
rows = [{"reason": key, "count": count}
|
||||||
|
for key, count in sorted(counts.items(), key=lambda item: (-item[1], item[0]))]
|
||||||
|
return rows if limit is None else rows[:limit]
|
||||||
|
|
||||||
|
|
||||||
|
def source_scan(cases):
|
||||||
|
configurations, occurrences, kinds = Counter(), Counter(), Counter()
|
||||||
|
for case in cases:
|
||||||
|
features = mechanics(case.battle)
|
||||||
|
configurations.update(features.keys())
|
||||||
|
occurrences.update(features)
|
||||||
|
kinds[(case.task_type, case.step_type)] += 1
|
||||||
|
return {"count": len(cases),
|
||||||
|
"counts": [{"type": task_type, "step_type": kind, "count": count}
|
||||||
|
for (task_type, kind), count in sorted(kinds.items())],
|
||||||
|
"mechanics": _rank(configurations), "occurrences": _rank(occurrences)}
|
||||||
|
|
||||||
|
|
||||||
|
def fixture_roster(tables=None):
|
||||||
|
"""Same ordinary level-20 roster recipe as test_battle_simulator.request.
|
||||||
|
|
||||||
|
Only the roster is synthetic. Battle configurations are never modified.
|
||||||
|
"""
|
||||||
|
if tables is None:
|
||||||
|
directory = ROOT / "ranch_assistant" / "data"
|
||||||
|
manifest = json.loads((directory / "combat_manifest.json").read_text(encoding="utf-8"))
|
||||||
|
artifact = (directory / "combat_tables.json.gz").read_bytes()
|
||||||
|
meta = manifest["artifacts"]["combat_tables.json.gz"]
|
||||||
|
if hashlib.sha256(artifact).hexdigest() != meta["sha256"]:
|
||||||
|
raise ValueError("combat_data_integrity")
|
||||||
|
decoded = gzip.decompress(artifact)
|
||||||
|
if hashlib.sha256(decoded).hexdigest() != meta["decoded_sha256"]:
|
||||||
|
raise ValueError("combat_data_integrity")
|
||||||
|
tables = json.loads(decoded)
|
||||||
|
row = tables["monster_info"]["1001010"]
|
||||||
|
monster = {"id": 101, "typeId": 1001010, "level": 20, "mode": 2,
|
||||||
|
"tpLevel": 0, "feel": 0, "upStar": 0,
|
||||||
|
"pAtk": 0, "pDef": 0, "pHp": 0, "pDex": 0}
|
||||||
|
for name in ("Atk", "Def", "Hp", "Dex"):
|
||||||
|
stat = name.lower()
|
||||||
|
monster["g" + name] = (row[stat + "_grow_min"] + row[stat + "_grow_max"]) / 2
|
||||||
|
return {"master": {"level": 43}, "monsters": [monster],
|
||||||
|
"teams": [{"teamName": "teamA", "monsters": [101]}], "monsterAttributes": []}
|
||||||
|
|
||||||
|
|
||||||
|
def load_snapshot(path):
|
||||||
|
"""Read a raw snapshot (or {raw: snapshot}) without echoing input/errors."""
|
||||||
|
try:
|
||||||
|
with Path(path).open("rb") as stream:
|
||||||
|
content = stream.read(MAX_SNAPSHOT_BYTES + 1)
|
||||||
|
if len(content) > MAX_SNAPSHOT_BYTES:
|
||||||
|
raise ValueError
|
||||||
|
raw = json.loads(content.decode("utf-8-sig"))
|
||||||
|
if isinstance(raw, dict) and isinstance(raw.get("raw"), dict):
|
||||||
|
raw = raw["raw"]
|
||||||
|
if not isinstance(raw, dict) or not all(k in raw for k in ("master", "monsters", "teams")):
|
||||||
|
raise ValueError
|
||||||
|
if not isinstance(raw["master"], dict):
|
||||||
|
raise ValueError
|
||||||
|
# Drop credentials/account-envelope fields before any model call.
|
||||||
|
result = {k: raw[k] for k in ("monsters", "teams", "monsterAttributes") if k in raw}
|
||||||
|
result["master"] = {k: v for k, v in raw["master"].items()
|
||||||
|
if k in ("level", "globalAtk", "globalDef", "globalHp", "globalDex")}
|
||||||
|
return result
|
||||||
|
except (OSError, UnicodeError, ValueError, TypeError, RecursionError):
|
||||||
|
raise ValueError("snapshot_load_failed") from None
|
||||||
|
|
||||||
|
|
||||||
|
def make_request(case, roster, *, team="teamA", seed=0, damage_profile=DEFAULT_DAMAGE_PROFILE):
|
||||||
|
if damage_profile not in DAMAGE_PROFILES:
|
||||||
|
raise ValueError("invalid_damage_profile")
|
||||||
|
return {"context": "task_pass_stage" if case.step_type == "passStage" else "task_battle",
|
||||||
|
"original_data": {"battle": case.battle}, "roster": roster, "team": team,
|
||||||
|
"battle_position": {"battleType": "task", "taskTypeId": case.task, "taskStep": case.step - 1},
|
||||||
|
"seed": seed, "trace_limit": 0, "damage_profile": damage_profile}
|
||||||
|
|
||||||
|
|
||||||
|
def representative_cases(cases, limit=3, tasks=()):
|
||||||
|
"""Priority task, protection objective, then both commission input routes."""
|
||||||
|
if not 0 <= limit <= MAX_RUNS:
|
||||||
|
raise ValueError("run_limit")
|
||||||
|
selected = []
|
||||||
|
|
||||||
|
def take(predicate):
|
||||||
|
case = next((case for case in cases if predicate(case) and case not in selected), None)
|
||||||
|
if case is not None:
|
||||||
|
selected.append(case)
|
||||||
|
|
||||||
|
for task in dict.fromkeys((PRIORITY_TASK, *tasks)):
|
||||||
|
take(lambda case: case.task == task)
|
||||||
|
take(lambda case: "objective:protectTarget" in mechanics(case.battle))
|
||||||
|
for kind in ("battle", "passStage"):
|
||||||
|
take(lambda case: case.task_type == 4 and case.step_type == kind)
|
||||||
|
take(lambda case: case.task_type == 1 and case.step_type == "battle")
|
||||||
|
return selected[:limit]
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_counts(report):
|
||||||
|
counts = Counter()
|
||||||
|
for anomaly in report.get("anomalies") or ():
|
||||||
|
code = anomaly.get("code") if isinstance(anomaly, Mapping) else None
|
||||||
|
key = code if isinstance(code, str) and re.fullmatch(r"\+\d{1,3}over[a-z]{1,16}", code) else "detected"
|
||||||
|
counts["anomaly:" + key] += 1
|
||||||
|
return _rank(counts)
|
||||||
|
|
||||||
|
|
||||||
|
def _elapsed(value):
|
||||||
|
if isinstance(value, (float, int)) and not isinstance(value, bool) and math.isfinite(value) and value >= 0:
|
||||||
|
return round(value, 3)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def result_summary(report, *, public_reasons=()):
|
||||||
|
"""Strict report boundary: no units, IDs, stats, traces, or arbitrary text."""
|
||||||
|
allowed = set(public_reasons)
|
||||||
|
reasons = sorted({reason if isinstance(reason, str) and reason in allowed else "input_or_model_failure"
|
||||||
|
for reason in report.get("reasons") or ()})
|
||||||
|
outcome = report.get("outcome")
|
||||||
|
if outcome not in ("win", "loss", "timeout", "cancelled", "unsupported", "error", None):
|
||||||
|
outcome = "error"
|
||||||
|
terminal_reason = report.get("terminal_reason")
|
||||||
|
if outcome in ("unsupported", "error", "timeout", "cancelled") and terminal_reason in (
|
||||||
|
"invalid_numeric_battle_data", "model_execution_failure", "resource_limit", "wall_clock", "cancelled"):
|
||||||
|
reasons = sorted(set(reasons) | {terminal_reason})
|
||||||
|
return {"support": report.get("supported") is True, "reason": reasons,
|
||||||
|
"outcome": outcome, "counts": _safe_counts(report),
|
||||||
|
"elapsed_ms": _elapsed(report.get("elapsed_ms"))}
|
||||||
|
|
||||||
|
|
||||||
|
def inspect_inputs(cases, runtime, *, cancel_event=None, deadline=None,
|
||||||
|
damage_profile=DEFAULT_DAMAGE_PROFILE):
|
||||||
|
"""Inspect all source inputs with the fixture; never run all battles."""
|
||||||
|
started = time.monotonic()
|
||||||
|
roster = fixture_roster()
|
||||||
|
rows, counts, reasons = [], Counter(), Counter()
|
||||||
|
for case in cases:
|
||||||
|
if cancel_event is not None and cancel_event.is_set():
|
||||||
|
return {"rows": rows, "reason": ["cancelled"], "count": len(rows)}
|
||||||
|
if deadline is not None and time.monotonic() >= deadline:
|
||||||
|
return {"rows": rows, "reason": ["budget_exhausted"], "count": len(rows)}
|
||||||
|
report = runtime.inspect(make_request(case, roster, damage_profile=damage_profile))
|
||||||
|
# These messages depend only on pinned public data and the test fixture.
|
||||||
|
public = [s[:240] for s in report.get("reasons") or () if isinstance(s, str)][:32]
|
||||||
|
row = dict(case.identity(), **result_summary(report, public_reasons=public))
|
||||||
|
rows.append(row)
|
||||||
|
counts[(case.task_type, case.step_type, row["support"])] += 1
|
||||||
|
reasons.update(set(row["reason"]))
|
||||||
|
return {"count": len(rows), "reason": [], "rows": rows,
|
||||||
|
"priority": [row for row in rows if row["task"] == PRIORITY_TASK],
|
||||||
|
"counts": [{"type": typ, "step_type": kind, "support": support, "count": count}
|
||||||
|
for (typ, kind, support), count in sorted(counts.items())],
|
||||||
|
"unsupported_reasons": _rank(reasons),
|
||||||
|
"wall_ms": round((time.monotonic() - started) * 1000, 3)}
|
||||||
|
|
||||||
|
|
||||||
|
def replay_cases(cases, runtime, roster, *, team="teamA", timeout=1.0,
|
||||||
|
cancel_event=None, deadline=None, public_reasons=(),
|
||||||
|
damage_profile=DEFAULT_DAMAGE_PROFILE):
|
||||||
|
"""Run a bounded handful through the existing quick runtime, unchanged."""
|
||||||
|
if len(cases) > MAX_RUNS or not math.isfinite(timeout) or not 0 < timeout <= 2:
|
||||||
|
raise ValueError("invalid_resource_bounds")
|
||||||
|
rows = []
|
||||||
|
for case in cases:
|
||||||
|
if cancel_event is not None and cancel_event.is_set():
|
||||||
|
break
|
||||||
|
remaining = timeout if deadline is None else min(timeout, deadline - time.monotonic())
|
||||||
|
if remaining <= 0:
|
||||||
|
break
|
||||||
|
started = time.monotonic()
|
||||||
|
try:
|
||||||
|
# Never forward library output, even if a future model prints input.
|
||||||
|
with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):
|
||||||
|
report = runtime.run(make_request(case, roster, team=team, damage_profile=damage_profile),
|
||||||
|
timeout=remaining, cancel_event=cancel_event)
|
||||||
|
row = result_summary(report, public_reasons=public_reasons)
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
row = {"support": None, "outcome": "cancelled", "reason": ["cancelled"], "counts": []}
|
||||||
|
except Exception:
|
||||||
|
row = {"support": None, "outcome": "error", "reason": ["model_execution_failed"], "counts": []}
|
||||||
|
rows.append(dict(case.identity(), **row, wall_ms=round((time.monotonic() - started) * 1000, 3)))
|
||||||
|
if row["outcome"] == "cancelled":
|
||||||
|
break
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
def quick_runtime():
|
||||||
|
"""Use Fermat's public quick API exclusively, including for inspection."""
|
||||||
|
quick = importlib.import_module("ranch_assistant.battle_quick")
|
||||||
|
return types.SimpleNamespace(inspect=lambda request: quick.prepare(request)[1], run=quick.simulate_quick)
|
||||||
|
|
||||||
|
|
||||||
|
def head_runtime():
|
||||||
|
"""Inspect committed HEAD model source in memory over the same public corpus.
|
||||||
|
|
||||||
|
No checkout, archive, worktree, private path copy, or Git mutation occurs.
|
||||||
|
HEAD inspection is historical information; it never gates the quick model.
|
||||||
|
"""
|
||||||
|
source = subprocess.run(["git", "show", "HEAD:ranch_assistant/battle_simulator.py"],
|
||||||
|
cwd=ROOT, capture_output=True, check=True, timeout=3).stdout
|
||||||
|
module = types.ModuleType("ranch_assistant._progression_support_head")
|
||||||
|
module.__file__ = str(ROOT / "ranch_assistant" / "battle_simulator.py")
|
||||||
|
sys.modules[module.__name__] = module
|
||||||
|
try:
|
||||||
|
exec(compile(source, module.__file__, "exec"), module.__dict__)
|
||||||
|
return module.ExperimentalBattleRuntime()
|
||||||
|
except Exception:
|
||||||
|
sys.modules.pop(module.__name__, None)
|
||||||
|
raise ValueError("head_model_unavailable") from None
|
||||||
|
|
||||||
|
|
||||||
|
def _offline_audit(event, args):
|
||||||
|
if event.startswith("socket.") or event == "urllib.Request":
|
||||||
|
raise PermissionError("offline_only")
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv=None):
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("--structure-only", action="store_true", help="Source scan only; no model import or simulation")
|
||||||
|
parser.add_argument("--snapshot", type=Path, help="Private local raw snapshot; contents/path are never reported")
|
||||||
|
parser.add_argument("--team", default="teamA")
|
||||||
|
parser.add_argument("--damage-profile", choices=DAMAGE_PROFILES, default=DEFAULT_DAMAGE_PROFILE,
|
||||||
|
help="Default matches Web automation; original_1x is an explicit comparison")
|
||||||
|
parser.add_argument("--task", action="append", default=[])
|
||||||
|
parser.add_argument("--runs", type=int, default=3)
|
||||||
|
parser.add_argument("--timeout", type=float, default=1.0)
|
||||||
|
parser.add_argument("--budget", type=float, default=15.0)
|
||||||
|
parser.add_argument("--compare-head", action="store_true", help="Historical HEAD inspection only; no baseline simulations")
|
||||||
|
parser.add_argument("--output", type=Path, help="Full JSON report under ignored test-artifacts/")
|
||||||
|
args = parser.parse_args(argv)
|
||||||
|
started = time.monotonic()
|
||||||
|
report = {"reason": [], "damage_profile": args.damage_profile}
|
||||||
|
output = None
|
||||||
|
try:
|
||||||
|
if not 0 <= args.runs <= MAX_RUNS or not math.isfinite(args.timeout) or not 0 < args.timeout <= 2:
|
||||||
|
raise ValueError("invalid_resource_bounds")
|
||||||
|
if not math.isfinite(args.budget) or not 0 < args.budget <= 30:
|
||||||
|
raise ValueError("invalid_resource_bounds")
|
||||||
|
if args.output is not None:
|
||||||
|
destination = args.output.resolve()
|
||||||
|
if not destination.is_relative_to(ROOT / "test-artifacts") or args.snapshot and destination == args.snapshot.resolve():
|
||||||
|
raise ValueError("invalid_report_destination")
|
||||||
|
output = destination
|
||||||
|
cases = collect_cases()
|
||||||
|
report["source"] = source_scan(cases)
|
||||||
|
if not args.structure_only:
|
||||||
|
deadline = started + args.budget
|
||||||
|
stop = threading.Event()
|
||||||
|
runtime = quick_runtime()
|
||||||
|
report["quick_inputs"] = inspect_inputs(cases, runtime, deadline=deadline, cancel_event=stop,
|
||||||
|
damage_profile=args.damage_profile)
|
||||||
|
report["reason"].extend(report["quick_inputs"]["reason"])
|
||||||
|
if args.compare_head and not report["reason"]:
|
||||||
|
report["historical_head"] = inspect_inputs(cases, head_runtime(), deadline=deadline,
|
||||||
|
damage_profile=args.damage_profile)
|
||||||
|
report["reason"].extend(report["historical_head"]["reason"])
|
||||||
|
if not report["reason"] and args.runs:
|
||||||
|
if any(task not in {case.task for case in cases} for task in args.task):
|
||||||
|
raise ValueError("task_not_found")
|
||||||
|
selected = representative_cases(cases, args.runs, args.task)
|
||||||
|
roster = load_snapshot(args.snapshot) if args.snapshot else fixture_roster()
|
||||||
|
public = [reason for row in report["quick_inputs"]["rows"] for reason in row["reason"]]
|
||||||
|
report["replays"] = replay_cases(selected, runtime, roster, team=args.team,
|
||||||
|
timeout=args.timeout, deadline=deadline, cancel_event=stop,
|
||||||
|
public_reasons=public, damage_profile=args.damage_profile)
|
||||||
|
if len(report["replays"]) < len(selected):
|
||||||
|
report["reason"].append("budget_exhausted")
|
||||||
|
if any(row["outcome"] in ("timeout", "error", "cancelled") for row in report["replays"]):
|
||||||
|
report["reason"].append("replay_incomplete")
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
report["reason"] = ["cancelled"]
|
||||||
|
except Exception as exc:
|
||||||
|
safe = {"invalid_resource_bounds", "invalid_report_destination", "snapshot_load_failed", "task_not_found"}
|
||||||
|
report["reason"] = [str(exc) if isinstance(exc, ValueError) and str(exc) in safe else "offline_check_failed"]
|
||||||
|
report["wall_ms"] = round((time.monotonic() - started) * 1000, 3)
|
||||||
|
if output is not None:
|
||||||
|
try:
|
||||||
|
output.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
output.write_text(json.dumps(report, ensure_ascii=True, indent=2) + "\n", encoding="utf-8")
|
||||||
|
except OSError:
|
||||||
|
report["reason"] = ["report_write_failed"]
|
||||||
|
summary = {key: ({k: v[:TOP] if isinstance(v, list) else v
|
||||||
|
for k, v in value.items() if k != "rows"} if isinstance(value, dict) else value)
|
||||||
|
for key, value in report.items()}
|
||||||
|
print(json.dumps(summary, ensure_ascii=True, separators=(",", ":")))
|
||||||
|
return 1 if report["reason"] else 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.addaudithook(_offline_audit)
|
||||||
|
raise SystemExit(main())
|
||||||
Reference in New Issue
Block a user