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: bring JS/TS indexing to C#/Rust/Go parity (#272)
Raghav Chamadiyaa36067c0fab7
diff --git a/docs/LANGUAGE_SUPPORT.md b/docs/LANGUAGE_SUPPORT.mdindex 0713af834..4dd4c5eb1 100644--- a/docs/LANGUAGE_SUPPORT.md+++ b/docs/LANGUAGE_SUPPORT.md@@ -56,6 +56,7 @@ All eight languages support:- For Go only: a package-granular workspace index (`GoPackageIndex`) built as a warmup phase — a package import resolves to every file in the package directory, and package-qualified calls (`pkg.Func`) / same-package bare calls resolve across all of a package's files; type-reference resolution emits `type_use` edges for field / parameter / return / composite-literal types (unwrapping `*T` / `[]T` / `map[K]V` / `pkg.T` / generics); package-aware dead-code reachability (a file is reachable when its package is imported or is a `package main` entry); structural interface satisfaction — concrete types are matched to the interfaces their method set satisfies (embedded interfaces expanded) and emit `method_implements` edges so interfaces reached only through implementors are not flagged dead; and Go never-flag conventions (`*_test.go`, `cmd/**/main.go`, `doc.go`, `magefile.go`, generated `*.pb.go` / `*_string.go` / `zz_generated*` / `bindata.go`) plus `init` / `TestMain` / `Test*` / `Benchmark*` / `Example*` / `Fuzz*` entry handling- For C/C++ only: visibility tracked from access specifiers (`public:` / `private:` / `protected:`), `static` file-scope storage class, and export attributes (`__declspec(dllexport)`, `__attribute__((visibility("default")))`, plus WebAssembly / emscripten / WASI markers `EMSCRIPTEN_KEEPALIVE` / `WASM_EXPORT` / `__attribute__((export_name(...)))` / `((used))` so functions exported across the JS↔WASM boundary are not flagged dead); type-reference resolution emits `type_use` edges for struct / typedef types used as field / parameter / return types across an `#include` (rescuing header structs that are never named in an import); COM / I-prefixed bases emit `implements` edges (rest are `extends`); Windows DLL entry points (`DllMain`, `DllGetClassObject`, `DllCanUnloadNow`, `DllRegisterServer`, `DllUnregisterServer`, `DllGetActivationFactory`) are never flagged as dead- For JavaScript only: esbuild/rollup bundle outputs (`*.bundle.js`), minified artifacts (`*.min.js`), LiveReload generated browser-global scripts (`livereload/gen/*`, `livereload.js`) and WASM JS glue (`*wasm_exec.js`) are never flagged as dead (build products / browser-loaded, never module-imported)+- For TypeScript / JavaScript only: a workspace-granular index (`TsWorkspaceIndex`) built as a warmup phase that surfaces every file reachable through a `package.json` `exports` map (including `"./locales/*"`-style wildcards) as an entry point so downstream npm consumers don't read as unreachable; type-reference resolution emits `type_use` edges for parameter / field / return / generic-constraint / type-alias-RHS / heritage clauses (unwrapping `Promise<T>`, `T[]`, `Pick<T,K>`, union/intersection, conditional/mapped types) so interfaces consumed only as types are not flagged dead; same-file rescue exempts symbols whose only consumer is another declaration in the same module; convention never-flag globs for `*.test.*` / `*.spec.*` / `*.stories.*` / `*.bench.*` / `__tests__/**` / `__mocks__/**` / Next.js app-router files (`page.tsx`, `layout.tsx`, `route.ts`, `middleware.ts`, `instrumentation.ts`, route segment configs) / SvelteKit `+page` / `+layout` / `+server` / Remix `entry.client` / `entry.server` / `next-env.d.ts` / `*.gen.ts` / `generated/**`; experimental sub-package rescue marks every source file in directories named `bench` / `benchmarks` / `treeshake` / `examples` / `demos` / `samples` / `playground` / `scratch` / `scripts` as a live entry (these dirs invoke their files via runtime CLI arguments no static scan can follow); npm-script entry detection — parses every `package.json` `scripts.*` command for paths (`tsx X.ts` / `bun run X.mts` / `rollup -c X.js`), quoted glob arguments (prettier / eslint scopes), and bare directory tokens; MDX `import` scan + `vitest.config` `include` glob scan as belt-and-suspenders for entry surfaces the static parser can't see; framework edges for Next.js App Router (`app/**/{page,layout,route,middleware,…}`), Hono / Fastify / Koa / Elysia router DSLs (`.get('/x', handler)`), Remix / SvelteKit / Astro filesystem-convention routes, and tRPC procedure registries (`.query(handler)` / `.mutation(handler)`); JSX-namespace types declared inside a `namespace JSX` file are exempt from `unused_export` (consumed by tsc via `jsxImportSource`, never imported as values)- For XAML only: `<ResourceDictionary Source="..."/>` and `MergedDictionaries` entries resolve across `pack://application:,,,/`, `ms-appx:///`, repo-rooted and relative URIs, emitting xaml→xaml `dynamic_uses` edges### Gooddiff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.pyindex a3aeb0948..826495484 100644--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py@@ -165,6 +165,40 @@ _ENTRY_POINT_SYMBOL_NAMES: frozenset[str] = frozenset({"TEST_CLASS_CLEANUP","BEGIN_TEST_METHOD_PROPERTIES","END_TEST_METHOD_PROPERTIES",+ # ---- Next.js (app + pages router) convention exports -------------+ # Loaded by the Next.js runtime by name; never appear as user-code+ # imports. The convention file globs already cover ``page.tsx``/+ # ``route.ts``/``layout.tsx``, so this set only catches the long+ # tail of route exports that escape file-glob protection (e.g.+ # routes placed in non-standard paths). Limited to names that are+ # distinctive enough not to risk masking dead code in unrelated+ # files; common identifiers (``load``, ``action``, ``metadata``,+ # ``config``, ``headers``, ``meta``, ``links``, ``runtime``) are+ # deliberately omitted — they get file-level protection via the+ # convention globs in :data:`_NEVER_FLAG_PATTERNS`.+ "generateStaticParams",+ "generateMetadata",+ "generateViewport",+ "generateImageMetadata",+ "generateSitemaps",+ "dynamicParams",+ "fetchCache",+ "preferredRegion",+ "maxDuration",+ "getStaticProps",+ "getStaticPaths",+ "getServerSideProps",+ "getInitialProps",+ "reportWebVitals",+ # ---- Remix route module exports (distinctive names only) ---------+ "shouldRevalidate",+ "ErrorBoundary",+ "CatchBoundary",+ "HydrateFallback",+ "clientLoader",+ "clientAction",+ # ---- SvelteKit page/layout module exports (distinctive names) ----+ "trailingSlash",})from .dynamic_markers import find_dynamic_edge_files, find_dynamic_import_filesfrom .models import DeadCodeFindingData, DeadCodeKind, DeadCodeReport@@ -190,6 +224,34 @@ _BARREL_FILENAMES: frozenset[str] = frozenset({})+def _find_jsx_namespace_files(parsed_files: dict) -> 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+ defining file lives in this set are integration points with the JSX+ transformer — referenced implicitly by every JSX expression, never+ imported by name. The scan is a cheap substring check; tree-sitter+ grammar work for a richer signal would be wasted effort.+ """+ matches: set[str] = set()+ for path, pf in parsed_files.items():+ try:+ file_info = getattr(pf, "file_info", None)+ if file_info is None:+ continue+ 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")+ # Match ``namespace JSX`` and ``declare namespace JSX`` — both+ # are JSX transformer integration points in practice.+ if "namespace JSX" in source:+ matches.add(path)+ except Exception:+ continue+ return matches++def _is_synthetic_node(node: str) -> bool:"""True for non-file graph nodes that should be skipped in 'is this dead?' passes.@@ -222,6 +284,9 @@ class DeadCodeAnalyzer:self._dynamic_import_files = find_dynamic_import_files(parsed_files or {}) | find_dynamic_edge_files(graph)+ self._jsx_namespace_files: set[str] = _find_jsx_namespace_files(+ 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@@ -556,6 +621,22 @@ class DeadCodeAnalyzer:# positives. C# auto-properties surface here as ``variable``.if sym.get("kind") in _non_importable_kinds(sym.get("language", "unknown")):continue+ # Types declared inside a ``namespace JSX`` block are+ # integration points with the JSX transformer — referenced+ # implicitly by every JSX expression, never imported by+ # name. The tree-sitter extractor doesn't carry namespace+ # parentage through to ``parent_name``, so the file-level+ # ``namespace JSX`` source-scan is the working signal we+ # have. Names like ``IntrinsicElements`` /+ # ``ElementChildrenAttribute`` carry the canonical TS+ # JSX-protocol meaning; anything else inside such a file+ # is an HTML-attribute / CSS-property shape consumed by+ # the same machinery.+ if (+ sym.get("kind") in ("interface", "type_alias")+ and str(node) in self._jsx_namespace_files+ ):+ continueif sym_name.startswith("__") and sym_name.endswith("__"):continueif sym_name in _ENTRY_POINT_SYMBOL_NAMES:@@ -617,6 +698,21 @@ class DeadCodeAnalyzer:if self._name_matches_dynamic(sym_name, dynamic_patterns):continue+ # Same-file type-position usage rescue (TS/JS): the+ # type-ref strategy stamps ``local_type_uses`` on a file+ # node with every type name referenced inside its own+ # source — parameter / field / return / heritage /+ # generic-constraint / type-alias-RHS positions. An+ # ``interface DefaultRenderer`` consumed only as a+ # ``type Renderer = ... : DefaultRenderer`` annotation in+ # the same module is genuinely live; without this rescue+ # the whole class of intra-module type protocols (Hono's+ # ``Get``/``Set`` generics, AWS Lambda's per-adapter+ # event-shape interfaces) reads as dead exports.+ local_type_uses = node_data.get("local_type_uses")+ if local_type_uses and sym_name in local_type_uses:+ continue+is_deprecated = any(sym_name.endswith(suffix) for suffix in ("_DEPRECATED", "_LEGACY", "_COMPAT"))diff --git a/packages/core/src/repowise/core/analysis/dead_code/constants.py b/packages/core/src/repowise/core/analysis/dead_code/constants.pyindex b7b9986ea..8d84fe0bc 100644--- a/packages/core/src/repowise/core/analysis/dead_code/constants.py+++ b/packages/core/src/repowise/core/analysis/dead_code/constants.py@@ -282,6 +282,105 @@ _NEVER_FLAG_PATTERNS: tuple[str, ...] = ("*/third_party/**/*.h","third_party/**/*.c","third_party/**/*.h",+ # ---- JavaScript / TypeScript conventions -----------------------------+ # ``fnmatch`` treats ``*`` as "match anything including ``/``", so a+ # leading ``*`` is enough to span both repo-root and nested paths.+ # Test files — discovered by the runner via filename glob (vitest,+ # jest, mocha, playwright, cypress), never imported by sibling source.+ "*.test.ts",+ "*.test.tsx",+ "*.test.js",+ "*.test.jsx",+ "*.test.mjs",+ "*.test.cjs",+ "*.spec.ts",+ "*.spec.tsx",+ "*.spec.js",+ "*.spec.jsx",+ "*.spec.mjs",+ "*/__tests__/*",+ "*/__mocks__/*",+ # Storybook stories — loaded by Storybook indexer via glob.+ "*.stories.ts",+ "*.stories.tsx",+ "*.stories.js",+ "*.stories.jsx",+ "*.stories.mdx",+ # Benchmarks — invoked by vitest/tinybench/bench scripts, not imported.+ "*.bench.ts",+ "*.bench.tsx",+ "*.bench.js",+ "*.bench.mjs",+ # Vitest / Playwright / Cypress config and workspace files.+ "*vitest.workspace.*",+ "*vitest.shims.*",+ "*vitest.root.*",+ "*playwright.config.*",+ "*cypress.config.*",+ "*rollup.config.*",+ "*esbuild.config.*",+ "*tsup.config.*",+ "*.config.mts",+ "*.config.cts",+ # Codegen / generated artifacts.+ "*.gen.ts",+ "*.gen.tsx",+ "*_generated.ts",+ "*_generated.tsx",+ "*.codegen.ts",+ "*/generated/*.ts",+ "*/generated/*.tsx",+ "*/generated/*.js",+ "*/__generated__/*",+ # Next.js app router convention files beyond page/layout/route already+ # covered above — loaded by the framework, no static importer. The+ # ``*/foo.ts`` form ensures the literal basename is required (so+ # ``mymiddleware.ts`` isn't accidentally exempt).+ "*/instrumentation.ts",+ "*/instrumentation-client.ts",+ "*/middleware.ts",+ "*/middleware.js",+ "*/global-error.tsx",+ "*/global-error.ts",+ "*/forbidden.tsx",+ "*/unauthorized.tsx",+ "*/sitemap.ts",+ "*/sitemap.tsx",+ "*/robots.ts",+ "*/robots.tsx",+ "*/manifest.ts",+ "*/manifest.tsx",+ "*/icon.tsx",+ "*/icon.ts",+ "*/apple-icon.tsx",+ "*/opengraph-image.tsx",+ "*/opengraph-image.ts",+ "*/twitter-image.tsx",+ "*/twitter-image.ts",+ # Repo-root variants (no leading directory) for monorepos where the+ # app lives at root.+ "instrumentation.ts",+ "middleware.ts",+ "sitemap.ts",+ "robots.ts",+ # Remix root/entry files — invoked by the framework runtime.+ "*/entry.client.ts",+ "*/entry.client.tsx",+ "*/entry.server.ts",+ "*/entry.server.tsx",+ "*/next-env.d.ts",+ "next-env.d.ts",+ # SvelteKit + Nuxt convention files.+ "*/+page.svelte",+ "*/+page.ts",+ "*/+page.server.ts",+ "*/+layout.svelte",+ "*/+layout.ts",+ "*/+layout.server.ts",+ "*/+server.ts",+ "*/+error.svelte",+ # ESM declaration outputs in dist trees.+ "*/dist/*.d.ts",)# Decorator patterns that indicate framework usage (route handlers, fixtures, etc.)@@ -423,6 +522,26 @@ _FIXTURE_PATH_SEGMENTS: tuple[str, ...] = ()+# JSX namespace types discovered by the TypeScript compiler via tsconfig+# ``jsxImportSource`` / the global ``namespace JSX`` declaration — never+# imported by name from user code, but referenced implicitly by every+# JSX expression. A symbol with one of these names declared inside a+# ``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",+})++def _is_fixture_path(path: str) -> bool:"""Return True if path is under a test fixture / sample data directory."""path_lower = path.lower().replace("\\", "/")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.pyindex f49e66cd7..ac1d8541b 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@@ -28,11 +28,77 @@ _DYNAMIC_IMPORT_MARKERS: dict[str, tuple[str, ...]] = {"importlib.reload","pkgutil.iter_modules",),- ".js": ("import(", "require(", "require.resolve("),- ".mjs": ("import(", "require("),- ".cjs": ("require(", "require.resolve("),- ".ts": ("import(", "require("),- ".tsx": ("import(", "require("),+ # JS/TS dynamic-dispatch markers. Each implies the surrounding file+ # (and, by the package-co-location heuristic, its siblings) reaches+ # code through a runtime mechanism the static import graph cannot+ # observe — runtime ``import()``, vitest/jest test mocking, React+ # lazy loading, Webpack ``require.context``, Vite ``import.meta.glob``,+ # Next.js server/client component boundaries.+ ".js": (+ "import(",+ "require(",+ "require.resolve(",+ "require.context(",+ "import.meta.glob(",+ "import.meta.globEager(",+ "import.meta.url",+ "import.meta.resolve(",+ "React.lazy(",+ "lazy(() =>",+ "next/dynamic",+ "jest.mock(",+ "vi.mock(",+ "vi.doMock(",+ "'use server'",+ "'use client'",+ '"use server"',+ '"use client"',+ ),+ ".mjs": (+ "import(",+ "require(",+ "import.meta.glob(",+ "import.meta.url",+ "import.meta.resolve(",+ "vi.mock(",+ ),+ ".cjs": ("require(", "require.resolve(", "require.context(", "jest.mock("),+ ".ts": (+ "import(",+ "require(",+ "require.context(",+ "import.meta.glob(",+ "import.meta.globEager(",+ "import.meta.url",+ "import.meta.resolve(",+ "React.lazy(",+ "lazy(() =>",+ "next/dynamic",+ "jest.mock(",+ "vi.mock(",+ "vi.doMock(",+ "'use server'",+ "'use client'",+ '"use server"',+ '"use client"',+ ),+ ".tsx": (+ "import(",+ "require(",+ "import.meta.glob(",+ "import.meta.globEager(",+ "import.meta.url",+ "React.lazy(",+ "lazy(() =>",+ "next/dynamic",+ "jest.mock(",+ "vi.mock(",+ "vi.doMock(",+ "'use server'",+ "'use client'",+ '"use server"',+ '"use client"',+ ),".java": ("Class.forName(", "ServiceLoader.load("),".kt": ("Class.forName(",diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py b/packages/core/src/repowise/core/ingestion/framework_edges/__init__.pyindex f3bf069ae..e0e3d6f6e 100644--- a/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py+++ b/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py@@ -24,11 +24,15 @@ from . import (fastapi,flask,go,+ hono,laravel,+ next_app,pytest_edges,rails,+ remix,rust,spring,+ trpc,typo3,)from .base import DetectionContext, FrameworkHandler, _add_edge_if_new, read_text@@ -51,6 +55,10 @@ _HANDLERS: list[FrameworkHandler] = [*laravel.HANDLERS,*spring.HANDLERS,*express.HANDLERS,+ *next_app.HANDLERS,+ *hono.HANDLERS,+ *remix.HANDLERS,+ *trpc.HANDLERS,*go.HANDLERS,*rust.HANDLERS,*typo3.HANDLERS,diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/base.py b/packages/core/src/repowise/core/ingestion/framework_edges/base.pyindex 01aebd61a..ef77f55af 100644--- a/packages/core/src/repowise/core/ingestion/framework_edges/base.py+++ b/packages/core/src/repowise/core/ingestion/framework_edges/base.py@@ -99,3 +99,30 @@ def _build_function_to_file(if sym.kind in ("function", "method"):result.setdefault(sym.name, []).append(path)return result+++def _build_ts_var_to_file(+ parsed: Any, path: str, ctx: ResolverContext, path_set: set[str]+) -> dict[str, str]:+ """Map identifiers imported into a TS/JS file → their source file path.++ The TS/JS framework handlers (Express, Hono, Fastify, …) all need to+ resolve a bare identifier (``handler``, ``router``) used in a router+ DSL back to the file that exports it, so a synthetic edge from the+ DSL call site to the handler module can be emitted. Pulling this+ builder up to ``base`` avoids three near-identical copies.+ """+ from ..resolvers import resolve_import++ var_to_file: dict[str, str] = {}+ for imp in parsed.imports:+ for name in imp.imported_names:+ resolved = resolve_import(+ imp.module_path,+ path,+ parsed.file_info.language,+ ctx,+ )+ if resolved and resolved in path_set:+ var_to_file[name] = resolved+ return var_to_filediff --git a/packages/core/src/repowise/core/ingestion/framework_edges/express.py b/packages/core/src/repowise/core/ingestion/framework_edges/express.pyindex 8b1cf61cf..daf5ee714 100644--- a/packages/core/src/repowise/core/ingestion/framework_edges/express.py+++ b/packages/core/src/repowise/core/ingestion/framework_edges/express.py@@ -8,12 +8,13 @@ from __future__ import annotationsimport refrom typing import TYPE_CHECKING, Any-from ..resolvers import ResolverContext, resolve_import+from ..resolvers import ResolverContextfrom .base import (DetectionContext,FrameworkHandler,_add_edge_if_new,_build_class_to_file,+ _build_ts_var_to_file,read_text,)@@ -55,18 +56,7 @@ def _add_express_edges(if not text:continue- # Build local var → source file map for this file- var_to_file: dict[str, str] = {}- for imp in parsed.imports:- for name in imp.imported_names:- resolved = resolve_import(- imp.module_path,- path,- parsed.file_info.language,- ctx,- )- if resolved and resolved in path_set:- var_to_file[name] = resolved+ var_to_file = _build_ts_var_to_file(parsed, path, ctx, path_set)if "express" in text or any(imp.module_path == "express" for imp in parsed.imports):for m in _EXPRESS_USE_RE.finditer(text):diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/hono.py b/packages/core/src/repowise/core/ingestion/framework_edges/hono.pynew file mode 100644index 000000000..2640bf56f--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/framework_edges/hono.py@@ -0,0 +1,96 @@+"""Hono / Fastify / Koa route framework edges.++These frameworks all share a common router DSL: an ``app`` (or ``router``)+instance has methods ``.get``/``.post``/``.put``/``.delete``/``.patch``/+``.use``/``.route`` whose final argument is a handler identifier. When+the handler is an imported identifier, the static parser sees an+``imports`` edge but no usage edge to the handler's file — making the+handler's only-from-route caller invisible. This module emits a+``framework`` edge from the router-DSL call site to the handler's file.+"""++from __future__ import annotations++import re+from typing import TYPE_CHECKING, Any++from ..resolvers import ResolverContext+from .base import (+ DetectionContext,+ FrameworkHandler,+ _add_edge_if_new,+ _build_ts_var_to_file,+ read_text,+)++if TYPE_CHECKING:+ import networkx as nx+++# Matches ``app.get('/path', handler)`` / ``router.post("/x", h)`` /+# ``app.use(middleware)`` / ``app.route('/', sub)`` where the last argument+# is a bare identifier. Multi-argument middlewares (`'/x', a, b, handler`)+# only capture the last identifier — good enough to reach the handler's+# file via the var map.+_ROUTE_METHODS = (+ "get", "post", "put", "delete", "patch", "options", "head", "all",+ "use", "route", "register", "mount", "addHook", "on",+)+_ROUTE_METHODS_ALT = "|".join(_ROUTE_METHODS)+_ROUTE_CALL_RE = re.compile(+ r"""\.\s*(?:""" + _ROUTE_METHODS_ALT + r""")\s*\(+ [^)]*?+ \b([A-Za-z_$][\w$]*)\s*+ \)""",+ re.VERBOSE,+)+_HONO_IMPORT_TOKENS = ("hono", "fastify", "@fastify/", "koa", "@koa/", "elysia")+++def _has_router_imports(parsed_files: dict[str, Any]) -> bool:+ for parsed in parsed_files.values():+ if parsed.file_info.language not in ("typescript", "javascript"):+ continue+ for imp in parsed.imports:+ mp = imp.module_path.lower()+ if any(tok in mp for tok in _HONO_IMPORT_TOKENS):+ return True+ return False+++class _RouterDslHandler:+ def detect(self, dctx: DetectionContext) -> bool:+ for tok in ("hono", "fastify", "koa", "elysia"):+ if tok in dctx.stack_lower:+ return True+ return _has_router_imports(dctx.parsed_files)++ def add_edges(+ self,+ graph: nx.DiGraph,+ parsed_files: dict[str, Any],+ ctx: ResolverContext,+ path_set: set[str],+ ) -> int:+ count = 0+ for path, parsed in parsed_files.items():+ if parsed.file_info.language not in ("typescript", "javascript"):+ continue+ text = read_text(parsed)+ if not text or not any(+ tok in text.lower()+ for tok in ("hono", "fastify", "koa", "elysia")+ ):+ continue+ var_to_file = _build_ts_var_to_file(parsed, path, ctx, path_set)+ if not var_to_file:+ continue+ for m in _ROUTE_CALL_RE.finditer(text):+ handler_name = m.group(1)+ target = var_to_file.get(handler_name)+ if target and target in path_set and _add_edge_if_new(graph, path, target):+ count += 1+ return count+++HANDLERS: list[FrameworkHandler] = [_RouterDslHandler()]diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/next_app.py b/packages/core/src/repowise/core/ingestion/framework_edges/next_app.pynew file mode 100644index 000000000..d39a63b48--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/framework_edges/next_app.py@@ -0,0 +1,89 @@+"""Next.js App Router framework edges.++In the App Router, every file matching ``app/**/{page,layout,route,+middleware,template,default,error,loading,not-found,global-error}.+{ts,tsx,js,jsx}`` is loaded by the Next.js runtime via filesystem+convention — never imported by any other source file. Phase 1's+``_NEVER_FLAG_PATTERNS`` already exempts those files from+``unreachable_file`` flagging, but they're still invisible to the+import graph, so any module they consume (helpers, layout configs,+component libraries) reads as unreachable.++This module emits ``framework`` edges from every recognised App-Router+file to whatever it imports inside the repo, so the consumed modules+inherit reachability through the router files (which themselves are+exempt). The router files act as roots of an implicit framework+subgraph the static parser can't see on its own.+"""++from __future__ import annotations++import re+from typing import TYPE_CHECKING, Any++from ..resolvers import ResolverContext+from .base import (+ DetectionContext,+ FrameworkHandler,+ _add_edge_if_new,+ _build_ts_var_to_file,+)++if TYPE_CHECKING:+ import networkx as nx+++_APP_ROUTER_BASENAMES: frozenset[str] = frozenset({+ "page", "layout", "route", "middleware", "template", "default",+ "error", "loading", "not-found", "global-error", "forbidden",+ "unauthorized", "instrumentation",+})+_APP_ROUTER_EXTS: tuple[str, ...] = (".ts", ".tsx", ".js", ".jsx", ".mjs")+_APP_DIR_RE = re.compile(r"(?:^|/)app/")+++def _is_app_router_file(path: str) -> bool:+ if not _APP_DIR_RE.search(path):+ return False+ for ext in _APP_ROUTER_EXTS:+ if path.endswith(ext):+ stem = path.rsplit("/", 1)[-1][: -len(ext)]+ if stem in _APP_ROUTER_BASENAMES:+ return True+ return False+++class _NextAppRouterHandler:+ def detect(self, dctx: DetectionContext) -> bool:+ if any("next" in tok for tok in dctx.stack_lower):+ return True+ # Cheap presence check: any app-router file in the parsed set.+ for path, parsed in dctx.parsed_files.items():+ if parsed.file_info.language not in ("typescript", "javascript"):+ continue+ if _is_app_router_file(path):+ return True+ return False++ def add_edges(+ self,+ graph: nx.DiGraph,+ parsed_files: dict[str, Any],+ ctx: ResolverContext,+ path_set: set[str],+ ) -> int:+ count = 0+ for path, parsed in parsed_files.items():+ if parsed.file_info.language not in ("typescript", "javascript"):+ continue+ if not _is_app_router_file(path):+ continue+ # Edge from the router file to every intra-repo module it+ # imports — those modules now reach a never-flagged file.+ for target in _build_ts_var_to_file(parsed, path, ctx, path_set).values():+ if target in path_set and _add_edge_if_new(graph, path, target):+ count += 1+ return count+++HANDLERS: list[FrameworkHandler] = [_NextAppRouterHandler()]diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/remix.py b/packages/core/src/repowise/core/ingestion/framework_edges/remix.pynew file mode 100644index 000000000..9506bb316--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/framework_edges/remix.py@@ -0,0 +1,76 @@+"""Remix / SvelteKit / Astro loader/action filesystem-convention edges.++These frameworks load files by filesystem convention — Remix's+``routes/*.tsx`` with ``loader``/``action`` exports, SvelteKit's+``+page.ts``/``+server.ts``, Astro's ``src/pages/*``. Phase 1's+``_NEVER_FLAG_PATTERNS`` already exempts the convention files+themselves; this module emits edges from each convention file to its+intra-repo imports so consumed helpers (``~/utils/db``,+``$lib/server/auth``) inherit reachability.+"""++from __future__ import annotations++import re+from typing import TYPE_CHECKING, Any++from ..resolvers import ResolverContext+from .base import (+ DetectionContext,+ FrameworkHandler,+ _add_edge_if_new,+ _build_ts_var_to_file,+)++if TYPE_CHECKING:+ import networkx as nx+++_REMIX_ROUTE_RE = re.compile(r"(?:^|/)(?:app/)?routes/")+_SVELTE_ROUTE_RE = re.compile(r"/\+(?:page|layout|server|error)\.(ts|tsx|js|mjs)$")+_ASTRO_PAGE_RE = re.compile(r"(?:^|/)src/pages/")+++def _is_convention_route(path: str) -> bool:+ if _SVELTE_ROUTE_RE.search(path):+ return True+ if _REMIX_ROUTE_RE.search(path) and any(+ path.endswith(ext) for ext in (".ts", ".tsx", ".js", ".jsx")+ ):+ return True+ if _ASTRO_PAGE_RE.search(path):+ return True+ return False+++class _ConventionRouteHandler:+ def detect(self, dctx: DetectionContext) -> bool:+ if any(tok in dctx.stack_lower for tok in ("remix", "sveltekit", "astro")):+ return True+ for path, parsed in dctx.parsed_files.items():+ if parsed.file_info.language not in ("typescript", "javascript"):+ continue+ if _is_convention_route(path):+ return True+ return False++ def add_edges(+ self,+ graph: nx.DiGraph,+ parsed_files: dict[str, Any],+ ctx: ResolverContext,+ path_set: set[str],+ ) -> int:+ count = 0+ for path, parsed in parsed_files.items():+ if parsed.file_info.language not in ("typescript", "javascript"):+ continue+ if not _is_convention_route(path):+ continue+ for target in _build_ts_var_to_file(parsed, path, ctx, path_set).values():+ if target in path_set and _add_edge_if_new(graph, path, target):+ count += 1+ return count+++HANDLERS: list[FrameworkHandler] = [_ConventionRouteHandler()]diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/trpc.py b/packages/core/src/repowise/core/ingestion/framework_edges/trpc.pynew file mode 100644index 000000000..a3779cee0--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/framework_edges/trpc.py@@ -0,0 +1,81 @@+"""tRPC procedure-registry framework edges.++A typical tRPC router declares procedures via a name-keyed object+literal: ``router({ getUser: publicProcedure.query(getUserHandler), …+})``. The handler is bound by identifier; tRPC consumers reach it+through the client-side procedure name, so no static caller appears in+the import graph. This module emits framework edges from the router+declaration site to each handler's file.+"""++from __future__ import annotations++import re+from typing import TYPE_CHECKING, Any++from ..resolvers import ResolverContext+from .base import (+ DetectionContext,+ FrameworkHandler,+ _add_edge_if_new,+ _build_ts_var_to_file,+ read_text,+)++if TYPE_CHECKING:+ import networkx as nx+++# Matches ``<chain>.query(handler)`` / ``.mutation(handler)`` /+# ``.subscription(handler)`` where the argument is a bare identifier.+_TRPC_PROC_RE = re.compile(+ r"""\.\s*(?:query|mutation|subscription)\s*\(\s*+ ([A-Za-z_$][\w$]*)+ \s*\)""",+ re.VERBOSE,+)+++def _has_trpc_imports(parsed_files: dict[str, Any]) -> bool:+ for parsed in parsed_files.values():+ if parsed.file_info.language not in ("typescript", "javascript"):+ continue+ for imp in parsed.imports:+ if "@trpc/" in imp.module_path or imp.module_path == "trpc":+ return True+ return False+++class _TrpcHandler:+ def detect(self, dctx: DetectionContext) -> bool:+ if "trpc" in dctx.stack_lower:+ return True+ return _has_trpc_imports(dctx.parsed_files)++ def add_edges(+ self,+ graph: nx.DiGraph,+ parsed_files: dict[str, Any],+ ctx: ResolverContext,+ path_set: set[str],+ ) -> int:+ count = 0+ for path, parsed in parsed_files.items():+ if parsed.file_info.language not in ("typescript", "javascript"):+ continue+ text = read_text(parsed)+ if not text or "@trpc/" not in text and "publicProcedure" not in text \+ and "protectedProcedure" not in text:+ continue+ var_to_file = _build_ts_var_to_file(parsed, path, ctx, path_set)+ if not var_to_file:+ continue+ for m in _TRPC_PROC_RE.finditer(text):+ handler_name = m.group(1)+ target = var_to_file.get(handler_name)+ if target and target in path_set and _add_edge_if_new(graph, path, target):+ count += 1+ return count+++HANDLERS: list[FrameworkHandler] = [_TrpcHandler()]diff --git a/packages/core/src/repowise/core/ingestion/graph_warmups.py b/packages/core/src/repowise/core/ingestion/graph_warmups.pyindex d4bb03cf3..776bebb7e 100644--- a/packages/core/src/repowise/core/ingestion/graph_warmups.py+++ b/packages/core/src/repowise/core/ingestion/graph_warmups.py@@ -46,11 +46,62 @@ def _warmup_go(ctx: "ResolverContext") -> None:get_or_build_go_index(ctx)+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+ (downstream npm consumers) read as ``in_degree==0`` and ship as+ unreachable findings.+ """+ from .resolvers.ts_workspace import (+ find_mdx_import_targets,+ find_npm_script_entry_targets,+ find_vitest_include_targets,+ get_or_build_ts_index,+ )++ index = get_or_build_ts_index(ctx)+ graph = getattr(ctx, "graph", None)+ if graph is None:+ return+ entry_paths: set[str] = set(index.exports_entry_paths)+ # MDX-only consumers (docs sites that import TSX components into+ # ``.mdx``) and custom vitest layouts (``runtime-tests/**``) — both+ # invisible to the TS parser, both real entry points.+ try:+ entry_paths |= find_mdx_import_targets(ctx)+ except Exception:+ pass+ try:+ entry_paths |= find_vitest_include_targets(ctx)+ except Exception:+ pass+ # ``package.json`` ``scripts.*`` references: benchmark / bench-runner /+ # rollup-input paths that ship as live code but are never imported+ # by the main entry graph.+ try:+ entry_paths |= find_npm_script_entry_targets(ctx)+ except Exception:+ pass+ for path in entry_paths:+ node = graph.nodes.get(path)+ if node is None:+ continue+ node["is_entry_point"] = True++# Map language tag → (phase-event name, warmup function). The phase# name shows up in the CLI progress bar and in ``state.json`` timings.+#+# Note: ``typescript`` and ``javascript`` share a single warmup — the+# workspace index is derived from ``package.json`` files and is the+# same for both languages. The dispatcher registers under each tag so+# a JS-only repo still triggers the index build._WARMUPS: dict[str, tuple[str, Warmup]] = {"csharp": ("graph.dotnet_index", _warmup_dotnet),"go": ("graph.go_index", _warmup_go),+ "typescript": ("graph.ts_index", _warmup_typescript),+ "javascript": ("graph.ts_index", _warmup_typescript),}@@ -66,9 +117,20 @@ def run_warmups(than dropping it into ``graph.imports``."""present_langs: set[str] = {pf.file_info.language for pf in parsed_files.values()}+ fired_phases: set[str] = set()for lang, (phase_name, warmup) in _WARMUPS.items():if lang not in present_langs:continue+ # Some warmups (TS + JS) share a phase event because they share the+ # underlying index — only fire start/done once per phase name and+ # rely on the warmup's own idempotency for the second invocation.+ if phase_name in fired_phases:+ try:+ warmup(ctx)+ except Exception:+ pass+ continue+ fired_phases.add(phase_name)if progress is not None:progress.on_phase_start(phase_name, None)try:diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.pyindex 47e53be40..0caaf9a5f 100644--- a/packages/core/src/repowise/core/ingestion/models.py+++ b/packages/core/src/repowise/core/ingestion/models.py@@ -262,6 +262,8 @@ class TypeReference:origin: Literal["ctor_param", "method_param", "delegate_param", # C#"param_type", "field_type", "composite_literal", # Go+ "return_type", "type_alias", "generic_constraint", # TS/JS+ "extends", "implements", # TS heritage clauses (file-level type_use)] = "ctor_param"diff --git a/packages/core/src/repowise/core/ingestion/parser_helpers.py b/packages/core/src/repowise/core/ingestion/parser_helpers.pyindex b5561b83f..7210ac188 100644--- a/packages/core/src/repowise/core/ingestion/parser_helpers.py+++ b/packages/core/src/repowise/core/ingestion/parser_helpers.py@@ -179,6 +179,23 @@ _PARAM_ORIGIN_BY_ANCESTOR: dict[str, str] = {"field_declaration": "field_type","parameter_declaration": "param_type","composite_literal": "composite_literal",+ # TypeScript / JavaScript type positions. Walk-up matches the nearest+ # enclosing declaration; the parameter / field / heritage nodes sit+ # closer than ``class_declaration`` so this dispatch is unambiguous.+ "required_parameter": "param_type",+ "optional_parameter": "param_type",+ "property_signature": "field_type",+ "public_field_definition": "field_type",+ "function_declaration": "return_type",+ "method_definition": "return_type",+ "method_signature": "return_type",+ "arrow_function": "return_type",+ "function_signature": "return_type",+ "type_alias_declaration": "type_alias",+ "type_parameter": "generic_constraint",+ "extends_clause": "extends",+ "extends_type_clause": "extends",+ "implements_clause": "implements",}@@ -457,6 +474,158 @@ def _c_head_type_identifier(type_node: Node, src: str) -> str | None:return text+# ---------------------------------------------------------------------------+# TypeScript / JavaScript type-reference head extraction+# ---------------------------------------------------------------------------++# Predeclared / lib.dom / lib.es type names that never resolve to a user-+# defined symbol in the workspace. Filtering them before the resolver+# lookup avoids polluting the graph with edges for ubiquitous globals+# (``string``, ``Promise``, ``Pick``) the dead-code analyzer does not+# care about. The list intentionally errs on the side of inclusion: a+# user type colliding with one of these names will fail to resolve via+# the type-ref path, but cross-file usage still surfaces through the+# value-import + call path.+_TS_BUILTIN_TYPES: frozenset[str] = frozenset(+ {+ # Primitives + structural+ "string", "number", "boolean", "bigint", "symbol",+ "void", "null", "undefined", "never", "unknown", "any",+ "object", "this", "Object",+ # Built-in containers / wrappers. ``Map`` / ``Set`` / ``WeakMap``+ # / ``WeakSet`` are intentionally **not** listed: they're routinely+ # shadowed by user-defined types (Hono ``interface Set<E>`` /+ # ``interface Get<E>`` is the canonical case) and filtering them+ # at extraction time hides the same-file rescue.+ "Array", "ReadonlyArray", "Promise", "Awaited", "WeakRef",+ "Date", "RegExp", "Error", "TypeError", "RangeError",+ "SyntaxError", "ReferenceError", "EvalError",+ "Function", "CallableFunction", "NewableFunction",+ "ArrayBuffer", "SharedArrayBuffer", "DataView",+ "Int8Array", "Uint8Array", "Uint8ClampedArray",+ "Int16Array", "Uint16Array", "Int32Array", "Uint32Array",+ "Float32Array", "Float64Array", "BigInt64Array", "BigUint64Array",+ "Iterable", "AsyncIterable", "Iterator", "AsyncIterator",+ "IterableIterator", "AsyncIterableIterator",+ "Generator", "AsyncGenerator", "GeneratorFunction",+ "Proxy", "Reflect", "JSON", "Math",+ # Utility types+ "Record", "Partial", "Required", "Readonly",+ "Pick", "Omit", "Exclude", "Extract", "NonNullable",+ "Parameters", "ConstructorParameters", "ReturnType",+ "InstanceType", "ThisType", "ThisParameterType", "OmitThisParameter",+ "Uppercase", "Lowercase", "Capitalize", "Uncapitalize",+ # Common DOM / Node globals that show up everywhere as parameter+ # types — listing here is a perf optimisation, not correctness.+ "URL", "URLSearchParams", "Request", "Response", "Headers",+ "Blob", "File", "FormData", "FileReader",+ "AbortController", "AbortSignal", "AbortError",+ "EventTarget", "Event", "CustomEvent", "MessageEvent",+ "Element", "HTMLElement", "Node", "Document", "Window",+ "Buffer", "NodeJS",+ }+)+++def _ts_head_type_identifier(type_node: Node, src: str) -> str | None:+ """Return the head identifier of a TypeScript/JavaScript type, or None.++ Unwraps the modifier shells TS layers around a named type so the+ resolver sees the bare identifier:++ ``Foo`` → "Foo"+ ``Foo[]`` → "Foo" (array_type)+ ``Promise<Foo>`` → "Promise" → filtered (builtin)+ ``ns.Foo`` → "Foo" (nested_type_identifier)+ ``Foo | null`` → None (union — ambiguous head)+ ``(x: A) => B`` → None (function_type — A/B are+ captured separately as their+ own param/return positions)+ ``{ x: number }`` → None (anonymous object type)+ ``string`` / ``number`` → None (predefined / builtin)+ ``T`` → None (single-uppercase generic)++ Union / intersection / function / object types return None because+ the head isn't a single name; the underlying parameter / field+ captures for each leaf already produced their own ``@param.type``+ captures so the bare leaves are still resolved.+ """+ node: Node | None = type_node+ text = ""+ for _ in range(8):+ if node is None:+ return None+ kind = node.type+ if kind == "type_identifier":+ text = _node_text(node, src)+ break+ if kind == "identifier":+ # ``extends_clause`` of a class uses ``identifier`` (E in+ # ``class D extends E``); treat it as a type name.+ text = _node_text(node, src)+ break+ if kind == "predefined_type":+ return None+ if kind in ("union_type", "intersection_type", "function_type",+ "constructor_type", "object_type", "literal_type",+ "tuple_type", "conditional_type", "mapped_type",+ "index_type_query", "type_query", "lookup_type",+ "template_literal_type", "infer_type", "readonly_type"):+ return None+ if kind == "generic_type":+ # ``Foo<T>`` — descend to the bare name; generic args are+ # captured separately if they hold user types.+ inner = node.child_by_field_name("name") or next(+ (c for c in node.named_children if c.type != "type_arguments"),+ None,+ )+ node = inner+ continue+ if kind == "nested_type_identifier":+ # ``ns.Foo`` — rightmost name component is the type itself.+ name = node.child_by_field_name("name") or next(+ (c for c in reversed(node.named_children)+ if c.type == "type_identifier"),+ None,+ )+ node = name+ continue+ if kind == "array_type":+ # ``T[]`` — element is the first named child.+ node = next(iter(node.named_children), None)+ continue+ if kind == "parenthesized_type":+ node = next(iter(node.named_children), None)+ continue+ if kind == "type_annotation":+ # Shouldn't be reached given the query strips the annotation,+ # but defensive: descend past the colon to the type itself.+ node = next(iter(node.named_children), None)+ continue+ if kind == "constraint":+ # ``extends Cons`` inside a type_parameter — the constraint+ # node wraps the actual constraint type.+ node = next(iter(node.named_children), None)+ continue+ # Anything else (type_predicate, asserts, type_assertion, ...)+ # — descend into the first named child and re-classify.+ node = next(iter(node.named_children), None)+ else:+ return None++ # JS/TS identifiers may start with `$` or `_` in addition to a+ # letter — Zod's ``$ZSF`` interface family is the canonical case.+ if not text or (not text[0].isalpha() and text[0] not in ("_", "$")):+ return None+ if text in _TS_BUILTIN_TYPES:+ return None+ # Single-uppercase-letter heads are overwhelmingly generic type params+ # (T, K, V, U). Skipping them avoids spurious lookups.+ if len(text) == 1 and text.isupper():+ return None+ return text++# Per-language head-identifier extractor for ``@param.type`` captures.# Defaults to the C#-shaped extractor; languages with a differently-shaped# type grammar register their own here.@@ -464,6 +633,8 @@ TYPE_HEAD_EXTRACTORS: dict[str, "Callable[[Node, str], str | None]"] = {"go": _go_head_type_identifier,"c": _c_head_type_identifier,"cpp": _c_head_type_identifier,+ "typescript": _ts_head_type_identifier,+ "javascript": _ts_head_type_identifier,}diff --git a/packages/core/src/repowise/core/ingestion/queries/typescript.scm b/packages/core/src/repowise/core/ingestion/queries/typescript.scmindex 6c8695b15..093a55403 100644--- a/packages/core/src/repowise/core/ingestion/queries/typescript.scm+++ b/packages/core/src/repowise/core/ingestion/queries/typescript.scm@@ -122,3 +122,70 @@constructor: (identifier) @call.targetarguments: (arguments) @call.arguments) @call.site++; ---------------------------------------------------------------------------+; Type references (non-import positions)+;+; Mirrors the C# / Go pattern: a single ``@param.type`` capture name fans+; in every position where a user-defined type appears outside an import+; statement. The TypeScript head extractor in parser_helpers.py unwraps+; ``Foo[]`` / ``Promise<Foo>`` / ``ns.Foo`` / ``Foo | Bar`` shells and+; filters TS builtins (``string`` / ``number`` / ``Promise`` / ...). The+; result lets the dead-code analyzer see an ``interface Foo`` referenced+; as ``bar: Foo`` in another file even when no value-import binds ``Foo``.+; ---------------------------------------------------------------------------++; Function / method parameter types: (x: Qux) / (y?: Quux)+(required_parameter+ type: (type_annotation (_) @param.type))+(optional_parameter+ type: (type_annotation (_) @param.type))++; Interface field types: { bar: Baz }+(property_signature+ type: (type_annotation (_) @param.type))++; Class field types: class C { f: Field }+(public_field_definition+ type: (type_annotation (_) @param.type))++; Return types on function / method / arrow / call-signature declarations+(function_declaration+ return_type: (type_annotation (_) @param.type))+(method_definition+ return_type: (type_annotation (_) @param.type))+(method_signature+ return_type: (type_annotation (_) @param.type))+(arrow_function+ return_type: (type_annotation (_) @param.type))+(function_signature+ return_type: (type_annotation (_) @param.type))++; Generic-parameter constraints: <T extends Constraint>+(type_parameter+ (constraint (_) @param.type))++; Type alias RHS: type Alias = OtherType+(type_alias_declaration+ value: (_) @param.type)++; Class heritage — file-level type_use edges complement the symbol-level+; ``extends`` / ``implements`` edges the heritage extractor emits, so a+; concrete class importing an interface only to implement it counts as a+; consumer of the interface's file for unused-export purposes.+(extends_clause+ value: (_) @param.type)+(implements_clause+ (_) @param.type)+; Interface extends: interface A extends B+(extends_type_clause+ (_) @param.type)++; Compound type expressions — descend so the leaf type names inside+; ``A | B``, ``A & B`` and conditional types (``X extends Y ? A : B``)+; are reachable. Without these patterns ``type R = X | DefaultRenderer``+; would never surface ``DefaultRenderer`` as a type reference because+; the head extractor refuses to pick a single name out of a union.+(union_type (_) @param.type)+(intersection_type (_) @param.type)+(conditional_type (_) @param.type)diff --git a/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace.py b/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace.pyindex e8d159bd4..3ec38bad9 100644--- a/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace.py+++ b/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace.py@@ -25,6 +25,7 @@ flattened to the first plausible source target. Packages without anfrom __future__ import annotationsimport json+from dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any@@ -305,3 +306,458 @@ def resolve_via_workspaces(module_path: str, ctx: "ResolverContext") -> str | Noif cand is not None:return candreturn None+++# ---------------------------------------------------------------------------+# TsWorkspaceIndex — aggregated workspace view consumed by the dead-code+# analyzer (exports-wildcard entry points), the resolver, and any future+# pass that needs to know "what does the workspace publish?".+# ---------------------------------------------------------------------------+++@dataclass+class TsWorkspaceIndex:+ """Aggregated TypeScript/JavaScript workspace metadata.++ ``packages`` mirrors :func:`build_workspace_info` — kept here so a+ single object carries every workspace fact the rest of the pipeline+ needs. ``exports_entry_paths`` is the set of repo-relative source+ files that any workspace package's ``package.json`` ``exports`` map+ resolves to (including wildcards expanded against ``ctx.path_set``).+ These files are *the* public surface of the monorepo — flagging them+ as unreachable just because nothing inside the repo imports them is+ a false positive, since downstream consumers reach them via the+ package boundary the analyzer can't observe.+ """++ packages: dict[str, dict[str, Any]] = field(default_factory=dict)+ exports_entry_paths: set[str] = field(default_factory=set)+++def _expand_exports_wildcard(+ target: str, exports_pattern: str, pkg_dir: str, path_set: set[str]+) -> set[str]:+ """Return every concrete source file matching a wildcard exports target.++ ``exports_pattern`` is the key like ``"./locales/*"``; ``target`` is+ the right-hand side like ``"./src/locales/*.ts"``. The function+ interprets ``*`` as ``[^/]*`` (single path segment, Node spec) and+ enumerates ``path_set`` entries under ``pkg_dir`` that match the+ expanded prefix/suffix.+ """+ if "*" not in target:+ # Non-wildcard target — just probe the concrete path.+ stripped = target.lstrip("./")+ resolved = _probe_path(f"{pkg_dir}/{stripped}", path_set)+ return {resolved} if resolved is not None else set()+ # Decompose ``./src/locales/*.ts`` into prefix=``src/locales/`` and+ # suffix=``.ts``. The Node spec only allows one ``*`` per pattern.+ stripped = target.lstrip("./")+ prefix, _, suffix = stripped.partition("*")+ base_prefix = f"{pkg_dir}/{prefix}"+ matches: set[str] = set()+ for candidate in path_set:+ if not candidate.startswith(base_prefix):+ continue+ if suffix and not candidate.endswith(suffix):+ continue+ # Reject paths whose captured segment crosses a directory boundary+ # unless the pattern itself spans dirs (``**`` is not part of the+ # spec; ``*`` matches a single segment).+ captured = candidate[len(base_prefix) : len(candidate) - len(suffix) if suffix else len(candidate)]+ if "/" in captured and exports_pattern.endswith("/*"):+ continue+ matches.add(candidate)+ return matches+++def build_ts_workspace_index(ctx: "ResolverContext") -> TsWorkspaceIndex:+ """Build the workspace index for *ctx*.++ Idempotent — safe to call multiple times. Reads the workspace+ metadata via :func:`build_workspace_info` and resolves every+ ``exports`` target (concrete and wildcard) against ``ctx.path_set``+ so a file's reachability through the package boundary is observable+ to downstream passes.+ """+ packages = get_or_build_workspace_info(ctx)+ entries: set[str] = set()+ path_set = ctx.path_set+ for _name, pkg in packages.items():+ dir_posix: str = pkg["dir"]+ exports_map: dict[str, str] = pkg.get("exports") or {}+ for pattern, target in exports_map.items():+ entries.update(_expand_exports_wildcard(target, pattern, dir_posix, path_set))+ # ``main``/``module`` shorthand — package's primary entry.+ main = pkg.get("main")+ if isinstance(main, str):+ resolved = _probe_path(f"{dir_posix}/{main.lstrip('./')}", path_set)+ if resolved is not None:+ entries.add(resolved)+ return TsWorkspaceIndex(packages=packages, exports_entry_paths=entries)+++def get_or_build_ts_index(ctx: "ResolverContext") -> TsWorkspaceIndex:+ """Memoized accessor — builds the index once per resolver context."""+ cached = getattr(ctx, "_ts_workspace_index", None)+ if cached is not None:+ return cached+ index = build_ts_workspace_index(ctx)+ ctx._ts_workspace_index = index # type: ignore[attr-defined]+ return index+++# ---------------------------------------------------------------------------+# MDX import scan + vitest config scan — entry-point sources the static+# graph never observes through the TS/JS parser path.+# ---------------------------------------------------------------------------++import re as _re++_MDX_IMPORT_RE = _re.compile(+ r"""import\s++ (?:type\s+)?+ (?:\{[^}]*\}|\*\s+as\s+\w+|\w+(?:\s*,\s*\{[^}]*\})?)+ \s+from\s+['"]([^'"]+)['"]""",+ _re.VERBOSE,+)++_VITEST_INCLUDE_RE = _re.compile(+ r"""include\s*:\s*\[\s*((?:['"][^'"]+['"]\s*,?\s*)+)\]""",+ _re.MULTILINE,+)+_VITEST_STRING_RE = _re.compile(r"""['"]([^'"]+)['"]""")+++def find_mdx_import_targets(ctx: "ResolverContext") -> set[str]:+ """Return repo-relative paths reached only via ``import`` in MDX/MD files.++ React-component libraries published as documentation (``.mdx`` files+ that embed live TSX components) hide their consumers from the static+ TS parser because nothing in this repo parses MDX. The regex below+ is intentionally narrow: ``import … from '...'``. Anything fancier+ (JSX-in-MDX components, MDX-specific shorthand) falls out and gets+ treated as no-edge — better than a parser dependency.+ """+ if ctx.repo_path is None:+ return set()+ from .typescript import resolve_ts_js_import++ targets: set[str] = set()+ for mdx in ctx.repo_path.rglob("*.mdx"):+ try:+ text = mdx.read_text(encoding="utf-8", errors="ignore")+ except Exception:+ continue+ try:+ rel = mdx.relative_to(ctx.repo_path).as_posix()+ except ValueError:+ continue+ for match in _MDX_IMPORT_RE.finditer(text):+ spec = match.group(1)+ # Pre-normalise relative specifiers so ``../foo`` resolves+ # against ``ctx.path_set`` — the underlying TS resolver+ # leaves ``..`` segments unflattened and relies on the+ # parser layer to do this, which doesn't run for MDX.+ if spec.startswith("."):+ import os as _os+ joined = _os.path.normpath(_os.path.join(_os.path.dirname(rel), spec))+ joined = joined.replace("\\", "/")+ # Re-express as a relative spec rooted at the repo so+ # ``resolve_ts_js_import`` treats it as relative.+ spec_for_resolve = "./" + joined+ resolved = resolve_ts_js_import(spec_for_resolve, "_root_.mdx", ctx)+ else:+ resolved = resolve_ts_js_import(spec, rel, ctx)+ if resolved is None:+ continue+ if resolved.startswith("external:"):+ continue+ targets.add(resolved)+ return targets+++def _vitest_glob_to_regex(glob: str) -> _re.Pattern[str]:+ """Translate a vitest/minimatch glob into a regex matching repo paths.++ ``**`` matches zero-or-more path segments (including empty); a single+ ``*`` matches one path segment (no ``/``); ``?`` matches a single+ non-``/`` char. Anything else is escaped. Python's ``fnmatch`` treats+ ``*`` as "any chars including ``/``", which collapses ``foo/**/x``+ into a too-strict regex that misses ``foo/x`` — hence this+ bespoke translator.+ """+ out: list[str] = ["^"]+ i = 0+ while i < len(glob):+ c = glob[i]+ if c == "*":+ if i + 1 < len(glob) and glob[i + 1] == "*":+ # ``**`` — zero or more path segments. Consume optional+ # trailing ``/`` so ``foo/**/bar`` matches ``foo/bar``.+ i += 2+ if i < len(glob) and glob[i] == "/":+ out.append("(?:.*/)?")+ i += 1+ else:+ out.append(".*")+ else:+ out.append("[^/]*")+ i += 1+ elif c == "?":+ out.append("[^/]")+ i += 1+ elif c in ".+()|^$[]{}\\":+ out.append("\\" + c)+ i += 1+ else:+ out.append(c)+ i += 1+ out.append("$")+ return _re.compile("".join(out))+++def find_vitest_include_targets(ctx: "ResolverContext") -> set[str]:+ """Return repo-relative source files matching vitest ``include`` globs.++ Belt-and-suspenders alongside the ``*.test.*`` never-flag pattern —+ catches custom test layouts like ``runtime-tests/**`` that escape+ the filename convention.+ """+ if ctx.repo_path is None:+ return set()++ targets: set[str] = set()+ config_globs = ("vitest.config.ts", "vitest.config.js", "vitest.config.mts",+ "vitest.config.mjs", "vitest.config.cjs", "vitest.config.cts",+ "vite.config.ts", "vite.config.js", "vite.config.mts",+ "vite.config.mjs")+ seen: set[Path] = set()+ for pattern in config_globs:+ for cfg in ctx.repo_path.rglob(pattern):+ if cfg in seen:+ continue+ seen.add(cfg)+ try:+ text = cfg.read_text(encoding="utf-8", errors="ignore")+ except Exception:+ continue+ cfg_dir = cfg.parent+ for inc_match in _VITEST_INCLUDE_RE.finditer(text):+ for str_match in _VITEST_STRING_RE.finditer(inc_match.group(1)):+ glob_pat = str_match.group(1)+ # Resolve glob relative to the config file's directory.+ base = (cfg_dir / glob_pat).as_posix()+ try:+ rel_glob = Path(base).relative_to(ctx.repo_path).as_posix()+ except ValueError:+ continue+ regex = _vitest_glob_to_regex(rel_glob)+ for candidate in ctx.path_set:+ if regex.match(candidate):+ targets.add(candidate)+ return targets+++# ---------------------------------------------------------------------------+# npm-script entry detection+# ---------------------------------------------------------------------------++# Source-file extensions a script might point at directly. Includes the+# ``.mts``/``.cts`` family because hono/zod benchmarks favour them.+_NPM_SCRIPT_SOURCE_EXTS: tuple[str, ...] = (+ ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts",+)++# Runner tokens that take a single source path as their first non-flag+# positional. Detection is positional rather than name-based so we don't+# have to track shell-syntax quirks (``--`` separators, env-var prefixes,+# multi-command ``&&`` chains).+_NPM_SCRIPT_RUNNERS: frozenset[str] = frozenset({+ "tsx", "ts-node", "ts-node-esm", "vite-node", "swc-node",+ "node", "deno", "bun",+ "esbuild", "rollup", "vite", "webpack",+})++# Sub-package names that conventionally hold ad-hoc / experimental+# scripts — bench harnesses, tree-shaking experiments, examples, demos.+# Their source files are typically passed as CLI arguments at runtime+# (``rollup -c --input X.ts``, ``tsx index.ts <file>``) rather than+# imported by anything in the static graph. Treating them as entry+# points matches how a human reads the repo: maintained code, not dead.+_EXPERIMENT_DIR_NAMES: frozenset[str] = frozenset({+ "bench", "benches", "benchmark", "benchmarks",+ "treeshake", "treeshaking",+ "example", "examples",+ "demo", "demos",+ "sample", "samples",+ "playground", "playgrounds",+ "scratch",+ # ``scripts/`` is conventionally ad-hoc tooling invoked via npm+ # commands or pre/post-commit hooks — never imported by application+ # code, but always maintained. Treat the whole dir as live.+ "scripts",+})+++def _iter_script_tokens(script: str) -> list[str]:+ """Split a script command on whitespace and shell separators.++ Strips quotes off individual tokens but does NOT honour shell quoting+ (``"a b"`` becomes two tokens) — matches Node's npm script semantics+ where commands are passed to ``sh -c`` and we only care about token+ *shape*, not faithful argv reconstruction.+ """+ # Replace shell chain operators with spaces so each chunk parses.+ cleaned = _re.sub(r"&&|\|\||;|\|", " ", script)+ return [tok.strip("'\"") for tok in cleaned.split() if tok.strip("'\"")]+++def find_npm_script_entry_targets(ctx: "ResolverContext") -> set[str]:+ """Return repo-relative source files referenced by ``package.json`` scripts.++ Hono's ``benchmarks/{jsx,routers,query-param}/**`` and zod's+ ``packages/{bench,treeshake,tsc}/**`` are invoked as ``tsx <path>`` /+ ``bun run <path>`` / ``rollup -c <path>`` from their package's+ ``scripts.*`` — never imported by the main entry graph, so they read+ as ``in_degree==0`` despite being live, maintained code. This scan+ surfaces those paths as entry points.++ Also picks up quoted glob arguments (prettier / eslint / format-check+ style ``"src/**/*.ts"``) so files only ever consumed by build tooling+ aren't flagged dead — they're maintained code, just not application+ code.+ """+ if ctx.repo_path is None:+ return set()++ repo_root = ctx.repo_path.resolve()+ path_set = ctx.path_set+ targets: set[str] = set()++ # Build a quick "directory → files under it" index lazily by scanning+ # ``path_set`` once. Cheap: a few thousand strings at most.+ dirs_in_repo: dict[str, list[str]] = {}+ for p in path_set:+ idx = 0+ while True:+ slash = p.find("/", idx)+ if slash == -1:+ break+ dirs_in_repo.setdefault(p[:slash], []).append(p)+ idx = slash + 1++ for pkg_file in repo_root.rglob("package.json"):+ # Skip node_modules — those are dependency manifests, not ours.+ if "node_modules" in pkg_file.parts:+ continue+ try:+ data = json.loads(pkg_file.read_text(encoding="utf-8", errors="ignore"))+ except Exception:+ continue+ scripts = data.get("scripts") or {}+ if not isinstance(scripts, dict):+ continue+ pkg_dir = pkg_file.parent+ try:+ pkg_rel = pkg_dir.relative_to(repo_root).as_posix()+ except ValueError:+ continue+ pkg_prefix = "" if pkg_rel in ("", ".") else f"{pkg_rel}/"++ # Experimental sub-package convention: ``packages/bench``,+ # ``packages/treeshake``, ``examples/`` style directories invoke+ # their source files via runtime-supplied CLI arguments+ # (``rollup --input``, ``import.meta.resolve``) that no static+ # scan can resolve. The presence of an ``experimental`` directory+ # name + a ``package.json`` is the human-meaningful "this is a+ # maintained script bag" signal — mark every source file under+ # it as an entry. Honour ``"private": true`` *or* the directory+ # name match; the conventional names are the load-bearing signal.+ pkg_dir_name = pkg_dir.name.lower()+ if pkg_dir_name in _EXPERIMENT_DIR_NAMES:+ dir_files = dirs_in_repo.get(pkg_rel) if pkg_rel else None+ if dir_files:+ for f in dir_files:+ if any(f.lower().endswith(ext) for ext in _NPM_SCRIPT_SOURCE_EXTS):+ targets.add(f)++ for command in scripts.values():+ if not isinstance(command, str):+ continue+ tokens = _iter_script_tokens(command)+ for token in tokens:+ if not token or token.startswith("-"):+ continue+ # Source file with a known extension — try resolving as a+ # path relative to the package directory. Glob meta-chars+ # are handled by the next branch.+ lower = token.lower()+ if (+ any(lower.endswith(ext) for ext in _NPM_SCRIPT_SOURCE_EXTS)+ and "*" not in token+ and "?" not in token+ ):+ candidate = (pkg_prefix + token).lstrip("./")+ candidate = _re.sub(r"\\", "/", candidate)+ # Normalise ``a/./b`` and ``a/../b`` segments.+ parts: list[str] = []+ for seg in candidate.split("/"):+ if seg in ("", "."):+ continue+ if seg == "..":+ if parts:+ parts.pop()+ continue+ parts.append(seg)+ norm = "/".join(parts)+ if norm in path_set:+ targets.add(norm)+ continue+ # Glob argument (prettier / eslint / format scope) — only+ # expand when the token has a glob meta-character and+ # contains a slash, so plain runner names like ``tsc`` and+ # plain flags don't get misinterpreted.+ if ("*" in token or "?" in token) and "/" in token:+ rel_glob = (pkg_prefix + token).lstrip("./")+ # Strip stray leading ``./`` left over from npm conv.+ if rel_glob.startswith("./"):+ rel_glob = rel_glob[2:]+ try:+ regex = _vitest_glob_to_regex(rel_glob)+ except _re.error:+ continue+ for candidate in path_set:+ if regex.match(candidate):+ targets.add(candidate)+ continue+ # Bare directory token (``eslint src runtime-tests build``)+ # — mark every source file inside as live. Constrained to+ # directories that actually exist in ``path_set`` to avoid+ # treating arbitrary identifiers (``run``, ``--``) as dirs.+ if "/" not in token and token in (+ "src", "lib", "app", "test", "tests", "scripts",+ "benchmarks", "perf-measures", "runtime-tests", "build",+ "examples",+ ):+ dir_rel = pkg_prefix + token+ files = dirs_in_repo.get(dir_rel.rstrip("/"))+ if files:+ for f in files:+ if any(f.lower().endswith(ext) for ext in _NPM_SCRIPT_SOURCE_EXTS):+ targets.add(f)++ # Catch experimental sub-directories nested inside a package — e.g.+ # ``packages/tsc/bench/*.ts``, ``examples/*/index.ts`` — where the+ # parent ``package.json`` doesn't itself match the experimental+ # convention but a descendant directory does. We only scan dirs that+ # already appear in ``dirs_in_repo`` (i.e., that hold source files),+ # so the pass is bounded by what's in ``path_set``.+ for dir_rel, files in dirs_in_repo.items():+ last_seg = dir_rel.rsplit("/", 1)[-1].lower()+ if last_seg not in _EXPERIMENT_DIR_NAMES:+ continue+ for f in files:+ if any(f.lower().endswith(ext) for ext in _NPM_SCRIPT_SOURCE_EXTS):+ targets.add(f)+ return targetsdiff --git a/packages/core/src/repowise/core/ingestion/resolvers/typescript.py b/packages/core/src/repowise/core/ingestion/resolvers/typescript.pyindex da4ec1ada..d19e200fa 100644--- a/packages/core/src/repowise/core/ingestion/resolvers/typescript.py+++ b/packages/core/src/repowise/core/ingestion/resolvers/typescript.py@@ -2,6 +2,7 @@from __future__ import annotations+import posixpathfrom pathlib import Pathfrom .context import ResolverContext@@ -13,21 +14,33 @@ def resolve_ts_js_import(module_path: str, importer_path: str, ctx: ResolverContimporter_dir = Path(importer_path).parentif module_path.startswith("."):- base = importer_dir / module_path+ # Join + normalize via posixpath so ``../../helper/html`` collapses+ # against the importer's directory. ``pathlib`` doesn't normalize+ # ``..`` segments unless the path exists on disk; without this+ # step, every cross-directory relative import silently fails to+ # resolve and reads as an external dep.+ base_posix = posixpath.normpath(+ posixpath.join(importer_dir.as_posix(), module_path)+ )exts: tuple[str, ...] = (".ts", ".tsx", ".js", ".jsx", "/index.ts", "/index.js")if ctx.has_sfc_files:exts = exts + (".vue", ".svelte", ".astro")for ext in exts:- candidate = Path(str(base) + ext).as_posix()- if candidate in ctx.path_set:- return candidate- candidate = (- base.with_suffix(ext).as_posix()- if not ext.startswith("/")- else (base / "index.ts").as_posix()- )+ candidate = base_posix + extif candidate in ctx.path_set:return candidate+ # Legacy fallback: ``.with_suffix``-style replacement only kicks+ # in when the specifier already carries a fake extension that+ # users intended to be stripped (``./foo.js`` resolving to+ # ``./foo.ts`` under TS rewrite rules). Guarded so it never+ # clobbers a real multi-dot stem (``foo.config``, ``site.meta``).+ stem_dot = base_posix.rfind(".")+ if stem_dot > base_posix.rfind("/"):+ real_stem = base_posix[:stem_dot]+ for ext in (".ts", ".tsx"):+ candidate = real_stem + ext+ if candidate in ctx.path_set:+ return candidatereturn None# Non-relative: try tsconfig path-alias resolution first.diff --git a/packages/core/src/repowise/core/ingestion/tsconfig_resolver.py b/packages/core/src/repowise/core/ingestion/tsconfig_resolver.pyindex d45c3f002..87591f41a 100644--- a/packages/core/src/repowise/core/ingestion/tsconfig_resolver.py+++ b/packages/core/src/repowise/core/ingestion/tsconfig_resolver.py@@ -382,9 +382,14 @@ class TsconfigResolver:if rel is not None and rel in self._path_set:return rel- # 2. Direct extensions.+ # 2. Direct extensions. ``Path.with_suffix`` *replaces* the last+ # ``.``-component, so for specifiers like ``app/layout.config``+ # Python's pathlib would clobber ``.config`` and probe+ # ``app/layout.tsx`` — yielding the wrong file. Append the+ # extension as a string instead so multi-dot module names+ # (``layout.config``, ``site.metadata``, ``foo.test``) resolve.for ext in _TS_EXTENSIONS:- rel = self._to_repo_relative(base.with_suffix(ext))+ rel = self._to_repo_relative(Path(str(base) + ext))if rel is not None and rel in self._path_set:return reldiff --git a/packages/core/src/repowise/core/ingestion/type_ref_resolution.py b/packages/core/src/repowise/core/ingestion/type_ref_resolution.pyindex a027bdeea..718a2f6f5 100644--- a/packages/core/src/repowise/core/ingestion/type_ref_resolution.py+++ b/packages/core/src/repowise/core/ingestion/type_ref_resolution.py@@ -350,6 +350,130 @@ def _find_c_type_file(return None+# ---------------------------------------------------------------------------+# Strategy: TypeScript / JavaScript+# ---------------------------------------------------------------------------++def _resolve_ts_type_refs(+ parsed: ParsedFile,+ ctx: "ResolverContext",+ graph: "nx.DiGraph",+) -> int:+ """Resolve TS/JS ``@param.type`` captures via import bindings + stem map.++ TypeScript has no central type-name registry the way C# has the+ project's type-map; the canonical place to learn ``Foo``'s defining+ file is the file's own ``import`` statements. The resolution order+ mirrors how ``tsc`` itself reasons about names:++ 1. ``import { Foo } from './x'`` — bound name; the import's+ ``resolved_file`` is the answer.+ 2. ``import * as ns from './x'`` — ``ns.Foo`` strips to ``Foo``;+ the namespace alias points at the module.+ 3. Stem-map fallback — unique global file whose+ basename matches the type name; matches Rust's strategy.+ 4. Same-file definitions are skipped silently (no edge needed).++ This emits ``type_use`` edges at file granularity — the dead-code+ analyzer's unused-export pass consumes ``imported_names`` on either+ edge type, so an ``interface Foo`` referenced only as a field type+ in a sibling module is no longer flagged.+ """+ if not parsed.type_refs:+ return 0++ from_path = parsed.file_info.path++ # name -> (resolved_file, exported_name) for direct imports.+ name_to_source: dict[str, str] = {}+ # alias -> resolved_file for namespace / module imports.+ namespace_to_source: dict[str, str] = {}+ for imp in parsed.imports:+ if not imp.resolved_file or imp.resolved_file.startswith("external:"):+ continue+ for binding in imp.bindings:+ if binding.local_name == "*":+ continue+ if binding.is_module_alias:+ namespace_to_source[binding.local_name] = imp.resolved_file+ else:+ name_to_source[binding.local_name] = imp.resolved_file++ # Symbol names defined in this file — used to filter same-file refs.+ local_names: set[str] = {s.name for s in parsed.symbols if s.name}++ # Stamp same-file type references on the file node so the dead-code+ # analyzer can treat an ``interface Foo`` referenced as ``bar: Foo``+ # inside its own file as live, even though we never emit a self-loop+ # edge. The C#/Go strategies don't need this because their resolvers+ # rely on package-level symbol indexes and reach types through value+ # imports; TS commonly defines a private interface beside the class+ # that consumes it (``src/context.ts::Get`` is the canonical case).+ same_file_refs: set[str] = set()++ emitted = 0+ seen: set[tuple[str, str]] = set()+ for ref in parsed.type_refs:+ name = ref.type_name+ if not name:+ continue+ if name in local_names:+ same_file_refs.add(name)+ continue+ target = name_to_source.get(name) or namespace_to_source.get(name)+ if target is None:+ target = _find_ts_type_in_stem_map(name, from_path, ctx, graph)+ if target is None or target == from_path:+ continue+ if (name, target) in seen:+ continue+ seen.add((name, target))+ if not graph.has_node(target):+ continue+ _add_or_merge_type_use_edge(+ graph, src=from_path, dst=target, type_name=name, origin=ref.origin+ )+ emitted += 1++ if same_file_refs and graph.has_node(from_path):+ existing = graph.nodes[from_path].get("local_type_uses")+ if existing is None:+ graph.nodes[from_path]["local_type_uses"] = same_file_refs+ else:+ existing.update(same_file_refs)++ return emitted+++def _find_ts_type_in_stem_map(+ type_name: str,+ from_path: str,+ ctx: "ResolverContext",+ graph: "nx.DiGraph",+) -> str | None:+ """Locate ``type_name`` via the global stem map.++ Used when no import binds the name — common when a sibling module+ in the same package augments a global ``namespace`` or when a type+ is reached via a tsconfig-paths alias whose binding wasn't extracted+ (rare but possible). A match is only accepted if exactly one file+ in the workspace defines a top-level symbol by that name.+ """+ candidates = ctx.stem_map.get(type_name.lower(), [])+ if len(candidates) != 1:+ return None+ candidate = candidates[0]+ if candidate == from_path or not graph.has_node(candidate):+ return None+ # Verify the candidate file actually exports a symbol matching name —+ # avoids accidentally matching ``utils.ts`` to a type called ``Utils``.+ for succ in graph.successors(candidate):+ nd = graph.nodes.get(succ, {})+ if nd.get("node_type") == "symbol" and nd.get("name") == type_name:+ return candidate+ return None++# ---------------------------------------------------------------------------# Strategy registry# ---------------------------------------------------------------------------@@ -365,6 +489,8 @@ _STRATEGIES: dict[str, Strategy] = {"go": _resolve_go_type_refs,"c": _resolve_c_type_refs,"cpp": _resolve_c_type_refs,+ "typescript": _resolve_ts_type_refs,+ "javascript": _resolve_ts_type_refs,}diff --git a/tests/fixtures/ts_sample/package.json b/tests/fixtures/ts_sample/package.jsonnew file mode 100644index 000000000..eb4b7407e--- /dev/null+++ b/tests/fixtures/ts_sample/package.json@@ -0,0 +1,9 @@+{+ "name": "@org/ts-sample-root",+ "private": true,+ "workspaces": ["packages/*"],+ "scripts": {+ "build": "tsx scripts/build.ts",+ "lint": "eslint src"+ }+}diff --git a/tests/fixtures/ts_sample/packages/app/package.json b/tests/fixtures/ts_sample/packages/app/package.jsonnew file mode 100644index 000000000..8cc71dcfb--- /dev/null+++ b/tests/fixtures/ts_sample/packages/app/package.json@@ -0,0 +1,8 @@+{+ "name": "@org/app",+ "private": true,+ "main": "./src/main.ts",+ "scripts": {+ "start": "tsx src/main.ts"+ }+}diff --git a/tests/fixtures/ts_sample/packages/app/src/__tests__/helper.test.ts b/tests/fixtures/ts_sample/packages/app/src/__tests__/helper.test.tsnew file mode 100644index 000000000..08cd0c2e2--- /dev/null+++ b/tests/fixtures/ts_sample/packages/app/src/__tests__/helper.test.ts@@ -0,0 +1,10 @@+import { helper } from "../helper";++// Phase 1's ``**/*.test.ts`` never-flag must exempt this file. Without it+// the file looks like a top-level orphan (vitest discovers it via filename+// convention, not via static import).+describe("helper", () => {+ it("returns world", () => {+ expect(helper()).toBe("world");+ });+});diff --git a/tests/fixtures/ts_sample/packages/app/src/app/page.tsx b/tests/fixtures/ts_sample/packages/app/src/app/page.tsxnew file mode 100644index 000000000..74bba91b9--- /dev/null+++ b/tests/fixtures/ts_sample/packages/app/src/app/page.tsx@@ -0,0 +1,8 @@+// Next.js App Router page — never imported by static code; reachability+// flows through Phase 3's next_app framework edges and the+// ``**/page.tsx`` never-flag glob.+import { helper } from "../helper";++export default function Page(): string {+ return helper();+}diff --git a/tests/fixtures/ts_sample/packages/app/src/app/route.ts b/tests/fixtures/ts_sample/packages/app/src/app/route.tsnew file mode 100644index 000000000..6787b5c8b--- /dev/null+++ b/tests/fixtures/ts_sample/packages/app/src/app/route.ts@@ -0,0 +1,4 @@+// Next.js App Router ``route.ts`` — same convention story as ``page.tsx``.+export function GET(): Response {+ return new Response("ok");+}diff --git a/tests/fixtures/ts_sample/packages/app/src/helper.ts b/tests/fixtures/ts_sample/packages/app/src/helper.tsnew file mode 100644index 000000000..5805ec275--- /dev/null+++ b/tests/fixtures/ts_sample/packages/app/src/helper.ts@@ -0,0 +1,3 @@+export function helper(): string {+ return "world";+}diff --git a/tests/fixtures/ts_sample/packages/app/src/main.ts b/tests/fixtures/ts_sample/packages/app/src/main.tsnew file mode 100644index 000000000..1c1a93c8a--- /dev/null+++ b/tests/fixtures/ts_sample/packages/app/src/main.ts@@ -0,0 +1,6 @@+import { UserService } from "@org/lib";+import { helper } from "./helper";++const svc = new UserService();+svc.setCurrent({ id: "1", name: helper() });+console.log(svc.greet());diff --git a/tests/fixtures/ts_sample/packages/lib/package.json b/tests/fixtures/ts_sample/packages/lib/package.jsonnew file mode 100644index 000000000..a4d7a261c--- /dev/null+++ b/tests/fixtures/ts_sample/packages/lib/package.json@@ -0,0 +1,9 @@+{+ "name": "@org/lib",+ "private": false,+ "main": "./src/index.ts",+ "exports": {+ ".": "./src/index.ts",+ "./locales/*": "./src/locales/*.ts"+ }+}diff --git a/tests/fixtures/ts_sample/packages/lib/src/index.ts b/tests/fixtures/ts_sample/packages/lib/src/index.tsnew file mode 100644index 000000000..3bc8c5d45--- /dev/null+++ b/tests/fixtures/ts_sample/packages/lib/src/index.ts@@ -0,0 +1,3 @@+// Public entry point. Re-exports everything an npm consumer would need.+export { UserService } from "./user-service";+export type { User } from "./types";diff --git a/tests/fixtures/ts_sample/packages/lib/src/locales/en.ts b/tests/fixtures/ts_sample/packages/lib/src/locales/en.tsnew file mode 100644index 000000000..8bc537816--- /dev/null+++ b/tests/fixtures/ts_sample/packages/lib/src/locales/en.ts@@ -0,0 +1,3 @@+// Reached only via the ``./locales/*`` wildcard in package.json#exports.+// Phase 1's TsWorkspaceIndex must surface this file as an entry point.+export const en = { hello: "Hello" };diff --git a/tests/fixtures/ts_sample/packages/lib/src/locales/fr.ts b/tests/fixtures/ts_sample/packages/lib/src/locales/fr.tsnew file mode 100644index 000000000..183ab0a89--- /dev/null+++ b/tests/fixtures/ts_sample/packages/lib/src/locales/fr.ts@@ -0,0 +1 @@+export const fr = { hello: "Bonjour" };diff --git a/tests/fixtures/ts_sample/packages/lib/src/orphan.ts b/tests/fixtures/ts_sample/packages/lib/src/orphan.tsnew file mode 100644index 000000000..7e00c2ad2--- /dev/null+++ b/tests/fixtures/ts_sample/packages/lib/src/orphan.ts@@ -0,0 +1,6 @@+// Genuinely-orphaned module: not in any package.json#exports map, not+// imported by anyone, no never-flag glob covers it. Must BE flagged+// unreachable_file — the analyzer's true-positive cross-check.+export function unusedHelper(): number {+ return 42;+}diff --git a/tests/fixtures/ts_sample/packages/lib/src/types.ts b/tests/fixtures/ts_sample/packages/lib/src/types.tsnew file mode 100644index 000000000..f16673b00--- /dev/null+++ b/tests/fixtures/ts_sample/packages/lib/src/types.ts@@ -0,0 +1,12 @@+// Interface used only as a field type — must NOT be flagged unused_export.+// Phase 2's type_use edges should connect User -> UserService.+export interface User {+ id: string;+ name: string;+}++// Genuinely-dead exported interface — referenced nowhere as a value or as a+// type. This is the planted "true positive" the analyzer must still flag.+export interface UnusedConfigShape {+ flag: boolean;+}diff --git a/tests/fixtures/ts_sample/packages/lib/src/user-service.ts b/tests/fixtures/ts_sample/packages/lib/src/user-service.tsnew file mode 100644index 000000000..8f173b490--- /dev/null+++ b/tests/fixtures/ts_sample/packages/lib/src/user-service.ts@@ -0,0 +1,16 @@+import type { User } from "./types";++// Class implementing an interface via a field-typed annotation — exercises+// Phase 2's type_use edge resolution. ``User`` must NOT be flagged+// unused_export despite no value-position reference.+export class UserService {+ private current: User | null = null;++ setCurrent(user: User): void {+ this.current = user;+ }++ greet(): string {+ return this.current?.name ?? "anonymous";+ }+}diff --git a/tests/fixtures/ts_sample/scripts/build.ts b/tests/fixtures/ts_sample/scripts/build.tsnew file mode 100644index 000000000..e97c883a6--- /dev/null+++ b/tests/fixtures/ts_sample/scripts/build.ts@@ -0,0 +1,7 @@+// Top-level script invoked through ``npm run build`` (``tsx scripts/build.ts``)+// — never imported by anything else but must not be flagged unreachable.+export function build(): void {+ console.log("build");+}++build();diff --git a/tests/fixtures/ts_sample/tsconfig.json b/tests/fixtures/ts_sample/tsconfig.jsonnew file mode 100644index 000000000..83caf541f--- /dev/null+++ b/tests/fixtures/ts_sample/tsconfig.json@@ -0,0 +1,13 @@+{+ "compilerOptions": {+ "target": "ESNext",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "jsx": "preserve",+ "baseUrl": ".",+ "paths": {+ "@/*": ["./packages/app/*"]+ }+ },+ "include": ["packages/**/*.ts", "packages/**/*.tsx"]+}diff --git a/tests/integration/test_ts_dead_code.py b/tests/integration/test_ts_dead_code.pynew file mode 100644index 000000000..207612e0b--- /dev/null+++ b/tests/integration/test_ts_dead_code.py@@ -0,0 +1,109 @@+"""End-to-end TS/JS dead-code regression test for the ts_sample fixture.++Runs the full FileTraverser -> ASTParser -> GraphBuilder -> DeadCodeAnalyzer+pipeline against tests/fixtures/ts_sample and proves the JS/TS-parity work+(Phases 1-3) holds together: the one planted genuinely-dead interface is+flagged, the genuinely-orphaned module is unreachable, and everything that+is actually live -- across workspace packages, exports-wildcard entry+points, never-flag convention files (tests/Next.js app router),+script-runner entry detection, and Phase 2 type-use edges -- is NOT+flagged.++This is the regression guard that keeps the TS analyzer honest: if a future+change makes it over-suppress (the live assertions hold but the dead ones+fail) or regress to false positives (the dead assertions hold but a live+one fails), this test breaks.+"""++from __future__ import annotations++from pathlib import Path++import pytest++from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind+from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder++TS_SAMPLE = Path(__file__).parent.parent / "fixtures" / "ts_sample"++[email protected](scope="module")+def ts_report():+ traverser = FileTraverser(TS_SAMPLE)+ parser = ASTParser()+ builder = GraphBuilder(repo_path=TS_SAMPLE)++ for fi in traverser.traverse():+ source = Path(fi.abs_path).read_bytes()+ builder.add_file(parser.parse_file(fi, source))++ graph = builder.build()+ analyzer = DeadCodeAnalyzer(graph, git_meta_map={})+ return analyzer.analyze({"min_confidence": 0.0})+++def _names(report, kind) -> set[str]:+ return {f.symbol_name for f in report.findings if f.kind == kind}+++def _paths(report, kind) -> set[str]:+ return {f.file_path for f in report.findings if f.kind == kind}+++class TestTsSampleHonesty:+ """The planted true positives must still be flagged."""++ def test_planted_dead_interface_is_flagged(self, ts_report) -> None:+ exports = _names(ts_report, DeadCodeKind.UNUSED_EXPORT)+ assert "UnusedConfigShape" in exports++ def test_orphan_module_is_unreachable(self, ts_report) -> None:+ unreachable = _paths(ts_report, DeadCodeKind.UNREACHABLE_FILE)+ assert any("packages/lib/src/orphan.ts" in p for p in unreachable)+++class TestTsSampleNoFalsePositives:+ """Live code must NOT be flagged."""++ def test_interface_used_only_as_type_is_live(self, ts_report) -> None:+ exports = _names(ts_report, DeadCodeKind.UNUSED_EXPORT)+ # ``User`` is referenced only as a field type / parameter type. Phase 2's+ # type_use resolution must keep it off the unused list.+ assert "User" not in exports++ def test_workspace_main_entry_not_unreachable(self, ts_report) -> None:+ unreachable = _paths(ts_report, DeadCodeKind.UNREACHABLE_FILE)+ for live in (+ "packages/lib/src/index.ts",+ "packages/lib/src/user-service.ts",+ "packages/app/src/main.ts",+ "packages/app/src/helper.ts",+ ):+ assert not any(live in p for p in unreachable), f"{live} wrongly unreachable"++ def test_exports_wildcard_locales_not_unreachable(self, ts_report) -> None:+ unreachable = _paths(ts_report, DeadCodeKind.UNREACHABLE_FILE)+ # Both locales are reached only through ``"./locales/*"`` in+ # package.json#exports. Phase 1's TsWorkspaceIndex must mark them+ # is_entry_point so the analyzer doesn't flag them.+ for locale in ("en.ts", "fr.ts"):+ assert not any(f"packages/lib/src/locales/{locale}" in p for p in unreachable)++ def test_test_file_not_unreachable(self, ts_report) -> None:+ unreachable = _paths(ts_report, DeadCodeKind.UNREACHABLE_FILE)+ # ``**/*.test.ts`` is never-flagged.+ assert not any("helper.test.ts" in p for p in unreachable)++ def test_next_app_router_files_not_unreachable(self, ts_report) -> None:+ unreachable = _paths(ts_report, DeadCodeKind.UNREACHABLE_FILE)+ # ``app/page.tsx`` and ``app/route.ts`` are filesystem-convention+ # entry points and must not be flagged.+ for fname in ("page.tsx", "route.ts"):+ assert not any(f"app/{fname}" in p for p in unreachable)++ def test_npm_script_entry_not_unreachable(self, ts_report) -> None:+ unreachable = _paths(ts_report, DeadCodeKind.UNREACHABLE_FILE)+ # ``scripts/build.ts`` is referenced from package.json#scripts.build+ # via ``tsx scripts/build.ts``. Phase 3's script scanner must+ # surface it as live.+ assert not any("scripts/build.ts" in p for p in unreachable)diff --git a/tests/unit/analysis/test_jsx_namespace_exempt.py b/tests/unit/analysis/test_jsx_namespace_exempt.pynew file mode 100644index 000000000..2a9f06717--- /dev/null+++ b/tests/unit/analysis/test_jsx_namespace_exempt.py@@ -0,0 +1,118 @@+"""Types declared inside a ``namespace JSX`` block are not flagged.++Hono's ``src/jsx/intrinsic-elements.ts`` declares ``namespace JSX``+and exports ~100 interfaces / type aliases (HTMLAttributes,+ButtonHTMLAttributes, CSSProperties, …). They're all referenced+implicitly by every JSX expression via the TypeScript compiler — never+via an ``import`` statement. The exemption is the file-level+``namespace JSX`` source check: any interface / type-alias defined in+a file with that declaration is treated as a JSX transformer+integration point.++Tree-sitter doesn't currently propagate namespace parentage to a+symbol's ``parent_name``, so the source-scan is the working signal.+Symbols outside a ``namespace JSX`` file are still flaggable.+"""++from __future__ import annotations++from pathlib import Path+from types import SimpleNamespace+from unittest.mock import patch++import networkx as nx++from repowise.core.analysis.dead_code.analyzer import DeadCodeAnalyzer+++def _file_node(graph: nx.DiGraph, path: str, language: str = "typescript") -> None:+ graph.add_node(+ path,+ node_type="file",+ language=language,+ symbol_count=1,+ is_test=False,+ is_entry_point=False,+ )+++def _sym_node(+ graph: nx.DiGraph,+ file_path: str,+ name: str,+ kind: str = "interface",+) -> str:+ sid = f"{file_path}::{name}"+ graph.add_node(+ sid,+ node_type="symbol",+ kind=kind,+ name=name,+ file_path=file_path,+ start_line=1,+ end_line=5,+ visibility="public",+ language="typescript",+ decorators=[],+ )+ graph.add_edge(file_path, sid, edge_type="defines")+ return sid+++def _fake_parsed(path: str, source: str, tmp_path: Path) -> dict:+ src_file = tmp_path / path+ src_file.parent.mkdir(parents=True, exist_ok=True)+ src_file.write_text(source, encoding="utf-8")+ file_info = SimpleNamespace(abs_path=str(src_file), language="typescript", is_test=False)+ pf = SimpleNamespace(file_info=file_info)+ return {path: pf}+++class TestJsxNamespaceExemption:+ def test_intrinsic_elements_in_jsx_namespace_not_flagged(self, tmp_path: Path) -> None:+ g = nx.DiGraph()+ # File node has an inbound importer so unused-export pass runs+ # at confidence=1.0 (not "missing implementors" path).+ _file_node(g, "src/jsx/base.ts")+ _file_node(g, "src/importer.ts")+ g.add_edge("src/importer.ts", "src/jsx/base.ts", edge_type="imports", imported_names=[])+ _sym_node(g, "src/jsx/base.ts", "IntrinsicElements", kind="interface")+ _sym_node(g, "src/jsx/base.ts", "ElementChildrenAttribute", kind="interface")+ # Other types declared in the same namespace JSX file — HTML+ # attribute shapes — also implicitly consumed by the transformer.+ _sym_node(g, "src/jsx/base.ts", "HTMLAttributes", kind="interface")+ _sym_node(g, "src/jsx/base.ts", "CSSProperties", kind="type_alias")+ # A function in the same file IS still flaggable (only types+ # get the JSX-namespace exemption).+ _sym_node(g, "src/jsx/base.ts", "someHelper", kind="function")+ parsed = _fake_parsed(+ "src/jsx/base.ts",+ "export namespace JSX { export interface IntrinsicElements {} }\n",+ tmp_path,+ )++ analyzer = DeadCodeAnalyzer(g, parsed_files=parsed)+ report = analyzer.analyze({"min_confidence": 0.0})+ flagged = {f.symbol_name for f in report.findings if f.kind.value == "unused_export"}+ assert "IntrinsicElements" not in flagged+ assert "ElementChildrenAttribute" not in flagged+ assert "HTMLAttributes" not in flagged+ assert "CSSProperties" not in flagged+ # Control: non-type symbols are still flaggable.+ assert "someHelper" in flagged++ def test_whitelist_name_outside_jsx_namespace_still_flagged(self, tmp_path: Path) -> None:+ g = nx.DiGraph()+ _file_node(g, "src/types.ts")+ _file_node(g, "src/importer.ts")+ g.add_edge("src/importer.ts", "src/types.ts", edge_type="imports", imported_names=[])+ _sym_node(g, "src/types.ts", "IntrinsicElements", kind="interface")+ # No ``namespace JSX`` declaration — exemption must NOT apply.+ parsed = _fake_parsed(+ "src/types.ts", "export interface IntrinsicElements {}\n", tmp_path+ )++ analyzer = DeadCodeAnalyzer(g, parsed_files=parsed)+ report = analyzer.analyze({"min_confidence": 0.0})+ flagged = {f.symbol_name for f in report.findings if f.kind.value == "unused_export"}+ assert "IntrinsicElements" in flaggeddiff --git a/tests/unit/analysis/test_ts_never_flag.py b/tests/unit/analysis/test_ts_never_flag.pynew file mode 100644index 000000000..32cd290b0--- /dev/null+++ b/tests/unit/analysis/test_ts_never_flag.py@@ -0,0 +1,114 @@+"""Phase 1 — TS/JS never-flag patterns and entry-point symbol coverage.++These tests pin the dead-code analyzer's TS/JS exemptions: test/spec+files, Storybook stories, codegen output, Next.js / Remix / SvelteKit+convention files, and route-export symbol names. Each assertion has a+matching "negative" — an ordinary source path that must still be+flaggable — so the patterns stay tight.+"""++from __future__ import annotations++import fnmatch+++def _matches(path: str) -> bool:+ from repowise.core.analysis.dead_code.constants import _NEVER_FLAG_PATTERNS+ return any(fnmatch.fnmatch(path, p) for p in _NEVER_FLAG_PATTERNS)+++class TestTestSpecFiles:+ def test_test_suffix_variants(self):+ assert _matches("src/compose.test.ts")+ assert _matches("src/foo.test.tsx")+ assert _matches("src/foo.test.js")+ assert _matches("src/foo.test.jsx")+ assert _matches("src/foo.test.mjs")+ assert _matches("src/foo.test.cjs")+ assert _matches("packages/app/src/util.spec.ts")++ def test_tests_and_mocks_dirs(self):+ assert _matches("src/__tests__/foo.ts")+ assert _matches("packages/lib/__tests__/util.tsx")+ assert _matches("src/__mocks__/fs.ts")++ def test_ordinary_source_not_flagged(self):+ assert not _matches("src/index.ts")+ assert not _matches("src/utils/format.ts")+++class TestStoriesAndBench:+ def test_storybook_stories(self):+ assert _matches("src/Button.stories.tsx")+ assert _matches("packages/ui/src/Card.stories.ts")+ assert _matches("apps/web/Foo.stories.mdx")++ def test_bench_files(self):+ assert _matches("packages/zod/bench/arr.bench.ts")+ assert _matches("bench/parse.bench.js")+++class TestCodegenAndConvention:+ def test_next_env_and_gen(self):+ assert _matches("next-env.d.ts")+ assert _matches("apps/web/next-env.d.ts")+ assert _matches("src/api.gen.ts")+ assert _matches("src/types_generated.ts")+ assert _matches("packages/api/src/__generated__/schema.ts")+ assert _matches("packages/api/src/generated/openapi.ts")++ def test_next_app_router_conventions(self):+ assert _matches("apps/web/middleware.ts")+ assert _matches("apps/web/app/sitemap.ts")+ assert _matches("apps/web/app/robots.ts")+ assert _matches("apps/web/app/manifest.ts")+ assert _matches("apps/web/app/icon.tsx")+ assert _matches("apps/web/app/opengraph-image.tsx")+ assert _matches("apps/web/app/global-error.tsx")+ assert _matches("apps/web/instrumentation.ts")++ def test_remix_entries(self):+ assert _matches("app/entry.client.tsx")+ assert _matches("app/entry.server.ts")++ def test_sveltekit_conventions(self):+ assert _matches("src/routes/+page.svelte")+ assert _matches("src/routes/+layout.ts")+ assert _matches("src/routes/api/+server.ts")+++class TestNeverFlagDoesNotLeak:+ def test_python_not_affected(self):+ # New TS-only globs must not accidentally match Python paths.+ assert not _matches("src/foo.py")+ assert not _matches("tests/test_foo.py") # py tests get their own conftest path++ def test_go_not_affected(self):+ assert not _matches("internal/server/handler.go")+ # *_test.go is already exempt via the Go block — sanity check.+ assert _matches("internal/server/handler_test.go")+++class TestEntryPointSymbolNames:+ def test_nextjs_route_exports_included(self):+ from repowise.core.analysis.dead_code.analyzer import _ENTRY_POINT_SYMBOL_NAMES+ for name in (+ "generateStaticParams",+ "generateMetadata",+ "getStaticProps",+ "getServerSideProps",+ "reportWebVitals",+ ):+ assert name in _ENTRY_POINT_SYMBOL_NAMES++ def test_remix_route_exports_included(self):+ from repowise.core.analysis.dead_code.analyzer import _ENTRY_POINT_SYMBOL_NAMES+ for name in ("ErrorBoundary", "HydrateFallback", "clientLoader", "shouldRevalidate"):+ assert name in _ENTRY_POINT_SYMBOL_NAMES++ def test_common_names_excluded(self):+ # These names are too common to blanket-exempt — they'd mask+ # genuine dead code in non-route files across every language.+ from repowise.core.analysis.dead_code.analyzer import _ENTRY_POINT_SYMBOL_NAMES+ for name in ("load", "action", "loader", "meta", "metadata", "config", "headers"):+ assert name not in _ENTRY_POINT_SYMBOL_NAMESdiff --git a/tests/unit/ingestion/test_ts_framework_edges.py b/tests/unit/ingestion/test_ts_framework_edges.pynew file mode 100644index 000000000..7c6be9112--- /dev/null+++ b/tests/unit/ingestion/test_ts_framework_edges.py@@ -0,0 +1,124 @@+"""Unit tests for Next.js / Hono / Remix / tRPC framework edges (Phase 3)."""++from __future__ import annotations++from datetime import datetime+from pathlib import Path++import networkx as nx++from repowise.core.ingestion.framework_edges import add_framework_edges+from repowise.core.ingestion.models import FileInfo, ParsedFile+from repowise.core.ingestion.parser import ASTParser+from repowise.core.ingestion.resolvers.context import ResolverContext+++def _file_info(rel: str, abs_path: str, language: str = "typescript") -> FileInfo:+ return FileInfo(+ path=rel,+ abs_path=abs_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,+ )+++def _build_parsed(repo: Path) -> dict[str, ParsedFile]:+ parser = ASTParser()+ out: dict[str, ParsedFile] = {}+ for src in list(repo.rglob("*.ts")) + list(repo.rglob("*.tsx")):+ rel = src.resolve().relative_to(repo.resolve()).as_posix()+ lang = "typescript"+ out[rel] = parser.parse_file(_file_info(rel, str(src.resolve()), lang), src.read_bytes())+ return out+++def _ctx(repo: Path, parsed: dict[str, ParsedFile]) -> ResolverContext:+ path_set = set(parsed.keys())+ stem_map: dict[str, list[str]] = {}+ for p in path_set:+ stem = Path(p).stem.lower()+ stem_map.setdefault(stem, []).append(p)+ return ResolverContext(+ path_set=path_set, stem_map=stem_map, graph=nx.DiGraph(), repo_path=repo+ )+++class TestNextAppRouter:+ def test_app_page_links_to_imported_helper(self, tmp_path: Path) -> None:+ (tmp_path / "lib").mkdir()+ (tmp_path / "lib" / "db.ts").write_text("export const db = {};\n")+ (tmp_path / "app").mkdir()+ (tmp_path / "app" / "page.tsx").write_text(+ "import { db } from '../lib/db';\nexport default function() { return db; }\n"+ )+ parsed = _build_parsed(tmp_path)+ graph = nx.DiGraph()+ for p in parsed:+ graph.add_node(p)+ ctx = _ctx(tmp_path, parsed)+ add_framework_edges(graph, parsed, ctx, tech_stack=["next"])+ assert graph.has_edge("app/page.tsx", "lib/db.ts")+++class TestHonoRouter:+ def test_app_get_links_handler(self, tmp_path: Path) -> None:+ (tmp_path / "handlers.ts").write_text(+ "export function userHandler() { return 'ok'; }\n"+ )+ (tmp_path / "app.ts").write_text(+ "import { Hono } from 'hono';\n"+ "import { userHandler } from './handlers';\n"+ "const app = new Hono();\n"+ "app.get('/users', userHandler);\n"+ )+ parsed = _build_parsed(tmp_path)+ graph = nx.DiGraph()+ for p in parsed:+ graph.add_node(p)+ ctx = _ctx(tmp_path, parsed)+ add_framework_edges(graph, parsed, ctx, tech_stack=["hono"])+ assert graph.has_edge("app.ts", "handlers.ts")+++class TestRemixConvention:+ def test_route_file_links_to_helper(self, tmp_path: Path) -> None:+ (tmp_path / "utils").mkdir()+ (tmp_path / "utils" / "auth.ts").write_text("export const auth = {};\n")+ (tmp_path / "app" / "routes").mkdir(parents=True)+ (tmp_path / "app" / "routes" / "_index.tsx").write_text(+ "import { auth } from '../../utils/auth';\nexport function loader() { return auth; }\n"+ )+ parsed = _build_parsed(tmp_path)+ graph = nx.DiGraph()+ for p in parsed:+ graph.add_node(p)+ ctx = _ctx(tmp_path, parsed)+ add_framework_edges(graph, parsed, ctx, tech_stack=["remix"])+ assert graph.has_edge("app/routes/_index.tsx", "utils/auth.ts")+++class TestTrpc:+ def test_procedure_query_links_handler(self, tmp_path: Path) -> None:+ (tmp_path / "users.ts").write_text(+ "export function getUserHandler() { return null; }\n"+ )+ (tmp_path / "router.ts").write_text(+ "import { publicProcedure, router } from '@trpc/server';\n"+ "import { getUserHandler } from './users';\n"+ "export const appRouter = router({\n"+ " getUser: publicProcedure.query(getUserHandler),\n"+ "});\n"+ )+ parsed = _build_parsed(tmp_path)+ graph = nx.DiGraph()+ for p in parsed:+ graph.add_node(p)+ ctx = _ctx(tmp_path, parsed)+ add_framework_edges(graph, parsed, ctx, tech_stack=["trpc"])+ assert graph.has_edge("router.ts", "users.ts")diff --git a/tests/unit/ingestion/test_ts_type_use.py b/tests/unit/ingestion/test_ts_type_use.pynew file mode 100644index 000000000..8c8094728--- /dev/null+++ b/tests/unit/ingestion/test_ts_type_use.py@@ -0,0 +1,240 @@+"""TypeScript / JavaScript Phase 2 — type-reference resolution.++Covers the chain that turns TS type-position references into graph edges+the dead-code analyzer respects:++* ``@param.type`` capture → ``TypeReference`` extraction with the TS head+ extractor (unwraps ``Foo[]`` / ``ns.Foo`` / ``Foo<T>`` and filters TS+ builtins);+* ``_resolve_ts_type_refs`` → ``type_use`` edges for interfaces / classes+ used only as parameter / field / return / generic-constraint / heritage+ types and never imported as values;+* the end-to-end dead-code outcome: an exported ``interface`` referenced+ only as a TypeScript type annotation is no longer flagged+ ``unused_export``, while genuinely-dead interfaces still are.+"""++from __future__ import annotations++from datetime import datetime+from pathlib import Path++import networkx as nx+import pytest++from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind+from repowise.core.ingestion.graph import GraphBuilder+from repowise.core.ingestion.models import FileInfo+from repowise.core.ingestion.parser import ASTParser++_PARSER = ASTParser()+++def _file_info(path: str, abs_path: str, language: str = "typescript") -> FileInfo:+ return FileInfo(+ path=path,+ abs_path=abs_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,+ )+++# ---------------------------------------------------------------------------+# Parser: TS type-ref extraction + head unwrapping+# ---------------------------------------------------------------------------+++class TestTsTypeRefExtraction:+ def _parse(self, body: str, language: str = "typescript") -> list:+ info = _file_info("p/f.ts" if language == "typescript" else "p/f.js",+ "/repo/p/f", language=language)+ return _PARSER.parse_file(info, body.encode("utf-8")).type_refs++ def test_param_field_return_captured(self) -> None:+ refs = self._parse(+ "interface I { f: Field }\n"+ "class C { g: Gee }\n"+ "function take(x: Param): Return { return null as any }\n"+ "const arr = (a: ArrowParam): ArrowReturn => null as any;\n"+ )+ names = {r.type_name for r in refs}+ assert {"Field", "Gee", "Param", "Return", "ArrowParam", "ArrowReturn"} <= names++ def test_builtins_filtered(self) -> None:+ refs = self._parse(+ "function f(s: string, n: number, p: Promise<number>): Date { return new Date() }\n"+ )+ names = {r.type_name for r in refs}+ assert names.isdisjoint(+ {"string", "number", "Promise", "Date", "void", "any"}+ )++ def test_array_and_generic_unwrapped(self) -> None:+ refs = self._parse(+ "interface I { items: Item[]; promised: Promise<PValue> }\n"+ )+ names = {r.type_name for r in refs}+ # Item[] → Item, Promise<...> → filtered (builtin). PValue is+ # only captured if the grammar walks into generic arguments; we+ # don't require it here — only that Item is captured and Promise+ # is not treated as a user type.+ assert "Item" in names+ assert "Promise" not in names++ def test_heritage_extends_and_implements_captured(self) -> None:+ refs = self._parse(+ "interface IA extends IB, IC { }\n"+ "class Derived extends Base implements Iface { }\n"+ )+ names_by_origin = {(r.type_name, r.origin) for r in refs}+ assert ("IB", "extends") in names_by_origin+ assert ("IC", "extends") in names_by_origin+ assert ("Base", "extends") in names_by_origin+ assert ("Iface", "implements") in names_by_origin++ def test_generic_constraint_captured(self) -> None:+ refs = self._parse("function f<T extends Cons>(x: T): T { return x }\n")+ names_by_origin = {(r.type_name, r.origin) for r in refs}+ assert ("Cons", "generic_constraint") in names_by_origin+ # ``T`` is a single-uppercase generic param — filtered.+ assert "T" not in {n for n, _ in names_by_origin}++ def test_type_alias_rhs_captured(self) -> None:+ refs = self._parse("type Alias = OtherType\n")+ names_by_origin = {(r.type_name, r.origin) for r in refs}+ assert ("OtherType", "type_alias") in names_by_origin++ def test_namespace_qualified_type_dropped_to_head(self) -> None:+ refs = self._parse(+ "import * as ns from './x'\n"+ "function f(x: ns.Inner): void {}\n"+ )+ names = {r.type_name for r in refs}+ assert "Inner" in names+ assert "ns" not in names+++# ---------------------------------------------------------------------------+# type_use edges + dead-code outcome (end-to-end through GraphBuilder)+# ---------------------------------------------------------------------------+++def _build_graph(repo: Path, sources: dict[str, str]) -> nx.DiGraph:+ for rel, body in sources.items():+ p = repo / rel+ p.parent.mkdir(parents=True, exist_ok=True)+ p.write_text(body, encoding="utf-8")+ builder = GraphBuilder(repo_path=repo)+ for rel in sources:+ abs_path = str((repo / rel).resolve())+ parsed = _PARSER.parse_file(+ _file_info(rel, abs_path), (repo / rel).read_bytes()+ )+ builder.add_file(parsed)+ return builder.build()+++_TYPE_ONLY_SOURCES = {+ "types.ts": (+ "export interface UsedAsFieldType { name: string }\n"+ "export interface UsedAsParamType { x: number }\n"+ "export interface UsedAsReturnType { y: number }\n"+ "export interface UsedAsImpl { run(): void }\n"+ "export class UsedAsExtends { value = 1 }\n"+ "export interface GenuinelyDead {}\n"+ ),+ "consumer.ts": (+ "import type { UsedAsFieldType, UsedAsParamType, UsedAsReturnType }\n"+ " from './types'\n"+ "import { UsedAsImpl, UsedAsExtends } from './types'\n"+ "export class HasField { f: UsedAsFieldType = { name: 'x' } }\n"+ "export function takes(p: UsedAsParamType): UsedAsReturnType {\n"+ " return { y: p.x }\n"+ "}\n"+ "export class Impl implements UsedAsImpl { run(): void {} }\n"+ "export class Sub extends UsedAsExtends {}\n"+ ),+ "entry.ts": (+ "import { HasField, takes, Impl, Sub } from './consumer'\n"+ "new HasField(); takes({x: 1}); new Impl(); new Sub();\n"+ ),+}+++class TestTsTypeUseEdges:+ def test_type_only_import_produces_type_use_provenance(+ self, tmp_path: Path+ ) -> None:+ graph = _build_graph(tmp_path, _TYPE_ONLY_SOURCES)+ edge = graph.get_edge_data("consumer.ts", "types.ts", {})+ assert edge, "consumer.ts should connect to types.ts"+ # Imported names should cover both value-imports and type-position+ # references (the latter folded in by the type-ref strategy).+ names = set(edge.get("imported_names", []))+ assert {+ "UsedAsFieldType",+ "UsedAsParamType",+ "UsedAsReturnType",+ "UsedAsImpl",+ "UsedAsExtends",+ } <= names+++class TestTsDeadCodeOutcome:+ def _report(self, graph: nx.DiGraph):+ analyzer = DeadCodeAnalyzer(graph, git_meta_map={})+ return analyzer.analyze(+ {+ "detect_unreachable_files": False,+ "detect_zombie_packages": False,+ "detect_unused_internals": True,+ "min_confidence": 0.0,+ }+ )++ def test_types_referenced_only_as_annotations_not_flagged(+ self, tmp_path: Path+ ) -> None:+ report = self._report(_build_graph(tmp_path, _TYPE_ONLY_SOURCES))+ unused = {+ f.symbol_name+ for f in report.findings+ if f.kind == DeadCodeKind.UNUSED_EXPORT+ }+ # Each interface/class is consumed cross-file only as a TS type —+ # without type_use edges every one of these would be flagged.+ assert {+ "UsedAsFieldType",+ "UsedAsParamType",+ "UsedAsReturnType",+ "UsedAsImpl",+ "UsedAsExtends",+ }.isdisjoint(unused)++ def test_genuinely_dead_interface_still_flagged(self, tmp_path: Path) -> None:+ report = self._report(_build_graph(tmp_path, _TYPE_ONLY_SOURCES))+ unused = {+ f.symbol_name+ for f in report.findings+ if f.kind == DeadCodeKind.UNUSED_EXPORT+ }+ assert "GenuinelyDead" in unused+++# ---------------------------------------------------------------------------+# Strategy registration — sanity check+# ---------------------------------------------------------------------------+++class TestStrategyRegistration:+ def test_typescript_and_javascript_registered(self) -> None:+ from repowise.core.ingestion.type_ref_resolution import _STRATEGIES++ assert "typescript" in _STRATEGIES+ assert "javascript" in _STRATEGIESdiff --git a/tests/unit/ingestion/test_ts_workspace_index.py b/tests/unit/ingestion/test_ts_workspace_index.pynew file mode 100644index 000000000..19ef57ae6--- /dev/null+++ b/tests/unit/ingestion/test_ts_workspace_index.py@@ -0,0 +1,237 @@+"""Unit tests for ``TsWorkspaceIndex`` — exports-wildcard entry points,+MDX import scan, and the vitest ``include`` glob scanner.+"""++from __future__ import annotations++from pathlib import Path++import networkx as nx++from repowise.core.ingestion.resolvers.context import ResolverContext+from repowise.core.ingestion.resolvers.ts_workspace import (+ build_ts_workspace_index,+ find_mdx_import_targets,+ find_npm_script_entry_targets,+ find_vitest_include_targets,+ get_or_build_ts_index,+)+++def _write(repo: Path, rel: str, body: str) -> None:+ p = repo / rel+ p.parent.mkdir(parents=True, exist_ok=True)+ p.write_text(body, encoding="utf-8")+++def _ctx(repo: Path, paths: list[str]) -> ResolverContext:+ return ResolverContext(+ path_set=set(paths),+ stem_map={},+ graph=nx.DiGraph(),+ repo_path=repo,+ )+++class TestExportsWildcardEntries:+ def test_concrete_export_target_added(self, tmp_path: Path) -> None:+ _write(tmp_path, "package.json", '{"workspaces":["packages/*"]}')+ _write(+ tmp_path,+ "packages/foo/package.json",+ '{"name":"@org/foo","exports":{".":"./src/index.ts"}}',+ )+ _write(tmp_path, "packages/foo/src/index.ts", "export const x = 1;\n")+ ctx = _ctx(tmp_path, ["packages/foo/src/index.ts"])+ index = build_ts_workspace_index(ctx)+ assert "packages/foo/src/index.ts" in index.exports_entry_paths++ def test_wildcard_export_expands_to_all_matching_files(self, tmp_path: Path) -> None:+ _write(tmp_path, "package.json", '{"workspaces":["packages/*"]}')+ _write(+ tmp_path,+ "packages/zod/package.json",+ '{"name":"@org/zod","exports":{"./locales/*":"./src/locales/*.ts"}}',+ )+ for locale in ("ru", "be", "hy"):+ _write(tmp_path, f"packages/zod/src/locales/{locale}.ts", "export {};\n")+ paths = [f"packages/zod/src/locales/{x}.ts" for x in ("ru", "be", "hy")]+ ctx = _ctx(tmp_path, paths)+ index = build_ts_workspace_index(ctx)+ for p in paths:+ assert p in index.exports_entry_paths, p++ def test_main_field_marked_as_entry(self, tmp_path: Path) -> None:+ _write(tmp_path, "package.json", '{"workspaces":["packages/*"]}')+ _write(+ tmp_path,+ "packages/lib/package.json",+ '{"name":"@org/lib","main":"./src/main.ts"}',+ )+ _write(tmp_path, "packages/lib/src/main.ts", "export {};\n")+ ctx = _ctx(tmp_path, ["packages/lib/src/main.ts"])+ index = build_ts_workspace_index(ctx)+ assert "packages/lib/src/main.ts" in index.exports_entry_paths++ def test_index_is_cached(self, tmp_path: Path) -> None:+ ctx = _ctx(tmp_path, [])+ first = get_or_build_ts_index(ctx)+ second = get_or_build_ts_index(ctx)+ assert first is second+++class TestVitestIncludeScanner:+ def test_runtime_tests_glob_matches(self, tmp_path: Path) -> None:+ _write(+ tmp_path,+ "vitest.config.ts",+ 'export default { test: { include: ["runtime-tests/**/*.test.ts"] } };\n',+ )+ _write(tmp_path, "runtime-tests/foo.test.ts", "")+ _write(tmp_path, "runtime-tests/nested/bar.test.ts", "")+ # Non-matching path — must NOT be marked.+ _write(tmp_path, "src/unrelated.ts", "")+ ctx = _ctx(+ tmp_path,+ ["runtime-tests/foo.test.ts", "runtime-tests/nested/bar.test.ts", "src/unrelated.ts"],+ )+ matched = find_vitest_include_targets(ctx)+ assert "runtime-tests/foo.test.ts" in matched+ assert "runtime-tests/nested/bar.test.ts" in matched+ assert "src/unrelated.ts" not in matched+++class TestMdxImportScan:+ def test_mdx_import_resolves_to_tsx(self, tmp_path: Path) -> None:+ _write(+ tmp_path,+ "docs/page.mdx",+ 'import Bronze from "../components/bronze";\n\n# Hello\n',+ )+ _write(tmp_path, "components/bronze.tsx", "export default function() {}\n")+ ctx = _ctx(tmp_path, ["components/bronze.tsx", "docs/page.mdx"])+ targets = find_mdx_import_targets(ctx)+ assert "components/bronze.tsx" in targets++ def test_external_import_skipped(self, tmp_path: Path) -> None:+ _write(tmp_path, "docs/page.mdx", 'import React from "react";\n')+ ctx = _ctx(tmp_path, ["docs/page.mdx"])+ targets = find_mdx_import_targets(ctx)+ # ``react`` resolves to an ``external:`` node and must not enter+ # the entry-point set.+ assert not any(t.startswith("external:") for t in targets)+++class TestNpmScriptEntryScanner:+ def test_tsx_runner_path_resolves(self, tmp_path: Path) -> None:+ _write(+ tmp_path,+ "packages/bench/package.json",+ '{"name":"@org/bench","scripts":{"bench":"tsx --conditions src index.ts"}}',+ )+ _write(tmp_path, "packages/bench/index.ts", "")+ ctx = _ctx(tmp_path, ["packages/bench/index.ts"])+ assert "packages/bench/index.ts" in find_npm_script_entry_targets(ctx)++ def test_relative_path_in_root_package(self, tmp_path: Path) -> None:+ _write(+ tmp_path,+ "package.json",+ '{"scripts":{"build":"bun ./build/build.ts"}}',+ )+ _write(tmp_path, "build/build.ts", "")+ ctx = _ctx(tmp_path, ["build/build.ts"])+ assert "build/build.ts" in find_npm_script_entry_targets(ctx)++ def test_mts_extension_picked_up(self, tmp_path: Path) -> None:+ _write(+ tmp_path,+ "benchmarks/routers/package.json",+ '{"scripts":{"bench:node":"tsx ./src/bench.mts"}}',+ )+ _write(tmp_path, "benchmarks/routers/src/bench.mts", "")+ ctx = _ctx(tmp_path, ["benchmarks/routers/src/bench.mts"])+ assert "benchmarks/routers/src/bench.mts" in find_npm_script_entry_targets(ctx)++ def test_quoted_glob_expands(self, tmp_path: Path) -> None:+ # Prettier-style glob argument in a root script — the files+ # matched are maintained code even if no static import reaches+ # them.+ _write(+ tmp_path,+ "package.json",+ '{"scripts":{"format":"prettier --check \\"perf-measures/**/*.ts\\""}}',+ )+ _write(tmp_path, "perf-measures/foo.ts", "")+ _write(tmp_path, "perf-measures/nested/bar.ts", "")+ _write(tmp_path, "src/app.ts", "")+ ctx = _ctx(+ tmp_path,+ ["perf-measures/foo.ts", "perf-measures/nested/bar.ts", "src/app.ts"],+ )+ targets = find_npm_script_entry_targets(ctx)+ assert "perf-measures/foo.ts" in targets+ assert "perf-measures/nested/bar.ts" in targets+ assert "src/app.ts" not in targets++ def test_bare_directory_token_expands(self, tmp_path: Path) -> None:+ _write(+ tmp_path,+ "package.json",+ '{"scripts":{"lint":"eslint src benchmarks"}}',+ )+ _write(tmp_path, "benchmarks/deno/hono.ts", "")+ _write(tmp_path, "src/index.ts", "")+ ctx = _ctx(tmp_path, ["benchmarks/deno/hono.ts", "src/index.ts"])+ targets = find_npm_script_entry_targets(ctx)+ assert "benchmarks/deno/hono.ts" in targets+ assert "src/index.ts" in targets++ def test_experimental_subpackage_marks_all_sources(self, tmp_path: Path) -> None:+ # zod-style ``packages/bench/*`` — runtime-resolved via+ # ``import.meta.resolve`` so no static path appears. The+ # convention-name match rescues the whole sub-package.+ _write(+ tmp_path,+ "packages/bench/package.json",+ '{"name":"@org/benchmarks","private":true,"scripts":{"bench":"tsx index.ts"}}',+ )+ for name in ("index.ts", "array.ts", "boolean.ts"):+ _write(tmp_path, f"packages/bench/{name}", "")+ ctx = _ctx(+ tmp_path,+ ["packages/bench/index.ts", "packages/bench/array.ts", "packages/bench/boolean.ts"],+ )+ targets = find_npm_script_entry_targets(ctx)+ assert "packages/bench/array.ts" in targets+ assert "packages/bench/boolean.ts" in targets++ def test_nested_experimental_dir_inside_package(self, tmp_path: Path) -> None:+ # ``packages/tsc/bench/*.ts`` — package.json at packages/tsc,+ # but ``bench/`` is the experimental segment one level deeper.+ _write(+ tmp_path,+ "packages/tsc/package.json",+ '{"name":"@org/tsc-perf","scripts":{"build":"tsc"}}',+ )+ _write(tmp_path, "packages/tsc/bench/lots-of-objects.ts", "")+ _write(tmp_path, "packages/tsc/src/index.ts", "")+ ctx = _ctx(+ tmp_path,+ ["packages/tsc/bench/lots-of-objects.ts", "packages/tsc/src/index.ts"],+ )+ targets = find_npm_script_entry_targets(ctx)+ assert "packages/tsc/bench/lots-of-objects.ts" in targets+ # The ordinary ``src/index.ts`` is NOT auto-marked — that's+ # handled by the regular exports/main path.+ assert "packages/tsc/src/index.ts" not in targets++ def test_flags_do_not_resolve(self, tmp_path: Path) -> None:+ _write(+ tmp_path,+ "package.json",+ '{"scripts":{"x":"tsc --noEmit"}}',+ )+ ctx = _ctx(tmp_path, [])+ # No source files referenced — empty set, no crashes from ``-`` tokens.+ assert find_npm_script_entry_targets(ctx) == set()diff --git a/tests/unit/ingestion/test_tsconfig_resolver.py b/tests/unit/ingestion/test_tsconfig_resolver.pyindex 39faa9096..d9e6b853a 100644--- a/tests/unit/ingestion/test_tsconfig_resolver.py+++ b/tests/unit/ingestion/test_tsconfig_resolver.py@@ -76,6 +76,26 @@ class TestBasicAliasResolution:result = resolver.resolve("services/api", _importer(tmp_path, "src/app.tsx"))assert result == "src/services/api.ts"+ def test_multi_dot_specifier_resolves_to_tsx(self, tmp_path: Path) -> None:+ """``@/app/layout.config`` must resolve to ``app/layout.config.tsx``+ — not ``app/layout.tsx``. The earlier ``Path.with_suffix`` probe+ would clobber the ``.config`` segment.+ """+ resolver = _make_resolver(+ tmp_path,+ configs={+ "tsconfig.json": {+ "compilerOptions": {+ "baseUrl": ".",+ "paths": {"@/*": ["./*"]},+ }+ }+ },+ path_set={"app/layout.tsx", "app/layout.config.tsx"},+ )+ result = resolver.resolve("@/app/layout.config", _importer(tmp_path, "app/page.tsx"))+ assert result == "app/layout.config.tsx"+def test_exact_non_wildcard_mapping(self, tmp_path: Path) -> None:"""paths: {'utils': ['./src/utils/index.ts']} — exact key, no wildcard."""resolver = _make_resolver(