modeling.py 36 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
"""业务建模管道:一张经业务专家梳理过的业务文档 → 四元组草案 + 流程卡草稿。

  输入(知识库文档 / 临时上传)
   → ① 行业路由:选一个行业模板当先验(只帮助命名,不强加内容)
   → ① 数据对齐:已接入的数据表翻译成对象 / 关系(带表绑定),作为 LLM 转换的种子
   → ② LLM 转换:按四元组找积木,每条带出处(kernel/propose.from_documents);
                 文档里说的是同一张表时并进种子,草案一出来就绑好了表
   → ③ 规则深化:文字规则 / 决策表写成可求值的表达式与表格;指标写出取数表达式并在业务库实跑;
                 动作骨架补全成参数 + 前置条件 + 效果。确定性校验不过就不采用
   → ④ SOP 编排:从同一批文档蒸馏出可执行的流程卡草稿(sop/draft)
   → ⑤ 建草稿:汇总成四列草案(对象 / 关系 / 函数 / 动作),人审核微调后采纳

每次运行存一条 `onto_model_run`,阶段进度实时写回,页面刷新也不丢。
AI 只产出草案:积木进审核队列,流程卡是草稿,都要人确认、再经变更提案发布才生效。
"""
from __future__ import annotations

import logging
import re
import tempfile
from pathlib import Path
from typing import Iterator

from fastapi import HTTPException
from sqlalchemy import select

from ..core import identity, llm
from ..core.dbx import iso, jdump, jload, new_id, session
from ..governance import audit, llmlog, review
from . import propose, schema, service, templates
from .models import ModelRun

log = logging.getLogger(__name__)

STAGES = [
    {"key": "route", "label": "行业路由", "desc": "识别行业,选参考模板作为命名先验"},
    {"key": "data", "label": "数据对齐", "desc": "读取已接入的数据表,对象与关系直接绑定到表"},
    {"key": "convert", "label": "LLM 转换", "desc": "按四元组抽取对象、关系、函数、动作,带出处"},
    {"key": "deepen", "label": "规则深化", "desc": "文字规则 → 可求值表达式 / 决策表,确定性校验"},
    {"key": "sop", "label": "SOP 编排", "desc": "蒸馏可执行的流程卡草稿"},
    {"key": "draft", "label": "建草稿", "desc": "汇总四元组草案,等人审核采纳"},
]
MAX_DEEPEN = 12
MAX_SOPS = 5


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


def _source(run_id: str) -> str:
    return f"modeling:{run_id}"


def _dict(r: ModelRun, full: bool = False) -> dict:
    inputs = jload(r.inputs_json, {}) or {}
    out = {"id": r.id, "title": r.title, "status": r.status, "job_id": r.job_id, "error": r.error or "",
           "options": jload(r.options_json, {}) or {}, "stages": jload(r.stages_json, []) or [],
           "counts": jload(r.counts_json, {}) or {}, "created_by": r.created_by,
           "created_at": iso(r.created_at), "updated_at": iso(r.updated_at),
           "inputs": {"doc_ids": inputs.get("doc_ids") or [],
                      "files": [f["name"] for f in inputs.get("files") or []],
                      "chunks": len(inputs.get("chunks") or [])}}
    if full:
        out["sop_ids"] = inputs.get("sop_ids") or []
    return out


def _load(run_id: str) -> ModelRun:
    with session() as s:
        r = s.get(ModelRun, run_id)
        if r is None or r.workspace != _ws():
            raise HTTPException(404, "建模记录不存在")
        s.expunge(r)
        return r


def list_runs() -> list[dict]:
    with session() as s:
        rows = s.scalars(select(ModelRun).where(ModelRun.workspace == _ws())
                         .order_by(ModelRun.created_at.desc())).all()
        return [_dict(r) for r in rows]


def get(run_id: str) -> dict:
    """运行记录 + 本次草案(按四种积木分列)+ 流程卡草稿。"""
    out = _dict(_load(run_id), full=True)
    items = review.list_items(status="", source=_source(run_id), limit=1000)["items"]
    cols: dict[str, list] = {"object_type": [], "link_type": [], "function": [], "action": [], "other": []}
    for it in items:
        p = it["payload"] or {}
        k = p.get("kind") if it["kind"] == "concept_create" else "other"
        cols.setdefault(k if k in cols else "other", []).append(it)
    out["items"] = cols
    from ..sop import service as sop_service
    sops = []
    for sid in out.pop("sop_ids"):
        try:
            d = sop_service.get(sid)
            sops.append({k: d[k] for k in ("id", "title", "description", "status", "step_count")})
        except HTTPException:
            continue
    out["sops"] = sops
    return out


