# GodotIQ — AI-Assisted Godot Development

You have GodotIQ MCP tools. ALWAYS prefer these over raw file operations.

**DO NOT** read `.tscn`, `.gd`, `.tres` files directly with `Read`/`cat`. GodotIQ parses them into structured data with cross-references, spatial transforms, signal wiring, and impact analysis that raw text cannot provide.

**DO NOT** grep the codebase to find signal connections or function callers. `godotiq_dependency_graph` and `godotiq_signal_map` trace the complete graph in one call.

**DO NOT** manually calculate positions or guess scales. `godotiq_placement` and `godotiq_suggest_scale` analyze the scene and return validated suggestions.

---

## CRITICAL: How to Build 3D Scenes

### Build in .tscn, NOT in code

When creating or modifying 3D scenes, add nodes directly to the .tscn file using `godotiq_node_ops`. Do NOT write GDScript that generates nodes at runtime (e.g., a `map_builder.gd` that creates tiles in `_ready()`).

Why: Runtime-generated nodes are invisible in the editor, impossible to debug visually, and break if the script has any silent error. Static .tscn nodes are visible in the editor tree, can be inspected and adjusted, and survive script errors.

```
❌  Write map_builder.gd that creates 64 tiles in _ready()
✅  Use build_scene(grid=...) to add 64 tile instances in Main.tscn
```

```
❌  Write spawn_decorations.gd that places trees randomly
✅  Use placement to find positions, then build_scene(scatter=...) to add tree instances
```

The only code that should exist at runtime is GAME LOGIC (movement, damage, spawning enemies, score tracking). The WORLD (terrain, decorations, static structures, towers) must be in the .tscn.

### You CANNOT see screenshots

You receive screenshot data as base64 but you CANNOT interpret it visually. Do not pretend you can see what's in a screenshot. Do not say "I can see the terrain and towers" — you cannot.

When visual verification is needed:
1. Take the screenshot (it gets displayed to the user)
2. **ASK THE USER** what they see: "I've taken a screenshot. Can you confirm you see [the terrain grid / the 3 towers / the enemy path]?"
3. Wait for the user's response before continuing
4. If the user reports a problem, debug it. If they confirm it looks good, proceed.

```
❌  "I can see the map is rendering correctly with all 64 tiles"
✅  "I've taken a screenshot. Can you see the terrain grid with tiles and the path? Let me know if anything looks wrong before I continue."
```

### Stop for confirmation after major steps

After completing each major piece of work (terrain built, enemies added, towers placed, etc.), STOP and ask the user to verify in the Godot editor before continuing.

```
✅  "Step 1 complete — I've added the terrain grid and path to Main.tscn.
    Open it in the Godot editor and let me know if the tiles and road
    are visible. I'll wait for your confirmation before adding enemies."
```

This prevents building an entire game on top of a broken foundation.

### Creation Workflow — `build_scene`

For scenes with many nodes (grids, scattered objects, paths), use `godotiq_build_scene` instead of individual `node_ops` calls. One `build_scene` call replaces dozens of `node_ops` add_child operations.

#### Phase 1: Setup Scene Structure

Use `nodes` mode to create container nodes, camera, and lights:

```
godotiq_build_scene(nodes=[
    {type: "Node3D", name: "Terrain"},
    {type: "Node3D", name: "Decorations"},
    {type: "Node3D", name: "Enemies"},
    {type: "Camera3D", name: "MainCamera", position: [0, 10, 10], rotation: [-45, 0, 0]},
    {type: "DirectionalLight3D", name: "Sun", rotation: [-60, 30, 0]}
])
godotiq_save_scene()
→ ASK USER to verify structure in editor
```

#### Phase 2: Build Terrain

Use `grid` mode for tile-based ground. Use `overrides` for special tiles:

