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.

perf(dead-code): feed the marker prepasses ingestion's bytes (#1223)

Raghav Chamadiyab501a957581a
diff --git a/packages/cli/src/repowise/cli/commands/dead_code_cmd.py b/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
index a961e990f..dc9e7154a 100644
--- a/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
@@ -150,11 +150,15 @@ def dead_code_command(
include_nested_repos=include_nested_repos,
)
+ # Kept alongside the parse so the analyzer's marker prepasses reuse these
+ # bytes instead of re-reading the repo four more times.
+ source_map: dict[str, bytes] = {}
for fi in file_infos:
try:
source = PathlibPath(fi.abs_path).read_bytes()
parsed = parser.parse_file(fi, source)
graph_builder.add_file(parsed)
+ source_map[fi.path] = source
except Exception:
pass
@@ -166,6 +170,7 @@ def dead_code_command(
include_submodules=include_submodules,
include_nested_repos=include_nested_repos,
)
+ graph_builder.set_source_map(source_map)
graph_builder.build()
# Framework-aware synthetic edges (Django, Laravel, TYPO3, ...). Without
@@ -209,7 +214,10 @@ def dead_code_command(
# bundler resolve.alias targets, export-alias maps) — without it those
# classes false-positive on the CLI path while init stays clean.
analyzer = DeadCodeAnalyzer(
- graph_builder.graph(), git_meta_map, parsed_files=graph_builder._parsed_files
+ graph_builder.graph(),
+ git_meta_map,
+ parsed_files=graph_builder._parsed_files,
+ source_map=source_map,
)
report = analyzer.analyze(config)
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
index 35ee677f7..4c05b9743 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
@@ -1065,7 +1065,7 @@ def run_update(
return UpdateOutcome.DRY_RUN
partial_health_report, dead_code_report = _run_partial_analysis(
- repo_path, graph_builder, git_meta_map, parsed_files, file_diffs
+ repo_path, graph_builder, git_meta_map, parsed_files, file_diffs, source_map
)
# Partial health has consumed the per-file ``BlameIndex``; drop it before
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/incremental.py b/packages/cli/src/repowise/cli/commands/update_cmd/incremental.py
index b557c9719..3d0e7be64 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/incremental.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/incremental.py
@@ -153,6 +153,7 @@ def _run_partial_analysis(
git_meta_map: dict,
parsed_files: list,
file_diffs: list,
+ source_map: dict[str, bytes] | None = None,
) -> tuple[Any, Any]:
"""Run partial code-health + dead-code analysis for the changed files.
@@ -170,5 +171,6 @@ def _run_partial_analysis(
git_meta_map,
parsed_files,
file_diffs,
+ source_map=source_map,
log=console.print,
)
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 009c1c940..a7128fc4d 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -36,7 +36,11 @@ from .cpp_reachability import (
is_cpp_file_reachable,
is_cpp_path,
)
-from .dynamic_markers import find_dynamic_edge_files, find_dynamic_import_files
+from .dynamic_markers import (
+ find_dynamic_edge_files,
+ find_dynamic_import_files,
+ read_source_text,
+)
from .go_reachability import build_go_package_files, is_go_file_reachable
from .jvm_reachability import build_jvm_package_files, is_jvm_file_reachable
from .models import DeadCodeFindingData, DeadCodeKind, DeadCodeReport
@@ -319,7 +323,10 @@ _BARREL_FILENAMES: frozenset[str] = frozenset(
)
-def _find_jsx_namespace_files(parsed_files: dict) -> set[str]:
+def _find_jsx_namespace_files(
+ parsed_files: dict,
+ source_map: dict[str, bytes] | None = None,
+) -> set[str]:
"""Return repo-relative paths of TS/TSX files that declare ``namespace JSX``.
Symbols whose name is in :data:`_TS_JSX_NAMESPACE_TYPES` and whose
@@ -337,7 +344,7 @@ def _find_jsx_namespace_files(parsed_files: dict) -> set[str]:
src_path = Path(file_info.abs_path)
if src_path.suffix not in (".ts", ".tsx", ".d.ts"):
continue
- source = src_path.read_text(errors="ignore")
+ source = read_source_text(path, file_info.abs_path, source_map)
# Match ``namespace JSX`` and ``declare namespace JSX`` — both
# are JSX transformer integration points in practice.
if "namespace JSX" in source:
@@ -358,7 +365,10 @@ _RELATIVE_PATH_STRING_RE = re.compile(r"""['"]((?:\.\.?/)?[\[email protected]]+(?:/[\[email protected]]+)+
_TS_PROBE_SUFFIXES = ("", ".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs")
-def _find_bundler_alias_targets(parsed_files: dict) -> set[str]:
+def _find_bundler_alias_targets(
+ parsed_files: dict,
+ source_map: dict[str, bytes] | None = None,
+) -> set[str]:
"""Repo-relative paths referenced from bundler config files.
Vite/webpack ``resolve.alias`` entries substitute a bare package import
@@ -378,7 +388,7 @@ def _find_bundler_alias_targets(parsed_files: dict) -> set[str]:
file_info = getattr(pf, "file_info", None)
if file_info is None:
continue
- source = Path(file_info.abs_path).read_text(errors="ignore")
+ source = read_source_text(path, file_info.abs_path, source_map)
except Exception:
continue
config_dir = Path(path).parent
@@ -402,7 +412,10 @@ def _posix_normpath(config_dir: Path, raw: str) -> str:
_TS_EXPORT_ALIAS_RE = re.compile(r"\bexport\s*\{([^}]*)\}(?!\s*from)")
-def _find_ts_export_aliases(parsed_files: dict) -> dict[str, dict[str, str]]:
+def _find_ts_export_aliases(
+ parsed_files: dict,
+ source_map: dict[str, bytes] | None = None,
+) -> dict[str, dict[str, str]]:
"""Per-file ``{local_name: exported_alias}`` maps for TS/JS alias exports.
``export { ConversationHistoryWrapper as ConversationHistory }`` publishes
@@ -418,7 +431,7 @@ def _find_ts_export_aliases(parsed_files: dict) -> dict[str, dict[str, str]]:
file_info = getattr(pf, "file_info", None)
if file_info is None:
continue
- source = Path(file_info.abs_path).read_text(errors="ignore")
+ source = read_source_text(path, file_info.abs_path, source_map)
except Exception:
continue
file_map: dict[str, str] = {}
@@ -487,11 +500,18 @@ class DeadCodeAnalyzer:
graph: Any, # nx.DiGraph
git_meta_map: dict | None = None,
parsed_files: dict | None = None,
+ source_map: dict[str, bytes] | None = None,
) -> None:
self.graph = graph
self.git_meta_map = git_meta_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
+ # into dict lookups. Callers that don't have it (a resume view, the
+ # standalone ``dead-code`` command on a graph built elsewhere) pass
+ # None and each prepass reads from disk exactly as before.
self._dynamic_import_files = find_dynamic_import_files(
- parsed_files or {}
+ parsed_files or {}, source_map
) | find_dynamic_edge_files(graph)
# Parent directories of the above, precomputed once.
#
@@ -510,14 +530,18 @@ class DeadCodeAnalyzer:
self._dynamic_import_dirs: set[str] = {
str(Path(dif).parent) for dif in self._dynamic_import_files
}
- self._jsx_namespace_files: set[str] = _find_jsx_namespace_files(parsed_files or {})
+ self._jsx_namespace_files: set[str] = _find_jsx_namespace_files(
+ parsed_files or {}, source_map
+ )
# Files substituted in via bundler ``resolve.alias`` config — named
# by the config, never imported by path.
- self._bundler_alias_targets: set[str] = _find_bundler_alias_targets(parsed_files or {})
+ self._bundler_alias_targets: set[str] = _find_bundler_alias_targets(
+ parsed_files or {}, source_map
+ )
# ``export { local as alias }`` maps so importer edges carrying the
# alias still count for the local symbol.
self._ts_export_aliases: dict[str, dict[str, str]] = _find_ts_export_aliases(
- parsed_files or {}
+ parsed_files or {}, source_map
)
# Lazily-built ``.go`` package-directory → file-node map, used by the
# Go package-granular reachability hook (see ``go_reachability``).
diff --git a/packages/core/src/repowise/core/analysis/dead_code/dynamic_markers.py b/packages/core/src/repowise/core/analysis/dead_code/dynamic_markers.py
index 2788b0639..1683c75e8 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/dynamic_markers.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/dynamic_markers.py
@@ -17,10 +17,38 @@ in Phase 2 stays mechanical.
from __future__ import annotations
+import locale
from pathlib import Path
from repowise.core.ids import is_external
+
+def read_source_text(
+ rel_path: str,
+ abs_path: str,
+ source_map: dict[str, bytes] | None,
+) -> str:
+ """Decoded source for *rel_path*, preferring ingestion's already-read bytes.
+
+ The dead-code prepasses each scan the whole indexed file set for text
+ markers. Ingestion already read every one of those files into
+ ``source_map`` (keyed by the same repo-relative path as ``parsed_files``),
+ so a hit here replaces a full-repo disk pass with a dict lookup.
+
+ Decoding is deliberately identical on both paths, and identical to the
+ ``Path.read_text(errors="ignore")`` these prepasses used to call, which
+ resolves ``encoding=None`` to the locale encoding at call time. Every
+ marker is ASCII, but pinning the codec keeps a source_map hit and a disk
+ fallback from ever disagreeing about the same bytes.
+ """
+ data: bytes | None = None
+ if source_map is not None:
+ data = source_map.get(rel_path)
+ if data is None:
+ data = Path(abs_path).read_bytes()
+ return data.decode(locale.getpreferredencoding(False), errors="ignore")
+
+
# Patterns in source that indicate dynamic/runtime imports, keyed by suffix.
_DYNAMIC_IMPORT_MARKERS: dict[str, tuple[str, ...]] = {
".py": (
@@ -449,7 +477,10 @@ _DYNAMIC_IMPORT_MARKERS: dict[str, tuple[str, ...]] = {
}
-def find_dynamic_import_files(parsed_files: dict) -> set[str]:
+def find_dynamic_import_files(
+ parsed_files: dict,
+ source_map: dict[str, bytes] | None = None,
+) -> set[str]:
"""Return the set of file paths whose source contains a dynamic-import marker."""
result: set[str] = set()
for path, pf in parsed_files.items():
@@ -461,7 +492,7 @@ def find_dynamic_import_files(parsed_files: dict) -> set[str]:
markers = _DYNAMIC_IMPORT_MARKERS.get(src_path.suffix)
if not markers:
continue
- source = src_path.read_text(errors="ignore")
+ source = read_source_text(path, file_info.abs_path, source_map)
if any(marker in source for marker in markers):
result.add(path)
except Exception:
diff --git a/packages/core/src/repowise/core/ingestion/graph/builder.py b/packages/core/src/repowise/core/ingestion/graph/builder.py
index ef4a81ef4..9fca64f2f 100644
--- a/packages/core/src/repowise/core/ingestion/graph/builder.py
+++ b/packages/core/src/repowise/core/ingestion/graph/builder.py
@@ -51,6 +51,11 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd
) -> None:
self._graph: nx.DiGraph = nx.DiGraph()
self._parsed_files: dict[str, ParsedFile] = {} # path → ParsedFile
+ # Raw source bytes the caller already read, keyed like _parsed_files.
+ # Populated via ``set_source_map`` before ``build()``; the language
+ # warmups that scan file text read it instead of re-opening every
+ # file. Empty means "not supplied": every reader falls back to disk.
+ self._source_map: dict[str, bytes] = {}
self._built = False
# Resolver-built DotNetProjectIndex, stashed by build() for the
# dynamic-hints phase to reuse (see build()).
@@ -171,6 +176,14 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd
# Building
# ------------------------------------------------------------------
+ def set_source_map(self, source_map: dict[str, bytes] | None) -> None:
+ """Hand the builder the source bytes already read for the indexed set.
+
+ Call before :meth:`build`. Keys must match ``file_info.path`` (the
+ same repo-relative POSIX key ``add_file`` registers under).
+ """
+ self._source_map = source_map or {}
+
def add_file(self, parsed: ParsedFile) -> None:
"""Register one parsed file and its symbols in the graph."""
path = parsed.file_info.path
@@ -285,6 +298,7 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd
go_modules=go_modules,
has_sfc_files=any(p.endswith((".vue", ".svelte", ".astro")) for p in path_set),
parsed_files=self._parsed_files,
+ source_map=self._source_map,
)
# --- Phase 1 prelude: language-specific warmups ---
diff --git a/packages/core/src/repowise/core/ingestion/graph_warmups.py b/packages/core/src/repowise/core/ingestion/graph_warmups.py
index a300d9c60..13ffea481 100644
--- a/packages/core/src/repowise/core/ingestion/graph_warmups.py
+++ b/packages/core/src/repowise/core/ingestion/graph_warmups.py
@@ -159,7 +159,7 @@ def _warmup_cpp(ctx: ResolverContext) -> None:
node["visibility"] = "public"
break
- _mark_cpp_entry_point_files(parsed_files, graph)
+ _mark_cpp_entry_point_files(parsed_files, graph, getattr(ctx, "source_map", None))
# Tokens whose presence means the surrounding TU wires itself into a
@@ -189,25 +189,46 @@ _CPP_ENTRY_MARKERS = (
)
-def _mark_cpp_entry_point_files(parsed_files: dict, graph: Any) -> None:
+def _read_warmup_source(
+ path: str,
+ parsed: Any,
+ source_map: dict[str, bytes] | None,
+) -> str | None:
+ """Text of *path* for a marker scan, from *source_map* if it has it.
+
+ Neither ``ParsedFile`` nor ``FileInfo`` carries the source, so before
+ ``source_map`` existed these scans always re-opened the file. Decoding
+ matches what the disk fallback below does (utf-8 / replace) so a hit and
+ a miss can never disagree about the same bytes. Returns None when the
+ file is unavailable, which the callers treat as "no markers".
+ """
+ if source_map is not None:
+ data = source_map.get(path)
+ if data is not None:
+ return data.decode("utf-8", errors="replace")
+ abs_path = getattr(parsed.file_info, "abs_path", None)
+ if not abs_path:
+ return None
+ try:
+ with open(abs_path, encoding="utf-8", errors="replace") as f:
+ return f.read()
+ except OSError:
+ return None
+
+
+def _mark_cpp_entry_point_files(
+ parsed_files: dict,
+ graph: Any,
+ source_map: dict[str, bytes] | None = None,
+) -> None:
"""Stamp ``is_entry_point=True`` on TU file nodes matching an entry marker."""
for path, parsed in parsed_files.items():
lang = parsed.file_info.language
if lang not in ("cpp", "c"):
continue
- # The parser already loaded the source; reuse it via the
- # ParsedFile (avoids a second filesystem read).
- src = getattr(parsed, "source", None) or getattr(parsed.file_info, "source", None)
+ src = _read_warmup_source(path, parsed, source_map)
if src is None:
- # ParsedFile doesn't always carry the source — fall back to disk.
- abs_path = getattr(parsed.file_info, "abs_path", None)
- if not abs_path:
- continue
- try:
- with open(abs_path, encoding="utf-8", errors="replace") as f:
- src = f.read()
- except OSError:
- continue
+ continue
if not any(tok in src for tok in _CPP_ENTRY_MARKERS):
continue
node = graph.nodes.get(path)
@@ -235,18 +256,14 @@ def _warmup_swift(ctx: ResolverContext) -> None:
graph = getattr(ctx, "graph", None)
parsed_files = getattr(ctx, "parsed_files", None) or {}
+ source_map = getattr(ctx, "source_map", None)
if graph is None:
return
for path, parsed in parsed_files.items():
if parsed.file_info.language != "swift":
continue
- abs_path = getattr(parsed.file_info, "abs_path", None)
- if not abs_path:
- continue
- try:
- with open(abs_path, encoding="utf-8", errors="replace") as f:
- src = f.read()
- except OSError:
+ src = _read_warmup_source(path, parsed, source_map)
+ if src is None:
continue
if not _SWIFT_ENTRY_RE.search(src):
continue
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/context.py b/packages/core/src/repowise/core/ingestion/resolvers/context.py
index 1a7e2fcbe..3b913d02f 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/context.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/context.py
@@ -40,6 +40,10 @@ class ResolverContext:
go_modules: tuple[tuple[str, str], ...] = () # (module_dir_posix, module_path), longest-first
has_sfc_files: bool = False # any .vue/.svelte/.astro present in path_set
parsed_files: dict | None = None # for Rust crate root detection
+ # ``{file_info.path: raw source bytes}`` the pipeline already read, same
+ # keys as *parsed_files*. Warmups that scan file text use it in place of
+ # a second read; None (or a missing key) means read from disk.
+ source_map: dict[str, bytes] | None = field(default=None, repr=False)
compile_commands_cache: dict[str, dict] | None = field(default=None, repr=False)
# Lazy per-language indexes are stashed via getattr/setattr (e.g.
# ``_php_psr4_map``, ``_ts_workspace_map``, ``_kotlin_index``,
diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.py
index d3cf54f1d..665be854a 100644
--- a/packages/core/src/repowise/core/pipeline/incremental.py
+++ b/packages/core/src/repowise/core/pipeline/incremental.py
@@ -155,6 +155,7 @@ def build_repo_graph(
include_submodules=include_submodules,
include_nested_repos=include_nested_repos,
)
+ graph_builder.set_source_map(source_map)
graph_builder.build()
if parse_cache is not None:
parse_cache.save()
@@ -307,12 +308,16 @@ def run_partial_analysis(
parsed_files: list,
file_diffs: list,
*,
+ source_map: dict[str, bytes] | None = None,
log: LogFn | None = None,
) -> tuple[Any, Any]:
"""Run partial code-health + dead-code analysis for the changed files.
Returns ``(partial_health_report, dead_code_report)`` — either may be
``None`` if its analysis failed (both are best-effort).
+
+ *source_map* is ingestion's ``{path: raw bytes}`` for this rebuild; the
+ dead-code prepasses read it instead of re-reading the repo from disk.
"""
log = log or _noop_log
@@ -360,7 +365,10 @@ def run_partial_analysis(
# parsed_files enables the source-scan rescues (dynamic markers,
# bundler aliases, export aliases) on the update path, matching init.
_analyzer_partial = DeadCodeAnalyzer(
- graph_builder.graph(), git_meta_map, parsed_files=graph_builder._parsed_files
+ graph_builder.graph(),
+ git_meta_map,
+ parsed_files=graph_builder._parsed_files,
+ source_map=source_map,
)
_changed_paths_partial = [fd.path for fd in file_diffs]
dead_code_report = _analyzer_partial.analyze_partial(_changed_paths_partial)
diff --git a/packages/core/src/repowise/core/pipeline/orchestrator.py b/packages/core/src/repowise/core/pipeline/orchestrator.py
index 8a04732c4..161b1ebca 100644
--- a/packages/core/src/repowise/core/pipeline/orchestrator.py
+++ b/packages/core/src/repowise/core/pipeline/orchestrator.py
@@ -484,7 +484,9 @@ async def run_pipeline(
# decision extraction is I/O/LLM-bound and its wall clock hides
# entirely behind the CPU-bound dead-code + health work.
dead_code_report, health_report, decision_report = await asyncio.gather(
- _run_dead_code_analysis(graph_builder, git_meta_map, progress=progress),
+ _run_dead_code_analysis(
+ graph_builder, git_meta_map, source_map=source_map, progress=progress
+ ),
_run_health_analysis(
graph_builder,
git_meta_map,
diff --git a/packages/core/src/repowise/core/pipeline/phases/analysis.py b/packages/core/src/repowise/core/pipeline/phases/analysis.py
index 5aaef3bd3..e119dff34 100644
--- a/packages/core/src/repowise/core/pipeline/phases/analysis.py
+++ b/packages/core/src/repowise/core/pipeline/phases/analysis.py
@@ -41,6 +41,7 @@ async def _run_dead_code_analysis(
graph_builder: Any,
git_meta_map: dict[str, dict],
*,
+ source_map: dict[str, bytes] | None = None,
progress: ProgressCallback | None,
) -> Any | None:
"""Run dead code detection (pure graph traversal, no LLM)."""
@@ -54,7 +55,10 @@ async def _run_dead_code_analysis(
progress.on_phase_start("dead_code", dead_code_steps)
analyzer = DeadCodeAnalyzer(
- graph_builder.graph(), git_meta_map, parsed_files=graph_builder._parsed_files
+ graph_builder.graph(),
+ git_meta_map,
+ parsed_files=graph_builder._parsed_files,
+ source_map=source_map,
)
def _step(_stage: str) -> None:
diff --git a/packages/core/src/repowise/core/pipeline/phases/ingestion.py b/packages/core/src/repowise/core/pipeline/phases/ingestion.py
index b4930be73..3570e9788 100644
--- a/packages/core/src/repowise/core/pipeline/phases/ingestion.py
+++ b/packages/core/src/repowise/core/pipeline/phases/ingestion.py
@@ -400,6 +400,9 @@ async def _run_ingestion(
if parse_cache is not None:
parse_cache.save()
+ # Lend the just-read bytes to the builder so the language warmups that
+ # scan file text during build() don't re-read the repo.
+ graph_builder.set_source_map(source_map)
_phase_done(progress, "parse")
# ---- tsconfig path-alias resolver (before graph build) ------------------
diff --git a/packages/core/src/repowise/core/workspace/update.py b/packages/core/src/repowise/core/workspace/update.py
index 6fbdbd453..7fdc9ed6f 100644
--- a/packages/core/src/repowise/core/workspace/update.py
+++ b/packages/core/src/repowise/core/workspace/update.py
@@ -372,7 +372,7 @@ async def _incremental_repo_update(
git_decay_map: dict[str, dict] = {}
(
parsed_files,
- _source_map,
+ source_map,
graph_builder,
_structure,
file_count,
@@ -390,7 +390,13 @@ async def _incremental_repo_update(
)
partial_health_report, dead_code_report = run_partial_analysis(
- repo_path, graph_builder, git_meta_map, parsed_files, file_diffs, log=_log.info
+ repo_path,
+ graph_builder,
+ git_meta_map,
+ parsed_files,
+ file_diffs,
+ source_map=source_map,
+ log=_log.info,
)
# Partial health has consumed the per-file ``BlameIndex``; drop it before
diff --git a/tests/unit/dead_code/test_prepass_source_map.py b/tests/unit/dead_code/test_prepass_source_map.py
new file mode 100644
index 000000000..d9239c029
--- /dev/null
+++ b/tests/unit/dead_code/test_prepass_source_map.py
@@ -0,0 +1,192 @@
+"""The four marker prepasses read ingestion's bytes, and fall back cleanly.
+
+``DeadCodeAnalyzer.__init__`` runs four scans over the whole indexed file
+set: dynamic-import markers, ``namespace JSX`` declarations, bundler
+``resolve.alias`` targets, and ``export { local as alias }`` maps. Each used
+to open every file itself, so a TS/JS repo paid four full-repo read passes
+before detection started. They now take ingestion's ``source_map``.
+
+These tests pin the three states that matter (map hit, map miss, no map at
+all) plus the decoding contract, since a prepass that decoded the handed-in
+bytes differently from the file it used to open would silently move findings.
+
+The discriminating trick throughout: the on-disk file and the ``source_map``
+entry carry *different* text. Whichever one a prepass actually consulted is
+then visible in the result.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+
+from repowise.core.analysis.dead_code import DeadCodeAnalyzer
+
+from ._helpers import _build_graph
+
+
+def _parsed(tmp_path: Path, rel: str, on_disk: str) -> SimpleNamespace:
+ """A ParsedFile stub for *rel*, with *on_disk* written to the real file."""
+ abs_path = tmp_path / rel
+ abs_path.parent.mkdir(parents=True, exist_ok=True)
+ abs_path.write_text(on_disk, encoding="utf-8")
+ return SimpleNamespace(file_info=SimpleNamespace(abs_path=str(abs_path)))
+
+
+def _analyzer(parsed_files: dict, source_map: dict[str, bytes] | None) -> DeadCodeAnalyzer:
+ """Analyzer over an empty graph, so only the __init__ prepasses are exercised."""
+ return DeadCodeAnalyzer(
+ _build_graph(nodes={}),
+ git_meta_map={},
+ parsed_files=parsed_files,
+ source_map=source_map,
+ )
+
+
+# --------------------------------------------------------------------------
+# find_dynamic_import_files
+# --------------------------------------------------------------------------
+
+
+def test_dynamic_markers_read_the_source_map_not_the_disk(tmp_path):
+ """A map hit wins: the marker is in the bytes, not in the file."""
+ parsed = {"pkg/loader.py": _parsed(tmp_path, "pkg/loader.py", "x = 1\n")}
+ source_map = {"pkg/loader.py": b"importlib.import_module('plugins')\n"}
+
+ assert _analyzer(parsed, source_map)._dynamic_import_files == {"pkg/loader.py"}
+
+
+def test_dynamic_markers_fall_back_to_disk_on_a_map_miss(tmp_path):
+ """A map that simply lacks this path must not lose the marker.
+
+ The update path hands over a map built for the files it re-read; anything
+ outside it has to keep reading from disk or the rescue silently narrows.
+ """
+ parsed = {"pkg/loader.py": _parsed(tmp_path, "pkg/loader.py", "__import__('plugins')\n")}
+ source_map = {"pkg/other.py": b"nothing here\n"}
+
+ assert _analyzer(parsed, source_map)._dynamic_import_files == {"pkg/loader.py"}
+
+
+def test_dynamic_markers_with_no_source_map_still_read_disk(tmp_path):
+ """``source_map=None`` is the pre-existing contract: every caller unchanged."""
+ parsed = {"pkg/loader.py": _parsed(tmp_path, "pkg/loader.py", "__import__('plugins')\n")}
+
+ assert _analyzer(parsed, None)._dynamic_import_files == {"pkg/loader.py"}
+
+
+def test_dynamic_markers_absent_from_both_sources(tmp_path):
+ """No marker anywhere is still no marker. The map is not a free pass."""
+ parsed = {"pkg/plain.py": _parsed(tmp_path, "pkg/plain.py", "x = 1\n")}
+
+ assert _analyzer(parsed, {"pkg/plain.py": b"y = 2\n"})._dynamic_import_files == set()
+
+
+# --------------------------------------------------------------------------
+# _find_jsx_namespace_files
+# --------------------------------------------------------------------------
+
+
+def test_jsx_namespace_scan_reads_the_source_map(tmp_path):
+ parsed = {"src/jsx.d.ts": _parsed(tmp_path, "src/jsx.d.ts", "export {};\n")}
+ source_map = {"src/jsx.d.ts": b"declare namespace JSX { interface Element {} }\n"}
+
+ assert _analyzer(parsed, source_map)._jsx_namespace_files == {"src/jsx.d.ts"}
+
+
+def test_jsx_namespace_scan_falls_back_to_disk(tmp_path):
+ parsed = {"src/jsx.d.ts": _parsed(tmp_path, "src/jsx.d.ts", "namespace JSX {}\n")}
+
+ assert _analyzer(parsed, {})._jsx_namespace_files == {"src/jsx.d.ts"}
+
+
+# --------------------------------------------------------------------------
+# _find_bundler_alias_targets
+# --------------------------------------------------------------------------
+
+
+def _alias_fixture(tmp_path: Path, config_on_disk: str) -> dict:
+ return {
+ "vite.config.ts": _parsed(tmp_path, "vite.config.ts", config_on_disk),
+ "src/shims/shiki.ts": _parsed(tmp_path, "src/shims/shiki.ts", "export default {};\n"),
+ }
+
+
+def test_bundler_alias_targets_read_the_source_map(tmp_path):
+ parsed = _alias_fixture(tmp_path, "export default {};\n")
+ source_map = {"vite.config.ts": b"alias: { shiki: './src/shims/shiki.ts' }\n"}
+
+ assert _analyzer(parsed, source_map)._bundler_alias_targets == {"src/shims/shiki.ts"}
+
+
+def test_bundler_alias_targets_fall_back_to_disk(tmp_path):
+ parsed = _alias_fixture(tmp_path, "alias: { shiki: './src/shims/shiki.ts' }\n")
+
+ assert _analyzer(parsed, {})._bundler_alias_targets == {"src/shims/shiki.ts"}
+
+
+# --------------------------------------------------------------------------
+# _find_ts_export_aliases
+# --------------------------------------------------------------------------
+
+
+def test_export_aliases_read_the_source_map(tmp_path):
+ parsed = {"src/history.ts": _parsed(tmp_path, "src/history.ts", "export {};\n")}
+ source_map = {"src/history.ts": b"export { HistoryWrapper as History };\n"}
+
+ assert _analyzer(parsed, source_map)._ts_export_aliases == {
+ "src/history.ts": {"HistoryWrapper": "History"}
+ }
+
+
+def test_export_aliases_fall_back_to_disk(tmp_path):
+ parsed = {
+ "src/history.ts": _parsed(
+ tmp_path, "src/history.ts", "export { HistoryWrapper as History };\n"
+ )
+ }
+
+ assert _analyzer(parsed, {})._ts_export_aliases == {
+ "src/history.ts": {"HistoryWrapper": "History"}
+ }
+
+
+# --------------------------------------------------------------------------
+# Decoding: a map hit and a disk read must agree on the same bytes
+# --------------------------------------------------------------------------
+
+# A UTF-8 BOM, a non-ASCII comment, and a lone 0xFF that is valid in the
+# locale codec but not in UTF-8. Three ways two decoders can diverge.
+_AWKWARD_BYTES = (
+ "\ufeff// caf\u00e9 \u00ff\nimportlib.import_module('plugins')\n".encode() + b"\xff\n"
+)
+
+
+def test_bom_and_non_ascii_decode_the_same_from_map_and_disk(tmp_path):
+ """The prepasses must not become encoding-sensitive by moving to bytes.
+
+ Reading via ``source_map`` decodes the bytes ourselves; reading from disk
+ used to go through ``Path.read_text(errors="ignore")``. Both paths decode
+ identically now, so a BOM or an undecodable byte cannot make the same file
+ match on one path and miss on the other.
+ """
+ abs_path = tmp_path / "pkg/awkward.py"
+ abs_path.parent.mkdir(parents=True, exist_ok=True)
+ abs_path.write_bytes(_AWKWARD_BYTES)
+ parsed = {"pkg/awkward.py": SimpleNamespace(file_info=SimpleNamespace(abs_path=str(abs_path)))}
+
+ from_map = _analyzer(parsed, {"pkg/awkward.py": _AWKWARD_BYTES})._dynamic_import_files
+ from_disk = _analyzer(parsed, None)._dynamic_import_files
+
+ assert from_map == from_disk == {"pkg/awkward.py"}
+
+
+def test_unreadable_file_with_no_map_entry_is_skipped(tmp_path):
+ """A path in neither place is dropped, not raised, because the pass is best-effort."""
+ parsed = {
+ "pkg/gone.py": SimpleNamespace(
+ file_info=SimpleNamespace(abs_path=str(tmp_path / "pkg/gone.py"))
+ )
+ }
+
+ assert _analyzer(parsed, {})._dynamic_import_files == set()
diff --git a/tests/unit/ingestion/test_warmup_source_map.py b/tests/unit/ingestion/test_warmup_source_map.py
new file mode 100644
index 000000000..cc67e8996
--- /dev/null
+++ b/tests/unit/ingestion/test_warmup_source_map.py
@@ -0,0 +1,154 @@
+"""The C/C++ and Swift entry-point warmups read ingestion's bytes.
+
+Both warmups scan file text for an entry marker across every file of their
+language. Neither ``ParsedFile`` nor ``FileInfo`` carries source, so both
+used to re-open each file during ``GraphBuilder.build()``, after ingestion
+had already read the whole repo. They now consult ``ctx.source_map``.
+
+Same discriminating trick as the dead-code prepass tests: disk and map carry
+different text, so the result says which one was read.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+
+import networkx as nx
+
+from repowise.core.ingestion.graph_warmups import _mark_cpp_entry_point_files, _warmup_swift
+
+
+def _parsed(tmp_path: Path, rel: str, language: str, on_disk: str) -> SimpleNamespace:
+ abs_path = tmp_path / rel
+ abs_path.parent.mkdir(parents=True, exist_ok=True)
+ abs_path.write_text(on_disk, encoding="utf-8")
+ return SimpleNamespace(file_info=SimpleNamespace(abs_path=str(abs_path), language=language))
+
+
+def _graph(*paths: str) -> nx.DiGraph:
+ g = nx.DiGraph()
+ for p in paths:
+ g.add_node(p, node_type="file", is_entry_point=False)
+ return g
+
+
+# --------------------------------------------------------------------------
+# C / C++
+# --------------------------------------------------------------------------
+
+
+def test_cpp_warmup_reads_the_source_map_not_the_disk(tmp_path):
+ parsed = {"src/mod.cpp": _parsed(tmp_path, "src/mod.cpp", "cpp", "int main() {}\n")}
+ graph = _graph("src/mod.cpp")
+
+ _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
+
+
+def test_cpp_warmup_falls_back_to_disk_on_a_map_miss(tmp_path):
+ parsed = {"src/mod.cpp": _parsed(tmp_path, "src/mod.cpp", "cpp", "PYBIND11_MODULE(m, x) {}\n")}
+ graph = _graph("src/mod.cpp")
+
+ _mark_cpp_entry_point_files(parsed, graph, {"src/other.cpp": b"nothing\n"})
+
+ assert graph.nodes["src/mod.cpp"]["is_entry_point"] is True
+
+
+def test_cpp_warmup_with_no_source_map_still_reads_disk(tmp_path):
+ parsed = {"src/mod.cpp": _parsed(tmp_path, "src/mod.cpp", "cpp", "PYBIND11_MODULE(m, x) {}\n")}
+ graph = _graph("src/mod.cpp")
+
+ _mark_cpp_entry_point_files(parsed, graph, None)
+
+ assert graph.nodes["src/mod.cpp"]["is_entry_point"] is True
+
+
+def test_cpp_warmup_leaves_unmarked_files_alone(tmp_path):
+ parsed = {"src/plain.cpp": _parsed(tmp_path, "src/plain.cpp", "cpp", "int f() { return 0; }\n")}
+ graph = _graph("src/plain.cpp")
+
+ _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
+
+
+# --------------------------------------------------------------------------
+# Swift
+# --------------------------------------------------------------------------
+
+
+def _swift_ctx(parsed: dict, graph: nx.DiGraph, source_map) -> SimpleNamespace:
+ return SimpleNamespace(graph=graph, parsed_files=parsed, source_map=source_map)
+
+
+def test_swift_warmup_reads_the_source_map_not_the_disk(tmp_path):
+ parsed = {"App.swift": _parsed(tmp_path, "App.swift", "swift", "struct App {}\n")}
+ graph = _graph("App.swift")
+
+ _warmup_swift(_swift_ctx(parsed, graph, {"App.swift": b"@main\nstruct App {}\n"}))
+
+ assert graph.nodes["App.swift"]["is_entry_point"] is True
+
+
+def test_swift_warmup_falls_back_to_disk_on_a_map_miss(tmp_path):
+ parsed = {"App.swift": _parsed(tmp_path, "App.swift", "swift", "@main\nstruct App {}\n")}
+ graph = _graph("App.swift")
+
+ _warmup_swift(_swift_ctx(parsed, graph, {}))
+
+ assert graph.nodes["App.swift"]["is_entry_point"] is True
+
+
+def test_swift_warmup_with_no_source_map_still_reads_disk(tmp_path):
+ parsed = {"App.swift": _parsed(tmp_path, "App.swift", "swift", "@main\nstruct App {}\n")}
+ graph = _graph("App.swift")
+
+ _warmup_swift(_swift_ctx(parsed, graph, None))
+
+ assert graph.nodes["App.swift"]["is_entry_point"] is True
+
+
+# --------------------------------------------------------------------------
+# Decoding parity
+# --------------------------------------------------------------------------
+
+# BOM, non-ASCII, and a byte that is not valid UTF-8. Both paths decode
+# utf-8 / replace, so the marker either survives on both or on neither.
+_AWKWARD_BYTES = "\ufeff// caf\u00e9\nPYBIND11_MODULE(m, x) {}\n".encode() + b"\xff\n"
+
+
+def test_awkward_bytes_decode_the_same_from_map_and_disk(tmp_path):
+ abs_path = tmp_path / "src/awkward.cpp"
+ abs_path.parent.mkdir(parents=True, exist_ok=True)
+ abs_path.write_bytes(_AWKWARD_BYTES)
+ parsed = {
+ "src/awkward.cpp": SimpleNamespace(
+ file_info=SimpleNamespace(abs_path=str(abs_path), language="cpp")
+ )
+ }
+
+ from_map = _graph("src/awkward.cpp")
+ _mark_cpp_entry_point_files(parsed, from_map, {"src/awkward.cpp": _AWKWARD_BYTES})
+ from_disk = _graph("src/awkward.cpp")
+ _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"]
+ is True
+ )
+
+
+def test_missing_file_with_no_map_entry_is_skipped(tmp_path):
+ parsed = {
+ "src/gone.cpp": SimpleNamespace(
+ file_info=SimpleNamespace(abs_path=str(tmp_path / "src/gone.cpp"), language="cpp")
+ )
+ }
+ graph = _graph("src/gone.cpp")
+
+ _mark_cpp_entry_point_files(parsed, graph, {})
+
+ assert graph.nodes["src/gone.cpp"]["is_entry_point"] is False