Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(workspace): one recognition of a framework's routes, two consumers (#1860)

Raghav Chamadiya350f6a3a746b
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/aspnet.py b/packages/core/src/repowise/core/ingestion/framework_edges/aspnet.py
index 352ec5edb..4aee42755 100644
--- a/packages/core/src/repowise/core/ingestion/framework_edges/aspnet.py
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/aspnet.py
@@ -9,6 +9,7 @@ import re
from pathlib import Path
from typing import TYPE_CHECKING, Any
+from ..framework_routes import aspnet_routes
from ..resolvers import ResolverContext
from .base import (
DetectionContext,
@@ -25,10 +26,6 @@ if TYPE_CHECKING:
# class name ends in "Controller" (the MVC discovery convention). The first
# is preferred — it produces zero false positives.
_ASPNET_CONTROLLER_ATTR_RE = re.compile(r"\[\s*ApiController\b")
-_ASPNET_ROUTE_RE = re.compile(r"\[\s*(?:Http(?:Get|Post|Put|Delete|Patch|Options|Head)|Route)\b")
-_ASPNET_MAP_CALL_RE = re.compile(
- r"\.\s*Map(?:Get|Post|Put|Delete|Patch|Controllers|Hub|GrpcService|Razor|Fallback)\s*[<(]"
-)
_ASPNET_USE_MIDDLEWARE_RE = re.compile(r"\.\s*UseMiddleware\s*<\s*(\w+)")
_DBCONTEXT_DECL_RE = re.compile(r"class\s+\w+\s*:\s*[\w.<>,\s]*\bDbContext\b")
_DBSET_RE = re.compile(r"\bDbSet\s*<\s*([A-Z]\w*)\s*>")
@@ -113,16 +110,16 @@ def _add_aspnet_edges(
count += 1
# ---- 3. Entry point → file containing handler class referenced in MapXxx ----
- handler_arg_re = re.compile(
- r"\.\s*Map(?:Get|Post|Put|Delete|Patch)\s*\(\s*[\"'][^\"']+[\"']\s*,\s*([A-Za-z_]\w*)"
- )
for entry in entry_points:
text = read_text(parsed_files[entry], encoding="utf-8-sig")
if not text:
continue
- for match in handler_arg_re.finditer(text):
- ident = match.group(1)
- target = type_decl_to_file.get(ident)
+ for route in aspnet_routes(text):
+ if not route.handler:
+ continue # an inline lambda names no type to link to
+ # The leading segment of `OrderHandlers.GetOrder` is the declaring
+ # type; the contract consumer reads the trailing one instead.
+ target = type_decl_to_file.get(route.handler.split(".")[0])
if target and target in path_set and _add_edge_if_new(graph, entry, target):
count += 1
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/express.py b/packages/core/src/repowise/core/ingestion/framework_edges/express.py
index f512d5ee0..20f231c5e 100644
--- a/packages/core/src/repowise/core/ingestion/framework_edges/express.py
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/express.py
@@ -8,6 +8,7 @@ from __future__ import annotations
import re
from typing import TYPE_CHECKING, Any
+from ..framework_routes import express_routes
from ..resolvers import ResolverContext
from .base import (
DetectionContext,
@@ -31,9 +32,6 @@ _IDENT_RE = re.compile(r"\b([A-Z]\w*)\b")
_EXPRESS_RECEIVER_RE = re.compile(
r"\b(\w+)\s*(?::[^=;\n]+)?=\s*(?:express\s*\(\s*\)|(?:express\s*\.\s*)?Router\s*\()"
)
-_ROUTE_CALL_START_RE = re.compile(
- r"\b(\w+)\s*\.\s*(?:get|post|put|delete|patch|options|head|all|use)\s*\("
-)
_STRING_LITERAL_RE = re.compile(r"'(?:[^'\\]|\\.)*'|\"(?:[^\"\\]|\\.)*\"|`(?:[^`\\]|\\.)*`")
_ARG_IDENT_RE = re.compile(r"[A-Za-z_$][\w$]*")
@@ -103,13 +101,15 @@ def _add_express_edges(
receivers = {m.group(1) for m in _EXPRESS_RECEIVER_RE.finditer(text)}
if local_funcs and receivers:
module_sym = f"{path}::__module__"
- for m in _ROUTE_CALL_START_RE.finditer(text):
- if m.group(1) not in receivers:
+ for route in express_routes(text):
+ if route.receiver not in receivers:
continue
- close = _match_paren(text, m.end() - 1)
+ close = _match_paren(text, route.paren_offset)
if close == -1:
continue
- arg_blob = _STRING_LITERAL_RE.sub("", text[m.end() : close])
+ arg_blob = _STRING_LITERAL_RE.sub(
+ "", text[route.paren_offset + 1 : close]
+ )
for ident in _ARG_IDENT_RE.finditer(arg_blob):
sym_id = local_funcs.get(ident.group(0))
if sym_id and add_symbol_edge(graph, module_sym, sym_id):
diff --git a/packages/core/src/repowise/core/ingestion/framework_routes.py b/packages/core/src/repowise/core/ingestion/framework_routes.py
new file mode 100644
index 000000000..a62cdd677
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/framework_routes.py
@@ -0,0 +1,146 @@
+"""One recognition of a framework's route-registration syntax, two consumers.
+
+``ingestion.framework_edges`` turns a route into a file-to-file graph edge, from
+the handler expression; ``workspace.extractors.http`` turns the same route into
+an HTTP contract, from the method and path. Each was matching the construct with
+its own regex and carrying its own bug history, so a fix landed on one side only
+(``MapGroup`` was missing from both, and ``[Route(...)]`` prefixes from one).
+
+The shared thing is the *match*, not the result: a :class:`RouteMatch` carries
+every part either consumer reads, and each builds its own output from the parts
+it cares about. Argument semantics stay with the consumer — Express middleware
+chains name several handlers, ASP.NET minimal APIs name at most one.
+
+Placed under ``ingestion`` because the workspace layer imports from it and never
+the other way round.
+"""
+
+from __future__ import annotations
+
+import re
+from collections.abc import Iterator
+from dataclasses import dataclass
+
+#: Verbs the contract layer records as an HTTP method. A consumer that sees a
+#: wider verb set (Express ``use``/``all``) filters against this.
+HTTP_METHODS = frozenset({"GET", "POST", "PUT", "DELETE", "PATCH"})
+
+
+@dataclass(frozen=True)
+class RouteMatch:
+ """One route-registration call site."""
+
+ verb: str # upper-cased as written; not necessarily an HTTP method
+ path: str | None # raw route text, None when the call carries no literal
+ receiver: str | None # variable the call hangs off, for group-prefix lookup
+ handler: str | None # handler argument, when the shape names one identifier
+ offset: int # match start, for line and nearest-prefix lookups
+ paren_offset: int # the '(' opening the call, for an argument scan
+
+
+@dataclass(frozen=True)
+class GroupMatch:
+ """One router-group binding — ``var v1 = api.MapGroup("/v1")``."""
+
+ var: str
+ parent: str | None
+ prefix: str
+
+
+def _opt(value: str | None) -> str | None:
+ return value or None
+
+
+# ---------------------------------------------------------------------------
+# ASP.NET
+# ---------------------------------------------------------------------------
+
+def _cs_str(name: str) -> str:
+ """A C# string-literal argument, capturing its body as *name*.
+
+ The optional verbatim (``@``) / interpolated (``$``) prefix is taken from
+ ``extractors.http.csharp_http`` — the only one of this tree's three C# route
+ matchers that handled either. Single quotes stay accepted because both
+ matchers this replaces took them, and narrowing would be a reduction.
+ """
+ return rf"\$?@?(?P<{name}_q>['\"])(?P<{name}>[^'\"]*)(?P={name}_q)"
+
+
+# app.MapGet("/users", GetUsers). The receiver may be empty for a fluent chain
+# (`.MapGroup("/api").MapGet(...)`). The handler must be followed by `,` or `)`:
+# without that a lambda's own parameter is captured as the handler name —
+# `MapPut("/z", async ctx => ...)` yields `async`, which the graph side merely
+# failed to resolve but which the contract side would persist and bind by.
+_ASPNET_MAP_RE = re.compile(
+ r"(?P<receiver>\w*)\s*\.\s*Map(?P<verb>Get|Post|Put|Delete|Patch)\s*(?P<paren>\()"
+ rf"\s*{_cs_str('path')}"
+ r"(?:\s*,\s*(?P<handler>[A-Za-z_]\w*(?:\s*\.\s*[A-Za-z_]\w*)*)\s*(?=[,)]))?",
+ re.IGNORECASE,
+)
+
+# var admin = app.MapGroup("/admin") — groups nest, so the parent is captured for
+# transitive composition by `mounts.group_prefixes`.
+_ASPNET_GROUP_RE = re.compile(
+ rf"(?P<var>\w+)\s*=\s*(?P<parent>\w*)\s*\.\s*MapGroup\s*\(\s*{_cs_str('prefix')}",
+ re.IGNORECASE,
+)
+
+
+def aspnet_routes(content: str) -> Iterator[RouteMatch]:
+ """Minimal-API ``.MapGet("/path", Handler)`` calls in *content*."""
+ for m in _ASPNET_MAP_RE.finditer(content):
+ handler = m.group("handler")
+ yield RouteMatch(
+ verb=m.group("verb").upper(),
+ path=m.group("path"),
+ receiver=_opt(m.group("receiver")),
+ handler=re.sub(r"\s+", "", handler) if handler else None,
+ offset=m.start(),
+ paren_offset=m.start("paren"),
+ )
+
+
+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")
+ )
+
+
+# ---------------------------------------------------------------------------
+# Express / Node
+# ---------------------------------------------------------------------------
+
+# `use` and `all` are here because the graph consumer scans them for handler
+# functions; the contract consumer drops them via HTTP_METHODS.
+_EXPRESS_VERBS = "get|post|put|delete|patch|options|head|all|use"
+
+# router.get('/path', handler). The path literal is optional — `app.use(router)`
+# carries none. The lookbehind excludes a word character as well as `@`, which
+# neither copy did: `\b` alone admits `@app.get` (a FastAPI/NestJS decorator, not
+# an Express route), and `(?<!@)` alone lets the engine restart inside the name
+# and match `pp.get` there instead.
+_EXPRESS_ROUTE_RE = re.compile(
+ rf"(?<![\w@])(?P<receiver>\w+)\s*\.\s*(?P<verb>{_EXPRESS_VERBS})\s*(?P<paren>\()"
+ r"""\s*(?:(?P<q>['"])(?P<path>[^'"]*)(?P=q))?""",
+ re.IGNORECASE,
+)
+
+
+def express_routes(content: str) -> Iterator[RouteMatch]:
+ """Router/app route registrations in *content*.
+
+ ``handler`` is always None: an Express call takes a middleware chain, so
+ naming one identifier would be a guess. The graph consumer scans the
+ argument list itself from ``paren_offset``.
+ """
+ for m in _EXPRESS_ROUTE_RE.finditer(content):
+ yield RouteMatch(
+ verb=m.group("verb").upper(),
+ path=m.group("path"),
+ receiver=m.group("receiver"),
+ handler=None,
+ offset=m.start(),
+ paren_offset=m.start("paren"),
+ )
diff --git a/packages/core/src/repowise/core/workspace/contracts.py b/packages/core/src/repowise/core/workspace/contracts.py
index 412638fc7..6da948306 100644
--- a/packages/core/src/repowise/core/workspace/contracts.py
+++ b/packages/core/src/repowise/core/workspace/contracts.py
@@ -42,10 +42,12 @@ _log = logging.getLogger("repowise.workspace.contracts")
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 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``.
#: 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 = 4
+CONTRACTS_VERSION = 5
# ---------------------------------------------------------------------------
@@ -243,6 +245,10 @@ def bind_symbol_ids(contracts: list[Contract], index: RepoIndex | None) -> dict[
are left alone here. Which of the two lookups applies is the one thing a
contract's own shape decides: see :data:`_DECLARED_ABOVE`.
+ A provider whose ``meta`` names a ``handler`` binds to that symbol first: an
+ ASP.NET minimal API declares the route in ``Program.cs`` and defines the
+ handler elsewhere, so the line lookup would bind it to the registration site.
+
Mutates *contracts* in place and returns the one counter the artifact
cannot recover on its own: ``identity_unindexed_<role>``, contracts whose
file has no parsed symbols at all — a ``.sql`` file, or a repo with no
@@ -252,6 +258,14 @@ def bind_symbol_ids(contracts: list[Contract], index: RepoIndex | None) -> dict[
"""
counts: dict[str, int] = {}
for contract in contracts:
+ meta = contract.meta or {}
+ handler = meta.get("handler") if contract.role == "provider" else None
+ if contract.symbol_id is None and index is not None and handler:
+ # The whole expression, qualifier included: the graph consumer reads
+ # `OrderHandlers` out of it to find a file, this one needs the member.
+ symbol = index.symbol_named(handler)
+ if symbol is not None:
+ contract.symbol_id = symbol.symbol_id
if contract.symbol_id is None and index is not None and contract.line is not None:
declares = contract.role == "provider" and contract.contract_type in _DECLARED_ABOVE
lookup = index.declared_symbol_at if declares else index.symbol_at
diff --git a/packages/core/src/repowise/core/workspace/extractors/http/aspnet.py b/packages/core/src/repowise/core/workspace/extractors/http/aspnet.py
index 48f433444..22b734cc1 100644
--- a/packages/core/src/repowise/core/workspace/extractors/http/aspnet.py
+++ b/packages/core/src/repowise/core/workspace/extractors/http/aspnet.py
@@ -5,8 +5,11 @@ Covers three shapes that can co-exist in one file:
* attribute routing — ``[HttpGet("path")]`` stitched onto the class
``[Route("api/users")]`` prefix;
* parameterless attributes — ``[HttpPost]`` whose route is the class prefix;
-* minimal APIs — ``app.MapGet("/users", ...)`` (not inside a controller, so
- never prefix-stitched).
+* minimal APIs — ``app.MapGet("/users", ...)``, prefix-stitched onto the
+ ``MapGroup`` chain the receiver is bound to rather than onto a class route.
+
+The minimal-API shape is recognised by ``ingestion.framework_routes``, shared
+with the graph-edge builder that reads the same call for its handler argument.
"""
from __future__ import annotations
@@ -14,9 +17,12 @@ from __future__ import annotations
import re
from typing import TYPE_CHECKING
+from repowise.core.ingestion.framework_routes import aspnet_groups, aspnet_routes
+
from ..base import line_at
from ..langs import CSHARP
-from .dialect import METHODS, build_provider_contract, nearest_prefix
+from .dialect import build_provider_contract, nearest_prefix
+from .mounts import compose_prefix, group_prefixes
if TYPE_CHECKING:
from repowise.core.workspace.contracts import Contract
@@ -42,12 +48,6 @@ _ASPNET_CLASS_ROUTE_RE = re.compile(
r"""\[\s*Route\s*\(\s*['"]([^'"]+)['"]""",
)
-# Minimal API: app.MapGet("/users", ...) — same shape, different method names.
-_ASPNET_MINIMAL_RE = re.compile(
- rf"""\.\s*Map({METHODS})\s*\(\s*['"]([^'"]+)['"]""",
- re.IGNORECASE,
-)
-
class AspNetDialect:
name = "aspnet"
@@ -78,14 +78,17 @@ class AspNetDialect:
if c is not None:
out.append(c)
- # Minimal API — not inside a controller, never prefix-stitched.
- for m in _ASPNET_MINIMAL_RE.finditer(content):
+ # Minimal API — the prefix comes from the MapGroup chain its receiver
+ # is bound to, not from a class [Route(...)].
+ prefixes = group_prefixes(aspnet_groups(content))
+ for route in aspnet_routes(content):
c = build_provider_contract(
ctx,
- method=m.group(1).upper(),
- path_raw=m.group(2),
+ method=route.verb,
+ path_raw=compose_prefix(prefixes.get(route.receiver or "", ""), route.path or ""),
framework="aspnet-minimal",
- line=line_at(content, m.start()),
+ line=line_at(content, route.offset),
+ handler=route.handler,
)
if c is not None:
out.append(c)
diff --git a/packages/core/src/repowise/core/workspace/extractors/http/dialect.py b/packages/core/src/repowise/core/workspace/extractors/http/dialect.py
index 56aded7a0..675ee69ba 100644
--- a/packages/core/src/repowise/core/workspace/extractors/http/dialect.py
+++ b/packages/core/src/repowise/core/workspace/extractors/http/dialect.py
@@ -66,12 +66,18 @@ def build_provider_contract(
framework: str,
line: int | None = None,
confidence: float = 0.85,
+ handler: str | None = None,
) -> Contract | None:
"""Build a provider contract, or ``None`` if the path is unusable.
A match whose path normalizes to bare ``/`` only counts when the raw text
actually carried a path — a template-variable-only or empty route is
dropped, matching the legacy extractor's skip rule.
+
+ *handler* is the expression the registration names, for frameworks that
+ declare a route away from its handler (an ASP.NET minimal API). It is what
+ lets :func:`.contracts.bind_symbol_ids` reach the handler rather than the
+ registration site; without it the line lookup binds to ``Program.cs``.
"""
from repowise.core.workspace.contracts import Contract
@@ -89,7 +95,12 @@ def build_provider_contract(
confidence=confidence,
service=None,
line=line,
- meta={"method": method, "path": norm_path, "framework": framework},
+ meta={
+ "method": method,
+ "path": norm_path,
+ "framework": framework,
+ **({"handler": handler} if handler else {}),
+ },
)
diff --git a/packages/core/src/repowise/core/workspace/extractors/http/express.py b/packages/core/src/repowise/core/workspace/extractors/http/express.py
index 16c37ac77..1db964ea3 100644
--- a/packages/core/src/repowise/core/workspace/extractors/http/express.py
+++ b/packages/core/src/repowise/core/workspace/extractors/http/express.py
@@ -3,6 +3,9 @@
Express routers carry no in-file prefix; the mount lives in a separate
``app.use('/prefix', router)`` call, so the real path is recovered by stitching
the cross-file mount prefix (collected by the orchestrator) onto the route.
+
+The route call itself is recognised by ``ingestion.framework_routes``, shared
+with the graph-edge builder that scans the same call's argument list.
"""
from __future__ import annotations
@@ -10,9 +13,11 @@ from __future__ import annotations
import re
from typing import TYPE_CHECKING
+from repowise.core.ingestion.framework_routes import HTTP_METHODS, express_routes
+
from ..base import line_at
from ..langs import JS_TS
-from .dialect import METHODS, build_provider_contract
+from .dialect import build_provider_contract
from .mounts import compose_prefix
if TYPE_CHECKING:
@@ -20,14 +25,6 @@ if TYPE_CHECKING:
from ..base import ScanContext
-# router.get('/path', ...) / app.post('/path', ...). The receiver variable is
-# captured so its mount prefix can be resolved; the negative lookbehind for ``@``
-# keeps decorator frameworks (FastAPI ``@app.get``, NestJS ``@Get``) out.
-_EXPRESS_RE = re.compile(
- rf"""(?<!@)(\w+)\.({METHODS})\s*\(\s*['"]([^'"]+)['"]""",
- re.IGNORECASE,
-)
-
# Variables bound to an Express app / router: ``r = express.Router()``,
# ``app = express()``, ``router = require('express').Router()``.
_ROUTER_BIND_RE = re.compile(r"""(\w+)\s*=\s*(?:[\w.]*\.Router\s*\(|express\s*\(|Router\s*\()""")
@@ -54,17 +51,19 @@ class ExpressDialect:
known |= _DEFAULT_ROUTER_NAMES
out: list[Contract] = []
- for m in _EXPRESS_RE.finditer(ctx.content):
- var, method, path_raw = m.group(1), m.group(2), m.group(3)
- if var not in known:
+ for route in express_routes(ctx.content):
+ # The registry also yields `use`/`all`, which the graph consumer
+ # scans for handlers but which name no HTTP method here.
+ if route.verb not in HTTP_METHODS or not route.path:
+ continue
+ if route.receiver not in known:
continue
- path = compose_prefix(ctx.mounts.get(var, ""), path_raw)
c = build_provider_contract(
ctx,
- method=method.upper(),
- path_raw=path,
+ method=route.verb,
+ path_raw=compose_prefix(ctx.mounts.get(route.receiver, ""), route.path),
framework="express",
- 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/go.py b/packages/core/src/repowise/core/workspace/extractors/http/go.py
index be2ad7d5b..920143f25 100644
--- a/packages/core/src/repowise/core/workspace/extractors/http/go.py
+++ b/packages/core/src/repowise/core/workspace/extractors/http/go.py
@@ -11,10 +11,12 @@ from __future__ import annotations
import re
from typing import TYPE_CHECKING
+from repowise.core.ingestion.framework_routes import GroupMatch
+
from ..base import line_at
from ..langs import GO
from .dialect import METHODS_UPPER, build_provider_contract
-from .mounts import compose_prefix
+from .mounts import compose_prefix, group_prefixes
if TYPE_CHECKING:
from repowise.core.workspace.contracts import Contract
@@ -33,28 +35,11 @@ _GO_ROUTE_RE = re.compile(
)
-def _group_prefixes(content: str) -> dict[str, str]:
- """Resolve each group variable to its full, transitively-composed prefix."""
- # child -> (parent, segment)
- edges: dict[str, tuple[str, str]] = {}
- for m in _GROUP_RE.finditer(content):
- edges[m.group(1)] = (m.group(2), m.group(3))
-
- resolved: dict[str, str] = {}
-
- def resolve(var: str, seen: frozenset[str]) -> str:
- if var in resolved:
- return resolved[var]
- if var not in edges or var in seen:
- return "" # base router (gin.Default()/echo.New()) or a cycle
- parent, segment = edges[var]
- prefix = compose_prefix(resolve(parent, seen | {var}), segment)
- resolved[var] = prefix
- return prefix
-
- for var in edges:
- resolve(var, frozenset())
- return resolved
+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)
+ ]
class GoDialect:
@@ -62,7 +47,7 @@ class GoDialect:
extensions = GO
def extract(self, ctx: ScanContext) -> list[Contract]:
- prefixes = _group_prefixes(ctx.content)
+ prefixes = group_prefixes(_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)
diff --git a/packages/core/src/repowise/core/workspace/extractors/http/mounts.py b/packages/core/src/repowise/core/workspace/extractors/http/mounts.py
index 97208b07c..b1f1f8c66 100644
--- a/packages/core/src/repowise/core/workspace/extractors/http/mounts.py
+++ b/packages/core/src/repowise/core/workspace/extractors/http/mounts.py
@@ -20,6 +20,9 @@ collected per dialect and merged by the orchestrator.
from __future__ import annotations
import re
+from collections.abc import Iterable
+
+from repowise.core.ingestion.framework_routes import GroupMatch
# A ``prefix="..."`` / ``prefix='...'`` keyword argument inside a constructor call.
_PREFIX_KW_RE = re.compile(r"""prefix\s*=\s*['"]([^'"]+)['"]""")
@@ -86,3 +89,30 @@ def merge_mount_maps(maps: list[dict[str, str]]) -> dict[str, str]:
for var, prefix in m.items():
collected.setdefault(var, set()).add(prefix)
return {var: next(iter(prefixes)) for var, prefixes in collected.items() if len(prefixes) == 1}
+
+
+def group_prefixes(groups: Iterable[GroupMatch]) -> dict[str, str]:
+ """Resolve each router-group variable to its transitively composed prefix.
+
+ ``api := r.Group("/api"); v1 := api.Group("/v1")`` gives ``v1 -> /api/v1``.
+ A variable with no binding (the base router) or in a cycle resolves to the
+ empty string, so a route on it keeps its literal path.
+ """
+ edges = {g.var: (g.parent, g.prefix) for g in groups}
+ resolved: dict[str, str] = {}
+
+ def resolve(var: str | None, seen: frozenset[str]) -> str:
+ if var is None:
+ return ""
+ if var in resolved:
+ return resolved[var]
+ if var not in edges or var in seen:
+ return ""
+ parent, segment = edges[var]
+ prefix = compose_prefix(resolve(parent, seen | {var}), segment)
+ resolved[var] = prefix
+ return prefix
+
+ for var in edges:
+ resolve(var, frozenset())
+ return resolved
diff --git a/packages/core/src/repowise/core/workspace/repo_index.py b/packages/core/src/repowise/core/workspace/repo_index.py
index 1897f36a0..b7e8e42ce 100644
--- a/packages/core/src/repowise/core/workspace/repo_index.py
+++ b/packages/core/src/repowise/core/workspace/repo_index.py
@@ -83,6 +83,7 @@ class RepoIndex:
self._session = session
self._engine = engine
self._by_file: dict[str, list[IndexedSymbol]] = {}
+ self._by_name: dict[str, list[IndexedSymbol]] = {}
self._externals: list[ExternalImport] = []
# -- Loading -----------------------------------------------------------
@@ -127,6 +128,8 @@ class RepoIndex:
# the last is the method.
for symbols in self._by_file.values():
symbols.sort(key=lambda s: (s.start_line, -s.end_line))
+ for sym in symbols:
+ self._by_name.setdefault(sym.name, []).append(sym)
edges = await self._session.execute(
select(
@@ -200,6 +203,21 @@ class RepoIndex:
return following
return containing
+ 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.
+ """
+ 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)]
+ return found[0] if len(found) == 1 else None
+
def external_import_edges(self) -> list[ExternalImport]:
"""Every ``imports`` edge leaving the repo, with the names it consumes."""
return self._externals
diff --git a/tests/unit/workspace/test_framework_routes.py b/tests/unit/workspace/test_framework_routes.py
new file mode 100644
index 000000000..be76450ac
--- /dev/null
+++ b/tests/unit/workspace/test_framework_routes.py
@@ -0,0 +1,294 @@
+"""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.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+from typing import Any
+
+import networkx as nx
+
+from repowise.core.ingestion.framework_edges import add_framework_edges
+from repowise.core.ingestion.framework_routes import (
+ HTTP_METHODS,
+ aspnet_groups,
+ aspnet_routes,
+ express_routes,
+)
+from repowise.core.ingestion.models import FileInfo, Symbol
+from repowise.core.ingestion.parser import ASTParser
+from repowise.core.ingestion.resolvers.context import ResolverContext
+from repowise.core.workspace.contracts import bind_symbol_ids
+from repowise.core.workspace.extractors.http_extractor import HttpExtractor
+
+from ._repo_index import make_repo_index
+
+# A minimal API written the way the shapes actually co-occur: a nested MapGroup
+# chain, a handler named by type and method, and an inline lambda that names
+# nothing. Both consumers below read this one text.
+PROGRAM_CS = """\
+using Microsoft.AspNetCore.Builder;
+
+var app = WebApplication.Create(args);
+
+var api = app.MapGroup("/api");
+var orders = api.MapGroup(@"/orders");
+
+orders.MapGet("/{id}", OrderHandlers.GetOrder);
+orders.MapPost("", OrderHandlers.CreateOrder);
+app.MapDelete($"/tenants/{tenant}/cache", () => Results.NoContent());
+app.MapControllers();
+"""
+
+HANDLERS_CS = """\
+namespace Acme.Api;
+
+public static class OrderHandlers
+{
+ public static IResult GetOrder(int id) => Results.Ok(id);
+ public static IResult CreateOrder(OrderRequest body) => Results.Ok();
+}
+"""
+
+
+# ---------------------------------------------------------------------------
+# The shared recognition
+# ---------------------------------------------------------------------------
+
+
+class TestAspNetRecognition:
+ def test_every_map_shape_is_matched_once(self) -> None:
+ routes = list(aspnet_routes(PROGRAM_CS))
+ assert [(r.verb, r.path, r.receiver, r.handler) for r in routes] == [
+ ("GET", "/{id}", "orders", "OrderHandlers.GetOrder"),
+ ("POST", "", "orders", "OrderHandlers.CreateOrder"),
+ ("DELETE", "/tenants/{tenant}/cache", "app", None),
+ ]
+
+ def test_map_controllers_is_not_a_route(self) -> None:
+ # `Map(Get|Post|...)` must not swallow the discovery anchor.
+ assert not list(aspnet_routes("app.MapControllers();"))
+
+ def test_verbatim_and_interpolated_paths_are_read(self) -> None:
+ # Neither Map matcher this replaced handled either prefix; the handling
+ # comes from the C# consumer dialect, which did.
+ paths = [r.path for r in aspnet_routes('a.MapGet(@"/v", H); a.MapPut($"/w", H);')]
+ assert paths == ["/v", "/w"]
+
+ def test_groups_carry_their_parent(self) -> None:
+ assert [(g.var, g.parent, g.prefix) for g in aspnet_groups(PROGRAM_CS)] == [
+ ("api", "app", "/api"),
+ ("orders", "api", "/orders"),
+ ]
+
+
+class TestExpressRecognition:
+ def test_receiver_verb_and_path(self) -> None:
+ routes = list(express_routes("router.get('/api/users', auth, listUsers);"))
+ assert [(r.verb, r.path, r.receiver) for r in routes] == [
+ ("GET", "/api/users", "router")
+ ]
+
+ def test_middleware_verbs_are_yielded_but_are_not_http_methods(self) -> None:
+ # The graph consumer scans `use`/`all` for handler functions; the
+ # contract consumer drops them against HTTP_METHODS.
+ verbs = {r.verb for r in express_routes("app.use('/api', router); app.all('/x', h);")}
+ assert verbs == {"USE", "ALL"}
+ assert not verbs & HTTP_METHODS
+
+ def test_a_decorator_is_not_a_route(self) -> None:
+ assert not list(express_routes("@app.get('/items')"))
+
+ def test_a_call_with_no_path_still_reports_its_paren(self) -> None:
+ (route,) = list(express_routes("app.use(router);"))
+ assert route.path is None
+ assert route.paren_offset == len("app.use")
+
+
+# ---------------------------------------------------------------------------
+# Consumer 1 — graph edges
+# ---------------------------------------------------------------------------
+
+
+def _parsed(repo: Path) -> dict[str, Any]:
+ parser = ASTParser()
+ out: dict[str, Any] = {}
+ for cs in repo.rglob("*.cs"):
+ rel = cs.resolve().relative_to(repo.resolve()).as_posix()
+ fi = FileInfo(
+ path=rel,
+ abs_path=str(cs.resolve()),
+ language="csharp",
+ size_bytes=cs.stat().st_size,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=rel.endswith("Program.cs"),
+ )
+ out[rel] = parser.parse_file(fi, cs.read_bytes())
+ return out
+
+
+class TestGraphConsumer:
+ def test_minimal_api_handler_links_the_entry_point_to_its_file(
+ self, tmp_path: Path
+ ) -> None:
+ (tmp_path / "Program.cs").write_text(PROGRAM_CS, encoding="utf-8")
+ (tmp_path / "OrderHandlers.cs").write_text(HANDLERS_CS, encoding="utf-8")
+ parsed = _parsed(tmp_path)
+ 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=tmp_path,
+ )
+ add_framework_edges(graph, parsed, ctx, ["aspnet"])
+ assert graph.has_edge("Program.cs", "OrderHandlers.cs")
+
+
+# ---------------------------------------------------------------------------
+# Consumer 2 — HTTP contracts
+# ---------------------------------------------------------------------------
+
+
+class TestContractConsumer:
+ def _extract(self, tmp_path: Path) -> dict[str, Any]:
+ (tmp_path / "Program.cs").write_text(PROGRAM_CS, encoding="utf-8")
+ return {
+ c.contract_id: c
+ for c in HttpExtractor().extract(tmp_path, "api")
+ if c.role == "provider"
+ }
+
+ def test_map_group_prefixes_are_stitched(self, tmp_path: Path) -> None:
+ ids = set(self._extract(tmp_path))
+ # Without MapGroup these were "/{param}" and an empty path, which the
+ # builder drops entirely.
+ assert "http::GET::/api/orders/{param}" in ids
+ assert "http::POST::/api/orders" in ids
+
+ def test_an_ungrouped_route_keeps_its_literal_path(self, tmp_path: Path) -> None:
+ assert "http::DELETE::/tenants/{param}/cache" in self._extract(tmp_path)
+
+ def test_the_handler_is_recorded_for_binding(self, tmp_path: Path) -> None:
+ contract = self._extract(tmp_path)["http::GET::/api/orders/{param}"]
+ assert contract.meta["handler"] == "OrderHandlers.GetOrder"
+
+ def test_a_lambda_parameter_is_not_a_handler(self, tmp_path: Path) -> None:
+ # `async ctx =>` used to yield handler="async", which the graph side only
+ # failed to resolve but the contract side would persist and bind by.
+ (tmp_path / "Program.cs").write_text(
+ 'app.MapPut("/z", async ctx => await Do(ctx));\n'
+ 'app.MapPatch("/y", ctx => Handle(ctx));\n'
+ 'app.MapGet("/x", Handlers.Get);\n',
+ encoding="utf-8",
+ )
+ handlers = {
+ c.contract_id: c.meta.get("handler")
+ for c in HttpExtractor().extract(tmp_path, "api")
+ if c.role == "provider"
+ }
+ assert handlers == {
+ "http::PUT::/z": None,
+ "http::PATCH::/y": None,
+ "http::GET::/x": "Handlers.Get",
+ }
+
+ def test_a_single_quoted_path_is_still_read(self, tmp_path: Path) -> None:
+ # Not valid C#, but both matchers this replaced accepted it, and the
+ # gate for this phase is that no framework loses a contract.
+ (tmp_path / "Program.cs").write_text("app.MapGet('/legacy', H);\n", encoding="utf-8")
+ ids = {c.contract_id for c in HttpExtractor().extract(tmp_path, "api")}
+ assert "http::GET::/legacy" in ids
+
+
+# ---------------------------------------------------------------------------
+# What the handler buys: identity
+# ---------------------------------------------------------------------------
+
+
+async def _index_of(tmp_path: Path) -> Any:
+ """Open an index over the rows real ingestion produces for the fixtures.
+
+ The symbol ids are never written by hand. C# ingestion mints
+ ``OrderHandlers.cs::OrderHandlers::GetOrder`` — class-qualified, not the
+ ``<file>::<name>`` shape a fixture would guess — and `Program.cs` is
+ top-level statements, so it yields no symbols at all.
+ """
+ parsed = _parsed(tmp_path)
+ by_file: dict[str, list[Symbol]] = {}
+ for rel, pf in parsed.items():
+ for sym in pf.symbols:
+ sym.file_path = rel
+ by_file[rel] = list(pf.symbols)
+ return await make_repo_index(tmp_path, by_file, alias="api")
+
+
+class TestHandlerBinding:
+ async def test_a_route_binds_to_its_handler_not_its_registration(
+ self, tmp_path: Path
+ ) -> None:
+ (tmp_path / "Program.cs").write_text(PROGRAM_CS, encoding="utf-8")
+ (tmp_path / "OrderHandlers.cs").write_text(HANDLERS_CS, encoding="utf-8")
+ contracts = [
+ c for c in HttpExtractor().extract(tmp_path, "api") if c.role == "provider"
+ ]
+ index = await _index_of(tmp_path)
+ try:
+ # The expected ids come from the parse, not from this file.
+ expected = {
+ s.name: s.symbol_id
+ for s in index.symbols_for_file("OrderHandlers.cs")
+ if s.kind == "method"
+ }
+ assert set(expected) == {"GetOrder", "CreateOrder"}
+ 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/orders/{param}"] == expected["GetOrder"]
+ assert bound["http::POST::/api/orders"] == expected["CreateOrder"]
+ # The lambda route names no handler and Program.cs has no symbols to fall
+ # back to, so it stays unbound — as it did before this change.
+ assert bound["http::DELETE::/tenants/{param}/cache"] is None
+
+ async def test_an_ambiguous_handler_is_refused_end_to_end(self, tmp_path: Path) -> None:
+ (tmp_path / "Program.cs").write_text(
+ 'app.MapGet("/a", Handle);\napp.MapGet("/b", Two.Handle);\n', encoding="utf-8"
+ )
+ for name in ("One", "Two"):
+ (tmp_path / f"{name}.cs").write_text(
+ f"public static class {name}\n{{\n"
+ " public static IResult Handle() => Results.Ok();\n}\n",
+ encoding="utf-8",
+ )
+ contracts = [
+ c for c in HttpExtractor().extract(tmp_path, "api") if c.role == "provider"
+ ]
+ index = await _index_of(tmp_path)
+ try:
+ bind_symbol_ids(contracts, index)
+ two = index.symbol_named("Two.Handle")
+ one = index.symbol_named("One.Handle")
+ finally:
+ await index.close()
+ # Both really are in the index, so the refusal below is not vacuous.
+ assert one is not None and two is not None and one.symbol_id != two.symbol_id
+ bound = {c.contract_id: c.symbol_id for c in contracts}
+ # Bare `Handle` names two symbols, so it binds to neither.
+ assert bound["http::GET::/a"] is None
+ # `Two.Handle` carries the qualifier that settles it.
+ assert two is not None
+ assert bound["http::GET::/b"] == two.symbol_id