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

- 文档:按段落分批喂给 LLM,让它按四元组(对象 / 关系 / 函数 / 动作)找积木,
  每条提议都带出处 chunk,采纳后成为积木的证据。文中的角色顺带登记为业务角色。
- 数据源:内省出来的表与关联是确定性的,直接翻译成对象 + 绑定、关系 + 绑定。
- 与已有积木同名:说法一致就只补证据;规则/周期的定义不一致则提「知识冲突」让人裁决。
"""
from __future__ import annotations

import logging
import re
from typing import Iterator

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

log = logging.getLogger(__name__)

BATCH_TOKENS = 3200

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

积木(kind)与 spec:
- object_type 对象:可被指认、有属性、会有多个实例的东西(组织、单据、批次、人员、产品)。
  spec: {"properties":[{"name":属性名,"data_type":"string|number|date|enum|boolean","is_key":bool,
         "is_dimension":是否常用来分组/拆分,"enum_values":[...]}]}
- link_type 关系:两个对象之间的关系。spec: {"from_type":对象名,"to_type":对象名,"cardinality":"1:1|1:n|n:1|n:n"}
- function 函数:对对象的计算,spec.category 取下面之一:
  - aggregate 聚合(指标):能算出一个数的度量(量、率、额、系数、差额、单价)。
    spec: {"category":"aggregate","object_type":对象名,"unit":单位,"direction":"higher_better|lower_better|neutral",
           "calibre_rule":口径规则名,"calendar":统计周期名,"formula_text":文字版计算公式}
  - rule 规则:判定条件、计算方法、口径约定、例外处理。
    spec: {"category":"rule","rule_kind":"judgement|calibre|calculation","params":[英文变量名],
           "expression":"用这些变量写的 Python 风格表达式,如 actual >= target;写不出就留空","text":规则原文要点}
  - decision 决策表:按多个条件分档 / 分级 / 打分。
    spec: {"category":"decision","inputs":[{"name":英文名,"label":中文}],"outputs":[{"name":英文名,"label":中文}],
           "rows":[{"when":{输入名:"> 3"},"then":{输出名:值}}],"text":原文要点}
  - calendar 周期:统计时间窗口(自然月、财务月、执行期、对照期)。
    spec: {"category":"calendar","start_day":1-31,"start_month_offset":整数,"end_day":1-31或"last","end_month_offset":整数,
           "applies_when":适用条件,"text":原文要点}
    例:「上月 26 日至本月 25 日」→ start_day=26,start_month_offset=-1,end_day=25,end_month_offset=0
- action 动作:文中明确要求「由某人对某对象做某事」的业务操作(标记、派发、通知、变更状态)。
  spec: {"target_type":对象名,"description_only":true,"text":要做什么、谁来审批}
  (动作的执行细节由人补全,这里只提议它存在)

另外:文中出现的岗位 / 职责主体,放进顶层 "roles":[{"name":角色名,"description":职责}],不要当成积木。
name 用文档里的中文业务叫法(如「机台」「批次」);英文名、代码名、缩写一律放进 synonyms。
术语、缩写、别称不要单独建积木,写进被指向积木的 synonyms。流程(有先后步骤的事)不要建积木,会另行生成流程卡。

判定要点:
- 能算出一个数的一律 function/aggregate —— 即使文中给了公式;公式写进 formula_text,计算规则另提一条 function/rule。
- 分档、分级、按区间给分的规则优先用 function/decision。

输出严格 JSON:
{"concepts":[{"kind":..., "name":规范名称, "synonyms":[文中出现的其他叫法], "description":一句话定义,
  "spec":{...}, "evidence":[出处片段编号,如 "d1:c3"], "confidence":0~1}],
 "roles":[{"name":..., "description":...}]}
"""

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

