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(ingestion): make the edge-type vocabulary true and enforced (#1516)

Swati Ahuja65519ccb73e2
diff --git a/docs/reference/COMPUTED_GLOSSARY.md b/docs/reference/COMPUTED_GLOSSARY.md
index bc448e76d..b26c8a226 100644
--- a/docs/reference/COMPUTED_GLOSSARY.md
+++ b/docs/reference/COMPUTED_GLOSSARY.md
@@ -393,7 +393,7 @@ workspace overlays, MCP responses, and CLI output.
| Dead-code status | `open`, `acknowledged`, `resolved`, `false_positive` |
| Security severity | `high`, `med`, `low` |
| Security kind | `eval_call`, `exec_call`, `pickle_loads`, `subprocess_shell_true`, `os_system`, `hardcoded_password`, `hardcoded_secret`, `fstring_sql`, `concat_sql`, `tls_verify_false`, `weak_hash`, `security_sensitive_symbol` |
-| Edge type | `imports`, `defines`, `calls`, `has_method`, `has_property`, `extends`, `implements`, `method_overrides`, `method_implements`, `co_changes`, `framework`, `dynamic`, plus dynamic subtypes such as `dynamic_uses`, `dynamic_imports`, `dynamic_url_route` |
+| Edge type | `imports`, `defines`, `calls`, `has_method`, `extends`, `implements`, `method_implements`, `co_changes`, `framework`, `reads`, `type_use`, `dynamic_uses`, `dynamic_imports`, `dynamic_url_route` — the complete list, declared as `EdgeType` in `ingestion/models.py` and enforced by `tests/unit/ingestion/test_edge_type_vocabulary.py` |
| Node type | `file`, `symbol`, `external` |
| Search type | `vector`, `fulltext` |
| Contract type | `http`, `grpc`, `topic` |
diff --git a/packages/core/src/repowise/core/analysis/communities.py b/packages/core/src/repowise/core/analysis/communities.py
index 8005f5f50..d0143f394 100644
--- a/packages/core/src/repowise/core/analysis/communities.py
+++ b/packages/core/src/repowise/core/analysis/communities.py
@@ -21,6 +21,7 @@ import networkx as nx
import structlog
from repowise.core.analysis.kg_curation import GENERIC_ORG_SEGMENTS, dominant_segments
+from repowise.core.ingestion.models import FILE_DEPENDENCY_EDGE_TYPES, SYMBOL_USE_EDGE_TYPES
from repowise.core.test_paths import is_test_related_path
log = structlog.get_logger(__name__)
@@ -32,15 +33,16 @@ log = structlog.get_logger(__name__)
_MAX_COMMUNITY_FRACTION = 0.30
_MIN_SPLIT_SIZE = 20
-# Edge types to include when building file-level community subgraph
-_FILE_COMMUNITY_EDGE_TYPES = frozenset({
- "imports", "framework", "dynamic", "extends", "implements",
-})
+# Edge types to include when building file-level community subgraph.
+# Was {imports, framework, dynamic, extends, implements}: "dynamic" matched no
+# real edge, and extends/implements are symbol-to-symbol so they never joined
+# two files.
+_FILE_COMMUNITY_EDGE_TYPES = FILE_DEPENDENCY_EDGE_TYPES
-# Edge types to include when building symbol-level community subgraph
-_SYMBOL_COMMUNITY_EDGE_TYPES = frozenset({
- "calls", "extends", "implements", "has_method",
-})
+# Edge types to include when building symbol-level community subgraph.
+# Containment is kept here on purpose: a class and its methods belong in one
+# community.
+_SYMBOL_COMMUNITY_EDGE_TYPES = SYMBOL_USE_EDGE_TYPES | {"has_method"}
# Generic directory segments excluded from heuristic labeling — the shared
# organisational-container vocabulary lives in kg_curation next to its
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
index 3aa1612fa..e2dc8993e 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -21,6 +21,7 @@ from typing import Any
import structlog
+from ...ingestion.models import REACHABILITY_USE_EDGE_TYPES
from .constants import (
_DEFAULT_DYNAMIC_PATTERNS,
_FRAMEWORK_DECORATOR_SUFFIXES,
@@ -984,9 +985,18 @@ class DeadCodeAnalyzer:
# any public member. Treat the whole file as live so we
# don't flag e.g. ``BasketService`` (registered via
# ``MapGrpcService<BasketService>()``) as an unused export.
+ # Was ("dynamic_uses", "dynamic", "framework"): the bare "dynamic"
+ # matched nothing and dynamic_imports was absent, so a file reached
+ # only by a dynamic import was never rescued here.
+ # Deliberately NOT `is_dynamic_edge`: `dynamic_imports` and
+ # `dynamic_url_route` mean the module gets loaded, which is what a
+ # plain `imports` edge means, and that is not rescued here either.
+ # Only `dynamic_uses` carries "the runtime reached a member".
+ # Widening this to every dynamic_* hides an unused export in any
+ # package.json `main` target or Django INSTALLED_APPS module.
file_dynamically_loaded = any(
self.graph.get_edge_data(pred, node, {}).get("edge_type")
- in ("dynamic_uses", "dynamic", "framework")
+ in ("dynamic_uses", "framework")
for pred in self.graph.predecessors(node)
)
if file_dynamically_loaded:
@@ -1184,8 +1194,7 @@ class DeadCodeAnalyzer:
# padding bases like ``BoundedLocalCache.BLCHeader``,
# Kotlin sealed parents, Scala typeclass traits).
if self.graph.has_node(sym_id) and any(
- self.graph[pred][sym_id].get("edge_type")
- in ("calls", "method_implements", "reads", "extends", "implements", "type_use")
+ self.graph[pred][sym_id].get("edge_type") in REACHABILITY_USE_EDGE_TYPES
for pred in self.graph.predecessors(sym_id)
):
continue
diff --git a/packages/core/src/repowise/core/analysis/dead_code/cpp_reachability.py b/packages/core/src/repowise/core/analysis/dead_code/cpp_reachability.py
index 8abf56dc9..3bdf318d2 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/cpp_reachability.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/cpp_reachability.py
@@ -38,6 +38,8 @@ from __future__ import annotations
from pathlib import PurePosixPath
from typing import Any
+from ...ingestion.models import REACHABILITY_USE_EDGE_TYPES
+
# File extensions this module rescues. The C/C++ tree-sitter grammar
# tag covers all of these; the resolver shares them too.
_CPP_HEADER_EXTS: tuple[str, ...] = (
@@ -66,14 +68,7 @@ _CPP_ENTRY_FUNCTION_NAMES: frozenset[str] = frozenset({
# Edge types that count as "this symbol is used by something". A header
# whose declared symbols carry any of these inbound edges is live, even
# without a file-level ``imports`` edge from the consumer.
-_SYMBOL_USE_EDGE_TYPES: frozenset[str] = frozenset({
- "calls",
- "method_implements",
- "reads",
- "extends",
- "implements",
- "type_use",
-})
+_SYMBOL_USE_EDGE_TYPES: frozenset[str] = REACHABILITY_USE_EDGE_TYPES
def is_cpp_path(path: str) -> bool:
diff --git a/packages/core/src/repowise/core/analysis/dead_code/dynamic_markers.py b/packages/core/src/repowise/core/analysis/dead_code/dynamic_markers.py
index b3293822f..06f38e79f 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/dynamic_markers.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/dynamic_markers.py
@@ -20,6 +20,7 @@ from __future__ import annotations
from pathlib import Path
from repowise.core.ids import is_external
+from repowise.core.ingestion.models import is_dynamic_edge
def read_source_text(
@@ -515,8 +516,7 @@ def find_dynamic_edge_files(graph) -> set[str]:
result: set[str] = set()
try:
for u, v, data in graph.edges(data=True):
- etype = data.get("edge_type", "")
- if etype != "dynamic" and not etype.startswith("dynamic_"):
+ if not is_dynamic_edge(data.get("edge_type", "")):
continue
for endpoint in (u, v):
if endpoint is None:
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/graph_signals.py b/packages/core/src/repowise/core/analysis/health/refactoring/graph_signals.py
index cf2a32f37..65782e5d7 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/graph_signals.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/graph_signals.py
@@ -16,15 +16,24 @@ from __future__ import annotations
from typing import Any
from ....ingestion.cohesion import is_cohesion_edge
+from ....ingestion.models import FILE_DEPENDENCY_EDGE_TYPES
# File->file edge types that constitute a structural dependency cycle.
# ``imports`` is the actionable, invertible edge; the others are carried so a
-# cycle that closes through a framework/type edge is still reported. Today the
-# only file-level edge type the graph emits is ``imports`` (the rest are
-# symbol-level), so this closely tracks ``GraphBuilder.file_subgraph`` (which
-# drops only git ``co_changes``) and the persisted ``graph_node_membership``
-# rows; the two could drift only if a new file-level edge type is added to one
-# definition but not the other.
+# cycle that closes through a framework/type edge is still reported.
+#
+# This used to be a hand-written tuple, with a comment claiming ``imports`` was
+# the only file-level type the graph emits. That was wrong in both directions:
+# the tuple held a bare ``dynamic`` no producer writes, so every real
+# ``dynamic_*`` edge was invisible to cycle detection, and it carried
+# ``extends``/``implements``, which are symbol-to-symbol and cannot close a
+# file cycle. Sharing ``FILE_DEPENDENCY_EDGE_TYPES`` is what stops the next
+# file-level type from being added to one definition and not the other.
+#
+# It stays deliberately different from ``GraphBuilder.file_subgraph``, which is
+# an exclusion list (drop ``co_changes``) rather than an allowlist. Both reach
+# the same set today; the allowlist is the safer shape here because a new
+# non-dependency type defaults to "not a cycle" instead of silently closing one.
#
# Edge *type* is not sufficient on its own: the resolver passes synthesise
# ``imports`` and ``type_use`` edges to express that two files are one
@@ -32,7 +41,7 @@ from ....ingestion.cohesion import is_cohesion_edge
# header/impl pair). Those are not dependencies and must not close a cycle, so
# both definitions additionally reject ``is_cohesion_edge``. See
# repowise.core.ingestion.cohesion.
-_CYCLE_EDGE_TYPES = ("imports", "framework", "dynamic", "type_use", "extends", "implements")
+_CYCLE_EDGE_TYPES = FILE_DEPENDENCY_EDGE_TYPES
def _is_cycle_edge(data: Any) -> bool:
diff --git a/packages/core/src/repowise/core/analysis/kg_curation.py b/packages/core/src/repowise/core/analysis/kg_curation.py
index c86de0360..33f4302da 100644
--- a/packages/core/src/repowise/core/analysis/kg_curation.py
+++ b/packages/core/src/repowise/core/analysis/kg_curation.py
@@ -118,7 +118,9 @@ def _graph_mode(dominant_lang: str, lang_by_path: dict[str, str], graph_builder:
external_targets = 0
try:
for src, dst, data in graph_builder.graph().edges(data=True):
- if (data or {}).get("edge_type") in ("imports", "tested_by") and src in dom_files:
+ # "tested_by" was a second member here; it is a knowledge-graph
+ # export label, never a raw edge type, so it never matched.
+ if (data or {}).get("edge_type") == "imports" and src in dom_files:
edge_count += 1
if isinstance(dst, str) and is_external(dst):
external_targets += 1
@@ -1087,7 +1089,10 @@ def _import_groups(
# The harness signal is "this test file *depends on* that one" — type
# references and inheritance (a base test class) are exactly that evidence;
# raw-graph type_use/heritage edges surface as plain imports in the export.
-_DEPENDENCY_EDGE_TYPES = frozenset({"imports", "type_use", "heritage"})
+# Deliberately narrower than FILE_DEPENDENCY_EDGE_TYPES: framework and dynamic
+# wiring is not harness evidence. "heritage" used to be a third member and was
+# never an edge type — inheritance reaches the graph as extends/implements.
+_DEPENDENCY_EDGE_TYPES = frozenset({"imports", "type_use"})
def _import_pairs_excluding_fanout(graph_builder: Any) -> list[tuple[str, str]]:
diff --git a/packages/core/src/repowise/core/analysis/knowledge_graph.py b/packages/core/src/repowise/core/analysis/knowledge_graph.py
index 8053d951f..0d3f143e0 100644
--- a/packages/core/src/repowise/core/analysis/knowledge_graph.py
+++ b/packages/core/src/repowise/core/analysis/knowledge_graph.py
@@ -205,14 +205,31 @@ def _slugify(text: str) -> str:
# Edge type mapping
# ---------------------------------------------------------------------------
+# An unmapped type is dropped from the export entirely (see the
+# `if not kg_type: continue` below), which is silent. Six real types used to be
+# missing — framework, the three dynamic_* kinds, reads and method_implements —
+# so framework-wired and dynamically-dispatched relations never reached the
+# knowledge graph at all. `test_edge_type_map_covers_the_vocabulary` keeps this
+# total over every dependency type.
+#
+# `co_changes` is the one deliberate omission: it is git history, not a code
+# reference, and the export has no relation kind that would keep that
+# distinction downstream. Admitting it here is how a co-change partner starts
+# looking like an import.
_EDGE_TYPE_MAP: dict[str, str] = {
"imports": "imports",
"type_use": "imports",
+ "framework": "imports",
+ "dynamic_imports": "imports",
+ "dynamic_uses": "depends_on",
+ "dynamic_url_route": "depends_on",
"defines": "contains",
"has_method": "contains",
"calls": "depends_on",
"extends": "depends_on",
"implements": "depends_on",
+ "method_implements": "depends_on",
+ "reads": "depends_on",
}
diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/base.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/base.py
index 5619bc46a..8f0615e60 100644
--- a/packages/core/src/repowise/core/ingestion/dynamic_hints/base.py
+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/base.py
@@ -5,6 +5,7 @@ from collections.abc import Iterator
from dataclasses import dataclass, field # noqa: F401 — re-exported
from pathlib import Path
+from ..models import DynamicKind
from ._walk import iter_glob
@@ -12,7 +13,10 @@ from ._walk import iter_glob
class DynamicEdge:
source: str # repo-relative path
target: str # repo-relative path
- edge_type: str # "dynamic_uses" | "dynamic_imports" | "url_route"
+ # The hint kind, not the graph edge type: `EdgesMixin.add_dynamic_edges`
+ # prefixes anything not already starting with "dynamic", so `url_route`
+ # lands in the graph as `dynamic_url_route`.
+ edge_type: DynamicKind
hint_source: str # extractor name
weight: float = 1.0
diff --git a/packages/core/src/repowise/core/ingestion/graph/_edges.py b/packages/core/src/repowise/core/ingestion/graph/_edges.py
index 6629ae680..98246b118 100644
--- a/packages/core/src/repowise/core/ingestion/graph/_edges.py
+++ b/packages/core/src/repowise/core/ingestion/graph/_edges.py
@@ -85,10 +85,15 @@ class EdgesMixin:
if self._exclude.patterns and self._exclude.match_file(e.target):
continue
self._graph.add_node(e.target)
- sub_type = e.edge_type or "dynamic"
- graph_edge_type = (
- sub_type if sub_type.startswith("dynamic") else f"dynamic_{sub_type}"
- )
+ # `DynamicEdge.edge_type` is a `DynamicKind`, so there is no empty
+ # case to fall back on. The `or "dynamic"` that used to sit here
+ # was the only writer of a bare `"dynamic"` edge — unreachable in
+ # practice (0 rows in 42 indexes) but enough to keep `"dynamic"`
+ # in the declared vocabulary, which in turn is what three
+ # consumers wrote their sets against and why none of them matched
+ # a real `dynamic_*` edge.
+ sub_type = e.edge_type
+ graph_edge_type = sub_type if sub_type.startswith("dynamic") else f"dynamic_{sub_type}"
self._graph.add_edge(
e.source,
e.target,
diff --git a/packages/core/src/repowise/core/ingestion/graph/_metrics.py b/packages/core/src/repowise/core/ingestion/graph/_metrics.py
index beb8e0b4d..3ba8f32ea 100644
--- a/packages/core/src/repowise/core/ingestion/graph/_metrics.py
+++ b/packages/core/src/repowise/core/ingestion/graph/_metrics.py
@@ -20,6 +20,7 @@ import networkx as nx
import structlog
from ..cohesion import is_cohesion_edge
+from ..models import SYMBOL_USE_EDGE_TYPES
log = structlog.get_logger(__name__)
@@ -163,7 +164,10 @@ class MetricsMixin:
edges_to_remove = [
(u, v)
for u, v, d in sub.edges(data=True)
- if d.get("edge_type") not in ("calls", "extends", "implements")
+ # Was ("calls", "extends", "implements"), which dropped
+ # method_implements — so Go structural interface satisfaction
+ # never contributed to symbol centrality.
+ if d.get("edge_type") not in SYMBOL_USE_EDGE_TYPES
]
sub.remove_edges_from(edges_to_remove)
self._symbol_subgraph_cache = sub
diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.py
index 00e7f5538..512741587 100644
--- a/packages/core/src/repowise/core/ingestion/models.py
+++ b/packages/core/src/repowise/core/ingestion/models.py
@@ -251,19 +251,43 @@ class HeritageRelation:
# Edge types used in the symbol-level dependency graph
# ---------------------------------------------------------------------------
+# The vocabulary is exhaustive and *true*: every member is emitted by some
+# producer, and no producer emits anything outside it. Both halves are load
+# bearing. A declared-but-never-emitted member is what let a dozen consumers
+# each write a set against a type that does not exist, and an emitted-but-
+# undeclared type is what made every one of those sets silently incomplete.
+#
+# `tests/unit/ingestion/test_edge_type_vocabulary.py` holds both directions
+# shut: it AST-walks every `add_edge` call in the packages and fails on a
+# literal that is not a member here.
+#
+# Removed 2026-08-14, each measured at 0 rows across 42 local indexes with no
+# producer anywhere in the tree: `has_property` (only `defines` and
+# `has_method` are emitted for containment), `method_overrides` (a
+# `HeritageKind`, never an edge type — the TS mirror in
+# `packages/types/src/symbols.ts` still declares it as a heritage kind, which
+# is correct), and bare `dynamic`.
EdgeType = Literal[
"imports",
"defines",
"calls",
"has_method",
- "has_property",
"extends",
"implements",
- "method_overrides",
"method_implements",
"co_changes",
"framework",
- "dynamic",
+ # A data reference rather than a call. Two `_add_reads_edge` helpers emit
+ # it at different layers: C# member access file → file, Express
+ # route/middleware wiring symbol → symbol.
+ "reads",
+ # Dynamic-dispatch hints. `dynamic_hints` extractors emit a `DynamicKind`
+ # sub-type and `EdgesMixin.add_dynamic_edges` prefixes it, so `url_route`
+ # reaches the graph as `dynamic_url_route` and never as itself. Consumers
+ # matching bare `"dynamic"` — three of them did — match none of these.
+ "dynamic_uses",
+ "dynamic_imports",
+ "dynamic_url_route",
# Synthesised file-to-file edge emitted from constructor / method /
# delegate / record parameter type references in statically-typed
# languages (currently C#; see type_ref_resolution.py). Distinct
@@ -272,12 +296,24 @@ EdgeType = Literal[
"type_use",
]
+# Runtime mirror of the Literal, for the places that must test membership
+# rather than annotate. Derived, never hand-written — a second hand-written
+# copy is the exact failure this phase exists to remove.
+EDGE_TYPE_VALUES: frozenset[str] = frozenset(get_args(EdgeType))
+
+# What a dynamic-hint extractor reports, *before* `add_dynamic_edges` prefixes
+# it. Deliberately a separate vocabulary from `EdgeType`: `url_route` is a
+# legal hint kind and never a legal graph edge type, and conflating the two is
+# what put `url_route` in the plan for this phase as an edge type to declare
+# when the graph has never held one.
+DynamicKind = Literal["dynamic_uses", "dynamic_imports", "url_route"]
+
# Structural containment, not reference. ``defines`` is file → symbol and
-# ``has_method`` / ``has_property`` are class symbol → member symbol, so both
-# endpoints describe the same code rather than one depending on the other.
-# Their target is a ``path::Name`` symbol node, which is why a consumer that
-# keys on file paths gets nothing usable out of them.
-CONTAINMENT_EDGE_TYPES: frozenset[str] = frozenset({"defines", "has_method", "has_property"})
+# ``has_method`` is class symbol → member symbol, so both endpoints describe
+# the same code rather than one depending on the other. Their target is a
+# ``path::Name`` symbol node, which is why a consumer that keys on file paths
+# gets nothing usable out of them.
+CONTAINMENT_EDGE_TYPES: frozenset[str] = frozenset({"defines", "has_method"})
# Evidence from history rather than from code: two files move together in
# commits, not one referencing the other. This is the one that bites, because
@@ -297,6 +333,79 @@ TEMPORAL_EDGE_TYPES: frozenset[str] = frozenset({"co_changes"})
# ``TEMPORAL_EDGE_TYPES`` and a ``node_type`` check instead.
NON_DEPENDENCY_EDGE_TYPES: frozenset[str] = CONTAINMENT_EDGE_TYPES | TEMPORAL_EDGE_TYPES
+# ---------------------------------------------------------------------------
+# The named views. Ask for the one that matches your question.
+# ---------------------------------------------------------------------------
+#
+# Before these existed, thirteen modules each kept a private set answering some
+# version of "which edges count as a dependency", and no two were identical:
+# `type_use` was a dependency in five and absent from four, `reads` appeared in
+# one of thirteen, and three tested for a bare `"dynamic"` that no producer has
+# ever emitted — so they matched none of the 6,153 real `dynamic_*` edges.
+#
+# The split below is not a taste call. Measured across 42 local indexes, every
+# edge type lands on one side 100% of the time, with a single exception noted
+# on `reads`. Add a member here, not a set of your own, and say which view you
+# want at the call site.
+
+# File → file code references: static imports, C#-style type references,
+# synthesised framework wiring, and dispatch the parser cannot see statically.
+# This is the right view for anything building a *file*-level subgraph —
+# communities, dependency cycles, coupling. Note what is absent: `co_changes`
+# is history rather than code, and symbol-level types put both endpoints on
+# nodes a file-keyed consumer cannot resolve.
+FILE_DEPENDENCY_EDGE_TYPES: frozenset[str] = frozenset(
+ {
+ "imports",
+ "type_use",
+ "framework",
+ "dynamic_uses",
+ "dynamic_imports",
+ "dynamic_url_route",
+ # C# member access (`var x = new T(); x.Prop`) resolves to the file
+ # declaring the type, so this is a real file-level reference. See the
+ # note on SYMBOL_USE_EDGE_TYPES: `reads` is emitted at both layers.
+ "reads",
+ }
+)
+
+# Symbol → symbol references. "Something reaches this symbol", so containment
+# is excluded: a class containing a method is not the method being used.
+#
+# `reads` is the one type that spans both layers, which is why it is the one
+# member of both sets. Two extractors share the name: `csharp_member_reads`
+# emits it file → file (596 rows locally) and `framework_edges/express` emits
+# it symbol → symbol from a `path::__module__` node (1 row).
+SYMBOL_USE_EDGE_TYPES: frozenset[str] = frozenset(
+ {
+ "calls",
+ "extends",
+ "implements",
+ "method_implements",
+ "reads",
+ }
+)
+
+
+# "Does anything use this symbol at all?" — the reachability view. Adds
+# ``type_use`` to the symbol set: a C#-style type reference is a real use, and
+# the dead-code analyzer and the C/C++ reachability pass both asked for exactly
+# this union with their own private copy.
+REACHABILITY_USE_EDGE_TYPES: frozenset[str] = SYMBOL_USE_EDGE_TYPES | {"type_use"}
+
+
+def is_dynamic_edge(edge_type: str | None) -> bool:
+ """Whether *edge_type* is a dynamic-dispatch hint.
+
+ Prefix-matched on purpose. The sub-type is open — ``add_dynamic_edges``
+ mints ``dynamic_<kind>`` from whatever a hint extractor reports — so a set
+ membership test here is what goes stale when a new hint kind lands, and
+ three separate consumers matching a bare ``"dynamic"`` is how that failure
+ already shipped. The trailing underscore is load bearing: without it a
+ future ``dynamically_*`` type would match by accident.
+ """
+ return edge_type is not None and edge_type.startswith("dynamic_")
+
@dataclass
class TypeReference:
diff --git a/packages/server/src/repowise/server/services/c4_builder/architecture.py b/packages/server/src/repowise/server/services/c4_builder/architecture.py
index 0a4b59083..8c788e1b3 100644
--- a/packages/server/src/repowise/server/services/c4_builder/architecture.py
+++ b/packages/server/src/repowise/server/services/c4_builder/architecture.py
@@ -12,6 +12,7 @@ from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from repowise.core.ids import ExternalSystemId, file_path_of, render
+from repowise.core.ingestion.models import CONTAINMENT_EDGE_TYPES
from repowise.core.persistence import (
ExternalSystem,
GraphEdge,
@@ -58,13 +59,10 @@ _ENTRY_POINT_NAMES = frozenset(
}
)
-_SYMBOL_EDGE_TYPES = frozenset(
- {
- "contains",
- "defines",
- "has_method",
- }
-)
+# "contains" used to sit here too. It is a knowledge-graph *export* label
+# derived from defines/has_method, never a persisted edge_type, so it matched
+# nothing.
+_SYMBOL_EDGE_TYPES = CONTAINMENT_EDGE_TYPES
_EXT_MAP = {
".py": "python",
diff --git a/packages/server/src/repowise/server/services/c4_builder/labels.py b/packages/server/src/repowise/server/services/c4_builder/labels.py
index a5a9f9a8e..0121c385b 100644
--- a/packages/server/src/repowise/server/services/c4_builder/labels.py
+++ b/packages/server/src/repowise/server/services/c4_builder/labels.py
@@ -23,19 +23,29 @@ from collections.abc import Iterable
# and `dynamic_uses`, which between them covered 1,351 of the 13,165 file-level
# edges on a live index (10%) and rendered as "depends on" for their whole life.
# `extends` is the token the extractors emit; `inherits` never was one.
+# Total over EdgeType, and `test_edge_verb_covers_the_vocabulary` keeps it that
+# way — the fall-through this comment describes is silent, so the only reliable
+# fix is for a missing key to fail a test rather than render as "depends on".
+# Dropped: "inherits", "references" and "contains", none of which is an edge
+# type ("contains" and "tested_by" are knowledge-graph export labels).
_EDGE_VERB: dict[str, str] = {
"imports": "imports",
"dynamic_imports": "imports",
"calls": "calls",
"extends": "inherits from",
- "inherits": "inherits from",
"implements": "implements",
+ "method_implements": "implements",
# A lazy/registry import and a framework-convention link (a test file to its
# conftest) are both real dependencies that no static import expresses.
"dynamic_uses": "uses",
+ "dynamic_url_route": "uses",
"framework": "uses",
- "references": "references",
- "contains": "contains",
+ "reads": "uses",
+ # A type reference without an import: named, but not imported.
+ "type_use": "references",
+ # Containment. Only reachable when the view includes symbol nodes.
+ "defines": "contains",
+ "has_method": "contains",
"co_changes": "co-changes",
}
diff --git a/packages/server/src/repowise/server/services/zoom_builder/scoring.py b/packages/server/src/repowise/server/services/zoom_builder/scoring.py
index fed49e103..d70948a27 100644
--- a/packages/server/src/repowise/server/services/zoom_builder/scoring.py
+++ b/packages/server/src/repowise/server/services/zoom_builder/scoring.py
@@ -22,11 +22,15 @@ from __future__ import annotations
from collections import deque
from dataclasses import dataclass, replace
+from repowise.core.ingestion.models import FILE_DEPENDENCY_EDGE_TYPES
+
from .models import ZoomNode
-# Edge types that represent "uses at runtime" for reachability. Symbol-level
-# containment edges are already excluded upstream (file-only architecture view).
-_FLOW_EDGE_TYPES = frozenset({"imports", "depends_on"})
+# Edge types that represent "uses at runtime" for reachability. This used to be
+# {"imports", "depends_on"}; "depends_on" is a knowledge-graph export label and
+# never a persisted edge_type, so only "imports" ever matched and framework and
+# dynamic wiring were invisible to reachability.
+_FLOW_EDGE_TYPES = FILE_DEPENDENCY_EDGE_TYPES
_SIZE_WEIGHT = {"simple": 0.0, "moderate": 0.5, "complex": 1.0}
diff --git a/tests/unit/dead_code/test_decorators_dynamic.py b/tests/unit/dead_code/test_decorators_dynamic.py
index 1c999810e..ea292a48e 100644
--- a/tests/unit/dead_code/test_decorators_dynamic.py
+++ b/tests/unit/dead_code/test_decorators_dynamic.py
@@ -155,7 +155,7 @@ def test_dynamic_edge_clamps_unreachable_confidence():
},
},
edges=[
- ("pkg/dispatcher.py", "pkg/handler.py", {"edge_type": "dynamic"}),
+ ("pkg/dispatcher.py", "pkg/handler.py", {"edge_type": "dynamic_uses"}),
],
)
diff --git a/tests/unit/dead_code/test_dynamic_import_dirs.py b/tests/unit/dead_code/test_dynamic_import_dirs.py
index d6fd752cb..5c4d36e39 100644
--- a/tests/unit/dead_code/test_dynamic_import_dirs.py
+++ b/tests/unit/dead_code/test_dynamic_import_dirs.py
@@ -38,7 +38,7 @@ def _orphan_graph() -> nx.DiGraph:
# pkg_b: orphan sits in a package with NO dynamic edge at all
"pkg_b/orphan.py": {"symbol_count": 5, "symbols": []},
},
- edges=[("pkg_a/dispatcher.py", "pkg_a/handler.py", {"edge_type": "dynamic"})],
+ edges=[("pkg_a/dispatcher.py", "pkg_a/handler.py", {"edge_type": "dynamic_uses"})],
)
@@ -110,7 +110,7 @@ def test_repo_root_dynamic_import_clamps_other_root_files():
"orphan.py": {"symbol_count": 5, "symbols": []},
"pkg_c/orphan.py": {"symbol_count": 5, "symbols": []},
},
- edges=[("loader.py", "main.py", {"edge_type": "dynamic"})],
+ edges=[("loader.py", "main.py", {"edge_type": "dynamic_uses"})],
)
analyzer = DeadCodeAnalyzer(
graph, git_meta_map=_stale_meta("orphan.py", "pkg_c/orphan.py")
diff --git a/tests/unit/ingestion/test_edge_type_vocabulary.py b/tests/unit/ingestion/test_edge_type_vocabulary.py
new file mode 100644
index 000000000..e633653a9
--- /dev/null
+++ b/tests/unit/ingestion/test_edge_type_vocabulary.py
@@ -0,0 +1,278 @@
+"""The declared edge-type vocabulary must stay true in both directions.
+
+`EdgeType` in :mod:`repowise.core.ingestion.models` was decorative for most of
+this repo's life: nothing checked it, so it drifted both ways at once. It
+declared `has_property`, `method_overrides` and a bare `dynamic` that no
+producer has ever emitted, and it omitted `reads`, `dynamic_uses`,
+`dynamic_imports` and `dynamic_url_route`, which producers emit constantly
+(6,750 rows across 42 local indexes).
+
+That is not a cosmetic defect. Thirteen modules each wrote a private set of
+"which edges are dependencies" *against the declaration*, so three of them
+tested for the bare `"dynamic"` and matched none of the 6,153 real `dynamic_*`
+edges, and `reads` reached exactly one of the thirteen. A vocabulary nothing
+enforces produces consumers that are all subtly, invisibly wrong.
+
+Two directions, two tests:
+
+* **Nothing emits an undeclared type** — every `add_edge` call site in the
+ packages passes an `edge_type=` the Literal knows.
+* **Nothing consumes a type no one emits** — every module-level `*_EDGE_TYPES`
+ set holds only real members, so a dead key like `"heritage"` cannot sit in a
+ dependency set pretending to do work.
+
+Ceiling: this is an AST check on *literal* edge types, in both the
+`add_edge(..., edge_type="x")` and the `{"edge_type": "x"}`-then-splat forms.
+What it cannot see is a computed value — `add_dynamic_edges` builds one by
+prefixing — so those files are listed in ``_COMPUTED`` and covered instead by
+the `DynamicKind` Literal on the field they read. A type assembled at runtime
+from a variable would still slip through, so this is not a proof that no
+undeclared type can be emitted.
+
+mypy cannot do this job instead: every `add_edge` in the tree ultimately lands
+on ``networkx.DiGraph.add_edge(**attrs)`` or ``GraphStore.add_edge(**attrs:
+Any)``, so there is no parameter to annotate and no error for it to raise.
+"""
+
+from __future__ import annotations
+
+import ast
+import pathlib
+
+import pytest
+
+from repowise.core.ingestion.models import EDGE_TYPE_VALUES
+
+_PACKAGES = pathlib.Path(__file__).resolve().parents[3] / "packages"
+
+# Call sites that build the edge type instead of naming it. Each needs the
+# reason it cannot be a literal, because "it's computed" is also what a call
+# site looks like just before it starts emitting something undeclared.
+_COMPUTED: frozenset[str] = frozenset(
+ {
+ # Prefixes a `DynamicKind` into `dynamic_<kind>`. The input vocabulary
+ # is a Literal, so the output is closed even though it is not literal
+ # here; `test_every_dynamic_kind_maps_into_the_vocabulary` pins it.
+ "packages/core/src/repowise/core/ingestion/graph/_edges.py",
+ # Both replay persisted rows back onto a fresh graph. The edge type
+ # comes from the database, which this test cannot reach; the rows were
+ # written by the producers this test does check.
+ "packages/core/src/repowise/core/ingestion/graph/_rehydrate.py",
+ "packages/core/src/repowise/core/persistence/coordinator.py",
+ }
+)
+
+# `add_edge` calls on graphs that are not the symbol/file dependency graph, so
+# `EdgeType` does not govern them. Each is a separate model with its own
+# vocabulary.
+_OTHER_GRAPHS: frozenset[str] = frozenset(
+ {
+ # Cross-repo SystemGraph: `kind` is a SystemEdge kind ("package",
+ # "co_change", contract-derived), a different vocabulary entirely.
+ "packages/core/src/repowise/core/workspace/system_graph.py",
+ "packages/core/src/repowise/core/workspace/architecture_metrics.py",
+ # Scratch networkx graphs built for one algorithm and discarded:
+ # community detection, cycle finding, split scoring, page levels.
+ # They carry no edge_type at all.
+ "packages/core/src/repowise/core/analysis/communities.py",
+ "packages/core/src/repowise/core/analysis/health/refactoring/graph_signals.py",
+ "packages/core/src/repowise/core/analysis/health/refactoring/split_file.py",
+ "packages/core/src/repowise/core/generation/page_generator/levels.py",
+ # Interface/passthrough declarations, not producers.
+ "packages/core/src/repowise/core/persistence/_interfaces/graph_store.py",
+ "packages/core/src/repowise/core/persistence/stores/in_process_graph_store.py",
+ }
+)
+
+
+def _python_files() -> list[pathlib.Path]:
+ return [p for p in _PACKAGES.rglob("*.py") if "node_modules" not in p.parts]
+
+
+def _rel(path: pathlib.Path) -> str:
+ return path.relative_to(_PACKAGES.parents[0]).as_posix()
+
+
+def _edge_type_literals() -> dict[str, set[str]]:
+ """Map of repo-relative path -> literal `edge_type=` values it passes to add_edge."""
+ found: dict[str, set[str]] = {}
+ for path in _python_files():
+ rel = _rel(path)
+ if rel in _OTHER_GRAPHS or rel in _COMPUTED:
+ continue
+ try:
+ tree = ast.parse(path.read_text(encoding="utf-8"))
+ except (SyntaxError, UnicodeDecodeError):
+ continue
+ for node in ast.walk(tree):
+ # `graph.add_edge(u, v, edge_type="imports")`
+ if isinstance(node, ast.Call):
+ func = node.func
+ name = func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", "")
+ if name != "add_edge":
+ continue
+ for kw in node.keywords:
+ if kw.arg == "edge_type" and _is_str_constant(kw.value):
+ found.setdefault(rel, set()).add(kw.value.value) # type: ignore[attr-defined]
+ # `attrs = {"edge_type": "imports", ...}` then `add_edge(u, v, **attrs)`.
+ # builder.py builds edges this way, so without this the splat form
+ # would be invisible to the check.
+ elif isinstance(node, ast.Dict):
+ for key, val in zip(node.keys, node.values, strict=True):
+ if (
+ isinstance(key, ast.Constant)
+ and key.value == "edge_type"
+ and _is_str_constant(val)
+ ):
+ found.setdefault(rel, set()).add(val.value) # type: ignore[attr-defined]
+ return found
+
+
+def _is_str_constant(node: ast.expr) -> bool:
+ return isinstance(node, ast.Constant) and isinstance(node.value, str)
+
+
+def _edge_type_set_members() -> dict[str, set[str]]:
+ """Map of `path::CONSTANT_NAME` -> string members of every *_EDGE_TYPES collection."""
+ found: dict[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
+ 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):
+ continue
+ if node.value is None:
+ continue
+ members = _string_members(node.value)
+ if members:
+ found[f"{rel}::{names[0]}"] = members
+ return found
+
+
+def _string_members(value: ast.expr) -> set[str]:
+ """Every string literal in a set expression, through calls and `|` unions.
+
+ Recursing through `BinOp` is the point. `SYMBOL_USE_EDGE_TYPES | {"heritage"}`
+ is a legal way to write a set, and a version of this that skipped BinOp
+ entirely let exactly the dead key it was written to catch survive by moving
+ to the right of the pipe.
+ """
+ # frozenset({...}) / set({...}) unwrap to their single argument.
+ if isinstance(value, ast.Call):
+ return set().union(*(_string_members(a) for a in value.args)) if value.args else set()
+ if isinstance(value, ast.BinOp):
+ return _string_members(value.left) | _string_members(value.right)
+ if isinstance(value, ast.Set | ast.List | ast.Tuple):
+ return {
+ el.value for el in value.elts if isinstance(el, ast.Constant) and isinstance(el.value, str)
+ }
+ return set() # a bare Name — checked where it is defined
+
+
+def test_nothing_emits_an_undeclared_edge_type() -> None:
+ offenders = {
+ path: sorted(values - EDGE_TYPE_VALUES)
+ for path, values in _edge_type_literals().items()
+ if values - EDGE_TYPE_VALUES
+ }
+ assert not offenders, (
+ "add_edge call site(s) emitting an edge type the EdgeType Literal does not declare:\n"
+ + "\n".join(f" {p}: {', '.join(v)}" for p, v in sorted(offenders.items()))
+ + "\n\nAdd it to EdgeType in repowise.core.ingestion.models, or emit a declared type."
+ " An undeclared type is invisible to every consumer that filters on the vocabulary."
+ )
+
+
+def test_no_consumer_set_holds_a_type_nothing_emits() -> None:
+ offenders = {
+ name: sorted(members - EDGE_TYPE_VALUES)
+ for name, members in _edge_type_set_members().items()
+ if members - EDGE_TYPE_VALUES
+ }
+ assert not offenders, (
+ "Edge-type set(s) containing a type no producer emits:\n"
+ + "\n".join(f" {n}: {', '.join(v)}" for n, v in sorted(offenders.items()))
+ + "\n\nA dead key does no work and hides that the set is incomplete —"
+ " `_DEPENDENCY_EDGE_TYPES` held 'heritage' while missing every real dynamic_* type."
+ " Remove it, or add the type to EdgeType if something really does emit it."
+ )
+
+
[email protected]("exempt", sorted(_COMPUTED | _OTHER_GRAPHS))
+def test_exemptions_still_call_add_edge(exempt: str) -> None:
+ """Every exemption must still be a real add_edge site, so neither list can rot.
+
+ Both lists, not just ``_COMPUTED``: an entry left in ``_OTHER_GRAPHS`` after
+ its file starts writing real ``EdgeType`` values would be exempt forever
+ and silently.
+ """
+ path = _PACKAGES.parents[0] / exempt
+ assert path.exists(), f"{exempt} no longer exists — remove it from the exemption list"
+ assert "add_edge" in path.read_text(encoding="utf-8"), (
+ f"{exempt} no longer calls add_edge — remove it from the exemption list"
+ )
+
+
+def test_every_dynamic_kind_maps_into_the_vocabulary() -> None:
+ """The one computed edge type that matters, pinned to its real transform.
+
+ Mirrors `EdgesMixin.add_dynamic_edges`. If a new `DynamicKind` lands
+ without its prefixed form being declared, this fails rather than shipping
+ an edge type no consumer can see.
+ """
+ from typing import get_args
+
+ from repowise.core.ingestion.models import DynamicKind
+
+ for kind in get_args(DynamicKind):
+ emitted = kind if kind.startswith("dynamic") else f"dynamic_{kind}"
+ assert emitted in EDGE_TYPE_VALUES, (
+ f"DynamicKind {kind!r} reaches the graph as {emitted!r}, which EdgeType"
+ " does not declare."
+ )
+
+
+def test_edge_type_map_covers_the_vocabulary() -> None:
+ """The knowledge-graph export must map every dependency edge type.
+
+ `build_knowledge_graph_skeleton` drops an unmapped type silently, and six
+ real ones were missing — framework and the dynamic_* family among them —
+ so those relations never reached the graph at all.
+ """
+ from repowise.core.analysis.knowledge_graph import _EDGE_TYPE_MAP
+ from repowise.core.ingestion.models import TEMPORAL_EDGE_TYPES
+
+ # Temporal edges are excluded on purpose; see the comment on _EDGE_TYPE_MAP.
+ expected = EDGE_TYPE_VALUES - TEMPORAL_EDGE_TYPES
+ assert not (expected - _EDGE_TYPE_MAP.keys()), (
+ "edge type(s) silently dropped from the knowledge-graph export: "
+ f"{sorted(expected - _EDGE_TYPE_MAP.keys())}"
+ )
+ assert not (_EDGE_TYPE_MAP.keys() - EDGE_TYPE_VALUES), (
+ f"export mapping keyed on a type nothing emits: {sorted(_EDGE_TYPE_MAP.keys() - EDGE_TYPE_VALUES)}"
+ )
+ assert not (_EDGE_TYPE_MAP.keys() & TEMPORAL_EDGE_TYPES), (
+ "a temporal edge reached the dependency export — that is how a co-change"
+ " partner starts looking like an import"
+ )
+
+
[email protected]("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.
+
+ Named individually so a re-add has to argue with the specific string rather
+ than a count.
+ """
+ assert phantom not in EDGE_TYPE_VALUES
diff --git a/tests/unit/ingestion/test_graph.py b/tests/unit/ingestion/test_graph.py
index b4c671354..4e6c5e355 100644
--- a/tests/unit/ingestion/test_graph.py
+++ b/tests/unit/ingestion/test_graph.py
@@ -915,7 +915,10 @@ class TestDynamicEdgeExcludeFilter:
return DynamicEdge(
source="src/main.py",
target=target,
- edge_type="co_change",
+ # Incidental to this test, but it has to be a real DynamicKind:
+ # anything else is minted as `dynamic_<kind>` and lands in the
+ # graph as an edge type nothing declares.
+ edge_type="dynamic_uses",
hint_source="git",
weight=1.0,
)
diff --git a/tests/unit/server/services/test_c4_edge_verb_coverage.py b/tests/unit/server/services/test_c4_edge_verb_coverage.py
new file mode 100644
index 000000000..89953d7bf
--- /dev/null
+++ b/tests/unit/server/services/test_c4_edge_verb_coverage.py
@@ -0,0 +1,36 @@
+"""The C4 verb map must stay total over the edge-type vocabulary.
+
+`relation_label` falls through to "depends on" for an unknown type, and that
+fall-through is silent: `framework` and `dynamic_uses` rendered that way for
+their whole life, covering 10% of file-level edges on a live index, and
+`type_use` (6,596 rows across 42 local indexes) still did until this test
+existed.
+
+Lives here rather than beside the other vocabulary tests in
+`tests/unit/ingestion/` because it imports `repowise.server` — an ingestion
+test that hard-fails when only the core package is installed is a worse trade
+than a slightly split test suite.
+"""
+
+from __future__ import annotations
+
+from repowise.core.ingestion.models import EDGE_TYPE_VALUES
+from repowise.server.services.c4_builder.labels import _EDGE_VERB, _VERB_PRIORITY
+
+
+def test_every_edge_type_has_a_verb() -> None:
+ missing = sorted(EDGE_TYPE_VALUES - _EDGE_VERB.keys())
+ assert not missing, (
+ f"edge type(s) with no C4 verb — they render as the vague 'depends on': {missing}"
+ )
+
+
+def test_no_verb_is_keyed_on_a_type_nothing_emits() -> None:
+ dead = sorted(_EDGE_VERB.keys() - EDGE_TYPE_VALUES)
+ assert not dead, f"C4 verb(s) keyed on a type nothing emits: {dead}"
+
+
+def test_every_verb_can_be_ranked() -> None:
+ """An aggregated edge picks the highest-priority verb, so an unranked one never wins."""
+ unranked = sorted(set(_EDGE_VERB.values()) - set(_VERB_PRIORITY))
+ assert not unranked, f"verb(s) missing from _VERB_PRIORITY: {unranked}"