ingest.py 120 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 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529
import asyncio
import glob
import hashlib
import os
import json
import json_repair
import re
import shutil
import tempfile
import frontmatter
import yaml
from dataclasses import dataclass, replace as dataclass_replace
from datetime import datetime
from decimal import Decimal
import logging
from typing import Any, Sequence

logger = logging.getLogger(__name__)

from sqlalchemy import select, delete
from fastapi import APIRouter, HTTPException, Body, Depends
from fastapi.concurrency import run_in_threadpool

from src.database.session import AsyncSessionLocal
from src.database.models import WikiFile, WikiFilePage, WikiOperationLog, WikiKbInfo, WikiOaUser
from src.services.oa.deps import require_perm
from src.services.oa.kb_guard import assert_file_action, NEED_WRITE
from src.services.oa.kb_paths import kb_wiki_dir, kb_raw_dir, kb_wiki_rel, kb_raw_rel
from config import (
    RAW_DIR, WIKI_DIR, BASE_DIR, INGEST_TRACE_DIR, INGEST_MODEL_NAME,
    INGEST_MODEL_TEMPERATURE,      # 摄入采样温度,低温减少字段幻觉
    INGEST_MAX_CONCURRENT_FILES,   # #2: 同时允许摄入的文件数
    INGEST_WRITER_CONCURRENCY,     # #11: Writer 并发数
    INGEST_TIMEOUT_SECONDS,        # 单文件摄入超时(秒)
    INGEST_PLANNER_MAX_RETRIES,    # Planner 最大重试次数
    INGEST_WRITER_MAX_RETRIES,     # 单页 Writer 最大重试次数
    INGEST_LONG_DOC_CHUNKING_ENABLED,  # 长文分块摄入总开关(关则一律走三阶段)
    INGEST_LONG_DOC_THRESHOLD_CHARS,  # 超过该字符数走长文档分块流水线
    INGEST_MAP_ENABLE_THINKING,       # Map 阶段是否开启思考(默认 False,显式传给模型)
    INGEST_MAP_MODEL_NAME,         # Map 阶段(逐块内容清单)模型
    INGEST_MAP_CONCURRENCY,        # Map 阶段并发数
)
from src.utils.llm_tracker import (
    current_llm_call_context,
    current_task_token_usage,
    current_task_tokens,
    get_llm_formatter,
    get_llm_model,
    load_skill_prompt,
    new_token_counter,
    print_thinking,
)
from src.utils.ingest_contract import (
    IngestContract,
    as_value_list as contract_as_value_list,
    build_source_ref,              # 规范来源路径,保留 raw 下的格式子目录
    canonicalize_type,
    contract_prompt_text,
    current_schema_version,
    load_ingest_contract,
    merge_field_sources as contract_merge_field_sources,
    missing_required_extra,        # 各 type 专属必填字段校验
    pick_series_for_path,          # sources 落盘目录:series 数组取首个非占位值
    recompute_after_source_removal as contract_recompute_after_source_removal,
    resolve_effective_dims,        # 文档级 global_dims + 页面级 sub_business
    sanitize_series,               # 生态品牌禁止作为 series
    validate_planner_output,       # #5: Planner 输出校验
)

from src.utils.ingest_chunking import (
    CHUNK_MAX_CHARS,               # 单块硬上限(日志展示切块参数用)
    CHUNK_TARGET_CHARS,            # 单块目标大小(日志展示切块参数用)
    DocChunk,
    PAGE_SOURCE_MAX_CHARS,         # 单页认领原文上限,超限回喂 Planner 拆页
    chunk_document,
    find_uncovered_chunks,
    format_chunks_for_prompt,
    select_chunks,
)
from src.tools.document_parser import extract_text_from_file, get_last_extract_stats
from src.tools.wiki_tools import (
    append_wiki_file,
    rebuild_index,
    normalize_br_tags,
)
from agentscope.agent import ReActAgent
from agentscope.message import Msg


router = APIRouter()


def _json_block(value: Any) -> str:
    return json.dumps(value, ensure_ascii=False, indent=2)


def _token_delta(before: dict[str, int], after: dict[str, int]) -> dict[str, int]:
    return {
        "input_tokens": int(after.get("input_tokens") or 0) - int(before.get("input_tokens") or 0),
        "output_tokens": int(after.get("output_tokens") or 0) - int(before.get("output_tokens") or 0),
        "total_tokens": int(after.get("total_tokens") or 0) - int(before.get("total_tokens") or 0),
    }


def build_shared_ingest_prefix(
    *,
    skill_prompt: str,
    schema_contract_text: str,
    raw_content: str | None,
) -> str:
    """Planner 与 Writer 共用的静态前缀:skill + 契约 + 原始文档。

    这三者在一次摄入内逐字节一致。把它们作为 system prompt 的**公共前缀**放在最前面,
    即可命中 DashScope(qwen-plus 系列,OpenAI 兼容端点)的自动上下文缓存:原文/技能/契约
    只在首个调用全价计费一次,其余 Planner/Writer 调用对这段按缓存价计费(约 4 折)。
    历史写法把原文塞进每个 Writer 的 user 消息、每页任务又插在契约之后,导致跨 Writer 的
    公共前缀在「每页任务」处就断裂,整篇原文一次都进不了缓存——这是摄入 token 浪费的主因。

    因此调用方务必保证:本前缀内绝不含任何时间戳/每次调用变化的内容;
    角色说明、每页任务、输出接口一律拼在本前缀**之后**。

    长文档分块模式传 raw_content=None:全文不进前缀(Planner 只看块清单、
    Writer 只看本页认领块),前缀退化为 skill + 契约,仍跨全部调用可缓存。
    """
    prefix = f"""【llm-ingest Skill】
{skill_prompt}

【Schema Contract】
{schema_contract_text}
"""
    if raw_content is not None:
        prefix += f"""
【原始文档内容】
{raw_content}
"""
    return prefix


# 分隔共享前缀与角色/任务尾部,纯展示用,不影响缓存前缀匹配。
_INGEST_PREFIX_DIVIDER = "———— 以上为本次摄入的共享上下文(技能 / 契约 / 原始文档),以下为你的角色与任务 ————"


def build_planner_system_prompt(
    *,
    shared_prefix: str,
    slug_registry_text: str,
) -> str:
    # shared_prefix 打头,保证与 Writer 的 system prompt 拥有相同的可缓存公共前缀。
    return f"""{shared_prefix}
{_INGEST_PREFIX_DIVIDER}

你是 PlannerAgent,负责执行 llm-ingest skill 的 Phase 1。
请只依据上述权威上下文(skill、schema contract)与原始文档进行摄入规划;
字段、类型、枚举、示例与写作规则均以 skill 和 schema contract 为准。

【现有知识库页面注册表】
{slug_registry_text}

【本次输出接口】
只输出一个合法 JSON 对象,不要输出 Markdown 代码块、前言或解释。
JSON 对象必须包含:
- global_dims:文档级过滤维度,只含 series、brand、business_category、role 四项,不含 sub_business。
- pages:页面任务列表;每个页面任务至少包含 type、slug、file_path、title、related_links、
  source_content_range,以及本页的 sub_business(页面级维度,必填)。
  sub_business 取值必须来自 schema contract 的 sub_business_values 枚举;
  页面确实跨多个子业务时(如 sources 摘要页)可给出数组。
"""


def _log_phase_banner(filename: str, title: str) -> None:
    """打印阶段横幅,让整条摄入流水线在日志里一眼可辨走到了哪一步。"""
    logger.info(f"[{filename}] {'=' * 18} {title} {'=' * 18}")


def _log_prefix_fingerprint(filename: str, role: str, sys_prompt: str) -> None:
    """记录 system prompt 的共享前缀指纹,用于诊断上下文缓存为何不命中。

    跨 Writer 的可缓存前缀(skill+契约+角色+输出接口)本应逐字节一致;
    若各次 prefix_sha1 不同,说明前缀在我们侧就被破坏了(与 provider 无关)。
    """
    head = sys_prompt[:4000]
    logger.info(
        "[PrefixFingerprint] role=%s file=%s prefix_sha1=%s head_len=%s sys_prompt_len=%s",
        role, filename, hashlib.sha1(head.encode("utf-8")).hexdigest()[:16],
        len(head), len(sys_prompt),
    )


# 二级及以下 Markdown 小节(原文「## 条目 N」/ 生成页「## 话术一」都命中),用于保真度观测。
_MD_SECTION_RE = re.compile(r"^#{2,6}\s+\S", re.MULTILINE)


def _count_md_sections(text: str) -> int:
    """统计 Markdown 二级及以下小节数,近似「条目/小节」数量。"""
    return len(_MD_SECTION_RE.findall(text or ""))


def _compute_fidelity_stats(chunks: Sequence[Any], valid_files: Sequence[dict]) -> dict:
    """保真度指标:原文小节/字符 vs 生成页小节/字符。

    wiki 是汇总提炼,有损是预期内的;量化出来便于按数据判断是否需要调分页粒度或写作指令。
    """
    src_sections = sum(_count_md_sections(c.text) for c in chunks)
    src_chars = sum(len(c.text) for c in chunks)
    out_sections = sum(_count_md_sections(vf.get("content") or "") for vf in valid_files)
    out_chars = sum(len(vf.get("content") or "") for vf in valid_files)
    return {
        "pages": len(valid_files),
        "src_sections": src_sections,
        "out_sections": out_sections,
        "section_ratio": round(src_sections / out_sections, 2) if out_sections else 0.0,
        "src_chars": src_chars,
        "out_chars": out_chars,
        "char_ratio": round(src_chars / out_chars, 2) if out_chars else 0.0,
    }


def _is_sources_page(page: dict) -> bool:
    """页面是否为 sources 来源摘要页(含 alias 'source')。"""
    return str(page.get("type", "")).strip() in ("sources", "source")


def _sources_slug_for_file(filename: str) -> str:
    """由原始文件名确定性生成 sources 页 slug(去扩展名、清洗非法字符)。

    保证「一份原始文件 ↔ 一个 sources 页」:不同原文档各自成页、重摄同一文件只更新自己那页。
    """
    stem = os.path.splitext(os.path.basename(filename or ""))[0].strip()
    stem = re.sub(r'[\\/:*?"<>|]', "_", stem)
    return stem or "来源摘要"


def build_planner_system_prompt_chunked(
    *,
    shared_prefix: str,
    slug_registry_text: str,
    chunk_inventory_text: str,
    chunk_count: int,
    sources_slug: str,
    max_chunks_per_page: int,
) -> str:
    """长文档分块模式的 Planner prompt:不含全文,只含全部块的内容清单。

    下游主题页必须认领 source_chunks(覆盖审计依据);sources 页留空(下游成品页写完后再合成)。
    """
    return f"""{shared_prefix}
{_INGEST_PREFIX_DIVIDER}

你是 PlannerAgent,负责执行 llm-ingest skill 的 Phase 1(长文档分块模式)。
原始文档过长,已被切分为 {chunk_count} 个带编号的原文块;你看到的不是全文,
而是下方每个块的内容清单(主题/实体/表格/摘要)。
请只依据上述权威上下文(skill、schema contract)、块清单与页面注册表进行摄入规划。

【现有知识库页面注册表】
{slug_registry_text}

【原文块清单(共 {chunk_count} 块)】
{chunk_inventory_text}

【本次输出接口】
只输出一个合法 JSON 对象,不要输出 Markdown 代码块、前言或解释。
JSON 对象必须包含:
- global_dims:文档级过滤维度,只含 series、brand、business_category、role 四项,不含 sub_business。
- pages:页面任务列表;每个页面任务至少包含 type、slug、file_path、title、related_links、
  source_content_range、sub_business(页面级维度,必填,取值来自 sub_business_values 枚举),
  以及本页取材的块编号数组 source_chunks(下游主题页必填非空、取值 1..{chunk_count};sources 页留空 [])。

【source_chunks 认领规则】
- Writer 写作时只能读到本页 source_chunks 对应的原文块,漏认领的内容会永久丢失;
- 除 sources 页外,全部 {chunk_count} 个块都必须被至少一个**下游主题页**认领;
- 一个块常包含多个主题:不同页面可以认领同一个块,一个页面也可以认领多个块;
- **单页认领最多约 {max_chunks_per_page} 个块**(总字符必须 ≤ {PAGE_SOURCE_MAX_CHARS})。
  上方清单每行都标了该块字符数,认领前请逐块累加核对;**宁可少认领一块,也不要超**。
  超限会让整份规划被打回重做,浪费一次完整调用。
- 为什么限制这么严:Writer 的输出预算基本固定,**一页塞太多原文只会被压缩得更狠、丢掉大量内容**,
  而不是产出更多。宁可多分几页,每页写透。

【分页原则(务必遵守,直接决定 wiki 质量)】
- **按语义主题聚合块**:一个连贯主题 = 一个页面,可跨多个块(只要不超上限),slug 用语义化名称;
- **允许且鼓励认领不连续的块**:同一主题散落在多处时请把它们聚到一页,
  例如某页 `source_chunks` 完全可以是 `[3, 17, 42]`,不必连号;
- **严禁**为省事按 `1-3 / 4-7 / 8-11` 这样顺序切分后再给页面套个语义标题——
  那是**位置切分不是语义分页**,会导致标题与页内实际内容对不上;
- 分组依据是上方块清单里的 **topics / entities**,不是块编号顺序;
- 只有当**单一主题**确实超出单页上限时,才按**真实子主题**再拆(如按异议类型/场景/产品维度分),
  拆出的每页仍用有意义的 slug;
- **严禁**把同一主题机械切成 `xxx-01`、`xxx-02`、`xxx-03` 这类顺序编号页;
- 页面标题必须**忠实反映该页实际聚合的主题**;也不要把不相关的多个主题硬塞进一页。

【slug 复用(硬要求,避免近重复页)】
- 规划**每一个**页面前,**必须先逐条比对**上方【现有知识库页面注册表】;
- 若某产品/实体 + 异议类型**已有页面**,**必须复用它现有的 slug**(系统会自动合并内容与维度),
  **不得**新建一个仅措辞不同的近重复页。
  反例:注册表里已有 `漆面保护膜价值论证与材质解析异议处理`,就**不要**再建
  `漆面保护膜信任疑虑与材质论证异议处理话术`——这两个讲的是同一件事,应复用前者;
- 只有当该主题在注册表中**确实不存在**时,才允许新建页面。

【type=sources 摘要页的特别约束(重要,务必遵守)】
- sources 页 source_chunks **必须是空数组 []**:它不认领任何原文块;
- 系统会在**所有下游主题页写完后**,用这些成品页面作为素材,单独合成 sources 页的摘要与导航——
  所以你此处**只需规划它的 slug/title/维度/related_links 占位**,不要给它塞块;
- **sources 页的 slug 必须用 `{sources_slug}`**(由原始文件名确定性生成,保证一份原始文件 1 个 sources 页)。
"""


