propose.py 53.9 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
"""AI 提议本体:从文档、从数据源。所有提议都进审核队列,人采纳后才落成概念。

- 文档:按段落分批喂给 LLM,让它按四元组(对象 / 关系 / 函数 / 动作)找元素,
  每条提议都带出处 chunk,采纳后成为元素的证据。文中的角色顺带登记为业务角色。
- 数据源:内省出来的表与关联是确定性的,翻译成对象 + 绑定、关系 + 绑定。
  概念优先:有文档时,对象和关系从文档来,表只是「映射的证据」—— 文档说到的对象对上表就绑表,
  对不上的设为本体自建(由本系统保存);文档没提到的表不硬塞进本体。只有数据库、没有文档时,表才直接成为对象。
- 与已有元素同名:说法一致就只补证据;规则 / 决策表的定义不一致则提「知识冲突」让人裁决。
"""
from __future__ import annotations

import collections
import contextvars
import logging
import re
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Any, Iterator

from ..core import llm
from ..governance import llmlog, review
from . import schema, service

log = logging.getLogger(__name__)

BATCH_TOKENS = 3200
PARALLEL = 4            # 同时发给模型的批数

PROPOSE_SYSTEM = """你是一名本体(Ontology)建模专家。本体由四种元素组成:对象、关系、函数、动作。
从业务文档里识别出可以建模的元素,只输出文档里**明确出现或明确定义**的内容,不要臆造,
不要输出通用词(系统、数据、功能、信息)。

先给文档里的每个术语归类,再决定建成什么(这是最容易错的一步):
- 一类记录**每一条自己的量或状态**(订单的「应付金额 = 数量 × 单价」、工单「是否逾期」、合同「剩余天数」)
  → 写进那个对象的 spec.derived,不要建成指标,也不要单独建规则;
- 文档给某一类记录的**子集**起了名字(「逾期订单」「高价值客户」)→ 也是一个状态,写进 derived,
  这个叫法放进那条 derived 的 subset_names,**不要**当成对象的别名;
- 要对**很多条记录汇总**才得到的数(逾期订单数、平均处理时长、合格率、某某率、合计)→ function/aggregate(指标)。
  两种常常同时存在:先有每条记录的状态,再有按它汇总的指标(「是否逾期」→「逾期率」「逾期单数」),**两个都要提**;
  文档里「指标」「口径」章节定义的每个率、数、额,至少要有一个指标;
- 要看**别的对象或额外输入**才能判定 / 计算的(按客户等级和金额定折扣、按两个条件判断是否升级)→ function/rule;
- 按多个条件分档 / 分级 / 定审批人和优先级 → function/decision;
- 具体的取值(某个客户名、某个网点名、某个产品型号)是**实例**,写进对象的 spec.value_hints,**不是别名**。

元素(kind)与 spec:
- object_type 对象:可被指认、有属性、会有多个实例的东西(组织、单据、批次、人员、产品)。
  文档里的对象对应【已接入的数据表】中的某张表时:spec 写 {"table":表名,"terms":{文档里的属性叫法:列名}},
  不用再列 properties(列已经从表里来了),name 仍用**文档里的叫法**。
  没有对应表的对象:spec: {"properties":[{"name":属性名,"data_type":"string|number|date|enum|boolean","is_key":bool,
         "is_dimension":是否常用来分组/拆分,"enum_values":[...]}]}
  两种对象都可以带:
  "derived":[{"name":"文档里的叫法","kind":"quantity|state","text":"原文的定义或算法,照抄","subset_names":["子集的叫法"]}]
  "value_hints":{"属性名或文档里的属性叫法":["文档里出现的具体取值"]}
  "lifecycle":{"property":状态属性的叫法,"states":[状态...],"transitions":[{"from":[状态],"to":状态,"action":完成这次流转的动作名}]}
    —— 文档写了单据 / 事项的状态怎么一步步变(「待审 → 已批准 → 已下单」)、每一步由哪个操作完成时才写;
       状态只能经由动作流转,所以每条流转都要对上一个动作(动作也要提出来)。
  对象是**本系统要自己记录**、业务库里没有的东西(如「××建议单」「××登记」「处理记录」)时,写 "managed": true。
- link_type 关系:两个对象之间的关系。name 写成「从 from 看过去」能读通的说法(如「所属客户」「负责人」「下单网点」),
  inverse_name 写反过来的说法(如「名下订单」「负责的工单」)。
  spec: {"from_type":对象名,"to_type":对象名,"cardinality":"1:1|1:n|n:1|n:n","inverse_name":反向说法}
- function 函数:spec.category 取下面之一:
  - aggregate 聚合(指标):对一类记录求和 / 计数 / 平均 / 相除得到的数。
    spec: {"category":"aggregate","object_type":对象名,"unit":单位,"direction":"higher_better|lower_better|neutral",
           "calibre_rule":口径规则名,"formula_text":文字版算法(用到 derived 的就写 derived 的叫法),
           "period":{"grain":"day|week|month|quarter|year","start_day":1-31,"start_month_offset":整数,"end_day":1-31或"last","end_month_offset":整数}}
    统计周期是指标自己的口径:文档写了「上月 26 日至本月 25 日」→ period={"grain":"month","start_day":26,"start_month_offset":-1,"end_day":25,"end_month_offset":0};
    没写就省略 period(按自然月)。库存、余额这类时点数要看走势的,写 "history":{"enabled":true}(每天拍快照)。
  - rule 规则:要看别的对象或额外输入的判定、计算、口径约定。
    spec: {"category":"rule","object_type":规则主要看哪类对象,"rule_kind":"judgement|calibre|calculation","params":[变量名],
           "expression":"用这些变量写的 Python 风格表达式,如 actual >= target;写不出就留空","text":规则原文要点}
    文中给了算例(「例如 A 为 25、B 为 20,结果是 40」)写进 "examples":[{"inputs":{变量:值},"expect":结果}]。
  - decision 决策表:按多个条件分档 / 分级 / 打分 / 定审批人。
    spec: {"category":"decision","inputs":[{"name":英文名,"label":中文}],"outputs":[{"name":英文名,"label":中文}],
           "rows":[{"when":{输入名:"> 3"},"then":{输出名:值}}],"text":原文要点}
  - object_set 对象集:文档给「满足某些条件的一批对象」起了名字、并且要拿它去盯、去批量处理(「低于下限的物料」「超期未处理的单据」)。
    spec: {"category":"object_set","base":对象名,"text":筛选条件原文,"where_text":条件的文字版}
- action 动作:文中明确要求「由某人对某对象做某事」、会改变数据的业务操作(登记、标记、撤销、派发、变更状态、新建单据)。
  spec: {"target_type":对象名,"description_only":true,"text":要做什么、填什么、谁来审批(照原文)}
  文中把成对的操作写在一起(「标记 / 解除」「启用 / 停用」「冻结 / 解冻」),**拆成两个动作**分别提。

另外:文中出现的岗位 / 职责主体,放进顶层 "roles":[{"name":角色名,"description":职责(照原文,包括他审批什么、负责什么)}],不要当成元素。
name 用文档里的中文业务叫法;英文名、代码名、缩写放进 synonyms。
synonyms 只放「同一个东西的别的叫法」:不放实例(具体的名称、编号、型号),不放子集的叫法,不放表名。
流程(有先后步骤的事)不要建元素,会另行生成流程卡。

宁缺毋滥 —— 提议出来的每一条都要人逐条审,凑数的条目只会添乱:
- aggregate 必须是对一类记录「求和 / 计数 / 平均 / 相除」算出来的数,而且文中给了它的名字或算法。
  下面这些**不是**指标:一条记录自己的量(写进 derived)、分类或标签、形容词和现象描述。
- rule 必须有明确的判定条件或计算式。审批要过谁、处理的先后步骤、谁负责什么**不是**规则(属于动作、决策表和流程卡)。
- action 只提文中明确列出的、会改变数据的业务操作。查询、查看、汇总、提醒不是动作。
- link_type:文中说了两个对象之间是什么关系就提(一对对象之间**最多提一条**),两端用对象的文档叫法;
  取数方式会自动对上数据表的外键,不用写。
- 同一个东西只提一次。【已存在的概念】和【这次已经提过的】里有的,不要换个名字、加个括号再提。
- 数量上限(每次输出):指标不超过 10 个,规则不超过 10 条,决策表不超过 3 张,对象集不超过 5 个,动作不超过 12 个。超出时留最重要的。

给了【文档条目】时:每个元素(以及每条 derived)写上它落实了哪几条:req_ids(条目编号列表)。

输出严格 JSON:
{"concepts":[{"kind":..., "name":规范名称, "synonyms":[文中出现的其他叫法], "description":一句话定义,
  "spec":{...}, "req_ids":["R03"], "evidence":[{"chunk":出处片段编号(如 "d1:c3"),"quote":"原文里能证明它的那句话,照抄,30 字以内"}],
  "confidence":0~1}],
 "roles":[{"name":..., "description":...}]}
"""

