service.py 51.3 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
"""本体内核的读写:概念、绑定、证据、发布与回滚、引用与血缘。

两份数据:
- **工作副本**(Concept 的各列 + Binding 表):建设台编辑的就是它;
- **已发布副本**(`published_json`):运行时唯一读取来源。发布时把工作副本冻结进去。
这样改到一半的指标口径不会影响正在被问的问题,发布前还能跑评测把关。
"""
from __future__ import annotations

import contextlib
import contextvars
import logging
import threading
import time
from typing import Any, Callable

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

from ..core import envs, identity
from ..core.dbx import iso, jdump, jload, new_id, now, session
from ..governance import audit
from . import schema
from .models import Binding, Concept, Evidence, Revision

log = logging.getLogger(__name__)


# ---------------- 序列化 ----------------
def _binding_dict(b: Binding) -> dict:
    return {"id": b.id, "concept_id": b.concept_id, "ds_id": b.ds_id,
            "target_kind": b.target_kind, "ref": jload(b.ref_json, {}),
            "updated_at": iso(b.updated_at)}


def _concept_dict(c: Concept, brief: bool = False) -> dict:
    spec = jload(c.spec_json, {})
    out = {"id": c.id, "kind": c.kind, "kind_label": schema.kind_label(c.kind, spec),
           "category": spec.get("category", "") if c.kind == "function" else "",
           "object_type": (spec.get("object_type") or spec.get("target_type") or "")
           if c.kind in ("function", "action") else "",
           "domain": spec.get("domain", ""),
           "name": c.name, "display_name": c.display_name or "",
           "description": c.description or "", "synonyms": jload(c.synonyms_json, []),
           "status": c.status, "dirty": bool(c.dirty),
           "version": c.version, "origin": c.origin, "published": bool(c.published_json),
           "created_by": c.created_by, "created_at": iso(c.created_at),
           "updated_at": iso(c.updated_at)}
    if c.kind == "object_type" and spec.get("abstract"):
        out["abstract"] = True
    if c.kind == "link_type":
        # 关系列表要显示「起点 → 终点」:放进摘要里,免得列表每一行再单独请求一次
        out["from_type"], out["to_type"] = spec.get("from_type", ""), spec.get("to_type", "")
        out["cardinality"] = spec.get("cardinality", "")
    if not brief:
        out["spec"] = spec
    return out


def _ws() -> str:
    return identity.current().workspace


# ---------------- 运行时视图(已发布) ----------------
_rt_cache: dict[str, tuple[float, dict[str, dict]]] = {}
_rt_lock = threading.Lock()
_RT_TTL = 30.0


# 预演(SOP 试运行、单步试跑、监控试扫描、动作预览、评测「待发布版本」)时,运行时改读工作副本(含草稿)。
# 值是这次预演自己的缓存 {workspace: {id: 概念}},None 表示正常模式;正式运行永远只认已发布的。
_draft_mode: contextvars.ContextVar[dict | None] = contextvars.ContextVar("onto_draft_mode", default=None)
# 预演范围:None = 全部工作副本;一组 id = 「上次发布的版本 + 只把这几个换成工作副本」(发布前体检用,
# 看到的正是「如果只发布选中的这些,运行时会是什么样」)。
_draft_only: contextvars.ContextVar[frozenset | None] = contextvars.ContextVar("onto_draft_only", default=None)
# 预演时再叠上一批「还不是概念」的元素(AI 建模的草案):试算计算属性、试跑指标 / 流程卡 / 监控用,
# 采纳之前就能看到它们在真实数据上的结果。形状和运行时概念一样(id、kind、name、spec、bindings…)。
_draft_extra: contextvars.ContextVar[tuple | None] = contextvars.ContextVar("onto_draft_extra", default=None)


@contextlib.contextmanager
def draft_runtime(only: list[str] | None = None, extra: list[dict] | None = None):
    if _draft_mode.get() is not None and only is None and extra is None:   # 已在预演里(如子流程):沿用同一份缓存
        yield
        return
    tok = _draft_mode.set({})
    tok_only = _draft_only.set(frozenset(only) if only is not None else None)
    tok_extra = _draft_extra.set(tuple(extra) if extra is not None else _draft_extra.get())
    try:
        yield
    finally:
        _draft_extra.reset(tok_extra)
        _draft_only.reset(tok_only)
        _draft_mode.reset(tok)


def in_draft_mode() -> bool:
    return _draft_mode.get() is not None


def invalidate_runtime() -> None:
    with _rt_lock:
        _rt_cache.clear()


def runtime(workspace: str | None = None) -> dict[str, dict]:
    """已发布、未废弃的概念:id → 概念 dict(含 spec 与 bindings)。"""
    ws = workspace or _ws()
    draft_cache = _draft_mode.get()
    if draft_cache is not None:
        if ws not in draft_cache:
            only = _draft_only.get()
            with session() as s:
                out = {}
                stmt = select(Concept).where(Concept.workspace == ws)
                if only is not None:
                    out = dict(_published(s, ws))
                    stmt = stmt.where(Concept.id.in_(only))
                for c in s.scalars(stmt).all():
                    if c.status == "deprecated":
                        out.pop(c.id, None)
                        continue
                    try:
                        out[c.id] = _publish_copy(s, c)
                    except Exception:                       # noqa: BLE001  坏草稿不拖垮整次预演
                        log.warning("预演时读取草稿 %s 失败", c.id, exc_info=True)
                for c in _draft_extra.get() or ():
                    # 同名的已有元素让位给草案(草案是这次要改成的样子)
                    for k in [k for k, v in out.items() if v["kind"] == c["kind"] and v["name"] == c["name"]]:
                        out.pop(k)
                    out[c["id"]] = c
                draft_cache[ws] = _with_system(out)
        return draft_cache[ws]
    with _rt_lock:
        hit = _rt_cache.get(f"{envs.current()}:{ws}")
        if hit and time.time() - hit[0] < _RT_TTL:
            return hit[1]
    with session() as s:
        out = _with_system(_published(s, ws))
    with _rt_lock:
        _rt_cache[f"{envs.current()}:{ws}"] = (time.time(), out)
    return out


