lint.py 44.3 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
import os
import json
import re
import asyncio
from datetime import datetime
import frontmatter
import logging

from src.database.models import WikiOperationLog
from src.database.session import AsyncSessionLocal
from fastapi import APIRouter, Body, BackgroundTasks
from fastapi.responses import StreamingResponse

logger = logging.getLogger(__name__)

from config import WIKI_DIR, BASE_DIR, LINT_MODEL_NAME, SKILLS_DIR
from src.utils.llm_tracker import get_llm_model, token_counter_context
from src.tools.wiki_tools import 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.formatter import DashScopeChatFormatter
from agentscope.tool import Toolkit

router = APIRouter()


def run_lint_phase1(wiki_dir: str, base_dir: str, mode: str = "full", changed_pages: list = None) -> dict:
    """
    Phase 1: 纯 Python 确定性预检。
    完成所有不需要 LLM 语义理解的结构化检查,返回结构化 JSON 供 Phase 2 的 LLM 消费。

    包含:
    - P1-A: 全量页面扫描 + slug 集合构建
    - P1-B: frontmatter 8 字段完整性校验
    - P1-C: schema_version 一致性
    - P1-D: 全量 wikilink 提取
    - P1-E: 断链检测(slug 集合 set difference)
    - P1-F: 孤立页面(反向引用计数 map)
    - P1-G: 过时检测(updated 字段 > 90 天,policy/script/procedure 类型)
    - P1-H: LLM 残留检测(<think> 标签)
    - P1-I: index.md 格式检查
    - P1-J: 截断链接检测
    - 自动修复部分(Python 层直接修复,记录修复日志):
      index.md 格式统一、LLM 残留清除、截断链接补全
    """
    from datetime import date as date_cls

    result = {
        "scan_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "mode": mode,
        "total_pages": 0,
        "slug_map": {},           # slug -> rel_path
        "frontmatter_errors": [],  # [{file, missing_fields, invalid_type, schema_version_mismatch, date_format_errors, extra_errors}]
        "broken_links": [],        # [{source, line, raw, target, pattern}]
        "truncated_links": [],     # [{file, line, content}]
        "orphan_pages": [],        # [{slug, file}]
        "stale_pages": [],         # [{file, updated, days_ago, type}]
        "llm_residuals": [],       # [{file, line}]
        "duplicate_slugs": [],     # [{slug, files}] 跨目录同名 slug(硬错误)
        "similar_slugs": [],       # [{a, b}] 高相似 slug(人工合并兜底)
        "index_violations": [],    # [{line_no, content, issue}]
        "cross_ref_issues": [],    # [{source, target}] A 正文链 B 但 B.related 缺 A(单向引用)
        "brand_violations": [],    # [{file, brand}] brand 字段值不在基线集合
        "script_issues": [],       # [{file, issue}] script 页面 script_type/violation_type 字段合规
        "meta_conflicts": [],      # [{key, slug, value_a, file_a, value_b, file_b}] frontmatter 级矛盾
        "conflict_candidates": [], # [{topic, pages:[{file, claims}]}] 供 Phase2 LLM 判断正文级矛盾
        "ingest_log_summary": {},  # 最近一次 ingest 记录
        "phase1_fixes": [],        # 已自动修复的问题记录
        "wikilink_count": 0,
    }

    VALID_TYPES = {"entity", "product", "concept", "procedure", "script", "policy",
                   "comparison", "troubleshooting", "source", "synthesis",
                   # 兼容 ingest 生成的复数形式
                   "entities", "products", "concepts", "procedures", "scripts",
                   "policies", "comparisons", "sources", "syntheses"}
    REQUIRED_FIELDS = ["schema_version", "type", "title",
                       "series", "brand", "business_category", "sub_business", "role",
                       "related", "sources", "created", "updated"]
    VALID_BUSINESS_CATEGORIES = {"轻改类", "权益类", "二手车类", "未知业务[待确认]"}
    STALE_TYPES = {"policy", "script", "procedure", "policies", "scripts", "procedures"}

    # --- 读取当前 schema_version ---
    # 与 ingest 共用同一份权威 spec(不维护两套):品牌基线与 schema 均取自 llm-ingest 的 references
    refs_dir = os.path.join(SKILLS_DIR, "llm-ingest", "references")
    current_schema_version = None
    schema_path = os.path.join(refs_dir, "schema.md")
    if os.path.exists(schema_path):
        with open(schema_path, "r", encoding="utf-8", errors="replace") as sf:
            for line in sf:
                m = re.search(r'schema_version[:\s]+([\w.]+)', line)
                if m:
                    current_schema_version = m.group(1).strip()
                    break

    # --- 读取品牌基线集合(反引号包裹的 token)---
    brand_baseline = set()
    brand_baseline_path = os.path.join(refs_dir, "brand-baseline.md")
    if os.path.exists(brand_baseline_path):
        with open(brand_baseline_path, "r", encoding="utf-8", errors="replace") as bf:
            for tok in re.findall(r'`([^`]+)`', bf.read()):
                tok = tok.strip()
                # 排除明显非品牌的占位/示例 token
                if tok and not tok.startswith(("^", "ware/")) and ":" not in tok:
                    brand_baseline.add(tok)

    # --- P1-A: 全量页面扫描 ---
    all_md_files = []
    metadata_dir = os.path.join(wiki_dir, "metadata")
    lint_reports_dir = os.path.join(wiki_dir, "lint_reports")
    for root, dirs, files in os.walk(wiki_dir):
        # 跳过 metadata 和 lint_reports 目录
        dirs[:] = [d for d in dirs if os.path.join(root, d) not in (metadata_dir, lint_reports_dir)
                   and not os.path.join(root, d).startswith(metadata_dir)
                   and not os.path.join(root, d).startswith(lint_reports_dir)]
        for f in files:
            if f.endswith(".md") and f not in ("index.md", "log.md"):
                full = os.path.join(root, f)
                if not full.startswith(metadata_dir) and not full.startswith(lint_reports_dir):
                    all_md_files.append(full)

    # 增量模式:只检查指定变更页面
    if mode == "incremental" and changed_pages:
        check_files = []
        for cp in changed_pages:
            fpath = os.path.join(base_dir, cp) if not os.path.isabs(cp) else cp
            if os.path.exists(fpath):
                check_files.append(fpath)
        # slug_map 仍需全量(用于断链验证)
    else:
        check_files = all_md_files

    # 构建全量 slug_map(用于断链验证,始终全量);同时检测跨目录同名 slug
    slug_map = {}
    slug_multimap = {}  # slug -> [rel, ...]
    for fpath in all_md_files:
        slug = os.path.splitext(os.path.basename(fpath))[0]
        rel = os.path.relpath(fpath, base_dir).replace("\\", "/")
        slug_map[slug] = rel
        slug_multimap.setdefault(slug, []).append(rel)
    result["slug_map"] = slug_map
    result["total_pages"] = len(all_md_files)

    # slug 全局唯一性硬错误
    for slug, rels in slug_multimap.items():
        if len(rels) > 1:
            result["duplicate_slugs"].append({"slug": slug, "files": sorted(rels)})

    # 高相似 slug 检测(同 type 目录内做包含关系比较,避免全库 O(n^2))
    by_dir = {}
    for slug, rel in slug_map.items():
        top = rel.split("/")[2] if rel.startswith("ware/wiki/") and len(rel.split("/")) > 3 else "_root"
        by_dir.setdefault(top, []).append(slug)
    for _dir, slugs in by_dir.items():
        slugs_sorted = sorted(set(slugs), key=len)
        for i in range(len(slugs_sorted)):
            for j in range(i + 1, len(slugs_sorted)):
                a, b = slugs_sorted[i], slugs_sorted[j]
                if a != b and a in b:  # 短的是长的子串,疑似同义碎片
                    result["similar_slugs"].append({"a": a, "b": b})

    # --- P1-B & P1-C: frontmatter 校验(仅检查 check_files)---
    for fpath in check_files:
        rel = os.path.relpath(fpath, base_dir).replace("\\", "/")
        errors = {"file": rel, "missing_fields": [], "invalid_type": None,
                  "schema_version_mismatch": False, "date_format_errors": [], "extra_errors": []}
        try:
            post = frontmatter.load(fpath)
            md = post.metadata
            for field in REQUIRED_FIELDS:
                if field not in md:
                    errors["missing_fields"].append(field)
            page_type = md.get("type", "")
            if page_type and page_type not in VALID_TYPES:
                errors["invalid_type"] = page_type
            if current_schema_version and md.get("schema_version") is not None:
                if str(md.get("schema_version")) != str(current_schema_version):
                    errors["schema_version_mismatch"] = True
            for date_field in ["created", "updated"]:
                val = md.get(date_field)
                if val and not re.match(r'^\d{4}-\d{2}-\d{2}$', str(val)):
                    errors["date_format_errors"].append(date_field)
            # 维度合规:business_category 枚举;brand/role 应为列表
            bc = md.get("business_category")
            if bc is not None and str(bc) not in VALID_BUSINESS_CATEGORIES:
                errors["extra_errors"].append(f"business_category 非法值: {bc}")
            for list_dim in ("brand", "role"):
                if list_dim in md and not isinstance(md.get(list_dim), list):
                    errors["extra_errors"].append(f"{list_dim} 应为列表")
        except Exception as e:
            errors["extra_errors"].append(f"frontmatter 解析失败: {e}")
        has_error = (errors["missing_fields"] or errors["invalid_type"] or
                     errors["schema_version_mismatch"] or errors["date_format_errors"] or errors["extra_errors"])
        if has_error:
            result["frontmatter_errors"].append(errors)

    # --- P1-D, P1-E: 全量 wikilink 提取 + 断链检测(全量扫描,不受增量限制)---
    WIKILINK_RE = re.compile(r'\[\[([^\]|#\n]+)(?:[|#][^\]]*)?]]')
    TRUNCATED_RE = re.compile(r'\[\[[^\]]*$')
    all_wikilinks = []  # (source_file_rel, line_no, raw_target, clean_target)
    for fpath in all_md_files:
        rel = os.path.relpath(fpath, base_dir).replace("\\", "/")
        try:
            with open(fpath, "r", encoding="utf-8", errors="replace") as f:
                for line_no, line in enumerate(f, 1):
                    # P1-J: 截断链接
                    if TRUNCATED_RE.search(line):
                        result["truncated_links"].append({"file": rel, "line": line_no, "content": line.strip()})
                    # P1-D: wikilink 提取
                    for m in WIKILINK_RE.finditer(line):
                        raw_target = m.group(1).strip()
                        # 清洗 raw_target
                        clean = raw_target
                        if '/' in clean:
                            # 路径格式:取最后一段,去 .md
                            clean = clean.split('/')[-1]
                        clean = re.sub(r'\.md$', '', clean)
                        all_wikilinks.append((rel, line_no, raw_target, clean))
        except Exception:
            pass

    result["wikilink_count"] = len(all_wikilinks)
    slug_set = set(slug_map.keys())

    for (src_rel, line_no, raw_target, clean_target) in all_wikilinks:
        if clean_target not in slug_set:
            # 判断断链模式
            if '/' in raw_target or raw_target.endswith('.md'):
                pattern = "路径格式"
            elif len([t for (_, _, _, t) in all_wikilinks if t == clean_target]) >= 3:
                pattern = "高频缺失"
            else:
                pattern = "笔误或概念无独立页"
            result["broken_links"].append({
                "source": src_rel, "line": line_no,
                "raw": f"[[{raw_target}]]", "target": clean_target,
                "pattern": pattern
            })

    # --- P1-E 自动修复:指向不存在 slug 的链接转纯文本 + 从 related[] 移除 ---
    # 主要覆盖摄出后遗留的跨文件断链(被删页的反向引用)
    if result["broken_links"]:
        by_source = {}
        for bl in result["broken_links"]:
            by_source.setdefault(bl["source"], []).append(bl)
        for src_rel, bls in by_source.items():
            fpath = os.path.join(base_dir, src_rel)
            if not os.path.exists(fpath):
                continue
            try:
                post = frontmatter.load(fpath)
                body = post.content
                changed = False
                for bl in bls:
                    inner = bl["raw"][2:-2]  # 去掉 [[ ]]
                    pat = re.compile(r'\[\[\s*' + re.escape(inner) + r'\s*(?:\|([^\]]*))?\s*\]\]')
                    new_body, n = pat.subn(lambda m, _t=bl["target"]: (m.group(1) or _t), body)
                    if n:
                        body, changed = new_body, True
                related = post.metadata.get("related")
                if isinstance(related, list):
                    broken_targets = {bl["target"] for bl in bls}
                    new_related = [r for r in related if r not in broken_targets]
                    if len(new_related) != len(related):
                        post.metadata["related"] = new_related
                        changed = True
                if changed:
                    post.content = body
                    with open(fpath, "w", encoding="utf-8") as fw:
                        frontmatter.dump(post, fw)
                    result["phase1_fixes"].append({
                        "file": src_rel,
                        "action": f"修复 {len(bls)} 处断链(转纯文本 / 从 related 移除)"
                    })
            except Exception as fix_e:
                result["phase1_fixes"].append({"file": src_rel, "action": f"断链修复失败: {fix_e}"})

    # --- P1-F: 孤立页面(反向引用计数)---
    ref_count = {}  # slug -> count
    for (_, _, _, clean_target) in all_wikilinks:
        ref_count[clean_target] = ref_count.get(clean_target, 0) + 1
    for slug, rel in slug_map.items():
        if ref_count.get(slug, 0) == 0:
            result["orphan_pages"].append({"slug": slug, "file": rel})

    # ==================================================================================
    # 下沉的确定性语义前置检查(取代 Phase2 LLM 的逐页扫描):
    #   交叉引用 / 品牌枚举 / 话术字段 / frontmatter 级矛盾 / 正文矛盾候选预抽
    # 全部基于全量页面 metadata,单次 frontmatter.load 收集后复用。
    # ==================================================================================
    def _as_list(v):
        if isinstance(v, list):
            return [x for x in v if x not in (None, "")]
        if v in (None, ""):
            return []
        return [v]

    def _clean_to_slug(raw):
        s = str(raw).strip()
        s = re.sub(r'^\[\[|\]\]$', '', s).strip()
        s = s.split('|')[0].split('#')[0]
        if '/' in s:
            s = s.split('/')[-1]
        return re.sub(r'\.md$', '', s).strip()

    page_meta = {}  # slug -> {rel, type, title, brand[], business_category, related(set), script_type, violation_type, content}
    for fpath in all_md_files:
        rel = os.path.relpath(fpath, base_dir).replace("\\", "/")
        slug = os.path.splitext(os.path.basename(fpath))[0]
        try:
            post = frontmatter.load(fpath)
            md = post.metadata
            page_meta[slug] = {
                "rel": rel,
                "type": str(md.get("type", "")),
                "title": str(md.get("title", slug)),
                "brand": _as_list(md.get("brand")),
                "business_category": md.get("business_category"),
                "related": {_clean_to_slug(r) for r in _as_list(md.get("related"))},
                "script_type": md.get("script_type"),
                "violation_type": md.get("violation_type"),
                "content": post.content,
            }
        except Exception:
            page_meta[slug] = {"rel": rel, "type": "", "title": slug, "brand": [],
                               "business_category": None, "related": set(),
                               "script_type": None, "violation_type": None, "content": ""}

    meta_slug_set = set(page_meta.keys())

    # 交叉引用:A 正文链 B,但 B.related 缺 A(单向引用)。每对只报一次。
    _seen_ref_pairs = set()
    for (src_rel, _ln, _raw, clean_target) in all_wikilinks:
        a = os.path.splitext(os.path.basename(src_rel))[0]
        b = clean_target
        if a not in meta_slug_set or b not in meta_slug_set or a == b or (a, b) in _seen_ref_pairs:
            continue
        _seen_ref_pairs.add((a, b))
        if a not in page_meta[b]["related"]:
            result["cross_ref_issues"].append({"source": a, "target": b})

    # 品牌枚举:brand 字段值不在基线集合(跳过 [待审批]/[待确认] 等故意标记)
    for slug, meta in page_meta.items():
        for bv in meta["brand"]:
            bvs = str(bv).strip()
            if not bvs or "待" in bvs or "[" in bvs:
                continue
            if brand_baseline and bvs not in brand_baseline:
                result["brand_violations"].append({"file": meta["rel"], "brand": bvs})

    # 话术字段合规:script 页面 script_type / violation_type(有字段才校验,避免新模板误报)
    for slug, meta in page_meta.items():
        if meta["type"] not in ("script", "scripts"):
            continue
        if meta.get("script_type") is None:
            result["script_issues"].append({"file": meta["rel"], "issue": "script_type 缺失"})
        elif str(meta.get("script_type")) == "违规话术" and not meta.get("violation_type"):
            result["script_issues"].append({"file": meta["rel"], "issue": "违规话术缺 violation_type"})

    # frontmatter 级矛盾:同 title 的多页面 business_category 不一致 / brand 集合不相交
    _by_title = {}
    for slug, meta in page_meta.items():
        t = meta["title"].strip()
        if t:
            _by_title.setdefault(t, []).append((slug, meta))
    for t, group in _by_title.items():
        if len(group) < 2:
            continue
        bcs = {str(m["business_category"]) for _s, m in group if m["business_category"]}
        if len(bcs) > 1:
            ga, gb = group[0], group[1]
            result["meta_conflicts"].append({
                "key": "business_category", "slug": t,
                "value_a": str(ga[1]["business_category"]), "file_a": ga[1]["rel"],
                "value_b": str(gb[1]["business_category"]), "file_b": gb[1]["rel"],
            })

    # 正文矛盾候选预抽:entity/product 页面,按 business_category 聚簇,抽含数值/保修关键词的声明行
    CLAIM_RE = re.compile(r'\d[\d,\.]*\s*(?:元|万元|万|年|公里|万公里|折|%)|覆盖|不含|不包括|包含|三电|保修|质保')
    _cand_groups = {}
    for slug, meta in page_meta.items():
        if meta["type"] not in ("entity", "entities", "product", "products"):
            continue
        claims = []
        for line in meta["content"].splitlines():
            ls = line.strip()
            if ls and CLAIM_RE.search(ls):
                claims.append(ls[:160])
            if len(claims) >= 8:
                break
        if not claims:
            continue
        key = str(meta["business_category"] or "未分类")
        _cand_groups.setdefault(key, []).append({"file": meta["rel"], "claims": claims})
    for topic, pages in _cand_groups.items():
        if len(pages) >= 2:
            result["conflict_candidates"].append({"topic": topic, "pages": pages})

    # --- P1-G: 过时检测 ---
    today = date_cls.today()
    for fpath in all_md_files:
        rel = os.path.relpath(fpath, base_dir).replace("\\", "/")
        try:
            post = frontmatter.load(fpath)
            page_type = str(post.metadata.get("type", ""))
            if page_type not in STALE_TYPES:
                continue
            updated_val = post.metadata.get("updated")
            if not updated_val:
                continue
            updated_str = str(updated_val)
            m = re.match(r'(\d{4})-(\d{2})-(\d{2})', updated_str)
            if not m:
                continue
            updated_date = date_cls(int(m.group(1)), int(m.group(2)), int(m.group(3)))
            days_ago = (today - updated_date).days
            if days_ago > 90:
                result["stale_pages"].append({
                    "file": rel, "updated": updated_str,
                    "days_ago": days_ago, "type": page_type
                })
        except Exception:
            pass

    # --- P1-H: LLM 残留检测 + 自动修复 ---
    THINK_RE = re.compile(r'<(?:think|thinking)>.*?</(?:think|thinking)>', re.DOTALL)
    for fpath in check_files:
        rel = os.path.relpath(fpath, base_dir).replace("\\", "/")
        try:
            with open(fpath, "r", encoding="utf-8", errors="replace") as f:
                raw_content = f.read()
            if '<think>' in raw_content or '<thinking>' in raw_content:
                result["llm_residuals"].append({"file": rel})
                # 自动修复:用 frontmatter 库安全读写,保留 sources/frontmatter 不变
                try:
                    post = frontmatter.loads(raw_content)
                    cleaned_content = THINK_RE.sub('', post.content).strip()
                    post.content = cleaned_content
                    with open(fpath, "w", encoding="utf-8") as fw:
                        frontmatter.dump(post, fw)
                    result["phase1_fixes"].append({
                        "file": rel, "action": "清除LLM残留think标签"
                    })
                except Exception as fix_e:
                    result["phase1_fixes"].append({
                        "file": rel, "action": f"清除LLM残留失败: {fix_e}"
                    })
        except Exception:
            pass

    # --- P1-H2: <br> 标签规范化(表格内→空格,正文→换行)---
    for fpath in check_files:
        rel = os.path.relpath(fpath, base_dir).replace("\\", "/")
        try:
            post = frontmatter.load(fpath)
            if "<br" not in post.content.lower():
                continue
            new_body = normalize_br_tags(post.content)
            if new_body != post.content:
                post.content = new_body
                with open(fpath, "w", encoding="utf-8") as fw:
                    frontmatter.dump(post, fw)
                result["phase1_fixes"].append({"file": rel, "action": "规范化 <br> 标签"})
        except Exception as fix_e:
            result["phase1_fixes"].append({"file": rel, "action": f"<br> 规范化失败: {fix_e}"})

    # --- P1-I: index.md 确定性全量重建(取代历史的逐行格式修复)---
    try:
        indexed = rebuild_index(wiki_dir)
        result["phase1_fixes"].append({
            "file": "ware/wiki/index.md",
            "action": f"确定性全量重建 index.md(按 type 分组,{indexed} 个页面)"
        })
    except Exception as ie:
        result["index_violations"].append({"line_no": 0, "content": "", "issue": f"index.md 重建失败: {ie}"})

    # --- 读取最近一次 ingest 记录(缺陷6:匹配新规范路径 ware/raw/)---
    log_path = os.path.join(wiki_dir, "log.md")
    if os.path.exists(log_path):
        try:
            with open(log_path, "r", encoding="utf-8", errors="replace") as f:
                log_content = f.read()
            # 匹配新格式(ware/raw/ 规范路径)
            new_fmt = re.search(
                r'- \[(.*?)\] 摄入 \[\[ware/raw/([^\]]+)\]\]\n\s+- 生成页面: (\d+) 个(([^)]*))\n\s+- wikilink总数: (\d+)',
                log_content
            )
            # 兼容旧格式
            old_fmt = re.search(
                r'- \[(.*?)\] 摄入 \[\[raw/([^\]]+)\]\],生成了 (\d+) 个页面',
                log_content
            )
            if new_fmt:
                result["ingest_log_summary"] = {
                    "last_ingest_time": new_fmt.group(1),
                    "last_ingest_file": new_fmt.group(2),
                    "pages_generated": [p.strip() for p in new_fmt.group(4).split(',') if p.strip()],
                    "wikilink_count": int(new_fmt.group(5)),
                    "format": "new"
                }
            elif old_fmt:
                result["ingest_log_summary"] = {
                    "last_ingest_time": old_fmt.group(1),
                    "last_ingest_file": old_fmt.group(2),
                    "pages_generated": [],
                    "wikilink_count": -1,
                    "format": "legacy"
                }
        except Exception:
            pass

    return result