def build_writer_system_prompt(
    *,
    shared_prefix: str,
    page_info: dict[str, Any],
    effective_dims: dict[str, Any],
    source_ref: str,
    schema_version: str,
    required_extra: list[str] | None = None,
    page_chunks_text: str | None = None,
    synthesis: bool = False,
) -> str:
    runtime_context = {
        "page_info": page_info,
        # 本页生效维度:文档级 global_dims + 本页 sub_business,Writer 直接照用。
        "effective_dims": effective_dims,
        # 规范来源路径,含 raw 下的格式子目录(如 ware/raw/pdf/x.pdf)
        "source": source_ref,
        "schema_version": schema_version,
    }
    if required_extra:
        # 本页 type 的专属必填字段,摄入网关会硬校验(须存在且非空)。
        # 契约里已按 type 列过一次,但那要求 Writer 自己去表里找;缺字段会被打回重试、
        # 每次重试都是一次完整 LLM 调用,故在本页上下文里直接点名。
        runtime_context["required_extra_fields"] = required_extra
    # shared_prefix 打头;角色/输出接口居中(跨 Writer 一致、可缓存);
    # 每页不同的 runtime_context 与素材原文放在**最后**,让其之前的内容都落入公共缓存前缀。
    # 长文档分块模式:原文不在 shared_prefix 里,本页认领块的原文经 page_chunks_text 注入尾部。
    # synthesis=True 用于 sources 页延后合成:素材是本次已生成的下游 wiki 页面,而非原文块。
    if synthesis:
        role_line = (
            "你是 WriterAgent,负责执行 llm-ingest skill 的 Phase 2(sources 来源摘要页合成)。\n"
            "下方【本次已生成的下游页面】是这份原始文档摄入后产出的全部下游 wiki 页面(含各自 frontmatter 与正文)。\n"
            "请据此为本来源文档生成一个完整的 sources 摘要页:\n"
            "- frontmatter:聚合下游各页的过滤维度(brand/series/business_category/sub_business/role/related 取并集),"
            "并按 schema contract 填全必填字段;\n"
            "- 正文:写一段全局摘要,并给出「下游页面导航」表,用**下游页面真实的 slug** 做 [[wikilink]]。"
        )
        material_block = (
            f"\n【本次已生成的下游页面(合成素材,非原文)】\n"
            f"以下是本次摄入已产出的全部下游 wiki 页面,请据此合成本来源摘要页:\n\n{page_chunks_text}\n"
            if page_chunks_text is not None
            else ""
        )
    else:
        role_line = (
            "你是 WriterAgent,负责执行 llm-ingest skill 的 Phase 2。\n"
            "请只依据上述权威上下文(skill、schema contract)、原始文档与下方本页任务生成一个完整 Markdown 页面。"
        )
        material_block = (
            f"\n【本页取材原文块】\n以下是本页 source_chunks 认领的原文块,本页事实必须且只能取材于此:\n\n{page_chunks_text}\n"
            if page_chunks_text is not None
            else ""
        )
    return f"""{shared_prefix}
{_INGEST_PREFIX_DIVIDER}

{role_line}

【本次输出接口】
只输出最终 Markdown 页面,不要输出前言、解释或代码块包裹。

【本页运行时上下文】
{_json_block(runtime_context)}
{material_block}"""


@router.post("/wiki/batch_ingest")
async def batch_ingest(data: dict = Body(...), me: WikiOaUser = Depends(require_perm("wiki:file:batchIngest"))):
    """批量开始摄入任务,接受 ids 列表(逐个校验对所属库的 owner 写权限)。
    摄入任务使用全局锁串行执行;摄出仅按文件级锁互斥。
    """
    ids = data.get("ids", [])
    if not ids:
        raise HTTPException(status_code=400, detail="ids 不能为空")
    logger.info(f"[BatchIngest] request ids={ids}")

    count = 0
    to_process = []
    skipped = []
    async with AsyncSessionLocal() as session:
        for fid in ids:
            result = await session.execute(select(WikiFile).where(WikiFile.id == fid))
            db_file = result.scalar_one_or_none()
            if not db_file:
                skipped.append({"id": fid, "reason": "not_found"})
                logger.warning(f"[BatchIngest] skip file_id={fid}, reason=not_found")
                continue
            try:
                await assert_file_action(session, me, db_file, NEED_WRITE)
            except HTTPException as he:
                skipped.append({"id": fid, "reason": he.detail})
                continue
            if db_file.status not in ("Ingesting", "Uploading"):
                logger.info(
                    f"[BatchIngest] enqueue file_id={fid}, name={db_file.name}, "
                    f"old_status={db_file.status}, new_status=Ingesting"
                )
                db_file.status = "Ingesting"
                db_file.error_message = None
                to_process.append(db_file.id)
                count += 1
            else:
                skipped.append({"id": fid, "reason": db_file.status})
                logger.info(
                    f"[BatchIngest] skip file_id={fid}, name={db_file.name}, "
                    f"reason=status_{db_file.status}"
                )
        await session.commit()
    logger.info(
        f"[BatchIngest] db_mark_done requested={len(ids)}, enqueued={len(to_process)}, "
        f"skipped={len(skipped)}, enqueued_ids={to_process}, skipped={skipped}"
    )

    for fid in to_process:
        _schedule_ingest_task(fid)

    logger.info(f"[BatchIngest] response count={count}, skipped={skipped}")
    return {"status": "batch ingest started", "count": count, "skipped": skipped}



@router.delete("/wiki/egress/{file_id}")
async def egress_wiki(file_id: str, me: WikiOaUser = Depends(require_perm("wiki:file:egress"))):
    """摄出:仅抹掉该文件自身在 wiki 中的全部足迹——它生成的页面、各页中本源的
    SOURCE 块、以及本源在 frontmatter(含 5 结构化字段)的所有贡献;其他来源贡献的
    内容与字段完整保留。状态回 Pending、保留原文以便重摄;彻底删原文+DB 走 delete_file。
    跨文件断链(其他页指向被删 slug)由 lint 统一修复,不在此处全库扫描。
    """
    logger.info(f"[Egress] request file_id={file_id}")

    async with AsyncSessionLocal() as session:
        result = await session.execute(select(WikiFile).where(WikiFile.id == file_id))
        current_file = result.scalar_one_or_none()
        if not current_file:
            logger.warning(f"[Egress] abort file_id={file_id}, reason=not_found")
            raise HTTPException(status_code=404, detail="File not found")
        if current_file.status in ("Ingesting", "Uploading"):
            logger.warning(
                f"[Egress] abort file_id={file_id}, name={current_file.name}, "
                f"status={current_file.status}, reason=busy_before_lock"
            )
            raise HTTPException(status_code=409, detail="文件正在摄入/上传中,无法摄出")

    logger.info(f"[Egress] waiting_for_file_lock file_id={file_id}")
    async with _get_file_operation_lock(file_id):
        logger.info(f"[Egress] acquired_file_lock file_id={file_id}")
        async with AsyncSessionLocal() as session:
            result = await session.execute(select(WikiFile).where(WikiFile.id == file_id))
            db_file = result.scalar_one_or_none()
            if not db_file:
                logger.warning(f"[Egress] abort file_id={file_id}, reason=not_found")
                raise HTTPException(status_code=404, detail="File not found")
            if db_file.status in ("Ingesting", "Uploading"):
                logger.warning(
                    f"[Egress] abort file_id={file_id}, name={db_file.name}, "
                    f"status={db_file.status}, reason=busy"
                )
                raise HTTPException(status_code=409, detail="文件正在摄入/上传中,无法摄出")
            await assert_file_action(session, me, db_file, NEED_WRITE)  # Reader/无权 → 403 权限不足

            name = db_file.name
            db_file_format = db_file.format
            # 多知识库:解析归属库 wiki 目录,用于摄出后 index 重建 / 空目录清理 / log 落盘
            egress_kb = await session.get(WikiKbInfo, db_file.kb_id) if db_file.kb_id else None
            egress_wiki_dir = kb_wiki_dir(egress_kb)
            # 溯源 key = 文件真实落盘路径(与摄入侧 canonical_source 同源),兜底回落旧布局
            egress_raw_path = db_file.raw_path or f"{kb_raw_rel(egress_kb)}/{db_file_format.lower()}/{name}"
            result_pages = await session.execute(select(WikiFilePage).where(WikiFilePage.file_id == file_id))
            pages = result_pages.scalars().all()
            generated_pages = [p.page_path for p in pages]
            logger.info(
                f"[Egress] loaded file_id={file_id}, name={name}, status={db_file.status}, "
                f"generated_pages_count={len(generated_pages)}, generated_pages={generated_pages}"
            )

        # 与摄入侧 canonical_source 保持同一构造规则(真实落盘路径),否则匹配不上会导致摄出静默跳过
        source_ref = build_source_ref(egress_raw_path)

        count = 0
        deleted_files = []
        touched_dirs = set()

        targets = [os.path.abspath(os.path.join(BASE_DIR, p)) for p in generated_pages] if generated_pages else []
        logger.info(
            f"[Egress] resolved_targets file_id={file_id}, name={name}, "
            f"targets_count={len(targets)}, source_ref={source_ref}"
        )

        block_pattern = re.compile(
            rf"<!-- SOURCE_START: {re.escape(source_ref)} -->.*?<!-- SOURCE_END: {re.escape(source_ref)} -->",
            re.DOTALL,
        )

        for file_path in targets:
            if not os.path.exists(file_path):
                logger.warning(f"[Egress] target_missing file_id={file_id}, path={file_path}")
                continue
            try:
                logger.info(f"[Egress] processing_page file_id={file_id}, path={file_path}")
                post = frontmatter.load(file_path)
                sources = _as_value_list(post.metadata.get("sources"))
                if source_ref not in sources:
                    # 本源未贡献该页(理论上不该发生),跳过以免误伤
                    logger.warning(
                        f"[Egress] skip_page_without_source file_id={file_id}, "
                        f"path={file_path}, source_ref={source_ref}, sources={sources}"
                    )
                    continue

                remaining_sources = [s for s in sources if s != source_ref]
                post.metadata["sources"] = remaining_sources
                logger.info(
                    f"[Egress] source_removed file_id={file_id}, path={file_path}, "
                    f"remaining_sources={remaining_sources}"
                )

                # 统一回收:移除本源在所有受追踪字段的贡献,按剩余来源重算/删除字段
                _recompute_after_source_removal(post.metadata, source_ref)

                # 正文:删除本源 SOURCE 块 + 兜底清理
                updated_content = block_pattern.sub("", post.content)
                updated_content = re.sub(
                    rf"^>\s*原始依据:\[\[{re.escape(source_ref)}\]\].*$",
                    "", updated_content, flags=re.MULTILINE,
                )
                updated_content = re.sub(r"\n{3,}", "\n\n", updated_content)
                updated_content = re.sub(r"(?m)^---\s*\n(?=---|\s*$)", "", updated_content)
                updated_content = updated_content.strip()

                if not remaining_sources or not updated_content:
                    os.remove(file_path)
                    deleted_files.append(file_path)
                    touched_dirs.add(os.path.dirname(file_path))
                    count += 1
                    logger.info(
                        f"[Egress] page_deleted file_id={file_id}, path={file_path}, "
                        f"remaining_sources_count={len(remaining_sources)}, "
                        f"updated_content_length={len(updated_content)}"
                    )
                else:
                    post.content = updated_content
                    save_post_with_formatting(post, file_path)
                    count += 1
                    logger.info(
                        f"[Egress] page_updated file_id={file_id}, path={file_path}, "
                        f"remaining_sources_count={len(remaining_sources)}, "
                        f"updated_content_length={len(updated_content)}"
                    )
            except Exception as e:
                logger.error(f"[Egress] 处理文件 {file_path} 时发生错误: {e}", exc_info=True)

        # 空目录清理(如 sources/极狐/ 删空后移除)
        for d in touched_dirs:
            try:
                if (os.path.isdir(d) and not os.listdir(d)
                        and os.path.abspath(d) != os.path.abspath(egress_wiki_dir)):
                    os.rmdir(d)
                    logger.info(f"[Egress] empty_dir_removed file_id={file_id}, dir={d}")
            except OSError:
                logger.warning(f"[Egress] empty_dir_remove_failed file_id={file_id}, dir={d}", exc_info=True)

        # index.md 确定性全量重建(删页的索引行自动消失)——按归属库 wiki 目录
        logger.info(f"[Egress] rebuilding_index file_id={file_id}, wiki_dir={egress_wiki_dir}")
        rebuild_index(egress_wiki_dir)
        logger.info(f"[Egress] rebuilt_index file_id={file_id}")

        # 清理长文摄入留下的排查 trace(短文档摄入无此文件,静默跳过)。
        # 新路径 {yyyyMM}/{文件名}_{file_id}.json,同时兼容清理历史扁平路径 {file_id}.json。
        for trace_path in (
            glob.glob(os.path.join(INGEST_TRACE_DIR, "*", f"*_{file_id}.json"))
            + [os.path.join(INGEST_TRACE_DIR, f"{file_id}.json")]
        ):
            if not os.path.exists(trace_path):
                continue
            try:
                os.remove(trace_path)
                logger.info(f"[Egress] ingest_trace_removed file_id={file_id}, path={trace_path}")
            except OSError:
                logger.warning(f"[Egress] ingest_trace_remove_failed file_id={file_id}", exc_info=True)

        async with AsyncSessionLocal() as session:
            result = await session.execute(select(WikiFile).where(WikiFile.id == file_id))
            db_f = result.scalar_one_or_none()
            if db_f:
                logger.info(
                    f"[Egress] db_reset_pending file_id={file_id}, name={name}, "
                    f"old_status={db_f.status}, cleaned_pages_count={count}, "
                    f"deleted_pages_count={len(deleted_files)}"
                )
                db_f.status = "Pending"
                # 摄出即回到「未摄入」态:清空所有摄入派生统计,否则列表按 token/字数排序时,
                # 这些已摄出文件仍带着旧值排到前面(界面却显示 "--"),造成"无数据却排最前"。
                db_f.input_tokens = 0
                db_f.output_tokens = 0
                db_f.total_tokens = 0
                db_f.cached_input_tokens = 0
                db_f.vlm_total_tokens = 0
                db_f.word_count = 0
                db_f.ingest_mode = None
                db_f.ingest_time = None
                db_f.ingest_duration = 0
                await session.execute(delete(WikiFilePage).where(WikiFilePage.file_id == file_id))

                log = WikiOperationLog(
                    file_id=file_id,
                    file_name=name,
                    operation="EGRESS",
                    details=json.dumps({
                        "cleaned_pages_count": count,
                        "deleted_pages_count": len(deleted_files)
                    }, ensure_ascii=False)
                )
                session.add(log)
                await session.commit()
                logger.info(f"[Egress] db_commit_done file_id={file_id}, name={name}")

        if count > 0 or deleted_files:
            date_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            log_entry = f"- [{date_str}] 摄出 [[{source_ref}]],清理了 {count} 个相关页面的内容,移除了 {len(deleted_files)} 个空页面。\n"
            log_path = os.path.join(egress_wiki_dir, "log.md")
            with open(log_path, "a", encoding="utf-8") as f:
                f.write(log_entry)
            logger.info(f"[Egress] 摄出完成: {name},清理 {count} 个页面,删除 {len(deleted_files)} 个空页面")
            return {"status": "success", "deleted": count}

        logger.info(f"[Egress] completed_without_pages file_id={file_id}, name={name}")
        return {"status": "success", "deleted": 0, "message": "已重置为待处理,但未发现相关生成的 Wiki 页面"}


