wiki_tools.py 27.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
import subprocess
import sys
import os
import json
import frontmatter
import re
from pathlib import Path
from agentscope.tool import ToolResponse
from agentscope.message import TextBlock

def execute_terminal_command(command: str) -> ToolResponse:
    """
    在项目根目录下执行 Shell 终端命令。
    支持跨平台,包括 Windows CMD。
    
    参数:
        command (str): 需要执行的 Shell 命令。
        
    返回:
        ToolResponse: 封装了命令执行输出 (stdout/stderr) 的响应对象。
    """
    # 定位到项目的根目录(即当前文件所在目录的上一级的上一级)
    root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
    
    # 简单的安全黑名单机制,拦截高危破坏性命令
    blacklisted = ["rm -rf /", "format c:", "del /f /s /q c:"]
    cmd_lower = command.lower().strip()
    for blocked in blacklisted:
        if blocked in cmd_lower:
            return ToolResponse(
                content=[TextBlock(type="text", text=f"❌ 安全拦截,命令已被禁止执行: {command}")]
            )
            
    try:
        is_win = sys.platform == "win32"
        if is_win:
            # 针对 Windows 系统:强制改变控制台代码页为 65001 (UTF-8),避免中文乱码
            wrapped = f"chcp 65001 >nul 2>&1 && {command}"
            result = subprocess.run(
                wrapped,
                shell=True,
                cwd=root_dir,
                capture_output=True,
                timeout=60,
            )
            # 使用自定义解码函数处理 Windows 控制台输出
            stdout = _decode(result.stdout)
            stderr = _decode(result.stderr)
        else:
            # Unix/Linux/Mac 系统,直接指定 utf-8 编码读取
            result = subprocess.run(
                command,
                shell=True,
                cwd=root_dir,
                capture_output=True,
                text=True,
                timeout=60,
                encoding="utf-8",
                errors="replace",
            )
            stdout = result.stdout
            stderr = result.stderr

        output = stdout
        if stderr:
            output += f"\n[stderr]: {stderr}"
        res_text = output.strip() or "(已完成,无任何输出)"
        
        return ToolResponse(
            content=[TextBlock(type="text", text=res_text)]
        )
    except Exception as e:
        # 捕获执行过程中的系统级异常(例如命令超时)
        return ToolResponse(
            content=[TextBlock(type="text", text=f"❌ 执行发生错误: {str(e)}")]
        )

def _decode(raw: bytes) -> str:
    """
    内部辅助函数:智能解码字节流,主要解决 Windows 下多种编码混杂导致的解码报错问题。
    """
    if not raw: return ""
    # 按照最常见编码的顺序依次尝试解码
    for enc in ["utf-8", "gbk", "latin-1"]:
        try: return raw.decode(enc)
        except: continue
    # 如果全失败,则强制回退到 latin-1 并忽略不可解析的字符
    return raw.decode("latin-1", errors="replace")

def write_wiki_file(file_path: str, content: str) -> ToolResponse:
    """
    将内容直接写入(覆盖)知识库目录中的指定文件。
    
    参数:
        file_path (str): 相对于项目根目录的文件路径 (例如: 'ware/wiki/sources/test.md')。
        content (str): 要写入的 Markdown 内容。
        
    返回:
        ToolResponse: 成功或失败的提示信息。
    """
    root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
    full_path = os.path.abspath(os.path.join(root_dir, file_path))
    
    # 路径穿越检查 (Path Traversal Check),防止恶意修改项目根目录以外的文件
    if not full_path.startswith(root_dir):
        return ToolResponse(
            content=[TextBlock(type="text", text="❌ 拒绝访问: 路径超出了项目根目录的限制")]
        )
        
    try:
        # 自动创建不存在的父级目录
        os.makedirs(os.path.dirname(full_path), exist_ok=True)
        # 写入文件,统一采用 UTF-8 编码
        with open(full_path, "w", encoding="utf-8") as f:
            f.write(content)
        return ToolResponse(
            content=[TextBlock(type="text", text=f"✅ 成功写入文件 {file_path}")]
        )
    except Exception as e:
        return ToolResponse(
            content=[TextBlock(type="text", text=f"❌ 文件写入错误: {str(e)}")]
        )

