feat: 引入 agents-workflow-engine 与 5 个 SDD skill

新增 agents-workflow-engine:主会话按泳道图调度子 agent 到提测,
含 schema、preset、CLI、单测,并接入 verify.sh。

agile-team-sdd 新增 5 个模板:ba-write-prototype、ba-requirement-review、
dev-plan-review、dev-plan-amend、pm-start-iteration,已登记 catalog
并同步安装到 example-project;README/AGENTS.md 同步 skill 数量 21→26。

验证:./.agents/verify.sh 全绿(67 项,含 AWE 14 个单测)。
文档同步检查:已更新 README、AGENTS.md、agile-team-sdd/README.md 与 SKILL.md。
This commit is contained in:
ning-inspire
2026-11-19 10:05:10 +08:00
parent f5b12d9ff7
commit 69cfaea7dc
34 changed files with 2851 additions and 13 deletions

View File

@@ -0,0 +1,37 @@
# agents-workflow-engine
一个人用主会话把一条迭代从启动调度到提测。图是 YAML。人、graph-master、子 agent 分三道泳道。子 agent 调用 skill,并且可以绑不同模型做对抗验证。
## 用法
在仓库根目录:
```bash
PYTHONPATH=agents-workflow-engine python -m agents_workflow_engine validate
PYTHONPATH=agents-workflow-engine python -m agents_workflow_engine render --dry-run
PYTHONPATH=agents-workflow-engine python -m agents_workflow_engine run \
--project <目标项目> --answers answers.yaml --agent '你的子 agent 命令'
```
`answers.yaml` 里,人的节点对应一段文字或「满意 / 不满意」。同一节点要答多次时写成列表。
子 agent 命令会额外收到 `--skill`、`--node`、`--model`。批量构建还会收到 `--task`。环境变量 `WORKFLOW_TASK` 是同一条任务。门禁要在标准输出单独一行打印 `满意` 或 `不满意`。`dev-plan` 用 `TASK: <id>` 宣布一批任务。
模型用环境变量,不写进仓库:`MODEL_WRITER`、`MODEL_REVIEWER`。两个值相同,或没设,会在 `.agents/workflow/decisions.jsonl` 记下「未做对抗验证」。
## 安装预设
```bash
./agents-workflow-engine/scripts/install.sh <目标项目> --dry-run
./agents-workflow-engine/scripts/install.sh <目标项目>
```
只写 `.agents/workflow/preset.yaml`。已存在则跳过,`--force` 才覆盖。不碰 `overlay.yaml`。
## 项目怎么改图
在目标项目放 `.agents/workflow/overlay.yaml`,可以 `disable` 节点、`replace` skill、改回路的 `maxIterations`。
## 维护
预设在 `presets/iteration-to-test.yaml`。形状说明在 `schema/graph.schema.json`。泳道预览在仓库 `.agents/plan/iteration-to-test.html`。

View File

@@ -0,0 +1,5 @@
"""agents-workflow-engine。"""
from .cli import main
__all__ = ["main"]

View File

@@ -0,0 +1,4 @@
from .cli import main
if __name__ == "__main__":
raise SystemExit(main())

View File

@@ -0,0 +1,153 @@
"""命令行:validate / resolve / render / run。"""
from __future__ import annotations
import argparse
import json
import os
import sys
from .errors import GraphError
from .load import load_overlay
from .load import load_preset
from .load import load_yaml
from .merge import merge
from .render_mermaid import render
from .runner import Runner
from .runner import spawn_agent
from .validate import validate
from .yaml_lite import loads
def _graph_from(args: argparse.Namespace) -> dict:
base = load_yaml(args.graph) if args.graph else load_preset()
overlay = load_overlay(args.project)
return merge(base, overlay)
def _print_warnings(warnings: list) -> None:
for warning in warnings:
print(warning, file=sys.stderr)
def cmd_validate(args: argparse.Namespace) -> int:
graph = _graph_from(args)
errors, warnings = validate(graph)
_print_warnings(warnings)
if errors:
for error in errors:
print(error, file=sys.stderr)
return 1
print("图有效:%s 个节点,%s 个警告" % (len(graph["nodes"]), len(warnings)))
return 0
def cmd_resolve(args: argparse.Namespace) -> int:
graph = _graph_from(args)
errors, warnings = validate(graph)
_print_warnings(warnings)
if errors:
for error in errors:
print(error, file=sys.stderr)
return 1
print(json.dumps(graph, ensure_ascii=False, indent=2))
return 0
def cmd_render(args: argparse.Namespace) -> int:
graph = _graph_from(args)
errors, warnings = validate(graph)
_print_warnings(warnings)
if errors:
for error in errors:
print(error, file=sys.stderr)
return 1
text = render(graph)
if args.dry_run or not args.output:
sys.stdout.write(text)
return 0
with open(args.output, "w", encoding="utf-8") as handle:
handle.write(text)
print("已写入 %s" % args.output)
return 0
def _load_answers(path: str) -> dict:
if not path:
return {}
with open(path, "r", encoding="utf-8") as handle:
data = loads(handle.read())
if not isinstance(data, dict):
raise GraphError("answers 文件的根必须是映射")
answers = {}
for key, value in data.items():
if isinstance(value, list):
answers[key] = [str(item) for item in value]
else:
answers[key] = [str(value)]
return answers
def cmd_run(args: argparse.Namespace) -> int:
graph = _graph_from(args)
errors, warnings = validate(graph)
_print_warnings(warnings)
if errors:
for error in errors:
print(error, file=sys.stderr)
return 1
answers = _load_answers(args.answers) if args.answers else {}
log = [] # type: list
def agent(node, model, task):
return spawn_agent(args.agent, node, model, task)
runner = Runner(graph, answers, agent, args.master_model, log)
end = runner.run()
out_dir = os.path.join(args.project, ".agents", "workflow")
os.makedirs(out_dir, exist_ok=True)
path = os.path.join(out_dir, "decisions.jsonl")
with open(path, "a", encoding="utf-8") as handle:
for item in log:
handle.write(json.dumps(item, ensure_ascii=False) + "\n")
print("到达 %s,记录写在 %s" % (end, path))
return 0
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(prog="agents_workflow_engine", description="按项目的工作流图调度子 agent")
parser.add_argument("--project", default=".", help="目标项目目录,默认当前目录")
parser.add_argument("--graph", default="", help="图 YAML。缺省用套件预设")
sub = parser.add_subparsers(dest="command", required=True)
validate_cmd = sub.add_parser("validate", help="校验预设叠覆盖之后的图")
validate_cmd.set_defaults(func=cmd_validate)
resolve_cmd = sub.add_parser("resolve", help="打印合并后的图")
resolve_cmd.set_defaults(func=cmd_resolve)
render_cmd = sub.add_parser("render", help="把图渲成 Mermaid")
render_cmd.add_argument("--dry-run", action="store_true", help="只打印,不写文件")
render_cmd.add_argument("--output", default="", help="写入的文件。缺省打印到标准输出")
render_cmd.set_defaults(func=cmd_render)
run_cmd = sub.add_parser("run", help="主会话按图执行到提测")
run_cmd.add_argument("--answers", default="", help="人的答案 YAML")
run_cmd.add_argument("--agent", default="", help="子 agent 命令")
run_cmd.add_argument("--master-model", default=os.environ.get("MODEL_MASTER", "master"), help="主会话模型,子 agent 未配置时沿用")
run_cmd.set_defaults(func=cmd_run)
return parser
def main(argv: list = None) -> int:
parser = build_parser()
args = parser.parse_args(argv)
try:
return args.func(args)
except GraphError as exc:
print(str(exc), file=sys.stderr)
return 1
if __name__ == "__main__":
raise SystemExit(main())