@router.post("/wiki/lint")
async def wiki_lint(data: dict = Body(...), background_tasks: BackgroundTasks = None):
    """
    执行知识库全局健康检查 (Lint),2-Phase 架构。

    Phase 1(Python 确定性预检):
      - 由 Python 直接完成断链/frontmatter/孤立页面/过时/LLM残留/index格式等确定性检查
      - 对可自动修复的问题(index格式、think标签)直接修复,记录修复日志
      - 输出结构化 JSON 结果

    Phase 2(LLM 语义层检查):
      - 接收 Phase 1 的 JSON,只做语义层工作(矛盾、品牌一致性、合规性、交叉引用、报告生成)
      - 生成完整 Markdown 报告并保存至 lint_reports/
      - 同时更新 log.md(由 Python 兜底确保写入)

    请求体参数:
      - mode: "full"(全量,默认)或 "incremental"(增量,只检查最近 ingest 的页面)
    """
    mode = data.get("mode", "full")  # "full" or "incremental"
    logger.info(f"Lint 任务启动,模式: {mode}")

    async def event_generator():
        queue = asyncio.Queue()

        # ======================================================================
        # Phase 1: 同步执行 Python 确定性预检(无 LLM 调用,几乎瞬时)
        # ======================================================================
        def push(msg_type: str, content: str):
            m_id = f"p1-{datetime.now().timestamp()}"
            queue.put_nowait({"id": m_id, "type": msg_type, "content": content})

        async def run_phase1_and_phase2():
            # 问题9:Token 追踪
            async with token_counter_context() as get_tokens:
                try:
                    push("thought", f"🔍 **Phase 1 启动**:Python 确定性预检(模式:{mode})...")

                    # 确定增量模式的变更页面
                    changed_pages = None
                    mode_actual = mode
                    if mode == "incremental":
                        # 先做一次简单的 log 扫描,拿到最近 ingest 生成的页面
                        log_path = os.path.join(WIKI_DIR, "log.md")
                        if os.path.exists(log_path):
                            with open(log_path, "r", encoding="utf-8", errors="replace") as lf:
                                log_content = lf.read()
                            new_fmt = re.search(
                                r'- 生成页面: \d+ 个(([^)]*))',
                                log_content
                            )
                            if new_fmt:
                                changed_pages = [p.strip() for p in new_fmt.group(1).split(',') if p.strip()]
                        if not changed_pages:
                            push("thought", "⚠️ 增量模式无法识别变更页面(log.md 为旧格式或无记录),回退到全量检查。")
                            mode_actual = "full"
                        else:
                            mode_actual = "incremental"
                            push("thought", f"📄 增量模式:检查 {len(changed_pages)} 个变更页面")

                    phase1_result = run_lint_phase1(WIKI_DIR, BASE_DIR, mode_actual, changed_pages)
                    logger.info(f"[Lint] Phase 1 完成,扫描 {phase1_result['total_pages']} 个页面,"
                                f"发现 {len(phase1_result['frontmatter_errors'])} 个 frontmatter 错误,"
                                f"{len(phase1_result['broken_links'])} 个断链")

                    # 问题10:Phase 1 结果独立保存为 JSON(确定性兜底)
                    report_date = datetime.now().strftime("%Y%m%d_%H%M%S")
                    phase1_json_path = os.path.join(WIKI_DIR, "lint_reports", f"phase1-{report_date}.json")
                    os.makedirs(os.path.dirname(phase1_json_path), exist_ok=True)
                    try:
                        with open(phase1_json_path, "w", encoding="utf-8") as pjf:
                            json.dump(phase1_result, pjf, ensure_ascii=False, indent=2)
                        logger.info(f"[Lint] Phase 1 结果已保存: {phase1_json_path}")
                    except Exception as pj_err:
                        logger.warning(f"[Lint] Phase 1 JSON 保存失败: {pj_err}")

                    # 推送 Phase 1 进度摘要
                    p1_summary = (
                        f"✅ **Phase 1 完成**:\n"
                        f"- 扫描页面: {phase1_result['total_pages']} 个\n"
                        f"- Frontmatter 错误: {len(phase1_result['frontmatter_errors'])} 个\n"
                        f"- 断链: {len(phase1_result['broken_links'])} 个\n"
                        f"- 重复 slug(硬错误): {len(phase1_result['duplicate_slugs'])} 个\n"
                        f"- 相似 slug(疑似碎片): {len(phase1_result['similar_slugs'])} 个\n"
                        f"- 孤立页面: {len(phase1_result['orphan_pages'])} 个\n"
                        f"- 过时页面: {len(phase1_result['stale_pages'])} 个\n"
                        f"- LLM 残留: {len(phase1_result['llm_residuals'])} 个\n"
                        f"- index.md 违规: {len(phase1_result['index_violations'])} 个\n"
                        f"- 截断链接: {len(phase1_result['truncated_links'])} 个\n"
                        f"- 交叉引用缺失: {len(phase1_result['cross_ref_issues'])} 个\n"
                        f"- 品牌枚举违规: {len(phase1_result['brand_violations'])} 个\n"
                        f"- 话术字段问题: {len(phase1_result['script_issues'])} 个\n"
                        f"- frontmatter 矛盾: {len(phase1_result['meta_conflicts'])} 个\n"
                        f"- 正文矛盾候选簇: {len(phase1_result['conflict_candidates'])} 个\n"
                        f"- Phase 1 自动修复: {len(phase1_result['phase1_fixes'])} 项"
                    )
                    push("thought", p1_summary)

                    if phase1_result['phase1_fixes']:
                        fixes_detail = "\n".join([f"  - [{fx['file']}] {fx['action']}" for fx in phase1_result['phase1_fixes']])
                        push("thought", f"🔧 **Phase 1 已自动修复**:\n{fixes_detail}")

                    push("thought", "🤖 **Phase 2 启动**:LLM 仅做正文级矛盾检测 + 综合报告(确定性检查已在 Phase 1 完成)...")

                    # ======================================================================
                    # Phase 2: LLM 语义层(职责收窄:正文级矛盾检测 + 综合报告)
                    # 确定性检查(交叉引用/品牌/话术/frontmatter 矛盾)已在 Phase 1 完成并随 JSON 注入,
                    # LLM 不再重复扫描,只做它不可替代的两件事。
                    # ======================================================================
                    # 精简工具箱(读候选页 + 写报告/log)
                    toolkit = Toolkit()
                    toolkit.register_tool_function(read_local_file)
                    toolkit.register_tool_function(write_wiki_file)
                    toolkit.register_tool_function(append_wiki_file)

                    # Phase 1 结果转 JSON 注入;slug_map 过大只传统计,避免撑爆 token
                    p1_for_llm = dict(phase1_result)
                    p1_for_llm["slug_map"] = f"(共 {len(phase1_result['slug_map'])} 个页面,slug 集合已在 Phase 1 完成断链/交叉引用检测)"
                    p1_json = json.dumps(p1_for_llm, ensure_ascii=False, indent=2)

                    report_date_str = datetime.now().strftime("%Y%m%d")
                    report_path = f"ware/wiki/lint_reports/lint-report-{report_date_str}.md"

                    sys_prompt = f"""你是 Wiki 知识库健康检查的语义层分析专家。

【背景】Python Phase 1 已完成全部确定性检查(断链、frontmatter、孤立、过时、LLM 残留、index、
重复/相似 slug、交叉引用、品牌枚举、话术字段、frontmatter 级矛盾),结果已通过 JSON 注入你的上下文。
**这些你都不要重复做、不要再扫描全库。** 你只负责两件 LLM 不可替代的事:

【任务 1:正文级矛盾检测】
Phase 1 已在 `conflict_candidates` 中预抽了「同业务大类、含数值/保修关键词」的候选页面簇及其声明行。
请只在这些候选簇内判断是否存在**正文级事实矛盾**,矛盾热点:
  - 价格矛盾(同一产品不同页报不同金额)
  - 保修/覆盖范围矛盾(一页"覆盖三电"、另一页"不含三电")
  - 年限/里程矛盾("8年/15万公里" vs "6年/10万公里")
  - 品牌归属矛盾(同一车型被归到不同品牌)
判断时若候选行信息不足,**最多**用 read_local_file 读取相关候选页确认(不要读候选簇之外的页面)。
发现矛盾仅**报告**,不自动改文件;不确定则标注「疑似,待人工」。

【任务 2:综合生成报告】
把 Phase 1 的结构化结果 + 你的正文矛盾结论,汇总成下面三层结构的 Markdown 报告。
Phase 1 已自动修复的项(phase1_fixes)单列「自动修复记录」,不要重复进高优先级。

【Phase 1 结果(JSON)】
```json
{p1_json}
```

【报告结构】
# Wiki 健康检查报告
> 检查时间: {datetime.now().strftime('%Y-%m-%d %H:%M')} | 检查范围: {phase1_result['total_pages']} 个页面 | 模式: {mode_actual}

## 🔧 自动修复记录(Phase 1 已处理)
(列出 phase1_fixes)

## 🔴 高优先级(需人工处理)
- Frontmatter 不合规(frontmatter_errors)
- 重复 slug(duplicate_slugs,跨目录同名,必须人工合并/改名)
- 品牌枚举违规(brand_violations)
- 话术字段问题(script_issues)
- 正文矛盾(你检测出的 + meta_conflicts)

## 🟡 中优先级(建议修复)
- 交叉引用缺失(cross_ref_issues)
- 相似 slug(similar_slugs)
- 孤立页面(orphan_pages)
- 断链(broken_links,Phase 1 多数已转纯文本,仅列残留供人工建页)

## 🟢 低优先级(可选优化)
- 过时页面(stale_pages)
- 截断链接 / index 违规(如有)

每节用简洁表格或列表,数量为 0 的小节写「无」。

【收尾】
1. 用 write_wiki_file 把完整报告写入 `{report_path}`。
2. 用 append_wiki_file 向 `ware/wiki/log.md` 追加:
```
- [{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Lint 健康检查({mode_actual}模式)
  - 检查范围: {phase1_result['total_pages']} 个页面
  - 🔴 高优先级: X 个 | 🟡 中优先级: Y 个 | 🟢 低优先级: Z 个
  - Phase1 自动修复: {len(phase1_result['phase1_fixes'])} 项
  - 报告: [[lint_reports/lint-report-{report_date_str}.md]]
```
3. 最后把完整报告作为你的最终回答直接输出,不要前言。
"""

                    agent = ReActAgent(
                        name="WikiLinter",
                        model=get_llm_model(LINT_MODEL_NAME),
                        formatter=DashScopeChatFormatter(),
                        sys_prompt=sys_prompt,
                        toolkit=toolkit,
                        max_iters=6,
                    )

                    def message_handler(msg: Msg):
                        if msg.role == "user":
                            return
                        content = msg.content
                        m_id = getattr(msg, "id", None) or f"msg-{datetime.now().timestamp()}"
                        if isinstance(content, str):
                            queue.put_nowait({"id": m_id, "type": "thought", "content": content})
                        elif isinstance(content, list):
                            for i, item in enumerate(content):
                                item_id = f"{m_id}-{i}"
                                if isinstance(item, dict):
                                    if item.get("type") in ["tool_use", "tool_result"]:
                                        queue.put_nowait({
                                            "id": item_id,
                                            "type": "call" if item.get("type") == "tool_use" else "response",
                                            "content": json.dumps(item, ensure_ascii=False),
                                            "name": item.get("name")
                                        })
                                    elif "text" in item:
                                        queue.put_nowait({"id": item_id, "type": "thought", "content": item["text"]})
                                else:
                                    queue.put_nowait({"id": item_id, "type": "thought", "content": str(item)})
                        elif isinstance(content, dict):
                            queue.put_nowait({"id": m_id, "type": "thought", "content": json.dumps(content, ensure_ascii=False)})

                    async def hooked_print(content, *args, **kwargs):
                        if isinstance(content, Msg):
                            msg_content = content.content
                            has_tool = False
                            if isinstance(msg_content, list):
                                for item in msg_content:
                                    if isinstance(item, dict) and item.get("type") in ["tool_use", "tool_result"]:
                                        has_tool = True
                                        break
                            elif isinstance(msg_content, dict) and msg_content.get("type") in ["tool_use", "tool_result"]:
                                has_tool = True

                            if has_tool:
                                logger.info(f"[Agent {content.name} Tool] {json.dumps(msg_content, ensure_ascii=False)}")

                            message_handler(content)

                    agent.print = hooked_print

                    user_msg = Msg("user", "请基于 Phase 1 结果完成语义层检查,生成报告并保存。", role="user")
                    final_res = await agent(user_msg)

                    fc = final_res.content if hasattr(final_res, "content") else str(final_res)
                    if isinstance(fc, list):
                        parts = []
                        for item in fc:
                            if isinstance(item, str):
                                parts.append(item)
                            elif isinstance(item, dict) and "text" in item:
                                parts.append(item["text"])
                        fc = "".join(parts)

                    if isinstance(fc, str) and fc:
                        # 报告整体一次性推送,去掉逐字 sleep 的纯延迟
                        m_id = f"msg-{datetime.now().timestamp()}"
                        queue.put_nowait({"id": m_id, "type": "stream", "content": fc})

                    # 问题10:Python 确定性兜底:如果 LLM 没有写入 log.md,由 Python 写入
                    # 检查 log.md 是否在本次 Lint 后被更新
                    log_md_path = os.path.join(WIKI_DIR, "log.md")
                    log_was_updated = False
                    if os.path.exists(log_md_path):
                        try:
                            with open(log_md_path, "r", encoding="utf-8") as lf:
                                log_current = lf.read()
                            # 粗判断:如果 log 中有本次报告文件名,说明 LLM 写入了
                            if f"lint-report-{report_date_str}.md" in log_current:
                                log_was_updated = True
                        except Exception:
                            pass

                    if not log_was_updated:
                        logger.warning("[Lint] LLM 未写入 log.md,Python 执行兜底写入")
                        date_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                        p1 = phase1_result
                        high_count = (len(p1['frontmatter_errors']) + len(p1['duplicate_slugs'])
                                      + len(p1['brand_violations']) + len(p1['script_issues'])
                                      + len(p1['meta_conflicts']) + len(p1['llm_residuals']))
                        mid_count = (len(p1['cross_ref_issues']) + len(p1['similar_slugs'])
                                     + len(p1['orphan_pages']) + len(p1['broken_links']))
                        low_count = len(p1['stale_pages']) + len(p1['truncated_links'])
                        log_entry = (
                            f"- [{date_str}] Lint 健康检查({mode_actual}模式)\n"
                            f"  - 检查范围: {p1['total_pages']} 个页面\n"
                            f"  - 🔴 高优先级: {high_count} 个\n"
                            f"  - 🟡 中优先级: {mid_count} 个\n"
                            f"  - 🟢 低优先级: {low_count} 个\n"
                            f"  - Phase1 自动修复: {len(p1['phase1_fixes'])} 项\n"
                            f"  - 报告: [[lint_reports/lint-report-{report_date_str}.md]]\n"
                        )
                        try:
                            with open(log_md_path, "a", encoding="utf-8") as lf:
                                lf.write(log_entry)
                        except Exception as log_err:
                            logger.error(f"[Lint] 兜底写入 log.md 也失败: {log_err}")

                    # 缺陷2:将 Lint 操作写入 DB 日志(之前完全缺失)
                    async def write_lint_db_log():
                        try:
                            total_tokens = get_tokens()
                            async with AsyncSessionLocal() as session:
                                log_db = WikiOperationLog(
                                    operation="LINT",
                                    details=json.dumps({
                                        "mode": mode_actual,
                                        "total_pages": phase1_result['total_pages'],
                                        "frontmatter_errors": len(phase1_result['frontmatter_errors']),
                                        "broken_links": len(phase1_result['broken_links']),
                                        "orphan_pages": len(phase1_result['orphan_pages']),
                                        "phase1_fixes": len(phase1_result['phase1_fixes']),
                                        "total_tokens": total_tokens,
                                        "report_path": report_path,
                                    }, ensure_ascii=False)
                                )
                                session.add(log_db)
                                await session.commit()
                            logger.info(f"[Lint] DB 日志写入完成,Token 消耗: {total_tokens}")
                        except Exception as db_err:
                            logger.error(f"[Lint] DB 日志写入失败: {db_err}", exc_info=True)

                    # 使用 asyncio.create_task 写入 DB(在 async 上下文内)
                    asyncio.create_task(write_lint_db_log())

                except Exception as e:
                    queue.put_nowait({"type": "error", "content": str(e)})
                    # 缺陷1:使用 logger 替代 traceback.print_exc()
                    logger.exception(f"[Lint] Lint 流程发生严重错误: {e}")
                finally:
                    queue.put_nowait("[DONE]")

        task = asyncio.create_task(run_phase1_and_phase2())
        task.add_done_callback(
            lambda t: logger.error(f"[Lint] run_phase1_and_phase2 异常退出: {t.exception()}", exc_info=t.exception())
            if not t.cancelled() and t.exception() else None
        )

        while True:
            item = await queue.get()
            if item == "[DONE]":
                yield "data: [DONE]\n\n"
                break
            yield f"data: {json.dumps(item, ensure_ascii=False)}\n\n"

    return StreamingResponse(event_generator(), media_type="text/event-stream")