Files
HenryandClaude Code 26e13ff032 feat: Agent 工作区初始提交(源码+文档+Skills)
包含 CodeAgent 前后端源码、SKILLS、MCP、demo 代码与工作区文档。
排除依赖缓存、运行数据、备份与二进制附件,规则见 .gitignore。

Co-Authored-By: Claude Code <[email protected]>
2026-11-13 13:48:41 +08:00

92 lines
3.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
审计日志
========
【功能说明】
记录工具层的每一次敏感操作(文件写入、命令执行、git 提交),
落盘到 D:\\Agent\\agent\\data\\audit,支持事后追溯与合规审查。
【技术选型理由】
1. 硬约束 5 要求「任何异常不能直接崩溃、要可排查」:
审计日志是排查 Agent 误操作的第一手证据。
2. 追加写 JSONL(每行一个 JSON):无需数据库、可 grep、可程序化分析。
3. 与工具层同步写入:不异步、不缓冲,保证操作与日志强一致。
【实现思路】
- log_action() 记录 {时间, 操作, 目标, 结果, 详情};
- 按日期分文件:audit-YYYYMMDD.jsonl,便于按天归档;
- 敏感字段(如完整文件内容)只记摘要,不记全文(防止日志膨胀+泄密)。
【潜在风险与应对】
风险1:日志写入失败影响主流程。
应对:日志写入全程 try/except,失败只 warning 不抛出。
风险2:日志文件无限膨胀。
应对:按日期分文件;后续可加自动清理(保留 N 天)。
"""
from __future__ import annotations
import json
import logging
from datetime import datetime
from pathlib import Path
from typing import Any
logger = logging.getLogger("agent.tools.audit")
# 审计日志默认目录
DEFAULT_AUDIT_DIR = Path(r"D:\Agent\agent\data\audit")
def log_action(
action: str,
target: str,
result: str = "success",
details: dict[str, Any] | None = None,
audit_dir: Path | None = None,
) -> None:
"""
记录一次工具操作。
【参数】
action:操作类型(file_write / file_edit / exec_command / git_commit 等)
target:操作对象(文件路径/命令/git 仓库)
result:success / failure / denied
details:补充详情(会做摘要,不记全文)
"""
try:
audit_dir = audit_dir or DEFAULT_AUDIT_DIR
audit_dir.mkdir(parents=True, exist_ok=True)
today = datetime.now().strftime("%Y%m%d")
log_file = audit_dir / f"audit-{today}.jsonl"
entry = {
"timestamp": datetime.now().astimezone().isoformat(timespec="seconds"),
"action": action,
"target": target,
"result": result,
"details": _summarize_details(details or {}),
}
with open(log_file, "a", encoding="utf-8") as f:
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
except Exception as exc: # noqa: BLE001 - 审计失败不阻塞主流程
logger.warning("审计日志写入失败:%s", exc)
def _summarize_details(details: dict[str, Any]) -> dict[str, Any]:
"""摘要化详情:长文本截断,避免日志膨胀。"""
summary: dict[str, Any] = {}
for key, value in details.items():
if isinstance(value, str) and len(value) > 500:
summary[key] = value[:500] + f"…(共{len(value)}字符)"
elif isinstance(value, (int, float, bool)):
summary[key] = value
elif value is None:
summary[key] = None
else:
summary[key] = str(value)[:200]
return summary