View File

@@ -0,0 +1,9 @@
"""图的加载、合并、校验、渲染与运行共用的错误。"""
class GraphError(Exception):
"""图不合法或跑不下去。消息里写明节点、原因和下一步。"""
class NeedInput(GraphError):
"""图停在人的节点上,进度已记下。"""

View File

@@ -0,0 +1,47 @@
"""读取预设图与覆盖文件。"""
from __future__ import annotations
import os
from typing import Any
from typing import Optional
from .errors import GraphError
from .yaml_lite import YamlError
from .yaml_lite import loads
PRESET_NAME = "iteration-to-test.yaml"
def package_root() -> str:
return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def preset_path() -> str:
return os.path.join(package_root(), "presets", PRESET_NAME)
def load_yaml(path: str) -> Any:
try:
with open(path, "r", encoding="utf-8") as handle:
text = handle.read()
except OSError as exc:
raise GraphError("读不到图文件 %s:%s" % (path, exc)) from exc
try:
data = loads(text)
except YamlError as exc:
raise GraphError("图文件 %s 不是合法 YAML:%s" % (path, exc)) from exc
if not isinstance(data, dict):
raise GraphError("图文件 %s 的根必须是映射" % path)
return data
def load_preset() -> dict:
return load_yaml(preset_path())
def load_overlay(project: str) -> Optional[dict]:
path = os.path.join(project, ".agents", "workflow", "overlay.yaml")
if not os.path.isfile(path):
return None
return load_yaml(path)

View File

@@ -0,0 +1,45 @@
"""把项目覆盖叠到预设图上。"""
from __future__ import annotations
import copy
from typing import Optional
from .errors import GraphError
def merge(base: dict, overlay: Optional[dict]) -> dict:
graph = copy.deepcopy(base)
if not overlay:
return graph
disabled = set(overlay.get("disable") or [])
unknown = disabled - {node["id"] for node in graph.get("nodes") or []}
if unknown:
raise GraphError("覆盖要禁用的节点不存在:%s" % "、".join(sorted(unknown)))
graph["nodes"] = [node for node in graph["nodes"] if node["id"] not in disabled]
graph["edges"] = [
edge for edge in graph.get("edges") or []
if edge.get("from") not in disabled and edge.get("to") not in disabled
]
by_id = {node["id"]: node for node in graph["nodes"]}
for node_id, fields in (overlay.get("replace") or {}).items():
if node_id not in by_id:
raise GraphError("覆盖要替换的节点不存在:%s" % node_id)
if not isinstance(fields, dict):
raise GraphError("节点 %s 的替换内容必须是映射" % node_id)
by_id[node_id].update(fields)
loops_by_id = {loop["id"]: loop for loop in graph.get("loops") or []}
for loop in overlay.get("loops") or []:
if loop.get("id") not in loops_by_id:
raise GraphError("覆盖要改的回路不存在:%s" % loop.get("id"))
loops_by_id[loop["id"]].update(loop)
edges_by_id = {edge["id"]: edge for edge in graph["edges"]}
for edge in overlay.get("edges") or []:
if "id" not in edge:
raise GraphError("覆盖里的边必须有 id")
if edge["id"] in edges_by_id:
edges_by_id[edge["id"]].update(edge)
else:
graph["edges"].append(edge)
edges_by_id[edge["id"]] = edge
return graph

View File

@@ -0,0 +1,44 @@
"""把解析后的图写成 Mermaid。扩展节点不输出。"""
from __future__ import annotations
def _shape(node: dict) -> str:
title = node.get("title") or node["id"]
if node.get("batch"):
title += " · 一批任务"
if node.get("repeatsBatch"):
title += " · 按批循环"
if node.get("sealed") and node.get("note"):
title += " / " + "、".join(node["note"])
node_id = node["id"]
kind = node.get("kind")
if kind == "action":
return "%s(%s)" % (node_id, title)
if kind == "gate":
return "%s[[%s]]" % (node_id, title)
if kind == "decision":
return "%s{%s}" % (node_id, title)
if kind == "human_input":
return "%s[/%s/]" % (node_id, title)
if kind == "end":
return "%s([%s])" % (node_id, title)
if kind == "entry":
return "%s{{%s}}" % (node_id, title)
return "%s[%s]" % (node_id, title)
def render(graph: dict) -> str:
lines = ["flowchart LR"]
titles = (("human", "人"), ("master", "graph-master"), ("subagent", "子 agent"))
for actor, title in titles:
lines.append(" subgraph %s [%s]" % (actor, title))
for node in graph.get("nodes") or []:
if node.get("actor") == actor:
lines.append(" " + _shape(node))
lines.append(" end")
for edge in graph.get("edges") or []:
arrow = "-.->" if edge.get("back") else "-->"
label = "|%s|" % edge["when"] if edge.get("when") else ""
lines.append(" %s %s%s %s" % (edge["from"], arrow, label, edge["to"]))
return "\n".join(lines) + "\n"

View File

