engine.py 77.5 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 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607
"""SOP 执行引擎:状态机。

三种模式跑同一份定义:
- live:正式运行。函数/AI 分析自动跑;人工任务派出去等人完成;动作按它自己的审批策略走,等有了结果再往下。
- dry_run:试运行。动作只做预览(视为批准)、人工任务按字段类型填模拟值自动完成;
  函数和 AI 分析真实执行(都是只读的)。
- ai_readonly:给问答当「剧本」。只跑函数/AI 分析/判断,遇到人工任务或动作就停下,
  把它们作为「建议的下一步」返回,由用户决定要不要发起。

推进在后台线程里做(函数/AI 分析可能要调大模型),每个运行一把锁,防止任务完成与审批回调并发推进。
状态转换一律在数据库里做「比较并交换」(UPDATE … WHERE status IN …):回调可能来自别的线程甚至别的进程,
谁先把状态换掉谁负责往下走,另一个发现换不动就什么都不做。

循环:每一行起一个「行运行」(kind=row)跑循环体,全部行都到终态后父流程才继续。

出错处理:每一步可配 error = {retry, mode: stop|default|branch, default, next, timeout}。
步骤失败时先按 retry 重试;还不行就按 mode:停止整个流程 / 把 default 当作这一步的结果继续 / 走 next(失败分支)。
"""
from __future__ import annotations

import contextvars
import datetime as dt
import logging
import threading
import time
from concurrent.futures import ThreadPoolExecutor
from typing import Any

from fastapi import HTTPException
from sqlalchemy import func, select, update

from ..capability import actions, registry, skills, tasks
from ..core import identity
from ..core.dbx import iso, jdump, jload, new_id, now, session
from ..governance import audit, notify
from ..kernel import objects, rules
from ..kernel import service as ksvc
from . import service
from .models import SopRun, SopStepRun

log = logging.getLogger(__name__)

_pool = ThreadPoolExecutor(max_workers=4, thread_name_prefix="sop")
_locks: dict[str, threading.Lock] = {}
_locks_guard = threading.Lock()
MAX_STEPS = 200          # 防御:一次推进最多走这么多步
ACTIVE = ("running", "waiting", "cancelling")
TERMINAL = ("done", "failed", "cancelled", "rejected", "paused")
_STATUS_LABEL = {"done": "完成", "failed": "失败", "cancelled": "取消", "rejected": "被驳回"}


def _lock(run_id: str) -> threading.Lock:
    with _locks_guard:
        return _locks.setdefault(run_id, threading.Lock())


# ---------------- 序列化 ----------------
def _run_dict(r: SopRun, steps: list[dict] | None = None) -> dict:
    return {"id": r.id, "def_id": r.def_id, "version": r.version, "title": r.title,
            "mode": r.mode, "params": jload(r.params_json, {}), "vars": jload(r.vars_json, {}),
            "status": r.status, "current_step": r.current_step, "trigger": r.trigger,
            "outcome": r.outcome, "error": r.error, "started_by": r.started_by,
            "parent_step_run": r.parent_step_run, "kind": r.kind or "main",
            "row_index": r.row_index or 0, "parent_run_id": r.parent_run_id or "",
            "workspace": r.workspace, "event_id": r.event_id or "",
            "subject": {"type_id": r.subject_type, "key": r.subject_key, "label": r.subject_label}
            if r.subject_type else None,
            "created_at": iso(r.created_at), "finished_at": iso(r.finished_at),
            "steps": steps if steps is not None else None}


def _step_dict(s: SopStepRun) -> dict:
    return {"id": s.id, "seq": s.seq, "step_id": s.step_id, "step_type": s.step_type,
            "title": s.title, "status": s.status, "inputs": jload(s.inputs_json, {}),
            "output": jload(s.output_json, None), "note": s.note, "error": s.error,
            "task_id": s.task_id, "action_run_id": s.action_run_id,
            "child_run_id": s.child_run_id, "started_at": iso(s.started_at),
            "finished_at": iso(s.finished_at)}


def get_run(run_id: str, rows: bool = False) -> dict:
    """rows=True 时带上逐条处理各行的运行(含各自的步骤),运行详情页按行展开用。"""
    with session() as s:
        r = s.get(SopRun, run_id)
        if r is None:
            raise HTTPException(404, "运行记录不存在")
        steps = [_step_dict(x) for x in s.scalars(select(SopStepRun).where(
            SopStepRun.run_id == run_id).order_by(SopStepRun.seq)).all()]
        out = _run_dict(r, steps)
        out["spec"] = jload(r.spec_json, {})
        out["params_view"] = _params_view(out["spec"], out["params"], out["vars"])
        out["started_by_name"] = _user_names().get(r.started_by, r.started_by)
        child_ids = [c.id for c in s.scalars(select(SopRun).where(
            SopRun.parent_run_id == run_id, SopRun.kind == "row")
            .order_by(SopRun.row_index)).all()] if rows else []
    if rows:
        by_step: dict[str, list[dict]] = {}
        for cid in child_ids:
            c = get_run(cid)
            by_step.setdefault(c["parent_step_run"], []).append(c)
        for st in out["steps"]:
            if st["step_type"] == "foreach":
                st["rows"] = by_step.get(st["id"], [])
                if st["rows"] and isinstance(st.get("output"), dict):
                    # 统计按各行现在的状态算:存下来的那份是这一步结束时的数,之后取消 / 重试就对不上了
                    n = {"ok": 0, "failed": 0, "rejected": 0, "cancelled": 0, "pending": 0}
                    for row in st["rows"]:
                        n[{"done": "ok", "failed": "failed", "rejected": "rejected",
                           "cancelled": "cancelled"}.get(row["status"], "pending")] += 1
                    st["output"] = {**st["output"], **n, "total": len(st["rows"])}
    return out


def _user_names() -> dict[str, str]:
    from ..governance import users
    try:
        return {u["id"]: u["name"] for u in users.list_users(identity.current().workspace)}
    except Exception:  # noqa: BLE001
        return {}


def _show(v: Any) -> str:
    if v is True:
        return "是"
    if v is False:
        return "否"
    if isinstance(v, float) and v.is_integer():
        return str(int(v))
    return "" if v is None else str(v)


def _params_view(spec: dict, params: dict, vars_: dict) -> list[dict]:
    """运行时填的参数,按人看的样子:[{name, label, value}]。对象参数显示对象的名称。"""
    out = []
    defs = {p["name"]: p for p in spec.get("params") or []}
    for k, v in (params or {}).items():
        if k.startswith("__") or k not in defs:
            continue
        p = defs[k]
        shown = _show(v)
        var = (vars_ or {}).get(k)
        if p["type"] == "object" and isinstance(var, dict) and var.get("label"):
            shown = str(var["label"])
        out.append({"name": k, "label": p.get("label") or k, "value": shown, "raw": v,
                    "object_type": p.get("object_type") or ""})
    return out


def list_runs_page(def_id: str = "", status: str = "", trigger: str = "", q: str = "", days: int = 0,
                   limit: int = 30, offset: int = 0) -> dict:
    """运行记录列表(分页):每一条带上参数、走到哪一步、在等谁、用了多久。"""
    import datetime as dt
    with session() as s:
        cond = [SopRun.workspace == identity.current().workspace, SopRun.kind == "main", SopRun.mode == "live"]
        if def_id:
            cond.append(SopRun.def_id == def_id)
        if status:
            cond.append(SopRun.status.in_(status.split(",")))
        if trigger == "manual":
            cond.append(SopRun.trigger.in_(("manual", "")))
        elif trigger:
            cond.append(SopRun.trigger.like(f"{trigger}%"))
        if q:
            cond.append(SopRun.title.like(f"%{q}%") | SopRun.params_json.like(f"%{q}%"))
        if days:
            cond.append(SopRun.created_at >= now() - dt.timedelta(days=int(days)))
        total = s.scalar(select(func.count(SopRun.id)).where(*cond)) or 0
        rows = s.scalars(select(SopRun).where(*cond).order_by(SopRun.created_at.desc())
                         .limit(int(max(1, min(limit, 200)))).offset(int(max(0, offset)))).all()
        names = _user_names()
        items = []
        for r in rows:
            d = _run_dict(r)
            spec = jload(r.spec_json, {})
            d["params_view"] = _params_view(spec, d["params"], d["vars"])
            d.pop("vars", None)
            d["started_by_name"] = names.get(r.started_by, r.started_by)
            last = s.scalars(select(SopStepRun).where(SopStepRun.run_id == r.id)
                             .order_by(SopStepRun.seq.desc())).first()
            cur = {"title": last.title, "status": last.status, "waiting_for": ""} if last else None
            if last and last.status.startswith("waiting"):
                try:
                    if last.task_id:
                        t = tasks.get(last.task_id)
                        cur["waiting_for"] = names.get(t.get("assignee") or "", "") or t.get("role") or ""
                    elif last.action_run_id:
                        ar = actions.get(last.action_run_id)
                        cur["waiting_for"] = "、".join((ar.get("preview") or {}).get("action", {}).get("approver_roles") or [])
                except HTTPException:
                    pass
            d["current"] = cur
            d["step_total"] = len(spec.get("steps") or [])
            items.append(d)
    return {"items": items, "total": int(total), "limit": limit, "offset": offset}