@router.post("/wiki/batch_egress")
async def batch_egress_wiki(data: dict = Body(...), me: WikiOaUser = Depends(require_perm("wiki:file:batchEgress"))):
    """批量摄出已索引文件,保留原始文件并把状态重置为 Pending(逐个校验 owner 写权限)。"""
    ids = data.get("ids", [])
    if not ids:
        raise HTTPException(status_code=400, detail="ids 不能为空")
    logger.info(f"[BatchEgress] request ids={ids}")

    results = []
    skipped = []
    for fid in ids:
        async with AsyncSessionLocal() as session:
            result = await session.execute(select(WikiFile).where(WikiFile.id == fid))
            db_file = result.scalar_one_or_none()
            if not db_file:
                skipped.append({"id": fid, "reason": "not_found"})
                logger.warning(f"[BatchEgress] skip file_id={fid}, reason=not_found")
                continue
            try:
                await assert_file_action(session, me, db_file, NEED_WRITE)
            except HTTPException as he:
                skipped.append({"id": fid, "reason": he.detail})
                continue
            if db_file.status != "Indexed":
                skipped.append({"id": fid, "reason": db_file.status})
                logger.info(
                    f"[BatchEgress] skip file_id={fid}, name={db_file.name}, "
                    f"reason=status_{db_file.status}"
                )
                continue
            logger.info(
                f"[BatchEgress] accepted file_id={fid}, name={db_file.name}, "
                f"status={db_file.status}"
            )

        try:
            logger.info(f"[BatchEgress] start_item file_id={fid}")
            result = await egress_wiki(fid, me)  # 直接传已授权用户,跳过 DI(require_perm 仅经路由生效)
            results.append({"id": fid, **result})
            logger.info(f"[BatchEgress] item_done file_id={fid}, result={result}")
        except HTTPException as exc:
            skipped.append({"id": fid, "reason": exc.detail})
            logger.warning(
                f"[BatchEgress] item_http_error file_id={fid}, status_code={exc.status_code}, "
                f"detail={exc.detail}"
            )

    logger.info(
        f"[BatchEgress] response requested={len(ids)}, succeeded={len(results)}, "
        f"skipped={len(skipped)}, skipped_items={skipped}"
    )
    return {
        "status": "success",
        "requested": len(ids),
        "succeeded": len(results),
        "results": results,
        "skipped": skipped,
    }


@router.post("/wiki/ingest/cancel")
async def cancel_ingest(data: dict = Body(...), me: WikiOaUser = Depends(require_perm("wiki:file:cancelIngest"))):
    """终止正在运行或排队中的摄入任务,并把文件恢复为待处理(逐个校验 owner 写权限)。"""
    ids = data.get("ids", [])
    if not ids:
        raise HTTPException(status_code=400, detail="ids 不能为空")
    logger.info(f"[CancelIngest] request ids={ids}")

    cancelled = []
    skipped = []
    async with AsyncSessionLocal() as session:
        for fid in ids:
            result = await session.execute(select(WikiFile).where(WikiFile.id == fid))
            db_file = result.scalar_one_or_none()
            if not db_file:
                skipped.append({"id": fid, "reason": "not_found"})
                logger.warning(f"[CancelIngest] skip file_id={fid}, reason=not_found")
                continue
            try:
                await assert_file_action(session, me, db_file, NEED_WRITE)
            except HTTPException as he:
                skipped.append({"id": fid, "reason": he.detail})
                continue
            if db_file.status != "Ingesting":
                skipped.append({"id": fid, "reason": db_file.status})
                logger.info(
                    f"[CancelIngest] skip file_id={fid}, name={db_file.name}, "
                    f"reason=status_{db_file.status}"
                )
                continue

            ingest_cancel_requested.add(fid)
            task = ingest_tasks.get(fid)
            task_exists = task is not None
            task_done = task.done() if task else None
            if task and not task.done():
                task.cancel()
                logger.info(
                    f"[CancelIngest] task_cancel_requested file_id={fid}, name={db_file.name}, "
                    f"task_id={id(task)}"
                )
            else:
                logger.info(
                    f"[CancelIngest] no_active_task file_id={fid}, name={db_file.name}, "
                    f"task_exists={task_exists}, task_done={task_done}"
                )

            logger.info(
                f"[CancelIngest] db_reset_pending file_id={fid}, name={db_file.name}, "
                f"old_status={db_file.status}, new_status=Pending"
            )
            db_file.status = "Pending"
            db_file.error_message = None
            session.add(WikiOperationLog(
                file_id=fid,
                file_name=db_file.name,
                operation="INGEST_CANCELLED",
                details=json.dumps({"reason": "user_cancelled"}, ensure_ascii=False),
            ))
            cancelled.append(fid)
        await session.commit()
    logger.info(
        f"[CancelIngest] response cancelled={cancelled}, skipped={skipped}, "
        f"cancel_requested_snapshot={list(ingest_cancel_requested)}"
    )

    return {"status": "success", "cancelled": cancelled, "skipped": skipped}


@router.post("/wiki/ingest/{file_id}")
async def ingest_file(file_id: str, me: WikiOaUser = Depends(require_perm("wiki:file:ingest"))):
    """根据 ID 为单个文件启动摄入流程(owner/editor 可写库才允许,Reader → 403 权限不足)。"""
    logger.info(f"[IngestStart] request file_id={file_id}")
    async with AsyncSessionLocal() as session:
        result = await session.execute(select(WikiFile).where(WikiFile.id == file_id))
        db_file = result.scalar_one_or_none()
        if not db_file:
            logger.warning(f"[IngestStart] abort file_id={file_id}, reason=not_found")
            raise HTTPException(status_code=404, detail="数据库中未找到该文件")
        await assert_file_action(session, me, db_file, NEED_WRITE)
        if db_file.status == "Ingesting":
            logger.info(f"[IngestStart] already_ingesting file_id={file_id}, name={db_file.name}")
            return {"status": "already ingesting", "file_id": file_id}
        logger.info(
            f"[IngestStart] db_mark_ingesting file_id={file_id}, name={db_file.name}, "
            f"old_status={db_file.status}, new_status=Ingesting"
        )
        db_file.status = "Ingesting"
        db_file.error_message = None
        await session.commit()

    _schedule_ingest_task(file_id)
    logger.info(f"[IngestStart] response file_id={file_id}, status=ingest_started")
    return {"status": "ingest started", "file_id": file_id}




# ==================================================================================
# 摄入并发控制:信号量允许最多 INGEST_MAX_CONCURRENT_FILES 份文件并行摄入;
# 文件级锁保证同一文件的摄入/摄出互斥。
# ==================================================================================
ingest_global_semaphore = asyncio.Semaphore(INGEST_MAX_CONCURRENT_FILES)  # #2: 可配置并发数
file_operation_locks: dict[str, asyncio.Lock] = {}
ingest_tasks: dict[str, asyncio.Task] = {}
ingest_cancel_requested: set[str] = set()


def _get_file_operation_lock(file_id: str) -> asyncio.Lock:
    lock = file_operation_locks.get(file_id)
    if lock is None:
        lock = asyncio.Lock()
        file_operation_locks[file_id] = lock
    return lock


def _schedule_ingest_task(file_id: str) -> None:
    """登记摄入任务,便于后续按文件 ID 终止运行或排队任务。"""
    old_task = ingest_tasks.get(file_id)
    if old_task and not old_task.done():
        logger.info(
            f"[IngestTask] schedule_skipped_existing_task file_id={file_id}, "
            f"task_id={id(old_task)}"
        )
        return
    ingest_cancel_requested.discard(file_id)
    task = asyncio.create_task(run_ingest_agent(file_id))
    ingest_tasks[file_id] = task
    logger.info(
        f"[IngestTask] scheduled file_id={file_id}, task_id={id(task)}, "
        f"active_task_count={len(ingest_tasks)}"
    )

    def _cleanup(done_task: asyncio.Task) -> None:
        if ingest_tasks.get(file_id) is done_task:
            ingest_tasks.pop(file_id, None)
            cancelled = done_task.cancelled()
            exc_repr = None
            if not cancelled:
                try:
                    exc = done_task.exception()
                    exc_repr = repr(exc) if exc else None
                except asyncio.CancelledError:
                    cancelled = True
            logger.info(
                f"[IngestTask] cleaned file_id={file_id}, task_id={id(done_task)}, "
                f"cancelled={cancelled}, exception={exc_repr}, "
                f"active_task_count={len(ingest_tasks)}"
            )

    task.add_done_callback(_cleanup)


def _raise_if_ingest_cancelled(file_id: str) -> None:
    if file_id in ingest_cancel_requested:
        logger.info(f"[IngestCancelCheck] cancellation_detected file_id={file_id}")
        raise asyncio.CancelledError()


async def recover_interrupted_ingests() -> int:
    """#3: 服务启动时调用,将上次中断遗留的 Ingesting 状态文件回滚为 Pending。
    防止进程重启后文件永远卡在 Ingesting 状态无法再摄入。
    """
    async with AsyncSessionLocal() as session:
        result = await session.execute(
            select(WikiFile).where(WikiFile.status == "Ingesting")
        )
        stuck_files = result.scalars().all()
        count = 0
        for db_file in stuck_files:
            logger.warning(
                f"[Recovery] resetting_stuck_file file_id={db_file.id}, "
                f"name={db_file.name}, old_status=Ingesting"
            )
            db_file.status = "Pending"
            db_file.error_message = "服务重启时自动回滚(上次摄入被中断)"
            session.add(WikiOperationLog(
                file_id=db_file.id,
                file_name=db_file.name,
                operation="INGEST_RECOVERY",
                details=json.dumps({"reason": "service_restart"}, ensure_ascii=False),
            ))
            count += 1
        if count:
            await session.commit()
            logger.info(f"[Recovery] reset {count} stuck Ingesting file(s) to Pending")
        return count


async def _mark_ingest_cancelled(file_id: str) -> None:
    logger.info(f"[IngestCancel] mark_cancelled_start file_id={file_id}")
    ingest_cancel_requested.discard(file_id)
    try:
        async with AsyncSessionLocal() as session:
            result = await session.execute(select(WikiFile).where(WikiFile.id == file_id))
            db_file = result.scalar_one_or_none()
            if db_file and db_file.status == "Ingesting":
                logger.info(
                    f"[IngestCancel] db_reset_pending_from_task file_id={file_id}, "
                    f"name={db_file.name}, old_status={db_file.status}"
                )
                db_file.status = "Pending"
                db_file.error_message = None
                session.add(WikiOperationLog(
                    file_id=file_id,
                    file_name=db_file.name,
                    operation="INGEST_CANCELLED",
                    details=json.dumps({"reason": "task_cancelled"}, ensure_ascii=False),
                ))
                await session.commit()
                logger.info(f"[IngestCancel] db_commit_done file_id={file_id}, name={db_file.name}")
            elif db_file:
                logger.info(
                    f"[IngestCancel] db_already_not_ingesting file_id={file_id}, "
                    f"name={db_file.name}, status={db_file.status}"
                )
            else:
                logger.warning(f"[IngestCancel] db_file_missing file_id={file_id}")
    except Exception as exc:
        logger.error(f"[{file_id}] 更新摄入终止状态失败: {exc}", exc_info=True)

def save_post_with_formatting(post, fpath):
    meta_copy = dict(post.metadata)
    fs = meta_copy.pop("field_sources", None)
    
    new_post = frontmatter.Post(post.content, **meta_copy)
    raw_text = frontmatter.dumps(new_post)
    
    if fs:
        # 强制使用 yaml 格式化 field_sources
        fs_yaml = yaml.dump({"field_sources": fs}, allow_unicode=True, sort_keys=False, default_flow_style=False).strip()
        
        # 将 field_sources 插入到 Frontmatter 的末尾(也就是最后一个 --- 之前)
        if raw_text.startswith("---\n"):
            parts = raw_text.split("\n---\n", 1)
            if len(parts) == 2:
                raw_text = parts[0] + "\n\n" + fs_yaml + "\n---\n" + parts[1]
                
    with open(fpath, "w", encoding="utf-8") as f_out:
        f_out.write(raw_text)

# ==================================================================================
# 统一字段级溯源 (field_sources) 机制
# ----------------------------------------------------------------------------------
# 每个「受追踪字段」都在 field_sources 里记录其每个值由哪些来源贡献。
# 列表字段与标量字段一视同仁(标量内部按单值列表处理)。
# - 摄入:把新页面的字段贡献并入目标页 → _merge_field_sources
# - 摄出:移除某来源的贡献并按剩余来源重算字段值 → _recompute_after_source_removal
# 这样摄出只需「去掉自身的 field_sources 条目」即可保证 frontmatter 无残留。
# ==================================================================================

# 不参与来源追踪的字段(页面级元数据,不随单个来源增删)
SOURCE_TRACKED_EXCLUDE = set(load_ingest_contract().source_tracked_exclude)


def _as_value_list(v):
    """把字段值归一为「值列表」:列表原样、标量包成单元素、空值返回空列表。"""
    return contract_as_value_list(v)


