VibeCoding / src /modules /skill /graph /compiler.py
dellweb3's picture
Deploy verified conversational workbench and isolated Java application previews
5ca3c16 verified
Raw History Blame Contribute Delete
11.6 kB
"""DAG/type/gate compiler. Fail closed; no eval, dynamic imports or shell."""
from collections import defaultdict, deque
from src.modules.skill.domain.models import Draft, Framework, Issue, ValidationReport, digest, fits
def compile_graph(draft: Draft, operations: dict, framework: Framework | None):
issues = []
def error(code, location, message):
issues.append(Issue(code=code, location=location, message=message))
nodes = {n.id: n for n in draft.graph.nodes}
if len(nodes) != len(draft.graph.nodes):
error("DUPLICATE_NODE", "graph.nodes", "节点ID必须唯一。")
start = [n.id for n in nodes.values() if n.kind == "start"]
end = [n.id for n in nodes.values() if n.kind == "end"]
if len(start) != 1 or len(end) != 1:
error("START_END_COUNT", "graph.nodes", "必须有唯一开始与结束。")
parents, children = defaultdict(set), defaultdict(set)
seen = set()
for i, edge in enumerate(draft.graph.control_edges):
if edge.source not in nodes or edge.target not in nodes:
error("UNKNOWN_NODE", f"control_edges.{i}", "控制边引用不存在节点。")
continue
if (edge.source, edge.target) in seen:
error("DUPLICATE_EDGE", f"control_edges.{i}", "不能重复控制边。")
seen.add((edge.source, edge.target))
parents[edge.target].add(edge.source)
children[edge.source].add(edge.target)
degree = {n: len(parents[n]) for n in nodes}
pending = deque(sorted(n for n in nodes if degree[n] == 0))
order = []
while pending:
n = pending.popleft()
order.append(n)
for child in sorted(children[n]):
degree[child] -= 1
if degree[child] == 0:
pending.append(child)
if len(order) != len(nodes):
error("CONTROL_CYCLE", "graph.control_edges", "首版不支持回边;修复由Agent有界状态机处理。")
ancestors, dominators = {}, {}
for n in order:
ancestors[n] = set().union(*(ancestors.get(p, set()) | {p} for p in parents[n])) if parents[n] else set()
dominators[n] = ({n} | set.intersection(*(dominators[p] for p in parents[n]))) if parents[n] else {n}
if len(start) == 1 and len(end) == 1:
for n in nodes:
if (n != start[0] and start[0] not in ancestors.get(n, set())) or (n != end[0] and n not in ancestors.get(end[0], set())):
error("DISCONNECTED_NODE", "nodes." + n, "每个节点都必须从开始可达且能到达结束。")
if parents[start[0]] or children[end[0]]:
error("START_END_DIRECTION", "graph.control_edges", "开始无入边、结束无出边。")
input_types, output_types, resolved, locks = {}, {}, {}, {}
calls = token_limits = 0
for node in nodes.values():
if node.kind == "operation":
op = operations.get(node.operation_ref)
if not op or op.state != "approved":
error("OPERATION_UNAVAILABLE", "nodes." + node.id, "原子操作必须引用精确批准版本。")
continue
resolved[node.id] = op
locks[node.operation_ref] = digest(op)
input_types[node.id] = {p.name: (p.type, p.required) for p in op.inputs}
output_types[node.id] = {p.name: p.type for p in op.outputs}
calls += op.model_calls
token_limits += op.token_limit
else:
input_types[node.id] = ({"manifest": ("object", True)} if node.kind == "end" else
{"requirement": ("string", False), "query": ("string", False),
"attachments": ("array", False)} if node.kind == "start" else {})
output_types[node.id] = {"requirement": "string", "query": "string"} if node.kind == "start" else {}
incoming = defaultdict(set)
for i, edge in enumerate(draft.graph.data_edges):
location = f"data_edges.{i}"
source_type = output_types.get(edge.source, {}).get(edge.source_port)
target_type = input_types.get(edge.target, {}).get(edge.target_port)
if not source_type or not target_type:
error("UNKNOWN_PORT", location, "数据边端口不存在。")
elif source_type != target_type[0]:
error("PORT_TYPE_MISMATCH", location, "数据边类型不一致。")
if edge.source not in ancestors.get(edge.target, set()):
error("DATA_ORDER", location, "数据必须来自控制流上游。")
if edge.target_port in incoming[edge.target]:
error("MULTIPLE_INPUT_SOURCES", location, "输入字段不能有多个数据来源。")
incoming[edge.target].add(edge.target_port)
for node in nodes.values():
fields = input_types.get(node.id, {})
for name, value in node.inputs.items():
if name not in fields:
error("UNKNOWN_INPUT", "nodes." + node.id + "." + name, "存在未声明输入。")
elif not fits(value, fields[name][0]):
error("LITERAL_TYPE", "nodes." + node.id + "." + name, "字面输入类型错误。")
if name in incoming[node.id]:
error("MULTIPLE_INPUT_SOURCES", "nodes." + node.id + "." + name, "字面量与数据边不能同时绑定。")
for name, (_, required) in fields.items():
if required and name not in node.inputs and name not in incoming[node.id]:
error("REQUIRED_INPUT", "nodes." + node.id + "." + name, "缺少必填输入。")
# Evidence/source objects cannot be replaced by a user literal or another object-shaped port.
producers = {"AO03": {"document": ("AO01", "document"), "citations": ("AO02", "citations")},
"AO04": {"snapshot": ("AO03", "snapshot")}, "AO05": {"design": ("AO04", "design")},
"AO06": {"patch": ("AO13" if any(op.operation_id=='AO13' for op in resolved.values()) else "AO05", "patch")},
"AO13": {"patch": ("AO05", "patch"), "design": ("AO04", "design")}, "AO07": {"source": ("AO06", "source")},
"AO08": {"source": ("AO06", "source"), "policy_evidence": ("AO07", "policy_evidence")},
"AO09": {"candidate": ("AO08", "candidate")},
"AO10": {"candidate": ("AO08", "candidate"), "test_evidence": ("AO09", "test_evidence")},
"AO11": {"preview_evidence": ("AO10", "preview_evidence"), "test_evidence": ("AO09", "test_evidence")}}
for node_id, op in resolved.items():
if op.operation_id == "AO12":
error("REPAIR_OWNED_BY_AGENT", "nodes." + node_id, "失败修复由Agent状态机发起,不放进常规成功路径。")
for port, expected in producers.get(op.operation_id, {}).items():
edges = [e for e in draft.graph.data_edges if e.target == node_id and e.target_port == port]
if len(edges) != 1 or edges[0].source not in resolved or (resolved[edges[0].source].operation_id, edges[0].source_port) != expected:
error("UNTRUSTED_STAGE_INPUT", "nodes." + node_id + "." + port, "必须引用对应上游阶段产物,不能注入替代证据。")
bindings = {b.name for b in draft.knowledge_bindings}
resource_bindings = defaultdict(set)
for i, edge in enumerate(draft.graph.resource_edges):
if edge.node not in nodes or edge.kind == "knowledge" and edge.resource not in bindings or edge.kind == "framework" and (framework is None or edge.resource != framework.profile_id):
error("RESOURCE_REFERENCE", f"resource_edges.{i}", "资源边必须引用已绑定知识或当前框架。")
resource_bindings[edge.node].add(edge.kind)
for n, op in resolved.items():
prior = dominators.get(n, set()) - {n}
gates = {nodes[p].approval_scope for p in prior if nodes[p].kind == "approval"}
prior_ops = {resolved[p].operation_id for p in prior if p in resolved}
if op.operation_id in {"AO05", "AO06", "AO08", "AO09", "AO10", "AO11", "AO13"} and "design" not in gates:
error("DESIGN_GATE_BYPASS", "nodes." + n, "所有编程路径必须经过设计确认。")
if op.operation_id in {"AO06", "AO08", "AO09", "AO10", "AO13"} and "execution" not in gates:
error("EXECUTION_GATE_BYPASS", "nodes." + n, "所有写入/执行路径必须经过执行授权。")
required_before = {"AO07": "AO06", "AO08": "AO07", "AO09": "AO08", "AO10": "AO09", "AO11": "AO10"}.get(op.operation_id)
if op.operation_id=='AO06' and any(o.operation_id=='AO13' for o in resolved.values()):required_before='AO13'
if required_before and required_before not in prior_ops:
error("QUALITY_GATE_BYPASS", "nodes." + n, "缺少强制上游阶段:" + required_before)
if op.operation_id == "AO11" and "acceptance" not in gates:
error("ACCEPTANCE_GATE_BYPASS", "nodes." + n, "交付前必须确认运行成果。")
if op.operation_id == "AO02" and "knowledge" not in resource_bindings[n]:
error("KNOWLEDGE_BINDING_REQUIRED", "nodes." + n, "检索操作必须绑定知识范围。")
if op.operation_id in {"AO05", "AO07"} and "framework" not in resource_bindings[n]:
error("FRAMEWORK_BINDING_REQUIRED", "nodes." + n, "代码生成与检查必须绑定框架。")
if len(end) == 1:
mandatory = {"AO04", "AO05", "AO06", "AO07", "AO08", "AO09", "AO10", "AO11"}
actual = {resolved[n].operation_id for n in dominators.get(end[0], set()) if n in resolved}
if not mandatory.issubset(actual):
error("INCOMPLETE_CODING_FLOW", "graph", "结束路径必须包含设计、代码、检查、构建、独立测试、预览与证据。")
manifest_edges = [e for e in draft.graph.data_edges if e.target == end[0] and e.target_port == "manifest"]
if len(manifest_edges) != 1 or manifest_edges[0].source not in resolved or resolved[manifest_edges[0].source].operation_id != "AO11" or manifest_edges[0].source_port != "manifest":
error("UNTRUSTED_MANIFEST", "nodes." + end[0], "最终结果必须引用证据登记操作的manifest。")
if framework is None or framework.state != "approved":
error("FRAMEWORK_UNAVAILABLE", "framework_ref", "框架画像必须为精确批准版本。")
if not draft.knowledge_bindings:
error("KNOWLEDGE_REQUIRED", "knowledge_bindings", "编程Skill至少绑定一个知识范围。")
repair_reserve=32000 if any(op.operation_id=='AO05' and op.version=='0.2.0' for op in resolved.values()) else 20000
# Review uses complete candidates. Its larger per-stage ceiling is not a
# preallocation: all calls/repairs are charged against one RuntimeStore budget.
# Do not reject a reachable flow by summing worst-case ceilings of all repairs.
if any(op.operation_id=='AO13' and op.version=='0.2.0' for op in resolved.values()):repair_reserve=0
if calls + draft.budget.max_repairs > draft.budget.max_model_calls or token_limits + draft.budget.max_repairs * repair_reserve > draft.budget.max_tokens:
error("BUDGET_UNREACHABLE", "budget", "主流程与预留修复超过同一任务的总预算。")
payload = {"draft": draft.model_dump(mode="json"), "operations": locks, "framework": framework.model_dump(mode="json") if framework else None}
return ValidationReport(valid=not issues, digest=digest(payload), issues=issues, execution_order=order,
operation_locks=locks, model_calls=calls, model_token_limits=token_limits)