actions.py 56.7 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
"""动作生命周期:提议 → 校验 → 预览 → 审批(人工 / 自动)→ 执行 → 完成/失败 →(可逆则可撤销)。

硬约束:
1. 动作只能调用已注册的 Tool,参数经模板替换后再过一次 Tool 的入参校验;
2. 审批策略由动作自己定(approval.mode):manual 人工审批;auto 提议即执行;
   conditional 满足 auto_when(或审批决策表输出 auto)就自动执行,否则走人工。
   **AI 提议的动作一律人工审批**,自动执行只对人、流程卡、监控发起的生效;
3. 提议人不能审批自己的提议(四眼原则,管理员除外);
4. 同一动作 + 同参数 + 同来源的未决提议不重复创建(幂等键);
5. 每一步状态变化都写审计。
"""
from __future__ import annotations

import hashlib
import logging
import re
import threading
from typing import Any, Callable

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

from ..core import identity
from ..core.dbx import iso, jdump, jload, new_id, now, session
from ..governance import audit, notify, permissions
from ..kernel import objects, rules
from . import defs, registry
from .models import ActionRun, ApprovalTask

log = logging.getLogger(__name__)

_listeners: list[Callable[[dict], None]] = []
FINAL = ("done", "failed", "rejected", "cancelled", "reverted")


def on_finish(fn: Callable[[dict], None]) -> None:
    """动作走到终态(done/failed/rejected/cancelled)时回调。SOP 引擎靠它继续流程。"""
    _listeners.append(fn)


def _emit(run: dict) -> None:
    for fn in _listeners:
        try:
            fn(run)
        except Exception:  # noqa: BLE001
            log.exception("动作监听者处理失败 run=%s", run["id"])


def _dict(r: ActionRun, approvals: list[dict] | None = None) -> dict:
    return {"id": r.id, "action_id": r.action_id, "action_name": r.action_name,
            "action_version": r.action_version, "kind": r.kind, "revert_of": r.revert_of,
            "params": jload(r.params_json, {}), "target_ref": r.target_ref,
            "initiator_kind": r.initiator_kind, "initiator_id": r.initiator_id,
            "submitted_by": r.submitted_by, "source_ref": r.source_ref, "reason": r.reason,
            "status": r.status, "preview": jload(r.preview_json, {}),
            "priority": r.priority or "P2", "evidence": jload(r.evidence_json, []) or [],
            "impact": jload(r.impact_json, {}) or {},
            "result": jload(r.result_json, {}), "error": r.error,
            "created_at": iso(r.created_at), "decided_at": iso(r.decided_at),
            "finished_at": iso(r.finished_at), "approvals": approvals or []}


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 _named(runs: list[dict]) -> list[dict]:
    """给每张单子带上发起人、审批人的名字(界面上不显示账号)。"""
    names = _user_names()
    for r in runs:
        who = r.get("submitted_by") or r.get("initiator_id") or ""
        who = who[3:] if who.startswith("ai:") else who
        r["submitted_name"] = names.get(who, who)
        for a in r.get("approvals") or []:
            a["decided_name"] = "系统" if str(a.get("decided_by") or "").startswith("system") \
                else names.get(a.get("decided_by") or "", a.get("decided_by") or "")
    return runs


def _approval_dict(a: ApprovalTask) -> dict:
    return {"id": a.id, "run_id": a.run_id, "approver_roles": jload(a.approver_roles_json, []),
            "stage": a.stage or 0, "stage_name": a.stage_name or "", "status": a.status, "decided_by": a.decided_by, "comment": a.comment,
            "created_at": iso(a.created_at), "decided_at": iso(a.decided_at)}


# ---------------- 模板替换 ----------------
_PATH = r"[A-Za-z_一-鿿][\w一-鿿]*(?:\[\d+\]|\.[\w一-鿿]+)*"
_WHOLE = re.compile(rf"^\$({_PATH})$")
_INNER = re.compile(rf"\$({_PATH})")
_STEP = re.compile(r"\.|(\[\d+\])")
KEEP = ("ops",)          # 执行到那一刻才知道的值(前面写入新建出来的主键),模板替换时原样保留


def path_parts(path: str) -> list[Any]:
    """`po.lines[0].qty` → ["po", "lines", 0, "qty"]。"""
    out: list[Any] = []
    for tok in _STEP.split(path):
        if not tok:
            continue
        out.append(int(tok[1:-1]) if tok.startswith("[") else tok)
    return out


def lookup(path: str, env: dict) -> Any:
    cur: Any = env
    for part in path_parts(path):
        if isinstance(part, int):
            cur = cur[part] if isinstance(cur, list) and -len(cur) <= part < len(cur) else None
        elif isinstance(cur, dict):
            cur = cur.get(part)
        else:
            return None
    return cur


def _readable(v: Any, max_rows: int = 20) -> str:
    """把引用值嵌进给人看的文字(任务说明、通知正文):取数结果变成表格,而不是一大段字典。"""
    if v is None:
        return ""
    if isinstance(v, dict) and isinstance(v.get("rows"), list) and v.get("columns"):
        cols, rows = [str(c) for c in v["columns"]], v["rows"]
        lines = [f"(共 {len(rows)} 行)", "| " + " | ".join(cols) + " |", "|" + "---|" * len(cols)]
        lines += ["| " + " | ".join("" if x is None else str(x) for x in r) + " |" for r in rows[:max_rows]]
        if len(rows) > max_rows:
            lines.append(f"……另有 {len(rows) - max_rows} 行")
        return "\n\n" + "\n".join(lines) + "\n\n"          # 表格前后空一行,嵌在列表项里也能渲染成表
    if isinstance(v, dict) and ("summary" in v or "value" in v):
        return str(v.get("summary") or v.get("value"))
    if isinstance(v, (list, tuple)):
        return "、".join(_readable(x) for x in v)
    if isinstance(v, bool):
        return "是" if v else "否"
    if isinstance(v, float):
        return str(int(v)) if v.is_integer() else f"{v:.2f}".rstrip("0").rstrip(".")
    return str(v)


def render(v: Any, env: dict) -> Any:
    """效果参数的模板:`$参数` / `$obj.属性` / `$q.items[0].数量` 取值;以 `=` 开头的是表达式
    (如 `=qty * obj.unit_price`)。引用 `$ops.…`(同一次写入里前面新建出来的主键)的原样保留,执行时再换。"""
    if isinstance(v, str):
        if v.startswith("="):
            try:
                if any(n in KEEP for n in rules.free_names(v[1:])):
                    return v
                return rules.evaluate(v[1:], env)
            except rules.RuleError as e:
                raise HTTPException(422, f"参数表达式「{v}」算不出来:{e}") from e
        m = _WHOLE.match(v.strip())
        if m:
            return v if path_parts(m.group(1))[0] in KEEP else lookup(m.group(1), env)
        return _INNER.sub(lambda mm: mm.group(0) if path_parts(mm.group(1))[0] in KEEP
                          else _readable(lookup(mm.group(1), env)), v)
    if isinstance(v, dict):
        return {k: render(x, env) for k, x in v.items()}
    if isinstance(v, list):
        return [render(x, env) for x in v]
    return v