# ---------------- 输入 ----------------
def _upload_chunks(run_id: str, files: list[tuple[str, bytes]]) -> tuple[list[dict], list[dict]]:
    """临时上传:只解析、切块,不进知识库,也不抽图谱。"""
    from ..ingest.chunk import chunk_text
    from ..ingest.parse import ParseError, parse_file
    chunks, meta = [], []
    tag = run_id.split("_")[-1][:6]
    for i, (name, raw) in enumerate(files):
        suffix = Path(name).suffix.lower() or ".txt"
        with tempfile.TemporaryDirectory() as tmp:
            path = Path(tmp) / f"upload{suffix}"
            path.write_bytes(raw)
            try:
                doc = parse_file(path)
            except ParseError as e:
                raise HTTPException(400, f"「{name}」解析失败:{e}") from e
        for n, c in enumerate(chunk_text(doc.text, 0)):
            c["id"] = f"u{tag}{i}:c{n}"
            c["heading"] = c.get("heading") or name
            c["doc_id"] = 0
            chunks.append({k: c[k] for k in ("id", "heading", "text", "doc_id")})
        meta.append({"name": name, "size": len(raw)})
    return chunks, meta


def _doc_chunks(doc_ids: list[int]) -> list[dict]:
    from ..api import deps
    want = {int(x) for x in doc_ids}
    return [c for c in deps.index().chunks.records if c.get("doc_id") in want]


def _default_ds_ids() -> list[int]:
    """当前本体可见、已经内省过的数据源。"""
    from ..text2sql import semantic
    return [d["id"] for d in semantic.list_datasources() if d.get("last_introspect_at")]


def create(title: str, *, doc_ids: list[int] | None = None, files: list[tuple[str, bytes]] | None = None,
           template: str = "", stages: list[str] | None = None, ds_ids: list[int] | None = None) -> dict:
    """ds_ids:参与「数据对齐」的数据源;None = 当前本体下所有已内省的数据源。"""
    run_id = new_id("mr")
    up_chunks, up_meta = _upload_chunks(run_id, files or [])
    if not doc_ids and not up_chunks:
        raise HTTPException(422, "请选择知识库文档或上传业务文档")
    keys = [s["key"] for s in STAGES]
    chosen = [k for k in (stages or keys) if k in keys]
    for must in ("convert", "draft"):
        if must not in chosen:
            chosen.append(must)
    stage_rows = [{**s, "status": "pending" if s["key"] in chosen else "skipped", "log": [],
                   "counts": {}} for s in STAGES]
    actor = identity.current()
    with session() as s:
        s.add(ModelRun(id=run_id, workspace=actor.workspace, title=(title or "业务建模")[:255],
                       inputs_json=jdump({"doc_ids": list(doc_ids or []), "files": up_meta,
                                          "chunks": up_chunks}),
                       options_json=jdump({"template": template or "", "stages": chosen,
                                           "ds_ids": _default_ds_ids() if ds_ids is None else ds_ids}),
                       stages_json=jdump(stage_rows), status="draft", created_by=actor.id))
        s.commit()
    audit.record("modeling.create", "model_run", run_id, f"新建业务建模「{title}」")
    return _dict(_load(run_id))


def start(run_id: str) -> dict:
    r = _load(run_id)
    if r.status == "running":
        raise HTTPException(409, "这次建模正在运行")
    from ..jobs.queue import submit_background
    try:
        job_id = submit_background("modeling", lambda: execute(run_id))
    except RuntimeError as e:
        raise HTTPException(503, str(e)) from e
    with session() as s:
        row = s.get(ModelRun, run_id)
        row.job_id = job_id
        row.status = "running"
        row.error = ""
        s.commit()
    return _dict(_load(run_id))


def delete(run_id: str) -> None:
    _load(run_id)
    with session() as s:
        s.delete(s.get(ModelRun, run_id))
        s.commit()


# ---------------- 执行 ----------------
class _Stages:
    """阶段状态落库:每条日志都写回 stages_json,前端轮询运行记录即可看到进度。"""

    def __init__(self, run_id: str):
        self.run_id = run_id
        self.rows = jload(_load(run_id).stages_json, []) or []

    def _save(self) -> None:
        with session() as s:
            row = s.get(ModelRun, self.run_id)
            row.stages_json = jdump(self.rows)
            s.commit()

    def row(self, key: str) -> dict:
        return next(r for r in self.rows if r["key"] == key)

    def active(self, key: str) -> bool:
        return self.row(key)["status"] != "skipped"

    def set(self, key: str, status: str, msg: str = "", **counts) -> None:
        r = self.row(key)
        r["status"] = status
        if msg:
            r["log"] = (r["log"] + [msg])[-30:]
        if counts:
            r["counts"] = {**r["counts"], **counts}
        self._save()


