Skip to content

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

feat(framework-edges): TYPO3 convention-file awareness (#114)

Sebastian Mendelb4be9138b195
diff --git a/README.md b/README.md
index 5430c39ea..693511519 100644
--- a/README.md
+++ b/README.md
@@ -402,7 +402,7 @@ repowise dead-code
✗ analytics/v1/tracker.ts file 0.41 recent activity — review first
```
-Conservative by design. `safe_to_delete` requires confidence ≥ 0.70 and excludes dynamically-loaded patterns (`*Plugin`, `*Handler`, `*Adapter`, `*Middleware`). Dynamic import detection (`importlib.import_module()`, `__import__()`) and framework decorator awareness (Flask/FastAPI/Django routes) further reduce false positives. repowise surfaces candidates. Engineers decide.
+Conservative by design. `safe_to_delete` requires confidence ≥ 0.70 and excludes dynamically-loaded patterns (`*Plugin`, `*Handler`, `*Adapter`, `*Middleware`). Dynamic import detection (`importlib.import_module()`, `__import__()`) and framework awareness (Flask/FastAPI/Django/Rails/Laravel/TYPO3 routes and convention files) further reduce false positives. repowise surfaces candidates. Engineers decide.
---
@@ -549,7 +549,7 @@ repowise reindex # rebuild vector store (no LLM calls)
| Tier | Languages | What works |
|------|-----------|------------|
| **Full** | Python · TypeScript · JavaScript · Java · Go · Rust · C++ · C# | AST parsing, import resolution, named bindings, call resolution, heritage extraction, docstrings; multi-project workspace resolvers (`.csproj`/`.sln` for C#, `Cargo.toml [workspace]` for Rust, `go.mod` multi-module, `package.json` workspaces, etc.); framework-aware edges (Django, FastAPI, Flask, ASP.NET, Spring Boot, Express/NestJS, Gin/Echo/Chi, Axum/Actix); per-language dynamic-hint extractors for runtime-resolved DI / reflection / plugins |
-| **Good** | C · Kotlin · Ruby · Swift · Scala · PHP | AST parsing, import resolution, named bindings, call resolution, heritage (mixins, derive, extensions, traits), docstrings, dedicated workspace-aware resolvers (Gradle subprojects, Rails / Zeitwerk, SPM, SBT/Mill, composer PSR-4); Rails / Laravel framework edges for Ruby and PHP; per-language dynamic-hint extractors |
+| **Good** | C · Kotlin · Ruby · Swift · Scala · PHP | AST parsing, import resolution, named bindings, call resolution, heritage (mixins, derive, extensions, traits), docstrings, dedicated workspace-aware resolvers (Gradle subprojects, Rails / Zeitwerk, SPM, SBT/Mill, composer PSR-4); Rails / Laravel / TYPO3 framework edges for Ruby and PHP; per-language dynamic-hint extractors |
| **Config / data** | OpenAPI · Protobuf · GraphQL · Dockerfile · Makefile · YAML · JSON · TOML · SQL · Terraform | Included in the file tree; special handlers extract endpoints/targets where applicable |
14 languages with full AST support, 8 of them at the Full tier. Adding a new language requires one `.scm` tree-sitter query file and one config entry. No changes to the parser core. See [Language Support](docs/LANGUAGE_SUPPORT.md) for details.
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 7c6ebd123..c6e8be731 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -74,6 +74,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **Spring Boot (Java/Kotlin)** — `@Component`/`@Service`/`@Repository`/`@Controller`/`@RestController`/`@Configuration` bean classes wire to their injection sites via `@Autowired` field/constructor analysis. Interface-typed dependencies fall back to `parsed.heritage` to find implementing classes. `@Bean` factory methods in `@Configuration` classes link to their return-type files.
- **Rails (Ruby)** — `config/routes.rb` is line-walked with namespace-stack tracking: `resources :users`, `get "/foo", to: "users#index"`, and nested `namespace :admin do … end` all resolve to controller files via the Zeitwerk autoload index. ActiveRecord `belongs_to`/`has_many`/`has_one` relationships link model files (with simple inflector-style singularisation).
- **Laravel (PHP)** — `routes/web.php` and `routes/api.php` parse modern `[Foo::class, 'method']` and legacy `'Foo@method'` syntaxes, plus `Route::resource`. Service-provider `bind`/`singleton`/`instance` calls link providers to bound classes. Eloquent `hasMany`/`belongsTo`/`hasOne` link models. Class resolution uses the composer PSR-4 map first, falling back to stem.
+- **TYPO3 (PHP)** — extension discovery via `composer.json` `"type": "typo3-cms-extension"` (canonical for v11–v14) with legacy fallback to `ext_emconf.php`; project-mode (`vendor/<vendor>/<pkg>/composer.json`) is also walked. Convention-loaded files (`ext_localconf.php`, `ext_emconf.php`, `ext_tables.sql`, `Configuration/TCA/*.php`, `Configuration/Backend/*.php`, `Configuration/JavaScriptModules.php`, `Configuration/ContentSecurityPolicies.php`, `Configuration/RequestMiddlewares.php`, `Configuration/Services.php`, `Configuration/Icons.php`) get incoming edges from a synthetic `framework:typo3-core` anchor, so they are no longer flagged as unreachable. `Configuration/JavaScriptModules.php` is parsed for `EXT:<key>/...js` references and edges are added to the registered JS modules. `tech_stack.detect_tech_stack` recognises `typo3/cms-core` and `symfony/framework-bundle` / `laravel/framework` from `composer.json`.
+- **`framework:` synthetic-node prefix in dead-code analysis** — distinguishes framework-mediated wiring from third-party `external:` imports. `framework:` predecessors *do* count as cross-package importers (preventing legitimate convention dirs like `Configuration/` from showing up as zombie packages); `external:` predecessors do not.
+- **`repowise dead-code` now invokes `add_framework_edges`** — the CLI previously skipped framework-aware edge synthesis, so even Django/Laravel/Rails repos showed false positives. The dead-code command now calls `detect_tech_stack` and adds framework edges before running the analyzer.
- **Express / NestJS (TS/JS)** — Express `app.use(routerVar)` mirrors the FastAPI router-var pattern (resolves imported names ending in `Router`/`router` to source file). NestJS `@Module({ controllers: [...], providers: [...], imports: [...] })` arrays parse into module → target edges using a class-name → file map.
- **Gin / Echo / Chi (Go)** — `r.GET("/p", users.Index)` style handler references resolve via the Go import list (using the multi-module resolver) for package-qualified handlers, or via a function-name → file map for receiver methods. Lambda handlers are accepted as missed.
- **Axum / Actix (Rust)** — Axum `Router::new().route("/p", get(handler))`, Actix `web::resource("/p").route(web::get().to(handler))` / `.service(handler)` / `.configure(routes::register)` all resolve to handler files via a function-name → file map.
diff --git a/docs/LANGUAGE_SUPPORT.md b/docs/LANGUAGE_SUPPORT.md
index 85cf08ab0..3dd6cf714 100644
--- a/docs/LANGUAGE_SUPPORT.md
+++ b/docs/LANGUAGE_SUPPORT.md
@@ -50,7 +50,7 @@ All eight languages support:
- Named binding extraction (mapping imported names to source symbols)
- 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; Express `app.use(router)` + NestJS `@Module` arrays; Gin/Echo/Chi router → handler files for Go; Axum/Actix `.route` → handler files for Rust)
+- 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 → handler files for Go; Axum/Actix `.route` → handler files for Rust)
- Per-language dynamic-hint extractors (Django/Pytest/Node 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`/`plugin.Open`/`plugin.Lookup`)
- 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
@@ -315,7 +315,7 @@ ingestion/
scala.py # package-to-directory mapping
php.py # namespace/PSR-4 resolution
generic.py # stem-matching fallback
- framework_edges.py # Django, FastAPI, Flask, pytest, ASP.NET detection
+ framework_edges.py # Django, FastAPI, Flask, pytest, ASP.NET, Rails, Laravel, TYPO3, Spring, Express, Gin, Axum detection
dynamic_hints/ # Per-language dynamic-edge extractors
base.py # DynamicHintExtractor + DynamicEdge
registry.py # HintRegistry
diff --git a/packages/cli/src/repowise/cli/commands/dead_code_cmd.py b/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
index e196cfded..2a9981c3e 100644
--- a/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
@@ -90,6 +90,17 @@ def dead_code_command(
pass
graph_builder.build()
+ # Framework-aware synthetic edges (Django, Laravel, TYPO3, ...). Without
+ # this, convention-loaded files appear as in_degree=0 unreachable — false
+ # positives in the dead-code report.
+ try:
+ from repowise.core.generation.editor_files.tech_stack import detect_tech_stack
+
+ tech_items = detect_tech_stack(repo_path)
+ graph_builder.add_framework_edges([item.name for item in tech_items])
+ except Exception:
+ pass
+
# Git metadata (best effort)
git_meta_map: dict = {}
try:
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
index 9d3ff039d..86af0bf69 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -31,6 +31,22 @@ from .models import DeadCodeFindingData, DeadCodeKind, DeadCodeReport
logger = structlog.get_logger(__name__)
+def _is_synthetic_node(node: str) -> bool:
+ """True for non-file graph nodes that should be skipped in 'is this dead?' passes.
+
+ Two synthetic prefixes exist:
+ - ``external:`` — third-party / unresolved imports.
+ - ``framework:`` — anchors added by ``framework_edges`` to model
+ convention-based loading (e.g. TYPO3 core loading ``ext_localconf.php``).
+
+ Both are skipped when the analyzer asks "is this node itself dead?",
+ but they are treated differently in the zombie-package pass: ``framework:``
+ predecessors *do* count as cross-package importers (real framework-
+ mediated dependencies), whereas ``external:`` predecessors do not.
+ """
+ return node.startswith("external:") or node.startswith("framework:")
+
+
class DeadCodeAnalyzer:
"""Detects unreachable files, unused exports, unused internals, and
zombie packages using the dependency graph and git metadata.
@@ -148,7 +164,7 @@ class DeadCodeAnalyzer:
findings = []
for node in self.graph.nodes():
- if str(node).startswith("external:"):
+ if _is_synthetic_node(str(node)):
continue
node_data = self.graph.nodes[node]
@@ -246,7 +262,7 @@ class DeadCodeAnalyzer:
findings = []
for node in self.graph.nodes():
- if str(node).startswith("external:"):
+ if _is_synthetic_node(str(node)):
continue
node_data = self.graph.nodes[node]
@@ -399,12 +415,18 @@ class DeadCodeAnalyzer:
return findings
def _detect_zombie_packages(self, whitelist: set[str]) -> list[DeadCodeFindingData]:
- """Detect monorepo packages with no incoming inter_package edges."""
+ """Detect monorepo packages with no incoming inter_package edges.
+
+ ``framework:`` predecessors (synthetic anchors added by
+ ``framework_edges``) count as cross-package importers — TYPO3 / Django
+ / etc. wiring is a real cross-cutting dependency. ``external:``
+ predecessors do not count (they represent third-party imports).
+ """
findings = []
packages: dict[str, list[str]] = {}
for node in self.graph.nodes():
- if str(node).startswith("external:"):
+ if _is_synthetic_node(str(node)):
continue
parts = Path(str(node)).parts
if len(parts) > 1:
@@ -423,6 +445,8 @@ class DeadCodeAnalyzer:
for pred in self.graph.predecessors(f):
pred_str = str(pred)
if pred_str.startswith("external:"):
+ # Third-party imports don't count as cross-package
+ # importers; framework: synthetic anchors do.
continue
pred_parts = Path(pred_str).parts
if len(pred_parts) > 0 and pred_parts[0] != pkg:
diff --git a/packages/core/src/repowise/core/generation/editor_files/tech_stack.py b/packages/core/src/repowise/core/generation/editor_files/tech_stack.py
index 7039749e0..a8e5f7805 100644
--- a/packages/core/src/repowise/core/generation/editor_files/tech_stack.py
+++ b/packages/core/src/repowise/core/generation/editor_files/tech_stack.py
@@ -119,8 +119,27 @@ def detect_tech_stack(repo_path: Path) -> list[TechStackItem]:
add("Ruby", None, "language")
# --- composer.json (PHP) ---
- if (repo_path / "composer.json").exists():
+ composer_json = repo_path / "composer.json"
+ if composer_json.exists():
add("PHP", None, "language")
+ try:
+ composer = json.loads(composer_json.read_text(encoding="utf-8"))
+ except Exception:
+ composer = None
+ if isinstance(composer, dict):
+ requires = {
+ **(composer.get("require") or {}),
+ **(composer.get("require-dev") or {}),
+ }
+ if (
+ composer.get("type") == "typo3-cms-extension"
+ or "typo3/cms-core" in requires
+ ):
+ add("TYPO3", None, "framework")
+ elif "symfony/framework-bundle" in requires or "symfony/symfony" in requires:
+ add("Symfony", None, "framework")
+ elif "laravel/framework" in requires:
+ add("Laravel", None, "framework")
# --- Docker ---
if (repo_path / "Dockerfile").exists():
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges.py b/packages/core/src/repowise/core/ingestion/framework_edges.py
index bc1cfbc9a..632d8ad94 100644
--- a/packages/core/src/repowise/core/ingestion/framework_edges.py
+++ b/packages/core/src/repowise/core/ingestion/framework_edges.py
@@ -6,6 +6,8 @@ convention-based relationships and adds ``edge_type="framework"`` edges.
from __future__ import annotations
+import fnmatch
+import json
import re
from pathlib import Path
from typing import TYPE_CHECKING, Any
@@ -83,6 +85,11 @@ def add_framework_edges(
if rust_router_in_stack or _has_rust_router_imports(parsed_files):
count += _add_rust_router_edges(graph, parsed_files, path_set)
+ # TYPO3: detect via composer.json `"type": "typo3-cms-extension"` or any
+ # `ext_emconf.php` (legacy fallback for non-composer installs).
+ if "typo3" in stack_lower or _has_typo3_extension(ctx, path_set):
+ count += _add_typo3_edges(graph, parsed_files, ctx, path_set)
+
return count
@@ -964,3 +971,287 @@ def _add_rust_router_edges(
count += 1
return count
+
+
+# ---------------------------------------------------------------------------
+# F8 — TYPO3 framework edges
+#
+# TYPO3 loads a fixed set of convention-named files from each extension at
+# bootstrap (``ext_localconf.php``, ``Configuration/TCA/*.php``, etc.). These
+# files are never imported via PHP/JS imports, so the static graph reports
+# ``in_degree=0`` and the dead-code analyzer flags them as unreachable.
+#
+# We attach an ``external:typo3-core`` synthetic source to each convention
+# file present in an extension. ``Configuration/JavaScriptModules.php`` is
+# also parsed to add edges to the JS modules it registers (CKEditor plugins,
+# backend modules, etc.).
+#
+# Discovery signal: ``composer.json`` with ``"type": "typo3-cms-extension"``
+# (canonical for v11-v14) or, as fallback, any ``ext_emconf.php`` (legacy
+# non-composer installs).
+# ---------------------------------------------------------------------------
+
+_TYPO3_EXTERNAL_NODE = "framework:typo3-core"
+
+# Convention files at the extension root (matched by basename).
+_TYPO3_ROOT_FILES: tuple[str, ...] = (
+ "ext_localconf.php",
+ "ext_emconf.php",
+ "ext_tables.php", # legacy v11-v13; absent in v14
+ "ext_tables.sql",
+)
+
+# Convention files / globs under ``Configuration/`` (matched relative to the
+# extension root, with forward-slash separators).
+_TYPO3_CONFIG_GLOBS: tuple[str, ...] = (
+ "Configuration/JavaScriptModules.php",
+ "Configuration/ContentSecurityPolicies.php",
+ "Configuration/RequestMiddlewares.php",
+ "Configuration/Icons.php",
+ "Configuration/Services.php",
+ "Configuration/Services.yaml",
+ "Configuration/Services.yml",
+ "Configuration/TCA/*.php",
+ "Configuration/TCA/Overrides/*.php",
+ "Configuration/Backend/*.php",
+ "Configuration/RTE/*.yaml",
+ "Configuration/RTE/*.yml",
+)
+
+# JavaScriptModules.php registers JS files via entries like
+# ``'@vendor/ext/MyModule' => 'EXT:ext_key/Resources/Public/JavaScript/My.js'``.
+# We extract the right-hand value to add edges to the registered files.
+_TYPO3_JS_MODULE_VALUE_RE = re.compile(
+ r"""['"]EXT:(?P<ext>[a-z0-9_]+)/(?P<rel>[^'"]+\.(?:js|mjs))['"]""",
+ re.IGNORECASE,
+)
+
+
+def _has_typo3_extension(ctx: ResolverContext, path_set: set[str]) -> bool:
+ """Return True if the repo contains at least one TYPO3 extension.
+
+ Checks ``composer.json`` ``type`` field first (canonical across v11-v14);
+ falls back to any ``ext_emconf.php`` in path_set for legacy installs.
+ """
+ return bool(_find_typo3_extension_roots(ctx, path_set))
+
+
+def _find_typo3_extension_roots(
+ ctx: ResolverContext, path_set: set[str]
+) -> set[str]:
+ """Return the set of extension root directories (repo-relative, posix).
+
+ Sources, in order of authority:
+ 1. Any ``composer.json`` with ``"type": "typo3-cms-extension"``.
+ 2. Any ``ext_emconf.php`` (legacy fallback when composer.json is missing).
+ """
+ roots: set[str] = set()
+
+ # 1. composer.json based discovery — walk the filesystem from repo root,
+ # bounded depth to avoid deep vendor/node_modules traversal during tests.
+ repo_path = getattr(ctx, "repo_path", None)
+ if repo_path is not None:
+ try:
+ for composer in _iter_composer_jsons(Path(repo_path)):
+ try:
+ data = json.loads(composer.read_text(encoding="utf-8", errors="ignore"))
+ except (OSError, ValueError):
+ continue
+ if not isinstance(data, dict):
+ continue
+ if data.get("type") != "typo3-cms-extension":
+ continue
+ ext_root = composer.parent.resolve()
+ rel = _to_repo_relative(repo_path, ext_root)
+ if rel is not None:
+ roots.add(rel)
+ except OSError:
+ pass
+
+ # 2. ext_emconf.php fallback for repos without a composer.json (legacy
+ # non-composer installs, mostly v11 and earlier).
+ for p in path_set:
+ if Path(p).name == "ext_emconf.php":
+ parent = Path(p).parent.as_posix()
+ roots.add("" if parent == "." else parent)
+
+ return roots
+
+
+def _iter_composer_jsons(root: Path):
+ """Yield composer.json paths likely to declare a TYPO3 extension.
+
+ Searched locations:
+ - ``<root>/composer.json``
+ - ``<root>/<dir>/composer.json`` (single-level, for monorepos of extensions)
+ - ``<root>/vendor/<vendor>/<package>/composer.json`` (project-mode TYPO3
+ installs where extensions live under ``vendor/``)
+
+ ``node_modules``, ``.git``, ``.bare``, and ``Build`` are skipped. Hidden
+ directories are skipped at the top level only — vendor packages keep their
+ nested layout.
+ """
+ skip_top = {"node_modules", ".git", ".bare", "var", "Build"}
+ if (root / "composer.json").is_file():
+ yield root / "composer.json"
+
+ try:
+ children = list(root.iterdir())
+ except OSError:
+ return
+
+ for child in children:
+ if not child.is_dir():
+ continue
+ if child.name == "vendor":
+ yield from _iter_vendor_composer_jsons(child)
+ continue
+ if child.name in skip_top or child.name.startswith("."):
+ continue
+ candidate = child / "composer.json"
+ if candidate.is_file():
+ yield candidate
+
+
+def _iter_vendor_composer_jsons(vendor_root: Path):
+ """Yield composer.json files at ``vendor/<vendor>/<package>/composer.json``.
+
+ Bounded to two levels deep — composer's flat layout means we never need
+ to recurse further. Symlinks are followed at most once.
+ """
+ try:
+ vendors = list(vendor_root.iterdir())
+ except OSError:
+ return
+ for vendor_dir in vendors:
+ if not vendor_dir.is_dir() or vendor_dir.name.startswith("."):
+ continue
+ try:
+ packages = list(vendor_dir.iterdir())
+ except OSError:
+ continue
+ for pkg_dir in packages:
+ if not pkg_dir.is_dir() or pkg_dir.name.startswith("."):
+ continue
+ candidate = pkg_dir / "composer.json"
+ if candidate.is_file():
+ yield candidate
+
+
+def _to_repo_relative(repo_path: Path, abs_path: Path) -> str | None:
+ try:
+ rel = abs_path.relative_to(Path(repo_path).resolve()).as_posix()
+ except ValueError:
+ return None
+ return "" if rel == "." else rel
+
+
+def _add_typo3_edges(
+ graph: nx.DiGraph,
+ parsed_files: dict[str, Any],
+ ctx: ResolverContext,
+ path_set: set[str],
+) -> int:
+ """Add framework edges for each detected TYPO3 extension.
+
+ Edges added:
+ - ``external:typo3-core`` → each convention file present in the extension.
+ - ``Configuration/JavaScriptModules.php`` → each JS file it registers.
+ """
+ count = 0
+ roots = _find_typo3_extension_roots(ctx, path_set)
+ if not roots:
+ return 0
+
+ if _TYPO3_EXTERNAL_NODE not in graph:
+ graph.add_node(_TYPO3_EXTERNAL_NODE, language="external")
+
+ for root in roots:
+ for basename in _TYPO3_ROOT_FILES:
+ target = f"{root}/{basename}" if root else basename
+ if target in path_set and _add_edge_if_new(graph, _TYPO3_EXTERNAL_NODE, target):
+ count += 1
+
+ for glob in _TYPO3_CONFIG_GLOBS:
+ prefix = f"{root}/" if root else ""
+ pat = f"{prefix}{glob}"
+ for p in path_set:
+ if fnmatch.fnmatch(p, pat) and _add_edge_if_new(graph, _TYPO3_EXTERNAL_NODE, p):
+ count += 1
+
+ # Parse JavaScriptModules.php for registered JS files.
+ js_modules_path = f"{root}/Configuration/JavaScriptModules.php" if root else "Configuration/JavaScriptModules.php"
+ if js_modules_path in path_set:
+ count += _add_typo3_js_module_edges(
+ graph, parsed_files, path_set, root, js_modules_path
+ )
+
+ return count
+
+
+def _add_typo3_js_module_edges(
+ graph: nx.DiGraph,
+ parsed_files: dict[str, Any],
+ path_set: set[str],
+ ext_root: str,
+ js_modules_path: str,
+) -> int:
+ """Parse JavaScriptModules.php and add edges to each registered JS file.
+
+ Resolves ``EXT:<ext_key>/<rel>`` to a repo-relative path under ``ext_root``
+ when the extension is local; cross-extension references are ignored.
+ """
+ parsed = parsed_files.get(js_modules_path)
+ if parsed is None:
+ return 0
+ text = _read_text(parsed)
+ if not text:
+ return 0
+
+ own_ext_key = _extract_ext_key_from_composer(parsed_files, ext_root)
+
+ count = 0
+ for m in _TYPO3_JS_MODULE_VALUE_RE.finditer(text):
+ ext_key = m.group("ext").lower()
+ rel = m.group("rel")
+ if own_ext_key is not None and ext_key != own_ext_key:
+ continue
+ target = f"{ext_root}/{rel}" if ext_root else rel
+ if target in path_set and _add_edge_if_new(graph, js_modules_path, target):
+ count += 1
+ return count
+
+
+def _extract_ext_key_from_composer(
+ parsed_files: dict[str, Any], ext_root: str
+) -> str | None:
+ """Best-effort extraction of the TYPO3 extension key from composer.json.
+
+ Reads ``extra.typo3/cms.extension-key`` first (canonical), falls back to
+ deriving the key from the package name (``vendor/ext-key`` → ``ext_key``).
+ Returns ``None`` if composer.json is missing or unreadable.
+ """
+ composer_path = f"{ext_root}/composer.json" if ext_root else "composer.json"
+ parsed = parsed_files.get(composer_path)
+ abs_path: Path | None = None
+ if parsed is not None:
+ abs_path = Path(parsed.file_info.abs_path)
+ if abs_path is None or not abs_path.is_file():
+ return None
+ try:
+ data = json.loads(abs_path.read_text(encoding="utf-8", errors="ignore"))
+ except (OSError, ValueError):
+ return None
+ if not isinstance(data, dict):
+ return None
+ extra_raw = data.get("extra")
+ extra: dict[str, Any] = extra_raw if isinstance(extra_raw, dict) else {}
+ typo3_raw = extra.get("typo3/cms")
+ typo3: dict[str, Any] = typo3_raw if isinstance(typo3_raw, dict) else {}
+ key = typo3.get("extension-key")
+ if isinstance(key, str) and key:
+ return key.lower()
+ name = data.get("name")
+ if isinstance(name, str) and "/" in name:
+ return name.split("/", 1)[1].replace("-", "_").lower()
+ return None
diff --git a/tests/unit/generation/test_tech_stack.py b/tests/unit/generation/test_tech_stack.py
index 493132298..364438ddc 100644
--- a/tests/unit/generation/test_tech_stack.py
+++ b/tests/unit/generation/test_tech_stack.py
@@ -118,6 +118,83 @@ def test_detects_pytest_from_pyproject(tmp_path):
assert "pytest" in cmds["test"]
+def test_detects_typo3_from_composer_type(tmp_path):
+ composer = {
+ "name": "vendor/my-ext",
+ "type": "typo3-cms-extension",
+ "require": {"typo3/cms-core": "^13.4"},
+ }
+ (tmp_path / "composer.json").write_text(json.dumps(composer), encoding="utf-8")
+ items = detect_tech_stack(tmp_path)
+ names = [i.name for i in items]
+ assert "PHP" in names
+ assert "TYPO3" in names
+
+
+def test_detects_typo3_from_cms_core_require(tmp_path):
+ # Project-mode install: composer.json without `type` but requires typo3/cms-core.
+ composer = {
+ "name": "vendor/my-site",
+ "type": "project",
+ "require": {"typo3/cms-core": "^13.4", "typo3/cms-backend": "^13.4"},
+ }
+ (tmp_path / "composer.json").write_text(json.dumps(composer), encoding="utf-8")
+ names = [i.name for i in detect_tech_stack(tmp_path)]
+ assert "TYPO3" in names
+
+
+def test_detects_symfony_from_framework_bundle(tmp_path):
+ composer = {
+ "name": "vendor/app",
+ "require": {"symfony/framework-bundle": "^7.0"},
+ }
+ (tmp_path / "composer.json").write_text(json.dumps(composer), encoding="utf-8")
+ names = [i.name for i in detect_tech_stack(tmp_path)]
+ assert "PHP" in names
+ assert "Symfony" in names
+
+
+def test_detects_laravel_from_framework_require(tmp_path):
+ composer = {
+ "name": "vendor/app",
+ "require": {"laravel/framework": "^11.0"},
+ }
+ (tmp_path / "composer.json").write_text(json.dumps(composer), encoding="utf-8")
+ names = [i.name for i in detect_tech_stack(tmp_path)]
+ assert "Laravel" in names
+
+
+def test_typo3_takes_precedence_over_symfony_when_both_match(tmp_path):
+ # TYPO3 ships Symfony — extension should still be classified as TYPO3.
+ composer = {
+ "name": "vendor/my-ext",
+ "type": "typo3-cms-extension",
+ "require": {
+ "typo3/cms-core": "^13.4",
+ "symfony/framework-bundle": "*",
+ },
+ }
+ (tmp_path / "composer.json").write_text(json.dumps(composer), encoding="utf-8")
+ names = [i.name for i in detect_tech_stack(tmp_path)]
+ assert "TYPO3" in names
+ assert "Symfony" not in names
+
+
+def test_plain_php_library_does_not_match_any_framework(tmp_path):
+ composer = {"name": "vendor/lib", "type": "library", "require": {"psr/log": "^3.0"}}
+ (tmp_path / "composer.json").write_text(json.dumps(composer), encoding="utf-8")
+ names = [i.name for i in detect_tech_stack(tmp_path)]
+ assert "PHP" in names
+ for fw in ("TYPO3", "Symfony", "Laravel"):
+ assert fw not in names
+
+
+def test_malformed_composer_does_not_crash(tmp_path):
+ (tmp_path / "composer.json").write_text("{ not valid json", encoding="utf-8")
+ names = [i.name for i in detect_tech_stack(tmp_path)]
+ assert "PHP" in names # PHP language still added (file existed)
+
+
def test_detects_ruff_from_pyproject(tmp_path):
(tmp_path / "pyproject.toml").write_text("[tool.ruff]\nline-length = 88\n", encoding="utf-8")
cmds = detect_build_commands(tmp_path)
diff --git a/tests/unit/ingestion/test_typo3_framework_edges.py b/tests/unit/ingestion/test_typo3_framework_edges.py
new file mode 100644
index 000000000..6683256db
--- /dev/null
+++ b/tests/unit/ingestion/test_typo3_framework_edges.py
@@ -0,0 +1,347 @@
+"""Unit tests for TYPO3 framework edges (F8)."""
+
+from __future__ import annotations
+
+import json
+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 = "php") -> 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 ext, lang in (
+ (".php", "php"),
+ (".js", "javascript"),
+ (".yaml", "yaml"),
+ (".yml", "yaml"),
+ ):
+ for src in repo.rglob(f"*{ext}"):
+ rel = src.resolve().relative_to(repo.resolve()).as_posix()
+ if "/.git/" in f"/{rel}/":
+ continue
+ fi = _file_info(rel, str(src.resolve()), language=lang)
+ out[rel] = parser.parse_file(fi, 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
+ )
+
+
+def _graph_with_nodes(parsed: dict[str, ParsedFile]) -> nx.DiGraph:
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p, language=parsed[p].file_info.language)
+ return graph
+
+
+def _make_extension(
+ repo: Path,
+ *,
+ composer_type: bool = True,
+ extension_key: str = "my_ext",
+ files: dict[str, str] | None = None,
+) -> None:
+ """Lay down a minimal TYPO3 extension at repo root."""
+ if composer_type:
+ composer = {
+ "name": f"vendor/{extension_key.replace('_', '-')}",
+ "type": "typo3-cms-extension",
+ "require": {"typo3/cms-core": "^13.4"},
+ "extra": {"typo3/cms": {"extension-key": extension_key}},
+ }
+ (repo / "composer.json").write_text(json.dumps(composer))
+ if files:
+ for rel, content in files.items():
+ target = repo / rel
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(content)
+
+
+class TestTypo3Detection:
+ def test_composer_type_detects_extension(self, tmp_path: Path) -> None:
+ _make_extension(
+ tmp_path,
+ files={
+ "ext_localconf.php": "<?php\n",
+ "Configuration/Icons.php": "<?php\nreturn [];\n",
+ },
+ )
+ parsed = _build_parsed(tmp_path)
+ graph = _graph_with_nodes(parsed)
+ ctx = _ctx(tmp_path, parsed)
+ count = add_framework_edges(graph, parsed, ctx, tech_stack=[])
+ assert count >= 2
+ assert graph.has_edge("framework:typo3-core", "ext_localconf.php")
+ assert graph.has_edge("framework:typo3-core", "Configuration/Icons.php")
+
+ def test_legacy_ext_emconf_only_triggers(self, tmp_path: Path) -> None:
+ # No composer.json — legacy non-composer install.
+ (tmp_path / "ext_emconf.php").write_text("<?php\n$EM_CONF[] = [];\n")
+ (tmp_path / "ext_localconf.php").write_text("<?php\n")
+ parsed = _build_parsed(tmp_path)
+ graph = _graph_with_nodes(parsed)
+ ctx = _ctx(tmp_path, parsed)
+ count = add_framework_edges(graph, parsed, ctx, tech_stack=[])
+ assert count >= 2
+ assert graph.has_edge("framework:typo3-core", "ext_emconf.php")
+ assert graph.has_edge("framework:typo3-core", "ext_localconf.php")
+
+ def test_non_typo3_php_repo_adds_no_typo3_edges(self, tmp_path: Path) -> None:
+ # Plain PHP package; composer.json without TYPO3 type.
+ (tmp_path / "composer.json").write_text(
+ json.dumps({"name": "vendor/lib", "type": "library"})
+ )
+ (tmp_path / "src").mkdir()
+ (tmp_path / "src" / "Foo.php").write_text("<?php\nclass Foo {}\n")
+ parsed = _build_parsed(tmp_path)
+ graph = _graph_with_nodes(parsed)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=[])
+ assert "framework:typo3-core" not in graph
+
+
+class TestTypo3ConventionFiles:
+ def test_tca_files_get_edges(self, tmp_path: Path) -> None:
+ _make_extension(
+ tmp_path,
+ files={
+ "Configuration/TCA/tx_my_ext_item.php": "<?php\nreturn [];\n",
+ "Configuration/TCA/Overrides/tt_content.php": "<?php\n",
+ "Configuration/Backend/Routes.php": "<?php\nreturn [];\n",
+ },
+ )
+ parsed = _build_parsed(tmp_path)
+ graph = _graph_with_nodes(parsed)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=[])
+ assert graph.has_edge(
+ "framework:typo3-core", "Configuration/TCA/tx_my_ext_item.php"
+ )
+ assert graph.has_edge(
+ "framework:typo3-core", "Configuration/TCA/Overrides/tt_content.php"
+ )
+ assert graph.has_edge(
+ "framework:typo3-core", "Configuration/Backend/Routes.php"
+ )
+
+ def test_v14_extension_without_legacy_files_works(self, tmp_path: Path) -> None:
+ # v14: no ext_emconf.php, no ext_tables.php, just composer.json + Configuration/.
+ composer = {
+ "name": "vendor/my-ext",
+ "type": "typo3-cms-extension",
+ "require": {"typo3/cms-core": "^14.0"},
+ "extra": {"typo3/cms": {"extension-key": "my_ext"}},
+ }
+ (tmp_path / "composer.json").write_text(json.dumps(composer))
+ (tmp_path / "ext_localconf.php").write_text("<?php\n")
+ (tmp_path / "Configuration").mkdir()
+ (tmp_path / "Configuration" / "Services.php").write_text("<?php\n")
+ parsed = _build_parsed(tmp_path)
+ graph = _graph_with_nodes(parsed)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=[])
+ assert graph.has_edge("framework:typo3-core", "ext_localconf.php")
+ assert graph.has_edge("framework:typo3-core", "Configuration/Services.php")
+
+ def test_yaml_only_configuration_directory(self, tmp_path: Path) -> None:
+ # Common minimal extension layout: only ``Configuration/Services.yaml``,
+ # no PHP files in ``Configuration/``. The yaml file must still get an
+ # edge so the directory doesn't show as a zombie package.
+ _make_extension(
+ tmp_path,
+ files={
+ "Configuration/Services.yaml": "services:\n _defaults:\n autowire: true\n",
+ "Configuration/RTE/Default.yaml": "editor:\n config: {}\n",
+ },
+ )
+ parsed = _build_parsed(tmp_path)
+ graph = _graph_with_nodes(parsed)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=[])
+ assert graph.has_edge("framework:typo3-core", "Configuration/Services.yaml")
+ assert graph.has_edge(
+ "framework:typo3-core", "Configuration/RTE/Default.yaml"
+ )
+
+
+class TestTypo3JavaScriptModules:
+ def test_registered_js_files_get_edges_from_js_modules(
+ self, tmp_path: Path
+ ) -> None:
+ _make_extension(
+ tmp_path,
+ extension_key="my_ext",
+ files={
+ "Configuration/JavaScriptModules.php": (
+ "<?php\nreturn [\n"
+ " 'dependencies' => ['core'],\n"
+ " 'imports' => [\n"
+ " '@vendor/my-ext/Cowriter' "
+ "=> 'EXT:my_ext/Resources/Public/JavaScript/Ckeditor/cowriter.js',\n"
+ " '@vendor/my-ext/AIService' "
+ '=> "EXT:my_ext/Resources/Public/JavaScript/Ckeditor/AIService.js",\n'
+ " ],\n"
+ "];\n"
+ ),
+ "Resources/Public/JavaScript/Ckeditor/cowriter.js": "// stub\n",
+ "Resources/Public/JavaScript/Ckeditor/AIService.js": "// stub\n",
+ },
+ )
+ parsed = _build_parsed(tmp_path)
+ graph = _graph_with_nodes(parsed)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=[])
+ assert graph.has_edge(
+ "Configuration/JavaScriptModules.php",
+ "Resources/Public/JavaScript/Ckeditor/cowriter.js",
+ )
+ assert graph.has_edge(
+ "Configuration/JavaScriptModules.php",
+ "Resources/Public/JavaScript/Ckeditor/AIService.js",
+ )
+
+ def test_cross_extension_js_references_are_skipped(self, tmp_path: Path) -> None:
+ # Reference into a different extension's JS file shouldn't create
+ # an edge in *this* repo's graph (we can't resolve EXT:other/ here).
+ _make_extension(
+ tmp_path,
+ extension_key="my_ext",
+ files={
+ "Configuration/JavaScriptModules.php": (
+ "<?php\nreturn [\n"
+ " 'imports' => [\n"
+ " '@core/Foo' => 'EXT:other_ext/Resources/Public/JavaScript/Foo.js',\n"
+ " ],\n"
+ "];\n"
+ ),
+ "Resources/Public/JavaScript/Local.js": "// stub\n",
+ },
+ )
+ parsed = _build_parsed(tmp_path)
+ graph = _graph_with_nodes(parsed)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=[])
+ # No edge to a file under a foreign extension key.
+ assert not any(
+ target.startswith("EXT:other_ext/") for _, target in graph.edges()
+ )
+
+
+class TestTypo3TechStackHint:
+ def test_tech_stack_alone_triggers_when_files_match(
+ self, tmp_path: Path
+ ) -> None:
+ # No composer.json, no ext_emconf.php — pure tech-stack hint.
+ # Without an extension root we still add zero edges (correct behaviour:
+ # we need a discoverable extension).
+ (tmp_path / "ext_localconf.php").write_text("<?php\n")
+ # ext_emconf.php missing on purpose
+ parsed = _build_parsed(tmp_path)
+ graph = _graph_with_nodes(parsed)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=["typo3"])
+ # ext_localconf.php at root with no other anchor: discovery walks
+ # composer.json (none) and ext_emconf.php (none). No roots → no edges.
+ # This documents the current behaviour; pure-tech-stack hint without
+ # any extension marker is a no-op.
+ assert "framework:typo3-core" not in graph or not list(
+ graph.successors("framework:typo3-core")
+ )
+
+
+class TestTypo3ProjectMode:
+ """Composer-managed full TYPO3 install: extensions live under vendor/."""
+
+ def test_vendor_extensions_discovered(self, tmp_path: Path) -> None:
+ # Project root has its own composer.json (type=project, requires cms-core).
+ (tmp_path / "composer.json").write_text(
+ json.dumps(
+ {
+ "name": "vendor/site",
+ "type": "project",
+ "require": {"typo3/cms-core": "^13.4"},
+ }
+ )
+ )
+ # An extension installed under vendor/.
+ ext_root = tmp_path / "vendor" / "myvendor" / "my-ext"
+ ext_root.mkdir(parents=True)
+ (ext_root / "composer.json").write_text(
+ json.dumps(
+ {
+ "name": "myvendor/my-ext",
+ "type": "typo3-cms-extension",
+ "extra": {"typo3/cms": {"extension-key": "my_ext"}},
+ }
+ )
+ )
+ (ext_root / "ext_localconf.php").write_text("<?php\n")
+ (ext_root / "Configuration").mkdir()
+ (ext_root / "Configuration" / "Icons.php").write_text("<?php\nreturn [];\n")
+
+ parsed = _build_parsed(tmp_path)
+ graph = _graph_with_nodes(parsed)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=[])
+ assert graph.has_edge(
+ "framework:typo3-core", "vendor/myvendor/my-ext/ext_localconf.php"
+ )
+ assert graph.has_edge(
+ "framework:typo3-core",
+ "vendor/myvendor/my-ext/Configuration/Icons.php",
+ )
+
+ def test_node_modules_is_skipped(self, tmp_path: Path) -> None:
+ # node_modules can contain composer.json by accident — never treat
+ # those as TYPO3 extensions.
+ bogus = tmp_path / "node_modules" / "evil" / "composer.json"
+ bogus.parent.mkdir(parents=True)
+ bogus.write_text(
+ json.dumps({"name": "evil/pkg", "type": "typo3-cms-extension"})
+ )
+ # Need any TYPO3 marker for detection to even fire.
+ (tmp_path / "composer.json").write_text(
+ json.dumps({"type": "typo3-cms-extension"})
+ )
+ (tmp_path / "ext_localconf.php").write_text("<?php\n")
+ parsed = _build_parsed(tmp_path)
+ graph = _graph_with_nodes(parsed)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=[])
+ # The bogus path should never become an edge target.
+ assert not any(
+ "node_modules/" in target
+ for _, target in graph.edges()
+ if isinstance(target, str)
+ )
diff --git a/tests/unit/test_dead_code.py b/tests/unit/test_dead_code.py
index ebd93cd27..99e059c66 100644
--- a/tests/unit/test_dead_code.py
+++ b/tests/unit/test_dead_code.py
@@ -419,6 +419,58 @@ def test_zombie_package_detected():
assert "pkgB" in pkgs
+def test_framework_anchor_counts_as_cross_package_importer():
+ """``framework:`` synthetic predecessors should rescue a package from zombie status.
+
+ ``external:`` predecessors don't count (third-party imports), but
+ ``framework:`` anchors model real framework-mediated loading
+ (e.g. TYPO3 core loading every ``Configuration/*.php``) and should.
+ """
+ g = _build_graph(
+ nodes={
+ "Configuration/foo.php": {"is_entry_point": False, "symbol_count": 1, "symbols": []},
+ "src/main.php": {"is_entry_point": False, "symbol_count": 1, "symbols": []},
+ },
+ )
+ g.add_node("framework:typo3-core", language="external")
+ g.add_edge("framework:typo3-core", "Configuration/foo.php", edge_type="framework")
+
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_unused_exports": False,
+ "min_confidence": 0.0,
+ }
+ )
+
+ zombie_pkgs = [
+ f.package for f in report.findings if f.kind == DeadCodeKind.ZOMBIE_PACKAGE
+ ]
+ assert "Configuration" not in zombie_pkgs, (
+ "framework: predecessors should count as cross-package importers"
+ )
+
+
+def test_framework_anchor_node_not_flagged_as_unreachable():
+ """A ``framework:`` synthetic node must not itself be flagged as dead."""
+ g = _build_graph(
+ nodes={
+ "ext_localconf.php": {"is_entry_point": False, "symbol_count": 1, "symbols": []},
+ },
+ )
+ g.add_node("framework:typo3-core", language="external")
+ g.add_edge("framework:typo3-core", "ext_localconf.php", edge_type="framework")
+
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze({"min_confidence": 0.0})
+
+ paths = [f.file_path for f in report.findings]
+ assert "framework:typo3-core" not in paths
+ # ext_localconf.php should also not be flagged: it has a framework: predecessor.
+ assert "ext_localconf.php" not in paths
+
+
# ---------------------------------------------------------------------------
# 10. test_whitelist_respected
# ---------------------------------------------------------------------------