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(csharp): close DI / XAML / monorepo gaps for .NET indexing (#180)

Raghav Chamadiya74ffb2b0f0ac
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 f9f07e94b..6c84f137d 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -33,18 +33,7 @@ from .constants import (
# namespace. C# auto-properties land in the graph as ``variable``;
# fields / enum members / type aliases / namespace anchors share the
# same property.
-#
-# ``interface`` is included here because in practice interfaces are
-# resolved through indirections the import-name analyser cannot see —
-# DI container registration, generic type constraints, type assertions
-# / casts, and (in C# / Java / Kotlin / Scala) namespace-level
-# ``using`` / ``import`` directives that don't name the interface
-# individually. Treating every public interface with no named-import
-# edge as dead produced 100s of false positives on DI-heavy codebases
-# (every ``IRepository<T>``, every ``IService``). The cost of missing
-# a genuinely dead public interface is low (it'll surface elsewhere
-# the moment its single implementation file is flagged dead).
-_NON_IMPORTABLE_SYMBOL_KINDS: frozenset[str] = frozenset({
+_UNIVERSAL_NON_IMPORTABLE: frozenset[str] = frozenset({
"method",
"variable",
"field",
@@ -54,9 +43,45 @@ _NON_IMPORTABLE_SYMBOL_KINDS: frozenset[str] = frozenset({
"type_alias",
"namespace",
"module",
- "interface",
})
+# Additional kinds skipped only for languages where the graph cannot yet
+# observe interface usage. In practice these are DI-heavy languages
+# whose canonical interface-consumption path is constructor injection —
+# resolved by the type-use edge pass (see
+# ``ingestion/type_ref_resolution.py``). Once a language emits
+# ``via=type_use`` edges, its entry here can be removed.
+#
+# C# already has type-use coverage (ctor + method + delegate +
+# primary-ctor param.type captures), so ``interface`` is *not* skipped
+# for C# — a genuinely unused C# interface is now observable.
+#
+# TS / Python / JS interfaces were always imported by name and never
+# needed the skip; treating them uniformly produced false negatives.
+_LANGUAGE_NON_IMPORTABLE: dict[str, frozenset[str]] = {
+ "java": frozenset({"interface"}),
+ "kotlin": frozenset({"interface"}),
+ "scala": frozenset({"interface"}),
+}
+
+
+def _non_importable_kinds(language: str) -> frozenset[str]:
+ """Per-language set of symbol kinds excluded from unused-export passes.
+
+ Returns the union of the universal set and any language-specific
+ additions. Cheap to call — short lookup, no per-call allocation
+ when the language has no additions.
+ """
+ extra = _LANGUAGE_NON_IMPORTABLE.get(language)
+ if extra is None:
+ return _UNIVERSAL_NON_IMPORTABLE
+ return _UNIVERSAL_NON_IMPORTABLE | extra
+
+
+# Preserved for tests / external callers that imported the old name.
+# New code should prefer ``_non_importable_kinds(language)``.
+_NON_IMPORTABLE_SYMBOL_KINDS: frozenset[str] = _UNIVERSAL_NON_IMPORTABLE | frozenset({"interface"})
+
# Symbol names that are language-runtime entry points or compiler-implicit
# anchors — never invoked by user-authored callers, never dead.
_ENTRY_POINT_SYMBOL_NAMES: frozenset[str] = frozenset({
@@ -384,7 +409,7 @@ class DeadCodeAnalyzer:
# class / module, so the unused-export pass can't observe
# their real usage and would report guaranteed false
# positives. C# auto-properties surface here as ``variable``.
- if sym.get("kind") in _NON_IMPORTABLE_SYMBOL_KINDS:
+ if sym.get("kind") in _non_importable_kinds(sym.get("language", "unknown")):
continue
if sym_name.startswith("__") and sym_name.endswith("__"):
continue
@@ -506,7 +531,7 @@ class DeadCodeAnalyzer:
# non-callable kinds bypass the call-edge pass by design.
if "." in sym_name:
continue
- if node_data.get("kind") in _NON_IMPORTABLE_SYMBOL_KINDS:
+ if node_data.get("kind") in _non_importable_kinds(node_data.get("language", "unknown")):
continue
if self._name_matches_dynamic(sym_name, dynamic_patterns):
continue
diff --git a/packages/core/src/repowise/core/analysis/dead_code/constants.py b/packages/core/src/repowise/core/analysis/dead_code/constants.py
index 8bf96bb09..a18da68cf 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/constants.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/constants.py
@@ -97,6 +97,29 @@ _NEVER_FLAG_PATTERNS: tuple[str, ...] = (
"*/Apis/*.cs",
"*/Endpoints/*.cs",
"*/Routes/*.cs",
+ # ---- Generic .NET / Win32 conventions ----------------------------
+ # Source-generator output directories. Many SDKs (CommunityToolkit
+ # MVVM, AOT, EF Core compiled-models, gRPC) emit generated files
+ # into a `Generated/` sibling next to the source. They get wired in
+ # at build time, never imported by name.
+ "*/Generated/*.cs",
+ "*/generated/*.cs",
+ # Win32 P/Invoke surfaces. NativeMethods / SafeNativeMethods are a
+ # decades-old .NET FX convention; they are reached only via
+ # `[DllImport]`-mediated calls, never via a `using` directive that
+ # names the type.
+ "*NativeMethods.cs",
+ "*SafeNativeMethods.cs",
+ "*UnsafeNativeMethods.cs",
+ # ETW / EventSource event-class folders. The runtime reflects on
+ # these at registration time; static graph rarely sees the import.
+ "*/Telemetry/Events/*.cs",
+ "*/Diagnostics/Events/*.cs",
+ # XAML resource dictionaries and merged styles. WPF / WinUI load
+ # these via `<ResourceDictionary Source="..."/>` not `using`.
+ "*/Themes/*.xaml",
+ "*/Styles/*.xaml",
+ "*/Resources/*.xaml",
)
# Decorator patterns that indicate framework usage (route handlers, fixtures, etc.)
diff --git a/packages/core/src/repowise/core/generation/editor_files/tech_stack.py b/packages/core/src/repowise/core/generation/editor_files/tech_stack.py
index a42dd2379..8db5baa8a 100644
--- a/packages/core/src/repowise/core/generation/editor_files/tech_stack.py
+++ b/packages/core/src/repowise/core/generation/editor_files/tech_stack.py
@@ -53,6 +53,60 @@ _PYTHON_FRAMEWORKS: dict[str, tuple[str, str]] = {
}
+# Maximum directory depth from the repo root to scan for .NET project
+# files. Five levels covers every observed .NET monorepo layout in the
+# wild (e.g. `src/<area>/<module>/<Project>/<Project>.csproj` is depth
+# 4; `services/<svc>/src/<Project>/<Project>.csproj` is depth 5).
+# Setting this higher would only add noise from samples / tests buried
+# inside generated SDK folders.
+_DOTNET_MAX_DEPTH = 5
+
+# Hard cap on returned .csproj count. Repos like dotnet/runtime have
+# thousands of project files; we only need a representative sample to
+# infer the tech stack.
+_DOTNET_MAX_PROJECTS = 200
+
+# Directory names to prune from the scan. These never host real
+# project source and bloat the walk on Windows where `bin/obj`
+# contains thousands of intermediate files per project.
+_DOTNET_PRUNE = frozenset({
+ "bin", "obj", ".vs", "node_modules", ".git", "packages",
+ ".idea", "artifacts", ".build", "TestResults",
+})
+
+
+def _find_dotnet_projects(repo_path: Path) -> list[Path]:
+ """Return up to ``_DOTNET_MAX_PROJECTS`` .csproj files under *repo_path*.
+
+ Bounded depth-first walk that prunes build-output and tooling
+ directories. Order is depth-first but stable across runs (sorted
+ children at each level) so caching downstream is deterministic.
+ """
+ found: list[Path] = []
+
+ def _walk(current: Path, depth: int) -> None:
+ if len(found) >= _DOTNET_MAX_PROJECTS:
+ return
+ if depth > _DOTNET_MAX_DEPTH:
+ return
+ try:
+ entries = sorted(current.iterdir(), key=lambda p: p.name.lower())
+ except (OSError, PermissionError):
+ return
+ for entry in entries:
+ if len(found) >= _DOTNET_MAX_PROJECTS:
+ return
+ if entry.is_dir():
+ if entry.name in _DOTNET_PRUNE or entry.name.startswith("."):
+ continue
+ _walk(entry, depth + 1)
+ elif entry.is_file() and entry.suffix == ".csproj":
+ found.append(entry)
+
+ _walk(repo_path, 0)
+ return found
+
+
def detect_tech_stack(repo_path: Path) -> list[TechStackItem]:
"""Detect languages, frameworks, and infra tools from manifest files.
@@ -168,9 +222,12 @@ def detect_tech_stack(repo_path: Path) -> list[TechStackItem]:
add("Laravel", None, "framework")
# --- .NET / C# (.csproj / .sln / Directory.Build.props) ---
- # Walk one level deep so multi-project solutions like eShop register.
- csproj_files = list(repo_path.glob("*.csproj")) + list(repo_path.glob("*/*.csproj"))
- sln_files = list(repo_path.glob("*.sln"))
+ # Walk the tree (bounded) so monorepos whose projects live under
+ # `src/modules/<module>/<Module>.csproj` or `services/foo/foo.csproj`
+ # still register. A shallow glob misses every real-world .NET
+ # monorepo layout — eShop, Aspire samples, PowerToys, Roslyn etc.
+ csproj_files = _find_dotnet_projects(repo_path)
+ sln_files = list(repo_path.glob("*.sln")) + list(repo_path.glob("*/*.sln"))
has_directory_build = (repo_path / "Directory.Build.props").exists() or (
repo_path / "Directory.Packages.props"
).exists()
@@ -179,7 +236,7 @@ def detect_tech_stack(repo_path: Path) -> list[TechStackItem]:
# net8.0, etc. Best-effort regex; the .csproj XML is small so a
# full parser would be overkill.
target_fw: str | None = None
- for csproj in csproj_files[:3]:
+ for csproj in csproj_files[:10]:
try:
ctext = csproj.read_text(encoding="utf-8", errors="ignore")
except OSError:
@@ -192,9 +249,12 @@ def detect_tech_stack(repo_path: Path) -> list[TechStackItem]:
break
add("C#", target_fw, "language")
add(".NET", target_fw, "framework")
- # Common .NET stack indicators read from any .csproj text.
+ # Common .NET stack indicators read from any .csproj text. The
+ # cap is per-file, not per-byte — small projects with many
+ # csprojs (PowerToys ~140, Roslyn ~300) need a generous limit
+ # before they look like an unflavoured .NET repo.
joined_csproj = ""
- for csproj in csproj_files[:20]:
+ for csproj in csproj_files[:80]:
try:
joined_csproj += csproj.read_text(encoding="utf-8", errors="ignore")
except OSError:
@@ -213,6 +273,12 @@ def detect_tech_stack(repo_path: Path) -> list[TechStackItem]:
"Maui" in p.stem for p in csproj_files
):
add(".NET MAUI", None, "framework")
+ if "Microsoft.WindowsAppSDK" in joined_csproj or "Microsoft.UI.Xaml" in joined_csproj:
+ add("WinUI 3", None, "framework")
+ if "Microsoft.NET.Sdk.WindowsDesktop" in joined_csproj or "<UseWPF>true" in joined_csproj:
+ add("WPF", None, "framework")
+ if "Microsoft.NET.Sdk.WindowsDesktop" in joined_csproj and "<UseWindowsForms>true" in joined_csproj:
+ add("Windows Forms", None, "framework")
# --- Docker ---
if (repo_path / "Dockerfile").exists():
diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.py
index db1a20e5f..06502d0fd 100644
--- a/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.py
+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.py
@@ -17,6 +17,7 @@ from .ruby import RubyDynamicHints
from .scala import ScalaDynamicHints
from .spring import SpringDynamicHints
from .swift import SwiftDynamicHints
+from .xaml import XamlDynamicHints
log = structlog.get_logger(__name__)
@@ -28,6 +29,7 @@ class HintRegistry:
PytestDynamicHints(),
NodeDynamicHints(),
DotNetDynamicHints(),
+ XamlDynamicHints(),
SpringDynamicHints(),
RubyDynamicHints(),
PhpDynamicHints(),
diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/xaml.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/xaml.py
new file mode 100644
index 000000000..21318d4a5
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/xaml.py
@@ -0,0 +1,199 @@
+"""Dynamic-hint extractor for XAML data-binding surfaces.
+
+Why this exists
+===============
+XAML (WPF, WinUI 3, UWP, MAUI, Avalonia/Uno via ``.axaml``) reaches
+into the C# code graph through three vectors the AST never sees:
+
+1. ``xmlns:vm="using:Acme.ViewModels"`` (WinUI / UWP / MAUI) or
+ ``xmlns:vm="clr-namespace:Acme.ViewModels"`` (WPF) — declares that
+ types in a namespace are addressable from this XAML file by the
+ ``vm:`` prefix.
+2. ``x:DataType="vm:GeneralViewModel"`` (compiled bindings) and
+ ``DataType="vm:..."`` / ``TargetType="vm:..."`` — names a concrete
+ C# type whose members are the binding source.
+3. ``DataContext`` literal types like
+ ``DataContext="{x:Type vm:SettingsViewModel}"``.
+
+Without these edges, every ViewModel and every settings-model class
+read by the view layer surfaces as an orphan — there is no ``using``
+directive on the C# side either, because the consumer is the XAML.
+
+Design
+======
+Pure regex pass over ``*.xaml`` and ``*.axaml`` files (avoids pulling
+in an XML parser and works on partial / malformed XAML during a
+mid-edit index). The class-name → file map is borrowed from
+``DotNetProjectIndex.type_map`` (built lazily on first access) so we
+don't re-walk the repo. When the index isn't available (no .csproj
+in the repo), we silently emit no edges — XAML without a backing
+.NET project doesn't have a target to point at.
+
+The extractor is generic across WPF / WinUI / MAUI / Avalonia / Uno —
+no framework-specific code paths. Adding a new XAML dialect is a matter
+of extending ``_XMLNS_RE`` to handle a new namespace prefix scheme.
+"""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+from .base import DynamicEdge, DynamicHintExtractor
+
+_SKIP_DIRS = {"bin", "obj", ".vs", "node_modules", ".git", "packages"}
+_XAML_EXTS = (".xaml", ".axaml")
+
+# xmlns:prefix="clr-namespace:Foo.Bar" — WPF
+# xmlns:prefix="clr-namespace:Foo.Bar;assembly=Acme.UI" — WPF cross-assembly
+# xmlns:prefix="using:Foo.Bar" — WinUI / UWP / MAUI
+# xmlns:prefix="https://github.com/avaloniaui" — Avalonia default (not a CLR map)
+_XMLNS_RE = re.compile(
+ r"""xmlns:(\w+)\s*=\s*["'](?:using:|clr-namespace:)([\w.]+)(?:;assembly=[^"']+)?["']""",
+ re.IGNORECASE,
+)
+
+# x:DataType / DataType / TargetType / d:DataContext attribute values.
+# Captures both `prefix:TypeName` and bare `TypeName` forms.
+_TYPE_ATTR_RE = re.compile(
+ r"""(?:x:DataType|d?:?DataType|TargetType|x:TypeArguments)\s*=\s*["']"""
+ r"""(?:(\w+):)?(\w+)["']""",
+ re.IGNORECASE,
+)
+
+# DataContext="{x:Type vm:Foo}" — the markup-extension form. Less
+# common but used in WPF tooling.
+_XTYPE_RE = re.compile(
+ r"""\{\s*x:Type\s+(?:(\w+):)?(\w+)\s*\}""",
+ re.IGNORECASE,
+)
+
+
+class XamlDynamicHints(DynamicHintExtractor):
+ """Emit ``dynamic_uses`` edges from XAML files to the C# types they bind to."""
+
+ name = "xaml"
+
+ def extract(self, repo_root: Path) -> list[DynamicEdge]:
+ # Cheap pre-flight: any XAML in the tree at all?
+ xaml_files = list(_iter_xaml_files(repo_root))
+ if not xaml_files:
+ return []
+
+ # Reuse the existing C# type index — it already walks every .cs
+ # file under every .csproj and dedupes builtins. Building it
+ # here keeps XAML resolution cross-project / cross-repo
+ # consistent with how `using` directives resolve.
+ type_map = _load_type_map(repo_root)
+ if not type_map:
+ return []
+
+ edges: list[DynamicEdge] = []
+ repo_root_resolved = repo_root.resolve()
+
+ for xaml_path in xaml_files:
+ try:
+ rel = xaml_path.resolve().relative_to(repo_root_resolved).as_posix()
+ except ValueError:
+ continue
+ try:
+ text = xaml_path.read_text(encoding="utf-8-sig", errors="ignore")
+ except OSError:
+ continue
+
+ prefix_to_namespace = _collect_prefix_namespaces(text)
+ type_refs = _extract_type_references(text, prefix_to_namespace)
+
+ for type_name in type_refs:
+ targets = type_map.get(type_name)
+ if not targets:
+ continue
+ for target_abs in targets:
+ try:
+ target_rel = target_abs.resolve().relative_to(repo_root_resolved).as_posix()
+ except ValueError:
+ continue
+ if target_rel == rel:
+ continue
+ edges.append(
+ DynamicEdge(
+ source=rel,
+ target=target_rel,
+ edge_type="dynamic_uses",
+ hint_source=f"{self.name}:binding",
+ )
+ )
+
+ return edges
+
+
+# ---------------------------------------------------------------------------
+# Helpers (module-level so they're easy to unit-test in isolation)
+# ---------------------------------------------------------------------------
+
+def _iter_xaml_files(repo_root: Path):
+ for ext in _XAML_EXTS:
+ for path in repo_root.rglob(f"*{ext}"):
+ try:
+ rel = path.resolve().relative_to(repo_root.resolve())
+ except ValueError:
+ continue
+ if any(part in _SKIP_DIRS for part in rel.parts):
+ continue
+ yield path
+
+
+def _collect_prefix_namespaces(text: str) -> dict[str, str]:
+ """Return the ``xmlns:prefix → namespace`` map declared in *text*."""
+ out: dict[str, str] = {}
+ for match in _XMLNS_RE.finditer(text):
+ prefix = match.group(1)
+ namespace = match.group(2)
+ out[prefix] = namespace
+ return out
+
+
+def _extract_type_references(text: str, prefix_to_ns: dict[str, str]) -> set[str]:
+ """Return the set of unqualified type names referenced by *text*.
+
+ Currently the namespace prefix is captured but not yet used to
+ disambiguate — the resolver picks the first matching file by name.
+ Reserved for a future refinement that prefers same-namespace
+ candidates when the prefix maps to a known namespace.
+ """
+ names: set[str] = set()
+ for match in _TYPE_ATTR_RE.finditer(text):
+ type_name = match.group(2)
+ if type_name and type_name[0].isupper():
+ names.add(type_name)
+ for match in _XTYPE_RE.finditer(text):
+ type_name = match.group(2)
+ if type_name and type_name[0].isupper():
+ names.add(type_name)
+ # The xmlns prefixes themselves never name a type, but their target
+ # namespaces are a useful signal — left here as a hook for future
+ # enhancement that resolves "every type in that namespace" when no
+ # finer attribute is present.
+ _ = prefix_to_ns
+ return names
+
+
+def _load_type_map(repo_root: Path) -> dict[str, list[Path]]:
+ """Return the unqualified-type-name → defining-files map for *repo_root*.
+
+ Wraps ``DotNetProjectIndex.build_index`` so XAML hints share the
+ same authoritative type index as the resolver. If the project
+ layout fails to parse (e.g. no .csproj at all), returns an empty
+ map and the extractor early-exits.
+ """
+ try:
+ # Local import to keep dynamic_hints package free of resolver
+ # transitive imports at module load time.
+ from ..resolvers.dotnet import build_index
+ except ImportError:
+ return {}
+ try:
+ index = build_index(repo_root)
+ except Exception: # pragma: no cover — defensive against partial repos
+ return {}
+ return index.type_map
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer.py b/packages/core/src/repowise/core/ingestion/git_indexer.py
index 3c02a7b44..19061e99c 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer.py
@@ -76,9 +76,24 @@ _DECISION_SIGNAL_WORDS: frozenset[str] = frozenset(
_SKIP_AUTHORS = ("dependabot", "renovate", "github-actions")
_MIN_MESSAGE_LEN = 12
-# Default per-file and co-change commit history depth.
+# Default per-file commit history depth.
_DEFAULT_COMMIT_LIMIT: int = 500
+# Co-change pair extraction widens the window because individual files
+# may only co-change a handful of times in 500 commits — well below the
+# ``min_count`` threshold. On low-churn repos the 500-commit window
+# produced 0 co-change pairs every run; 2000 commits captures enough
+# history for the decay-weighted score to clear the bar without
+# meaningfully blowing up wall-clock time (single `git log` call).
+_DEFAULT_CO_CHANGE_COMMIT_LIMIT: int = 2000
+
+# Minimum decay-weighted co-occurrence weight for a pair to be recorded.
+# Was 3 historically; on repos with sparse change history (libraries,
+# stable services) that produced empty co-change tables. Two recent
+# co-changes is enough signal to surface in the UI, and the dashboard
+# already sorts partners by weight so the ranking is unaffected.
+_DEFAULT_CO_CHANGE_MIN_COUNT: int = 2
+
# Commit message classification regexes (Phase 2.2).
_COMMIT_CATEGORIES: dict[str, re.Pattern[str]] = {
"feature": re.compile(
@@ -298,13 +313,18 @@ class GitIndexer:
file_tasks = [index_one(fp) for fp in indexable_files]
async def _co_change_task() -> dict[str, list[dict]]:
+ # Co-change uses a wider window than per-file history (set
+ # by ``self.commit_limit``) so low-churn repos surface
+ # any pairs at all. Defaults live in module constants so
+ # tests and re-index paths can override without touching
+ # this call site.
return await loop.run_in_executor(
executor,
self._compute_co_changes,
repo,
set(tracked_files),
- self.commit_limit,
- 3,
+ max(self.commit_limit, _DEFAULT_CO_CHANGE_COMMIT_LIMIT),
+ _DEFAULT_CO_CHANGE_MIN_COUNT,
on_commit_done,
on_co_change_start,
)
@@ -808,8 +828,8 @@ class GitIndexer:
self,
repo: Any,
all_files: set[str],
- commit_limit: int = 500,
- min_count: int = 3,
+ commit_limit: int = _DEFAULT_CO_CHANGE_COMMIT_LIMIT,
+ min_count: int = _DEFAULT_CO_CHANGE_MIN_COUNT,
on_commit_done: Callable[[], None] | None = None,
on_co_change_start: Callable[[int], None] | None = None,
) -> dict[str, list[dict]]:
@@ -911,6 +931,20 @@ class GitIndexer:
for fp in result:
result[fp].sort(key=lambda x: x["co_change_count"], reverse=True)
+ # Lightweight observability: every audit so far has had to
+ # answer "why are co-change tables empty?" by guessing. Logging
+ # the filter funnel lets future debugging look at one log line.
+ logger.debug(
+ "co_change_computed",
+ commits=actual_commits,
+ tracked_files=len(all_files),
+ pairs_considered=len(pair_scores),
+ pairs_above_threshold=sum(1 for s in pair_scores.values() if s >= min_count),
+ files_with_partners=len(result),
+ min_count=min_count,
+ commit_limit=commit_limit,
+ )
+
return dict(result)
@staticmethod
diff --git a/packages/core/src/repowise/core/ingestion/graph.py b/packages/core/src/repowise/core/ingestion/graph.py
index 3f02372a7..ac21a1295 100644
--- a/packages/core/src/repowise/core/ingestion/graph.py
+++ b/packages/core/src/repowise/core/ingestion/graph.py
@@ -35,6 +35,7 @@ import structlog
from .models import ParsedFile
from .resolvers import ResolverContext, resolve_import
from .resolvers.go import read_go_module_path, read_go_modules
+from .type_ref_resolution import resolve_type_refs
log = structlog.get_logger(__name__)
@@ -266,6 +267,18 @@ class GraphBuilder:
if _phase_done is not None:
_phase_done("graph.imports")
+ # --- Phase 1b: Resolve non-import type references (e.g. C# ctor params) ---
+ # Lives between import resolution and heritage so the type-use
+ # 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.
+ 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":
+ import_targets.setdefault(path, set()).add(target)
+ del type_use_counts # used only for logging inside resolve_type_refs
+
# --- Phase 2: Resolve heritage (extends/implements) ---
self._resolve_heritage(import_targets, progress=progress)
diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.py
index 857ca410a..de1c3618a 100644
--- a/packages/core/src/repowise/core/ingestion/models.py
+++ b/packages/core/src/repowise/core/ingestion/models.py
@@ -235,6 +235,21 @@ EdgeType = Literal[
]
+@dataclass
+class TypeReference:
+ """A non-import type reference extracted from a source file.
+
+ Captures usages like constructor parameter types and method parameter
+ types where the referenced type is named but not imported through a
+ statement the resolver already handles. Resolved to file-level
+ ``imports`` edges by the graph builder.
+ """
+
+ type_name: str # head identifier (e.g. "IBasketService" from "IBasketService<T>")
+ line: int # 1-indexed source line
+ origin: Literal["ctor_param", "method_param", "delegate_param"] = "ctor_param"
+
+
@dataclass
class ParsedFile:
"""Full result of parsing a single source file."""
@@ -248,6 +263,7 @@ class ParsedFile:
docstring: str | None = None # module/file-level docstring
parse_errors: list[str] = field(default_factory=list) # non-fatal parser warnings/errors
content_hash: str = "" # SHA-256 hex of raw file bytes
+ type_refs: list[TypeReference] = field(default_factory=list)
def compute_content_hash(source: bytes) -> str:
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index 90cbb78d3..cd926bcdb 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -63,6 +63,7 @@ from .models import (
Import,
ParsedFile,
Symbol,
+ TypeReference,
)
log = structlog.get_logger(__name__)
@@ -546,6 +547,7 @@ class ASTParser:
heritage = extract_heritage(tree, query, config, file_info, src, run_query=_run_query)
exports = self._derive_exports(symbols, config, src)
docstring = extract_module_docstring(root, src, lang)
+ type_refs = self._extract_type_refs(tree, query, src)
return ParsedFile(
file_info=file_info,
@@ -556,6 +558,7 @@ class ASTParser:
heritage=heritage,
docstring=docstring,
parse_errors=parse_errors,
+ type_refs=type_refs,
)
# ------------------------------------------------------------------
@@ -842,6 +845,53 @@ class ASTParser:
return [s.name for s in symbols if s.visibility == "public" and s.parent_name is None]
return [s.name for s in symbols if s.visibility == "public" and s.parent_name is None]
+ # ------------------------------------------------------------------
+ # Type reference extraction (non-import positions)
+ # ------------------------------------------------------------------
+
+ def _extract_type_refs(
+ self,
+ tree: object,
+ query: object,
+ src: str,
+ ) -> list[TypeReference]:
+ """Collect ``@param.type`` captures into TypeReference records.
+
+ Currently only the C# query emits these captures (constructor /
+ method / delegate / primary-ctor parameter types). The graph
+ builder resolves each reference to a defining file via the
+ language-specific resolver index and emits a file-level edge.
+
+ Capture origin is inferred from the parameter's enclosing node:
+ ``constructor_declaration`` → ``ctor_param`` (highest signal:
+ canonical DI vector), ``method_declaration`` → ``method_param``,
+ ``delegate_declaration`` → ``delegate_param``. Primary
+ constructors on records / classes also resolve to ``ctor_param``.
+ """
+ if query is None:
+ return []
+
+ refs: list[TypeReference] = []
+ seen: set[tuple[str, int]] = set()
+
+ for capture_dict in _run_query(query, tree.root_node): # type: ignore[attr-defined]
+ type_nodes = capture_dict.get("param.type", [])
+ if not type_nodes:
+ continue
+ for type_node in type_nodes:
+ head = _head_type_identifier(type_node, src)
+ if not head:
+ continue
+ line = type_node.start_point[0] + 1
+ key = (head, line)
+ if key in seen:
+ continue
+ seen.add(key)
+ origin = _classify_param_origin(type_node)
+ refs.append(TypeReference(type_name=head, line=line, origin=origin))
+
+ return refs
+
# ---------------------------------------------------------------------------
# Convenience function
@@ -912,6 +962,138 @@ def _build_qualified_name(file_path: str, parent_name: str | None, name: str) ->
return f"{module}.{name}"
+# ---------------------------------------------------------------------------
+# Type reference helpers (used by _extract_type_refs)
+# ---------------------------------------------------------------------------
+
+# Type expressions that never resolve to a user-defined .NET type. Skipping
+# these here avoids polluting the resolver with hopeless lookups. Generic
+# args inside `IList<T>` are stripped before this check is applied.
+_BUILTIN_CSHARP_TYPES: frozenset[str] = frozenset({
+ "void", "bool", "byte", "sbyte", "char", "short", "ushort", "int",
+ "uint", "long", "ulong", "float", "double", "decimal", "string",
+ "object", "nint", "nuint", "dynamic", "var",
+ # Frequently appearing BCL types that are always external — listing
+ # them here is purely a performance optimisation (one dict miss
+ # avoided per occurrence).
+ "Task", "ValueTask", "CancellationToken", "Action", "Func",
+ "Type", "Exception", "DateTime", "DateTimeOffset", "TimeSpan",
+ "Guid", "Uri", "Stream",
+})
+
+_PARAM_ORIGIN_BY_ANCESTOR: dict[str, str] = {
+ "constructor_declaration": "ctor_param",
+ "method_declaration": "method_param",
+ "delegate_declaration": "delegate_param",
+ "record_declaration": "ctor_param",
+ "class_declaration": "ctor_param",
+ "struct_declaration": "ctor_param",
+}
+
+
+def _head_type_identifier(type_node: Node, src: str) -> str | None:
+ """Return the head identifier of a C# type expression, or None.
+
+ Examples:
+ ``IBasketService`` → "IBasketService"
+ ``IList<Basket>`` → "IList"
+ ``Acme.Catalog.IRepository<T>`` → "IRepository"
+ ``ref readonly Span<byte>`` → "Span"
+ ``string`` → None (built-in)
+ ``int?`` → None
+ ``T`` → None (likely a generic param)
+
+ The point of returning the head identifier is that the
+ DotNetProjectIndex type-name lookup is keyed by unqualified type
+ name. Generic-arg recursion is intentionally NOT done here — each
+ generic arg is captured in its own ``@param.type`` if it's a real
+ parameter type, and the resolver doesn't currently track generic
+ instantiation graphs.
+ """
+ head_node: Node | None = type_node
+
+ # Unwrap modifier wrappers: nullable_type, ref_type, pointer_type,
+ # array_type, tuple_type. tree-sitter-c-sharp puts the inner type
+ # at field "type" or as the first non-trivia child.
+ for _ in range(6):
+ if head_node is None:
+ return None
+ if head_node.type in ("nullable_type", "ref_type", "pointer_type", "array_type"):
+ inner = head_node.child_by_field_name("type")
+ if inner is None:
+ # Fall back to first identifier-bearing child
+ inner = next(
+ (c for c in head_node.children if c.type not in (",", "?", "*", "&", "ref", "out", "in", "[", "]")),
+ None,
+ )
+ head_node = inner
+ continue
+ break
+
+ if head_node is None:
+ return None
+
+ if head_node.type == "identifier":
+ text = _node_text(head_node, src)
+ elif head_node.type == "predefined_type":
+ text = _node_text(head_node, src)
+ elif head_node.type == "generic_name":
+ name_child = head_node.child_by_field_name("name") or next(
+ (c for c in head_node.children if c.type == "identifier"), None,
+ )
+ text = _node_text(name_child, src) if name_child else ""
+ elif head_node.type == "qualified_name":
+ # `Foo.Bar.Baz` — take the rightmost identifier
+ idents = [c for c in head_node.children if c.type == "identifier"]
+ text = _node_text(idents[-1], src) if idents else ""
+ elif head_node.type == "tuple_type":
+ return None # Tuple elements aren't single types
+ else:
+ # Unknown shape — fall back to first identifier in the subtree
+ ident = _first_descendant(head_node, "identifier")
+ text = _node_text(ident, src) if ident else ""
+
+ if not text or not text[0].isalpha() and text[0] != "_":
+ return None
+ if text in _BUILTIN_CSHARP_TYPES:
+ return None
+ # Single-uppercase-letter heads are overwhelmingly generic params (T, K, V).
+ # Skipping them avoids spurious lookups against a type-name index that
+ # would never contain them.
+ if len(text) == 1 and text.isupper():
+ return None
+ return text
+
+
+def _first_descendant(node: Node, type_name: str) -> Node | None:
+ stack = [node]
+ while stack:
+ current = stack.pop()
+ if current.type == type_name:
+ return current
+ stack.extend(current.children)
+ return None
+
+
+def _classify_param_origin(type_node: Node) -> str:
+ """Walk up to find the enclosing declaration and map to an origin tag.
+
+ The walk stops at the first matching ancestor or after a small depth
+ cap. Falling off the cap means the capture was outside a recognised
+ declaration shape (shouldn't happen given the query patterns, but
+ guards against grammar drift); we tag those ``method_param``.
+ """
+ cur: Node | None = type_node
+ for _ in range(8):
+ if cur is None:
+ break
+ origin = _PARAM_ORIGIN_BY_ANCESTOR.get(cur.type)
+ if origin is not None:
+ return origin
+ cur = cur.parent
+ return "method_param"
+
+
# ---------------------------------------------------------------------------
# Call extraction helpers
# ---------------------------------------------------------------------------
diff --git a/packages/core/src/repowise/core/ingestion/queries/csharp.scm b/packages/core/src/repowise/core/ingestion/queries/csharp.scm
index 209c09906..1dbea2ac9 100644
--- a/packages/core/src/repowise/core/ingestion/queries/csharp.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/csharp.scm
@@ -197,3 +197,37 @@
type: (identifier) @call.target
arguments: (argument_list) @call.arguments
) @call.site
+
+; ---------------------------------------------------------------------------
+; Parameter type references
+;
+; Captures the type node of every parameter inside a constructor, method,
+; or delegate signature so the graph builder can emit a "type_use" edge
+; from the containing file to the file declaring the type. This is the
+; backbone of DI-heavy resolution in C# / .NET — without it, classes that
+; exist only to be injected as ctor parameters read as orphans.
+; ---------------------------------------------------------------------------
+
+(constructor_declaration
+ parameters: (parameter_list
+ (parameter
+ type: (_) @param.type)))
+
+(method_declaration
+ parameters: (parameter_list
+ (parameter
+ type: (_) @param.type)))
+
+(delegate_declaration
+ parameters: (parameter_list
+ (parameter
+ type: (_) @param.type)))
+
+; Primary constructors on records (C# 9+): `record Foo(IBar bar)`.
+; tree-sitter-c-sharp 0.23 exposes the parameter list as an unnamed
+; child of record_declaration rather than a named field, so we omit
+; the `parameters:` field anchor that constructor_declaration uses.
+(record_declaration
+ (parameter_list
+ (parameter
+ type: (_) @param.type)))
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/dotnet/__init__.py b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/__init__.py
index 73b7dda5b..54686cfc7 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/dotnet/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/__init__.py
@@ -12,7 +12,7 @@ and cached on the ``ResolverContext`` for the lifetime of one
from __future__ import annotations
-from .index import DotNetProjectIndex, get_or_build_index
+from .index import DotNetProjectIndex, build_index, get_or_build_index
from .msbuild import MSBuildProject, parse_csproj
from .namespace_map import build_namespace_map
from .solution import SolutionEntry, parse_sln
@@ -21,6 +21,7 @@ __all__ = [
"DotNetProjectIndex",
"MSBuildProject",
"SolutionEntry",
+ "build_index",
"build_namespace_map",
"get_or_build_index",
"parse_csproj",
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 1c5a1ba26..9db23115c 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/dotnet/index.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/index.py
@@ -30,6 +30,13 @@ class DotNetProjectIndex:
namespace_map: dict[str, list[Path]] = field(default_factory=dict)
"""Maps a fully-qualified namespace to the set of .cs files declaring it."""
+ type_map: dict[str, list[Path]] = field(default_factory=dict)
+ """Maps an unqualified type name (e.g. ``IBasketService``) to defining files.
+
+ A type name can appear in multiple files (partial types, distinct types
+ with the same simple name in different namespaces). Callers rank the
+ candidates by project enclosure — see ``rank_type_candidates`` below."""
+
project_globals: dict[Path, set[str]] = field(default_factory=dict)
"""Maps a project's directory → global+implicit using namespaces."""
@@ -60,6 +67,50 @@ class DotNetProjectIndex:
def files_for_namespace(self, ns: str) -> list[Path]:
return self.namespace_map.get(ns, [])
+ def files_for_type(self, type_name: str) -> list[Path]:
+ return self.type_map.get(type_name, [])
+
+ def rank_type_candidates(
+ self,
+ type_name: str,
+ from_file: Path,
+ ) -> list[Path]:
+ """Return defining files for *type_name*, ranked by project enclosure.
+
+ Ranking matches ``resolve_csharp_import`` for namespace lookups:
+ 1. Same project as *from_file*
+ 2. Projects referenced by from_file's project (transitive=1)
+ 3. Anywhere else in the workspace
+
+ Same-named partial-type fragments collapse: each unique file
+ appears once. ``from_file`` is excluded so a class that only
+ names its own types doesn't get a self-edge.
+ """
+ candidates = self.type_map.get(type_name)
+ if not candidates:
+ return []
+
+ from_resolved = from_file.resolve()
+ from_proj = self.file_to_project.get(from_resolved)
+ ref_projs = self.project_refs_by_proj.get(from_proj, set()) if from_proj else set()
+
+ same_proj: list[Path] = []
+ ref_proj: list[Path] = []
+ repo_wide: list[Path] = []
+ seen: set[Path] = set()
+ for cand in candidates:
+ if cand in seen or cand == from_resolved:
+ continue
+ seen.add(cand)
+ cand_proj = self.file_to_project.get(cand)
+ if cand_proj is not None and cand_proj == from_proj:
+ same_proj.append(cand)
+ elif cand_proj is not None and cand_proj in ref_projs:
+ ref_proj.append(cand)
+ else:
+ repo_wide.append(cand)
+ return same_proj + ref_proj + repo_wide
+
def globals_for_project(self, csproj: Path) -> set[str]:
proj = self.projects.get(csproj)
if not proj:
@@ -116,7 +167,7 @@ def build_index(repo_path: Path) -> DotNetProjectIndex:
all_cs_files.extend(proj_files)
for f in proj_files:
index.file_to_project[f] = proj.path
- index.namespace_map = build_namespace_map(all_cs_files)
+ index.namespace_map, index.type_map = build_namespace_map(all_cs_files)
# ---- 4. Compute per-project global+implicit usings ----
for proj in index.projects.values():
@@ -137,6 +188,7 @@ def build_index(repo_path: Path) -> DotNetProjectIndex:
repo=str(repo_path),
projects=len(index.projects),
namespaces=len(index.namespace_map),
+ types=len(index.type_map),
sln=len(index.sln_paths),
)
return index
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 eb1ee1d86..b95f93def 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
@@ -1,9 +1,10 @@
-"""Build a namespace → file mapping by scanning .cs files for namespace declarations.
+"""Build namespace → file and type-name → file mappings.
-We use a regex rather than re-parsing the AST because the resolver runs
+We use regexes rather than re-parsing the AST because the resolver runs
after parsing has finished and ``parsed_files`` does not preserve raw
-namespace text in a uniform shape across grammar versions. The regex
-covers both block-form and file-scoped namespaces (C# 10+).
+namespace text in a uniform shape across grammar versions. The regexes
+cover both block-form and file-scoped namespaces (C# 10+) and the
+canonical type declaration forms.
"""
from __future__ import annotations
@@ -18,6 +19,27 @@ _NAMESPACE_RE = re.compile(
re.MULTILINE,
)
+# Captures `class Foo`, `interface IFoo`, `struct Foo`, `enum Foo`, `record Foo`.
+# Permits leading modifier soup (`public partial sealed class`) and an
+# optional generic-parameter list / inheritance clause after the name.
+# The name is captured up to (but excluding) the first `<`, `:`, `{`,
+# `(`, `;` or whitespace — covering generics, primary ctors, base
+# clauses, and braces / file-scoped forms uniformly.
+# The leading alternation accepts start-of-line OR semicolon as the
+# preceding context so file-scoped namespaces like
+# ``namespace Foo; class Bar {}`` (single-line, common in tests and
+# small samples) match as well as the canonical line-per-decl form.
+# A comment line like ``// class Foo {}`` is ruled out because the
+# alternation does not include ``/`` and the modifier-soup group is
+# anchored on whitespace, not arbitrary text.
+_TYPE_DECL_RE = re.compile(
+ r"(?:^|;)\s*(?:(?:public|private|internal|protected|static|sealed|abstract|partial|"
+ r"readonly|ref|unsafe|new|file)\s+)*"
+ r"(?:class|interface|struct|enum|record(?:\s+(?:class|struct))?)\s+"
+ r"([A-Za-z_]\w*)",
+ re.MULTILINE,
+)
+
def declared_namespaces(cs_text: str) -> list[str]:
"""Return every namespace declared in *cs_text*, in source order.
@@ -28,21 +50,46 @@ def declared_namespaces(cs_text: str) -> list[str]:
return [m.group(1) for m in _NAMESPACE_RE.finditer(cs_text)]
-def build_namespace_map(cs_files: list[Path]) -> dict[str, list[Path]]:
- """Return {namespace: [files declaring it]} for every .cs file given.
+def declared_type_names(cs_text: str) -> list[str]:
+ """Return every top-level type name declared in *cs_text*.
- Files that fail to read or declare no namespace are skipped silently.
+ Generic parameters and base clauses are stripped. ``partial`` types
+ declared across multiple files yield one match per file — the caller
+ builds a list-valued map so all defining files are surfaced.
"""
- out: dict[str, list[Path]] = {}
+ return [m.group(1) for m in _TYPE_DECL_RE.finditer(cs_text)]
+
+
+def build_namespace_map(
+ cs_files: list[Path],
+) -> tuple[dict[str, list[Path]], dict[str, list[Path]]]:
+ """Return ``(namespace_map, type_map)`` for every .cs file given.
+
+ * ``namespace_map[ns]`` → files declaring that namespace.
+ * ``type_map[type_name]`` → files declaring that type (unqualified
+ name). Multiple files per name is expected (partial types,
+ same-named types in different namespaces) — callers disambiguate
+ by project enclosure.
+
+ Files that fail to read or declare nothing 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
- seen: set[str] = set()
+ seen_ns: set[str] = set()
for ns in declared_namespaces(text):
- if ns in seen:
+ if ns in seen_ns:
+ continue
+ seen_ns.add(ns)
+ namespaces.setdefault(ns, []).append(path)
+ seen_t: set[str] = set()
+ for tn in declared_type_names(text):
+ if tn in seen_t:
continue
- seen.add(ns)
- out.setdefault(ns, []).append(path)
- return out
+ seen_t.add(tn)
+ types.setdefault(tn, []).append(path)
+ return namespaces, types
diff --git a/packages/core/src/repowise/core/ingestion/type_ref_resolution.py b/packages/core/src/repowise/core/ingestion/type_ref_resolution.py
new file mode 100644
index 000000000..edb94a979
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/type_ref_resolution.py
@@ -0,0 +1,200 @@
+"""Resolve ``TypeReference`` records to file-level ``imports`` edges.
+
+Background
+==========
+Static-typed, DI-heavy languages (C#, Java, Kotlin, Scala, Swift) place
+half their dependency surface inside constructor and method parameter
+lists rather than at the top of the file. A constructor like::
+
+ public class BasketViewModel(IBasketService basket) { ... }
+
+declares a hard dependency on ``IBasketService`` that the existing
+``using``-directive resolver never sees — there is no statement to
+translate into a file-to-file edge. The result is a graph in which every
+class registered for DI as a concrete implementation reads as an
+orphan, and dead-code analysis fires on every interface and ViewModel.
+
+This module closes the gap. The parser emits ``TypeReference`` records
+from ``@param.type`` captures in each language's ``.scm`` file; this
+module resolves them to defining files and emits ``imports`` edges
+during the graph build phase.
+
+Design
+======
+Per-language *strategies* sit behind a single ``resolve_type_refs``
+entrypoint. A strategy receives the ``ParsedFile``, the resolver
+context, and the graph being built, and is responsible for emitting
+edges into the graph. Strategies are registered in
+``_STRATEGIES`` keyed by ``LanguageTag``.
+
+Adding a new language is a matter of:
+ 1. Capturing ``@param.type`` in that language's ``.scm`` file.
+ 2. Writing a ``_resolve_<lang>_type_refs`` function (typically a
+ 30-line wrapper that calls the language's existing resolver
+ index — Java uses the package map, Kotlin the package map plus
+ Gradle sourceSets, Swift the SPM target map, etc).
+ 3. Registering it in ``_STRATEGIES``.
+
+No changes are required to ``parser.py`` or ``graph.py`` to add a
+language — the dispatcher walks every ``ParsedFile`` and routes by
+language tag.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+import structlog
+
+from .models import ParsedFile
+
+if TYPE_CHECKING:
+ import networkx as nx
+
+ from .resolvers import ResolverContext
+
+log = structlog.get_logger(__name__)
+
+# Confidence floor for synthesised type-use edges. Lower than a real
+# `using` directive (~1.0) because a same-name type can be defined in
+# multiple files and we rank-pick the most likely. The dead-code
+# analyzer treats any confidence > 0 as "reachable" so the exact value
+# only matters for downstream weighting (PageRank, blast-radius).
+_TYPE_USE_CONFIDENCE = 0.8
+
+
+# ---------------------------------------------------------------------------
+# Strategy: C# / .NET
+# ---------------------------------------------------------------------------
+
+def _resolve_csharp_type_refs(
+ parsed: ParsedFile,
+ ctx: "ResolverContext",
+ graph: "nx.DiGraph",
+) -> int:
+ """Resolve C# ``@param.type`` captures via ``DotNetProjectIndex``.
+
+ Returns the number of edges emitted. Same-file references and
+ references to builtin types are dropped silently (the parser
+ already filters builtins, but defence-in-depth is cheap here).
+ """
+ from .resolvers.dotnet import get_or_build_index
+
+ if not parsed.type_refs:
+ return 0
+
+ index = get_or_build_index(ctx)
+ if index is None or not index.type_map:
+ return 0
+
+ from_path = parsed.file_info.path
+ from_abs = Path(parsed.file_info.abs_path) if parsed.file_info.abs_path else None
+ if from_abs is None:
+ return 0
+
+ emitted = 0
+ for ref in parsed.type_refs:
+ candidates = index.rank_type_candidates(ref.type_name, from_abs)
+ if not candidates:
+ continue
+ target_abs = candidates[0]
+ # Convert to repo-relative POSIX path for graph keying.
+ try:
+ target_rel = target_abs.resolve().relative_to(index.repo_path).as_posix()
+ except ValueError:
+ continue
+ if target_rel == from_path:
+ continue
+ if not graph.has_node(target_rel):
+ # The defining file may have been gated out (e.g. excluded
+ # by .gitignore but still on disk). Skip silently.
+ continue
+ _add_or_merge_type_use_edge(
+ graph,
+ src=from_path,
+ dst=target_rel,
+ type_name=ref.type_name,
+ origin=ref.origin,
+ )
+ emitted += 1
+ return emitted
+
+
+# ---------------------------------------------------------------------------
+# Strategy registry
+# ---------------------------------------------------------------------------
+
+Strategy = Callable[[ParsedFile, "ResolverContext", "nx.DiGraph"], int]
+
+# Add new languages here — see module docstring. Keep the entries
+# tightly scoped: each strategy must only touch its own language's
+# index, never share resolver state across languages.
+_STRATEGIES: dict[str, Strategy] = {
+ "csharp": _resolve_csharp_type_refs,
+}
+
+
+def resolve_type_refs(
+ parsed_files: dict[str, ParsedFile],
+ ctx: "ResolverContext",
+ graph: "nx.DiGraph",
+) -> dict[str, int]:
+ """Dispatch each parsed file to its language's type-ref strategy.
+
+ Returns a per-language emitted-edge count for logging.
+ """
+ counts: dict[str, int] = {}
+ for parsed in parsed_files.values():
+ lang = parsed.file_info.language
+ strategy = _STRATEGIES.get(lang)
+ if strategy is None:
+ continue
+ emitted = strategy(parsed, ctx, graph)
+ if emitted:
+ counts[lang] = counts.get(lang, 0) + emitted
+ if counts:
+ log.info("type_use edges emitted", per_language=counts)
+ return counts
+
+
+# ---------------------------------------------------------------------------
+# Edge writer
+# ---------------------------------------------------------------------------
+
+def _add_or_merge_type_use_edge(
+ graph: "nx.DiGraph",
+ src: str,
+ dst: str,
+ 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.
+ """
+ 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)
+ return
+ graph.add_edge(
+ src,
+ dst,
+ edge_type="imports",
+ via="type_use",
+ origin=origin,
+ confidence=_TYPE_USE_CONFIDENCE,
+ type_uses=[type_name],
+ imported_names=[type_name],
+ )
diff --git a/tests/unit/ingestion/test_csharp_resolver.py b/tests/unit/ingestion/test_csharp_resolver.py
index ba528b518..1b25b6028 100644
--- a/tests/unit/ingestion/test_csharp_resolver.py
+++ b/tests/unit/ingestion/test_csharp_resolver.py
@@ -165,9 +165,12 @@ class TestNamespaceMap:
def test_build_namespace_map(self, tmp_path: Path) -> None:
(tmp_path / "user.cs").write_text("namespace Domain.Users; class User {}")
(tmp_path / "order.cs").write_text("namespace Domain.Orders; class Order {}")
- m = build_namespace_map([tmp_path / "user.cs", tmp_path / "order.cs"])
- assert "Domain.Users" in m
- assert "Domain.Orders" in m
+ ns_map, type_map = build_namespace_map([tmp_path / "user.cs", tmp_path / "order.cs"])
+ assert "Domain.Users" in ns_map
+ assert "Domain.Orders" in ns_map
+ # The type map surfaces the unqualified type name for each declared type.
+ assert tmp_path / "user.cs" in type_map["User"]
+ assert tmp_path / "order.cs" in type_map["Order"]
class TestGlobalUsings:
diff --git a/tests/unit/ingestion/test_csharp_type_use.py b/tests/unit/ingestion/test_csharp_type_use.py
new file mode 100644
index 000000000..615637e32
--- /dev/null
+++ b/tests/unit/ingestion/test_csharp_type_use.py
@@ -0,0 +1,311 @@
+"""Unit tests for C# type-use edge emission.
+
+Covers the chain from `@param.type` capture in the tree-sitter query
+through ``TypeReference`` extraction, ``DotNetProjectIndex.type_map``
+construction, candidate ranking by project enclosure, and graph-builder
+edge emission. End-to-end cases mirror real DI-heavy layouts: a
+controller takes an interface in its constructor; the interface lives
+in a referenced project.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import networkx as nx
+
+from repowise.core.ingestion.models import FileInfo, ParsedFile, TypeReference
+from repowise.core.ingestion.parser import ASTParser
+from repowise.core.ingestion.resolvers.context import ResolverContext
+from repowise.core.ingestion.resolvers.dotnet.index import build_index
+from repowise.core.ingestion.resolvers.dotnet.namespace_map import (
+ build_namespace_map,
+ declared_type_names,
+)
+from repowise.core.ingestion.type_ref_resolution import resolve_type_refs
+
+
+# ---------------------------------------------------------------------------
+# Fixtures
+# ---------------------------------------------------------------------------
+
+
+_CSPROJ_TEMPLATE = """<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <TargetFramework>net8.0</TargetFramework>
+ </PropertyGroup>
+ <ItemGroup>
+{refs}
+ </ItemGroup>
+</Project>
+"""
+
+
+def _csproj(refs: list[str] | None = None) -> str:
+ refs = refs or []
+ block = "\n".join(f' <ProjectReference Include="{p}" />' for p in refs)
+ return _CSPROJ_TEMPLATE.format(refs=block)
+
+
+def _file_info(repo: Path, rel: str) -> FileInfo:
+ """Build a minimal FileInfo for a .cs file at *rel*."""
+ abs_path = repo / rel
+ from datetime import UTC, datetime
+
+ return FileInfo(
+ path=rel,
+ abs_path=str(abs_path.resolve()),
+ language="csharp",
+ size_bytes=abs_path.stat().st_size if abs_path.exists() else 0,
+ git_hash="",
+ last_modified=datetime.now(UTC),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+
+
+# ---------------------------------------------------------------------------
+# Type-name regex
+# ---------------------------------------------------------------------------
+
+
+class TestDeclaredTypeNames:
+ def test_class(self) -> None:
+ assert declared_type_names("public class Foo {}") == ["Foo"]
+
+ def test_interface(self) -> None:
+ assert declared_type_names("internal interface IFoo {}") == ["IFoo"]
+
+ def test_struct(self) -> None:
+ assert declared_type_names("public readonly struct Point {}") == ["Point"]
+
+ def test_record(self) -> None:
+ assert declared_type_names("public record User(string Name);") == ["User"]
+
+ def test_record_class(self) -> None:
+ assert declared_type_names("public sealed record class User(string N);") == ["User"]
+
+ def test_generic_strips_args(self) -> None:
+ assert declared_type_names("public interface IRepo<T> where T : new() {}") == ["IRepo"]
+
+ def test_partial_repeats(self) -> None:
+ text = "partial class Foo {}\npartial class Foo {}"
+ # Same name yields two matches; the type_map deduplicates per
+ # file but preserves cross-file occurrences.
+ assert declared_type_names(text) == ["Foo", "Foo"]
+
+ def test_modifier_soup(self) -> None:
+ text = "public partial sealed unsafe class Net {}"
+ assert declared_type_names(text) == ["Net"]
+
+ def test_comment_not_matched(self) -> None:
+ # Leading whitespace + a comment shouldn't be matched. The
+ # regex anchors on start-of-line+whitespace+modifier, so a
+ # line starting with `//` falls through.
+ assert declared_type_names("// class Foo {}") == []
+
+
+# ---------------------------------------------------------------------------
+# DotNetProjectIndex.type_map
+# ---------------------------------------------------------------------------
+
+
+class TestTypeMap:
+ def test_built_from_repo(self, tmp_path: Path) -> None:
+ (tmp_path / "Domain").mkdir()
+ (tmp_path / "Domain" / "Domain.csproj").write_text(_csproj())
+ (tmp_path / "Domain" / "User.cs").write_text(
+ "namespace Acme.Domain;\npublic class User {}\n"
+ )
+ (tmp_path / "Domain" / "IRepo.cs").write_text(
+ "namespace Acme.Domain;\npublic interface IRepo {}\n"
+ )
+
+ index = build_index(tmp_path)
+ assert "User" in index.type_map
+ assert "IRepo" in index.type_map
+ assert len(index.type_map["User"]) == 1
+
+ def test_rank_prefers_same_project_then_referenced(self, tmp_path: Path) -> None:
+ # Three-project layout where the same type name exists in two
+ # places: the consumer's own project (should rank first) and
+ # a referenced project (second).
+ (tmp_path / "A").mkdir()
+ (tmp_path / "B").mkdir()
+ (tmp_path / "C").mkdir()
+ (tmp_path / "A" / "A.csproj").write_text(_csproj(refs=[r"..\B\B.csproj"]))
+ (tmp_path / "B" / "B.csproj").write_text(_csproj())
+ (tmp_path / "C" / "C.csproj").write_text(_csproj())
+ (tmp_path / "A" / "Local.cs").write_text("namespace A;\nclass Helper {}\n")
+ (tmp_path / "B" / "Ref.cs").write_text("namespace B;\nclass Helper {}\n")
+ (tmp_path / "C" / "Other.cs").write_text("namespace C;\nclass Helper {}\n")
+
+ index = build_index(tmp_path)
+ a_file = (tmp_path / "A" / "Local.cs").resolve()
+ ranked = index.rank_type_candidates("Helper", a_file)
+ # First should be from referenced project B (A_file itself is
+ # excluded from candidates as it's the source file); C should
+ # come last because A doesn't reference it.
+ paths = [p.resolve() for p in ranked]
+ b_file = (tmp_path / "B" / "Ref.cs").resolve()
+ c_file = (tmp_path / "C" / "Other.cs").resolve()
+ assert paths.index(b_file) < paths.index(c_file)
+
+
+# ---------------------------------------------------------------------------
+# Parser surfaces TypeReference records on real C# source
+# ---------------------------------------------------------------------------
+
+
+class TestParserEmitsTypeRefs:
+ def test_constructor_param(self, tmp_path: Path) -> None:
+ rel = "Foo.cs"
+ (tmp_path / rel).write_text(
+ "namespace Demo;\n"
+ "public class Foo {\n"
+ " public Foo(IBasketService basket) {}\n"
+ "}\n"
+ )
+ parsed = ASTParser().parse_file(_file_info(tmp_path, rel), (tmp_path / rel).read_bytes())
+ names = {r.type_name for r in parsed.type_refs}
+ assert "IBasketService" in names
+ # Origin should be classified as ctor_param
+ refs_for = [r for r in parsed.type_refs if r.type_name == "IBasketService"]
+ assert refs_for[0].origin == "ctor_param"
+
+ def test_method_param(self, tmp_path: Path) -> None:
+ rel = "Svc.cs"
+ (tmp_path / rel).write_text(
+ "namespace Demo;\n"
+ "class Svc {\n"
+ " public void Handle(EventEnvelope env) {}\n"
+ "}\n"
+ )
+ parsed = ASTParser().parse_file(_file_info(tmp_path, rel), (tmp_path / rel).read_bytes())
+ refs = [r for r in parsed.type_refs if r.type_name == "EventEnvelope"]
+ assert refs and refs[0].origin == "method_param"
+
+ def test_record_primary_constructor(self, tmp_path: Path) -> None:
+ rel = "Rec.cs"
+ (tmp_path / rel).write_text(
+ "namespace Demo;\n"
+ "public record Rec(Address Address);\n"
+ )
+ parsed = ASTParser().parse_file(_file_info(tmp_path, rel), (tmp_path / rel).read_bytes())
+ refs = [r for r in parsed.type_refs if r.type_name == "Address"]
+ assert refs and refs[0].origin == "ctor_param"
+
+ def test_builtin_types_skipped(self, tmp_path: Path) -> None:
+ rel = "X.cs"
+ (tmp_path / rel).write_text(
+ "namespace Demo;\nclass X { public X(int n, string s, bool b) {} }\n"
+ )
+ parsed = ASTParser().parse_file(_file_info(tmp_path, rel), (tmp_path / rel).read_bytes())
+ names = {r.type_name for r in parsed.type_refs}
+ # None of int / string / bool / Task etc. should appear.
+ assert names.isdisjoint({"int", "string", "bool"})
+
+ def test_generic_uses_head_identifier(self, tmp_path: Path) -> None:
+ rel = "G.cs"
+ (tmp_path / rel).write_text(
+ "namespace Demo;\nclass G { public G(IRepo<Basket> r) {} }\n"
+ )
+ parsed = ASTParser().parse_file(_file_info(tmp_path, rel), (tmp_path / rel).read_bytes())
+ names = {r.type_name for r in parsed.type_refs}
+ assert "IRepo" in names
+
+
+# ---------------------------------------------------------------------------
+# End-to-end: graph builder emits type_use edges (cross-project workspace)
+# ---------------------------------------------------------------------------
+
+
+class TestGraphEdgeEmission:
+ def test_cross_project_workspace_edge(self, tmp_path: Path) -> None:
+ # Two-project workspace: Api → Domain via ProjectReference.
+ # Api/UserController.cs takes an IUserRepo (declared in Domain)
+ # only as a ctor parameter, never via a using directive. The
+ # type_use pass must connect the two files.
+ (tmp_path / "src" / "Api").mkdir(parents=True)
+ (tmp_path / "src" / "Domain").mkdir(parents=True)
+ (tmp_path / "src" / "Api" / "Api.csproj").write_text(
+ _csproj(refs=[r"..\Domain\Domain.csproj"])
+ )
+ (tmp_path / "src" / "Domain" / "Domain.csproj").write_text(_csproj())
+ (tmp_path / "src" / "Domain" / "IUserRepo.cs").write_text(
+ "namespace Acme.Domain;\npublic interface IUserRepo {}\n"
+ )
+ (tmp_path / "src" / "Api" / "UserController.cs").write_text(
+ "namespace Acme.Api;\n"
+ "public class UserController {\n"
+ " public UserController(IUserRepo repo) {}\n"
+ "}\n"
+ )
+
+ parser = ASTParser()
+ parsed_files: dict[str, ParsedFile] = {}
+ for cs in tmp_path.rglob("*.cs"):
+ rel = cs.resolve().relative_to(tmp_path.resolve()).as_posix()
+ parsed = parser.parse_file(_file_info(tmp_path, rel), cs.read_bytes())
+ parsed_files[rel] = parsed
+
+ graph = nx.DiGraph()
+ for rel in parsed_files:
+ graph.add_node(rel, node_type="file", language="csharp")
+ ctx = ResolverContext(
+ path_set=set(parsed_files),
+ stem_map={},
+ graph=graph,
+ repo_path=tmp_path,
+ )
+
+ emitted = resolve_type_refs(parsed_files, ctx, graph)
+ assert emitted.get("csharp", 0) >= 1
+ src = "src/Api/UserController.cs"
+ 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 "IUserRepo" in data["type_uses"]
+
+
+# ---------------------------------------------------------------------------
+# Type-ref resolution is a no-op for non-C# languages
+# ---------------------------------------------------------------------------
+
+
+def test_resolve_type_refs_no_csharp(tmp_path: Path) -> None:
+ # A Python parsed file with manually-attached type_refs (which the
+ # parser never emits for Python today). The dispatcher must skip
+ # languages without a registered strategy.
+ from datetime import UTC, datetime
+
+ info = FileInfo(
+ path="a.py",
+ abs_path=str((tmp_path / "a.py").resolve()),
+ language="python",
+ size_bytes=0,
+ git_hash="",
+ last_modified=datetime.now(UTC),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+ parsed = ParsedFile(
+ file_info=info,
+ symbols=[],
+ imports=[],
+ exports=[],
+ type_refs=[TypeReference(type_name="Foo", line=1, origin="ctor_param")],
+ )
+ graph = nx.DiGraph()
+ graph.add_node("a.py", node_type="file", language="python")
+ ctx = ResolverContext(
+ path_set={"a.py"}, stem_map={}, graph=graph, repo_path=tmp_path,
+ )
+ emitted = resolve_type_refs({"a.py": parsed}, ctx, graph)
+ assert emitted == {}
diff --git a/tests/unit/ingestion/test_xaml_dynamic_hints.py b/tests/unit/ingestion/test_xaml_dynamic_hints.py
new file mode 100644
index 000000000..18e0b3ccb
--- /dev/null
+++ b/tests/unit/ingestion/test_xaml_dynamic_hints.py
@@ -0,0 +1,98 @@
+"""Unit tests for the XAML dynamic-hint extractor.
+
+Covers WinUI 3 ``using:`` and WPF ``clr-namespace:`` xmlns shapes,
+``x:DataType`` extraction, and end-to-end edge emission against a
+mini workspace with a .csproj on disk (so the C# type_map gets built).
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from repowise.core.ingestion.dynamic_hints.xaml import (
+ XamlDynamicHints,
+ _collect_prefix_namespaces,
+ _extract_type_references,
+)
+
+
+_CSPROJ = """<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <TargetFramework>net8.0-windows10.0.19041.0</TargetFramework>
+ <UseWPF>true</UseWPF>
+ </PropertyGroup>
+</Project>
+"""
+
+
+class TestPrefixCollection:
+ def test_winui_using_prefix(self) -> None:
+ text = '<Page xmlns:vm="using:Acme.ViewModels">'
+ assert _collect_prefix_namespaces(text) == {"vm": "Acme.ViewModels"}
+
+ def test_wpf_clr_namespace(self) -> None:
+ text = '<Window xmlns:m="clr-namespace:Acme.Models">'
+ assert _collect_prefix_namespaces(text) == {"m": "Acme.Models"}
+
+ def test_wpf_cross_assembly(self) -> None:
+ text = '<Window xmlns:m="clr-namespace:Acme.Models;assembly=Acme.Domain">'
+ assert _collect_prefix_namespaces(text) == {"m": "Acme.Models"}
+
+ def test_multiple(self) -> None:
+ text = (
+ '<Page xmlns:vm="using:Acme.ViewModels" '
+ 'xmlns:m="clr-namespace:Acme.Models">'
+ )
+ result = _collect_prefix_namespaces(text)
+ assert result["vm"] == "Acme.ViewModels"
+ assert result["m"] == "Acme.Models"
+
+
+class TestTypeReferenceExtraction:
+ def test_x_datatype(self) -> None:
+ text = '<Page><Grid x:DataType="vm:GeneralViewModel"/></Page>'
+ refs = _extract_type_references(text, {"vm": "Acme.ViewModels"})
+ assert "GeneralViewModel" in refs
+
+ def test_xtype_markup_extension(self) -> None:
+ text = '<Page DataContext="{x:Type vm:SettingsViewModel}"/>'
+ refs = _extract_type_references(text, {"vm": "Acme.ViewModels"})
+ assert "SettingsViewModel" in refs
+
+ def test_lowercase_attribute_value_skipped(self) -> None:
+ # Attribute values that don't start with an uppercase letter
+ # (e.g. property names accidentally captured) are skipped.
+ text = '<Page TargetType="control"/>'
+ refs = _extract_type_references(text, {})
+ assert "control" not in refs
+
+
+class TestEndToEnd:
+ def test_emits_edge_from_xaml_to_viewmodel_file(self, tmp_path: Path) -> None:
+ (tmp_path / "App").mkdir()
+ (tmp_path / "App" / "App.csproj").write_text(_CSPROJ)
+ (tmp_path / "App" / "ViewModels").mkdir()
+ (tmp_path / "App" / "ViewModels" / "GeneralViewModel.cs").write_text(
+ "namespace App.ViewModels;\npublic class GeneralViewModel {}\n"
+ )
+ (tmp_path / "App" / "Views").mkdir()
+ (tmp_path / "App" / "Views" / "GeneralPage.xaml").write_text(
+ '<Page xmlns:vm="using:App.ViewModels" x:DataType="vm:GeneralViewModel">\n'
+ "</Page>\n"
+ )
+
+ edges = XamlDynamicHints().extract(tmp_path)
+ sources = {(e.source, e.target) for e in edges}
+ assert (
+ "App/Views/GeneralPage.xaml",
+ "App/ViewModels/GeneralViewModel.cs",
+ ) in sources
+
+ def test_no_csproj_emits_nothing(self, tmp_path: Path) -> None:
+ # A repo with XAML but no .csproj has no .NET type index to
+ # bind against; the extractor should silently produce nothing
+ # rather than spuriously create external edges.
+ (tmp_path / "View.xaml").write_text(
+ '<Page xmlns:vm="using:Foo" x:DataType="vm:Bar"/>'
+ )
+ assert XamlDynamicHints().extract(tmp_path) == []