def _finish(run_id: str, status: str, error: str = "", counts: dict | None = None) -> None:
    with session() as s:
        row = s.get(ModelRun, run_id)
        row.status = status
        row.error = error[:2000]
        if counts is not None:
            row.counts_json = jdump(counts)
        s.commit()


def execute(run_id: str) -> Iterator[dict]:
    st = _Stages(run_id)
    run = _load(run_id)
    inputs = jload(run.inputs_json, {}) or {}
    opts = jload(run.options_json, {}) or {}
    chunks = _doc_chunks(inputs.get("doc_ids") or []) + (inputs.get("chunks") or [])
    chunks = [c for c in chunks if (c.get("text") or "").strip()]
    if not chunks:
        _finish(run_id, "failed", "没有可用的文档片段:知识库文档要先完成解析")
        yield {"stage": "error", "error": "没有可用的文档片段"}
        return
    try:
        hint = ""
        if st.active("route"):
            st.set("route", "running", f"共 {len(chunks)} 个片段")
            tpl, why = _route(chunks, opts.get("template") or "")
            hint = _template_hint(tpl) if tpl else ""
            st.set("route", "done", f"参考模板:{tpl or '无(按文档原样建模)'}{(',' + why) if why else ''}",
                   template=tpl or "")
            yield {"stage": "route", "progress": 5, "message": f"行业路由:{tpl or '无'}"}

        seed: list[dict] = []
        if st.active("data"):
            st.set("data", "running")
            for ds_id in opts.get("ds_ids") or []:
                try:
                    seed += propose.datasource_proposals(int(ds_id))
                except Exception as e:  # noqa: BLE001
                    st.set("data", "running", f"数据源 #{ds_id} 读取失败:{str(e)[:120]}")
            objs = [p["name"] for p in seed if p["kind"] == "object_type"]
            links = sum(1 for p in seed if p["kind"] == "link_type")
            st.set("data", "done", f"{len(objs)} 张表 → 对象({'、'.join(objs[:8])}),{links} 条表间关联"
                   if seed else "没有已内省的数据表:对象先不绑定,之后在对象页绑定", tables=len(objs), joins=links)
            yield {"stage": "data", "progress": 8, "message": f"数据对齐:{len(objs)} 张表"}

        st.set("convert", "running")
        result = {}
        for ev in propose.from_documents(chunks, source=_source(run_id), hint=hint, seed=seed):
            if ev.get("message"):
                st.set("convert", "running", ev["message"])
            if ev.get("stage") == "done":
                result = ev.get("result") or {}
            yield {**ev, "stage": "convert", "progress": 5 + int((ev.get("progress") or 0) * 0.55)}
        st.set("convert", "done", f"提议 {result.get('proposed', 0)} 块新积木({result.get('bound', 0)} 块已绑定数据表)、"
                                  f"{result.get('conflicts', 0)} 个冲突",
               **{k: v for k, v in result.items() if isinstance(v, int)})

        if st.active("deepen"):
            st.set("deepen", "running")
            note = lambda m: st.set("deepen", "running", m)  # noqa: E731
            n, tried = _deepen(run_id, note)
            bound, btried = _bind_metrics(run_id, note)
            acts, atried = _complete_actions(run_id, note)
            st.set("deepen", "done", f"深化 {n}/{tried} 条规则与决策表,绑定 {bound}/{btried} 个指标的取数表达式,"
                                     f"补全 {acts}/{atried} 个动作", deepened=n, tried=tried,
                   metrics_bound=bound, actions_completed=acts)
            yield {"stage": "deepen", "progress": 75, "message": f"规则深化 {n} 条"}

        if st.active("sop"):
            st.set("sop", "running")
            sop_ids = _sops(chunks, lambda m: st.set("sop", "running", m), run_id)
            with session() as s:
                row = s.get(ModelRun, run_id)
                inp = jload(row.inputs_json, {}) or {}
                inp["sop_ids"] = sop_ids
                row.inputs_json = jdump(inp)
                s.commit()
            st.set("sop", "done", f"生成 {len(sop_ids)} 张流程卡草稿", sops=len(sop_ids))
            yield {"stage": "sop", "progress": 92, "message": f"流程卡 {len(sop_ids)} 张"}

        g = get(run_id)
        counts = {k: len(v) for k, v in g["items"].items()}
        counts["sop"] = len(g["sops"])
        st.set("draft", "done", "四元组草案:" + "、".join(
            f"{schema.KINDS[k]['label']} {counts[k]}" for k in schema.KINDS), **counts)
        _finish(run_id, "done", counts=counts)
        audit.record("modeling.done", "model_run", run_id, f"业务建模完成:{counts}")
        yield {"stage": "done", "progress": 100, "message": "建模完成", "result": counts}
    except Exception as e:  # noqa: BLE001
        log.exception("业务建模 %s 失败", run_id)
        for r in st.rows:
            if r["status"] == "running":
                r["status"] = "failed"
        st._save()
        _finish(run_id, "failed", str(getattr(e, "detail", e))[:500])
        yield {"stage": "error", "error": str(getattr(e, "detail", e))[:300]}


