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): bind cross-repo contracts to real symbol ids (#1830)
Raghav Chamadiya82153afb6bb7
diff --git a/packages/core/src/repowise/core/workspace/breaking_change.py b/packages/core/src/repowise/core/workspace/breaking_change.pyindex e75c548c8..224b25b8c 100644--- a/packages/core/src/repowise/core/workspace/breaking_change.py+++ b/packages/core/src/repowise/core/workspace/breaking_change.py@@ -87,9 +87,13 @@ class ImpactedConsumer:symbol: strmatch_type: strconfidence: float+ #: The ingestion symbol id behind ``symbol``, when the contract bound to+ #: one. ``symbol`` is a display label ("axios:GET /v1/orders"); this is what+ #: an agent can pass to ``get_symbol`` / ``get_context``.+ symbol_id: str | None = Nonedef to_dict(self) -> dict[str, Any]:- return {+ d = {"repo": self.repo,"service": self.service,"node_id": self.node_id,@@ -98,6 +102,9 @@ class ImpactedConsumer:"match_type": self.match_type,"confidence": self.confidence,}+ if self.symbol_id is not None:+ d["symbol_id"] = self.symbol_id+ return d@classmethoddef from_dict(cls, data: dict[str, Any]) -> ImpactedConsumer:@@ -109,6 +116,7 @@ class ImpactedConsumer:symbol=data.get("symbol", ""),match_type=data.get("match_type", "exact"),confidence=data.get("confidence", 0.0),+ symbol_id=data.get("symbol_id"),)@@ -125,6 +133,8 @@ class BreakingChange:provider_symbol: strprovider_service: str | Nonedetail: str # human-readable one-liner+ #: The provider handler's symbol id, when its contract bound to one.+ provider_symbol_id: str | None = Nonefield_name: str | None = Noneold_value: str | None = Nonenew_value: str | None = None@@ -148,6 +158,8 @@ class BreakingChange:"detail": self.detail,"impacted_consumers": [c.to_dict() for c in self.impacted_consumers],}+ if self.provider_symbol_id is not None:+ d["provider_symbol_id"] = self.provider_symbol_idif self.field_name is not None:d["field_name"] = self.field_nameif self.old_value is not None:@@ -166,6 +178,7 @@ class BreakingChange:provider_repo=data.get("provider_repo", ""),provider_file=data.get("provider_file", ""),provider_symbol=data.get("provider_symbol", ""),+ provider_symbol_id=data.get("provider_symbol_id"),provider_service=data.get("provider_service"),detail=data.get("detail", ""),field_name=data.get("field_name"),@@ -486,6 +499,7 @@ def _resolve_impacted(node_id=node_id,file=lk.consumer_file,symbol=lk.consumer_symbol,+ symbol_id=lk.consumer_symbol_id,match_type=lk.match_type,confidence=lk.confidence,)@@ -550,6 +564,7 @@ def detect_breaking_changes(provider_repo=rep.repo,provider_file=rep.file_path,provider_symbol=rep.symbol_name,+ provider_symbol_id=rep.symbol_id,provider_service=rep.service,detail=raw.detail,field_name=raw.field_name,diff --git a/packages/core/src/repowise/core/workspace/contracts.py b/packages/core/src/repowise/core/workspace/contracts.pyindex aa3fb843a..289209296 100644--- a/packages/core/src/repowise/core/workspace/contracts.py+++ b/packages/core/src/repowise/core/workspace/contracts.py@@ -30,7 +30,7 @@ from repowise.core.workspace.contract_schema import ContractSchemaif TYPE_CHECKING:from repowise.core.workspace.extractors.service_boundary import ServiceBoundary- from repowise.core.workspace.repo_index import WorkspaceIndex+ from repowise.core.workspace.repo_index import RepoIndex, WorkspaceIndex_log = logging.getLogger("repowise.workspace.contracts")@@ -40,6 +40,11 @@ _log = logging.getLogger("repowise.workspace.contracts")CONTRACTS_FILENAME = "contracts.json"+#: Artifact schema version. Bumped to 2 when contracts gained ``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 = 2+# ---------------------------------------------------------------------------# Data models@@ -55,9 +60,18 @@ class Contract:contract_type: str # "http" | "grpc" | "socket" | "topic" | "data"role: str # "provider" | "consumer"file_path: str # relative to repo root- symbol_name: str # handler name, service.method, etc.+ symbol_name: str # handler name, service.method, etc. — display onlyconfidence: float # 0.7–0.9 based on extraction strategyservice: str | None = None # service boundary path (monorepo)+ #: 1-indexed line of the declaration or call this contract was read from.+ #: The key :func:`bind_symbol_ids` binds against, and what says *where* a+ #: contract that failed to bind actually is.+ line: int | None = None+ #: The ingestion symbol id (``"<rel_path>::<name>"``) this contract belongs+ #: to. None when the repo has no index, the file has no parsed symbols, or+ #: nothing is declared at ``line`` — such a contract still matches, it just+ #: cannot be traversed into the call graph.+ symbol_id: str | None = Nonemeta: dict = field(default_factory=dict)# Optional request/response shape — populated by dialects that can recover# it (proto message fields today). Drives schema-level breaking-change diffs.@@ -67,6 +81,9 @@ class Contract:d = asdict(self)if d["service"] is None:del d["service"]+ for optional in ("line", "symbol_id"):+ if d[optional] is None:+ del d[optional]if not d["meta"]:del d["meta"]if self.schema is None or self.schema.is_empty:@@ -87,6 +104,9 @@ class Contract:symbol_name=data["symbol_name"],confidence=data["confidence"],service=data.get("service"),+ # Absent on a v1 artifact: the row predates contract identity.+ line=data.get("line"),+ symbol_id=data.get("symbol_id"),meta=data.get("meta", {}),schema=ContractSchema.from_dict(raw_schema) if raw_schema else None,)@@ -108,6 +128,11 @@ class ContractLink:consumer_file: strconsumer_symbol: strconsumer_service: str | None+ #: The linked contracts' symbol ids, carried through so a consumer of this+ #: link (``ImpactedConsumer``, ``get_risk``) can name the code rather than+ #: a display label. None when the contract never bound to one.+ provider_symbol_id: str | None = None+ consumer_symbol_id: str | None = Nonedef to_dict(self) -> dict[str, Any]:d = asdict(self)@@ -115,6 +140,9 @@ class ContractLink:del d["provider_service"]if d["consumer_service"] is None:del d["consumer_service"]+ for optional in ("provider_symbol_id", "consumer_symbol_id"):+ if d[optional] is None:+ del d[optional]return d@classmethod@@ -132,6 +160,8 @@ class ContractLink:consumer_file=data["consumer_file"],consumer_symbol=data.get("consumer_symbol", ""),consumer_service=data.get("consumer_service"),+ provider_symbol_id=data.get("provider_symbol_id"),+ consumer_symbol_id=data.get("consumer_symbol_id"),)@@ -139,7 +169,7 @@ class ContractLink:class ContractStore:"""Top-level container for contract data, serialized to JSON."""- version: int = 1+ version: int = CONTRACTS_VERSIONgenerated_at: str = ""contracts: list[Contract] = field(default_factory=list)contract_links: list[ContractLink] = field(default_factory=list)@@ -189,6 +219,51 @@ class ContractStore:return [c for c in self.contracts if c.repo == alias]+# ---------------------------------------------------------------------------+# Symbol identity+# ---------------------------------------------------------------------------+++# Contract types whose *provider* declaration sits above the symbol it names: a+# route decorator, an annotation. A data provider is the other shape — a table+# name is a member inside its owning class — and every consumer is a call inside+# a body, so for those the symbol containing the line is already the answer and+# looking below it would take the first method instead.+_DECLARED_ABOVE = frozenset({"http", "grpc", "socket", "topic"})+++def bind_symbol_ids(contracts: list[Contract], index: RepoIndex | None) -> dict[str, int]:+ """Give each contract in *contracts* the id of the symbol it belongs to.++ One pass over every contract type, so identity does not depend on how the+ dialect found the route — only on the line it reported. Dialects that+ already know their symbol (the index-backed ones) bind at extraction and+ are left alone here. Which of the two lookups applies is the one thing a+ contract's own shape decides: see :data:`_DECLARED_ABOVE`.++ 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+ index. That is the part of the denominator no binding rule can reach, and+ reporting a ratio without it would blame the rule for it. How many *did*+ bind is countable from the contracts themselves.+ """+ counts: dict[str, int] = {}+ for contract in contracts:+ 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+ symbol = lookup(contract.file_path, contract.line)+ if symbol is not None:+ contract.symbol_id = symbol.symbol_id+ if contract.symbol_id is None and (+ index is None or not index.symbols_for_file(contract.file_path)+ ):+ key = f"identity_unindexed_{contract.role}"+ counts[key] = counts.get(key, 0) + 1+ return counts++# ---------------------------------------------------------------------------# Contract ID normalization# ---------------------------------------------------------------------------@@ -399,6 +474,8 @@ def _make_link(consumer_repo=consumer.repo,consumer_file=consumer.file_path,consumer_symbol=consumer.symbol_name,+ provider_symbol_id=provider.symbol_id,+ consumer_symbol_id=consumer.symbol_id,consumer_service=consumer.service,)@@ -830,7 +907,10 @@ async def run_contract_extraction(json.dumps(contract_config.to_dict(), sort_keys=True).encode()).hexdigest()[:16]- if previous_store is not None:+ # A store written before contracts carried identity holds rows that cannot+ # be given one without re-reading the source, so its whole reuse question+ # is moot: extract every repo once, and the next run reuses normally.+ if previous_store is not None and prior.version >= CONTRACTS_VERSION:from ..ingestion.change_detector import has_working_tree_changesaliases = list(repo_paths)@@ -908,7 +988,8 @@ async def run_contract_extraction(# The symbols ingestion persisted for this repo. None means the regex# dialects are the only path, which is also the answer for a repo that- # has never been indexed. Only the HTTP extractor consults it.+ # has never been indexed. The HTTP extractor reads it during+ # extraction; every contract type reads it again in bind_symbol_ids.repo_index = workspace_index.get(alias) if workspace_index is not None else None# Counters the HTTP extractor fills in as it goes. The unresolved-path@@ -937,6 +1018,8 @@ async def run_contract_extraction(c.meta.setdefault(EXTRACTION_LAYER_KEY, LAYER_REGEX)contracts.extend(found)+ stats.update(bind_symbol_ids(contracts, repo_index))+unresolved = stats.get("http_consumer_unresolved", 0)if unresolved:_log.info(@@ -990,7 +1073,7 @@ async def run_contract_extraction(links.extend(_build_manual_links(contract_config.manual_links))store = ContractStore(- version=1,+ version=CONTRACTS_VERSION,generated_at=now_iso,contracts=all_contracts,contract_links=links,diff --git a/packages/core/src/repowise/core/workspace/diagnostics.py b/packages/core/src/repowise/core/workspace/diagnostics.pyindex 25c410d91..566c94a94 100644--- a/packages/core/src/repowise/core/workspace/diagnostics.py+++ b/packages/core/src/repowise/core/workspace/diagnostics.py@@ -109,6 +109,34 @@ class OrphanProvider:return asdict(self)+@dataclass+class SymbolIdentity:+ """How many of one role's contracts bound to a symbol id, and out of what.++ Two denominators because they answer different questions. *total* is the+ honest workspace-wide share. *bound_ratio_indexed* excludes the files with+ no parsed symbols at all — ``.sql``, ``.proto``, anything in a repo without+ an index — which is what says whether the binding rule itself is working:+ no rule can reach a file the parser never saw.+ """++ total: int = 0+ bound: int = 0+ unindexed_file: int = 0++ def _ratio(self, denominator: int) -> float | None:+ return self.bound / denominator if denominator > 0 else None++ def to_dict(self) -> dict[str, Any]:+ return {+ "total": self.total,+ "bound": self.bound,+ "unindexed_file": self.unindexed_file,+ "bound_ratio": self._ratio(self.total),+ "bound_ratio_indexed": self._ratio(self.total - self.unindexed_file),+ }++@dataclassclass ExtractionDiagnostics:"""Aggregate explanation of contract extraction + matching coverage."""@@ -127,6 +155,9 @@ class ExtractionDiagnostics:#: HTTP client calls located but not resolvable to an endpoint, workspace#: wide. This is the only miss count extraction can actually observe.http_consumers_unresolved: int = 0+ #: Symbol-id binding coverage, keyed by role. Reported, never asserted: a+ #: contract with no symbol id still matches, it just cannot be traversed.+ symbol_identity: dict[str, SymbolIdentity] = field(default_factory=dict)@propertydef http_consumer_coverage(self) -> float | None:@@ -158,6 +189,7 @@ class ExtractionDiagnostics:"consumers_by_layer": self.consumers_by_layer,"http_consumers_unresolved": self.http_consumers_unresolved,"http_consumer_coverage": self.http_consumer_coverage,+ "symbol_identity": {r: v.to_dict() for r, v in sorted(self.symbol_identity.items())},}@classmethod@@ -203,6 +235,14 @@ class ExtractionDiagnostics:providers_by_layer=data.get("providers_by_layer", {}),consumers_by_layer=data.get("consumers_by_layer", {}),http_consumers_unresolved=data.get("http_consumers_unresolved", 0),+ symbol_identity={+ role: SymbolIdentity(+ total=v.get("total", 0),+ bound=v.get("bound", 0),+ unindexed_file=v.get("unindexed_file", 0),+ )+ for role, v in (data.get("symbol_identity") or {}).items()+ },)@@ -338,6 +378,17 @@ def build_diagnostics())+ identity = {+ role: SymbolIdentity(+ total=len(rows),+ bound=sum(1 for c in rows if c.symbol_id is not None),+ unindexed_file=sum(+ s.get(f"identity_unindexed_{role}", 0) for s in stats_by_repo.values()+ ),+ )+ for role, rows in (("provider", providers), ("consumer", consumers))+ }+return ExtractionDiagnostics(total_providers=len(providers),total_consumers=len(consumers),@@ -355,4 +406,5 @@ def build_diagnostics(http_consumers_unresolved=sum(s.get("http_consumer_unresolved", 0) for s in stats_by_repo.values()),+ symbol_identity=identity,)diff --git a/packages/core/src/repowise/core/workspace/extractors/base.py b/packages/core/src/repowise/core/workspace/extractors/base.pyindex 2dd675417..da1e64396 100644--- a/packages/core/src/repowise/core/workspace/extractors/base.py+++ b/packages/core/src/repowise/core/workspace/extractors/base.py@@ -52,6 +52,15 @@ _TEST_FILE_PATTERNS = (_SELF_EXCLUDE_GLOBS = ("*/repowise/core/workspace/extractors/*",)+def line_at(content: str, offset: int) -> int:+ """The 1-indexed line of *content* holding character *offset*.++ Every regex dialect reports where it matched this way, which is what binds+ a contract to a symbol id (see :func:`..contracts.bind_symbol_ids`).+ """+ return content.count("\n", 0, offset) + 1++def is_test_path(rel_path: str) -> bool:"""True when *rel_path* (POSIX) lives in a test tree or is a test file."""parts = rel_path.split("/")diff --git a/packages/core/src/repowise/core/workspace/extractors/data/dialect.py b/packages/core/src/repowise/core/workspace/extractors/data/dialect.pyindex 7e6fd7175..7c5f4b3a8 100644--- a/packages/core/src/repowise/core/workspace/extractors/data/dialect.py+++ b/packages/core/src/repowise/core/workspace/extractors/data/dialect.py@@ -35,6 +35,7 @@ def build_table_provider(*,table_raw: str,framework: str,+ line: int | None = None,confidence: float = 0.85,) -> Contract | None:"""Build a provider contract for a declared table, or ``None``.@@ -57,6 +58,7 @@ def build_table_provider(symbol_name=f"{framework}:{table_raw}",confidence=confidence,service=None,+ line=line,meta={"table": table, "framework": framework},)@@ -67,6 +69,7 @@ def build_table_consumer(table_raw: str,verb: str,client: str,+ line: int | None = None,confidence: float = 0.7,) -> Contract | None:"""Build a consumer contract for a table referenced from app code.@@ -89,5 +92,6 @@ def build_table_consumer(symbol_name=f"{client}:{verb} {table}",confidence=confidence,service=None,+ line=line,meta={"table": table, "verb": verb, "client": client},)diff --git a/packages/core/src/repowise/core/workspace/extractors/data/orm_models.py b/packages/core/src/repowise/core/workspace/extractors/data/orm_models.pyindex 2ade4aaba..a4049fee0 100644--- a/packages/core/src/repowise/core/workspace/extractors/data/orm_models.py+++ b/packages/core/src/repowise/core/workspace/extractors/data/orm_models.py@@ -15,9 +15,10 @@ property) are emitted at lower confidence: a wrong guess costs a missed linkfrom __future__ import annotationsimport re+from collections.abc import Callablefrom typing import TYPE_CHECKING-from ..base import ScanContext+from ..base import ScanContext, line_atfrom ..langs import CSHARP, JAVA, KOTLIN, PHP, PYTHON, RUBYfrom .dialect import build_table_provider@@ -46,19 +47,42 @@ def _pluralize(name: str) -> str:return name + "s"+#: One table declaration: ``(raw_name, confidence, line)``.+_Found = tuple[str, float, int]+++def _found(+ pattern: re.Pattern[str],+ content: str,+ confidence: float,+ transform: Callable[[str], str] = str,+) -> list[_Found]:+ r"""Every match of *pattern*'s first group, with the line it sits on.++ The line comes from the group, not the match: three of these patterns open+ with ``^\s*`` under ``MULTILINE``, where ``^`` matches at a preceding blank+ line and ``\s*`` eats the newlines, putting ``m.start()`` above the+ declaration.+ """+ return [+ (transform(m.group(1)), confidence, line_at(content, m.start(1)))+ for m in pattern.finditer(content)+ ]++def _dedup_emit(ctx: ScanContext,framework: str,- found: list[tuple[str, float]],+ found: list[_Found],) -> list[Contract]:out: list[Contract] = []seen: set[str] = set()- for raw, confidence in found:+ for raw, confidence, line in found:if raw in seen:continueseen.add(raw)contract = build_table_provider(- ctx, table_raw=raw, framework=framework, confidence=confidence+ ctx, table_raw=raw, framework=framework, line=line, confidence=confidence)if contract is not None:out.append(contract)@@ -79,12 +103,10 @@ class SqlAlchemyDjangoDialect:_SQLMODEL_RE = re.compile(r"\bclass\s+(\w+)\([^)]*\btable\s*=\s*True[^)]*\)")def extract(self, ctx: ScanContext) -> list[Contract]:- found = [(m, _EXPLICIT_CONFIDENCE) for m in self._TABLENAME_RE.findall(ctx.content)]- found += [(m, _EXPLICIT_CONFIDENCE) for m in self._DB_TABLE_RE.findall(ctx.content)]- found += [(m, _EXPLICIT_CONFIDENCE) for m in self._CREATE_TABLE_RE.findall(ctx.content)]- found += [- (m.lower(), _CONVENTION_CONFIDENCE) for m in self._SQLMODEL_RE.findall(ctx.content)- ]+ found = _found(self._TABLENAME_RE, ctx.content, _EXPLICIT_CONFIDENCE)+ found += _found(self._DB_TABLE_RE, ctx.content, _EXPLICIT_CONFIDENCE)+ found += _found(self._CREATE_TABLE_RE, ctx.content, _EXPLICIT_CONFIDENCE)+ found += _found(self._SQLMODEL_RE, ctx.content, _CONVENTION_CONFIDENCE, str.lower)return _dedup_emit(ctx, self.name, found)@@ -101,14 +123,13 @@ class JpaDialect:)def extract(self, ctx: ScanContext) -> list[Contract]:- found = [(m, _EXPLICIT_CONFIDENCE) for m in self._TABLE_RE.findall(ctx.content)]+ found = _found(self._TABLE_RE, ctx.content, _EXPLICIT_CONFIDENCE)if not found:# Only fall back to the class-name convention when no explicit# @Table names the table (one entity per file is the JPA norm).- found = [- (_snake_case(m), _CONVENTION_CONFIDENCE)- for m in self._ENTITY_CLASS_RE.findall(ctx.content)- ]+ found = _found(+ self._ENTITY_CLASS_RE, ctx.content, _CONVENTION_CONFIDENCE, _snake_case+ )return _dedup_emit(ctx, self.name, found)@@ -122,8 +143,8 @@ class EfCoreDialect:_DBSET_RE = re.compile(r"\bDbSet<\s*\w+\s*>\s+(\w+)")def extract(self, ctx: ScanContext) -> list[Contract]:- found = [(m, _EXPLICIT_CONFIDENCE) for m in self._TABLE_ATTR_RE.findall(ctx.content)]- found += [(m, _CONVENTION_CONFIDENCE) for m in self._DBSET_RE.findall(ctx.content)]+ found = _found(self._TABLE_ATTR_RE, ctx.content, _EXPLICIT_CONFIDENCE)+ found += _found(self._DBSET_RE, ctx.content, _CONVENTION_CONFIDENCE)return _dedup_emit(ctx, self.name, found)@@ -139,12 +160,14 @@ class ActiveRecordDialect:)def extract(self, ctx: ScanContext) -> list[Contract]:- found = [(m, _EXPLICIT_CONFIDENCE) for m in self._TABLE_NAME_RE.findall(ctx.content)]+ found = _found(self._TABLE_NAME_RE, ctx.content, _EXPLICIT_CONFIDENCE)if not found:- found = [- (_pluralize(_snake_case(m)), _CONVENTION_CONFIDENCE)- for m in self._MODEL_CLASS_RE.findall(ctx.content)- ]+ found = _found(+ self._MODEL_CLASS_RE,+ ctx.content,+ _CONVENTION_CONFIDENCE,+ lambda m: _pluralize(_snake_case(m)),+ )return _dedup_emit(ctx, self.name, found)@@ -157,5 +180,5 @@ class EloquentDialect:_TABLE_RE = re.compile(r"protected\s+\$table\s*=\s*['\"](\w+)['\"]")def extract(self, ctx: ScanContext) -> list[Contract]:- found = [(m, _EXPLICIT_CONFIDENCE) for m in self._TABLE_RE.findall(ctx.content)]+ found = _found(self._TABLE_RE, ctx.content, _EXPLICIT_CONFIDENCE)return _dedup_emit(ctx, self.name, found)diff --git a/packages/core/src/repowise/core/workspace/extractors/data/sql_strings.py b/packages/core/src/repowise/core/workspace/extractors/data/sql_strings.pyindex 695ace2b1..d9d9ce111 100644--- a/packages/core/src/repowise/core/workspace/extractors/data/sql_strings.py+++ b/packages/core/src/repowise/core/workspace/extractors/data/sql_strings.py@@ -19,7 +19,7 @@ import loggingimport refrom typing import TYPE_CHECKING-from ..base import ScanContext+from ..base import ScanContext, line_atfrom ..langs import CSHARP, GO, JAVA, JS_TS, KOTLIN, PHP, PYTHON, RUBYfrom .dialect import build_table_consumer@@ -126,7 +126,7 @@ class SqlStringsDialect:def extract(self, ctx: ScanContext) -> list[Contract]:out: list[Contract] = []seen: set[str] = set()- for literal in self._sql_literals(ctx.content):+ for literal, line in self._sql_literals(ctx.content):for table_raw, verb in self._tables_in(literal):if table_raw.lower().strip('"`[]') in _SQL_KEYWORDS:continue@@ -135,15 +135,16 @@ class SqlStringsDialect:continueseen.add(key)contract = build_table_consumer(- ctx, table_raw=table_raw, verb=verb, client=self.name+ ctx, table_raw=table_raw, verb=verb, client=self.name, line=line)if contract is not None:out.append(contract)return out@staticmethod- def _sql_literals(content: str) -> list[str]:- literals: list[str] = []+ def _sql_literals(content: str) -> list[tuple[str, int]]:+ """``(literal, line)`` for each SQL-looking string literal in *content*."""+ literals: list[tuple[str, int]] = []for m in _STRING_RE.finditer(content):s = next(g for g in m.groups() if g is not None)if (@@ -152,7 +153,7 @@ class SqlStringsDialect:and _SQL_VERB_RE.search(s)and (_UPPER_VERB_RE.search(s) or _SQL_PUNCT_RE.search(s))):- literals.append(s)+ literals.append((s, line_at(content, m.start())))return literalsdef _tables_in(self, literal: str) -> list[tuple[str, str]]:diff --git a/packages/core/src/repowise/core/workspace/extractors/from_index.py b/packages/core/src/repowise/core/workspace/extractors/from_index.pyindex bf947c177..a431b5416 100644--- a/packages/core/src/repowise/core/workspace/extractors/from_index.py+++ b/packages/core/src/repowise/core/workspace/extractors/from_index.py@@ -273,11 +273,15 @@ def extract_http_providers(seen.add(key)framework = "flask" if _is_route_head(decorator) else "fastapi"contract = build_provider_contract(- ctx, method=method, path_raw=path, framework=framework+ ctx, method=method, path_raw=path, framework=framework, line=symbol.start_line)if contract is not None:contract.meta[EXTRACTION_LAYER_KEY] = LAYER_INDEXcontract.meta["handler"] = symbol.name+ # Bound here rather than by line: this path found the route *by*+ # walking up from the handler's own span, so the symbol is known+ # exactly and no lookahead rule needs to re-derive it.+ contract.symbol_id = symbol.symbol_idout.append(contract)return outdiff --git a/packages/core/src/repowise/core/workspace/extractors/grpc/csharp.py b/packages/core/src/repowise/core/workspace/extractors/grpc/csharp.pyindex 993ff2d57..68d189b1f 100644--- a/packages/core/src/repowise/core/workspace/extractors/grpc/csharp.py+++ b/packages/core/src/repowise/core/workspace/extractors/grpc/csharp.py@@ -13,6 +13,7 @@ from __future__ import annotationsimport refrom typing import TYPE_CHECKING+from ..base import line_atfrom ..langs import CSHARPfrom .dialect import make_grpc_contract@@ -55,6 +56,7 @@ class CSharpGrpcDialect: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):@@ -67,6 +69,7 @@ class CSharpGrpcDialect: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 —@@ -85,6 +88,7 @@ class CSharpGrpcDialect: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/dialect.py b/packages/core/src/repowise/core/workspace/extractors/grpc/dialect.pyindex 2685892fc..f727c1a10 100644--- a/packages/core/src/repowise/core/workspace/extractors/grpc/dialect.py+++ b/packages/core/src/repowise/core/workspace/extractors/grpc/dialect.py@@ -35,6 +35,7 @@ def make_grpc_contract(symbol_name: str,confidence: float,meta: dict,+ line: int | None = None,) -> Contract:"""Build a gRPC :class:`Contract` with the common fields filled in."""from repowise.core.workspace.contracts import Contract@@ -48,5 +49,6 @@ def make_grpc_contract(symbol_name=symbol_name,confidence=confidence,service=None,+ line=line,meta=meta,)diff --git a/packages/core/src/repowise/core/workspace/extractors/grpc/go.py b/packages/core/src/repowise/core/workspace/extractors/grpc/go.pyindex ec89cdd6f..509d5edfe 100644--- a/packages/core/src/repowise/core/workspace/extractors/grpc/go.py+++ b/packages/core/src/repowise/core/workspace/extractors/grpc/go.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport refrom typing import TYPE_CHECKING+from ..base import line_atfrom ..langs import GOfrom .dialect import make_grpc_contract@@ -35,6 +36,7 @@ class GoGrpcDialect: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):@@ -47,6 +49,7 @@ class GoGrpcDialect: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.pyindex 4402b2fda..5dfef7bb6 100644--- a/packages/core/src/repowise/core/workspace/extractors/grpc/java.py+++ b/packages/core/src/repowise/core/workspace/extractors/grpc/java.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport refrom typing import TYPE_CHECKING+from ..base import line_atfrom ..langs import JAVAfrom .dialect import make_grpc_contract@@ -35,6 +36,7 @@ class JavaGrpcDialect: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):@@ -47,6 +49,7 @@ class JavaGrpcDialect: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/python.py b/packages/core/src/repowise/core/workspace/extractors/grpc/python.pyindex cdf6b0586..1a0378571 100644--- a/packages/core/src/repowise/core/workspace/extractors/grpc/python.py+++ b/packages/core/src/repowise/core/workspace/extractors/grpc/python.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport refrom typing import TYPE_CHECKING+from ..base import line_atfrom ..langs import PYTHONfrom .dialect import make_grpc_contract@@ -38,6 +39,7 @@ class PythonGrpcDialect: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):@@ -52,6 +54,7 @@ class PythonGrpcDialect: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.pyindex b617fd4f6..2b1eefe43 100644--- a/packages/core/src/repowise/core/workspace/extractors/grpc/typescript.py+++ b/packages/core/src/repowise/core/workspace/extractors/grpc/typescript.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport refrom typing import TYPE_CHECKING+from ..base import line_atfrom ..langs import JS_TSfrom .dialect import make_grpc_contract@@ -34,6 +35,7 @@ class TypeScriptGrpcDialect: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/aspnet.py b/packages/core/src/repowise/core/workspace/extractors/http/aspnet.pyindex 5bf38696a..48f433444 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/aspnet.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/aspnet.py@@ -14,6 +14,7 @@ from __future__ import annotationsimport refrom typing import TYPE_CHECKING+from ..base import line_atfrom ..langs import CSHARPfrom .dialect import METHODS, build_provider_contract, nearest_prefix@@ -67,14 +68,24 @@ class AspNetDialect:prefix = nearest_prefix(class_mappings, m.start())if prefix:path_raw = prefix + "/" + path_raw.lstrip("/")- c = build_provider_contract(ctx, method=method, path_raw=path_raw, framework="aspnet")+ c = build_provider_contract(+ ctx,+ method=method,+ path_raw=path_raw,+ framework="aspnet",+ line=line_at(content, m.start()),+ )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):c = build_provider_contract(- ctx, method=m.group(1).upper(), path_raw=m.group(2), framework="aspnet-minimal"+ ctx,+ method=m.group(1).upper(),+ path_raw=m.group(2),+ framework="aspnet-minimal",+ line=line_at(content, m.start()),)if c is not None:out.append(c)@@ -87,7 +98,13 @@ class AspNetDialect:prefix = nearest_prefix(class_mappings, m.start())if not prefix:continue- c = build_provider_contract(ctx, method=method, path_raw=prefix, framework="aspnet")+ c = build_provider_contract(+ ctx,+ method=method,+ path_raw=prefix,+ framework="aspnet",+ line=line_at(content, m.start()),+ )if c is not None:out.append(c)diff --git a/packages/core/src/repowise/core/workspace/extractors/http/csharp_http.py b/packages/core/src/repowise/core/workspace/extractors/http/csharp_http.pyindex 690e3e8d9..0dc1e4a8c 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/csharp_http.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/csharp_http.py@@ -18,6 +18,7 @@ from __future__ import annotationsimport refrom typing import TYPE_CHECKING+from ..base import line_atfrom ..langs import CSHARPfrom .dialect import build_consumer_contract@@ -66,22 +67,22 @@ class CSharpHttpDialect:content = ctx.contentout: list[Contract] = []- def emit(method: str, prefix: str, text: str, client: str) -> None:+ def emit(method: str, prefix: str, text: str, client: str, line: int) -> None:url = _to_template(prefix, text)if "/" not in url:return # Not a URL path — skip non-route strings.c = build_consumer_contract(- ctx, method=method.upper(), url=url, client=client, confidence=0.70+ ctx, method=method.upper(), url=url, client=client, line=line, confidence=0.70)if c is not None:out.append(c)for m in _WRAPPER_RE.finditer(content):- emit(m.group(1), m.group(2), m.group(3), "httpclient")+ emit(m.group(1), m.group(2), m.group(3), "httpclient", line_at(content, m.start()))for m in _UNITY_RE.finditer(content):- emit(m.group(1), m.group(2), m.group(3), "unitywebrequest")+ emit(m.group(1), m.group(2), m.group(3), "unitywebrequest", line_at(content, m.start()))for m in _BESTHTTP_RE.finditer(content):# Group order: prefix, text, method (method trails the URL here).- emit(m.group(3), m.group(1), m.group(2), "besthttp")+ emit(m.group(3), m.group(1), m.group(2), "besthttp", line_at(content, m.start()))return outdiff --git a/packages/core/src/repowise/core/workspace/extractors/http/dialect.py b/packages/core/src/repowise/core/workspace/extractors/http/dialect.pyindex 18606dd7f..56aded7a0 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/dialect.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/dialect.py@@ -64,6 +64,7 @@ def build_provider_contract(method: str,path_raw: str,framework: str,+ line: int | None = None,confidence: float = 0.85,) -> Contract | None:"""Build a provider contract, or ``None`` if the path is unusable.@@ -87,6 +88,7 @@ def build_provider_contract(symbol_name=f"{framework}:{method} {path_raw}",confidence=confidence,service=None,+ line=line,meta={"method": method, "path": norm_path, "framework": framework},)@@ -97,6 +99,7 @@ def build_consumer_contract(method: str,url: str,client: str,+ line: int | None = None,confidence: float = 0.75,) -> Contract | None:"""Build a consumer contract from a raw client-call URL.@@ -122,5 +125,6 @@ def build_consumer_contract(symbol_name=f"{client}:{method} {url}",confidence=confidence,service=None,+ line=line,meta=consumer_meta(method, norm_path, client, base_token, host),)diff --git a/packages/core/src/repowise/core/workspace/extractors/http/express.py b/packages/core/src/repowise/core/workspace/extractors/http/express.pyindex 501c2bda8..16c37ac77 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/express.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/express.py@@ -10,6 +10,7 @@ from __future__ import annotationsimport refrom typing import TYPE_CHECKING+from ..base import line_atfrom ..langs import JS_TSfrom .dialect import METHODS, build_provider_contractfrom .mounts import compose_prefix@@ -59,7 +60,11 @@ class ExpressDialect:continuepath = compose_prefix(ctx.mounts.get(var, ""), path_raw)c = build_provider_contract(- ctx, method=method.upper(), path_raw=path, framework="express"+ ctx,+ method=method.upper(),+ path_raw=path,+ framework="express",+ line=line_at(ctx.content, m.start()),)if c is not None:out.append(c)diff --git a/packages/core/src/repowise/core/workspace/extractors/http/fastapi.py b/packages/core/src/repowise/core/workspace/extractors/http/fastapi.pyindex 3b37f6ad5..349aa089c 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/fastapi.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/fastapi.py@@ -10,6 +10,7 @@ from __future__ import annotationsimport refrom typing import TYPE_CHECKING+from ..base import line_atfrom ..langs import PYTHONfrom .dialect import METHODS, build_provider_contractfrom .mounts import balanced_args, compose_prefix, router_prefixes@@ -72,7 +73,11 @@ class FastApiDialect:path = compose_prefix(prefixes.get(var, ""), path_raw)path = compose_prefix(ctx.mounts.get(var, ""), path)c = build_provider_contract(- ctx, method=method.upper(), path_raw=path, framework="fastapi"+ ctx,+ method=method.upper(),+ path_raw=path,+ framework="fastapi",+ line=line_at(ctx.content, m.start()),)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.pyindex 304bae987..be2ad7d5b 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/go.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/go.py@@ -11,6 +11,7 @@ from __future__ import annotationsimport refrom typing import TYPE_CHECKING+from ..base import line_atfrom ..langs import GOfrom .dialect import METHODS_UPPER, build_provider_contractfrom .mounts import compose_prefix@@ -68,7 +69,13 @@ class GoDialect:# 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)- c = build_provider_contract(ctx, method=method, path_raw=path, framework="go")+ c = build_provider_contract(+ ctx,+ method=method,+ path_raw=path,+ framework="go",+ line=line_at(ctx.content, m.start()),+ )if c is not None:out.append(c)return outdiff --git a/packages/core/src/repowise/core/workspace/extractors/http/index_clients.py b/packages/core/src/repowise/core/workspace/extractors/http/index_clients.pyindex 06ab8d8a3..dfa8bbe81 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/index_clients.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/index_clients.py@@ -21,6 +21,7 @@ from __future__ import annotationsimport refrom typing import TYPE_CHECKING+from ..base import line_atfrom .dialect import build_consumer_contractfrom .wrappers import (DEFAULT_HOP_BUDGET,@@ -230,7 +231,7 @@ def extract_consumers(# (concrete literal) and unresolved. The set of wrappers proven to take a# path is only complete once the whole file has been scanned, so the# unresolved tally is settled afterwards.- resolved: list[tuple[str, str, str]] = [] # (callee, url, method)+ resolved: list[tuple[str, str, str, int]] = [] # (callee, url, method, line)unresolved_by_callee: dict[str, int] = {}path_taking: set[str] = set()# Calls whose argument list would not parse. Kept apart from the@@ -251,7 +252,7 @@ def extract_consumers(is_sink_call = m.group("recv") is None and name in sinksif not is_sink_call and name not in confirmed:continue- line = content.count("\n", 0, m.start()) + 1+ line = line_at(content, m.start())if (line, name) in declarations:continue # the wrapper's own signature, not a call to itopen_idx = m.end() - 1@@ -276,17 +277,17 @@ def extract_consumers(continuepath_taking.add(name)opt = _METHOD_OPT_RE.search(rest)- resolved.append((name, url, opt.group(1).upper() if opt else "GET"))+ resolved.append((name, url, opt.group(1).upper() if opt else "GET", line))from ..from_index import EXTRACTION_LAYER_KEY, LAYER_INDEXout: list[Contract] = []- for callee, url, method in resolved:+ for callee, url, method, line in resolved:# Higher than the regex dialect's 0.65/0.75: the callee is a confirmed# sink-reaching wrapper and the URL is a whole literal argument, not a# string that happened to sit next to a parenthesis.contract = build_consumer_contract(- ctx, method=method, url=url, client=callee, confidence=0.85+ ctx, method=method, url=url, client=callee, line=line, confidence=0.85)if contract is not None:contract.meta[EXTRACTION_LAYER_KEY] = LAYER_INDEXdiff --git a/packages/core/src/repowise/core/workspace/extractors/http/js_clients.py b/packages/core/src/repowise/core/workspace/extractors/http/js_clients.pyindex 67f84f5a3..e2175d9de 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/js_clients.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/js_clients.py@@ -12,6 +12,7 @@ from __future__ import annotationsimport refrom typing import TYPE_CHECKING+from ..base import line_atfrom ..langs import JS_TSfrom .dialect import METHODS, build_consumer_contract@@ -59,16 +60,23 @@ class JsClientsDialect:content = ctx.contentout: list[Contract] = []- def emit(*, method: str, url: str, client: str, confidence: float = 0.75) -> None:+ def emit(+ *, method: str, url: str, client: str, line: int, confidence: float = 0.75+ ) -> None:c = build_consumer_contract(- ctx, method=method, url=url, client=client, confidence=confidence+ ctx, method=method, url=url, client=client, line=line, confidence=confidence)if c is not None:out.append(c)# fetch() with an explicit method.for m in _FETCH_METHOD_RE.finditer(content):- emit(method=m.group(2).upper(), url=m.group(1), client="fetch")+ emit(+ method=m.group(2).upper(),+ url=m.group(1),+ client="fetch",+ line=line_at(content, m.start()),+ )# fetch() without a method → GET, skipping URLs already matched above.method_urls = {m.group(1) for m in _FETCH_METHOD_RE.finditer(content)}@@ -76,11 +84,16 @@ class JsClientsDialect:url = m.group(1)if url in method_urls:continue- emit(method="GET", url=url, client="fetch")+ emit(method="GET", url=url, client="fetch", line=line_at(content, m.start()))# axios.<method>()for m in _AXIOS_RE.finditer(content):- emit(method=m.group(1).upper(), url=m.group(2), client="axios")+ emit(+ method=m.group(1).upper(),+ url=m.group(2),+ client="axios",+ line=line_at(content, m.start()),+ )# Wrapper calls — fetchJSON(`${BASE}/path`, { method: "POST" }) etc.for m in _WRAPPER_CALL_RE.finditer(content):@@ -94,6 +107,12 @@ class JsClientsDialect:if not (_HTTP_NAME_RE.search(callee) or method_opt):continuemethod = method_opt.group(1).upper() if method_opt else "GET"- emit(method=method, url=m.group(2), client="wrapper", confidence=0.65)+ emit(+ method=method,+ url=m.group(2),+ client="wrapper",+ line=line_at(content, m.start()),+ confidence=0.65,+ )return outdiff --git a/packages/core/src/repowise/core/workspace/extractors/http/laravel.py b/packages/core/src/repowise/core/workspace/extractors/http/laravel.pyindex f4a40a2da..117ef6e07 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/laravel.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/laravel.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport refrom typing import TYPE_CHECKING+from ..base import line_atfrom ..langs import PHPfrom .dialect import METHODS, build_provider_contract@@ -28,7 +29,11 @@ class LaravelDialect:out: list[Contract] = []for m in _LARAVEL_RE.finditer(ctx.content):c = build_provider_contract(- ctx, method=m.group(1).upper(), path_raw=m.group(2), framework="laravel"+ ctx,+ method=m.group(1).upper(),+ path_raw=m.group(2),+ framework="laravel",+ line=line_at(ctx.content, m.start()),)if c is not None:out.append(c)diff --git a/packages/core/src/repowise/core/workspace/extractors/http/python_clients.py b/packages/core/src/repowise/core/workspace/extractors/http/python_clients.pyindex 52302617d..fa4cba52b 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/python_clients.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/python_clients.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport refrom typing import TYPE_CHECKING+from ..base import line_atfrom ..langs import PYTHONfrom .dialect import METHODS, build_consumer_contract@@ -28,7 +29,11 @@ class PythonClientsDialect:out: list[Contract] = []for m in _REQUESTS_RE.finditer(ctx.content):c = build_consumer_contract(- ctx, method=m.group(1).upper(), url=m.group(2), client="requests"+ ctx,+ method=m.group(1).upper(),+ url=m.group(2),+ client="requests",+ line=line_at(ctx.content, m.start()),)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 d1c9815a6..823b58099 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@@ -15,6 +15,7 @@ from __future__ import annotationsimport refrom typing import TYPE_CHECKING+from ..base import line_atfrom ..langs import RUSTfrom .dialect import build_provider_contract@@ -63,7 +64,11 @@ class RustAxumDialect: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"+ ctx,+ method=method,+ path_raw=path_raw,+ framework="axum",+ line=line_at(content, m.start()),)if c is not None:out.append(c)@@ -71,7 +76,11 @@ class RustAxumDialect:# Actix-web / Rocket attribute macros.for m in _RUST_ATTR_ROUTE_RE.finditer(content):c = build_provider_contract(- ctx, method=m.group(1).upper(), path_raw=m.group(2), framework="rust-attr"+ ctx,+ method=m.group(1).upper(),+ path_raw=m.group(2),+ framework="rust-attr",+ line=line_at(content, m.start()),)if c is not None:out.append(c)diff --git a/packages/core/src/repowise/core/workspace/extractors/http/rust_clients.py b/packages/core/src/repowise/core/workspace/extractors/http/rust_clients.pyindex 87db3e180..57508bf3b 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/rust_clients.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/rust_clients.py@@ -16,6 +16,7 @@ from __future__ import annotationsimport refrom typing import TYPE_CHECKING+from ..base import line_atfrom ..langs import RUSTfrom .dialect import build_consumer_contract@@ -49,22 +50,22 @@ class RustClientsDialect:content = ctx.contentout: list[Contract] = []- def emit(method: str, url: str) -> None:+ def emit(method: str, url: str, line: int) -> None:if "/" not in url:return # Not a URL path — skip map/collection .get("key") calls.c = build_consumer_contract(- ctx, method=method.upper(), url=url, client="reqwest", confidence=0.65+ ctx, method=method.upper(), url=url, client="reqwest", line=line, confidence=0.65)if c is not None:out.append(c)for rx in (_METHOD_LIT_RE, _FREE_LIT_RE):for m in rx.finditer(content):- emit(m.group(1), m.group(2))+ emit(m.group(1), m.group(2), line_at(content, m.start()))for rx in (_METHOD_FMT_RE, _FREE_FMT_RE):for m in rx.finditer(content):url = _FMT_PLACEHOLDER_RE.sub("${x}", m.group(2))- emit(m.group(1), url)+ emit(m.group(1), url, line_at(content, m.start()))return outdiff --git a/packages/core/src/repowise/core/workspace/extractors/http/spring.py b/packages/core/src/repowise/core/workspace/extractors/http/spring.pyindex 71547b8f3..87e16c11c 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/spring.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/spring.py@@ -9,6 +9,7 @@ from __future__ import annotationsimport refrom typing import TYPE_CHECKING+from ..base import line_atfrom ..langs import JAVAfrom .dialect import build_provider_contract, nearest_prefix@@ -49,7 +50,13 @@ class SpringDialect:prefix = nearest_prefix(class_mappings, m.start())if prefix:path_raw = prefix + "/" + path_raw.lstrip("/")- c = build_provider_contract(ctx, method=method, path_raw=path_raw, framework="spring")+ c = build_provider_contract(+ ctx,+ method=method,+ path_raw=path_raw,+ framework="spring",+ line=line_at(content, m.start()),+ )if c is not None:out.append(c)return outdiff --git a/packages/core/src/repowise/core/workspace/extractors/socket_extractor.py b/packages/core/src/repowise/core/workspace/extractors/socket_extractor.pyindex 56b28e4c2..8bab4515e 100644--- a/packages/core/src/repowise/core/workspace/extractors/socket_extractor.py+++ b/packages/core/src/repowise/core/workspace/extractors/socket_extractor.py@@ -12,7 +12,7 @@ from dataclasses import dataclassfrom pathlib import Pathfrom typing import TYPE_CHECKING-from .base import select_files+from .base import line_at, select_filesfrom .http.paths import (extract_path_from_url,is_unusable_consumer_path,@@ -189,6 +189,7 @@ class SocketExtractor:symbol_name=f"{pdef.label}('{identity}')",confidence=pdef.confidence,service=None,+ line=line_at(content, match.start()),meta={"path": identity,"transport": pdef.transport,diff --git a/packages/core/src/repowise/core/workspace/extractors/topic_extractor.py b/packages/core/src/repowise/core/workspace/extractors/topic_extractor.pyindex a5882dd98..6c272112f 100644--- a/packages/core/src/repowise/core/workspace/extractors/topic_extractor.py+++ b/packages/core/src/repowise/core/workspace/extractors/topic_extractor.py@@ -14,7 +14,7 @@ from typing import TYPE_CHECKINGfrom repowise.core.ingestion.languages.registry import REGISTRY as _LANG_REGISTRY-from .base import select_files+from .base import line_at, select_filesif TYPE_CHECKING:from collections.abc import Callable, Sequence@@ -271,6 +271,7 @@ class TopicExtractor:symbol_name=f"{pdef.label}('{topic_name}')",confidence=pdef.confidence,service=None,+ line=line_at(content, match.start()),meta={"topic": topic_name,"broker": pdef.broker,diff --git a/packages/core/src/repowise/core/workspace/repo_index.py b/packages/core/src/repowise/core/workspace/repo_index.pyindex 7afd5e122..cf7faf778 100644--- a/packages/core/src/repowise/core/workspace/repo_index.py+++ b/packages/core/src/repowise/core/workspace/repo_index.py@@ -33,6 +33,14 @@ _log = logging.getLogger("repowise.workspace.repo_index")# the repo — a third-party package or a sibling workspace repo.EXTERNAL_PREFIX = "external:"+# How far below a declaration line its symbol may open. Covers a stack of+# decorators or annotations and the blank lines between them. The ceiling: a+# declaration this close above an unrelated *nested* definition binds to it,+# since the index alone cannot tell a decorator run from ordinary code. Reading+# the intervening text would settle it, at the cost of the caller holding the+# file (see :func:`.extractors.from_index._decorators_above`, which does).+_DECLARATION_LOOKAHEAD = 8+@dataclass(frozen=True)class IndexedSymbol:@@ -143,6 +151,36 @@ class RepoIndex:best = symreturn best+ def declared_symbol_at(self, rel_path: str, line: int) -> IndexedSymbol | None:+ """The symbol a declaration on *line* names, or None.++ :meth:`symbol_at` answers "which symbol contains this line", which is+ the wrong question for a declaration that sits *above* its handler: a+ route decorator or annotation is outside the handler's span, because+ the parser takes a symbol's span from the definition node rather than+ the decorated one. So a symbol opening just below *line* is preferred,+ but only when it is nested inside whatever contains *line* — that guard+ is what stops a call on a function's last line from binding to the next+ function down.+ """+ containing = self.symbol_at(rel_path, line)+ # A match *on* a symbol's own declaration line names that symbol, not+ # the first member under it (a gRPC servicer class, say).+ if containing is not None and containing.start_line == line:+ return containing+ following: IndexedSymbol | None = None+ for sym in self._by_file.get(rel_path, ()):+ if line < sym.start_line <= line + _DECLARATION_LOOKAHEAD and (+ following is None or sym.start_line < following.start_line+ ):+ following = sym+ if following is not None and (+ containing is None+ or containing.start_line <= following.start_line <= containing.end_line+ ):+ return following+ return containing+def external_import_edges(self) -> list[ExternalImport]:"""Every ``imports`` edge leaving the repo, with the names it consumes."""return self._externalsdiff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/directives.py b/packages/server/src/repowise/server/mcp_server/tool_risk/directives.pyindex 11a9a16e8..c08540f72 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk/directives.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/directives.py@@ -86,10 +86,14 @@ def _breaking_change_directive(repo_alias: str) -> list[dict[str, Any]]:"severity": change.get("severity"),"detail": change.get("detail"),"impacted_consumers": [+ # symbol_id only when the contract bound to one: it is+ # what the reader can pass to get_symbol, and a null+ # would just cost budget.{"repo": c.get("repo"),"service": c.get("service"),"file": c.get("file"),+ **({"symbol_id": sid} if (sid := c.get("symbol_id")) else {}),}for c in cross[:_BC_CONSUMER_LIMIT]],diff --git a/packages/server/src/repowise/server/schemas/workspace.py b/packages/server/src/repowise/server/schemas/workspace.pyindex 1937ee04d..83848b81f 100644--- a/packages/server/src/repowise/server/schemas/workspace.py+++ b/packages/server/src/repowise/server/schemas/workspace.py@@ -274,7 +274,8 @@ class WorkspaceImpactedConsumer(BaseModel):service: str | None = Nonenode_id: strfile: str- symbol: str+ symbol: str # display label; symbol_id is the one a tool can look up+ symbol_id: str | None = Nonematch_type: str = "exact"confidence: float = 0.0diff --git a/tests/unit/workspace/test_contract_identity.py b/tests/unit/workspace/test_contract_identity.pynew file mode 100644index 000000000..53b45466a--- /dev/null+++ b/tests/unit/workspace/test_contract_identity.py@@ -0,0 +1,406 @@+"""Contract identity: the symbol id a contract belongs to.++A contract's ``symbol_name`` is a display label — ``"axios:GET /v1/orders"`` —+so it names nothing an agent can look up. ``symbol_id`` is the ingestion symbol+id, bound from the line the dialect matched on against the repo's symbol table.++Two claims are under test. The first is that binding is language-agnostic: it+reads a line and a symbol table, so a dialect that never heard of it gets+identity by reporting where it matched. The second is that it is additive+everywhere — a contract that cannot bind still matches, and a v1 artifact still+loads.+"""++from __future__ import annotations++from pathlib import Path++import pytest++from repowise.core.ingestion.models import Symbol+from repowise.core.workspace.config import ContractConfig, RepoEntry, WorkspaceConfig+from repowise.core.workspace.contracts import (+ CONTRACTS_VERSION,+ Contract,+ ContractStore,+ bind_symbol_ids,+ run_contract_extraction,+)+from repowise.core.workspace.diagnostics import build_diagnostics++from ._repo_index import make_repo_index+++def _symbol(name: str, start: int, end: int, *, path="app/api.py", kind="function"):+ return Symbol(+ id=f"{path}::{name}",+ name=name,+ qualified_name=name,+ kind=kind,+ signature=f"def {name}()",+ start_line=start,+ end_line=end,+ docstring=None,+ visibility="public",+ )+++def _contract(line: int | None, *, role="provider", path="app/api.py") -> Contract:+ return Contract(+ repo="backend",+ contract_id="http::GET::/users",+ contract_type="http",+ role=role,+ file_path=path,+ symbol_name="fastapi:GET /users",+ confidence=0.85,+ line=line,+ )+++# ---------------------------------------------------------------------------+# Binding by line+# ---------------------------------------------------------------------------+++class TestDeclaredSymbolAt:+ """The lookup that turns a matched line into a symbol.++ ``symbol_at`` alone is not enough: a route decorator sits *above* its+ handler, outside the span, because the parser takes a symbol's extent from+ the ``def`` node rather than the decorated one.+ """++ async def test_a_decorator_binds_to_the_handler_below_it(self, tmp_path: Path) -> None:+ index = await make_repo_index(tmp_path, {"app/api.py": [_symbol("users", 11, 14)]})+ try:+ assert index.symbol_at("app/api.py", 10) is None # outside the span+ found = index.declared_symbol_at("app/api.py", 10)+ assert found is not None and found.name == "users"+ finally:+ await index.close()++ async def test_a_decorated_method_wins_over_its_class(self, tmp_path: Path) -> None:+ index = await make_repo_index(+ tmp_path,+ {+ "app/api.py": [+ _symbol("Views", 1, 20, kind="class"),+ _symbol("get", 5, 8, kind="method"),+ ]+ },+ )+ try:+ assert index.symbol_at("app/api.py", 4).name == "Views"+ assert index.declared_symbol_at("app/api.py", 4).name == "get"+ finally:+ await index.close()++ async def test_a_call_inside_a_body_binds_to_that_body(self, tmp_path: Path) -> None:+ index = await make_repo_index(tmp_path, {"app/api.py": [_symbol("fetch_all", 1, 9)]})+ try:+ assert index.declared_symbol_at("app/api.py", 5).name == "fetch_all"+ finally:+ await index.close()++ async def test_a_call_on_a_last_line_does_not_leak_to_the_next_symbol(+ self, tmp_path: Path+ ) -> None:+ """The nesting guard: the next definition down is not this one's."""+ index = await make_repo_index(+ tmp_path,+ {"app/api.py": [_symbol("first", 1, 5), _symbol("second", 7, 12)]},+ )+ try:+ assert index.declared_symbol_at("app/api.py", 5).name == "first"+ finally:+ await index.close()++ async def test_a_match_on_a_declaration_line_names_that_symbol(+ self, tmp_path: Path+ ) -> None:+ """A gRPC servicer class, not the first method inside it."""+ index = await make_repo_index(+ tmp_path,+ {+ "app/api.py": [+ _symbol("OrderService", 2, 30, kind="class"),+ _symbol("get_order", 5, 9, kind="method"),+ ]+ },+ )+ try:+ assert index.declared_symbol_at("app/api.py", 2).name == "OrderService"+ finally:+ await index.close()++ async def test_a_distant_definition_is_out_of_reach(self, tmp_path: Path) -> None:+ index = await make_repo_index(tmp_path, {"app/api.py": [_symbol("late", 60, 70)]})+ try:+ assert index.declared_symbol_at("app/api.py", 2) is None+ finally:+ await index.close()+++class TestBindSymbolIds:+ async def test_a_line_becomes_a_symbol_id(self, tmp_path: Path) -> None:+ index = await make_repo_index(tmp_path, {"app/api.py": [_symbol("users", 11, 14)]})+ try:+ contracts = [_contract(10)]+ bind_symbol_ids(contracts, index)+ assert contracts[0].symbol_id == "app/api.py::users"+ assert contracts[0].symbol_name == "fastapi:GET /users", "display label is untouched"+ finally:+ await index.close()++ async def test_an_already_bound_contract_is_left_alone(self, tmp_path: Path) -> None:+ """The index-backed dialects bind exactly; no line rule may overrule them."""+ index = await make_repo_index(tmp_path, {"app/api.py": [_symbol("users", 11, 14)]})+ try:+ contract = _contract(10)+ contract.symbol_id = "app/api.py::chosen_by_the_dialect"+ bind_symbol_ids([contract], index)+ assert contract.symbol_id == "app/api.py::chosen_by_the_dialect"+ finally:+ await index.close()++ async def test_a_contract_without_a_line_stays_unbound(self, tmp_path: Path) -> None:+ index = await make_repo_index(tmp_path, {"app/api.py": [_symbol("users", 1, 99)]})+ try:+ contracts = [_contract(None)]+ bind_symbol_ids(contracts, index)+ assert contracts[0].symbol_id is None+ finally:+ await index.close()++ def test_no_index_binds_nothing_and_counts_every_row_unindexed(self) -> None:+ contracts = [_contract(10), _contract(10, role="consumer")]+ counts = bind_symbol_ids(contracts, None)+ assert all(c.symbol_id is None for c in contracts)+ assert counts == {"identity_unindexed_provider": 1, "identity_unindexed_consumer": 1}++ async def test_a_file_the_parser_never_saw_is_counted_separately(+ self, tmp_path: Path+ ) -> None:+ """A ``.sql`` file has no symbols, so no binding rule can reach it."""+ index = await make_repo_index(tmp_path, {"app/api.py": [_symbol("users", 11, 14)]})+ try:+ contracts = [_contract(10), _contract(4, path="db/schema.sql")]+ counts = bind_symbol_ids(contracts, index)+ assert contracts[0].symbol_id == "app/api.py::users"+ assert contracts[1].symbol_id is None+ assert counts == {"identity_unindexed_provider": 1}+ finally:+ await index.close()++ async def test_a_table_declared_in_a_class_body_binds_to_the_class(+ self, tmp_path: Path+ ) -> None:+ """A ``__tablename__`` is a member, so the lookahead must not apply and+ take the first method under it."""+ index = await make_repo_index(+ tmp_path,+ {+ "app/models.py": [+ _symbol("Order", 1, 20, path="app/models.py", kind="class"),+ _symbol("label", 4, 6, path="app/models.py", kind="method"),+ ]+ },+ )+ try:+ contract = _contract(2, path="app/models.py")+ contract.contract_type = "data"+ contract.contract_id = "data::orders"+ bind_symbol_ids([contract], index)+ assert contract.symbol_id == "app/models.py::Order"+ finally:+ await index.close()++ async def test_a_module_level_call_does_not_claim_the_next_definition(+ self, tmp_path: Path+ ) -> None:+ """A consumer is a call, so nothing below the line can be its symbol."""+ index = await make_repo_index(tmp_path, {"app/api.py": [_symbol("load_orders", 6, 9)]})+ try:+ contract = _contract(3, role="consumer")+ bind_symbol_ids([contract], index)+ assert contract.symbol_id is None+ finally:+ await index.close()++ async def test_an_indexed_file_with_nothing_at_the_line_is_not_called_unindexed(+ self, tmp_path: Path+ ) -> None:+ """Reported honestly as a binding miss, not blamed on a missing parse."""+ index = await make_repo_index(tmp_path, {"app/api.py": [_symbol("users", 60, 70)]})+ try:+ counts = bind_symbol_ids([_contract(2)], index)+ assert counts == {}+ finally:+ await index.close()+++class TestReportedLines:+ r"""The line a dialect reports must be the declaration's own.++ Three ORM patterns open with ``^\s*`` under ``MULTILINE``, where ``^``+ matches at a preceding blank line and ``\s*`` eats the newlines. Taking+ the match's start rather than its group put the contract above its class.+ """++ def test_a_tablename_after_a_blank_line_reports_its_own_line(self) -> None:+ from repowise.core.workspace.extractors.base import ScanContext+ from repowise.core.workspace.extractors.data.orm_models import SqlAlchemyDjangoDialect++ content = 'class Order(Base):\n\n __tablename__ = "orders"\n'+ ctx = ScanContext("backend", "app/models.py", ".py", content)+ contracts = SqlAlchemyDjangoDialect().extract(ctx)++ assert [c.line for c in contracts] == [3]++ def test_a_rails_model_after_blank_lines_reports_its_own_line(self) -> None:+ from repowise.core.workspace.extractors.base import ScanContext+ from repowise.core.workspace.extractors.data.orm_models import ActiveRecordDialect++ content = "module X\nend\n\n\nclass Order < ApplicationRecord\nend\n"+ ctx = ScanContext("backend", "app/models/order.rb", ".rb", content)+ contracts = ActiveRecordDialect().extract(ctx)++ assert [c.line for c in contracts] == [5]+++# ---------------------------------------------------------------------------+# The artifact+# ---------------------------------------------------------------------------+++class TestSerialization:+ def test_identity_round_trips(self) -> None:+ contract = _contract(10)+ contract.symbol_id = "app/api.py::users"+ restored = Contract.from_dict(contract.to_dict())+ assert restored.symbol_id == "app/api.py::users"+ assert restored.line == 10++ def test_an_unbound_contract_carries_no_empty_keys(self) -> None:+ d = _contract(None).to_dict()+ assert "symbol_id" not in d+ assert "line" not in d++ def test_a_v1_contract_still_loads(self) -> None:+ """The older shape: no line, no symbol id, and still a valid contract."""+ v1 = {+ "repo": "backend",+ "contract_id": "http::GET::/users",+ "contract_type": "http",+ "role": "provider",+ "file_path": "app/api.py",+ "symbol_name": "fastapi:GET /users",+ "confidence": 0.85,+ }+ contract = Contract.from_dict(v1)+ assert contract.symbol_id is None+ assert contract.line is None+ assert contract.contract_id == "http::GET::/users"++ def test_a_fresh_store_declares_the_identity_version(self) -> None:+ assert ContractStore().version == CONTRACTS_VERSION+ assert ContractStore.from_dict({}).version == 1, "an unversioned artifact is v1"+++class TestDiagnostics:+ def test_the_ratio_is_reported_against_both_denominators(self) -> None:+ bound = _contract(10)+ bound.symbol_id = "app/api.py::users"+ contracts = [bound, _contract(4, path="db/schema.sql"), _contract(2)]+ stats = {"backend": {"identity_unindexed_provider": 1}}++ identity = build_diagnostics(contracts, [], stats).to_dict()["symbol_identity"]++ assert identity["provider"]["total"] == 3+ assert identity["provider"]["bound"] == 1+ assert identity["provider"]["unindexed_file"] == 1+ assert identity["provider"]["bound_ratio"] == pytest.approx(1 / 3)+ assert identity["provider"]["bound_ratio_indexed"] == pytest.approx(1 / 2)+ assert identity["consumer"]["bound_ratio"] is None, "0/0 is not 100%"+++# ---------------------------------------------------------------------------+# End to end+# ---------------------------------------------------------------------------+++ROUTE_SOURCE = (+ "from fastapi import APIRouter\n"+ "\n"+ "router = APIRouter()\n"+ "\n"+ '@router.get("/users")\n'+ "async def list_users():\n"+ " return []\n"+)+++def two_repos(tmp_path: Path) -> WorkspaceConfig:+ for alias in ("alpha", "beta"):+ repo = tmp_path / alias+ (repo / "app").mkdir(parents=True)+ (repo / "app" / "api.py").write_text(ROUTE_SOURCE, encoding="utf-8")+ (repo / ".repowise").mkdir()+ return WorkspaceConfig(+ repos=[RepoEntry(path="alpha", alias="alpha"), RepoEntry(path="beta", alias="beta")],+ contracts=ContractConfig(),+ )+++async def test_a_regex_extracted_route_binds_to_its_handler(+ two_repos: WorkspaceConfig, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The whole path, from a dialect's match offset to the persisted id."""+ from repowise.core.workspace import contracts as contracts_mod+ from repowise.core.workspace.repo_index import WorkspaceIndex++ monkeypatch.setattr(contracts_mod, "save_contract_store", lambda store, root: root)+ index = await make_repo_index(+ tmp_path / "alpha", {"app/api.py": [_symbol("list_users", 6, 7)]}, alias="alpha"+ )+ try:+ store = await run_contract_extraction(+ two_repos, tmp_path, [], workspace_index=WorkspaceIndex({"alpha": index})+ )+ finally:+ await index.close()++ alpha = [c for c in store.contracts if c.repo == "alpha" and c.role == "provider"]+ assert alpha+ assert all(c.symbol_id == "app/api.py::list_users" for c in alpha)+ beta = [c for c in store.contracts if c.repo == "beta"]+ assert beta+ assert all(c.symbol_id is None for c in beta), "no index, no identity, still a row"+++async def test_a_v1_store_is_never_carried_forward(+ two_repos: WorkspaceConfig, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Its rows have no identity and re-reading the source is the only fix."""+ from repowise.core.workspace import contracts as contracts_mod+ from repowise.core.workspace.extractors import base++ monkeypatch.setattr(contracts_mod, "save_contract_store", lambda store, root: root)+ walked: list[str] = []+ original = base.iter_source_files++ def recording(repo_path, wanted, exclude=None):+ walked.append(Path(repo_path).name)+ return original(repo_path, wanted, exclude)++ monkeypatch.setattr(base, "iter_source_files", recording)++ first = await run_contract_extraction(two_repos, tmp_path, [])+ first.version = 1+ walked.clear()++ await run_contract_extraction(two_repos, tmp_path, [], None, first)++ assert sorted(walked) == ["alpha", "beta"]diff --git a/tests/unit/workspace/test_system_graph.py b/tests/unit/workspace/test_system_graph.pyindex 9141e87e5..edfc592d8 100644--- a/tests/unit/workspace/test_system_graph.py+++ b/tests/unit/workspace/test_system_graph.py@@ -311,6 +311,7 @@ def test_system_graph_json_shape_is_locked():"consumers_by_layer","http_consumers_unresolved","http_consumer_coverage",+ "symbol_identity",}