PROPOSE_USER = """已存在的概念(不要重复提议,除非你发现了新的别名或定义):
{existing}
{reqs}
文档片段:
{text}
"""


def _existing_names(limit: int = 300) -> str:
    items = service.list_concepts(limit=limit)
    if not items:
        return "(暂无)"
    return "、".join(f"{c['name']}({c['kind_label']})" for c in items)


_SUFFIX = re.compile(r"[((][^()()]{1,8}[))]$")


def _base_name(name: str) -> str:
    """「缺件单数(区域)」「缺件单数(汇总)」这类只差一个括号后缀的,看作同一个东西。"""
    return _SUFFIX.sub("", name).strip()


def _batches(chunks: list[dict]) -> list[list[dict]]:
    out: list[list[dict]] = []
    cur: list[dict] = []
    size = 0
    for c in chunks:
        t = llm.count_tokens(c.get("text", ""))
        if cur and size + t > BATCH_TOKENS:
            out.append(cur)
            cur, size = [], 0
        cur.append(c)
        size += t
    if cur:
        out.append(cur)
    return out


def _merge(bucket: dict, item: dict, chunk_map: dict[str, dict]) -> None:
    up = schema.element_kind(str(item.get("kind") or ""), item.get("spec") if isinstance(item.get("spec"), dict) else {})
    name = str(item.get("name") or "").strip()
    if up is None or not name or len(name) > 60:
        return
    kind, spec0 = up
    item = {**item, "kind": kind, "spec": spec0}
    if kind == "action":
        # 文档里只能看出「要有这个动作」,效果要人补;先记成动作草稿的说明,采纳后在动作编辑器里补全
        item["spec"] = {"_stub": True, "text": str(spec0.get("text") or item.get("description") or "")}
    raw_spec = item.get("spec") if isinstance(item.get("spec"), dict) else {}
    table = str(raw_spec.pop("table", "") or "") if kind == "object_type" else ""
    terms = raw_spec.pop("terms", None) if kind == "object_type" else None
    derived = [d for d in (raw_spec.pop("derived", None) or []) if isinstance(d, dict) and d.get("name")]         if kind == "object_type" else []
    hints = raw_spec.pop("value_hints", None) if kind == "object_type" else None
    req_ids = [str(x) for x in item.get("req_ids") or [] if x]
    key = _seed_by_table(bucket, table) or _bucket_key(bucket, kind, name, item.get("synonyms") or [])
    ev = []
    for e in item.get("evidence") or []:
        cid, quote = (e.get("chunk"), e.get("quote")) if isinstance(e, dict) else (e, "")
        ch = chunk_map.get(str(cid))
        if ch:
            heading, snippet = locate(ch, str(quote or ""))
            ev.append({"chunk_id": ch["id"], "doc_id": ch.get("doc_id", 0),
                       "heading": heading, "snippet": snippet})
    cur = bucket.get(key)
    if cur is not None and isinstance(terms, dict):
        _apply_terms(cur, terms)
    if cur is None:
        bucket[key] = cur = {"kind": kind, "name": key[1], "synonyms": list(item.get("synonyms") or []),
                             "description": str(item.get("description") or ""),
                             "spec": item.get("spec") if isinstance(item.get("spec"), dict) else {},
                             "evidence": ev, "confidence": float(item.get("confidence") or 0.6)}
        _extras(cur, derived, hints, req_ids)
        return
    _extras(cur, derived, hints, req_ids)
    if cur.pop("_seed", False) and name != cur["name"]:
        # 数据表起的名字(取自表注释)让位给文档里的业务叫法,原名留作别名
        cur["synonyms"].append(cur["name"])
        cur["name"] = name
    for s in [name, *(item.get("synonyms") or [])]:
        if s != cur["name"] and s not in cur["synonyms"]:
            cur["synonyms"].append(s)
    if len(str(item.get("description") or "")) > len(cur["description"]):
        cur["description"] = str(item["description"])
    if isinstance(item.get("spec"), dict):
        for k, v in item["spec"].items():
            if v not in (None, "", [], {}) and not cur["spec"].get(k):
                cur["spec"][k] = v
    have = {e["chunk_id"] for e in cur["evidence"]}
    cur["evidence"] += [e for e in ev if e["chunk_id"] not in have]
    cur["confidence"] = max(cur["confidence"], float(item.get("confidence") or 0))