def expand_ops(ops: list[dict], env: dict) -> list[dict]:
    """写多张表的操作按当前数据填好:`rows` 换成真实的多行数据,每一行的字段映射以 `$row.列` 取这一行的值;
    其余值按 env 替换(`$ops.…` 保留到执行时)。条件 when 不满足的操作去掉。"""
    out = []
    for op in ops or []:
        if op.get("when"):
            try:
                if not rules.evaluate(str(op["when"]), env):
                    continue
            except rules.RuleError as e:
                raise HTTPException(422, f"写入「{op.get('object_type')}」的执行条件算不出来:{e}") from e
        o = {k: v for k, v in op.items() if k not in ("values", "rows", "when", "key")}
        if op.get("op") == "create_rows":
            src = render(op.get("rows"), env)
            rows = rules._rows(src) if src is not None else []
            o["rows"] = [render(op.get("values") or {}, {**env, "row": r, "item": env.get("item", r)}) for r in rows]
        else:
            o["values"] = render(op.get("values") or {}, env)
            if op.get("key") not in (None, ""):
                k = render(op["key"], env)
                o["key"] = k.get("key") if isinstance(k, dict) else k
        out.append(o)
    return out


# ---------------- 准备:校验 + 预览 ----------------
def _load_action(ref: str) -> dict:
    a = defs.find(ref, "action")
    if a is None:
        raise HTTPException(404, f"动作「{ref}」不存在")
    if a["status"] != "published":
        raise HTTPException(409, f"动作「{a['display_name'] or a['name']}」未发布(在本体里发布后才能提议)")
    return a


def _coerce_params(action: dict, params: dict) -> dict:
    out = {}
    for p in action["spec"]["params"]:
        v = params.get(p["name"])
        if v in (None, "") and p.get("default") not in (None, ""):
            v = p["default"]
        if v in (None, ""):
            if p["required"]:
                raise HTTPException(422, f"缺少参数「{p['label']}」")
            continue
        if p["type"] in ("number", "integer"):
            try:
                v = float(v) if p["type"] == "number" else int(v)
            except (TypeError, ValueError) as e:
                raise HTTPException(422, f"参数「{p['label']}」应为数字") from e
        elif p["type"] == "boolean":
            v = v in (True, "true", "1", 1, "是")
        elif p["type"] == "list":
            if isinstance(v, str):
                try:
                    v = jload(v, None)
                except Exception:  # noqa: BLE001
                    v = None
            v = rules._rows(v) if v is not None else None
            if not isinstance(v, list) or (p["required"] and not v):
                raise HTTPException(422, f"参数「{p['label']}」应为多行数据(明细行)")
            cols = {c["name"]: c for c in p.get("columns") or []}
            for i, row in enumerate(v, 1):
                if not isinstance(row, dict):
                    raise HTTPException(422, f"参数「{p['label']}」第 {i} 行不是一行数据")
                for c in cols.values():
                    if c.get("required") and row.get(c["name"]) in (None, ""):
                        raise HTTPException(422, f"参数「{p['label']}」第 {i} 行缺少「{c.get('label') or c['name']}」")
                    if c.get("type") in ("number", "integer") and row.get(c["name"]) not in (None, ""):
                        try:
                            row[c["name"]] = float(row[c["name"]]) if c["type"] == "number" else int(row[c["name"]])
                        except (TypeError, ValueError) as e:
                            raise HTTPException(422, f"参数「{p['label']}」第 {i} 行的「{c.get('label') or c['name']}」应为数字") from e
            out[p["name"]] = v
            continue
        if p["enum"] and str(v) not in p["enum"]:
            raise HTTPException(422, f"参数「{p['label']}」只能是 {'/'.join(p['enum'])}")
        out[p["name"]] = v
    return out


def preview_spec(concept: dict, params: dict, object_key: str = "") -> dict:
    """试跑一个还没发布(甚至没保存)的动作定义:只校验与预览,不提议、不执行。"""
    spec = concept.get("spec") or {}
    action = {"id": concept.get("id") or "", "name": concept.get("name") or "试跑",
              "display_name": concept.get("display_name") or "", "version": concept.get("version") or 0,
              "risk_level": spec.get("risk_level") or "medium", "spec": spec}
    return _prepare(action, params, object_key, strict=False)


def prepare(action_ref: str, params: dict, object_key: str = "", now_id: str = "", strict: bool = True) -> dict:
    """校验参数与前置条件,渲染效果并生成预览。不落库 —— 编排层用它给 AI 的建议做预览卡。
    now_id:沿用上一次预览时生成的编号(人看过预览再提交,单号不能变)。
    strict=False:校验不过也不报错,把每条校验过没过放在结果里(界面上「先看看能不能提交」用)。"""
    return _prepare(_load_action(action_ref), params, object_key, now_id, strict)


def _obj_env(obj: dict) -> dict:
    return {**obj["properties"], "key": obj["key"], "label": obj["label"]}


def _find_related(lk: dict, env: dict) -> dict | None:
    """按条件找到「还要用到的那个对象」。条件里的值可以引用参数和目标对象。找不到返回 None。"""
    filters = []
    for w in lk.get("where") or []:
        v = render(w.get("value"), env)
        if v in (None, "") and (w.get("op") or "eq") not in ("empty", "not_empty"):
            return None                    # 条件的值是空的(如这张单子没有关联别的单据):就是没有这个对象
        filters.append({"property": w["property"], "op": w.get("op") or "eq", "value": v})
    many = lk.get("mode") == "list"
    try:
        r = objects.query(lk["object_type"], filters, limit=int(lk.get("limit") or 50) if many else 1)
    except HTTPException as e:
        raise HTTPException(422, f"查不到「{lk.get('label') or lk['name']}」:{e.detail}") from e
    if many:
        return [_obj_env(o) for o in r["items"]]
    return _obj_env(r["items"][0]) if r["items"] else None


_seq_lock = threading.Lock()
_seq = 0


def new_now_id() -> str:
    """$now_id 的取值:到秒的时间戳 + 三位顺序号。光用时间戳的话,同一秒里发起的两张单会撞号
    (逐条处理一秒能发好几张,第二张就因为单号重复写不进业务库)。"""
    global _seq
    with _seq_lock:
        _seq = (_seq + 1) % 1000
        n = _seq
    return f"{now().strftime('%Y%m%d%H%M%S')}{n:03d}"