@@ -0,0 +1,248 @@
"""按图往下走:人答题,子 agent 执行 skill,主会话只调度。"""
from __future__ import annotations
import os
import shlex
import subprocess
from typing import Callable
from typing import Dict
from typing import List
from typing import Optional
from .errors import GraphError
from .errors import NeedInput
from .validate import REVIEW_PAIRS
from .validate import node_map
def _plain_edges(edges: List[dict], node_id: str) -> List[dict]:
outgoing = [
edge for edge in edges
if edge.get("from") == node_id and not edge.get("when")
]
drop = set()
for edge in outgoing:
others = [item["to"] for item in outgoing if item is not edge]
for other in others:
if _can_reach(other, edge["to"], edges):
drop.add(edge["id"])
return [edge for edge in outgoing if edge["id"] not in drop]
def _can_reach(start: str, target: str, edges: List[dict]) -> bool:
seen = set()
stack = [start]
while stack:
current = stack.pop()
if current == target:
return True
if current in seen:
continue
seen.add(current)
for edge in edges:
if edge.get("from") != current or edge.get("back") or edge.get("when"):
continue
stack.append(edge["to"])
return False
def _when_edge(edges: List[dict], node_id: str, answer: str) -> dict:
for edge in edges:
if edge.get("from") == node_id and edge.get("when") == answer:
return edge
raise GraphError("节点 %s 没有「%s」这条出边" % (node_id, answer))
def _loop_for(graph: dict, edge_id: str) -> Optional[dict]:
for loop in graph.get("loops") or []:
if edge_id in (loop.get("backEdges") or []):
return loop
return None
def _take_answer(answers: Dict[str, List[str]], node_id: str) -> str:
queue = answers.get(node_id) or []
if not queue:
raise NeedInput(
"节点 %s 需要人的输入。进度已记下。补上 answers 后用同一个 --iteration 再执行 run"
% node_id
)
return str(queue.pop(0))
def _resolve_model(graph: dict, node: dict, master_model: str) -> str:
key = node.get("model")
models = graph.get("models") or {}
if not key or key not in models:
return master_model
spec = models[key]
if isinstance(spec, dict) and spec.get("env"):
return os.environ.get(str(spec["env"]), "") or master_model
return str(spec) or master_model
def _verdict(text: str) -> str:
for line in reversed(text.splitlines()):
line = line.strip()
if line in ("满意", "不满意"):
return line
if "不满意" in text:
return "不满意"
if "满意" in text:
return "满意"
raise GraphError("子 agent 没有给出「满意」或「不满意」。输出是:%s" % text.strip()[:200])
def _tasks(text: str) -> List[str]:
found = []
for line in text.splitlines():
line = line.strip()
if line.startswith("TASK:"):
task = line[5:].strip()
if task:
found.append(task)
return found or ["task-1"]
class Runner:
def __init__(self, graph: dict, answers: Dict[str, List[str]], agent: Callable, master_model: str, log: List[dict], current: str = "", visits: Dict[str, int] = None, loop_counts: Dict[str, int] = None, tasks: List[str] = None, task_index: int = 0) -> None:
self.graph = graph
self.answers = answers
self.agent = agent
self.master_model = master_model
self.log = log
self.nodes = node_map(graph)
self.edges = graph.get("edges") or []
self.current = current or graph["entry"]
self.visits = visits or {}
self.loop_counts = loop_counts or {}
self.tasks = list(tasks or [])
self.task_index = task_index
def run(self) -> str:
current = self.current
guard = 0
while guard < 500:
guard += 1
self.current = current
node = self.nodes[current]
kind = node.get("kind")
if kind == "end":
self.log.append({"node": current, "event": "end", "title": node.get("title")})
return current
if kind == "entry":
current = self._only(current)
continue
if kind == "human_input":
text = _take_answer(self.answers, current)
self.log.append({"node": current, "event": "human_input", "text": text})
current = self._only(current)
continue
if kind == "decision":
choice = _take_answer(self.answers, current)
self.log.append({"node": current, "event": "decision", "choice": choice})
current = self._follow_when(current, choice)
continue
if kind == "gate":
self._warn_pair(node)
result = self._call(node, None)
verdict = _verdict(result)
self.log.append({"node": current, "event": "gate", "verdict": verdict, "model": _resolve_model(self.graph, node, self.master_model)})
current = self._follow_when(current, verdict)
continue
if kind == "action":
current = self._run_action(node)
continue
raise GraphError("节点 %s 的 kind 无法执行:%s" % (current, kind))
raise GraphError("走了 500 步还没到终点,图里可能有死循环")
def _run_action(self, node: dict) -> str:
node_id = node["id"]
if node.get("once") and self.visits.get(node_id):
return self._only(node_id)
if node.get("repeatsBatch"):
if self.task_index >= len(self.tasks):
return self._only(node_id)
task = self.tasks[self.task_index]
result = self._call(node, task)
self.visits[node_id] = self.visits.get(node_id, 0) + 1
self.task_index += 1
self.log.append({"node": node_id, "event": "batch-step", "task": task, "output": result})
if self.task_index < len(self.tasks):
return node_id
return self._only(node_id)
result = self._call(node, None)
self.visits[node_id] = self.visits.get(node_id, 0) + 1
self.log.append({"node": node_id, "event": "action", "output": result, "model": _resolve_model(self.graph, node, self.master_model)})
if node.get("batch"):
self.tasks = _tasks(result)
self.task_index = 0
self.log.append({"node": node_id, "event": "batch", "tasks": list(self.tasks)})
return self._only(node_id)
def _call(self, node: dict, task: Optional[str]) -> str:
model = _resolve_model(self.graph, node, self.master_model)
return self.agent(node, model, task)
def _warn_pair(self, reviewer: dict) -> None:
for writer_id, reviewer_id in REVIEW_PAIRS:
if reviewer["id"] != reviewer_id:
continue
writer = self.nodes.get(writer_id)
if not writer:
return
left = _resolve_model(self.graph, writer, self.master_model)
right = _resolve_model(self.graph, reviewer, self.master_model)
if not left or not right or left == right:
self.log.append({
"node": reviewer["id"],
"event": "model-check",
"warning": "未做对抗验证",
"writer": writer_id,
"writerModel": left,
"reviewerModel": right,
})
def _follow_when(self, node_id: str, answer: str) -> str:
edge = _when_edge(self.edges, node_id, answer)
if edge.get("back"):
loop = _loop_for(self.graph, edge["id"])
if loop is None:
raise GraphError("打回边 %s 没有上限" % edge["id"])
count = self.loop_counts.get(loop["id"], 0) + 1
self.loop_counts[loop["id"]] = count
if count > int(loop["maxIterations"]):
raise GraphError(
"回路 %s 已打回 %s 次,达到上限 %s。请人工处理节点 %s 后再继续"
% (loop["id"], count - 1, loop["maxIterations"], node_id)
)
return edge["to"]
def _only(self, node_id: str) -> str:
chosen = _plain_edges(self.edges, node_id)
if len(chosen) != 1:
raise GraphError("节点 %s 有 %s 条向前的边,调度不知道走哪条" % (node_id, len(chosen)))
return chosen[0]["to"]
def spawn_agent(command: str, node: dict, model: str, task: Optional[str]) -> str:
if not command.strip():
raise GraphError("没有配置子 agent 命令。run 时加上 --agent,例如 --agent 'opencode run'")
env = os.environ.copy()
env["WORKFLOW_SKILL"] = str(node.get("skill") or "")
env["WORKFLOW_NODE"] = node["id"]
env["WORKFLOW_MODEL"] = model
env["WORKFLOW_TASK"] = task or ""
argv = shlex.split(command) + ["--skill", str(node.get("skill") or ""), "--node", node["id"], "--model", model]
if task:
argv.extend(["--task", task])
try:
completed = subprocess.run(argv, env=env, text=True, capture_output=True, check=False)
except OSError as exc:
raise GraphError("启动子 agent 失败:%s。命令是:%s" % (exc, command)) from exc
if completed.returncode != 0:
raise GraphError(
"子 agent 退出码 %s,节点 %s。stderr:%s" % (completed.returncode, node["id"], completed.stderr.strip()[:400])
)
return completed.stdout

View File

@@ -0,0 +1,102 @@
"""一个迭代一条 workflow,进度落在 state.json。"""
from __future__ import annotations
import json
import os
import re
from .errors import GraphError
_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
def check_iteration(name: str) -> str:
if not name or not _NAME.match(name):
raise GraphError("迭代名不合法:%s。只用字母、数字、点、下划线和连字符" % name)
return name
def instance_dir(project: str, iteration: str) -> str:
return os.path.join(project, ".agents", "workflow", "iterations", check_iteration(iteration))
def state_path(project: str, iteration: str) -> str:
return os.path.join(instance_dir(project, iteration), "state.json")
def decisions_path(project: str, iteration: str) -> str:
return os.path.join(instance_dir(project, iteration), "decisions.jsonl")
def load_state(project: str, iteration: str) -> dict:
path = state_path(project, iteration)
if not os.path.isfile(path):
return {}
with open(path, "r", encoding="utf-8") as handle:
data = json.load(handle)
if not isinstance(data, dict):
raise GraphError("进度文件损坏:%s" % path)
return data
def save_state(project: str, iteration: str, state: dict) -> str:
path = state_path(project, iteration)
os.makedirs(os.path.dirname(path), exist_ok=True)
temporary = path + ".tmp"
with open(temporary, "w", encoding="utf-8") as handle:
json.dump(state, handle, ensure_ascii=False, indent=2)
handle.write("\n")
os.replace(temporary, path)
logged = int(state.get("logged") or 0)
progress = state.get("progress") or []
fresh = progress[logged:]
if fresh:
with open(decisions_path(project, iteration), "a", encoding="utf-8") as handle:
for item in fresh:
handle.write(json.dumps(item, ensure_ascii=False) + "\n")
state["logged"] = len(progress)
with open(temporary, "w", encoding="utf-8") as handle:
json.dump(state, handle, ensure_ascii=False, indent=2)
handle.write("\n")
os.replace(temporary, path)
return path
def list_states(project: str) -> list:
root = os.path.join(project, ".agents", "workflow", "iterations")
if not os.path.isdir(root):
return []
found = []
for name in sorted(os.listdir(root)):
path = os.path.join(root, name, "state.json")
if os.path.isfile(path):
with open(path, "r", encoding="utf-8") as handle:
found.append(json.load(handle))
return found
def open_instance(project: str, iteration: str, entry: str) -> dict:
"""没有记录就创建。已有记录就返回它,用来接着跑。已到提测则拒绝再开一条。"""
check_iteration(iteration)
existing = load_state(project, iteration)
if not existing:
state = {
"iteration": iteration,
"status": "running",
"current": entry,
"visits": {},
"loopCounts": {},
"tasks": [],
"taskIndex": 0,
"progress": [],
"logged": 0,
}
save_state(project, iteration, state)
return state
if existing.get("status") == "completed":
raise GraphError(
"迭代 %s 已经有一条 workflow,并且已经到提测。不能再创建一条。用 status --iteration %s 查看"
% (iteration, iteration)
)
return existing