def list_runs(def_id: str = "", status: str = "", mode: str = "", limit: int = 50,
              param_value: str = "", started_by: str = "") -> list[dict]:
    with session() as s:
        stmt = select(SopRun).where(SopRun.workspace == identity.current().workspace,
                                    SopRun.kind == "main")
        if def_id:
            stmt = stmt.where(SopRun.def_id == def_id)
        if status:
            stmt = stmt.where(SopRun.status.in_(status.split(",")))
        if mode:
            stmt = stmt.where(SopRun.mode == mode)
        if started_by:
            stmt = stmt.where(SopRun.started_by == started_by)
        if param_value:
            stmt = stmt.where(SopRun.params_json.like(f"%{param_value}%"))
        return [_run_dict(r) for r in s.scalars(stmt.order_by(SopRun.created_at.desc())
                                                .limit(limit)).all()]


def stats() -> dict:
    with session() as s:
        rows = s.execute(select(SopRun.status, func.count(SopRun.id)).where(
            SopRun.workspace == identity.current().workspace, SopRun.mode == "live",
            SopRun.kind == "main").group_by(SopRun.status)).all()
    return {st: int(n) for st, n in rows}


# ---------------- 变量 ----------------
def _render(v: Any, env: dict) -> Any:
    return actions.render(v, env)


def _rows_of(v: Any) -> list[dict]:
    """把取数结果变成一行一个字典:{columns, rows} 按列名展开;对象列表 {items} 摊平成
    「属性 + key + label」;本来就是字典列表的原样用。"""
    if isinstance(v, dict) and isinstance(v.get("rows"), list):
        cols = [str(c) for c in v.get("columns") or []]
        out = []
        for r in v["rows"]:
            if isinstance(r, dict):
                out.append(r)
            elif isinstance(r, (list, tuple)):
                out.append({c: r[i] if i < len(r) else None for i, c in enumerate(cols)})
        return out
    if isinstance(v, dict) and isinstance(v.get("items"), list):
        v = v["items"]
    if isinstance(v, list):
        # 对象摊平成「属性 + key + label」:流程里引用的是「当前这一条.数量」,不是「当前这一条.properties.数量」
        return [{**(o.get("properties") or {}), "key": o.get("key"), "label": o.get("label")}
                if isinstance(o, dict) and isinstance(o.get("properties"), dict)
                else (o if isinstance(o, dict) else {"value": o}) for o in v]
    return []


def _filter_rows(title: str, rows: list[dict], cond: str, env: dict) -> list[dict]:
    """只留下满足条件的行(如 value > 0,条件里可直接写列名或 item.列名)。"""
    cond = (cond or "").strip()
    if not cond:
        return rows
    kept = []
    for r in rows:
        try:
            if rules.evaluate(cond, {**env, **r, "item": r}):
                kept.append(r)
        except rules.RuleError as e:
            raise HTTPException(422, f"「{title}」的筛选条件「{cond}」求值失败:{e}") from e
    return kept


def _pick_rows(step: dict, src: Any, env: dict, default_limit: int = 20) -> list[dict]:
    """逐条处理要处理的行:先按「只处理满足条件的行」筛,再截上限。"""
    rows = _filter_rows(step["title"], _rows_of(src), step.get("when") or "", env)
    return rows[: int(step.get("limit") or default_limit)]


def _apply_where(step: dict, res: Any, env: dict) -> Any:
    """取数步骤的「只看满足条件的行」:过滤 {columns, rows},并记下筛掉了多少。"""
    if not step.get("where") or not isinstance(res, dict) or not isinstance(res.get("rows"), list):
        return res
    cols = [str(c) for c in res.get("columns") or []]
    kept = _filter_rows(step["title"], _rows_of(res), step["where"], env)
    out = {**res, "rows": [[r.get(c) for c in cols] for r in kept], "rows_before_filter": len(res["rows"])}
    out["summary"] = f"{res.get('summary') or ''}(筛选后 {len(kept)} 行)".strip()
    return out


def _load_param(p: dict, v: Any) -> Any:
    """对象类参数:尽量把对象属性装进变量,分支条件里就能写 obj.某属性。"""
    if p["type"] == "object" and p.get("object_type") and v not in (None, ""):
        key = v.get("key") if isinstance(v, dict) else v
        try:
            o = objects.get(p["object_type"], str(key))
            return {**o["properties"], "key": o["key"], "label": o["label"]}
        except HTTPException:
            return {"key": str(key), "label": str(key)}
    if p["type"] == "period" and isinstance(v, str):
        # 统计周期参数:按哪个指标的周期口径解析(参数上的 calendar 写的是指标名),没写就是自然月
        from ..kernel import calendar as cal
        m = ksvc.rt_fn(p["calendar"], "aggregate") if p.get("calendar") else None
        period = ((m or {}).get("spec") or {}).get("period") or None
        try:
            return cal.resolve({**cal.NATURAL_MONTH, **period} if period else None, v)
        except Exception:  # noqa: BLE001
            return {"period": v}
    if p["type"] == "number" and isinstance(v, str):
        try:
            return float(v)
        except ValueError:
            return v
    if p["type"] == "boolean" and isinstance(v, str):
        return v.strip().lower() in ("true", "1", "yes", "是")
    return v


def _step_evidence(run: dict, step: dict, env: dict) -> list[dict]:
    """把上游步骤取到的数据整理成审批依据:审批人要看到「凭什么建议我批这一单」。"""
    ev: list[dict] = [{"kind": "sop", "text": f"由流程卡「{run['title']}」的步骤「{step['title']}」发起",
                       "ref": run["id"]}]
    if isinstance(env.get("item"), dict):
        ev.append({"kind": "data", "text": f"本行数据:{str(env['item'])[:200]}", "ref": ""})
    for name, val in (env or {}).items():
        if not isinstance(val, dict) or name == "item":
            continue
        if val.get("columns") and isinstance(val.get("rows"), list):
            ev.append({"kind": "data",
                       "text": f"{name}:{len(val['rows'])} 行({'、'.join(map(str, val['columns'][:6]))})",
                       "ref": val.get("sql") or ""})
        elif val.get("summary"):
            ev.append({"kind": "data", "text": f"{name}:{str(val['summary'])[:180]}", "ref": ""})
    return ev[:8]


# ---------------- 启动 ----------------
def _create_run(*, def_id: str, title: str, spec: dict, env: dict, params: dict, mode: str, trigger: str,
                started_by: str, version_id: str = "", version: int = 0, parent_step_run: str = "",
                kind: str = "main", row_index: int = 0, parent_run_id: str = "", event_id: str = "",
                subject: dict | None = None) -> str:
    subject = subject or {}
    with session() as s:
        r = SopRun(id=new_id("sr"), workspace=identity.current().workspace, def_id=def_id, version_id=version_id,
                   version=version, title=title, mode=mode, params_json=jdump(params),
                   vars_json=jdump(env), spec_json=jdump(spec), status="running",
                   current_step=spec.get("start") or "", trigger=trigger,
                   parent_step_run=parent_step_run, started_by=started_by, kind=kind,
                   row_index=row_index, parent_run_id=parent_run_id, event_id=event_id or "",
                   subject_type=str(subject.get("type_id") or "")[:64], subject_key=str(subject.get("key") or "")[:255],
                   subject_label=str(subject.get("label") or "")[:255])
        s.add(r)
        s.commit()
        rid = r.id
    if kind == "main" and version and (subject or event_id):
        from ..kernel import sysobjects
        sysobjects.add_edge("sys_link_sop", "sop_run", rid, str(subject.get("type_id") or ""), str(subject.get("key") or ""))
        if event_id:
            sysobjects.add_edge("sys_link_sop_event", "sop_run", rid, sysobjects.TYPES["alert_event"]["id"], event_id)
    return rid


def _subject(spec: dict, env: dict) -> dict:
    """这次运行处理的是哪个对象:第一个对象类参数。"""
    for p in spec.get("params") or []:
        v = env.get(p["name"])
        if p.get("type") == "object" and p.get("object_type") and isinstance(v, dict) and v.get("key"):
            ot = ksvc.rt_find(p["object_type"], "object_type") or {}
            return {"type_id": ot.get("id") or "", "key": v["key"], "label": v.get("label") or v["key"]}
    return {}


def start(def_id: str, params: dict | None = None, *, mode: str = "live", trigger: str = "manual",
          version: int | None = None, parent_step_run: str = "", wait: bool = False,
          started_by: str = "", note: str = "", event_id: str = "", subject: dict | None = None) -> dict:
    """started_by 不给就是当前登录人;定时 / 预警触发时由调用方显式传(规则的创建人)。
    note 记进审计(如「AI 建议,张三确认」)。
    event_id / subject:预警触发时这次运行处置的是哪条预警、哪个对象 —— 流程里可以用 $event.*,
    运行记录(系统对象「流程运行」)挂到这条预警和这个对象上。"""
    d = service.get(def_id)
    if d["status"] == "archived":
        raise HTTPException(409, f"流程卡「{d['title']}」已归档,先在流程卡列表里恢复才能运行")
    if mode == "dry_run":
        spec, ver, vid = d["spec"], 0, ""
        if d["validation"]["errors"]:
            raise HTTPException(422, "草稿有错误,不能试运行:" + ";".join(d["validation"]["errors"][:5]))
    else:
        vid, ver, spec = service.version_spec(def_id, version)
    params = dict(params or {})
    env: dict[str, Any] = {}
    for p in spec.get("params") or []:
        v = params.get(p["name"], p.get("default"))
        if v in (None, "") and p.get("required") and mode != "dry_run":
            raise HTTPException(422, f"缺少参数「{p['label']}」")
        env[p["name"]] = _load_param(p, v) if v not in (None, "") else None
    if event_id:
        from ..watch import events as wev
        try:
            ev = wev.get(event_id)
            env["event"] = {"id": ev["id"], "title": ev["title"], "severity": ev["severity"], "rule": ev["rule"],
                            "value": ev["value"], "baseline": ev["baseline"], "deviation": ev["deviation"],
                            "object": ev["object"] or {}}
        except HTTPException:
            env["event"] = {"id": event_id}
    subj = subject or _subject(spec, env)
    parent_run_id = ""
    if parent_step_run:
        with session() as s:
            psr = s.get(SopStepRun, parent_step_run)
            parent_run_id = psr.run_id if psr else ""
    rid = _create_run(def_id=def_id, title=d["title"], spec=spec, env=env, params=params, mode=mode,
                      trigger=trigger, started_by=started_by or identity.current().id, version_id=vid,
                      version=ver, parent_step_run=parent_step_run,
                      kind="subflow" if parent_step_run else "main", parent_run_id=parent_run_id,
                      event_id=event_id, subject=subj)
    if mode == "live" and not parent_step_run:
        audit.record("sop.run_start", "sop_run", rid,
                     f"启动 流程卡「{d['title']}」v{ver}({note or trigger})", after={"params": params})
        if trigger == "manual":
            from ..memory import service as memory
            try:
                memory.record_pattern("sop", def_id, d["title"])
            except Exception:  # noqa: BLE001
                log.debug("记录操作习惯失败", exc_info=True)
    if wait:
        advance(rid)
    else:
        _submit(rid)
    return get_run(rid)