def _with_system(out: dict[str, dict]) -> dict[str, dict]:
    """每个本体空间都有的系统元素(预警事件 / 动作记录 / 流程运行 + 效果指标)。用户自己的同名元素优先。"""
    from . import sysobjects
    try:
        extra = sysobjects.concepts()
    except Exception:  # noqa: BLE001  系统元素出问题不能拖垮整个运行时
        log.warning("加载系统对象失败", exc_info=True)
        return out
    names = {(c["kind"], c["name"]) for c in out.values()}
    for c in extra:
        if (c["kind"], c["name"]) not in names:
            out.setdefault(c["id"], c)
    return out


def _published(s, ws: str) -> dict[str, dict]:
    out = {}
    for c in s.scalars(select(Concept).where(
            Concept.workspace == ws, Concept.status == "published",
            Concept.published_json != "")).all():
        d = jload(c.published_json, None)
        if isinstance(d, dict):
            out[c.id] = d
    return out


def rt_get(cid: str) -> dict | None:
    return runtime().get(cid)


def _match_kind(c: dict, kind: str | None, category: str | None) -> bool:
    if kind and c["kind"] != kind:
        return False
    if category and (c.get("spec") or {}).get("category") != category:
        return False
    return True


def rt_find(name: str, kind: str | None = None, category: str | None = None) -> dict | None:
    """按名称 / 显示名 / 同义词在已发布概念里找。也接受直接传 id。

    函数再按 category 细分:rt_find("销售额", "function", "aggregate"),简写 rt_fn(name, category)。
    """
    if not name:
        return None
    rt = runtime()
    if name in rt and _match_kind(rt[name], kind, category):
        return rt[name]
    n = str(name).strip().lower()
    for c in rt.values():
        if not _match_kind(c, kind, category):
            continue
        names = [c["name"], c.get("display_name") or ""] + list(c.get("synonyms") or [])
        if any(n == x.strip().lower() for x in names if x):
            return c
    return None


def rt_fn(name: str, category: str) -> dict | None:
    return rt_find(name, "function", category)


def rt_by_kind(kind: str, category: str | None = None) -> list[dict]:
    return [c for c in runtime().values() if _match_kind(c, kind, category)]


def rt_binding(concept: dict, target_kind: str, ds_id: int | None = None) -> dict | None:
    for b in concept.get("bindings") or []:
        if b["target_kind"] == target_kind and (ds_id is None or b["ds_id"] == ds_id):
            return b
    return None


# ---------------- 查询 ----------------
def list_concepts(kind: str = "", status: str = "", q: str = "", limit: int = 1000) -> list[dict]:
    with session() as s:
        stmt = select(Concept).where(Concept.workspace == _ws())
        if kind:
            stmt = stmt.where(Concept.kind == kind)
        if status == "dirty":
            stmt = stmt.where(Concept.dirty == 1)
        elif status:
            stmt = stmt.where(Concept.status == status)
        else:
            stmt = stmt.where(Concept.status != "deprecated")
        if q:
            like = f"%{q}%"
            stmt = stmt.where(or_(Concept.name.like(like), Concept.display_name.like(like),
                                  Concept.synonyms_json.like(like), Concept.description.like(like)))
        rows = s.scalars(stmt.order_by(Concept.kind, Concept.name).limit(limit)).all()
        bound: dict[str, set[str]] = {}
        for cid, tk in s.execute(select(Binding.concept_id, Binding.target_kind).where(
                Binding.workspace == _ws())).all():
            bound.setdefault(cid, set()).add(tk)
        out = []
        for c in rows:
            d = _concept_dict(c, brief=True)
            d["mapped"] = is_mapped(d, bound.get(c.id, set()))
            out.append(d)
        return out


def list_full(kind: str = "", limit: int = 2000) -> list[dict]:
    """工作副本里的元素连同定义和绑定一次读出来(两条查询)。本体图、一键补全这类要看全量的地方用它,
    不要对每个元素调一次 get_concept。"""
    with session() as s:
        stmt = select(Concept).where(Concept.workspace == _ws(), Concept.status != "deprecated")
        if kind:
            stmt = stmt.where(Concept.kind == kind)
        rows = s.scalars(stmt.order_by(Concept.kind, Concept.name).limit(limit)).all()
        binds: dict[str, list[dict]] = {}
        for b in s.scalars(select(Binding).where(Binding.workspace == _ws())).all():
            binds.setdefault(b.concept_id, []).append(_binding_dict(b))
        out = []
        for c in rows:
            d = _concept_dict(c)
            d["bindings"] = binds.get(c.id, [])
            out.append(d)
        return out


def is_mapped(c: dict, target_kinds: set[str]) -> bool | None:
    """这个元素是否已落到真实数据。不需要绑定的元素(规则、决策表、动作……)返回 None。"""
    if c["kind"] == "object_type":
        if c.get("abstract"):
            return None                       # 接口没有自己的数据来源,数据来自实现它的对象
        return "table" in target_kinds
    if c["kind"] == "link_type":
        return "join" in target_kinds
    if c["kind"] == "function" and c.get("category") == "aggregate":
        return "metric_expr" in target_kinds
    return None


def stats() -> dict:
    with session() as s:
        rows = s.execute(select(Concept.kind, Concept.status, func.count(Concept.id))
                         .where(Concept.workspace == _ws())
                         .group_by(Concept.kind, Concept.status)).all()
        dirty = s.scalar(select(func.count(Concept.id)).where(
            Concept.workspace == _ws(), Concept.dirty == 1)) or 0
        rev = s.scalar(select(func.max(Revision.revision)).where(Revision.workspace == _ws())) or 0
    by_kind: dict[str, dict] = {}
    for k, st, n in rows:
        by_kind.setdefault(k, {"total": 0})
        by_kind[k][st] = int(n)
        if st != "deprecated":
            by_kind[k]["total"] += int(n)
    by_cat: dict[str, int] = {}
    with session() as s:
        for (sj,) in s.execute(select(Concept.spec_json).where(
                Concept.workspace == _ws(), Concept.kind == "function",
                Concept.status != "deprecated")).all():
            cat = jload(sj, {}).get("category") or "rule"
            by_cat[cat] = by_cat.get(cat, 0) + 1
    return {"by_kind": by_kind, "by_category": by_cat, "dirty": int(dirty), "revision": int(rev),
            "kinds": [{"kind": k, **v} for k, v in schema.KINDS.items()],
            "categories": [{"category": k, **v} for k, v in schema.FN_CATEGORIES.items()]}


def _load(s, cid: str) -> Concept:
    c = s.get(Concept, cid)
    if c is None or c.workspace != _ws():
        raise HTTPException(404, "概念不存在")
    return c


