Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

refactor(context): split get_context enrichment into call_graph, signals and skeleton modules (#4072)

Raghav Chamadiyaeb35d16746e2
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/call_graph.py b/packages/server/src/repowise/server/mcp_server/tool_context/call_graph.py
new file mode 100644
index 000000000..6bf5e6130
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/call_graph.py
@@ -0,0 +1,553 @@
+"""get_context ``callers`` / ``callees`` / ``relations`` block."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any
+
+from sqlalchemy import func, select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from repowise.core.ingestion.models import SYMBOL_USE_EDGE_TYPES
+from repowise.core.ingestion.symbol_identity import id_segment_name
+from repowise.core.persistence.crud import (
+ get_graph_edges_for_node,
+ get_graph_node,
+ get_graph_nodes_by_ids,
+)
+from repowise.core.persistence.models import GraphEdge, GraphNode, Repository
+from repowise.server.mcp_server._basis import call_resolution_basis
+from repowise.server.mcp_server._budget import OmissionCollector, cap_collection
+from repowise.server.mcp_server._edit_sites import attach_call_text, first_call_line
+from repowise.server.mcp_server._graph_files import keep_projected_edge, node_to_file
+from repowise.server.mcp_server._helpers import filter_dicts_by_key
+from repowise.server.mcp_server._index_state import index_state_key
+from repowise.server.mcp_server._wrapper_callers import forwarding_wrapper_callers
+from repowise.server.schemas.intelligence import SYMBOL_RELATION_GROUP_OF
+
+# Symbol-level call floor. The file-level rollup uses the shared
+# ``_graph_files`` floor instead; the totals query and the symbol rows must
+# share this one.
+_MIN_CALL_CONFIDENCE = 0.7
+
+# Every edge type meaning "something reaches this symbol", sorted so the SQL is
+# stable. Right for degree, wrong for ``callers``: a subclass reaches its base
+# without calling it, so only ``calls`` populates callers/callees.
+_SYMBOL_USE_EDGE_TYPES = sorted(SYMBOL_USE_EDGE_TYPES)
+
+#: The one edge type that is literally a call; everything else that reaches a
+#: symbol is reported by kind under ``relations``. ``tool_symbol`` imports it
+#: for its callee walk, so keep it meaning what it is named.
+_CALL_EDGE_TYPES = ["calls"]
+
+#: Maximum caller/callee rows returned for one symbol; a named seam so contract
+#: tests can force an omission.
+_SYMBOL_NEIGHBOR_LIMIT = 50
+
+#: Rows carried per relation kind, far below the call cap: the kind and the
+#: honest total answer "what else reaches this, and how".
+_RELATION_ROW_CAP = 5
+
+
+def _unique_by_symbol(entries: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """Collapse entries sharing a ``symbol_id``, keeping the first.
+
+ Order-preserving, so callers sort by confidence before calling this and
+ the survivor is the highest-confidence edge to that symbol.
+ """
+ seen: set[str] = set()
+ out: list[dict[str, Any]] = []
+ for entry in entries:
+ symbol_id = str(entry.get("symbol_id"))
+ if symbol_id in seen:
+ continue
+ seen.add(symbol_id)
+ out.append(entry)
+ return out
+
+
+async def _count_neighbors_by_edge_type(
+ session: AsyncSession, repo_id: str, node_id: str, *, inbound: bool
+) -> dict[str, int]:
+ """Count qualifying edge rows per type to size each directional fetch.
+
+ The emitted true total is computed after policy filtering and symbol
+ deduplication. These raw counts only ensure each ranked fetch is large
+ enough to contain that complete post-policy population.
+ """
+ matched = GraphEdge.target_node_id if inbound else GraphEdge.source_node_id
+ stmt = (
+ select(GraphEdge.edge_type, func.count(GraphEdge.id))
+ .where(
+ GraphEdge.repository_id == repo_id,
+ matched == node_id,
+ GraphEdge.edge_type.in_(_SYMBOL_USE_EDGE_TYPES),
+ GraphEdge.confidence >= _MIN_CALL_CONFIDENCE,
+ )
+ .group_by(GraphEdge.edge_type)
+ )
+ return {edge_type: int(n or 0) for edge_type, n in await session.execute(stmt)}
+
+
+@dataclass
+class _CallGraphRun:
+ """One symbol's call-graph request plus the neighbour nodes fetched for it."""
+
+ session: AsyncSession
+ repository: Repository
+ target: str
+ node: GraphNode
+ result_data: dict[str, Any]
+ want_callers: bool
+ want_callees: bool
+ exclude_spec: Any
+ collector: OmissionCollector | None
+ repo_root: Any
+ node_map: dict[str, Any] = field(default_factory=dict)
+
+ def wants(self, direction: str) -> bool:
+ return self.want_callers if direction == "in" else self.want_callees
+
+
+async def _resolve_call_graph(
+ session: AsyncSession,
+ repository: Repository,
+ target: str,
+ target_type: str | None,
+ result_data: dict[str, Any],
+ *,
+ want_callers: bool = False,
+ want_callees: bool = False,
+ exclude_spec: Any = None,
+ collector: OmissionCollector | None = None,
+ repo_root: Any = None,
+) -> None:
+ """Resolve callers/callees for a symbol and attach to result_data.
+
+ Served call rows carry ``call_line`` and, read from *repo_root*, its ``text``.
+ """
+ repo_id = repository.id
+ node = await _call_graph_node(session, repo_id, target)
+ if node is None or node.node_type != "symbol":
+ await _resolve_non_symbol_call_graph(
+ session,
+ repository,
+ target,
+ node,
+ result_data,
+ want_callers=want_callers,
+ want_callees=want_callees,
+ exclude_spec=exclude_spec,
+ collector=collector,
+ )
+ return
+ run = _CallGraphRun(
+ session=session,
+ repository=repository,
+ target=target,
+ node=node,
+ result_data=result_data,
+ want_callers=want_callers,
+ want_callees=want_callees,
+ exclude_spec=exclude_spec,
+ collector=collector,
+ repo_root=repo_root,
+ )
+
+ # Totals per edge type and direction come first: they say which relation
+ # kinds exist, so nothing is fetched speculatively, and the rows are cut by
+ # the same rule.
+ row_counts_in = (
+ await _count_neighbors_by_edge_type(session, repo_id, node.node_id, inbound=True)
+ if want_callers
+ else {}
+ )
+ row_counts_out = (
+ await _count_neighbors_by_edge_type(session, repo_id, node.node_id, inbound=False)
+ if want_callees
+ else {}
+ )
+ edges_by_type = await _fetch_edges_by_type(run, row_counts_in, row_counts_out)
+ # Hydrated once for every edge type: the neighbour lookup is the expensive half.
+ run.node_map = await get_graph_nodes_by_ids(
+ session,
+ repo_id,
+ list(
+ {
+ e.source_node_id if e.target_node_id == node.node_id else e.target_node_id
+ for edges in edges_by_type.values()
+ for e in edges
+ }
+ ),
+ )
+
+ relations: list[dict[str, Any]] = []
+ for edge_type, edges in edges_by_type.items():
+ inbound, outbound = _split_edges(run, edge_type, edges)
+ for direction, rows in (("in", inbound), ("out", outbound)):
+ await _place_rows(run, edge_type, direction, rows, relations)
+
+ # An omitted key reads as "not asked for" rather than "none".
+ if want_callers:
+ result_data.setdefault("callers", [])
+ if want_callees:
+ result_data.setdefault("callees", [])
+ await _attach_empty_bases(run)
+ _attach_relations(run, relations, row_counts_in)
+
+
+async def _call_graph_node(session: AsyncSession, repo_id: str, target: str) -> GraphNode | None:
+ """Graph node for *target*, falling back to the bare name for ``file::Name``."""
+ node = await get_graph_node(session, repo_id, target)
+ if node is not None or "::" not in target:
+ return node
+ bare_name = id_segment_name(target.split("::")[-1])
+ res = await session.execute(
+ select(GraphNode).where(
+ GraphNode.repository_id == repo_id,
+ GraphNode.node_type == "symbol",
+ GraphNode.name == bare_name,
+ )
+ )
+ rows = list(res.scalars().all())
+ if not rows:
+ return None
+ file_hint = target.split("::")[0]
+ return next((r for r in rows if r.file_path == file_hint), rows[0])
+
+
+async def _resolve_non_symbol_call_graph(
+ session: AsyncSession,
+ repository: Repository,
+ target: str,
+ node: GraphNode | None,
+ result_data: dict[str, Any],
+ *,
+ want_callers: bool,
+ want_callees: bool,
+ exclude_spec: Any,
+ collector: OmissionCollector | None,
+) -> None:
+ """File targets get the file-level rollup; anything else gets empty lists and a note."""
+ repo_id = repository.id
+ if node is not None and node.node_type == "file" and want_callers:
+ await _resolve_file_level_callers(
+ session, repo_id, node, result_data, exclude_spec, collector, repository=repository
+ )
+ if want_callees:
+ result_data["callees"] = []
+ result_data["callees_basis"] = await call_resolution_basis(
+ session, repo_id, node.language, cache_key=index_state_key(repository)
+ )
+ return
+ if want_callers:
+ result_data["callers"] = []
+ if want_callees:
+ result_data["callees"] = []
+ if node is not None and node.node_type != "symbol":
+ result_data["_call_graph_note"] = (
+ "callers/callees require a symbol target (function/class/method), "
+ f"but '{target}' is a {node.node_type}. Pass a symbol name or file::Symbol."
+ )
+
+
+async def _fetch_edges_by_type(
+ run: _CallGraphRun, row_counts_in: dict[str, int], row_counts_out: dict[str, int]
+) -> dict[str, list[GraphEdge]]:
+ """One fetch per edge type present, each capped on its own.
+
+ One fetch over every use edge type would share a confidence-ranked cap,
+ so the commonest kind could evict the rest.
+ """
+ edges_by_type: dict[str, list[GraphEdge]] = {}
+ for edge_type in sorted(set(row_counts_in) | set(row_counts_out)):
+ want_in = run.want_callers and edge_type in row_counts_in
+ want_out = run.want_callees and edge_type in row_counts_out
+ if not (want_in or want_out):
+ continue
+ edges_by_type[edge_type] = await get_graph_edges_for_node(
+ run.session,
+ run.repository.id,
+ run.node.node_id,
+ direction=("both" if want_in and want_out else ("callers" if want_in else "callees")),
+ edge_types=[edge_type],
+ limit=max(row_counts_in.get(edge_type, 0), row_counts_out.get(edge_type, 0), 1),
+ )
+ return edges_by_type
+
+
+def _neighbor_entry(
+ edge: GraphEdge, other_id: str, node_map: dict[str, Any], *, with_edge_type: bool
+) -> dict[str, Any]:
+ """One row for the symbol at the other end of *edge*."""
+ other_node = node_map.get(other_id)
+ entry: dict[str, Any] = {
+ "symbol_id": other_id,
+ "name": other_node.name
+ if other_node
+ else (other_id.split("::")[-1] if "::" in other_id else other_id),
+ "kind": other_node.kind if other_node else None,
+ "file": other_node.file_path
+ if other_node
+ else (other_id.split("::")[0] if "::" in other_id else other_id),
+ # Definition line of the other symbol.
+ "line": other_node.start_line if other_node else None,
+ "confidence": edge.confidence,
+ }
+ # A relation row's group already names the edge type once.
+ if with_edge_type:
+ entry["edge_type"] = edge.edge_type
+ # Absent on an index built before origins were stamped.
+ if edge.resolution_origin:
+ entry["via"] = edge.resolution_origin
+ return entry
+
+
+def _split_edges(
+ run: _CallGraphRun, edge_type: str, edges: list[GraphEdge]
+) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
+ """Inbound and outbound rows for one edge type, above the confidence floor.
+
+ A self-edge (a recursive call) matches both direction queries, so it is
+ deduped on the edge and then placed on every side it touches.
+ """
+ node_id = run.node.node_id
+ is_call = edge_type == "calls"
+ inbound: list[dict[str, Any]] = []
+ outbound: list[dict[str, Any]] = []
+ for e in {edge.id: edge for edge in edges}.values():
+ if (e.confidence or 0) < _MIN_CALL_CONFIDENCE:
+ continue
+ if e.target_node_id == node_id:
+ row = _neighbor_entry(e, e.source_node_id, run.node_map, with_edge_type=is_call)
+ # ``line`` is where the caller is defined; this is where it calls.
+ if is_call and (call_line := first_call_line(e.call_lines_json)):
+ row["call_line"] = call_line
+ inbound.append(row)
+ if e.source_node_id == node_id:
+ outbound.append(
+ _neighbor_entry(e, e.target_node_id, run.node_map, with_edge_type=is_call)
+ )
+ return inbound, outbound
+
+
+async def _place_rows(
+ run: _CallGraphRun,
+ edge_type: str,
+ direction: str,
+ rows: list[dict[str, Any]],
+ relations: list[dict[str, Any]],
+) -> None:
+ """Rank and dedupe one direction's rows, then serve them as calls or a relation."""
+ rows = filter_dicts_by_key(rows, "file", run.exclude_spec)
+ rows.sort(key=lambda x: -(x.get("confidence") or 0))
+ # One entry per neighbouring symbol; this list is the public true total.
+ rows = _unique_by_symbol(rows)
+ if edge_type == "calls":
+ if run.wants(direction):
+ await _serve_call_rows(run, direction, rows)
+ return
+ relation = _relation_block(run, edge_type, direction, rows)
+ if relation is not None:
+ relations.append(relation)
+
+
+async def _serve_call_rows(run: _CallGraphRun, direction: str, rows: list[dict[str, Any]]) -> None:
+ """Cap ``callers``/``callees``; callers also get wrapper hops and call text."""
+ key = "callers" if direction == "in" else "callees"
+ result_data = run.result_data
+ total = len(rows)
+ # Nearly every symbol fits under the cap; a hub gets explicit truncation counts.
+ limit = _SYMBOL_NEIGHBOR_LIMIT
+ visible = cap_collection(
+ result_data,
+ key,
+ rows,
+ limit,
+ run.collector,
+ label=f"{run.target} :: {key} beyond cap={limit}",
+ )
+ if direction != "in":
+ return
+ if total > len(visible):
+ result_data["_callers_note"] = (
+ f"Showing top {len(visible)} of {total} callers by confidence. "
+ "Recover the omitted rows with get_symbol on the response's "
+ "repowise omission reference; grep remains useful when graph "
+ "coverage itself may be incomplete."
+ )
+ else:
+ # Appended after the direct rows and only under the cap, so the
+ # callers_* counts keep meaning direct callers.
+ hop = await forwarding_wrapper_callers(
+ run.session,
+ run.repository.id,
+ run.node,
+ [r["symbol_id"] for r in visible],
+ known_nodes=run.node_map,
+ )
+ hop = filter_dicts_by_key(hop, "file", run.exclude_spec)
+ if hop:
+ result_data[key] = visible + hop
+ await attach_call_text(run.repo_root, result_data[key], run.node.node_id)
+ # Unserved rows are never checked against the live file.
+ for row in rows[len(visible) :]:
+ row.pop("call_line", None)
+
+
+def _relation_block(
+ run: _CallGraphRun, edge_type: str, direction: str, rows: list[dict[str, Any]]
+) -> dict[str, Any] | None:
+ """A non-call edge type's capped rows, or None when there are none."""
+ total = len(rows)
+ if not total:
+ return None
+ relation: dict[str, Any] = {
+ "edge_type": edge_type,
+ "group": SYMBOL_RELATION_GROUP_OF[edge_type],
+ "direction": direction,
+ "total": total,
+ }
+ cap_collection(
+ relation,
+ "rows",
+ rows,
+ _RELATION_ROW_CAP,
+ run.collector,
+ label=f"{run.target} :: relations.{edge_type}.{direction} beyond cap={_RELATION_ROW_CAP}",
+ )
+ return relation
+
+
+async def _attach_empty_bases(run: _CallGraphRun) -> None:
+ """An empty ``callers``/``callees`` list earns a basis; a populated one is its own evidence."""
+ result_data = run.result_data
+ for key in ("callers", "callees"):
+ if key in result_data and not result_data[key]:
+ result_data[f"{key}_basis"] = await call_resolution_basis(
+ run.session,
+ run.repository.id,
+ run.node.language,
+ cache_key=index_state_key(run.repository),
+ )
+
+
+def _attach_relations(
+ run: _CallGraphRun, relations: list[dict[str, Any]], row_counts_in: dict[str, int]
+) -> None:
+ """Attach sorted ``relations`` and say so when nothing calls the symbol.
+
+ Keyed on the inbound ``calls`` count, not on ``callers`` being empty: an
+ exclusion spec can filter every row while callers still exist.
+ """
+ if not relations:
+ return
+ relations.sort(key=lambda r: (r["direction"], -r["total"], r["edge_type"]))
+ run.result_data["relations"] = relations
+ inbound_kinds = [r for r in relations if r["direction"] == "in"]
+ if run.want_callers and not row_counts_in.get("calls") and inbound_kinds:
+ reached = ", ".join(f"{r['total']} {r['edge_type']}" for r in inbound_kinds)
+ run.result_data["_call_graph_note"] = (
+ f"Nothing calls '{run.node.name}'; it is reached by {reached}. See `relations`."
+ )
+
+
+async def _resolve_file_level_callers(
+ session: AsyncSession,
+ repo_id: str,
+ node: GraphNode,
+ result_data: dict[str, Any],
+ exclude_spec: Any = None,
+ collector: OmissionCollector | None = None,
+ *,
+ repository: Repository | None = None,
+) -> None:
+ """File-target callers: importing files + inbound symbol-call rollup.
+
+ Two granularities merged per caller file: ``imports: true`` when the
+ file imports this one, ``inbound_calls`` counting cross-file call edges
+ into any symbol defined here.
+ """
+ importer_files = await _file_importers(session, repo_id, node)
+ calls_by_file = await _file_inbound_calls(session, repo_id, node)
+
+ entries: list[dict[str, Any]] = []
+ for f in sorted(importer_files | set(calls_by_file)):
+ entry: dict[str, Any] = {"file": f}
+ if f in importer_files:
+ entry["imports"] = True
+ if calls_by_file.get(f):
+ entry["inbound_calls"] = calls_by_file[f]
+ entries.append(entry)
+ entries = filter_dicts_by_key(entries, "file", exclude_spec)
+ entries.sort(key=lambda x: -(x.get("inbound_calls") or 0))
+
+ cap_collection(
+ result_data,
+ "callers",
+ entries,
+ 20,
+ collector,
+ label=f"{node.node_id} :: file callers beyond cap=20",
+ )
+ result_data["_call_graph_note"] = (
+ "File-level rollup: importing files plus inbound cross-file call "
+ "counts. For symbol-precise callers pass 'file.py::Symbol'."
+ )
+ if repository is not None and not result_data.get("callers"):
+ result_data["callers_basis"] = await call_resolution_basis(
+ session, repo_id, node.language, cache_key=index_state_key(repository)
+ )
+
+
+async def _file_importers(session: AsyncSession, repo_id: str, node: GraphNode) -> set[str]:
+ """Files whose inbound ``imports`` edge points at this file node."""
+ import_res = await session.execute(
+ select(GraphEdge).where(
+ GraphEdge.repository_id == repo_id,
+ GraphEdge.target_node_id == node.node_id,
+ GraphEdge.edge_type == "imports",
+ )
+ )
+ import_edges = list(import_res.scalars().all())
+ importer_ids = [e.source_node_id for e in import_edges if e.target_node_id == node.node_id]
+ importer_nodes = await get_graph_nodes_by_ids(session, repo_id, importer_ids)
+ # For file nodes the node_id IS the path; file_path may be unset.
+ return {
+ (n.file_path or n.node_id)
+ for n in importer_nodes.values()
+ if n is not None and (n.file_path or n.node_id)
+ }
+
+
+async def _file_inbound_calls(
+ session: AsyncSession, repo_id: str, node: GraphNode
+) -> dict[str, int]:
+ """Cross-file calls into any symbol defined in this file, counted per calling file."""
+ target_file = node.file_path or node.node_id
+ sym_res = await session.execute(
+ select(GraphNode.node_id).where(
+ GraphNode.repository_id == repo_id,
+ GraphNode.node_type == "symbol",
+ GraphNode.file_path == target_file,
+ )
+ )
+ sym_ids = [row[0] for row in sym_res.all()]
+ calls_by_file: dict[str, int] = {}
+ if not sym_ids:
+ return calls_by_file
+ edge_res = await session.execute(
+ select(GraphEdge.source_node_id, GraphEdge.confidence).where(
+ GraphEdge.repository_id == repo_id,
+ GraphEdge.target_node_id.in_(sym_ids),
+ GraphEdge.edge_type == "calls",
+ )
+ )
+ # The shared projection rule every calls-onto-files surface uses. Its
+ # same-extension guard drops genuine cross-language calls: a known ceiling.
+ for src_id, confidence in edge_res.all():
+ src_file = node_to_file(src_id)
+ if not keep_projected_edge(src_file, target_file, "calls", confidence):
+ continue
+ calls_by_file[src_file] = calls_by_file.get(src_file, 0) + 1
+ return calls_by_file
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py b/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py
index afb8494e4..145c3723b 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py
@@ -1,23 +1,19 @@
"""Optional enrichment blocks for get_context.
-Each helper resolves one ``include=`` block (callers/callees, metrics,
-community, health) and attaches it to ``result_data`` in place. They are split
-out of the main target resolver so the orchestrator and the resolver read as
-dispatch rather than one long body.
+Each helper resolves one ``include=`` block and attaches it to ``result_data``
+in place: call graph in ``call_graph``, metrics / community / health in
+``signals``, skeleton in ``skeleton``, document references here. This module
+re-exports the others so callers keep one import path.
"""
from __future__ import annotations
-import json
from collections import Counter
-from dataclasses import asdict, dataclass, field
from typing import Any
-from sqlalchemy import func, select
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.ext.asyncio import AsyncSession
-from repowise.core.analysis.communities import has_community
from repowise.core.analysis.doc_drift.constants import (
REFERENCE_BASIS,
UNAVAILABLE_NO_TABLE,
@@ -28,55 +24,36 @@ from repowise.core.analysis.doc_drift.serialize import (
collapse_reference_sites,
documents_with_drift,
)
-from repowise.core.analysis.finding_registry import excluded_types
-from repowise.core.analysis.health.complexity.languages import NO_DIALECT_STATUS
-from repowise.core.analysis.health.signals import file_signals
-from repowise.core.ingestion.models import (
- FILE_DEPENDENCY_EDGE_TYPES,
- SYMBOL_USE_EDGE_TYPES,
-)
-from repowise.core.ingestion.symbol_identity import id_segment_name
from repowise.core.persistence.crud import (
- coverage_row_dict,
doc_drift_references_stored,
- get_all_file_metrics,
- get_community_members,
- get_cross_community_edges,
get_doc_drift_findings,
get_doc_drift_references,
- get_git_metadata,
- get_graph_edges_for_node,
- get_graph_node,
- get_graph_nodes_by_ids,
- get_node_degree_counts,
- load_coverage_for_repo,
serialize_doc_drift_reference_row,
)
-from repowise.core.persistence.crud.analysis.shown import ungated
-from repowise.core.persistence.models import (
- GraphEdge,
- GraphNode,
- HealthFileMetric,
- HealthFinding,
- Repository,
+from repowise.core.persistence.models import Repository
+from repowise.server.mcp_server._budget import OmissionCollector, cap_collection
+from repowise.server.mcp_server._helpers import filter_rows_by_attr, is_missing_table
+from repowise.server.mcp_server.tool_context.call_graph import ( # noqa: F401
+ _CALL_EDGE_TYPES,
+ _MIN_CALL_CONFIDENCE,
+ _RELATION_ROW_CAP,
+ _SYMBOL_NEIGHBOR_LIMIT,
+ _SYMBOL_USE_EDGE_TYPES,
+ _count_neighbors_by_edge_type,
+ _resolve_call_graph,
+ _resolve_file_level_callers,
+ _unique_by_symbol,
)
-from repowise.server.mcp_server._basis import call_resolution_basis
-from repowise.server.mcp_server._budget import (
- DEFAULT_RESPONSE_CHARS,
- OmissionCollector,
- cap_collection,
+from repowise.server.mcp_server.tool_context.signals import ( # noqa: F401
+ _FILE_DEPENDENCY_EDGE_TYPES,
+ _resolve_community,
+ _resolve_health,
+ _resolve_metrics,
)
-from repowise.server.mcp_server._edit_sites import attach_call_text, first_call_line
-from repowise.server.mcp_server._graph_files import keep_projected_edge, node_to_file
-from repowise.server.mcp_server._helpers import (
- filter_dicts_by_key,
- filter_path_list,
- filter_rows_by_attr,
- is_missing_table,
+from repowise.server.mcp_server.tool_context.skeleton import ( # noqa: F401
+ _FOCUS_CONTAINER_MAX_CHARS,
+ _resolve_skeleton,
)
-from repowise.server.mcp_server._index_state import index_state_key
-from repowise.server.mcp_server._wrapper_callers import forwarding_wrapper_callers
-from repowise.server.schemas.intelligence import SYMBOL_RELATION_GROUP_OF
#: Where a resolved target path waits between its card being built and the
#: batched doc-drift read. Popped by that pass, so it never reaches a response.
@@ -86,805 +63,6 @@ _DOC_DRIFT_PATH = "_doc_drift_path"
#: ``targets._MAX_USED_BY``, for the same "who points at this" question.
_MAX_DOC_REFERENCES = 20
-# Minimum confidence for call edges to filter false positives.
-#
-# Symbol-level only. The file-level rollup below defers to the shared
-# ``_graph_files`` floor (0.5) that every other file-pair surface uses; this
-# one stays at 0.7 because the two sites that read it -- the totals query and
-# the symbol rows -- have to be cut by the same rule as each other, and that
-# rule is documented at ``_count_neighbors_by_edge_type``.
-_MIN_CALL_CONFIDENCE = 0.7
-
-# Every edge type meaning "something reaches this symbol". Sorted so the
-# generated SQL is stable; the shared view is the source of truth.
-#
-# The private copy this replaced omitted `method_implements`, so a Go type
-# satisfying an interface was neither a caller nor a callee of it — +2,799
-# edges across 42 local indexes, all of them in Go repos.
-#
-# It also omitted `reads`, and that member is worth naming precisely rather
-# than counting as another fixed omission. At the symbol layer `reads` has one
-# producer, `framework_edges/express.py`, which joins a file's synthetic
-# `path::__module__` node to a route handler in the same file. So it admits
-# exactly one edge across all 42 indexes, and what it admits is a `__module__`
-# entry in an Express handler's caller list. Taking the shared view whole is
-# still right: hand-trimming a member here is how the private sets started.
-#
-# It is the right set for *degree* and the wrong one for `callers`: a subclass
-# reaches its base without ever calling it. Only `calls` populates
-# callers/callees now; `_RELATION_EDGE_TYPES` carries the rest, named.
-_SYMBOL_USE_EDGE_TYPES = sorted(SYMBOL_USE_EDGE_TYPES)
-
-#: The one edge type that is literally a call. Everything else that reaches a
-#: symbol is reported by kind under `relations` instead of being poured into
-#: `callers`. Measured on this repo's own index: 9.1% of rows served under
-#: `callers` were not calls, and on 705 symbols *every* row was not a call — a
-#: pytest fixture was reported as having 388 callers, with a note telling the
-#: agent to grep for a call site that does not exist.
-#:
-#: `tool_symbol._expand_callees` imports this for its `callee_bodies` walk, so
-#: widening it again would serve base-class and framework-wiring *source* as
-#: callees for three hops. Keep it meaning what it is named.
-_CALL_EDGE_TYPES = ["calls"]
-
-#: Maximum caller/callee rows returned for one symbol. Kept as a named seam so
-#: contract tests can force an omission without depending on response size or
-#: platform-specific serialization details.
-_SYMBOL_NEIGHBOR_LIMIT = 50
-
-#: Rows carried per relation kind. Deliberately far below the call cap: the
-#: agent question these answer is "what else reaches this, and how", which the
-#: kind and the honest total answer. Naming them costs less than the
-#: mislabelled rows it removes — measured net −27% on the affected symbols.
-_RELATION_ROW_CAP = 5
-
-# Degree reported for a FILE. `file_signals` states it as "N files depend on
-# this", so it is counted over file dependencies rather than every adjacent
-# row, which would add one per symbol the file declares.
-_FILE_DEPENDENCY_EDGE_TYPES = sorted(FILE_DEPENDENCY_EDGE_TYPES)
-
-
-def _unique_by_symbol(entries: list[dict[str, Any]]) -> list[dict[str, Any]]:
- """Collapse entries sharing a ``symbol_id``, keeping the first.
-
- Order-preserving, so callers sort by confidence before calling this and
- the survivor is the highest-confidence edge to that symbol.
- """
- seen: set[str] = set()
- out: list[dict[str, Any]] = []
- for entry in entries:
- symbol_id = str(entry.get("symbol_id"))
- if symbol_id in seen:
- continue
- seen.add(symbol_id)
- out.append(entry)
- return out
-
-
-async def _count_neighbors_by_edge_type(
- session: AsyncSession, repo_id: str, node_id: str, *, inbound: bool
-) -> dict[str, int]:
- """Count qualifying edge rows per type to size each directional fetch.
-
- The emitted true total is computed after policy filtering and symbol
- deduplication. These raw counts only ensure each ranked fetch is large
- enough to contain that complete post-policy population.
- """
- matched = GraphEdge.target_node_id if inbound else GraphEdge.source_node_id
- stmt = (
- select(GraphEdge.edge_type, func.count(GraphEdge.id))
- .where(
- GraphEdge.repository_id == repo_id,
- matched == node_id,
- GraphEdge.edge_type.in_(_SYMBOL_USE_EDGE_TYPES),
- GraphEdge.confidence >= _MIN_CALL_CONFIDENCE,
- )
- .group_by(GraphEdge.edge_type)
- )
- return {edge_type: int(n or 0) for edge_type, n in await session.execute(stmt)}
-
-
-@dataclass
-class _CallGraphRun:
- """One symbol's call-graph request plus the neighbour nodes fetched for it."""
-
- session: AsyncSession
- repository: Repository
- target: str
- node: GraphNode
- result_data: dict[str, Any]
- want_callers: bool
- want_callees: bool
- exclude_spec: Any
- collector: OmissionCollector | None
- repo_root: Any
- node_map: dict[str, Any] = field(default_factory=dict)
-
- def wants(self, direction: str) -> bool:
- return self.want_callers if direction == "in" else self.want_callees
-
-
-async def _resolve_call_graph(
- session: AsyncSession,
- repository: Repository,
- target: str,
- target_type: str | None,
- result_data: dict[str, Any],
- *,
- want_callers: bool = False,
- want_callees: bool = False,
- exclude_spec: Any = None,
- collector: OmissionCollector | None = None,
- repo_root: Any = None,
-) -> None:
- """Resolve callers/callees for a symbol and attach to result_data.
-
- Served call rows carry ``call_line`` and, read from *repo_root*, its ``text``.
- """
- repo_id = repository.id
- node = await _call_graph_node(session, repo_id, target)
- if node is None or node.node_type != "symbol":
- await _resolve_non_symbol_call_graph(
- session,
- repository,
- target,
- node,
- result_data,
- want_callers=want_callers,
- want_callees=want_callees,
- exclude_spec=exclude_spec,
- collector=collector,
- )
- return
- run = _CallGraphRun(
- session=session,
- repository=repository,
- target=target,
- node=node,
- result_data=result_data,
- want_callers=want_callers,
- want_callees=want_callees,
- exclude_spec=exclude_spec,
- collector=collector,
- repo_root=repo_root,
- )
-
- # Totals per edge type and direction come first: they say which relation
- # kinds exist, so nothing is fetched speculatively, and the rows are cut by
- # the same rule.
- row_counts_in = (
- await _count_neighbors_by_edge_type(session, repo_id, node.node_id, inbound=True)
- if want_callers
- else {}
- )
- row_counts_out = (
- await _count_neighbors_by_edge_type(session, repo_id, node.node_id, inbound=False)
- if want_callees
- else {}
- )
- edges_by_type = await _fetch_edges_by_type(run, row_counts_in, row_counts_out)
- # Hydrated once for every edge type: the neighbour lookup is the expensive half.
- run.node_map = await get_graph_nodes_by_ids(
- session,
- repo_id,
- list(
- {
- e.source_node_id if e.target_node_id == node.node_id else e.target_node_id
- for edges in edges_by_type.values()
- for e in edges
- }
- ),
- )
-
- relations: list[dict[str, Any]] = []
- for edge_type, edges in edges_by_type.items():
- inbound, outbound = _split_edges(run, edge_type, edges)
- for direction, rows in (("in", inbound), ("out", outbound)):
- await _place_rows(run, edge_type, direction, rows, relations)
-
- # An omitted key reads as "not asked for" rather than "none".
- if want_callers:
- result_data.setdefault("callers", [])
- if want_callees:
- result_data.setdefault("callees", [])
- await _attach_empty_bases(run)
- _attach_relations(run, relations, row_counts_in)
-
-
-async def _call_graph_node(session: AsyncSession, repo_id: str, target: str) -> GraphNode | None:
- """Graph node for *target*, falling back to the bare name for ``file::Name``."""
- node = await get_graph_node(session, repo_id, target)
- if node is not None or "::" not in target:
- return node
- bare_name = id_segment_name(target.split("::")[-1])
- res = await session.execute(
- select(GraphNode).where(
- GraphNode.repository_id == repo_id,
- GraphNode.node_type == "symbol",
- GraphNode.name == bare_name,
- )
- )
- rows = list(res.scalars().all())
- if not rows:
- return None
- file_hint = target.split("::")[0]
- return next((r for r in rows if r.file_path == file_hint), rows[0])
-
-
-async def _resolve_non_symbol_call_graph(
- session: AsyncSession,
- repository: Repository,
- target: str,
- node: GraphNode | None,
- result_data: dict[str, Any],
- *,
- want_callers: bool,
- want_callees: bool,
- exclude_spec: Any,
- collector: OmissionCollector | None,
-) -> None:
- """File targets get the file-level rollup; anything else gets empty lists and a note."""
- repo_id = repository.id
- if node is not None and node.node_type == "file" and want_callers:
- await _resolve_file_level_callers(
- session, repo_id, node, result_data, exclude_spec, collector, repository=repository
- )
- if want_callees:
- result_data["callees"] = []
- result_data["callees_basis"] = await call_resolution_basis(
- session, repo_id, node.language, cache_key=index_state_key(repository)
- )
- return
- if want_callers:
- result_data["callers"] = []
- if want_callees:
- result_data["callees"] = []
- if node is not None and node.node_type != "symbol":
- result_data["_call_graph_note"] = (
- "callers/callees require a symbol target (function/class/method), "
- f"but '{target}' is a {node.node_type}. Pass a symbol name or file::Symbol."
- )
-
-
-async def _fetch_edges_by_type(
- run: _CallGraphRun, row_counts_in: dict[str, int], row_counts_out: dict[str, int]
-) -> dict[str, list[GraphEdge]]:
- """One fetch per edge type present, each capped on its own.
-
- One fetch over every use edge type would share a confidence-ranked cap,
- so the commonest kind could evict the rest.
- """
- edges_by_type: dict[str, list[GraphEdge]] = {}
- for edge_type in sorted(set(row_counts_in) | set(row_counts_out)):
- want_in = run.want_callers and edge_type in row_counts_in
- want_out = run.want_callees and edge_type in row_counts_out
- if not (want_in or want_out):
- continue
- edges_by_type[edge_type] = await get_graph_edges_for_node(
- run.session,
- run.repository.id,
- run.node.node_id,
- direction=("both" if want_in and want_out else ("callers" if want_in else "callees")),
- edge_types=[edge_type],
- limit=max(row_counts_in.get(edge_type, 0), row_counts_out.get(edge_type, 0), 1),
- )
- return edges_by_type
-
-
-def _neighbor_entry(
- edge: GraphEdge, other_id: str, node_map: dict[str, Any], *, with_edge_type: bool
-) -> dict[str, Any]:
- """One row for the symbol at the other end of *edge*."""
- other_node = node_map.get(other_id)
- entry: dict[str, Any] = {
- "symbol_id": other_id,
- "name": other_node.name
- if other_node
- else (other_id.split("::")[-1] if "::" in other_id else other_id),
- "kind": other_node.kind if other_node else None,
- "file": other_node.file_path
- if other_node
- else (other_id.split("::")[0] if "::" in other_id else other_id),
- # Definition line of the other symbol.
- "line": other_node.start_line if other_node else None,
- "confidence": edge.confidence,
- }
- # A relation row's group already names the edge type once.
- if with_edge_type:
- entry["edge_type"] = edge.edge_type
- # Absent on an index built before origins were stamped.
- if edge.resolution_origin:
- entry["via"] = edge.resolution_origin
- return entry
-
-
-def _split_edges(
- run: _CallGraphRun, edge_type: str, edges: list[GraphEdge]
-) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
- """Inbound and outbound rows for one edge type, above the confidence floor.
-
- A self-edge (a recursive call) matches both direction queries, so it is
- deduped on the edge and then placed on every side it touches.
- """
- node_id = run.node.node_id
- is_call = edge_type == "calls"
- inbound: list[dict[str, Any]] = []
- outbound: list[dict[str, Any]] = []
- for e in {edge.id: edge for edge in edges}.values():
- if (e.confidence or 0) < _MIN_CALL_CONFIDENCE:
- continue
- if e.target_node_id == node_id:
- row = _neighbor_entry(e, e.source_node_id, run.node_map, with_edge_type=is_call)
- # ``line`` is where the caller is defined; this is where it calls.
- if is_call and (call_line := first_call_line(e.call_lines_json)):
- row["call_line"] = call_line
- inbound.append(row)
- if e.source_node_id == node_id:
- outbound.append(
- _neighbor_entry(e, e.target_node_id, run.node_map, with_edge_type=is_call)
- )
- return inbound, outbound
-
-
-async def _place_rows(
- run: _CallGraphRun,
- edge_type: str,
- direction: str,
- rows: list[dict[str, Any]],
- relations: list[dict[str, Any]],
-) -> None:
- """Rank and dedupe one direction's rows, then serve them as calls or a relation."""
- rows = filter_dicts_by_key(rows, "file", run.exclude_spec)
- rows.sort(key=lambda x: -(x.get("confidence") or 0))
- # One entry per neighbouring symbol; this list is the public true total.
- rows = _unique_by_symbol(rows)
- if edge_type == "calls":
- if run.wants(direction):
- await _serve_call_rows(run, direction, rows)
- return
- relation = _relation_block(run, edge_type, direction, rows)
- if relation is not None:
- relations.append(relation)
-
-
-async def _serve_call_rows(run: _CallGraphRun, direction: str, rows: list[dict[str, Any]]) -> None:
- """Cap ``callers``/``callees``; callers also get wrapper hops and call text."""
- key = "callers" if direction == "in" else "callees"
- result_data = run.result_data
- total = len(rows)
- # Nearly every symbol fits under the cap; a hub gets explicit truncation counts.
- limit = _SYMBOL_NEIGHBOR_LIMIT
- visible = cap_collection(
- result_data,
- key,
- rows,
- limit,
- run.collector,
- label=f"{run.target} :: {key} beyond cap={limit}",
- )
- if direction != "in":
- return
- if total > len(visible):
- result_data["_callers_note"] = (
- f"Showing top {len(visible)} of {total} callers by confidence. "
- "Recover the omitted rows with get_symbol on the response's "
- "repowise omission reference; grep remains useful when graph "
- "coverage itself may be incomplete."
- )
- else:
- # Appended after the direct rows and only under the cap, so the
- # callers_* counts keep meaning direct callers.
- hop = await forwarding_wrapper_callers(
- run.session,
- run.repository.id,
- run.node,
- [r["symbol_id"] for r in visible],
- known_nodes=run.node_map,
- )
- hop = filter_dicts_by_key(hop, "file", run.exclude_spec)
- if hop:
- result_data[key] = visible + hop
- await attach_call_text(run.repo_root, result_data[key], run.node.node_id)
- # Unserved rows are never checked against the live file.
- for row in rows[len(visible) :]:
- row.pop("call_line", None)
-
-
-def _relation_block(
- run: _CallGraphRun, edge_type: str, direction: str, rows: list[dict[str, Any]]
-) -> dict[str, Any] | None:
- """A non-call edge type's capped rows, or None when there are none."""
- total = len(rows)
- if not total:
- return None
- relation: dict[str, Any] = {
- "edge_type": edge_type,
- "group": SYMBOL_RELATION_GROUP_OF[edge_type],
- "direction": direction,
- "total": total,
- }
- cap_collection(
- relation,
- "rows",
- rows,
- _RELATION_ROW_CAP,
- run.collector,
- label=f"{run.target} :: relations.{edge_type}.{direction} beyond cap={_RELATION_ROW_CAP}",
- )
- return relation
-
-
-async def _attach_empty_bases(run: _CallGraphRun) -> None:
- """An empty ``callers``/``callees`` list earns a basis; a populated one is its own evidence."""
- result_data = run.result_data
- for key in ("callers", "callees"):
- if key in result_data and not result_data[key]:
- result_data[f"{key}_basis"] = await call_resolution_basis(
- run.session,
- run.repository.id,
- run.node.language,
- cache_key=index_state_key(run.repository),
- )
-
-
-def _attach_relations(
- run: _CallGraphRun, relations: list[dict[str, Any]], row_counts_in: dict[str, int]
-) -> None:
- """Attach sorted ``relations`` and say so when nothing calls the symbol.
-
- Keyed on the inbound ``calls`` count, not on ``callers`` being empty: an
- exclusion spec can filter every row while callers still exist.
- """
- if not relations:
- return
- relations.sort(key=lambda r: (r["direction"], -r["total"], r["edge_type"]))
- run.result_data["relations"] = relations
- inbound_kinds = [r for r in relations if r["direction"] == "in"]
- if run.want_callers and not row_counts_in.get("calls") and inbound_kinds:
- reached = ", ".join(f"{r['total']} {r['edge_type']}" for r in inbound_kinds)
- run.result_data["_call_graph_note"] = (
- f"Nothing calls '{run.node.name}'; it is reached by {reached}. See `relations`."
- )
-
-
-async def _resolve_file_level_callers(
- session: AsyncSession,
- repo_id: str,
- node: GraphNode,
- result_data: dict[str, Any],
- exclude_spec: Any = None,
- collector: OmissionCollector | None = None,
- *,
- repository: Repository | None = None,
-) -> None:
- """File-target callers: importing files + inbound symbol-call rollup.
-
- Two granularities merged per caller file: ``imports: true`` when the
- file imports this one, ``inbound_calls`` counting cross-file call edges
- into any symbol defined here.
- """
- importer_files = await _file_importers(session, repo_id, node)
- calls_by_file = await _file_inbound_calls(session, repo_id, node)
-
- entries: list[dict[str, Any]] = []
- for f in sorted(importer_files | set(calls_by_file)):
- entry: dict[str, Any] = {"file": f}
- if f in importer_files:
- entry["imports"] = True
- if calls_by_file.get(f):
- entry["inbound_calls"] = calls_by_file[f]
- entries.append(entry)
- entries = filter_dicts_by_key(entries, "file", exclude_spec)
- entries.sort(key=lambda x: -(x.get("inbound_calls") or 0))
-
- cap_collection(
- result_data,
- "callers",
- entries,
- 20,
- collector,
- label=f"{node.node_id} :: file callers beyond cap=20",
- )
- result_data["_call_graph_note"] = (
- "File-level rollup: importing files plus inbound cross-file call "
- "counts. For symbol-precise callers pass 'file.py::Symbol'."
- )
- if repository is not None and not result_data.get("callers"):
- result_data["callers_basis"] = await call_resolution_basis(
- session, repo_id, node.language, cache_key=index_state_key(repository)
- )
-
-
-async def _file_importers(session: AsyncSession, repo_id: str, node: GraphNode) -> set[str]:
- """Files whose inbound ``imports`` edge points at this file node."""
- import_res = await session.execute(
- select(GraphEdge).where(
- GraphEdge.repository_id == repo_id,
- GraphEdge.target_node_id == node.node_id,
- GraphEdge.edge_type == "imports",
- )
- )
- import_edges = list(import_res.scalars().all())
- importer_ids = [e.source_node_id for e in import_edges if e.target_node_id == node.node_id]
- importer_nodes = await get_graph_nodes_by_ids(session, repo_id, importer_ids)
- # For file nodes the node_id IS the path; file_path may be unset.
- return {
- (n.file_path or n.node_id)
- for n in importer_nodes.values()
- if n is not None and (n.file_path or n.node_id)
- }
-
-
-async def _file_inbound_calls(
- session: AsyncSession, repo_id: str, node: GraphNode
-) -> dict[str, int]:
- """Cross-file calls into any symbol defined in this file, counted per calling file."""
- target_file = node.file_path or node.node_id
- sym_res = await session.execute(
- select(GraphNode.node_id).where(
- GraphNode.repository_id == repo_id,
- GraphNode.node_type == "symbol",
- GraphNode.file_path == target_file,
- )
- )
- sym_ids = [row[0] for row in sym_res.all()]
- calls_by_file: dict[str, int] = {}
- if not sym_ids:
- return calls_by_file
- edge_res = await session.execute(
- select(GraphEdge.source_node_id, GraphEdge.confidence).where(
- GraphEdge.repository_id == repo_id,
- GraphEdge.target_node_id.in_(sym_ids),
- GraphEdge.edge_type == "calls",
- )
- )
- # The shared projection rule every calls-onto-files surface uses. Its
- # same-extension guard drops genuine cross-language calls: a known ceiling.
- for src_id, confidence in edge_res.all():
- src_file = node_to_file(src_id)
- if not keep_projected_edge(src_file, target_file, "calls", confidence):
- continue
- calls_by_file[src_file] = calls_by_file.get(src_file, 0) + 1
- return calls_by_file
-
-
-async def _resolve_metrics(
- session: AsyncSession,
- repository: Repository,
- target: str,
- result_data: dict[str, Any],
-) -> None:
- """Resolve graph importance metrics and attach to result_data["metrics"]."""
- repo_id = repository.id
-
- node = await get_graph_node(session, repo_id, target)
- if node is None:
- result_data["metrics"] = None
- return
-
- try:
- meta = json.loads(node.community_meta_json or "{}")
- except (json.JSONDecodeError, TypeError):
- meta = {}
-
- # Scoped by layer, because "degree" means a different edge set on each: a
- # file's neighbours are files, a symbol's are symbols. Unscoped, a symbol's
- # in-degree always counted the containment edge from its own declaring file
- # or class, and a file's out-degree counted one edge per symbol it declares.
- degrees = await get_node_degree_counts(
- session,
- repo_id,
- node.node_id,
- edge_types=(
- # Degree is "how connected is this symbol", so it stays over every
- # use edge type even though `callers` narrowed to calls. Matching
- # `routers/graph/intelligence.py`, which reports the same number.
- _SYMBOL_USE_EDGE_TYPES
- if node.node_type == "symbol"
- else _FILE_DEPENDENCY_EDGE_TYPES
- ),
- )
-
- # Percentile computation against same-type peers
- all_nodes = await get_all_file_metrics(session, repo_id)
- pr_values = [n.pagerank for n in all_nodes if n.pagerank is not None]
- bt_values = [n.betweenness for n in all_nodes if n.betweenness is not None]
-
- def _pct(value: float, all_vals: list[float]) -> int:
- if not all_vals:
- return 0
- return round(100 * sum(1 for v in all_vals if v < value) / len(all_vals))
-
- metrics: dict[str, Any] = {
- "pagerank": round(node.pagerank or 0.0, 6),
- "pagerank_percentile": _pct(node.pagerank or 0.0, pr_values),
- "in_degree": degrees["in_degree"],
- "out_degree": degrees["out_degree"],
- "community_id": node.community_id,
- "community_label": meta.get("label") or None,
- }
- # A node added since the last scoring holds the column default and has
- # never been measured. Reporting that 0.0 would read as "on no shortest
- # path" — the opposite claim for a symbol just spliced into a hot call
- # chain.
- if node.betweenness_commit is None:
- metrics["betweenness"] = None
- metrics["betweenness_note"] = "not scored yet: added since the last centrality run"
- else:
- metrics["betweenness"] = round(node.betweenness or 0.0, 6)
- metrics["betweenness_percentile"] = _pct(node.betweenness or 0.0, bt_values)
- result_data["metrics"] = metrics
-
-
-async def _resolve_community(
- session: AsyncSession,
- repository: Repository,
- target: str,
- result_data: dict[str, Any],
- *,
- exclude_spec: Any = None,
-) -> None:
- """Resolve community membership and attach to result_data["community"]."""
- repo_id = repository.id
-
- node = await get_graph_node(session, repo_id, target)
- if node is None or not has_community(node.community_id):
- result_data["community"] = None
- return
-
- try:
- meta = json.loads(node.community_meta_json or "{}")
- except (json.JSONDecodeError, TypeError):
- meta = {}
-
- label = meta.get("label") or f"cluster_{node.community_id}"
- cohesion = float(meta.get("cohesion", 0.0) or 0.0)
-
- # Get top members (cap at 10 for compact output)
- members = await get_community_members(session, repo_id, node.community_id, limit=10)
- member_paths = filter_path_list([m.node_id for m in members], exclude_spec)
-
- # Neighboring communities (cap at 5)
- cross_edges = await get_cross_community_edges(session, repo_id, node.community_id)
- neighbors: list[dict[str, Any]] = []
- for ce in cross_edges[:5]:
- nid = ce["target_community_id"]
- nm = await get_community_members(session, repo_id, nid, limit=1)
- nlabel = ""
- if nm:
- try:
- nmeta = json.loads(nm[0].community_meta_json or "{}")
- nlabel = nmeta.get("label", "")
- except (json.JSONDecodeError, TypeError):
- pass
- neighbors.append(
- {
- "id": nid,
- "label": nlabel or f"cluster_{nid}",
- "cross_edges": ce["edge_count"],
- }
- )
-
- result_data["community"] = {
- "id": node.community_id,
- "label": label,
- "cohesion": round(cohesion, 3),
- "top_members": member_paths,
- "neighbors": neighbors,
- }
-
-
-async def _resolve_health(
- session: AsyncSession,
- repository: Repository,
- target: str,
- target_type: str,
- result_data: dict[str, Any],
-) -> None:
- """Attach per-file health metric + top 2 biomarkers + coverage row.
-
- Only meaningful for *file* targets. For symbol targets we resolve the
- enclosing file path via the already-computed ``file_path_for_git`` is
- not available here — we fall back to ``target`` when ``target_type``
- is ``"file"`` and otherwise inspect the target string for a
- ``"path::symbol"`` separator.
- """
- file_path: str | None
- if target_type == "file":
- file_path = target
- elif "::" in target:
- file_path = target.split("::", 1)[0]
- else:
- file_path = None
-
- if not file_path:
- result_data["health"] = None
- return
-
- repo_id = repository.id
- metric = (
- await session.execute(
- select(HealthFileMetric).where(
- HealthFileMetric.repository_id == repo_id,
- HealthFileMetric.file_path == file_path,
- )
- )
- ).scalar_one_or_none()
-
- if metric is None:
- result_data["health"] = None
- return
-
- findings_res = await session.execute(
- select(HealthFinding)
- .where(
- HealthFinding.repository_id == repo_id,
- HealthFinding.file_path == file_path,
- HealthFinding.status == "open",
- HealthFinding.biomarker_type.not_in(excluded_types()),
- ungated("health", HealthFinding.file_path, HealthFinding.biomarker_type),
- )
- .order_by(HealthFinding.health_impact.desc())
- .limit(2)
- )
- from repowise.core.analysis.health.suggestions import suggestion_for
-
- top_biomarkers = [
- {
- "biomarker_type": f.biomarker_type,
- "severity": f.severity,
- # Absent rather than null on a file-level biomarker, same as the
- # identical field on get_risk's cards.
- **({"function_name": f.function_name} if f.function_name else {}),
- "impact": round(f.health_impact, 2),
- "suggestion": suggestion_for(f.biomarker_type),
- }
- for f in findings_res.scalars().all()
- ]
-
- coverage_rows = await load_coverage_for_repo(
- session, repo_id, file_paths=[file_path], include_covered_lines=False
- )
-
- health: dict[str, Any] = {
- "score": round(metric.score, 2) if metric.score is not None else None,
- # Said in words, so a missing score is not read as a missing index.
- **({"analysis_status": NO_DIALECT_STATUS} if metric.score is None else {}),
- "max_ccn": metric.max_ccn,
- "max_nesting": metric.max_nesting,
- "nloc": metric.nloc,
- "has_test_file": metric.has_test_file,
- "module": metric.module,
- "duplication_pct": metric.duplication_pct,
- "top_biomarkers": top_biomarkers,
- }
- if coverage_rows:
- health["coverage"] = coverage_row_dict(coverage_rows[0], include_covered_lines=False)
- elif metric.line_coverage_pct is not None:
- health["coverage"] = {
- "line_coverage_pct": metric.line_coverage_pct,
- "branch_coverage_pct": metric.branch_coverage_pct,
- }
-
- # Process / people / topology signals — the "should I touch this file"
- # context an agent can't get from the score alone. Null fields are dropped
- # so the block stays compact; absent entirely when the file has neither git
- # history nor a graph node.
- git_meta = await get_git_metadata(session, repo_id, file_path)
- node = await get_graph_node(session, repo_id, file_path)
- degrees = (
- await get_node_degree_counts(
- session, repo_id, file_path, edge_types=_FILE_DEPENDENCY_EDGE_TYPES
- )
- if node is not None
- else None
- )
- signals = {k: v for k, v in asdict(file_signals(git_meta, degrees)).items() if v is not None}
- if signals:
- health["signals"] = signals
-
- result_data["health"] = health
-
async def attach_doc_references(
session: AsyncSession,
@@ -1018,160 +196,3 @@ def _doc_reference_block(
# read as proof that nothing documents this file.
block["references_basis"] = REFERENCE_BASIS
return block
-
-
-#: Same threshold get_symbol uses to outline a container instead of inlining it.
-_FOCUS_CONTAINER_MAX_CHARS = DEFAULT_RESPONSE_CHARS // 2
-
-
-async def _resolve_skeleton(
- session: AsyncSession,
- repository: Repository,
- target: str,
- target_type: str | None,
- result_data: dict[str, Any],
- *,
- repo_root: Any = None,
- mode: str = "smart",
-) -> None:
- """Resolve ``include=["skeleton"]`` — a body-elided rendering of one file.
-
- Slices the on-disk source on the line bounds persisted at index time
- (zero parsing), keeping every signature and the bodies of the
- highest-PageRank symbols under a token budget. ``include=["skeleton+"]``
- passes ``mode="plus"``: all non-function code kept, every function and
- method body elided. A ``file.py::Symbol`` target renders its file with
- that symbol's whole body and every other symbol as its signature.
- """
- # A "file.py::Symbol" target still has a useful skeleton — the file that
- # defines the symbol. Strip the suffix and skeleton that file rather than
- # failing on a literal path containing "::" (which surfaced as the opaque
- # "Source file could not be read" in the S2 dogfood). Module/other
- # non-file targets with no "::" have no file to render.
- is_symbol_target = "::" in target
- file_target = target.split("::", 1)[0] if is_symbol_target else target
- if not is_symbol_target and target_type != "file":
- result_data["skeleton"] = {"error": "skeleton requires a file target; pass the file path."}
- return
- if not repo_root:
- result_data["skeleton"] = {"error": "MCP server has no repo path configured."}
- return
-
- from pathlib import Path
-
- from repowise.core.distill.skeleton import SkeletonSymbol, build_skeleton
- from repowise.core.persistence.models import WikiSymbol
- from repowise.server.mcp_server._symbol_lookup import symbol_id_variants
-
- repo_id = repository.id
- res = await session.execute(
- select(WikiSymbol).where(
- WikiSymbol.repository_id == repo_id,
- WikiSymbol.file_path == file_target,
- )
- )
- rows = list(res.scalars().all())
-
- # Symbol-node PageRank is the importance signal for smart body retention.
- pr_res = await session.execute(
- select(GraphNode.name, GraphNode.pagerank).where(
- GraphNode.repository_id == repo_id,
- GraphNode.node_type == "symbol",
- GraphNode.file_path == file_target,
- )
- )
- pagerank = {name: pr or 0.0 for name, pr in pr_res.all() if name}
-
- repo_path = Path(str(repo_root))
- abs_path = (repo_path / file_target).resolve()
- try:
- abs_path.relative_to(repo_path.resolve())
- source = abs_path.read_text(encoding="utf-8", errors="replace")
- except (OSError, ValueError):
- result_data["skeleton"] = {
- "error": "Source file could not be read; it may have moved since indexing."
- }
- return
-
- # Trust contract: the skeleton is sliced on stored bounds but claims
- # ``verified: True``. Gate each row against the live source first (cheap
- # string check; a re-parse fires only on a miss) so a drifted bound can't
- # render the wrong lines as a signature. Corrected rows render at their real
- # bounds; a symbol that moved and can't be re-located is dropped rather than
- # garbling the skeleton (its region collapses into an elision marker), which
- # keeps the ``verified`` claim honest. Healing is left to get_symbol / the
- # hydrator / incremental update, which hold a writable session on their path.
- from repowise.server.mcp_server._verify import check_symbol_bounds
-
- focus_ids = set(symbol_id_variants(target)) if is_symbol_target else set()
- source_lines = source.splitlines()
- symbols = []
- for r in rows:
- check = check_symbol_bounds(r, source)
- if check.approximate:
- continue
- focus = r.symbol_id in focus_ids
- if focus and r.kind not in ("function", "method"):
- # Ceiling: a container body over the get_symbol outline threshold is
- # not inlined; the ranked skeleton shows its methods as signatures.
- span = source_lines[check.start_line - 1 : check.end_line]
- focus = sum(len(ln) + 1 for ln in span) <= _FOCUS_CONTAINER_MAX_CHARS
- symbols.append(
- SkeletonSymbol(
- name=r.name,
- kind=r.kind,
- start_line=check.start_line,
- end_line=check.end_line,
- signature=r.signature,
- importance=pagerank.get(r.name, 0.0),
- focus=focus,
- )
- )
- result = build_skeleton(
- source,
- symbols,
- mode=mode,
- hotspot=bool(result_data.get("hotspot")),
- )
- result_data["skeleton"] = {
- "mode": result.mode,
- "tokens": result.skeleton_tokens,
- "full_tokens": result.full_tokens,
- "pct_of_full": round(result.pct_of_full, 1),
- "bodies_kept": list(result.bodies_kept),
- "text": result.text,
- # The skeleton is rendered from the live source file read above —
- # its text is fresh by construction. Part of the trust contract:
- # a verified response never needs a follow-up Read.
- "verified": True,
- }
- focused = any(sym.focus for sym in symbols)
- if is_symbol_target:
- name = target.split("::", 1)[1]
- result_data["skeleton"]["of_file"] = file_target
- if focused:
- result_data["skeleton"]["symbol_hint"] = (
- f"Skeleton of the file defining '{name}': its full body, every "
- "other symbol as its signature."
- )
- else:
- # No row for the symbol passed the bounds check, or it is a container
- # over the ceiling, so its body is not guaranteed here.
- result_data["skeleton"]["symbol_hint"] = (
- f"Skeleton of the file defining '{name}'. For that "
- f"symbol's full body call get_symbol('{target}')."
- )
- if result.mode == "raw":
- result_data["skeleton"]["note"] = (
- "No usable symbol bounds for this file — returned source as-is."
- )
- elif result.pct_of_full > 40.0 and not focused:
- # Small files skeletonize poorly: when the skeleton is already a
- # large fraction of the source, tell the agent a Read costs little
- # more and carries everything. A focused skeleton is already the
- # symbol plus a file map, so a Read is not the cheaper answer.
- result_data["skeleton"]["mostly_full"] = True
- result_data["skeleton"]["note"] = (
- f"Skeleton is {round(result.pct_of_full, 1)}% of the full file — "
- "a direct Read costs little more."
- )
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/signals.py b/packages/server/src/repowise/server/mcp_server/tool_context/signals.py
new file mode 100644
index 000000000..87797fd50
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/signals.py
@@ -0,0 +1,259 @@
+"""get_context ``metrics``, ``community`` and ``health`` blocks."""
+
+from __future__ import annotations
+
+import json
+from dataclasses import asdict
+from typing import Any
+
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from repowise.core.analysis.communities import has_community
+from repowise.core.analysis.finding_registry import excluded_types
+from repowise.core.analysis.health.complexity.languages import NO_DIALECT_STATUS
+from repowise.core.analysis.health.signals import file_signals
+from repowise.core.ingestion.models import FILE_DEPENDENCY_EDGE_TYPES
+from repowise.core.persistence.crud import (
+ coverage_row_dict,
+ get_all_file_metrics,
+ get_community_members,
+ get_cross_community_edges,
+ get_git_metadata,
+ get_graph_node,
+ get_node_degree_counts,
+ load_coverage_for_repo,
+)
+from repowise.core.persistence.crud.analysis.shown import ungated
+from repowise.core.persistence.models import HealthFileMetric, HealthFinding, Repository
+from repowise.server.mcp_server._helpers import filter_path_list
+from repowise.server.mcp_server.tool_context.call_graph import _SYMBOL_USE_EDGE_TYPES
+
+# Degree reported for a FILE: "N files depend on this", counted over file
+# dependencies rather than one edge per symbol the file declares.
+_FILE_DEPENDENCY_EDGE_TYPES = sorted(FILE_DEPENDENCY_EDGE_TYPES)
+
+
+async def _resolve_metrics(
+ session: AsyncSession,
+ repository: Repository,
+ target: str,
+ result_data: dict[str, Any],
+) -> None:
+ """Resolve graph importance metrics and attach to result_data["metrics"]."""
+ repo_id = repository.id
+
+ node = await get_graph_node(session, repo_id, target)
+ if node is None:
+ result_data["metrics"] = None
+ return
+
+ try:
+ meta = json.loads(node.community_meta_json or "{}")
+ except (json.JSONDecodeError, TypeError):
+ meta = {}
+
+ # Scoped by layer: a file's neighbours are files, a symbol's are symbols.
+ degrees = await get_node_degree_counts(
+ session,
+ repo_id,
+ node.node_id,
+ edge_types=(
+ # Every use edge type, as `routers/graph/intelligence.py` reports it.
+ _SYMBOL_USE_EDGE_TYPES
+ if node.node_type == "symbol"
+ else _FILE_DEPENDENCY_EDGE_TYPES
+ ),
+ )
+
+ # Percentile computation against same-type peers
+ all_nodes = await get_all_file_metrics(session, repo_id)
+ pr_values = [n.pagerank for n in all_nodes if n.pagerank is not None]
+ bt_values = [n.betweenness for n in all_nodes if n.betweenness is not None]
+
+ def _pct(value: float, all_vals: list[float]) -> int:
+ if not all_vals:
+ return 0
+ return round(100 * sum(1 for v in all_vals if v < value) / len(all_vals))
+
+ metrics: dict[str, Any] = {
+ "pagerank": round(node.pagerank or 0.0, 6),
+ "pagerank_percentile": _pct(node.pagerank or 0.0, pr_values),
+ "in_degree": degrees["in_degree"],
+ "out_degree": degrees["out_degree"],
+ "community_id": node.community_id,
+ "community_label": meta.get("label") or None,
+ }
+ # A node added since the last scoring was never measured; its 0.0 default
+ # would read as "on no shortest path".
+ if node.betweenness_commit is None:
+ metrics["betweenness"] = None
+ metrics["betweenness_note"] = "not scored yet: added since the last centrality run"
+ else:
+ metrics["betweenness"] = round(node.betweenness or 0.0, 6)
+ metrics["betweenness_percentile"] = _pct(node.betweenness or 0.0, bt_values)
+ result_data["metrics"] = metrics
+
+
+async def _resolve_community(
+ session: AsyncSession,
+ repository: Repository,
+ target: str,
+ result_data: dict[str, Any],
+ *,
+ exclude_spec: Any = None,
+) -> None:
+ """Resolve community membership and attach to result_data["community"]."""
+ repo_id = repository.id
+
+ node = await get_graph_node(session, repo_id, target)
+ if node is None or not has_community(node.community_id):
+ result_data["community"] = None
+ return
+
+ try:
+ meta = json.loads(node.community_meta_json or "{}")
+ except (json.JSONDecodeError, TypeError):
+ meta = {}
+
+ label = meta.get("label") or f"cluster_{node.community_id}"
+ cohesion = float(meta.get("cohesion", 0.0) or 0.0)
+
+ # Get top members (cap at 10 for compact output)
+ members = await get_community_members(session, repo_id, node.community_id, limit=10)
+ member_paths = filter_path_list([m.node_id for m in members], exclude_spec)
+
+ # Neighboring communities (cap at 5)
+ cross_edges = await get_cross_community_edges(session, repo_id, node.community_id)
+ neighbors: list[dict[str, Any]] = []
+ for ce in cross_edges[:5]:
+ nid = ce["target_community_id"]
+ nm = await get_community_members(session, repo_id, nid, limit=1)
+ nlabel = ""
+ if nm:
+ try:
+ nmeta = json.loads(nm[0].community_meta_json or "{}")
+ nlabel = nmeta.get("label", "")
+ except (json.JSONDecodeError, TypeError):
+ pass
+ neighbors.append(
+ {
+ "id": nid,
+ "label": nlabel or f"cluster_{nid}",
+ "cross_edges": ce["edge_count"],
+ }
+ )
+
+ result_data["community"] = {
+ "id": node.community_id,
+ "label": label,
+ "cohesion": round(cohesion, 3),
+ "top_members": member_paths,
+ "neighbors": neighbors,
+ }
+
+
+async def _resolve_health(
+ session: AsyncSession,
+ repository: Repository,
+ target: str,
+ target_type: str,
+ result_data: dict[str, Any],
+) -> None:
+ """Attach per-file health metric + top 2 biomarkers + coverage row.
+
+ A symbol target reads the file before its ``::`` separator.
+ """
+ file_path: str | None
+ if target_type == "file":
+ file_path = target
+ elif "::" in target:
+ file_path = target.split("::", 1)[0]
+ else:
+ file_path = None
+
+ if not file_path:
+ result_data["health"] = None
+ return
+
+ repo_id = repository.id
+ metric = (
+ await session.execute(
+ select(HealthFileMetric).where(
+ HealthFileMetric.repository_id == repo_id,
+ HealthFileMetric.file_path == file_path,
+ )
+ )
+ ).scalar_one_or_none()
+
+ if metric is None:
+ result_data["health"] = None
+ return
+
+ findings_res = await session.execute(
+ select(HealthFinding)
+ .where(
+ HealthFinding.repository_id == repo_id,
+ HealthFinding.file_path == file_path,
+ HealthFinding.status == "open",
+ HealthFinding.biomarker_type.not_in(excluded_types()),
+ ungated("health", HealthFinding.file_path, HealthFinding.biomarker_type),
+ )
+ .order_by(HealthFinding.health_impact.desc())
+ .limit(2)
+ )
+ from repowise.core.analysis.health.suggestions import suggestion_for
+
+ top_biomarkers = [
+ {
+ "biomarker_type": f.biomarker_type,
+ "severity": f.severity,
+ # Absent rather than null on a file-level biomarker, same as the
+ # identical field on get_risk's cards.
+ **({"function_name": f.function_name} if f.function_name else {}),
+ "impact": round(f.health_impact, 2),
+ "suggestion": suggestion_for(f.biomarker_type),
+ }
+ for f in findings_res.scalars().all()
+ ]
+
+ coverage_rows = await load_coverage_for_repo(
+ session, repo_id, file_paths=[file_path], include_covered_lines=False
+ )
+
+ health: dict[str, Any] = {
+ "score": round(metric.score, 2) if metric.score is not None else None,
+ # Said in words, so a missing score is not read as a missing index.
+ **({"analysis_status": NO_DIALECT_STATUS} if metric.score is None else {}),
+ "max_ccn": metric.max_ccn,
+ "max_nesting": metric.max_nesting,
+ "nloc": metric.nloc,
+ "has_test_file": metric.has_test_file,
+ "module": metric.module,
+ "duplication_pct": metric.duplication_pct,
+ "top_biomarkers": top_biomarkers,
+ }
+ if coverage_rows:
+ health["coverage"] = coverage_row_dict(coverage_rows[0], include_covered_lines=False)
+ elif metric.line_coverage_pct is not None:
+ health["coverage"] = {
+ "line_coverage_pct": metric.line_coverage_pct,
+ "branch_coverage_pct": metric.branch_coverage_pct,
+ }
+
+ # Process / people / topology signals. Null fields are dropped; the block is
+ # absent when the file has neither git history nor a graph node.
+ git_meta = await get_git_metadata(session, repo_id, file_path)
+ node = await get_graph_node(session, repo_id, file_path)
+ degrees = (
+ await get_node_degree_counts(
+ session, repo_id, file_path, edge_types=_FILE_DEPENDENCY_EDGE_TYPES
+ )
+ if node is not None
+ else None
+ )
+ signals = {k: v for k, v in asdict(file_signals(git_meta, degrees)).items() if v is not None}
+ if signals:
+ health["signals"] = signals
+
+ result_data["health"] = health
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/skeleton.py b/packages/server/src/repowise/server/mcp_server/tool_context/skeleton.py
new file mode 100644
index 000000000..5db0a9b4a
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/skeleton.py
@@ -0,0 +1,157 @@
+"""get_context ``skeleton`` block: a body-elided rendering of one file."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from repowise.core.persistence.models import GraphNode, Repository
+from repowise.server.mcp_server._budget import DEFAULT_RESPONSE_CHARS
+
+#: Same threshold get_symbol uses to outline a container instead of inlining it.
+_FOCUS_CONTAINER_MAX_CHARS = DEFAULT_RESPONSE_CHARS // 2
+
+
+async def _resolve_skeleton(
+ session: AsyncSession,
+ repository: Repository,
+ target: str,
+ target_type: str | None,
+ result_data: dict[str, Any],
+ *,
+ repo_root: Any = None,
+ mode: str = "smart",
+) -> None:
+ """Resolve ``include=["skeleton"]`` — a body-elided rendering of one file.
+
+ Slices the on-disk source on the line bounds persisted at index time
+ (zero parsing), keeping every signature and the bodies of the
+ highest-PageRank symbols under a token budget. ``include=["skeleton+"]``
+ passes ``mode="plus"``: all non-function code kept, every function and
+ method body elided. A ``file.py::Symbol`` target renders its file with
+ that symbol's whole body and every other symbol as its signature.
+ """
+ # A "file.py::Symbol" target renders the file defining the symbol; other
+ # non-file targets have no file to render.
+ is_symbol_target = "::" in target
+ file_target = target.split("::", 1)[0] if is_symbol_target else target
+ if not is_symbol_target and target_type != "file":
+ result_data["skeleton"] = {"error": "skeleton requires a file target; pass the file path."}
+ return
+ if not repo_root:
+ result_data["skeleton"] = {"error": "MCP server has no repo path configured."}
+ return
+
+ from pathlib import Path
+
+ from repowise.core.distill.skeleton import SkeletonSymbol, build_skeleton
+ from repowise.core.persistence.models import WikiSymbol
+ from repowise.server.mcp_server._symbol_lookup import symbol_id_variants
+
+ repo_id = repository.id
+ res = await session.execute(
+ select(WikiSymbol).where(
+ WikiSymbol.repository_id == repo_id,
+ WikiSymbol.file_path == file_target,
+ )
+ )
+ rows = list(res.scalars().all())
+
+ # Symbol-node PageRank is the importance signal for smart body retention.
+ pr_res = await session.execute(
+ select(GraphNode.name, GraphNode.pagerank).where(
+ GraphNode.repository_id == repo_id,
+ GraphNode.node_type == "symbol",
+ GraphNode.file_path == file_target,
+ )
+ )
+ pagerank = {name: pr or 0.0 for name, pr in pr_res.all() if name}
+
+ repo_path = Path(str(repo_root))
+ abs_path = (repo_path / file_target).resolve()
+ try:
+ abs_path.relative_to(repo_path.resolve())
+ source = abs_path.read_text(encoding="utf-8", errors="replace")
+ except (OSError, ValueError):
+ result_data["skeleton"] = {
+ "error": "Source file could not be read; it may have moved since indexing."
+ }
+ return
+
+ # The skeleton claims ``verified: True``, so each stored bound is checked
+ # against the live source first; a symbol that cannot be re-located is
+ # dropped rather than rendering the wrong lines.
+ from repowise.server.mcp_server._verify import check_symbol_bounds
+
+ focus_ids = set(symbol_id_variants(target)) if is_symbol_target else set()
+ source_lines = source.splitlines()
+ symbols = []
+ for r in rows:
+ check = check_symbol_bounds(r, source)
+ if check.approximate:
+ continue
+ focus = r.symbol_id in focus_ids
+ if focus and r.kind not in ("function", "method"):
+ # Ceiling: a container body over the get_symbol outline threshold is
+ # not inlined; the ranked skeleton shows its methods as signatures.
+ span = source_lines[check.start_line - 1 : check.end_line]
+ focus = sum(len(ln) + 1 for ln in span) <= _FOCUS_CONTAINER_MAX_CHARS
+ symbols.append(
+ SkeletonSymbol(
+ name=r.name,
+ kind=r.kind,
+ start_line=check.start_line,
+ end_line=check.end_line,
+ signature=r.signature,
+ importance=pagerank.get(r.name, 0.0),
+ focus=focus,
+ )
+ )
+ result = build_skeleton(
+ source,
+ symbols,
+ mode=mode,
+ hotspot=bool(result_data.get("hotspot")),
+ )
+ result_data["skeleton"] = {
+ "mode": result.mode,
+ "tokens": result.skeleton_tokens,
+ "full_tokens": result.full_tokens,
+ "pct_of_full": round(result.pct_of_full, 1),
+ "bodies_kept": list(result.bodies_kept),
+ "text": result.text,
+ # The skeleton is rendered from the live source file read above —
+ # its text is fresh by construction. Part of the trust contract:
+ # a verified response never needs a follow-up Read.
+ "verified": True,
+ }
+ focused = any(sym.focus for sym in symbols)
+ if is_symbol_target:
+ name = target.split("::", 1)[1]
+ result_data["skeleton"]["of_file"] = file_target
+ if focused:
+ result_data["skeleton"]["symbol_hint"] = (
+ f"Skeleton of the file defining '{name}': its full body, every "
+ "other symbol as its signature."
+ )
+ else:
+ # No row for the symbol passed the bounds check, or it is a container
+ # over the ceiling, so its body is not guaranteed here.
+ result_data["skeleton"]["symbol_hint"] = (
+ f"Skeleton of the file defining '{name}'. For that "
+ f"symbol's full body call get_symbol('{target}')."
+ )
+ if result.mode == "raw":
+ result_data["skeleton"]["note"] = (
+ "No usable symbol bounds for this file — returned source as-is."
+ )
+ elif result.pct_of_full > 40.0 and not focused:
+ # A skeleton this close to the source makes a Read nearly as cheap;
+ # a focused skeleton is not the case (it is the symbol plus a file map).
+ result_data["skeleton"]["mostly_full"] = True
+ result_data["skeleton"]["note"] = (
+ f"Skeleton is {round(result.pct_of_full, 1)}% of the full file — "
+ "a direct Read costs little more."
+ )
diff --git a/tests/unit/server/mcp/test_caller_call_text.py b/tests/unit/server/mcp/test_caller_call_text.py
index bba7143d6..a699e4dec 100644
--- a/tests/unit/server/mcp/test_caller_call_text.py
+++ b/tests/unit/server/mcp/test_caller_call_text.py
@@ -16,7 +16,7 @@ from repowise.core.persistence.models import GraphEdge, GraphNode, Repository
from repowise.server.mcp_server import _basis
from repowise.server.mcp_server._edit_sites import MAX_TEXT_CHARS
from repowise.server.mcp_server.tool_answer import callers
-from repowise.server.mcp_server.tool_context import enrichment
+from repowise.server.mcp_server.tool_context import call_graph, enrichment
_NOW = datetime(2026, 3, 19, 12, 0, 0, tzinfo=UTC)
@@ -370,8 +370,8 @@ async def test_get_context_without_callers_is_byte_identical(
async def _noop(*_a, **_k):
return None
- monkeypatch.setattr(enrichment, "attach_call_text", _noop)
- monkeypatch.setattr(enrichment, "first_call_line", lambda _raw: None)
+ monkeypatch.setattr(call_graph, "attach_call_text", _noop)
+ monkeypatch.setattr(call_graph, "first_call_line", lambda _raw: None)
for include in (None, ["callees"]):
without = await get_context(targets=["src/diag.ts::tick"], include=include)
assert _strip(shown[str(include)]) == _strip(without)
diff --git a/tests/unit/server/mcp/test_wrapper_callers.py b/tests/unit/server/mcp/test_wrapper_callers.py
index 2d4c031db..3e73aced6 100644
--- a/tests/unit/server/mcp/test_wrapper_callers.py
+++ b/tests/unit/server/mcp/test_wrapper_callers.py
@@ -13,7 +13,7 @@ import pytest
from repowise.core.persistence.models import GraphEdge, GraphNode, Repository
from repowise.server.mcp_server import _basis, _wrapper_callers
-from repowise.server.mcp_server.tool_context import enrichment
+from repowise.server.mcp_server.tool_context import call_graph, enrichment
_NOW = datetime(2026, 3, 19, 12, 0, 0, tzinfo=UTC)
@@ -284,6 +284,6 @@ async def test_output_is_byte_identical_when_no_caller_is_a_wrapper(
async def _none(*_a, **_k):
return []
- monkeypatch.setattr(enrichment, "forwarding_wrapper_callers", _none)
+ monkeypatch.setattr(call_graph, "forwarding_wrapper_callers", _none)
without = await _callers(session, rid, "x.py::target")
assert json.dumps(with_hop, sort_keys=False) == json.dumps(without, sort_keys=False)