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
refactor(core): one home for "is this path a test?" (#1112)
Raghav Chamadiya82cd55b0fc6a
diff --git a/packages/core/src/repowise/core/analysis/communities.py b/packages/core/src/repowise/core/analysis/communities.pyindex d607c1c6d..c08c05067 100644--- a/packages/core/src/repowise/core/analysis/communities.py+++ b/packages/core/src/repowise/core/analysis/communities.py@@ -12,7 +12,6 @@ from __future__ import annotationsimport contextlibimport inspectimport io-import reimport sysfrom collections import Counterfrom dataclasses import dataclass, field@@ -22,6 +21,7 @@ import networkx as nximport structlogfrom repowise.core.analysis.kg_curation import GENERIC_ORG_SEGMENTS, dominant_segments+from repowise.core.test_paths import is_test_related_pathlog = structlog.get_logger(__name__)@@ -386,15 +386,18 @@ def _dominant_language(# Test / production separation# ----------------------------------------------------------------------------_TEST_PATH_RE = re.compile(- r"(test[s_/]|_test\.|\.test\.|\.spec\.|__tests__|conftest|fixture[s]?[/.])",- re.IGNORECASE,-)-+def _is_test_node(node_id: str, data: dict) -> bool:+ """Whether a graph file node is test material.-def _is_test_file(path: str) -> bool:- """True if *path* looks like a test, fixture, or spec file."""- return bool(_TEST_PATH_RE.search(path))+ Reads the flag ingestion stored on the node, which was decided with the+ file's language in hand. The path rules are the fallback for a node that+ predates the flag. The regex this replaced matched ``test[s_/]`` unanchored,+ so ``src/latest/api.py`` and ``protest/main.py`` were pulled out of+ community assignment as tests (#1103).+ """+ if "is_test" in data:+ return bool(data["is_test"])+ return is_test_related_path(node_id, data.get("language"))def _assign_tests_to_communities(@@ -456,8 +459,9 @@ def detect_file_communities(# separately then assigned to the community of their most-imported# production file, preventing test directories from dominating labels# and mixing unrelated production modules.- prod_nodes = [n for n in file_nodes if not _is_test_file(n)]- test_nodes = [n for n in file_nodes if _is_test_file(n)]+ is_test = {n: _is_test_node(n, graph.nodes[n]) for n in file_nodes}+ prod_nodes = [n for n in file_nodes if not is_test[n]]+ test_nodes = [n for n in file_nodes if is_test[n]]# Build undirected subgraph from production files + relevant edgesundirected = nx.Graph()diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/coverage_gap.py b/packages/core/src/repowise/core/analysis/health/biomarkers/coverage_gap.pyindex 4510a1cc6..8fce6d53a 100644--- a/packages/core/src/repowise/core/analysis/health/biomarkers/coverage_gap.py+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/coverage_gap.py@@ -13,6 +13,7 @@ does nothing — the absence-of-coverage case is thefrom __future__ import annotations+from ....test_paths import is_test_related_pathfrom ..models import Severityfrom .base import BiomarkerResult, FileContext@@ -31,7 +32,7 @@ class CoverageGapDetector:return []if ctx.total_coverable_lines <= 0:return []- if _looks_like_test_path(ctx.file_path):+ if is_test_related_path(ctx.file_path, ctx.language):return []cov = ctx.line_coverage_pct@@ -71,30 +72,4 @@ class CoverageGapDetector:]-def _looks_like_test_path(path: str) -> bool:- p = path.replace("\\", "/").lower()- return (- "/test/" in p- or "/tests/" in p- or "/__tests__/" in p- or p.startswith(("test/", "tests/", "__tests__/"))- or p.endswith(- (- "_test.py",- "_test.go",- ".test.ts",- ".test.tsx",- ".test.js",- ".test.mts",- ".test.cts",- ".spec.ts",- ".spec.js",- ".spec.mts",- ".spec.cts",- )- )- or p.rsplit("/", 1)[-1].startswith("test_")- )--BIOMARKER = CoverageGapDetector()diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/coverage_gradient.py b/packages/core/src/repowise/core/analysis/health/biomarkers/coverage_gradient.pyindex c042413f6..9378092af 100644--- a/packages/core/src/repowise/core/analysis/health/biomarkers/coverage_gradient.py+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/coverage_gradient.py@@ -27,6 +27,7 @@ the has-tests / hotspot gates.from __future__ import annotations+from ....test_paths import is_test_related_pathfrom ..models import Severityfrom .base import BiomarkerResult, FileContext@@ -43,32 +44,6 @@ _COVERAGE_HIGH = 40.0_COVERAGE_MEDIUM = 70.0-def _looks_like_test_path(path: str) -> bool:- p = path.replace("\\", "/").lower()- return (- "/test/" in p- or "/tests/" in p- or "/__tests__/" in p- or p.startswith(("test/", "tests/", "__tests__/"))- or p.endswith(- (- "_test.py",- "_test.go",- ".test.ts",- ".test.tsx",- ".test.js",- ".test.mts",- ".test.cts",- ".spec.ts",- ".spec.js",- ".spec.mts",- ".spec.cts",- )- )- or p.rsplit("/", 1)[-1].startswith("test_")- )--class CoverageGradientDetector:name = "coverage_gradient"category = "test_coverage_gradient"@@ -78,7 +53,7 @@ class CoverageGradientDetector:if cov is None:# No coverage data -> silent. Absent is not the same as uncovered.return []- if _looks_like_test_path(ctx.file_path):+ if is_test_related_path(ctx.file_path, ctx.language):return []uncovered_fraction = max(0.0, (100.0 - float(cov)) / 100.0)diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/hidden_coupling.py b/packages/core/src/repowise/core/analysis/health/biomarkers/hidden_coupling.pyindex 63f4ec755..9e1265e45 100644--- a/packages/core/src/repowise/core/analysis/health/biomarkers/hidden_coupling.py+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/hidden_coupling.py@@ -23,9 +23,9 @@ empty short-circuit is explicit so backfill behavior is testable.from __future__ import annotationsimport json-from pathlib import Pathfrom typing import Any+from ....test_paths import is_test_related_pathfrom ..models import Severityfrom .base import BiomarkerResult, FileContext@@ -42,41 +42,6 @@ _MAX_FINDINGS_PER_FILE = 3# above ``_MIN_COMMITS``), severity is capped at MEDIUM: a hint, not a verdict._MIN_CO_CHANGE_FOR_HIGH = 8-# Same conventions used by engine._has_paired_test_file. Keeping them-# inline (rather than importing) avoids a circular dependency between-# the engine and the biomarker package.-_TEST_BASENAME_PATTERNS: tuple[str, ...] = (- "test_", # prefix-)-_TEST_SUFFIXES: tuple[str, ...] = (- "_test.py",- ".test.ts",- ".test.tsx",- ".test.js",- ".test.mts",- ".test.cts",- ".spec.ts",- ".spec.js",- ".spec.mts",- ".spec.cts",- "_test.go",-)-_TEST_DIR_FRAGMENTS: tuple[str, ...] = (- "/test/",- "/tests/",- "/__tests__/",-)---def _is_test_path(path: str) -> bool:- p = path.replace("\\", "/").lower()- if any(frag in f"/{p}" for frag in _TEST_DIR_FRAGMENTS):- return True- base = Path(p).name- if base.startswith(_TEST_BASENAME_PATTERNS):- return True- return any(p.endswith(suf) for suf in _TEST_SUFFIXES)-def _parse_partners(meta: dict[str, Any]) -> dict[str, int]:raw = meta.get("co_change_partners_json")@@ -135,7 +100,7 @@ class HiddenCouplingDetector:if total_self < _MIN_COMMITS:return []- self_is_test = _is_test_path(ctx.file_path)+ self_is_test = is_test_related_path(ctx.file_path, ctx.language)graph = ctx.graph_viewcounts = ctx.repo_commit_counts or {}@@ -152,8 +117,11 @@ class HiddenCouplingDetector:correlation = co_count / denomif correlation < _MIN_CORRELATION:continue- # Skip test ↔ production pairings — expected to co-change.- if self_is_test ^ _is_test_path(partner_path):+ # Skip test ↔ production pairings — expected to co-change. The+ # partner is a bare path from the co-change record and ``graph_view``+ # exposes only ``has_edge``, so there is no node to read its stored+ # flag from and no language to pass; the path rules are all we have.+ if self_is_test ^ is_test_related_path(partner_path):continue# Skip when an explicit import edge already documents the# coupling.diff --git a/packages/core/src/repowise/core/analysis/health/coverage/detector.py b/packages/core/src/repowise/core/analysis/health/coverage/detector.pyindex 26e0cc105..4656a4a18 100644--- a/packages/core/src/repowise/core/analysis/health/coverage/detector.py+++ b/packages/core/src/repowise/core/analysis/health/coverage/detector.py@@ -21,42 +21,13 @@ from __future__ import annotationsimport refrom pathlib import Path+from ....test_paths import is_test_related_pathfrom .clover import parse_cloverfrom .cobertura import parse_coberturafrom .lcov import parse_lcovfrom .model import CoverageReportfrom .repowise_json import parse_repowise_json-# Test-file globs / suffixes — checked against POSIX-normalized paths.-_TEST_PATH_FRAGMENTS = (- "/test/",- "/tests/",- "/__tests__/",- "/spec/",- "/specs/",-)-_TEST_FILE_SUFFIXES = (- "_test.py",- "_test.go",- ".test.ts",- ".test.tsx",- ".test.js",- ".test.jsx",- ".test.mts",- ".test.cts",- ".spec.ts",- ".spec.tsx",- ".spec.js",- ".spec.jsx",- ".spec.mts",- ".spec.cts",- "_spec.rb",- "Test.java",- "Tests.java",- "Spec.scala",-)-_TEST_FILE_PREFIXES = ("test_",)-# Test framework import patterns — used when the path heuristic is# inconclusive. Detected via cheap substring scan (no tree-sitter pass)._FRAMEWORK_IMPORTS = (@@ -113,22 +84,14 @@ def parse(text: str, *, format: str | None = None) -> CoverageReport:def is_test_file(rel_path: str, source: str | None = None) -> bool:- """Heuristic — does *rel_path* look like a test file?+ """Does *rel_path* look like a test file?- *source* is an optional file body; when supplied we additionally- check for test-framework imports for files whose paths don't match- obvious conventions.+ The path rules live in :mod:`repowise.core.test_paths`, the one home for+ them (#1103). What this adds is the *source* branch: given a file body, a+ test-framework import marks a test whose path follows no convention at all,+ which no amount of path matching can tell you."""- p = rel_path.replace("\\", "/")- lower = p.lower()- base = p.rsplit("/", 1)[-1]- if any(frag in lower for frag in _TEST_PATH_FRAGMENTS):- return True- if any(lower.startswith(frag.lstrip("/")) for frag in _TEST_PATH_FRAGMENTS):- return True- if base.startswith(_TEST_FILE_PREFIXES):- return True- if any(base.endswith(sfx) for sfx in _TEST_FILE_SUFFIXES):+ if is_test_related_path(rel_path):return Trueif source:head = source[:4096]diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.pyindex 577d364dc..1166cb303 100644--- a/packages/core/src/repowise/core/analysis/health/engine.py+++ b/packages/core/src/repowise/core/analysis/health/engine.py@@ -85,27 +85,6 @@ def _log_duplication_diagnostics(report: DuplicationReport) -> None:log.debug("health_duplication_limits", **diag)-def _is_test_file(rel_path: str) -> bool:- p = rel_path.lower()- return (- "/test/" in p- or "/tests/" in p- or "/__tests__/" in p- or p.startswith("test_")- or p.endswith("_test.py")- or p.endswith(".test.ts")- or p.endswith(".test.tsx")- or p.endswith(".test.js")- or p.endswith(".test.mts")- or p.endswith(".test.cts")- or p.endswith(".spec.ts")- or p.endswith(".spec.js")- or p.endswith(".spec.mts")- or p.endswith(".spec.cts")- or p.endswith("_test.go")- )--def _fallback_module(rel_path: str) -> str | None:"""Top-level directory as a stand-in module label when no community map.@@ -846,8 +825,13 @@ class HealthAnalyzer:file_path=file_path,language=pf.file_info.language,nloc=nloc,+ # ``pf.file_info.is_test`` is the decision ingestion already made+ # for this file, with its language in hand — read it rather than+ # re-derive from the path string (#1103). The coverage check stays+ # because it also sniffs framework imports out of the source, which+ # a path cannot tell you.has_test_file=_has_paired_test_file(file_path, path_basenames)- or _is_test_file(file_path)+ or pf.file_info.is_testor _coverage_is_test_file(file_path)or fcx.has_inline_tests,module=module,diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.py b/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.pyindex c4c9bb928..f897f55c1 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.py@@ -40,6 +40,7 @@ from __future__ import annotationsfrom typing import Any+from ....test_paths import is_test_related_pathfrom .models import RefactoringContext, RefactoringSuggestionfrom .registry import RefactoringDetector, effort_bucket, register@@ -67,33 +68,6 @@ _REGION_SLACK = 1_MAX_SNIPPET_LINES = 40-def _is_test_path(path: str) -> bool:- """Conservative test-file check (mirrors the engine's ``_is_test_file``).-- Kept local so the detector stays self-contained — duplication among test- fixtures is common and low value, so test occurrences are dropped before- a suggestion is formed.- """- p = path.lower().replace("\\", "/")- return (- "/test/" in p- or "/tests/" in p- or "/__tests__/" in p- or p.rsplit("/", 1)[-1].startswith("test_")- or p.endswith("_test.py")- or p.endswith("_test.go")- or p.endswith(".test.ts")- or p.endswith(".test.tsx")- or p.endswith(".test.js")- or p.endswith(".test.mts")- or p.endswith(".test.cts")- or p.endswith(".spec.ts")- or p.endswith(".spec.js")- or p.endswith(".spec.mts")- or p.endswith(".spec.cts")- )--def _is_generated_path(path: str) -> bool:"""Non-refactorable generated/append-only code (DB migrations, vendoredbundles). Their boilerplate duplicates heavily but extracting a shared@@ -112,8 +86,14 @@ def _is_generated_path(path: str) -> bool:)-def _is_skippable_occurrence(path: str) -> bool:- return _is_test_path(path) or _is_generated_path(path)+def _is_skippable_occurrence(path: str, language: str | None = None) -> bool:+ """Duplication among test fixtures is common and low value, and a migration+ must stay self-contained, so both are dropped before a suggestion is formed.++ Test support counts as test material here: sharing a helper out of+ ``conftest.py`` is the same bad advice as sharing one out of a test.+ """+ return is_test_related_path(path, language) or _is_generated_path(path)class _Block:@@ -222,7 +202,11 @@ class ExtractHelperDetector(RefactoringDetector):# then coalesce the overlapping windows the clone detector emits for one# physical block into a single site per region (without merging, the# same import/parse block reads as "5 sites" when it is really one).- kept = [o for o in block.occurrences if not _is_skippable_occurrence(o[0])]+ # Clones are detected within a language, so every occurrence in a block+ # shares ``ctx.language`` — which the ambiguous ``spec/`` rule needs.+ kept = [+ o for o in block.occurrences if not _is_skippable_occurrence(o[0], ctx.language)+ ]occurrences = _merge_ranges_per_file(kept)if len(occurrences) < 2:return Nonediff --git a/packages/core/src/repowise/core/analysis/health/refactoring/move_method.py b/packages/core/src/repowise/core/analysis/health/refactoring/move_method.pyindex 5180611fc..bce009cbb 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/move_method.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/move_method.py@@ -30,6 +30,7 @@ from __future__ import annotationsfrom typing import Any+from ....test_paths import is_test_related_pathfrom .models import RefactoringContext, RefactoringSuggestionfrom .registry import RefactoringDetector, effort_bucket, register@@ -52,47 +53,26 @@ _MAX_TARGET_DISTANCE = 0.7_MIN_DISTANCE_MARGIN = 0.25-def _is_test_path(path: str) -> bool:- """Conservative test-file check (segment-aware).-- A test method that exercises the class under test calls into it heavily —- that reads as feature envy but is never a move target, so test files are- excluded on both ends (the method's file and the proposed destination).- Catches both a ``test/`` / ``tests/`` directory anywhere in the path- (including the first segment, e.g. Django's ``tests/app/tests.py``) and- the usual per-file naming conventions."""- p = path.lower().replace("\\", "/")- segments = p.split("/")- if any(seg in ("test", "tests", "__tests__") for seg in segments[:-1]):- return True- base = segments[-1]- return (- base in ("tests.py", "test.py", "conftest.py")- or base.startswith("test_")- or base.endswith(- (- "_test.py",- "_test.go",- ".test.ts",- ".test.tsx",- ".test.js",- ".test.mts",- ".test.cts",- ".spec.ts",- ".spec.js",- ".spec.mts",- ".spec.cts",- )- )- )--def _node(graph: Any, node_id: str) -> dict | None:if node_id not in graph:return Nonereturn graph.nodes[node_id]+def _file_is_test(graph: Any, path: str) -> bool:+ """Whether *path* is test material, preferring the flag ingestion stored.++ A move target is a different file, so its language is not ``ctx.language``+ and a path-only check cannot resolve the cases that need one (Ruby's+ ``spec/``). The graph node carries the decision made at ingestion, with the+ language in hand; the path rules are the fallback when the file has no node.+ """+ node = _node(graph, path)+ if node is not None and "is_test" in node:+ return bool(node["is_test"])+ return is_test_related_path(path)++def _owning_class_id(graph: Any, callee_id: str) -> str | None:"""The class node a callee belongs to: the method's parent class, or theclass itself for a constructor call. ``None`` for free functions and@@ -119,7 +99,7 @@ class MoveMethodDetector(RefactoringDetector):def detect(self, ctx: RefactoringContext) -> list[RefactoringSuggestion]:graph = ctx.graph- if graph is None or _is_test_path(ctx.file_path):+ if graph is None or is_test_related_path(ctx.file_path, ctx.language):return []if ctx.file_methods is not None:@@ -241,7 +221,7 @@ class MoveMethodDetector(RefactoringDetector):target_node = _node(graph, target_id) or {}target_class = target_node.get("name") or target_id.rsplit("::", 1)[-1]target_file = target_node.get("file_path")- if target_file and _is_test_path(target_file):+ if target_file and _file_is_test(graph, target_file):return None # never propose moving production code into a test classcallers = self._caller_count(graph, method_id)diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/split_file.py b/packages/core/src/repowise/core/analysis/health/refactoring/split_file.pyindex 980636ac4..c0e5645ce 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/split_file.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/split_file.py@@ -51,6 +51,7 @@ from __future__ import annotationsfrom collections import Counter, defaultdictfrom typing import Any+from ....test_paths import is_test_related_pathfrom .models import RefactoringContext, RefactoringSuggestionfrom .registry import RefactoringDetector, effort_bucket, register@@ -109,34 +110,6 @@ _SPINE_MIN_CALLERS = 3_HIGH_CONFIDENCE_MODULARITY = 0.45-def _is_test_path(path: str) -> bool:- """Conservative test-file check (mirrors the other detectors)."""- p = path.lower().replace("\\", "/")- segments = p.split("/")- if any(seg in ("test", "tests", "__tests__") for seg in segments[:-1]):- return True- base = segments[-1]- return (- base in ("tests.py", "test.py", "conftest.py")- or base.startswith("test_")- or base.endswith(- (- "_test.py",- "_test.go",- ".test.ts",- ".test.tsx",- ".test.js",- ".test.mts",- ".test.cts",- ".spec.ts",- ".spec.js",- ".spec.mts",- ".spec.cts",- )- )- )--def _is_generated_path(path: str) -> bool:"""Generated / vendored / append-only code: a migration or a barrelre-export file must stay self-contained, so it is never a split target."""@@ -155,8 +128,8 @@ def _is_generated_path(path: str) -> bool:)-def _is_skippable_path(path: str) -> bool:- return _is_test_path(path) or _is_generated_path(path)+def _is_skippable_path(path: str, language: str | None = None) -> bool:+ return is_test_related_path(path, language) or _is_generated_path(path)def _node_span(data: dict) -> int:@@ -288,7 +261,7 @@ class SplitFileDetector(RefactoringDetector):def detect(self, ctx: RefactoringContext) -> list[RefactoringSuggestion]:graph = ctx.graph- if graph is None or _is_skippable_path(ctx.file_path):+ if graph is None or _is_skippable_path(ctx.file_path, ctx.language):return []if ctx.nloc < _MIN_FILE_NLOC:return []diff --git a/packages/core/src/repowise/core/generation/layers.py b/packages/core/src/repowise/core/generation/layers.pyindex 3bc82a94e..f36fe907a 100644--- a/packages/core/src/repowise/core/generation/layers.py+++ b/packages/core/src/repowise/core/generation/layers.py@@ -26,6 +26,7 @@ from collections.abc import Iterable, Mappingfrom pathlib import PurePosixPathfrom repowise.core.ingestion.languages.registry import REGISTRY as _LANG_REGISTRY+from repowise.core.test_paths import is_test_related_path# ---------------------------------------------------------------------------# Directory → layer hint table. Each canonical layer maps to the@@ -34,8 +35,6 @@ from repowise.core.ingestion.languages.registry import REGISTRY as _LANG_REGISTR# from the deepest segment outward (the closest directory wins).# ----------------------------------------------------------------------------_TEST_DIR_TOKENS = frozenset({"__tests__", "test", "tests", "spec", "specs", "e2e"})-_LAYER_HINTS: tuple[tuple[str, frozenset[str]], ...] = (("CLI", frozenset({"cli", "commands", "cmd", "cli_commands"})),("API", frozenset({"routes", "api", "controllers", "endpoints", "handlers", "routers"})),@@ -45,7 +44,6 @@ _LAYER_HINTS: tuple[tuple[str, frozenset[str]], ...] = (("Middleware", frozenset({"middleware", "plugins", "interceptors", "guards"})),("Utility", frozenset({"utils", "helpers", "common", "shared", "tools", "util"})),("Config", frozenset({"config", "constants", "env", "settings", "conf"})),- ("Test", _TEST_DIR_TOKENS),("Types", frozenset({"types", "interfaces", "schemas", "contracts", "dtos", "typings"})),)@@ -56,89 +54,11 @@ _LAYER_HINTS: tuple[tuple[str, frozenset[str]], ...] = (# and pinned after the runtime layers instead.ADJACENT_LAYERS: frozenset[str] = frozenset({"Test"})-# Test-dir tokens that also name non-test directories in the wild ("spec(s)" =-# specifications, OpenAPI specs, language specs, …). These assign the Test-# layer only when the *file* corroborates; otherwise the scan continues-# outward to the next matching segment.-_AMBIGUOUS_TEST_DIR_TOKENS: frozenset[str] = frozenset({"spec", "specs"})--# Filename shapes that mark a test on their own (pytest, Go, Jest/Vitest,-# RSpec/minitest fixtures, …). Derived from the language registry — each-# language declares its own conventions on its spec; the union applies-# globally here (parity with the historical hard-coded tuples is pinned by-# tests/unit/ingestion/test_language_capabilities.py).-_TEST_FILE_STEM_PREFIXES = _LANG_REGISTRY.test_stem_prefixes()-_TEST_FILE_STEM_SUFFIXES = _LANG_REGISTRY.test_stem_suffixes()-_TEST_FILE_INFIXES = _LANG_REGISTRY.test_infixes()-_TEST_FIXTURE_STEMS = _LANG_REGISTRY.test_fixture_stems()--# Case-sensitive camel-boundary suffix patterns (FooTest.java, BarSpec.scala),-# keyed by extension so each language's convention applies only to its own-# files (polyglot fairness). The lowercase-boundary lookbehind keeps-# `latest.java`, `contest.cs`, and bare `Test.java` out — conventions match-# with their own case sensitivity.-_TEST_CAMEL_RES = _LANG_REGISTRY.camel_test_res_by_extension()--# Multi-segment test roots (src/it/java) and case-sensitive test-project dir-# suffixes (.NET sibling Foo.Tests/ projects). Both are unambiguous — like-# tests/ and __tests__/, they mark any file beneath them.-# A ``*``-segment form ("src/*Test") matches a Gradle source-set directory:-# the literal segment(s) match lowercased, the ``*<Suffix>`` segment matches-# the original-case dir name by proper suffix (src/jvmTest, src/commonTest,-# src/integrationTest, …).-_TEST_DIR_PATHS: tuple[tuple[str, ...], ...] = tuple(- tuple(p.split("/")) for p in _LANG_REGISTRY.test_dir_paths() if "*" not in p-)-_TEST_DIR_WILDCARDS: tuple[tuple[str, str], ...] = tuple(- (p.split("/")[0], p.split("/")[1].lstrip("*"))- for p in _LANG_REGISTRY.test_dir_paths()- if "*" in p-)-_TEST_DIR_SUFFIXES = _LANG_REGISTRY.test_dir_suffixes()-# Per-language unambiguous test-dir tokens: ruby's spec/ needs no filename-# corroboration — a Ruby file under spec/ is RSpec material whatever its-# name (support helpers, vendored fixtures).-_LANG_TEST_DIR_TOKENS = _LANG_REGISTRY.test_dir_tokens_by_language()---def _is_test_file_name(filename: str) -> bool:- """Whether *filename* alone marks a test (test_x.py, x_test.go, x.spec.ts, …)."""- name = filename.lower()- stem = PurePosixPath(name).stem- if (- stem in _TEST_FIXTURE_STEMS- or stem.startswith(_TEST_FILE_STEM_PREFIXES)- or stem.endswith(_TEST_FILE_STEM_SUFFIXES)- or any(m in name for m in _TEST_FILE_INFIXES)- ):- return True- camel_re = _TEST_CAMEL_RES.get(PurePosixPath(filename).suffix.lower())- return camel_re is not None and camel_re.search(PurePosixPath(filename).stem) is not None---def _is_test_dir_path(segments: list[str], original_segments: list[str]) -> bool:- """Whether the directory path itself is an unambiguous test root.-- *segments* are lowercased dir names, *original_segments* preserve case- for the case-sensitive project-dir suffix rule (``Foo.Tests/``).- """- for needle in _TEST_DIR_PATHS:- span = len(needle)- if span <= len(segments) and any(- tuple(segments[i : i + span]) == needle- for i in range(len(segments) - span + 1)- ):- return True- for prefix_seg, camel_sfx in _TEST_DIR_WILDCARDS:- for i in range(len(segments) - 1):- nxt = original_segments[i + 1]- if (- segments[i] == prefix_seg- and nxt.endswith(camel_sfx)- and len(nxt) > len(camel_sfx)- ):- return True- return any(seg.endswith(_TEST_DIR_SUFFIXES) for seg in original_segments)+# Every test convention this module used to carry - registry-derived filename+# shapes, camel-boundary suffixes, multi-segment roots, the ambiguous `spec/`+# rule - now lives in ``core.test_paths``, which answers the same question for+# ingestion and for the MCP tools (#1103). The table above no longer carries a+# Test row: the check runs ahead of it, so the row was unreachable.# Per-language layer hints (they fire only for files of the@@ -309,27 +229,12 @@ def infer_layer(path: str, language: str | None = None) -> str:"""original_parts = list(PurePosixPath(path).parts)parts = [s.lower() for s in original_parts]- # Original case is preserved for the case-sensitive rules (camel-suffix- # filenames, .NET ``Foo.Tests/`` project dirs).- filename = original_parts[-1] if original_parts else ""segments = parts[:-1] # drop filename- if _is_test_file_name(filename):- return "Test"-- lang_test_tokens = _LANG_TEST_DIR_TOKENS.get((language or "").lower(), frozenset())- for seg in segments:- if seg not in _TEST_DIR_TOKENS:- continue- if (- seg in _AMBIGUOUS_TEST_DIR_TOKENS- and seg not in lang_test_tokens- and not _is_test_file_name(filename)- ):- continue # "spec(s)/" without a test-shaped file: not a test root- return "Test"-- if _is_test_dir_path(segments, original_parts[:-1]):+ # Checked before the hint table below, and deliberately: that table scans+ # deepest-segment-outward, so ``tests/utils/foo.py`` would answer "Utility".+ # A test is a test wherever in the path the marker sits.+ if is_test_related_path(path, language):return "Test"# Repo-root dot-directories (.github, .agents, .claude, .vscode, …) hold@@ -358,8 +263,6 @@ def infer_layer(path: str, language: str | None = None) -> str:for i in range(len(segments) - 1, -1, -1):seg = segments[i]for layer_name, tokens in _LAYER_HINTS:- if layer_name == "Test":- continue # handled aboveif seg in tokens:return layer_nameif token_hints and seg in token_hints:diff --git a/packages/core/src/repowise/core/ingestion/graph/_edges.py b/packages/core/src/repowise/core/ingestion/graph/_edges.pyindex 06748cd3b..6629ae680 100644--- a/packages/core/src/repowise/core/ingestion/graph/_edges.py+++ b/packages/core/src/repowise/core/ingestion/graph/_edges.py@@ -96,10 +96,16 @@ class EdgesMixin:hint_source=e.hint_source,weight=e.weight,)- # Propagate test marker: if hint_source ends with ":test", tag the- # source file node as is_test so downstream consumers can filter it.- if e.hint_source and e.hint_source.endswith(":test"):- self._graph.nodes[e.source]["is_test"] = True+ # A ``:test`` hint used to set ``is_test`` on the source node. Only+ # the Rust hinter emits one, for `#[test]` / `#[cfg(test)]` markers,+ # and Rust keeps its unit tests *inside* the production file - so+ # every `src/lib.rs` with an inline `mod tests` was marked a test+ # file wholesale and dropped from dead-code analysis, the knowledge+ # graph and key-concept selection (#1103). The marker means "contains+ # tests", not "is a test": it stays recorded on this edge's+ # ``hint_source``, where it says that and nothing more. Health+ # computes the file-level version itself, from the source, as+ # ``FileContext.has_inline_tests``.if edges:self._invalidate_subgraph_caches()diff --git a/packages/core/src/repowise/core/ingestion/traverser.py b/packages/core/src/repowise/core/ingestion/traverser.pyindex baa532d55..174613b63 100644--- a/packages/core/src/repowise/core/ingestion/traverser.py+++ b/packages/core/src/repowise/core/ingestion/traverser.py@@ -21,11 +21,12 @@ import threadingfrom collections.abc import Iteratorfrom dataclasses import dataclass, fieldfrom datetime import datetime-from pathlib import Path, PurePosixPath+from pathlib import Pathimport pathspecimport structlog+from ..test_paths import is_test_related_pathfrom .languages.registry import REGISTRY as _LANG_REGISTRYfrom .models import (EXTENSION_TO_LANGUAGE,@@ -197,27 +198,9 @@ _ENTRY_POINT_NAME_SUFFIXES: tuple[str, ...] = tuple(sorted(p[1:] for p in _LANG_REGISTRY.entry_point_names() if p.startswith("*")))-# Test-file conventions, from the same registry each language declares them-# on. ``spec_`` is carried over from the rule these replaced: the registry-# has the ``_spec`` suffix and the ``spec_helper`` stem but no prefix, and-# dropping it would unclassify RSpec-style ``spec_foo.rb``.-_TEST_STEM_PREFIXES: tuple[str, ...] = tuple(- sorted({*_LANG_REGISTRY.test_stem_prefixes(), "spec_"})-)-_TEST_STEM_SUFFIXES: tuple[str, ...] = _LANG_REGISTRY.test_stem_suffixes()-_TEST_INFIXES: tuple[str, ...] = _LANG_REGISTRY.test_infixes()-_TEST_FIXTURE_STEMS: frozenset[str] = _LANG_REGISTRY.test_fixture_stems()-# Directory names that mark everything beneath them as test material.-# ``__tests__`` is the JavaScript convention and is the reason this set is-# not simply the registry's per-language tokens.-_TEST_DIR_SEGMENTS: frozenset[str] = frozenset(- {"test", "tests", "__tests__", "__test__"}- | {- token- for tokens in _LANG_REGISTRY.test_dir_tokens_by_language().values()- for token in tokens- }-)+# Test-file conventions live in ``core.test_paths`` - the same code answers the+# question at query time, so the flag stored here and the fallback the MCP+# tools use can never disagree (#1103).# Default file-size limit_DEFAULT_MAX_FILE_SIZE_BYTES: int = 500 * 1024 # 500 KB@@ -531,7 +514,7 @@ class FileTraverser:size_bytes=size_bytes,git_hash="",last_modified=datetime.fromtimestamp(stat.st_mtime),- is_test=_is_test_file(rel_str, filename),+ is_test=is_test_related_path(rel_str, language),is_config=_is_config_file(language),is_api_contract=_is_api_contract(abs_path, language),is_entry_point=(@@ -671,32 +654,6 @@ def _is_generated(abs_path: Path) -> bool:return False-def _is_test_file(rel_path: str, filename: str) -> bool:- """Whether *rel_path* is test material, by directory or by filename.-- Conventions come from the language registry, which is where each- language already declares them, rather than from a second hard-coded- list. The two rules this replaced knew only ``test_x`` / ``x_test`` and a- slash-delimited ``/tests/`` substring, so both halves of the JavaScript- convention (``__tests__/`` directories and ``x.test.ts`` filenames) and- every root-level suite (``tests/conftest.py``) read as production code to- everything downstream of this flag.- """- name = filename.lower()- stem = PurePosixPath(name).stem- if (- stem in _TEST_FIXTURE_STEMS- or stem.startswith(_TEST_STEM_PREFIXES)- or stem.endswith(_TEST_STEM_SUFFIXES)- or any(infix in name for infix in _TEST_INFIXES)- ):- return True- # Directory segments, including the first: a repository-root ``tests/``- # is the usual layout, not the exception.- segments = rel_path.lower().replace("\\", "/").split("/")[:-1]- return any(seg in _TEST_DIR_SEGMENTS for seg in segments)--def _is_config_file(language: LanguageTag) -> bool:return language in ("yaml", "toml", "json", "dockerfile", "makefile")diff --git a/packages/core/src/repowise/core/test_paths.py b/packages/core/src/repowise/core/test_paths.pynew file mode 100644index 000000000..8e5f833f2--- /dev/null+++ b/packages/core/src/repowise/core/test_paths.py@@ -0,0 +1,267 @@+"""Single home for "is this path test material?".++Fourteen implementations of this question used to live across ingestion,+analysis, generation and the server, and they disagreed on real layouts+(#1103). This module is the one answer. It sits beside :mod:`exclusion` for the+same reason that one does: the question is asked both during ingestion and at+query time, so it cannot live under ``ingestion/`` without the server importing+across a layer to reach it.++**The decision is made once, at ingestion.** :func:`is_test_related_path` is+what stamps ``FileInfo.is_test`` (``ingestion/traverser.py``), which is carried+onto graph nodes and persisted as ``GraphNode.is_test``. Any caller holding a+``FileInfo`` or a graph node should read that flag rather than call back in+here. The functions below are for callers that genuinely only have a path+string, chiefly the MCP tools ranking wiki-page rows: they exist so that the+fallback and the stored flag can never disagree, because they are the same code.++**Test versus test support.** ``conftest.py`` is not a test — pytest collects no+tests from it, it is a per-directory fixture plugin. But a refactoring detector+that skips tests wants to skip it too, while search should still surface it when+someone asks where the fixtures are. So the two are separate questions:+:func:`is_test_path` for tests, :func:`is_test_support_path` for the+infrastructure around them, and :func:`is_test_related_path` for the callers+that mean "either". Pick deliberately at the call site; do not reach for+``is_test_related_path`` by default.++**Conventions are data, not code.** Every pattern comes from the language+registry, where each language already declares its own conventions on its spec.+Adding an ecosystem is a row on a spec, not an edit here. That is also why+``.test.mts``/``.spec.cts`` need no mention anywhere: ``.test.`` and ``.spec.``+are registry *infixes*, so every extension that will ever exist is covered by+construction. The suffix-list copies that had to be edited per extension are+what let #288 regress twice.++**Matching is anchored.** Directory rules compare whole path segments and+filename rules compare stems, never substrings. An unanchored ``test[s_/]``+substring is what made ``src/latest/api.py`` and ``protest/main.py`` read as+tests to community assignment.+"""++from __future__ import annotations++import re+from dataclasses import dataclass+from functools import cache+from pathlib import PurePosixPath++# Directory segments that mark every file beneath them as test material,+# whatever the filename. ``__test__`` is the Jest variant of ``__tests__``.+_TEST_DIR_TOKENS: frozenset[str] = frozenset({"test", "tests", "__tests__", "__test__", "e2e"})++# Tokens that also name non-test directories in the wild: "spec(s)" is as often+# OpenAPI/language specifications as it is RSpec. These count only when the+# filename corroborates, or when the file's own language declares the token+# (Ruby's spec/ needs no corroboration - a Ruby file under spec/ is RSpec+# material whatever its name).+_AMBIGUOUS_TEST_DIR_TOKENS: frozenset[str] = frozenset({"spec", "specs"})++# A whole module named for testing and nothing else: Django's per-app+# ``myapp/tests.py``, which no prefix/suffix/infix rule catches. Matched against+# the filename's own case, deliberately: a lowercase ``tests.py`` is the+# snake_case-module convention, while a capitalised ``Test.java`` is a class+# named Test and may be production code - which is why the registry's camel rule+# requires a lowercase boundary and excludes it. Ceiling: if one language ever+# needs to disagree, this moves onto the language specs like everything else here.+_TEST_EXACT_STEMS: frozenset[str] = frozenset({"test", "tests"})++# Directories that hold the scaffolding rather than the tests. These only count+# inside a test tree: ``src/helpers/`` is production code, ``tests/helpers/`` is+# not. A test-shaped filename still wins over them, so+# ``tests/helpers/test_builders.py`` stays a test.+_SUPPORT_DIR_TOKENS: frozenset[str] = frozenset(+ {"fixtures", "factories", "support", "helpers", "mocks", "__mocks__"}+)+++@dataclass(frozen=True, slots=True)+class _Conventions:+ """The registry-declared halves of the rules, resolved once."""++ stem_prefixes: tuple[str, ...]+ stem_suffixes: tuple[str, ...]+ infixes: tuple[str, ...]+ camel_res: dict[str, re.Pattern[str]]+ support_stems: frozenset[str]+ support_camel_res: dict[str, re.Pattern[str]]+ dir_paths: tuple[tuple[str, ...], ...]+ dir_wildcards: tuple[tuple[str, str], ...]+ dir_suffixes: tuple[str, ...]+ lang_dir_tokens: dict[str, frozenset[str]]+++@cache+def _conventions() -> _Conventions:+ """Resolve the language registry on first use, not at import.++ The registry lives under ``ingestion/``, and importing anything from there+ runs ``ingestion/__init__``, which imports the traverser, which imports this+ module. Deferring the import breaks that cycle and costs one branch per+ call. ``spec_`` is carried over from the rule the traverser used to hold:+ the registry declares the ``_spec`` suffix and the ``spec_helper`` stem but+ no prefix, and dropping it would unclassify RSpec-style ``spec_foo.rb``.+ """+ from .ingestion.languages.registry import REGISTRY++ return _Conventions(+ stem_prefixes=tuple(sorted({*REGISTRY.test_stem_prefixes(), "spec_"})),+ stem_suffixes=REGISTRY.test_stem_suffixes(),+ infixes=REGISTRY.test_infixes(),+ camel_res=REGISTRY.camel_test_res_by_extension(),+ support_stems=REGISTRY.test_fixture_stems(),+ support_camel_res=REGISTRY.camel_fixture_res_by_extension(),+ # Multi-segment test roots (src/test/java, src/it/scala) and the+ # ``*``-segment Gradle source-set form (src/*Test matches src/jvmTest).+ dir_paths=tuple(tuple(p.split("/")) for p in REGISTRY.test_dir_paths() if "*" not in p),+ dir_wildcards=tuple(+ (p.split("/")[0], p.split("/")[1].lstrip("*"))+ for p in REGISTRY.test_dir_paths()+ if "*" in p+ ),+ # Case-sensitive .NET sibling project dirs (Foo.Tests/, Foo.Specs/).+ dir_suffixes=REGISTRY.test_dir_suffixes(),+ lang_dir_tokens=REGISTRY.test_dir_tokens_by_language(),+ )+++def _parts(path: str) -> tuple[list[str], list[str]]:+ """Original-case and lowercased path segments, filename last.++ Original case is preserved because two rules are deliberately+ case-sensitive: camel-boundary filenames (``FooTest.java``) and .NET+ project dirs (``Foo.Tests/``).+ """+ original = list(PurePosixPath(path.replace("\\", "/")).parts)+ return original, [seg.lower() for seg in original]+++def _is_test_name(filename: str) -> bool:+ """Whether the filename alone marks a test (test_x.py, x_test.go, x.spec.ts)."""+ if not filename:+ return False+ rules = _conventions()+ if PurePosixPath(filename).stem in _TEST_EXACT_STEMS:+ return True+ lowered = filename.lower()+ stem = PurePosixPath(lowered).stem+ if (+ stem.startswith(rules.stem_prefixes)+ or stem.endswith(rules.stem_suffixes)+ or any(infix in lowered for infix in rules.infixes)+ ):+ return True+ camel_re = rules.camel_res.get(PurePosixPath(lowered).suffix)+ return camel_re is not None and camel_re.search(PurePosixPath(filename).stem) is not None+++def _is_support_name(filename: str) -> bool:+ """Whether the filename marks test support (conftest.py, FooFixtures.java)."""+ if not filename:+ return False+ rules = _conventions()+ lowered = filename.lower()+ if PurePosixPath(lowered).stem in rules.support_stems:+ return True+ camel_re = rules.support_camel_res.get(PurePosixPath(lowered).suffix)+ return camel_re is not None and camel_re.search(PurePosixPath(filename).stem) is not None+++def _is_test_dir(+ segments: list[str], original: list[str], filename: str, language: str | None+) -> bool:+ """Whether any directory segment marks this path as sitting in a test tree."""+ rules = _conventions()+ lang_tokens = rules.lang_dir_tokens.get((language or "").lower(), frozenset())+ # ``spec/`` needs corroboration from somewhere: the language declaring the+ # token, a test- or support-shaped filename, or a scaffolding dir beneath it+ # (``spec/support/helper.rb`` is RSpec whatever the filename says, and+ # path-only callers have no language to go on).+ corroborated = (+ _is_test_name(filename)+ or _is_support_name(filename)+ or any(seg in _SUPPORT_DIR_TOKENS for seg in segments)+ )+ for seg in segments:+ if seg in _TEST_DIR_TOKENS:+ return True+ if seg in _AMBIGUOUS_TEST_DIR_TOKENS and (seg in lang_tokens or corroborated):+ return True++ for needle in rules.dir_paths:+ span = len(needle)+ if span <= len(segments) and any(+ tuple(segments[i : i + span]) == needle for i in range(len(segments) - span + 1)+ ):+ return True++ for prefix_seg, camel_suffix in rules.dir_wildcards:+ for i in range(len(segments) - 1):+ nxt = original[i + 1]+ if (+ segments[i] == prefix_seg+ and nxt.endswith(camel_suffix)+ and len(nxt) > len(camel_suffix)+ ):+ return True++ return any(seg.endswith(rules.dir_suffixes) for seg in original)+++def _classify(path: str, language: str | None) -> str:+ """``"test"``, ``"support"``, or ``""`` for production code.++ One traversal, so the two public predicates cannot disagree with each other+ the way the copies they replace disagreed.+ """+ original, lowered = _parts(path)+ if not original:+ return ""+ filename = original[-1]+ segments, original_segments = lowered[:-1], original[:-1]++ # A name that says "support" settles it wherever the file sits: conftest.py+ # at the repo root is still a fixture plugin.+ if _is_support_name(filename):+ return "support"++ named_test = _is_test_name(filename)+ if not named_test and not _is_test_dir(segments, original_segments, filename, language):+ return ""++ # Inside test material. A test-shaped filename wins; otherwise a+ # scaffolding directory demotes it to support.+ if not named_test and any(seg in _SUPPORT_DIR_TOKENS for seg in segments):+ return "support"+ return "test"+++def is_test_path(path: str, language: str | None = None) -> bool:+ """Whether *path* is a test.++ Test *support* (``conftest.py``, ``tests/factories/user.py``) is+ deliberately not a test here - see :func:`is_test_support_path`. Pass+ *language* when it is known: it decides the ambiguous ``spec/`` case, which+ is RSpec for Ruby and a specification folder for everything else.+ """+ return _classify(path, language) == "test"+++def is_test_support_path(path: str, language: str | None = None) -> bool:+ """Whether *path* is test infrastructure rather than a test.++ ``conftest.py``, ``spec_helper.rb``, ``FooFixtures.java``, and the+ scaffolding directories inside a test tree (``tests/factories/user.py``).+ Never true at the same time as :func:`is_test_path`.+ """+ return _classify(path, language) == "support"+++def is_test_related_path(path: str, language: str | None = None) -> bool:+ """Whether *path* is a test **or** test support.++ This is what stamps ``FileInfo.is_test`` at ingestion, and what callers+ should use when they mean "not production code" - a refactoring detector+ skipping files, a health biomarker exempting them. Callers that rank or+ search should prefer :func:`is_test_path`, so fixtures stay findable.+ """+ return _classify(path, language) != ""diff --git a/tests/unit/generation/test_layers.py b/tests/unit/generation/test_layers.pyindex 24dd49414..52649c31d 100644--- a/tests/unit/generation/test_layers.py+++ b/tests/unit/generation/test_layers.py@@ -68,6 +68,16 @@ def test_infer_layer_colocated_test_files_are_test():assert infer_layer("rack-protection/spec/spec_helper.rb") == "Test"+def test_infer_layer_bare_suite_module_is_test():+ # Django's per-app suite: a module named exactly tests.py, outside any test+ # directory. No prefix/suffix/infix rule catches it, so it read as+ # production code until the conventions were consolidated (#1103).+ assert infer_layer("myapp/tests.py") == "Test"+ assert infer_layer("myapp/test.py") == "Test"+ # ...but a capitalised Test.java is a class named Test, which may not be one.+ assert infer_layer("src/main/java/Test.java") != "Test"++def test_infer_layer_ambiguous_spec_dir_needs_language_corroboration():# Ruby declares spec/ as an unambiguous test-dir token: a Ruby file under# spec/ is RSpec material whatever its name, so config.ru is Test only whendiff --git a/tests/unit/health/test_file_nloc.py b/tests/unit/health/test_file_nloc.pyindex 1155a72dc..645a39832 100644--- a/tests/unit/health/test_file_nloc.py+++ b/tests/unit/health/test_file_nloc.py@@ -82,7 +82,9 @@ def test_health_metric_nloc_uses_file_nloc():pytest.skip("javascript tree-sitter pack missing")pf = SimpleNamespace(- file_info=SimpleNamespace(path="src/route.js", language="javascript", abs_path=str(p)),+ file_info=SimpleNamespace(+ path="src/route.js", language="javascript", abs_path=str(p), is_test=False+ ),symbols=[],)metric, _, _ = HealthAnalyzer(graph=None)._evaluate_file(diff --git a/tests/unit/health/test_hidden_coupling.py b/tests/unit/health/test_hidden_coupling.pyindex ce9883682..e7cb4710b 100644--- a/tests/unit/health/test_hidden_coupling.py+++ b/tests/unit/health/test_hidden_coupling.py@@ -140,6 +140,38 @@ def test_test_to_production_pair_is_filtered():assert HiddenCouplingDetector().detect(ctx) == []+def test_test_support_is_test_material_when_paired_with_production():+ """``conftest.py`` against a production file is an expected test/production+ pairing, so it is filtered like any test would be.++ Both ends go through the one shared classifier, which counts fixture plugins+ as test material (#1103). Two *test-material* files are a different case and+ still score — the rule only skips the asymmetric pairing.+ """+ ctx = _ctx(+ "tests/conftest.py",+ partners={"src/cart.py": 18},+ self_commits=20,+ repo_commits={"src/cart.py": 22},+ )+ assert HiddenCouplingDetector().detect(ctx) == []+++def test_production_path_containing_the_word_test_is_not_test_material():+ """``src/latest/`` is production on both ends, so the pair is still scored.++ An unanchored ``test[s_/]`` match would classify ``src/latest/api.py`` as a+ test and filter this pair away as an expected test/production pairing.+ """+ ctx = _ctx(+ "src/latest/api.py",+ partners={"src/billing.py": 18},+ self_commits=20,+ repo_commits={"src/billing.py": 22},+ )+ assert HiddenCouplingDetector().detect(ctx) != []++def test_findings_capped_at_top_three_partners():partners = {"src/a.py": 18,diff --git a/tests/unit/health/test_mts_cts_test_classification.py b/tests/unit/health/test_mts_cts_test_classification.pyindex 4656b2b5b..af6eb2105 100644--- a/tests/unit/health/test_mts_cts_test_classification.py+++ b/tests/unit/health/test_mts_cts_test_classification.py@@ -1,90 +1,16 @@-"""`.mts`/`.cts` test files must be classified as tests across health logic (#288).+"""A source file's *paired* test must be found for `.mts`/`.cts` sources (#288).-The original version of this file asserted on four implementations, one test-function each. Two further copies of the same predicate existed at the time and-were not listed, so they never received the fix: ``coverage_gradient`` and-``move_method`` still read ``foo.test.mts`` as production code. The matrix below-covers every reachable implementation instead, so a copy that is added or edited-without the `.mts`/`.cts` conventions fails here rather than in a user's repo.--New implementations still have to be added to ``_IMPLEMENTATIONS`` by hand, which-is the limit of this approach and the reason #1103 exists.+This is a different question from "is this path a test?" — that one now has a+single implementation and a single corpus in ``tests/unit/test_test_paths.py``.+What remains here is the pairing rule: given ``src/foo.mts``, is there a+``src/foo.test.mts`` beside it? The per-implementation matrix this file used to+carry is gone with the implementations it named (#1103)."""from __future__ import annotations-from collections.abc import Callable--import pytest--from repowise.core.analysis.health.biomarkers.coverage_gap import (- _looks_like_test_path as _coverage_gap_looks_like_test_path,-)-from repowise.core.analysis.health.biomarkers.coverage_gradient import (- _looks_like_test_path as _coverage_gradient_looks_like_test_path,-)-from repowise.core.analysis.health.biomarkers.hidden_coupling import (- _is_test_path as _coupling_is_test_path,-)-from repowise.core.analysis.health.coverage import is_test_file, paired_test_file-from repowise.core.analysis.health.engine import (- _has_paired_test_file,- _path_basenames,-)-from repowise.core.analysis.health.engine import (- _is_test_file as _engine_is_test_file,-)-from repowise.core.analysis.health.refactoring.extract_helper import (- _is_test_path as _extract_helper_is_test_path,-)-from repowise.core.analysis.health.refactoring.move_method import (- _is_test_path as _move_method_is_test_path,-)-from repowise.core.analysis.health.refactoring.split_file import (- _is_test_path as _split_file_is_test_path,-)--# Every implementation of "is this path a test?" reachable from health logic.-# Consolidating them is #1103; until then they all have to agree here.-_IMPLEMENTATIONS: tuple[tuple[str, Callable[[str], bool]], ...] = (- ("engine", _engine_is_test_file),- ("coverage_detector", is_test_file),- ("hidden_coupling", _coupling_is_test_path),- ("coverage_gap", _coverage_gap_looks_like_test_path),- ("coverage_gradient", _coverage_gradient_looks_like_test_path),- ("split_file", _split_file_is_test_path),- ("move_method", _move_method_is_test_path),- ("extract_helper", _extract_helper_is_test_path),-)--_MTS_CTS_TEST_PATHS = (- "src/foo.test.mts",- "src/foo.test.cts",- "src/foo.spec.mts",- "src/foo.spec.cts",-)--# Same extensions, production files: the suffix has to be the whole convention,-# not a substring, or `.mts` sources get exempted from coverage scoring wholesale.-_MTS_CTS_PRODUCTION_PATHS = (- "src/foo.mts",- "src/foo.cts",- "src/testable.mts",-)--[email protected]("path", _MTS_CTS_TEST_PATHS)[email protected](("name", "is_test"), _IMPLEMENTATIONS, ids=lambda v: v)-def test_mts_cts_paths_are_tests(name: str, is_test: Callable[[str], bool], path: str) -> None:- assert is_test(path), f"{name} does not classify {path} as a test"--[email protected]("path", _MTS_CTS_PRODUCTION_PATHS)[email protected](("name", "is_test"), _IMPLEMENTATIONS, ids=lambda v: v)-def test_mts_cts_production_paths_are_not_tests(- name: str, is_test: Callable[[str], bool], path: str-) -> None:- assert not is_test(path), f"{name} wrongly classifies {path} as a test"+from repowise.core.analysis.health.coverage import paired_test_file+from repowise.core.analysis.health.engine import _has_paired_test_file, _path_basenamesdef test_paired_test_file_finds_mts_cts() -> None:diff --git a/tests/unit/health/test_refactoring_extract_helper.py b/tests/unit/health/test_refactoring_extract_helper.pyindex 80db015d2..1440a8567 100644--- a/tests/unit/health/test_refactoring_extract_helper.py+++ b/tests/unit/health/test_refactoring_extract_helper.py@@ -233,6 +233,28 @@ def test_test_file_occurrences_dropped():] == []+def test_test_support_occurrences_dropped():+ # Extracting a shared helper out of conftest.py is the same bad advice as+ # extracting one out of a test, so support counts as test material (#1103).+ pair = _pair("pkg/a.py", "tests/conftest.py", 10, 25, 40, 55)+ assert [+ s+ for s in detect_refactorings(_ctx("pkg/a.py", [pair]))+ if s.refactoring_type == "extract_helper"+ ] == []+++def test_production_path_containing_the_word_test_is_kept():+ # `src/latest/` is production: an unanchored match would drop this+ # occurrence and collapse a real two-site clone to one.+ pair = _pair("pkg/a.py", "src/latest/api.py", 10, 25, 40, 55)+ assert [+ s+ for s in detect_refactorings(_ctx("pkg/a.py", [pair]))+ if s.refactoring_type == "extract_helper"+ ] != []++def test_test_file_dropped_but_real_sites_kept():clones = [_pair("pkg/a.py", "pkg/b.py", 10, 25, 40, 55),diff --git a/tests/unit/health/test_severity_overrides_integration.py b/tests/unit/health/test_severity_overrides_integration.pyindex 90e16fce7..088086933 100644--- a/tests/unit/health/test_severity_overrides_integration.py+++ b/tests/unit/health/test_severity_overrides_integration.py@@ -50,7 +50,10 @@ def _evaluate(severity_overrides):pytest.skip("python tree-sitter pack missing")pf = SimpleNamespace(file_info=SimpleNamespace(- path="src/tangled.py", language="python", abs_path="/tmp/tangled.py"+ path="src/tangled.py",+ language="python",+ abs_path="/tmp/tangled.py",+ is_test=False,),symbols=[],)diff --git a/tests/unit/ingestion/test_graph.py b/tests/unit/ingestion/test_graph.pyindex e36c5f9d1..6aef1af17 100644--- a/tests/unit/ingestion/test_graph.py+++ b/tests/unit/ingestion/test_graph.py@@ -979,3 +979,36 @@ class TestDynamicEdgeExcludeFilter:gb._graph.add_node("src/main.py")gb.add_dynamic_edges([self._edge("src/utils.py")])assert "src/utils.py" in gb._graph+++class TestInlineTestHintDoesNotMarkFileAsTest:+ """A ``:test`` hint records that a file *contains* tests, not that it is one.++ Rust keeps unit tests inside the production file, so the old propagation+ marked every ``src/lib.rs`` with an inline ``mod tests`` as a test file and+ dropped it from dead-code analysis, the knowledge graph and key-concept+ selection (#1103).+ """++ def _test_edge(self, source: str):+ from repowise.core.ingestion.dynamic_hints import DynamicEdge++ return DynamicEdge(+ source=source,+ target=source,+ edge_type="dynamic_uses",+ hint_source="rust:test",+ weight=1.0,+ )++ def test_production_file_with_inline_tests_keeps_its_flag(self):+ gb = GraphBuilder("/tmp/fake")+ gb._graph.add_node("src/lib.rs", is_test=False)+ gb.add_dynamic_edges([self._test_edge("src/lib.rs")])+ assert gb._graph.nodes["src/lib.rs"]["is_test"] is False++ def test_the_hint_is_still_recorded_on_the_edge(self):+ gb = GraphBuilder("/tmp/fake")+ gb._graph.add_node("src/lib.rs", is_test=False)+ gb.add_dynamic_edges([self._test_edge("src/lib.rs")])+ assert gb._graph.edges["src/lib.rs", "src/lib.rs"]["hint_source"] == "rust:test"diff --git a/tests/unit/ingestion/test_language_capabilities.py b/tests/unit/ingestion/test_language_capabilities.pyindex 47e6fff78..7e183c4a7 100644--- a/tests/unit/ingestion/test_language_capabilities.py+++ b/tests/unit/ingestion/test_language_capabilities.py@@ -20,7 +20,6 @@ Two kinds of test live here:from __future__ import annotationsfrom repowise.core.analysis.kg_curation import _CODE_SUFFIXES-from repowise.core.generation import layersfrom repowise.core.generation.tour import _ENTRY_FILENAME_STEMS, _NON_CODE_LANGUAGESfrom repowise.core.ingestion.languages.registry import REGISTRY@@ -49,20 +48,20 @@ class TestParityGoldens:) == _ENTRY_FILENAME_STEMSdef test_test_stem_prefixes_match_historical_set(self) -> None:- assert set(layers._TEST_FILE_STEM_PREFIXES) == {"test_"}+ assert set(REGISTRY.test_stem_prefixes()) == {"test_"}def test_test_stem_suffixes_match_historical_set(self) -> None:# "_unittest" (C/C++ GoogleTest convention) was a conscious# addition to the historical {"_test", "_spec"} union.- assert set(layers._TEST_FILE_STEM_SUFFIXES) == {"_test", "_spec", "_unittest"}+ assert set(REGISTRY.test_stem_suffixes()) == {"_test", "_spec", "_unittest"}def test_test_infixes_match_historical_set(self) -> None:- assert set(layers._TEST_FILE_INFIXES) == {".test.", ".spec."}+ assert set(REGISTRY.test_infixes()) == {".test.", ".spec."}def test_test_fixture_stems_match_historical_set(self) -> None:assert frozenset({"conftest", "spec_helper", "test_helper"}- ) == layers._TEST_FIXTURE_STEMS+ ) == REGISTRY.test_fixture_stems()def test_suite_anchor_stems(self) -> None:# ruby (rspec/minitest helpers) and elixir (ExUnit'sdiff --git a/tests/unit/ingestion/test_traverser.py b/tests/unit/ingestion/test_traverser.pyindex 4bbc2e6dc..5c404ae34 100644--- a/tests/unit/ingestion/test_traverser.py+++ b/tests/unit/ingestion/test_traverser.py@@ -815,9 +815,9 @@ def test_test_files_are_recognised_including_root_level_suites(rel_path):measured on this repository, 122 test files survived into the productionset and five concept pages were nothing but tests."""- from repowise.core.ingestion.traverser import _is_test_file+ from repowise.core.test_paths import is_test_related_path- assert _is_test_file(rel_path, Path(rel_path).name)+ assert is_test_related_path(rel_path)@pytest.mark.parametrize(@@ -831,6 +831,6 @@ def test_test_files_are_recognised_including_root_level_suites(rel_path):)def test_production_paths_that_merely_contain_the_word_are_not_tests(rel_path):"""Segment match, not substring: ``contest`` and ``latest`` are not tests."""- from repowise.core.ingestion.traverser import _is_test_file+ from repowise.core.test_paths import is_test_related_path- assert not _is_test_file(rel_path, Path(rel_path).name)+ assert not is_test_related_path(rel_path)diff --git a/tests/unit/test_no_test_path_copies.py b/tests/unit/test_no_test_path_copies.pynew file mode 100644index 000000000..742d3f2d7--- /dev/null+++ b/tests/unit/test_no_test_path_copies.py@@ -0,0 +1,138 @@+"""No thirteenth copy of "is this path a test?" (#1103).++An architecture check rather than a behaviour one: it fails when a new private+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+carried docstrings claiming to mirror implementations they had already drifted+from, so a reviewer noticing the thirteenth 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.++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.+"""++from __future__ import annotations++import ast+import pathlib++import pytest++import repowise.core.test_paths as test_paths++# Function-name shapes that answer this question. Matched on the definition, so+# a helper named for something else that happens to take a path is unaffected.+_PREDICATE_NAMES = (+ "_is_test_file",+ "_is_test_path",+ "_looks_like_test_path",+ "_is_test_file_name",+ "_is_test_dir_path",+)++# Module-level constants holding test-path patterns. The `_TEST_PATH_TOKENS`+# tuple existed verbatim in three server modules at once, so a fix to one+# search path silently left the other two behind.+_PREDICATE_CONSTANTS = (+ "_TEST_PATH_TOKENS",+ "_TEST_PATH_RE",+ "_TEST_PATH_FRAGMENTS",+ "_TEST_FILE_SUFFIXES",+ "_TEST_FILE_PREFIXES",+ "_TEST_DIR_FRAGMENTS",+ "_TEST_SUFFIXES",+)++# Copies that still exist, with the reason each is still here. Shrink, never grow.+#+# 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",+ }+)++_PACKAGES = pathlib.Path(__file__).resolve().parents[2] / "packages"++# The one place these are allowed to be defined.+_HOME = "packages/core/src/repowise/core/test_paths.py"+++def _offenders() -> dict[str, list[str]]:+ """Map of repo-relative path -> the predicate names/constants it defines."""+ found: dict[str, list[str]] = {}+ for path in _PACKAGES.rglob("*.py"):+ rel = path.relative_to(_PACKAGES.parents[0]).as_posix()+ if rel == _HOME:+ continue+ try:+ tree = ast.parse(path.read_text(encoding="utf-8"))+ except (SyntaxError, UnicodeDecodeError): # not ours to police+ continue+ hits: list[str] = []+ # Whole tree, not just module level: a copy tucked inside a class body or+ # nested in a function is still a copy.+ for node in ast.walk(tree):+ if (+ isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef)+ and node.name in _PREDICATE_NAMES+ ):+ hits.append(node.name)+ elif isinstance(node, ast.Assign):+ hits.extend(+ t.id+ for t in node.targets+ if isinstance(t, ast.Name) and t.id in _PREDICATE_CONSTANTS+ )+ elif (+ isinstance(node, ast.AnnAssign)+ and isinstance(node.target, ast.Name)+ and node.target.id in _PREDICATE_CONSTANTS+ ):+ hits.append(node.target.id)+ if hits:+ found[rel] = sorted(hits)+ return found+++def test_no_new_test_path_predicates() -> None:+ offenders = {p: names for p, names in _offenders().items() if p not in _KNOWN}+ assert not offenders, (+ "New test-path predicate(s) outside repowise.core.test_paths:\n"+ + "\n".join(f" {p}: {', '.join(names)}" for p, names in sorted(offenders.items()))+ + "\n\nImport is_test_path / is_test_support_path / is_test_related_path from"+ " repowise.core.test_paths instead. If a call site genuinely needs to differ,"+ " say why in the code and add it to _KNOWN in this file."+ )+++def test_known_copies_still_exist() -> None:+ """Every allowlist entry must still be a real copy, so the list cannot rot.++ Without this, a converted call site leaves a stale exemption behind and the+ next copy added to that same file goes unnoticed.+ """+ found = _offenders()+ stale = sorted(p for p in _KNOWN if p not in found)+ assert not stale, (+ "These no longer define a test-path predicate — remove them from _KNOWN:\n"+ + "\n".join(f" {p}" for p in stale)+ )++[email protected]("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.pynew file mode 100644index 000000000..ef65564ae--- /dev/null+++ b/tests/unit/test_test_paths.py@@ -0,0 +1,119 @@+"""The one answer to "is this path a test?" (#1103).++The corpus is the point of this file. Every row is a real layout, and adding an+ecosystem means adding rows here rather than writing a new predicate somewhere+and hoping a reviewer notices. The paths that opened #1103 - the five the twelve+implementations disagreed on - are marked inline.+"""++from __future__ import annotations++import pytest++from repowise.core.test_paths import (+ is_test_path,+ is_test_related_path,+ is_test_support_path,+)++# (path, language or None, expected classification)+_CORPUS: tuple[tuple[str, str | None, str], ...] = (+ # pytest+ ("tests/test_thing.py", None, "test"),+ ("pkg/test_thing.py", None, "test"),+ ("tests/unit/health/test_engine.py", None, "test"),+ ("conftest.py", None, "support"), # #1103: four said test, five said not+ ("tests/conftest.py", None, "support"),+ ("tests/factories/user.py", None, "support"),+ ("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"),+ ("tests/app/tests.py", None, "test"), # #1103: five said test, four said not+ # go+ ("app/user_test.go", None, "test"),+ ("pkg/thing_test.go", None, "test"),+ # jest / vitest+ ("src/__tests__/x.js", None, "test"),+ ("src/components/Button.test.tsx", None, "test"),+ ("src/lib/parse.spec.ts", None, "test"),+ # the extensions #288 had to chase twice, covered here by the `.test.`+ # and `.spec.` infixes rather than by a suffix list+ ("src/foo.test.mts", None, "test"),+ ("src/foo.spec.cts", None, "test"),+ ("src/foo.mts", None, ""),+ # maven / gradle / kotlin multiplatform+ ("src/test/java/Foo.java", None, "test"),+ ("src/it/scala/FooSpec.scala", None, "test"),+ ("src/jvmTest/kotlin/A.kt", None, "test"),+ ("FooTest.java", None, "test"),+ ("src/main/java/Latest.java", None, ""),+ # .net sibling test projects+ ("Foo.Tests/Bar.cs", None, "test"),+ # rspec: `spec/` is RSpec for ruby and a specification folder otherwise+ ("spec/models/user_spec.rb", None, "test"), # #1103: one of nine said test+ ("spec/models/user.rb", "ruby", "test"),+ ("spec/models/user.rb", None, ""),+ ("spec/openapi/users.yaml", None, ""),+ ("spec/support/helper.rb", None, "support"),+ # e2e suites+ ("e2e/login.ts", None, "test"),+ # production code that merely contains the word: the unanchored+ # `test[s_/]` substring rule classified the first three as tests+ ("src/latest/api.py", None, ""), # #1103 finding 1+ ("protest/main.py", None, ""), # #1103 finding 1+ ("src/contest/rules.py", None, ""),+ ("lib/contest.py", None, ""),+ ("src/testing/helpers.py", None, ""),+ ("src/testing_utils.py", None, ""),+ ("src/manifest/loader.py", None, ""),+ ("src/helpers/fmt.py", None, ""),+ ("src/fixtures/data.py", None, ""),+)++[email protected](("path", "language", "expected"), _CORPUS, ids=lambda v: str(v))+def test_corpus(path: str, language: str | None, expected: str) -> None:+ actual = (+ "test"+ if is_test_path(path, language)+ else "support"+ if is_test_support_path(path, language)+ else ""+ )+ assert actual == expected, f"{path} (language={language}) classified {actual!r}"++[email protected](("path", "language", "expected"), _CORPUS, ids=lambda v: str(v))+def test_test_and_support_are_never_both_true(+ path: str, language: str | None, expected: str+) -> None:+ """The two questions partition test material; the copies they replace did not."""+ assert not (is_test_path(path, language) and is_test_support_path(path, language))++[email protected](("path", "language", "expected"), _CORPUS, ids=lambda v: str(v))+def test_related_is_the_union(path: str, language: str | None, expected: str) -> None:+ assert is_test_related_path(path, language) is (expected != "")++[email protected]("path", ["", ".", "/"])+def test_degenerate_paths_are_not_tests(path: str) -> None:+ assert not is_test_related_path(path)+++def test_windows_separators_match_posix() -> None:+ """Callers pass repo-relative paths from both a walk and a database row."""+ assert is_test_path("tests\\unit\\test_engine.py")+ assert is_test_support_path("tests\\conftest.py")+ assert not is_test_related_path("src\\latest\\api.py")+++def test_case_sensitive_rules_stay_case_sensitive() -> None:+ """``FooTest.java`` is a test; ``latest.java`` and bare ``Test.java`` are not.++ The camel rule needs a lowercase boundary before the suffix, which is what+ keeps every word ending in "test" out.+ """+ assert is_test_path("src/FooTest.java")+ assert not is_test_path("src/latest.java")+ assert not is_test_path("src/Test.java")