Skip to content

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

feat(mcp): list every edit site of a symbol, verified against live files (#3126)

Raghav Chamadiya9a3c00ffb065
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index 461c5f089..2ded4bd84 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -162,7 +162,7 @@ A triage card for files, modules or symbols: summary, symbols with signatures an
| Parameter | Type | Default | Meaning |
|-----------|------|---------|---------|
| `targets` | list[string] | required | File paths, module paths, or `"path::Symbol"` ids |
-| `include` | list[string] | none | Any of `full_doc`, `ownership`, `last_change`, `callers`, `callees`, `metrics`, `community`, `decisions`, `skeleton`, `health`, `doc_drift`, `symbols` |
+| `include` | list[string] | none | Any of `full_doc`, `ownership`, `last_change`, `callers`, `callees`, `references`, `metrics`, `community`, `decisions`, `skeleton`, `health`, `doc_drift`, `symbols` |
| `compact` | bool | `true` | `false` adds the structure block, imports and docstrings |
| `repo` | string | default repo | Workspace repo alias. `"all"` is not supported (returns an error) |
@@ -172,6 +172,13 @@ A file's compact symbol list holds its top 15 symbols: types (classes, interface
`full_doc` returns the page as `content_md`, plus `digest_md` on pages that carry an agent digest: the questions the page answers, its concept index, public API and git signals. Both are dropped first when the response is over budget. `skeleton` renders a file with bodies elided: every signature, the imports, and the bodies of its most central symbols, with line ranges on every elision. `doc_drift` lists the documents that name the file and whether they carry drift. An empty `callers` or `callees` list comes with a `*_basis` saying how much of that language's calls the graph resolved; read it before concluding nothing calls a symbol.
+`references` is the edit set for a symbol target: every live line naming it, as `{path, line, kind, text}` with kind `definition`, `import`, `call` or `reference`. For a rename, a `complete` list is the whole edit set. Otherwise `reasons` says why. It is never complete for:
+
+- languages other than Python, TypeScript and JavaScript (same-package use needs no import)
+- more than 200 sites, a stale call line, an unreadable file, or an uncommitted edit outside the scanned files
+- a rename on import, export or destructure, a default export, or a CommonJS export
+- a dynamic use the graph recorded; access built from strings is otherwise not seen
+
```
get_context(targets=["src/auth/middleware.ts", "src/api/routes.ts"], include=["callers"])
get_context(targets=["src/big_module.py"], include=["skeleton"])
diff --git a/packages/cli/src/repowise/cli/commands/context_cmd.py b/packages/cli/src/repowise/cli/commands/context_cmd.py
index f068054b3..2fbccb86b 100644
--- a/packages/cli/src/repowise/cli/commands/context_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/context_cmd.py
@@ -14,6 +14,7 @@ _INCLUDE_BLOCKS = (
"last_change",
"callers",
"callees",
+ "references",
"metrics",
"community",
"decisions",
diff --git a/packages/server/src/repowise/server/mcp_server/_edit_sites.py b/packages/server/src/repowise/server/mcp_server/_edit_sites.py
new file mode 100644
index 000000000..24d99e880
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/_edit_sites.py
@@ -0,0 +1,313 @@
+"""Every site an agent edits to rename one symbol or update all its callers.
+
+The graph says where to look (the definition, importers of its file, call
+edges with their lines); the live files say what is there now. Each candidate
+file is scanned for the symbol's bare name on a word boundary and every hit is
+classified, so a stale graph line is dropped instead of served, and a hit the
+graph never saw is still listed. ``complete`` is true only when nothing the
+scan could not see may hold another site.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import re
+from itertools import islice
+from pathlib import Path
+from typing import Any
+
+from sqlalchemy import or_, select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from repowise.core.fs_walk import PRUNED_DIRS, iter_glob
+from repowise.core.ingestion.languages.registry import REGISTRY
+from repowise.core.ingestion.symbol_identity import id_segment_name
+from repowise.core.persistence.models import GraphEdge, GraphNode
+from repowise.server.mcp_server._helpers import read_repo_file_text
+from repowise.server.mcp_server._meta import _working_tree_dirty_paths, uncommitted_targets
+
+MAX_SITES = 200
+MAX_TEXT_CHARS = 160
+# Ceiling on files read per call; past it the set is reported incomplete
+# rather than read without bound.
+MAX_FILES = 300
+_MAX_FILE_BYTES = 2_000_000
+_MIN_CALL_CONFIDENCE = 0.7
+_MEMBER_KINDS = frozenset({"method", "constructor", "property", "field"})
+# Languages where using a symbol from another file takes an import naming that
+# file or the symbol, so importers are every file that can use it. Elsewhere
+# (same-package or namespace visibility) sites are listed but never complete.
+_IMPORT_SCOPED_LANGUAGES = frozenset({"python", "typescript", "javascript"})
+_PYTHON_EXTENSIONS = REGISTRY.extensions_for(("python",))
+# A statement that brings a name into a file, in the languages the graph
+# resolves imports for. Continuation lines are found by bracket balance.
+_IMPORT_START = re.compile(
+ r"^\s*(?:from\s+\S+\s+import\b|import\b|export\s.*\bfrom\b|export\s*\{|using\b|use\b"
+ r"|#\s*include\b|(?:const|let|var)\s.*\brequire\s*\()"
+)
+
+
+def _bare_name(node: GraphNode) -> str:
+ return id_segment_name((node.name or node.node_id).split("::")[-1].split(".")[-1])
+
+
+def _import_lines(lines: list[str]) -> set[int]:
+ """1-based line numbers that belong to an import statement."""
+ out: set[int] = set()
+ i = 0
+ while i < len(lines):
+ if not _IMPORT_START.match(lines[i]):
+ i += 1
+ continue
+ depth = 0
+ while i < len(lines):
+ text = lines[i]
+ out.add(i + 1)
+ depth += text.count("(") + text.count("{") - text.count(")") - text.count("}")
+ i += 1
+ if depth <= 0 and not text.rstrip().endswith("\\"):
+ break
+ return out
+
+
+def _read_lines(root: Path, rel: str) -> list[str] | None:
+ try:
+ if (root / rel).stat().st_size > _MAX_FILE_BYTES:
+ return None
+ except OSError:
+ return None
+ text = read_repo_file_text(root, rel)
+ return None if text is None else text.splitlines()
+
+
+def _scan(
+ root: Path,
+ files: list[str],
+ name: str,
+ definition: tuple[str, int, int],
+ call_lines: dict[str, set[int]],
+) -> tuple[list[dict[str, Any]], list[str], int, set[str], bool]:
+ """``(sites, unreadable, stale call lines, files renaming it, default-exported)``."""
+ esc = re.escape(name)
+ word = re.compile(rf"(?<![\w$]){esc}(?![\w$])")
+ as_rename = re.compile(rf"(?<![\w$.]){esc}\s+as\s+([\w$]+)")
+ # ``{ name: other } = require(...)`` or a destructured import; a ternary's
+ # ``name : other`` is excluded, anything else colon-shaped counts.
+ colon_rename = re.compile(rf"(?<![\w$.?]){esc}\s*:\s*([A-Za-z_$][\w$]*)")
+ ternary = re.compile(rf"\?[^:]*(?<![\w$]){esc}\s*:")
+ # Bound under any name by its importers, so no spelling can be scanned for.
+ default_export = re.compile(r"\bexport\s+default\b|\bas\s+default\b")
+ cjs_export = re.compile(r"\bmodule\.exports\b|(?<![\w$.])exports\.")
+ def_path, def_start, def_end = definition
+ sites: list[dict[str, Any]] = []
+ unreadable: list[str] = []
+ stale = 0
+ renamed: set[str] = set()
+ is_default = False
+ for rel in files:
+ lines = _read_lines(root, rel)
+ if lines is None:
+ unreadable.append(rel)
+ continue
+ imports = _import_lines(lines)
+ python = Path(rel).suffix in _PYTHON_EXTENSIONS
+ aliases: set[str] = set()
+ for n, text in enumerate(lines, 1):
+ if not word.search(text):
+ continue
+ if n in imports:
+ aliases.update(m.group(1) for m in as_rename.finditer(text))
+ if not python and not ternary.search(text):
+ aliases.update(m.group(1) for m in colon_rename.finditer(text))
+ # ``name as default`` is the default-export case below, not a rename.
+ aliases.discard("default")
+ if aliases:
+ renamed.add(rel)
+ if rel == def_path and not python:
+ # A CommonJS module's exports can rename on any line, so any use counts.
+ commonjs = any(cjs_export.search(t) for t in lines)
+ if commonjs or any(default_export.search(t) and word.search(t) for t in lines):
+ is_default = True
+ spellings = [word] + [re.compile(rf"(?<![\w$]){re.escape(a)}(?![\w$])") for a in aliases]
+ graph_calls = call_lines.get(rel, set())
+ def_seen = rel != def_path
+ for n, text in enumerate(lines, 1):
+ in_graph = n in graph_calls
+ if in_graph and not any(s.search(text) for s in spellings):
+ stale += 1
+ continue
+ if not in_graph and not any(s.search(text) for s in spellings):
+ continue
+ if not def_seen and def_start <= n <= def_end:
+ kind, def_seen = "definition", True
+ elif n in imports:
+ kind = "import"
+ elif in_graph:
+ kind = "call"
+ else:
+ kind = "reference"
+ sites.append({"path": rel, "line": n, "kind": kind, "text": text.strip()[:MAX_TEXT_CHARS]})
+ return sites, unreadable, stale, renamed, is_default
+
+
+def _unseen_dirty_files(root: Path, local_path: str) -> list[str] | None:
+ """Uncommitted files the index has not seen; ``None`` when git cannot say."""
+ dirty = _working_tree_dirty_paths(local_path)
+ if dirty is None:
+ return None
+ candidates = [d for d in dirty if d.split("/", 1)[0] not in PRUNED_DIRS]
+ out: list[str] = []
+ for rel in uncommitted_targets(local_path, candidates):
+ path = root / rel
+ if path.is_dir():
+ found = (f for f in iter_glob(path, "*") if f.is_file())
+ out.extend(f.relative_to(root).as_posix() for f in islice(found, MAX_FILES + 1))
+ elif path.is_file():
+ out.append(rel)
+ return out
+
+
+async def reference_edit_set(
+ session: AsyncSession, repo_id: str, repo_root: str | Path, node: GraphNode
+) -> dict[str, Any]:
+ """Every live site naming *node*, classified, with a completeness verdict.
+
+ Returns ``{"sites": [{"path", "line", "kind", "text"}], "complete": bool}``
+ plus ``reasons`` when incomplete and ``sites_omitted`` past the cap. Kinds:
+ definition | import | call | reference.
+ """
+ root = Path(repo_root).resolve()
+ name = _bare_name(node)
+ def_file = node.file_path
+ reasons: list[str] = []
+
+ cols = (
+ GraphEdge.source_node_id,
+ GraphEdge.target_node_id,
+ GraphEdge.edge_type,
+ GraphEdge.imported_names_json,
+ GraphEdge.call_lines_json,
+ GraphEdge.confidence,
+ )
+
+ def _names(raw: str | None) -> list[str]:
+ try:
+ return [str(n) for n in json.loads(raw or "[]")]
+ except (TypeError, ValueError):
+ return []
+
+ edges = (
+ await session.execute(
+ select(*cols).where(
+ GraphEdge.repository_id == repo_id,
+ or_(
+ GraphEdge.target_node_id == node.node_id,
+ (GraphEdge.target_node_id == def_file)
+ & (GraphEdge.edge_type == "dynamic_uses"),
+ ),
+ )
+ )
+ ).all()
+
+ # Importers of the definition file, then anything re-exporting the name
+ # onward from them, so a package barrel's own importers are scanned too.
+ files: set[str] = {def_file}
+ files.update(row[0] for row in edges if row[2] == "imports")
+ frontier, seen = [def_file], {def_file}
+ while frontier and len(files) <= MAX_FILES:
+ rows = (
+ await session.execute(
+ select(GraphEdge.source_node_id, GraphEdge.imported_names_json).where(
+ GraphEdge.repository_id == repo_id,
+ GraphEdge.edge_type == "imports",
+ GraphEdge.target_node_id.in_(frontier),
+ )
+ )
+ ).all()
+ frontier = []
+ for src, names_json in rows:
+ files.add(src)
+ names = _names(names_json)
+ # Unknown names may carry this one onward, so they are followed too.
+ if src not in seen and (not names or name in names or "*" in names):
+ seen.add(src)
+ frontier.append(src)
+
+ call_lines: dict[str, set[int]] = {}
+ uncertain = dynamic = unlined = False
+ for src, tgt, etype, names_json, lines_json, conf in edges:
+ if etype == "dynamic_uses":
+ names = _names(names_json)
+ if tgt == node.node_id or not names or name in names:
+ dynamic = True
+ continue
+ if tgt != node.node_id or etype in ("imports", "defines"):
+ continue
+ src_file = src.split("::", 1)[0]
+ lines = {int(n) for n in _names(lines_json) if n.isdigit()}
+ if etype == "calls" and not lines:
+ unlined = True
+ if not lines:
+ continue
+ files.add(src_file)
+ call_lines.setdefault(src_file, set()).update(lines)
+ if (conf or 0) < _MIN_CALL_CONFIDENCE:
+ uncertain = True
+
+ unseen = await asyncio.to_thread(_unseen_dirty_files, root, str(repo_root))
+ if unseen is None:
+ reasons.append("working tree status unknown")
+ unseen = []
+ unindexed = sorted(set(unseen) - files)
+
+ ordered = sorted(files)
+ if len(ordered) + len(unindexed) > MAX_FILES:
+ reasons.append(f"over {MAX_FILES} candidate files")
+ ordered = ordered[:MAX_FILES]
+ unindexed = unindexed[: max(0, MAX_FILES - len(ordered))]
+ definition = (def_file, node.start_line or 0, node.end_line or node.start_line or 0)
+ sites, unreadable, stale, renamed_in, is_default = await asyncio.to_thread(
+ _scan, root, ordered + unindexed, name, definition, call_lines
+ )
+
+ unindexed_set = set(unindexed)
+ if unreadable:
+ reasons.append(f"unreadable: {', '.join(unreadable[:3])}")
+ if stale:
+ reasons.append(f"stale: {stale} graph call lines no longer name it")
+ if unlined:
+ reasons.append("call edges without line numbers")
+ if uncertain:
+ reasons.append("low-confidence call edges")
+ if dynamic:
+ reasons.append("dynamic use of the symbol or its file")
+ language = node.language or await session.scalar(
+ select(GraphNode.language).where(
+ GraphNode.repository_id == repo_id, GraphNode.node_id == def_file
+ )
+ )
+ language = (language or "").lower()
+ if language not in _IMPORT_SCOPED_LANGUAGES:
+ reasons.append(f"{language or 'unknown language'}: same-package use is not scanned")
+ if renamed_in:
+ reasons.append(f"renamed on import or export: {', '.join(sorted(renamed_in)[:3])}")
+ if is_default:
+ reasons.append("default export: importers may rename it")
+ if len(sites) > MAX_SITES:
+ reasons.append(f"over {MAX_SITES} sites")
+ if node.kind in _MEMBER_KINDS or node.node_id.count("::") > 1:
+ reasons.append("member: calls through untyped receivers are not scanned")
+ touched = sorted({s["path"] for s in sites if s["path"] in unindexed_set})
+ if touched:
+ reasons.append(f"unindexed edits name it: {', '.join(touched[:3])}")
+ if not any(s["kind"] == "definition" for s in sites) and def_file not in unreadable:
+ reasons.append("definition not found at its indexed line")
+
+ sites.sort(key=lambda s: (s["kind"] != "definition", s["path"], s["line"]))
+ out: dict[str, Any] = {"sites": sites[:MAX_SITES], "complete": not reasons}
+ if len(sites) > MAX_SITES:
+ out["sites_omitted"] = len(sites) - MAX_SITES
+ if reasons:
+ out["reasons"] = reasons
+ return out
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/context.py b/packages/server/src/repowise/server/mcp_server/tool_context/context.py
index d3f784667..f7d0e5c38 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_context/context.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/context.py
@@ -14,6 +14,9 @@ Optional ``include`` parameter widens the response:
digest (questions, identifiers, git signals)
- include=["callers"] → who calls this symbol (symbol targets only)
- include=["callees"] → what this symbol calls (symbol targets only)
+ - include=["references"]→ every live edit site of a symbol (definition,
+ imports, calls, other mentions) and whether
+ the list is complete (symbol targets only)
- include=["ownership"] → primary owner, bus factor, contributor count
- include=["last_change"]→ last commit date and author
- include=["metrics"] → PageRank, betweenness, percentile ranks
@@ -77,6 +80,7 @@ _INCLUDE_BLOCKS = frozenset(
"full_doc",
"callers",
"callees",
+ "references",
"ownership",
"last_change",
"metrics",
@@ -122,6 +126,8 @@ async def get_context(
Batch targets in one call. No source bytes by default: pass
include=["skeleton"] for the whole file body-elided and line-verified in
ONE call, or Read it. Do not call get_symbol per signature.
+ For a rename or update-all-callers task, include=["references"] is the
+ whole edit set when complete is true.
Default responses fit 24,000 serialized chars; nonempty ``include`` uses
32,000. Reductions carry counts and ``_meta.omitted`` recovery refs;
@@ -131,11 +137,9 @@ async def get_context(
Args:
targets: file paths, module paths, or "path::Symbol" ids.
include: opt-in blocks: full_doc | ownership | last_change | callers
- | callees | metrics | community | decisions | skeleton | skeleton+ | health
- | doc_drift (documents naming this file) | symbols (all of a
- file's symbols; the default lists the top 15, classes and
- functions first).
- An unrecognised key is named in ignored_arguments.
+ | callees | references | metrics | community | decisions | skeleton
+ | skeleton+ | health | doc_drift (docs naming this file)
+ | symbols (all of a file's symbols, not the top 15).
compact: default True; False adds structure+imports+docstrings.
repo: usually omitted.
"""
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py b/packages/server/src/repowise/server/mcp_server/tool_context/targets.py
index a61dc6077..32626c029 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/targets.py
@@ -43,6 +43,7 @@ from repowise.core.persistence.models import (
)
from repowise.server.mcp_server._basis import call_resolution_basis
from repowise.server.mcp_server._budget import OmissionCollector, cap_collection
+from repowise.server.mcp_server._edit_sites import reference_edit_set
from repowise.server.mcp_server._helpers import (
LIKE_ESCAPE,
_decision_body,
@@ -1288,6 +1289,28 @@ async def _resolve_one_target(
collector=collector,
)
+ # --- Reference edit set: every live site naming the symbol ---
+ if include and "references" in include:
+ ref_node = graph_symbol
+ if ref_node is None and target_type == "symbol" and symbol_node_id:
+ res = await session.execute(
+ select(GraphNode).where(
+ GraphNode.repository_id == repo_id,
+ GraphNode.node_id.in_(symbol_id_variants(symbol_node_id)),
+ GraphNode.node_type == "symbol",
+ )
+ )
+ ref_node = min(
+ res.scalars().all(),
+ key=lambda g: (g.node_id != symbol_node_id, g.node_id),
+ default=None,
+ )
+ root = repo_root or getattr(repository, "local_path", None)
+ if ref_node is not None and root:
+ result_data["references"] = await reference_edit_set(session, repo_id, root, ref_node)
+ else:
+ result_data["references_note"] = "references require a symbol target in the graph"
+
# --- Metrics (replaces get_graph_metrics) ---
if include and "metrics" in include:
await _resolve_metrics(session, repository, symbol_node_id or target, result_data)
diff --git a/tests/unit/server/mcp/test_context_references.py b/tests/unit/server/mcp/test_context_references.py
new file mode 100644
index 000000000..f5002271d
--- /dev/null
+++ b/tests/unit/server/mcp/test_context_references.py
@@ -0,0 +1,380 @@
+"""include=["references"]: every live edit site of a symbol, and whether that is all of them."""
+
+from __future__ import annotations
+
+import json
+from datetime import UTC, datetime
+
+import pytest
+
+from repowise.core.persistence.models import GraphEdge, GraphNode
+from repowise.server.mcp_server import _edit_sites, _meta
+from repowise.server.mcp_server._edit_sites import reference_edit_set
+
+_NOW = datetime(2026, 3, 19, 12, 0, 0, tzinfo=UTC)
+_DEF = "pkg/catalog.py"
+_SYM = "pkg/catalog.py::backend_of"
+_USER = "app/widget.py"
+
+_CATALOG = """def helper():
+ return backend_of("x")
+
+
+def backend_of(name):
+ return name
+"""
+_WIDGET = """from pkg.catalog import (
+ MODELS,
+ backend_of,
+)
+
+
+class W:
+ def __init__(self):
+ self.b = backend_of("m")
+ self.label = "backend_of"
+"""
+
+
+def _dirty(monkeypatch, paths: frozenset[str]) -> None:
+ for module in (_edit_sites, _meta):
+ monkeypatch.setattr(module, "_working_tree_dirty_paths", lambda _p: paths)
+
+
[email protected](autouse=True)
+def _clean_tree(monkeypatch):
+ _dirty(monkeypatch, frozenset())
+
+
+def _edge(i: int, repo_id: str, src: str, tgt: str, etype: str, **kw) -> GraphEdge:
+ return GraphEdge(
+ id=f"ref_edge_{i}",
+ repository_id=repo_id,
+ source_node_id=src,
+ target_node_id=tgt,
+ edge_type=etype,
+ confidence=kw.pop("confidence", 0.95),
+ created_at=_NOW,
+ **kw,
+ )
+
+
+async def _seed(
+ session, repo_id: str, tmp_path, *, widget_call_lines=(9,), extra=(), language="python"
+):
+ (tmp_path / "pkg").mkdir()
+ (tmp_path / "app").mkdir()
+ (tmp_path / _DEF).write_text(_CATALOG, encoding="utf-8")
+ (tmp_path / _USER).write_text(_WIDGET, encoding="utf-8")
+ node = GraphNode(
+ id="ref_sym",
+ repository_id=repo_id,
+ node_id=_SYM,
+ node_type="symbol",
+ name="backend_of",
+ file_path=_DEF,
+ kind="function",
+ language=language,
+ start_line=5,
+ end_line=6,
+ created_at=_NOW,
+ )
+ rows = [
+ node,
+ _edge(1, repo_id, _USER, _DEF, "imports", imported_names_json='["MODELS", "backend_of"]'),
+ _edge(
+ 2,
+ repo_id,
+ f"{_USER}::W::__init__",
+ _SYM,
+ "calls",
+ call_lines_json=json.dumps(list(widget_call_lines)),
+ ),
+ _edge(3, repo_id, f"{_DEF}::helper", _SYM, "calls", call_lines_json="[2]"),
+ *(_edge(10 + i, repo_id, *e[:3], **e[3]) for i, e in enumerate(extra)),
+ ]
+ session.add_all(rows)
+ await session.flush()
+ return node
+
+
+def _sites(out):
+ return [(s["path"], s["line"], s["kind"]) for s in out["sites"]]
+
+
+async def test_definition_import_call_and_same_file_call(session, repo_id, tmp_path):
+ node = await _seed(session, repo_id, tmp_path)
+
+ out = await reference_edit_set(session, repo_id, tmp_path, node)
+
+ assert _sites(out) == [
+ (_DEF, 5, "definition"),
+ (_USER, 3, "import"), # continuation line of a multi-line import
+ (_USER, 9, "call"),
+ (_USER, 10, "reference"), # a string naming it
+ (_DEF, 2, "call"), # same-file call
+ ]
+ assert out["complete"] is True
+ assert "reasons" not in out
+
+
+async def test_stale_call_line_is_dropped_and_marks_incomplete(session, repo_id, tmp_path):
+ node = await _seed(session, repo_id, tmp_path, widget_call_lines=(7, 9))
+
+ out = await reference_edit_set(session, repo_id, tmp_path, node)
+
+ assert (_USER, 7) not in {(p, n) for p, n, _k in _sites(out)}
+ assert out["complete"] is False
+ assert any(r.startswith("stale") for r in out["reasons"])
+
+
+async def test_dynamic_use_of_the_file_marks_incomplete(session, repo_id, tmp_path):
+ node = await _seed(
+ session,
+ repo_id,
+ tmp_path,
+ extra=[("app/loader.py", _DEF, "dynamic_uses", {"imported_names_json": "[]"})],
+ )
+
+ out = await reference_edit_set(session, repo_id, tmp_path, node)
+
+ assert out["complete"] is False
+ assert any("dynamic" in r for r in out["reasons"])
+
+
+async def test_dynamic_use_naming_another_symbol_does_not(session, repo_id, tmp_path):
+ node = await _seed(
+ session,
+ repo_id,
+ tmp_path,
+ extra=[("app/loader.py", _DEF, "dynamic_uses", {"imported_names_json": '["helper"]'})],
+ )
+
+ out = await reference_edit_set(session, repo_id, tmp_path, node)
+
+ assert out["complete"] is True
+
+
+async def test_unindexed_edit_naming_the_symbol_is_listed_and_incomplete(
+ session, repo_id, tmp_path, monkeypatch
+):
+ node = await _seed(session, repo_id, tmp_path)
+ (tmp_path / "app" / "new.py").write_text("x = backend_of(1)\n", encoding="utf-8")
+ _dirty(monkeypatch, frozenset({"app/new.py"}))
+
+ out = await reference_edit_set(session, repo_id, tmp_path, node)
+
+ assert ("app/new.py", 1, "reference") in _sites(out)
+ assert out["complete"] is False
+
+
+async def test_same_package_language_is_never_complete(session, repo_id, tmp_path):
+ node = await _seed(session, repo_id, tmp_path, language="java")
+
+ out = await reference_edit_set(session, repo_id, tmp_path, node)
+
+ assert (_USER, 9, "call") in _sites(out)
+ assert out["complete"] is False
+ assert "java: same-package use is not scanned" in out["reasons"]
+
+
+async def test_renamed_barrel_re_export_marks_incomplete(session, repo_id, tmp_path):
+ node = await _seed(
+ session,
+ repo_id,
+ tmp_path,
+ extra=[("pkg/__init__.py", _DEF, "imports", {"imported_names_json": '["backend_of"]'})],
+ )
+ (tmp_path / "pkg" / "__init__.py").write_text(
+ "from .catalog import backend_of as pick_backend\n", encoding="utf-8"
+ )
+
+ out = await reference_edit_set(session, repo_id, tmp_path, node)
+
+ assert ("pkg/__init__.py", 1, "import") in _sites(out)
+ assert out["complete"] is False
+ assert any(r.startswith("renamed on import or export") for r in out["reasons"])
+
+
+async def test_over_the_site_cap_is_incomplete(session, repo_id, tmp_path):
+ node = await _seed(session, repo_id, tmp_path)
+ with (tmp_path / _USER).open("a", encoding="utf-8") as fh:
+ fh.write("refs = [\n" + " backend_of,\n" * 200 + "]\n")
+
+ out = await reference_edit_set(session, repo_id, tmp_path, node)
+
+ assert len(out["sites"]) == _edit_sites.MAX_SITES
+ assert out["sites_omitted"] > 0
+ assert out["complete"] is False
+ assert f"over {_edit_sites.MAX_SITES} sites" in out["reasons"]
+
+
+async def test_module_import_then_attribute_access_is_found(session, repo_id, tmp_path):
+ """``from pkg import catalog`` imports the module; ``catalog.backend_of`` is the site."""
+ node = await _seed(
+ session,
+ repo_id,
+ tmp_path,
+ extra=[("app/mod_user.py", _DEF, "imports", {"imported_names_json": '["catalog"]'})],
+ )
+ (tmp_path / "app" / "mod_user.py").write_text(
+ "from pkg import catalog\n\nvalue = catalog.backend_of(1)\n", encoding="utf-8"
+ )
+
+ out = await reference_edit_set(session, repo_id, tmp_path, node)
+
+ assert ("app/mod_user.py", 3, "reference") in _sites(out)
+ assert out["complete"] is True
+
+
+async def test_importer_with_unknown_names_is_followed_onward(session, repo_id, tmp_path):
+ node = await _seed(
+ session,
+ repo_id,
+ tmp_path,
+ extra=[
+ ("app/hub.py", _DEF, "imports", {"imported_names_json": "[]"}),
+ ("app/far.py", "app/hub.py", "imports", {"imported_names_json": '["thing"]'}),
+ ],
+ )
+ (tmp_path / "app" / "hub.py").write_text("from pkg.catalog import *\n", encoding="utf-8")
+ (tmp_path / "app" / "far.py").write_text(
+ "from app.hub import thing\n\nthing(backend_of)\n", encoding="utf-8"
+ )
+
+ out = await reference_edit_set(session, repo_id, tmp_path, node)
+
+ assert ("app/far.py", 3, "reference") in _sites(out)
+
+
+async def _seed_js(session, repo_id: str, tmp_path, files: dict[str, str], names='["pick"]'):
+ """``web/a.ts`` defines ``pick`` on line 1; every other file imports it."""
+ for rel, text in files.items():
+ (tmp_path / rel).parent.mkdir(parents=True, exist_ok=True)
+ (tmp_path / rel).write_text(text, encoding="utf-8")
+ node = GraphNode(
+ id="js_sym",
+ repository_id=repo_id,
+ node_id="web/a.ts::pick",
+ node_type="symbol",
+ name="pick",
+ file_path="web/a.ts",
+ kind="function",
+ language="typescript",
+ start_line=1,
+ end_line=1,
+ created_at=_NOW,
+ )
+ importers = [
+ _edge(40 + i, repo_id, rel, "web/a.ts", "imports", imported_names_json=names)
+ for i, rel in enumerate(r for r in files if r != "web/a.ts")
+ ]
+ session.add_all([node, *importers])
+ await session.flush()
+ return node
+
+
+async def test_plain_named_import_in_typescript_is_complete(session, repo_id, tmp_path):
+ node = await _seed_js(
+ session,
+ repo_id,
+ tmp_path,
+ {
+ "web/a.ts": "export function pick(x: number): number { return x }\n",
+ "web/b.tsx": "import { pick } from './a'\nconst v = cond ? pick : other\n",
+ },
+ )
+
+ out = await reference_edit_set(session, repo_id, tmp_path, node)
+
+ assert ("web/b.tsx", 2, "reference") in _sites(out)
+ assert out["complete"] is True, out.get("reasons")
+
+
+async def test_default_export_is_incomplete(session, repo_id, tmp_path):
+ """``import anything from './a'`` binds a default export under any name."""
+ node = await _seed_js(
+ session,
+ repo_id,
+ tmp_path,
+ {
+ "web/a.ts": "export default function pick(x: number) { return x }\n",
+ "web/b.ts": "import chooser from './a'\nchooser(1)\n",
+ },
+ )
+
+ out = await reference_edit_set(session, repo_id, tmp_path, node)
+
+ assert out["complete"] is False
+ assert "default export: importers may rename it" in out["reasons"]
+
+
+async def test_commonjs_destructure_rename_is_incomplete(session, repo_id, tmp_path):
+ """Both the one-line and the multi-line ``{ pick: other } = require(...)``."""
+ node = await _seed_js(
+ session,
+ repo_id,
+ tmp_path,
+ {
+ "web/a.ts": "export function pick(x: number) { return x }\n",
+ "web/one.js": "const { pick: choose } = require('./a')\nchoose(1)\n",
+ "web/multi.js": "const {\n pick: choose,\n} = require('./a')\nchoose(2)\n",
+ },
+ )
+
+ out = await reference_edit_set(session, repo_id, tmp_path, node)
+
+ sites = _sites(out)
+ assert ("web/one.js", 2, "reference") in sites # the alias is scanned for too
+ assert ("web/multi.js", 4, "reference") in sites
+ assert out["complete"] is False
+ renamed = next(r for r in out["reasons"] if r.startswith("renamed on import or export"))
+ assert "web/one.js" in renamed and "web/multi.js" in renamed
+
+
+async def test_rename_in_a_file_outside_the_re_export_chain_is_incomplete(
+ session, repo_id, tmp_path
+):
+ """A file importing only the module is not followed, yet its rename still counts."""
+ node = await _seed_js(
+ session,
+ repo_id,
+ tmp_path,
+ {
+ "web/a.ts": "export function pick(x: number) { return x }\n",
+ "web/c.ts": "import * as a from './a'\nexport const { pick: choose } = a\n",
+ },
+ names='["a"]',
+ )
+
+ out = await reference_edit_set(session, repo_id, tmp_path, node)
+
+ assert out["complete"] is False
+ assert any("web/c.ts" in r for r in out["reasons"])
+
+
+async def test_get_context_serves_references_for_a_symbol(setup_mcp, session, tmp_path):
+ from repowise.server.mcp_server import get_context
+
+ await _seed(session, setup_mcp, tmp_path)
+ await session.commit()
+
+ t = (await get_context([_SYM], include=["references"]))["targets"][_SYM]
+
+ assert t["references"]["complete"] is True
+ assert (_USER, 9, "call") in _sites(t["references"])