def _extras(cur: dict, derived: list[dict], hints: Any, req_ids: list[str]) -> None:
    """对象上的派生量 / 状态、文档里出现的具体取值,元素落实的文档条目:合并进候选(同名的不重复)。"""
    have = {d["name"] for d in cur.get("derived") or []}
    for d in derived:
        if str(d["name"]) not in have:
            cur.setdefault("derived", []).append({
                "name": str(d["name"])[:40], "kind": "state" if d.get("kind") == "state" else "quantity",
                "text": str(d.get("text") or "")[:300],
                "subset_names": [str(x) for x in d.get("subset_names") or [] if x][:6],
                "req_ids": [str(x) for x in d.get("req_ids") or [] if x]})
            have.add(str(d["name"]))
    if isinstance(hints, dict):
        vh = cur.setdefault("value_hints", {})
        for k, vals in hints.items():
            vals = vals if isinstance(vals, list) else [vals]
            vh[str(k)] = list(dict.fromkeys([*vh.get(str(k), []), *[str(v) for v in vals if v not in (None, "")]]))[:30]
    if req_ids:
        cur["req_ids"] = list(dict.fromkeys([*(cur.get("req_ids") or []), *req_ids]))


def locate(chunk: dict, quote: str) -> tuple[str, str]:
    """出处定位到原文那一句:(所在章节, 那一行前后)。找不到就退回片段开头。
    片段正文里带着 Markdown 标题(建模切块时保留的),往上找最近的标题当章节名。"""
    text = chunk.get("text") or ""
    q = re.sub(r"\s+", "", quote or "")
    lines = text.splitlines()
    hit = -1
    if q:
        for i, ln in enumerate(lines):
            flat = re.sub(r"\s+", "", ln)
            if q in flat or (len(q) > 12 and q[:12] in flat):
                hit = i
                break
    if hit < 0:
        return chunk.get("heading", ""), text[:300]
    heading = chunk.get("heading", "")
    for ln in reversed(lines[:hit + 1]):
        m = re.match(r"^\s*#{1,6}\s+(.*)$", ln)
        if m:
            heading = m.group(1).strip()
            break
    return heading, "\n".join(lines[hit:hit + 2])[:400]


def _seed_by_table(bucket: dict, table: str) -> tuple[str, str] | None:
    """文档里的对象说了对应哪张表:归到这张表翻译出来的那一条(随后文档叫法顶替表注释名)。"""
    if not table:
        return None
    low = table.lower()
    for k, cur in bucket.items():
        if k[0] != "object_type":
            continue
        for b in cur.get("bindings") or []:
            if str((b.get("ref") or {}).get("table") or "").lower() == low:
                return k
    return None


def _apply_terms(cur: dict, terms: dict) -> None:
    """文档里的属性叫法 → 对应列的显示名;表注释里的说法留在说明里。"""
    props = {p["name"]: p for p in (cur.get("spec") or {}).get("properties") or []}
    cur["spec"].setdefault("_terms", {}).update({str(k): str(v) for k, v in terms.items() if str(v) in props})
    for term, col in terms.items():
        p = props.get(str(col))
        term = str(term).strip()
        if p is None or not term or len(term) > 30:
            continue
        if p.get("display_name") and p["display_name"] != term and p["display_name"] not in (p.get("description") or ""):
            p["description"] = f"{p.get('description') or ''}(表注释:{p['display_name']})".strip()
        p["display_name"] = term


def _bucket_key(bucket: dict, kind: str, name: str, synonyms: list) -> tuple[str, str]:
    """同一个东西的不同叫法合并到一条:名称或别名(含表名)撞上已有候选就归到它名下。"""
    if (kind, name) in bucket:
        return (kind, name)
    names = {name, *[str(x) for x in synonyms]}
    base = _base_name(name)
    for (k, n), cur in bucket.items():
        if k != kind:
            continue
        if {n, cur["name"]} & names or names & set(cur.get("synonyms") or []):
            return (k, n)
        if kind != "object_type" and base and base in (_base_name(n), _base_name(cur["name"])):
            return (k, n)
    return (kind, name)


def _absorb(cur: dict, other: dict) -> None:
    """把 other 并进 cur:叫法变成别名,出处、绑定、定义里缺的补上。函数类别不同(规则 vs 决策表)时不混定义。"""
    for s in [other["name"], *(other.get("synonyms") or [])]:
        if s != cur["name"] and s not in cur["synonyms"]:
            cur["synonyms"].append(s)
    if not cur.get("description") and other.get("description"):
        cur["description"] = other["description"]
    if (cur["spec"] or {}).get("category") == (other["spec"] or {}).get("category"):
        for k, v in (other["spec"] or {}).items():
            if v not in (None, "", [], {}) and not cur["spec"].get(k):
                cur["spec"][k] = v
    if not cur.get("bindings") and other.get("bindings"):
        cur["bindings"] = other["bindings"]
    have = {e["chunk_id"] for e in cur["evidence"]}
    cur["evidence"] += [e for e in other.get("evidence") or [] if e["chunk_id"] not in have]
    cur["confidence"] = max(cur["confidence"], other.get("confidence") or 0)
    _extras(cur, other.get("derived") or [], other.get("value_hints"), other.get("req_ids") or [])


def _union_by_alias(bucket: dict) -> int:
    """各批分开读,后来的一批可能把前面单独建了的名字写成了别名(「发起调拨」又叫「强制调拨」):
    同一种元素里,一条的名称是另一条的别名,就并到写了这个别名的那条上。返回并掉的条数。"""
    merged = 0
    changed = True
    while changed:
        changed = False
        for ka, a in list(bucket.items()):
            if ka not in bucket:
                continue
            for kb, b in list(bucket.items()):
                if kb == ka or kb[0] != ka[0] or kb not in bucket or b.get("_seed"):
                    continue
                if b["name"] in a["synonyms"]:
                    _absorb(a, bucket.pop(kb))
                    merged += 1
                    changed = True
    return merged


