# AI Loop: Optimization & Consolidation Targets

Based on the technical trace and sequence mapping of the AI interaction loop, the following areas are identified as primary targets for "Heavy Curation".

### 1. Unified Provider Loop (`ai_client.py`)
- **Observation:** `_send_anthropic`, `_send_gemini`, and `_send_gemini_cli` all implement their own `for r_idx in range(MAX_TOOL_ROUNDS + 2)` loops.
- **Problem:** Significant boilerplate duplication for tool execution, error handling, and file re-reading.
- **Curation Goal:** Refactor the multi-turn recursion into a single `_base_send_loop` method that takes a provider-specific `generate_turn` callback.

### 2. Threading Model Management (`app_controller.py`)
- **Observation:** `_process_event_queue` spawns a new `threading.Thread` for every `user_request`.
- **Problem:** Potential for thread explosion if multiple asynchronous requests are triggered rapidly (though rare in typical usage).
- **Curation Goal:** Consolidate into a single dedicated "AI Worker" thread with a task queue, or use a small `ThreadPoolExecutor` to manage background lifetimes.

### 3. Redundant Context Markers
- **Observation:** `_FILE_REFRESH_MARKER` and `_get_context_marker()` are used in multiple places to inject diffs.
- **Problem:** String duplication and fragmented logic for deciding when to "refresh" the AI's file context.
- **Curation Goal:** Centralize the context-refresh injection logic within the `aggregate` module or a dedicated `ContextRefresher` class.

### 4. Blocking Call Audit
- **Observation:** `asyncio.run_coroutine_threadsafe(...).result()` is used to call async tool logic from the sync worker thread.
- **Problem:** This bridge is technically correct but adds complexity.
- **Curation Goal:** If possible, move more of the AI loop logic into a proper `async` context to avoid the `.result()` blocking pattern.
