Skip to content

Open source CapCut alternative.

TypeScript

Add plans

David Le0c277cec2ebd
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 00000000..3f50cdee
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,13 @@
+## macOS
+.DS_Store
+._*
+
+## Swift / Xcode
+.build/
+.swiftpm/
+DerivedData/
+xcuserdata/
+*.dSYM
+
+## Project policy
+# Keep Package.resolved tracked for reproducible dependency resolution.
diff --git a/READ.ME b/READ.ME
new file mode 100644
index 00000000..203b32d5
--- /dev/null
+++ b/READ.ME
@@ -0,0 +1,88 @@
+# Low-Latency Desktop Gaming Agent
+
+## Goal
+
+Build a desktop AI agent that can play games in real time.
+
+Gaming is the first proof point because it makes latency obvious. If the agent can understand the screen, make decisions, and control the game quickly, the same architecture can later operate normal desktop software.
+
+## Core Positioning
+
+> A real-time desktop agent that sees your screen and controls your computer with low latency.
+
+Gaming is the demo.
+Desktop automation is the larger platform.
+
+---
+
+# Product Principles
+
+## 1. Latency First
+
+The agent must feel instant.
+
+Target loop:
+
+- Screen capture: 5–15ms
+- Perception: 10–50ms
+- Action decision: 1–20ms
+- Input execution: 1–5ms
+- Total reflex loop: under 100ms
+
+Do not call a large LLM every frame.
+
+---
+
+## 2. Hybrid Intelligence
+
+Use two brains:
+
+### Fast Controller
+
+Runs many times per second.
+
+Handles:
+- movement
+- aiming/clicking
+- dodging
+- combat reactions
+- menu navigation
+- repeated game loops
+
+This should be local and small.
+
+### Slow Planner
+
+Runs occasionally.
+
+Handles:
+- strategy
+- goals
+- “what should I do next?”
+- quests
+- resource planning
+- inventory choices
+- recovery from confusion
+
+This can use a larger VLM/LLM.
+
+---
+
+# High-Level Architecture
+
+```text
+Game Screen
+ ↓
+Screen Capture
+ ↓
+Perception Pipeline
+ ↓
+World State
+ ↓
+Planner + Controller
+ ↓
+Action Engine
+ ↓
+Keyboard / Mouse / Controller Input
+ ↓
+Game
\ No newline at end of file
diff --git a/plans/00-overview.md b/plans/00-overview.md
new file mode 100644
index 00000000..c46b4203
--- /dev/null
+++ b/plans/00-overview.md
@@ -0,0 +1,111 @@
+# Super Low-Latency Agent Plan
+
+## Objective
+
+Build a desktop AI agent that can play iPhone games through Apple's iPhone Mirroring app with low latency, while keeping the architecture general enough to later control normal desktop software.
+
+iPhone games are the first product focus. Gaming is the latency proof. The larger platform is real-time desktop and mobile-app control from the Mac.
+
+## Near-Term Focus
+
+Become genuinely good at playing iPhone games through iPhone Mirroring.
+
+That means:
+
+- capture the iPhone Mirroring window reliably
+- map the mirrored iPhone content rectangle
+- perform calibrated taps, swipes, and controller-style actions
+- parse game state from screenshots with low latency
+- survive real game loops, not just click menus
+- measure Mac-side latency separately from mirroring/game response latency
+- avoid purchases, ads, account flows, and system dialogs
+
+## Core Architecture
+
+```text
+Screen Capture
+ -> Perception
+ -> World State
+ -> Fast Controller
+ -> Action Engine
+ -> Keyboard / Mouse / Controller
+```
+
+The slow planner runs beside this loop, not inside it:
+
+```text
+World State Snapshots
+ -> Slow Planner
+ -> Goals / Policies / Recovery Hints
+ -> Fast Controller
+```
+
+## Latency Rule
+
+The real-time path must never depend on a large LLM or remote VLM call.
+
+Every frame should use local, bounded-cost logic:
+
+- capture only the pixels needed
+- run small perception models or classical CV
+- keep a compact world state
+- choose from cheap action policies
+- execute input immediately
+
+## Plan Breakdown
+
+- [01-latency-budget.md](01-latency-budget.md): hard timing budget and optimization priorities
+- [02-capture-and-perception.md](02-capture-and-perception.md): screen capture, visual parsing, and world-state updates
+- [03-fast-controller.md](03-fast-controller.md): real-time controller design
+- [04-slow-planner.md](04-slow-planner.md): slow strategy, recovery, and goal-setting layer
+- [05-action-engine.md](05-action-engine.md): low-latency keyboard, mouse, and controller output
+- [06-benchmarking.md](06-benchmarking.md): latency measurement, monitoring, traces, and regression gates
+- [07-rollout.md](07-rollout.md): phased delivery path from prototype to demo
+- [08-dom-parsing.md](08-dom-parsing.md): DOM-driven perception for browser games and web apps
+- [09-screenshot-model-inference.md](09-screenshot-model-inference.md): screenshot capture into low-latency vision models
+- [10-gaps-to-expand.md](10-gaps-to-expand.md): remaining gaps needed to make the system real
+- [11-game-targets.md](11-game-targets.md): recommended games and target sequence
+- [12-iphone-mirroring.md](12-iphone-mirroring.md): iPhone Mirroring as a mobile-game target
+- [13-subway-surfers-target.md](13-subway-surfers-target.md): concrete Subway Surfers target profile
+- [14-synthetic-controller.md](14-synthetic-controller.md): generic synthetic input adapter
+- [15-gamepad-controller.md](15-gamepad-controller.md): generic controller/gamepad abstraction for controller-supported games
+- [16-iphone-gameplay-roadmap.md](16-iphone-gameplay-roadmap.md): iPhone Mirroring gameplay roadmap
+- [17-ios-control-prompt.md](17-ios-control-prompt.md): iOS control prompt and PhoneAgent reference
+- [18-macos-accessibility.md](18-macos-accessibility.md): macOS Accessibility tree/action backend
+
+## System Priorities
+
+1. Latency over generality.
+2. iPhone Mirroring competence before broad desktop automation.
+3. Local execution over remote calls in the reflex loop.
+4. State updates over full-screen re-interpretation.
+5. Specialized controllers over universal reasoning.
+6. Measurement before optimization claims.
+7. Small vision models over large VLMs inside the reflex loop.
+8. DOM signals over vision when the target is web-based and the DOM is available.
+
+## First Target Demo
+
+Start with iPhone Mirroring targets that have:
+
+- fast visual feedback
+- simple action space
+- deterministic or repeatable scenarios
+- stable iPhone Mirroring window capture
+- no multiplayer anti-cheat risk
+
+Good first candidates:
+
+- tap-only iPhone games
+- iPhone puzzle/card games
+- simple iPhone endless runners
+- Subway Surfers after swipe calibration works
+- local iPhone Safari test pages as measurement harnesses
+
+Avoid for the first demo:
+
+- competitive multiplayer games
+- games with anti-cheat
+- visually noisy 3D iPhone games
+- games requiring multi-touch, gyro, camera, or microphone
+- games requiring long strategic memory before basic control works
diff --git a/plans/01-latency-budget.md b/plans/01-latency-budget.md
new file mode 100644
index 00000000..524ccffc
--- /dev/null
+++ b/plans/01-latency-budget.md
@@ -0,0 +1,77 @@
+# Latency Budget
+
+## Target
+
+The reflex loop should complete in under 100ms end to end.
+
+Stretch target: 30-60ms for simple games.
+
+## Budget
+
+| Stage | Baseline Target | Stretch Target |
+| --- | ---: | ---: |
+| Screen capture | 5-15ms | 2-8ms |
+| Perception / model inference | 10-50ms | 5-20ms |
+| World-state update | 1-5ms | <2ms |
+| Action decision | 1-20ms | <5ms |
+| Input execution | 1-5ms | <2ms |
+| Total | <100ms | 30-60ms |
+
+## Hard Rules
+
+- No large LLM calls in the per-frame loop.
+- No remote calls in the per-frame loop.
+- No full-screen expensive inference unless the game requires it.
+- No full-resolution model input in the hot path unless measured under budget.
+- No unbounded queues between capture, perception, and action.
+- Drop stale frames instead of processing late frames.
+
+## Loop Shape
+
+Use a latest-frame-wins design:
+
+```text
+Capture thread
+ -> overwrites latest frame buffer
+
+Perception thread
+ -> reads latest frame
+ -> emits latest world state
+
+Controller thread
+ -> reads latest world state
+ -> emits immediate action
+```
+
+Do not preserve every frame if the system falls behind. A real-time agent should be current, not complete.
+
+## Optimization Order
+
+1. Measure each stage with monotonic timestamps.
+2. Remove unnecessary work from the hot path.
+3. Shrink the capture region.
+4. Use frame differencing to skip perception when nothing relevant changed.
+5. Move repeated calculations into cached state.
+6. Quantize or replace slow models.
+7. Split perception into fast local signals and slower background interpretation.
+8. Batch only when it reduces total latency without increasing frame age.
+
+## Latency Risks
+
+- Full-screen capture at high resolution.
+- Python-only hot loops for pixel-heavy work.
+- Large image copies between processes.
+- Image encoding/decoding before inference.
+- GPU upload/download overhead.
+- Model warmup during the first live loop.
+- Remote model calls.
+- Synchronous logging in the frame loop.
+- Waiting for planner output before acting.
+- Input APIs with hidden OS scheduling delays.
+
+## Acceptance Criteria
+
+- Every action trace includes capture timestamp, perception timestamp, decision timestamp, and input timestamp.
+- p50 reflex latency is under 60ms for the first demo.
+- p95 reflex latency is under 100ms for the first demo.
+- Stale-frame actions are counted and visible in metrics.
diff --git a/plans/02-capture-and-perception.md b/plans/02-capture-and-perception.md
new file mode 100644
index 00000000..02e748b8
--- /dev/null
+++ b/plans/02-capture-and-perception.md
@@ -0,0 +1,99 @@
+# Capture And Perception
+
+## Goal
+
+Convert screen pixels into a compact world state quickly enough for real-time control.
+
+The perception layer should answer only the questions the controller needs right now.
+
+For browser games and web apps, DOM parsing can be an additional perception channel. Prefer direct DOM signals over pixel inference when they are available, stable, and fast enough. See [08-dom-parsing.md](08-dom-parsing.md).
+
+For visual targets that cannot be parsed through the DOM, screenshots can feed a low-latency vision model. Keep that path local, cropped, and benchmarked. See [09-screenshot-model-inference.md](09-screenshot-model-inference.md).
+
+## Capture Plan
+
+Start with window or region capture, not whole-desktop capture.
+
+Priority order:
+
+1. Capture only the game window.
+2. Crop to the gameplay area.
+3. Crop further to regions of interest when possible.
+4. Lower resolution for controller signals.
+5. Keep occasional high-resolution snapshots for the slow planner.
+
+## Perception Modes
+
+Use the cheapest technique that works:
+
+| Need | Preferred Method |
+| --- | --- |
+| browser UI/web app state | live DOM query, DOM snapshot, or parsed HTML |
+| UI/menu state | template matching, OCR only where needed |
+| visually complex state | cropped screenshot into a small vision model |
+| player/enemy location | color thresholding, sprite matching, tiny detector |
+| aim target | local object detector, contour tracking |
+| motion | frame differencing, optical flow, tracked boxes |
+| health/resources | fixed-region OCR or bar measurement |
+| confusion recovery | slow planner snapshot |
+
+## World State
+
+Keep world state small and typed:
+
+```text
+timestamp
+scene_id
+player_position
+player_velocity
+targets
+hazards
+resources
+active_menu
+confidence
+raw_signals
+```
+
+The controller should consume this state without needing raw pixels.
+
+## Fast Path
+
+Per frame:
+
+1. Read latest captured frame.
+2. Apply crop and downscale.
+3. Run cheap detectors.
+4. Update tracks from previous state.
+5. Emit latest world state.
+
+When using a model, the fast path should pass preprocessed tensors or raw pixel buffers directly to inference. Avoid PNG/JPEG encoding in the reflex loop.
+
+## Slow Path
+
+Occasionally:
+
+1. Save high-resolution snapshot.
+2. Ask planner to classify scene, objective, or recovery action.
+3. Update controller policy or goal.
+
+Slow-path output must be advisory. The agent should keep acting while waiting.
+
+For web targets, slow-path snapshots may include compact DOM summaries alongside screenshots. Do not send a full DOM tree to the planner unless the page is small or the summary failed.
+
+## First Milestones
+
+1. Capture a selected window at stable frame rate.
+2. Measure capture latency and copy cost.
+3. Build a region cropper.
+4. Add simple object detection for the first demo game.
+5. Emit a world-state JSON event each frame.
+6. Record traces for replay.
+7. Benchmark screenshot-to-model inference on cropped regions.
+
+## Acceptance Criteria
+
+- Capture can run at 30 FPS minimum for the first demo.
+- Perception p95 stays under 50ms.
+- The controller never reads raw screenshots directly.
+- Full-resolution snapshots are outside the reflex loop.
+- Model input dimensions and preprocessing cost are included in perception latency.
diff --git a/plans/03-fast-controller.md b/plans/03-fast-controller.md
new file mode 100644
index 00000000..5ccdaeb1
--- /dev/null
+++ b/plans/03-fast-controller.md
@@ -0,0 +1,105 @@
+# Fast Controller
+
+## Goal
+
+Make real-time decisions from world state without waiting on slow reasoning.
+
+The fast controller is the agent's reflex system.
+
+## Responsibilities
+
+- movement
+- aiming
+- clicking
+- dodging
+- combat reactions
+- menu navigation
+- repeated game loops
+- emergency recovery actions
+
+## Non-Responsibilities
+
+- long-term strategy
+- quest interpretation
+- inventory planning
+- natural-language reasoning
+- visual explanation
+- broad desktop task planning
+
+Those belong to the slow planner.
+
+## Controller Design
+
+Start simple and deterministic:
+
+```text
+World State
+ -> Policy Selector
+ -> Action Policy
+ -> Action Command
+```
+
+The policy selector chooses a small controller:
+
+- `combat_policy`
+- `navigation_policy`
+- `menu_policy`
+- `avoidance_policy`
+- `recovery_policy`
+
+Each policy should have a bounded runtime and clear inputs.
+
+## Policy Options
+
+Use the simplest viable method first:
+
+| Situation | Method |
+| --- | --- |
+| target clicking | nearest/most valuable target heuristic |
+| dodging | vector away from hazard |
+| movement | waypoint or potential-field controller |
+| repeated loops | finite-state machine |
+| game-specific skill | small trained model or behavior clone |
+| uncertainty | safe default plus slow-planner request |
+
+## Timing
+
+The controller should run faster than perception. Target decision time:
+
+- baseline: 1-20ms
+- stretch: under 5ms
+
+## Planner Interaction
+
+The slow planner can update:
+
+- current goal
+- policy weights
+- target priority
+- route hints
+- recovery instructions
+
+The fast controller should treat planner output as configuration, not a blocking dependency.
+
+## Safety Rails
+
+- Rate-limit repeated inputs.
+- Add maximum hold durations for keys.
+- Add emergency input release.
+- Stop acting if the game window loses focus.
+- Stop acting if world-state confidence is too low for too long.
+
+## First Milestones
+
+1. Define the world-state schema the controller consumes.
+2. Implement deterministic policies for the first demo game.
+3. Add policy-selection logic.
+4. Add confidence-aware fallback behavior.
+5. Record every chosen action with the state snapshot id.
+
+## Acceptance Criteria
+
+- p95 decision time is under 20ms.
+- Controller can keep acting while planner is unavailable.
+- Actions are reproducible from recorded world-state traces.
+
diff --git a/plans/04-slow-planner.md b/plans/04-slow-planner.md
new file mode 100644
index 00000000..0b88b372
--- /dev/null
+++ b/plans/04-slow-planner.md
@@ -0,0 +1,95 @@
+# Slow Planner
+
+## Goal
+
+Handle strategy and recovery without slowing down the reflex loop.
+
+The slow planner is useful, but never frame-critical.
+
+## Responsibilities
+
+- setting goals
+- choosing high-level strategy
+- interpreting quests or menus
+- selecting resources or inventory
+- recovering from confusion
+- explaining what the agent is doing
+- producing new controller hints
+
+## Inputs
+
+- recent world-state history
+- occasional high-resolution screenshots
+- OCR snippets
+- controller failure events
+- game-specific memory
+- user instructions
+
+## Outputs
+
+- active goal
+- preferred policy
+- target priority
+- route or waypoint hints
+- menu instructions
+- recovery action
+- updated memory
+
+## Cadence
+
+Run the planner only when useful:
+
+- every few seconds
+- when the scene changes
+- when confidence drops
+- when the controller reports repeated failure
+- when a goal is completed
+- when the user gives a new instruction
+
+## Architecture
+
+```text
+Trace Buffer
+ -> Planner Trigger
+ -> Snapshot Builder
+ -> VLM/LLM Planner
+ -> Controller Hints
+```
+
+The planner writes hints into shared state. The controller reads the latest available hints.
+
+## Planner Prompt Shape
+
+Planner prompts should be compact:
+
+- current goal
+- latest summarized state
+- recent failures
+- screenshot when needed
+- allowed hint schema
+
+The planner should return structured output, not prose, for the controller.
+
+## Failure Handling
+
+If the planner is slow, unavailable, or wrong:
+
+- controller continues with last valid hints
+- stale hints expire
+- repeated failures trigger fallback policy
+- user can interrupt or reset goal
+
+## First Milestones
+
+1. Define planner hint schema.
+2. Build trigger rules.
+3. Add snapshot capture outside the frame loop.
+4. Implement a basic planner that returns JSON hints.
+5. Add hint expiry and validation.
+
+## Acceptance Criteria
+
+- Planner latency does not affect p95 reflex latency.
+- Controller can run for at least 30 seconds without planner output.
+- Planner output is validated before it reaches the controller.
+
diff --git a/plans/05-action-engine.md b/plans/05-action-engine.md
new file mode 100644
index 00000000..1651a690
--- /dev/null
+++ b/plans/05-action-engine.md
@@ -0,0 +1,89 @@
+# Action Engine
+
+## Goal
+
+Execute keyboard, mouse, and controller actions with low latency and predictable timing.
+
+## Responsibilities
+
+- keyboard press/release
+- mouse movement
+- mouse click/drag
+- controller input, if needed
+- action scheduling
+- input cancellation
+- focus checks
+
+## Design
+
+The controller emits action commands:
+
+```text
+press_key(W, duration=40ms)
+move_mouse(dx=10, dy=-4)
+click(button=left)
+tap(x, y)
+swipe(start_x, start_y, end_x, end_y, duration=80ms)
+press_button(A, duration=40ms)
+set_axis(left_stick_x, 0.5)
+release_all()
+```
+
+The action engine translates commands into OS input calls.
+
+For touch-style targets such as iPhone Mirroring, the action engine should expose a synthetic controller adapter. It turns semantic commands like `swipe_left` or `tap_lane_center` into calibrated mouse/touch-like gestures. See [14-synthetic-controller.md](14-synthetic-controller.md).
+
+For games that support controllers, the action engine should expose a generic gamepad abstraction with buttons, sticks, triggers, and directional pads. See [15-gamepad-controller.md](15-gamepad-controller.md).
+
+## Rules
+
+- Input execution should be fire-and-forget where safe.
+- Long key holds must have explicit release times.
+- The engine should release all inputs on shutdown or loss of focus.
+- The controller should not call OS input APIs directly.
+- Every command should be timestamped and traceable.
+
+## Mouse Strategy
+
+For games, mouse movement should support:
+
+- relative movement
+- absolute movement
+- smooth movement over a short duration
+- instant click after movement
+- calibrated sensitivity per game
+
+## Keyboard Strategy
+
+Support:
+
+- tap
+- hold
+- chord
+- release
+- rate limit
+
+Movement keys should be represented as desired direction first, then converted to key states. This prevents conflicting commands like left and right being held accidentally.
+
+## Latency Risks
+
+- OS accessibility/input permission prompts.
+- APIs that add smoothing or delay.
+- Cross-process command queues.
+- Too many tiny scheduled timers.
+- Failure to release inputs after an exception.
+
+## First Milestones
+
+1. Choose the input backend per OS.
+2. Build a command interface.
+3. Add input tracing.
+4. Add focus guard.
+5. Add emergency release.
+6. Calibrate mouse movement for first demo.
+
+## Acceptance Criteria
+
+- Input execution p95 is under 5ms after command creation.
+- All held inputs release on stop.
+- Commands can be replayed from a trace.
diff --git a/plans/06-benchmarking.md b/plans/06-benchmarking.md
new file mode 100644
index 00000000..3ccb4d89
--- /dev/null
+++ b/plans/06-benchmarking.md
@@ -0,0 +1,319 @@
+# Benchmarking And Monitoring
+
+## Goal
+
+Make latency visible, measurable, and hard to accidentally regress.
+
+No latency claim counts unless it is measured.
+
+The project needs two observability loops:
+
+- local measurement while building and tuning the agent
+- continuous monitoring so latency regressions show up over time
+
+## Required Metrics
+
+Per loop:
+
+- capture start timestamp
+- capture end timestamp
+- perception start timestamp
+- perception end timestamp
+- model preprocess start timestamp
+- model preprocess end timestamp
+- model inference start timestamp
+- model inference end timestamp
+- world-state timestamp
+- controller start timestamp
+- controller end timestamp
+- input command timestamp
+- input execution timestamp
+- frame age when perception begins
+- state age when controller begins
+- action age when input executes
+
+Aggregate:
+
+- p50 latency
+- p95 latency
+- p99 latency
+- dropped frames
+- stale actions
+- planner calls
+- planner latency
+- controller fallback count
+- capture FPS
+- perception FPS
+- controller tick rate
+- queue depth
+- CPU usage
+- GPU usage, if used
+- GPU memory usage, if used
+- memory usage
+- thermal throttling indicator, when available
+
+## Clock Rules
+
+Use a monotonic high-resolution clock for all internal timing.
+
+Do not use wall-clock time for latency deltas. Wall-clock time can jump due to NTP updates, sleep/wake, or user changes. It is useful for log labels, but not for measuring elapsed time.
+
+Every trace event should include:
+
+- monotonic timestamp for latency math
+- wall-clock timestamp for humans
+- process id
+- thread or worker id
+- build/version id
+- machine profile
+
+## Measuring End-To-End Latency
+
+There are three levels of latency to measure.
+
+### Internal Software Latency
+
+This is the time from captured frame to input command execution inside the agent.
+
+```text
+capture_end -> perception_end -> controller_end -> input_execute
+```
+
+This is the easiest latency to measure and should be present from the first prototype.
+
+### Reflex Latency
+
+This is the time from a visual change becoming available to the agent taking an action.
+
+```text
+visual_change_on_screen -> captured_frame -> world_state -> action
+```
+
+For controlled tests, create a synthetic target that changes color or position on screen, then measure how long the agent takes to respond.
+
+### Physical Loop Latency
+
+This is the true player-feel number:
+
+```text
+screen changes -> agent sees it -> input fires -> game responds on screen
+```
+
+This may require external measurement, such as a high-FPS camera, OS-level input event tracing, or a game/test app that logs both rendered frame ids and received input events.
+
+## Instrumentation Plan
+
+Add tiny timestamp spans around every hot-path boundary:
+
+```text
+capture.start
+capture.end
+preprocess.start
+preprocess.end
+model.start
+model.end
+perception.start
+perception.end
+state.publish
+controller.start
+controller.end
+action.enqueue
+input.execute
+```
+
+Each span should be cheap enough to leave on all the time. Avoid synchronous disk writes in the frame loop. Buffer trace events in memory and flush from a background worker.
+
+## Latency Breakdown
+
+Reports should show both total latency and stage latency:
+
+| Metric | Definition |
+| --- | --- |
+| capture_ms | `capture.end - capture.start` |
+| preprocess_ms | `preprocess.end - preprocess.start` |
+| model_inference_ms | `model.end - model.start` |
+| perception_ms | `perception.end - perception.start` |
+| decision_ms | `controller.end - controller.start` |
+| input_ms | `input.execute - action.enqueue` |
+| software_loop_ms | `input.execute - capture.end` |
+| frame_age_ms | `controller.start - capture.end` |
+| state_age_ms | `input.execute - state.publish` |
+
+Frame and state age matter because an action can be computed quickly but still be based on stale data.
+
+## Trace Format
+
+Every reflex action should be traceable:
+
+```text
+trace_id
+frame_id
+state_id
+action_id
+timestamps
+latency_breakdown
+controller_policy
+confidence
+planner_hint_id
+machine_profile
+build_id
+```
+
+## Benchmark Modes
+
+1. Capture-only benchmark.
+2. Perception-only benchmark from recorded frames.
+3. Controller-only benchmark from recorded world states.
+4. End-to-end dry run with input disabled.
+5. End-to-end live run with input enabled.
+6. Synthetic reflex test with a controlled visual stimulus.
+7. Long soak test for drift, throttling, and memory growth.
+
+## Monitoring Over Time
+
+Keep a rolling latency history for every serious run.
+
+Track at least:
+
+- latest run
+- last good run
+- daily best
+- daily median
+- seven-day trend
+- worst regression by stage
+
+Store summaries in a simple machine-readable format:
+
+```text
+runs/
+ 2026-05-12T10-30-00Z/
+ summary.json
+ trace.jsonl
+ config.json
+```
+
+The `summary.json` should contain p50, p95, p99, max, FPS, dropped frames, stale actions, and environment details. The `trace.jsonl` can be larger and sampled or compressed as needed.
+
+## Dashboards
+
+Start with a CLI report before building a UI:
+
+```text
+Latency report
+ total p50/p95/p99
+ per-stage p50/p95/p99
+ stale actions
+ dropped frames
+ worst 10 traces
+ regression versus baseline
+```
+
+Later, add a lightweight local dashboard with:
+
+- live loop latency graph
+- per-stage stacked latency
+- FPS and queue depth
+- stale frame rate
+- planner call timeline
+- action timeline
+- alerts when thresholds are crossed
+
+## Alerts
+
+Alert on symptoms that matter to feel:
+
+- p95 end-to-end latency over 100ms
+- p99 end-to-end latency over 150ms
+- stale action rate over 2%
+- dropped frame rate over 5%
+- perception p95 over 50ms
+- model inference p95 over target budget
+- preprocessing cost over 20% of perception budget
+- controller p95 over 20ms
+- queue depth above 1 in the reflex loop
+- sustained FPS below target
+
+Alerts should include the stage that regressed, the previous baseline, and the worst trace ids.
+
+## Regression Gates
+
+For the first demo:
+
+- capture p95 under 15ms
+- perception p95 under 50ms
+- screenshot preprocessing plus model inference p95 under 50ms
+- controller p95 under 20ms
+- action execution p95 under 5ms
+- end-to-end p95 under 100ms
+
+Use both absolute and comparative gates:
+
+- absolute gate: fail when latency exceeds the product target
+- comparative gate: warn when a stage gets 10% slower than baseline
+- comparative hard fail: fail when a stage gets 25% slower than baseline
+
+Small changes can pass absolute targets while still making the system worse over time. The comparative gate catches that drift.
+
+## Replay Harness
+
+Record frames and world states so performance work can happen without launching the game every time.
+
+Replay should support:
+
+- fixed-speed playback
+- maximum-speed playback
+- deterministic controller comparison
+- output action diffing
+- latency comparison against a saved baseline
+- frame-age and state-age reporting
+
+## Baselines
+
+Keep explicit baselines for each demo target and machine class.
+
+Example:
+
+```text
+baselines/
+ macbook-pro-m3/
+ simple-2d-game.json
+ windows-desktop-gpu/
+ simple-2d-game.json
+```
+
+Each baseline should record:
+
+- hardware
+- OS version
+- screen resolution
+- game/window settings
+- agent config
+- capture backend
+- model versions
+- model runtime
+- model precision
+- input resolution
+- preprocessing pipeline
+- measured p50/p95/p99
+
+Do not compare runs across different machines without labeling them. Hardware differences can hide real software regressions.
+
+## First Milestones
+
+1. Add monotonic timestamp helper.
+2. Add trace event schema.
+3. Record capture and action events.
+4. Build a local trace viewer or summary command.
+5. Add p50/p95/p99 report.
+6. Add a failing threshold check for regressions.
+7. Add baseline comparison.
+8. Add a 10-minute soak test.
+9. Add live console monitoring for active runs.
+
+## Acceptance Criteria
+
+- A single command can print the latest latency report.
+- Trace files can explain why an action happened.
+- Performance regressions are visible before demo time.
+- Latency trends can be compared across runs from different days.
+- The system can identify whether capture, perception, controller, or input caused a regression.
diff --git a/plans/07-rollout.md b/plans/07-rollout.md
new file mode 100644
index 00000000..24b01f20
--- /dev/null
+++ b/plans/07-rollout.md
@@ -0,0 +1,116 @@
+# Rollout Plan
+
+## Phase 0: Prototype Target
+
+Pick the first iPhone Mirroring target and define the minimum viable agent behavior.
+
+Deliverables:
+
+- iPhone game or iPhone Safari harness choice
+- iPhone Mirroring window capture working
+- iPhone content rectangle detection
+- latency measurement harness
+- first world-state schema
+- Mac input/accessibility permission path documented
+
+Success:
+
+- capture and action can run independently
+- no planner is required
+
+## Phase 1: iPhone Mirroring Control Loop
+
+Build the complete low-latency loop for one narrow iPhone game behavior.
+
+Deliverables:
+
+- iPhone Mirroring capture crop
+- synthetic tap/swipe controller
+- coordinate calibration
+- simple perception
+- fast controller
+- action engine
+- trace logging
+
+Success:
+
+- agent reacts to a visible signal in under 100ms p95
+- stale frames are dropped
+- input can be stopped safely
+- taps/swipes are blocked when the wrong window has focus
+
+## Phase 2: Competent iPhone Game Demo
+
+Expand from one reaction to a short playable loop.
+
+Deliverables:
+
+- multiple perception signals
+- policy selector
+- confidence-aware fallback
+- basic replay harness
+- latency report command
+- game-specific adapter for the first iPhone game
+
+Success:
+
+- agent plays a repeatable scenario for 1-3 minutes
+- p95 reflex latency remains under 100ms
+- failures are diagnosable from traces
+
+## Phase 3: Slow Planner
+
+Add high-level strategy without touching the reflex latency path.
+
+Deliverables:
+
+- planner trigger rules
+- screenshot snapshot builder
+- structured planner hints
+- hint expiry
+- recovery flow
+
+Success:
+
+- planner can change goals or recover from confusion
+- controller continues while planner waits
+- planner latency does not move reflex-loop p95
+
+## Phase 4: Broader Game/App Foundation
+
+Abstract the iPhone-game-specific pieces into desktop/mobile-control primitives.
+
+Deliverables:
+
+- reusable capture module
+- reusable action engine
+- generic world-state/event interface
+- iPhone game adapters
+- desktop app/game adapters
+- safety and focus guards
+
+Success:
+
+- a second demo can reuse the same loop
+- only perception and policy adapters need major changes
+
+## Open Decisions
+
+- First iPhone demo game.
+- Primary implementation language.
+- macOS capture backend.
+- macOS synthetic input backend.
+- First iPhone Mirroring calibration method.
+- Whether the first controller is heuristic, trained, or hybrid.
+
+## Suggested Default Path
+
+For fastest learning:
+
+1. Use iPhone Mirroring on macOS as the primary target surface.
+2. Start with a simple tap/swipe iPhone game or local iPhone Safari test page.
+3. Build robust window capture, content-rect detection, and synthetic taps/swipes.
+4. Move to Subway Surfers once swipe calibration is reliable.
+5. Start with heuristic perception and control.
+6. Add a tiny model only when heuristics hit a real wall.
+7. Add the slow planner after the reflex loop already works.
diff --git a/plans/08-dom-parsing.md b/plans/08-dom-parsing.md
new file mode 100644
index 00000000..24c8b241
--- /dev/null
+++ b/plans/08-dom-parsing.md
@@ -0,0 +1,157 @@
+# DOM Parsing
+
+## Goal
+
+Use DOM state as a low-latency perception channel for browser games, web apps, and desktop software built on web views.
+
+When available, DOM state can be faster and more reliable than computer vision:
+
+- exact text instead of OCR
+- element roles instead of visual guessing
+- stable ids/classes/data attributes
+- input values and checked states
+- clickable targets and links
+- layout bounds from the browser
+
+DOM parsing should complement screen perception, not replace it entirely. Canvas-heavy games, WebGL games, videos, and custom-rendered UIs may still require pixels.
+
+## Position In The Architecture
+
+```text
+Browser / WebView
+ -> DOM Snapshot Or HTML String
+ -> DOM Parser / Extractor
+ -> DOM State
+ -> World State
+ -> Fast Controller
+```
+
+DOM extraction runs beside screen capture. Both should publish into the same world-state model.
+
+## Recommended Default
+
+Use `node-html-parser` for fast parsing of HTML snapshots:
+
+Source: https://github.com/taoqf/node-html-parser
+
+Why it fits this project:
+
+- designed for performance
+- produces a simplified DOM tree
+- supports `querySelector` and `querySelectorAll`
+- lightweight compared with full browser emulation
+- good enough for extracting state from known pages or controlled game UIs
+
+Example use:
+
+```ts
+import { parse } from "node-html-parser";
+
+const root = parse(html);
+const score = root.querySelector("[data-score]")?.textContent;
+const buttons = root.querySelectorAll("button, [role=button]");
+```
+
+## Important Limitation
+
+Parsing HTML is not the same as reading a live browser DOM.
+
+If the page is dynamic, the HTML string may miss:
+
+- runtime state stored in JavaScript
+- canvas/WebGL content
+- shadow DOM details
+- computed layout
+- event listeners
+- transient animation state
+- framework state not reflected in attributes or text
+
+For browser-controlled targets, prefer live DOM queries or Chrome DevTools Protocol snapshots when possible.
+
+## Decision Tree
+
+1. If the target is a normal browser page and the agent can execute JavaScript in it, use live DOM queries first.
+2. If the agent needs layout bounds, shadow DOM, or computed styles, use Chrome DevTools Protocol `DOMSnapshot.captureSnapshot`.
+3. If the agent only has HTML strings or saved snapshots, use `node-html-parser`.
+4. If strict browser-compatible parsing matters more than speed, use `parse5`.
+5. If jQuery-style extraction is more productive than raw DOM traversal, use `cheerio`.
+6. If a nearly complete DOM environment is needed, use `happy-dom` or `jsdom` outside the reflex loop.
+
+## Alternatives
+
+| Option | Best Use | Tradeoff |
+| --- | --- | --- |
+| Browser-native DOM APIs | fastest live state when inside the page | requires page execution or browser automation access |
+| Chrome DevTools Protocol `DOMSnapshot.captureSnapshot` | DOM plus layout/style snapshots | Chrome-specific and snapshot payloads can be large |
+| `node-html-parser` | fast HTML snapshot parsing | simplified DOM, not full browser behavior |
+| `htmlparser2` | very fast streaming/callback parsing | lower-level API unless paired with DOM utilities |
+| `parse5` | standards-compliant HTML parsing | usually heavier than performance-first parsers |
+| `cheerio` | ergonomic jQuery-like extraction | useful API, but adds abstraction and may be slower than direct parsing |
+| `linkedom` | lightweight DOMParser-style API | less battle-tested than `parse5`/`jsdom` for edge cases |
+| `happy-dom` | faster browser-like DOM environment for tests/simulation | much heavier than a simple parser |
+| `jsdom` | broad web standards emulation | too heavy for the hot path |
+
+## Hot-Path Rules
+
+- Extract only the selectors needed by the controller.
+- Avoid reparsing the full DOM every frame.
+- Keep selector lists explicit and small.
+- Cache stable nodes or selector results when possible.
+- Prefer incremental mutation signals when available.
+- Keep full DOM snapshots out of the reflex loop unless measured and proven cheap.
+- Drop stale DOM snapshots the same way stale video frames are dropped.
+
+## DOM State Shape
+
+Keep the parsed output compact:
+
+```text
+timestamp
+page_url
+scene_id
+visible_text
+interactive_elements
+game_state_elements
+form_values
+selected_menu
+layout_bounds
+confidence
+raw_source_id
+```
+
+Do not pass parser-specific nodes into the controller. Convert DOM data into the common world-state schema.
+
+## Measurement
+
+Track DOM parsing separately from visual perception:
+
+- html_fetch_ms
+- dom_snapshot_ms
+- parse_ms
+- selector_ms
+- extraction_ms
+- dom_state_age_ms
+- dom_payload_bytes
+- selected_node_count
+
+Add these to the latency report so the team can compare:
+
+- vision-only reflex loop
+- DOM-only reflex loop
+- hybrid DOM plus vision loop
+
+## First Milestones
+
+1. Add `node-html-parser` as the first HTML snapshot parser candidate.
+2. Build a small extractor that maps selectors to world-state fields.
+3. Benchmark parse time and selector time on representative pages.
+4. Add a live DOM query path for browser-controlled targets.
+5. Add CDP snapshot evaluation for pages where layout bounds matter.
+6. Decide per target whether DOM, vision, or hybrid perception is fastest.
+
+## Acceptance Criteria
+
+- DOM extraction p95 is measured separately from visual perception.
+- DOM-derived state can feed the same controller interface as vision-derived state.
+- Full DOM parsing is not required on every frame unless it stays inside the latency budget.
+- The chosen parser is justified by benchmark results on target pages, not generic package claims.
diff --git a/plans/09-screenshot-model-inference.md b/plans/09-screenshot-model-inference.md
new file mode 100644
index 00000000..7d0bd536
--- /dev/null
+++ b/plans/09-screenshot-model-inference.md
@@ -0,0 +1,167 @@
+# Screenshot Model Inference
+
+## Goal
+
+Capture screenshots or screen regions and feed them into a low-latency vision model that emits compact perception signals for the controller.
+
+This is the visual fallback when DOM parsing, template matching, or simple CV are not enough.
+
+## Core Rule
+
+The reflex loop may use small local vision models. It must not depend on a large remote VLM.
+
+Large VLMs can still be useful for slow planner snapshots, debugging, labeling, and recovery.
+
+## Pipeline
+
+```text
+Screen Region
+ -> Raw Pixel Buffer
+ -> Crop / Resize / Normalize
+ -> Low-Latency Vision Model
+ -> Detections / Labels / Embeddings
+ -> World State
+ -> Fast Controller
+```
+
+Keep screenshots as raw pixel buffers for the hot path. Encoding to PNG or JPEG is usually a slow-path/debug operation.
+
+## Model Jobs
+
+Use a model only for perception questions that justify it:
+
+- object detection
+- player/enemy localization
+- UI state classification
+- minimap interpretation
+- inventory/menu recognition
+- OCR-like recognition when native OCR is too slow or brittle
+- learned affordance detection, such as "clickable target" or "danger zone"
+
+Avoid asking the model broad questions like "what should I do?" in the reflex loop. That belongs to the planner.
+
+## Capture Strategy
+
+Use the smallest input that preserves the needed signal:
+
+1. capture the game window, not the whole desktop
+2. crop to the gameplay area
+3. crop to regions of interest when possible
+4. downscale to the model's native input size
+5. run high-resolution inference only on slow-path snapshots
+
+For multi-region perception, prefer several small crops over one large full-frame model input if the total measured latency is lower.
+
+## Runtime Choices
+
+Pick the runtime based on measured latency in the target environment:
+
+- platform-native acceleration when available
+- ONNX Runtime for portable local inference
+- TensorRT/Core ML/DirectML/OpenVINO where they reduce p95 latency
+- WebGPU/WebNN for browser-contained demos when practical
+- CPU inference only when the model is tiny and predictable
+
+The plan should keep the model interface abstract so runtimes can be swapped after benchmarking.
+
+## Hot-Path Rules
+
+- Warm the model before live control starts.
+- Reuse input/output buffers.
+- Avoid cross-process image copies.
+- Avoid image compression in the reflex loop.
+- Use quantized or smaller models when accuracy allows.
+- Drop stale frames instead of queuing inference.
+- Emit confidence with every model result.
+- Keep the controller dependent on structured outputs, not raw model tensors.
+
+## Model Output Shape
+
+Convert model outputs into world-state fields:
+
+```text
+timestamp
+source_frame_id
+model_id
+input_region
+input_size
+detections
+classifications
+keypoints
+confidence
+inference_ms
+preprocess_ms
+```
+
+Do not expose model-specific tensor formats to the controller.
+
+## Measurement
+
+Track every part of screenshot-to-model latency:
+
+- capture_ms
+- crop_ms
+- resize_ms
+- normalize_ms
+- upload_ms, if GPU-backed
+- inference_ms
+- decode_ms
+- world_state_update_ms
+- model_result_age_ms
+
+Report p50, p95, and p99 for each stage.
+
+Also record:
+
+- model name/version
+- runtime/backend
+- precision, such as fp32/fp16/int8
+- input resolution
+- batch size
+- device used
+- warm/cold run status
+
+## Quality Measurement
+
+Low latency only matters if the model output is useful.
+
+Track:
+
+- false positive rate
+- false negative rate
+- confidence calibration
+- missed-action count
+- wrong-action count
+- recovery count after bad perception
+
+For games, benchmark on recorded traces first, then live runs.
+
+## Slow-Path VLM Use
+
+Large VLMs can still help outside the reflex loop:
+
+- identify what a new screen means
+- label training data
+- explain failure traces
+- suggest new regions of interest
+- recover when the fast model is confused
+
+Slow-path outputs should become hints, labels, or updated configuration. They should not block immediate control.
+
+## First Milestones
+
+1. Build raw screenshot capture into a fixed-size tensor.
+2. Measure crop, resize, normalize, and copy costs separately.
+3. Add a tiny placeholder model or model stub with identical input/output shape.
+4. Add one real low-latency model for the first visual task.
+5. Emit model results into the common world-state schema.
+6. Add latency and quality reports for recorded frames.
+7. Run a live latest-frame-wins inference loop.
+
+## Acceptance Criteria
+
+- Screenshot-to-model p95 latency is under the perception budget for the first demo.
+- No PNG/JPEG encode/decode occurs in the reflex loop.
+- Model cold-start/warmup is measured separately from steady-state latency.
+- The controller receives structured world-state updates, not raw screenshots or tensors.
+- Stale inference results are detected and dropped.
diff --git a/plans/10-gaps-to-expand.md b/plans/10-gaps-to-expand.md
new file mode 100644
index 00000000..81881a09
--- /dev/null
+++ b/plans/10-gaps-to-expand.md
@@ -0,0 +1,335 @@
+# Gaps To Expand
+
+## Goal
+
+Identify the missing plans needed to turn the low-latency agent architecture into a working product.
+
+The current plans cover the main loop, perception options, planner, action engine, and latency measurement. The remaining gaps are mostly about integration, reliability, target selection, safety, and repeatable development.
+
+## Priority 0: Pick A Narrow First Target
+
+The architecture needs one concrete game or app to force decisions.
+
+Open questions:
+
+- Which exact first game or browser demo?
+- What is the minimum behavior that counts as success?
+- What frame rate and reflex latency does that target require?
+- Does the target expose DOM, pixels only, or both?
+- What input method does it need: keyboard, mouse, or controller?
+
+Deliverable:
+
+- `target-profile.md` with window size, capture region, actions, signals, latency goal, and success criteria.
+
+Why it matters:
+
+Without a target, the system will overgeneralize too early.
+
+## Priority 1: Platform And Backend Selection
+
+Low latency depends heavily on OS capture and input APIs.
+
+Expand into:
+
+- macOS capture backend
+- Windows capture backend
+- Linux capture backend, if needed
+- browser-only capture path, if using a web demo
+- input backend per OS
+- permission setup and failure handling
+
+Deliverable:
+
+- a backend decision matrix with measured capture/input latency on each supported platform
+
+Key risks:
+
+- macOS screen recording/accessibility permissions
+- Windows capture API tradeoffs
+- browser automation overhead
+- OS input APIs that add hidden delay
+- focus loss or wrong-window input
+
+## Priority 1: Process And Threading Architecture
+
+The plan says latest-frame-wins, but needs an implementation shape.
+
+Expand into:
+
+- single process vs multi-process
+- capture thread ownership
+- perception worker ownership
+- controller tick loop
+- input worker
+- shared memory or zero-copy frame passing
+- bounded queues
+- shutdown behavior
+- crash recovery
+
+Deliverable:
+
+- a runtime architecture doc with queue sizes, thread responsibilities, and timing contracts
+
+Rule:
+
+Any queue in the reflex path should have an explicit maximum size, usually 1.
+
+## Priority 1: World-State Schema
+
+Every perception path needs to publish the same kind of state.
+
+Expand into:
+
+- base world-state schema
+- source-specific extensions for DOM, model, OCR, and CV
+- confidence model
+- timestamps and frame ids
+- stale-state rules
+- planner hint schema
+- action command schema
+
+Deliverable:
+
+- versioned JSON or TypeScript schemas for world state, planner hints, and action commands
+
+Why it matters:
+
+The controller should not care whether a signal came from DOM, screenshots, OCR, or a model.
+
+## Priority 1: Safety And Operator Control
+
+The agent controls the computer, so stopping and bounding it is product-critical.
+
+Expand into:
+
+- global kill switch
+- release-all-inputs command
+- focus guard
+- allowed window/app guard
+- maximum action rate
+- maximum key hold duration
+- input dead-man timer
+- confidence-based pause
+- manual override mode
+- visible status indicator
+
+Deliverable:
+
+- safety plan plus test cases for stuck keys, wrong focus, lost window, and low confidence
+
+Rule:
+
+The system should fail still, not fail active.
+
+## Priority 2: Calibration
+
+Mouse movement, capture regions, model crops, and coordinate transforms need calibration.
+
+Expand into:
+
+- screen coordinate system
+- window coordinate system
+- game viewport coordinate system
+- model input coordinate system
+- mouse sensitivity calibration
+- click target offset calibration
+- DPI/scaling handling
+- multi-monitor handling
+
+Deliverable:
+
+- calibration flow that maps model/DOM/vision outputs to reliable input coordinates
+
+Key risk:
+
+A model can be accurate but still click the wrong place if coordinate transforms drift.
+
+## Priority 2: Data, Replay, And Labeling
+
+The replay plan needs a data lifecycle.
+
+Expand into:
+
+- frame recording format
+- world-state recording format
+- action trace format
+- labeling workflow
+- dataset splits
+- retention policy
+- privacy filtering
+- trace compression
+- reproducible replay seeds
+
+Deliverable:
+
+- `data-and-replay.md` with file formats and commands for record, replay, label, and compare
+
+Why it matters:
+
+Recorded traces are the fastest way to improve perception and controllers without constantly running the game.
+
+## Priority 2: Evaluation Beyond Latency
+
+Latency is necessary, but the agent also needs to be good.
+
+Expand into:
+
+- task success rate
+- survival time
+- score improvement
+- missed reaction count
+- wrong action count
+- recovery rate
+- false positive/false negative perception metrics
+- planner intervention count
+- human takeover count
+
+Deliverable:
+
+- evaluation report that combines latency, accuracy, and task outcome
+
+Rule:
+
+A 30ms wrong action is still wrong.
+
+## Priority 2: Target Adapters
+
+Each game/app should live behind a small adapter.
+
+Expand into:
+
+- capture regions
+- DOM selectors, if any
+- perception config
+- action mapping
+- controller policies
+- success metrics
+- recovery rules
+
+Deliverable:
+
+- adapter interface and one first-target adapter
+
+Why it matters:
+
+This is how the project avoids hardcoding one demo while still staying latency-first.
+
+## Priority 3: Model Lifecycle
+
+The screenshot-model plan needs a way to choose and improve models.
+
+Expand into:
+
+- candidate model list
+- benchmark protocol
+- conversion pipeline
+- quantization plan
+- warmup behavior
+- versioning
+- rollback
+- quality gates
+- training/fine-tuning path, if needed
+
+Deliverable:
+
+- model selection doc with measured latency and accuracy on recorded traces
+
+Rule:
+
+Do not pick a model from general benchmark numbers. Pick it from target traces.
+
+## Priority 3: Planner Memory And Policy Updates
+
+The slow planner needs boundaries for what it can change.
+
+Expand into:
+
+- memory format
+- goal format
+- planner hint validation
+- hint expiry
+- policy override rules
+- conflict resolution between controller and planner
+- user instruction priority
+
+Deliverable:
+
+- planner contract doc
+
+Key risk:
+
+A slow planner should not inject unsafe or stale behavior into the real-time controller.
+
+## Priority 3: Privacy, Security, And Compliance
+
+Screen agents can see sensitive information.
+
+Expand into:
+
+- local-only hot path
+- screenshot redaction rules
+- trace storage location
+- trace retention
+- opt-in remote planner calls
+- secret detection before logging or upload
+- multiplayer and anti-cheat exclusion policy
+
+Deliverable:
+
+- privacy and safety policy for captured screens, logs, and remote calls
+
+Rule:
+
+Avoid multiplayer anti-cheat targets. Start with offline or controlled environments.
+
+## Priority 3: Developer Tooling
+
+The project needs commands that make latency work pleasant.
+
+Expand into:
+
+- run live demo
+- record trace
+- replay trace
+- print latency report
+- compare against baseline
+- visualize action timeline
+- inspect latest world state
+- test input release
+- benchmark parser/model/capture backend
+
+Deliverable:
+
+- CLI plan with command names and expected outputs
+
+Why it matters:
+
+If measurement is annoying, it will not happen often enough.
+
+## Suggested Next Plan Docs
+
+Create these next, in order:
+
+1. `11-target-profile.md`
+2. `12-runtime-architecture.md`
+3. `13-world-state-schema.md`
+4. `14-safety-and-control.md`
+5. `15-data-and-replay.md`
+6. `16-platform-backends.md`
+7. `17-evaluation.md`
+
+## Immediate Next Step
+
+Pick the first target and write the target profile.
+
+The target profile should force concrete answers for:
+
+- pixels vs DOM vs hybrid
+- capture region
+- action space
+- latency budget
+- success metric
+- safety constraints
+- first replay traces
+
diff --git a/plans/11-game-targets.md b/plans/11-game-targets.md
new file mode 100644
index 00000000..268b27d4
--- /dev/null
+++ b/plans/11-game-targets.md
@@ -0,0 +1,236 @@
+# Game Targets
+
+## Goal
+
+Choose iPhone games that expose latency problems quickly, avoid anti-cheat risk, and let the agent become good at mobile gameplay through iPhone Mirroring.
+
+The project should not start with the most impressive iPhone game. It should start with the game that makes the iPhone Mirroring loop measurable.
+
+## Selection Criteria
+
+Prefer games with:
+
+- offline or single-player play
+- no anti-cheat
+- simple action space
+- fast visual feedback
+- repeatable scenarios
+- stable iPhone Mirroring window capture
+- clear success metrics
+- legal and reproducible setup
+- low-cost recording and replay
+
+Avoid early:
+
+- competitive multiplayer games
+- games with anti-cheat
+- games with heavy camera control
+- visually noisy 3D games
+- games where progress depends mostly on long-term strategy
+- games with random UI transitions that are hard to replay
+- games requiring multi-touch, gyro, camera, or microphone
+
+## Recommended Sequence
+
+### 1. iPhone Mirroring Harness
+
+Best first target.
+
+Examples:
+
+- local iPhone Safari test page
+- simple tap target page
+- simple swipe detector page
+- local web microgame opened on iPhone
+- harmless iPhone app screen with safe tap points
+
+Why:
+
+- measures the real iPhone Mirroring window path
+- can log true visual-change time and input-received time
+- can run locally without anti-cheat or purchase risk
+- can intentionally create latency tests
+
+Use this to prove:
+
+- iPhone Mirroring capture loop
+- latest-frame-wins behavior
+- action engine
+- synthetic tap/swipe controller
+- content-rect calibration
+- latency reporting
+- replay traces
+- screenshot vs model perception
+
+Success metric:
+
+- agent reacts to a controlled stimulus in under 100ms p95
+- taps/swipes are recognized reliably
+- agent can run for 5-10 minutes without stuck input
+
+### 2. Simple iPhone Tap/Swipe Game
+
+Best first real App Store game category.
+
+Recommended types:
+
+- tap-only games
+- simple puzzle games
+- card games
+- turn-based games
+- idle/clicker games
+- one-finger swipe games
+
+Why:
+
+- real iPhone app behavior
+- low action complexity
+- safer than high-speed runners
+- good for menus, retries, and visual-state parsing
+
+Best fit:
+
+- iPhone game adapters
+- tap/swipe reliability
+- safety guards
+- screenshot perception
+
+Tradeoff:
+
+- less impressive than Subway Surfers, but much better for hardening the loop.
+
+### 3. Subway Surfers
+
+Best stress test once basic iPhone control works.
+
+Why:
+
+- fast endless runner
+- small control set
+- clear success metric
+- latency-sensitive
+- strongly visual
+
+Use this after:
+
+- iPhone Mirroring capture is stable
+- synthetic left/right/up/down swipes are reliable
+- game phase detection works
+- purchase/ad/system-screen guards exist
+
+See [13-subway-surfers-target.md](13-subway-surfers-target.md).
+
+### 4. Controller-Supported iPhone Games
+
+Best for testing generic controller support.
+
+Why:
+
+- avoids some touch coordinate problems
+- maps well to a generic gamepad abstraction
+- useful for wider game coverage
+
+Tradeoff:
+
+- Apple documents that wireless game controllers for iPhone apps should pair to the iPhone, not the Mac.
+- A Mac-side virtual gamepad may not work through iPhone Mirroring.
+- This likely needs a separate controller bridge backend.
+
+See [15-gamepad-controller.md](15-gamepad-controller.md).
+
+### 5. Browser/Emulator Games As Secondary Harnesses
+
+These are useful for development, but not the product focus.
+
+Use:
+
+- local browser games to debug components faster
+- Atari/Gymnasium to test policies
+- emulators to test deterministic replay
+- DOM games to test web-app automation
+
+## Best First Choice
+
+Start with an iPhone Mirroring harness: a local iPhone Safari page or very simple iPhone app/game that lets us measure tap/swipe response.
+
+Make it instrumented from day one:
+
+- render frame id on screen
+- log stimulus timestamp
+- log input received timestamp
+- expose optional debug state when using a local page
+- support deterministic reset
+- support scripted scenarios
+
+This gives three test modes in one target:
+
+- pixel-only perception
+- screenshot-to-model perception
+- calibrated tap/swipe input
+
+## Best Second Choice
+
+Use a simple real iPhone tap/swipe game.
+
+Why:
+
+- real iPhone app surface
+- manageable action space
+- safer than Subway Surfers
+- enough UI variation to exercise retries, menus, and failure handling
+
+## Best Third Choice
+
+Use Subway Surfers through iPhone Mirroring.
+
+Why:
+
+- it proves the system can handle fast visual mobile gameplay
+- it stresses swipes, timing, perception, and latency
+- it gives a compelling demo
+
+## Decision Matrix
+
+| Target | Latency Proof | iPhone Realism | Perception Difficulty | Setup Risk | Recommendation |
+| --- | --- | --- | --- | --- | --- |
+| iPhone Safari harness | high | high | low | low | start here |
+| iPhone tap game | medium | high | low-medium | low-medium | second |
+| iPhone swipe puzzle/game | medium-high | high | medium | medium | second |
+| Subway Surfers via iPhone Mirroring | high | high | high | medium-high | flagship demo |
+| Controller-supported iPhone game | high | high | medium | high | later backend |
+| Local browser game | high | low-medium | low | low | support harness |
+| Atari/Gymnasium | high | low | medium | medium | policy harness |
+| Multiplayer iPhone game | high | high | high | very high | avoid |
+
+## Target Profile Template
+
+For each chosen game, write:
+
+```text
+name
+source / install path
+legal notes
+window size
+capture mode
+perception mode
+action space
+success metric
+latency target
+reset method
+replay method
+safety constraints
+known risks
+```
+
+## Immediate Recommendation
+
+Build an iPhone Mirroring harness first.
+
+Then run the same agent architecture against:
+
+1. a simple iPhone tap game
+2. a simple iPhone swipe game
+3. Subway Surfers through iPhone Mirroring
+4. controller-supported iPhone games once the controller backend is solved
+5. browser/emulator targets only as supporting harnesses
+
diff --git a/plans/12-iphone-mirroring.md b/plans/12-iphone-mirroring.md
new file mode 100644
index 00000000..e8e9f259
--- /dev/null
+++ b/plans/12-iphone-mirroring.md
@@ -0,0 +1,193 @@
+# iPhone Mirroring
+
+## Goal
+
+Use Apple's iPhone Mirroring app as the primary near-term target surface for mobile-game and mobile-app automation from the Mac.
+
+This lets the agent interact with real iPhone apps through a Mac window, using the same desktop capture, perception, and input architecture.
+
+## Feasibility
+
+Yes, this is the main near-term use case.
+
+The mirroring layer adds wireless latency and input translation that the agent does not control, so measurement must separate Mac-side latency from iPhone/mirroring response latency. That is a reason to instrument carefully, not a reason to defer the target.
+
+## How It Fits The Architecture
+
+```text
+iPhone Game
+ -> iPhone Mirroring App Window On Mac
+ -> Mac Window Capture
+ -> Screenshot / Model / OCR Perception
+ -> World State
+ -> Fast Controller
+ -> Mac Mouse / Keyboard Input
+ -> iPhone Mirroring
+ -> iPhone Game
+```
+
+The agent should see iPhone Mirroring as another desktop window target.
+
+PhoneAgent is a useful reference for a second iOS-control path: an XCTest-hosted JSON-RPC bridge that can return accessibility trees, screenshots, context, and perform actions like open app, tap, tap element, enter text, scroll, swipe, and stop. Treat it as a complementary iOS automation backend and prompt pattern, not a replacement for the iPhone Mirroring gameplay loop. See [17-ios-control-prompt.md](17-ios-control-prompt.md).
+
+## Apple Requirements And Constraints
+
+Current Apple requirements include:
+
+- macOS Sequoia 15 or later
+- Mac with Apple silicon or Apple T2 Security Chip
+- iPhone with iOS 18 or later and a passcode
+- same Apple Account with two-factor authentication
+- Wi-Fi and Bluetooth enabled
+- iPhone locked and near the Mac
+- one Mac and one iPhone connected at a time
+
+Important constraints:
+
+- iPhone Mirroring is unavailable in the European Union.
+- The Mac cannot be using AirPlay or Sidecar during iPhone Mirroring.
+- iPhone camera and microphone are not available through iPhone Mirroring.
+- Some protected media may not mirror correctly.
+- A wireless game controller for iPhone apps should be connected to the iPhone, not the Mac.
+
+## Good First iPhone Game Types
+
+Prefer:
+
+- tap-only games
+- drag/simple-swipe games
+- puzzle games
+- card games
+- turn-based games
+- idle/clicker games
+- single-player games with no anti-cheat
+- games with stable portrait or landscape orientation
+
+Avoid early:
+
+- multiplayer games
+- anti-cheat games
+- rhythm games
+- twitch shooters
+- games requiring multi-touch
+- games requiring accelerometer or gyro
+- camera or microphone games
+- games requiring complex controller input
+
+## Perception Path
+
+Assume screenshot/model perception first.
+
+Possible inputs:
+
+- Mac window screenshot of iPhone Mirroring
+- cropped game viewport
+- OCR for labels, scores, and menus
+- small vision model for buttons, objects, or game state
+- template matching for stable UI elements
+
+DOM parsing generally does not apply unless the iPhone app is a web app exposed through a controllable browser context.
+
+## Input Path
+
+Use Mac input against the iPhone Mirroring window:
+
+- click maps to tap
+- click-and-hold maps to touch-and-hold
+- scroll/trackpad gestures can map to swipe
+- keyboard can type into iPhone text fields
+- Mac shortcuts can navigate Home Screen, App Switcher, and Spotlight
+
+Assume single-pointer input until tested. Multi-touch gestures should not be part of the first target profile.
+
+Use a synthetic controller adapter for repeatable taps and swipes. The controller should generate calibrated mouse down, movement, and mouse up events inside the iPhone Mirroring content rectangle instead of relying on hand gestures. See [14-synthetic-controller.md](14-synthetic-controller.md).
+
+For controller games:
+
+- pair the game controller directly to the iPhone
+- treat controller automation as a separate backend
+- do not assume Mac keyboard/mouse can emulate all controller interactions through mirroring
+
+## Latency Risks
+
+- wireless mirroring delay
+- variable Wi-Fi/Bluetooth conditions
+- Mac window capture overhead
+- iPhone Mirroring rendering/composition overhead
+- Mac input event translation
+- game response latency on the iPhone
+- orientation changes resizing the capture region
+- app animations hiding true state
+
+The measured reflex loop should distinguish:
+
+- Mac capture latency
+- perception/model latency
+- Mac input execution latency
+- mirroring/game response latency
+- visual confirmation latency
+
+## Measurement Plan
+
+Start with a simple instrumentable iPhone target if possible, such as a local web app opened on iPhone Safari.
+
+Measure:
+
+- time from visual stimulus in the mirrored window to agent action
+- time from Mac input event to visible iPhone response
+- p50/p95/p99 response latency across a 5-10 minute run
+- dropped or stale screenshot frames
+- wrong tap rate
+- coordinate drift after orientation/window-size changes
+
+If using an App Store game, use external observation or visual confirmation because the app will not expose internal timestamps.
+
+## Calibration
+
+The coordinate mapping must handle:
+
+- iPhone Mirroring window position
+- iPhone screen content bounds inside the window
+- portrait vs landscape orientation
+- Mac display scaling
+- window resizing
+- letterboxing or toolbar offsets
+
+Add a calibration check before each run:
+
+1. locate the iPhone Mirroring window
+2. identify the visible iPhone content rectangle
+3. click known safe points
+4. verify visual response
+5. lock the capture region for the run
+
+## Safety
+
+Add mobile-specific safety rules:
+
+- use only offline or single-player games
+- avoid accounts with purchases or sensitive data
+- disable in-app purchase flows for test devices when possible
+- stop if the mirrored window loses focus
+- stop if the app opens payment, login, contacts, messages, or system settings
+- release/stop input on disconnect
+
+Use a dedicated test iPhone or test Apple Account if this becomes a serious target.
+
+## First Milestones
+
+1. Open iPhone Mirroring and capture its window.
+2. Build coordinate calibration for portrait and landscape.
+3. Click/tap a known safe UI element reliably.
+4. Measure Mac input to visible response latency.
+5. Run a tap-only game or local iPhone Safari test page.
+6. Add screenshot-model or template perception on the mirrored window.
+7. Record and replay mirrored-window traces.
+
+## Acceptance Criteria
+
+- The agent can identify and capture the iPhone Mirroring content region.
+- Tap coordinates are accurate after window movement and resizing.
+- p95 Mac-side capture/perception/action latency remains under the desktop budget.
+- Additional mirroring/game response latency is measured separately.
+- The target game is offline/single-player and has no anti-cheat risk.
diff --git a/plans/13-subway-surfers-target.md b/plans/13-subway-surfers-target.md
new file mode 100644
index 00000000..cd02d621
--- /dev/null
+++ b/plans/13-subway-surfers-target.md
@@ -0,0 +1,219 @@
+# Subway Surfers Target Profile
+
+## Goal
+
+Use Subway Surfers as a high-pressure iPhone Mirroring target for low-latency screenshot perception and swipe control.
+
+This is a strong demo candidate, but not the first prototype. The game is fast, visual, and swipe-driven, so it should come after the agent can reliably capture, calibrate, and input into the iPhone Mirroring window.
+
+## Why Subway Surfers
+
+Subway Surfers is useful because:
+
+- it is single-player endless running
+- the character moves forward automatically
+- the control set is small
+- mistakes are visually obvious
+- latency directly affects survival
+- it runs on iPhone and can be accessed through iPhone Mirroring
+- the score/distance gives a simple success metric
+
+It is harder than tap-only games because the core inputs are swipes, timing, and fast lane decisions.
+
+## Source
+
+App Store: https://apps.apple.com/us/app/subway-surfers/id512939461
+
+Current App Store notes:
+
+- free with in-app purchases
+- iPhone and iPad support
+- action category
+- Game Center support
+- age rating 9+
+
+Use a test device/account and avoid purchase flows.
+
+## Input Model
+
+Core controls:
+
+- swipe left: move one lane left
+- swipe right: move one lane right
+- swipe up: jump
+- swipe down: roll
+- double tap: hoverboard, if enabled/available
+
+Through iPhone Mirroring:
+
+- Mac drag/swipe gestures need to map reliably to iPhone swipes
+- click/tap may start runs or dismiss menus
+- keyboard shortcuts are useful for iPhone navigation, not core gameplay
+- a synthetic controller should emit calibrated tap/swipe commands for repeatability
+
+First implementation should focus on:
+
+- lane left
+- lane right
+- jump
+- roll
+
+Defer:
+
+- hoverboard timing
+- power-up strategy
+- missions/events
+- ads/rewards
+- menus beyond starting/restarting
+
+## Perception Model
+
+Subway Surfers is mostly screenshot/model perception.
+
+Useful signals:
+
+- current lane of player
+- nearest obstacle lane
+- obstacle type: train, barrier, sign, low obstacle
+- gap/open lane
+- upcoming coin/power-up, optional
+- game-over screen
+- start/retry buttons
+- score/distance text, optional
+
+Likely perception approaches:
+
+1. heuristic lane segmentation from the screen crop
+2. template matching for common obstacles and menus
+3. small vision model for obstacle/lane classification
+4. OCR only for score/debug, not frame-critical control
+
+DOM parsing does not apply.
+
+## World State
+
+Minimum state:
+
+```text
+timestamp
+frame_id
+player_lane
+player_state
+nearest_obstacles
+safe_lanes
+recommended_action
+confidence
+game_phase
+```
+
+`game_phase` values:
+
+```text
+menu
+running
+crashed
+ad_or_offer
+unknown
+```
+
+## Controller Policy
+
+Start with a simple reflex policy:
+
+1. detect immediate obstacle in current lane
+2. choose left/right if adjacent lane is safe
+3. jump or roll if the obstacle type requires vertical action
+4. do nothing if current lane is safe
+5. pause if confidence is low or screen is unknown
+
+The controller should emit at most one swipe decision per short cooldown window so it does not overcorrect.
+
+## Latency Target
+
+For this target:
+
+- Mac-side capture/perception/controller/input p95 under 100ms
+- screenshot-model path p95 under 50ms if using a model
+- swipe execution p95 under 10ms after action command
+- mirroring/game visual response measured separately
+
+Subway Surfers gets faster over time, so early success should be measured in survival duration and avoided obstacles, not infinite play.
+
+## Measurement
+
+Track:
+
+- capture_ms
+- preprocessing_ms
+- inference_ms
+- decision_ms
+- input_ms
+- visual_response_ms
+- total_mac_side_ms
+- stale_frame_rate
+- wrong_swipe_rate
+- missed_obstacle_rate
+- survival_time
+- score/distance, if readable
+
+Add event labels:
+
+- obstacle_seen
+- action_chosen
+- swipe_sent
+- obstacle_cleared
+- crash_detected
+- retry_tapped
+
+## Calibration
+
+Before each run:
+
+1. locate the iPhone Mirroring window
+2. identify the iPhone content rectangle
+3. detect portrait/landscape orientation
+4. map the three gameplay lanes to screen coordinates
+5. validate swipe gesture distance and duration
+6. verify the game reacts to a safe menu tap/swipe
+
+Swipe calibration should tune:
+
+- start point
+- end point
+- duration
+- minimum distance
+- cooldown between swipes
+
+## Safety
+
+Use a test setup:
+
+- dedicated test iPhone if available
+- no payment method or purchase restrictions enabled
+- avoid purchases, ads, rewards, and login flows
+- stop on App Store/payment/login/system dialogs
+- stop if iPhone Mirroring disconnects
+- stop if window focus changes
+
+Do not use leaderboard or social features as success criteria.
+
+## First Milestones
+
+1. Open Subway Surfers in iPhone Mirroring.
+2. Capture the iPhone Mirroring content rectangle.
+3. Start/restart a run with a tap.
+4. Calibrate left/right/up/down swipes.
+5. Detect `menu`, `running`, and `crashed` phases.
+6. Segment screen into three lanes.
+7. Detect obvious near-lane obstacles.
+8. Execute a reflex dodge policy.
+9. Record traces and measure survival duration.
+10. Compare synthetic swipe latency and success rate across gesture durations.
+
+## Acceptance Criteria
+
+- The agent can start a run and detect when gameplay is active.
+- The agent can perform reliable left/right/up/down swipes through iPhone Mirroring.
+- The agent can survive longer than a no-op baseline.
+- Crashes are traceable to perception, decision, input, or mirroring latency.
+- No in-app purchases, ads, or external account flows are touched.
diff --git a/plans/14-synthetic-controller.md b/plans/14-synthetic-controller.md
new file mode 100644
index 00000000..82faae14
--- /dev/null
+++ b/plans/14-synthetic-controller.md
@@ -0,0 +1,218 @@
+# Synthetic Controller
+
+## Goal
+
+Build a generic synthetic input controller that emits calibrated input into a target game or app.
+
+This layer should work across games by separating:
+
+- semantic game actions
+- normalized controller actions
+- target-specific mappings
+- OS or device-specific input backends
+
+Touch gestures for iPhone Mirroring are one backend. A virtual gamepad is another backend. Keyboard/mouse is another.
+
+## Core Idea
+
+The fast controller should not know about screen coordinates, key codes, HID details, or OS input APIs.
+
+It should emit semantic actions:
+
+```text
+move_left
+move_right
+jump
+roll
+attack
+interact
+pause
+release_all
+```
+
+The synthetic controller maps those actions through a target profile:
+
+```text
+move_left -> gamepad.dpad_left
+move_right -> gamepad.left_stick_x = 1.0
+jump -> gamepad.button_south
+roll -> touch.swipe_down
+interact -> keyboard.E
+```
+
+## Architecture
+
+```text
+Fast Controller
+ -> Semantic Action
+ -> Action Mapper
+ -> Normalized Input Command
+ -> Backend Adapter
+ -> Game / App
+```
+
+Backends can include:
+
+- macOS Accessibility tree/action backend
+- gamepad / controller
+- touch gestures
+- keyboard
+- mouse
+- browser automation
+- emulator API
+
+## Normalized Command Interface
+
+Generic commands:
+
+```text
+press(action, duration_ms)
+hold(action)
+release(action)
+set_axis(axis, value)
+tap(point, duration_ms)
+swipe(direction, distance_px, duration_ms)
+drag(start, end, duration_ms)
+release_all()
+stop()
+```
+
+Gamepad-shaped commands:
+
+```text
+press_button(button, duration_ms)
+hold_button(button)
+release_button(button)
+set_left_stick(x, y)
+set_right_stick(x, y)
+set_left_trigger(value)
+set_right_trigger(value)
+tap_dpad(direction, duration_ms)
+release_gamepad()
+```
+
+Touch-shaped commands:
+
+```text
+tap(point, duration_ms=30)
+double_tap(point, gap_ms=80)
+swipe(direction, distance_px, duration_ms)
+drag(start, end, duration_ms)
+```
+
+## Target Mappings
+
+Each game should define a mapping file:
+
+```text
+target_id
+backend
+semantic_actions
+bindings
+timing
+dead_zones
+cooldowns
+safety_rules
+```
+
+Example:
+
+```text
+target_id: subway-surfers-iphone-mirroring
+backend: touch
+move_left: swipe_left
+move_right: swipe_right
+jump: swipe_up
+roll: swipe_down
+hoverboard: double_tap_center
+```
+
+Example:
+
+```text
+target_id: generic-controller-game
+backend: gamepad
+move_left: left_stick_x=-1.0
+move_right: left_stick_x=1.0
+jump: button_south
+attack: button_west
+pause: button_menu
+```
+
+## Backend Selection
+
+Pick the backend per target:
+
+| Target Type | Preferred Backend |
+| --- | --- |
+| native Mac app with accessible controls | macOS Accessibility backend |
+| native PC/Mac game with controller support | gamepad backend |
+| emulator with API | emulator backend |
+| iPhone Mirroring touch game | touch gesture backend |
+| browser canvas game | mouse/keyboard or browser backend |
+| DOM game/app | browser automation or DOM action backend |
+
+If a game supports controllers, prefer the gamepad backend because it is usually more stable than screen-coordinate mouse gestures.
+
+## Calibration State
+
+Store calibration separately from controller logic:
+
+```text
+target_id
+target_window_id
+target_window_title
+backend
+content_rect
+display_scale
+device_orientation
+gamepad_layout
+axis_dead_zones
+button_hold_ms
+gesture_distance_px
+gesture_duration_ms
+cooldowns
+last_verified_at
+```
+
+## Timing Rules
+
+- Use monotonic timestamps for every command.
+- Do not queue stale commands.
+- Enforce per-command deadlines.
+- Prevent contradictory held inputs.
+- Release held axes/buttons on stop.
+- Rate-limit repeated taps, swipes, and button presses.
+- Keep backend calls out of the perception loop.
+
+Trace every command:
+
+```text
+action_id
+semantic_action
+normalized_command
+backend
+target_id
+created_at
+input_start_at
+input_end_at
+visual_confirmation_at
+success
+```
+
+## Safety Rules
+
+- Verify the target before input.
+- Stop if the target window or device disappears.
+- Stop if confidence is low.
+- Stop on payment, login, system dialog, or unknown screen.
+- Always support `stop()` and `release_all()`.
+- Release all held buttons, keys, sticks, triggers, and mouse buttons on shutdown.
+
+## Acceptance Criteria
+
+- The fast controller emits semantic actions, not backend-specific input.
+- A target mapping can swap touch, keyboard/mouse, and gamepad backends without changing controller logic.
+- Held inputs are always released on stop.
+- Commands are timestamped and replayable.
+- Backend latency is measured separately from decision latency.
diff --git a/plans/15-gamepad-controller.md b/plans/15-gamepad-controller.md
new file mode 100644
index 00000000..997c0051
--- /dev/null
+++ b/plans/15-gamepad-controller.md
@@ -0,0 +1,189 @@
+# Gamepad Controller
+
+## Goal
+
+Build a generic controller/gamepad abstraction that can drive any supported game with controller input, without hardcoding a single game.
+
+The agent should think in semantic actions. The gamepad layer should translate those actions into normalized buttons, sticks, triggers, and D-pad commands.
+
+## Why This Matters
+
+Many games expose cleaner input through controller support than through mouse/keyboard or touch gestures.
+
+Benefits:
+
+- fewer coordinate calibration problems
+- lower ambiguity than mouse gestures
+- stable action space
+- easier replay
+- easier game-to-game remapping
+- useful for emulators, desktop games, and controller-friendly mobile games
+
+## Generic Gamepad Model
+
+Use a common modern controller shape:
+
+```text
+buttons:
+ south
+ east
+ west
+ north
+ left_bumper
+ right_bumper
+ left_stick_button
+ right_stick_button
+ menu
+ view
+ home
+
+dpad:
+ up
+ down
+ left
+ right
+
+axes:
+ left_stick_x [-1.0, 1.0]
+ left_stick_y [-1.0, 1.0]
+ right_stick_x [-1.0, 1.0]
+ right_stick_y [-1.0, 1.0]
+ left_trigger [0.0, 1.0]
+ right_trigger [0.0, 1.0]
+```
+
+Avoid naming the base abstraction after one vendor layout. Put Xbox/PlayStation/Nintendo labels in mapping metadata.
+
+## Command Interface
+
+```text
+press_button(button, duration_ms=40)
+hold_button(button)
+release_button(button)
+tap_dpad(direction, duration_ms=40)
+hold_dpad(direction)
+release_dpad(direction)
+set_left_stick(x, y)
+set_right_stick(x, y)
+set_left_trigger(value)
+set_right_trigger(value)
+neutralize_sticks()
+release_all()
+```
+
+For low latency, axis updates should be cheap and not allocate.
+
+## Game Mappings
+
+Each game gets a mapping:
+
+```text
+target_id
+backend
+layout
+semantic_action -> gamepad command
+cooldowns
+hold_durations
+axis_curves
+dead_zones
+```
+
+Example:
+
+```text
+jump -> press_button(south, 50ms)
+dodge -> press_button(east, 50ms)
+move_left -> set_left_stick(-1.0, 0.0)
+move_right -> set_left_stick(1.0, 0.0)
+aim_at -> set_right_stick(x, y)
+shoot -> set_right_trigger(1.0)
+stop_shoot -> set_right_trigger(0.0)
+```
+
+## Backend Options
+
+Possible backends:
+
+- virtual gamepad device
+- hardware controller bridge
+- emulator controller API
+- browser Gamepad API test harness
+- platform-specific HID driver
+
+Backend choice depends on platform and target.
+
+Important iPhone Mirroring caveat:
+
+- Apple documents that wireless game controllers for iPhone apps should be connected to the iPhone, not the Mac.
+- A Mac-side virtual controller may not control iPhone games through iPhone Mirroring.
+- For iPhone games, gamepad automation may require a controller bridge paired directly to the iPhone, or the touch backend if controller bridging is not available.
+
+## Backend Contract
+
+Every backend should implement:
+
+```text
+connect()
+is_available()
+get_capabilities()
+send(command)
+release_all()
+measure_latency()
+disconnect()
+```
+
+Capabilities should declare:
+
+```text
+supports_buttons
+supports_dpad
+supports_analog_sticks
+supports_triggers
+supports_rumble
+supports_low_latency
+requires_focus
+requires_pairing
+```
+
+## Safety
+
+- Always release sticks to neutral on stop.
+- Always set triggers to zero on stop.
+- Avoid holding movement indefinitely without a deadline.
+- Stop if backend disconnects.
+- Stop if target loses focus when focus is required.
+- Block inputs on payment/login/system screens.
+
+## Measurement
+
+Track:
+
+- command_create_ms
+- backend_send_ms
+- device_update_ms, if measurable
+- visual_response_ms
+- dropped_command_count
+- stale_command_count
+- held_input_duration
+- release_all_latency_ms
+
+For controller games, visual response is the real proof that the backend works.
+
+## Testing Plan
+
+1. Build a local gamepad visualizer target.
+2. Send every button and axis command.
+3. Verify neutral/release behavior.
+4. Measure p50/p95 command send latency.
+5. Test one emulator or simple controller-friendly game.
+6. Add a target mapping.
+7. Replay a recorded action trace.
+
+## Acceptance Criteria
+
+- The same semantic controller can drive at least two different controller-supported targets by changing only the mapping/backend.
+- Buttons, D-pad, sticks, and triggers are all supported in the normalized interface.
+- `release_all()` reliably neutralizes every held input.
+- Backend latency and visual response latency are measured.
+- iPhone controller support is treated as a separate backend problem, not assumed through Mac iPhone Mirroring.
+
diff --git a/plans/16-iphone-gameplay-roadmap.md b/plans/16-iphone-gameplay-roadmap.md
new file mode 100644
index 00000000..b9efd6df
--- /dev/null
+++ b/plans/16-iphone-gameplay-roadmap.md
@@ -0,0 +1,145 @@
+# iPhone Gameplay Roadmap
+
+## Goal
+
+Make the agent good at playing iPhone games through Apple's iPhone Mirroring app.
+
+This is the near-term product focus. Other targets are useful only when they help this path.
+
+## Product Thesis
+
+iPhone Mirroring turns mobile apps into a Mac window. If the agent can capture that window, understand game state, and send calibrated taps/swipes/controllers with low latency, it can play a broad class of iPhone games without custom game integrations.
+
+## Core Capabilities
+
+Build these in order:
+
+1. iPhone Mirroring window detection
+2. iPhone content-rectangle calibration
+3. synthetic tap/swipe controller
+4. screenshot capture of the mirrored content
+5. low-latency perception from screenshots
+6. game phase detection: menu, running, crashed, ad/offer, unknown
+7. safety guard for purchases, login, ads, system dialogs
+8. trace recording and replay
+9. per-game adapters
+10. model-assisted perception when heuristics are not enough
+11. optional PhoneAgent-style RPC/accessibility backend for app navigation, setup, and non-frame-critical iOS control
+
+## Game Progression
+
+### Stage 1: Harness
+
+Target:
+
+- local iPhone Safari test page
+- simple tap/swipe detector
+
+Purpose:
+
+- measure mirroring latency
+- calibrate coordinates
+- verify tap/swipe synthesis
+- test focus and stop behavior
+
+Exit criteria:
+
+- 99% tap recognition on a static target
+- 95% swipe recognition in four directions
+- p95 Mac-side action latency under 100ms
+- no stuck input after 10-minute soak
+
+### Stage 2: Simple iPhone Games
+
+Target:
+
+- tap-only games
+- puzzle/card/turn-based games
+- simple one-finger swipe games
+
+Purpose:
+
+- prove real App Store gameplay
+- build menu/retry handling
+- harden screenshot perception
+- collect traces
+
+Exit criteria:
+
+- agent can play for 3-5 minutes
+- failures are classified by perception, control, latency, or safety guard
+- no purchase/ad/account flows are touched
+
+### Stage 3: Subway Surfers
+
+Target:
+
+- Subway Surfers through iPhone Mirroring
+
+Purpose:
+
+- flagship latency and perception demo
+- lane tracking
+- obstacle detection
+- left/right/up/down swipe control
+
+Exit criteria:
+
+- agent survives longer than no-op and random baselines
+- wrong-swipe and missed-obstacle rates are measured
+- crashes are explainable from traces
+- gameplay improves across recorded runs
+
+### Stage 4: Controller-Supported iPhone Games
+
+Target:
+
+- iPhone games with controller support
+
+Purpose:
+
+- validate generic controller abstraction
+- reduce coordinate-dependence
+- broaden game coverage
+
+Exit criteria:
+
+- controller backend can drive at least one iPhone controller game
+- backend limitations through iPhone Mirroring are documented
+- touch and controller mappings share the same semantic action layer
+
+## Success Metrics
+
+Measure both latency and game competence:
+
+- p50/p95/p99 Mac-side loop latency
+- iPhone mirroring visual-response latency
+- tap/swipe recognition rate
+- stale-frame rate
+- wrong-action rate
+- missed-action rate
+- survival time
+- score/distance when readable
+- retries completed
+- safety stops
+
+## Safety Rules
+
+- Use offline or single-player games first.
+- Avoid anti-cheat and multiplayer.
+- Use a test iPhone/account where possible.
+- Stop on purchases, App Store prompts, login, messages, contacts, system settings, ads, or unknown screens.
+- Keep all remote model calls outside the reflex loop.
+- Record only the cropped mirrored game content when possible.
+
+## Immediate Build Order
+
+1. Finish the macOS synthetic controller prototype.
+2. Add iPhone Mirroring window/content detection.
+3. Add a calibration command for tap and four swipe directions.
+4. Add screenshot capture of the calibrated content rectangle.
+5. Add trace logging for every capture, perception result, and input command.
+6. Build the local iPhone Safari harness.
+7. Capture a PhoneAgent-inspired iOS control prompt and backend contract.
+8. Move to one simple iPhone game.
+9. Move to Subway Surfers.
diff --git a/plans/17-ios-control-prompt.md b/plans/17-ios-control-prompt.md
new file mode 100644
index 00000000..aa42351e
--- /dev/null
+++ b/plans/17-ios-control-prompt.md
@@ -0,0 +1,156 @@
+# iOS Control Prompt
+
+## Goal
+
+Capture the operating prompt for controlling iOS, using PhoneAgent as a reference while keeping iPhone Mirroring gameplay as the main product path.
+
+Reference:
+
+- https://github.com/rounak/PhoneAgent
+
+PhoneAgent is an experimental mobile automation project with two relevant ideas:
+
+- an in-app iPhone agent using SwiftUI, XCTest, and the OpenAI Responses API
+- an external JSON-RPC bridge that lets agents control iOS/Android devices
+
+For this project, the most useful pattern is the structured control loop: inspect context, choose one action, execute, verify, repeat.
+
+The same pattern applies on macOS through Apple's Accessibility APIs. macOS can expose an accessibility tree and actions for native controls, windows, menus, dialogs, and many app UIs. See [18-macos-accessibility.md](18-macos-accessibility.md).
+
+## Backend Positioning
+
+Use two iOS-control backends:
+
+| Backend | Best Use | Tradeoff |
+| --- | --- | --- |
+| iPhone Mirroring window backend | real-time visual gameplay, Subway Surfers, App Store games | needs screenshot perception and calibrated Mac input |
+| PhoneAgent-style RPC backend | app navigation, accessibility tree, screenshots, setup flows, non-frame-critical iOS actions | XCTest/RPC setup, not necessarily suitable for fast frame-by-frame gameplay |
+
+The gameplay reflex loop should remain iPhone Mirroring first. The RPC backend can help with setup, menus, app launching, screenshots, and accessibility-grounded verification.
+
+## PhoneAgent-Inspired Action Surface
+
+Model the generic iOS action surface around:
+
+```text
+get_tree
+get_screen_image
+get_context
+open_app
+tap
+tap_element
+enter_text
+scroll
+swipe
+stop
+```
+
+PhoneAgent's README describes these as shared RPC methods for iOS and Android, with an iOS-only `submit_prompt` for its in-app agent loop.
+
+## Core iOS Control Loop
+
+Use this prompt pattern for non-frame-critical iOS control:
+
+```text
+You are controlling an iOS device.
+
+Loop:
+1. Get context: accessibility tree plus screenshot when available.
+2. Decide the next single safe action.
+3. Prefer accessibility-tree targets when the UI is structured.
+4. Use coordinate/touch actions only when necessary.
+5. Execute one action.
+6. Verify the result with a fresh tree, screenshot, or context.
+7. Stop or ask for help on payment, login, system, privacy, unknown, or unsafe screens.
+
+Rules:
+- Use one action at a time.
+- Do not queue actions against stale UI.
+- Re-read the tree after animations, navigation, or failed taps.
+- Prefer tap_element over raw tap when a reliable element frame exists.
+- Prefer get_context when both tree and screenshot are useful.
+- For games, use screenshot perception and the fast controller instead of slow tree reasoning.
+- Keep remote model calls outside the reflex loop.
+```
+
+## Game-Specific Prompt Boundary
+
+For iPhone games:
+
+- use the prompt loop for menus, setup, app launch, and recovery
+- use the fast screenshot/controller loop for live gameplay
+- do not ask the slow planner to decide every dodge, tap, or swipe
+- use `game_phase` to decide whether the slow iOS prompt loop is allowed
+
+Recommended boundary:
+
+```text
+menu / setup / crashed / unknown -> iOS control prompt may act
+running / live gameplay -> fast controller acts
+payment / login / system / ad_or_offer -> stop or require explicit approval
+```
+
+## World-State Additions
+
+Add optional iOS-control fields:
+
+```text
+ios_backend
+bundle_identifier
+accessibility_tree_id
+screenshot_id
+focused_app
+game_phase
+unsafe_screen_reason
+last_verified_action_id
+```
+
+## Backend Contract
+
+Whether the implementation is PhoneAgent, iPhone Mirroring, or a future bridge, expose a common interface:
+
+```text
+get_context() -> tree?, screenshot?, metadata
+open_app(bundle_identifier)
+tap(x, y)
+tap_element(frame_or_element_id)
+enter_text(target, text)
+scroll(x, y, dx, dy)
+swipe(x, y, direction)
+stop()
+```
+
+Every response should include enough fresh context to verify progress when practical.
+
+## Safety Rules
+
+- Keep iOS control localhost/local-device oriented.
+- Do not enter passwords, 2FA codes, payment details, or private messages automatically.
+- Stop on App Store purchases, login screens, permission prompts, messages, contacts, system settings, or unknown sensitive screens.
+- Use test devices/accounts where possible.
+- Screenshot artifacts can contain sensitive phone data; crop to game content and redact when possible.
+
+## When To Use PhoneAgent Ideas
+
+Use them for:
+
+- opening apps by bundle identifier
+- reading accessibility trees
+- tapping known UI elements
+- entering text into structured fields
+- taking screenshots for verification
+- recovering from menus or settings screens
+
+Avoid them for:
+
+- per-frame Subway Surfers decisions
+- low-latency dodge/jump/roll loops
+- any gameplay path where RPC round trips make state stale
+
+## First Milestones
+
+1. Keep iPhone Mirroring as the primary gameplay backend.
+2. Define the shared iOS control interface above.
+3. Add an optional PhoneAgent-style backend adapter plan.
+4. Build prompts that separate slow iOS UI control from fast gameplay control.
+5. Use accessibility/context only when it improves reliability without hurting reflex latency.
diff --git a/plans/18-macos-accessibility.md b/plans/18-macos-accessibility.md
new file mode 100644
index 00000000..73e9e669
--- /dev/null
+++ b/plans/18-macos-accessibility.md
@@ -0,0 +1,160 @@
+# macOS Accessibility
+
+## Goal
+
+Use macOS Accessibility as a PhoneAgent-like tree/action backend for Mac apps, window management, setup flows, and non-frame-critical UI control.
+
+This complements the fast screenshot/input loop. It does not replace low-latency visual gameplay perception.
+
+## Feasibility
+
+Yes, macOS has a system Accessibility API based around `AXUIElement`.
+
+Apple describes `AXUIElement` as the object assistive applications use to communicate with and control accessible applications running in macOS. The API can expose attributes, children, positions, actions, focused elements, and notifications.
+
+Useful Apple references:
+
+- `AXUIElement.h`: https://developer.apple.com/documentation/applicationservices/axuielement_h
+- `AXUIElement`: https://developer.apple.com/documentation/applicationservices/axuielement
+- `AXUIElementCreateApplication`: https://developer.apple.com/documentation/applicationservices/1459374-axuielementcreateapplication
+- `AXUIElementCopyElementAtPosition`: https://developer.apple.com/documentation/applicationservices/1462077-axuielementcopyelementatposition
+- Accessibility Inspector: https://developer.apple.com/documentation/accessibility/accessibility-inspector
+
+## Best Uses
+
+Use macOS Accessibility for:
+
+- finding the iPhone Mirroring window
+- reading window title, position, size, and focus state
+- bringing a target app/window forward
+- detecting native dialogs
+- detecting payment, login, permission, or system prompts
+- pressing native buttons and menu items
+- reading labels and values in normal Mac apps
+- verifying that an action changed the UI
+- setup and recovery outside live gameplay
+
+For iPhone Mirroring specifically:
+
+- Accessibility can help control the Mac-side iPhone Mirroring app and window.
+- It probably cannot see the internal game objects inside an iPhone game.
+- Live gameplay should still rely on screenshot perception and synthetic taps/swipes.
+
+## Poor Uses
+
+Do not rely on macOS Accessibility for:
+
+- per-frame gameplay decisions
+- canvas/WebGL game internals
+- iPhone game internals inside the mirrored video stream
+- highly animated visual state
+- latency-critical dodge/jump/shoot loops
+- apps that expose incomplete or stale accessibility trees
+
+## Operating Loop
+
+Use the same inspect-act-verify pattern as PhoneAgent:
+
+```text
+1. Get the active app/window accessibility tree.
+2. Identify a safe target element by role, title, label, value, or frame.
+3. Perform one action.
+4. Re-read the tree or screenshot.
+5. Verify the result.
+6. Stop on unknown, sensitive, payment, login, or system screens.
+```
+
+Rules:
+
+- Use one action at a time.
+- Do not queue actions against stale trees.
+- Prefer accessibility actions for native controls.
+- Fall back to synthetic mouse/keyboard only when needed.
+- Keep AX calls outside the hot gameplay loop unless measured under budget.
+
+## Action Surface
+
+Expose a backend similar to the iOS control prompt:
+
+```text
+get_tree(app_or_window)
+get_focused_window()
+get_element_at_position(x, y)
+perform_action(element_id, action)
+set_value(element_id, value)
+tap_element(element_id)
+focus_window(window_id)
+get_window_rect(window_id)
+stop()
+```
+
+Bridge into the synthetic controller:
+
+```text
+semantic_action -> accessibility action
+semantic_action -> synthetic mouse/keyboard action
+semantic_action -> screenshot/gameplay action
+```
+
+## Permissions
+
+The process needs Accessibility trust.
+
+Use:
+
+```text
+AXIsProcessTrusted()
+AXIsProcessTrustedWithOptions(...)
+```
+
+If not trusted, show a setup path:
+
+```text
+System Settings -> Privacy & Security -> Accessibility
+```
+
+## iPhone Mirroring Workflow
+
+Use macOS Accessibility to support iPhone Mirroring:
+
+1. find the iPhone Mirroring app/window
+2. read its window bounds
+3. focus the window before input
+4. detect if the window moved or resized
+5. detect Mac-side dialogs or disconnection state
+6. hand the content rectangle to screenshot capture
+7. hand input coordinates to the synthetic controller
+
+The AX tree helps with the container. The screenshot/model loop handles the game content.
+
+## Latency And Reliability
+
+Track:
+
+- ax_tree_ms
+- ax_action_ms
+- ax_verify_ms
+- tree_stale_count
+- action_failed_count
+- inaccessible_element_count
+- fallback_to_synthetic_input_count
+
+Accessibility APIs can block or return stale/incomplete data if the target app is busy or not fully accessible. Keep timeouts short and do not let AX calls block the reflex loop.
+
+## First Milestones
+
+1. Check Accessibility trust status from the Mac synthetic controller.
+2. Find the focused window and dump basic AX attributes.
+3. Find the iPhone Mirroring window and read its bounds.
+4. Detect focus loss before sending synthetic input.
+5. Add an accessibility-backed window guard to the iPhone gameplay loop.
+6. Add tree/action/verify support for native Mac setup dialogs.
+
+## Acceptance Criteria
+
+- The system can identify the active target window through Accessibility.
+- The system can refuse input when the wrong window is focused.
+- The system can read iPhone Mirroring window bounds for calibration.
+- Accessibility calls are timed and never block the gameplay hot path.
+- Native Mac dialogs can be detected as safety stops.
+