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 calling runtime-loaded web assets safe to delete (#1463)
Raghav Chamadiya31d99151ddd2
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.pyindex 4aadb5be4..e13b5a288 100644--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py@@ -922,7 +922,7 @@ class DeadCodeAnalyzer:confidence = min(confidence, 0.4)# Runtime-load risk factors (config / bootstrap / database /- # environment / script). These are files the never-flag allowlist+ # environment / script / asset). These are files the never-flag allowlist# didn't catch but that are commonly referenced outside static# imports, so "in_degree=0" is weak evidence. Cap confidence below the# deletion-ready threshold and surface the factors as evidence — the@@ -1278,7 +1278,7 @@ class DeadCodeAnalyzer:confidence = min(confidence, 0.4)# Runtime-load risk factors for the defining file (config /- # bootstrap / database / environment / script): symbols in+ # bootstrap / database / environment / script / asset): symbols in# such files are often wired up reflectively, so cap below the# deletion-ready threshold and tag the finding for review.risk_factors = path_risk_factors(str(node))diff --git a/packages/core/src/repowise/core/analysis/dead_code/risk_factors.py b/packages/core/src/repowise/core/analysis/dead_code/risk_factors.pyindex df4b2a534..54890613e 100644--- a/packages/core/src/repowise/core/analysis/dead_code/risk_factors.py+++ b/packages/core/src/repowise/core/analysis/dead_code/risk_factors.py@@ -5,11 +5,11 @@ The ``_NEVER_FLAG_PATTERNS`` allowlist in :mod:`constants` removes files weare *confident* are framework/config/generated (``alembic/versions/*``,``*.config.*``, ``page.tsx``, …). This module is the softer, complementarylayer: a file that *escaped* that allowlist but still looks like a config /-bootstrap / database / environment / script file. Such a file is not removed-from the report — surfacing likely-unused code is the whole point — but it is-capped below the deletion-ready threshold and tagged with the risk factors-that explain why, so the UI can present it as a *candidate to review* rather-than as *safe to delete*.+bootstrap / database / environment / script / runtime-asset file. Such a file+is not removed from the report, since surfacing likely-unused code is the+whole point. It is capped below the deletion-ready threshold and tagged with+the risk factors that explain why, so the UI can present it as a *candidate to+review* rather than as *safe to delete*.Static reachability + git age cannot *prove* a file is unused; it can onlysay nothing imports it. For ordinary modules that is a strong signal. For a@@ -17,6 +17,12 @@ say nothing imports it. For ordinary modules that is a strong signal. For ais wired up by a runtime loader, a config key, or a string path rather than astatic import — it is not. This module encodes that asymmetry.+Note which way git age points for these files. Confidence rises the longer a+file goes untouched, but a runtime-loaded asset is written once and then+correct forever, so the top confidence tier is precisely where it lands. Age+is evidence of deadness only for a file that something would have had to+import in the first place.+The classifier is pure path inspection, so it can run both at analysis time(to cap the persisted finding) and at read time (to defensively re-deriveeffective safety for findings persisted before this logic existed).@@ -72,6 +78,29 @@ _FILENAME_RISK_TOKENS: dict[str, str] = {"migrations": "database","datastore": "database","sqlite": "database",+ # runtime-loaded web asset+ #+ # The sharpest case in this module. A service worker is registered by URL,+ # so nothing imports it, and it is written once and then correct forever,+ # so it ages into the top confidence tier. Both halves of the evidence+ # point at "delete me" for a file that must not be deleted.+ #+ # Only ``sw``, covering ``sw.js`` and ``firebase-messaging-sw.js``. A bare+ # ``worker`` token would catch every ``queue_worker.py`` and thread-pool+ # module in the world, so the hyphenated ``service-worker`` spelling is+ # handled as a token pair below instead. ``manifest`` is deliberately+ # absent: ``manifest.json`` and ``.webmanifest`` are non-code languages and+ # never become findings, and ``*/manifest.ts`` is already in+ # ``_NEVER_FLAG_PATTERNS``, so the token's only remaining reach would be+ # real modules like ``manifest.rs``.+ "sw": "asset",+}++# Filename token *pairs* → risk-factor tag. ``_SPLIT_RE`` splits on ``. _ -``,+# so ``service-worker.ts`` and ``service_worker.js`` both yield the pair below+# while ``queue_worker.py`` does not.+_FILENAME_RISK_TOKEN_PAIRS: dict[frozenset[str], str] = {+ frozenset({"service", "worker"}): "asset",}# Directory-segment tokens → risk-factor tag. A file *inside* one of these@@ -89,6 +118,12 @@ _DIRECTORY_RISK_TOKENS: dict[str, str] = {"scripts": "script","bin": "script","tasks": "script",+ # Served verbatim rather than bundled, so nothing in the tree imports it.+ # ``assets`` is deliberately absent: ``src/assets/`` is the Vite / Vue /+ # Angular convention for *bundled* source, which is imported normally.+ "public": "asset",+ "static": "asset",+ "www": "asset",}# Human-readable one-liners per factor, used to build evidence strings.@@ -98,6 +133,7 @@ _FACTOR_BLURB: dict[str, str] = {"bootstrap": "bootstrap/entry-point","database": "database/schema","script": "script/task",+ "asset": "runtime-loaded web asset",}_SPLIT_RE = re.compile(r"[._\-]+")@@ -108,8 +144,9 @@ def path_risk_factors(file_path: str) -> tuple[str, ...]:Empty tuple means no risk factor — an ordinary module. A non-empty resultmeans the file looks like the kind of thing that is referenced outside- normal static imports (config, bootstrap, database, environment, script),- so a "no importers" finding for it is weaker evidence than it looks.+ normal static imports (config, bootstrap, database, environment, script,+ runtime asset), so a "no importers" finding for it is weaker evidence than+ it looks."""if not file_path:return ()@@ -119,11 +156,18 @@ def path_risk_factors(file_path: str) -> tuple[str, ...]:factors: set[str] = set()# Filename tokens (includes the extension, which never matches a token).- for token in _SPLIT_RE.split(p.name.lower()):+ tokens = set(_SPLIT_RE.split(p.name.lower()))+ for token in tokens:tag = _FILENAME_RISK_TOKENS.get(token)if tag:factors.add(tag)+ # Token pairs, for names whose signal is the combination rather than any+ # one word (``service-worker`` vs an ordinary ``worker``).+ for pair, tag in _FILENAME_RISK_TOKEN_PAIRS.items():+ if pair <= tokens:+ factors.add(tag)+# Directory segments.for segment in p.parent.parts:tag = _DIRECTORY_RISK_TOKENS.get(segment.lower())diff --git a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py b/packages/server/src/repowise/server/mcp_server/tool_dead_code.pyindex da43b4d7c..8cc5094b4 100644--- a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py+++ b/packages/server/src/repowise/server/mcp_server/tool_dead_code.py@@ -400,8 +400,9 @@ def _effective_safe(f: Any) -> bool:"""Re-derive deletion-readiness for a DeadCodeFinding ORM row.Mirrors the API/CLI: the persisted boolean is only ever downgraded, never- trusted blindly, so config/bootstrap/database/environment/script files (and- findings written before risk factors existed) never read as safe-to-delete.+ trusted blindly, so config/bootstrap/database/environment/script/asset+ files (and findings written before risk factors existed) never read as+ safe-to-delete."""return effective_safe_to_delete(f.confidence, f.file_path, f.safe_to_delete)diff --git a/packages/types/src/dead-code.ts b/packages/types/src/dead-code.tsindex a49ed8b37..1ea4edcb1 100644--- a/packages/types/src/dead-code.ts+++ b/packages/types/src/dead-code.ts@@ -57,7 +57,8 @@ export interface DeadCodeFinding {safe_to_delete: boolean;/*** Runtime-load risk factors (config / bootstrap / database / environment /- * script). Non-empty means a review candidate, never deletion-ready.+ * script / asset). Non-empty means a review candidate, never+ * deletion-ready.*/risk_factors?: string[];primary_owner: string | null;diff --git a/tests/unit/dead_code/test_risk_factors.py b/tests/unit/dead_code/test_risk_factors.pyindex 9140bf61c..df31d0284 100644--- a/tests/unit/dead_code/test_risk_factors.py+++ b/tests/unit/dead_code/test_risk_factors.py@@ -35,6 +35,22 @@ from tests.unit.dead_code._helpers import _build_graph, _old_date("config/loader.py", {"config"}),("scripts/cleanup.py", {"script"}),("db/connection.py", {"database"}),+ # Runtime-loaded web assets: fetched by URL, never imported. Each+ # filename case sits outside a served directory, so it exercises the+ # filename token rather than inheriting the tag from its parent.+ ("src/sw.js", {"asset"}),+ ("src/firebase-messaging-sw.js", {"asset"}),+ ("src/service-worker.ts", {"asset"}),+ ("src/service_worker.js", {"asset"}),+ # A generic name inside a served directory inherits the tag.+ ("public/analytics.js", {"asset"}),+ ("static/legacy.js", {"asset"}),+ # ...but an ordinary worker module is not a web asset. A bare "worker"+ # token would cap every queue and thread-pool module in the repo.+ ("src/queue_worker.py", set()),+ ("app/worker.ts", set()),+ # src/assets is the bundled-source convention, not a served directory.+ ("src/assets/theme.ts", set()),# Ordinary modules — no risk factor.("src/services/user_service.py", set()),("pkg/old_unused.py", set()),@@ -131,3 +147,60 @@ def test_analyzer_caps_risk_file_even_when_old() -> None:ordinary = by_path["src/old_module.js"]assert ordinary.safe_to_delete is Trueassert ordinary.risk_factors == []+++def test_analyzer_caps_untouched_service_worker() -> None:+ """A service worker is the worst case for a staleness-driven confidence.++ It is registered by URL, so nothing imports it, and it is written once and+ then correct forever, so it ages into the 1.0 tier. Both halves of the+ evidence point at "delete me" for a file that must not be deleted.+ """+ node = {+ "language": "javascript",+ "is_entry_point": False,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": 4,+ "symbols": [],+ }+ g = _build_graph(+ nodes={+ "src/sw.js": dict(node),+ "src/old_module.js": dict(node),+ },+ )+ git_meta = {+ path: {+ "commit_count_90d": 0,+ "last_commit_at": _old_date(days=400),+ "age_days": 400,+ }+ for path in ("src/sw.js", "src/old_module.js")+ }++ analyzer = DeadCodeAnalyzer(g, git_meta_map=git_meta)+ report = analyzer.analyze(+ {+ "detect_unused_exports": False,+ "detect_zombie_packages": False,+ "min_confidence": 0.0,+ }+ )+ by_path = {f.file_path: f for f in report.findings}++ sw = by_path["src/sw.js"]+ assert sw.safe_to_delete is False+ assert set(sw.risk_factors) == {"asset"}+ # Capped to exactly the cap, which is also the default min_confidence+ # floor across the CLI, REST router and MCP tool, so the finding is+ # demoted to a review candidate but still surfaces.+ assert sw.confidence == RISK_CAP_CONFIDENCE++ assert by_path["src/old_module.js"].safe_to_delete is True+++def test_effective_safe_downgrades_persisted_service_worker() -> None:+ """Read-time re-derivation, so an index built before this fix is corrected+ without a re-index."""+ assert effective_safe_to_delete(1.0, "src/sw.js", stored_safe=True) is False