# Sprint 10a: Agent Efficiency & Quality Assurance — Complete Specification

## Problem Statement

GodotIQ is a working MCP server with 33 tools for AI-assisted Godot 4 development. An agent successfully built a complete Tower Defense 3D game (4 tower types, 4 enemy types, 8 waves, UI, visual effects) from a single prompt, running at first F5. However, the agent exhibits critical efficiency and quality issues:

1. **Time waste**: 25-30 minutes for tasks achievable in 10-15 minutes
2. **Context blindness**: Agent gets stuck on obvious issues (no scene open, unseen errors)
3. **False completions**: Agent declares "done" without verifying results (disconnected path tiles)
4. **Error invisibility**: Agent cannot see Godot console errors

## Root Cause Analysis (from codebase research)

### Information Asymmetry
Every bridge tool response is **isolated** — no ambient editor context. After `build_scene()`, the response is only `{"created": 5, "errors": [], "parent": "Terrain"}`. The agent doesn't know which scene is open, if there are errors, or if the game is running. It must call `editor_context` separately, wasting round trips.

### No Error Forwarding
The debugger.gd captures `godotiq:error` messages from the running game, but:
- Generic Godot console errors (Script error, Node not found) are NOT captured
- Editor-side errors from node_ops/build_scene are NOT returned
- No mechanism to surface last N editor errors to the agent

### No Post-Build Validation
`build_scene` creates nodes and returns a count. No validation of:
- Grid path connectivity (are road tiles connected?)
- Scene reference resolution (did .tscn files load?)
- Spatial integrity (overlaps, gaps)

### Prompt Gaps
The MCP prompt has a solid creation workflow but lacks:
- Mandatory QA checklist before declaring "done"
- Efficiency rules to prevent overthinking and redundant calls
- Error recovery guidance

## Solution: 5 Fixes

### Fix 1: `_editor_state` in Every Bridge Response

**What**: Every bridge tool handler in `godotiq_server.gd` attaches an `_editor_state` dict to its response before sending.

**Structure**:
```python
"_editor_state": {
    "open_scene": "res://Main.tscn",  # or "" if none
    "game_running": false,
    "recent_errors": [...]             # last 3 errors, or []
}
```

**Implementation**:
- Add `_get_editor_state() -> Dictionary` helper in godotiq_server.gd
- Add `_recent_errors: Array` ring buffer (max 10 entries)
- Wire debugger error capture to populate `_recent_errors`
- Call `_get_editor_state()` in every handler before `send_response()`

**Affected handlers**: ALL bridge handlers (node_ops, build_scene, save_scene, scene_tree, run, screenshot, input, exec, state_inspect, camera, and any others)

### Fix 2: Pre-flight Checks

**What**: `build_scene` and `node_ops` handlers verify preconditions before executing.

**Checks**:
1. Scene is open → if not: `"No scene is open in the editor. Call godotiq_exec to open a scene first: EditorInterface.open_scene_from_path('res://Main.tscn')"`
2. Scene matches parameter → if not: auto-open the correct scene

**Implementation**: Add `_preflight_scene_check(params)` in godotiq_server.gd. Return error response immediately if check fails.

### Fix 3: Build Scene Grid Connectivity Validation

**What**: After `build_scene` creates nodes in `grid` mode with `overrides`, validate that override tiles form a connected path.

**Validation rules**:
1. Every override tile must be adjacent to at least one other override tile (no isolated tiles)
2. Distance between adjacent override tiles must equal `spacing` (±0.01 tolerance)
3. Disconnections produce warnings in the response

**Response format with warnings**:
```json
{
    "created": 64,
    "errors": [],
    "warnings": ["Path tile at grid(2,3) has no adjacent path tile — possible gap in road"],
    "_editor_state": {...}
}
```

**Implementation**: Add `_validate_grid_connectivity(overrides, spacing) -> Array` in godotiq_server.gd. Call it after node creation in `_handle_build_scene` if mode is "grid" and overrides exist.

### Fix 4: MCP Prompt — Mandatory QA Checklist

**What**: Add a "MANDATORY: Final QA Before Declaring Done" section to the MCP prompt.

**Location**: After "Creation Workflow", before "Error Recovery"

**6 steps**:
1. Spatial coherence — spatial_audit(detail="brief"), 0 critical/warning
2. Grid/path connectivity — check build_scene warnings, fix with node_ops
3. Code quality — validate every .gd file created
4. Signal wiring — signal_map(detail="brief", find="orphans"), 0 orphans
5. Gameplay test — run/state_inspect/input/state_inspect/stop sequence
6. Report to user — never claim to "see" visual results

### Fix 5: MCP Prompt — Efficiency Rules

**What**: Add efficiency guidelines to the MCP prompt.

**Location**: After detail level rules, near the top

**Rules**:
- Don't overthink — act (call the tool, get feedback)
- Batch operations (build_scene > individual node_ops)
- Don't repeat tool calls (cache results in memory)
- Check _editor_state in every response
- One script, one validate (don't batch then validate)

## Scope Boundaries

### In Scope
- GDScript server changes (godotiq_server.gd)
- Python build_scene.py changes (warning passthrough)
- MCP prompt additions (godot_development.md)
- New tests for grid connectivity validation

### Out of Scope
- Parsers (tscn_parser, gd_parser, scene_resolver, project_index)
- Analysis tools (scene_map, dependency_graph, signal_map, etc.)
- Existing bridge tool logic (only adding _editor_state attachment)
- Existing test modifications (only adding new tests)

## Files to Modify

| File | Changes |
|------|---------|
| `godot-addon/addons/godotiq/godotiq_server.gd` | `_get_editor_state()`, `_recent_errors` ring buffer, `_validate_grid_connectivity()`, `_preflight_scene_check()`, attach to all handlers |
| `src/godotiq/tools/bridge/build_scene.py` | Pass through warnings from GDScript response |
| `src/godotiq/prompts/godot_development.md` | QA checklist section + Efficiency rules section |

## Testing Strategy

- All existing tests must pass (`pytest tests/ -v`)
- New unit tests for `_validate_grid_connectivity` logic
- New tests for _editor_state structure validation
- New tests for pre-flight check error messages
- All tests are pure Python with mocked bridge responses

## Success Criteria

1. Every bridge tool response includes `_editor_state` with open_scene, game_running, recent_errors
2. build_scene/node_ops return actionable errors when no scene is open
3. Grid builds with overrides include connectivity warnings
4. MCP prompt includes mandatory QA checklist
5. MCP prompt includes efficiency rules
6. All existing tests pass, new tests added