def _submit(run_id: str) -> None:
    ctx = contextvars.copy_context()
    _pool.submit(lambda: ctx.run(_safe_advance, run_id))


def _run_actor(run_id: str) -> identity.Actor | None:
    """这次运行以谁的身份往下走:发起人。审批人批完、经办人填完任务之后,流程不该换成他们的身份
    (数据范围、后续动作的发起人都会跟着变)。"""
    from ..governance import users
    with session() as s:
        r = s.get(SopRun, run_id)
        if r is None:
            return None
        uid, ws = r.started_by, r.workspace
    if not uid or uid == "system":
        return identity.Actor(id="system", name="系统", kind="system", roles=["admin"], workspace=ws)
    return users.load_actor(uid, ws)


def _safe_advance(run_id: str) -> None:
    actor = _run_actor(run_id)
    tok = identity.set_current(actor) if actor else None
    try:
        advance(run_id)
    except Exception as e:  # noqa: BLE001
        log.exception("SOP 推进异常 run=%s", run_id)
        _finish(run_id, "failed", error=str(e)[:500])
    finally:
        if tok is not None:
            identity.reset(tok)


# ---------------- 状态读写 ----------------
def _new_step(run_id: str, step: dict, inputs: Any = None) -> str:
    with session() as s:
        seq = (s.scalar(select(func.max(SopStepRun.seq)).where(SopStepRun.run_id == run_id)) or 0) + 1
        sr = SopStepRun(id=new_id("ss"), run_id=run_id, seq=seq, step_id=step["id"],
                        step_type=step["type"], title=step["title"], status="running",
                        inputs_json=jdump(inputs or {}))
        s.add(sr)
        s.commit()
        return sr.id


def _update_step(step_run_id: str, **fields: Any) -> None:
    with session() as s:
        sr = s.get(SopStepRun, step_run_id)
        for k, v in fields.items():
            if k in ("output", "inputs"):
                setattr(sr, f"{k}_json", jdump(v))
            else:
                setattr(sr, k, v)
        if fields.get("status") in ("done", "failed", "suggested", "cancelled"):
            sr.finished_at = now()
        s.commit()


def _cas_step(step_run_id: str, expect: str, to: str) -> bool:
    with session() as s:
        n = s.execute(update(SopStepRun).where(SopStepRun.id == step_run_id, SopStepRun.status == expect)
                      .values(status=to)).rowcount
        s.commit()
        return bool(n)


def _cas_run(run_id: str, expect: tuple[str, ...], to: str, **fields: Any) -> bool:
    with session() as s:
        n = s.execute(update(SopRun).where(SopRun.id == run_id, SopRun.status.in_(expect))
                      .values(status=to, **fields)).rowcount
        s.commit()
        return bool(n)


def _set_run(run_id: str, **fields: Any) -> None:
    with session() as s:
        r = s.get(SopRun, run_id)
        for k, v in fields.items():
            if k == "vars":
                r.vars_json = jdump(v)
            else:
                setattr(r, k, v)
        s.commit()


def _finish(run_id: str, status: str, outcome: str = "", error: str = "") -> None:
    """把运行收尾。只有还没到终态的运行会被收尾,而且只收一次(并发的另一方换不动状态就直接返回)。"""
    if not _cas_run(run_id, ACTIVE, status, outcome=outcome[:255], error=error, finished_at=now()):
        return
    run = get_run(run_id)
    if run["kind"] == "main":
        if run["mode"] == "dry_run":
            service.record_dry_run(run["def_id"], run, service._hash(run["spec"]))
        if run["mode"] == "live":
            label = _STATUS_LABEL.get(status, status)
            audit.record(f"sop.run_{status}", "sop_run", run_id,
                         f"流程卡「{run['title']}」{label}" + (f":{outcome or error}" if (outcome or error) else ""))
            notify.send(run["started_by"], f"流程「{run['title']}」已{label}",
                        outcome or error, link=f"#/sop?run={run_id}")
            from ..watch import events as wev
            try:
                wev.on_finished("sop_run", run_id)       # 处置预警的流程走完了:事件进入「待验证」
            except Exception:  # noqa: BLE001
                log.exception("回写预警事件失败 run=%s", run_id)
    if run.get("parent_step_run"):
        _child_finished(run)


def advance(run_id: str) -> dict:
    """从当前步骤一直往下走,直到需要等待(人工/审批/子流程/逐条处理)或结束。

    试运行读工作副本(草稿里的指标、规则、动作都能用上);正式运行只认已发布的元素。"""
    with _lock(run_id):
        run = get_run(run_id)
        if run["status"] != "running":
            return run
        if run["mode"] == "dry_run":
            with ksvc.draft_runtime():
                return _advance(run_id, run)
        return _advance(run_id, run)


# ---------------- 各类步骤 ----------------
class _Stop(Exception):
    """这一步之后不再往下走(在等人 / 等审批 / 已经收尾)。"""


class _Failed(Exception):
    """这一步失败了。由 _advance 按这一步的「出错时」配置决定重试、停止、带默认值继续还是走失败分支。"""

    def __init__(self, sid: str, title: str, detail: Any, prefix: str = "失败") -> None:
        super().__init__(str(detail))
        self.sid, self.title, self.detail, self.prefix = sid, title, str(detail), prefix


class _Ctx:
    def __init__(self, run_id: str, run: dict) -> None:
        self.run_id, self.run = run_id, run
        self.spec = run["spec"]
        self.env: dict[str, Any] = dict(run["vars"])
        self.mode: str = run["mode"]

    def save(self) -> None:
        _set_run(self.run_id, vars=self.env)

    def fail(self, sid: str, title: str, detail: Any, prefix: str = "失败") -> None:
        _update_step(sid, status="failed", error=str(detail))
        raise _Failed(sid, title, detail, prefix)

    def wait(self) -> None:
        _set_run(self.run_id, status="waiting", vars=self.env)
        raise _Stop

    def sop_actor(self) -> identity.Actor:
        return identity.Actor(id=self.run["started_by"] or "system", name=f"流程卡「{self.run['title']}」",
                              kind="system", roles=["operator"], workspace=identity.current().workspace)


RESULT_VAR = "__result"      # 结束节点算出来的流程输出存在这个变量里(子流程的调用方、运行详情拿它)


def _do_end(c: _Ctx, step: dict) -> str:
    sid = _new_step(c.run_id, step)
    result = {o["name"]: _render(o.get("value"), c.env) for o in step.get("outputs") or [] if o.get("name")}
    if result:
        c.env[RESULT_VAR] = result
    outcome = str(_render(step.get("outcome") or "", c.env) or step["title"])
    _update_step(sid, status="done", output=result or None, note=outcome if step.get("outcome") else "")
    c.save()
    _finish(c.run_id, "done", outcome=outcome)
    raise _Stop


def _do_decision(c: _Ctx, step: dict) -> str:
    chosen, label = step.get("default"), "默认"
    for b in step.get("branches") or []:
        try:
            if rules.evaluate(b["when"], c.env):
                chosen, label = b["next"], b.get("label") or b["when"]
                break
        except rules.RuleError as e:
            sid = _new_step(c.run_id, step)
            c.fail(sid, step["title"], f"分支「{b.get('label') or b['when']}」的条件算不出来:{e}", "求值失败")
    sid = _new_step(c.run_id, step, {"conditions": [{"label": b.get("label"), "when": b["when"]}
                                                    for b in step.get("branches") or []]})
    _update_step(sid, status="done", output={"branch": label, "next": chosen}, note=f"走「{label}」分支")
    return chosen


def _with_items(res: Any) -> Any:
    """取数结果是 {columns, rows(列表的列表)}:补一份 items(一行一个字典),
    后面的步骤就能统一写 $变量.items[0].列名、用 sum_by / where 这些列表函数。"""
    if isinstance(res, dict) and isinstance(res.get("rows"), list) and res.get("columns") and "items" not in res:
        return {**res, "items": _rows_of(res)}
    return res


