ingest.py 60.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
import asyncio
import ast
import os
import json
import re
import frontmatter
import yaml
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, BackgroundTasks, 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
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 (
    as_value_list as contract_as_value_list,
    canonicalize_type,
    contract_prompt_text,
    current_schema_version,
    load_ingest_contract,
    merge_field_sources as contract_merge_field_sources,
    recompute_after_source_removal as contract_recompute_after_source_removal,
)

from src.tools.document_parser import extract_text_from_file, get_last_extract_stats
from src.tools.wiki_tools import (
    execute_terminal_command,
    read_local_file,
    write_wiki_file,
    append_wiki_file,
    rebuild_index,
    normalize_br_tags,
)
from agentscope.agent import ReActAgent
from agentscope.message import Msg
from agentscope.tool import Toolkit


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:Planner 锁定的全局过滤维度。
- pages:页面任务列表;每个页面任务至少包含 type、slug、file_path、title、related_links、source_content_range。
"""


def build_writer_system_prompt(
    *,
    skill_prompt: str,
    schema_contract_text: str,
    page_info: dict[str, Any],
    global_dims: dict[str, Any],
    filename: str,
    schema_version: str,
) -> str:
    runtime_context = {
        "page_info": page_info,
        "global_dims": global_dims,
        "source": f"ware/raw/{filename}",
        "schema_version": schema_version,
    }
    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(...), background_tasks: BackgroundTasks = None
):
    """批量开始摄入任务,接受 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
            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}"
            )

        source_ref = f"ware/raw/{name}"

        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}] 摄出 [[ware/raw/{name}]],清理了 {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, background_tasks: BackgroundTasks):
    """根据 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_global_lock = asyncio.Lock()
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 _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):
    import frontmatter
    import yaml
    
    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)


async def run_ingest_agent(file_id: str):
    try:
        _raise_if_ingest_cancelled(file_id)
        logger.info(f"[IngestTask] waiting_for_ingest_global_lock file_id={file_id}")
        async with ingest_global_lock:
            logger.info(f"[IngestTask] acquired_ingest_global_lock 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)
                await _run_ingest_agent_impl(file_id)
                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)

async def _run_ingest_agent_impl(file_id: str):
    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

        # 双重检查:防止并发情况下的重复摄入
        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

        filename = db_file.name
        logger.info(
            f"[Ingest] loaded file_id={file_id}, name={filename}, "
            f"format={db_file.format}, status={db_file.status}, size={db_file.size}"
        )

    """
    核心摄入 Agent 业务逻辑(精简重构版 3-Phase 架构)。
    
    工作流详解:
    1. 【Phase 1: 统筹规划与全局打标】加载所有基线约束文件(静态上下文注入),进行宏观分析,输出全局5维标签和页面结构(含段落分配)。
    2. 【Phase 2: 并发写作与网关自检】依据规划信息和基线示例,使用大批并发 Writer 独立写作;使用代码拦截产出,严格校验 Frontmatter 和清理 <think> 标签,失败则局部重试。
    3. 【Phase 3: 合并保存与同步】执行文件 Upsert(支持防覆盖追加),并同步索引文件。
    """
    start_time = datetime.now()
    current_task_tokens.set(new_token_counter())
    logger.info(f"[{filename if 'filename' in dir() else file_id}] 摄入任务启动")

    try:
        _raise_if_ingest_cancelled(file_id)
        file_path = os.path.join(RAW_DIR, db_file.format.lower(), filename)
        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)
        vlm_total_tokens = int(vlm_token_usage.get("vlm_total_tokens") or 0)
        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,
            vlm_total_tokens,
            vlm_token_usage.get("vlm_duration_ms") or 0,
        )
        _raise_if_ingest_cancelled(file_id)

        # 加载摄入专用提示词与唯一 schema contract(静态上下文注入)
        skill_prompt = load_skill_prompt("llm-ingest")
        schema_contract = load_ingest_contract()
        schema_contract_text = contract_prompt_text()
        schema_version = current_schema_version()
        required_fields = list(schema_contract.required_fields)

        # ==================================================================================
        # 阶段一:统筹规划与全局打标 (Phase 1: Macro Planning & Tagging)
        # ==================================================================================
        print_thinking.set(True)
        logger.info(f"[{filename}] [阶段一] 开始统筹规划与全局打标... 使用模型: {INGEST_MODEL_NAME}")
        
        # 构建现有 slug 注册表(供 Planner 复用已有页、避免同义碎片化与跨目录撞名)
        existing_slugs = {}
        _skip_dirs = {os.path.join(WIKI_DIR, "metadata"), os.path.join(WIKI_DIR, "lint_reports")}
        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 _f.endswith(".md") and _f not in ("index.md", "log.md"):
                    _slug = os.path.splitext(_f)[0]
                    try:
                        _post = frontmatter.load(os.path.join(_root, _f))
                        _title = str(_post.metadata.get("title") or _slug)
                        _ptype = str(_post.metadata.get("type") or "")
                    except Exception:
                        _title, _ptype = _slug, ""
                    existing_slugs[_slug] = (_ptype, _title)
        slug_registry_text = "\n".join(
            f"- [[{s}]] ({t[0]}) — {t[1]}" for s, t in sorted(existing_slugs.items())
        ) or "(当前知识库为空,无既有页面)"

        planner_sys_prompt = build_planner_system_prompt(
            skill_prompt=skill_prompt,
            schema_contract_text=schema_contract_text,
            slug_registry_text=slug_registry_text,
        )
        planner_agent = ReActAgent(
            name="PlannerAgent",
            model=get_llm_model(INGEST_MODEL_NAME, purpose="INGEST"),
            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{raw_content}", role="user")
        planner_tokens_before = current_task_token_usage()
        llm_context_token = current_llm_call_context.set({
            "file_id": file_id,
            "filename": filename,
            "phase": "planner",
        })
        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 "
            "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_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"],
        )
        _raise_if_ingest_cancelled(file_id)
        logger.info(f"[{filename}] [Phase 1] planner_response_received")
        
        # 将大模型可能返回的复杂混合格式统一处理
        plan_content = plan_res.content
        pages = []
        
        # 健壮的 JSON 解析逻辑
        plan_text = ""
        if isinstance(plan_content, list):
            parts = []
            for item in plan_content:
                if isinstance(item, str): 
                    parts.append(item)
                elif isinstance(item, dict):
                    if item.get("type") == "thinking":
                        logger.debug(f"[{filename}] [Phase 1] Planner 思考过程 (partial): {item.get('thinking', '')[:200]}")
                    elif "text" in item:
                        parts.append(item["text"])
            plan_text = "".join(parts)
        elif not isinstance(plan_content, str):
            plan_text = str(plan_content)
        else:
            plan_text = plan_content

        json_match = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", plan_text, re.DOTALL)
        if json_match:
            clean_json = json_match.group(1)
        else:
            start_idx = plan_text.find('{')
            end_idx = plan_text.rfind('}')
            if start_idx != -1 and end_idx != -1:
                clean_json = plan_text[start_idx:end_idx+1]
            else:
                raise ValueError(f"未找到合法的 JSON 格式: {plan_text[:200]}...")

        try:
            plan_data = json.loads(clean_json)
        except json.JSONDecodeError:
            try:
                safe_str = clean_json.replace('true', 'True').replace('false', 'False').replace('null', 'None')
                plan_data = ast.literal_eval(safe_str)
            except Exception as e:
                raise ValueError(f"无法解析 JSON 格式: {clean_json[:200]}..., error: {e}")
                
        pages = plan_data.get("pages", [])
        logger.info(
            f"[{filename}] [Phase 1] plan_parsed pages_count={len(pages)}, "
            f"page_paths={[p.get('file_path') for p in pages if isinstance(p, dict)]}"
        )
        _raise_if_ingest_cancelled(file_id)

        # 解析结构化 5 维(兼容旧 global_tags 数组格式做兜底)
        raw_dims = plan_data.get("global_dims") or {}

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

        def _norm_list(v):
            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]

        if not raw_dims and isinstance(plan_data.get("global_tags"), list):
            gt = plan_data["global_tags"] + ["", "", "", "", ""]
            raw_dims = {"series": gt[1], "brand": gt[0], "business_category": gt[2],
                        "sub_business": gt[3], "role": gt[4]}

        global_dims = {
            "series": _norm_scalar(raw_dims.get("series"), "未知系列[待确认]"),
            "brand": _norm_list(raw_dims.get("brand")) or ["未知品牌[待确认]"],
            "business_category": _norm_scalar(raw_dims.get("business_category"), "未知业务[待确认]"),
            "sub_business": _norm_scalar(raw_dims.get("sub_business"), "未知子业务[待确认]"),
            "role": _norm_list(raw_dims.get("role")) or ["通用"],
        }

        logger.info(f"[{filename}] [Phase 1] 规划完成。全局维度: {global_dims},规划页面数: {len(pages)}")

        # ==================================================================================
        # 阶段二:并发写作与网关自检 (Phase 2: Concurrent Writing & Validation)
        # ==================================================================================
        print_thinking.set(False)
        async def write_single_page_with_retry(page_info, max_retries=4):
            """
            包含 Python 级强校验的并发写作任务。
            """
            writer_sys_prompt = build_writer_system_prompt(
                skill_prompt=skill_prompt,
                schema_contract_text=schema_contract_text,
                page_info=page_info,
                global_dims=global_dims,
                filename=filename,
                schema_version=schema_version,
            )

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

            msg_prompt = f"原始文档内容:\n{raw_content}"
            msg_write = Msg("user", msg_prompt, role="user")

            for attempt in range(max_retries + 1):
                try:
                    llm_context_token = current_llm_call_context.set({
                        "attempt": attempt + 1,
                        "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 = res_write.content
                    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
                                elif "text" in item:
                                    parts.append(item["text"])
                        content = "".join(parts)
                    content = str(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 已在文件顶部导入)
                    try:
                        post = frontmatter.loads(content)
                        md = post.metadata
                        missing = [f for f in required_fields if f not in md]
                        if missing:
                            raise ValueError(f"YAML 缺少必填字段: {missing}")
                        if str(md.get("schema_version")) != schema_version:
                            raise ValueError(f"schema_version 必须是 {schema_version},当前为: {md.get('schema_version')}")
                        canonicalize_type(md.get("type"), schema_contract)
                    except Exception as parse_err:
                        raise ValueError(f"Frontmatter 解析失败: {str(parse_err)}")

                    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:
                        msg_write = Msg("user", f"你上一次的输出未通过规范校验!错误原因:{str(check_err)}。请修复后重新输出完整的 Markdown 页面。", role="user")
                    else:
                        error_msg = f"页面 {page_info.get('file_path')} 连续重试校验失败,摄入中止。"
                        logger.error(f"[{filename}] [Phase 2] {error_msg}")
                        raise ValueError(error_msg)

        # 引入 asyncio.Semaphore(20) 作为并发信号量控制器
        sem = asyncio.Semaphore(20)
        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)

        # ==================================================================================
        # 阶段三:合并保存与同步 (Phase 3: Batch Save & Sync)
        # ==================================================================================
        if valid_files:
            logger.info(f"[{filename}] [Phase 3] 开始批量安全保存...")
            _raise_if_ingest_cancelled(file_id)

            # 构建磁盘上现有 slug -> 路径 映射,用于 slug 全局唯一性预检
            disk_slug_paths = {}
            for _r, _ds, _fs in os.walk(WIKI_DIR):
                _ds[:] = [d for d in _ds if os.path.join(_r, d) not in _skip_dirs]
                for _ff in _fs:
                    if _ff.endswith(".md") and _ff not in ("index.md", "log.md"):
                        disk_slug_paths[os.path.splitext(_ff)[0]] = os.path.abspath(os.path.join(_r, _ff))

            canonical_source = f"ware/raw/{filename}"

            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"

            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"]),
                        schema_contract,
                    )
                    post.metadata["type"] = page_type
                    if page_type == "sources":
                        series_value = _as_value_list(post.metadata.get("series")) or ["未分类"]
                        series = str(series_value[0]).strip()
                        series = re.sub(r'[\\/:*?"<>|]', "_", series) or "未分类"
                        rel_path = f"ware/wiki/sources/{series}/{slug}.md"
                    else:
                        rel_path = f"ware/wiki/{page_type}/{slug}.md"
                    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
                    os.makedirs(os.path.dirname(fpath), exist_ok=True)
                    logger.info(
                        f"[{filename}] [Phase 3] saving_page slug={slug}, "
                        f"rel_path={rel_path}, abs_path={fpath}, exists={os.path.exists(fpath)}"
                    )

                    # 归一化 sources 为规范路径 ware/raw/{filename}
                    sources = _as_value_list(post.metadata.get("sources"))
                    sources = [s for s in sources if s not in (
                        f"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,
                    )

                    if os.path.exists(fpath):
                        old_post = frontmatter.load(fpath)

                        # 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)

                        # 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, fpath)
                        logger.info(
                            f"[{filename}] [Phase 3] merged_existing_page slug={slug}, "
                            f"rel_path={rel_path}, source={canonical_source}"
                        )
                    else:
                        # 新建:从零初始化 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, fpath)
                        logger.info(
                            f"[{filename}] [Phase 3] created_new_page slug={slug}, "
                            f"rel_path={rel_path}, source={canonical_source}"
                        )

                    # 记录新落盘的 slug,供后续页面的唯一性预检
                    disk_slug_paths[slug] = os.path.abspath(fpath)
                except ValueError:
                    raise
                except Exception as e:
                    logger.error(f"[{filename}] [Phase 3] 解析或保存文件时发生错误,退化为直接写入: {e}", exc_info=True)
                    wrapped_raw = f"\n<!-- SOURCE_START: {canonical_source} -->\n{vf['content']}\n<!-- SOURCE_END: {canonical_source} -->\n"
                    os.makedirs(os.path.dirname(fpath), exist_ok=True)
                    if os.path.exists(fpath):
                        with open(fpath, "a", encoding="utf-8") as f_out:
                            f_out.write(wrapped_raw)
                    else:
                        with open(fpath, "w", encoding="utf-8") as f_out:
                            f_out.write(wrapped_raw)

            logger.info(f"[{filename}] [Phase 3] 文件保存完成。")

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

        print(f"[{filename}] [阶段三] 正在重建 index.md 并写入 log.md...")
        # 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}] 摄入 [[raw/{filename}]]\n"
            f"  - 生成页面: {len(valid_files)} 个({pages_list})\n"
            f"  - wikilink总数: {total_wikilinks}\n"
            f"  - 模式: 3-phase\n"
        )
        append_wiki_file("ware/wiki/log.md", log_entry)
        print(f"[{filename}] [阶段三] 数据同步完成,摄入流水线整体结束。")

        # ==================================================================================
        # 任务后处理:元数据与统计指标记录
        # ==================================================================================
        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),
        )

        # 1. 更新数据库状态与指标
        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}"
                )
        ingest_cancel_requested.discard(file_id)
        logger.info(f"[{filename}] [IngestSuccess] completed file_id={file_id}")

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

        # 1. 更新数据库状态为 Failed
        try:
            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 = "Failed"
                    db_file_cur.error_message = str(e)
                    
                    log = WikiOperationLog(
                        file_id=file_id,
                        file_name=filename,
                        operation="INGEST_FAIL",
                        details=json.dumps({"error": str(e)}, ensure_ascii=False)
                    )
                    session.add(log)
                    
                    await session.commit()
        except Exception as db_err:
            logger.error(f"[{file_id}] 更新数据库 Failed 状态时发生错误: {db_err}", exc_info=True)