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(dead-code): one owner for the confidence tier boundaries (#1574)
Swati Ahuja74b47c4fabcd
diff --git a/docs/architecture/ARCHITECTURE.md b/docs/architecture/ARCHITECTURE.mdindex 7ddbb40ea..115cba618 100644--- a/docs/architecture/ARCHITECTURE.md+++ b/docs/architecture/ARCHITECTURE.md@@ -926,11 +926,17 @@ The analyzer runs after `GitIndexer` during init (Step 3.6) and optionally durin- `zombie_package` — monorepo package with no incoming `inter_package` edges**Confidence scoring (conservative — when in doubt, do NOT flag):**-- Unreachable + no commits in 90d + last commit > 6 months → 1.0-- Unreachable + no commits in 90d → 0.7+- Unreachable + no commits in 90d + last commit > 1 year → 1.0+- Unreachable + no commits in 90d + last commit > 6 months → 0.9+- Unreachable + no commits in 90d + last commit > 90 days → 0.8+- Unreachable + no commits in 90d + file under 30 days old → 0.55+- Unreachable + no commits in 90d, no commit date to age it by → 0.7- Unreachable but recently touched → 0.4-- `safe_to_delete` only set at confidence >= 0.7, and NOT for files matching- dynamic patterns (`*Plugin*`, `*Handler*`, `*Adapter*`, `*Middleware*`)+- `safe_to_delete` only set at confidence >= `SAFE_CONFIDENCE_THRESHOLD` (0.7),+ and NOT for files matching dynamic patterns (`*Plugin*`, `*Handler*`,+ `*Adapter*`, `*Middleware*`), and NOT for paths carrying a runtime-load risk+ factor. The rungs above are an evidence scale, not the tier boundaries; the+ boundaries live in `core/analysis/dead_code/risk_factors.py`**Never flagged as dead:**- `__init__.py` public re-exportsdiff --git a/docs/architecture/deep-dives.md b/docs/architecture/deep-dives.mdindex 5d2cdf2d2..d2b2deac0 100644--- a/docs/architecture/deep-dives.md+++ b/docs/architecture/deep-dives.md@@ -106,13 +106,20 @@ Files in the same package as `importlib.import_module()` or `__import__()` callsThis is where it gets interesting. A file with zero importers might be dead, or it might be actively used via dynamic loading. Git history helps distinguish:```-if no_commits_in_90_days AND file_older_than_180_days:- confidence = 1.0 # Almost certainly dead- reasoning: Nobody imports it AND nobody has touched it in 6 months+if no_commits_in_90_days AND last_commit_over_364_days_ago:+ confidence = 1.0 # Almost certainly dead — untouched for a year+++elif no_commits_in_90_days AND last_commit_over_179_days_ago:+ confidence = 0.9++elif no_commits_in_90_days AND last_commit_over_89_days_ago:+ confidence = 0.8++elif no_commits_in_90_days AND file_under_30_days_old:+ confidence = 0.55 # Recently created — may be work in progresselif no_commits_in_90_days:- confidence = 0.7 # Probably dead- reasoning: Nobody imports it AND no recent activity, but file isn't ancient+ confidence = 0.7 # No recent activity, and no commit date to age it byelse: # has recent commitsconfidence = 0.4 # Suspicious but uncertain@@ -120,15 +127,21 @@ else: # has recent commits(maybe dynamically loaded, maybe a script run manually)```+The rungs are an evidence scale, not tier boundaries. The high/medium tier cuts+are `SAFE_CONFIDENCE_THRESHOLD` and `RISK_CAP_CONFIDENCE` in+`core/analysis/dead_code/risk_factors.py`, which every comparison reads by name.+**Intuition:** If a file is truly dead, it stops receiving commits. Active files — even dynamically loaded ones — still get bug fixes and updates. The combination of in_degree=0 (structural signal) and no-recent-commits (behavioral signal) gives high confidence.**safe_to_delete computation:**```-safe_to_delete = (confidence >= 0.7) AND (not matches_dynamic_patterns)+safe_to_delete = (confidence >= SAFE_CONFIDENCE_THRESHOLD) # 0.7+ AND (not matches_dynamic_patterns)+ AND (no runtime-load risk factors on the path)```-A file is only marked safe to delete if we're confident it's dead AND it doesn't look like a plugin/handler/adapter that might be dynamically loaded.+A file is only marked safe to delete if we're confident it's dead, it doesn't look like a plugin/handler/adapter that might be dynamically loaded, and its path doesn't look like config / bootstrap / database / environment / script / runtime-asset code. That last condition is re-derived at read time by `effective_safe_to_delete`, so a finding persisted before the risk factors existed is still evaluated against them.#### Strategy 2: Unused Exportsdiff --git a/docs/layers/DEAD_CODE.md b/docs/layers/DEAD_CODE.mdindex eaa6ea36e..25d7b7415 100644--- a/docs/layers/DEAD_CODE.md+++ b/docs/layers/DEAD_CODE.md@@ -77,12 +77,25 @@ Then it only ever goes down. Two caps apply:- **Dynamic imports nearby.** If any file in the same directory uses a runtimeloader, confidence is capped at `0.40`.- **Runtime-load risk factors.** If the path looks like config, environment,- bootstrap, database, or script code (`config`, `settings`, `env`, `bootstrap`,- `startup`, `entrypoint`, `database`, `db`, `schema`, `seed`, `migration`, or a- `scripts/` / `bin/` / `tasks/` directory), confidence is capped at `0.40` and- the finding carries an evidence line explaining why. These are exactly the- files wired up by a config key or a string path rather than an import, so- "nothing imports it" is weak evidence.+ bootstrap, database, script, or runtime-asset code, confidence is capped at+ `0.40` and the finding carries an evidence line explaining why. These are+ exactly the files wired up by a config key or a string path rather than an+ import, so "nothing imports it" is weak evidence. The full token set, matched+ against the filename split on `. _ -` and against directory segments:++ | Factor | Filename tokens | Directory segments |+ |---|---|---|+ | `config` | `config`, `configs`, `configuration`, `conf`, `settings`, `setting`, `setup` | `config/`, `configs/`, `settings/` |+ | `environment` | `env`, `environment`, `environ`, `dotenv` | `env/`, `environments/` |+ | `bootstrap` | `bootstrap`, `startup`, `entrypoint` | `bootstrap/` |+ | `database` | `database`, `db`, `schema`, `seed`, `seeds`, `migration`, `migrations`, `datastore`, `sqlite` | `database/`, `db/`, `migrations/` |+ | `script` | — | `scripts/`, `bin/`, `tasks/` |+ | `asset` | `sw`, plus the token pair `service` + `worker` | `public/`, `static/`, `www/` |++ Broad identifiers (`app`, `main`, `index`, `core`, `base`, `util`) are+ deliberately excluded: they would cap ordinary modules. `src/assets/` is+ likewise absent, because that is the Vite / Vue / Angular convention for+ *bundled* source, which is imported normally.## Confidence tiers and `safe_to_delete`diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.pyindex 40fc8c97d..9eea7d4ed 100644--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py@@ -43,7 +43,12 @@ from .file_reachability import (is_file_reachable,)from .models import DeadCodeFindingData, DeadCodeKind, DeadCodeReport-from .risk_factors import RISK_CAP_CONFIDENCE, path_risk_factors, risk_evidence+from .risk_factors import (+ RISK_CAP_CONFIDENCE,+ SAFE_CONFIDENCE_THRESHOLD,+ path_risk_factors,+ 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@@ -720,16 +725,20 @@ class DeadCodeAnalyzer:# deserves.findings = self._clamp_for_unindexed_importers(findings)- min_conf = cfg.get("min_confidence", 0.4)+ min_conf = cfg.get("min_confidence", RISK_CAP_CONFIDENCE)hidden_below_threshold = sum(1 for f in findings if f.confidence < min_conf)findings = [f for f in findings if f.confidence >= min_conf]now = datetime.now(UTC)deletable = sum(f.lines for f in findings if f.safe_to_delete)- high = sum(1 for f in findings if f.confidence >= 0.7)- medium = sum(1 for f in findings if 0.4 <= f.confidence < 0.7)- low = sum(1 for f in findings if f.confidence < 0.4)+ high = sum(1 for f in findings if f.confidence >= SAFE_CONFIDENCE_THRESHOLD)+ medium = sum(+ 1+ for f in findings+ if RISK_CAP_CONFIDENCE <= f.confidence < SAFE_CONFIDENCE_THRESHOLD+ )+ low = sum(1 for f in findings if f.confidence < RISK_CAP_CONFIDENCE)return DeadCodeReport(repo_id="",@@ -891,9 +900,14 @@ class DeadCodeAnalyzer:else:confidence = 0.4+ # The ladder above is an evidence scale, not a tier boundary: its rungs+ # stay literal so moving a threshold does not silently re-score how+ # strong the git signal is. Everything below compares against or caps+ # to a threshold, so it reads the constants.+# Reduce confidence when dynamic imports exist in the same package.if self._dynamic_import_dirs and str(Path(node).parent) in self._dynamic_import_dirs:- confidence = min(confidence, 0.4)+ confidence = min(confidence, RISK_CAP_CONFIDENCE)# Runtime-load risk factors (config / bootstrap / database /# environment / script / asset). These are files the never-flag allowlist@@ -905,14 +919,14 @@ class DeadCodeAnalyzer:if risk_factors:confidence = min(confidence, RISK_CAP_CONFIDENCE)- safe = confidence >= 0.7+ safe = confidence >= SAFE_CONFIDENCE_THRESHOLDif safe and self._matches_dynamic_patterns(node, dynamic_patterns):safe = Falseevidence = ["in_degree=0 (no files import this)"]if commit_90d == 0:evidence.append("No commits in last 90 days")- if self._dynamic_import_files and confidence <= 0.4:+ if self._dynamic_import_files and confidence <= RISK_CAP_CONFIDENCE:evidence.append("Package uses dynamic imports or runtime-resolved edges")risk_line = risk_evidence(risk_factors)if risk_line:@@ -1248,7 +1262,7 @@ class DeadCodeAnalyzer:# confident dead code. Generic across all languages# (C#, Java, Kotlin, Scala, Swift protocols, TS).if sym.get("kind") == "interface" and not self._file_has_implementors(node):- confidence = min(confidence, 0.4)+ confidence = min(confidence, RISK_CAP_CONFIDENCE)# COM / IUnknown / IDispatch contract methods# (``QueryInterface``, ``AddRef``, ``Release``, …) are@@ -1257,7 +1271,7 @@ class DeadCodeAnalyzer:# safe-to-delete threshold so we never ship them as# confident dead code on Windows / COM-heavy C++ repos.if is_contract_method(sym_name, sym.get("kind"), sym.get("language", "unknown")):- confidence = min(confidence, 0.4)+ confidence = min(confidence, RISK_CAP_CONFIDENCE)# Runtime-load risk factors for the defining file (config /# bootstrap / database / environment / script / asset): symbols in@@ -1267,7 +1281,7 @@ class DeadCodeAnalyzer:if risk_factors:confidence = min(confidence, RISK_CAP_CONFIDENCE)- safe = confidence >= 0.7+ safe = confidence >= SAFE_CONFIDENCE_THRESHOLDgit_meta = self.git_meta_map.get(str(node), {})diff --git a/packages/server/src/repowise/server/chat_tools.py b/packages/server/src/repowise/server/chat_tools.pyindex 8411e1558..ac0f66ca6 100644--- a/packages/server/src/repowise/server/chat_tools.py+++ b/packages/server/src/repowise/server/chat_tools.py@@ -11,6 +11,8 @@ from collections.abc import Awaitable, Callablefrom dataclasses import dataclassfrom typing import Any+from repowise.core.analysis.dead_code.risk_factors import RISK_CAP_CONFIDENCE+logger = logging.getLogger(__name__)@@ -203,8 +205,11 @@ _TOOL_SCHEMAS: list[dict[str, Any]] = [},"min_confidence": {"type": "number",- "description": "Minimum confidence threshold (default 0.4; matches RISK_CAP_CONFIDENCE).",- "default": 0.4,+ "description": (+ f"Minimum confidence threshold (default {RISK_CAP_CONFIDENCE}; "+ "matches RISK_CAP_CONFIDENCE)."+ ),+ "default": RISK_CAP_CONFIDENCE,},"safe_only": {"type": "boolean",diff --git a/packages/types/src/dead-code.ts b/packages/types/src/dead-code.tsindex 1ea4edcb1..8edc024b4 100644--- a/packages/types/src/dead-code.ts+++ b/packages/types/src/dead-code.ts@@ -41,6 +41,33 @@ export function deadCodeConfidenceTier(confidence: number): "high" | "medium" |return "low";}+/**+ * Human-readable label per runtime-load risk factor.+ *+ * Mirrors `_FACTOR_BLURB` in `core/analysis/dead_code/risk_factors.py`, which+ * is where the engine's own evidence line gets its wording. The slugs are an+ * API vocabulary, not English: joining them straight into a sentence renders+ * "Runtime-load risk (config, asset)" where the engine says+ * "configuration, runtime-loaded web asset".+ *+ * Keyed on every tag `path_risk_factors` can emit; a contract test+ * (`tests/unit/dead_code/test_confidence_parity.py`) fails when the two key+ * sets drift, so a new engine factor cannot ship without a label here.+ */+export const DEAD_CODE_RISK_FACTOR_LABELS: Record<string, string> = {+ config: "configuration",+ environment: "environment/bootstrap",+ bootstrap: "bootstrap/entry-point",+ database: "database/schema",+ script: "script/task",+ asset: "runtime-loaded web asset",+};++/** Label for one risk factor, falling back to the raw slug for an unknown tag. */+export function deadCodeRiskFactorLabel(factor: string): string {+ return DEAD_CODE_RISK_FACTOR_LABELS[factor] ?? factor;+}+export interface DeadCodeFinding {id: string;kind: string;diff --git a/packages/ui/__tests__/dead-code/risk-factor-labels.test.tsx b/packages/ui/__tests__/dead-code/risk-factor-labels.test.tsxnew file mode 100644index 000000000..6ed10cc34--- /dev/null+++ b/packages/ui/__tests__/dead-code/risk-factor-labels.test.tsx@@ -0,0 +1,61 @@+/**+ * Risk factors reach a reader as English, not as API slugs.+ *+ * Both surfaces that render `risk_factors` used to `join(", ")` the raw tags,+ * so the badge tooltip and the agent prompt said "config, asset" where the+ * engine's own evidence line says "configuration, runtime-loaded web asset".+ *+ * The two were uncovered in different ways, which is worth keeping straight.+ * The tooltip was *executed* with a real factor — `dead-code-view`'s fixture+ * gives one finding `risk_factors: ["bootstrap"]` and the table renders it —+ * but nothing asserted on the text. The prompt branch was never executed at+ * all: the only prompt test seeds from `safeFindings`, which filters on+ * `safe_to_delete`, and every safe fixture has an empty factor list.+ */++import { describe, it, expect } from "vitest";+import { render, screen } from "@testing-library/react";+import type { DeadCodeFinding } from "@repowise-dev/types/dead-code";++import { FindingSafety } from "../../src/dead-code/finding-cells.js";+import { buildDeadCodeAiPrompt } from "../../src/health/ai-prompt-builder.js";++function finding(over: Partial<DeadCodeFinding>): DeadCodeFinding {+ return {+ id: "f1",+ kind: "unreachable_file",+ file_path: "public/sw.js",+ symbol_name: null,+ symbol_kind: null,+ confidence: 0.4,+ reason: "No importers",+ lines: 10,+ safe_to_delete: false,+ risk_factors: [],+ primary_owner: null,+ status: "open",+ note: null,+ ...over,+ };+}++describe("risk-factor labels", () => {+ it("renders the badge tooltip with labels, not slugs", () => {+ render(<FindingSafety finding={finding({ risk_factors: ["asset", "config"] })} />);+ const badge = screen.getByTitle(/Runtime-load risk/);+ expect(badge.getAttribute("title")).toContain("runtime-loaded web asset, configuration");+ expect(badge.getAttribute("title")).not.toContain("asset, config)");+ });++ it("labels the risk factors in the dead-code agent prompt", () => {+ const prompt = buildDeadCodeAiPrompt({+ findings: [{ file_path: "public/sw.js", lines: 10, risk_factors: ["asset"] }],+ });+ expect(prompt).toContain("Runtime-load risk to rule out first: runtime-loaded web asset");+ });++ it("falls back to the raw tag for a factor the label map has not learned", () => {+ render(<FindingSafety finding={finding({ risk_factors: ["telemetry"] })} />);+ expect(screen.getByTitle(/Runtime-load risk/).getAttribute("title")).toContain("telemetry");+ });+});diff --git a/packages/ui/src/dead-code/dead-code-lede.tsx b/packages/ui/src/dead-code/dead-code-lede.tsxindex 6ecd97799..007adb1c8 100644--- a/packages/ui/src/dead-code/dead-code-lede.tsx+++ b/packages/ui/src/dead-code/dead-code-lede.tsx@@ -14,7 +14,7 @@*/import type { ReactNode } from "react";-import type { DeadCodeSummary } from "@repowise-dev/types/dead-code";+import { DEAD_CODE_CONFIDENCE, type DeadCodeSummary } from "@repowise-dev/types/dead-code";import { PageLede } from "../shared/page-lede";import { StatRibbon, type RibbonStat } from "../stats/stat-ribbon";@@ -89,7 +89,7 @@ export function DeadCodeLede({label: "High confidence",value: formatNumber(high),valueColor: high > 0 ? "text-[var(--color-success)]" : undefined,- sub: "confidence 0.7 or better",+ sub: `confidence ${DEAD_CODE_CONFIDENCE.HIGH} or better`,hint: "No dynamic reference, no re-export, no entry point that we can see.",},{diff --git a/packages/ui/src/dead-code/finding-cells.tsx b/packages/ui/src/dead-code/finding-cells.tsxindex 9e19d8d4e..e8f23f1a3 100644--- a/packages/ui/src/dead-code/finding-cells.tsx+++ b/packages/ui/src/dead-code/finding-cells.tsx@@ -13,6 +13,7 @@ import { toFriendlyMessage } from "../lib/errors";import { cn } from "../lib/cn";import {deadCodeConfidenceTier,+ deadCodeRiskFactorLabel,type DeadCodeFinding,type DeadCodeStatus,} from "@repowise-dev/types/dead-code";@@ -155,7 +156,7 @@ export function FindingSafety({ finding }: { finding: DeadCodeFinding }) {variant="default"title={finding.risk_factors && finding.risk_factors.length > 0- ? `Runtime-load risk (${finding.risk_factors.join(", ")}) - verify it isn't loaded outside static imports before deleting`+ ? `Runtime-load risk (${finding.risk_factors.map(deadCodeRiskFactorLabel).join(", ")}) - verify it isn't loaded outside static imports before deleting`: "Lower confidence - verify before deleting"}>diff --git a/packages/ui/src/health/ai-prompt-builder.ts b/packages/ui/src/health/ai-prompt-builder.tsindex cca916bbf..f5de05b94 100644--- a/packages/ui/src/health/ai-prompt-builder.ts+++ b/packages/ui/src/health/ai-prompt-builder.ts@@ -12,6 +12,8 @@* follow-up questions before making its first move.*/+import { deadCodeRiskFactorLabel } from "@repowise-dev/types/dead-code";+import { biomarkerInfo, CATEGORY_LABEL } from "./biomarker-glossary";import type { RefactoringTarget } from "./refactoring-card";import {@@ -624,7 +626,9 @@ export function buildDeadCodeAiPrompt({`- \`${path}\`${symbols ? ` — ${symbols}` : ""}`,kinds.length ? ` - Kind: ${kinds.join(", ")}` : null,reason ? ` - Why flagged: ${reason}` : null,- risk.length ? ` - Runtime-load risk to rule out first: ${risk.join(", ")}` : null,+ risk.length+ ? ` - Runtime-load risk to rule out first: ${risk.map(deadCodeRiskFactorLabel).join(", ")}`+ : null,].filter(Boolean).join("\n");diff --git a/tests/unit/dead_code/test_confidence_parity.py b/tests/unit/dead_code/test_confidence_parity.pyindex 9ce98c766..30dd29b7d 100644--- a/tests/unit/dead_code/test_confidence_parity.py+++ b/tests/unit/dead_code/test_confidence_parity.py@@ -1,7 +1,10 @@-"""Cross-language contract test for dead-code confidence threshold alignment.+"""Cross-language contract tests for the dead-code vocabulary.-Verifies that TypeScript's DEAD_CODE_CONFIDENCE.MEDIUM in packages/types/src/dead-code.ts-matches Python's RISK_CAP_CONFIDENCE in repowise.core.analysis.dead_code.risk_factors.+The TypeScript surface cannot import from Python, so `packages/types/src/dead-code.ts`+hand-mirrors two things the engine owns: the confidence tier boundaries+(`DEAD_CODE_CONFIDENCE` against `RISK_CAP_CONFIDENCE` / `SAFE_CONFIDENCE_THRESHOLD`)+and the risk-factor labels (`DEAD_CODE_RISK_FACTOR_LABELS` against `_FACTOR_BLURB`).+These parse the `.ts` file and fail when either mirror drifts."""from __future__ import annotations@@ -10,6 +13,7 @@ import refrom pathlib import Pathfrom repowise.core.analysis.dead_code.risk_factors import (+ _FACTOR_BLURB,RISK_CAP_CONFIDENCE,SAFE_CONFIDENCE_THRESHOLD,)@@ -53,3 +57,51 @@ def test_ts_confidence_high_matches_python_safe_threshold() -> None:f"Cross-language drift detected! TypeScript DEAD_CODE_CONFIDENCE.HIGH is {ts_high}, "f"but Python SAFE_CONFIDENCE_THRESHOLD is {SAFE_CONFIDENCE_THRESHOLD}.")+++def test_ts_risk_factor_labels_match_python_blurbs() -> None:+ """Every factor the engine can emit has the same label in TypeScript.++ The UI joins `risk_factors` into a sentence, so an unlabelled factor renders+ as its raw API slug ("config, asset" where the engine says "configuration,+ runtime-loaded web asset"). Key sets are compared, not just values, so+ adding a factor in Python fails here until TypeScript learns its wording.+ """+ repo_root = Path(__file__).parents[3]+ ts_file = repo_root / "packages" / "types" / "src" / "dead-code.ts"+ content = ts_file.read_text(encoding="utf-8")++ block = re.search(+ r"DEAD_CODE_RISK_FACTOR_LABELS[^=]*=\s*\{(.*?)\n\};", content, re.DOTALL+ )+ assert block is not None, "Could not parse DEAD_CODE_RISK_FACTOR_LABELS from dead-code.ts"+ ts_labels = dict(re.findall(r"(\w+):\s*\"([^\"]*)\"", block.group(1)))++ assert ts_labels == _FACTOR_BLURB, (+ "Cross-language drift detected between DEAD_CODE_RISK_FACTOR_LABELS in "+ f"dead-code.ts and _FACTOR_BLURB in risk_factors.py.\n TypeScript: {ts_labels}\n"+ f" Python: {_FACTOR_BLURB}"+ )+++def test_every_emittable_factor_has_a_label() -> None:+ """`_FACTOR_BLURB` covers every tag the classifier's tables can produce.++ Guards the other direction from the test above: a new token added to the+ filename / pair / directory tables with a tag nobody wrote a blurb for+ would keep both mirrors consistent and still render the raw slug.+ """+ from repowise.core.analysis.dead_code.risk_factors import (+ _DIRECTORY_RISK_TOKENS,+ _FILENAME_RISK_TOKEN_PAIRS,+ _FILENAME_RISK_TOKENS,+ )++ emittable = (+ set(_FILENAME_RISK_TOKENS.values())+ | set(_FILENAME_RISK_TOKEN_PAIRS.values())+ | set(_DIRECTORY_RISK_TOKENS.values())+ )+ assert emittable <= set(_FACTOR_BLURB), (+ f"risk factors with no blurb: {sorted(emittable - set(_FACTOR_BLURB))}"+ )diff --git a/tests/unit/dead_code/test_no_threshold_literals.py b/tests/unit/dead_code/test_no_threshold_literals.pynew file mode 100644index 000000000..a1e164741--- /dev/null+++ b/tests/unit/dead_code/test_no_threshold_literals.py@@ -0,0 +1,125 @@+"""The dead-code tier boundaries are compared against constants, never literals.++``SAFE_CONFIDENCE_THRESHOLD`` (0.7) and ``RISK_CAP_CONFIDENCE`` (0.4) own the+high/medium boundaries. They were re-typed as bare literals in thirteen places+across three modules that all already imported from ``risk_factors``, or in one+case named the constant in the very string beside the literal.++This *shape* has already shipped a bug, though not on the Python side: the+comment in ``packages/types/src/dead-code.ts`` records three TypeScript surfaces+disagreeing, which put one 0.72 finding in "high" on the summary card and+"Medium" in the breakdown grid at once. That was fixed by giving TypeScript one+owner (#1087). No user-visible bug is known to have come from the Python+copies — they agreed with the constants — which is the argument for removing+them while they still do.++``test_confidence_parity.py`` guards the TypeScript mirror, which cannot import+from Python. This guards the Python side, where importing is available and so a+literal is never the right answer.++``get_dead_code`` brackets its own tiers at 0.8 / 0.5, not at these two, and+that is deliberate — an agent acts on the answer with less review, so the bar+is higher (``docs/layers/DEAD_CODE.md``). Those numbers are a different+decision with a different owner and must not be folded into these constants;+``tool_dead_code.py`` is guarded here only against the 0.7 / 0.4 pair.++Ceiling: matched on source text, over a named file set. It catches the shapes+that recurred — a comparison, a ``min()`` cap, or a ``min_confidence`` default+written against the number instead of the name — and stays blind to a threshold+spelled some other way (``max()``, ``== 0.7``), or appearing in a module not+listed below. It also does not skip docstrings, so a docstring quoting+``>= 0.7`` inside a guarded module would false-positive; that is the safe+direction and no such docstring exists today. Assignments are deliberately not+matched: the git-age evidence ladder in ``_score_unreachable_file`` sets 0.7 and+0.4 as rungs of a scale, not as boundaries, and must not move when a boundary+does.+"""++from __future__ import annotations++import pathlib+import re++import pytest++_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/risk_factors.py",+ "core/src/repowise/core/persistence/crud/analysis/dead_code.py",+ "cli/src/repowise/cli/commands/dead_code_cmd.py",+ "server/src/repowise/server/routers/dead_code.py",+ "server/src/repowise/server/mcp_server/tool_dead_code.py",+ "server/src/repowise/server/chat_tools.py",+]++#: ``0.7``, ``0.70``, ``0.4``, ``0.400`` — the same number, spelled loosely.+_N = r"0\.[47]0*"++_BANNED = (+ # ``confidence >= 0.7``, ``0.4 <= f.confidence``, ``confidence < 0.4``+ re.compile(rf"[<>]=?\s*{_N}\b"),+ # ``min(confidence, 0.4)`` / ``max(confidence, 0.7)``+ re.compile(rf"\b(?:min|max)\([^)]*\b{_N}\b"),+ # ``cfg.get("min_confidence", 0.4)``, ``min_confidence: float = 0.4``+ re.compile(rf"min_confidence\b[^\n]*?=\s*{_N}\b|min_confidence\"\s*,\s*{_N}\b"),+ # A JSON-schema default two lines under a ``"min_confidence"`` key, which+ # is how the thirteenth site hid: no ``min_confidence`` token on its own+ # line for the rule above to see.+ re.compile(rf"\"default\"\s*:\s*{_N}\b"),+)+++def _offending_lines(text: str) -> list[str]:+ hits = []+ for line in text.splitlines():+ stripped = line.strip()+ if stripped.startswith("#"):+ continue+ if any(pattern.search(line) for pattern in _BANNED):+ hits.append(stripped)+ return hits++[email protected]("relative", _GUARDED)+def test_no_bare_threshold_literal(relative: str) -> None:+ path = _PACKAGES / relative+ assert path.exists(), f"guarded module moved or was renamed: {relative}"++ offenders = _offending_lines(path.read_text(encoding="utf-8"))+ assert not offenders, (+ f"{relative} compares against a dead-code confidence threshold by value. "+ "Import SAFE_CONFIDENCE_THRESHOLD / RISK_CAP_CONFIDENCE from "+ "repowise.core.analysis.dead_code.risk_factors instead:\n "+ + "\n ".join(offenders)+ )+++ "probe",+ [+ " safe = confidence >= 0.7",+ " low = sum(1 for f in findings if f.confidence < 0.4)",+ " medium = sum(1 for f in findings if 0.4 <= f.confidence < 0.7)",+ " confidence = min(confidence, 0.4)",+ ' min_conf = cfg.get("min_confidence", 0.4)',+ ' "default": 0.4,',+ # Not removed by this change; the shape a consumer would regress *to*+ # if it stopped importing the constant for its signature default.+ " min_confidence: float = 0.4,",+ # Loose spellings of the same two numbers.+ " safe = confidence >= 0.70",+ " confidence = min(confidence, 0.400)",+ ],+)+def test_guard_catches_the_shapes_that_shipped(probe: str) -> None:+ """The first six are lines this change removed, verbatim; see the comments+ above for the three that are near-misses rather than history."""+ assert _offending_lines(probe) == [probe.strip()]+++def test_guard_ignores_the_evidence_ladder() -> None:+ """Assigning 0.7 as a git-age score is not a boundary and stays legal."""+ assert _offending_lines(" confidence = 0.7\n confidence = 0.4") == []