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): confirm HTTP client wrappers from the parsed symbol table (#1585)
Raghav Chamadiya0515a7f77845
diff --git a/packages/core/src/repowise/core/workspace/contracts.py b/packages/core/src/repowise/core/workspace/contracts.pyindex e088b7741..c3ec15a46 100644--- a/packages/core/src/repowise/core/workspace/contracts.py+++ b/packages/core/src/repowise/core/workspace/contracts.py@@ -705,6 +705,7 @@ async def run_contract_extraction()from .extractors.base import iter_source_files, make_exclude_predicatefrom .extractors.from_index import (+ ALL_INDEX_SUFFIXES,EXTRACTION_LAYER_KEY,LAYER_REGEX,load_repo_index,@@ -769,11 +770,16 @@ async def run_contract_extraction(# extractor consults it, so nothing is loaded when it is disabled.index = Noneif contract_config.detect_http:- index = await asyncio.to_thread(load_repo_index, repo_path)+ index = await asyncio.to_thread(load_repo_index, repo_path, ALL_INDEX_SUFFIXES)++ # Counters the HTTP extractor fills in as it goes. The unresolved-path+ # count is the honest half of any recall figure: it says how many real+ # client calls were located but could not be resolved to an endpoint.+ stats: dict[str, int] = {}for extractor in extractors:kwargs = (- {"index": index, "content_hashes": content_hashes}+ {"index": index, "content_hashes": content_hashes, "stats": stats}if isinstance(extractor, HttpExtractor)else {})@@ -787,6 +793,14 @@ async def run_contract_extraction(c.meta.setdefault(EXTRACTION_LAYER_KEY, LAYER_REGEX)contracts.extend(found)+ unresolved = stats.get("http_consumer_unresolved", 0)+ if unresolved:+ _log.info(+ "%s: %d HTTP client call(s) reach a confirmed wrapper but their "+ "path could not be resolved statically; counted, not extracted",+ alias,+ unresolved,+ )return contractsresults = await asyncio.gather(diff --git a/packages/core/src/repowise/core/workspace/extractors/from_index.py b/packages/core/src/repowise/core/workspace/extractors/from_index.pyindex 0d54b2f21..781045128 100644--- a/packages/core/src/repowise/core/workspace/extractors/from_index.py+++ b/packages/core/src/repowise/core/workspace/extractors/from_index.py@@ -35,6 +35,7 @@ from typing import TYPE_CHECKINGfrom .http.dialect import build_provider_contractfrom .http.mounts import compose_prefix, router_prefixes+from .langs import JS_TSif TYPE_CHECKING:from pathlib import Path@@ -81,6 +82,18 @@ _ROUTE_HEADS = frozenset({"route"})# widening :func:`extract_http_providers` to match.INDEX_SUFFIXES = frozenset({".py"})+# Consumer extraction needs the *symbol table* — line ranges and kinds — for the+# languages HTTP clients are written in, so the wrapper-confirmation pass can+# bound "this symbol's own body" to a parsed extent instead of guessing it by+# counting braces. Kept separate from INDEX_SUFFIXES because the two passes read+# different things off the same parse: providers read ``Symbol.decorators``,+# consumers read line ranges.+CONSUMER_INDEX_SUFFIXES = frozenset(JS_TS)++# What :func:`load_repo_index` deserializes for both passes together. One load+# per repo feeds both; asking for them separately would read the cache twice.+ALL_INDEX_SUFFIXES = INDEX_SUFFIXES | CONSUMER_INDEX_SUFFIXES+def _decorator_head_and_arg(decorator: str) -> tuple[str, str | None]:"""Split verbatim decorator text into its dotted head and first string arg.diff --git a/packages/core/src/repowise/core/workspace/extractors/http/__init__.py b/packages/core/src/repowise/core/workspace/extractors/http/__init__.pyindex 8725c6253..5f2a57173 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/__init__.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/__init__.py@@ -62,6 +62,13 @@ CONSUMER_DIALECTS: tuple[HttpDialect, ...] = (# runs its dialect, because nothing reads their decorators yet._INDEX_BACKED_DIALECTS = frozenset({"fastapi"})+# Consumer dialects whose duplicates the index pass removes. Unlike the+# provider side this supersedes per *contract id*, not per file: the index pass+# reads wrapper calls, while the dialect also reads shapes the index pass does+# not model (``axios.get``), so dropping the dialect wholesale for a file would+# subtract recall from a change made to add it.+_INDEX_BACKED_CONSUMER_DIALECTS = frozenset({"js-clients"})+def _union_extensions(dialects: tuple[HttpDialect, ...]) -> frozenset[str]:out: set[str] = set()@@ -91,6 +98,7 @@ class HttpExtractor:files: Sequence[SourceFile] | None = None,index: dict[str, object] | None = None,content_hashes: dict[str, str] | None = None,+ stats: dict[str, int] | None = None,) -> list[Contract]:"""Scan all source files in *repo_path* and return Contract instances.@@ -106,6 +114,12 @@ class HttpExtractor:a route from a comment, and cannot lose an empty path. *content_hashes*is the walk's ``rel_path -> sha256`` map, which is what proves a cachedparse describes the file as it is now; without it the index is unused.++ *stats* is an optional out-dict of counters. ``http_consumer_unresolved``+ counts calls to a *confirmed* HTTP wrapper whose path argument could not+ be resolved statically — real endpoint calls that were located but+ cannot be named. They are counted rather than dropped, so a recall+ figure built from these contracts states its own denominator."""own_hashes: dict[str, str] | None = Noneif files is None and index is not None and content_hashes is None:@@ -115,7 +129,8 @@ class HttpExtractor:)mounts = self._collect_mounts(scanned)- from ..from_index import extract_http_providers, parsed_for+ from ..from_index import CONSUMER_INDEX_SUFFIXES, extract_http_providers, parsed_for+ from .index_clients import extract_consumerscontracts: list[Contract] = []for rel_path, suffix, content in scanned:@@ -124,7 +139,7 @@ class HttpExtractor:# regex; a stale or missing entry leaves the dialect in charge.parsed = (parsed_for(index, rel_path, (content_hashes or {}).get(rel_path))- if suffix in PYTHON+ if suffix in PYTHON or suffix in CONSUMER_INDEX_SUFFIXESelse None)# Run the index pass first: it only supersedes the text dialect for@@ -132,17 +147,44 @@ class HttpExtractor:# decorated symbols (a grammar the parser stumbled on, a route# shape the queries do not capture) must not silently delete the# routes the regex can still see in the file's text.- from_parse = extract_http_providers(ctx, parsed) if parsed else []+ from_parse = (+ extract_http_providers(ctx, parsed)+ if parsed is not None and suffix in PYTHON+ else []+ )contracts.extend(from_parse)++ # Consumers, under the same per-file supersede rule: calls at the+ # sites of wrappers confirmed to reach an HTTP sink.+ consumers_from_parse: list[Contract] = []+ if parsed is not None and suffix in CONSUMER_INDEX_SUFFIXES:+ consumers_from_parse, unresolved = extract_consumers(ctx, parsed)+ contracts.extend(consumers_from_parse)+ if stats is not None and unresolved:+ stats["http_consumer_unresolved"] = (+ stats.get("http_consumer_unresolved", 0) + unresolved+ )+for dialect in self.provider_dialects:if suffix not in dialect.extensions:continueif from_parse and dialect.name in _INDEX_BACKED_DIALECTS:continue # superseded by the index pass abovecontracts.extend(dialect.extract(ctx))+ index_ids = {c.contract_id for c in consumers_from_parse}for dialect in self.consumer_dialects:- if suffix in dialect.extensions:- contracts.extend(dialect.extract(ctx))+ if suffix not in dialect.extensions:+ continue+ found = dialect.extract(ctx)+ if index_ids and dialect.name in _INDEX_BACKED_CONSUMER_DIALECTS:+ # Supersede per *contract*, not per file. Dropping the whole+ # dialect for a file the index read would delete anything+ # the index cannot see but the regex can — an ``axios.get``+ # beside a confirmed wrapper, say — which is a silent loss+ # of recall in a change made to increase it. Only the+ # duplicates the index already produced are removed.+ found = [c for c in found if c.contract_id not in index_ids]+ contracts.extend(found)return contractsdef _collect_mounts(self, files: list[tuple[str, str, str]]) -> dict[str, str]:diff --git a/packages/core/src/repowise/core/workspace/extractors/http/index_clients.py b/packages/core/src/repowise/core/workspace/extractors/http/index_clients.pynew file mode 100644index 000000000..47b1b5de0--- /dev/null+++ b/packages/core/src/repowise/core/workspace/extractors/http/index_clients.py@@ -0,0 +1,288 @@+"""HTTP consumer contracts at the call sites of *confirmed* wrapper functions.++The regex dialect (:mod:`.js_clients`) recognises a client call by the callee's+name. This module recognises one by asking :mod:`.wrappers` whether the callee+actually reaches an HTTP sink, so a function named ``fetchUser`` that only reads+a cache yields nothing, and a wrapper whose name carries no HTTP word is still+found.++It also parses the call's argument list properly rather than matching a literal+that happens to sit next to a parenthesis. That difference is what recovers the+bulk of the missing recall: the frontend spells every call+``this.fetch<SnapshotResponse>(`/snapshots/${id}`)``, and the existing dialect's+``fetch\\s*\\(`` cannot match across the ``<SnapshotResponse>`` type argument.++Unresolved paths are counted, never guessed and never silently dropped — see+:func:`extract_consumers`' ``unresolved`` return value.+"""++from __future__ import annotations++import re+from typing import TYPE_CHECKING++from .dialect import build_consumer_contract+from .wrappers import (+ DEFAULT_HOP_BUDGET,+ GENERIC_ARGS,+ confirm_wrappers,+ mask_source,+ sink_call_names,+)++if TYPE_CHECKING:+ from repowise.core.ingestion.models import ParsedFile+ from repowise.core.workspace.contracts import Contract++ from ..base import ScanContext++# A call to a named function, optionally through ``this``/``self`` and optionally+# carrying TypeScript type arguments. The name is captured to be looked up+# against the confirmed-wrapper set; it is never pattern-matched for meaning.+_CALL_RE = re.compile(+ r"(?<![.\w$])(?:(?P<recv>this|self)\s*\.\s*)?(?P<name>[A-Za-z_$][\w$]*)\s*"+ + GENERIC_ARGS+ + r"\(",+)++# A first argument concrete enough to be a URL: a path, a base placeholder, or+# an absolute URL. Mirrors the concreteness test the regex dialect already+# applies, so both paths agree on what counts as a usable literal.+_CONCRETE_URL_RE = re.compile(r"^(?:/|\$\{|https?:|//)")++# ``method: "POST"`` anywhere in the remaining arguments of the same call.+_METHOD_OPT_RE = re.compile(r"""method\s*:\s*['"](\w+)['"]""")++_QUOTES = "'\"`"+++def _match_paren(content: str, open_idx: int) -> int:+ """Index of the ``)`` closing the ``(`` at *open_idx*, or -1.++ Quote- and template-aware so a parenthesis inside a string literal does not+ unbalance the scan. Nested ``${...}`` inside a template literal is tracked+ as ordinary depth, which is what makes ``` `/a/${f(x)}/b` ``` parse.+ """+ depth = 0+ i = open_idx+ n = len(content)+ # Open template literals, innermost last. A backtick inside a ``${...}``+ # opens a *nested* literal rather than closing the outer one, so the state+ # has to be a stack: ``fetch(`/a/${c ? `x` : `y`}/b`)`` otherwise reads the+ # inner backtick as the end of the string and desynchronises everything+ # after it.+ tmpl: list[int] = []+ quote: str | None = None+ while i < n:+ ch = content[i]+ if quote is not None:+ if ch == "\\":+ i += 2+ continue+ if quote == "`" and ch == "$" and i + 1 < n and content[i + 1] == "{":+ tmpl.append(depth)+ depth += 1+ quote = None+ i += 2+ continue+ if ch == quote:+ quote = None+ i += 1+ continue+ if ch in _QUOTES:+ quote = ch+ elif ch in "([{":+ depth += 1+ elif ch in ")]}":+ depth -= 1+ if tmpl and ch == "}" and depth == tmpl[-1]:+ tmpl.pop()+ quote = "`" # back inside the template literal that opened it+ elif depth == 0 and ch == ")":+ return i+ i += 1+ return -1+++def _split_first_arg(args: str) -> tuple[str, str]:+ """Split an argument list into ``(first_arg, rest)`` at the top-level comma."""+ depth = 0+ tmpl: list[int] = [] # see :func:`_match_paren` — nested templates need a stack+ quote: str | None = None+ i = 0+ n = len(args)+ while i < n:+ ch = args[i]+ if quote is not None:+ if ch == "\\":+ i += 2+ continue+ if quote == "`" and ch == "$" and i + 1 < n and args[i + 1] == "{":+ tmpl.append(depth)+ depth += 1+ quote = None+ i += 2+ continue+ if ch == quote:+ quote = None+ i += 1+ continue+ if ch in _QUOTES:+ quote = ch+ elif ch in "([{":+ depth += 1+ elif ch in ")]}":+ depth -= 1+ if tmpl and ch == "}" and depth == tmpl[-1]:+ tmpl.pop()+ quote = "`"+ elif ch == "," and depth == 0:+ return args[:i].strip(), args[i + 1 :]+ i += 1+ return args.strip(), ""+++def _literal_url(arg: str) -> str | None:+ """The URL text of *arg* when it is a single string/template literal, else None.++ A literal spanning the whole argument is required: ``"/a" + x`` and a bare+ identifier both return ``None``, because neither is a path this layer may+ claim to know.+ """+ arg = arg.strip()+ if len(arg) < 2 or arg[0] not in _QUOTES or arg[-1] != arg[0]:+ return None+ inner = arg[1:-1]+ # A closing quote in the middle means the literal ended and something else+ # followed (concatenation), so the argument is not a single literal.+ if arg[0] in inner:+ return None+ return inner if _CONCRETE_URL_RE.match(inner) else None+++def _declaration_sites(parsed: ParsedFile) -> set[tuple[int, str]]:+ """``(line, name)`` for each callable's own declaration.++ A method declaration is syntactically a call — ``fetch<T>(path: string)`` —+ so without this the wrapper's own signature would be read as a call site+ with an unresolvable first argument, inflating the unresolved count with+ one phantom per wrapper.+ """+ return {+ (s.start_line, s.name)+ for s in parsed.symbols+ if s.kind in {"function", "method", "constructor"}+ }+++def _confirmed_ranges(parsed: ParsedFile, confirmed: set[str]) -> list[tuple[int, int]]:+ """Line extents of the symbols confirmed to reach a sink."""+ return [+ (s.start_line, s.end_line)+ for s in parsed.symbols+ if s.name in confirmed and s.kind in {"function", "method", "constructor"}+ ]+++def _within(ranges: list[tuple[int, int]], line: int) -> bool:+ return any(start <= line <= end for start, end in ranges)+++def extract_consumers(+ ctx: ScanContext,+ parsed: ParsedFile,+ budget: int = DEFAULT_HOP_BUDGET,+) -> tuple[list[Contract], int]:+ """Consumer contracts at confirmed wrapper call sites, plus an unresolved count.++ The second element counts call sites of a wrapper *known to take a URL path*+ — proven by another call site in the same file passing it a concrete literal+ — whose own path argument could not be resolved statically. Those are real+ endpoint calls this layer cannot name; reporting the number is what keeps+ the recall figure honest rather than flattering.+ """+ confirmed = confirm_wrappers(parsed, ctx.content, ctx.suffix, budget)+ sinks = sink_call_names(ctx.suffix)+ if not confirmed and not sinks:+ return [], 0++ # Comments are blanked (string bodies are not — the URL literal is what we+ # are here to read). This both stops a commented-out call becoming a+ # contract and keeps an apostrophe in prose from desynchronising the+ # argument scanner. Masking preserves offsets and length, so slices taken+ # against this text are the real argument text.+ content = mask_source(ctx.content, ctx.suffix)+ declarations = _declaration_sites(parsed)++ # Pass 1: every call site of a confirmed wrapper, split into resolved+ # (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)+ unresolved_by_callee: dict[str, int] = {}+ path_taking: set[str] = set()+ # Calls whose argument list would not parse. Kept apart from the+ # non-literal tally because they must be reported unconditionally: the+ # `path_taking` gate below is a judgement about what a *resolved* call+ # proved, and a call that never parsed proved nothing either way. Gating+ # these would let a scanner failure zero itself out.+ parse_failures = 0+ confirmed_ranges = _confirmed_ranges(parsed, confirmed)++ for m in _CALL_RE.finditer(content):+ name = m.group("name")+ # Either the callee is a wrapper proven to reach a sink, or the call is+ # a receiverless call to a sink itself (a streaming endpoint calls the+ # global ``fetch`` directly, bypassing the client's own wrapper). A+ # *member* call that merely shares a sink's name — ``this.fetch(...)`` —+ # gets no such shortcut and must be confirmed on its own merits.+ is_sink_call = m.group("recv") is None and name in sinks+ if not is_sink_call and name not in confirmed:+ continue+ line = content.count("\n", 0, m.start()) + 1+ if (line, name) in declarations:+ continue # the wrapper's own signature, not a call to it+ open_idx = m.end() - 1+ close_idx = _match_paren(content, open_idx)+ if close_idx < 0:+ # A call whose argument list would not parse is still a call to a+ # wrapper. Counting it rather than dropping it keeps the guarantee+ # that nothing located is silently discarded — a scanner failure+ # must show up in the number, not hide inside it.+ parse_failures += 1+ continue+ first, rest = _split_first_arg(content[open_idx + 1 : close_idx])+ url = _literal_url(first)+ if url is None:+ # The wrapper's own plumbing — ``fetch(path)`` inside the very+ # function that wraps it — is not a lost endpoint. Whatever flows+ # through it is already counted at that wrapper's call sites, so+ # counting it here would report each indirection as a miss.+ if is_sink_call and _within(confirmed_ranges, line):+ continue+ unresolved_by_callee[name] = unresolved_by_callee.get(name, 0) + 1+ continue+ path_taking.add(name)+ opt = _METHOD_OPT_RE.search(rest)+ resolved.append((name, url, opt.group(1).upper() if opt else "GET"))++ from ..from_index import EXTRACTION_LAYER_KEY, LAYER_INDEX++ out: list[Contract] = []+ for callee, url, method 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+ )+ if contract is not None:+ contract.meta[EXTRACTION_LAYER_KEY] = LAYER_INDEX+ out.append(contract)++ # Only a wrapper some call site proved takes a URL contributes unresolved+ # counts. Without that gate every ``client.getSnapshot(id)`` — a call to an+ # API method, whose first argument is an id and never was a path — would be+ # reported as an unresolved endpoint, and the number would mean nothing.+ unresolved = sum(n for name, n in unresolved_by_callee.items() if name in path_taking)+ return out, unresolved + parse_failuresdiff --git a/packages/core/src/repowise/core/workspace/extractors/http/wrappers.py b/packages/core/src/repowise/core/workspace/extractors/http/wrappers.pynew file mode 100644index 000000000..107c256e8--- /dev/null+++ b/packages/core/src/repowise/core/workspace/extractors/http/wrappers.py@@ -0,0 +1,343 @@+"""Confirm that a function really is an HTTP wrapper, instead of guessing.++``js_clients.py`` decides whether ``IDENT("/path")`` is a service call by+pattern-matching *IDENT's name* against ``fetch|request|http|api|ajax|rest|rpc``.+That cannot distinguish ``apiGet("/users")`` (a real call) from ``apiGet`` reading+a local cache, and it cannot recognise a wrapper whose name carries no HTTP word.++This module answers the question by construction instead: a symbol is an HTTP+wrapper when its **own body** issues a sink call (``fetch(``, ``axios.get(``,+``new XMLHttpRequest``…), or when it calls another symbol that does, within a+small hop budget. The name is never consulted.++**Why this reads symbol bodies rather than the resolved call graph.** The plan+for this work assumed ``ParsedFile.calls`` / the persisted ``graph_edges`` rows+already encode "does this wrapper reach ``fetch``". Measured on the live+frontend index, they do not, for two independent reasons:++1. ``fetch`` is in TypeScript's ``builtin_calls`` set+ (``ingestion/languages/specs/typescript.py:37``), and ``parser.py:1041``+ *drops* a call site whose target is a builtin. The sink call is erased+ before it ever reaches a ``CallSite``, so no ``calls`` edge can exist for it.+2. The TypeScript call queries match ``object: (identifier)``+ (``queries/typescript.scm:222``). ``this`` is a distinct node type, not an+ identifier, so ``this.foo(...)`` matches no call pattern at all. Measured on+ ``frontend/src/lib/api/client.ts``: **0** call sites with ``receiver == "this"``+ out of 297, while the file makes 172 of them.++So the call graph cannot see either end of the chain this module needs. What the+index *does* carry, verified and load-bearing here, is the **symbol table**:+every function/method with its exact ``start_line``/``end_line`` and its class.+That is what bounds "this symbol's own body" to real, parsed extents rather than+a brace-counting guess, and it is why a body scan here is not the same kind of+claim as a regex over a whole file.+"""++from __future__ import annotations++import re+from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from repowise.core.ingestion.models import ParsedFile, Symbol++# Hop budget for wrapper confirmation. 2 is not arbitrary: the real chain in+# ``frontend/src/lib/api/client.ts`` is+# ``getSnapshot -> this.fetch -> this.request -> fetch()``, so a caller's target+# (``fetch``) sits one hop from the sink and the budget has to cover it with+# room for one more indirection. It stays small on purpose — each hop widens the+# search, and an unbounded walk would turn confirmation into a whole-repo graph+# traversal, which the performance budget for this phase forbids.+DEFAULT_HOP_BUDGET = 2++# A call to a real HTTP sink. The negative lookbehind is the whole point: it+# requires the sink to be called *globally* (``fetch(...)``), not as a member+# (``this.fetch(...)`` / ``client.fetch(...)``), because a member call is the+# wrapper we are trying to confirm rather than the sink that confirms it.+# ``(?:<[^<>()]*>\s*)?`` admits TypeScript's generic call syntax — ``fetch<T>(``+# — which is exactly what the existing dialect's ``fetch\s*\(`` cannot match.+# TypeScript type arguments, admitting one level of nesting so+# ``publicFetch<Paginated<Commit>>(...)`` is still recognised as a call.+GENERIC_ARGS = r"(?:<[^<>()]*(?:<[^<>()]*>[^<>()]*)*>\s*)?"++_JS_SINK_RE = re.compile(+ r"(?<![.\w$])(?:fetch|axios|XMLHttpRequest|EventSource)\s*" + GENERIC_ARGS + r"\(",+)+# ``axios.get(...)`` / ``new XMLHttpRequest()`` reach the sink through a member+# or constructor rather than a bare call, so they get their own patterns.+_JS_SINK_MEMBER_RE = re.compile(r"(?<![.\w$])(?:axios)\s*\.\s*\w+\s*\(")+_JS_SINK_NEW_RE = re.compile(r"\bnew\s+(?:XMLHttpRequest|EventSource)\s*\(")++_PY_SINK_RE = re.compile(+ r"(?<![.\w])(?:requests|httpx|aiohttp)\s*\.\s*\w+\s*\(|"+ r"(?<![.\w])(?:urlopen|ClientSession)\s*\(",+)++_CS_SINK_RE = re.compile(r"\b(?:HttpClient|RestClient)\b")++_SINKS_BY_SUFFIX: dict[str, tuple[re.Pattern[str], ...]] = {+ ".ts": (_JS_SINK_RE, _JS_SINK_MEMBER_RE, _JS_SINK_NEW_RE),+ ".tsx": (_JS_SINK_RE, _JS_SINK_MEMBER_RE, _JS_SINK_NEW_RE),+ ".js": (_JS_SINK_RE, _JS_SINK_MEMBER_RE, _JS_SINK_NEW_RE),+ ".jsx": (_JS_SINK_RE, _JS_SINK_MEMBER_RE, _JS_SINK_NEW_RE),+ ".mjs": (_JS_SINK_RE, _JS_SINK_MEMBER_RE, _JS_SINK_NEW_RE),+ ".py": (_PY_SINK_RE,),+ ".cs": (_CS_SINK_RE,),+}++# Symbol kinds that can hold a body worth scanning.+_CALLABLE_KINDS = frozenset({"function", "method", "constructor"})++# A call to a locally-declared name, used to walk one hop. Deliberately matches+# both ``name(`` and ``this.name(`` / ``self.name(`` — the receiver is not what+# decides anything here; whether *name* resolves to a callable symbol in this+# file, and whether that symbol reaches a sink, is.+_LOCAL_CALL_RE = re.compile(+ r"(?:(?:this|self)\s*\.\s*)?([A-Za-z_$][\w$]*)\s*" + GENERIC_ARGS + r"\("+)+++# Sinks that are themselves callable by name, so a *global* call to one is an+# HTTP call outright and needs no wrapper behind it. Only consulted for a call+# with no receiver: ``this.fetch(...)`` is a method on the enclosing class that+# happens to share the sink's name, and must still be confirmed on its merits.+_SINK_CALL_NAMES_BY_SUFFIX: dict[str, frozenset[str]] = {+ ".ts": frozenset({"fetch"}),+ ".tsx": frozenset({"fetch"}),+ ".js": frozenset({"fetch"}),+ ".jsx": frozenset({"fetch"}),+ ".mjs": frozenset({"fetch"}),+}+++_JS_LIKE = frozenset({".ts", ".tsx", ".js", ".jsx", ".mjs"})++# A ``/`` opens a regex literal (rather than dividing) when the previous+# significant character cannot end an expression. The standard heuristic, and+# enough to stop a ``/\\)/`` corrupting a parenthesis scan.+_REGEX_PRECEDERS = frozenset("(,=:[!&|?{};+-*%~^<>")+++def mask_source(text: str, suffix: str, *, strings: bool = False) -> str:+ """Blank out comments — and optionally string bodies — preserving offsets.++ Every masked character is replaced by a space and newlines are kept, so the+ result is the same length as *text* and indexes into it interchangeably.+ That is what lets the call scanner match against masked text while slicing+ arguments by the same offsets.++ Two callers, two needs. Sink detection masks strings as well, because a+ ``fetch(`` inside a comment or a string is not a call — without this, a+ symbol is confirmed an HTTP wrapper by a line like+ ``// used to fetch(path) directly``, which is the name-guessing failure+ reappearing through the back door. The call-site scanner masks comments+ only, since it still has to read the URL literal it is looking for.+ """+ if suffix.lower() not in _JS_LIKE:+ # Python: ``#`` to end of line. Triple-quoted strings are left alone;+ # no sink pattern here matches inside one without a call following it.+ if suffix.lower() != ".py":+ return text+ out = list(text)+ i, n, in_str = 0, len(text), ""+ while i < n:+ ch = text[i]+ if in_str:+ if ch == "\\":+ i += 2+ continue+ if ch == in_str:+ in_str = ""+ elif ch in "'\"":+ in_str = ch+ elif ch == "#":+ while i < n and text[i] != "\n":+ out[i] = " "+ i += 1+ continue+ i += 1+ return "".join(out)++ out = list(text)+ i, n = 0, len(text)+ # Stack of open template literals, so a nested `` `x` `` inside ``${...}``+ # is opened rather than read as closing the outer one.+ tmpl_depth: list[int] = []+ quote = ""+ prev_sig = ""+ while i < n:+ ch = text[i]+ if quote:+ if ch == "\\":+ if strings:+ out[i] = " "+ if i + 1 < n and text[i + 1] != "\n":+ out[i + 1] = " "+ i += 2+ continue+ if quote == "`" and ch == "$" and i + 1 < n and text[i + 1] == "{":+ tmpl_depth.append(1)+ quote = ""+ i += 2+ continue+ if ch == quote:+ quote = ""+ elif strings:+ out[i] = " " if ch != "\n" else "\n"+ i += 1+ continue+ if ch == "/" and i + 1 < n and text[i + 1] == "/":+ while i < n and text[i] != "\n":+ out[i] = " "+ i += 1+ continue+ if ch == "/" and i + 1 < n and text[i + 1] == "*":+ while i < n and not (text[i] == "*" and i + 1 < n and text[i + 1] == "/"):+ if text[i] != "\n":+ out[i] = " "+ i += 1+ for j in range(i, min(i + 2, n)):+ out[j] = " "+ i += 2+ continue+ if ch == "/" and prev_sig in _REGEX_PRECEDERS:+ i += 1+ while i < n and text[i] != "\n":+ if text[i] == "\\":+ out[i] = " "+ if i + 1 < n:+ out[i + 1] = " "+ i += 2+ continue+ if text[i] == "/":+ out[i] = " "+ i += 1+ break+ out[i] = " "+ i += 1+ continue+ if ch in "'\"`":+ quote = ch+ elif tmpl_depth and ch == "}":+ tmpl_depth.pop()+ quote = "`"+ elif tmpl_depth and ch == "{":+ tmpl_depth[-1] += 1+ if not ch.isspace():+ prev_sig = ch+ i += 1+ return "".join(out)+++def sink_patterns(suffix: str) -> tuple[re.Pattern[str], ...]:+ """The sink patterns for *suffix*, or empty when the language has none."""+ return _SINKS_BY_SUFFIX.get(suffix.lower(), ())+++def sink_call_names(suffix: str) -> frozenset[str]:+ """Names whose *receiverless* call is itself an HTTP sink."""+ return _SINK_CALL_NAMES_BY_SUFFIX.get(suffix.lower(), frozenset())+++def symbol_body(lines: list[str], symbol: Symbol) -> str:+ """The source text of *symbol*'s body, excluding its own declaration.++ The declaration must be excluded because a symbol *named* like a sink+ declares itself with the sink's own syntax: ``private async fetch<T>(path)``+ matches the sink pattern on the strength of its signature alone. Keeping it+ would confirm any symbol called ``fetch`` by name, which is the failure this+ module exists to remove.++ Excluding the whole first *line* is too blunt: a concise wrapper puts its+ body on the declaration line (``getX() { return fetch("/x"); }``) and would+ lose it entirely. So for a brace language the body starts just after the+ first ``{`` on the declaration line — the symbol's own name always precedes+ its parameter list, and therefore precedes any brace on that line, so the+ self-match is excluded either way. With no brace there (a multi-line+ signature, or Python) the body starts on the next line as before.+ """+ first = symbol.start_line - 1 # 0-based index of the declaration line+ end = symbol.end_line+ if first < 0 or end <= first:+ return ""+ decl = lines[first] if first < len(lines) else ""+ brace = decl.find("{")+ head = decl[brace + 1 :] if brace >= 0 else ""+ rest = lines[first + 1 : end]+ return "\n".join([head, *rest]) if head else "\n".join(rest)+++def _callable_symbols(parsed: ParsedFile) -> dict[str, list[Symbol]]:+ """Callable symbols in this file, indexed by bare name.++ A name can be declared more than once (two classes with a ``get`` method);+ every candidate is kept and a wrapper chain is confirmed if *any* of them+ reaches a sink. That is deliberately the permissive side of the ambiguity:+ the alternative — dropping ambiguous names — would lose real calls in every+ file with two similarly-shaped classes.+ """+ out: dict[str, list[Symbol]] = {}+ for sym in parsed.symbols:+ if sym.kind in _CALLABLE_KINDS:+ out.setdefault(sym.name, []).append(sym)+ return out+++def confirm_wrappers(+ parsed: ParsedFile,+ content: str,+ suffix: str,+ budget: int = DEFAULT_HOP_BUDGET,+) -> set[str]:+ """Names of symbols in this file confirmed to reach an HTTP sink.++ Returns bare symbol names, because that is what a call site spells: the call+ ``this.fetch(path)`` names ``fetch``, not ``client.ts::HostedApiClient::fetch``.+ A name is present only if some symbol carrying it reaches a sink within+ *budget* hops.+ """+ patterns = sink_patterns(suffix)+ if not patterns:+ return set()++ # Comments and string bodies are blanked before any sink or hop matching:+ # a `fetch(` inside `// used to fetch(path) directly` is prose, and+ # confirming a wrapper on it would reintroduce name-guessing by another+ # route. Masking preserves offsets, so symbol line ranges still apply.+ lines = mask_source(content, suffix, strings=True).split("\n")+ by_name = _callable_symbols(parsed)+ if not by_name:+ return set()++ # Memo over symbol id, so a fan-in method body is scanned once regardless of+ # how many callers reach it. Values are the best (largest) budget already+ # proven insufficient, so a later, deeper visit is still allowed to try.+ failed_at: dict[str, int] = {}+ confirmed: set[str] = set()++ def reaches_sink(sym: Symbol, hops: int, stack: frozenset[str]) -> bool:+ if sym.id in stack: # a cycle cannot introduce a new sink+ return False+ if failed_at.get(sym.id, -1) >= hops:+ return False+ body = symbol_body(lines, sym)+ if not body:+ failed_at[sym.id] = max(failed_at.get(sym.id, -1), hops)+ return False+ if any(p.search(body) for p in patterns):+ return True+ if hops <= 0:+ failed_at[sym.id] = max(failed_at.get(sym.id, -1), hops)+ return False+ inner = stack | {sym.id}+ for m in _LOCAL_CALL_RE.finditer(body):+ for callee in by_name.get(m.group(1), ()):+ if callee.id != sym.id and reaches_sink(callee, hops - 1, inner):+ return True+ failed_at[sym.id] = max(failed_at.get(sym.id, -1), hops)+ return False++ for name, syms in by_name.items():+ if any(reaches_sink(s, budget, frozenset()) for s in syms):+ confirmed.add(name)+ return confirmeddiff --git a/tests/unit/workspace/test_index_clients.py b/tests/unit/workspace/test_index_clients.pynew file mode 100644index 000000000..006172e7c--- /dev/null+++ b/tests/unit/workspace/test_index_clients.py@@ -0,0 +1,649 @@+"""Consumer contracts at *confirmed* HTTP-wrapper call sites.++The claim under test is that a client call is recognised because the callee+provably reaches an HTTP sink, not because its name contains "fetch" or "api".+Two consequences are what these tests pin:++* a wrapper the regex dialect cannot see — ``this.fetch<T>(path)``, whose type+ argument breaks ``fetch\\s*\\(`` — is extracted, with the right path;+* a function *named* like a wrapper that never calls a sink yields nothing.+ The second is the false positive the name-matching approach cannot avoid, and+ is the thing this layer is bought for.++Symbols come from the real :class:`ASTParser` rather than hand-built+:class:`Symbol` objects. Wrapper confirmation depends on each symbol's+``start_line``/``end_line`` being the extent ingestion actually recorded, so+fabricating those here would test this module against my own arithmetic instead+of against the parse it consumes in production.+"""++from __future__ import annotations++from datetime import UTC, datetime++import pytest++from repowise.core.ingestion.models import FileInfo+from repowise.core.ingestion.parser import ASTParser+from repowise.core.workspace.extractors.base import ScanContext+from repowise.core.workspace.extractors.from_index import EXTRACTION_LAYER_KEY, LAYER_INDEX+from repowise.core.workspace.extractors.http.index_clients import extract_consumers+from repowise.core.workspace.extractors.http.js_clients import JsClientsDialect+from repowise.core.workspace.extractors.http.wrappers import confirm_wrappers+++def _parse(path: str, source: str):+ info = FileInfo(+ path=path,+ abs_path=f"C:/fake/{path}",+ language="typescript",+ size_bytes=len(source),+ git_hash="",+ last_modified=datetime.now(UTC),+ is_test=False,+ is_config=False,+ is_api_contract=False,+ is_entry_point=False,+ )+ return ASTParser().parse_file(info, source.encode())+++def _run(source: str, path: str = "src/lib/api/client.ts"):+ """Extract via the index path; returns ``(contracts, unresolved, ctx)``."""+ parsed = _parse(path, source)+ suffix = "." + path.rsplit(".", 1)[1]+ ctx = ScanContext("frontend", path, suffix, source, {})+ contracts, unresolved = extract_consumers(ctx, parsed)+ return contracts, unresolved, ctx+++def _ids(contracts) -> set[str]:+ return {c.contract_id for c in contracts}+++# The shape frontend/src/lib/api/client.ts really uses: a private `request`+# holding the sink, a generic `fetch<T>` delegating to it, and API methods+# calling `this.fetch<T>(...)`. Three hops from call site to sink.+CLIENT_TS = """\+const API_BASE = "https://api.example.com";++export class HostedApiClient {+ private async request(path: string, init?: RequestInit): Promise<Response> {+ const res = await fetch(`${API_BASE}${path}`, init);+ if (!res.ok) throw new Error("bad");+ return res;+ }++ private async fetch<T>(path: string, init?: RequestInit): Promise<T> {+ return (await this.request(path, init)).json();+ }++ getSnapshot(id: string) {+ return this.fetch<SnapshotResponse>(`/snapshots/${id}`);+ }++ listRepos() {+ return this.fetch<Repo[]>("/repos/mine");+ }++ patchFinding(id: string, status: string) {+ return this.fetch<Ok>(`/snapshots/${id}/dead-code`, {+ method: "PATCH",+ body: JSON.stringify({ status }),+ });+ }+}+"""+++class TestClassMethodWrapper:+ """``this.fetch<T>(path)`` — the shape that produced the 20% recall."""++ def test_generic_class_method_calls_are_extracted(self):+ contracts, _unresolved, _ctx = _run(CLIENT_TS)+ assert _ids(contracts) == {+ "http::GET::/snapshots/{param}",+ "http::GET::/repos/mine",+ "http::PATCH::/snapshots/{param}/dead-code",+ }++ def test_template_interpolation_normalises_to_param(self):+ contracts, _u, _c = _run(CLIENT_TS)+ got = next(c for c in contracts if c.contract_id.endswith("/snapshots/{param}"))+ assert got.meta["path"] == "/snapshots/{param}"+ assert got.role == "consumer"++ def test_method_option_is_read_from_the_call(self):+ contracts, _u, _c = _run(CLIENT_TS)+ patch = next(c for c in contracts if "dead-code" in c.contract_id)+ assert patch.meta["method"] == "PATCH"++ def test_provenance_is_the_index_layer(self):+ contracts, _u, _c = _run(CLIENT_TS)+ # Compared against the literal, not the constant the production code+ # sets: asserting `== LAYER_INDEX` would move with any rename and could+ # never fail.+ assert all(c.meta[EXTRACTION_LAYER_KEY] == "index" for c in contracts)+ assert LAYER_INDEX == "index"++ def test_the_regex_dialect_alone_cannot_see_these(self):+ """Fails before this change: the generic type argument breaks the regex.++ Locks the actual gap rather than the fix. ``fetch\\s*\\(`` cannot match+ ``fetch<SnapshotResponse>(``, so the three real endpoint calls above are+ invisible to the text dialect.+ """+ ctx = ScanContext("frontend", "src/lib/api/client.ts", ".ts", CLIENT_TS, {})+ old = JsClientsDialect().extract(ctx)+ assert _ids(old) & {+ "http::GET::/snapshots/{param}",+ "http::PATCH::/snapshots/{param}/dead-code",+ } == set()+++PUBLIC_CLIENT_TS = """\+const API_BASE = "https://api.example.com";++async function publicFetch<T>(path: string, opts: { revalidate?: number } = {}) {+ const res = await fetch(`${API_BASE}${path}`, { next: opts });+ if (!res.ok) return null;+ return res.json() as T;+}++export function getOverview(shortId: string) {+ return publicFetch<OverviewResponse>(`/snapshots/${shortId}/overview`);+}++export function getCommits(shortId: string) {+ return publicFetch<Paginated<Commit>>(`/snapshots/${shortId}/commits`);+}+"""+++class TestModuleLevelHelper:+ """``publicFetch<T>()`` — a module function, extracted 0 before this change."""++ def test_module_level_wrapper_yields_contracts(self):+ contracts, _u, _c = _run(PUBLIC_CLIENT_TS, "src/lib/api/public-client.ts")+ assert _ids(contracts) == {+ "http::GET::/snapshots/{param}/overview",+ "http::GET::/snapshots/{param}/commits",+ }++ def test_regex_dialect_yields_nothing_here(self):+ """Fails before this change: this file's yield was 0."""+ ctx = ScanContext(+ "frontend", "src/lib/api/public-client.ts", ".ts", PUBLIC_CLIENT_TS, {}+ )+ assert JsClientsDialect().extract(ctx) == []+++# Named exactly like an HTTP wrapper, reaches no sink. `_HTTP_NAME_RE` matches+# both `fetchUser` and `apiGet`, so the name-guessing dialect emits contracts+# for the two paths below; confirmation must not.+DECOY_TS = """\+const cache = new Map<string, string>();++export function fetchUser(key: string) {+ return cache.get(key);+}++export function apiGet(key: string) {+ return cache.get(key);+}++export function loadThings() {+ const a = fetchUser("/users/me");+ const b = apiGet("/things/all");+ return [a, b];+}+"""+++class TestNameLookalikesAreRejected:+ """The false positive the name-matching approach cannot avoid."""++ def test_wrapper_named_functions_without_a_sink_yield_nothing(self):+ contracts, unresolved, _c = _run(DECOY_TS, "src/lib/cache.ts")+ assert contracts == []+ assert unresolved == 0++ def test_they_are_not_confirmed_as_wrappers(self):+ parsed = _parse("src/lib/cache.ts", DECOY_TS)+ assert confirm_wrappers(parsed, DECOY_TS, ".ts") == set()++ def test_the_regex_dialect_does_emit_them(self):+ """Documents the defect being removed, so the gain is not hypothetical."""+ ctx = ScanContext("frontend", "src/lib/cache.ts", ".ts", DECOY_TS, {})+ assert _ids(JsClientsDialect().extract(ctx)) == {+ "http::GET::/users/me",+ "http::GET::/things/all",+ }++ def test_a_method_merely_named_fetch_is_not_a_sink(self):+ """A `fetch` that calls nothing must not confirm itself by its signature.++ Its own declaration line reads ``fetch<T>(`` — the sink pattern — so+ without excluding the declaration this would confirm by name, which is+ the whole failure mode under repair.+ """+ source = (+ "export class Fake {\n"+ " private async fetch<T>(path: string): Promise<T> {\n"+ " return JSON.parse(path) as T;\n"+ " }\n"+ " getThing() {\n"+ ' return this.fetch<Thing>("/things/1");\n'+ " }\n"+ "}\n"+ )+ contracts, unresolved, _c = _run(source, "src/lib/fake.ts")+ assert contracts == []+ assert unresolved == 0+++UNRESOLVED_TS = """\+const API_BASE = "https://api.example.com";++export class Client {+ private async request(path: string): Promise<Response> {+ return fetch(`${API_BASE}${path}`);+ }++ private async fetch<T>(path: string): Promise<T> {+ return (await this.request(path)).json();+ }++ known() {+ return this.fetch<Ok>("/repos/mine");+ }++ bridge(path: string) {+ return this.fetch<Ok>(path);+ }++ built(id: string) {+ return this.fetch<Ok>(buildPath(id));+ }+}+"""+++class TestUnresolvedPathsAreCounted:+ """A path that cannot be resolved is counted, never guessed and never dropped."""++ def test_dynamic_paths_are_counted_not_extracted(self):+ contracts, unresolved, _c = _run(UNRESOLVED_TS, "src/lib/api/dyn.ts")+ assert _ids(contracts) == {"http::GET::/repos/mine"}+ assert unresolved == 2++ def test_no_contract_is_invented_for_them(self):+ contracts, _u, _c = _run(UNRESOLVED_TS, "src/lib/api/dyn.ts")+ # Nothing named after the variable, and no bare-param path.+ assert not any("path" in c.contract_id for c in contracts)+ assert not any(c.meta["path"] in ("/{param}", "/") for c in contracts)++ def test_calls_to_api_methods_are_not_counted_as_unresolved(self):+ """``client.getSnapshot(id)`` is a call to an endpoint method, not a path.++ Its first argument was never a URL, so counting it would inflate the+ unresolved figure with calls that were never lost.+ """+ source = UNRESOLVED_TS + (+ "\nexport function page(c: Client) {\n return c.known();\n}\n"+ )+ _contracts, unresolved, _c = _run(source, "src/lib/api/dyn.ts")+ assert unresolved == 2+++class TestFallbackRemainsReachable:+ """A repo with no usable index keeps the regex path.++ The parse cache is version-gated, so a repo indexed by an older repowise+ loads zero entries — measured on two of three repos in this workspace. The+ regex dialect is therefore not a legacy path but the only path for those+ repos, and it has to stay reachable.+ """++ # Plain `fetch("/x")` — the one shape the text dialect handles well.+ PLAIN = 'export async function go() {\n return fetch("/legacy/ping");\n}\n'++ def _extract(self, tmp_path, *, index):+ from repowise.core.workspace.extractors.http import HttpExtractor++ return HttpExtractor().extract(+ tmp_path,+ "frontend",+ None,+ files=[("src/legacy.ts", ".ts", self.PLAIN)],+ index=index,+ content_hashes={},+ )++ def test_without_an_index_the_regex_dialect_still_extracts(self, tmp_path):+ got = self._extract(tmp_path, index=None)+ assert "http::GET::/legacy/ping" in _ids(got)++ def test_an_index_that_cannot_read_a_file_does_not_delete_its_contracts(+ self, tmp_path+ ):+ """An index present but missing this file must not suppress the dialect.++ This is the rule that stops a bad or partial parse silently deleting+ contracts the regex can still see.+ """+ got = self._extract(tmp_path, index={"src/other.ts": _parse("src/other.ts", "")})+ assert "http::GET::/legacy/ping" in _ids(got)++ def test_a_language_with_no_sink_patterns_confirms_nothing(self):+ parsed = _parse("src/main.go", "package main\n")+ assert confirm_wrappers(parsed, "package main\n", ".go") == set()++ def test_one_line_wrapper_bodies_are_not_lost(self):+ """A concise wrapper puts its body on the declaration line."""+ source = (+ "export class C {\n"+ ' ping() { return fetch("/x/ping"); }\n'+ " go() { return this.ping(); }\n"+ "}\n"+ )+ parsed = _parse("src/lib/one.ts", source)+ assert "ping" in confirm_wrappers(parsed, source, ".ts")+++class TestHopBudget:+ """Confirmation is bounded, so it cannot become a whole-repo graph walk."""++ def test_budget_one_still_reaches_through_the_two_hop_chain(self):+ """call site -> fetch -> request -> sink: the target is 1 hop from the sink."""+ parsed = _parse("src/lib/api/client.ts", CLIENT_TS)+ assert "fetch" in confirm_wrappers(parsed, CLIENT_TS, ".ts", budget=1)++ def test_budget_zero_confirms_only_the_symbol_holding_the_sink(self):+ parsed = _parse("src/lib/api/client.ts", CLIENT_TS)+ assert confirm_wrappers(parsed, CLIENT_TS, ".ts", budget=0) == {"request"}++ def test_a_chain_longer_than_the_budget_is_not_confirmed(self):+ source = (+ "export class Deep {\n"+ " a(p: string) { return fetch(p); }\n"+ " b(p: string) { return this.a(p); }\n"+ " c(p: string) { return this.b(p); }\n"+ " d(p: string) { return this.c(p); }\n"+ " e() { return this.d('/x/y'); }\n"+ "}\n"+ )+ parsed = _parse("src/lib/deep.ts", source)+ confirmed = confirm_wrappers(parsed, source, ".ts", budget=2)+ assert "a" in confirmed and "b" in confirmed and "c" in confirmed+ assert "d" not in confirmed+++class TestCycleSafety:+ def test_mutual_recursion_terminates(self):+ source = (+ "export class R {\n"+ " a(p: string) { return this.b(p); }\n"+ " b(p: string) { return this.a(p); }\n"+ "}\n"+ )+ parsed = _parse("src/lib/r.ts", source)+ assert confirm_wrappers(parsed, source, ".ts") == set()+++class TestSseEndpointsLinkToTheirConsumers:+ """The Phase 1 SSE endpoints reach a provider once their callers are seen.++ Note on where these consumers live: the three call sites named in the plan+ (``app/s/[shortId]/chat/page.tsx``, ``app/w/[id]/chat/page.tsx``,+ ``components/ask/ask-modal.tsx``) call *client methods* — ``postChatMessage``,+ ``postSnapshotAnswer``. The ``fetch`` carrying the URL is inside+ ``client.ts``, so that is the file the consumer contract is attributed to.+ Verified on the live index: all three endpoints below are extracted from+ ``src/lib/api/client.ts``.+ """++ # A streaming endpoint bypasses `this.fetch` and calls the global `fetch`+ # directly, because it needs the raw Response rather than parsed JSON.+ SSE_CLIENT = """\+const API_BASE = "https://api.example.com";++export class HostedApiClient {+ async postChatMessage(snapshotId: string, body: ChatBody) {+ return fetch(`${API_BASE}/snapshots/${snapshotId}/chat`, {+ method: "POST",+ body: JSON.stringify(body),+ });+ }++ async postSnapshotAnswer(snapshotId: string, body: AskBody) {+ return fetch(`${API_BASE}/snapshots/${snapshotId}/answer`, {+ method: "POST",+ body: JSON.stringify(body),+ });+ }+}+"""++ def test_sse_consumers_are_extracted(self):+ contracts, _u, _c = _run(self.SSE_CLIENT, "src/lib/api/client.ts")+ assert _ids(contracts) == {+ "http::POST::/snapshots/{param}/chat",+ "http::POST::/snapshots/{param}/answer",+ }++ def test_they_link_to_the_backend_providers(self):+ """End to end: FastAPI route declarations link to the frontend calls.++ Providers are built through :func:`build_provider_contract` from the raw+ decorator paths, so the join runs against whatever normalisation the+ product actually applies rather than an id hand-written to match.+ """+ from repowise.core.workspace.contracts import match_contracts+ from repowise.core.workspace.extractors.http.dialect import build_provider_contract++ consumers, _u, _c = _run(self.SSE_CLIENT, "src/lib/api/client.ts")+ backend_ctx = ScanContext("backend", "app/routers/chat.py", ".py", "", {})+ providers = [+ build_provider_contract(+ backend_ctx, method="POST", path_raw=raw, framework="fastapi"+ )+ for raw in (+ "/snapshots/{snapshot_id}/chat",+ "/snapshots/{snapshot_id}/answer",+ )+ ]+ links = match_contracts([*providers, *consumers])+ linked = {lk.contract_id for lk in links}+ assert linked == {+ "http::POST::/snapshots/{param}/chat",+ "http::POST::/snapshots/{param}/answer",+ }+ assert all(lk.consumer_repo == "frontend" for lk in links)+ assert all(lk.provider_repo == "backend" for lk in links)+++class TestLexicalNoiseIsNotEvidence:+ """Comments and string bodies are not code, and must not confirm anything.++ Every case here was found by review of the first implementation, which+ searched raw text. Each one made the layer emit a contract for something+ that is not a call, which is the same name-guessing failure arriving by a+ different route.+ """++ def test_a_sink_mentioned_in_a_comment_does_not_confirm_a_wrapper(self):+ source = (+ "const cache = new Map<string, string>();\n"+ "export function niceWrapper(path: string) {\n"+ " // TODO: used to fetch(path) directly, now cached\n"+ " return cache.get(path);\n"+ "}\n"+ 'export function go() { return niceWrapper("/users/me"); }\n'+ )+ contracts, unresolved, _c = _run(source, "src/lib/cache.ts")+ assert contracts == []+ assert unresolved == 0++ def test_a_sink_named_in_a_string_does_not_confirm_a_wrapper(self):+ source = (+ "export function describeIt(path: string) {\n"+ ' return "call fetch(" + path + ") to load";\n'+ "}\n"+ 'export function go() { return describeIt("/users/me"); }\n'+ )+ contracts, _u, _c = _run(source, "src/lib/desc.ts")+ assert contracts == []++ def test_a_commented_out_call_is_not_a_contract(self):+ source = (+ "export class C {\n"+ " private async fetch<T>(p: string): Promise<T> {\n"+ " return (await fetch(p)).json();\n"+ " }\n"+ " live() { return this.fetch<A>('/live'); }\n"+ " // dead() { return this.fetch<A>('/dead'); }\n"+ "}\n"+ )+ contracts, _u, _c = _run(source, "src/lib/c.ts")+ assert _ids(contracts) == {"http::GET::/live"}++ def test_an_apostrophe_in_a_comment_does_not_swallow_the_call(self):+ """A stray quote used to desynchronise the argument scanner."""+ source = (+ "export class C {\n"+ " private async fetch<T>(p: string): Promise<T> {\n"+ " return (await fetch(p)).json();\n"+ " }\n"+ " getIt(id: string) {\n"+ " return this.fetch<Snap>(\n"+ " // don't cache this\n"+ " `/snapshots/${id}`\n"+ " );\n"+ " }\n"+ "}\n"+ )+ contracts, unresolved, _c = _run(source, "src/lib/c.ts")+ assert _ids(contracts) == {"http::GET::/snapshots/{param}"}+ assert unresolved == 0++ def test_nested_template_literals_parse(self):+ source = (+ "export class C {\n"+ " private async fetch<T>(p: string): Promise<T> {\n"+ " return (await fetch(p)).json();\n"+ " }\n"+ " q(id: string, f: string) {\n"+ " return this.fetch<A>(`/a/${f ? `${id}` : `none`}/b`);\n"+ " }\n"+ " after() { return this.fetch<A>('/plain'); }\n"+ "}\n"+ )+ contracts, _u, _c = _run(source, "src/lib/c.ts")+ # The nested-template call normalises to {param}; the crucial part is+ # that the call *after* it still parses, which a desynced scan loses.+ assert "http::GET::/plain" in _ids(contracts)++ def test_a_regex_literal_containing_a_paren_does_not_desync(self):+ source = (+ "export class C {\n"+ " private async fetch<T>(p: string): Promise<T> {\n"+ " return (await fetch(p)).json();\n"+ " }\n"+ " a(s: string) { return this.fetch<A>('/x/' + s.replace(/\\)/g, '')); }\n"+ " b() { return this.fetch<A>('/after'); }\n"+ "}\n"+ )+ contracts, _u, _c = _run(source, "src/lib/c.ts")+ assert "http::GET::/after" in _ids(contracts)+++class TestNothingFoundIsSilentlyDropped:+ def test_an_unparseable_argument_list_is_counted_not_dropped(self):+ """A scanner failure must show up in the number, not hide in it."""+ from repowise.core.workspace.extractors.http import index_clients++ source = (+ "export class C {\n"+ " private async fetch<T>(p: string): Promise<T> {\n"+ " return (await fetch(p)).json();\n"+ " }\n"+ " ok() { return this.fetch<A>('/ok'); }\n"+ " weird(p: string) { return this.fetch<A>(p); }\n"+ "}\n"+ )+ # Force every paren scan to fail, the way a malformed file would.+ original = index_clients._match_paren+ index_clients._match_paren = lambda _c, _i: -1+ try:+ contracts, unresolved, _c = _run(source, "src/lib/c.ts")+ finally:+ index_clients._match_paren = original+ assert contracts == []+ # Both call sites failed to parse; neither vanished.+ assert unresolved >= 2+++class TestSupersedeCannotSubtract:+ """The index pass removes its own duplicates, never another shape."""++ def test_an_axios_call_survives_beside_a_confirmed_wrapper(self, tmp_path):+ from repowise.core.workspace.extractors.http import HttpExtractor++ source = (+ "export class C {\n"+ " private async fetch<T>(p: string): Promise<T> {\n"+ " return (await fetch(p)).json();\n"+ " }\n"+ " wrapped() { return this.fetch<A>('/wrapped'); }\n"+ "}\n"+ "export function legacy() { return axios.get('/legacy'); }\n"+ )+ parsed = _parse("src/lib/mix.ts", source)+ got = HttpExtractor().extract(+ tmp_path,+ "frontend",+ None,+ files=[("src/lib/mix.ts", ".ts", source)],+ index={"src/lib/mix.ts": parsed},+ content_hashes={"src/lib/mix.ts": parsed.content_hash},+ )+ ids = _ids(got)+ assert "http::GET::/wrapped" in ids # from the index pass+ assert "http::GET::/legacy" in ids # only the regex dialect sees this++ def test_duplicates_are_not_emitted_twice(self, tmp_path):+ from repowise.core.workspace.extractors.http import HttpExtractor++ source = (+ "export async function load() {\n"+ " return fetch('/dup');\n"+ "}\n"+ )+ parsed = _parse("src/lib/dup.ts", source)+ got = HttpExtractor().extract(+ tmp_path,+ "frontend",+ None,+ files=[("src/lib/dup.ts", ".ts", source)],+ index={"src/lib/dup.ts": parsed},+ content_hashes={"src/lib/dup.ts": parsed.content_hash},+ )+ dup = [c for c in got if c.contract_id == "http::GET::/dup"]+ assert len(dup) == 1+++ ("args", "expected"),+ [+ ('"/a/b"', "/a/b"),+ ("`/a/${id}`", "/a/${id}"),+ ("path", None),+ ('"/a" + id', None),+ ("buildPath(id)", None),+ ],+)+def test_literal_url_recognition(args: str, expected: str | None):+ from repowise.core.workspace.extractors.http.index_clients import _literal_url++ assert _literal_url(args) == expected