modeling.py 123 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303
"""AI 建模流水线:业务文档和 / 或数据库 → 四元组草案 + 流程卡草稿 + 定时任务草稿。

  输入(知识库文档 / 临时上传 / 已接入的数据库,至少一样)
   → ① 读表结构:已接入的表翻译成候选对象 / 关系(带表绑定、可选值、时间列、维度),作为映射的证据。
                 只选了数据库、没有文档时,这一步的结果直接成为草案
   → ② 读文档(概念优先):按四元组找元素,每条带出处(kernel/propose.from_documents);文档里的对象对上了表就绑表、
                 用文档叫法;对不上而本系统要自己记录的设为本体自建;文档没提到的表不建对象;文档写了状态流转的挂成状态机
   → ③ 规则落到对象:规则写成可求值的表达式、挂成对象的计算属性,决策表理顺行序,原文算例变成测试并跑一遍
   → ④ 指标取数:写出取数表达式(可以沿关系引用别的表)并在业务库实跑
   → ⑤ 动作补全:参数 + 前置条件 + 效果,审批挂决策表;表里没有地方存的信息记成「数据缺口」,不挪用别的列
     (④⑤ 互不依赖,同时跑)
   → ⑥ 起草流程卡:按章节找流程,起草成可执行的流程卡草稿(sop/draft)
   → ⑦ 定时与监控:文档里写了「每天几点做」「低于多少就通知」的,生成监控与定时草稿(modeling_schedule)
   → ⑧ 对账:手册条目逐条对上草案,列出漏项,顺带生成验收问题(modeling_check)
   → ⑨ 汇总草案

整条流水线用「AI 建模用的模型」(配置 MODELING_MODEL),不动全局的对话模型。

是一条真的流水线:每个环节记开始 / 结束时间和带时间的日志,每次 AI 调用(含思考过程)记进
`otlg_model_call`;可以暂停、继续、终止、从某一步重跑。各环节可重入:重跑前先清掉这一环节上次的产出。

草案不进「审批与待办」:搭建的人在建模页自己决定采纳与否,采纳即发布上线(体检不过的留作草稿并说明原因);
采纳的定时任务直接建好并启用。
"""
from __future__ import annotations

import contextvars
import copy
import logging
import re
import tempfile
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
from typing import Any, Callable, Iterator

from fastapi import HTTPException
from sqlalchemy import delete as sa_delete
from sqlalchemy import func, select

from ..core import db, envs, identity, llm
from ..core.dbx import iso, jdump, jload, new_id, now, session
from ..governance import audit, llmlog, review
from ..governance.models import ReviewItem
from . import propose, schema, service
from .models import ModelCall, ModelRun

log = logging.getLogger(__name__)

STAGES = [
    {"key": "data", "label": "读表结构", "desc": "读数据库里的表和关联,作为对象映射的证据(只选了数据库时直接成为草案)"},
    {"key": "reqs", "label": "列条目", "desc": "把文档拆成一条条要落地的条目,后面每个元素都标上它落实了哪几条"},
    {"key": "convert", "label": "读文档 · 映射", "desc": "概念优先:从文档里找出对象、关系、函数、动作和状态机,每条带原文出处;"
                                                    "对象对上数据表就绑表,库里没有的设为本体自建,文档没提的表不建对象"},
    {"key": "rules", "label": "计算属性与规则", "desc": "每条记录自己的量和状态写成对象的计算属性,规则写成公式,跑测试,再在真实数据上试算"},
    {"key": "metrics", "label": "指标取数", "desc": "指标写出取数方式(优先用对象的计算属性),在业务库里试算一次"},
    {"key": "actions", "label": "动作补全", "desc": "动作补全参数、前置条件、效果和审批方式"},
    {"key": "sop", "label": "起草流程卡", "desc": "把文档里的操作流程起草成流程卡,逐步对上文档,再试运行一遍"},
    {"key": "schedule", "label": "预警与定时", "desc": "按文档里写的盯数条件和时间,配好预警规则(含检测量、严重度、处置)和定时任务,按今天的数据试扫一遍"},
    {"key": "check", "label": "对账", "desc": "文档条目逐条对上草案:哪些落实了、哪些有出入、哪些漏了、哪些平台本来就有"},
    {"key": "fix", "label": "按对账修改", "desc": "把对账发现的出入和遗漏交给 AI 改进草案(只改草案,不上线),改完再核对一次"},
    {"key": "draft", "label": "汇总草案", "desc": "全部草案在真实数据上体检一遍,标出能直接用的和还差什么"},
]
ORDER = [s["key"] for s in STAGES]
DOC_STAGES = ("reqs", "convert", "rules", "metrics", "actions", "sop", "schedule", "check", "fix")   # 没有文档时这几步没东西可做
TOGETHER = ("metrics", "actions")    # 互不依赖,同时跑
MAX_DEEPEN = 24
MAX_SOPS = 5
PARALLEL = 4            # 规则深化、指标取数同时发几条
ACTION_PARALLEL = 8     # 动作补全要和模型来回几轮,多开几路


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


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


# ---------------- 运行控制 ----------------
class Halt(BaseException):
    """暂停 / 终止。BaseException:穿过各环节兜底的 except Exception,直达 execute。"""

    def __init__(self, mode: str):
        super().__init__(mode)
        self.mode = mode


_ctl: dict[tuple[str, str], str] = {}        # (环境, run_id) → stop / cancel:有人按了暂停 / 终止
_live: set[tuple[str, str]] = set()          # 本进程里正在跑的
_lock = threading.Lock()


def _k(run_id: str) -> tuple[str, str]:
    return (envs.current(), run_id)


def _check(run_id: str) -> None:
    mode = _ctl.get(_k(run_id))
    if mode:
        raise Halt(mode)


class _Calls:
    """调用追踪的接收方:每次 AI 调用一行 otlg_model_call,思考过程边想边写;顺带在这里响应暂停 / 终止
    (调用开始前不再开新的,流式进行中直接打断 —— 反正继续时这一环节要整个重跑)。"""

    def __init__(self, run_id: str, stage: str):
        self.run_id = run_id
        self.stage = stage

    def begin(self, label: str, feature: str, model: str, prompt: str) -> tuple[int, float]:
        _check(self.run_id)
        with session() as s:
            row = ModelCall(run_id=self.run_id, stage=self.stage, feature=feature or "", label=(label or "")[:255],
                            model=(model or "")[:128], prompt=prompt[:60000], started_at=now(), status="running",
                            prompt_tokens=llm.count_tokens(prompt))
            s.add(row)
            s.commit()
            return row.id, time.time()

    def update(self, h: tuple[int, float], reasoning: str, output: str) -> None:
        if _ctl.get(_k(self.run_id)):
            raise llm.Cancelled()
        with session() as s:
            row = s.get(ModelCall, h[0])
            if row is not None:
                row.reasoning, row.output = reasoning, output
                row.duration_ms = int((time.time() - h[1]) * 1000)
                row.reasoning_tokens, row.output_tokens = llm.count_tokens(reasoning), llm.count_tokens(output)
                s.commit()

    def end(self, h: tuple[int, float], *, output: str = "", reasoning: str = "", usage: dict | None = None,
            cached: bool = False, ok: bool = True, error: str = "") -> None:
        u = usage or {}
        think = int(((u.get("output_tokens_details") or {}).get("reasoning_tokens"))
                    or (llm.count_tokens(reasoning) if reasoning else 0))
        try:
            with session() as s:
                row = s.get(ModelCall, h[0])
                if row is None:
                    return
                row.status = "done" if ok else ("cancelled" if error == "已终止" else "failed")
                row.duration_ms = 0 if cached else int((time.time() - h[1]) * 1000)
                row.cached = 1 if cached else 0
                row.error = error or ""
                if output or reasoning:
                    row.output, row.reasoning = output, reasoning
                row.prompt_tokens = int(u.get("input_tokens") or llm.count_tokens(row.prompt))
                row.output_tokens = max(0, int(u.get("output_tokens") or 0) - think) if u.get("output_tokens") \
                    else llm.count_tokens(output)
                row.reasoning_tokens = think
                s.commit()
        except Exception:  # noqa: BLE001 —— 记不上不能影响建模本身
            log.debug("记录建模 AI 调用失败", exc_info=True)


def _pool_map(fn: Callable, items: list, workers: int) -> list:
    """并发跑 fn(item),结果按原顺序返回;当前空间、操作人、调用追踪随上下文带进线程。"""
    if not items:
        return []
    with ThreadPoolExecutor(max_workers=min(workers, len(items))) as pool:
        futs = [pool.submit(contextvars.copy_context().run, fn, it) for it in items]
        return [f.result() for f in futs]


# ---------------- 记录 ----------------
def _elapsed(stages: list[dict]) -> tuple[str | None, int]:
    """(最早开始时间, 各环节实际占用的时长 ms)。运行中的环节算到现在;同时跑的环节(指标、动作)重叠部分只算一次。"""
    import datetime as dt
    spans = []
    for r in stages:
        a = r.get("started_at")
        if not a:
            continue
        t0 = dt.datetime.fromisoformat(a)
        t1 = dt.datetime.fromisoformat(r["ended_at"]) if r.get("ended_at") else now()
        spans.append((t0, max(t0, t1)))
    if not spans:
        return None, 0
    spans.sort()
    total, (cs, ce) = 0, spans[0]
    for s0, s1 in spans[1:]:
        if s0 <= ce:
            ce = max(ce, s1)
        else:
            total += int((ce - cs).total_seconds() * 1000)
            cs, ce = s0, s1
    total += int((ce - cs).total_seconds() * 1000)
    return iso(spans[0][0]), total


def _stage_rows(raw: list[dict]) -> list[dict]:
    """存下来的环节状态 → 现在的环节表。老记录:「识别行业」不再显示;「规则变成可算的」拆成了
    规则 / 指标 / 动作三步(状态、日志都记在第一步上);后来加的环节在老记录里算跳过。"""
    have = {x.get("key"): x for x in raw or [] if x.get("key") != "route"}
    old = have.pop("deepen", None)
    rows = []
    for meta in STAGES:
        k = meta["key"]
        r = have.get(k)
        if r is None and old is not None and k in ("rules", "metrics", "actions"):
            r = {**old, "log": old.get("log") if k == "rules" else [], "counts": old.get("counts") if k == "rules" else {}}
        if r is None:
            r = {"status": "skipped", "log": [], "counts": {}, "started_at": "", "ended_at": ""}
        r = {**r, **meta}
        r["log"] = [x if isinstance(x, dict) else {"t": "", "msg": str(x)} for x in r.get("log") or []]   # 老记录的日志是纯文字
        rows.append(r)
    return rows


def _dict(r: ModelRun, full: bool = False) -> dict:
    inputs = jload(r.inputs_json, {}) or {}
    stages = _stage_rows(jload(r.stages_json, []) or [])
    started, elapsed = _elapsed(stages)
    out = {"id": r.id, "title": r.title, "status": r.status, "error": r.error or "",
           "control": _ctl.get(_k(r.id), ""),
           "options": jload(r.options_json, {}) or {}, "stages": stages,
           "counts": jload(r.counts_json, {}) or {}, "created_by": r.created_by,
           "created_at": iso(r.created_at), "updated_at": iso(r.updated_at),
           "started_at": started, "elapsed_ms": elapsed,
           "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 []
        out["sop_hints"] = inputs.get("sop_hints") or {}
        out["issues"] = inputs.get("issues") or {}
        out["watches"] = inputs.get("watch_drafts") or []
        out["check"] = inputs.get("check") or {}
        out["reqs"] = inputs.get("reqs") or []
        out["fixes"] = inputs.get("fixes") or []
    model = (inputs.get("model") or "").strip()
    if model:
        out["model"] = model
    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)
    if r.status == "running" and _k(run_id) not in _live:
        # 服务重启过:本进程里没在跑,记录却停在「运行中」。转成暂停,可以继续
        with session() as s:
            row = s.get(ModelRun, run_id)
            row.status = "stopped"
            row.error = "服务重启,这次建模被中断了,可以点「继续」接着跑"
            stages = _stage_rows(jload(row.stages_json, []) or [])
            for st in stages:
                if st["status"] == "running":
                    st["status"], st["ended_at"] = "stopped", iso(now())
            row.stages_json = jdump(stages)
            s.commit()
            s.refresh(row)
            s.expunge(row)
            r = row
    return r


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


def _call_stats(run_id: str) -> dict[str, dict]:
    with session() as s:
        rows = s.execute(select(ModelCall.stage, func.count(ModelCall.id), func.sum(ModelCall.duration_ms),
                                func.sum(ModelCall.prompt_tokens), func.sum(ModelCall.output_tokens),
                                func.sum(ModelCall.reasoning_tokens))
                         .where(ModelCall.run_id == run_id).group_by(ModelCall.stage)).all()
    return {st: {"calls": int(n), "ms": int(ms or 0), "prompt_tokens": int(p or 0), "output_tokens": int(o or 0),
                 "reasoning_tokens": int(rt or 0)} for st, n, ms, p, o, rt in rows}


def _concept_of(it: dict) -> dict | None:
    """草案采纳后落成的元素(按名称找;补别名 / 冲突 / 绑定这几种本来就指向已有元素)。"""
    p = it.get("payload") or {}
    if it["kind"] == "concept_create":
        c = service.find(str(p.get("name") or ""), str(p.get("kind") or ""))
        return service.get_concept(c["id"]) if c else None
    cid = p.get("concept_id")
    try:
        return service.get_concept(cid) if cid else None
    except HTTPException:
        return None