def call_function(step: dict, env: dict) -> Any:
    args = _render(step.get("args") or {}, env)
    return _with_items(_apply_where(step, registry.call_function(step["function"], args), env)), args


def _do_function(c: _Ctx, step: dict) -> str:
    sid = _new_step(c.run_id, step, _render(step.get("args") or {}, c.env))
    try:
        res, _ = call_function(step, c.env)
    except HTTPException as e:
        c.fail(sid, step["title"], e.detail)
    _update_step(sid, status="done", output=_compact(res), note=res.get("summary", "") if isinstance(res, dict) else "")
    if step.get("output"):
        c.env[step["output"]] = res
    c.save()
    return step["next"]


def _render_cond(cond: Any, env: dict) -> Any:
    """查数据的条件组:右边的值引用了流程里的数据就先换成真实的值。"""
    if not isinstance(cond, dict):
        return cond
    items = []
    for it in cond.get("items") or []:
        if "items" in it:
            items.append(_render_cond(it, env))
        else:
            items.append({**it, "right": _render(it.get("right"), env)})
    return {**cond, "items": items}


def _render_include(incs: list[dict], env: dict) -> list[dict]:
    return [{**i, "where": _render_cond(i.get("where"), env), "include": _render_include(i.get("include") or [], env)}
            for i in incs or []]


def run_query(step: dict, env: dict) -> dict:
    r = objects.fetch(step["object_type"], where=_render_cond(step.get("where"), env), fields=step.get("fields"),
                      include=_render_include(step.get("include") or [], env), sort=step.get("sort"),
                      limit=step.get("limit") or 50, mode=step.get("mode") or "list")
    if step.get("mode") == "one":
        # 只取一个时,结果就是这个对象本身($工单.车牌号),外加 found
        return {**(r["item"] or {}), "found": r["found"], "summary": r["summary"]}
    return r


def _do_query(c: _Ctx, step: dict) -> str:
    sid = _new_step(c.run_id, step, {"where": _render_cond(step.get("where"), c.env)})
    try:
        res = run_query(step, c.env)
    except HTTPException as e:
        c.fail(sid, step["title"], e.detail)
    _update_step(sid, status="done", output=_compact(res), note=res.get("summary", ""))
    if step.get("output"):
        c.env[step["output"]] = res
    c.save()
    return step["next"]


def run_compute(step: dict, env: dict) -> dict:
    """按顺序算每个字段:后面的公式可以用前面算出来的字段。"""
    out: dict[str, Any] = {}
    for a in step.get("assign") or []:
        expr = str(a.get("expr") or "").strip()
        try:
            if expr.startswith("$") and " " not in expr:
                val = _render(expr, {**env, **out})
            else:
                val = rules.evaluate(expr, {**env, **out})
        except rules.RuleError as e:
            raise HTTPException(422, f"「{a.get('label') or a['name']}」的公式算不出来:{e}") from e
        if a.get("type") == "number" and isinstance(val, str):
            try:
                val = float(val)
            except ValueError:
                pass
        out[a["name"]] = val
    return out


def _do_compute(c: _Ctx, step: dict) -> str:
    sid = _new_step(c.run_id, step, {"assign": [{a["name"]: a.get("expr")} for a in step.get("assign") or []]})
    try:
        res = run_compute(step, c.env)
    except HTTPException as e:
        c.fail(sid, step["title"], e.detail)
    note = ",".join(f"{a.get('label') or a['name']} = {_show(res.get(a['name']))}"[:60]
                    for a in (step.get("assign") or [])[:4])
    _update_step(sid, status="done", output=_compact(res), note=note)
    if step.get("output"):
        c.env[step["output"]] = res
    c.save()
    return step["next"]


def run_skill(step: dict, env: dict, live: bool) -> dict:
    inputs = _render(step.get("inputs") or {}, env)
    if step.get("skill"):
        return skills.run(step["skill"], inputs, require_published=live)
    return skills.run_inline(_render(step.get("instruction") or "", env), inputs, step.get("outputs") or None)


def _confirm_form(step: dict) -> list[dict]:
    """AI 把握不足时给人确认的表单:先问对不对,再给每个输出字段一个可以改的格子。"""
    form = [{"name": "__ok", "label": "AI 的判断对吗", "type": "choice", "options": ["对", "不对,我来改"], "required": True}]
    for f in step.get("outputs") or []:
        t = "choice" if f.get("options") else {"number": "number", "boolean": "boolean", "date": "date"}.get(f.get("type"), "text")
        form.append({"name": f["name"], "label": f"{f.get('label') or f['name']}(不对时填正确的)", "type": t,
                     "options": f.get("options") or [], "required": False})
    return form


def _do_skill(c: _Ctx, step: dict) -> str:
    inputs = _render(step.get("inputs") or {}, c.env)
    sid = _new_step(c.run_id, step, inputs)
    try:
        res = run_skill(step, c.env, live=(c.mode == "live"))
    except HTTPException as e:
        c.fail(sid, step["title"], e.detail)
    out = dict(res.get("output") or {})
    out.setdefault("ai_judged", True)
    conf = out.get("confidence")
    low = bool(step.get("confirm_below")) and (conf is None or float(conf) < float(step["confirm_below"]))
    note = (res.get("summary") or "") + (f"(AI 判断,把握 {round(float(conf) * 100)}%)" if conf is not None else "(AI 判断)")
    if low and c.mode == "live":
        ctx = {"sop_run": c.run_id, "title": c.run["title"], "ai_output": out,
               "vars": {k: _compact(v) for k, v in inputs.items()}}
        detail = ";".join(f"{f.get('label') or f['name']}:{_show(out.get(f['name']))}" for f in step.get("outputs") or []) \
            or str(out.get("conclusion") or "")
        task = tasks.create(
            title=f"{c.run['title']} · 确认 AI 的判断:{step['title']}",
            description=f"AI 的结论:{detail}\n\n依据:{out.get('reason') or res.get('summary') or ''}\n\n"
                        f"AI 的把握不足({round(float(conf or 0) * 100)}%,低于 {round(float(step['confirm_below']) * 100)}%),请确认或更正。",
            role=step.get("confirm_role", ""), form=_confirm_form(step), source_type="sop", source_id=sid, context=ctx)
        _update_step(sid, status="waiting_human", task_id=task["id"], output=out,
                     note=f"{note};把握不足,等「{step.get('confirm_role')}」确认")
        c.wait()
    if low:
        note += ";把握不足,正式运行时会转人工确认"
    _update_step(sid, status="done", output=out, note=note)
    if step.get("output"):
        c.env[step["output"]] = out
    c.save()
    return step["next"]


def mock_form(form: list[dict], given: dict | None = None) -> dict:
    """试运行时人工任务的模拟答案:是否 → 是,选项 → 第一个,数字 → 1,其余给一句占位。
    以前一律填一串文字,「是否需要处理」这种字段永远不等于 True,后面的分支必走「否则」。"""
    out = {}
    for f in form or []:
        t = f.get("type") or "text"
        if t == "boolean":
            v: Any = True
        elif t == "choice":
            v = (f.get("options") or [""])[0]
        elif t == "number":
            v = 1
        elif t == "date":
            v = dt.date.today().isoformat()
        else:
            v = f"(试运行:{f.get('label') or f['name']})"
        out[f["name"]] = v
    out.update({k: v for k, v in (given or {}).items() if k in out})
    return out


def _do_human_task(c: _Ctx, step: dict) -> str:
    ctx = {"sop_run": c.run_id, "title": c.run["title"],
           "vars": {k: _compact(v) for k, v in c.env.items()}}
    sid = _new_step(c.run_id, step, ctx)
    who = step.get("assignee") or step.get("role")
    if c.mode == "dry_run":
        fake = mock_form(step.get("form") or [], (c.run["params"].get("__mock__") or {}).get(step["id"]))
        _update_step(sid, status="done", output=fake, note="试运行:人工任务按模拟答案视为已完成")
        if step.get("output"):
            c.env[step["output"]] = fake
        return step["next"]
    if c.mode == "ai_readonly":
        _update_step(sid, status="suggested",
                     note=f"需要「{who}」处理:{step.get('instructions') or step['title']}")
        c.save()
        _finish(c.run_id, "paused", outcome=f"下一步需要人工:{step['title']}")
        raise _Stop
    due = dt.datetime.now() + dt.timedelta(hours=step["sla_hours"]) if step.get("sla_hours") else None
    obj_ref = ""
    for p in c.spec.get("params") or []:
        if p["type"] == "object" and isinstance(c.env.get(p["name"]), dict):
            obj_ref = f"{p['object_type']}:{c.env[p['name']].get('key')}"
            break
    task = tasks.create(
        title=f"{c.run['title']} · {step['title']}",
        description=_render(step.get("instructions") or step.get("description") or "", c.env),
        role=step.get("role", ""), assignee=step.get("assignee", ""), form=step.get("form"),
        checklist=step.get("checklist"), due_at=due, object_ref=obj_ref,
        source_type="sop", source_id=sid, context=ctx)
    _update_step(sid, status="waiting_human", task_id=task["id"])
    c.wait()
    return ""


def _do_notify(c: _Ctx, step: dict) -> str:
    subject = str(_render(step.get("subject") or step["title"], c.env))
    body = str(_render(step.get("body") or "", c.env))
    to = step.get("assignee") or f"role:{step.get('role')}"
    sid = _new_step(c.run_id, step, {"to": to, "subject": subject, "body": body})
    if c.mode == "live":
        notify.send(to, subject, body, link=f"#/sop?run={c.run.get('parent_run_id') or c.run_id}")
        audit.record("sop.notify", "sop_run", c.run_id, f"流程「{c.run['title']}」通知 {to}:{subject}")
        _update_step(sid, status="done", note=f"已通知 {step.get('assignee') or step.get('role')}")
    else:
        _update_step(sid, status="done", note=f"试运行:不真的发。将通知 {step.get('assignee') or step.get('role')}:{subject}")
    return step["next"]


