Open source CapCut alternative.
TypeScript
Update plans
David Le2a7eb5d2df5c
diff --git a/docs/README.md b/docs/README.mdindex cb026e12..b0ff0d0c 100644--- a/docs/README.md+++ b/docs/README.md@@ -4,7 +4,7 @@ This folder is the product and engineering source of truth for capabilities thatPlans describe what we might build. Guides describe what Donkey currently supports and how to maintain it.-There is an active milestone plan in `plans/master-plan.md`. It tracks the unfinished work needed before the fast local navigation and AI-harness roadmap can be considered complete: generic local-app task knowledge, local JSON/JSONL task-definition loading, installed-app/task resolution, local-model command parsing with catalog validation, local task-context intake, Accessibility control discovery and action planning, review-first document form-fill planning, Parakeet-only local voice transcription, YOLO screenshot segmentation and local UI-understanding sidecar boundaries, post-install local runtime setup without bundled model weights, setup-managed command-parser LLM weight download, semantic memory/redaction/model-observability scaffolding, local navigation, guarded input, result verification, latency reporting, and optional slow planner recovery. Weather lookup, media playback, and document form-fill are benchmark definitions for this generic system, not source-specific architectures.+There is an active milestone plan in `plans/master-plan.md`. It tracks the unfinished work needed before the fast local navigation and AI-harness roadmap can be considered complete: generic local-app task knowledge, local JSON/JSONL task-definition loading, installed-app/task resolution, local-model command parsing with catalog validation, local task-context intake, Accessibility control discovery and action planning, review-first document form-fill planning, Parakeet-only local voice transcription, YOLO screenshot segmentation and local UI-understanding sidecar boundaries, post-install local runtime setup without bundled model weights, setup-managed command-parser LLM weight download, semantic memory retrieval, provider memory proposals, redaction/model-observability scaffolding, local navigation, guarded input, result verification, latency reporting, and optional slow planner recovery. Weather lookup, media playback, and document form-fill are benchmark definitions for this generic system, not source-specific architectures.## Guidesdiff --git a/docs/guides/minimal-run-coordinator.md b/docs/guides/minimal-run-coordinator.mdindex ce48c101..ab6d3135 100644--- a/docs/guides/minimal-run-coordinator.md+++ b/docs/guides/minimal-run-coordinator.md@@ -18,9 +18,9 @@ Donkey also supports the first real reflex trace shape for the off-the-shelf runDonkey also supports shared hot-loop contracts for deterministic reflex-loop slices. Frames, crops, coordinate spaces, perception signals, compact world states, controller actions, and action results are typed, Codable, Sendable contracts. Coordinate spaces are explicit across screen, window, crop, and normalized target space. Perception signals carry confidence and monotonic source age, and stale signals are marked on world state instead of being silently reused.-Donkey also supports a deterministic dry-run reflex loop skeleton. The loop consumes synthetic, recorded, target-window, or local-navigation metadata frame batches through a latest-frame-wins buffer with queue depth 1, counts dropped frames, converts signals into compact world state through a swappable projector, chooses an inspectable semantic action, projects the action in dry-run mode without OS input, and publishes `ReflexTraceRecord` samples through `RunCoordinator`. This skeleton is for contract validation and replayable tests only; continuous streaming capture and reflex-loop default OS input are not supported yet.+Donkey also supports a deterministic dry-run reflex loop skeleton. The loop consumes synthetic, recorded, target-window, streaming target-window, or local-navigation metadata frame batches through a latest-frame-wins buffer with queue depth 1, counts dropped frames, converts signals into compact world state through a swappable projector, chooses an inspectable semantic action, projects the action in dry-run mode without OS input, and publishes `ReflexTraceRecord` samples through `RunCoordinator`. This skeleton is for contract validation and replayable tests only; reflex-loop default OS input is not supported yet.-Donkey also supports a bounded target-window frame source for the dry-run hot-loop boundary. The frame source reuses macOS window selection and safety checks, captures selected windows through ScreenCaptureKit's desktop-independent window path, returns `HotLoopFrame` metadata for a caller-provided maximum frame count, and records capture latency and copy cost with monotonic timestamps. This path does not write screenshot artifacts and does not PNG/JPEG encode or decode frames. High-resolution manual screenshot artifacts remain separate from reflex frames.+Donkey also supports a bounded target-window frame source for the dry-run hot-loop boundary. The frame source reuses macOS window selection and safety checks, captures selected windows through ScreenCaptureKit's desktop-independent window path, returns `HotLoopFrame` metadata for a caller-provided maximum frame count, and records capture latency and copy cost with monotonic timestamps. The frame source can carry an explicit content crop, and iPhone Mirroring windows default to a centered phone-aspect content rectangle so mirrored game perception can target the phone content inside the generic Mac window. This path does not write screenshot artifacts and does not PNG/JPEG encode or decode frames. High-resolution manual screenshot artifacts remain separate from reflex frames.Donkey also supports the first cheap perception and deterministic controller slice. `CheapPerceptionAdapter` reads deterministic fixture or recorded-frame metadata for template-style targets, emits compact perception signals with confidence and monotonic source age, and marks that raw pixels are not exposed past the perception boundary. `HotLoopWorldStateProjector` converts those signals into compact world state and action affordances. `DeterministicControllerPolicy` selects a semantic `tapTarget` action for fresh high-confidence affordances, otherwise falls back to `wait` or `observe` with explicit rationale and fallback metadata. `DryRunActionProjector` remains side-effect free and records projected dry-run actions without OS input.@@ -28,13 +28,13 @@ Donkey also supports the first off-the-shelf local vision evidence boundary insiDonkey also tracks the first screenshot segmentation model candidate for the off-the-shelf vision boundary. `OffTheShelfVisionModelCatalog` lists Ultralytics YOLO26 nano segmentation (`yolo26n-seg.pt`) as the current screenshot/crop segmentation candidate, with official docs rechecked on May 17, 2026. `YOLOScreenshotSegmentationRunner` accepts bounded crop metadata plus a crop image or artifact URL, and `ProcessBackedScreenshotSegmentationBackend` calls a local JSON stdin/stdout sidecar from `DONKEY_YOLO_SEGMENTER`. Missing executable configuration, nonzero exits, and invalid output produce explicit unavailable or decoding failures. Decoded masks become the same recorded off-the-shelf segmentation evidence used by replay and dry-run perception.-Donkey also supports the first action-engine guardrail boundary. `ActionEngineGuardrail` accepts typed tap, swipe, key, mouse, controller, and `releaseAll` commands; checks input permission policy, focus guard status, command rate, and maximum hold duration; tracks held-input state; and records replayable command traces. Live input remains disabled by default and requires explicit configuration, an input-allowing policy, a passing focus guard, and an injected input backend. The local-app live runner injects a narrow macOS keyboard backend for guarded key/text commands; other action-engine use still records dry-run traces unless a caller opts into live input. Allowed non-live commands are projected as dry-run traces, live commands record backend execution evidence, denied commands include explicit denial reasons, and `releaseAll` clears held-input state.+Donkey also supports the first action-engine guardrail boundary. `ActionEngineGuardrail` accepts typed tap, swipe, key, mouse, controller, and `releaseAll` commands; checks input permission policy, focus guard status, command rate, and maximum hold duration; tracks held-input state; and records replayable command traces. Live input remains disabled by default and requires explicit configuration, an input-allowing policy, a passing focus guard, and an injected input backend. `MacTargetWindowFocusGuard` can protect generic target-window input, including iPhone Mirroring, by requiring the same durable window id, process, optional bundle, focused state, stable bounds, visibility, and allowed safety status before input executes. The local-app live runner injects a narrow macOS keyboard backend for guarded key/text commands; other action-engine use still records dry-run traces unless a caller opts into live input. Allowed non-live commands are projected as dry-run traces, live commands record backend execution evidence, denied commands include explicit denial reasons, and `releaseAll` clears held-input state.Donkey also supports reflex latency reports and a synthetic replay benchmark. `ReflexLatencyReportBuilder` summarizes reflex traces into p50/p95/p99 latency for software-loop, capture, preprocess/crop-normalize, model inference, perception, state update, controller decision, action projection, and input stages, plus component latency fields for command parse, launch/focus, observation, Accessibility action, keyboard action, verification, YOLO segmentation, UI understanding, and Parakeet transcription when traces include those metadata keys. Reports also include capture/perception/controller rates, dropped frames, stale actions, and worst traces. `ReflexReplayBenchmark` can generate deterministic dry-run traces for capture-only, controller-only, or end-to-end dry-run report modes. The installed debug entrypoint can print a CLI-friendly dry-run latency report with `--dry-run-latency-report`.Donkey also supports the first fast local-navigation dry-run slice end to end through the dry-run reflex loop. `LocalNavigationMetadataFrameSource` can turn macOS window candidate metadata and optional browser-tab metadata supplied by callers into metadata-only hot-loop frames. `LocalNavigationDryRunPerceptionAdapter` and `LocalNavigationDryRunWorldStateProjector` keep the local-navigation path swappable while preserving the no-remote-model fallback. `LocalNavigationControllerPolicy` can choose traceable dry-run semantic actions such as `focusWindow`, `activateCandidate`, `switchTab`, `wait`, or `observe` from typed state. This slice is metadata-only and side-effect free by default; guarded live-action smoke requires an injected backend, and richer visual inference remains future work.-Donkey also supports the first generic local-app task catalog, intent, live runner, and local task-definition loading boundary. `TaskIntent` can represent a parsed task, target app, normalized entities, parser source, confidence, and confirmation state. `LocalAppTaskDefinition` describes app-task knowledge as data: target app metadata, deterministic trigger terms, required entities and aliases, workflow steps, observation strategies, and verification rules. `LocalAppTaskDefinitionLoader` can load additional JSON or JSONL task definitions from `~/Library/Application Support/Donkey/TaskDefinitions/` and merge them with built-ins, so new use cases do not require Swift source changes. `LocalAppTaskCatalog` resolves validated intents against known task definitions, checks target-app availability through an injected provider, and exposes built-in definitions such as Weather lookup, Music playback, and PDF/document form-fill as data rather than source-specific adapters. `ProcessBackedLocalLLMTaskIntentAdapter` is the submitted-command parser: it sends the user command and available task definitions to the app-managed `DONKEY_LOCAL_LLM_RUNNER` sidecar, decodes a `TaskIntent`, and validates it against the catalog before execution can proceed. `OllamaTaskIntentAdapter` remains available for adapter-level tests and compatibility, while `LocalAppTaskIntentParser` remains deterministic validator and benchmark scaffold code rather than a user-command fallback. `LocalAppTaskAdapter` can build a target-app local-navigation metadata request, project dry-run workflow steps, emit guarded keyboard command templates, and verify observed visible text against the requested entity. `LocalAppAccessibilityControlDiscovery` can index controls and form fields from bounded Accessibility snapshots, and `MacAccessibilityActionEngineInputBackend` can execute guarded `AXPress` and `AXSetValue` commands when Accessibility is trusted, focus guard passes, and input policy allows it. `ProcessBackedLocalUIUnderstandingAdapter` can call a local JSON sidecar from `DONKEY_UI_UNDERSTANDER` for bounded screenshot/crop context and return visible text, controls, form fields, and confidence as a `LocalAppTaskObservation`; those results feed observation only and never direct input actions. `LocalAppTaskLiveRunner` can launch or focus the resolved app, prefer discovered Accessibility commands when available, fall back to guarded keyboard templates, observe visible Accessibility text when trusted, include bounded screenshot understanding context when configured, and return a final verification plan. Review-only tasks, such as document form-fill with external data, resolve into a local context snapshot and `DocumentFormFillPlanner` review plan. A user-facing document approval UI is intentionally out of scope for this slice; live form filling remains review/planning code until a separate product decision enables it.+Donkey also supports the first generic local-app task catalog, intent, live runner, and local task-definition loading boundary. `TaskIntent` can represent a parsed task, target app, normalized entities, parser source, confidence, and confirmation state. `LocalAppTaskDefinition` describes app-task knowledge as data: target app metadata, deterministic trigger terms, required entities and aliases, workflow steps, observation strategies, and verification rules. `LocalAppTaskDefinitionLoader` can load additional JSON or JSONL task definitions from `~/Library/Application Support/Donkey/TaskDefinitions/` and merge them with built-ins, so new use cases do not require Swift source changes. `LocalAppTaskCatalog` resolves validated intents against known task definitions, checks target-app availability through an injected provider, and exposes built-in definitions such as Weather lookup, Music playback, and PDF/document form-fill as data rather than source-specific adapters. `ProcessBackedLocalLLMTaskIntentAdapter` is the submitted-command parser: it sends the user command and available task definitions to the app-managed `DONKEY_LOCAL_LLM_RUNNER` sidecar, decodes a `TaskIntent`, and validates it against the catalog before execution can proceed. `OllamaTaskIntentAdapter` remains available for adapter-level tests and compatibility, while `LocalAppTaskIntentParser` remains deterministic validator and benchmark scaffold code rather than a user-command fallback. `LocalAppTaskAdapter` can build a target-app local-navigation metadata request, project dry-run workflow steps, emit guarded keyboard command templates, and verify observed visible text against the requested entity. `LocalAppAccessibilityControlDiscovery` can index controls and form fields from bounded Accessibility snapshots, and `MacAccessibilityActionEngineInputBackend` can execute guarded `AXPress` and `AXSetValue` commands when Accessibility is trusted, focus guard passes, and input policy allows it. `ProcessBackedLocalUIUnderstandingAdapter` can call a local JSON sidecar from `DONKEY_UI_UNDERSTANDER` for bounded screenshot/crop context and return visible text, controls, form fields, and confidence as a `LocalAppTaskObservation`; those results feed observation only and never direct input actions. `LocalAppTaskLiveRunner` publishes coordinator lifecycle/tool events, can launch or focus the resolved app, prefer discovered Accessibility commands when available, fall back to guarded keyboard templates, observe visible Accessibility text when trusted, include bounded screenshot understanding only when Accessibility/metadata are insufficient, and return a final verification plan. Review-only tasks, such as document form-fill with external data, resolve into a local context snapshot and `DocumentFormFillPlanner` review plan. The pointer prompt opens a user-visible review window for proposed document field mappings; only user-approved fields are sent to the guarded Accessibility input runner.Donkey also supports a guarded live-action smoke boundary for local-navigation behavior. `GuardedLiveActionSmokeRunner` requires an end-to-end dry-run result, a latency report with p95 evidence, a non-fallback latest action, explicit input policy allowance, and a passing action-engine focus guard before mapping semantic local-navigation actions to typed action-engine commands. The smoke path records replayable action traces and can execute only through an injected backend.@@ -42,19 +42,19 @@ Donkey also supports slow-path planner hint contracts. `StructuredPlannerHint` cDonkey also supports the first slow-planner sidecar beside the dry-run reflex loop. `DryRunSlowPlannerSidecar` can trigger on scene changes, low confidence, repeated fallback/failure, already-complete local-navigation goals, or explicit user instruction. It builds compact planner snapshots from the latest world state, action, bounded trace summaries, optional screenshot artifact references, and run memory. Planner work is notified from the dry-run loop after reflex trace publication in a fire-and-forget task, so model latency is not included in reflex p95. `ValidatedPlannerHintBus` publishes only validated hints, and `PlannerHintAwareControllerPolicy` can expose the latest still-valid hint to a controller without letting planner output become direct input.-Donkey also supports the first AI harness model registry and router boundary. `AIModelRegistry` stores model roles, providers, literal model ids, endpoints, capabilities, timeouts, prompt versions, eval status, docs URLs, and rollback ids as registry data. `AIModelRouter` routes slow-path jobs by job type, risk, privacy mode, latency tolerance, capabilities, failed-model history, and allowed providers. Privacy-sensitive planner routes prefer local Ollama-compatible entries when they are available. Privacy-sensitive voice-transcription routes prefer local runtime entries and select NVIDIA Parakeet TDT 0.6B v3 only; Whisper fallback has been removed. `ProcessBackedParakeetTranscriptionRuntime` calls a local JSON stdin/stdout sidecar from `DONKEY_PARAKEET_TRANSCRIBER`, and missing configuration or nonzero exits fail clearly instead of silently falling back. `LocalVoiceTranscriptionAdapter` accepts bounded local audio buffers, routes to the selected local runtime model, returns transcript text plus timing/confidence trace metadata, and marks transcripts as inputs to the normal command parser rather than actions. Literal provider model ids should stay in registry entries, not planner/controller logic.+Donkey also supports the first AI harness model registry and router boundary. `AIModelRegistry` stores model roles, providers, literal model ids, endpoints, capabilities, timeouts, prompt versions, eval status, docs URLs, and rollback ids as registry data. `AIModelRouter` routes slow-path jobs by job type, risk, privacy mode, latency tolerance, capabilities, failed-model history, and allowed providers. Privacy-sensitive planner routes prefer local Ollama-compatible entries when they are available. Privacy-sensitive voice-transcription routes prefer local runtime entries and select NVIDIA Parakeet TDT 0.6B v3 only; Whisper fallback has been removed. `ProcessBackedParakeetTranscriptionRuntime` calls a local JSON stdin/stdout sidecar from `DONKEY_PARAKEET_TRANSCRIBER`, and missing configuration or nonzero exits fail clearly instead of silently falling back. `LocalVoiceTranscriptionAdapter` accepts bounded local audio buffers, normalizes pointer-prompt `pcm_f32le` capture into Parakeet-compatible 16 kHz mono WAV, routes to the selected local runtime model, returns transcript text plus timing/confidence trace metadata, and marks transcripts as inputs to the normal command parser rather than actions. Literal provider model ids should stay in registry entries, not planner/controller logic.Donkey also supports a reusable local JSON sidecar runner for local model processes. `ProcessBackedLocalJSONSidecarRunner` reads executable paths from environment variables first, then from Donkey's app-managed local runtime registry, validates executability, sends request JSON on stdin, captures stdout/stderr, records exit status and latency metadata, and returns explicit unavailable or failed statuses. Current model sidecars use `DONKEY_LOCAL_LLM_RUNNER`, `DONKEY_YOLO_SEGMENTER`, `DONKEY_PARAKEET_TRANSCRIBER`, and `DONKEY_UI_UNDERSTANDER`. Submitted pointer-prompt commands prefer the local LLM sidecar and validated `TaskIntent` schema. If that runtime is unavailable, the built-in deterministic parser may resolve known built-in commands as a local fallback; this keeps benchmark commands local and traceable while still requiring catalog validation before execution.-Donkey's live local-app observation path uses Accessibility and bounded screenshots only. `MacLocalAppTaskController` captures Accessibility controls/visible text and, when the task definition includes screenshot local-model observation, concurrently captures a bounded target-window screenshot with ScreenCaptureKit and sends that image to `ProcessBackedLocalUIUnderstandingAdapter`. The adapter output is merged into `LocalAppTaskObservation` as visible text, controls, form fields, confidence, and metadata. Screenshot understanding is observation context only and never emits direct input actions.+Donkey's live local-app observation path uses Accessibility and bounded screenshots only. `MacLocalAppTaskController` captures Accessibility controls/visible text first and, when the task definition includes screenshot local-model observation, captures a bounded target-window screenshot only if Accessibility/metadata did not provide the verification text or required controls. That screenshot is sent to `ProcessBackedLocalUIUnderstandingAdapter`. The adapter output is merged into `LocalAppTaskObservation` as visible text, controls, form fields, confidence, and metadata. Screenshot understanding is observation context only and never emits direct input actions.Donkey also supports the first post-install local runtime setup boundary. The app package does not ship Parakeet or YOLO model weights, but `scripts/package-donkey-app.sh` creates Donkey-compatible sidecar runner packages and embeds them in `Donkey.app/Contents/Resources/LocalRuntimePackages/`. Each Python-backed package contains a small executable wrapper plus `donkey_runtime_runner.py`, and manifests checksum both files. Parakeet and YOLO packages also include a manifest-tracked `requirements.txt`; the runner creates a managed virtual environment under Application Support, installs those dependencies there, and uses a package-local wheelhouse when release artifacts are built with `scripts/build-local-runtime-wheelhouses.sh`. UI understanding ships as a Swift sidecar using Apple's on-device Vision text recognition, so it does not need downloaded model weights. `LocalModelRuntimeSetupManager` describes the required Parakeet, YOLO26, UI-understanding, and local command-parser LLM runtime packages, provides user-facing setup instructions, installs bundled package manifests before remote manifests, validates user-downloaded runtime folders, downloads manifest-backed package files when configured, enforces SHA-256 checksums and required signature metadata, verifies Curve25519 manifest signatures when trusted release keys are configured, caches verified package files under Application Support, asks each installed sidecar to prepare model weights in Application Support, and records executable paths in `~/Library/Application Support/Donkey/LocalModelRuntimes/runtime-installations.json`. The `local-llm` runner uses Ollama `qwen3:8b` when available but reports a non-blocking external-unavailable state during setup when Ollama is absent; submitted commands still have the deterministic local-app parser fallback. The Parakeet runner can prepare a Hugging Face snapshot and calls NVIDIA NeMo for transcription when available; YOLO installs its managed Ultralytics dependency and prepares the selected segmentation model. After registration, sidecar calls can resolve app-managed executables without shell environment variables. The first-run setup window exposes one setup button that installs/downloads, verifies, registers, prepares model weights, and health-checks all required runtimes, with one overall ready or retryable needs-attention state. Retry keeps completed runtime installs and resumes at failed or not-yet-attempted runtimes. Settings can reopen setup, and runtime lifecycle helpers can repair or remove managed installs and export user-data-free support status. Developer launch arguments can print setup instructions, show install status, export support status, repair, remove, or register a downloaded runtime folder.-Donkey also supports the first provider-neutral planner-hint adapter boundary using OpenAI's Responses API. `OpenAIPlannerHintAdapter` reads `OPENAI_API_KEY` from the environment, routes through the model registry, sends a structured-output Responses request with `store: false`, decodes a strict planner-hint JSON response, and records a model-call trace with role, provider, model id, prompt version, schema id, latency, timeout, validation status, and source trace/state ids. Missing credentials, cancellation, timeout, rate limit, invalid output, and provider outage return traceable failures without stopping the reflex loop. Official OpenAI docs were rechecked on May 16, 2026 for the Responses API, `text.format` JSON schema structured outputs, `store: false`, and current model registry default guidance.+Donkey also supports the first provider-neutral planner-hint adapter boundary using OpenAI's Responses API. `OpenAIPlannerHintAdapter` reads `OPENAI_API_KEY` from the environment, routes through the model registry, sends a structured-output Responses request with `store: false`, decodes a strict JSON response containing a planner hint plus optional memory write proposals, and records a model-call trace with role, provider, model id, prompt version, schema id, latency, timeout, validation status, and source trace/state ids. Missing credentials, cancellation, timeout, rate limit, invalid output, and provider outage return traceable failures without stopping the reflex loop. Official OpenAI docs were rechecked on May 16, 2026 for the Responses API, `text.format` JSON schema structured outputs, `store: false`, and current model registry default guidance.-Donkey also supports an Ollama-compatible local planner-hint adapter and provider-backed slow planner generator. `OllamaPlannerHintAdapter` sends a local `/api/generate` request with `stream: false` and the same strict planner-hint JSON schema, decodes the local model response into `StructuredPlannerHint`, and records the same model-call trace shape as the OpenAI adapter. `ProviderBackedSlowPlannerHintGenerator` can try local planning first and fall back to the online adapter; either provider can publish only validated hints through the existing slow-planner sidecar and hint bus. Official Ollama docs were checked on May 16, 2026 for the `/api/generate` endpoint, JSON schema `format`, and non-streaming response shape.+Donkey also supports an Ollama-compatible local planner-hint adapter and provider-backed slow planner generator. `OllamaPlannerHintAdapter` sends a local `/api/generate` request with `stream: false` and the same strict planner-hint-plus-memory-proposal JSON schema, decodes the local model response into `StructuredPlannerHint` and approved memory decisions, and records the same model-call trace shape as the OpenAI adapter. `ProviderBackedSlowPlannerHintGenerator` can try local planning first and fall back to the online adapter; either provider can publish only validated hints through the existing slow-planner sidecar and hint bus. Official Ollama docs were checked on May 16, 2026 for the `/api/generate` endpoint, JSON schema `format`, and non-streaming response shape.-Donkey also supports the first memory boundary for slow-path context. Short-term run memory is in-process and bounded; it can retain the current goal, active valid hints, recent world states, recent failures, user instructions, safety stops, and target records for context assembly. Target memory is stored as scoped, source-linked JSONL records under Application Support by default, with tests and tools able to pass an explicit base directory. Semantic memory retrieval contracts include target/scope filters, max-record and prompt-character budgets, minimum relevance, and an embedding-provider protocol. Model-proposed or provider-decoded memory writes go through the deterministic approver before storage. Target and user scoped records require either an expiry timestamp or an explicit durable flag, and records can be listed or deleted by target, run, user, or record id.+Donkey also supports the first memory boundary for slow-path context. Short-term run memory is in-process and bounded; it can retain the current goal, active valid hints, recent world states, recent failures, user instructions, safety stops, and target records for context assembly. Target memory is stored as scoped, source-linked JSONL records under Application Support by default, with tests and tools able to pass an explicit base directory. Semantic memory retrieval contracts include target/scope filters, max-record and prompt-character budgets, minimum relevance, and an embedding-provider protocol. Pointer-prompt command handling loads target-scoped JSONL records after catalog resolution and records the selected semantic memory ids in run metadata; slow-planner snapshots can carry selected semantic results in `RunContextPackage`, and provider prompts include only the bounded selected memory summaries. Provider-backed planner outputs may include memory write proposals beside the validated hint. Proposals are decoded independently from hints, run through the deterministic approver, and approved target memories are persisted through `TargetMemoryJSONLStore` when a store is available. Target and user scoped records require either an expiry timestamp or an explicit durable flag, and records can be listed or deleted by target, run, user, or record id.Donkey also supports a replay/eval scaffold for model and prompt changes. Planner-hint replay cases summarize recorded traces, decoded hints, validation issues, model-call latency, estimated cost, fallback count, recovery success, and memory-write decisions. `PlannerHintReplayEvaluator` aggregates schema validity, hint acceptance, memory write acceptance and rejection, latency, cost, fallbacks, and recovery success into a promotion report. `AIModelObservabilityReportBuilder` aggregates model-call latency, status, provider, schema validity, acceptance, estimated cost, and recovery success across arbitrary `AIModelCallTrace` samples. `AIHarnessRedactor` provides hooks for remote-bound screenshot summaries, DOM summaries, and model context before provider calls. `AIModelUpdateChecklist` records the model entry, prompt version, `last_verified_at`, docs URLs, eval suite id, rollback model id, and optional report id before model or prompt promotion.@@ -69,17 +69,17 @@ accessibility/The artifact store can append ordered event records, reserve safe screenshot or Accessibility artifact paths, record artifact metadata, and keep `summary.json` current.-Donkey can also resolve visible macOS target-window metadata for the manual capture path. The resolver enumerates on-screen app windows, describes window id, pid, app name, bundle id, title, bounds, focus/frontmost state, iPhone Mirroring hints, and conservative safety metadata. Callers can request a candidate-list snapshot with ephemeral labels such as `window 1` and `window 2`; labels are valid only for that enumeration snapshot and should be converted to the candidate's durable `windowID` for follow-up capture commands. Callers can select an explicit window id or fall back to the focused/frontmost visible window.+Donkey can also resolve visible macOS target-window metadata for the manual capture path. The resolver enumerates on-screen app windows, builds a runtime map of known running applications from `NSWorkspace`, enriches each window with app identity when available, and describes window id, pid, app name, bundle id, title, bounds, focus/frontmost state, iPhone Mirroring hints, and conservative safety metadata. iPhone Mirroring is treated as an ordinary visible window candidate; the hint is derived dynamically from the same app identity and window metadata used for every other app, not from a separate selection path. Callers can request a candidate-list snapshot with ephemeral labels such as `window 1` and `window 2`; labels are valid only for that enumeration snapshot and should be converted to the candidate's durable `windowID` for follow-up capture commands. Callers can select an explicit window id or fall back to the focused/frontmost visible window.Donkey can create a single read-only target-window screenshot artifact after a run folder has been prepared. The screenshot service resolves the target, refuses blocked or review-required safety surfaces, captures the selected window with ScreenCaptureKit's desktop-independent window path, writes PNG bytes under `screenshots/`, and records flattened target/capture metadata in `summary.json`. Overlap-sensitive fallback capture backends must refuse occluded targets instead of silently recording pixels from another window.-Donkey can also create a shallow read-only Accessibility snapshot artifact after a run folder has been prepared. The Accessibility snapshot service resolves the same target-window selection, refuses blocked or review-required safety surfaces, checks Accessibility trust without prompting, writes a bounded JSON tree under `accessibility/` when trusted, and records artifact metadata in `summary.json`. If Accessibility trust is missing, the service appends a clear partial-run tool event to `events.jsonl` and does not create an artifact.+Donkey can also create a shallow read-only Accessibility snapshot artifact after a run folder has been prepared. The Accessibility snapshot service resolves the same target-window selection, refuses blocked or review-required safety surfaces, checks Accessibility trust without prompting, races tree capture against a short timeout, detects native macOS dialogs in the resulting tree as safety stops, writes a bounded JSON tree under `accessibility/` when trusted and safe, and records artifact metadata in `summary.json`. If Accessibility trust is missing, the service appends a clear partial-run tool event to `events.jsonl` and does not create an artifact. If capture times out or a native dialog is detected, no artifact is created.Donkey supports a runtime-level manual target context capture service that wires one read-only capture run through `RunCoordinator`. The service prepares the run folder, starts the session, resolves the target once, passes explicit durable `windowID` selection to screenshot and Accessibility capture services, records coordinator-assigned lifecycle and tool events, persists those events to `events.jsonl`, and completes the run after screenshot success. Missing Accessibility trust is a partial completion: the coordinator records one permission-denied tool event, the screenshot artifact remains, and no Accessibility artifact is created.The installed executable also supports a developer-only launch-argument entrypoint for manual verification. `--list-window-candidates` prints the current candidate-list labels and durable `windowID` values. `--manual-capture` runs one manual capture, optionally with `--window-id <id>`, `--run-id <safe-id>`, and `--trace-id <safe-id>`, then prints the run folder and artifact paths. These commands are non-interactive and exit before showing the pointer prompt overlay.-This is a coordination, in-memory reflex trace, hot-loop contract, deterministic dry-run skeleton, bounded target-window frame-source, cheap metadata perception, recorded off-the-shelf local vision evidence, screenshot segmentation model-candidate catalog and sidecar runner boundary, local UI-understanding sidecar observation boundary wired into live local-app observation, post-install local runtime setup/registration boundary, deterministic controller, local-navigation dry-run, generic local-app task catalog/intent/live-runner boundary, local JSON/JSONL task-definition loading, local task-context intake, Accessibility control discovery/action execution boundary, document form-fill review planning, sample task definitions across weather/media/document domains, guarded live-action smoke boundary, slow-planner sidecar, action-engine guardrail, latency-report, planner-hint contract, model-registry/router, Parakeet-only local voice-transcription sidecar boundary wired from pointer-prompt microphone buffers, OpenAI and Ollama-compatible planner adapters, semantic memory/redaction/model-observability scaffolding, replay/eval, target-metadata, single-screenshot artifact, read-only Accessibility snapshot, and manual capture orchestration foundation only. It does not bundle live transcription or vision model binaries, run OCR over captured pixels by default, provide a manual capture UI, persist high-volume reflex traces to disk, provide continuous streaming capture, or make model calls required for reflex ticks.+This is a coordination, in-memory reflex trace, hot-loop contract, deterministic dry-run skeleton, bounded target-window frame-source, streaming target-window frame-source, cheap metadata perception, recorded off-the-shelf local vision evidence, screenshot segmentation model-candidate catalog and sidecar runner boundary, local UI-understanding sidecar observation boundary wired into live local-app observation, post-install local runtime setup/registration boundary, deterministic controller, local-navigation dry-run, generic local-app task catalog/intent/live-runner boundary, local JSON/JSONL task-definition loading, local task-context intake, Accessibility control discovery/action execution boundary, document form-fill review planning and approval UI, sample task definitions across weather/media/document domains, guarded live-action smoke boundary, slow-planner sidecar, action-engine guardrail, latency-report, planner-hint contract, model-registry/router, Parakeet-only local voice-transcription sidecar boundary wired from pointer-prompt microphone buffers, OpenAI and Ollama-compatible planner adapters, semantic memory/redaction/model-observability scaffolding, replay/eval, target-metadata, single-screenshot artifact, read-only Accessibility snapshot, and manual capture orchestration foundation only. It does not bundle live transcription or vision model binaries, run OCR over captured pixels by default, provide a manual capture UI, persist high-volume reflex traces to disk, or make model calls required for reflex ticks.## Technical Guidelines@@ -87,9 +87,10 @@ This is a coordination, in-memory reflex trace, hot-loop contract, deterministic- Keep coordinator state and append ordering in `DonkeyRuntime`; UI code should read status through narrow provider boundaries.- Treat `RunCoordinator` as the owner of lifecycle and event ordering, not as the owner of perception, controller internals, or input backends.- Treat `LocalRunArtifactStore` as a persistence sink for trace records and artifact metadata. It should not own lifecycle state or decide whether tool calls are allowed.-- Treat macOS window resolution as read-only metadata collection. Safety classifications should be conservative and used by later capture code to refuse or stop on sensitive surfaces.+- Treat macOS window resolution as read-only metadata collection. Build app identity from the current runtime environment, keep app-specific hints additive, and continue selecting targets through generic window ids. Safety classifications should be conservative and used by later capture code to refuse or stop on sensitive surfaces.- Treat target-window screenshot capture as a one-shot artifact write, not a continuous capture loop. ScreenCaptureKit desktop-independent window capture is preferred because overlapping windows do not contaminate the selected target artifact.-- Treat Accessibility snapshot capture as read-only inspection. Keep trees bounded, redact long text values, avoid permission prompts in the capture service, and never perform AX actions from this path.+- Treat target-window content calibration as window metadata, not target discovery. iPhone Mirroring can use the default centered phone-aspect crop, while callers may pass an explicit crop or calibration when the target requires a different content rectangle.+- Treat Accessibility snapshot capture as read-only inspection. Keep trees bounded, timeout-protected, dialog-aware, and redacted for long text values; avoid permission prompts in the capture service, and never perform AX actions from this path.- Treat manual target context capture as orchestration. `RunCoordinator` owns event order and policy decisions, while screenshot, Accessibility, and artifact-store services remain capture/persistence workers.- Treat the launch-argument debug entrypoint as developer tooling. It should stay plain text, non-interactive, and should never accept ephemeral labels as capture input.- Keep mutable installed-app run artifacts in Application Support, not inside the `.app` bundle and not relative to process working directory.@@ -99,13 +100,13 @@ This is a coordination, in-memory reflex trace, hot-loop contract, deterministic- Keep dry-run action projection side-effect free. It records semantic action intent and trace evidence, but never calls the input capability.- Keep dry-run world-state projection swappable. Local-navigation metadata, cheap template metadata, and future local inference adapters should share the loop boundary instead of requiring planner or remote-model output.- Keep reflex frame buffers at queue depth 1. Dropped frames are expected under pressure and should be counted.-- Keep target-window reflex frames bounded by caller-provided frame count until a streaming capture loop exists.+- Keep target-window reflex frames bounded by caller-provided frame count unless a caller explicitly selects the streaming frame source.- Keep manual screenshot artifacts and high-resolution planner snapshots separate from reflex frames. The reflex frame source should not encode PNG/JPEG or write screenshot artifacts.- Keep cheap perception deterministic and compact until real pixel/model adapters exist. Perception may summarize fixture metadata, recorded off-the-shelf detector/template/OCR/segmentation evidence, or model-candidate catalog choices, but controllers must only see typed signals, world state, and action affordances.- Keep controller fallback explicit. Low confidence, stale signals, missing affordances, and missing signals should produce traceable `wait` or `observe` actions, not silent no-ops.- Keep every chosen controller action trace-linked with action id, state id, frame id, policy name, confidence, rationale, fallback metadata, and any compact source-evidence metadata needed to explain the rule.- Keep action-engine commands typed and replayable. Guardrails must run before live input and record permission, focus, rate-limit, hold-duration, release, backend, issued time, backend completion time, and execution status. Live held-input tracking starts only after the backend reports execution.-- Keep live OS input disabled unless a caller explicitly configures live mode, allows input in policy, passes focus guard, and supplies an input backend. The macOS keyboard backend is narrow: it is for guarded local-app key/text commands, not arbitrary controller output. The macOS Accessibility backend is narrow too: it may execute only traceable `AXPress` or `AXSetValue` commands against discovered nodes in the focused target app.+- Keep live OS input disabled unless a caller explicitly configures live mode, allows input in policy, passes focus guard, and supplies an input backend. Use `MacTargetWindowFocusGuard` for generic window targets before synthetic input. The macOS keyboard backend is narrow: it is for guarded local-app key/text commands, not arbitrary controller output. The macOS Accessibility backend is narrow too: it may execute only timeout-bounded, traceable `AXPress` or `AXSetValue` commands against discovered nodes in the focused target app.- Use monotonic timestamps for latency math. Wall-clock timestamps are for human labels and trace correlation only.- Use latency reports for any p50/p95/p99 claim. Reports should include dropped frames, stale actions, tick rates, and worst traces.- Keep local-navigation decisions typed and side-effect free until the guarded live-action slice. Metadata projectors may use window, browser-tab, and Accessibility facts when available, but controllers should emit semantic actions only.@@ -117,14 +118,14 @@ This is a coordination, in-memory reflex trace, hot-loop contract, deterministic- Treat planner hints as validated, expiring advice. Controllers may use the latest valid hint, but planner output must never become direct input.- Keep slow planner work beside the reflex loop. Trigger it from compact state, trace, memory, and artifact references; never await model calls from the hot tick before recording the reflex trace.- Keep model selection in `AIModelRegistry` data. Do not scatter provider model ids through planner code.-- Keep local voice transcription as a Parakeet-only model-routed local runtime job. Transcription output is transcript text only and must enter the same validated command path as typed input before any task can run. If `DONKEY_PARAKEET_TRANSCRIBER` is missing or fails, the voice path fails clearly; it must not silently fall back to Whisper or any remote transcription provider.+- Keep local voice transcription as a Parakeet-only model-routed local runtime job. Normalize pointer-prompt audio into Parakeet-compatible 16 kHz mono WAV before calling the sidecar. Transcription output is transcript text only and must enter the same validated command path as typed input before any task can run. If `DONKEY_PARAKEET_TRANSCRIBER` is missing or fails, the voice path fails clearly; it must not silently fall back to Whisper or any remote transcription provider.- Keep local model runtimes behind JSON sidecars. Use `DONKEY_YOLO_SEGMENTER`, `DONKEY_PARAKEET_TRANSCRIBER`, and `DONKEY_UI_UNDERSTANDER` for developer overrides, then Donkey's app-managed runtime registry for normal user installs. Return explicit unavailable results when executables are absent.- Do not bundle model weights in the app. Users download compatible runtime packages after app install; Donkey validates manifests, checksums, signature metadata or configured cryptographic signatures, executable paths, and health checks, then records executable paths under Application Support.- Keep privacy-sensitive Responses API calls configured with `store: false` unless an explicit later policy changes that default.- Treat provider failures as sidecar failures. Missing credentials, timeout, rate limit, invalid output, or outage should leave the controller running on local state and existing valid hints.- Keep memory writes source-linked and scoped. Model-proposed memory writes must pass the deterministic approver before storage; target and user records require TTL or explicit durable retention.-- Keep provider-decoded memory proposals on the same deterministic approval path as runtime-created proposals.-- Keep semantic memory retrieval bounded by target/scope filters, max record count, prompt-character budget, and minimum relevance before adding it to model context.+- Keep provider-decoded memory proposals on the same deterministic approval path as runtime-created proposals. Decode proposals independently so malformed proposal payloads do not invalidate a valid planner hint.+- Keep semantic memory retrieval bounded by target/scope filters, max record count, prompt-character budget, and minimum relevance before adding selected summaries to model context.- Redact remote-bound screenshot summaries, DOM summaries, and model context before online provider calls.- Keep target memory inspectable and deleteable by target, run, user, and record id. Do not use memory JSONL as an opaque cache.- Promote model or prompt changes only after replay/eval records schema validity, hint acceptance, memory acceptance, latency, cost, fallback count, recovery success, docs URLs, and rollback model id.@@ -139,7 +140,7 @@ From `apps/Donkey/`:swift test```-The runtime tests should cover lifecycle ordering, abort and timeout safety, latest-session queue drops, tool permission denial, event-store ordering, context compaction, reflex trace latency math, bounded in-memory reflex trace retention, reflex event publication, hot-loop contract Codable round trips, coordinate conversion, stale-signal marking, deterministic dry-run trace publication, queue-depth-1 dropped-frame counting, bounded target-window frame capture, target-frame safety and overlap refusal, target-frame no-artifact/no-encoding metadata, cheap perception signal projection, recorded off-the-shelf vision evidence projection, screenshot segmentation model-candidate selection, YOLO sidecar decoding and unavailable states, local UI-understanding observation decoding, local runtime setup instructions/status/registration, manifest-backed runtime download, checksum/signature enforcement, managed package cache install, health recheck, app-managed sidecar executable resolution, controller confidence/staleness fallback, controller p95 replay timing under 20ms, local-navigation metadata projection and action selection, local-navigation browser-tab metadata projection, loop-integrated local-navigation dry-run action selection, local-model task intent request shaping and validation, deterministic local-app task parser validation and alias expansion, local task-definition loading, local-app catalog resolution and app availability checks, local task-context intake, Accessibility control discovery, document form-fill review planning, local-app navigation request construction, generic dry-run step projection, guarded keyboard and Accessibility command templates, observed visible-text verification, guarded local-navigation live-smoke gating and trace evidence, abort/timeout release traces, slow-planner trigger/snapshot/validated-hint publication, planner-latency isolation from reflex reports, action-engine permission/focus/rate/hold/release guardrails, latency report percentiles, component latency fields, replay benchmark formatting, planner hint validation/expiry/latest-selection, model registry routing, Parakeet-only local voice-transcription routing, Parakeet sidecar decoding and unavailable states, local JSON sidecar missing-env/nonzero-exit states, OpenAI Responses request shaping and failure handling, semantic memory retrieval, remote-bound redaction, model-call observability, provider-decoded memory proposal approval, memory approval/storage/list/delete/context snapshots, replay/eval metric aggregation and model update checklist fields, artifact path validation, trace folder layout, JSONL event persistence, summary updates, deterministic window resolver behavior through fixture providers, candidate-list label snapshots, screenshot artifact metadata, bounded Accessibility serialization, missing Accessibility trust partial events, unsafe target refusal, overlap-sensitive capture refusal, manual capture event ordering through persisted coordinator events, and debug launch-argument parsing/formatting.+The runtime tests should cover lifecycle ordering, abort and timeout safety, latest-session queue drops, tool permission denial, event-store ordering, context compaction, reflex trace latency math, bounded in-memory reflex trace retention, reflex event publication, hot-loop contract Codable round trips, coordinate conversion, stale-signal marking, deterministic dry-run trace publication, queue-depth-1 dropped-frame counting, bounded target-window frame capture, target-frame safety and overlap refusal, target-frame no-artifact/no-encoding metadata, iPhone Mirroring content-rectangle calibration, generic target-window focus guarding, cheap perception signal projection, recorded off-the-shelf vision evidence projection, screenshot segmentation model-candidate selection, YOLO sidecar decoding and unavailable states, local UI-understanding observation decoding, local runtime setup instructions/status/registration, manifest-backed runtime download, checksum/signature enforcement, managed package cache install, health recheck, app-managed sidecar executable resolution, controller confidence/staleness fallback, controller p95 replay timing under 20ms, local-navigation metadata projection and action selection, local-navigation browser-tab metadata projection, loop-integrated local-navigation dry-run action selection, local-model task intent request shaping and validation, deterministic local-app task parser validation and alias expansion, local task-definition loading, local-app catalog resolution and app availability checks, local task-context intake, Accessibility control discovery, document form-fill review planning, local-app navigation request construction, generic dry-run step projection, guarded keyboard and Accessibility command templates, observed visible-text verification, guarded local-navigation live-smoke gating and trace evidence, abort/timeout release traces, slow-planner trigger/snapshot/validated-hint publication, planner-latency isolation from reflex reports, action-engine permission/focus/rate/hold/release guardrails, latency report percentiles, component latency fields, replay benchmark formatting, planner hint validation/expiry/latest-selection, model registry routing, Parakeet-only local voice-transcription routing, Parakeet sidecar decoding and unavailable states, local JSON sidecar missing-env/nonzero-exit states, OpenAI Responses request shaping and failure handling, semantic memory retrieval, remote-bound redaction, model-call observability, provider-decoded memory proposal approval, memory approval/storage/list/delete/context snapshots, replay/eval metric aggregation and model update checklist fields, artifact path validation, trace folder layout, JSONL event persistence, summary updates, deterministic window resolver behavior through fixture providers, runtime app-identity-enriched window hints, candidate-list label snapshots, screenshot artifact metadata, bounded Accessibility serialization, Accessibility timeout handling, native dialog safety stops, missing Accessibility trust partial events, unsafe target refusal, overlap-sensitive capture refusal, manual capture event ordering through persisted coordinator events, and debug launch-argument parsing/formatting.Manual smoke commands:@@ -171,6 +172,7 @@ Remaining live verification is environment-dependent. On May 16, 2026, iPhone Mi- Runtime coordination lives in `apps/Donkey/Sources/DonkeyRuntime/`.- The deterministic dry-run reflex skeleton lives in `apps/Donkey/Sources/DonkeyRuntime/DryRunReflexLoop.swift`.- Bounded target-window reflex frame capture lives in `apps/Donkey/Sources/DonkeyRuntime/TargetWindowFrameSource.swift`.+- Continuous target-window reflex frame streaming lives in `apps/Donkey/Sources/DonkeyRuntime/TargetWindowFrameSource.swift`.- Cheap perception, world-state projection, deterministic controller policy, and dry-run action projection live in `apps/Donkey/Sources/DonkeyRuntime/CheapPerceptionAndController.swift`.- Recorded off-the-shelf detector/template/OCR/segmentation evidence projection lives in `apps/Donkey/Sources/DonkeyRuntime/OffTheShelfVisionPerception.swift`.- Action-engine guardrails live in `apps/Donkey/Sources/DonkeyRuntime/ActionEngineGuardrails.swift`.@@ -185,8 +187,11 @@ Remaining live verification is environment-dependent. On May 16, 2026, iPhone Mi- Local task context intake lives in `apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskContext.swift`.- Local Accessibility control discovery and Accessibility action planning live in `apps/Donkey/Sources/DonkeyRuntime/LocalAppAccessibilityControls.swift`.- Document form-fill review planning lives in `apps/Donkey/Sources/DonkeyRuntime/DocumentFormFillPlanner.swift`.+- Guarded document form-fill approval execution lives in `apps/Donkey/Sources/DonkeyRuntime/DocumentFormFillApprovalLiveRunner.swift`.+- The user-visible document form-fill approval window lives in `apps/Donkey/Sources/Donkey/DocumentFormFillReviewWindowController.swift`.- Deterministic local-app task parsing lives in `apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskIntentParser.swift`.- Generic local-app dry-run adapter and guarded keyboard command templates live in `apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskAdapter.swift`.+- Local-app screenshot fallback policy lives in `apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskObservationFallbackPolicy.swift`.- Ollama-compatible local task-intent parsing lives in `apps/Donkey/Sources/DonkeyAI/OllamaTaskIntentAdapter.swift`.- Local voice transcription adapter boundary lives in `apps/Donkey/Sources/DonkeyAI/LocalVoiceTranscriptionAdapter.swift`.- YOLO screenshot segmentation runner boundary lives in `apps/Donkey/Sources/DonkeyRuntime/YOLOScreenshotSegmentationRunner.swift`.@@ -206,9 +211,12 @@ Remaining live verification is environment-dependent. On May 16, 2026, iPhone Mi- Replay/eval scaffolding lives in `apps/Donkey/Sources/DonkeyAI/AIReplayEvaluation.swift`.- Recent reflex trace retention lives in `apps/Donkey/Sources/DonkeyRuntime/InMemoryReflexTraceStore.swift`.- macOS window resolution lives in `apps/Donkey/Sources/DonkeyRuntime/MacWindowResolver.swift`.+- Generic target-window focus guarding lives in `apps/Donkey/Sources/DonkeyRuntime/MacTargetWindowFocusGuard.swift`.+- Target-window content calibration lives in `apps/Donkey/Sources/DonkeyRuntime/TargetWindowContentCalibration.swift`.- Target-window screenshot capture lives in `apps/Donkey/Sources/DonkeyRuntime/WindowScreenshotCaptureService.swift`.- Accessibility snapshot contracts live in `apps/Donkey/Sources/DonkeyContracts/AccessibilitySnapshotContracts.swift`.- Read-only Accessibility snapshot capture lives in `apps/Donkey/Sources/DonkeyRuntime/MacAccessibilitySnapshotCaptureService.swift`.+- Accessibility timeout helpers live in `apps/Donkey/Sources/DonkeyRuntime/MacAccessibilityTimeout.swift`.- Manual target context capture orchestration lives in `apps/Donkey/Sources/DonkeyRuntime/ManualTargetContextCaptureService.swift`.- Manual capture debug command parsing lives in `apps/Donkey/Sources/DonkeyRuntime/ManualCaptureDebugCommand.swift`.- Local artifact persistence lives in `apps/Donkey/Sources/DonkeyRuntime/LocalRunArtifactStore.swift`.diff --git a/plans/00-overview.md b/plans/00-overview.mdindex 13f912cd..d6f50d7e 100644--- a/plans/00-overview.md+++ b/plans/00-overview.md@@ -64,12 +64,11 @@ Every frame should use local, bounded-cost logic:- [manual-target-context-capture-master-plan.md](manual-target-context-capture-master-plan.md): completed manual screenshot, Accessibility tree, and trace artifact capture milestone- [../master-plan.md](../master-plan.md): current master plan for closing out the off-the-shelf run loop and AI harness milestones-- [../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): completed 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+- [../06-benchmarking.md](../06-benchmarking.md): hard latency budgets, measurement, monitoring, traces, and regression gates- [07-rollout.md](07-rollout.md): phased delivery path from first supported target to production readiness- [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@@ -77,12 +76,11 @@ Every frame should use local, bounded-cost logic:- [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+- [14-synthetic-controller.md](14-synthetic-controller.md): generic synthetic input adapter, including gamepad/controller backends- [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+- [done/19-ai-harness.md](done/19-ai-harness.md): completed AI harness memory, proposal, and voice-hardening slice- [../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 Prioritiesdiff --git a/plans/01-latency-budget.md b/plans/01-latency-budget.mddeleted file mode 100644index 894dd470..00000000--- a/plans/01-latency-budget.md+++ /dev/null@@ -1,106 +0,0 @@-# Latency Budget--> Active status: not complete. Current reports support synthetic and dry-run traces, but this plan is not complete until p50/p95/p99 budgets are measured for the first fast-navigation benchmark and compared with a manual baseline.--## Target--The local navigation loop should feel faster than manual navigation. For the first Weather benchmark, measure both command-to-result time and per-step hot-path latency.--Target for the first Weather demo:--- command-to-first-action p95 under 300ms after text submission-- local observation/controller/input step p95 under 100ms-- command-to-verified-result faster than a documented manual baseline on the same machine--For later game/visual targets, the reflex loop should still complete in under 100ms end to end.--Stretch target: 30-60ms for simple games.--## Budget--### Weather Task Budget--| Stage | Baseline Target | Stretch Target |-| --- | ---: | ---: |-| Intent parse | 5-100ms | <20ms deterministic |-| App launch/focus | 100-800ms | 50-300ms when already warm |-| App observation | 5-50ms | 2-15ms |-| Controller decision | 1-20ms | <5ms |-| Input execution | 1-20ms | <5ms |-| Result verification | 10-100ms | 5-30ms |--### Visual Reflex 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 remote call is required for common Weather command parsing or execution.-- 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-Observation thread- -> overwrites latest app/window/task state--Perception thread- -> reads latest structured observation or latest frame fallback- -> 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.-- App launch cold-start time.-- Accessibility permission or trust checks.-- Typing into an unverified focused control.--## Acceptance Criteria--- Every action trace includes capture timestamp, perception timestamp, decision timestamp, and input timestamp.-- Every Weather task trace includes intent parse, app launch/focus, observation, decision, input, and verification timestamps.-- p50 local observation/controller/input step latency is under 60ms for the first supported target.-- p95 local observation/controller/input step latency is under 100ms for the first supported target.-- command-to-result time is compared with a manual Weather lookup baseline.-- Stale-frame actions are counted and visible in metrics.diff --git a/plans/02-capture-and-perception.md b/plans/02-capture-and-perception.mddeleted file mode 100644index a7149c33..00000000--- a/plans/02-capture-and-perception.md+++ /dev/null@@ -1,112 +0,0 @@-# Capture And Perception--> Active status: not complete. Current capture/perception support includes target-window frames and metadata perception, but not the live observation needed to verify the first fast-navigation benchmark.--## Goal--Convert app, window, Accessibility, and screen observations into compact state quickly enough for local task control.--The perception layer should answer only the questions the controller needs right now.--For the first Weather task, the controller needs app/task facts more than pixels: whether Weather is running and frontmost, whether the search field or search results are available, what location is visible, and whether the requested city is verified.--For Mac apps, Accessibility is the preferred observation channel when trusted and available. Prefer direct app/UI structure over pixel inference when it is available, stable, and fast enough.--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 app/window metadata and Accessibility snapshots. Use window or region capture only when structured app observation is insufficient.--Priority order:--1. Resolve the target app/window.-2. Read Accessibility state for controls and labels.-3. Capture only the target window when Accessibility cannot answer the question.-4. Crop to the relevant app region or control.-5. Lower resolution for controller signals.-6. Keep occasional high-resolution snapshots for the slow planner.--## Perception Modes--Use the cheapest technique that works:--| Need | Preferred Method |-| --- | --- |-| Mac app focus/running state | window metadata, NSWorkspace/Accessibility |-| Mac app controls and labels | Accessibility snapshot/action metadata |-| Weather visible location | Accessibility label/value first, cropped OCR fallback |-| 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-intent_id-scene_id-app_id-task_type-visible_location-search_field_state-result_state-confidence-raw_signals-```--The controller should consume this state without needing raw pixels.--## Fast Path--Per frame:--1. Read latest app/window/Accessibility state.-2. Capture and crop only if structured state is missing.-3. Run cheap OCR/template fallback only on the crop.-4. Update task state 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. Resolve and observe the Weather app window.-2. Measure app/window/Accessibility observation latency.-3. Extract search/result/location state for Weather.-4. Build a region cropper for Weather screenshot fallback.-5. Add cropped OCR fallback only if Accessibility cannot verify location.-6. Emit a world-state JSON event for each task step.-7. Record traces for replay.-8. Benchmark screenshot-to-model inference on cropped regions as a later visual-target path.--## Acceptance Criteria--- App observation p95 stays under the target budget for Weather lookup.-- Capture can run at 30 FPS minimum for later visual targets.-- Perception p95 stays under 50ms when screenshot/OCR fallback is used.-- 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.-- Weather result verification is traceable to Accessibility or cropped OCR evidence.diff --git a/plans/03-fast-controller.md b/plans/03-fast-controller.mddeleted file mode 100644index 0c54b3fa..00000000--- a/plans/03-fast-controller.md+++ /dev/null@@ -1,141 +0,0 @@-# Fast Controller--> Active status: not complete. Current controller support is deterministic and traceable for metadata/local-navigation dry-runs, but not yet proven against a live fast-navigation benchmark such as Weather lookup.--## Goal--Make local task decisions from typed state without waiting on slow reasoning.--The fast controller is the agent's reflex system. For the first product proof, that means deterministic navigation and UI actions; game movement is a later specialization of the same navigation loop.--## Responsibilities--- app launch/focus decisions-- search/type/select decisions-- clicking or Accessibility action selection-- menu navigation-- repeated app workflows-- result verification-- safe fallback and recovery triggers-- 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 first app-task path uses the same contract:--```text-TaskIntent + App Observation- -> Task State- -> Weather Lookup Policy- -> Semantic 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`-- `navigation_policy`-- `menu_policy`-- `avoidance_policy`-- `recovery_policy`-- `weather_lookup_policy`-- `app_search_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 |-| Weather lookup | finite-state app task policy over app focus/search/result state |-| app search box | type normalized entity once, submit/select, then verify |-| dodging | vector away from hazard |-| movement | waypoint or potential-field controller |-| repeated loops | finite-state machine |-| 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.--For app workflows, do not use an LLM to choose each click or keystroke. Use a task adapter and deterministic policy over current app state. The LLM may only produce a validated intent or recovery hint.--## 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-- ambiguous entity resolution when deterministic parsing fails--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 target app or later game window loses focus.-- Stop acting if world-state confidence is too low for too long.-- Stop before interacting with sensitive apps, login screens, payment screens, or private-message surfaces.--## First Milestones--1. Define the `TaskIntent` and task-state schema the controller consumes for Weather lookup.-2. Implement `weather_lookup_policy` for launch/focus/search/select/verify.-3. Add policy-selection logic for local app tasks.-4. Add confidence-aware fallback behavior and recovery hint triggers.-5. Record every chosen action with the intent id and state snapshot id.-6. Add Accessibility/window/screenshot-derived state inputs.-7. Replay recorded app-state traces before live input.-8. Keep detector/OCR/template-derived game inputs as follow-on policies.--## 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.-- Weather lookup can complete from parsed intent using deterministic state transitions.diff --git a/plans/05-action-engine.md b/plans/05-action-engine.mdindex 7b5e2805..f190d137 100644--- a/plans/05-action-engine.md+++ b/plans/05-action-engine.md@@ -49,7 +49,7 @@ For local app tasks, prefer the safest high-level primitive that works: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).+For games that support controllers, the action engine should expose a generic gamepad backend with buttons, sticks, triggers, and directional pads through the synthetic controller abstraction. See [14-synthetic-controller.md](14-synthetic-controller.md).## Rulesdiff --git a/plans/06-benchmarking.md b/plans/06-benchmarking.mdindex 5c530ed9..1cc479d3 100644--- a/plans/06-benchmarking.md+++ b/plans/06-benchmarking.md@@ -1,12 +1,12 @@-# Benchmarking And Monitoring+# Latency Budget, Benchmarking, And Monitoring-> Active status: not complete. Current benchmark support can summarize dry-run traces, but not persistent cross-run trends or a concrete fast-navigation command-to-result baseline.+> Active status: not complete. Current reports support synthetic and dry-run traces, but this plan is not complete until p50/p95/p99 budgets are measured for the first fast-navigation benchmark, compared with a same-machine manual baseline, and persisted across runs.## GoalMake latency visible, measurable, and hard to accidentally regress.-No latency claim counts unless it is measured.+No latency claim counts unless it is measured with local traces.The first benchmark target is the user-facing Weather navigation task:@@ -22,31 +22,89 @@ The project needs two observability loops:- local measurement while building and tuning the agent- continuous monitoring so latency regressions show up over time+## Product Targets++For the first Weather demo:++- command-to-first-action p95 under 300ms after text submission+- local observation/controller/input step p95 under 100ms+- command-to-verified-result faster than a documented manual baseline on the same machine++For later game and visual targets:++- visual reflex p95 under 100ms end to end+- stretch target of 30-60ms for simple games++## Stage Budgets++### Weather Task Budget++| Stage | Baseline Target | Stretch Target |+| --- | ---: | ---: |+| Intent parse | 5-100ms | <20ms deterministic |+| App launch/focus | 100-800ms | 50-300ms when already warm |+| App observation | 5-50ms | 2-15ms |+| Controller decision | 1-20ms | <5ms |+| Input execution | 1-20ms | <5ms |+| Result verification | 10-100ms | 5-30ms |++### Visual Reflex 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 remote call is required for common Weather command parsing or execution.+- No full-screen expensive inference unless the target 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.+- Do not wait for planner output before acting in the reflex loop.+- Do not type into an unverified focused control.++## Loop Shape++Use a latest-frame-wins design:++```text+Observation thread+ -> overwrites latest app/window/task state++Perception thread+ -> reads latest structured observation or latest frame fallback+ -> 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.+## Required MetricsPer loop:-- intent parse start timestamp-- intent parse end timestamp-- app launch/focus start timestamp-- app launch/focus end timestamp-- app observation start timestamp-- app observation end timestamp-- 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+- intent parse start and end timestamps+- app launch/focus start and end timestamps+- app observation start and end timestamps+- capture start and end timestamps+- perception start and end timestamps+- model preprocess start and end timestamps+- model inference start and end timestamps- world-state timestamp-- controller start timestamp-- controller end timestamp-- input command timestamp-- input execution timestamp-- verification start timestamp-- verification end timestamp+- controller start and end timestamps+- input command and execution timestamps+- verification start and end timestamps- command-to-result timestamp- frame age when perception begins- state age when controller begins@@ -54,26 +112,19 @@ Per loop:Aggregate:-- p50 latency-- p95 latency-- p99 latency-- dropped frames-- stale actions-- planner calls-- planner latency+- p50, p95, and p99 latency+- dropped frames and stale actions+- planner calls and planner latency- app launch/focus latency- app observation latency- result verification latency- command-to-result latency- manual baseline latency- controller fallback count-- capture FPS-- perception FPS-- controller tick rate+- capture FPS, perception FPS, and controller tick rate- queue depth- CPU usage-- GPU usage, if used-- GPU memory usage, if used+- GPU usage and GPU memory usage, if used- memory usage- thermal throttling indicator, when available@@ -92,9 +143,7 @@ Every trace event should include:- build/version id- machine profile-## Measuring End-To-End Latency--There are three levels of latency to measure.+## Measurement Levels### Command-To-Result Latency@@ -141,14 +190,15 @@ This may require external measurement, such as a high-FPS camera, OS-level inputAdd tiny timestamp spans around every hot-path boundary:```text-capture.start-capture.end+command.acceptedintent_parse.startintent_parse.endapp_focus.startapp_focus.endapp_observation.startapp_observation.end+capture.start+capture.endpreprocess.startpreprocess.endmodel.start@@ -182,6 +232,7 @@ Reports should show both total latency and stage latency:| decision_ms | `controller.end - controller.start` || input_ms | `input.execute - action.enqueue` || verification_ms | `verification.end - verification.start` |+| command_to_first_action_ms | `input.execute - command.accepted` || command_to_result_ms | `verification.end - command.accepted` || software_loop_ms | `input.execute - capture.end` || frame_age_ms | `controller.start - capture.end` |@@ -191,7 +242,7 @@ Frame and state age matter because an action can be computed quickly but still b## Trace Format-Every reflex action should be traceable:+Every action should be traceable:```texttrace_id@@ -208,6 +259,32 @@ machine_profilebuild_id```+## 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 or decoding before inference.+- GPU upload/download overhead.+- Model warmup during the first live loop.+- Remote model calls.+- Synchronous logging in the frame loop.+- Input APIs with hidden OS scheduling delays.+- App launch cold-start time.+- Accessibility permission or trust checks.+- Typing into an unverified focused control.+## Benchmark Modes1. Capture-only benchmark.@@ -268,13 +345,13 @@ Later, add a lightweight local dashboard with:- action timeline- alerts when thresholds are crossed-## Alerts+## Alerts And Regression GatesAlert on symptoms that matter to feel:-- p95 end-to-end latency over 100ms+- p95 visual reflex latency over 100ms- Weather command-to-result latency slower than manual baseline by more than the configured tolerance-- p99 end-to-end latency over 150ms+- p99 visual reflex latency over 150ms- stale action rate over 2%- dropped frame rate over 5%- perception p95 over 50ms@@ -284,17 +361,14 @@ Alert on symptoms that matter to feel:- 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 supported target:- intent parse p95 under the Weather budget- app observation p95 under the Weather budget- verification p95 under the Weather budget-- controller p95 under 20ms-- action execution p95 under 5ms+- command-to-first-action p95 under 300ms+- local observation/controller/input step p50 under 60ms+- local observation/controller/input step p95 under 100ms- command-to-result p95 faster than the manual Weather baseline or explicitly flaggedFor later visual targets:@@ -310,11 +384,11 @@ Use both absolute and comparative gates:- 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.+Small changes can pass absolute targets while still making the system worse over time. The comparative gate catches that drift. Alerts should include the stage that regressed, the previous baseline, and the worst trace ids.## Replay Harness-Record frames and world states so performance work can happen without launching the game every time.+Record frames and world states so performance work can happen without launching the target every time.Replay should support:@@ -334,6 +408,7 @@ Example:```textbaselines/macbook-pro-m3/+ weather.jsonsimple-2d-game.jsonwindows-desktop-gpu/simple-2d-game.json@@ -344,7 +419,7 @@ Each baseline should record:- hardware- OS version- screen resolution-- game/window settings+- app/window settings- agent config- capture backend- model versions@@ -360,18 +435,26 @@ Do not compare runs across different machines without labeling them. Hardware di1. 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.+3. Record Weather command, observation, action, and verification events.+4. Record capture and action events for visual/reflex runs.+5. Build a local trace viewer or summary command.+6. Add p50/p95/p99 report.+7. Add a same-machine manual Weather baseline.+8. Add a failing threshold check for regressions.+9. Add baseline comparison.+10. Add a 10-minute soak test.+11. Add live console monitoring for active runs.## Acceptance Criteria- A single command can print the latest latency report.+- Every Weather task trace includes intent parse, app launch/focus, observation, decision, input, and verification timestamps.+- Every visual action trace includes capture, perception, decision, and input timestamps.+- p50 local observation/controller/input step latency is under 60ms for the first supported target.+- p95 local observation/controller/input step latency is under 100ms for the first supported target.+- command-to-result time is compared with a manual Weather lookup baseline.+- Stale-frame actions are counted and visible in metrics.- Trace files can explain why an action happened.- Performance regressions are visible before release time.- Latency trends can be compared across runs from different days.-- The system can identify whether capture, perception, controller, or input caused a regression.+- The system can identify whether capture, perception, controller, input, app observation, or verification caused a regression.diff --git a/plans/07-rollout.md b/plans/07-rollout.mddeleted file mode 100644index f60fa5c9..00000000--- a/plans/07-rollout.md+++ /dev/null@@ -1,139 +0,0 @@-# Rollout Plan--> Archived status: historical context only. This file is not an active implementation queue. Supported behavior lives in `docs/`; future work from this idea needs a fresh active plan created deliberately.--## Phase 0: First Supported Target--Pick the first iPhone Mirroring target and define the initial supported 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 Target--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 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.--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 target can reuse the same loop-- only perception and policy adapters need major changes--## Open Decisions--- First supported iPhone game.-- Primary implementation language.-- macOS capture backend.-- macOS synthetic input backend.-- First iPhone Mirroring calibration method.-- Whether the first controller is pure rules or rules plus off-the-shelf perception.--## 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 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/08-dom-parsing.md b/plans/08-dom-parsing.mdindex c1a1257e..24c8b241 100644--- a/plans/08-dom-parsing.md+++ b/plans/08-dom-parsing.md@@ -1,7 +1,5 @@# DOM Parsing-> Archived status: historical context only. This file is not an active implementation queue. Supported behavior lives in `docs/`; future work from this idea needs a fresh active plan created deliberately.-## GoalUse DOM state as a low-latency perception channel for browser games, web apps, and desktop software built on web views.diff --git a/plans/09-screenshot-model-inference.md b/plans/09-screenshot-model-inference.mddeleted file mode 100644index f0ae792d..00000000--- a/plans/09-screenshot-model-inference.md+++ /dev/null@@ -1,189 +0,0 @@-# Screenshot Model Inference--> Archived status: historical context only. This file is not an active implementation queue. Supported behavior lives in `docs/`; future work from this idea needs a fresh active plan created deliberately.--## 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- -> 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.--## 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-- 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.--## 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 targets 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.-- Reuse input/output buffers.-- 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.--## 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-- explain unfamiliar UI-- explain failure traces-- suggest new regions of interest-- recover when the fast model is confused--Slow-path outputs should become hints 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 compatibility model 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 supported target.-- 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.mddeleted file mode 100644index d2bb096d..00000000--- a/plans/10-gaps-to-expand.md+++ /dev/null@@ -1,338 +0,0 @@-# Gaps To Expand--> Archived status: historical context only. This file is not an active implementation queue. Supported behavior lives in `docs/`; future work from this idea needs a fresh active plan created deliberately.--## 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 target?-- 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 target-- 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-- retention policy-- privacy filtering-- trace compression-- reproducible replay seeds--Deliverable:--- `data-and-replay.md` with file formats and commands for record, replay, inspect, 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 target while still staying latency-first.--## Priority 3: Model Lifecycle--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-- benchmark protocol-- conversion pipeline-- quantization plan-- warmup behavior-- versioning-- rollback-- quality gates-- runtime compatibility checks--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.--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-- 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 validation-- 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 tracesdiff --git a/plans/11-game-targets.md b/plans/11-game-targets.mddeleted file mode 100644index 72529a50..00000000--- a/plans/11-game-targets.md+++ /dev/null@@ -1,237 +0,0 @@-# Game Targets--> Archived status: historical context only. This file is not an active implementation queue. Supported behavior lives in `docs/`; future work from this idea needs a fresh active plan created deliberately.--## 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 production proving ground--## 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 target |-| 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 harnessesdiff --git a/plans/12-iphone-mirroring.md b/plans/12-iphone-mirroring.mddeleted file mode 100644index 54d5103b..00000000--- a/plans/12-iphone-mirroring.md+++ /dev/null@@ -1,195 +0,0 @@-# iPhone Mirroring--> Archived status: historical context only. This file is not an active implementation queue. Supported behavior lives in `docs/`; future work from this idea needs a fresh active plan created deliberately.--## 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.mddeleted file mode 100644index 29982f1a..00000000--- a/plans/13-subway-surfers-target.md+++ /dev/null@@ -1,221 +0,0 @@-# Subway Surfers Target Profile--> Archived status: historical context only. This file is not an active implementation queue. Supported behavior lives in `docs/`; future work from this idea needs a fresh active plan created deliberately.--## Goal--Use Subway Surfers as a high-pressure iPhone Mirroring target for low-latency screenshot perception and swipe control.--This is a strong production-readiness target, but not the first supported target. 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.mdindex d0941968..051f59f3 100644--- a/plans/14-synthetic-controller.md+++ b/plans/14-synthetic-controller.md@@ -15,6 +15,8 @@ This layer should work across games by separating:Touch gestures for iPhone Mirroring are one backend. A virtual gamepad is another backend. Keyboard/mouse is another.+This plan consolidates the previous standalone gamepad-controller sketch. Gamepad support is a backend and command family inside the broader synthetic controller, not a separate top-level architecture.+## Core IdeaThe fast controller should not know about screen coordinates, key codes, HID details, or OS input APIs.@@ -85,14 +87,19 @@ Gamepad-shaped commands:press_button(button, duration_ms)hold_button(button)release_button(button)+tap_dpad(direction, duration_ms)+hold_dpad(direction)+release_dpad(direction)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()+neutralize_sticks()+release_all()```+For low latency, axis updates should be cheap and avoid allocation.+Touch-shaped commands:```text@@ -156,6 +163,92 @@ Pick the backend per target:If a game supports controllers, prefer the gamepad backend because it is usually more stable than screen-coordinate mouse gestures.+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.++## Gamepad Backend Shape++Use a common modern controller shape and keep vendor labels in mapping metadata:++```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]+```++Gamepad-specific mappings should support:++```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)+```++Possible gamepad backends:++- virtual gamepad device+- hardware controller bridge+- emulator controller API+- browser Gamepad API test harness+- platform-specific HID driver++## 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+```+## Calibration StateStore calibration separately from controller logic:@@ -200,8 +293,18 @@ input_start_atinput_end_atvisual_confirmation_atsuccess+command_create_ms+backend_send_ms+device_update_ms+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.+## Safety Rules- Verify the target before input.@@ -211,10 +314,22 @@ success- Always support `stop()` and `release_all()`.- Release all held buttons, keys, sticks, triggers, and mouse buttons on shutdown.+## Testing Plan++1. Build a local input visualizer target for each backend family.+2. Send every button, axis, key, pointer, and gesture command that the backend declares.+3. Verify neutral and release behavior.+4. Measure p50/p95 command-send latency.+5. Test one emulator, simple controller-friendly game, or touch target.+6. Add a target mapping.+7. Replay a recorded action trace.+## 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.+- Buttons, D-pad, sticks, and triggers are all supported in the normalized gamepad interface.- Held inputs are always released on stop.- Commands are timestamped and replayable.- Backend latency is measured separately from decision latency.+- iPhone controller support is treated as a separate backend problem, not assumed through Mac iPhone Mirroring.diff --git a/plans/15-gamepad-controller.md b/plans/15-gamepad-controller.mddeleted file mode 100644index 9be04d73..00000000--- a/plans/15-gamepad-controller.md+++ /dev/null@@ -1,191 +0,0 @@-# Gamepad Controller--> Archived status: historical context only. This file is not an active implementation queue. Supported behavior lives in `docs/`; future work from this idea needs a fresh active plan created deliberately.--## 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/17-ios-control-prompt.md b/plans/17-ios-control-prompt.mdindex 42b90cb8..aa42351e 100644--- a/plans/17-ios-control-prompt.md+++ b/plans/17-ios-control-prompt.md@@ -1,7 +1,5 @@# iOS Control Prompt-> Archived status: historical context only. This file is not an active implementation queue. Supported behavior lives in `docs/`; future work from this idea needs a fresh active plan created deliberately.-## GoalCapture the operating prompt for controlling iOS, using PhoneAgent as a reference while keeping iPhone Mirroring gameplay as the main product path.diff --git a/plans/18-macos-accessibility.md b/plans/18-macos-accessibility.mdindex 82fdf215..a1a3d904 100644--- a/plans/18-macos-accessibility.md+++ b/plans/18-macos-accessibility.md@@ -1,185 +1,20 @@# macOS Accessibility-> Archived status: historical context only. This file is not an active implementation queue. Supported behavior lives in `docs/`; future work from this idea needs a fresh active plan created deliberately.+> Archived status: this slice is implemented. Supported behavior lives in `docs/`; future work needs a fresh active plan created deliberately.-## Goal+## Completed Slice-Use macOS Accessibility as a PhoneAgent-like tree/action backend for Mac apps, window management, setup flows, and non-frame-critical UI control.+Donkey now treats iPhone Mirroring as an ordinary Mac window candidate. Window discovery builds runtime app identity from the current `NSWorkspace` running-app map, enriches each visible window by pid, and keeps iPhone Mirroring as an additive hint instead of a separate discovery path.-This complements the fast screenshot/input loop. It does not replace low-latency visual gameplay perception.+The implemented accessibility/window slice covers:-## Feasibility+- content-rectangle calibration for mirrored iPhone content inside the selected generic target window+- generic target-window focus, process, bundle, bounds, visibility, and safety guarding before synthetic input+- timeout-bounded Accessibility snapshot reads and Accessibility action execution+- native macOS dialog detection from Accessibility trees as a safety stop-Yes, macOS has a system Accessibility API based around `AXUIElement`.+## Current Boundary-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.+Accessibility still describes the Mac-side container and native dialogs. It does not inspect iPhone game internals inside the mirrored video stream. Live gameplay perception remains screenshot/model driven, with the calibrated content rectangle feeding the capture/control loop.-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--## Supported Read-Only Snapshot Boundary--Donkey now supports bounded, read-only Accessibility snapshots for the manual target context capture milestone.--Supported behavior:--- check process Accessibility trust without prompting-- resolve a selected target window by pid, title, focus, and frame metadata when possible-- serialize a shallow tree with role, title/label, value summary, frame, enabled/focused state, and available action names-- cap depth, children per node, total nodes, and text length-- write trusted snapshots to the run artifact store under `accessibility/`-- append a clear partial-run event when Accessibility trust is missing--Current boundary:--- The snapshot service records action names but does not perform actions.-- Full app navigation, menu selection, value setting, focus changes, and setup/recovery flows remain future work.--## 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--Completed for the manual capture milestone:--1. Check Accessibility trust status from the runtime capture path.-2. Resolve a target app/window and dump bounded read-only AX attributes.-3. Store shallow AX snapshots as local run artifacts.--Remaining future milestones:--1. Find the iPhone Mirroring window and read its bounds for calibration.-2. Detect focus loss before sending synthetic input.-3. Add an accessibility-backed window guard to the iPhone gameplay loop.-4. 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.+No remaining implementation queue is tracked in this plan.diff --git a/plans/19-ai-harness.md b/plans/19-ai-harness.mddeleted file mode 100644index 6e79c8a8..00000000--- a/plans/19-ai-harness.md+++ /dev/null@@ -1,700 +0,0 @@-# AI Harness--> Active status: not complete. The current repo now has OpenAI and Ollama-compatible planner adapters, model routing, local task-intent parsing, local voice-transcription model selection and adapter boundary, memory scaffolding, and a provider-backed slow-planner generator, but installed live transcription runtime wiring, semantic retrieval, redaction, aggregate model observability, and provider-decoded memory write proposals still remain.--## Goal--Build the slow-path AI harness that connects the agent to LLMs/VLMs, manages memory, routes model calls, validates structured intent/planner output, and keeps model choices updateable without touching the low-latency local task loop.--The harness is the agent's reasoning and memory layer. It supports ambiguous command parsing, planning, recovery, trace explanation, model-assisted perception setup, and long-running improvement. It does not drive app navigation, typing, clicking, or frame-by-frame gameplay.--## Core Rule--The AI harness must never block the local task 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-Intent / Observation / Controller / Action- -> local, bounded, latest-frame-wins--AI Harness- -> async, slow-path, memory-backed, validated intent/hint 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-- route local voice transcription before command parsing-- parse ambiguous natural commands into validated task intents when deterministic parsing is insufficient-- 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-- produce recovery suggestions when local app navigation cannot verify progress-- 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 app launching, typing, clicking, or Accessibility actions-- 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- -> Intent Parser / Intent Validator- -> 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, app activation, or the controller tick.--## Intent Parsing Role--Common commands should use deterministic parsing first. The first target command is:--```text-"show me the weather for SF"- -> weather_lookup(city: "San Francisco", app: "Weather")-```--Use the AI harness only when deterministic parsing cannot confidently resolve the task, target app, or entities. AI output must become a validated `TaskIntent`, not direct input.--The intent parser output should include:--```text-intent_id-task_type-target_app-entities-normalized_entities-confidence-parser_source-needs_confirmation-source_model_call_id-```--Validation rules:--- unsupported task types are rejected-- low-confidence entity normalization asks for clarification or falls back to dry-run only-- dangerous apps or sensitive targets are rejected before app launch-- model-proposed actions are ignored unless they fit the task adapter's allowed action space--## 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)-transcribe_audio(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.--## Local Voice Transcription Candidate--Voice input should become plain transcript text before it enters command parsing. Treat transcription as a local runtime job, not as an Ollama chat task and not as direct action authority.--The current default candidate is NVIDIA Parakeet TDT 0.6B v3 through a local NeMo-style runtime. It is selected because the official model card describes a current 600M-parameter ASR model with automatic language detection across 25 languages, punctuation/capitalization, word and segment timestamps, 16kHz mono `.wav`/`.flac` input, and a permissive CC BY 4.0 license. Whisper large-v3-turbo remains the local rollback candidate because it is widely supported in Transformers and local speech stacks.--The current implementation has the adapter boundary: it accepts bounded local audio buffers, routes through `AIModelRouter`, invokes an injectable local transcription runtime, emits transcript text plus timing/confidence metadata, and marks transcript text as input to the same validated `TaskIntent` path used by typed commands. The next slice is installing concrete Parakeet/Whisper runtime adapters and wiring pointer-prompt microphone buffers into this adapter.--## Model Roles--Do not hardcode one model everywhere. Assign models by role.--| Role | Default Candidate | Use |-| --- | --- | --- |-| `intent_local` | small local structured-output model, with deterministic parser as fallback/validator | common command-to-intent parsing before local app execution |-| `voice_transcription_local` | `nvidia/parakeet-tdt-0.6b-v3`, rollback `openai/whisper-large-v3-turbo` | local speech-to-text before command parsing; never direct input |-| `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 task loop |-| `vision_local_slow` | Gemma 3 or PaliGemma candidate | local multimodal UI understanding outside the task loop |-| `vision_snapshot` | `gpt-5.4-mini` or `gpt-5.5` | occasional screenshot understanding outside the task 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 common app command parsing:- prefer intent_local with a strict timeout and validate output against app-task definitions--if job is voice transcription:- prefer voice_transcription_local through a local runtime and route the transcript through normal intent validation--if intent_local is unavailable or invalid:- use deterministic parser only as fallback for known commands--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 validated intents and controller hints, not prose.--For app tasks, structured intent is the first output:--```text-intent_id-task_type-target_app-entities-normalized_entities-confidence-needs_confirmation-allowed_action_space-```--For longer-running recovery, planner hints remain advisory:--```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 `TaskIntent` and validation for `weather_lookup`.-2. Add deterministic parsing for the Weather command and aliases such as `SF`.-3. Route ambiguous intent parsing through local-first model selection with strict timeout.-4. Define model registry schema and role names.-5. Build the OpenAI Responses provider adapter.-6. Add one structured planner hint schema.-7. Build short-term run memory and target memory as JSONL files.-8. Add text embedding support for semantic memory.-9. Add snapshot builder with screenshot/DOM redaction hooks.-10. Add model router with intent, default, cheap, strong, local, and fallback roles.-11. Add optional Ollama provider support for local slow-path planning.-12. Add memory write proposals with deterministic approval.-13. Add trace events for model calls, intent parsing, and memory operations.-14. Add a replay/eval command for model and prompt changes.-15. Add a model update checklist that writes `last_verified_at` and docs URLs.--## Acceptance Criteria--- No remote model call appears in the local task/reflex trace.-- The Weather command can parse and execute through the deterministic path without a remote model call.-- The controller can continue for a full run with the harness disabled.-- Model-generated intents are schema-validated before task-adapter selection.-- 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.--## Current Supported Slice--The AI harness foundation now supports the optional slow-path sidecar pieces needed by the first local-navigation loop:--- structured planner hints with validation, expiry, latest-valid selection, and trace/state/model-call source links-- a model registry and router boundary so default provider model ids live in registry entries instead of controller logic-- a provider-neutral OpenAI Responses structured-output adapter with `store: false`, traceable failure results, and strict planner-hint decoding-- an Ollama-compatible local planner adapter using the same strict planner-hint schema-- `ProviderBackedSlowPlannerHintGenerator`, which can try local slow planning first and fall back to the online OpenAI adapter without changing the hint bus or controller contract-- short-term run memory, scoped target JSONL memory, deterministic memory-write approval, listing, and deletion-- planner replay/eval scaffolding and model update checklist records-- `DryRunSlowPlannerSidecar` snapshots from compact world state, action, trace summaries, optional screenshot artifact references, and memory-- `ValidatedPlannerHintBus` and `PlannerHintAwareControllerPolicy`, which allow validated hints to advise controller metadata without becoming direct input-- tests proving planner latency does not move reflex p95 when the harness runs beside the dry-run loop--This is not complete AI harness work. Local/online planner hint generation is now supported, but semantic memory retrieval, redaction hooks, aggregate model observability, and provider-decoded memory proposals still need to be built before this plan can move to `plans/done/`.--## Required Before This Plan Is Done--- Add embedding-backed semantic memory retrieval and explicit retrieval budgets.-- Add `weather_lookup` intent parsing and validation with deterministic coverage for "show me the weather for SF".-- Add redaction hooks before any screenshot or DOM summary is sent to a remote provider.-- Add aggregate model-call observability reports for latency, schema validity, hint acceptance, cost, and recovery success.-- Add memory write proposal decoding directly from provider outputs, then route proposals through the deterministic approver.diff --git a/plans/20-off-the-shelf-run-loop.md b/plans/20-off-the-shelf-run-loop.mdindex dcecb8db..261f5f7b 100644--- a/plans/20-off-the-shelf-run-loop.md+++ b/plans/20-off-the-shelf-run-loop.md@@ -1,7 +1,5 @@# Off-The-Shelf Run Loop-> Active status: not complete. The current repo supports metadata-only local-navigation dry-run scaffolding, generic local-app task catalog parsing/adaptation, local JSON/JSONL task-definition loading, local-model command parsing, local task-context intake, Accessibility control discovery and guarded AX action commands, review/approval-first document form-fill planning, pointer-prompt typed command submission, macOS app launch/focus, guarded macOS keyboard input, local voice-transcription model selection and adapter boundary, target-app availability checks, Accessibility visible-text observation when trusted, built-in task definitions across weather/media/document domains, YOLO26 screenshot segmentation runner boundary, and guarded live-action smoke. It still needs installed local model runtimes, user-visible document approval UI, benchmark evidence, and real-session verification before any benchmark should be treated as done.-## GoalBuild the first fast local navigation agent from existing system components instead of custom model work.@@ -519,20 +517,16 @@ The runtime foundation now supports a product-shaped local-navigation slice of t- screenshot segmentation model-candidate metadata and runner evidence boundary for Ultralytics YOLO26 nano segmentation (`yolo26n-seg.pt`)- local voice transcription adapter boundary that routes bounded local audio to the selected local ASR runtime and emits transcript text for the normal command parser- optional slow-planner sidecar that publishes only validated hints without blocking reflex latency+- coordinator event publication for pointer-prompt local-app task runs, including lifecycle and tool events for launch/focus, guarded input, Accessibility actions, observation, and terminal status+- user-visible document form-fill review UI that applies only approved field proposals through guarded Accessibility input+- live local-app visual fallback policy that uses bounded screenshot UI understanding only when Accessibility/window metadata do not provide required controls or verification text+- continuous target-window frame streaming source for longer dry-run reflex sessions while preserving latest-frame-wins queue behavior-This is still not the full off-the-shelf vision stack and must not be treated as completion. It can replay and trace compact local vision evidence, name a current YOLO segmentation candidate, load local task definitions, discover Accessibility controls, build approval-gated document form-fill commands, and run a guarded keyboard/AX local-app task path, but it does not bundle live local detector/local-model/OCR/segmentation runtimes, continuous streaming capture, user-visible form-fill approval UI, high-volume persisted replay traces, or target-specific visual calibration.+This slice can replay and trace compact local vision evidence, name a current YOLO segmentation candidate, load local task definitions, discover Accessibility controls, build approval-gated document form-fill commands, run a guarded keyboard/AX local-app task path, publish coordinator events for local-app runs, open a document form-fill approval UI, use local UI understanding only as an observation fallback, and stream target-window frames for longer dry-run sessions. Broader visual model runtime expansion is intentionally outside this plan.## Required Before This Plan Is Done-- Manually verify measured guarded-live execution for the first local-app task benchmark command "show me the weather for SF".-- Prove fast local navigation from parsed intent, local app observation, deterministic controller state, and guarded live input, not remote planning.-- Add the user-visible review and approval UI for document form-fill proposals before enabling default guarded field entry.-- Add result verification through Accessibility plus local model UI-understanding fallback, with OCR only if a narrow benchmark justifies it.-- Add installed measured YOLO26 screenshot/crop segmentation inference for visual fallback, including export/runtime choice, crop size, mask quality, and p95 latency.-- Add installed measured local ASR runtime wiring for Parakeet/Whisper and route transcripts through command parsing.-- Add continuous streaming capture once queue-depth, stale-result, and trace sinks are ready for longer sessions.-- Add durable high-volume replay trace persistence and target-specific benchmark baselines.-- Keep local model UI understanding, segmentation, and OCR optional in the live path until each has cropped, measured, target-specific evidence.+No remaining implementation items are tracked in this plan. Benchmarking and broader model-runtime expansion are intentionally ignored here; create or activate a separate plan before pursuing them.## Where To Lookdiff --git a/plans/done/15-gamepad-controller.md b/plans/done/15-gamepad-controller.mdnew file mode 100644index 00000000..3cf6b520--- /dev/null+++ b/plans/done/15-gamepad-controller.md@@ -0,0 +1,5 @@+# Gamepad Controller++> Consolidated into `plans/14-synthetic-controller.md`.++This historical plan duplicated the synthetic-controller abstraction. Its useful gamepad-specific details now live in the canonical synthetic controller plan as the gamepad backend shape, backend contract, iPhone Mirroring caveat, measurement notes, testing plan, and acceptance criteria.diff --git a/plans/done/19-ai-harness.md b/plans/done/19-ai-harness.mdnew file mode 100644index 00000000..5a8067a1--- /dev/null+++ b/plans/done/19-ai-harness.md@@ -0,0 +1,73 @@+# AI Harness Memory And Voice Cleanup++> Active status: implemented. This plan was narrowed to semantic-memory wiring, provider memory write proposals, live voice audio hardening, and focused tests. Those slices are now supported in local code. Benchmarking is out of scope for this plan.++## 1. Wire Real Semantic Memory Retrieval++Original gap: `SemanticRunMemoryRetriever` existed, but the live pointer-prompt path called it with no records. Retrieval needed to search actual run/target memory and feed the selected results into planner or command context.++Implemented:++- load target-scoped records from `TargetMemoryJSONLStore` or the active run memory before command/planner calls+- pass real records to `SemanticRunMemoryRetriever.retrieve`+- include selected memory ids and summaries in `RunContextPackage` or provider prompt context+- keep retrieval bounded by record count, prompt characters, scope, target id, and minimum relevance+- record retrieval metadata on the command/planner trace++Done:++- a command or planner call can retrieve non-empty target memories from local storage+- retrieved memory is visible in the assembled model context without sending full memory logs+- tests cover target scoping, prompt budget limits, and empty-memory fallback++## 2. Integrate Provider Memory Write Proposals++Original gap: `ProviderDecodedMemoryProposalHandler` could decode proposals and apply deterministic approval, but live provider flows did not request, decode, approve, or persist model-proposed memory writes.++Implemented:++- extend provider planner output to include optional memory write proposals+- keep planner hints valid even when memory proposals are absent or rejected+- run decoded proposals through `RunMemoryApprover`+- persist approved target memories through `TargetMemoryJSONLStore`+- attach proposal, approval, rejection, and persistence counts to model trace metadata+- reject proposals that lack source links, retention, target/run/user scope requirements, or safe content++Done:++- provider-backed planner calls can return memory proposals alongside validated hints+- approved target memories are persisted and later retrievable+- rejected proposals are traceable without being stored+- tests cover accepted proposals, rejected proposals, malformed proposal payloads, and no-proposal outputs++## 3. Harden Live Voice Transcription Audio++Original gap: pointer-prompt voice capture fed `LocalVoiceTranscriptionAdapter` and `ProcessBackedParakeetTranscriptionRuntime`, but the captured audio format could differ from the Parakeet runtime expectation.++Original risk:++- microphone capture emits `pcm_f32le`+- device sample rate may not be 16 kHz+- Parakeet registry metadata expects 16 kHz mono `.wav` or `.flac`+- the sidecar writes received bytes to a temp file based on the provided format, so unsupported raw PCM can fail or decode incorrectly++Implemented:++- convert pointer-prompt audio to a supported Parakeet input format before transcription+- normalize to mono 16 kHz where required+- prefer a small local conversion utility with explicit metadata over implicit sidecar assumptions+- surface clear failure metadata when conversion or transcription is unavailable+- keep transcript text flowing through the normal validated task-intent path++Done:++- live pointer-prompt voice input sends Parakeet-compatible audio+- tests cover PCM input conversion metadata, empty audio fallback, runtime unavailable fallback, and successful transcript-to-command flow++## 4. Verification++Completed checks:++1. `swift test --filter AIHarnessAdapterTests`+2. `swift test --filter RunMemoryStoreTests`+3. `swift test`diff --git a/plans/21-swiftui-pointer-ui.md b/plans/done/21-swiftui-pointer-ui.mdsimilarity index 96%rename from plans/21-swiftui-pointer-ui.mdrename to plans/done/21-swiftui-pointer-ui.mdindex ee9ed3b9..ede6f7f8 100644--- a/plans/21-swiftui-pointer-ui.md+++ b/plans/done/21-swiftui-pointer-ui.md@@ -15,7 +15,7 @@ Add the production macOS SwiftUI pointer prompt UI while keeping the future real- The active pointer renders with a shadow and supports theme-color customization.- Contracts, UI, runtime boundary, AI boundary, and app entrypoint are separate Swift targets.- Runtime boundary references `plans/20-off-the-shelf-run-loop.md`.-- AI boundary references `plans/19-ai-harness.md`.+- AI boundary references `plans/done/19-ai-harness.md`.- No Screen Recording, Accessibility, model calls, capture loop, or input execution is included in this slice.## Acceptance