文档片段:
{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)


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.upgrade(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 "")}
    key = _bucket_key(bucket, kind, name, item.get("synonyms") or [])
    ev = []
    for cid in item.get("evidence") or []:
        ch = chunk_map.get(str(cid))
        if ch:
            ev.append({"chunk_id": ch["id"], "doc_id": ch.get("doc_id", 0),
                       "heading": ch.get("heading", ""), "snippet": ch.get("text", "")[:400]})
    cur = bucket.get(key)
    if cur is None:
        bucket[key] = {"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)}
        return
    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 _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]}
    for (k, n), cur in bucket.items():
        if k == kind and ({n, cur["name"]} & names or names & set(cur.get("synonyms") or [])):
            return (k, n)
    return (kind, name)


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")}
    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")
        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)
            merged += 1
            break
    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 == "calendar":
        return f"{spec.get('start_day')}/{spec.get('start_month_offset')}-{spec.get('end_day')}/{spec.get('end_month_offset')}"
    return ""


def submit_proposals(proposals: list[dict], source: str) -> dict:
    """把一批提议送进审核队列(或补证据 / 提冲突)。返回计数。"""
    created = conflicts = enriched = 0
    for p in proposals:
        up = schema.upgrade(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 = {"category": raw.get("category")} if p["kind"] == "function" else {}
                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}


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

    source:提议的来源标记(业务建模用 `modeling:<run_id>` 找回自己这次的草案);
    hint:行业路由给的先验(参考模板里的常见积木名),只帮助命名,不强加内容;
    seed:已接入数据表翻译出的对象 / 关系(带绑定)。文档里说的是同一个东西时并进去,
          草案一出来就绑好了表,不会出现「文档一套对象、数据表又一套对象」。
    """
    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}
                    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['name']}(表 {p['bindings'][0]['ref']['table']},列 "
              f"{'、'.join(list(p['bindings'][0]['ref'].get('columns') or {})[:12])})"
              for p in seed or [] if p["kind"] == "object_type"]
    if tables:
        existing += ("\n\n已接入的数据表(文档里指的是同一个东西时,对象名必须沿用这里的名称,"
                     "关系的两端也用这些名称):\n" + "\n".join(tables))
    with llmlog.feature("ontology_propose"):
        for i, batch in enumerate(batches, 1):
            text = "\n\n".join(f"[{c['id']}]【{c.get('heading') or '正文'}】\n{c['text']}" for c in batch)
            try:
                res = llm.chat_json([{"role": "system", "content": PROPOSE_SYSTEM},
                                     {"role": "user", "content": PROPOSE_USER.format(
                                         existing=existing, text=text)}])
            except Exception as e:  # noqa: BLE001
                yield {"stage": "propose", "message": f"第 {i} 批失败:{str(e)[:200]}",
                       "progress": int(i / len(batches) * 90)}
                continue
            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 ""))
            yield {"stage": "propose", "message": f"第 {i}/{len(batches)} 批,累计 {len(bucket)} 个候选",
                   "progress": int(i / len(batches) * 90)}
    aligned = _align_links(bucket)
    for p in bucket.values():
        p.pop("_seed", None)
    stats = submit_proposals(list(bucket.values()), source)
    stats["bound"] = sum(1 for p in bucket.values() if p.get("bindings"))
    stats["aligned_links"] = aligned
    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 from_datasource(ds_id: int) -> dict:
    return submit_proposals(datasource_proposals(ds_id), "introspect")


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] = []
    by_id = {m["id"]: m for m in models}
    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"))), "")
        props = []
        for c in cols[:40]:
            dt_ = "number" if c.get("is_measure") or any(
                t in (c.get("data_type") or "").lower() for t in ("int", "dec", "double", "float")) \
                else "date" if "date" in (c.get("data_type") or "").lower() or "time" in (c.get("data_type") or "").lower() \
                else "string"
            props.append({"name": c["name"], "display_name": (c.get("description") or "")[:40],
                          "data_type": dt_, "is_key": c["name"] == key,
                          "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),
                                  "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}
    for r in semantic.list_relations(ds_id, enabled_only=True):
        a, b = names.get(r["from_model_id"]), names.get(r["to_model_id"])
        if not a or not b or a == b:
            continue
        proposals.append({
            "kind": "link_type", "name": f"{a}-{b}", "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"), ("calendar", "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": "notify.send", "args": {"recipient": "role:approver",
                                                             "title": payload["name"],
                                                             "body": "$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)