def _effects_note(result: dict | None) -> str:
    """执行完的效果摘要:只用工具自己给的 summary(常常带着新记录的 id)。"""
    parts = []
    for e in (result or {}).get("effects") or []:
        if not e.get("ok"):
            parts.append(f"{e.get('tool')} 失败:{str(e.get('error') or '')[:120]}")
        elif (e.get("result") or {}).get("summary"):
            parts.append(str(e["result"]["summary"]))
    return ";".join(parts)


def _created_keys(result: dict | None) -> dict:
    """动作执行结果里各次写入的主键:{as 名: 主键 | [主键…]}(写数据节点的输出 keys)。"""
    keys: dict[str, Any] = {}
    for e in (result or {}).get("effects") or []:
        keys.update(((e.get("result") or {}).get("created")) or {})
    return keys


def _action_outcome(step: dict, ar: dict) -> tuple[str, str, str, dict] | None:
    """动作已经有结果时决定流程往哪走:返回 (去向, 下一步, 说明, 输出)。

    去向:next = 继续往下;end = 流程到此结束(rejected / cancelled);返回 None 表示还要等
    (待审批,或执行失败 —— 失败的动作可以在待办里重试,重试成功后流程接着走)。"""
    out = {"status": ar["status"], "action_run_id": ar["id"], "result": ar.get("result"),
           "keys": _created_keys(ar.get("result"))}
    if ar["status"] == "done":
        how = "自动执行完成" if (ar.get("approvals") or [{}])[0].get("status") == "auto" else "动作已批准并执行"
        return "next", step["next"], how, out
    if ar["status"] == "rejected":
        if step.get("on_reject"):
            return "next", step["on_reject"], "动作被驳回,走驳回后的步骤", out
        comment = (ar.get("approvals") or [{}])[0].get("comment", "")
        return "rejected", "", f"动作被驳回:{comment}", out
    if ar["status"] == "cancelled":
        # 撤回 ≠ 驳回:有人把这张单撤了,流程应当停下,而不是当成「审批人不同意」走驳回分支
        return "cancelled", "", "动作被撤回,流程停止", out
    return None


def _do_action(c: _Ctx, step: dict) -> str:
    params = _render(step.get("params") or {}, c.env)
    okey = _render(step.get("object_key") or "", c.env)
    if isinstance(okey, dict):
        okey = okey.get("key", "")
    sid = _new_step(c.run_id, step, {"params": params, "object_key": okey})
    if c.mode in ("dry_run", "ai_readonly"):
        try:
            prep = actions.prepare(step["action"], params, str(okey or ""))
        except HTTPException as e:
            c.fail(sid, step["title"], e.detail, "动作预览失败")
        if c.mode == "ai_readonly":
            _update_step(sid, status="suggested", output={"preview": prep}, note=f"建议发起动作:{prep['summary']}")
            _finish(c.run_id, "paused", outcome=f"建议动作:{prep['summary']}")
            raise _Stop
        _update_step(sid, status="done", output={"preview": prep},
                     note=f"试运行:仅预览,视为批准。{prep['summary']}")
        if step.get("output"):
            c.env[step["output"]] = {"status": "approved", "preview": prep}
        return step["next"]
    tok = identity.set_current(c.sop_actor())
    try:
        ar = actions.propose(step["action"], params, object_key=str(okey or ""),
                             reason=f"流程卡「{c.run['title']}」步骤「{step['title']}」",
                             initiator_kind="sop", source_ref=f"sop_step:{sid}",
                             evidence=_step_evidence(c.run, step, c.env))
    except HTTPException as e:
        identity.reset(tok)
        c.fail(sid, step["title"], e.detail, "提交动作失败")
    identity.reset(tok)
    return _after_action(c, step, sid, ar)


def _after_action(c: _Ctx, step: dict, sid: str, ar: dict) -> str:
    """动作 / 写数据提交之后:有结果就往下走,还在等审批就停在这里等回调。"""
    _update_step(sid, action_run_id=ar["id"])
    decided = _action_outcome(step, ar)
    if decided is None:
        note = ar["preview"].get("summary", "")
        if ar["status"] == "failed":
            note = f"执行失败:{ar.get('error') or ''}。可在「审批与待办」里重试,或取消这次运行"
        _update_step(sid, status="waiting_approval", note=note, error=ar.get("error") or "")
        c.wait()
    where, nxt, how, out = decided
    if where != "next":
        _update_step(sid, status="failed" if where == "rejected" else "cancelled", output=out, note=how)
        c.save()
        _finish(c.run_id, where, error=how)
        raise _Stop
    _update_step(sid, status="done", output=out,
                 note=f"{how}:{_effects_note(out.get('result')) or ar['preview'].get('summary', '')}")
    if step.get("output"):
        c.env[step["output"]] = out
    c.save()
    return nxt


def write_spec(step: dict) -> dict:
    """写数据节点 → 内联动作的定义:一项「写多张表」的执行内容 + 节点上配的审批方式。"""
    appr = step.get("approval") or {}
    return {"params": [], "effects": [{"tool": "object.batch", "label": step["title"], "args": {"ops": step.get("ops") or []}}],
            "approval": {"mode": appr.get("mode") or "manual", "approver_roles": appr.get("approver_roles") or [],
                         **({"auto_when": appr["auto_when"]} if appr.get("auto_when") else {})}}


def _write_context(env: dict) -> dict:
    return {k: v for k, v in env.items() if not str(k).startswith("__")}


def _write_ref(run: dict, step: dict) -> str:
    """写数据步骤的运行记在哪个动作名下:发布时沉淀成了本体动作的,就是那个动作。"""
    return step.get("ontology_action") or f"sop:{run['def_id']}:{step['id']}"[:64]


def preview_write(run: dict, step: dict, env: dict, dry_write: bool = True) -> dict:
    """试运行 / 单步试跑:出预览,并在事务里真的写一遍再回滚(数据库的约束问题这时就能看到)。"""
    prep = actions.prepare_inline(_write_ref(run, step), step["title"], write_spec(step), _write_context(env))
    if dry_write:
        ops = ((prep["effects"][0]["args"] or {}).get("ops") or []) if prep.get("effects") else []
        prep["dry_write"] = objects.apply_ops(ops, dry=True) if ops else {"summary": "这一单没有要写的内容"}
    return prep


def _do_write(c: _Ctx, step: dict) -> str:
    sid = _new_step(c.run_id, step, {"ops": len(step.get("ops") or [])})
    if c.mode in ("dry_run", "ai_readonly"):
        try:
            prep = preview_write(c.run, step, c.env, dry_write=(c.mode == "dry_run"))
        except HTTPException as e:
            c.fail(sid, step["title"], e.detail, "写入预览失败")
        if c.mode == "ai_readonly":
            _update_step(sid, status="suggested", output={"preview": prep}, note=f"建议写入:{prep['summary']}")
            _finish(c.run_id, "paused", outcome=f"建议写入:{prep['summary']}")
            raise _Stop
        dry = prep.get("dry_write") or {}
        _update_step(sid, status="done", output={"preview": prep},
                     note=f"试运行:{dry.get('summary') or prep['summary']}(不会真的写入)")
        if step.get("output"):
            c.env[step["output"]] = {"status": "approved", "action_run_id": "", "keys": dry.get("created") or {},
                                     "preview": prep}
        return step["next"]
    tok = identity.set_current(c.sop_actor())
    try:
        ar = actions.propose_inline(_write_ref(c.run, step), step["title"], write_spec(step), _write_context(c.env),
                                    reason=f"流程卡「{c.run['title']}」步骤「{step['title']}」",
                                    source_ref=f"sop_step:{sid}", evidence=_step_evidence(c.run, step, c.env))
    except HTTPException as e:
        identity.reset(tok)
        c.fail(sid, step["title"], e.detail, "提交写入失败")
    identity.reset(tok)
    return _after_action(c, step, sid, ar)