def get(run_id: str) -> dict:
    """运行记录 + 本次草案(按四种元素分列)+ 流程卡草稿(含步骤树)+ 各环节的 AI 调用统计。"""
    out = _dict(_load(run_id), full=True)
    issues = out.pop("issues")
    hints = out.pop("sop_hints")
    items = review.list_items(status="", source=_source(run_id), limit=2000)["items"]
    cols: dict[str, list] = {"object_type": [], "link_type": [], "function": [], "action": [], "other": []}
    for it in items:
        p = it["payload"] or {}
        if it["status"] == "accepted":
            c = _concept_of(it)
            it["concept"] = ({"id": c["id"], "name": c["name"], "status": c["status"], "dirty": bool(c.get("dirty")),
                              "issue": issues.get(c["id"], "")} if c else None)
        if it["id"] in issues:
            it["issue"] = issues[it["id"]]
        k = p.get("kind") if it["kind"] == "concept_create" else "other"
        if it["kind"] == "concept_create" and it["status"] == "pending":
            from .modeling_grade import readiness
            it["readiness"] = p.get("readiness") or readiness(p)
        cols.setdefault(k if k in cols else "other", []).append(it)
    out["items"] = cols
    from ..sop import service as sop_service
    from ..sop import spec as sop_spec
    names = _draft_names(run_id)
    sops = []
    for sid in out.pop("sop_ids"):
        try:
            d = sop_service.get(sid)
        except HTTPException:
            continue
        valid = d.get("validation")
        if not d["current_version"] and any(names.values()):
            valid = sop_spec.validate(d["spec"], def_id=sid, draft_names=names)
        sops.append({**{k: d.get(k) for k in ("id", "title", "description", "status", "step_count", "owner_role",
                                              "current_version", "updated_at")},
                     "validation": valid, "schedule": (hints.get(sid) or {}).get("schedule", ""),
                     "coverage": (hints.get(sid) or {}).get("coverage") or {},
                     "dry_run": (hints.get(sid) or {}).get("dry_run") or {},
                     "fix_log": (hints.get(sid) or {}).get("fix_log") or [],
                     "params": (d.get("spec") or {}).get("params") or [],
                     "outline": sop_spec.outline(d["spec"]),
                     "issue": issues.get(sid, "")})
    out["sops"] = sops
    out["call_stats"] = _call_stats(run_id)
    return out


def calls(run_id: str, stage: str = "") -> list[dict]:
    """某个环节(或全部)的 AI 调用列表,不含大字段;思考过程 / 输出只给长度和开头。"""
    _load(run_id)
    with session() as s:
        stmt = select(ModelCall).where(ModelCall.run_id == run_id)
        if stage:
            stmt = stmt.where(ModelCall.stage == stage)
        rows = s.scalars(stmt.order_by(ModelCall.id)).all()
        return [{"id": r.id, "stage": r.stage, "feature": r.feature, "label": r.label, "model": r.model,
                 "status": r.status, "started_at": iso(r.started_at), "duration_ms": r.duration_ms,
                 "prompt_tokens": r.prompt_tokens, "output_tokens": r.output_tokens,
                 "reasoning_tokens": r.reasoning_tokens, "cached": bool(r.cached), "error": r.error,
                 "reasoning_chars": len(r.reasoning or ""), "output_preview": (r.output or "")[:160]}
                for r in rows]


def call_detail(run_id: str, call_id: int) -> dict:
    _load(run_id)
    with session() as s:
        r = s.get(ModelCall, call_id)
        if r is None or r.run_id != run_id:
            raise HTTPException(404, "调用记录不存在")
        return {"id": r.id, "stage": r.stage, "label": r.label, "status": r.status, "model": r.model,
                "started_at": iso(r.started_at), "duration_ms": r.duration_ms, "error": r.error,
                "prompt_tokens": r.prompt_tokens, "output_tokens": r.output_tokens,
                "reasoning_tokens": r.reasoning_tokens, "cached": bool(r.cached),
                "prompt": r.prompt, "reasoning": r.reasoning, "output": r.output}


def pending_count() -> int:
    """各次建模里还没决定的草案条数(工作台「下一步」用)。"""
    with session() as s:
        return int(s.scalar(select(func.count(ReviewItem.id)).where(
            ReviewItem.workspace == _ws(), ReviewItem.status == "pending",
            ReviewItem.source.like("modeling:%"))) or 0)


# ---------------- 输入 ----------------
WHOLE_DOC_TOKENS = 8000     # 不超过这么长的文档整篇一块读:一次调用,章节之间的引用也不会被切断
DOC_CHUNK_TOKENS = 3000     # 更长的文档按章节切成这么大的块


def _split_doc(text: str, prefix: str, name: str, doc_id: int) -> list[dict]:
    """建模用的切块:和知识库检索的切块不同,标题行留在正文里(AI 靠「## 六、审批规则」分清每段讲什么),
    块之间不重叠(重叠会从表格中间切开,出处只剩半句话)。"""
    from ..ingest.chunk import chunk_text
    text = (text or "").strip()
    if not text:
        return []
    if llm.count_tokens(text) <= WHOLE_DOC_TOKENS:
        return [{"id": f"{prefix}:c0", "heading": name, "text": text, "doc_id": doc_id}]
    out = []
    for n, c in enumerate(chunk_text(text, doc_id, chunk_tokens=DOC_CHUNK_TOKENS, overlap_tokens=0, min_tokens=120,
                                     inline_headings=True)):
        out.append({"id": f"{prefix}:c{n}", "heading": c.get("heading") or name, "text": c["text"], "doc_id": doc_id})
    return out


def _upload_chunks(run_id: str, files: list[tuple[str, bytes]]) -> tuple[list[dict], list[dict]]:
    """临时上传:只解析、切块,不进知识库,也不抽图谱。"""
    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
        chunks += _split_doc(doc.text, f"u{tag}{i}", Path(name).stem, 0)
        meta.append({"name": name, "size": len(raw)})
    return chunks, meta


def _doc_chunks(doc_ids: list[int]) -> list[dict]:
    """知识库文档:从原文件重新切一遍(知识库的块是给检索用的,标题不在正文里、块间有重叠);
    原文件读不到时退回知识库里已有的块。"""
    if not doc_ids:
        return []
    from ..api import deps
    from ..api.documents import _upload_path
    from ..ingest.parse import parse_file
    out = []
    for did in dict.fromkeys(int(x) for x in doc_ids):
        doc = db.get_document(did) or {}
        try:
            text = parse_file(_upload_path(doc)).text if doc else ""
        except Exception:  # noqa: BLE001
            text = ""
        part = _split_doc(text, f"d{did}", Path(str(doc.get("filename") or f"文档{did}")).stem, did) if text else []
        out += part or [c for c in deps.index().chunks.records if c.get("doc_id") == did]
    return out


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,
           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 [])
    dss = _default_ds_ids() if ds_ids is None else [int(x) for x in ds_ids]
    has_docs = bool(doc_ids or up_chunks)
    asked = [x for k in (stages or ORDER) for x in (("rules", "metrics", "actions") if k == "deepen" else (k,))]
    chosen = [k for k in asked if k in ORDER]
    if not has_docs:
        if not dss:
            raise HTTPException(422, "请选择业务文档,或者选择要对上的数据库")
        chosen = [k for k in chosen if k not in DOC_STAGES] + [k for k in ("data",) if k not in chosen]
    for must in (("convert", "draft") if has_docs else ("draft",)):
        if must not in chosen:
            chosen.append(must)
    stage_rows = [{**s, "status": "pending" if s["key"] in chosen else "skipped", "log": [], "counts": {},
                   "started_at": "", "ended_at": ""} for s in STAGES]
    actor = identity.current()
    with session() as s:
        s.add(ModelRun(id=run_id, workspace=actor.workspace, title=(title or "AI 建模")[:255],
                       inputs_json=jdump({"doc_ids": list(doc_ids or []), "files": up_meta,
                                          "chunks": up_chunks}),
                       options_json=jdump({"stages": chosen, "ds_ids": dss}),
                       stages_json=jdump(stage_rows), status="draft", created_by=actor.id))
        s.commit()
    audit.record("modeling.create", "model_run", run_id, f"新建 AI 建模「{title}」")
    return _dict(_load(run_id))


def start(run_id: str, from_stage: str = "") -> dict:
    """开始 / 继续 / 从某一步重跑。

    from_stage 给了:这一步和之后的步骤重置后重跑;没给:已完成的跑完了就整条重跑,否则从没跑完的那一步继续。"""
    r = _load(run_id)
    k = _k(run_id)
    with _lock:
        if k in _live:
            raise HTTPException(409, "这次建模正在运行")
        rows = _stage_rows(jload(r.stages_json, []) or [])
        if from_stage == "deepen":
            from_stage = "rules"
        if from_stage:
            if from_stage not in ORDER:
                raise HTTPException(422, f"没有「{from_stage}」这一步")
            if next(x for x in rows if x["key"] == from_stage)["status"] == "skipped":
                raise HTTPException(422, "这一步在这次建模里是跳过的")
            again = ORDER[ORDER.index(from_stage):]
        elif r.status == "done":
            again = ORDER
        else:
            again = []
        for x in rows:
            if x["key"] in again and x["status"] != "skipped":
                x["status"] = "pending"
        _ctl.pop(k, None)
        _live.add(k)
        with session() as s:
            row = s.get(ModelRun, run_id)
            row.stages_json = jdump(rows)
            row.status = "running"
            row.error = ""
            s.commit()
    env, actor = envs.current(), identity.current()

    def main() -> None:
        t1, t2 = envs.set_current(env), identity.set_current(actor)
        try:
            for _ in execute(run_id):
                pass
        except BaseException:  # noqa: BLE001
            log.exception("AI 建模 %s 线程异常退出", run_id)
        finally:
            identity.reset(t2)
            envs.reset(t1)
            _live.discard(k)

    # 不走全局任务队列:那里只有一个 worker,建模一跑就是几分钟,知识库解析会被堵在后面
    threading.Thread(target=main, name=f"modeling-{run_id}", daemon=True).start()
    return _dict(_load(run_id))


def control(run_id: str, mode: str) -> dict:
    """stop = 暂停(之后可以继续);cancel = 终止。正在进行的 AI 调用会被立刻打断。"""
    if mode not in ("stop", "cancel"):
        raise HTTPException(422, "只能暂停(stop)或终止(cancel)")
    r = _load(run_id)
    if _k(run_id) not in _live:
        if mode == "cancel" and r.status in ("stopped", "failed"):
            _finish(run_id, "cancelled", "已终止")
            return _dict(_load(run_id))
        raise HTTPException(409, "这次建模没有在运行")
    _ctl[_k(run_id)] = mode
    audit.record(f"modeling.{mode}", "model_run", run_id, f"{'暂停' if mode == 'stop' else '终止'} AI 建模「{r.title}」")
    return _dict(_load(run_id))


def delete(run_id: str) -> None:
    _load(run_id)
    if _k(run_id) in _live:
        raise HTTPException(409, "这次建模正在运行,先终止再删除")
    with session() as s:
        s.execute(sa_delete(ModelCall).where(ModelCall.run_id == run_id))
        # 还没决定的草案跟着记录一起删;已经采纳上线的元素不受影响
        s.execute(sa_delete(ReviewItem).where(ReviewItem.source == _source(run_id), ReviewItem.status == "pending"))
        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 = _stage_rows(jload(_load(run_id).stages_json, []) or [])
        self.lock = threading.Lock()

    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:
        with self.lock:
            r = self.row(key)
            if status and status != r["status"]:
                if status == "running":
                    r["started_at"], r["ended_at"] = iso(now()), ""
                elif status in ("done", "failed", "stopped", "cancelled"):
                    r["ended_at"] = iso(now())
                r["status"] = status
            if msg:
                r["log"] = (list(r.get("log") or []) + [{"t": iso(now()), "msg": msg}])[-300:]
            if counts:
                r["counts"] = {**(r.get("counts") or {}), **counts}
            self._save()

    def note(self, key: str) -> Callable[[str], None]:
        return lambda m: self.set(key, msg=m)

    def reset(self, key: str) -> None:
        with self.lock:
            r = self.row(key)
            r.update(log=[], counts={}, started_at="", ended_at="")
            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 _inputs(run_id: str) -> dict:
    with session() as s:
        return jload(s.get(ModelRun, run_id).inputs_json, {}) or {}


def _patch_inputs(run_id: str, fn: Callable[[dict], None]) -> None:
    with _lock, session() as s:
        row = s.get(ModelRun, run_id)
        inp = jload(row.inputs_json, {}) or {}
        fn(inp)
        row.inputs_json = jdump(inp)
        s.commit()


def _clean(run_id: str, key: str, st: _Stages) -> None:
    """重跑一个环节前,清掉它上次的产出和调用记录(已经采纳的东西不动)。"""
    with session() as s:
        s.execute(sa_delete(ModelCall).where(ModelCall.run_id == run_id, ModelCall.stage == key))
        if key == "convert" or (key == "data" and not st.active("convert")):
            s.execute(sa_delete(ReviewItem).where(ReviewItem.source == _source(run_id),
                                                  ReviewItem.status == "pending"))
        s.commit()
    if key == "sop":
        from ..sop import service as sop_service
        keep = []
        for sid in _inputs(run_id).get("sop_ids") or []:
            try:
                d = sop_service.get(sid)
            except HTTPException:
                continue
            if d["current_version"]:
                keep.append(sid)                   # 已经采纳上线的留着
            elif d["status"] != "archived":
                sop_service.archive(sid)
        _patch_inputs(run_id, lambda inp: inp.update(sop_ids=keep))
    if key == "schedule":
        _patch_inputs(run_id, lambda inp: inp.update(
            watch_drafts=[w for w in inp.get("watch_drafts") or [] if w.get("status") == "accepted"]))
    if key == "check":
        _patch_inputs(run_id, lambda inp: inp.pop("check", None))
    if key == "reqs":
        _patch_inputs(run_id, lambda inp: inp.pop("reqs", None))
    if key == "fix":
        _patch_inputs(run_id, lambda inp: inp.pop("fixes", None))
    st.reset(key)