def append_wiki_file(file_path: str, content: str) -> ToolResponse:
    """
    将内容追加到知识库目录中的指定文件末尾,如果文件不存在则创建。
    
    参数:
        file_path (str): 相对于项目根目录的文件路径 (例如: 'ware/wiki/log.md')。
        content (str): 要追加的文本内容。
        
    返回:
        ToolResponse: 成功或失败的提示信息。
    """
    root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
    full_path = os.path.abspath(os.path.join(root_dir, file_path))
    
    # 路径穿越防护
    if not full_path.startswith(root_dir):
        return ToolResponse(
            content=[TextBlock(type="text", text="❌ 拒绝访问: 路径超出了项目根目录的限制")]
        )
        
    try:
        os.makedirs(os.path.dirname(full_path), exist_ok=True)
        # 以追加模式 'a' 打开文件
        with open(full_path, "a", encoding="utf-8") as f:
            # 确保追加的内容独占一行,不会和之前内容的最后一行粘连在一起
            f.write(content if content.endswith("\n") else content + "\n")
        return ToolResponse(
            content=[TextBlock(type="text", text=f"✅ 成功追加内容至文件 {file_path}")]
        )
    except Exception as e:
        return ToolResponse(
            content=[TextBlock(type="text", text=f"❌ 文件追加错误: {str(e)}")]
        )

def read_local_file(file_path: str, start_line: int = 1, end_line: int = None) -> ToolResponse:
    """
    读取本地文件的内容,支持指定行号范围进行局部读取。
    
    参数:
        file_path (str): 相对于项目根目录的文件路径。
        start_line (int): 起始行号 (1-based index,包含该行)。默认从第 1 行开始。
        end_line (int): 结束行号 (1-based index,包含该行)。如果为 None 则读取到文件末尾。
        
    返回:
        ToolResponse: 封装了所读取文件内容的响应对象。
    """
    root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
    full_path = os.path.abspath(os.path.join(root_dir, file_path))
    
    # 安全拦截:禁止跨目录读取系统文件
    if not full_path.startswith(root_dir):
        return ToolResponse(
            content=[TextBlock(type="text", text="❌ 拒绝访问: 路径超出了项目根目录的限制")]
        )
    
    if not os.path.exists(full_path):
        return ToolResponse(
            content=[TextBlock(type="text", text=f"❌ 找不到文件: {file_path}")]
        )
        
    try:
        # errors="replace" 防止遇到非 UTF-8 字符时崩溃
        with open(full_path, "r", encoding="utf-8", errors="replace") as f:
            lines = f.readlines()
            
            # 将基于 1 的行号转换为基于 0 的数组索引,并防止越界
            start_idx = max(0, start_line - 1)
            end_idx = len(lines) if end_line is None else min(len(lines), end_line)
            
            # 截取所需行数并组合成字符串
            selected_lines = lines[start_idx:end_idx]
            content = "".join(selected_lines)
            
            # 字符数限制安全锁:防止读取过大文件导致大模型上下文被爆破 (OOM / Token超限)
            MAX_CHARS = 30000
            if len(content) > MAX_CHARS:
                content = content[:MAX_CHARS] + f"\n\n...[由于内容过长已截断。总行数: {len(lines)}。当前显示范围: 第 {start_line} 行 - 第 {end_line or len(lines)} 行]"
                
            return ToolResponse(
                content=[TextBlock(type="text", text=content)]
            )
    except Exception as e:
        return ToolResponse(
            content=[TextBlock(type="text", text=f"❌ 读取错误: {str(e)}")]
        )

_BR_RE = re.compile(r"\s*<br\s*/?>\s*", re.IGNORECASE)


def normalize_br_tags(text: str) -> str:
    """规范化 <br>/<br/>/<br /> 标签(表格感知):
    - 表格行(含 `|`):cell 内换行替换为单个空格,保持列结构不被破坏;
    - 普通正文行:<br> 还原为真实换行。
    返回 (是否有改动, 规范化后文本) 由调用方按需判断;此处只返回文本。
    """
    if "<br" not in text.lower():
        return text
    out = []
    for line in text.split("\n"):
        if "|" in line:
            out.append(_BR_RE.sub(" ", line))
        else:
            out.append(_BR_RE.sub("\n", line))
    return "\n".join(out)


