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
fix(dead-code,graph): cut .NET false-positives, populate symbol-level centrality (#164)
Raghav Chamadiya04ccdfaec95a
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd.py b/packages/cli/src/repowise/cli/commands/update_cmd.pyindex 5c6ca0754..a488da339 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd.py@@ -388,6 +388,24 @@ def update_command(console.print("[yellow]Dry run — no pages regenerated.[/yellow]")return+ # Run partial dead-code analysis up front so both branches can+ # persist its results. Previously this sat below the ``if index_only``+ # short-circuit, which left the closure's reference to+ # ``dead_code_report`` unbound and crashed every ``--index-only`` run.+ dead_code_report = None+ try:+ from repowise.core.analysis.dead_code import DeadCodeAnalyzer++ _analyzer_partial = DeadCodeAnalyzer(graph_builder.graph(), git_meta_map)+ _changed_paths_partial = [fd.path for fd in file_diffs]+ dead_code_report = _analyzer_partial.analyze_partial(_changed_paths_partial)+ if dead_code_report.total_findings:+ console.print(+ f"Dead code findings (partial): [yellow]{dead_code_report.total_findings}[/yellow]"+ )+ except Exception as exc:+ console.print(f"[yellow]Dead code analysis skipped: {exc}[/yellow]")+if index_only:# Refresh graph, git metadata, and dead-code artifacts without# paying for LLM regeneration. Persist what we already computed@@ -441,6 +459,21 @@ def update_command(f"[yellow]Dead-code persist skipped: {exc}[/yellow]")+ # Re-persist graph_nodes so symbol-level PageRank /+ # betweenness / community ids stay in sync with the+ # current graph build. Without this, ``repowise update``+ # leaves stale per-symbol metrics from the original init+ # and the UI shows "Not indexed in graph" for every+ # symbol on existing repos.+ try:+ from repowise.core.pipeline.persist import persist_graph_nodes++ await persist_graph_nodes(session, repo_id, graph_builder)+ except Exception as exc:+ console.print(+ f"[yellow]Graph nodes persist skipped: {exc}[/yellow]"+ )+run_async(_persist_index_only())save_state(repo_path, {**state, "last_sync_commit": head})elapsed = time.monotonic() - start@@ -482,20 +515,7 @@ def update_command(cost_tracker = CostTracker()provider._cost_tracker = cost_tracker- # Run partial dead code analysis on affected files- dead_code_report = None- try:- from repowise.core.analysis.dead_code import DeadCodeAnalyzer-- analyzer = DeadCodeAnalyzer(graph_builder.graph(), git_meta_map)- changed_paths = [fd.path for fd in file_diffs]- dead_code_report = analyzer.analyze_partial(changed_paths)- if dead_code_report.total_findings:- console.print(- f"Dead code findings (partial): [yellow]{dead_code_report.total_findings}[/yellow]"- )- except Exception as exc:- console.print(f"[yellow]Dead code analysis skipped: {exc}[/yellow]")+ # (dead_code_report computed above, before the index-only branch)# Re-scan changed files for inline decision markersnew_decision_markers: list = []@@ -621,6 +641,18 @@ def update_command(except Exception:pass # dead code persistence is best-effort+ # Re-persist graph_nodes so symbol-level PageRank / betweenness+ # / community ids reflect the current build. Same rationale as+ # the index-only branch above — without this every per-symbol+ # metric stays at its original value forever.+ try:+ from repowise.core.pipeline.persist import persist_graph_nodes++ async with get_session(sf) as session:+ await persist_graph_nodes(session, repo_id, graph_builder)+ except Exception:+ pass # graph node persistence is best-effort+# Record a GenerationJob so the web UI "last synced" timestamp updatestry:from datetime import datetime, UTC as _UTCdiff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.pyindex 3c5045370..33eb04d14 100644--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py@@ -22,9 +22,40 @@ from .constants import (_DEFAULT_DYNAMIC_PATTERNS,_FRAMEWORK_DECORATORS,_NEVER_FLAG_PATTERNS,+ _NEVER_PACKAGE_DIRS,_NON_CODE_LANGUAGES,_is_fixture_path,)++# Symbol kinds that cannot be independently imported by name in any+# supported language. Flagging them as "unused exports" is a guaranteed+# false-positive — they're always accessed through an enclosing class /+# namespace. C# auto-properties land in the graph as ``variable``;+# fields / enum members / type aliases / namespace anchors share the+# same property.+_NON_IMPORTABLE_SYMBOL_KINDS: frozenset[str] = frozenset({+ "method",+ "variable",+ "field",+ "property",+ "enum_member",+ "constant",+ "type_alias",+ "namespace",+ "module",+})++# Symbol names that are language-runtime entry points or compiler-implicit+# anchors — never invoked by user-authored callers, never dead.+_ENTRY_POINT_SYMBOL_NAMES: frozenset[str] = frozenset({+ "Main", # C#, Java, Kotlin, Go, Rust, Swift, Scala+ "main", # most others+ "MauiProgram", # .NET MAUI+ "Program", # C# top-level / classic console+ "Startup", # ASP.NET Core legacy+ "__module__", # synthetic per-file module anchor+ "_start", # C runtime+})from .dynamic_markers import find_dynamic_edge_files, find_dynamic_import_filesfrom .models import DeadCodeFindingData, DeadCodeKind, DeadCodeReport@@ -305,6 +336,20 @@ class DeadCodeAnalyzer:file_has_importers = self.graph.in_degree(node) > 0+ # Dynamic-use edges (DI registration, reflection, event bus+ # subscriptions, framework-mediated loading) target a file+ # as a whole — the runtime resolves the class and reaches+ # any public member. Treat the whole file as live so we+ # don't flag e.g. ``BasketService`` (registered via+ # ``MapGrpcService<BasketService>()``) as an unused export.+ file_dynamically_loaded = any(+ self.graph.get_edge_data(pred, node, {}).get("edge_type")+ in ("dynamic_uses", "dynamic", "framework")+ for pred in self.graph.predecessors(node)+ )+ if file_dynamically_loaded:+ continue+# Function/method line ranges in this file — used to skip symbols# whose definition is nested inside another function (closures,# inner helpers). Such symbols are only reachable from their@@ -321,14 +366,22 @@ class DeadCodeAnalyzer:continuesym_name = sym.get("name", "")- # Methods are not independently importable — they're attribute- # access on an instance — so flagging them as unused-exports- # produces guaranteed false positives. Same for dunders, which- # are invoked by the language runtime, not by name lookup.- if sym.get("kind") == "method":+ # Skip symbol kinds that can't be independently imported+ # (methods, properties, fields, enum members, namespace+ # anchors). They're always reached through their enclosing+ # class / module, so the unused-export pass can't observe+ # their real usage and would report guaranteed false+ # positives. C# auto-properties surface here as ``variable``.+ if sym.get("kind") in _NON_IMPORTABLE_SYMBOL_KINDS:continueif sym_name.startswith("__") and sym_name.endswith("__"):continue+ if sym_name in _ENTRY_POINT_SYMBOL_NAMES:+ continue+ # Names that contain a dot are namespace path fragments+ # (e.g. ``eShop.ClientApp``), not user-visible exports.+ if "." in sym_name:+ continue# Skip nested defs: a symbol whose start_line falls strictly# inside another function/method's body cannot be imported@@ -435,6 +488,14 @@ class DeadCodeAnalyzer:sym_name = node_data.get("name", "")if sym_name.startswith("__") and sym_name.endswith("__"):continue+ if sym_name in _ENTRY_POINT_SYMBOL_NAMES:+ continue+ # Namespace-path fragments (e.g. ``eShop.ClientApp``) and+ # non-callable kinds bypass the call-edge pass by design.+ if "." in sym_name:+ continue+ if node_data.get("kind") in _NON_IMPORTABLE_SYMBOL_KINDS:+ continueif self._name_matches_dynamic(sym_name, dynamic_patterns):continue@@ -494,6 +555,20 @@ class DeadCodeAnalyzer:for pkg, files in packages.items():if pkg in whitelist:continue+ # Skip known non-package dirs (.github, .vscode, docs, ...)+ # and any other dotfile directory at the repo root.+ if pkg in _NEVER_PACKAGE_DIRS or pkg.startswith("."):+ continue+ # A real package contains at least one source-code file. If+ # every file under the candidate dir is config/data (YAML,+ # JSON, MD, TOML), it is not a package — it is metadata.+ has_code_file = any(+ self.graph.nodes.get(f, {}).get("language", "unknown")+ not in _NON_CODE_LANGUAGES+ for f in files+ )+ if not has_code_file:+ continuehas_external_importers = Falsefor f in files:diff --git a/packages/core/src/repowise/core/analysis/dead_code/constants.py b/packages/core/src/repowise/core/analysis/dead_code/constants.pyindex 59895fbfc..8bf96bb09 100644--- a/packages/core/src/repowise/core/analysis/dead_code/constants.py+++ b/packages/core/src/repowise/core/analysis/dead_code/constants.py@@ -57,6 +57,46 @@ _NEVER_FLAG_PATTERNS: tuple[str, ...] = ("*/default.tsx",# Nuxt route pages"*/pages/*.vue",+ # ---- .NET / C# conventions --------------------------------------+ # Implicit / generated / framework-loaded files that have no+ # static importers by design.+ "*GlobalUsings.cs", # global usings — file-implicit, never imported by symbol+ "*.xaml.cs", # XAML code-behind, wired by the source generator+ "*.xaml",+ "*.razor",+ "*.razor.cs", # Blazor code-behind+ "*.razor.js", # Blazor JS interop side-files+ "*.cshtml",+ "*.cshtml.cs",+ "*.designer.cs", # Roslyn designer+ "*Designer.cs",+ "*.g.cs", # Roslyn-generated+ "*.g.i.cs",+ "*.AssemblyInfo.cs",+ "*MauiProgram.cs", # MAUI app entry — invoked by host, not imported+ "*App.xaml.cs",+ "*AppShell.xaml.cs",+ # Aspire / ServiceDefaults host wiring is consumed by AppHost project graph,+ # not by C# `using` directives.+ "*AppHost*.cs",+ "*ServiceDefaults*.cs",+ # Integration events + EF entity configurations are loaded reflectively+ # by event-bus subscribers and EF model builder respectively.+ "*IntegrationEvent.cs",+ "*IntegrationEvents/Events/*.cs",+ "*EntityConfigurations/*.cs",+ "*EntityTypeConfiguration.cs",+ # gRPC generated artifacts.+ "*.pb.cs",+ "*Grpc.cs",+ # Minimal-API endpoint modules — ASP.NET Core convention. These+ # static classes expose extension methods like ``MapCatalogApi``+ # that are wired by ``app.MapCatalogApi()`` in ``Program.cs``. The+ # static call doesn't currently land in the import graph, so without+ # an explicit pass these read as orphaned every time.+ "*/Apis/*.cs",+ "*/Endpoints/*.cs",+ "*/Routes/*.cs",)# Decorator patterns that indicate framework usage (route handlers, fixtures, etc.)@@ -126,6 +166,40 @@ _DEFAULT_DYNAMIC_PATTERNS: tuple[str, ...] = ("*_task",)+# Top-level directories that are NOT packages — they're configuration,+# CI, docs, or platform metadata. The zombie-package detector splits paths+# on the first segment and treats everything as a candidate package; without+# this guard, dotfile dirs like `.github` get reported as "zombie packages+# with no importers" on every repo.+_NEVER_PACKAGE_DIRS: frozenset[str] = frozenset({+ ".github",+ ".gitlab",+ ".vscode",+ ".idea",+ ".aspire",+ ".config",+ ".devcenter",+ ".devcontainer",+ ".husky",+ ".changeset",+ ".azure",+ ".azuredevops",+ ".circleci",+ ".buildkite",+ ".cargo",+ ".husky",+ ".yarn",+ "docs",+ "doc",+ "documentation",+ "examples",+ "scripts",+ "assets",+ "static",+ "public",+})++# Path segments that indicate test fixture / sample data directories._FIXTURE_PATH_SEGMENTS: tuple[str, ...] = ("fixture",diff --git a/packages/core/src/repowise/core/generation/editor_files/tech_stack.py b/packages/core/src/repowise/core/generation/editor_files/tech_stack.pyindex a8e5f7805..a42dd2379 100644--- a/packages/core/src/repowise/core/generation/editor_files/tech_stack.py+++ b/packages/core/src/repowise/core/generation/editor_files/tech_stack.py@@ -66,23 +66,49 @@ def detect_tech_stack(repo_path: Path) -> list[TechStackItem]:items[name] = TechStackItem(name=name, version=version, category=category)# --- package.json (Node.js) ---+ # Many .NET / Python / Go repos drop a package.json at the root for+ # tooling like Playwright or Husky without being Node.js applications.+ # We only register Node.js as a language when there is real evidence+ # of a Node.js runtime: a ``main``/``bin`` field, runtime+ # ``dependencies``, or a known framework dep.pkg_json = repo_path / "package.json"+ pkg: dict[str, object] | None = Noneif pkg_json.exists():try:pkg = json.loads(pkg_json.read_text(encoding="utf-8"))- # Detect Node version from engines field- node_ver = pkg.get("engines", {}).get("node")+ except Exception:+ pkg = None++ if isinstance(pkg, dict):+ runtime_deps = pkg.get("dependencies") or {}+ dev_deps = pkg.get("devDependencies") or {}+ all_deps = {**runtime_deps, **dev_deps}+ node_ver = (pkg.get("engines") or {}).get("node") if isinstance(pkg.get("engines"), dict) else None+ # Tooling-only manifests (e.g. .NET / Python repos that drop a+ # package.json for Playwright or Husky) declare no runtime+ # dependencies, no entry-point fields, and no engines hint. We+ # gate the "Node.js" language tag on at least one of those+ # signals to keep them from being labelled Node.js apps.+ has_runtime_signal = bool(+ runtime_deps+ or pkg.get("main")+ or pkg.get("bin")+ or pkg.get("module")+ or pkg.get("exports")+ or node_ver+ )+ has_framework_dep = any(dep_key in all_deps for dep_key in _NODE_FRAMEWORKS)+ if has_runtime_signal or has_framework_dep:add("Node.js", node_ver, "language")- all_deps = {**pkg.get("dependencies", {}), **pkg.get("devDependencies", {})}for dep_key, (display, cat) in _NODE_FRAMEWORKS.items():if dep_key in all_deps:raw = all_deps[dep_key].lstrip("^~>=")add(display, raw or None, cat)- if "typescript" in all_deps or (repo_path / "tsconfig.json").exists():- ts_ver = all_deps.get("typescript", "").lstrip("^~>=") or None- add("TypeScript", ts_ver, "language")- except Exception:- pass+ # TypeScript can be added independently — many monorepos only use+ # TS via tsconfig.json without depending on a Node.js runtime.+ if "typescript" in all_deps or (repo_path / "tsconfig.json").exists():+ ts_ver = all_deps.get("typescript", "").lstrip("^~>=") or None+ add("TypeScript", ts_ver, "language")# --- pyproject.toml / setup.py (Python) ---pyproject = repo_path / "pyproject.toml"@@ -141,6 +167,53 @@ def detect_tech_stack(repo_path: Path) -> list[TechStackItem]:elif "laravel/framework" in requires:add("Laravel", None, "framework")+ # --- .NET / C# (.csproj / .sln / Directory.Build.props) ---+ # Walk one level deep so multi-project solutions like eShop register.+ csproj_files = list(repo_path.glob("*.csproj")) + list(repo_path.glob("*/*.csproj"))+ sln_files = list(repo_path.glob("*.sln"))+ has_directory_build = (repo_path / "Directory.Build.props").exists() or (+ repo_path / "Directory.Packages.props"+ ).exists()+ if csproj_files or sln_files or has_directory_build:+ # Pull TargetFramework from the first .csproj — captures net9.0,+ # net8.0, etc. Best-effort regex; the .csproj XML is small so a+ # full parser would be overkill.+ target_fw: str | None = None+ for csproj in csproj_files[:3]:+ try:+ ctext = csproj.read_text(encoding="utf-8", errors="ignore")+ except OSError:+ continue+ m = re.search(+ r"<TargetFrameworks?>\s*([^<;]+)", ctext+ )+ if m:+ target_fw = m.group(1).strip()+ break+ add("C#", target_fw, "language")+ add(".NET", target_fw, "framework")+ # Common .NET stack indicators read from any .csproj text.+ joined_csproj = ""+ for csproj in csproj_files[:20]:+ try:+ joined_csproj += csproj.read_text(encoding="utf-8", errors="ignore")+ except OSError:+ continue+ if "Microsoft.AspNetCore" in joined_csproj:+ add("ASP.NET Core", None, "framework")+ if "Microsoft.EntityFrameworkCore" in joined_csproj:+ add("Entity Framework Core", None, "database")+ if "Aspire.Hosting" in joined_csproj or any(+ "AppHost" in p.stem for p in csproj_files+ ):+ add(".NET Aspire", None, "infra")+ if "Grpc.AspNetCore" in joined_csproj or "Google.Protobuf" in joined_csproj:+ add("gRPC", None, "framework")+ if "MAUI" in joined_csproj.upper() or any(+ "Maui" in p.stem for p in csproj_files+ ):+ add(".NET MAUI", None, "framework")+# --- Docker ---if (repo_path / "Dockerfile").exists():add("Docker", None, "infra")diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/dotnet.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/dotnet.pyindex b6036cbbd..7c4db5827 100644--- a/packages/core/src/repowise/core/ingestion/dynamic_hints/dotnet.py+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/dotnet.py@@ -26,8 +26,33 @@ from .base import DynamicEdge, DynamicHintExtractor_SKIP_DIRS = {"bin", "obj", ".vs", "node_modules", ".git", "packages"}# services.AddScoped<IFoo, Foo>() / AddSingleton<...> / AddTransient<...>+# Also matches the framework-specific registration helpers that wire up+# concrete types at runtime: EF Core DbContexts, gRPC services, SignalR+# hubs, typed HttpClients, options, and middleware. Each of those+# patterns hands a closed generic type to the runtime which then loads+# the named class — without recording the edge here, the dead-code+# analyser sees the registered type as having no importers._DI_GENERIC_RE = re.compile(- r"\.\s*Add(?:Scoped|Singleton|Transient|HostedService)\s*<\s*([\w.]+)\s*(?:,\s*([\w.]+)\s*)?>"+ r"\.\s*(?:Add|Map|Use)"+ r"(?:Scoped|Singleton|Transient|HostedService"+ r"|DbContext(?:Pool|Factory)?"+ r"|HttpClient|Options"+ r"|GrpcService|GrpcClient|Hub|SignalR"+ r"|Controllers?"+ r"|Middleware)"+ r"\s*<\s*([\w.]+)\s*(?:,\s*([\w.]+)\s*)?>"+)++# Configure<TOptions>(...) — options binding, very common in ASP.NET+# Core. Same shape as DI registration: argument type is the consumer.+_CONFIGURE_RE = re.compile(r"\.\s*Configure\s*<\s*([\w.]+)\s*>")++# eventBus.Subscribe<TIntegrationEvent, THandler>() and the matching+# UnsubscribeDynamic / SubscribeDynamic forms used by integration+# event buses (RabbitMQ, EventBus). Drives consumer wiring across+# microservices that the static graph never sees.+_EVENT_BUS_SUBSCRIBE_RE = re.compile(+ r"\.\s*(?:Un)?Subscribe(?:Dynamic)?\s*<\s*([\w.]+)\s*(?:,\s*([\w.]+)\s*)?>")# Activator.CreateInstance(typeof(Foo)) / Activator.CreateInstance("Acme.Foo")@@ -51,11 +76,17 @@ class DotNetDynamicHints(DynamicHintExtractor):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] = {}+ # Build a class-name → list-of-files index in one pass so the+ # regex hits below can resolve target file paths cheaply. A+ # short type name can map to multiple files when projects+ # legitimately reuse names across namespaces (e.g. eShop has+ # ``Basket.API/Grpc/BasketService.cs`` and+ # ``WebApp/Services/BasketService.cs``). Collisions are common+ # in microservice repos, so we emit dynamic edges to *every*+ # candidate rather than picking the first match — pruning false+ # positives is the dead-code analyser's job, but missing edges+ # cause real services to be flagged dead with high confidence.+ type_to_files: dict[str, list[str]] = {}cs_files: list[tuple[Path, str]] = [] # (path, text)repo_root_resolved = repo_root.resolve()for cs in repo_root.rglob("*.cs"):@@ -71,18 +102,21 @@ class DotNetDynamicHints(DynamicHintExtractor):continuerel = rel_path.as_posix()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)+ bucket = type_to_files.setdefault(name, [])+ if rel not in bucket:+ bucket.append(rel)def _short(name: str) -> str:return name.rsplit(".", 1)[-1]+ def _files_for(name: str) -> list[str]:+ return type_to_files.get(_short(name), [])+for cs, text in cs_files:try:rel = cs.resolve().relative_to(repo_root.resolve()).as_posix()@@ -91,75 +125,130 @@ class DotNetDynamicHints(DynamicHintExtractor):# ---- 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+ first = match.group(1)+ second = 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 typetarget_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",+ for target in _files_for(target_name):+ if 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:+ iface_targets = _files_for(first)+ impl_targets = _files_for(second)+ for iface_target in iface_targets:+ for impl_target in impl_targets:+ if 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",+ )+ )++ # ---- Configure<TOptions>(section) ----+ for match in _CONFIGURE_RE.finditer(text):+ for target in _files_for(match.group(1)):+ if target != rel:+ edges.append(+ DynamicEdge(+ source=rel,+ target=target,+ edge_type="dynamic_uses",+ hint_source=f"{self.name}:configure_options",+ )+ )++ # ---- eventBus.Subscribe<TEvent, THandler>() ----+ for match in _EVENT_BUS_SUBSCRIBE_RE.finditer(text):+ event_targets = _files_for(match.group(1))+ handler_targets = (+ _files_for(match.group(2)) if match.group(2) else []+ )+ for tgt in event_targets:+ if tgt != rel:+ edges.append(+ DynamicEdge(+ source=rel,+ target=tgt,+ edge_type="dynamic_uses",+ hint_source=f"{self.name}:subscribe_event",+ )+ )+ for tgt in handler_targets:+ if tgt != rel:edges.append(DynamicEdge(- source=iface_target,- target=impl_target,+ source=rel,+ target=tgt,edge_type="dynamic_uses",- hint_source=f"{self.name}:di_interface_to_impl",+ hint_source=f"{self.name}:subscribe_handler",))+ # Link each event type to its handler so dead-code+ # analysis sees handler classes as reached.+ for evt in event_targets:+ for hdl in handler_targets:+ if evt != hdl:+ edges.append(+ DynamicEdge(+ source=evt,+ target=hdl,+ edge_type="dynamic_uses",+ hint_source=f"{self.name}:event_to_handler",+ )+ )# ---- 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",+ for target in _files_for(match.group(1)):+ if 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",+ for target in _files_for(match.group(1)):+ if 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",+ for target in _files_for(match.group(1)):+ if 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):diff --git a/packages/core/src/repowise/core/ingestion/graph.py b/packages/core/src/repowise/core/ingestion/graph.pyindex 26202ea51..3f02372a7 100644--- a/packages/core/src/repowise/core/ingestion/graph.py+++ b/packages/core/src/repowise/core/ingestion/graph.py@@ -107,6 +107,8 @@ class GraphBuilder:self._community_algo: str = ""self._pagerank_cache: dict[str, float] | None = Noneself._betweenness_cache: dict[str, float] | None = None+ self._symbol_pagerank_cache: dict[str, float] | None = None+ self._symbol_betweenness_cache: dict[str, float] | None = Noneself._execution_flow_cache: Any | None = Nonedef set_tsconfig_resolver(self, resolver: Any) -> None:@@ -200,6 +202,8 @@ class GraphBuilder:self._community_algo = ""self._pagerank_cache = Noneself._betweenness_cache = None+ self._symbol_pagerank_cache = None+ self._symbol_betweenness_cache = Noneself._execution_flow_cache = None# Clear import/call edges but keep structural edges (defines, has_method)@@ -500,6 +504,8 @@ class GraphBuilder:await _asyncio.gather(_asyncio.to_thread(self.pagerank),_asyncio.to_thread(self.betweenness_centrality),+ _asyncio.to_thread(self.symbol_pagerank),+ _asyncio.to_thread(self.symbol_betweenness_centrality),_asyncio.to_thread(self.community_detection),_asyncio.to_thread(self.symbol_communities),)@@ -762,6 +768,67 @@ class GraphBuilder:self._pagerank_cache = {node: 1.0 / n for node in filtered.nodes()}return self._pagerank_cache+ def symbol_subgraph(self) -> nx.DiGraph:+ """Return a subgraph of symbol nodes connected by call + heritage edges.++ File-to-symbol ``defines`` edges and class-to-method ``has_method``+ ownership edges are dropped so that the resulting centrality+ scores reflect call/heritage flow rather than containment.+ """+ g = self.graph()+ symbol_nodes = [+ n for n, d in g.nodes(data=True) if d.get("node_type") == "symbol"+ ]+ sub = g.subgraph(symbol_nodes).copy()+ edges_to_remove = [+ (u, v)+ for u, v, d in sub.edges(data=True)+ if d.get("edge_type") not in ("calls", "extends", "implements")+ ]+ sub.remove_edges_from(edges_to_remove)+ return sub++ def symbol_pagerank(self, alpha: float = 0.85) -> dict[str, float]:+ """Return PageRank scores for symbol nodes only (cached).++ Computed on the call/heritage symbol subgraph — this is what the+ UI's per-symbol "graph metrics" panel reads. Without it every+ symbol shows ``Not indexed in graph``.+ """+ if self._symbol_pagerank_cache is not None:+ return self._symbol_pagerank_cache+ sub = self.symbol_subgraph()+ if sub.number_of_nodes() == 0:+ self._symbol_pagerank_cache = {}+ return self._symbol_pagerank_cache+ try:+ self._symbol_pagerank_cache = nx.pagerank(sub, alpha=alpha)+ except nx.PowerIterationFailedConvergence:+ log.warning("Symbol PageRank did not converge, using uniform scores")+ n = sub.number_of_nodes()+ self._symbol_pagerank_cache = {node: 1.0 / n for node in sub.nodes()}+ return self._symbol_pagerank_cache++ def symbol_betweenness_centrality(self) -> dict[str, float]:+ """Return betweenness centrality for symbol nodes (cached)."""+ if self._symbol_betweenness_cache is not None:+ return self._symbol_betweenness_cache+ sub = self.symbol_subgraph()+ n = sub.number_of_nodes()+ if n == 0:+ self._symbol_betweenness_cache = {}+ return self._symbol_betweenness_cache+ if n > _LARGE_REPO_THRESHOLD:+ k = min(500, n)+ self._symbol_betweenness_cache = nx.betweenness_centrality(+ sub, k=k, normalized=True+ )+ else:+ self._symbol_betweenness_cache = nx.betweenness_centrality(+ sub, normalized=True+ )+ return self._symbol_betweenness_cache+def _build_scc_map(self) -> dict[str, int]:"""Assign a numeric SCC ID to each node."""result: dict[str, int] = {}diff --git a/packages/core/src/repowise/core/ingestion/languages/registry.py b/packages/core/src/repowise/core/ingestion/languages/registry.pyindex 78f0b7789..8ba177e7a 100644--- a/packages/core/src/repowise/core/ingestion/languages/registry.py+++ b/packages/core/src/repowise/core/ingestion/languages/registry.py@@ -684,7 +684,13 @@ _SPECS: tuple[LanguageSpec, ...] = ("record_declaration",}),- entry_point_patterns=("Program.cs", "Startup.cs"),+ entry_point_patterns=(+ "Program.cs",+ "Startup.cs",+ "MauiProgram.cs", # .NET MAUI host bootstrap+ "Main.cs", # Tizen / classic console entry+ "App.xaml.cs", # WPF / WinUI / MAUI app shell+ ),manifest_files=("Directory.Build.props","Directory.Build.targets",diff --git a/packages/core/src/repowise/core/pipeline/orchestrator.py b/packages/core/src/repowise/core/pipeline/orchestrator.pyindex 6805911fe..30fdfa8ab 100644--- a/packages/core/src/repowise/core/pipeline/orchestrator.py+++ b/packages/core/src/repowise/core/pipeline/orchestrator.py@@ -569,6 +569,8 @@ async def _run_ingestion(await asyncio.gather(asyncio.to_thread(graph_builder.pagerank),asyncio.to_thread(graph_builder.betweenness_centrality),+ asyncio.to_thread(graph_builder.symbol_pagerank),+ asyncio.to_thread(graph_builder.symbol_betweenness_centrality),)_phase_done(progress, "graph.metrics")diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.pyindex e54de4b46..87e239fea 100644--- a/packages/core/src/repowise/core/pipeline/persist.py+++ b/packages/core/src/repowise/core/pipeline/persist.py@@ -15,64 +15,29 @@ import structloglogger = structlog.get_logger(__name__)-async def persist_pipeline_result(- result: Any,+async def persist_graph_nodes(session: Any,repo_id: str,+ graph_builder: Any,+ ep_scores: dict[str, float] | None = None,) -> None:- """Persist all outputs from a :class:`PipelineResult` into the database.-- Parameters- ----------- result:- A ``PipelineResult`` from ``run_pipeline()``.- session:- An active SQLAlchemy ``AsyncSession`` (caller manages commit/rollback).- repo_id:- The repository ID to associate all records with.-- Note- ----- FTS indexing is intentionally excluded here — callers must do it after- this session closes to avoid SQLite write-lock conflicts.+ """Persist file- and symbol-level graph nodes with full centrality metrics.- This function mutates ``sym.file_path`` on parsed-file symbols that- lack one. Callers should treat *result* as consumed after this call.+ Lifted out of :func:`persist_pipeline_result` so the incremental+ update path can refresh ``graph_nodes`` (including symbol-level+ PageRank / betweenness) without constructing a full ``PipelineResult``."""- from repowise.core.persistence import (- batch_upsert_graph_edges,- batch_upsert_graph_nodes,- batch_upsert_symbols,- upsert_page_from_generated,- )- from repowise.core.persistence.crud import (- bulk_upsert_decisions,- recompute_decision_staleness,- save_dead_code_findings,- upsert_git_metadata_bulk,- )-- # ---- Pages (if generated) ------------------------------------------------ if result.generated_pages:- for page in result.generated_pages:- await upsert_page_from_generated(session, page, repo_id)-- # ---- Graph nodes ---------------------------------------------------------- graph = result.graph_builder.graph()- pr = result.graph_builder.pagerank()- bc = result.graph_builder.betweenness_centrality()- cd = result.graph_builder.community_detection()- sc = result.graph_builder.symbol_communities()- ci = result.graph_builder.community_info()-- # Entry point scores from execution flow analysis- ep_scores: dict[str, float] = {}- if result.execution_flow_report and getattr(result.execution_flow_report, "flows", None):- ep_scores = {- f.entry_point_id: f.entry_point_score- for f in result.execution_flow_report.flows- if hasattr(f, "entry_point_id") and hasattr(f, "entry_point_score")- }+ from repowise.core.persistence import batch_upsert_graph_nodes++ graph = graph_builder.graph()+ pr = graph_builder.pagerank()+ bc = graph_builder.betweenness_centrality()+ sym_pr = graph_builder.symbol_pagerank()+ sym_bc = graph_builder.symbol_betweenness_centrality()+ cd = graph_builder.community_detection()+ sc = graph_builder.symbol_communities()+ ci = graph_builder.community_info()+ ep_scores = ep_scores or {}nodes = []for node_id in graph.nodes:@@ -87,12 +52,14 @@ async def persist_pipeline_result("has_error": data.get("has_error", False),"is_test": data.get("is_test", False),"is_entry_point": data.get("is_entry_point", False),- "pagerank": pr.get(node_id, 0.0),- "betweenness": bc.get(node_id, 0.0),+ # Files draw from the file-level metric tables; symbols fall+ # back to the symbol subgraph (calls + heritage) so that the+ # per-symbol UI panel shows real centrality instead of 0.+ "pagerank": pr.get(node_id, sym_pr.get(node_id, 0.0)),+ "betweenness": bc.get(node_id, sym_bc.get(node_id, 0.0)),"community_id": cd.get(node_id, 0),}- # Community metadatacommunity_meta: dict[str, Any] = {}if node_type == "file":cid = cd.get(node_id, 0)@@ -110,7 +77,6 @@ async def persist_pipeline_result(community_meta["entry_point_score"] = ep_scores[node_id]node_dict["community_meta_json"] = json.dumps(community_meta)- # Symbol-specific fieldsif node_type == "symbol":node_dict.update({@@ -125,12 +91,66 @@ async def persist_pipeline_result("parent_symbol_id": data.get("parent_name"),})-nodes.append(node_dict)+if nodes:await batch_upsert_graph_nodes(session, repo_id, nodes)++async def persist_pipeline_result(+ result: Any,+ session: Any,+ repo_id: str,+) -> None:+ """Persist all outputs from a :class:`PipelineResult` into the database.++ Parameters+ ----------+ result:+ A ``PipelineResult`` from ``run_pipeline()``.+ session:+ An active SQLAlchemy ``AsyncSession`` (caller manages commit/rollback).+ repo_id:+ The repository ID to associate all records with.++ Note+ ----+ FTS indexing is intentionally excluded here — callers must do it after+ this session closes to avoid SQLite write-lock conflicts.++ This function mutates ``sym.file_path`` on parsed-file symbols that+ lack one. Callers should treat *result* as consumed after this call.+ """+ from repowise.core.persistence import (+ batch_upsert_graph_edges,+ batch_upsert_graph_nodes,+ batch_upsert_symbols,+ upsert_page_from_generated,+ )+ from repowise.core.persistence.crud import (+ bulk_upsert_decisions,+ recompute_decision_staleness,+ save_dead_code_findings,+ upsert_git_metadata_bulk,+ )++ # ---- Pages (if generated) -----------------------------------------------+ if result.generated_pages:+ for page in result.generated_pages:+ await upsert_page_from_generated(session, page, repo_id)++ # ---- Graph nodes ---------------------------------------------------------+ ep_scores: dict[str, float] = {}+ if result.execution_flow_report and getattr(result.execution_flow_report, "flows", None):+ ep_scores = {+ f.entry_point_id: f.entry_point_score+ for f in result.execution_flow_report.flows+ if hasattr(f, "entry_point_id") and hasattr(f, "entry_point_score")+ }+ await persist_graph_nodes(session, repo_id, result.graph_builder, ep_scores)+# ---- Graph edges ---------------------------------------------------------+ graph = result.graph_builder.graph()edges = []for u, v, data in graph.edges(data=True):edges.append(