# ---------------- ① 行业路由 ----------------
ROUTE_PROMPT = """下面是一份业务文档的章节标题。从候选行业模板里选一个最贴近的,没有合适的就选 none。
候选:
{cands}

章节:
{heads}

输出 JSON:{{"template":"模板 id 或 none","reason":"一句话"}}"""


def _route(chunks: list[dict], chosen: str) -> tuple[str, str]:
    tpls = {t["id"]: t for t in templates.list_templates()}
    if chosen:
        if chosen not in tpls and chosen != "none":
            raise HTTPException(422, f"模板「{chosen}」不存在")
        return ("" if chosen == "none" else chosen), "人工指定"
    cands = [t for t in tpls.values() if t["id"] != "generic_starter"]
    if not cands:
        return "", ""
    heads = list(dict.fromkeys(c.get("heading") or "" for c in chunks))[:60]
    try:
        with llmlog.feature("modeling_route"):
            res = llm.chat_json([{"role": "user", "content": ROUTE_PROMPT.format(
                cands="\n".join(f"- {t['id']}:{t['name']},{t['description']}" for t in cands),
                heads="\n".join(f"- {h}" for h in heads if h))}], temperature=0)
    except Exception as e:  # noqa: BLE001
        log.warning("行业路由失败:%s", e)
        return "", ""
    tid = str((res or {}).get("template") or "") if isinstance(res, dict) else ""
    return (tid if tid in tpls else ""), str((res or {}).get("reason") or "") if isinstance(res, dict) else ""


def _template_hint(tid: str, limit: int = 120) -> str:
    import yaml
    p = templates.TEMPLATE_DIR / f"{tid}.yaml"
    try:
        doc = yaml.safe_load(p.read_text(encoding="utf-8")) or {}
    except Exception:  # noqa: BLE001
        return ""
    return "、".join(str(c.get("name")) for c in (doc.get("concepts") or [])[:limit] if c.get("name"))


# ---------------- ③ 规则深化 ----------------
DEEPEN_PROMPT = """把下面这条业务规则写成可执行的定义。
名称:{name}
类别:{category}
原文要点:{text}
说明:{desc}

- rule:写成 Python 风格表达式,变量用英文标识符,例如 actual >= target * 0.9;只能用算术、比较、and/or/not、
  min/max/abs/round、if-else 表达式。输出 {{"expression":"...","params":["变量名"]}}
- decision:写成决策表。输出 {{"inputs":[{{"name":英文名,"label":中文}}],"outputs":[{{"name":英文名,"label":中文}}],
  "rows":[{{"when":{{输入名:"> 3"}},"then":{{输出名:值}}}}]}}
原文信息不足以写出时输出 {{"skip":true}}。只输出 JSON。"""


def _deepen(run_id: str, note) -> tuple[int, int]:
    items = review.list_items(status="pending", kind="concept_create", source=_source(run_id),
                              limit=500)["items"]
    todo = []
    for it in items:
        p = it["payload"] or {}
        spec = p.get("spec") or {}
        if p.get("kind") != "function":
            continue
        cat = spec.get("category")
        if (cat == "rule" and not spec.get("expression")) or (cat == "decision" and not spec.get("rows")):
            todo.append(it)
    done = 0
    for it in todo[:MAX_DEEPEN]:
        p = dict(it["payload"])
        spec = dict(p.get("spec") or {})
        try:
            with llmlog.feature("modeling_deepen"):
                res = llm.chat_json([{"role": "user", "content": DEEPEN_PROMPT.format(
                    name=p["name"], category=spec.get("category"), text=spec.get("text") or "",
                    desc=p.get("description") or "")}], temperature=0.1)
        except Exception as e:  # noqa: BLE001
            note(f"「{p['name']}」深化失败:{str(e)[:80]}")
            continue
        if not isinstance(res, dict) or res.get("skip"):
            note(f"「{p['name']}」原文信息不足,保留文字描述")
            continue
        try:
            new_spec = schema.normalize_spec("function", {**spec, **res})
        except schema.SpecError as e:
            note(f"「{p['name']}」深化结果没通过校验({e}),不采用")
            continue
        p["spec"] = new_spec
        p["deepened"] = True
        review.update_payload(it["id"], p)
        done += 1
        note(f"「{p['name']}」已写成{'表达式' if spec.get('category') == 'rule' else '决策表'}")
    return done, min(len(todo), MAX_DEEPEN)


