Skip to content

Open source CapCut alternative.

TypeScript

Refocus plans on fast local navigation benchmarks

David Lec4ad9e8ad442
diff --git a/apps/Donkey/Package.swift b/apps/Donkey/Package.swift
index 983c568f..102853dc 100644
--- a/apps/Donkey/Package.swift
+++ b/apps/Donkey/Package.swift
@@ -27,7 +27,10 @@ let package = Package(
),
.target(
name: "DonkeyAI",
- dependencies: ["DonkeyContracts"]
+ dependencies: [
+ "DonkeyContracts",
+ "DonkeyRuntime"
+ ]
),
.target(
name: "DonkeyUI",
diff --git a/apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift b/apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift
index 7b15c6b9..f5bfa72b 100644
--- a/apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift
+++ b/apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift
@@ -3,6 +3,7 @@ import Foundation
public enum AIModelProvider: String, Codable, Equatable, Sendable {
case openAI
+ case ollama
}
public enum AIModelRole: String, Codable, Equatable, Sendable {
@@ -95,6 +96,45 @@ public struct AIModelRegistry: Codable, Equatable, Sendable {
)
]
)
+
+ public static let defaultHybridPlanner = AIModelRegistry(
+ entries: [
+ AIModelRegistryEntry(
+ id: "ollama-planner-hint-local",
+ role: .plannerHint,
+ provider: .ollama,
+ modelID: "qwen3:8b",
+ endpoint: URL(string: "http://127.0.0.1:11434/api/generate")!,
+ capabilities: [.textInput, .structuredOutputs],
+ timeoutMS: 8_000,
+ promptVersion: "planner-hint-v1",
+ evalStatus: .candidate,
+ docsURL: URL(string: "https://docs.ollama.com/api")!,
+ rollbackID: nil,
+ metadata: [
+ "local": "true",
+ "docsSource": "official Ollama API docs"
+ ]
+ ),
+ AIModelRegistryEntry(
+ id: "openai-planner-hint-default",
+ role: .plannerHint,
+ provider: .openAI,
+ modelID: "gpt-5.2",
+ endpoint: URL(string: "https://api.openai.com/v1/responses")!,
+ capabilities: [.textInput, .structuredOutputs],
+ timeoutMS: 8_000,
+ promptVersion: "planner-hint-v1",
+ evalStatus: .candidate,
+ docsURL: URL(string: "https://platform.openai.com/docs/api-reference/responses/create")!,
+ rollbackID: nil,
+ metadata: [
+ "lastVerifiedAt": "2026-05-16",
+ "docsSource": "official OpenAI Responses API and models docs"
+ ]
+ )
+ ]
+ )
}
public enum AIModelJobType: String, Codable, Equatable, Sendable {
@@ -126,6 +166,7 @@ public struct AIModelRouteRequest: Codable, Equatable, Sendable {
public var latencyTolerance: AIModelLatencyTolerance
public var failedModelEntryIDs: Set<String>
public var requiredCapabilities: Set<AIModelCapability>
+ public var allowedProviders: Set<AIModelProvider>?
public init(
jobType: AIModelJobType,
@@ -133,7 +174,8 @@ public struct AIModelRouteRequest: Codable, Equatable, Sendable {
privacyMode: AIModelPrivacyMode = .privacySensitive,
latencyTolerance: AIModelLatencyTolerance = .interactive,
failedModelEntryIDs: Set<String> = [],
- requiredCapabilities: Set<AIModelCapability> = [.structuredOutputs]
+ requiredCapabilities: Set<AIModelCapability> = [.structuredOutputs],
+ allowedProviders: Set<AIModelProvider>? = nil
) {
self.jobType = jobType
self.risk = risk
@@ -141,6 +183,19 @@ public struct AIModelRouteRequest: Codable, Equatable, Sendable {
self.latencyTolerance = latencyTolerance
self.failedModelEntryIDs = failedModelEntryIDs
self.requiredCapabilities = requiredCapabilities
+ self.allowedProviders = allowedProviders
+ }
+
+ public func limitingProviders(_ providers: Set<AIModelProvider>) -> AIModelRouteRequest {
+ AIModelRouteRequest(
+ jobType: jobType,
+ risk: risk,
+ privacyMode: privacyMode,
+ latencyTolerance: latencyTolerance,
+ failedModelEntryIDs: failedModelEntryIDs,
+ requiredCapabilities: requiredCapabilities,
+ allowedProviders: allowedProviders.map { $0.intersection(providers) } ?? providers
+ )
}
}
@@ -165,6 +220,7 @@ public struct AIModelRouter: Sendable {
&& entry.evalStatus != .disabled
&& !request.failedModelEntryIDs.contains(entry.id)
&& request.requiredCapabilities.isSubset(of: entry.capabilities)
+ && (request.allowedProviders?.contains(entry.provider) ?? true)
&& allowsRisk(request.risk, entry: entry)
}
.sorted { lhs, rhs in
@@ -204,9 +260,13 @@ public struct AIModelRouter: Sendable {
var value = 0
if entry.evalStatus == .passing { value += 10 }
if request.latencyTolerance == .interactive { value -= entry.timeoutMS / 1_000 }
- if request.privacyMode == .privacySensitive,
- entry.provider == .openAI {
- value += 1
+ if request.privacyMode == .privacySensitive {
+ switch entry.provider {
+ case .ollama:
+ value += 4
+ case .openAI:
+ value -= 1
+ }
}
return value
}
diff --git a/apps/Donkey/Sources/DonkeyAI/OllamaPlannerHintAdapter.swift b/apps/Donkey/Sources/DonkeyAI/OllamaPlannerHintAdapter.swift
new file mode 100644
index 00000000..df58cba3
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyAI/OllamaPlannerHintAdapter.swift
@@ -0,0 +1,251 @@
+import DonkeyContracts
+import DonkeyRuntime
+import Foundation
+
+public struct OllamaPlannerHintAdapter: Sendable {
+ public static let schemaID = "planner_hint_v1"
+
+ public var router: AIModelRouter
+ public var httpClient: any AIHTTPClient
+
+ public init(
+ router: AIModelRouter = AIModelRouter(registry: .defaultHybridPlanner),
+ httpClient: any AIHTTPClient = URLSessionAIHTTPClient()
+ ) {
+ self.router = router
+ self.httpClient = httpClient
+ }
+
+ public func generatePlannerHint(
+ _ request: PlannerHintAdapterRequest
+ ) async -> PlannerHintAdapterResult {
+ let entry: AIModelRegistryEntry
+ do {
+ entry = try router.route(request.routeRequest.limitingProviders([.ollama]))
+ } catch {
+ return result(
+ entry: nil,
+ request: request,
+ status: .invalidOutput,
+ validationStatus: "routingFailed",
+ latencyMS: nil,
+ metadata: ["error": String(describing: error)]
+ )
+ }
+
+ let startedAt = ProcessInfo.processInfo.systemUptime
+ do {
+ let urlRequest = try makeURLRequest(entry: entry, adapterRequest: request)
+ let (data, response) = try await httpClient.send(urlRequest)
+ let latencyMS = (ProcessInfo.processInfo.systemUptime - startedAt) * 1_000
+
+ if response.statusCode == 429 {
+ return result(entry: entry, request: request, status: .rateLimited, validationStatus: "notValidated", latencyMS: latencyMS)
+ }
+
+ if response.statusCode >= 500 {
+ return result(entry: entry, request: request, status: .providerOutage, validationStatus: "notValidated", latencyMS: latencyMS)
+ }
+
+ guard (200..<300).contains(response.statusCode),
+ let outputText = try Self.outputText(from: data),
+ let hint = try PlannerHintWireCodec.decodeHint(
+ outputText,
+ sourceTraceID: request.sourceTraceID,
+ sourceFrameID: request.sourceFrameID,
+ sourceStateID: request.sourceStateID,
+ modelCallID: "model-call-\(request.sourceTraceID)",
+ now: request.now
+ )
+ else {
+ return result(entry: entry, request: request, status: .invalidOutput, validationStatus: "invalid", latencyMS: latencyMS)
+ }
+
+ return PlannerHintAdapterResult(
+ hint: hint,
+ trace: trace(
+ entry: entry,
+ request: request,
+ status: .completed,
+ validationStatus: "schemaDecoded",
+ latencyMS: latencyMS,
+ metadata: [
+ "http.status": String(response.statusCode),
+ "local.provider": "ollama"
+ ]
+ )
+ )
+ } catch is CancellationError {
+ return result(entry: entry, request: request, status: .cancelled, validationStatus: "notValidated", latencyMS: nil)
+ } catch {
+ let latencyMS = (ProcessInfo.processInfo.systemUptime - startedAt) * 1_000
+ let status: AIModelCallStatus = (error as NSError).code == NSURLErrorTimedOut ? .timeout : .providerOutage
+ return result(
+ entry: entry,
+ request: request,
+ status: status,
+ validationStatus: "notValidated",
+ latencyMS: latencyMS,
+ metadata: ["error": String(describing: error)]
+ )
+ }
+ }
+
+ private func makeURLRequest(
+ entry: AIModelRegistryEntry,
+ adapterRequest: PlannerHintAdapterRequest
+ ) throws -> URLRequest {
+ var request = URLRequest(url: entry.endpoint)
+ request.httpMethod = "POST"
+ request.timeoutInterval = Double(entry.timeoutMS) / 1_000
+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")
+ request.httpBody = try JSONSerialization.data(withJSONObject: requestBody(entry: entry, adapterRequest: adapterRequest))
+ return request
+ }
+
+ private func requestBody(
+ entry: AIModelRegistryEntry,
+ adapterRequest: PlannerHintAdapterRequest
+ ) -> [String: Any] {
+ [
+ "model": entry.modelID,
+ "prompt": promptText(for: adapterRequest),
+ "stream": false,
+ "format": PlannerHintWireCodec.jsonSchema(),
+ "options": [
+ "num_predict": 512
+ ]
+ ]
+ }
+
+ private func promptText(for request: PlannerHintAdapterRequest) -> String {
+ [
+ "Return one planner hint as strict JSON. Hints are advisory and never direct input.",
+ "goal: \(request.context.userGoal)",
+ "target: \(request.context.targetID)",
+ "runtime: \(request.context.runtimeProfile)",
+ "latest_state: \(request.context.latestWorldState?.summary ?? "none")",
+ "source_state_id: \(request.sourceStateID ?? "none")",
+ "valid_hints: \(request.context.activeHints.map(\.summary).joined(separator: " | "))",
+ "recent_failures: \(request.context.recentFailures.map(\.summary).joined(separator: " | "))"
+ ]
+ .joined(separator: "\n")
+ }
+
+ private func result(
+ entry: AIModelRegistryEntry?,
+ request: PlannerHintAdapterRequest,
+ status: AIModelCallStatus,
+ validationStatus: String,
+ latencyMS: Double?,
+ metadata: [String: String] = [:]
+ ) -> PlannerHintAdapterResult {
+ PlannerHintAdapterResult(
+ hint: nil,
+ trace: trace(
+ entry: entry,
+ request: request,
+ status: status,
+ validationStatus: validationStatus,
+ latencyMS: latencyMS,
+ metadata: metadata
+ )
+ )
+ }
+
+ private func trace(
+ entry: AIModelRegistryEntry?,
+ request: PlannerHintAdapterRequest,
+ status: AIModelCallStatus,
+ validationStatus: String,
+ latencyMS: Double?,
+ metadata: [String: String] = [:]
+ ) -> AIModelCallTrace {
+ AIModelCallTrace(
+ id: "model-call-\(request.sourceTraceID)",
+ role: entry?.role ?? .plannerHint,
+ provider: entry?.provider ?? .ollama,
+ modelID: entry?.modelID ?? "unrouted",
+ promptVersion: entry?.promptVersion ?? "unrouted",
+ schemaID: Self.schemaID,
+ latencyMS: latencyMS,
+ timeoutMS: entry?.timeoutMS ?? 0,
+ status: status,
+ validationStatus: validationStatus,
+ sourceTraceID: request.sourceTraceID,
+ sourceStateID: request.sourceStateID,
+ metadata: metadata
+ )
+ }
+}
+
+public struct ProviderBackedSlowPlannerHintGenerator: SlowPlannerHintGenerating {
+ public var localAdapter: OllamaPlannerHintAdapter
+ public var onlineAdapter: OpenAIPlannerHintAdapter
+ public var providerOrder: [AIModelProvider]
+
+ public init(
+ localAdapter: OllamaPlannerHintAdapter = OllamaPlannerHintAdapter(),
+ onlineAdapter: OpenAIPlannerHintAdapter = OpenAIPlannerHintAdapter(),
+ providerOrder: [AIModelProvider] = [.ollama, .openAI]
+ ) {
+ self.localAdapter = localAdapter
+ self.onlineAdapter = onlineAdapter
+ self.providerOrder = providerOrder
+ }
+
+ public func generatePlannerHint(
+ snapshot: SlowPlannerSnapshot
+ ) async -> SlowPlannerHintGenerationResult {
+ let request = PlannerHintAdapterRequest(
+ context: snapshot.context,
+ sourceTraceID: snapshot.latestWorldState.traceID,
+ sourceFrameID: snapshot.latestWorldState.frameID,
+ sourceStateID: snapshot.latestWorldState.id,
+ now: snapshot.latestWorldState.observedAt,
+ routeRequest: AIModelRouteRequest(
+ jobType: .plannerHint,
+ privacyMode: .privacySensitive,
+ latencyTolerance: .background
+ )
+ )
+ var metadata: [String: String] = [
+ "providerOrder": providerOrder.map(\.rawValue).joined(separator: ",")
+ ]
+
+ for provider in providerOrder {
+ let result: PlannerHintAdapterResult
+ switch provider {
+ case .ollama:
+ result = await localAdapter.generatePlannerHint(request)
+ case .openAI:
+ result = await onlineAdapter.generatePlannerHint(request)
+ }
+
+ metadata["\(provider.rawValue).status"] = result.trace.status.rawValue
+ metadata["\(provider.rawValue).validationStatus"] = result.trace.validationStatus
+ metadata["lastProvider"] = provider.rawValue
+
+ if let hint = result.hint,
+ result.trace.status == .completed {
+ metadata["selectedProvider"] = provider.rawValue
+ metadata["selectedModelID"] = result.trace.modelID
+ metadata["selectedModelCallID"] = result.trace.id
+ return SlowPlannerHintGenerationResult(hint: hint, metadata: metadata)
+ }
+ }
+
+ metadata["selectedProvider"] = "none"
+ return SlowPlannerHintGenerationResult(hint: nil, metadata: metadata)
+ }
+}
+
+private struct OllamaGenerateResponse: Decodable {
+ var response: String?
+}
+
+private extension OllamaPlannerHintAdapter {
+ static func outputText(from data: Data) throws -> String? {
+ try JSONDecoder().decode(OllamaGenerateResponse.self, from: data).response
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyAI/OpenAIPlannerHintAdapter.swift b/apps/Donkey/Sources/DonkeyAI/OpenAIPlannerHintAdapter.swift
index 978f4b20..80cdfbea 100644
--- a/apps/Donkey/Sources/DonkeyAI/OpenAIPlannerHintAdapter.swift
+++ b/apps/Donkey/Sources/DonkeyAI/OpenAIPlannerHintAdapter.swift
@@ -137,7 +137,7 @@ public struct OpenAIPlannerHintAdapter: Sendable {
) async -> PlannerHintAdapterResult {
let entry: AIModelRegistryEntry
do {
- entry = try router.route(request.routeRequest)
+ entry = try router.route(request.routeRequest.limitingProviders([.openAI]))
} catch {
return result(
entry: nil,
@@ -305,21 +305,7 @@ public struct OpenAIPlannerHintAdapter: Sendable {
}
private func plannerHintJSONSchema() -> [String: Any] {
- [
- "type": "object",
- "additionalProperties": false,
- "required": ["id", "goal", "policyName", "priorities", "preferredActions", "avoidActions", "confidence", "expiryMilliseconds"],
- "properties": [
- "id": ["type": "string"],
- "goal": ["type": "string"],
- "policyName": ["type": "string"],
- "priorities": ["type": "array", "items": ["type": "string"]],
- "preferredActions": ["type": "array", "items": ["type": "string", "enum": HotLoopActionKind.allCases.map(\.rawValue)]],
- "avoidActions": ["type": "array", "items": ["type": "string", "enum": HotLoopActionKind.allCases.map(\.rawValue)]],
- "confidence": ["type": "number"],
- "expiryMilliseconds": ["type": "integer"]
- ]
- ]
+ PlannerHintWireCodec.jsonSchema()
}
private func result(
@@ -354,7 +340,7 @@ public struct OpenAIPlannerHintAdapter: Sendable {
AIModelCallTrace(
id: "model-call-\(request.sourceTraceID)",
role: entry?.role ?? .plannerHint,
- provider: entry?.provider ?? .openAI,
+ provider: entry?.provider ?? request.routeRequest.allowedProviders?.first ?? .openAI,
modelID: entry?.modelID ?? "unrouted",
promptVersion: entry?.promptVersion ?? "unrouted",
schemaID: Self.schemaID,
@@ -390,7 +376,7 @@ private struct OpenAIResponseContent: Decodable {
var text: String?
}
-private struct PlannerHintWireOutput: Decodable {
+struct PlannerHintWireOutput: Decodable {
var id: String
var goal: String
var policyName: String
@@ -401,17 +387,23 @@ private struct PlannerHintWireOutput: Decodable {
var expiryMilliseconds: UInt64
}
-private extension OpenAIPlannerHintAdapter {
- static func outputText(from data: Data) throws -> String? {
- let envelope = try JSONDecoder().decode(OpenAIResponseEnvelope.self, from: data)
- if let outputText = envelope.outputText {
- return outputText
- }
-
- return envelope.output?
- .flatMap { $0.content ?? [] }
- .first { $0.type == "output_text" }?
- .text
+enum PlannerHintWireCodec {
+ static func jsonSchema() -> [String: Any] {
+ [
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["id", "goal", "policyName", "priorities", "preferredActions", "avoidActions", "confidence", "expiryMilliseconds"],
+ "properties": [
+ "id": ["type": "string"],
+ "goal": ["type": "string"],
+ "policyName": ["type": "string"],
+ "priorities": ["type": "array", "items": ["type": "string"]],
+ "preferredActions": ["type": "array", "items": ["type": "string", "enum": HotLoopActionKind.allCases.map(\.rawValue)]],
+ "avoidActions": ["type": "array", "items": ["type": "string", "enum": HotLoopActionKind.allCases.map(\.rawValue)]],
+ "confidence": ["type": "number"],
+ "expiryMilliseconds": ["type": "integer"]
+ ]
+ ]
}
static func decodeHint(
@@ -447,7 +439,7 @@ private extension OpenAIPlannerHintAdapter {
)
}
- static func actions(from rawValues: [String]) -> [HotLoopActionKind]? {
+ private static func actions(from rawValues: [String]) -> [HotLoopActionKind]? {
var actions: [HotLoopActionKind] = []
for rawValue in rawValues {
guard let action = HotLoopActionKind(rawValue: rawValue) else {
@@ -459,6 +451,38 @@ private extension OpenAIPlannerHintAdapter {
}
}
+private extension OpenAIPlannerHintAdapter {
+ static func outputText(from data: Data) throws -> String? {
+ let envelope = try JSONDecoder().decode(OpenAIResponseEnvelope.self, from: data)
+ if let outputText = envelope.outputText {
+ return outputText
+ }
+
+ return envelope.output?
+ .flatMap { $0.content ?? [] }
+ .first { $0.type == "output_text" }?
+ .text
+ }
+
+ static func decodeHint(
+ _ text: String,
+ sourceTraceID: String,
+ sourceFrameID: String?,
+ sourceStateID: String?,
+ modelCallID: String,
+ now: RunTraceTimestamp
+ ) throws -> StructuredPlannerHint? {
+ try PlannerHintWireCodec.decodeHint(
+ text,
+ sourceTraceID: sourceTraceID,
+ sourceFrameID: sourceFrameID,
+ sourceStateID: sourceStateID,
+ modelCallID: modelCallID,
+ now: now
+ )
+ }
+}
+
private extension RunTraceTimestamp {
func addingMilliseconds(_ milliseconds: UInt64) -> RunTraceTimestamp {
RunTraceTimestamp(
diff --git a/apps/Donkey/Sources/DonkeyRuntime/CheapPerceptionAndController.swift b/apps/Donkey/Sources/DonkeyRuntime/CheapPerceptionAndController.swift
index 4965dcce..5ed8b6b7 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/CheapPerceptionAndController.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/CheapPerceptionAndController.swift
@@ -157,10 +157,10 @@ public struct DeterministicControllerPolicy: DryRunControllerPolicy {
target: affordance.targetBounds,
confidence: affordance.confidence,
rationale: "Selected highest-confidence tap target affordance",
- metadata: [
+ metadata: affordance.metadata.merging([
"fallback": "false",
"sourceSignalID": affordance.sourceSignalID
- ]
+ ]) { current, _ in current }
)
}
@@ -169,12 +169,12 @@ public struct DeterministicControllerPolicy: DryRunControllerPolicy {
kind: .wait,
confidence: affordance.confidence,
rationale: "Best affordance confidence is below action threshold",
- metadata: [
+ metadata: affordance.metadata.merging([
"fallback": "true",
"fallbackReason": "lowConfidence",
"sourceSignalID": affordance.sourceSignalID,
"minimumActionConfidence": String(minimumActionConfidence)
- ]
+ ]) { current, _ in current }
)
}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/OffTheShelfVisionPerception.swift b/apps/Donkey/Sources/DonkeyRuntime/OffTheShelfVisionPerception.swift
new file mode 100644
index 00000000..ae82f823
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/OffTheShelfVisionPerception.swift
@@ -0,0 +1,323 @@
+import DonkeyContracts
+import Foundation
+
+public enum OffTheShelfVisionSignalKind: String, Codable, Equatable, Sendable {
+ case detector
+ case template
+ case ocr
+ case segmentation
+}
+
+public struct RecordedOffTheShelfVisionObservation: Codable, Equatable, Sendable {
+ public var id: String
+ public var label: String
+ public var bounds: HotLoopRect?
+ public var confidence: Double
+ public var metadata: [String: String]
+
+ public init(
+ id: String,
+ label: String,
+ bounds: HotLoopRect? = nil,
+ confidence: Double,
+ metadata: [String: String] = [:]
+ ) {
+ self.id = id
+ self.label = label
+ self.bounds = bounds
+ self.confidence = Self.clamped(confidence)
+ self.metadata = metadata
+ }
+
+ private static func clamped(_ value: Double) -> Double {
+ min(max(value, 0), 1)
+ }
+}
+
+public struct RecordedOffTheShelfVisionSignal: Codable, Equatable, Sendable {
+ public var id: String
+ public var kind: OffTheShelfVisionSignalKind
+ public var componentID: String
+ public var modelID: String?
+ public var cropID: String?
+ public var confidence: Double
+ public var observations: [RecordedOffTheShelfVisionObservation]
+ public var preprocessMS: Double
+ public var modelInferenceMS: Double
+ public var adapterOverheadMS: Double
+ public var metadata: [String: String]
+
+ public init(
+ id: String,
+ kind: OffTheShelfVisionSignalKind,
+ componentID: String,
+ modelID: String? = nil,
+ cropID: String? = nil,
+ confidence: Double,
+ observations: [RecordedOffTheShelfVisionObservation],
+ preprocessMS: Double = 0,
+ modelInferenceMS: Double = 0,
+ adapterOverheadMS: Double = 1,
+ metadata: [String: String] = [:]
+ ) {
+ self.id = id
+ self.kind = kind
+ self.componentID = componentID
+ self.modelID = modelID
+ self.cropID = cropID
+ self.confidence = Self.clamped(confidence)
+ self.observations = observations
+ self.preprocessMS = max(0, preprocessMS)
+ self.modelInferenceMS = max(0, modelInferenceMS)
+ self.adapterOverheadMS = max(0, adapterOverheadMS)
+ self.metadata = metadata
+ }
+
+ private static func clamped(_ value: Double) -> Double {
+ min(max(value, 0), 1)
+ }
+}
+
+public enum RecordedOffTheShelfVisionMetadataCodec {
+ public static func encode(signals: [RecordedOffTheShelfVisionSignal]) -> [String: String] {
+ var metadata = [
+ "vision.offTheShelf.encoded": "true",
+ "vision.offTheShelf.rawPixelsExposed": "false",
+ "vision.offTheShelf.signal.count": String(signals.count)
+ ]
+
+ for (signalIndex, signal) in signals.enumerated() {
+ let prefix = "vision.offTheShelf.signal.\(signalIndex)."
+ metadata[prefix + "id"] = signal.id
+ metadata[prefix + "kind"] = signal.kind.rawValue
+ metadata[prefix + "componentID"] = signal.componentID
+ metadata[prefix + "modelID"] = signal.modelID ?? ""
+ metadata[prefix + "cropID"] = signal.cropID ?? ""
+ metadata[prefix + "confidence"] = String(signal.confidence)
+ metadata[prefix + "latency.preprocessMS"] = String(signal.preprocessMS)
+ metadata[prefix + "latency.modelInferenceMS"] = String(signal.modelInferenceMS)
+ metadata[prefix + "latency.adapterOverheadMS"] = String(signal.adapterOverheadMS)
+ metadata[prefix + "observation.count"] = String(signal.observations.count)
+ for (key, value) in signal.metadata {
+ metadata[prefix + "metadata.\(key)"] = value
+ }
+
+ for (observationIndex, observation) in signal.observations.enumerated() {
+ let observationPrefix = prefix + "observation.\(observationIndex)."
+ metadata[observationPrefix + "id"] = observation.id
+ metadata[observationPrefix + "label"] = observation.label
+ metadata[observationPrefix + "confidence"] = String(observation.confidence)
+ if let bounds = observation.bounds {
+ metadata[observationPrefix + "bounds.x"] = String(bounds.origin.x)
+ metadata[observationPrefix + "bounds.y"] = String(bounds.origin.y)
+ metadata[observationPrefix + "bounds.width"] = String(bounds.size.width)
+ metadata[observationPrefix + "bounds.height"] = String(bounds.size.height)
+ metadata[observationPrefix + "bounds.space"] = bounds.space.rawValue
+ }
+ for (key, value) in observation.metadata {
+ metadata[observationPrefix + "metadata.\(key)"] = value
+ }
+ }
+ }
+
+ return metadata
+ }
+
+ public static func decode(from metadata: [String: String]) -> [RecordedOffTheShelfVisionSignal] {
+ let count = Int(metadata["vision.offTheShelf.signal.count"] ?? "") ?? 0
+ guard count > 0 else { return [] }
+
+ return (0..<count).compactMap { index -> RecordedOffTheShelfVisionSignal? in
+ let prefix = "vision.offTheShelf.signal.\(index)."
+ guard let id = nonEmpty(metadata[prefix + "id"]),
+ let kind = OffTheShelfVisionSignalKind(rawValue: metadata[prefix + "kind"] ?? ""),
+ let componentID = nonEmpty(metadata[prefix + "componentID"])
+ else {
+ return nil
+ }
+
+ let observationCount = Int(metadata[prefix + "observation.count"] ?? "") ?? 0
+ let observations = (0..<observationCount).compactMap { observationIndex -> RecordedOffTheShelfVisionObservation? in
+ let observationPrefix = prefix + "observation.\(observationIndex)."
+ guard let observationID = nonEmpty(metadata[observationPrefix + "id"]),
+ let label = nonEmpty(metadata[observationPrefix + "label"])
+ else {
+ return nil
+ }
+
+ return RecordedOffTheShelfVisionObservation(
+ id: observationID,
+ label: label,
+ bounds: decodeBounds(prefix: observationPrefix + "bounds.", metadata: metadata),
+ confidence: Double(metadata[observationPrefix + "confidence"] ?? "") ?? 0,
+ metadata: prefixedMetadata(
+ prefix: observationPrefix + "metadata.",
+ metadata: metadata
+ )
+ )
+ }
+
+ return RecordedOffTheShelfVisionSignal(
+ id: id,
+ kind: kind,
+ componentID: componentID,
+ modelID: nonEmpty(metadata[prefix + "modelID"]),
+ cropID: nonEmpty(metadata[prefix + "cropID"]),
+ confidence: Double(metadata[prefix + "confidence"] ?? "") ?? 0,
+ observations: observations,
+ preprocessMS: Double(metadata[prefix + "latency.preprocessMS"] ?? "") ?? 0,
+ modelInferenceMS: Double(metadata[prefix + "latency.modelInferenceMS"] ?? "") ?? 0,
+ adapterOverheadMS: Double(metadata[prefix + "latency.adapterOverheadMS"] ?? "") ?? 1,
+ metadata: prefixedMetadata(prefix: prefix + "metadata.", metadata: metadata)
+ )
+ }
+ }
+
+ private static func decodeBounds(
+ prefix: String,
+ metadata: [String: String]
+ ) -> HotLoopRect? {
+ guard let x = Double(metadata[prefix + "x"] ?? ""),
+ let y = Double(metadata[prefix + "y"] ?? ""),
+ let width = Double(metadata[prefix + "width"] ?? ""),
+ let height = Double(metadata[prefix + "height"] ?? ""),
+ let space = HotLoopCoordinateSpace(rawValue: metadata[prefix + "space"] ?? "")
+ else {
+ return nil
+ }
+
+ return HotLoopRect(x: x, y: y, width: width, height: height, space: space)
+ }
+
+ private static func prefixedMetadata(
+ prefix: String,
+ metadata: [String: String]
+ ) -> [String: String] {
+ metadata.reduce(into: [:]) { result, item in
+ guard item.key.hasPrefix(prefix) else { return }
+ let key = String(item.key.dropFirst(prefix.count))
+ guard !key.isEmpty else { return }
+ result[key] = item.value
+ }
+ }
+
+ private static func nonEmpty(_ value: String?) -> String? {
+ guard let value, !value.isEmpty else { return nil }
+ return value
+ }
+}
+
+public struct OffTheShelfVisionPerceptionAdapter: DryRunPerceptionAdapting {
+ public var adapterName: String
+
+ public init(adapterName: String = "off-the-shelf-vision-perception") {
+ self.adapterName = adapterName
+ }
+
+ public func perceive(frame: HotLoopFrame) async -> [HotLoopPerceptionSignal] {
+ let signals = RecordedOffTheShelfVisionMetadataCodec.decode(from: frame.metadata)
+ return signals.map { signal in
+ let observedAt = frame.capturedAt.addingMilliseconds(
+ signal.preprocessMS + signal.modelInferenceMS + signal.adapterOverheadMS
+ )
+ return HotLoopPerceptionSignal(
+ id: signal.id,
+ traceID: frame.traceID,
+ frameID: frame.id,
+ kind: signal.kind.rawValue,
+ capturedAt: frame.capturedAt,
+ observedAt: observedAt,
+ confidence: signal.confidence,
+ observations: signal.observations.map { observation in
+ HotLoopPerceptionObservation(
+ id: observation.id,
+ label: observation.label,
+ bounds: observation.bounds,
+ confidence: observation.confidence,
+ metadata: observation.metadata.merging([
+ "vision.componentID": signal.componentID,
+ "vision.modelID": signal.modelID ?? "",
+ "vision.cropID": signal.cropID ?? "",
+ "vision.signalKind": signal.kind.rawValue
+ ]) { current, _ in current }
+ )
+ },
+ plannerHintID: frame.plannerHintID,
+ metadata: signal.metadata.merging([
+ "adapter": adapterName,
+ "rawPixelsExposed": "false",
+ "vision.localEvidence": "true",
+ "vision.componentID": signal.componentID,
+ "vision.modelID": signal.modelID ?? "",
+ "vision.cropID": signal.cropID ?? "",
+ "latency.preprocessMS": String(signal.preprocessMS),
+ "latency.modelInferenceMS": String(signal.modelInferenceMS)
+ ]) { current, _ in current }
+ )
+ }
+ }
+}
+
+public struct OffTheShelfVisionWorldStateProjector: DryRunWorldStateProjecting {
+ public var staleSignalThresholdMS: Double
+
+ public init(staleSignalThresholdMS: Double = 250) {
+ self.staleSignalThresholdMS = staleSignalThresholdMS
+ }
+
+ public func project(
+ frame: HotLoopFrame,
+ signals: [HotLoopPerceptionSignal],
+ observedAt: RunTraceTimestamp
+ ) async -> HotLoopWorldState {
+ HotLoopWorldState.build(
+ id: "state-\(frame.id)",
+ frame: frame,
+ signals: signals,
+ observedAt: observedAt,
+ staleThresholdMS: staleSignalThresholdMS,
+ actionAffordances: actionAffordances(from: signals),
+ metadata: [
+ "projector": "off-the-shelf-vision-world-state-projector",
+ "vision.localEvidence": String(!signals.isEmpty),
+ "rawPixelsExposed": "false"
+ ]
+ )
+ }
+
+ private func actionAffordances(
+ from signals: [HotLoopPerceptionSignal]
+ ) -> [HotLoopActionAffordance] {
+ signals.flatMap { signal in
+ signal.observations.compactMap { observation in
+ guard let bounds = observation.bounds else { return nil }
+ return HotLoopActionAffordance(
+ id: "affordance-\(observation.id)",
+ kind: .tapTarget,
+ targetBounds: bounds,
+ confidence: min(signal.confidence, observation.confidence),
+ sourceSignalID: signal.id,
+ metadata: [
+ "vision.label": observation.label,
+ "vision.signalKind": signal.kind,
+ "vision.componentID": signal.metadata["vision.componentID"] ?? "",
+ "vision.modelID": signal.metadata["vision.modelID"] ?? "",
+ "vision.cropID": signal.metadata["vision.cropID"] ?? "",
+ "vision.localEvidence": "true"
+ ].merging(observation.metadata) { current, _ in current }
+ )
+ }
+ }
+ }
+}
+
+private extension RunTraceTimestamp {
+ func addingMilliseconds(_ milliseconds: Double) -> RunTraceTimestamp {
+ RunTraceTimestamp(
+ wallClock: wallClock.addingTimeInterval(milliseconds / 1_000),
+ monotonicUptimeNanoseconds: UInt64(
+ max(0, Double(monotonicUptimeNanoseconds) + milliseconds * 1_000_000)
+ )
+ )
+ }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
index c034822d..8cdd3287 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
@@ -1,5 +1,6 @@
import DonkeyAI
import DonkeyContracts
+import DonkeyRuntime
import Foundation
import Testing
@@ -46,6 +47,27 @@ struct AIHarnessAdapterTests {
}
}
+ @Test
+ func privacySensitivePlannerRoutePrefersLocalProviderWhenAvailable() throws {
+ let registry = AIModelRegistry(
+ entries: [
+ entry(id: "online", provider: .openAI, modelID: "gpt-5.2", evalStatus: .candidate),
+ entry(id: "local", provider: .ollama, modelID: "qwen3:8b", evalStatus: .candidate)
+ ]
+ )
+ let router = AIModelRouter(registry: registry)
+
+ let selected = try router.route(
+ AIModelRouteRequest(
+ jobType: .plannerHint,
+ privacyMode: .privacySensitive
+ )
+ )
+
+ #expect(selected.id == "local")
+ #expect(selected.provider == .ollama)
+ }
+
@Test
func openAIAdapterBuildsResponsesRequestWithStoreFalseAndDecodesStructuredHint() async throws {
let httpClient = FakeAIHTTPClient(
@@ -112,6 +134,97 @@ struct AIHarnessAdapterTests {
#expect(invalidOutput.trace.status == .invalidOutput)
}
+ @Test
+ func ollamaAdapterBuildsLocalGenerateRequestAndDecodesStructuredHint() async throws {
+ let httpClient = FakeAIHTTPClient(
+ data: ollamaResponseData(
+ response: """
+ {"id":"local-hint-1","goal":"recover locally","policyName":"local-planner-policy","priorities":["observe menu"],"preferredActions":["observe"],"avoidActions":["tapTarget"],"confidence":0.74,"expiryMilliseconds":3000}
+ """
+ ),
+ statusCode: 200
+ )
+ let adapter = OllamaPlannerHintAdapter(
+ router: AIModelRouter(
+ registry: AIModelRegistry(
+ entries: [
+ entry(
+ id: "local-planner",
+ provider: .ollama,
+ modelID: "qwen3:8b",
+ endpoint: URL(string: "http://127.0.0.1:11434/api/generate")!
+ )
+ ]
+ )
+ ),
+ httpClient: httpClient
+ )
+
+ let result = await adapter.generatePlannerHint(adapterRequest())
+
+ #expect(result.hint?.id == "local-hint-1")
+ #expect(result.hint?.preferredActions == [.observe])
+ #expect(result.trace.status == .completed)
+ #expect(result.trace.provider == .ollama)
+ #expect(result.trace.metadata["local.provider"] == "ollama")
+
+ let request = try #require(httpClient.requests.first)
+ #expect(request.url?.absoluteString == "http://127.0.0.1:11434/api/generate")
+ let body = try #require(request.httpBodyJSONObject)
+ #expect(body["model"] as? String == "qwen3:8b")
+ #expect(body["stream"] as? Bool == false)
+ #expect(body["format"] as? [String: Any] != nil)
+ #expect(request.value(forHTTPHeaderField: "Authorization") == nil)
+ }
+
+ @Test
+ func providerBackedSlowPlannerFallsBackFromLocalToOnlineProvider() async {
+ let localAdapter = OllamaPlannerHintAdapter(
+ router: AIModelRouter(
+ registry: AIModelRegistry(
+ entries: [
+ entry(
+ id: "local-planner",
+ provider: .ollama,
+ modelID: "qwen3:8b",
+ endpoint: URL(string: "http://127.0.0.1:11434/api/generate")!
+ )
+ ]
+ )
+ ),
+ httpClient: FakeAIHTTPClient(data: Data("{}".utf8), statusCode: 500)
+ )
+ let onlineAdapter = OpenAIPlannerHintAdapter(
+ router: AIModelRouter(
+ registry: AIModelRegistry(
+ entries: [entry(id: "online-planner", provider: .openAI, modelID: "gpt-5.2")]
+ )
+ ),
+ httpClient: FakeAIHTTPClient(
+ data: responseData(
+ outputText: """
+ {"id":"online-hint-1","goal":"fallback online","policyName":"online-planner-policy","priorities":["recover"],"preferredActions":["wait"],"avoidActions":[],"confidence":0.81,"expiryMilliseconds":4000}
+ """
+ ),
+ statusCode: 200
+ ),
+ environment: ["OPENAI_API_KEY": "test-key"]
+ )
+ let planner = ProviderBackedSlowPlannerHintGenerator(
+ localAdapter: localAdapter,
+ onlineAdapter: onlineAdapter,
+ providerOrder: [.ollama, .openAI]
+ )
+
+ let result = await planner.generatePlannerHint(snapshot: slowPlannerSnapshot())
+
+ #expect(result.hint?.id == "online-hint-1")
+ #expect(result.metadata["ollama.status"] == "providerOutage")
+ #expect(result.metadata["openAI.status"] == "completed")
+ #expect(result.metadata["selectedProvider"] == "openAI")
+ #expect(result.metadata["selectedModelID"] == "gpt-5.2")
+ }
+
private func adapterRequest() -> PlannerHintAdapterRequest {
PlannerHintAdapterRequest(
context: RunContextPackage(
@@ -135,21 +248,25 @@ struct AIHarnessAdapterTests {
private func entry(
id: String,
+ provider: AIModelProvider = .openAI,
modelID: String,
+ endpoint: URL = URL(string: "https://api.openai.com/v1/responses")!,
evalStatus: AIModelEvalStatus = .candidate,
timeoutMS: Int = 8_000
) -> AIModelRegistryEntry {
AIModelRegistryEntry(
id: id,
role: .plannerHint,
- provider: .openAI,
+ provider: provider,
modelID: modelID,
- endpoint: URL(string: "https://api.openai.com/v1/responses")!,
+ endpoint: endpoint,
capabilities: [.textInput, .structuredOutputs],
timeoutMS: timeoutMS,
promptVersion: "planner-hint-v1",
evalStatus: evalStatus,
- docsURL: URL(string: "https://platform.openai.com/docs/api-reference/responses/create")!
+ docsURL: provider == .openAI
+ ? URL(string: "https://platform.openai.com/docs/api-reference/responses/create")!
+ : URL(string: "https://docs.ollama.com/api")!
)
}
@@ -161,6 +278,59 @@ struct AIHarnessAdapterTests {
return Data("{\"id\":\"resp-1\",\"output_text\":\"\(escaped)\"}".utf8)
}
+ private func ollamaResponseData(response: String) -> Data {
+ let escaped = response
+ .replacingOccurrences(of: "\\", with: "\\\\")
+ .replacingOccurrences(of: "\"", with: "\\\"")
+ .replacingOccurrences(of: "\n", with: "\\n")
+ return Data("{\"model\":\"qwen3:8b\",\"response\":\"\(escaped)\",\"done\":true}".utf8)
+ }
+
+ private func slowPlannerSnapshot() -> SlowPlannerSnapshot {
+ let observedAt = timestamp(10)
+ let context = RunContextPackage(
+ sessionID: "session-1",
+ userGoal: "avoid hazards",
+ targetID: "target-1",
+ runtimeProfile: "dry-run",
+ latestWorldState: RunWorldStateSummary(
+ stateID: "state-1",
+ summary: "player centered",
+ confidence: 0.9
+ ),
+ transcriptSummary: ""
+ )
+ let worldState = HotLoopWorldState(
+ id: "state-1",
+ traceID: "trace-1",
+ frameID: "frame-1",
+ targetID: "target-1",
+ observedAt: observedAt,
+ signalSummaries: [],
+ actionAffordances: [],
+ confidence: 0.9
+ )
+ let action = HotLoopControllerAction(
+ id: "action-1",
+ traceID: "trace-1",
+ frameID: "frame-1",
+ stateID: "state-1",
+ kind: .wait,
+ target: nil,
+ policyName: "test-policy",
+ confidence: 0.9,
+ rationale: "test"
+ )
+ return SlowPlannerSnapshot(
+ id: "snapshot-1",
+ triggerReasons: [.sceneChanged],
+ context: context,
+ latestWorldState: worldState,
+ latestAction: action,
+ traceSummaries: []
+ )
+ }
+
private func timestamp(_ milliseconds: UInt64) -> RunTraceTimestamp {
RunTraceTimestamp(
wallClock: Date(timeIntervalSince1970: Double(milliseconds) / 1_000),
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/OffTheShelfVisionPerceptionTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/OffTheShelfVisionPerceptionTests.swift
new file mode 100644
index 00000000..2e33f039
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/OffTheShelfVisionPerceptionTests.swift
@@ -0,0 +1,163 @@
+import DonkeyContracts
+@testable import DonkeyRuntime
+import Foundation
+import Testing
+
+@Suite
+struct OffTheShelfVisionPerceptionTests {
+ @Test
+ func metadataCodecRoundTripsLocalVisionEvidence() throws {
+ let metadata = RecordedOffTheShelfVisionMetadataCodec.encode(signals: [
+ recordedSignal(kind: .detector, id: "detector-signal", modelID: "yolo-nano-local"),
+ recordedSignal(kind: .ocr, id: "ocr-signal", modelID: "vision-text-local")
+ ])
+
+ let signals = RecordedOffTheShelfVisionMetadataCodec.decode(from: metadata)
+
+ #expect(metadata["vision.offTheShelf.rawPixelsExposed"] == "false")
+ #expect(signals.map(\.kind) == [.detector, .ocr])
+ #expect(signals.first?.componentID == "component-detector-signal")
+ #expect(signals.first?.observations.first?.bounds == HotLoopRect(
+ x: 0.42,
+ y: 0.58,
+ width: 0.12,
+ height: 0.08,
+ space: .normalizedTarget
+ ))
+ }
+
+ @Test
+ func adapterBuildsSignalsFromRecordedOffTheShelfVisionOutput() async throws {
+ let frame = fixtureFrame(signals: [
+ recordedSignal(
+ kind: .template,
+ id: "template-signal",
+ modelID: "button-template-v1",
+ preprocessMS: 2,
+ modelInferenceMS: 3,
+ adapterOverheadMS: 1
+ )
+ ])
+
+ let signals = await OffTheShelfVisionPerceptionAdapter().perceive(frame: frame)
+ let signal = try #require(signals.first)
+ let observation = try #require(signal.observations.first)
+
+ #expect(signal.kind == "template")
+ #expect(signal.metadata["vision.localEvidence"] == "true")
+ #expect(signal.metadata["rawPixelsExposed"] == "false")
+ #expect(signal.metadata["latency.preprocessMS"] == "2.0")
+ #expect(signal.metadata["latency.modelInferenceMS"] == "3.0")
+ #expect(signal.sourceAgeMS(at: timestamp(16)) == 6)
+ #expect(observation.metadata["vision.modelID"] == "button-template-v1")
+ #expect(observation.bounds?.space == .normalizedTarget)
+ }
+
+ @Test
+ func dryRunLoopActsFromLocalVisionEvidenceAndRecordsLatency() async throws {
+ let coordinator = RunCoordinator()
+ let frame = fixtureFrame(signals: [
+ recordedSignal(
+ kind: .detector,
+ id: "detector-signal",
+ modelID: "yolo-nano-local",
+ preprocessMS: 3,
+ modelInferenceMS: 7,
+ adapterOverheadMS: 1
+ )
+ ])
+ let loop = DryRunReflexLoop(
+ coordinator: coordinator,
+ frameSource: RecordedFrameSource(frames: [frame]),
+ perceptionAdapter: OffTheShelfVisionPerceptionAdapter(),
+ worldStateProjector: OffTheShelfVisionWorldStateProjector(),
+ controllerPolicy: DeterministicControllerPolicy()
+ )
+
+ let result = await loop.run(
+ session: RunSession(
+ id: "session-local-vision",
+ userGoal: "tap detected play button",
+ targetID: "target-visual-game"
+ )
+ )
+
+ let trace = try #require(await coordinator.latestReflexTrace())
+ let report = await ReflexLatencyReportBuilder.build(from: coordinator.reflexTraces())
+
+ #expect(result.processedFrameCount == 1)
+ #expect(result.latestWorldState?.metadata["vision.localEvidence"] == "true")
+ #expect(result.latestAction?.kind == .tapTarget)
+ #expect(result.latestAction?.metadata["vision.modelID"] == "yolo-nano-local")
+ #expect(trace.latencyBreakdown.preprocessMS == 3)
+ #expect(trace.latencyBreakdown.modelInferenceMS == 7)
+ #expect(trace.latencyBreakdown.perceptionMS == 11)
+ #expect(trace.metadata["vision.localEvidence"] == "true")
+ #expect(trace.metadata["vision.signalKind"] == "detector")
+ #expect(report.modelInferenceMS.p95 == 7)
+ #expect(report.decisionMS.p95 == 1)
+ }
+
+ private func recordedSignal(
+ kind: OffTheShelfVisionSignalKind,
+ id: String,
+ modelID: String,
+ preprocessMS: Double = 1,
+ modelInferenceMS: Double = 4,
+ adapterOverheadMS: Double = 1
+ ) -> RecordedOffTheShelfVisionSignal {
+ RecordedOffTheShelfVisionSignal(
+ id: id,
+ kind: kind,
+ componentID: "component-\(id)",
+ modelID: modelID,
+ cropID: "gameplay-crop",
+ confidence: 0.88,
+ observations: [
+ RecordedOffTheShelfVisionObservation(
+ id: "observation-\(id)",
+ label: "play-button",
+ bounds: HotLoopRect(
+ x: 0.42,
+ y: 0.58,
+ width: 0.12,
+ height: 0.08,
+ space: .normalizedTarget
+ ),
+ confidence: 0.82,
+ metadata: [
+ "templateID": "play-button-template"
+ ]
+ )
+ ],
+ preprocessMS: preprocessMS,
+ modelInferenceMS: modelInferenceMS,
+ adapterOverheadMS: adapterOverheadMS
+ )
+ }
+
+ private func fixtureFrame(signals: [RecordedOffTheShelfVisionSignal]) -> HotLoopFrame {
+ HotLoopFrame(
+ id: "frame-local-vision",
+ traceID: "trace-local-vision",
+ targetID: "target-visual-game",
+ capturedAt: timestamp(10),
+ sourceKind: .recorded,
+ windowBounds: HotLoopRect(x: 0, y: 0, width: 390, height: 844, space: .screen),
+ crop: HotLoopCrop(
+ id: "gameplay-crop",
+ bounds: HotLoopRect(x: 0, y: 120, width: 390, height: 600, space: .window),
+ outputSize: HotLoopSize(width: 390, height: 600, space: .crop)
+ ),
+ pixelSize: HotLoopSize(width: 390, height: 844, space: .window),
+ metadata: RecordedOffTheShelfVisionMetadataCodec.encode(signals: signals)
+ )
+ }
+
+ private func timestamp(_ milliseconds: UInt64) -> RunTraceTimestamp {
+ RunTraceTimestamp(
+ wallClock: Date(timeIntervalSince1970: Double(milliseconds) / 1_000),
+ monotonicUptimeNanoseconds: milliseconds * 1_000_000
+ )
+ }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/SlowPlannerSidecarTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/SlowPlannerSidecarTests.swift
index 1f8e987f..ffdf5034 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/SlowPlannerSidecarTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/SlowPlannerSidecarTests.swift
@@ -148,6 +148,29 @@ struct SlowPlannerSidecarTests {
#expect(plannedAction.metadata["plannerHintPreferredAction"] == "true")
}
+ @Test
+ func controllerRunsThirtySecondsWithoutPlannerOutput() async {
+ let frames = (0...30).map { index in
+ frame(id: "frame-\(index + 1)", milliseconds: UInt64(index * 1_000))
+ }
+ let coordinator = RunCoordinator()
+ let loop = DryRunReflexLoop(
+ coordinator: coordinator,
+ frameSource: SyntheticFrameSource(frames: frames)
+ )
+
+ let result = await loop.run(session: session())
+ let report = await ReflexLatencyReportBuilder.build(
+ from: coordinator.reflexTraces(),
+ droppedFrameCount: result.droppedFrameCount
+ )
+
+ #expect(result.processedFrameCount == 31)
+ #expect(result.latestAction != nil)
+ #expect(report.traceCount == 31)
+ #expect(report.softwareLoopMS.p95 != nil)
+ }
+
@Test
func slowPlannerLatencyDoesNotMoveReflexLatencyReport() async {
let frames = (0..<4).map { index in
diff --git a/docs/README.md b/docs/README.md
index 25c98cb0..8c621ca8 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 that
Plans 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 run-loop and AI-harness roadmap can be considered complete, especially fast local navigation from local model/perception output and a slow planner loop that can use both local and online LLM providers.
+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, especially the first Weather lookup benchmark from natural command to local navigation, guarded input, result verification, latency reporting, and optional slow planner recovery.
## Product Guides
diff --git a/docs/guides/minimal-run-coordinator.md b/docs/guides/minimal-run-coordinator.md
index dfa26896..cfe54d37 100644
--- a/docs/guides/minimal-run-coordinator.md
+++ b/docs/guides/minimal-run-coordinator.md
@@ -24,6 +24,8 @@ Donkey also supports a bounded target-window frame source for the dry-run hot-lo
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.
+Donkey also supports the first off-the-shelf local vision evidence boundary inside the dry-run reflex loop. `RecordedOffTheShelfVisionMetadataCodec` can carry recorded detector, template, OCR, or segmentation observations with crop ids, component ids, model ids, confidence, coordinate spaces, and measured preprocessing/model latency. `OffTheShelfVisionPerceptionAdapter` converts that local evidence into compact `HotLoopPerceptionSignal` values, and `OffTheShelfVisionWorldStateProjector` exposes only typed affordances to the deterministic controller. This is a local perception contract and replay path; it does not yet run a live Core ML, ONNX, OCR, or template matcher over captured pixels.
+
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. Allowed non-live commands are projected as dry-run traces, live smoke 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 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`.
@@ -36,10 +38,12 @@ Donkey also supports slow-path planner hint contracts. `StructuredPlannerHint` c
Donkey 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, and failed-model history. 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. Literal provider model ids should stay in registry entries, not planner/controller logic.
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 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 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. Model-proposed memory writes go through a 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 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. `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.
@@ -65,7 +69,7 @@ Donkey supports a runtime-level manual target context capture service that wires
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, deterministic controller, local-navigation dry-run, guarded live-action smoke boundary, slow-planner sidecar, action-engine guardrail, latency-report, planner-hint contract, model-registry/router, provider-neutral AI adapter, memory, replay/eval, target-metadata, single-screenshot artifact, read-only Accessibility snapshot, and manual capture orchestration foundation only. It does not run real vision models or OCR, ship a default OS input backend, perform Accessibility actions, 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, cheap metadata perception, recorded off-the-shelf local vision evidence, deterministic controller, local-navigation dry-run, guarded live-action smoke boundary, slow-planner sidecar, action-engine guardrail, latency-report, planner-hint contract, model-registry/router, OpenAI and Ollama-compatible planner adapters, memory, replay/eval, target-metadata, single-screenshot artifact, read-only Accessibility snapshot, and manual capture orchestration foundation only. It does not run live vision models or OCR over captured pixels, ship a default OS input backend, perform Accessibility actions, provide a manual capture UI, persist high-volume reflex traces to disk, provide continuous streaming capture, or make model calls required for reflex ticks.
## Technical Guidelines
@@ -87,9 +91,9 @@ This is a coordination, in-memory reflex trace, hot-loop contract, deterministic
- 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 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 or recorded-frame metadata, but controllers must only see typed signals, world state, and action affordances.
+- Keep cheap perception deterministic and compact until real pixel/model adapters exist. Perception may summarize fixture metadata or recorded off-the-shelf detector/template/OCR/segmentation evidence, 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, and fallback metadata.
+- 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 default backend does not synthesize OS events.
- Use monotonic timestamps for latency math. Wall-clock timestamps are for human labels and trace correlation only.
@@ -114,7 +118,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, 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, 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 and replay benchmark formatting, planner hint validation/expiry/latest-selection, model registry routing, OpenAI Responses request shaping and failure handling, 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, cheap perception signal projection, recorded off-the-shelf vision evidence projection, 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, 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 and replay benchmark formatting, planner hint validation/expiry/latest-selection, model registry routing, OpenAI Responses request shaping and failure handling, 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.
Manual smoke commands:
@@ -140,6 +144,7 @@ Remaining live verification is environment-dependent. On May 16, 2026, iPhone Mi
- 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`.
- 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`.
- Guarded live-action smoke lives in `apps/Donkey/Sources/DonkeyRuntime/GuardedLiveActionSmoke.swift`.
- Reflex latency reports and synthetic replay benchmarks live in `apps/Donkey/Sources/DonkeyRuntime/ReflexLatencyReport.swift`.
@@ -148,7 +153,8 @@ Remaining live verification is environment-dependent. On May 16, 2026, iPhone Mi
- Local-navigation dry-run frame source, loop adapter, world-state projector, and generic controller wrapper live in `apps/Donkey/Sources/DonkeyRuntime/LocalNavigationDryRunLoop.swift`.
- Slow-planner sidecar triggers, snapshots, validated hint bus, and hint-aware controller wrapper live in `apps/Donkey/Sources/DonkeyRuntime/SlowPlannerSidecar.swift`.
- AI model registry and routing live in `apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift`.
-- The first OpenAI Responses planner-hint adapter lives in `apps/Donkey/Sources/DonkeyAI/OpenAIPlannerHintAdapter.swift`.
+- The OpenAI Responses planner-hint adapter lives in `apps/Donkey/Sources/DonkeyAI/OpenAIPlannerHintAdapter.swift`.
+- The Ollama-compatible local planner-hint adapter and provider-backed slow-planner generator live in `apps/Donkey/Sources/DonkeyAI/OllamaPlannerHintAdapter.swift`.
- Memory contracts live in `apps/Donkey/Sources/DonkeyContracts/MemoryContracts.swift`.
- Short-term run memory and target-memory JSONL storage live in `apps/Donkey/Sources/DonkeyRuntime/RunMemoryStore.swift`.
- Replay/eval scaffolding lives in `apps/Donkey/Sources/DonkeyAI/AIReplayEvaluation.swift`.
diff --git a/plans/01-latency-budget.md b/plans/01-latency-budget.md
index c8f6ffed..894dd470 100644
--- a/plans/01-latency-budget.md
+++ b/plans/01-latency-budget.md
@@ -1,15 +1,36 @@
# 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 a concrete local-model navigation target.
+> 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 reflex loop should complete in under 100ms end to end.
+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 |
@@ -23,6 +44,7 @@ Stretch target: 30-60ms for simple games.
- 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.
@@ -33,11 +55,11 @@ Stretch target: 30-60ms for simple games.
Use a latest-frame-wins design:
```text
-Capture thread
- -> overwrites latest frame buffer
+Observation thread
+ -> overwrites latest app/window/task state
Perception thread
- -> reads latest frame
+ -> reads latest structured observation or latest frame fallback
-> emits latest world state
Controller thread
@@ -70,10 +92,15 @@ Do not preserve every frame if the system falls behind. A real-time agent should
- 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.
-- p50 reflex latency is under 60ms for the first supported target.
-- p95 reflex latency is under 100ms for the first supported target.
+- 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.md
index 841e54ae..a7149c33 100644
--- a/plans/02-capture-and-perception.md
+++ b/plans/02-capture-and-perception.md
@@ -1,28 +1,33 @@
# Capture And Perception
-> Active status: not complete. Current capture/perception support includes target-window frames and metadata perception, but not measured local model/OCR/segmentation perception for a concrete target.
+> 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 screen pixels into a compact world state quickly enough for real-time control.
+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 window or region capture, not whole-desktop capture.
+Start with app/window metadata and Accessibility snapshots. Use window or region capture only when structured app observation is insufficient.
Priority order:
-1. Capture only the game window.
-2. Crop to the gameplay area.
-3. Crop further to regions of interest when possible.
-4. Lower resolution for controller signals.
-5. Keep occasional high-resolution snapshots for the slow planner.
+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
@@ -30,6 +35,9 @@ 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 |
@@ -45,13 +53,13 @@ Keep world state small and typed:
```text
timestamp
+intent_id
scene_id
-player_position
-player_velocity
-targets
-hazards
-resources
-active_menu
+app_id
+task_type
+visible_location
+search_field_state
+result_state
confidence
raw_signals
```
@@ -62,10 +70,10 @@ The controller should consume this state without needing raw pixels.
Per frame:
-1. Read latest captured frame.
-2. Apply crop and downscale.
-3. Run cheap detectors.
-4. Update tracks from previous state.
+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.
@@ -84,18 +92,21 @@ For web targets, slow-path snapshots may include compact DOM summaries alongside
## First Milestones
-1. Capture a selected window at stable frame rate.
-2. Measure capture latency and copy cost.
-3. Build a region cropper.
-4. Add simple object detection for the first supported game.
-5. Emit a world-state JSON event each frame.
-6. Record traces for replay.
-7. Benchmark screenshot-to-model inference on cropped regions.
+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
-- Capture can run at 30 FPS minimum for the first supported target.
-- Perception p95 stays under 50ms.
+- 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.md
index 01a9de89..0c54b3fa 100644
--- a/plans/03-fast-controller.md
+++ b/plans/03-fast-controller.md
@@ -1,22 +1,22 @@
# Fast Controller
-> Active status: not complete. Current controller support is deterministic and traceable for metadata/local-navigation dry-runs, but not yet proven against local model perception for a real target.
+> 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 real-time decisions from world state without waiting on slow reasoning.
+Make local task decisions from typed state without waiting on slow reasoning.
-The fast controller is the agent's reflex system.
+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
-- movement
-- aiming
-- clicking
-- dodging
-- combat reactions
+- app launch/focus decisions
+- search/type/select decisions
+- clicking or Accessibility action selection
- menu navigation
-- repeated game loops
+- repeated app workflows
+- result verification
+- safe fallback and recovery triggers
- emergency recovery actions
## Non-Responsibilities
@@ -41,6 +41,15 @@ World State
-> 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
@@ -59,6 +68,8 @@ The policy selector chooses a small controller:
- `menu_policy`
- `avoidance_policy`
- `recovery_policy`
+- `weather_lookup_policy`
+- `app_search_policy`
Each policy should have a bounded runtime and clear inputs.
@@ -69,6 +80,8 @@ 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 |
@@ -77,6 +90,8 @@ Use the simplest viable method first:
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:
@@ -93,6 +108,7 @@ The slow planner can update:
- 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.
@@ -101,18 +117,20 @@ The fast controller should treat planner output as configuration, not a blocking
- Rate-limit repeated inputs.
- Add maximum hold durations for keys.
- Add emergency input release.
-- Stop acting if the game window loses focus.
+- Stop acting if 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 world-state schema the controller consumes.
-2. Implement deterministic policies for the first supported game.
-3. Add policy-selection logic.
-4. Add confidence-aware fallback behavior.
-5. Record every chosen action with the state snapshot id.
-6. Add detector/OCR/template-derived state inputs.
-7. Replay recorded state traces before live input.
+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
@@ -120,3 +138,4 @@ The fast controller should treat planner output as configuration, not a blocking
- 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.md
index 28692dc6..7b5e2805 100644
--- a/plans/05-action-engine.md
+++ b/plans/05-action-engine.md
@@ -1,16 +1,19 @@
# Action Engine
-> Active status: not complete. Current action-engine support provides guardrails, traces, and injected-backend smoke execution, but not a default live OS input backend with measured input latency.
+> Active status: not complete. Current action-engine support provides guardrails, traces, and injected-backend smoke execution, but not the narrow default macOS app-control backend needed for the first fast-navigation benchmark.
## Goal
-Execute keyboard, mouse, and controller actions with low latency and predictable timing.
+Execute app activation, keyboard, mouse, Accessibility, and controller actions with low latency and predictable timing.
## Responsibilities
+- app launch and activation
- keyboard press/release
+- text entry
- mouse movement
- mouse click/drag
+- Accessibility focus/action when trusted
- controller input, if needed
- action scheduling
- input cancellation
@@ -22,6 +25,7 @@ The controller emits action commands:
```text
press_key(W, duration=40ms)
+type_text("San Francisco")
move_mouse(dx=10, dy=-4)
click(button=left)
tap(x, y)
@@ -29,10 +33,20 @@ swipe(start_x, start_y, end_x, end_y, duration=80ms)
press_button(A, duration=40ms)
set_axis(left_stick_x, 0.5)
release_all()
+launch_app(bundle_id=com.apple.weather)
+activate_app(bundle_id=com.apple.weather)
+perform_accessibility_action(element_id=search-field, action=focus)
```
The action engine translates commands into OS input calls.
+For local app tasks, prefer the safest high-level primitive that works:
+
+1. Launch or activate the target app through the app-control backend.
+2. Use Accessibility focus/actions when trusted and the target element is confidently identified.
+3. Use guarded keyboard text entry for ordinary search text.
+4. Use mouse clicks only when coordinates are derived from typed state and focus guard passes.
+
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).
@@ -44,6 +58,9 @@ For games that support controllers, the action engine should expose a generic ga
- The engine should release all inputs on shutdown or loss of focus.
- The controller should not call OS input APIs directly.
- Every command should be timestamped and traceable.
+- App launch/focus commands must be traceable and covered by tool policy.
+- Text entry must be scoped to the verified focused app/control.
+- Accessibility actions must not run on sensitive or review-required surfaces.
## Mouse Strategy
@@ -63,10 +80,25 @@ Support:
- hold
- chord
- release
+- type text
- rate limit
Movement keys should be represented as desired direction first, then converted to key states. This prevents conflicting commands like left and right being held accidentally.
+For the Weather demo, text entry should be a first-class command so traces can show the normalized entity being typed without exposing unrelated keyboard events.
+
+## App-Control Strategy
+
+Support a narrow macOS backend for the first target:
+
+- launch app by bundle identifier
+- activate/focus app
+- verify frontmost app before input
+- focus a known Accessibility element when available
+- fall back to keyboard shortcut/search only when focus is safe
+
+This backend is intentionally narrower than a general desktop-control agent. Add capabilities only when a task adapter needs them and the guardrails can explain them.
+
## Latency Risks
- OS accessibility/input permission prompts.
@@ -77,15 +109,18 @@ Movement keys should be represented as desired direction first, then converted t
## First Milestones
-1. Choose the input backend per OS.
-2. Build a command interface.
-3. Add input tracing.
-4. Add focus guard.
+1. Add semantic app-control commands for launch, activate, type text, focus element, click/select, and verify.
+2. Implement a narrow macOS backend for Weather behind existing guardrails.
+3. Add input and app-control tracing.
+4. Add focus guard for target app and target control.
5. Add emergency release.
-6. Calibrate mouse movement for the first supported target.
+6. Measure command-to-input latency for Weather lookup.
+7. Calibrate mouse movement only if Accessibility/keyboard control is insufficient.
## Acceptance Criteria
- Input execution p95 is under 5ms after command creation.
+- App launch/focus and text-entry latency are measured separately.
- All held inputs release on stop.
- Commands can be replayed from a trace.
+- Weather lookup live input cannot run unless the Weather app/control is verified safe.
diff --git a/plans/06-benchmarking.md b/plans/06-benchmarking.md
index e5a4003c..5c530ed9 100644
--- a/plans/06-benchmarking.md
+++ b/plans/06-benchmarking.md
@@ -1,6 +1,6 @@
# Benchmarking And Monitoring
-> Active status: not complete. Current benchmark support can summarize dry-run traces, but not persistent cross-run trends or concrete local-model target baselines.
+> 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.
## Goal
@@ -8,6 +8,15 @@ Make latency visible, measurable, and hard to accidentally regress.
No latency claim counts unless it is measured.
+The first benchmark target is the user-facing Weather navigation task:
+
+```text
+"show me the weather for SF"
+ -> Weather app visible with San Francisco verified
+```
+
+This must be compared against a manual baseline on the same machine so the product claim is honest: local navigation should be faster than doing the navigation by hand, or the report should show which stage prevents that.
+
The project needs two observability loops:
- local measurement while building and tuning the agent
@@ -17,6 +26,12 @@ The project needs two observability loops:
Per 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
@@ -30,6 +45,9 @@ Per loop:
- controller end timestamp
- input command timestamp
- input execution timestamp
+- verification start timestamp
+- verification end timestamp
+- command-to-result timestamp
- frame age when perception begins
- state age when controller begins
- action age when input executes
@@ -43,6 +61,11 @@ Aggregate:
- stale actions
- planner calls
- 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
@@ -73,6 +96,16 @@ Every trace event should include:
There are three levels of latency to measure.
+### Command-To-Result Latency
+
+This is the product-feel number for local app tasks.
+
+```text
+user command accepted -> intent parsed -> app focused -> input executed -> result verified
+```
+
+For Weather lookup, report both cold-start and warm-app numbers. Compare against a manual run where the operator opens Weather, searches for San Francisco, and confirms the result.
+
### Internal Software Latency
This is the time from captured frame to input command execution inside the agent.
@@ -110,6 +143,12 @@ Add tiny timestamp spans around every hot-path boundary:
```text
capture.start
capture.end
+intent_parse.start
+intent_parse.end
+app_focus.start
+app_focus.end
+app_observation.start
+app_observation.end
preprocess.start
preprocess.end
model.start
@@ -121,6 +160,8 @@ controller.start
controller.end
action.enqueue
input.execute
+verification.start
+verification.end
```
Each span should be cheap enough to leave on all the time. Avoid synchronous disk writes in the frame loop. Buffer trace events in memory and flush from a background worker.
@@ -131,12 +172,17 @@ Reports should show both total latency and stage latency:
| Metric | Definition |
| --- | --- |
+| intent_parse_ms | `intent_parse.end - intent_parse.start` |
+| app_focus_ms | `app_focus.end - app_focus.start` |
+| app_observation_ms | `app_observation.end - app_observation.start` |
| capture_ms | `capture.end - capture.start` |
| preprocess_ms | `preprocess.end - preprocess.start` |
| model_inference_ms | `model.end - model.start` |
| perception_ms | `perception.end - perception.start` |
| decision_ms | `controller.end - controller.start` |
| input_ms | `input.execute - action.enqueue` |
+| verification_ms | `verification.end - verification.start` |
+| command_to_result_ms | `verification.end - command.accepted` |
| software_loop_ms | `input.execute - capture.end` |
| frame_age_ms | `controller.start - capture.end` |
| state_age_ms | `input.execute - state.publish` |
@@ -149,6 +195,7 @@ Every reflex action should be traceable:
```text
trace_id
+intent_id
frame_id
state_id
action_id
@@ -170,6 +217,7 @@ build_id
5. End-to-end live run with input enabled.
6. Synthetic reflex test with a controlled visual stimulus.
7. Long soak test for drift, throttling, and memory growth.
+8. Weather command-to-result benchmark, with cold-start, warm-app, and manual-baseline modes.
## Monitoring Over Time
@@ -225,6 +273,7 @@ Later, add a lightweight local dashboard with:
Alert on symptoms that matter to feel:
- p95 end-to-end 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
- stale action rate over 2%
- dropped frame rate over 5%
@@ -241,12 +290,19 @@ Alerts should include the stage that regressed, the previous baseline, and the w
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-result p95 faster than the manual Weather baseline or explicitly flagged
+
+For later visual targets:
+
- capture p95 under 15ms
- perception p95 under 50ms
- screenshot preprocessing plus model inference p95 under 50ms
-- controller p95 under 20ms
-- action execution p95 under 5ms
-- end-to-end p95 under 100ms
+- end-to-end visual reflex p95 under 100ms
Use both absolute and comparative gates:
diff --git a/plans/19-ai-harness.md b/plans/19-ai-harness.md
index 84748f1a..5696ee12 100644
--- a/plans/19-ai-harness.md
+++ b/plans/19-ai-harness.md
@@ -1,25 +1,25 @@
# AI Harness
-> Active status: not complete. The current repo has OpenAI adapter scaffolding, model routing, memory scaffolding, and an optional slow-planner sidecar, but it does not yet provide a complete slow loop that can use both local and online LLM providers.
+> Active status: not complete. The current repo now has OpenAI and Ollama-compatible planner adapters, model routing, memory scaffolding, and a provider-backed slow-planner generator, but 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 planner output, and keeps model choices updateable without touching the low-latency reflex loop.
+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 planning, recovery, trace explanation, model-assisted perception setup, and long-running improvement. It does not drive frame-by-frame gameplay.
+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 reflex loop.
+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
-Capture / Perception / Controller / Action
+Intent / Observation / Controller / Action
-> local, bounded, latest-frame-wins
AI Harness
- -> async, slow-path, memory-backed, validated output
+ -> 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.
@@ -28,11 +28,13 @@ If the harness is slow, offline, rate-limited, or wrong, the controller continue
- connect to model providers
- choose the right model for each slow-path job
+- 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
@@ -42,6 +44,7 @@ If the harness is slow, offline, rate-limited, or wrong, the controller continue
- 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
@@ -56,6 +59,7 @@ User Goal
Target Adapter
Screenshots / DOM Summary
-> Snapshot Builder
+ -> Intent Parser / Intent Validator
-> Memory Retriever
-> Model Router
-> Provider Adapter
@@ -65,7 +69,39 @@ Screenshots / DOM Summary
-> Trace / Metrics Sink
```
-The harness should be a sidecar service or worker owned by the agent runtime. It reads snapshots and emits typed outputs. It should not own capture, input, or the controller tick.
+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
@@ -311,13 +347,14 @@ Do not hardcode one model everywhere. Assign models by role.
| Role | Default Candidate | Use |
| --- | --- | --- |
+| `intent_local` | deterministic parser, then small local model if needed | common command-to-intent parsing before local app execution |
| `planner_default` | `gpt-5.4-mini` | routine slow planning, recovery hints, target reasoning |
| `planner_strong` | `gpt-5.5` | hard recovery, unfamiliar screens, complex strategy, plan generation |
| `planner_deep_eval` | `gpt-5.5-pro` | offline trace critique or high-value evaluation only |
| `planner_cheap` | `gpt-5.4-nano` | simple classification, short summaries, routing decisions |
-| `planner_local` | Qwen3 8B, Phi-family, or Gemma 3 through Ollama/vLLM/llama.cpp | local reasoning/dialogue/UI understanding outside the reflex loop |
-| `vision_local_slow` | Gemma 3 or PaliGemma candidate | local multimodal UI understanding outside the reflex loop |
-| `vision_snapshot` | `gpt-5.4-mini` or `gpt-5.5` | occasional screenshot understanding outside the reflex loop |
+| `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 |
@@ -329,6 +366,12 @@ Current OpenAI docs list GPT-5.5 as the flagship model for complex coding/profes
Route by job type, risk, latency tolerance, and failure history.
```text
+if deterministic intent parser can resolve the command:
+ skip model call
+
+if job is common app intent disambiguation and local model is available:
+ prefer intent_local or planner_local with a strict timeout
+
if job is hot_path:
reject remote model call
reject general chat LLM call unless a measured specialized local model meets the budget
@@ -365,7 +408,22 @@ prompt_version
## Structured Planner Output
-The harness should emit controller hints, not prose.
+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
@@ -573,23 +631,28 @@ The harness should degrade quietly and visibly.
## First Milestones
-1. Define model registry schema and role names.
-2. Build the OpenAI Responses provider adapter.
-3. Add one structured planner hint schema.
-4. Build short-term run memory and target memory as JSONL files.
-5. Add text embedding support for semantic memory.
-6. Add snapshot builder with screenshot/DOM redaction hooks.
-7. Add model router with default, cheap, strong, and fallback roles.
-8. Add optional Ollama provider support for local slow-path planning.
-9. Add memory write proposals with deterministic approval.
-10. Add trace events for model calls and memory operations.
-11. Add a replay/eval command for model and prompt changes.
-12. Add a model update checklist that writes `last_verified_at` and docs URLs.
+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 reflex-loop trace.
+- 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.
@@ -604,19 +667,20 @@ The AI harness foundation now supports the optional slow-path sidecar pieces nee
- 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 slow-loop AI. The current `AIModelProvider` supports only OpenAI, and the sidecar consumes an injected `SlowPlannerHintGenerating` implementation instead of owning a provider-backed local/online planner 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 local/Ollama slow-planner providers behind the same hint-generation boundary.
-- Wire the slow planner loop so it can route to local and online providers, apply timeout/failure policy, and publish only validated hints.
+- 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.md
index c269c8a8..26830e49 100644
--- a/plans/20-off-the-shelf-run-loop.md
+++ b/plans/20-off-the-shelf-run-loop.md
@@ -1,29 +1,34 @@
# Off-The-Shelf Run Loop
-> Active status: not complete. The current repo supports metadata-only local-navigation dry-run scaffolding and guarded live-action smoke, but not fast local navigation using local detector/OCR/segmentation/model inference for a concrete target.
+> Active status: not complete. The current repo supports metadata-only local-navigation dry-run scaffolding and guarded live-action smoke, but not a live fast-navigation agent for a concrete command such as "show me the weather for SF".
## Goal
-Build the first real-time game assistant from existing components instead of custom model work.
+Build the first fast local navigation agent from existing system components instead of custom model work.
-Use LLMs, open-vocabulary detectors, Segment Anything-style models, OCR, templates, classical CV, and deterministic controllers. The system should be useful before any custom model work exists.
+The first product proof is a local Weather lookup navigation benchmark. Donkey should interpret a natural command, use local macOS navigation to open or focus Weather, type/search for San Francisco, verify the app is showing the requested place, and leave the result visible. It should feel faster than manual app navigation or a chat assistant because most work is local and deterministic.
+
+Fast navigation is the focus across apps and games. Use Accessibility, app/window metadata, LaunchServices, keyboard input, screenshot/OCR fallback, open-vocabulary detectors, segmentation, templates, and classical CV as swappable navigation signals. Start with the cheapest local signal that can reliably move the target toward the requested state.
## Target Shape
```text
-Screen Capture
- -> Crop / Normalize
- -> Off-The-Shelf Vision
- -> Game State
- -> Deterministic Controller
+User Command
+ -> Intent Parser
+ -> Task Adapter
+ -> App Launch / Focus
+ -> Accessibility / Window Metadata / Screenshot Fallback
+ -> Task State
+ -> Deterministic UI Controller
-> Action Engine
- -> Mouse / Keyboard / Controller
+ -> Keyboard / Mouse / Accessibility Action
+ -> Result Verification
Reasoning LLM
- <-> Goals / Hints / UI Understanding / Memory / Recovery
+ <-> Ambiguous Intent / UI Understanding / Memory / Recovery
```
-The hot loop is still local and bounded. The LLM can reason beside it, but action timing comes from deterministic logic over structured state.
+The hot path is local and bounded. A small model can help interpret unusual phrasing, but app navigation and action timing come from deterministic logic over structured state.
## Core Rule
@@ -31,21 +36,31 @@ Do not build a custom model pipeline for the first version.
The first version should prove:
-- capture is reliable
-- perception can extract useful state from off-the-shelf models
+- command-to-intent parsing is reliable for common tasks
+- macOS app launch/focus is reliable
+- Accessibility/window metadata can extract useful app state
+- screenshot/OCR fallback is available only when needed
- state is compact and timestamped
- controller rules can act on that state
+- guarded live input can type/search safely
+- result verification can confirm the requested target
- latency is measured end to end
-- the LLM can help with strategy and recovery without blocking the loop
+- the LLM can help with ambiguous phrasing and recovery without blocking local navigation
## Hot-Path Components
Use existing, swappable components:
+- deterministic intent parser for common local commands
+- small local model or planner hint only for ambiguous command parsing
+- target/task adapters for app-specific workflows
+- LaunchServices or Workspace app launch/focus
+- Accessibility snapshots/actions for app UI state and controls
+- keyboard/mouse input behind guardrails
+- template matching or OCR for UI fallback
- YOLO-family detector for boxes, UI elements, enemies, objects, and markers
- SAM / SAM2 / MobileSAM / FastSAM for masks when boxes are not enough
-- OCR for text, scores, labels, and menus
-- template matching for stable UI buttons and icons
+- OCR for text, labels, and menus when Accessibility is insufficient
- color/edge/motion heuristics for simple fast signals
- deterministic state machines for action decisions
- LLM planner only for slow hints and recovery
@@ -57,6 +72,7 @@ Avoid:
- custom neural networks
- full LLM decision-making every frame
- Ollama or any chat LLM in the per-frame action path
+- remote model calls for common app-command execution
- Python pixel loops in the hot path
- generic agent frameworks around every frame
@@ -90,12 +106,14 @@ Wrap the low-latency loop in an OpenClaw-inspired runtime shell, but do not make
The product loop should look like:
```text
-intake
+intake / local intent parse
-> session queue
-> context assembly
- -> local perception / model inference
+ -> task adapter selection
+ -> local app observation
-> deterministic controller
-> tool / action execution
+ -> result verification
-> streaming events
-> transcript / trace persistence
-> compaction / recovery
@@ -103,7 +121,29 @@ intake
The runtime shell owns coordination. It loads target adapters and skills, resolves model/auth/runtime profiles, subscribes to model/tool/reflex events, enforces queue sizes and deadlines, applies tool permission policy, and bridges events back to UI or client streams.
-The runtime shell does not own per-frame perception logic, controller policy internals, or direct OS input. Those stay behind explicit capture, perception, controller, and action-engine interfaces.
+The runtime shell does not own app-specific workflow internals, perception logic, controller policy internals, or direct OS input. Those stay behind explicit intent, task-adapter, capture/perception, controller, and action-engine interfaces.
+
+### First Benchmark: Weather Lookup
+
+The first supported benchmark is:
+
+```text
+"show me the weather for SF"
+ -> weather_lookup(city: "San Francisco")
+ -> open/focus Weather
+ -> search/select San Francisco
+ -> verify displayed location
+```
+
+The first navigation adapter should support:
+
+- deterministic alias expansion for common city shorthand such as `SF`
+- dry-run trace output before live input
+- app launch/focus through a narrow macOS app-control boundary
+- observation through Accessibility first, window metadata second, screenshot/OCR fallback last
+- guarded text entry into the Weather search field
+- verification that the visible Weather location matches San Francisco
+- terminal result states: completed, needs-user-review, failed-safe, timed-out
### Event Bridge
@@ -185,6 +225,8 @@ Define these contracts before the first production coordinator implementation:
- `RunSession`: user goal, target id, runtime profile, permission scope, lifecycle state
- `RunEvent`: assistant/tool/lifecycle/reflex event envelope with trace ids
+- `TaskIntent`: parsed local app task, normalized entities, confidence, parser source
+- `TaskAdapter`: app-specific observation, action selection, verification, and recovery hooks
- `ToolCallPolicy`: allow, deny, or ask rules for capture, Accessibility, model, and input actions
- `TranscriptStore` / `TraceStore`: append-only persistence with a single writer or explicit lock
- `ContextAssembler`: compact planner context from world state, traces, memory, screenshots, and user goal
@@ -207,22 +249,24 @@ Use TensorRT first on NVIDIA if the model exports cleanly and p95 latency improv
### macOS
-Best default for iPhone Mirroring and Mac app control:
+Best default for local app task control:
```text
-ScreenCaptureKit
- -> IOSurface / CVPixelBuffer
- -> Core ML / Metal / ONNX Runtime CoreML EP
- -> synthetic input with Accessibility focus guard
+Natural command
+ -> deterministic/local intent parser
+ -> NSWorkspace/LaunchServices app activation
+ -> Accessibility tree/action when trusted
+ -> guarded keyboard/mouse fallback
+ -> ScreenCaptureKit/OCR only for missing UI facts
```
-Use Accessibility for window bounds, focus checks, dialogs, and setup flows. Use screenshot perception for the mirrored game content.
+Use Accessibility for window bounds, focus checks, controls, dialogs, and setup flows. Use screenshot perception only when the app does not expose the needed state through Accessibility.
## Vision Options
### Detector First
-Start with a detector when the game state can be represented as objects.
+For later visual targets, start with a detector when the target state can be represented as objects.
Good jobs:
@@ -280,22 +324,22 @@ Use simple methods when they work:
These are often faster and easier to debug than a model.
-## Game State
+## Task State
-Convert all perception outputs into a compact state object:
+Convert all observation outputs into a compact state object:
```text
state_id
frame_id
timestamp
target_id
+task_intent_id
+app_id
scene_type
objects
masks
text
ui_flags
-player_state
-hazards
action_affordances
confidence
source_ages
@@ -310,12 +354,26 @@ Rules:
- do not expose detector tensors or raw masks directly to the controller
- prefer task-specific state over generic scene captions
+For the Weather target, state should include:
+
+```text
+app_running
+app_frontmost
+search_field_available
+search_text
+selected_location
+visible_location
+weather_result_visible
+confidence
+verification_reason
+```
+
## Controller
-Use deterministic logic over game state:
+Use deterministic logic over task state:
```text
-Game State
+Task State
-> Policy Selector
-> Rule / State Machine
-> Semantic Action
@@ -324,6 +382,11 @@ Game State
Examples:
+- Weather not running -> launch app
+- Weather running but not focused -> focus app
+- search field visible and empty -> type normalized city
+- matching location suggestion visible -> select suggestion
+- visible location matches normalized city -> complete
- obstacle on left lane -> move center/right
- button visible and safe -> tap button center
- health low -> request planner recovery hint
@@ -337,6 +400,7 @@ The controller should be boring, inspectable, and traceable.
Use LLMs for:
+- interpreting ambiguous commands when deterministic intent parsing is insufficient
- interpreting unfamiliar screens
- choosing objectives
- explaining failures
@@ -348,6 +412,9 @@ Use LLMs for:
Do not use LLMs for:
+- launching apps
+- typing ordinary search text
+- clicking known controls
- aiming every frame
- dodge timing
- tap/swipe timing
@@ -356,56 +423,62 @@ Do not use LLMs for:
LLM output must become validated hints, not direct actions.
-## First Supported Target Recommendation
+## First Supported Benchmark Recommendation
+
+Pick one navigation scenario with a visible, verifiable end state.
+
+The first benchmark is Weather lookup:
-Pick one game and one task.
+- command: "show me the weather for SF"
+- normalized intent: `weather_lookup(city: "San Francisco")`
+- target app: Weather
+- success: Weather is frontmost and visibly showing San Francisco weather
-Good first tasks:
+Good follow-on tasks:
-- dodge obstacles from detected lanes/hazards
-- tap a button when a visual condition appears
-- navigate a repeated menu
-- collect visible items
-- use OCR to react to a countdown or label
+- fast game/menu navigation to a known screen
+- open Calendar to a named date
+- search Mail for a sender
+- create a short Notes note
+- open a browser tab to a known site
+- navigate a repeated game menu
Suggested first stack:
```text
-Capture: ScreenCaptureKit for iPhone Mirroring, DXGI for Windows
-Detector: YOLO-family nano/small model
-Segmentation: MobileSAM or FastSAM as optional fallback
-OCR: cropped-region OCR
-Rules: deterministic state machine
-Inference: ONNX Runtime, TensorRT, Core ML, or DirectML depending on platform
-Reasoning: OpenAI Responses API or local Qwen/Phi/Gemma in a separate slow path
-IPC: latest-frame-wins shared buffer
-Runtime: native core where the hot path needs it
+Intent: deterministic parser with local-model fallback for ambiguity
+App control: NSWorkspace/LaunchServices activation
+Observation: Accessibility snapshot first, screenshot/OCR fallback
+Rules: deterministic Weather task state machine
+Input: guarded keyboard/mouse or Accessibility action backend
+Reasoning: local/online planner only for recovery or ambiguity
+Runtime: native Swift coordinator and trace pipeline
```
## Rollout
-1. Choose one target and one behavior.
-2. Define the state fields needed for that behavior.
-3. Capture the target window and crop to the gameplay/content area.
-4. Add one off-the-shelf detector or template signal.
-5. Add one deterministic rule that emits a safe semantic action.
-6. Add action calibration and focus guard.
-7. Add a minimal Swift runtime coordinator around `DonkeyRuntime`.
-8. Use `OffTheShelfRunLoopBoundary` as the first status/event boundary.
-9. Add session queue, lifecycle state, permission policy, and abort handling.
-10. Add trace logging and latency report.
-11. Add optional segmentation only if detection/templates fail.
-12. Add OCR only for text-dependent screens.
-13. Add slow LLM recovery after the reflex loop works.
-14. Add transcript compaction and memory writes only after planner hints are useful.
+1. Define `TaskIntent` for `weather_lookup`.
+2. Add deterministic parsing for "weather", city names, and common aliases such as `SF`.
+3. Define Weather task-state fields and terminal states.
+4. Add a Weather navigation adapter with dry-run semantic actions.
+5. Add app launch/focus action commands and guardrails.
+6. Add guarded text-entry and submit/select commands.
+7. Add Accessibility observation for Weather controls and visible location.
+8. Add screenshot/OCR fallback only where Accessibility is insufficient.
+9. Add result verification for San Francisco.
+10. Add command-to-result latency report and manual baseline comparison.
+11. Add optional slow planner recovery only after deterministic execution works.
+12. Keep game/vision adapters as follow-on targets using the same contracts.
## Acceptance Criteria
- No custom model work is required.
- The hot loop can run with the LLM disabled.
+- The Weather lookup navigation benchmark can run without a remote model call.
- Every perception component is swappable.
- Every action is explainable from state, rule, and trace id.
-- p95 reflex latency stays under the target budget.
+- p95 local navigation/action latency stays under the target budget.
+- command-to-result latency is measured against a manual baseline.
- LLM output is validated before it changes controller configuration.
- Segmentation and OCR are cropped and measured before live use.
- The runtime coordinator can start, pause, abort, timeout, and complete a run.
@@ -422,6 +495,7 @@ The runtime foundation now supports a product-shaped local-navigation slice of t
- typed reflex trace records with capture, preprocessing, model, perception, state, controller, action, and input timestamps
- bounded target-window frame capture for dry-run frames without PNG/JPEG hot-path encoding
- cheap metadata perception and swappable world-state projection
+- recorded off-the-shelf detector/template/OCR/segmentation evidence projection with crop ids, model/component ids, confidence, coordinate spaces, and measured preprocessing/model latency
- loop-integrated metadata-only local-navigation dry-run selection with optional browser-tab metadata
- latest-frame-wins queue depth 1 with dropped-frame counting
- p50/p95/p99 latency reports across capture, preprocess, model, perception, state update, controller decision, action projection, and input stages
@@ -429,14 +503,15 @@ The runtime foundation now supports a product-shaped local-navigation slice of t
- guarded live-action smoke through an injected backend only after dry-run latency evidence, explicit input policy allowance, and focus guard success
- optional slow-planner sidecar that publishes only validated hints without blocking reflex latency
-This is still not the full off-the-shelf vision stack and must not be treated as completion. It does not ship real local detector/OCR/segmentation/model adapters, continuous streaming capture, a default OS input backend, high-volume persisted replay traces, or target-specific visual calibration.
+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, but it does not ship live local detector/OCR/segmentation/model adapters over captured pixels, continuous streaming capture, a default OS input backend, high-volume persisted replay traces, or target-specific visual calibration.
## Required Before This Plan Is Done
-- Add measured local detector/template/OCR/segmentation adapters for a real visual target.
-- Prove fast local navigation from local perception/model output, not only macOS window metadata or supplied browser-tab metadata.
+- Add a measured Weather lookup navigation adapter for the concrete 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 a default narrow macOS app-control backend for launch/focus/type/select/verify with focus guard and emergency release.
+- Add result verification through Accessibility or screenshot/OCR fallback.
- Add continuous streaming capture once queue-depth, stale-result, and trace sinks are ready for longer sessions.
-- Add a real macOS input backend behind the existing guardrails only after manual operator safety review.
- Add durable high-volume replay trace persistence and target-specific benchmark baselines.
- Keep segmentation/OCR optional and introduce them only with cropped, measured, target-specific evidence.
diff --git a/plans/done/00-overview.md b/plans/done/00-overview.md
index da73c3a5..13f912cd 100644
--- a/plans/done/00-overview.md
+++ b/plans/done/00-overview.md
@@ -67,7 +67,7 @@ Every frame should use local, bounded-cost logic:
- [../01-latency-budget.md](../01-latency-budget.md): hard timing budget and optimization priorities
- [../02-capture-and-perception.md](../02-capture-and-perception.md): screen capture, visual parsing, and world-state updates
- [../03-fast-controller.md](../03-fast-controller.md): real-time controller design
-- [../04-slow-planner.md](../04-slow-planner.md): slow strategy, recovery, and goal-setting layer
+- [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
- [07-rollout.md](07-rollout.md): phased delivery path from first supported target to production readiness
diff --git a/plans/04-slow-planner.md b/plans/done/04-slow-planner.md
similarity index 67%
rename from plans/04-slow-planner.md
rename to plans/done/04-slow-planner.md
index 0933cf00..44c2095f 100644
--- a/plans/04-slow-planner.md
+++ b/plans/done/04-slow-planner.md
@@ -1,6 +1,6 @@
# Slow Planner
-> Active status: not complete. Current slow-planner support includes snapshots, validation, and hint bus scaffolding, but not a provider-backed local/online LLM planner loop.
+> Completed status: the slow planner has trigger rules, compact snapshots, validated hint publication, provider-backed local/online planner hint generation, and tests showing planner latency does not affect reflex p95.
## Goal
@@ -94,3 +94,11 @@ If the planner is slow, unavailable, or wrong:
- Planner latency does not affect p95 reflex latency.
- Controller can run for at least 30 seconds without planner output.
- Planner output is validated before it reaches the controller.
+
+## Completion Notes
+
+- `DryRunSlowPlannerSidecar` triggers beside the dry-run reflex loop and builds compact snapshots from world state, action, trace summaries, screenshots, and memory.
+- `ProviderBackedSlowPlannerHintGenerator` can try a local Ollama-compatible provider and fall back to OpenAI through the same structured planner-hint schema.
+- `ValidatedPlannerHintBus` rejects invalid or unsafe hints before controller publication.
+- `PlannerHintAwareControllerPolicy` exposes the latest validated hint as metadata, not direct input.
+- Tests cover snapshot construction, invalid-hint rejection, hint-aware controller metadata, 30 simulated seconds without planner output, provider fallback, and reflex p95 isolation from planner latency.
diff --git a/plans/master-plan.md b/plans/master-plan.md
index 60fc0c10..1e7e2041 100644
--- a/plans/master-plan.md
+++ b/plans/master-plan.md
@@ -1,6 +1,8 @@
-# Real-Time Run Loop And AI Harness Master Plan
+# Fast Local Navigation Agent Master Plan
-This is the active task queue again. A past archive commit closed this roadmap too early: the repo has a useful dry-run/local-navigation scaffold and slow-planner sidecar pieces, but the critical features are not complete yet.
+This is the active task queue. The milestone is focused on fast local navigation: Donkey should turn a short user command into structured intent, navigate the local desktop/app surface quickly, perform guarded local actions, verify the result, and leave the target in the requested state.
+
+Weather lookup is the first simple benchmark scenario for this navigation engine: when the user says something like "show me the weather for SF", Donkey should open or focus Weather, type/search for San Francisco, verify the result, and present it. The same loop should later generalize to faster game/app navigation where local observation and deterministic control matter more than chat reasoning.
Primary plans:
@@ -12,10 +14,13 @@ Supporting plans:
- `plans/01-latency-budget.md`
- `plans/02-capture-and-perception.md`
- `plans/03-fast-controller.md`
-- `plans/04-slow-planner.md`
- `plans/05-action-engine.md`
- `plans/06-benchmarking.md`
+Completed supporting plans:
+
+- `plans/done/04-slow-planner.md`
+
Supported behavior and engineering guidance belong in `docs/guides/`. This file tracks what is still needed before those active plans can move to `plans/done/`.
## Plan Management Note
@@ -24,18 +29,21 @@ Keep this queue grounded in code reality. Move a plan to `plans/done/` only afte
## Milestone Goal
-Build the first product-shaped loop where Donkey can run a local navigation session with bounded reflex behavior and an optional slow AI sidecar:
+Build the first product-shaped loop where Donkey can run a local navigation session with bounded local execution and an optional slow AI sidecar:
```text
-local desktop/window/browser context
- -> focused capture / Accessibility / browser-tab metadata
- -> local perception or cheap metadata/template signal
- -> compact world state
- -> deterministic navigation controller
- -> dry-run action trace first, guarded live action later
+user command: "show me the weather for SF"
+ -> local intent parse: weather_lookup(city: "San Francisco")
+ -> app/task adapter: Weather
+ -> launch or focus app
+ -> observe app state through Accessibility/window metadata/screenshot fallback
+ -> deterministic UI controller
+ -> guarded keyboard/mouse/Accessibility action execution
+ -> verify Weather is showing San Francisco
-> latency report and replayable trace
slow AI harness
+ -> ambiguous-command parse or recovery only
-> compact snapshot
-> model router
-> structured planner hint
@@ -43,19 +51,20 @@ slow AI harness
-> scoped memory proposal
```
-The hot path must continue to work with the AI harness disabled.
+The normal Weather benchmark path should work without a remote model call. A tiny local parser or local slow-model call may help turn the command into structured intent, but navigation, typing, verification, and input must stay local and deterministic.
## Supported Boundary
- Runtime shell: minimal run coordination, ordered events, bounded context assembly, local run artifacts, manual target context capture, in-memory reflex trace retention, and stage-split latency reports are supported.
-- Reflex hot path: typed frame/world-state/action contracts, deterministic dry-run loop, bounded target-window frame source, cheap metadata perception, swappable world-state projection, deterministic controller, loop-integrated metadata-only local-navigation dry-run action selection, optional caller-supplied browser-tab metadata, and dry-run action projection are supported. This is not yet fast local navigation using local vision/model inference.
-- Safety boundary: action-engine command contracts, permission/focus/rate/hold/release guardrails, guarded live-action smoke with an injected backend, and replayable command traces are supported before any default OS input backend exists.
-- Slow AI boundary: structured planner hints, validation/expiry/latest-valid selection, loop-adjacent slow-planner trigger/snapshot sidecar, model registry/router, an OpenAI Responses structured-output adapter, source-linked memory, and replay/eval scaffolding are supported as optional sidecar pieces. This is not yet a complete slow loop using both local and online LLM providers.
+- Fast navigation hot path: typed frame/world-state/action contracts, deterministic dry-run loop, bounded target-window frame source, cheap metadata perception, recorded off-the-shelf detector/template/OCR/segmentation evidence projection, swappable world-state projection, deterministic controller, loop-integrated metadata-only local-navigation dry-run action selection, optional caller-supplied browser-tab metadata, and dry-run action projection are supported. This is not yet a live fast-navigation agent: there is no Weather benchmark adapter, no default app launch/focus/type backend, and no verified command-to-result loop.
+- Safety boundary: action-engine command contracts, permission/focus/rate/hold/release guardrails, guarded live-action smoke with an injected backend, and replayable command traces are supported before any default OS input or Accessibility-action backend exists.
+- Slow AI boundary: structured planner hints, validation/expiry/latest-valid selection, loop-adjacent slow-planner trigger/snapshot sidecar, model registry/router, OpenAI Responses and Ollama-compatible planner adapters, provider-backed local/online planner fallback, source-linked memory, and replay/eval scaffolding are supported as optional sidecar pieces. This is not yet the complete AI harness because semantic retrieval, redaction, aggregate model observability, and provider-decoded memory write proposals remain active.
- Source of truth: detailed supported behavior lives in `docs/guides/minimal-run-coordinator.md`; active unfinished work lives in this plan and its primary/supporting plans.
## Non-Negotiable Rules
- No remote model call, chat LLM call, or general VLM call may be required for a reflex tick.
+- Common app commands must prefer deterministic or local intent parsing before remote planning.
- The reflex path uses latest-frame-wins queues; stale frames are dropped and counted.
- The controller consumes typed world state, not raw screenshots.
- The action engine owns OS input; controller policies emit semantic commands only.
@@ -71,24 +80,27 @@ Recent commits completed these pieces:
- `9b160f8` and `201e76c`: metadata-only local-navigation dry-run, local-navigation controller contracts, memory/replay scaffolding.
- `0e21088`: OpenAI Responses adapter, planner hint contracts, model registry/router scaffolding.
- `9bebfbb`: slow-planner sidecar trigger/snapshot/hint bus and guarded live-action smoke boundary.
+- current working slice: Ollama-compatible local planner adapter, provider-backed local/online slow planner fallback, and explicit slow-planner completion tests.
- `d6e48c9`: archived plans, which was premature for this milestone.
-The code does not yet include local detector/OCR/segmentation/model inference adapters, continuous local-model navigation, a default OS input backend, a local LLM provider, or a provider-backed slow planner loop that can choose between local and online models.
+The code does not yet include a Weather benchmark adapter, command-to-intent parsing for navigation tasks, default app launch/focus/type execution, Accessibility action execution, live result verification, local detector/OCR/segmentation/model inference adapters, semantic memory retrieval, remote-input redaction hooks, aggregate model observability, or provider-decoded memory write proposals.
## What Should Be Done Next
-1. Implement fast local navigation with local perception/model evidence, not only window/browser metadata.
-2. Implement a slow planner loop that can call both an online provider and a local provider behind the same validated hint boundary.
-3. Add benchmark/reporting evidence that local perception, controller, action projection, and input stages meet the target p95 budgets for a concrete target.
-4. Keep the current dry-run/guarded-live safety boundary: local or online LLM output can only become validated hints, never direct input.
+1. Add a `weather_lookup` intent contract and parser as the first fast-navigation benchmark, including deterministic aliases such as `SF -> San Francisco`.
+2. Add a Weather navigation adapter that can dry-run and then guarded-live: launch/focus Weather, find the search affordance, type the city, submit/select, and verify the displayed location.
+3. Add the default local action backend needed for this narrow task: app launch/activation plus guarded keyboard typing/clicking or Accessibility actions, with emergency release and focus checks.
+4. Add benchmark/reporting evidence for command-to-result latency, local navigation/action latency, verification confidence, and comparison against manual/chat-style workflows.
+5. Keep the current dry-run/guarded-live safety boundary: local or online LLM output can only become validated intent or planner hints, never direct input.
## Completion Gates
Do not move the primary/supporting plans back to `plans/done/` until:
-- Fast local navigation runs from local model/perception output for at least one concrete target, with no remote model dependency in the reflex trace.
-- The slow loop can generate validated planner hints through an online LLM provider and a local LLM provider, with strict timeout/failure behavior.
+- The fast-navigation agent can run from "show me the weather for SF" to a verified Weather app result with no remote model dependency in the execution trace.
+- Dry-run traces and guarded live traces explain intent parsing, app launch/focus, observation, selected rule, input/backend calls, verification, and guardrail decisions.
+- The task is measurably faster than a documented manual baseline on the same machine, or the report clearly identifies which stage prevents that.
+- The broader AI harness can retrieve bounded semantic memory, redact remote-bound visual/DOM context, aggregate model-call observability, and route provider-decoded memory proposals through deterministic approval.
- The hot loop continues to run when the slow AI harness is disabled or failing.
-- p50/p95/p99 reports cover capture, preprocessing, local model inference/perception, state update, controller, action projection, and input.
-- Action traces can explain state, model/perception evidence, selected rule, validated hint influence, and guardrail decisions.
+- p50/p95/p99 reports cover intent parse, app launch/focus, observation, controller decision, action projection, input execution, result verification, and any capture/perception fallback.
- The relevant guide in `docs/guides/` documents the supported behavior and boundaries.