def save_write_as_action(def_id: str, step_id: str, name: str = "", step_def: dict | None = None) -> dict:
    """写数据步骤 → 本体里的动作(草稿)。步骤里引用的流程数据变成动作参数:
    `$工单.店号` → 参数「工单_店号」;按行新建的数据来源 `$缺件.items` → 明细参数「缺件_items」(列按 $row.列 推出来)。"""
    import re as _re
    from ..kernel import service as ksvc
    from . import spec as sop_spec
    d = service.get(def_id)
    step = sop_spec.normalize({"steps": [step_def]})["steps"][0] if step_def else _find_step(d["spec"], step_id)
    if step is None or step["type"] != "write":
        raise HTTPException(422, "只有「写数据」步骤可以另存为动作")
    params: dict[str, dict] = {}
    ref_re = _re.compile(r"\$([A-Za-z_一-鿿][\w一-鿿]*(?:\[\d+\]|\.[\w一-鿿]+)*)")

    def pname(ref: str) -> str:
        return _re.sub(r"[^\w一-鿿]+", "_", ref).strip("_")[:40]

    def conv(v: Any) -> Any:
        if isinstance(v, str):
            def sub(m: Any) -> str:
                ref = m.group(1)
                if ref.split(".")[0].split("[")[0] in ("ops", "row", "today", "now_id", "this_month"):
                    return m.group(0)
                n = pname(ref)
                params.setdefault(n, {"name": n, "label": ref.replace(".", " · "), "type": "string", "required": True})
                return f"${n}"
            return ref_re.sub(sub, v)
        if isinstance(v, dict):
            return {k: conv(x) for k, x in v.items()}
        if isinstance(v, list):
            return [conv(x) for x in v]
        return v
    ops = []
    for op in step.get("ops") or []:
        o = {**op, "values": conv(op.get("values") or {})}
        if op.get("key") not in (None, ""):
            o["key"] = conv(op["key"])
        if op["op"] == "create_rows":
            n = pname(str(op.get("rows") or "").lstrip("$")) or "rows"
            cols = sorted({m.split(".")[1] for m in ref_re.findall(_json(op.get("values"))) if m.startswith("row.")})
            params[n] = {"name": n, "label": f"{op['object_type']}明细", "type": "list", "required": True,
                         "columns": [{"name": c, "label": c, "type": "string"} for c in cols] or [{"name": "value", "label": "值"}]}
            o["rows"] = f"${n}"
        ops.append(o)
    appr = step.get("approval") or {}
    spec = {"params": list(params.values()),
            "effects": [{"tool": "object.batch", "label": step["title"], "args": {"ops": ops}}],
            "approval": {"mode": appr.get("mode") or "manual", "approver_roles": appr.get("approver_roles") or [],
                         **({"auto_when": appr["auto_when"]} if appr.get("auto_when") and "$" not in appr["auto_when"] else {})}}
    return ksvc.create_concept("action", name or step["title"], description=f"由流程卡「{d['title']}」的写数据步骤另存",
                               spec=spec)


def _json(v: Any) -> str:
    return jdump(v)


# ---- 逐条处理 ----
def _row_summary(step_run_id: str, collect: str = "") -> dict:
    """汇总一个循环步骤下各行运行的结果。collect:循环体里某一步的结果变量,按行收集成 results。"""
    with session() as s:
        rows = s.scalars(select(SopRun).where(SopRun.parent_step_run == step_run_id, SopRun.kind == "row")
                         .order_by(SopRun.row_index)).all()
        items = [{"row": r.row_index, "status": r.status, "run_id": r.id,
                  "summary": r.outcome or r.error or ""} for r in rows]
        results = [jload(r.vars_json, {}).get(collect) for r in rows if r.status == "done"] if collect else []
    count = lambda *st: sum(1 for x in items if x["status"] in st)   # noqa: E731
    out = {"total": len(items), "ok": count("done"), "failed": count("failed"),
           "rejected": count("rejected"), "cancelled": count("cancelled"),
           "pending": count("running", "waiting", "cancelling"), "items": items}
    if collect:
        out["results"] = results
    return out


def _row_note(out: dict, dry: bool = False) -> str:
    parts = [f"共 {out['total']} 条"]
    for key, label in (("ok", "预览通过" if dry else "完成"), ("pending", "处理中"), ("rejected", "被驳回"),
                       ("failed", "失败"), ("cancelled", "已取消")):
        if out.get(key):
            parts.append(f"{label} {out[key]}")
    return ",".join(parts)


def _first_action(body: dict) -> dict | None:
    return next((s for s in body.get("steps") or [] if s["type"] in ("action", "write")), None)


def _preview_rows(step: dict, rows: list[dict], env: dict, def_id: str = "") -> list[dict]:
    """只读地看一遍每一行会发起什么动作 / 写入什么(AI 剧本、单步试跑用,不起行运行)。"""
    act = _first_action(step.get("body") or {})
    out = []
    for i, row in enumerate(rows, 1):
        if act is None:
            out.append({"row": i, "ok": True, "summary": "按本条数据走循环体"})
            continue
        env_i = {**env, "item": row, "index": i}
        try:
            if act["type"] == "write":
                prep = preview_write({"def_id": def_id}, act, env_i, dry_write=False)
            else:
                okey = _render(act.get("object_key") or "", env_i)
                if isinstance(okey, dict):
                    okey = okey.get("key", "")
                prep = actions.prepare(act["action"], _render(act.get("params") or {}, env_i), str(okey or ""))
            out.append({"row": i, "ok": True, "summary": prep["summary"],
                        "priority": (prep.get("approval_decision") or {}).get("priority", "")})
        except HTTPException as e:
            out.append({"row": i, "ok": False, "error": str(e.detail)})
    return out


def _do_foreach(c: _Ctx, step: dict) -> str:
    src = _render(step.get("items") or "", c.env)
    try:
        rows = _pick_rows(step, src, c.env)
    except HTTPException as e:
        c.fail(_new_step(c.run_id, step), step["title"], e.detail)
    sid = _new_step(c.run_id, step, {"rows": len(rows)})
    if c.mode == "ai_readonly":
        items = _preview_rows(step, rows, c.env, c.run["def_id"])
        ok = sum(1 for x in items if x["ok"])
        note = f"共 {len(rows)} 条,其中 {ok} 条可以发起"
        out = {"total": len(rows), "ok": ok, "items": items}
        if rows:
            _update_step(sid, status="suggested", output=out, note=f"建议逐条处理:{note}")
            _finish(c.run_id, "paused", outcome=f"建议逐条处理:{note}")
            raise _Stop
        _update_step(sid, status="done", output=out, note=note)
        return step["next"]
    body = step["body"]
    stopped = 0
    for i, row in enumerate(rows, 1):
        rid = _create_run(def_id=c.run["def_id"], title=f"{c.run['title']} · {step['title']} 第 {i} 条",
                          spec={"params": [], "start": body["start"], "steps": body["steps"]},
                          env={**c.env, "item": row, "index": i}, params={"item": row}, mode=c.mode,
                          trigger=f"row:{c.run_id}", started_by=c.run["started_by"],
                          version_id="", version=c.run["version"], parent_step_run=sid,
                          kind="row", row_index=i, parent_run_id=c.run_id)
        try:
            advance(rid)                      # 一行一行同步跑到「结束」或「在等人」;行内的等待不阻塞下一行
        except Exception as e:  # noqa: BLE001
            log.exception("逐条处理第 %s 条异常 run=%s", i, rid)
            _finish(rid, "failed", error=str(e)[:500])
        if step.get("on_item_error") == "stop" and get_run(rid)["status"] == "failed":
            stopped = len(rows) - i           # 有一条失败就不再处理后面的
            break
    out = _row_summary(sid, step.get("collect") or "")
    if stopped:
        out["skipped"] = stopped
    if out["pending"]:
        _update_step(sid, status="waiting_child", output=out, note=_row_note(out))
        _set_run(c.run_id, status="waiting", vars=c.env)
        # 写完「在等」之后再看一眼:可能最后几行恰好在这一瞬间都结束了,它们的回调看到的还是「运行中」
        out = _row_summary(sid, step.get("collect") or "")
        if out["pending"] or not _cas_step(sid, "waiting_child", "running"):
            raise _Stop                       # 还有行没完;或者行的回调已经抢先接手续跑
        if not _cas_run(c.run_id, ("waiting",), "running"):
            raise _Stop
    note = _row_note(out, dry=(c.mode == "dry_run")) + (f",有一条失败,后面 {stopped} 条没有处理" if stopped else "")
    if stopped:
        _update_step(sid, output=out)
        c.fail(sid, step["title"], note, "中止")
    _update_step(sid, status="done", output=out, note=note)
    if step.get("output"):
        c.env[step["output"]] = out
    c.save()
    return step["next"]


def _child_output(child: dict) -> Any:
    """子流程交给调用方的数据:它「结束」节点定义的输出;没定义输出就是它全部的变量。"""
    v = child.get("vars") or {}
    return v.get(RESULT_VAR) if isinstance(v.get(RESULT_VAR), dict) else v


def _do_subprocess(c: _Ctx, step: dict) -> str:
    params = _render(step.get("params") or {}, c.env)
    sid = _new_step(c.run_id, step, params)
    try:
        child = start(step["sop"], params, mode=c.mode, trigger=f"subprocess:{c.run_id}",
                      parent_step_run=sid, wait=True, started_by=c.run["started_by"])
    except HTTPException as e:
        c.fail(sid, step["title"], e.detail, "子流程启动失败")
    _update_step(sid, child_run_id=child["id"])
    if child["status"] == "done":
        _update_step(sid, status="done", output=_child_output(child), note=child["outcome"])
        if step.get("output"):
            c.env[step["output"]] = _child_output(child)
        return step["next"]
    if child["status"] in ("failed", "cancelled", "rejected"):
        c.fail(sid, step["title"], f"子流程没有走完:{child['error'] or child['status']}")
    _update_step(sid, status="waiting_child")
    _set_run(c.run_id, status="waiting", vars=c.env)
    # 子流程可能恰好在这一瞬间结束,它的回调看到的还是「运行中」而没有续跑父流程:再看一眼
    child = get_run(child["id"])
    if child["status"] in TERMINAL and _cas_step(sid, "waiting_child", "running") \
            and _cas_run(c.run_id, ("waiting",), "running"):
        if child["status"] == "done":
            _update_step(sid, status="done", output=_child_output(child), note=child["outcome"])
            if step.get("output"):
                c.env[step["output"]] = _child_output(child)
            return step["next"]
        _update_step(sid, status="failed", error=child["error"])
        _finish(c.run_id, "failed", error=f"子流程失败:{child['error']}")
    raise _Stop


