Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(dead-code): a reachability-root flag separate from the entry-point flag (#2704)

Swati Ahuja0a64814bd5c9
diff --git a/packages/core/alembic/versions/0091_graph_node_reachability_root.py b/packages/core/alembic/versions/0091_graph_node_reachability_root.py
new file mode 100644
index 000000000..cc2b1ace5
--- /dev/null
+++ b/packages/core/alembic/versions/0091_graph_node_reachability_root.py
@@ -0,0 +1,39 @@
+"""graph_nodes: split the dead-code exemption from the entry-point flag.
+
+``is_reachability_root`` marks a file reached from outside the import graph (a
+runner or loader starts it), which dead-code analysis never flags.
+``is_entry_point`` keeps meaning "where a reader enters the system". Existing
+rows back-fill from ``is_entry_point``, the flag that carried both jobs.
+
+Local SQLite stores get the column from ``init_db``'s additive reconciler; this
+migration covers managed Postgres.
+
+Revision ID: 0091
+Revises: 0090
+Create Date: 2026-09-30
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers
+revision: str = "0091"
+down_revision: str | None = "0090"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ op.add_column(
+ "graph_nodes",
+ sa.Column("is_reachability_root", sa.Boolean(), nullable=False, server_default=sa.false()),
+ )
+ op.execute("UPDATE graph_nodes SET is_reachability_root = is_entry_point")
+
+
+def downgrade() -> None:
+ op.drop_column("graph_nodes", "is_reachability_root")
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
index 767068d86..9d9c64c76 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -22,6 +22,7 @@ from typing import Any
import structlog
+from ...entry_candidacy import is_reachability_root
from ...ingestion.models import REACHABILITY_USE_EDGE_TYPES
from .constants import (
_CONTAINER_USE_LANGUAGES,
@@ -1240,10 +1241,10 @@ class DeadCodeAnalyzer:
node_data = self.graph.nodes[node]
if node_data.get("language", "unknown") in _DEAD_CODE_EXEMPT_LANGUAGES:
return None
- # Entry points include framework-instantiated files the runtime constructs.
+ # Roots include framework-instantiated files the runtime constructs.
# Not ``is_file_reachable``: its barrel rescue is scoped to files, and an
# unused symbol defined in a barrel should still be flagged.
- if node_data.get("is_entry_point", False):
+ if is_reachability_root(node_data):
return None
if node_data.get("is_test", False):
return None
diff --git a/packages/core/src/repowise/core/analysis/dead_code/cpp_reachability.py b/packages/core/src/repowise/core/analysis/dead_code/cpp_reachability.py
index 7c3733df6..265d92ec3 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/cpp_reachability.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/cpp_reachability.py
@@ -29,7 +29,7 @@ file-level import graph cannot see:
The helper derives directories from the graph itself; the
:class:`CppWorkspaceIndex` populated during ingestion is not threaded
into the analyzer. Workspace-discovered conditional sources surface
-through the warmup as ``is_never_flag`` / ``is_entry_point`` graph
+through the warmup as ``is_never_flag`` / ``is_reachability_root`` graph
attributes instead.
"""
@@ -38,6 +38,7 @@ from __future__ import annotations
from pathlib import PurePosixPath
from typing import Any
+from ...entry_candidacy import is_reachability_root
from ...ingestion.languages.specs.cpp import INCLUDE_FRAGMENT_EXTENSIONS
from ...ingestion.models import REACHABILITY_USE_EDGE_TYPES
@@ -198,7 +199,7 @@ def is_cpp_file_reachable(
continue
sib_data = graph.nodes.get(sibling, {})
sib_has_importer = graph.in_degree(sibling) > 0
- if sib_data.get("is_entry_point", False):
+ if is_reachability_root(sib_data):
has_sibling_entry = True
break
if _file_defines_entry_function(graph, sibling):
diff --git a/packages/core/src/repowise/core/analysis/dead_code/file_reachability.py b/packages/core/src/repowise/core/analysis/dead_code/file_reachability.py
index fcd167ce1..6ebdb2248 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/file_reachability.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/file_reachability.py
@@ -42,6 +42,7 @@ from dataclasses import dataclass, field
from pathlib import PurePosixPath
from typing import Any
+from repowise.core.entry_candidacy import is_reachability_root
from repowise.core.ids import SYMBOL_SEP, file_path_of, is_external
from .constants import never_flag_match
@@ -276,7 +277,7 @@ def is_file_reachable(
# Conventional entry points, framework-instantiated files and published
# API contracts are reached from outside the graph. Nothing imports
# ``main.py`` either.
- if node_data.get("is_entry_point", False):
+ if is_reachability_root(node_data):
return True
if node_data.get("is_api_contract", False):
return True
diff --git a/packages/core/src/repowise/core/analysis/dead_code/go_reachability.py b/packages/core/src/repowise/core/analysis/dead_code/go_reachability.py
index 11de7fe78..8ba3e9ee2 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/go_reachability.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/go_reachability.py
@@ -30,6 +30,8 @@ from __future__ import annotations
from pathlib import PurePosixPath
from typing import Any
+from ...entry_candidacy import is_reachability_root
+
def _pkg_dir(node: str) -> str:
"""Repo-relative POSIX directory of a ``.go`` file ("" = repo root)."""
@@ -70,7 +72,7 @@ def is_go_file_reachable(
continue
if graph.in_degree(sibling) > 0:
return True
- if graph.nodes.get(sibling, {}).get("is_entry_point", False):
+ if is_reachability_root(graph.nodes.get(sibling, {})):
return True
return False
diff --git a/packages/core/src/repowise/core/analysis/dead_code/jvm_reachability.py b/packages/core/src/repowise/core/analysis/dead_code/jvm_reachability.py
index ba9fbb2d8..30f2f826c 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/jvm_reachability.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/jvm_reachability.py
@@ -20,9 +20,9 @@ JVM source that view misses three real shapes:
META-INF/services, JPMS ``provides ... with``, and Spring Boot autoconfig
imports are *not* re-checked here — those are stamped as
-``is_entry_point`` on the file node during the JVM warmup (see
-:mod:`graph_warmups`), and the analyzer's existing entry-point skip
-honours them before reaching this hook.
+``is_reachability_root`` on the file node during the JVM warmup (see
+:mod:`graph_warmups`), and the analyzer's root skip honours them before
+reaching this hook.
"""
from __future__ import annotations
@@ -30,6 +30,8 @@ from __future__ import annotations
from pathlib import PurePosixPath
from typing import Any
+from ...entry_candidacy import is_reachability_root
+
# Class-level annotation names (without the leading ``@``) that mark the
# bearing class as runtime-instantiated. Kept compact; full Spring
# stereotype recognition + meta-annotation resolution lands in Phase 4
@@ -168,7 +170,7 @@ def is_jvm_file_reachable(
sib_data = graph.nodes.get(sibling, {})
if graph.in_degree(sibling) > 0:
return True
- if sib_data.get("is_entry_point", False):
+ if is_reachability_root(sib_data):
return True
if _file_defines_entry_class(graph, sibling):
return True
diff --git a/packages/core/src/repowise/core/entry_candidacy.py b/packages/core/src/repowise/core/entry_candidacy.py
index 6a447a843..26d60ac63 100644
--- a/packages/core/src/repowise/core/entry_candidacy.py
+++ b/packages/core/src/repowise/core/entry_candidacy.py
@@ -21,8 +21,10 @@ data table — so every rule is unit-testable directly.
from __future__ import annotations
+from collections.abc import Mapping
from functools import cache
from pathlib import PurePosixPath
+from typing import Any
# Generic module stems that *dispatch or re-export* rather than start a program.
# ``index`` (a JS/TS barrel or a per-language resolver shell) and ``mod`` (a Rust
@@ -110,3 +112,13 @@ def not_an_execution_start(path: str, language: str) -> bool:
them too.
"""
return language in non_code_entry_languages() or is_glue_leaf(path)
+
+
+def is_reachability_root(node_data: Mapping[str, Any]) -> bool:
+ """Whether a file node is reached from outside the graph (dead-code exempt).
+
+ Every entry point is a root; the root flag adds files a runner loads without
+ them being entries. Reading both also covers stamps that set only the entry
+ flag and rows stored before the root flag existed.
+ """
+ return bool(node_data.get("is_reachability_root") or node_data.get("is_entry_point"))
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/gtest.py b/packages/core/src/repowise/core/ingestion/framework_edges/gtest.py
index f5b81c7b6..557f14749 100644
--- a/packages/core/src/repowise/core/ingestion/framework_edges/gtest.py
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/gtest.py
@@ -12,7 +12,7 @@ The handler emits two things:
file — so a public ``class BrewFixture : public ::testing::Test {…}``
declared in one header and used as ``TEST_F(BrewFixture, …)`` from
another TU stays reachable;
-* an ``is_entry_point=True`` stamp on the test TU's file node (the warmup
+* an ``is_reachability_root=True`` stamp on the test TU's file node (the warmup
already marks ``LLVMFuzzerTestOneInput`` carriers and the registration-
macro TUs, but ``TEST(…)``-only and ``BENCHMARK(…)``-only TUs are not in
that token list — emitting the flag here keeps them out of
@@ -106,12 +106,12 @@ def _add_gtest_edges(
if not text or not _file_uses_test_framework(text):
continue
- # Mark the TU as an entry point — the test runner discovers TEST
+ # Mark the TU a reachability root — the test runner discovers TEST
# bodies via static-init registration, so no static caller edge
- # exists.
+ # exists. A root, not an entry point: nobody enters the system here.
node = graph.nodes.get(path)
if node is not None:
- node["is_entry_point"] = True
+ node["is_reachability_root"] = True
seen: set[str] = set()
for rx in (_GTEST_FIXTURE_RE, _BOOST_FIXTURE_RE, _CATCH_FIXTURE_RE):
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/spring.py b/packages/core/src/repowise/core/ingestion/framework_edges/spring.py
index c6d4c827d..797ee70b1 100644
--- a/packages/core/src/repowise/core/ingestion/framework_edges/spring.py
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/spring.py
@@ -20,7 +20,7 @@ Expanded in Phase 4 of the JVM parity plan. The handler now covers:
``META-INF/spring/...AutoConfiguration.imports`` file (and
``spring.factories``) to the listed FQNs so the resource file
shows as the importer (the FQN files were already stamped
- ``is_entry_point`` during the JVM warmup).
+ ``is_reachability_root`` during the JVM warmup).
"""
from __future__ import annotations
@@ -311,7 +311,7 @@ def _add_spring_edges(
# ---- 3. Autoconfig consumer edges ----
# Pull the JVM workspace index (already memoised on ctx) and emit edges
# from each autoconfig resource file (key) to the FQN target files.
- # The autoconfig FQN files were stamped ``is_entry_point`` in the
+ # The autoconfig FQN files were stamped ``is_reachability_root`` in the
# warmup; here we add the resource file as a visible importer so the
# autoconfig file itself does not read as orphan.
try:
@@ -332,7 +332,7 @@ def _add_spring_edges(
node_type="file",
language="properties",
path=resource_path,
- is_entry_point=True,
+ is_reachability_root=True,
)
for fqn in fqns:
for target in jvm_index.files_for_fqn(fqn):
@@ -342,7 +342,7 @@ def _add_spring_edges(
for iface_fqn, impls in jvm_index.services.items():
# The resource path isn't tracked per-iface; we use a synthetic
# source so the impl files gain a visible importer. The warmup
- # already stamped them ``is_entry_point``, so this is belt-and-
+ # already stamped them ``is_reachability_root``, so this is belt-and-
# suspenders for the unused_export visibility heuristic.
source = f"META-INF/services/{iface_fqn}"
if source not in graph:
@@ -351,7 +351,7 @@ def _add_spring_edges(
node_type="file",
language="properties",
path=source,
- is_entry_point=True,
+ is_reachability_root=True,
)
for impl_fqn in impls:
for target in jvm_index.files_for_fqn(impl_fqn):
diff --git a/packages/core/src/repowise/core/ingestion/graph/_rehydrate.py b/packages/core/src/repowise/core/ingestion/graph/_rehydrate.py
index e6b2ba31a..ee96013be 100644
--- a/packages/core/src/repowise/core/ingestion/graph/_rehydrate.py
+++ b/packages/core/src/repowise/core/ingestion/graph/_rehydrate.py
@@ -36,6 +36,7 @@ _NODE_ATTR_KEYS = (
"has_error",
"is_test",
"is_entry_point",
+ "is_reachability_root",
"kind",
"name",
"qualified_name",
diff --git a/packages/core/src/repowise/core/ingestion/graph/builder.py b/packages/core/src/repowise/core/ingestion/graph/builder.py
index 48e3ffde2..276037ff2 100644
--- a/packages/core/src/repowise/core/ingestion/graph/builder.py
+++ b/packages/core/src/repowise/core/ingestion/graph/builder.py
@@ -231,6 +231,7 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd
has_error=bool(parsed.parse_errors),
is_test=parsed.file_info.is_test,
is_entry_point=parsed.file_info.is_entry_point,
+ is_reachability_root=parsed.file_info.is_reachability_root,
docstring=parsed.docstring,
# Same-file references (Python): names used intra-module in a
# non-call/non-import position. Rescues them in the unused-export
diff --git a/packages/core/src/repowise/core/ingestion/graph_warmups.py b/packages/core/src/repowise/core/ingestion/graph_warmups.py
index a825acc12..faa583e9f 100644
--- a/packages/core/src/repowise/core/ingestion/graph_warmups.py
+++ b/packages/core/src/repowise/core/ingestion/graph_warmups.py
@@ -47,6 +47,23 @@ _CPP_MACRO_SCAN_EXTS: tuple[str, ...] = (
)
+def _stamp_entry(graph: Any, parsed_files: dict, path: str) -> None:
+ """Stamp an entry on both the graph node and ``FileInfo``.
+
+ The node flag feeds dead code, ``FileInfo`` the entry-point list and tour.
+ A test file only becomes a reachability root: a runner loads it, but no
+ reader enters the system there.
+ """
+ node = graph.nodes.get(path) if graph is not None else None
+ info = getattr(parsed_files.get(path), "file_info", None)
+ is_test = bool((node or {}).get("is_test") or getattr(info, "is_test", False))
+ flag = "is_reachability_root" if is_test else "is_entry_point"
+ if node is not None:
+ node[flag] = True
+ if info is not None:
+ setattr(info, flag, True)
+
+
def _warmup_jvm(ctx: ResolverContext) -> None:
from .resolvers.jvm_workspace import get_or_build_jvm_index
@@ -59,7 +76,7 @@ def _warmup_jvm(ctx: ResolverContext) -> None:
# graph cannot see: META-INF/services lines, JPMS ``provides ... with``
# directives (both merged into ``index.services``), and Spring Boot
# autoconfig imports (Boot-2 ``spring.factories``, Boot-3 ``.imports``).
- # Stamp the defining file node as ``is_entry_point`` so the
+ # Stamp the defining file node a reachability root so the
# unreachable-file pass treats it as live without a per-language
# check on every node.
entry_fqns: set[str] = set()
@@ -72,7 +89,7 @@ def _warmup_jvm(ctx: ResolverContext) -> None:
for path in index.files_for_fqn(fqn):
node = graph.nodes.get(path)
if node is not None:
- node["is_entry_point"] = True
+ node["is_reachability_root"] = True
# Stamp every JVM source file under a non-``main`` Gradle source-set
# (``testFixtures``, ``integrationTest``, ``javaPoet``, ``jcstress``,
@@ -129,7 +146,7 @@ def _warmup_cpp(ctx: ResolverContext) -> None:
``RCLCPP_COMPONENTS_REGISTER_NODE``, ``BOOST_CLASS_EXPORT``,
``LLVMFuzzerTestOneInput``, ``Q_OBJECT``, ``__attribute__((constructor))``,
``[[gnu::retain]]`` / ``[[gnu::used]]`` and the like — and stamps
- ``is_entry_point=True`` on the file node. These macros wire the file
+ ``is_reachability_root=True`` on the file node. These macros wire the file
into a runtime registry at static-init time, so a static call edge
will never exist; without this rescue, every such TU reads as
``unreachable_file``.
@@ -232,7 +249,7 @@ def _mark_cpp_entry_point_files(
graph: Any,
source_map: dict[str, bytes] | None = None,
) -> None:
- """Stamp ``is_entry_point=True`` on TU file nodes matching an entry marker."""
+ """Stamp TU file nodes carrying a registration marker as reachability roots."""
for path, parsed in parsed_files.items():
lang = parsed.file_info.language
if lang not in ("cpp", "c"):
@@ -244,7 +261,7 @@ def _mark_cpp_entry_point_files(
continue
node = graph.nodes.get(path)
if node is not None:
- node["is_entry_point"] = True
+ node["is_reachability_root"] = True
_SWIFT_ENTRY_RE = None # compiled lazily inside _warmup_swift
@@ -303,22 +320,13 @@ def _warmup_go(ctx: ResolverContext) -> None:
parsed = getattr(ctx, "parsed_files", None) or {}
for pkg in index.packages.values():
for path in pkg.main_files:
- # The graph attribute feeds dead-code reachability; the parsed
- # FileInfo flag feeds the exported KG's entry tags and the tour
- # seeds — both surfaces must agree.
- if graph is not None:
- node = graph.nodes.get(path)
- if node is not None:
- node["is_entry_point"] = True
- pf = parsed.get(path)
- if pf is not None and getattr(pf, "file_info", None) is not None:
- pf.file_info.is_entry_point = True
+ _stamp_entry(graph, parsed, path)
def _warmup_typescript(ctx: ResolverContext) -> None:
- """Build the TS workspace index and stamp ``is_entry_point`` on every
- source file the workspace's ``package.json`` ``exports`` map resolves
- to. Without this, files reachable only through the package boundary
+ """Build the TS workspace index and stamp every source file the
+ workspace's ``package.json`` ``exports`` map resolves to as a
+ reachability root. Without this, files reachable only through the package boundary
(downstream npm consumers) read as ``in_degree==0`` and ship as
unreachable findings.
@@ -341,9 +349,9 @@ def _warmup_typescript(ctx: ResolverContext) -> None:
return
parsed = getattr(ctx, "parsed_files", None) or {}
for path in index.manifest_entry_paths:
+ _stamp_entry(graph, parsed, path)
pf = parsed.get(path)
if pf is not None and getattr(pf, "file_info", None) is not None:
- pf.file_info.is_entry_point = True
pf.file_info.is_manifest_entry = True
entry_paths: set[str] = set(index.exports_entry_paths) | index.manifest_entry_paths
# MDX-only consumers (docs sites that import TSX components into
@@ -358,11 +366,11 @@ def _warmup_typescript(ctx: ResolverContext) -> None:
# by the main entry graph.
with contextlib.suppress(Exception):
entry_paths |= find_npm_script_entry_targets(ctx)
- for path in entry_paths:
+ # Roots, not entry points: these keep code alive without being a front door.
+ for path in entry_paths - index.manifest_entry_paths:
node = graph.nodes.get(path)
- if node is None:
- continue
- node["is_entry_point"] = True
+ if node is not None:
+ node["is_reachability_root"] = True
_FLUTTER_SHELL_DIRS = ("android/", "ios/", "linux/", "macos/", "windows/", "web/")
@@ -402,12 +410,7 @@ def _warmup_dart(ctx: ResolverContext) -> None:
# forms can't express — stamp them here instead.
basename = s.rsplit("/", 1)[-1]
if basename.startswith("main_") and basename.endswith(".dart"):
- nd = graph.nodes.get(node_name)
- if nd is not None:
- nd["is_entry_point"] = True
- pf = parsed.get(node_name)
- if pf is not None and getattr(pf, "file_info", None) is not None:
- pf.file_info.is_entry_point = True
+ _stamp_entry(graph, parsed, node_name)
def _warmup_godot(ctx: ResolverContext) -> None:
@@ -487,17 +490,7 @@ def _warmup_godot(ctx: ResolverContext) -> None:
# this repo, so only in-repo targets are stamped.
if target is None or target not in ctx.path_set:
continue
- node = graph.nodes.get(target)
- if node is not None:
- node["is_entry_point"] = True
- # Both, as _warmup_dart and _warmup_go do: the graph attribute is
- # what dead-code reachability reads, but the wiki's entry-point
- # list, the tour and page selection all read FileInfo. Stamping
- # only the first would leave an addon-publisher repo still
- # reporting no entry point anywhere a reader looks.
- target_parsed = parsed_files.get(target)
- if target_parsed is not None and getattr(target_parsed, "file_info", None):
- target_parsed.file_info.is_entry_point = True
+ _stamp_entry(graph, parsed_files, target)
# A project root of "" (project.godot at the repo root) gives "addons/".
# Keyed on project.godot only: a plugin.cfg is what marks an addon, not
diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.py
index c84a37821..a07bbc92d 100644
--- a/packages/core/src/repowise/core/ingestion/models.py
+++ b/packages/core/src/repowise/core/ingestion/models.py
@@ -161,6 +161,9 @@ class FileInfo:
# pyproject scripts, a distribution's package ``__init__``): the strongest
# entry evidence, ranked above every filename guess.
is_manifest_entry: bool = False
+ # Reached from outside the import graph (a runner or loader starts it), so
+ # dead-code analysis never flags it. Read through ``is_reachability_root``.
+ is_reachability_root: bool = False
@dataclass
diff --git a/packages/core/src/repowise/core/ingestion/traverser.py b/packages/core/src/repowise/core/ingestion/traverser.py
index de775f628..5427527a5 100644
--- a/packages/core/src/repowise/core/ingestion/traverser.py
+++ b/packages/core/src/repowise/core/ingestion/traverser.py
@@ -794,6 +794,7 @@ class FileTraverser:
or rel_str in self._distribution_inits
)
is_test = is_test_related_path(rel_str, language)
+ entry = _is_entry_point(rel_str, abs_path, language) or manifest_entry
return FileInfo(
path=rel_str,
abs_path=str(abs_path),
@@ -804,8 +805,10 @@ class FileTraverser:
is_test=is_test,
is_config=_is_config_file(language),
is_api_contract=not is_test and _is_api_contract(abs_path, language),
- is_entry_point=_is_entry_point(rel_str, abs_path, language) or manifest_entry,
+ # A runner loads a test file, but no reader enters the system there.
+ is_entry_point=entry and not is_test,
is_manifest_entry=manifest_entry,
+ is_reachability_root=entry,
)
# ------------------------------------------------------------------
@@ -1144,8 +1147,8 @@ def _is_entry_point(rel_str: str, abs_path: Path, language: str) -> bool:
A conventional filename or stem is a guess, so it passes through
``not_an_execution_start``, the same correction the wiki's orientation list
uses. A manifest-named file (a ``[project.scripts]`` target) is evidence,
- so the caller ORs it in outside that gate: this flag is what exempts a
- file from dead-code detection.
+ so the caller ORs it in outside that gate. Dead-code exemption reads
+ ``is_reachability_root``, which every entry point also carries.
"""
filename = abs_path.name
named_entry = (
diff --git a/packages/core/src/repowise/core/persistence/crud/graph.py b/packages/core/src/repowise/core/persistence/crud/graph.py
index e45b2bf4c..bc54eb26c 100644
--- a/packages/core/src/repowise/core/persistence/crud/graph.py
+++ b/packages/core/src/repowise/core/persistence/crud/graph.py
@@ -59,6 +59,7 @@ _NODE_FIELDS = (
"has_error",
"is_test",
"is_entry_point",
+ "is_reachability_root",
"pagerank",
"betweenness",
"betweenness_commit",
@@ -486,6 +487,7 @@ async def get_all_graph_nodes(
"has_error": row.has_error,
"is_test": row.is_test,
"is_entry_point": row.is_entry_point,
+ "is_reachability_root": row.is_reachability_root,
"kind": row.kind,
"name": row.name,
"qualified_name": row.qualified_name,
diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.py
index 887ea0a27..3cf00fc7b 100644
--- a/packages/core/src/repowise/core/persistence/models.py
+++ b/packages/core/src/repowise/core/persistence/models.py
@@ -283,6 +283,8 @@ class GraphNode(Base):
has_error: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
is_test: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
is_entry_point: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
+ # Dead-code exempt: reached from outside the graph. Every entry point is one.
+ is_reachability_root: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=false())
pagerank: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)
betweenness: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)
# The commit ``betweenness`` was last actually computed at. Betweenness is
diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.py
index 428223fad..d6bcbb876 100644
--- a/packages/core/src/repowise/core/pipeline/persist.py
+++ b/packages/core/src/repowise/core/pipeline/persist.py
@@ -15,6 +15,7 @@ from typing import Any
import structlog
+from repowise.core.entry_candidacy import is_reachability_root
from repowise.core.generation.models import (
STRUCTURALLY_KEYED_PAGE_TYPES,
STUB_FALLBACK_ERROR,
@@ -457,6 +458,7 @@ async def persist_graph_nodes(
"has_error": data.get("has_error", False),
"is_test": data.get("is_test", False),
"is_entry_point": data.get("is_entry_point", False),
+ "is_reachability_root": is_reachability_root(data),
# Files draw from the file-level metric tables; symbols fall
# back to the symbol subgraph (calls + heritage) so that the
# per-symbol UI panel shows real centrality instead of 0.
diff --git a/tests/integration/test_reachability_root_equivalence.py b/tests/integration/test_reachability_root_equivalence.py
new file mode 100644
index 000000000..bbb2d8713
--- /dev/null
+++ b/tests/integration/test_reachability_root_equivalence.py
@@ -0,0 +1,50 @@
+"""Dead code reads ``is_reachability_root`` exactly as it read the single flag.
+
+Before the split one ``is_entry_point`` flag both named entry points and exempted
+files from dead code. The legacy graph below rebuilds that world: every root is
+stamped an entry point and the root flag is dropped. The analyzer must report
+the same findings on both graphs, whatever the entry flag means now.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from repowise.core.analysis.dead_code import DeadCodeAnalyzer
+from repowise.core.entry_candidacy import is_reachability_root
+from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder
+
+FIXTURES = Path(__file__).parent.parent / "fixtures"
+
+
+def _graph(repo: Path):
+ parser = ASTParser()
+ builder = GraphBuilder(repo_path=repo)
+ for fi in FileTraverser(repo).traverse():
+ builder.add_file(parser.parse_file(fi, Path(fi.abs_path).read_bytes()))
+ return builder.build()
+
+
+def _legacy(graph):
+ legacy = graph.copy()
+ for _node, data in legacy.nodes(data=True):
+ data["is_entry_point"] = is_reachability_root(data)
+ data.pop("is_reachability_root", None)
+ return legacy
+
+
+def _findings(graph) -> list[tuple]:
+ report = DeadCodeAnalyzer(graph, git_meta_map={}).analyze({"min_confidence": 0.0})
+ return sorted(
+ (f.kind.value, f.file_path, f.symbol_name or "", f.confidence) for f in report.findings
+ )
+
+
[email protected]("fixture", ["sample_repo", "ts_sample", "go_sample"])
+def test_dead_code_unchanged_by_root_split(fixture: str) -> None:
+ graph = _graph(FIXTURES / fixture)
+ findings = _findings(graph)
+ assert findings, "fixture should produce some findings"
+ assert findings == _findings(_legacy(graph))
diff --git a/tests/unit/dead_code/test_reachability.py b/tests/unit/dead_code/test_reachability.py
index caff25aae..302bbe439 100644
--- a/tests/unit/dead_code/test_reachability.py
+++ b/tests/unit/dead_code/test_reachability.py
@@ -63,6 +63,27 @@ def test_entry_point_not_flagged():
assert all(f.file_path != "pkg/main.py" for f in report.findings)
+def test_reachability_root_not_flagged():
+ """A root that is not an entry point is still exempt from dead code."""
+ g = _build_graph(
+ nodes={
+ "pkg/loaded_by_runner.py": {
+ "is_entry_point": False,
+ "is_reachability_root": True,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 10,
+ "symbols": [],
+ },
+ },
+ )
+
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze({"detect_unused_exports": False, "detect_zombie_packages": False})
+
+ assert all(f.file_path != "pkg/loaded_by_runner.py" for f in report.findings)
+
+
def test_test_files_excluded():
"""A test file (is_test=True) with in_degree=0 should NOT be flagged."""
g = _build_graph(
diff --git a/tests/unit/ingestion/test_cpp_framework_edges.py b/tests/unit/ingestion/test_cpp_framework_edges.py
index 0281c1bcf..623b77a13 100644
--- a/tests/unit/ingestion/test_cpp_framework_edges.py
+++ b/tests/unit/ingestion/test_cpp_framework_edges.py
@@ -74,7 +74,8 @@ class TestGoogleTestFixtureEdges:
ctx = _ctx(tmp_path, parsed)
add_framework_edges(graph, parsed, ctx, tech_stack=["gtest"])
assert graph.has_edge("brew_test.cc", "fixture.h")
- assert graph.nodes["brew_test.cc"].get("is_entry_point") is True
+ assert graph.nodes["brew_test.cc"].get("is_reachability_root") is True
+ assert not graph.nodes["brew_test.cc"].get("is_entry_point")
def test_typed_test_fixture_edge(self, tmp_path: Path) -> None:
(tmp_path / "ty_fix.h").write_text(
@@ -101,7 +102,8 @@ class TestGoogleTestFixtureEdges:
graph = _graph_with_nodes(parsed)
ctx = _ctx(tmp_path, parsed)
add_framework_edges(graph, parsed, ctx, tech_stack=["gtest"])
- assert graph.nodes["plain_test.cc"].get("is_entry_point") is True
+ assert graph.nodes["plain_test.cc"].get("is_reachability_root") is True
+ assert not graph.nodes["plain_test.cc"].get("is_entry_point")
class TestBoostAndCatch2Fixtures:
@@ -150,7 +152,8 @@ class TestBenchmarkAndFuzzer:
graph = _graph_with_nodes(parsed)
ctx = _ctx(tmp_path, parsed)
add_framework_edges(graph, parsed, ctx, tech_stack=["benchmark"])
- assert graph.nodes["bench.cc"].get("is_entry_point") is True
+ assert graph.nodes["bench.cc"].get("is_reachability_root") is True
+ assert not graph.nodes["bench.cc"].get("is_entry_point")
def test_libfuzzer_entry(self, tmp_path: Path) -> None:
(tmp_path / "fuzz.cc").write_text(
@@ -161,7 +164,8 @@ class TestBenchmarkAndFuzzer:
graph = _graph_with_nodes(parsed)
ctx = _ctx(tmp_path, parsed)
add_framework_edges(graph, parsed, ctx)
- assert graph.nodes["fuzz.cc"].get("is_entry_point") is True
+ assert graph.nodes["fuzz.cc"].get("is_reachability_root") is True
+ assert not graph.nodes["fuzz.cc"].get("is_entry_point")
class TestNonTestFilesUnaffected:
@@ -174,3 +178,4 @@ class TestNonTestFilesUnaffected:
ctx = _ctx(tmp_path, parsed)
add_framework_edges(graph, parsed, ctx)
assert graph.nodes["lib.cc"].get("is_entry_point") is None
+ assert graph.nodes["lib.cc"].get("is_reachability_root") is None
diff --git a/tests/unit/ingestion/test_graph_rehydrate.py b/tests/unit/ingestion/test_graph_rehydrate.py
index b81695eb0..c6bfd7b84 100644
--- a/tests/unit/ingestion/test_graph_rehydrate.py
+++ b/tests/unit/ingestion/test_graph_rehydrate.py
@@ -190,3 +190,12 @@ def test_supplied_props_survives_rehydration():
for e in edges[1:]:
assert "supplied_props" not in graph[e["source_node_id"]][e["target_node_id"]]
+
+
+def test_reachability_root_survives_rehydration():
+ original = _build_sample()
+ original.graph().nodes["c.py"]["is_reachability_root"] = True
+ nodes, edges = _serialize(original)
+ hydrated = GraphBuilder.from_persisted(nodes, edges, original.file_metrics_snapshot())
+ assert hydrated.graph().nodes["c.py"]["is_reachability_root"] is True
+ assert not hydrated.graph().nodes["a.py"].get("is_reachability_root")
diff --git a/tests/unit/ingestion/test_manifest_entry_points.py b/tests/unit/ingestion/test_manifest_entry_points.py
index 8db9726eb..95bd23c2a 100644
--- a/tests/unit/ingestion/test_manifest_entry_points.py
+++ b/tests/unit/ingestion/test_manifest_entry_points.py
@@ -20,6 +20,7 @@ import pytest
from repowise.core.analysis.dead_code.file_reachability import is_file_reachable
from repowise.core.analysis.kg_curation import curate_knowledge_graph
from repowise.core.analysis.knowledge_graph import build_knowledge_graph_skeleton
+from repowise.core.entry_candidacy import is_reachability_root
from repowise.core.ingestion.graph import GraphBuilder
from repowise.core.ingestion.parser import ASTParser
from repowise.core.ingestion.resolvers.ts_workspace import (
@@ -229,7 +230,10 @@ def test_build_target_escaping_the_repo_is_ignored(tmp_path: Path) -> None:
def test_fixture_pkg_under_tests(tmp_path: Path) -> None:
- """Test and example packages' bins stay dead-code exempt but are never surfaced."""
+ """Test and example packages' bins stay dead-code exempt but are never surfaced.
+
+ A test fixture's bin is a reachability root, not an entry point.
+ """
repo = _write(
tmp_path,
{
@@ -243,8 +247,11 @@ def test_fixture_pkg_under_tests(tmp_path: Path) -> None:
idx = _index(repo)
for hidden in ("tests/e2e/pkg/tool.js", "examples/demo/start.js"):
assert idx.info[hidden].is_manifest_entry
- assert idx.graph.nodes[hidden]["is_entry_point"]
+ assert is_reachability_root(idx.graph.nodes[hidden])
assert hidden not in idx.project["entry_candidates"]
+ assert not idx.info["tests/e2e/pkg/tool.js"].is_entry_point
+ assert not idx.graph.nodes["tests/e2e/pkg/tool.js"].get("is_entry_point")
+ assert idx.graph.nodes["examples/demo/start.js"]["is_entry_point"]
assert idx.project["entry_points"] == ["src/main.py"]
@@ -267,3 +274,22 @@ def test_bin_source_is_reachable_for_dead_code(tmp_path: Path) -> None:
idx = _index(repo)
assert is_file_reachable("src/cli.ts", idx.graph)
assert not is_file_reachable("src/old.ts", idx.graph)
+
+
+def test_exports_subpath_is_a_root_not_an_entry(tmp_path: Path) -> None:
+ """Only ``exports["."]`` is a front door; other subpaths just keep code alive."""
+ repo = _write(
+ tmp_path,
+ {
+ "package.json": json.dumps({"workspaces": ["packages/*"]}),
+ "packages/lib/package.json": json.dumps(
+ {"name": "lib", "exports": {".": "./src/index.ts", "./util": "./src/util.ts"}}
+ ),
+ "packages/lib/src/index.ts": "export const a = 1;\n",
+ "packages/lib/src/util.ts": "export const b = 2;\n",
+ },
+ )
+ idx = _index(repo)
+ assert idx.graph.nodes["packages/lib/src/index.ts"]["is_entry_point"]
+ util = idx.graph.nodes["packages/lib/src/util.ts"]
+ assert util.get("is_reachability_root") and not util.get("is_entry_point")
diff --git a/tests/unit/ingestion/test_traverser.py b/tests/unit/ingestion/test_traverser.py
index d6c8f4d6d..006392ab0 100644
--- a/tests/unit/ingestion/test_traverser.py
+++ b/tests/unit/ingestion/test_traverser.py
@@ -997,6 +997,17 @@ class TestEntryPointFlag:
flagged = self._flagged(tmp_path)
assert flagged == set(files), flagged
+ def test_test_file_is_a_root_not_an_entry_point(self, tmp_path: Path) -> None:
+ for rel in ("tests/app.py", "src/main.py"):
+ p = tmp_path / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text("print('x')")
+ info = {f.path: f for f in FileTraverser(tmp_path).traverse()}
+ assert info["tests/app.py"].is_reachability_root
+ assert not info["tests/app.py"].is_entry_point
+ assert info["src/main.py"].is_reachability_root
+ assert info["src/main.py"].is_entry_point
+
def test_historical_stem_parity_and_non_entries(self, tmp_path: Path) -> None:
files = {
"run.py": "print('x')", # covered by the run stem (dropped pattern)
diff --git a/tests/unit/ingestion/test_warmup_source_map.py b/tests/unit/ingestion/test_warmup_source_map.py
index cc67e8996..c570d5c67 100644
--- a/tests/unit/ingestion/test_warmup_source_map.py
+++ b/tests/unit/ingestion/test_warmup_source_map.py
@@ -44,7 +44,7 @@ def test_cpp_warmup_reads_the_source_map_not_the_disk(tmp_path):
_mark_cpp_entry_point_files(parsed, graph, {"src/mod.cpp": b"PYBIND11_MODULE(m, x) {}\n"})
- assert graph.nodes["src/mod.cpp"]["is_entry_point"] is True
+ assert graph.nodes["src/mod.cpp"]["is_reachability_root"] is True
def test_cpp_warmup_falls_back_to_disk_on_a_map_miss(tmp_path):
@@ -53,7 +53,7 @@ def test_cpp_warmup_falls_back_to_disk_on_a_map_miss(tmp_path):
_mark_cpp_entry_point_files(parsed, graph, {"src/other.cpp": b"nothing\n"})
- assert graph.nodes["src/mod.cpp"]["is_entry_point"] is True
+ assert graph.nodes["src/mod.cpp"]["is_reachability_root"] is True
def test_cpp_warmup_with_no_source_map_still_reads_disk(tmp_path):
@@ -62,7 +62,7 @@ def test_cpp_warmup_with_no_source_map_still_reads_disk(tmp_path):
_mark_cpp_entry_point_files(parsed, graph, None)
- assert graph.nodes["src/mod.cpp"]["is_entry_point"] is True
+ assert graph.nodes["src/mod.cpp"]["is_reachability_root"] is True
def test_cpp_warmup_leaves_unmarked_files_alone(tmp_path):
@@ -71,7 +71,7 @@ def test_cpp_warmup_leaves_unmarked_files_alone(tmp_path):
_mark_cpp_entry_point_files(parsed, graph, {"src/plain.cpp": b"int f() { return 0; }\n"})
- assert graph.nodes["src/plain.cpp"]["is_entry_point"] is False
+ assert "is_reachability_root" not in graph.nodes["src/plain.cpp"]
# --------------------------------------------------------------------------
@@ -135,8 +135,8 @@ def test_awkward_bytes_decode_the_same_from_map_and_disk(tmp_path):
_mark_cpp_entry_point_files(parsed, from_disk, None)
assert (
- from_map.nodes["src/awkward.cpp"]["is_entry_point"]
- == from_disk.nodes["src/awkward.cpp"]["is_entry_point"]
+ from_map.nodes["src/awkward.cpp"]["is_reachability_root"]
+ == from_disk.nodes["src/awkward.cpp"]["is_reachability_root"]
is True
)
@@ -151,4 +151,4 @@ def test_missing_file_with_no_map_entry_is_skipped(tmp_path):
_mark_cpp_entry_point_files(parsed, graph, {})
- assert graph.nodes["src/gone.cpp"]["is_entry_point"] is False
+ assert "is_reachability_root" not in graph.nodes["src/gone.cpp"]