def execute(run_id: str) -> Iterator[dict]:
    """按顺序跑还没完成的环节。逐步 yield 进度事件,最后一条是 done / stopped / error。"""
    k = _k(run_id)
    _live.add(k)
    try:
        yield from _execute(run_id)
    finally:
        _live.discard(k)
        _ctl.pop(k, None)


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 and st.active("convert"):
        _finish(run_id, "failed", "没有可用的文档片段:知识库文档要先完成解析")
        yield {"stage": "error", "error": "没有可用的文档片段"}
        return
    _finish(run_id, "running")
    ctx: dict[str, Any] = {"chunks": chunks, "opts": opts}
    model = (db.get_config("MODELING_MODEL") or "").strip()
    _patch_inputs(run_id, lambda inp: inp.update(model=model or db.get_config("QWEN_MODEL")))
    from . import modeling_check, modeling_fix, modeling_reqs, modeling_schedule
    ctx["reqs"] = inputs.get("reqs") or []
    runners = {"data": _stage_data, "reqs": modeling_reqs.stage, "convert": _stage_convert, "rules": _stage_rules,
               "metrics": _stage_metrics, "actions": _stage_actions, "sop": _stage_sop,
               "schedule": modeling_schedule.stage, "check": modeling_check.stage, "fix": modeling_fix.stage,
               "draft": _stage_draft}

    def run_one(key: str) -> list[dict]:
        _check(run_id)
        _clean(run_id, key, st)
        st.set(key, "running")
        with llm.use_model(model), llm.tracing(_Calls(run_id, key), st.row(key)["label"]):
            events = list(runners[key](run_id, st, ctx))
        if st.row(key)["status"] == "running":
            st.set(key, "done")
        return events

    try:
        for key in ORDER:
            if st.row(key)["status"] in ("done", "skipped"):
                continue
            group = [k for k in TOGETHER if st.row(k)["status"] not in ("done", "skipped")] if key in TOGETHER else [key]
            if len(group) > 1:
                for events in _pool_map(run_one, group, len(group)):
                    yield from events
            else:
                yield from run_one(key)
        counts = st.row("draft")["counts"]
        _finish(run_id, "done", counts=counts)
        audit.record("modeling.done", "model_run", run_id, f"AI 建模完成:{counts}")
        yield {"stage": "done", "progress": 100, "message": "建模完成", "result": counts}
    except (Halt, llm.Cancelled) as h:
        mode = h.mode if isinstance(h, Halt) else (_ctl.get(_k(run_id)) or "cancel")
        status = "stopped" if mode == "stop" else "cancelled"
        for r in st.rows:
            if r["status"] == "running":
                st.set(r["key"], status, "已暂停:继续时这一步会重新跑" if mode == "stop" else "已终止")
        _finish(run_id, status, "")
        audit.record(f"modeling.{status}", "model_run", run_id, "AI 建模" + ("已暂停" if mode == "stop" else "已终止"))
        yield {"stage": status, "message": "已暂停" if mode == "stop" else "已终止"}
    except Exception as e:  # noqa: BLE001
        log.exception("AI 建模 %s 失败", run_id)
        msg = str(getattr(e, "detail", e))[:500]
        for r in st.rows:
            if r["status"] == "running":
                st.set(r["key"], "failed", f"出错:{msg}")
        _finish(run_id, "failed", msg)
        yield {"stage": "error", "error": msg[:300]}


# ---------------- 各环节 ----------------
def _seed(st: _Stages, opts: dict) -> list[dict]:
    seed: list[dict] = []
    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", msg=f"数据源 #{ds_id} 读取失败:{str(e)[:120]}")
    return seed


def _stage_data(run_id: str, st: _Stages, ctx: dict) -> Iterator[dict]:
    seed = _seed(st, ctx["opts"])
    ctx["seed"] = seed
    objs = [p["name"] for p in seed if p["kind"] == "object_type"]
    links = sum(1 for p in seed if p["kind"] == "link_type")
    if not ctx["opts"].get("ds_ids"):
        msg = "没有选数据库:对象先不绑定,之后在对象页绑定"
    elif not seed:
        msg = "选中的数据库里没有可用的表(要有主键,并且已读取表结构)"
    else:
        msg = f"{len(objs)} 张表 → 对象({'、'.join(objs[:8])}{' 等' if len(objs) > 8 else ''}),{links} 条表间关联"
    if not st.active("convert"):
        # 只从数据库起步:表和关联直接成为草案
        stats = propose.submit_proposals(copy.deepcopy(seed), _source(run_id))
        msg += f";生成 {stats['proposed']} 条草案,{stats['enriched']} 条已有元素补了出处"
    for p in seed:
        if p["kind"] == "object_type":
            st.set("data", msg=f"对象「{p['name']}」")
    st.set("data", "done", msg, tables=len(objs), joins=links)
    yield {"stage": "data", "progress": 8, "message": f"对上数据表:{len(objs)} 张表"}


def _stage_convert(run_id: str, st: _Stages, ctx: dict) -> Iterator[dict]:
    if "seed" not in ctx:
        ctx["seed"] = _seed(st, ctx["opts"]) if st.active("data") else []
    st.set("convert", msg=f"参考文档片段 {len(ctx['chunks'])} 个" + (f",参考数据库里的 {len(ctx['seed'])} 个已有元素" if ctx.get("seed") else ""))
    result: dict = {}
    for ev in propose.from_documents(ctx["chunks"], source=_source(run_id), seed=ctx["seed"],
                                     label="读文档 · ", reqs=ctx.get("reqs") or []):
        if ev.get("stage") == "error":
            raise RuntimeError(ev.get("error") or "读文档失败")
        if ev.get("message") and ev.get("stage") != "done":    # 收尾那句和下面的完成日志重复
            st.set("convert", msg=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)})


def _stage_rules(run_id: str, st: _Stages, ctx: dict) -> Iterator[dict]:
    n, tried, props, tests = _rules(run_id, st.note("rules"))
    st.set("rules", "done", f"{n}/{tried} 条规则和决策表写成了可算的,挂成对象计算属性 {props} 个,"
                            f"测试用例 {tests['ok']}/{tests['all']} 条通过",
           deepened=n, tried=tried, properties=props, tests=tests["all"], tests_ok=tests["ok"])
    yield {"stage": "rules", "progress": 45, "message": f"规则落到对象:{n} 条"}


def _stage_metrics(run_id: str, st: _Stages, ctx: dict) -> Iterator[dict]:
    bound, tried = _bind_metrics(run_id, st.note("metrics"))
    st.set("metrics", "done", f"{bound}/{tried} 个指标对上了数据并试算通过", metrics_bound=bound, tried=tried)
    yield {"stage": "metrics", "progress": 55, "message": f"指标取数:{bound} 个"}


def _stage_actions(run_id: str, st: _Stages, ctx: dict) -> Iterator[dict]:
    note = st.note("actions")
    acts, tried, gaps = _complete_actions(run_id, note, ctx.get("reqs") or [])
    msg = f"{acts}/{tried} 个动作补全了参数和执行内容"
    if gaps:
        msg += f";{gaps} 处业务表里没有地方存的信息,建成了本体自有属性(值由本系统保存)"
    st.set("actions", "done", msg, actions_completed=acts, tried=tried, gaps=gaps)
    yield {"stage": "actions", "progress": 65, "message": f"动作补全:{acts} 个"}


def _stage_sop(run_id: str, st: _Stages, ctx: dict) -> Iterator[dict]:
    made = _sops(ctx["chunks"], st.note("sop"), run_id, ctx.get("reqs") or [])
    st.set("sop", "done", f"生成 {made} 张流程卡草稿", sops=made)
    yield {"stage": "sop", "progress": 92, "message": f"流程卡 {made} 张"}


def _stage_draft(run_id: str, st: _Stages, ctx: dict) -> Iterator[dict]:
    from . import modeling_grade
    note = st.note("draft")
    graded = modeling_grade.grade_all(run_id, note)
    g = get(run_id)
    counts = {k: len(g["items"].get(k) or []) for k in schema.KINDS}
    counts["sop"] = len(g["sops"])
    counts["watch"] = len(g["watches"])
    counts["ready"] = graded["ready"]
    st.set("draft", "done", f"体检 {graded['total']} 条元素:{graded['ready']} 条能直接用,"
                            f"{graded['total'] - graded['ready']} 条还差点东西(各条详情里写了差什么);"
                            + "、".join(f"{schema.KINDS[k]['label']} {counts[k]}" for k in schema.KINDS)
                            + f"、流程卡 {counts['sop']}、定时与监控 {counts['watch']}", **counts)
    yield {"stage": "draft", "progress": 98, "message": "汇总草案"}


# ---------------- ③ 计算属性与规则 ----------------
RULES_PROMPT = """下面是这次从业务文档里找出来的:对象上每条记录自己的量和状态、规则、决策表。把它们写成**能直接算**的定义。

【对象及属性】(属性名(中文名, 类型[可选值]);「经关系 X 可取 Y 的属性」表示可以写 X.属性;
「被关系 X 指向」表示可以用 count_of(X, ...) 汇总指向它的那些记录)
{objects}

【业务角色】{roles}

【对象上的量和状态】(对象|文档叫法|量 / 状态|原文)
{derived}

【规则】
{rules}

【决策表】
{decisions}

要求:
- 对象上的量和状态 → properties,每条写成那个对象的一个计算属性:
  · expression 只能用:这个对象的属性名、前面写好的计算属性名、「关系名.属性」(关系另一头只有一个时),
    以及汇总「指向我的那些记录」:count_of(关系名, '对方的是否属性')、sum_of(关系名, '对方的属性', '对方的是否属性'),
    avg_of / max_of / min_of 同理(条件可以不写)。
    函数只能用 min max abs round floor ceil coalesce safe_div days_between add_days today contains startswith;
    占同一组的比例用 share(量, 分组属性)(如 一家店占同区域合计的比例 = share(qty, region)),同组合计用 total(量, 分组属性)。
  · 状态写成得出 是 / 否 的表达式(data_type=boolean),量写成数(data_type=number)。
  · name 用英文(如 is_overdue、amount_due),display_name 用文档叫法;文档给这一类记录起了名字的(如「逾期订单」),放进 synonyms。
  · 后一个属性可以引用前一个(如 剩余天数 = days_between(today(), due_date),是否逾期 = 剩余天数 < 0)。
  · 写 2~3 个 tests 覆盖边界:{{"inputs":{{"属性名":值,"关系名":{{"对方属性":值}},"被汇总的关系名":[{{"对方属性":值}}]}},"expect":期望值}}。
- 规则 expression 用变量名写(Python 风格:算术、比较、and/or/not、x if c else y;函数同上)。
  expression 里的每个变量都要在 inputs 里声明,不能写「关系名.属性」;变量对得上对象属性时**直接用属性名**,
  inputs 里写上 property;别的对象上的值也写成一个输入。
  规则算的正好是某类对象每条记录自己的量或判断时,再给 as_property 把它挂成计算属性(写法同 properties)。
- 原文给了算例的写进 tests;没给的按原文构造 1~2 个有代表性的(边界值)。规则 tests 的 expect 写 {{"result": 期望值}}。
- 决策表:inputs 写清类型(number / string / boolean);hit_policy=first 时,**条件更严、结论更重的行放前面**,
  保证任何取值组合都落到正确的那一行;原文分档里的每一种情况(包括「自行确认」「不用审批」)都要有一行。
  决定审批的决策表,outputs 固定用 priority(P0~P3)、approver_roles(审批角色名,取自业务角色;不用审批时留空)、
  auto(布尔值:true = 不用人批,直接执行;原文写「自行确认」「直接执行」的就是 true)。
  决策表 tests 的 expect 写 {{"result.输出名": 期望值}}。
- name 照抄上面列出的原名,一个字都不要改。原文信息不足写不出的,skip 写 true 并给 reason。

只输出 JSON:
{{"properties":[{{"object_type":"对象名","name":"英文","display_name":"中文","data_type":"number|boolean|string|date",
   "expression":"...","synonyms":[],"from":"对应的文档叫法(照抄上面列出的)","tests":[{{"inputs":{{}},"expect":1}}]}}],
 "rules":[{{"name":"原名","object_type":"对象名或空","rule_kind":"judgement|calculation|calibre","expression":"...",
   "inputs":[{{"name":"变量名","label":"中文","type":"number|integer|string|date|boolean","property":"对应的属性名或空"}}],
   "as_property":{{"name":"英文属性名","display_name":"中文","data_type":"number|boolean|string|date","expression":"..."}},
   "tests":[{{"name":"用例说明","inputs":{{"变量名":1}},"expect":{{"result":1}}}}],"skip":false,"reason":""}}],
 "decisions":[{{"name":"原名","inputs":[{{"name":"","label":"","type":"number"}}],"outputs":[{{"name":"","label":""}}],
   "rows":[{{"when":{{}},"then":{{}},"note":""}}],"hit_policy":"first","default":{{}},
   "tests":[{{"name":"","inputs":{{}},"expect":{{}}}}]}}]}}
as_property 不需要时写 null。"""

RULES_FIX_PROMPT = """下面这些计算属性 / 规则 / 决策表没过校验、测试,或者在真实数据上算不出来,请按问题改好,
输出改好后的完整定义(格式同之前,name 不要改)。

【对象及属性】
{objects}

{items}

注意:规则 expression 只能用 inputs 里的变量;计算属性和 as_property 才可以写「关系名.属性」和 count_of 这类汇总。
测试的期望值要和原文一致;原文算例本身没问题时改表达式,不要改期望值去迁就表达式。
只输出 JSON:{{"properties":[...],"rules":[...],"decisions":[...]}}"""

RULES_BATCH = 12


def _pending(run_id: str) -> list[dict]:
    return review.list_items(status="pending", kind="concept_create", source=_source(run_id), limit=1000)["items"]


