Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(csharp): promote C# to Full tier with enterprise multi-repo support (#105)
Raghav Chamadiya8316d44e51dd
diff --git a/.gitignore b/.gitignoreindex 6d68a1771..f814a6aaf 100644--- a/.gitignore+++ b/.gitignore@@ -120,4 +120,5 @@ ehthumbs.db# Internal docs (not for distribution)docs/COMPETITIVE_ANALYSIS.mddocs/GRAPH_INTELLIGENCE_UPGRADE.md+docs/LOCAL_DEV.mddocs/multi-repo/diff --git a/README.md b/README.mdindex c7fa3cd4c..a206d36d6 100644--- a/README.md+++ b/README.md@@ -549,11 +549,11 @@ repowise reindex # rebuild vector store (no LLM calls)| Tier | Languages | What works ||------|-----------|------------|-| **Full** | Python · TypeScript · JavaScript · Java · Go · Rust · C++ | AST parsing, import resolution, named bindings, call resolution, heritage extraction, docstrings |-| **Good** | C · Kotlin · Ruby · C# · Swift · Scala · PHP | AST parsing, import resolution, named bindings, call resolution, heritage (mixins, derive, extensions, traits), docstrings, dedicated resolvers |+| **Full** | Python · TypeScript · JavaScript · Java · Go · Rust · C++ · C# | AST parsing, import resolution, named bindings, call resolution, heritage extraction, docstrings; .csproj/.sln-aware multi-project resolver and ASP.NET framework edges for C# |+| **Good** | C · Kotlin · Ruby · Swift · Scala · PHP | AST parsing, import resolution, named bindings, call resolution, heritage (mixins, derive, extensions, traits), docstrings, dedicated resolvers || **Config / data** | OpenAPI · Protobuf · GraphQL · Dockerfile · Makefile · YAML · JSON · TOML · SQL · Terraform | Included in the file tree; special handlers extract endpoints/targets where applicable |-14 languages with full AST support. Adding a new language requires one `.scm` tree-sitter query file and one config entry. No changes to the parser core. See [Language Support](docs/LANGUAGE_SUPPORT.md) for details.+14 languages with full AST support, 8 of them at the Full tier. Adding a new language requires one `.scm` tree-sitter query file and one config entry. No changes to the parser core. See [Language Support](docs/LANGUAGE_SUPPORT.md) for details.---diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 6f3344a45..770f05fc7 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -9,6 +9,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0---+## [0.3.2] — Unreleased++### Added++#### C# Full tier+- **MSBuild-aware import resolver** — new `resolvers/dotnet/` subpackage parses every `.csproj` and `.sln` in the repo, builds a namespace → file map across projects, walks `Directory.Build.props` ancestry, and resolves `using` directives by ranking candidates: same project → directly-referenced project → anywhere. NuGet `<PackageReference>` ids are emitted as `external:nuget:<id>` nodes. Falls back to legacy stem-match for repos without `.csproj`.+- **Modern C# language features** — `csharp.scm` now captures `record_declaration`, `delegate_declaration`, `event_declaration`/`event_field_declaration`, `field_declaration`, `enum_member_declaration`, and both block-form and file-scoped `namespace_declaration`. `LANGUAGE_CONFIGS` and the registry's `heritage_node_types` are extended accordingly.+- **`global using` / `using static` / `using alias` propagation** — `NamedBinding` gains `is_global` and `is_static_import` flags; `extract_csharp_bindings` distinguishes all four flavours of `using` directive. Default `<ImplicitUsings>` set (with Web SDK extras) and `global using` lines are merged into a per-project implicit-usings set used by the resolver.+- **XML doc parsing** — module-level and symbol-level `///` runs are extracted, `<summary>` content is unwrapped as the rendered docstring, structural tags (`<param>`, `<returns>`, `<see/>`) are stripped, and `<inheritdoc/>` emits a `{inheritdoc}` marker.+- **Heritage for records** — `record User(...) : Base(args), IInterface` now produces both `extends` and `implements` edges; primary-constructor argument lists are skipped.+- **ASP.NET / .NET framework edges** — `_add_aspnet_edges()` runs whenever the tech stack mentions ASP.NET or any `.cs` file imports `Microsoft.AspNetCore.*`. Adds edges from `Program.cs` / `Startup.cs` to every `[ApiController]` file, `app.MapGet/...` handler classes, `app.UseMiddleware<T>()` middleware, and from each `DbContext` to entity files referenced via `DbSet<T>`.+- **.NET dynamic hints** — new `DotNetDynamicHints` extractor (registered in `HintRegistry`) records DI registrations (`AddScoped`/`AddSingleton`/`AddTransient`/`AddHostedService`), reflection (`Activator.CreateInstance`, `Type.GetType`, `Assembly.Load*`), `[assembly: InternalsVisibleTo]`, and MEF `[Export]`/`[ImportMany]` as graph edges.+- **Workspace contract extraction for ASP.NET and gRPC-dotnet** — `http_extractor.py` learns `[HttpGet/Post/...]` attribute routing with class-level `[Route]` prefix stitching, parameterless `[HttpVerb]` attributes, minimal API (`app.MapGet`/...), and HttpClient consumers (`*Async`). `grpc_extractor.py` recognises `app.MapGrpcService<T>()`, `class X : Service.ServiceBase`, and `new ServiceClient(channel)`.+- **Cross-repo `<ProjectReference>` and internal NuGet** — `cross_repo._scan_csproj` walks every `.csproj` in every workspace repo and emits `dotnet_project_ref` for cross-repo project references and `dotnet_nuget_internal` when a `<PackageReference>` id matches a sibling repo's `<AssemblyName>`.+- **Dead-code dynamic markers for C#** — `_DYNAMIC_IMPORT_MARKERS` learns reflection / DI / MEF / `InternalsVisibleTo` patterns so the dead-code analyser doesn't flag types only loaded by the framework at runtime.+- **Multi-project test fixtures** — `tests/fixtures/dotnet_solution/` (Api / Domain / Infrastructure with EF Core, controllers, minimal API, GlobalUsings) and `tests/fixtures/dotnet_workspace/` (3 repos demonstrating cross-repo `<ProjectReference>` + internal-NuGet patterns), with end-to-end coverage in `tests/integration/test_dotnet_solution.py`.++### Changed+- **Language tier promotion** — C# moves from "Good" to "Full" in `README.md` and `docs/LANGUAGE_SUPPORT.md`. Eight languages now sit at Full tier (was: seven).++---+## [0.3.1] — 2026-04-26### Addeddiff --git a/docs/LANGUAGE_SUPPORT.md b/docs/LANGUAGE_SUPPORT.mdindex 6f8457ccb..1f2c9aa53 100644--- a/docs/LANGUAGE_SUPPORT.md+++ b/docs/LANGUAGE_SUPPORT.md@@ -42,14 +42,16 @@ call resolution, named bindings, heritage extraction, and docstrings.| **Go** | `.go` | `main.go` `cmd/main.go` | `import "path"` with `go.mod` resolution || **Rust** | `.rs` | `main.rs` `lib.rs` | `use crate::` / `use super::` / `use self::` with `Cargo.toml` || **C++** | `.cpp` `.cc` `.cxx` `.h` `.hpp` `.hxx` | `main.cpp` `main.cc` | `#include` with `compile_commands.json` resolution |+| **C#** | `.cs` | `Program.cs` `Startup.cs` | `using Acme.Domain` / `global using` / `using static` / `using Alias = X.Y.Z` with `.csproj` / `.sln` / `Directory.Build.props` resolution |-All seven languages support:+All eight languages support:- Tree-sitter AST parsing with dedicated `.scm` query files- Three-tier call resolution (same-file, cross-file, global stem match)- Named binding extraction (mapping imported names to source symbols)-- Heritage extraction (class/interface/trait inheritance chains)-- Docstring extraction (Python, JSDoc, GoDoc, Rustdoc, Javadoc, Doxygen)-- Framework-aware edges (Django, FastAPI, Flask for Python; tsconfig path aliases for TS/JS; pytest fixture detection)+- Heritage extraction (class/interface/trait/record inheritance chains)+- Docstring extraction (Python, JSDoc, GoDoc, Rustdoc, Javadoc, Doxygen, XML doc)+- Framework-aware edges (Django, FastAPI, Flask for Python; tsconfig path aliases for TS/JS; pytest fixture detection; ASP.NET controllers / minimal API / EF Core DbContext for C#)+- For C# only: MSBuild project graph (`<ProjectReference>` / `<PackageReference>`), namespace → file mapping across projects, `global using` / `using static` / `using alias` propagation, ASP.NET HTTP and gRPC-dotnet contract extraction in workspace mode, cross-repo `<ProjectReference>` and internal-NuGet detection### Good@@ -63,7 +65,6 @@ resolvers for each language.| **C** | `.c` | `main.c` | `#include` with `compile_commands.json` (shares C++ grammar) || **Kotlin** | `.kt` `.kts` | `Main.kt` `Application.kt` | `import com.example.Foo` || **Ruby** | `.rb` | `main.rb` `app.rb` `config.ru` | `require 'mod'` / `require_relative './mod'` |-| **C#** | `.cs` | `Program.cs` `Startup.cs` | `using System.Collections.Generic` || **Swift** | `.swift` | `main.swift` `App.swift` | `import Foundation` || **Scala** | `.scala` | `Main.scala` `App.scala` | `import pkg.{A, B => C}` || **PHP** | `.php` | `index.php` `public/index.php` | `use Foo\Bar\Baz` |diff --git a/packages/core/src/repowise/core/analysis/dead_code.py b/packages/core/src/repowise/core/analysis/dead_code.pyindex 778323bb5..12e103ed4 100644--- a/packages/core/src/repowise/core/analysis/dead_code.py+++ b/packages/core/src/repowise/core/analysis/dead_code.py@@ -194,6 +194,29 @@ class DeadCodeAnalyzer:".rb": ("autoload ", "const_get(", "send(:require"),".php": ("class_exists(", "interface_exists("),".go": ("plugin.Open(", "reflect.New("),+ ".cs": (+ # Reflection-driven type loading+ "Type.GetType(",+ "Activator.CreateInstance(",+ "Assembly.Load(",+ "Assembly.LoadFrom(",+ "Assembly.LoadFile(",+ "GetExecutingAssembly().GetTypes(",+ # Cross-assembly visibility — types named in the friend assembly+ # may be used externally even with no static call site.+ "[assembly: InternalsVisibleTo",+ # Trim-safe reflection annotation+ "[DynamicDependency",+ # MEF / VS extensibility composition+ "[Export",+ "[ImportMany",+ # DI registration: types registered here have no static caller+ # but the framework instantiates them at runtime. Three forms.+ "AddScoped<",+ "AddSingleton<",+ "AddTransient<",+ "AddHostedService<",+ ),}def __init__(diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/dotnet.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/dotnet.pynew file mode 100644index 000000000..7492c858d--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/dotnet.py@@ -0,0 +1,180 @@+"""Dynamic-hint extractor for .NET / C# patterns that escape static analysis.++The .NET ecosystem leans heavily on conventions that the AST never sees:++- ``services.AddScoped<IFoo, Foo>()`` — DI container registration that+ wires consumers (which depend on ``IFoo``) to producers (the ``Foo``+ implementation type) only at runtime.+- ``Activator.CreateInstance(typeof(T))`` / ``Type.GetType("X.Y.Z")`` —+ reflection-driven type loading.+- ``[assembly: InternalsVisibleTo("Other.Tests")]`` — cross-project+ visibility that pretends the friend assembly imports everything+ without writing any using directive.++These patterns produce ``DynamicEdge`` rows so the dead-code analyser+won't flag DI-registered types and the graph reflects the de facto+dependency surface.+"""++from __future__ import annotations++import re+from pathlib import Path++from .base import DynamicEdge, DynamicHintExtractor++_SKIP_DIRS = {"bin", "obj", ".vs", "node_modules", ".git", "packages"}++# services.AddScoped<IFoo, Foo>() / AddSingleton<...> / AddTransient<...>+_DI_GENERIC_RE = re.compile(+ r"\.\s*Add(?:Scoped|Singleton|Transient|HostedService)\s*<\s*([\w.]+)\s*(?:,\s*([\w.]+)\s*)?>"+)++# Activator.CreateInstance(typeof(Foo)) / Activator.CreateInstance("Acme.Foo")+_ACTIVATOR_TYPEOF_RE = re.compile(r"Activator\.CreateInstance\s*\(\s*typeof\s*\(\s*([\w.]+)\s*\)")+_ACTIVATOR_STRING_RE = re.compile(r"Activator\.CreateInstance\s*\(\s*[\"']([\w.]+)[\"']")++# Type.GetType("Acme.Foo")+_TYPE_GETTYPE_RE = re.compile(r"Type\.GetType\s*\(\s*[\"']([\w.]+)[\"']")++# [assembly: InternalsVisibleTo("Other.Tests")]+_INTERNALS_VISIBLE_RE = re.compile(+ r"\[\s*assembly\s*:\s*InternalsVisibleTo\s*\(\s*[\"']([^\"']+)[\"']"+)+++class DotNetDynamicHints(DynamicHintExtractor):+ """Discover DI registrations, reflection, and assembly-level hints in .NET."""++ name = "dotnet"++ def extract(self, repo_root: Path) -> list[DynamicEdge]:+ edges: list[DynamicEdge] = []++ # Build a class-name → file index in one pass so the regex hits below+ # can resolve target file paths cheaply. We deliberately use a regex+ # rather than re-running the AST parser — this extractor runs after+ # parsing and operates on raw file text.+ type_to_file: dict[str, str] = {}+ cs_files: list[tuple[Path, str]] = [] # (path, text)+ for cs in repo_root.rglob("*.cs"):+ if any(part in _SKIP_DIRS for part in cs.parts):+ continue+ try:+ text = cs.read_text(encoding="utf-8-sig", errors="ignore")+ except OSError:+ continue+ try:+ rel = cs.resolve().relative_to(repo_root.resolve()).as_posix()+ except ValueError:+ continue+ cs_files.append((cs, text))+ # Only index publicly-declared top-level types — generic regex; a+ # collision falls back to the first match seen.+ for match in re.finditer(+ r"\b(?:class|interface|struct|record(?:\s+(?:class|struct))?|enum)\s+([A-Z]\w*)",+ text,+ ):+ name = match.group(1)+ type_to_file.setdefault(name, rel)++ def _short(name: str) -> str:+ return name.rsplit(".", 1)[-1]++ for cs, text in cs_files:+ try:+ rel = cs.resolve().relative_to(repo_root.resolve()).as_posix()+ except ValueError:+ continue++ # ---- DI: AddScoped<IFoo, Foo>() ----+ for match in _DI_GENERIC_RE.finditer(text):+ first = _short(match.group(1))+ second = _short(match.group(2)) if match.group(2) else None+ # When two type args are present, edge: registration site → impl+ # When one type arg is present, edge: registration site → that type+ target_name = second or first+ target = type_to_file.get(target_name)+ if target and target != rel:+ edges.append(+ DynamicEdge(+ source=rel,+ target=target,+ edge_type="dynamic_uses",+ hint_source=f"{self.name}:di_register",+ )+ )+ # Also link interface → impl when both are present so the+ # interface file is recorded as having a real implementation+ # (helps dead-code analysis treat unused interfaces correctly).+ if second is not None:+ iface_target = type_to_file.get(first)+ impl_target = type_to_file.get(second)+ if iface_target and impl_target and iface_target != impl_target:+ edges.append(+ DynamicEdge(+ source=iface_target,+ target=impl_target,+ edge_type="dynamic_uses",+ hint_source=f"{self.name}:di_interface_to_impl",+ )+ )++ # ---- Reflection: Activator.CreateInstance(typeof(...)) ----+ for match in _ACTIVATOR_TYPEOF_RE.finditer(text):+ target = type_to_file.get(_short(match.group(1)))+ if target and target != rel:+ edges.append(+ DynamicEdge(+ source=rel,+ target=target,+ edge_type="dynamic_uses",+ hint_source=f"{self.name}:activator",+ )+ )++ # ---- Reflection: Activator.CreateInstance("Acme.Foo") ----+ for match in _ACTIVATOR_STRING_RE.finditer(text):+ target = type_to_file.get(_short(match.group(1)))+ if target and target != rel:+ edges.append(+ DynamicEdge(+ source=rel,+ target=target,+ edge_type="dynamic_uses",+ hint_source=f"{self.name}:activator_string",+ )+ )++ # ---- Reflection: Type.GetType("Acme.Foo") ----+ for match in _TYPE_GETTYPE_RE.finditer(text):+ target = type_to_file.get(_short(match.group(1)))+ if target and target != rel:+ edges.append(+ DynamicEdge(+ source=rel,+ target=target,+ edge_type="dynamic_uses",+ hint_source=f"{self.name}:type_gettype",+ )+ )++ # ---- [assembly: InternalsVisibleTo("Other.Tests")] ----+ for match in _INTERNALS_VISIBLE_RE.finditer(text):+ friend = match.group(1)+ # Map by best-effort: AssemblyName usually equals the project's+ # csproj filename. We can't always resolve precisely without the+ # DotNetProjectIndex, so we record the friend as a synthetic+ # external target. The dead-code analyser uses InternalsVisibleTo+ # presence as a strong "type may be used" signal regardless of+ # whether we can resolve it.+ edges.append(+ DynamicEdge(+ source=rel,+ target=f"external:friend:{friend}",+ edge_type="dynamic_uses",+ hint_source=f"{self.name}:internals_visible_to",+ )+ )++ return edgesdiff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.pyindex 16b375001..de7ccaa3c 100644--- a/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.py+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.py@@ -6,6 +6,7 @@ import structlogfrom .base import DynamicEdge, DynamicHintExtractorfrom .django import DjangoDynamicHints+from .dotnet import DotNetDynamicHintsfrom .pytest_hints import PytestDynamicHintsfrom .node import NodeDynamicHints@@ -18,6 +19,7 @@ class HintRegistry:DjangoDynamicHints(),PytestDynamicHints(),NodeDynamicHints(),+ DotNetDynamicHints(),]def extract_all(self, repo_root: Path) -> list[DynamicEdge]:diff --git a/packages/core/src/repowise/core/ingestion/extractors/bindings.py b/packages/core/src/repowise/core/ingestion/extractors/bindings.pyindex eb879f025..90f94b0e1 100644--- a/packages/core/src/repowise/core/ingestion/extractors/bindings.py+++ b/packages/core/src/repowise/core/ingestion/extractors/bindings.py@@ -335,21 +335,81 @@ def extract_ruby_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[Nadef extract_csharp_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[NamedBinding]]:- """Extract bindings from C# using directives."""- alias = None+ """Extract bindings from C# using directives.++ Recognises:+ using Foo; -> NamedBinding(local="Foo", exported="Foo")+ using Foo.Bar.Baz; -> NamedBinding(local="Baz", exported="Foo.Bar.Baz")+ using Alias = Foo.Bar.Type; -> NamedBinding(local="Alias", exported=..., is_module_alias=True)+ global using Foo; -> NamedBinding(..., is_global=True)+ using static Foo.Bar; -> NamedBinding(..., is_static_import=True)+ global using static Foo.Bar; -> both flags True++ The ``global`` and ``static`` modifiers appear as keyword child nodes+ of ``using_directive`` in tree-sitter-c-sharp >= 0.23.+ """+ alias: str | None = Nonenamespace = ""+ is_global = False+ is_static = False+ saw_equals = False+ pending_identifier: str | None = None # the identifier seen before `=`, if any+for child in stmt_node.children:+ # Modifier keywords / structural tokens.+ if not child.is_named:+ tok = node_text(child, src)+ if tok == "global":+ is_global = True+ continue+ if tok == "static":+ is_static = True+ continue+ if tok == "=":+ saw_equals = True+ if pending_identifier is not None:+ alias = pending_identifier+ pending_identifier = None+ continue+ continue+ # name_equals appears in some grammar versions as a wrapper for+ # `(identifier) =`. Older 0.23 grammars emit the identifier as a+ # bare sibling and the `=` as an anonymous token — handled above.if child.type == "name_equals":- # using Alias = Full.Namespace;for sub in child.children:if sub.type == "identifier":alias = node_text(sub, src)- elif child.type in ("qualified_name", "identifier"):+ continue+ if child.type == "identifier":+ text = node_text(child, src)+ if saw_equals:+ # Identifier on the right of `=` is the alias target.+ namespace = text+ else:+ # Could be the alias (if `=` follows) or a single-name namespace.+ # Stash it and decide once we know.+ pending_identifier = text+ continue+ if child.type == "qualified_name":namespace = node_text(child, src)++ # If we never saw `=`, the pending identifier (if any) is the namespace.+ if pending_identifier is not None and not namespace:+ namespace = pending_identifier+if not namespace:return [], []local = alias if alias else namespace.rsplit(".", 1)[-1]- return [local], [NamedBinding(local_name=local, exported_name=namespace, source_file=None)]+ return [local], [+ NamedBinding(+ local_name=local,+ exported_name=namespace,+ source_file=None,+ is_module_alias=alias is not None,+ is_global=is_global,+ is_static_import=is_static,+ )+ ]def extract_swift_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[NamedBinding]]:diff --git a/packages/core/src/repowise/core/ingestion/extractors/docstrings.py b/packages/core/src/repowise/core/ingestion/extractors/docstrings.pyindex 7ebd74f25..651e5fc43 100644--- a/packages/core/src/repowise/core/ingestion/extractors/docstrings.py+++ b/packages/core/src/repowise/core/ingestion/extractors/docstrings.py@@ -2,6 +2,8 @@from __future__ import annotations+import re+from tree_sitter import Nodefrom .helpers import (@@ -13,6 +15,32 @@ from .helpers import ()+# C# XML doc comments use a small set of tags. We extract <summary> as the+# primary docstring text and drop the structural markup. The fragments are+# rarely strict XML (e.g. unclosed <see cref="..."/> in legacy code), so a+# real parser would refuse to load them — regex extraction is correct here.+_CSHARP_SUMMARY_RE = re.compile(r"<summary>\s*(.*?)\s*</summary>", re.DOTALL | re.IGNORECASE)+_CSHARP_TAG_RE = re.compile(r"<[^>]+>")+_CSHARP_INHERITDOC_RE = re.compile(r"<inheritdoc\s*/?>", re.IGNORECASE)+++def _csharp_clean_xml_doc(text: str) -> str:+ """Strip XML scaffolding from a C# /// XML doc string.++ If a <summary> block is present, return its inner text (with tags+ removed). Otherwise return the input with all tags stripped. This+ mirrors the convention dotnet's documentation tooling applies when+ rendering Markdown.+ """+ if _CSHARP_INHERITDOC_RE.search(text):+ # Mark the doc so a future post-pass can resolve it from the parent.+ return "{inheritdoc}"+ summary_match = _CSHARP_SUMMARY_RE.search(text)+ body = summary_match.group(1) if summary_match else text+ body = _CSHARP_TAG_RE.sub("", body)+ return " ".join(body.split())++def extract_module_docstring(root: Node, src: str, lang: str) -> str | None:"""Extract a module/file-level docstring or leading comment."""if lang == "python":@@ -89,13 +117,29 @@ def extract_module_docstring(root: Node, src: str, lang: str) -> str | None:return "\n".join(lines) if lines else Noneelif lang == "csharp":+ # Module-level XML doc: a run of `///` lines, optionally preceded by+ # a /** block. Either form may appear before any using directives or+ # the (file-scoped) namespace declaration.+ triple_slash_lines: list[str] = []for child in root.children:if child.type == "comment":text = node_text(child, src).strip()if text.startswith("/**"):return clean_jsdoc(text)- elif child.type not in ("comment", "using_directive"):+ if text.startswith("///"):+ triple_slash_lines.append(text.lstrip("/ ").strip())+ continue+ # Plain // comment — ignore but keep scanning for /// runs.+ continue+ elif child.type not in (+ "comment",+ "using_directive",+ "global_using_directive",+ "extern_alias_directive",+ ):break+ if triple_slash_lines:+ return _csharp_clean_xml_doc("\n".join(triple_slash_lines))elif lang == "swift":for child in root.children:@@ -209,11 +253,14 @@ def extract_symbol_docstring(def_node: Node, src: str, lang: str) -> str | None:return _find_preceding_line_doc_comments(def_node, src, "#")elif lang == "csharp":- # XML doc comments: /// lines or /** block+ # XML doc comments: /// lines or /** block. After collecting the raw+ # text, strip XML tags so callers see the human-readable summary.result = find_preceding_block_comment(def_node, src, "/**")+ if not result:+ result = _find_preceding_line_doc_comments(def_node, src, "///")if result:- return result- return _find_preceding_line_doc_comments(def_node, src, "///")+ return _csharp_clean_xml_doc(result)+ return Noneelif lang == "swift":# Swift doc: /** block or /// linesdiff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage.py b/packages/core/src/repowise/core/ingestion/extractors/heritage.pyindex a18fca152..fdbd0a025 100644--- a/packages/core/src/repowise/core/ingestion/extractors/heritage.py+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage.py@@ -470,28 +470,63 @@ def _extract_swift_heritage(def _extract_csharp_heritage(def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]) -> None:- """C#: class Foo : Bar, IFoo."""+ """C#: ``class Foo : Bar, IFoo`` and ``record Point(...) : BaseRecord(...)``.++ Classification heuristic — C# uses a single ``base_list`` with no syntactic+ distinction between ``extends`` (the optional single base class) and+ ``implements`` (zero or more interfaces). We classify by:++ 1. The first non-interface-named base is the extends target. C#+ requires the base class to come first when present, so position+ is a strong hint.+ 2. Names matching the I[A-Z]... convention or known framework+ interfaces (``System.IDisposable`` etc.) are treated as+ ``implements``.+ 3. Records can also appear in the base list with an argument list:+ ``record Point(int X) : Base(X)`` — the ``argument_list`` child+ is ignored, only the type identifier matters.++ The classification is best-effort. A future post-pass that resolves+ each parent_name to its declared kind (class vs interface) could+ refine this.+ """+ # Index children for record primary-constructor base call.+ base_list = Nonefor child in def_node.children:if child.type == "base_list":- for base in child.children:- if base.type in (":", ","):- continue- text = node_text(base, src).strip()- bare = text.split(".")[-1].split("<")[0].strip()- if bare and bare != name:- kind = (- "implements"- if bare.startswith("I") and len(bare) > 1 and bare[1].isupper()- else "extends"- )- out.append(- HeritageRelation(- child_name=name,- parent_name=bare,- kind=kind,- line=line,- )- )+ base_list = child+ break+ if base_list is None:+ return++ seen_extends = False # Only the first non-interface-looking base counts as extends.+ for base in base_list.children:+ if base.type in (":", ",") or not base.is_named:+ continue+ # Records: `: Base(X, Y)` is a primary_constructor_base_type wrapping+ # the type name and an argument list. Skip the argument list.+ if base.type == "argument_list":+ continue+ text = node_text(base, src).strip()+ # Strip generic args and outer namespace qualification.+ bare = text.split("<")[0].split("(")[0].strip()+ bare = bare.rsplit(".", 1)[-1].strip()+ if not bare or bare == name:+ continue+ looks_interface = bare.startswith("I") and len(bare) > 1 and bare[1].isupper()+ if looks_interface or seen_extends:+ kind = "implements"+ else:+ kind = "extends"+ seen_extends = True+ out.append(+ HeritageRelation(+ child_name=name,+ parent_name=bare,+ kind=kind,+ line=line,+ )+ )def _extract_scala_heritage(diff --git a/packages/core/src/repowise/core/ingestion/framework_edges.py b/packages/core/src/repowise/core/ingestion/framework_edges.pyindex 65894a97d..68d39a407 100644--- a/packages/core/src/repowise/core/ingestion/framework_edges.py+++ b/packages/core/src/repowise/core/ingestion/framework_edges.py@@ -43,6 +43,16 @@ def add_framework_edges(if "flask" in stack_lower:count += _add_flask_edges(graph, parsed_files, ctx, path_set)+ # ASP.NET framework edges run when the tech stack hints at .NET web,+ # OR when any .cs file imports Microsoft.AspNetCore.* (cheap fallback+ # so we don't depend on detect_tech_stack catching the project).+ aspnet_in_stack = any(+ token in stack_lower+ for token in ("aspnet", "asp.net", "aspnetcore", "asp.net core")+ )+ if aspnet_in_stack or _has_aspnet_imports(parsed_files):+ count += _add_aspnet_edges(graph, parsed_files, path_set)+return count@@ -190,3 +200,141 @@ def _add_flask_edges(if target and target in path_set and _add_edge_if_new(graph, path, target):count += 1return count+++# ---------------------------------------------------------------------------+# ASP.NET / .NET framework edges+# ---------------------------------------------------------------------------++# A class becomes a controller when it is annotated [ApiController] OR its+# class name ends in "Controller" (the MVC discovery convention). The first+# is preferred — it produces zero false positives.+_ASPNET_CONTROLLER_ATTR_RE = re.compile(r"\[\s*ApiController\b")+_ASPNET_ROUTE_RE = re.compile(r"\[\s*(?:Http(?:Get|Post|Put|Delete|Patch|Options|Head)|Route)\b")+_ASPNET_MAP_CALL_RE = re.compile(+ r"\.\s*Map(?:Get|Post|Put|Delete|Patch|Controllers|Hub|GrpcService|Razor|Fallback)\s*[<(]"+)+_ASPNET_USE_MIDDLEWARE_RE = re.compile(r"\.\s*UseMiddleware\s*<\s*(\w+)")+_DBCONTEXT_DECL_RE = re.compile(r"class\s+\w+\s*:\s*[\w.<>,\s]*\bDbContext\b")+_DBSET_RE = re.compile(r"\bDbSet\s*<\s*([A-Z]\w*)\s*>")+++def _has_aspnet_imports(parsed_files: dict[str, Any]) -> bool:+ """True if any parsed file imports Microsoft.AspNetCore.* — cheap signal."""+ for parsed in parsed_files.values():+ if parsed.file_info.language != "csharp":+ continue+ for imp in parsed.imports:+ if imp.module_path.startswith("Microsoft.AspNetCore"):+ return True+ return False+++def _read_cs_text(parsed: Any) -> str:+ try:+ return Path(parsed.file_info.abs_path).read_text(encoding="utf-8-sig", errors="ignore")+ except OSError:+ return ""+++def _add_aspnet_edges(+ graph: nx.DiGraph,+ parsed_files: dict[str, Any],+ path_set: set[str],+) -> int:+ """Add edges representing ASP.NET wiring.++ Three independent signal sources are merged:++ 1. Application entry point (``Program.cs``/``Startup.cs``) → every+ controller file. ``MapControllers()`` is the discovery anchor;+ individual controllers are not statically referenced from+ ``Program.cs`` but the framework wires them at runtime.++ 2. Application entry point → handler files for any ``app.MapGet(...)``+ / ``MapPost(...)`` minimal API call. We can't resolve the handler+ expression statically, so we approximate by linking to every file+ whose class is named in the handler argument (heuristic only).++ 3. ``DbContext`` subclasses → files declaring the entity types named+ in their ``DbSet<T>`` properties. This surfaces EF Core's implicit+ persistence model wiring that no static import edge captures.++ Returns the number of edges added.+ """+ count = 0+ cs_files = [+ (path, parsed)+ for path, parsed in parsed_files.items()+ if parsed.file_info.language == "csharp" and path in path_set+ ]+ if not cs_files:+ return 0++ # ---- 1. Discover controllers and entry points ----+ controllers: list[str] = []+ entry_points: list[str] = []+ dbcontext_files: list[tuple[str, str]] = [] # (path, source)+ type_decl_to_file: dict[str, str] = {} # ClassName -> defining file path++ for path, parsed in cs_files:+ # Index every named class/struct/record this file declares so the+ # DbSet<T> step can resolve targets without re-parsing.+ for sym in parsed.symbols:+ if sym.kind in ("class", "struct", "record"):+ # Last-write wins is fine — duplicates are rare in well-formed code.+ type_decl_to_file[sym.name] = path++ text = _read_cs_text(parsed)+ if not text:+ continue+ if _ASPNET_CONTROLLER_ATTR_RE.search(text) or path.endswith("Controller.cs"):+ controllers.append(path)+ name = Path(path).name+ if name in ("Program.cs", "Startup.cs"):+ entry_points.append(path)+ if _DBCONTEXT_DECL_RE.search(text):+ dbcontext_files.append((path, text))++ # ---- 2. Entry point → controllers (MapControllers / UseEndpoints) ----+ for entry in entry_points:+ for ctrl in controllers:+ if ctrl == entry:+ continue+ if _add_edge_if_new(graph, entry, ctrl):+ count += 1++ # ---- 3. Entry point → file containing handler class referenced in MapXxx ----+ handler_arg_re = re.compile(+ r"\.\s*Map(?:Get|Post|Put|Delete|Patch)\s*\(\s*[\"'][^\"']+[\"']\s*,\s*([A-Za-z_]\w*)"+ )+ for entry in entry_points:+ text = _read_cs_text(parsed_files[entry])+ if not text:+ continue+ for match in handler_arg_re.finditer(text):+ ident = match.group(1)+ target = type_decl_to_file.get(ident)+ if target and target in path_set and _add_edge_if_new(graph, entry, target):+ count += 1++ # ---- 4. UseMiddleware<T>() ----+ middleware_re = _ASPNET_USE_MIDDLEWARE_RE+ for entry in entry_points:+ text = _read_cs_text(parsed_files[entry])+ if not text:+ continue+ for match in middleware_re.finditer(text):+ target = type_decl_to_file.get(match.group(1))+ if target and target in path_set and _add_edge_if_new(graph, entry, target):+ count += 1++ # ---- 5. DbContext → DbSet<T> entity files ----+ for db_path, db_text in dbcontext_files:+ for match in _DBSET_RE.finditer(db_text):+ entity = match.group(1)+ target = type_decl_to_file.get(entity)+ if target and target in path_set and _add_edge_if_new(graph, db_path, target):+ count += 1++ return countdiff --git a/packages/core/src/repowise/core/ingestion/languages/registry.py b/packages/core/src/repowise/core/ingestion/languages/registry.pyindex 933b904b0..8fe9d92cf 100644--- a/packages/core/src/repowise/core/ingestion/languages/registry.py+++ b/packages/core/src/repowise/core/ingestion/languages/registry.py@@ -677,8 +677,31 @@ _SPECS: tuple[LanguageSpec, ...] = (grammar_package="tree_sitter_c_sharp",scm_file="csharp.scm",heritage_node_types=frozenset(- {"class_declaration", "interface_declaration", "struct_declaration"}+ {+ "class_declaration",+ "interface_declaration",+ "struct_declaration",+ "record_declaration",+ }+ ),+ entry_point_patterns=("Program.cs", "Startup.cs"),+ manifest_files=(+ "Directory.Build.props",+ "Directory.Build.targets",+ "Directory.Packages.props",+ "global.json",+ "nuget.config",+ "NuGet.Config",+ ),+ lock_files=("packages.lock.json",),+ generated_suffixes=(+ ".g.cs",+ ".Designer.cs",+ ".AssemblyInfo.cs",+ ".AssemblyAttributes.cs",+ ".g.i.cs",),+ blocked_dirs=("bin", "obj", ".vs", "TestResults", "packages"),builtin_calls=frozenset({"Console",diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.pyindex ca7dc242b..857ca410a 100644--- a/packages/core/src/repowise/core/ingestion/models.py+++ b/packages/core/src/repowise/core/ingestion/models.py@@ -168,6 +168,8 @@ class NamedBinding:exported_name: str | None # original name in source (None for module aliases)source_file: str | None # resolved file path (populated during graph build)is_module_alias: bool = False # True for "import x" / "import * as ns"+ is_global: bool = False # C# `global using` — applies to every file in the project+ is_static_import: bool = False # C# `using static` / Java static import — pulls members@dataclassdiff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.pyindex fde0f2fac..b9d15da6c 100644--- a/packages/core/src/repowise/core/ingestion/parser.py+++ b/packages/core/src/repowise/core/ingestion/parser.py@@ -351,16 +351,32 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {"interface_declaration": "interface","struct_declaration": "struct","enum_declaration": "enum",+ "enum_member_declaration": "variable","method_declaration": "method","constructor_declaration": "function","property_declaration": "variable",+ "field_declaration": "variable",+ "record_declaration": "class",+ "delegate_declaration": "function",+ "event_declaration": "variable",+ "event_field_declaration": "variable",+ "namespace_declaration": "module",+ "file_scoped_namespace_declaration": "module",},- import_node_types=["using_directive"],+ import_node_types=["using_directive", "global_using_directive"],export_node_types=[],visibility_fn=csharp_visibility,parent_extraction="nesting",parent_class_types=frozenset(- {"class_declaration", "interface_declaration", "struct_declaration", "enum_declaration"}+ {+ "class_declaration",+ "interface_declaration",+ "struct_declaration",+ "enum_declaration",+ "record_declaration",+ "namespace_declaration",+ "file_scoped_namespace_declaration",+ }),entry_point_patterns=["Program.cs", "Startup.cs"],),diff --git a/packages/core/src/repowise/core/ingestion/queries/csharp.scm b/packages/core/src/repowise/core/ingestion/queries/csharp.scmindex 38b347c56..209c09906 100644--- a/packages/core/src/repowise/core/ingestion/queries/csharp.scm+++ b/packages/core/src/repowise/core/ingestion/queries/csharp.scm@@ -44,6 +44,36 @@name: (identifier) @symbol.name) @symbol.def+(record_declaration+ (modifier) @symbol.modifiers+ name: (identifier) @symbol.name+) @symbol.def++(delegate_declaration+ (modifier) @symbol.modifiers+ name: (identifier) @symbol.name+ parameters: (parameter_list) @symbol.params+) @symbol.def++(event_declaration+ (modifier) @symbol.modifiers+ name: (identifier) @symbol.name+) @symbol.def++(event_field_declaration+ (modifier) @symbol.modifiers+ (variable_declaration+ (variable_declarator+ name: (identifier) @symbol.name))+) @symbol.def++(field_declaration+ (modifier) @symbol.modifiers+ (variable_declaration+ (variable_declarator+ name: (identifier) @symbol.name))+) @symbol.def+; ---------------------------------------------------------------------------; Symbols — fallback without modifiers; ---------------------------------------------------------------------------@@ -78,6 +108,59 @@name: (identifier) @symbol.name) @symbol.def+(record_declaration+ name: (identifier) @symbol.name+) @symbol.def++(delegate_declaration+ name: (identifier) @symbol.name+ parameters: (parameter_list) @symbol.params+) @symbol.def++(event_declaration+ name: (identifier) @symbol.name+) @symbol.def++(event_field_declaration+ (variable_declaration+ (variable_declarator+ name: (identifier) @symbol.name))+) @symbol.def++(field_declaration+ (variable_declaration+ (variable_declarator+ name: (identifier) @symbol.name))+) @symbol.def++; ---------------------------------------------------------------------------+; Namespaces (block + file-scoped C# 10+)+; ---------------------------------------------------------------------------++(namespace_declaration+ name: (qualified_name) @symbol.name+) @symbol.def++(namespace_declaration+ name: (identifier) @symbol.name+) @symbol.def++(file_scoped_namespace_declaration+ name: (qualified_name) @symbol.name+) @symbol.def++(file_scoped_namespace_declaration+ name: (identifier) @symbol.name+) @symbol.def++; ---------------------------------------------------------------------------+; Enum members+; ---------------------------------------------------------------------------++(enum_member_declaration+ name: (identifier) @symbol.name+) @symbol.def+; ---------------------------------------------------------------------------; Imports (using directives); ---------------------------------------------------------------------------diff --git a/packages/core/src/repowise/core/ingestion/resolvers/csharp.py b/packages/core/src/repowise/core/ingestion/resolvers/csharp.pyindex 38a35a6be..29c202938 100644--- a/packages/core/src/repowise/core/ingestion/resolvers/csharp.py+++ b/packages/core/src/repowise/core/ingestion/resolvers/csharp.py@@ -1,25 +1,123 @@-"""C# import resolution."""+"""C# import resolution.++Resolution algorithm (in priority order):++1. Build (and cache) a ``DotNetProjectIndex`` for the repo. This parses+ every ``.csproj`` and ``.sln``, builds a namespace → file map, and+ collects implicit + global usings per project.++2. Locate the project enclosing the importer file. If unknown, fall back+ to the legacy stem-match resolver — that handles the loose collection+ of .cs files repos that have no .csproj at all.++3. Look up the ``using`` namespace in the namespace map:+ a. Prefer files inside the same project.+ b. Then files inside any directly-referenced project (ProjectReference).+ c. Otherwise pick the first match anywhere in the repo (rare —+ a .cs file outside any project).++4. If no match is found and the namespace prefix matches a declared+ ``<PackageReference>``, register an external NuGet node.++5. Final fallback: register a generic external node so the using is+ visible in the graph even if unresolvable.++The legacy stem-match path is preserved so repos without .csproj files+keep working.+"""from __future__ import annotations+from pathlib import Path+from .context import ResolverContext+from .dotnet import get_or_build_index++def _to_repo_relative(abs_path: Path, repo_path: Path) -> str | None:+ """Return *abs_path* relative to *repo_path* in posix form, or None."""+ try:+ return abs_path.resolve().relative_to(repo_path.resolve()).as_posix()+ except ValueError:+ return None-def resolve_csharp_import(module_path: str, importer_path: str, ctx: ResolverContext) -> str | None:- """Resolve a C# using directive to a repo-relative file path."""++def _legacy_stem_resolve(+ module_path: str, ctx: ResolverContext+) -> str | None:+ """Original 26-line resolver — used when no project index is available."""parts = module_path.split(".")local = parts[-1]-- # Try stem lookup on the last namespace componentresult = ctx.stem_lookup(local.lower())if result and result.endswith(".cs"):return result-- # Try matching namespace components as directory pathif len(parts) > 1:dir_suffix = "/".join(parts)for p in ctx.path_set:if p.endswith(".cs") and dir_suffix.lower() in p.lower():return p+ return None+++def _matches_package_prefix(module_path: str, packages: set[str]) -> bool:+ """True if *module_path* equals or is a child namespace of any package id."""+ for pkg in packages:+ if module_path == pkg or module_path.startswith(pkg + "."):+ return True+ return False+++def resolve_csharp_import(+ module_path: str, importer_path: str, ctx: ResolverContext+) -> str | None:+ """Resolve a C# using directive to a repo-relative file path or external key."""+ index = get_or_build_index(ctx)+ if index is None or not ctx.repo_path:+ # No repo path — fall back to stem-match only.+ legacy = _legacy_stem_resolve(module_path, ctx)+ return legacy if legacy else ctx.add_external_node(module_path)++ # Locate the importer's project (if any).+ importer_abs = (ctx.repo_path / importer_path).resolve()+ importer_proj = index.project_for_file(importer_abs)++ candidates = index.files_for_namespace(module_path)++ if candidates:+ # Rank: same project, then referenced projects, then anywhere.+ same_project: list[Path] = []+ referenced: list[Path] = []+ other: list[Path] = []++ if importer_proj is not None:+ ref_csprojs = index.referenced_projects(importer_proj.path)+ for cand in candidates:+ cand_proj_path = index.file_to_project.get(cand)+ if cand_proj_path == importer_proj.path:+ same_project.append(cand)+ elif cand_proj_path in ref_csprojs:+ referenced.append(cand)+ else:+ other.append(cand)+ ordered = same_project or referenced or other+ else:+ ordered = candidates++ chosen = ordered[0]+ rel = _to_repo_relative(chosen, ctx.repo_path)+ if rel and rel in ctx.path_set:+ return rel++ # No file declares this namespace — could be NuGet or a sibling project's+ # public API surface. If a package reference matches, mark external NuGet.+ if importer_proj is not None:+ pkgs = index.package_refs.get(importer_proj.path, set())+ if _matches_package_prefix(module_path, pkgs):+ return ctx.add_external_node(f"nuget:{module_path}")++ # Last resort: legacy stem-match (catches repos with no .csproj).+ legacy = _legacy_stem_resolve(module_path, ctx)+ if legacy:+ return legacyreturn ctx.add_external_node(module_path)diff --git a/packages/core/src/repowise/core/ingestion/resolvers/dotnet/__init__.py b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/__init__.pynew file mode 100644index 000000000..73b7dda5b--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/__init__.py@@ -0,0 +1,28 @@+"""MSBuild / .sln aware resolution helpers for C# / .NET.++The ``DotNetProjectIndex`` is the entry point — it walks a repo once,+parses every ``.csproj`` and ``.sln``, builds a namespace → file map,+collects implicit/global usings, and exposes lookup helpers used by+``resolvers/csharp.py``.++Construction is lazy and idempotent: the index is built on first access+and cached on the ``ResolverContext`` for the lifetime of one+``GraphBuilder.build()`` invocation.+"""++from __future__ import annotations++from .index import DotNetProjectIndex, get_or_build_index+from .msbuild import MSBuildProject, parse_csproj+from .namespace_map import build_namespace_map+from .solution import SolutionEntry, parse_sln++__all__ = [+ "DotNetProjectIndex",+ "MSBuildProject",+ "SolutionEntry",+ "build_namespace_map",+ "get_or_build_index",+ "parse_csproj",+ "parse_sln",+]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.pynew file mode 100644index 000000000..58843d430--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/global_usings.py@@ -0,0 +1,82 @@+"""Collect implicit + global using namespaces per MSBuild project.++C# 10 introduced ``global using`` directives that apply to every file in+the compilation unit. The .NET 6 SDK auto-injects a set of common+namespaces when ``<ImplicitUsings>enable</ImplicitUsings>`` is set in the+.csproj. Both must be honoured for accurate import resolution.+"""++from __future__ import annotations++import re+from pathlib import Path++# Default ImplicitUsings set for SDK ``Microsoft.NET.Sdk`` projects.+# Source: dotnet/sdk repo, Sdks/Microsoft.NET.Sdk/targets/Microsoft.NET.Sdk.ImplicitNamespaceImports.props+_DEFAULT_IMPLICIT_USINGS: frozenset[str] = frozenset(+ {+ "System",+ "System.Collections.Generic",+ "System.IO",+ "System.Linq",+ "System.Net.Http",+ "System.Threading",+ "System.Threading.Tasks",+ }+)++# Web SDK adds these on top of the defaults.+_WEB_IMPLICIT_USINGS: frozenset[str] = frozenset(+ {+ "System.Net.Http.Json",+ "Microsoft.AspNetCore.Builder",+ "Microsoft.AspNetCore.Hosting",+ "Microsoft.AspNetCore.Http",+ "Microsoft.AspNetCore.Routing",+ "Microsoft.Extensions.Configuration",+ "Microsoft.Extensions.DependencyInjection",+ "Microsoft.Extensions.Hosting",+ "Microsoft.Extensions.Logging",+ }+)+++_GLOBAL_USING_RE = re.compile(+ r"^\s*global\s+using(?:\s+static)?\s+(?:[A-Za-z_]\w*\s*=\s*)?([A-Za-z_][\w.]*)\s*;",+ re.MULTILINE,+)+++def scan_global_usings(cs_text: str) -> list[str]:+ """Return every namespace target of a ``global using`` line in *cs_text*."""+ return [m.group(1) for m in _GLOBAL_USING_RE.finditer(cs_text)]+++def collect_project_global_usings(+ project_dir: Path, implicit_usings: bool, sdk_is_web: bool = False+) -> set[str]:+ """Walk *project_dir* for global using sources and return the merged set.++ Sources merged:+ - Default ImplicitUsings set (when enabled)+ - 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+ """+ result: set[str] = set()+ if implicit_usings:+ result.update(_DEFAULT_IMPLICIT_USINGS)+ if sdk_is_web:+ result.update(_WEB_IMPLICIT_USINGS)++ 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):+ continue+ try:+ text = cs_path.read_text(encoding="utf-8-sig", errors="replace")+ except OSError:+ continue+ result.update(scan_global_usings(text))++ return resultdiff --git a/packages/core/src/repowise/core/ingestion/resolvers/dotnet/index.py b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/index.pynew file mode 100644index 000000000..1c5a1ba26--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/index.py@@ -0,0 +1,159 @@+"""Repo-scoped .NET project index — built once per resolver run, cached on the context."""++from __future__ import annotations++from dataclasses import dataclass, field+from pathlib import Path+from typing import TYPE_CHECKING++import structlog++from .global_usings import collect_project_global_usings+from .msbuild import MSBuildProject, find_csproj_files, find_directory_build_props, parse_csproj+from .namespace_map import build_namespace_map+from .solution import find_sln_files, parse_sln++if TYPE_CHECKING:+ from ..context import ResolverContext++log = structlog.get_logger(__name__)+++@dataclass+class DotNetProjectIndex:+ """Cached view of every .NET project in a single repo."""++ repo_path: Path+ projects: dict[Path, MSBuildProject] = field(default_factory=dict)+ """Keyed by absolute .csproj path."""++ namespace_map: dict[str, list[Path]] = field(default_factory=dict)+ """Maps a fully-qualified namespace to the set of .cs files declaring it."""++ project_globals: dict[Path, set[str]] = field(default_factory=dict)+ """Maps a project's directory → global+implicit using namespaces."""++ file_to_project: dict[Path, Path] = field(default_factory=dict)+ """Maps a .cs file's absolute path → enclosing project's .csproj path."""++ project_refs_by_proj: dict[Path, set[Path]] = field(default_factory=dict)+ """Maps a .csproj path → set of referenced .csproj paths (transitive=False)."""++ package_refs: dict[Path, set[str]] = field(default_factory=dict)+ """Maps a .csproj path → declared NuGet package ids."""++ sln_paths: list[Path] = field(default_factory=list)++ # ------------------------------------------------------------------+ # Lookups+ # ------------------------------------------------------------------++ def project_for_file(self, file_abs: Path) -> MSBuildProject | None:+ """Return the project enclosing *file_abs*, or None."""+ csproj = self.file_to_project.get(file_abs.resolve())+ return self.projects.get(csproj) if csproj else None++ def referenced_projects(self, csproj: Path) -> set[Path]:+ """Return the direct ProjectReference set for *csproj*."""+ return self.project_refs_by_proj.get(csproj, set())++ def files_for_namespace(self, ns: str) -> list[Path]:+ return self.namespace_map.get(ns, [])++ def globals_for_project(self, csproj: Path) -> set[str]:+ proj = self.projects.get(csproj)+ if not proj:+ return set()+ return self.project_globals.get(proj.project_dir, set())++ def package_for(self, csproj: Path, package_id: str) -> bool:+ 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"}+ out: list[Path] = []+ for cs in project_dir.rglob("*.cs"):+ if any(part in skip for part in cs.parts):+ continue+ out.append(cs.resolve())+ return out+++def build_index(repo_path: Path) -> DotNetProjectIndex:+ """Walk *repo_path* and construct a fully-populated DotNetProjectIndex."""+ repo_path = repo_path.resolve()+ index = DotNetProjectIndex(repo_path=repo_path)++ # ---- 1. Parse every .csproj ----+ for csproj_path in find_csproj_files(repo_path):+ proj = parse_csproj(csproj_path)+ if proj is None:+ continue+ index.projects[proj.path] = proj+ index.project_refs_by_proj[proj.path] = set(proj.project_references)+ index.package_refs[proj.path] = set(proj.package_references)++ # ---- 2. Walk .sln files (informational; surfaces orphaned .csprojs) ----+ index.sln_paths = find_sln_files(repo_path)+ for sln in index.sln_paths:+ for entry in parse_sln(sln):+ if entry.csproj not in index.projects:+ # Solution references a .csproj we didn't pick up — try parsing it.+ proj = parse_csproj(entry.csproj)+ if proj is not None:+ index.projects[proj.path] = proj+ index.project_refs_by_proj.setdefault(proj.path, set()).update(+ proj.project_references+ )+ 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 = build_namespace_map(all_cs_files)++ # ---- 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.+ sdk_is_web = any(+ 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+ )+ # Honour <Using Include="X"/> ItemGroup entries on top of file scans.+ globals_set.update(proj.project_usings)+ index.project_globals[proj.project_dir] = globals_set++ log.info(+ "DotNetProjectIndex built",+ repo=str(repo_path),+ projects=len(index.projects),+ namespaces=len(index.namespace_map),+ sln=len(index.sln_paths),+ )+ return index+++# Stash key on the ResolverContext (reuses a generic cache slot to avoid+# adding a typed field for every language plugin).+_INDEX_KEY = "_dotnet_index"+++def get_or_build_index(ctx: "ResolverContext") -> DotNetProjectIndex | None:+ """Return the cached DotNetProjectIndex, building it on first access."""+ if not ctx.repo_path:+ return None+ cached = getattr(ctx, _INDEX_KEY, None)+ if cached is not None:+ return cached+ index = build_index(ctx.repo_path)+ setattr(ctx, _INDEX_KEY, index)+ return indexdiff --git a/packages/core/src/repowise/core/ingestion/resolvers/dotnet/msbuild.py b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/msbuild.pynew file mode 100644index 000000000..ed849e6e2--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/msbuild.py@@ -0,0 +1,119 @@+"""Parse MSBuild project files (.csproj, Directory.Build.props/targets).++Only the fields repowise actually uses are extracted: ProjectReference,+PackageReference, RootNamespace, AssemblyName, ImplicitUsings, and+project-level <Using Include=...> items. The parser tolerates both+SDK-style and legacy XML (``<Project ToolsVersion="...">``).+"""++from __future__ import annotations++from dataclasses import dataclass, field+from pathlib import Path+from xml.etree import ElementTree as ET++import structlog++log = structlog.get_logger(__name__)+++@dataclass+class MSBuildProject:+ """Parsed MSBuild project file."""++ path: Path # absolute path to the .csproj+ project_dir: Path # directory containing the .csproj+ root_namespace: str | None = None+ assembly_name: str | None = None+ implicit_usings: bool = False+ project_references: list[Path] = field(default_factory=list) # absolute paths to referenced .csproj+ package_references: set[str] = field(default_factory=set) # NuGet package ids+ project_usings: set[str] = field(default_factory=set) # <Using Include="X"/> namespaces++ @property+ def name(self) -> str:+ """Display name — the .csproj filename without extension."""+ return self.path.stem+++# Strip XML namespace prefix from a tag — MSBuild docs say the namespace+# is optional in SDK-style projects but legacy projects use+# ``http://schemas.microsoft.com/developer/msbuild/2003``.+def _local(tag: str) -> str:+ return tag.split("}", 1)[1] if tag.startswith("{") else tag+++def _bool(value: str | None) -> bool:+ return (value or "").strip().lower() in ("true", "enable", "1")+++def parse_csproj(csproj_path: Path) -> MSBuildProject | None:+ """Parse a single .csproj file. Returns None on parse failure."""+ try:+ tree = ET.parse(csproj_path)+ except (ET.ParseError, OSError) as exc:+ log.debug("Failed to parse csproj", path=str(csproj_path), error=str(exc))+ return None++ project = MSBuildProject(path=csproj_path.resolve(), project_dir=csproj_path.parent.resolve())+ root = tree.getroot()++ for elem in root.iter():+ tag = _local(elem.tag)++ if tag == "RootNamespace" and elem.text:+ project.root_namespace = elem.text.strip()+ elif tag == "AssemblyName" and elem.text:+ project.assembly_name = elem.text.strip()+ elif tag == "ImplicitUsings" and elem.text:+ project.implicit_usings = _bool(elem.text)+ elif tag == "ProjectReference":+ include = elem.get("Include")+ if include:+ # ProjectReference paths use Windows-style backslashes by+ # convention; normalise and resolve relative to the .csproj.+ rel = include.replace("\\", "/")+ target = (project.project_dir / rel).resolve()+ project.project_references.append(target)+ elif tag == "PackageReference":+ pkg = elem.get("Include")+ if pkg:+ project.package_references.add(pkg.strip())+ elif tag == "Using":+ ns = elem.get("Include")+ if ns:+ project.project_usings.add(ns.strip())++ return project+++def find_csproj_files(repo_path: Path) -> list[Path]:+ """Return all .csproj files under *repo_path*, skipping bin/obj output."""+ skip = {"bin", "obj", ".vs", "node_modules", ".git", "packages", "TestResults"}+ out: list[Path] = []+ for csproj in repo_path.rglob("*.csproj"):+ if any(part in skip for part in csproj.parts):+ continue+ out.append(csproj)+ return out+++def find_directory_build_props(start: Path, repo_root: Path) -> list[Path]:+ """Walk from *start* up to *repo_root* collecting Directory.Build.props.++ The first match closer to start "wins" but MSBuild semantics merge them+ bottom-up. Repowise just collects them so the resolver can union the+ implicit-using flags and project usings.+ """+ out: list[Path] = []+ cur = start.resolve()+ repo_root = repo_root.resolve()+ while True:+ for name in ("Directory.Build.props", "Directory.Build.targets", "Directory.Packages.props"):+ cand = cur / name+ if cand.exists():+ out.append(cand)+ if cur == repo_root or cur.parent == cur:+ break+ cur = cur.parent+ return outdiff --git a/packages/core/src/repowise/core/ingestion/resolvers/dotnet/namespace_map.py b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/namespace_map.pynew file mode 100644index 000000000..eb1ee1d86--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/namespace_map.py@@ -0,0 +1,48 @@+"""Build a namespace → file mapping by scanning .cs files for namespace declarations.++We use a regex 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+).+"""++from __future__ import annotations++import re+from pathlib import Path++# `namespace Foo.Bar.Baz {` (block-form)+# `namespace Foo.Bar.Baz;` (file-scoped, C# 10+)+_NAMESPACE_RE = re.compile(+ r"^\s*namespace\s+([A-Za-z_][\w.]*)\s*[;{]",+ re.MULTILINE,+)+++def declared_namespaces(cs_text: str) -> list[str]:+ """Return every namespace declared in *cs_text*, in source order.++ A single .cs file may declare multiple namespaces (rare but legal).+ Duplicates are preserved so callers can count them if they care.+ """+ 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.++ Files that fail to read or declare no namespace are skipped silently.+ """+ out: 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()+ for ns in declared_namespaces(text):+ if ns in seen:+ continue+ seen.add(ns)+ out.setdefault(ns, []).append(path)+ return outdiff --git a/packages/core/src/repowise/core/ingestion/resolvers/dotnet/solution.py b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/solution.pynew file mode 100644index 000000000..b1005488b--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/solution.py@@ -0,0 +1,66 @@+"""Parse Visual Studio .sln solution files.++The .sln format is line-oriented and not XML. Each project is declared as::++ Project("{<type-guid>}") = "Name", "relative\\path\\Name.csproj", "{<proj-guid>}"++Solution folders use a different type GUID and are skipped — repowise only+cares about real project entries that point to a .csproj on disk.+"""++from __future__ import annotations++import re+from dataclasses import dataclass+from pathlib import Path++import structlog++log = structlog.get_logger(__name__)++# Project("{TYPE}") = "Name", "rel\path.csproj", "{GUID}"+_PROJECT_RE = re.compile(+ r'^Project\("\{([^}]+)\}"\)\s*=\s*"([^"]+)"\s*,\s*"([^"]+)"\s*,\s*"\{([^}]+)\}"',+ re.MULTILINE,+)++# Solution-folder type GUID — these have no .csproj and must be skipped.+_FOLDER_TYPE_GUID = "2150E333-8FDC-42A3-9474-1A3956D46DE8"+++@dataclass(frozen=True)+class SolutionEntry:+ name: str+ csproj: Path # absolute+ project_guid: str+++def parse_sln(sln_path: Path) -> list[SolutionEntry]:+ """Return one SolutionEntry per .csproj declared in *sln_path*."""+ try:+ text = sln_path.read_text(encoding="utf-8-sig", errors="replace")+ except OSError as exc:+ log.debug("Failed to read sln", path=str(sln_path), error=str(exc))+ return []++ sln_dir = sln_path.parent+ out: list[SolutionEntry] = []+ for match in _PROJECT_RE.finditer(text):+ type_guid, name, rel_path, proj_guid = match.groups()+ if type_guid.upper() == _FOLDER_TYPE_GUID:+ continue+ if not rel_path.lower().endswith(".csproj"):+ continue+ csproj = (sln_dir / rel_path.replace("\\", "/")).resolve()+ out.append(SolutionEntry(name=name, csproj=csproj, project_guid=proj_guid))+ return out+++def find_sln_files(repo_path: Path) -> list[Path]:+ skip = {".git", "node_modules", "bin", "obj"}+ out: list[Path] = []+ for sln in repo_path.rglob("*.sln"):+ if any(part in skip for part in sln.parts):+ continue+ out.append(sln)+ return outdiff --git a/packages/core/src/repowise/core/workspace/cross_repo.py b/packages/core/src/repowise/core/workspace/cross_repo.pyindex aed0915f0..39dad4a43 100644--- a/packages/core/src/repowise/core/workspace/cross_repo.py+++ b/packages/core/src/repowise/core/workspace/cross_repo.py@@ -500,6 +500,96 @@ def _scan_go_mod(return results+def _scan_csproj(+ repo_path: Path,+ repo_paths: dict[str, Path],+ alias: str,+) -> list[CrossRepoPackageDep]:+ """Scan every .csproj for cross-repo references.++ Two patterns are recognised:++ 1. ``<ProjectReference Include="..\\..\\OtherRepo\\Foo.csproj"/>`` — a+ relative path that resolves into a sibling indexed repo. Emits+ ``kind="dotnet_project_ref"``.++ 2. ``<PackageReference Include="MyOrg.SharedLib"/>`` whose package id+ matches a sibling repo's ``<AssemblyName>`` or ``.csproj`` filename.+ Emits ``kind="dotnet_nuget_internal"`` — the "internal NuGet+ feed" pattern enterprise teams use when their shared libs live+ in a separate repo.++ Skips ``bin``/``obj``/``packages``/``.vs``/``TestResults`` build outputs.+ """+ from xml.etree import ElementTree as ET++ results: list[CrossRepoPackageDep] = []+ skip = {"bin", "obj", ".vs", "packages", "node_modules", ".git", "TestResults"}++ # Pre-compute the assembly-name → repo-alias map so we can resolve+ # internal-NuGet references in a second pass.+ assembly_to_repo: dict[str, str] = {}+ for sib_alias, sib_path in repo_paths.items():+ for csproj in sib_path.rglob("*.csproj"):+ if any(part in skip for part in csproj.parts):+ continue+ try:+ tree = ET.parse(csproj)+ except (ET.ParseError, OSError):+ continue+ assembly_name = csproj.stem # default: filename minus extension+ for elem in tree.getroot().iter():+ tag = elem.tag.split("}", 1)[1] if elem.tag.startswith("{") else elem.tag+ if tag == "AssemblyName" and elem.text:+ assembly_name = elem.text.strip()+ break+ assembly_to_repo[assembly_name] = sib_alias++ for csproj in repo_path.rglob("*.csproj"):+ if any(part in skip for part in csproj.parts):+ continue+ try:+ tree = ET.parse(csproj)+ except (ET.ParseError, OSError):+ continue+ try:+ rel_manifest = csproj.relative_to(repo_path).as_posix()+ except ValueError:+ rel_manifest = csproj.name++ for elem in tree.getroot().iter():+ tag = elem.tag.split("}", 1)[1] if elem.tag.startswith("{") else elem.tag+ include = elem.get("Include") if elem.attrib else None+ if not include:+ continue+ if tag == "ProjectReference":+ rel = include.replace("\\", "/")+ target = _resolve_target_repo(rel, csproj.parent, repo_paths)+ if target and target != alias:+ results.append(+ CrossRepoPackageDep(+ source_repo=alias,+ target_repo=target,+ source_manifest=rel_manifest,+ kind="dotnet_project_ref",+ )+ )+ elif tag == "PackageReference":+ pkg = include.strip()+ target = assembly_to_repo.get(pkg)+ if target and target != alias:+ results.append(+ CrossRepoPackageDep(+ source_repo=alias,+ target_repo=target,+ source_manifest=rel_manifest,+ kind="dotnet_nuget_internal",+ )+ )++ return results++def detect_package_dependencies(repo_paths: dict[str, Path],) -> list[CrossRepoPackageDep]:@@ -508,7 +598,13 @@ def detect_package_dependencies(seen: set[tuple[str, str, str]] = set() # (source, target, kind)for alias, path in repo_paths.items():- for scanner in (_scan_package_json, _scan_pyproject_toml, _scan_cargo_toml, _scan_go_mod):+ for scanner in (+ _scan_package_json,+ _scan_pyproject_toml,+ _scan_cargo_toml,+ _scan_go_mod,+ _scan_csproj,+ ):for dep in scanner(path, repo_paths, alias):key = (dep.source_repo, dep.target_repo, dep.kind)if key not in seen:diff --git a/packages/core/src/repowise/core/workspace/extractors/grpc_extractor.py b/packages/core/src/repowise/core/workspace/extractors/grpc_extractor.pyindex e11b3da44..779c491d2 100644--- a/packages/core/src/repowise/core/workspace/extractors/grpc_extractor.py+++ b/packages/core/src/repowise/core/workspace/extractors/grpc_extractor.py@@ -51,7 +51,7 @@ _MAX_FILE_SIZE = 512 * 1024_PROTO_EXTENSIONS = _LANG_REGISTRY.extensions_for(["proto"])_SOURCE_EXTENSIONS = _LANG_REGISTRY.extensions_for(- ["go", "java", "python", "typescript", "javascript"]+ ["go", "java", "python", "typescript", "javascript", "csharp"])_ALL_EXTENSIONS = _PROTO_EXTENSIONS | _SOURCE_EXTENSIONS@@ -151,6 +151,19 @@ _PY_CONSUMER_RE = re.compile(r"(\w+)Stub\s*\(")# TypeScript providers: @GrpcMethod('AuthService', 'Login')_TS_PROVIDER_RE = re.compile(r"@GrpcMethod\s*\(\s*'(\w+)'\s*,\s*'(\w+)'\s*\)")+# C# / gRPC-dotnet providers: app.MapGrpcService<GreeterService>() — explicit+# service registration. The generated server-base class follows the+# convention `class Impl : ServiceName.ServiceNameBase` where ServiceName+# matches the .proto service name (e.g. `Greeter.GreeterBase`,+# `AuthService.AuthServiceBase`). We capture the prefix as the service id.+_CSHARP_GRPC_MAP_RE = re.compile(r"\.\s*MapGrpcService\s*<\s*(\w+)\s*>")+_CSHARP_GRPC_BASE_RE = re.compile(+ r"class\s+\w+\s*:\s*(?:[\w.]+\.)?(\w+?)\s*\.\s*\1Base\b"+)+# C# consumers: new AuthServiceClient(channel) / new GreeterClient(channel).+# The generated stub class always ends in "Client" and follows a `new` keyword.+_CSHARP_GRPC_CLIENT_RE = re.compile(r"\bnew\s+(\w+)Client\s*\(")+# ---------------------------------------------------------------------------# Extractor@@ -347,4 +360,59 @@ class GrpcExtractor:))+ # --- C# (gRPC-dotnet) ---+ elif suffix == ".cs":+ for m in _CSHARP_GRPC_MAP_RE.finditer(content):+ svc = m.group(1)+ contract_id = f"grpc::{svc}/*"+ contracts.append(+ Contract(+ repo=repo_alias,+ contract_id=contract_id,+ contract_type="grpc",+ role="provider",+ file_path=rel_path,+ symbol_name=f"cs:MapGrpcService<{svc}>",+ confidence=0.8,+ service=None,+ meta={"service": svc, "source": "csharp_mapgrpc"},+ )+ )++ for m in _CSHARP_GRPC_BASE_RE.finditer(content):+ svc = m.group(1)+ contract_id = f"grpc::{svc}/*"+ contracts.append(+ Contract(+ repo=repo_alias,+ contract_id=contract_id,+ contract_type="grpc",+ role="provider",+ file_path=rel_path,+ symbol_name=f"cs:extends {svc}.{svc}ServiceBase",+ confidence=0.8,+ service=None,+ meta={"service": svc, "source": "csharp_base"},+ )+ )++ for m in _CSHARP_GRPC_CLIENT_RE.finditer(content):+ svc = m.group(1)+ if svc.lower().startswith(("mock", "test", "fake", "http")):+ continue+ contract_id = f"grpc::{svc}/*"+ contracts.append(+ Contract(+ repo=repo_alias,+ contract_id=contract_id,+ contract_type="grpc",+ role="consumer",+ file_path=rel_path,+ symbol_name=f"cs:new {svc}Client",+ confidence=0.65,+ service=None,+ meta={"service": svc, "source": "csharp_client"},+ )+ )+return contractsdiff --git a/packages/core/src/repowise/core/workspace/extractors/http_extractor.py b/packages/core/src/repowise/core/workspace/extractors/http_extractor.pyindex eb789082f..4f34552f3 100644--- a/packages/core/src/repowise/core/workspace/extractors/http_extractor.py+++ b/packages/core/src/repowise/core/workspace/extractors/http_extractor.py@@ -49,10 +49,12 @@ _BLOCKED_DIRS = frozenset(_MAX_FILE_SIZE = 512 * 1024 # 512 KB_PROVIDER_EXTENSIONS = _LANG_REGISTRY.extensions_for(- ["python", "typescript", "javascript", "java", "php", "go"]+ ["python", "typescript", "javascript", "java", "php", "go", "csharp"])-_CONSUMER_EXTENSIONS = _LANG_REGISTRY.extensions_for(["python", "typescript", "javascript"])+_CONSUMER_EXTENSIONS = _LANG_REGISTRY.extensions_for(+ ["python", "typescript", "javascript", "csharp"]+)_ALL_EXTENSIONS = _PROVIDER_EXTENSIONS | _CONSUMER_EXTENSIONS@@ -75,7 +77,14 @@ def normalize_http_path(path: str) -> str:s = path.strip().split("?")[0].lower()if s != "/":s = s.rstrip("/")- # Unify Express :param+ # ASP.NET routes commonly omit the leading slash; add one so all+ # frameworks compare on equal footing.+ if s and not s.startswith("/") and not s.startswith("http"):+ s = "/" + s+ # ASP.NET route constraints: `{id:int}` / `{slug:regex(\d+)}` — strip the+ # ``:type`` portion so the next normalisation step doesn't double-wrap it.+ s = re.sub(r"(\{[a-z_][\w]*):[^}]+(\})", r"\1\2", s)+ # Unify Express :param (must run before {…} so it doesn't eat braces).s = re.sub(r":(\w+)", "{param}", s)# Unify Spring/FastAPI {name} → {param}s = re.sub(r"\{[^}]+\}", "{param}", s)@@ -132,12 +141,39 @@ _GO_ROUTE_RE = re.compile(rf"""\.({_METHODS_UPPER}|Handle|HandleFunc)\s*\(\s*['"]([^'"]+)['"]""",)+# ASP.NET attribute routing: [HttpGet("path")], [HttpPost("path")], etc.+# The leading bracket may be on its own line, so we anchor on the attribute name.+_ASPNET_METHOD_RE = re.compile(+ r"""\[\s*Http(Get|Post|Put|Delete|Patch)\s*\(\s*['"]([^'"]+)['"]""",+ re.IGNORECASE,+)++# Parameterless attribute: [HttpPost] / [HttpGet] — the route is the class+# prefix only. We capture an empty path that the prefix-stitcher will fill in.+_ASPNET_BARE_METHOD_RE = re.compile(+ r"""\[\s*Http(Get|Post|Put|Delete|Patch)\s*\]""",+ re.IGNORECASE,+)++# ASP.NET class-level prefix: [Route("api/users")] above an [ApiController] class.+_ASPNET_CLASS_ROUTE_RE = re.compile(+ r"""\[\s*Route\s*\(\s*['"]([^'"]+)['"]""",+)++# ASP.NET minimal API: app.MapGet("/users", ...) — same shape, different method names.+_ASPNET_MINIMAL_RE = re.compile(+ rf"""\.\s*Map({_METHODS})\s*\(\s*['"]([^'"]+)['"]""",+ re.IGNORECASE,+)+_PROVIDER_PATTERNS = [(_EXPRESS_RE, "express"),(_FASTAPI_RE, "fastapi"),(_SPRING_METHOD_RE, "spring"),(_LARAVEL_RE, "laravel"),(_GO_ROUTE_RE, "go"),+ (_ASPNET_METHOD_RE, "aspnet"),+ (_ASPNET_MINIMAL_RE, "aspnet-minimal"),]# ---------------------------------------------------------------------------@@ -165,6 +201,12 @@ _REQUESTS_RE = re.compile(re.IGNORECASE,)+# C# HttpClient: client.GetAsync("/api/users") / PostAsync / PutAsync / DeleteAsync+_HTTPCLIENT_RE = re.compile(+ rf"""\.\s*({_METHODS})Async\s*\(\s*['"]([^'"]+)['"]""",+ re.IGNORECASE,+)+# ---------------------------------------------------------------------------# Extractor@@ -223,6 +265,13 @@ class HttpExtractor:for cm in _SPRING_CLASS_RE.finditer(content):spring_class_mappings.append((cm.start(), cm.group(1).rstrip("/")))+ # ASP.NET: same prefix-stitching logic as Spring — [Route("api/users")]+ # above an [ApiController] class anchors the per-method prefixes.+ aspnet_class_mappings: list[tuple[int, str]] = []+ if suffix == ".cs":+ for cm in _ASPNET_CLASS_ROUTE_RE.finditer(content):+ aspnet_class_mappings.append((cm.start(), cm.group(1).rstrip("/")))+for pattern, framework in _PROVIDER_PATTERNS:for match in pattern.finditer(content):method_raw = match.group(1)@@ -248,6 +297,20 @@ class HttpExtractor:if spring_prefix:path_raw = spring_prefix + "/" + path_raw.lstrip("/")+ # Apply ASP.NET class-level prefix using the same nearest-+ # preceding rule. Skipped for the minimal-API pattern since+ # those are not inside controller classes.+ if framework == "aspnet" and aspnet_class_mappings:+ match_pos = match.start()+ cls_prefix = ""+ for pos, prefix in aspnet_class_mappings:+ if pos < match_pos:+ cls_prefix = prefix+ else:+ break+ if cls_prefix:+ path_raw = cls_prefix + "/" + path_raw.lstrip("/")+norm_path = normalize_http_path(path_raw)# Skip paths that look like template variables or empty@@ -275,6 +338,42 @@ class HttpExtractor:))+ # Bare ASP.NET attributes — `[HttpPost]` with no route arg.+ # The path is whichever class-level [Route("...")] precedes+ # the attribute. If no class route exists, we skip the+ # match — there's no useful path to record.+ if suffix == ".cs" and aspnet_class_mappings:+ for match in _ASPNET_BARE_METHOD_RE.finditer(content):+ method = match.group(1).upper()+ match_pos = match.start()+ cls_prefix = ""+ for pos, prefix in aspnet_class_mappings:+ if pos < match_pos:+ cls_prefix = prefix+ else:+ break+ if not cls_prefix:+ continue+ norm_path = normalize_http_path(cls_prefix)+ contract_id = f"http::{method}::{norm_path}"+ contracts.append(+ Contract(+ repo=repo_alias,+ contract_id=contract_id,+ contract_type="http",+ role="provider",+ file_path=rel_path,+ symbol_name=f"aspnet:{method} {cls_prefix}",+ confidence=0.85,+ service=None,+ meta={+ "method": method,+ "path": norm_path,+ "framework": "aspnet",+ },+ )+ )+# --- Consumers ---if suffix in _CONSUMER_EXTENSIONS:# fetch() with method@@ -342,6 +441,35 @@ class HttpExtractor:))+ # C# HttpClient (only run on .cs files to avoid false matches+ # against non-HTTP `*Async` methods like `WriteAsync`).+ if suffix == ".cs":+ for match in _HTTPCLIENT_RE.finditer(content):+ method = match.group(1).upper()+ url = match.group(2)+ if "/" not in url:+ continue # Avoid matching non-URL strings.+ path = _extract_path_from_url(url)+ norm_path = normalize_http_path(path)+ contract_id = f"http::{method}::{norm_path}"+ contracts.append(+ Contract(+ repo=repo_alias,+ contract_id=contract_id,+ contract_type="http",+ role="consumer",+ file_path=rel_path,+ symbol_name=f"httpclient:{method} {url}",+ confidence=0.70,+ service=None,+ meta={+ "method": method,+ "path": norm_path,+ "client": "httpclient",+ },+ )+ )+# requests / httpxfor match in _REQUESTS_RE.finditer(content):method = match.group(1).upper()diff --git a/tests/fixtures/dotnet_solution/Directory.Build.props b/tests/fixtures/dotnet_solution/Directory.Build.propsnew file mode 100644index 000000000..30d962d8d--- /dev/null+++ b/tests/fixtures/dotnet_solution/Directory.Build.props@@ -0,0 +1,7 @@+<Project>+ <PropertyGroup>+ <TargetFramework>net8.0</TargetFramework>+ <ImplicitUsings>enable</ImplicitUsings>+ <Nullable>enable</Nullable>+ </PropertyGroup>+</Project>diff --git a/tests/fixtures/dotnet_solution/MySolution.sln b/tests/fixtures/dotnet_solution/MySolution.slnnew file mode 100644index 000000000..cafa020c5--- /dev/null+++ b/tests/fixtures/dotnet_solution/MySolution.sln@@ -0,0 +1,12 @@+Microsoft Visual Studio Solution File, Format Version 12.00+# Visual Studio Version 17+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Api", "src\Api\Api.csproj", "{11111111-1111-1111-1111-111111111111}"+EndProject+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Domain", "src\Domain\Domain.csproj", "{22222222-2222-2222-2222-222222222222}"+EndProject+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Infrastructure", "src\Infrastructure\Infrastructure.csproj", "{33333333-3333-3333-3333-333333333333}"+EndProject+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{44444444-4444-4444-4444-444444444444}"+EndProject+Global+EndGlobaldiff --git a/tests/fixtures/dotnet_solution/global.json b/tests/fixtures/dotnet_solution/global.jsonnew file mode 100644index 000000000..5ce849551--- /dev/null+++ b/tests/fixtures/dotnet_solution/global.json@@ -0,0 +1,5 @@+{+ "sdk": {+ "version": "8.0.100"+ }+}diff --git a/tests/fixtures/dotnet_solution/src/Api/Api.csproj b/tests/fixtures/dotnet_solution/src/Api/Api.csprojnew file mode 100644index 000000000..50db8b4bf--- /dev/null+++ b/tests/fixtures/dotnet_solution/src/Api/Api.csproj@@ -0,0 +1,11 @@+<Project Sdk="Microsoft.NET.Sdk.Web">+ <PropertyGroup>+ <RootNamespace>Acme.Api</RootNamespace>+ <AssemblyName>Acme.Api</AssemblyName>+ </PropertyGroup>+ <ItemGroup>+ <ProjectReference Include="..\Domain\Domain.csproj" />+ <ProjectReference Include="..\Infrastructure\Infrastructure.csproj" />+ <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.0" />+ </ItemGroup>+</Project>diff --git a/tests/fixtures/dotnet_solution/src/Api/Controllers/UsersController.cs b/tests/fixtures/dotnet_solution/src/Api/Controllers/UsersController.csnew file mode 100644index 000000000..24faa7d0b--- /dev/null+++ b/tests/fixtures/dotnet_solution/src/Api/Controllers/UsersController.cs@@ -0,0 +1,26 @@+using Microsoft.AspNetCore.Mvc;+using Acme.Domain;++namespace Acme.Api;++[ApiController]+[Route("api/users")]+public class UsersController : ControllerBase+{+ private readonly IUserRepository _repo;+ public UsersController(IUserRepository repo) { _repo = repo; }++ [HttpGet("{email}")]+ public async Task<IActionResult> Get(string email)+ {+ var user = await _repo.FindAsync(email);+ return user is null ? NotFound() : Ok(user);+ }++ [HttpPost]+ public async Task<IActionResult> Create([FromBody] User user)+ {+ await _repo.AddAsync(user);+ return Created($"/api/users/{user.Email}", user);+ }+}diff --git a/tests/fixtures/dotnet_solution/src/Api/GlobalUsings.cs b/tests/fixtures/dotnet_solution/src/Api/GlobalUsings.csnew file mode 100644index 000000000..528147cb2--- /dev/null+++ b/tests/fixtures/dotnet_solution/src/Api/GlobalUsings.cs@@ -0,0 +1,3 @@+global using System;+global using System.Threading.Tasks;+global using Acme.Domain;diff --git a/tests/fixtures/dotnet_solution/src/Api/Program.cs b/tests/fixtures/dotnet_solution/src/Api/Program.csnew file mode 100644index 000000000..559f9520a--- /dev/null+++ b/tests/fixtures/dotnet_solution/src/Api/Program.cs@@ -0,0 +1,18 @@+using Acme.Domain;+using Acme.Infrastructure;+using Microsoft.AspNetCore.Builder;+using Microsoft.EntityFrameworkCore;+using Microsoft.Extensions.DependencyInjection;++var builder = WebApplication.CreateBuilder(args);++builder.Services.AddDbContext<AppDbContext>(opt => opt.UseInMemoryDatabase("test"));+builder.Services.AddScoped<IUserRepository, UserRepository>();+builder.Services.AddControllers();++var app = builder.Build();++app.MapControllers();+app.MapGet("/health", () => Results.Ok("alive"));++app.Run();diff --git a/tests/fixtures/dotnet_solution/src/Domain/Domain.csproj b/tests/fixtures/dotnet_solution/src/Domain/Domain.csprojnew file mode 100644index 000000000..d043209a2--- /dev/null+++ b/tests/fixtures/dotnet_solution/src/Domain/Domain.csproj@@ -0,0 +1,6 @@+<Project Sdk="Microsoft.NET.Sdk">+ <PropertyGroup>+ <RootNamespace>Acme.Domain</RootNamespace>+ <AssemblyName>Acme.Domain</AssemblyName>+ </PropertyGroup>+</Project>diff --git a/tests/fixtures/dotnet_solution/src/Domain/Entities/User.cs b/tests/fixtures/dotnet_solution/src/Domain/Entities/User.csnew file mode 100644index 000000000..2f7f885e4--- /dev/null+++ b/tests/fixtures/dotnet_solution/src/Domain/Entities/User.cs@@ -0,0 +1,12 @@+namespace Acme.Domain;++/// <summary>A user in the system.</summary>+public record User(string Name, string Email) : IAuditable+{+ public DateTime CreatedAt { get; init; } = DateTime.UtcNow;+}++public interface IAuditable+{+ DateTime CreatedAt { get; }+}diff --git a/tests/fixtures/dotnet_solution/src/Domain/Repositories/IUserRepository.cs b/tests/fixtures/dotnet_solution/src/Domain/Repositories/IUserRepository.csnew file mode 100644index 000000000..cc07ad645--- /dev/null+++ b/tests/fixtures/dotnet_solution/src/Domain/Repositories/IUserRepository.cs@@ -0,0 +1,7 @@+namespace Acme.Domain;++public interface IUserRepository+{+ Task<User?> FindAsync(string email);+ Task AddAsync(User user);+}diff --git a/tests/fixtures/dotnet_solution/src/Infrastructure/Infrastructure.csproj b/tests/fixtures/dotnet_solution/src/Infrastructure/Infrastructure.csprojnew file mode 100644index 000000000..301c9ad0c--- /dev/null+++ b/tests/fixtures/dotnet_solution/src/Infrastructure/Infrastructure.csproj@@ -0,0 +1,10 @@+<Project Sdk="Microsoft.NET.Sdk">+ <PropertyGroup>+ <RootNamespace>Acme.Infrastructure</RootNamespace>+ <AssemblyName>Acme.Infrastructure</AssemblyName>+ </PropertyGroup>+ <ItemGroup>+ <ProjectReference Include="..\Domain\Domain.csproj" />+ <PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.0" />+ </ItemGroup>+</Project>diff --git a/tests/fixtures/dotnet_solution/src/Infrastructure/Persistence/AppDbContext.cs b/tests/fixtures/dotnet_solution/src/Infrastructure/Persistence/AppDbContext.csnew file mode 100644index 000000000..28c9b6610--- /dev/null+++ b/tests/fixtures/dotnet_solution/src/Infrastructure/Persistence/AppDbContext.cs@@ -0,0 +1,11 @@+using Microsoft.EntityFrameworkCore;+using Acme.Domain;++namespace Acme.Infrastructure;++public class AppDbContext : DbContext+{+ public DbSet<User> Users { get; set; } = null!;++ public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }+}diff --git a/tests/fixtures/dotnet_solution/src/Infrastructure/Repositories/UserRepository.cs b/tests/fixtures/dotnet_solution/src/Infrastructure/Repositories/UserRepository.csnew file mode 100644index 000000000..f2fe8ccbd--- /dev/null+++ b/tests/fixtures/dotnet_solution/src/Infrastructure/Repositories/UserRepository.cs@@ -0,0 +1,19 @@+using Microsoft.EntityFrameworkCore;+using Acme.Domain;++namespace Acme.Infrastructure;++public class UserRepository : IUserRepository+{+ private readonly AppDbContext _db;+ public UserRepository(AppDbContext db) { _db = db; }++ public Task<User?> FindAsync(string email) =>+ _db.Users.FirstOrDefaultAsync(u => u.Email == email);++ public Task AddAsync(User user)+ {+ _db.Users.Add(user);+ return _db.SaveChangesAsync();+ }+}diff --git a/tests/fixtures/dotnet_workspace/api-service/src/Api/Api.csproj b/tests/fixtures/dotnet_workspace/api-service/src/Api/Api.csprojnew file mode 100644index 000000000..2b2b38c59--- /dev/null+++ b/tests/fixtures/dotnet_workspace/api-service/src/Api/Api.csproj@@ -0,0 +1,11 @@+<Project Sdk="Microsoft.NET.Sdk.Web">+ <PropertyGroup>+ <RootNamespace>Acme.Api</RootNamespace>+ <AssemblyName>Acme.Api</AssemblyName>+ <TargetFramework>net8.0</TargetFramework>+ </PropertyGroup>+ <ItemGroup>+ <ProjectReference Include="..\..\..\shared-libs\src\Common\Common.csproj" />+ <PackageReference Include="Acme.Telemetry" Version="2.1.0" />+ </ItemGroup>+</Project>diff --git a/tests/fixtures/dotnet_workspace/api-service/src/Api/Program.cs b/tests/fixtures/dotnet_workspace/api-service/src/Api/Program.csnew file mode 100644index 000000000..2333b1b0e--- /dev/null+++ b/tests/fixtures/dotnet_workspace/api-service/src/Api/Program.cs@@ -0,0 +1,6 @@+using Acme.Common;++var builder = WebApplication.CreateBuilder(args);+builder.Services.AddSharedServices();+var app = builder.Build();+app.Run();diff --git a/tests/fixtures/dotnet_workspace/shared-libs/src/Common/Common.csproj b/tests/fixtures/dotnet_workspace/shared-libs/src/Common/Common.csprojnew file mode 100644index 000000000..045a24b14--- /dev/null+++ b/tests/fixtures/dotnet_workspace/shared-libs/src/Common/Common.csproj@@ -0,0 +1,7 @@+<Project Sdk="Microsoft.NET.Sdk">+ <PropertyGroup>+ <RootNamespace>Acme.Common</RootNamespace>+ <AssemblyName>Acme.Common</AssemblyName>+ <TargetFramework>net8.0</TargetFramework>+ </PropertyGroup>+</Project>diff --git a/tests/fixtures/dotnet_workspace/shared-libs/src/Common/Telemetry.cs b/tests/fixtures/dotnet_workspace/shared-libs/src/Common/Telemetry.csnew file mode 100644index 000000000..f331d1d65--- /dev/null+++ b/tests/fixtures/dotnet_workspace/shared-libs/src/Common/Telemetry.cs@@ -0,0 +1,7 @@+namespace Acme.Common;++public static class TelemetryExtensions+{+ public static IServiceCollection AddSharedServices(this IServiceCollection services)+ => services;+}diff --git a/tests/fixtures/dotnet_workspace/telemetry-lib/src/Telemetry/Telemetry.csproj b/tests/fixtures/dotnet_workspace/telemetry-lib/src/Telemetry/Telemetry.csprojnew file mode 100644index 000000000..ca3fc2059--- /dev/null+++ b/tests/fixtures/dotnet_workspace/telemetry-lib/src/Telemetry/Telemetry.csproj@@ -0,0 +1,7 @@+<Project Sdk="Microsoft.NET.Sdk">+ <PropertyGroup>+ <RootNamespace>Acme.Telemetry</RootNamespace>+ <AssemblyName>Acme.Telemetry</AssemblyName>+ <TargetFramework>net8.0</TargetFramework>+ </PropertyGroup>+</Project>diff --git a/tests/integration/test_dotnet_solution.py b/tests/integration/test_dotnet_solution.pynew file mode 100644index 000000000..f29841f05--- /dev/null+++ b/tests/integration/test_dotnet_solution.py@@ -0,0 +1,150 @@+"""End-to-end integration test for the dotnet_solution fixture.++Runs the full FileTraverser → ASTParser → GraphBuilder pipeline against+the multi-project fixture under tests/fixtures/dotnet_solution and+verifies the key edges Batches 1-6 promise:++- All 3 projects (Api, Domain, Infrastructure) are discovered.+- Records / namespaces / DbContext / record-with-base-and-interface+ produce the expected symbols.+- ProjectReference relationships are reflected as import edges.+- ASP.NET framework edges run (Program.cs → controllers, DbContext+ → entity).+- Cross-repo workspace fixture detects ProjectReference and internal+ NuGet links across the two repos.+"""++from __future__ import annotations++from pathlib import Path++import pytest++DOTNET_SOLUTION = Path(__file__).parent.parent / "fixtures" / "dotnet_solution"+DOTNET_WORKSPACE = Path(__file__).parent.parent / "fixtures" / "dotnet_workspace"++[email protected](scope="module")+def ingest_solution():+ """Run the ingestion pipeline against the dotnet_solution fixture."""+ from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder++ traverser = FileTraverser(DOTNET_SOLUTION)+ parser = ASTParser()+ builder = GraphBuilder(repo_path=DOTNET_SOLUTION)++ parsed_list = []+ for file_info in traverser.traverse():+ source = Path(file_info.abs_path).read_bytes()+ parsed = parser.parse_file(file_info, source)+ builder.add_file(parsed)+ parsed_list.append(parsed)++ graph = builder.build()+ builder.add_framework_edges(tech_stack=["aspnet"])+ return {"parsed": parsed_list, "builder": builder, "graph": graph}+++class TestSolutionIngestion:+ def test_discovers_csharp_files(self, ingest_solution) -> None:+ cs_files = [p for p in ingest_solution["parsed"] if p.file_info.language == "csharp"]+ # Domain (User, IUserRepository), Infrastructure (AppDbContext,+ # UserRepository), Api (Program, GlobalUsings, UsersController) = 7+ assert len(cs_files) >= 6++ def test_records_captured(self, ingest_solution) -> None:+ names: set[str] = set()+ for p in ingest_solution["parsed"]:+ for s in p.symbols:+ names.add(s.name)+ assert "User" in names+ assert "IUserRepository" in names+ assert "UserRepository" in names+ assert "AppDbContext" in names+ assert "UsersController" in names++ def test_namespaces_captured(self, ingest_solution) -> None:+ modules: set[str] = set()+ for p in ingest_solution["parsed"]:+ for s in p.symbols:+ if s.kind == "module":+ modules.add(s.name)+ # File-scoped namespaces from each project+ assert any("Acme.Domain" in m or m == "Acme.Domain" for m in modules)+ assert any("Acme.Infrastructure" in m or m == "Acme.Infrastructure" for m in modules)+ assert any("Acme.Api" in m or m == "Acme.Api" for m in modules)++ def test_record_inherits_iauditable(self, ingest_solution) -> None:+ """`record User(...) : IAuditable` should produce an implements edge."""+ relations: list = []+ for p in ingest_solution["parsed"]:+ relations.extend(p.heritage)+ assert any(+ r.child_name == "User" and r.parent_name == "IAuditable" and r.kind == "implements"+ for r in relations+ )++ def test_dbcontext_inherits_dbcontext(self, ingest_solution) -> None:+ """AppDbContext extends DbContext (heritage edge present even though+ DbContext is external)."""+ relations: list = []+ for p in ingest_solution["parsed"]:+ relations.extend(p.heritage)+ assert any(+ r.child_name == "AppDbContext" and r.parent_name == "DbContext"+ for r in relations+ )++ def test_program_to_controller_framework_edge(self, ingest_solution) -> None:+ """ASP.NET framework edge: Program.cs -> UsersController.cs."""+ graph = ingest_solution["graph"]+ # Find the entry/controller paths regardless of separator.+ nodes = list(graph.nodes())+ program = next((n for n in nodes if n.endswith("Program.cs")), None)+ controller = next((n for n in nodes if n.endswith("UsersController.cs")), None)+ assert program and controller, f"missing nodes: {nodes}"+ assert graph.has_edge(program, controller)+ edge = graph[program][controller]+ # Either a framework edge or an import edge — both are valid here+ # since the controller is in a referenced project.+ assert edge.get("edge_type") in ("framework", "import", None) or edge++ def test_dbcontext_to_user_framework_edge(self, ingest_solution) -> None:+ """DbContext with `DbSet<User>` should edge to the User entity file."""+ graph = ingest_solution["graph"]+ nodes = list(graph.nodes())+ ctx = next((n for n in nodes if n.endswith("AppDbContext.cs")), None)+ user = next((n for n in nodes if n.endswith("User.cs")), None)+ assert ctx and user, f"missing nodes — ctx={ctx} user={user}"+ assert graph.has_edge(ctx, user)+++class TestCrossRepoWorkspace:+ def test_project_ref_and_internal_nuget_detected(self) -> None:+ """The two-repo .NET workspace produces both kinds of cross-repo deps."""+ from repowise.core.workspace.cross_repo import detect_package_dependencies++ repos = {+ "api-service": DOTNET_WORKSPACE / "api-service",+ "shared-libs": DOTNET_WORKSPACE / "shared-libs",+ "telemetry-lib": DOTNET_WORKSPACE / "telemetry-lib",+ }+ deps = detect_package_dependencies(repos)+ kinds = {d.kind for d in deps}+ assert "dotnet_project_ref" in kinds, [d for d in deps]+ # api-service references shared-libs via <ProjectReference>+ assert any(+ d.source_repo == "api-service"+ and d.target_repo == "shared-libs"+ and d.kind == "dotnet_project_ref"+ for d in deps+ )+ # api-service references Acme.Telemetry NuGet whose AssemblyName+ # lives in telemetry-lib — internal-NuGet pattern.+ assert "dotnet_nuget_internal" in kinds+ assert any(+ d.source_repo == "api-service"+ and d.target_repo == "telemetry-lib"+ and d.kind == "dotnet_nuget_internal"+ for d in deps+ )diff --git a/tests/unit/ingestion/test_csharp_extractors.py b/tests/unit/ingestion/test_csharp_extractors.pynew file mode 100644index 000000000..42ba2796d--- /dev/null+++ b/tests/unit/ingestion/test_csharp_extractors.py@@ -0,0 +1,187 @@+"""Unit tests for C# heritage, binding, and docstring extractors.++These tests exercise the post-Batch-3 extractors:++- ``_extract_csharp_heritage`` — class/record inheritance with the+ "first-non-interface = extends" classification heuristic.+- ``extract_csharp_bindings`` — ``global`` / ``static`` / alias flag+ propagation onto ``NamedBinding`` instances.+- ``extract_module_docstring`` / ``extract_symbol_docstring`` — XML+ ``<summary>`` extraction and ``///`` line-comment runs at the module+ level.++The parser path is invoked end-to-end (parse → extract) so we exercise+the same code paths as production.+"""++from __future__ import annotations++from datetime import datetime++import pytest++from repowise.core.ingestion.models import FileInfo+from repowise.core.ingestion.parser import ASTParser+++def _file(path: str = "Foo.cs") -> FileInfo:+ return FileInfo(+ path=path,+ abs_path=f"/tmp/{path}",+ language="csharp",+ size_bytes=100,+ git_hash="",+ last_modified=datetime.now(),+ is_test=False,+ is_config=False,+ is_api_contract=False,+ is_entry_point=False,+ )++[email protected](scope="module")+def parser() -> ASTParser:+ return ASTParser()+++# ---------------------------------------------------------------------------+# Heritage+# ---------------------------------------------------------------------------+++class TestCSharpHeritage:+ def test_extends_and_implements(self, parser: ASTParser) -> None:+ # Note: IDisposable / IEnumerable etc. are in the C# builtin_parents+ # filter list (see languages/registry.py) so they're stripped from+ # the heritage graph. Use custom interfaces to exercise the path.+ src = b"""\+namespace App;+public class FooService : BaseService, IFooService, ILogger+{+}+"""+ result = parser.parse_file(_file(), src)+ rels = {(r.parent_name, r.kind) for r in result.heritage}+ assert ("BaseService", "extends") in rels+ assert ("IFooService", "implements") in rels+ assert ("ILogger", "implements") in rels++ def test_implements_only_when_no_class_base(self, parser: ASTParser) -> None:+ src = b"""\+namespace App;+public class Foo : IFooService, IBarService {}+"""+ result = parser.parse_file(_file(), src)+ rels = {(r.parent_name, r.kind) for r in result.heritage}+ # No concrete base — both interface-looking names land as implements.+ assert ("IFooService", "implements") in rels+ assert ("IBarService", "implements") in rels+ # And neither should sneak through as "extends".+ assert ("IFooService", "extends") not in rels++ def test_record_inheritance(self, parser: ASTParser) -> None:+ src = b"""\+namespace App;+public record User(string Name) : Entity(Name), IAuditable;+"""+ result = parser.parse_file(_file(), src)+ rels = {(r.parent_name, r.kind) for r in result.heritage}+ assert ("Entity", "extends") in rels+ assert ("IAuditable", "implements") in rels++ def test_strips_generic_args_and_namespace(self, parser: ASTParser) -> None:+ src = b"""\+namespace App;+public class Repo : Microsoft.EntityFrameworkCore.DbContext, IRepository<User>+{+}+"""+ result = parser.parse_file(_file(), src)+ names = {r.parent_name for r in result.heritage}+ assert "DbContext" in names+ assert "IRepository" in names+++# ---------------------------------------------------------------------------+# Bindings+# ---------------------------------------------------------------------------+++class TestCSharpBindings:+ def test_plain_using(self, parser: ASTParser) -> None:+ src = b"using System.Linq;\n"+ result = parser.parse_file(_file(), src)+ bindings = [b for imp in result.imports for b in imp.bindings]+ assert any(+ b.local_name == "Linq" and not b.is_global and not b.is_static_import+ for b in bindings+ )++ def test_global_using(self, parser: ASTParser) -> None:+ src = b"global using System.Threading.Tasks;\n"+ result = parser.parse_file(_file(), src)+ bindings = [b for imp in result.imports for b in imp.bindings]+ assert any(b.local_name == "Tasks" and b.is_global for b in bindings)++ def test_using_static(self, parser: ASTParser) -> None:+ src = b"using static System.Math;\n"+ result = parser.parse_file(_file(), src)+ bindings = [b for imp in result.imports for b in imp.bindings]+ assert any(b.local_name == "Math" and b.is_static_import for b in bindings)++ def test_alias_form(self, parser: ASTParser) -> None:+ src = b"using JsonNode = System.Text.Json.Nodes.JsonNode;\n"+ result = parser.parse_file(_file(), src)+ bindings = [b for imp in result.imports for b in imp.bindings]+ # Alias form sets is_module_alias and uses the alias as local_name.+ assert any(b.local_name == "JsonNode" and b.is_module_alias for b in bindings)+++# ---------------------------------------------------------------------------+# Docstrings+# ---------------------------------------------------------------------------+++class TestCSharpDocstrings:+ def test_summary_xml_stripped_from_symbol_docstring(self, parser: ASTParser) -> None:+ src = b"""\+namespace App;++/// <summary>Compute things efficiently.</summary>+/// <param name="x">First operand.</param>+public class Calculator {}+"""+ result = parser.parse_file(_file(), src)+ cls = next(s for s in result.symbols if s.name == "Calculator")+ assert cls.docstring == "Compute things efficiently."++ def test_inheritdoc_marker(self, parser: ASTParser) -> None:+ src = b"""\+namespace App;++/// <inheritdoc/>+public class Derived : Base {}++public class Base {}+"""+ result = parser.parse_file(_file(), src)+ derived = next(s for s in result.symbols if s.name == "Derived")+ assert derived.docstring == "{inheritdoc}"++ def test_module_level_triple_slash_docstring(self, parser: ASTParser) -> None:+ src = b"""\+/// <summary>Top-level helpers shared across the API tier.</summary>+using System;++namespace App;++public class Helper {}+"""+ result = parser.parse_file(_file(), src)+ assert result.docstring == "Top-level helpers shared across the API tier."++ def test_no_docstring_returns_none(self, parser: ASTParser) -> None:+ src = b"namespace App;\npublic class Plain {}\n"+ result = parser.parse_file(_file(), src)+ plain = next(s for s in result.symbols if s.name == "Plain")+ assert plain.docstring is Nonediff --git a/tests/unit/ingestion/test_csharp_framework_edges.py b/tests/unit/ingestion/test_csharp_framework_edges.pynew file mode 100644index 000000000..c18367df2--- /dev/null+++ b/tests/unit/ingestion/test_csharp_framework_edges.py@@ -0,0 +1,208 @@+"""Unit tests for ASP.NET framework edges and .NET dynamic hints.++These tests cover Batch 4 of the C# Full-tier upgrade:++- ``_add_aspnet_edges`` in ``framework_edges.py`` — Program.cs/Startup.cs+ to controllers, minimal-API handler resolution, UseMiddleware<T>(),+ and DbContext → DbSet<T> entity wiring.+- ``DotNetDynamicHints`` in ``dynamic_hints/dotnet.py`` — DI container+ registrations, reflection, and InternalsVisibleTo discovery.+"""++from __future__ import annotations++from datetime import datetime+from pathlib import Path++import networkx as nx++from repowise.core.ingestion.dynamic_hints.dotnet import DotNetDynamicHints+from repowise.core.ingestion.framework_edges import add_framework_edges+from repowise.core.ingestion.models import FileInfo, ParsedFile, Symbol+from repowise.core.ingestion.parser import ASTParser+from repowise.core.ingestion.resolvers.context import ResolverContext+++# ---------------------------------------------------------------------------+# Framework edges+# ---------------------------------------------------------------------------+++def _file_info(path: str, abs_path: str, language: str = "csharp") -> FileInfo:+ return FileInfo(+ path=path,+ abs_path=abs_path,+ language=language,+ size_bytes=100,+ git_hash="",+ last_modified=datetime.now(),+ is_test=False,+ is_config=False,+ is_api_contract=False,+ is_entry_point=path.endswith("Program.cs"),+ )+++def _build_parsed_files(repo: Path) -> dict[str, ParsedFile]:+ """Parse every .cs file under *repo* and return a {rel_path: ParsedFile} map."""+ parser = ASTParser()+ out: dict[str, ParsedFile] = {}+ for cs in repo.rglob("*.cs"):+ rel = cs.resolve().relative_to(repo.resolve()).as_posix()+ fi = _file_info(rel, str(cs.resolve()))+ result = parser.parse_file(fi, cs.read_bytes())+ out[rel] = result+ return out+++def _ctx(repo: Path, parsed: dict[str, ParsedFile]) -> ResolverContext:+ path_set = set(parsed.keys())+ stem_map: dict[str, list[str]] = {}+ for p in path_set:+ stem = Path(p).stem.lower()+ stem_map.setdefault(stem, []).append(p)+ return ResolverContext(+ path_set=path_set, stem_map=stem_map, graph=nx.DiGraph(), repo_path=repo+ )+++class TestAspNetEdges:+ def test_program_to_controllers(self, tmp_path: Path) -> None:+ (tmp_path / "Program.cs").write_text(+ """using Microsoft.AspNetCore.Builder;+var app = WebApplication.CreateBuilder(args).Build();+app.MapControllers();+app.Run();+"""+ )+ (tmp_path / "Controllers").mkdir()+ (tmp_path / "Controllers" / "UsersController.cs").write_text(+ """using Microsoft.AspNetCore.Mvc;+namespace Acme.Api;+[ApiController]+[Route("api/users")]+public class UsersController : ControllerBase {+ [HttpGet] public IActionResult Get() => Ok();+}+"""+ )+ parsed = _build_parsed_files(tmp_path)+ graph = nx.DiGraph()+ for p in parsed:+ graph.add_node(p)+ ctx = _ctx(tmp_path, parsed)++ count = add_framework_edges(graph, parsed, ctx, tech_stack=["aspnet"])+ assert count >= 1+ assert graph.has_edge("Program.cs", "Controllers/UsersController.cs")+ edge = graph["Program.cs"]["Controllers/UsersController.cs"]+ assert edge["edge_type"] == "framework"++ def test_dbcontext_to_dbset_entity(self, tmp_path: Path) -> None:+ (tmp_path / "Domain").mkdir()+ (tmp_path / "Infra").mkdir()+ (tmp_path / "Domain" / "User.cs").write_text(+ "namespace Acme.Domain;\npublic class User { public int Id; }\n"+ )+ (tmp_path / "Infra" / "AppDbContext.cs").write_text(+ """using Microsoft.EntityFrameworkCore;+namespace Acme.Infra;+public class AppDbContext : DbContext {+ public DbSet<User> Users { get; set; }+}+"""+ )+ # Need a Program.cs or any ASP.NET signal to enable the path; use the+ # Microsoft.EntityFrameworkCore using directive as the fallback signal.+ (tmp_path / "Program.cs").write_text(+ "using Microsoft.AspNetCore.Builder;\nvar app = 1;\n"+ )+ parsed = _build_parsed_files(tmp_path)+ graph = nx.DiGraph()+ for p in parsed:+ graph.add_node(p)+ ctx = _ctx(tmp_path, parsed)++ add_framework_edges(graph, parsed, ctx, tech_stack=[])+ assert graph.has_edge("Infra/AppDbContext.cs", "Domain/User.cs")++ def test_no_edges_when_no_aspnet_signal(self, tmp_path: Path) -> None:+ (tmp_path / "Plain.cs").write_text(+ "namespace Plain;\npublic class Foo {}\n"+ )+ parsed = _build_parsed_files(tmp_path)+ graph = nx.DiGraph()+ for p in parsed:+ graph.add_node(p)+ ctx = _ctx(tmp_path, parsed)++ count = add_framework_edges(graph, parsed, ctx, tech_stack=[])+ # Conftest detection runs unconditionally but should produce 0+ # for a single C# file with no test conventions.+ assert count == 0+++# ---------------------------------------------------------------------------+# Dynamic hints+# ---------------------------------------------------------------------------+++class TestDotNetDynamicHints:+ def test_di_registration_emits_interface_to_impl(self, tmp_path: Path) -> None:+ (tmp_path / "IUserService.cs").write_text(+ "namespace Acme;\npublic interface IUserService { }\n"+ )+ (tmp_path / "UserService.cs").write_text(+ "namespace Acme;\npublic class UserService : IUserService { }\n"+ )+ (tmp_path / "Program.cs").write_text(+ """var builder = WebApplication.CreateBuilder(args);+builder.Services.AddScoped<IUserService, UserService>();+"""+ )+ edges = DotNetDynamicHints().extract(tmp_path)+ targets = {(e.source, e.target) for e in edges}+ # Program.cs registers it (registration site -> impl)+ assert ("Program.cs", "UserService.cs") in targets+ # Interface file is recorded as having a real implementation+ assert ("IUserService.cs", "UserService.cs") in targets++ def test_activator_create_instance_typeof(self, tmp_path: Path) -> None:+ (tmp_path / "Plugin.cs").write_text(+ "namespace Acme;\npublic class Plugin { }\n"+ )+ (tmp_path / "Loader.cs").write_text(+ "namespace Acme;\npublic class Loader { void Load() { var p = Activator.CreateInstance(typeof(Plugin)); } }\n"+ )+ edges = DotNetDynamicHints().extract(tmp_path)+ assert any(e.source == "Loader.cs" and e.target == "Plugin.cs" for e in edges)++ def test_type_gettype_string_form(self, tmp_path: Path) -> None:+ (tmp_path / "Worker.cs").write_text(+ "namespace Acme;\npublic class Worker { }\n"+ )+ (tmp_path / "Boot.cs").write_text(+ 'namespace Acme;\npublic class Boot { void Go() { var t = Type.GetType("Acme.Worker"); } }\n'+ )+ edges = DotNetDynamicHints().extract(tmp_path)+ assert any(e.source == "Boot.cs" and e.target == "Worker.cs" for e in edges)++ def test_internals_visible_to_emits_friend_edge(self, tmp_path: Path) -> None:+ (tmp_path / "AssemblyInfo.cs").write_text(+ '[assembly: InternalsVisibleTo("Acme.Tests")]\n'+ )+ edges = DotNetDynamicHints().extract(tmp_path)+ assert any(+ e.source == "AssemblyInfo.cs" and e.target == "external:friend:Acme.Tests"+ for e in edges+ )++ def test_skips_bin_obj_directories(self, tmp_path: Path) -> None:+ (tmp_path / "obj" / "Debug").mkdir(parents=True)+ (tmp_path / "obj" / "Debug" / "Generated.cs").write_text(+ 'public class Junk { void X() { Activator.CreateInstance(typeof(Plugin)); } }\n'+ )+ (tmp_path / "Plugin.cs").write_text("public class Plugin { }\n")+ edges = DotNetDynamicHints().extract(tmp_path)+ # No edge should originate from obj/...+ assert not any("obj/" in e.source for e in edges)diff --git a/tests/unit/ingestion/test_csharp_resolver.py b/tests/unit/ingestion/test_csharp_resolver.pynew file mode 100644index 000000000..ba528b518--- /dev/null+++ b/tests/unit/ingestion/test_csharp_resolver.py@@ -0,0 +1,273 @@+"""Unit tests for the C# / .NET-aware import resolver.++The resolver is project-graph aware: it parses ``.csproj`` and ``.sln``+files under the repo, builds a namespace → file map, and ranks+candidates by enclosing project + ProjectReference relationships. These+tests build small repos on disk (via ``tmp_path``) so the index parses+real MSBuild XML.+"""++from __future__ import annotations++from pathlib import Path++import networkx as nx+import pytest++from repowise.core.ingestion.resolvers.context import ResolverContext+from repowise.core.ingestion.resolvers.csharp import resolve_csharp_import+from repowise.core.ingestion.resolvers.dotnet import (+ DotNetProjectIndex,+ build_namespace_map,+ parse_csproj,+ parse_sln,+)+from repowise.core.ingestion.resolvers.dotnet.global_usings import scan_global_usings+from repowise.core.ingestion.resolvers.dotnet.index import build_index+from repowise.core.ingestion.resolvers.dotnet.namespace_map import declared_namespaces+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _csproj(deps: list[str] = (), packages: list[tuple[str, str]] = (), implicit: bool = True) -> str:+ refs = "\n".join(f' <ProjectReference Include="{p}" />' for p in deps)+ pkgs = "\n".join(+ f' <PackageReference Include="{name}" Version="{ver}" />' for name, ver in packages+ )+ return f"""<Project Sdk="Microsoft.NET.Sdk">+ <PropertyGroup>+ <TargetFramework>net8.0</TargetFramework>+ <ImplicitUsings>{"enable" if implicit else "disable"}</ImplicitUsings>+ <Nullable>enable</Nullable>+ </PropertyGroup>+ <ItemGroup>+{refs}+{pkgs}+ </ItemGroup>+</Project>+"""+++def _ctx_for(repo: Path) -> ResolverContext:+ """Build a ResolverContext rooted at *repo* with all .cs files indexed."""+ cs_files = [p for p in repo.rglob("*.cs")]+ path_set: set[str] = set()+ stem_map: dict[str, list[str]] = {}+ for cs in cs_files:+ rel = cs.resolve().relative_to(repo.resolve()).as_posix()+ path_set.add(rel)+ stem = cs.stem.lower()+ stem_map.setdefault(stem, []).append(rel)+ return ResolverContext(+ path_set=path_set,+ stem_map=stem_map,+ graph=nx.DiGraph(),+ repo_path=repo,+ )+++# ---------------------------------------------------------------------------+# .csproj parsing+# ---------------------------------------------------------------------------+++class TestCsprojParsing:+ def test_extracts_project_and_package_references(self, tmp_path: Path) -> None:+ csproj_path = tmp_path / "Foo.csproj"+ csproj_path.write_text(+ _csproj(+ deps=[r"..\Bar\Bar.csproj"],+ packages=[("Newtonsoft.Json", "13.0.1"), ("Serilog", "3.0.0")],+ )+ )+ proj = parse_csproj(csproj_path)+ assert proj is not None+ assert proj.implicit_usings is True+ assert proj.package_references == {"Newtonsoft.Json", "Serilog"}+ # ProjectReference Include used Windows-style backslashes — the+ # parser must normalise to forward slashes and resolve.+ assert any(p.name == "Bar.csproj" for p in proj.project_references)++ def test_handles_legacy_xml_namespace(self, tmp_path: Path) -> None:+ csproj_path = tmp_path / "Legacy.csproj"+ csproj_path.write_text(+ """<?xml version="1.0" encoding="utf-8"?>+<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">+ <PropertyGroup>+ <RootNamespace>MyOrg.Legacy</RootNamespace>+ <AssemblyName>MyOrg.Legacy</AssemblyName>+ </PropertyGroup>+</Project>+"""+ )+ proj = parse_csproj(csproj_path)+ assert proj is not None+ assert proj.root_namespace == "MyOrg.Legacy"+ assert proj.assembly_name == "MyOrg.Legacy"++ def test_returns_none_on_invalid_xml(self, tmp_path: Path) -> None:+ bad = tmp_path / "Bad.csproj"+ bad.write_text("not <xml at all >")+ assert parse_csproj(bad) is None+++# ---------------------------------------------------------------------------+# .sln parsing+# ---------------------------------------------------------------------------+++class TestSlnParsing:+ def test_extracts_csproj_entries(self, tmp_path: Path) -> None:+ # Create the .csproj files referenced by the .sln so paths resolve.+ (tmp_path / "Api").mkdir()+ (tmp_path / "Api" / "Api.csproj").write_text(_csproj())+ (tmp_path / "Domain").mkdir()+ (tmp_path / "Domain" / "Domain.csproj").write_text(_csproj())++ sln = tmp_path / "MySln.sln"+ sln.write_text(+ """Microsoft Visual Studio Solution File, Format Version 12.00+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Api", "Api\\Api.csproj", "{AAAAAAAA-1111-2222-3333-444444444444}"+EndProject+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Domain", "Domain\\Domain.csproj", "{BBBBBBBB-1111-2222-3333-444444444444}"+EndProject+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{CCCCCCCC-1111-2222-3333-444444444444}"+EndProject+"""+ )+ entries = parse_sln(sln)+ names = {e.name for e in entries}+ # Solution folder must be skipped.+ assert names == {"Api", "Domain"}+++# ---------------------------------------------------------------------------+# Namespace map + global usings+# ---------------------------------------------------------------------------+++class TestNamespaceMap:+ def test_block_form(self) -> None:+ text = "namespace Foo.Bar { public class A {} }"+ assert declared_namespaces(text) == ["Foo.Bar"]++ def test_file_scoped(self) -> None:+ text = "namespace Foo.Bar.Baz;\npublic class A {}"+ assert declared_namespaces(text) == ["Foo.Bar.Baz"]++ def test_multiple_namespaces_in_one_file(self) -> None:+ text = "namespace A { class X {} }\nnamespace B { class Y {} }"+ assert declared_namespaces(text) == ["A", "B"]++ 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+++class TestGlobalUsings:+ def test_scan_plain_global_using(self) -> None:+ text = "global using System;\nglobal using System.Linq;"+ assert scan_global_usings(text) == ["System", "System.Linq"]++ def test_scan_global_using_static(self) -> None:+ text = "global using static System.Math;"+ assert scan_global_usings(text) == ["System.Math"]++ def test_scan_global_using_alias(self) -> None:+ text = "global using MyAlias = Some.Long.Namespace;"+ assert scan_global_usings(text) == ["Some.Long.Namespace"]+++# ---------------------------------------------------------------------------+# End-to-end resolver+# ---------------------------------------------------------------------------+++class TestResolverEndToEnd:+ def _make_solution(self, repo: Path) -> None:+ """Create a 2-project solution: Api references Domain."""+ (repo / "src" / "Api").mkdir(parents=True)+ (repo / "src" / "Domain").mkdir(parents=True)++ (repo / "src" / "Api" / "Api.csproj").write_text(+ _csproj(+ deps=[r"..\Domain\Domain.csproj"],+ packages=[("Newtonsoft.Json", "13.0.1"), ("Microsoft.AspNetCore.App", "8.0.0")],+ )+ )+ (repo / "src" / "Domain" / "Domain.csproj").write_text(_csproj())++ (repo / "src" / "Domain" / "User.cs").write_text(+ "namespace Acme.Domain;\npublic record User(string Name);\n"+ )+ (repo / "src" / "Api" / "UsersController.cs").write_text(+ "using Acme.Domain;\nnamespace Acme.Api;\npublic class UsersController {}\n"+ )++ def test_resolves_cross_project_via_namespace(self, tmp_path: Path) -> None:+ self._make_solution(tmp_path)+ ctx = _ctx_for(tmp_path)+ importer = "src/Api/UsersController.cs"+ result = resolve_csharp_import("Acme.Domain", importer, ctx)+ assert result == "src/Domain/User.cs"++ def test_external_nuget_package(self, tmp_path: Path) -> None:+ self._make_solution(tmp_path)+ ctx = _ctx_for(tmp_path)+ importer = "src/Api/UsersController.cs"+ # Newtonsoft.Json is declared as a PackageReference on Api; the same+ # namespace as the package id resolves to a nuget: external node.+ result = resolve_csharp_import("Newtonsoft.Json", importer, ctx)+ assert result is not None and result.startswith("external:nuget:")++ def test_unknown_namespace_falls_to_external(self, tmp_path: Path) -> None:+ self._make_solution(tmp_path)+ ctx = _ctx_for(tmp_path)+ result = resolve_csharp_import("Totally.Unknown.Thing", "src/Api/UsersController.cs", ctx)+ assert result is not None and result.startswith("external:")++ def test_no_repo_path_falls_back_to_stem_match(self, tmp_path: Path) -> None:+ # Repo without .csproj — exercise the legacy path.+ (tmp_path / "loose.cs").write_text("namespace Loose; class L {}")+ path_set = {"loose.cs"}+ stem_map = {"loose": ["loose.cs"]}+ ctx = ResolverContext(+ path_set=path_set, stem_map=stem_map, graph=nx.DiGraph(), repo_path=None+ )+ assert resolve_csharp_import("Loose", "other.cs", ctx) == "loose.cs"+++class TestProjectIndexCaching:+ def test_index_cached_on_context(self, tmp_path: Path) -> None:+ (tmp_path / "Api").mkdir()+ (tmp_path / "Api" / "Api.csproj").write_text(_csproj())+ (tmp_path / "Api" / "Foo.cs").write_text("namespace Foo;\nclass F {}")++ ctx = _ctx_for(tmp_path)+ from repowise.core.ingestion.resolvers.dotnet.index import get_or_build_index++ first = get_or_build_index(ctx)+ second = get_or_build_index(ctx)+ assert first is second # cached on ctx+ assert isinstance(first, DotNetProjectIndex)+ assert first.repo_path == tmp_path.resolve()+ assert "Foo" in first.namespace_map+++ "raw,expected",+ [+ ("namespace Foo;", ["Foo"]),+ (" namespace Foo.Bar.Baz {", ["Foo.Bar.Baz"]),+ ("namespace Foo_Bar.Baz123 ;", ["Foo_Bar.Baz123"]),+ ("// namespace NotReal;", []),+ ],+)+def test_namespace_regex_edge_cases(raw: str, expected: list[str]) -> None:+ assert declared_namespaces(raw) == expecteddiff --git a/tests/unit/ingestion/test_parser.py b/tests/unit/ingestion/test_parser.pyindex 60b8b096b..5694dba05 100644--- a/tests/unit/ingestion/test_parser.py+++ b/tests/unit/ingestion/test_parser.py@@ -798,6 +798,132 @@ class TestCSharpParser:assert result.parse_errors == []+# ---------------------------------------------------------------------------+# C# — modern features (records, delegates, events, namespaces, global using)+# ---------------------------------------------------------------------------++CSHARP_MODERN_SOURCE = b"""\+global using System;+global using static System.Math;+using Foo = Sample.Very.Long.Namespace.Type;+using static System.Convert;++namespace Sample.Modern;++public delegate int BinaryOp(int x, int y);++public record User(string Name, int Age);++public record struct Coordinate(double X, double Y);++public class EventBus+{+ public event EventHandler<string>? MessageReceived;+ public string Topic = "default";+ private const int MaxListeners = 100;+}++public enum Status { Active, Inactive, Pending }+"""+++class TestCSharpModernParser:+ def test_finds_record(self, parser: ASTParser) -> None:+ fi = _make_file_info("csharp_pkg/Modern.cs", "csharp")+ result = parser.parse_file(fi, CSHARP_MODERN_SOURCE)+ names = {s.name for s in result.symbols}+ assert "User" in names++ def test_finds_record_struct(self, parser: ASTParser) -> None:+ fi = _make_file_info("csharp_pkg/Modern.cs", "csharp")+ result = parser.parse_file(fi, CSHARP_MODERN_SOURCE)+ names = {s.name for s in result.symbols}+ assert "Coordinate" in names++ def test_finds_delegate(self, parser: ASTParser) -> None:+ fi = _make_file_info("csharp_pkg/Modern.cs", "csharp")+ result = parser.parse_file(fi, CSHARP_MODERN_SOURCE)+ names = {s.name for s in result.symbols}+ assert "BinaryOp" in names++ def test_finds_event(self, parser: ASTParser) -> None:+ fi = _make_file_info("csharp_pkg/Modern.cs", "csharp")+ result = parser.parse_file(fi, CSHARP_MODERN_SOURCE)+ names = {s.name for s in result.symbols}+ assert "MessageReceived" in names++ def test_finds_field(self, parser: ASTParser) -> None:+ fi = _make_file_info("csharp_pkg/Modern.cs", "csharp")+ result = parser.parse_file(fi, CSHARP_MODERN_SOURCE)+ names = {s.name for s in result.symbols}+ assert "Topic" in names+ assert "MaxListeners" in names++ def test_finds_enum_member(self, parser: ASTParser) -> None:+ fi = _make_file_info("csharp_pkg/Modern.cs", "csharp")+ result = parser.parse_file(fi, CSHARP_MODERN_SOURCE)+ names = {s.name for s in result.symbols}+ assert "Active" in names+ assert "Inactive" in names++ def test_finds_file_scoped_namespace(self, parser: ASTParser) -> None:+ fi = _make_file_info("csharp_pkg/Modern.cs", "csharp")+ result = parser.parse_file(fi, CSHARP_MODERN_SOURCE)+ modules = [s for s in result.symbols if s.kind == "module"]+ assert any("Sample.Modern" in s.name or s.name == "Sample.Modern" for s in modules)++ def test_imports_capture_global_and_static(self, parser: ASTParser) -> None:+ fi = _make_file_info("csharp_pkg/Modern.cs", "csharp")+ result = parser.parse_file(fi, CSHARP_MODERN_SOURCE)+ modules = {imp.module_path for imp in result.imports}+ # global using and using static still surface as imports — full flag+ # propagation (is_global / is_static) lives in the binding extractor.+ assert "System" in modules+ assert any("Math" in m for m in modules)+ assert any("Convert" in m for m in modules)+ # The alias form `using Foo = Long.Namespace.Type` is captured as the+ # right-hand qualified name; alias propagation is wired in Batch 3.+ assert len(result.imports) >= 3++ def test_no_parse_errors(self, parser: ASTParser) -> None:+ fi = _make_file_info("csharp_pkg/Modern.cs", "csharp")+ result = parser.parse_file(fi, CSHARP_MODERN_SOURCE)+ assert result.parse_errors == []+++class TestCSharpRegistryMetadata:+ def test_csharp_spec_has_manifest_files(self) -> None:+ from repowise.core.ingestion.languages.registry import REGISTRY++ spec = REGISTRY.get("csharp")+ assert spec is not None+ assert "global.json" in spec.manifest_files+ assert "Directory.Build.props" in spec.manifest_files++ def test_csharp_spec_has_blocked_dirs(self) -> None:+ from repowise.core.ingestion.languages.registry import REGISTRY++ spec = REGISTRY.get("csharp")+ assert spec is not None+ assert "bin" in spec.blocked_dirs+ assert "obj" in spec.blocked_dirs++ def test_csharp_spec_has_generated_suffixes(self) -> None:+ from repowise.core.ingestion.languages.registry import REGISTRY++ spec = REGISTRY.get("csharp")+ assert spec is not None+ assert ".g.cs" in spec.generated_suffixes+ assert ".Designer.cs" in spec.generated_suffixes++ def test_csharp_record_in_heritage_node_types(self) -> None:+ from repowise.core.ingestion.languages.registry import REGISTRY++ spec = REGISTRY.get("csharp")+ assert spec is not None+ assert "record_declaration" in spec.heritage_node_types++# ---------------------------------------------------------------------------# Swift# ---------------------------------------------------------------------------@@ -1032,6 +1158,13 @@ end"""+# tree-sitter-luau is a real dep in pyproject.toml, but it is sometimes+# absent from a partially-synced developer venv (e.g. when an old `uv pip+# install -e .` ran before the dep was added). Skip explicitly so the+# failure mode is "go run uv sync" rather than two confusing AssertionErrors.+pytest.importorskip("tree_sitter_luau", reason="run `uv sync --all-packages`")++class TestLuauParser:def test_finds_top_level_function(self, parser: ASTParser) -> None:fi = _make_file_info("luau_pkg/init.luau", "luau")diff --git a/tests/unit/test_csharp_dead_code_markers.py b/tests/unit/test_csharp_dead_code_markers.pynew file mode 100644index 000000000..4d398e36e--- /dev/null+++ b/tests/unit/test_csharp_dead_code_markers.py@@ -0,0 +1,83 @@+"""Tests for C# dynamic-import markers in dead-code analysis.++Files containing reflection / DI registration / InternalsVisibleTo are+recorded in ``DeadCodeAnalyzer._dynamic_import_files`` so the analyser+can lower confidence on dead-code candidates that may actually be+loaded at runtime by the framework.+"""++from __future__ import annotations++from datetime import datetime+from pathlib import Path++import networkx as nx++from repowise.core.analysis.dead_code import DeadCodeAnalyzer+from repowise.core.ingestion.models import FileInfo, ParsedFile+++def _make_parsed(path: str, abs_path: str) -> ParsedFile:+ fi = FileInfo(+ path=path,+ abs_path=abs_path,+ language="csharp",+ size_bytes=100,+ git_hash="",+ last_modified=datetime.now(),+ is_test=False,+ is_config=False,+ is_api_contract=False,+ is_entry_point=False,+ )+ return ParsedFile(+ file_info=fi,+ symbols=[],+ imports=[],+ exports=[],+ )+++def test_activator_create_instance_marks_file(tmp_path: Path) -> None:+ src = tmp_path / "Loader.cs"+ src.write_text(+ "public class Loader { void Go() { Activator.CreateInstance(typeof(Plugin)); } }\n"+ )+ parsed = {"Loader.cs": _make_parsed("Loader.cs", str(src))}+ analyzer = DeadCodeAnalyzer(graph=nx.DiGraph(), parsed_files=parsed)+ assert "Loader.cs" in analyzer._dynamic_import_files+++def test_di_registration_marks_file(tmp_path: Path) -> None:+ src = tmp_path / "Program.cs"+ src.write_text(+ "var b = WebApplication.CreateBuilder(args);\n"+ "b.Services.AddScoped<IUserService, UserService>();\n"+ )+ parsed = {"Program.cs": _make_parsed("Program.cs", str(src))}+ analyzer = DeadCodeAnalyzer(graph=nx.DiGraph(), parsed_files=parsed)+ assert "Program.cs" in analyzer._dynamic_import_files+++def test_internals_visible_to_marks_file(tmp_path: Path) -> None:+ src = tmp_path / "AssemblyInfo.cs"+ src.write_text('[assembly: InternalsVisibleTo("Acme.Tests")]\n')+ parsed = {"AssemblyInfo.cs": _make_parsed("AssemblyInfo.cs", str(src))}+ analyzer = DeadCodeAnalyzer(graph=nx.DiGraph(), parsed_files=parsed)+ assert "AssemblyInfo.cs" in analyzer._dynamic_import_files+++def test_type_gettype_marks_file(tmp_path: Path) -> None:+ src = tmp_path / "Boot.cs"+ src.write_text('var t = Type.GetType("Acme.Worker");\n')+ parsed = {"Boot.cs": _make_parsed("Boot.cs", str(src))}+ analyzer = DeadCodeAnalyzer(graph=nx.DiGraph(), parsed_files=parsed)+ assert "Boot.cs" in analyzer._dynamic_import_files+++def test_plain_csharp_file_not_marked(tmp_path: Path) -> None:+ src = tmp_path / "Plain.cs"+ src.write_text("public class Plain { public int X => 1; }\n")+ parsed = {"Plain.cs": _make_parsed("Plain.cs", str(src))}+ analyzer = DeadCodeAnalyzer(graph=nx.DiGraph(), parsed_files=parsed)+ assert "Plain.cs" not in analyzer._dynamic_import_filesdiff --git a/tests/unit/workspace/test_dotnet_workspace.py b/tests/unit/workspace/test_dotnet_workspace.pynew file mode 100644index 000000000..5b8a2db6a--- /dev/null+++ b/tests/unit/workspace/test_dotnet_workspace.py@@ -0,0 +1,231 @@+"""Workspace-level tests for .NET / C# support added in Batch 5.++Covers:+- ASP.NET HTTP contract extraction (provider attributes + minimal API ++ HttpClient consumer)+- gRPC-dotnet contract extraction (MapGrpcService, generated-base+ inheritance, generated-Client consumers)+- Cross-repo .NET package dependency scanner: ProjectReference and+ internal-NuGet (PackageReference id matching a sibling AssemblyName).+"""++from __future__ import annotations++from pathlib import Path+from textwrap import dedent++from repowise.core.workspace.cross_repo import (+ _scan_csproj,+ detect_package_dependencies,+)+from repowise.core.workspace.extractors.grpc_extractor import GrpcExtractor+from repowise.core.workspace.extractors.http_extractor import HttpExtractor+++# ---------------------------------------------------------------------------+# HTTP — ASP.NET+# ---------------------------------------------------------------------------+++class TestAspNetHttpExtraction:+ def test_attribute_routing_with_class_prefix(self, tmp_path: Path) -> None:+ (tmp_path / "Controllers").mkdir()+ (tmp_path / "Controllers" / "UsersController.cs").write_text(+ dedent(+ """\+ using Microsoft.AspNetCore.Mvc;+ namespace Acme.Api;++ [ApiController]+ [Route("api/users")]+ public class UsersController : ControllerBase+ {+ [HttpGet("{id:int}")]+ public IActionResult Get(int id) => Ok();++ [HttpPost]+ public IActionResult Create() => Ok();+ }+ """+ )+ )+ contracts = HttpExtractor().extract(tmp_path, repo_alias="api")+ provider_paths = {(c.meta["method"], c.meta["path"]) for c in contracts if c.role == "provider"}+ assert ("GET", "/api/users/{param}") in provider_paths+ assert ("POST", "/api/users") in provider_paths++ def test_minimal_api(self, tmp_path: Path) -> None:+ (tmp_path / "Program.cs").write_text(+ dedent(+ """\+ var app = WebApplication.CreateBuilder(args).Build();+ app.MapGet("/health", () => "ok");+ app.MapPost("/orders", (Order o) => Results.Created());+ """+ )+ )+ contracts = HttpExtractor().extract(tmp_path, repo_alias="api")+ paths = {(c.meta["method"], c.meta["path"]) for c in contracts if c.role == "provider"}+ assert ("GET", "/health") in paths+ assert ("POST", "/orders") in paths++ def test_httpclient_consumer(self, tmp_path: Path) -> None:+ (tmp_path / "OrderClient.cs").write_text(+ dedent(+ """\+ public class OrderClient {+ private readonly HttpClient _http;+ public async Task Pull() {+ await _http.GetAsync("/api/orders/123");+ }+ }+ """+ )+ )+ contracts = HttpExtractor().extract(tmp_path, repo_alias="web")+ consumers = [c for c in contracts if c.role == "consumer"]+ assert any(+ c.meta["client"] == "httpclient"+ and c.meta["method"] == "GET"+ and c.meta["path"] == "/api/orders/123"+ for c in consumers+ )+++# ---------------------------------------------------------------------------+# gRPC-dotnet+# ---------------------------------------------------------------------------+++class TestGrpcDotnetExtraction:+ def test_map_grpc_service_provider(self, tmp_path: Path) -> None:+ (tmp_path / "Program.cs").write_text(+ dedent(+ """\+ builder.Services.AddGrpc();+ var app = builder.Build();+ app.MapGrpcService<GreeterService>();+ """+ )+ )+ contracts = GrpcExtractor().extract(tmp_path, repo_alias="api")+ provider_services = {c.meta["service"] for c in contracts if c.role == "provider"}+ # MapGrpcService<T>() captures the literal type-arg name. Either+ # `Greeter` (raw) or `GreeterService` (suffixed) is correct here.+ assert "GreeterService" in provider_services or "Greeter" in provider_services++ def test_generated_base_provider(self, tmp_path: Path) -> None:+ (tmp_path / "GreeterImpl.cs").write_text(+ dedent(+ """\+ namespace Acme;+ public class GreeterImpl : Greeter.GreeterBase+ {+ }+ """+ )+ )+ contracts = GrpcExtractor().extract(tmp_path, repo_alias="api")+ assert any(c.role == "provider" and c.meta["service"] == "Greeter" for c in contracts)++ def test_generated_client_consumer(self, tmp_path: Path) -> None:+ (tmp_path / "Caller.cs").write_text(+ dedent(+ """\+ using Grpc.Net.Client;+ public class Caller {+ public void Go() {+ var channel = GrpcChannel.ForAddress("https://api");+ var client = new GreeterClient(channel);+ }+ }+ """+ )+ )+ contracts = GrpcExtractor().extract(tmp_path, repo_alias="web")+ consumers = [c for c in contracts if c.role == "consumer"]+ assert any(c.meta["service"] == "Greeter" for c in consumers)+++# ---------------------------------------------------------------------------+# Cross-repo .NET dependencies+# ---------------------------------------------------------------------------+++def _csproj(deps: list[str] = (), assembly_name: str | None = None,+ packages: list[str] = ()) -> str:+ refs = "\n".join(f' <ProjectReference Include="{p}" />' for p in deps)+ pkgs = "\n".join(f' <PackageReference Include="{p}" Version="1.0.0" />' for p in packages)+ asm = f"<AssemblyName>{assembly_name}</AssemblyName>" if assembly_name else ""+ return dedent(+ f"""\+ <Project Sdk="Microsoft.NET.Sdk">+ <PropertyGroup>+ <TargetFramework>net8.0</TargetFramework>+ {asm}+ </PropertyGroup>+ <ItemGroup>+ {refs}+ {pkgs}+ </ItemGroup>+ </Project>+ """+ )+++class TestScanCsproj:+ def _two_repo_workspace(self, root: Path) -> dict[str, Path]:+ api = root / "api-service"+ shared = root / "shared-libs"+ (api / "src" / "Api").mkdir(parents=True)+ (shared / "src" / "Common").mkdir(parents=True)+ (shared / "src" / "Common" / "Common.csproj").write_text(+ _csproj(assembly_name="Acme.Common")+ )+ return {"api": api, "shared": shared}++ def test_project_reference_emits_cross_repo_dep(self, tmp_path: Path) -> None:+ repos = self._two_repo_workspace(tmp_path)+ # api references shared via relative ProjectReference+ (repos["api"] / "src" / "Api" / "Api.csproj").write_text(+ _csproj(deps=[r"..\..\..\shared-libs\src\Common\Common.csproj"])+ )+ deps = _scan_csproj(repos["api"], repos, alias="api")+ assert any(+ d.source_repo == "api"+ and d.target_repo == "shared"+ and d.kind == "dotnet_project_ref"+ for d in deps+ )++ def test_internal_nuget_emits_cross_repo_dep(self, tmp_path: Path) -> None:+ repos = self._two_repo_workspace(tmp_path)+ # api consumes the published Acme.Common NuGet package whose+ # AssemblyName lives in `shared-libs`.+ (repos["api"] / "src" / "Api" / "Api.csproj").write_text(+ _csproj(packages=["Acme.Common"])+ )+ deps = _scan_csproj(repos["api"], repos, alias="api")+ assert any(+ d.source_repo == "api"+ and d.target_repo == "shared"+ and d.kind == "dotnet_nuget_internal"+ for d in deps+ )++ def test_external_nuget_does_not_emit_cross_repo_dep(self, tmp_path: Path) -> None:+ repos = self._two_repo_workspace(tmp_path)+ (repos["api"] / "src" / "Api" / "Api.csproj").write_text(+ _csproj(packages=["Newtonsoft.Json"])+ )+ deps = _scan_csproj(repos["api"], repos, alias="api")+ assert not any(d.kind == "dotnet_nuget_internal" for d in deps)++ def test_detect_package_dependencies_includes_csproj_scanner(self, tmp_path: Path) -> None:+ repos = self._two_repo_workspace(tmp_path)+ (repos["api"] / "src" / "Api" / "Api.csproj").write_text(+ _csproj(deps=[r"..\..\..\shared-libs\src\Common\Common.csproj"])+ )+ deps = detect_package_dependencies(repos)+ kinds = {d.kind for d in deps}+ assert "dotnet_project_ref" in kinds