def _prepare(action: dict, params: dict, object_key: str = "", now_id: str = "", strict: bool = True,
             context: dict | None = None) -> dict:
    """context:发起方带进来的数据(流程卡里内联的写数据步骤:前面各步的结果),条件和写入内容都能直接引用。"""
    spec = action["spec"]
    p = _coerce_params(action, params or {})
    stamp = now()
    now_id = now_id if re.fullmatch(r"\d{14,20}", now_id or "") else new_now_id()
    # 内置变量:$today 今天、$this_month 本月(YYYY-MM)、$now_id 不重复的编号(新建单据的单号用,如 PO$now_id)
    env: dict[str, Any] = {**(context or {}), "today": stamp.date().isoformat(), "this_month": stamp.strftime("%Y-%m"),
                           "now_id": now_id, **{x["name"]: None for x in spec.get("params") or []}, **p}
    target_ref, target_label = "", ""
    if spec.get("target_type"):
        key = object_key or str(params.get("obj_key") or params.get("key") or "")
        if not key:
            raise HTTPException(422, "这个动作要对一个具体的对象做,请先选对象")
        obj = objects.get(spec["target_type"], key)
        env["obj"] = _obj_env(obj)
        env["obj_key"] = obj["key"]
        env["rel"] = _related(spec["target_type"], obj["key"])
        target_ref = f"object:{obj['type_id']}:{obj['key']}"
        target_label = f"{obj['type_name']}「{obj['label']}」"
    # 参数是一个对象:把它的属性也取出来,校验和执行内容里可以用
    for x in spec.get("params") or []:
        if x["type"] == "object" and x.get("object_type"):
            v = p.get(x["name"])
            try:
                env[f"{x['name']}_obj"] = _obj_env(objects.get(x["object_type"], str(v))) if v not in (None, "") else {}
            except HTTPException as e:
                raise HTTPException(422, f"参数「{x['label']}」:{e.detail}") from e
    for lk in spec.get("lookups") or []:
        env[lk["name"]] = _find_related(lk, env) or ([] if lk.get("mode") == "list" else {})
    checks = []
    for c in spec.get("criteria") or []:
        note = ""
        try:
            ok = bool(rules.evaluate(c["expression"], env))
        except rules.RuleError as e:
            ok, note = False, f"(算不出来:{e})"
        try:
            msg = str(render(c["message"], env))
        except HTTPException:
            msg = c["message"]
        checks.append({"label": c.get("label") or "", "ok": ok, "message": msg + note})
    tr = spec.get("transition") or {}
    if tr and env.get("obj") is not None:
        checks.append(_transition_check(spec, env, tr))
    failed = [c["message"] for c in checks if not c["ok"]]
    if failed and strict:
        raise HTTPException(422, "不能提交:" + ";".join(failed))
    effects = []
    if tr and env.get("obj") is not None and not failed:
        cur = env["obj"].get(tr["property"])
        effects.append({"tool": "object.transition", "label": f"状态:{cur} → {tr['to']}",
                        "args": {"object_type": spec["target_type"], "key": env["obj_key"],
                                 "property": tr["property"], "to": tr["to"]},
                        "as": "", "preview": {"summary": f"{target_label}的{tr['property']}:{cur} → {tr['to']}"},
                        "risk_level": "low", "external": False})
    for e in spec["effects"]:
        tool = registry.TOOLS[e["tool"]]
        what = e.get("label") or tool.title
        try:
            if e.get("when") and not rules.evaluate(e["when"], env):
                continue                  # 这一单不满足这项的执行条件
        except rules.RuleError as ex:
            if failed:
                continue
            raise HTTPException(422, f"「{what}」的执行条件算不出来:{ex}") from ex
        try:
            raw = ({**e["args"], "ops": expand_ops(e["args"].get("ops") or [], env)} if tool.name == "object.batch"
                   else render(e["args"], env))
            args = registry.validate_args(tool.input_schema, raw, f"「{what}」")
            with objects.acting(action):  # 预览时也按「这个动作在做」核对状态流转
                pv = tool.preview(args)
        except HTTPException as ex:
            if failed:                    # 校验没过时,后面的内容算不出来是正常的:照样把校验结果给人看
                continue
            raise HTTPException(422, f"「{what}」做不了:{ex.detail}") from ex
        effects.append({"tool": tool.name, "label": what, "args": args, "as": e.get("as") or "",
                        "preview": pv, "risk_level": tool.risk_level, "external": tool.external})
    reject_effects = []
    for e in spec.get("on_reject") or []:
        tool = registry.TOOLS[e["tool"]]
        try:
            args = registry.validate_args(tool.input_schema, render(e["args"], {**env, "reject_reason": "$reject_reason"}),
                                          f"「{e.get('label') or tool.title}」")
        except HTTPException:
            if failed:
                continue
            raise
        reject_effects.append({"tool": tool.name, "label": e.get("label") or tool.title, "args": args})
    # 效果渲染后的实际取值(如采购金额)也进环境:审批决策要按「这一单多少钱」判,
    # 而金额是效果里算出来的,不是入参。
    eff: dict[str, Any] = {}
    for e in effects:
        for k, v in (e["args"] or {}).items():
            if isinstance(v, dict):
                eff.update({str(kk): vv for kk, vv in v.items() if not isinstance(vv, (dict, list))})
            elif k == "ops" and isinstance(v, list):
                for op in v:                       # 写多张表:各条写入的字段值也进来(同名的后写的为准)
                    for vals in [op.get("values") or {}, *(op.get("rows") or [])]:
                        eff.update({str(kk): vv for kk, vv in vals.items() if not isinstance(vv, (dict, list))})
                    if op.get("rows"):
                        eff[f"{op.get('as') or op.get('object_type')}_行数"] = len(op["rows"])
            elif not isinstance(v, list):
                eff[str(k)] = v
    env["eff"] = eff
    # 类型是「一个对象」的参数:给审批人看名称,不是主键
    shown: dict[str, str] = {}
    for x in spec.get("params") or []:
        v = p.get(x["name"])
        if x.get("type") == "object" and x.get("object_type") and v not in (None, ""):
            shown[x["name"]] = objects.labels(x["object_type"], [v]).get(str(v), str(v))
    out = {"action": {"id": action["id"], "name": action["name"],
                      "display_name": action["display_name"], "version": action["version"],
                      "reversible": spec.get("reversible", False),
                      "risk_level": action["risk_level"],
                      "approver_roles": spec["approval"]["approver_roles"]},
           "params": p, "target_ref": target_ref, "target_label": target_label,
           "effects": effects, "now_id": now_id, "checks": checks, "blocked": bool(failed),
           "param_labels": {x["name"]: x["label"] for x in spec.get("params") or []},
           "param_values": shown,
           "summary": ";".join(e["preview"].get("summary", "") for e in effects)}
    if reject_effects:
        out["on_reject"] = reject_effects
    appr = spec["approval"]
    dec: dict = {}
    env.setdefault("rel", {})
    if (appr.get("decision") or {}).get("function"):
        dec = _approval_decision(appr["decision"], env)
        if dec:
            out["approval_decision"] = dec
            if dec.get("priority"):
                out["action"]["priority"] = dec["priority"]
            if dec.get("approver_roles"):
                out["action"]["approver_roles"] = dec["approver_roles"]
    env["priority"] = out["action"].get("priority") or _RISK_PRIORITY.get(action["risk_level"], "P2")
    out["auto"] = _auto_policy(appr, env, dec)
    # 分段审批:逐段判断这一单要不要过这一段
    stages = []
    for st in appr.get("stages") or []:
        skip, why = False, ""
        if st.get("skip_when"):
            try:
                skip = bool(rules.evaluate(st["skip_when"], env))
            except rules.RuleError:
                skip = False              # 算不出来就照常批,不放过
            why = "符合免批条件" if skip else ""
        stages.append({"name": st["name"], "approver_roles": st["approver_roles"], "skip": skip, "why": why})
    if stages:
        out["stages"] = stages
        cur = next((i for i, s in enumerate(stages) if not s["skip"]), None)
        out["stage_index"] = cur
        if cur is not None:
            out["action"]["approver_roles"] = stages[cur]["approver_roles"]
        elif out["auto"]["mode"] == "manual":
            out["auto"] = {"mode": "conditional", "eligible": True, "why": "各审批环节都符合免批条件"}
    return out