def _objects_text(objs: dict[str, dict], links: list[dict]) -> str:
    """对象目录:属性名(中文名, 类型[可选值]),计算属性带公式,可写的标出来;
    n:1 关系能取对方的属性、被别的对象指向(可以汇总)也写上。"""
    lines, seen = [], set()
    for rec in objs.values():
        if id(rec) in seen:
            continue
        seen.add(id(rec))
        props = []
        for x in rec["properties"][:50]:
            bits = [x.get("display_name") or "", x.get("data_type") or ""]
            if x.get("expression"):
                bits.append(f"计算属性 = {x['expression']}")
            if x.get("is_writable"):
                bits.append("可写")
            if x.get("storage") == "ontology":
                bits.append("本系统保存")
            enum = f"[{'/'.join(x['enum_values'])}]" if x.get("enum_values") else ""
            props.append(f"{x['name']}({', '.join(b for b in bits if b)}{enum})")
        ups = [f"经关系「{l['name']}」可取 {l['to']} 的属性" for l in links if l["from"] == rec["name"] and l["n1"]]
        downs = [f"被关系「{l['name']}」的{l['from']}指向" for l in links if l["to"] == rec["name"] and l["n1"]]
        lines.append(f"- {rec['name']}:{'、'.join(props)}" + (f";{';'.join(ups)}" if ups else "")
                     + (f";{';'.join(downs)}" if downs else ""))
    return "\n".join(lines) or "(无)"


def _run_links(run_id: str) -> list[dict]:
    """这次草案 + 已有的关系:{name, from, to, n1(from 指向唯一一个 to), from_column, to_column}。"""
    out = []

    def add(name: str, sp: dict, bindings: list[dict]) -> None:
        b = next((x for x in bindings or [] if x.get("target_kind") == "join"), None)
        card = str(sp.get("cardinality") or "n:1")
        out.append({"name": name, "from": sp.get("from_type"), "to": sp.get("to_type"),
                    "n1": card in ("n:1", "1:1"), "inverse": sp.get("inverse_name") or "",
                    "from_column": ((b or {}).get("ref") or {}).get("from_column", ""),
                    "to_column": ((b or {}).get("ref") or {}).get("to_column", "")})
    for c in service.list_concepts(kind="link_type", limit=300):
        full = service.get_concept(c["id"])
        add(c["name"], full.get("spec") or {}, full.get("bindings") or [])
    for it in _pending(run_id):
        pl = it["payload"] or {}
        if pl.get("kind") == "link_type":
            add(pl["name"], pl.get("spec") or {}, pl.get("bindings") or [])
    return out


def _fn_line(p: dict) -> str:
    sp = p.get("spec") or {}
    head = f"- {p['name']}:{p.get('description') or ''}"
    if sp.get("category") == "decision":
        return head + f"(原文:{sp.get('text') or ''})现有草稿:{jdump({k: sp.get(k) for k in ('inputs', 'outputs', 'rows')})[:800]}"
    return (head + f"(原文:{sp.get('text') or ''})" + (f" 现有表达式:{sp['expression']}" if sp.get("expression") else "")
            + (f" 原文算例:{jdump(sp['examples'])[:300]}" if sp.get("examples") else ""))


_FN_SUFFIX = re.compile(r"(规则|计算|判定|判断|决策表|决策|标准|口径|公式|动作|操作|表)$")


def _core_name(s: str) -> str:
    s = re.sub(r"[\s()()「」]", "", str(s or ""))
    for _ in range(2):
        s = _FN_SUFFIX.sub("", s)
    return s


def _match_fn(name: str, by_name: dict[str, Any]) -> Any:
    """AI 写回来的名字常常和原名差几个字(「某某计算规则」写成「某某计算」):
    先精确,再去掉「规则 / 计算 / 决策表」这类后缀比,再看包含关系;对不上唯一一条就返回 None。"""
    if name in by_name:
        return by_name[name]
    c = _core_name(name)
    if not c:
        return None
    hits = [v for n, v in by_name.items() if _core_name(n) == c] or \
        [v for n, v in by_name.items() if c in _core_name(n) or _core_name(n) in c]
    return hits[0] if len(hits) == 1 else None


def _num_eq(a: Any, b: Any) -> bool:
    if isinstance(a, bool) or isinstance(b, bool):
        return bool(a) == bool(b) if isinstance(a, bool) and isinstance(b, bool) else a == b
    try:
        return abs(float(a) - float(b)) < 1e-6
    except (TypeError, ValueError):
        return str(a) == str(b)


def _prop_test_failures(prop: dict) -> list[str]:
    """计算属性的测试:把用例的输入当成一条记录(关联对象是嵌套字典,被汇总的记录是列表)逐个求值。"""
    from . import rules as rule_engine
    out = []
    for i, t in enumerate(prop.get("tests") or [], 1):
        if not isinstance(t, dict):
            continue
        env = dict(t.get("inputs") or {})
        try:
            got = rule_engine.evaluate(prop["expression"], env)
        except Exception as e:  # noqa: BLE001
            out.append(f"用例 {i}:算不出({e})")
            continue
        want = t.get("expect")
        if isinstance(want, dict) and "result" in want:
            want = want["result"]
        if not _num_eq(got, want):
            out.append(f"用例 {i}:输入 {jdump(env)[:120]} 期望 {want},实际算出 {got}")
    return out


def _rules(run_id: str, note, only: set[str] | None = None) -> tuple[int, int, int, dict]:
    """对象上的量和状态 → 计算属性;规则 / 决策表 → 能直接算的定义;测试用例当场跑一遍;
    计算属性再在真实数据上试算;没过的(测试、校验、试算)合在一起按错误改一轮。
    only:只处理这几条草案(按对账修改时用)。返回 (写成的条数, 处理的条数, 挂上的计算属性数, {all, ok} 测试用例数)。"""
    from ..governance import roles
    from . import fntests
    pend = _pending(run_id)
    todo = [it for it in pend if (it["payload"] or {}).get("kind") == "function"
            and ((it["payload"].get("spec") or {}).get("category") in ("rule", "decision"))
            and (only is None or it["id"] in only)]
    derived: list[tuple[dict, dict]] = []
    for it in pend:
        pl = it["payload"] or {}
        if pl.get("kind") != "object_type" or (only is not None and it["id"] not in only):
            continue
        for d in pl.get("derived") or []:
            if not d.get("done"):
                derived.append((it, d))
    tests = {"all": 0, "ok": 0}
    if not todo and not derived:
        note("计算属性与规则:这次没有")
        return 0, 0, 0, tests
    objs = _run_objects(run_id)
    links = _run_links(run_id)
    catalog = _objects_text(objs, links)
    names = "、".join([it["payload"]["name"] for it in todo[:6]] + [d["name"] for _, d in derived[:6]])
    note(f"对象上的量和状态 {len(derived)} 个、规则和决策表 {len(todo)} 条({names} 等):写成公式、挂到对象上、跑测试、在数据上试算")
    batches = [todo[i:i + RULES_BATCH] for i in range(0, len(todo), RULES_BATCH)][:4] or [[]]
    der_text = "\n".join(f"- {it['payload']['name']}|{d['name']}|{'状态' if d.get('kind') == 'state' else '量'}|"
                         f"{d.get('text') or ''}" + (f"(这一类记录叫:{'、'.join(d['subset_names'])})" if d.get("subset_names") else "")
                         for it, d in derived) or "(无)"

    def one(ib: tuple[int, list[dict]]) -> tuple[list[dict], dict, str]:
        i, batch = ib
        rs = [it["payload"] for it in batch if (it["payload"].get("spec") or {}).get("category") == "rule"]
        ds = [it["payload"] for it in batch if (it["payload"].get("spec") or {}).get("category") == "decision"]
        msg = RULES_PROMPT.format(objects=catalog, roles="、".join(f"{r['name']}({r['description']})" if r.get("description") else r["name"]
                                                                  for r in roles.list_roles()) or "(无)",
                                  derived=der_text if i == 0 else "(无)",
                                  rules="\n".join(_fn_line(x) for x in rs) or "(无)",
                                  decisions="\n".join(_fn_line(x) for x in ds) or "(无)")
        what = "、".join([x["name"] for x in rs + ds] + ([f"{len(derived)} 个计算属性"] if i == 0 and derived else []))
        try:
            with llmlog.feature("modeling_rules"), llm.trace_label(f"计算属性与规则:{what[:60]}"):
                res = llm.chat_json([{"role": "user", "content": msg}], temperature=0.1)
        except Exception as e:  # noqa: BLE001
            return batch, {}, str(e)[:120]
        return batch, res if isinstance(res, dict) else {}, ""

    done = props_added = 0
    by_name = {it["payload"]["name"]: it for it in todo}
    der_by = {d["name"]: (it, d) for it, d in derived}

    def apply(it: dict, r: dict, final: bool) -> list[str] | None:
        """把一条写好的规则 / 决策表落进草案并跑测试。返回没过的测试(None = 没写成);
        不是最后一轮时,没过的先不落盘,留给按错误改的那一轮。"""
        p = dict(it["payload"])
        spec = dict(p.get("spec") or {})
        if spec.get("category") == "decision":
            new_spec, msg = _decision_spec(spec, r, p["name"], note)
        else:
            new_spec, msg = _rule_spec(spec, r)
        if new_spec is None:
            if final:
                note(f"「{p['name']}」没写成:{msg},保留原样")
            return None if final else [msg]
        fails = _rule_problems(new_spec)
        if new_spec.get("tests") and not fails:
            outcome = fntests.run({"name": p["name"], "kind": "function", "spec": new_spec})
            fails = [f"{x['name']}:{x['error']}" for x in outcome if not x["ok"]]
        if fails and not final:
            return fails
        n_tests = len(new_spec.get("tests") or [])
        tests["all"] += n_tests
        tests["ok"] += n_tests - len(fails) if n_tests else 0
        p["spec"] = new_spec
        p["deepened"] = True
        p.pop("test_failures", None)
        if fails:
            p["test_failures"] = fails[:5]
            note(f"「{p['name']}」测试没过:{fails[0]}(请对照原文看看)")
        review.update_payload(it["id"], p)
        it["payload"] = p
        return fails

    def attach_prop(r: dict, final: bool, fn_payload: dict | None = None) -> str:
        """挂一个计算属性。返回问题(空串 = 挂上了);不是最后一轮时,测试没过的先不挂。"""
        obj = str(r.get("object_type") or (fn_payload or {}).get("spec", {}).get("object_type") or "")
        fails = _prop_test_failures(r) if r.get("expression") else ["没有公式"]
        if fails and not final:
            return "测试没过:" + ";".join(fails[:2])
        why = _attach_property(objs, links, obj, r, fn_payload or {"name": r.get("from") or r.get("display_name") or r.get("name"),
                                                                     "description": ""}, replace=True)
        if why:
            return why
        tests["all"] += len(r.get("tests") or [])
        tests["ok"] += len(r.get("tests") or []) - len(fails)
        src = der_by.get(str(r.get("from") or "")) or der_by.get(str(r.get("display_name") or ""))
        if src:
            src[1]["done"] = r["name"]
            pl = dict(src[0]["payload"])
            pl["derived"] = [{**d, "done": r["name"]} if d["name"] == src[1]["name"] else d for d in pl.get("derived") or []]
            # 计算属性挂上之后对象的 payload 已被 _attach_property 改过:以那份为准,只补上 derived 的进度
            rec = _resolve_obj(obj, objs)
            if rec is not None and rec["item"] is not None:
                rec["item"]["payload"] = {**rec["item"]["payload"], "derived": pl["derived"]}
                review.update_payload(rec["item"]["id"], rec["item"]["payload"])
        if fails:
            note(f"计算属性「{r.get('display_name') or r['name']}」测试没过:{fails[0]}")
        return ""

    retry: list[tuple[str, Any, dict, list[str]]] = []       # (种类, 草案或对象名, 写回来的定义, 问题)
    for batch, res, err in _pool_map(one, list(enumerate(batches)), PARALLEL):
        if err:
            note(f"这一批没写成:{err}")
            continue
        for r in res.get("properties") or []:
            if not isinstance(r, dict) or not r.get("name"):
                continue
            why = attach_prop(r, final=False)
            if why:
                retry.append(("property", r.get("object_type"), r, [why]))
            else:
                props_added += 1
        for r in (res.get("rules") or []) + (res.get("decisions") or []):
            if not isinstance(r, dict):
                continue
            it = _match_fn(str(r.get("name") or ""), by_name)
            if it is None:
                ap = r.get("as_property")
                if isinstance(ap, dict) and ap.get("name") and ap.get("expression"):
                    # 不在清单里的规则(AI 顺手写的中间量):规则不要,算出来的量挂到对象上
                    if not attach_prop({**ap, "object_type": r.get("object_type"), "tests": []}, final=True):
                        props_added += 1
                        note(f"「{r.get('name')}」不在规则清单里,只把它挂成计算属性 {ap['name']} = {ap['expression']}")
                else:
                    note(f"AI 写回来的「{r.get('name')}」对不上清单里的规则,丢弃")
                continue
            if r.get("skip"):
                note(f"「{it['payload']['name']}」原文信息不足,保留文字描述:{r.get('reason') or ''}")
                continue
            fails = apply(it, r, final=False)
            if fails:
                retry.append(("fn", it, r, fails))
                continue
            done += 1
            if _attach_rule_prop(it, r, attach_prop):
                props_added += 1
    # 挂上的计算属性在真实数据上算一遍:编译不过(属性名、关系名写错)的也一起改
    trial_bad = _trial_new_props(run_id, objs, note)
    for obj, prop, err in trial_bad:
        retry.append(("property", obj, prop, [f"在真实数据上算不出:{err}"]))
    for it, d in derived:
        if not d.get("done") and not any(k == "property" and str((r or {}).get("from") or "") == d["name"] for k, _, r, _ in retry):
            note(f"「{it['payload']['name']}」的「{d['name']}」没写成计算属性")
    if retry:
        brief = ";".join(f"{(x.get('payload') or {}).get('name') if k == 'fn' else (r.get('display_name') or r.get('name'))}:"
                         f"{fails[0][:60]}" for k, x, r, fails in retry[:3])
        note(f"{len(retry)} 条没过({brief}),按错误改一次")
        ask = "\n\n".join(f"「{(x['payload']['name'] if k == 'fn' else r.get('name'))}」"
                          f"({'计算属性,对象 ' + str(x) if k == 'property' else '函数'})现在写的是:{jdump(r)}\n问题:"
                          + ";".join(f[:200] for f in fails[:4]) for k, x, r, fails in retry)
        fixed_fn: dict[str, dict] = {}
        fixed_prop: dict[str, dict] = {}
        try:
            with llmlog.feature("modeling_rules_fix"), llm.trace_label("计算属性与规则:按错误改"):
                res = llm.chat_json([{"role": "user", "content": RULES_FIX_PROMPT.format(objects=_objects_text(objs, links),
                                                                                         items=ask)}], temperature=0)
            if isinstance(res, dict):
                fixed_fn = {str(x.get("name")): x for x in (res.get("rules") or []) + (res.get("decisions") or [])
                            if isinstance(x, dict)}
                fixed_prop = {str(x.get("name")): x for x in res.get("properties") or [] if isinstance(x, dict)}
        except Exception as e:  # noqa: BLE001
            note(f"按错误改没成:{str(e)[:80]}")
        for k, x, r, _ in retry:
            if k == "fn":
                r2 = _match_fn(x["payload"]["name"], fixed_fn)
                r2 = {**r, **r2} if r2 else r
                if apply(x, r2, final=True) is not None:
                    done += 1
                    if _attach_rule_prop(x, r2, attach_prop):
                        props_added += 1
            else:
                r2 = fixed_prop.get(str(r.get("name"))) or r
                r2 = {**r, **r2, "object_type": r2.get("object_type") or x}
                why = attach_prop(r2, final=True)
                if why:
                    note(f"计算属性「{r2.get('display_name') or r2.get('name')}」没挂上:{why}")
                else:
                    props_added += 1
        for obj, prop, err in _trial_new_props(run_id, objs, note, quiet=True):
            note(f"计算属性「{prop.get('display_name') or prop.get('name')}」改过之后在数据上还是算不出:{err}")
    return done, len(todo), props_added, tests


