test_sop_v9.py 26.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
"""流程卡:条件组编译、每一步产出什么、循环等全部完成、取消与驳回分开、
失败可重试续跑、以发起人身份续跑、中断回收、发布规则(直接发布 / 四眼)、确认即发起。
(v12 起编辑器直接编辑图,定义都写成图。)"""
from __future__ import annotations

import datetime as dt
import sys
from pathlib import Path

import pytest
from fastapi import HTTPException

sys.path.insert(0, str(Path(__file__).parent))

from test_platform import as_user, build_basics, env, make_action, sop_spec  # noqa: E402,F401
from test_v8 import _auto_action  # noqa: E402

from app.core import identity  # noqa: E402


def patrol_graph(action: str = "mark_follow") -> dict:
    """查指标 → 循环(金额大的发动作,否则只通知)→ 结束。"""
    return {"start": "amt", "steps": [
        {"id": "amt", "type": "function", "title": "各网点成交金额", "function": "metric.query",
         "args": {"metric": "成交金额", "dimensions": ["网点"]},
         "filter": {"mode": "all", "items": [{"left": "$item.value", "op": "gt", "right": 0}]}, "next": "each"},
        {"id": "each", "type": "foreach", "title": "逐个网点处理", "items": "$amt", "limit": 10, "next": "fin",
         "body": {"start": "big", "steps": [
             {"id": "big", "type": "decision", "title": "金额大吗", "branches": [
                 {"label": "≥ 700", "cond": {"mode": "all", "items": [{"left": "$item.value", "op": "ge", "right": 700}]},
                  "next": "act"}], "default": "tell"},
             {"id": "act", "type": "action", "title": "标记跟进", "action": action, "object_key": "$item.网点",
              "params": {"reason": "成交 $item.value"}, "next": "row_end"},
             {"id": "tell", "type": "notify", "title": "知会", "role": "operator",
              "subject": "$item.网点名称 成交 $item.value", "body": "金额不大,知会一下", "next": "row_end"},
             {"id": "row_end", "type": "end", "title": "本条处理完"}]}},
        {"id": "fin", "type": "end", "title": "完成", "outcome": "巡检完成"}]}


def chain(*steps: dict) -> dict:
    """一串顺序执行的步骤:没写 next 的依次连到下一步,最后补一个结束。"""
    out = [dict(x) for x in steps]
    if out[-1].get("type") != "end":
        out.append({"id": "fin", "type": "end", "title": "完成", "outcome": "完成"})
    for i, st in enumerate(out[:-1]):
        if st.get("type") not in ("end", "decision") and not st.get("next"):
            st["next"] = out[i + 1]["id"]
    return {"steps": out}


def _publish(def_id: str) -> None:
    from app.sop import service
    assert service.publish(def_id)["published"]["version"] >= 1


# ---------------------------------------------------------------- 条件组 / 产出结构
def test_条件组编译成表达式(env):
    from app.kernel import rules
    from app.sop import cond
    c = cond.to_expr
    assert c({"mode": "all", "items": [{"left": "$gap.value", "op": "gt", "right": "0"}]}) == "(gap.value > 0)"
    assert c({"mode": "any", "items": [{"left": "$item.等级", "op": "eq", "right": "A"},
                                       {"left": "$item.缺口 数量", "op": "ge", "right": 5}]}) == \
        "(item.等级 == 'A') or (item['缺口 数量'] >= 5)"
    assert c({"mode": "all", "items": [{"left": "$a.code", "op": "eq", "right": "007"}]}) == "(a.code == '007')"   # 编号不当数字
    assert c({"mode": "all", "items": [{"left": "$a.x", "op": "eq", "right": "$b.y"}]}) == "(a.x == b.y)"
    assert c({"mode": "all", "items": [{"left": "$q.items[0].数量", "op": "gt", "right": 1}]}) == "(q.items[0].数量 > 1)"
    # 条件组可以嵌套:A 且(B 或 C)
    nested = {"mode": "all", "items": [{"left": "$a.lv", "op": "eq", "right": "A"},
                                       {"mode": "any", "items": [{"left": "$a.n", "op": "gt", "right": 5},
                                                                 {"left": "$a.vip", "op": "is_true"}]}]}
    assert rules.evaluate(c(nested), {"a": {"lv": "A", "n": 1, "vip": True}}) is True
    assert rules.evaluate(c(nested), {"a": {"lv": "A", "n": 1, "vip": False}}) is False
    assert rules.evaluate(c({"mode": "all", "items": [{"left": "$a.note", "op": "empty"}]}), {"a": {"note": ""}}) is True
    assert rules.evaluate(c({"mode": "all", "items": [{"left": "$a.lv", "op": "in", "right": "A, B"}]}), {"a": {"lv": "B"}})
    assert rules.evaluate(c({"mode": "all", "items": [{"left": "$a.rows", "op": "len_gt", "right": 1}]}), {"a": {"rows": [1, 2]}})
    assert c({"expr": "len(d.rows) > 3"}) == "len(d.rows) > 3" and c(None) == ""
    assert c({"mode": "all", "items": [{"left": "$a.x", "op": "gt", "right": ""}]}) == ""      # 没填值 = 没写