DEDUPE_PROMPT = """下面是从同一份业务文档的不同段落里分别找出来的候选元素。各段是分开读的,同一个东西可能换了说法被提了好几次。
找出「其实是同一个东西」的组:同一种元素(对象 / 关系 / 函数 / 动作),名字不同,但指的是同一个业务概念、同一个指标、
同一条规则或同一个操作。函数里,同一条规则可能一次被提成规则、一次被提成决策表或聚合,也算重复。
关系要两端对象相同(或正好相反)且说的是同一种联系才算重复。

不是同一个东西的不要合:「缺件单数」和「缺件率」是两个指标;「发起调拨」和「审批调拨」是两个动作;
「调入」「调出」虽然两端相同,但是两种联系。拿不准就不合。

每组挑一个保留(名字最贴近文档的业务叫法、定义最完整的那条),其余并进去。

候选:
{items}

只输出 JSON:{{"groups":[{{"keep":编号,"merge":[编号,...],"why":"一句话"}}]}},没有重复就输出 {{"groups":[]}}。"""


def _dedupe(bucket: dict, label: str = "") -> int:
    """让 AI 看一遍合并后的全部候选,把换了说法的重复并掉(只在同一种元素之间并)。返回并掉的条数。"""
    keys = [k for k, cur in bucket.items() if not cur.get("_seed")]
    if len(keys) < 2:
        return 0
    lines = []
    for i, k in enumerate(keys):
        cur = bucket[k]
        sp = cur["spec"] or {}
        ends = f"({sp.get('from_type')} → {sp.get('to_type')})" if k[0] == "link_type" else ""
        syn = f"(又叫 {'、'.join(cur['synonyms'][:6])})" if cur["synonyms"] else ""
        lines.append(f"[{i}] {schema.kind_label(k[0], sp)} {cur['name']}{ends}{syn}:{(cur.get('description') or '')[:60]}")
    try:
        with llmlog.feature("ontology_dedupe"), llm.trace_label(f"{label}合并换了说法的重复"):
            res = llm.chat_json([{"role": "user", "content": DEDUPE_PROMPT.format(items="\n".join(lines))}],
                                temperature=0)
    except Exception as e:  # noqa: BLE001
        log.warning("合并重复候选失败,保留原样:%s", e)
        return 0
    merged = 0
    for g in (res.get("groups") or []) if isinstance(res, dict) else []:
        try:
            keep = int(g.get("keep"))
            others = [int(x) for x in g.get("merge") or []]
        except (TypeError, ValueError):
            continue
        if not 0 <= keep < len(keys) or keys[keep] not in bucket:
            continue
        kk = keys[keep]
        for o in others:
            if o == keep or not 0 <= o < len(keys):
                continue
            ko = keys[o]
            if ko[0] != kk[0] or ko not in bucket:
                continue                                  # 只在同一种元素之间并
            _absorb(bucket[kk], bucket.pop(ko))
            merged += 1
    return merged


def _object_names(bucket: dict) -> dict[str, str]:
    """对象的任一叫法 → 规范名称(关系两端按它对齐)。"""
    out: dict[str, str] = {}
    for (k, n), cur in bucket.items():
        if k == "object_type":
            for alias in (n, cur["name"], *(cur.get("synonyms") or [])):
                out[str(alias)] = cur["name"]
    return out


def _align_links(bucket: dict) -> int:
    """文档里的关系没有取数方式;数据表推出来的关系有 join 但名字是机器起的。
    两端对得上就合成一条:用文档的名字和说法,带上表的 join 绑定。返回合并条数。"""
    names = _object_names(bucket)
    for (k, _), cur in bucket.items():
        if k == "link_type":
            sp = cur["spec"]
            for end in ("from_type", "to_type"):
                if sp.get(end) in names:
                    sp[end] = names[sp[end]]
    table_links = {key: cur for key, cur in bucket.items() if key[0] == "link_type" and cur.get("bindings")}
    has_tables = bool(table_links)
    objects = set(names.values())
    taken: dict[frozenset, dict] = {}      # 这对对象之间,已经用文档说法命名过的关系
    merged = 0
    for key, cur in list(bucket.items()):
        if key[0] != "link_type" or cur.get("bindings"):
            continue
        a, b = cur["spec"].get("from_type"), cur["spec"].get("to_type")
        pair = frozenset((a, b))
        if any(x not in objects and not service.find(str(x or ""), "object_type") for x in (a, b)):
            bucket.pop(key, None)          # 有一头既不是这次提的对象、也不是已有的对象:连不起来,不提
            continue
        for tkey, t in list(table_links.items()):
            ta, tb = t["spec"].get("from_type"), t["spec"].get("to_type")
            if (a, b) == (ta, tb):
                cur["bindings"] = t["bindings"]
            elif (a, b) == (tb, ta):          # 文档说的方向和外键相反:join 两列对调
                cur["bindings"] = [{**bd, "ref": {"from_column": bd["ref"].get("to_column"),
                                                  "to_column": bd["ref"].get("from_column")}}
                                   for bd in t["bindings"]]
            else:
                continue
            cur["confidence"] = max(cur["confidence"], t.get("confidence") or 0)
            bucket.pop(tkey, None)
            table_links.pop(tkey, None)
            taken.setdefault(pair, cur)
            merged += 1
            break
        else:
            first = taken.get(pair)
            if first is not None:          # 这对对象的 join 都用完了:只是同一条关系的另一种说法
                for s in [cur["name"], *(cur.get("synonyms") or [])]:
                    if s != first["name"] and s not in first["synonyms"]:
                        first["synonyms"].append(s)
                bucket.pop(key, None)
            elif has_tables:               # 表里没有这条关联:留着,但默认不勾选,由人判断要不要
                cur["confidence"] = min(cur["confidence"], 0.5)
    return merged


def _same_join_link(p: dict) -> bool:
    """提议的关系和已有关系连的是同一对对象、用的是同一组关联列(任一方向)。"""
    jb = next((b for b in p.get("bindings") or [] if b.get("target_kind") == "join"), None)
    if not jb:
        return False
    sp = p.get("spec") or {}
    ends = {(service.find(str(sp.get("from_type") or ""), "object_type") or {}).get("id"),
            (service.find(str(sp.get("to_type") or ""), "object_type") or {}).get("id")}
    cols = {jb["ref"].get("from_column"), jb["ref"].get("to_column")}
    for c in service.list_concepts(kind="link_type", limit=500):
        full = service.get_concept(c["id"])
        fs = full.get("spec") or {}
        b = next((x for x in full.get("bindings") or [] if x["target_kind"] == "join"), None)
        if b and {fs.get("from_type"), fs.get("to_type")} == ends and \
                {b["ref"].get("from_column"), b["ref"].get("to_column")} == cols:
            return True
    return False


def _definition(kind: str, spec: dict) -> str:
    cat = spec.get("category") if kind == "function" else ""
    if cat == "rule":
        return str(spec.get("expression") or "").replace(" ", "")
    if cat == "object_set":
        return f"{spec.get('base')}|{spec.get('where')}"
    return ""