def get_concept(cid: str) -> dict:
    with session() as s:
        c = _load(s, cid)
        out = _concept_dict(c)
        out["bindings"] = [_binding_dict(b) for b in s.scalars(
            select(Binding).where(Binding.concept_id == cid)).all()]
        out["evidence"] = [{"id": e.id, "doc_id": e.doc_id, "chunk_id": e.chunk_id,
                            "heading": e.heading, "snippet": e.snippet,
                            "graph_entity_id": e.graph_entity_id}
                           for e in s.scalars(select(Evidence).where(
                               Evidence.concept_id == cid).order_by(Evidence.id)).all()]
        out["published_copy"] = jload(c.published_json, None)
    return out


def find(name: str, kind: str | None = None) -> dict | None:
    """在工作副本里按名称 / 同义词找(建设期用;运行时请用 rt_find)。"""
    n = (name or "").strip()
    if not n:
        return None
    with session() as s:
        stmt = select(Concept).where(Concept.workspace == _ws(), Concept.status != "deprecated")
        if kind:
            stmt = stmt.where(Concept.kind == kind)
        exact = s.scalars(stmt.where(or_(Concept.id == n, Concept.name == n,
                                         Concept.display_name == n))).first()
        if exact:
            return _concept_dict(exact)
        for c in s.scalars(stmt.where(Concept.synonyms_json.like(f"%{n}%"))).all():
            if n in jload(c.synonyms_json, []):
                return _concept_dict(c)
    return None


# ---------------- 写入 ----------------
def _clean_synonyms(v: Any, name: str) -> list[str]:
    items = schema._list_str(v)
    out: list[str] = []
    for x in items:
        if x != name and x not in out:
            out.append(x)
    return out[:50]


def create_concept(kind: str, name: str, *, display_name: str = "", description: str = "",
                   synonyms: Any = None, spec: dict | None = None,
                   origin: str = "user", evidence: list[dict] | None = None,
                   bindings: list[dict] | None = None) -> dict:
    name = (name or "").strip()
    if not name:
        raise HTTPException(422, "名称不能为空")
    up = schema.element_kind(kind, spec)             # kind 写成函数类别简写(metric / rule …)也认
    if up is None:
        raise HTTPException(422, f"「{kind}」不是本体元素(只有{'、'.join(v['label'] for v in schema.KINDS.values())}):"
                                 f"角色请在「成员与角色」维护,流程请建流程卡,术语写成同义词")
    kind, spec = up
    try:
        spec = schema.normalize_spec(kind, spec)
    except schema.SpecError as e:
        raise HTTPException(422, str(e)) from e
    if find(name, kind):
        raise HTTPException(409, f"已存在同名的{schema.KINDS[kind]['label']}「{name}」")
    if kind != "function" or spec.get("category") != "aggregate":
        bindings = [b for b in bindings or []
                    if (b.get("target_kind") or schema.BINDING_KINDS.get(kind)) != "metric_expr"]
    actor = identity.current()
    cid = new_id(kind[:3])
    with session() as s:
        c = Concept(id=cid, workspace=actor.workspace, kind=kind, name=name[:255],
                    display_name=(display_name or "")[:255], description=description or "",
                    synonyms_json=jdump(_clean_synonyms(synonyms, name)),
                    spec_json=jdump(spec), status="draft",
                    dirty=1, origin=origin, created_by=actor.id)
        s.add(c)
        s.commit()
    for b in bindings or []:
        set_binding(cid, int(b.get("ds_id") or 0), b.get("target_kind") or
                    schema.BINDING_KINDS.get(kind, ""), b.get("ref") or {}, _audit=False)
    if evidence:
        add_evidence(cid, evidence)
    out = get_concept(cid)
    audit.record("concept.create", "concept", cid, f"新建{out['kind_label']}「{name}」",
                 after=out)
    return out


def update_concept(cid: str, **fields: Any) -> dict:
    before = get_concept(cid)
    with session() as s:
        c = _load(s, cid)
        if "name" in fields and fields["name"] is not None:
            nm = str(fields["name"]).strip()
            if not nm:
                raise HTTPException(422, "概念名称不能为空")
            other = find(nm, c.kind)
            if other and other["id"] != cid:
                raise HTTPException(409, f"已存在同名概念「{nm}」")
            c.name = nm[:255]
        for key in ("display_name", "description"):
            if key in fields and fields[key] is not None:
                setattr(c, key, str(fields[key]))
        if "synonyms" in fields and fields["synonyms"] is not None:
            c.synonyms_json = jdump(_clean_synonyms(fields["synonyms"], c.name))
        if "spec" in fields and fields["spec"] is not None:
            new_spec = dict(fields["spec"])
            old_ui = jload(c.spec_json, {}).get("ui")
            if old_ui and "ui" not in new_spec:
                new_spec["ui"] = old_ui           # 表单编辑不带画布位置,别把它冲掉
            try:
                c.spec_json = jdump(schema.normalize_spec(c.kind, new_spec))
            except schema.SpecError as e:
                raise HTTPException(422, str(e)) from e
        c.version += 1
        c.dirty = 1
        if c.status == "deprecated" and fields.get("restore"):
            c.status = "draft"
        _settle(s, c)
        s.commit()
    if before["kind"] == "object_type" and fields.get("spec") is not None:
        _refresh_managed(cid)
    after = get_concept(cid)
    audit.record("concept.update", "concept", cid, f"修改{after['kind_label']}「{after['name']}」",
                 before=before, after=after)
    return after


def _refresh_managed(cid: str) -> None:
    """本体自建对象改了属性:存储表的列跟着属性走(发布时补列)。"""
    from . import storage
    with session() as s:
        c = s.get(Concept, cid)
        for b in s.scalars(select(Binding).where(Binding.concept_id == cid, Binding.target_kind == "table")).all():
            ref = jload(b.ref_json, {})
            if ref.get("kind") == "managed":
                b.ref_json = jdump(schema.normalize_binding("table", storage.managed_ref(cid, jload(c.spec_json, {}), ref)))
                _settle(s, c)
        s.commit()