View File

@@ -0,0 +1,174 @@
"""校验解析后的图。错误阻断,模型未拉开只警告。"""
from __future__ import annotations
import os
from typing import Any
WORK_KINDS = ("action", "gate", "decision", "human_input")
ACTORS = ("human", "master", "subagent")
REVIEW_PAIRS = (
("ba-write-spec", "ba-requirement-review"),
("dev-plan", "dev-plan-review"),
)
def node_map(graph: dict) -> dict:
return {node["id"]: node for node in graph.get("nodes") or []}
def extension_ids(graph: dict) -> set:
found = set()
for ext in graph.get("extensions") or []:
for node in ext.get("nodes") or []:
if "id" in node:
found.add(node["id"])
return found
def _model_value(graph: dict, node: dict) -> str:
key = node.get("model")
models = graph.get("models") or {}
if not key or key not in models:
return ""
spec = models[key]
if isinstance(spec, dict) and spec.get("env"):
return os.environ.get(str(spec["env"]), "")
return str(spec)
def validate(graph: dict) -> tuple:
"""返回 (errors, warnings)。errors 非空时图不能跑。"""
errors = []
warnings = []
nodes = graph.get("nodes") or []
edges = graph.get("edges") or []
ids = [node.get("id") for node in nodes]
if len(ids) != len(set(ids)):
errors.append("节点 id 有重复")
by_id = {}
for node in nodes:
node_id = node.get("id")
if not node_id:
errors.append("有节点缺少 id")
continue
by_id[node_id] = node
kind = node.get("kind")
actor = node.get("actor")
if kind not in WORK_KINDS and kind not in ("entry", "end"):
errors.append("节点 %s 的 kind 不合法:%s" % (node_id, kind))
if actor not in ACTORS:
errors.append("节点 %s 的 actor 必须是 human、master 或 subagent" % node_id)
if node.get("skill") and actor != "subagent":
errors.append("节点 %s 调用了 skill,actor 必须是 subagent" % node_id)
if kind == "end" and _outgoing(edges, node_id):
errors.append("终点 %s 不能有出边" % node_id)
if kind == "human_input" and len(_outgoing(edges, node_id)) > 1:
errors.append("人类输入 %s 只能有一条出边" % node_id)
if kind == "decision":
options = set(node.get("options") or [])
for edge in _outgoing(edges, node_id):
if edge.get("when") not in options:
errors.append("决策 %s 的出边 %s 不在选项里" % (node_id, edge.get("id")))
if kind == "gate":
for edge in _outgoing(edges, node_id):
if edge.get("when") not in ("满意", "不满意"):
errors.append("门禁 %s 的出边 %s 只能是满意或不满意" % (node_id, edge.get("id")))
entries = [node["id"] for node in nodes if node.get("kind") == "entry"]
ends = [node["id"] for node in nodes if node.get("kind") == "end"]
if entries != [graph.get("entry")]:
errors.append("入口必须恰好是 entry 节点 %s" % graph.get("entry"))
if len(ends) != 1:
errors.append("必须恰好有一个终点")
ext = extension_ids(graph)
notes = set()
for node in nodes:
if node.get("sealed"):
for item in node.get("note") or []:
notes.add(item)
known = set(by_id) | ext | notes
loops = graph.get("loops") or []
back_to_loop = {}
for loop in loops:
if "maxIterations" not in loop:
errors.append("回路 %s 缺少 maxIterations" % loop.get("id"))
for edge_id in loop.get("backEdges") or []:
back_to_loop[edge_id] = loop
for edge in edges:
edge_id = edge.get("id")
src = edge.get("from")
dst = edge.get("to")
if src not in by_id:
errors.append("边 %s 的起点不存在:%s" % (edge_id, src))
if dst in notes:
errors.append("边 %s 指向了封死节点内部的步骤 %s,不能加边" % (edge_id, dst))
elif dst in ext:
errors.append("边 %s 指向了未接入的扩展节点 %s" % (edge_id, dst))
elif dst not in by_id:
errors.append("边 %s 的终点不存在:%s" % (edge_id, dst))
if edge.get("back") and edge.get("when") and edge_id not in back_to_loop:
errors.append("打回边 %s 没有写入任何回路的上限" % edge_id)
if src in by_id and by_id[src].get("kind") in ("decision", "gate"):
if edge.get("when") not in ("满意", "不满意"):
errors.append("边 %s 从门禁或决策出发,when 只能是满意或不满意" % edge_id)
batches = {node["id"] for node in nodes if node.get("batch")}
consumed = {node.get("repeatsBatch") for node in nodes if node.get("repeatsBatch")}
missing = batches - consumed
if missing:
errors.append("批量节点没有被消费:%s" % "、".join(sorted(missing)))
for node in nodes:
target = node.get("repeatsBatch")
if target and target not in by_id:
errors.append("节点 %s 要循环的批量节点不存在:%s" % (node["id"], target))
if graph.get("entry") in by_id and not errors:
reached = _reachable(graph["entry"], edges)
stranded = [node_id for node_id in by_id if node_id not in reached]
if stranded:
errors.append("这些节点从入口走不到:%s。覆盖可能把图切断了" % "、".join(stranded))
for writer_id, reviewer_id in REVIEW_PAIRS:
writer = by_id.get(writer_id)
reviewer = by_id.get(reviewer_id)
if not writer or not reviewer:
continue
left = _model_value(graph, writer)
right = _model_value(graph, reviewer)
if not left or not right:
warnings.append("未配置对抗模型:%s 与 %s 将沿用主会话模型" % (writer_id, reviewer_id))
elif left == right:
warnings.append("未做对抗验证:%s 与 %s 使用了同一个模型" % (writer_id, reviewer_id))
return errors, warnings
def _outgoing(edges: list, node_id: str) -> list:
return [edge for edge in edges if edge.get("from") == node_id]
def _reachable(entry: str, edges: list) -> set:
seen = set()
stack = [entry]
while stack:
current = stack.pop()
if current in seen:
continue
seen.add(current)
for edge in edges:
if edge.get("from") == current:
stack.append(edge.get("to"))
return seen
def _model_value(graph: dict, node: dict) -> str:
key = node.get("model")
models = graph.get("models") or {}
if not key or key not in models:
return ""
spec: Any = models[key]
if isinstance(spec, dict) and spec.get("env"):
return os.environ.get(str(spec["env"]), "")
return str(spec)

View File

