Files
AgentScript/agent/backend/app/graph/worker.py
T
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

497 lines
17 KiB
Python
Raw 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.
"""
Worker 子图(真实改码循环)
===========================
【功能说明】
执行单个 TaskStep 的子图:locate → modify → verify(失败则 repair 重试 ≤3 次)。
M4 已接入真实自研工具链:文件定位、模型生成编辑、写盘落地、编译验证。
【技术选型理由】
1. 决策点 2「纯自研工具链」:改码动作由强模型生成结构化编辑指令,
再用 file_tools.edit_file 精确替换——不靠外部编码引擎,机制透明可控。
2. 编辑指令走「精确字符串替换」:最小改动面、diff 可读、可单测,
比整文件重写安全得多(避免模型重写引入无关改动)。
3. verify 走白名单执行器跑编译(决策点 8):机器可判定、确定性强。
【实现思路】
- locate:search_tools.find_files / grep_files 真实定位目标文件;
- modify:强模型读文件 → 产出 [{file, old_str, new_str}] 编辑计划 → 逐条落地;
- verify:executor.run_compile_check 跑 Maven/npm 编译;
- repair:验证失败后把错误信息回灌给模型重新生成编辑(≤3 次)。
【潜在风险与应对】
风险1:模型生成的 old_str 与文件不匹配。
应对:edit_file 严格唯一匹配,失败记录到 edits 并进 repair 循环重试。
风险2:模型重写范围过大(改无关代码)。
应对:prompt 明确要求「最小改动」;edit_file 只做精确替换不整文件覆盖。
风险3:编译失败耗时(Maven 慢)。
应对:executor 超时 60s;verify 结果记 stderr 摘要供 repair 参考。
"""
from __future__ import annotations
import json
import logging
import re
from pathlib import Path
from typing import Any
from langgraph.graph import END, START, StateGraph
from app.graph.state import WorkerState
from app.models.model_router import get_model_for_task
from app.tools import file_tools, search_tools
from app.tools.executor import run_compile_check
logger = logging.getLogger("agent.graph.worker")
# 单步骤最大重试次数(防无限循环烧 token)
MAX_RETRY = 3
# 每步最多读取的文件数(控制上下文规模)
MAX_FILES_PER_STEP = 3
# 每个文件最多读取行数(防止大文件撑爆上下文)
MAX_LINES_PER_FILE = 400
def _get_coding_engine() -> str:
"""读取改码引擎配置(builtin / claude_code)。"""
from app.config.settings import load_settings
return (load_settings().coding_engine or "builtin").strip().lower()
def _parse_json_loose(text: str) -> Any:
"""从模型输出宽松提取 JSON(兼容 ```json 围栏)。"""
if not text:
return {}
fence = re.search(r"```(?:json)?\s*(\[.*?\]|\{.*?\})\s*```", text, re.DOTALL)
if fence:
try:
return json.loads(fence.group(1))
except json.JSONDecodeError:
pass
arr = re.search(r"\[.*\]", text, re.DOTALL)
if arr:
try:
return json.loads(arr.group(0))
except json.JSONDecodeError:
pass
brace = re.search(r"\{.*\}", text, re.DOTALL)
if brace:
try:
return json.loads(brace.group(0))
except json.JSONDecodeError:
pass
return {}
# ---------- 节点 1:代码定位(真实)----------
def locate_node(state: WorkerState) -> dict[str, Any]:
"""
代码定位节点:按 target_hints 在项目目录下真实定位候选文件。
【能力】支持文件名片段匹配 + 正则内容搜索(决策点 6:符号检索)。
"""
step = state.get("step", {})
hints = step.get("target_hints", []) or []
project_id = state.get("project_id", "")
if not hints:
logger.info("步骤 %s 无目标线索", step.get("step_id"))
return {"located_files": []}
code_root = Path(r"D:\Agent\code")
candidates: set[str] = set()
for hint in hints[:5]:
hint_str = str(hint).strip()
if not hint_str:
continue
try:
# 1. 文件名模糊查找
found = search_tools.find_files(hint_str, code_root, max_results=10)
candidates.update(found.get("files", []))
# 2. 内容正则搜索(把线索当关键词搜内容)
if len(candidates) < 10:
grepped = search_tools.grep_files(
re.escape(hint_str), code_root, max_results=5
)
candidates.update(r["file"] for r in grepped.get("results", []))
except Exception as exc: # noqa: BLE001 - 单条线索失败不影响其余
logger.warning("定位线索 %s 失败:%s", hint_str, exc)
result_list = sorted(candidates)[:20]
logger.info("步骤 %s 定位到 %d 个候选文件", step.get("step_id"), len(result_list))
return {"located_files": result_list}
# ---------- 节点 2:代码修改(真实)----------
def modify_node(state: WorkerState) -> dict[str, Any]:
"""
代码修改节点:按配置分流到自研工具链或 Claude Code 引擎。
【引擎分流】
CODING_ENGINE=builtin → 自研工具链(默认):强模型生成编辑指令 → edit_file 落地
CODING_ENGINE=claude_code → Claude Code CLI:claude 自主读/理解/改/验证
【可插拔设计(方案 B)】两种引擎共存,改配置值即可切换/回退,主图零改动。
"""
engine = _get_coding_engine()
if engine == "claude_code":
return _modify_by_claude_code(state)
return _modify_by_builtin(state)
def _modify_by_claude_code(state: WorkerState) -> dict[str, Any]:
"""Claude Code 引擎:调用 claude CLI 自主完成改码。"""
step = state.get("step", {})
located = state.get("located_files", []) or []
retry = state.get("retry_count", 0)
task_id = state.get("task_id", "")
prev_error = state.get("error", "")
from app.tools.claude_engine import ClaudeCodeError, build_prompt, execute
from app.config.settings import load_settings
settings = load_settings()
project_root = Path(r"D:\Agent\code")
# 从定位到的文件推断项目根(找最近的 pom.xml/package.json)
for fp in located[:3]:
current = Path(fp).parent
for _ in range(8):
if (current / "pom.xml").exists() or (current / "package.json").exists():
project_root = current
break
if current.parent == current:
break
current = current.parent
if project_root != Path(r"D:\Agent\code"):
break
prompt = build_prompt(
step_description=step.get("description", ""),
expected_output=step.get("expected_output", ""),
target_files=located,
prev_error=prev_error,
retry=retry,
)
try:
result = execute(
project_root=project_root,
prompt=prompt,
task_id=task_id,
timeout=settings.claude_timeout_seconds,
model=state.get("model_preference", "") or "",
)
edit_record = {
"step_id": step.get("step_id", ""),
"action": "claude_code_edit",
"target_files": located[:5],
"summary": result.get("summary", ""),
"duration": result.get("duration", 0),
"success": result.get("success", False),
"retry": retry,
"engine": "claude_code",
}
return {"edits": [edit_record]}
except ClaudeCodeError as exc:
logger.error("Claude Code 引擎执行失败:%s", exc)
return {
"edits": [
{
"step_id": step.get("step_id", ""),
"action": "failed",
"reason": f"Claude Code 执行失败:{exc}",
"engine": "claude_code",
}
]
}
def _modify_by_builtin(state: WorkerState) -> dict[str, Any]:
"""
自研工具链引擎(默认):强模型生成编辑指令,工具链真实落地。
【流程】
1. 读取候选文件内容(截断到 MAX_LINES_PER_FILE);
2. 调用强模型产出结构化编辑计划 [{file, old_str, new_str, reason}];
3. 用 file_tools.edit_file 逐条精确替换;
4. 记录每条编辑结果(成功/失败)到 edits。
"""
step = state.get("step", {})
located = state.get("located_files", []) or []
retry = state.get("retry_count", 0)
task_id = state.get("task_id", "")
prev_error = state.get("error", "")
if not located:
logger.warning("步骤 %s 无定位到文件,跳过修改", step.get("step_id"))
return {
"edits": [
{
"step_id": step.get("step_id", ""),
"action": "skipped",
"reason": "未定位到目标文件",
}
]
}
# 读取候选文件内容(最多 3 个,每个最多 400 行)
file_contents = []
for fp in located[:MAX_FILES_PER_STEP]:
try:
read_result = file_tools.read_file(fp, end_line=MAX_LINES_PER_FILE)
file_contents.append(
{
"path": read_result["path"],
"content": read_result["content"],
"total_lines": read_result["total_lines"],
}
)
except Exception as exc: # noqa: BLE001
logger.warning("读取文件失败 %s:%s", fp, exc)
if not file_contents:
return {
"edits": [
{
"step_id": step.get("step_id", ""),
"action": "failed",
"reason": "候选文件全部读取失败",
}
]
}
# 构造 prompt 让模型生成编辑计划
files_desc = "\n\n".join(
f"【文件】{f['path']}(共 {f['total_lines']} 行)\n```\n{f['content']}\n```"
for f in file_contents
)
retry_hint = f"\n【上次修改失败原因,请修正】{prev_error}" if prev_error else ""
prompt = f"""你是资深 Java 开发工程师。请针对下面的修改步骤,生成最小化的代码编辑指令。
【修改步骤】{step.get('description', '')}
【预期产出】{step.get('expected_output', '')}
【重试次数】{retry}{retry_hint}
【当前代码】
{files_desc}
【输出要求】只输出 JSON 数组,每个元素是一次精确替换:
[
{{
"file": "完整文件路径",
"old_str": "要替换的原文(必须与文件内容完全一致,含缩进)",
"new_str": "替换后的新文本",
"reason": "改动理由(简短)"
}}
]
【硬性约束】
1. old_str 必须来自上面给出的代码原文,逐字符一致(含空格换行);
2. 单次 old_str 长度不超过 20 行,只改必要部分,禁止整文件重写;
3. 若无需改动,返回空数组 [];
4. 只输出 JSON,不要任何解释。"""
edits: list[dict[str, Any]] = []
try:
# 按任务模型偏好选模型:auto → 强模型;否则用指定模型
model = get_model_for_task(state.get("model_preference", "auto"), "strong")
resp = model.invoke(prompt)
content = resp.content if hasattr(resp, "content") else str(resp)
plan = _parse_json_loose(content)
if isinstance(plan, dict):
plan = plan.get("edits", [])
if not isinstance(plan, list):
plan = []
except Exception as exc: # noqa: BLE001
logger.error("生成编辑计划失败:%s", exc)
return {
"edits": [
{
"step_id": step.get("step_id", ""),
"action": "failed",
"reason": f"生成编辑计划失败:{exc}",
}
]
}
# 逐条落地编辑
for item in plan[:10]: # 单步最多 10 次编辑
if not isinstance(item, dict):
continue
target = item.get("file", "")
old_str = item.get("old_str", "")
new_str = item.get("new_str", "")
if not target or not old_str:
edits.append({"action": "skipped", "reason": "编辑项缺少 file/old_str", "item": item})
continue
try:
result = file_tools.edit_file(target, old_str, new_str, task_id=task_id)
edits.append(
{
"step_id": step.get("step_id", ""),
"action": "edited",
"file": target,
"replacements": result["replacements"],
"backup_path": result.get("backup_path"),
"reason": item.get("reason", ""),
"retry": retry,
}
)
logger.info("编辑成功:%s(%d 处)", target, result["replacements"])
except Exception as exc: # noqa: BLE001 - 单条失败继续其余
edits.append(
{
"step_id": step.get("step_id", ""),
"action": "failed",
"file": target,
"reason": str(exc)[:300],
"retry": retry,
}
)
logger.warning("编辑失败:%s %s", target, exc)
return {"edits": edits}
# ---------- 节点 3:编译验证(真实)----------
def verify_node(state: WorkerState) -> dict[str, Any]:
"""
验证节点:对项目执行编译级验证(决策点 8)。
【能力】自动识别 Maven/npm 项目,跑 compile/build;
【返回】verify_result:{passed, command, stderr_tail}
"""
step = state.get("step", {})
located = state.get("located_files", []) or []
edits = state.get("edits", []) or []
# 若本步没有任何成功编辑且无定位,直接视为不通过
has_edit = any(e.get("action") == "edited" for e in edits)
if not located and not has_edit:
return {
"verify_result": {
"passed": False,
"step_id": step.get("step_id", ""),
"message": "无定位结果且无有效编辑",
}
}
# 推断项目根目录:用定位到的文件向上找 pom.xml/package.json
project_root = None
for fp in located[:3]:
current = Path(fp).parent
for _ in range(8): # 最多向上找 8 层
if (current / "pom.xml").exists() or (current / "package.json").exists():
project_root = current
break
if current.parent == current:
break
current = current.parent
if project_root:
break
if project_root is None:
# 兜底:用 D:\Agent\code 下第一个含 pom 的目录
code_root = Path(r"D:\Agent\code")
for pom in code_root.rglob("pom.xml"):
project_root = pom.parent
break
if project_root is None:
return {
"verify_result": {
"passed": True, # 无项目可验证时放行(避免误杀)
"step_id": step.get("step_id", ""),
"message": "未识别到可验证的项目结构,跳过编译验证",
}
}
try:
result = run_compile_check(project_root)
except Exception as exc: # noqa: BLE001
return {
"verify_result": {
"passed": False,
"step_id": step.get("step_id", ""),
"message": f"编译验证执行失败:{exc}",
"stderr_tail": "",
}
}
stderr_tail = (result.get("stderr") or "")[-1500:]
return {
"verify_result": {
"passed": result["passed"],
"step_id": step.get("step_id", ""),
"command": result.get("command", ""),
"message": "编译通过" if result["passed"] else "编译失败",
"stderr_tail": stderr_tail,
}
}
# ---------- 节点 4:修复循环 ----------
def repair_node(state: WorkerState) -> dict[str, Any]:
"""
修复节点:验证失败后把错误信息回灌,重新进入 modify 生成编辑。
"""
retry = state.get("retry_count", 0) + 1
verify = state.get("verify_result", {})
error_msg = f"第 {retry} 次修复尝试;编译失败:{verify.get('stderr_tail', '')[-500:]}"
logger.info("进入修复循环第 %d 次", retry)
return {"retry_count": retry, "error": error_msg}
def _route_after_verify(state: WorkerState) -> str:
"""条件路由:验证通过或重试用尽 → END;否则 → repair。"""
verify = state.get("verify_result", {})
retry = state.get("retry_count", 0)
if verify.get("passed") or retry >= MAX_RETRY:
return END
return "repair"
def build_worker_graph():
"""构建 Worker 子图。"""
builder = StateGraph(WorkerState)
builder.add_node("locate", locate_node)
builder.add_node("modify", modify_node)
builder.add_node("verify", verify_node)
builder.add_node("repair", repair_node)
builder.add_edge(START, "locate")
builder.add_edge("locate", "modify")
builder.add_edge("modify", "verify")
builder.add_conditional_edges(
"verify",
_route_after_verify,
{"repair": "repair", END: END},
)
builder.add_edge("repair", "modify")
return builder.compile()
_worker_graph = None
def get_worker_graph():
"""获取 Worker 子图单例。"""
global _worker_graph
if _worker_graph is None:
_worker_graph = build_worker_graph()
return _worker_graph