METRIC_PROMPT = """把下面这个指标写成一条 SQL 聚合表达式,基于数据表 {table}(方言 {dialect})。
指标:{name}(单位:{unit})
口径:{formula}
说明:{desc}
表的列(列名 类型 含义):
{columns}

要求:
- expression 是 SELECT 里的一个聚合表达式,只能用这张表的列,如 SUM(on_hand + in_transit)、
  AVG(CASE WHEN a < b THEN 1.0 ELSE 0 END)、COUNT(*)。单位是 % 时算成 0~100 的数。
- 这张表的列算不出这个口径(需要别的表)时输出 {{"skip": true, "reason": "一句话"}}。
- dimensions:可以按哪些列拆分,{{属性名: 列名}},挑 2~4 个类别型的列(编号、状态、品类、城市等)。
- time_column:口径涉及时间窗口且表里有日期列时填,否则空串。
- object_key_column:按单个对象取数用的键列,一般是主键。
- filters:口径里固定的过滤条件(SQL 片段数组,如 "status = '已到货'"),没有就空数组。
只输出 JSON:{{"expression":"...","dimensions":{{}},"time_column":"","object_key_column":"","filters":[]}}"""


def _run_objects(run_id: str) -> dict[str, dict]:
    """这次草案 + 已有积木里的对象:名称 / 别名 → {name, properties, binding}。"""
    out: dict[str, dict] = {}
    for c in service.list_concepts(kind="object_type", limit=300):
        full = service.get_concept(c["id"])
        b = next((x for x in full.get("bindings") or [] if x["target_kind"] == "table"), None)
        rec = {"name": c["name"], "id": c["id"], "properties": (full.get("spec") or {}).get("properties") or [],
               "binding": b, "item": None}
        for n in [c["id"], c["name"], *(c.get("synonyms") or [])]:
            out[n] = rec
    items = review.list_items(status="pending", kind="concept_create", source=_source(run_id), limit=500)["items"]
    for it in items:
        p = it["payload"] or {}
        if p.get("kind") != "object_type":
            continue
        b = next((x for x in p.get("bindings") or [] if x.get("target_kind") == "table"), None)
        rec = {"name": p["name"], "id": "", "properties": (p.get("spec") or {}).get("properties") or [],
               "binding": b, "item": it}
        for n in [p["name"], *(p.get("synonyms") or [])]:
            out[n] = rec
    return out


def _try_metric_sql(ds_id: int, table: str, ref: dict) -> str:
    """在业务库上真跑一次,跑得通才采用。返回错误信息,空串 = 通过。"""
    from ..text2sql import executor, semantic
    from .sqlutil import ident, to_dialect
    ds = semantic.get_datasource(ds_id) or {}
    sql = f"SELECT {ref['expression']} AS v FROM {ident(table)}"
    if ref.get("filters"):
        sql += " WHERE " + " AND ".join(f"({f})" for f in ref["filters"])
    out = executor.execute(ds_id, to_dialect(sql, ds.get("ds_type") or "mysql"), ds.get("ds_type") or "mysql")
    return "" if out.ok else str(out.error or "执行失败")[:300]