def _attach_rule_prop(it: dict, r: dict, attach_prop) -> bool:
    """规则带了 as_property:把它算的量挂成对象的计算属性。"""
    ap = r.get("as_property")
    if not isinstance(ap, dict) or not ap.get("name") or not ap.get("expression"):
        return False
    obj = str(r.get("object_type") or (it["payload"].get("spec") or {}).get("object_type") or "")
    why = attach_prop({**ap, "object_type": obj, "tests": []}, True, it["payload"])
    return not why


def _trial_new_props(run_id: str, objs: dict[str, dict], note, quiet: bool = False) -> list[tuple[str, dict, str]]:
    """这次挂上的计算属性在真实数据上算一遍,返回算不出来的 [(对象名, 属性定义, 原因)]。"""
    from . import modeling_world
    bad: list[tuple[str, dict, str]] = []
    pend = _pending(run_id)
    seen = set()
    with modeling_world.world(pend):
        for rec in objs.values():
            if id(rec) in seen or rec["item"] is None or not rec.get("binding"):
                continue
            seen.add(id(rec))
            props = [x for x in rec["properties"] if x.get("expression")]
            if not props:
                continue
            res = modeling_world.property_trial(rec["name"], [x["name"] for x in props])
            for x in props:
                t = res.get(x["name"]) or {}
                if t.get("ok"):
                    if not quiet:
                        note(f"「{rec['name']}.{x.get('display_name') or x['name']}」= {x['expression']}:{t['summary']}")
                else:
                    bad.append((rec["name"], {**x, "object_type": rec["name"]}, str(t.get("error") or "算不出")))
    return bad


def _rule_problems(spec: dict) -> list[str]:
    """规则表达式只能用自己的输入:写了「关系名.属性」、或者用了没声明的变量,求值时就是空值。"""
    if spec.get("category") != "rule" or not spec.get("expression"):
        return []
    from . import rules as rule_engine
    try:
        used = rule_engine.free_names(spec["expression"])
    except Exception as e:  # noqa: BLE001
        return [f"表达式有误:{e}"]
    have = {i.get("name") for i in spec.get("inputs") or []}
    ghost = [n for n in used if n not in have and n not in ("today",)]
    return [f"表达式里的 {'、'.join(ghost)} 不是这条规则的输入(规则只能用 inputs 里的变量,"
            f"要用别的对象的值就加一个输入;跨关系取值只能写在 as_property 里)"] if ghost else []


def _rule_spec(spec: dict, r: dict) -> tuple[dict | None, str]:
    expr = str(r.get("expression") or "").strip()
    if not expr:
        return None, "没有表达式"
    inputs = [{"name": str(i.get("name")), "label": str(i.get("label") or i.get("name")),
               "type": str(i.get("type") or "number"), "required": True,
               "description": f"对应属性 {i['property']}" if i.get("property") else ""}
              for i in r.get("inputs") or [] if isinstance(i, dict) and i.get("name")]
    try:
        return schema.normalize_spec("function", {
            **spec, "expression": expr, "params": [i["name"] for i in inputs], "inputs": inputs,
            "rule_kind": r.get("rule_kind") or spec.get("rule_kind") or "judgement",
            "object_type": str(r.get("object_type") or spec.get("object_type") or ""),
            "output_type": "boolean" if (r.get("rule_kind") or spec.get("rule_kind")) == "judgement" else "number",
            "tests": [t for t in r.get("tests") or [] if isinstance(t, dict)][:6]}), ""
    except schema.SpecError as e:
        return None, str(e)


def _decision_spec(spec: dict, r: dict, name: str, note) -> tuple[dict | None, str]:
    """决策表规范化 + 体检;同一组取值命中多行而结论不同(first 只取第一行)就让 AI 按原文改一次行序。"""
    from . import decision as decision_engine
    cand = {**spec, **{k: r[k] for k in ("inputs", "outputs", "rows", "hit_policy", "default") if r.get(k) is not None},
            "tests": [t for t in r.get("tests") or [] if isinstance(t, dict)][:8]}
    try:
        out = schema.normalize_spec("function", cand)
    except schema.SpecError as e:
        return None, str(e)
    chk = decision_engine.check(out)
    clash = [o for o in chk["overlaps"]
             if len({jdump(out["rows"][i - 1]["then"]) for i in o["rows"]}) > 1] if out.get("hit_policy") == "first" else []
    if not clash and not chk["shadowed"]:
        return out, ""
    detail = ";".join(f"取值 {jdump(o['inputs'])} 同时命中第 {'、'.join(map(str, o['rows']))} 行,按「第一条命中」只取第 {o['rows'][0]} 行"
                      for o in clash[:3])
    if chk["shadowed"]:
        detail += f";第 {'、'.join(map(str, chk['shadowed']))} 行被前面的行挡住了"
    msg = (f"决策表「{name}」的行序有问题:{detail}。原文:{spec.get('text') or ''}\n"
           f"现在的表:{jdump({k: out.get(k) for k in ('inputs', 'outputs', 'rows', 'hit_policy', 'default')})}\n"
           "请按原文调整行的顺序或条件(条件更严、结论更重的放前面),输出完整决策表 JSON:"
           '{"inputs":[],"outputs":[],"rows":[],"hit_policy":"first","default":{}}')
    try:
        with llmlog.feature("modeling_rules_fix"), llm.trace_label(f"理顺决策表:{name}"):
            fix = llm.chat_json([{"role": "user", "content": msg}], temperature=0)
        out2 = schema.normalize_spec("function", {**out, **{k: fix[k] for k in ("inputs", "outputs", "rows", "hit_policy", "default")
                                                           if isinstance(fix, dict) and fix.get(k) is not None}})
    except Exception as e:  # noqa: BLE001
        note(f"「{name}」行序有问题({detail}),没改成:{str(e)[:80]}")
        return out, ""
    chk2 = decision_engine.check(out2)
    clash2 = [o for o in chk2["overlaps"] if len({jdump(out2["rows"][i - 1]["then"]) for i in o["rows"]}) > 1]
    if len(clash2) + len(chk2["shadowed"]) <= len(clash) + len(chk["shadowed"]):
        note(f"「{name}」按原文理顺了行序({detail})")
        return out2, ""
    return out, ""


def _attach_property(objs: dict[str, dict], links: list[dict], obj_name: str, ap: dict, fn_payload: dict,
                     replace: bool = False) -> str:
    """把一个计算属性挂到对象上(草案里的对象改草案)。返回不挂的原因,空串 = 挂上了。
    replace:同名的计算属性换成新的(按错误改的那一轮);同名的普通属性(表里的列)不动。"""
    rec = _resolve_obj(obj_name, objs)
    if rec is None:
        return f"找不到对象「{obj_name}」"
    if rec["item"] is None:
        return "对象已经上线了,计算属性请在对象页加"
    name = str(ap.get("name") or "").strip()
    if not re.match(r"^[A-Za-z_][A-Za-z0-9_]*$", name):
        return f"属性名「{name}」要用英文"
    from . import rules as rule_engine
    old = next((x for x in rec["properties"] if x["name"] == name), None)
    if old is not None and not (replace and old.get("expression")):
        return f"已经有属性 {name}"
    expr = rule_engine.normalize_text(str(ap.get("expression") or "").strip())
    try:
        used = set(rule_engine.free_names(expr)) - set(rule_engine.rollup_names(expr))
    except Exception as e:  # noqa: BLE001
        return f"表达式有误:{e}"
    have = {x["name"] for x in rec["properties"] if x["name"] != name}
    ups = {l["name"] for l in links if l["from"] == rec["name"] and l["n1"]} |           {l["to"] for l in links if l["from"] == rec["name"] and l["n1"]}
    bad = sorted(n for n in used if n not in have and n not in ups)
    if bad:
        return f"用到了对象上没有的 {'、'.join(bad)}"
    dt = str(ap.get("data_type") or "number")
    prop = {"name": name, "display_name": str(ap.get("display_name") or fn_payload.get("name") or name)[:40],
            "data_type": dt if dt in schema.DATA_TYPES else "number",
            "description": str(ap.get("description") or fn_payload.get("description") or "")[:200],
            "expression": expr, "is_key": False, "is_time": False, "is_dimension": dt == "boolean", "is_writable": False,
            "enum_values": [], "synonyms": [str(x) for x in ap.get("synonyms") or [] if x][:8]}
    if old is not None:
        rec["properties"][rec["properties"].index(old)] = prop
    else:
        rec["properties"].append(prop)
    payload = dict(rec["item"]["payload"])
    payload["spec"] = {**(payload.get("spec") or {}), "properties": rec["properties"]}
    review.update_payload(rec["item"]["id"], payload)
    rec["item"]["payload"] = payload
    return ""


METRIC_PROMPT = """把下面这个指标写成一条取数定义(SQL 方言 {dialect})。
指标:{name}(单位:{unit})
口径:{formula}
说明:{desc}

对象「{obj}」的计算属性(每条记录自己算出来的量和状态,已经在真实数据上算过):
{derived}

主表 {table}(对象「{obj}」)的列(列名 类型 含义):
{columns}

经关系连得到的表(可以在 expression / filters 里用子查询引用,如
customer_id IN (SELECT customer_id FROM 客户表 WHERE level = 'A')):
{related}

两种写法,能用第一种就用第一种(口径和对象上的计算属性同源,改一处处处生效):
1. 建在对象上:{{"base_object":"{obj}","expression":"SUM(amount_due)"或"SUM(CASE WHEN is_overdue THEN 1 ELSE 0 END)",
   "dimensions":{{}},"filters":[]}} —— expression / filters / dimensions 里直接写对象的属性名(含上面的计算属性)。
2. 直接查表:{{"base_table":"{table}","expression":"...","dimensions":{{}},"filters":[],"time_column":"","object_key_column":""}}。
   口径其实按另一张表的记录来算时,把 base_table 换成那张表(只能是上面列出的表),
   object_key_column 写能对上本对象的那一列,维度也取那张表的列。

要求:
- expression 是 SELECT 里的一个聚合表达式,如 SUM(x)、AVG(CASE WHEN a < b THEN 1.0 ELSE 0 END)、COUNT(*)。
  单位是 % / 百分比 时算成 0~100 的数。
- 真算不出时才输出 {{"skip": true, "reason": "一句话"}}。
- dimensions:{{维度名: 列名或属性名}},挑 2~4 个类别型的(编号、状态、类别、地区等),维度名用中文业务叫法;
  dimension_types:维度指向哪类对象就写 {{维度名: 对象名}}。
- time_column:口径涉及可选的统计时间段且有日期列时填,否则空串;固定的窗口(近 90 天)直接写进 filters。
- filters:口径里固定的过滤条件(SQL 片段数组),没有就空数组。
- same_column:表里已经有一列存的就是这个数(只是没按口径现算)时写那一列的列名,否则空串。
只输出 JSON。"""


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
    for it in _pending(run_id):
        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 {}
    dims = [ident(c) for c in (ref.get("dimensions") or {}).values()]
    sql = f"SELECT {', '.join(dims + [ref['expression'] + ' AS v'])} FROM {ident(table)}"
    if ref.get("filters"):
        sql += " WHERE " + " AND ".join(f"({f})" for f in ref["filters"])
    if dims:
        sql += " GROUP BY " + ", ".join(dims)
    out = executor.execute(ds_id, to_dialect(sql, ds.get("ds_type") or "mysql"), ds.get("ds_type") or "mysql",
                           policy="catalog")
    return "" if out.ok else str(out.error or "执行失败")[:300]