```
godotiq_build_scene(parent="Terrain", grid={
    scene: "res://tiles/grass.tscn",
    prefix: "Tile",
    rows: 8, cols: 8,
    spacing: 2.0,
    overrides: {
        "3,0": {scene: "res://tiles/road.tscn"},
        "3,1": {scene: "res://tiles/road.tscn"}
    }
})
godotiq_save_scene()
→ ASK USER to verify terrain
```

#### Phase 3: Add Decorations

Use `scatter` mode for handpicked placements:

```
godotiq_build_scene(parent="Decorations", scatter={items: [
    {scene: "res://props/tree.tscn", name: "Tree1", position: [5, 0, 3]},
    {scene: "res://props/rock.tscn", name: "Rock1", position: [8, 0, 1]}
]})
godotiq_save_scene()
→ ASK USER to verify decorations
```

#### Phase 4: Add Key Objects

Use `godotiq_placement` to find safe positions, then `scatter` to place.

#### Phase 5: Create Scripts

Use `godotiq_script_ops` for game logic ONLY — NOT for scene construction.

#### Phase 6: Verify

```
godotiq_spatial_audit(scene="res://scenes/main.tscn")
godotiq_signal_map(detail="brief")
godotiq_save_scene()
→ ASK USER to do final visual check
```

#### Key Principles

- **Everything static goes in .tscn** via build_scene
- **One build_scene call per logical group**
- **Save and verify after each phase**
- **Grid** for repetitive, **scatter** for handpicked, **line** for paths
- **Max 256 nodes per call** — split larger layouts

### Test-Driven Completion

You are NOT done when code compiles or the game starts without crashing. Done means every player-facing feature works during actual gameplay.

Examples of "broken but compiles":
- Towers that don't shoot at enemies
- Buttons that don't respond to clicks
- Score labels that never update
- Enemies that spawn but don't follow the path
- Resources that never change when they should

After building any feature, ask yourself: "If a player tried every feature right now, would it all work?" If you are unsure, test it with runtime tools (`godotiq_run`, `godotiq_state_inspect`, `godotiq_input`). Compiling is the floor, not the finish line.

### MANDATORY: Final QA (before declaring "done")

Before telling the user the task is complete, you MUST run ALL 6 checks:

1. **Spatial coherence** — `godotiq_spatial_audit(detail="brief")`. Must have 0 critical issues and 0 warnings. If any exist, fix them before proceeding.

2. **Grid/path connectivity** — If you used `build_scene` with grid mode and overrides, check the `warnings` field in the response. If there are connectivity warnings (isolated tiles, gaps in path), fix them with `node_ops` before continuing.

3. **Code quality** — For every `.gd` file you created or modified, call `godotiq_validate(target="res://path/to/file.gd", detail="brief")`. Fix all issues before proceeding.

4. **Signal wiring** — `godotiq_signal_map(detail="brief", find="orphans")`. Must have 0 orphan signals. If any exist, connect or remove them.

5. **Gameplay test** — Run a thorough play-test with real interaction:

   **5.1** Check for script errors first:
   - Call `godotiq_check_errors(scope="scene")` before starting
   - If errors found, fix them before attempting to run

   **5.2** Start and verify initial state:
   - `godotiq_run(action="play")`, wait for confirmation
   - `godotiq_state_inspect` to verify starting values (gold, lives, wave, etc.)

   **5.3** Test every interactive feature:
   - Use `godotiq_ui_map(detail="brief")` to find clickable elements
   - Use `godotiq_input` to click/tap each interactive element
   - Use `godotiq_state_inspect` to verify expected changes after each interaction
   - If something didn't change when it should have, that's a bug — fix it

   **5.4** Wait for a complete cycle:
   - If the game has waves/rounds/turns, start one
   - Wait with `godotiq_input(commands=[{"wait_ms": 10000}])`
   - Verify enemies were processed, resources changed, scores updated

   **5.5** Check for runtime errors:
   - Read `_editor_state.recent_errors` from any bridge tool response
   - If errors appeared during gameplay, stop the game and fix them

   **5.6** Stop and report results:
   - `godotiq_run(action="stop")`
   - Summarize what was tested and what passed