_EXECUTORS = {"end": _do_end, "decision": _do_decision, "function": _do_function, "skill": _do_skill,
              "query": _do_query, "compute": _do_compute, "write": _do_write,
              "human_task": _do_human_task, "notify": _do_notify, "action": _do_action,
              "foreach": _do_foreach, "subprocess": _do_subprocess}
_RETRYABLE = ("function", "query", "skill", "compute", "notify")     # 只读或可重复的步骤才自动重试
_TIMEOUT_OK = ("function", "query", "skill", "compute")
_timeout_pool = ThreadPoolExecutor(max_workers=4, thread_name_prefix="sop-step")


def _run_step(fn: Any, c: "_Ctx", step: dict) -> str:
    """执行一步;配了超时的只读步骤放到另一个线程里等,超时就当作失败(那个线程自己跑完后结果丢弃)。"""
    limit = (step.get("error") or {}).get("timeout") or 0
    if not limit or step["type"] not in _TIMEOUT_OK:
        return fn(c, step)
    from concurrent.futures import TimeoutError as _TO
    ctx = contextvars.copy_context()
    fut = _timeout_pool.submit(lambda: ctx.run(fn, c, step))
    try:
        return fut.result(timeout=limit)
    except _TO:
        raise _Failed("", step["title"], f"超过 {limit} 秒没有完成", "超时") from None


def _on_failed(c: "_Ctx", step: dict, f: _Failed) -> str | None:
    """按「出错时」的配置处理一次失败:返回下一步去哪;None 表示整个流程失败。"""
    err = step.get("error") or {}
    mode = err.get("mode") or "stop"
    if mode == "default":
        if f.sid:
            _update_step(f.sid, status="done", output=err.get("default"),
                         note=f"出错了({f.detail[:120]}),按设置用默认值继续")
        if step.get("output"):
            c.env[step["output"]] = err.get("default")
        c.save()
        return step.get("next") or ""
    if mode == "branch" and err.get("next"):
        if f.sid:
            _update_step(f.sid, note=f"出错了,走失败分支:{f.detail[:120]}")
        c.env["error"] = {"step": step["title"], "message": f.detail}
        c.save()
        return err["next"]
    return None


def _advance(run_id: str, run: dict) -> dict:
    c = _Ctx(run_id, run)
    by_id = {st["id"]: st for st in c.spec["steps"]}
    cur = run["current_step"]
    try:
        for _ in range(MAX_STEPS):
            # 每一步之前重读状态:运行可能刚被取消
            with session() as s:
                r = s.get(SopRun, run_id)
                if r is None or r.status != "running":
                    break
            step = by_id.get(cur)
            if step is None:
                _finish(run_id, "failed", error=f"步骤 {cur} 不存在")
                break
            _set_run(run_id, current_step=cur)
            fn = _EXECUTORS.get(step["type"])
            if fn is None:
                _finish(run_id, "failed", error=f"未知步骤类型 {step['type']}")
                break
            retries = int((step.get("error") or {}).get("retry") or 0) if step["type"] in _RETRYABLE else 0
            for attempt in range(retries + 1):
                try:
                    cur = _run_step(fn, c, step)
                    break
                except _Failed as f:
                    if attempt < retries:
                        log.info("步骤「%s」失败,第 %s 次重试:%s", step["title"], attempt + 1, f.detail)
                        time.sleep(min(2 ** attempt, 5))
                        continue
                    nxt = _on_failed(c, step, f)
                    if nxt is None:
                        if not f.sid:
                            sid = _new_step(run_id, step)
                            _update_step(sid, status="failed", error=f.detail)
                        c.save()
                        _finish(run_id, "failed", error=f"「{f.title}」{f.prefix}:{f.detail}")
                        raise _Stop from None
                    cur = nxt
        else:
            _finish(run_id, "failed", error="步骤数超过上限")
    except _Stop:
        pass
    return get_run(run_id)


def _compact(v: Any, limit: int = 20000) -> Any:
    """步骤输出落库前瘦身:大结果集只留前 50 行。"""
    if isinstance(v, dict) and isinstance(v.get("rows"), list) and len(v["rows"]) > 50:
        v = {**v, "rows": v["rows"][:50], "rows_truncated": True}
    if isinstance(v, dict) and isinstance(v.get("items"), list) and len(v["items"]) > 50:
        v = {**v, "items": v["items"][:50], "items_truncated": True}
    if isinstance(v, dict) and "chunks" in v:
        v = {**v, "chunks": [{**c, "text": c.get("text", "")[:300]} for c in v["chunks"][:8]]}
        v.pop("subgraph", None)
    if len(jdump(v)) > limit:
        return {"summary": (v.get("summary") if isinstance(v, dict) else "") or "(结果过大,已省略)"}
    return v


# ---------------- 续跑(任务完成 / 审批有结果 / 子运行结束) ----------------
def _resume(run_id: str, step_run_id: str, expect: str, next_step: str, output: Any, output_var: str,
            note: str = "") -> None:
    """抢到「这一步从 expect 状态往下走」的资格才续跑;抢不到说明别人已经接手或运行已取消。"""
    if not _cas_step(step_run_id, expect, "running"):
        return
    if not _cas_run(run_id, ("waiting",), "running"):
        _cas_step(step_run_id, "running", expect)        # 运行不在等(已取消 / 正在取消):原样放回
        return
    _update_step(step_run_id, status="done", output=output, note=note)
    run = get_run(run_id)
    env = dict(run["vars"])
    if output_var:
        env[output_var] = output
    _set_run(run_id, vars=env, current_step=next_step)
    _submit(run_id)


def _step_of(step_run_id: str) -> tuple[dict, dict, dict] | None:
    with session() as s:
        sr = s.get(SopStepRun, step_run_id)
        if sr is None:
            return None
        r = s.get(SopRun, sr.run_id)
        spec = jload(r.spec_json, {})
        step = next((x for x in spec.get("steps") or [] if x["id"] == sr.step_id), None)
        if step is None:
            return None
        return _step_dict(sr), _run_dict(r), step


def _end_from_callback(run: dict, sr: dict, step_status: str, run_status: str, how: str,
                       output: Any = None, error: str = "") -> None:
    if not _cas_step(sr["id"], sr["status"], step_status):
        return
    _update_step(sr["id"], status=step_status, output=output, note=how, error=error)
    _finish(run["id"], run_status, error=how)


def _on_task(task: dict) -> None:
    if task.get("source_type") != "sop":
        return
    found = _step_of(task["source_id"])
    if not found:
        return
    sr, run, step = found
    if sr["status"] != "waiting_human" or run["status"] != "waiting":
        return
    if task["status"] == "done":
        out, note = task["result"], f"{task.get('completed_by')} 已完成"
        if step["type"] == "skill":
            # AI 把握不足转人工确认:人确认对就用 AI 的结论;改了的字段以人填的为准
            res = task.get("result") or {}
            out = dict(sr.get("output") or {})
            fixed = {k: v for k, v in res.items() if k != "__ok" and v not in (None, "")}
            out.update(fixed)
            out["human_confirmed"] = True
            out["ai_judged"] = not fixed
            note = f"{task.get('completed_by')} 已确认 AI 的判断" + (f",改了 {'、'.join(fixed)}" if fixed else "")
        _resume(run["id"], sr["id"], "waiting_human", step["next"], out, step.get("output", ""), note=note)
    elif task["status"] == "cancelled":
        _end_from_callback(run, sr, "cancelled", "cancelled", "人工任务被取消")


def _on_action(ar: dict) -> None:
    ref = ar.get("source_ref") or ""
    if not ref.startswith("sop_step:"):
        return
    found = _step_of(ref.split(":", 1)[1])
    if not found:
        return
    sr, run, step = found
    if sr["status"] != "waiting_approval" or run["status"] != "waiting":
        return
    decided = _action_outcome(step, ar)
    if decided is None:
        if ar["status"] == "failed":
            _update_step(sr["id"], error=ar.get("error") or "",
                         note=f"执行失败:{ar.get('error') or ''}。可在「审批与待办」里重试,或取消这次运行")
        return
    where, nxt, how, out = decided
    if where == "next":
        note = f"{how}:{_effects_note(out.get('result')) or (ar.get('preview') or {}).get('summary', '')}"
        _resume(run["id"], sr["id"], "waiting_approval", nxt, out, step.get("output", ""), note=note)
        return
    _end_from_callback(run, sr, "failed" if where == "rejected" else "cancelled", where, how, output=out)


def _child_finished(child: dict) -> None:
    found = _step_of(child["parent_step_run"])
    if not found:
        return
    sr, run, step = found
    if sr["status"] != "waiting_child" or run["status"] != "waiting":
        return                 # 父流程还在同步地一行行起(或已取消):由它自己汇总
    if child["kind"] == "row":
        out = _row_summary(sr["id"], step.get("collect") or "")
        if out["pending"]:
            _update_step(sr["id"], output=out, note=_row_note(out))      # 进度随每一行更新
            return             # 还有别的行没完
        _resume(run["id"], sr["id"], "waiting_child", step["next"], out, step.get("output", ""),
                note=_row_note(out))
        return
    if child["status"] == "done":
        _resume(run["id"], sr["id"], "waiting_child", step["next"], _child_output(child), step.get("output", ""),
                note=child["outcome"])
    else:
        _end_from_callback(run, sr, "failed", "failed", f"子流程{_STATUS_LABEL.get(child['status'], child['status'])}",
                           error=child.get("error", ""))


tasks.on_change(_on_task)
actions.on_finish(_on_action)


