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.

fix: XAML ingestion, type_use provenance, interface FP cap, .NET perf (#181)

Raghav Chamadiya22c9c94d7b00
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd.py b/packages/cli/src/repowise/cli/commands/init_cmd.py
index 1ec542de0..9929a4d5a 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd.py
@@ -274,6 +274,22 @@ async def _persist_result(
name=result.repo_name,
local_path=str(repo_path),
)
+ # Persist the detected tech stack into the repository's settings
+ # blob. Merge into any pre-existing settings so we don't clobber
+ # unrelated state (workspace flags, etc.). Done here rather than
+ # in upsert_repository so the persistence helper stays
+ # signature-stable.
+ if getattr(result, "tech_stack", None):
+ import json as _json
+
+ try:
+ existing = _json.loads(repo.settings_json or "{}")
+ if not isinstance(existing, dict):
+ existing = {}
+ except Exception:
+ existing = {}
+ existing["tech_stack"] = result.tech_stack
+ repo.settings_json = _json.dumps(existing)
await persist_pipeline_result(result, session, repo.id)
# Record a completed GenerationJob so the web UI can show
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 6c84f137d..cbb81078d 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -467,6 +467,18 @@ class DeadCodeAnalyzer:
else:
confidence = 0.7
+ # Interfaces / protocols are reached almost exclusively
+ # through their implementors. Implementor detection is
+ # heuristic — its absence is "evidence missing", not
+ # "evidence of absence". Cap confidence below the
+ # safe-to-delete threshold when the file containing the
+ # interface has no incoming ``implements``-class edges,
+ # so the demo doesn't ship public-API interfaces as
+ # confident dead code. Generic across all languages
+ # (C#, Java, Kotlin, Scala, Swift protocols, TS).
+ if sym.get("kind") == "interface" and not self._file_has_implementors(node):
+ confidence = min(confidence, 0.4)
+
safe = confidence >= 0.7
git_meta = self.git_meta_map.get(str(node), {})
@@ -687,6 +699,34 @@ class DeadCodeAnalyzer:
def _is_api_contract(self, node_data: dict) -> bool:
return node_data.get("is_api_contract", False)
+ def _file_has_implementors(self, file_node: Any) -> bool:
+ """Return True iff any ``implements`` / ``method_implements`` /
+ ``extends`` edge terminates at *file_node* or at a symbol it
+ defines.
+
+ Implementor detection drives the confidence cap on
+ ``interface``-kind unused-export findings. Resolution quality
+ varies by language (C# DI containers, Java reflection, Swift
+ protocol extensions etc.), so an interface with zero observed
+ implementors should be treated as "missing signal", not
+ "confirmed dead".
+ """
+ implementor_edges = ("implements", "method_implements", "extends")
+ # File-level incoming edges (XAML bindings, framework edges)
+ for pred in self.graph.predecessors(file_node):
+ if self.graph[pred][file_node].get("edge_type") in implementor_edges:
+ return True
+ # Symbol-level incoming edges — interfaces typically receive
+ # ``implements`` edges on the type symbol, not on the file.
+ for succ in self.graph.successors(file_node):
+ succ_data = self.graph.nodes.get(succ, {})
+ if succ_data.get("node_type") != "symbol":
+ continue
+ for pred in self.graph.predecessors(succ):
+ if self.graph[pred][succ].get("edge_type") in implementor_edges:
+ return True
+ return False
+
def _matches_dynamic_patterns(self, path: str, patterns: tuple[str, ...]) -> bool:
name = Path(path).stem
return any(fnmatch.fnmatch(name, pattern) for pattern in patterns)
diff --git a/packages/core/src/repowise/core/ingestion/graph.py b/packages/core/src/repowise/core/ingestion/graph.py
index ac21a1295..a4021b109 100644
--- a/packages/core/src/repowise/core/ingestion/graph.py
+++ b/packages/core/src/repowise/core/ingestion/graph.py
@@ -272,11 +272,23 @@ class GraphBuilder:
# edges feed into heritage's import_targets propagation if a
# future language emits them, and so dead-code reachability
# sees every edge before any analysis pass runs.
+ if progress:
+ progress.on_phase_start("graph.type_refs", len(self._parsed_files))
type_use_counts = resolve_type_refs(self._parsed_files, ctx, self._graph)
for path in self._parsed_files:
for _, target, data in self._graph.out_edges(path, data=True):
- if data.get("edge_type") == "imports":
+ # Treat both real ``using`` imports and synthesised
+ # type-use edges as import-like for downstream heritage
+ # / call resolution. Without this, type-use edges would
+ # only contribute to file-reachability — not to
+ # ``import_targets`` which gates cross-file call /
+ # heritage lookups.
+ if data.get("edge_type") in ("imports", "type_use"):
import_targets.setdefault(path, set()).add(target)
+ if progress:
+ _phase_done = getattr(progress, "on_phase_done", None)
+ if _phase_done is not None:
+ _phase_done("graph.type_refs")
del type_use_counts # used only for logging inside resolve_type_refs
# --- Phase 2: Resolve heritage (extends/implements) ---
diff --git a/packages/core/src/repowise/core/ingestion/languages/registry.py b/packages/core/src/repowise/core/ingestion/languages/registry.py
index 8ba177e7a..d094c9069 100644
--- a/packages/core/src/repowise/core/ingestion/languages/registry.py
+++ b/packages/core/src/repowise/core/ingestion/languages/registry.py
@@ -981,6 +981,18 @@ _SPECS: tuple[LanguageSpec, ...] = (
is_passthrough=True,
is_api_contract=True,
),
+ # XAML / AXAML markup for WPF, WinUI 3, UWP, MAUI, Avalonia, Uno.
+ # No AST grammar — handled by the XamlDynamicHints extractor which
+ # emits ``dynamic_uses`` edges to bound C# types. Registered here so
+ # that the traverser surfaces a file node these edges can attach to.
+ LanguageSpec(
+ tag="xaml",
+ display_name="XAML",
+ extensions=frozenset({".xaml", ".axaml"}),
+ is_code=False,
+ is_passthrough=True,
+ color_hex="#0C479C",
+ ),
# -----------------------------------------------------------------
# Extra languages — git blame coverage only (passthrough + is_code)
# These exist so git_indexer tracks their history even though
diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.py
index de1c3618a..34c470118 100644
--- a/packages/core/src/repowise/core/ingestion/models.py
+++ b/packages/core/src/repowise/core/ingestion/models.py
@@ -46,6 +46,7 @@ LanguageTag = Literal[
"markdown",
"sql",
"openapi",
+ "xaml",
"unknown",
]
@@ -232,6 +233,12 @@ EdgeType = Literal[
"co_changes",
"framework",
"dynamic",
+ # 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
+ # from ``imports`` so analyses can weight it lower and so the
+ # persistence layer can surface provenance for these edges.
+ "type_use",
]
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/dotnet/global_usings.py b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/global_usings.py
index 58843d430..3346162c9 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/dotnet/global_usings.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/global_usings.py
@@ -53,7 +53,11 @@ def scan_global_usings(cs_text: str) -> list[str]:
def collect_project_global_usings(
- project_dir: Path, implicit_usings: bool, sdk_is_web: bool = False
+ project_dir: Path,
+ implicit_usings: bool,
+ sdk_is_web: bool = False,
+ *,
+ project_texts: dict[Path, str] | None = None,
) -> set[str]:
"""Walk *project_dir* for global using sources and return the merged set.
@@ -62,6 +66,13 @@ def collect_project_global_usings(
- Web SDK extras (when ``sdk_is_web`` is True)
- Every ``global using`` directive found in any .cs file under the project
- Project usings declared in the .csproj are added by the caller
+
+ When *project_texts* is provided (the hot path used by
+ ``DotNetProjectIndex.build_index``), the per-project rglob and
+ per-file ``read_text`` are skipped — the caller has already done a
+ single repo-wide walk and read each file once. The dict should
+ contain only files that belong to this project (longest-prefix
+ matched), keyed by resolved absolute path.
"""
result: set[str] = set()
if implicit_usings:
@@ -69,6 +80,11 @@ def collect_project_global_usings(
if sdk_is_web:
result.update(_WEB_IMPLICIT_USINGS)
+ if project_texts is not None:
+ for text in project_texts.values():
+ result.update(scan_global_usings(text))
+ return result
+
skip = {"bin", "obj", ".vs", "node_modules"}
for cs_path in project_dir.rglob("*.cs"):
if any(part in skip for part in cs_path.parts):
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/dotnet/index.py b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/index.py
index 9db23115c..b0eb9e51c 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/dotnet/index.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/index.py
@@ -121,19 +121,67 @@ class DotNetProjectIndex:
return package_id in self.package_refs.get(csproj, set())
-def _gather_project_files(project_dir: Path) -> list[Path]:
- """Return every .cs file under *project_dir*, ignoring build outputs."""
- skip = {"bin", "obj", ".vs", "node_modules"}
+_CS_WALK_SKIP_DIRS = frozenset({"bin", "obj", ".vs", "node_modules", ".git", "packages"})
+
+
+def _walk_repo_cs_files(repo_path: Path) -> list[Path]:
+ """Single repo-wide rglob for ``*.cs`` files, dedup by resolved path.
+
+ Lives at module scope (not nested inside ``build_index``) so it's
+ independently testable and so the skip-list is shared with the
+ XAML extractor's walk above.
+ """
+ seen: set[Path] = set()
out: list[Path] = []
- for cs in project_dir.rglob("*.cs"):
- if any(part in skip for part in cs.parts):
+ for cs in repo_path.rglob("*.cs"):
+ if any(part in _CS_WALK_SKIP_DIRS for part in cs.parts):
+ continue
+ try:
+ resolved = cs.resolve()
+ except OSError:
continue
- out.append(cs.resolve())
+ if resolved in seen:
+ continue
+ seen.add(resolved)
+ out.append(resolved)
+ return out
+
+
+def _bucket_files_by_project(
+ cs_files: list[Path],
+ project_dirs: list[tuple[Path, Path]],
+) -> dict[Path, Path]:
+ """Map each resolved .cs file → enclosing csproj path via longest-prefix.
+
+ *project_dirs* is a list of ``(project_dir_resolved, csproj_path)``
+ pairs sorted by descending path-component depth so the most
+ specific project wins for nested project layouts (e.g. a test
+ project nested under its production project's directory).
+ """
+ out: dict[Path, Path] = {}
+ for f in cs_files:
+ parents = set(f.parents)
+ for proj_dir, csproj in project_dirs:
+ if proj_dir in parents or proj_dir == f.parent:
+ out[f] = csproj
+ break
return out
def build_index(repo_path: Path) -> DotNetProjectIndex:
- """Walk *repo_path* and construct a fully-populated DotNetProjectIndex."""
+ """Walk *repo_path* and construct a fully-populated DotNetProjectIndex.
+
+ Performance note: a previous version of this function walked the
+ ``*.cs`` tree three times — once for ``_gather_project_files``,
+ once inside ``build_namespace_map`` (per-file ``read_text``), and a
+ third time inside ``collect_project_global_usings`` (rglob +
+ read_text per project, with heavy overlap on shared parent dirs).
+ On NTFS with Defender that pattern dominates indexing time
+ (40+ minutes on PowerToys-scale repos). The current shape does
+ ONE master walk, reads each file ONCE, and dispatches the cached
+ texts to both the namespace-map pass and per-project global-usings
+ collection. No data-quality loss — same regexes, same outputs.
+ """
repo_path = repo_path.resolve()
index = DotNetProjectIndex(repo_path=repo_path)
@@ -160,16 +208,39 @@ def build_index(repo_path: Path) -> DotNetProjectIndex:
)
index.package_refs.setdefault(proj.path, set()).update(proj.package_references)
- # ---- 3. Build namespace map across every .cs file in every project ----
- all_cs_files: list[Path] = []
- for proj in index.projects.values():
- proj_files = _gather_project_files(proj.project_dir)
- all_cs_files.extend(proj_files)
- for f in proj_files:
- index.file_to_project[f] = proj.path
- index.namespace_map, index.type_map = build_namespace_map(all_cs_files)
+ # ---- 3. Single master walk: enumerate .cs files & read each once ----
+ all_cs_files = _walk_repo_cs_files(repo_path)
+ cs_texts: dict[Path, str] = {}
+ for f in all_cs_files:
+ try:
+ cs_texts[f] = f.read_text(encoding="utf-8-sig", errors="replace")
+ except OSError:
+ continue
+
+ # Build the file → project map by longest-prefix match. Sort by
+ # descending parent-depth so nested projects (e.g. a test project
+ # whose directory sits under its prod project's tree) bind first.
+ project_dirs: list[tuple[Path, Path]] = sorted(
+ ((proj.project_dir.resolve(), proj.path) for proj in index.projects.values()),
+ key=lambda t: -len(t[0].parts),
+ )
+ index.file_to_project = _bucket_files_by_project(all_cs_files, project_dirs)
+
+ # ---- 4. Namespace + type map from cached texts ----
+ index.namespace_map, index.type_map = build_namespace_map(
+ all_cs_files, texts=cs_texts
+ )
+
+ # ---- 5. Per-project global+implicit usings from cached texts ----
+ # Bucket the cached texts by project once so each project's call to
+ # ``collect_project_global_usings`` is O(files in that project).
+ texts_by_proj: dict[Path, dict[Path, str]] = {}
+ for f, csproj in index.file_to_project.items():
+ text = cs_texts.get(f)
+ if text is None:
+ continue
+ texts_by_proj.setdefault(csproj, {})[f] = text
- # ---- 4. Compute per-project global+implicit usings ----
for proj in index.projects.values():
# Heuristic: presence of any AspNetCore PackageReference flags the
# web SDK's expanded implicit-using set.
@@ -177,7 +248,10 @@ def build_index(repo_path: Path) -> DotNetProjectIndex:
pkg.startswith("Microsoft.AspNetCore") for pkg in proj.package_references
)
globals_set = collect_project_global_usings(
- proj.project_dir, proj.implicit_usings, sdk_is_web=sdk_is_web
+ proj.project_dir,
+ proj.implicit_usings,
+ sdk_is_web=sdk_is_web,
+ project_texts=texts_by_proj.get(proj.path, {}),
)
# Honour <Using Include="X"/> ItemGroup entries on top of file scans.
globals_set.update(proj.project_usings)
@@ -187,6 +261,7 @@ def build_index(repo_path: Path) -> DotNetProjectIndex:
"DotNetProjectIndex built",
repo=str(repo_path),
projects=len(index.projects),
+ cs_files=len(all_cs_files),
namespaces=len(index.namespace_map),
types=len(index.type_map),
sln=len(index.sln_paths),
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/dotnet/namespace_map.py b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/namespace_map.py
index b95f93def..1f0676bee 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/dotnet/namespace_map.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/namespace_map.py
@@ -62,6 +62,8 @@ def declared_type_names(cs_text: str) -> list[str]:
def build_namespace_map(
cs_files: list[Path],
+ *,
+ texts: dict[Path, str] | None = None,
) -> tuple[dict[str, list[Path]], dict[str, list[Path]]]:
"""Return ``(namespace_map, type_map)`` for every .cs file given.
@@ -71,15 +73,24 @@ def build_namespace_map(
same-named types in different namespaces) — callers disambiguate
by project enclosure.
- Files that fail to read or declare nothing are skipped silently.
+ When *texts* is provided, file contents are read from the dict
+ rather than the filesystem — this is the hot path used by
+ ``DotNetProjectIndex.build_index`` to share one read with the
+ global-usings collector. Files missing from *texts* (or that fail
+ to read when ``texts`` is None) are skipped silently.
"""
namespaces: dict[str, list[Path]] = {}
types: dict[str, list[Path]] = {}
for path in cs_files:
- try:
- text = path.read_text(encoding="utf-8-sig", errors="replace")
- except OSError:
- continue
+ if texts is not None:
+ text = texts.get(path)
+ if text is None:
+ continue
+ else:
+ try:
+ text = path.read_text(encoding="utf-8-sig", errors="replace")
+ except OSError:
+ continue
seen_ns: set[str] = set()
for ns in declared_namespaces(text):
if ns in seen_ns:
diff --git a/packages/core/src/repowise/core/ingestion/type_ref_resolution.py b/packages/core/src/repowise/core/ingestion/type_ref_resolution.py
index edb94a979..d313b4bf1 100644
--- a/packages/core/src/repowise/core/ingestion/type_ref_resolution.py
+++ b/packages/core/src/repowise/core/ingestion/type_ref_resolution.py
@@ -170,29 +170,39 @@ def _add_or_merge_type_use_edge(
type_name: str,
origin: str,
) -> None:
- """Add a ``type_use``-flavoured ``imports`` edge, merging on conflict.
-
- The edge re-uses the ``imports`` edge type so existing analyses
- (dead-code reachability, PageRank, blast-radius) pick it up for
- free. The ``via`` attribute distinguishes it from a real ``using``
- directive for observability and downstream weighting.
-
- If a regular ``using`` edge already connects the same files, we
- leave it alone — the directive is strictly stronger evidence than
- a type-name match — and only record the type name in the
- ``type_uses`` attribute for traceability.
+ """Add a ``type_use`` edge between two files, merging on conflict.
+
+ The edge is persisted as its own ``edge_type='type_use'`` row so it
+ is observable in ``graph_edges`` (the SQLite layer drops ad-hoc
+ NetworkX attributes like ``via`` and ``origin``, so encoding the
+ provenance in the edge type itself is the only round-tripping way
+ to surface it). All file-reachability analyses
+ (dead-code's ``in_degree`` check, PageRank, blast-radius) operate
+ across edge types and still pick it up.
+
+ If a stronger ``imports`` edge from a real ``using`` directive
+ already connects the same files, leave it alone — the directive is
+ strictly stronger evidence — and just record the type name in
+ ``type_uses`` for traceability. Likewise, parallel type_use edges
+ between the same pair of files are merged into one row with the
+ full list of referenced types in ``imported_names``.
"""
if graph.has_edge(src, dst):
data = graph[src][dst]
type_uses = data.setdefault("type_uses", [])
if type_name not in type_uses:
type_uses.append(type_name)
+ # Keep imported_names in sync so the unused-export analyzer can
+ # see the referenced type name as evidence of import-like usage.
+ if data.get("edge_type") == "type_use":
+ names = data.setdefault("imported_names", [])
+ if type_name not in names:
+ names.append(type_name)
return
graph.add_edge(
src,
dst,
- edge_type="imports",
- via="type_use",
+ edge_type="type_use",
origin=origin,
confidence=_TYPE_USE_CONFIDENCE,
type_uses=[type_name],
diff --git a/packages/core/src/repowise/core/pipeline/orchestrator.py b/packages/core/src/repowise/core/pipeline/orchestrator.py
index a477c1d4d..805c2055f 100644
--- a/packages/core/src/repowise/core/pipeline/orchestrator.py
+++ b/packages/core/src/repowise/core/pipeline/orchestrator.py
@@ -142,6 +142,12 @@ class PipelineResult:
traversal_stats: Any | None = None
"""``TraversalStats`` from the file traverser, or None."""
+ # Detected tech stack (languages, frameworks, databases, infra).
+ # Stored as plain dicts (``{"name", "version", "category"}``) so the
+ # persistence layer can serialise without importing the editor_files
+ # data module. Populated post-traversal during the graph build phase.
+ tech_stack: list[dict] = field(default_factory=list)
+
# ---------------------------------------------------------------------------
# Pipeline
@@ -255,6 +261,7 @@ async def run_pipeline(
source_map,
graph_builder,
traversal_stats,
+ tech_items,
),
(
git_summary,
@@ -388,6 +395,10 @@ async def run_pipeline(
symbol_count=symbol_count,
languages=languages,
elapsed_seconds=elapsed,
+ tech_stack=[
+ {"name": t.name, "version": t.version, "category": t.category}
+ for t in tech_items
+ ],
)
@@ -407,7 +418,8 @@ async def _run_ingestion(
) -> tuple[list[Any], list[Any], Any, dict[str, bytes], Any, Any]:
"""Traverse, parse, and build the dependency graph.
- Returns (parsed_files, file_infos, repo_structure, source_map, graph_builder, traversal_stats).
+ Returns (parsed_files, file_infos, repo_structure, source_map,
+ graph_builder, traversal_stats, tech_items).
"""
from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder
@@ -555,6 +567,7 @@ async def _run_ingestion(
await asyncio.to_thread(graph_builder.build, progress)
# Add framework-aware synthetic edges (conftest, Django, FastAPI, Flask)
+ tech_items: list = []
try:
from repowise.core.generation.editor_files.tech_stack import detect_tech_stack
@@ -643,7 +656,7 @@ async def _run_ingestion(
lang_str += f", other {rest_count:,}"
progress.on_message("info", f" Languages: {lang_str}")
- return parsed_files, file_infos, repo_structure, source_map, graph_builder, stats
+ return parsed_files, file_infos, repo_structure, source_map, graph_builder, stats, tech_items
async def _run_git_indexing(
diff --git a/tests/unit/ingestion/test_csharp_type_use.py b/tests/unit/ingestion/test_csharp_type_use.py
index 615637e32..072bae9c0 100644
--- a/tests/unit/ingestion/test_csharp_type_use.py
+++ b/tests/unit/ingestion/test_csharp_type_use.py
@@ -267,9 +267,9 @@ class TestGraphEdgeEmission:
dst = "src/Domain/IUserRepo.cs"
assert graph.has_edge(src, dst)
data = graph[src][dst]
- assert data["edge_type"] == "imports"
- assert data["via"] == "type_use"
+ assert data["edge_type"] == "type_use"
assert "IUserRepo" in data["type_uses"]
+ assert "IUserRepo" in data["imported_names"]
# ---------------------------------------------------------------------------
diff --git a/tests/unit/ingestion/test_xaml_dynamic_hints.py b/tests/unit/ingestion/test_xaml_dynamic_hints.py
index 18e0b3ccb..770c7e8ff 100644
--- a/tests/unit/ingestion/test_xaml_dynamic_hints.py
+++ b/tests/unit/ingestion/test_xaml_dynamic_hints.py
@@ -96,3 +96,27 @@ class TestEndToEnd:
'<Page xmlns:vm="using:Foo" x:DataType="vm:Bar"/>'
)
assert XamlDynamicHints().extract(tmp_path) == []
+
+
+class TestLanguageRegistration:
+ """``.xaml``/``.axaml`` must surface as their own LanguageTag so
+ the traverser produces file nodes the dynamic edges can attach to.
+
+ Regression guard: before this branch, the extractor emitted edges
+ correctly but ``GraphBuilder.add_dynamic_edges`` dropped them
+ because ``.xaml`` files were never added as graph nodes.
+ """
+
+ def test_xaml_extension_resolves_to_xaml_tag(self) -> None:
+ from repowise.core.ingestion.languages.registry import REGISTRY
+
+ assert REGISTRY.from_extension(".xaml") == "xaml"
+ assert REGISTRY.from_extension(".axaml") == "xaml"
+
+ def test_xaml_is_passthrough_not_code(self) -> None:
+ from repowise.core.ingestion.languages.registry import REGISTRY
+
+ spec = REGISTRY.get("xaml")
+ assert spec is not None
+ assert spec.is_passthrough is True
+ assert spec.is_code is False
diff --git a/tests/unit/test_dead_code.py b/tests/unit/test_dead_code.py
index 89e40b432..c35999c05 100644
--- a/tests/unit/test_dead_code.py
+++ b/tests/unit/test_dead_code.py
@@ -199,6 +199,51 @@ def test_unused_export_detected():
assert "helper_func" in sym_names
+def test_interface_without_implementor_demoted_below_safe_threshold():
+ """Public interfaces with no incoming ``implements`` edges have
+ their unused-export confidence clamped below 0.7 so the demo
+ doesn't ship them as confident dead code. Implementor detection
+ is heuristic — absence is missing-signal, not evidence-of-absence.
+ """
+ g = _build_graph(
+ nodes={
+ "src/IBasketService.cs": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 1,
+ "symbols": [
+ {
+ "name": "IBasketService",
+ "kind": "interface",
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 1,
+ "end_line": 5,
+ "complexity_estimate": 1,
+ "language": "csharp",
+ },
+ ],
+ },
+ },
+ edges=[],
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze({
+ "detect_unreachable_files": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+ })
+ interface_findings = [
+ f for f in report.findings
+ if f.kind == DeadCodeKind.UNUSED_EXPORT and f.symbol_name == "IBasketService"
+ ]
+ # The finding may still surface, but never at safe-to-delete confidence.
+ for f in interface_findings:
+ assert f.confidence <= 0.4, f"interface flagged at unsafe confidence {f.confidence}"
+ assert f.safe_to_delete is False
+
+
# ---------------------------------------------------------------------------
# 5. test_framework_decorator_excluded
# ---------------------------------------------------------------------------