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): make a top-tier confidence mean we actually looked (#1666)
Raghav Chamadiya7eadd6eb53ce
diff --git a/docs/layers/DEAD_CODE.md b/docs/layers/DEAD_CODE.mdindex 25d7b7415..c915aaf5b 100644--- a/docs/layers/DEAD_CODE.md+++ b/docs/layers/DEAD_CODE.md@@ -43,7 +43,7 @@ get_dead_code(kind="unused_export", group_by="owner")| Kind | What it means | How it is computed | Base confidence ||------|---------------|--------------------|-----------------|| `unreachable_file` | No file in the repo imports this one. | File-node in-degree of 0 on the dependency graph, after entry points and the never-flag allowlist are removed. | Scored from git age (below) |-| `unused_export` | A public symbol nothing imports. | No `imports` edge names the symbol (or `*`, or a TypeScript `export { local as alias }` rename), and no `calls` / `method_implements` / `reads` / `extends` / `implements` / `type_use` edge reaches it. Member kinds (`method`, `field`, `property`, `enum_member`) are excluded from this pass across all languages since they are accessed through their container, not imported by name. Top-level `export const` primitives, objects, and arrays in TypeScript and JavaScript are fully evaluated (they are always importable by name). | `1.00` when the containing file *does* have importers (so the file is alive and only this symbol is not), `0.70` when it does not, `0.30` when the name ends in `_DEPRECATED` / `_LEGACY` / `_COMPAT` |+| `unused_export` | A public symbol nothing imports. | No `imports` edge names the symbol (or `*`, or a TypeScript `export { local as alias }` rename), and no `calls` / `method_implements` / `reads` / `extends` / `implements` / `type_use` edge reaches it. Member kinds (`method`, `field`, `property`, `enum_member`) are excluded from this pass across all languages since they are accessed through their container, not imported by name. Top-level `export const` primitives, objects, and arrays in TypeScript and JavaScript are fully evaluated (they are always importable by name). | `1.00` when the containing file *does* have importers (so the file is alive and only this symbol is not), `0.70` when it does not, `0.30` when the name ends in `_DEPRECATED` / `_LEGACY` / `_COMPAT` — then capped as described below || `unused_internal` | A private or underscore-prefixed symbol nothing calls. | No `calls` edge, and no cross-file importer pulls the name (which would mean a dispatch-table lookup). Off by default. | `0.65` || `zombie_package` | A whole top-level package no other package imports. | No inter-package import edges into it. Never marked safe to delete. | `0.50` |@@ -52,6 +52,31 @@ default and can be turned off with `--no-include-zombie-packages`. Passing`--kind` overrides both toggles, so `--kind unused_internal` enables internals onits own.+### An unused export must survive a search for its own name++The base confidences above score how strong the evidence for deadness is. They+do not ask whether a use would have been visible at all — and "no import edge"+only means "unused" in a language where using a symbol requires importing it.+That holds in Python and TypeScript. It is false for a same-package Kotlin or+Go reference, a same-translation-unit C++ type, an intra-crate Rust path, and a+C# or Swift member of the same module, where a use needs no import. The same+blind spot swallows a use written through an aliased import, an attribute call+on an imported module, or a handler named by string from infrastructure config.++So before an `unused_export` keeps a confidence above `0.40`, the repository is+searched for the symbol's name. If the name is written anywhere other than the+declaration itself — in any indexed file, including non-code ones such as+Terraform or YAML — the finding is capped at `0.40`, loses `safe_to_delete`,+and its reason names where the name was found. The same cap applies when the+search could not be run at all, because not looking and looking without finding+are different results.++The check only ever suppresses. A name written solely in a comment counts as a+use, so this costs recall and buys precision, which is the trade the top tier+exists for. Nothing is removed from the report: the cap lands exactly on the+default `min_confidence`, so a capped finding still appears as a review+candidate and only stops claiming to be deletion-ready.+Two caveats on the numbers. `unused_internal` is disabled entirely for Rust,where the graph does not yet emit intra-file call edges, so a private Rust helperis never flagged. And the `lines` count on file and package findings is andiff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.pyindex d090b1df2..8d2282545 100644--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py@@ -43,6 +43,7 @@ from .file_reachability import (is_file_reachable,)from .models import DeadCodeFindingData, DeadCodeKind, DeadCodeReport+from .name_occurrences import IDENTIFIER_RE, clamp_unverified_absencefrom .risk_factors import (RISK_CAP_CONFIDENCE,SAFE_CONFIDENCE_THRESHOLD,@@ -50,11 +51,10 @@ from .risk_factors import (risk_evidence,)-#: Identifier shape, matched over raw bytes so an unindexed file never has to-#: be decoded (these files are large by definition, and a decode would double-#: the peak). ASCII-only is deliberate: a non-ASCII identifier that fails to-#: match can only under-suppress.-_IDENTIFIER_RE = re.compile(rb"[A-Za-z_][A-Za-z0-9_]{2,}")+#: The unindexed scan below and the repo-wide absence check ask the same+#: question of different file sets, so they share one identifier shape rather+#: than each carrying a copy. See :mod:`name_occurrences`, which owns it.+_IDENTIFIER_RE = IDENTIFIER_RE#: The confidence ceiling for a finding an unread file could explain is#: ``RISK_CAP_CONFIDENCE``, imported above rather than redefined: it already@@ -623,6 +623,11 @@ class DeadCodeAnalyzer:self._unindexed_source_files = list(unindexed_source_files or [])self._repo_root = repo_rootself._unindexed_tokens: frozenset[str] | None = None+ # Kept for the absence check below, which is the one pass that needs+ # the raw text of *every* indexed file rather than of a suffix-filtered+ # subset. Empty when a caller has no source access, which is what makes+ # that check skip rather than guess.+ self._source_map: dict[str, bytes] = source_map or {}# Four prepasses below each scan every indexed file for text markers.# ``source_map`` is ingestion's ``{repo_relative_path: raw bytes}`` for# the same file set, so passing it turns four full-repo disk passes@@ -724,6 +729,10 @@ class DeadCodeAnalyzer:# out entirely, rather than being reported at a number it no longer# deserves.findings = self._clamp_for_unindexed_importers(findings)+ # Same position and for the same reason. This one asks the wider+ # 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)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/name_occurrences.py b/packages/core/src/repowise/core/analysis/dead_code/name_occurrences.pynew file mode 100644index 000000000..d005fdc87--- /dev/null+++ b/packages/core/src/repowise/core/analysis/dead_code/name_occurrences.py@@ -0,0 +1,322 @@+"""Did we actually look — the knowledge term behind a dead-code confidence.++Every other input to a dead-code confidence scores *how strong the evidence+for deadness is*. None of them asks the second question a confidence has to+answer before a user can act on it without checking: **would a use have been+visible to us at all?**++``_detect_unused_exports`` promotes a finding to the top of the scale when the+defining file has importers — the argument being that our import graph+demonstrably works for this file, so the symbol's absence from every importer's+imported names means something. That argument assumes *using a symbol requires+importing it*. It holds in Python and TypeScript. It is false for:++* a same-package Kotlin or Go reference,+* a same-translation-unit C++ type,+* an intra-crate Rust path,+* a C# or Swift member of the same module,++where a use needs no import at all, so the absence of an import edge carries no+information about the symbol. The same blind spot swallows a use written+through an aliased import, an attribute call on an imported module, or a+handler named by string from infrastructure config.++This module supplies the missing term, and it is deliberately the weakest+possible form of it: **does the repository write this name anywhere other than+the declaration itself?** If it does, we have not looked everywhere, and the+finding is capped to the review tier with the file that said so. If it does+not, the original confidence stands.++Two properties make that safe to apply to every finding rather than to a+hand-picked language list:++* **It only ever suppresses.** A name written only in a comment counts as a+ use. That is a real ceiling, not an oversight, and it is why this can cost+ recall and can never invent a false negative in the other direction.+* **It never removes a finding.** The cap lands exactly on the default+ ``min_confidence``, so a capped finding is still reported. What it loses is+ the claim, not its place in the report.++The alternative considered and not taken was a per-language table of "does+usage require an import here". It is cheaper, but it is a list someone has to+keep true as languages are added, and it answers the question by assertion+where this answers it from the repository in front of us.+"""++from __future__ import annotations++import re+from dataclasses import dataclass+from enum import Enum++from .models import DeadCodeFindingData, DeadCodeKind+from .risk_factors import RISK_CAP_CONFIDENCE++#: Identifier shape, matched over raw bytes so nothing has to be decoded — the+#: scan covers every indexed file, and decoding them all would dominate it.+#: ASCII-only is deliberate: a non-ASCII identifier that fails to match can+#: only under-suppress, which is the safe direction.+IDENTIFIER_RE = re.compile(rb"[A-Za-z_][A-Za-z0-9_]{2,}")++#: Shortest name this check can answer for. :data:`IDENTIFIER_RE` needs three+#: characters, so a two-character name matches nowhere — including on its own+#: declaration. Reading that as "the name appears nowhere" would turn the+#: strongest verdict into the least reliable one, so a name this short is+#: treated as a question we cannot ask rather than as an answer.+MIN_ANSWERABLE_NAME_LEN = 3+++class _Answer(Enum):+ """What the search actually established. Four outcomes, kept apart.++ Only :data:`ABSENT` leaves a finding alone. The other three all cap it,+ but for reasons a reader needs told apart: a use was found, or the search+ could not be run, or it ran and only the declaration's own extent was+ unknown. Collapsing them into "not verified" is what makes an evidence+ line say something that did not happen.+ """++ ABSENT = "absent"+ USED = "used"+ NOT_SEARCHABLE = "not_searchable"+ SPAN_UNKNOWN = "span_unknown"+++@dataclass(frozen=True)+class _Verdict:+ answer: _Answer+ used_at: str | None = None+++_NOT_SEARCHABLE = _Verdict(_Answer.NOT_SEARCHABLE)+_SPAN_UNKNOWN = _Verdict(_Answer.SPAN_UNKNOWN)+_ABSENT = _Verdict(_Answer.ABSENT)+++def occurrence_files(+ source_map: dict[str, bytes], names: set[bytes]+) -> dict[bytes, set[str]]:+ """For each name in *names*, the indexed files whose source writes it.++ One pass over the whole indexed source. The candidate names are known+ before the scan starts, so the returned map only ever holds the few names+ some finding actually asks about rather than every identifier in the+ repository — which is what keeps this affordable on a large tree.+ """+ found: dict[bytes, set[str]] = {}+ if not names:+ return found+ for path, blob in source_map.items():+ for match in IDENTIFIER_RE.finditer(blob):+ token = match.group()+ if token in names:+ found.setdefault(token, set()).add(path)+ return found+++def _uses_in_own_file(+ source_map: dict[str, bytes],+ path: str,+ findings: list[DeadCodeFindingData],+) -> dict[int, _Verdict]:+ """Where each of *findings* is named in its own file outside its own span.++ Reached only for a name no other file mentions — the same-translation-unit+ shape, where a C++ helper struct used inside the very function below it is+ the use the import graph cannot see. A recursive call sits *inside* the+ declaration and correctly does not count; a doc comment above it sits+ outside and does, which is this module's stated textual ceiling.++ Two things make the line arithmetic exact rather than nearly right:++ * The split is on ``\\n`` alone. ``bytes.splitlines`` also breaks on a bare+ ``\\r`` and on the form-feed family, which the parser's row counter does+ not — so a lone ``\\r`` inside a string literal (a progress-bar ``print``+ is the common one) would shift every line after it and make a symbol's+ own recursive call land outside its recorded span.+ * A sibling declaration's *header line* is excluded as well as the judged+ symbol's own span. Overloads share a name, so each declaration would+ otherwise read as a use of the other. Only the header, never the sibling's+ whole body: a span can enclose an unrelated same-named symbol's real call+ site, and excluding the body would drop that use and leave a live symbol+ claiming the top tier.+ """+ spanned = [+ f for f in findings if f.start_line is not None and f.end_line is not None+ ]+ out: dict[int, _Verdict] = {+ id(f): (_ABSENT if f in spanned else _SPAN_UNKNOWN) for f in findings+ }+ blob = source_map.get(path)+ if blob is None or not spanned:+ return out++ wanted: dict[bytes, list[DeadCodeFindingData]] = {}+ headers: dict[bytes, set[int]] = {}+ for finding in spanned:+ token = _token(finding.symbol_name)+ wanted.setdefault(token, []).append(finding)+ headers.setdefault(token, set()).add(finding.start_line)++ for lineno, line in enumerate(blob.split(b"\n"), start=1):+ for match in IDENTIFIER_RE.finditer(line):+ token = match.group()+ for finding in wanted.get(token, ()):+ if out[id(finding)].answer is _Answer.USED:+ continue+ if finding.start_line <= lineno <= finding.end_line:+ continue+ if lineno in headers[token]:+ continue # a sibling declaration of the same name+ out[id(finding)] = _Verdict(_Answer.USED, f"{path}:{lineno}")+ return out+++def _token(name: str) -> bytes:+ """The searchable form of *name*, or empty when the scan cannot find it.++ The one rule is that the result must be something :data:`IDENTIFIER_RE`+ would actually match, because a token the scan cannot produce is absent+ from every file including the one that declares it — and reading that as+ "the name appears nowhere" would turn the strongest verdict into the least+ reliable one. Two shapes fail it, for different reasons:++ * a non-ASCII name, since ``encode(errors="ignore")`` drops characters+ rather than failing and would search for ``caf`` on behalf of ``café``,+ letting an unrelated ``caf`` elsewhere read as a use;+ * a name carrying a character the identifier shape does not admit, such as+ the ``$`` in a JVM or JavaScript synthetic name, which the scan would+ only ever see as two shorter tokens.+ """+ encoded = name.encode("ascii", "ignore")+ if encoded.decode("ascii") != name:+ return b""+ if len(encoded) < MIN_ANSWERABLE_NAME_LEN or not IDENTIFIER_RE.fullmatch(encoded):+ return b""+ return encoded+++def _is_own_type_sibling(occurrence: str, declaring: str) -> bool:+ """True when *occurrence* is *declaring*'s own generated declaration file.++ A ``.d.ts`` beside ``runtime.js`` restates that module's exports as types.+ It declares the same names a second time and calls none of them, so+ counting it as a use makes every symbol in a generated binding module look+ alive — measured as the single largest source of lost true positives on+ this corpus.++ Deliberately narrow: only the same directory and the same stem. A ``.d.ts``+ naming a symbol from *elsewhere* really is referring to it, and stays a use.+ """+ if not occurrence.endswith(".d.ts"):+ return False+ stem = occurrence[: -len(".d.ts")]+ base = declaring.rsplit(".", 1)[0]+ return stem == base+++def _verdicts(+ source_map: dict[str, bytes], candidates: list[DeadCodeFindingData]+) -> dict[int, _Verdict]:+ """One verdict per candidate, from one repo-wide scan plus targeted reads."""+ # Built from the candidates alone, which is what keeps a whole-repo scan+ # affordable: the index only ever holds the names some finding asks about.+ answerable = {_token(f.symbol_name) for f in candidates} - {b""}+ occurrences = occurrence_files(source_map, answerable)++ out: dict[int, _Verdict] = {}+ # A name occurring in no file but its own needs the declaration's span+ # excluded before the question is answered at all. Those are gathered here+ # and read per file below, so each file is walked once however many of its+ # symbols are candidates.+ same_file_only: dict[str, list[DeadCodeFindingData]] = {}++ for finding in candidates:+ token = _token(finding.symbol_name)+ if not token:+ out[id(finding)] = _NOT_SEARCHABLE+ continue+ files = occurrences.get(token, set())+ elsewhere = sorted(+ f+ for f in files - {finding.file_path}+ if not _is_own_type_sibling(f, finding.file_path)+ )+ if elsewhere:+ out[id(finding)] = _Verdict(_Answer.USED, elsewhere[0])+ elif finding.file_path in files:+ same_file_only.setdefault(finding.file_path, []).append(finding)+ else:+ # The scan cannot see the declaration it is standing on, so this+ # file was not among those searched and nothing about it was+ # established either way.+ out[id(finding)] = _NOT_SEARCHABLE++ for path, pending in same_file_only.items():+ out.update(_uses_in_own_file(source_map, path, pending))+ return out+++def clamp_unverified_absence(+ findings: list[DeadCodeFindingData], source_map: dict[str, bytes]+) -> list[DeadCodeFindingData]:+ """Cap findings whose symbol the repository names somewhere else.++ Mutates in place and returns the same list, matching the sibling clamp in+ 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.++ With no source access there is no knowledge to add, so the pass declines+ rather than guessing in either direction.+ """+ if not source_map:+ return findings++ candidates = [+ f+ for f in findings+ if f.kind == DeadCodeKind.UNUSED_EXPORT+ and f.symbol_name+ and f.confidence > RISK_CAP_CONFIDENCE+ ]+ if not candidates:+ return findings++ verdicts = _verdicts(source_map, candidates)+ # Keyed by identity, so a findings list that happens to hold one object+ # twice does not collect the same evidence line twice.+ for finding in {id(f): f for f in candidates}.values():+ verdict = verdicts.get(id(finding), _NOT_SEARCHABLE)+ if verdict.answer is _Answer.ABSENT:+ continue+ name = finding.symbol_name+ # ``reason`` carries this, not only ``evidence``. The unchanged reason+ # asserts "has no importers" as the ground for the finding, which is+ # the very inference this check has just declined to make — and it is+ # the field every surface renders, where the evidence list reaches+ # only the JSON ones.+ if verdict.answer is _Answer.USED:+ finding.reason = f"'{name}' is not imported, but is named elsewhere in the repo"+ detail = f"is written at {verdict.used_at}"+ else:+ # Both remaining answers mean the same thing to a reader — we did+ # not establish an absence — so they share a reason and differ only+ # in the evidence line, which is where the distinction is useful.+ finding.reason = f"'{name}' is not imported, and its use could not be verified"+ detail = (+ "is named in its own file, whose declaration could not be bounded"+ if verdict.answer is _Answer.SPAN_UNKNOWN+ else "could not be searched for across the repository"+ )+ finding.confidence = min(finding.confidence, RISK_CAP_CONFIDENCE)+ finding.safe_to_delete = False+ finding.evidence.append(+ f"'{name}' {detail}, so the absence of an import does not establish disuse"+ )+ return findingsdiff --git a/tests/unit/dead_code/test_name_occurrences.py b/tests/unit/dead_code/test_name_occurrences.pynew file mode 100644index 000000000..8fb146d65--- /dev/null+++ b/tests/unit/dead_code/test_name_occurrences.py@@ -0,0 +1,364 @@+"""A top-tier dead-code confidence must mean "we looked everywhere".++The unused-export pass promotes to 1.0 when the defining file has importers,+which assumes that using a symbol requires importing it. Where that is false —+a same-package Kotlin or Go reference, a same-translation-unit C++ type, an+aliased import, a handler named by string from infrastructure config — the+promotion is not weak evidence, it is inadmissible, and the finding shipped as+deletion-ready.++These exercise the clamp directly rather than through a detector. What needs+pinning is which findings it touches and which it must leave alone; building a+graph that yields one finding per case would test the detectors instead. The+detector-level behaviour is covered by the fixtures in+``test_unused_exports.py``.++The control in every rescue case is the second symbol: a change that suppresses+false positives by suppressing everything passes every other assertion here.+"""++from __future__ import annotations++import pytest++from repowise.core.analysis.dead_code.models import DeadCodeFindingData, DeadCodeKind+from repowise.core.analysis.dead_code.name_occurrences import clamp_unverified_absence+from repowise.core.analysis.dead_code.risk_factors import RISK_CAP_CONFIDENCE+++def _finding(+ symbol_name: str,+ *,+ file_path: str = "src/lib.kt",+ confidence: float = 1.0,+ kind: DeadCodeKind = DeadCodeKind.UNUSED_EXPORT,+ start_line: int | None = 1,+ end_line: int | None = 3,+) -> DeadCodeFindingData:+ return DeadCodeFindingData(+ kind=kind,+ file_path=file_path,+ symbol_name=symbol_name,+ symbol_kind="class",+ confidence=confidence,+ reason="test",+ last_commit_at=None,+ commit_count_90d=0,+ lines=3,+ start_line=start_line,+ end_line=end_line,+ package=None,+ evidence=[],+ safe_to_delete=True,+ primary_owner=None,+ age_days=None,+ )+++def _src(**files: str) -> dict[str, bytes]:+ """Keyword paths, since a dict literal per case buries the source itself.++ ``src__sky_cpp=...`` is ``src/sky.cpp``: ``__`` is a directory separator+ and the last ``_`` is the extension dot.+ """+ out: dict[str, bytes] = {}+ for key, body in files.items():+ stem, _, ext = key.replace("__", "/").rpartition("_")+ out[f"{stem}.{ext}"] = body.encode("utf-8")+ return out+++class TestUsedElsewhere:+ """A name the repository writes somewhere else stops claiming certainty."""++ def test_same_package_reference_in_another_file_caps(self):+ # No import statement anywhere: this is the Kotlin/Go shape.+ source = _src(+ src__lib_kt="package app\n\nclass Registry\n",+ src__server_kt="package app\n\nfun start() = Registry()\n",+ )+ finding = _finding("Registry")+ clamp_unverified_absence([finding], source)++ assert finding.confidence == RISK_CAP_CONFIDENCE+ assert finding.safe_to_delete is False+ assert "src/server.kt" in finding.evidence[-1]++ def test_untouched_when_the_name_appears_only_in_its_declaration(self):+ source = _src(+ src__lib_kt="package app\n\nclass Registry\n",+ src__server_kt="package app\n\nfun start() = 1\n",+ )+ finding = _finding("Registry")+ clamp_unverified_absence([finding], source)++ assert finding.confidence == 1.0+ assert finding.safe_to_delete is True+ assert finding.evidence == []++ def test_a_modules_own_generated_type_sibling_is_not_a_use(self):+ # A .d.ts beside runtime.js restates that module's exports as types. It+ # declares the names a second time and calls none of them, so counting+ # it would make every symbol in a generated binding module look alive.+ source = _src(+ **{+ "runtime__runtime_js": "export function WindowHide() {}\n",+ "runtime__runtime_d.ts": "export function WindowHide(): void;\n",+ }+ )+ finding = _finding("WindowHide", file_path="runtime/runtime.js")+ clamp_unverified_absence([finding], source)++ assert finding.confidence == 1.0+ assert finding.safe_to_delete is True++ def test_a_declaration_file_elsewhere_is_still_a_use(self):+ # The narrowing is same-directory, same-stem only. A .d.ts naming a+ # symbol from another module really is referring to it.+ source = _src(+ **{+ "runtime__runtime_js": "export function WindowHide() {}\n",+ "types__api_d.ts": "import { WindowHide } from '../runtime/runtime'\n",+ }+ )+ finding = _finding("WindowHide", file_path="runtime/runtime.js")+ clamp_unverified_absence([finding], source)++ assert finding.confidence == RISK_CAP_CONFIDENCE++ def test_a_non_code_file_counts_as_a_use(self):+ # The handler is named by string from infrastructure config, which is+ # the only place in the repository that knows it is an entry point.+ source = _src(+ broker_mjs="export const handleEvent = async () => 1;\n",+ main_tf='resource "aws_lambda_function" "b" {\n handler = "broker.handleEvent"\n}\n',+ )+ finding = _finding("handleEvent", file_path="broker.mjs")+ clamp_unverified_absence([finding], source)++ assert finding.confidence == RISK_CAP_CONFIDENCE+ assert "main.tf" in finding.evidence[-1]+++class TestOwnFile:+ """The same-translation-unit shape, where the only use is in the declaring file."""++ def test_use_below_its_own_span_caps(self):+ source = _src(+ src__sky_cpp=(+ "struct Row { float a; };\n"+ "float compute() {\n"+ " Row scratch{1.0f};\n"+ " return scratch.a;\n"+ "}\n"+ )+ )+ finding = _finding("Row", file_path="src/sky.cpp", start_line=1, end_line=1)+ clamp_unverified_absence([finding], source)++ assert finding.confidence == RISK_CAP_CONFIDENCE+ assert "src/sky.cpp:3" in finding.evidence[-1]++ def test_a_recursive_call_inside_the_span_is_not_a_use(self):+ # The symbol names itself, which is not evidence that anything else does.+ source = _src(+ src__rec_py=(+ "def walk(n):\n"+ " if n:\n"+ " return walk(n - 1)\n"+ " return 0\n"+ )+ )+ finding = _finding("walk", file_path="src/rec.py", start_line=1, end_line=4)+ clamp_unverified_absence([finding], source)++ assert finding.confidence == 1.0+ assert finding.safe_to_delete is True++ def test_unknown_span_cannot_be_answered_and_caps(self):+ source = _src(src__lib_kt="class Registry\n")+ finding = _finding("Registry", start_line=None, end_line=None)+ clamp_unverified_absence([finding], source)++ assert finding.confidence == RISK_CAP_CONFIDENCE+ # The repository *was* searched and nothing was found in another file.+ # Only the declaration's own extent was unknown, so saying the repo+ # could not be searched would describe something that did not happen.+ assert "could not be bounded" in finding.evidence[-1]++ def test_a_bare_carriage_return_does_not_shift_the_span(self):+ # ``bytes.splitlines`` breaks on a lone \r and the parser's row counter+ # does not, so a progress-bar print earlier in the file used to push+ # every later line out of its recorded span — which made a symbol's own+ # recursive call read as an external use.+ source = _src(+ src__rec_py=(+ 'def progress():\n'+ ' print("\rworking\r", end="")\n'+ '\n'+ 'def walk(n):\n'+ ' if n:\n'+ ' return walk(n - 1)\n'+ ' return 0\n'+ )+ )+ finding = _finding("walk", file_path="src/rec.py", start_line=4, end_line=7)+ clamp_unverified_absence([finding], source)++ assert finding.confidence == 1.0++ def test_overloads_do_not_count_each_other_as_uses(self):+ # Two declarations share a name, so each one's header sits outside the+ # other's span. Nothing calls either.+ source = _src(+ src__util_cpp=(+ "void process(int a) {\n (void)a;\n}\n"+ "\n"+ "void process(float b) {\n (void)b;\n}\n"+ )+ )+ first = _finding("process", file_path="src/util.cpp", start_line=1, end_line=3)+ second = _finding("process", file_path="src/util.cpp", start_line=5, end_line=7)+ clamp_unverified_absence([first, second], source)++ assert first.confidence == 1.0+ assert second.confidence == 1.0++ def test_a_use_inside_a_same_named_symbols_body_still_counts(self):+ # Only a sibling's declaration header is discounted, never its body. A+ # span that encloses an unrelated same-named symbol's real call site+ # would otherwise swallow that use and leave a live symbol at the top+ # of the scale, which is the one outcome this module must not produce.+ source = _src(+ src__util_cpp=(+ "class process {\n"+ " void run() {\n"+ " other(process());\n"+ " }\n"+ "};\n"+ "\n"+ "int process() { return 1; }\n"+ )+ )+ klass = _finding("process", file_path="src/util.cpp", start_line=1, end_line=5)+ func = _finding("process", file_path="src/util.cpp", start_line=7, end_line=7)+ clamp_unverified_absence([klass, func], source)++ assert func.confidence == RISK_CAP_CONFIDENCE+ assert "src/util.cpp:3" in func.evidence[-1]++ def test_one_object_listed_twice_collects_one_evidence_line(self):+ source = _src(+ src__lib_kt="class Registry\n", src__b_kt="fun f() = Registry()\n"+ )+ finding = _finding("Registry")+ clamp_unverified_absence([finding, finding], source)++ assert len(finding.evidence) == 1+++class TestScopeAndSafety:+ """What the clamp must refuse to touch."""++ def test_no_source_access_declines_rather_than_guessing(self):+ finding = _finding("Registry")+ clamp_unverified_absence([finding], {})++ assert finding.confidence == 1.0+ assert finding.evidence == []++ @pytest.mark.parametrize(+ "kind",+ [+ DeadCodeKind.UNREACHABLE_FILE,+ DeadCodeKind.UNUSED_INTERNAL,+ DeadCodeKind.ZOMBIE_PACKAGE,+ ],+ )+ def test_only_unused_exports_are_in_scope(self, kind):+ source = _src(+ src__lib_kt="class Registry\n", src__b_kt="fun f() = Registry()\n"+ )+ finding = _finding("Registry", kind=kind, confidence=0.9)+ clamp_unverified_absence([finding], source)++ assert finding.confidence == 0.9++ def test_never_raises_a_confidence(self):+ # 0.5 is above the cap, so this one is in scope and falls to it. What+ # is being pinned is the direction: a clamp that could move a number+ # up would be a way to invent certainty rather than to withdraw it.+ source = _src(+ src__lib_kt="class Registry\n", src__b_kt="fun f() = Registry()\n"+ )+ finding = _finding("Registry", confidence=0.5)+ clamp_unverified_absence([finding], source)++ assert finding.confidence <= 0.5++ def test_a_finding_already_at_the_cap_is_left_alone(self):+ # Otherwise every low-confidence finding collects a second evidence+ # line saying something its confidence already said.+ source = _src(+ src__lib_kt="class Registry\n", src__b_kt="fun f() = Registry()\n"+ )+ finding = _finding("Registry", confidence=RISK_CAP_CONFIDENCE)+ clamp_unverified_absence([finding], source)++ assert finding.evidence == []++ def test_no_finding_is_ever_removed(self):+ source = _src(+ src__lib_kt="class Registry\n", src__b_kt="fun f() = Registry()\n"+ )+ findings = [_finding("Registry"), _finding("Stranded")]+ result = clamp_unverified_absence(findings, source)++ assert len(result) == 2++ def test_a_name_too_short_to_search_for_is_not_an_absence(self):+ # The identifier scan needs three characters, so a shorter name matches+ # nowhere — including on its own declaration. That is a question we+ # cannot ask, not an answer.+ source = _src(src__lib_kt="class Ab\n")+ finding = _finding("Ab")+ clamp_unverified_absence([finding], source)++ assert finding.confidence == RISK_CAP_CONFIDENCE+ assert "could not be searched" in finding.evidence[-1]++ def test_a_non_ascii_name_is_not_searched_for_by_its_ascii_stump(self):+ # Dropping the non-ASCII characters would search for "caf" and let an+ # unrelated identifier elsewhere read as a use of this symbol.+ source = _src(+ src__lib_py="class café:\n pass\n",+ src__other_py="caf = 1\n",+ )+ finding = _finding("café", file_path="src/lib.py")+ clamp_unverified_absence([finding], source)++ assert "could not be searched" in finding.evidence[-1]+ assert "other.py" not in finding.evidence[-1]++ def test_a_name_the_identifier_scan_cannot_match_is_not_an_absence(self):+ # A JVM or JavaScript synthetic name carries a character the identifier+ # shape does not admit, so the scan would only ever see two shorter+ # tokens and would miss the declaration itself.+ source = _src(+ src__lib_kt="class Foo$Companion\n",+ src__b_kt="val x = Foo$Companion\n",+ )+ finding = _finding("Foo$Companion")+ clamp_unverified_absence([finding], source)++ assert "could not be searched" in finding.evidence[-1]++ def test_a_file_outside_the_indexed_set_is_not_an_absence(self):+ # The scan cannot see the declaration it is standing on, so nothing+ # about this file was established either way.+ source = _src(src__other_kt="fun f() = 1\n")+ finding = _finding("Registry")+ clamp_unverified_absence([finding], source)++ assert finding.confidence == RISK_CAP_CONFIDENCE+ assert "could not be searched" in finding.evidence[-1]diff --git a/tests/unit/dead_code/test_no_threshold_literals.py b/tests/unit/dead_code/test_no_threshold_literals.pyindex a1e164741..6671ca366 100644--- a/tests/unit/dead_code/test_no_threshold_literals.py+++ b/tests/unit/dead_code/test_no_threshold_literals.py@@ -47,6 +47,7 @@ _PACKAGES = pathlib.Path(__file__).resolve().parents[3] / "packages"#: Modules that decide, cap, or bucket by the dead-code confidence tiers._GUARDED = ["core/src/repowise/core/analysis/dead_code/analyzer.py",+ "core/src/repowise/core/analysis/dead_code/name_occurrences.py","core/src/repowise/core/analysis/dead_code/risk_factors.py","core/src/repowise/core/persistence/crud/analysis/dead_code.py","cli/src/repowise/cli/commands/dead_code_cmd.py",