def submit_proposals(proposals: list[dict], source: str) -> dict:
    """把一批提议送进审核队列(或补证据 / 提冲突)。返回计数。"""
    created = conflicts = enriched = 0
    for p in proposals:
        up = schema.element_kind(p.get("kind") or "", p.get("spec") or {})
        if up is None:
            continue
        p["kind"], raw = up
        if p["kind"] == "action" and raw.get("_stub"):
            spec = raw                     # 动作骨架:采纳时建成「待补全」的说明,不走完整校验
        else:
            try:
                spec = schema.normalize_spec(p["kind"], raw)
            except schema.SpecError as e:
                log.warning("提议「%s」的定义不合法,只保留名称、原文与出处:%s", p.get("name"), e)
                # 表达式写坏了也要留住原文要点:后面「计算属性与规则」这一步照着原文重写
                spec = {k: raw.get(k) for k in ("category", "text", "object_type", "rule_kind", "examples", "unit",
                                                 "formula_text", "direction") if raw.get(k) not in (None, "")} \
                    if p["kind"] == "function" else {}
                if p["kind"] == "function" and not spec.get("text") and raw.get("expression"):
                    spec["text"] = f"(AI 起草的公式写法有误:{raw['expression']})"
                if p["kind"] == "function":
                    try:
                        spec = schema.normalize_spec("function", spec)
                    except schema.SpecError:
                        spec = {}
        p["spec"] = spec
        existing = service.find(p["name"], p["kind"])
        if existing is None and p["kind"] == "link_type" and _same_join_link(p):
            enriched += 1        # 同一对对象、同一组关联列的关系已经有了(名字不同而已):不重复提议
            continue
        if existing:
            old_def = _definition(p["kind"], existing.get("spec") or {})
            new_def = _definition(p["kind"], spec)
            if old_def and new_def and old_def != new_def:
                review.propose("conflict", f"「{p['name']}」的定义存在冲突", {
                    "concept_id": existing["id"], "kind": p["kind"],
                    "current": {"spec": existing.get("spec"), "description": existing.get("description")},
                    "proposed": {"spec": spec, "description": p.get("description")},
                    "evidence": p.get("evidence") or []},
                    source=source, confidence=p.get("confidence", 0.5), target_ref=existing["id"])
                conflicts += 1
            else:
                if p.get("bindings") and not service.get_concept(existing["id"]).get("bindings"):
                    for b in p["bindings"]:
                        review.propose("binding", f"为「{existing['name']}」绑定数据表",
                                       {"concept_id": existing["id"], **b}, source=source,
                                       confidence=p.get("confidence", 0.8), target_ref=existing["id"])
                if p.get("evidence"):
                    service.add_evidence(existing["id"], p["evidence"])
                new_syn = [s for s in p.get("synonyms") or []
                           if s not in (existing.get("synonyms") or []) and s != existing["name"]]
                if new_syn:
                    review.propose("concept_update", f"为「{existing['name']}」补充别名", {
                        "concept_id": existing["id"],
                        "synonyms": list(existing.get("synonyms") or []) + new_syn},
                        source=source, confidence=p.get("confidence", 0.5),
                        target_ref=existing["id"])
                enriched += 1
            continue
        title = f"{schema.kind_label(p['kind'], spec)}「{p['name']}」"
        review.propose("concept_create", title, p, source=source,
                       confidence=p.get("confidence", 0.6), target_ref=f"{p['kind']}:{p['name']}")
        created += 1
    return {"proposed": created, "conflicts": conflicts, "enriched": enriched}


_MACHINE = re.compile(r"^[A-Za-z0-9]+(_[A-Za-z0-9]+)+$")


def _tidy_objects(bucket: dict) -> dict[str, int]:
    """对象的别名里常混进三样不是别名的东西,这里按数据和定义确定性地挑出来:
    - 表名、snake_case 的机器名(绑定里已经有了);
    - 子集的叫法(derived 里写了 subset_names 的,会挂到那个状态上);
    - 实例值(某个具体的名称):和业务表名称列抽样出来的取值比,等于某个取值、或只出现在少数几个取值里的,
      挪进名称属性的「常见取值」。出现在大多数取值里的(如每个名称都带同一个词)是类型词,留着。
    再把文档里出现的具体取值(value_hints)落到对应属性上。返回 {tables, subsets, instances} 计数。"""
    from .modeling_world import sample_values
    stats = {"tables": 0, "subsets": 0, "instances": 0}
    for (k, _), cur in bucket.items():
        if k != "object_type":
            continue
        spec = cur.get("spec") or {}
        props = spec.get("properties") or []
        tb = next((b for b in cur.get("bindings") or [] if b.get("target_kind") == "table"), None)
        ref = (tb or {}).get("ref") or {}
        table = str(ref.get("table") or "").lower()
        col2prop = {v: k2 for k2, v in (ref.get("columns") or {}).items()}
        label_prop = spec.get("label_property") or col2prop.get(ref.get("label_column") or "", "")
        subsets = {n for d in cur.get("derived") or [] for n in d.get("subset_names") or []}
        hints: dict[str, list[str]] = {}
        values = sample_values(int(tb["ds_id"]), ref["table"], ref["label_column"]) if tb and ref.get("label_column") else []
        enums = {v: p["name"] for p in props for v in p.get("enum_values") or []}
        keep = []
        for syn in cur.get("synonyms") or []:
            if syn.lower() == table or _MACHINE.match(syn):
                stats["tables"] += 1
                continue
            if syn in subsets:
                stats["subsets"] += 1
                continue
            if syn in enums:
                hints.setdefault(enums[syn], []).append(syn)
                stats["instances"] += 1
                continue
            hit = sum(1 for v in values if syn in v) if values and len(syn) >= 2 else 0
            if label_prop and (syn in values or (hit and hit <= max(1, int(len(values) * 0.3)))):
                hints.setdefault(label_prop, []).append(syn)
                stats["instances"] += 1
                continue
            keep.append(syn)
        cur["synonyms"] = keep
        by: dict[str, str] = {}
        for p in props:
            for n in (p["name"], p.get("display_name") or ""):
                if n:
                    by[n] = p["name"]
        for term, col in (spec.pop("_terms", None) or {}).items():
            by.setdefault(term, col)
        for key, vals in (cur.pop("value_hints", None) or {}).items():
            target = by.get(str(key)) or col2prop.get(str(key)) or label_prop
            if target:
                hints.setdefault(target, []).extend(vals)
        for p in props:
            if hints.get(p["name"]):
                p["value_hints"] = list(dict.fromkeys([*(p.get("value_hints") or []), *hints[p["name"]]]))[:30]
    return stats