def _transition_check(spec: dict, env: dict, tr: dict) -> dict:
    """状态流转的前置校验:当前状态在不在 from 里、状态机允不允许这样走。"""
    cur = env["obj"].get(tr["property"])
    label = f"{tr['property']}:{cur} → {tr['to']}"
    if tr.get("from") and str(cur) not in tr["from"]:
        return {"label": "状态", "ok": False,
                "message": f"只有{tr['property']}是{'、'.join(tr['from'])}时才能做(现在是 {cur})"}
    try:
        ot = objects.object_type(spec["target_type"])
        if objects.is_interface(ot):
            ot, _ = objects.concrete(ot["id"], env["obj_key"])
        p = objects._prop(ot, tr["property"])
    except HTTPException as e:
        return {"label": "状态", "ok": False, "message": str(e.detail)}
    if p is None or not p.get("lifecycle"):
        return {"label": "状态", "ok": False, "message": f"「{tr['property']}」不是带状态机的属性"}
    hits = [t for t in p["lifecycle"].get("transitions") or [] if t["to"] == tr["to"] and str(cur) in t["from"]]
    if not hits:
        return {"label": "状态", "ok": False, "message": f"状态机不允许从「{cur}」流转到「{tr['to']}」"}
    return {"label": "状态", "ok": True, "message": label}


def _auto_policy(appr: dict, env: dict, dec: dict) -> dict:
    """这一单能不能不等人批、直接执行。条件算不出来一律退回人工审批。"""
    mode = appr.get("mode") or "manual"
    if mode == "auto":
        return {"mode": mode, "eligible": True, "why": "动作设为「自动执行」"}
    if mode != "conditional":
        return {"mode": "manual", "eligible": False, "why": "动作设为「人工审批」"}
    if dec.get("auto") is True:
        return {"mode": mode, "eligible": True, "why": f"审批决策表「{dec['function']}」判定可自动执行"}
    cond = appr.get("auto_when") or ""
    if cond:
        try:
            if rules.evaluate(cond, env):
                return {"mode": mode, "eligible": True, "why": f"满足自动执行条件:{cond}"}
            return {"mode": mode, "eligible": False, "why": f"不满足自动执行条件({cond}),转人工审批"}
        except rules.RuleError as e:
            return {"mode": mode, "eligible": False, "why": f"自动执行条件算不出来({e}),转人工审批"}
    return {"mode": mode, "eligible": False, "why": "没有满足自动执行的条件,转人工审批"}


def _related(type_id: str, key: str) -> dict:
    """目标对象沿 n:1 关系走一跳,按关系名放进 rel,供审批决策写
    `rel.供货.status == '延期'` 这类跨对象条件。查不到就给空,不让审批流程挂掉。"""
    if not type_id or not key:
        return {}
    out: dict[str, Any] = {}
    try:
        # 取 2 条:正好 1 条才说明这一侧是唯一的,才敢当成「这一单的供应商」用。
        # 方向不限 —— 「商品 ← 供货 ← 供应商」从商品这边看是入边,但供应商依然唯一。
        for g in objects.linked(type_id, key, limit=2) or []:
            items = g.get("items") or []
            if len(items) != 1:
                continue
            props = {**(items[0].get("properties") or {}),
                     "key": items[0].get("key"), "label": items[0].get("label")}
            out[g["link_type"]] = props           # 按关系名,如 rel.供货.status
            out.setdefault(g["object_type"], props)   # 也按对象名,如 rel.供应商.status
    except Exception:  # noqa: BLE001
        log.debug("解析关联对象失败", exc_info=True)
    return out


def _approval_decision(cfg: dict, env: dict) -> dict:
    """用本体里的决策表算这一单的优先级与审批人。

    决策表算不出来(没发布、输入缺失、表达式报错)时返回空,调用方退回动作的静态 risk_level ——
    审批本身绝不能因为决策表有问题就卡住。
    """
    from ..kernel import decision as decision_engine, service as ksvc
    name = cfg.get("function") or ""
    try:
        fn = ksvc.rt_fn(name, "decision")
    except Exception:  # noqa: BLE001
        log.info("审批决策表「%s」不可用,按动作风险等级定优先级", name)
        return {}
    values = {}
    for k, v in (cfg.get("inputs") or {}).items():
        try:
            values[k] = render(v, env)
        except Exception:  # noqa: BLE001
            log.info("审批决策输入「%s」求值失败", k)
            return {}
    try:
        r = decision_engine.evaluate(fn.get("spec") or {}, values)
    except Exception:  # noqa: BLE001
        log.info("审批决策表「%s」求值失败", name)
        return {}
    res = r.get("result") or {}
    if isinstance(res, list):
        res = res[0] if res else {}
    prio = str(res.get("priority") or "").upper()
    approver = res.get("approver_roles") or res.get("approver") or ""
    roles = [str(x) for x in approver] if isinstance(approver, list) else         ([str(approver)] if approver else [])
    auto = res.get("auto")
    return {"function": name, "inputs": values, "matched": r.get("matched") or [],
            "priority": prio if prio in PRIORITIES else "",
            "approver_roles": roles, "auto": auto in (True, 1, "true", "True", "是", "yes", "Y"),
            "why": f"按决策表「{name}」:" + ",".join(f"{k}={v}" for k, v in values.items())}


# ---------------- 提议 ----------------
PRIORITIES = ("P0", "P1", "P2", "P3")
_RISK_PRIORITY = {"high": "P1", "medium": "P2", "low": "P3"}