def save_layout(positions: dict[str, dict]) -> int:
    """画布拖动后的位置。纯展示信息:不算修改、不进发布、不写审计。"""
    n = 0
    with session() as s:
        for cid, pos in (positions or {}).items():
            c = s.get(Concept, cid)
            if c is None or c.workspace != _ws() or not isinstance(pos, dict):
                continue
            spec = jload(c.spec_json, {})
            try:
                spec["ui"] = {"pos": {"x": float(pos.get("x") or 0), "y": float(pos.get("y") or 0)}}
            except (TypeError, ValueError):
                continue
            c.spec_json = jdump(spec)
            n += 1
        s.commit()
    return n


def deprecate_concept(cid: str, reason: str = "", force: bool = False) -> dict:
    """废弃一个元素。被别的元素或流程卡引用时默认拦住 —— 以前不拦,废弃「商品」不会有
    任何提示,但「库存→记录→商品」这条关系和「库存缺口」这个指标当场就哑了。"""
    before = get_concept(cid)
    if not force:
        refs = usage(cid)
        if refs:
            names = "、".join(f"「{r['name']}」" for r in refs[:5])
            raise HTTPException(409, f"「{before['name']}」还被 {len(refs)} 处引用({names}"
                                     f"{' 等' if len(refs) > 5 else ''}),"
                                     "确认要废弃就勾选「仍然废弃」,否则先改掉这些引用")
    with session() as s:
        c = _load(s, cid)
        c.status = "deprecated"
        c.dirty = 1
        s.commit()
    invalidate_runtime()
    audit.record("concept.deprecate", "concept", cid,
                 f"废弃「{before['name']}」" + (f":{reason}" if reason else ""), before=before)
    return get_concept(cid)


def delete_concept(cid: str) -> None:
    with session() as s:
        c = _load(s, cid)
        if c.published_json:
            raise HTTPException(409, "已发布过的概念不能删除,只能废弃(保证历史答案仍可追溯)")
        snap = _concept_dict(c)
        s.execute(delete(Binding).where(Binding.concept_id == cid))
        s.execute(delete(Evidence).where(Evidence.concept_id == cid))
        s.delete(c)
        s.commit()
    audit.record("concept.delete", "concept", cid, f"删除草稿「{snap['name']}」", before=snap)


def _touch(cid: str) -> None:
    with session() as s:
        c = s.get(Concept, cid)
        if c is not None:
            c.dirty = 1
            c.version += 1
            _settle(s, c)
            s.commit()


def _settle(s, c: Concept) -> None:
    """保存后内容其实和线上一样(打开看了一眼点了保存、或改完又改回去):不算「有未发布的修改」。
    以前这种情况会一直挂着「有未发布的修改」,而发布页又说没有可发布的变更,流程卡还因此发布不了。"""
    if c.status != "published" or not c.published_json:
        return
    s.flush()
    prev = jload(c.published_json, {})
    cur = _publish_copy(s, c)

    def binds(d: dict) -> list:
        return sorted(([b.get("ds_id"), b.get("target_kind"), b.get("ref")] for b in d.get("bindings") or []),
                      key=lambda x: jdump(x))
    same = all(jdump(_cmp(prev.get(f), f)) == jdump(_cmp(cur.get(f), f))
               for f in ("name", "display_name", "description", "synonyms", "spec"))
    if same and jdump(binds(prev)) == jdump(binds(cur)):
        c.dirty = 0


# ---------------- 绑定 ----------------
def list_bindings(cid: str) -> list[dict]:
    with session() as s:
        return [_binding_dict(b) for b in s.scalars(
            select(Binding).where(Binding.concept_id == cid)).all()]


def set_binding(cid: str, ds_id: int, target_kind: str, ref: dict, _audit: bool = True) -> dict:
    if target_kind == "table" and (ref or {}).get("kind") == "managed":
        # 本体自建:表名、列都由系统按属性定,数据源是「本体存储」
        from . import storage
        with session() as s:
            spec = jload(_load(s, cid).spec_json, {})
        ref = storage.managed_ref(cid, spec, ref)
        ds_id = storage.datasource_id()
        with session() as s:              # 一个对象只能有一个数据来源:换成本体自建时清掉原来的表绑定
            s.execute(delete(Binding).where(Binding.concept_id == cid, Binding.target_kind == "table",
                                            Binding.ds_id != ds_id))
            s.commit()
    try:
        ref = schema.normalize_binding(target_kind, ref)
    except schema.SpecError as e:
        raise HTTPException(422, str(e)) from e
    with session() as s:
        _load(s, cid)
        b = s.scalars(select(Binding).where(Binding.concept_id == cid, Binding.ds_id == ds_id,
                                            Binding.target_kind == target_kind)).first()
        before = _binding_dict(b) if b else None
        if b is None:
            b = Binding(id=new_id("bd"), workspace=_ws(), concept_id=cid, ds_id=ds_id,
                        target_kind=target_kind)
            s.add(b)
        b.ref_json = jdump(ref)
        s.commit()
        out = _binding_dict(b)
    _touch(cid)
    if _audit:
        audit.record("binding.set", "concept", cid, f"设置数据绑定(数据源 {ds_id})",
                     before=before, after=out)
    return out


def delete_binding(binding_id: str) -> None:
    with session() as s:
        b = s.get(Binding, binding_id)
        if b is None:
            raise HTTPException(404, "绑定不存在")
        snap, cid = _binding_dict(b), b.concept_id
        s.delete(b)
        s.commit()
    _touch(cid)
    audit.record("binding.delete", "concept", cid, "删除数据绑定", before=snap)


# ---------------- 证据 ----------------
def add_evidence(cid: str, items: list[dict]) -> int:
    n = 0
    with session() as s:
        have = {(e.chunk_id, e.graph_entity_id) for e in s.scalars(
            select(Evidence).where(Evidence.concept_id == cid)).all()}
        for it in items or []:
            key = (str(it.get("chunk_id") or ""), str(it.get("graph_entity_id") or ""))
            if key in have or key == ("", ""):
                continue
            have.add(key)
            s.add(Evidence(workspace=_ws(), concept_id=cid, doc_id=int(it.get("doc_id") or 0),
                           chunk_id=key[0], heading=str(it.get("heading") or "")[:500],
                           snippet=str(it.get("snippet") or "")[:2000], graph_entity_id=key[1]))
            n += 1
        s.commit()
    return n


def evidence_for(cids: list[str]) -> dict[str, list[dict]]:
    if not cids:
        return {}
    with session() as s:
        out: dict[str, list[dict]] = {}
        for e in s.scalars(select(Evidence).where(Evidence.concept_id.in_(cids))).all():
            out.setdefault(e.concept_id, []).append(
                {"doc_id": e.doc_id, "chunk_id": e.chunk_id, "heading": e.heading,
                 "snippet": e.snippet})
        return out