# ---------------- 取消 / 回收 ----------------
def cancel(run_id: str, reason: str = "") -> dict:
    """取消一次运行:先把运行换成「取消中」(之后任务 / 审批 / 子运行的回调都成了空操作),
    再取消它挂着的待办、待审批动作和子运行,最后只收尾一次。"""
    if not _cas_run(run_id, ("running", "waiting"), "cancelling"):
        raise HTTPException(409, "只能取消进行中的运行")
    run = get_run(run_id)
    # 收拾这次运行挂着的待办和审批单是系统在做事(取消的人不一定是当初发起那张单子的人)
    tok = identity.set_current(identity.Actor(id="system", name="系统", kind="system", roles=["admin"],
                                              workspace=run["workspace"]))
    try:
        for st in run["steps"] or []:
            if st["status"] == "waiting_human" and st["task_id"]:
                try:
                    tasks.cancel(st["task_id"], "流程已取消")
                except HTTPException:
                    pass
            if st["status"] == "waiting_approval" and st["action_run_id"]:
                try:
                    actions.cancel(st["action_run_id"], "流程已取消")
                except HTTPException:
                    pass
            if st["status"] in ("waiting_human", "waiting_approval", "waiting_child", "running"):
                _update_step(st["id"], status="cancelled", note="流程已取消")
    finally:
        identity.reset(tok)
    with session() as s:
        children = [c.id for c in s.scalars(select(SopRun).where(
            SopRun.parent_run_id == run_id, SopRun.status.in_(("running", "waiting")))).all()]
    for cid in children:
        try:
            cancel(cid, "上级流程已取消")
        except HTTPException:
            pass
    _finish(run_id, "cancelled", error=reason or "手动取消")
    return get_run(run_id)


def recover_stuck(minutes: int = 10) -> int:
    """服务重启时回收僵尸运行:状态还是「运行中 / 取消中」、但已经很久没动的 —— 推进它们的线程随进程没了,
    不回收就永远挂着。「等待中」的不动:它们在等人,任务完成 / 审批的回调会把它们接着跑起来。"""
    cutoff = now() - dt.timedelta(minutes=minutes)
    with session() as s:
        stale = [r.id for r in s.scalars(select(SopRun).where(
            SopRun.status.in_(("running", "cancelling")), SopRun.created_at < cutoff)).all()]
    n = 0
    for rid in stale:
        with session() as s:
            last = s.scalar(select(func.max(SopStepRun.started_at)).where(SopStepRun.run_id == rid))
        if last and last > cutoff:
            continue
        actor = _run_actor(rid)
        tok = identity.set_current(actor) if actor else None
        try:
            _finish(rid, "failed", error="服务中断,这次运行没有跑完,请按相同参数重新运行")
            n += 1
        finally:
            if tok is not None:
                identity.reset(tok)
    if n:
        log.warning("回收了 %d 个中断的流程运行", n)
    return n


def object_section(type_id: str, key: str) -> tuple[str, Any]:
    return "sop_runs", list_runs(param_value=key, mode="live", limit=20)


# ---------------- 单步试跑 ----------------
def _find_step(spec: dict, step_id: str) -> dict | None:
    for s in spec.get("steps") or []:
        if s["id"] == step_id:
            return s
        if s["type"] == "foreach":
            hit = _find_step(s.get("body") or {}, step_id)
            if hit:
                return hit
    return None


def try_step(def_id: str, step_id: str, env: dict | None = None, step_def: dict | None = None) -> dict:
    """单步试跑:只执行这一个步骤,不建运行实例、不推进流程。上游数据可以手填(JSON),
    循环体里的步骤给 item 填一行样例。会改数据的步骤一律只出预览(写数据会在事务里写一遍再回滚)。
    step_def:编辑器里还没保存的这一步(改了马上试,不用等自动保存)。"""
    d = service.get(def_id)
    if step_def:
        from . import spec as sop_spec
        step = sop_spec.normalize({"steps": [step_def]})["steps"][0]
    else:
        step = _find_step(d["spec"], step_id)
    if step is None:
        raise HTTPException(404, f"步骤「{step_id}」不存在")
    with ksvc.draft_runtime():
        return _try_step(def_id, step, dict(env or {}))


def _try_step(def_id: str, step: dict, env: dict) -> dict:
    step_id = step["id"]
    t = step["type"]
    started = time.time()

    def done(output: Any, note: str = "") -> dict:
        return {"step_id": step_id, "type": t, "title": step["title"], "ok": True,
                "output": output, "note": note, "var": step.get("output") or "",
                "ms": int((time.time() - started) * 1000)}

    try:
        if t == "function":
            res, _ = call_function(step, env)
            return done(res, res.get("summary", "") if isinstance(res, dict) else "")
        if t == "query":
            res = run_query(step, env)
            return done(res, res.get("summary", ""))
        if t == "compute":
            return done(run_compute(step, env), "算好了")
        if t == "write":
            prep = preview_write({"def_id": def_id}, step, env)
            return done({"preview": prep}, f"{(prep.get('dry_write') or {}).get('summary') or prep['summary']}"
                                           "(试跑在事务里写一遍再回滚,不会真的写入)")
        if t == "skill":
            res = run_skill(step, env, live=False)
            out = res.get("output") or {}
            conf = out.get("confidence")
            return done(out, (res.get("summary") or "") + (f"(AI 判断,把握 {round(float(conf) * 100)}%)" if conf is not None else ""))
        if t == "end":
            return done({o["name"]: _render(o.get("value"), env) for o in step.get("outputs") or []}, "流程输出")
        if t == "decision":
            for i, br in enumerate(step.get("branches") or []):
                if rules.evaluate(br["when"], env):
                    return done({"branch": i, "next": br["next"]},
                                f"走分支「{br.get('label') or br['when']}」")
            return done({"branch": -1, "next": step.get("default")}, "都不满足,走「否则」")
        if t == "foreach":
            rows = _pick_rows(step, _render(step.get("items") or "", env), env, 10)
            out = _preview_rows(step, rows, env, def_id)
            return done({"preview_rows": out}, f"预览 {len(out)} 条;正式运行时每条各走一遍里面的步骤")
        if t == "action":
            okey = _render(step.get("object_key") or "", env)
            if isinstance(okey, dict):
                okey = okey.get("key", "")
            prep = actions.prepare(step["action"], _render(step.get("params") or {}, env), str(okey or ""))
            return done({"preview": prep}, f"{prep['summary']}(试跑只预览,不会真的提交)")
        if t == "human_task":
            return done({"role": step.get("role"), "assignee": step.get("assignee"), "form": step.get("form") or [],
                         "mock": mock_form(step.get("form") or [])},
                        "人工任务:正式运行时会生成待办,这里只看它会长什么样")
        if t == "notify":
            return done({"to": step.get("assignee") or step.get("role"),
                         "subject": _render(step.get("subject") or step["title"], env),
                         "body": _render(step.get("body") or "", env)}, "通知:试跑不真的发")
        if t == "subprocess":
            return done({"sop": step.get("sop")}, "子流程:请到那张流程卡里单独试跑")
        return done({}, "没有可执行的内容")
    except HTTPException as e:
        return {"step_id": step_id, "type": t, "title": step["title"], "ok": False,
                "error": str(e.detail), "ms": int((time.time() - started) * 1000)}
    except rules.RuleError as e:
        return {"step_id": step_id, "type": t, "title": step["title"], "ok": False,
                "error": f"条件求值失败:{e}(上游数据可以在左边填模拟值)",
                "ms": int((time.time() - started) * 1000)}
    except Exception as e:  # noqa: BLE001
        log.exception("单步试跑失败 sop=%s step=%s", def_id, step_id)
        return {"step_id": step_id, "type": t, "title": step["title"], "ok": False,
                "error": str(e)[:300], "ms": int((time.time() - started) * 1000)}


# ---------------- 运行详情:在等谁、当前这个人能不能直接办 ----------------
def annotate_waiting(run: dict, actor: identity.Actor) -> None:
    """给在等人的步骤挂上它的待办 / 审批单,并标出当前这个人能不能直接办。
    运行详情页据此在步骤卡上直接给出「填写并完成」「批准 / 驳回」「重试」,不用再去待办里找。"""
    for st in run.get("steps") or []:
        try:
            if st["status"] == "waiting_human" and st.get("task_id"):
                t = tasks.get(st["task_id"])
                st["task"] = {**t, "can_handle": t["status"] == "open" and tasks._can_handle(actor, t)}
            elif st["status"] == "waiting_approval" and st.get("action_run_id"):
                ar = actions.get(st["action_run_id"])
                roles = (ar.get("preview") or {}).get("action", {}).get("approver_roles") or []
                st["action"] = {
                    "id": ar["id"], "status": ar["status"], "priority": ar.get("priority"),
                    "summary": (ar.get("preview") or {}).get("summary", ""), "error": ar.get("error") or "",
                    "approver_roles": roles,
                    "can_decide": ar["status"] == "pending_approval" and not actions._can_approve(actor, ar, roles),
                    "can_retry": ar["status"] == "failed" and actor.can("operate")}
            elif st.get("action_run_id"):
                # 已经办完的动作步骤:带上它做了什么,运行详情里能直接看到、点过去
                ar = actions.get(st["action_run_id"])
                st["action_brief"] = {"id": ar["id"], "status": ar["status"],
                                      "summary": (ar.get("preview") or {}).get("summary", ""),
                                      "error": ar.get("error") or ""}
        except HTTPException:
            pass
        for row in st.get("rows") or []:
            annotate_waiting(row, actor)