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.

feat(graph): record which strategy resolved each call edge (#1628)

Raghav Chamadiya0c746bd2c44d
diff --git a/packages/core/alembic/versions/0053_graph_edge_resolution_origin.py b/packages/core/alembic/versions/0053_graph_edge_resolution_origin.py
new file mode 100644
index 000000000..59af8893f
--- /dev/null
+++ b/packages/core/alembic/versions/0053_graph_edge_resolution_origin.py
@@ -0,0 +1,45 @@
+"""Record which resolution strategy produced a call edge.
+
+Call resolution runs a cascade of strategies whose confidences overlap: a
+same-file match and a self/this match both score 0.95, and a repo-wide unique
+name scores 0.50 — a guess that execution-flow tracing admits at exactly the
+threshold it clears. Once an edge reached the graph, which strategy minted it
+was unrecoverable, so a consumer could not tell a certainty from a guess.
+
+``graph_edges.resolution_origin`` carries one name from the closed
+``ResolutionOrigin`` vocabulary. NULL means the row predates the vocabulary or
+the edge is not resolver-produced; consumers omit the field rather than showing
+it as unknown, so no re-index is required.
+
+``init_db``'s additive schema reconciler picks the column up from the model for
+local SQLite stores that never run Alembic; this migration covers the managed
+Postgres ones.
+
+Revision ID: 0053
+Revises: 0052
+Create Date: 2026-08-16
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers
+revision: str = "0053"
+down_revision: str | None = "0052"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ op.add_column(
+ "graph_edges",
+ sa.Column("resolution_origin", sa.String(length=32), nullable=True),
+ )
+
+
+def downgrade() -> None:
+ op.drop_column("graph_edges", "resolution_origin")
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
index c4a467301..1b1fcc8f2 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -16,8 +16,10 @@ Resolution tiers (checked in order, first match wins):
The call target matches exactly one symbol across the entire codebase.
Only fires when the match is unambiguous to avoid false edges.
-Each resolved call produces a (source_id, target_id, confidence) triple that
-the GraphBuilder converts into a CALLS edge.
+Each resolved call produces a (source_id, target_id, confidence, origin) tuple
+that the GraphBuilder converts into a CALLS edge. The tiers above are the
+headline three; ``ResolutionOrigin`` in ``models`` is the full set, one name
+per strategy, and it is what the edge carries.
"""
from __future__ import annotations
@@ -28,7 +30,7 @@ from typing import Any
import structlog
-from .models import CallSite, NamedBinding, ParsedFile
+from .models import CallSite, NamedBinding, ParsedFile, ResolutionOrigin
log = structlog.get_logger(__name__)
@@ -48,6 +50,7 @@ class ResolvedCall:
callee_id: str # symbol node ID of the called function/method
confidence: float # 0.0–1.0
line: int # call site line number (for diagnostics)
+ origin: ResolutionOrigin # which strategy below produced it
class CallResolver:
@@ -291,7 +294,7 @@ class CallResolver:
syms = self._file_symbols.get(sibling, {})
sym_id = syms.get(call.target_name)
if sym_id is not None and sym_id != caller_id:
- return ResolvedCall(caller_id, sym_id, 0.85, call.line)
+ return ResolvedCall(caller_id, sym_id, 0.85, call.line, "same_target")
return None
def _get_jvm_index(self) -> Any:
@@ -335,7 +338,7 @@ class CallResolver:
syms = self._file_symbols.get(sibling, {})
sym_id = syms.get(call.target_name)
if sym_id is not None and sym_id != caller_id:
- return ResolvedCall(caller_id, sym_id, 0.90, call.line)
+ return ResolvedCall(caller_id, sym_id, 0.90, call.line, "same_package")
return None
def _resolve_go_package_call(
@@ -364,7 +367,7 @@ class CallResolver:
syms = self._file_symbols.get(sibling, {})
sym_id = syms.get(call.target_name)
if sym_id is not None and sym_id != caller_id:
- return ResolvedCall(caller_id, sym_id, 0.88, call.line)
+ return ResolvedCall(caller_id, sym_id, 0.88, call.line, "package_alias")
return None
def _resolve_go_same_package(
@@ -392,7 +395,7 @@ class CallResolver:
syms = self._file_symbols.get(sibling, {})
sym_id = syms.get(call.target_name)
if sym_id is not None and sym_id != caller_id:
- return ResolvedCall(caller_id, sym_id, 0.90, call.line)
+ return ResolvedCall(caller_id, sym_id, 0.90, call.line, "same_package")
return None
def _build_indices(self, parsed_files: dict[str, ParsedFile]) -> None:
@@ -499,7 +502,13 @@ class CallResolver:
target = self._decl_to_def.get(resolved.callee_id)
if target is None or target == resolved.caller_id:
return resolved
- return ResolvedCall(resolved.caller_id, target, resolved.confidence, resolved.line)
+ return ResolvedCall(
+ resolved.caller_id,
+ target,
+ resolved.confidence,
+ resolved.line,
+ resolved.origin,
+ )
def _merged_symbols_for(self, file_path: str) -> dict[str, str]:
"""Merged ``{name → symbol_id}`` across every file *file_path* imports.
@@ -578,7 +587,7 @@ class CallResolver:
if target_name in file_syms:
callee_id = file_syms[target_name]
if callee_id != caller_id: # no self-recursion edges for now
- return ResolvedCall(caller_id, callee_id, 0.95, call.line)
+ return ResolvedCall(caller_id, callee_id, 0.95, call.line, "same_file")
# Go: a bare call may target a function defined in a sibling file of
# the same package (shared namespace, no import). Resolve against the
@@ -615,7 +624,9 @@ class CallResolver:
source_file = barrel[lookup_name]
source_syms = self._file_symbols.get(source_file, {})
if lookup_name in source_syms:
- return ResolvedCall(caller_id, source_syms[lookup_name], 0.90, call.line)
+ return ResolvedCall(
+ caller_id, source_syms[lookup_name], 0.90, call.line, "import_scoped"
+ )
# 2a fallback: plain _import_names (for imports without binding data)
name_to_file = self._import_names.get(file_path, {})
@@ -626,12 +637,16 @@ class CallResolver:
source_file = barrel[target_name]
source_syms = self._file_symbols.get(source_file, {})
if target_name in source_syms:
- return ResolvedCall(caller_id, source_syms[target_name], 0.90, call.line)
+ return ResolvedCall(
+ caller_id, source_syms[target_name], 0.90, call.line, "import_scoped"
+ )
# 2b: Check all imported files for the symbol (pre-merged lookup)
merged_syms = self._merged_symbols_for(file_path)
if target_name in merged_syms:
- return ResolvedCall(caller_id, merged_syms[target_name], 0.85, call.line)
+ return ResolvedCall(
+ caller_id, merged_syms[target_name], 0.85, call.line, "import_merged"
+ )
# Tier 3: global unique match — only within the same language
candidates = self._global_symbols.get(target_name, [])
@@ -640,7 +655,7 @@ class CallResolver:
callee_lang = _file_language(self._parsed_files, candidates[0])
if caller_lang and callee_lang and caller_lang != callee_lang:
return None # reject cross-language Tier 3 match
- return ResolvedCall(caller_id, candidates[0], 0.50, call.line)
+ return ResolvedCall(caller_id, candidates[0], 0.50, call.line, "global_unique")
return None
@@ -673,18 +688,18 @@ class CallResolver:
methods = self._file_methods.get(sibling, {})
key = (receiver_name, method_name)
if key in methods:
- return ResolvedCall(caller_id, methods[key], 0.90, call.line)
- syms = self._file_symbols.get(sibling, {})
- # Found the class; look for the method on it
- if receiver_name in syms and key in methods:
- return ResolvedCall(caller_id, methods[key], 0.88, call.line)
+ return ResolvedCall(
+ caller_id, methods[key], 0.90, call.line, "receiver_same_package"
+ )
# Strategy 1: receiver is a module alias (e.g. "import models" → "models.User()")
module_file = self._module_aliases.get(file_path, {}).get(receiver_name)
if module_file:
source_syms = self._file_symbols.get(module_file, {})
if method_name in source_syms:
- return ResolvedCall(caller_id, source_syms[method_name], 0.88, call.line)
+ return ResolvedCall(
+ caller_id, source_syms[method_name], 0.88, call.line, "module_alias"
+ )
# Strategy 1b: receiver in import names (non-alias fallback for backward compat)
name_to_file = self._import_names.get(file_path, {})
@@ -692,7 +707,9 @@ class CallResolver:
source_file = name_to_file[receiver_name]
source_syms = self._file_symbols.get(source_file, {})
if method_name in source_syms:
- return ResolvedCall(caller_id, source_syms[method_name], 0.88, call.line)
+ return ResolvedCall(
+ caller_id, source_syms[method_name], 0.88, call.line, "module_alias"
+ )
# Strategy 1c: Rust crate-scoped reference (e.g. typst_html::module)
# The receiver is a crate name, the target is a symbol in that crate's lib.rs
@@ -702,19 +719,25 @@ class CallResolver:
crate_root = f"{crate_src}/{root_file}"
root_syms = self._file_symbols.get(crate_root, {})
if method_name in root_syms:
- return ResolvedCall(caller_id, root_syms[method_name], 0.88, call.line)
+ return ResolvedCall(
+ caller_id, root_syms[method_name], 0.88, call.line, "crate_root"
+ )
# Strategy 2: receiver is a known class name → look for method on that class
# Check same-file classes first
file_methods = self._file_methods.get(file_path, {})
key = (receiver_name, method_name)
if key in file_methods:
- return ResolvedCall(caller_id, file_methods[key], 0.93, call.line)
+ return ResolvedCall(
+ caller_id, file_methods[key], 0.93, call.line, "receiver_same_file"
+ )
# Check imported files for (class, method) pairs (pre-merged lookup)
merged_methods = self._merged_methods_for(file_path)
if key in merged_methods:
- return ResolvedCall(caller_id, merged_methods[key], 0.88, call.line)
+ return ResolvedCall(
+ caller_id, merged_methods[key], 0.88, call.line, "receiver_import"
+ )
# Strategy 2b: trait method dispatch — receiver is a type that
# implements a trait; the method may be defined on the trait's
@@ -724,7 +747,7 @@ class CallResolver:
for _path, sym_id in self._global_methods.get(key, ()):
if _path == file_path:
continue
- return ResolvedCall(caller_id, sym_id, 0.75, call.line)
+ return ResolvedCall(caller_id, sym_id, 0.75, call.line, "receiver_global")
# Strategy 3: receiver is "self" or "this" — look in same class.
# Only the caller's own file can hold the match, so index straight
@@ -740,7 +763,7 @@ class CallResolver:
and sym_id != caller_id
and cls_name == caller_class
):
- return ResolvedCall(caller_id, sym_id, 0.95, call.line)
+ return ResolvedCall(caller_id, sym_id, 0.95, call.line, "self_scope")
# No further fallback: any (class, method) pair present in any file's
# method index was already resolved by strategy 2 (same file) or 2b
diff --git a/packages/core/src/repowise/core/ingestion/graph/_rehydrate.py b/packages/core/src/repowise/core/ingestion/graph/_rehydrate.py
index 86b3890c6..9e966a341 100644
--- a/packages/core/src/repowise/core/ingestion/graph/_rehydrate.py
+++ b/packages/core/src/repowise/core/ingestion/graph/_rehydrate.py
@@ -110,6 +110,9 @@ class RehydrateMixin:
hint_source = edge.get("hint_source")
if hint_source:
edge_attrs["hint_source"] = hint_source
+ resolution_origin = edge.get("resolution_origin")
+ if resolution_origin:
+ edge_attrs["resolution_origin"] = resolution_origin
graph.add_edge(source, target, **edge_attrs)
edge_count += 1
diff --git a/packages/core/src/repowise/core/ingestion/graph/_resolvers.py b/packages/core/src/repowise/core/ingestion/graph/_resolvers.py
index 8db2e35d0..adf28e62e 100644
--- a/packages/core/src/repowise/core/ingestion/graph/_resolvers.py
+++ b/packages/core/src/repowise/core/ingestion/graph/_resolvers.py
@@ -528,12 +528,17 @@ class ResolveMixin:
rc.callee_id,
edge_type="calls",
confidence=rc.confidence,
+ resolution_origin=rc.origin,
)
total_resolved += 1
else:
+ # Several call sites collapse onto one edge; the
+ # strongest wins, and the origin has to follow the
+ # confidence it explains.
existing = self._graph[rc.caller_id][rc.callee_id]
if rc.confidence > existing.get("confidence", 0):
existing["confidence"] = rc.confidence
+ existing["resolution_origin"] = rc.origin
if progress:
progress.on_item_done("graph.calls")
@@ -591,6 +596,7 @@ class ResolveMixin:
rc.callee_id,
edge_type="references",
confidence=rc.confidence,
+ resolution_origin=rc.origin,
)
total += 1
log.info("Reference edges resolved", total=total)
diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.py
index 361de9381..a96dea56e 100644
--- a/packages/core/src/repowise/core/ingestion/models.py
+++ b/packages/core/src/repowise/core/ingestion/models.py
@@ -315,6 +315,40 @@ EdgeType = Literal[
# copy is the exact failure this phase exists to remove.
EDGE_TYPE_VALUES: frozenset[str] = frozenset(get_args(EdgeType))
+# Which resolution strategy produced a `calls` / `references` edge. Same
+# closed-vocabulary discipline as `EdgeType`, held shut by the same test.
+#
+# An edge is not a fact. `global_unique` binds a name to the only symbol
+# carrying it anywhere in the repo, which is a guess; `same_file` is a
+# certainty. Both used to reach a consumer as an unlabelled arrow, so an agent
+# reading a flow could not tell which it was looking at.
+#
+# Every origin has exactly one confidence (see `CallResolver`), so the origin
+# distribution and the confidence histogram are two views of the same data —
+# which is what makes the stamping checkable against the existing numbers.
+# NULL on an edge means the row predates this vocabulary, not "unknown origin".
+ResolutionOrigin = Literal[
+ "same_file", # 0.95 — defined in the calling file
+ "self_scope", # 0.95 — self/this, method on the caller's own class
+ "receiver_same_file", # 0.93 — receiver names a class in this file
+ "same_package", # 0.90 — Go/JVM sibling file, no import needed
+ "import_scoped", # 0.90 — the name was imported from the defining file
+ "receiver_same_package", # 0.90 — receiver is a same-package class (JVM)
+ "package_alias", # 0.88 — Go pkg.Func, resolved across the whole package
+ "module_alias", # 0.88 — receiver is an imported module
+ "crate_root", # 0.88 — Rust crate-scoped reference
+ "receiver_import", # 0.88 — receiver class found in an imported file
+ "import_merged", # 0.85 — in *some* imported file; which one is unattributed
+ "same_target", # 0.85 — C/C++ sibling TU of the same build target
+ # 0.75 — the (class, method) pair exists somewhere in the repo. The member
+ # analogue of `global_unique`, and no more than that: the strategy is
+ # named for Rust trait impls but is gated on no language.
+ "receiver_global",
+ "global_unique", # 0.50 — the name is unique repo-wide. A guess.
+]
+
+RESOLUTION_ORIGIN_VALUES: frozenset[str] = frozenset(get_args(ResolutionOrigin))
+
# 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
diff --git a/packages/core/src/repowise/core/persistence/crud/graph.py b/packages/core/src/repowise/core/persistence/crud/graph.py
index ab5a2f882..03c7d7458 100644
--- a/packages/core/src/repowise/core/persistence/crud/graph.py
+++ b/packages/core/src/repowise/core/persistence/crud/graph.py
@@ -93,6 +93,10 @@ def _update_graph_edge(existing: GraphEdge, edge_data: dict) -> None:
# (_resolvers.py:504-505). A pair can carry several resolved calls of
# differing confidence; a last-write upsert could stamp a real call
# below _FLOW_CALLS_CONF_FLOOR (0.5) and drop it from flow-path answers.
+ # The origin explains the confidence, so it moves only when the
+ # confidence does.
+ if confidence > (existing.confidence or 0.0):
+ existing.resolution_origin = edge_data.get("resolution_origin")
existing.confidence = max(existing.confidence or 0.0, confidence)
@@ -162,7 +166,8 @@ async def batch_upsert_graph_edges(
"""Upsert graph edges for a repository.
Each element of *edges* should have ``source_node_id``, ``target_node_id``,
- ``edge_type``, and optionally ``imported_names_json`` and ``confidence``.
+ ``edge_type``, and optionally ``imported_names_json``, ``confidence``,
+ ``hint_source`` and ``resolution_origin``.
The unique constraint is (repository_id, source, target, edge_type),
allowing multiple edge types between the same pair of nodes.
@@ -188,6 +193,7 @@ async def batch_upsert_graph_edges(
edge_type=e.get("edge_type", "imports"),
confidence=e.get("confidence", 1.0),
hint_source=e.get("hint_source"),
+ resolution_origin=e.get("resolution_origin"),
),
)
@@ -281,6 +287,7 @@ async def reconcile_edges_for_files(
edge_type=e.get("edge_type", "imports"),
confidence=e.get("confidence", 1.0),
hint_source=e.get("hint_source"),
+ resolution_origin=e.get("resolution_origin"),
)
)
await session.flush()
@@ -514,6 +521,7 @@ async def get_all_graph_edges(
"confidence": row.confidence,
"imported_names": imported_names,
"hint_source": row.hint_source,
+ "resolution_origin": row.resolution_origin,
}
)
return edges
diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.py
index 014f95ef6..c011106dd 100644
--- a/packages/core/src/repowise/core/persistence/models.py
+++ b/packages/core/src/repowise/core/persistence/models.py
@@ -314,6 +314,12 @@ class GraphEdge(Base):
# repowise.core.ingestion.cohesion. Persisted because the health engine and
# incremental updates run against a graph rehydrated from these rows.
hint_source: Mapped[str | None] = mapped_column(String(64), nullable=True)
+ # Which resolution strategy produced a ``calls`` / ``references`` edge, from
+ # the closed ``ResolutionOrigin`` vocabulary. NULL means the row predates
+ # the vocabulary or the edge is not resolver-produced — not "unknown".
+ # Persisted because the graph is rehydrated from these rows, so an
+ # unpersisted origin would exist only on the indexing run that minted it.
+ resolution_origin: Mapped[str | None] = mapped_column(String(32), nullable=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, default=_now_utc
)
diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.py
index 9204a4d0e..2a499ea9e 100644
--- a/packages/core/src/repowise/core/pipeline/persist.py
+++ b/packages/core/src/repowise/core/pipeline/persist.py
@@ -489,6 +489,7 @@ def _changed_file_edges(
"edge_type": data.get("edge_type", "imports"),
"confidence": data.get("confidence", 1.0),
"hint_source": data.get("hint_source"),
+ "resolution_origin": data.get("resolution_origin"),
}
)
return sorted(reconcile), edges
@@ -1366,6 +1367,7 @@ async def persist_ingestion(result: Any, session: Any, repo_id: str) -> int:
"edge_type": data.get("edge_type", "imports"),
"confidence": data.get("confidence", 1.0),
"hint_source": data.get("hint_source"),
+ "resolution_origin": data.get("resolution_origin"),
}
)
if edges:
diff --git a/packages/server/src/repowise/server/mcp_server/_graph_utils.py b/packages/server/src/repowise/server/mcp_server/_graph_utils.py
index f067d68a5..c68daec7e 100644
--- a/packages/server/src/repowise/server/mcp_server/_graph_utils.py
+++ b/packages/server/src/repowise/server/mcp_server/_graph_utils.py
@@ -68,6 +68,7 @@ async def bfs_trace(
entry_id: str,
max_depth: int,
node_cache: dict[str, GraphNode] | None = None,
+ hop_origins: dict[tuple[str, str], str] | None = None,
) -> list[str]:
"""Trace the primary execution path from *entry_id* along ``calls`` edges.
@@ -78,6 +79,11 @@ async def bfs_trace(
DB-cheap proxy for the core scorer's fan-out ordering). Test/demo/fixture
nodes and low-confidence (< 0.5) edges are skipped; a visited set keeps it
cycle-safe.
+
+ *hop_origins*, when given, is filled with ``{(src, dst): resolution_origin}``
+ for each hop taken. Keyed by pair rather than position because callers
+ filter the returned trace afterwards, and a positional list would then
+ describe the wrong hops.
"""
if node_cache is None:
node_cache = {}
@@ -98,6 +104,7 @@ async def bfs_trace(
best_id: str | None = None
best_conf = -1.0
+ best_origin: str | None = None
for e in edges:
tid = e.target_node_id
conf = e.confidence if e.confidence is not None else 0.0
@@ -110,10 +117,13 @@ async def bfs_trace(
if conf > best_conf:
best_conf = conf
best_id = tid
+ best_origin = e.resolution_origin
if best_id is None:
break
+ if hop_origins is not None and best_origin:
+ hop_origins[(current, best_id)] = best_origin
visited.add(best_id)
trace.append(best_id)
current = best_id
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 7ca642442..6ea86bc43 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
@@ -206,6 +206,10 @@ async def _resolve_call_graph(
"confidence": e.confidence,
"edge_type": e.edge_type,
}
+ # Which resolution strategy produced the edge. Absent on an index built
+ # before origins were stamped, so it is added only when present.
+ if e.resolution_origin:
+ entry["via"] = e.resolution_origin
if is_caller:
callers.append(entry)
else:
diff --git a/packages/server/src/repowise/server/mcp_server/tool_flows.py b/packages/server/src/repowise/server/mcp_server/tool_flows.py
index c1f8a1e24..6f9869515 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_flows.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_flows.py
@@ -9,6 +9,7 @@ off the hot path.
from __future__ import annotations
import time
+from itertools import pairwise
from typing import Any
from repowise.core.persistence.crud import (
@@ -110,8 +111,9 @@ async def get_execution_flows(
flows: list[dict[str, Any]] = []
for ep_node, ep_score in entry_nodes:
+ hop_origins: dict[tuple[str, str], str] = {}
trace = await bfs_trace(
- session, repo_id, ep_node.node_id, max_depth, node_cache
+ session, repo_id, ep_node.node_id, max_depth, node_cache, hop_origins
)
# Drop excluded files reached downstream so they don't leak via the
# trace (entry-point filtering above doesn't cover BFS descendants).
@@ -122,7 +124,7 @@ async def get_execution_flows(
session, repo_id, trace, node_cache
)
- flows.append({
+ flow: dict[str, Any] = {
"entry_point": ep_node.node_id,
"entry_point_name": ep_node.name or ep_node.node_id.split("::")[-1],
"entry_point_score": round(ep_score, 3),
@@ -130,7 +132,14 @@ async def get_execution_flows(
"depth": len(trace) - 1,
"crosses_community": crosses,
"communities_visited": communities_visited,
- })
+ }
+ # Which strategy produced each hop, aligned to `trace` pairwise.
+ # Omitted when no hop has one, so an older index shows no field
+ # rather than a list of nulls.
+ via = [hop_origins.get(pair) for pair in pairwise(trace)]
+ if any(via):
+ flow["trace_via"] = via
+ flows.append(flow)
# Sort by score descending
flows.sort(key=lambda f: -f["entry_point_score"])
diff --git a/tests/unit/ingestion/test_edge_type_vocabulary.py b/tests/unit/ingestion/test_edge_type_vocabulary.py
index a5f02e141..ffa29d6b4 100644
--- a/tests/unit/ingestion/test_edge_type_vocabulary.py
+++ b/tests/unit/ingestion/test_edge_type_vocabulary.py
@@ -329,6 +329,83 @@ def test_an_edge_type_alias_points_at_the_shared_vocabulary() -> None:
)
+def _resolved_call_origins() -> dict[str, set[float]]:
+ """Map origin literal -> confidences it is constructed with, from the AST.
+
+ Reads the ``ResolvedCall(caller, callee, <confidence>, line, <origin>)``
+ construction sites rather than the ``add_edge`` call, because the edge
+ passes a variable and the literal only ever exists at the resolver.
+ """
+ found: dict[str, set[float]] = {}
+ for path in _python_files():
+ try:
+ tree = ast.parse(path.read_text(encoding="utf-8"))
+ except (SyntaxError, UnicodeDecodeError):
+ continue
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call):
+ continue
+ func = node.func
+ name = func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", "")
+ if name != "ResolvedCall":
+ continue
+ origin = next(
+ (kw.value for kw in node.keywords if kw.arg == "origin"),
+ node.args[4] if len(node.args) > 4 else None,
+ )
+ if origin is None or not _is_str_constant(origin):
+ continue
+ confidence = node.args[2] if len(node.args) > 2 else None
+ confs = found.setdefault(origin.value, set()) # type: ignore[attr-defined]
+ if isinstance(confidence, ast.Constant) and isinstance(
+ confidence.value, int | float
+ ):
+ confs.add(float(confidence.value))
+ return found
+
+
+def test_nothing_stamps_an_undeclared_resolution_origin() -> None:
+ from repowise.core.ingestion.models import RESOLUTION_ORIGIN_VALUES
+
+ emitted = set(_resolved_call_origins())
+ assert emitted, "found no ResolvedCall construction sites — the AST scan has rotted"
+ assert not (emitted - RESOLUTION_ORIGIN_VALUES), (
+ "resolution origin(s) stamped but not declared: "
+ f"{sorted(emitted - RESOLUTION_ORIGIN_VALUES)}\n"
+ "Add them to ResolutionOrigin in repowise.core.ingestion.models. An"
+ " undeclared origin reaches consumers as an unrecognised string."
+ )
+
+
+def test_every_declared_resolution_origin_has_a_producer() -> None:
+ """The other direction — the failure `EdgeType` shipped for years.
+
+ A declared origin nothing stamps is a word consumers can filter on and
+ never match, which is indistinguishable from a filter that works.
+ """
+ from repowise.core.ingestion.models import RESOLUTION_ORIGIN_VALUES
+
+ orphans = RESOLUTION_ORIGIN_VALUES - set(_resolved_call_origins())
+ assert not orphans, (
+ f"resolution origin(s) declared with no producer: {sorted(orphans)}"
+ )
+
+
+def test_each_resolution_origin_carries_one_confidence() -> None:
+ """One origin, one confidence — what makes the stamping auditable.
+
+ The origin distribution and the confidence histogram are then two views of
+ the same data, so an origin that starts disagreeing with the number it is
+ supposed to explain fails here instead of quietly reshaping both.
+ """
+ split = {o: sorted(c) for o, c in _resolved_call_origins().items() if len(c) > 1}
+ assert not split, (
+ "resolution origin(s) constructed at more than one confidence:\n"
+ + "\n".join(f" {o}: {c}" for o, c in sorted(split.items()))
+ + "\n\nSplit the origin, or give the strategies one confidence."
+ )
+
+
@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/ingestion/test_graph_rehydrate.py b/tests/unit/ingestion/test_graph_rehydrate.py
index 23ebb09c8..bfd85707e 100644
--- a/tests/unit/ingestion/test_graph_rehydrate.py
+++ b/tests/unit/ingestion/test_graph_rehydrate.py
@@ -129,6 +129,27 @@ def test_rehydrated_graph_is_traversal_equivalent():
assert og[node][succ].get("edge_type") == hg[node][succ].get("edge_type")
+def test_resolution_origin_survives_rehydration():
+ """An edge's origin must outlive the process that resolved it.
+
+ The graph is rebuilt from rows on every incremental update, so an origin
+ that only exists in memory would be present on the indexing run and gone
+ on every read after it. A row without one stays without one — that is what
+ lets an index built before the vocabulary keep working unchanged.
+ """
+ original = _build_sample()
+ nodes, edges = _serialize(original)
+ edges[0] = {**edges[0], "edge_type": "calls", "resolution_origin": "same_file"}
+
+ hydrated = GraphBuilder.from_persisted(nodes, edges, original.file_metrics_snapshot())
+ graph = hydrated.graph()
+
+ stamped = graph[edges[0]["source_node_id"]][edges[0]["target_node_id"]]
+ assert stamped["resolution_origin"] == "same_file"
+ for e in edges[1:]:
+ assert "resolution_origin" not in graph[e["source_node_id"]][e["target_node_id"]]
+
+
def test_rehydrate_without_metrics_falls_back_to_recompute():
"""No snapshot supplied → caches stay empty and metrics recompute on read."""
original = _build_sample()