fix(web): finalize quick battle and commission procurement for 2.0.9

This commit is contained in:
AttilaNet
2026-11-13 11:28:14 +08:00
parent cfce3e0bc5
commit 7845751cf6
21 changed files with 2442 additions and 117 deletions
+10
View File
@@ -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
+3 -1
View File
@@ -19,7 +19,9 @@ 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** 仅移除设置页重复的最近抽取、喂养等待、赠礼下次就绪和执行计划批量运行提示;保留账号简短状态、错误、表格、表单与原单一底部分类日志,后端、日志及策略逻辑不变。本补丁21项相关测试通过,历史结果不计入,见 [发布说明](analysis/RELEASE_2_0_9.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)。
+7 -6
View File
@@ -2,14 +2,15 @@
Web **2.0.9** 基于 **2.0.8**;游戏资料 **1.9.68**,桌面正式版 **1.2.0**。
- 移除设置页重复的最近抽取、喂养等待、赠礼下次就绪和执行计划批量运行提示,详情沿用原单一底部分类日志。
- 保留账号简短状态、错误、业务表格、配置表单与日志显隐、筛选和账号隔离;后端、日志及策略逻辑不变。
- Web 元数据与当前部署示例更新为 2.0.9;[2.0.8 自动委托与每日历史](RELEASE_2_0_8.md)等既有功能沿用。
- **界面清理**:移除设置页重复运行提示,保留简短状态、错误、业务表格、配置表单与原单一底部分类日志。
- **委托原因与备料**:明确中文未接取原因,成熟魔物需求联动购蛋/孵化,先备齐资源再接取;保护锁定、培养、优质备份等魔物,遵守耗用预算与孵蛋缺口限制。
- **快速数值战斗**:正常执行默认使用现有实验运行时入口的快速 HP/DPS 模型,保留现有伤害配置,无需选择新模式;逐帧实现仅供研发。按双方属性、有效血量、伤害、时间和关卡目标估算胜利、战败或超时。
- **潜能误报修复**:按合法的 `PotentialPanel` 上限识别正常潜能,避免误报为异常。
## 验证
本补丁21项相关测试全部通过:浏览器8项、任务日志10项、独立更新器包3项;无失败或跳过。浏览器冻结证据为 `test-artifacts/ui209/verification.json`,任务日志独立复核10/10通过(1.320秒)。Node 语法、差异检查和桌面视觉复核通过,历史版本结果不计入本补丁。
617项唯一回归用例中615项通过,2项因Windows环境跳过;另有8项界面浏览器测试通过。多步骤委托的采购范围不一致问题已修复,并通过独立复核。
另验证6项私有助手操作门禁;更新包3份源文件逐字节一致、可复现构建及版本 / 帮助 / 离线计划通过,以上检查不计入21项测试。
快速模型的输入预检覆盖由147/358提升至358/358份主线与委托战斗配置,表示配置可计算,实际仍可能打不过。“猫狗的恩怨”的真实账号离线样本预计战斗5秒,直接计算约1.2毫秒,含隔离进程启动与检查约0.21秒;8个20氪金委托战斗样本为5胜3败。
更新包位于 `test-artifacts/releases/v2.0.9/updater.pyz`,同目录 `SHA256SUMS` 使用 LF 换行。标签 `v2.0.9`,镜像 `ghcr.io/attilanet/myrzx_bot-web:v2.0.9`;在线更新须等稳定 Release 与正式镜像均就绪,见 [部署说明](../deploy/web/README.md)。本轮未部署 X99 或执行真实游戏操作。
本轮未在线提交游戏结算或手动部署X99。模型结果可能与客户端不同;发布后通过在线更新升级,见 [部署说明](../deploy/web/README.md)。
+370
View File
@@ -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"])
+30 -17
View File
@@ -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,
+1
View File
@@ -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:
+158 -6
View File
@@ -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 = []
+306
View File
@@ -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
+117 -64
View File
@@ -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):
+23 -3
View File
@@ -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", ""))
+184
View File
@@ -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()
@@ -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",
@@ -0,0 +1,393 @@
"""Offline task procurement replay: all writes go to the fake below."""
from copy import deepcopy
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
from ranch_assistant.engine import Engine
from ranch_assistant.game_data import ProgressionData
from ranch_assistant.model import Catalog, Policy, Snapshot
from ranch_assistant.progression import ProgressionPlanner, ProgressionPolicy
from ranch_assistant.quests import QuestPolicy
from ranch_assistant.tests.test_progression import config, snapshot, step, task
EGG = "1030010"
def requirement(kind="getMonster", count=1, key=EGG):
return step(kind, statusValue={"type": key, "num": count, "mode": 2 if kind == "getMonster" else 0, "remove": True})
def monster(catalog, mid, **changes):
row = catalog.monster(EGG)
return {"id": mid, "typeId": int(EGG), "mode": 2, "process": 3, "level": 1, "roomId": 1,
**{"g" + stat.capitalize(): row[stat + "_grow_min"] for stat in ("atk", "def", "hp", "dex")}, **changes}
class OfflineProcurementClient:
def __init__(self, raw, catalog):
self.raw, self.catalog, self.writes = deepcopy(raw), catalog, []
self.timeout = False
def snapshot(self):
return Snapshot(deepcopy(self.raw))
def call(self, path, payload):
self.writes.append((path, deepcopy(payload)))
if self.timeout:
raise TimeoutError("offline fake lost reply")
if path == "gachaService/gachaGetEggs":
count = payload["num"]
self.raw["master"]["money"] -= self.catalog.data["markets"][payload["id"]]["money"] * count
existing = next((i for i in self.raw["items"] if str(i["typeId"]) == EGG), None)
if existing:
existing["num"] += count
else:
self.raw["items"].append({"id": 500, "typeId": int(EGG), "num": count})
return {"resCode": 0, "eggs": [{"typeId": int(EGG), "num": count}]}
if path == "stackService/stackAddMonster":
for egg in payload["eggs"]:
item = next(i for i in self.raw["items"] if i["id"] == egg["itemId"])
item["num"] -= 1
mid = max([m["id"] for m in self.raw["monsters"]] + [900]) + 1
self.raw["monsters"].append(monster(self.catalog, mid, mode=0, process=2,
timeStart=self.snapshot().now * 1000, roomId=0))
next(s for s in self.raw["stacks"] if s["id"] == egg["stackId"])["monsterId"] = mid
return {"resCode": 0}
if path == "stackService/stackTransferMonster":
for data in payload["datas"]:
for mid in data["monsterId"]:
next(m for m in self.raw["monsters"] if m["id"] == mid).update(process=3, roomId=data["roomId"])
for stack in self.raw["stacks"]:
if stack["monsterId"] == mid:
stack["monsterId"] = 0
return {"resCode": 0}
if path == "taskService/taskLoopReceive":
received = {"id": 51, "typeId": payload["taskTypeId"], "curStep": 1}
self.raw["currentTasks"].append(received)
self.raw["history"]["loopTaskNum"] -= 1
return {"resCode": 0, "task": deepcopy(received)}
if path == "taskService/taskCompleteStep":
for mid in payload.get("removeIds") or []:
self.raw["monsters"] = [m for m in self.raw["monsters"] if m["id"] != mid]
for stack in self.raw["stacks"]:
if stack["monsterId"] == mid:
stack["monsterId"] = 0
next(t for t in self.raw["currentTasks"] if t["id"] == payload["taskId"])["curStep"] += 1
return {"resCode": 0, "taskStepValue": None}
if path == "taskService/taskComplete":
self.raw["currentTasks"] = [t for t in self.raw["currentTasks"] if t["id"] != payload["taskId"]]
return {"resCode": 0, "reward": {"ke": 20}}
raise AssertionError("Unexpected fake write: " + path)
class CommissionProcurementTests(unittest.TestCase):
def setUp(self):
self.catalog = Catalog()
# Keep a real gold market and real growth/protection rules; make the
# offline draw deterministic without asserting real RNG outcomes.
self.catalog.data["markets"]["sc_city1"]["eggs"] = {"2": [int(EGG)]}
self.tasks = {"400": task("400", type=4, reward={"ke": 20}, steps=[requirement()]),
"401": task("401", type=4, reward={"ke": 15})}
self.data = ProgressionData(config(self.tasks))
self.raw = snapshot(currentTasks=[]).raw
self.raw["master"]["money"] = 10000
self.raw["history"].update(loopTaskTime=snapshot().now, loopTaskNum=4, loopTask={"2": ["400"], "1": ["401"]}, unlockCity={"1": True, "2": True})
self.raw["stacks"] = [{"id": i + 1, "position": i % 3, "monsterId": 0} for i in range(10)]
self.quest = QuestPolicy(enabled=True, allow_monsters=True, allow_items=True)
self.ranch = Policy(buy=True, allow_single_draw=True, buy_batch=5)
self.folder = tempfile.TemporaryDirectory()
self.addCleanup(self.folder.cleanup)
def engine(self, *, raw=None, folder=None):
client = OfflineProcurementClient(raw or self.raw, self.catalog)
engine = Engine(self.catalog, client, Path(folder or self.folder.name) / "budget.json", game_data=self.data)
engine.snapshot = client.snapshot()
engine.policy, engine.quest_policy = deepcopy(self.ranch), deepcopy(self.quest)
engine._refresh_progression_cache(force=True)
self.assertEqual(engine._progression_error, "")
return engine, client
def sync(self, engine, client):
engine.snapshot = client.snapshot()
engine._refresh_progression_cache(force=True)
def intent(self, engine):
return next(i for i in engine._progression_intents if not i.block_reason)
def test_cross_city_twenty_buy_hatch_wait_submit_complete_replay(self):
engine, client = self.engine()
buy = self.intent(engine)
self.assertEqual((buy.kind, buy.phase, buy.source_task_type_id), ("progression_procure", "buy", "400"))
self.assertEqual(buy.payload["num"], 1)
offer = next(r for r in engine.commission_offer_diagnostics() if r["task_type_id"] == "400")
self.assertFalse(offer["eligible"])
self.assertTrue(offer["preparable"])
self.assertEqual(offer["resources"][0]["available"], 0)
engine._run_progression_intent(buy)
self.assertIsNone(engine.battle_journal.pending(engine.snapshot))
hatch = self.intent(engine)
self.assertEqual(hatch.phase, "hatch")
engine._run_progression_intent(hatch)
self.assertEqual(engine.snapshot.raw["history"]["loopTaskNum"], 4)
self.assertFalse(any(not i.block_reason for i in engine._progression_intents))
for _ in range(3):
self.sync(engine, client)
self.assertEqual([p for p, _ in client.writes], ["gachaService/gachaGetEggs", "stackService/stackAddMonster"])
client.raw["monsters"][0].update(mode=2)
self.sync(engine, client)
accept = self.intent(engine)
self.assertEqual((accept.kind, accept.payload["city"]), ("progression_loop_accept", 2))
engine._run_progression_intent(accept)
for _ in range(3):
engine._run_progression_intent(self.intent(engine))
self.assertEqual(engine.commission_history()["summary"]["confirmed_ke"], 20)
self.assertEqual(client.raw["history"]["loopTaskNum"], 3)
def test_one_missing_ten_empty_slots_thousand_eggs_hatches_only_one(self):
self.raw["items"] = [{"id": 500, "typeId": int(EGG), "num": 1000}]
engine, client = self.engine()
intent = self.intent(engine)
self.assertEqual(len(intent.payload["eggs"]), 1)
engine._run_progression_intent(intent)
self.assertEqual(sum(bool(s["monsterId"]) for s in client.raw["stacks"]), 1)
self.assertEqual(client.raw["items"][0]["num"], 999)
self.assertFalse(any(not i.block_reason for i in engine._progression_intents))
self.assertFalse(any(a.kind in ("buy", "hatch") for a in engine.plans()))
self.assertEqual(engine.pending_hatches, [])
def test_quota_zero_never_procures_or_accepts(self):
self.raw["history"]["loopTaskNum"] = 0
engine, client = self.engine()
engine._run_progression_intent()
self.assertEqual(client.writes, [])
self.assertTrue(all(r["reason_kind"] == "quota" and not r["preparable"] for r in engine.commission_offer_diagnostics()))
def test_existing_eggs_and_incubator_count_before_buy(self):
self.tasks["400"]["steps"] = [requirement(count=3)]
self.raw["items"] = [{"id": 500, "typeId": int(EGG), "num": 1}]
self.raw["monsters"] = [monster(self.catalog, 901, mode=0, process=2, timeStart=snapshot().now * 1000)]
self.raw["stacks"][0]["monsterId"] = 901
engine, client = self.engine()
engine._run_progression_intent(self.intent(engine)) # reuse the egg
buy = self.intent(engine)
self.assertEqual(buy.phase, "buy")
self.assertEqual(buy.payload["num"], 1)
engine._run_progression_intent(buy)
self.assertEqual(sum(p == "gachaService/gachaGetEggs" for p, _ in client.writes), 1)
def test_shared_eggs_user_reserve_and_multistep_demands_are_not_double_counted(self):
self.tasks["400"]["steps"] = [requirement("getItem", 1), requirement("getItem", 1), requirement(count=1)]
self.raw["items"] = [{"id": 500, "typeId": int(EGG), "num": 5}]
self.ranch.reserved_eggs = {EGG: 2}
engine, client = self.engine()
self.assertEqual(self.intent(engine).phase, "hatch")
engine._run_progression_intent(self.intent(engine))
self.assertEqual(client.raw["items"][0]["num"], 4) # 2 task eggs + 2 user reserve
self.assertFalse(any(not i.block_reason for i in engine._progression_intents))
self.assertFalse(any(path == "gachaService/gachaGetEggs" for path, _ in client.writes))
def test_multistep_adult_removals_cannot_reuse_one_monster(self):
self.tasks["400"]["steps"] = [requirement(), requirement()]
self.raw["monsters"] = [monster(self.catalog, 901)]
engine, _ = self.engine()
buy = self.intent(engine)
self.assertEqual(buy.payload["num"], 1)
self.assertEqual(engine.commission_offer_diagnostics()[0]["resources"][0]["needed"], 2)
def test_active_same_species_steps_buy_remaining_deficit_and_advance(self):
self.tasks["400"]["steps"] = [requirement(), requirement()]
for cursor in (1, 2):
with self.subTest(cursor=cursor), tempfile.TemporaryDirectory(dir=self.folder.name) as folder:
raw = deepcopy(self.raw)
raw["currentTasks"] = [{"id": 51, "typeId": "400", "curStep": cursor}]
engine, client = self.engine(raw=raw, folder=folder)
deficit = 3 - cursor
buy = self.intent(engine)
self.assertEqual((buy.kind, buy.phase, buy.source_task_id), ("progression_procure", "buy", 51))
self.assertEqual(buy.payload["num"], deficit)
engine._run_progression_intent(buy)
self.assertEqual(client.writes, [("gachaService/gachaGetEggs", buy.payload)])
self.assertIsNone(engine.battle_journal.pending(engine.snapshot))
for _ in range(deficit):
hatch = self.intent(engine)
self.assertEqual((hatch.kind, hatch.phase), ("progression_procure", "hatch"))
engine._run_progression_intent(hatch)
self.assertIsNone(engine.battle_journal.pending(engine.snapshot))
for _ in range(3):
engine._run_progression_intent()
self.assertEqual(len(client.writes), 1 + deficit)
self.assertEqual(client.raw["currentTasks"][0]["curStep"], cursor)
for growing in client.raw["monsters"]:
growing["mode"] = 2
self.sync(engine, client)
submitted = []
for number in range(cursor, 3):
submit = self.intent(engine)
self.assertEqual((submit.kind, submit.step_number), ("progression_step", number))
submitted.extend(submit.payload["removeIds"])
engine._run_progression_intent(submit)
self.assertEqual(client.raw["currentTasks"][0]["curStep"], number + 1)
local = self.intent(engine)
self.assertEqual(local.kind, "progression_local_step")
engine._run_progression_intent(local)
self.assertEqual(len(set(submitted)), deficit)
complete = self.intent(engine)
self.assertEqual(complete.kind, "progression_complete")
engine._run_progression_intent(complete)
purchases = [payload["num"] for path, payload in client.writes if path == "gachaService/gachaGetEggs"]
self.assertEqual(purchases, [deficit])
self.assertEqual(client.raw["currentTasks"], [])
self.assertEqual(client.raw["history"]["loopTaskNum"], 4)
self.assertEqual(engine.commission_history()["summary"]["confirmed_ke"], 20)
def test_active_procurement_keeps_future_handin_money_in_both_checks(self):
handin = 500
self.tasks["400"]["steps"] = [requirement(count=2),
step("getMoney", statusValue={"money": handin, "remove": True})]
self.raw["currentTasks"] = [{"id": 51, "typeId": "400", "curStep": 1}]
self.quest.max_money = handin
price = self.catalog.data["markets"]["sc_city1"]["money"]
self.raw["master"]["money"] = self.ranch.keep_money + handin + price
engine, client = self.engine()
buy = self.intent(engine)
self.assertEqual((buy.kind, buy.phase, buy.payload["num"]), ("progression_procure", "buy", 1))
engine._run_progression_intent(buy)
self.assertEqual(client.writes, [("gachaService/gachaGetEggs", buy.payload)])
self.assertEqual(client.raw["master"]["money"], self.ranch.keep_money + handin)
self.assertIsNone(engine.battle_journal.pending(engine.snapshot))
self.assertEqual(client.raw["currentTasks"][0]["curStep"], 1)
def test_protected_duplicates_are_reported_and_not_submitted(self):
self.raw["monsters"] = [monster(self.catalog, 1, lock=True), monster(self.catalog, 2),
monster(self.catalog, 3), monster(self.catalog, 4)]
self.raw["teams"] = [{"name": "teamA", "monsters": [2]}]
self.ranch.feed_targets = {"3": 1}
engine, client = self.engine()
info = self.data.task("400")
ready, ids, reason = engine.progression_planner.requirement(engine.snapshot, info["steps"][0], {},
engine._intent_policy({"task_type_id": "400"}), engine.policy)
self.assertTrue(ready)
self.assertEqual(ids, [4])
self.assertIn("保护3", reason)
self.assertIn("已锁定", reason)
engine._run_progression_intent(self.intent(engine))
engine._run_progression_intent(self.intent(engine))
self.assertEqual({m["id"] for m in client.raw["monsters"]}, {1, 2, 3})
def test_protected_star_species_cannot_be_procured_by_unprotecting(self):
self.ranch.protect_star = 2
engine, client = self.engine()
row = engine.commission_offer_diagnostics()[0]
self.assertFalse(row["eligible"] or row["preparable"])
self.assertIn("新孵魔物也受", row["reason"])
self.assertFalse(any(i.kind == "progression_procure" for i in engine._progression_intents))
self.assertEqual(client.writes, [])
def test_coin_reserve_daily_budget_and_ten_draw_rule_remain_enforced(self):
for changes in ({"daily_buy_money": 0}, {"keep_money": 10000}, {"allow_single_draw": False}):
with self.subTest(changes=changes):
self.ranch = Policy(buy=True, allow_single_draw=True, **{k: v for k, v in changes.items() if k != "allow_single_draw"})
if "allow_single_draw" in changes:
self.ranch.allow_single_draw = False
engine, client = self.engine()
self.assertFalse(any(i.kind == "progression_procure" for i in engine._progression_intents))
self.assertEqual(client.writes, [])
def test_stop_and_changed_offer_cancel_before_dispatch(self):
for change in (lambda e: e.cancel_progression(), lambda e: e.snapshot.raw["history"].update(loopTaskNum=0),
lambda e: e.snapshot.raw["history"].update(loopTask={}),
lambda e: e.snapshot.raw["currentTasks"].append({"id": 52, "typeId": "401", "curStep": 1})):
with self.subTest(change=change):
engine, client = self.engine()
intent = self.intent(engine)
original = engine._journal_commission
def change_before_dispatch(record, incoming):
original(record, incoming)
change(engine)
with patch.object(engine, "_journal_commission", side_effect=change_before_dispatch):
engine._execute_procurement(intent)
self.assertEqual(client.writes, [])
self.assertIsNone(engine.battle_journal.pending(engine.snapshot))
def test_active_task_changed_before_dispatch_is_cancelled(self):
self.raw["currentTasks"] = [{"id": 51, "typeId": "400", "curStep": 1}]
engine, client = self.engine()
intent = self.intent(engine)
original = engine._journal_commission
def replace_task(record, incoming):
original(record, incoming)
engine.snapshot.raw["currentTasks"] = [{"id": 52, "typeId": "400", "curStep": 1}]
with patch.object(engine, "_journal_commission", side_effect=replace_task):
engine._execute_procurement(intent)
self.assertEqual(client.writes, [])
self.assertIsNone(engine.battle_journal.pending(engine.snapshot))
def test_hard_prerequisite_is_not_misreported_as_preparable(self):
self.tasks["400"]["steps"][0]["condition"] = {"finishTask": ["999"]}
engine, client = self.engine()
row = engine.commission_offer_diagnostics()[0]
self.assertFalse(row["eligible"] or row["preparable"])
self.assertEqual(row["reason_kind"], "prerequisite")
self.assertFalse(any(i.kind == "progression_procure" for i in engine._progression_intents))
self.assertEqual(client.writes, [])
def test_ten_draw_cost_uses_verified_unit_price_without_fictitious_discount(self):
self.tasks["400"]["steps"] = [requirement(count=10)]
price = self.catalog.data["markets"]["sc_city1"]["money"]
self.ranch.daily_buy_money = price * 10
self.raw["master"]["money"] = self.ranch.keep_money + price * 10
engine, _ = self.engine()
buy = self.intent(engine)
self.assertEqual(buy.payload["num"], 10)
engine._run_progression_intent(buy)
self.assertEqual(engine.purchase_budget.spent(engine.snapshot.now), price * 10)
def test_unknown_buy_survives_restart_and_account_isolation(self):
engine, client = self.engine()
client.timeout = True
with self.assertRaises(TimeoutError):
engine._execute_procurement(self.intent(engine))
self.assertEqual(len(client.writes), 1)
restored, second = self.engine()
restored._run_progression_intent()
self.assertEqual(second.writes, [])
self.assertIsNotNone(restored.battle_journal.pending(restored.snapshot))
other = deepcopy(self.raw)
other["master"]["id"] = 2
isolated, _ = self.engine(raw=other)
self.assertIsNone(isolated.battle_journal.pending(isolated.snapshot))
with self.assertRaises(ValueError):
isolated._execute_procurement(self.intent(engine))
def test_mainline_confirmed_unlock_changes_offer_eligibility(self):
self.tasks["100"] = task("100", steps=[step()])
data = config(self.tasks)
data["game_setting"]["cityInfo"]["2"] = {"name": "测试城", "openTask": "100"}
planner = ProgressionPlanner(self.catalog, data)
raw = deepcopy(self.raw)
raw["history"]["unlockCity"]["2"] = False
raw["currentTasks"] = [{"id": 11, "typeId": "100", "curStep": 2}]
raw["monsters"] = [monster(self.catalog, 901)]
snap = Snapshot(raw)
before = planner.commission_offers(snap, self.quest, self.ranch)[0]
self.assertEqual(before["reason_kind"], "city_locked")
self.assertIn("测试城", before["reason"])
finish = planner.plan(snap, ProgressionPolicy(enabled=True), self.ranch)[0]
planner.acknowledge(snap, finish, {"reward": {}})
self.assertTrue(planner.commission_offers(snap, self.quest, self.ranch)[0]["eligible"])
def test_material_shortage_uses_real_supported_sweep_source(self):
self.tasks["400"]["steps"] = [requirement("getItem", 3, "30054")]
data = config(self.tasks, farming={"items": {"30054": [{"stage_id": "0101", "difficulty": 1}]}})
self.raw["history"]["passStage"] = {"0101": [1, 2, 3]}
planner = ProgressionPlanner(self.catalog, data)
actions = planner.commission_plan(Snapshot(self.raw), self.quest, self.ranch)
self.assertEqual(actions[0].kind, "sweep")
self.assertEqual(actions[0].source_task_type_id, "400")
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,194 @@
"""Offline coverage-tool regressions against the packaged original task data."""
from copy import deepcopy
import io
import json
from pathlib import Path
import tempfile
import threading
import time
import sys
import unittest
from unittest.mock import patch
from ranch_assistant.game_data import load_progression_data
from tools import check_progression_support as support
class ProgressionSupportTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.data = load_progression_data()
cls.cases = support.collect_cases(cls.data)
cls.priority = next(case for case in cls.cases if case.task == "1002013")
def test_every_mainline_and_commission_battle_step_is_resolved(self):
expected = {(str(key), number, step["statusType"])
for key, task in self.data.tasks.items() if task.get("type") in (1, 4)
for number, step in enumerate(task.get("steps") or (), 1)
if step.get("statusType") in ("battle", "passStage")}
self.assertEqual({(case.task, case.step, case.step_type) for case in self.cases}, expected)
self.assertEqual(len(self.cases), len(expected))
self.assertEqual({(case.task_type, case.step_type) for case in self.cases},
{(1, "battle"), (1, "passStage"), (4, "battle"), (4, "passStage")})
self.assertTrue(all(isinstance(case.battle, dict) and case.battle for case in self.cases))
def test_priority_task_uses_original_0216_level_one_configuration(self):
self.assertEqual((self.priority.task_type, self.priority.step, self.priority.step_type), (1, 1, "passStage"))
step = self.data.task("1002013")["steps"][0]
self.assertEqual(step["statusValue"], {"stage": "0216", "level": "1"})
self.assertEqual(self.priority.battle, self.data.stage_battle("0216", "1"))
self.assertEqual(self.priority.battle, self.data.task_battle("1002013", 1))
features = support.mechanics(self.priority.battle)
for reason in ("trigger:monDead", "trigger_effect:unlockWave", "unit_controller:monMaker",
"unit_controller:monSteps", "unit_controller:skill"):
self.assertGreater(features[reason], 0)
def test_structural_hotspots_count_configurations_separately_from_occurrences(self):
report = support.source_scan(self.cases)
self.assertEqual(report["count"], len(self.cases))
self.assertEqual(sum(row["count"] for row in report["counts"]), len(self.cases))
affected = {row["reason"]: row["count"] for row in report["mechanics"]}
occurrences = {row["reason"]: row["count"] for row in report["occurrences"]}
self.assertGreater(affected["unit_controller:hpArea"], 0)
self.assertGreater(occurrences["unit_controller:hpArea"], affected["unit_controller:hpArea"])
# Source mechanics are descriptive; they cannot themselves deny quick input.
self.assertNotIn("support", report)
def test_fixture_and_requests_preserve_original_source_and_roster(self):
roster = support.fixture_roster()
before = deepcopy((roster, self.priority.battle))
request = support.make_request(self.priority, roster)
self.assertEqual(request["context"], "task_pass_stage")
self.assertEqual(request["battle_position"], {"battleType": "task", "taskTypeId": "1002013", "taskStep": 0})
self.assertEqual(request["damage_profile"], "client_v4_x10")
self.assertEqual(support.make_request(self.priority, roster, damage_profile="original_1x")["damage_profile"],
"original_1x")
self.assertEqual(request["trace_limit"], 0)
self.assertIs(request["original_data"]["battle"], self.priority.battle)
self.assertEqual(roster["monsters"][0]["level"], 20)
self.assertEqual((roster, self.priority.battle), before)
def test_bounded_case_selection_includes_actual_protection_and_commission(self):
cases = support.representative_cases(self.cases, support.MAX_RUNS)
self.assertEqual(cases[0], self.priority)
self.assertEqual(len(cases), len({(case.task, case.step) for case in cases}))
self.assertTrue(any("objective:protectTarget" in support.mechanics(case.battle) for case in cases))
self.assertTrue(any(case.task_type == 4 and case.step_type == "battle" for case in cases))
self.assertTrue(any(case.task_type == 4 and case.step_type == "passStage" for case in cases))
self.assertEqual(support.representative_cases(self.cases, 0), [])
with self.assertRaises(ValueError):
support.representative_cases(self.cases, support.MAX_RUNS + 1)
def test_snapshot_loader_drops_identity_envelope_and_sanitizes_failures(self):
raw = support.fixture_roster()
raw.update(token="private-token-canary", account="private-account-canary")
raw["master"].update(id=987654321, nickname="private-nickname-canary")
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "private-path-canary.json"
path.write_text(json.dumps({"raw": raw}), encoding="utf-8")
loaded = support.load_snapshot(path)
self.assertEqual(loaded, support.fixture_roster())
path.write_text('{"token":"private-token-canary",broken', encoding="utf-8")
with self.assertRaisesRegex(ValueError, "^snapshot_load_failed$"):
support.load_snapshot(path)
with self.assertRaisesRegex(ValueError, "^snapshot_load_failed$"):
support.load_snapshot(path.with_suffix(".missing"))
def test_reports_keep_anomaly_counts_separate_from_input_support(self):
private = "private-result-canary"
raw = {"supported": True, "outcome": "loss", "elapsed_ms": 420,
"reasons": [], "units": [{"id": private}], "battle_data": {"monsterIds": [private]},
"anomalies": [{"code": "+15overpoten", "monsterId": private}] * 4,
"token": private, "events": [{"message": private}]}
result = support.result_summary(raw)
self.assertTrue(result["support"])
self.assertEqual(result["outcome"], "loss")
self.assertEqual(result["counts"], [{"reason": "anomaly:+15overpoten", "count": 4}])
self.assertNotIn(private, json.dumps(result))
raw.update(supported=False, reasons=[private], outcome=private)
raw["anomalies"] = [{"code": private}]
result = support.result_summary(raw)
self.assertNotIn(private, json.dumps(result))
self.assertEqual(result["reason"], ["input_or_model_failure"])
self.assertEqual(result["outcome"], "error")
def test_inspection_cancellation_and_deadline_do_not_run_the_model(self):
runtime = unittest.mock.Mock()
stop = threading.Event()
stop.set()
cancelled = support.inspect_inputs(self.cases, runtime, cancel_event=stop)
self.assertEqual(cancelled["reason"], ["cancelled"])
expired = support.inspect_inputs(self.cases, runtime, deadline=time.monotonic() - 1)
self.assertEqual(expired["reason"], ["budget_exhausted"])
runtime.inspect.assert_not_called()
runtime.run.assert_not_called()
def test_private_model_output_and_exceptions_are_not_logged(self):
private = "private-runtime-canary"
runtime = unittest.mock.Mock()
def run(request, **kwargs):
print(private)
print(private, file=sys.stderr)
raise ValueError(private)
runtime.run.side_effect = run
stdout, stderr = io.StringIO(), io.StringIO()
with patch.object(sys, "stdout", stdout), patch.object(sys, "stderr", stderr):
rows = support.replay_cases([self.priority], runtime, support.fixture_roster())
self.assertEqual((stdout.getvalue(), stderr.getvalue()), ("", ""))
self.assertNotIn(private, json.dumps(rows))
self.assertEqual(rows[0]["outcome"], "error")
self.assertEqual(rows[0]["reason"], ["model_execution_failed"])
def test_replay_uses_web_profile_and_wire_step_without_changing_a_loss(self):
runtime = unittest.mock.Mock()
runtime.run.return_value = {"supported": True, "outcome": "loss", "elapsed_ms": 1000,
"reasons": [], "anomalies": []}
rows = support.replay_cases([self.priority], runtime, support.fixture_roster())
self.assertEqual(rows[0]["outcome"], "loss")
request = runtime.run.call_args.args[0]
self.assertEqual(request["damage_profile"], "client_v4_x10")
self.assertEqual(request["battle_position"]["taskStep"], 0)
self.assertLessEqual(runtime.run.call_args.kwargs["timeout"], 1)
def test_structure_only_cli_never_imports_or_runs_a_model(self):
stdout = io.StringIO()
with patch.object(support, "collect_cases", return_value=self.cases), \
patch.object(sys, "stdout", stdout), \
patch.object(support.importlib, "import_module", side_effect=AssertionError("model import")):
self.assertEqual(support.main(["--structure-only"]), 0)
report = json.loads(stdout.getvalue())
self.assertEqual(report["source"]["count"], len(self.cases))
self.assertLessEqual(len(report["source"]["mechanics"]), support.TOP)
def test_quick_input_counts_follow_current_model_over_the_original_corpus(self):
from ranch_assistant import battle_simulator
runtime = support.quick_runtime()
with patch.object(battle_simulator, "simulate", side_effect=AssertionError("detailed model")):
report = support.inspect_inputs(self.cases, runtime)
self.assertEqual(report["reason"], [])
self.assertEqual(report["count"], len(self.cases))
self.assertEqual(sum(row["count"] for row in report["counts"]), len(self.cases))
self.assertTrue(report["priority"][0]["support"])
# Numeric inputs can remain unsupported. Never freeze an all-supported total.
blocked = [row for row in report["rows"] if not row["support"]]
self.assertTrue(all(row["reason"] for row in blocked))
self.assertEqual(len(blocked), sum(row["count"] for row in report["counts"] if not row["support"]))
def test_original_priority_and_protection_cases_have_fast_natural_results(self):
from ranch_assistant import battle_simulator
protection = next(case for case in self.cases if case.task == "1002002" and case.step == 2)
roster = support.fixture_roster()
before = deepcopy((roster, self.priority.battle, protection.battle))
with patch.object(battle_simulator, "simulate", side_effect=AssertionError("detailed model")):
rows = support.replay_cases([self.priority, protection], support.quick_runtime(), roster)
self.assertEqual([row["outcome"] for row in rows], ["loss", "win"])
self.assertTrue(all(row["support"] for row in rows))
self.assertTrue(all(0 < row["wall_ms"] < 1000 for row in rows))
self.assertTrue(all(row["elapsed_ms"] > 0 for row in rows))
self.assertEqual((roster, self.priority.battle, protection.battle), before)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,73 @@
"""Offline cultivation-bound checks using public tables and synthetic monsters."""
from copy import deepcopy
from types import SimpleNamespace
import unittest
from ranch_assistant.battle_simulator import _snapshot_anomalies, combat_tables
class SnapshotPotentialAnomalyTests(unittest.TestCase):
def snapshot(self, *, species=5208010, **changes):
tables = combat_tables()
row = tables["monster_info"][str(species)]
mon = {"id": 100001, "typeId": species, "level": 1, "potentialLevel": 3,
"tpLevel": 0, "feel": 0, "upStar": 0,
"pAtk": 0, "pDef": 0, "pHp": 0, "pDex": 0}
mon.update(changes)
unit = SimpleNamespace(key="player-1", species=species,
stats=SimpleNamespace(atk=row["atk"], defense=row["def"],
hp=row["hp"], dex=row["dex"]))
return mon, unit, tables
def test_cultivated_potential_at_zero_tp_is_valid(self):
# PotentialPanel.as:102,245: job=1, star=5, potentialLevel=3
# permits atk=64, def=58, hp=510, dex=22, independently of tpLevel.
mon, unit, tables = self.snapshot(pAtk=38, pDef=44, pHp=300, pDex=22)
before = deepcopy((mon, unit))
self.assertEqual(_snapshot_anomalies(mon, unit, tables), [])
self.assertEqual((mon, unit), before)
def test_all_four_excesses_keep_blocking_records(self):
# Preserve the existing strict > 1.5 * cultivation-cap check.
mon, unit, tables = self.snapshot(pAtk=97, pDef=88, pHp=766, pDex=34)
before = deepcopy((mon, unit))
records = _snapshot_anomalies(mon, unit, tables)
self.assertEqual([r["code"] for r in records], ["+15overpoten"] * 4)
self.assertEqual({r["stat"]: (r["value"], r["source_maximum"]) for r in records},
{"atk": (97, 96), "def": (88, 87),
"hp": (766, 765), "dex": (34, 33)})
self.assertTrue(all(r["source_cheat_points"] == 30 for r in records))
self.assertEqual((mon, unit), before)
def test_tp_and_display_star_cannot_hide_uncultivated_excess(self):
for tp in (0, 4, 8):
with self.subTest(tp=tp):
mon, unit, tables = self.snapshot(potentialLevel=1, tpLevel=tp,
upStar=2, pAtk=19)
records = _snapshot_anomalies(mon, unit, tables)
self.assertEqual(len(records), 1)
self.assertEqual(records[0]["code"], "+15overpoten")
self.assertEqual(records[0]["source_maximum"], 18)
def test_existing_tolerance_boundary_is_preserved(self):
mon, unit, tables = self.snapshot(pAtk=96, pDef=87, pHp=765, pDex=33)
self.assertEqual(_snapshot_anomalies(mon, unit, tables), [])
mon["pDex"] = 33.25
records = _snapshot_anomalies(mon, unit, tables)
self.assertEqual(len(records), 1)
self.assertEqual(records[0]["value"], 33.25)
def test_other_source_anomalies_and_temporary_id_exemption_remain(self):
mon, unit, tables = self.snapshot(level=31, feel=201, pAtk=1000000)
unit.stats.atk = 1000000
before = deepcopy((mon, unit))
records = _snapshot_anomalies(mon, unit, tables)
self.assertEqual({r["code"] for r in records},
{"+15overfeel", "+15overgrow", "+15overpoten", "+50overlv"})
self.assertEqual((mon, unit), before)
mon["id"] = 99998
self.assertEqual(_snapshot_anomalies(mon, unit, tables), [])
if __name__ == "__main__":
unittest.main()
+13 -1
View File
@@ -4,7 +4,7 @@
把现有桌面助手的功能和操作结构迁移至单管理员 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 仅整理设置页重复运行提示,保留账号简短状态、错误、表格、表单与原单一底部分类日志;后端、日志及策略逻辑不变,21项相关测试通过,历史结果不计入本补丁,见 [本版发布说明](../analysis/RELEASE_2_0_9.md)。
2.0.9 包含界面清理、委托补缺、默认快速战斗与潜能误报修复;保留账号简短状态、错误、表格、表单与原单一底部分类日志,见 [本版发布说明](../analysis/RELEASE_2_0_9.md)。
使用者在 Windows 本机配置、验证,随后可在 Linux Docker 常驻运行。多个浏览器访问同一个管理员工作台;账号互相隔离,各账号串行执行,账号之间可以并行。
@@ -28,6 +28,14 @@
- 帮助可检查 GitHub 正式版本并提交受控更新请求。未配置部署器时明确显示原因,更新提交不表示更新成功。
- 已在 2.0.1 完成私有仓库和 GHCR 认证的部署,稳定 Release 与正式镜像发布后,可直接通过“帮助 → 检查版本更新…”升级,无需先安装 2.0.2、重复初始化或替换宿主机更新器;升级完成后刷新网页以加载新版界面,安装结果以宿主机健康检查为准。
## 2.0.9 本轮范围
默认使用快速数值模型,委托按剩余步骤统一计算采购和提交需求:
- 委托用明确中文说明未接取的实际原因;成熟魔物交付需求联动购蛋、孵化,优先备齐所需资源再接取。锁定、培养、优质备份等魔物继续受保护,采购与孵蛋遵守耗用预算和需求缺口限制。
- 正常执行默认使用现有内置实验运行时入口的快速 HP/DPS 模型,保留现有伤害配置,无需选择新模式;逐帧实现仅供研发。模型结合双方属性、血量、每秒伤害(DPS)、有效血量(EHP)、时间与关卡目标估算胜利、战败或超时,仍有机制简化,不保证全部关卡可通关或与客户端结果一致。
- 潜能检查依据合法的 `PotentialPanel` 上限区分正常数值与异常,修复正常潜能的误报。
## 2.0.8 自动委托与每日历史
- 自动委托包含“当前委托 / 每日记录”。当前页展示原始候选、任务状态、标注奖励及选择 / 回退原因;城市锁定候选显示不可接取。
@@ -81,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 负责。
+7 -1
View File
@@ -2,7 +2,9 @@
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 仅整理设置页重复运行提示,21项相关测试通过,历史结果不计入本补丁,见 [本版发布说明](../analysis/RELEASE_2_0_9.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)。多浏览器连接同一个管理员工作台;一个服务实例内,各账号独立线程并行,同一账号操作串行。
@@ -110,6 +112,10 @@ Web 检查固定官方 GitHub Releases 的稳定 `v2.x.y`,跳过桌面 1.x、
## 离线验证
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)
@@ -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()
+10 -4
View File
@@ -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__":
+45 -10
View File
@@ -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 氪金委托"}
+402
View File
@@ -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())