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 时调回去。
|
检查客户区尺寸, 偏离 set_win_size 时调回去。
|
||||||
"""
|
"""
|
||||||
import json
|
import json
|
||||||
|
import logging
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import threading
|
import threading
|
||||||
@@ -20,6 +21,8 @@ import time
|
|||||||
import unicodedata
|
import unicodedata
|
||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
|
|
||||||
|
from .decisions import decisions
|
||||||
|
|
||||||
TEAM_TARGET = re.compile(r'(?:TEAMS|TFAMS|编队)#(\d+)', re.IGNORECASE)
|
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 team_name_match(t, names) == 'exact']
|
||||||
if current: # 已经是这支队就不用动列表; 带后缀的队名要回列表里确认唯一后再点
|
if current: # 已经是这支队就不用动列表; 带后缀的队名要回列表里确认唯一后再点
|
||||||
log('[lc_mcp] patch: 当前已经是编队 %s, 无需切换' % current[0])
|
log('[lc_mcp] patch: 当前已经是编队 %s, 无需切换' % current[0])
|
||||||
|
decisions.record('team', current[0], 'current', wanted=list(names))
|
||||||
return True
|
return True
|
||||||
|
seen = []
|
||||||
auto.mouse_click(1, 1)
|
auto.mouse_click(1, 1)
|
||||||
time.sleep(0.3)
|
time.sleep(0.3)
|
||||||
_scroll_team_list(auto, +1) # 先回到顶部
|
_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)
|
log('[lc_mcp] 第 %d 屏截图失败' % round_index)
|
||||||
continue
|
continue
|
||||||
items = [item for item in _team_ocr(auto) if _in_list(item[1], item[2])]
|
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)
|
hit, reason = pick_team_item(items, names)
|
||||||
if hit:
|
if hit:
|
||||||
text, x, y = 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)
|
auto.mouse_action_with_pos([x, y], offset=False)
|
||||||
if _wait_header(auto, (label,)):
|
if _wait_header(auto, (label,)):
|
||||||
log('[lc_mcp] patch: 已按体系名选中编队 %s' % label)
|
log('[lc_mcp] patch: 已按体系名选中编队 %s' % label)
|
||||||
|
decisions.record('team', label, team_name_match(label, names), wanted=list(names))
|
||||||
return True
|
return True
|
||||||
log('[lc_mcp] 点了 %s 但顶栏没变(顶栏读到: %s), 继续往下翻'
|
header = [normalize_team_name(t) for t in _header_texts(auto) or ()]
|
||||||
% (label, '/'.join(normalize_team_name(t) for t in _header_texts(auto) or ()) or '无'))
|
log('[lc_mcp] 点了 %s 但顶栏没变(顶栏读到: %s), 继续往下翻' % (label, '/'.join(header) or '无'))
|
||||||
|
decisions.record('team', label, 'header_unchanged', wanted=list(names), header=header)
|
||||||
else:
|
else:
|
||||||
log('[lc_mcp] 第 %d 屏没有 %s%s; 这一屏的名字: %s'
|
log('[lc_mcp] 第 %d 屏没有 %s%s; 这一屏的名字: %s'
|
||||||
% (round_index, '/'.join(names), ', ' + reason if reason else '',
|
% (round_index, '/'.join(names), ', ' + reason if reason else '',
|
||||||
'/'.join(_list_names(items)) or '(空)'))
|
'/'.join(_list_names(items)) or '(空)'))
|
||||||
_scroll_team_list(auto, -1, times=3)
|
_scroll_team_list(auto, -1, times=3)
|
||||||
log('[lc_mcp] 编队列表里没找到 %s(共 %d 轮)' % ('/'.join(names), rounds))
|
log('[lc_mcp] 编队列表里没找到 %s(共 %d 轮)' % ('/'.join(names), rounds))
|
||||||
|
decisions.record('team', None, 'not_found', wanted=list(names), seen=seen)
|
||||||
return False
|
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)
|
ranked = rank_next_nodes(bus, nodes, cfg.set_win_size / 1440, weights, column_gap, row_gap)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
log('[lc_mcp] 键盘寻路: 识别下一列节点出错(%s: %s), 退回按 ↑' % (type(e).__name__, e))
|
log('[lc_mcp] 键盘寻路: 识别下一列节点出错(%s: %s), 退回按 ↑' % (type(e).__name__, e))
|
||||||
|
decisions.record('road', 'up', 'fallback', why='%s: %s' % (type(e).__name__, e))
|
||||||
return original()
|
return original()
|
||||||
if not ranked:
|
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()
|
return original()
|
||||||
log('[lc_mcp] 键盘寻路: 下一列 %s, 按权重从低到高依次尝试'
|
candidates = ['%s=%s(%d)' % item for item in ranked]
|
||||||
% ' '.join('%s=%s(%d)' % item for item in ranked))
|
log('[lc_mcp] 键盘寻路: 下一列 %s, 按权重从低到高依次尝试' % ' '.join(candidates))
|
||||||
for direction, kind, weight in ranked:
|
for direction, kind, weight in ranked:
|
||||||
auto.key_press(ROAD_KEYS[direction])
|
auto.key_press(ROAD_KEYS[direction])
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
if road._keyboard_enter_succeeded():
|
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))
|
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
|
return True
|
||||||
log('[lc_mcp] 键盘寻路: %s 方向的 %s 没能进入, 试下一个' % (direction, kind))
|
log('[lc_mcp] 键盘寻路: %s 方向的 %s 没能进入, 试下一个' % (direction, kind))
|
||||||
log('[lc_mcp] 键盘寻路: 按类型都没进入, 退回按 ↑')
|
log('[lc_mcp] 键盘寻路: 按类型都没进入, 退回按 ↑')
|
||||||
|
decisions.record('road', 'up', 'fallback', why='按类型都没进入', candidates=candidates)
|
||||||
return original()
|
return original()
|
||||||
|
|
||||||
road.search_road_simple_keyboard = search_road_simple_keyboard
|
road.search_road_simple_keyboard = search_road_simple_keyboard
|
||||||
@@ -824,6 +840,25 @@ def install_typed_keyboard_road(log=print, env=None):
|
|||||||
return original
|
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() 两张卡时只看白棉花和已持有, 拿第一张; 三张卡时虽然用
|
# 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])) # 日志按从左到右编号
|
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 '')
|
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))
|
for n, i in enumerate(by_x))
|
||||||
|
first = by_x.index(order[0]) + 1
|
||||||
if any(hits):
|
if any(hits):
|
||||||
log('[lc_mcp] 饰品选择(体系 %s): %s; 命中体系关键词, 先看第%d张'
|
log('[lc_mcp] 饰品选择(体系 %s): %s; 命中体系关键词, 先看第%d张' % (system, detail, first))
|
||||||
% (system, detail, by_x.index(order[0]) + 1))
|
|
||||||
else:
|
else:
|
||||||
log('[lc_mcp] 饰品选择(体系 %s): %s; 未命中体系关键词, 保持原顺序' % (system, detail))
|
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]
|
return [cards[i] for i in order]
|
||||||
|
|
||||||
def acquire_ego_gift(self, *args, **kwargs):
|
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 是"拒绝饰品"界面
|
if kwargs.get('type', args[0] if args else 1) != 1 or not keywords: # type=2 是"拒绝饰品"界面
|
||||||
return original(self, *args, **kwargs)
|
return original(self, *args, **kwargs)
|
||||||
real = auto.find_element
|
real = auto.find_element
|
||||||
own = vars(auto).get('find_element')
|
|
||||||
|
|
||||||
def find_element(target, *a, **kw):
|
def find_element(target, *a, **kw):
|
||||||
found = real(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))
|
log('[lc_mcp] 饰品选择: 关键词排序出错(%s: %s), 沿用原顺序' % (type(e).__name__, e))
|
||||||
return found
|
return found
|
||||||
|
|
||||||
auto.find_element = find_element
|
with _override(auto, 'find_element', find_element):
|
||||||
try:
|
|
||||||
return original(self, *args, **kwargs)
|
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
|
mirror_mod.Mirror.acquire_ego_gift = acquire_ego_gift
|
||||||
log('[lc_mcp] patch: 镜牢饰品选择按体系关键词排序(%s)' % os.path.basename(path))
|
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))
|
shown = ' | '.join('%d=%s' % (i + 1, text or '?') for i, text in enumerate(texts))
|
||||||
|
|
||||||
def once(message):
|
def once(message):
|
||||||
if (texts, message) not in state['logged']:
|
if (texts, message) in state['logged']:
|
||||||
|
return False
|
||||||
state['logged'].add((texts, message))
|
state['logged'].add((texts, message))
|
||||||
log(message)
|
log(message)
|
||||||
|
return True
|
||||||
|
|
||||||
if rule is None:
|
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
|
return False
|
||||||
i, how, reason = choose_event_option(rule, texts)
|
i, how, reason = choose_event_option(rule, texts)
|
||||||
if how == 'text' and state['text_clicks'] >= EVENT_TEXT_CLICKS:
|
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):
|
if how == 'index' and (state['signature'] not in (None, texts) or state['index_tries'] >= EVENT_INDEX_TRIES):
|
||||||
how, reason = None, '编号只用于第一屏选项'
|
how, reason = None, '编号只用于第一屏选项'
|
||||||
if how is 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
|
return False
|
||||||
if how == 'text':
|
if how == 'text':
|
||||||
state['text_clicks'] += 1
|
state['text_clicks'] += 1
|
||||||
@@ -1111,6 +1146,7 @@ def install_event_choices(log=print, env=None):
|
|||||||
state['index_tries'] += 1
|
state['index_tries'] += 1
|
||||||
state['signature'] = texts
|
state['signature'] = texts
|
||||||
log('[lc_mcp] 事件 %s: %s; 选第 %d 项(%s)' % (rule['name'], shown, i + 1, reason))
|
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]
|
position = options[i][0]
|
||||||
auto.mouse_click(position[0], position[1])
|
auto.mouse_click(position[0], position[1])
|
||||||
return True
|
return True
|
||||||
@@ -1118,7 +1154,6 @@ def install_event_choices(log=print, env=None):
|
|||||||
def event_handling(self, *args, **kwargs):
|
def event_handling(self, *args, **kwargs):
|
||||||
state = {'rule': None, 'signature': None, 'index_tries': 0, 'text_clicks': 0, 'logged': set()}
|
state = {'rule': None, 'signature': None, 'index_tries': 0, 'text_clicks': 0, 'logged': set()}
|
||||||
real = auto.click_element
|
real = auto.click_element
|
||||||
own = vars(auto).get('click_element')
|
|
||||||
|
|
||||||
def click_element(target, *a, **kw):
|
def click_element(target, *a, **kw):
|
||||||
if target == EVENT_HOOK:
|
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))
|
log('[lc_mcp] 事件选项表出错(%s: %s), 交给 AALC' % (type(e).__name__, e))
|
||||||
return real(target, *a, **kw)
|
return real(target, *a, **kw)
|
||||||
|
|
||||||
auto.click_element = click_element
|
with _override(auto, 'click_element', click_element):
|
||||||
try:
|
|
||||||
return original(self, *args, **kwargs)
|
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
|
mirror_mod.Mirror.event_handling = event_handling
|
||||||
log('[lc_mcp] patch: 镜牢事件按选项表选择(%s, %d 条)' % (os.path.basename(path), len(rules)))
|
log('[lc_mcp] patch: 镜牢事件按选项表选择(%s, %d 条)' % (os.path.basename(path), len(rules)))
|
||||||
return original
|
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
|
||||||
|
|||||||
+7
-3
@@ -13,9 +13,10 @@ from . import killswitch, preflight
|
|||||||
from .aalc_engine import bootstrap
|
from .aalc_engine import bootstrap
|
||||||
from .aalc_patches import (WindowGuard, driver_click_tasks, headless_hdr_warning,
|
from .aalc_patches import (WindowGuard, driver_click_tasks, headless_hdr_warning,
|
||||||
install_default_battle_team, install_event_choices, install_exact_team_match,
|
install_default_battle_team, install_event_choices, install_exact_team_match,
|
||||||
install_gift_preference, install_robust_set_foreground, install_shop_lists,
|
install_gift_preference, install_robust_set_foreground, install_shop_audit,
|
||||||
install_system_team_selection, install_typed_keyboard_road,
|
install_shop_lists, install_system_team_selection, install_theme_pack_audit,
|
||||||
mirror_progress, stop_driver_click)
|
install_typed_keyboard_road, mirror_progress, stop_driver_click)
|
||||||
|
from .decisions import decisions
|
||||||
from .game_lock import GameBusyError, exclusive_game
|
from .game_lock import GameBusyError, exclusive_game
|
||||||
|
|
||||||
# 任务 -> {参数名: AALC 配置项}; 参数只在本次运行内生效
|
# 任务 -> {参数名: AALC 配置项}; 参数只在本次运行内生效
|
||||||
@@ -119,6 +120,7 @@ def _run(task, params):
|
|||||||
log('[ERROR] [lc_mcp] preflight: %s' % p)
|
log('[ERROR] [lc_mcp] preflight: %s' % p)
|
||||||
return PREFLIGHT_EXIT
|
return PREFLIGHT_EXIT
|
||||||
|
|
||||||
|
decisions.open() # TaskRunner 给的 .decisions.jsonl; 直接运行时不写
|
||||||
install_exact_team_match(auto, log)
|
install_exact_team_match(auto, log)
|
||||||
install_robust_set_foreground(screen, log=log)
|
install_robust_set_foreground(screen, log=log)
|
||||||
# 日常本(经验/纽本)不翻队伍列表: 队伍是自定义名字时按名字找必然失败,
|
# 日常本(经验/纽本)不翻队伍列表: 队伍是自定义名字时按名字找必然失败,
|
||||||
@@ -132,6 +134,8 @@ def _run(task, params):
|
|||||||
install_typed_keyboard_road(log=log)
|
install_typed_keyboard_road(log=log)
|
||||||
install_gift_preference(log=log)
|
install_gift_preference(log=log)
|
||||||
install_event_choices(log=log)
|
install_event_choices(log=log)
|
||||||
|
install_shop_audit(log=log)
|
||||||
|
install_theme_pack_audit(log=log)
|
||||||
guard = WindowGuard(screen, cfg, log=log)
|
guard = WindowGuard(screen, cfg, log=log)
|
||||||
guard.start()
|
guard.start()
|
||||||
restore_path = os.environ.get(RESTORE_ENV)
|
restore_path = os.environ.get(RESTORE_ENV)
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""决策审计日志(BACKLOG P2-8)。
|
||||||
|
|
||||||
|
任务子进程把选队/寻路/卡包/饰品/事件/商店的每个决策追加成一行 JSON, 写到 TaskRunner 给的路径
|
||||||
|
(和任务日志同名, 后缀 .decisions.jsonl)。每行至少有 time / stage / choice / reason:
|
||||||
|
reason 是用来计数的短类别(例如 gift 的 keyword / no_keyword), 细节放在其余字段。
|
||||||
|
写失败只丢这一行, 不影响任务。
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from collections import Counter
|
||||||
|
|
||||||
|
DECISIONS_ENV = 'LCP_DECISIONS'
|
||||||
|
SUFFIX = '.decisions.jsonl'
|
||||||
|
|
||||||
|
|
||||||
|
class DecisionLog:
|
||||||
|
|
||||||
|
def __init__(self, path=None):
|
||||||
|
self.path = path
|
||||||
|
self._lock = threading.Lock()
|
||||||
|
|
||||||
|
def open(self, env=None):
|
||||||
|
"""按环境变量决定写到哪; 没设置时 record 什么也不做。"""
|
||||||
|
env = os.environ if env is None else env
|
||||||
|
self.path = env.get(DECISIONS_ENV) or None
|
||||||
|
return self.path
|
||||||
|
|
||||||
|
def record(self, stage, choice, reason, **detail):
|
||||||
|
if not self.path:
|
||||||
|
return
|
||||||
|
entry = {'time': time.strftime('%Y-%m-%dT%H:%M:%S'), 'stage': stage, 'choice': choice, 'reason': reason}
|
||||||
|
entry.update(detail)
|
||||||
|
line = json.dumps(entry, ensure_ascii=False, default=str) + '\n'
|
||||||
|
try:
|
||||||
|
with self._lock, open(self.path, 'a', encoding='utf-8') as f:
|
||||||
|
f.write(line)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
decisions = DecisionLog()
|
||||||
|
|
||||||
|
|
||||||
|
def summarize(path):
|
||||||
|
"""{stage: {reason: 次数}}; 文件不存在返回 None, 坏行跳过。"""
|
||||||
|
try:
|
||||||
|
with open(path, encoding='utf-8') as f:
|
||||||
|
lines = f.readlines()
|
||||||
|
except OSError:
|
||||||
|
return None
|
||||||
|
counts = {}
|
||||||
|
for line in lines:
|
||||||
|
try:
|
||||||
|
entry = json.loads(line)
|
||||||
|
stage, reason = str(entry['stage']), str(entry['reason'])
|
||||||
|
except (ValueError, KeyError, TypeError):
|
||||||
|
continue
|
||||||
|
counts.setdefault(stage, Counter())[reason] += 1
|
||||||
|
return {stage: dict(counter) for stage, counter in sorted(counts.items())}
|
||||||
+2
-1
@@ -87,7 +87,8 @@ TOOLS = [
|
|||||||
'inputSchema': _obj({'task': {'type': 'string', 'enum': sorted(TASKS)},
|
'inputSchema': _obj({'task': {'type': 'string', 'enum': sorted(TASKS)},
|
||||||
'exp': _NUM, 'thread': _NUM, 'times': _NUM, 'count': _NUM}, ['task'])},
|
'exp': _NUM, 'thread': _NUM, 'times': _NUM, 'count': _NUM}, ['task'])},
|
||||||
{'name': 'task_status', 'description': '启动 run_task 前检查占用,启动后轮询此工具监控,避免逐帧截图和重复启动。'
|
{'name': 'task_status', 'description': '启动 run_task 前检查占用,启动后轮询此工具监控,避免逐帧截图和重复启动。'
|
||||||
'返回 idle/running/succeeded/failed/stopped、日志及异常。'
|
'返回 idle/running/succeeded/failed/stopped、日志及异常;'
|
||||||
|
'decisions.counts 按阶段统计选队/寻路/卡包/饰品/事件/商店的决策理由。'
|
||||||
'succeeded 也要看 errors 和 pending_restore;running 出现 stall 应 stop_task 并确认停止后排障;'
|
'succeeded 也要看 errors 和 pending_restore;running 出现 stall 应 stop_task 并确认停止后排障;'
|
||||||
'stopped/退出码130 表示用户停止,不自动重跑。',
|
'stopped/退出码130 表示用户停止,不自动重跑。',
|
||||||
'inputSchema': _obj({'lines': {'type': 'number', 'default': 30}})},
|
'inputSchema': _obj({'lines': {'type': 'number', 'default': 30}})},
|
||||||
|
|||||||
+8
-1
@@ -12,6 +12,7 @@ import time
|
|||||||
from collections import deque
|
from collections import deque
|
||||||
|
|
||||||
from .aalc_task import RESTORE_ENV
|
from .aalc_task import RESTORE_ENV
|
||||||
|
from .decisions import DECISIONS_ENV, SUFFIX as DECISIONS_SUFFIX, summarize as summarize_decisions
|
||||||
from .killswitch import EXIT_CODE as USER_ABORT_EXIT
|
from .killswitch import EXIT_CODE as USER_ABORT_EXIT
|
||||||
|
|
||||||
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||||
@@ -168,11 +169,13 @@ class TaskRunner:
|
|||||||
base = os.path.join(self.run_dir, 'task_%s_%s' % (stamp, task))
|
base = os.path.join(self.run_dir, 'task_%s_%s' % (stamp, task))
|
||||||
env = self._env()
|
env = self._env()
|
||||||
env[RESTORE_ENV] = base + RESTORE_SUFFIX
|
env[RESTORE_ENV] = base + RESTORE_SUFFIX
|
||||||
|
env[DECISIONS_ENV] = base + DECISIONS_SUFFIX
|
||||||
kw = {'creationflags': subprocess.CREATE_NEW_PROCESS_GROUP} if IS_WIN else {'start_new_session': True}
|
kw = {'creationflags': subprocess.CREATE_NEW_PROCESS_GROUP} if IS_WIN else {'start_new_session': True}
|
||||||
with open(base + '.log', 'wb') as logf:
|
with open(base + '.log', 'wb') as logf:
|
||||||
self.proc = subprocess.Popen(self.argv_factory(task, params), cwd=REPO, env=env,
|
self.proc = subprocess.Popen(self.argv_factory(task, params), cwd=REPO, env=env,
|
||||||
stdin=subprocess.DEVNULL, stdout=logf, stderr=subprocess.STDOUT, **kw)
|
stdin=subprocess.DEVNULL, stdout=logf, stderr=subprocess.STDOUT, **kw)
|
||||||
self.info = {'task': task, 'params': params, 'log': (base + '.log').replace('\\', '/'),
|
self.info = {'task': task, 'params': params, 'log': (base + '.log').replace('\\', '/'),
|
||||||
|
'decisions': (base + DECISIONS_SUFFIX).replace('\\', '/'),
|
||||||
'restore': env[RESTORE_ENV], 'started': time.time(), 'stopped_by_user': False}
|
'restore': env[RESTORE_ENV], 'started': time.time(), 'stopped_by_user': False}
|
||||||
self._prune()
|
self._prune()
|
||||||
return {'ok': True, 'task': task, 'pid': self.proc.pid, 'log': self.info['log']}
|
return {'ok': True, 'task': task, 'pid': self.proc.pid, 'log': self.info['log']}
|
||||||
@@ -192,6 +195,9 @@ class TaskRunner:
|
|||||||
r = {'ok': True, 'state': state, 'task': self.info['task'], 'params': self.info['params'],
|
r = {'ok': True, 'state': state, 'task': self.info['task'], 'params': self.info['params'],
|
||||||
'elapsed_s': int((self.info.get('ended') or time.time()) - self.info['started']),
|
'elapsed_s': int((self.info.get('ended') or time.time()) - self.info['started']),
|
||||||
'log': self.info['log'], 'log_tail': tail(self.info['log'], max(1, min(int(lines), 200)))}
|
'log': self.info['log'], 'log_tail': tail(self.info['log'], max(1, min(int(lines), 200)))}
|
||||||
|
counts = summarize_decisions(self.info['decisions'])
|
||||||
|
if counts:
|
||||||
|
r['decisions'] = {'path': self.info['decisions'], 'counts': counts}
|
||||||
if code is None:
|
if code is None:
|
||||||
stalls = log_stalls(self.info['log'])
|
stalls = log_stalls(self.info['log'])
|
||||||
if stalls:
|
if stalls:
|
||||||
@@ -238,7 +244,8 @@ class TaskRunner:
|
|||||||
def _prune(self):
|
def _prune(self):
|
||||||
logs = sorted(glob.glob(os.path.join(self.run_dir, 'task_*.log')), key=os.path.getmtime)
|
logs = sorted(glob.glob(os.path.join(self.run_dir, 'task_*.log')), key=os.path.getmtime)
|
||||||
for p in logs[:-self.keep_logs]:
|
for p in logs[:-self.keep_logs]:
|
||||||
|
for path in (p, p[:-len('.log')] + DECISIONS_SUFFIX):
|
||||||
try:
|
try:
|
||||||
os.remove(p)
|
os.remove(path)
|
||||||
except OSError:
|
except OSError:
|
||||||
pass
|
pass
|
||||||
|
|||||||
Reference in New Issue
Block a user