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
fix(dead-code): stop flagging internals used in their own file, files named by path, and receiver-registered functions (#2673)
Swati Ahujad06d0bdb48c5
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.pyindex ce2ea4bec..ebc7b097e 100644--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py@@ -31,6 +31,8 @@ from .constants import (_FRAMEWORK_DECORATOR_SUFFIXES,_FRAMEWORK_DECORATORS,_NEVER_PACKAGE_DIRS,+ _PURE_WRAPPER_DECORATOR_ATTRS,+ _PURE_WRAPPER_DECORATOR_MODULES,_is_fixture_path,never_flag_match,)@@ -47,7 +49,12 @@ from .file_reachability import (is_file_reachable,)from .models import DeadCodeFindingData, DeadCodeKind, DeadCodeReport-from .name_occurrences import IDENTIFIER_RE, clamp_unverified_absence+from .name_occurrences import (+ IDENTIFIER_RE,+ clamp_path_mentions,+ clamp_unverified_absence,+ drop_internals_used_in_own_file,+)from .risk_factors import (NO_GIT_SIGNAL_CONFIDENCE,RISK_CAP_CONFIDENCE,@@ -171,11 +178,13 @@ def _is_framework_registered(decorators: list[str]) -> bool:drifts between the export pass and the internals pass is a bug nobody goeslooking for.- Three spellings of one fact:+ Four spellings of one fact:* a known base name or dotted prefix (``@Component``, ``@app.route``);* a known trailing attribute, for a receiver the prefix list cannotanticipate because it is named locally (``@my_group.command``);+ * any other attribute of a receiver that is not a pure wrapper+ (``@nox.session``), see :func:`_is_receiver_registration`;* a registration verb in the final path segment. Every suffix entry beginswith a dot, so that list can only ever see a *dotted* decorator, andcelery's ``@register_drainer('eventlet')`` is bare — invisible to all of@@ -189,12 +198,40 @@ def _is_framework_registered(decorators: list[str]) -> bool:return Trueif any(b.endswith(_FRAMEWORK_DECORATOR_SUFFIXES) for b in bases):return True+ if any(_is_receiver_registration(b) for b in bases):+ return Truereturn any(segment == "register" or segment.startswith("register_")for segment in (b.rsplit(".", 1)[-1] for b in bases))+def _is_receiver_registration(base: str) -> bool:+ """Whether a dotted decorator hands the symbol to a receiver object.++ ``@nox.session``, ``@mcp.tool()`` and ``@sub.handle(...)`` are the shape:+ an attribute of some object, called later by that object. The lists above+ can only name receivers someone thought of, so the rule is inverted: any+ ``recv.attr`` is a registration unless it is a pure wrapper (functools,+ typing, contextlib, ``@x.setter`` and the like), which returns the function+ for an ordinary caller to call.++ Held to a lowercase attribute. A capitalised last segment is a qualified+ type name (``@java.lang.Deprecated``, ``[System.Obsolete]``), an annotation+ rather than a method on a receiver.++ Ceiling: matched on the text, so an aliased wrapper module+ (``import functools as ft``) reads as a registration. That only ever hides+ a finding.+ """+ receiver, _, attr = base.rpartition(".")+ if not receiver or not (attr[:1].islower() or attr.startswith("_")):+ return False+ if receiver.split(".", 1)[0] in _PURE_WRAPPER_DECORATOR_MODULES:+ return False+ return attr not in _PURE_WRAPPER_DECORATOR_ATTRS++def _is_symbol_deprecated(sym_name: str, decorators: list[str]) -> bool:"""Return True when the symbol is marked deprecated by name suffix or annotation.@@ -855,6 +892,8 @@ class DeadCodeAnalyzer:# version of the same question — not "could an unread file explain# this" but "did we look anywhere except the import graph".findings = clamp_unverified_absence(findings, self._source_map)+ findings = drop_internals_used_in_own_file(findings, self._source_map)+ findings = clamp_path_mentions(findings, self._source_map)min_conf = cfg.get("min_confidence", RISK_CAP_CONFIDENCE)hidden_below_threshold = sum(1 for f in findings if f.confidence < min_conf)diff --git a/packages/core/src/repowise/core/analysis/dead_code/constants.py b/packages/core/src/repowise/core/analysis/dead_code/constants.pyindex 7ed1ca7b4..aabc0629c 100644--- a/packages/core/src/repowise/core/analysis/dead_code/constants.py+++ b/packages/core/src/repowise/core/analysis/dead_code/constants.py@@ -924,6 +924,39 @@ _FRAMEWORK_DECORATOR_SUFFIXES: tuple[str, ...] = (".inclusion_tag",)+# A dotted decorator (``@recv.attr`` or ``@recv.attr(...)``) is read as a+# registration: ``@nox.session``, ``@mcp.tool()``, ``@sub.handle(...)`` hand the+# function to an object that calls it later, and no list of receivers can keep+# up with every framework. The exceptions are decorators that only wrap the+# function and hand it back, so the decorated name still needs a caller.+# Matched on the first path segment (the module) ...+_PURE_WRAPPER_DECORATOR_MODULES: frozenset[str] = frozenset(+ {+ "functools",+ "typing",+ "typing_extensions",+ "contextlib",+ "abc",+ "dataclasses",+ "mock",+ "unittest",+ }+)+# ... or on the last one (``@prop.setter``, ``@functools.cached_property``).+_PURE_WRAPPER_DECORATOR_ATTRS: frozenset[str] = frozenset(+ {+ "setter",+ "getter",+ "deleter",+ "property",+ "staticmethod",+ "classmethod",+ "cached_property",+ "override",+ "deprecated",+ }+)+# Languages whose idiom is a static holder class the call site never names,# because it names only the member (C# extension methods). A set so widening it# is a deliberate act.diff --git a/packages/core/src/repowise/core/analysis/dead_code/name_occurrences.py b/packages/core/src/repowise/core/analysis/dead_code/name_occurrences.pyindex d005fdc87..f533bad67 100644--- a/packages/core/src/repowise/core/analysis/dead_code/name_occurrences.py+++ b/packages/core/src/repowise/core/analysis/dead_code/name_occurrences.py@@ -65,6 +65,12 @@ IDENTIFIER_RE = re.compile(rb"[A-Za-z_][A-Za-z0-9_]{2,}")#: treated as a question we cannot ask rather than as an answer.MIN_ANSWERABLE_NAME_LEN = 3+#: Where an unused internal lands when its own file could not be searched for+#: it: the declaration's extent is unknown, or the name is one the scan cannot+#: see. Below :data:`RISK_CAP_CONFIDENCE`, so the default report hides it rather+#: than showing a finding nothing has checked.+UNVERIFIED_INTERNAL_CONFIDENCE = 0.3+class _Answer(Enum):"""What the search actually established. Four outcomes, kept apart.@@ -266,11 +272,10 @@ def clamp_unverified_absence(the analyzer. Never raises a confidence and never drops a finding.Scoped to unused *exports*, the one pass that promotes on import absence.- Unused internals already sit below the threshold and never claim to be- safe, and a whole-file finding would have to match on the path stem — the- broad-word shape ("index", "main", "utils") that the unindexed clamp and- the risk-factor token lists both refuse for being unable to tell a mention- from a coincidence.+ Unused internals are settled by :func:`drop_internals_used_in_own_file`,+ which can drop rather than cap because a private name has only its own file+ to be used in. A whole-file finding is matched by path, never by its stem,+ in :func:`clamp_path_mentions`.With no source access there is no knowledge to add, so the pass declinesrather than guessing in either direction.@@ -320,3 +325,171 @@ def clamp_unverified_absence(f"'{name}' {detail}, so the absence of an import does not establish disuse")return findings+++def drop_internals_used_in_own_file(+ findings: list[DeadCodeFindingData], source_map: dict[str, bytes]+) -> list[DeadCodeFindingData]:+ """Drop unused internals their own file names outside their declaration.++ The graph carries calls and a few reference kinds, but not every way a+ private name is used: a module constant read in a function below it, a+ handler passed as a value (``target=fn``, ``re.sub(pattern, fn, s)``), a+ type named in an annotation, a component written as JSX or as object+ shorthand. Each of those reached this pass as "not used anywhere". A+ private name can only be used in its own file, so a mention there outside+ the symbol's own span is a use and the finding is dropped, not capped.++ A recursive call sits inside the span and does not count, so a function+ only calling itself stays reported. A mention in a comment does count:+ that is this module's textual ceiling, and it only ever costs recall.++ When the file was read but the question could not be asked (no span, or a+ name the identifier scan cannot see), the finding stays but falls to+ :data:`UNVERIFIED_INTERNAL_CONFIDENCE`. A file with no source at all is+ left as it was: nothing was established either way.+ """+ by_file: dict[str, list[DeadCodeFindingData]] = {}+ for finding in findings:+ if (+ finding.kind is DeadCodeKind.UNUSED_INTERNAL+ and finding.symbol_name+ and finding.file_path in source_map+ ):+ by_file.setdefault(finding.file_path, []).append(finding)+ if not by_file:+ return findings++ verdicts: dict[int, _Verdict] = {}+ for path, pending in by_file.items():+ verdicts.update(_uses_in_own_file(source_map, path, pending))++ kept: list[DeadCodeFindingData] = []+ for finding in findings:+ verdict = verdicts.get(id(finding))+ if verdict is not None:+ if verdict.answer is _Answer.USED:+ continue+ if verdict.answer is _Answer.SPAN_UNKNOWN or not _token(finding.symbol_name):+ finding.confidence = min(finding.confidence, UNVERIFIED_INTERNAL_CONFIDENCE)+ finding.evidence.append(+ f"'{finding.symbol_name}' could not be checked against the rest of "+ "its own file, so its disuse is unverified"+ )+ kept.append(finding)+ return kept+++#: A path-shaped run of bytes: what a manifest, build script or doc writes when+#: it names a file. It must hold a ``.`` or a ``/`` (every key does), so the+#: regex engine skips plain words instead of handing each one to Python.+#: Whether a run names a candidate is decided by the lookup.+_PATH_TOKEN_RE = re.compile(rb"[A-Za-z0-9_@~+\-]*[./][A-Za-z0-9_.@~+\-/]*")+++def _path_keys(path: str) -> list[str]:+ """The spellings that name *path*: the repo-relative path, the path without+ its extension, and its ``dir/basename.ext`` tail.++ Never the bare stem. ``index``, ``main`` and ``utils`` name a file in every+ directory, and a stem cannot tell a mention from a coincidence. So the+ extension-less form is kept only while it still carries a directory, and a+ root-level file with no extension (a bare word) has no key at all.+ """+ keys = [path] if ("/" in path or "." in path) else []+ stem, dot, ext = path.rpartition(".")+ if dot and "/" in stem and "/" not in ext:+ keys.append(stem)+ parent, slash, base = path.rpartition("/")+ if slash:+ keys.append(f"{parent.rpartition('/')[2]}/{base}")+ return keys+++def _token_spellings(token: str) -> list[str]:+ """What a path-shaped *token* could be naming.++ Every suffix that starts after a ``/``, so ``./src/a.ts``, ``../src/a.ts``+ and an absolute path all reach ``src/a.ts``; and each suffix without its+ extension, so a build output (``src/a.js``) names its source (``src/a.ts``)+ through the shared extension-less key.+ """+ token = token.strip(".")+ out: list[str] = []+ start = 0+ while True:+ suffix = token[start:]+ if suffix:+ out.append(suffix)+ stem, dot, ext = suffix.rpartition(".")+ if dot and stem and "/" not in ext:+ out.append(stem)+ slash = token.find("/", start)+ if slash < 0:+ return out+ start = slash + 1+++def _first_file_naming(targets: set[str], source_map: dict[str, bytes]) -> dict[str, str]:+ """For each of *targets* another file names by path, the first such file."""+ wanted: dict[str, set[str]] = {}+ for target in targets:+ for key in _path_keys(target):+ wanted.setdefault(key, set()).add(target)+ # The last segment of every key, checked before any suffix work: nearly+ # every path-shaped token in a repository names none of the candidates.+ tails = {key.rpartition("/")[2] for key in wanted}++ named_in: dict[str, str] = {}+ for path, blob in sorted(source_map.items()):+ for match in _PATH_TOKEN_RE.finditer(blob):+ for target in _targets_named_by(match.group().decode("ascii"), wanted, tails):+ if target != path:+ named_in.setdefault(target, path)+ return named_in+++def _targets_named_by(token: str, wanted: dict[str, set[str]], tails: set[str]) -> set[str]:+ """The targets one path-shaped *token* names, through any of its spellings."""+ tail = token.strip(".").rpartition("/")[2]+ if tail not in tails and tail.rpartition(".")[0] not in tails:+ return set()+ return {target for spelling in _token_spellings(token) for target in wanted.get(spelling, ())}+++def clamp_path_mentions(+ findings: list[DeadCodeFindingData], source_map: dict[str, bytes]+) -> list[DeadCodeFindingData]:+ """Cap unreachable files that another file names by path.++ "Nothing imports this" is not "nothing uses this". A build script reads a+ template by path, a JSON manifest lists example files, a doc links a+ script, ``package.json`` names a bin: each loads the file without an import+ edge, and such a file reported as deletion-ready breaks whatever reads it.+ A mention is not proof of use either, so the finding is capped to the+ review tier rather than dropped.++ One scan over the indexed source. That already holds JSON, YAML, Markdown,+ shell and ``package.json``: each has a language spec, so ingestion reads+ it. A file's mention of itself is not a use. Mutates in place and returns+ the same list; never raises a confidence and never removes a finding.+ """+ if not source_map:+ return findings+ candidates = [+ f+ for f in findings+ if f.kind is DeadCodeKind.UNREACHABLE_FILE and f.confidence > RISK_CAP_CONFIDENCE+ ]+ if not candidates:+ return findings++ named_in = _first_file_naming({f.file_path for f in candidates}, source_map)+ for finding in candidates:+ where = named_in.get(finding.file_path)+ if where is None:+ continue+ finding.confidence = min(finding.confidence, RISK_CAP_CONFIDENCE)+ finding.safe_to_delete = False+ finding.evidence.append(f"Named by path in {where}, which may load it without an import")+ return findingsdiff --git a/tests/unit/dead_code/test_decorators_dynamic.py b/tests/unit/dead_code/test_decorators_dynamic.pyindex a2f47098e..568b7f1f1 100644--- a/tests/unit/dead_code/test_decorators_dynamic.py+++ b/tests/unit/dead_code/test_decorators_dynamic.py@@ -394,8 +394,10 @@ def test_renamed_receiver_and_registry_decorators_excluded(decorator):"@registered_only","@registry_cache",# The receiver being called ``register`` says nothing about the- # decorator, which is what the final path segment is read for.- "@register.unwrap",+ # decorator, which is what the final path segment is read for. The+ # attribute has to be a pure wrapper here: any other ``recv.attr`` is+ # now read as a registration in its own right.+ "@register.setter",],)def test_register_lookalike_decorators_still_flagged(decorator):diff --git a/tests/unit/dead_code/test_framework_registration_rescues.py b/tests/unit/dead_code/test_framework_registration_rescues.pyindex 520814c69..0a393052a 100644--- a/tests/unit/dead_code/test_framework_registration_rescues.py+++ b/tests/unit/dead_code/test_framework_registration_rescues.py@@ -228,3 +228,67 @@ def test_an_annotation_beside_suppresswarnings_does_not_leak_its_argument():},)assert "activate" in _unused_export_names(graph)+++# ---------------------------------------------------------------------------+# Any ``recv.attr`` decorator is a registration unless it only wraps.+# ---------------------------------------------------------------------------+++def _decorated(decorator: str, visibility: str) -> nx.DiGraph:+ return _build_graph(+ nodes={+ "pkg/handlers.py": {+ "symbols": [+ {+ "name": "handle_thing",+ "kind": "function",+ "visibility": visibility,+ "decorators": [decorator],+ "start_line": 1,+ "end_line": 4,+ },+ ],+ },+ },+ )+++def _reported(decorator: str) -> tuple[bool, bool]:+ """(reported as unused export, reported as unused internal)."""+ export = "handle_thing" in _unused_export_names(_decorated(decorator, "public"))+ report = DeadCodeAnalyzer(_decorated(decorator, "private"), git_meta_map={}).analyze(+ {"detect_unreachable_files": False, "min_confidence": 0.0}+ )+ internal = any(f.kind == DeadCodeKind.UNUSED_INTERNAL for f in report.findings)+ return export, internal+++def test_receiver_decorators_are_registrations_in_both_passes():+ for decorator in ("@nox.session", "@sub.handle('created')", "@mcp.tool()", "@bot.on.message"):+ assert _reported(decorator) == (False, False), decorator+++def test_pure_wrapper_decorators_are_not_registrations():+ for decorator in (+ "@functools.wraps(fn)",+ "@functools.lru_cache(maxsize=None)",+ "@typing.override",+ "@abc.abstractmethod",+ "@typing.no_type_check",+ "@mock.create_autospec(spec)",+ "@unittest.mock.create_autospec(spec)",+ "@value.setter",+ ):+ assert _reported(decorator) == (True, True), decorator+++def test_a_deprecation_marker_is_not_a_registration():+ # An exported deprecated symbol is kept for its own reason, so the internal+ # pass is where a wrapper-shaped ``deprecated`` shows it registers nothing.+ assert _reported("@warnings.deprecated('use other')")[1] is True+++def test_a_qualified_annotation_type_is_not_a_receiver():+ # ``@java.lang.Deprecated``-style: a capitalised last segment names a type.+ assert _reported("@org.example.Marker") == (True, True)diff --git a/tests/unit/dead_code/test_path_mentions.py b/tests/unit/dead_code/test_path_mentions.pynew file mode 100644index 000000000..964154053--- /dev/null+++ b/tests/unit/dead_code/test_path_mentions.py@@ -0,0 +1,119 @@+"""An unreachable file another file names by path is not deletion-ready.++A build script that reads a file by path, or a JSON manifest that lists it,+uses the file without an import edge. The pass caps such a finding to the+review tier; it never matches on a bare stem, and a file nobody names keeps+its confidence.+"""++from __future__ import annotations++from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind+from repowise.core.analysis.dead_code.models import DeadCodeFindingData+from repowise.core.analysis.dead_code.name_occurrences import clamp_path_mentions+from repowise.core.analysis.dead_code.risk_factors import RISK_CAP_CONFIDENCE+from tests.unit.dead_code._helpers import _build_graph, _old_date+++def _file(path: str, confidence: float = 1.0) -> DeadCodeFindingData:+ return DeadCodeFindingData(+ kind=DeadCodeKind.UNREACHABLE_FILE,+ file_path=path,+ symbol_name=None,+ symbol_kind=None,+ confidence=confidence,+ reason="File has no importers (in_degree=0)",+ last_commit_at=None,+ commit_count_90d=0,+ lines=1,+ evidence=[],+ safe_to_delete=True,+ primary_owner=None,+ age_days=None,+ )+++def _clamp(path: str, source: dict[str, str]) -> DeadCodeFindingData:+ finding = _file(path)+ clamp_path_mentions([finding], {p: s.encode() for p, s in source.items()})+ return finding+++def test_a_json_manifest_listing_example_files_caps_them():+ manifest = '{"examples": ["examples/basic/run.py", "./examples/advanced/run.py"]}'+ source = {"examples.json": manifest, "examples/basic/run.py": "print(1)\n"}+ for path in ("examples/basic/run.py", "examples/advanced/run.py"):+ finding = _clamp(path, source)+ assert finding.confidence == RISK_CAP_CONFIDENCE+ assert finding.safe_to_delete is False+ assert "examples.json" in finding.evidence[-1]+++def test_a_build_script_reading_a_python_file_by_path_caps_it():+ script = "#!/bin/sh\npython tools/codegen/emit.py > out.txt\n"+ finding = _clamp("tools/codegen/emit.py", {"scripts/build.sh": script})+ assert finding.confidence == RISK_CAP_CONFIDENCE+++def test_dir_and_basename_with_extension_is_enough():+ finding = _clamp("src/pkg/loader.py", {"docs/usage.md": "See `pkg/loader.py`."})+ assert finding.confidence == RISK_CAP_CONFIDENCE+++def test_a_build_output_path_names_its_source():+ pkg = '{"main": "src/cli/index.js"}'+ finding = _clamp("src/cli/index.ts", {"package.json": pkg})+ assert finding.confidence == RISK_CAP_CONFIDENCE+++def test_a_bare_stem_never_matches():+ # "loader" and "loader.py" alone name a file in any directory.+ source = {"README.md": "The loader reads config. loader.py is old.\n"}+ finding = _clamp("src/pkg/loader.py", source)+ assert finding.confidence == 1.0+ assert finding.safe_to_delete is True+++def test_a_longer_file_name_sharing_the_prefix_is_not_a_mention():+ finding = _clamp("src/pkg/loader.py", {"a.md": "src/pkg/loader_v2.py"})+ assert finding.confidence == 1.0+++def test_a_file_naming_itself_is_not_a_use():+ own = '"""Run as: python scripts/old_migrate.py"""\n'+ finding = _clamp("scripts/old_migrate.py", {"scripts/old_migrate.py": own})+ assert finding.confidence == 1.0+++def test_a_truly_dead_file_through_the_analyzer_stays_deletion_ready():+ g = _build_graph(+ nodes={+ "pkg/used.py": {"is_entry_point": True, "symbols": []},+ "pkg/old.py": {"symbols": []},+ "pkg/listed.py": {"symbols": []},+ },+ )+ old = {"commit_count_90d": 0, "last_commit_at": _old_date(400)}+ source = {+ "pkg/used.py": b"print('hi')\n",+ "pkg/old.py": b"x = 1\n",+ "pkg/listed.py": b"y = 2\n",+ "tox.yaml": b"files: [pkg/listed.py]\n",+ }+ report = DeadCodeAnalyzer(+ g,+ git_meta_map={"pkg/old.py": old, "pkg/listed.py": old},+ source_map=source,+ ).analyze(+ {+ "detect_unused_exports": False,+ "detect_unused_internals": False,+ "detect_zombie_packages": False,+ "min_confidence": 0.0,+ }+ )+ by_path = {f.file_path: f for f in report.findings if f.kind == DeadCodeKind.UNREACHABLE_FILE}+ assert by_path["pkg/old.py"].safe_to_delete is True+ assert by_path["pkg/old.py"].confidence == 1.0+ assert by_path["pkg/listed.py"].confidence == RISK_CAP_CONFIDENCE+ assert by_path["pkg/listed.py"].safe_to_delete is Falsediff --git a/tests/unit/dead_code/test_unused_internal.py b/tests/unit/dead_code/test_unused_internal.pyindex 5b54209d1..bd919a838 100644--- a/tests/unit/dead_code/test_unused_internal.py+++ b/tests/unit/dead_code/test_unused_internal.py@@ -6,6 +6,8 @@ from repowise.core.analysis.dead_code import (DeadCodeAnalyzer,DeadCodeKind,)+from repowise.core.analysis.dead_code.name_occurrences import UNVERIFIED_INTERNAL_CONFIDENCE+from repowise.core.analysis.dead_code.risk_factors import RISK_CAP_CONFIDENCEfrom tests.unit.dead_code._helpers import _build_graph@@ -378,3 +380,159 @@ def test_unused_internal_rust_impl_uncallable():names = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_INTERNAL}assert "MyStruct" not in names++# ---------------------------------------------------------------------------+# In-file use: the graph carries no ``reads`` edge for a constant, a callback+# passed as a value, or a type in an annotation, so the file's own text decides.+# ---------------------------------------------------------------------------+++def _internals_over(path: str, source: str, symbols: list[dict], language: str = "python") -> dict:+ """Unused-internal findings for one file analysed with its own source."""+ g = _build_graph(+ nodes={+ path: {+ "is_entry_point": False,+ "is_test": False,+ "is_api_contract": False,+ "symbols": [+ {+ "visibility": "private",+ "decorators": [],+ "kind": "function",+ "language": language,+ **s,+ }+ for s in symbols+ ],+ },+ },+ )+ report = DeadCodeAnalyzer(g, git_meta_map={}, source_map={path: source.encode()}).analyze(+ {+ "detect_unreachable_files": False,+ "detect_unused_exports": False,+ "detect_zombie_packages": False,+ "min_confidence": 0.0,+ }+ )+ return {f.symbol_name: f for f in report.findings if f.kind == DeadCodeKind.UNUSED_INTERNAL}+++def test_ts_module_const_read_in_the_same_file_is_not_reported():+ source = (+ "const RETRY_LIMIT = 5;\n" # 1+ "const STRANDED = 9;\n" # 2+ "export function run(n: number) {\n" # 3+ " return n < RETRY_LIMIT;\n" # 4+ "}\n"+ )+ found = _internals_over(+ "src/run.ts",+ source,+ [+ {"name": "RETRY_LIMIT", "kind": "constant", "start_line": 1, "end_line": 1},+ {"name": "STRANDED", "kind": "constant", "start_line": 2, "end_line": 2},+ ],+ language="typescript",+ )+ assert "RETRY_LIMIT" not in found+ assert "STRANDED" in found # the control: a const nothing reads+++def test_python_callback_passed_as_target_is_not_reported():+ source = (+ "import threading\n" # 1+ "def _worker():\n" # 2+ " pass\n" # 3+ "def start():\n" # 4+ " threading.Thread(target=_worker).start()\n" # 5+ )+ found = _internals_over(+ "pkg/jobs.py", source, [{"name": "_worker", "start_line": 2, "end_line": 3}]+ )+ assert found == {}+++def test_python_function_handed_to_re_sub_is_not_reported():+ source = (+ "import re\n"+ "def _escape(match):\n"+ " return match.group(0)\n"+ "def clean(text):\n"+ " return re.sub(r'x', _escape, text)\n"+ )+ found = _internals_over(+ "pkg/text.py", source, [{"name": "_escape", "start_line": 2, "end_line": 3}]+ )+ assert found == {}+++def test_class_named_only_in_a_type_annotation_is_not_reported():+ source = (+ "class _Options:\n" # 1+ " verbose = False\n" # 2+ "def configure(opts: '_Options') -> None:\n" # 3+ " print(opts)\n"+ )+ found = _internals_over(+ "pkg/opts.py",+ source,+ [{"name": "_Options", "kind": "class", "start_line": 1, "end_line": 2}],+ )+ assert found == {}+++def test_recursive_only_function_stays_reported():+ source = (+ "def _walk(node):\n" # 1+ " for child in node:\n" # 2+ " _walk(child)\n" # 3+ )+ found = _internals_over(+ "pkg/tree.py", source, [{"name": "_walk", "start_line": 1, "end_line": 3}]+ )+ assert "_walk" in found+ assert found["_walk"].confidence == 0.65+++def test_unknown_span_is_kept_but_hidden_below_the_review_floor():+ source = "def _helper():\n pass\n"+ found = _internals_over("pkg/util.py", source, [{"name": "_helper"}])+ assert found["_helper"].confidence == UNVERIFIED_INTERNAL_CONFIDENCE+ assert UNVERIFIED_INTERNAL_CONFIDENCE < RISK_CAP_CONFIDENCE+ assert "unverified" in found["_helper"].evidence[-1]+++def test_a_mention_in_a_comment_counts_as_a_use():+ # The accepted textual ceiling: a comment naming the helper is read as a+ # use. It can only cost recall, never report a live symbol.+ source = "# see _helper below\ndef _helper():\n pass\n"+ found = _internals_over(+ "pkg/util.py", source, [{"name": "_helper", "start_line": 2, "end_line": 3}]+ )+ assert found == {}+++def test_without_source_the_finding_is_left_as_it_was():+ g = _build_graph(+ nodes={+ "pkg/util.py": {+ "symbols": [+ {+ "name": "_helper",+ "kind": "function",+ "visibility": "private",+ "decorators": [],+ "start_line": 1,+ "end_line": 2,+ }+ ],+ },+ },+ )+ report = DeadCodeAnalyzer(g, git_meta_map={}).analyze(+ {"detect_unreachable_files": False, "detect_unused_exports": False, "min_confidence": 0.0}+ )+ [finding] = [f for f in report.findings if f.kind == DeadCodeKind.UNUSED_INTERNAL]+ assert finding.confidence == 0.65