def _merge_field_sources(target_md: dict, new_md: dict, canonical_source: str) -> None:
    """将 new_md 各受追踪字段的贡献并入 target_md,并维护 target_md['field_sources']。"""
    contract_merge_field_sources(target_md, new_md, canonical_source)


def _recompute_after_source_removal(md: dict, removed_source: str) -> None:
    """从 field_sources 移除某来源贡献,并按剩余来源重算字段值;无来源支撑的字段删除。"""
    contract_recompute_after_source_removal(md, removed_source)


# ==================================================================================
# 公共 LLM 响应解析工具函数
# ==================================================================================

def _extract_llm_text(content: Any) -> str:
    """从 LLM 响应 content 中提取纯文本,兼容 str / list / thinking-block 混合格式。"""
    if isinstance(content, list):
        parts = []
        for item in content:
            if isinstance(item, str):
                parts.append(item)
            elif isinstance(item, dict):
                if item.get("type") == "thinking":
                    pass  # 跳过 thinking 块
                elif "text" in item:
                    parts.append(item["text"])
        return "".join(parts)
    if not isinstance(content, str):
        return str(content)
    return content


def _extract_json_str(text: str) -> str:
    """从可能包含 Markdown 代码块包裹符的文本中提取 JSON 字符串。

    优先匹配 ```json ... ``` 代码块,否则取首个 { 到末尾 } 之间的内容。
    若均未找到则抛 ValueError。
    """
    json_match = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", text, re.DOTALL)
    if json_match:
        return json_match.group(1)
    start_idx = text.find("{")
    end_idx = text.rfind("}")
    if start_idx != -1 and end_idx != -1:
        return text[start_idx : end_idx + 1]
    raise ValueError(f"未找到合法的 JSON 格式: {text[:200]}...")


def _parse_json_safe(json_str: str, context_label: str = "") -> dict:
    """安全解析 JSON,json.loads 失败后使用 json_repair 兜底。

    json_repair 避免了 ast.literal_eval + 全局字符串替换的副作用。
    """
    try:
        return json.loads(json_str)
    except json.JSONDecodeError as e:
        logger.warning(
            "[JSONParse] json.loads 失败,尝试 json_repair context=%s error=%s",
            context_label or "-",
            e,
        )
        try:
            return json_repair.loads(json_str)
        except Exception as repair_err:
            raise ValueError(
                f"无法解析 JSON(json_repair 也失败): {json_str[:200]}..., error: {repair_err}"
            ) from repair_err


# ==================================================================================
# 摄入失败状态写入辅助(避免在多处重复 DB 更新代码)
# ==================================================================================

async def _mark_ingest_failed(file_id: str, error_message: str) -> None:
    """将文件状态标记为 Failed,写入错误信息和操作日志。

    必须清掉 cancel 标记:否则超时/失败的文件会残留该标记,
    导致下次重新摄入在入口处被直接判为「已取消」而中止。
    """
    logger.info(f"[IngestFail] mark_failed_start file_id={file_id}")
    ingest_cancel_requested.discard(file_id)
    try:
        async with AsyncSessionLocal() as session:
            result = await session.execute(select(WikiFile).where(WikiFile.id == file_id))
            db_file = result.scalar_one_or_none()
            if db_file:
                db_file.status = "Failed"
                db_file.error_message = error_message
                session.add(WikiOperationLog(
                    file_id=file_id,
                    file_name=db_file.name,
                    operation="INGEST_FAIL",
                    details=json.dumps({"error": error_message}, ensure_ascii=False),
                ))
                await session.commit()
                logger.info(
                    f"[IngestFail] db_commit_done file_id={file_id}, name={db_file.name}"
                )
            else:
                logger.warning(f"[IngestFail] db_file_missing file_id={file_id}")
    except Exception as db_err:
        logger.error(
            f"[IngestFail] db_update_failed file_id={file_id}, error={db_err}", exc_info=True
        )


# ==================================================================================
# Slug 注册表:一次遍历 wiki_dir 同时满足 Phase 1 和 Phase 3 的需求
# ==================================================================================

@dataclass
class SlugInfo:
    """单个已存在 wiki 页面的注册信息。"""
    slug: str
    page_type: str
    title: str
    abs_path: str


def _build_slug_registry(wiki_dir: str, skip_dirs: set) -> dict[str, SlugInfo]:
    """一次遍历 wiki_dir,构建 slug 注册表。

    返回值同时满足:
    - Phase 1 Planner 文本格式(slug → (type, title))
    - Phase 3 slug 冲突检测(slug → abs_path)
    """
    registry: dict[str, SlugInfo] = {}
    for root, dirs, files in os.walk(wiki_dir):
        dirs[:] = [d for d in dirs if os.path.join(root, d) not in skip_dirs]
        for f in files:
            if not f.endswith(".md") or f in ("index.md", "log.md"):
                continue
            slug = os.path.splitext(f)[0]
            fpath = os.path.join(root, f)
            try:
                post = frontmatter.load(fpath)
                title = str(post.metadata.get("title") or slug)
                ptype = str(post.metadata.get("type") or "")
            except Exception:
                title, ptype = slug, ""
            registry[slug] = SlugInfo(
                slug=slug,
                page_type=ptype,
                title=title,
                abs_path=os.path.abspath(fpath),
            )
    return registry


async def run_ingest_agent(file_id: str):
    try:
        _raise_if_ingest_cancelled(file_id)
        logger.info(
            f"[IngestTask] waiting_for_ingest_global_semaphore file_id={file_id}, "
            f"max_concurrent={INGEST_MAX_CONCURRENT_FILES}"
        )
        async with ingest_global_semaphore:  # #2: 信号量,允许最多 N 份文件并行
            logger.info(f"[IngestTask] acquired_ingest_global_semaphore file_id={file_id}")
            _raise_if_ingest_cancelled(file_id)
            logger.info(f"[IngestTask] waiting_for_file_lock file_id={file_id}")
            async with _get_file_operation_lock(file_id):
                logger.info(f"[IngestTask] acquired_file_lock file_id={file_id}")
                _raise_if_ingest_cancelled(file_id)
                timeout = INGEST_TIMEOUT_SECONDS if INGEST_TIMEOUT_SECONDS > 0 else None
                if timeout:
                    logger.info(
                        f"[IngestTask] timeout_set file_id={file_id}, timeout_seconds={timeout}"
                    )
                try:
                    await asyncio.wait_for(_run_ingest_agent_impl(file_id), timeout=timeout)
                except asyncio.TimeoutError:
                    logger.error(
                        f"[IngestTask] timeout_exceeded file_id={file_id}, "
                        f"timeout_seconds={timeout}, marking_failed"
                    )
                    await _mark_ingest_failed(
                        file_id, f"摄入超时({INGEST_TIMEOUT_SECONDS}s),任务被强制终止"
                    )
                logger.info(f"[IngestTask] released_work_after_impl file_id={file_id}")
    except asyncio.CancelledError:
        logger.info(f"[{file_id}] 摄入任务已被用户终止")
        await _mark_ingest_cancelled(file_id)

@dataclass(frozen=True)
class IngestContext:
    """一次摄入的阶段间不变量,三个阶段函数共用。

    只放全程只读的东西;阶段产物(规划结果、生成页面)走函数参数与返回值。
    """
    file_id: str
    filename: str
    canonical_source: str          # ware/raw/{format}/{filename},Phase 2 上下文与 Phase 3 溯源共用
    raw_content: str
    contract: IngestContract
    contract_text: str
    schema_version: str
    required_fields: list[str]     # 已剔除 created/updated 等系统维护字段
    skill_prompt: str
    shared_prefix: str             # skill + 契约 (+ 原始文档):Planner/Writer 共用的可缓存前缀
    # 多知识库隔离:本次摄入落到哪个库。base 库为 WIKI_DIR / 'ware/wiki',
    # 部门库为 ware/kb/dept/<dept_id>/wiki。slug 清单构建、落盘 rebase、index 重建都以此为准。
    wiki_dir: str = WIKI_DIR       # 该库 wiki 绝对目录
    wiki_rel: str = "ware/wiki"    # 该库 wiki 项目根相对路径
    is_long_doc: bool = False      # 超过 INGEST_LONG_DOC_THRESHOLD_CHARS 走分块流水线
    chunks: tuple[DocChunk, ...] = ()  # 长文档的原文块序列(短文档为空)


@dataclass(frozen=True)
class PlanResult:
    """Phase 1 产物。"""
    global_dims: dict[str, Any]
    pages: list[dict]
    slug_registry: dict[str, SlugInfo]  # Phase 3 冲突检测复用,避免二次遍历 WIKI_DIR


def _resolve_page_path(
    page_type: str, slug: str, series: Any, contract: IngestContract, wiki_rel: str = "ware/wiki"
) -> str:
    """按契约 `canonical_types[].directory` 生成确定性落盘相对路径。

    契约是路径的唯一事实源:改 schema 的 directory 即改落盘位置,代码不再各写一份。
    `sources` 的模板含 `{series}` 占位符(按体系分层),其余 type 的模板无占位符。

    多知识库:契约里的 directory 一律以 `ware/wiki/` 打头(base 布局);`wiki_rel` 非默认时
    把该前缀重定位到目标库的 wiki 根(如 ware/kb/dept/<id>/wiki)。纯函数,便于单测。
    """
    spec = contract.canonical_types.get(page_type) or {}
    template = str(spec.get("directory") or f"ware/wiki/{page_type}")
    if "{series}" in template:
        # series 可能是多来源合并后的数组,取首个非占位值作目录
        safe_series = pick_series_for_path(series, contract)
        safe_series = re.sub(r'[\\/:*?"<>|]', "_", safe_series) or "未分类"
        template = template.format(series=safe_series)
    rel = f"{template.rstrip('/')}/{slug}.md"
    # 多知识库:契约模板一律以 ware/wiki/ 打头,非 base 库把该前缀替换为目标库 wiki 根
    if wiki_rel and wiki_rel != "ware/wiki" and rel.startswith("ware/wiki/"):
        rel = f"{wiki_rel.rstrip('/')}/{rel[len('ware/wiki/'):]}"
    return rel


def _type_dir_of(rel_or_abs_path: str) -> str:
    """从 wiki 相对/绝对路径取 type 目录(wiki 根之后的第一段,兼容 base 与部门库)。"""
    p = str(rel_or_abs_path).replace("\\", "/")
    # base: ware/wiki/<type>/...;部门库: ware/kb/dept/<id>/wiki/<type>/...
    if "/wiki/" in p:
        tail = p.split("/wiki/", 1)[1]
    elif "ware/wiki/" in p:
        tail = p.split("ware/wiki/", 1)[1]
    else:
        tail = os.path.relpath(p, WIKI_DIR).replace("\\", "/")
    segs = [s for s in tail.split("/") if s]
    return segs[0] if segs else "misc"


# ==================================================================================
# 阶段零:分块内容清单 (Phase 0: Map,仅长文档分块模式)
# ==================================================================================

# 跨块逐字节一致的 system prompt,稳定前缀可命中上下文缓存;块内容放 user 消息。
_MAP_SYSTEM_PROMPT = """你是长文档摄入流水线的内容清单提取器(Map 阶段)。
输入是一份长文档中的一个原文块,你的任务是为它生成一份简洁的内容清单,
供后续规划器(Planner)在不阅读全文的情况下为各 Wiki 页面分配取材范围。

只输出一个合法 JSON 对象(不要 Markdown 代码块、前言或解释),结构:
{
  "topics": ["块内涉及的主题,3-8 个短语"],
  "entities": ["块内出现的关键实体:产品/品牌/车型/政策/活动名等"],
  "tables": ["块内每个表格的主题(关键列名),无表格则给空数组"],
  "summary": "不超过 80 字的一句话概括"
}
要求:只罗列块内客观存在的内容,不展开、不评价、不编造。"""


async def _phase0_map(ctx: IngestContext) -> list[dict]:
    """逐块提取内容清单,供长文档 Planner 在不读全文的情况下做页面规划。

    单块清单失败不阻断摄入:重试 1 次后降级为「heading_path + 块首 500 字」。
    """
    file_id, filename = ctx.file_id, ctx.filename
    _log_phase_banner(filename, "摄入阶段零 Map 逐块内容清单")
    logger.info(
        f"[{filename}] [Phase 0] 开始 Map 内容清单提取,共 {len(ctx.chunks)} 块,"
        f"模型: {INGEST_MAP_MODEL_NAME},并发: {INGEST_MAP_CONCURRENCY},"
        f"思考={'开' if INGEST_MAP_ENABLE_THINKING else '关'}"
    )
    sem = asyncio.Semaphore(INGEST_MAP_CONCURRENCY)
    map_tokens_before = current_task_token_usage()

    async def map_one(chunk: DocChunk) -> dict:
        fallback = {
            "chunk_id": chunk.chunk_id,
            "heading_path": chunk.heading_path,
            "summary": chunk.text[:500].strip(),
        }
        async with sem:
            for attempt in range(2):
                _raise_if_ingest_cancelled(file_id)
                try:
                    mapper = ReActAgent(
                        name=f"Mapper_{chunk.chunk_id}",
                        model=get_llm_model(
                            # enable_thinking 显式下发,Map 默认关思考(config.INGEST_MAP_ENABLE_THINKING);
                            # 不依赖全局 env 思考解析,避免"设了却不生效"。
                            INGEST_MAP_MODEL_NAME, purpose="INGEST_MAP",
                            temperature=INGEST_MODEL_TEMPERATURE,
                            enable_thinking=INGEST_MAP_ENABLE_THINKING,
                        ),
                        formatter=get_llm_formatter(INGEST_MAP_MODEL_NAME),
                        sys_prompt=_MAP_SYSTEM_PROMPT,
                    )
                    mapper.set_console_output_enabled(False)
                    msg = Msg(
                        "user",
                        f"【块 {chunk.chunk_id}:{chunk.heading_path}】\n"
                        f"{chunk.prompt_text}\n\n"
                        f"请输出该块的内容清单 JSON。",
                        role="user",
                    )
                    llm_context_token = current_llm_call_context.set({
                        "file_id": file_id,
                        "filename": filename,
                        "phase": "map",
                        "chunk_id": chunk.chunk_id,
                        "attempt": attempt + 1,
                    })
                    try:
                        res = await mapper(msg)
                    finally:
                        current_llm_call_context.reset(llm_context_token)
                    data = _parse_json_safe(
                        _extract_json_str(_extract_llm_text(res.content)),
                        f"{filename}/map/chunk{chunk.chunk_id}",
                    )
                    if not isinstance(data, dict):
                        raise ValueError(f"Map 输出必须是 JSON 对象: {type(data).__name__}")
                    data["chunk_id"] = chunk.chunk_id
                    data.setdefault("heading_path", chunk.heading_path)
                    # 打印 Map 产出的内容清单,便于核对分块抽取质量(关思考后仍可见 map 结果)。
                    logger.info(
                        "[%s] [Phase 0] map_result chunk_id=%s heading=%s topics=%s entities=%s tables=%s summary=%s",
                        filename, chunk.chunk_id, data.get("heading_path"),
                        data.get("topics"), data.get("entities"),
                        data.get("tables"), str(data.get("summary") or "")[:120],
                    )
                    return data
                except asyncio.CancelledError:
                    raise
                except Exception as e:
                    logger.warning(
                        f"[{filename}] [Phase 0] map_chunk_failed chunk_id={chunk.chunk_id} "
                        f"attempt={attempt + 1}: {e}"
                    )
            logger.warning(
                f"[{filename}] [Phase 0] map_chunk_fallback chunk_id={chunk.chunk_id},"
                f"降级使用块首摘要"
            )
            return fallback

    inventories = list(await asyncio.gather(*(map_one(c) for c in ctx.chunks)))
    map_token_delta = _token_delta(map_tokens_before, current_task_token_usage())
    logger.info(
        "[IngestTokenUsage] phase=map file_id=%s name=%s chunks=%s "
        "input_tokens=%s output_tokens=%s total_tokens=%s",
        file_id, filename, len(ctx.chunks),
        map_token_delta["input_tokens"],
        map_token_delta["output_tokens"],
        map_token_delta["total_tokens"],
    )
    return inventories