def batch_write_wiki_files(files: list[dict], source_ref: str = None) -> ToolResponse:
    """
    批量将多个内容写入知识库目录。
    该方法内置了同名文件的合并(Upsert)机制。如果存在同名文件,会将新内容追加并在 Markdown 的 Frontmatter 元数据中追加来源标记。
    
    参数:
        files (list[dict]): 包含待写入数据的字典列表,每个字典需包含 'file_path' 和 'content' 两个键。
        source_ref (str): 可选的溯源标记,通常为原始文件路径 (例如 'raw/A.md'),用于跟踪这段内容是从哪个原文档提取出来的。
        
    返回:
        ToolResponse: 批量写入的整体成功数量和错误日志的提示信息。
    """
    root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
    successes = []
    errors = []
    
    # 遍历每个提交的写入任务
    for file_obj in files:
        file_path = file_obj.get("file_path", "")
        content = file_obj.get("content", "").strip()
        
        # 参数校验
        if not file_path or not content:
            errors.append(f"数据缺失: 某个对象的 file_path 或 content 为空。")
            continue
            
        full_path = os.path.abspath(os.path.join(root_dir, file_path))
        # 路径穿越防护
        if not full_path.startswith(root_dir):
            errors.append(f"❌ 拒绝访问: {file_path} 路径超出了项目根目录")
            continue
            
        try:
            # 确保父级目录结构存在
            os.makedirs(os.path.dirname(full_path), exist_ok=True)
            
            if source_ref:
                # 安全的更新与合并逻辑 (Upsert Logic)
                new_section = content
                # 若内容中未注明原始依据,则自动补齐一条引用的追溯链接
                if f"原始依据:[[ware/{source_ref}]]" not in new_section:
                    new_section += f"\n\n> 原始依据:[[ware/{source_ref}]]\n"
                    
                if os.path.exists(full_path):
                    # 发现存在同名文件,需要读取后合并,以免覆盖原有积累的知识片段
                    post = frontmatter.load(full_path)
                    
                    # 更新 Markdown 头部的 sources 数组,将新的来源文件记录进去
                    sources = post.metadata.get("sources", [])
                    if isinstance(sources, list):
                        if source_ref not in sources:
                            sources.append(source_ref)
                    else:
                        sources = [sources, source_ref]
                    post.metadata["sources"] = sources
                    
                    # 在旧内容的最下方追加新内容分段
                    old_content = post.content.strip()
                    if old_content:
                        post.content = f"{old_content}\n\n{new_section}"
                    else:
                        post.content = new_section
                        
                    # 将合并后的包含新 Frontmatter 的内容回写
                    with open(full_path, "w", encoding="utf-8") as f:
                        frontmatter.dump(post, f)
                else:
                    # 对于全新文件,构建标准化的 Markdown Frontmatter 元数据头部再写入
                    post = frontmatter.Post(new_section)
                    post.metadata["sources"] = [source_ref]
                    with open(full_path, "w", encoding="utf-8") as f:
                        frontmatter.dump(post, f)
            else:
                # 如果没有提供 source_ref,则回退为“直接全量覆盖”的旧模式
                with open(full_path, "w", encoding="utf-8") as f:
                    f.write(content)
                    
            successes.append(file_path)
        except Exception as e:
            errors.append(f"❌ 写入文件失败 {file_path}: {str(e)}")
            
    # 汇总写入报告并返回给大模型
    res_text = f"✅ 成功写入 {len(successes)} 个文件。\n"
    if successes:
        res_text += f"写入成功列表: {', '.join(successes)}\n"
    if errors:
        res_text += f"发生的错误:\n" + "\n".join(errors)
        
    return ToolResponse(
        content=[TextBlock(type="text", text=res_text.strip())]
    )