6. **Report to user** — State what was built, summarize QA results, and EXPLICITLY ask the user to visually verify in the Godot editor. You CANNOT see the game. You MUST ask the user to look.

**NEVER say "I can see the terrain" or "the game looks great" or any variation.** You are an AI with NO visual perception of the Godot editor or game window. You have tool data only. Always phrase it as: "I've completed the build and all QA checks pass. Please open the scene in the editor and verify that [specific things] look correct."

---

## Token Efficiency (CRITICAL)

### Default to detail="brief"

ALWAYS use `detail="brief"` unless you specifically need more data. A single `asset_registry(detail="full")` can produce 140,000 characters and crash the session.

```
❌  godotiq_scene_map(detail="full")          → can be 50,000+ chars on large scenes
❌  godotiq_asset_registry()                   → 140,000 chars with default "normal" on large projects
✅  godotiq_scene_map(detail="brief")          → ~2,000 chars, enough for overview
✅  godotiq_asset_registry(detail="brief", path_filter="kenney_furniturekit")  → filtered + compact
```

### Always filter

Use `focus` + `radius` on scene_map. Use `path_filter` on asset_registry. Use `scope="file:path.gd"` on signal_map. Never request full project data unless debugging a specific issue.

### Screenshot sparingly

Each screenshot consumes thousands of tokens. Use `state_inspect` when you only need data values. Use screenshots only when visual verification is genuinely needed, and limit to 2-3 per session.

```
✅  state_inspect(queries=[{autoload: "GameManager", properties: ["gold", "lives"]}])  → 200 chars
❌  screenshot just to check if gold increased  → 10,000+ chars
```

---

## Efficiency Rules

1. **Don't overthink — act.** If you know what tool to call, call it immediately. Don't deliberate for 3 paragraphs about whether to call it. If the call fails, you'll see the error in the response and can adjust. Action is faster than speculation.

2. **Batch operations.** Use `build_scene` for multiple nodes instead of individual `node_ops` calls. Use `script_ops` patch mode for targeted changes instead of rewriting entire files. One tool call that does 20 things beats 20 tool calls that each do 1 thing.

3. **Don't repeat tool calls.** If you already called `project_summary` or `asset_registry` this session, don't call them again — the project structure hasn't changed. Keep results from previous calls in your conversation context and refer back to them.

4. **Check `_editor_state`.** Every bridge tool response includes an `_editor_state` dict with `open_scene`, `game_running`, and `recent_errors`. Read it after every tool call. If `recent_errors` is not empty, address the errors before continuing. If `open_scene` is wrong or empty, fix it before doing more scene work. This saves you from calling `editor_context` separately.

5. **One script, one validate.** After writing or modifying each `.gd` file, immediately call `godotiq_validate` on it. Don't write 5 scripts and then validate them all at the end — errors compound and become harder to debug when you can't tell which script introduced the problem.

6. **Act immediately.** When you know the next step, execute it. Don't write multi-paragraph plans. The tool will tell you if something is wrong — act on the response, don't pre-plan for every contingency.

7. **Maximum 2 paragraphs between tool calls.** After a tool call, explain what happened in 1-2 sentences, then make the next call. Don't write essay-length analysis between actions. If you find yourself writing more than 2 short paragraphs without a tool call, stop and act instead.

---

## Known Godot Quirks

1. **play_main_scene() is unreliable** — GodotIQ works around this internally. Always use `godotiq_run(action="play")` which uses `play_current_scene()` under the hood. If you need a specific scene, pass it as parameter: `godotiq_run(action="play", scene="res://Main.tscn")` or just `godotiq_run(action="play", scene="Main")`.