def _format_map_inventories(
    inventories: list[dict], chunks: Sequence[Any] = (),
) -> str:
    """把 Map 清单压成 Planner 可读的紧凑行文本。

    带上每块字符数,Planner 才能精确累加、守住单页认领上限,
    避免"估算超限被打回重试"白烧一次思考调用。
    """
    sizes = {c.chunk_id: len(c.text) for c in chunks}
    lines = []
    for inv in inventories:
        topics = "、".join(str(t) for t in (inv.get("topics") or []))
        entities = "、".join(str(e) for e in (inv.get("entities") or []))
        tables = "、".join(str(t) for t in (inv.get("tables") or []))
        _cid = inv.get("chunk_id")
        _size = sizes.get(_cid)
        _size_txt = f" [{_size}字符]" if _size is not None else ""
        parts = [f"- 块 {_cid}{_size_txt}({inv.get('heading_path') or '无标题'})"]
        if topics:
            parts.append(f"主题[{topics}]")
        if entities:
            parts.append(f"实体[{entities}]")
        if tables:
            parts.append(f"表格[{tables}]")
        summary = str(inv.get("summary") or "").strip()
        if summary:
            parts.append(summary)
        lines.append(" ".join(parts))
    return "\n".join(lines)


def _check_page_source_budget(pages: list[dict], chunks: tuple[DocChunk, ...]) -> None:
    """单页认领原文超预算即抛 ValueError,走 Planner 重试回路修正。"""
    sizes = {c.chunk_id: len(c.text) for c in chunks}
    for page in pages:
        # sources 页不认领原文块(延后合成),跳过预算校验。
        if str(page.get("type", "")).strip() in ("sources", "source"):
            continue
        claimed = page.get("source_chunks") or []
        total = sum(sizes.get(int(c), 0) for c in claimed)
        if total > PAGE_SOURCE_MAX_CHARS:
            raise ValueError(
                f"页面 {page.get('slug', '?')}(type={page.get('type', '?')})认领的原文块共 "
                f"{total} 字符,超过单页上限 {PAGE_SOURCE_MAX_CHARS};"
                f"请把该主题拆分为多个页面,或减少本页认领的块"
            )


