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(workspace): share one route recogniser with go, laravel and axum (#1867)
Raghav Chamadiyad0946ee40b88
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/express.py b/packages/core/src/repowise/core/ingestion/framework_edges/express.pyindex 20f231c5e..9fa69f9b5 100644--- a/packages/core/src/repowise/core/ingestion/framework_edges/express.py+++ b/packages/core/src/repowise/core/ingestion/framework_edges/express.py@@ -8,7 +8,7 @@ from __future__ import annotationsimport refrom typing import TYPE_CHECKING, Any-from ..framework_routes import express_routes+from ..framework_routes import express_routes, match_parenfrom ..resolvers import ResolverContextfrom .base import (DetectionContext,@@ -36,26 +36,6 @@ _STRING_LITERAL_RE = re.compile(r"'(?:[^'\\]|\\.)*'|\"(?:[^\"\\]|\\.)*\"|`(?:[^`_ARG_IDENT_RE = re.compile(r"[A-Za-z_$][\w$]*")-def _match_paren(text: str, open_idx: int) -> int:- depth = 0- i = open_idx- n = len(text)- while i < n:- c = text[i]- if c in "\"'`":- i += 1- while i < n and text[i] != c:- i += 2 if text[i] == "\\" else 1- elif c == "(":- depth += 1- elif c == ")":- depth -= 1- if depth == 0:- return i- i += 1- return -1--def _has_express_imports(parsed_files: dict[str, Any]) -> bool:for parsed in parsed_files.values():if parsed.file_info.language not in ("typescript", "javascript"):@@ -104,7 +84,7 @@ def _add_express_edges(for route in express_routes(text):if route.receiver not in receivers:continue- close = _match_paren(text, route.paren_offset)+ close = match_paren(text, route.paren_offset)if close == -1:continuearg_blob = _STRING_LITERAL_RE.sub(diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/go.py b/packages/core/src/repowise/core/ingestion/framework_edges/go.pyindex e5d402d8a..6d2b5c911 100644--- a/packages/core/src/repowise/core/ingestion/framework_edges/go.py+++ b/packages/core/src/repowise/core/ingestion/framework_edges/go.py@@ -6,7 +6,9 @@ Covers the route/handler wiring that carries no import edge:* **stdlib ``net/http``** — ``http.HandleFunc("/path", handler)`` and``mux.Handle("/path", handler)`` (same ``.HandleFunc`` / ``.Handle``selector shape as the router frameworks, so one regex serves both —- the only difference is which import gates emission).+ the only difference is which import gates emission). The recogniser lives in+ ``ingestion.framework_routes``, shared with the contract extractor that reads+ the same call for its path.* **gRPC** — ``pb.RegisterXxxServer(s, &impl{})`` connects the registrationsite to the file defining the server implementation type.@@ -19,6 +21,7 @@ from __future__ import annotationsimport refrom typing import TYPE_CHECKING, Any+from ..framework_routes import go_routesfrom ..resolvers import ResolverContextfrom .base import (DetectionContext,@@ -42,11 +45,6 @@ _GO_ROUTER_PKG_PATTERNS = (# the ``.HandleFunc`` / ``.Handle`` selector shape with the router frameworks._GO_HTTP_PKG = "net/http"-_GO_ROUTE_CALL_RE = re.compile(- r"\.\s*(?:GET|POST|PUT|DELETE|PATCH|OPTIONS|HEAD|HandleFunc|Handle|Any)"- r"\s*\(\s*[\"'][^\"']*[\"']\s*,\s*([\w.]+)"-)-# gRPC generated registration: ``pb.RegisterGreeterServer(s, &greeter{})`` or# ``RegisterGreeterServer(srv, impl)``. Capture the implementation argument# (the second positional arg); we resolve its leading type identifier.@@ -94,9 +92,12 @@ def _add_go_route_edges(if not text:continue- for m in _GO_ROUTE_CALL_RE.finditer(text):- handler = m.group(1)- targets = _resolve_go_handler(handler, parsed, func_to_files, class_to_file)+ for route in go_routes(text):+ if not route.handler:+ continue # an inline `func(c *gin.Context)` names nothing to link to+ targets = _resolve_go_handler(+ route.handler, parsed, func_to_files, class_to_file+ )for target in targets:if target != path and target in path_set and _add_edge_if_new(graph, path, target):count += 1diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/laravel.py b/packages/core/src/repowise/core/ingestion/framework_edges/laravel.pyindex d05694f70..8f2fe0d40 100644--- a/packages/core/src/repowise/core/ingestion/framework_edges/laravel.py+++ b/packages/core/src/repowise/core/ingestion/framework_edges/laravel.py@@ -1,6 +1,8 @@"""Laravel routes / service-provider / Eloquent convention edges.-Split out of ``framework_edges.py`` (PR 3.5) — behaviour-preserving move.+Split out of ``framework_edges.py`` (PR 3.5) — behaviour-preserving move. The+``Route::`` recogniser lives in ``ingestion.framework_routes``, shared with the+contract extractor that reads the same call for its path."""from __future__ import annotations@@ -8,6 +10,7 @@ from __future__ import annotationsimport refrom typing import TYPE_CHECKING, Any+from ..framework_routes import laravel_routesfrom ..resolvers import ResolverContextfrom .base import (DetectionContext,@@ -21,15 +24,6 @@ if TYPE_CHECKING:import networkx as nx-_LARAVEL_ROUTE_ARRAY_RE = re.compile(- r"Route::(?:get|post|put|patch|delete|any|match|resource|apiResource)\s*\([^,]*,\s*\[\s*([\w\\]+)::class"-)-_LARAVEL_ROUTE_LEGACY_RE = re.compile(- r"Route::(?:get|post|put|patch|delete|any|match)\s*\([^,]*,\s*['\"]([\w\\]+)@\w+['\"]"-)-_LARAVEL_ROUTE_RESOURCE_RE = re.compile(- r"Route::(?:resource|apiResource)\s*\(\s*['\"][^'\"]+['\"]\s*,\s*([\w\\]+)::class"-)_LARAVEL_BIND_RE = re.compile(r"->\s*(?:bind|singleton|instance)\s*\(\s*([\w\\]+)::class\s*,\s*([\w\\]+)::class")@@ -69,17 +63,14 @@ def _add_laravel_edges(if not text:continueseen_targets: set[str] = set()- for regex in (- _LARAVEL_ROUTE_ARRAY_RE,- _LARAVEL_ROUTE_LEGACY_RE,- _LARAVEL_ROUTE_RESOURCE_RE,- ):- for m in regex.finditer(text):- target = _resolve_laravel_class(ctx, m.group(1), class_to_file, path_set)- if target and target in path_set and target not in seen_targets:- seen_targets.add(target)- if _add_edge_if_new(graph, routes_path, target):- count += 1+ for route in laravel_routes(text):+ if not route.handler:+ continue # a closure route names no controller to link to+ target = _resolve_laravel_class(ctx, route.handler, class_to_file, path_set)+ if target and target in path_set and target not in seen_targets:+ seen_targets.add(target)+ if _add_edge_if_new(graph, routes_path, target):+ count += 1# ---- Service providers → bound classes ----for path, parsed in parsed_files.items():diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/rust.py b/packages/core/src/repowise/core/ingestion/framework_edges/rust.pyindex dc7a5c0cb..416dfba71 100644--- a/packages/core/src/repowise/core/ingestion/framework_edges/rust.py+++ b/packages/core/src/repowise/core/ingestion/framework_edges/rust.py@@ -1,6 +1,10 @@"""Axum / Actix / Rocket (Rust) router convention edges.-Split out of ``framework_edges.py`` (PR 3.5) — behaviour-preserving move.+Split out of ``framework_edges.py`` (PR 3.5) — behaviour-preserving move. The+axum ``.route(...)`` recogniser lives in ``ingestion.framework_routes``, shared+with the contract extractor that reads the same call for its path. Actix's+builder (``web::get().to(h)``) is a different construct from the attribute macro+the contract side reads, so only axum overlaps."""from __future__ import annotations@@ -8,6 +12,7 @@ from __future__ import annotationsimport refrom typing import TYPE_CHECKING, Any+from ..framework_routes import axum_routesfrom ..resolvers import ResolverContextfrom .base import (DetectionContext,@@ -21,10 +26,6 @@ if TYPE_CHECKING:import networkx as nx-_RUST_AXUM_ROUTE_RE = re.compile(- r"\.\s*route\s*\(\s*[\"'][^\"']*[\"']\s*,\s*"- r"(?:get|post|put|delete|patch|head|options|on)\s*\(\s*([\w:]+)\s*\)"-)_RUST_ACTIX_TO_RE = re.compile(r"web::\s*(?:get|post|put|delete|patch|head)\(\)\s*\.\s*to\s*\(\s*([\w:]+)\s*\)")@@ -70,8 +71,14 @@ def _add_rust_router_edges(text = read_text(parsed)if not text:continue+ for route in axum_routes(text):+ if not route.handler:+ continue # a closure or an `on(MethodFilter::GET, ...)` filter+ for target in _resolve(route.handler):+ if target != path and target in path_set and _add_edge_if_new(graph, path, target):+ count += 1+for regex in (- _RUST_AXUM_ROUTE_RE,_RUST_ACTIX_TO_RE,_RUST_ACTIX_SERVICE_RE,_RUST_SCOPE_CONFIGURE_RE,diff --git a/packages/core/src/repowise/core/ingestion/framework_routes.py b/packages/core/src/repowise/core/ingestion/framework_routes.pyindex a62cdd677..b3974c4b5 100644--- a/packages/core/src/repowise/core/ingestion/framework_routes.py+++ b/packages/core/src/repowise/core/ingestion/framework_routes.py@@ -36,6 +36,10 @@ class RouteMatch:handler: str | None # handler argument, when the shape names one identifieroffset: int # match start, for line and nearest-prefix lookupsparen_offset: int # the '(' opening the call, for an argument scan+ #: The handler expression is itself invoked (``api.RequireSession(h)``), so+ #: it names a wrapper. The graph consumer still wants the edge to it; the+ #: contract consumer must not bind a route to its middleware.+ handler_call: bool = False@dataclass(frozen=True)@@ -51,6 +55,22 @@ def _opt(value: str | None) -> str | None:return value or None+def _next_top_level_comma(args: str, *, hash_comments: bool = False) -> int:+ """Index just past the first comma separating *args*, or -1."""+ for i, c, depth in scan_code(args, hash_comments=hash_comments):+ if c == "," and depth == 0:+ return i + 1+ return -1+++def _groups(pattern: re.Pattern[str], content: str) -> Iterator[GroupMatch]:+ """Every ``var``/``parent``/``prefix`` match of *pattern* in *content*."""+ for m in pattern.finditer(content):+ yield GroupMatch(+ var=m.group("var"), parent=_opt(m.group("parent")), prefix=m.group("prefix")+ )++# ---------------------------------------------------------------------------# ASP.NET# ---------------------------------------------------------------------------@@ -102,10 +122,7 @@ def aspnet_routes(content: str) -> Iterator[RouteMatch]:def aspnet_groups(content: str) -> Iterator[GroupMatch]:"""``MapGroup`` prefix bindings in *content*."""- for m in _ASPNET_GROUP_RE.finditer(content):- yield GroupMatch(- var=m.group("var"), parent=_opt(m.group("parent")), prefix=m.group("prefix")- )+ return _groups(_ASPNET_GROUP_RE, content)# ---------------------------------------------------------------------------@@ -144,3 +161,220 @@ def express_routes(content: str) -> Iterator[RouteMatch]:offset=m.start(),paren_offset=m.start("paren"),)+++# ---------------------------------------------------------------------------+# Shared scanning+# ---------------------------------------------------------------------------+++def scan_code(+ text: str, start: int = 0, *, quotes: str = "\"'`", hash_comments: bool = False+) -> Iterator[tuple[int, str, int]]:+ """``(index, char, paren_depth)`` over *text*, skipping strings and comments.++ Route calls run across lines and carry commented-out arguments, so a scanner+ that reads a comment as code is worse than one that reads a line: an+ apostrophe in ``// won't work`` opens a string that never closes.++ *quotes* is what opens a string literal — Rust must pass ``'"'``, because its+ ``'`` is a lifetime. *hash_comments* adds PHP's ``#``, excluding the ``#[``+ of an attribute.+ """+ depth = 0+ i, n = start, len(text)+ while i < n:+ c = text[i]+ if c in quotes:+ i += 1+ while i < n and text[i] != c:+ i += 2 if text[i] == "\\" else 1+ i += 1+ continue+ if c == "/" and i + 1 < n and text[i + 1] == "/":+ i = text.find("\n", i)+ if i == -1:+ return+ continue+ if c == "/" and i + 1 < n and text[i + 1] == "*":+ end = text.find("*/", i + 2)+ if end == -1:+ return+ i = end + 2+ continue+ if hash_comments and c == "#" and text[i + 1 : i + 2] != "[":+ i = text.find("\n", i)+ if i == -1:+ return+ continue+ if c == "(":+ depth += 1+ elif c == ")":+ depth -= 1+ yield i, c, depth+ i += 1+++def match_paren(+ text: str, open_idx: int, *, quotes: str = "\"'`", hash_comments: bool = False+) -> int:+ """Index of the ``)`` closing the ``(`` at *open_idx*, or -1."""+ for i, c, depth in scan_code(text, open_idx, quotes=quotes, hash_comments=hash_comments):+ if c == ")" and depth == 0:+ return i+ return -1+++# ---------------------------------------------------------------------------+# Go — gin / echo / chi routers and stdlib net/http+# ---------------------------------------------------------------------------++# `HandleFunc` precedes `Handle` so the longer name wins the alternation.+_GO_VERBS = "GET|POST|PUT|DELETE|PATCH|OPTIONS|HEAD|Any|HandleFunc|Handle"++# r.GET("/users", GetUsers). The receiver may be empty on an inline chain. The+# handler may be wrapped (`api.RequireSession(h)`) or a composite literal+# (`healthHandler{}`). The two keywords that can open one are excluded: they name+# no symbol, and `r.GET("/x", func(c *gin.Context) {...})` otherwise yields the+# handler `func`.+_GO_ROUTE_RE = re.compile(+ rf"(?P<receiver>\w*)\s*\.\s*(?P<verb>{_GO_VERBS})\s*(?P<paren>\()"+ r"""\s*(?P<q>["'])(?P<path>[^"']*)(?P=q)"""+ r"(?:\s*,\s*(?P<handler>(?!(?:func|struct)\b)[A-Za-z_][\w.]*)\s*(?P<after>[,)({]))?"+)++# api := r.Group("/v1") — groups nest, so the parent is captured for transitive+# composition by `mounts.group_prefixes`.+_GO_GROUP_RE = re.compile(+ r"""(?P<var>\w+)\s*:?=\s*(?P<parent>\w+)\s*\.\s*Group\s*\(\s*["'](?P<prefix>[^"']+)["']"""+)+++def go_routes(content: str) -> Iterator[RouteMatch]:+ """Router and ``net/http`` handler registrations in *content*."""+ for m in _GO_ROUTE_RE.finditer(content):+ yield RouteMatch(+ verb=m.group("verb").upper(),+ path=m.group("path"),+ receiver=_opt(m.group("receiver")),+ handler=m.group("handler"),+ offset=m.start(),+ paren_offset=m.start("paren"),+ handler_call=m.group("after") == "(",+ )+++def go_groups(content: str) -> Iterator[GroupMatch]:+ """``Group`` prefix bindings in *content*."""+ return _groups(_GO_GROUP_RE, content)+++# ---------------------------------------------------------------------------+# Laravel+# ---------------------------------------------------------------------------++# `resource`/`apiResource`/`any`/`match` name no single verb; the contract+# consumer drops them, the graph consumer wants their controller.+_LARAVEL_VERBS = "get|post|put|patch|delete|any|match|resource|apiResource"++_LARAVEL_CALL_RE = re.compile(+ rf"Route::(?P<verb>{_LARAVEL_VERBS})\s*(?P<paren>\()", re.IGNORECASE+)++# The path literal, when the first argument is one. It often is not:+# `Route::post('/hook/'.config('x'), ...)` truncates to the literal head, which+# is what the matcher this replaces recorded too.+_LARAVEL_PATH_RE = re.compile(r"""\s*(?P<q>["'])(?P<path>[^"']*)(?P=q)""")++# Three handler spellings co-exist: the array form, the legacy+# 'Controller@method' string, and the bare `Controller::class` of a resource+# route. The array branch is first so `[C::class, 'm']` is not read as bare.+_LARAVEL_HANDLER_RE = re.compile(+ r"\[\s*(?P<array>[\w\\]+)\s*::\s*class"+ r"""|["'](?P<legacy>[\w\\]+)@\w+["']"""+ r"|(?P<cls>[\w\\]+)\s*::\s*class"+)+++def laravel_routes(content: str) -> Iterator[RouteMatch]:+ """``Route::verb(...)`` registrations in *content*.++ The arguments are delimited by the call's own parens: a route's path is+ routinely a concatenation containing a call of its own, which a scan to the+ next comma reads wrongly and a scan to the next paren stops short of.++ ``handler`` is the controller class only; the member name the array form+ also carries is dropped, since the graph consumer links to the class's file.+ """+ for m in _LARAVEL_CALL_RE.finditer(content):+ close = match_paren(content, m.start("paren"), hash_comments=True)+ if close == -1:+ continue+ args = content[m.end() : close]+ path = _LARAVEL_PATH_RE.match(args)+ # Only past the first top-level comma: the path expression can itself+ # contain `X::class` or a quoted 'word@word', neither of which is the+ # handler (`Route::get(trans('Contact@us'), [PageController::class, ...])`).+ second = _next_top_level_comma(args, hash_comments=True)+ handler = _LARAVEL_HANDLER_RE.search(args, second) if second != -1 else None+ yield RouteMatch(+ verb=m.group("verb").upper(),+ path=path.group("path") or None if path else None,+ receiver=None,+ handler=(+ handler.group("array") or handler.group("legacy") or handler.group("cls")+ if handler+ else None+ ),+ offset=m.start(),+ paren_offset=m.start("paren"),+ )+++# ---------------------------------------------------------------------------+# Rust — axum+# ---------------------------------------------------------------------------++# The head of `.route("/path", <method router>)`.+_AXUM_ROUTE_HEAD_RE = re.compile(+ r"""\.\s*route\s*(?P<paren>\()\s*(?P<q>["'])(?P<path>[^"']+)(?P=q)\s*,"""+)++# A verb inside the method-router argument. `on` names no literal verb+# (`on(MethodFilter::GET, h)`); the contract consumer drops it. Requiring the+# closing paren is what makes a `get(|| async {...})` closure yield no handler.+_AXUM_METHOD_RE = re.compile(+ r"\b(?P<verb>get|post|put|delete|patch|head|options|trace|on)\s*\("+ r"\s*(?:(?P<handler>[\w:]+)\s*\))?"+)+++def axum_routes(content: str) -> Iterator[RouteMatch]:+ """Axum ``.route(...)`` registrations in *content*, one per verb.++ A method router chains verbs (``get(list).post(create)``), so one call site+ yields several matches sharing a path and an offset. The verb scan is bounded+ by the route call's own parens, so a multi-line route is still read.+ """+ for head in _AXUM_ROUTE_HEAD_RE.finditer(content):+ close = match_paren(content, head.start("paren"), quotes='"')+ if close == -1:+ continue # truncated call; scanning to EOF would credit it every verb+ region = content[head.end() : close]+ # Only verbs the method router itself chains. A verb nested in another+ # call's arguments is not one: `get(h).with_state(state.options())`+ # would otherwise fabricate an OPTIONS route.+ for i, _c, depth in scan_code(region, quotes='"'):+ if depth != 0:+ continue+ m = _AXUM_METHOD_RE.match(region, i)+ if m is None:+ continue+ yield RouteMatch(+ verb=m.group("verb").upper(),+ path=head.group("path"),+ receiver=None,+ handler=m.group("handler"),+ offset=head.start(),+ paren_offset=head.start("paren"),+ )diff --git a/packages/core/src/repowise/core/workspace/contracts.py b/packages/core/src/repowise/core/workspace/contracts.pyindex 6da948306..5f0526fbb 100644--- a/packages/core/src/repowise/core/workspace/contracts.py+++ b/packages/core/src/repowise/core/workspace/contracts.py@@ -44,10 +44,12 @@ CONTRACTS_FILENAME = "contracts.json"#: Artifact schema version. Bumped to 2 when contracts gained ``symbol_id``,#: to 3 when providers gained a signature-derived ``schema``, to 4 when a#: package surface became a ``code`` contract, and to 5 when ASP.NET minimal-#: APIs gained ``MapGroup`` prefixes and a handler-bound ``symbol_id``.+#: APIs gained ``MapGroup`` prefixes and a handler-bound ``symbol_id``, and to 6+#: when a multi-line axum route became readable and go/axum providers gained a+#: handler-bound ``symbol_id``.#: A store written under an older version is readable but not reusable: its#: rows carry no identity, and nothing short of re-extraction can give them one.-CONTRACTS_VERSION = 5+CONTRACTS_VERSION = 6# ---------------------------------------------------------------------------diff --git a/packages/core/src/repowise/core/workspace/extractors/grpc/__init__.py b/packages/core/src/repowise/core/workspace/extractors/grpc/__init__.pyindex a83a42d1a..5cf04c6a7 100644--- a/packages/core/src/repowise/core/workspace/extractors/grpc/__init__.py+++ b/packages/core/src/repowise/core/workspace/extractors/grpc/__init__.py@@ -2,8 +2,9 @@Scans ``.proto`` files for service/rpc declarations (providers) andlanguage-specific source files for gRPC server registrations (providers) and-client stubs (consumers). Each language is an independent *dialect* module-registered in :data:`DIALECTS`; :class:`GrpcExtractor` owns only the file walk+client stubs (consumers). The generated-stub shapes are one table in+:mod:`.languages`; ``.proto`` keeps its own dialect because it is an IDL with a+grammar rather than a stub shape. :class:`GrpcExtractor` owns only the file walkand dispatch."""@@ -12,13 +13,9 @@ from __future__ import annotationsfrom typing import TYPE_CHECKINGfrom ..base import ScanContext, select_files-from .csharp import CSharpGrpcDialectfrom .dialect import GrpcDialect-from .go import GoGrpcDialect-from .java import JavaGrpcDialect+from .languages import LANGUAGES, LanguageGrpcDialectfrom .proto import ProtoDialect, _extract_service_blocks-from .python import PythonGrpcDialect-from .typescript import TypeScriptGrpcDialectif TYPE_CHECKING:from collections.abc import Callable, Sequence@@ -32,11 +29,7 @@ if TYPE_CHECKING:# per file.DIALECTS: tuple[GrpcDialect, ...] = (ProtoDialect(),- GoGrpcDialect(),- JavaGrpcDialect(),- PythonGrpcDialect(),- TypeScriptGrpcDialect(),- CSharpGrpcDialect(),+ *(LanguageGrpcDialect(lang) for lang in LANGUAGES),)diff --git a/packages/core/src/repowise/core/workspace/extractors/grpc/csharp.py b/packages/core/src/repowise/core/workspace/extractors/grpc/csharp.pydeleted file mode 100644index 68d189b1f..000000000--- a/packages/core/src/repowise/core/workspace/extractors/grpc/csharp.py+++ /dev/null@@ -1,94 +0,0 @@-"""C# (gRPC-dotnet) dialect.--Providers come from explicit ``MapGrpcService<T>()`` registration and from the-generated server-base convention ``class Impl : ServiceName.ServiceNameBase``.-Consumers come from ``new XxxClient(...)`` generated stubs — but only in files-that carry gRPC context (a ``GrpcChannel`` / ``Grpc.Net`` / ``Grpc.Core`` /-``AddGrpcClient`` marker), since ``new XxxClient(...)`` on its own also matches-TLS, HTTP, and other unrelated client classes.-"""--from __future__ import annotations--import re-from typing import TYPE_CHECKING--from ..base import line_at-from ..langs import CSHARP-from .dialect import make_grpc_contract--if TYPE_CHECKING:- from repowise.core.workspace.contracts import Contract-- from ..base import ScanContext--# app.MapGrpcService<GreeterService>()-_CSHARP_GRPC_MAP_RE = re.compile(r"\.\s*MapGrpcService\s*<\s*(\w+)\s*>")-# class Impl : ServiceName.ServiceNameBase-_CSHARP_GRPC_BASE_RE = re.compile(r"class\s+\w+\s*:\s*(?:[\w.]+\.)?(\w+?)\s*\.\s*\1Base\b")-# new AuthServiceClient(channel) — generated stub class ending in "Client".-_CSHARP_GRPC_CLIENT_RE = re.compile(r"\bnew\s+(\w+)Client\s*\(")--# Generic-class false positives — test doubles and non-gRPC clients.-_CONSUMER_FALSE_PREFIXES = ("mock", "test", "fake", "http")--# Markers that a file actually uses gRPC-dotnet, required before a bare-# `new XxxClient(...)` is treated as a gRPC consumer.-_GRPC_CONTEXT_RE = re.compile(- r"\bGrpcChannel\b|\bGrpc\.(?:Net|Core)\b|\bCallInvoker\b|\bChannelBase\b"- r"|\bAddGrpcClient\b|using\s+Grpc\b"-)---class CSharpGrpcDialect:- name = "csharp"- extensions = CSHARP-- def extract(self, ctx: ScanContext) -> list[Contract]:- out: list[Contract] = []- for m in _CSHARP_GRPC_MAP_RE.finditer(ctx.content):- svc = m.group(1)- out.append(- make_grpc_contract(- ctx,- contract_id=f"grpc::{svc}/*",- role="provider",- symbol_name=f"cs:MapGrpcService<{svc}>",- confidence=0.8,- meta={"service": svc, "source": "csharp_mapgrpc"},- line=line_at(ctx.content, m.start()),- )- )- for m in _CSHARP_GRPC_BASE_RE.finditer(ctx.content):- svc = m.group(1)- out.append(- make_grpc_contract(- ctx,- contract_id=f"grpc::{svc}/*",- role="provider",- symbol_name=f"cs:extends {svc}.{svc}ServiceBase",- confidence=0.8,- meta={"service": svc, "source": "csharp_base"},- line=line_at(ctx.content, m.start()),- )- )- # Consumers are only credible when the file shows real gRPC usage —- # otherwise `new XxxClient(...)` matches unrelated client classes.- if not _GRPC_CONTEXT_RE.search(ctx.content):- return out- for m in _CSHARP_GRPC_CLIENT_RE.finditer(ctx.content):- svc = m.group(1)- if svc.lower().startswith(_CONSUMER_FALSE_PREFIXES):- continue- out.append(- make_grpc_contract(- ctx,- contract_id=f"grpc::{svc}/*",- role="consumer",- symbol_name=f"cs:new {svc}Client",- confidence=0.65,- meta={"service": svc, "source": "csharp_client"},- line=line_at(ctx.content, m.start()),- )- )- return outdiff --git a/packages/core/src/repowise/core/workspace/extractors/grpc/go.py b/packages/core/src/repowise/core/workspace/extractors/grpc/go.pydeleted file mode 100644index 509d5edfe..000000000--- a/packages/core/src/repowise/core/workspace/extractors/grpc/go.py+++ /dev/null@@ -1,55 +0,0 @@-"""Go gRPC dialect — ``RegisterXxxServer`` providers / ``NewXxxClient`` consumers."""--from __future__ import annotations--import re-from typing import TYPE_CHECKING--from ..base import line_at-from ..langs import GO-from .dialect import make_grpc_contract--if TYPE_CHECKING:- from repowise.core.workspace.contracts import Contract-- from ..base import ScanContext--# pb.RegisterAuthServiceServer(grpcServer, &impl{})-_GO_PROVIDER_RE = re.compile(r"\.Register(\w+)Server\s*\(")-# pb.NewAuthServiceClient(conn)-_GO_CONSUMER_RE = re.compile(r"\.New(\w+)Client\s*\(")---class GoGrpcDialect:- name = "go"- extensions = GO-- def extract(self, ctx: ScanContext) -> list[Contract]:- out: list[Contract] = []- for m in _GO_PROVIDER_RE.finditer(ctx.content):- svc = m.group(1)- out.append(- make_grpc_contract(- ctx,- contract_id=f"grpc::{svc}/*",- role="provider",- symbol_name=f"go:Register{svc}Server",- confidence=0.8,- meta={"service": svc, "source": "go_register"},- line=line_at(ctx.content, m.start()),- )- )- for m in _GO_CONSUMER_RE.finditer(ctx.content):- svc = m.group(1)- out.append(- make_grpc_contract(- ctx,- contract_id=f"grpc::{svc}/*",- role="consumer",- symbol_name=f"go:New{svc}Client",- confidence=0.7,- meta={"service": svc, "source": "go_client"},- line=line_at(ctx.content, m.start()),- )- )- return outdiff --git a/packages/core/src/repowise/core/workspace/extractors/grpc/java.py b/packages/core/src/repowise/core/workspace/extractors/grpc/java.pydeleted file mode 100644index 5dfef7bb6..000000000--- a/packages/core/src/repowise/core/workspace/extractors/grpc/java.py+++ /dev/null@@ -1,55 +0,0 @@-"""Java gRPC dialect — ``extends XxxGrpc.XxxImplBase`` / ``XxxGrpc.newStub``."""--from __future__ import annotations--import re-from typing import TYPE_CHECKING--from ..base import line_at-from ..langs import JAVA-from .dialect import make_grpc_contract--if TYPE_CHECKING:- from repowise.core.workspace.contracts import Contract-- from ..base import ScanContext--# extends AuthServiceGrpc.AuthServiceImplBase-_JAVA_PROVIDER_RE = re.compile(r"extends\s+(\w+)Grpc\.(\w+)ImplBase")-# AuthServiceGrpc.newBlockingStub(channel)-_JAVA_CONSUMER_RE = re.compile(r"(\w+)Grpc\.new(?:Blocking|Future)?Stub\s*\(")---class JavaGrpcDialect:- name = "java"- extensions = JAVA-- def extract(self, ctx: ScanContext) -> list[Contract]:- out: list[Contract] = []- for m in _JAVA_PROVIDER_RE.finditer(ctx.content):- svc = m.group(1)- out.append(- make_grpc_contract(- ctx,- contract_id=f"grpc::{svc}/*",- role="provider",- symbol_name=f"java:extends {svc}Grpc.ImplBase",- confidence=0.8,- meta={"service": svc, "source": "java_extends"},- line=line_at(ctx.content, m.start()),- )- )- for m in _JAVA_CONSUMER_RE.finditer(ctx.content):- svc = m.group(1)- out.append(- make_grpc_contract(- ctx,- contract_id=f"grpc::{svc}/*",- role="consumer",- symbol_name=f"java:{svc}Grpc.newStub",- confidence=0.7,- meta={"service": svc, "source": "java_stub"},- line=line_at(ctx.content, m.start()),- )- )- return outdiff --git a/packages/core/src/repowise/core/workspace/extractors/grpc/languages.py b/packages/core/src/repowise/core/workspace/extractors/grpc/languages.pynew file mode 100644index 000000000..c6ee952b7--- /dev/null+++ b/packages/core/src/repowise/core/workspace/extractors/grpc/languages.py@@ -0,0 +1,159 @@+"""The generated-stub shapes gRPC produces, one table row per language.++Every language dialect was the same loop over a provider regex and a consumer+regex, differing only in the pattern, the display wording and the confidence.+The three real per-language facts are declared instead of coded: C# has two+provider shapes, TypeScript has no consumer shape and is the only one whose+match names a method, and a bare ``new XxxClient(...)`` needs a gRPC marker in+the file before it means anything.++``.proto`` is not here — it is an IDL with a real grammar, not a stub shape.+"""++from __future__ import annotations++import re+from dataclasses import dataclass, field+from typing import TYPE_CHECKING++from ..base import line_at+from ..langs import CSHARP, GO, JAVA, JS_TS, PYTHON+from .dialect import make_grpc_contract++if TYPE_CHECKING:+ from repowise.core.workspace.contracts import Contract++ from ..base import ScanContext+++@dataclass(frozen=True)+class _Rule:+ """One recognisable shape. Group 1 is always the service name."""++ role: str+ pattern: re.Pattern[str]+ symbol: str # display template over {service} and {method}+ source: str # meta["source"], the tag that says which shape matched+ confidence: float+ method_group: int | None = None # only a shape that names a method sets this+++@dataclass(frozen=True)+class _Language:+ name: str+ extensions: frozenset[str]+ rules: tuple[_Rule, ...]+ #: A marker the file must carry before any consumer rule runs.+ consumer_gate: re.Pattern[str] | None = None+ #: Stub-name prefixes that are test doubles rather than clients.+ false_prefixes: tuple[str, ...] = field(default=())+++LANGUAGES: tuple[_Language, ...] = (+ _Language(+ name="go",+ extensions=GO,+ rules=(+ # pb.RegisterAuthServiceServer(grpcServer, &impl{})+ _Rule("provider", re.compile(r"\.Register(\w+)Server\s*\("),+ "go:Register{service}Server", "go_register", 0.8),+ # pb.NewAuthServiceClient(conn)+ _Rule("consumer", re.compile(r"\.New(\w+)Client\s*\("),+ "go:New{service}Client", "go_client", 0.7),+ ),+ ),+ _Language(+ name="java",+ extensions=JAVA,+ rules=(+ # extends AuthServiceGrpc.AuthServiceImplBase+ _Rule("provider", re.compile(r"extends\s+(\w+)Grpc\.(\w+)ImplBase"),+ "java:extends {service}Grpc.ImplBase", "java_extends", 0.8),+ # AuthServiceGrpc.newBlockingStub(channel)+ _Rule("consumer", re.compile(r"(\w+)Grpc\.new(?:Blocking|Future)?Stub\s*\("),+ "java:{service}Grpc.newStub", "java_stub", 0.7),+ ),+ ),+ _Language(+ name="python",+ extensions=PYTHON,+ rules=(+ # add_AuthServiceServicer_to_server(servicer, server)+ _Rule("provider", re.compile(r"add_(\w+?)Servicer_to_server\s*\("),+ "py:add_{service}Servicer_to_server", "py_servicer", 0.8),+ # AuthServiceStub(channel)+ _Rule("consumer", re.compile(r"(\w+)Stub\s*\("),+ "py:{service}Stub", "py_stub", 0.7),+ ),+ false_prefixes=("mock", "test", "fake"),+ ),+ _Language(+ name="typescript",+ extensions=JS_TS,+ rules=(+ # @GrpcMethod('AuthService', 'Login') — the one shape naming a method.+ _Rule("provider", re.compile(r"@GrpcMethod\s*\(\s*'(\w+)'\s*,\s*'(\w+)'\s*\)"),+ "ts:@GrpcMethod('{service}', '{method}')", "ts_decorator", 0.8,+ method_group=2),+ ),+ ),+ _Language(+ name="csharp",+ extensions=CSHARP,+ rules=(+ # app.MapGrpcService<GreeterService>()+ _Rule("provider", re.compile(r"\.\s*MapGrpcService\s*<\s*(\w+)\s*>"),+ "cs:MapGrpcService<{service}>", "csharp_mapgrpc", 0.8),+ # class Impl : ServiceName.ServiceNameBase+ _Rule("provider",+ re.compile(r"class\s+\w+\s*:\s*(?:[\w.]+\.)?(\w+?)\s*\.\s*\1Base\b"),+ "cs:extends {service}.{service}ServiceBase", "csharp_base", 0.8),+ # new AuthServiceClient(channel)+ _Rule("consumer", re.compile(r"\bnew\s+(\w+)Client\s*\("),+ "cs:new {service}Client", "csharp_client", 0.65),+ ),+ consumer_gate=re.compile(+ r"\bGrpcChannel\b|\bGrpc\.(?:Net|Core)\b|\bCallInvoker\b|\bChannelBase\b"+ r"|\bAddGrpcClient\b|using\s+Grpc\b"+ ),+ false_prefixes=("mock", "test", "fake", "http"),+ ),+)+++class LanguageGrpcDialect:+ """The one dialect every entry in :data:`LANGUAGES` is served by."""++ def __init__(self, language: _Language) -> None:+ self._lang = language+ self.name = language.name+ self.extensions = language.extensions++ def extract(self, ctx: ScanContext) -> list[Contract]:+ lang = self._lang+ gated = lang.consumer_gate is not None and not lang.consumer_gate.search(ctx.content)+ out: list[Contract] = []+ for rule in lang.rules:+ if rule.role == "consumer" and gated:+ continue+ for m in rule.pattern.finditer(ctx.content):+ service = m.group(1)+ if rule.role == "consumer" and service.lower().startswith(lang.false_prefixes):+ continue+ method = m.group(rule.method_group) if rule.method_group else None+ out.append(+ make_grpc_contract(+ ctx,+ contract_id=f"grpc::{service}/{method or '*'}",+ role=rule.role,+ symbol_name=rule.symbol.format(service=service, method=method),+ confidence=rule.confidence,+ meta={+ "service": service,+ **({"method": method} if method else {}),+ "source": rule.source,+ },+ line=line_at(ctx.content, m.start()),+ )+ )+ return outdiff --git a/packages/core/src/repowise/core/workspace/extractors/grpc/python.py b/packages/core/src/repowise/core/workspace/extractors/grpc/python.pydeleted file mode 100644index 1a0378571..000000000--- a/packages/core/src/repowise/core/workspace/extractors/grpc/python.py+++ /dev/null@@ -1,60 +0,0 @@-"""Python gRPC dialect — ``add_XxxServicer_to_server`` / ``XxxStub``."""--from __future__ import annotations--import re-from typing import TYPE_CHECKING--from ..base import line_at-from ..langs import PYTHON-from .dialect import make_grpc_contract--if TYPE_CHECKING:- from repowise.core.workspace.contracts import Contract-- from ..base import ScanContext--# add_AuthServiceServicer_to_server(servicer, server)-_PY_PROVIDER_RE = re.compile(r"add_(\w+?)Servicer_to_server\s*\(")-# AuthServiceStub(channel)-_PY_CONSUMER_RE = re.compile(r"(\w+)Stub\s*\(")--# Common stub false positives — test doubles, not real clients.-_CONSUMER_FALSE_PREFIXES = ("mock", "test", "fake")---class PythonGrpcDialect:- name = "python"- extensions = PYTHON-- def extract(self, ctx: ScanContext) -> list[Contract]:- out: list[Contract] = []- for m in _PY_PROVIDER_RE.finditer(ctx.content):- svc = m.group(1)- out.append(- make_grpc_contract(- ctx,- contract_id=f"grpc::{svc}/*",- role="provider",- symbol_name=f"py:add_{svc}Servicer_to_server",- confidence=0.8,- meta={"service": svc, "source": "py_servicer"},- line=line_at(ctx.content, m.start()),- )- )- for m in _PY_CONSUMER_RE.finditer(ctx.content):- svc = m.group(1)- if svc.lower().startswith(_CONSUMER_FALSE_PREFIXES):- continue- out.append(- make_grpc_contract(- ctx,- contract_id=f"grpc::{svc}/*",- role="consumer",- symbol_name=f"py:{svc}Stub",- confidence=0.7,- meta={"service": svc, "source": "py_stub"},- line=line_at(ctx.content, m.start()),- )- )- return outdiff --git a/packages/core/src/repowise/core/workspace/extractors/grpc/typescript.py b/packages/core/src/repowise/core/workspace/extractors/grpc/typescript.pydeleted file mode 100644index 2b1eefe43..000000000--- a/packages/core/src/repowise/core/workspace/extractors/grpc/typescript.py+++ /dev/null@@ -1,41 +0,0 @@-"""TypeScript / JavaScript gRPC dialect — NestJS ``@GrpcMethod`` providers."""--from __future__ import annotations--import re-from typing import TYPE_CHECKING--from ..base import line_at-from ..langs import JS_TS-from .dialect import make_grpc_contract--if TYPE_CHECKING:- from repowise.core.workspace.contracts import Contract-- from ..base import ScanContext--# @GrpcMethod('AuthService', 'Login')-_TS_PROVIDER_RE = re.compile(r"@GrpcMethod\s*\(\s*'(\w+)'\s*,\s*'(\w+)'\s*\)")---class TypeScriptGrpcDialect:- name = "typescript"- extensions = JS_TS-- def extract(self, ctx: ScanContext) -> list[Contract]:- out: list[Contract] = []- for m in _TS_PROVIDER_RE.finditer(ctx.content):- svc = m.group(1)- method = m.group(2)- out.append(- make_grpc_contract(- ctx,- contract_id=f"grpc::{svc}/{method}",- role="provider",- symbol_name=f"ts:@GrpcMethod('{svc}', '{method}')",- confidence=0.8,- meta={"service": svc, "method": method, "source": "ts_decorator"},- line=line_at(ctx.content, m.start()),- )- )- return outdiff --git a/packages/core/src/repowise/core/workspace/extractors/http/go.py b/packages/core/src/repowise/core/workspace/extractors/http/go.pyindex 920143f25..ea1f4b49d 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/go.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/go.py@@ -2,20 +2,22 @@stdlib ``.HandleFunc("/path", ...)`` (which carries no method, recorded as``*``).+The route call is recognised by ``ingestion.framework_routes``, shared with the+graph-edge builder that reads the same call for its handler argument.+Route groups (``api := r.Group("/api"); v1 := api.Group("/v1")``) are resolvedtransitively so a handler on ``v1`` records its full ``/api/v1/...`` path."""from __future__ import annotations-import refrom typing import TYPE_CHECKING-from repowise.core.ingestion.framework_routes import GroupMatch+from repowise.core.ingestion.framework_routes import HTTP_METHODS, go_groups, go_routesfrom ..base import line_atfrom ..langs import GO-from .dialect import METHODS_UPPER, build_provider_contract+from .dialect import build_provider_contractfrom .mounts import compose_prefix, group_prefixesif TYPE_CHECKING:@@ -23,23 +25,8 @@ if TYPE_CHECKING:from ..base import ScanContext-# group := parent.Group("/segment") — a nested router group.-_GROUP_RE = re.compile(r"""(\w+)\s*:?=\s*(\w+)\.Group\s*\(\s*['"]([^'"]+)['"]""")--# r.GET("/path", ...) or .HandleFunc("/path", ...). The receiver variable is-# captured (when it is a bare identifier) so its group prefix can be resolved; an-# empty capture (e.g. an inline-chained ``Group("/x").GET(...)``) falls back to no-# prefix, preserving the pre-group-resolution behaviour.-_GO_ROUTE_RE = re.compile(- rf"""(\w*)\.({METHODS_UPPER}|Handle|HandleFunc)\s*\(\s*['"]([^'"]+)['"]""",-)---def _groups(content: str) -> list[GroupMatch]:- return [- GroupMatch(var=m.group(1), parent=m.group(2), prefix=m.group(3))- for m in _GROUP_RE.finditer(content)- ]+# Registration selectors that carry no verb of their own.+_VERBLESS = ("HANDLE", "HANDLEFUNC")class GoDialect:@@ -47,19 +34,29 @@ class GoDialect:extensions = GOdef extract(self, ctx: ScanContext) -> list[Contract]:- prefixes = group_prefixes(_groups(ctx.content))+ prefixes = group_prefixes(go_groups(ctx.content))out: list[Contract] = []- for m in _GO_ROUTE_RE.finditer(ctx.content):- var, method_raw, path_raw = m.group(1), m.group(2), m.group(3)- # Handle/HandleFunc don't carry a method verb.- method = "*" if method_raw in ("Handle", "HandleFunc") else method_raw.upper()- path = compose_prefix(prefixes.get(var, ""), path_raw)+ for route in go_routes(ctx.content):+ if route.verb in _VERBLESS:+ method = "*"+ elif route.verb in HTTP_METHODS:+ method = route.verb+ else:+ continue # gin's `Any`, and OPTIONS/HEAD, are not recorded herec = build_provider_contract(ctx,method=method,- path_raw=path,+ # An empty path under a group is still that group's route, so+ # the emptiness rule is `build_provider_contract`'s, after+ # stitching — the same order ASP.NET's MapGroup uses.+ path_raw=compose_prefix(+ prefixes.get(route.receiver or "", ""), route.path or ""+ ),framework="go",- line=line_at(ctx.content, m.start()),+ line=line_at(ctx.content, route.offset),+ # A wrapped handler names the middleware, not the route's own+ # function, so binding by it would be wrong.+ handler=None if route.handler_call else route.handler,)if c is not None:out.append(c)diff --git a/packages/core/src/repowise/core/workspace/extractors/http/laravel.py b/packages/core/src/repowise/core/workspace/extractors/http/laravel.pyindex 117ef6e07..dbcf0a7f1 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/laravel.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/laravel.py@@ -1,25 +1,24 @@-"""Laravel (PHP) HTTP provider dialect — ``Route::get('/path', ...)``."""+"""Laravel (PHP) HTTP provider dialect — ``Route::get('/path', ...)``.++The route call is recognised by ``ingestion.framework_routes``, shared with the+graph-edge builder that reads the same call for its controller class.+"""from __future__ import annotations-import refrom typing import TYPE_CHECKING+from repowise.core.ingestion.framework_routes import HTTP_METHODS, laravel_routes+from ..base import line_atfrom ..langs import PHP-from .dialect import METHODS, build_provider_contract+from .dialect import build_provider_contractif TYPE_CHECKING:from repowise.core.workspace.contracts import Contractfrom ..base import ScanContext-# Route::get('/path', ...)-_LARAVEL_RE = re.compile(- rf"""Route::({METHODS})\s*\(\s*['"]([^'"]+)['"]""",- re.IGNORECASE,-)-class LaravelDialect:name = "laravel"@@ -27,13 +26,17 @@ class LaravelDialect:def extract(self, ctx: ScanContext) -> list[Contract]:out: list[Contract] = []- for m in _LARAVEL_RE.finditer(ctx.content):+ for route in laravel_routes(ctx.content):+ # `resource`/`apiResource` stand for a set of routes and `any`/`match`+ # for an unnamed verb, so neither is one method+path contract.+ if route.verb not in HTTP_METHODS or not route.path:+ continuec = build_provider_contract(ctx,- method=m.group(1).upper(),- path_raw=m.group(2),+ method=route.verb,+ path_raw=route.path,framework="laravel",- line=line_at(ctx.content, m.start()),+ line=line_at(ctx.content, route.offset),)if c is not None:out.append(c)diff --git a/packages/core/src/repowise/core/workspace/extractors/http/rust_axum.py b/packages/core/src/repowise/core/workspace/extractors/http/rust_axum.pyindex 823b58099..030fdec1d 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/rust_axum.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/rust_axum.py@@ -3,8 +3,12 @@Covers the route-declaration shapes used by the common Rust web frameworks:* **Axum** — ``.route("/path", get(handler))``, including method routers that- chain several verbs (``get(h).post(h2)``);-* **Actix-web / Rocket** — attribute-macro routes (``#[get("/path")]``).+ chain several verbs (``get(h).post(h2)``). Recognised by+ ``ingestion.framework_routes``, shared with the graph-edge builder that reads+ the same call for its handler argument;+* **Actix-web / Rocket** — attribute-macro routes (``#[get("/path")]``). Actix's+ builder form (``web::get().to(h)``) is a different construct that only the+ graph side reads, so it is not shared.Warp's filter-combinator routing (``warp::path!(...)``) has no stable literalpath to anchor on and is intentionally not modelled here.@@ -15,6 +19,8 @@ from __future__ import annotationsimport refrom typing import TYPE_CHECKING+from repowise.core.ingestion.framework_routes import axum_routes+from ..base import line_atfrom ..langs import RUSTfrom .dialect import build_provider_contract@@ -24,14 +30,6 @@ if TYPE_CHECKING:from ..base import ScanContext-# Axum: the head of a `.route("/path", <method-router>)` call. The method router-# itself is parsed separately so chained verbs (`get(h).post(h2)`) are all found.-_AXUM_ROUTE_HEAD_RE = re.compile(r"""\.route\s*\(\s*["']([^"']+)["']\s*,""")--# Method-router verbs inside a `.route(...)` second argument, or the verbs used-# by `MethodRouter`/`on` builders. Lower-case function form, e.g. `get(`, `post(`.-_AXUM_METHOD_RE = re.compile(r"""\b(get|post|put|delete|patch|head|options|trace)\s*\(""")-# Actix-web / Rocket attribute macros: #[get("/path")], #[post("/path", ...)]._RUST_ATTR_ROUTE_RE = re.compile(r"""#\[\s*(get|post|put|delete|patch|head|options)\s*\(\s*["']([^"']+)["']""",@@ -39,16 +37,6 @@ _RUST_ATTR_ROUTE_RE = re.compile()-def _line_window(content: str, start: int) -> str:- """Return the text from *start* up to the next newline.-- Axum routes are written one per line, so the method router for a given- ``.route(...)`` lives between the path literal and the end of the line.- """- nl = content.find("\n", start)- return content[start:] if nl == -1 else content[start:nl]--class RustAxumDialect:name = "rust-axum"extensions = RUST@@ -57,21 +45,23 @@ class RustAxumDialect:content = ctx.contentout: list[Contract] = []- # Axum `.route("/path", get(...).post(...))`.- for m in _AXUM_ROUTE_HEAD_RE.finditer(content):- path_raw = m.group(1)- window = _line_window(content, m.end())- methods = {mm.group(1).upper() for mm in _AXUM_METHOD_RE.finditer(window)}- for method in sorted(methods):- c = build_provider_contract(- ctx,- method=method,- path_raw=path_raw,- framework="axum",- line=line_at(content, m.start()),- )- if c is not None:- out.append(c)+ # One call site yields a match per verb, so collapse repeats of a verb.+ seen: set[tuple[int, str]] = set()+ for route in axum_routes(content):+ # `on(MethodFilter::GET, h)` names no literal verb.+ if route.verb == "ON" or (route.offset, route.verb) in seen:+ continue+ seen.add((route.offset, route.verb))+ c = build_provider_contract(+ ctx,+ method=route.verb,+ path_raw=route.path or "",+ framework="axum",+ line=line_at(content, route.offset),+ handler=route.handler,+ )+ if c is not None:+ out.append(c)# Actix-web / Rocket attribute macros.for m in _RUST_ATTR_ROUTE_RE.finditer(content):diff --git a/packages/core/src/repowise/core/workspace/repo_index.py b/packages/core/src/repowise/core/workspace/repo_index.pyindex b7e8e42ce..07efe322e 100644--- a/packages/core/src/repowise/core/workspace/repo_index.py+++ b/packages/core/src/repowise/core/workspace/repo_index.py@@ -19,6 +19,7 @@ from __future__ import annotationsimport asyncioimport jsonimport logging+import refrom dataclasses import dataclassfrom typing import TYPE_CHECKING, Any@@ -69,6 +70,11 @@ class ExternalImport:imported_names: tuple[str, ...]+#: What separates a qualifier from the name it qualifies, across the languages+#: whose handler expressions reach :meth:`RepoIndex.symbol_named`.+_QUALIFIER_RE = re.compile(r"::|\.")++class RepoIndex:"""Read-only accessor over one repo's ``wiki.db``.@@ -206,16 +212,24 @@ class RepoIndex:def symbol_named(self, expression: str) -> IndexedSymbol | None:"""The one symbol *expression* names in this repo, or None.- *expression* may be qualified (``OrderHandlers.GetOrder``); the qualifier- settles a member name that is ambiguous on its own, which is the common- case for the handler shape this exists for (``Endpoint.HandleAsync``).- A name that still resolves to more than one symbol is refused rather- than guessed: which one the caller meant would otherwise be decided by- index row order.+ *expression* may be qualified (``OrderHandlers.GetOrder``,+ ``handlers::ping``); the qualifier settles a member name that is+ ambiguous on its own, which is the common case for the handler shape+ this exists for (``Endpoint.HandleAsync``). A name that still resolves to+ more than one symbol is refused rather than guessed: which one the caller+ meant would otherwise be decided by index row order.++ ``::`` separates a qualifier too. Without it a Rust handler written+ ``handlers::ping`` is looked up whole, matches nothing, and the caller+ falls back to a line lookup that binds the route to its router builder."""- found = self._by_name.get(expression.rsplit(".", 1)[-1], ())- if len(found) > 1 and "." in expression:- found = [s for s in found if s.qualified_name.endswith(expression)]+ parts = _QUALIFIER_RE.split(expression)+ found = self._by_name.get(parts[-1], ())+ if len(found) > 1 and len(parts) > 1:+ tail = parts[-2:]+ found = [+ s for s in found if _QUALIFIER_RE.split(s.qualified_name)[-2:] == tail+ ]return found[0] if len(found) == 1 else Nonedef external_import_edges(self) -> list[ExternalImport]:diff --git a/tests/unit/workspace/test_framework_routes.py b/tests/unit/workspace/test_framework_routes.pyindex be76450ac..150e0dc5a 100644--- a/tests/unit/workspace/test_framework_routes.py+++ b/tests/unit/workspace/test_framework_routes.py@@ -1,10 +1,12 @@"""One recognition of a framework's routes, two consumers.``ingestion.framework_edges`` and ``workspace.extractors.http`` each used to-match ASP.NET's ``.MapGet(...)`` and Express's ``router.get(...)`` with their own-regex, so a fix landed on one side only. The claims under test are that both now-read the same match, that neither consumer's output collapsed into the other's,-and that ``MapGroup`` — which neither copy recognised — now stitches a prefix.+match ASP.NET's ``.MapGet(...)``, Express's ``router.get(...)``, gin's+``r.GET(...)``, Laravel's ``Route::get(...)`` and axum's ``.route(...)`` with+their own regex, so a fix landed on one side only. The claims under test are+that both now read the same match, that neither consumer's output collapsed into+the other's, and that the shapes neither copy handled — ``MapGroup`` prefixes, a+multi-line axum route, Laravel's third handler spelling — now work."""from __future__ import annotations@@ -20,12 +22,17 @@ from repowise.core.ingestion.framework_routes import (HTTP_METHODS,aspnet_groups,aspnet_routes,+ axum_routes,express_routes,+ go_groups,+ go_routes,+ laravel_routes,)from repowise.core.ingestion.models import FileInfo, Symbolfrom repowise.core.ingestion.parser import ASTParserfrom repowise.core.ingestion.resolvers.context import ResolverContextfrom repowise.core.workspace.contracts import bind_symbol_ids+from repowise.core.workspace.extractors.http.mounts import group_prefixesfrom repowise.core.workspace.extractors.http_extractor import HttpExtractorfrom ._repo_index import make_repo_index@@ -117,16 +124,16 @@ class TestExpressRecognition:# ----------------------------------------------------------------------------def _parsed(repo: Path) -> dict[str, Any]:+def _parse_repo(repo: Path, glob: str, language: str) -> dict[str, Any]:parser = ASTParser()out: dict[str, Any] = {}- for cs in repo.rglob("*.cs"):- rel = cs.resolve().relative_to(repo.resolve()).as_posix()+ for src in repo.rglob(glob):+ rel = src.resolve().relative_to(repo.resolve()).as_posix()fi = FileInfo(path=rel,- abs_path=str(cs.resolve()),- language="csharp",- size_bytes=cs.stat().st_size,+ abs_path=str(src.resolve()),+ language=language,+ size_bytes=src.stat().st_size,git_hash="",last_modified=datetime.now(),is_test=False,@@ -134,10 +141,36 @@ def _parsed(repo: Path) -> dict[str, Any]:is_api_contract=False,is_entry_point=rel.endswith("Program.cs"),)- out[rel] = parser.parse_file(fi, cs.read_bytes())+ out[rel] = parser.parse_file(fi, src.read_bytes())return out+def _parsed(repo: Path) -> dict[str, Any]:+ return _parse_repo(repo, "*.cs", "csharp")+++def _graph_edges(repo: Path, parsed: dict[str, Any], stack: list[str]) -> nx.DiGraph:+ graph = nx.DiGraph()+ for path in parsed:+ graph.add_node(path)+ ctx = ResolverContext(+ path_set=set(parsed),+ stem_map={Path(p).stem.lower(): [p] for p in parsed},+ graph=graph,+ repo_path=repo,+ )+ add_framework_edges(graph, parsed, ctx, stack)+ return graph+++def _providers(repo: Path) -> dict[str, Any]:+ return {+ c.contract_id: c+ for c in HttpExtractor().extract(repo, "api")+ if c.role == "provider"+ }++class TestGraphConsumer:def test_minimal_api_handler_links_the_entry_point_to_its_file(self, tmp_path: Path@@ -219,7 +252,7 @@ class TestContractConsumer:# ----------------------------------------------------------------------------async def _index_of(tmp_path: Path) -> Any:+async def _index_of_repo(tmp_path: Path, glob: str, language: str) -> Any:"""Open an index over the rows real ingestion produces for the fixtures.The symbol ids are never written by hand. C# ingestion mints@@ -227,7 +260,7 @@ async def _index_of(tmp_path: Path) -> Any:``<file>::<name>`` shape a fixture would guess — and `Program.cs` istop-level statements, so it yields no symbols at all."""- parsed = _parsed(tmp_path)+ parsed = _parse_repo(tmp_path, glob, language)by_file: dict[str, list[Symbol]] = {}for rel, pf in parsed.items():for sym in pf.symbols:@@ -245,7 +278,7 @@ class TestHandlerBinding:contracts = [c for c in HttpExtractor().extract(tmp_path, "api") if c.role == "provider"]- index = await _index_of(tmp_path)+ index = await _index_of_repo(tmp_path, "*.cs", "csharp")try:# The expected ids come from the parse, not from this file.expected = {@@ -277,7 +310,7 @@ class TestHandlerBinding:contracts = [c for c in HttpExtractor().extract(tmp_path, "api") if c.role == "provider"]- index = await _index_of(tmp_path)+ index = await _index_of_repo(tmp_path, "*.cs", "csharp")try:bind_symbol_ids(contracts, index)two = index.symbol_named("Two.Handle")@@ -292,3 +325,449 @@ class TestHandlerBinding:# `Two.Handle` carries the qualifier that settles it.assert two is not Noneassert bound["http::GET::/b"] == two.symbol_id+++# ===========================================================================+# W5b — go, laravel and axum, the three remaining one-construct duplicates+# ===========================================================================++# A gin router written the way the shapes co-occur: nested groups, a handler+# named bare, one named through a package, and a closure that names nothing.+ROUTES_GO = """\+package main++import "github.com/gin-gonic/gin"++func Setup(r *gin.Engine) {+ api := r.Group("/api")+ v1 := api.Group("/v1")+ v1.GET("/orders/:id", GetOrder)+ v1.POST("/orders", CreateOrder)+ r.GET("/ping", func(c *gin.Context) { c.String(200, "pong") })+ r.HandleFunc("/health", Health)+ r.Any("/catchall", CatchAll)+}+"""++HANDLERS_GO = """\+package main++import "github.com/gin-gonic/gin"++func GetOrder(c *gin.Context) {}+func CreateOrder(c *gin.Context) {}+func Health(c *gin.Context) {}+func CatchAll(c *gin.Context) {}+"""++ROUTES_PHP = """\+<?php++Route::get('/orders/{id}', [OrderController::class, 'show']);+Route::post('/orders', 'OrderController@store');+Route::resource('photos', PhotoController::class);+Route::get('/ping', function () { return 'pong'; });+"""++MAIN_RS = """\+use axum::{routing::get, Router};++pub fn app() -> Router {+ Router::new()+ .route("/orders", get(list_orders).post(create_order))+ .route(+ "/orders/:id",+ get(show_order).delete(remove_order),+ )+ .route("/ping", get(|| async { "pong" }))+}+"""++# Split across two files so "links every chained handler" is a claim a single+# resolved handler cannot satisfy.+COLLECTION_RS = """\+pub async fn list_orders() {}+pub async fn create_order() {}+"""++ITEM_RS = """\+pub async fn show_order() {}+pub async fn remove_order() {}+"""+++class TestGoRecognition:+ def test_receiver_verb_path_and_handler(self) -> None:+ routes = [(r.verb, r.path, r.receiver, r.handler) for r in go_routes(ROUTES_GO)]+ assert routes == [+ ("GET", "/orders/:id", "v1", "GetOrder"),+ ("POST", "/orders", "v1", "CreateOrder"),+ ("GET", "/ping", "r", None),+ ("HANDLEFUNC", "/health", "r", "Health"),+ ("ANY", "/catchall", "r", "CatchAll"),+ ]++ def test_a_closure_or_anonymous_struct_is_not_a_handler(self) -> None:+ # Excluding the two keywords that can open one is what stops the tokens+ # `func` and `struct` being read as handler names.+ assert [r.handler for r in go_routes('r.GET("/x", func(c *gin.Context) {})')] == [+ None+ ]+ assert [r.handler for r in go_routes('mux.Handle("/y", struct{}{})')] == [None]++ def test_a_wrapped_handler_is_kept_but_flagged(self) -> None:+ # Middleware wrappers are the dominant real shape in mattermost/grafana.+ # The graph consumer wants the edge; the contract consumer must not bind+ # a route to its middleware.+ (route,) = list(go_routes('r.GET("/x", api.RequireSession(handleUser))'))+ assert (route.handler, route.handler_call) == ("api.RequireSession", True)+ (plain,) = list(go_routes('r.GET("/y", handleUser)'))+ assert (plain.handler, plain.handler_call) == ("handleUser", False)++ def test_groups_carry_their_parent(self) -> None:+ assert [(g.var, g.parent, g.prefix) for g in go_groups(ROUTES_GO)] == [+ ("api", "r", "/api"),+ ("v1", "api", "/v1"),+ ]+++class TestLaravelRecognition:+ def test_all_three_handler_spellings(self) -> None:+ routes = [(r.verb, r.path, r.handler) for r in laravel_routes(ROUTES_PHP)]+ assert routes == [+ ("GET", "/orders/{id}", "OrderController"),+ ("POST", "/orders", "OrderController"),+ ("RESOURCE", "photos", "PhotoController"),+ ("GET", "/ping", None),+ ]++ def test_a_namespaced_controller_keeps_its_namespace(self) -> None:+ (route,) = list(+ laravel_routes(r"Route::get('/x', [App\Http\Controllers\Orders::class, 'i']);")+ )+ assert route.handler == r"App\Http\Controllers\Orders"++ def test_a_concatenated_path_with_a_call_in_it(self) -> None:+ # Real monica route: scanning to the next `)` stops inside `config(`, and+ # scanning to the next `,` runs past the call. Only the balanced argument+ # span reads both parts.+ (route,) = list(+ laravel_routes(+ "Route::post(\n '/telegram/webhook/'.config('x.webhook'),\n"+ " [TelegramWebhookController::class, 'store']\n);"+ )+ )+ assert (route.path, route.handler) == (+ "/telegram/webhook/",+ "TelegramWebhookController",+ )++ def test_a_chained_name_call_is_outside_the_arguments(self) -> None:+ (route,) = list(+ laravel_routes("Route::get('/x', [C::class, 'i'])->name('login.provider');")+ )+ assert (route.path, route.handler) == ("/x", "C")++ def test_a_non_literal_path_still_yields_its_handler(self) -> None:+ # The graph regexes matched `[^,]*` here; requiring a literal would have+ # dropped the edge.+ (route,) = list(laravel_routes("Route::put($uri, [EditController::class, 'e']);"))+ assert (route.path, route.handler) == (None, "EditController")++ def test_resource_reaches_the_graph_consumer_with_its_controller(self) -> None:+ # It stands for a set of routes, so only the graph consumer can use it.+ (resource,) = [r for r in laravel_routes(ROUTES_PHP) if r.verb == "RESOURCE"]+ assert resource.handler == "PhotoController"+++class TestAxumRecognition:+ def test_chained_verbs_share_one_path_and_offset(self) -> None:+ routes = [(r.verb, r.path, r.handler, r.offset) for r in axum_routes(MAIN_RS)]+ assert [(v, p, h) for v, p, h, _ in routes] == [+ ("GET", "/orders", "list_orders"),+ ("POST", "/orders", "create_order"),+ ("GET", "/orders/:id", "show_order"),+ ("DELETE", "/orders/:id", "remove_order"),+ ("GET", "/ping", None),+ ]+ # The two verbs of one call site report the same registration offset.+ assert routes[0][3] == routes[1][3]+ assert routes[2][3] == routes[3][3]++ def test_a_multi_line_route_is_read(self) -> None:+ # The contract matcher this replaced scanned only to end of line, so the+ # verbs of a wrapped `.route(` were invisible to it.+ verbs = [r.verb for r in axum_routes(MAIN_RS) if r.path == "/orders/:id"]+ assert verbs == ["GET", "DELETE"]++ def test_on_names_no_literal_verb(self) -> None:+ (route,) = list(axum_routes('.route("/x", on(MethodFilter::GET, custom))'))+ assert (route.verb, route.handler) == ("ON", None)++ def test_a_lifetime_does_not_open_a_string(self) -> None:+ # `'` is a Rust lifetime; a quote-aware paren scan would swallow the file.+ src = '.route("/x", get(handler::<\'a>))\n.route("/y", post(other))'+ assert [r.path for r in axum_routes(src)] == ["/x", "/y"]+++class TestGoConsumers:+ def _write(self, tmp_path: Path) -> None:+ (tmp_path / "routes.go").write_text(ROUTES_GO, encoding="utf-8")+ (tmp_path / "handlers.go").write_text(HANDLERS_GO, encoding="utf-8")++ def test_graph_links_the_router_to_its_handler_file(self, tmp_path: Path) -> None:+ self._write(tmp_path)+ graph = _graph_edges(tmp_path, _parse_repo(tmp_path, "*.go", "go"), ["gin"])+ assert graph.has_edge("routes.go", "handlers.go")++ def test_contracts_keep_their_group_prefixes(self, tmp_path: Path) -> None:+ self._write(tmp_path)+ ids = set(_providers(tmp_path))+ assert "http::GET::/api/v1/orders/{param}" in ids+ assert "http::POST::/api/v1/orders" in ids++ def test_handlefunc_records_no_verb_and_any_records_nothing(+ self, tmp_path: Path+ ) -> None:+ self._write(tmp_path)+ ids = set(_providers(tmp_path))+ assert "http::*::/health" in ids+ # gin's `Any` reaches the graph consumer but is not an HTTP method.+ assert not [i for i in ids if "catchall" in i]++ async def test_a_route_binds_to_its_handler(self, tmp_path: Path) -> None:+ self._write(tmp_path)+ contracts = [+ c for c in HttpExtractor().extract(tmp_path, "api") if c.role == "provider"+ ]+ index = await _index_of_repo(tmp_path, "*.go", "go")+ try:+ expected = {+ s.name: s.symbol_id for s in index.symbols_for_file("handlers.go")+ }+ assert "GetOrder" in expected+ bind_symbol_ids(contracts, index)+ finally:+ await index.close()+ bound = {c.contract_id: c.symbol_id for c in contracts}+ assert bound["http::GET::/api/v1/orders/{param}"] == expected["GetOrder"]+++class TestLaravelConsumers:+ def _write(self, tmp_path: Path) -> None:+ (tmp_path / "routes").mkdir()+ (tmp_path / "routes" / "api.php").write_text(ROUTES_PHP, encoding="utf-8")+ controllers = tmp_path / "app" / "Http" / "Controllers"+ controllers.mkdir(parents=True)+ for name in ("OrderController", "PhotoController"):+ (controllers / f"{name}.php").write_text(+ f"<?php\nclass {name} {{ public function show() {{}} }}\n", encoding="utf-8"+ )++ def test_graph_links_the_route_file_to_every_controller(self, tmp_path: Path) -> None:+ self._write(tmp_path)+ graph = _graph_edges(tmp_path, _parse_repo(tmp_path, "*.php", "php"), ["laravel"])+ assert graph.has_edge("routes/api.php", "app/Http/Controllers/OrderController.php")+ # The bare `Controller::class` of a resource route is a third spelling+ # that the one shared alternation now covers.+ assert graph.has_edge("routes/api.php", "app/Http/Controllers/PhotoController.php")++ def test_contracts_cover_the_verbs_and_nothing_else(self, tmp_path: Path) -> None:+ self._write(tmp_path)+ ids = set(_providers(tmp_path))+ assert "http::GET::/orders/{param}" in ids+ assert "http::POST::/orders" in ids+ assert "http::GET::/ping" in ids+ # `resource` stands for a set of routes, so it is not one contract.+ assert not [i for i in ids if "photos" in i]+++class TestAxumConsumers:+ def _write(self, tmp_path: Path) -> None:+ (tmp_path / "main.rs").write_text(MAIN_RS, encoding="utf-8")+ (tmp_path / "collection.rs").write_text(COLLECTION_RS, encoding="utf-8")+ (tmp_path / "item.rs").write_text(ITEM_RS, encoding="utf-8")++ def test_graph_links_every_chained_handler(self, tmp_path: Path) -> None:+ self._write(tmp_path)+ graph = _graph_edges(tmp_path, _parse_repo(tmp_path, "*.rs", "rust"), ["axum"])+ # The second verb of each chain was invisible to the regex this replaced,+ # so item.rs is the edge that proves chaining is read.+ assert graph.has_edge("main.rs", "collection.rs")+ assert graph.has_edge("main.rs", "item.rs")++ def test_contracts_are_exactly_the_chained_verbs(self, tmp_path: Path) -> None:+ self._write(tmp_path)+ # Equality, not containment: a nested call inside the method-router+ # argument used to fabricate extra verbs on the same path.+ assert set(_providers(tmp_path)) == {+ "http::GET::/orders",+ "http::POST::/orders",+ "http::GET::/orders/{param}",+ "http::DELETE::/orders/{param}",+ "http::GET::/ping",+ }++ async def test_a_route_binds_to_its_handler(self, tmp_path: Path) -> None:+ self._write(tmp_path)+ contracts = [+ c for c in HttpExtractor().extract(tmp_path, "api") if c.role == "provider"+ ]+ index = await _index_of_repo(tmp_path, "*.rs", "rust")+ try:+ expected = {+ s.name: s.symbol_id+ for f in ("collection.rs", "item.rs")+ for s in index.symbols_for_file(f)+ }+ assert {"list_orders", "remove_order"} <= set(expected)+ bind_symbol_ids(contracts, index)+ finally:+ await index.close()+ bound = {c.contract_id: c.symbol_id for c in contracts}+ assert bound["http::GET::/orders"] == expected["list_orders"]+ # The second verb of a chain binds to its own handler, not the first's.+ assert bound["http::DELETE::/orders/{param}"] == expected["remove_order"]+++# ===========================================================================+# Shapes the W5b review found: everything below failed before it was fixed.+# ===========================================================================+++class TestCommentsInsideARouteCall:+ def test_an_apostrophe_in_a_php_comment_does_not_eat_the_route(self) -> None:+ # `// won't work` opened a string that never closed, so the paren scan+ # failed and the whole route — contract and edge — was dropped.+ (route,) = list(+ laravel_routes(+ "Route::post(\n '/x',\n // won't work\n"+ " [XController::class, 'store']\n);"+ )+ )+ assert (route.verb, route.path, route.handler) == ("POST", "/x", "XController")++ def test_a_hash_comment_is_a_comment_but_an_attribute_is_not(self) -> None:+ (route,) = list(+ laravel_routes("Route::get(\n '/y', # it's fine\n [C::class, 'i']\n);")+ )+ assert route.handler == "C"+ # PHP 8 `#[...]` is an attribute; treating it as a comment would swallow+ # the argument list.+ (attr,) = list(laravel_routes("Route::get('/z', #[Pure] [C::class, 'i']);"))+ assert attr.handler == "C"++ def test_an_unbalanced_paren_in_a_rust_comment_does_not_eat_the_route(self) -> None:+ routes = list(+ axum_routes(+ '.route(\n "/orders",\n // see issue (123\n'+ " get(list_orders),\n)\n"+ )+ )+ assert [(r.verb, r.path, r.handler) for r in routes] == [+ ("GET", "/orders", "list_orders")+ ]++ def test_a_stray_close_paren_in_a_comment_does_not_truncate_the_arguments(+ self,+ ) -> None:+ (route,) = list(+ laravel_routes(+ "Route::post(\n '/webhook', // closes with )\n"+ " [HookController::class, 'store']\n);"+ )+ )+ assert route.handler == "HookController"+++class TestNestedCallsDoNotInventRoutes:+ def test_a_verb_inside_another_calls_arguments_is_not_a_method_router(+ self,+ ) -> None:+ # `state.options()` used to fabricate an OPTIONS provider on this path,+ # and `cache.head(id)` a HEAD one bound to a symbol named `id`.+ routes = list(+ axum_routes('.route("/x", get(list_items).with_state(state.options()))')+ )+ assert [(r.verb, r.handler) for r in routes] == [("GET", "list_items")]++ def test_a_closure_body_naming_a_verb_yields_one_route(self) -> None:+ routes = list(+ axum_routes('.route("/cfg", get(move || async move { settings.get(&key) }))')+ )+ assert [(r.verb, r.handler) for r in routes] == [("GET", None)]++ def test_chaining_still_reaches_every_top_level_verb(self) -> None:+ # The depth rule must not cost the thing the depth scan was added for.+ routes = list(axum_routes('.route("/x", get(a).post(b).delete(c))'))+ assert [(r.verb, r.handler) for r in routes] == [+ ("GET", "a"),+ ("POST", "b"),+ ("DELETE", "c"),+ ]+++class TestTheHandlerIsNotReadFromTheFirstArgument:+ def test_a_class_constant_in_the_path_expression_is_not_a_handler(self) -> None:+ (route,) = list(+ laravel_routes("Route::get(Legacy::class, [OrderController::class, 'show']);")+ )+ assert route.handler == "OrderController"++ def test_an_at_sign_inside_a_translated_path_is_not_a_legacy_handler(self) -> None:+ (route,) = list(+ laravel_routes("Route::get(trans('Contact@us'), [PageController::class, 's']);")+ )+ assert route.handler == "PageController"++ def test_a_call_with_one_argument_names_no_handler(self) -> None:+ (route,) = list(laravel_routes("Route::get('/only');"))+ assert route.handler is None+++class TestGoHandlerShapes:+ def test_a_composite_literal_handler_is_kept(self) -> None:+ # `mux.Handle("/x", healthHandler{})` is a net/http idiom; requiring+ # `,` or `)` after the handler dropped its edge.+ (route,) = list(go_routes('mux.Handle("/x", healthHandler{})'))+ assert (route.handler, route.handler_call) == ("healthHandler", False)++ def test_an_index_expression_is_not_a_handler(self) -> None:+ # `mlog.Any("selected_field", lookup.Submission["k"])` is a logging call,+ # not a route; the matcher this replaced captured it.+ assert not [r.handler for r in go_routes('r.GET("/x", handlers[0])') if r.handler]++ def test_an_empty_path_under_a_group_is_still_that_groups_route(self) -> None:+ src = 'api := r.Group("/api")\napi.GET("", Index)\n'+ (route,) = list(go_routes(src))+ assert route.path == ""+ assert group_prefixes(go_groups(src)) == {"api": "/api"}+++class TestQualifiedHandlerBinding:+ async def test_a_rust_path_qualified_handler_binds(self, tmp_path: Path) -> None:+ # `symbol_named` split on `.` only, so `handlers::ping` matched nothing+ # and the route silently fell back to binding its router builder.+ (tmp_path / "main.rs").write_text(+ 'use axum::{routing::get, Router};\n\n'+ 'pub fn app() -> Router {\n'+ ' Router::new().route("/ping", get(handlers::ping))\n}\n',+ encoding="utf-8",+ )+ (tmp_path / "handlers.rs").write_text("pub async fn ping() {}\n", encoding="utf-8")+ contracts = [+ c for c in HttpExtractor().extract(tmp_path, "api") if c.role == "provider"+ ]+ index = await _index_of_repo(tmp_path, "*.rs", "rust")+ try:+ expected = {s.name: s.symbol_id for s in index.symbols_for_file("handlers.rs")}+ assert "ping" in expected+ builder = {s.name for s in index.symbols_for_file("main.rs")}+ bind_symbol_ids(contracts, index)+ finally:+ await index.close()+ bound = {c.contract_id: c.symbol_id for c in contracts}+ # The fallback this used to take is a real symbol, so the assertion below+ # discriminates rather than merely finding something.+ assert "app" in builder+ assert bound["http::GET::/ping"] == expected["ping"]diff --git a/tests/unit/workspace/test_grpc_languages.py b/tests/unit/workspace/test_grpc_languages.pynew file mode 100644index 000000000..dd36d1310--- /dev/null+++ b/tests/unit/workspace/test_grpc_languages.py@@ -0,0 +1,128 @@+"""The gRPC stub shapes, one table row per language.++`grpc/{go,java,python,typescript,csharp}.py` were five near-identical modules and+are now five rows in `grpc/languages.py`. A corpus diff over 1,300 candidate+files proved the fold byte-identical for go, java and python — but that corpus+contains no gRPC C# and no `@GrpcMethod` at all, and those two rows carry every+per-language rule the table had to grow a field for: C#'s second provider shape,+its consumer gate and its false-prefix list, and TypeScript's method group.++So they are pinned here, field by field, against what the deleted modules built.+"""++from __future__ import annotations++from repowise.core.workspace.extractors.base import ScanContext+from repowise.core.workspace.extractors.grpc import DIALECTS+++def _extract(suffix: str, content: str) -> list[tuple]:+ ctx = ScanContext("api", f"Sample{suffix}", suffix, content)+ out = []+ for dialect in DIALECTS:+ if suffix in dialect.extensions:+ for c in dialect.extract(ctx):+ out.append(+ (c.contract_id, c.role, c.symbol_name, c.confidence, tuple(c.meta.items()))+ )+ return out+++class TestCSharp:+ def test_both_provider_shapes_and_a_gated_consumer(self) -> None:+ rows = _extract(+ ".cs",+ "using Grpc.Net.Client;\n"+ "app.MapGrpcService<GreeterService>();\n"+ "class Impl : Acme.Rpc.Greeter.GreeterBase { }\n"+ "var c = new AuthServiceClient(channel);\n",+ )+ assert rows == [+ (+ "grpc::GreeterService/*",+ "provider",+ "cs:MapGrpcService<GreeterService>",+ 0.8,+ (("service", "GreeterService"), ("source", "csharp_mapgrpc")),+ ),+ (+ "grpc::Greeter/*",+ "provider",+ # The template says ServiceBase while the regex matched `GreeterBase`.+ # Preserved verbatim from the module this replaced, quirk included.+ "cs:extends Greeter.GreeterServiceBase",+ 0.8,+ (("service", "Greeter"), ("source", "csharp_base")),+ ),+ (+ "grpc::AuthService/*",+ "consumer",+ "cs:new AuthServiceClient",+ 0.65,+ (("service", "AuthService"), ("source", "csharp_client")),+ ),+ ]++ def test_without_a_grpc_marker_only_consumers_are_suppressed(self) -> None:+ # `new XxxClient(...)` also matches TLS and HTTP classes, so it needs the+ # gate — but the providers in the same file must still be emitted.+ rows = _extract(+ ".cs",+ "app.MapGrpcService<GreeterService>();\nvar c = new AuthServiceClient(channel);\n",+ )+ assert [r[1] for r in rows] == ["provider"]++ def test_the_false_prefix_list_includes_http(self) -> None:+ # C#'s list carries "http", python's does not; one shared list would have+ # deleted a real Python `HttpStub` or admitted a C# `HttpClient`.+ rows = _extract(+ ".cs",+ "using Grpc.Core;\nvar a = new HttpClient();\nvar b = new MockThingClient();\n"+ "var c = new RealThingClient();\n",+ )+ assert [r[0] for r in rows] == ["grpc::RealThing/*"]+++class TestTypeScript:+ def test_the_only_method_qualified_contract_id(self) -> None:+ rows = _extract(".ts", "@GrpcMethod('AuthService', 'Login')\nlogin() {}\n")+ assert rows == [+ (+ # Every other language emits `/*`; this is the one that names a method.+ "grpc::AuthService/Login",+ "provider",+ "ts:@GrpcMethod('AuthService', 'Login')",+ 0.8,+ (+ ("service", "AuthService"),+ ("method", "Login"),+ ("source", "ts_decorator"),+ ),+ )+ ]++ def test_typescript_has_no_consumer_shape(self) -> None:+ assert not _extract(".ts", "const s = new AuthServiceClient(channel);\n")+++class TestPythonAndGoKeepTheirOwnRules:+ def test_python_false_prefixes_exclude_test_doubles_but_not_http(self) -> None:+ rows = _extract(+ ".py",+ "a = MockThingStub(ch)\nb = RealThingStub(ch)\nc = HttpThingStub(ch)\n",+ )+ # "http" is absent from python's list, so HttpThing survives — the+ # difference between the two lists that a shared one would erase.+ # Source order, which is the order the dialect emits in.+ assert [r[0] for r in rows] == ["grpc::RealThing/*", "grpc::HttpThing/*"]++ def test_python_needs_no_gate(self) -> None:+ # Unlike C#, a bare `XxxStub(` is credible on its own.+ assert _extract(".py", "s = AuthServiceStub(channel)\n")++ def test_go_emits_both_roles(self) -> None:+ rows = _extract(+ ".go",+ "pb.RegisterAuthServiceServer(s, &impl{})\nc := pb.NewAuthServiceClient(conn)\n",+ )+ assert [(r[1], r[3]) for r in rows] == [("provider", 0.8), ("consumer", 0.7)]