Skip to content

Open source CapCut alternative.

TypeScript

Add plans

David Lef11eb1624275
diff --git a/plans/00-overview.md b/plans/00-overview.md
index c46b4203..f11b42ba 100644
--- a/plans/00-overview.md
+++ b/plans/00-overview.md
@@ -24,8 +24,8 @@ That means:
```text
Screen Capture
- -> Perception
- -> World State
+ -> Off-The-Shelf Vision
+ -> Game State Tensor / World State
-> Fast Controller
-> Action Engine
-> Keyboard / Mouse / Controller
@@ -72,6 +72,8 @@ Every frame should use local, bounded-cost logic:
- [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
+- [19-ai-harness.md](19-ai-harness.md): slow-path memory, LLM/VLM connection, model routing, and update plan
+- [20-off-the-shelf-run-loop.md](20-off-the-shelf-run-loop.md): off-the-shelf perception, deterministic control, and low-latency runtime stack
## System Priorities
@@ -83,6 +85,7 @@ Every frame should use local, bounded-cost logic:
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.
+9. Off-the-shelf components before custom model work.
## First Target Demo
diff --git a/plans/03-fast-controller.md b/plans/03-fast-controller.md
index 5ccdaeb1..2e122e1a 100644
--- a/plans/03-fast-controller.md
+++ b/plans/03-fast-controller.md
@@ -39,6 +39,17 @@ World State
-> Action Command
```
+The off-the-shelf perception path uses the same contract:
+
+```text
+Detector / Segmenter / OCR / Template
+ -> Game State
+ -> Rule / State Machine
+ -> Action Command
+```
+
+See [20-off-the-shelf-run-loop.md](20-off-the-shelf-run-loop.md) for the off-the-shelf runtime plan.
+
The policy selector chooses a small controller:
- `combat_policy`
@@ -59,9 +70,11 @@ Use the simplest viable method first:
| 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 |
+| game-specific skill | target-specific rule set over detector/OCR/SAM outputs |
| uncertainty | safe default plus slow-planner request |
+For aiming, movement, dodging, recoil control, and tap/swipe timing, do not use an LLM. Use deterministic logic over current perception state.
+
## Timing
The controller should run faster than perception. Target decision time:
@@ -96,10 +109,12 @@ The fast controller should treat planner output as configuration, not a blocking
3. Add policy-selection logic.
4. Add confidence-aware fallback behavior.
5. Record every chosen action with the state snapshot id.
+6. Add detector/OCR/template-derived state inputs.
+7. Replay recorded state traces before live input.
## Acceptance Criteria
- p95 decision time is under 20ms.
- Controller can keep acting while planner is unavailable.
- Actions are reproducible from recorded world-state traces.
-
+- Perception output cannot bypass action projection or safety guards.
diff --git a/plans/07-rollout.md b/plans/07-rollout.md
index 24b01f20..c8d83e3a 100644
--- a/plans/07-rollout.md
+++ b/plans/07-rollout.md
@@ -58,6 +58,26 @@ Success:
- p95 reflex latency remains under 100ms
- failures are diagnosable from traces
+## Phase 2.5: Off-The-Shelf Vision Upgrade
+
+Add stronger off-the-shelf perception only after the deterministic loop exposes a real gap.
+
+Deliverables:
+
+- fixed game-state schema
+- YOLO-family detector candidate
+- SAM/MobileSAM/FastSAM fallback candidate, if masks are needed
+- OCR or template matcher for UI/text signals
+- runtime benchmark through the target execution provider
+- replay state/action report
+- live input-disabled canary
+
+Success:
+
+- off-the-shelf perception improves one target metric against the simpler baseline
+- detector/segmenter/OCR p95 stays inside the reflex budget
+- all perception outputs pass through state validation and safety guards
+
## Phase 3: Slow Planner
Add high-level strategy without touching the reflex latency path.
@@ -101,7 +121,7 @@ Success:
- macOS capture backend.
- macOS synthetic input backend.
- First iPhone Mirroring calibration method.
-- Whether the first controller is heuristic, trained, or hybrid.
+- Whether the first controller is pure rules or rules plus off-the-shelf perception.
## Suggested Default Path
@@ -113,4 +133,5 @@ For fastest learning:
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.
+7. Add SAM/OCR/LLM slow-path recovery only where simple perception fails.
+8. Add the slow planner after the reflex loop already works.
diff --git a/plans/09-screenshot-model-inference.md b/plans/09-screenshot-model-inference.md
index 7d0bd536..544de8e0 100644
--- a/plans/09-screenshot-model-inference.md
+++ b/plans/09-screenshot-model-inference.md
@@ -18,10 +18,10 @@ Large VLMs can still be useful for slow planner snapshots, debugging, labeling,
Screen Region
-> Raw Pixel Buffer
-> Crop / Resize / Normalize
- -> Low-Latency Vision Model
- -> Detections / Labels / Embeddings
- -> World State
- -> Fast Controller
+ -> Vision Encoder
+ -> Detections / Labels / Embeddings / State Tensor
+ -> World State or Game State Tensor
+ -> Fast Controller / Reflex Policy
```
Keep screenshots as raw pixel buffers for the hot path. Encoding to PNG or JPEG is usually a slow-path/debug operation.
@@ -36,7 +36,7 @@ Use a model only for perception questions that justify it:
- 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"
+- off-the-shelf 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.
@@ -62,8 +62,26 @@ Pick the runtime based on measured latency in the target environment:
- WebGPU/WebNN for browser-contained demos when practical
- CPU inference only when the model is tiny and predictable
+Local LLM runners such as Ollama are useful for slow-path reasoning, planning, dialogue, UI understanding, and trace analysis. They should not be assumed suitable for the gameplay hot path just because they run locally. For per-frame control, prefer off-the-shelf detectors, segmenters, OCR, templates, classical CV, and deterministic policies that are benchmarked under the target p95 latency budget.
+
The plan should keep the model interface abstract so runtimes can be swapped after benchmarking.
+## Candidate Vision Models
+
+Use candidates based on the target task:
+
+| Candidate | Best Use | Hot-Path Risk |
+| --- | --- | --- |
+| YOLO-family nano/small model | enemies, obstacles, UI elements, minimap markers, health bars | postprocessing and capture copies can dominate if careless |
+| SAM / SAM2 | high-quality masks and image/video segmentation | usually too expensive for every frame |
+| MobileSAM / FastSAM | lighter masks, irregular affordances, scene segmentation | still measure carefully before hot-path use |
+| OCR | labels, scores, menus, countdowns | full-frame OCR is usually too slow |
+| templates/classical CV | stable buttons, icons, bars, lanes, motion | brittle if art/theme changes |
+
+Use current Ultralytics YOLO-family nano/small models as first detector candidates because they have mature export paths and published runtime benchmarks, but every latency claim must be remeasured on target traces and target hardware.
+
+Segmentation and OCR belong outside the per-frame loop until proven otherwise.
+
## Hot-Path Rules
- Warm the model before live control starts.
@@ -71,6 +89,8 @@ The plan should keep the model interface abstract so runtimes can be swapped aft
- Avoid cross-process image copies.
- Avoid image compression in the reflex loop.
- Use quantized or smaller models when accuracy allows.
+- Prefer fp16 first, int8 only after calibration preserves action quality.
+- Prefer fixed input shapes when using TensorRT/CUDA graphs.
- Drop stale frames instead of queuing inference.
- Emit confidence with every model result.
- Keep the controller dependent on structured outputs, not raw model tensors.
@@ -141,12 +161,12 @@ For games, benchmark on recorded traces first, then live runs.
Large VLMs can still help outside the reflex loop:
- identify what a new screen means
-- label training data
+- explain unfamiliar UI
- 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.
+Slow-path outputs should become hints or updated configuration. They should not block immediate control.
## First Milestones
diff --git a/plans/10-gaps-to-expand.md b/plans/10-gaps-to-expand.md
index 81881a09..1a15d8b4 100644
--- a/plans/10-gaps-to-expand.md
+++ b/plans/10-gaps-to-expand.md
@@ -154,8 +154,6 @@ Expand into:
- frame recording format
- world-state recording format
- action trace format
-- labeling workflow
-- dataset splits
- retention policy
- privacy filtering
- trace compression
@@ -163,7 +161,7 @@ Expand into:
Deliverable:
-- `data-and-replay.md` with file formats and commands for record, replay, label, and compare
+- `data-and-replay.md` with file formats and commands for record, replay, inspect, and compare
Why it matters:
@@ -219,6 +217,8 @@ This is how the project avoids hardcoding one demo while still staying latency-f
The screenshot-model plan needs a way to choose and improve models.
+See [19-ai-harness.md](19-ai-harness.md) for the slow-path model registry, provider connection layer, role-based model routing, and model update workflow. See [20-off-the-shelf-run-loop.md](20-off-the-shelf-run-loop.md) for the hot-path off-the-shelf perception and deterministic control plan.
+
Expand into:
- candidate model list
@@ -229,7 +229,7 @@ Expand into:
- versioning
- rollback
- quality gates
-- training/fine-tuning path, if needed
+- runtime compatibility checks
Deliverable:
@@ -243,6 +243,8 @@ Do not pick a model from general benchmark numbers. Pick it from target traces.
The slow planner needs boundaries for what it can change.
+See [19-ai-harness.md](19-ai-harness.md) for memory layers, memory write rules, planner hint validation, and model-backed policy update boundaries.
+
Expand into:
- memory format
@@ -332,4 +334,3 @@ The target profile should force concrete answers for:
- success metric
- safety constraints
- first replay traces
-
diff --git a/plans/19-ai-harness.md b/plans/19-ai-harness.md
new file mode 100644
index 00000000..2f7c673c
--- /dev/null
+++ b/plans/19-ai-harness.md
@@ -0,0 +1,596 @@
+# AI Harness
+
+## Goal
+
+Build the slow-path AI harness that connects the agent to LLMs/VLMs, manages memory, routes model calls, validates structured planner output, and keeps model choices updateable without touching the low-latency reflex loop.
+
+The harness is the agent's reasoning and memory layer. It supports planning, recovery, trace explanation, model-assisted perception setup, and long-running improvement. It does not drive frame-by-frame gameplay.
+
+## Core Rule
+
+The AI harness must never block the reflex loop.
+
+Remote LLM/VLM calls can help the agent think, remember, and recover, but the fast controller must keep running from local world state and the latest valid planner hints.
+
+```text
+Capture / Perception / Controller / Action
+ -> local, bounded, latest-frame-wins
+
+AI Harness
+ -> async, slow-path, memory-backed, validated output
+```
+
+If the harness is slow, offline, rate-limited, or wrong, the controller continues with local policy, stale hint expiry, and safe fallback behavior.
+
+## Responsibilities
+
+- connect to model providers
+- choose the right model for each slow-path job
+- build compact model inputs from world state, traces, screenshots, DOM summaries, and user goals
+- retrieve useful memory before a planner call
+- validate structured model outputs
+- write approved memory updates
+- produce planner hints for the fast controller
+- summarize failure traces
+- review screenshots or traces for evaluation
+- track model latency, cost, output quality, and schema validity
+- provide a safe model update process
+
+## Non-Responsibilities
+
+- per-frame action decisions
+- direct OS input
+- direct mutation of controller state without validation
+- raw screenshot logging without redaction rules
+- choosing local fast-vision models without trace benchmarks
+- silently switching production model behavior
+
+## Architecture
+
+```text
+World State History
+Trace Buffer
+User Goal
+Target Adapter
+Screenshots / DOM Summary
+ -> Snapshot Builder
+ -> Memory Retriever
+ -> Model Router
+ -> Provider Adapter
+ -> Structured Output Validator
+ -> Planner Hint Bus
+ -> Memory Writer
+ -> Trace / Metrics Sink
+```
+
+The harness should be a sidecar service or worker owned by the agent runtime. It reads snapshots and emits typed outputs. It should not own capture, input, or the controller tick.
+
+## Memory Layers
+
+Use several small memory types instead of one vague long-term memory store.
+
+### Short-Term Run Memory
+
+Lives in process for the current run.
+
+Contains:
+
+- current goal
+- active plan
+- latest planner hints
+- recent world-state summaries
+- recent failures
+- recent user instructions
+- active safety stops
+
+This memory should be cheap, small, and cleared when the run ends.
+
+### Trace Memory
+
+Lives with recorded runs.
+
+Contains:
+
+- frame ids
+- world-state snapshots
+- action decisions
+- planner hint ids
+- failures and recoveries
+- model calls and output validation status
+
+Trace memory is the evidence layer. Any durable lesson should point back to a trace id.
+
+### Target Memory
+
+Lives per game/app target.
+
+Contains:
+
+- target-specific strategies
+- useful regions of interest
+- common screens and menus
+- calibration notes
+- safe recovery policies
+- known bad planner suggestions
+- successful policy sequences
+
+Target memory should be versioned with the target adapter.
+
+### Semantic Memory
+
+Lives in a searchable store.
+
+Contains:
+
+- summarized lessons from traces
+- user preferences
+- task instructions that should carry across sessions
+- target notes
+- prompt/eval learnings
+
+Use embeddings only for text summaries and metadata. Do not embed raw screenshots unless there is a deliberate image-retrieval plan.
+
+### Model Registry Memory
+
+Lives as configuration, not generated memory.
+
+Contains:
+
+- provider ids
+- model ids
+- role assignments
+- feature support
+- context limits
+- reasoning settings
+- prompt versions
+- eval scores
+- rollout status
+- rollback model id
+- last verified date
+- source docs URL
+
+The model registry is the control plane for "which model should this job use?"
+
+## Memory Record Shape
+
+Every durable memory item should be inspectable and deleteable.
+
+```text
+memory_id
+memory_type
+target_id
+scope
+content
+metadata
+source_trace_id
+source_frame_id
+source_model_call_id
+confidence
+created_at
+expires_at
+embedding_model
+embedding_version
+schema_version
+```
+
+## Memory Write Rules
+
+- The model may propose memory writes, but deterministic code approves them.
+- Every write needs a source: user instruction, trace id, evaluation result, or explicit operator note.
+- Memory must have scope: run, target, global, or user.
+- Memory must have a TTL unless it is a deliberate durable target fact.
+- Do not store secrets, account data, payment screens, login screens, personal messages, or unrelated desktop content.
+- Prefer summaries over raw logs.
+- Prefer "observed in trace X" over unsupported claims.
+- Conflicting memories should be kept with confidence and source, not silently merged.
+
+## Retrieval Rules
+
+Before each planner call, build a small context package:
+
+- current user goal
+- latest summarized world state
+- recent failures
+- current valid planner hints
+- target adapter facts
+- top matching target memories
+- top matching semantic memories
+- screenshot or DOM summary only when needed
+
+The retrieval budget should be explicit:
+
+```text
+working_state_tokens
+target_memory_tokens
+semantic_memory_tokens
+trace_summary_tokens
+visual_input_budget
+max_total_input_tokens
+```
+
+If retrieval returns too much, summarize or drop lower-confidence memory. Do not send the full trace or full DOM tree by default.
+
+## Provider Connection Layer
+
+Expose a small provider-neutral interface.
+
+```text
+list_models(provider)
+generate_text(request)
+generate_structured(request, schema)
+analyze_image(request, schema)
+embed_text(request)
+stream_events(request)
+cancel(request_id)
+```
+
+The first provider should be OpenAI through the Responses API. Keep the adapter narrow so Anthropic, Google, Ollama, local models, or a custom inference server can be added later without changing planner/controller contracts.
+
+## OpenAI Connection Plan
+
+Use the Responses API for new slow-path model calls because it supports multimodal inputs, tool use, structured outputs, stateful workflows, and built-in agentic primitives.
+
+Default connection rules:
+
+- read `OPENAI_API_KEY` from the environment
+- use `store: false` by default for privacy-sensitive screen-agent calls
+- allow opt-in stateful conversation only when the user/product explicitly wants server-side state
+- use structured outputs for planner hints and memory write proposals
+- place static instructions and schemas before variable state to benefit from prompt caching
+- set timeouts per job type
+- stream when useful for operator visibility, but publish only validated final hints to the controller
+- log request metadata, not secrets or raw sensitive content
+
+## Ollama And Local LLM Plan
+
+Ollama can be useful for local slow-path AI work:
+
+- reasoning
+- planning
+- dialogue
+- UI understanding
+- trace summarization
+- offline prompt and memory experiments
+
+It is probably not the right tool for the ultra-low-latency gameplay control loop. Even when local, a chat LLM still pays transformer inference costs: tokenization, attention, matrix multiplication, KV-cache management, and next-token sampling. Those costs can be fine for a planner that runs every few seconds, but they are a bad fit for a controller that needs fresh actions in under 100ms and often much faster.
+
+Treat Ollama as a local harness provider, not a reflex controller.
+
+```text
+Ollama
+ -> local planner / dialogue / UI interpretation
+ -> async hint generation
+ -> local privacy-friendly experimentation
+
+Not Ollama
+ -> per-frame dodging
+ -> aiming
+ -> tap/swipe timing
+ -> obstacle reaction
+```
+
+For the hot path, prefer:
+
+- smaller specialized models
+- ONNX Runtime
+- TensorRT, Core ML, DirectML, or OpenVINO where they reduce p95 latency
+- direct GPU inference with preallocated buffers
+- vision models optimized for less than 50ms p95 latency
+- off-the-shelf detectors, segmenters, OCR, and direct GPU inference
+- classical CV, templates, and finite-state policies when they beat heavier models
+
+Ollama is still useful as inspiration for the local runtime direction. It runs local models through an inference server and can use GPU acceleration depending on platform and hardware. Its local stack is shaped around the same low-level work any transformer runtime must do: model loading, quantized weights, KV cache, CPU/GPU scheduling, and sampling. The lesson for this project is to keep local inference close to the data, warmed up, measured, and specialized.
+
+Useful Ollama checks:
+
+- `ollama ps` to see whether a model is loaded on GPU, CPU, or split CPU/GPU
+- `OLLAMA_CONTEXT_LENGTH` to control context size
+- `OLLAMA_NUM_PARALLEL` and `OLLAMA_MAX_QUEUE` to avoid hidden request queues
+- local-only mode when remote/cloud features are not desired
+
+If an Ollama-backed planner is added, give it strict timeouts, queue size 1, latest-request-wins cancellation, schema validation, and the same hint expiry rules as remote providers.
+
+## Local Reasoning Model Candidates
+
+Local reasoning models are candidates for the AI harness, not the reflex policy.
+
+| Candidate | Best Use | Notes |
+| --- | --- | --- |
+| Qwen3 8B | local reasoning, coding-adjacent planning, tool-style workflows | strong open model candidate; benchmark thinking vs non-thinking modes separately |
+| Phi-family small models | fast lightweight planning, tool calling, tactical summaries | use the smallest model that passes schema/eval gates |
+| Gemma 3 | local text+image reasoning, UI understanding, broad language support | useful when a small multimodal model is enough |
+| PaliGemma | fine-tuned visual question answering, OCR-like UI tasks, detection/segmentation experiments | better as a fine-tuned VLM tool than a reflex controller |
+
+These models can support objectives, coaching, memory, strategy adaptation, and trace review. They should never emit direct input. Their outputs must still become validated planner hints.
+
+## Model Roles
+
+Do not hardcode one model everywhere. Assign models by role.
+
+| Role | Default Candidate | Use |
+| --- | --- | --- |
+| `planner_default` | `gpt-5.4-mini` | routine slow planning, recovery hints, target reasoning |
+| `planner_strong` | `gpt-5.5` | hard recovery, unfamiliar screens, complex strategy, plan generation |
+| `planner_deep_eval` | `gpt-5.5-pro` | offline trace critique or high-value evaluation only |
+| `planner_cheap` | `gpt-5.4-nano` | simple classification, short summaries, routing decisions |
+| `planner_local` | Qwen3 8B, Phi-family, or Gemma 3 through Ollama/vLLM/llama.cpp | local reasoning/dialogue/UI understanding outside the reflex loop |
+| `vision_local_slow` | Gemma 3 or PaliGemma candidate | local multimodal UI understanding outside the reflex loop |
+| `vision_snapshot` | `gpt-5.4-mini` or `gpt-5.5` | occasional screenshot understanding outside the reflex loop |
+| `memory_embed_default` | `text-embedding-3-small` | default semantic memory retrieval |
+| `memory_embed_high_quality` | `text-embedding-3-large` | offline reindexing or higher-quality retrieval experiments |
+| `local_fast_vision` | target-specific local model | hot-path perception, selected only from target traces |
+
+Current OpenAI docs list GPT-5.5 as the flagship model for complex coding/professional work and GPT-5.4 mini/nano as lower-latency/lower-cost options. Re-check the model docs before implementation because model names, pricing, rate limits, and feature support change.
+
+## Model Routing
+
+Route by job type, risk, latency tolerance, and failure history.
+
+```text
+if job is hot_path:
+ reject remote model call
+ reject general chat LLM call unless a measured specialized local model meets the budget
+
+if job is simple classification or summarization:
+ use planner_cheap
+
+if job requires local-only privacy and can tolerate slower output:
+ use planner_local
+
+if job is normal goal planning:
+ use planner_default
+
+if confidence is low or recovery has failed repeatedly:
+ escalate to planner_strong
+
+if job is offline benchmark, critique, or prompt migration:
+ optionally use planner_deep_eval
+```
+
+The router should return:
+
+```text
+model_role
+provider
+model_id
+reasoning_effort
+timeout_ms
+max_output_tokens
+fallback_role
+schema_id
+prompt_version
+```
+
+## Structured Planner Output
+
+The harness should emit controller hints, not prose.
+
+```text
+hint_id
+target_id
+goal
+policy
+priorities
+regions_of_interest
+avoid_actions
+recovery_action
+confidence
+expires_at
+source_model_call_id
+source_memory_ids
+memory_write_proposals
+```
+
+Validation rules:
+
+- schema must validate
+- unknown actions are rejected
+- unsafe actions are rejected
+- stale world-state references are rejected
+- low-confidence hints do not replace high-confidence active hints unless the controller asks for recovery
+- every hint expires
+
+## Prompt Shape
+
+Keep planner prompts compact and stable.
+
+```text
+System:
+ role, safety rules, output schema, controller contract
+
+Static target context:
+ adapter facts, action space, known safe/unsafe behavior
+
+Dynamic state:
+ current goal, latest world-state summary, recent failures
+
+Retrieved memory:
+ top relevant target/semantic memories with ids
+
+Visual input:
+ only the current crop/screenshot when needed
+
+Output:
+ strict JSON planner hint plus memory write proposals
+```
+
+Prompt versions should be stored beside model registry entries. Any prompt change should be evaluated on recorded traces before becoming default.
+
+## Model Update Flow
+
+Model updates are a release process, not a string replacement.
+
+1. Check provider availability with the provider model-list endpoint.
+2. Read current official provider docs for model capabilities, pricing, rate limits, deprecations, and migration notes.
+3. Add or update a candidate in the model registry with `status: candidate`.
+4. Run the replay/eval suite on representative traces.
+5. Compare schema validity, hint quality, memory write quality, latency, cost, and recovery success.
+6. Run a canary target with the candidate model behind a feature flag.
+7. Promote the model role only if it beats or matches the current default on the target metrics.
+8. Keep the previous model as rollback.
+9. Record the docs URLs and verification date.
+
+## Model Registry Shape
+
+```text
+role
+provider
+model_id
+snapshot_id
+endpoint
+supports_text
+supports_image_input
+supports_structured_output
+supports_tools
+supports_streaming
+reasoning_effort_default
+context_window
+max_output_tokens
+timeout_ms
+fallback_role
+prompt_version
+eval_suite_id
+last_eval_score
+last_verified_at
+docs_url
+status
+rollback_model_id
+```
+
+Prefer role references in code:
+
+```text
+planner_default
+planner_strong
+memory_embed_default
+```
+
+Avoid scattering literal model ids through prompts, adapters, and tests.
+
+## Where To Look
+
+For OpenAI model/API work, use official docs first:
+
+- [Latest model guide](https://developers.openai.com/api/docs/guides/latest-model)
+- [Models catalog](https://developers.openai.com/api/docs/models)
+- [All models](https://developers.openai.com/api/docs/models/all)
+- [Compare models](https://developers.openai.com/api/docs/models/compare)
+- [Responses API guide](https://developers.openai.com/api/docs/guides/migrate-to-responses)
+- [Model list API](https://developers.openai.com/api/reference/resources/models/methods/list)
+- [Embeddings guide](https://developers.openai.com/api/docs/guides/embeddings)
+- [Conversation state](https://developers.openai.com/api/docs/guides/conversation-state)
+- [Compaction](https://developers.openai.com/api/docs/guides/compaction)
+- [Prompt caching](https://developers.openai.com/api/docs/guides/prompt-caching)
+- [Pricing](https://developers.openai.com/api/docs/pricing)
+- [Rate limits](https://developers.openai.com/api/docs/guides/rate-limits)
+- [Deprecations](https://developers.openai.com/api/docs/deprecations)
+- [Changelog](https://developers.openai.com/api/docs/changelog)
+
+For Ollama and local LLM provider work, use official docs first:
+
+- [Ollama docs](https://docs.ollama.com/)
+- [Ollama FAQ](https://docs.ollama.com/faq)
+- [Ollama API reference](https://docs.ollama.com/api)
+- [Ollama GPU docs](https://docs.ollama.com/gpu)
+- [llama.cpp repository](https://github.com/ggml-org/llama.cpp)
+- [Qwen3 8B model card](https://huggingface.co/Qwen/Qwen3-8B)
+- [Microsoft Phi models](https://azure.microsoft.com/en-us/products/phi/)
+- [Microsoft Phi-4-mini model card](https://huggingface.co/microsoft/Phi-4-mini-instruct)
+- [Google Gemma docs](https://ai.google.dev/gemma/docs)
+- [Gemma 3 model card](https://ai.google.dev/gemma/docs/core/model_card_3)
+- [PaliGemma model card](https://huggingface.co/google/paligemma-3b-pt-224)
+
+For local fast models, trust local evidence first:
+
+- recorded target traces
+- latency reports
+- false-positive/false-negative reports
+- missed-action and wrong-action counts
+- replay comparison results
+- hardware-specific baselines
+
+General benchmark numbers are useful only for choosing candidates. Target traces decide what ships.
+
+## Observability
+
+Every model call should emit:
+
+```text
+model_call_id
+provider
+model_id
+model_role
+prompt_version
+schema_id
+input_token_estimate
+output_token_count
+latency_ms
+timeout_ms
+retry_count
+cache_hit_status
+validation_status
+memory_read_count
+memory_write_proposal_count
+accepted_memory_write_count
+source_trace_id
+source_state_id
+```
+
+Add aggregate reports:
+
+- model latency p50/p95/p99 by role
+- schema validation failure rate
+- planner hint acceptance rate
+- memory write acceptance rate
+- fallback/escalation count
+- cost by target/run
+- recovery success after planner intervention
+
+## Failure Handling
+
+The harness should degrade quietly and visibly.
+
+- timeout returns no new hint
+- invalid output is rejected and traced
+- rate limit triggers backoff and fallback model if safe
+- repeated invalid output disables the model role for the run
+- failed memory retrieval uses target defaults only
+- failed memory write drops the write, not the run
+- provider outage leaves controller running with local policy
+
+## Privacy And Safety
+
+- Remote model calls are opt-in per product mode.
+- Default to `store: false` for screen-agent calls.
+- Redact or block sensitive screens before remote upload.
+- Never send payment, login, account, private message, or unrelated desktop content to a remote model.
+- Log model metadata separately from prompt contents.
+- Keep screenshot retention short unless the user records a trace intentionally.
+- Memory deletion must be possible by target, run, and user scope.
+- The harness can recommend actions only through validated planner hints.
+
+## First Milestones
+
+1. Define model registry schema and role names.
+2. Build the OpenAI Responses provider adapter.
+3. Add one structured planner hint schema.
+4. Build short-term run memory and target memory as JSONL files.
+5. Add text embedding support for semantic memory.
+6. Add snapshot builder with screenshot/DOM redaction hooks.
+7. Add model router with default, cheap, strong, and fallback roles.
+8. Add optional Ollama provider support for local slow-path planning.
+9. Add memory write proposals with deterministic approval.
+10. Add trace events for model calls and memory operations.
+11. Add a replay/eval command for model and prompt changes.
+12. Add a model update checklist that writes `last_verified_at` and docs URLs.
+
+## Acceptance Criteria
+
+- No remote model call appears in the reflex-loop trace.
+- The controller can continue for a full run with the harness disabled.
+- Planner hints are schema-validated and expire automatically.
+- Memory writes are source-linked, scoped, and deleteable.
+- The model registry is the only place default model ids are assigned.
+- Model upgrades require replay/eval results before promotion.
+- A failed model call cannot produce direct input.
+- A trace can explain which memories and model outputs influenced a planner hint.
diff --git a/plans/20-off-the-shelf-run-loop.md b/plans/20-off-the-shelf-run-loop.md
new file mode 100644
index 00000000..bab85cc8
--- /dev/null
+++ b/plans/20-off-the-shelf-run-loop.md
@@ -0,0 +1,313 @@
+# Off-The-Shelf Run Loop
+
+## Goal
+
+Build the first real-time game assistant from existing components instead of custom model work.
+
+Use LLMs, open-vocabulary detectors, Segment Anything-style models, OCR, templates, classical CV, and deterministic controllers. The system should be useful before any custom model work exists.
+
+## Target Shape
+
+```text
+Screen Capture
+ -> Crop / Normalize
+ -> Off-The-Shelf Vision
+ -> Game State
+ -> Deterministic Controller
+ -> Action Engine
+ -> Mouse / Keyboard / Controller
+
+Reasoning LLM
+ <-> Goals / Hints / UI Understanding / Memory / Recovery
+```
+
+The hot loop is still local and bounded. The LLM can reason beside it, but action timing comes from deterministic logic over structured state.
+
+## Core Rule
+
+Do not build a custom model pipeline for the first version.
+
+The first version should prove:
+
+- capture is reliable
+- perception can extract useful state from off-the-shelf models
+- state is compact and timestamped
+- controller rules can act on that state
+- latency is measured end to end
+- the LLM can help with strategy and recovery without blocking the loop
+
+## Hot-Path Components
+
+Use existing, swappable components:
+
+- YOLO-family detector for boxes, UI elements, enemies, objects, and markers
+- SAM / SAM2 / MobileSAM / FastSAM for masks when boxes are not enough
+- OCR for text, scores, labels, and menus
+- template matching for stable UI buttons and icons
+- color/edge/motion heuristics for simple fast signals
+- deterministic state machines for action decisions
+- LLM planner only for slow hints and recovery
+
+Avoid:
+
+- custom policy models
+- custom action models
+- custom neural networks
+- full LLM decision-making every frame
+- Ollama or any chat LLM in the per-frame action path
+- Python pixel loops in the hot path
+- generic agent frameworks around every frame
+
+## Runtime Stack
+
+Keep the runtime optimized even when the models are off the shelf.
+
+Preferred inference paths:
+
+- ONNX Runtime as the portable boundary
+- TensorRT on NVIDIA when it wins measured p95 latency
+- CUDA graphs for fixed-shape repeated inference when launch overhead matters
+- DirectML or WinML as a broad Windows fallback
+- Core ML / Metal on Apple hardware
+- CPU only for tiny templates, OCR snippets, or very small models
+
+Runtime rules:
+
+- keep model inputs fixed-size when possible
+- warm every model before live control starts
+- preallocate buffers
+- avoid PNG/JPEG encode/decode in the hot loop
+- drop stale frames
+- cap queue sizes at 1 in the reflex path
+- benchmark each component separately and together
+
+## Platform Defaults
+
+### Windows
+
+Best default for raw desktop game performance:
+
+```text
+DXGI Desktop Duplication
+ -> crop on GPU or with minimal copy
+ -> ONNX Runtime / TensorRT / DirectML
+ -> native input backend
+```
+
+Use TensorRT first on NVIDIA if the model exports cleanly and p95 latency improves. Use DirectML/WinML when broader GPU support matters more than peak NVIDIA performance.
+
+### macOS
+
+Best default for iPhone Mirroring and Mac app control:
+
+```text
+ScreenCaptureKit
+ -> IOSurface / CVPixelBuffer
+ -> Core ML / Metal / ONNX Runtime CoreML EP
+ -> synthetic input with Accessibility focus guard
+```
+
+Use Accessibility for window bounds, focus checks, dialogs, and setup flows. Use screenshot perception for the mirrored game content.
+
+## Vision Options
+
+### Detector First
+
+Start with a detector when the game state can be represented as objects.
+
+Good jobs:
+
+- enemies
+- obstacles
+- buttons
+- collectibles
+- health bars
+- hit markers
+- lane markers
+- minimap markers
+
+Use current Ultralytics YOLO-family nano/small models as candidates. The exact model should be selected by export support, license, latency, and whether the built-in labels are useful. As of current Ultralytics docs, YOLO26 is the newest line, YOLO11 is a stable modern line, and YOLOv8 remains widely supported.
+
+### Segment Anything When Needed
+
+Use SAM-style segmentation when object boundaries matter or the scene is too irregular for boxes.
+
+Candidate options:
+
+- SAM / SAM2 for high-quality masks and video/image segmentation
+- MobileSAM for lighter local segmentation
+- FastSAM for faster approximate masks
+- Ultralytics SAM integrations when they simplify wiring
+
+Use segmentation sparingly in the hot loop. It is often better as:
+
+- slow-path scene understanding
+- mask proposal for a region of interest
+- setup/calibration helper
+- fallback when detection is ambiguous
+
+### OCR And UI Parsing
+
+Use OCR for:
+
+- menus
+- labels
+- scores
+- inventory text
+- quest text
+- countdowns
+
+OCR should usually run on cropped regions, not the full frame.
+
+### Templates And Classical CV
+
+Use simple methods when they work:
+
+- template matching for known buttons/icons
+- color thresholding for health/resource bars
+- optical flow or frame differencing for motion
+- edge/shape heuristics for simple lanes and obstacles
+- DOM parsing when the target is web-based
+
+These are often faster and easier to debug than a model.
+
+## Game State
+
+Convert all perception outputs into a compact state object:
+
+```text
+state_id
+frame_id
+timestamp
+target_id
+scene_type
+objects
+masks
+text
+ui_flags
+player_state
+hazards
+action_affordances
+confidence
+source_ages
+planner_hint_id
+```
+
+Rules:
+
+- include confidence and age for every signal
+- keep coordinate spaces explicit
+- mark stale fields instead of silently using them
+- do not expose detector tensors or raw masks directly to the controller
+- prefer task-specific state over generic scene captions
+
+## Controller
+
+Use deterministic logic over game state:
+
+```text
+Game State
+ -> Policy Selector
+ -> Rule / State Machine
+ -> Semantic Action
+ -> Calibrated Input
+```
+
+Examples:
+
+- obstacle on left lane -> move center/right
+- button visible and safe -> tap button center
+- health low -> request planner recovery hint
+- menu state unknown -> pause and ask LLM to classify snapshot
+- target box center offset -> move/click toward center
+- countdown text appears -> wait or prepare action
+
+The controller should be boring, inspectable, and traceable.
+
+## LLM Role
+
+Use LLMs for:
+
+- interpreting unfamiliar screens
+- choosing objectives
+- explaining failures
+- deciding which detector/OCR/template signals matter
+- suggesting recovery steps
+- summarizing memory
+- reading slow-path screenshots or UI snapshots
+- producing structured planner hints
+
+Do not use LLMs for:
+
+- aiming every frame
+- dodge timing
+- tap/swipe timing
+- continuous movement
+- direct OS input
+
+LLM output must become validated hints, not direct actions.
+
+## First Demo Recommendation
+
+Pick one game and one task.
+
+Good first tasks:
+
+- dodge obstacles from detected lanes/hazards
+- tap a button when a visual condition appears
+- navigate a repeated menu
+- collect visible items
+- use OCR to react to a countdown or label
+
+Suggested first stack:
+
+```text
+Capture: ScreenCaptureKit for iPhone Mirroring, DXGI for Windows
+Detector: YOLO-family nano/small model
+Segmentation: MobileSAM or FastSAM as optional fallback
+OCR: cropped-region OCR
+Rules: deterministic state machine
+Inference: ONNX Runtime, TensorRT, Core ML, or DirectML depending on platform
+Reasoning: OpenAI Responses API or local Qwen/Phi/Gemma in a separate slow path
+IPC: latest-frame-wins shared buffer
+Runtime: native core where the hot path needs it
+```
+
+## Rollout
+
+1. Choose one target and one behavior.
+2. Define the state fields needed for that behavior.
+3. Capture the target window and crop to the gameplay/content area.
+4. Add one off-the-shelf detector or template signal.
+5. Add one deterministic rule that emits a safe semantic action.
+6. Add action calibration and focus guard.
+7. Add trace logging and latency report.
+8. Add optional segmentation only if detection/templates fail.
+9. Add OCR only for text-dependent screens.
+10. Add slow LLM recovery after the reflex loop works.
+
+## Acceptance Criteria
+
+- No custom model work is required.
+- The hot loop can run with the LLM disabled.
+- Every perception component is swappable.
+- Every action is explainable from state, rule, and trace id.
+- p95 reflex latency stays under the target budget.
+- LLM output is validated before it changes controller configuration.
+- Segmentation and OCR are cropped and measured before live use.
+
+## Where To Look
+
+- Ultralytics supported models: https://docs.ultralytics.com/models/
+- YOLO11 model card: https://huggingface.co/Ultralytics/YOLO11
+- Segment Anything repository: https://github.com/facebookresearch/segment-anything
+- SAM2 repository: https://github.com/facebookresearch/sam2
+- FastSAM repository: https://github.com/CASIA-LMC-Lab/FastSAM
+- ONNX Runtime execution providers: https://onnxruntime.ai/docs/execution-providers/
+- ONNX Runtime TensorRT EP: https://onnxruntime.ai/docs/execution-providers/TensorRT-ExecutionProvider.html
+- ONNX Runtime DirectML EP: https://onnxruntime.ai/docs/execution-providers/DirectML-ExecutionProvider.html
+- Microsoft DXGI Desktop Duplication API: https://learn.microsoft.com/en-us/windows/win32/direct3ddxgi/desktop-dup-api
+- Apple ScreenCaptureKit: https://developer.apple.com/documentation/screencapturekit
+- Apple Core ML: https://developer.apple.com/machine-learning/core-ml/
+- OpenAI model guide: https://developers.openai.com/api/docs/models
+- OpenAI Responses API: https://platform.openai.com/docs/api-reference/responses