@@ -0,0 +1,549 @@
"""本模块自带的 YAML 子集解析器。
与 overnight-runner 的实现相同,但是一份拷贝:两个模块不许互相 import。
零第三方依赖,Python 3.9+。
"""
from __future__ import annotations
from typing import Any
__all__ = ["loads", "dumps", "YamlError"]
class YamlError(ValueError):
"""YAML 解析失败。消息里带行号,便于定位。"""
# 序列项标记(用不可能出现在正文里的字符,避免与缩进层级混淆)
_SEQ = "\x00seq"
# ── 行处理 ──────────────────────────────────────────────────────────
class _Line:
__slots__ = ("indent", "text", "lineno", "raw_idx")
def __init__(self, indent: int, text: str, lineno: int, raw_idx: int) -> None:
self.indent = indent
self.text = text
self.lineno = lineno
self.raw_idx = raw_idx
def __repr__(self) -> str: # pragma: no cover - 调试用
return f"_Line({self.indent}, {self.text!r}, line={self.lineno})"
def _strip_comment(text: str) -> str:
"""去掉引号外的注释。"""
out = []
quote = ""
i = 0
while i < len(text):
ch = text[i]
if quote:
out.append(ch)
if ch == "\\" and quote == '"' and i + 1 < len(text):
out.append(text[i + 1])
i += 2
continue
if ch == quote:
quote = ""
i += 1
continue
if ch in ("'", '"'):
quote = ch
out.append(ch)
i += 1
continue
if ch == "#" and (not out or out[-1] in " \t"):
break
out.append(ch)
i += 1
return "".join(out).rstrip()
def _split_key(text: str) -> tuple[str, str, str]:
"""拆 ``key: value``。
返回 (key, sep, value)。sep 为空表示这一行不是映射项。
引号内的冒号不算分隔符。
"""
quote = ""
i = 0
while i < len(text):
ch = text[i]
if quote:
if ch == "\\" and quote == '"' and i + 1 < len(text):
i += 2
continue
if ch == quote:
quote = ""
i += 1
continue
if ch in ("'", '"'):
quote = ch
i += 1
continue
if ch in "[{":
break
if ch == ":":
rest = text[i + 1:]
if rest == "" or rest[0] in " \t":
return text[:i].strip(), ":", rest.strip()
i += 1
return text.strip(), "", ""
def _unterminated(text: str) -> bool:
"""引号没闭合(只关心行尾的引号状态)。"""
t = text.rstrip()
if len(t) >= 1 and t[-1] in ("'", '"'):
# 可能闭合了,也可能是转义过的
return t.count(t[-1]) % 2 == 1
if t.startswith("'") or t.startswith('"'):
return True
return False
def _fold(parts: list[str]) -> str:
"""多行引号标量的折行规则:单换行折成空格,空行保留为换行。"""
result = ""
prev_blank = False
for i, ln in enumerate(parts):
if i == 0:
result = ln
continue
if ln.strip() == "":
result += "\n"
prev_blank = True
continue
if not prev_blank:
result += " "
result += ln
prev_blank = False
return result
def _preprocess(raw_lines: list[str]) -> list[_Line]:
"""把原始行变成逻辑行。
做三件事:
1. 跳过空行、整行注释、``---``
2. 把 ``- key: value`` 拆成序列标记 + 内容行
3. 把跨行的引号标量合并成一行
"""
out: list[_Line] = []
idx = 0
total = len(raw_lines)
while idx < total:
raw = raw_lines[idx]
if "\t" in raw[: len(raw) - len(raw.lstrip())]:
raise YamlError(f"第 {idx + 1} 行:YAML 缩进不能用 Tab")
stripped = raw.strip()
if not stripped or stripped.startswith("#"):
idx += 1
continue
if stripped == "---":
idx += 1
continue
if stripped in ("...",):
break
indent = len(raw) - len(raw.lstrip(" "))
text = _strip_comment(raw[indent:])
if text == "-" or text.startswith("- "):
rest = text[1:].strip()
key, sep, _ = _split_key(rest)
# 统一拆成:序列标记 + 内容行
out.append(_Line(indent, _SEQ, idx + 1, idx))
if rest:
content_indent = indent + 2 if (sep and key) else indent
out.append(_Line(content_indent, rest, idx + 1, idx))
idx += 1
continue
# 跨行的引号标量(PyYAML 会把带换行的字符串写成这种形式)
key, sep, val = _split_key(text)
if sep and val and _unterminated(val):
prefix = text[: len(text) - len(val)]
parts = [val]
j = idx + 1
while j < total and _unterminated(_fold(parts)):
parts.append(raw_lines[j].strip())
j += 1
out.append(_Line(indent, prefix + _fold(parts), idx + 1, idx))
idx = j
continue
out.append(_Line(indent, text, idx + 1, idx))
idx += 1
return out
# ── 标量 ────────────────────────────────────────────────────────────
_TRUE = {"true", "True", "TRUE"}
_FALSE = {"false", "False", "FALSE"}
_NULL = {"", "~", "null", "Null", "NULL"}
def _parse_scalar(text: str, lineno: int) -> Any:
t = text.strip()
if len(t) >= 2 and t[0] == '"' and t[-1] == '"':
return _unescape_double(t[1:-1], lineno)
if len(t) >= 2 and t[0] == "'" and t[-1] == "'":
return t[1:-1].replace("''", "'")
if t.startswith("[") and t.endswith("]"):
return _parse_flow_seq(t[1:-1], lineno)
if t.startswith("{") and t.endswith("}"):
return _parse_flow_map(t[1:-1], lineno)
if t in _TRUE:
return True
if t in _FALSE:
return False
if t in _NULL:
return None
try:
if t.lstrip("+-").isdigit():
return int(t)
except ValueError:
pass
try:
if any(c in t for c in ".eE") and t.lstrip("+-").replace(".", "", 1).isdigit():
return float(t)
except ValueError:
pass
return t
def _unescape_double(s: str, lineno: int) -> str:
out = []
i = 0
while i < len(s):
ch = s[i]
if ch == "\\" and i + 1 < len(s):
nxt = s[i + 1]
mapping = {"n": "\n", "t": "\t", "r": "\r", '"': '"', "\\": "\\", "/": "/", "0": "\0"}
if nxt in mapping:
out.append(mapping[nxt])
i += 2
continue
if nxt == "u" and i + 5 < len(s) + 1:
try:
out.append(chr(int(s[i + 2: i + 6], 16)))
i += 6
continue
except ValueError:
raise YamlError(f"第 {lineno} 行:非法的 \\u 转义")
raise YamlError(f"第 {lineno} 行:未知的转义 \\{nxt}")
out.append(ch)
i += 1
return "".join(out)
def _split_flow(body: str, lineno: int) -> list[str]:
"""按顶层逗号切分流式集合的内容。"""
parts = []
buf = []
depth = 0
quote = ""
for ch in body:
if quote:
buf.append(ch)
if ch == quote:
quote = ""
continue
if ch in ("'", '"'):
quote = ch
buf.append(ch)
continue
if ch in "[{":
depth += 1
elif ch in "]}":
depth -= 1
if ch == "," and depth == 0:
parts.append("".join(buf))
buf = []
continue
buf.append(ch)
tail = "".join(buf)
if tail.strip() or parts:
parts.append(tail)
return [p.strip() for p in parts]
def _parse_flow_seq(body: str, lineno: int) -> list:
body = body.strip()
if not body:
return []
return [_parse_scalar(p, lineno) for p in _split_flow(body, lineno)]
def _parse_flow_map(body: str, lineno: int) -> dict:
body = body.strip()
if not body:
return {}
out = {}
for part in _split_flow(body, lineno):
key, sep, value = _split_key(part)
if not sep:
raise YamlError(f"第 {lineno} 行:流式映射项格式错误: {part!r}")
out[_parse_scalar(key, lineno)] = _parse_scalar(value, lineno)
return out
# ── 块标量 ──────────────────────────────────────────────────────────
def _read_block_scalar(
raw_lines: list[str], start_raw: int, key_indent: int, style: str, lineno: int
) -> tuple[str, int]:
"""读块标量(| 或 >)。返回 (文本, 消耗到的 raw 索引)。"""
folded = style[0] == ">"
chomp = "clip"
if style.endswith("-"):
chomp = "strip"
elif style.endswith("+"):
chomp = "keep"
body: list[str] = []
i = start_raw
block_indent: int | None = None
while i < len(raw_lines):
raw = raw_lines[i]
if raw.strip() == "":
body.append("")
i += 1
continue
indent = len(raw) - len(raw.lstrip(" "))
if indent <= key_indent:
break
if block_indent is None:
block_indent = indent
body.append(raw[block_indent:] if len(raw) >= block_indent else "")
i += 1
# 去掉尾部空行(按 chomp 策略再决定加不加回来)
while body and body[-1] == "":
body.pop()
i -= 1
if folded:
text = ""
for idx, ln in enumerate(body):
if idx == 0:
text = ln
elif ln == "" or body[idx - 1] == "":
text += "\n" + ln
else:
text += " " + ln
else:
text = "\n".join(body)
if chomp == "strip":
return text, i
if chomp == "keep":
return text + "\n", i
return (text + "\n") if text else "", i
# ── 主解析 ──────────────────────────────────────────────────────────
def loads(text: str) -> Any:
"""解析 YAML 文本。"""
raw_lines = text.replace("\r\n", "\n").replace("\r", "\n").split("\n")
lines = _preprocess(raw_lines)
if not lines:
return None
value, idx = _parse_node(lines, 0, lines[0].indent, raw_lines)
if idx < len(lines):
raise YamlError(f"第 {lines[idx].lineno} 行:缩进异常")
return value
def _parse_node(lines: list[_Line], i: int, indent: int, raw_lines: list[str]) -> tuple[Any, int]:
if lines[i].text == _SEQ:
return _parse_sequence(lines, i, indent, raw_lines)
return _parse_mapping(lines, i, indent, raw_lines)
def _parse_mapping(
lines: list[_Line], i: int, indent: int, raw_lines: list[str]
) -> tuple[dict, int]:
result: dict = {}
while i < len(lines) and lines[i].indent == indent:
line = lines[i]
if line.text == _SEQ:
break
key, sep, rest = _split_key(line.text)
if not sep:
raise YamlError(f"第 {line.lineno} 行:期望 `key: value`,得到 {line.text!r}")
if key.startswith("&") or key.startswith("*") or key.startswith("!"):
raise YamlError(f"第 {line.lineno} 行:不支持锚点/别名/标签")
key_value = _parse_scalar(key, line.lineno)
if rest and rest[0] in "|>":
value, consumed = _read_block_scalar(
raw_lines, line.raw_idx + 1, indent, rest, line.lineno
)
result[key_value] = value
# 跳到块标量之后的第一条逻辑行
i += 1
while i < len(lines) and lines[i].raw_idx < consumed:
i += 1
continue
if rest == "":
nxt = lines[i + 1] if i + 1 < len(lines) else None
# 块序列可以与它的 key 同缩进(PyYAML 的写法),也可以更深
if nxt is not None and (
nxt.indent > indent
or (nxt.indent == indent and nxt.text == _SEQ)
):
value, i = _parse_node(lines, i + 1, nxt.indent, raw_lines)
else:
value = None
i += 1
else:
value = _parse_scalar(rest, line.lineno)
i += 1
result[key_value] = value
return result, i
def _parse_sequence(
lines: list[_Line], i: int, indent: int, raw_lines: list[str]
) -> tuple[list, int]:
result: list = []
while i < len(lines) and lines[i].indent == indent and lines[i].text == _SEQ:
marker = lines[i]
i += 1
if i >= len(lines):
result.append(None)
break
content = lines[i]
if content.indent == indent + 2:
# 序列项是映射
value, i = _parse_mapping(lines, i, content.indent, raw_lines)
result.append(value)
continue
if content.indent != indent:
# 空项 / 嵌套块
value, i = _parse_node(lines, i, content.indent, raw_lines)
result.append(value)
continue
rest = content.text
if rest and rest[0] in "|>":
value, consumed = _read_block_scalar(
raw_lines, marker.raw_idx + 1, indent, rest, marker.lineno
)
result.append(value)
i += 1
while i < len(lines) and lines[i].raw_idx < consumed:
i += 1
continue
result.append(_parse_scalar(rest, marker.lineno))
i += 1
return result, i
# ── 序列化 ──────────────────────────────────────────────────────────
_PLAIN_SAFE = set(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_./+@"
)
def _needs_quote(s: str) -> bool:
if s == "":
return True
if s.strip() != s:
return True
if s[0] in "-?:,[]{}#&*!|>'\"%@`":
return True
if ": " in s or " #" in s or s.endswith(":"):
return True
if "\n" in s or "\t" in s:
return True
if any(c not in _PLAIN_SAFE for c in s):
# 含中文、空格等 —— 加引号更安全
return True
if s in _TRUE or s in _FALSE or s in _NULL:
return True
try:
float(s)
return True
except ValueError:
return False
def _dump_scalar(value: Any) -> str:
if value is None:
return "null"
if value is True:
return "true"
if value is False:
return "false"
if isinstance(value, (int, float)):
return str(value)
s = str(value)
if "\n" in s:
return '"' + s.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n") + '"'
if _needs_quote(s):
return '"' + s.replace("\\", "\\\\").replace('"', '\\"') + '"'
return s
def dumps(data: Any, indent: int = 0) -> str:
"""把数据序列化成 YAML 子集文本。"""
lines: list[str] = []
def emit(node: Any, level: int) -> None:
pad = " " * (level * 2)
if isinstance(node, dict):
for key, value in node.items():
if isinstance(value, dict) and value:
lines.append(f"{pad}{key}:")
emit(value, level + 1)
elif isinstance(value, list) and value:
lines.append(f"{pad}{key}:")
emit(value, level + 1)
elif isinstance(value, dict):
lines.append(f"{pad}{key}: {{}}")
elif isinstance(value, list):
lines.append(f"{pad}{key}: []")
elif isinstance(value, str) and "\n" in value:
lines.append(f"{pad}{key}: |")
for ln in value.rstrip("\n").split("\n"):
lines.append(f"{pad} {ln}")
else:
lines.append(f"{pad}{key}: {_dump_scalar(value)}")
elif isinstance(node, list):
for item in node:
if isinstance(item, dict) and item:
first = True
for key, value in item.items():
prefix = f"{pad}- " if first else f"{pad} "
first = False
if isinstance(value, dict) and value:
lines.append(f"{prefix}{key}:")
emit(value, level + 2)
elif isinstance(value, list) and value:
lines.append(f"{prefix}{key}:")
emit(value, level + 2)
elif isinstance(value, str) and "\n" in value:
lines.append(f"{prefix}{key}: |")
for ln in value.rstrip("\n").split("\n"):
lines.append(f"{pad} {ln}")
else:
lines.append(f"{prefix}{key}: {_dump_scalar(value)}")
elif isinstance(item, (list, dict)):
lines.append(f"{pad}-")
emit(item, level + 1)
else:
lines.append(f"{pad}- {_dump_scalar(item)}")
else:
lines.append(f"{pad}{_dump_scalar(node)}")
emit(data, indent)
return "\n".join(lines) + "\n"

