diff --git a/.github/workflows/web-image.yml b/.github/workflows/web-image.yml index b16d059..b7ad71f 100644 --- a/.github/workflows/web-image.yml +++ b/.github/workflows/web-image.yml @@ -7,6 +7,7 @@ on: paths: - ranch_web/** - ranch_assistant/** + - tools/check_progression_support.py - deploy/web/** - Dockerfile - .dockerignore @@ -71,6 +72,15 @@ jobs: 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 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 account recovery regression diff --git a/Dockerfile b/Dockerfile index 07d93cb..0f30afc 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,6 +1,6 @@ FROM python:3.12-slim-bookworm -ARG WEB_VERSION=2.0.8 +ARG WEB_VERSION=2.0.9 ARG VCS_REF=unknown LABEL org.opencontainers.image.source="https://github.com/attilanet/myrzx_bot" \ org.opencontainers.image.title="myrzx_bot Web" \ diff --git a/README.md b/README.md index 374826b..9609306 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,11 @@ # 牧羊人之心Bot -Web **2.0.8**,源码发布入口为 `main`;原生 PySide6 桌面正式版本保留 **1.2.0**(`v1.2.0`)。两者的适配资料基线均为《牧羊人之心》Android **1.9.68**。 +Web **2.0.9**,源码发布入口为 `main`;原生 PySide6 桌面正式版本保留 **1.2.0**(`v1.2.0`)。两者的适配资料基线均为《牧羊人之心》Android **1.9.68**。 支持多账号独立运行、牧场培养、每日事务、主线与委托推进、近似战斗模拟、探险、扫荡及本地掉落分析,能力与验证限制见下文。 ## 运行指引 -### Web 2.0.8(源码发布入口 main) +### Web 2.0.9(源码发布入口 main) Windows 使用 Python 3.12+,在项目根目录执行: @@ -19,6 +19,10 @@ 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)。 +**2.0.9** 清理设置页重复运行提示,沿用原单一底部分类日志。委托明确显示中文未接取原因,成熟魔物需求联动购蛋、孵化,先备齐资源再接取;按剩余步骤计算缺口,继续遵守预算及魔物保护设置。 + +正常自动战斗默认使用快速数值模型,保留现有伤害配置,无需另选模式;按双方属性、血量、伤害、时间及关卡目标估算胜负,逐帧实现仅供研发。358/358份主线与委托战斗配置通过输入预检,表示配置可计算,实际仍可能打不过。正常潜能误报也已修复;验证结果见 [发布说明](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)。 @@ -38,7 +42,7 @@ Web 无需 Node/npm 或 PySide6,数据独立保存在 `local_state/ranch_web` | 组件与版本 | 《牧羊人之心》Android 基线 | 入口与状态 | | --- | --- | --- | -| Web 2.0.8 | 1.9.68 | 源码发布入口 `main`,`Start_Ranch_Web.cmd` / `sh start-web.sh` | +| Web 2.0.9 | 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.1.1(`v1.1.1`) | 1.9.68 | 历史正式版本,1.1 系列修复与界面更新 | | 桌面 1.1.0(`v1.1.0`) | 1.9.68 | 历史已发布版本 | diff --git a/analysis/RELEASE_2_0_9.md b/analysis/RELEASE_2_0_9.md new file mode 100644 index 0000000..b71f619 --- /dev/null +++ b/analysis/RELEASE_2_0_9.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)。 diff --git a/compose.yaml b/compose.yaml index b44f940..6cd62c4 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,11 +1,11 @@ name: ranch-web services: web: - image: ${RANCH_WEB_IMAGE:-ghcr.io/attilanet/myrzx_bot-web:v2.0.8} + image: ${RANCH_WEB_IMAGE:-ghcr.io/attilanet/myrzx_bot-web:v2.0.9} build: context: . args: - WEB_VERSION: ${RANCH_WEB_BUILD_VERSION:-2.0.8} + WEB_VERSION: ${RANCH_WEB_BUILD_VERSION:-2.0.9} user: "10001:10001" init: true restart: unless-stopped diff --git a/deploy/web/README.md b/deploy/web/README.md index 3920482..db53ebf 100644 --- a/deploy/web/README.md +++ b/deploy/web/README.md @@ -1,6 +1,8 @@ # Web 2 Linux Docker 部署与更新 -当前应用及更新示例为 `v2.0.8`。下文首次初始化章节保留 2.0.1 流程及历史版本示例。游戏资料基线为 `1.9.68`,桌面版保留 `1.2.0`。镜像流水线成功、Git tag 与 GitHub Release 是不同的发布步骤:在线更新必须等对应镜像及非草稿、非预发布的 Release 均发布后才能使用。私有仓库未获授权返回 404 属于访问失败,不代表没有版本;只有成功读取列表且没有稳定 2.x 时才显示“暂无正式版”。 +当前应用及更新示例为 `v2.0.9`。下文首次初始化章节保留 2.0.1 流程及历史版本示例。游戏资料基线为 `1.9.68`,桌面版保留 `1.2.0`。镜像流水线成功、Git tag 与 GitHub Release 是不同的发布步骤:在线更新必须等对应镜像及非草稿、非预发布的 Release 均发布后才能使用。私有仓库未获授权返回 404 属于访问失败,不代表没有版本;只有成功读取列表且没有稳定 2.x 时才显示“暂无正式版”。 + +2.0.9 仅整理设置页重复运行提示,21项相关测试通过;以下历史结果不计入本补丁,见 [本版发布说明](../../analysis/RELEASE_2_0_9.md)。 已在 2.0.1 完成私有仓库和 GHCR 认证的部署,稳定 Release 与正式镜像发布后,可直接通过“帮助 → 检查版本更新…”升级,无需先安装 2.0.2、重复初始化或替换宿主机更新器。尚未接入私有在线更新的宿主机才需参考下文“已有宿主机首次初始化”。 @@ -21,7 +23,7 @@ sudo install -m 0600 -o root -g root deploy/web/image.env.example .image.env sudoedit .env .image.env ``` -在 `.env` 填入独立的 `RANCH_WEB_PASSWORD`,这是 Web 管理密码,不是游戏密码;`.image.env` 的目标示例为 `RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:v2.0.8`,需确认对应镜像已发布后再 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.9`,需确认对应镜像已发布后再 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`。不要对现有账号目录重新初始化密钥。 @@ -53,7 +55,7 @@ Web 只读检查官方 GitHub Releases;默认只接受 `v2.MINOR.PATCH`,跳 ### 已完成 2.0.1 初始化的宿主机 -稳定 Release 与正式镜像发布后,用户打开“帮助 → 检查版本更新…”,检查到 2.0.8 后手动提交更新请求,可从 2.0.1 直接安装。现有私有仓库认证、GHCR 登录与宿主机更新器继续使用;Web 按钮仍要求有效心跳及 `accept_web_requests=true`。请求显示 `pending` 只表示已提交,宿主机完成备份、安装及健康检查后才确认成功;升级完成后刷新网页以加载新版界面,底部日志默认收起。Windows 或未启用执行器时仍仅可检查版本。自动安装默认关闭。 +稳定 Release 与正式镜像发布后,用户打开“帮助 → 检查版本更新…”,检查到 2.0.9 后手动提交更新请求,可从 2.0.1 直接安装。现有私有仓库认证、GHCR 登录与宿主机更新器继续使用;Web 按钮仍要求有效心跳及 `accept_web_requests=true`。请求显示 `pending` 只表示已提交,宿主机完成备份、安装及健康检查后才确认成功;升级完成后刷新网页以加载新版界面,底部日志默认收起。Windows 或未启用执行器时仍仅可检查版本。自动安装默认关闭。 ### 全新宿主机安装 @@ -108,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) -4. 使用新包先检查再由用户明确发起在线更新。以下 `--apply v2.0.1` 仅保留首次初始化的历史示例,不是本轮 2.0.8 升级命令: +4. 使用新包先检查再由用户明确发起在线更新。以下 `--apply v2.0.1` 仅保留首次初始化的历史示例,不是本轮 2.0.9 升级命令: ```sh sudo python3 -B /opt/ranch-web/updater.pyz --config /etc/ranch-web-updater.toml --check @@ -166,9 +168,9 @@ Windows 或未安装执行器的 Docker 部署仍能检查版本,但按钮会 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 -python -B tools/build_web_updater.py --output test-artifacts/releases/v2.0.8/updater.pyz -python -B test-artifacts/releases/v2.0.8/updater.pyz --version -python -B test-artifacts/releases/v2.0.8/updater.pyz --config deploy/web/updater.example.toml --apply v2.0.8 --dry-run +python -B tools/build_web_updater.py --output test-artifacts/releases/v2.0.9/updater.pyz +python -B test-artifacts/releases/v2.0.9/updater.pyz --version +python -B test-artifacts/releases/v2.0.9/updater.pyz --config deploy/web/updater.example.toml --apply v2.0.9 --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 ``` diff --git a/deploy/web/image.env.example b/deploy/web/image.env.example index 7b7f76e..074a013 100644 --- a/deploy/web/image.env.example +++ b/deploy/web/image.env.example @@ -1,2 +1,2 @@ -# Pull only after the v2.0.8 image publishing workflow succeeds and the image is available. -RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:v2.0.8 +# Pull only after the v2.0.9 image publishing workflow succeeds and the image is available. +RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:v2.0.9 diff --git a/ranch_assistant/battle_quick.py b/ranch_assistant/battle_quick.py new file mode 100644 index 0000000..bd2fb50 --- /dev/null +++ b/ranch_assistant/battle_quick.py @@ -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"]) diff --git a/ranch_assistant/battle_simulator.py b/ranch_assistant/battle_simulator.py index a9beb0b..dd61c54 100644 --- a/ranch_assistant/battle_simulator.py +++ b/ranch_assistant/battle_simulator.py @@ -419,11 +419,17 @@ class Scenario: triggers: tuple = () -def _prepare(request, tables): +def _prepare(request, tables, *, quick=False): report = _envelope() report.update(supported=False, reasons=[], implemented_skills=sorted(KNOWN_SKILLS)) 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} if record not in report["diagnostics"]: report["diagnostics"].append(record) @@ -498,7 +504,9 @@ def _prepare(request, tables): units = [] # BattleCenter empties the master team before adding authored allies. configured_mons = [(team, mon) for team in battle.get("teams", ()) 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 = [] for entry in battle.get("triggers", ()) or (): if mining: @@ -549,24 +557,26 @@ def _prepare(request, tables): if mining: 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) - 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") 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") field_config = battle.get("battleField") + if quick and not isinstance(field_config, Mapping): + field_config = {} if not isinstance(field_config, Mapping): raise SimulationInputError("Full original battleField configuration is required") if field_config.get("fieldMode"): name = field_config.get("fieldName", "default") 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") - field_config = dict(original_field, mapObjects=field_config.get("mapObjects", ()), - mapAreas=tuple(original_field.get("mapAreas", ())) + tuple(field_config.get("mapAreas", ()))) + field_config = dict(original_field or {}, mapObjects=field_config.get("mapObjects", ()), + mapAreas=tuple((original_field or {}).get("mapAreas", ())) + tuple(field_config.get("mapAreas", ()))) points = {p["id"]: p for p in field_config.get("mapPoints", ())} 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") for area in areas.values(): 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) 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) - 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") - 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") - 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}" 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): @@ -629,7 +639,7 @@ def _unit_preview(unit): 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 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)] potential_level = _int(mon.get("potentialLevel", 1)) - tp = min(4, _int(mon.get("tpLevel", 0))) if _number(mon.get("feel", 0)) > 200: add("+15overfeel", 50, feel=mon["feel"]) 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 if value > 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)) if potential and value_potential > 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: - """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 eligibility. Calls do not mutate the request, cache, or input snapshot. @@ -1343,7 +1354,8 @@ class ExperimentalBattleRuntime: def inspect(self, request): try: - _, report = _prepare(request, combat_tables()) + from .battle_quick import prepare + _, report = prepare(request, combat_tables()) return report except SimulationInputError as exc: result = _envelope() @@ -1418,7 +1430,8 @@ def _worker(): if len(wire) > MAX_WIRE_BYTES: raise SimulationInputError("Worker input exceeds limit") 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": result.update(execution_status="unsupported", terminal=False, terminal_reason="unsupported_scenario") encoded = json.dumps(result, ensure_ascii=True, allow_nan=False, diff --git a/ranch_assistant/battles.py b/ranch_assistant/battles.py index f3e93eb..95732bd 100644 --- a/ranch_assistant/battles.py +++ b/ranch_assistant/battles.py @@ -427,6 +427,7 @@ class BattleOrchestrator: "requires_realtime_wait", "wall_time_ms", "trace_path", "resource_identity", "terminal_reason", "settlement_eligible", "experimental_settlement_eligible", "execution_mode", "execution_status", "terminal", "diagnostics", "ignored_mechanics", "anomalies", "assumptions", "experimental_eligibility_reasons", "omitted_events", + "model", "simulation_method", "team_budgets", "generated_units", "spawn_bound_reached", "damage_profile", "damage_multiplier", "damage_cap", "damage_profile_digest", "damage_profile_scope")}} trace = value(result, "trace") if trace is None: diff --git a/ranch_assistant/engine.py b/ranch_assistant/engine.py index 6290b86..340ce6c 100644 --- a/ranch_assistant/engine.py +++ b/ranch_assistant/engine.py @@ -12,7 +12,8 @@ from types import SimpleNamespace from .model import Action, Catalog, Planner, Policy, Snapshot, seconds from .daily import DailyLedger, DailyPolicy, selected_entries from .sweeping import SweepPolicy, SweepRunner -from .quests import QuestPolicy, TaskPlanner, commission_priority +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 .management import expansion_quote, manual_monster_actions @@ -389,6 +390,8 @@ class Engine: self.game_data = load_progression_data() if self.progression_planner is None: 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 # and dialogue, not just the battle action they lead to. self.progression_planner.battle_capability = self._battle_capability @@ -531,6 +534,7 @@ class Engine: def _recover_confirmed_progression(self): """Replay only local acknowledgement of a durably received success.""" + self._reconcile_procurement() record = self.battle_journal.pending(self.snapshot) if (not record or str(record.get("role_id")) != str(self.snapshot.raw["master"].get("id")) or not str(record.get("kind", "")).startswith("progression_")): @@ -657,7 +661,8 @@ class Engine: source_supported = row.get("supported") is not False 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: - 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"))) if commission is not None: row.update(next_action=value(commission, "description"), block_reason=value(commission, "block_reason", "")) @@ -675,6 +680,7 @@ class Engine: else: row["supported"] = bool(source_supported and not reason) row["block_reason"] = row["blocked_reason"] = reason + row["reason_kind"] = commission_reason_kind(reason) return rows, adjusted def _battle_request(self, snapshot, intent, policy, request): @@ -754,7 +760,9 @@ class Engine: 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})) + "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: @@ -872,6 +880,13 @@ class Engine: policy = self._intent_policy({"task_type_id": str(type_id)}) ready, _, requirement_reason = self.progression_planner.requirement(self.snapshot, step, {}, policy, self.policy) 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, {"id": 0, "typeId": str(type_id), "curStep": number}, policy, self.policy) source_reasons = [] @@ -904,6 +919,7 @@ class Engine: "snapshot": self._battle_snapshot_digest, "runtime": id(self.battles.runtime)}) 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), + "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: @@ -919,9 +935,18 @@ class Engine: self._commission_offer_diagnostics = deepcopy(self.progression_planner.commission_offer_rows) intents.sort(key=lambda intent: not self._is_commission(intent)) 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._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), + "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 = "" @@ -986,6 +1011,8 @@ class Engine: 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: message = self._execute_task_intent(intent) if self.battle_journal.pending(self.snapshot) and kind == "progression_battle": @@ -998,7 +1025,7 @@ class Engine: self.read_snapshot(sync_master=False) return self.snapshot, self.plans(), message 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._persist_progression() raise @@ -1006,6 +1033,117 @@ class Engine: self._sync_commission_history() 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): path, kind = value(intent, "path", "") or "", value(intent, "kind") payload = deepcopy(value(intent, "payload", {}) or {}) @@ -1058,6 +1196,7 @@ class Engine: if self._progression_pending(): self.last_pending_check = time.monotonic() self.snapshot = self.client.snapshot() + 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: @@ -1512,10 +1651,23 @@ class Engine: # One owner for commission writes; never accept the same offer through # 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) - 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) for key, count in eggs.items(): 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) self.hatch_planner.notes = [] self.pending_hatches = self.hatch_planner.hatch_actions(self.snapshot, policy) @@ -1524,7 +1676,7 @@ class Engine: map_action = self._next_map_action() sweep_actions = [map_action] if map_action else [] 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) breakthrough_policy = SimpleNamespace(**(asdict(policy) | {"item_reserves": dict(self.quest_policy.item_reserves)})) self.breakthrough_planner.notes = [] diff --git a/ranch_assistant/procurement.py b/ranch_assistant/procurement.py new file mode 100644 index 0000000..2be08bd --- /dev/null +++ b/ranch_assistant/procurement.py @@ -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 diff --git a/ranch_assistant/progression.py b/ranch_assistant/progression.py index 948e378..d2735e2 100644 --- a/ranch_assistant/progression.py +++ b/ranch_assistant/progression.py @@ -45,7 +45,8 @@ import uuid from .game_data import ProgressionData, load_progression_data from .model import Planner, seconds -from .quests import commission_priority, commission_selection, 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", "支线"), @@ -180,6 +181,8 @@ class ProgressionPlanner: self.catalog = catalog self.data = data if isinstance(data, ProgressionData) else ProgressionData(data) if data is not None else load_progression_data() 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._anonymous = uuid.uuid4().hex self._accounts = {} @@ -328,6 +331,18 @@ class ProgressionPlanner: "bar": "酒馆", "shop": "商店", "wild": "野外", "mine": "矿洞", "pve": "挑战"} 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): if not position or position in ("farm", "stackGround"): return "" @@ -341,7 +356,7 @@ class ProgressionPlanner: if city_info.get("hide") is True: return "城市已隐藏" 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 == "mine" and (snapshot.raw.get("history") or {}).get("openMine") is not True: return "矿洞功能尚未开放" @@ -459,47 +474,9 @@ class ProgressionPlanner: if money - amount < ranch_policy.keep_money: return False, None, "提交后低于牧场金币保留量" return money >= amount, None, f"金币 {money}/{amount}" - if kind == "getItem" or kind == "getMonster" and _integer(value.get("mode"), -2) == 0: - key, count = str(value.get("type", "")), _integer(value.get("num"), -1) - if not key.isdigit() or count < 0: - 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 resource_kind(step): + row = self.procurement.inventory(snapshot, step, policy, ranch_policy) + return row["ready"], row["ids"] if row["ready"] else None, row["reason"] if kind == "killMonster": target = task.get("stepValue") kills = indexed(history.get("numKillMonsters"), value.get("type")) @@ -600,6 +577,13 @@ class ProgressionPlanner: reason = self._script_gate(step.get("afterStory")) if reason or step.get("afterStory") and not policy.auto_dialogue: 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) if farming: return farming[0] @@ -838,6 +822,54 @@ class ProgressionPlanner: 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) + 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): if info.get("closed"): return False, "委托已关闭" @@ -847,9 +879,14 @@ class ProgressionPlanner: # Acceptance spends a daily slot. Keep the old scheduler's conservative # resource preflight, now allowing verified linear story completion. money = 0 - item_costs = {} - monster_costs = {} + scope, account = self._account(snapshot) 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")): reason = self._script_gate(script) if reason or script and not policy.auto_dialogue: @@ -862,7 +899,7 @@ class ProgressionPlanner: return False, "委托战斗配置缺失" if kind == "passStage" and not self.data.stage(value.get("stage")): return False, "委托关卡配置缺失" - else: + elif not resource_kind(step): ready, _, reason = self.requirement(snapshot, step, {}, policy, ranch) if not ready: preview = {"id": 0, "typeId": str(info.get("id", "")), "curStep": number} @@ -871,23 +908,12 @@ class ProgressionPlanner: if value.get("remove") is True: if kind == "getMoney": 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): return False, "整份委托提交金币超过设置或保留量" - for key, count in item_costs.items(): - trial = {"statusType": "getItem", "statusValue": {"type": key, "num": count, "remove": True}} - if not self.requirement(snapshot, trial, {}, policy, ranch)[0]: - if not self.farming_intents(snapshot, trial, {"id": 0}, policy, ranch): - 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, "整份委托提交魔物不足或受保留保护" + supply = self.resource_plan(snapshot, info.get("steps") or [], {"id": 0, "typeId": str(info.get("id", ""))}, + policy, replace(ranch, keep_money=ranch.keep_money + money)) + if not supply.feasible: + return False, supply.reason return (True, "可接取") if info.get("steps") else (False, "委托没有有效步骤") def commission_plan(self, snapshot, quest_policy, ranch_policy, *, battle_policy=None, accept_supported=None): @@ -936,6 +962,16 @@ class ProgressionPlanner: for candidate in candidates: city, key = candidate["city"], candidate["task_type_id"] info = self.data.task(key) + if candidate.get("preparable"): + 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)) + action = self._resource_intent(snapshot, supply, {"id": 0, "typeId": key}, 0, {}, policy) + if action is not None: + 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"]: @@ -969,11 +1005,13 @@ class ProgressionPlanner: 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 - "城市尚未解锁" if not snapshot.city_unlocked(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 remaining <= 0 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 @@ -988,9 +1026,24 @@ class ProgressionPlanner: 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}) + "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): diff --git a/ranch_assistant/quests.py b/ranch_assistant/quests.py index 33f8e99..5faa4ad 100644 --- a/ranch_assistant/quests.py +++ b/ranch_assistant/quests.py @@ -7,6 +7,26 @@ from .model import Action, Planner, seconds 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): try: reward = int((info.get("reward") or {}).get("ke") or 0) @@ -234,10 +254,10 @@ class TaskPlanner: rejected.append(candidate | {"reason": reason}) return [] - def reservations(self, snapshot): + def reservations(self, snapshot, *, extra_tasks=()): types, eggs = set(), {} - for task in self.current(snapshot): - info = self.catalog.data["task_info"][str(task["typeId"])] + for task in [*self.current(snapshot), *extra_tasks]: + 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):]: value = step.get("statusValue") or {} key = str(value.get("type", "")) diff --git a/ranch_assistant/tests/test_battle_quick.py b/ranch_assistant/tests/test_battle_quick.py new file mode 100644 index 0000000..a1ceed5 --- /dev/null +++ b/ranch_assistant/tests/test_battle_quick.py @@ -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() diff --git a/ranch_assistant/tests/test_battle_simulator.py b/ranch_assistant/tests/test_battle_simulator.py index 8127af6..c4c5527 100644 --- a/ranch_assistant/tests/test_battle_simulator.py +++ b/ranch_assistant/tests/test_battle_simulator.py @@ -415,8 +415,9 @@ class SimulatorTests(unittest.TestCase): req = request(players=[monster(species=1001020)]) # actual skill 10 report = ExperimentalBattleRuntime().inspect(req) self.assertTrue(report["supported"]) - self.assertTrue(any(d["code"] == "unsupported_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(d["code"] == "aggregate_skill" and "10" in d["message"] for d in report["diagnostics"])) + 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): for key, value in (("controller", [{"type": "monMaker"}]), @@ -476,11 +477,13 @@ class WorkerTests(unittest.TestCase): self.assertEqual(result["outcome"], "win") 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() with patch("socket.socket", side_effect=AssertionError("No network")): 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): completed = subprocess.run([sys.executable, "-c", diff --git a/ranch_assistant/tests/test_commission_procurement.py b/ranch_assistant/tests/test_commission_procurement.py new file mode 100644 index 0000000..34129e5 --- /dev/null +++ b/ranch_assistant/tests/test_commission_procurement.py @@ -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() diff --git a/ranch_assistant/tests/test_progression_support.py b/ranch_assistant/tests/test_progression_support.py new file mode 100644 index 0000000..aaa3158 --- /dev/null +++ b/ranch_assistant/tests/test_progression_support.py @@ -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() diff --git a/ranch_assistant/tests/test_snapshot_potential_anomalies.py b/ranch_assistant/tests/test_snapshot_potential_anomalies.py new file mode 100644 index 0000000..9ddc2a7 --- /dev/null +++ b/ranch_assistant/tests/test_snapshot_potential_anomalies.py @@ -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() diff --git a/ranch_web/PRODUCT.md b/ranch_web/PRODUCT.md index 99baeb9..fad2654 100644 --- a/ranch_web/PRODUCT.md +++ b/ranch_web/PRODUCT.md @@ -1,8 +1,10 @@ -# 牧羊人之心牧场助手 · Web 2.0.8 +# 牧羊人之心牧场助手 · Web 2.0.9 ## 产品约束 -把现有桌面助手的功能和操作结构迁移至单管理员 Web 工作台。桌面版是页面顺序、信息密度、业务名称、保护条件与交互的依据,保留桌面兼容。Web `2.0.8`,源码发布入口 `main`,游戏数据版本 `1.9.68`;桌面正式版保留 `1.2.0`。启动与配置见 [运行说明](README.md),Docker 与更新条件见 [部署说明](../deploy/web/README.md),功能与验证状态见 [2.0.8 发布说明](../analysis/RELEASE_2_0_8.md)。 +把现有桌面助手的功能和操作结构迁移至单管理员 Web 工作台。桌面版是页面顺序、信息密度、业务名称、保护条件与交互的依据,保留桌面兼容。Web `2.0.9`,源码发布入口 `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.9 包含界面清理、委托补缺、默认快速战斗与潜能误报修复;保留账号简短状态、错误、表格、表单与原单一底部分类日志,见 [本版发布说明](../analysis/RELEASE_2_0_9.md)。 使用者在 Windows 本机配置、验证,随后可在 Linux Docker 常驻运行。多个浏览器访问同一个管理员工作台;账号互相隔离,各账号串行执行,账号之间可以并行。 @@ -26,6 +28,14 @@ - 帮助可检查 GitHub 正式版本并提交受控更新请求。未配置部署器时明确显示原因,更新提交不表示更新成功。 - 已在 2.0.1 完成私有仓库和 GHCR 认证的部署,稳定 Release 与正式镜像发布后,可直接通过“帮助 → 检查版本更新…”升级,无需先安装 2.0.2、重复初始化或替换宿主机更新器;升级完成后刷新网页以加载新版界面,安装结果以宿主机健康检查为准。 +## 2.0.9 本轮范围 + +默认使用快速数值模型,委托按剩余步骤统一计算采购和提交需求: + +- 委托用明确中文说明未接取的实际原因;成熟魔物交付需求联动购蛋、孵化,优先备齐所需资源再接取。锁定、培养、优质备份等魔物继续受保护,采购与孵蛋遵守耗用预算和需求缺口限制。 +- 正常执行默认使用现有内置实验运行时入口的快速 HP/DPS 模型,保留现有伤害配置,无需选择新模式;逐帧实现仅供研发。模型结合双方属性、血量、每秒伤害(DPS)、有效血量(EHP)、时间与关卡目标估算胜利、战败或超时,仍有机制简化,不保证全部关卡可通关或与客户端结果一致。 +- 潜能检查依据合法的 `PotentialPanel` 上限区分正常数值与异常,修复正常潜能的误报。 + ## 2.0.8 自动委托与每日历史 - 自动委托包含“当前委托 / 每日记录”。当前页展示原始候选、任务状态、标注奖励及选择 / 回退原因;城市锁定候选显示不可接取。 @@ -79,6 +89,10 @@ ## 安全与验证 +2.0.9 快速模型可读取358/358份主线与委托战斗配置,表示输入可计算。离线样本有胜有败,8个20氪金委托战斗为5胜3败;当前卡点样本的默认路径结果及耗时见 [发布说明](../analysis/RELEASE_2_0_9.md#验证)。 + +617项唯一回归用例中615项通过,2项因Windows环境跳过;另有8项界面浏览器测试通过。多步骤采购修复已通过独立复核;未在线提交游戏结算。 + 2.0.8 共验证739项独立测试:736通过、3项 Windows 跳过;其中非浏览器662项(659通过、3跳过),浏览器77项全部验证通过。证据与发布门禁见 [发布说明](../analysis/RELEASE_2_0_8.md#验证);历史版本结果不计入本版。 不发真实游戏 API 测试,不读取或更改私人 `local_state` 账号。浏览器测试仅使用临时目录、fake 后端或服务端离线演示。所有游戏文本用 `textContent` 呈现;日志使用服务端脱敏数据。管理登录、同源校验与 cookie 由 API 负责。 diff --git a/ranch_web/README.md b/ranch_web/README.md index 88a63e6..4564d8b 100644 --- a/ranch_web/README.md +++ b/ranch_web/README.md @@ -1,6 +1,10 @@ -# Web 2.0.8 运行说明 +# Web 2.0.9 运行说明 -Web **2.0.8**,源码发布入口 `main`,游戏资料基线 **1.9.68**。桌面正式版保留 **1.2.0**,入口为 `python -m ranch_assistant`;Web 使用独立依赖与数据根。自动委托提供当前委托与每日记录,功能和验证状态见 [2.0.8 发布说明](../analysis/RELEASE_2_0_8.md)。 +Web **2.0.9**,源码发布入口 `main`,游戏资料基线 **1.9.68**。桌面正式版保留 **1.2.0**,入口为 `python -m ranch_assistant`;Web 使用独立依赖与数据根。自动委托提供当前委托与每日记录,功能和历史验证状态见 [2.0.8 发布说明](../analysis/RELEASE_2_0_8.md)。 + +2.0.9 清理重复运行提示,补齐委托资源准备、默认快速战斗及正常潜能误报修复。委托明确显示中文未接取原因,成熟魔物需求联动购蛋、孵化;按剩余步骤备料,遵守预算、需求缺口及魔物保护设置。详情继续使用原单一底部分类日志,见 [本版发布说明](../analysis/RELEASE_2_0_9.md)。 + +正常执行默认使用现有内置实验运行时入口的快速 HP/DPS 模型,保留现有伤害配置,无需选择新模式;逐帧实现仅供研发。模型按双方属性、血量、每秒伤害、时间与目标估算胜利、战败或超时,仍有机制简化,不保证全部关卡可通关或与客户端结果一致。 Web 采用 FastAPI / Uvicorn 和原生 HTML/CSS/ES 模块,无 Node、npm 或前端编译步骤,不安装 PySide6。页面和策略能力沿用现有核心,详细业务范围与原有限制见 [桌面使用说明](../ranch_assistant/README.md)。多浏览器连接同一个管理员工作台;一个服务实例内,各账号独立线程并行,同一账号操作串行。 @@ -104,10 +108,14 @@ 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。 -已在 **2.0.1** 完成私有仓库和 GHCR 认证的部署,稳定 Release 和正式镜像就绪、宿主机心跳有效后,可直接通过“帮助 → 检查版本更新…”升级 **2.0.8**,无需先安装 2.0.2、重复初始化或替换宿主机更新器。升级完成后刷新网页以加载新版界面,底部日志默认收起。安装结果以宿主机健康检查为准;首次配置仅供尚未初始化的宿主机参考。 +已在 **2.0.1** 完成私有仓库和 GHCR 认证的部署,稳定 Release 和正式镜像就绪、宿主机心跳有效后,可直接通过“帮助 → 检查版本更新…”升级 **2.0.9**,无需先安装 2.0.2、重复初始化或替换宿主机更新器。升级完成后刷新网页以加载新版界面,底部日志默认收起。安装结果以宿主机健康检查为准;首次配置仅供尚未初始化的宿主机参考。 ## 离线验证 +2.0.9 快速模型的输入预检覆盖358/358份主线与委托战斗配置。当前卡点的真实账号离线样本预计战斗5秒,直接计算约1.2毫秒,含隔离进程启动与检查约0.21秒;8个20氪金委托战斗的离线结果为5胜3败,见 [本版发布说明](../analysis/RELEASE_2_0_9.md#验证)。 + +617项唯一回归用例中615项通过,2项因Windows环境跳过;另有8项界面浏览器测试通过。多步骤采购循环已经修复并独立复核。本轮未在线提交游戏结算或手动部署X99。 + 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) diff --git a/ranch_web/__init__.py b/ranch_web/__init__.py index 12e3857..4322e05 100644 --- a/ranch_web/__init__.py +++ b/ranch_web/__init__.py @@ -1,6 +1,6 @@ """Headless Web workspace for the ranch assistant.""" -__version__ = "2.0.8" +__version__ = "2.0.9" GAME_VERSION = "1.9.68" __all__ = ["__version__", "GAME_VERSION"] diff --git a/ranch_web/static/app.js b/ranch_web/static/app.js index b954e9b..13d66c2 100644 --- a/ranch_web/static/app.js +++ b/ranch_web/static/app.js @@ -415,7 +415,7 @@ async function exportYields(account=current()) { async function command(name,account=current()) { try { 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.8'}`}),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.9'}`}),el('p',{text:`游戏数据版本 ${state.meta?.gameVersion || '1.9.68'}`})),{info:true}); if(name==='updates')return await showUpdates(); if(name==='admin-logout'){hideWorkbench();try{await api.logout();}finally{requireAuth();}return;} if(!account)throw new Error('请先新增或选择账号。'); @@ -640,7 +640,7 @@ async function bootstrap() { $('#app').hidden=false; const [meta,schema]=await Promise.all([api.meta(),api.schema()]);state.meta=meta;state.schema=schema; if(state.redirecting)return; - $('#app-version').textContent=meta.version || '2.0.8';$('#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.9';$('#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('工作台已连接'); }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})));} } diff --git a/ranch_web/static/index.html b/ranch_web/static/index.html index 6d33606..2d9d912 100644 --- a/ranch_web/static/index.html +++ b/ranch_web/static/index.html @@ -26,7 +26,7 @@ - 牧羊人之心牧场助手 2.0.8 + 牧羊人之心牧场助手 2.0.9
diff --git a/ranch_web/static/pages.js b/ranch_web/static/pages.js index bbb5793..74c7273 100644 --- a/ranch_web/static/pages.js +++ b/ranch_web/static/pages.js @@ -116,7 +116,6 @@ export class PageView { this.subtabs = el('div', {class: 'subtabs', role: 'tablist', 'aria-label': '子页面', hidden: true}); this.filterHost = el('div', {class: 'filter-bar'}); this.summary = el('p', {class: 'page-summary'}); - this.runtimeStatus=el('div',{class:'page-summary',hidden:true}); this.formHost = el('div', {class: 'policy-form'}); this.actionsHost = el('div', {class: 'page-toolbar'}); 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(), onContext: (event, selected, row) => this.openContext(event, selected, row), onDetail: row => this.showDetail(row)}; 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.root.append(this.header, this.body); if (key === 'login') this.login = new LoginPage(this.content, this); @@ -248,7 +247,7 @@ export class PageView { this.updateFilters(data.filters || []); this.summary.textContent = typeof data.summary === 'string' ? data.summary : textValue(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); 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); @@ -276,29 +275,6 @@ export class PageView { } 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) { const data = this.data.details?.[row.id] || row.details; if (!data) return; diff --git a/ranch_web/tests/browser/test_page_loading_browser.py b/ranch_web/tests/browser/test_page_loading_browser.py index 98931d1..4a4fcf8 100644 --- a/ranch_web/tests/browser/test_page_loading_browser.py +++ b/ranch_web/tests/browser/test_page_loading_browser.py @@ -131,11 +131,12 @@ class PageLoadingBrowserTests(unittest.TestCase): expect(panel.locator("tbody tr")).to_have_count(32) 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() panel = self.bag() 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_NOTE_SENTINEL", panel.inner_text()) self.assertEqual(panel.locator(".info-note, .field-help").count(), 0) @@ -156,6 +157,7 @@ class PageLoadingBrowserTests(unittest.TestCase): expect(field).to_be_focused() expect(field).to_have_value("") 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() self.assertEqual(self.page.locator("#log-panel").count(), 1) diff --git a/ranch_web/tests/browser/test_workbench_browser.py b/ranch_web/tests/browser/test_workbench_browser.py index 6213265..773e8a8 100644 --- a/ranch_web/tests/browser/test_workbench_browser.py +++ b/ranch_web/tests/browser/test_workbench_browser.py @@ -148,7 +148,7 @@ class WorkbenchBrowserTests(unittest.TestCase): expect(panel.locator('.form-section legend')).to_have_text('孵蛋策略') panel.locator('.subtab[data-key="喂养策略"]').click() 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': expect(panel.locator('.subtab[data-key="policy"]')).to_be_visible() 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') 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): self.fulfill(route,{'data':{'page':'gifts','title':'自动赠礼','summary':'离线状态','form':[],'filters':[],'columns':[],'rows':[],'actions':[], 'details':{'next_ready_at':1794294489}},'loading':False}) self.page.route(f'**/api/accounts/{self.first}/views/gifts?*',gifts_view) self.open() 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() - data=self.manager.view(self.first,'hatching',{})['data'] - expect(panel.locator('[data-view-status="feed_status"]')).to_contain_text(data['details']['feed_status'][1]) + expect(panel.locator('.form-section legend')).to_have_text('喂养策略') + 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() expect(self.page.locator('#action-dialog')).not_to_be_visible() self.page.wait_for_timeout(1400) @@ -462,9 +465,72 @@ class WorkbenchBrowserTests(unittest.TestCase): self.assertTrue(self.manager.get_config(self.first)['config']['policy']['egg_rules']['1001010']['enabled']) self.assertFalse(self.manager.status(self.first)['running']) 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, []) + def test_update_dialog_polls_host_progress_recovers_and_stops_on_close(self): calls=[] applied=False diff --git a/ranch_web/tests/test_commission_procurement_views.py b/ranch_web/tests/test_commission_procurement_views.py new file mode 100644 index 0000000..dcab214 --- /dev/null +++ b/ranch_web/tests/test_commission_procurement_views.py @@ -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() diff --git a/ranch_web/tests/test_web_integration.py b/ranch_web/tests/test_web_integration.py index 388c4c8..616db31 100644 --- a/ranch_web/tests/test_web_integration.py +++ b/ranch_web/tests/test_web_integration.py @@ -790,14 +790,15 @@ class FreshProcessIntegrationTests(unittest.TestCase): def test_real_engine_battle_worker_subprocess_still_runs_after_web_imports(self): result = self.child(''' - import json, tempfile + import json, sys, tempfile from pathlib import Path from unittest.mock import patch import subprocess from ranch_web.app import create_app from ranch_web.service import WebManager 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'] 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'): @@ -819,15 +820,20 @@ class FreshProcessIntegrationTests(unittest.TestCase): result = engine.battles.runtime.run(request, timeout=15) assert launch.call_count == 1 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 not any(n.startswith('PySide6') or n == 'ranch_assistant.gui' or n.endswith('_gui') for n in sys.modules) 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: manager.close() ''') self.assertEqual(result["real_worker_processes"], 1) self.assertEqual(result["outcome"], "win") + self.assertEqual(result["simulation_method"], "aggregate_hp_dps") if __name__ == "__main__": diff --git a/ranch_web/views.py b/ranch_web/views.py index 42e0b50..25fdd10 100644 --- a/ranch_web/views.py +++ b/ranch_web/views.py @@ -13,7 +13,7 @@ from ranch_assistant.drop_statistics import analyze from ranch_assistant.presentation import monster_rows 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.quests import commission_priority, commission_selection +from ranch_assistant.quests import commission_priority, commission_selection, commission_reason_kind from .policies import default_config, validate_config @@ -478,6 +478,26 @@ def _category(value): 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): selected, state = str(query.get("category", "mainline")), str(query.get("state", "current")) dto["filters"] = [_filter("category", "任务类别", selected, [("", "全部类别"), *CATEGORIES.items()]), @@ -492,7 +512,8 @@ def _mainline(dto, engine, config, query): 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: 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 "支持状态未确认" battle = _text(source.get("battle_kind"), "未确认") battle = BATTLE_ALIASES.get(battle, battle) @@ -500,11 +521,15 @@ def _mainline(dto, engine, config, query): "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")), "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"], "目标 / 位置": row["location"], "NPC": _text(source.get("npc_name")), "需求": row["requirement"], "对话": _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(): continue dto["rows"].append(row) @@ -645,11 +670,11 @@ def _commissions(dto, engine, config, query): snapshot, catalog = engine.snapshot, engine.catalog search = _search(dto, query) dto["columns"] = [_column(key, label) for key, label in (("task_type_id", "编号"), ("name", "委托"), ("city", "城市"), ("status", "状态"), - ("reward_money", "标注金币"), ("reward_ke", "标注氪金"), ("selection_reason", "选择 / 回退原因"), ("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"} 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), {}) + 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: ( @@ -661,15 +686,23 @@ def _commissions(dto, engine, config, query): 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: - status = "暂不接取" if "city" in meta else "等待条件" + status = "补齐后接取" if offer.get("preparable") else "暂不接取" if "city" in meta else "等待条件" text = reason elif not offer and diagnostic.get("next_action"): text = diagnostic["next_action"] info = catalog.data.get("task_info", {}).get(str(key), {}) 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, - "reward_money": reward.get("money", 0), "reward_ke": reward.get("ke", 0), "reason": battle_message(text), - "city": meta.get("city"), "active": "city" not in meta, + "reward_money": reward.get("money", 0), "reward_ke": reward.get("ke", 0), "reason": _task_diagnostic_reason(text), + "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 "已接取,优先推进当前委托")} @@ -677,7 +710,9 @@ def _commissions(dto, engine, config, query): continue dto["rows"].append(row) dto["details"][row["id"]] = {"描述": info.get("des", ""), "标注奖励": reward_summary(catalog, reward), - "城市": _text(meta.get("city")), "选择 / 回退原因": row["selection_reason"], "需求 / 下一步": row["reason"], + "城市": _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.max_money, "允许已支持战斗": engine.quest_policy.battle_tasks}, "接取优先级": "跨城市按标注氪金 20 → 15 → 10 优先;20 氪金均不可用时回退到可执行的 15 / 10 氪金委托"} diff --git a/tools/check_progression_support.py b/tools/check_progression_support.py new file mode 100644 index 0000000..3ea0c2e --- /dev/null +++ b/tools/check_progression_support.py @@ -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())