def grep_wiki_files(pattern: str, path_prefix: str = "ware/wiki") -> ToolResponse:
    """
    在指定目录下的所有 Markdown 文件中,进行基于正则表达式的全文检索。
    
    参数:
        pattern (str): 要检索的正则表达式模式。
        path_prefix (str): 需要搜索的目录前缀路径(相对于项目根目录),默认范围是 'ware/wiki'。
        
    返回:
        ToolResponse: 检索命中结果,格式为 '相对文件路径:所在行号: 该行内容'。
    """
    root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
    search_dir = os.path.abspath(os.path.join(root_dir, path_prefix))
    
    if not search_dir.startswith(root_dir):
        return ToolResponse(content=[TextBlock(type="text", text="❌ 拒绝访问: 搜索路径超出了项目根目录")])
        
    if not os.path.exists(search_dir):
        return ToolResponse(content=[TextBlock(type="text", text=f"❌ 目录不存在: {path_prefix}")])
        
    try:
        # 预编译正则表达式以提高多次匹配的效率
        regex = re.compile(pattern)
    except Exception as e:
        return ToolResponse(content=[TextBlock(type="text", text=f"❌ 正则表达式编译无效: {str(e)}")])
        
    matches = []
    # 限制最大返回结果条数,防止返回大量匹配内容导致大模型 Token 撑爆
    MAX_MATCHES = 500
    
    try:
        # 递归遍历目录树
        for root, _, files in os.walk(search_dir):
            for file in files:
                # 仅对后缀为 .md 的 Markdown 文件进行检索
                if file.endswith(".md"):
                    file_path = os.path.join(root, file)
                    rel_path = os.path.relpath(file_path, root_dir).replace("\\", "/")
                    try:
                        with open(file_path, "r", encoding="utf-8", errors="replace") as f:
                            # 逐行扫描匹配
                            for i, line in enumerate(f):
                                if regex.search(line):
                                    matches.append(f"{rel_path}:{i+1}: {line.strip()}")
                                    if len(matches) >= MAX_MATCHES:
                                        matches.append("... [匹配结果过多,已截断剩余部分]")
                                        break
                    except Exception:
                        pass
            # 双重打断:当收集到的总匹配数超限时停止目录遍历
            if len(matches) >= MAX_MATCHES:
                break
                
        if not matches:
            return ToolResponse(content=[TextBlock(type="text", text="未找到任何匹配的内容。")])
            
        return ToolResponse(content=[TextBlock(type="text", text="\n".join(matches))])
    except Exception as e:
        return ToolResponse(content=[TextBlock(type="text", text=f"❌ 检索过程发生错误: {str(e)}")])

def glob_wiki_files(pattern: str) -> ToolResponse:
    """
    通过 Glob 模式(通配符机制)列出与模式匹配的所有文件路径。
    例如使用 'ware/wiki/**/*.md' 可列出 wiki 下所有 Markdown 文件。
    
    参数:
        pattern (str): 相对于项目根目录的 Glob 检索规则表达式,支持使用 ** 代表递归多层级匹配。
        
    返回:
        ToolResponse: 匹配到的文件相对路径列表。
    """
    root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
    
    try:
        # 转换为适应操作系统的绝对路径表达式进行底层搜索
        search_pattern = os.path.join(root_dir, pattern.replace("/", os.sep))
        import glob
        
        # 执行匹配查询,开启 recursive=True 以支持 ** 跨目录递归
        matched_paths = glob.glob(search_pattern, recursive=True)
        
        rel_paths = []
        for p in matched_paths:
            # 仅提取普通文件路径(排除文件夹)
            if os.path.isfile(p):
                # 统一转换为 POSIX 风格的以 / 分割的相对路径
                rel_path = os.path.relpath(p, root_dir).replace("\\", "/")
                # 必须经过安全性校验,确保路径没有逃逸出项目根目录
                if os.path.abspath(p).startswith(root_dir):
                    rel_paths.append(rel_path)
                    
        if not rel_paths:
            return ToolResponse(content=[TextBlock(type="text", text="未找到任何符合匹配规则的文件。")])
            
        return ToolResponse(content=[TextBlock(type="text", text="\n".join(rel_paths))])
    except Exception as e:
        return ToolResponse(content=[TextBlock(type="text", text=f"❌ 列出文件时发生错误: {str(e)}")])