View File

@@ -0,0 +1,85 @@
id: iteration-to-test
entry: graph-start
lanes:
- { id: human, title: 人 }
- { id: master, title: graph-master }
- { id: subagent, title: 子 agent }
models:
writer: { env: MODEL_WRITER }
reviewer: { env: MODEL_REVIEWER }
loops:
- id: spec
maxIterations: 3
backEdges: [req-gate-reject, req-decision-reject]
- id: hld
maxIterations: 3
backEdges: [hld-reject]
- id: dev
maxIterations: 3
backEdges: [build-reject]
nodes:
- { id: graph-start, actor: master, kind: entry, title: 会话启动 }
- { id: start-version, actor: human, kind: human_input, title: 开始版本 }
- { id: pm-start-iteration, actor: subagent, kind: action, skill: pm-start-iteration, title: 开始迭代, model: writer }
- { id: write-spec, actor: human, kind: human_input, title: 编写规格 }
- { id: ba-write-spec, actor: subagent, kind: action, skill: ba-write-spec, title: 需求规格, model: writer }
- { id: ba-write-prototype, actor: subagent, kind: action, skill: ba-write-prototype, title: 原型, once: true, model: writer }
- { id: ba-requirement-review, actor: subagent, kind: gate, skill: ba-requirement-review, title: 需求质量门, model: reviewer }
- { id: requirement-decision, actor: human, kind: decision, title: 需求决策, options: [满意, 不满意] }
- { id: tech-brief, actor: human, kind: human_input, title: 技术高阶 }
- { id: tl-high-level-design, actor: subagent, kind: action, skill: tl-high-level-design, title: 技术高阶设计, once: true, model: writer }
- { id: hld-decision, actor: human, kind: decision, title: 高阶决策, options: [满意, 不满意] }
- { id: dev-plan, actor: subagent, kind: action, skill: dev-plan, title: 详细规划, batch: true, model: writer }
- { id: dev-plan-review, actor: subagent, kind: gate, skill: dev-plan-review, title: plan 质量门, model: reviewer }
- { id: plan-confirm, actor: human, kind: human_input, title: plan 确认 }
- { id: plan-decision, actor: human, kind: decision, title: plan 决策, options: [满意, 不满意] }
- { id: overnight-runner, actor: subagent, kind: action, skill: overnight-runner, title: 排本批顺序, model: writer }
- id: dev-build
actor: subagent
kind: action
skill: dev-build
title: 构建与自测
sealed: true
repeatsBatch: dev-plan
model: writer
note: [后端 TDD, 前端 TDD, 构建/Lint, 前端 UI review, API 测试, 浏览器自测]
- { id: build-decision, actor: human, kind: decision, title: 构建决策, options: [满意, 不满意] }
- { id: amend-input, actor: human, kind: human_input, title: 修订输入 }
- { id: dev-plan-amend, actor: subagent, kind: action, skill: dev-plan-amend, title: 规划修订, model: writer }
- { id: handoff, actor: master, kind: end, title: 提测 }
extensions:
- id: qa
title: 测试
linked: false
requires: pipeline
nodes:
- { id: qa-write-cases, kind: action, title: QA 用例 }
- { id: dev-create-mr, kind: action, title: 创建 MR/流水线部署 }
- { id: qa-run-e2e, kind: action, title: E2E 测试 }
- { id: manual-test, kind: human_input, title: 人工补测 }
edges:
- { id: e0, from: graph-start, to: start-version }
- { id: e1, from: start-version, to: pm-start-iteration }
- { id: e2, from: pm-start-iteration, to: write-spec }
- { id: e3, from: write-spec, to: ba-write-spec }
- { id: e4, from: ba-write-spec, to: ba-write-prototype }
- { id: e5, from: ba-write-spec, to: ba-requirement-review }
- { id: e6, from: ba-write-prototype, to: ba-requirement-review }
- { id: req-pass, from: ba-requirement-review, to: requirement-decision, when: 满意 }
- { id: req-gate-reject, from: ba-requirement-review, to: write-spec, when: 不满意, back: true }
- { id: req-decision-reject, from: requirement-decision, to: write-spec, when: 不满意, back: true }
- { id: e7, from: tech-brief, to: tl-high-level-design }
- { id: e8, from: tl-high-level-design, to: hld-decision }
- { id: req-ok, from: requirement-decision, to: tech-brief, when: 满意 }
- { id: hld-reject, from: hld-decision, to: tech-brief, when: 不满意, back: true }
- { id: hld-ok, from: hld-decision, to: dev-plan, when: 满意 }
- { id: e9, from: dev-plan, to: dev-plan-review }
- { id: plan-pass, from: dev-plan-review, to: plan-confirm, when: 满意 }
- { id: e10, from: plan-confirm, to: plan-decision }
- { id: plan-ok, from: plan-decision, to: overnight-runner, when: 满意 }
- { id: e11, from: overnight-runner, to: dev-build }
- { id: e12, from: dev-build, to: build-decision }
- { id: build-pass, from: build-decision, to: handoff, when: 满意 }
- { id: build-reject, from: build-decision, to: amend-input, when: 不满意, back: true }
- { id: e13, from: amend-input, to: dev-plan-amend }
- { id: e14, from: dev-plan-amend, to: dev-plan, back: true }

