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>
This commit is contained in:
+167
-27
@@ -13,6 +13,7 @@
|
||||
检查客户区尺寸, 偏离 set_win_size 时调回去。
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import threading
|
||||
@@ -20,6 +21,8 @@ import time
|
||||
import unicodedata
|
||||
from contextlib import contextmanager
|
||||
|
||||
from .decisions import decisions
|
||||
|
||||
TEAM_TARGET = re.compile(r'(?:TEAMS|TFAMS|编队)#(\d+)', re.IGNORECASE)
|
||||
|
||||
|
||||
@@ -597,7 +600,9 @@ def _select_team_by_name(auto, names, log=print, rounds=4):
|
||||
if team_name_match(t, names) == 'exact']
|
||||
if current: # 已经是这支队就不用动列表; 带后缀的队名要回列表里确认唯一后再点
|
||||
log('[lc_mcp] patch: 当前已经是编队 %s, 无需切换' % current[0])
|
||||
decisions.record('team', current[0], 'current', wanted=list(names))
|
||||
return True
|
||||
seen = []
|
||||
auto.mouse_click(1, 1)
|
||||
time.sleep(0.3)
|
||||
_scroll_team_list(auto, +1) # 先回到顶部
|
||||
@@ -606,6 +611,7 @@ def _select_team_by_name(auto, names, log=print, rounds=4):
|
||||
log('[lc_mcp] 第 %d 屏截图失败' % round_index)
|
||||
continue
|
||||
items = [item for item in _team_ocr(auto) if _in_list(item[1], item[2])]
|
||||
seen.append(_list_names(items))
|
||||
hit, reason = pick_team_item(items, names)
|
||||
if hit:
|
||||
text, x, y = hit
|
||||
@@ -614,15 +620,18 @@ def _select_team_by_name(auto, names, log=print, rounds=4):
|
||||
auto.mouse_action_with_pos([x, y], offset=False)
|
||||
if _wait_header(auto, (label,)):
|
||||
log('[lc_mcp] patch: 已按体系名选中编队 %s' % label)
|
||||
decisions.record('team', label, team_name_match(label, names), wanted=list(names))
|
||||
return True
|
||||
log('[lc_mcp] 点了 %s 但顶栏没变(顶栏读到: %s), 继续往下翻'
|
||||
% (label, '/'.join(normalize_team_name(t) for t in _header_texts(auto) or ()) or '无'))
|
||||
header = [normalize_team_name(t) for t in _header_texts(auto) or ()]
|
||||
log('[lc_mcp] 点了 %s 但顶栏没变(顶栏读到: %s), 继续往下翻' % (label, '/'.join(header) or '无'))
|
||||
decisions.record('team', label, 'header_unchanged', wanted=list(names), header=header)
|
||||
else:
|
||||
log('[lc_mcp] 第 %d 屏没有 %s%s; 这一屏的名字: %s'
|
||||
% (round_index, '/'.join(names), ', ' + reason if reason else '',
|
||||
'/'.join(_list_names(items)) or '(空)'))
|
||||
_scroll_team_list(auto, -1, times=3)
|
||||
log('[lc_mcp] 编队列表里没找到 %s(共 %d 轮)' % ('/'.join(names), rounds))
|
||||
decisions.record('team', None, 'not_found', wanted=list(names), seen=seen)
|
||||
return False
|
||||
|
||||
|
||||
@@ -801,21 +810,28 @@ def install_typed_keyboard_road(log=print, env=None):
|
||||
ranked = rank_next_nodes(bus, nodes, cfg.set_win_size / 1440, weights, column_gap, row_gap)
|
||||
except Exception as e:
|
||||
log('[lc_mcp] 键盘寻路: 识别下一列节点出错(%s: %s), 退回按 ↑' % (type(e).__name__, e))
|
||||
decisions.record('road', 'up', 'fallback', why='%s: %s' % (type(e).__name__, e))
|
||||
return original()
|
||||
if not ranked:
|
||||
log('[lc_mcp] 键盘寻路: %s, 退回按 ↑' % ('没找到巴士' if not bus else '下一列没识别到节点'))
|
||||
why = '没找到巴士' if not bus else '下一列没识别到节点'
|
||||
log('[lc_mcp] 键盘寻路: %s, 退回按 ↑' % why)
|
||||
decisions.record('road', 'up', 'fallback', why=why)
|
||||
return original()
|
||||
log('[lc_mcp] 键盘寻路: 下一列 %s, 按权重从低到高依次尝试'
|
||||
% ' '.join('%s=%s(%d)' % item for item in ranked))
|
||||
candidates = ['%s=%s(%d)' % item for item in ranked]
|
||||
log('[lc_mcp] 键盘寻路: 下一列 %s, 按权重从低到高依次尝试' % ' '.join(candidates))
|
||||
for direction, kind, weight in ranked:
|
||||
auto.key_press(ROAD_KEYS[direction])
|
||||
time.sleep(1)
|
||||
if road._keyboard_enter_succeeded():
|
||||
reason = '下一列中最低' if direction == ranked[0][0] else '更优的方向没能进入'
|
||||
best = direction == ranked[0][0]
|
||||
reason = '下一列中最低' if best else '更优的方向没能进入'
|
||||
log('[lc_mcp] 键盘寻路: 进入 %s 方向的 %s(权重 %d, %s)' % (direction, kind, weight, reason))
|
||||
decisions.record('road', '%s:%s' % (direction, kind), 'lowest' if best else 'next_best',
|
||||
candidates=candidates)
|
||||
return True
|
||||
log('[lc_mcp] 键盘寻路: %s 方向的 %s 没能进入, 试下一个' % (direction, kind))
|
||||
log('[lc_mcp] 键盘寻路: 按类型都没进入, 退回按 ↑')
|
||||
decisions.record('road', 'up', 'fallback', why='按类型都没进入', candidates=candidates)
|
||||
return original()
|
||||
|
||||
road.search_road_simple_keyboard = search_road_simple_keyboard
|
||||
@@ -824,6 +840,25 @@ def install_typed_keyboard_road(log=print, env=None):
|
||||
return original
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 临时替换 auto 的方法
|
||||
|
||||
_MISSING = object()
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _override(obj, name, value):
|
||||
"""在 with 期间把 obj.name 换成 value(实例属性), 结束时还原成原来的实例属性或类方法。"""
|
||||
own = vars(obj).get(name, _MISSING)
|
||||
setattr(obj, name, value)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if own is _MISSING:
|
||||
vars(obj).pop(name, None)
|
||||
else:
|
||||
setattr(obj, name, own)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 饰品选择按体系关键词
|
||||
|
||||
# 2026-11-14 核对: acquire_ego_gift() 两张卡时只看白棉花和已持有, 拿第一张; 三张卡时虽然用
|
||||
@@ -933,11 +968,14 @@ def install_gift_preference(log=print, env=None):
|
||||
by_x = sorted(range(len(cards)), key=lambda i: float(cards[i][0])) # 日志按从左到右编号
|
||||
detail = ' '.join('第%d张=%d%s' % (n + 1, len(hits[i]), '(%s)' % '/'.join(hits[i]) if hits[i] else '')
|
||||
for n, i in enumerate(by_x))
|
||||
first = by_x.index(order[0]) + 1
|
||||
if any(hits):
|
||||
log('[lc_mcp] 饰品选择(体系 %s): %s; 命中体系关键词, 先看第%d张'
|
||||
% (system, detail, by_x.index(order[0]) + 1))
|
||||
log('[lc_mcp] 饰品选择(体系 %s): %s; 命中体系关键词, 先看第%d张' % (system, detail, first))
|
||||
else:
|
||||
log('[lc_mcp] 饰品选择(体系 %s): %s; 未命中体系关键词, 保持原顺序' % (system, detail))
|
||||
# 上游随后还会跳过白棉花、把已持有排后, 这里记的是交给上游的第一顺位
|
||||
decisions.record('gift', first, 'keyword' if any(hits) else 'no_keyword', system=system,
|
||||
hits=[hits[i] for i in by_x])
|
||||
return [cards[i] for i in order]
|
||||
|
||||
def acquire_ego_gift(self, *args, **kwargs):
|
||||
@@ -946,7 +984,6 @@ def install_gift_preference(log=print, env=None):
|
||||
if kwargs.get('type', args[0] if args else 1) != 1 or not keywords: # type=2 是"拒绝饰品"界面
|
||||
return original(self, *args, **kwargs)
|
||||
real = auto.find_element
|
||||
own = vars(auto).get('find_element')
|
||||
|
||||
def find_element(target, *a, **kw):
|
||||
found = real(target, *a, **kw)
|
||||
@@ -958,14 +995,8 @@ def install_gift_preference(log=print, env=None):
|
||||
log('[lc_mcp] 饰品选择: 关键词排序出错(%s: %s), 沿用原顺序' % (type(e).__name__, e))
|
||||
return found
|
||||
|
||||
auto.find_element = find_element
|
||||
try:
|
||||
with _override(auto, 'find_element', find_element):
|
||||
return original(self, *args, **kwargs)
|
||||
finally:
|
||||
if own is None:
|
||||
vars(auto).pop('find_element', None)
|
||||
else:
|
||||
auto.find_element = own
|
||||
|
||||
mirror_mod.Mirror.acquire_ego_gift = acquire_ego_gift
|
||||
log('[lc_mcp] patch: 镜牢饰品选择按体系关键词排序(%s)' % os.path.basename(path))
|
||||
@@ -1090,12 +1121,15 @@ def install_event_choices(log=print, env=None):
|
||||
shown = ' | '.join('%d=%s' % (i + 1, text or '?') for i, text in enumerate(texts))
|
||||
|
||||
def once(message):
|
||||
if (texts, message) not in state['logged']:
|
||||
if (texts, message) in state['logged']:
|
||||
return False
|
||||
state['logged'].add((texts, message))
|
||||
log(message)
|
||||
return True
|
||||
|
||||
if rule is None:
|
||||
once('[lc_mcp] 事件选项: %s; 表里没有这个事件, 交给 AALC' % shown)
|
||||
if once('[lc_mcp] 事件选项: %s; 表里没有这个事件, 交给 AALC' % shown):
|
||||
decisions.record('event', None, 'not_in_table', options=list(texts))
|
||||
return False
|
||||
i, how, reason = choose_event_option(rule, texts)
|
||||
if how == 'text' and state['text_clicks'] >= EVENT_TEXT_CLICKS:
|
||||
@@ -1103,7 +1137,8 @@ def install_event_choices(log=print, env=None):
|
||||
if how == 'index' and (state['signature'] not in (None, texts) or state['index_tries'] >= EVENT_INDEX_TRIES):
|
||||
how, reason = None, '编号只用于第一屏选项'
|
||||
if how is None:
|
||||
once('[lc_mcp] 事件 %s: %s; %s, 交给 AALC' % (rule['name'], shown, reason))
|
||||
if once('[lc_mcp] 事件 %s: %s; %s, 交给 AALC' % (rule['name'], shown, reason)):
|
||||
decisions.record('event', None, 'deferred', event=rule['name'], options=list(texts), why=reason)
|
||||
return False
|
||||
if how == 'text':
|
||||
state['text_clicks'] += 1
|
||||
@@ -1111,6 +1146,7 @@ def install_event_choices(log=print, env=None):
|
||||
state['index_tries'] += 1
|
||||
state['signature'] = texts
|
||||
log('[lc_mcp] 事件 %s: %s; 选第 %d 项(%s)' % (rule['name'], shown, i + 1, reason))
|
||||
decisions.record('event', i + 1, how, event=rule['name'], options=list(texts), why=reason)
|
||||
position = options[i][0]
|
||||
auto.mouse_click(position[0], position[1])
|
||||
return True
|
||||
@@ -1118,7 +1154,6 @@ def install_event_choices(log=print, env=None):
|
||||
def event_handling(self, *args, **kwargs):
|
||||
state = {'rule': None, 'signature': None, 'index_tries': 0, 'text_clicks': 0, 'logged': set()}
|
||||
real = auto.click_element
|
||||
own = vars(auto).get('click_element')
|
||||
|
||||
def click_element(target, *a, **kw):
|
||||
if target == EVENT_HOOK:
|
||||
@@ -1129,15 +1164,120 @@ def install_event_choices(log=print, env=None):
|
||||
log('[lc_mcp] 事件选项表出错(%s: %s), 交给 AALC' % (type(e).__name__, e))
|
||||
return real(target, *a, **kw)
|
||||
|
||||
auto.click_element = click_element
|
||||
try:
|
||||
with _override(auto, 'click_element', click_element):
|
||||
return original(self, *args, **kwargs)
|
||||
finally:
|
||||
if own is None:
|
||||
vars(auto).pop('click_element', None)
|
||||
else:
|
||||
auto.click_element = own
|
||||
|
||||
mirror_mod.Mirror.event_handling = event_handling
|
||||
log('[lc_mcp] patch: 镜牢事件按选项表选择(%s, %d 条)' % (os.path.basename(path), len(rules)))
|
||||
return original
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 决策审计: 商店购买、卡包选择
|
||||
|
||||
SHOP_PURCHASE = 'mirror/shop/purchase_assets.png'
|
||||
SHOP_CONFIRM = 'mirror/road_in_mir/ego_gift_get_confirm_assets.png'
|
||||
|
||||
|
||||
def install_shop_audit(log=print):
|
||||
"""商店买东西时记一条审计。只观察, 不改上游的购买逻辑。"""
|
||||
try:
|
||||
from tasks.mirror.in_shop import Shop
|
||||
from module.automation import auto
|
||||
except Exception as e:
|
||||
log('[lc_mcp] 商店审计跳过: 无法导入 %s' % e)
|
||||
return None
|
||||
original = getattr(Shop, 'buy_gifts', None)
|
||||
if original is None:
|
||||
log('[lc_mcp] 商店审计跳过: 上游没有 Shop.buy_gifts')
|
||||
return None
|
||||
|
||||
def buy_gifts(self, *args, **kwargs):
|
||||
last = {'item': None}
|
||||
real_click, real_pos = auto.click_element, auto.mouse_action_with_pos
|
||||
|
||||
def click_element(target, *a, **kw):
|
||||
result = real_click(target, *a, **kw)
|
||||
if result and target == SHOP_PURCHASE:
|
||||
# 点到"购买"按钮; 钱不够时按钮匹配不上, 不会走到这里
|
||||
decisions.record('shop', last['item'] or 'unknown', 'purchase_clicked',
|
||||
system=getattr(self, 'system', None))
|
||||
last['item'] = None
|
||||
elif result and target != SHOP_CONFIRM:
|
||||
last['item'] = os.path.splitext(os.path.basename(str(target)))[0] # 必买项/四级/三级素材
|
||||
return result
|
||||
|
||||
def mouse_action_with_pos(*a, **kw):
|
||||
last['item'] = 'by_position' # 本体系饰品是按模板坐标点的
|
||||
return real_pos(*a, **kw)
|
||||
|
||||
with _override(auto, 'click_element', click_element), \
|
||||
_override(auto, 'mouse_action_with_pos', mouse_action_with_pos):
|
||||
return original(self, *args, **kwargs)
|
||||
|
||||
Shop.buy_gifts = buy_gifts
|
||||
log('[lc_mcp] patch: 商店购买写入决策审计')
|
||||
return original
|
||||
|
||||
|
||||
THEME_PACK_PICK = re.compile(r'此次选择卡包关键词[::]\s*(\S+)')
|
||||
THEME_PACK_WEIGHTS = '当前主题包权重列表'
|
||||
THEME_PACK_SOURCE = 'select_theme_pack.py'
|
||||
|
||||
|
||||
class _LogCapture(logging.Handler):
|
||||
"""收集某个源文件打出的 AALC 日志。"""
|
||||
|
||||
def __init__(self, source):
|
||||
super().__init__(logging.DEBUG)
|
||||
self.source = source
|
||||
self.messages = []
|
||||
|
||||
def emit(self, record):
|
||||
if os.path.basename(record.pathname or '') == self.source:
|
||||
try:
|
||||
self.messages.append(record.getMessage())
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def theme_pack_decision(messages):
|
||||
"""从上游 select_theme_pack 的日志里取 (卡包, 理由, 权重列表); 没选就返回 None。"""
|
||||
weights = next((m.split(':', 1)[-1] for m in reversed(messages) if m.startswith(THEME_PACK_WEIGHTS)), None)
|
||||
for message in reversed(messages):
|
||||
if '最左边的(活动)卡包' in message:
|
||||
return '最左边的活动卡包', 'event_pack', weights
|
||||
match = THEME_PACK_PICK.search(message)
|
||||
if match:
|
||||
return match.group(1), 'highest_weight' if '无匹配最低阈值' in message else 'preferred', weights
|
||||
return None
|
||||
|
||||
|
||||
def install_theme_pack_audit(log=print):
|
||||
"""卡包选完后按上游自己的日志记一条审计。只观察, 不改选择。"""
|
||||
try:
|
||||
from tasks.mirror import mirror as mirror_mod
|
||||
except Exception as e:
|
||||
log('[lc_mcp] 卡包审计跳过: 无法导入 %s' % e)
|
||||
return None
|
||||
original = getattr(mirror_mod, 'select_theme_pack', None)
|
||||
if original is None:
|
||||
log('[lc_mcp] 卡包审计跳过: mirror 模块没有 select_theme_pack')
|
||||
return None
|
||||
|
||||
def select_theme_pack(*args, **kwargs):
|
||||
capture = _LogCapture(THEME_PACK_SOURCE)
|
||||
logger = logging.getLogger('AALC')
|
||||
logger.addHandler(capture)
|
||||
try:
|
||||
return original(*args, **kwargs)
|
||||
finally:
|
||||
logger.removeHandler(capture)
|
||||
decision = theme_pack_decision(capture.messages)
|
||||
if decision:
|
||||
pack, reason, weights = decision
|
||||
decisions.record('theme_pack', pack, reason, weights=weights,
|
||||
floor=kwargs.get('floor', args[1] if len(args) > 1 else None))
|
||||
|
||||
mirror_mod.select_theme_pack = select_theme_pack
|
||||
log('[lc_mcp] patch: 卡包选择写入决策审计')
|
||||
return original
|
||||
|
||||
Reference in New Issue
Block a user