def update_wiki_tags(file_path: str, action: str, tags: list) -> ToolResponse:
    """
    修改 Markdown 文件的 YAML frontmatter 中的 tags 字段。
    action: "add" 或 "remove"
    tags: 要添加或移除的标签列表
    """
    root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
    full_path = os.path.abspath(os.path.join(root_dir, file_path))
    
    if not full_path.startswith(root_dir):
        return ToolResponse(content=[TextBlock(type="text", text="❌ 拒绝访问: 路径超出了项目根目录")])
        
    if not os.path.exists(full_path):
        return ToolResponse(content=[TextBlock(type="text", text=f"❌ 文件不存在: {file_path}")])
        
    try:
        post = frontmatter.load(full_path)
        current_tags = post.metadata.get("tags", [])
        if not isinstance(current_tags, list):
            current_tags = [current_tags] if current_tags else []
            
        modified = False
        for tag in tags:
            if action == "add" and tag not in current_tags:
                current_tags.append(tag)
                modified = True
            elif action == "remove" and tag in current_tags:
                current_tags.remove(tag)
                modified = True
                
        if modified:
            post.metadata["tags"] = current_tags
            with open(full_path, "w", encoding="utf-8") as f:
                frontmatter.dump(post, f)
            return ToolResponse(content=[TextBlock(type="text", text=f"✅ 成功更新标签 {file_path}")])
        else:
            return ToolResponse(content=[TextBlock(type="text", text=f"✅ 标签无变化 {file_path}")])
    except Exception as e:
        return ToolResponse(content=[TextBlock(type="text", text=f"❌ 更新标签失败: {str(e)}")])

def add_wiki_warning(file_path: str, warning_text: str) -> ToolResponse:
    """
    在文件正文的最开头(在前端 metadata 之后, SOURCE_START 之前)安全追加 warning 提示框。
    """
    root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
    full_path = os.path.abspath(os.path.join(root_dir, file_path))
    
    if not full_path.startswith(root_dir):
        return ToolResponse(content=[TextBlock(type="text", text="❌ 拒绝访问: 路径超出了项目根目录")])
        
    if not os.path.exists(full_path):
        return ToolResponse(content=[TextBlock(type="text", text=f"❌ 文件不存在: {file_path}")])
        
    try:
        # 剥离 warning_text 里的 wikilink 格式,防止大模型误写导致新断链
        warning_text = re.sub(r'\[\[([^\]|#\n]+)(?:[|#][^\]]*)?\]\]', r'“\1”', warning_text)
        
        post = frontmatter.load(full_path)
        warning_block = f"> [!WARNING]\n> {warning_text}\n\n"
        # 避免重复添加
        if warning_text not in post.content:
            post.content = warning_block + post.content
            with open(full_path, "w", encoding="utf-8") as f:
                frontmatter.dump(post, f)
            return ToolResponse(content=[TextBlock(type="text", text=f"✅ 成功添加警告至 {file_path}")])
        else:
            return ToolResponse(content=[TextBlock(type="text", text=f"✅ 警告已存在 {file_path}")])
    except Exception as e:
        return ToolResponse(content=[TextBlock(type="text", text=f"❌ 添加警告失败: {str(e)}")])

# ==================================================================================
# index.md 确定性重建(供 ingest / egress / lint 复用)
# ==================================================================================

# type -> (展示分组标题, 排序权重)。同时兼容单复数两种写法。
_INDEX_TYPE_GROUPS = [
    ("entities", "实体(entities/)"),
    ("products", "产品(products/)"),
    ("concepts", "概念(concepts/)"),
    ("procedures", "流程(procedures/)"),
    ("scripts", "话术(scripts/)"),
    ("policies", "政策(policies/)"),
    ("comparisons", "对比(comparisons/)"),
    ("troubleshooting", "系统排障(troubleshooting/)"),
    ("sources", "资料摘要(sources/)"),
    ("synthesis", "综合分析(synthesis/)"),
]

# 单数/异体 type 值归一到上面的复数分组键
_INDEX_TYPE_ALIAS = {
    "entity": "entities", "product": "products", "concept": "concepts",
    "procedure": "procedures", "script": "scripts", "policy": "policies",
    "comparison": "comparisons", "source": "sources",
    "syntheses": "synthesis", "synthesi": "synthesis",
}


def _normalize_index_type(raw_type) -> str:
    t = str(raw_type or "").strip().lower()
    return _INDEX_TYPE_ALIAS.get(t, t)