def _impact(target_ref: str) -> dict:
    """提议时顺带算影响面:这个对象在关系网上会波及谁(骨架没同步就跳过)。"""
    if not target_ref.startswith("object:"):
        return {}
    _, type_id, key = target_ref.split(":", 2)
    try:
        from ..kernel import traverse
        t = traverse.traverse(type_id, key, depth=2, limit=200)
    except HTTPException:
        return {}
    except Exception:  # noqa: BLE001
        log.debug("计算影响面失败", exc_info=True)
        return {}
    return {"by_type": t["by_type"], "total": sum(t["by_type"].values()),
            "sample": [{"type_name": n["type_name"], "label": n["label"], "depth": n["depth"]}
                       for n in t["nodes"] if n["depth"]][:12],
            "synced_at": t["synced_at"]}


def _evidence(items: Any) -> list[dict]:
    out = []
    for it in items or []:
        if isinstance(it, str):
            it = {"text": it}
        if isinstance(it, dict) and (it.get("text") or it.get("ref")):
            out.append({"kind": str(it.get("kind") or "note"), "text": str(it.get("text") or "")[:1000],
                        "ref": str(it.get("ref") or "")[:255]})
    return out[:20]


def propose(action_ref: str, params: dict, *, object_key: str = "", reason: str = "",
            initiator_kind: str = "user", source_ref: str = "", priority: str = "",
            evidence: Any = None, now_id: str = "") -> dict:
    prep = prepare(action_ref, params, object_key, now_id)
    return _propose(prep, object_key=object_key, reason=reason, initiator_kind=initiator_kind,
                    source_ref=source_ref, priority=priority, evidence=evidence)


def inline_action(ref: str, title: str, spec: dict, context: dict) -> dict:
    """流程卡里内联的写数据步骤 → 一个「当场定义」的动作:同样的校验、预览、审批、执行、撤销与审计,
    只是定义不在本体的动作列表里,而是冻结在这次运行的预览里。"""
    norm, risk = defs.validate_action(spec, extra_names=set(context))
    return {"id": ref, "name": title, "display_name": title, "version": 0, "risk_level": risk,
            "status": "published", "spec": norm}


def prepare_inline(ref: str, title: str, spec: dict, context: dict, strict: bool = True) -> dict:
    return _prepare(inline_action(ref, title, spec, context), {}, strict=strict, context=context)


def propose_inline(ref: str, title: str, spec: dict, context: dict, *, reason: str = "",
                   source_ref: str = "", evidence: Any = None) -> dict:
    prep = prepare_inline(ref, title, spec, context)
    return _propose(prep, reason=reason, initiator_kind="sop", source_ref=source_ref, evidence=evidence)


def _propose(prep: dict, *, object_key: str = "", reason: str = "", initiator_kind: str = "user",
             source_ref: str = "", priority: str = "", evidence: Any = None) -> dict:
    actor = identity.current()
    prio = (priority or "").upper()
    if prio and prio not in PRIORITIES:
        raise HTTPException(422, f"优先级只能是 {'/'.join(PRIORITIES)}")
    # 优先级三级兜底:调用方显式指定 → 本体里的审批决策表按这一单的实际情况算 → 动作的静态风险等级
    dec = prep.get("approval_decision") or {}
    prio = prio or dec.get("priority") or _RISK_PRIORITY.get(prep["action"]["risk_level"], "P2")
    if dec.get("why"):
        evidence = list(evidence or []) + [{"kind": "rule", "text": dec["why"],
                                            "ref": dec.get("function", "")}]
    auto = prep.get("auto") or {}
    # AI 提议的一律等人批:自动执行只给人、流程卡、监控发起的
    auto_ok = bool(auto.get("eligible")) and initiator_kind != "ai"
    if auto.get("mode") in ("auto", "conditional"):
        evidence = list(evidence or []) + [{"kind": "rule", "text": (auto.get("why") or "") +
                                            ("" if auto_ok or initiator_kind != "ai" else ";AI 提议的动作一律人工审批"),
                                            "ref": "approval.auto"}]
    key_src = jdump({"a": prep["action"]["id"], "p": prep["params"], "t": prep["target_ref"],
                     "s": source_ref})
    idem = hashlib.sha1(key_src.encode("utf-8")).hexdigest()
    with session() as s:
        dup = s.scalars(select(ActionRun).where(
            ActionRun.workspace == actor.workspace, ActionRun.idempotency_key == idem,
            ActionRun.status.in_(("pending_approval", "executing")))).first()
        if dup:
            return get(dup.id)
        run = ActionRun(id=new_id("ar"), workspace=actor.workspace,
                        action_id=prep["action"]["id"], action_name=prep["action"]["display_name"]
                        or prep["action"]["name"], action_version=prep["action"]["version"],
                        params_json=jdump(prep["params"] | ({"obj_key": object_key} if object_key else {})),
                        target_ref=prep["target_ref"], initiator_kind=initiator_kind,
                        target_type=_target_part(prep["target_ref"], 1), target_key=_target_part(prep["target_ref"], 2),
                        target_label=str(prep.get("target_label") or "")[:255],
                        initiator_id=actor.id,
                        submitted_by=actor.id if actor.kind == "user"
                        else actor.id[3:] if actor.id.startswith("ai:") else "",
                        source_ref=source_ref, reason=reason or "",
                        status="executing" if auto_ok else "pending_approval", preview_json=jdump(prep),
                        decided_at=now() if auto_ok else None,
                        idempotency_key=idem, priority=prio,
                        evidence_json=jdump(_evidence(evidence)),
                        impact_json=jdump(_impact(prep["target_ref"])))
        s.add(run)
        roles = prep["action"]["approver_roles"]
        stages = prep.get("stages") or []
        if stages and not auto_ok:
            cur = prep.get("stage_index") or 0
            for i, st in enumerate(stages[:cur + 1]):
                s.add(ApprovalTask(id=new_id("ap"), workspace=actor.workspace, run_id=run.id,
                                   approver_roles_json=jdump(st["approver_roles"]), stage=i, stage_name=st["name"],
                                   **({"status": "auto", "decided_by": "system:auto", "comment": st["why"],
                                       "decided_at": now()} if i < cur else {})))
        else:
            s.add(ApprovalTask(id=new_id("ap"), workspace=actor.workspace, run_id=run.id,
                               approver_roles_json=jdump(roles),
                               stage_name=stages[0]["name"] if stages else "",
                               **({"status": "auto", "decided_by": "system:auto", "comment": auto.get("why", ""),
                                   "decided_at": now()} if auto_ok else {})))
        s.commit()
        rid = run.id
    from ..kernel import sysobjects
    sysobjects.add_edge("sys_link_action", "action_run", rid, _target_part(prep["target_ref"], 1),
                        _target_part(prep["target_ref"], 2))
    out = get(rid)
    who = {"ai": "AI", "sop": "流程卡", "watch": "预警规则"}.get(initiator_kind, "")
    audit.record("action.propose", "action_run", rid,
                 f"{who}提议动作「{out['action_name']}」:{prep['summary']}",
                 after={"params": prep["params"], "preview": prep, "reason": reason})
    if auto_ok:
        audit.record("action.auto_approve", "action_run", rid,
                     f"自动执行动作「{out['action_name']}」:{auto.get('why', '')}")
        out = _execute(rid)
        _record_habit(initiator_kind, prep, out, reason)
        return out
    for r in roles or ["approver"]:
        notify.send(f"role:{r}", f"待审批:{out['action_name']}", prep["summary"],
                    link=f"#/inbox?run={rid}")
    _record_habit(initiator_kind, prep, out, reason)
    return out


