mirror of
https://github.com/ThearchyHelios/AgentLab.git
synced 2026-11-15 19:51:59 +00:00
d071bf119f
一、表结构、实体与引文
- 数据源工具查库时顺带存一份表结构快照(schema_snapshot),和查询快照一起进台账、进封存;
台账里的查询记下 SQL 用到的表
- 报告里的表名、字段名可以点:反引号里的名字一律核对,正文里的裸名字只在明显是标识符时才自动链接,
常见英文单词不链接;点开看到它出现在哪次查询、类型、所属的表,快照被截断时写明
- 找不到的名字标成可疑实体:在快照、SQL、结果列里都没有的记「可能是编造的名字」并给出最接近的 3 个;
快照被截断、核对不了的记「核对不了」,不冤枉成编造
- 检索引文 [[q:K1|原文]]:原文在检索快照的命中片段里逐字出现(空白归一化后)才算有出处,点开高亮原文位置
- 自动链接的名字不算句子的引用,只有写作者写的引用才算
二、结论句与出具
- 报告节点新增 claims:off(默认,保持原样)或 require_citation(没有引用的结论句计入缺口)
- 受管级别的正式运行里,可疑实体和没有引用的结论句按「有缺口」降档,不拦截;探索运行和已发布级别只标注
- 契约的 claims 和报告节点的设置取更严的那个;受管正式运行里写 ignore 也按降档处理,并给出警告
- 出具横幅除了数字,也写出可疑实体和没有引用的结论句
三、受管门禁 G1–G5(只看图和配置)
- G1 带契约的出口,成果字段的文字只能来自报告撰写节点
- G2 模型写的文字不绕过报告撰写节点直接流进出口
- G3 报告撰写节点写明 numbers: strict、on_violation: fail、claims: require_citation
- G4 口径卡的输入不来自计算角色的沙箱代码
- G5 给口径卡供数的 agent 配 output_schema 并开 cite_fields
- 受管级别是错误、挡住发布;已发布级别只给警告;已经发布的版本照常运行,下次发布时按新规则检查
- 每条规则都接进发布前自动修复(一键修复 / 给选项 / 交给 Copilot);禁止的改动补上关 cite_fields、
删 output_schema、放宽契约 claims;Copilot 兜底不许自己把代码节点标成 source、不许放宽报告节点
- 发布弹窗里选「交给 Copilot」时明确写「正在交给 Copilot」
四、旧运行与审计
- 没有契约的旧答案:数字和已封存的查询单元格、口径卡值按数值比对,每个数最多 3 个候选,
默认折叠,写明「猜测的来源,不能当证据」
- 有契约的旧运行:候选只从已封存的口径卡里找,人为插进工件表的行不当证据
- 证据审计:GET /api/runs/{id}/evidence/audit 按「无证据 / 可疑实体 / 有出处 / 旧运行猜测」分组,
可导出 JSON 和 CSV(带封存状态);记录页和画布上的报告节点显示「有出处 N · 无证据 M」
五、SQL 守卫修正(安全)
- 去注释改成单遍扫描,认得字符串和各方言的引号(单引号转义、MySQL 反斜杠与 #、PostgreSQL 的 $$ 与嵌套注释、
Oracle 的 q'[…]'、SQLite 的方括号);以前字符串里的 -- 会被当成注释,SELECT '--'; DROP … 这类写法能骗过多语句拦截
- 看不到服务器设置时每种读法都扫一遍,读法之间切分不一致就拒绝,任何一种读法是写操作就按写操作处理
- 执行查询和工具危险判定都按数据源的方言检查
六、其他
- 修掉检查脚本里画布检查的一处竞态,并行估时按实测更新
160 lines
7.3 KiB
Python
160 lines
7.3 KiB
Python
"""发布级别记在版本上(WorkflowVersion.level)。
|
||
|
||
以前「这次正式运行按不按受管出具」看的是工作流当前的 status。可 status 说的是当前画布:
|
||
受管版本发布之后在画布上改一笔,status 就退回 draft,再从那个受管版本发起的正式运行
|
||
就被当成已发布级别出具(单元格不必在契约里声明 cells 就放行)。级别要跟着版本走:
|
||
发布时记在那一版上,正式运行看它钉的版本;没有记过级别的老版本照旧看 status。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import asyncio
|
||
|
||
import pytest
|
||
from httpx import ASGITransport, AsyncClient
|
||
from langchain_core.messages import AIMessage
|
||
from sqlalchemy import create_engine, select, text
|
||
|
||
from app.db.base import SessionLocal
|
||
from app.db.models import Run, RunEvent, Workflow, WorkflowVersion
|
||
from app.engine.runner import run_manager
|
||
from app.main import app
|
||
|
||
|
||
@pytest.fixture(autouse=True)
|
||
async def engine_up():
|
||
await run_manager.setup()
|
||
yield
|
||
await run_manager.shutdown()
|
||
|
||
|
||
@pytest.fixture
|
||
async def client():
|
||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c:
|
||
yield c
|
||
|
||
|
||
@pytest.fixture(autouse=True)
|
||
def writer(monkeypatch):
|
||
from app.providers import mock_model
|
||
|
||
monkeypatch.setattr(mock_model.MockChatModel, "_decide",
|
||
lambda model, messages: AIMessage(content="本周销售额 [[m:gmv]]。"))
|
||
|
||
|
||
def node(nid, ntype, **config):
|
||
return {"id": nid, "type": ntype, "position": {"x": 0, "y": 0}, "data": {"label": nid, "config": config}}
|
||
|
||
|
||
def weekly() -> dict:
|
||
nodes = [
|
||
node("start", "input"),
|
||
node("fetch", "transform", mode="expression", expression="{'gmv': 300.5}", assign_to="kpi"),
|
||
node("card", "metrics", caliber="周报口径", metrics=[
|
||
{"id": "gmv", "name": "销售额", "unit": "元", "expression": "vars.kpi.gmv"}]),
|
||
node("write", "report", instructions="写周报",
|
||
numbers="strict", on_violation="fail", claims="require_citation"),
|
||
node("out", "output", fields=[{"name": "周报", "value": "{{ nodes.write.text }}"}],
|
||
contract={"report_from": "write", "metrics_from": ["card"], "required": ["gmv"], "strict": True}),
|
||
]
|
||
return {"nodes": nodes, "edges": [{"source": a["id"], "target": b["id"]} for a, b in zip(nodes, nodes[1:])]}
|
||
|
||
|
||
async def version_row(wf: str, version: int) -> WorkflowVersion:
|
||
async with SessionLocal() as session:
|
||
return (await session.execute(select(WorkflowVersion).where(
|
||
WorkflowVersion.workflow_id == wf, WorkflowVersion.version == version))).scalar_one()
|
||
|
||
|
||
async def notes(run_id: str) -> list[dict]:
|
||
async with SessionLocal() as session:
|
||
rows = (await session.execute(select(RunEvent).where(
|
||
RunEvent.run_id == run_id, RunEvent.type == "log").order_by(RunEvent.seq))).scalars()
|
||
return [e.data for e in rows if e.data.get("code") == "run_governance"]
|
||
|
||
|
||
async def settle(run_id: str) -> Run:
|
||
for _ in range(400):
|
||
await asyncio.sleep(0.05)
|
||
async with SessionLocal() as session:
|
||
row = await session.get(Run, run_id)
|
||
if row.status in ("succeeded", "failed") and row.manifest_seq is not None:
|
||
return row
|
||
raise AssertionError(f"run {run_id} 没跑完:{row.status}")
|
||
|
||
|
||
@pytest.mark.parametrize("level", ["published", "governed"])
|
||
async def test_publishing_records_the_level_on_the_version(client, level):
|
||
wf = (await client.post("/api/workflows", json={"name": f"周报-{level}", "graph": weekly()})).json()["id"]
|
||
body = (await client.post(f"/api/workflows/{wf}/publish", json={"level": level})).json()
|
||
assert body["ok"] is True, body["issues"]
|
||
assert (await version_row(wf, 1)).level == level
|
||
versions = (await client.get(f"/api/workflows/{wf}/versions")).json()
|
||
assert versions[0]["level"] == level
|
||
detail = (await client.get(f"/api/workflows/{wf}/versions/1")).json()
|
||
assert detail["level"] == level and detail["published"] is True
|
||
|
||
|
||
async def test_a_blocked_publish_records_nothing(client):
|
||
graph = weekly()
|
||
graph["nodes"][-1]["data"]["config"]["contract"].pop("required")
|
||
wf = (await client.post("/api/workflows", json={"name": "周报-被拦", "graph": graph})).json()["id"]
|
||
assert (await client.post(f"/api/workflows/{wf}/publish", json={"level": "governed"})).json()["ok"] is False
|
||
assert (await version_row(wf, 1)).level is None
|
||
|
||
|
||
async def test_republishing_the_same_version_updates_its_level(client):
|
||
wf = (await client.post("/api/workflows", json={"name": "周报-升档", "graph": weekly()})).json()["id"]
|
||
await client.post(f"/api/workflows/{wf}/publish", json={"level": "published"})
|
||
await client.post(f"/api/workflows/{wf}/publish", json={"level": "governed"})
|
||
assert (await version_row(wf, 1)).level == "governed"
|
||
|
||
|
||
@pytest.mark.parametrize("level, governed", [("governed", True), ("published", False)])
|
||
async def test_editing_the_canvas_after_publishing_does_not_change_how_the_version_issues(client, level, governed):
|
||
from app.engine.governance import governed_formal
|
||
|
||
wf = (await client.post("/api/workflows", json={"name": f"周报-改画布-{level}", "graph": weekly()})).json()["id"]
|
||
assert (await client.post(f"/api/workflows/{wf}/publish", json={"level": level})).json()["ok"] is True
|
||
edited = weekly()
|
||
edited["nodes"][3]["data"]["label"] = "改过的报告"
|
||
after = (await client.patch(f"/api/workflows/{wf}", json={"graph": edited})).json()
|
||
assert after["status"] == "draft" and after["published_version"] == 1
|
||
r = await client.post("/api/runs", json={"workflow_id": wf, "run_class": "formal"})
|
||
assert r.status_code == 201, r.text
|
||
run_id = r.json()["id"]
|
||
row = await settle(run_id)
|
||
[note] = await notes(run_id)
|
||
assert note["governed"] is governed and "v1" in note["message"], note
|
||
assert await governed_formal(run_id) is governed
|
||
assert row.status == "succeeded", row.error
|
||
|
||
|
||
async def test_a_version_published_before_the_column_existed_follows_the_status(client):
|
||
"""老版本没有记级别:照旧看工作流现在的 status(test_contract_cells 那套旧规则)。"""
|
||
async with SessionLocal() as session:
|
||
w = Workflow(name="周报-老版本", graph=weekly(), status="governed", published_version=1)
|
||
session.add(w)
|
||
await session.flush()
|
||
session.add(WorkflowVersion(workflow_id=w.id, version=1, graph=weekly()))
|
||
await session.commit()
|
||
wf = w.id
|
||
r = await client.post("/api/runs", json={"workflow_id": wf, "run_class": "formal"})
|
||
run_id = r.json()["id"]
|
||
await settle(run_id)
|
||
[note] = await notes(run_id)
|
||
assert note["governed"] is True
|
||
|
||
|
||
def test_the_column_is_added_to_old_databases():
|
||
from app.db.base import _migrate
|
||
|
||
engine = create_engine("sqlite://")
|
||
with engine.begin() as conn:
|
||
conn.execute(text("CREATE TABLE workflow_versions (id VARCHAR(32) PRIMARY KEY, workflow_id VARCHAR(32), "
|
||
"version INTEGER, graph JSON, note TEXT, graph_hash VARCHAR(64))"))
|
||
conn.execute(text("INSERT INTO workflow_versions (id, workflow_id, version) VALUES ('a', 'w', 1)"))
|
||
_migrate(conn)
|
||
cols = {row[1] for row in conn.execute(text("PRAGMA table_info(workflow_versions)"))}
|
||
assert "level" in cols
|
||
assert conn.execute(text("SELECT level FROM workflow_versions")).scalar() is None
|