def rebuild_index(wiki_dir: str) -> int:
    """
    扫描 wiki_dir 下所有页面的 frontmatter,按 type 分组(组内按 series/brand/slug 排序),
    确定性地全量重建 index.md。返回纳入索引的页面数。

    供 ingest(Phase3 收尾)、egress(删页后)、lint(Phase1 修复)复用,
    取代历史上「只追加、易损坏」的索引维护方式。
    """
    from datetime import datetime as _dt

    skip_names = {"index.md", "log.md"}
    skip_dirs = {os.path.join(wiki_dir, "metadata"), os.path.join(wiki_dir, "lint_reports")}

    # 收集页面元信息:group_key -> list of (sort_key, slug, title)
    grouped: dict[str, list] = {}
    total = 0
    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 fname in files:
            if not fname.endswith(".md") or fname in skip_names:
                continue
            fpath = os.path.join(root, fname)
            slug = os.path.splitext(fname)[0]
            ptype, title, series, brand = "", slug, "", ""
            try:
                post = frontmatter.load(fpath)
                md = post.metadata
                ptype = _normalize_index_type(md.get("type"))
                title = str(md.get("title") or slug)
                series = str(md.get("series") or "")
                b = md.get("brand")
                brand = (b[0] if isinstance(b, list) and b else str(b or "")) if b else ""
            except Exception:
                ptype = ""
            group_key = ptype if ptype in dict(_INDEX_TYPE_GROUPS) else "_其他"
            sort_key = (series, brand, slug)
            grouped.setdefault(group_key, []).append((sort_key, slug, title))
            total += 1

    # 组装 markdown
    lines = [
        "# 知识索引",
        "",
        "> 本文件由系统在每次摄入/摄出/Lint 后自动全量重建,请勿手动编辑。",
        f"> 最后更新:{_dt.now().strftime('%Y-%m-%d %H:%M:%S')} | 页面总数:{total}",
        "",
    ]
    for group_key, heading in _INDEX_TYPE_GROUPS:
        entries = grouped.get(group_key)
        if not entries:
            continue
        entries.sort(key=lambda x: x[0])
        lines.append(f"## {heading}")
        for _sort_key, slug, title in entries:
            if title and title != slug:
                lines.append(f"- [[{slug}]] — {title}")
            else:
                lines.append(f"- [[{slug}]]")
        lines.append("")

    # 未识别 type 的兜底分组
    others = grouped.get("_其他")
    if others:
        others.sort(key=lambda x: x[0])
        lines.append("## 未分类")
        for _sort_key, slug, title in others:
            lines.append(f"- [[{slug}]] — {title}" if title and title != slug else f"- [[{slug}]]")
        lines.append("")

    index_path = os.path.join(wiki_dir, "index.md")
    with open(index_path, "w", encoding="utf-8") as f:
        f.write("\n".join(lines).rstrip() + "\n")
    return total


def remove_wiki_link(file_path: str, target: str) -> ToolResponse:
    """
    将指定的断链转化为纯文本。例如 [[target]] 变为 target,[[target|别名]] 变为 别名。
    """
    root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
    full_path = os.path.abspath(os.path.join(root_dir, file_path))
    
    if not full_path.startswith(root_dir):
        return ToolResponse(content=[TextBlock(type="text", text="❌ 拒绝访问: 路径超出了项目根目录")])
        
    if not os.path.exists(full_path):
        return ToolResponse(content=[TextBlock(type="text", text=f"❌ 文件不存在: {file_path}")])
        
    try:
        post = frontmatter.load(full_path)
        content = post.content
        
        escaped_target = re.escape(target)
        
        def repl(match):
            alias = match.group(1)
            return alias if alias else target

        pattern = r'\[\[\s*' + escaped_target + r'\s*(?:\|([^\]]*))?\s*\]\]'
        new_content = re.sub(pattern, repl, content)
        
        if new_content != content:
            post.content = new_content
            with open(full_path, "w", encoding="utf-8") as f:
                frontmatter.dump(post, f)
            return ToolResponse(content=[TextBlock(type="text", text=f"✅ 成功将断链转化为纯文本 {file_path}")])
        else:
            return ToolResponse(content=[TextBlock(type="text", text=f"✅ 未发现匹配的断链 {file_path}")])
    except Exception as e:
        return ToolResponse(content=[TextBlock(type="text", text=f"❌ 转化为纯文本失败: {str(e)}")])