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.

Convert the last test-path copies in the server to the shared rules (#1113)

Raghav Chamadiya60cbf462851d
diff --git a/packages/core/src/repowise/core/ingestion/traverser.py b/packages/core/src/repowise/core/ingestion/traverser.py
index 174613b63..e36779089 100644
--- a/packages/core/src/repowise/core/ingestion/traverser.py
+++ b/packages/core/src/repowise/core/ingestion/traverser.py
@@ -117,8 +117,8 @@ _BLOCKED_DIRS: frozenset[str] = frozenset(
# test files can be indexed safely. Their content is needed to
# answer questions about test helpers and fixtures. Files under
# these directories are still tagged is_test=True via
- # _is_test_file() so downstream consumers can filter them when
- # appropriate.
+ # is_test_related_path() so downstream consumers can filter them
+ # when appropriate.
#
# The following ARE still blocked because they typically hold
# binary fixtures, generated artifacts, or browser-driven test
diff --git a/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py b/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py
index bec3fc218..2a1965599 100644
--- a/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py
+++ b/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py
@@ -44,6 +44,7 @@ from sqlalchemy import select
from repowise.core.persistence.database import get_session
from repowise.core.persistence.models import GraphEdge, GraphNode, Page
+from repowise.core.test_paths import is_test_path
# How many candidates each retriever fetches before merging. Both modes
# tend to put the right answer in their top ~10, so 15 gives RRF room to
@@ -189,20 +190,14 @@ def _hit_dict_from_result(result: Any) -> dict:
# Retrieval noise that should not occupy get_answer's top-5 on a plain question.
# Mirrors search_codebase's demotion (tool_search._sort_demoting_noise) on the
-# answer pipeline's hit shape. Kept local so the answer pipeline does not import
-# the search tool; the token lists are intentionally the same.
-_TEST_PATH_TOKENS = ("/test/", "/tests/", "/__tests__/", "test_", "_test.", ".spec.", ".test.")
+# answer pipeline's hit shape. Both now read the same test-path rules, so the
+# two tools can no longer demote different sets of files.
_TEST_QUERY_RE = re.compile(
r"\b(test|tests|testing|tested|unit[\s-]?test|integration[\s-]?test|pytest|fixture|mock|spec)\b",
re.IGNORECASE,
)
-def _is_test_path(target_path: str) -> bool:
- tp = (target_path or "").lower()
- return any(tok in tp for tok in _TEST_PATH_TOKENS)
-
-
def demote_noise_hits(hits: list[dict], question: str, *, is_why: bool) -> list[dict]:
"""Stable-partition retrieval noise below real pages before the top-5 cap.
@@ -213,6 +208,10 @@ def demote_noise_hits(hits: list[dict], question: str, *, is_why: bool) -> list[
then, folded into the prelude); test file pages demote unless the question is
explicitly about tests. Stable: real hits keep their order, and noise keeps
its relative order at the tail (never dropped — an agent may still want it).
+
+ Tests demote, test support does not: "where are the shared fixtures" is a
+ plain question whose answer is a ``conftest.py``, and demoting it would push
+ the answer out of the window that feeds synthesis.
"""
if not hits:
return hits
@@ -221,9 +220,7 @@ def demote_noise_hits(hits: list[dict], question: str, *, is_why: bool) -> list[
def _is_noise(h: dict) -> bool:
pt = h.get("page_type")
return (pt == "decision_record" and not is_why) or (
- pt == "file_page"
- and not test_focused
- and _is_test_path(h.get("target_path", ""))
+ pt == "file_page" and not test_focused and is_test_path(h.get("target_path") or "")
)
real = [h for h in hits if not _is_noise(h)]
diff --git a/packages/server/src/repowise/server/mcp_server/_flow_path.py b/packages/server/src/repowise/server/mcp_server/_flow_path.py
index 06d0c3c56..16618e344 100644
--- a/packages/server/src/repowise/server/mcp_server/_flow_path.py
+++ b/packages/server/src/repowise/server/mcp_server/_flow_path.py
@@ -39,6 +39,7 @@ from typing import Any
from sqlalchemy import select
from repowise.core.persistence.models import GraphEdge, Page, WikiSymbol
+from repowise.core.test_paths import is_test_related_path
from repowise.server.mcp_server.tool_answer.retrieval import _question_terms
# Edge kinds that form the file-level dependency graph. ``imports`` is
@@ -107,14 +108,15 @@ def _is_plumbing(path: str) -> bool:
graph (a test imports both ends of the codebase), so they make good BFS
coincidences and bad injected answers. Kept out of anchors and injection;
they may still be traversed as interior nodes.
+
+ Test material means the union, fixtures included: a factory module bridges
+ the graph exactly the way a test does. The rules come from
+ :mod:`repowise.core.test_paths` rather than the substring list this used to
+ carry, which anchored on ``/tests/`` and so missed a repo's root-level
+ ``tests/`` tree entirely (#1103).
"""
- norm = path.replace("\\", "/").lower()
- base = norm.rsplit("/", 1)[-1]
- if base == "__init__.py":
- return True
- if base.startswith("test_") or base.endswith("_test.py") or base.endswith(".test.ts"):
- return True
- return "/tests/" in norm or "/test/" in norm or "/__tests__/" in norm
+ base = path.replace("\\", "/").rsplit("/", 1)[-1]
+ return base.lower() == "__init__.py" or is_test_related_path(path)
def _token_matches_stem(token: str, stem: str) -> bool:
diff --git a/packages/server/src/repowise/server/mcp_server/tool_search.py b/packages/server/src/repowise/server/mcp_server/tool_search.py
index 5f7533fb4..ac56fc506 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_search.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_search.py
@@ -14,6 +14,7 @@ from repowise.core.persistence.models import (
Page,
)
from repowise.core.registry import mcp_tool_registry as mcp
+from repowise.core.test_paths import is_test_path, is_test_related_path
from repowise.server.mcp_server._answer_pipeline import _RRF_K, _RRF_SCORE_SCALE
from repowise.server.mcp_server._helpers import (
_get_exclude_spec,
@@ -190,10 +191,14 @@ def _is_test_query(query: str) -> bool:
def _is_test_page(item: dict) -> bool:
- """True when a hit is a file_page documenting a test file."""
- return item.get("page_type") == "file_page" and (
- _classify_hit_kind(item.get("target_path") or "", "file_page") == "test"
- )
+ """True when a hit is a file_page documenting a test file.
+
+ Tests only, deliberately not test support: a ``conftest.py`` or a fixture
+ module is often exactly what the person searching wanted, so it keeps its
+ rank. The ``kind`` filter counts both (see :func:`_classify_hit_kind`) —
+ asking for tests and asking to rank tests lower are different questions.
+ """
+ return item.get("page_type") == "file_page" and is_test_path(item.get("target_path") or "")
def _downweight_test_pages(output: list[dict], query: str) -> None:
@@ -328,7 +333,8 @@ def _fetch_limit_for(limit: int, kind: str | None) -> int:
# Path-prefix heuristics for the ``kind`` filter. We classify a hit's
# target_path against these prefixes; if none match, the hit falls into
# ``other`` and is dropped only when the caller asked for a specific kind.
-_TEST_PATH_TOKENS = ("/test/", "/tests/", "/__tests__/", "test_", "_test.", ".spec.", ".test.")
+# Tests are not in this list: they come from ``repowise.core.test_paths``, the
+# same rules that stamped the file's ``is_test`` flag at ingestion.
_CONFIG_PATH_TOKENS = (
"pyproject.toml",
"package.json",
@@ -357,16 +363,26 @@ def _classify_hit_kind(target_path: str, page_type: str) -> str:
them fall through to the path heuristics classified every decision
record as "implementation", so ``kind="implementation"`` returned
decision pages instead of filtering them out.
+
+ ``test`` is the union of tests and test support here: someone asking for
+ ``kind="implementation"`` does not want a ``conftest.py`` back, and someone
+ asking for ``kind="test"`` does.
+
+ Config wins over test, which the token list this replaced never had to
+ decide: ``.github/workflows/tests.yml`` is a workflow whatever it is named,
+ and dropping it from ``kind="config"`` would be the more surprising answer.
"""
tp = (target_path or "").lower()
if page_type in ("module_page", "symbol_spotlight") or tp.endswith(".md"):
return "doc"
if not tp or page_type not in ("file_page",):
return "doc"
- if any(tok in tp for tok in _TEST_PATH_TOKENS):
- return "test"
if any(tok in tp for tok in _CONFIG_PATH_TOKENS):
return "config"
+ # Original case, not ``tp``: the camel (FooTest.java) and .NET project-dir
+ # (Foo.Tests/) rules are deliberately case-sensitive.
+ if is_test_related_path(target_path):
+ return "test"
return "implementation"
diff --git a/packages/server/src/repowise/server/mcp_server/tool_search_symbols.py b/packages/server/src/repowise/server/mcp_server/tool_search_symbols.py
index d0351640a..98c9a1fc9 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_search_symbols.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_search_symbols.py
@@ -25,26 +25,19 @@ from sqlalchemy import case, func, or_, select
from repowise.core.persistence.database import get_session
from repowise.core.persistence.models import GraphNode, Page, WikiSymbol
+from repowise.core.test_paths import is_test_path, is_test_related_path
from repowise.server.mcp_server._helpers import (
_get_exclude_spec,
_get_repo,
is_excluded,
)
-# Path tokens that mark a symbol's file as a test (mirrors tool_search's set).
-_TEST_PATH_TOKENS = ("/test/", "/tests/", "/__tests__/", "test_", "_test.", ".spec.", ".test.")
-
# Candidate ceiling: scoring/sorting happens in Python, so the SQL pre-filter
# caps how many rows we pull. Generous enough that the true top-`limit` is
# always inside the window, bounded so a pathological LIKE can't load the table.
_MAX_CANDIDATES = 400
-def _is_test_path(path: str | None) -> bool:
- tp = (path or "").lower()
- return any(tok in tp for tok in _TEST_PATH_TOKENS)
-
-
def _tokens(text: str | None) -> set[str]:
"""Lowercase token set, splitting on non-alnum AND camelCase humps.
@@ -114,7 +107,12 @@ def _score_symbol(
if gnode.is_entry_point:
score += 3.0
- if (gnode is not None and gnode.is_test) or _is_test_path(row.file_path):
+ # Tests only, not test support: a fixture or a conftest helper is often what
+ # the query was after, so it keeps its score. The flag is read first for the
+ # same reason everywhere else does, but note it decides nothing here today —
+ # it is stamped on file nodes and these are symbol nodes, so the path rules
+ # are what answer in practice.
+ if (gnode is not None and gnode.is_test) or is_test_path(row.file_path or "", row.language):
score -= 5.0
return score
@@ -238,7 +236,11 @@ async def search_symbols_single(
if is_excluded(row.file_path, spec) or row.file_path in tombstoned:
continue
g = gmap.get(row.symbol_id)
- is_test = (g is not None and g.is_test) or _is_test_path(row.file_path)
+ # The union here, unlike the ranking penalty above: ``kind`` splits the
+ # repo in two, and a fixture belongs on the test side of that line.
+ is_test = (g is not None and g.is_test) or is_test_related_path(
+ row.file_path or "", row.language
+ )
if not _symbol_kind_for_request_kind(kind, is_test):
continue
scored.append((_score_symbol(row, g, qtokens, qnorm), row))
diff --git a/packages/server/src/repowise/server/routers/stats.py b/packages/server/src/repowise/server/routers/stats.py
index 35a98183b..1cf4045d1 100644
--- a/packages/server/src/repowise/server/routers/stats.py
+++ b/packages/server/src/repowise/server/routers/stats.py
@@ -39,6 +39,7 @@ from repowise.core.persistence.models import (
HealthFileMetric,
WikiSymbol,
)
+from repowise.core.test_paths import is_test_related_path
from repowise.server.deps import get_db_session, verify_api_key
router = APIRouter(
@@ -149,13 +150,6 @@ def _as_utc(dt: datetime | None) -> datetime | None:
return dt if dt.tzinfo is not None else dt.replace(tzinfo=UTC)
-# Test-path convention shared with analysis (communities / execution_flows):
-# catches conftest, fixtures, and spec files the `is_test` flag misses.
-_TEST_PATH_RE = re.compile(
- r"(test[s_/]|_test\.|\.test\.|\.spec\.|__tests__|conftest|fixture[s]?[/.])"
-)
-
-
# ---------------------------------------------------------------------------
# Scale — what this codebase is, dimensionally.
# ---------------------------------------------------------------------------
@@ -677,10 +671,19 @@ async def _records(
# Most imported file — highest fan-in among non-test file nodes, the
# legible version of "most central". External and test nodes are excluded
- # so the award names real project source; the `is_test` flag misses
- # conftest/fixture files, so the top candidates are re-checked against the
- # test-path convention used across analysis. Falls back to the PageRank
- # pick when graph metrics were not materialized for this repo.
+ # so the award names real project source, and the top candidates are then
+ # re-checked against the shared test-path rules.
+ #
+ # The re-check is not redundant with the SQL filter. `is_test` is *stored*,
+ # stamped when the file was last traversed, so an index written before the
+ # current rules can carry a stale answer — and the file this award is most
+ # likely to hand to is `tests/conftest.py`, which tops fan-in in any repo
+ # that shares fixtures widely (713 imports in this one, more than double the
+ # runner-up). The rules themselves now come from one place rather than the
+ # unanchored regex this used to hold, which read `src/latest/api.py` and
+ # `protest/main.py` as tests and passed the award to the runner-up (#1103).
+ #
+ # Falls back to the PageRank pick when graph metrics were not materialized.
candidates = (
await session.execute(
select(GraphMetric.node_id, GraphMetric.in_degree, GraphMetric.pagerank)
@@ -700,7 +703,7 @@ async def _records(
.limit(10)
)
).all()
- imported = next((c for c in candidates if not _TEST_PATH_RE.search(c[0])), None)
+ imported = next((c for c in candidates if not is_test_related_path(c[0])), None)
if imported is not None and (imported[1] or 0) > 0:
out["most_central_file"] = {
"path": imported[0],
diff --git a/tests/unit/server/mcp/test_answer_noise_demotion.py b/tests/unit/server/mcp/test_answer_noise_demotion.py
index ec6a8c090..5883eb144 100644
--- a/tests/unit/server/mcp/test_answer_noise_demotion.py
+++ b/tests/unit/server/mcp/test_answer_noise_demotion.py
@@ -53,6 +53,35 @@ def test_test_page_kept_on_test_question():
assert out[0]["target_path"] == "tests/unit/test_incremental.py" # test-focused: no demotion
+def test_fixtures_and_test_lookalikes_keep_their_rank():
+ """Only tests demote, and only real ones (#1103).
+
+ The question is often about the fixtures themselves, and the substring
+ tokens this ran on also demoted production files spelling "test_".
+ """
+ # Leading segments on purpose: the token list this replaced anchored on
+ # "/tests/", so a root-level `tests/` path would pass it for the wrong
+ # reason and the assertion would prove nothing.
+ hits = [
+ _hit("file_page", "packages/core/tests/conftest.py"),
+ _hit("file_page", "packages/core/tests/factories/user.py"),
+ _hit("file_page", "src/analysis/missing_test_signal.py"),
+ _hit("file_page", "src/latest/api.py"),
+ ]
+ out = demote_noise_hits(list(hits), "where do the shared fixtures live", is_why=False)
+ assert [h["target_path"] for h in out] == [h["target_path"] for h in hits]
+
+
+def test_layouts_the_token_list_missed_now_demote():
+ hits = [
+ _hit("file_page", "myapp/tests.py"),
+ _hit("file_page", "Foo.Tests/Bar.cs"),
+ _hit("file_page", "src/pipeline/incremental.py"),
+ ]
+ out = demote_noise_hits(hits, "how does incremental update work", is_why=False)
+ assert out[0]["target_path"] == "src/pipeline/incremental.py"
+
+
def test_stable_order_preserved_among_real_hits():
hits = [
_hit("file_page", "src/a.py"),
diff --git a/tests/unit/server/mcp/test_flow_path.py b/tests/unit/server/mcp/test_flow_path.py
index f3259e2b4..13609485c 100644
--- a/tests/unit/server/mcp/test_flow_path.py
+++ b/tests/unit/server/mcp/test_flow_path.py
@@ -214,3 +214,22 @@ async def test_cross_language_anchor_dropped(session, repo_id):
paths = {h.get("target_path") for h in combined}
assert sym_py in paths # in-language endpoint injected
assert sym_ts not in paths # off-language same-name match dropped
+
+
+def test_plumbing_covers_test_material_by_the_shared_rules():
+ """Tests bridge unrelated files, so none of them make a flow endpoint.
+
+ The substring list this replaced anchored on ``/tests/``, so a repo whose
+ suite sits at the root had its whole test tree treated as ordinary source
+ and eligible for injection (#1103).
+ """
+ from repowise.server.mcp_server._flow_path import _is_plumbing
+
+ assert _is_plumbing("tests/unit/server/test_flow_path.py") # root-level suite
+ assert _is_plumbing("myapp/tests.py")
+ assert _is_plumbing("Foo.Tests/Bar.cs")
+ assert _is_plumbing("packages/core/tests/conftest.py") # support bridges too
+ assert _is_plumbing("pkg/server/__init__.py") # re-export glue, unchanged
+ # Production code that merely spells "test" is a legitimate endpoint.
+ assert not _is_plumbing("src/analysis/missing_test_signal.py")
+ assert not _is_plumbing("src/latest/api.py")
diff --git a/tests/unit/server/mcp/test_search.py b/tests/unit/server/mcp/test_search.py
index 0b9ebae99..1f7c8a200 100644
--- a/tests/unit/server/mcp/test_search.py
+++ b/tests/unit/server/mcp/test_search.py
@@ -246,6 +246,32 @@ class TestNoiseDemotion:
# Only file pages classify as test pages, never decision/concept pages.
assert not _is_test_page({"page_type": "decision_record", "target_path": ""})
+ def test_is_test_page_keeps_support_and_lookalikes_ranked(self):
+ """Demotion is tests only, and only real tests (#1103).
+
+ The substring token list this used to run on demoted every production
+ file whose path merely contained "test_", and demoted the fixtures a
+ "where are the shared fixtures" query is asking for.
+ """
+ from repowise.server.mcp_server.tool_search import _is_test_page
+
+ def page(path: str) -> dict:
+ return {"page_type": "file_page", "target_path": path}
+
+ # Test support keeps its rank: it is often the answer. Leading segments
+ # on purpose — the token list this replaced anchored on "/tests/", so a
+ # root-level path would pass for the wrong reason.
+ assert not _is_test_page(page("packages/core/tests/conftest.py"))
+ assert not _is_test_page(page("packages/core/tests/factories/user.py"))
+ # Production code that merely spells "test".
+ assert not _is_test_page(page("src/analysis/missing_test_signal.py"))
+ assert not _is_test_page(page("src/latest/api.py"))
+ # Real tests the token list missed.
+ assert _is_test_page(page("myapp/tests.py"))
+ assert _is_test_page(page("src/test/java/Foo.java"))
+ assert _is_test_page(page("Foo.Tests/Bar.cs"))
+ assert _is_test_page(page("e2e/login.ts"))
+
def test_downweight_test_pages_scales_unless_test_query(self):
from repowise.server.mcp_server.tool_search import _downweight_test_pages
@@ -390,6 +416,26 @@ class TestClassifyHitKind:
assert _classify_hit_kind("pyproject.toml", "file_page") == "config"
assert _classify_hit_kind("docs/guide.md", "file_page") == "doc"
+ def test_kind_test_covers_support_unlike_the_demotion(self):
+ """``kind`` splits the repo in two, so a fixture lands on the test side.
+
+ Deliberately a different answer from ``_is_test_page``: nobody asking
+ for ``kind="implementation"`` wants a conftest back, but a fixture page
+ should still rank normally on an ordinary query.
+ """
+ from repowise.server.mcp_server.tool_search import _classify_hit_kind, _is_test_page
+
+ for path in ("packages/core/tests/conftest.py", "packages/core/tests/factories/user.py"):
+ assert _classify_hit_kind(path, "file_page") == "test"
+ assert not _is_test_page({"page_type": "file_page", "target_path": path})
+ # Config beats test: a workflow named for tests is still a workflow.
+ assert _classify_hit_kind(".github/workflows/tests.yml", "file_page") == "config"
+ # Case-sensitive rules survive: the classifier must not see a lowercased
+ # path, or FooTest.java and Foo.Tests/ stop matching.
+ assert _classify_hit_kind("Foo.Tests/Bar.cs", "file_page") == "test"
+ assert _classify_hit_kind("src/FooTest.java", "file_page") == "test"
+ assert _classify_hit_kind("src/latest/api.py", "file_page") == "implementation"
+
def test_module_page_is_doc(self):
from repowise.server.mcp_server.tool_search import _classify_hit_kind
@@ -477,6 +523,42 @@ class TestDecisionDemotionAndRescue:
assert result["results"][0]["page_type"] == "decision_record"
+class TestSymbolTestPenalty:
+ """The -5 a symbol takes for living in a test file (#1103)."""
+
+ @staticmethod
+ def _score(path: str, language: str = "python") -> float:
+ from repowise.core.persistence.models import WikiSymbol
+ from repowise.server.mcp_server.tool_search_symbols import _score_symbol
+
+ row = WikiSymbol(
+ name="build_index",
+ qualified_name="build_index",
+ file_path=path,
+ language=language,
+ )
+ # No graph node: symbol nodes never carry `is_test`, so the path rules
+ # are what decide here in practice.
+ return _score_symbol(row, None, {"build", "index"}, "build_index")
+
+ def test_tests_are_penalised_and_support_is_not(self):
+ base = self._score("src/indexing/build.py")
+ assert self._score("packages/core/tests/test_build.py") == base - 5.0
+ assert self._score("myapp/tests.py") == base - 5.0
+ # A fixture factory is often what the query was after.
+ assert self._score("packages/core/tests/conftest.py") == base
+ assert self._score("packages/core/tests/factories/user.py") == base
+ # Production code that merely spells "test".
+ assert self._score("src/analysis/missing_test_signal.py") == base
+
+ def test_language_decides_the_ambiguous_spec_dir(self):
+ base = self._score("src/indexing/build.py")
+ # RSpec for Ruby, a specifications folder for anything else — the same
+ # call the traverser made when it stamped the file's flag.
+ assert self._score("spec/models/user.rb", language="ruby") == base - 5.0
+ assert self._score("spec/openapi/users.py", language="python") == base
+
+
class TestSymbolSearch:
"""mode="symbol" / "auto" routing into the structural index (issue #484)."""
diff --git a/tests/unit/server/test_stats_superlatives.py b/tests/unit/server/test_stats_superlatives.py
index 99ba17512..351a5ec96 100644
--- a/tests/unit/server/test_stats_superlatives.py
+++ b/tests/unit/server/test_stats_superlatives.py
@@ -2,7 +2,8 @@
``biggest_commit`` must skip the repo's very first commit (every initial
import would win otherwise) and ``longest_streak`` counts consecutive UTC
-days with at least one commit.
+days with at least one commit. ``most_central_file`` names the most-imported
+file that is not a test.
"""
from __future__ import annotations
@@ -14,7 +15,8 @@ from httpx import AsyncClient
from repowise.core.persistence.crud import get_repository, upsert_git_commits_bulk
from repowise.core.persistence.database import get_session
-from repowise.server.routers.stats import _commit_pass
+from repowise.core.persistence.models import GraphMetric, GraphNode
+from repowise.server.routers.stats import _commit_pass, _records
from tests.unit.server.conftest import create_test_repo
_DAY = 86400
@@ -70,3 +72,50 @@ async def test_biggest_commit_skips_initial_and_streak_counts_days(
streak = activity["rhythm"]["longest_streak"]
assert streak is not None
assert streak["days"] == 4
+
+
+async def test_most_central_file_skips_tests_without_false_positives(
+ client: AsyncClient, app
+) -> None:
+ """The award goes to the top real source file (#1103).
+
+ Two ways to get this wrong, one on each side. The unanchored regex this
+ used to re-check with read ``src/latest/api.py`` as a test and handed the
+ award to the runner-up. Trusting ``is_test`` alone would hand it to
+ ``tests/conftest.py``, which tops fan-in in any repo sharing fixtures
+ widely and whose stored flag is only as fresh as its last traversal.
+ """
+ repo = await create_test_repo(client)
+ nodes = [
+ # Stale flag: stamped before conftest counted as test material.
+ ("tests/conftest.py", False, 700),
+ ("src/latest/api.py", False, 90), # not a test, whatever the name reads like
+ ("src/util.py", False, 40),
+ ]
+ async with get_session(app.state.session_factory) as session:
+ for path, is_test, in_degree in nodes:
+ session.add(
+ GraphNode(
+ repository_id=repo["id"],
+ node_id=path,
+ node_type="file",
+ is_test=is_test,
+ pagerank=0.1,
+ )
+ )
+ session.add(
+ GraphMetric(
+ repository_id=repo["id"],
+ node_id=path,
+ in_degree=in_degree,
+ pagerank=0.1,
+ )
+ )
+ await session.commit()
+
+ async with get_session(app.state.session_factory) as session:
+ out = await _records(session, repo["id"], metrics=[], all_meta=[])
+
+ assert out["most_central_file"]["path"] == "src/latest/api.py"
+ assert out["most_central_file"]["import_count"] == 90
diff --git a/tests/unit/test_no_test_path_copies.py b/tests/unit/test_no_test_path_copies.py
index 742d3f2d7..b971e791e 100644
--- a/tests/unit/test_no_test_path_copies.py
+++ b/tests/unit/test_no_test_path_copies.py
@@ -1,20 +1,21 @@
-"""No thirteenth copy of "is this path a test?" (#1103).
+"""No fifteenth copy of "is this path a test?" (#1103).
-An architecture check rather than a behaviour one: it fails when a new private
+An architecture check rather than a behaviour one: it fails when a new
test-path predicate appears anywhere outside :mod:`repowise.core.test_paths`.
-Twelve of these existed and disagreed on five real layouts, and two of them
+Fourteen of these existed and disagreed on five real layouts, and two of them
carried docstrings claiming to mirror implementations they had already drifted
-from, so a reviewer noticing the thirteenth is not a plan.
+from, so a reviewer noticing the fifteenth is not a plan.
-The remaining entries in ``_KNOWN`` are the ones still to be converted. The list
-only ever shrinks: deleting a copy means deleting its line here, and adding one
-means this test tells you to use the shared module instead.
+``_KNOWN`` holds the call sites that answer a *narrower* question on purpose,
+each with its reason. The list only ever shrinks; adding a plain copy means this
+test tells you to use the shared module instead.
Ceiling: this matches on names, so a predicate called something the lists below
-do not know stays invisible. It catches the shapes that actually recurred in this
-codebase, which is what the twelve copies were named. The corpus in
-``test_test_paths.py`` is what catches a *wrong* answer; this only catches a
-second implementation of the question.
+do not know stays invisible — which is exactly how the two entries in ``_KNOWN``
+went unnoticed until someone read for them. It catches the shapes that actually
+recurred here, and a wrapper that calls the shared module is not one of them.
+The corpus in ``test_test_paths.py`` is what catches a *wrong* answer; this only
+catches a second implementation of the question.
"""
from __future__ import annotations
@@ -34,6 +35,11 @@ _PREDICATE_NAMES = (
"_looks_like_test_path",
"_is_test_file_name",
"_is_test_dir_path",
+ # Public spellings too. These shadow the shared module's own exported name,
+ # which is the worst case for a wrong import, and listing only the private
+ # forms is what kept the two in `_KNOWN` below invisible until review.
+ "is_test_file",
+ "is_test_path",
)
# Module-level constants holding test-path patterns. The `_TEST_PATH_TOKENS`
@@ -47,21 +53,35 @@ _PREDICATE_CONSTANTS = (
"_TEST_FILE_PREFIXES",
"_TEST_DIR_FRAGMENTS",
"_TEST_SUFFIXES",
+ "_TEST_DIRS",
+ "_TEST_DIR_SEGMENTS",
+ "_TEST_FILE_RE",
+ "_TEST_FILE_PATTERNS",
)
-# Copies that still exist, with the reason each is still here. Shrink, never grow.
+# Copies that still exist, with the reason each is still here. Shrink, never
+# grow — an entry needs the reason it is exempt written in the code it exempts.
+#
+# Both entries are deliberate divergences rather than unconverted copies: each
+# answers a narrower question than the shared rules, with the reason in a
+# comment above it. They became visible only when the public name shapes were
+# added to `_PREDICATE_NAMES`, which is the point of recording them.
#
# Note what is deliberately *not* listed: `communities._is_test_node` and
# `move_method._file_is_test` read the flag off a graph node and fall back to the
# shared module. That is the pattern to copy, not a copy to remove.
_KNOWN: frozenset[str] = frozenset(
{
- # The MCP tools and the stats router, converted next. Each re-derives
- # from a substring token list weaker than the shared rules.
- "packages/server/src/repowise/server/mcp_server/tool_search.py",
- "packages/server/src/repowise/server/mcp_server/tool_search_symbols.py",
- "packages/server/src/repowise/server/mcp_server/_answer_pipeline.py",
- "packages/server/src/repowise/server/routers/stats.py",
+ # Excludes bare `test/` on purpose: `django/test/` and `flask/testing.py`
+ # are shipped test-*framework* code, and counting fixes to them would
+ # inflate every downstream repo's defect count. Also exempts
+ # config-shaped names, because fixing `vitest.config.ts` is a toolchain
+ # fix rather than a defect.
+ "packages/core/src/repowise/core/ingestion/git_indexer/fix_shape.py",
+ # Excludes singular `test/`, `spec/` and `e2e/` on purpose: a route
+ # handler under an OpenAPI `spec/` is a real service contract, and
+ # over-excluding drops it from the workspace contract map entirely.
+ "packages/core/src/repowise/core/workspace/extractors/base.py",
}
)
@@ -71,6 +91,26 @@ _PACKAGES = pathlib.Path(__file__).resolve().parents[2] / "packages"
_HOME = "packages/core/src/repowise/core/test_paths.py"
+# The shared answers. A function that calls one of these is a wrapper around
+# the single home, not a second implementation of it.
+_SHARED = frozenset({"is_test_path", "is_test_support_path", "is_test_related_path"})
+
+
+def _delegates(fn: ast.FunctionDef | ast.AsyncFunctionDef) -> bool:
+ """Whether *fn* answers by calling the shared module rather than re-deriving.
+
+ ``coverage.detector.is_test_file`` adds a source-content branch on top of
+ the shared rules, and ``communities._is_test_node`` falls back to them. Both
+ are the pattern to copy. Only a body that never reaches the shared module is
+ a copy.
+ """
+ return any(
+ (isinstance(node, ast.Name) and node.id in _SHARED)
+ or (isinstance(node, ast.Attribute) and node.attr in _SHARED)
+ for node in ast.walk(fn)
+ )
+
+
def _offenders() -> dict[str, list[str]]:
"""Map of repo-relative path -> the predicate names/constants it defines."""
found: dict[str, list[str]] = {}
@@ -89,6 +129,7 @@ def _offenders() -> dict[str, list[str]]:
if (
isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef)
and node.name in _PREDICATE_NAMES
+ and not _delegates(node)
):
hits.append(node.name)
elif isinstance(node, ast.Assign):
@@ -133,6 +174,17 @@ def test_known_copies_still_exist() -> None:
)
+def test_a_wrapper_is_not_a_copy() -> None:
+ """The check must not push call sites into re-deriving to dodge it."""
+ wrapper = ast.parse(
+ "def _is_test_path(p):\n"
+ " return is_test_related_path(p) or p.endswith('.fixture')\n"
+ ).body[0]
+ copy = ast.parse("def _is_test_path(p):\n return '/tests/' in p\n").body[0]
+ assert _delegates(wrapper)
+ assert not _delegates(copy)
+
+
@pytest.mark.parametrize("name", ["is_test_path", "is_test_support_path", "is_test_related_path"])
def test_shared_module_exports_the_replacements(name: str) -> None:
assert callable(getattr(test_paths, name))
diff --git a/tests/unit/test_test_paths.py b/tests/unit/test_test_paths.py
index ef65564ae..776d08700 100644
--- a/tests/unit/test_test_paths.py
+++ b/tests/unit/test_test_paths.py
@@ -25,6 +25,9 @@ _CORPUS: tuple[tuple[str, str | None, str], ...] = (
("conftest.py", None, "support"), # #1103: four said test, five said not
("tests/conftest.py", None, "support"),
("tests/factories/user.py", None, "support"),
+ # a package marker carries no test itself, but it is not production code
+ # either, and the tree it sits in settles it
+ ("tests/unit/__init__.py", None, "test"),
("tests/fixtures/repo/vitest.config.mts", None, "support"),
# django: a per-app suite module, which no prefix/suffix rule catches
("myapp/tests.py", None, "test"),
@@ -65,6 +68,11 @@ _CORPUS: tuple[tuple[str, str | None, str], ...] = (
("lib/contest.py", None, ""),
("src/testing/helpers.py", None, ""),
("src/testing_utils.py", None, ""),
+ # the same word mid-stem, which is how the MCP tools' `test_` substring
+ # token demoted this repo's own source in search results
+ ("src/analysis/missing_test_signal.py", None, ""),
+ ("src/ingestion/pytest_hints.py", None, ""),
+ ("alembic/versions/0036_test_coverage.py", None, ""),
("src/manifest/loader.py", None, ""),
("src/helpers/fmt.py", None, ""),
("src/fixtures/data.py", None, ""),