def test_每一步产出什么_带类型_供数据选择器用(env):
    from app.kernel import service as ksvc
    from app.sop import spec, types
    build_basics(env["ds_id"])
    g = spec.normalize({"params": [{"name": "store", "label": "网点", "type": "object", "object_type": "网点"}],
                        **patrol_graph()})
    g["steps"][1]["body"]["steps"].insert(0, {"id": "ask", "type": "human_task", "title": "确认", "role": "operator",
                                              "form": [{"label": "需要处理", "type": "boolean"}], "next": "big"})
    g = spec.normalize(g)
    with ksvc.draft_runtime():
        outs = {o["id"]: o for o in types.outputs(g)}
    assert [f["name"] for f in outs["param:store"]["schema"]["fields"]][:2] == ["key", "label"]
    items = next(f for f in outs["amt"]["schema"]["fields"] if f["name"] == "items")
    assert [f["name"] for f in items["items"]["fields"]] == ["网点", "网点名称", "value"]
    assert outs["each:item"]["var"] == "item" and outs["each:item"]["scope"] == "each"
    assert [f["name"] for f in outs["each:item"]["schema"]["fields"]] == ["网点", "网点名称", "value"]  # 当前这一条 = 上游每行
    assert outs["act"]["scope"] == "each"
    assert outs["ask"]["schema"]["fields"][0] == {"name": "f1", "label": "需要处理", "type": "boolean"}


def test_循环体里不能放子流程(env):
    from app.sop import service
    build_basics(env["ds_id"])
    d = service.create("嵌套", spec={"start": "a", "steps": [
        {"id": "a", "type": "foreach", "title": "外层", "items": "$x", "next": "z", "body": {"start": "b", "steps": [
            {"id": "b", "type": "subprocess", "title": "调别的", "sop": "x", "next": "e"},
            {"id": "e", "type": "end", "title": "完"}]}},
        {"id": "z", "type": "end", "title": "结束"}]})
    assert any("不能放「子流程」" in e for e in d["validation"]["errors"])


# ---------------------------------------------------------------- 执行
def test_取数步骤的筛选_只留下满足条件的行(env):
    from app.sop import engine, service
    build_basics(env["ds_id"])
    d = service.create("筛选", spec=chain(
        {"id": "amt", "type": "function", "title": "成交", "function": "metric.query",
         "args": {"metric": "成交金额", "dimensions": ["网点"]},
         "filter": {"mode": "all", "items": [{"left": "$item.value", "op": "ge", "right": 700}]}}))
    run = engine.start(d["id"], {}, mode="dry_run", wait=True)
    out = run["steps"][0]["output"]
    assert run["status"] == "done" and len(out["rows"]) == 2 and out["rows_before_filter"] == 3
    assert [r["value"] for r in out["items"]] == [r[-1] for r in out["rows"]]      # 多行结果同时给一份 items(一行一个字典)