# ---------------- 发布 / 回滚 ----------------
# 发布闸门:fn(diff, concept_ids) -> (ok, message),concept_ids 为 None 表示发布全部改动。
# 评测模块会注册一个「回归不能掉点」的闸门。
_gates: list[Callable[[dict, list[str] | None], tuple[bool, str]]] = []
# 发布监听:新版本生效后通知运行时各部分刷新(链接器、MCP 目录……)。进程内事件,不需要消息队列。
_listeners: list[Callable[[int], None]] = []


def register_publish_gate(fn: Callable[[dict, list[str] | None], tuple[bool, str]]) -> None:
    _gates.append(fn)


def on_publish(fn: Callable[[int], None]) -> None:
    _listeners.append(fn)


def _released(revision: int) -> None:
    invalidate_runtime()
    for fn in _listeners:
        try:
            fn(revision)
        except Exception:  # noqa: BLE001
            log.exception("发布监听处理失败")


def _publish_copy(s, c: Concept) -> dict:
    d = _concept_dict(c)
    d["bindings"] = [_binding_dict(b) for b in s.scalars(
        select(Binding).where(Binding.concept_id == c.id)).all()]
    d.pop("published", None)
    d.pop("dirty", None)
    return d


def _last_snapshot(s) -> tuple[int, dict]:
    r = s.scalars(select(Revision).where(Revision.workspace == _ws())
                  .order_by(Revision.revision.desc())).first()
    return (r.revision, jload(r.snapshot_json, {})) if r else (0, {})


def _diff(prev: dict, cur: dict) -> dict:
    added = [{"id": k, "name": v["name"], "kind": v["kind"]} for k, v in cur.items() if k not in prev]
    removed = [{"id": k, "name": v["name"], "kind": v["kind"]} for k, v in prev.items() if k not in cur]
    changed = []
    for k, v in cur.items():
        if k in prev:
            fields = [f for f in ("name", "display_name", "description", "synonyms", "spec", "bindings")
                      if jdump(_cmp(prev[k].get(f), f)) != jdump(_cmp(v.get(f), f))]
            if fields:
                changed.append({"id": k, "name": v["name"], "kind": v["kind"], "fields": fields})
    return {"added": added, "removed": removed, "changed": changed}


def _cmp(v: Any, field: str) -> Any:
    if field == "spec" and isinstance(v, dict) and "ui" in v:
        return {k: x for k, x in v.items() if k != "ui"}
    return v


def _field_changes(a: dict, b: dict) -> list[dict]:
    """两份概念快照之间逐字段的前后值(给版本对比页看)。"""
    out = []
    for f in ("name", "display_name", "description", "synonyms"):
        if jdump(a.get(f)) != jdump(b.get(f)):
            out.append({"field": f, "before": a.get(f), "after": b.get(f)})
    sa, sb = _cmp(a.get("spec") or {}, "spec"), _cmp(b.get("spec") or {}, "spec")
    for k in sorted(set(sa) | set(sb)):
        if jdump(sa.get(k)) != jdump(sb.get(k)):
            out.append({"field": f"spec.{k}", "before": sa.get(k), "after": sb.get(k)})

    def _bind(c: dict) -> list[dict]:
        return [{"ds_id": x.get("ds_id"), "target_kind": x.get("target_kind"), "ref": x.get("ref")}
                for x in c.get("bindings") or []]
    if jdump(_bind(a)) != jdump(_bind(b)):
        out.append({"field": "bindings", "before": _bind(a), "after": _bind(b)})
    return out


def compare_revisions(rev_from: int, rev_to: int) -> dict:
    """任意两个版本之间的差异(rev=0 表示空本体),含每个修改概念的逐字段前后值。"""
    a = get_revision(rev_from)["snapshot"] if rev_from else {}
    b = get_revision(rev_to)["snapshot"] if rev_to else {}
    d = _diff(a, b)
    names = {k: v["name"] for k, v in {**a, **b}.items()}

    def readable(v: Any) -> Any:           # 引用别的元素时显示名称而不是 id
        if isinstance(v, str) and v in names:
            return names[v]
        if isinstance(v, list):
            return [readable(x) for x in v]
        return v
    for ch in d["changed"]:
        ch["changes"] = [{**x, "before": readable(x["before"]), "after": readable(x["after"])}
                         for x in _field_changes(a[ch["id"]], b[ch["id"]])]
    for x in d["added"]:
        x["type_key"] = schema.type_key(b[x["id"]])
    for x in d["removed"]:
        x["type_key"] = schema.type_key(a[x["id"]])
    return {"from": rev_from, "to": rev_to, **d}


def pending_diff(concept_ids: list[str] | None = None) -> dict:
    """如果现在发布,会变什么。concept_ids 给了就只看选中的这些。"""
    with session() as s:
        _, prev = _last_snapshot(s)
        cur = dict(prev)
        stmt = select(Concept).where(Concept.workspace == _ws(), Concept.dirty == 1)
        if concept_ids is not None:
            stmt = stmt.where(Concept.id.in_(concept_ids))
        for c in s.scalars(stmt).all():
            if c.status == "deprecated":
                cur.pop(c.id, None)
            else:
                cur[c.id] = _publish_copy(s, c)
    return _diff(prev, cur)


def publish(note: str = "", concept_ids: list[str] | None = None, force: bool = False) -> dict:
    actor = identity.current()
    diff = pending_diff(concept_ids or None)
    if not (diff["added"] or diff["removed"] or diff["changed"]):
        raise HTTPException(409, "没有待发布的变更")
    if not force:
        for gate in _gates:
            ok, msg = gate(diff, concept_ids or None)
            if not ok:
                raise HTTPException(412, f"发布被闸门拦下:{msg}")
    with session() as s:
        rev, prev = _last_snapshot(s)
        stmt = select(Concept).where(Concept.workspace == actor.workspace, Concept.dirty == 1)
        if concept_ids:
            stmt = stmt.where(Concept.id.in_(concept_ids))
        snapshot = dict(prev)
        for c in s.scalars(stmt).all():
            if c.status == "deprecated":
                snapshot.pop(c.id, None)
                c.published_json = ""
            else:
                copy = _publish_copy(s, c)
                copy["status"] = "published"
                c.status = "published"
                c.published_json = jdump(copy)
                snapshot[c.id] = copy
            c.dirty = 0
        real_diff = _diff(prev, snapshot)
        r = Revision(workspace=actor.workspace, revision=rev + 1, note=note or "",
                     snapshot_json=jdump(snapshot), diff_json=jdump(real_diff),
                     published_by=actor.id)
        s.add(r)
        s.commit()
        out = {"revision": r.revision, "note": r.note, "diff": real_diff,
               "concepts": len(snapshot)}
    _released(out["revision"])
    audit.record("ontology.publish", "revision", str(out["revision"]),
                 f"发布本体第 {out['revision']} 版:新增 {len(real_diff['added'])},"
                 f"修改 {len(real_diff['changed'])},移除 {len(real_diff['removed'])}"
                 + (f"({note})" if note else ""), after=real_diff)
    return out