def _bind_metrics(run_id: str, note) -> tuple[int, int]:
    """聚合函数只有口径文字、没有取数方式。对象已经绑了表,就让 AI 写出取数表达式并实跑校验,
    省掉「人去绑定页手写 SQL」这一步;写不出或跑不通的保持未绑定,由人补。"""
    from ..text2sql import semantic
    objs = _run_objects(run_id)
    items = review.list_items(status="pending", kind="concept_create", source=_source(run_id), limit=500)["items"]
    todo = [it for it in items if (it["payload"] or {}).get("kind") == "function"
            and ((it["payload"].get("spec") or {}).get("category") == "aggregate")
            and not any(b.get("target_kind") == "metric_expr" for b in it["payload"].get("bindings") or [])]
    done = 0
    for it in todo[:MAX_DEEPEN]:
        p = dict(it["payload"])
        spec = p.get("spec") or {}
        obj = objs.get(str(spec.get("object_type") or ""))
        if not obj or not obj.get("binding"):
            note(f"「{p['name']}」的对象没有绑定数据表,取数表达式留给人补")
            continue
        b = obj["binding"]
        table = b["ref"]["table"]
        ds = semantic.get_datasource(int(b["ds_id"])) or {}
        cols = {c["name"]: c for m in semantic.models_with_columns(int(b["ds_id"]))
                if (m.get("physical_table") or m["name"]) == table for c in m.get("columns") or []}
        col_text = "\n".join(f"- {c.get('physical_column') or n} {c.get('data_type')} {c.get('description') or ''}"
                             for n, c in cols.items())
        msgs = [{"role": "user", "content": METRIC_PROMPT.format(
            table=table, dialect=ds.get("ds_type") or "mysql", name=p["name"], unit=spec.get("unit") or "",
            formula=spec.get("formula_text") or "", desc=p.get("description") or "", columns=col_text)}]
        ref: dict = {}
        err = ""
        for attempt in (1, 2):
            try:
                with llmlog.feature("modeling_metric"):
                    res = llm.chat_json(msgs, temperature=0.1)
            except Exception as e:  # noqa: BLE001
                err = str(e)[:120]
                break
            if not isinstance(res, dict) or res.get("skip"):
                err = (res or {}).get("reason") or "这张表算不出这个口径" if isinstance(res, dict) else "输出无效"
                break
            try:
                ref = schema.normalize_binding("metric_expr", {**res, "base_table": table})
            except schema.SpecError as e:
                err = str(e)
            else:
                err = _try_metric_sql(int(b["ds_id"]), table, ref)
            if not err:
                break
            msgs += [{"role": "assistant", "content": jdump(res)},
                     {"role": "user", "content": f"执行报错:{err}\n请修正后输出完整 JSON。"}]
        if err or not ref:
            note(f"「{p['name']}」没绑上取数表达式:{err}")
            continue
        p["bindings"] = [*(p.get("bindings") or []),
                         {"ds_id": int(b["ds_id"]), "target_kind": "metric_expr", "ref": ref}]
        review.update_payload(it["id"], p)
        done += 1
        note(f"「{p['name']}」= {ref['expression']}(已在业务库实跑通过)")
    return done, min(len(todo), MAX_DEEPEN)


def _complete_actions(run_id: str, note) -> tuple[int, int]:
    """文档只说明了「要有这个动作」。对象和系统效果都已知,就让 AI 写出参数、前置条件和效果,
    过一遍动作校验再采用;用到 object.write 的属性顺手标成可写,否则执行时才发现写不进去。"""
    from ..governance import roles
    from . import draft
    objs = _run_objects(run_id)
    items = review.list_items(status="pending", kind="concept_create", source=_source(run_id), limit=500)["items"]
    todo = [it for it in items if (it["payload"] or {}).get("kind") == "action"
            and (it["payload"].get("spec") or {}).get("_stub")]
    if not todo:
        return 0, 0
    seen, lines = set(), []
    for rec in objs.values():
        if id(rec) in seen:
            continue
        seen.add(id(rec))
        props = "、".join(f"{x['name']}({x.get('display_name') or x.get('description') or ''})"
                         for x in rec["properties"][:30])
        lines.append(f"- {rec['name']}:{props}")
    guide = (draft.GUIDES["action"].replace("{tools}", draft._tools_text())
             .replace("{roles}", "、".join(roles.names()) or "(无,可留空)"))
    system = draft.GENERATE_SYSTEM.format(guide=guide, objects="\n".join(lines) or "(无)",
                                          functions=draft._functions_text())
    done = 0
    for it in todo[:MAX_DEEPEN]:
        p = dict(it["payload"])
        msgs = [{"role": "system", "content": system},
                {"role": "user", "content": f"动作:{p['name']}\n说明:{p.get('description') or ''}\n"
                                            f"原文要点:{(p.get('spec') or {}).get('text') or ''}"}]
        spec, err = {}, ""
        for attempt in (1, 2, 3):
            try:
                with llmlog.feature("modeling_action"):
                    res = llm.chat_json(msgs, temperature=0.1)
            except Exception as e:  # noqa: BLE001
                err = str(e)[:120]
                break
            spec = dict((res or {}).get("spec") or {}) if isinstance(res, dict) else {}
            err = _check_action_refs(spec, objs)
            if not err:
                _open_writes(spec, objs)
                try:
                    schema.normalize_spec("action", spec)
                    break
                except schema.SpecError as e:
                    err = str(e)
            if err:
                msgs += [{"role": "assistant", "content": jdump(res)},
                         {"role": "user", "content": f"校验失败:{err}\n请修正后输出完整 JSON。"}]
        if err or not spec:
            note(f"「{p['name']}」没能补全:{err}(采纳后在动作页补)")
            continue
        p["spec"] = spec
        p["completed"] = True
        review.update_payload(it["id"], p)
        done += 1
        tools = "、".join(e.get("tool", "") for e in spec.get("effects") or [])
        note(f"「{p['name']}」已补全:{len(spec.get('params') or [])} 个参数,效果 {tools}")
    return done, min(len(todo), MAX_DEEPEN)