def test_逐条处理_每条各走循环体_全部办完才往下(env):
    from app.capability import actions
    from app.governance import notify
    from app.sop import engine, service
    b = build_basics(env["ds_id"])
    make_action(b["ot"]["id"])
    d = service.create("巡检", spec=patrol_graph())
    assert service.get(d["id"])["validation"]["errors"] == []
    dry = engine.start(d["id"], {}, mode="dry_run", wait=True)
    assert dry["status"] == "done" and actions.list_runs() == []            # 试运行:动作只预览,全部当场走完
    _publish(d["id"])
    tok = as_user("operator")
    live = engine.start(d["id"], {}, wait=True)
    identity.reset(tok)
    # 三个网点:900、700 走动作(等审批),500 只通知(当场完成)
    assert live["status"] == "waiting"
    each = next(s for s in live["steps"] if s["step_id"] == "each")
    assert (each["output"]["total"], each["output"]["ok"], each["output"]["pending"]) == (3, 1, 2)
    assert any("成交 500" in n["title"] for n in notify.list_for(identity.Actor(id="operator", roles=["operator"])))
    pend = actions.list_runs(status="pending_approval")
    assert len(pend) == 2 and all(r["initiator_id"] == "operator" for r in pend)
    tok = as_user("approver")
    actions.decide(pend[0]["id"], True, "同意")
    identity.reset(tok)
    assert engine.get_run(live["id"])["status"] == "waiting"                # 还有一条没批
    tok = as_user("approver")
    actions.decide(pend[1]["id"], True, "同意")
    identity.reset(tok)
    done = engine.get_run(live["id"], rows=True)
    each = next(s for s in done["steps"] if s["step_id"] == "each")
    assert done["status"] == "done" and done["outcome"] == "巡检完成"
    assert (each["output"]["ok"], each["output"]["pending"]) == (3, 0) and len(each["rows"]) == 3
    assert [s["step_id"] for s in each["rows"][0]["steps"]][0] == "big"       # 行运行里能看到循环体的每一步


def test_续跑用发起人的身份_不是审批人的(env):
    from app.capability import actions, tasks
    from app.sop import engine, service
    b = build_basics(env["ds_id"])
    make_action(b["ot"]["id"])
    d = service.create("整改", spec=sop_spec(b["ot"]["id"]))
    _publish(d["id"])
    tok = as_user("operator")
    run = engine.start(d["id"], {"store": "1"}, wait=True)
    identity.reset(tok)
    task = next(t for t in tasks.list_tasks(scope="all") if t["source_type"] == "sop")
    tok = as_user("builder")                          # 换一个人来完成任务
    tasks.complete(task["id"], {"plan": "培训"})
    identity.reset(tok)
    st = next(s for s in engine.get_run(run["id"])["steps"] if s["step_id"] == "act")
    assert actions.get(st["action_run_id"])["initiator_id"] == "operator"     # 后续动作的发起人仍是流程发起人


def test_撤回动作不走驳回分支_流程停下(env):
    from app.capability import actions, tasks
    from app.sop import engine, service
    b = build_basics(env["ds_id"])
    make_action(b["ot"]["id"])
    d = service.create("整改", spec=sop_spec(b["ot"]["id"]))             # act 驳回后走「无需处理」
    _publish(d["id"])
    run = engine.start(d["id"], {"store": "1"}, wait=True)
    tasks.complete(next(t for t in tasks.list_tasks(scope="all") if t["source_type"] == "sop")["id"], {"plan": "x"})
    st = next(s for s in engine.get_run(run["id"])["steps"] if s["step_id"] == "act")
    actions.cancel(st["action_run_id"], "提错了")
    got = engine.get_run(run["id"])
    assert got["status"] == "cancelled" and got["outcome"] != "正常"            # 以前会被当成驳回,走到「无需处理」
    assert [s["step_id"] for s in got["steps"]][-1] == "act"


