Skip to content

Open source CapCut alternative.

TypeScript

Document slow-path AI harness and trim master plan

David Le0e210887d8d5
diff --git a/apps/Donkey/Package.swift b/apps/Donkey/Package.swift
index b0cad930..983c568f 100644
--- a/apps/Donkey/Package.swift
+++ b/apps/Donkey/Package.swift
@@ -48,6 +48,7 @@ let package = Package(
.testTarget(
name: "DonkeyRuntimeTests",
dependencies: [
+ "DonkeyAI",
"DonkeyContracts",
"DonkeyRuntime"
],
diff --git a/apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift b/apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift
new file mode 100644
index 00000000..7b15c6b9
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift
@@ -0,0 +1,213 @@
+import DonkeyContracts
+import Foundation
+
+public enum AIModelProvider: String, Codable, Equatable, Sendable {
+ case openAI
+}
+
+public enum AIModelRole: String, Codable, Equatable, Sendable {
+ case plannerHint
+ case traceSummary
+ case recovery
+}
+
+public enum AIModelCapability: String, Codable, Equatable, Hashable, Sendable {
+ case textInput
+ case structuredOutputs
+ case imageInput
+}
+
+public enum AIModelEvalStatus: String, Codable, Equatable, Sendable {
+ case candidate
+ case passing
+ case failing
+ case disabled
+}
+
+public struct AIModelRegistryEntry: Codable, Equatable, Sendable {
+ public var id: String
+ public var role: AIModelRole
+ public var provider: AIModelProvider
+ public var modelID: String
+ public var endpoint: URL
+ public var capabilities: Set<AIModelCapability>
+ public var timeoutMS: Int
+ public var promptVersion: String
+ public var evalStatus: AIModelEvalStatus
+ public var docsURL: URL
+ public var rollbackID: String?
+ public var metadata: [String: String]
+
+ public init(
+ id: String,
+ role: AIModelRole,
+ provider: AIModelProvider,
+ modelID: String,
+ endpoint: URL,
+ capabilities: Set<AIModelCapability>,
+ timeoutMS: Int,
+ promptVersion: String,
+ evalStatus: AIModelEvalStatus,
+ docsURL: URL,
+ rollbackID: String? = nil,
+ metadata: [String: String] = [:]
+ ) {
+ self.id = id
+ self.role = role
+ self.provider = provider
+ self.modelID = modelID
+ self.endpoint = endpoint
+ self.capabilities = capabilities
+ self.timeoutMS = timeoutMS
+ self.promptVersion = promptVersion
+ self.evalStatus = evalStatus
+ self.docsURL = docsURL
+ self.rollbackID = rollbackID
+ self.metadata = metadata
+ }
+}
+
+public struct AIModelRegistry: Codable, Equatable, Sendable {
+ public var entries: [AIModelRegistryEntry]
+
+ public init(entries: [AIModelRegistryEntry]) {
+ self.entries = entries
+ }
+
+ public static let defaultOpenAIPlanner = AIModelRegistry(
+ entries: [
+ 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 {
+ case plannerHint
+ case traceSummary
+ case recovery
+}
+
+public enum AIModelRisk: String, Codable, Equatable, Sendable {
+ case low
+ case medium
+ case high
+}
+
+public enum AIModelPrivacyMode: String, Codable, Equatable, Sendable {
+ case standard
+ case privacySensitive
+}
+
+public enum AIModelLatencyTolerance: String, Codable, Equatable, Sendable {
+ case interactive
+ case background
+}
+
+public struct AIModelRouteRequest: Codable, Equatable, Sendable {
+ public var jobType: AIModelJobType
+ public var risk: AIModelRisk
+ public var privacyMode: AIModelPrivacyMode
+ public var latencyTolerance: AIModelLatencyTolerance
+ public var failedModelEntryIDs: Set<String>
+ public var requiredCapabilities: Set<AIModelCapability>
+
+ public init(
+ jobType: AIModelJobType,
+ risk: AIModelRisk = .low,
+ privacyMode: AIModelPrivacyMode = .privacySensitive,
+ latencyTolerance: AIModelLatencyTolerance = .interactive,
+ failedModelEntryIDs: Set<String> = [],
+ requiredCapabilities: Set<AIModelCapability> = [.structuredOutputs]
+ ) {
+ self.jobType = jobType
+ self.risk = risk
+ self.privacyMode = privacyMode
+ self.latencyTolerance = latencyTolerance
+ self.failedModelEntryIDs = failedModelEntryIDs
+ self.requiredCapabilities = requiredCapabilities
+ }
+}
+
+public enum AIModelRouteError: Error, Equatable, Sendable {
+ case noMatchingModel
+}
+
+public struct AIModelRouter: Sendable {
+ public var registry: AIModelRegistry
+
+ public init(registry: AIModelRegistry = .defaultOpenAIPlanner) {
+ self.registry = registry
+ }
+
+ public func route(
+ _ request: AIModelRouteRequest
+ ) throws -> AIModelRegistryEntry {
+ let role = role(for: request.jobType)
+ let candidates = registry.entries
+ .filter { entry in
+ entry.role == role
+ && entry.evalStatus != .disabled
+ && !request.failedModelEntryIDs.contains(entry.id)
+ && request.requiredCapabilities.isSubset(of: entry.capabilities)
+ && allowsRisk(request.risk, entry: entry)
+ }
+ .sorted { lhs, rhs in
+ score(lhs, request: request) > score(rhs, request: request)
+ }
+
+ guard let selected = candidates.first else {
+ throw AIModelRouteError.noMatchingModel
+ }
+
+ return selected
+ }
+
+ private func role(for jobType: AIModelJobType) -> AIModelRole {
+ switch jobType {
+ case .plannerHint:
+ return .plannerHint
+ case .traceSummary:
+ return .traceSummary
+ case .recovery:
+ return .recovery
+ }
+ }
+
+ private func allowsRisk(_ risk: AIModelRisk, entry: AIModelRegistryEntry) -> Bool {
+ if risk == .high {
+ return entry.evalStatus == .passing
+ }
+
+ return true
+ }
+
+ private func score(
+ _ entry: AIModelRegistryEntry,
+ request: AIModelRouteRequest
+ ) -> Int {
+ 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
+ }
+ return value
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyAI/OpenAIPlannerHintAdapter.swift b/apps/Donkey/Sources/DonkeyAI/OpenAIPlannerHintAdapter.swift
new file mode 100644
index 00000000..de0289cd
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyAI/OpenAIPlannerHintAdapter.swift
@@ -0,0 +1,448 @@
+import DonkeyContracts
+import Foundation
+
+public enum AIModelCallStatus: String, Codable, Equatable, Sendable {
+ case completed
+ case timeout
+ case cancelled
+ case rateLimited
+ case invalidOutput
+ case providerOutage
+ case missingCredentials
+}
+
+public struct AIModelCallTrace: Codable, Equatable, Sendable {
+ public var id: String
+ public var role: AIModelRole
+ public var provider: AIModelProvider
+ public var modelID: String
+ public var promptVersion: String
+ public var schemaID: String
+ public var latencyMS: Double?
+ public var timeoutMS: Int
+ public var status: AIModelCallStatus
+ public var validationStatus: String
+ public var sourceTraceID: String
+ public var sourceStateID: String?
+ public var metadata: [String: String]
+
+ public init(
+ id: String,
+ role: AIModelRole,
+ provider: AIModelProvider,
+ modelID: String,
+ promptVersion: String,
+ schemaID: String,
+ latencyMS: Double?,
+ timeoutMS: Int,
+ status: AIModelCallStatus,
+ validationStatus: String,
+ sourceTraceID: String,
+ sourceStateID: String? = nil,
+ metadata: [String: String] = [:]
+ ) {
+ self.id = id
+ self.role = role
+ self.provider = provider
+ self.modelID = modelID
+ self.promptVersion = promptVersion
+ self.schemaID = schemaID
+ self.latencyMS = latencyMS
+ self.timeoutMS = timeoutMS
+ self.status = status
+ self.validationStatus = validationStatus
+ self.sourceTraceID = sourceTraceID
+ self.sourceStateID = sourceStateID
+ self.metadata = metadata
+ }
+}
+
+public struct PlannerHintAdapterRequest: Equatable, Sendable {
+ public var context: RunContextPackage
+ public var sourceTraceID: String
+ public var sourceFrameID: String?
+ public var sourceStateID: String?
+ public var now: RunTraceTimestamp
+ public var routeRequest: AIModelRouteRequest
+
+ public init(
+ context: RunContextPackage,
+ sourceTraceID: String,
+ sourceFrameID: String? = nil,
+ sourceStateID: String? = nil,
+ now: RunTraceTimestamp,
+ routeRequest: AIModelRouteRequest = AIModelRouteRequest(jobType: .plannerHint)
+ ) {
+ self.context = context
+ self.sourceTraceID = sourceTraceID
+ self.sourceFrameID = sourceFrameID
+ self.sourceStateID = sourceStateID
+ self.now = now
+ self.routeRequest = routeRequest
+ }
+}
+
+public struct PlannerHintAdapterResult: Equatable, Sendable {
+ public var hint: StructuredPlannerHint?
+ public var trace: AIModelCallTrace
+
+ public init(
+ hint: StructuredPlannerHint?,
+ trace: AIModelCallTrace
+ ) {
+ self.hint = hint
+ self.trace = trace
+ }
+}
+
+public protocol AIHTTPClient: Sendable {
+ func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse)
+}
+
+public struct URLSessionAIHTTPClient: AIHTTPClient {
+ public init() {}
+
+ public func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {
+ let (data, response) = try await URLSession.shared.data(for: request)
+ guard let httpResponse = response as? HTTPURLResponse else {
+ throw OpenAIPlannerHintAdapterError.invalidHTTPResponse
+ }
+ return (data, httpResponse)
+ }
+}
+
+public enum OpenAIPlannerHintAdapterError: Error, Equatable, Sendable {
+ case invalidHTTPResponse
+}
+
+public struct OpenAIPlannerHintAdapter: Sendable {
+ public static let schemaID = "planner_hint_v1"
+
+ public var router: AIModelRouter
+ public var httpClient: any AIHTTPClient
+ public var environment: [String: String]
+
+ public init(
+ router: AIModelRouter = AIModelRouter(),
+ httpClient: any AIHTTPClient = URLSessionAIHTTPClient(),
+ environment: [String: String] = ProcessInfo.processInfo.environment
+ ) {
+ self.router = router
+ self.httpClient = httpClient
+ self.environment = environment
+ }
+
+ public func generatePlannerHint(
+ _ request: PlannerHintAdapterRequest
+ ) async -> PlannerHintAdapterResult {
+ let entry: AIModelRegistryEntry
+ do {
+ entry = try router.route(request.routeRequest)
+ } catch {
+ return result(
+ entry: nil,
+ request: request,
+ status: .invalidOutput,
+ validationStatus: "routingFailed",
+ latencyMS: nil,
+ metadata: ["error": String(describing: error)]
+ )
+ }
+
+ guard let apiKey = environment["OPENAI_API_KEY"], !apiKey.isEmpty else {
+ return result(
+ entry: entry,
+ request: request,
+ status: .missingCredentials,
+ validationStatus: "notValidated",
+ latencyMS: nil,
+ metadata: ["credential": "OPENAI_API_KEY"]
+ )
+ }
+
+ let startedAt = ProcessInfo.processInfo.systemUptime
+ do {
+ let urlRequest = try makeURLRequest(
+ entry: entry,
+ adapterRequest: request,
+ apiKey: apiKey
+ )
+ 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 Self.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),
+ "privacy.store": "false"
+ ]
+ )
+ )
+ } 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,
+ apiKey: String
+ ) 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.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
+ 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,
+ "store": false,
+ "instructions": "Return one planner hint as strict JSON. Hints are advisory and never direct input.",
+ "input": [
+ [
+ "role": "user",
+ "content": [
+ [
+ "type": "input_text",
+ "text": promptText(for: adapterRequest)
+ ]
+ ]
+ ]
+ ],
+ "text": [
+ "format": [
+ "type": "json_schema",
+ "name": Self.schemaID,
+ "strict": true,
+ "schema": plannerHintJSONSchema()
+ ]
+ ],
+ "metadata": [
+ "source_trace_id": adapterRequest.sourceTraceID,
+ "prompt_version": entry.promptVersion
+ ]
+ ]
+ }
+
+ private func promptText(for request: PlannerHintAdapterRequest) -> String {
+ [
+ "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 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"]
+ ]
+ ]
+ }
+
+ 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 ?? .openAI,
+ 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
+ )
+ }
+}
+
+private struct OpenAIResponseEnvelope: Decodable {
+ var id: String?
+ var outputText: String?
+ var output: [OpenAIResponseOutput]?
+
+ enum CodingKeys: String, CodingKey {
+ case id
+ case outputText = "output_text"
+ case output
+ }
+}
+
+private struct OpenAIResponseOutput: Decodable {
+ var content: [OpenAIResponseContent]?
+}
+
+private struct OpenAIResponseContent: Decodable {
+ var type: String?
+ var text: String?
+}
+
+private struct PlannerHintWireOutput: Decodable {
+ var id: String
+ var goal: String
+ var policyName: String
+ var priorities: [String]
+ var preferredActions: [String]
+ var avoidActions: [String]
+ var confidence: Double
+ 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
+ }
+
+ static func decodeHint(
+ _ text: String,
+ sourceTraceID: String,
+ sourceFrameID: String?,
+ sourceStateID: String?,
+ modelCallID: String,
+ now: RunTraceTimestamp
+ ) throws -> StructuredPlannerHint? {
+ guard let data = text.data(using: .utf8) else { return nil }
+ let wire = try JSONDecoder().decode(PlannerHintWireOutput.self, from: data)
+ guard let preferredActions = actions(from: wire.preferredActions),
+ let avoidActions = actions(from: wire.avoidActions)
+ else {
+ return nil
+ }
+
+ return StructuredPlannerHint(
+ id: wire.id,
+ goal: wire.goal,
+ policyName: wire.policyName,
+ priorities: wire.priorities,
+ preferredActions: preferredActions,
+ avoidActions: avoidActions,
+ confidence: wire.confidence,
+ createdAt: now,
+ expiresAt: now.addingMilliseconds(wire.expiryMilliseconds),
+ sourceTraceID: sourceTraceID,
+ sourceFrameID: sourceFrameID,
+ sourceStateID: sourceStateID,
+ sourceModelCallID: modelCallID
+ )
+ }
+
+ static func actions(from rawValues: [String]) -> [HotLoopActionKind]? {
+ var actions: [HotLoopActionKind] = []
+ for rawValue in rawValues {
+ guard let action = HotLoopActionKind(rawValue: rawValue) else {
+ return nil
+ }
+ actions.append(action)
+ }
+ return actions
+ }
+}
+
+private extension RunTraceTimestamp {
+ func addingMilliseconds(_ milliseconds: UInt64) -> RunTraceTimestamp {
+ RunTraceTimestamp(
+ wallClock: wallClock.addingTimeInterval(Double(milliseconds) / 1_000),
+ monotonicUptimeNanoseconds: monotonicUptimeNanoseconds + milliseconds * 1_000_000
+ )
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyContracts/HotLoopContracts.swift b/apps/Donkey/Sources/DonkeyContracts/HotLoopContracts.swift
index 698b8007..8a4837c9 100644
--- a/apps/Donkey/Sources/DonkeyContracts/HotLoopContracts.swift
+++ b/apps/Donkey/Sources/DonkeyContracts/HotLoopContracts.swift
@@ -483,7 +483,7 @@ public struct HotLoopWorldState: Codable, Equatable, Sendable {
}
}
-public enum HotLoopActionKind: String, Codable, Equatable, Sendable {
+public enum HotLoopActionKind: String, CaseIterable, Codable, Equatable, Hashable, Sendable {
case observe
case wait
case tapTarget
diff --git a/apps/Donkey/Sources/DonkeyContracts/PlannerHintContracts.swift b/apps/Donkey/Sources/DonkeyContracts/PlannerHintContracts.swift
new file mode 100644
index 00000000..a26e9a5a
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyContracts/PlannerHintContracts.swift
@@ -0,0 +1,194 @@
+import Foundation
+
+public enum PlannerHintValidationIssue: String, Codable, Equatable, Sendable {
+ case unknownAction
+ case unsafeAction
+ case staleStateReference
+ case lowConfidenceReplacement
+ case expired
+}
+
+public struct StructuredPlannerHint: Codable, Equatable, Sendable {
+ public var id: String
+ public var goal: String
+ public var policyName: String
+ public var priorities: [String]
+ public var regionsOfInterest: [HotLoopRect]
+ public var preferredActions: [HotLoopActionKind]
+ public var avoidActions: [HotLoopActionKind]
+ public var confidence: Double
+ public var createdAt: RunTraceTimestamp
+ public var expiresAt: RunTraceTimestamp
+ public var sourceTraceID: String
+ public var sourceFrameID: String?
+ public var sourceStateID: String?
+ public var sourceModelCallID: String?
+ public var replacesHintID: String?
+ public var metadata: [String: String]
+
+ public init(
+ id: String,
+ goal: String,
+ policyName: String,
+ priorities: [String] = [],
+ regionsOfInterest: [HotLoopRect] = [],
+ preferredActions: [HotLoopActionKind] = [],
+ avoidActions: [HotLoopActionKind] = [],
+ confidence: Double,
+ createdAt: RunTraceTimestamp,
+ expiresAt: RunTraceTimestamp,
+ sourceTraceID: String,
+ sourceFrameID: String? = nil,
+ sourceStateID: String? = nil,
+ sourceModelCallID: String? = nil,
+ replacesHintID: String? = nil,
+ metadata: [String: String] = [:]
+ ) {
+ self.id = id
+ self.goal = goal
+ self.policyName = policyName
+ self.priorities = priorities
+ self.regionsOfInterest = regionsOfInterest
+ self.preferredActions = preferredActions
+ self.avoidActions = avoidActions
+ self.confidence = confidence
+ self.createdAt = createdAt
+ self.expiresAt = expiresAt
+ self.sourceTraceID = sourceTraceID
+ self.sourceFrameID = sourceFrameID
+ self.sourceStateID = sourceStateID
+ self.sourceModelCallID = sourceModelCallID
+ self.replacesHintID = replacesHintID
+ self.metadata = metadata
+ }
+
+ public func isExpired(at timestamp: RunTraceTimestamp) -> Bool {
+ expiresAt.milliseconds(until: timestamp) != nil
+ }
+
+ public func summaryHint(isValid: Bool = true) -> RunPlannerHint {
+ RunPlannerHint(
+ id: id,
+ summary: "\(policyName): \(goal)",
+ isValid: isValid
+ )
+ }
+}
+
+public struct PlannerHintValidationContext: Equatable, Sendable {
+ public var currentStateID: String?
+ public var allowedActions: Set<HotLoopActionKind>
+ public var unsafeActions: Set<HotLoopActionKind>
+ public var minimumConfidence: Double
+ public var minimumReplacementConfidence: Double
+ public var now: RunTraceTimestamp
+
+ public init(
+ currentStateID: String? = nil,
+ allowedActions: Set<HotLoopActionKind> = Set(HotLoopActionKind.allCases),
+ unsafeActions: Set<HotLoopActionKind> = [],
+ minimumConfidence: Double = 0.3,
+ minimumReplacementConfidence: Double = 0.6,
+ now: RunTraceTimestamp
+ ) {
+ self.currentStateID = currentStateID
+ self.allowedActions = allowedActions
+ self.unsafeActions = unsafeActions
+ self.minimumConfidence = minimumConfidence
+ self.minimumReplacementConfidence = minimumReplacementConfidence
+ self.now = now
+ }
+}
+
+public struct PlannerHintValidationResult: Equatable, Sendable {
+ public var hint: StructuredPlannerHint
+ public var issues: [PlannerHintValidationIssue]
+
+ public init(
+ hint: StructuredPlannerHint,
+ issues: [PlannerHintValidationIssue] = []
+ ) {
+ self.hint = hint
+ self.issues = issues
+ }
+
+ public var isValid: Bool {
+ issues.isEmpty
+ }
+}
+
+public enum PlannerHintValidator {
+ public static func validate(
+ _ hint: StructuredPlannerHint,
+ context: PlannerHintValidationContext
+ ) -> PlannerHintValidationResult {
+ let actions = Set(hint.preferredActions + hint.avoidActions)
+ var issues: [PlannerHintValidationIssue] = []
+
+ if !actions.isSubset(of: context.allowedActions) {
+ issues.append(.unknownAction)
+ }
+
+ if !actions.intersection(context.unsafeActions).isEmpty {
+ issues.append(.unsafeAction)
+ }
+
+ if let currentStateID = context.currentStateID,
+ let sourceStateID = hint.sourceStateID,
+ sourceStateID != currentStateID {
+ issues.append(.staleStateReference)
+ }
+
+ if hint.confidence < context.minimumConfidence {
+ issues.append(.lowConfidenceReplacement)
+ }
+
+ if hint.replacesHintID != nil,
+ hint.confidence < context.minimumReplacementConfidence {
+ issues.append(.lowConfidenceReplacement)
+ }
+
+ if hint.isExpired(at: context.now) {
+ issues.append(.expired)
+ }
+
+ return PlannerHintValidationResult(
+ hint: hint,
+ issues: Array(Set(issues)).sorted { $0.rawValue < $1.rawValue }
+ )
+ }
+}
+
+public struct PlannerHintSelection: Equatable, Sendable {
+ public var latestValidHint: StructuredPlannerHint?
+ public var validationResults: [PlannerHintValidationResult]
+
+ public init(
+ latestValidHint: StructuredPlannerHint?,
+ validationResults: [PlannerHintValidationResult]
+ ) {
+ self.latestValidHint = latestValidHint
+ self.validationResults = validationResults
+ }
+}
+
+public enum PlannerHintSelector {
+ public static func latestValidHint(
+ from hints: [StructuredPlannerHint],
+ context: PlannerHintValidationContext
+ ) -> PlannerHintSelection {
+ let results = hints.map { PlannerHintValidator.validate($0, context: context) }
+ let latest = results
+ .filter(\.isValid)
+ .map(\.hint)
+ .sorted {
+ $0.createdAt.monotonicUptimeNanoseconds > $1.createdAt.monotonicUptimeNanoseconds
+ }
+ .first
+
+ return PlannerHintSelection(
+ latestValidHint: latest,
+ validationResults: results
+ )
+ }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
new file mode 100644
index 00000000..c034822d
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
@@ -0,0 +1,205 @@
+import DonkeyAI
+import DonkeyContracts
+import Foundation
+import Testing
+
+@Suite
+struct AIHarnessAdapterTests {
+ @Test
+ func routerSelectsPlannerModelFromRegistryAndSkipsFailedEntries() throws {
+ let registry = AIModelRegistry(
+ entries: [
+ entry(id: "failed", modelID: "gpt-5-mini", evalStatus: .passing, timeoutMS: 1_000),
+ entry(id: "selected", modelID: "gpt-5.2", evalStatus: .passing, timeoutMS: 2_000)
+ ]
+ )
+ let router = AIModelRouter(registry: registry)
+
+ let selected = try router.route(
+ AIModelRouteRequest(
+ jobType: .plannerHint,
+ failedModelEntryIDs: ["failed"]
+ )
+ )
+
+ #expect(selected.id == "selected")
+ #expect(selected.modelID == "gpt-5.2")
+ }
+
+ @Test
+ func highRiskRouteRequiresPassingModel() throws {
+ let router = AIModelRouter(
+ registry: AIModelRegistry(
+ entries: [
+ entry(id: "candidate", modelID: "gpt-5.2", evalStatus: .candidate)
+ ]
+ )
+ )
+
+ #expect(throws: AIModelRouteError.noMatchingModel) {
+ _ = try router.route(
+ AIModelRouteRequest(
+ jobType: .plannerHint,
+ risk: .high
+ )
+ )
+ }
+ }
+
+ @Test
+ func openAIAdapterBuildsResponsesRequestWithStoreFalseAndDecodesStructuredHint() async throws {
+ let httpClient = FakeAIHTTPClient(
+ data: responseData(
+ outputText: """
+ {"id":"hint-1","goal":"avoid hazards","policyName":"planner-policy","priorities":["center lane"],"preferredActions":["wait"],"avoidActions":["tapTarget"],"confidence":0.82,"expiryMilliseconds":5000}
+ """
+ ),
+ statusCode: 200
+ )
+ let adapter = OpenAIPlannerHintAdapter(
+ router: AIModelRouter(registry: AIModelRegistry(entries: [entry(id: "planner", modelID: "gpt-5.2")])),
+ httpClient: httpClient,
+ environment: ["OPENAI_API_KEY": "test-key"]
+ )
+
+ let result = await adapter.generatePlannerHint(adapterRequest())
+
+ #expect(result.hint?.id == "hint-1")
+ #expect(result.hint?.preferredActions == [.wait])
+ #expect(result.hint?.avoidActions == [.tapTarget])
+ #expect(result.hint?.sourceTraceID == "trace-1")
+ #expect(result.trace.status == .completed)
+ #expect(result.trace.validationStatus == "schemaDecoded")
+ #expect(result.trace.metadata["privacy.store"] == "false")
+
+ let request = try #require(httpClient.requests.first)
+ #expect(request.url?.absoluteString == "https://api.openai.com/v1/responses")
+ #expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer test-key")
+ let body = try #require(request.httpBodyJSONObject)
+ #expect(body["model"] as? String == "gpt-5.2")
+ #expect(body["store"] as? Bool == false)
+ let text = try #require(body["text"] as? [String: Any])
+ let formatContainer = try #require(text["format"] as? [String: Any])
+ #expect(formatContainer["type"] as? String == "json_schema")
+ }
+
+ @Test
+ func openAIAdapterHandlesMissingCredentialsRateLimitAndInvalidOutput() async {
+ let adapter = OpenAIPlannerHintAdapter(
+ router: AIModelRouter(registry: AIModelRegistry(entries: [entry(id: "planner", modelID: "gpt-5.2")])),
+ httpClient: FakeAIHTTPClient(data: responseData(outputText: "{}"), statusCode: 200),
+ environment: [:]
+ )
+
+ let missingCredentials = await adapter.generatePlannerHint(adapterRequest())
+ #expect(missingCredentials.hint == nil)
+ #expect(missingCredentials.trace.status == .missingCredentials)
+
+ let rateLimited = await OpenAIPlannerHintAdapter(
+ router: AIModelRouter(registry: AIModelRegistry(entries: [entry(id: "planner", modelID: "gpt-5.2")])),
+ httpClient: FakeAIHTTPClient(data: Data(), statusCode: 429),
+ environment: ["OPENAI_API_KEY": "test-key"]
+ )
+ .generatePlannerHint(adapterRequest())
+ #expect(rateLimited.trace.status == .rateLimited)
+
+ let invalidOutput = await OpenAIPlannerHintAdapter(
+ router: AIModelRouter(registry: AIModelRegistry(entries: [entry(id: "planner", modelID: "gpt-5.2")])),
+ httpClient: FakeAIHTTPClient(data: responseData(outputText: "{}"), statusCode: 200),
+ environment: ["OPENAI_API_KEY": "test-key"]
+ )
+ .generatePlannerHint(adapterRequest())
+ #expect(invalidOutput.trace.status == .invalidOutput)
+ }
+
+ private func adapterRequest() -> PlannerHintAdapterRequest {
+ PlannerHintAdapterRequest(
+ 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: ""
+ ),
+ sourceTraceID: "trace-1",
+ sourceFrameID: "frame-1",
+ sourceStateID: "state-1",
+ now: timestamp(10)
+ )
+ }
+
+ private func entry(
+ id: String,
+ modelID: String,
+ evalStatus: AIModelEvalStatus = .candidate,
+ timeoutMS: Int = 8_000
+ ) -> AIModelRegistryEntry {
+ AIModelRegistryEntry(
+ id: id,
+ role: .plannerHint,
+ provider: .openAI,
+ modelID: modelID,
+ endpoint: URL(string: "https://api.openai.com/v1/responses")!,
+ capabilities: [.textInput, .structuredOutputs],
+ timeoutMS: timeoutMS,
+ promptVersion: "planner-hint-v1",
+ evalStatus: evalStatus,
+ docsURL: URL(string: "https://platform.openai.com/docs/api-reference/responses/create")!
+ )
+ }
+
+ private func responseData(outputText: String) -> Data {
+ let escaped = outputText
+ .replacingOccurrences(of: "\\", with: "\\\\")
+ .replacingOccurrences(of: "\"", with: "\\\"")
+ .replacingOccurrences(of: "\n", with: "\\n")
+ return Data("{\"id\":\"resp-1\",\"output_text\":\"\(escaped)\"}".utf8)
+ }
+
+ private func timestamp(_ milliseconds: UInt64) -> RunTraceTimestamp {
+ RunTraceTimestamp(
+ wallClock: Date(timeIntervalSince1970: Double(milliseconds) / 1_000),
+ monotonicUptimeNanoseconds: milliseconds * 1_000_000
+ )
+ }
+}
+
+private final class FakeAIHTTPClient: AIHTTPClient, @unchecked Sendable {
+ var data: Data
+ var statusCode: Int
+ var requests: [URLRequest] = []
+
+ init(data: Data, statusCode: Int) {
+ self.data = data
+ self.statusCode = statusCode
+ }
+
+ func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {
+ requests.append(request)
+ return (
+ data,
+ HTTPURLResponse(
+ url: request.url!,
+ statusCode: statusCode,
+ httpVersion: nil,
+ headerFields: nil
+ )!
+ )
+ }
+}
+
+private extension URLRequest {
+ var httpBodyJSONObject: [String: Any]? {
+ guard let httpBody,
+ let object = try? JSONSerialization.jsonObject(with: httpBody) as? [String: Any]
+ else {
+ return nil
+ }
+ return object
+ }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/PlannerHintContractsTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/PlannerHintContractsTests.swift
new file mode 100644
index 00000000..dc6b3e7d
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/PlannerHintContractsTests.swift
@@ -0,0 +1,103 @@
+import DonkeyContracts
+import Foundation
+import Testing
+
+@Suite
+struct PlannerHintContractsTests {
+ @Test
+ func validPlannerHintCanBeSelectedAsLatest() {
+ let older = hint(id: "hint-old", createdAtMS: 10, sourceStateID: "state-1", confidence: 0.7)
+ let latest = hint(id: "hint-latest", createdAtMS: 20, sourceStateID: "state-1", confidence: 0.8)
+ let expired = hint(id: "hint-expired", createdAtMS: 30, expiresAtMS: 40, sourceStateID: "state-1", confidence: 0.9)
+
+ let selection = PlannerHintSelector.latestValidHint(
+ from: [older, latest, expired],
+ context: context(nowMS: 50, currentStateID: "state-1")
+ )
+
+ #expect(selection.latestValidHint?.id == "hint-latest")
+ #expect(selection.validationResults.first(where: { $0.hint.id == "hint-expired" })?.issues == [.expired])
+ }
+
+ @Test
+ func validatorRejectsUnsafeActionsStaleStateAndLowConfidenceReplacement() {
+ let candidate = hint(
+ id: "hint-bad",
+ sourceStateID: "old-state",
+ confidence: 0.4,
+ preferredActions: [.tapTarget],
+ replacesHintID: "hint-current"
+ )
+
+ let result = PlannerHintValidator.validate(
+ candidate,
+ context: PlannerHintValidationContext(
+ currentStateID: "state-1",
+ allowedActions: Set(HotLoopActionKind.allCases),
+ unsafeActions: [.tapTarget],
+ minimumConfidence: 0.3,
+ minimumReplacementConfidence: 0.6,
+ now: timestamp(20)
+ )
+ )
+
+ #expect(result.isValid == false)
+ #expect(result.issues == [
+ .lowConfidenceReplacement,
+ .staleStateReference,
+ .unsafeAction
+ ])
+ }
+
+ @Test
+ func structuredHintRoundTripsThroughCodableAndSummaryBridge() throws {
+ let candidate = hint(id: "hint-codable", sourceStateID: "state-1", confidence: 0.75)
+
+ let data = try JSONEncoder().encode(candidate)
+ let decoded = try JSONDecoder().decode(StructuredPlannerHint.self, from: data)
+
+ #expect(decoded == candidate)
+ #expect(decoded.summaryHint().id == "hint-codable")
+ #expect(decoded.summaryHint().isValid == true)
+ }
+
+ private func context(nowMS: UInt64, currentStateID: String?) -> PlannerHintValidationContext {
+ PlannerHintValidationContext(
+ currentStateID: currentStateID,
+ now: timestamp(nowMS)
+ )
+ }
+
+ private func hint(
+ id: String,
+ createdAtMS: UInt64 = 10,
+ expiresAtMS: UInt64 = 100,
+ sourceStateID: String?,
+ confidence: Double,
+ preferredActions: [HotLoopActionKind] = [.wait],
+ replacesHintID: String? = nil
+ ) -> StructuredPlannerHint {
+ StructuredPlannerHint(
+ id: id,
+ goal: "stay safe",
+ policyName: "planner-policy",
+ priorities: ["avoid hazards"],
+ preferredActions: preferredActions,
+ avoidActions: [.tapTarget],
+ confidence: confidence,
+ createdAt: timestamp(createdAtMS),
+ expiresAt: timestamp(expiresAtMS),
+ sourceTraceID: "trace-1",
+ sourceFrameID: "frame-1",
+ sourceStateID: sourceStateID,
+ replacesHintID: replacesHintID
+ )
+ }
+
+ private func timestamp(_ milliseconds: UInt64) -> RunTraceTimestamp {
+ RunTraceTimestamp(
+ wallClock: Date(timeIntervalSince1970: Double(milliseconds) / 1_000),
+ monotonicUptimeNanoseconds: milliseconds * 1_000_000
+ )
+ }
+}
diff --git a/docs/guides/minimal-run-coordinator.md b/docs/guides/minimal-run-coordinator.md
index 799870aa..bd0efe96 100644
--- a/docs/guides/minimal-run-coordinator.md
+++ b/docs/guides/minimal-run-coordinator.md
@@ -28,6 +28,12 @@ Donkey also supports the first action-engine guardrail boundary. `ActionEngineGu
Donkey also supports reflex latency reports and a synthetic replay benchmark. `ReflexLatencyReportBuilder` summarizes reflex traces into p50/p95/p99 latency, capture/perception/controller rates, dropped frames, stale actions, and worst traces. `ReflexReplayBenchmark` can generate deterministic dry-run traces for capture-only, controller-only, or end-to-end dry-run report modes. The installed debug entrypoint can print a CLI-friendly dry-run latency report with `--dry-run-latency-report`.
+Donkey also supports slow-path planner hint contracts. `StructuredPlannerHint` carries a goal, policy, priorities, regions of interest, preferred and avoided semantic actions, confidence, expiry, and source trace/frame/state/model-call ids. Planner hints are advisory only; they are validated for unknown actions, unsafe actions, stale state references, low-confidence replacement, and expiry before selection. `PlannerHintSelector` chooses the latest valid hint, and the reflex loop remains able to run without any planner hint.
+
+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 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 a local run artifact store for durable trace data. Installed app runs are stored under `~/Library/Application Support/Donkey/Runs/<run-id>/`; tests and development tools may pass an explicit base directory override. Each prepared run creates:
```text
@@ -49,7 +55,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, action-engine guardrail, latency-report, target-metadata, single-screenshot artifact, read-only Accessibility snapshot, and manual capture orchestration foundation only. It does not run real vision models or OCR, call LLMs, execute OS input, perform Accessibility actions, provide a manual capture UI, persist high-volume reflex traces to disk, or provide continuous streaming capture yet.
+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, action-engine guardrail, latency-report, planner-hint contract, model-registry/router, provider-neutral AI adapter, target-metadata, single-screenshot artifact, read-only Accessibility snapshot, and manual capture orchestration foundation only. It does not run real vision models or OCR, execute OS input, 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
@@ -77,6 +83,10 @@ This is a coordination, in-memory reflex trace, hot-loop contract, deterministic
- Keep live OS input disabled until a later smoke slice explicitly wires a real backend. The guardrail boundary may project dry-run commands and release held state, but should not synthesize OS events.
- Use monotonic timestamps for latency math. Wall-clock timestamps are for human labels and trace correlation only.
- Use latency reports for any p50/p95/p99 claim. Reports should include dropped frames, stale actions, tick rates, and worst traces.
+- Treat planner hints as validated, expiring advice. Controllers may use the latest valid hint, but planner output must never become direct input.
+- Keep model selection in `AIModelRegistry` data. Do not scatter provider model ids through planner code.
+- Keep privacy-sensitive Responses API calls configured with `store: false` unless an explicit later policy changes that default.
+- Treat provider failures as sidecar failures. Missing credentials, timeout, rate limit, invalid output, or outage should leave the controller running on local state and existing valid hints.
- Keep reflex trace retention bounded. The current in-memory store is for recent status and tests, not high-volume replay persistence.
- Use sampled or summarized reflex events until a measured disk trace sink exists.
@@ -88,7 +98,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, action-engine permission/focus/rate/hold/release guardrails, latency report percentiles and replay benchmark formatting, 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, controller confidence/staleness fallback, controller p95 replay timing under 20ms, 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, 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:
@@ -108,6 +118,7 @@ Remaining live verification is environment-dependent. On May 16, 2026, iPhone Mi
- Runtime contracts live in `apps/Donkey/Sources/DonkeyContracts/RunLoopContracts.swift`.
- Hot-loop contracts live in `apps/Donkey/Sources/DonkeyContracts/HotLoopContracts.swift`.
+- Planner hint contracts live in `apps/Donkey/Sources/DonkeyContracts/PlannerHintContracts.swift`.
- Window target contracts live in `apps/Donkey/Sources/DonkeyContracts/WindowTargetContracts.swift`.
- Runtime coordination lives in `apps/Donkey/Sources/DonkeyRuntime/`.
- The deterministic dry-run reflex skeleton lives in `apps/Donkey/Sources/DonkeyRuntime/DryRunReflexLoop.swift`.
@@ -115,6 +126,8 @@ Remaining live verification is environment-dependent. On May 16, 2026, iPhone Mi
- Cheap perception, world-state projection, deterministic controller policy, and dry-run action projection live in `apps/Donkey/Sources/DonkeyRuntime/CheapPerceptionAndController.swift`.
- Action-engine guardrails live in `apps/Donkey/Sources/DonkeyRuntime/ActionEngineGuardrails.swift`.
- Reflex latency reports and synthetic replay benchmarks live in `apps/Donkey/Sources/DonkeyRuntime/ReflexLatencyReport.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`.
- Recent reflex trace retention lives in `apps/Donkey/Sources/DonkeyRuntime/InMemoryReflexTraceStore.swift`.
- macOS window resolution lives in `apps/Donkey/Sources/DonkeyRuntime/MacWindowResolver.swift`.
- Target-window screenshot capture lives in `apps/Donkey/Sources/DonkeyRuntime/WindowScreenshotCaptureService.swift`.
diff --git a/plans/master-plan.md b/plans/master-plan.md
index c50cd41f..744bf5e8 100644
--- a/plans/master-plan.md
+++ b/plans/master-plan.md
@@ -16,11 +16,13 @@ Supporting plans:
- `plans/05-action-engine.md`
- `plans/06-benchmarking.md`
-Supported behavior and engineering guidance belong in `docs/guides/`. This master plan should shrink as slices become supported.
+Supported behavior and engineering guidance belong in `docs/guides/`. This master plan should stay small: keep only critical current-boundary context and the active queue.
## Plan Management Note
-As work progresses, move actionable items out of the supporting plans and into this master plan so there is one active queue. When a supporting plan has no remaining active work, either move it to `plans/done/` if its acceptance criteria are supported, or leave it active only for clearly named future work that still remains.
+As work progresses, move only still-actionable items out of the supporting plans and into this master plan so there is one active queue. Do not grow a historical completed-task log here. When a slice becomes supported, update the supported-boundary summary below and the relevant guide in `docs/guides/`; use search across `docs/` and `plans/` for older implementation history.
+
+When a supporting plan has no remaining active work, either move it to `plans/done/` if its acceptance criteria are supported, or leave it active only for clearly named future work that still remains.
## Milestone Goal
@@ -45,19 +47,13 @@ slow AI harness
The hot path must continue to work with the AI harness disabled.
-## Current Supported Baseline
+## Supported Boundary
-- Minimal run coordination exists: session queueing, lifecycle events, policy checks, context compaction, abort/timeout input-release flags, and ordered event publication.
-- Local run artifact storage exists for `events.jsonl`, `summary.json`, screenshots, and Accessibility artifacts.
-- Manual target context capture exists for selected macOS windows with screenshot and bounded read-only Accessibility artifacts.
-- The first reflex trace contract exists: monotonic stage timestamps, latency breakdown, bounded in-memory trace retention, and matching coordinator `reflex` events.
-- Shared hot-loop contracts exist for frames, crops, explicit coordinate spaces, perception signals, compact world state, controller actions, action results, stale-signal marking, and trace-linked IDs.
-- A deterministic dry-run reflex loop skeleton exists for synthetic or recorded frame batches with latest-frame-wins queue depth 1, dropped-frame counting, dry-run action projection, and coordinator-published reflex traces.
-- Bounded target-window frame capture exists for the dry-run hot-loop boundary with selected-window safety checks, optional crop metadata, monotonic capture/copy timing, and no PNG/JPEG artifact encoding.
-- A cheap deterministic perception adapter exists for fixture or recorded-frame metadata, with compact world-state projection and raw pixels kept behind the perception boundary.
-- A deterministic controller policy exists for the first supported dry-run behavior: tap a fresh high-confidence target affordance, otherwise fall back to traceable wait/observe actions.
-- An action-engine guardrail boundary exists for typed commands, input permission checks, focus guard checks, rate limits, maximum hold durations, held-input release, and replayable command traces. Live OS input is still disabled.
-- Reflex latency reports and synthetic replay benchmark modes exist for p50/p95/p99 latency, frame/controller rates, dropped frames, stale actions, and worst traces.
+- Runtime shell: minimal run coordination, ordered events, bounded context assembly, local run artifacts, manual target context capture, in-memory reflex trace retention, and 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, deterministic controller, and dry-run action projection are supported. Live OS input is not supported.
+- Safety boundary: action-engine command contracts, permission/focus/rate/hold/release guardrails, and replayable command traces are supported before live input.
+- Slow AI boundary: structured planner hints, validation/expiry/latest-valid selection, model registry/router, and an OpenAI Responses structured-output adapter are supported as optional sidecar pieces. The hot loop still runs without AI output.
+- Source of truth: detailed supported behavior lives in `docs/guides/minimal-run-coordinator.md`; historical implementation details should be found with search in `docs/`, `plans/`, and git history, not duplicated here.
## Non-Negotiable Rules
@@ -70,77 +66,45 @@ The hot path must continue to work with the AI harness disabled.
- Latency claims require monotonic timestamps and a report.
- Full-resolution snapshots, screenshots for AI, and memory writes stay outside the reflex loop.
-## Completed Tasks
-
-- [x] Complete manual target context capture milestone.
-- [x] Add the first reflex trace contract and bounded in-memory trace retention.
-- [x] Publish reflex trace records through `RunCoordinator` as sampled `reflex` events.
-- [x] Define shared hot-loop contracts for typed frame, crop, world-state, perception-signal, controller-action, action-result, and coordinate conversion.
-- [x] Add deterministic dry-run reflex loop skeleton for synthetic or recorded frames only.
-- [x] Add bounded target-window capture as a dry-run frame source without screenshot artifact writes.
-- [x] Add the first cheap perception adapter and compact world-state projector for deterministic metadata/fixture signals.
-- [x] Add deterministic controller policy and dry-run action projection with confidence-aware fallback and trace metadata.
-- [x] Add action-engine guardrails and replayable command traces before live input.
-- [x] Add latency reports and synthetic replay benchmark modes for reflex traces.
-
-## Remaining Tasks
-
-8. Add slow-path planner hint contracts.
- - Define structured planner hint schema with goal, policy, priorities, regions of interest, avoid actions, confidence, expiry, and source ids.
- - Validate unknown actions, unsafe actions, stale state references, and low-confidence replacements.
- - Add hint expiry and latest-valid-hint selection.
- - Ensure the controller can run for at least 30 seconds without planner output.
-
-9. Add AI harness model registry and router.
- - Define model registry schema with role, provider, model id, endpoint, capabilities, timeouts, prompt version, eval status, docs URL, and rollback id.
- - Route by job type, risk, privacy mode, latency tolerance, and failure history.
- - Keep literal model ids in registry data, not scattered through planner code.
- - Re-check official provider docs before implementation because model names and capabilities change.
-
-10. Add the first provider-neutral AI harness adapter.
- - Start with OpenAI Responses API for slow-path structured planner hints.
- - Read credentials from environment.
- - Default privacy-sensitive calls to `store: false`.
- - Emit model-call trace events with role, provider, model id, prompt version, schema id, latency, timeout, validation status, and source trace/state ids.
- - Add timeout, cancellation, rate-limit, invalid-output, and provider-outage handling that leaves the controller running.
-
-11. Add short-term and target memory.
- - Build short-term run memory in process for current goal, active hints, recent states, failures, user instructions, and safety stops.
- - Add target memory as scoped, source-linked JSONL records.
- - Require TTL or deliberate durable target scope.
- - Add deterministic approval for model-proposed memory writes.
- - Make memory records inspectable and deleteable by target, run, and user scope.
-
-12. Add replay/eval for model and prompt changes.
- - Evaluate planner hints against recorded traces before promotion.
- - Track schema validity, hint acceptance, memory write acceptance, latency, cost, fallback count, and recovery success.
- - Add a model update checklist that records `last_verified_at`, docs URLs, eval suite id, and rollback model id.
-
-13. Integrate slow planner beside the dry-run loop.
- - Trigger planner calls on scene change, low confidence, repeated failure, goal completion, or user instruction.
- - Build compact snapshots from world state, trace summaries, optional screenshots, and memory.
- - Publish only validated hints to the controller.
- - Prove planner latency does not move p95 reflex latency.
-
-14. Enable guarded live-action smoke only after dry-run closeout.
- - Pick one target and one behavior.
- - Run end-to-end dry-run with input disabled and latency report passing.
- - Enable live input only with explicit policy allowance and focus guard.
- - Verify abort and timeout release held input.
- - Record trace evidence for every action.
-
-15. Close out the primary plans.
- - Update supported behavior guides in `docs/guides/`.
- - Move `plans/20-off-the-shelf-run-loop.md` to `plans/done/` when the reflex loop acceptance criteria are supported.
- - Move `plans/19-ai-harness.md` to `plans/done/` when the AI harness acceptance criteria are supported.
- - Move supporting plans to `plans/done/` only if their acceptance criteria are fully satisfied; otherwise update them to describe the remaining future work.
- - Move this master plan to `plans/done/` after both primary plans are closed out.
+## Active Queue
+
+1. Add short-term and target memory.
+ - Build short-term run memory in process for current goal, active hints, recent states, failures, user instructions, and safety stops.
+ - Add target memory as scoped, source-linked JSONL records.
+ - Require TTL or deliberate durable target scope.
+ - Add deterministic approval for model-proposed memory writes.
+ - Make memory records inspectable and deleteable by target, run, and user scope.
+
+2. Add replay/eval for model and prompt changes.
+ - Evaluate planner hints against recorded traces before promotion.
+ - Track schema validity, hint acceptance, memory write acceptance, latency, cost, fallback count, and recovery success.
+ - Add a model update checklist that records `last_verified_at`, docs URLs, eval suite id, and rollback model id.
+
+3. Integrate slow planner beside the dry-run loop.
+ - Trigger planner calls on scene change, low confidence, repeated failure, goal completion, or user instruction.
+ - Build compact snapshots from world state, trace summaries, optional screenshots, and memory.
+ - Publish only validated hints to the controller.
+ - Prove planner latency does not move p95 reflex latency.
+
+4. Enable guarded live-action smoke only after dry-run closeout.
+ - Pick one target and one behavior.
+ - Run end-to-end dry-run with input disabled and latency report passing.
+ - Enable live input only with explicit policy allowance and focus guard.
+ - Verify abort and timeout release held input.
+ - Record trace evidence for every action.
+
+5. Close out the primary plans.
+ - Update supported behavior guides in `docs/guides/`.
+ - Move `plans/20-off-the-shelf-run-loop.md` to `plans/done/` when the reflex loop acceptance criteria are supported.
+ - Move `plans/19-ai-harness.md` to `plans/done/` when the AI harness acceptance criteria are supported.
+ - Move supporting plans to `plans/done/` only if their acceptance criteria are fully satisfied; otherwise update them to describe the remaining future work.
+ - Move this master plan to `plans/done/` after both primary plans are closed out.
## What Should Be Done Next
-Start with task 8: add slow-path planner hint contracts.
+Start with active task 1: add short-term and target memory.
-This is the right next slice because the current runtime now has lifecycle, event, artifact, manual capture, reflex trace, shared hot-loop contracts, a synthetic/recorded-frame dry-run skeleton, bounded selected-window frame capture, cheap deterministic perception, a dry-run controller policy, action-engine guardrails, and latency reports. It still needs validated, expiring slow-path planner hints before the AI harness can safely influence controller behavior.
+This is the right next slice because the current boundary has a dry-run reflex path, guardrails, latency reporting, validated planner hints, model routing, and the first slow-path adapter. It still needs scoped short-term and target memory before planner hints and future memory writes can be source-linked, inspectable, and deleteable.
## Closeout Criteria