Files
lc-mcp/tests/test_event_choices.py
T
ywsandClaude Opus 5.5 51525722cd P2-8 镜牢局内决策写入审计日志
- 新增 lc_mcp/decisions.py:每个决策追加一行 JSON(time/stage/choice/reason + 细节),
  写失败只丢该行;summarize 按 stage/reason 计数
- TaskRunner 用 LCP_DECISIONS 把 task_*.decisions.jsonl 路径交给子进程,
  task_status 返回 decisions.counts,清理旧日志时一并删除
- 选队/键盘寻路/饰品/事件补丁记录各自决策;商店购买与卡包选择用只观察的补丁记录
  (购买按钮点中前的商品;卡包取自上游日志里的选择结果与权重)
- 抽出 _override 统一临时替换 auto 方法并在结束时还原

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 07:11:30 +00:00

298 lines
14 KiB
Python

# -*- coding: utf-8 -*-
"""镜牢事件按选项表选择(BACKLOG P1-4)。
2026-11-14 核对: Mirror.event_handling() 不认事件, 最后总是点第一个选项。补丁在上游每轮挑选项前
认事件、按表点; 端到端用例执行上游真实的 event_handling。
"""
import ast
import json
import os
import sys
import tempfile
import time
import types
import unittest
from pathlib import Path
from types import SimpleNamespace
from unittest import mock
REPO = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO))
from lc_mcp import aalc_patches as ap # noqa: E402
MIRROR = REPO / 'vendor' / 'aalc' / 'tasks' / 'mirror' / 'mirror.py'
SCALE = 720 / 1440
MARKER_X = 699 # 选项框左边缘(1280x720, 由 2560 模板换算)
ROW_GAP = 60
def markers(count):
return [(MARKER_X, 200 + ROW_GAP * i) for i in range(count)]
def rule(name='e', match=('事件名',), text=(), index=None):
return {'name': name, 'match': tuple(match), 'text': tuple(text), 'index': index}
class EventOptionsTest(unittest.TestCase):
def test_lines_attach_to_the_nearest_option_on_the_right(self):
lines = [('你是特别的', 900, 200),
('你不是', 900, 255), ('特别的。', 1000, 265), # 一项换成两行
('离开', 900, 322),
('侧耳倾听', 300, 260), # 左边的叙述文字不算选项
('梦中的电子羊', 200, 60)] # 标题
options = ap.event_options(list(reversed(markers(3))), lines, SCALE)
self.assertEqual([text for _, text in options], ['你是特别的', '你不是特别的。', '离开'])
self.assertEqual([pos for pos, _ in options], markers(3))
def test_text_far_below_the_last_option_is_ignored(self):
options = ap.event_options(markers(1), [('继续', 900, 200 + 31)], SCALE)
self.assertEqual(options[0][1], '')
def test_first_matching_rule_wins(self):
rules = [rule('折射', ('折射的往昔的睡袋',), index=1), rule('睡袋', ('往昔的睡袋',), index=2)]
self.assertEqual(ap.match_event_rule(rules, [('折射的往昔的睡袋', 200, 60)])['name'], '折射')
self.assertEqual(ap.match_event_rule(rules, [('往昔的 睡袋', 200, 60)])['name'], '睡袋')
self.assertIsNone(ap.match_event_rule(rules, [('别的事件', 200, 60)]))
def test_text_beats_index(self):
self.assertEqual(ap.choose_event_option(rule(text=('不是特别',), index=1), ('是特别', '不是特别的')),
(1, 'text', '选项文字含「不是特别」'))
self.assertEqual(ap.choose_event_option(rule(text=('没有',), index=2), ('a', 'b'))[:2], (1, 'index'))
self.assertEqual(ap.choose_event_option(rule(index=4), ('a', 'b', 'c')),
(None, None, '表里是第 4 项, 画面上只有 3 项'))
self.assertEqual(ap.choose_event_option(rule(text=('没有',)), ('a',))[:2], (None, None))
class EventTableTest(unittest.TestCase):
def test_shipped_table_is_valid_and_has_at_least_five_events(self):
rules = ap.load_event_choices()
self.assertGreaterEqual(len(rules), 5)
names = [r['name'] for r in rules]
self.assertLess(names.index('折射的往昔的睡袋'), names.index('往昔的睡袋'))
def test_shipped_events_come_from_the_event_reference(self):
reference = (REPO / 'docs/skills/limbus-mirror-speedrun/references/event-choices.md').read_text(encoding='utf-8')
for r in ap.load_event_choices():
with self.subTest(event=r['name']):
self.assertTrue(any(word in reference for word in r['match']))
def test_bad_tables_raise_value_error(self):
bad = ['[]', '{"events": {}}', '{"events": [1]}',
'{"events": [{"name": "a", "match": ["x"]}]}',
'{"events": [{"name": "a", "match": [], "index": 1}]}',
'{"events": [{"name": "a", "match": ["x"], "index": 0}]}',
'{"events": [{"name": "a", "match": ["x"], "index": true}]}',
'{"events": [{"name": "a", "match": "x", "index": 1}]}']
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, 'e.json')
for content in bad:
with self.subTest(content=content):
with open(path, 'w', encoding='utf-8') as f:
f.write(content)
with self.assertRaises(ValueError):
ap.load_event_choices(path)
class EventScreen:
"""事件界面: 依次几屏选项, 点了一项就进下一屏, 最后回到地图。"""
def __init__(self, title, screens, ignore_clicks=0):
self.title = title
self.screens = [list(s) for s in screens]
self.stage = 0
self.ignore_clicks = ignore_clicks
self.chosen = []
self.model = None
self.screenshot = object()
@property
def options(self):
return self.screens[self.stage] if self.stage < len(self.screens) else None
def take_screenshot(self):
return self.screenshot
def mouse_to_blank(self, *args, **kwargs):
pass
def find_element(self, target, find_type='image', threshold=0.8, **kwargs):
options = self.options
if target == 'mirror/road_in_mir/legend_assets.png':
return options is None
if target == ap.EVENT_OPTION and options:
return markers(len(options)) if find_type == 'image_with_multiple_targets' else markers(1)[0]
if target == 'event/choices_assets.png':
return bool(options)
return [] if find_type == 'image_with_multiple_targets' else False
def click_element(self, target, **kwargs):
if target == ap.EVENT_OPTION and self.options:
self.mouse_click(*markers(1)[0])
return True
return False
def mouse_click(self, x, y):
if not self.options:
return
self.chosen.append(markers(len(self.options)).index((x, y)))
if self.ignore_clicks:
self.ignore_clicks -= 1
return
self.stage += 1
def find_language_text(self, *args, **kwargs):
return False
def find_text_element(self, *args, **kwargs):
return False
def run(self, image):
lines = [(self.title, 200, 60)]
for (x, y), text in zip(markers(len(self.options or ())), self.options or ()):
lines.append((text, x + 200, y))
return SimpleNamespace(txts=tuple(t for t, _, _ in lines),
boxes=[[[x - 10, y - 5], [x + 10, y - 5], [x + 10, y + 5], [x - 10, y + 5]]
for _, x, y in lines])
@unittest.skipUnless(MIRROR.is_file(), 'vendor/aalc 子模块未检出')
class UpstreamEventHandlingTest(unittest.TestCase):
"""执行上游真实的 Mirror.event_handling, 看每屏点了第几项。"""
def setUp(self):
self.lines = []
tree = ast.parse(MIRROR.read_text(encoding='utf-8'))
cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == 'Mirror')
self.fn_node = next(n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == 'event_handling')
def play(self, title, screens, patched=True, env=None, ignore_clicks=0):
screen = EventScreen(title, screens, ignore_clicks=ignore_clicks)
cfg = SimpleNamespace(set_win_size=720)
ns = dict(auto=screen, retry=lambda: True, log=mock.Mock(), time=time, back_init_menu=mock.Mock(),
ImageUtils=SimpleNamespace(get_bbox=lambda image: (0, 0, 10, 10), load_image=lambda path: None))
exec(compile(ast.Module(body=[self.fn_node], type_ignores=[]), str(MIRROR), 'exec'), ns)
method = ns['event_handling']
ns['event_handling'] = SimpleNamespace(decision_event_handling=lambda: False) # 上游模块同名
mirror_cls = type('Mirror', (), {'event_handling': method})
mirror_mod = types.ModuleType('tasks.mirror.mirror')
mirror_mod.Mirror = mirror_cls
package = types.ModuleType('tasks.mirror')
package.mirror = mirror_mod
modules = {'tasks': types.ModuleType('tasks'), 'tasks.mirror': package, 'tasks.mirror.mirror': mirror_mod,
'module': types.ModuleType('module'),
'module.automation': SimpleNamespace(auto=screen),
'module.config': SimpleNamespace(cfg=cfg),
'module.ocr': SimpleNamespace(ocr=screen)}
with mock.patch.dict(sys.modules, modules):
if patched:
self.assertIsNotNone(ap.install_event_choices(log=self.lines.append, env=env or {}))
mirror = mirror_cls()
mirror.event_total_time, mirror.event_times = 0, 0
mirror.event_handling()
self.assertEqual(mirror.event_times, 1)
self.assertNotIn('click_element', vars(screen), 'click_element 必须还原')
return screen.chosen
@property
def log(self):
return '\n'.join(self.lines)
def test_option_text_overrides_the_first_option(self):
options = [['你是特别的', '你不是特别的。', '离开']]
self.assertEqual(self.play('梦中的电子羊', options, patched=False), [0])
self.assertEqual(self.play('梦中的电子羊', options), [1])
self.assertIn('事件 梦中的电子羊: 1=你是特别的 | 2=你不是特别的。 | 3=离开; 选第 2 项(选项文字含「你不是特别的」)',
self.log)
def test_decisions_are_recorded_once_per_screen(self):
with mock.patch.object(ap.decisions, 'record') as record:
self.play('梦中的电子羊', [['你是特别的', '你不是特别的。']])
self.play('没见过的事件', [['战斗', '离开']])
self.assertEqual(record.call_args_list, [
mock.call('event', 2, 'text', event='梦中的电子羊', options=['你是特别的', '你不是特别的。'],
why='选项文字含「你不是特别的」'),
mock.call('event', None, 'not_in_table', options=['战斗', '离开'])])
def test_unknown_event_behaves_like_upstream(self):
options = [['战斗', '离开']]
self.assertEqual(self.play('没见过的事件', options), self.play('没见过的事件', options, patched=False))
self.assertIn('事件选项: 1=战斗 | 2=离开; 表里没有这个事件, 交给 AALC', self.log)
def test_index_rule(self):
self.assertEqual(self.play('浸染棉花', [['判定', '战斗', '离开']]), [2])
def test_index_beyond_the_options_falls_back(self):
self.assertEqual(self.play('破碎罗盘', [['a', 'b', 'c']]), [0])
self.assertIn('表里是第 4 项, 画面上只有 3 项, 交给 AALC', self.log)
def test_refracted_variant_is_matched_first(self):
self.assertEqual(self.play('折射的往昔的睡袋', [['判定', '全体降理智']]), [0])
self.assertEqual(self.play('往昔的睡袋', [['判定', '恢复']]), [1])
def test_index_only_applies_to_the_first_screen(self):
self.assertEqual(self.play('鸡群的激情探戈', [['判定', '探戈蘸酱'], ['好', '不好']]), [1, 0])
self.assertIn('编号只用于第一屏选项', self.log)
def test_index_click_is_retried_while_the_screen_is_unchanged(self):
self.assertEqual(self.play('终末日历', [['判定', '离开']], ignore_clicks=1), [1, 1])
def test_env_zero_keeps_upstream(self):
self.assertIsNone(ap.install_event_choices(log=self.lines.append, env={ap.EVENT_CHOICES_ENV: '0'}))
class InstallEventChoicesTest(unittest.TestCase):
def setUp(self):
self.lines = []
self.original = mock.Mock(side_effect=RuntimeError('boom'))
self.mirror_cls = type('Mirror', (), {'event_handling': self.original})
mirror_mod = types.ModuleType('tasks.mirror.mirror')
mirror_mod.Mirror = self.mirror_cls
package = types.ModuleType('tasks.mirror')
package.mirror = mirror_mod
self.auto = SimpleNamespace(click_element=mock.Mock(return_value=False))
modules = {'tasks': types.ModuleType('tasks'), 'tasks.mirror': package, 'tasks.mirror.mirror': mirror_mod,
'module': types.ModuleType('module'),
'module.automation': SimpleNamespace(auto=self.auto),
'module.config': SimpleNamespace(cfg=SimpleNamespace(set_win_size=720))}
patcher = mock.patch.dict(sys.modules, modules)
patcher.start()
self.addCleanup(patcher.stop)
def test_click_element_is_restored_after_an_exception(self):
real = self.auto.click_element
ap.install_event_choices(log=self.lines.append, env={})
with self.assertRaises(RuntimeError):
self.mirror_cls().event_handling()
self.assertIs(self.auto.click_element, real)
def test_unreadable_table_is_an_error(self):
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, 'e.json')
with open(path, 'w', encoding='utf-8') as f:
json.dump({'events': [{'name': 'a', 'match': ['x']}]}, f)
self.assertIsNone(ap.install_event_choices(log=self.lines.append, env={ap.EVENT_CHOICES_ENV: path}))
self.assertIs(self.mirror_cls.event_handling, self.original)
self.assertTrue(self.lines[0].startswith('[ERROR] [lc_mcp] 事件选项表补丁跳过'))
def test_decision_error_falls_back_to_upstream_click(self):
calls = []
def original(mirror):
calls.append(self.auto.click_element(ap.EVENT_HOOK))
self.mirror_cls.event_handling = original
self.auto.find_element = mock.Mock(side_effect=RuntimeError('template'))
ap.install_event_choices(log=self.lines.append, env={})
self.mirror_cls().event_handling()
self.assertEqual(calls, [False])
self.auto.click_element.assert_called_once_with(ap.EVENT_HOOK)
self.assertIn('事件选项表出错(RuntimeError: template)', '\n'.join(self.lines))
if __name__ == '__main__':
unittest.main()