# Controller State Mutation Matrix

This document maps application methods to the state fields they modify and the locks that protect those mutations.

## 1. Mutation Matrix Table

| Method Name | Class | State Field(s) Modified | Lock(s) Used | Thread Context |
| :--- | :--- | :--- | :--- | :--- |
| `_process_event_queue` | `AppController` | `ai_status`, `mma_status` | `_pending_gui_tasks_lock` | Event Thread |
| `_handle_request_event` | `AppController` | `ai_status` | `_pending_gui_tasks_lock` | AI Worker Thread |
| `_set_status` | `AppController` | `ai_status` | `_pending_gui_tasks_lock` | Any (Helper) |
| `_set_mma_status` | `AppController` | `mma_status` | `_pending_gui_tasks_lock` | Any (Helper) |
| `_send_anthropic/gemini` | `ai_client` | `history` (via callback) | `_anthropic/deepseek/minimax_history_lock`, `_send_lock` | AI Worker Thread |
| `init_state` | `AppController` | `disc_entries` | `_disc_entries_lock` | Main Thread (Init) |
| `switch_discussion` | `AppController` | `active_discussion`, `disc_entries` | `_disc_entries_lock` | Main/Event Thread |
| `_process_pending_gui_tasks`| `App` | `disc_entries`, `ai_status`, `mma_status` | `_pending_gui_tasks_lock`, `_disc_entries_lock` | Render Thread |
| `_take_snapshot` | `App` | `_last_ui_snapshot` | None (Single threaded UI) | Render Thread |
| `_handle_history_logic` | `App` | `history` (HistoryManager) | None (Single threaded UI) | Render Thread |
| `_rebuild_rag_index` | `AppController` | `rag_status` | `_pending_gui_tasks_lock` | RAG Worker Thread |
| `_queue_put` (FastAPI) | `AppController` | `_api_event_queue` | `_api_event_queue_lock` | FastAPI Thread |

## 2. Lock Ownership Audit

### 2.1 The Foreground/Background Gate
The `_pending_gui_tasks_lock` is the most critical synchronization point. Background threads (AI, MMA, RAG) use this to queue state updates. The Render thread (Pipeline 2.3) drains this queue every frame.
- **Risk:** High lock contention if background threads queue too frequently (e.g., streaming status).

### 2.2 Global SDK Serializer
`_send_lock` in `ai_client.py` serializes *all* AI requests across the entire application, regardless of provider. 
- **Finding:** This is a major bottleneck if multi-agent concurrency is desired, as it prevents parallel SDK calls.

### 2.3 History Data Integrity
`_disc_entries_lock` ensures that the UI doesn't render a partially-updated history list while a background thread is appending a new AI response.

## 3. State Lifecycle & Flushing
- **Memory vs. Disk:** State is held in memory (`AppController` attributes). 
- **Flushing:** `_last_autosave` tracks the 60s interval. `_process_event_queue` (Event Thread) triggers the disk flush to `history.toml` or `manual_slop.toml`.
- **Finding:** The UI Thread (`_handle_history_logic`) also performs snapshots for Undo/Redo, creating a dual-layer state persistence model.