View File

@@ -0,0 +1,16 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "agents workflow graph",
"type": "object",
"required": ["id", "entry", "lanes", "nodes", "edges"],
"properties": {
"id": { "type": "string" },
"entry": { "type": "string" },
"lanes": { "type": "array" },
"models": { "type": "object" },
"loops": { "type": "array" },
"nodes": { "type": "array" },
"edges": { "type": "array" },
"extensions": { "type": "array" }
}
}

View File

@@ -0,0 +1,71 @@
#!/usr/bin/env bash
# 把工作流预设安装到目标项目的 .agents/workflow/preset.yaml。
# 不覆盖已有 overlay.yaml。
#
# 用法:
# ./install.sh <目标项目目录> [--dry-run] [--force]
#
# --dry-run 只打印将要写的文件
# --force 覆盖已有 preset.yaml
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
PRESET="$ROOT/presets/iteration-to-test.yaml"
DRY_RUN=0
FORCE=0
TARGET=""
usage() {
sed -n '2,9p' "$0" | sed 's/^# \{0,1\}//'
exit "${1:-0}"
}
while [ $# -gt 0 ]; do
case "$1" in
--dry-run) DRY_RUN=1 ;;
--force) FORCE=1 ;;
-h|--help) usage 0 ;;
-*) echo "未知参数: $1" >&2; usage 1 ;;
*) TARGET="$1" ;;
esac
shift
done
if [ -z "$TARGET" ]; then
echo "错误:缺少目标项目目录。" >&2
usage 1
fi
if [ ! -d "$TARGET" ]; then
echo "错误:目标目录不存在: $TARGET" >&2
exit 1
fi
PROJECT="$(cd "$TARGET" && pwd)"
DEST="$PROJECT/.agents/workflow"
FILE="$DEST/preset.yaml"
echo "agents-workflow-engine 安装器"
echo " 预设: $PRESET"
echo " 目标: $FILE"
if [ "$DRY_RUN" -eq 1 ]; then
if [ -f "$FILE" ] && [ "$FORCE" -eq 0 ]; then
echo " 跳过: 已存在 preset.yaml(没有 --force)"
else
echo " 将写入 preset.yaml"
fi
echo " 不碰 overlay.yaml"
exit 0
fi
mkdir -p "$DEST"
if [ -f "$FILE" ] && [ "$FORCE" -eq 0 ]; then
echo " 跳过: 已存在 $FILE"
exit 0
fi
tmp="$FILE.tmp.$$"
cp "$PRESET" "$tmp"
mv "$tmp" "$FILE"
echo " 已写入 $FILE"
echo " 未修改 overlay.yaml"

