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(godot): make Godot scripts reachable through scenes, autoloads and class_name (#1624)
Raghav Chamadiyababf2c447000
diff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.mdindex 6174eb8b3..2e14647f3 100644--- a/docs/layers/LANGUAGE_SUPPORT.md+++ b/docs/layers/LANGUAGE_SUPPORT.md@@ -55,7 +55,7 @@ produce meaningful output.| Tier | Languages | What you get ||------|-----------|--------------|| **Full** (13) | Python · TypeScript · JavaScript · Svelte · Vue · Java · Kotlin · Go · Rust · C++ · C# · Scala · Ruby | The whole pipeline: AST symbols, import resolution, a resolved call graph, heritage, docstrings, framework edges, **and code-health markers** |-| **Good** (7) | C · Swift · PHP · Dart · Object Pascal · GDScript · VB.NET | Everything above except the full health suite. Dart and Object Pascal *do* get health markers; C, Swift, PHP, GDScript and VB.NET don't yet. GDScript has a dedicated import resolver but no framework edges or named bindings (see [Known gaps](#gdscript-known-gaps)) |+| **Good** (7) | C · Swift · PHP · Dart · Object Pascal · GDScript · VB.NET | Everything above except the full health suite. Dart and Object Pascal *do* get health markers; C, Swift, PHP, GDScript and VB.NET don't yet. GDScript has a dedicated import resolver and Godot-specific framework edges but no named bindings (see [Known gaps](#gdscript-known-gaps)) || **Partial** (2) | Luau / Roblox · Razor / Blazor | Luau: AST symbols and `require()` resolution (Rojo / `.luaurc` aware), no health markers yet. Razor: a component symbol per file, call edges from `@code` blocks and component tags, C# health markers; no import resolution yet || | | ⎯⎯ *tree-sitter parsing stops here. The rungs below are derived from git and imports, not from an AST.* ⎯⎯ || **Lightweight** (8) | Elixir · Clojure · Haskell · Lean 4 · Erlang · F# · HTML · QML | A real file-to-file import graph, no symbol-level claims |@@ -272,7 +272,7 @@ bindings and heritage, with a dedicated workspace resolver per language.| **PHP** | `.php` | `use Foo\Bar\Baz` with composer.json PSR-4 longest-prefix resolution; Laravel, TYPO3 edges || **Dart** | `.dart` | `import` / `export` / `part` URIs, `package:` via every `pubspec.yaml`, Flutter route tables and `runApp()` edges. **Health markers included** || **Object Pascal** | `.pas` `.pp` `.dpr` `.dpk` `.lpr` `.inc` | `uses` clauses via the generic unit-name → file-stem fallback; project files as entry points. **Health markers included** |-| **GDScript** | `.gd` | `preload(...)` / `load(...)` / `extends "res://..."` resolved as absolute paths from the nearest `project.godot`, so a repo holding many Godot projects keeps each project's `res://` namespace separate |+| **GDScript** | `.gd` | `preload(...)` / `load(...)` / `extends "res://..."` resolved as absolute paths from the nearest `project.godot`, so a repo holding many Godot projects keeps each project's `res://` namespace separate, plus scene, autoload and `class_name` edges (see [Godot project files](#godot-project-files)) || **VB.NET** | `.vb` | `Imports` through the same MSBuild project index C# uses: `.vbproj` / `.sln` parsing, `<RootNamespace>`-aware namespace lookup, NuGet package references |### GDScript known gaps@@ -301,9 +301,13 @@ script resolves; the two failures are the `$%UniqueName` form below.For the same reason, a scene's `[ext_resource]` that carries only a `uid://`and no `path` cannot be followed back to the script it names.- **Signals share the `variable` kind** (no `signal` member in `SymbolKind`).-- **No framework edges and no named bindings.** Unlike C / Swift / PHP / Dart- at this tier, there is no Godot framework-edge handler and no binding- extractor, so every `Import` carries `bindings=[]`.+- **No named bindings.** Unlike C / Swift / PHP / Dart at this tier there is no+ binding extractor, so every `Import` carries `bindings=[]`.+- **`class_name` reachability is file-level only.** A scene connection binds to+ the method symbol; a global class does not. A global class's *methods*+ still read as uncalled to the unused-export pass: `DamageEffect.new()` gives+ the call resolver a receiver it cannot map to a class symbol, because a+ script-level class is a sibling of its methods rather than their parent.- **String and annotation dispatch is invisible**: `@rpc` methods invoked via`rpc("name")`, `connect(..., "method_name")`, GDScript 3 `setget` accessornames, and `$NodePath` / `%UniqueName` lookups produce no edges, so those@@ -320,17 +324,6 @@ script resolves; the two failures are the `$%UniqueName` form below.- **Code health: duplication markers DO run** (the clone tokenizer needs only agrammar), but complexity, performance and dataflow dialects are notregistered, and that gap is what keeps GDScript at Good rather than Full.-- **Dead code reads Godot's wiring, not only imports.** A script registered- under `[autoload]` in project.godot counts as an entry point, and a script a- `.tscn` attaches to a node is never flagged, because neither reference is an- import. Without that, 384 of the 461 `.gd` files in- godotengine/godot-demo-projects read as unreachable; with it, 29 do. A file- reached that way is exempt from the symbol-level passes too: a scene wires- handlers by name (`[connection ... method="_on_pressed"]`) and that name- appears in no script, which accounted for 522 of the 1,547 symbol findings- on that corpus. **A script reached only through a `.tres` resource, an editor- plugin manifest or `load()` on a computed path is still reported**, so the- remaining output is narrower than the ladder tier implies.- **Upstream grammar gap, reserved words:** calling a function named `export`or `onready` as a bare statement (`export()`) fails to parse, because thegrammar still reserves those words at statement position for the GDScript 3@@ -367,6 +360,93 @@ and Lake1059/FFmpegFreeUI (197 `.vb` files, 24 of which still carry one).globs mirror the C# ones: designer files, `AssemblyInfo`, everything under`My Project`, and the `ApplicationEvents` runtime hooks.+### Godot project files++A Godot script is rarely referenced by another script. It is attached to a node+in a scene, the scene is instanced by another scene, and the whole thing is+entered from `project.godot`. So `.tscn` / `.tres` / `.escn`, `project.godot`+and an addon's `plugin.cfg` are indexed as their own data language+(`godot_resource`) and read for the paths they name. Line-anchored ini, matched+with regexes, and no second tree-sitter grammar.++| Construct | Becomes |+|---|---|+| `[ext_resource type="Script" path="res://x.gd"]` in a scene or resource | scene → script / scene → sub-scene import edge |+| `[autoload] Events="*res://global/events.gd"` | entry point on the target |+| `[application] run/main_scene="res://main.tscn"` | entry point on the boot scene |+| `[plugin] script="plugin.gd"` in `addons/<name>/plugin.cfg` | entry point on the EditorPlugin |+| `class_name Effect` used by name in another script | framework edge, user → declarer |+| `[connection ... to="Player" method="_on_hit"]` in a scene | framework edge, scene → the handler method |+| `_ready` / `_process` / `_input` / `_draw` / … | never reported as uncalled |++`addons/` is treated as **vendored**, exempt from dead-code reporting the way+`vendor/` is for C, but only when a `project.godot` sits in an *ancestor*+directory of it. Godot has no package manager, so a *consumer* copies a+plugin's `addons/<name>/` tree into its own project, while a *publisher's*+repo is the addon itself. On the validation corpus that exempts Pixelorama's+39 vendored scripts and spares Dialogic's 264 first-party ones.++**Its failure mode is worth knowing before you trust the output**: a publisher+that ships a demo or test project at the repo root has that project enclose+its own `addons/` tree, and the whole product goes unreported. Dialogic+escapes only because its single `project.godot` is a CI fixture parked under+`.github/`. Two of the four corpus repos have no `addons/` at all, so the rule+rests on two data points.++Measured on four Godot repositories (651 `.gd` files; 895 references recorded+from scenes and manifests), this took total dead-code findings from 4965 to+2620, and `unreachable_file` findings, the ones this machinery exists to fix,+from 602 to 85.++**85 is not zero.** Roughly one in eight corpus files still reports as+unreachable, and the ceilings below are the known causes, so treat an+individual dead-code finding on a Godot project as a candidate rather than a+conclusion. What is gone is the systematic part: after these edges land, not+one remaining finding names a file whose `class_name` another file uses.++Ceilings specific to these files:++- **`uid://` is never resolved**, in a scene reference or an autoload entry.+ Resolving one needs the generated `.uid` sidecars, which are build-cache+ artifacts excluded from indexing. Godot 4.4 can also write an `ext_resource`+ with `uid=` and no `path=`; that yields no edge. Not observed in the corpus:+ a `grep` counted 1150 `[ext_resource` lines, all 1150 carrying `path=`.+- **Art assets get no edge**, in a scene's `ext_resource` list or on a script+ `preload` that resolves to nothing. A `.png` is not a code dependency, and+ recording each as an external node would put a repo's whole art tree in the+ graph. Same call HTML's tier makes for `<img src>`. A data file that *is*+ indexed, a `res://data/cards.json`, keeps its edge: the filter only decides+ what an unmatched reference becomes.+- **A reference suffix we do not recognise vanishes from a scene**, where it+ would survive a script `preload` as an external node. The scene side filters+ with a whitelist (`.gd` `.cs` `.tscn` `.tres` `.escn` `.gdshader`), so Godot+ 3's `.shader`, GDNative's `.gdns`, and the binary `.scn` / `.res` forms are+ dropped there. None appear in the corpus.+- **`.gdshader` is out of scope**, so a shader reference becomes an external+ node rather than an edge into the repo, visible as a dependency with no+ file behind it. Every unresolved `res://` reference from a scene across the+ corpus is one of these (20 of the 895 recorded references).+- **`[editor_plugins] enabled=` is not read**, so there is no `project.godot` →+ `plugin.cfg` edge, and a plugin's script is stamped as an entry point whether+ or not the project has the plugin switched on.+- **A programmatically registered autoload is invisible.** `dialogic` installs+ itself with `add_autoload_singleton()` from its `EditorPlugin`, which no+ `[autoload]` table shows.+- **Only a scene's half of signal wiring is read.** A+ `[connection ... to="Player" method="_on_hit"]` block becomes an edge to+ that method, by resolving the `to` node path to the script attached to it+ or to its nearest scripted ancestor. A connection is refused, with no+ edge, when the node is absent from the scene, when no node on that chain+ carries a script, when the script would come from an+ `instance=ExtResource(...)` of another scene, or when the resolved script+ declares no such function. Never matched on the method name alone.+ `connect(..., "method_name")` written in GDScript is still string+ dispatch and still invisible. A node that overrides the instanced+ scene's script with its own `script =` line binds to that override; only+ a chain with no local script anywhere is refused, so a scene that+ inherits another and connects to a handler declared in the *parent*+ scene's script gets no edge.+---## Beyond code files@@ -450,6 +530,11 @@ OpenAPI, Protobuf, GraphQL, Dockerfile, Makefile, YAML, JSON, TOML, Terraform anMarkdown appear in the file tree and the wiki, with special handlers extractingendpoints and targets where applicable.+Godot resource files sit here too: `.tscn` / `.tres` / `.escn`,+`project.godot` and an addon's `plugin.cfg` carry no symbols, but the paths+they name are how a Godot project reaches its scripts, so they are indexed and+read for those paths. See [Godot project files](#godot-project-files).+---## Code-health coverage@@ -532,6 +617,7 @@ cannot check.| Ruby | Full (health) | Dataflow dialect, LCOM4 via `@ivar` grouping || C# | Full (health) | Dataflow dialect || Dart | Good | riverpod / get_it dynamic hints, dataflow dialect |+| GDScript | Good | The health dialects (complexity, performance, dataflow) that would take it to Full; the grammar supports all three || Object Pascal | Good | Assertion and performance markers, a dedicated `uses` resolver || VB.NET | Good | Health markers, project-level `<Import Include=...>` as implicit imports || Elixir · F# | Good | AST upgrade (both grammars are available on PyPI) |diff --git a/packages/core/src/repowise/core/analysis/dead_code/contract_methods.py b/packages/core/src/repowise/core/analysis/dead_code/contract_methods.pyindex fc2925946..e67312169 100644--- a/packages/core/src/repowise/core/analysis/dead_code/contract_methods.py+++ b/packages/core/src/repowise/core/analysis/dead_code/contract_methods.py@@ -18,6 +18,9 @@ Currently covers:``GetIDsOfNames``, ``Invoke``, etc.). They never appear as staticcallers in C# / C++ COM-interop code because the runtime resolvesthe vtable slot.+* **JVM / C++ / Godot**: the ``Object`` and STL contracts, and the Godot+ engine callbacks (``_ready``, ``_process``, …) the engine invokes on+ every node it owns.Extend this list (and the matching helper) when other reserved-namepatterns surface — e.g. WinRT activation factories, .NET ``ToString``@@ -181,6 +184,93 @@ _CPP_CONTRACT_METHOD_NAMES: frozenset[str] = frozenset({_CPP_LANGUAGES: frozenset[str] = frozenset({"cpp", "c"})+# Godot engine callbacks. The engine invokes these on every node it owns:+# ``_ready`` when the node enters the scene tree, ``_process`` once a frame,+# ``_input`` on every event. So a script that does nothing but override them+# is the *normal* shape of a Godot script and has no static caller anywhere.+# Without this, every ``.gd`` file in a Godot project reads as a file full of+# uncalled private functions.+#+# All of them are leading-underscore, which GDScript's visibility convention+# (shared with Python) reads as private, which is exactly why they land in+# the uncalled-private pass rather than the unused-export one.+#+# Godot documents ~200 virtuals across its class hierarchy. Enumerating them+# all would be arbitrary and stale within a release, so this covers the ones+# a project actually overrides: the ``Node`` / ``CanvasItem`` lifecycle, the+# ``Object`` property protocol, and the ``EditorPlugin`` interface an+# ``addons/`` plugin must implement. The ceiling is the mirror image of the+# gap: a project method that happens to share a name with a Godot virtual is+# silently exempted. Contained to GDScript, and every name here starts with+# ``_``, which a project author uses for a helper it does not expect anyone+# else to call either.+_GODOT_CALLBACK_NAMES: frozenset[str] = frozenset({+ # ---- Object / RefCounted ----------------------------------------+ "_init",+ "_notification",+ "_to_string",+ # Property protocol: the engine calls these when the inspector or a+ # script reads/writes a property that does not exist as a real field.+ "_get",+ "_set",+ "_get_property_list",+ "_validate_property",+ "_property_can_revert",+ "_property_get_revert",+ # ---- Node lifecycle ---------------------------------------------+ "_ready",+ "_enter_tree",+ "_exit_tree",+ "_process",+ "_physics_process",+ "_get_configuration_warnings",+ # ---- Input ------------------------------------------------------+ "_input",+ "_unhandled_input",+ "_unhandled_key_input",+ "_shortcut_input",+ "_gui_input",+ "_input_event",+ # ---- CanvasItem / Control drawing and hit-testing ----------------+ "_draw",+ "_has_point",+ "_get_minimum_size",+ "_make_custom_tooltip",+ "_structured_text_parser",+ # ---- Control drag and drop --------------------------------------+ "_get_drag_data",+ "_can_drop_data",+ "_drop_data",+ # ---- GDScript 3 spellings ---------------------------------------+ # Godot 3 named several of these virtuals without a leading underscore and+ # singularised the configuration-warning hook. Both dialects parse (see+ # LANGUAGE_SUPPORT.md), so both spellings belong here. The+ # underscore-free ones read as *public*, which puts them in the+ # unused-export pass rather than the uncalled-private one.+ "get_drag_data",+ "can_drop_data",+ "drop_data",+ "make_custom_tooltip",+ "_get_configuration_warning",+ # ---- Physics bodies ---------------------------------------------+ "_integrate_forces",+ # ---- EditorPlugin: what an addons/ plugin must implement ---------+ "_enable_plugin",+ "_disable_plugin",+ "_get_plugin_name",+ "_get_plugin_icon",+ "_has_main_screen",+ "_make_visible",+ "_handles",+ "_edit",+ "_apply_changes",+ "_save_external_data",+ "_get_window_layout",+ "_set_window_layout",+ "_build",+})++def is_contract_method(sym_name: str, sym_kind: str | None, language: str | None) -> bool:"""Return True if *sym_name* is a reserved contract-method name in *language*.@@ -205,6 +295,8 @@ def is_contract_method(sym_name: str, sym_kind: str | None, language: str | Nonereturn Trueif language in _JVM_LANGUAGES and sym_name in _JVM_CONTRACT_METHOD_NAMES:return True+ if language == "gdscript" and sym_name in _GODOT_CALLBACK_NAMES:+ return Trueif language in _CPP_LANGUAGES:if sym_name in _CPP_CONTRACT_METHOD_NAMES:return Truediff --git a/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py b/packages/core/src/repowise/core/ingestion/framework_edges/__init__.pyindex d96ff3d2d..79999f38e 100644--- a/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py+++ b/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py@@ -1,9 +1,9 @@"""Framework-aware synthetic edge detection.Detects convention-based relationships (Django, FastAPI, Flask, ASP.NET, Rails,-Laravel, Spring, Express/Nest, Gin/Echo/Chi, Axum/Actix/Rocket, TYPO3, and-pytest ``conftest.py``) and adds ``edge_type="framework"`` edges that no static-import graph captures.+Laravel, Spring, Express/Nest, Gin/Echo/Chi, Axum/Actix/Rocket, TYPO3, Godot+``class_name`` globals, and pytest ``conftest.py``) and adds+``edge_type="framework"`` edges that no static import graph captures.Previously a single ``framework_edges.py`` module; split (PR 3.5) into onemodule per framework behind this façade. The public entry point —@@ -26,6 +26,7 @@ from . import (flask,flutter,go,+ godot,gtest,hono,jakarta,@@ -71,6 +72,10 @@ _HANDLERS: list[FrameworkHandler] = [*remix.HANDLERS,*trpc.HANDLERS,*go.HANDLERS,+ # `class_name Foo` registers a project-global identifier other scripts use+ # with no import at all: Godot's own name table, and the largest remaining+ # dead-code false positive once scene edges land.+ *godot.HANDLERS,*gtest.HANDLERS,*rust.HANDLERS,*typo3.HANDLERS,diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/godot.py b/packages/core/src/repowise/core/ingestion/framework_edges/godot.pynew file mode 100644index 000000000..48ce7f0bd--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/framework_edges/godot.py@@ -0,0 +1,392 @@+"""Godot ``class_name`` global-registry edges.++``class_name Effect`` at the top of a ``.gd`` file registers ``Effect`` as a+**project-global identifier**. Every other script in the project then writes::++ var damage_effect := DamageEffect.new()+ func apply(e: Effect) -> void:++with no import, no path, and no qualifier of any kind. Godot keeps the name+table in ``.godot/global_script_class_cache.cfg`` and the compiler resolves it.+It is the same mechanism as an ``[autoload]`` singleton, one level down: a+name the engine injects rather than one the source declares a dependency on.++So the static graph sees nothing. On the validation corpus this was the single+largest remaining source of dead-code false positives once scene edges landed:+94 of the 180 ``unreachable_file`` findings that survived those edges named a+``.gd`` whose ``class_name`` another file uses by name: every+``src/Classes/*.gd`` in Pixelorama, every ``custom_resources/*.gd`` in+deck_builder_tutorial. Adding these edges cleared all 94; the ``plugin.cfg``+entry point cleared one more, leaving 85.++**Declarations are read from the source text, not from the symbol list.** The+parser emits a ``class`` symbol for ``class_name Effect`` and for an inner+``class Inner:`` alike, and only the first is globally registered. The two are+distinguishable in the symbol list today only by a ``signature`` string that+happens to keep the ``class`` keyword for one of them, which is an artifact of+signature extraction rather than a contract. Godot itself requires+``class_name`` to be a top-level statement at the start of a line, so a+line-anchored match is exact; and this handler has to scan every file's text+anyway to find the *usages*, so reading the declaration from that same pass+keeps the whole mechanism in one place.++**Usage is an identifier-token match**, which counts an occurrence inside a+comment or a string literal. That errs toward "reachable", the safe direction+for dead code, and matches how the dead-code analyzer's own unindexed-token+prepass reads source.++Ceiling: this emits *file*-level edges only. A ``class_name`` script's+individual methods still read as uncalled to the unused-export pass, because+``DamageEffect.new()`` gives the call resolver a receiver it cannot map to a+class symbol, because GDScript's script-level class is a sibling of its methods, not+their parent, so there is no ``(class, method)`` pair to look up. That is a+call-graph problem, not a project-awareness one.++Scene signal connections+------------------------++The second handler here closes the symbol-level half for the case that+dominates the residue. A ``.tscn`` records the editor's signal wiring as::++ [connection signal="pressed" from="StartButton" to="." method="_on_start"]++and ``_on_start`` lives in the script attached to the node ``to`` names. No+script mentions the method, so every editor-wired handler reads as an uncalled+private. The scene is the caller, and it is indexed, so the edge can be real:+scene module symbol to handler method symbol, through+:func:`~..framework_edges.base.add_symbol_edge`, the same shape Express uses+for a route argument and Spring for a container-wired bean.++**The node path is resolved, never the method name.** ``to`` is a path from+the scene root (``.`` is the root itself, ``Player/Sprite`` a descendant), and+each ``[node ...]`` block may carry ``script = ExtResource("id")`` naming a+``[ext_resource]`` header already read for its path. A node with no script of+its own runs its nearest ancestor's, so the walk climbs. Four refusals, each+recording no edge rather than a guess:++* the ``to`` path names no node in this scene,+* neither that node nor any ancestor carries a script,+* the node the script would come from is an ``instance=ExtResource(...)`` of+ another scene, whose script this file does not name,+* the resolved script declares no function by that name.++Matching on the method name alone would be the tempting shortcut and is the+one thing this must not do: ``_on_pressed`` appears in dozens of unrelated+scripts in a repo of many projects, and a wrong edge is worse than no edge.+"""++from __future__ import annotations++import re+from typing import TYPE_CHECKING, Any++from .base import (+ DetectionContext,+ FrameworkHandler,+ _add_edge_if_new,+ add_symbol_edge,+ read_text,+)++if TYPE_CHECKING:+ import networkx as nx++ from ..resolvers import ResolverContext++# ``class_name Effect`` / ``class_name Effect extends RefCounted``. Anchored to+# the start of a line because Godot requires the statement at top level.+_CLASS_NAME_RE = re.compile(r"^class_name[ \t]+([A-Za-z_]\w*)", re.MULTILINE)++_IDENTIFIER_RE = re.compile(r"[A-Za-z_]\w*")+++def _has_gdscript(parsed_files: dict[str, Any]) -> bool:+ return any(p.file_info.language == "gdscript" for p in parsed_files.values())+++def _source_text(path: str, parsed: Any, source_map: dict[str, bytes]) -> str:+ """Source text for *path*, preferring bytes ingestion already read.++ This handler is the only one whose file set is the repo's dominant+ language, so re-reading it would be a second full pass over the tree.+ ``utf-8-sig`` on both paths: a BOM on line 1 would otherwise hide a+ ``class_name`` declared there.+ """+ raw = source_map.get(path)+ if raw is not None:+ return raw.decode("utf-8-sig", errors="replace")+ return read_text(parsed, encoding="utf-8-sig")+++def _add_class_name_edges(+ graph: nx.DiGraph,+ parsed_files: dict[str, Any],+ ctx: ResolverContext,+) -> int:+ from ..resolvers.gdscript import godot_project_root++ source_map = getattr(ctx, "source_map", None) or {}+ texts: dict[str, str] = {}+ roots: dict[str, str] = {}+ # Keyed by (project root, name), not by name alone. Godot's global class+ # table is per *project*, and one repo can hold many: `godot-demo-projects`+ # is dozens of independent projects side by side, several of which declare+ # `class_name Player`. Keying by name alone would collapse them and wire+ # every project's `Player` token to whichever file was parsed last -- the+ # same repo-root mistake resolvers/gdscript.py exists to avoid for res://.+ declared_in: dict[tuple[str, str], str] = {}++ for path, parsed in parsed_files.items():+ if parsed.file_info.language != "gdscript":+ continue+ text = _source_text(path, parsed, source_map)+ if not text:+ continue+ texts[path] = text+ roots[path] = godot_project_root(path, ctx)+ for match in _CLASS_NAME_RE.finditer(text):+ declared_in[(roots[path], match.group(1))] = path++ if not declared_in:+ return 0++ count = 0+ for path, text in texts.items():+ root = roots[path]+ names = {n for n in _IDENTIFIER_RE.findall(text) if (root, n) in declared_in}+ # Sorted, not raw set order: string hashing is randomised per process,+ # so an unsorted iteration would insert this file's edges in a+ # different order on every run. Same reason ResolverContext exposes+ # sorted_paths rather than path_set.+ for name in sorted(names):+ # A self-reference is the declaration itself; _add_edge_if_new+ # rejects it.+ if _add_edge_if_new(graph, path, declared_in[(root, name)]):+ count += 1+ return count+++# ---------------------------------------------------------------------------+# Scene signal connections+# ---------------------------------------------------------------------------++# `[ext_resource type="Script" path="res://x.gd" id="1_abc"]`, and Godot 3's+# unquoted `id=1`. Read for the id, since the path itself is already an import.+_EXT_RESOURCE_ID_RE = re.compile(+ r"""^\[ext_resource\b[^\]]*?\bpath\s*=\s*(["'])(?P<path>.+?)\1[^\]]*?"""+ r"""\bid\s*=\s*(?:(["'])(?P<qid>[^"']+)\3|(?P<bid>\d+))""",+ re.MULTILINE,+)++# `[node name="Player" type="Area2D" parent="." instance=ExtResource("3")]`.+# `parent` is absent on exactly one node per scene, the root.+_NODE_RE = re.compile(r"^\[node\s+(?P<attrs>[^\]]*)\]", re.MULTILINE)++# `[connection signal="pressed" from="Btn" to="." method="_on_pressed"]`+_CONNECTION_RE = re.compile(r"^\[connection\s+(?P<attrs>[^\]]*)\]", re.MULTILINE)++_ATTR_RE = re.compile(r"""(\w+)\s*=\s*(?:(["'])(.*?)\2|(\S+))""")++# `script = ExtResource("2")` / Godot 3's `script = ExtResource( 2 )`, as a+# property line under a node header.+_SCRIPT_PROP_RE = re.compile(+ r"""^script\s*=\s*ExtResource\(\s*(?:(["'])([^"']+)\1|(\d+))\s*\)""",+ re.MULTILINE,+)+++def _attrs(blob: str) -> dict[str, str]:+ out: dict[str, str] = {}+ for m in _ATTR_RE.finditer(blob):+ out[m.group(1)] = m.group(3) if m.group(3) is not None else (m.group(4) or "")+ return out+++class _SceneNode:+ """One ``[node]`` block: where it sits, and what script it runs."""++ __slots__ = ("instance_id", "parent", "script_id")++ def __init__(self, parent: str | None, script_id: str | None, instance_id: str | None):+ self.parent = parent+ self.script_id = script_id+ self.instance_id = instance_id+++def parse_scene(text: str) -> tuple[dict[str, str], dict[str, _SceneNode], list[dict[str, str]]]:+ """Return ``(ext_resource id -> path, node path -> node, connections)``.++ Node paths are keyed the way ``[connection]`` writes them: ``"."`` is the+ root, a child of the root is its bare name, and anything deeper is+ slash-joined. That is the same spelling Godot uses, so no translation+ happens at lookup time.+ """+ resources: dict[str, str] = {}+ for m in _EXT_RESOURCE_ID_RE.finditer(text):+ rid = m.group("qid") or m.group("bid")+ if rid:+ resources[rid] = m.group("path")++ nodes: dict[str, _SceneNode] = {}+ # A node's `script =` property sits on its own line *after* the header, so+ # each block runs to the next header (of any kind) rather than to the next+ # blank line: Godot writes other properties in between.+ headers = list(_NODE_RE.finditer(text))+ for i, m in enumerate(headers):+ end = headers[i + 1].start() if i + 1 < len(headers) else len(text)+ body = text[m.end() : end]+ # A `[connection]` or `[sub_resource]` between two node headers ends+ # this node's property block; anything after it belongs to neither.+ cut = body.find("\n[")+ if cut != -1:+ body = body[:cut]+ attrs = _attrs(m.group("attrs"))+ name = attrs.get("name")+ if not name:+ continue+ parent = attrs.get("parent")+ path = "." if parent is None else (name if parent == "." else f"{parent}/{name}")+ script = _SCRIPT_PROP_RE.search(body)+ script_id = (script.group(2) or script.group(3)) if script else None+ instance = attrs.get("instance") or ""+ inst_match = re.search(r"""ExtResource\(\s*["']?([^"')]+)["']?\s*\)""", instance)+ nodes[path] = _SceneNode(parent, script_id, inst_match.group(1) if inst_match else None)++ connections = [_attrs(m.group("attrs")) for m in _CONNECTION_RE.finditer(text)]+ return resources, nodes, connections+++def _parent_path(path: str, nodes: dict[str, _SceneNode]) -> str | None:+ """The path of *path*'s parent node, or None once past the root."""+ if path == ".":+ return None+ node = nodes.get(path)+ if node is None or node.parent is None:+ return None+ return "." if node.parent == "." else node.parent+++def resolve_handler_node(+ to: str, nodes: dict[str, _SceneNode]+) -> tuple[str | None, str]:+ """Return ``(ext_resource id of the script that runs *to*, reason)``.++ The reason is a short tag naming the refusal when the id is None, so a+ caller counting refusals does not have to re-derive why.+ """+ path = "." if to in ("", ".") else to+ if path not in nodes:+ return None, "node_not_found"+ seen: set[str] = set()+ while path is not None and path not in seen:+ seen.add(path)+ node = nodes.get(path)+ if node is None:+ return None, "node_not_found"+ if node.script_id is not None:+ return node.script_id, "ok"+ if node.instance_id is not None:+ # The script lives in the instanced scene, which this file does+ # not name. Climbing past it would attribute the handler to an+ # ancestor that does not own it.+ return None, "instanced_scene"+ path = _parent_path(path, nodes)+ return None, "no_script"+++def _add_connection_edges(+ graph: nx.DiGraph,+ parsed_files: dict[str, Any],+ ctx: ResolverContext,+) -> int:+ from ..resolvers.gdscript import resolve_gdscript_import++ source_map = getattr(ctx, "source_map", None) or {}+ # `{script path: {function name: symbol id}}`. Methods included: GDScript+ # writes a handler as a plain `func`, but an inner class puts one under a+ # parent, and either is a legitimate target for a connection.+ functions: dict[str, dict[str, str]] = {}+ for path, parsed in parsed_files.items():+ if parsed.file_info.language != "gdscript":+ continue+ table = {+ sym.name: sym.id+ for sym in parsed.symbols+ if sym.kind in ("function", "method")+ }+ if table:+ functions[path] = table+ if not functions:+ return 0++ count = 0+ for path, parsed in parsed_files.items():+ if parsed.file_info.language != "godot_resource":+ continue+ if not path.lower().endswith((".tscn", ".escn")):+ continue+ raw = source_map.get(path)+ text = (+ raw.decode("utf-8-sig", errors="replace")+ if raw is not None+ else read_text(parsed, encoding="utf-8-sig")+ )+ if "[connection" not in text:+ continue+ resources, nodes, connections = parse_scene(text)+ if not nodes:+ continue+ module_sym = f"{path}::__module__"+ for conn in connections:+ method = conn.get("method")+ if not method:+ continue+ script_id, _reason = resolve_handler_node(conn.get("to", "."), nodes)+ if script_id is None:+ continue+ raw_path = resources.get(script_id)+ if raw_path is None:+ continue+ target_file = resolve_gdscript_import(raw_path, path, ctx)+ if target_file is None or target_file not in ctx.path_set:+ continue+ sym_id = functions.get(target_file, {}).get(method)+ if sym_id is not None and add_symbol_edge(graph, module_sym, sym_id):+ count += 1+ return count+++class _GodotClassNameHandler:+ def detect(self, dctx: DetectionContext) -> bool:+ return _has_gdscript(dctx.parsed_files)++ def add_edges(+ self,+ graph: nx.DiGraph,+ parsed_files: dict[str, Any],+ ctx: ResolverContext,+ path_set: set[str],+ ) -> int:+ return _add_class_name_edges(graph, parsed_files, ctx)+++class _GodotSceneConnectionHandler:+ def detect(self, dctx: DetectionContext) -> bool:+ return _has_gdscript(dctx.parsed_files) and any(+ p.file_info.language == "godot_resource" for p in dctx.parsed_files.values()+ )++ def add_edges(+ self,+ graph: nx.DiGraph,+ parsed_files: dict[str, Any],+ ctx: ResolverContext,+ path_set: set[str],+ ) -> int:+ return _add_connection_edges(graph, parsed_files, ctx)+++HANDLERS: list[FrameworkHandler] = [+ _GodotClassNameHandler(),+ _GodotSceneConnectionHandler(),+]diff --git a/packages/core/src/repowise/core/ingestion/graph/_edges.py b/packages/core/src/repowise/core/ingestion/graph/_edges.pyindex 7cf607959..0d346e945 100644--- a/packages/core/src/repowise/core/ingestion/graph/_edges.py+++ b/packages/core/src/repowise/core/ingestion/graph/_edges.py@@ -189,6 +189,11 @@ class EdgesMixin:go_modules=go_modules,has_sfc_files=any(p.endswith((".vue", ".svelte", ".astro")) for p in path_set),parsed_files=self._parsed_files,+ # Same reason ``build()`` passes it: a handler that scans file text+ # (the Godot ``class_name`` one covers every ``.gd`` in the repo)+ # reads the bytes ingestion already has instead of a second pass+ # over the tree. Empty unless ``set_source_map`` was called.+ source_map=self._source_map,)count = add_framework_edges(self._graph, self._parsed_files, ctx, tech_stack)diff --git a/packages/core/src/repowise/core/ingestion/graph_warmups.py b/packages/core/src/repowise/core/ingestion/graph_warmups.pyindex e1a9432b1..61561ac56 100644--- a/packages/core/src/repowise/core/ingestion/graph_warmups.py+++ b/packages/core/src/repowise/core/ingestion/graph_warmups.py@@ -398,38 +398,105 @@ def _warmup_dart(ctx: ResolverContext) -> None:pf.file_info.is_entry_point = True-def _warmup_gdscript(ctx: ResolverContext) -> None:- """Stamp the Godot scripts the engine loads without an import.-- An ``[autoload]`` entry in project.godot registers a script as a global- singleton the engine instantiates at startup, so it is an entry point in- the same sense ``main.py`` is. A script attached to a scene node is saved- in the ``.tscn`` as an ext_resource, which is a reference no GDScript file- makes: without this, every gameplay script in a Godot project reads as- unreachable, because scenes -- not scripts -- are what a Godot game wires- together.-- A repo with no project.godot and no scenes gets two empty sets, so this is- a no-op on a loose bag of .gd files.+def _warmup_godot(ctx: ResolverContext) -> None:+ """Stamp Godot engine-invoked entry points, and vendored ``addons/``.++ Two facts about a Godot project that the import graph cannot express, both+ read off its ini manifests.++ **Autoloads, the main scene and an addon's EditorPlugin are entry points.**+ Godot instantiates every ``[autoload]`` singleton before the first scene,+ boots into ``run/main_scene``, and loads an addon's ``plugin.cfg``+ ``script`` when the plugin is enabled. No source imports any of them by+ name (an autoload is reached through a global identifier the engine+ injects), so such a file has inbound edges from the manifest alone, and the+ unreachable-file pass would report the most load-bearing scripts in the+ project. See ``lightweight_imports/godot.py`` for why every import on one+ of these manifests is an execution start.++ Two deliberate imprecisions here. An autoload named by ``uid://`` rather+ than ``res://`` cannot be resolved (the ``.uid`` sidecars are build-cache+ artifacts the spec blocks) and goes unstamped. And a ``plugin.cfg`` script+ is stamped whether or not ``project.godot``'s ``[editor_plugins] enabled=``+ lists it: a checked-in but switched-off plugin is not dead code, it is+ off.++ **``addons/`` is vendored when a Godot project encloses it.** Godot has no+ package manager: a plugin is distributed by copying its ``addons/<name>/``+ tree into the consuming project, so ``addons/`` is a checked-in+ ``node_modules``. Its scripts are a third party's public API, reached by+ the editor or by the plugin's own scenes, and reporting them as dead is+ reporting on code the repo does not own.++ But the *publisher* of a plugin also keeps it in ``addons/``, and there the+ same tree is the entire product. The discriminator implemented here is+ whether a ``project.godot`` sits in an *ancestor* directory of the+ ``addons/`` tree, not whether the repo has one anywhere. On the corpus+ that exempts Pixelorama's 39 vendored scripts and spares dialogic's 264+ first-party ones, which matters because 97% of dialogic *is* ``addons/``.++ **Its known failure mode**, and it is not hypothetical: a publisher that+ ships a demo or test project at the repo root gets its own product+ never-flagged. dialogic escapes only because its single ``project.godot``+ is a CI fixture parked under ``.github/``. Two of the four corpus repos+ have no ``addons/`` at all, so the rule is really evidenced by n=2.++ The alternative rule, vendored unless the project declares a plugin entry+ for it, reaches the same verdict on both corpus repos. It differs only for+ a vendored plugin that is switched *off*, which ``[editor_plugins]+ enabled=`` would not list and which this treats as vendored anyway."""graph = getattr(ctx, "graph", None)if graph is None:return- from .resolvers.gdscript import engine_loaded_scripts- autoloads, scene_scripts = engine_loaded_scripts(ctx)- parsed = getattr(ctx, "parsed_files", None) or {}- for path in autoloads:- node = graph.nodes.get(path)- if node is not None:- node["is_entry_point"] = True- pf = parsed.get(path)- if pf is not None and getattr(pf, "file_info", None) is not None:- pf.file_info.is_entry_point = True- for path in scene_scripts - autoloads:- node = graph.nodes.get(path)- if node is not None:- node["is_never_flag"] = True+ project_files: list[str] = []+ manifests: list[str] = []+ for p in getattr(ctx, "sorted_paths", ()):+ name = p.rsplit("/", 1)[-1]+ if name == "project.godot":+ project_files.append(p)+ manifests.append(p)+ elif name == "plugin.cfg":+ manifests.append(p)+ if not manifests:+ return++ from .resolvers.gdscript import resolve_gdscript_import++ parsed_files = getattr(ctx, "parsed_files", None) or {}+ for path in manifests:+ parsed = parsed_files.get(path)+ for imp in getattr(parsed, "imports", ()) or ():+ target = resolve_gdscript_import(imp.module_path, path, ctx)+ # An unresolved path comes back as an ``external:`` node the+ # resolver just minted. Flagging that says nothing about a file in+ # this repo, so only in-repo targets are stamped.+ if target is None or target not in ctx.path_set:+ continue+ node = graph.nodes.get(target)+ if node is not None:+ node["is_entry_point"] = True+ # Both, as _warmup_dart and _warmup_go do: the graph attribute is+ # what dead-code reachability reads, but the wiki's entry-point+ # list, the tour and page selection all read FileInfo. Stamping+ # only the first would leave an addon-publisher repo still+ # reporting no entry point anywhere a reader looks.+ target_parsed = parsed_files.get(target)+ if target_parsed is not None and getattr(target_parsed, "file_info", None):+ target_parsed.file_info.is_entry_point = True++ # A project root of "" (project.godot at the repo root) gives "addons/".+ # Keyed on project.godot only: a plugin.cfg is what marks an addon, not+ # what makes it someone else's.+ if not project_files:+ return+ addon_prefixes = tuple(p[: -len("project.godot")] + "addons/" for p in project_files)+ for node_name in list(graph.nodes()):+ if str(node_name).startswith(addon_prefixes):+ nd = graph.nodes.get(node_name)+ if nd is not None:+ nd["is_never_flag"] = True# Map language tag → (phase-event name, warmup function). The phase@@ -450,7 +517,12 @@ _WARMUPS: dict[str, tuple[str, Warmup]] = {"c": ("graph.cpp_index", _warmup_cpp),"swift": ("graph.swift_entry", _warmup_swift),"dart": ("graph.dart_shells", _warmup_dart),- "gdscript": ("graph.godot_scenes", _warmup_gdscript),+ # Registered under both tags: a repo of loose .gd scripts has no scenes,+ # and an addon distributed as scenes plus a project.godot may carry no+ # first-party .gd at all. Shared event name, and the warmup is a no-op+ # without a project.godot, so firing twice is harmless.+ "gdscript": ("graph.godot_project", _warmup_godot),+ "godot_resource": ("graph.godot_project", _warmup_godot),}diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py b/packages/core/src/repowise/core/ingestion/languages/specs/__init__.pyindex 79a22780b..e1555856f 100644--- a/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py+++ b/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py@@ -26,6 +26,7 @@ from .erlang import SPEC as _ERLANGfrom .fsharp import SPEC as _FSHARPfrom .gdscript import SPEC as _GDSCRIPTfrom .go import SPEC as _GO+from .godot_resource import SPEC as _GODOT_RESOURCEfrom .graphql import SPEC as _GRAPHQLfrom .haskell import SPEC as _HASKELLfrom .html import SPEC as _HTML@@ -131,6 +132,11 @@ ALL_SPECS: tuple[LanguageSpec, ...] = (# emits ``dynamic_uses`` edges to bound C# types. Registered here so# that the traverser surfaces a file node these edges can attach to._XAML,+ # Godot scenes/resources and project.godot. Data, so never reported as+ # dead, but a Godot script is attached to a scene rather than imported+ # by another script, so these files carry nearly every inbound edge the+ # .gd graph has. See the spec's docstring.+ _GODOT_RESOURCE,# -----------------------------------------------------------------# Extra languages — git blame coverage only (passthrough + is_code)# These exist so git_indexer tracks their history even thoughdiff --git a/packages/core/src/repowise/core/ingestion/languages/specs/godot_resource.py b/packages/core/src/repowise/core/ingestion/languages/specs/godot_resource.pynew file mode 100644index 000000000..50835e598--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/languages/specs/godot_resource.py@@ -0,0 +1,90 @@+"""LanguageSpec for Godot's resource files, an import-tier language.++Covers ``.tscn`` (scenes), ``.tres`` (resources), ``.escn`` (Blender-exported+scenes), ``project.godot`` and an addon's ``plugin.cfg``. All are the same+line-anchored ini dialect, so one tag covers them and+``lightweight_imports/godot.py`` distinguishes them by the section names+present rather than by filename.++**Why this exists at all.** A Godot script is almost never referenced by+another script. It is attached to a node in a scene::++ [ext_resource type="Script" path="res://actors/player.gd" id="1_4s751"]+ ...+ [node name="Player" type="CharacterBody2D"]+ script = ExtResource("1_4s751")++and the scene is instanced by another scene, or named in ``project.godot``'s+``[autoload]`` table. Index the ``.gd`` files alone and the dependency graph+has no edges into most of them, which makes GDScript dead-code reporting+worse than not supporting the language at all, so this ships in the same+release as the GDScript AST, never after it.++**No second grammar.** ``tree-sitter-language-pack`` ships a+``godot_resource`` grammar and it parses these files correctly, but the two+constructs that carry dependencies (an ``[ext_resource]`` header line and an+``autoload`` assignment) are single lines with a quoted path on them. A+regex is the right rung, and it keeps the wheel-publishing problem GDScript+already carries down to exactly one grammar.++``is_code=False`` is truthful and load-bearing, the same way it is for+``html``: these files are data, they declare no symbols, and the+classification puts them in dead code's ``_NON_CODE_LANGUAGES`` so a scene+nobody instances is never *reported* as dead while its outbound edges still+anchor every script it attaches. Whether a scene is reachable is not+statically decidable: ``load()`` takes a runtime string, and the editor+opens scenes directly.++Known ceilings:++* **``uid://``**: Godot 4.4 can write it in place of ``path=`` in an+ ``ext_resource`` header, and resolving one needs the generated ``.uid``+ sidecars this spec blocks from indexing. Recorded as an external reference+ rather than guessed at (see ``resolvers/gdscript.py``). Not yet observed: a+ ``grep`` over the four-repo validation corpus counted 1150 ``[ext_resource``+ lines, all 1150 carrying ``path=``.+* **The binary scene and resource formats ``.scn`` / ``.res``** are not+ covered, not by ``extensions`` here and not by the suffix lists in+ ``resolvers/gdscript.py``. Godot writes text by default and the corpus has+ none, but a project that ships binary scenes gets no extraction from them+ and no edge to one.+* **Unrecognised reference suffixes vanish from a scene** rather than becoming+ external nodes, because the scene side filters with a whitelist. See+ ``lightweight_imports/godot.py``.++Registering the bare filename ``plugin.cfg`` has one side effect worth+naming: an unrelated ``plugin.cfg`` in a non-Godot repo is now classified as+"Godot Resource" in the file tree and language stats. It yields no imports,+not because of its section names, which are ordinary ini, but because the+extractor's suffix whitelist admits only code paths, so it costs a label,+not an edge.+"""++from ..spec import LanguageSpec++SPEC = LanguageSpec(+ tag="godot_resource",+ display_name="Godot Resource",+ extensions=frozenset({".tscn", ".tres", ".escn"}),+ # project.godot is also gdscript's `manifest_files` entry, which marks its+ # directory as a package root. The registry keeps the two maps separate+ # (extension/filename vs manifest), so a file can be both: the res:// root+ # for the resolver, and an indexed file whose [autoload] table is a real+ # set of edges.+ # `plugin.cfg` is an addon's manifest; its `script=` names the EditorPlugin+ # subclass the editor loads. See the docstring for what registering the+ # bare name costs outside Godot.+ special_filenames=frozenset({"project.godot", "plugin.cfg"}),+ # Data, not code -- no symbols exist to extract. See the module docstring.+ is_code=False,+ is_passthrough=True,+ # `res://` is absolute from the project root and resolves exactly, via the+ # same resolver the .gd files use. The one gap (uid://) is a Godot+ # build-cache artifact rather than a dialect we fail to read, so this is+ # "full" where html's src/href tier is "partial".+ import_support="full",+ blocked_dirs=(".godot", ".import"),+ blocked_extensions=(".import", ".uid"),+ # Godot's own brand blue, matching the gdscript spec.+ color_hex="#478CBF",+)diff --git a/packages/core/src/repowise/core/ingestion/lightweight_imports/__init__.py b/packages/core/src/repowise/core/ingestion/lightweight_imports/__init__.pyindex 0edfdc695..cb31b2161 100644--- a/packages/core/src/repowise/core/ingestion/lightweight_imports/__init__.py+++ b/packages/core/src/repowise/core/ingestion/lightweight_imports/__init__.py@@ -1,7 +1,14 @@"""Import-only extraction for languages the symbol pipeline does not parse.-Languages whose ``LanguageSpec.import_support`` is ``"partial"`` via the-lightweight-resolver mechanism get their import statements extracted here.+Languages with no ``LanguageConfig`` get their import statements extracted+here. Most are ``import_support="partial"``, a dedicated resolver with a+major known gap, usually a dialect the regex cannot read. ``godot_resource``+is the exception at ``"full"``, on the terms ``languages/spec.py`` sets for+that value: its ini dialect has no variant left unread, and a ``res://`` path+is absolute, so resolution is exact rather than a rank-and-guess. Its gaps+are narrow and named in ``specs/godot_resource.py``, not the+44%-of-real-files kind that keeps ``html`` at ``"partial"``.+The parser consults :func:`extract_lightweight_imports` on itsno-``LanguageConfig`` path, so these files keep an empty symbol list — thistier claims no symbol knowledge — but carry real :class:`~..models.Import`@@ -25,6 +32,7 @@ from .dart import extract_dart_importsfrom .elixir import extract_elixir_importsfrom .erlang import extract_erlang_importsfrom .fsharp import extract_fsharp_imports+from .godot import extract_godot_importsfrom .haskell import extract_haskell_importsfrom .html import extract_html_importsfrom .lean import extract_lean_imports@@ -49,6 +57,10 @@ _EXTRACTORS: dict[str, ExtractorFn] = {"sql": extract_dbt_imports,# <script src> / <link href>. AST-backed rather than regex — see above."html": extract_html_imports,+ # [ext_resource path=...] in .tscn/.tres/.escn, plus project.godot's+ # [autoload] table and run/main_scene. These are how a Godot project+ # reaches its .gd files -- scripts are attached to scenes, not imported.+ "godot_resource": extract_godot_imports,}LIGHTWEIGHT_IMPORT_LANGUAGES = frozenset(_EXTRACTORS)diff --git a/packages/core/src/repowise/core/ingestion/lightweight_imports/godot.py b/packages/core/src/repowise/core/ingestion/lightweight_imports/godot.pynew file mode 100644index 000000000..9ef4fa5f3--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/lightweight_imports/godot.py@@ -0,0 +1,173 @@+"""Dependency extraction for Godot's resource files.++``.tscn`` / ``.tres`` / ``.escn``, ``project.godot`` and an addon's+``plugin.cfg`` are one line-anchored ini dialect, and every construct that+carries a dependency is a single line with a quoted path on it::++ [ext_resource type="Script" path="res://actors/player.gd" id="1_4s751"]+ [ext_resource path="res://actors/player.gd" type="Script" id=1] # Godot 3++ [autoload]+ Events="*res://global/events.gd"++ [application]+ run/main_scene="res://scenes/run/run.tscn"++ [plugin]+ script="plugin.gd"++so a regex is the right rung and no second tree-sitter grammar is needed. One+extractor covers all three file shapes because the section names disambiguate+them without a filename: ``[ext_resource]`` appears only in a scene or+resource, ``[autoload]`` / ``[application]`` only in ``project.godot``,+``[plugin]`` only in a ``plugin.cfg``.++**Invariant ``graph_warmups._warmup_godot`` depends on:** every import this+extractor emits from a ``project.godot`` or a ``plugin.cfg`` is a declaration+that the *engine* starts there: an ``[autoload]`` singleton it instantiates+before the first scene, the ``run/main_scene`` it boots into, or the+``EditorPlugin`` subclass the editor loads when the plugin is enabled. The+warmup stamps those files' resolved imports as entry points wholesale rather+than re-reading and re-parsing them. Adding a key here that is not an+execution start means teaching the warmup to tell them apart.++``plugin.cfg``'s ``script`` is relative to the plugin's own directory, not+``res://``; the resolver's importer-relative fallback covers that. It matters+most for a repo that *publishes* an addon (``dialogic``): the ``EditorPlugin``+is then the only declared entry point it has.++``script = ExtResource("1_4s751")`` on a node needs no handling of its own:+it dereferences an id whose ``[ext_resource]`` header already carries the path.++A scene's ``[ext_resource]`` list also names every texture, sound and font the+scene uses, thousands per repo, so it is filtered here to+``resolvers.gdscript.GODOT_CODE_SUFFIXES``. That is a **whitelist**, unlike+the ``.gd`` side, which drops assets only on the resolver's miss path: a+reference this list does not recognise (Godot 3's ``.shader``, GDNative's+``.gdns``, the binary ``.scn`` / ``.res`` forms) vanishes from a scene with no+edge and no external node, where the same reference in a ``preload`` would+survive as an external node. Documented in ``LANGUAGE_SUPPORT.md``; widening+the list is the fix if one of those turns up in a real repo.++Known ceilings, all recorded as absent edges rather than guesses:++* Godot 4.4 may write ``uid="uid://..."`` with no ``path=``. Resolving one+ needs the generated ``.uid`` sidecars the spec blocks from indexing. Not+ observed on the validation corpus. An independent ``grep`` over the four+ repos counted 1150 ``[ext_resource`` lines and 1150 carrying ``path=``.+ (This module cannot establish that itself: its pattern only matches lines+ that have ``path=``, so a path-less header is invisible to it.)+* An autoload registered programmatically,+ ``add_autoload_singleton("Foo", "res://foo.gd")`` from an ``EditorPlugin``,+ which is how ``dialogic`` installs itself, appears in no ``[autoload]``+ table and cannot be seen here.+* ``project.godot``'s ``[editor_plugins] enabled=`` is not read, so there is+ no project → ``plugin.cfg`` edge. It names ``.cfg`` files, which carry no+ code; the plugin's *script* is reached from the ``plugin.cfg`` itself.+"""++from __future__ import annotations++import re++from ..models import Import++# A whitelist here; the .gd path uses an asset blacklist on the resolver's+# miss path instead. The two agree on the case that matters (a `.png` gets no+# edge either way) and differ on an unrecognised suffix -- see the docstring.+from ..resolvers.gdscript import GODOT_CODE_SUFFIXES++# An ext_resource *header* line. Attribute order varies between Godot 3 and 4,+# so this scans the whole header for `path=` rather than assuming a position.+# The editor writes double quotes; single quotes are accepted because a+# hand-edited or tool-generated scene may use them, and the backreference+# keeps the pair matched.+_EXT_RESOURCE_RE = re.compile(+ r"""^\[ext_resource\b[^\]]*?\bpath\s*=\s*(["'])(.+?)\1"""+)++# A bare section header: `[autoload]`, `[application]`. Deliberately anchored+# and closed so it cannot match an `[ext_resource ...]` header, which carries+# attributes after the name.+_SECTION_RE = re.compile(r"^\[([A-Za-z_][\w.]*)\]\s*$")++# `Events="*res://global/events.gd"`. The leading `*` marks the entry as an+# enabled singleton; it is not part of the path.+_AUTOLOAD_RE = re.compile(r'^\s*[\w.]+\s*=\s*"\*?([^"]+)"')++# `run/main_scene="res://scenes/run/run.tscn"`: the scene the engine loads at+# boot, and the only key in [application] that names a file with code in it.+_MAIN_SCENE_RE = re.compile(r'^\s*run/main_scene\s*=\s*"([^"]+)"')++# `script="plugin.gd"` in a plugin.cfg. Keyed by name rather than by position+# because [plugin] also carries name/description/author/version.+_PLUGIN_SCRIPT_RE = re.compile(r'^\s*script\s*=\s*"([^"]+)"')++# A `key="…` line whose quote never closes: the value continues onto the next+# line. Godot writes these -- dialogic's plugin.cfg description runs to two+# lines, one of which is a bare URL. Every line until the closing quote has to+# be skipped wholesale, or a description containing a line that is exactly+# `[b]` or `[center]` (legal BBCode, and a perfect _SECTION_RE match) would+# silently move the parser out of [plugin] and lose the `script` key below it.+_OPENS_UNCLOSED_VALUE = re.compile(r'^\s*[\w./]+\s*=\s*"[^"]*$')+++def _is_code_path(path: str) -> bool:+ # Case-insensitive to match the resolver's asset test, which lowercases.+ return path.lower().endswith(GODOT_CODE_SUFFIXES)+++def extract_godot_imports(text: str) -> list[Import]:+ """Return one ``Import`` per script/scene/resource this file references."""+ raw: list[tuple[str, str]] = []++ section = ""+ in_multiline_value = False+ # A UTF-8 BOM would otherwise make line 1 `[plugin]`, which no+ # pattern here matches -- losing the whole file's first section.+ for line in text.lstrip("").splitlines():+ if in_multiline_value:+ in_multiline_value = '"' not in line+ continue+ if _OPENS_UNCLOSED_VALUE.match(line):+ in_multiline_value = True+ continue+ ext_resource = _EXT_RESOURCE_RE.match(line)+ if ext_resource is not None:+ raw.append(("ext_resource", ext_resource.group(2)))+ continue+ header = _SECTION_RE.match(line)+ if header is not None:+ section = header.group(1)+ continue+ if section == "autoload":+ autoload = _AUTOLOAD_RE.match(line)+ if autoload is not None:+ raw.append(("autoload", autoload.group(1)))+ elif section == "application":+ main_scene = _MAIN_SCENE_RE.match(line)+ if main_scene is not None:+ raw.append(("run/main_scene", main_scene.group(1)))+ elif section == "plugin":+ script = _PLUGIN_SCRIPT_RE.match(line)+ if script is not None:+ raw.append(("plugin script", script.group(1)))++ imports: list[Import] = []+ seen: set[str] = set()+ for kind, path in raw:+ if not _is_code_path(path) or path in seen:+ continue+ seen.add(path)+ imports.append(+ Import(+ raw_statement=f'{kind}: "{path}"',+ module_path=path,+ imported_names=[],+ # `res://` is absolute from the Godot project root, never+ # relative to the referencing file. See resolvers/gdscript.py.+ is_relative=False,+ resolved_file=None,+ )+ )+ return importsdiff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.pyindex fa9b4282f..f9cb442cc 100644--- a/packages/core/src/repowise/core/ingestion/models.py+++ b/packages/core/src/repowise/core/ingestion/models.py@@ -80,6 +80,10 @@ LanguageTag = Literal["html",# Lightweight: qmldir-declared module imports and quoted references."qml",+ # Godot .tscn/.tres/.escn + project.godot: data with no symbols, but+ # [ext_resource path=...] and [autoload] are how a Godot project reaches+ # its scripts at all.+ "godot_resource","unknown",]diff --git a/packages/core/src/repowise/core/ingestion/resolvers/__init__.py b/packages/core/src/repowise/core/ingestion/resolvers/__init__.pyindex faca7a508..593340546 100644--- a/packages/core/src/repowise/core/ingestion/resolvers/__init__.py+++ b/packages/core/src/repowise/core/ingestion/resolvers/__init__.py@@ -52,6 +52,9 @@ _RESOLVERS: dict[str, ResolverFn] = {"luau": resolve_luau_import,# res:// resolved against the nearest project.godot, not the repo root."gdscript": resolve_gdscript_import,+ # .tscn/.tres/.escn and project.godot name their dependencies with the+ # same res:// paths a .gd file does, so they share the resolver.+ "godot_resource": resolve_gdscript_import,"ruby": resolve_ruby_import,"csharp": resolve_csharp_import,"swift": resolve_swift_import,diff --git a/packages/core/src/repowise/core/ingestion/resolvers/gdscript.py b/packages/core/src/repowise/core/ingestion/resolvers/gdscript.pyindex 56b573d5c..432674125 100644--- a/packages/core/src/repowise/core/ingestion/resolvers/gdscript.py+++ b/packages/core/src/repowise/core/ingestion/resolvers/gdscript.py@@ -25,12 +25,17 @@ of ``res://`` when the project boundary is not declared.Unresolved paths are deliberately NOT stem-matched onto a same-named fileelsewhere in the repo: ``res://`` is exact by construction, so a miss meansthe target genuinely is not indexed, and a wrong edge is worse than none.-They fall through to ``add_external_node`` so the reference still shows up.+They fall through to ``add_external_node`` so the reference still shows up,+unless the path names an art or data asset, which yields nothing at all; see+:data:`GODOT_CODE_SUFFIXES`.++Shared with ``godot_resource`` (``.tscn`` / ``.tres`` / ``.escn`` and+``project.godot``): those files name their dependencies with the same+``res://`` paths, so they dispatch to the same function."""from __future__ import annotations-import refrom pathlib import PurePosixPathfrom repowise.core.fs_walk import iter_glob@@ -49,6 +54,35 @@ _UID_PREFIX = "uid://"# points at a repo file._USER_PREFIX = "user://"+#: Suffixes a Godot resource reference must carry for the *scene* extractor to+#: record it at all: a script, a scene, a resource instance (whose own+#: ``[ext_resource]`` list names the script implementing it), or a shader.+#:+#: A scene's ``[ext_resource]`` list mixes those with every texture, sound and+#: font the scene uses, thousands per repo, so it is filtered at extraction.+#: A script's ``preload`` is filtered here instead, and only on the miss path;+#: see :func:`_is_asset`.+GODOT_CODE_SUFFIXES: tuple[str, ...] = (".gd", ".cs", ".tscn", ".tres", ".escn", ".gdshader")++# Suffixes that name art or bulk data. Consulted ONLY when a reference has+# already failed to match an indexed file, so an indexed `.json` data table+# still gets its edge; this decides whether a *miss* is worth an external+# node. On the validation corpus 114 of Pixelorama's `res://` script+# references are .png/.svg/.ttf, and minting an external node each would put+# the repo's whole art tree in the dependency graph. Same call+# `lightweight_imports/html.py` makes for `<img src>`.+_ASSET_SUFFIXES: frozenset[str] = frozenset({+ ".png", ".jpg", ".jpeg", ".svg", ".webp", ".bmp", ".tga", ".exr", ".hdr",+ ".ktx", ".dds", ".ogg", ".wav", ".mp3", ".ttf", ".otf", ".woff", ".woff2",+ ".fnt", ".obj", ".glb", ".gltf", ".dae", ".blend", ".json", ".csv", ".txt",+ ".po", ".pot", ".translation", ".theme", ".cfg", ".webm", ".ogv",+})+++def _is_asset(path: str) -> bool:+ """True when *path* names an art/data asset rather than code."""+ return PurePosixPath(path).suffix.lower() in _ASSET_SUFFIXES+def _project_roots(ctx: ResolverContext) -> tuple[str, ...]:"""Repo-relative POSIX dirs holding a ``project.godot``, longest first.@@ -84,8 +118,13 @@ def _project_roots(ctx: ResolverContext) -> tuple[str, ...]:return result-def _root_for(importer_path: str, ctx: ResolverContext) -> str:- """Return the repo-relative project root governing *importer_path*."""+def godot_project_root(importer_path: str, ctx: ResolverContext) -> str:+ """Return the repo-relative project root governing *importer_path*.++ Public because ``res://`` is not the only per-project namespace Godot+ keeps: ``framework_edges/godot.py`` scopes the ``class_name`` global table+ the same way, and for the same reason (see ``_project_roots``).+ """for root in _project_roots(ctx):if not root:return ""@@ -106,21 +145,36 @@ def resolve_gdscript_import(return Noneif raw.startswith(_UID_PREFIX) or raw.startswith(_USER_PREFIX):- return ctx.add_external_node(raw)+ return _miss(raw, ctx)if raw.startswith(_RES_PREFIX):relative = raw[len(_RES_PREFIX) :].lstrip("/")- root = _root_for(importer_path, ctx)+ root = godot_project_root(importer_path, ctx)candidate = f"{root}/{relative}" if root else relativeif candidate in ctx.path_set:return candidate- return ctx.add_external_node(raw)+ return _miss(raw, ctx)# Godot also accepts a path relative to the importing script.candidate = _join_relative(PurePosixPath(importer_path).parent, raw)if candidate is not None and candidate in ctx.path_set:return candidate+ return _miss(raw, ctx)+++def _miss(raw: str, ctx: ResolverContext) -> str | None:+ """What an unmatched reference becomes: an external node, or nothing.++ Reached only once *raw* has failed to match an indexed file, so an+ in-repo ``.json`` data table keeps its real edge and only a genuine miss+ is judged here. An art asset yields nothing at all; anything else stays+ visible as an external node, because "we do not recognise this" is not+ "this is art" (``.gdshader`` is the case that matters: out of scope, but+ a real dependency).+ """+ if _is_asset(raw):+ return Nonereturn ctx.add_external_node(raw)@@ -146,104 +200,3 @@ def _join_relative(base: PurePosixPath, relative: str) -> str | None:elif segment not in ("", "."):parts.append(segment)return "/".join(parts)---# ----------------------------------------------------------------------------# Engine-loaded scripts-# ----------------------------------------------------------------------------# Godot reaches a script two ways that are not imports and so leave no edge in-# the graph: an ``[autoload]`` entry in project.godot registers it as a global-# singleton, and a scene attaches it to a node, saved in the .tscn as a-# ``Script`` ext_resource. Read here so the dead-code pass does not report-# every gameplay script in a Godot project as unreachable.--# `[ext_resource type="Script" uid="uid://..." path="res://player.gd" id="5"]`.-# Matched on the path suffix rather than on `type="Script"`: attribute order is-# not fixed, a Godot 3 scene may omit the type, and a `.gd` ext_resource is a-# script whatever the header says. The editor writes double quotes; single-# quotes are accepted because a hand-edited or tool-generated scene may use-# them and the backreference keeps the pair matched.-_SCRIPT_RESOURCE_RE = re.compile(- r"""\[ext_resource\b[^\]]*?\bpath=(["'])(res://.+?\.gd)\1"""-)--_AUTOLOAD_SECTION = "[autoload]"---def _resolve_res(raw: str, owner_path: str, ctx: ResolverContext) -> str | None:- """Return the indexed path *raw* names, or None if it is not indexed.-- Unlike :func:`resolve_gdscript_import` this never records an external- node: a scene referencing an asset outside the index is not a dependency- anyone asked to see, it is just a path that does not resolve.- """- relative = raw[len(_RES_PREFIX) :].lstrip("/")- root = _root_for(owner_path, ctx)- candidate = f"{root}/{relative}" if root else relative- return candidate if candidate in ctx.path_set else None---def _rel_posix(path, ctx: ResolverContext) -> str | None:- if ctx.repo_path is None:- return None- try:- return path.relative_to(ctx.repo_path).as_posix()- except ValueError:- return None---def engine_loaded_scripts(- ctx: ResolverContext,-) -> tuple[frozenset[str], frozenset[str]]:- """Return ``(autoload singletons, scene-attached scripts)``.-- Both are sets of indexed repo-relative paths. A path that resolves to a- file the index does not hold is dropped rather than guessed at, the same- rule the import resolver follows.- """- if ctx.repo_path is None:- return frozenset(), frozenset()-- autoloads: set[str] = set()- for manifest in iter_glob(- ctx.repo_path, "project.godot", prune_nested_git=ctx.prune_nested_git- ):- owner = _rel_posix(manifest, ctx)- if owner is None:- continue- try:- text = manifest.read_text(encoding="utf-8", errors="ignore")- except OSError:- continue- in_section = False- for line in text.splitlines():- stripped = line.strip()- if stripped.startswith("["):- in_section = stripped == _AUTOLOAD_SECTION- continue- if not in_section or "=" not in stripped:- continue- # `Global="*res://autoload/global.gd"` -- the leading `*` marks the- # singleton as enabled and is not part of the path.- value = stripped.split("=", 1)[1].strip().strip('"').lstrip("*")- if not value.startswith(_RES_PREFIX) or not value.endswith(".gd"):- continue- resolved = _resolve_res(value, owner, ctx)- if resolved is not None:- autoloads.add(resolved)-- scene_scripts: set[str] = set()- for scene in iter_glob(ctx.repo_path, "*.tscn", prune_nested_git=ctx.prune_nested_git):- owner = _rel_posix(scene, ctx)- if owner is None:- continue- try:- text = scene.read_text(encoding="utf-8", errors="ignore")- except OSError:- continue- for match in _SCRIPT_RESOURCE_RE.finditer(text):- resolved = _resolve_res(match.group(2), owner, ctx)- if resolved is not None:- scene_scripts.add(resolved)-- return frozenset(autoloads), frozenset(scene_scripts)diff --git a/tests/unit/ingestion/test_gdscript_resolver.py b/tests/unit/ingestion/test_gdscript_resolver.pyindex d9e3b4ed3..a8b35d11a 100644--- a/tests/unit/ingestion/test_gdscript_resolver.py+++ b/tests/unit/ingestion/test_gdscript_resolver.py@@ -23,10 +23,7 @@ from pathlib import Pathimport networkx as nxfrom repowise.core.ingestion.resolvers.context import ResolverContext-from repowise.core.ingestion.resolvers.gdscript import (- engine_loaded_scripts,- resolve_gdscript_import,-)+from repowise.core.ingestion.resolvers.gdscript import resolve_gdscript_importdef _ctx(paths: set[str], repo_path: Path | None = None) -> ResolverContext:@@ -166,70 +163,3 @@ class TestProjectRootScanIsCached:# than repeated per import (this runs once per file per build).(tmp_path / "game" / "project.godot").unlink()assert resolve_gdscript_import("res://b.gd", "game/a.gd", ctx) == "game/b.gd"---AUTOLOAD_MANIFEST = """\-config_version=5--[autoload]--Global="*res://autoload/global.gd"-Music="res://autoload/music.gd"-Scene="*res://autoload/hud.tscn"-Missing="*res://autoload/gone.gd"-"""--SCENE = """\-[gd_scene format=3 uid="uid://dxq1b4cth265d"]--[ext_resource type="Script" uid="uid://e3f" path="res://bullets.gd" id="2"]-[ext_resource type="Texture2D" path="res://face.png" id="3"]-[ext_resource type="Script" path="res://absent.gd" id="4"]-[ext_resource type="Script" uid="uid://n0path" id="5"]-"""--SINGLE_QUOTED_SCENE = """\-[gd_scene format=3]--[ext_resource type='Script' path='res://bullets.gd' id='2']-"""---class TestEngineLoadedScripts:- """The two ways Godot reaches a script without importing it."""-- def test_autoload_entries_resolve_against_their_own_project(self, tmp_path: Path) -> None:- _write_project(tmp_path, "game")- (tmp_path / "game" / "project.godot").write_text(AUTOLOAD_MANIFEST, encoding="utf-8")- ctx = _ctx(- {"game/autoload/global.gd", "game/autoload/music.gd", "game/player.gd"},- repo_path=tmp_path,- )- autoloads, scenes = engine_loaded_scripts(ctx)- # The leading `*` marks a singleton as enabled and is not part of the- # path. `gone.gd` is not indexed and `hud.tscn` is not a script:- # neither is guessed at, the rule the import resolver follows.- assert autoloads == frozenset({"game/autoload/global.gd", "game/autoload/music.gd"})- assert scenes == frozenset()-- def test_scene_script_resources_are_collected(self, tmp_path: Path) -> None:- _write_project(tmp_path, "game")- (tmp_path / "game" / "shower.tscn").write_text(SCENE, encoding="utf-8")- ctx = _ctx({"game/bullets.gd", "game/other.gd"}, repo_path=tmp_path)- autoloads, scenes = engine_loaded_scripts(ctx)- assert autoloads == frozenset()- # `absent.gd` is not indexed, `face.png` is not a script, and the- # `uid://`-only entry carries no path to resolve.- assert scenes == frozenset({"game/bullets.gd"})-- def test_single_quoted_paths_are_accepted(self, tmp_path: Path) -> None:- _write_project(tmp_path, "game")- (tmp_path / "game" / "hand_edited.tscn").write_text(- SINGLE_QUOTED_SCENE, encoding="utf-8"- )- ctx = _ctx({"game/bullets.gd"}, repo_path=tmp_path)- assert engine_loaded_scripts(ctx)[1] == frozenset({"game/bullets.gd"})-- def test_no_godot_project_yields_nothing(self, tmp_path: Path) -> None:- ctx = _ctx({"a.gd"}, repo_path=tmp_path)- assert engine_loaded_scripts(ctx) == (frozenset(), frozenset())diff --git a/tests/unit/ingestion/test_godot_project_awareness.py b/tests/unit/ingestion/test_godot_project_awareness.pynew file mode 100644index 000000000..54a7c34c0--- /dev/null+++ b/tests/unit/ingestion/test_godot_project_awareness.py@@ -0,0 +1,818 @@+"""Unit tests for Godot project awareness.++Four mechanisms, none of which needs the ``tree_sitter_gdscript`` grammar+except where a test parses real GDScript:++1. ``lightweight_imports/godot.py``: ``[ext_resource]`` / ``[autoload]`` /+ ``run/main_scene`` / ``plugin.cfg`` ``script`` extraction.+2. ``graph_warmups._warmup_godot``: engine-invoked entry points, and the+ ``addons/`` vendoring rule.+3. ``framework_edges/godot.py``: a scene's ``[connection]`` blocks, resolved+ through the node tree to the handler method they name.+4. ``framework_edges/godot.py``: ``class_name`` global-registry edges.++The dead-code side (Godot engine callbacks) is covered at the bottom against+:func:`is_contract_method` directly, matching how the JVM and C++ contract+sets are tested.+"""++from __future__ import annotations++from datetime import datetime+from pathlib import Path+from types import SimpleNamespace++import networkx as nx++from repowise.core.analysis.dead_code.contract_methods import is_contract_method+from repowise.core.ingestion.framework_edges import DetectionContext, add_framework_edges+from repowise.core.ingestion.framework_edges import godot as godot_edges+from repowise.core.ingestion.graph_warmups import _warmup_godot+from repowise.core.ingestion.languages.registry import REGISTRY+from repowise.core.ingestion.lightweight_imports import extract_lightweight_imports+from repowise.core.ingestion.lightweight_imports.godot import extract_godot_imports+from repowise.core.ingestion.models import FileInfo+from repowise.core.ingestion.resolvers import resolve_import+from repowise.core.ingestion.resolvers.context import ResolverContext++# ---------------------------------------------------------------------------+# Fixtures / helpers+# ---------------------------------------------------------------------------++SCENE = """\+[gd_scene load_steps=4 format=3 uid="uid://cahno8aso5net"]++[ext_resource type="Script" path="res://scenes/battle/battle.gd" id="1_4s751"]+[ext_resource type="Texture2D" uid="uid://cp4iq" path="res://art/background.png" id="1_ybkl6"]+[ext_resource type="PackedScene" path="res://scenes/enemy/enemy.tscn" id="2_02s5s"]+[ext_resource type="Resource" path="res://characters/warrior.tres" id="4_fwb8a"]++[node name="Battle" type="Node2D"]+script = ExtResource("1_4s751")+"""++PROJECT_GODOT = """\+; Engine configuration file.+config_version=5++[application]++config/name="Deck Builder"+run/main_scene="res://scenes/run/run.tscn"+config/icon="res://icon.png"++[autoload]++Events="*res://global/events.gd"+MusicPlayer="*res://global/music_player.tscn"+Keychain="*uid://dgiia2xg7fsud"++[display]++window/size/viewport_width=256+"""++PLUGIN_CFG = """\+[plugin]++name="Dialogic"+description="Create dialogs and characters."+author="Jowan"+version="2.0"+script="plugin.gd"+"""+++def _paths(imports) -> list[str]:+ return [imp.module_path for imp in imports]+++def _file_info(rel: str, language: str, abs_path: str = "") -> FileInfo:+ return FileInfo(+ path=rel,+ abs_path=abs_path or rel,+ language=language, # type: ignore[arg-type]+ size_bytes=0,+ git_hash="",+ last_modified=datetime.now(),+ is_test=False,+ is_config=False,+ is_api_contract=False,+ is_entry_point=False,+ )+++def _ctx(paths: set[str], repo_path: Path | None = None, **kwargs) -> ResolverContext:+ graph = kwargs.pop("graph", None) or nx.DiGraph()+ return ResolverContext(+ path_set=paths, stem_map={}, graph=graph, repo_path=repo_path, **kwargs+ )+++# ---------------------------------------------------------------------------+# 1. Extraction+# ---------------------------------------------------------------------------+++class TestSceneExtraction:+ def test_ext_resource_scripts_scenes_and_resources(self) -> None:+ assert _paths(extract_godot_imports(SCENE)) == [+ "res://scenes/battle/battle.gd",+ "res://scenes/enemy/enemy.tscn",+ "res://characters/warrior.tres",+ ]++ def test_art_assets_are_dropped(self) -> None:+ # background.png sits in the same [ext_resource] list and is not code.+ assert "res://art/background.png" not in _paths(extract_godot_imports(SCENE))++ def test_godot_3_attribute_order(self) -> None:+ line = '[ext_resource path="res://a.gd" type="Script" id=1]\n'+ assert _paths(extract_godot_imports(line)) == ["res://a.gd"]++ def test_single_quoted_path(self) -> None:+ # The editor writes double quotes; a hand-edited or tool-generated+ # scene may use single ones.+ line = "[ext_resource type='Script' path='res://a.gd' id='2']\n"+ assert _paths(extract_godot_imports(line)) == ["res://a.gd"]++ def test_uid_only_ext_resource_yields_nothing(self) -> None:+ # Godot 4.4 may omit path=. Documented ceiling, recorded as no edge+ # rather than a guess.+ line = '[ext_resource type="Script" uid="uid://bxyz" id="1_a"]\n'+ assert extract_godot_imports(line) == []++ def test_script_extresource_reference_is_not_a_second_edge(self) -> None:+ # `script = ExtResource("1_4s751")` dereferences the header above it.+ assert _paths(extract_godot_imports(SCENE)).count("res://scenes/battle/battle.gd") == 1+++class TestProjectGodotExtraction:+ def test_autoloads_and_main_scene(self) -> None:+ assert _paths(extract_godot_imports(PROJECT_GODOT)) == [+ "res://scenes/run/run.tscn",+ "res://global/events.gd",+ "res://global/music_player.tscn",+ ]++ def test_singleton_star_prefix_is_stripped(self) -> None:+ assert not any(p.startswith("*") for p in _paths(extract_godot_imports(PROJECT_GODOT)))++ def test_uid_autoload_is_skipped_by_the_suffix_filter(self) -> None:+ # `Keychain="*uid://…"` carries no suffix we recognise as code, so it+ # produces no import. Documented ceiling.+ assert not any("uid://" in p for p in _paths(extract_godot_imports(PROJECT_GODOT)))++ def test_only_main_scene_is_read_from_the_application_section(self) -> None:+ # `config/icon` and `config/name` sit in the same section; the key+ # match, not the suffix filter, is what excludes them.+ assert _paths(extract_godot_imports(PROJECT_GODOT)) == [+ "res://scenes/run/run.tscn",+ "res://global/events.gd",+ "res://global/music_player.tscn",+ ]++ def test_a_section_we_do_not_read_contributes_nothing(self) -> None:+ # [display]'s `window/size/viewport_width=256` is key=value shaped and+ # would match _AUTOLOAD_RE if the section gate were not doing its job.+ with_display = PROJECT_GODOT.replace(+ '[display]', '[display]\n\nfake/path="res://sneaky.gd"'+ )+ assert "res://sneaky.gd" not in _paths(extract_godot_imports(with_display))+++class TestPluginCfgExtraction:+ def test_script_key_only(self) -> None:+ assert _paths(extract_godot_imports(PLUGIN_CFG)) == ["plugin.gd"]++ def test_a_multiline_description_does_not_lose_the_script_key(self) -> None:+ # dialogic's real plugin.cfg: the description runs onto a second line.+ # `script=` is conventionally last, so a parser that mishandles the+ # continuation loses the addon's only entry point.+ multiline = (+ '[plugin]\n\n'+ 'name="Dialogic"\n'+ 'description="Create dialogs and characters.\n'+ 'https://github.com/dialogic-godot/dialogic"\n'+ 'author="Jowan"\n'+ 'script="plugin.gd"\n'+ )+ assert _paths(extract_godot_imports(multiline)) == ["plugin.gd"]++ def test_bbcode_in_a_description_cannot_close_the_plugin_section(self) -> None:+ # `[b]` on its own line is legal BBCode inside a description and is a+ # perfect bare-section-header match.+ bbcode = (+ '[plugin]\n\n'+ 'description="Bold:\n'+ '[b]\n'+ 'done."\n'+ 'script="plugin.gd"\n'+ )+ assert _paths(extract_godot_imports(bbcode)) == ["plugin.gd"]++ def test_a_utf8_bom_does_not_hide_the_first_section(self) -> None:+ assert _paths(extract_godot_imports("" + PLUGIN_CFG)) == ["plugin.gd"]++ def test_crlf_line_endings(self) -> None:+ assert _paths(extract_godot_imports(PLUGIN_CFG.replace("\n", "\r\n"))) == [+ "plugin.gd"+ ]+++class TestDispatch:+ def test_registered_for_the_godot_resource_tag(self) -> None:+ imports = extract_lightweight_imports(+ _file_info("scenes/battle.tscn", "godot_resource"), SCENE.encode()+ )+ assert _paths(imports) == [+ "res://scenes/battle/battle.gd",+ "res://scenes/enemy/enemy.tscn",+ "res://characters/warrior.tres",+ ]++ def test_extensions_and_special_filenames_map_to_the_tag(self) -> None:+ for ext in (".tscn", ".tres", ".escn"):+ assert REGISTRY.from_extension(ext) == "godot_resource"+ assert REGISTRY.from_filename("project.godot") == "godot_resource"+ assert REGISTRY.from_filename("plugin.cfg") == "godot_resource"++ def test_scenes_share_the_gdscript_resolver(self, tmp_path: Path) -> None:+ (tmp_path / "project.godot").write_text("config_version=5\n", encoding="utf-8")+ ctx = _ctx({"scenes/battle.tscn", "scenes/battle/battle.gd"}, repo_path=tmp_path)+ got = resolve_import(+ "res://scenes/battle/battle.gd", "scenes/battle.tscn", "godot_resource", ctx+ )+ assert got == "scenes/battle/battle.gd"++ def test_plugin_cfg_script_resolves_relative_to_its_own_directory(+ self, tmp_path: Path+ ) -> None:+ ctx = _ctx({"addons/dialogic/plugin.cfg", "addons/dialogic/plugin.gd"}, repo_path=tmp_path)+ got = resolve_import("plugin.gd", "addons/dialogic/plugin.cfg", "godot_resource", ctx)+ assert got == "addons/dialogic/plugin.gd"++ def test_asset_paths_yield_no_edge_at_all(self, tmp_path: Path) -> None:+ # Not an external node either: a .png in the dependency graph says+ # nothing about how the code fits together.+ ctx = _ctx({"actors/player.gd"}, repo_path=tmp_path)+ assert resolve_import("res://art/icon.png", "actors/player.gd", "gdscript", ctx) is None+ assert not list(ctx.graph.nodes())++ def test_an_indexed_data_file_still_gets_its_edge(self, tmp_path: Path) -> None:+ # `.json` is on the asset list AND is a language repowise indexes. The+ # asset filter decides what a *miss* becomes, so it must not fire+ # before the path_set lookup.+ ctx = _ctx({"actors/player.gd", "data/cards.json"}, repo_path=tmp_path)+ got = resolve_import("res://data/cards.json", "actors/player.gd", "gdscript", ctx)+ assert got == "data/cards.json"++ def test_an_unrecognised_suffix_stays_visible_as_an_external_node(+ self, tmp_path: Path+ ) -> None:+ # .gdshader is out of scope but is a real dependency, unlike art.+ ctx = _ctx({"actors/player.gd"}, repo_path=tmp_path)+ got = resolve_import("res://fx/wave.gdshader", "actors/player.gd", "gdscript", ctx)+ assert got == "external:res://fx/wave.gdshader"+++# ---------------------------------------------------------------------------+# 2. Warmup: entry points and addons/ vendoring+# ---------------------------------------------------------------------------+++def _warmup_ctx(tmp_path: Path, files: dict[str, str]) -> ResolverContext:+ """Write *files*, build a file-node graph, and return a wired context."""+ parsed = {}+ graph = nx.DiGraph()+ for rel, text in files.items():+ abs_path = tmp_path / rel+ abs_path.parent.mkdir(parents=True, exist_ok=True)+ abs_path.write_text(text, encoding="utf-8")+ language = (+ "godot_resource"+ if rel.endswith((".tscn", ".tres", ".escn", "project.godot", "plugin.cfg"))+ else "gdscript"+ )+ fi = _file_info(rel, language, str(abs_path))+ parsed[rel] = SimpleNamespace(+ file_info=fi,+ imports=extract_godot_imports(text) if language == "godot_resource" else [],+ )+ graph.add_node(rel, node_type="file")+ return _ctx(set(files), repo_path=tmp_path, graph=graph, parsed_files=parsed)+++class TestWarmupEntryPoints:+ def test_autoloads_and_main_scene_are_entry_points(self, tmp_path: Path) -> None:+ ctx = _warmup_ctx(+ tmp_path,+ {+ "project.godot": PROJECT_GODOT,+ "global/events.gd": "extends Node\n",+ "global/music_player.tscn": "[gd_scene format=3]\n",+ "scenes/run/run.tscn": "[gd_scene format=3]\n",+ "other/helper.gd": "extends Node\n",+ },+ )+ _warmup_godot(ctx)++ stamped = {n for n, d in ctx.graph.nodes(data=True) if d.get("is_entry_point")}+ assert stamped == {+ "global/events.gd",+ "global/music_player.tscn",+ "scenes/run/run.tscn",+ }++ def test_plugin_cfg_script_is_an_entry_point(self, tmp_path: Path) -> None:+ # A repo that *publishes* an addon has no project.godot at all; the+ # EditorPlugin is then its only declared entry point.+ ctx = _warmup_ctx(+ tmp_path,+ {+ "addons/dialogic/plugin.cfg": PLUGIN_CFG,+ "addons/dialogic/plugin.gd": "extends EditorPlugin\n",+ },+ )+ _warmup_godot(ctx)++ assert ctx.graph.nodes["addons/dialogic/plugin.gd"].get("is_entry_point")++ def test_no_manifest_is_a_no_op(self, tmp_path: Path) -> None:+ ctx = _warmup_ctx(tmp_path, {"a.gd": "extends Node\n"})+ _warmup_godot(ctx)+ assert not any(d.get("is_entry_point") for _, d in ctx.graph.nodes(data=True))++ def test_file_info_is_stamped_too(self, tmp_path: Path) -> None:+ # The graph attribute drives dead code; FileInfo drives the wiki's+ # entry-point list, the tour and page selection. Both, or a repo still+ # reports no entry point where a reader looks.+ ctx = _warmup_ctx(+ tmp_path,+ {+ "addons/dialogic/plugin.cfg": PLUGIN_CFG,+ "addons/dialogic/plugin.gd": "extends EditorPlugin\n",+ },+ )+ _warmup_godot(ctx)+ assert ctx.parsed_files["addons/dialogic/plugin.gd"].file_info.is_entry_point++ def test_tolerates_a_context_with_no_parsed_files(self, tmp_path: Path) -> None:+ ctx = _warmup_ctx(tmp_path, {"project.godot": PROJECT_GODOT})+ object.__setattr__(ctx, "parsed_files", None)+ _warmup_godot(ctx) # must not raise+++class TestAddonsVendoring:+ def test_addons_under_a_project_are_vendored(self, tmp_path: Path) -> None:+ # The consumer case: Pixelorama's shape. addons/ is a checked-in+ # node_modules, and its scripts are a third party's public API.+ ctx = _warmup_ctx(+ tmp_path,+ {+ "project.godot": "config_version=5\n",+ "addons/keychain/plugin.gd": "extends EditorPlugin\n",+ "src/Main.gd": "extends Node\n",+ },+ )+ _warmup_godot(ctx)++ assert ctx.graph.nodes["addons/keychain/plugin.gd"].get("is_never_flag")+ assert not ctx.graph.nodes["src/Main.gd"].get("is_never_flag")++ def test_addons_with_no_enclosing_project_are_first_party(self, tmp_path: Path) -> None:+ # The publisher case: dialogic's shape, where 97% of the source lives+ # under addons/ and blanket-vendoring would erase the whole repo.+ ctx = _warmup_ctx(+ tmp_path,+ {+ "addons/dialogic/plugin.cfg": PLUGIN_CFG,+ "addons/dialogic/plugin.gd": "extends EditorPlugin\n",+ },+ )+ _warmup_godot(ctx)++ assert not ctx.graph.nodes["addons/dialogic/plugin.gd"].get("is_never_flag")++ def test_a_project_in_a_sibling_directory_does_not_vendor(self, tmp_path: Path) -> None:+ # The rule is pure ancestry, not a "is this a CI fixture" judgement.+ # dialogic's only project.godot sits under .github/workflows/resources/,+ # which encloses nothing, so its own addons/ stays first-party.+ ctx = _warmup_ctx(+ tmp_path,+ {+ ".github/workflows/resources/project.godot": "config_version=5\n",+ "addons/dialogic/plugin.gd": "extends EditorPlugin\n",+ },+ )+ _warmup_godot(ctx)++ assert not ctx.graph.nodes["addons/dialogic/plugin.gd"].get("is_never_flag")++ def test_a_nested_project_vendors_only_its_own_addons(self, tmp_path: Path) -> None:+ # godot-gamejam keeps its project under godot/.+ ctx = _warmup_ctx(+ tmp_path,+ {+ "godot/project.godot": "config_version=5\n",+ "godot/addons/tool/tool.gd": "extends Node\n",+ "addons/unrelated/other.gd": "extends Node\n",+ },+ )+ _warmup_godot(ctx)++ assert ctx.graph.nodes["godot/addons/tool/tool.gd"].get("is_never_flag")+ assert not ctx.graph.nodes["addons/unrelated/other.gd"].get("is_never_flag")+++# ---------------------------------------------------------------------------+# 3. Scene signal connections+# ---------------------------------------------------------------------------+++def _connection_edges(tmp_path: Path, files: dict[str, str]) -> nx.DiGraph:+ """Build the graph a scene's ``[connection]`` blocks should wire up.++ Scripts get one symbol node per ``func``, the way the parser emits them,+ because ``add_symbol_edge`` refuses an end that is not already a symbol.+ """+ parsed = {}+ graph = nx.DiGraph()+ for rel, text in files.items():+ abs_path = tmp_path / rel+ abs_path.parent.mkdir(parents=True, exist_ok=True)+ abs_path.write_text(text, encoding="utf-8")+ language = "gdscript" if rel.endswith(".gd") else "godot_resource"+ symbols = []+ if language == "gdscript":+ for line in text.splitlines():+ if line.startswith("func "):+ name = line[5:].split("(", 1)[0].strip()+ sym_id = f"{rel}::{name}"+ symbols.append(+ SimpleNamespace(id=sym_id, name=name, kind="function")+ )+ graph.add_node(sym_id, node_type="symbol")+ parsed[rel] = SimpleNamespace(+ file_info=_file_info(rel, language, str(abs_path)),+ imports=[],+ symbols=symbols,+ )+ graph.add_node(rel, node_type="file")+ graph.add_node(f"{rel}::__module__", node_type="symbol")+ ctx = _ctx(set(files), repo_path=tmp_path, graph=graph, parsed_files=parsed)+ add_framework_edges(graph, parsed, ctx)+ return graph+++ROOT_SCRIPT_SCENE = """\+[gd_scene format=3]++[ext_resource type="Script" path="res://hud.gd" id="1"]++[node name="HUD" type="CanvasLayer"]+script = ExtResource("1")+[node name="StartButton" type="Button" parent="."]++[connection signal="pressed" from="StartButton" to="." method="_on_start_pressed"]+"""++CHILD_SCRIPT_SCENE = """\+[gd_scene format=3]++[ext_resource type="Script" path="res://hud.gd" id="1"]+[ext_resource type="Script" path="res://player.gd" id="2"]++[node name="HUD" type="CanvasLayer"]+script = ExtResource("1")+[node name="Player" type="Area2D" parent="."]+script = ExtResource("2")+[node name="Shape" type="CollisionShape2D" parent="Player"]++[connection signal="hit" from="Shape" to="Player" method="_on_hit"]+"""++INHERITED_SCRIPT_SCENE = """\+[gd_scene format=3]++[ext_resource type="Script" path="res://hud.gd" id="1"]++[node name="HUD" type="CanvasLayer"]+script = ExtResource("1")+[node name="Panel" type="Panel" parent="."]+[node name="Deep" type="Button" parent="Panel"]++[connection signal="pressed" from="Deep" to="Panel/Deep" method="_on_start_pressed"]+"""++INSTANCED_ROOT_WITH_SCRIPT_SCENE = """\+[gd_scene format=3]++[ext_resource type="PackedScene" path="res://chat.tscn" id="1"]+[ext_resource type="Script" path="res://hud.gd" id="2"]++[node name="Client" instance=ExtResource("1")]+script = ExtResource("2")++[connection signal="pressed" from="Btn" to="." method="_on_start_pressed"]+"""++INSTANCED_ROOT_SCENE = """\+[gd_scene format=3]++[ext_resource type="PackedScene" path="res://player.tscn" id="1"]++[node name="Player" instance=ExtResource("1")]++[connection signal="hit" from="." to="." method="_on_start_pressed"]+"""++HUD_GD = "extends CanvasLayer\n\nfunc _on_start_pressed() -> void:\n\tpass\n"+PLAYER_GD = "extends Area2D\n\nfunc _on_hit() -> void:\n\tpass\n"+++class TestSceneParsing:+ def test_node_paths_resources_and_connections(self) -> None:+ resources, nodes, connections = godot_edges.parse_scene(CHILD_SCRIPT_SCENE)+ assert resources == {"1": "res://hud.gd", "2": "res://player.gd"}+ assert set(nodes) == {".", "Player", "Player/Shape"}+ assert nodes["."].script_id == "1"+ assert nodes["Player"].script_id == "2"+ assert nodes["Player/Shape"].script_id is None+ assert connections[0]["method"] == "_on_hit"++ def test_godot_3_unquoted_resource_ids(self) -> None:+ text = (+ '[ext_resource path="res://a.gd" type="Script" id=1]\n'+ '[node name="Root" type="Node"]\n'+ "script = ExtResource( 1 )\n"+ )+ resources, nodes, _ = godot_edges.parse_scene(text)+ assert resources == {"1": "res://a.gd"}+ assert nodes["."].script_id == "1"++ def test_the_walk_climbs_to_the_nearest_scripted_ancestor(self) -> None:+ _, nodes, _ = godot_edges.parse_scene(INHERITED_SCRIPT_SCENE)+ assert godot_edges.resolve_handler_node("Panel/Deep", nodes) == ("1", "ok")++ def test_a_missing_node_is_refused(self) -> None:+ _, nodes, _ = godot_edges.parse_scene(ROOT_SCRIPT_SCENE)+ assert godot_edges.resolve_handler_node("Ghost", nodes) == (+ None,+ "node_not_found",+ )++ def test_a_local_script_wins_over_an_instance(self) -> None:+ # An instanced root that overrides the instanced scene's script with+ # its own is the common shape for a scene that customises a reusable+ # one (networking/websocket_chat/client.tscn). The script is right+ # here in this file, so there is nothing to refuse.+ _, nodes, _ = godot_edges.parse_scene(INSTANCED_ROOT_WITH_SCRIPT_SCENE)+ assert nodes["."].instance_id == "1"+ assert godot_edges.resolve_handler_node(".", nodes) == ("2", "ok")++ def test_an_instanced_root_is_refused(self) -> None:+ _, nodes, _ = godot_edges.parse_scene(INSTANCED_ROOT_SCENE)+ assert godot_edges.resolve_handler_node(".", nodes) == (+ None,+ "instanced_scene",+ )++ def test_a_scene_with_no_script_anywhere_is_refused(self) -> None:+ text = '[node name="Root" type="Node"]\n[node name="Kid" parent="."]\n'+ _, nodes, _ = godot_edges.parse_scene(text)+ assert godot_edges.resolve_handler_node("Kid", nodes) == (None, "no_script")+++class TestSceneConnectionEdges:+ def test_root_handler(self, tmp_path: Path) -> None:+ graph = _connection_edges(+ tmp_path, {"hud.tscn": ROOT_SCRIPT_SCENE, "hud.gd": HUD_GD}+ )+ assert graph.has_edge("hud.tscn::__module__", "hud.gd::_on_start_pressed")+ assert (+ graph["hud.tscn::__module__"]["hud.gd::_on_start_pressed"]["edge_type"]+ == "framework_binds"+ )++ def test_child_node_with_its_own_script(self, tmp_path: Path) -> None:+ graph = _connection_edges(+ tmp_path,+ {+ "hud.tscn": CHILD_SCRIPT_SCENE,+ "hud.gd": HUD_GD,+ "player.gd": PLAYER_GD,+ },+ )+ # The handler belongs to the node named by `to`, not to the scene root.+ assert graph.has_edge("hud.tscn::__module__", "player.gd::_on_hit")+ assert not graph.has_edge("hud.tscn::__module__", "hud.gd::_on_start_pressed")++ def test_child_without_a_script_inherits_the_root(self, tmp_path: Path) -> None:+ graph = _connection_edges(+ tmp_path, {"hud.tscn": INHERITED_SCRIPT_SCENE, "hud.gd": HUD_GD}+ )+ assert graph.has_edge("hud.tscn::__module__", "hud.gd::_on_start_pressed")++ def test_a_to_node_that_does_not_exist_gets_no_edge(self, tmp_path: Path) -> None:+ scene = ROOT_SCRIPT_SCENE.replace('to="."', 'to="Ghost"')+ graph = _connection_edges(tmp_path, {"hud.tscn": scene, "hud.gd": HUD_GD})+ assert not graph.has_edge("hud.tscn::__module__", "hud.gd::_on_start_pressed")++ def test_a_method_absent_from_the_script_gets_no_edge(self, tmp_path: Path) -> None:+ scene = ROOT_SCRIPT_SCENE.replace('method="_on_start_pressed"', 'method="_gone"')+ graph = _connection_edges(tmp_path, {"hud.tscn": scene, "hud.gd": HUD_GD})+ # Never matched by name alone: the script has a handler, just not this+ # one, and no other file's `_gone` may stand in for it.+ assert not any(+ t.endswith("::_gone") for _, t in graph.out_edges("hud.tscn::__module__")+ )++ def test_an_instanced_root_with_its_own_script_binds(self, tmp_path: Path) -> None:+ graph = _connection_edges(+ tmp_path,+ {"client.tscn": INSTANCED_ROOT_WITH_SCRIPT_SCENE, "hud.gd": HUD_GD},+ )+ assert graph.has_edge("client.tscn::__module__", "hud.gd::_on_start_pressed")++ def test_an_instanced_root_gets_no_edge(self, tmp_path: Path) -> None:+ graph = _connection_edges(+ tmp_path,+ {+ "main.tscn": INSTANCED_ROOT_SCENE,+ "player.tscn": ROOT_SCRIPT_SCENE,+ "hud.gd": HUD_GD,+ },+ )+ assert not graph.has_edge("main.tscn::__module__", "hud.gd::_on_start_pressed")++ def test_the_handler_needs_a_scene(self, tmp_path: Path) -> None:+ parsed = {+ "a.gd": SimpleNamespace(+ file_info=_file_info("a.gd", "gdscript"), imports=[], symbols=[]+ )+ }+ graph = nx.DiGraph()+ graph.add_node("a.gd", node_type="file")+ ctx = _ctx({"a.gd"}, repo_path=tmp_path, graph=graph, parsed_files=parsed)+ dctx = DetectionContext(+ stack_lower=set(), parsed_files=parsed, ctx=ctx, path_set={"a.gd"}+ )+ assert godot_edges.HANDLERS[1].detect(dctx) is False+++# ---------------------------------------------------------------------------+# 4. class_name global-registry edges+# ---------------------------------------------------------------------------+++def _class_name_edges(tmp_path: Path, files: dict[str, str]) -> nx.DiGraph:+ parsed = {}+ graph = nx.DiGraph()+ for rel, text in files.items():+ abs_path = tmp_path / rel+ abs_path.parent.mkdir(parents=True, exist_ok=True)+ abs_path.write_text(text, encoding="utf-8")+ parsed[rel] = SimpleNamespace(+ file_info=_file_info(rel, "gdscript", str(abs_path)), imports=[], symbols=[]+ )+ graph.add_node(rel, node_type="file")+ ctx = _ctx(set(files), repo_path=tmp_path, graph=graph, parsed_files=parsed)+ add_framework_edges(graph, parsed, ctx)+ return graph+++class TestClassNameEdges:+ def test_global_class_use_creates_a_dependency_edge(self, tmp_path: Path) -> None:+ graph = _class_name_edges(+ tmp_path,+ {+ "custom_resources/effect.gd": "class_name Effect\nextends RefCounted\n",+ "cards/slash.gd": "extends Card\n\nfunc apply() -> void:\n\tvar e := Effect.new()\n",+ },+ )+ assert graph.has_edge("cards/slash.gd", "custom_resources/effect.gd")++ def test_extends_form_with_a_trailing_clause(self, tmp_path: Path) -> None:+ graph = _class_name_edges(+ tmp_path,+ {+ "a.gd": "class_name DamageEffect extends Effect\n",+ "b.gd": "func f():\n\tDamageEffect.new()\n",+ },+ )+ assert graph.has_edge("b.gd", "a.gd")++ def test_an_unused_global_class_gets_no_edge(self, tmp_path: Path) -> None:+ graph = _class_name_edges(+ tmp_path,+ {+ "a.gd": "class_name Unused\nextends Node\n",+ "b.gd": "extends Node\n\nfunc f() -> void:\n\tpass\n",+ },+ )+ assert not graph.has_edge("b.gd", "a.gd")++ def test_the_declaring_file_gets_no_self_edge(self, tmp_path: Path) -> None:+ graph = _class_name_edges(+ tmp_path, {"a.gd": "class_name Effect\n\nfunc f() -> Effect:\n\treturn self\n"}+ )+ assert not graph.has_edge("a.gd", "a.gd")++ def test_an_inner_class_is_not_globally_registered(self, tmp_path: Path) -> None:+ # `class Inner:` is script-local; Godot registers only `class_name`.+ graph = _class_name_edges(+ tmp_path,+ {+ "a.gd": "extends Node\n\nclass Inner:\n\tvar x := 1\n",+ "b.gd": "func f():\n\tvar y = Inner.new()\n",+ },+ )+ assert not graph.has_edge("b.gd", "a.gd")++ def test_class_name_must_start_the_line(self, tmp_path: Path) -> None:+ graph = _class_name_edges(+ tmp_path,+ {+ "a.gd": '\tvar s = "class_name Sneaky"\n',+ "b.gd": "func f():\n\tSneaky.new()\n",+ },+ )+ assert not graph.has_edge("b.gd", "a.gd")++ def test_the_handler_does_not_fire_without_gdscript(self, tmp_path: Path) -> None:+ # Asserting a 0 edge count would pass even if the handler ran, since+ # every handler returns 0 on a one-file Python repo. Assert on detect()+ # itself, which is the gate that actually matters.+ parsed = {+ "a.py": SimpleNamespace(+ file_info=_file_info("a.py", "python"), imports=[], symbols=[]+ )+ }+ graph = nx.DiGraph()+ graph.add_node("a.py", node_type="file")+ ctx = _ctx({"a.py"}, repo_path=tmp_path, graph=graph, parsed_files=parsed)+ dctx = DetectionContext(+ stack_lower=set(), parsed_files=parsed, ctx=ctx, path_set={"a.py"}+ )+ assert godot_edges.HANDLERS[0].detect(dctx) is False++ def test_two_projects_do_not_share_one_global_class_table(self, tmp_path: Path) -> None:+ # Godot's class_name table is per *project*, and one repo can hold+ # many -- godot-demo-projects is dozens side by side. Two projects+ # each declaring `class_name Player` must not wire to each other.+ for project in ("alpha", "beta"):+ (tmp_path / project).mkdir(parents=True, exist_ok=True)+ (tmp_path / project / "project.godot").write_text(+ "config_version=5\n", encoding="utf-8"+ )+ graph = _class_name_edges(+ tmp_path,+ {+ "alpha/player.gd": "class_name Player\nextends Node\n",+ "alpha/game.gd": "func f():\n\tPlayer.new()\n",+ "beta/player.gd": "class_name Player\nextends Node\n",+ "beta/game.gd": "func f():\n\tPlayer.new()\n",+ },+ )+ assert graph.has_edge("alpha/game.gd", "alpha/player.gd")+ assert graph.has_edge("beta/game.gd", "beta/player.gd")+ assert not graph.has_edge("alpha/game.gd", "beta/player.gd")+ assert not graph.has_edge("beta/game.gd", "alpha/player.gd")++ def test_a_bom_does_not_hide_a_line_one_declaration(self, tmp_path: Path) -> None:+ graph = _class_name_edges(+ tmp_path,+ {+ "a.gd": "class_name Effect\nextends Node\n",+ "b.gd": "func f():\n\tEffect.new()\n",+ },+ )+ assert graph.has_edge("b.gd", "a.gd")+++# ---------------------------------------------------------------------------+# 5. Godot engine callbacks are not dead code+# ---------------------------------------------------------------------------+++class TestEngineCallbacks:+ def test_node_lifecycle_callbacks(self) -> None:+ for name in ("_ready", "_process", "_physics_process", "_enter_tree", "_exit_tree"):+ assert is_contract_method(name, "function", "gdscript"), name++ def test_input_and_drawing_callbacks(self) -> None:+ for name in ("_input", "_unhandled_input", "_gui_input", "_draw", "_notification"):+ assert is_contract_method(name, "function", "gdscript"), name++ def test_editor_plugin_interface(self) -> None:+ for name in ("_enable_plugin", "_get_plugin_name", "_handles", "_edit"):+ assert is_contract_method(name, "function", "gdscript"), name++ def test_a_project_helper_is_still_eligible(self) -> None:+ assert not is_contract_method("_recalculate_damage", "function", "gdscript")++ def test_scoped_to_gdscript(self) -> None:+ # `_process` is an ordinary private helper name in Python.+ assert not is_contract_method("_process", "function", "python")+ assert not is_contract_method("_ready", "method", "typescript")diff --git a/tests/unit/ingestion/test_language_capabilities.py b/tests/unit/ingestion/test_language_capabilities.pyindex c9558f13a..748ba0bd2 100644--- a/tests/unit/ingestion/test_language_capabilities.py+++ b/tests/unit/ingestion/test_language_capabilities.py@@ -146,6 +146,9 @@ _FULL = {# res:// is an absolute path from the nearest project.godot, so GDScript# import targets resolve exactly rather than through a stem guess."gdscript",+ # .tscn/.tres/.escn, project.godot and plugin.cfg name their dependencies+ # with the same res:// paths and share the same resolver.+ "godot_resource","go","java","javascript",diff --git a/tests/unit/ingestion/test_lightweight_resolvers.py b/tests/unit/ingestion/test_lightweight_resolvers.pyindex c41044820..394893961 100644--- a/tests/unit/ingestion/test_lightweight_resolvers.py+++ b/tests/unit/ingestion/test_lightweight_resolvers.py@@ -95,6 +95,9 @@ class TestDispatch:"html",# import QtQuick / import "components" (regex tier, #727)."qml",+ # Godot .tscn/.tres/.escn + project.godot + plugin.cfg. The only+ # member at import_support="full" -- see the package docstring.+ "godot_resource",} == LIGHTWEIGHT_IMPORT_LANGUAGESdef test_other_language_returns_empty(self) -> None: