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
feat(dead-code): eliminate systematic false-positive classes (#886)
Raghav Chamadiya1b6e6c586af5
diff --git a/packages/cli/src/repowise/cli/commands/dead_code_cmd.py b/packages/cli/src/repowise/cli/commands/dead_code_cmd.pyindex 5ca6d3ff6..8724a0f77 100644--- a/packages/cli/src/repowise/cli/commands/dead_code_cmd.py+++ b/packages/cli/src/repowise/cli/commands/dead_code_cmd.py@@ -201,7 +201,12 @@ def dead_code_command(config["detect_unused_internals"] = kind == "unused_internal"config["detect_zombie_packages"] = kind == "zombie_package"- analyzer = DeadCodeAnalyzer(graph_builder.graph(), git_meta_map)+ # parsed_files powers the source-scan rescues (dynamic-import markers,+ # 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+ )report = analyzer.analyze(config)findings = report.findingsdiff --git a/packages/cli/src/repowise/cli/commands/health_cmd/command.py b/packages/cli/src/repowise/cli/commands/health_cmd/command.pyindex 96c54d83c..e144a8f85 100644--- a/packages/cli/src/repowise/cli/commands/health_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/health_cmd/command.py@@ -194,7 +194,7 @@ def health_command(parsed_files.append(parsed)except Exception:continue-+from repowise.core.ingestion import wire_tsconfig_resolverwire_tsconfig_resolver(diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.pyindex 5c9e28d85..8d0697378 100644--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py@@ -324,6 +324,93 @@ def _find_jsx_namespace_files(parsed_files: dict) -> set[str]:return matches+_BUNDLER_CONFIG_STEMS = ("vite.config", "webpack.config", "rollup.config", "rspack.config")++# Any quoted slash-containing path-ish string. Bundler configs reference+# alias targets both as ``'./src/shims/x.ts'`` and as bare segments fed to+# ``path.resolve(here, 'src/shims/x.ts')``; the parsed-files membership+# probe below keeps loose matches harmless.+_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]:+ """Repo-relative paths referenced from bundler config files.++ Vite/webpack ``resolve.alias`` entries substitute a bare package import+ with a local file (``shiki`` → ``src/shims/shiki.ts``): no source file+ ever imports the shim path, only the config names it, so the shim reads+ as unreachable. Any relative path string inside a bundler config that+ resolves to an indexed file marks that file reachable.+ """+ targets: set[str] = set()+ configs = [+ (path, pf)+ for path, pf in parsed_files.items()+ if Path(path).name.startswith(_BUNDLER_CONFIG_STEMS)+ ]+ for path, pf in configs:+ try:+ file_info = getattr(pf, "file_info", None)+ if file_info is None:+ continue+ source = Path(file_info.abs_path).read_text(errors="ignore")+ except Exception:+ continue+ config_dir = Path(path).parent+ for match in _RELATIVE_PATH_STRING_RE.finditer(source):+ base = _posix_normpath(config_dir, match.group(1))+ for suffix in _TS_PROBE_SUFFIXES:+ candidate = base + suffix+ if candidate in parsed_files:+ targets.add(candidate)+ break+ return targets+++def _posix_normpath(config_dir: Path, raw: str) -> str:+ """Join *raw* onto *config_dir* and normalise ``.``/``..`` as POSIX."""+ import posixpath++ return posixpath.normpath(posixpath.join(config_dir.as_posix(), raw))+++_TS_EXPORT_ALIAS_RE = re.compile(r"\bexport\s*\{([^}]*)\}(?!\s*from)")+++def _find_ts_export_aliases(parsed_files: dict) -> dict[str, dict[str, str]]:+ """Per-file ``{local_name: exported_alias}`` maps for TS/JS alias exports.++ ``export { ConversationHistoryWrapper as ConversationHistory }`` publishes+ the symbol under the alias, so importers pull ``ConversationHistory`` and+ the local name never appears in any ``imported_names`` edge. The unused-+ export pass consults this map to match the alias as well.+ """+ aliases: dict[str, dict[str, str]] = {}+ for path, pf in parsed_files.items():+ if not path.endswith((".ts", ".tsx", ".js", ".jsx", ".mts", ".mjs")):+ continue+ try:+ file_info = getattr(pf, "file_info", None)+ if file_info is None:+ continue+ source = Path(file_info.abs_path).read_text(errors="ignore")+ except Exception:+ continue+ file_map: dict[str, str] = {}+ for match in _TS_EXPORT_ALIAS_RE.finditer(source):+ for part in match.group(1).split(","):+ if " as " in part:+ local, _, alias = part.strip().partition(" as ")+ local, alias = local.strip(), alias.strip()+ if local and alias:+ file_map[local] = alias+ if file_map:+ aliases[path] = file_map+ return aliases++def _is_synthetic_node(node: str) -> bool:"""True for non-file graph nodes that should be skipped in 'is this dead?' passes.@@ -384,6 +471,14 @@ class DeadCodeAnalyzer:parsed_files or {}) | find_dynamic_edge_files(graph)self._jsx_namespace_files: set[str] = _find_jsx_namespace_files(parsed_files or {})+ # 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 {})+ # ``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 {}+ )# Lazily-built ``.go`` package-directory → file-node map, used by the# Go package-granular reachability hook (see ``go_reachability``).self._go_package_files: dict[str, list[str]] | None = None@@ -530,6 +625,10 @@ class DeadCodeAnalyzer:continueif self._is_api_contract(node_data):continue+ # Bundler ``resolve.alias`` targets are reached through the+ # aliased package name; only the config references them by path.+ if str(node) in self._bundler_alias_targets:+ continue# Go reachability is package-granular: a file with no direct# importer can still be live (entry-package sibling next to@@ -726,6 +825,12 @@ class DeadCodeAnalyzer:if file_dynamically_loaded:continue+ # Bundler ``resolve.alias`` shim: the whole module is substituted+ # for a package at build time — every public symbol is reachable+ # through the aliased import.+ if str(node) in self._bundler_alias_targets:+ continue+# Function/method line ranges in this file — used to skip symbols# whose definition is nested inside another function (closures,# inner helpers). Such symbols are only reachable from their@@ -770,6 +875,11 @@ class DeadCodeAnalyzer:continueif sym_name in _ENTRY_POINT_SYMBOL_NAMES:continue+ # VS Code extension lifecycle: the host calls ``activate`` /+ # ``deactivate`` on the ``main`` module (conventionally+ # ``extension.ts``) — no in-repo importer ever names them.+ if sym_name in ("activate", "deactivate") and Path(str(node)).stem == "extension":+ continue# Compiler-builtin macros defined as a fallback# (``#if !defined(__has_include)\n#define __has_include(h) 0``).# The tree-sitter cpp grammar emits the ``#define`` as a@@ -868,11 +978,19 @@ class DeadCodeAnalyzer:sym_name.endswith(suffix) for suffix in ("_DEPRECATED", "_LEGACY", "_COMPAT"))+ # ``export { local as alias }`` publishes the symbol under the+ # alias; importers carry the alias in ``imported_names``.+ export_alias = self._ts_export_aliases.get(str(node), {}).get(sym_name)+has_importers = Falsefor pred in self.graph.predecessors(node):edge_data = self.graph[pred][node]imported_names = edge_data.get("imported_names", [])- if sym_name in imported_names or "*" in imported_names:+ if (+ sym_name in imported_names+ or "*" in imported_names+ or (export_alias is not None and export_alias in imported_names)+ ):has_importers = Truebreakdiff --git a/packages/core/src/repowise/core/analysis/dead_code/constants.py b/packages/core/src/repowise/core/analysis/dead_code/constants.pyindex 5df6995c6..063a01d17 100644--- a/packages/core/src/repowise/core/analysis/dead_code/constants.py+++ b/packages/core/src/repowise/core/analysis/dead_code/constants.py@@ -72,20 +72,20 @@ _NEVER_FLAG_PATTERNS: tuple[str, ...] = (# ---- .NET / C# conventions --------------------------------------# Implicit / generated / framework-loaded files that have no# static importers by design.- "*GlobalUsings.cs", # global usings — file-implicit, never imported by symbol- "*.xaml.cs", # XAML code-behind, wired by the source generator+ "*GlobalUsings.cs", # global usings — file-implicit, never imported by symbol+ "*.xaml.cs", # XAML code-behind, wired by the source generator"*.xaml","*.razor",- "*.razor.cs", # Blazor code-behind- "*.razor.js", # Blazor JS interop side-files+ "*.razor.cs", # Blazor code-behind+ "*.razor.js", # Blazor JS interop side-files"*.cshtml","*.cshtml.cs",- "*.designer.cs", # Roslyn designer+ "*.designer.cs", # Roslyn designer"*Designer.cs",- "*.g.cs", # Roslyn-generated+ "*.g.cs", # Roslyn-generated"*.g.i.cs","*.AssemblyInfo.cs",- "*MauiProgram.cs", # MAUI app entry — invoked by host, not imported+ "*MauiProgram.cs", # MAUI app entry — invoked by host, not imported"*App.xaml.cs","*AppShell.xaml.cs",# Aspire / ServiceDefaults host wiring is consumed by AppHost project graph,@@ -380,29 +380,29 @@ _NEVER_FLAG_PATTERNS: tuple[str, ...] = ("*/out/Release/**",# Generated source-file patterns. Wired in at build time, no static# importer; the analyzer should silence them universally.- "moc_*.cpp", # Qt MOC+ "moc_*.cpp", # Qt MOC"moc_*.cc",- "ui_*.h", # Qt UIC- "qrc_*.cpp", # Qt RCC+ "ui_*.h", # Qt UIC+ "qrc_*.cpp", # Qt RCC"qrc_*.cc",- "*.moc", # inline MOC includes- "*.pb.cc", # protoc generated+ "*.moc", # inline MOC includes+ "*.pb.cc", # protoc generated"*.pb.h",- "*.pb-c.c", # protobuf-c+ "*.pb-c.c", # protobuf-c"*.pb-c.h",- "*.grpc.pb.cc", # protoc-gen-grpc+ "*.grpc.pb.cc", # protoc-gen-grpc"*.grpc.pb.h",- "*.capnp.c++", # Cap'n Proto+ "*.capnp.c++", # Cap'n Proto"*.capnp.h","*.flatbuffers.h",- "*_generated.h", # FlatBuffers convention- "*.tab.c", # Bison / Yacc+ "*_generated.h", # FlatBuffers convention+ "*.tab.c", # Bison / Yacc"*.tab.h",- "*.yy.c", # Flex / Lex+ "*.yy.c", # Flex / Lex"*_lex.cc",- "*_wrap.cxx", # SWIG+ "*_wrap.cxx", # SWIG"*_wrap.cpp",- "*.cython.cpp", # Cython+ "*.cython.cpp", # Cython# Vendored / third-party roots. The existing ``vendor`` / ``third_party``# / ``deps`` globs only cover ``.c`` / ``.h``; extend them to the full# C++ extension set, and add the additional vendor conventions@@ -747,21 +747,21 @@ _NEVER_FLAG_PATTERNS: tuple[str, ...] = (# Generated-name suffixes that have unambiguous tool ownership."*_Generated.java","*$Generated.java",- "*MapperImpl.java", # MapStruct compile-time impl+ "*MapperImpl.java", # MapStruct compile-time impl"*Dagger*.java","*AutoValue_*.java","*ServiceGrpc.java",- "*OuterClass.java", # protoc generated outer class+ "*OuterClass.java", # protoc generated outer class"*$WrapperImpl.java",# ---- Dart / Flutter conventions ---------------------------------------# build_runner codegen outputs — linked from their source file via# ``part`` directives, regenerated by tooling, never hand-imported."*.g.dart",- "*.freezed.dart", # freezed data classes- "*.gr.dart", # auto_route generated router- "*.config.dart", # injectable DI config- "*.mocks.dart", # mockito codegen- "*.gen.dart", # flutter_gen assets+ "*.freezed.dart", # freezed data classes+ "*.gr.dart", # auto_route generated router+ "*.config.dart", # injectable DI config+ "*.mocks.dart", # mockito codegen+ "*.gen.dart", # flutter_gen assets# package:test / integration_test runners execute these directly; no# static importer exists. ``example/`` is pub.dev's showcase convention."*_test.dart",@@ -782,6 +782,9 @@ _NEVER_FLAG_PATTERNS: tuple[str, ...] = (_FRAMEWORK_DECORATORS: tuple[str, ...] = ("pytest.fixture","pytest.mark",+ # Unqualified ``from pytest import fixture`` form — the decorator text is+ # bare ``fixture``, which the dotted prefixes above never match.+ "fixture",# Flask"app.route","blueprint.route",@@ -836,7 +839,7 @@ _FRAMEWORK_DECORATORS: tuple[str, ...] = ("Configuration","ControllerAdvice","RestControllerAdvice",- "Mapper", # MapStruct + MyBatis+ "Mapper", # MapStruct + MyBatis"SpringBootApplication","SpringBootConfiguration","EnableAutoConfiguration",@@ -848,14 +851,14 @@ _FRAMEWORK_DECORATORS: tuple[str, ...] = ("Entity","MappedSuperclass","Embeddable",- "Converter", # JPA AttributeConverter+ "Converter", # JPA AttributeConverter"QuarkusMain","QuarkusTest","QuarkusIntegrationTest","NativeImageTest","MicronautApplication","MicronautTest",- "Path", # JAX-RS+ "Path", # JAX-RS"Provider","WebServlet","WebFilter",@@ -875,7 +878,7 @@ _FRAMEWORK_DECORATORS: tuple[str, ...] = ("EventListener","TransactionalEventListener","Scheduled",- "Schedule", # Quarkus+ "Schedule", # Quarkus"JmsListener","KafkaListener","RabbitListener",@@ -905,11 +908,11 @@ _FRAMEWORK_DECORATORS: tuple[str, ...] = ("AfterClass","DataProvider","ArchTest",- "Container", # Testcontainers+ "Container", # Testcontainers"DynamicTest",- "JsonCreator", # Jackson factory method — reflectively invoked+ "JsonCreator", # Jackson factory method — reflectively invoked"JsonProperty",- "Mojo", # Maven plugin entry+ "Mojo", # Maven plugin entry"Goal","RegisterForReflection",# ---- JVM: routing / HTTP-verb annotations -----------------------@@ -926,7 +929,7 @@ _FRAMEWORK_DECORATORS: tuple[str, ...] = ("ExceptionHandler","InitBinder","ModelAttribute",- "GET", # JAX-RS / Quarkus / Micronaut+ "GET", # JAX-RS / Quarkus / Micronaut"POST","PUT","DELETE",@@ -955,10 +958,33 @@ _FRAMEWORK_DECORATOR_SUFFIXES: tuple[str, ...] = (".command",".group",".callback",+ # Registry registration: ``@filter_registry.register`` / ``@hooks.register``+ # wires the symbol in by side effect; consumers look it up by string key,+ # so the name never appears in an import. Any decorator whose attribute+ # path ends in ``.register`` is a registration, whatever the registry+ # object is called.+ ".register",+ # FastAPI / Flask / Sanic route decorators on a receiver the prefix list+ # doesn't anticipate (``api = FastAPI()``, ``_repo_health_router =+ # APIRouter()``). A decorator ending in an HTTP verb or routing method is+ # a route registration regardless of the local variable name — the same+ # reasoning that added ``.command`` for locally-named Click groups.+ ".route",+ ".get",+ ".post",+ ".put",+ ".delete",+ ".patch",+ ".head",+ ".options",+ ".websocket",+ ".middleware",+ ".exception_handler",+ # Celery apps under a non-``app``/``celery`` local name (``@worker.task``).+ ".task",)-# Default dynamic patterns (plugins, handlers, etc.)_DEFAULT_DYNAMIC_PATTERNS: tuple[str, ...] = ("*Plugin",@@ -983,37 +1009,39 @@ _DEFAULT_DYNAMIC_PATTERNS: tuple[str, ...] = (# on the first segment and treats everything as a candidate package; without# this guard, dotfile dirs like `.github` get reported as "zombie packages# with no importers" on every repo.-_NEVER_PACKAGE_DIRS: frozenset[str] = frozenset({- ".github",- ".gitlab",- ".vscode",- ".idea",- ".aspire",- ".config",- ".devcenter",- ".devcontainer",- ".husky",- ".changeset",- ".azure",- ".azuredevops",- ".circleci",- ".buildkite",- ".cargo",- ".yarn",- "docs",- "doc",- "documentation",- "examples",- "scripts",- "assets",- "static",- "public",- "tests",- "test",- "benches",- "bench",- "fuzz",-})+_NEVER_PACKAGE_DIRS: frozenset[str] = frozenset(+ {+ ".github",+ ".gitlab",+ ".vscode",+ ".idea",+ ".aspire",+ ".config",+ ".devcenter",+ ".devcontainer",+ ".husky",+ ".changeset",+ ".azure",+ ".azuredevops",+ ".circleci",+ ".buildkite",+ ".cargo",+ ".yarn",+ "docs",+ "doc",+ "documentation",+ "examples",+ "scripts",+ "assets",+ "static",+ "public",+ "tests",+ "test",+ "benches",+ "bench",+ "fuzz",+ }+)# Path segments that indicate test fixture / sample data directories.@@ -1035,17 +1063,19 @@ _FIXTURE_PATH_SEGMENTS: tuple[str, ...] = (# ``namespace JSX`` block is an integration point with the JSX# transformer, not dead code. The set is intentionally small and# targeted; anything broader risks masking genuinely-unused exports.-_TS_JSX_NAMESPACE_TYPES: frozenset[str] = frozenset({- "IntrinsicElements",- "IntrinsicAttributes",- "IntrinsicClassAttributes",- "Element",- "ElementType",- "ElementClass",- "ElementAttributesProperty",- "ElementChildrenAttribute",- "LibraryManagedAttributes",-})+_TS_JSX_NAMESPACE_TYPES: frozenset[str] = frozenset(+ {+ "IntrinsicElements",+ "IntrinsicAttributes",+ "IntrinsicClassAttributes",+ "Element",+ "ElementType",+ "ElementClass",+ "ElementAttributesProperty",+ "ElementChildrenAttribute",+ "LibraryManagedAttributes",+ }+)def _is_fixture_path(path: str) -> bool:diff --git a/packages/core/src/repowise/core/ingestion/extractors/visibility.py b/packages/core/src/repowise/core/ingestion/extractors/visibility.pyindex eec9197a4..3d7cddbc8 100644--- a/packages/core/src/repowise/core/ingestion/extractors/visibility.py+++ b/packages/core/src/repowise/core/ingestion/extractors/visibility.py@@ -11,6 +11,7 @@ parser calls it after the generic ``visibility_fn`` for C/C++ files.from __future__ import annotations+import refrom collections.abc import Callablefrom typing import TYPE_CHECKING@@ -125,6 +126,83 @@ def php_visibility(_name: str, modifier_texts: list[str]) -> str:return "public"+# ---------------------------------------------------------------------------+# TS / JS node-aware visibility refinement+# ---------------------------------------------------------------------------++# ``export { a, b as c }`` lists (with or without a ``from`` clause),+# ``export default name``, and TS ``export = name`` — the deferred-export+# forms that make a plainly-declared top-level symbol part of the module's+# public surface.+_TS_EXPORT_LIST_RE = re.compile(r"\bexport\s*\{([^}]*)\}")+_TS_EXPORT_DEFAULT_RE = re.compile(r"\bexport\s+default\s+([A-Za-z_$][\w$]*)")+_TS_EXPORT_ASSIGN_RE = re.compile(r"\bexport\s*=\s*([A-Za-z_$][\w$]*)")+_TS_CJS_EXPORTS_RE = re.compile(r"\bmodule\.exports\b|\bexports\s*[.\[]")++_TS_CLASSLIKE_ANCESTORS = frozenset(+ {+ "class_declaration",+ "abstract_class_declaration",+ "class_body",+ "interface_body",+ "enum_body",+ "internal_module", # TS ``namespace X { ... }``+ }+)+++def ts_deferred_export_names(src: str) -> frozenset[str] | None:+ """Names exported after their declaration, or ``None`` when unsafe to track.++ CommonJS surfaces (``module.exports`` / ``exports.x``) assign exports+ dynamically, so per-name tracking is unreliable — return ``None`` and the+ caller keeps everything public (the safe direction).+ """+ if _TS_CJS_EXPORTS_RE.search(src):+ return None+ names: set[str] = set()+ for m in _TS_EXPORT_LIST_RE.finditer(src):+ for part in m.group(1).split(","):+ # ``local as exported`` — the local name is what we match against.+ base = part.strip().split(" as ")[0].strip()+ if base:+ names.add(base)+ for regex in (_TS_EXPORT_DEFAULT_RE, _TS_EXPORT_ASSIGN_RE):+ for m in regex.finditer(src):+ names.add(m.group(1))+ return frozenset(names)+++def refine_ts_visibility(+ def_node: Node, current_visibility: str, name: str, deferred_exports: frozenset[str] | None+) -> str:+ """Demote non-exported TS/JS top-level symbols to ``private``.++ ``ts_visibility`` only sees class-member accessibility modifiers, so every+ top-level declaration lands ``public`` whether or not it carries an+ ``export`` — which makes plainly-private module helpers eligible for the+ dead-code unused-export pass and inflates the file's derived export list.+ A symbol stays public only when its declaration sits under an+ ``export_statement`` or its name appears in a deferred-export form.+ Class/namespace members are left untouched (their visibility is governed+ by the member modifiers and the enclosing declaration's export).+ """+ if current_visibility != "public":+ return current_visibility+ if deferred_exports is None:+ return current_visibility+ node = def_node.parent+ while node is not None:+ if node.type == "export_statement":+ return "public"+ if node.type in _TS_CLASSLIKE_ANCESTORS:+ return current_visibility+ node = node.parent+ if name in deferred_exports:+ return "public"+ return "private"++# ---------------------------------------------------------------------------# C / C++ node-aware visibility refinement# ---------------------------------------------------------------------------@@ -133,7 +211,7 @@ _CPP_EXPORT_MARKERS: tuple[str, ...] = ("__declspec(dllexport)","__declspec( dllexport )",'visibility("default")',- "visibility(\"default\")",+ 'visibility("default")',# WebAssembly / emscripten / WASI export surfaces. A function compiled# to WASM and called across the JS<->WASM boundary carries one of these# markers; without them the export reads as an unused symbol because no@@ -147,7 +225,7 @@ _CPP_EXPORT_MARKERS: tuple[str, ...] = ("WASM_EXPORT","export_name(","__attribute__((used))",- "__attribute__((visibility(\"default\")))",+ '__attribute__((visibility("default")))',)@@ -163,7 +241,11 @@ def _preceding_access_specifier(def_node: Node) -> str | None:while sibling is not None:if sibling.type == "access_specifier":# The specifier's text is "public" / "private" / "protected".- children = [c for c in sibling.children if c.is_named or c.type in ("public", "private", "protected")]+ children = [+ c+ for c in sibling.children+ if c.is_named or c.type in ("public", "private", "protected")+ ]for c in children:if c.type in ("public", "private", "protected"):return c.type@@ -218,9 +300,7 @@ def _has_file_scope_static(def_node: Node, src: str) -> bool:return False-def refine_cpp_visibility(- def_node: Node, current_visibility: str, src: str-) -> tuple[str, bool]:+def refine_cpp_visibility(def_node: Node, current_visibility: str, src: str) -> tuple[str, bool]:"""Return ``(visibility, is_exported)`` for a C/C++ symbol.Inputs:diff --git a/packages/core/src/repowise/core/ingestion/graph/builder.py b/packages/core/src/repowise/core/ingestion/graph/builder.pyindex d0242976f..ef4a81ef4 100644--- a/packages/core/src/repowise/core/ingestion/graph/builder.py+++ b/packages/core/src/repowise/core/ingestion/graph/builder.py@@ -342,6 +342,12 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehydfrom ..resolvers.cpp import resolve_cpp_import_alltargets = resolve_cpp_import_all(imp.module_path, path, ctx)+ elif _lang == "python":+ # ``from pkg import submodule`` must also edge into the+ # submodule file, not just ``pkg/__init__.py`` (#666).+ from ..resolvers.python import resolve_python_import_all++ targets = resolve_python_import_all(imp, path, ctx)else:single = resolve_import(imp.module_path, path, _lang, ctx)targets = (single,) if single else ()@@ -462,9 +468,7 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd# the same type map and otherwise rebuilds the index from disk.# Only stashed when this build pruned nested git repos, because a# standalone rebuild always prunes — the maps must be identical.- self.dotnet_index = (- getattr(ctx, "_dotnet_index", None) if self._prune_nested_git else None- )+ self.dotnet_index = getattr(ctx, "_dotnet_index", None) if self._prune_nested_git else None# Count edge types for loggingedge_counts: dict[str, int] = {}diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.pyindex 599cbfb10..d31fd9010 100644--- a/packages/core/src/repowise/core/ingestion/parser.py+++ b/packages/core/src/repowise/core/ingestion/parser.py@@ -44,7 +44,11 @@ from .extractors import ()from .extractors.bindings.python import expand_bare_relative_importsfrom .extractors.synthetic_symbols import extract_synthetic_symbols-from .extractors.visibility import refine_cpp_visibility+from .extractors.visibility import (+ refine_cpp_visibility,+ refine_ts_visibility,+ ts_deferred_export_names,+)from .language_configs import LANGUAGE_CONFIGS, LanguageConfigfrom .languages.registry import REGISTRY as _LANG_REGISTRYfrom .models import (@@ -356,6 +360,12 @@ class ASTParser:symbols: list[Symbol] = []seen: set[tuple[int, str]] = set() # (start_line, name) — dedup decorated dupes+ # Deferred-export names (``export { x }`` / ``export default x``),+ # computed once per file for the TS/JS visibility refinement.+ ts_deferred_exports: frozenset[str] | None = None+ if file_info.language in ("typescript", "javascript"):+ ts_deferred_exports = ts_deferred_export_names(src)+for capture_dict in matches:def_nodes = capture_dict.get("symbol.def", [])name_nodes = capture_dict.get("symbol.name", [])@@ -482,6 +492,10 @@ class ASTParser:# modifier text. Refine after the generic fn ran.if file_info.language in ("cpp", "c"):visibility, is_exported_symbol = refine_cpp_visibility(def_node, visibility, src)+ # TS/JS: a top-level declaration is only public when exported —+ # inline, via ``export { x }`` lists, or ``export default x``.+ elif file_info.language in ("typescript", "javascript"):+ visibility = refine_ts_visibility(def_node, visibility, name, ts_deferred_exports)# Parent class detectionparent_name = self._find_parent(def_node, config, receiver_nodes, src)diff --git a/packages/core/src/repowise/core/ingestion/resolvers/python.py b/packages/core/src/repowise/core/ingestion/resolvers/python.pyindex 9b76e8fdf..40355ed59 100644--- a/packages/core/src/repowise/core/ingestion/resolvers/python.py+++ b/packages/core/src/repowise/core/ingestion/resolvers/python.py@@ -3,10 +3,14 @@from __future__ import annotationsfrom pathlib import Path+from typing import TYPE_CHECKINGfrom ..languages.python_modules import build_python_module_indexfrom .context import ResolverContext+if TYPE_CHECKING:+ from ..models import Import+def _module_index(ctx: ResolverContext) -> dict[str, str]:"""Source-root-aware dotted-module → path index, built once per context.@@ -70,3 +74,44 @@ def resolve_python_import(module_path: str, importer_path: str, ctx: ResolverCon# Stem-only fallbackstem = module_path.split(".")[-1].lower()return ctx.stem_lookup(stem)+++def resolve_python_import_all(+ imp: Import, importer_path: str, ctx: ResolverContext+) -> tuple[str, ...]:+ """Resolve a Python import, fanning edges out to submodule files.++ ``from pkg import a, b`` resolves to ``pkg/__init__.py`` only, so when an+ imported name is itself a submodule file the submodule never gains an+ inbound edge and the dead-code analyzer reports it unreachable (#666) —+ FastAPI apps wiring routers through their package are the canonical hit.+ Probe every imported name against the package directory and emit the+ submodule targets alongside the package itself. The bare-relative form+ (``from . import a, b``) is already split upstream by+ ``expand_bare_relative_imports``; this covers the named-package forms,+ both absolute and relative.+ """+ base = resolve_python_import(imp.module_path, importer_path, ctx)+ if base is None:+ return ()+ targets = [base]+ names = imp.imported_names or []+ if base.endswith("__init__.py") and names and names != ["*"]:+ index = _module_index(ctx)+ base_dir = Path(base).parent.as_posix()+ for name in names:+ if not name or name == "*" or "." in name:+ continue+ # Source-root-aware index first (absolute imports), then direct+ # sibling probes, which also cover the relative form.+ hit = None+ if not imp.is_relative:+ hit = index.get(f"{imp.module_path}.{name}")+ if hit is None:+ for candidate in (f"{base_dir}/{name}.py", f"{base_dir}/{name}/__init__.py"):+ if candidate in ctx.path_set:+ hit = candidate+ break+ if hit and hit != base:+ targets.append(hit)+ return tuple(dict.fromkeys(targets))diff --git a/packages/core/src/repowise/core/ingestion/traverser.py b/packages/core/src/repowise/core/ingestion/traverser.pyindex c15b0a6d2..4485d7800 100644--- a/packages/core/src/repowise/core/ingestion/traverser.py+++ b/packages/core/src/repowise/core/ingestion/traverser.py@@ -266,6 +266,14 @@ class FileTraverser:self._submodule_paths: frozenset[str] = _parse_gitmodules(self.repo_root)self._include_submodules = include_submodulesself._include_nested_repos = include_nested_repos+ # Dotted-module targets of pyproject console scripts. A CLI entry+ # module (``repowise-augment = "repowise.cli.augment_hook:main"``)+ # has no in-repo importer, so without this it reads as unreachable+ # unless its filename happens to match an entry-stem heuristic.+ self._console_script_modules = _collect_console_script_modules(+ self.repo_root,+ prune_nested_git=not (include_submodules or include_nested_repos),+ )self.stats = TraversalStats()self._count_lock = threading.Lock()log.info(@@ -503,6 +511,7 @@ class FileTraverser:filename in _ENTRY_POINT_NAMESor filename.endswith(_ENTRY_POINT_NAME_SUFFIXES)or _stem_is_entry_point(abs_path)+ or _is_console_script_target(rel_str, self._console_script_modules)),)@@ -664,6 +673,73 @@ def _stem_is_entry_point(abs_path: Path) -> bool:return stem in _ENTRY_POINT_STEMS+def _collect_console_script_modules(+ repo_root: Path, *, prune_nested_git: bool = True+) -> frozenset[str]:+ """Dotted-module targets declared in pyproject console-script tables.++ Reads ``[project.scripts]``, ``[project.gui-scripts]``, and every+ ``[project.entry-points.*]`` group from each ``pyproject.toml`` in the+ repo. Values look like ``"repowise.cli.augment_hook:main"`` — the part+ before the colon names the module a console launcher imports at runtime.+ Best-effort: unparsable files are skipped.+ """+ import tomllib++ from repowise.core.fs_walk import iter_glob++ modules: set[str] = set()+ try:+ config_files = list(+ iter_glob(repo_root, ("pyproject.toml",), prune_nested_git=prune_nested_git)+ )+ except OSError:+ return frozenset()+ for config_file in config_files:+ try:+ data = tomllib.loads(config_file.read_text(encoding="utf-8"))+ except Exception:+ continue+ project = data.get("project")+ if not isinstance(project, dict):+ continue+ groups = [project.get("scripts"), project.get("gui-scripts")]+ entry_points = project.get("entry-points")+ if isinstance(entry_points, dict):+ groups.extend(entry_points.values())+ for group in groups:+ if not isinstance(group, dict):+ continue+ for target in group.values():+ if isinstance(target, str):+ module = target.split(":", 1)[0].strip()+ if module:+ modules.add(module)+ return frozenset(modules)+++def _is_console_script_target(rel_path: str, modules: frozenset[str]) -> bool:+ """True when *rel_path* is the file a console-script module target names.++ The repo-relative path is compared as a dot-boundary suffix because the+ dotted module omits source-root prefixes (``src/``, ``packages/*/src/``).+ Single-segment module names must match exactly — a bare ``main`` target+ must not blanket-flag every ``main.py``-adjacent path suffix.+ """+ if not modules or not rel_path.endswith(".py"):+ return False+ dotted = rel_path[: -len(".py")]+ if dotted.endswith("/__init__"):+ dotted = dotted[: -len("/__init__")]+ dotted = dotted.replace("/", ".")+ for module in modules:+ if dotted == module:+ return True+ if "." in module and dotted.endswith("." + module):+ return True+ return False++def _primary_language_in(directory: Path, *, prune_nested_git: bool = True) -> LanguageTag:from repowise.core.fs_walk import walk_repodiff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.pyindex 298352b89..f965ad4b9 100644--- a/packages/core/src/repowise/core/pipeline/incremental.py+++ b/packages/core/src/repowise/core/pipeline/incremental.py@@ -119,6 +119,20 @@ def build_repo_graph(if collect_sources:source_map[fi.path] = sourcegraph_builder.add_file(parsed)++ # TS/JS path aliases (``@/components/...``) resolve only when the+ # tsconfig resolver is attached before build(); without it the alias+ # targets read as external nodes and every aliased file looks+ # unreachable to the dead-code analyzer (#648 — this rebuild path was+ # missed when the CLI commands were wired).+ from repowise.core.ingestion import wire_tsconfig_resolver++ wire_tsconfig_resolver(+ graph_builder,+ repo_path,+ include_submodules=include_submodules,+ include_nested_repos=include_nested_repos,+ )graph_builder.build()if parse_cache is not None:parse_cache.save()@@ -310,7 +324,11 @@ def run_partial_analysis(try:from repowise.core.analysis.dead_code import DeadCodeAnalyzer- _analyzer_partial = DeadCodeAnalyzer(graph_builder.graph(), git_meta_map)+ # 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+ )_changed_paths_partial = [fd.path for fd in file_diffs]dead_code_report = _analyzer_partial.analyze_partial(_changed_paths_partial)if dead_code_report.total_findings:diff --git a/tests/unit/dead_code/test_decorators_dynamic.py b/tests/unit/dead_code/test_decorators_dynamic.pyindex 36b638a14..1c999810e 100644--- a/tests/unit/dead_code/test_decorators_dynamic.py+++ b/tests/unit/dead_code/test_decorators_dynamic.py@@ -329,3 +329,46 @@ def test_unrelated_dot_command_function_still_flagged():report = analyzer.analyze({"detect_unreachable_files": False, "detect_zombie_packages": False})names = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT}assert "expensive_lookup" in names+++ "decorator",+ [+ # Route decorator on a receiver the prefix list doesn't know+ # (``_repo_health_router = APIRouter()``): the HTTP-verb suffix match+ # must rescue it regardless of the local variable name.+ '@_repo_health_router.get("/health/coordinator")',+ '@api.websocket("/ws")',+ # Registry registration by side effect: consumers resolve the symbol+ # by string key, never by import.+ '@filter_registry.register("git_status")',+ # ``from pytest import fixture`` leaves a bare, undotted decorator.+ "@fixture",+ ],+)+def test_renamed_receiver_and_registry_decorators_excluded(decorator):+ g = _build_graph(+ nodes={+ "pkg/wired.py": {+ "is_entry_point": False,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": 1,+ "symbols": [+ {+ "name": "wired_symbol",+ "kind": "function",+ "visibility": "public",+ "decorators": [decorator],+ "start_line": 1,+ "end_line": 10,+ "complexity_estimate": 1,+ },+ ],+ },+ },+ )+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})+ report = analyzer.analyze({"detect_unreachable_files": False, "detect_zombie_packages": False})+ names = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT}+ assert "wired_symbol" not in namesdiff --git a/tests/unit/dead_code/test_fp_rescues.py b/tests/unit/dead_code/test_fp_rescues.pynew file mode 100644index 000000000..f8ea5ae89--- /dev/null+++ b/tests/unit/dead_code/test_fp_rescues.py@@ -0,0 +1,160 @@+"""FP-class rescues: VS Code lifecycle, export aliases, bundler alias shims.++Each of these surfaced as a manually-verified false positive in the dogfood+audit: ``deactivate`` in ``extension.ts`` (called by the extension host),+``export { Local as Alias }`` symbols whose importers carry only the alias,+and Vite ``resolve.alias`` shim modules referenced only by the bundler+config.+"""++from __future__ import annotations++from pathlib import Path+from types import SimpleNamespace++from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind+from tests.unit.dead_code._helpers import _build_graph++_EXPORT_CONFIG = {"detect_unreachable_files": False, "detect_zombie_packages": False}+++def _sym(name: str, **overrides) -> dict:+ base = {+ "name": name,+ "kind": "function",+ "visibility": "public",+ "decorators": [],+ "start_line": 1,+ "end_line": 5,+ "complexity_estimate": 1,+ }+ base.update(overrides)+ return base+++def _file_node(symbols: list[dict], language: str = "typescript") -> dict:+ return {+ "is_entry_point": False,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": len(symbols),+ "symbols": symbols,+ "language": language,+ }+++def _parsed_stub(tmp_path: Path, rel: str, source: str) -> SimpleNamespace:+ abs_path = tmp_path / rel+ abs_path.parent.mkdir(parents=True, exist_ok=True)+ abs_path.write_text(source, encoding="utf-8")+ return SimpleNamespace(file_info=SimpleNamespace(abs_path=str(abs_path)))+++def _unused_export_names(analyzer: DeadCodeAnalyzer) -> set[str]:+ report = analyzer.analyze(_EXPORT_CONFIG)+ return {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT}+++def test_vscode_lifecycle_exports_not_flagged():+ g = _build_graph(+ nodes={+ "src/extension.ts": _file_node(+ [_sym("activate"), _sym("deactivate"), _sym("helperFn", start_line=7, end_line=9)]+ ),+ },+ )+ names = _unused_export_names(DeadCodeAnalyzer(g, git_meta_map={}))+ assert "activate" not in names+ assert "deactivate" not in names+ # Only the lifecycle pair is exempt, not the rest of the file.+ assert "helperFn" in names+++def test_deactivate_outside_extension_module_still_flagged():+ g = _build_graph(+ nodes={"src/util.ts": _file_node([_sym("deactivate")])},+ )+ names = _unused_export_names(DeadCodeAnalyzer(g, git_meta_map={}))+ assert "deactivate" in names+++def test_export_alias_importer_rescues_local_symbol(tmp_path: Path):+ src = (+ "function ConversationHistoryWrapper() {}\n"+ "export { ConversationHistoryWrapper as ConversationHistory };\n"+ )+ parsed = {"web/history.tsx": _parsed_stub(tmp_path, "web/history.tsx", src)}+ g = _build_graph(+ nodes={+ "web/history.tsx": _file_node([_sym("ConversationHistoryWrapper")]),+ "web/page.tsx": _file_node([]),+ },+ edges=[+ (+ "web/page.tsx",+ "web/history.tsx",+ {"edge_type": "imports", "imported_names": ["ConversationHistory"]},+ ),+ ],+ )+ names = _unused_export_names(DeadCodeAnalyzer(g, git_meta_map={}, parsed_files=parsed))+ assert "ConversationHistoryWrapper" not in names+++def test_export_alias_without_importer_still_flagged(tmp_path: Path):+ src = "function Widget() {}\nexport { Widget as PublicWidget };\n"+ parsed = {"web/widget.tsx": _parsed_stub(tmp_path, "web/widget.tsx", src)}+ g = _build_graph(+ nodes={+ "web/widget.tsx": _file_node([_sym("Widget")]),+ "web/page.tsx": _file_node([]),+ },+ edges=[+ (+ "web/page.tsx",+ "web/widget.tsx",+ {"edge_type": "imports", "imported_names": ["SomethingElse"]},+ ),+ ],+ )+ names = _unused_export_names(DeadCodeAnalyzer(g, git_meta_map={}, parsed_files=parsed))+ assert "Widget" in names+++def test_bundler_alias_shim_rescued(tmp_path: Path):+ # Both alias shapes seen in the wild: a plain relative string and a+ # bare segment fed through ``path.resolve(here, ...)``.+ config_src = (+ "export default defineConfig({\n"+ " resolve: { alias: [\n"+ " { find: /^shiki$/, replacement: './src/shims/shiki.ts' },\n"+ ' { find: "next-themes", replacement: path.resolve(here, "src/shims/next-themes.ts") },\n'+ " ] },\n"+ "});\n"+ )+ parsed = {+ "webview/vite.config.mts": _parsed_stub(tmp_path, "webview/vite.config.mts", config_src),+ "webview/src/shims/shiki.ts": _parsed_stub(+ tmp_path, "webview/src/shims/shiki.ts", "export const codeToHtml = () => '';\n"+ ),+ "webview/src/shims/next-themes.ts": _parsed_stub(+ tmp_path, "webview/src/shims/next-themes.ts", "export const ThemeProvider = 0;\n"+ ),+ }+ g = _build_graph(+ nodes={+ "webview/src/shims/shiki.ts": _file_node([_sym("codeToHtml")]),+ },+ )+ analyzer = DeadCodeAnalyzer(g, git_meta_map={}, parsed_files=parsed)+ assert "webview/src/shims/shiki.ts" in analyzer._bundler_alias_targets+ assert "webview/src/shims/next-themes.ts" in analyzer._bundler_alias_targets++ names = _unused_export_names(analyzer)+ assert "codeToHtml" not in names++ file_report = analyzer.analyze({"detect_zombie_packages": False})+ unreachable = {+ f.file_path for f in file_report.findings if f.kind == DeadCodeKind.UNREACHABLE_FILE+ }+ assert "webview/src/shims/shiki.ts" not in unreachablediff --git a/tests/unit/ingestion/test_python_resolver_fanout.py b/tests/unit/ingestion/test_python_resolver_fanout.pynew file mode 100644index 000000000..368af13fc--- /dev/null+++ b/tests/unit/ingestion/test_python_resolver_fanout.py@@ -0,0 +1,99 @@+"""Submodule fan-out for ``from pkg import submodule`` imports (#666).++The single-target resolver maps a package import to ``pkg/__init__.py`` only,+so submodules pulled in through their package never gain inbound edges and the+dead-code analyzer flags them unreachable. ``resolve_python_import_all`` probes+every imported name as a submodule file and fans the edge out.+"""++from __future__ import annotations++import networkx as nx++from repowise.core.ingestion.models import Import+from repowise.core.ingestion.resolvers.context import ResolverContext+from repowise.core.ingestion.resolvers.python import resolve_python_import_all+++def _ctx(path_set: set[str]) -> ResolverContext:+ return ResolverContext(path_set=path_set, stem_map={}, graph=nx.DiGraph())+++def _imp(module_path: str, names: list[str], *, relative: bool = False) -> Import:+ return Import(+ raw_statement="",+ module_path=module_path,+ imported_names=names,+ is_relative=relative,+ resolved_file=None,+ )+++PATHS = {+ "app.py",+ "routers/__init__.py",+ "routers/workspace.py",+ "routers/git/__init__.py",+}+++def test_package_import_fans_out_to_submodules() -> None:+ imp = _imp("routers", ["workspace", "git", "overview"])+ targets = resolve_python_import_all(imp, "app.py", _ctx(PATHS))+ assert targets == (+ "routers/__init__.py",+ "routers/workspace.py",+ "routers/git/__init__.py",+ )+++def test_non_submodule_names_resolve_to_package_only() -> None:+ imp = _imp("routers", ["some_function"])+ targets = resolve_python_import_all(imp, "app.py", _ctx(PATHS))+ assert targets == ("routers/__init__.py",)+++def test_star_import_does_not_probe() -> None:+ imp = _imp("routers", ["*"])+ targets = resolve_python_import_all(imp, "app.py", _ctx(PATHS))+ assert targets == ("routers/__init__.py",)+++def test_direct_module_import_unchanged() -> None:+ # ``import routers.workspace`` resolves straight to the submodule; no+ # package fan-out applies because the base is not an ``__init__.py``.+ imp = _imp("routers.workspace", ["workspace"])+ targets = resolve_python_import_all(imp, "app.py", _ctx(PATHS))+ assert targets == ("routers/workspace.py",)+++def test_relative_package_import_fans_out() -> None:+ paths = {+ "pkg/__init__.py",+ "pkg/api.py",+ "pkg/sub/__init__.py",+ "pkg/sub/handlers.py",+ }+ # ``from .sub import handlers`` inside pkg/api.py+ imp = _imp(".sub", ["handlers"], relative=True)+ targets = resolve_python_import_all(imp, "pkg/api.py", _ctx(paths))+ assert targets == ("pkg/sub/__init__.py", "pkg/sub/handlers.py")+++def test_unresolvable_import_returns_empty() -> None:+ imp = _imp("nonexistent", ["thing"])+ assert resolve_python_import_all(imp, "app.py", _ctx(PATHS)) == ()+++def test_source_root_nested_package_fans_out() -> None:+ # src-layout: the module index maps the dotted path across the source+ # root, and fan-out must follow it for absolute imports.+ paths = {+ "src/myapp/__init__.py",+ "src/myapp/server.py",+ "src/myapp/routers/__init__.py",+ "src/myapp/routers/users.py",+ }+ imp = _imp("myapp.routers", ["users"])+ targets = resolve_python_import_all(imp, "src/myapp/server.py", _ctx(paths))+ assert targets == ("src/myapp/routers/__init__.py", "src/myapp/routers/users.py")diff --git a/tests/unit/ingestion/test_traverser.py b/tests/unit/ingestion/test_traverser.pyindex e5eff100b..6d8fc788d 100644--- a/tests/unit/ingestion/test_traverser.py+++ b/tests/unit/ingestion/test_traverser.py@@ -745,3 +745,39 @@ class TestEntryPointFlag:assert "server.py" in flaggedassert "pkg/helper.py" not in flaggedassert "latest_app.py" not in flagged++ def test_pyproject_console_scripts_flag_entry_modules(self, tmp_path: Path) -> None:+ (tmp_path / "pyproject.toml").write_text(+ "[project]\n"+ 'name = "demo"\n'+ "[project.scripts]\n"+ 'demo-hook = "demo.cli.hook:main"\n'+ "[project.entry-points.plugins]\n"+ 'demo-plugin = "demo.plugins:register"\n'+ )+ files = {+ "src/demo/cli/hook.py": "def main(): pass",+ "src/demo/plugins/__init__.py": "def register(): pass",+ "src/demo/cli/other.py": "x = 1",+ }+ for rel, content in files.items():+ p = tmp_path / rel+ p.parent.mkdir(parents=True, exist_ok=True)+ p.write_text(content)+ flagged = self._flagged(tmp_path)+ assert "src/demo/cli/hook.py" in flagged+ assert "src/demo/plugins/__init__.py" in flagged+ assert "src/demo/cli/other.py" not in flagged++ def test_single_segment_script_target_matches_exactly(self, tmp_path: Path) -> None:+ # A bare ``main`` target must not suffix-match every ``.../main.py``.+ (tmp_path / "pyproject.toml").write_text(+ '[project]\nname = "demo"\n[project.scripts]\ndemo = "cli:main"\n'+ )+ (tmp_path / "cli.py").write_text("def main(): pass")+ nested = tmp_path / "pkg" / "cli.py"+ nested.parent.mkdir(parents=True)+ nested.write_text("x = 1")+ flagged = self._flagged(tmp_path)+ assert "cli.py" in flagged+ assert "pkg/cli.py" not in flaggeddiff --git a/tests/unit/ingestion/test_ts_visibility_refinement.py b/tests/unit/ingestion/test_ts_visibility_refinement.pynew file mode 100644index 000000000..9c2124a4f--- /dev/null+++ b/tests/unit/ingestion/test_ts_visibility_refinement.py@@ -0,0 +1,109 @@+"""Non-exported TS/JS top-level symbols must not read as public exports.++``ts_visibility`` only inspects class-member accessibility modifiers, so a+plain top-level ``const helper = ...`` with no ``export`` keyword used to be+stamped ``public`` and surface as an "unused export" dead-code finding (and+inflate the file's derived export list). ``refine_ts_visibility`` demotes+those to ``private`` while keeping every genuine export form public.+"""++from __future__ import annotations++from datetime import datetime++from repowise.core.ingestion.models import FileInfo+from repowise.core.ingestion.parser import ASTParser++_PARSER = ASTParser()+++def _symbols(src: str, path: str = "src/mod.ts") -> dict[str, str]:+ language = "javascript" if path.endswith((".js", ".mjs", ".cjs")) else "typescript"+ info = FileInfo(+ path=path,+ abs_path=f"/repo/{path}",+ language=language,+ size_bytes=100,+ git_hash="",+ last_modified=datetime.now(),+ is_test=False,+ is_config=False,+ is_api_contract=False,+ is_entry_point=False,+ )+ parsed = _PARSER.parse_file(info, src.encode("utf-8"))+ return {s.name: s.visibility for s in parsed.symbols}+++def test_unexported_top_level_symbols_are_private() -> None:+ src = """+const skipRetryOn404 = (err: unknown) => false;+function helper(x: number): number { return x; }+const NOOP = () => {};+export const useRepo = () => ({ onErrorRetry: skipRetryOn404, m: NOOP, h: helper });+"""+ vis = _symbols(src)+ assert vis["skipRetryOn404"] == "private"+ assert vis["helper"] == "private"+ assert vis["NOOP"] == "private"+ assert vis["useRepo"] == "public"+++def test_inline_export_forms_stay_public() -> None:+ src = """+export function fetchData(): void {}+export const config = { a: 1 };+export default function main(): void {}+export class Client {}+"""+ vis = _symbols(src)+ assert vis["fetchData"] == "public"+ assert vis["config"] == "public"+ assert vis["main"] == "public"+ assert vis["Client"] == "public"+++def test_deferred_export_list_stays_public() -> None:+ src = """+const alpha = 1;+const beta = 2;+function gamma(): void {}+export { alpha, gamma as renamed };+"""+ vis = _symbols(src)+ assert vis["alpha"] == "public"+ assert vis["gamma"] == "public"+ assert vis["beta"] == "private"+++def test_export_default_identifier_stays_public() -> None:+ src = """+const handler = () => {};+export default handler;+"""+ assert _symbols(src)["handler"] == "public"+++def test_class_members_keep_modifier_visibility() -> None:+ src = """+export class Widget {+ render(): void {}+ private hide(): void {}+}+"""+ vis = _symbols(src)+ assert vis["render"] == "public"+ assert vis["hide"] == "private"+++def test_commonjs_file_keeps_everything_public() -> None:+ # ``module.exports`` assigns the export surface dynamically; per-name+ # tracking is unreliable, so nothing is demoted.+ src = """+const run = () => {};+const internal = () => {};+module.exports = { run };+"""+ vis = _symbols(src, path="src/mod.js")+ assert vis["run"] == "public"+ assert vis["internal"] == "public"