Files
lc-mcp/lc_mcp/decisions.py
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

63 lines
2.0 KiB
Python

# -*- 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())}