from __future__ import annotations

import difflib
import base64
import binascii
import codecs
import hashlib
import json
import os
import stat
import threading
import time
import re
from functools import wraps
from dataclasses import dataclass
from pathlib import Path, PurePosixPath
from typing import Any

from ..graph.store import GraphStore
from .index import KeywordIndex, SymbolIndex, FileIndex
from .semantic_index import SemanticIndex
from .git_diff import GitBudgetExceeded, GitDiffReader


_MAX_CONTENT_CURSOR_CHARS = 8192


def _file_handle_fingerprint(file_stat: os.stat_result) -> str:
    """Bind a filesystem cursor to the exact opened file generation."""
    return ":".join(str(int(value)) for value in (
        file_stat.st_dev,
        file_stat.st_ino,
        file_stat.st_size,
        file_stat.st_mtime_ns,
        file_stat.st_ctime_ns,
    ))


def _encode_content_cursor(payload: dict[str, Any]) -> str:
    """Encode a small, versioned continuation token for public responses."""
    raw = json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8")
    return "pb1." + base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")


def _decode_content_cursor(value: str) -> dict[str, Any] | None:
    # Cursors emitted by this module are a few hundred characters at most.
    # Reject oversized untrusted input before base64/UTF-8/JSON decoding can
    # multiply its allocation footprint.
    if (
        not isinstance(value, str)
        or len(value) > _MAX_CONTENT_CURSOR_CHARS
        or not value.startswith("pb1.")
    ):
        return None
    encoded = value[4:]
    try:
        padding = "=" * (-len(encoded) % 4)
        payload = json.loads(
            base64.urlsafe_b64decode(encoded + padding).decode("utf-8")
        )
    except (ValueError, UnicodeError, binascii.Error, json.JSONDecodeError):
        return None
    return payload if isinstance(payload, dict) else None


def _utf8_bounded_prefix(value: str, byte_budget: int) -> str:
    """Return the longest easily bounded UTF-8 prefix within ``byte_budget``.

    At most ``byte_budget`` Python characters are encoded, so a pathological
    single-line snapshot cannot create another unbounded temporary allocation.
    """
    if byte_budget <= 0 or not value:
        return ""
    candidate = value[:byte_budget]
    encoded = candidate.encode("utf-8")
    if len(encoded) <= byte_budget:
        return candidate
    return encoded[:byte_budget].decode("utf-8", errors="ignore")


def _read_locked(method):
    """Keep each public query on one coherent incremental-update boundary."""
    @wraps(method)
    def wrapped(self, *args, **kwargs):
        with self._lock:
            return method(self, *args, **kwargs)
    return wrapped


@dataclass
class FreshnessStatus:
    """Build freshness reported to MCP clients so agents can gauge data staleness."""

    status: str
    last_updated: float

    def to_dict(self) -> dict:
        return {
            "status": self.status,
            "last_updated": self.last_updated,
            "seconds_since_update": round(time.time() - self.last_updated, 1)
            if self.last_updated
            else None,
        }


