ingest.py 77.1 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
import asyncio
import os
import json
import json_repair
import re
import shutil
import tempfile
import frontmatter
import yaml
from dataclasses import dataclass
from datetime import datetime
from decimal import Decimal
import logging
from typing import Any

logger = logging.getLogger(__name__)

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

from src.database.session import AsyncSessionLocal
from src.database.models import WikiFile, WikiFilePage, WikiOperationLog
from config import (
    RAW_DIR, WIKI_DIR, BASE_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 最大重试次数
)
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.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_planner_system_prompt(
    *,
    skill_prompt: str,
    schema_contract_text: str,
    slug_registry_text: str,
) -> str:
    return f"""你是 PlannerAgent,负责执行 llm-ingest skill 的 Phase 1。
请只依据下列权威上下文进行摄入规划;字段、类型、枚举、示例与写作规则均以 skill 和 schema contract 为准。

【llm-ingest Skill】
{skill_prompt}

【Schema Contract】
{schema_contract_text}

【现有知识库页面注册表】
{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 build_writer_system_prompt(
    *,
    skill_prompt: str,
    schema_contract_text: str,
    page_info: dict[str, Any],
    effective_dims: dict[str, Any],
    source_ref: str,
    schema_version: str,
    required_extra: list[str] | None = None,
) -> 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
    return f"""你是 WriterAgent,负责执行 llm-ingest skill 的 Phase 2。
请只依据下列权威上下文、页面任务和用户提供的原始文档生成一个完整 Markdown 页面。

【llm-ingest Skill】
{skill_prompt}

【Schema Contract】
{schema_contract_text}

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

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


@router.post("/wiki/batch_ingest")
async def batch_ingest(data: dict = Body(...)):
    """批量开始摄入任务,接受 ids 列表。
    摄入任务使用全局锁串行执行;摄出仅按文件级锁互斥。
    """
    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")
            elif 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):
    """摄出:仅抹掉该文件自身在 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="文件正在摄入/上传中,无法摄出")

            name = db_file.name
            db_file_format = db_file.format
            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 保持同一构造规则,否则 sources 匹配不上会导致摄出静默跳过
        source_ref = build_source_ref(name, db_file_format)

        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(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 确定性全量重建(删页的索引行自动消失)
        logger.info(f"[Egress] rebuilding_index file_id={file_id}, wiki_dir={WIKI_DIR}")
        rebuild_index(WIKI_DIR)
        logger.info(f"[Egress] rebuilt_index file_id={file_id}")

        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"
                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(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(...)):
    """批量摄出已索引文件,保留原始文件并把状态重置为 Pending。"""
    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
            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)
            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(...)):
    """终止正在运行或排队中的摄入任务,并把文件恢复为待处理。"""
    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
            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):
    """根据 ID 为单个文件启动摄入流程。"""
    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="数据库中未找到该文件")
        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


@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) -> str:
    """按契约 `canonical_types[].directory` 生成确定性落盘相对路径。

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

    纯函数,便于单测。
    """
    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)
    return f"{template.rstrip('/')}/{slug}.md"


def _type_dir_of(rel_or_abs_path: str) -> str:
    """从 wiki 相对/绝对路径取 type 目录(ware/wiki 之后的第一段)。"""
    p = str(rel_or_abs_path).replace("\\", "/")
    if "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 1: Macro Planning & Tagging)
# ==================================================================================
async def _phase1_plan(ctx: IngestContext) -> PlanResult:
    """全局分析原始文档,输出文档级过滤维度与页面切分规划。

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

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

    # 一次遍历构建 slug 注册表(Phase 1 Planner 文本 + Phase 3 冲突检测复用同一份)
    _skip_dirs = {os.path.join(WIKI_DIR, "metadata"), os.path.join(WIKI_DIR, "lint_reports")}
    slug_registry = _build_slug_registry(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)}"
    )

    planner_sys_prompt = build_planner_system_prompt(
        skill_prompt=ctx.skill_prompt,
        schema_contract_text=ctx.contract_text,
        slug_registry_text=slug_registry_text,
    )
    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)

    msg_plan = Msg("user", f"原始文档内容如下:\n{ctx.raw_content}", 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 做结构校验,格式非法时立即抛异常
            raw_global_dims, pages = validate_planner_output(plan_data)

            retry_label = "首次尝试" if planner_attempt == 0 else f"第 {planner_attempt} 次重试后"
            logger.info(
                f"[{filename}] [Phase 1] planner_success ({retry_label}) "
                f"pages_count={len(pages)}, "
                f"page_paths={[p.get('file_path') for p in pages if isinstance(p, dict)]}"
            )
            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 _phase2_write(ctx: IngestContext, plan: PlanResult) -> list[dict]:
    """按规划并发写作各页面,产出经 Python 强校验的 Markdown。

    任一页面连续重试仍不合格即 fail-fast 中止整份摄入:宁可整体失败,
    也不要落一半页面导致知识库处于半成品状态。
    """
    file_id, filename, pages = ctx.file_id, ctx.filename, plan.pages

    print_thinking.set(False)

    async def write_single_page_with_retry(page_info, max_retries=INGEST_WRITER_MAX_RETRIES):
        """包含 Python 级强校验的并发写作任务。"""
        # 本页生效维度 = 文档级 global_dims + 本页声明的 sub_business。
        # 子业务是页面级维度:一份文档常覆盖多个子业务,全局单值会把所有页面打成同一个值。
        effective_dims, dim_warnings = resolve_effective_dims(
            page_info, plan.global_dims, ctx.contract
        )
        for _w in dim_warnings:
            logger.warning(f"[{filename}] [Phase 2] {_w}")

        # Planner 规划的 type 未必是 canonical 写法,先归一才能查到该 type 的专属必填字段。
        # 归一失败说明 Planner 给了非法 type,留给下面的页面级校验报错,此处不阻断。
        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 = []

        writer_sys_prompt = build_writer_system_prompt(
            skill_prompt=ctx.skill_prompt,
            schema_contract_text=ctx.contract_text,
            page_info=page_info,
            effective_dims=effective_dims,
            source_ref=ctx.canonical_source,
            schema_version=ctx.schema_version,
            required_extra=_required_extra,
        )

        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)

        msg_prompt = f"原始文档内容:\n{ctx.raw_content}"
        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": "writer",
                })
                try:
                    res_write = await writer_agent(msg_write)
                finally:
                    current_llm_call_context.reset(llm_context_token)

                # 1. 解析内容
                content = _extract_llm_text(res_write.content)

                # 2. 净化 <think> 标签(Python 级硬删除)
                content = re.sub(r"<(?:think|thinking)>.*?</(?:think|thinking)>", "", content, flags=re.DOTALL)

                # 3. 净化 Markdown 代码块包裹符
                content = content.strip()
                content = re.sub(r"^```[a-zA-Z]*\s*\n", "", content)
                content = re.sub(r"\n```\s*$", "", content)
                content = content.strip()

                # 3.5 规范化 <br> 标签(表格内→空格,正文→换行)
                content = normalize_br_tags(content)

                # 4. Frontmatter 严格检查(frontmatter 已在文件顶部导入)
                # 校验消息会原样回喂给 Writer 让它自我修复,故逐项分开抛,不要笼统包一层。
                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')}"
                    )
                # 归一 type 后才能查该 type 的专属必填字段
                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}成功)")
                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:
                    # #6: 将上次失败的完整输出一并传给 LLM,让它精准修复而非重头生成
                    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)

    # #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_with_retry(page_info)

    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()
    logger.info(
        "[IngestTokenUsage] phase=writer_summary file_id=%s name=%s "
        "pages_planned=%s pages_generated=%s llm_input_tokens=%s "
        "llm_output_tokens=%s llm_total_tokens=%s",
        file_id,
        filename,
        len(pages),
        len(valid_files),
        phase2_token_usage["input_tokens"],
        phase2_token_usage["output_tokens"],
        phase2_token_usage["total_tokens"],
    )
    _raise_if_ingest_cancelled(file_id)
    return valid_files