2. **Script cache staleness** — When you write a `.gd` file via `script_ops`, GodotIQ automatically sends a `reload_script` command to the editor. However, if you use `exec` to create or modify scripts, the editor may not pick up changes until a manual reload. Use `godotiq_exec` with context `"editor"` and call `EditorInterface.get_resource_filesystem().scan()` to force a refresh.

3. **class_name in new scripts** — When you create a new script with a `class_name` declaration, the editor may not register it immediately. Prefer the `load("res://path.gd").new()` pattern over `ClassName.new()` for scripts created during the current session. See "Script Loading Pattern" below.

4. **Asset loading time** — Projects with many 3D assets (GLB/GLTF files) take longer to start. GodotIQ handles this with adaptive timeout: it counts GLB files and adjusts the run timeout automatically. If you still get a timeout, check with `godotiq_state_inspect` before assuming failure.

5. **Verifying movement** — Screenshots are single frames and cannot prove motion. Use `godotiq_verify_motion` to confirm a node is actually moving, or take two `state_inspect` readings with a wait between them. See "Verifying Movement and Animations" below.

6. **Setting main scene** — When you run a scene for the first time in a project with no `main_scene` set in `project.godot`, GodotIQ auto-sets it. The run response will include `"main_scene_set": true` when this happens.

---

## Script Loading Pattern for New Scripts

When creating a new GDScript with a `class_name` declaration, the Godot editor registers that class name in a global cache that updates asynchronously. If another script immediately tries to use `ClassName.new()`, it may fail because the class is not yet registered.

The safe pattern is to always use `load()` for any script created or modified during the current session:

```gdscript
# WRONG — may fail for scripts created during this session:
var enemy = EnemyUnit.new()

# RIGHT — works reliably:
var EnemyScript = load("res://scripts/enemy_unit.gd")
var enemy = EnemyScript.new()
```

Scripts that existed before the session started are already registered and can use `ClassName.new()` safely. This only matters for scripts you CREATE or MODIFY during the current session.

---

## Verifying Movement and Animations

Screenshots are single frames — they cannot prove a node is moving, animating, or following a path.

**Preferred approach:** Use `godotiq_verify_motion`:

```
godotiq_verify_motion(node="/root/Main/Cars/Car1", property_name="position", duration=2.0)
→ {"verdict": "MOVING", "before": "(3, 0, 5)", "after": "(5.2, 0, 5)", "changed": true}
```

The tool also works for any property:
- `property_name="rotation"` for spinning objects
- `property_name="scale"` for growing/shrinking
- `property_name="modulate"` for color changes

**Manual alternative** using double `state_inspect`:

1. `godotiq_state_inspect(queries=[{node: "/root/Main/Enemy", properties: ["position"]}])`
2. `godotiq_input(commands=[{"wait_ms": 2000}])`
3. `godotiq_state_inspect(queries=[{node: "/root/Main/Enemy", properties: ["position"]}])`
4. Compare the two position values — if different, the node is moving

Use `verify_motion` for simple "is it moving?" checks. Use double `state_inspect` when you need to inspect multiple properties or complex state alongside the motion check.

ALWAYS verify movement this way for any object that should animate.

---

## Game Loading Time

Asset-heavy projects (especially those with many GLB/GLTF 3D models) can take 10-15+ seconds to start. `godotiq_run()` handles this automatically with adaptive timeout based on project asset count.

If the run times out despite adaptive timeout, the game may still be starting — wait a few seconds and try `godotiq_state_inspect` to check if it eventually started.

Do NOT immediately retry `godotiq_run(action="play")` after a timeout — the first run may still be in progress. Call `godotiq_run(action="stop")` first, then retry.

---

## Mandatory Workflows

### 1. Session Start (EVERY new conversation)

```
godotiq_project_summary(detail="brief")   → architecture, autoloads, counts
```

Call this FIRST. It gives you the project context you need in ~500 chars.

### 2. Before Editing ANY File

```
godotiq_file_context(file, detail="brief")           → public API, dependencies
godotiq_impact_check(file, action, target)            → what breaks if you change this
```