def _resolve_obj(ref: str, objs: dict[str, dict]) -> dict | None:
    """AI 引用对象时常用英文 / 表名(supplier、otlgt3_dm_supplier):按名称、别名、表名后缀找回来。"""
    if not ref:
        return None
    if ref in objs:
        return objs[ref]
    low = ref.lower()
    for rec in objs.values():
        table = str(((rec.get("binding") or {}).get("ref") or {}).get("table") or "").lower()
        if table and (table == low or table.endswith("_" + low)):
            return rec
    return None


def _check_action_refs(spec: dict, objs: dict[str, dict]) -> str:
    """对象名换成规范名称;写 / 建的属性必须真的存在。返回错误(喂回给 AI 修),空串 = 通过。"""
    if spec.get("target_type"):
        rec = _resolve_obj(str(spec["target_type"]), objs)
        if rec is None:
            return f"找不到对象「{spec['target_type']}」,只能用这些对象:{'、'.join(sorted({r['name'] for r in objs.values()}))}"
        spec["target_type"] = rec["name"]
        props = {p["name"] for p in rec["properties"]}
        text = " ".join(str(c.get("expression") or "") for c in spec.get("criteria") or []) + jdump(spec.get("effects"))
        ghost = sorted({m for m in re.findall(r"obj\.([A-Za-z_一-鿿][\w一-鿿]*)", text)
                        if m not in props and m not in ("key", "label")})
        if ghost:
            return (f"{rec['name']} 没有属性 {'、'.join(ghost)}(obj 只能取它自己的属性:{'、'.join(sorted(props))});"
                    f"取不到的信息就改成参数,或者删掉这条条件")
    for e in spec.get("effects") or []:
        args = e.get("args") or {}
        if e.get("tool") not in ("object.write", "object.create"):
            continue
        rec = _resolve_obj(str(args.get("object_type") or spec.get("target_type") or ""), objs)
        if rec is None:
            return f"效果 {e.get('tool')} 的对象「{args.get('object_type')}」不存在"
        args["object_type"] = rec["name"]
        names = [p["name"] for p in rec["properties"]]
        want = [str(args.get("property") or "")] if e["tool"] == "object.write" else list(args.get("values") or {})
        bad = [w for w in want if w not in names]
        if bad:
            return f"{rec['name']} 没有属性 {'、'.join(bad)},可用属性:{'、'.join(names)}"
    return ""


def _open_writes(spec: dict, objs: dict[str, dict]) -> None:
    """动作要写的属性标成可写(草案里的对象改草案,已有对象改工作副本),校验才能过。"""
    for e in spec.get("effects") or []:
        if e.get("tool") != "object.write":
            continue
        args = e.get("args") or {}
        rec = objs.get(str(args.get("object_type") or spec.get("target_type") or ""))
        prop = str(args.get("property") or "")
        if not rec or not prop:
            continue
        hit = next((x for x in rec["properties"] if x["name"] == prop), None)
        if hit is None or hit.get("is_writable"):
            continue
        hit["is_writable"] = True
        if rec["item"] is not None:
            payload = dict(rec["item"]["payload"])
            payload["spec"] = {**(payload.get("spec") or {}), "properties": rec["properties"]}
            review.update_payload(rec["item"]["id"], payload)
        elif rec["id"]:
            service.update_concept(rec["id"], spec={**(service.get_concept(rec["id"]).get("spec") or {}),
                                                    "properties": rec["properties"]})


# ---------------- ④ SOP 编排 ----------------
SOP_TOPICS_PROMPT = """下面是业务文档的片段(方括号里是片段编号)。找出其中描述了「有先后步骤、有角色分工、有判断分支」的业务流程,
最多 {n} 个,只挑文档里写得比较完整的。

{text}

只挑跨多个步骤的流程(如每日巡检、月度对账);单个操作(创建某单据、标记某状态)是动作,不要当成流程。

输出 JSON:{{"processes":[{{"title":"流程名","chunks":["片段编号"]}}]}},没有就输出空数组。"""