def list_revisions() -> list[dict]:
    with session() as s:
        rows = s.scalars(select(Revision).where(Revision.workspace == _ws())
                         .order_by(Revision.revision.desc())).all()
        return [{"revision": r.revision, "note": r.note, "diff": jload(r.diff_json, {}),
                 "published_by": r.published_by, "created_at": iso(r.created_at),
                 "concepts": len(jload(r.snapshot_json, {}))} for r in rows]


def get_revision(rev: int) -> dict:
    with session() as s:
        r = s.scalars(select(Revision).where(Revision.workspace == _ws(),
                                             Revision.revision == rev)).first()
        if r is None:
            raise HTTPException(404, "版本不存在")
        return {"revision": r.revision, "note": r.note, "snapshot": jload(r.snapshot_json, {}),
                "diff": jload(r.diff_json, {}), "published_by": r.published_by,
                "created_at": iso(r.created_at)}


def rollback(rev: int) -> dict:
    """回滚到某个版本:工作副本与发布副本都恢复成那一版,然后记为一个新版本。"""
    target = get_revision(rev)["snapshot"]
    actor = identity.current()
    with session() as s:
        cur_rev, prev = _last_snapshot(s)
        for cid, d in target.items():
            c = s.get(Concept, cid)
            if c is None:
                c = Concept(id=cid, workspace=actor.workspace, kind=d["kind"],
                            origin=d.get("origin") or "user", created_by=actor.id)
                s.add(c)
            c.name = d["name"]
            c.display_name = d.get("display_name") or ""
            c.description = d.get("description") or ""
            c.synonyms_json = jdump(d.get("synonyms") or [])
            c.spec_json = jdump(d.get("spec") or {})
            c.status = "published"
            c.dirty = 0
            c.version = (c.version or 0) + 1
            c.published_json = jdump(d)
            s.execute(delete(Binding).where(Binding.concept_id == cid))
            for b in d.get("bindings") or []:
                s.add(Binding(id=b.get("id") or new_id("bd"), workspace=actor.workspace,
                              concept_id=cid, ds_id=int(b.get("ds_id") or 0),
                              target_kind=b["target_kind"], ref_json=jdump(b.get("ref") or {})))
        for cid in set(prev) - set(target):
            c = s.get(Concept, cid)
            if c is not None:
                c.status = "deprecated"
                c.published_json = ""
                c.dirty = 0
        diff = _diff(prev, target)
        r = Revision(workspace=actor.workspace, revision=cur_rev + 1,
                     note=f"回滚到第 {rev} 版", snapshot_json=jdump(target),
                     diff_json=jdump(diff), published_by=actor.id)
        s.add(r)
        s.commit()
        new_rev = r.revision
    _released(new_rev)
    audit.record("ontology.rollback", "revision", str(new_rev), f"回滚到第 {rev} 版", after=diff)
    return {"revision": new_rev, "diff": diff}


# ---------------- 选择发布 ----------------
def _strings(v: Any) -> set[str]:
    """spec / 绑定里出现过的所有字符串(引用别的元素时写的是 id 或名称)。"""
    if isinstance(v, str):
        return {v}
    if isinstance(v, dict):
        return set().union(*(_strings(x) for x in v.values())) if v else set()
    if isinstance(v, (list, tuple)):
        return set().union(*(_strings(x) for x in v)) if v else set()
    return set()


def _refs_of(copy: dict) -> set[str]:
    return _strings(copy.get("spec")) | _strings([b.get("ref") for b in copy.get("bindings") or []])


def release_scope(concept_ids: list[str] | None) -> dict:
    """这次发布实际会带上哪些元素:选中的 + 它们引用到的、还从没发布过的元素(不带上就会引用悬空)。

    返回 {ids, auto: [{id, name, kind, because}], blocked: [{id, name, used_by}]};
    blocked 是「要移除、但仍被不在本次移除范围里的线上元素引用」的 —— 发出去就会留下悬空引用。
    concept_ids 为 None 表示发布全部改动。
    """
    with session() as s:
        dirty = {c.id: c for c in s.scalars(select(Concept).where(
            Concept.workspace == _ws(), Concept.dirty == 1)).all()}
        copies = {cid: _publish_copy(s, c) for cid, c in dirty.items() if c.status != "deprecated"}
        meta = {cid: {"name": c.name, "kind": c.kind, "removed": c.status == "deprecated"}
                for cid, c in dirty.items()}
        _, published = _last_snapshot(s)          # 线上版本(要移除的元素此刻还在里面)
    chosen = list(dirty) if concept_ids is None else [i for i in dict.fromkeys(concept_ids) if i in dirty]
    # 从没发布过的草稿:按 id 或名称被引用到就要一起发
    fresh = {cid for cid in copies if cid not in published}
    by_name = {meta[cid]["name"]: cid for cid in fresh}
    auto: list[dict] = []
    seen, queue = set(chosen), list(chosen)
    while queue:
        copy = copies.get(queue.pop())
        if copy is None:
            continue
        for r in sorted(_refs_of(copy)):
            dep = r if r in fresh else by_name.get(r)
            if dep and dep not in seen:
                seen.add(dep)
                queue.append(dep)
                auto.append({"id": dep, "name": meta[dep]["name"], "kind": meta[dep]["kind"],
                             "because": copy["name"]})
    ids = chosen + [a["id"] for a in auto]
    # 反向:要移除的元素还被谁用着
    blocked = []
    removing = {cid for cid in ids if meta[cid]["removed"] and cid in published}
    for cid in sorted(removing):
        gone = published[cid]
        users = []
        for oid, other in published.items():
            if oid in removing:
                continue
            cur = copies.get(oid) if oid in ids else other        # 这次一起发的看新版,否则看线上版
            if cur and (cid in _refs_of(cur) or gone["name"] in _refs_of(cur)):
                users.append(cur["name"])
        if users:
            blocked.append({"id": cid, "name": gone["name"], "used_by": sorted(users)})
    return {"ids": ids, "auto": auto, "blocked": blocked}