def _query_aware_preview(text: str, query: str | None, limit: int = 200) -> str | None:
    """Return a bounded excerpt centred on the best literal query match."""
    if not text:
        return None
    if len(text) <= limit:
        return text

    folded = text.casefold()
    candidates: list[str] = []
    if query:
        query = query.strip()
        if query:
            candidates.append(query)
            candidates.extend(
                token for token in re.findall(r"[\w.-]+", query, flags=re.UNICODE)
                if token not in candidates
            )

    match_at = -1
    match_len = 0
    for candidate in candidates:
        pos = folded.find(candidate.casefold())
        if pos >= 0 and (match_at < 0 or pos < match_at):
            match_at = pos
            match_len = len(candidate)

    if match_at < 0:
        start = 0
    else:
        start = max(0, match_at - max(0, (limit - match_len) // 2))
        start = min(start, len(text) - limit)

    prefix = "…" if start > 0 else ""
    suffix = "…" if start + limit < len(text) else ""
    available = limit - len(prefix) - len(suffix)
    return f"{prefix}{text[start:start + available]}{suffix}"


def _content_preview(
    node: dict,
    query: str | None = None,
    store: GraphStore | None = None,
) -> str | None:
    """Short, query-aware content preview for keyword-search results."""
    t = node.get("type")
    if t == "document_chunk":
        text = ""
        doc_id = node.get("doc_id")
        parent = store.get_node(doc_id) if store is not None and doc_id else None
        parent_content = parent.get("content") if parent else None
        if isinstance(parent_content, str):
            try:
                start = max(0, int(node.get("char_start") or 0))
                raw_end = node.get("char_end")
                end = int(raw_end) if raw_end is not None else len(parent_content)
            except (TypeError, ValueError):
                start, end = 0, 0
            text = parent_content[start:max(start, end)]
        if not text:
            text = node.get("content_preview") or ""
        return _query_aware_preview(text, query)
    if t == "document":
        # Document roots are indexed by title/path only; body hits are emitted
        # as bounded chunk nodes. Avoid case-folding an arbitrarily large
        # stored snapshot merely to preview a root-title match.
        text = node.get("summary") or node.get("title") or ""
        return _query_aware_preview(text, query)
    if t == "section":
        text = node.get("content") or ""
        return _query_aware_preview(text, query)
    if t == "function":
        text = node.get("docstring") or node.get("signature") or ""
        return _query_aware_preview(text, query)
    if t == "class":
        text = node.get("docstring") or node.get("name") or ""
        return _query_aware_preview(text, query)
    if t == "concept":
        return _query_aware_preview(node.get("name") or "", query)
    if t == "code_chunk":
        # Fallback chunk: content is stored inline.
        return _query_aware_preview(node.get("content") or "", query)
    return None


class QueryEngine:
    # Content retrieval is intentionally bounded because documents and JSON
    # files can be arbitrarily large.  Callers receive ``truncated=True`` and
    # can request a narrower section/range instead of risking process OOM.
    MAX_CONTENT_BYTES = 1_000_000
    MAX_CONTENT_LINES = 10_000
    MAX_SEARCH_QUERY_CHARS = KeywordIndex.MAX_QUERY_CHARS
    MAX_SEARCH_RESULTS = KeywordIndex.MAX_QUERY_RESULTS
    MAX_SEARCH_SCOPE_CHARS = 4096

    def __init__(
        self,
        store: GraphStore,
        keyword_index: KeywordIndex,
        symbol_index: SymbolIndex,
        file_index: FileIndex,
        semantic_index: SemanticIndex | None = None,
        search_strategy: str = "keyword",
        project_path: str | None = None,
        graph_profile: str = "full",
    ):
        self.store = store
        self.keyword_index = keyword_index
        self.symbol_index = symbol_index
        self.file_index = file_index
        self.semantic_index = semantic_index
        self.semantic_stale = False
        self.search_strategy = search_strategy
        self.graph_profile = graph_profile
        self._project_path = Path(project_path) if project_path else None
        # Freshness tracking: mutated by the incremental updater during rebuilds.
        # RLock is required because public query methods call one another.
        # The incremental updater takes the same lock for the complete batch.
        self._lock = threading.RLock()
        self.build_status = "idle"
        self.last_updated = time.time()

    def get_freshness(self) -> FreshnessStatus:
        return FreshnessStatus(status=self.build_status, last_updated=self.last_updated)

    @_read_locked
    def keyword_search(
        self, query: str, scope: str | None = None, top_k: int = 20,
        test_filter: str = "normal",
    ) -> list[dict]:
        """Search by keywords (BM25), semantics (vector), or hybrid (RRF fusion).

        Args:
            test_filter: "all" (everything), "normal" (non-test only, default),
                "test" (test functions only). For semantic/hybrid the matching
                subset index is searched so top_k is fully utilised.
        """
        if (
            not isinstance(query, str)
            or not query.strip()
            or len(query) > self.MAX_SEARCH_QUERY_CHARS
            or (
                scope is not None
                and (
                    not isinstance(scope, str)
                    or len(scope) > self.MAX_SEARCH_SCOPE_CHARS
                )
            )
            or test_filter not in {"normal", "test", "all"}
        ):
            return []
        try:
            top_k = min(self.MAX_SEARCH_RESULTS, int(top_k))
        except (TypeError, ValueError, OverflowError):
            return []
        if top_k <= 0:
            return []
        raw = self._retrieve(query, top_k, test_filter)
        output = []
        for node_id, score in raw:
            node = self.store.get_node(node_id)
            if not node:
                continue
            is_test = bool(node.get("is_test"))
            if test_filter == "normal" and is_test:
                continue
            if test_filter == "test" and not is_test:
                continue
            file_path = self._file_path(node)
            if scope and scope not in (file_path or "") and scope not in (node.get("module_id") or ""):
                continue
            item = {
                "id": node_id,
                "type": node.get("type"),
                "name": node.get("name") or node.get("title"),
                "class_name": node.get("class_name"),
                "module_path": node.get("module_path"),
                "file": file_path,
                "line": node.get("line_start"),
                "line_end": node.get("line_end"),
                "score": score,
                "content_preview": _content_preview(node, query, self.store),
            }
            if node.get("type") == "document_chunk":
                doc_id = node.get("doc_id")
                parent = self.store.get_node(doc_id) if doc_id else None
                parent_content = parent.get("content") if parent else None
                item.update({
                    "doc_id": doc_id,
                    # Empty, intentionally persisted documents are available too.
                    "content_available": bool(
                        parent
                        and parent.get("content_complete") is True
                        and isinstance(parent_content, str)
                    ),
                })
            elif node.get("type") == "code_chunk":
                # Fallback chunk for a parse-failed code file: content is
                # stored inline, so it is always available.
                item.update({
                    "source_id": node.get("source_id"),
                    "content_available": isinstance(node.get("content"), str),
                })
            elif node.get("type") == "document":
                item["content_available"] = bool(
                    node.get("content_complete") is True
                    and isinstance(node.get("content"), str)
                )
            elif node.get("type") == "section":
                doc_id = node.get("doc_id")
                parent = self.store.get_node(doc_id) if doc_id else None
                item.update({
                    "doc_id": doc_id,
                    "content_available": bool(
                        parent
                        and parent.get("content_complete") is True
                        and isinstance(parent.get("content"), str)
                    ),
                })
            output.append(item)
            if len(output) >= top_k:
                break
        return output

    def _retrieve(
        self, query: str, top_k: int, test_filter: str = "all"
    ) -> list[tuple[str, float]]:
        """Return (doc_id, score) pairs using the configured search strategy.

        Falls back to BM25 when the semantic index is unavailable or empty.
        ``test_filter`` routes semantic search to the matching subset index.
        """
        if top_k <= 0:
            return []
        sem = self.semantic_index
        fetch = max(top_k * 2, 40)
        if not self.semantic_stale and sem is not None and sem.available() and len(sem) > 0:
            target = test_filter if test_filter in ("all", "normal", "test") else "all"
            if self.search_strategy == "semantic":
                return sem.search(query, fetch, target) if hasattr(sem, "index_for") else sem.search(query, fetch)
            if self.search_strategy == "hybrid":
                bm25 = self.keyword_index.search(query, fetch)
                vec = sem.search(query, fetch, target) if hasattr(sem, "index_for") else sem.search(query, fetch)
                return self._rrf(bm25, vec)
        return self.keyword_index.search(query, fetch)

    @staticmethod
    def _rrf(
        bm25_results: list[tuple[str, float]],
        sem_results: list[tuple[str, float]],
        k: int = 60,
    ) -> list[tuple[str, float]]:
        """Reciprocal Rank Fusion: merge two ranked lists by rank only."""
        scores: dict[str, float] = {}
        for rank, (doc_id, _) in enumerate(bm25_results):
            scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + rank + 1)
        for rank, (doc_id, _) in enumerate(sem_results):
            scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + rank + 1)
        return sorted(scores.items(), key=lambda x: -x[1])

    @_read_locked
    def locate_symbol(
        self, symbol_name: str, kind: str | None = None
    ) -> list[dict]:
        """Locate a symbol by name."""
        qualified_parts = [part for part in symbol_name.split("::") if part]
        lookup_name = qualified_parts[-1] if qualified_parts else symbol_name
        qualifier = "::".join(qualified_parts[:-1])
        node_ids = list(self.symbol_index.lookup(lookup_name))
        # Module lookups: also match by crate name (e.g. "ylong_io"), since the
        # module node's `name` is the directory name, not the crate name.
        if kind in (None, "module"):
            seen = set(node_ids)
            for m in self.store.get_nodes_by_type("module"):
                if m.get("crate") == lookup_name and m.get("id") not in seen:
                    node_ids.append(m.get("id"))
                    seen.add(m.get("id"))
        results = []
        for node_id in node_ids:
            node = self.store.get_node(node_id)
            if node:
                if kind and node.get("type") != kind and node.get("kind") != kind:
                    continue
                if qualifier and not self._matches_qualified_symbol(
                    node, symbol_name,
                ):
                    continue
                results.append({
                    "id": node_id,
                    "name": node.get("name") or node.get("title"),
                    "type": node.get("type"),
                    "kind": node.get("kind"),
                    "class_name": node.get("class_name"),
                    "module_path": node.get("module_path"),
                    "file": self._file_path(node),
                    "line_start": node.get("line_start"),
                    "line_end": node.get("line_end"),
                    "signature": node.get("signature"),
                    "visibility": node.get("visibility"),
                    "is_definition": node.get("is_definition"),
                    "byte_start": node.get("byte_start"),
                    "byte_end": node.get("byte_end"),
                    "data_type": node.get("data_type"),
                    "value": node.get("value"),
                    "owner_name": node.get("owner_name"),
                })
        return results

    @staticmethod
    def _matches_qualified_symbol(
        node: dict[str, Any], qualified_name: str,
    ) -> bool:
        """Match Rust/C++-style qualified queries against persisted owners."""
        name = str(node.get("name") or node.get("title") or "")
        module_path = str(node.get("module_path") or "").strip(":")
        owner = str(
            node.get("class_name") or node.get("owner_name") or ""
        ).strip(":")
        parts = [part for part in (module_path, owner, name) if part]
        candidate = "::".join(parts)
        wanted = qualified_name.strip(":")
        return candidate == wanted or candidate.endswith(f"::{wanted}")

    @_read_locked
    def get_symbol_info(
        self, symbol_id: str, include: str = "any"
    ) -> dict | None:
        """Get detailed information about a symbol.

        ``include`` selects which relation lists to attach, as a slash-separated
        string: "callers", "callees", "tests", "declarations", "definitions",
        "referenced_types", "type_references", "accesses", "accessed_by",
        "symbol_references", "ffi_bindings", "ffi_calls", "ffi_callers",
        "overrides", "overridden_by", "template_uses", "template_sources",
        "called_macros", "macro_callers", or
        "any" (default, all). For class/struct/trait targets,
        method-level relations are aggregated with direct type relations.
        """
        node = self.store.get_node(symbol_id)
        if not node:
            node_ids = self.symbol_index.lookup(symbol_id)
            if len(node_ids) == 1:
                symbol_id = node_ids[0]
                node = self.store.get_node(symbol_id)
            elif len(node_ids) > 1:
                return {
                    "ambiguous": True,
                    "query": symbol_id,
                    "candidates": [self._summarize(nid) for nid in node_ids],
                }
        if not node:
            return None

        # This endpoint returns the complete node dictionary below.  Keep it
        # restricted to code symbols so a Document node cannot bypass the
        # bounded, cursor-based get_content API and return an arbitrarily large
        # persisted snapshot in one response.
        if node.get("type") not in {"function", "class", "symbol", "module"}:
            return None

        include_set = (
            None if (not include or include == "any")
            else set(s.strip() for s in include.split("/") if s.strip())
        )

        def wants(key: str) -> bool:
            return include_set is None or key in include_set

        info = dict(node)
        # Function bodies can also be arbitrarily large when index_body is
        # enabled.  Symbol metadata remains useful without duplicating source
        # text that belongs behind get_content's paging boundary.
        info.pop("body", None)
        info.pop("content", None)

        # Class nodes: expand to methods so CALL/TEST edges resolve (they live
        # on methods, not the class node itself).
        if node.get("type") == "class":
            method_ids = self.get_class_methods(symbol_id)
            targets = [symbol_id, *method_ids]
        else:
            targets = [symbol_id]

        def collect(direction: str, edge_type: str, key: str) -> None:
            if not wants(key):
                return
            out: list[dict] = []
            seen: set[str] = set()
            for tid in targets:
                edges = self.store.get_edges(tid, edge_type=edge_type, direction=direction)
                for e in edges:
                    other = e.source if direction == "in" else e.target
                    if other not in seen:
                        seen.add(other)
                        out.append({"id": other, "name": self._get_name(other)})
            info[key] = out

        collect("in", "CALL", "callers")
        collect("out", "CALL", "callees")
        collect("in", "DECLARE", "declarations")
        collect("out", "DECLARE", "definitions")
        collect("out", "TYPE_REF", "referenced_types")
        collect("in", "TYPE_REF", "type_references")
        collect("out", "ACCESS", "accesses")
        collect("in", "ACCESS", "accessed_by")
        collect("out", "REFERENCE", "symbol_references")
        collect("out", "OVERRIDES", "overridden_by")
        collect("in", "OVERRIDES", "overrides")
        collect("out", "TEMPLATE_SPECIALIZATION", "template_uses")
        collect("in", "TEMPLATE_SPECIALIZATION", "template_sources")
        collect("out", "MACRO_CALLS", "called_macros")
        collect("in", "MACRO_CALLS", "macro_callers")
        collect("out", "FFI_BIND", "ffi_bindings")
        collect("out", "FFI_CALL", "ffi_calls")
        collect("in", "FFI_CALL", "ffi_callers")

        # tests: use get_related_tests (infers tests from is_test callers) so
        # results stay consistent with get_context / impact_analysis rather
        # than relying on sparse explicit TEST edges.
        if wants("tests"):
            tests: list[dict] = []
            seen_t: set[str] = set()
            for tid in targets:
                for t in self.get_related_tests(tid):
                    if t.get("id") not in seen_t:
                        seen_t.add(t.get("id"))
                        tests.append({"id": t.get("id"), "name": t.get("name")})
            info["tests"] = tests

        return info

    @_read_locked
    def get_callers(self, function_id: str, depth: int = 1) -> list[dict]:
        """Get functions that call this function."""
        if depth <= 0:
            return []
        ids = self._resolve_ids(function_id, "function")
        if not ids:
            return []

        callers = []
        seen = set()
        visited = set()
        queue = [(i, 0) for i in ids]

        while queue:
            current_id, current_depth = queue.pop(0)
            if current_id in visited or current_depth > depth:
                continue
            visited.add(current_id)

            edges = [
                edge
                for edge_type in ("CALL", "FFI_CALL", "FFI_BIND", "MACRO_CALLS")
                for edge in self.store.get_edges(
                    current_id, edge_type=edge_type, direction="in"
                )
            ]
            for edge in edges:
                if edge.source not in visited and edge.source not in seen:
                    node = self.store.get_node(edge.source)
                    if node:
                        seen.add(edge.source)
                        callers.append({
                            "id": edge.source,
                            "name": node.get("name") or node.get("title"),
                            "file": node.get("path") or node.get("file_id"),
                            "line": node.get("line_start"),
                            "depth": current_depth + 1,
                        })
                        if current_depth + 1 < depth:
                            queue.append((edge.source, current_depth + 1))

        return callers

    @_read_locked
    def get_callees(self, function_id: str, depth: int = 1) -> list[dict]:
        """Get functions that this function calls."""
        if depth <= 0:
            return []
        ids = self._resolve_ids(function_id, "function")
        if not ids:
            return []

        callees = []
        seen = set()
        visited = set()
        queue = [(i, 0) for i in ids]

        while queue:
            current_id, current_depth = queue.pop(0)
            if current_id in visited or current_depth > depth:
                continue
            visited.add(current_id)

            edges = [
                edge
                for edge_type in ("CALL", "FFI_CALL", "FFI_BIND", "MACRO_CALLS")
                for edge in self.store.get_edges(
                    current_id, edge_type=edge_type, direction="out"
                )
            ]
            for edge in edges:
                if edge.target not in visited and edge.target not in seen:
                    node = self.store.get_node(edge.target)
                    if node:
                        seen.add(edge.target)
                        callees.append({
                            "id": edge.target,
                            "name": node.get("name") or node.get("title"),
                            "file": node.get("path") or node.get("file_id"),
                            "line": node.get("line_start"),
                            "depth": current_depth + 1,
                        })
                        if current_depth + 1 < depth:
                            queue.append((edge.target, current_depth + 1))

        return callees

    @_read_locked
    def get_dependencies(
        self, module_id: str, direction: str = "both"
    ) -> dict:
        """Get module dependencies."""
        resolved_id = self._resolve_id(module_id, "module")
        if not resolved_id:
            norm = module_id.replace("::", "/").replace(".", "/")
            for mod in self.store.get_nodes_by_type("module"):
                mp = (mod.get("path") or "").replace("src/", "")
                if mp == norm or mp.endswith("/" + norm):
                    resolved_id = mod.get("id")
                    break
        if not resolved_id:
            return {"upstream": [], "downstream": []}

        if direction not in ("up", "down", "both"):
            return {"upstream": [], "downstream": []}

        # Collect the complete subtree.  The previous implementation stopped
        # after one child level and therefore missed dependencies originating
        # in deeply nested packages.
        module_ids: set[str] = set()
        module_files: set[str] = set()
        queue = [resolved_id]
        while queue:
            current = queue.pop(0)
            if current in module_ids:
                continue
            module_ids.add(current)
            for edge in self.store.get_edges(
                current, edge_type="CONTAIN", direction="out"
            ):
                child = self.store.get_node(edge.target)
                if not child:
                    continue
                if child.get("type") == "module":
                    queue.append(edge.target)
                elif child.get("type") == "file":
                    module_files.add(edge.target)

        def owning_module(node_id: str) -> str | None:
            node = self.store.get_node(node_id)
            if node and node.get("type") == "module":
                return node_id
            for edge in self.store.get_edges(
                node_id, edge_type="CONTAIN", direction="in"
            ):
                container = self.store.get_node(edge.source)
                if container and container.get("type") == "module":
                    return edge.source
            return None

        def entry(module_node_id: str) -> dict | None:
            node = self.store.get_node(module_node_id)
            if not node or node.get("type") != "module":
                return None
            return {
                "id": module_node_id,
                "name": node.get("name"),
                "type": "import",
            }

        upstream: list[dict] = []
        downstream: list[dict] = []
        seen_upstream: set[str] = set()
        seen_downstream: set[str] = set()
        dependency_sources = module_ids | module_files

        if direction in ("down", "both"):
            for source_id in dependency_sources:
                for edge in self.store.get_edges(
                    source_id, edge_type="DEPEND", direction="out"
                ):
                    target_module_id = owning_module(edge.target)
                    if (
                        not target_module_id
                        or target_module_id in module_ids
                        or target_module_id in seen_downstream
                    ):
                        continue
                    item = entry(target_module_id)
                    if item:
                        seen_downstream.add(target_module_id)
                        downstream.append(item)

        if direction in ("up", "both"):
            # Incoming edges may target the root module, any descendant module,
            # or a file in the subtree.  Scan all formats without an early
            # return so one legacy module edge cannot hide file-based edges.
            dependency_targets = module_ids | module_files
            for edge in self.store.get_all_edges():
                if edge.type != "DEPEND" or edge.target not in dependency_targets:
                    continue
                source_module_id = owning_module(edge.source)
                if (
                    not source_module_id
                    or source_module_id in module_ids
                    or source_module_id in seen_upstream
                ):
                    continue
                item = entry(source_module_id)
                if item:
                    seen_upstream.add(source_module_id)
                    upstream.append(item)

        upstream.sort(key=lambda item: (item.get("name") or "", item["id"]))
        downstream.sort(key=lambda item: (item.get("name") or "", item["id"]))
        return {"upstream": upstream, "downstream": downstream}

    @_read_locked
    def get_module_contents(
        self,
        module_id: str,
        exported_only: bool = False,
        feature: str | None = None,
        max_items: int = 500,
    ) -> dict | None:
        """Get contents of a module (classes, functions, submodules).

        When ``exported_only`` is True, only public/exported symbols are
        returned (Rust pub non pub(crate), Python non-underscore, etc.),
        equivalent to the former ``get_module_api``.

        When ``feature`` is set, only symbols available under that feature
        gate are returned: symbols whose ``cfg_conditions`` contain
        ``feature:<name>`` plus symbols with no cfg conditions (always built).
        """
        resolved_id = self._resolve_id(module_id, "module")
        if not resolved_id:
            return None

        module = self.store.get_node(resolved_id)
        if not module:
            return None

        def matches_feature(node: dict) -> bool:
            """True if node is built under the given feature (or always built)."""
            if feature is None:
                return True
            conds = node.get("cfg_conditions") or []
            if not conds:
                return True  # no guard -> always compiled
            return f"feature:{feature}" in conds or feature in conds

        contents = {
            "module": {
                "id": resolved_id,
                "name": module.get("name"),
                "path": module.get("path"),
            },
            "submodules": [],
            "classes": [],
            "functions": [],
        }

        edges = self.store.get_edges(resolved_id, edge_type="CONTAIN", direction="out")
        seen: set[str] = set()
        for edge in edges:
            if edge.target in seen:
                continue
            seen.add(edge.target)
            node = self.store.get_node(edge.target)
            if node:
                node_type = node.get("type")
                if node_type == "class":
                    if exported_only:
                        if not self._is_exported(edge.target):
                            continue
                        # Exclude classes whose file is a private mod
                        # (mod foo; without pub) — they are not reachable
                        # from the crate root.
                        file_id = node.get("file_id") or ""
                        if file_id:
                            fnode = self.store.get_node(file_id)
                            if fnode and fnode.get("is_exported", True) is False:
                                continue
                    if not matches_feature(node):
                        continue
                    # When exported_only, filter the class's method list to
                    # only public methods.  The methods field on ClassNode
                    # contains all method IDs; we must check each one.
                    cls_entry = {
                        "id": edge.target,
                        "name": node.get("name") or node.get("title"),
                        "kind": node.get("kind"),
                        "module_path": node.get("module_path"),
                        "cfg_conditions": node.get("cfg_conditions") or [],
                    }
                    if exported_only:
                        method_count = self._count_exported_methods(node)
                        cls_entry["method_count"] = method_count
                    contents["classes"].append(cls_entry)
                elif node_type == "function":
                    if exported_only:
                        if not self._is_exported(edge.target):
                            continue
                        # Exclude functions in private-mod files.
                        file_id = node.get("file_id") or ""
                        if file_id:
                            fnode = self.store.get_node(file_id)
                            if fnode and fnode.get("is_exported", True) is False:
                                continue
                    if not matches_feature(node):
                        continue
                    contents["functions"].append({
                        "id": edge.target,
                        "name": node.get("name") or node.get("title"),
                        "visibility": node.get("visibility"),
                        "class_name": node.get("class_name"),
                        "module_path": node.get("module_path"),
                        "cfg_conditions": node.get("cfg_conditions") or [],
                    })
                elif node_type == "module":
                    mod_name = node.get("name") or ""
                    mod_path = node.get("path") or ""
                    # Filter out test/benchmark/example directory modules so
                    # they do not appear as public submodules.  This covers
                    # Cargo's benches/, examples/, tests/ directories.
                    if mod_name in ("benches", "examples", "tests", "test"):
                        continue
                    if any(p in ("benches", "examples", "tests", "test")
                           for p in mod_path.replace("\\", "/").split("/")):
                        continue
                    # When exported_only is requested, skip non-exported modules
                    # (e.g. Rust ``mod util;`` without ``pub``).
                    if exported_only and node.get("is_exported", True) is False:
                        continue
                    contents["submodules"].append({
                        "id": edge.target,
                        "name": mod_name,
                        "path": mod_path,
                    })

        # When ``exported_only`` is requested, recurse into descendant public
        # modules to surface the full public API (crate roots typically delegate
        # to ``src/lib.rs`` and ``pub mod`` children).
        if exported_only:
            self._flatten_child_symbols(contents, resolved_id, feature)
            self._resolve_reexports(contents, resolved_id, feature)

        # Bound response size: truncate lists to max_items and set truncated flag.
        total = len(contents["functions"]) + len(contents["classes"]) + len(contents["submodules"])
        if max_items and total > max_items:
            fn_keep = min(len(contents["functions"]), max_items // 3)
            cls_keep = min(len(contents["classes"]), max_items // 3)
            sub_keep = max_items - fn_keep - cls_keep
            sub_keep = min(len(contents["submodules"]), sub_keep)
            contents["functions"] = contents["functions"][:fn_keep]
            contents["classes"] = contents["classes"][:cls_keep]
            contents["submodules"] = contents["submodules"][:sub_keep]
            contents["truncated"] = True
            contents["total_items"] = total
        else:
            contents["truncated"] = False

        return contents

    def _flatten_child_symbols(
        self,
        contents: dict,
        parent_module_id: str,
        feature: str | None,
    ) -> None:
        """Pull public symbols from descendant modules recursively.

        A crate root (e.g. ``ylong_runtime``) typically has no direct symbols —
        its public API lives in ``src/lib.rs`` which is nested under a ``src``
        directory module.  This method recurses through all non-test descendant
        modules to collect exported functions and classes so the caller sees
        the crate's full public surface.
        """

        def matches_feature(node: dict) -> bool:
            if feature is None:
                return True
            conds = node.get("cfg_conditions") or []
            if not conds:
                return True
            return f"feature:{feature}" in conds or feature in conds

        seen_fn: set[str] = {f["id"] for f in contents["functions"]}
        seen_cls: set[str] = {c["id"] for c in contents["classes"]}
        visited: set[str] = set()

        def collect_from_module(mod_id: str) -> None:
            if mod_id in visited:
                return
            visited.add(mod_id)
            for edge in self.store.get_edges(
                mod_id, edge_type="CONTAIN", direction="out"
            ):
                node = self.store.get_node(edge.target)
                if not node:
                    continue
                node_type = node.get("type")
                if node_type == "module":
                    child_name = node.get("name") or ""
                    if child_name in ("benches", "examples", "tests", "test"):
                        continue
                    # Skip non-exported modules (e.g. Rust ``mod util;`` without
                    # ``pub``) so their contents do not leak into the public API.
                    if node.get("is_exported", True) is False:
                        continue
                    collect_from_module(edge.target)
                elif node_type == "function":
                    if not self._is_exported(edge.target):
                        continue
                    if node.get("is_test"):
                        continue
                    # Exclude functions in private-mod files.
                    file_id = node.get("file_id") or ""
                    if file_id:
                        fnode = self.store.get_node(file_id)
                        if fnode and fnode.get("is_exported", True) is False:
                            continue
                    if not matches_feature(node):
                        continue
                    if edge.target in seen_fn:
                        continue
                    seen_fn.add(edge.target)
                    contents["functions"].append({
                        "id": edge.target,
                        "name": node.get("name"),
                        "visibility": node.get("visibility"),
                        "class_name": node.get("class_name"),
                        "module_path": node.get("module_path"),
                        "cfg_conditions": node.get("cfg_conditions") or [],
                    })
                elif node_type == "class":
                    if not self._is_exported(edge.target):
                        continue
                    if "test" in (node.get("cfg_conditions") or []):
                        continue
                    # Exclude classes in private-mod files.
                    file_id = node.get("file_id") or ""
                    if file_id:
                        fnode = self.store.get_node(file_id)
                        if fnode and fnode.get("is_exported", True) is False:
                            continue
                    if not matches_feature(node):
                        continue
                    if edge.target in seen_cls:
                        continue
                    seen_cls.add(edge.target)
                    cls_entry = {
                        "id": edge.target,
                        "name": node.get("name"),
                        "kind": node.get("kind"),
                        "module_path": node.get("module_path"),
                        "method_count": self._count_exported_methods(node),
                        "cfg_conditions": node.get("cfg_conditions") or [],
                    }
                    contents["classes"].append(cls_entry)

        collect_from_module(parent_module_id)

    def _resolve_reexports(
        self,
        contents: dict,
        parent_module_id: str,
        feature: str | None,
    ) -> None:
        """Resolve ``pub use`` re-exports and add them to *contents*.

        Collects re-exported symbol names from all files under this module
        tree, then looks up matching symbols in ALL descendant modules
        (including private ones) since a re-export makes a private module's
        symbol publicly accessible.
        """

        def matches_feature(node: dict) -> bool:
            if feature is None:
                return True
            conds = node.get("cfg_conditions") or []
            if not conds:
                return True
            return f"feature:{feature}" in conds or feature in conds

        seen_fn: set[str] = {f["id"] for f in contents["functions"]}
        seen_cls: set[str] = {c["id"] for c in contents["classes"]}
        reexport_names: set[str] = set()
        visited_rex: set[str] = set()

        def collect_reexports(mod_id: str) -> None:
            if mod_id in visited_rex:
                return
            visited_rex.add(mod_id)
            for edge in self.store.get_edges(
                mod_id, edge_type="CONTAIN", direction="out"
            ):
                node = self.store.get_node(edge.target)
                if not node:
                    continue
                node_type = node.get("type")
                if node_type == "module":
                    child_name = node.get("name") or ""
                    if child_name in ("benches", "examples", "tests", "test"):
                        continue
                    collect_reexports(edge.target)
                elif node_type == "file":
                    rex = node.get("reexports") or []
                    if rex:
                        reexport_names.update(rex)

        collect_reexports(parent_module_id)

        if not reexport_names:
            return

        visited2: set[str] = set()

        def find_reexported(mod_id: str) -> None:
            if mod_id in visited2:
                return
            visited2.add(mod_id)
            for edge in self.store.get_edges(
                mod_id, edge_type="CONTAIN", direction="out"
            ):
                node = self.store.get_node(edge.target)
                if not node:
                    continue
                node_type = node.get("type")
                if node_type == "module":
                    child_name = node.get("name") or ""
                    if child_name in ("benches", "examples", "tests", "test"):
                        continue
                    find_reexported(edge.target)
                elif node_type == "function":
                    name = node.get("name") or ""
                    if name in reexport_names and edge.target not in seen_fn:
                        if node.get("is_test"):
                            continue
                        if not matches_feature(node):
                            continue
                        seen_fn.add(edge.target)
                        contents["functions"].append({
                            "id": edge.target,
                            "name": name,
                            "visibility": node.get("visibility"),
                            "class_name": node.get("class_name"),
                            "module_path": node.get("module_path"),
                            "cfg_conditions": node.get("cfg_conditions") or [],
                        })
                elif node_type == "class":
                    name = node.get("name") or ""
                    if name in reexport_names and edge.target not in seen_cls:
                        if "test" in (node.get("cfg_conditions") or []):
                            continue
                        if not matches_feature(node):
                            continue
                        seen_cls.add(edge.target)
                        contents["classes"].append({
                            "id": edge.target,
                            "name": name,
                            "kind": node.get("kind"),
                            "module_path": node.get("module_path"),
                            "cfg_conditions": node.get("cfg_conditions") or [],
                        })

        find_reexported(parent_module_id)

    @_read_locked
    def get_module_api(
        self, module_id: str, feature: str | None = None
    ) -> dict | None:
        """Get the exported (public API) symbols of a module.

        Thin wrapper over ``get_module_contents(exported_only=True)`` kept for
        backwards compatibility with internal callers. ``feature`` filters to
        symbols available under a given feature gate.
        """
        return self.get_module_contents(module_id, exported_only=True, feature=feature)

    def _is_exported(self, node_id: str) -> bool:
        node = self.store.get_node(node_id)
        return bool(node and node.get("is_exported", True))

    def _count_exported_methods(self, cls_node: dict) -> int:
        """Count how many of a class's methods are exported (public).

        Used by ``get_module_contents(exported_only=True)`` to report the
        number of public methods without leaking private method IDs.
        """
        count = 0
        for mid in cls_node.get("methods") or []:
            m = self.store.get_node(mid)
            if m and m.get("is_exported", True):
                # Also exclude test methods.
                if not m.get("is_test"):
                    count += 1
        return count

    @_read_locked
    def get_file_symbols(self, file_path: str) -> list[dict]:
        """Get all symbols defined in a file."""
        file_info = self.file_index.get(file_path)
        if not file_info:
            return []

        symbols = []
        for node_id in file_info.get("nodes", []):
            node = self.store.get_node(node_id)
            if node:
                symbols.append({
                    "id": node_id,
                    "name": node.get("name") or node.get("title"),
                    "type": node.get("type"),
                    "kind": node.get("kind"),
                    "line": node.get("line_start"),
                    "line_end": node.get("line_end"),
                    "is_definition": node.get("is_definition"),
                })

        return symbols

    @_read_locked
    def get_class_methods(self, class_id: str) -> list[str]:
        """Return method node ids belonging to a class/struct/trait."""
        node = self.store.get_node(class_id)
        if not node:
            resolved = self._resolve_id(class_id, "class")
            if resolved:
                class_id = resolved
                node = self.store.get_node(class_id)
        if not node:
            return []
        methods = node.get("methods") or []
        if methods:
            return list(methods)
        # Try CONTAIN edges first (O(degree) with adjacency list).
        result = []
        for edge in self.store.get_edges(class_id, edge_type="CONTAIN", direction="out"):
            target = self.store.get_node(edge.target)
            if target and target.get("type") == "function":
                result.append(edge.target)
        if result:
            return result
        # Fallback: scan functions by class_id/class_name (O(N), rare path).
        name = node.get("name")
        for fn in self.store.get_nodes_by_type("function"):
            if fn.get("class_id") == class_id or (name and fn.get("class_name") == name):
                result.append(fn.get("id"))
        return result

    @_read_locked
    def get_related_tests(self, symbol_id: str) -> list[dict]:
        """Get tests related to a symbol.

        Uses explicit TEST edges when available, and additionally infers tests
        from callers flagged is_test (test functions that invoke the symbol).
        """
        resolved_id = self._resolve_id(symbol_id)
        if not resolved_id:
            return []

        tests = []
        seen: set[str] = set()

        edges = self.store.get_edges(resolved_id, edge_type="TEST", direction="in")
        for edge in edges:
            if edge.source in seen:
                continue
            node = self.store.get_node(edge.source)
            if node:
                seen.add(edge.source)
                tests.append({
                    "id": edge.source,
                    "name": node.get("name") or node.get("title"),
                    "file": self._file_path(node),
                    "line": node.get("line_start"),
                    "framework": node.get("framework"),
                })

        for c in self.get_callers(resolved_id, depth=1):
            if c["id"] in seen:
                continue
            node = self.store.get_node(c["id"])
            if node and node.get("is_test"):
                seen.add(c["id"])
                tests.append({
                    "id": c["id"],
                    "name": node.get("name") or node.get("title"),
                    "file": self._file_path(node),
                    "line": node.get("line_start"),
                    "framework": node.get("framework"),
                })

        return tests

    @_read_locked
    def get_history(self, target: str, limit: int = 10) -> list[dict]:
        """Get commit history for a symbol or file."""
        if limit <= 0:
            return []
        # 先尝试从 file_index 查找
        file_info = self.file_index.get(target)
        if file_info:
            file_id = file_info.get("file_id")
        else:
            # 尝试解析为符号 ID
            resolved_id = self._resolve_id(target)
            if not resolved_id:
                return []
            
            node = self.store.get_node(resolved_id)
            if not node:
                return []
            
            # 获取文件 ID
            file_id = node.get("file_id") or resolved_id
        
        if not file_id:
            return []
        
        # 查找修改该文件的 commit(MODIFY 边的 source)
        modify_edges = self.store.get_edges(file_id, edge_type="MODIFY", direction="in")
        
        commits = []
        for edge in modify_edges:
            commit_node = self.store.get_node(edge.source)
            if commit_node:
                commits.append({
                    "id": commit_node.get("id"),
                    "sha": commit_node.get("sha"),
                    "author": commit_node.get("author"),
                    "timestamp": commit_node.get("timestamp"),
                    "message": commit_node.get("message"),
                })
        
        # 按时间戳排序(最新的在前)
        commits.sort(key=lambda x: x.get("timestamp", 0), reverse=True)
        
        return commits[:limit]

    @_read_locked
    def get_owner(self, target: str) -> list[dict]:
        """Get ownership information for a symbol or file."""
        # 获取该 target 的提交历史
        history = self.get_history(target, limit=100)
        
        if not history:
            return []
        
        # 统计每个作者的提交次数
        author_stats: dict[str, dict] = {}
        for commit in history:
            author = commit.get("author")
            if not author:
                continue
            
            if author not in author_stats:
                author_stats[author] = {
                    "author": author,
                    "commit_count": 0,
                    "last_commit": 0,
                }
            
            author_stats[author]["commit_count"] += 1
            timestamp = commit.get("timestamp", 0)
            if timestamp > author_stats[author]["last_commit"]:
                author_stats[author]["last_commit"] = timestamp
        
        # 按提交次数排序
        owners = sorted(
            author_stats.values(),
            key=lambda x: x["commit_count"],
            reverse=True
        )
        
        return owners

    @_read_locked
    def get_conventions(self, scope: str | None = None) -> list[dict]:
        """Get project conventions."""
        conventions = self.store.get_nodes_by_type("convention")
        results = []
        for conv in conventions:
            if scope is not None and conv.get("scope") != scope:
                continue
            results.append({
                "category": conv.get("category"),
                "name": conv.get("name"),
                "description": conv.get("description"),
                "source": conv.get("source"),
                "scope": conv.get("scope"),
            })
        return results

    @_read_locked
    def get_doc_links(self, symbol_id: str) -> list[dict]:
        """Get documents/sections that describe or reference a symbol."""
        resolved_id = self._resolve_id(symbol_id)
        if not resolved_id:
            return []

        docs = []
        seen: set[str] = set()
        edges = self.store.get_edges(resolved_id, edge_type="DESCRIBE", direction="in")
        for edge in edges:
            if edge.source in seen:
                continue
            node = self.store.get_node(edge.source)
            if not node or node.get("type") not in ("document", "section"):
                continue
            seen.add(edge.source)
            entry = {
                "id": edge.source,
                "type": node.get("type"),
                "title": node.get("title"),
                "relevance": edge.properties.get("method", "explicit"),
            }
            if node.get("type") == "section":
                doc = self.store.get_node(node.get("doc_id", ""))
                entry["path"] = doc.get("path") if doc else None
                entry["line"] = node.get("line_start")
            else:
                entry["path"] = node.get("path")
            docs.append(entry)

        return docs

    @_read_locked
    def impact_analysis(self, target: str) -> dict:
        """Analyze the impact of changing a symbol or class.

        For class/struct/trait targets, aggregates impact across all methods.
        """
        node = self.store.get_node(target)
        if not node:
            resolved = self._resolve_id(target)
            if resolved:
                target = resolved
                node = self.store.get_node(target)

        if not node:
            return {
                "target": target,
                "error": f"Target not found: {target}",
                "found": False,
            }

        if node and node.get("type") in ("class",):
            method_ids = self.get_class_methods(target)
            symbols = method_ids if method_ids else [target]
        else:
            symbols = [target]

        callers: list[dict] = []
        seen: set[str] = set()
        for sym in symbols:
            for c in self.get_callers(sym, depth=2):
                if c["id"] not in seen:
                    seen.add(c["id"])
                    callers.append(c)

        tests: list[dict] = []
        seen_t: set[str] = set()
        for sym in symbols:
            for t in self.get_related_tests(sym):
                if t["id"] not in seen_t:
                    seen_t.add(t["id"])
                    tests.append(t)

        docs: list[dict] = []
        seen_d: set[str] = set()
        for sym in symbols:
            for d in self.get_doc_links(sym):
                did = d.get("id")
                if did not in seen_d:
                    seen_d.add(did)
                    docs.append(d)
        for d in self.get_doc_links(target):
            did = d.get("id")
            if did not in seen_d:
                seen_d.add(did)
                docs.append(d)

        risk_score = 0
        risk_reasons: list[str] = []
        if len(callers) > 5:
            risk_score += 3
            risk_reasons.append(f"High number of callers ({len(callers)})")
        elif len(callers) > 0:
            risk_score += 1
            risk_reasons.append(f"{len(callers)} caller(s)")
        if len(tests) > 0:
            risk_reasons.append(f"{len(tests)} related test(s)")
        if len(docs) > 0:
            risk_reasons.append(f"Referenced in {len(docs)} document(s)")

        if risk_score >= 3:
            risk_level = "high"
        elif risk_score >= 1:
            risk_level = "medium"
        else:
            risk_level = "low"

        # Under the mini profile the call graph only spans public symbols and
        # tests/history are absent, so a ``low`` score reflects missing data
        # rather than genuinely low impact.  Promote it to ``unknown`` to avoid
        # a false sense of safety.
        if risk_level == "low" and self.graph_profile == "mini":
            risk_level = "unknown"
            risk_reasons.append(
                "risk downgraded to unknown: mini profile excludes private "
                "callers, tests and history"
            )

        affected_modules: set[str] = set()
        for caller in callers:
            cnode = self.store.get_node(caller["id"])
            if cnode and cnode.get("module_id"):
                affected_modules.add(cnode["module_id"])

        return {
            "target": target,
            "affected_modules": list(affected_modules),
            "affected_functions": callers,
            "affected_tests": tests,
            "affected_documents": docs,
            "risk_level": risk_level,
            "risk_reasons": risk_reasons,
        }

    def _resolve_id(self, identifier: str, expected_type: str | None = None) -> str | None:
        """Resolve a name or ID to a node ID.

        Picks the best match when a name is ambiguous: an exact case-sensitive
        name match is preferred, and type priority (class/module > function)
        prevents a struct like ``Poll`` from being shadowed by a method named
        ``poll`` when looked up case-insensitively.
        """
        if identifier.startswith((
            "fn_", "cls_", "mod_", "file_", "doc_", "sec_", "dchunk_",
            "cchunk_",
        )):
            node = self.store.get_node(identifier)
            if node and (
                expected_type is None or node.get("type") == expected_type
            ):
                return identifier

        matches = self._ranked_matches(identifier, expected_type)
        return matches[0] if matches else None

    def _resolve_ids(self, identifier: str, expected_type: str | None = None) -> list[str]:
        """Resolve a name to all matching node IDs (handles ambiguity)."""
        if identifier.startswith((
            "fn_", "cls_", "mod_", "file_", "doc_", "sec_", "dchunk_",
            "cchunk_",
        )):
            node = self.store.get_node(identifier)
            if node and (
                expected_type is None or node.get("type") == expected_type
            ):
                return [identifier]
        return self._ranked_matches(identifier, expected_type)

    # Type priority for name resolution: classes/modules rank above functions so
    # that looking up "Poll" resolves to the struct, not a `poll` method.
    _TYPE_PRIORITY = {"class": 0, "module": 0, "function": 1}

    def _ranked_matches(
        self, identifier: str, expected_type: str | None = None
    ) -> list[str]:
        """Return node ids matching ``identifier``, best match first.

        Ranking: type priority (class/module > function) then exact
        case-sensitive name match. Nodes whose type contradicts an explicit
        ``expected_type`` are dropped entirely.

        For module lookups, also matches by the ``crate`` field (e.g. looking
        up ``ylong_io`` resolves to the crate's root module even though the
        module node's ``name`` is the directory name ``src``). The crate root
        (parentless, shortest path) ranks first.
        """
        result: list[str] = []
        seen: set[str] = set()
        for node_id in self.symbol_index.lookup(identifier):
            node = self.store.get_node(node_id)
            if not node:
                continue
            if expected_type is not None and node.get("type") != expected_type:
                continue
            result.append(node_id)
            seen.add(node_id)

        # Module lookups: supplement with crate-name matches.
        if expected_type == "module":
            for m in self.store.get_nodes_by_type("module"):
                if m.get("crate") == identifier and m.get("id") not in seen:
                    result.append(m.get("id"))
                    seen.add(m.get("id"))

        if not result:
            return []

        def rank(node_id: str) -> tuple[int, int, int, int]:
            node = self.store.get_node(node_id) or {}
            type_prio = self._TYPE_PRIORITY.get(node.get("type"), 2)
            exact = 0 if node.get("name") == identifier else 1
            # Crate-root modules (no parent) rank above sub-modules matched only
            # via the crate name. Prefer the source root (name == "src") over
            # examples/tests/benches directories.
            is_crate = (
                node.get("type") == "module"
                and node.get("crate") == identifier
                and node.get("parent") is None
            )
            crate_root = 0 if is_crate else 1
            src_first = 0 if (is_crate and node.get("name") == "src") else 1
            return (type_prio, exact, crate_root, src_first)

        return sorted(result, key=rank)


    def _get_name(self, node_id: str) -> str:
        """Get the name of a node by ID."""
        node = self.store.get_node(node_id)
        if node:
            return node.get("name", node_id)
        return node_id

    def _normalize_project_rel_path(self, path: str | None) -> str | None:
        """Normalise a path and reject anything outside the project root."""
        if not path:
            return None
        raw = Path(str(path).replace("\\", "/"))
        if self._project_path is None:
            if raw.is_absolute() or ".." in raw.parts:
                return None
            return raw.as_posix()

        root = self._project_path.resolve()
        candidate = raw if raw.is_absolute() else root / raw
        try:
            resolved = candidate.resolve(strict=False)
            return resolved.relative_to(root).as_posix()
        except (OSError, RuntimeError, ValueError):
            return None

    @staticmethod
    def _normalize_stored_rel_path(path: str | None) -> str | None:
        """Lexically normalise a persisted project-relative path.

        Snapshot reads must not depend on the *current* filesystem topology: a
        document remains queryable after it is deleted or replaced by a
        symlink.  Filesystem reads still pass through
        :meth:`_normalize_project_rel_path`, which resolves symlinks and
        enforces the project-root boundary before opening anything.
        """
        if not path:
            return None
        value = str(path).replace("\\", "/")
        if "\x00" in value or value.startswith("/") or re.match(r"^[A-Za-z]:", value):
            return None
        raw = PurePosixPath(value)
        if any(part == ".." for part in raw.parts):
            return None
        normalised = raw.as_posix()
        if normalised in {"", "."}:
            return None
        return normalised

    def _read_file_slice(
        self,
        rel_path: str | None,
        line_start: int | None,
        line_end: int | None,
        max_bytes: int | None = None,
    ) -> tuple[str | None, bool, int | None]:
        """Compatibility wrapper returning the first bounded filesystem page."""
        text, truncated, last_line, _, _, _ = self._read_file_page(
            rel_path, line_start, line_end, max_bytes=max_bytes,
        )
        return text, truncated, last_line

    def _read_file_page(
        self,
        rel_path: str | None,
        line_start: int | None,
        line_end: int | None,
        max_bytes: int | None = None,
        *,
        byte_cursor: int | None = None,
        cursor_line: int | None = None,
        expected_fingerprint: str | None = None,
    ) -> tuple[
        str | None, bool, int | None, int | None, int | None, str | None
    ]:
        """Stream one filesystem page and return a resumable byte position.

        Byte cursors are bound to the identity, size, and nanosecond timestamps
        of the opened file handle.  A changed live file therefore rejects the
        cursor instead of silently combining content from two versions.
        Resolving the final path before opening also prevents symlink and
        traversal escapes.
        """
        normalised = self._normalize_project_rel_path(rel_path)
        if normalised is None or self._project_path is None:
            return None, False, None, None, None, None
        try:
            root = self._project_path.resolve()
            abs_path = (root / normalised).resolve(strict=False)
            abs_path.relative_to(root)
        except (OSError, RuntimeError, ValueError):
            return None, False, None, None, None, None
        try:
            start = max(1, int(line_start or 1))
        except (TypeError, ValueError):
            start = 1
        try:
            end = int(line_end) if line_end is not None else None
        except (TypeError, ValueError):
            end = None
        try:
            byte_budget = (
                self.MAX_CONTENT_BYTES
                if max_bytes is None
                else min(self.MAX_CONTENT_BYTES, max(1, int(max_bytes)))
            )
        except (TypeError, ValueError):
            byte_budget = self.MAX_CONTENT_BYTES

        lines: list[str] = []
        byte_count = 0
        last_line: int | None = None
        truncated = False
        next_byte: int | None = None
        next_line_number: int | None = None
        last_terminator_offset: int | None = None
        last_terminator_line: int | None = None
        output_prefix = ""

        def discard_line(stream) -> bool:
            """Consume one logical line using fixed-size chunks."""
            saw_data = False
            while True:
                chunk = stream.readline(64 * 1024)
                if not chunk:
                    return saw_data
                saw_data = True
                if chunk.endswith(b"\n"):
                    return True

        def read_line(stream, limit: int) -> tuple[bytes, bool, bool, int]:
            """Return bounded bytes, existence, overflow, and line start."""
            line_offset = stream.tell()
            captured = bytearray()
            saw_data = False
            while True:
                remaining = max(0, limit + 4 - len(captured))
                chunk = stream.readline(min(64 * 1024, max(1, remaining + 1)))
                if not chunk:
                    return (
                        bytes(captured), saw_data, len(captured) > limit,
                        line_offset,
                    )
                saw_data = True
                ended = chunk.endswith(b"\n")
                payload = chunk[:-1] if ended else chunk
                if ended and payload.endswith(b"\r"):
                    payload = payload[:-1]
                captured.extend(payload)
                if ended:
                    return bytes(captured), True, len(captured) > limit, line_offset
                if len(captured) > limit + 4:
                    return bytes(captured), True, True, line_offset

        def decode_bounded(
            raw: bytes,
            limit: int,
            *,
            final: bool,
            allow_one_codepoint: bool,
        ) -> tuple[str, int]:
            """Decode within an output UTF-8 budget and return raw bytes used."""
            limit = max(0, limit)
            decoded, consumed = codecs.utf_8_decode(raw, "replace", final)
            if consumed == len(raw) and len(decoded.encode("utf-8")) <= limit:
                return decoded, consumed

            # Output size is monotonic as a raw prefix grows. Decode candidate
            # prefixes with final=False so a page boundary never turns half of
            # a valid multibyte code point into U+FFFD.
            low, high = 0, len(raw)
            best_text = ""
            best_consumed = 0
            while low <= high:
                middle = (low + high) // 2
                text_prefix, raw_consumed = codecs.utf_8_decode(
                    raw[:middle],
                    "replace",
                    final and middle == len(raw),
                )
                output_bytes = len(text_prefix.encode("utf-8"))
                if output_bytes <= limit:
                    if raw_consumed >= best_consumed:
                        best_text = text_prefix
                        best_consumed = raw_consumed
                    low = middle + 1
                else:
                    high = middle - 1

            if best_consumed or not raw or not allow_one_codepoint:
                return best_text, best_consumed

            # A 1-3 byte page budget cannot contain U+FFFD or a four-byte code
            # point. Permit exactly the first decoded unit to guarantee cursor
            # progress; this is the documented single-codepoint exception.
            for width in range(1, min(4, len(raw)) + 1):
                text_prefix, raw_consumed = codecs.utf_8_decode(
                    raw[:width],
                    "replace",
                    final and width == len(raw),
                )
                if text_prefix and raw_consumed:
                    return text_prefix[0], raw_consumed
            return "", 0

        fingerprint: str | None = None
        try:
            with abs_path.open("rb") as stream:
                file_stat = os.fstat(stream.fileno())
                if not stat.S_ISREG(file_stat.st_mode):
                    return None, False, None, None, None, None
                fingerprint = _file_handle_fingerprint(file_stat)
                if (
                    expected_fingerprint is not None
                    and expected_fingerprint != fingerprint
                ):
                    return None, False, None, None, None, fingerprint

                def verified_page(
                    page: tuple[
                        str | None,
                        bool,
                        int | None,
                        int | None,
                        int | None,
                        str | None,
                    ],
                ) -> tuple[
                    str | None,
                    bool,
                    int | None,
                    int | None,
                    int | None,
                    str | None,
                ]:
                    """Reject a page if its opened file changed while read."""
                    current = _file_handle_fingerprint(os.fstat(stream.fileno()))
                    if current != fingerprint:
                        return None, False, None, None, None, current
                    return page

                if end is not None and end < start:
                    return verified_page(
                        ("", False, start - 1, None, None, fingerprint)
                    )
                if byte_cursor is not None:
                    if byte_cursor < 0 or byte_cursor > file_stat.st_size:
                        return None, False, None, None, None, fingerprint
                    stream.seek(byte_cursor)
                    line_number = max(start, int(cursor_line or start))
                    # Continuations may deliberately point at the previous
                    # line terminator so concatenated pages preserve that
                    # separator. Consume it into an explicit output prefix;
                    # otherwise a one-byte budget could loop forever on an
                    # empty replayed line.
                    marker = stream.read(2)
                    if marker.startswith(b"\r\n"):
                        output_prefix = "\n"
                        byte_count = 1
                        last_line = line_number
                        line_number += 1
                    elif marker.startswith(b"\n"):
                        output_prefix = "\n"
                        byte_count = 1
                        last_line = line_number
                        line_number += 1
                        stream.seek(byte_cursor + 1)
                    else:
                        stream.seek(byte_cursor)
                else:
                    line_number = 1
                    while line_number < start:
                        if not discard_line(stream):
                            return verified_page(
                                ("", False, None, None, None, fingerprint)
                            )
                        line_number += 1

                while end is None or line_number <= end:
                    if len(lines) >= self.MAX_CONTENT_LINES:
                        next_byte = (
                            last_terminator_offset
                            if last_terminator_offset is not None
                            else stream.tell()
                        )
                        truncated = next_byte < file_stat.st_size
                        next_line_number = (
                            last_terminator_line
                            if truncated and last_terminator_line is not None
                            else (line_number if truncated else None)
                        )
                        break
                    separator_bytes = 1 if lines else 0
                    remaining = byte_budget - byte_count - separator_bytes
                    if remaining < 0:
                        next_byte = (
                            last_terminator_offset
                            if last_terminator_offset is not None
                            else stream.tell()
                        )
                        truncated = next_byte < file_stat.st_size
                        next_line_number = (
                            last_terminator_line
                            if truncated and last_terminator_line is not None
                            else (line_number if truncated else None)
                        )
                        break
                    raw_line, exists, overflow, line_offset = read_line(
                        stream, remaining
                    )
                    if not exists:
                        break
                    decoded, consumed = decode_bounded(
                        raw_line,
                        remaining,
                        final=not overflow,
                        allow_one_codepoint=not lines and not output_prefix,
                    )
                    if overflow or consumed < len(raw_line):
                        if not decoded and (lines or output_prefix):
                            truncated = True
                            # If this page already completed a prior line,
                            # replay its terminator on the next page so page
                            # concatenation preserves the separator.  A page
                            # that only replayed ``output_prefix`` has no such
                            # terminator and must resume at the current line.
                            next_byte = (
                                last_terminator_offset
                                if lines and last_terminator_offset is not None
                                else line_offset
                            )
                            next_line_number = (
                                last_terminator_line
                                if lines and last_terminator_line is not None
                                else line_number
                            )
                            break
                        lines.append(decoded)
                        last_line = line_number
                        truncated = True
                        next_byte = line_offset + consumed
                        next_line_number = line_number
                        break
                    lines.append(decoded)
                    byte_count += len(decoded.encode("utf-8")) + separator_bytes
                    last_line = line_number
                    position = stream.tell()
                    terminator_offset = line_offset + len(raw_line)
                    if position > terminator_offset:
                        last_terminator_offset = terminator_offset
                        last_terminator_line = line_number
                    if byte_count >= byte_budget:
                        if (end is None or line_number < end) and position < file_stat.st_size:
                            truncated = True
                            next_byte = (
                                last_terminator_offset
                                if last_terminator_offset is not None
                                else position
                            )
                            next_line_number = (
                                last_terminator_line
                                if last_terminator_line is not None
                                else line_number + 1
                            )
                        break
                    line_number += 1
                return verified_page((
                    output_prefix + "\n".join(lines), truncated, last_line,
                    next_byte, next_line_number, fingerprint,
                ))
        except OSError:
            return None, False, None, None, None, fingerprint

    def _read_graph_slice(
        self,
        text: str,
        base_line: int,
        line_start: int | None,
        line_end: int | None,
        max_bytes: int | None = None,
        char_cursor: int | None = None,
        preserve_exact: bool = False,
        cursor_line: int | None = None,
    ) -> tuple[str, bool, int | None, str | None]:
        """Read a bounded range from a persisted text snapshot.

        Normal pages resume at a line number.  If the byte budget cuts through
        one exceptionally long line, ``char:<offset>`` resumes within that
        line, so concatenating all returned pages never loses content.
        Character offsets are relative to ``text`` and intentionally opaque to
        callers.
        """
        try:
            budget = (
                self.MAX_CONTENT_BYTES
                if max_bytes is None
                else min(self.MAX_CONTENT_BYTES, max(1, int(max_bytes)))
            )
        except (TypeError, ValueError):
            budget = self.MAX_CONTENT_BYTES

        try:
            base = max(1, int(base_line))
        except (TypeError, ValueError):
            base = 1
        try:
            start = max(base, int(line_start or base))
        except (TypeError, ValueError):
            start = base
        try:
            end = int(line_end) if line_end is not None else None
        except (TypeError, ValueError):
            end = None
        if end is not None and end < start:
            return "", False, start - 1, None

        if preserve_exact:
            cursor_offset = char_cursor if char_cursor is not None else 0
            if cursor_offset < 0 or cursor_offset > len(text):
                raise ValueError("snapshot cursor is outside the stored content")
            if cursor_offset == len(text):
                return "", False, None, None

            line_boundary = cursor_offset
            search_from = cursor_offset
            for _ in range(max(1, self.MAX_CONTENT_LINES)):
                newline = text.find("\n", search_from)
                if newline < 0:
                    line_boundary = len(text)
                    break
                line_boundary = newline + 1
                search_from = line_boundary

            # A byte budget can contain at most that many Python characters,
            # so this slice remains bounded even when the stored document is
            # one exceptionally large line.
            candidate_end = min(line_boundary, cursor_offset + budget)
            candidate = text[cursor_offset:candidate_end]
            page = _utf8_bounded_prefix(candidate, budget)
            # Ensure forward progress for a budget smaller than one UTF-8 code
            # point. This can exceed the requested budget by at most three
            # bytes, while the hard server cap still applies.
            if not page and candidate:
                page = candidate[0]

            page_end = cursor_offset + len(page)
            truncated = page_end < len(text)
            next_cursor = f"char:{page_end}" if truncated else None
            if not page:
                last_line = None
            else:
                # Use the cursor-carried line number when available so we do
                # not recount every preceding newline from offset 0 (O(n^2)
                # across pages of a large snapshot).
                if cursor_line is not None and cursor_line >= base:
                    start_line_number = cursor_line
                else:
                    start_line_number = base + text.count("\n", 0, cursor_offset)
                last_line = start_line_number + page.count("\n")
                if page.endswith("\n"):
                    last_line -= 1
                last_line = max(base, last_line)
            return page, truncated, last_line, next_cursor

        if not text:
            return "", False, None, None

        # Locate and page logical lines directly in the stored string.  The
        # former ``splitlines(keepends=True)`` path built one Python object per
        # line before applying the response cap; a selected million-line
        # snapshot could therefore exhaust memory just to return a small
        # Section. Canonical document text uses LF, so scanning with ``find``
        # preserves line numbering with constant auxiliary memory.
        line_number = base
        content_start = 0
        while line_number < start:
            newline = text.find("\n", content_start)
            if newline < 0:
                return "", False, None, None
            content_start = newline + 1
            line_number += 1

        first_char_offset = 0
        if char_cursor is not None:
            if char_cursor < content_start or char_cursor > len(text):
                raise ValueError("snapshot cursor is outside the requested range")
            found = False
            while end is None or line_number <= end:
                newline = text.find("\n", content_start)
                raw_end = len(text) if newline < 0 else newline
                logical_end = (
                    raw_end - 1
                    if raw_end > content_start and text[raw_end - 1] == "\r"
                    else raw_end
                )
                if content_start <= char_cursor < logical_end:
                    first_char_offset = char_cursor - content_start
                    found = True
                    break
                if char_cursor == logical_end:
                    if newline < 0:
                        return "", False, None, None
                    content_start = newline + 1
                    line_number += 1
                    found = True
                    break
                if newline < 0 or char_cursor < content_start:
                    break
                content_start = newline + 1
                line_number += 1
            if not found or (end is not None and line_number > end):
                raise ValueError("snapshot cursor is outside the requested range")

        lines: list[str] = []
        byte_count = 0
        truncated = False
        last_line: int | None = None
        next_cursor: str | None = None
        while content_start < len(text) and (end is None or line_number <= end):
            if len(lines) >= self.MAX_CONTENT_LINES:
                truncated = True
                next_cursor = str(line_number)
                break

            newline = text.find("\n", content_start)
            raw_end = len(text) if newline < 0 else newline
            logical_end = (
                raw_end - 1
                if raw_end > content_start and text[raw_end - 1] == "\r"
                else raw_end
            )
            line_offset = first_char_offset
            first_char_offset = 0
            segment_start = min(logical_end, content_start + line_offset)
            separator_bytes = 1 if lines else 0
            remaining = budget - byte_count - separator_bytes
            if remaining < 0:
                truncated = True
                next_cursor = (
                    f"char:{segment_start}"
                    if line_offset
                    else str(line_number)
                )
                break

            # UTF-8 uses at least one byte per Python character.  Slice no
            # more than the remaining byte budget (plus one progress code
            # point), so even a single enormous line never creates an enormous
            # temporary string before clipping.
            candidate_end = min(
                logical_end,
                segment_start + max(1, remaining),
            )
            candidate = text[segment_start:candidate_end]
            clipped = _utf8_bounded_prefix(candidate, remaining)
            complete_line = (
                candidate_end == logical_end and clipped == candidate
            )
            if not complete_line:
                # A strict byte budget smaller than one UTF-8 code point cannot
                # both return valid text and make progress. Permit that single
                # code point (at most four bytes) so the cursor never loops.
                if not clipped and candidate and not lines:
                    clipped = candidate[0]
                lines.append(clipped)
                last_line = line_number
                truncated = True
                next_cursor = f"char:{segment_start + len(clipped)}"
                break

            lines.append(candidate)
            byte_count += len(candidate.encode("utf-8")) + separator_bytes
            last_line = line_number
            if newline < 0:
                break
            content_start = newline + 1
            line_number += 1
            if byte_count >= budget and (
                content_start < len(text)
                and (end is None or line_number <= end)
            ):
                truncated = True
                next_cursor = str(line_number)
                break

        return "\n".join(lines), truncated, last_line, next_cursor

    def _read_file_lines(self, rel_path: str | None, line_start: int | None,
                         line_end: int | None) -> str | None:
        """Compatibility wrapper returning only text for internal callers."""
        return self._read_file_slice(rel_path, line_start, line_end)[0]

    def _file_path(self, node: dict) -> str | None:
        """Resolve a node's source path: functions/classes via file_id, files via path,
        sections/concepts via their owning document."""
        file_id = node.get("file_id")
        if file_id:
            f = self.store.get_node(file_id)
            if f:
                return f.get("path")
        path = node.get("path")
        if path:
            return path
        doc_id = node.get("doc_id") or node.get("source")
        if doc_id:
            d = self.store.get_node(doc_id)
            if d:
                return d.get("path")
        return None

    @staticmethod
    def _index_text(
        node: dict,
        index_body: bool = False,
        store: GraphStore | None = None,
        parent_document: dict | None = None,
    ) -> str | None:
        """Unified index text for a node (used by both BM25 and semantic indexes).

        Richer text improves semantic recall, especially for cross-language
        queries where a bare identifier (e.g. ``Timeout``) carries little
        signal: we add the owning class, parameter names, and kind so a
        function/class is retrievable by the concepts it involves.
        """
        t = node.get("type")
        if t == "function":
            parts = [
                node.get("name", ""),
                node.get("signature", ""),
                node.get("docstring") or "",
            ]
            # Owning class gives methods like `poll` the context `Poll::poll`.
            if node.get("class_name"):
                parts.append(node["class_name"])
            # Parameter names add semantic anchors (e.g. "events timeout").
            params = node.get("params") or []
            if params:
                parts.append(" ".join(p.get("name", "") for p in params if isinstance(p, dict)))
            if index_body and node.get("body"):
                parts.append(node["body"])
            return " ".join(p for p in parts if p)
        if t == "class":
            parts = [node.get("name", ""), node.get("kind") or "", node.get("docstring") or ""]
            return " ".join(p for p in parts if p)
        if t == "symbol":
            parts = [
                node.get("name", ""),
                node.get("kind") or "",
                node.get("signature") or "",
                node.get("value") or "",
                node.get("data_type") or "",
                node.get("owner_name") or "",
            ]
            return " ".join(str(part) for part in parts if part)
        if t == "document":
            return f"{node.get('title', '')} {node.get('path', '')}"
        if t == "section":
            return f"{node.get('title', '')} {node.get('content', '')}"
        if t == "document_chunk":
            parent = parent_document
            doc_id = node.get("doc_id")
            if parent is None and store is not None and doc_id:
                parent = store.get_node(doc_id)

            content = parent.get("content") if parent else None
            chunk_text = ""
            if isinstance(content, str):
                try:
                    start = max(0, int(node.get("char_start") or 0))
                    raw_end = node.get("char_end")
                    end = int(raw_end) if raw_end is not None else len(content)
                except (TypeError, ValueError):
                    start, end = 0, 0
                # char_end is a Python-character, end-exclusive offset.
                chunk_text = content[start:max(start, end)]
            elif node.get("content") is not None:
                # Compatibility for experimental/legacy chunk nodes.
                chunk_text = str(node.get("content") or "")
            else:
                chunk_text = node.get("content_preview") or ""

            title = node.get("title") or (parent.get("title") if parent else "")
            path = node.get("path") or (parent.get("path") if parent else "")
            return " ".join(
                part for part in (title or "", path or "", chunk_text) if part
            )
        if t == "concept":
            return node.get("name", "")
        if t == "module":
            return node.get("name", "")
        if t == "code_chunk":
            # Fallback chunk for a parse-failed code file.  The content is
            # stored inline on the node (unlike document_chunk which slices
            # the parent).  Index keywords + content + the parent file path.
            keywords = node.get("keywords") or ""
            content = node.get("content") or ""
            source_id = node.get("source_id") or ""
            parent = store.get_node(source_id) if store is not None and source_id else None
            path = parent.get("path") if parent else ""
            return " ".join(
                part for part in (path, keywords, content) if part
            )
        return None

    def _summarize(self, node_id: str) -> dict:
        """Compact summary for ambiguity candidates."""
        node = self.store.get_node(node_id)
        if not node:
            return {"id": node_id}
        return {
            "id": node_id,
            "name": node.get("name") or node.get("title"),
            "type": node.get("type"),
            "kind": node.get("kind"),
            "class_name": node.get("class_name"),
            "file": self._file_path(node),
            "line": node.get("line_start"),
        }

    def _build_section_tree(self, doc_id: str) -> list[dict]:
        """Build a hierarchical section tree for a document.

        Returns a list of top-level sections, each with nested ``children``.
        Sections are matched to the document via the ``doc_id`` field and
        sorted by line_start. Nesting is determined by heading level.
        """
        all_sections = [
            n for n in self.store.get_nodes_by_type("section")
            if n.get("doc_id") == doc_id
        ]
        all_sections.sort(key=lambda s: s.get("line_start", 0))
        # Build tree by tracking a stack of (level, node) and popping until
        # the parent's level is less than the current section's level.
        roots: list[dict] = []
        stack: list[tuple[int, dict]] = []
        for sec in all_sections:
            entry = {
                "id": sec.get("id"),
                "title": sec.get("title"),
                "level": sec.get("level"),
                "line_start": sec.get("line_start"),
                "line_end": sec.get("line_end"),
                "children": [],
            }
            while stack and stack[-1][0] >= entry["level"]:
                stack.pop()
            if stack:
                stack[-1][1]["children"].append(entry)
            else:
                roots.append(entry)
            stack.append((entry["level"], entry))
        return roots

    @_read_locked
    def list_documents(
        self, scope: str | None = None, pattern: str | None = None,
        max_items: int = 200, include_sections: bool = True,
    ) -> dict:
        """List documents with summary and optional section tree.

        Returns a dict with ``documents``, ``total``, and ``truncated`` keys.
        When ``include_sections`` is False, ``section_tree`` is omitted for
        faster listing of large document sets.  ``max_items`` bounds the
        response size (default 200).
        """
        import fnmatch

        documents = self.store.get_nodes_by_type("document")
        all_results = []

        for doc in documents:
            path = doc.get("path", "")

            if scope and scope not in path:
                continue

            if pattern:
                # Support both glob patterns and plain substrings. If the user
                # passes a bare substring like "wiki", treat it as "*wiki*" so
                # it matches any path containing it (the intuitive default).
                # Patterns that already contain glob metacharacters (* ? [)
                # are used verbatim so explicit globs still work.
                if not any(ch in pattern for ch in "*?["):
                    pattern = f"*{pattern}*"
                if not fnmatch.fnmatch(path, pattern):
                    continue

            entry = {
                "id": doc.get("id"),
                "title": doc.get("title"),
                "path": path,
                "summary": doc.get("summary"),
                "section_titles": doc.get("section_titles", []),
                "line_count": doc.get("line_count"),
                "content_available": bool(
                    doc.get("content_complete") is True
                    and isinstance(doc.get("content"), str)
                ),
                "content_state": doc.get("content_state") or "not_selected",
                "content_bytes": doc.get("content_bytes"),
                "content_representation": doc.get("content_representation"),
            }
            if include_sections:
                entry["section_tree"] = self._build_section_tree(doc.get("id"))
            all_results.append(entry)

        total = len(all_results)
        truncated = max_items and total > max_items
        results = all_results[:max_items] if max_items else all_results

        return {
            "documents": results,
            "total": total,
            "truncated": truncated,
        }

    @_read_locked
    def get_context(
        self, target: str, scope: str = "all", depth: int = 1
    ) -> dict:
        """Get multi-dimensional context around a target symbol.

        For class/struct/trait targets, relations (callers/callees/tests/docs)
        are aggregated across all methods, mirroring ``impact_analysis``;
        querying the class node directly would yield empty results since CALL
        edges live on the methods, not the class.
        """
        resolved_id = self._resolve_id(target)
        if not resolved_id:
            return {"target": target, "context": {}}

        node = self.store.get_node(resolved_id)
        if not node:
            return {"target": target, "context": {}}

        # Class nodes: expand to their methods so relation edges resolve.
        if node.get("type") == "class":
            method_ids = self.get_class_methods(resolved_id)
            targets = method_ids if method_ids else [resolved_id]
        else:
            targets = [resolved_id]

        context = {}

        def collect(fetcher) -> list[dict]:
            """Run ``fetcher`` across all targets, de-duplicating by node id."""
            out: list[dict] = []
            seen: set[str] = set()
            for tid in targets:
                for item in fetcher(tid):
                    key = item.get("id")
                    if key and key not in seen:
                        seen.add(key)
                        out.append(item)
            return out

        # 获取 callers
        if scope in ("all", "callers"):
            callers = collect(lambda tid: self.get_callers(tid, depth=depth))
            context["callers"] = [
                {"id": c["id"], "name": c["name"], "relation": "caller"}
                for c in callers
            ]

        # 获取 callees
        if scope in ("all", "callees"):
            callees = collect(lambda tid: self.get_callees(tid, depth=depth))
            context["callees"] = [
                {"id": c["id"], "name": c["name"], "relation": "callee"}
                for c in callees
            ]

        # 获取 tests
        if scope in ("all", "tests"):
            tests = collect(self.get_related_tests)
            context["tests"] = [
                {"id": t["id"], "name": t["name"]}
                for t in tests
            ]

        # 获取 docs
        if scope in ("all", "docs"):
            docs = collect(self.get_doc_links)
            context["docs"] = [
                {"id": d["id"], "title": d["title"], "path": d["path"]}
                for d in docs
            ]

        # 获取 params
        if scope in ("all", "params"):
            params = node.get("params", [])
            context["params"] = params

        return {
            "target": resolved_id,
            "context": context,
        }

    def get_code_slice(
        self,
        target: str,
        kind: str | None = None,
        section: str | None = None,
        include_source: bool = True,
        source: str = "auto",
        line_start: int | None = None,
        line_end: int | None = None,
        max_bytes: int | None = None,
        cursor: str | int | None = None,
    ) -> dict | None:
        """Get bounded source/document content by ID, name, or file path.

        ``auto`` prefers a complete document snapshot stored in the graph and
        falls back to the live filesystem. ``graph`` is snapshot-only and
        ``filesystem`` deliberately bypasses the snapshot. Cursor values are
        opaque continuation tokens returned by a previous bounded request;
        plain line numbers remain accepted for backwards compatibility.
        """
        requested_kind = (kind or "any").lower()
        valid_kinds = {
            "any", "function", "class", "document", "section",
            "document_chunk", "code_chunk", "file",
        }
        if requested_kind not in valid_kinds:
            return None
        requested_source = (source or "auto").lower()
        if requested_source not in {"auto", "graph", "filesystem"}:
            return None

        requested_line_start = line_start
        requested_line_end = line_end
        requested_char_cursor: int | None = None
        requested_byte_cursor: int | None = None
        requested_cursor_line: int | None = None
        requested_fingerprint: str | None = None
        cursor_line_end: int | None = None
        cursor_preserve_exact = False
        cursor_payload: dict[str, Any] | None = None
        if cursor is not None:
            try:
                cursor_text = str(cursor).strip()
                if cursor_text.startswith("pb1."):
                    cursor_payload = _decode_content_cursor(cursor_text)
                    if cursor_payload is None or cursor_payload.get("v") != 1:
                        return None
                    cursor_preserve_exact = bool(cursor_payload.get("x"))
                    raw_cursor_end = cursor_payload.get("e")
                    if raw_cursor_end is not None:
                        cursor_line_end = int(raw_cursor_end)
                        if cursor_line_end < 1:
                            return None
                        if requested_line_end is None:
                            requested_line_end = cursor_line_end
                        elif int(requested_line_end) != cursor_line_end:
                            return None
                    position = cursor_payload.get("p")
                    if cursor_payload.get("k") == "char":
                        requested_char_cursor = int(position)
                        if requested_char_cursor < 0:
                            return None
                        # The cursor carries the line number reached by the
                        # previous page so this page does not recount every
                        # newline from the start of the snapshot (O(n^2)).
                        raw_cursor_line = cursor_payload.get("l")
                        if raw_cursor_line is not None:
                            requested_cursor_line = int(raw_cursor_line)
                    elif cursor_payload.get("k") == "line":
                        requested_line_start = int(position)
                    elif cursor_payload.get("k") == "byte":
                        requested_byte_cursor = int(position)
                        requested_cursor_line = int(cursor_payload.get("l"))
                        requested_fingerprint = str(cursor_payload.get("f"))
                        if requested_byte_cursor < 0 or requested_cursor_line < 1:
                            return None
                    else:
                        return None
                elif cursor_text.lower().startswith("char:"):
                    requested_char_cursor = int(cursor_text.split(":", 1)[1])
                    if requested_char_cursor < 0:
                        return None
                else:
                    if cursor_text.lower().startswith("line:"):
                        cursor_text = cursor_text.split(":", 1)[1]
                    requested_line_start = int(cursor_text)
            except (TypeError, ValueError):
                return None

        with self._lock:
            normalised_target = self._normalize_project_rel_path(target)
            stored_target = (
                normalised_target or self._normalize_stored_rel_path(target)
            )
            file_info = (
                self.file_index.get(stored_target)
                if stored_target is not None
                else None
            )
            node: dict | None = None
            resolved_id: str | None = None

            if file_info:
                resolved_id = file_info.get("file_id")
                stored = self.store.get_node(resolved_id) if resolved_id else None
                if stored:
                    node = dict(stored)
                else:
                    # Some legacy graphs index a file without persisting its
                    # File node.  File-path content retrieval should still work.
                    resolved_id = resolved_id or stored_target
                    node = {
                        "id": resolved_id,
                        "type": "file",
                        "path": stored_target,
                    }
            elif stored_target is not None:
                for candidate_type in ("file", "document"):
                    for candidate in self.store.get_nodes_by_type(candidate_type):
                        candidate_path = self._normalize_stored_rel_path(
                            candidate.get("path")
                        )
                        if candidate_path == stored_target:
                            node = dict(candidate)
                            resolved_id = candidate.get("id")
                            break
                    if node is not None:
                        break

            if node is None:
                expected_type = (
                    requested_kind
                    if requested_kind in {"function", "class"}
                    else None
                )
                resolved_id = self._resolve_id(target, expected_type)
                stored = self.store.get_node(resolved_id) if resolved_id else None
                node = dict(stored) if stored else None
            if node is None or resolved_id is None:
                return None

            original_type = node.get("type")
            if section is not None:
                if original_type == "document":
                    matches = [
                        candidate
                        for candidate in self.store.get_nodes_by_type("section")
                        if candidate.get("doc_id") == resolved_id
                        and (
                            candidate.get("id") == section
                            or candidate.get("title") == section
                        )
                    ]
                    if not matches:
                        folded = section.casefold()
                        matches = [
                            candidate
                            for candidate in self.store.get_nodes_by_type("section")
                            if candidate.get("doc_id") == resolved_id
                            and str(candidate.get("title") or "").casefold() == folded
                        ]
                    if not matches:
                        return None
                    node = dict(matches[0])
                    resolved_id = node.get("id")
                elif original_type == "section":
                    if section not in (resolved_id, node.get("title")):
                        return None
                else:
                    return None

            node_type = node.get("type")
            kind_matches = node_type == requested_kind
            document_section_request = (
                section is not None
                and original_type == "document"
                and requested_kind in ("document", "section")
            )
            if requested_kind != "any" and not kind_matches and not document_section_request:
                return None

            if node_type == "document":
                file_path = node.get("path")
                line_start = 1
                line_end = node.get("line_count")
                content_key = "source"
            elif node_type in ("section", "document_chunk"):
                file_path = self._file_path(node)
                target_line_start = node.get("line_start")
                target_line_end = node.get("line_end")
                content_key = "content"
            elif node_type == "code_chunk":
                # Fallback chunk: content is inline.  Resolve the parent file
                # path via source_id so filesystem reads can locate the file.
                source_id = node.get("source_id")
                parent = self.store.get_node(source_id) if source_id else None
                file_path = parent.get("path") if parent else None
                target_line_start = node.get("line_start")
                target_line_end = node.get("line_end")
                content_key = "content"
            elif node_type in ("function", "class", "file"):
                file_path = self._file_path(node)
                target_line_start = node.get("line_start") or (1 if node_type == "file" else None)
                target_line_end = node.get("line_end") or node.get("line_count")
                content_key = "source"
            else:
                return None

            if node_type == "document":
                target_line_start = 1
                target_line_end = node.get("line_count")

            if file_path is not None:
                safe_path = self._normalize_stored_rel_path(file_path)
                if safe_path is None:
                    return None
                file_path = safe_path

            try:
                effective_start = max(
                    int(target_line_start or 1),
                    int(requested_line_start or target_line_start or 1),
                )
            except (TypeError, ValueError):
                return None
            try:
                effective_end = (
                    int(requested_line_end)
                    if requested_line_end is not None
                    else (
                        int(target_line_end) if target_line_end is not None else None
                    )
                )
            except (TypeError, ValueError):
                return None
            if target_line_end is not None:
                target_end_value = int(target_line_end)
                effective_end = (
                    target_end_value
                    if effective_end is None
                    else min(effective_end, target_end_value)
                )

            parent_doc: dict | None = None
            if node_type == "document":
                parent_doc = node
            elif node_type in ("section", "document_chunk"):
                doc_id = node.get("doc_id")
                stored_parent = self.store.get_node(doc_id) if doc_id else None
                parent_doc = dict(stored_parent) if stored_parent else None
            elif node_type == "code_chunk":
                # Fallback chunk: content is inline on the node itself.
                parent_doc = dict(node)
                parent_doc["content_complete"] = True

            persisted_content = parent_doc.get("content") if parent_doc else None
            graph_available = isinstance(persisted_content, str)
            stored_complete = bool(
                graph_available and parent_doc.get("content_complete") is True
            ) if parent_doc else False
            snapshot_md5 = parent_doc.get("md5") if parent_doc else None

            if cursor_payload is not None:
                cursor_source = cursor_payload.get("s")
                if cursor_payload.get("t") != resolved_id:
                    return None
                if requested_source == "auto":
                    requested_source = str(cursor_source)
                elif requested_source != cursor_source:
                    return None
                if cursor_source == "graph":
                    # Computing a fallback md5 from the full snapshot is O(n);
                    # defer it until a cursor actually needs cross-generation
                    # validation.  New builds always set ``md5``, so this only
                    # affects legacy documents without one.
                    if snapshot_md5 is None and isinstance(persisted_content, str):
                        snapshot_md5 = hashlib.md5(
                            persisted_content.encode("utf-8")
                        ).hexdigest()
                    if cursor_payload.get("m") != snapshot_md5:
                        # Prevent a continuation page from mixing two graph
                        # generations.
                        return None
                elif cursor_source != "filesystem":
                    return None

            result = {
                "target": resolved_id,
                "kind": node_type,
                "file": file_path,
                "line_start": effective_start,
                "line_end": effective_end,
                content_key: None,
                "token_count": None,
                "truncated": False,
                "content_source": None,
                "stored_complete": stored_complete,
                "returned_complete": False,
                "next_line_start": None,
                "next_cursor": None,
                "snapshot_md5": snapshot_md5,
                "content_encoding": (
                    parent_doc.get("content_encoding") if parent_doc else None
                ),
                "content_representation": (
                    parent_doc.get("content_representation") if parent_doc else None
                ),
                "content_unavailable_reason": None,
            }
            if node_type == "section":
                result["title"] = node.get("title")

            graph_segment: str | None = None
            graph_base_line = 1
            if graph_available:
                graph_segment = persisted_content
                if node_type == "document_chunk":
                    try:
                        char_start = max(0, int(node.get("char_start") or 0))
                        raw_char_end = node.get("char_end")
                        char_end = (
                            int(raw_char_end)
                            if raw_char_end is not None
                            else len(persisted_content)
                        )
                    except (TypeError, ValueError):
                        return None
                    # Offsets are Python-character offsets and end-exclusive.
                    graph_segment = persisted_content[
                        char_start:max(char_start, char_end)
                    ]
                    graph_base_line = int(target_line_start or 1)

            preserve_exact_graph = cursor_preserve_exact or bool(
                node_type in {"document", "document_chunk"}
                and requested_line_start is None
                and requested_line_end is None
            )

        if not include_source:
            return result

        use_graph = requested_source == "graph" or (
            requested_source == "auto" and stored_complete
        )
        read_effective_end = effective_end
        canonical_is_converted = bool(
            parent_doc
            and parent_doc.get("content_representation") == "converted_markdown"
        )
        if (
            not use_graph
            and requested_source in {"auto", "filesystem"}
            and canonical_is_converted
            and node_type in {"section", "document_chunk"}
        ):
            # Section/chunk ranges address the canonical MarkItDown output and
            # cannot be applied to the live HTML/RST/office source safely.
            result["content_unavailable_reason"] = (
                "converted_document_section_requires_graph_snapshot"
            )
            return result
        if (
            not use_graph
            and requested_source in {"auto", "filesystem"}
            and node_type in {"document", "file"}
            and requested_line_end is None
        ):
            # A whole live-file read must not stop at a line_count captured by
            # an older graph generation. Explicit ranges remain authoritative.
            read_effective_end = None
            result["line_end"] = None

        if use_graph and graph_segment is not None:
            try:
                text, truncated, returned_line_end, continuation_cursor = (
                    self._read_graph_slice(
                        graph_segment,
                        graph_base_line,
                        effective_start,
                        read_effective_end,
                        max_bytes=max_bytes,
                        char_cursor=requested_char_cursor,
                        preserve_exact=preserve_exact_graph,
                        cursor_line=requested_cursor_line,
                    )
                )
            except ValueError:
                return None
            content_source = "graph"
        elif requested_source == "graph":
            text, truncated, returned_line_end = None, False, None
            continuation_cursor = None
            content_source = None
        elif file_path is not None:
            # Character cursors are emitted only for persisted snapshots.  A
            # filesystem fallback cannot safely reinterpret that offset after
            # the live file changes.
            if requested_char_cursor is not None:
                return None
            (
                text,
                truncated,
                returned_line_end,
                next_byte,
                filesystem_next_line,
                filesystem_fingerprint,
            ) = self._read_file_page(
                file_path,
                effective_start,
                read_effective_end,
                max_bytes=max_bytes,
                byte_cursor=requested_byte_cursor,
                cursor_line=requested_cursor_line,
                expected_fingerprint=requested_fingerprint,
            )
            if requested_byte_cursor is not None and text is None:
                return None
            continuation_cursor = f"byte:{next_byte}" if next_byte is not None else None
            content_source = "filesystem" if text is not None else None
        else:
            if requested_byte_cursor is not None:
                return None
            text, truncated, returned_line_end = None, False, None
            continuation_cursor = None
            content_source = None

        result[content_key] = text
        result["truncated"] = truncated
        result["returned_line_end"] = returned_line_end
        result["content_source"] = content_source
        if content_source == "filesystem":
            result["content_encoding"] = "utf-8-errors-replace"
            result["content_representation"] = "filesystem_text_decode"
        result["returned_complete"] = bool(
            text is not None
            and not truncated
            and (content_source != "graph" or stored_complete)
        )
        if truncated and returned_line_end is not None:
            if content_source == "graph" and continuation_cursor:
                # A continuation cursor needs a stable md5 so the next page
                # can validate it.  Compute the fallback here (only for legacy
                # documents missing ``md5``) so the next page's check matches.
                if (
                    snapshot_md5 is None
                    and isinstance(persisted_content, str)
                ):
                    snapshot_md5 = hashlib.md5(
                        persisted_content.encode("utf-8")
                    ).hexdigest()
                if ":" in continuation_cursor:
                    cursor_kind, cursor_position = continuation_cursor.split(":", 1)
                else:
                    cursor_kind, cursor_position = "line", continuation_cursor
                cursor_payload = {
                    "v": 1,
                    "s": "graph",
                    "t": resolved_id,
                    "m": snapshot_md5,
                    "k": cursor_kind,
                    "p": int(cursor_position),
                    "e": read_effective_end,
                    "x": preserve_exact_graph,
                }
                # For char cursors (preserve_exact paging) carry the line
                # number so the next page avoids recounting all preceding
                # newlines from offset 0.
                if cursor_kind == "char":
                    cursor_payload["l"] = int(returned_line_end)
                result["next_cursor"] = _encode_content_cursor(cursor_payload)
            elif content_source == "filesystem" and continuation_cursor:
                _, cursor_position = continuation_cursor.split(":", 1)
                result["next_cursor"] = _encode_content_cursor({
                    "v": 1,
                    "s": "filesystem",
                    "t": resolved_id,
                    "k": "byte",
                    "p": int(cursor_position),
                    "l": int(filesystem_next_line or returned_line_end),
                    "f": filesystem_fingerprint,
                    "e": read_effective_end,
                })
            else:
                result["next_cursor"] = continuation_cursor
            if continuation_cursor and continuation_cursor.startswith("char:"):
                result["next_line_start"] = (
                    returned_line_end + 1
                    if isinstance(text, str) and text.endswith(("\n", "\r"))
                    else returned_line_end
                )
            elif continuation_cursor and continuation_cursor.startswith("byte:"):
                result["next_line_start"] = filesystem_next_line
            else:
                result["next_line_start"] = returned_line_end + 1
        if result["line_end"] is None:
            result["line_end"] = returned_line_end
        return result

    def get_change_diff(
        self, target: str, format: str = "unified"
    ) -> dict | None:
        """Return real, bounded Git diffs for a commit, file, or symbol."""
        if format not in {"unified", "side_by_side", "pair"}:
            return {
                "target": target,
                "format": format,
                "changes": [],
                "error": "format must be unified, side_by_side, or pair",
            }
        if self._project_path is None:
            return None

        commit_sha: str | None = None
        restricted_path: str | None = None
        restricted_symbol_id: str | None = None
        restricted_lines: tuple[int, int] | None = None
        with self._lock:
            for node in self.store.get_nodes_by_type("commit"):
                sha = str(node.get("sha") or "")
                if target and (sha.startswith(target) or node.get("id") == target):
                    commit_sha = sha
                    break

            normalised = self._normalize_project_rel_path(target)
            if commit_sha is None and normalised and self.file_index.get(normalised):
                restricted_path = normalised

            if commit_sha is None and restricted_path is None:
                resolved = self._resolve_id(target)
                node = self.store.get_node(resolved) if resolved else None
                if node:
                    restricted_path = self._file_path(node)
                    restricted_path = self._normalize_project_rel_path(restricted_path)
                    if node.get("type") in {"function", "class"}:
                        try:
                            line_start = int(node.get("line_start"))
                            line_end = int(node.get("line_end") or line_start)
                        except (TypeError, ValueError):
                            pass
                        else:
                            bounded_start = max(1, line_start)
                            restricted_symbol_id = resolved
                            restricted_lines = (
                                bounded_start, max(bounded_start, line_end),
                            )

        reader = GitDiffReader(self._project_path)
        if not reader.available():
            return {
                "target": target,
                "format": format,
                "changes": [],
                "error": "Git history is not available for this project",
            }

        if (
            commit_sha is None
            and restricted_path is not None
            and restricted_lines is not None
        ):
            try:
                commit_sha = reader.latest_commit_for_lines(
                    restricted_path, *restricted_lines,
                )
            except GitBudgetExceeded as exc:
                return {
                    "target": target,
                    "format": format,
                    "changes": [],
                    "truncated": True,
                    "error": str(exc),
                }
            except (OSError, RuntimeError):
                # Line history is unavailable for some binary/renamed files;
                # the bounded file history fallback still provides a useful diff.
                commit_sha = None
        if commit_sha is None and restricted_path is not None:
            try:
                commit_sha = reader.latest_commit(restricted_path)
            except GitBudgetExceeded as exc:
                return {
                    "target": target,
                    "format": format,
                    "changes": [],
                    "truncated": True,
                    "error": str(exc),
                }
            except (OSError, RuntimeError):
                commit_sha = None
        if commit_sha is None and re.fullmatch(r"[0-9a-fA-F]{4,64}", target):
            commit_sha = target
        if not commit_sha:
            return None

        try:
            git_changes = reader.changes(commit_sha)
        except GitBudgetExceeded as exc:
            return {
                "target": target,
                "commit_sha": commit_sha,
                "format": format,
                "changes": [],
                "truncated": True,
                "error": str(exc),
            }
        except (OSError, RuntimeError) as exc:
            return {
                "target": target,
                "commit_sha": commit_sha,
                "format": format,
                "changes": [],
                "error": f"Unable to read Git diff: {exc}",
            }

        if restricted_path is not None:
            git_changes = [
                change for change in git_changes
                if restricted_path in {change.old_path, change.new_path}
            ]

        status_names = {
            "A": "added",
            "D": "deleted",
            "M": "modified",
            "R": "renamed",
            "C": "copied",
            "T": "type_changed",
        }
        changes: list[dict] = []
        truncated = False
        truncation_reason: str | None = None
        for change in git_changes:
            entry: dict[str, Any] = {
                "commit_sha": commit_sha,
                "file": change.path,
                "old_file": change.old_path,
                "change_type": status_names.get(change.status, "modified"),
            }
            try:
                if format == "unified":
                    diff = reader.unified(commit_sha, change)
                    entry["diff"] = diff
                    entry["before"] = None
                    entry["after"] = None
                    changed_ranges = self._unified_changed_ranges(diff)
                else:
                    before, after = reader.file_pair(commit_sha, change)
                    entry["before"] = before
                    entry["after"] = after
                    changed_ranges = self._pair_changed_ranges(before, after)
                    if format == "side_by_side":
                        entry["before_lines"] = (before or "").splitlines()
                        entry["after_lines"] = (after or "").splitlines()
                entry["changed_functions"] = self._functions_for_path(
                    change.path, changed_ranges,
                )
            except GitBudgetExceeded as exc:
                truncated = True
                truncation_reason = str(exc)
                break
            except (OSError, RuntimeError) as exc:
                entry["error"] = str(exc)
            changes.append(entry)

        return {
            "target": target,
            "commit_sha": commit_sha,
            "format": format,
            "changes": changes,
            "truncated": truncated,
            "truncation_reason": truncation_reason,
            "scope": "symbol" if restricted_symbol_id else (
                "file" if restricted_path else "commit"
            ),
            "symbol_id": restricted_symbol_id,
        }

    @staticmethod
    def _unified_changed_ranges(diff: str) -> list[tuple[int, int]]:
        ranges: list[tuple[int, int]] = []
        for match in re.finditer(
            r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@",
            diff,
            flags=re.MULTILINE,
        ):
            start = int(match.group(1))
            count = int(match.group(2) or 1)
            ranges.append((max(1, start), max(1, start + max(1, count) - 1)))
        return ranges

    @staticmethod
    def _pair_changed_ranges(
        before: str | None, after: str | None
    ) -> list[tuple[int, int]]:
        before_lines = (before or "").splitlines()
        after_lines = (after or "").splitlines()
        ranges: list[tuple[int, int]] = []
        matcher = difflib.SequenceMatcher(a=before_lines, b=after_lines, autojunk=False)
        for tag, _old_start, _old_end, new_start, new_end in matcher.get_opcodes():
            if tag == "equal":
                continue
            start = max(1, new_start + 1)
            end = max(start, new_end)
            ranges.append((start, end))
        return ranges

    def _functions_for_path(
        self, path: str, changed_ranges: list[tuple[int, int]] | None = None
    ) -> list[str]:
        """Return current functions whose line spans overlap changed hunks."""
        with self._lock:
            file_info = self.file_index.get(path)
            file_id = file_info.get("file_id") if file_info else None
            if not file_id:
                return []
            node_ids = set(file_info.get("nodes", [])) if file_info else set()
            node_ids.update(
                edge.target
                for edge in self.store.get_edges(
                    file_id, edge_type="CONTAIN", direction="out"
                )
            )
            functions: list[str] = []
            for node_id in node_ids:
                node = self.store.get_node(node_id) or {}
                if node.get("type") != "function":
                    continue
                if changed_ranges is not None:
                    try:
                        line_start = int(node.get("line_start"))
                        line_end = int(node.get("line_end") or line_start)
                    except (TypeError, ValueError):
                        continue
                    if not any(
                        line_start <= changed_end and line_end >= changed_start
                        for changed_start, changed_end in changed_ranges
                    ):
                        continue
                functions.append(node_id)
            return sorted(functions)