NEVER modify a `.gd` file without calling `file_context` first.

### 3. 3D Scene Work

```
godotiq_scene_map(scene, focus=area, radius=N, detail="brief")  → spatial layout
godotiq_placement(near=ref, constraints={...})                    → find safe positions
godotiq_build_scene(grid=..., parent="Terrain")                   → batch creation (grids, scatter, lines)
godotiq_node_ops(operations=[...], validate=true)                 → individual edits with validation
godotiq_save_scene()                                              → persist to disk
→ ASK USER to verify visually in the editor
```

ALWAYS use `validate: true` on move/scale/add_child. ALWAYS ask the user to verify after 3D changes.

### 4. After Any Code Change

```
godotiq_validate(target=file, detail="brief")   → convention check
```

### 5. Testing & Debugging

```
godotiq_run(action="play")                → start game
godotiq_state_inspect(queries)            → check runtime values (PREFERRED — cheap)
godotiq_verify_motion(node="Enemy")       → prove movement (PREFERRED over screenshot for motion)
godotiq_screenshot(scale=0.3, quality=0.3) → visual check (EXPENSIVE — ask user to interpret)
godotiq_run(action="stop")                → stop game
```

Use `state_inspect` for data. Use `verify_motion` to prove animation/movement. Use `screenshot` only when visual confirmation is needed, and always ask the user what they see.

---

## Tool Reference

### UNDERSTAND — Project Analysis (no addon needed)

**`godotiq_project_summary`** — Call FIRST in every session. Returns architecture, autoloads, file counts. Use `detail="brief"` (always).

**`godotiq_file_context`** — Call BEFORE editing any file. Returns public API, dependencies, signals, importers.

**`godotiq_scene_map`** — Spatial understanding of a scene. ALWAYS use `focus` + `radius` to limit scope. ALWAYS call before placing or moving 3D objects.

**`godotiq_dependency_graph`** — Complete dependency graph for a script. Call before refactoring.

**`godotiq_signal_map`** — Project-wide signal wiring. Find orphan signals, busiest signals, missing definitions.

**`godotiq_impact_check`** — Predicts what breaks before you make a change.

**`godotiq_validate`** — Convention check: missing type hints, naming violations, orphan signals.

**`godotiq_trace_flow`** — Trace execution flow from a trigger through the entire codebase.

**`godotiq_spatial_audit`** — Automated 3D issue scan: floating objects, scale mismatches, z-fighting, overlapping.

**`godotiq_check_errors`** — Check GDScript files for compilation/parse errors. Call before `godotiq_run` or after writing scripts. Use `scope="scene"` for current scene scripts + autoloads, `scope="project"` for all scripts in the project.

**`godotiq_asset_registry`** — Asset inventory with usage tracking. ALWAYS use `path_filter` to limit scope.

**`godotiq_suggest_scale`** — Recommend scale + position for a model based on similar assets.

**`godotiq_placement`** — Smart placement: finds Marker3D slots first, then grid-searches with constraints. Returns suggestions with confidence scores.

**`godotiq_animation_info`** — Animation data for any node: tracks, length, looping, state machine.

**`godotiq_animation_audit`** — Find animation problems: broken tracks, missing transitions.

### EDIT — Scene & Script Modification (requires addon)

**`godotiq_scene_tree`** — Live editor scene tree. Use `detail="brief"` and `depth=2` for overview.

**`godotiq_node_ops`** — Core editing. Batch operations with Ctrl+Z undo: move, rotate, scale, set_property, add_child, delete, duplicate, reparent. ALWAYS use `validate: true` for spatial operations.

**`godotiq_build_scene`** — Batch node creation with high-level patterns: grid (tile maps), line (paths/fences), scatter (handpicked placements), nodes (mixed types). One call = one undo action. Max 256 nodes per call. Use `parent` to target a container node. Response includes `node_names` array with actual names assigned by Godot (may differ from requested names due to collision renaming).

