mirror of
https://github.com/ThearchyHelios/AgentLab.git
synced 2026-11-24 23:22:29 +00:00
fcdcc30d4e
一、可点击证据第二期
取数链路
- 智能体、工具节点、代码节点、知识检索取数时都记进证据台账;报告目录按台账编出 Q1… / K1…
- 报告可以引用快照里的一格([[v:Q1.r0.gmv]]),也可以由系统从快照生成整张表([[table:Q1 cols=… rows=0-4]]),
表里每一格都是可点的片段;取值一律以快照为准,取回快照时复验哈希
- 口径卡表达式新增 cell(x, row, column),lineage 精确到单元格
- 智能体开 cite_fields(配合 output_schema)后,循环结束做一次结构化抽取,每个字段标出取自哪次查询的哪一格,
再到快照里核对:一致记 verified;不一致以快照为准并告警;查不到的记为空值,永远不兜底成 0
- 代码节点新增 evidence_role(source / compute)和 code_sha;沙箱算出来的数不能被报告直接引用,要进口径卡
- 查询快照记下列类型,文本列按文本渲染(年份 "2026" 不再显示成「2,026」)
- 升级前发起的运行(停在审批上的)一律走旧逻辑:新的 task 只追加在循环之后,恢复时不会错号
证据接口与面板
- 片段链接上查询步骤:SQL、被引用的行加前后各 2 行、高亮到格;数据源可设 mask_columns 遮罩列,
遮罩在查询时记进快照,数据源事后改名或删除也照样遮罩(在有身份体系之前,遮罩只减少暴露,不是安全边界)
- 输入来源写明核对结果(与快照一致 / 模型报的值和快照不一致 / 没查到记为空);口径卡缺输入时也给出完整的链
- 受管出具要在契约里声明 cells 才能引用单元格;受管与否记在所钉版本上,改画布不再让受管版本的正式运行降级
- 口径卡可以用 caliber_from 钉住另一个已发布工作流里的口径卡,上游有新版本时按 upgrade_policy 处置,
和子工作流同一套规则;子工作流节点也补上了升版处置的配置项
Copilot、校验与报错
- 问数据的答案里有数字时,搭 input → 智能体 → 报告 → 出口,报告直接引用查过的单元格
- 写 SQL 前核对数据源的表结构,SQL 里出现表结构里没有的列会被打回
- 不再搭「智能体文字 → 转换节点解析 JSON」这种图;转换节点的 JSON 报错分清是上游模型写坏了、
模板里裸插了模型文字(给出 | json 的改法),还是模板本身写错了
- 工具节点遇到「查询失败」「SQL 被拒绝」判为失败;发起运行前检查绑定的工具是否存在,不存在时直接拒绝并给出入口
二、发布前自动修复
- 问题带上机器编号(code)和修复 id;新增只读接口 POST /api/workflows/{id}/publish-check 和 /autofix
- 修复分三类:答案唯一、不降低要求的一键修复;要人拿主意的给选项(不替人选);结构性问题交给 Copilot
- 一律先预览,不自动保存、不自动发布;删节点、删契约、放宽审批、关掉 strict、改级别等降低要求的改动一律拒绝,
Copilot 的方案也要过这一关;应用后重跑检查,错误必须变少且不能冒出新的
- 发布弹窗打开就先检查;问题面板新增「发布前检查」,平时就能看到、就地修掉
- 门禁修正:契约有 report_from 时不再要求 narrative(模板⑨可以发成受管);全图默认审批为「全部放行」时同样拦下
- 修掉画布保存会抹掉全图默认(defaults)的老问题:以前任何一次保存都会把它清空,审批 always 因此被悄悄放宽
验证(沙箱):tsc 干净,生产构建通过,pytest 2268 passed(两遍),check-all 17 项检查、3915 项全过
(新增 check-publish);关键行为做了变异验证、全部抓到。
279 lines
14 KiB
Python
279 lines
14 KiB
Python
"""自动修复的 Copilot 兜底(autofix 的 assist: true)。
|
|
|
|
确定性修复修不了的 error 交给 Copilot:模型给剧本,看采纳规则——
|
|
- 正常的修复(error 变少、没有新 error、不降低要求)被采纳,只是预览,不落库
|
|
- 试图删契约的被拒
|
|
- 让错误变多的被拒
|
|
- 要人拿主意的放进 questions,不硬改
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
|
|
import pytest
|
|
from httpx import ASGITransport, AsyncClient
|
|
from sqlalchemy import select
|
|
|
|
from app.db.base import SessionLocal
|
|
from app.db.models import Workflow, WorkflowVersion
|
|
from app.main import app
|
|
|
|
|
|
@pytest.fixture
|
|
async def client():
|
|
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c:
|
|
yield c
|
|
|
|
|
|
def node(nid, ntype, label=None, **config):
|
|
return {"id": nid, "type": ntype, "position": {"x": 40, "y": 80}, "data": {"label": label or nid, "config": config}}
|
|
|
|
|
|
CONTRACT = {"report_from": "write", "metrics_from": ["card"], "required": ["gmv"], "strict": True}
|
|
|
|
|
|
def two_exits() -> dict:
|
|
"""受管模板没有带契约的出口,而且出口有两个:该给哪个写契约说不准,确定性修复只能交给 Copilot。"""
|
|
nodes = [
|
|
node("start", "input", "周期"),
|
|
node("fetch", "tool", "取数", tool="db_query__shop", args={"sql": "SELECT SUM(amount) AS gmv FROM orders"}),
|
|
node("card", "metrics", "周报口径卡", caliber="周报口径", metrics=[
|
|
{"id": "gmv", "name": "销售额", "unit": "元", "expression": "cell(nodes.fetch, 0, 'gmv')"}]),
|
|
node("write", "report", "报告撰写", instructions="写周报"),
|
|
node("done", "output", "出具", fields=[{"name": "周报", "value": "{{ nodes.write.text }}"}]),
|
|
node("raw", "output", "原始数", fields=[{"name": "数", "value": "{{ nodes.fetch }}"}]),
|
|
]
|
|
edges = [{"id": f"e{i}", "source": a, "target": b} for i, (a, b) in enumerate(
|
|
[("start", "fetch"), ("fetch", "card"), ("card", "write"), ("write", "done"), ("fetch", "raw")])]
|
|
return {"nodes": nodes, "edges": edges, "viewport": {"x": 3, "y": 4, "zoom": 1.2}}
|
|
|
|
|
|
class Scripted:
|
|
"""按剧本吐操作流的模型;记下每次收到的请求。"""
|
|
|
|
def __init__(self, ops: list[dict]) -> None:
|
|
self.lines = [json.dumps(o, ensure_ascii=False) for o in ops]
|
|
self.calls: list[list] = []
|
|
|
|
async def astream(self, messages):
|
|
from langchain_core.messages import AIMessageChunk
|
|
|
|
self.calls.append(messages)
|
|
for line in self.lines:
|
|
yield AIMessageChunk(content=line + "\n")
|
|
|
|
|
|
def script(monkeypatch, ops: list[dict]) -> Scripted:
|
|
import app.api.copilot as copilot
|
|
|
|
model = Scripted(ops)
|
|
|
|
async def _model(*_a, **_k):
|
|
return model, "mock-fast"
|
|
|
|
monkeypatch.setattr(copilot, "get_chat_model", _model)
|
|
return model
|
|
|
|
|
|
async def create(client, graph: dict) -> str:
|
|
return (await client.post("/api/workflows", json={"name": "周报-兜底", "graph": graph})).json()["id"]
|
|
|
|
|
|
async def rows(wf: str) -> list:
|
|
async with SessionLocal() as session:
|
|
w = await session.get(Workflow, wf)
|
|
vs = (await session.execute(select(WorkflowVersion).where(WorkflowVersion.workflow_id == wf))).scalars()
|
|
return [{c.name: getattr(w, c.name) for c in Workflow.__table__.columns},
|
|
[{c.name: getattr(v, c.name) for c in WorkflowVersion.__table__.columns} for v in vs]]
|
|
|
|
|
|
async def assist(client, wf: str, **extra) -> dict:
|
|
r = await client.post(f"/api/workflows/{wf}/autofix", json={"level": "governed", "apply": [], "assist": True,
|
|
**extra})
|
|
assert r.status_code == 200, r.text
|
|
return r.json()
|
|
|
|
|
|
def done(ops: list[dict]) -> list[dict]:
|
|
return [{"op": "plan", "summary": "给出具节点补契约"}, *ops, {"op": "done", "explanation": "补上了出具契约"}]
|
|
|
|
|
|
async def test_a_sound_fix_is_adopted_as_a_preview(client, monkeypatch):
|
|
model = script(monkeypatch, done([{"op": "update_node", "id": "done", "config": {"contract": CONTRACT}}]))
|
|
wf = await create(client, two_exits())
|
|
before = await rows(wf)
|
|
out = await assist(client, wf)
|
|
assert out["assist"]["ok"] is True and out["assist"]["summary"] == "补上了出具契约"
|
|
assert out["applied"] == ["assist"] and out["ok"] is True, out
|
|
fixed = out["graph"]
|
|
assert next(n for n in fixed["nodes"] if n["id"] == "done")["data"]["config"]["contract"] == CONTRACT
|
|
assert fixed["viewport"] == two_exits()["viewport"] and [e["id"] for e in fixed["edges"]] == [
|
|
e["id"] for e in two_exits()["edges"]]
|
|
assert out["ops"] == [{"op": "update_node", "id": "done", "config": {"contract": CONTRACT}}]
|
|
assert [(c["fix_id"], c["node_id"], c["field"]) for c in out["changes"]] == [("assist", "done", "contract")]
|
|
assert await rows(wf) == before # 只是预览
|
|
# 交给模型的请求里有剩下的问题和不许降低要求、不许替人选的约定
|
|
human = next(text for role, text in model.calls[0] if role == "human")
|
|
assert "受管模板至少要有一个「成果 / 出具」节点声明出具契约" in human
|
|
assert "不许降低要求" in human and "不替人选" in human and "question" in human
|
|
|
|
|
|
async def test_deleting_the_contract_is_refused(client, monkeypatch):
|
|
graph = two_exits()
|
|
graph["nodes"][4]["data"]["config"]["contract"] = {**CONTRACT, "report_from": "fetch"}
|
|
graph["nodes"][3] = node("write", "llm", "写周报", prompt="写周报") # 没有报告撰写节点:只能交给 Copilot
|
|
script(monkeypatch, done([{"op": "update_node", "id": "done", "config": {"contract": None}}]))
|
|
wf = await create(client, graph)
|
|
out = await assist(client, wf)
|
|
assert out["assist"]["ok"] is False and "assist" not in out["applied"]
|
|
[rejected] = [r for r in out["rejected"] if r["fix_id"] == "assist"]
|
|
assert "契约" in rejected["reason"] and "降低" in rejected["reason"]
|
|
assert out["graph"] == graph and out["ok"] is False
|
|
|
|
|
|
async def test_a_fix_that_makes_errors_grow_is_refused(client, monkeypatch):
|
|
script(monkeypatch, done([
|
|
{"op": "update_node", "id": "done", "config": {"contract": CONTRACT}},
|
|
{"op": "update_node", "id": "card", "config": {"metrics": [{"id": "gmv"}]}}, # 口径卡的表达式被写丢了
|
|
]))
|
|
wf = await create(client, two_exits())
|
|
out = await assist(client, wf)
|
|
assert out["assist"]["ok"] is False
|
|
[rejected] = [r for r in out["rejected"] if r["fix_id"] == "assist"]
|
|
assert "新的问题" in rejected["reason"] and "expression" in rejected["reason"]
|
|
assert out["graph"] == two_exits()
|
|
|
|
|
|
async def test_removing_a_node_is_refused_even_if_it_helps(client, monkeypatch):
|
|
script(monkeypatch, done([
|
|
{"op": "remove_node", "id": "raw"},
|
|
{"op": "update_node", "id": "done", "config": {"contract": CONTRACT}},
|
|
]))
|
|
wf = await create(client, two_exits())
|
|
out = await assist(client, wf)
|
|
[rejected] = [r for r in out["rejected"] if r["fix_id"] == "assist"]
|
|
assert "删" in rejected["reason"] and out["graph"] == two_exits()
|
|
|
|
|
|
async def test_questions_are_passed_on_without_changes(client, monkeypatch):
|
|
script(monkeypatch, [
|
|
{"op": "plan", "summary": "要先问清楚"},
|
|
{"op": "question", "node_id": "done", "text": "两个出口里,哪个是要出具的?「出具」还是「原始数」?"},
|
|
{"op": "question", "node_id": "card", "text": "required 要包括哪些指标?候选:gmv"},
|
|
{"op": "question", "text": " "},
|
|
{"op": "done", "explanation": "等你决定出具的是哪个出口"},
|
|
])
|
|
wf = await create(client, two_exits())
|
|
out = await assist(client, wf)
|
|
# 一句一条的文字,前面标上是哪个节点的事(句子里已经点了名的不重复标)
|
|
assert out["assist"] == {"ok": False, "summary": "等你决定出具的是哪个出口", "questions": [
|
|
"两个出口里,哪个是要出具的?「出具」还是「原始数」?", "「周报口径卡」:required 要包括哪些指标?候选:gmv"]}
|
|
assert out["rejected"] == [] and out["graph"] == two_exits()
|
|
|
|
|
|
async def test_deterministic_fixes_run_first_and_copilot_sees_what_is_left(client, monkeypatch):
|
|
graph = two_exits()
|
|
graph["nodes"].insert(2, node("ask", "agent", "查数员", tools=["db_query__shop"], approval="never",
|
|
prompt="用 db_query__shop 查"))
|
|
graph["edges"] += [{"source": "start", "target": "ask"}, {"source": "ask", "target": "card"}]
|
|
model = script(monkeypatch, done([{"op": "update_node", "id": "done", "config": {"contract": CONTRACT}}]))
|
|
wf = await create(client, graph)
|
|
out = await assist(client, wf, apply=["governed.agent_approval_never:ask"])
|
|
assert out["applied"] == ["governed.agent_approval_never:ask", "assist"] and out["ok"] is True
|
|
human = next(text for role, text in model.calls[0] if role == "human")
|
|
assert "的审批策略是「全部自动放行」" not in human and '"approval": "dangerous"' in human
|
|
|
|
|
|
async def test_nothing_left_means_no_model_call(client, monkeypatch):
|
|
model = script(monkeypatch, [])
|
|
graph = two_exits()
|
|
graph["nodes"][4]["data"]["config"]["contract"] = CONTRACT
|
|
wf = await create(client, graph)
|
|
out = await assist(client, wf)
|
|
assert out["assist"]["ok"] is True and model.calls == []
|
|
|
|
|
|
async def test_an_unconfigured_model_is_said_plainly(client, monkeypatch):
|
|
import app.api.copilot as copilot
|
|
from app.providers.factory import ProviderNotConfigured
|
|
|
|
async def _nothing(*_a, **_k):
|
|
raise ProviderNotConfigured("没有可用的 provider")
|
|
|
|
monkeypatch.setattr(copilot, "get_chat_model", _nothing)
|
|
wf = await create(client, two_exits())
|
|
out = await assist(client, wf)
|
|
assert out["assist"]["ok"] is False and "设置" in out["assist"]["summary"]
|
|
assert out["rejected"] == []
|
|
|
|
|
|
async def test_blocking_issues_only_add_the_gate_when_asked():
|
|
from app.api.copilot import _blocking_issues
|
|
|
|
graph = two_exits()
|
|
nodes = {n["id"]: n for n in graph["nodes"]}
|
|
assert _blocking_issues(nodes, graph["edges"]) == []
|
|
gated = _blocking_issues(nodes, graph["edges"], level="governed")
|
|
assert [i["code"] for i in gated] == ["governed.no_contract"]
|
|
assert _blocking_issues(nodes, graph["edges"], level="published") == []
|
|
|
|
|
|
def guarded() -> dict:
|
|
"""受管图里只剩一处 error:协作团队节点。团队后面还有一个「人工把关」节点。"""
|
|
nodes = [
|
|
node("start", "input", "周期"),
|
|
node("fetch", "tool", "取数", tool="db_query__shop", args={"sql": "SELECT SUM(amount) AS gmv FROM orders"}),
|
|
node("card", "metrics", "周报口径卡", caliber="周报口径", metrics=[
|
|
{"id": "gmv", "name": "销售额", "unit": "元", "expression": "cell(nodes.fetch, 0, 'gmv')"}]),
|
|
node("team", "supervisor", "复核团队", goal="复核", agents=[{"name": "checker", "tools": []}]),
|
|
node("gate", "human", "人工把关", prompt="确认数字"),
|
|
node("write", "report", "报告撰写", instructions="写周报"),
|
|
node("done", "output", "出具", fields=[{"name": "周报", "value": "{{ nodes.write.text }}"}], contract=CONTRACT),
|
|
]
|
|
edges = [{"id": f"e{i}", "source": a, "target": b} for i, (a, b) in enumerate(
|
|
[("start", "fetch"), ("fetch", "card"), ("card", "team"), ("team", "gate"), ("gate", "write"),
|
|
("write", "done")])]
|
|
return {"nodes": nodes, "edges": edges}
|
|
|
|
|
|
@pytest.mark.parametrize("ops, word", [
|
|
# 同一个 id 换了类型:团队换成模型调用,顺手把人工把关换成整形——等于删了重建
|
|
([{"op": "add_node", "node": {"id": "team", "type": "llm", "label": "复核团队", "config": {"prompt": "复核"}}},
|
|
{"op": "add_node", "node": {"id": "gate", "type": "transform", "label": "人工把关",
|
|
"config": {"mode": "expression", "expression": "vars"}}}], "人工把关"),
|
|
# 类型没变,也是整个覆盖掉旧节点(配置、位置全丢)
|
|
([{"op": "add_node", "node": {"id": "gate", "type": "human", "label": "人工把关", "config": {"prompt": "随便"}}},
|
|
{"op": "add_node", "node": {"id": "team", "type": "llm", "label": "复核团队", "config": {"prompt": "复核"}}}],
|
|
"覆盖"),
|
|
])
|
|
async def test_overwriting_an_existing_node_with_add_node_is_refused(client, monkeypatch, ops, word):
|
|
graph = guarded()
|
|
script(monkeypatch, done(ops))
|
|
wf = await create(client, graph)
|
|
before = await rows(wf)
|
|
out = await assist(client, wf)
|
|
assert out["assist"]["ok"] is False and "assist" not in out["applied"] and out["ok"] is False
|
|
[rejected] = [r for r in out["rejected"] if r["fix_id"] == "assist"]
|
|
assert "降低" in rejected["reason"] and word in rejected["reason"], rejected
|
|
assert out["graph"] == graph and out["changes"] == [] and out["ops"] == []
|
|
assert [(n["id"], n["type"]) for n in out["graph"]["nodes"]] == [(n["id"], n["type"]) for n in graph["nodes"]]
|
|
assert await rows(wf) == before
|
|
|
|
|
|
async def test_renaming_a_node_while_fixing_another_error_is_adopted(client, monkeypatch):
|
|
"""改了名的节点上没修好的 error 文案跟着变了,但还是同一处问题:不算冒出新问题。"""
|
|
graph = guarded()
|
|
graph["nodes"][6]["data"]["config"].pop("contract") # 两处 error:协作团队、没有带契约的出口
|
|
script(monkeypatch, done([
|
|
{"op": "update_node", "id": "team", "label": "复核团队(待拆成固定步骤)"},
|
|
{"op": "update_node", "id": "done", "config": {"contract": CONTRACT}},
|
|
]))
|
|
wf = await create(client, graph)
|
|
out = await assist(client, wf)
|
|
assert out["applied"] == ["assist"] and out["assist"]["ok"] is True, out["rejected"]
|
|
assert [(i["code"], i["node_id"]) for i in out["remaining"] if i["level"] == "error"] == [
|
|
("governed.supervisor", "team")]
|
|
assert "复核团队(待拆成固定步骤)" in out["remaining"][0]["message"] or any(
|
|
"复核团队(待拆成固定步骤)" in i["message"] for i in out["remaining"])
|
|
assert {(c["node_id"], c["field"]) for c in out["changes"]} == {("team", "label"), ("done", "contract")}
|