def _bind_metrics(run_id: str, note, only: set[str] | None = None) -> tuple[int, int]:
    """聚合函数只有口径文字、没有取数方式。对象已经绑了表,就让 AI 写出取数定义并实跑校验:
    优先建在对象上(直接用对象的计算属性,口径同源),不行再直接查表。写不出或跑不通的保持未绑定,由人补。"""
    from ..text2sql import semantic
    from . import modeling_world
    objs = _run_objects(run_id)
    links = _run_links(run_id)
    todo = [it for it in _pending(run_id) if (it["payload"] or {}).get("kind") == "function"
            and ((it["payload"].get("spec") or {}).get("category") == "aggregate")
            and (only is not None and it["id"] in only
                 or only is None and not any(b.get("target_kind") == "metric_expr" for b in it["payload"].get("bindings") or []))]
    batch = todo[:MAX_DEEPEN]
    note(f"指标取数:{len(todo)} 个指标还没有取数方式" + (f",本次处理 {len(batch)} 个" if len(todo) > len(batch) else "")
         + ",写好后会在业务库里实跑一次校验")

    def one(it: dict) -> tuple[dict, dict, str, str]:
        p = it["payload"]
        spec = p.get("spec") or {}
        obj = _resolve_obj(str(spec.get("object_type") or ""), objs)
        if not obj or not obj.get("binding"):
            return it, {}, "它的对象没有绑定数据表,取数方式留给人补", ""
        b = obj["binding"]
        table = b["ref"]["table"]
        ds = semantic.get_datasource(int(b["ds_id"])) or {}
        models = semantic.models_with_columns(int(b["ds_id"]))

        def col_text(t: str) -> str:
            return "\n".join(f"- {c.get('physical_column') or c['name']} {c.get('data_type')} {c.get('description') or ''}"
                             for m in models if (m.get("physical_table") or m["name"]) == t for c in m.get("columns") or [])
        related, tables = [], {table}
        for l in links:
            if obj["name"] not in (l["from"], l["to"]) or not l["from_column"]:
                continue
            other = _resolve_obj(l["to"] if l["from"] == obj["name"] else l["from"], objs)
            ot = ((other or {}).get("binding") or {}).get("ref", {}).get("table") if other else ""
            if not ot or ot in tables:
                continue
            tables.add(ot)
            mine, theirs = (l["from_column"], l["to_column"]) if l["from"] == obj["name"] else (l["to_column"], l["from_column"])
            related.append(f"表 {ot}(对象「{other['name']}」,关系「{l['name']}」:{table}.{mine} = {ot}.{theirs})的列:\n"
                           + col_text(ot))
        derived = "\n".join(f"- {x['name']}({x.get('display_name') or ''},{x.get('data_type')})= {x['expression']}"
                            for x in obj["properties"] if x.get("expression")) or "(无)"
        msgs = [{"role": "user", "content": METRIC_PROMPT.format(
            table=table, obj=obj["name"], 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(table),
            derived=derived, related="\n\n".join(related) or "(无)")}]
        err, same = "", ""
        for _attempt in (1, 2):
            try:
                with llmlog.feature("modeling_metric"), llm.trace_label(f"写取数式:{p['name']}"):
                    res = llm.chat_json(msgs, temperature=0.1)
            except Exception as e:  # noqa: BLE001
                return it, {}, str(e)[:120], ""
            if not isinstance(res, dict) or res.get("skip"):
                return it, {}, ((res or {}).get("reason") or "这张表算不出这个口径") if isinstance(res, dict) else "输出无效", ""
            same = str(res.get("same_column") or "").strip()
            binding: dict = {}
            try:
                if res.get("base_object"):
                    ref = schema.normalize_binding("metric_expr", {**res, "base_object": obj["name"], "base_table": ""})
                    binding = {"ds_id": int(b["ds_id"]), "target_kind": "metric_expr", "ref": ref}
                    with modeling_world.world(_pending(run_id)):
                        t = modeling_world.metric_trial({"id": "draft:m", "kind": "function", "name": p["name"],
                                                         "spec": spec, "bindings": [binding]})
                    err = "" if t.get("ok") else str(t.get("error"))
                else:
                    base = str(res.get("base_table") or table)
                    if base not in tables:
                        raise schema.SpecError(f"base_table 只能是这几张表:{'、'.join(sorted(tables))}")
                    ref = schema.normalize_binding("metric_expr", {**res, "base_table": base})
                    binding = {"ds_id": int(b["ds_id"]), "target_kind": "metric_expr", "ref": ref}
                    err = _try_metric_sql(int(b["ds_id"]), base, ref)
            except schema.SpecError as e:
                err = str(e)
            if not err:
                return it, binding, "", same
            msgs += [{"role": "assistant", "content": jdump(res)},
                     {"role": "user", "content": f"执行报错:{err}\n请修正后输出完整 JSON。"}]
        return it, {}, err, same

    done = 0
    for it, binding, err, same in _pool_map(one, batch, PARALLEL):
        p = dict(it["payload"])
        if same:
            p["calibre_conflicts"] = [{"column": same, "note": f"业务表里的「{same}」列存的也是这个数,但没按口径现算;"
                                                            f"规则和监控里要统一用指标(或这一列),不要两套混用"}]
        if err or not binding:
            if same:
                review.update_payload(it["id"], p)
            note(f"「{p['name']}」没绑上取数方式:{err}")
            continue
        p["bindings"] = [*[x for x in p.get("bindings") or [] if x.get("target_kind") != "metric_expr"], binding]
        review.update_payload(it["id"], p)
        done += 1
        where = f"建在对象「{binding['ref']['base_object']}」上" if binding["ref"].get("base_object") else f"查表 {binding['ref']['base_table']}"
        note(f"「{p['name']}」= {binding['ref']['expression']}({where},已在业务库实跑通过)"
             + (f";注意:表里的「{same}」列和它是同一个数" if same else ""))
    return done, len(batch)


ACTION_ASK = """动作:{name}
说明:{desc}
原文要点:{text}
原文出处:
{evidence}

文档里的审批规则、管理动作和业务规则(逐条):
{reqs}

业务角色和职责:{roles}

另外注意:
- 审批人**照文档写**:先看上面的审批规则里有没有专门说这个动作谁批,再看角色职责;不要换成别的角色。
  文档写「自行确认」「直接登记」「无需审批」的,approval.mode 写 auto。
- 审批按条件分档(按金额、按对象状态定谁批、优先级)时,approval 写 mode=conditional,
  并用 approval.decision 挂上面「函数」里对应的审批决策表:{{"function":"决策表名","inputs":{{"决策表输入名":"=表达式"}}}},
  表达式可以用参数、lookups 的英文名.属性、eff.属性(效果里算出来的值)。用了 approval.decision 就不要再写 stages。
- 原文说新建时是什么状态(如「先为待审批」),按可选值写对状态。
- 数量、金额有对应的规则函数或计算属性时按同样的算法写,算法要和它一致。
- 写入有可选值的属性,只能写可选值之一。
- 要存的信息(原因、备注、说明、人工判断)在对象里**没有对应属性**时,不要挪用别的属性(尤其不要把原因拼进状态里):
  在顶层 "new_properties" 里声明,由本系统保存:
  [{{"object_type":"对象名","name":"英文属性名","display_name":"中文","data_type":"text|string|number|date"}}],
  效果里照常用 object.write 写它。"""


def _draft_functions_text(run_id: str) -> str:
    """已上线的函数 + 这次草案里的函数(决策表带输入输出,动作才能挂上审批决策)。"""
    from . import draft
    lines = [draft._functions_text()]
    for it in _pending(run_id):
        pl = it["payload"] or {}
        sp = pl.get("spec") or {}
        if pl.get("kind") != "function":
            continue
        if sp.get("category") == "decision":
            lines.append(f"- {pl['name']}(决策表,草案):输入 {[i.get('name') for i in sp.get('inputs') or []]},"
                         f"输出 {[o.get('name') for o in sp.get('outputs') or []]};{(pl.get('description') or '')[:60]}")
        elif sp.get("category") == "rule":
            lines.append(f"- {pl['name']}(规则,草案):{sp.get('expression') or sp.get('text') or ''}")
        else:
            lines.append(f"- {pl['name']}({schema.kind_label('function', sp)},草案):{(pl.get('description') or '')[:60]}")
    return "\n".join(x for x in lines if x and x != "(无)") or "(无)"


def _writes(e: dict, spec: dict) -> list[tuple[str, dict, dict]]:
    """一项效果要写哪些对象的哪些属性:[(对象名, args, {属性: 值})]。
    object.write 可以只改一个(property + value),也可以一次改几个(values);object.batch 是一组写入。"""
    args = e.get("args") or {}
    tool = e.get("tool")
    if tool == "object.batch":
        return [(str(op.get("object_type") or spec.get("target_type") or ""), op, dict(op.get("values") or {}))
                for op in args.get("ops") or [] if isinstance(op, dict)]
    if tool == "object.create":
        return [(str(args.get("object_type") or spec.get("target_type") or ""), args, dict(args.get("values") or {}))]
    if tool == "object.write":
        vals = dict(args["values"]) if isinstance(args.get("values"), dict) and args["values"] \
            else ({str(args["property"]): args.get("value")} if args.get("property") else {})
        return [(str(args.get("object_type") or spec.get("target_type") or ""), args, vals)]
    return []


def _check_enum_writes(spec: dict, objs: dict[str, dict]) -> str:
    """有可选值的属性只能写可选值:'已延期:' + 原因 这种把说明拼进状态的写法打回去。"""
    for e in spec.get("effects") or []:
        for obj, _, vals in _writes(e, spec):
            rec = _resolve_obj(obj, objs)
            if rec is None:
                continue
            bad = _bad_enum(rec, vals)
            if bad:
                return bad
    return ""


def _bad_enum(rec: dict, vals: dict) -> str:
    props = {x["name"]: x for x in rec["properties"]}
    for prop, val in vals.items():
        enum = (props.get(str(prop or "")) or {}).get("enum_values") or []
        if not enum or not isinstance(val, str) or val.startswith("$"):
            continue
        if (val.startswith("=") and "+" in val) or any(v not in enum for v in _lits(val)):
            return (f"{rec['name']}.{prop} 只能取 {'/'.join(enum)},不能写 {val};"
                    f"要存的说明没有地方放,就在 new_properties 里声明一个本体自有属性来存")
    return ""


def _lits(val: str) -> list[str]:
    lits = re.findall(r"'([^']*)'|\"([^\"]*)\"", val) if val.startswith("=") else [(val, "")]
    return [a or b for a, b in lits]


def _complete_actions(run_id: str, note, reqs: list[dict] | None = None,
                      only: set[str] | None = None) -> tuple[int, int, int]:
    """文档只说明了「要有这个动作」。对象和系统效果都已知,就让 AI 写出参数、前置条件和效果,
    过一遍动作校验再采用;用到 object.write 的属性顺手标成可写,否则执行时才发现写不进去。
    给它看的不只是动作名:还有文档里的审批规则、管理动作、角色职责(以前没给,审批人常常写错)。
    业务表里没有地方存的信息(原因、备注),建成本体自有属性,值由本系统保存,动作照常能写。
    only:只处理这几条草案(按对账修改时用)。返回 (补全的个数, 处理的个数, 建了本体自有属性的条数)。"""
    from ..governance import roles
    from . import draft
    objs = _run_objects(run_id)
    todo = [it for it in _pending(run_id) if (it["payload"] or {}).get("kind") == "action"
            and ((it["payload"].get("spec") or {}).get("_stub") if only is None else it["id"] in only)]
    if not todo:
        note("动作补全:没有需要补全的动作")
        return 0, 0, 0
    note(f"动作补全:{len(todo)} 个动作只有说明,要补参数、前置条件和执行效果(写完逐个过校验,不通过会按错误改最多几次)")
    role_text = ";".join(f"{r['name']}:{r['description']}" if r.get("description") else r["name"]
                         for r in roles.list_roles()) or "(无,可留空)"
    guide = (draft.GUIDES["action"].replace("{tools}", draft._tools_text()).replace("{roles}", role_text))
    system = draft.GENERATE_SYSTEM.format(guide=guide, objects=_objects_text(objs, _run_links(run_id)),
                                          functions=_draft_functions_text(run_id))
    rules_text = "\n".join(f"- {r['id']}【{r['kind_label']}】{r['text']}" for r in reqs or []
                           if r["kind"] in ("approval", "action", "rule")) or "(没有拆出条目)"
    lock = threading.Lock()

    def one(it: dict) -> tuple[dict, dict, str]:
        p = dict(it["payload"])
        ev = "\n".join(f"- {e.get('heading') or ''}:{e.get('snippet') or ''}" for e in (p.get("evidence") or [])[:4]) or "(无)"
        msgs = [{"role": "system", "content": system},
                {"role": "user", "content": ACTION_ASK.format(name=p["name"], desc=p.get("description") or "",
                                                              text=(p.get("spec") or {}).get("text") or "",
                                                              evidence=ev, reqs=rules_text, roles=role_text)}]
        spec, err = {}, ""
        for attempt in (1, 2, 3):
            try:
                # 第一次要想清楚参数和效果;后面几次只是照着校验错误改,不用再长考
                feat, tag = ("modeling_action", "") if attempt == 1 else ("modeling_action_fix", f"(按校验错误改,第 {attempt} 次)")
                with llmlog.feature(feat), llm.trace_label(f"补全动作:{p['name']}{tag}"):
                    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 {}
            newp = [x for x in (res.get("new_properties") or []) if isinstance(x, dict) and x.get("name")] \
                if isinstance(res, dict) else []
            with lock:                     # objs 是几个动作共用的,加属性、标可写属性时不能同时改
                made = _own_properties(newp, objs)
                if made:
                    p["schema_gaps"] = [{"object_type": o, "need": d, "why": "业务表里没有这一列", "resolved": n}
                                        for o, n, d in made]
                err = _check_action_refs(spec, objs) or _check_enum_writes(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。"}]
        return p, spec, err

    batch = todo[:MAX_DEEPEN]
    results = list(zip(batch, _pool_map(one, batch, ACTION_PARALLEL)))
    done = own = 0
    for it, (p, spec, err) in results:
        if p.get("schema_gaps"):
            own += 1
            note(f"「{p['name']}」要存的信息业务表里没有列,建成了本体自有属性:"
                 + "、".join(f"{g['object_type']}.{g['need']}" for g in p["schema_gaps"]))
        if err or not spec:
            note(f"「{p['name']}」没能补全:{err}(采纳后在动作页补)")
            review.update_payload(it["id"], p)
            continue
        p["spec"] = spec
        p["completed"] = True
        p.pop("problems", None)
        review.update_payload(it["id"], p)
        done += 1
        tools = "、".join(e.get("tool", "") for e in spec.get("effects") or [])
        appr = (spec.get("approval") or {})
        how = f",审批按决策表「{appr['decision']['function']}」" if (appr.get("decision") or {}).get("function") else \
            (f",审批人:{'、'.join(r for s_ in appr.get('stages') or [] for r in s_.get('approver_roles') or [])}" if appr.get("stages") else "")
        note(f"「{p['name']}」已补全:{len(spec.get('params') or [])} 个参数,效果 {tools}{how}")
    return done, len(batch), own


def _own_properties(newp: list[dict], objs: dict[str, dict]) -> list[tuple[str, str, str]]:
    """动作要存、业务表里又没有列的信息:给对象加本体自有属性(值由本系统保存),可写。
    返回加上的 [(对象名, 属性名, 中文名)]。草案里的对象改草案,已有对象改工作副本。"""
    made = []
    for x in newp:
        rec = _resolve_obj(str(x.get("object_type") or ""), objs)
        name = str(x.get("name") or "").strip()
        if rec is None or not re.match(r"^[A-Za-z_][A-Za-z0-9_]*$", name):
            continue
        if any(p["name"] == name for p in rec["properties"]):
            continue
        dt = str(x.get("data_type") or "text")
        rec["properties"].append({"name": name, "display_name": str(x.get("display_name") or name)[:40],
                                  "data_type": dt if dt in schema.DATA_TYPES else "text",
                                  "description": str(x.get("description") or "")[:200], "is_key": False, "is_time": False,
                                  "is_dimension": False, "is_writable": True, "enum_values": [], "expression": "",
                                  "storage": "ontology"})
        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)
            rec["item"]["payload"] = payload
        elif rec["id"]:
            service.update_concept(rec["id"], spec={**(service.get_concept(rec["id"]).get("spec") or {}),
                                                    "properties": rec["properties"]})
        made.append((rec["name"], name, str(x.get("display_name") or name)))
    return made