def test_取消运行_连同行运行和待办一起收尾_只收一次(env):
    from app.capability import actions
    from app.governance import audit
    from app.sop import engine, service
    b = build_basics(env["ds_id"])
    make_action(b["ot"]["id"])
    d = service.create("巡检", spec=patrol_graph())
    _publish(d["id"])
    live = engine.start(d["id"], {}, wait=True)
    assert live["status"] == "waiting"
    out = engine.cancel(live["id"], "不巡了")
    assert out["status"] == "cancelled" and out["error"] == "不巡了"
    rows = next(s for s in engine.get_run(live["id"], rows=True)["steps"] if s["step_id"] == "each")["rows"]
    assert {r["status"] for r in rows} == {"done", "cancelled"}
    assert all(r["status"] == "cancelled" for r in actions.list_runs())
    assert len([x for x in audit.query(event="sop.run_cancelled")["items"]]) == 1     # 行运行不单独记
    with pytest.raises(HTTPException):
        engine.cancel(live["id"])


def test_动作执行失败_流程停在这一步_重试成功后接着走(env, monkeypatch):
    from app.capability import actions, registry
    from app.sop import engine, service
    b = build_basics(env["ds_id"])
    _auto_action(b["ot"]["id"])
    d = service.create("派人", spec=chain(
        {"id": "act", "type": "action", "title": "派人复核", "action": "dispatch_check", "object_key": "1",
         "params": {"reason": "看看"}},
        {"id": "fin", "type": "end", "title": "完成", "outcome": "已派"}))
    _publish(d["id"])
    tool = registry.TOOLS["task.create"]
    real, calls = tool.run, {"n": 0}

    def flaky(args, ctx):
        calls["n"] += 1
        if calls["n"] == 1:
            raise RuntimeError("外部系统超时")
        return real(args, ctx)
    monkeypatch.setattr(tool, "run", flaky)
    run = engine.start(d["id"], {}, wait=True)
    st = run["steps"][0]
    assert run["status"] == "waiting" and st["status"] == "waiting_approval" and "执行失败" in st["note"]
    engine.annotate_waiting(run, identity.current())
    assert run["steps"][0]["action"]["can_retry"] is True
    actions.retry(st["action_run_id"])
    assert engine.get_run(run["id"])["status"] == "done"


def test_试运行的人工任务按字段类型给模拟答案(env):
    from app.sop import engine, service
    build_basics(env["ds_id"])
    d = service.create("确认", spec={"start": "ask", "steps": [
        {"id": "ask", "type": "human_task", "title": "要处理吗", "role": "operator", "next": "gate",
         "form": [{"label": "需要处理", "type": "boolean"}, {"label": "等级", "type": "choice", "options": ["高", "低"]}]},
        {"id": "gate", "type": "decision", "title": "按答案分", "branches": [
            {"label": "要", "cond": {"mode": "all", "items": [{"left": "$ask.f1", "op": "eq", "right": True}]},
             "next": "yes"}], "default": "no"},
        {"id": "yes", "type": "end", "title": "处理", "outcome": "要处理"},
        {"id": "no", "type": "end", "title": "不处理", "outcome": "不处理"}]})
    run = engine.start(d["id"], {}, mode="dry_run", wait=True)
    assert run["outcome"] == "要处理" and run["vars"]["ask"] == {"f1": True, "f2": "高"}     # 以前一律填文字,必走「否则」
    run = engine.start(d["id"], {"__mock__": {"ask": {"f1": False}}}, mode="dry_run", wait=True)
    assert run["outcome"] == "不处理"