def _target_part(target_ref: str, i: int) -> str:
    parts = (target_ref or "").split(":", 2)
    return parts[i][:255] if len(parts) == 3 and parts[0] == "object" else ""


def _record_habit(initiator_kind: str, prep: dict, out: dict, reason: str) -> None:
    if initiator_kind != "user":
        return
    from ..memory import service as memory
    try:
        memory.record_pattern("action", prep["action"]["name"], out["action_name"], reason or prep["summary"])
    except Exception:  # noqa: BLE001
        log.debug("记录操作习惯失败", exc_info=True)


# ---------------- 查询 ----------------
def get(run_id: str) -> dict:
    with session() as s:
        r = s.get(ActionRun, run_id)
        if r is None:
            raise HTTPException(404, "动作记录不存在")
        aps = [_approval_dict(a) for a in s.scalars(
            select(ApprovalTask).where(ApprovalTask.run_id == run_id).order_by(ApprovalTask.created_at)).all()]
        return _named([_dict(r, aps)])[0]


def list_runs(*, status: str = "", action_id: str = "", target_ref: str = "",
              source_ref: str = "", limit: int = 100) -> list[dict]:
    with session() as s:
        stmt = select(ActionRun).where(ActionRun.workspace == identity.current().workspace)
        if status:
            stmt = stmt.where(ActionRun.status.in_(status.split(",")))
        if action_id:
            stmt = stmt.where(ActionRun.action_id == action_id)
        if target_ref:
            stmt = stmt.where(ActionRun.target_ref == target_ref)
        if source_ref:
            stmt = stmt.where(ActionRun.source_ref.like(f"{source_ref}%"))
        runs = [_dict(r) for r in s.scalars(stmt.order_by(ActionRun.created_at.desc())
                                            .limit(limit)).all()]
    # 列表里的按钮要和后端判断一致:以前审批历史里的「批准」对谁都显示,点了才 403
    actor = identity.current()
    for r in runs:
        if r["status"] == "pending_approval":
            why = _can_approve(actor, r, r["preview"].get("action", {}).get("approver_roles") or [])
            r["can_approve"], r["cannot_reason"] = not why, why
            r["can_cancel"] = _can_cancel(actor, r)
        else:
            r["can_approve"], r["cannot_reason"], r["can_cancel"] = False, "", False
    return _named(runs)


def _can_cancel(actor: identity.Actor, run: dict) -> bool:
    """谁能撤回一张待审批的单子:发起人自己(含他让 AI 代提的、他发起的流程提的),或管理员。
    以前流程卡提的单子任何有操作权限的人都能撤,撤了还会让流程走错分支。"""
    mine = {actor.id, f"ai:{actor.id}"}
    return "admin" in actor.roles or run["initiator_id"] in mine or run["submitted_by"] in mine


def _can_approve(actor: identity.Actor, run: dict, roles: list[str]) -> str:
    """返回不能审批的原因;空串表示可以(规则统一在 governance.permissions)。

    流程卡和监控发起的动作,提议人算流程 / 监控本身,不算「启动它的那个人」—— 参数是已发布的
    流程卡定义算出来的,不是谁现填的。否则批准了「发起补货流程」的采购经理,就再也批不了这条
    流程里的补货单,整条流程卡在半路上(审批角色该担的责任一点没少,这一单他还是要看过才放行)。
    """
    submitters = () if run["initiator_kind"] in ("sop", "watch") \
        else (run["initiator_id"], run["submitted_by"])
    return permissions.can_decide(actor, perm="approve", roles=roles, what="动作",
                                  submitters=submitters)


def pending_for(actor: identity.Actor) -> list[dict]:
    with session() as s:
        rows = s.scalars(select(ActionRun).where(
            ActionRun.workspace == actor.workspace,
            ActionRun.status == "pending_approval").order_by(ActionRun.created_at.desc())).all()
        runs = [_dict(r) for r in rows]
    out = []
    for r in runs:
        roles = r["preview"].get("action", {}).get("approver_roles") or []
        why = _can_approve(actor, r, roles)
        r["can_approve"] = not why
        r["cannot_reason"] = why
        r["can_cancel"] = _can_cancel(actor, r)
        out.append(r)
    out.sort(key=lambda r: r["priority"])          # 稳定排序:同优先级仍按提议时间倒序
    return _named(out)


def count_pending(actor: identity.Actor) -> int:
    return sum(1 for r in pending_for(actor) if r["can_approve"])


# ---------------- 审批 & 执行 ----------------
def decide(run_id: str, approve: bool, comment: str = "") -> dict:
    actor = identity.current()
    run = get(run_id)
    if run["status"] != "pending_approval":
        raise HTTPException(409, f"该动作当前状态为「{run['status']}」,不能审批")
    roles = run["preview"].get("action", {}).get("approver_roles") or []
    why = _can_approve(actor, run, roles)
    if why:
        raise HTTPException(403, why)
    if not approve and not comment.strip():
        raise HTTPException(422, "驳回时请填写原因")
    stages = run["preview"].get("stages") or []
    nxt = None                               # 批准后还要过的下一段
    with session() as s:
        ap = s.scalars(select(ApprovalTask).where(ApprovalTask.run_id == run_id,
                                                  ApprovalTask.status == "pending")).first()
        cur = (ap.stage or 0) if ap else 0
        if ap:
            ap.status = "approved" if approve else "rejected"
            ap.decided_by = actor.id
            ap.comment = comment
            ap.decided_at = now()
        r = s.get(ActionRun, run_id)
        if approve and stages:
            for i in range(cur + 1, len(stages)):
                st = stages[i]
                if st.get("skip"):
                    s.add(ApprovalTask(id=new_id("ap"), workspace=r.workspace, run_id=run_id,
                                       approver_roles_json=jdump(st["approver_roles"]), stage=i,
                                       stage_name=st["name"], status="auto", decided_by="system:auto",
                                       comment=st.get("why") or "", decided_at=now()))
                    continue
                nxt = (i, st)
                s.add(ApprovalTask(id=new_id("ap"), workspace=r.workspace, run_id=run_id,
                                   approver_roles_json=jdump(st["approver_roles"]), stage=i, stage_name=st["name"]))
                pv = jload(r.preview_json, {})
                pv["stage_index"] = i
                pv.setdefault("action", {})["approver_roles"] = st["approver_roles"]
                r.preview_json = jdump(pv)
                break
        if nxt is None:
            r.status = "executing" if approve else "rejected"
            r.decided_at = now()
        s.commit()
    if nxt is not None:
        audit.record("action.approve", "action_run", run_id,
                     f"「{run['action_name']}」的「{stages[cur]['name']}」已通过,转「{nxt[1]['name']}」"
                     + (f":{comment}" if comment else ""))
        for role in nxt[1]["approver_roles"] or ["approver"]:
            notify.send(f"role:{role}", f"待审批:{run['action_name']}({nxt[1]['name']})",
                        run["preview"].get("summary", ""), link=f"#/inbox?run={run_id}")
        return get(run_id)
    exempt = permissions.self_decided(actor, (run["initiator_id"], run["submitted_by"]))
    audit.record("action.approve" if approve else "action.reject", "action_run", run_id,
                 f"{'批准' if approve else '驳回'}动作「{run['action_name']}」"
                 + (f":{comment}" if comment else "") + (f"({permissions.ADMIN_NOTE})" if exempt else ""))
    notify.send(run["initiator_id"] if not run["initiator_id"].startswith("ai:")
                else run["initiator_id"][3:],
                f"动作{'已批准' if approve else '被驳回'}:{run['action_name']}", comment,
                link=f"#/inbox?run={run_id}")
    if not approve:
        _run_on_reject(run, comment)
        out = get(run_id)
        _emit(out)
        return out
    return _execute(run_id)