def from_documents(chunks: list[dict], *, source: str = "extract", hint: str = "",
                   seed: list[dict] | None = None, label: str = "", reqs: list[dict] | None = None) -> Iterator[dict]:
    """后台任务:分批让 LLM 提议概念。yield 进度事件,最后一条带统计。

    source:提议的来源标记(业务建模用 `modeling:<run_id>` 找回自己这次的草案);
    hint:行业路由给的先验(参考模板里的常见元素名),只帮助命名,不强加内容;
    seed:已接入数据表翻译出的对象 / 关系(带绑定)。文档里说的是同一个东西时并进去,
          草案一出来就绑好了表,不会出现「文档一套对象、数据表又一套对象」。
    label:调用追踪里的名字前缀(业务建模的流水线节点详情里看得到每一批)。

    各批同时发给模型(带思考的模型一批要一两分钟,一批接一批太慢),回来后按批次顺序合并:
    同一个东西在不同批里换了叫法,由 _bucket_key 按名称 / 别名 / 去括号后缀归到一条。
    """
    chunks = [c for c in chunks if (c.get("text") or "").strip()]
    if not chunks:
        yield {"stage": "error", "error": "没有可用的文档片段,请先上传并抽取文档"}
        return
    batches = _batches(chunks)
    chunk_map = {c["id"]: c for c in chunks}
    bucket: dict = {(p["kind"], p["name"]): {**p, "evidence": list(p.get("evidence") or []),
                                             "synonyms": list(p.get("synonyms") or []), "_seed": True,
                                             "_auto_name": p["kind"] == "link_type"}
                    for p in seed or []}
    role_bucket: dict[str, str] = {}
    yield {"stage": "propose", "message": f"共 {len(chunks)} 个片段,分 {len(batches)} 批同时读", "progress": 2}
    existing = _existing_names()
    if hint:
        existing += f"\n\n行业参考(该行业常见的元素名,文档里有对应内容时优先沿用这些名称):{hint}"
    tables = [f"- 表 {p['bindings'][0]['ref']['table']}({p['name']}):" + "、".join(
                  f"{x['name']}({x.get('display_name') or ''})" for x in (p.get("spec") or {}).get("properties") or [])[:600]
              for p in seed or [] if p["kind"] == "object_type"]
    if tables:
        existing += ("\n\n已接入的数据表(括号里是表注释,只作参考;文档里说的是同一个东西时,"
                     "对象 name 用文档叫法、spec.table 写这里的表名):\n" + "\n".join(tables))

    req_text = ("\n【文档条目】(编号|类别|内容):\n" + "\n".join(
        f"{r['id']}|{r.get('kind_label') or r.get('kind')}|{r['text']}" for r in reqs if r.get("kind") != "background") + "\n") \
        if reqs else ""

    def one(i: int, batch: list[dict]) -> Any:
        text = "\n\n".join(f"[{c['id']}]【{c.get('heading') or '正文'}】\n{c['text']}" for c in batch)
        heads = "、".join(dict.fromkeys(c.get("heading") or "" for c in batch if c.get("heading")))[:60]
        with llmlog.feature("ontology_propose"), llm.trace_label(f"{label}第 {i}/{len(batches)} 批:{heads}"):
            return llm.chat_json([{"role": "system", "content": PROPOSE_SYSTEM},
                                  {"role": "user", "content": PROPOSE_USER.format(existing=existing, reqs=req_text,
                                                                                  text=text)}])

    results: dict[int, Any] = {}
    with ThreadPoolExecutor(max_workers=min(PARALLEL, len(batches))) as pool:
        futs = {pool.submit(contextvars.copy_context().run, one, i, b): i for i, b in enumerate(batches, 1)}
        done = 0
        for f in as_completed(futs):
            i = futs[f]
            done += 1
            try:
                results[i] = f.result()
            except Exception as e:  # noqa: BLE001
                results[i] = None
                yield {"stage": "propose", "message": f"第 {i} 批失败:{str(e)[:200]}",
                       "progress": int(done / len(batches) * 90)}
                continue
            res = results[i]
            n = len((res.get("concepts") if isinstance(res, dict) else res) or [])
            yield {"stage": "propose", "message": f"第 {i}/{len(batches)} 批读完,找到 {n} 条(已读完 {done}/{len(batches)} 批)",
                   "progress": int(done / len(batches) * 90)}
    for i in sorted(results):
        res = results[i]
        items = res.get("concepts") if isinstance(res, dict) else res
        for it in items or []:
            if isinstance(it, dict):
                if it.get("kind") == "role":           # 老习惯:角色混在元素里
                    role_bucket.setdefault(str(it.get("name") or ""), str(it.get("description") or ""))
                    continue
                _merge(bucket, it, chunk_map)
        for r in (res.get("roles") if isinstance(res, dict) else None) or []:
            if isinstance(r, dict) and r.get("name"):
                role_bucket.setdefault(str(r["name"]).strip(), str(r.get("description") or ""))
    before = len(bucket)
    _union_by_alias(bucket)
    yield {"stage": "propose", "message": f"按名称和别名合并后 {len(bucket)} 个候选(并掉 {before - len(bucket)} 个),"
                                          f"再让 AI 找换了说法的重复", "progress": 92}
    same = _dedupe(bucket, label) if len(batches) > 1 else 0
    if same:
        yield {"stage": "propose", "message": f"AI 找出 {same} 个换了说法的重复,已合并,剩 {len(bucket)} 个候选", "progress": 95}
    aligned = _align_links(bucket)
    mapped = _concept_first(bucket)
    yield {"stage": "propose", "progress": 96,
           "message": f"概念优先:{mapped['bound']} 个对象对上了数据表,{mapped['managed']} 个设为本体自建(库里没有、由本系统保存),"
                      f"{mapped['unbound']} 个还没有数据来源;文档没提到的表 {len(mapped['dropped_tables'])} 张不建对象"
                      + (f"({'、'.join(mapped['dropped_tables'][:6])}{' 等' if len(mapped['dropped_tables']) > 6 else ''})"
                         if mapped["dropped_tables"] else "")
                      + (f";{mapped['lifecycles']} 个状态机" if mapped["lifecycles"] else "")}
    tidy = _tidy_objects(bucket)
    if any(tidy.values()):
        yield {"stage": "propose", "progress": 96,
               "message": f"整理别名:去掉表名 {tidy['tables']} 个、子集叫法 {tidy['subsets']} 个,"
                          f"实例值 {tidy['instances']} 个改记为属性的常见取值"}
    for p in bucket.values():
        p.pop("_seed", None)
        if p.pop("_auto_name", False):
            sp = p.get("spec") or {}
            tail = re.search(r"([^()]+)$", p["name"])
            p["name"] = f"{sp.get('from_type')}-{sp.get('to_type')}" + (tail.group(0) if tail else "")
    stats = submit_proposals(list(bucket.values()), source)
    stats["bound"] = sum(1 for p in bucket.values() if p.get("bindings"))
    stats["aligned_links"] = aligned
    stats["managed"] = mapped["managed"]
    stats["dropped_tables"] = len(mapped["dropped_tables"])
    from ..governance import roles
    have = set(roles.names())
    new_roles = [n for n in role_bucket if n and n not in have and len(n) <= 30]
    for n in new_roles:
        roles.upsert(n, role_bucket[n])
    stats["roles"] = len(new_roles)
    yield {"stage": "done", "progress": 100,
           "message": f"提议 {stats['proposed']} 块新元素({stats['bound']} 块已绑定数据表),{stats['conflicts']} 个冲突,"
                      f"{stats['enriched']} 块已有元素补充了出处,登记 {len(new_roles)} 个业务角色",
           "result": stats}