def _draft_catalog(run_id: str) -> dict:
    """这次草案里的积木(还没采纳):流程卡按这些名字引用,采纳发布后就能跑。"""
    items = review.list_items(status="pending", kind="concept_create", source=_source(run_id), limit=500)["items"]
    by: dict[str, list[str]] = {"actions": [], "metrics": [], "rules": [], "object_types": []}
    for it in items:
        p = it["payload"] or {}
        sp = p.get("spec") or {}
        if p.get("kind") == "action" and not sp.get("_stub"):
            by["actions"].append(f"- {p['name']}:{p.get('description') or ''} 参数:{[x.get('name') for x in sp.get('params') or []]}"
                                 + (f" 作用对象:{sp.get('target_type')}" if sp.get("target_type") else ""))
        elif p.get("kind") == "function" and sp.get("category") == "aggregate":
            by["metrics"].append(p["name"])
        elif p.get("kind") == "function" and sp.get("category") in ("rule", "decision"):
            by["rules"].append(p["name"])
        elif p.get("kind") == "object_type":
            by["object_types"].append(p["name"])
    return {k: ("\n" if k == "actions" else "、").join(v) for k, v in by.items()}


def _sops(chunks: list[dict], note, run_id: str = "") -> list[str]:
    from ..sop import draft as sop_draft
    extra = _draft_catalog(run_id) if run_id else None
    text = "\n\n".join(f"[{c['id']}]【{c.get('heading') or '正文'}】{c['text'][:1500]}" for c in chunks[:80])
    try:
        with llmlog.feature("modeling_sop"):
            res = llm.chat_json([{"role": "user", "content": SOP_TOPICS_PROMPT.format(
                n=MAX_SOPS, text=llm.truncate_to_tokens(text, 12000))}], temperature=0.1)
    except Exception as e:  # noqa: BLE001
        note(f"识别流程失败:{str(e)[:100]}")
        return []
    by_id = {c["id"]: c for c in chunks}
    out = []
    for proc in ((res or {}).get("processes") or [])[:MAX_SOPS] if isinstance(res, dict) else []:
        title = str((proc or {}).get("title") or "").strip()
        if not title:
            continue
        sub = [by_id[x] for x in proc.get("chunks") or [] if x in by_id] or chunks[:8]
        try:
            d = sop_draft.generate(title, chunks=sub[:8], extra_catalog=extra)
            out.append(d["id"])
            note(f"流程卡「{d['title']}」{d['step_count']} 步")
        except HTTPException as e:
            note(f"「{title}」起草失败:{e.detail}")
    return out


# ---------------- 导出 ----------------
def export_md(run_id: str) -> str:
    g = get(run_id)
    lines = [f"# {g['title']}", "", f"> 业务建模草案 · {g['created_at']} · 状态 {g['status']}", ""]
    for k, meta in schema.KINDS.items():
        items = g["items"].get(k) or []
        lines += [f"## {meta['label']}({len(items)})", ""]
        for it in items:
            p = it["payload"] or {}
            spec = p.get("spec") or {}
            head = f"- **{p.get('name')}**"
            if k == "function":
                head += f"({schema.FN_CATEGORIES.get(spec.get('category') or '', {}).get('label', '')})"
            if it["status"] != "pending":
                head += f" `{'已采纳' if it['status'] == 'accepted' else '已驳回'}`"
            lines.append(head + (f":{p.get('description')}" if p.get("description") else ""))
            if k == "object_type":
                props = [x.get("name") for x in spec.get("properties") or []]
                if props:
                    lines.append(f"  - 属性:{'、'.join(props)}")
            elif k == "link_type":
                lines.append(f"  - {spec.get('from_type')} → {spec.get('to_type')}({spec.get('cardinality')})")
            elif spec.get("expression"):
                lines.append(f"  - 表达式:`{spec['expression']}`")
            elif spec.get("formula_text"):
                lines.append(f"  - 公式:{spec['formula_text']}")
            for e in (p.get("evidence") or [])[:2]:
                lines.append(f"  - 出处:{e.get('heading') or ''} {(e.get('snippet') or '')[:80]}")
        lines.append("")
    if g["sops"]:
        lines += [f"## 流程卡({len(g['sops'])})", ""]
        lines += [f"- **{s['title']}**({s['step_count']} 步):{s['description']}" for s in g["sops"]]
    return "\n".join(lines) + "\n"