# ==================================================================================
# 阶段三:合并保存与同步 (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

    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 决定
                    rel_path = _resolve_page_path(
                        page_type, slug, post.metadata.get("series"), ctx.contract
                    )
                    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 确定性全量重建(替换历史的「只追加」方式)
    rebuild_index(WIKI_DIR)
    logger.info(f"[{filename}] [Phase 3] index_rebuilt wiki_dir={WIKI_DIR}")

    date_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    log_entry = (
        f"- [{date_str}] 摄入 [[{canonical_source}]]\n"
        f"  - 生成页面: {len(valid_files)} 个({pages_text})\n"
        f"  - wikilink总数: {total_wikilinks}\n"
        f"  - 模式: 3-phase\n"
    )
    append_wiki_file("ware/wiki/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,
) -> 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
    logger.info(
        "[IngestTokenUsage] final_summary file_id=%s name=%s "
        "llm_input_tokens=%s 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"],
        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"]
            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"],
                    "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
                }, 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
        logger.info(
            f"[Ingest] loaded file_id={file_id}, name={filename}, "
            f"format={file_format}, status={db_file.status}, size={db_file.size}"
        )

    _raise_if_ingest_cancelled(file_id)
    file_path = os.path.join(RAW_DIR, file_format.lower(), filename)
    # 规范来源路径:与 RAW_DIR 实际布局一致,保留格式子目录(ware/raw/pdf/x.pdf)。
    # Phase 2 的 Writer 上下文与 Phase 3 的 sources/field_sources 共用同一个值。
    canonical_source = build_source_ref(filename, file_format)
    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)
    ctx = IngestContext(
        file_id=file_id,
        filename=filename,
        canonical_source=canonical_source,
        raw_content=raw_content,
        contract=schema_contract,
        contract_text=contract_prompt_text(),
        schema_version=current_schema_version(),
        required_fields=[
            f for f in schema_contract.required_fields if f not in _system_fields
        ],
        skill_prompt=load_skill_prompt("llm-ingest"),
    )
    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:
        plan = await _phase1_plan(ctx)
        valid_files = await _phase2_write(ctx, plan)
        await _phase3_persist(ctx, valid_files, plan.slug_registry)
        await _record_ingest_success(ctx, valid_files, start_time, vlm_token_usage)

        ingest_cancel_requested.discard(file_id)
        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))