def _resolve_obj(ref: str, objs: dict[str, dict]) -> dict | None:
    """AI 引用对象时常用英文 / 表名(supplier、otlg_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 []:
        for obj, args, vals in _writes(e, spec):
            rec = _resolve_obj(obj, objs)
            if rec is None:
                return f"效果 {e.get('tool')} 的对象「{obj}」不存在"
            if args.get("object_type"):
                args["object_type"] = rec["name"]
            names = [p["name"] for p in rec["properties"]]
            if e.get("tool") == "object.write" and not vals:
                return f"效果「{e.get('label') or '修改对象'}」没写要改哪个属性(写 property + value,或 values)"
            bad = [w for w in vals if w not in names]
            if bad:
                return f"{rec['name']} 没有属性 {'、'.join(bad)},可用属性:{'、'.join(names)}"
            derived = [w for w in vals if any(p["name"] == w and p.get("expression") for p in rec["properties"])]
            if derived:
                return (f"{rec['name']} 的 {'、'.join(derived)} 是按公式算出来的,不能直接写;"
                        f"要改就改它依赖的那几列,或者在 new_properties 里另建一个本体自有属性来记")
    return ""


def _open_writes(spec: dict, objs: dict[str, dict]) -> None:
    """动作要写的属性标成可写(草案里的对象改草案,已有对象改工作副本),校验才能过。"""
    for e in spec.get("effects") or []:
        targets = [(obj, vals) for obj, _, vals in _writes(e, spec)] if e.get("tool") in ("object.write", "object.batch") else []
        for obj, vals in targets:
            rec = _resolve_obj(obj, objs)
            if rec is not None:
                _mark_writable(rec, list(vals))


def _mark_writable(rec: dict, props: list[str]) -> None:
    changed = False
    for prop in props:
        hit = next((x for x in rec["properties"] if x["name"] == prop), None)
        if hit is None or hit.get("is_writable") or hit.get("expression"):
            continue
        hit["is_writable"] = True
        changed = True
    if changed:
        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}

- 一个流程通常就是文档里的一个章节(如「每日巡检 SOP」):一个章节只算一个流程,不要拆成几个,也不要把几条业务规则拼成一个流程。
- 业务规则、审批规则、术语口径、管理动作清单这类章节**不是**流程;单个操作(创建某单据、标记某状态)是动作,也不是流程。
- owner_role:文中写了由谁执行就填;schedule:文中写了什么时候做(每天 9:00、每周一、每月 1 日)就照抄,没写留空。

输出 JSON:{{"processes":[{{"title":"流程名(用章节里的叫法)","section":"所在章节标题","chunks":["片段编号"],
"owner_role":"","schedule":""}}]}},没有就输出空数组。"""


def _draft_names(run_id: str) -> dict[str, set[str]]:
    """这次草案里还没采纳的元素名(按种类):流程卡、定时任务引用它们不算错,采纳时它们先上线。"""
    out: dict[str, set[str]] = {"object_type": set(), "action": set(), "function": set(), "link_type": set()}
    for it in _pending(run_id):
        pl = it["payload"] or {}
        if pl.get("kind") in out:
            out[pl["kind"]].update([pl["name"], *(pl.get("synonyms") or [])])
    return out


def _draft_catalog(run_id: str) -> dict:
    """这次草案里的元素(还没采纳):流程卡按这些名字引用,采纳发布后就能跑。对象带上属性,
    否则流程卡会写出 $supplier.名称 这种不存在的字段。"""
    by: dict[str, list[str]] = {"actions": [], "metrics": [], "rules": [], "decisions": [], "object_types": [], "links": []}
    for it in _pending(run_id):
        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") == "rule":
            by["rules"].append(p["name"])
        elif p.get("kind") == "function" and sp.get("category") == "decision":
            by["decisions"].append(p["name"])
        elif p.get("kind") == "object_type":
            props = [f"{x['name']}{'(可改)' if x.get('is_writable') else ''}"
                     + (f"[{'/'.join(x['enum_values'])}]" if x.get("enum_values") else "")
                     + (f"「{x['display_name']}」" if x.get("display_name") else "")
                     for x in sp.get("properties") or []]
            by["object_types"].append(f"- {p['name']}:{'、'.join(props[:40])}")
        elif p.get("kind") == "link_type":
            by["links"].append(f"- {p['name']}:{sp.get('from_type')} → {sp.get('to_type')}({sp.get('cardinality')})")
    return {k: ("\n" if k in ("actions", "object_types", "links") else "、").join(v) for k, v in by.items()}


def _sops(chunks: list[dict], note, run_id: str, reqs: list[dict] | None = None,
          only: list[dict] | None = None) -> int:
    """按章节识别文档里的流程,几张一起起草;每起草好一张就记进这次建模(中途停下也不留下没人认的草稿)。
    流程的负责角色、执行时间记下来,「定时与监控」按它配定时任务。
    文档条目里这个流程的每一步都要有对应步骤(起草时一起改);起草完在草案世界里试运行一遍。
    only:直接给要起草的流程(按对账修改时重起草用),不再让 AI 找。"""
    from ..sop import draft as sop_draft
    from . import modeling_reqs
    extra = _draft_catalog(run_id)
    names = _draft_names(run_id)
    by_id = {c["id"]: c for c in chunks}
    if only is None:
        text = "\n\n".join(f"[{c['id']}]【{c.get('heading') or '正文'}】\n{c['text'][:6000]}" for c in chunks[:40])
        try:
            with llmlog.feature("modeling_sop_find"), llm.trace_label("找出文档里的流程"):
                res = llm.chat_json([{"role": "user", "content": SOP_TOPICS_PROMPT.format(
                    n=MAX_SOPS, text=llm.truncate_to_tokens(text, 16000))}], temperature=0.1)
        except Exception as e:  # noqa: BLE001
            note(f"识别流程失败:{str(e)[:100]}")
            return 0
        jobs = []
        for proc in ((res or {}).get("processes") or [])[:MAX_SOPS] if isinstance(res, dict) else []:
            title = str((proc or {}).get("title") or "").strip()
            if title:
                jobs.append({"title": title, "chunks": [by_id[x] for x in proc.get("chunks") or [] if x in by_id] or chunks[:8],
                             "section": str(proc.get("section") or ""), "owner_role": str(proc.get("owner_role") or "").strip(),
                             "schedule": str(proc.get("schedule") or "").strip()})
        note(f"找到 {len(jobs)} 个流程:{'、'.join(j['title'] for j in jobs)}" if jobs else "文档里没有识别出完整的流程")
    else:
        jobs = [{**j, "chunks": j.get("chunks") or chunks[:8]} for j in only]

    def one(job: dict) -> tuple[dict, dict | None, str]:
        must = job.get("must") or modeling_reqs.steps_of(reqs or [], job["title"], job["section"])
        topic = job["title"] + (f"(文档章节「{job['section']}」:这一节列了几步,流程卡里就要有对应的几步,"
                                 f"排序、汇总、通知这类要求也要做出来)" if job["section"] else "") \
            + (f"\n另外要做到:{job['extra']}" if job.get("extra") else "")
        try:
            with llm.trace_label(f"起草流程卡:{job['title']}"):
                return job, sop_draft.generate(topic, chunks=job["chunks"][:8], extra_catalog=extra,
                                               draft_names=names, owner_role=job["owner_role"], must_cover=must), ""
        except HTTPException as e:
            return job, None, str(e.detail)

    made = 0
    if not jobs:
        return 0
    created: list[str] = []
    with ThreadPoolExecutor(max_workers=min(3, len(jobs))) as pool:
        futs = [pool.submit(contextvars.copy_context().run, one, j) for j in jobs]
        for f in as_completed(futs):
            job, d, err = f.result()
            if d is None:
                note(f"「{job['title']}」起草失败:{err}")
                continue
            cov = d.get("coverage") or {}
            hint = {"schedule": job["schedule"], "owner_role": job["owner_role"], "section": job["section"],
                    "coverage": cov}

            def keep(inp: dict, sid: str = d["id"], h: dict = hint) -> None:
                inp["sop_ids"] = [*(inp.get("sop_ids") or []), sid]
                inp["sop_hints"] = {**(inp.get("sop_hints") or {}), sid: h}
            _patch_inputs(run_id, keep)
            created.append(d["id"])
            made += 1
            note(f"流程卡「{d['title']}」{d['step_count']} 步" + (f",{job['owner_role']}" if job["owner_role"] else "")
                 + (f",{job['schedule']}" if job["schedule"] else "")
                 + (f";文档里的 {cov['total']} 步对上了 {cov['covered']} 步" if cov.get("total") else ""))
    for sid in created:
        res = _sop_trial(run_id, sid, note)
        if res and not res.get("ok") and not res.get("skipped"):
            # 试运行没走通(常见:查了不存在的列、引用写错):把报错交给 AI 改一次,改好会再试运行
            from . import modeling_edit
            try:
                fixed = modeling_edit.ai_edit_sop(run_id, sid, f"试运行出错了:{res.get('summary') or res.get('error')}。"
                                                              "按对象的真实属性改正出错的那一步,其余不动")
                note(f"按试运行的报错改了一次:{fixed.get('summary')};" + ((fixed.get("dry_run") or {}).get("summary") or ""))
            except HTTPException as e:
                note(f"按试运行的报错改没成:{e.detail}")
    return made


def _sop_trial(run_id: str, sid: str, note=None) -> dict:
    """流程卡草稿在草案世界里试运行一遍(不写数据、不发通知),结果记在这次建模里。草稿有错误时不跑。"""
    from ..sop import service as sop_service
    from . import modeling_world
    try:
        d = sop_service.get(sid)
    except HTTPException:
        return {}
    v = sop_spec_validate(d["spec"], sid, _draft_names(run_id))
    if v["errors"]:
        res = {"ok": False, "skipped": True, "summary": "草稿还有错误,改好之后才能试运行"}
    else:
        with modeling_world.world(_pending(run_id)):
            res = modeling_world.sop_trial(sid)
    _patch_inputs(run_id, lambda inp: inp.setdefault("sop_hints", {}).setdefault(sid, {}).update(dry_run=res))
    if note and not res.get("skipped"):
        note(f"「{d['title']}」试运行:{res.get('summary') or res.get('error')}")
    return res


def sop_spec_validate(spec: dict, sid: str, names: dict) -> dict:
    from ..sop import spec as sop_spec
    return sop_spec.validate(spec, def_id=sid, draft_names=names)


# ---------------- 采纳 / 不要 ----------------
_RANK = {"object_type": 0, "link_type": 1, "function": 2, "action": 3}


def _items_of(run_id: str, item_ids: list[str]) -> list[dict]:
    out = []
    for iid in dict.fromkeys(item_ids):
        it = review.get(iid)
        if it is None or it["source"] != _source(run_id):
            raise HTTPException(404, f"草案 {iid} 不属于这次建模")
        out.append(it)
    return out


def _failing_tests(ids: list[str], skip: dict) -> dict[str, str]:
    """测试用例没过的函数先挑出来:发布闸门只要有一个函数没过就整批拦下,
    采纳一批草案时不能因为一条规则的算例不对,对象、关系、指标全都上不了线。"""
    from . import fntests
    out = {}
    for cid in ids:
        if cid in skip:
            continue
        try:
            c = service.get_concept(cid)
        except HTTPException:
            continue
        if c.get("kind") != "function" or not (c.get("spec") or {}).get("tests"):
            continue
        fails = [r for r in fntests.run(c) if not r["ok"]]
        if fails:
            out[cid] = "测试用例没过:" + ";".join(f"{r['name']}:{r['error'][:80]}" for r in fails[:3])
    return out