def _concept_first(bucket: dict) -> dict:
    """概念优先:对象和关系以文档为准,表只是映射的证据。

    - 文档从头到尾没提到的表(只是数据库里有)不建成对象,连带只连着它们的表间关联也不提;
    - 文档里的对象对上了表的,绑定已经在合并时带上;对不上、而 AI 判断「本系统要自己记录」的,设为本体自建;
    - 文档写了状态流转的,把状态机挂到那个对象的状态属性上(属性不存在就新建一个,绑了表的设为本体自有属性)。"""
    out = {"bound": 0, "managed": 0, "unbound": 0, "dropped_tables": [], "lifecycles": 0}
    drop = [k for k, p in bucket.items() if k[0] == "object_type" and p.get("_seed") and not p.get("evidence")
            and not p.get("req_ids") and not p.get("derived")]
    if not any(k[0] == "object_type" and not p.get("_seed") or p.get("evidence")
               for k, p in bucket.items() if k[0] == "object_type"):
        drop = []      # 文档一个对象也没读出来(多半是读失败了):表照样建成对象,不能全丢
    gone = set()
    for k in drop:
        p = bucket.pop(k)
        gone |= {p["name"], *(p.get("synonyms") or [])}
        out["dropped_tables"].append(((p.get("bindings") or [{}])[0].get("ref") or {}).get("table") or p["name"])
    for k in [k for k, p in bucket.items() if k[0] == "link_type"]:
        sp = bucket[k].get("spec") or {}
        if sp.get("from_type") in gone or sp.get("to_type") in gone:
            bucket.pop(k)
    for k, p in bucket.items():
        if k[0] != "object_type":
            continue
        spec = p.setdefault("spec", {})
        managed = bool(spec.pop("managed", False))
        lc = spec.pop("lifecycle", None)
        if isinstance(lc, dict) and _attach_lifecycle(p, lc):
            out["lifecycles"] += 1
        if p.get("bindings"):
            out["bound"] += 1
        elif managed:
            p["bindings"] = [{"ds_id": 0, "target_kind": "table", "ref": {"kind": "managed"}}]
            out["managed"] += 1
        else:
            out["unbound"] += 1
    return out


def _attach_lifecycle(p: dict, lc: dict) -> bool:
    states = [str(x).strip() for x in lc.get("states") or [] if str(x).strip()]
    if len(states) < 2:
        return False
    spec = p["spec"]
    props = spec.setdefault("properties", [])
    want = str(lc.get("property") or "状态").strip()
    hit = next((x for x in props if want in (x.get("name"), x.get("display_name"))), None) \
        or next((x for x in props if x.get("enum_values") and set(states) <= set(x["enum_values"])), None)
    if hit is None:
        hit = {"name": want, "data_type": "enum", "enum_values": states}
        if p.get("bindings"):
            hit["storage"] = "ontology"           # 业务表里没有这一列:状态由本系统保存
        props.append(hit)
    trans = []
    for t in lc.get("transitions") or []:
        frm = [str(x).strip() for x in (t.get("from") or []) if str(x).strip() in states]
        to = str(t.get("to") or "").strip()
        if frm and to in states:
            trans.append({"from": frm, "to": to, "action": str(t.get("action") or "").strip()})
    hit["lifecycle"] = {"states": [{"value": x} for x in states], "transitions": trans, "initial": states[0]}
    return True


_ENUM_SPLIT = re.compile(r"[//、||,,]")


def _column_enum(desc: str) -> tuple[str, list[str]]:
    """列注释「状态:待审批/已下单/已到货」→ ("状态", [待审批, 已下单, 已到货]);不是这种写法就原样返回、没有可选值。"""
    m = re.match(r"^\s*([^::]{1,20})[::]\s*(.+?)\s*$", desc or "")
    if m:
        items = [x.strip() for x in _ENUM_SPLIT.split(m.group(2)) if x.strip()]
        if len(items) >= 2 and all(len(x) <= 12 for x in items):
            return m.group(1).strip(), items
    return (desc or "").strip(), []