def _max_chunks_per_page(chunks: tuple[DocChunk, ...]) -> int:
    """把单页字符预算折算成「最多认领几块」,用于 Planner prompt。

    实测让 LLM 精确累加字符数不可靠(多次因超限被打回重试),而数块很稳。
    按平均块大小折算并至少留 1 块,避免出现 0。
    """
    if not chunks:
        return 1
    avg = max(1, sum(len(c.text) for c in chunks) // len(chunks))
    return max(1, PAGE_SOURCE_MAX_CHARS // avg)


def _check_chunk_coverage(pages: list[dict], chunks: tuple[DocChunk, ...]) -> None:
    """全部块必须被至少一个下游页认领;漏块即抛 ValueError 走 Planner 重试回路反思重规划。

    覆盖是分块摄入的正确性底线(未认领块 = Writer 永远读不到 = 内容必然丢失),
    故前移到 Planner 校验阶段——在任何 Writer 跑之前拦住,避免写完才发现再补救。
    """
    uncovered = find_uncovered_chunks(chunks, pages)
    if not uncovered:
        return
    ids = [c.chunk_id for c in uncovered]
    raise ValueError(
        f"未认领块 {ids}:每个块都必须被至少一个下游主题页认领。"
        f"请把它们补进语义最相关的页面;若这些块的主题与现有页面都不相关,"
        f"应当新增对应主题的页面来承接。允许认领不连续的块。"
    )


# ==================================================================================
# 阶段一:统筹规划与全局打标 (Phase 1: Macro Planning & Tagging)
# ==================================================================================
async def _phase1_plan(
    ctx: IngestContext,
    map_inventories: list[dict] | None = None,
    slug_registry: dict[str, SlugInfo] | None = None,
) -> PlanResult:
    """全局分析原始文档,输出文档级过滤维度与页面切分规划。

    Planner 输出非法时把上次输出连同错误原因回喂,让它增量修复而非从头重写;
    连续 INGEST_PLANNER_MAX_RETRIES + 1 次失败则中止摄入。

    长文档分块模式(ctx.is_long_doc):Planner 只看 map_inventories 块清单,
    每页必须认领 source_chunks,并做单页原文预算校验 + 全量块覆盖校验。
    """
    file_id, filename = ctx.file_id, ctx.filename

    print_thinking.set(True)
    _log_phase_banner(filename, "摄入阶段一 统筹规划与全局打标")
    logger.info(f"[{filename}] [阶段一] 开始统筹规划与全局打标... 使用模型: {INGEST_MODEL_NAME}")

    # 一次遍历构建 slug 注册表(Phase 1 Planner 文本 + Phase 3 冲突检测复用同一份)
    # 多知识库:只扫本次目标库的 wiki 目录,避免拿别的库 slug 去规划本库页面
    if slug_registry is None:
        _skip_dirs = {os.path.join(ctx.wiki_dir, "metadata"), os.path.join(ctx.wiki_dir, "lint_reports")}
        slug_registry = _build_slug_registry(ctx.wiki_dir, _skip_dirs)
    slug_registry_text = "\n".join(
        f"- [[{s}]] ({info.page_type}) — {info.title}"
        for s, info in sorted(slug_registry.items())
    ) or "(当前知识库为空,无既有页面)"
    logger.info(
        f"[{filename}] [Phase 1] slug_registry_built slugs_count={len(slug_registry)}"
    )

    if ctx.is_long_doc:
        planner_sys_prompt = build_planner_system_prompt_chunked(
            shared_prefix=ctx.shared_prefix,
            slug_registry_text=slug_registry_text,
            chunk_inventory_text=_format_map_inventories(map_inventories or [], ctx.chunks),
            chunk_count=len(ctx.chunks),
            sources_slug=_sources_slug_for_file(ctx.filename),
            # 让 LLM 数块比让它累加字符数可靠得多:把预算同时折算成块数上限给它
            max_chunks_per_page=_max_chunks_per_page(ctx.chunks),
        )
    else:
        planner_sys_prompt = build_planner_system_prompt(
            shared_prefix=ctx.shared_prefix,
            slug_registry_text=slug_registry_text,
        )
    _log_prefix_fingerprint(filename, "planner", planner_sys_prompt)
    planner_agent = ReActAgent(
        name="PlannerAgent",
        model=get_llm_model(
            INGEST_MODEL_NAME, purpose="INGEST", temperature=INGEST_MODEL_TEMPERATURE
        ),
        formatter=get_llm_formatter(INGEST_MODEL_NAME),
        sys_prompt=planner_sys_prompt
    )
    # 规划时不开启终端并发打印干扰
    planner_agent.set_console_output_enabled(False)

    # 原始文档/块清单已在 system prompt 里,此处不再重发,仅给触发指令。
    if ctx.is_long_doc:
        _plan_trigger = "请依据上述原文块清单,按输出接口与认领规则完成规划,只输出规划 JSON 对象。"
    else:
        _plan_trigger = "请依据上述共享上下文中的原始文档,按输出接口要求完成规划,只输出规划 JSON 对象。"
    msg_plan = Msg("user", _plan_trigger, role="user")
    raw_global_dims: dict[str, Any] = {}
    pages: list[dict] = []

    for planner_attempt in range(INGEST_PLANNER_MAX_RETRIES + 1):
        _raise_if_ingest_cancelled(file_id)
        logger.info(
            f"[{filename}] [Phase 1] planner_attempt={planner_attempt + 1}/"
            f"{INGEST_PLANNER_MAX_RETRIES + 1}"
        )

        planner_tokens_before = current_task_token_usage()
        llm_context_token = current_llm_call_context.set({
            "file_id": file_id,
            "filename": filename,
            "phase": "planner",
            "attempt": planner_attempt + 1,
        })
        try:
            plan_res = await planner_agent(msg_plan)
        finally:
            current_llm_call_context.reset(llm_context_token)

        planner_tokens_after = current_task_token_usage()
        planner_token_delta = _token_delta(planner_tokens_before, planner_tokens_after)
        logger.info(
            "[IngestTokenUsage] phase=planner file_id=%s name=%s attempt=%s "
            "input_tokens=%s output_tokens=%s total_tokens=%s "
            "task_input_tokens=%s task_output_tokens=%s task_total_tokens=%s",
            file_id, filename, planner_attempt + 1,
            planner_token_delta["input_tokens"],
            planner_token_delta["output_tokens"],
            planner_token_delta["total_tokens"],
            planner_tokens_after["input_tokens"],
            planner_tokens_after["output_tokens"],
            planner_tokens_after["total_tokens"],
        )

        plan_text = _extract_llm_text(plan_res.content)

        try:
            clean_json = _extract_json_str(plan_text)
            plan_data = _parse_json_safe(
                clean_json, f"{filename}/planner/attempt{planner_attempt + 1}"
            )
            # #5: validate_planner_output 做结构校验,格式非法时立即抛异常
            # 长文档分块模式附加 source_chunks 校验。
            raw_global_dims, pages = validate_planner_output(
                plan_data,
                chunk_count=len(ctx.chunks) if ctx.is_long_doc else None,
            )
            if ctx.is_long_doc:
                # 单页认领超预算 → 抛 ValueError 走同一重试回路,让 Planner 拆页
                _check_page_source_budget(pages, ctx.chunks)
                # 覆盖校验前移:漏块即回喂让 Planner 反思重规划,保证在任何 Writer 跑之前
                # 全部块都已被认领;重试耗尽由回路统一硬失败中止摄入。
                _check_chunk_coverage(pages, ctx.chunks)

            retry_label = "首次尝试" if planner_attempt == 0 else f"第 {planner_attempt} 次重试后"
            _covered = f", chunks_covered={len(ctx.chunks)}/{len(ctx.chunks)}" if ctx.is_long_doc else ""
            logger.info(
                f"[{filename}] [Phase 1] planner_success ({retry_label}) "
                f"pages_count={len(pages)}{_covered}, "
                f"page_paths={[p.get('file_path') for p in pages if isinstance(p, dict)]}"
            )
            # slug 复用决策:观察"复用已有页 vs 新建近重复页"的实际比例,判断复用提示是否生效
            _planned = [str(p.get("slug")) for p in pages if isinstance(p, dict) and p.get("slug")]
            _reused = [s for s in _planned if s in slug_registry]
            logger.info(
                f"[{filename}] [Phase 1] slug_reuse reused={_reused} "
                f"new={[s for s in _planned if s not in slug_registry]}"
            )
            break  # 成功,跳出重试循环

        except (ValueError, json.JSONDecodeError) as parse_err:
            logger.warning(
                f"[{filename}] [Phase 1] planner_attempt={planner_attempt + 1} "
                f"校验失败: {parse_err}"
            )
            if planner_attempt < INGEST_PLANNER_MAX_RETRIES:
                msg_plan = Msg(
                    "user",
                    f"你上一次的输出未通过结构校验!\n"
                    f"错误原因:{parse_err}\n\n"
                    f"以下是你上次的完整输出(请在此基础上修复,而非从头重写):\n\n"
                    f"{plan_text}\n\n"
                    f"请修复后重新输出合法的 JSON 对象。",
                    role="user",
                )
            else:
                raise ValueError(
                    f"[Phase 1] Planner 连续 {INGEST_PLANNER_MAX_RETRIES + 1} 次校验失败,"
                    f"摄入中止: {parse_err}"
                ) from parse_err

    _raise_if_ingest_cancelled(file_id)

    # #9: 从 schema contract 读取维度默认值,避免硬编码在代码中
    _defaults = ctx.contract.dim_defaults
    # 生态品牌(嘀加、广联数科)不是品牌体系,禁止作为 series;命中即回落 通用品牌。
    _series, _series_warning = sanitize_series(
        _norm_scalar(raw_global_dims.get("series"), _defaults.get("series")),
        ctx.contract,
    )
    if _series_warning:
        logger.warning(f"[{filename}] [Phase 1] {_series_warning}")
    # sub_business 不在此处:它是页面级维度,由 Planner 逐页声明(见 pages[].sub_business),
    # 在 resolve_effective_dims 中解析。全局默认值会静默污染所有下游页面。
    global_dims = {
        "series": _series,
        "brand": _norm_list(raw_global_dims.get("brand")) or [_defaults.get("brand")],
        "business_category": _norm_scalar(
            raw_global_dims.get("business_category"), _defaults.get("business_category")
        ),
        "role": _norm_list(raw_global_dims.get("role")) or [_defaults.get("role")],
    }

    logger.info(
        f"[{filename}] [Phase 1] 规划完成。全局维度: {global_dims},"
        f"页面级子业务: {[(p.get('slug'), p.get('sub_business')) for p in pages]},"
        f"规划页面数: {len(pages)}"
    )
    return PlanResult(global_dims=global_dims, pages=pages, slug_registry=slug_registry)


def _norm_scalar(v: Any, default: Any) -> Any:
    if isinstance(v, list):
        return v[0] if v else default
    return v if v not in (None, "") else default


def _norm_list(v: Any) -> list:
    if isinstance(v, list):
        out = []
        for x in v:
            if x and x not in out:
                out.append(x)
        return out
    return [] if v in (None, "") else [v]


# ==================================================================================
# 阶段二:并发写作与网关自检 (Phase 2: Concurrent Writing & Validation)
# ==================================================================================
async def _write_single_page(
    ctx: IngestContext,
    global_dims: dict,
    page_info: dict,
    *,
    max_retries: int = INGEST_WRITER_MAX_RETRIES,
    synthesis: bool = False,
    material_text: str | None = None,
) -> dict:
    """写单个 wiki 页面 + Python 级 frontmatter 强校验 + 失败回喂重试。

    - 普通页:长文取本页认领块、短文读共享前缀全文;
    - synthesis=True(sources 延后合成):素材是 material_text(本次已生成的下游页面)。
    连续重试仍不合格则抛 ValueError(fail-fast)。
    """
    file_id, filename = ctx.file_id, ctx.filename
    effective_dims, dim_warnings = resolve_effective_dims(page_info, global_dims, ctx.contract)
    for _w in dim_warnings:
        logger.warning(f"[{filename}] [Phase 2] {_w}")

    try:
        _planned_type = canonicalize_type(page_info.get("type"), ctx.contract)
        _required_extra = list(
            (ctx.contract.canonical_types.get(_planned_type) or {}).get("required_extra") or []
        )
    except ValueError:
        _required_extra = []

    if synthesis:
        page_chunks_text = material_text
    elif ctx.is_long_doc:
        page_chunks = select_chunks(ctx.chunks, page_info.get("source_chunks") or [])
        page_chunks_text = format_chunks_for_prompt(page_chunks)
        logger.info(
            f"[{filename}] [Phase 2] writer_chunks page={page_info.get('slug')}, "
            f"claimed={[c.chunk_id for c in page_chunks]}, "
            f"chars={sum(len(c.text) for c in page_chunks)}"
        )
    else:
        page_chunks_text = None

    writer_sys_prompt = build_writer_system_prompt(
        shared_prefix=ctx.shared_prefix,
        page_info=page_info,
        effective_dims=effective_dims,
        source_ref=ctx.canonical_source,
        schema_version=ctx.schema_version,
        required_extra=_required_extra,
        page_chunks_text=page_chunks_text,
        synthesis=synthesis,
    )
    _log_prefix_fingerprint(filename, f"writer:{page_info.get('slug', 'page')}", writer_sys_prompt)

    writer_agent = ReActAgent(
        name=f"Writer_{page_info.get('slug', 'page')}",
        model=get_llm_model(
            INGEST_MODEL_NAME, purpose="INGEST", temperature=INGEST_MODEL_TEMPERATURE
        ),
        formatter=get_llm_formatter(INGEST_MODEL_NAME),
        sys_prompt=writer_sys_prompt
    )
    writer_agent.set_console_output_enabled(False)

    if synthesis:
        msg_prompt = "请依据上述【本次已生成的下游页面】与本页运行时上下文,合成并只输出完整的 sources 摘要页 Markdown。"
    elif ctx.is_long_doc:
        msg_prompt = "请依据上述本页取材原文块与本页运行时上下文,生成并只输出完整 Markdown 页面。"
    else:
        msg_prompt = "请依据上述共享上下文中的原始文档与本页运行时上下文,生成并只输出完整 Markdown 页面。"
    msg_write = Msg("user", msg_prompt, role="user")
    content = ""

    for attempt in range(max_retries + 1):
        _raise_if_ingest_cancelled(file_id)
        try:
            llm_context_token = current_llm_call_context.set({
                "file_id": file_id,
                "filename": filename,
                "page_path": page_info.get("file_path"),
                "phase": "sources_synthesis" if synthesis else "writer",
            })
            try:
                res_write = await writer_agent(msg_write)
            finally:
                current_llm_call_context.reset(llm_context_token)

            content = _extract_llm_text(res_write.content)
            content = re.sub(r"<(?:think|thinking)>.*?</(?:think|thinking)>", "", content, flags=re.DOTALL)
            content = content.strip()
            content = re.sub(r"^```[a-zA-Z]*\s*\n", "", content)
            content = re.sub(r"\n```\s*$", "", content)
            content = content.strip()
            content = normalize_br_tags(content)

            try:
                post = frontmatter.loads(content)
            except Exception as parse_err:
                raise ValueError(f"Frontmatter 解析失败: {parse_err}") from parse_err

            md = post.metadata
            missing = [f for f in ctx.required_fields if f not in md]
            if missing:
                raise ValueError(f"YAML 缺少必填字段: {missing}")
            if str(md.get("schema_version")) != ctx.schema_version:
                raise ValueError(
                    f"schema_version 必须是 {ctx.schema_version},当前为: {md.get('schema_version')}"
                )
            page_type = canonicalize_type(md.get("type"), ctx.contract)
            missing_extra = missing_required_extra(md, page_type, ctx.contract)
            if missing_extra:
                raise ValueError(f"type={page_type} 缺少该类型必填字段: {missing_extra}")

            retry_info = "首次尝试" if attempt == 0 else f"第 {attempt} 次重试后"
            logger.info(f"[{filename}] [Phase 2] 页面校验成功: {page_info.get('file_path')} ({retry_info}成功)")
            # 逐页保真度:本页取材原文 vs 生成正文(wiki 汇总有损,量化便于调参)
            if page_chunks_text is not None:
                _src_sec = _count_md_sections(page_chunks_text)
                _out_sec = _count_md_sections(content)
                logger.info(
                    "[Fidelity] page=%s src_sections=%s out_sections=%s "
                    "src_chars=%s out_chars=%s section_ratio=%s",
                    page_info.get("slug"), _src_sec, _out_sec,
                    len(page_chunks_text), len(content),
                    round(_src_sec / _out_sec, 2) if _out_sec else 0.0,
                )
            return {"file_path": page_info.get("file_path"), "content": content}
        except Exception as check_err:
            logger.warning(f"[{filename}] [Phase 2] 页面校验失败 {page_info.get('file_path')} (第 {attempt+1} 次): {check_err}")
            if attempt < max_retries:
                failed_output = content or "(上次未能解析出有效内容)"
                msg_write = Msg(
                    "user",
                    f"你上一次的输出未通过规范校验!\n"
                    f"错误原因:{str(check_err)}\n\n"
                    f"以下是你上次的完整输出(请在此基础上修复,而非从头重写):\n\n"
                    f"{failed_output}\n\n"
                    f"请修复后重新输出完整的 Markdown 页面。",
                    role="user",
                )
            else:
                error_msg = f"页面 {page_info.get('file_path')} 连续重试校验失败,摄入中止。"
                logger.error(f"[{filename}] [Phase 2] {error_msg}")
                raise ValueError(error_msg)


async def _phase2_write(ctx: IngestContext, plan: PlanResult) -> list[dict]:
    """按规划并发写作各页面,产出经 Python 强校验的 Markdown。

    任一页面连续重试仍不合格即 fail-fast 中止整份摄入:宁可整体失败,
    也不要落一半页面导致知识库处于半成品状态。
    """
    file_id, filename = ctx.file_id, ctx.filename
    _log_phase_banner(filename, "摄入阶段二 并发写作与网关自检")
    # 长文分块模式:sources 页从本批次剔除,延后到全部下游页写完后由 _phase2_6_synthesize_sources 合成
    #(sources 内容取材于成品下游页,不是原文块)。短文/补充轮路径照旧写全部页。
    if ctx.is_long_doc:
        pages = [p for p in plan.pages if not _is_sources_page(p)]
    else:
        pages = plan.pages

    if not pages:
        logger.info(f"[{filename}] [Phase 2] 无下游页面需写作(跳过)")
        return []

    print_thinking.set(False)

    # #11: Writer 并发信号量,数量由配置项 INGEST_WRITER_CONCURRENCY 控制
    sem = asyncio.Semaphore(INGEST_WRITER_CONCURRENCY)

    async def sem_write_single_page(page_info):
        async with sem:
            return await _write_single_page(ctx, plan.global_dims, page_info)

    _raise_if_ingest_cancelled(file_id)

    # 曾在此做「首页 Writer 串行预热」以图暖热共享前缀缓存,实测无效、已移除:
    # scripts/probe_prefix_cache.py 证明 DashScope 该模型的隐式缓存**只对「新请求是已缓存请求的
    # 严格前缀延展」命中**;Writer 各页取材不同属"共享前缀后分叉",实测 0% 命中
    #(把独有内容改放 user 消息同样 0%)。预热只会白加一个 Writer 时长的串行延迟。
    logger.info(f"[{filename}] [Phase 2] 开始并发写作与自检,共 {len(pages)} 个页面...")
    _raise_if_ingest_cancelled(file_id)
    write_tasks = [asyncio.create_task(sem_write_single_page(p)) for p in pages]

    # 使用 asyncio.wait 实现 fail-fast,如果任一页面发生异常立即阻断
    try:
        done, pending = await asyncio.wait(write_tasks, return_when=asyncio.FIRST_EXCEPTION)
    except asyncio.CancelledError:
        for task in write_tasks:
            task.cancel()
        await asyncio.gather(*write_tasks, return_exceptions=True)
        raise

    # 问题8:先取消未完成任务,再 await gather 确保资源干净释放
    for task in pending:
        task.cancel()
    if pending:
        await asyncio.gather(*pending, return_exceptions=True)

    generated_results = []
    first_exception = None
    for task in done:
        exc = task.exception()
        if exc and first_exception is None:
            first_exception = exc
        elif not exc:
            generated_results.append(task.result())
    if first_exception:
        raise first_exception

    valid_files = [res for res in generated_results if res is not None]
    logger.info(f"[{filename}] [Phase 2] 并发写作完成。成功生成 {len(valid_files)} / {len(pages)} 个页面。")
    phase2_token_usage = current_task_token_usage()
    # 累计到 Phase 2 结束时,整份文档(Planner + 全部 Writer)命中缓存的 input token 总量。
    _cached = phase2_token_usage["cached_input_tokens"]
    _cache_hit_rate = (_cached / phase2_token_usage["input_tokens"]) if phase2_token_usage["input_tokens"] else 0.0
    logger.info(
        "[IngestTokenUsage] phase=writer_summary file_id=%s name=%s "
        "pages_planned=%s pages_generated=%s llm_input_tokens=%s "
        "llm_cached_input_tokens=%s llm_cache_hit_rate=%.2f "
        "llm_output_tokens=%s llm_total_tokens=%s",
        file_id,
        filename,
        len(pages),
        len(valid_files),
        phase2_token_usage["input_tokens"],
        _cached,
        _cache_hit_rate,
        phase2_token_usage["output_tokens"],
        phase2_token_usage["total_tokens"],
    )
    _raise_if_ingest_cancelled(file_id)
    return valid_files


# ==================================================================================
# 阶段 2.5:覆盖补充轮 (Coverage Supplement,仅长文档分块模式)
# ==================================================================================

def _slug_of_generated(vf: dict) -> str:
    return os.path.splitext(os.path.basename(vf.get("file_path") or ""))[0]


def _format_downstream_digest(downstream_files: list[dict]) -> str:
    """把本次已生成的下游 wiki 页面拼成 sources 合成素材:逐页给出落盘路径 + 完整 frontmatter+正文。

    素材已是下游成品页(远小于原始长文),不截断,让 sources 合成器据此聚合维度、写摘要与真实导航。
    """
    parts = []
    for vf in downstream_files:
        path = vf.get("file_path") or ""
        content = (vf.get("content") or "").strip()
        parts.append(f"===== 页面 {path} =====\n{content}")
    return "\n\n".join(parts)


async def _phase2_6_synthesize_sources(
    ctx: IngestContext,
    plan: PlanResult,
    downstream_files: list[dict],
    map_inventories: list[dict] | None,
) -> list[dict]:
    """长文分块模式:所有下游页写完后,用成品下游页作素材单独合成 sources 摘要页。

    - sources 页 slug 由原始文件名确定性生成(1 份原始文件 ↔ 1 个 sources 页);
    - 下游为空时兜底用 Map 清单,避免 sources 无素材可写。
    """
    sources_pages = [p for p in plan.pages if _is_sources_page(p)]
    if not sources_pages:
        return []

    _log_phase_banner(ctx.filename, "摄入阶段2.6 sources 来源摘要页合成")
    material = _format_downstream_digest(downstream_files)
    if not material.strip():
        material = _format_map_inventories(map_inventories or [])
    forced_slug = _sources_slug_for_file(ctx.filename)

    results: list[dict] = []
    for page_info in sources_pages:
        page_info = dict(page_info)  # 不改动 plan 原对象
        # 确定性覆盖 slug 与落盘路径,保证 sources 与原始文件 1:1
        page_info["slug"] = forced_slug
        page_info["file_path"] = _resolve_page_path(
            canonicalize_type(page_info.get("type"), ctx.contract), forced_slug,
            page_info.get("series") or plan.global_dims.get("series"), ctx.contract,
            ctx.wiki_rel,
        )
        logger.info(
            f"[{ctx.filename}] [Phase 2.6] 合成 sources 页 slug={forced_slug} "
            f"path={page_info['file_path']},素材={len(downstream_files)} 个下游页"
        )
        vf = await _write_single_page(
            ctx, plan.global_dims, page_info, synthesis=True, material_text=material,
        )
        results.append(vf)
    return results



def _write_ingest_trace(
    ctx: IngestContext,
    map_inventories: list[dict] | None,
    plan: PlanResult,
    fidelity: dict | None = None,
) -> str | None:
    """长文摄入全过程落盘 `ware/ingest_trace/{yyyyMM}/{文件名}_{file_id}.json`,供事后排查
    「某段原文切在哪个块、被哪个页面认领、Map 清单有没有漏」。写失败不阻塞摄入。"""
    try:
        month_dir = os.path.join(INGEST_TRACE_DIR, datetime.now().strftime("%Y%m"))
        os.makedirs(month_dir, exist_ok=True)
        trace_path = os.path.join(
            month_dir, f"{_sources_slug_for_file(ctx.filename)}_{ctx.file_id}.json"
        )
        payload = {
            "file_id": ctx.file_id,
            "filename": ctx.filename,
            "ingest_time": datetime.now().isoformat(timespec="seconds"),
            "content_chars": len(ctx.raw_content),
            "fidelity": fidelity or {},
            "chunks": [
                {
                    "chunk_id": c.chunk_id,
                    "heading_path": c.heading_path,
                    "char_start": c.char_start,
                    "char_end": c.char_end,
                    "text": c.text,
                }
                for c in ctx.chunks
            ],
            "map_inventories": map_inventories or [],
            "page_claims": {
                str(p.get("slug")): [int(c) for c in (p.get("source_chunks") or [])]
                for p in plan.pages
                if isinstance(p, dict)
            },
            # 覆盖由 Phase 1 的 _check_chunk_coverage 前置保证,恒为空,仅作审计留痕
            "uncovered_chunks": [],
        }
        with open(trace_path, "w", encoding="utf-8") as f:
            json.dump(payload, f, ensure_ascii=False, indent=2)
        logger.info(f"[{ctx.filename}] [IngestTrace] saved path={trace_path}")
        return trace_path
    except Exception:
        logger.warning(f"[{ctx.filename}] [IngestTrace] save_failed", exc_info=True)
        return None


# ==================================================================================
# 阶段三:合并保存与同步 (Phase 3: Batch Save & Sync)
# ==================================================================================
async def _phase3_persist(
    ctx: IngestContext,
    valid_files: list[dict],
    slug_registry: dict[str, SlugInfo],
) -> None:
    """原子落盘(staging + backup + rollback)、同 slug 合并、重建 index、追加 log。

    `valid_files[i]["file_path"]` 会被原地改写为真实落点,供调用方写 DB。
    """
    file_id, filename = ctx.file_id, ctx.filename
    canonical_source = ctx.canonical_source
    _log_phase_banner(filename, "摄入阶段三 原子落盘与索引重建")

    if valid_files:
        logger.info(f"[{filename}] [Phase 3] 开始批量原子保存 (staging)...")
        _raise_if_ingest_cancelled(file_id)

        # 复用 Phase 1 构建好的 slug_registry,无需第二次遍历 WIKI_DIR
        disk_slug_paths = {slug: info.abs_path for slug, info in slug_registry.items()}

        # ── #4 原子保存:staging + backup + rollback ──────────────────────────
        # staging_dir: 临时目录,所有新文件/合并文件先写入此处
        # backup_pairs: [(原始路径, 备份路径)],仅已存在的文件才备份
        # staged_pairs: [(staging文件路径, 最终目标路径)],全部成功后才 shutil.move
        staging_dir = tempfile.mkdtemp(
            prefix=f"ingest_{file_id[:8]}_", dir=os.path.dirname(WIKI_DIR)
        )
        backup_pairs: list[tuple[str, str]] = []
        staged_pairs: list[tuple[str, str]] = []

        # created/updated 由系统维护,不采信 Writer 输出(LLM 会编造日期)。
        # 循环外取一次,保证同一批次落盘日期完全一致。
        ingest_date = datetime.now().strftime("%Y-%m-%d")

        try:
            for vf in valid_files:
                _raise_if_ingest_cancelled(file_id)
                slug = os.path.splitext(os.path.basename(vf["file_path"]))[0]
                # 解析失败兜底用的预备落点(Planner 原始路径)
                fpath = os.path.join(BASE_DIR, vf["file_path"])

                try:
                    post = frontmatter.loads(vf["content"])

                    # —— 路径确定性化:按 type 推导落点,忽略 Planner 自加的子目录 ——
                    page_type = canonicalize_type(
                        post.metadata.get("type") or _type_dir_of(vf["file_path"]),
                        ctx.contract,
                    )
                    post.metadata["type"] = page_type

                    # —— series 兜底拦截:生态品牌不是品牌体系,禁止作为 series ——
                    # Phase 1 已拦过 global_dims,这里防 Writer 自行写回(sources 目录由它派生)。
                    _raw_series = _as_value_list(post.metadata.get("series"))
                    if _raw_series:
                        _clean_series: list[str] = []
                        for _s in _raw_series:
                            _sv, _sw = sanitize_series(_s, ctx.contract)
                            if _sw:
                                logger.warning(f"[{filename}] [{slug}] {_sw}")
                            if _sv and _sv not in _clean_series:
                                _clean_series.append(_sv)
                        if _clean_series:
                            post.metadata["series"] = (
                                _clean_series
                                if isinstance(post.metadata.get("series"), list)
                                else _clean_series[0]
                            )

                    # 落盘位置由契约的 canonical_types[].directory 决定(按库 rebase)
                    rel_path = _resolve_page_path(
                        page_type, slug, post.metadata.get("series"), ctx.contract, ctx.wiki_rel
                    )
                    fpath = os.path.join(BASE_DIR, rel_path)

                    # —— slug 冲突 → 合并而非报错 ——
                    conflict = disk_slug_paths.get(slug)
                    if conflict and os.path.abspath(conflict) != os.path.abspath(fpath):
                        if _type_dir_of(conflict) == page_type:
                            # 同类型:同一 slug = 同一页面,重定向合并到既有页面
                            logger.info(
                                f"[{filename}] [Phase 3] slug '{slug}' 已存在于 "
                                f"{os.path.relpath(conflict, BASE_DIR)},本次内容合并入既有页面"
                            )
                            fpath = conflict
                            rel_path = os.path.relpath(conflict, BASE_DIR).replace("\\", "/")
                        else:
                            # 跨类型撞名:真正的命名歧义,保证 [[slug]] 可解析
                            raise ValueError(
                                f"slug 跨类型冲突:'{slug}' 已存在于 "
                                f"{os.path.relpath(conflict, BASE_DIR)}(type={_type_dir_of(conflict)}),"
                                f"无法作为 {page_type} 重复创建"
                            )

                    # 记录真实落点,供后续 DB(WikiFilePage)/log/摄出精确定位
                    vf["file_path"] = rel_path
                    logger.info(
                        f"[{filename}] [Phase 3] staging_page slug={slug}, "
                        f"rel_path={rel_path}, abs_path={fpath}, exists={os.path.exists(fpath)}"
                    )

                    # 归一化 sources 为规范路径 ware/raw/{format}/{filename}。
                    # 同时剔除历史扁平写法 ware/raw/{filename},避免同一来源留下两条记录。
                    sources = _as_value_list(post.metadata.get("sources"))
                    sources = [s for s in sources if s not in (
                        f"raw/{filename}", f"ware/raw/{filename}", canonical_source
                    ) and not s.startswith("ware/raw/sources/")]
                    sources.append(canonical_source)
                    post.metadata["sources"] = sources

                    # 被 HTML 注释包裹的正文块
                    wrapped_content = f"\n<!-- SOURCE_START: {canonical_source} -->\n{post.content.strip()}\n<!-- SOURCE_END: {canonical_source} -->\n"
                    block_re = re.compile(
                        rf"<!-- SOURCE_START: {re.escape(canonical_source)} -->.*?<!-- SOURCE_END: {re.escape(canonical_source)} -->",
                        re.DOTALL,
                    )

                    # 确定 staging 路径(与 fpath 结构对应但在 staging_dir 下)
                    rel_to_base = os.path.relpath(fpath, BASE_DIR)
                    staging_path = os.path.join(staging_dir, rel_to_base)
                    os.makedirs(os.path.dirname(staging_path), exist_ok=True)

                    if os.path.exists(fpath):
                        # 已有文件:先备份,再在 staging 中操作合并结果
                        backup_path = fpath + f".ingest_{file_id[:8]}.bak"
                        shutil.copy2(fpath, backup_path)
                        backup_pairs.append((fpath, backup_path))

                        # 以磁盘原文件为基础,在 staging_path 上做合并写入
                        shutil.copy2(fpath, staging_path)
                        old_post = frontmatter.load(staging_path)

                        # 1. 合并 sources
                        old_sources = _as_value_list(old_post.metadata.get("sources"))
                        if canonical_source not in old_sources:
                            old_sources.append(canonical_source)
                        old_post.metadata["sources"] = old_sources

                        # 2. 统一字段级溯源合并(含 5 结构化字段 + title/tags/related 等)
                        _merge_field_sources(old_post.metadata, post.metadata, canonical_source)

                        # 2.1 日期由系统维护:created 保留首次落盘日期,updated 刷新为本次。
                        # created/updated 在 SOURCE_TRACKED_EXCLUDE 中,不会被上面的合并覆盖。
                        old_post.metadata["created"] = (
                            old_post.metadata.get("created") or ingest_date
                        )
                        old_post.metadata["updated"] = ingest_date

                        # 3. 正文:已存在本源 SOURCE 块则替换(避免重复摄入叠加),否则追加
                        old_body = old_post.content
                        if block_re.search(old_body):
                            old_body = block_re.sub(wrapped_content.strip(), old_body)
                        else:
                            old_body = old_body.strip() + "\n" + wrapped_content
                        old_post.content = old_body

                        save_post_with_formatting(old_post, staging_path)
                        logger.info(
                            f"[{filename}] [Phase 3] staged_merge slug={slug}, "
                            f"rel_path={rel_path}, source={canonical_source}"
                        )
                    else:
                        # 新建:日期由系统维护,覆盖 Writer 可能编造的 created/updated
                        post.metadata["created"] = ingest_date
                        post.metadata["updated"] = ingest_date

                        # 从零初始化 field_sources(覆盖全部受追踪字段)
                        fs = {}
                        for key, val in post.metadata.items():
                            if key in SOURCE_TRACKED_EXCLUDE:
                                continue
                            vals = _as_value_list(val)
                            if not vals:
                                continue
                            fs[key] = {item: [canonical_source] for item in vals}
                        if fs:
                            post.metadata["field_sources"] = fs
                        post.content = wrapped_content.strip()
                        save_post_with_formatting(post, staging_path)
                        logger.info(
                            f"[{filename}] [Phase 3] staged_new slug={slug}, "
                            f"rel_path={rel_path}, source={canonical_source}"
                        )

                    staged_pairs.append((staging_path, fpath))
                    # 记录新落盘的 slug,供后续页面的唯一性预检
                    disk_slug_paths[slug] = os.path.abspath(fpath)

                except ValueError:
                    raise
                except Exception as e:
                    logger.error(
                        f"[{filename}] [Phase 3] 解析或 staging 文件时发生错误: {e}",
                        exc_info=True
                    )
                    raise  # 直接向上抛出,触发下面的 rollback

            # ── 全部 staging 成功 → 原子性移动到目标路径 ──
            logger.info(
                f"[{filename}] [Phase 3] all staging done, committing "
                f"{len(staged_pairs)} file(s) to final paths..."
            )
            for staging_path, final_path in staged_pairs:
                os.makedirs(os.path.dirname(final_path), exist_ok=True)
                shutil.move(staging_path, final_path)

            # ── 提交成功 → 清理备份 ──
            for _, backup_path in backup_pairs:
                if os.path.exists(backup_path):
                    os.remove(backup_path)

            logger.info(f"[{filename}] [Phase 3] 文件原子保存完成,共 {len(staged_pairs)} 个页面。")

        except Exception:
            # ── 回滚:恢复备份文件,确保磁盘与改动前一致 ──
            logger.error(
                f"[{filename}] [Phase 3] 保存过程中发生错误,正在回滚 "
                f"{len(backup_pairs)} 个备份文件...",
                exc_info=True
            )
            for original_path, backup_path in backup_pairs:
                if os.path.exists(backup_path):
                    try:
                        shutil.move(backup_path, original_path)
                        logger.info(f"[{filename}] [Phase 3] rollback_restored path={original_path}")
                    except Exception as rb_err:
                        logger.error(
                            f"[{filename}] [Phase 3] rollback_failed path={original_path}, err={rb_err}"
                        )
            raise
        finally:
            # ── 无论成败,清理临时目录 ──
            if os.path.exists(staging_dir):
                shutil.rmtree(staging_dir, ignore_errors=True)

    # 统计本次生成内容中的 wikilink 总数(供 lint 增量模式使用)
    total_wikilinks = sum(
        len(re.findall(r'\[\[', vf.get('content', '')))
        for vf in valid_files
    )
    pages_text = ", ".join([vf.get('file_path', '') for vf in valid_files])

    logger.info(f"[{filename}] [Phase 3] 正在重建 index.md 并写入 log.md...")  # #14
    # index.md 确定性全量重建(替换历史的「只追加」方式)——按本次目标库的 wiki 目录
    rebuild_index(ctx.wiki_dir)
    logger.info(f"[{filename}] [Phase 3] index_rebuilt wiki_dir={ctx.wiki_dir}")

    date_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    mode_label = "3-phase-chunked" if ctx.is_long_doc else "3-phase"
    log_entry = (
        f"- [{date_str}] 摄入 [[{canonical_source}]]\n"
        f"  - 生成页面: {len(valid_files)} 个({pages_text})\n"
        f"  - wikilink总数: {total_wikilinks}\n"
        f"  - 模式: {mode_label}\n"
    )
    append_wiki_file(f"{ctx.wiki_rel}/log.md", log_entry)
    logger.info(f"[{filename}] [Phase 3] 数据同步完成,摄入流水线整体结束。")  # #14


async def _record_ingest_success(
    ctx: IngestContext,
    valid_files: list[dict],
    start_time: datetime,
    vlm_token_usage: dict,
    extra_details: dict | None = None,
) -> None:
    """任务后处理:写回摄入状态、token 指标与生成页面清单。"""
    file_id, filename = ctx.file_id, ctx.filename
    vlm_total_tokens = int(vlm_token_usage.get("vlm_total_tokens") or 0)

    end_time = datetime.now()
    duration = (end_time - start_time).total_seconds()
    token_usage = current_task_token_usage()
    total_tokens = token_usage["total_tokens"]
    overall_total_tokens = total_tokens + vlm_total_tokens
    # 整份文档摄入(Planner + 全部 Writer,含各自重试)命中缓存的 input token 总量。
    # cached ⊆ input,命中率越高说明共享前缀(技能+契约+原文)被缓存复用得越充分。
    cached_input_tokens = token_usage["cached_input_tokens"]
    cache_hit_rate = (cached_input_tokens / token_usage["input_tokens"]) if token_usage["input_tokens"] else 0.0
    logger.info(
        "[IngestTokenUsage] final_summary file_id=%s name=%s "
        "llm_input_tokens=%s llm_cached_input_tokens=%s llm_cache_hit_rate=%.2f "
        "llm_output_tokens=%s llm_total_tokens=%s "
        "vlm_input_tokens=%s vlm_output_tokens=%s vlm_image_tokens=%s "
        "vlm_total_tokens=%s overall_total_tokens=%s duration_seconds=%s",
        file_id,
        filename,
        token_usage["input_tokens"],
        cached_input_tokens,
        cache_hit_rate,
        token_usage["output_tokens"],
        token_usage["total_tokens"],
        vlm_token_usage.get("vlm_input_tokens") or 0,
        vlm_token_usage.get("vlm_output_tokens") or 0,
        vlm_token_usage.get("vlm_image_tokens") or 0,
        vlm_total_tokens,
        overall_total_tokens,
        round(duration, 2),
    )

    async with AsyncSessionLocal() as session:
        result = await session.execute(select(WikiFile).where(WikiFile.id == file_id))
        db_file_cur = result.scalar_one_or_none()
        if db_file_cur:
            db_file_cur.status = "Indexed"
            db_file_cur.input_tokens = token_usage["input_tokens"]
            db_file_cur.output_tokens = token_usage["output_tokens"]
            db_file_cur.total_tokens = token_usage["total_tokens"]
            # 命中上下文缓存的 input token(⊆ input_tokens),落库便于逐文件观测缓存效果。
            db_file_cur.cached_input_tokens = cached_input_tokens
            # 字数=解析后正文字符数(上传期不再抽取正文,此前该列恒为 0)。
            db_file_cur.word_count = len(ctx.raw_content or "")
            # VLM 解析(PDF/PPT 图片/表格页)消耗的 token;列早已建模但此前从未写入,
            # 导致文件列表「Token 消耗」漏算 VLM。overall = total + vlm 由读取侧合成。
            db_file_cur.vlm_total_tokens = vlm_total_tokens
            # 摄入路线:区分长文分块(3-phase-chunked)与整篇(3-phase),便于排查/统计。
            db_file_cur.ingest_mode = (extra_details or {}).get("mode")
            db_file_cur.ingest_duration = Decimal(str(round(duration, 2)))
            db_file_cur.ingest_time = end_time
            db_file_cur.error_message = None

            # 写入生成的关联页面到数据库
            await session.execute(delete(WikiFilePage).where(WikiFilePage.file_id == file_id))
            pages_list = []
            for vf in valid_files:
                page_path = vf.get('file_path')
                if page_path:
                    pages_list.append(page_path)
                    wiki_file_page = WikiFilePage(
                        file_id=file_id,
                        page_path=page_path
                    )
                    session.add(wiki_file_page)

            log = WikiOperationLog(
                file_id=file_id,
                file_name=filename,
                operation="INGEST_SUCCESS",
                details=json.dumps({
                    "input_tokens": token_usage["input_tokens"],
                    "cached_input_tokens": cached_input_tokens,
                    "cache_hit_rate": round(cache_hit_rate, 4),
                    "output_tokens": token_usage["output_tokens"],
                    "total_tokens": token_usage["total_tokens"],
                    "vlm_input_tokens": vlm_token_usage.get("vlm_input_tokens") or 0,
                    "vlm_output_tokens": vlm_token_usage.get("vlm_output_tokens") or 0,
                    "vlm_image_tokens": vlm_token_usage.get("vlm_image_tokens") or 0,
                    "vlm_total_tokens": vlm_total_tokens,
                    "overall_total_tokens": overall_total_tokens,
                    "duration_seconds": round(duration, 1),
                    "generated_wiki_pages": pages_list,
                    **(extra_details or {}),
                }, ensure_ascii=False)
            )
            session.add(log)
            await session.commit()
            logger.info(
                f"[{filename}] [IngestSuccess] db_commit_done file_id={file_id}, "
                f"status=Indexed, llm_total_tokens={total_tokens}, "
                f"vlm_total_tokens={vlm_total_tokens}, overall_total_tokens={overall_total_tokens}, "
                f"duration_seconds={round(duration, 2)}, "
                f"pages={pages_list}"
            )


async def _build_ingest_context(file_id: str) -> tuple[IngestContext, dict] | None:
    """读取 db_file、抽取正文、装配阶段间不变量。

    返回 (ctx, vlm_token_usage);文件不存在或状态已变则返回 None(调用方跳过本次摄入)。
    """
    async with AsyncSessionLocal() as session:
        result = await session.execute(select(WikiFile).where(WikiFile.id == file_id))
        db_file = result.scalar_one_or_none()
        if not db_file:
            logger.error(f"[Ingest] File ID {file_id} not found in database.")
            return None

        # 双重检查:防止并发情况下的重复摄入
        if db_file.status != "Ingesting":
            logger.warning(f"[Ingest] File {file_id} status is '{db_file.status}', skipped.")
            ingest_cancel_requested.discard(file_id)
            return None

        filename = db_file.name
        file_format = db_file.format
        # 多知识库:解析归属库,决定 raw 取数目录与 wiki 落盘目录(kb_id 空=base/comm)
        kb = await session.get(WikiKbInfo, db_file.kb_id) if db_file.kb_id else None
        kb_raw = kb_raw_dir(kb)
        ctx_wiki_dir = kb_wiki_dir(kb)
        ctx_wiki_rel = kb_wiki_rel(kb)
        # 原始文件真实落盘路径(项目根相对,含 uuid,允许同名)——取数与溯源唯一真相源。
        # 兜底:历史无 raw_path 的文件回落旧布局 <kb_raw>/<fmt>/<name>。
        raw_path = db_file.raw_path or f"{kb_raw_rel(kb)}/{file_format.lower()}/{filename}"
        logger.info(
            f"[Ingest] loaded file_id={file_id}, name={filename}, "
            f"format={file_format}, status={db_file.status}, size={db_file.size}, "
            f"kb_id={db_file.kb_id or 'base'}, wiki_rel={ctx_wiki_rel}, raw_path={raw_path}"
        )

    _raise_if_ingest_cancelled(file_id)
    file_path = os.path.join(BASE_DIR, raw_path)
    # 规范来源 key = 文件真实落盘路径(含 uuid,按库分目录、不撞名)。
    # Phase 2 的 Writer 上下文与 Phase 3 的 sources/field_sources 共用同一个值。
    canonical_source = build_source_ref(raw_path)
    logger.info(f"[Ingest] extracting_raw_content file_id={file_id}, name={filename}, path={file_path}")
    raw_content = await run_in_threadpool(extract_text_from_file, file_path, file_id)
    vlm_token_usage = get_last_extract_stats(file_path)
    logger.info(
        f"[Ingest] extracted_raw_content file_id={file_id}, name={filename}, "
        f"content_length={len(raw_content)}"
    )
    logger.info(
        "[IngestTokenUsage] parse_stage file_id=%s name=%s parse_engine=%s "
        "vlm_page_count=%s vlm_input_tokens=%s vlm_output_tokens=%s "
        "vlm_image_tokens=%s vlm_total_tokens=%s vlm_duration_ms=%s",
        file_id,
        filename,
        vlm_token_usage.get("parse_engine") or "-",
        vlm_token_usage.get("vlm_page_count") or 0,
        vlm_token_usage.get("vlm_input_tokens") or 0,
        vlm_token_usage.get("vlm_output_tokens") or 0,
        vlm_token_usage.get("vlm_image_tokens") or 0,
        int(vlm_token_usage.get("vlm_total_tokens") or 0),
        vlm_token_usage.get("vlm_duration_ms") or 0,
    )
    _raise_if_ingest_cancelled(file_id)

    # 加载摄入专用提示词与唯一 schema contract(静态上下文注入)
    schema_contract = load_ingest_contract()
    # 校验 Writer 输出时跳过系统维护字段(created/updated 由网关落盘阶段写入)。
    # 它们仍是最终页面的必填项,只是不该由 LLM 提供。
    _system_fields = set(schema_contract.system_maintained_fields)
    _skill_prompt = load_skill_prompt("llm-ingest")
    _contract_text = contract_prompt_text()

    # 长文档分流:开关打开且超阈值才走分块流水线(Map→按块认领→补充轮);
    # 开关关闭时一律走原始三阶段整篇摄入(无视阈值)。
    is_long_doc = INGEST_LONG_DOC_CHUNKING_ENABLED and len(raw_content) > INGEST_LONG_DOC_THRESHOLD_CHARS
    chunks: tuple[DocChunk, ...] = ()
    if is_long_doc:
        _log_phase_banner(filename, "解析与切块(长文档分块模式)")
        _chunk_stats: dict = {}
        chunks = tuple(chunk_document(raw_content, file_format, _chunk_stats))
        _fmt = (file_format or "").lower().lstrip(".")
        if _fmt in ("pdf", "ppt", "pptx"):
            _route = "按 ## Page N 页标记切分(页为原子单位)"
        elif _fmt in ("xlsx", "xls"):
            _route = "按 --- Sheet: x --- 切分,超大 Sheet 按行组切并重复表头"
        else:
            _route = "按 Markdown 标题层级切分,小节贪心合并;无标题退化为段落切分"
        _sizes = [len(c.text) for c in chunks] or [0]
        logger.info(
            f"[Ingest] long_doc_chunked file_id={file_id}, name={filename}, "
            f"content_chars={len(raw_content)}, threshold={INGEST_LONG_DOC_THRESHOLD_CHARS}, "
            f"format={_fmt or '-'}, 切分路由={_route}, "
            f"原子数={_chunk_stats.get('atoms')} → 细分后={_chunk_stats.get('atoms_after_subdivide')} "
            f"→ 装箱成块={_chunk_stats.get('chunks')}, chunks_count={len(chunks)}, "
            f"chunk_chars(min/avg/max)={min(_sizes)}/{sum(_sizes) // len(_sizes)}/{max(_sizes)}, "
            f"目标块大小(装箱收口)={CHUNK_TARGET_CHARS}, 硬上限(单原子细分阈值)={CHUNK_MAX_CHARS}, "
            f"原文小节数={_count_md_sections(raw_content)}"
        )
        for c in chunks:
            logger.info(
                f"[Ingest] chunk_detail id={c.chunk_id} chars={len(c.text)} "
                f"range=[{c.char_start},{c.char_end}) sections={_count_md_sections(c.text)} "
                f"heading={c.heading_path or '-'}"
            )

    ctx = IngestContext(
        file_id=file_id,
        filename=filename,
        canonical_source=canonical_source,
        raw_content=raw_content,
        contract=schema_contract,
        contract_text=_contract_text,
        schema_version=current_schema_version(),
        required_fields=[
            f for f in schema_contract.required_fields if f not in _system_fields
        ],
        skill_prompt=_skill_prompt,
        # Planner 与全部 Writer 共用同一份前缀 → 逐字节一致 → 命中自动上下文缓存。
        # 长文档模式全文不进前缀(Planner 看块清单、Writer 看认领块),前缀退化为 skill+契约。
        shared_prefix=build_shared_ingest_prefix(
            skill_prompt=_skill_prompt,
            schema_contract_text=_contract_text,
            raw_content=None if is_long_doc else raw_content,
        ),
        wiki_dir=ctx_wiki_dir,
        wiki_rel=ctx_wiki_rel,
        is_long_doc=is_long_doc,
        chunks=chunks,
    )
    return ctx, vlm_token_usage


async def _run_ingest_agent_impl(file_id: str):
    """核心摄入 Agent 业务逻辑(3-Phase 架构编排)。

    1. 【Phase 1】全局分析原始文档,输出文档级过滤维度与页面切分规划。
    2. 【Phase 2】按规划并发写作各页面,Python 侧强校验 frontmatter,失败则局部重试。
    3. 【Phase 3】原子落盘(staging/backup/rollback)、同 slug 合并、重建 index 与 log。

    本函数只做编排与异常兜底;各阶段实现见 `_phase1_plan` / `_phase2_write` / `_phase3_persist`。
    """
    start_time = datetime.now()
    current_task_tokens.set(new_token_counter())

    built = await _build_ingest_context(file_id)
    if built is None:
        return
    ctx, vlm_token_usage = built
    logger.info(f"[{ctx.filename}] 摄入任务启动")

    try:
        # 长文档分块模式:Phase 0 Map 逐块清单 → Planner 按清单规划并认领块
        map_inventories = await _phase0_map(ctx) if ctx.is_long_doc else None
        plan = await _phase1_plan(ctx, map_inventories=map_inventories)
        valid_files = await _phase2_write(ctx, plan)

        extra_details: dict[str, Any] = {
            "mode": "3-phase-chunked" if ctx.is_long_doc else "3-phase",
        }
        if ctx.is_long_doc:
            # 覆盖已由 Phase 1 的 _check_chunk_coverage 前置保证(漏块会让 Planner 反思重规划,
            # 重试耗尽则硬失败),此处无需再做事后补充轮。
            # Phase 2.6:所有下游页写完后,用它们作素材合成 sources 摘要页
            sources_files = await _phase2_6_synthesize_sources(
                ctx, plan, valid_files, map_inventories
            )
            valid_files.extend(sources_files)
            # 保真度整体指标:wiki 汇总必然有损,量化出来便于后续按数据调分页粒度/写作指令
            fidelity = _compute_fidelity_stats(ctx.chunks, valid_files)
            logger.info(
                "[Fidelity] summary file_id=%s name=%s pages=%s "
                "src_sections=%s out_sections=%s section_ratio=%s "
                "src_chars=%s out_chars=%s char_ratio=%s",
                file_id, ctx.filename, fidelity["pages"],
                fidelity["src_sections"], fidelity["out_sections"], fidelity["section_ratio"],
                fidelity["src_chars"], fidelity["out_chars"], fidelity["char_ratio"],
            )
            extra_details["fidelity"] = fidelity
            trace_path = _write_ingest_trace(ctx, map_inventories, plan, fidelity)
            extra_details.update({
                "chunks_count": len(ctx.chunks),
                # 覆盖由 Phase 1 保证,落库恒为空,仅作审计留痕
                "uncovered_chunks": [],
            })
            if trace_path:
                extra_details["trace_path"] = (
                    os.path.relpath(trace_path, BASE_DIR).replace("\\", "/")
                )

        await _phase3_persist(ctx, valid_files, plan.slug_registry)
        await _record_ingest_success(
            ctx, valid_files, start_time, vlm_token_usage, extra_details=extra_details
        )

        ingest_cancel_requested.discard(file_id)
        _log_phase_banner(ctx.filename, "摄入完成")
        logger.info(f"[{ctx.filename}] [IngestSuccess] completed file_id={file_id}")

    except asyncio.CancelledError:
        logger.info(f"[{ctx.filename}] [IngestCancel] cancelled_error_propagating")
        raise
    except Exception as e:
        logger.error(f"[{ctx.filename}] 摄入流程发生严重错误: {e}", exc_info=True)
        await _mark_ingest_failed(file_id, str(e))