def test_服务重启时回收中断的运行_在等人的不动(env):
    from app.core.dbx import session
    from app.sop import engine, service
    from app.sop.models import SopRun, SopStepRun
    b = build_basics(env["ds_id"])
    make_action(b["ot"]["id"])
    d = service.create("整改", spec=sop_spec(b["ot"]["id"]))
    _publish(d["id"])
    waiting = engine.start(d["id"], {"store": "1"}, wait=True)
    stuck = engine.start(d["id"], {"store": "2"}, wait=True)
    old = dt.datetime.now() - dt.timedelta(hours=2)
    with session() as s:
        for rid in (waiting["id"], stuck["id"]):
            r = s.get(SopRun, rid)
            r.created_at = old
            for st in s.query(SopStepRun).filter(SopStepRun.run_id == rid).all():
                st.started_at = old
        s.get(SopRun, stuck["id"]).status = "running"          # 模拟:进程在推进到一半时没了
        s.commit()
    assert engine.recover_stuck() == 1
    assert engine.get_run(stuck["id"])["status"] == "failed" and "服务中断" in engine.get_run(stuck["id"])["error"]
    assert engine.get_run(waiting["id"])["status"] == "waiting"


def test_AI分析步骤可以直接写要求_通知步骤只在正式运行时真的发(env, monkeypatch):
    from app.capability import skills
    from app.governance import notify
    from app.sop import engine, service
    build_basics(env["ds_id"])
    monkeypatch.setattr(skills.llm, "chat_json", lambda m, **kw: {"conclusion": "网点 1 最高", "points": ["集中在一家"]})
    d = service.create("分析", spec=chain(
        {"id": "amt", "type": "function", "title": "成交", "function": "metric.query",
         "args": {"metric": "成交金额", "dimensions": ["网点"]}},
        {"id": "ai", "type": "skill", "title": "看看分布", "instruction": "哪家最高?", "inputs": {"数据": "$amt"}},
        {"id": "tell", "type": "notify", "title": "知会", "assignee": "admin", "subject": "结论:$ai.conclusion"}))
    before = len(notify.list_for(identity.current()))
    dry = engine.start(d["id"], {}, mode="dry_run", wait=True)
    assert dry["status"] == "done" and dry["vars"]["ai"]["conclusion"] == "网点 1 最高"
    assert dry["vars"]["ai"]["ai_judged"] is True                              # AI 的结论一律标上「由 AI 判断」
    assert len(notify.list_for(identity.current())) == before                 # 试运行不真的发
    _publish(d["id"])
    engine.start(d["id"], {}, wait=True)
    assert any(n["title"] == "结论:网点 1 最高" for n in notify.list_for(identity.current()))


# ---------------------------------------------------------------- 编辑与发布
def test_保存有并发保护_编辑不写审计(env):
    from app.governance import audit
    from app.sop import service
    build_basics(env["ds_id"])
    d = service.create("巡检", spec=patrol_graph())
    t2 = {**d["spec"], "priority": "P0"}
    ok = service.update(d["id"], spec=t2, etag=d["draft_hash"])
    assert ok["spec"]["priority"] == "P0" and ok["draft_hash"] != d["draft_hash"]
    with pytest.raises(HTTPException) as e:
        service.update(d["id"], spec=patrol_graph(), etag=d["draft_hash"])          # 拿着旧版本再存
    assert e.value.status_code == 409
    assert audit.query(event="sop.edit")["items"] == []


def test_发布规则_管理员和负责角色直接发_其他人提交审核且不能自己批(env):
    from app.governance import review, roles, users
    from app.sop import service
    build_basics(env["ds_id"])
    d = service.create("巡检", spec=chain({"id": "amt", "type": "function", "title": "成交", "function": "metric.query", "args": {"metric": "成交金额"}}))
    assert any("还没有试运行" in w for w in d["validation"]["warnings"])            # 没试运行只是提醒
    tok = as_user("builder")
    try:
        out = service.publish(d["id"], "首版")
        assert out["published"] is None and out["review"]["status"] == "pending"   # 不是负责角色 → 进审核
        with pytest.raises(HTTPException) as e:
            review.decide(out["review"]["id"], True, "我自己批")
        assert e.value.status_code == 403                                           # 四眼:不能批自己提交的
    finally:
        identity.reset(tok)
    review.decide(out["review"]["id"], True, "同意")                                # 管理员批
    assert service.get(d["id"])["current_version"] == 1
    # 负责角色的实施人员:直接发布
    roles.upsert("流程负责人")
    users.upsert_user("builder", name="实施", roles=["builder"], biz_roles=["流程负责人"])
    users.invalidate()
    service.update(d["id"], owner_role="流程负责人", spec=chain(
        {"id": "amt", "type": "function", "title": "成交", "function": "metric.query",
         "args": {"metric": "成交金额", "dimensions": ["网点"]}}))
    tok = as_user("builder")
    try:
        assert service.publish(d["id"])["published"]["version"] == 2
    finally:
        identity.reset(tok)
    assert [c["change"] for c in service.version_changes(service.get(d["id"]))] == []


