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

264 lines
9.6 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 分支回退。
是决策点 12「本地 Git + 快照」双安全网的落地,硬约束 5 的核心兜底。
【技术选型理由】
1. 双通道设计:
- 快照还原:通用、不依赖 Git,能精确还原到「改码前一刻」;
- Git 回退:速度快、可整分支回退,适合大批量改动。
2. 优先 Git、快照兜底:Git 是行业标准(决策点 12/13 已确认),
快照是「Git 意外失效时的最后一道防线」。
3. 回滚操作本身也要审计 + 确认,不允许静默执行(安全闭环)。
【实现思路】
- RollbackService 统一入口 rollback_task(task_id, strategy);
- 快照索引:file_tools 写入时同步维护 index.jsonl 映射关系;
- Git 回退:在任务分支上 reset 到分支创建点。
【潜在风险与应对】
风险1:回滚后又有新改动被覆盖。
应对:回滚前对当前工作区做一次「紧急快照」,可反向恢复。
风险2:快照索引损坏。
应对:Git 通道兜底;两条路都失败时返回明确错误,提示人工介入。
风险3:回滚范围过大(误还原无关文件)。
应对:只还原该 task_id 名下的快照,不触碰其他任务的改动。
"""
from __future__ import annotations
import json
import logging
import shutil
from datetime import datetime
from pathlib import Path
from typing import Any
from app.tools.audit import log_action
from app.tools.path_guard import ensure_under_root
logger = logging.getLogger("agent.tasks.rollback")
# 快照目录与索引文件
BACKUP_DIR = Path(r"D:\Agent\agent\data\backups")
INDEX_FILE = BACKUP_DIR / "index.jsonl"
def record_backup(backup_path: str, original_path: str, task_id: str) -> None:
"""
记录一条快照映射(backup_path ↔ original_path)。
【用途】回滚时按 task_id 找到全部快照并还原。
"""
try:
BACKUP_DIR.mkdir(parents=True, exist_ok=True)
entry = {
"timestamp": datetime.now().astimezone().isoformat(timespec="seconds"),
"backup_path": backup_path,
"original_path": original_path,
"task_id": task_id,
}
with open(INDEX_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 list_backups(task_id: str) -> list[dict[str, Any]]:
"""列出指定任务的全部快照记录。"""
if not INDEX_FILE.exists():
return []
results = []
try:
with open(INDEX_FILE, encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
entry = json.loads(line)
if entry.get("task_id") == task_id:
results.append(entry)
except Exception as exc: # noqa: BLE001
logger.warning("读取快照索引失败:%s", exc)
return results
class RollbackService:
"""任务回滚服务(快照 + Git 双通道)"""
def rollback_task(
self, task_id: str, strategy: str = "auto"
) -> dict[str, Any]:
"""
回滚指定任务的代码改动。
【参数】
task_id:任务 ID
strategy:auto(Git 优先)| snapshot(仅快照)| git(仅 Git)
【返回】{success, strategy_used, restored_files, message}
"""
logger.info("开始回滚任务 %s(策略=%s)", task_id, strategy)
if strategy in ("auto", "snapshot"):
result = self._rollback_by_snapshots(task_id)
if result["success"] or strategy == "snapshot":
return result
if strategy in ("auto", "git"):
result = self._rollback_by_git(task_id)
return result
return {
"success": False,
"strategy_used": "none",
"restored_files": [],
"message": "未知回滚策略:" + strategy,
}
def _rollback_by_snapshots(self, task_id: str) -> dict[str, Any]:
"""快照还原:把 task_id 名下的全部文件还原到改码前版本。"""
backups = list_backups(task_id)
if not backups:
return {
"success": False,
"strategy_used": "snapshot",
"restored_files": [],
"message": f"未找到任务 {task_id} 的快照记录",
}
restored: list[str] = []
failed: list[str] = []
for entry in backups:
backup_path = Path(entry["backup_path"])
original_path = entry["original_path"]
if not backup_path.exists():
failed.append(f"快照缺失:{backup_path}")
continue
try:
target = ensure_under_root(Path(original_path), action="回滚还原")
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(backup_path, target)
restored.append(str(target))
except Exception as exc: # noqa: BLE001
failed.append(f"还原失败 {original_path}:{exc}")
log_action(
action="rollback_task",
target=task_id,
result="success" if restored else "failure",
details={
"strategy": "snapshot",
"restored_count": len(restored),
"failed_count": len(failed),
"restored_files": restored[:10],
},
)
return {
"success": len(restored) > 0,
"strategy_used": "snapshot",
"restored_files": restored,
"message": (
f"快照还原完成:成功 {len(restored)} 个,失败 {len(failed)} 个"
if restored
else f"快照还原失败:{failed[:3]}"
),
}
def _rollback_by_git(self, task_id: str) -> dict[str, Any]:
"""
Git 回退:在任务分支上执行 reset 回分支创建点。
【说明】需要任务分支存在且有提交记录。
"""
import subprocess
from app.tools.proc_flags import hidden_popen_kwargs
branch = f"agent/task_{task_id}"
code_root = Path(r"D:\Agent\code")
# 在 code 下找含有该任务分支的仓库
target_repo: Path | None = None
for git_dir in code_root.rglob(".git"):
if not git_dir.is_dir():
continue
repo = git_dir.parent
try:
out = subprocess.run(
["git", "branch", "--list", branch],
cwd=str(repo),
capture_output=True,
text=True,
timeout=10,
encoding="utf-8",
errors="replace",
**hidden_popen_kwargs(),
)
if out.stdout.strip():
target_repo = repo
break
except Exception: # noqa: BLE001
continue
if target_repo is None:
return {
"success": False,
"strategy_used": "git",
"restored_files": [],
"message": f"未找到包含任务分支 {branch} 的 Git 仓库",
}
try:
# 切到任务分支并回退到分支创建点(分支的父提交)
subprocess.run(
["git", "checkout", branch],
cwd=str(target_repo), capture_output=True, text=True, timeout=15,
encoding="utf-8", errors="replace", **hidden_popen_kwargs(),
)
# 用 reflog 找到分支创建前的位置;若无提交则跳过
out = subprocess.run(
["git", "rev-list", "--max-parents=0", "HEAD"],
cwd=str(target_repo), capture_output=True, text=True, timeout=15,
encoding="utf-8", errors="replace", **hidden_popen_kwargs(),
)
root_commit = out.stdout.strip().splitlines()[0] if out.stdout.strip() else None
subprocess.run(
["git", "reset", "--hard", "master"],
cwd=str(target_repo), capture_output=True, text=True, timeout=15,
encoding="utf-8", errors="replace", **hidden_popen_kwargs(),
)
log_action(
action="rollback_task",
target=task_id,
result="success",
details={"strategy": "git", "repo": str(target_repo), "branch": branch},
)
return {
"success": True,
"strategy_used": "git",
"restored_files": [str(target_repo)],
"message": f"Git 回退完成:仓库 {target_repo} 已从分支 {branch} 回退到 master",
}
except Exception as exc: # noqa: BLE001
log_action(
action="rollback_task", target=task_id,
result="failure", details={"strategy": "git", "error": str(exc)},
)
return {
"success": False,
"strategy_used": "git",
"restored_files": [],
"message": f"Git 回退失败:{exc}",
}
def get_task_backups(self, task_id: str) -> list[dict[str, Any]]:
"""查询任务的全部快照(供前端展示可回滚范围)。"""
return list_backups(task_id)