def governed_publish(note: str = "", concept_ids: list[str] | None = None) -> dict:
    """受治理的发布(审批通过、立即发布都走这里):依赖闭包 → 体检闸 → 评测闸 → 发布。
    `publish()` 本身不过体检,留给模板导入、种子脚本和测试直接用。"""
    from . import health
    if concept_ids is not None and not concept_ids:
        raise HTTPException(422, "没有选中任何要发布的元素")
    scope = release_scope(concept_ids)
    if not scope["ids"]:
        raise HTTPException(409, "没有待发布的变更")
    if scope["blocked"]:
        raise HTTPException(412, "这些元素还在被线上的其他元素使用,不能移除:"
                            + ";".join(f"「{b['name']}」被 {'、'.join(b['used_by'][:5])} 使用"
                                       for b in scope["blocked"]))
    report = health.check(scope["ids"])
    if report["errors"]:
        raise HTTPException(412, f"体检发现 {len(report['errors'])} 处会在运行时出错的问题,修好再发布:"
                            + ";".join(f"「{e['name']}」{e['message']}" for e in report["errors"][:5])
                            + ("……" if len(report["errors"]) > 5 else ""))
    out = publish(note, scope["ids"])
    out["auto_included"] = scope["auto"]
    out["warnings"] = report["warnings"]
    return out


def publish_now(note: str = "", concept_ids: list[str] | None = None) -> dict:
    """立即发布:有资格自己批的人(管理员 / 开了单人自审)一步完成,不先建提案 ——
    以前是「建提案 → 批准」,中途被闸门拦下就留下一份卡死的提案,之后谁也提交不了。"""
    actor = identity.current()
    why = can_decide_release(actor, {"created_by": actor.id})
    if why:
        raise HTTPException(403, why)
    if _pending_release():
        raise HTTPException(409, "已有一份待审批的变更提案,请先处理它(或撤回)再发布")
    return governed_publish(note, concept_ids)


def rollback_preview(rev: int) -> dict:
    """回滚到这一版会顺带冲掉哪些还没发布的修改:
    overwritten = 改过、且这一版里也有的元素(工作副本会被这一版覆盖);
    lost = 改过、但这一版里没有的线上元素(会被一并下线)。"""
    target = get_revision(rev)["snapshot"]
    with session() as s:
        _, prev = _last_snapshot(s)
        dirty = s.scalars(select(Concept).where(Concept.workspace == _ws(), Concept.dirty == 1)).all()
        over = [{"id": c.id, "name": c.name, "kind": c.kind} for c in dirty if c.id in target]
        lost = [{"id": c.id, "name": c.name, "kind": c.kind} for c in dirty
                if c.id not in target and c.id in prev]
    return {"revision": rev, "overwritten": over, "lost": lost}


# ---------------- 变更提案(发布与回滚都要人审) ----------------
# 规则:提交人不能审批自己的提案;AI / 外部 Agent 不能审批;审批时如果草稿又被改过,要重新提交。
def _dirty_fingerprint(concept_ids: list[str] | None = None) -> list[list]:
    with session() as s:
        stmt = select(Concept.id, Concept.version).where(Concept.workspace == _ws(), Concept.dirty == 1)
        if concept_ids:
            stmt = stmt.where(Concept.id.in_(concept_ids))
        return sorted([cid, int(v)] for cid, v in s.execute(stmt).all())


def _pending_release() -> dict | None:
    from ..governance import review
    items = review.list_items(status="pending", kind="release", limit=1)["items"]
    return items[0] if items else None


def propose_release(note: str = "", concept_ids: list[str] | None = None) -> dict:
    """提交变更提案。concept_ids 为 None 表示全部改动;给了就只提交选中的(外加它们引用到的新元素)。
    提案里存的是这次要发布的元素清单和它们的指纹 —— 别的元素之后再怎么改,都不影响这份提案。"""
    from ..governance import review
    if concept_ids is not None and not concept_ids:
        raise HTTPException(422, "没有选中任何要发布的元素")
    scope = release_scope(concept_ids)
    diff = pending_diff(scope["ids"])
    if not (diff["added"] or diff["removed"] or diff["changed"]):
        raise HTTPException(409, "没有待发布的变更")
    if _pending_release():
        raise HTTPException(409, "已有一份待审批的变更提案,请先处理它(或撤回后重新提交)")
    with session() as s:
        rev, _ = _last_snapshot(s)
    title = f"发布第 {rev + 1} 版:新增 {len(diff['added'])},修改 {len(diff['changed'])},移除 {len(diff['removed'])}"
    return review.propose("release", title, {
        "op": "publish", "note": note or "", "concept_ids": scope["ids"], "diff": diff,
        "auto_included": scope["auto"],
        "fingerprint": _dirty_fingerprint(scope["ids"]), "base_revision": rev},
        source="user", target_ref="release", assignee_role="builder", dedupe=False)


def propose_rollback(rev: int, note: str = "") -> dict:
    from ..governance import review
    get_revision(rev)
    if _pending_release():
        raise HTTPException(409, "已有一份待审批的变更提案,请先处理它")
    with session() as s:
        cur, _ = _last_snapshot(s)
    diff = compare_revisions(cur, rev) if cur else {}
    return review.propose("release", f"回滚到第 {rev} 版", {
        "op": "rollback", "rev": rev, "note": note or "", "diff": diff, "base_revision": cur,
        "fingerprint": _dirty_fingerprint(), "discards": rollback_preview(rev)},
        source="user", target_ref="release", assignee_role="builder", dedupe=False)


def can_decide_release(actor: identity.Actor, item: dict) -> str:
    """返回不能审批的原因;空串表示可以。管理员什么都能批(含自己提交的,审计里注明);
    其他人不能批自己的,单人团队可在系统设置里放开(RELEASE_SELF_APPROVE)。"""
    from ..core import db as core_db
    from ..governance import permissions
    self_ok = core_db.get_config("RELEASE_SELF_APPROVE", "0").lower() in ("1", "true", "yes")
    why = permissions.can_decide(actor, perm="review", submitters=[item.get("created_by") or ""],
                                 allow_self=self_ok, what="变更提案")
    if why.startswith("不能审批自己"):
        why += ";单人团队可在「系统设置 → 治理」里打开「允许自审变更提案」"
    return why