def test_归档的不能发布_引用草稿元素的不能发布_挂着监控的不能归档(env):
    from app.kernel import service as ksvc
    from app.sop import service
    from app.watch import service as watch
    build_basics(env["ds_id"])
    ksvc.create_concept("function", "草稿指标", spec={"category": "aggregate"})
    d = service.create("用了草稿", spec=chain({"id": "m", "type": "function", "title": "取", "function": "metric.query",
                                              "args": {"metric": "草稿指标"}}))
    with pytest.raises(HTTPException) as e:
        service.publish(d["id"])
    assert e.value.status_code == 412
    ok = service.create("巡检", spec=chain({"id": "amt", "type": "function", "title": "成交", "function": "metric.query", "args": {"metric": "成交金额"}}))
    _publish(ok["id"])
    watch.create({"title": "每天巡检", "schedule": {"kind": "daily", "at": "08:00"},
                  "source": {"kind": "sop", "sop": ok["id"]}, "condition": "",
                  "strategies": [{"kind": "run_sop", "sop": ok["id"]}]})
    with pytest.raises(HTTPException) as e:
        service.archive(ok["id"])
    assert e.value.status_code == 409 and "每天巡检" in e.value.detail
    service.archive(d["id"])
    with pytest.raises(HTTPException) as e:
        service.publish(d["id"])
    assert e.value.status_code == 409


def test_子流程绕一圈调回自己_校验拦下(env):
    from app.sop import service
    build_basics(env["ds_id"])
    a = service.create("甲", spec=chain({"id": "m", "type": "function", "title": "取", "function": "metric.query",
                                        "args": {"metric": "成交金额"}}))
    b = service.create("乙", spec=chain({"id": "s", "type": "subprocess", "title": "调甲", "sop": a["id"]}))
    got = service.update(a["id"], spec=chain({"id": "s", "type": "subprocess", "title": "调乙", "sop": b["id"]}))
    assert any("绕回" in x for x in got["validation"]["errors"])


# ---------------------------------------------------------------- 发起
def test_提问里确认即发起_不再有发起流程的审批单(env):
    from fastapi.testclient import TestClient
    from app.agents import action as agent_action
    from app.capability import actions
    from app.governance import audit
    from app.main import app
    from app.sop import service
    b = build_basics(env["ds_id"])
    make_action(b["ot"]["id"])
    d = service.create("低成交整改", spec=sop_spec(b["ot"]["id"]))
    _publish(d["id"])
    card = agent_action.prepare_sop_cards([{"sop": "低成交整改", "params": {"store": "1", "瞎编的": 1}}], {})[0]
    assert card["sop_id"] == d["id"] and card["params"] == {"store": "1"} and "error" not in card
    assert [s["title"] for s in card["steps"]][0] == "取成交金额"
    assert agent_action.prepare_sop_cards([{"sop": "低成交整改"}], {})[0]["missing"] == ["网点"]
    assert actions.list_runs() == []                                           # 建议阶段不产生任何审批单
    c = TestClient(app)
    r = c.post(f"/api/sop/defs/{d['id']}/run", json={"params": card["params"], "source": "ask"},
               headers={"X-User-Id": "operator"})
    assert r.status_code == 200 and r.json()["started_by"] == "operator" and r.json()["trigger"] == "ask"
    assert any("AI 建议" in x["summary"] and "确认" in x["summary"] for x in audit.query(event="sop.run_start")["items"])
    with pytest.raises(HTTPException):
        actions.prepare(f"sop:{d['id']}", {})                                   # 「发起流程」不再是一个动作


