# Implementation Plan: Hook API & Test Harness Hardening

## Phase 1: Dynamic Port Allocation
- [ ] Task: Modify `src/api_hooks.py` to attempt binding to port `8999`. If unsuccessful, iterate up to `9010`.
- [ ] Task: Upon successful binding, write the selected port to a temporary artifact file (e.g., `.mcp_port`).
- [ ] Task: Update the `live_gui` fixture in `tests/conftest.py` to read the assigned port from the artifact file and use it for all `ApiHookClient` requests.
- [ ] Task: Conductor - User Manual Verification 'Phase 1: Dynamic Port Allocation' (Protocol in workflow.md)

## Phase 2: Graceful Teardown
- [ ] Task: Implement a `/api/shutdown` POST endpoint in `src/api_hooks.py`.
- [ ] Task: Ensure the `/api/shutdown` endpoint correctly signals the `AppController` and `App` to perform a clean exit (e.g., joining threads, writing pending saves).
- [ ] Task: Update the `live_gui` fixture to call `/api/shutdown` during teardown, relying on `taskkill` only as a last resort if the process fails to exit gracefully within a timeout.
- [ ] Task: Conductor - User Manual Verification 'Phase 2: Graceful Teardown' (Protocol in workflow.md)

## Phase 3: State Serialization Audit
- [ ] Task: Audit `src/app_controller.py` to identify all GUI-related state variables that should be exposed to tests (e.g., `show_windows`, individual window toggles).
- [ ] Task: Update `_gettable_fields` to ensure all necessary state is mapped.
- [ ] Task: Refine `_serialize_for_api` in `src/api_hooks.py` (or introduce lightweight dataclass parsing) to handle complex nested objects predictably.
- [ ] Task: Conductor - User Manual Verification 'Phase 3: State Serialization Audit' (Protocol in workflow.md)

## Phase 4: Verification
- [ ] Task: Write Tests: Create a concurrency test verifying multiple `live_gui` instances can launch simultaneously without port conflicts.
- [ ] Task: Run the entire test suite to ensure the new dynamic port and graceful shutdown logic has not introduced regressions.
- [ ] Task: Conductor - User Manual Verification 'Phase 4: Verification' (Protocol in workflow.md)