**`godotiq_script_ops`** — Read, write, patch GDScript. Patch mode (find-and-replace) is safest. After writing .gd files, GodotIQ automatically reloads the script in the editor.

**`godotiq_file_ops`** — Filesystem operations. Respects protected files.

**`godotiq_save_scene`** — Persist editor changes to disk. Call after `node_ops`.

**`godotiq_undo_history`** — Review what was changed.

**`godotiq_editor_context`** — Editor state: open scenes, selected nodes, game running status.

### PLAY & DEBUG — Runtime (requires addon + running game)

**`godotiq_run`** — Start/stop game. Automatically opens the requested scene, uses reliable `play_current_scene()`, applies adaptive timeout based on project size, and auto-sets `main_scene` in project.godot if not already configured.

**`godotiq_state_inspect`** — Query runtime properties. PREFERRED over screenshot for checking values.

**`godotiq_verify_motion`** — Verify a node property changes over time (proves movement/animation). Takes two readings separated by a duration and returns MOVING or STATIC verdict. Use instead of screenshots to verify motion. Game must be running.

**`godotiq_screenshot`** — Capture viewport. You CANNOT interpret this — ask the user what they see.

**`godotiq_perf_snapshot`** — FPS, draw calls, memory.

**`godotiq_ui_map`** — Map all UI elements. Call before `godotiq_input`.

**`godotiq_input`** — Simulate player input: actions, keys, UI taps.

**`godotiq_exec`** — Execute GDScript. `func run():` required. Use `context="editor"` for editor, `context="game"` for runtime. Prefer dedicated tools over exec.

**`godotiq_nav_query`** — Live pathfinding queries.

**`godotiq_watch`** — Persistent property monitoring.

**`godotiq_camera`** — Editor 3D camera control.

---

## Spatial Validation

Add `validate: true` to move/scale/add_child in `node_ops`. Checks:
- Wall proximity (< 0.2m blocked)
- Node overlap (< 0.05m blocked)
- Sibling outlier (warns if far from similar nodes)
- Scale outlier (warns if different from siblings)

Atomic batches: if ANY operation is BLOCKED, NO operations execute.

## Node Paths

Paths in `node_ops` are relative to scene root:
- Use `"Sun"` not `"Main/Sun"`
- Use `"Entities/Worker_1"` not `"Main/Entities/Worker_1"`

## GDScript Conventions

- Files: `snake_case.gd` — Classes: `PascalCase` — Functions/vars: `snake_case`
- Always use type hints: `var count: int = 0`, `func get_name() -> String:`
- Use `@onready` for node refs: `@onready var label: Label = $UI/Label`
- Check null: `if is_instance_valid(node):`
- Prefer explicit types over `:=` type inference to avoid GDScript inference bugs

## Error Recovery

- `GAME_NOT_RUNNING` → `godotiq_run(action="play")`
- `NODE_NOT_FOUND` → `godotiq_scene_tree(detail="brief")` to find correct name
- `ADDON_NOT_CONNECTED` → Enable GodotIQ addon in Godot editor
- `TIMEOUT` → The adaptive timeout should handle most cases. If it still times out, wait a few seconds and check with `godotiq_state_inspect`. If the game truly did not start, call `godotiq_run(action="stop")` then try again.
- `SCRIPT_ERRORS` → `godotiq_check_errors(scope="scene")` to see details, then fix the broken scripts before running again
- `BLOCKED` (node_ops) → Check `validation` array, adjust position/scale
- `NO_SCENE` (build_scene) → Open a scene in the Godot editor first
- `PARENT_NOT_FOUND` (build_scene) → Check parent node name/path; create the parent node first if needed
- `NO_NODES` (build_scene) → Ensure exactly one mode (grid/line/scatter/nodes) with valid data
- Partial success (build_scene) → Check `errors` array, fix failed items, retry only those
- Node count limit (build_scene) → Split into multiple `build_scene` calls grouped by parent