def _run_on_reject(run: dict, reason: str) -> None:
    """驳回时要做的事(把驳回原因写回单据之类)。它们失败不影响驳回本身,只记进审计。"""
    done = []
    for i, e in enumerate(run["preview"].get("on_reject") or []):
        tool = registry.TOOLS.get(e["tool"])
        if tool is None:
            continue
        try:
            args = jload(jdump(e["args"]).replace("$reject_reason", jdump(reason)[1:-1]), e["args"])
            res = tool.run(args, {"run_id": run["id"], "index": 1000 + i})
            done.append({"tool": e["tool"], "ok": True, "label": e.get("label") or tool.title, "result": res})
        except Exception as ex:  # noqa: BLE001
            log.warning("驳回后的处理失败 run=%s:%s", run["id"], ex)
            done.append({"tool": e["tool"], "ok": False, "label": e.get("label") or tool.title,
                         "error": str(getattr(ex, "detail", ex))[:300]})
    if done:
        with session() as s:
            r = s.get(ActionRun, run["id"])
            r.result_json = jdump({"on_reject": done})
            s.commit()
        audit.record("action.effect", "action_run", run["id"], "驳回后已处理:" + "、".join(
            d["label"] + ("" if d["ok"] else "(失败)") for d in done), after={"on_reject": done})


def _execute(run_id: str) -> dict:
    run = get(run_id)
    return _execute_revert(run_id) if run["kind"] == "revert" else _execute_normal(run_id)


OBJECT_TOOLS = ("object.write", "object.create", "object.batch", "object.delete", "object.transition",
                "object.link", "object.unlink")


def _ops_of(e: dict) -> list[dict]:
    """一个改数据的效果 → 写入操作(合并进同一个事务用)。"""
    from .builtins import _write_values
    a = e["args"] or {}
    if e["tool"] == "object.batch":
        return list(a.get("ops") or [])
    if e["tool"] == "object.create":
        return [{"op": "create", "object_type": a["object_type"], "values": a.get("values") or {},
                 "as": e.get("as") or ""}]
    if e["tool"] == "object.delete":
        return [{"op": "delete", "object_type": a["object_type"], "key": str(a["key"]), "as": e.get("as") or ""}]
    if e["tool"] == "object.transition":
        return [{"op": "transition", "object_type": a["object_type"], "key": str(a["key"]),
                 "property": a["property"], "to": a["to"], "as": e.get("as") or ""}]
    if e["tool"] in ("object.link", "object.unlink"):
        return [{"op": e["tool"].split(".")[1], "link": a["link"], "from_key": str(a["from_key"]),
                 "to_key": str(a["to_key"]), "values": a.get("values") or {}}]
    return [{"op": "update", "object_type": a["object_type"], "key": str(a["key"]), "values": _write_values(a),
             "as": e.get("as") or ""}]


def _combined(run_id: str, effects: list[dict], done: int, action: dict) -> tuple[list[int], dict | None, str]:
    """动作里改数据的效果有好几项时,放进同一个事务一起执行:任何一项失败全部回滚,
    不会出现「主单建了、明细没建」的半截状态。跨数据源的放不进一个事务,退回逐项执行。
    返回 (这些效果的下标, 合并执行的结果, 错误)。"""
    idx = [i for i, e in enumerate(effects) if e["tool"] in OBJECT_TOOLS]
    if len(idx) < 2 or any(i < done for i in idx):
        return [], None, ""
    try:
        with objects.acting(action):
            return idx, objects.apply_ops([op for i in idx for op in _ops_of(effects[i])], action_run_id=run_id), ""
    except HTTPException as ex:
        if "同一个数据源" in str(ex.detail):
            return [], None, ""
        return idx, None, f"写入数据:{ex.detail}"


def _execute_normal(run_id: str, done_before: list[dict] | None = None) -> dict:
    """按批准时冻结的预览逐个执行效果。执行的是被审批过的那组参数,不重新渲染。
    done_before:重试时上次已成功的效果结果,这些效果不再重复执行。"""
    run = get(run_id)
    results = list(done_before or [])
    error = ""
    effects = run["preview"].get("effects") or []
    action = {"id": run["action_id"], "name": (run["preview"].get("action") or {}).get("name") or run["action_name"],
              "display_name": run["action_name"]}
    together, combined, cerr = _combined(run_id, effects, len(results), action)
    for i, e in enumerate(effects):
        if i < len(results):
            continue
        tool = registry.TOOLS.get(e["tool"])
        if tool is None:
            error = f"工具 {e['tool']} 已不存在"
            break
        if i in together:
            if cerr:
                error = cerr
                results.append({"tool": e["tool"], "ok": False, "error": error})
                break
            first = i == together[0]
            results.append({"tool": e["tool"], "ok": True, "result": combined if first else
                            {"summary": "(和上一项在同一个事务里写入)", "combined": True}})
            if first:
                audit.record("action.effect", "action_run", run_id, "写入数据(同一事务)", after=combined)
            continue
        try:
            with objects.acting(action):
                res = tool.run(e["args"], {"run_id": run_id, "index": i})
            results.append({"tool": e["tool"], "ok": True, "result": res})
            audit.record("action.effect", "action_run", run_id,
                         f"执行效果「{e.get('label') or tool.title}」", after=res)
        except HTTPException as ex:
            error = f"{e.get('label') or tool.title}:{ex.detail}"
        except Exception as ex:  # noqa: BLE001
            log.exception("动作效果执行失败 run=%s", run_id)
            error = f"{e.get('label') or tool.title}:{str(ex)[:300]}"
        if error:
            results.append({"tool": e["tool"], "ok": False, "error": error})
            break
    with session() as s:
        r = s.get(ActionRun, run_id)
        r.status = "failed" if error else "done"
        r.result_json = jdump({"effects": results})
        r.error = error
        r.finished_at = now()
        s.commit()
    audit.record("action.fail" if error else "action.done", "action_run", run_id,
                 f"动作「{run['action_name']}」{'执行失败:' + error if error else '执行完成'}",
                 after={"effects": results})
    out = get(run_id)
    _emit(out)
    return out


