From 51525722cd100ce5c9be58e4e569a26c8528c0b8 Mon Sep 17 00:00:00 2001 From: ywsabc2 Date: Sat, 14 Nov 2026 07:11:30 +0000 Subject: [PATCH] =?UTF-8?q?P2-8=20=E9=95=9C=E7=89=A2=E5=B1=80=E5=86=85?= =?UTF-8?q?=E5=86=B3=E7=AD=96=E5=86=99=E5=85=A5=E5=AE=A1=E8=AE=A1=E6=97=A5?= =?UTF-8?q?=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 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 --- README.md | 12 ++ docs/BACKLOG.md | 12 ++ lc_mcp/aalc_patches.py | 198 +++++++++++++++++---- lc_mcp/aalc_task.py | 10 +- lc_mcp/decisions.py | 62 +++++++ lc_mcp/protocol.py | 3 +- lc_mcp/tasks.py | 15 +- tests/test_decisions.py | 256 ++++++++++++++++++++++++++++ tests/test_event_choices.py | 9 + tests/test_gift_preference.py | 6 + tests/test_system_team_selection.py | 18 +- tests/test_typed_road.py | 14 ++ 12 files changed, 575 insertions(+), 40 deletions(-) create mode 100644 lc_mcp/decisions.py create mode 100644 tests/test_decisions.py diff --git a/README.md b/README.md index 1e5e8a0..df062b1 100644 --- a/README.md +++ b/README.md @@ -143,6 +143,18 @@ MCP 初始化说明与工具描述均指导 AI 优先使用 AALC:常规日常 任务运行中如果 `task_status` 带 `stall` 字段,说明 AALC 在原地空转(例如选中了空队伍, 编队人数检查一直刷屏)。它不会自己报错退出,应当 `stop_task` 后重跑。 +镜牢任务的局内决策逐条写进与日志同名的 `~/lc_mcp/runs/task_*.decisions.jsonl`(每行一个 JSON: +`time`/`stage`/`choice`/`reason` 加细节)。`task_status` 的 `decisions.counts` 按阶段统计 `reason`: + +| `stage` | `reason` | +|---|---| +| `team` | `current` 已是目标队 / `exact` / `prefix` 后缀队名 / `header_unchanged` / `not_found` | +| `road` | `lowest` 下一列最优 / `next_best` 更优方向进不去 / `fallback` 退回按 ↑ | +| `theme_pack` | `preferred` 达到优选阈值 / `highest_weight` 刷新后取最高权重 / `event_pack` 最左活动卡包 | +| `gift` | `keyword` 命中体系关键词 / `no_keyword`(记的是交给 AALC 的第一顺位,白棉花、已持有仍由 AALC 处理) | +| `event` | `text` / `index` 按表选 / `deferred` 表里有但交给 AALC / `not_in_table`(带 `options`,可直接拿来补表) | +| `shop` | `purchase_clicked` 点到了购买按钮(`choice` 是之前点的商品:必买项名、`level_IV_to_buy`、`by_position` 本体系饰品) | + ### 任务进程里的保护 `run_task` 启动的任务子进程会做以下处理,都不改 `vendor/aalc` 源码: diff --git a/docs/BACKLOG.md b/docs/BACKLOG.md index f3c98ff..a81f639 100644 --- a/docs/BACKLOG.md +++ b/docs/BACKLOG.md @@ -239,6 +239,18 @@ Dijkstra 那套(`search_road.py:735`,代价 event 1 / shop 2 / battle 4 / bo **涉及**:`lc_mcp/aalc_patches.py`、`lc_mcp/tasks.py`(结果归档)。 +**状态(2026-11-14 云端)**:已实现,待实机验收。 + +- 文件与任务日志同名:`~/lc_mcp/runs/task_<时间>_<任务>.decisions.jsonl`。TaskRunner 通过 `LCP_DECISIONS` 把路径传给子进程, + 清理旧日志时一起删;直接 `python -m lc_mcp.aalc_task` 运行时不写。写失败只丢那一行。 +- 每行 `time`/`stage`/`choice`/`reason` + 细节(候选、命中、选项文字…);`reason` 是用来计数的短类别,表见 README。 + `task_status` 返回 `decisions: {path, counts: {stage: {reason: 次数}}}`。 +- 来源:选队(P1-5)、键盘寻路(P0-2)、饰品(P1-3)、事件(P1-4)直接在补丁里记; + 商店与卡包是只观察的补丁:`Shop.buy_gifts` 期间看 `purchase_assets` 是否点中、之前点的是哪件商品; + `select_theme_pack` 期间临时挂一个 logging handler,从上游自己的 `此次选择卡包关键词:X` 日志取结果和权重列表。 +- 「画面摘要」只记了各决策用到的文字(选项、队名、命中关键词),没存截图。 +- 验收对应:卡包理由 = `counts.theme_pack`,三选一命中体系 = `counts.gift.keyword`,商店购买 = `counts.shop.purchase_clicked`。 + --- ## 已知但暂不做的 diff --git a/lc_mcp/aalc_patches.py b/lc_mcp/aalc_patches.py index ae6f6ac..7bcb679 100644 --- a/lc_mcp/aalc_patches.py +++ b/lc_mcp/aalc_patches.py @@ -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']: - state['logged'].add((texts, message)) - log(message) + 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 diff --git a/lc_mcp/aalc_task.py b/lc_mcp/aalc_task.py index 74ed2dc..3a4a481 100644 --- a/lc_mcp/aalc_task.py +++ b/lc_mcp/aalc_task.py @@ -13,9 +13,10 @@ from . import killswitch, preflight from .aalc_engine import bootstrap from .aalc_patches import (WindowGuard, driver_click_tasks, headless_hdr_warning, install_default_battle_team, install_event_choices, install_exact_team_match, - install_gift_preference, install_robust_set_foreground, install_shop_lists, - install_system_team_selection, install_typed_keyboard_road, - mirror_progress, stop_driver_click) + install_gift_preference, install_robust_set_foreground, install_shop_audit, + install_shop_lists, install_system_team_selection, install_theme_pack_audit, + install_typed_keyboard_road, mirror_progress, stop_driver_click) +from .decisions import decisions from .game_lock import GameBusyError, exclusive_game # 任务 -> {参数名: AALC 配置项}; 参数只在本次运行内生效 @@ -119,6 +120,7 @@ def _run(task, params): log('[ERROR] [lc_mcp] preflight: %s' % p) return PREFLIGHT_EXIT + decisions.open() # TaskRunner 给的 .decisions.jsonl; 直接运行时不写 install_exact_team_match(auto, log) install_robust_set_foreground(screen, log=log) # 日常本(经验/纽本)不翻队伍列表: 队伍是自定义名字时按名字找必然失败, @@ -132,6 +134,8 @@ def _run(task, params): install_typed_keyboard_road(log=log) install_gift_preference(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.start() restore_path = os.environ.get(RESTORE_ENV) diff --git a/lc_mcp/decisions.py b/lc_mcp/decisions.py new file mode 100644 index 0000000..54885dc --- /dev/null +++ b/lc_mcp/decisions.py @@ -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())} diff --git a/lc_mcp/protocol.py b/lc_mcp/protocol.py index 07782ea..16a5eae 100644 --- a/lc_mcp/protocol.py +++ b/lc_mcp/protocol.py @@ -87,7 +87,8 @@ TOOLS = [ 'inputSchema': _obj({'task': {'type': 'string', 'enum': sorted(TASKS)}, 'exp': _NUM, 'thread': _NUM, 'times': _NUM, 'count': _NUM}, ['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 并确认停止后排障;' 'stopped/退出码130 表示用户停止,不自动重跑。', 'inputSchema': _obj({'lines': {'type': 'number', 'default': 30}})}, diff --git a/lc_mcp/tasks.py b/lc_mcp/tasks.py index 640639b..08c95ae 100644 --- a/lc_mcp/tasks.py +++ b/lc_mcp/tasks.py @@ -12,6 +12,7 @@ import time from collections import deque 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 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)) env = self._env() 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} with open(base + '.log', 'wb') as logf: self.proc = subprocess.Popen(self.argv_factory(task, params), cwd=REPO, env=env, stdin=subprocess.DEVNULL, stdout=logf, stderr=subprocess.STDOUT, **kw) 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} self._prune() 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'], '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)))} + counts = summarize_decisions(self.info['decisions']) + if counts: + r['decisions'] = {'path': self.info['decisions'], 'counts': counts} if code is None: stalls = log_stalls(self.info['log']) if stalls: @@ -238,7 +244,8 @@ class TaskRunner: def _prune(self): logs = sorted(glob.glob(os.path.join(self.run_dir, 'task_*.log')), key=os.path.getmtime) for p in logs[:-self.keep_logs]: - try: - os.remove(p) - except OSError: - pass + for path in (p, p[:-len('.log')] + DECISIONS_SUFFIX): + try: + os.remove(path) + except OSError: + pass diff --git a/tests/test_decisions.py b/tests/test_decisions.py new file mode 100644 index 0000000..a4aac14 --- /dev/null +++ b/tests/test_decisions.py @@ -0,0 +1,256 @@ +# -*- coding: utf-8 -*- +"""决策审计日志(BACKLOG P2-8): 写入、统计、TaskRunner 归档, 以及商店/卡包两处只观察的审计。""" +import ast +import json +import logging +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 +from lc_mcp.decisions import DECISIONS_ENV, SUFFIX, DecisionLog, summarize # noqa: E402 +from lc_mcp.tasks import TaskRunner # noqa: E402 + +THEME = REPO / 'vendor' / 'aalc' / 'tasks' / 'mirror' / 'select_theme_pack.py' + + +def read(path): + with open(path, encoding='utf-8') as f: + return [json.loads(line) for line in f] + + +class DecisionLogTest(unittest.TestCase): + + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.path = os.path.join(tmp.name, 'run' + SUFFIX) + + def test_without_env_nothing_is_written(self): + log = DecisionLog() + self.assertIsNone(log.open(env={})) + log.record('gift', 1, 'keyword') + self.assertFalse(os.path.exists(self.path)) + + def test_records_and_counts(self): + log = DecisionLog() + self.assertEqual(log.open(env={DECISIONS_ENV: self.path}), self.path) + log.record('gift', 2, 'keyword', system='bleed', hits=[[], ['流血']]) + log.record('gift', 1, 'no_keyword', system='bleed', hits=[[], []]) + log.record('gift', 1, 'keyword', system='bleed', hits=[['出血'], []]) + log.record('shop', 'carmilla', 'purchase_clicked') + entries = read(self.path) + self.assertEqual(entries[0]['hits'], [[], ['流血']]) + self.assertEqual(set(entries[0]), {'time', 'stage', 'choice', 'reason', 'system', 'hits'}) + self.assertEqual(summarize(self.path), {'gift': {'keyword': 2, 'no_keyword': 1}, + 'shop': {'purchase_clicked': 1}}) + + def test_bad_lines_are_skipped_and_missing_file_is_none(self): + with open(self.path, 'w', encoding='utf-8') as f: + f.write('{"stage": "road", "reason": "lowest"}\nnot json\n{"stage": "road"}\n[]\n') + self.assertEqual(summarize(self.path), {'road': {'lowest': 1}}) + self.assertIsNone(summarize(self.path + '.missing')) + + def test_write_failure_does_not_raise(self): + DecisionLog(os.path.dirname(self.path)).record('gift', 1, 'keyword') # 路径是目录 + + +class TaskRunnerDecisionsTest(unittest.TestCase): + + CHILD = ('import os\n' + 'from lc_mcp.decisions import decisions\n' + 'decisions.open()\n' + 'decisions.record("theme_pack", "信仰", "preferred")\n' + 'decisions.record("gift", 2, "keyword")\n' + 'decisions.record("gift", 1, "no_keyword")\n' + 'print("[lc_mcp] done")\n') + + def wait(self, runner): + deadline = time.time() + 15 + while time.time() < deadline and runner.running(): + time.sleep(0.05) + + def test_child_writes_next_to_its_log_and_status_counts_it(self): + with tempfile.TemporaryDirectory() as d: + runner = TaskRunner(d, argv_factory=lambda t, p: [sys.executable, '-c', self.CHILD]) + started = runner.start('mirror', {'count': 1}) + self.assertTrue(started['ok'], started) + self.wait(runner) + status = runner.status() + self.assertEqual(status['state'], 'succeeded', status) + self.assertEqual(status['decisions']['path'], started['log'][:-len('.log')] + SUFFIX) + self.assertEqual(status['decisions']['counts'], + {'gift': {'keyword': 1, 'no_keyword': 1}, 'theme_pack': {'preferred': 1}}) + + def test_no_decisions_field_when_nothing_was_recorded(self): + with tempfile.TemporaryDirectory() as d: + runner = TaskRunner(d, argv_factory=lambda t, p: [sys.executable, '-c', 'print(1)']) + runner.start('daily', {}) + self.wait(runner) + self.assertNotIn('decisions', runner.status()) + + def test_prune_removes_decisions_with_their_log(self): + with tempfile.TemporaryDirectory() as d: + runner = TaskRunner(d, argv_factory=lambda t, p: [sys.executable, '-c', 'print(1)'], keep_logs=1) + old = os.path.join(d, 'task_20260101_000000_mirror') + for path in (old + '.log', old + SUFFIX): + with open(path, 'w') as f: + f.write('{}\n') + os.utime(old + '.log', (1, 1)) + runner.start('daily', {}) + self.wait(runner) + self.assertFalse(os.path.exists(old + '.log')) + self.assertFalse(os.path.exists(old + SUFFIX)) + + +class RecordingTest(unittest.TestCase): + """把模块级 decisions 指到临时文件。""" + + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.path = os.path.join(tmp.name, 'run' + SUFFIX) + patcher = mock.patch.object(ap.decisions, 'path', self.path) + patcher.start() + self.addCleanup(patcher.stop) + self.lines = [] + + def entries(self): + return read(self.path) if os.path.exists(self.path) else [] + + +class ShopAuditTest(RecordingTest): + + def setUp(self): + super().setUp() + self.auto = SimpleNamespace(click_element=mock.Mock(return_value=True), + mouse_action_with_pos=mock.Mock()) + self.shop_cls = type('Shop', (), {'system': 'bleed'}) + in_shop = types.ModuleType('tasks.mirror.in_shop') + in_shop.Shop = self.shop_cls + modules = {'tasks': types.ModuleType('tasks'), 'tasks.mirror': types.ModuleType('tasks.mirror'), + 'tasks.mirror.in_shop': in_shop, 'module': types.ModuleType('module'), + 'module.automation': SimpleNamespace(auto=self.auto)} + patcher = mock.patch.dict(sys.modules, modules) + patcher.start() + self.addCleanup(patcher.stop) + + def test_purchases_are_recorded_with_the_item_clicked_before(self): + auto = self.auto + + def buy_gifts(shop): + # 上游的三条购买路径: 必买项、四级素材、本体系饰品(按坐标) + auto.click_element('mirror/shop/must_purchase/carmilla.png', threshold=0.85) + auto.click_element(ap.SHOP_PURCHASE) + auto.click_element(ap.SHOP_CONFIRM) + auto.click_element('mirror/shop/level_IV_to_buy.png', threshold=0.82) + auto.click_element(ap.SHOP_PURCHASE) + auto.mouse_action_with_pos((300, 400), offset=True) + auto.click_element(ap.SHOP_PURCHASE, take_screenshot=True) + return 'done' + + self.shop_cls.buy_gifts = buy_gifts + click, position = auto.click_element, auto.mouse_action_with_pos + ap.install_shop_audit(log=self.lines.append) + self.assertEqual(self.shop_cls().buy_gifts(), 'done') + self.assertEqual([(e['choice'], e['reason'], e['system']) for e in self.entries()], + [('carmilla', 'purchase_clicked', 'bleed'), + ('level_IV_to_buy', 'purchase_clicked', 'bleed'), + ('by_position', 'purchase_clicked', 'bleed')]) + self.assertIs(auto.click_element, click) + self.assertIs(auto.mouse_action_with_pos, position) + position.assert_called_once_with((300, 400), offset=True) + + def test_failed_purchase_click_is_not_recorded(self): + auto, real = self.auto, self.auto.click_element + + def buy_gifts(shop): + auto.click_element('mirror/shop/must_purchase/carmilla.png') + real.return_value = False # 钱不够: 购买按钮匹配不上 + auto.click_element(ap.SHOP_PURCHASE) + + self.shop_cls.buy_gifts = buy_gifts + ap.install_shop_audit(log=self.lines.append) + self.shop_cls().buy_gifts() + self.assertEqual(self.entries(), []) + + +class ThemePackDecisionTest(unittest.TestCase): + + def test_messages_to_decision(self): + weights = "当前主题包权重列表:[('信仰', 0), ('unknown', -5)]" + self.assertEqual(ap.theme_pack_decision([weights, '此次选择卡包关键词:信仰']), + ('信仰', 'preferred', "[('信仰', 0), ('unknown', -5)]")) + self.assertEqual(ap.theme_pack_decision(['无匹配最低阈值的主题包,选择最高权重主题包\n此次选择卡包关键词:赌徒'])[:2], + ('赌徒', 'highest_weight')) + self.assertEqual(ap.theme_pack_decision(['此次主题包选择了最左边的(活动)卡包'])[:2], + ('最左边的活动卡包', 'event_pack')) + self.assertIsNone(ap.theme_pack_decision(['选择卡包: (1, 2)'])) + + +@unittest.skipUnless(THEME.is_file(), 'vendor/aalc 子模块未检出') +class UpstreamThemePackAuditTest(RecordingTest): + """执行上游真实的 select_theme_pack, 审计从它自己的日志里取结果。""" + + class Match: + def __init__(self, value, text): + self.value, self.text, self.position = value, text, [0, 0] + + def run_upstream(self, packs, thresholds=0): + tree = ast.parse(THEME.read_text(encoding='utf-8')) + node = next(n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == 'select_theme_pack') + node.decorator_list = [] + positions = [(300 + 300 * i, 300) for i in range(len(packs))] + weights = {name: weight for name, weight in packs if name} + + def find_language_text(zh, en, crop): + x = (crop[0] + crop[2]) / 2 + name = packs[min(range(len(packs)), key=lambda i: abs(positions[i][0] - x))][0] + return self.Match(weights[name], name) if name else False + + auto = SimpleNamespace( + model=None, take_screenshot=lambda: object(), mouse_to_blank=lambda *a, **k: None, + find_element=lambda target, **kw: list(positions) if 'theme_pack_features' in target else False, + find_language_text=find_language_text, mouse_drag_down=mock.Mock(), + click_element=lambda *a, **k: False) + ns = dict(auto=auto, TextMatchResult=self.Match, sleep=lambda *a: None, back_init_menu=mock.Mock(), + log=logging.getLogger('AALC'), + cfg=SimpleNamespace(set_win_size=720, select_event_pack=False, skip_event_pack=False), + path_manager=SimpleNamespace(current_language='zh_cn'), + theme_list=SimpleNamespace(preferred_thresholds=thresholds, + get_effective_theme_pack_list=lambda *a: dict(weights))) + exec(compile(ast.Module(body=[node], type_ignores=[]), str(THEME), 'exec'), ns) + mirror_mod = types.ModuleType('tasks.mirror.mirror') + mirror_mod.select_theme_pack = ns['select_theme_pack'] + package = types.ModuleType('tasks.mirror') + package.mirror = mirror_mod + logger = logging.getLogger('AALC') + with mock.patch.dict(sys.modules, {'tasks': types.ModuleType('tasks'), 'tasks.mirror': package, + 'tasks.mirror.mirror': mirror_mod}), \ + mock.patch.object(logger, 'level', logging.DEBUG), \ + mock.patch.object(logger, 'propagate', False): + ap.install_theme_pack_audit(log=self.lines.append) + handlers = list(logger.handlers) + mirror_mod.select_theme_pack(False, 2, 1, False) + self.assertEqual(logger.handlers, handlers, '临时 handler 必须移除') + return auto.mouse_drag_down + + def test_preferred_pack_is_recorded(self): + drag = self.run_upstream([('赌徒', -1), ('信仰', 2), (None, None)]) + drag.assert_called_once_with(600, 300) + entry, = self.entries() + self.assertEqual((entry['stage'], entry['choice'], entry['reason'], entry['floor']), + ('theme_pack', '信仰', 'preferred', 2)) + self.assertIn("('信仰', 2)", entry['weights']) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_event_choices.py b/tests/test_event_choices.py index 58202f6..1234170 100644 --- a/tests/test_event_choices.py +++ b/tests/test_event_choices.py @@ -207,6 +207,15 @@ class UpstreamEventHandlingTest(unittest.TestCase): 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)) diff --git a/tests/test_gift_preference.py b/tests/test_gift_preference.py index 6c9bbe5..eaede19 100644 --- a/tests/test_gift_preference.py +++ b/tests/test_gift_preference.py @@ -237,6 +237,12 @@ class UpstreamAcquireEgoGiftTest(unittest.TestCase): self.assertEqual(self.choose(cards)[0], [1]) self.assertIn('第1张=1(流血) 第2张=2(流血/出血)', self.log) + def test_decision_is_recorded_left_to_right(self): + cards = [card(300, '烧伤层数+1'), card(600, '施加2层流血')] + with mock.patch.object(ap.decisions, 'record') as record: + self.choose(cards) + record.assert_called_once_with('gift', 2, 'keyword', system='bleed', hits=[[], ['流血']]) + def test_unknown_system_skips_ocr(self): cards = [card(300, '烧伤'), card(600, '流血')] chosen, screen = self.choose(cards, system='unknown') diff --git a/tests/test_system_team_selection.py b/tests/test_system_team_selection.py index f80a0f8..3d3731b 100644 --- a/tests/test_system_team_selection.py +++ b/tests/test_system_team_selection.py @@ -197,9 +197,10 @@ class SelectTeamByNameTest(unittest.TestCase): def setUp(self): self.lines = [] - patcher = mock.patch.object(aalc_patches.time, 'sleep') - patcher.start() - self.addCleanup(patcher.stop) + for patcher in (mock.patch.object(aalc_patches.time, 'sleep'), + mock.patch.object(aalc_patches.decisions, 'record')): + self.records = patcher.start() + self.addCleanup(patcher.stop) def select(self, auto, names): return aalc_patches._select_team_by_name(auto, names, log=self.lines.append) @@ -253,6 +254,17 @@ class SelectTeamByNameTest(unittest.TestCase): self.assertEqual(auto.clicks, []) self.assertIn('前缀匹配到多条(流血2/流血队), 不点', self.log) + def test_decisions_are_recorded(self): + self.select(_FakeTeamScreen([self.TOP, ['流血队', '震颤']]), ('流血',)) + self.records.assert_called_with('team', '流血队', 'prefix', wanted=['流血']) + self.select(_FakeTeamScreen([self.TOP], header='流血'), ('流血',)) + self.records.assert_called_with('team', '流血', 'current', wanted=['流血']) + self.select(_FakeTeamScreen([self.TOP, self.BOTTOM]), ('编队#999',)) + args, kwargs = self.records.call_args + self.assertEqual(args, ('team', None, 'not_found')) + self.assertEqual(kwargs['seen'][0], self.TOP) + self.assertEqual(len(kwargs['seen']), 4) + def test_header_not_changing_is_reported(self): auto = _FakeTeamScreen([self.TOP, self.MIDDLE], click_changes_header=False) self.assertFalse(self.select(auto, ('流血',))) diff --git a/tests/test_typed_road.py b/tests/test_typed_road.py index 62b0e4b..4966de9 100644 --- a/tests/test_typed_road.py +++ b/tests/test_typed_road.py @@ -114,6 +114,9 @@ class TypedKeyboardRoadTest(unittest.TestCase): for patch in (mock.patch.dict(sys.modules, modules), mock.patch.object(ap.time, 'sleep')): patch.start() self.addCleanup(patch.stop) + patch = mock.patch.object(ap.decisions, 'record') + self.records = patch.start() + self.addCleanup(patch.stop) def install(self, env=None): return ap.install_typed_keyboard_road(log=self.lines.append, env=env or {}) @@ -136,6 +139,17 @@ class TypedKeyboardRoadTest(unittest.TestCase): self.assertEqual(self.keys, ['up', 'down']) self.assertIn('更优的方向没能进入', '\n'.join(self.lines)) + def test_decisions_are_recorded(self): + self.install() + self.entered = [False, True] + self.road.search_road_simple_keyboard() + self.records.assert_called_once_with('road', 'D:shop', 'next_best', + candidates=['U=event(1)', 'D=shop(2)', 'M=battle(4)']) + self.records.reset_mock() + self.auto.find_element.return_value = None + self.road.search_road_simple_keyboard() + self.records.assert_called_once_with('road', 'up', 'fallback', why='没找到巴士') + def test_falls_back_to_original_when_nothing_can_be_entered(self): self.install() self.entered = [False, False, False]