Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat: dead-code accuracy for embedded JS + C/WASM (#268)
Raghav Chamadiya674d341bfa21
diff --git a/docs/LANGUAGE_SUPPORT.md b/docs/LANGUAGE_SUPPORT.mdindex 3e2c834ce..0713af834 100644--- a/docs/LANGUAGE_SUPPORT.md+++ b/docs/LANGUAGE_SUPPORT.md@@ -51,10 +51,11 @@ All eight languages support:- Heritage extraction (class/interface/trait/record inheritance chains)- Docstring extraction (Python, JSDoc, GoDoc, Rustdoc, Javadoc, Doxygen, XML doc)- Framework-aware edges (Django, FastAPI, Flask for Python; tsconfig path aliases for TS/JS; pytest fixture detection; ASP.NET controllers / minimal API / EF Core DbContext for C#; Spring Boot DI + `@Bean` factories for Java/Kotlin; Rails routes + ActiveRecord relationships; Laravel routes + service providers + Eloquent; TYPO3 convention files (`ext_localconf.php`, `Configuration/TCA/*`, `JavaScriptModules.php` registrations) for PHP; Express `app.use(router)` + NestJS `@Module` arrays; Gin/Echo/Chi router + stdlib `net/http` (`http.HandleFunc` / `mux.Handle`) + gRPC `RegisterXxxServer` → handler/impl files for Go; Axum/Actix `.route` → handler files for Rust)-- Per-language dynamic-hint extractors (Django/Pytest/Node/`importlib` string-import registries for Python+JS/TS; .NET DI/Activator/InternalsVisibleTo for C#; Spring `getBean`/`@Bean` factories for Java/Kotlin; Ruby `send`/`const_get`/`define_method`/`delegate`; PHP `call_user_func`/`ReflectionClass`/container `get`; Scala `Class.forName`/`given`/`implicit val`; Swift `NSClassFromString`/`Selector`/`#selector`/KVC; C function-pointer assignment + `dlopen`/`dlsym`; Luau `game:GetService`/`setmetatable __index`; Go `reflect.TypeOf`/`reflect.New`/`reflect.ValueOf`/`plugin.Open`/`plugin.Lookup`)+- Per-language dynamic-hint extractors (Django/Pytest/Node/`importlib` string-import registries for Python+JS/TS; .NET DI/Activator/InternalsVisibleTo for C#; Spring `getBean`/`@Bean` factories for Java/Kotlin; Ruby `send`/`const_get`/`define_method`/`delegate`; PHP `call_user_func`/`ReflectionClass`/container `get`; Scala `Class.forName`/`given`/`implicit val`; Swift `NSClassFromString`/`Selector`/`#selector`/KVC; C function-pointer assignment + `dlopen`/`dlsym`; Luau `game:GetService`/`setmetatable __index`; Go `reflect.TypeOf`/`reflect.New`/`reflect.ValueOf`/`plugin.Open`/`plugin.Lookup`; Alpine.js `Alpine.data`/`store`/`magic`/`directive` registrations → handler files for JS)- For C# only: MSBuild project graph (`<ProjectReference>` / `<PackageReference>`), namespace → file mapping across projects, `global using` / `using static` / `using alias` propagation, ASP.NET HTTP and gRPC-dotnet contract extraction in workspace mode, cross-repo `<ProjectReference>` and internal-NuGet detection, host-builder extension method resolution (`app.MapCatalogApi()` / `services.AddCatalogServices()` on any C# repo, not just ASP.NET), `nameof(Type)` references resolved as dynamic uses, local `var x = new T()` property reads bound to the defining file, and CommunityToolkit MVVM source-generator synthesis (`[ObservableProperty]` fields → PascalCase property, `[RelayCommand]` methods → `<Name>Command`)- 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")))`); 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 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 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/constants.py b/packages/core/src/repowise/core/analysis/dead_code/constants.pyindex 7ae1e8406..b7b9986ea 100644--- a/packages/core/src/repowise/core/analysis/dead_code/constants.py+++ b/packages/core/src/repowise/core/analysis/dead_code/constants.py@@ -244,6 +244,44 @@ _NEVER_FLAG_PATTERNS: tuple[str, ...] = ("*_string.go","*zz_generated*.go","*bindata.go",+ # ---- JavaScript conventions ------------------------------------------+ # ``fnmatch`` ``*`` spans ``/`` (see the Go note above), so leading-``*``+ # suffix globs match nested asset paths too.+ # esbuild / rollup / webpack bundle outputs and minified artifacts are+ # build products served to the browser, not module-imported by name.+ "*.bundle.js",+ "*.min.js",+ "*.bundle.mjs",+ # LiveReload ships a generated browser-global script set (IIFE /+ # ``window.LiveReload =``) under ``livereload/gen/`` plus the+ # ``livereload.js`` shim — loaded via a ``<script>`` tag, never imported.+ "*/livereload/gen/*",+ "livereload/gen/*",+ "*/livereload/livereload.js",+ "livereload/livereload.js",+ # Hugo embeds a WASM toolchain whose JS glue under ``internal/warpc/js``+ # is shipped as a bundle and loaded by the Go side via ``go:embed``,+ # never by a JS importer.+ "*wasm_exec.js",+ # ---- Vendored / third-party C ----------------------------------------+ # A vendored C library (``deps/`` / ``vendor/`` / ``third_party/``) is a+ # self-contained unit: its structs/typedefs and functions are used within+ # the dependency's own translation units, not exported to the host repo+ # by a statement the graph sees. Flagging its internals as dead is noise —+ # the dependency is maintained upstream, not here. (Hugo's+ # ``internal/warpc/deps/parson`` JSON lib is the canonical case.)+ "*/deps/**/*.c",+ "*/deps/**/*.h",+ "deps/**/*.c",+ "deps/**/*.h",+ "*/vendor/**/*.c",+ "*/vendor/**/*.h",+ "vendor/**/*.c",+ "vendor/**/*.h",+ "*/third_party/**/*.c",+ "*/third_party/**/*.h",+ "third_party/**/*.c",+ "third_party/**/*.h",)# Decorator patterns that indicate framework usage (route handlers, fixtures, etc.)diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/alpine.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/alpine.pynew file mode 100644index 000000000..4d1fe9531--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/alpine.py@@ -0,0 +1,115 @@+"""Dynamic-hint extractor for Alpine.js component registration.++Why this exists+===============+Alpine.js wires components into the runtime by *value*, not by import::++ import explorer from './data/explorer.js'+ Alpine.data('explorer', explorer)+ Alpine.store('search', searchStore)+ Alpine.magic('clipboard', () => ...)+ Alpine.directive('tooltip', tooltipFn)++The registration names a string key and passes a JS identifier. The+module that *defines* ``explorer`` exports it solely to be handed to+``Alpine.data`` — there is no other importer that references the export+by name, so the defining file reads as unreachable and the exported+function reads as an unused export. (In Hugo this is the+``docs/assets/js/alpinejs/**`` cluster: ``explorer`` / ``search`` etc.)++Design+======+Pure two-pass regex scan, mirroring the Go reflect extractor+(:mod:`dynamic_hints.go`): first build an ``identifier → defining file``+map from top-level ``function`` / ``const`` / ``class`` declarations across+the repo's JS/TS files, then find every ``Alpine.<verb>('key', ident)``+registration and emit a ``dynamic_uses`` edge from the registering file to+the file that defines ``ident``. No JS parser is pulled in — the patterns+work on partial/minified sources and are cheap.++A name can be defined in more than one file (common for small helpers);+we emit to every definition. Over-emitting a use edge only ever rescues a+false dead-code finding — it never invents one — which is the safe+direction for this pass.+"""++from __future__ import annotations++import re+from pathlib import Path++from .base import DynamicEdge, DynamicHintExtractor++_SKIP_DIRS = {"node_modules", ".git", "dist", "build", ".next", "vendor"}+_JS_EXTS = (".js", ".mjs", ".cjs", ".ts")++# Alpine.data('explorer', explorer) / .store / .magic / .directive — capture+# the identifier passed as the second argument. An inline function/object+# literal (``Alpine.data('x', () => ...)``) has no identifier to resolve and+# is intentionally not matched.+_ALPINE_REGISTER_RE = re.compile(+ r"""Alpine\s*\.\s*(?:data|store|magic|directive)\s*\(\s*"""+ r"""['"][^'"]+['"]\s*,\s*([A-Za-z_$][\w$]*)""",+)++# Top-level definitions that a registration identifier can resolve to.+# ``export`` prefixes and ``default`` are tolerated.+_DEF_RES: tuple[re.Pattern[str], ...] = (+ re.compile(r"^\s*(?:export\s+)?(?:default\s+)?function\s+([A-Za-z_$][\w$]*)", re.MULTILINE),+ re.compile(r"^\s*(?:export\s+)?(?:default\s+)?class\s+([A-Za-z_$][\w$]*)", re.MULTILINE),+ re.compile(r"^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=", re.MULTILINE),+)+++class AlpineDynamicHints(DynamicHintExtractor):+ """Emit ``dynamic_uses`` edges from Alpine registrations to their handlers."""++ name = "alpine"++ def extract(self, repo_root: Path) -> list[DynamicEdge]:+ name_to_files: dict[str, list[str]] = {}+ sources: list[tuple[str, str]] = []+ repo_root_resolved = repo_root.resolve()++ for ext in _JS_EXTS:+ for src in self._rglob(repo_root, f"*{ext}"):+ try:+ rel_path = src.resolve().relative_to(repo_root_resolved)+ except ValueError:+ continue+ if any(part in _SKIP_DIRS for part in rel_path.parts):+ continue+ try:+ text = src.read_text(encoding="utf-8", errors="ignore")+ except OSError:+ continue+ rel = rel_path.as_posix()+ # Only files that actually register with Alpine are scanned for+ # registrations in pass 2, but every JS file is a candidate+ # *definition* site.+ sources.append((rel, text))+ for pattern in _DEF_RES:+ for match in pattern.finditer(text):+ name_to_files.setdefault(match.group(1), []).append(rel)++ if not name_to_files:+ return []++ edges: list[DynamicEdge] = []+ seen: set[tuple[str, str]] = set()+ for rel, text in sources:+ if "Alpine" not in text:+ continue+ for match in _ALPINE_REGISTER_RE.finditer(text):+ ident = match.group(1)+ for target in name_to_files.get(ident, ()):+ if target == rel or (rel, target) in seen:+ continue+ seen.add((rel, target))+ edges.append(DynamicEdge(+ source=rel,+ target=target,+ edge_type="dynamic_uses",+ hint_source=f"{self.name}:register",+ ))+ return edgesdiff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.pyindex 6b86a4348..fe198cbe6 100644--- a/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.py+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.py@@ -20,6 +20,7 @@ from pathlib import Pathimport structlog+from .alpine import AlpineDynamicHintsfrom .base import DynamicEdge, DynamicHintExtractorfrom .c import CDynamicHintsfrom .django import DjangoDynamicHints@@ -57,6 +58,7 @@ class HintRegistry:PytestDynamicHints(),PythonDynamicHints(),NodeDynamicHints(),+ AlpineDynamicHints(),DotNetDynamicHints(),XamlDynamicHints(),SpringDynamicHints(),diff --git a/packages/core/src/repowise/core/ingestion/extractors/visibility.py b/packages/core/src/repowise/core/ingestion/extractors/visibility.pyindex 92bcd863c..d2e62822e 100644--- a/packages/core/src/repowise/core/ingestion/extractors/visibility.py+++ b/packages/core/src/repowise/core/ingestion/extractors/visibility.py@@ -129,6 +129,20 @@ _CPP_EXPORT_MARKERS: tuple[str, ...] = ("__declspec( dllexport )",'visibility("default")',"visibility(\"default\")",+ # WebAssembly / emscripten / WASI export surfaces. A function compiled+ # to WASM and called across the JS<->WASM boundary carries one of these+ # markers; without them the export reads as an unused symbol because no+ # in-binary caller exists in the static graph (the caller is the host+ # runtime). ``EMSCRIPTEN_KEEPALIVE`` / ``WASM_EXPORT`` appear as a bare+ # macro token preceding the return type (parsed as the function's+ # leading ``type_identifier``); ``export_name(...)`` / ``used`` appear+ # inside an ``__attribute__((...))`` specifier — both are caught by the+ # leading-children scan in ``_has_export_marker``.+ "EMSCRIPTEN_KEEPALIVE",+ "WASM_EXPORT",+ "export_name(",+ "__attribute__((used))",+ "__attribute__((visibility(\"default\")))",)diff --git a/packages/core/src/repowise/core/ingestion/parser_helpers.py b/packages/core/src/repowise/core/ingestion/parser_helpers.pyindex d35b580bf..b5561b83f 100644--- a/packages/core/src/repowise/core/ingestion/parser_helpers.py+++ b/packages/core/src/repowise/core/ingestion/parser_helpers.py@@ -379,11 +379,91 @@ def _go_head_type_identifier(type_node: Node, src: str) -> str | None:return text+# ---------------------------------------------------------------------------+# C / C++ type-reference head extraction+# ---------------------------------------------------------------------------++# Predeclared / standard-library scalar types that never resolve to a+# user-defined struct, so they're dropped before the resolver lookup.+# ``primitive_type`` / ``sized_type_specifier`` nodes are filtered+# structurally below; this set catches the ``<stdint.h>`` / ``<stddef.h>``+# typedefs that the grammar surfaces as plain ``type_identifier`` nodes.+_C_BUILTIN_TYPES: frozenset[str] = frozenset(+ {+ "void", "char", "short", "int", "long", "float", "double",+ "signed", "unsigned", "bool", "_Bool", "_Complex",+ "size_t", "ssize_t", "rsize_t", "ptrdiff_t", "intptr_t", "uintptr_t",+ "int8_t", "int16_t", "int32_t", "int64_t",+ "uint8_t", "uint16_t", "uint32_t", "uint64_t",+ "intmax_t", "uintmax_t", "wchar_t", "wint_t", "char16_t", "char32_t",+ "va_list", "FILE",+ }+)+++def _c_head_type_identifier(type_node: Node, src: str) -> str | None:+ """Return the head type name of a C / C++ type expression, or None.++ In C the pointer / array shells wrap the *declarator*, not the type,+ so the captured ``type:`` field is the bare type node:++ ``JSON_Value`` → "JSON_Value"+ ``struct JSON_Object`` → "JSON_Object" (named struct ref)+ ``int`` / ``unsigned long`` → None (primitive)+ ``size_t`` → None (stdlib typedef)+ ``Acme::Widget`` (C++) → "Widget" (rightmost name)+ ``std::vector<T>`` (C++) → "vector" (template head)+ anonymous ``struct {...}`` → None+ """+ node: Node | None = type_node+ text = ""+ for _ in range(6):+ if node is None:+ return None+ kind = node.type+ if kind == "type_identifier":+ text = _node_text(node, src)+ break+ if kind in ("primitive_type", "sized_type_specifier"):+ return None+ if kind in ("struct_specifier", "union_specifier", "enum_specifier", "class_specifier"):+ name = node.child_by_field_name("name")+ if name is None:+ return None # anonymous aggregate — no named type to resolve+ text = _node_text(name, src)+ break+ if kind == "template_type":+ node = node.child_by_field_name("name")+ continue+ if kind == "qualified_identifier":+ # ``NS::Type`` — take the rightmost name component.+ name = node.child_by_field_name("name")+ node = name if name is not None else (+ node.named_children[-1] if node.named_children else None+ )+ continue+ # type_qualifier (const/volatile) wrappers and anything else:+ # descend into the first named child.+ node = node.named_children[0] if node.named_children else None+ else:+ return None++ if not text or (not text[0].isalpha() and text[0] != "_"):+ return None+ if text in _C_BUILTIN_TYPES:+ return None+ 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.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,}diff --git a/packages/core/src/repowise/core/ingestion/queries/c.scm b/packages/core/src/repowise/core/ingestion/queries/c.scmindex 158b5e12d..f598f2099 100644--- a/packages/core/src/repowise/core/ingestion/queries/c.scm+++ b/packages/core/src/repowise/core/ingestion/queries/c.scm@@ -96,3 +96,27 @@)arguments: (argument_list) @call.arguments) @call.site++; ---------------------------------------------------------------------------+; Type references — drive file-level ``type_use`` edges+; ---------------------------------------------------------------------------+; A struct / typedef declared in a header (``parson.h``) and used as a+; field / parameter / return type in a ``.c`` that ``#include``s it carries+; no import statement naming the type — only the ``#include`` of the header.+; Without these captures every header struct reads as an unused export. The+; shared ``@param.type`` capture name routes through the C head extractor+; (see parser_helpers.TYPE_HEAD_EXTRACTORS), which drops the pointer/array+; declarator wrapping (it lives on the declarator side in C, not the type)+; and filters primitive builtins. Mirrors the Go / C# captures.++; Parameter types: void f(JSON_Object *obj)+(parameter_declaration+ type: (_) @param.type)++; Struct / union field types: struct { JSON_Value *vals; }+(field_declaration+ type: (_) @param.type)++; Function return type: JSON_Value * json_parse(...)+(function_definition+ type: (_) @param.type)diff --git a/packages/core/src/repowise/core/ingestion/queries/cpp.scm b/packages/core/src/repowise/core/ingestion/queries/cpp.scmindex 3c7f26779..5cae658cd 100644--- a/packages/core/src/repowise/core/ingestion/queries/cpp.scm+++ b/packages/core/src/repowise/core/ingestion/queries/cpp.scm@@ -176,3 +176,26 @@)arguments: (argument_list) @call.arguments) @call.site++; ---------------------------------------------------------------------------+; Type references — drive file-level ``type_use`` edges+; ---------------------------------------------------------------------------+; A struct / class / typedef declared in a header and used as a field /+; parameter / return type in a translation unit that ``#include``s it+; carries no import statement naming the type — only the ``#include``.+; Without these captures every header type reads as an unused export. The+; shared ``@param.type`` capture name routes through the C head extractor+; (see parser_helpers.TYPE_HEAD_EXTRACTORS); pointer/array declarator+; wrapping lives on the declarator side, and primitive builtins are filtered.++; Parameter types: void f(Widget *w)+(parameter_declaration+ type: (_) @param.type)++; Struct / class field types+(field_declaration+ type: (_) @param.type)++; Function return type: Widget * make(...)+(function_definition+ type: (_) @param.type)diff --git a/packages/core/src/repowise/core/ingestion/resolvers/cpp.py b/packages/core/src/repowise/core/ingestion/resolvers/cpp.pyindex fb9ed326c..9cd63b69c 100644--- a/packages/core/src/repowise/core/ingestion/resolvers/cpp.py+++ b/packages/core/src/repowise/core/ingestion/resolvers/cpp.py@@ -2,6 +2,7 @@from __future__ import annotations+import posixpathfrom pathlib import Pathfrom .context import ResolverContext@@ -9,10 +10,22 @@ from .context import ResolverContextdef resolve_cpp_import(module_path: str, importer_path: str, ctx: ResolverContext) -> str | None:"""Resolve a C/C++ ``#include`` to a repo-relative file path."""- importer_dir = Path(importer_path).parentrepo_root = ctx.repo_path.resolve() if ctx.repo_path else None- # 1. Try compile_commands.json include paths+ # The graph builder passes ``importer_path`` as a *repo-relative* POSIX+ # path. Reduce it to its repo-relative directory; if a caller ever passes+ # an absolute path, fold it back under the repo root first so the+ # importer-relative join below stays repo-relative (and never resolves+ # against the process CWD).+ importer_rel = importer_path+ if repo_root and Path(importer_path).is_absolute():+ try:+ importer_rel = Path(importer_path).resolve().relative_to(repo_root).as_posix()+ except ValueError:+ importer_rel = Path(importer_path).as_posix()+ importer_dir = posixpath.dirname(Path(importer_rel).as_posix())++ # 1. Try compile_commands.json include paths (absolute on-disk dirs)for inc_dir in ctx.extract_include_dirs(importer_path):candidate = (Path(inc_dir) / module_path).resolve()if repo_root:@@ -23,14 +36,13 @@ def resolve_cpp_import(module_path: str, importer_path: str, ctx: ResolverContexexcept ValueError:pass- # 2. Try relative to the importer's directory- if repo_root:- try:- rel = (importer_dir / module_path).resolve().relative_to(repo_root).as_posix()- if rel in ctx.path_set:- return rel- except ValueError:- pass+ # 2. Relative to the importer's directory. ``importer_dir`` and the+ # ``#include`` target are both repo-relative, so normalise the join as a+ # plain POSIX path (collapsing ``..``/``.``) and test membership directly —+ # never touch the filesystem, which would resolve against the CWD.+ candidate_rel = posixpath.normpath(posixpath.join(importer_dir, module_path))+ if candidate_rel in ctx.path_set:+ return candidate_rel# 3. Stem-matching fallbackstem = Path(module_path).stem.lower()diff --git a/packages/core/src/repowise/core/ingestion/type_ref_resolution.py b/packages/core/src/repowise/core/ingestion/type_ref_resolution.pyindex 44f76dc9c..a027bdeea 100644--- a/packages/core/src/repowise/core/ingestion/type_ref_resolution.py+++ b/packages/core/src/repowise/core/ingestion/type_ref_resolution.py@@ -276,6 +276,80 @@ def _find_go_type_file(return None+# ---------------------------------------------------------------------------+# Strategy: C / C+++# ---------------------------------------------------------------------------++def _resolve_c_type_refs(+ parsed: ParsedFile,+ ctx: "ResolverContext",+ graph: "nx.DiGraph",+) -> int:+ """Resolve C / C++ ``@param.type`` captures via ``#include`` + stem map.++ A struct or typedef declared in a header and used as a field / param /+ return type in a ``.c`` that ``#include``s the header has no statement+ naming the type — the ``#include`` resolves to the header *file*, but+ the type itself never lands in ``imported_names``. This mirrors the Go+ type-ref strategy for ``.go`` and the Rust one for ``.rs``: resolve the+ bare type name against the files this translation unit includes, falling+ back to a unique global stem match, and emit a ``type_use`` edge so the+ unused-export pass sees the header type as used.+ """+ if not parsed.type_refs:+ return 0++ from .parser_helpers import _C_BUILTIN_TYPES++ from_path = parsed.file_info.path++ import_targets: set[str] = set()+ for imp in parsed.imports:+ if imp.resolved_file and not imp.resolved_file.startswith("external:"):+ import_targets.add(imp.resolved_file)++ emitted = 0+ seen_targets: set[tuple[str, str]] = set()+ for ref in parsed.type_refs:+ name = ref.type_name+ if not name or name in _C_BUILTIN_TYPES:+ continue+ target = _find_c_type_file(name, from_path, import_targets, ctx, graph)+ if target is None or target == from_path:+ continue+ if (name, target) in seen_targets:+ continue+ seen_targets.add((name, target))+ _add_or_merge_type_use_edge(graph, src=from_path, dst=target,+ type_name=name, origin=ref.origin)+ emitted += 1+ return emitted+++def _find_c_type_file(+ type_name: str,+ from_path: str,+ import_targets: set[str],+ ctx: "ResolverContext",+ graph: "nx.DiGraph",+) -> str | None:+ """Find the file defining *type_name*, preferring ``#include``d headers."""+ for imp_file in import_targets:+ if not graph.has_node(imp_file):+ continue+ for succ in graph.successors(imp_file):+ nd = graph.nodes.get(succ, {})+ if nd.get("node_type") == "symbol" and nd.get("name") == type_name:+ return imp_file++ candidates = ctx.stem_map.get(type_name.lower(), [])+ if len(candidates) == 1 and candidates[0] != from_path:+ if graph.has_node(candidates[0]):+ return candidates[0]++ return None++# ---------------------------------------------------------------------------# Strategy registry# ---------------------------------------------------------------------------@@ -289,6 +363,8 @@ _STRATEGIES: dict[str, Strategy] = {"csharp": _resolve_csharp_type_refs,"rust": _resolve_rust_type_refs,"go": _resolve_go_type_refs,+ "c": _resolve_c_type_refs,+ "cpp": _resolve_c_type_refs,}diff --git a/tests/unit/analysis/test_js_never_flag.py b/tests/unit/analysis/test_js_never_flag.pynew file mode 100644index 000000000..d0a26a80f--- /dev/null+++ b/tests/unit/analysis/test_js_never_flag.py@@ -0,0 +1,45 @@+"""Phase 5A — JavaScript never-flag patterns for embedded/built assets."""++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 TestJsNeverFlagPatterns:+ def test_bundle_outputs(self):+ assert _matches("internal/warpc/js/main.bundle.js")+ assert _matches("docs/assets/js/index.bundle.js")+ assert _matches("static/app.bundle.mjs")++ def test_minified(self):+ assert _matches("docs/static/js/vendor.min.js")++ def test_livereload_generated_and_shim(self):+ assert _matches("livereload/gen/Connector.js")+ assert _matches("transport/livereload/gen/Timer.js")+ assert _matches("livereload/livereload.js")++ def test_wasm_exec_glue(self):+ assert _matches("internal/warpc/js/wasm_exec.js")++ def test_ordinary_js_not_flagged(self):+ assert not _matches("docs/assets/js/explorer.js")+ assert not _matches("src/app.js")+++class TestVendoredCNeverFlag:+ def test_deps_vendor_third_party(self):+ assert _matches("internal/warpc/deps/parson/parson.c")+ assert _matches("internal/warpc/deps/parson/parson.h")+ assert _matches("vendor/json/json.c")+ assert _matches("third_party/lib/foo.h")++ def test_live_c_not_flagged(self):+ # Hand-written C outside a vendored dir must still be analysable.+ assert not _matches("internal/warpc/genavif/avif.c")+ assert not _matches("src/main.c")diff --git a/tests/unit/ingestion/test_alpine_dynamic_hints.py b/tests/unit/ingestion/test_alpine_dynamic_hints.pynew file mode 100644index 000000000..7eeb930f6--- /dev/null+++ b/tests/unit/ingestion/test_alpine_dynamic_hints.py@@ -0,0 +1,55 @@+"""Tests for the Alpine.js dynamic-hint extractor."""++from __future__ import annotations++from pathlib import Path++from repowise.core.ingestion.dynamic_hints.alpine import AlpineDynamicHints+++class TestAlpineDynamicHints:+ def test_resolves_data_registration_to_defining_file(self, tmp_path: Path) -> None:+ (tmp_path / "data").mkdir()+ (tmp_path / "data" / "explorer.js").write_text(+ "export default function explorer() { return {}; }\n"+ )+ (tmp_path / "index.js").write_text(+ "import explorer from './data/explorer.js'\n"+ "Alpine.data('explorer', explorer)\n"+ )+ edges = AlpineDynamicHints().extract(tmp_path)+ assert any(+ e.source == "index.js"+ and e.target == "data/explorer.js"+ and e.edge_type == "dynamic_uses"+ for e in edges+ )++ def test_resolves_store_magic_directive(self, tmp_path: Path) -> None:+ (tmp_path / "search.js").write_text("export const searchStore = {}\n")+ (tmp_path / "clip.js").write_text("function clipboard() {}\n")+ (tmp_path / "tip.js").write_text("const tooltip = () => {}\n")+ (tmp_path / "boot.js").write_text(+ "Alpine.store('search', searchStore)\n"+ "Alpine.magic('clipboard', clipboard)\n"+ "Alpine.directive('tooltip', tooltip)\n"+ )+ targets = {e.target for e in AlpineDynamicHints().extract(tmp_path)}+ assert {"search.js", "clip.js", "tip.js"} <= targets++ def test_inline_handler_emits_no_edge(self, tmp_path: Path) -> None:+ # An inline arrow/object literal has no identifier to resolve.+ (tmp_path / "x.js").write_text("Alpine.data('x', () => ({ open: false }))\n")+ assert AlpineDynamicHints().extract(tmp_path) == []++ def test_unknown_identifier_emits_no_edge(self, tmp_path: Path) -> None:+ # Registration references a symbol defined nowhere in the repo.+ (tmp_path / "x.js").write_text("Alpine.data('x', someExternal)\n")+ assert AlpineDynamicHints().extract(tmp_path) == []++ def test_skips_node_modules(self, tmp_path: Path) -> None:+ nm = tmp_path / "node_modules" / "pkg"+ nm.mkdir(parents=True)+ (nm / "thing.js").write_text("function thing() {}\n")+ (nm / "reg.js").write_text("Alpine.data('thing', thing)\n")+ assert AlpineDynamicHints().extract(tmp_path) == []diff --git a/tests/unit/ingestion/test_c_type_use.py b/tests/unit/ingestion/test_c_type_use.pynew file mode 100644index 000000000..a3166c583--- /dev/null+++ b/tests/unit/ingestion/test_c_type_use.py@@ -0,0 +1,165 @@+"""Phase 5B — C/C++ type-reference resolution + WASM export markers.++Covers the chain that stops Hugo's embedded C → WASM modules+(``internal/warpc/genavif``, ``deps/parson``) from reading as dead:++* ``@param.type`` capture → ``TypeReference`` extraction with the C head+ extractor (filters primitive builtins / stdlib typedefs, unwraps named+ ``struct``/``class`` specifiers, drops the ``NS::`` qualifier for C++);+* ``_resolve_c_type_refs`` → ``type_use`` edges for a header struct used+ only as a field / parameter / return type across a ``#include``;+* WASM / emscripten export markers (``EMSCRIPTEN_KEEPALIVE`` /+ ``__attribute__((export_name(...)))`` / ``WASM_EXPORT``) → the symbol is+ marked ``is_exported_symbol`` so the unused-export pass skips it;+* the honesty guard: a genuinely-dead ``static`` helper is still flagged.+"""++from __future__ import annotations++from datetime import datetime+from pathlib import Path++import networkx as nx++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) -> FileInfo:+ return FileInfo(+ path=path,+ abs_path=abs_path,+ language="c",+ size_bytes=100,+ git_hash="",+ last_modified=datetime.now(),+ is_test=False,+ is_config=False,+ is_api_contract=False,+ is_entry_point=False,+ )+++# A tiny vendored-C-style module: a header declaring structs, a .c that+# includes it and uses those structs as field/param/return types, plus a+# WASM-exported entry and a genuinely-dead static helper.+_SOURCES: dict[str, str] = {+ "parson.h": (+ "#ifndef PARSON_H\n#define PARSON_H\n"+ "typedef struct json_value_t JSON_Value;\n"+ "typedef struct json_object_t JSON_Object;\n"+ "struct json_object_t { JSON_Value *values; int count; };\n"+ "#endif\n"+ ),+ "parson.c": (+ '#include "parson.h"\n\n'+ "/* json_count uses JSON_Object as a param — reached only through the "+ "#include; it is itself genuinely unused (no caller, no export marker) "+ "and must stay flagged. */\n"+ "int json_count(JSON_Object *obj) { return obj->count; }\n"+ ),+ "avif.c": (+ '#include "parson.h"\n'+ "#define EMSCRIPTEN_KEEPALIVE __attribute__((used))\n\n"+ "/* exported across the WASM boundary — no in-binary caller. */\n"+ "EMSCRIPTEN_KEEPALIVE int avif_encode(JSON_Object *cfg) {\n"+ " return cfg->count;\n"+ "}\n"+ ),+}+++def _build_graph(repo: Path) -> 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()+++# ---------------------------------------------------------------------------+# Parser: C type-ref extraction + head unwrapping+# ---------------------------------------------------------------------------+++class TestCTypeRefExtraction:+ def _parse(self, body: str) -> list:+ info = _file_info("p/f.c", "/repo/p/f.c")+ return _PARSER.parse_file(info, body.encode("utf-8")).type_refs++ def test_struct_field_and_param_types_captured(self) -> None:+ refs = self._parse(+ 'struct Box { Widget *w; };\n'+ "int use(Gadget *g) { return 0; }\n"+ )+ names = {r.type_name for r in refs}+ assert {"Widget", "Gadget"} <= names++ def test_primitive_and_stdlib_builtins_filtered(self) -> None:+ refs = self._parse(+ "int f(int n, char *s, size_t len, unsigned long u) { return 0; }\n"+ )+ names = {r.type_name for r in refs}+ assert names.isdisjoint({"int", "char", "size_t", "unsigned", "long"})++ def test_named_struct_specifier_unwrapped(self) -> None:+ refs = self._parse("int f(struct Thing *t) { return 0; }\n")+ assert "Thing" in {r.type_name for r in refs}+++# ---------------------------------------------------------------------------+# type_use edges + WASM export markers (end-to-end through GraphBuilder)+# ---------------------------------------------------------------------------+++class TestCTypeUseEdges:+ def test_header_struct_used_across_include(self, tmp_path: Path) -> None:+ graph = _build_graph(tmp_path)+ # parson.c references JSON_Object (defined in parson.h) as a param.+ edge = graph.get_edge_data("parson.c", "parson.h", {})+ assert "JSON_Object" in edge.get("imported_names", [])+++class TestWasmExportMarkers:+ def test_emscripten_keepalive_marks_exported(self, tmp_path: Path) -> None:+ graph = _build_graph(tmp_path)+ node = graph.nodes.get("avif.c::avif_encode")+ assert node is not None, "avif_encode symbol should be in the graph"+ assert node.get("is_exported_symbol") is True+++# ---------------------------------------------------------------------------+# Honesty guard — genuinely-dead code must still surface+# ---------------------------------------------------------------------------+++class TestHonestyGuard:+ def test_genuinely_unused_export_still_flagged(self, tmp_path: Path) -> None:+ # json_count carries no export marker and has no caller — the+ # WASM-marker work must not silence ordinary dead exports.+ graph = _build_graph(tmp_path)+ findings = DeadCodeAnalyzer(graph).analyze().findings+ dead_exports = {+ f.symbol_name+ for f in findings+ if f.kind == DeadCodeKind.UNUSED_EXPORT+ }+ assert "json_count" in dead_exports++ def test_exported_wasm_fn_not_flagged(self, tmp_path: Path) -> None:+ # avif_encode carries EMSCRIPTEN_KEEPALIVE → exported across the WASM+ # boundary → must NOT be flagged despite having no in-binary caller.+ graph = _build_graph(tmp_path)+ findings = DeadCodeAnalyzer(graph).analyze().findings+ flagged = {f.symbol_name for f in findings}+ assert "avif_encode" not in flagged