def datasource_proposals(ds_id: int) -> list[dict]:
    """把内省好的语义模型翻译成本体提议:表 → 对象 + 表绑定,表间关联 → 关系 + join 绑定。

    指标(聚合函数)不从库里猜:同一张表能算出几十个数,哪些是业务真正关心的只有人知道 ——
    用「一句话生成函数」或从文档提议。
    """
    from ..text2sql import semantic
    models = semantic.models_with_columns(ds_id, enabled_only=True)
    proposals: list[dict] = []
    rels = semantic.list_relations(ds_id, enabled_only=True)
    for m in models:
        cols = m.get("columns") or []
        phys = {c["name"]: (c.get("physical_column") or c["name"]) for c in cols}
        key = m.get("primary_key") or next((c["name"] for c in cols if c["name"].lower() == "id"), "")
        if not key:
            continue
        # 没有名称列、又指向别的表的(明细、余额这类几张表的组合)不拿主键当名称:读的时候用它指向的对象的名称拼一个
        label_col = next((c["name"] for c in cols if any(
            t in c["name"].lower() for t in ("name", "title", "label"))), "")
        if not label_col and not any(r["from_model_id"] == m["id"] for r in rels):
            label_col = key
        props = []
        for c in cols[:40]:
            ctype = (c.get("data_type") or "").lower()
            dt_ = "number" if c.get("is_measure") or any(t in ctype for t in ("int", "dec", "double", "float")) \
                else "date" if "date" in ctype or "time" in ctype else "string"
            label, enum = _column_enum(c.get("description") or "")
            if enum:
                dt_ = "enum"
            # 取值不多的文字列(品类、城市、状态)常用来分组;主键、名称这种一行一个值的不算
            few = (dt_ in ("string", "enum") and c["name"] not in (key, label_col)
                   and (enum or 0 < int(c.get("distinct_count") or 0) <= 12))
            props.append({"name": c["name"], "display_name": label[:40],
                          "data_type": dt_, "is_key": c["name"] == key,
                          "is_time": dt_ == "date", "is_dimension": bool(few), "enum_values": enum,
                          "description": c.get("description") or ""})
        name = re.split(r"[((,,。;;]", m.get("description") or "")[0].strip()[:30] or m["name"]
        proposals.append({
            "kind": "object_type", "name": name, "synonyms": [m["name"]] if name != m["name"] else [],
            "description": m.get("description") or "",
            "spec": {"properties": props, "label_property": label_col},
            "bindings": [{"ds_id": ds_id, "target_kind": "table",
                          "ref": {"table": m["physical_table"] or m["name"],
                                  "key_column": phys.get(key, key),
                                  "label_column": phys.get(label_col, label_col) if label_col else "",
                                  "columns": {p["name"]: phys.get(p["name"], p["name"])
                                              for p in props}}}],
            "confidence": 0.8})
    names = {m["id"]: next((x["name"] for x in proposals
                            if x["bindings"][0]["ref"]["table"] == (m["physical_table"] or m["name"])), "")
             for m in models}
    pairs = collections.Counter((names.get(r["from_model_id"]), names.get(r["to_model_id"])) for r in rels)
    for r in rels:
        a, b = names.get(r["from_model_id"]), names.get(r["to_model_id"])
        if not a or not b or a == b:
            continue
        # 同一对表之间有两条关联(调出方、调入方这种):名字带上关联列,否则会被当成同一条合并掉
        name = f"{a}-{b}" if pairs[(a, b)] == 1 else f"{a}-{b}({r['from_column']})"
        proposals.append({
            "kind": "link_type", "name": name, "description": r.get("description") or "",
            "spec": {"from_type": a, "to_type": b, "cardinality": (r.get("cardinality") or "n:1").lower()},
            "bindings": [{"ds_id": ds_id, "target_kind": "join",
                          "ref": {"from_column": r["from_column"], "to_column": r["to_column"]}}],
            "confidence": 0.75})
    return proposals


# ---------------- 审核处理器 ----------------
def _resolve_refs(kind: str, spec: dict) -> dict:
    """spec 里按名称引用的元素,能找到的换成 id(找不到保留名称,运行时仍可按名称解析)。"""
    ref_fields = {"function": [("calibre_rule", "function"), ("object_type", "object_type")],
                  "link_type": [("from_type", "object_type"), ("to_type", "object_type")],
                  "action": [("target_type", "object_type")]}
    for field, k in ref_fields.get(kind, []):
        v = spec.get(field)
        if v:
            found = service.find(str(v), k)
            if found:
                spec[field] = found["id"]
    return spec


def _accept_create(payload: dict, item: dict) -> dict:
    kind = payload["kind"]
    # 提议之后,别的提议可能已经被采纳、并把这个名字当成了别名(如「二级品牌」带别名「品牌」)。
    # 这时合并进已有概念(补别名与出处),而不是让采纳失败。
    existing = service.find(payload["name"], kind)
    if existing:
        syn = list(dict.fromkeys([*(existing.get("synonyms") or []), payload["name"],
                                  *(payload.get("synonyms") or [])]))
        syn = [s for s in syn if s != existing["name"]]
        service.update_concept(existing["id"], synonyms=syn)
        if payload.get("evidence"):
            service.add_evidence(existing["id"], payload["evidence"])
        return {"concept_id": existing["id"], "name": existing["name"], "merged": True}
    spec = _resolve_refs(kind, dict(payload.get("spec") or {}))
    desc = payload.get("description", "")
    if kind == "action" and spec.get("_stub"):
        # 文档只说明了「要有这个动作」:建成待补全的草稿。效果先设成「派一项待办」——
        # 批准后至少会真的落成一件有人跟进的事,而不是只发一条通知就结束。
        text = spec.get("text") or desc
        desc = f"{desc}(AI 从文档提议,请补全参数与效果:{text})" if text and text != desc else desc
        spec = {"target_type": "", "params": [{"name": "reason", "label": "原因", "type": "text",
                                                "required": True}],
                "effects": [{"tool": "task.create", "args": {"title": payload["name"], "role": "operator",
                                                             "description": "$reason"}}],
                "approval": {"mode": "manual", "approver_roles": []}}
    c = service.create_concept(kind, payload["name"], display_name=payload.get("display_name", ""),
                               description=desc,
                               synonyms=payload.get("synonyms"), spec=spec,
                               origin=(item.get("source") or "ai").split(":")[0][:24],
                               evidence=payload.get("evidence"),
                               bindings=payload.get("bindings"))
    return {"concept_id": c["id"], "name": c["name"]}


def _accept_update(payload: dict, item: dict) -> dict:
    cid = payload["concept_id"]
    fields = {k: payload[k] for k in ("name", "display_name", "description", "synonyms", "spec")
              if k in payload}
    c = service.update_concept(cid, **fields)
    return {"concept_id": cid, "name": c["name"]}


def _accept_conflict(payload: dict, item: dict) -> dict:
    """冲突采纳 = 用提议的定义覆盖;驳回 = 保留现有定义。payload.choice 可显式选 current。"""
    cid = payload["concept_id"]
    if payload.get("choice") == "current":
        return {"concept_id": cid, "kept": "current"}
    prop = payload.get("proposed") or {}
    c = service.update_concept(cid, spec=prop.get("spec"),
                               description=prop.get("description") or None)
    if payload.get("evidence"):
        service.add_evidence(cid, payload["evidence"])
    return {"concept_id": cid, "kept": "proposed", "name": c["name"]}


def _accept_binding(payload: dict, item: dict) -> dict:
    b = service.set_binding(payload["concept_id"], int(payload.get("ds_id") or 0),
                            payload["target_kind"], payload.get("ref") or {})
    return {"binding_id": b["id"]}


review.register_handler("concept_create", _accept_create)
review.register_handler("concept_update", _accept_update)
review.register_handler("conflict", _accept_conflict)
review.register_handler("binding", _accept_binding)