def retry(run_id: str) -> dict:
    """执行失败的动作重试:已经成功的效果不再重复,从失败的那一个接着执行。
    它已经批过了,所以发起人自己或有审批资格的人都可以点重试。"""
    actor = identity.current()
    run = get(run_id)
    if run["status"] != "failed" or run["kind"] == "revert":
        raise HTTPException(409, "只有执行失败的动作可以重试")
    if actor.id not in (run["initiator_id"], run["submitted_by"]):
        why = _can_approve(actor, run, run["preview"].get("action", {}).get("approver_roles") or [])
        if why:
            raise HTTPException(403, f"不能重试:{why}")
    ok = [e for e in (run["result"] or {}).get("effects") or [] if e.get("ok")]
    with session() as s:
        r = s.get(ActionRun, run_id)
        r.status, r.error, r.finished_at = "executing", "", None
        s.commit()
    audit.record("action.retry", "action_run", run_id,
                 f"重试动作「{run['action_name']}」(跳过已成功的 {len(ok)} 个效果)")
    return _execute_normal(run_id, ok)


def recover_stuck(minutes: int = 10) -> int:
    """服务重启时,把卡在「执行中」的动作标成失败(可重试)。执行在请求线程里同步进行,
    进程中途退出就会留下这种半截状态,以前它们永远停在执行中。"""
    import datetime as dt
    cutoff = now() - dt.timedelta(minutes=minutes)
    n = 0
    with session() as s:
        for r in s.scalars(select(ActionRun).where(ActionRun.status == "executing",
                                                  ActionRun.decided_at < cutoff)).all():
            r.status, r.error, r.finished_at = "failed", "服务中断,执行结果未知,可检查后重试", now()
            n += 1
        s.commit()
    if n:
        log.warning("把 %d 个卡在执行中的动作标为失败", n)
    return n


def cancel(run_id: str, reason: str = "") -> dict:
    actor = identity.current()
    run = get(run_id)
    if run["status"] != "pending_approval":
        raise HTTPException(409, "只能撤回待审批的动作")
    if not _can_cancel(actor, run):
        raise HTTPException(403, "只有发起人或管理员可以撤回")
    with session() as s:
        r = s.get(ActionRun, run_id)
        r.status = "cancelled"
        r.error = reason
        r.finished_at = now()
        for ap in s.scalars(select(ApprovalTask).where(ApprovalTask.run_id == run_id,
                                                       ApprovalTask.status == "pending")).all():
            ap.status = "cancelled"
        s.commit()
    audit.record("action.cancel", "action_run", run_id, f"撤回动作「{run['action_name']}」:{reason}")
    out = get(run_id)
    _emit(out)
    return out


# ---------------- 撤销 ----------------
def propose_revert(run_id: str, reason: str = "") -> dict:
    """撤销也是一次需要审批的动作:生成 kind=revert 的运行记录。"""
    actor = identity.current()
    run = get(run_id)
    if run["status"] != "done":
        raise HTTPException(409, "只有执行完成的动作可以撤销")
    if not run["preview"].get("action", {}).get("reversible"):
        raise HTTPException(409, "这个动作不可撤销(包含不可逆的效果,如外部调用或通知)")
    with session() as s:
        dup = s.scalars(select(ActionRun).where(ActionRun.revert_of == run_id,
                                                ActionRun.status.in_(("pending_approval", "done")))).first()
        if dup:
            raise HTTPException(409, "已有针对它的撤销申请")
        summary = "撤销:" + run["preview"].get("summary", "")
        rv = ActionRun(id=new_id("ar"), workspace=actor.workspace, action_id=run["action_id"],
                       action_name=f"撤销 · {run['action_name']}",
                       action_version=run["action_version"], kind="revert", revert_of=run_id,
                       params_json=jdump(run["params"]), target_ref=run["target_ref"],
                       initiator_kind="user", initiator_id=actor.id, submitted_by=actor.id,
                       reason=reason, status="pending_approval",
                       preview_json=jdump({**run["preview"], "summary": summary}),
                       idempotency_key=f"revert:{run_id}")
        s.add(rv)
        s.add(ApprovalTask(id=new_id("ap"), workspace=actor.workspace, run_id=rv.id,
                           approver_roles_json=jdump(run["preview"].get("action", {})
                                                     .get("approver_roles") or [])))
        s.commit()
        rid = rv.id
    audit.record("action.revert_propose", "action_run", rid, f"申请撤销「{run['action_name']}」:{reason}")
    return get(rid)


def _execute_revert(run_id: str) -> dict:
    rv = get(run_id)
    orig = get(rv["revert_of"])
    effects = orig["preview"].get("effects") or []
    results = (orig["result"] or {}).get("effects") or []
    error = ""
    for e, res in reversed(list(zip(effects, results))):
        tool = registry.TOOLS.get(e["tool"])
        if tool is None or tool.revert is None or not res.get("ok"):
            continue
        try:
            tool.revert(e["args"], res.get("result") or {})
        except Exception as ex:  # noqa: BLE001
            error = f"撤销「{e.get('label')}」失败:{getattr(ex, 'detail', str(ex))[:300]}"
            break
    with session() as s:
        r = s.get(ActionRun, run_id)
        r.status = "failed" if error else "done"
        r.error = error
        r.finished_at = now()
        if not error:
            o = s.get(ActionRun, rv["revert_of"])
            o.status = "reverted"
        s.commit()
    audit.record("action.reverted" if not error else "action.fail", "action_run", run_id,
                 error or f"已撤销「{orig['action_name']}」")
    return get(run_id)


def object_section(type_id: str, key: str) -> tuple[str, Any]:
    return "action_runs", list_runs(target_ref=f"object:{type_id}:{key}", limit=30)


def stats(actor: identity.Actor) -> dict:
    with session() as s:
        rows = s.execute(select(ActionRun.status, func.count(ActionRun.id))
                         .where(ActionRun.workspace == actor.workspace)
                         .group_by(ActionRun.status)).all()
    return {st: int(n) for st, n in rows}


def search(q: str, limit: int = 50) -> list[dict]:
    with session() as s:
        rows = s.scalars(select(ActionRun).where(
            ActionRun.workspace == identity.current().workspace,
            or_(ActionRun.action_name.like(f"%{q}%"), ActionRun.reason.like(f"%{q}%")))
            .order_by(ActionRun.created_at.desc()).limit(limit)).all()
        return [_dict(r) for r in rows]