def _accept_release(payload: dict, item: dict) -> dict:
    why = can_decide_release(identity.current(), item)
    if why:
        raise HTTPException(403, why)
    with session() as s:
        cur, _ = _last_snapshot(s)
    if int(payload.get("base_revision") or 0) != cur:
        raise HTTPException(409, "提交之后本体已经发布过新版本,请重新提交变更提案")
    if payload.get("op") == "rollback":
        # 提交时确认过会冲掉哪些未发布修改;之后又有新的修改,就得重新确认
        if "fingerprint" in payload and _dirty_fingerprint() != payload["fingerprint"]:
            raise HTTPException(409, "提交回滚之后又有元素被修改过,回滚会把它们一并冲掉,请重新提交并确认")
        return rollback(int(payload["rev"]))
    ids = payload.get("concept_ids") or None
    if _dirty_fingerprint(ids) != payload.get("fingerprint"):
        raise HTTPException(409, "提交之后这些元素又被修改过,请重新提交变更提案")
    return governed_publish(payload.get("note") or item["title"], ids)


def list_releases(status: str = "", limit: int = 50) -> list[dict]:
    from ..governance import review
    items = review.list_items(status=status, kind="release", limit=limit)["items"]
    actor = identity.current()
    for it in items:
        why = can_decide_release(actor, it) if it["status"] == "pending" else ""
        it["can_decide"] = it["status"] == "pending" and not why
        it["cannot_reason"] = why
    return items


def _register_release_handler() -> None:
    from ..governance import review
    review.register_handler("release", _accept_release)


_register_release_handler()


# ---------------- 引用 / 影响 / 血缘 ----------------
# 其他模块(能力、SOP、编排)注册自己的引用查找:fn(concept_id, names) -> [{type,id,name}]
_usage_providers: list[Callable[[str, list[str]], list[dict]]] = []


def register_usage_provider(fn: Callable[[str, list[str]], list[dict]]) -> None:
    _usage_providers.append(fn)


def usage(cid: str) -> list[dict]:
    c = get_concept(cid)
    out: list[dict] = []
    with session() as s:
        for other in s.scalars(select(Concept).where(
                Concept.workspace == _ws(), Concept.id != cid,
                Concept.spec_json.like(f"%{cid}%"))).all():
            out.append({"type": "concept", "id": other.id, "name": other.name,
                        "kind": other.kind})
    names = [c["name"]] + list(c.get("synonyms") or [])
    for fn in _usage_providers:
        try:
            out.extend(fn(cid, names))
        except Exception:  # noqa: BLE001
            log.debug("引用查找失败", exc_info=True)
    return out


def lineage(cid: str) -> dict:
    """血缘图:概念 → 引用的概念 → 绑定的表/列 → 数据源;概念 → 文档出处。"""
    from ..text2sql import semantic
    nodes: dict[str, dict] = {}
    edges: list[dict] = []

    def node(nid: str, label: str, kind: str) -> None:
        nodes.setdefault(nid, {"id": nid, "label": label, "kind": kind})

    def walk(concept_id: str, depth: int) -> None:
        try:
            c = get_concept(concept_id)
        except HTTPException:
            return
        node(concept_id, c["name"], c["kind"])
        if depth > 2:
            return
        for key, val in (c.get("spec") or {}).items():
            if isinstance(val, str) and val and val != concept_id:
                with session() as s:
                    ref = s.get(Concept, val)
                if ref is not None:
                    walk(val, depth + 1)
                    edges.append({"from": concept_id, "to": val, "label": key})
        for b in c.get("bindings") or []:
            ref = b["ref"]
            table = ref.get("table") or ref.get("base_table")
            ds = semantic.get_datasource(b["ds_id"]) if b["ds_id"] else None
            ds_node = f"ds:{b['ds_id']}"
            node(ds_node, ds["name"] if ds else f"数据源 {b['ds_id']}", "datasource")
            if table:
                tnode = f"table:{b['ds_id']}:{table}"
                node(tnode, table, "table")
                edges.append({"from": concept_id, "to": tnode, "label": "绑定"})
                edges.append({"from": tnode, "to": ds_node, "label": "位于"})
                cols = [ref.get("key_column"), ref.get("label_column"), ref.get("time_column"),
                        ref.get("object_key_column"), *(ref.get("columns") or {}).values(),
                        *(ref.get("dimensions") or {}).values()]
                for col in _expr_columns(ref.get("expression") or "") + [x for x in cols if x]:
                    cnode = f"col:{b['ds_id']}:{table}.{col}"
                    node(cnode, f"{table}.{col}", "column")
                    edges.append({"from": tnode, "to": cnode, "label": "列"})
        for e in (c.get("evidence") or [])[:8]:
            dnode = f"doc:{e['doc_id']}"
            node(dnode, e.get("heading") or f"文档 {e['doc_id']}", "document")
            edges.append({"from": concept_id, "to": dnode, "label": "出处"})

    walk(cid, 0)
    uniq = {(e["from"], e["to"], e["label"]): e for e in edges}
    return {"nodes": list(nodes.values()), "edges": list(uniq.values())}


def _expr_columns(expr: str) -> list[str]:
    if not expr:
        return []
    try:
        import sqlglot
        from sqlglot import exp
        tree = sqlglot.parse_one(f"SELECT {expr}", read="mysql")
        return sorted({c.name for c in tree.find_all(exp.Column) if c.name})
    except Exception:  # noqa: BLE001
        return []


def impact(cid: str) -> dict:
    """改这个概念会波及什么:直接引用它的一切 + 已发布状态 + 绑定。"""
    c = get_concept(cid)
    refs = usage(cid)
    by_type: dict[str, int] = {}
    for r in refs:
        by_type[r["type"]] = by_type.get(r["type"], 0) + 1
    return {"concept": {"id": cid, "name": c["name"], "kind": c["kind"],
                        "status": c["status"]},
            "references": refs, "by_type": by_type,
            "bindings": c.get("bindings") or [],
            "risk": "high" if len(refs) >= 5 else "medium" if refs else "low"}