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(edges): retire the last three private edge-type sets (#1518)

Swati Ahuja52db02fe9856
diff --git a/packages/core/src/repowise/core/generation/onboarding/subkinds/key_concepts.py b/packages/core/src/repowise/core/generation/onboarding/subkinds/key_concepts.py
index 6eb2dae62..c9dcf198f 100644
--- a/packages/core/src/repowise/core/generation/onboarding/subkinds/key_concepts.py
+++ b/packages/core/src/repowise/core/generation/onboarding/subkinds/key_concepts.py
@@ -27,6 +27,7 @@ from typing import Any
import structlog
+from ....ingestion.models import SYMBOL_USE_EDGE_TYPES
from ..registry import SubkindSpec, register
from ..signals import OnboardingSignals
from ..slots import SLOT_KEY_CONCEPTS, SLOT_TITLES
@@ -54,12 +55,26 @@ _SKIP_KINDS = frozenset({"module", "variable", "constant"})
_TRIVIAL_NAMES = frozenset(
{"get", "set", "run", "main", "new", "init", "of", "to", "call", "setup", "wrap"}
)
-# Symbol-graph edge types that mean "depends on": a call, or a heritage
-# link (subclass / interface implementation).
-_CONCEPT_EDGE_TYPES = frozenset({"calls", "extends", "implements"})
-# Relationship edge types rendered into "How they connect" - heritage and
-# calls plus resolved imports, so the LLM states real links, not guesses.
-_RELATION_EDGE_TYPES = frozenset({"calls", "extends", "implements", "imports"})
+# Symbol-graph edge types that mean "depends on": a call, a heritage link, or
+# a Go-style interface satisfaction. Both users below - the cross-file caller
+# count and the "How they connect" relations - keep only edges whose endpoints
+# are chosen symbols.
+#
+# The two private copies this replaced both omitted `method_implements`, and
+# the relations copy additionally carried `imports`. `imports` is file -> file
+# and every one of its producers emits it between file nodes, so it could not
+# match here at all: 0 symbol -> symbol `imports` edges exist across 42 local
+# indexes.
+#
+# `reads` is in the shared view and is *nearly* as inert here, for a weaker
+# reason worth writing down. Its one symbol-layer producer,
+# `framework_edges/express.py`, joins a file's `path::__module__` node to a
+# handler in the same file, so the cross-file test below drops it and
+# `_SKIP_KINDS` keeps `__module__` from ever being a chosen concept. That is a
+# property of today's extractor, not of the graph's shape, so it is taken from
+# the shared view rather than trimmed out: a future cross-file `reads` should
+# start counting here without anyone remembering to add it.
+_CONCEPT_EDGE_TYPES = SYMBOL_USE_EDGE_TYPES
@dataclass
@@ -75,6 +90,28 @@ class ConceptSymbol:
cross_file_callers: int = 0
+# One verb per edge type the relations list can carry, so both templates print
+# a phrase instead of a raw token. Total over _CONCEPT_EDGE_TYPES and asserted
+# so by test_relation_verb_covers_the_edge_types: the fall-through is silent,
+# and the template it replaced fell through to "imports from" — which was
+# harmless only while `imports` was in the set and would have mislabelled a Go
+# `method_implements` edge the moment it was not.
+#
+# Ceiling: c4_builder/labels.py `_EDGE_VERB` answers a similar question over
+# all 14 types, but it lives in packages/server and core cannot import it, and
+# it disagrees here on 2 of the 5 shared keys - `extends` reads "inherits from"
+# and `reads` reads "uses", both tuned for a C4 arrow rather than for prose. If
+# a third copy appears, reconcile the wording first, then lift one map into
+# core; a straight merge would silently reword these prompts.
+_RELATION_VERB: dict[str, str] = {
+ "calls": "calls",
+ "extends": "extends",
+ "implements": "implements",
+ "method_implements": "implements",
+ "reads": "reads from",
+}
+
+
@dataclass
class ConceptRelation:
"""One grounded edge between two chosen concepts, drawn from the graph
@@ -82,7 +119,13 @@ class ConceptRelation:
source: str
target: str
- kind: str # calls | extends | implements | imports
+ kind: str # a member of _CONCEPT_EDGE_TYPES
+
+ @property
+ def verb(self) -> str:
+ """The phrase to render. ``"depends on"`` only if a new edge type
+ reaches here before it is given a verb above."""
+ return _RELATION_VERB.get(self.kind, "depends on")
@dataclass
@@ -215,7 +258,7 @@ def _relations_among(
relations: list[ConceptRelation] = []
for src, dst, data in graph.edges(data=True):
etype = data.get("edge_type")
- if etype not in _RELATION_EDGE_TYPES:
+ if etype not in _CONCEPT_EDGE_TYPES:
continue
if src not in chosen_ids or dst not in chosen_ids or src == dst:
continue
diff --git a/packages/core/src/repowise/core/generation/templates/onboarding/key_concepts.j2 b/packages/core/src/repowise/core/generation/templates/onboarding/key_concepts.j2
index d4012898a..8b00abf62 100644
--- a/packages/core/src/repowise/core/generation/templates/onboarding/key_concepts.j2
+++ b/packages/core/src/repowise/core/generation/templates/onboarding/key_concepts.j2
@@ -17,7 +17,7 @@ explain how they fit together.
These are the real edges between the concepts above. Base "How they
connect" on these; do not assert a relationship that is not listed here.
{% for r in ctx.relations %}
-- `{{ r.source }}` {% if r.kind == 'calls' %}calls{% elif r.kind == 'extends' %}extends{% elif r.kind == 'implements' %}implements{% else %}imports from{% endif %} `{{ r.target }}`
+- `{{ r.source }}` {{ r.verb }} `{{ r.target }}`
{% endfor %}
{% endif %}
@@ -65,8 +65,8 @@ Produce a Key Concepts markdown page. Required structure:
it's awkward.
3. **## How they connect** — one paragraph (4–7 sentences) tracing how
the concepts collaborate. This is the section that turns the list
- into a mental model. Ground every "X calls / extends / implements /
- imports Y" claim in the dependency edges listed above; if two
+ into a mental model. Ground every "X depends on Y" claim in the
+ dependency edges listed above, using the verb given there; if two
concepts have no listed edge, describe their relationship structurally
(same layer, shared cluster) rather than asserting a direct call. If
no edges were listed, keep this to how the clusters relate, not
diff --git a/packages/core/src/repowise/core/generation/templates/stub/onboarding/key_concepts.j2 b/packages/core/src/repowise/core/generation/templates/stub/onboarding/key_concepts.j2
index 583541ecf..a8d979963 100644
--- a/packages/core/src/repowise/core/generation/templates/stub/onboarding/key_concepts.j2
+++ b/packages/core/src/repowise/core/generation/templates/stub/onboarding/key_concepts.j2
@@ -27,7 +27,7 @@ The types and functions the rest of `{{ ctx.repo_name }}` leans on most, ranked
{% if ctx.relations %}
## How they connect
{% for r in ctx.relations %}
-- `{{ r.source }}` {{ r.kind }} `{{ r.target }}`
+- `{{ r.source }}` {{ r.verb }} `{{ r.target }}`
{% endfor %}
{% endif %}
diff --git a/packages/core/src/repowise/core/ingestion/graph/_metrics.py b/packages/core/src/repowise/core/ingestion/graph/_metrics.py
index 3ba8f32ea..c5c1dd96d 100644
--- a/packages/core/src/repowise/core/ingestion/graph/_metrics.py
+++ b/packages/core/src/repowise/core/ingestion/graph/_metrics.py
@@ -20,7 +20,7 @@ import networkx as nx
import structlog
from ..cohesion import is_cohesion_edge
-from ..models import SYMBOL_USE_EDGE_TYPES
+from ..models import SYMBOL_USE_EDGE_TYPES, TEMPORAL_EDGE_TYPES
log = structlog.get_logger(__name__)
@@ -103,7 +103,9 @@ class MetricsMixin:
]
sub = g.subgraph(file_nodes).copy()
edges_to_remove = [
- (u, v) for u, v, d in sub.edges(data=True) if d.get("edge_type") in ("co_changes",)
+ (u, v)
+ for u, v, d in sub.edges(data=True)
+ if d.get("edge_type") in TEMPORAL_EDGE_TYPES
]
sub.remove_edges_from(edges_to_remove)
self._file_subgraph_cache = sub
diff --git a/packages/core/src/repowise/core/persistence/stores/in_process_graph_store.py b/packages/core/src/repowise/core/persistence/stores/in_process_graph_store.py
index a6745a001..eed2e16ae 100644
--- a/packages/core/src/repowise/core/persistence/stores/in_process_graph_store.py
+++ b/packages/core/src/repowise/core/persistence/stores/in_process_graph_store.py
@@ -169,16 +169,48 @@ class InProcessGraphStore(GraphStore):
def _file_subgraph(self) -> nx.DiGraph:
"""Return the subgraph restricted to file-level nodes.
- Matches the convention used by :class:`GraphBuilder` — symbol
- nodes are excluded from file-centric metrics so PageRank reflects
- module-level importance rather than per-function frequency.
+ Symbol nodes are excluded from file-centric metrics so PageRank
+ reflects module-level importance rather than per-function frequency.
+
+ Kept in step with :meth:`GraphBuilder.file_subgraph`, the other
+ implementation of this same rule: ``external`` nodes are file-level
+ too, and ``co_changes`` is history rather than code, so leaving it in
+ makes every co-change partner contribute PageRank as though it were an
+ import. This body previously claimed to match the builder while doing
+ neither, and only the absence of a production call site kept that from
+ being a live defect — the two would have scored different centrality
+ for one graph.
+
+ That parity covers :meth:`pagerank` and :meth:`betweenness_centrality`,
+ the two builder metrics computed over ``file_subgraph``. It does *not*
+ make :meth:`communities` agree with the pipeline: that path runs
+ ``detect_file_communities``, which excludes ``external`` deliberately,
+ allowlists ``FILE_DEPENDENCY_EDGE_TYPES`` rather than denying temporal
+ edges, and clusters with Leiden instead of greedy modularity. Only the
+ subgraph rule is shared.
+
+ The import is function-local on purpose: ``ingestion/__init__`` eagerly
+ pulls the tree-sitter parser stack, and ``stores/__init__`` is imported
+ by the job-store path, so a module-level import would make
+ ``repowise upgrade`` load a parser to read a ledger. The two existing
+ persistence → ingestion imports are local for the same reason.
"""
+ from ...ingestion.models import TEMPORAL_EDGE_TYPES
+
file_nodes = [
n
for n, attrs in self._graph.nodes(data=True)
- if attrs.get("node_type", "file") == "file"
+ if attrs.get("node_type", "file") in ("file", "external")
]
- return self._graph.subgraph(file_nodes).copy()
+ sub = self._graph.subgraph(file_nodes).copy()
+ sub.remove_edges_from(
+ [
+ (u, v)
+ for u, v, attrs in sub.edges(data=True)
+ if attrs.get("edge_type") in TEMPORAL_EDGE_TYPES
+ ]
+ )
+ return sub
__all__ = ["InProcessGraphStore"]
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 315e8500e..7ddc43645 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
@@ -16,6 +16,7 @@ from sqlalchemy import distinct, func, select
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.health.signals import file_signals
+from repowise.core.ingestion.models import SYMBOL_USE_EDGE_TYPES
from repowise.core.persistence.crud import (
get_all_file_metrics,
get_community_members,
@@ -39,8 +40,38 @@ from repowise.server.mcp_server._helpers import filter_dicts_by_key, filter_path
# Minimum confidence for call edges to filter false positives
_MIN_CALL_CONFIDENCE = 0.7
-# Edge types that count as a "caller"/"callee" relationship.
-_CALL_EDGE_TYPES = ["calls", "extends", "implements"]
+# Edge types that count as a "caller"/"callee" relationship. 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.
+_CALL_EDGE_TYPES = sorted(SYMBOL_USE_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_call_neighbors(
@@ -179,6 +210,16 @@ async def _resolve_call_graph(
callers.sort(key=lambda x: -(x.get("confidence") or 0))
callees.sort(key=lambda x: -(x.get("confidence") or 0))
+ # One entry per neighbouring symbol, highest-confidence edge kept. Two
+ # symbols can be joined by more than one edge — in Go a struct routinely
+ # both `calls` an interface's methods and `method_implements` it — and the
+ # truncation check below compares this length against a COUNT(DISTINCT),
+ # so counting edges here reports "not truncated" while real callers are
+ # missing. That is the S2 dogfood failure `_count_call_neighbors` exists
+ # to prevent, so the two sides have to count the same thing.
+ callers = _unique_by_symbol(callers)
+ callees = _unique_by_symbol(callees)
+
if want_callers:
result_data["callers"] = callers
total = await _count_call_neighbors(session, repo_id, node.node_id, inbound=True)
diff --git a/tests/unit/generation/test_onboarding_key_concepts.py b/tests/unit/generation/test_onboarding_key_concepts.py
index b3d08b5de..ed5dbfbc9 100644
--- a/tests/unit/generation/test_onboarding_key_concepts.py
+++ b/tests/unit/generation/test_onboarding_key_concepts.py
@@ -23,11 +23,20 @@ from repowise.core.generation.onboarding.slots import (
SLOT_KEY_CONCEPTS,
)
from repowise.core.generation.onboarding.subkinds.key_concepts import (
+ _CONCEPT_EDGE_TYPES,
+ _RELATION_VERB,
+ ConceptRelation,
ConceptSymbol,
KeyConceptsContext,
_prose_hits,
)
-from repowise.core.ingestion.models import FileInfo, ParsedFile, RepoStructure, Symbol
+from repowise.core.ingestion.models import (
+ SYMBOL_USE_EDGE_TYPES,
+ FileInfo,
+ ParsedFile,
+ RepoStructure,
+ Symbol,
+)
# ---------------------------------------------------------------------------
# Fixture builders: a ParsedFile + a real networkx symbol graph so the builder
@@ -104,7 +113,7 @@ def _graph_builder(files: list[ParsedFile], edges: list[tuple[str, str, str]]):
concept_edges = [
(u, v)
for u, v, d in g.edges(data=True)
- if d.get("edge_type") in ("calls", "extends", "implements")
+ if d.get("edge_type") in SYMBOL_USE_EDGE_TYPES
]
sub = nx.DiGraph()
sub.add_nodes_from(n for n, d in g.nodes(data=True) if d.get("node_type") == "symbol")
@@ -269,6 +278,46 @@ def test_key_concepts_grounds_relationships_from_edges() -> None:
assert ("OpenAIProvider", "extends", "BaseProvider") in rels
+def test_relation_verb_covers_the_edge_types() -> None:
+ """Every type the relations list can carry needs a verb.
+
+ The fall-through is silent: an unmapped type renders as "depends on" into
+ an LLM prompt that says to use the verb given. The template this replaced
+ fell through to "imports from", which would have called a Go
+ ``method_implements`` edge an import.
+ """
+ assert not (_CONCEPT_EDGE_TYPES - _RELATION_VERB.keys())
+ assert not (_RELATION_VERB.keys() - _CONCEPT_EDGE_TYPES)
+
+
+def test_go_interface_satisfaction_is_a_relation() -> None:
+ """``method_implements`` was absent from the private set this file kept, so
+ a Go type satisfying an interface produced no relation at all."""
+ base = _file("m/base.go", [_sym("m/base.go", "Storer", "interface", doc="Interface.")])
+ impl = _file("m/disk.go", [_sym("m/disk.go", "DiskStore", "struct", doc="Concrete.")])
+ other = _file("m/client.go", [_sym("m/client.go", "ApiClient", "struct", doc="Client.")])
+ conf = _file("m/config.go", [_sym("m/config.go", "Settings", "struct", doc="Config.")])
+ files = [base, impl, other, conf]
+ edges = [("m/disk.go::DiskStore", "m/base.go::Storer", "method_implements")]
+ for i in range(5):
+ c = f"call/u{i}.go"
+ files.append(_file(c, [_sym(c, f"u{i}", "function")]))
+ for tgt in (
+ "m/base.go::Storer",
+ "m/disk.go::DiskStore",
+ "m/client.go::ApiClient",
+ "m/config.go::Settings",
+ ):
+ edges.append((f"{c}::u{i}", tgt, "calls"))
+ ctx = onboarding.get_spec(SLOT_KEY_CONCEPTS).build_context(
+ _signals(files, _graph_builder(files, edges))
+ )
+ assert ctx is not None
+ rels = {(r.source, r.kind, r.target) for r in ctx.relations}
+ assert ("DiskStore", "method_implements", "Storer") in rels
+ assert ConceptRelation("DiskStore", "Storer", "method_implements").verb == "implements"
+
+
def test_key_concepts_excludes_test_helpers() -> None:
prod = [
_file("app/service.py", [_sym("app/service.py", "Service", "class")]),
diff --git a/tests/unit/ingestion/test_edge_type_vocabulary.py b/tests/unit/ingestion/test_edge_type_vocabulary.py
index e633653a9..a5f02e141 100644
--- a/tests/unit/ingestion/test_edge_type_vocabulary.py
+++ b/tests/unit/ingestion/test_edge_type_vocabulary.py
@@ -268,6 +268,67 @@ def test_edge_type_map_covers_the_vocabulary() -> None:
)
+def _alias_targets() -> dict[str, tuple[str, set[str]]]:
+ """Map `path::CONSTANT` -> (referenced name, names that file imports from models).
+
+ Only for `*_EDGE_TYPES = <bare name>` and the `sorted(<bare name>)` /
+ `frozenset(<bare name>)` wrappers around one. `_string_members` returns an
+ empty set for those shapes, so without this they are invisible to both
+ directions of the check.
+ """
+ found: dict[str, tuple[str, set[str]]] = {}
+ for path in _python_files():
+ rel = _rel(path)
+ try:
+ tree = ast.parse(path.read_text(encoding="utf-8"))
+ except (SyntaxError, UnicodeDecodeError):
+ continue
+ from_models = {
+ alias.asname or alias.name
+ for node in ast.walk(tree)
+ if isinstance(node, ast.ImportFrom) and (node.module or "").endswith("ingestion.models")
+ for alias in node.names
+ }
+ for node in ast.walk(tree):
+ targets: list[ast.expr] = []
+ if isinstance(node, ast.Assign):
+ targets = list(node.targets)
+ elif isinstance(node, ast.AnnAssign):
+ targets = [node.target]
+ else:
+ continue
+ names = [t.id for t in targets if isinstance(t, ast.Name)]
+ if not any(n.endswith("_EDGE_TYPES") for n in names) or node.value is None:
+ continue
+ value = node.value
+ if isinstance(value, ast.Call) and len(value.args) == 1:
+ value = value.args[0]
+ if isinstance(value, ast.Name):
+ found[f"{rel}::{names[0]}"] = (value.id, from_models)
+ return found
+
+
+def test_an_edge_type_alias_points_at_the_shared_vocabulary() -> None:
+ """`_X_EDGE_TYPES = SOME_NAME` must name something this test can still see.
+
+ The AST checks read literals, so an alias is a blind spot: `_TYPES =
+ {"heritage"}` followed by `_CALL_EDGE_TYPES = _TYPES` would smuggle a dead
+ key past both directions. Aliasing a shared view is the intended shape and
+ stays legal; aliasing an arbitrary local name does not.
+ """
+ offenders = {
+ name: referenced
+ for name, (referenced, from_models) in _alias_targets().items()
+ if referenced not in from_models and not referenced.endswith("_EDGE_TYPES")
+ }
+ assert not offenders, (
+ "edge-type set(s) aliasing a name this check cannot follow:\n"
+ + "\n".join(f" {n} = {v}" for n, v in sorted(offenders.items()))
+ + "\n\nAlias a view imported from repowise.core.ingestion.models, or name the"
+ " referent `*_EDGE_TYPES` so it is checked where it is defined."
+ )
+
+
@pytest.mark.parametrize("phantom", ["has_property", "method_overrides", "dynamic"])
def test_the_removed_phantoms_stay_removed(phantom: str) -> None:
"""Each measured at 0 rows across 42 local indexes with no producer in the tree.
diff --git a/tests/unit/server/mcp/test_context.py b/tests/unit/server/mcp/test_context.py
index 296124398..d98b8da07 100644
--- a/tests/unit/server/mcp/test_context.py
+++ b/tests/unit/server/mcp/test_context.py
@@ -529,6 +529,80 @@ async def test_symbol_callers_carry_definition_line(setup_mcp, session):
assert caller["line"] == 55
+async def test_one_caller_joined_by_two_edge_types_is_listed_once(setup_mcp, session):
+ """Two edges between the same pair must not become two callers.
+
+ The displayed list is compared against a COUNT(DISTINCT) to decide
+ truncation, so an entry per edge makes the two sides count different
+ things: the list looks longer than the true total and `callers_truncated`
+ stays unset while real callers have been cut. Reachable since the caller
+ set became the shared symbol view — in Go a struct routinely both `calls`
+ an interface's methods and `method_implements` it.
+ """
+ from repowise.core.persistence.models import GraphEdge, GraphNode, Repository
+ from repowise.server.mcp_server import get_context
+
+ repo = (await session.execute(__import__("sqlalchemy").select(Repository))).scalars().first()
+ target_id = "src/store/iface.go::Storer"
+ caller_id = "src/store/disk.go::DiskStore"
+ session.add_all(
+ [
+ GraphNode(
+ id="dup_tgt",
+ repository_id=repo.id,
+ node_id=target_id,
+ node_type="symbol",
+ name="Storer",
+ file_path="src/store/iface.go",
+ kind="interface",
+ start_line=1,
+ end_line=5,
+ created_at=_NOW,
+ ),
+ GraphNode(
+ id="dup_src",
+ repository_id=repo.id,
+ node_id=caller_id,
+ node_type="symbol",
+ name="DiskStore",
+ file_path="src/store/disk.go",
+ kind="struct",
+ start_line=1,
+ end_line=9,
+ created_at=_NOW,
+ ),
+ GraphEdge(
+ id="dup_edge_calls",
+ repository_id=repo.id,
+ source_node_id=caller_id,
+ target_node_id=target_id,
+ edge_type="calls",
+ confidence=0.9,
+ created_at=_NOW,
+ ),
+ GraphEdge(
+ id="dup_edge_impl",
+ repository_id=repo.id,
+ source_node_id=caller_id,
+ target_node_id=target_id,
+ edge_type="method_implements",
+ confidence=0.95,
+ created_at=_NOW,
+ ),
+ ]
+ )
+ await session.flush()
+
+ result = await get_context([target_id], include=["callers"], compact=False)
+ t = result["targets"][target_id]
+ matching = [c for c in t.get("callers", []) if c["symbol_id"] == caller_id]
+ assert len(matching) == 1, matching
+ # Highest-confidence edge survives the collapse.
+ assert matching[0]["edge_type"] == "method_implements"
+ assert not t.get("callers_truncated")
+
+
@pytest.mark.asyncio
async def test_high_fan_in_callers_signal_truncation(setup_mcp, session):
"""A symbol with more callers than the display cap must report the TRUE