def test_外部Agent只能请人确认发起(env):
    from app.capability import actions, mcp
    from app.governance import notify
    from app.sop import engine, service
    b = build_basics(env["ds_id"])
    make_action(b["ot"]["id"])
    d = service.create("低成交整改", spec=sop_spec(b["ot"]["id"]))
    _publish(d["id"])
    tool, args = mcp.resolve("execute_runcard", {"runcard": "低成交整改", "mode": "confirm",
                                                 "params": {"store": "1"}, "reason": "网点 1 偏低"})
    out = tool.run(args, None)
    assert out["status"] == "pending_confirm" and f"start={d['id']}" in out["confirm_link"]
    assert engine.list_runs(def_id=d["id"], mode="live") == [] and actions.list_runs() == []
    assert any("请确认" in n["title"] for n in notify.list_for(identity.current()))


def test_运行详情告诉当前这个人能不能直接办(env):
    from fastapi.testclient import TestClient
    from app.main import app
    from app.sop import engine, service
    b = build_basics(env["ds_id"])
    make_action(b["ot"]["id"])
    d = service.create("低成交整改", spec=sop_spec(b["ot"]["id"]))
    _publish(d["id"])
    run = engine.start(d["id"], {"store": "1"}, wait=True)
    c = TestClient(app)
    as_op = c.get(f"/api/sop/runs/{run['id']}", headers={"X-User-Id": "operator"}).json()
    fix = next(s for s in as_op["steps"] if s["step_id"] == "fix")
    assert fix["task"]["can_handle"] is True and as_op["spec"]["steps"][0]["function"] == "metric.query"
    as_viewer = c.get(f"/api/sop/runs/{run['id']}", headers={"X-User-Id": "viewer"}).json()
    assert next(s for s in as_viewer["steps"] if s["step_id"] == "fix")["task"]["can_handle"] is False


def test_同一秒发起的两张单_单号不重复_预览的单号提交后不变(env):
    from app.capability import actions
    b = build_basics(env["ds_id"])
    _auto_action(b["ot"]["id"], mode="manual")
    ids = {actions.new_now_id() for _ in range(50)}
    assert len(ids) == 50
    pre = actions.prepare("dispatch_check", {"reason": "看看"}, "1")
    run = actions.propose("dispatch_check", {"reason": "看看"}, object_key="1", now_id=pre["now_id"])
    assert run["preview"]["now_id"] == pre["now_id"]
    assert actions.prepare("dispatch_check", {"reason": "看看"}, "1", now_id="乱写的")["now_id"] != "乱写的"


def test_流程提的审批单_只有发起人和管理员能撤回_别人取消运行时由系统收尾(env):
    from app.capability import actions, tasks
    from app.sop import engine, service
    b = build_basics(env["ds_id"])
    make_action(b["ot"]["id"])
    d = service.create("整改", spec=sop_spec(b["ot"]["id"]))
    _publish(d["id"])
    tok = as_user("operator")
    run = engine.start(d["id"], {"store": "1"}, wait=True)
    tasks.complete(next(t for t in tasks.list_tasks(scope="all") if t["source_type"] == "sop")["id"], {"plan": "x"})
    identity.reset(tok)
    rid = next(s for s in engine.get_run(run["id"])["steps"] if s["step_id"] == "act")["action_run_id"]
    tok = as_user("builder")                          # 不相干的人:看得到但撤不了
    try:
        assert next(r for r in actions.list_runs() if r["id"] == rid)["can_cancel"] is False
        with pytest.raises(HTTPException) as e:
            actions.cancel(rid, "手滑")
        assert e.value.status_code == 403
    finally:
        identity.reset(tok)
    tok = as_user("operator")
    try:
        assert next(r for r in actions.list_runs() if r["id"] == rid)["can_cancel"] is True
    finally:
        identity.reset(tok)
    assert engine.cancel(run["id"], "不做了")["status"] == "cancelled"     # 管理员取消运行,审批单跟着撤掉
    assert actions.get(rid)["status"] == "cancelled"