View File

@@ -0,0 +1,186 @@
#!/usr/bin/env python3
"""agents-workflow-engine 单元测试。"""
from __future__ import annotations
import os
import sys
import tempfile
import unittest
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, ROOT)
from agents_workflow_engine.errors import GraphError # noqa: E402
from agents_workflow_engine.load import load_preset # noqa: E402
from agents_workflow_engine.merge import merge # noqa: E402
from agents_workflow_engine.render_mermaid import render # noqa: E402
from agents_workflow_engine.runner import Runner # noqa: E402
from agents_workflow_engine.validate import validate # noqa: E402
from agents_workflow_engine.yaml_lite import loads # noqa: E402
def happy_answers():
return {
"start-version": ["iteration1"],
"write-spec": ["登录"],
"requirement-decision": ["满意"],
"tech-brief": ["账号"],
"hld-decision": ["满意"],
"plan-confirm": ["确认"],
"plan-decision": ["满意"],
"build-decision": ["满意"],
}
def fake_agent(calls):
def run(node, model, task):
calls.append((node["id"], model, task))
skill = node.get("skill")
if skill == "dev-plan":
return "TASK: a\nTASK: b\n"
if skill in ("ba-requirement-review", "dev-plan-review"):
return "满意\n"
return "ok\n"
return run
class PresetTest(unittest.TestCase):
def test_preset_valid_and_warns_when_model_unset(self):
graph = load_preset()
errors, warnings = validate(graph)
self.assertEqual(errors, [])
self.assertTrue(any("未配置对抗模型" in item for item in warnings))
def test_distinct_models_have_no_same_model_warning(self):
os.environ["MODEL_WRITER"] = "writer-a"
os.environ["MODEL_REVIEWER"] = "reviewer-b"
try:
errors, warnings = validate(load_preset())
finally:
del os.environ["MODEL_WRITER"]
del os.environ["MODEL_REVIEWER"]
self.assertEqual(errors, [])
self.assertFalse(any("未做对抗验证" in item for item in warnings))
self.assertFalse(any("未配置对抗模型" in item for item in warnings))
def test_render_shapes_and_hides_extensions(self):
text = render(load_preset())
self.assertIn("flowchart LR", text)
self.assertIn("dev-plan(详细规划 · 一批任务)", text)
self.assertIn("ba-requirement-review[[需求质量门]]", text)
self.assertIn("start-version[/开始版本/]", text)
self.assertIn("requirement-decision{需求决策}", text)
self.assertIn("handoff([提测])", text)
self.assertIn("graph-start{{会话启动}}", text)
self.assertIn("后端 TDD", text)
self.assertNotIn("qa-write-cases", text)
self.assertIn("-.->|不满意|", text)
def test_disable_prototype_still_reaches_end(self):
graph = merge(load_preset(), {"disable": ["ba-write-prototype"]})
errors, _warnings = validate(graph)
self.assertEqual(errors, [])
self.assertNotIn("ba-write-prototype", {node["id"] for node in graph["nodes"]})
def test_edge_into_sealed_step_fails(self):
graph = load_preset()
graph["edges"].append({"id": "bad", "from": "dev-build", "to": "后端 TDD"})
errors, _warnings = validate(graph)
self.assertTrue(any("封死" in item for item in errors))
def test_edge_into_extension_fails(self):
graph = load_preset()
graph["edges"].append({"id": "bad", "from": "handoff", "to": "qa-write-cases"})
errors, _warnings = validate(graph)
self.assertTrue(any("扩展" in item for item in errors))
def test_back_edge_without_loop_fails(self):
graph = load_preset()
graph["loops"] = [loop for loop in graph["loops"] if loop["id"] != "spec"]
errors, _warnings = validate(graph)
self.assertTrue(any("没有写入任何回路" in item for item in errors))
def test_replace_skill(self):
graph = merge(load_preset(), {"replace": {"ba-write-spec": {"skill": "my-write-spec"}}})
node = [item for item in graph["nodes"] if item["id"] == "ba-write-spec"][0]
self.assertEqual(node["skill"], "my-write-spec")
class RunTest(unittest.TestCase):
def test_happy_path_runs_build_once_per_task(self):
calls = []
log = []
end = Runner(load_preset(), happy_answers(), fake_agent(calls), "master", log).run()
self.assertEqual(end, "handoff")
build_calls = [item for item in calls if item[0] == "dev-build"]
self.assertEqual([item[2] for item in build_calls], ["a", "b"])
self.assertTrue(any(item.get("event") == "batch" for item in log))
def test_spec_reject_then_pass(self):
calls = []
answers = happy_answers()
answers["write-spec"] = ["第一稿", "第二稿"]
answers["requirement-decision"] = ["不满意", "满意"]
end = Runner(load_preset(), answers, fake_agent(calls), "master", []).run()
self.assertEqual(end, "handoff")
self.assertEqual(sum(1 for item in calls if item[0] == "ba-write-spec"), 2)
self.assertEqual(sum(1 for item in calls if item[0] == "ba-write-prototype"), 1)
def test_loop_cap_stops(self):
answers = happy_answers()
answers["write-spec"] = ["a", "b", "c", "d"]
answers["requirement-decision"] = ["不满意", "不满意", "不满意", "不满意"]
with self.assertRaises(GraphError) as caught:
Runner(load_preset(), answers, fake_agent([]), "master", []).run()
self.assertIn("达到上限", str(caught.exception))
def test_missing_answer_names_the_node(self):
with self.assertRaises(GraphError) as caught:
Runner(load_preset(), {}, fake_agent([]), "master", []).run()
self.assertIn("start-version", str(caught.exception))
def test_same_model_is_logged(self):
os.environ["MODEL_WRITER"] = "same"
os.environ["MODEL_REVIEWER"] = "same"
log = []
try:
Runner(load_preset(), happy_answers(), fake_agent([]), "master", log).run()
finally:
del os.environ["MODEL_WRITER"]
del os.environ["MODEL_REVIEWER"]
self.assertTrue(any(item.get("warning") == "未做对抗验证" for item in log))
def test_cli_run_writes_jsonl(self):
from agents_workflow_engine.cli import main
with tempfile.TemporaryDirectory() as folder:
answers = os.path.join(folder, "answers.yaml")
with open(answers, "w", encoding="utf-8") as handle:
handle.write(loads and "")
text = "\n".join("%s: %s" % (key, value[0]) for key, value in happy_answers().items()) + "\n"
with open(answers, "w", encoding="utf-8") as handle:
handle.write(text)
agent = os.path.join(folder, "agent.sh")
with open(agent, "w", encoding="utf-8") as handle:
handle.write(
"#!/bin/sh\n"
"case \"$2\" in\n"
" dev-plan) printf 'TASK: a\\nTASK: b\\n' ;;\n"
" ba-requirement-review|dev-plan-review) printf '满意\\n' ;;\n"
" *) printf 'ok\\n' ;;\n"
"esac\n"
)
os.chmod(agent, 0o755)
code = main(["--project", folder, "run", "--answers", answers, "--agent", agent])
self.assertEqual(code, 0)
record = os.path.join(folder, ".agents", "workflow", "decisions.jsonl")
self.assertTrue(os.path.isfile(record))
with open(record, encoding="utf-8") as handle:
body = handle.read()
self.assertIn("handoff", body)
self.assertIn('"task": "b"', body)
if __name__ == "__main__":
unittest.main()