def _publish_concepts(concept_ids: list[str], note: str) -> dict:
    """把采纳出来的元素直接发布上线:依赖一起带上;体检有错的(以及因为引用它们才被带上的)留作草稿。"""
    from . import health
    cands = list(dict.fromkeys(c for c in concept_ids if c))
    held: dict[str, str] = {}
    for _ in range(8):
        if not cands:
            break
        scope = service.release_scope(cands)
        if not scope["ids"]:
            break
        rep = health.check(scope["ids"])
        bad = {e["id"]: e["message"] for e in rep["errors"]}
        bad.update(_failing_tests(scope["ids"], bad))
        if not bad:
            try:
                out = service.publish(note, scope["ids"])
            except HTTPException as e:
                for c in scope["ids"]:
                    held.setdefault(c, f"发布被拦下:{e.detail}")
                return {"published": 0, "held": held}
            return {"published": len(scope["ids"]), "revision": out.get("revision"), "held": held,
                    "warnings": rep.get("warnings") or []}
        for cid, msg in bad.items():
            held.setdefault(cid, msg)
        because = {a["because"] for a in scope["auto"] if a["id"] in bad}
        names = {c: (service.get_concept(c) or {}).get("name") for c in cands}
        for c in cands:
            if c not in bad and names.get(c) in because:
                held.setdefault(c, "引用的元素体检没过,一起留在草稿里")
        cands = [c for c in cands if c not in held]
    return {"published": 0, "held": held}


def deps(run_id: str, item_ids: list[str], sop_ids: list[str] | None = None,
         watch_ids: list[str] | None = None) -> dict:
    """采纳这些之前还得一起采纳的待定草案:关系的两端、函数 / 动作作用的对象、动作的审批决策表、
    计算属性用到的关系、流程卡和监控引用的元素。返回 {item_ids: 要连带的, items: [{id, name, why}]}。"""
    pend = {it["id"]: it for it in _pending(run_id)}
    index: dict[str, dict] = {}
    for it in pend.values():
        p = it["payload"] or {}
        for n in [p.get("name"), *(p.get("synonyms") or [])]:
            if n:
                index.setdefault(str(n), it)
    want = set(item_ids)
    extra: dict[str, str] = {}

    def need(name: Any, why: str) -> None:
        it = index.get(str(name or ""))
        if it is not None and it["id"] not in want and it["id"] not in extra:
            extra[it["id"]] = why
            queue.append(it)

    def refs_of(it: dict) -> None:
        p = it["payload"] or {}
        sp = p.get("spec") or {}
        me = f"「{p.get('name')}」"
        if p.get("kind") == "link_type":
            need(sp.get("from_type"), f"关系{me}的一端")
            need(sp.get("to_type"), f"关系{me}的一端")
        if p.get("kind") == "function":
            need(sp.get("object_type"), f"函数{me}算的对象")
            for b in p.get("bindings") or []:
                if b.get("target_kind") == "metric_expr":
                    need((b.get("ref") or {}).get("base_object"), f"指标{me}统计的对象")
        if p.get("kind") == "action":
            need(sp.get("target_type"), f"动作{me}作用的对象")
            need(((sp.get("approval") or {}).get("decision") or {}).get("function"), f"动作{me}的审批决策表")
            for e in sp.get("effects") or []:
                need((e.get("args") or {}).get("object_type"), f"动作{me}要写的对象")
        if p.get("kind") == "object_type":
            from . import rules as rule_engine
            for x in sp.get("properties") or []:
                if not x.get("expression"):
                    continue
                try:
                    used = rule_engine.free_names(x["expression"]) + rule_engine.rollup_names(x["expression"])
                except rule_engine.RuleError:
                    continue
                for n in used:
                    need(n, f"「{p.get('name')}.{x.get('display_name') or x['name']}」用到的关系")
                for m in re.findall(r"([\w一-鿿]+)\.", x["expression"]):
                    need(m, f"「{p.get('name')}.{x.get('display_name') or x['name']}」用到的关系")
    queue: list[dict] = [pend[i] for i in item_ids if i in pend]
    if sop_ids:
        from ..sop import service as sop_service
        from ..sop import spec as sop_spec
        names = _draft_names(run_id)
        for sid in sop_ids:
            try:
                d = sop_service.get(sid)
            except HTTPException:
                continue
            for r in sop_spec.validate(d["spec"], def_id=sid, draft_names=names).get("draft_refs") or []:
                need(r.get("name"), f"流程卡「{d['title']}」用到")
    if watch_ids:
        for w in _inputs(run_id).get("watch_drafts") or []:
            if w["id"] not in watch_ids:
                continue
            src = (w.get("body") or {}).get("source") or {}
            need(src.get("object_type") or src.get("metric"), f"监控「{w['title']}」盯的")
            for s_ in (w.get("body") or {}).get("strategies") or []:
                need(s_.get("action"), f"监控「{w['title']}」要提交的动作")
    while queue:
        refs_of(queue.pop())
    return {"item_ids": list(extra), "items": [{"id": i, "name": (pend[i]["payload"] or {}).get("name"), "why": w}
                                               for i, w in extra.items()]}


def adopt(run_id: str, item_ids: list[str], sop_ids: list[str] | None = None,
          watch_ids: list[str] | None = None) -> dict:
    """采纳:草案落成元素并直接发布上线(不建变更提案、不进审批)。已采纳但没能上线的再试一次上线。
    流程卡草稿直接发布;定时任务在它们之后建好并启用。返回每条的结果,失败原因也记进这次建模,页面上就地显示。"""
    run = _load(run_id)
    note = f"AI 建模「{run.title}」采纳,直接发布"
    # 依赖的待定草案一起采纳(流程卡引用的对象、动作的审批决策表……),否则它们自己上不了线
    item_ids = [*item_ids, *deps(run_id, item_ids, sop_ids, watch_ids)["item_ids"]]
    items = _items_of(run_id, item_ids)
    pending = sorted([x for x in items if x["status"] == "pending"],
                     key=lambda x: _RANK.get((x["payload"] or {}).get("kind"), 2))
    ok: list[str] = []
    failed: dict[str, str] = {}
    cids: dict[str, str] = {}                 # concept_id → 草案 id
    for it in pending:
        try:
            out = review.decide(it["id"], True, note, perm="build")
        except HTTPException as e:
            failed[it["id"]] = str(e.detail)
            continue
        ok.append(it["id"])
        cid = (out.get("result") or {}).get("concept_id") or (_concept_of(it) or {}).get("id")
        if cid:
            cids[cid] = it["id"]
    for it in items:
        if it["status"] == "accepted":
            c = _concept_of(it)
            if c:
                cids[c["id"]] = it["id"]
    pub = _publish_concepts(list(cids), note) if cids else {"published": 0, "held": {}}
    sop_res: dict[str, str] = {}
    if sop_ids:
        from ..sop import service as sop_service
        mine = set(_inputs(run_id).get("sop_ids") or [])
        for sid in sop_ids:
            if sid not in mine:
                raise HTTPException(404, "流程卡不属于这次建模")
            try:
                sop_service.publish_unreviewed(sid, note)
                sop_res[sid] = ""
            except HTTPException as e:
                sop_res[sid] = str(e.detail)
    from . import modeling_schedule
    watch_res = modeling_schedule.adopt(run_id, watch_ids or []) if watch_ids else {}

    def keep(inp: dict) -> None:
        issues = dict(inp.get("issues") or {})
        for iid in ok:
            issues.pop(iid, None)
        issues.update(failed)
        for cid in cids:
            issues.pop(cid, None)
        issues.update(pub["held"])
        for sid, err in sop_res.items():
            if err:
                issues[sid] = err
            else:
                issues.pop(sid, None)
        inp["issues"] = issues
    _patch_inputs(run_id, keep)
    audit.record("modeling.adopt", "model_run", run_id,
                 f"{note}:{len(ok)} 条草案,上线 {pub['published']} 个元素,流程卡 {sum(1 for e in sop_res.values() if not e)} 张,"
                 f"定时任务 {sum(1 for e in watch_res.values() if not e)} 条")
    return {"accepted": ok, "failed": failed, "published": pub["published"], "revision": pub.get("revision"),
            "held": pub["held"], "warnings": pub.get("warnings") or [], "sops": sop_res, "watches": watch_res}


def discard(run_id: str, item_ids: list[str], sop_ids: list[str] | None = None,
            watch_ids: list[str] | None = None) -> dict:
    """不要:草案标成不采纳,流程卡草稿归档,定时任务草稿标掉。"""
    run = _load(run_id)
    n = 0
    for it in _items_of(run_id, item_ids):
        if it["status"] == "pending":
            review.decide(it["id"], False, f"AI 建模「{run.title}」:不采纳", perm="build")
            n += 1
    m = 0
    if sop_ids:
        from ..sop import service as sop_service
        mine = set(_inputs(run_id).get("sop_ids") or [])
        for sid in sop_ids:
            if sid in mine and sop_service.get(sid)["status"] != "archived":
                sop_service.archive(sid)
                m += 1
    w = 0
    if watch_ids:
        want = set(watch_ids)

        def drop(inp: dict) -> None:
            nonlocal w
            for d in inp.get("watch_drafts") or []:
                if d["id"] in want and d.get("status") == "pending":
                    d["status"] = "discarded"
                    w += 1
        _patch_inputs(run_id, drop)
    return {"discarded": n, "sops": m, "watches": w}


# ---------------- 导出 ----------------
def _effect_text(e: dict) -> str:
    a = e.get("args") or {}
    tool = e.get("tool") or ""
    if tool == "object.write":
        return f"把 {a.get('object_type') or '对象'}.{a.get('property')} 改成 {a.get('value')}"
    if tool == "object.create":
        return f"新建一条 {a.get('object_type')}:{'、'.join(f'{k}={v}' for k, v in (a.get('values') or {}).items())}"
    if tool == "notify.send":
        return f"通知 {a.get('to') or a.get('role') or ''}:{a.get('title') or a.get('text') or ''}"
    if tool == "task.create":
        return f"派一项待办给 {a.get('role') or a.get('assignee') or ''}:{a.get('title') or ''}"
    return f"{tool} {jdump(a)}"


def export_md(run_id: str) -> str:
    g = get(run_id)
    lines = [f"# {g['title']}", "", f"> AI 建模草案 · {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 k == "action" and not spec.get("_stub"):
                params = "、".join(f"{x.get('label') or x.get('name')}{'*' if x.get('required') else ''}"
                                   for x in spec.get("params") or [])
                lines.append(f"  - 作用对象:{spec.get('target_type') or '无'};参数:{params or '无'}")
                for c in spec.get("criteria") or []:
                    lines.append(f"  - 前置条件:`{c.get('expression')}`")
                for e in spec.get("effects") or []:
                    lines.append(f"  - 效果:{_effect_text(e)}")
            elif spec.get("expression"):
                lines.append(f"  - 表达式:`{spec['expression']}`")
            elif spec.get("formula_text"):
                lines.append(f"  - 公式:{spec['formula_text']}")
            for gap in p.get("schema_gaps") or []:
                lines.append(f"  - 数据缺口:{gap.get('object_type') or ''}缺「{gap.get('need')}」—— {gap.get('why') or ''}")
            for f in p.get("test_failures") or []:
                lines.append(f"  - 测试没过:{f}")
            for e in (p.get("evidence") or [])[:2]:
                snip = " ".join((e.get("snippet") or "").split())[:120]
                lines.append(f"  - 出处:{e.get('heading') or ''}|{snip}")
        lines.append("")
    if g["sops"]:
        lines += [f"## 流程卡({len(g['sops'])})", ""]
        for s in g["sops"]:
            lines.append(f"- **{s['title']}**({s['step_count']} 步):{s['description']}"
                         + (f"({s['owner_role']},{s['schedule']})" if s.get("schedule") else ""))
            lines += [f"  {'  ' * x['depth']}- {x['title']}" + (f"({x['kind_label']})" if x.get("kind_label") else "")
                      for x in s.get("outline") or []]
        lines.append("")
    if g["watches"]:
        from . import modeling_schedule
        lines += [f"## 定时与监控({len(g['watches'])})", ""]
        for w in g["watches"]:
            lines.append(f"- **{w['title']}**:{modeling_schedule.describe(w)}"
                         + (f" `{'已建好' if w['status'] == 'accepted' else '不要'}`" if w.get("status") != "pending" else ""))
        lines.append("")
    chk = g.get("check") or {}
    if chk.get("items"):
        sm = chk.get("summary") or {}
        lines += [f"## 对账(落实 {sm.get('covered', 0)}、有出入 {sm.get('partial', 0)}、漏了 {sm.get('missing', 0)}、"
                  f"不用建模 {sm.get('builtin', 0)})", ""]
        mark = {"covered": "✓", "partial": "△", "missing": "✗", "builtin": "◎", "na": "·"}
        for x in chk["items"]:
            why = x.get("gap") or x.get("reason") or x.get("note") or ""
            lines.append(f"- {mark.get(x.get('status'), '?')} {x.get('id') or ''} {x.get('text')}"
                         + (f" → {'、'.join(x.get('by') or [])}" if x.get("by") else "")
                         + (f"({why})" if why else "") + ("(已忽略)" if x.get("ignored") else ""))
        if chk.get("questions"):
            lines += ["", "上线后试问:"] + [f"- {q}" for q in chk["questions"]]
    if g.get("fixes"):
        lines += ["", f"## 按对账修改({len(g['fixes'])})", ""]
        lines += [f"- {'✓' if f.get('ok') else '✗'} {f.get('req_id')} {f.get('target')}:{f.get('summary')}" for f in g["fixes"]]
    return "\n".join(lines) + "\n"