Skip to content

Open source CapCut alternative.

TypeScript

Refine guarded live smoke and ground plans in reality

David Le9bebfbb562af
diff --git a/apps/Donkey/Sources/DonkeyRuntime/ActionEngineGuardrails.swift b/apps/Donkey/Sources/DonkeyRuntime/ActionEngineGuardrails.swift
index 316ae7c1..3ef30b47 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/ActionEngineGuardrails.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/ActionEngineGuardrails.swift
@@ -52,6 +52,7 @@ public struct ActionEngineCommand: Codable, Equatable, Sendable {
public enum ActionEngineCommandDecision: Codable, Equatable, Sendable {
case projectedDryRun
+ case executedLive
case denied(reason: String)
}
@@ -112,6 +113,26 @@ public protocol ActionEngineFocusGuard: Sendable {
func targetIsSafeForInput(targetID: String) async -> Bool
}
+public struct ActionEngineInputBackendResult: Equatable, Sendable {
+ public var executed: Bool
+ public var completedAt: RunTraceTimestamp
+ public var metadata: [String: String]
+
+ public init(
+ executed: Bool,
+ completedAt: RunTraceTimestamp,
+ metadata: [String: String] = [:]
+ ) {
+ self.executed = executed
+ self.completedAt = completedAt
+ self.metadata = metadata
+ }
+}
+
+public protocol ActionEngineInputBackend: Sendable {
+ func execute(_ command: ActionEngineCommand) async -> ActionEngineInputBackendResult
+}
+
public struct AlwaysSafeActionEngineFocusGuard: ActionEngineFocusGuard {
public init() {}
@@ -120,19 +141,36 @@ public struct AlwaysSafeActionEngineFocusGuard: ActionEngineFocusGuard {
}
}
+public struct UnavailableActionEngineInputBackend: ActionEngineInputBackend {
+ public init() {}
+
+ public func execute(_ command: ActionEngineCommand) async -> ActionEngineInputBackendResult {
+ ActionEngineInputBackendResult(
+ executed: false,
+ completedAt: command.issuedAt,
+ metadata: [
+ "liveInputBackend": "notImplemented"
+ ]
+ )
+ }
+}
+
public actor ActionEngineGuardrail {
private let configuration: ActionEngineConfiguration
private let focusGuard: any ActionEngineFocusGuard
+ private let inputBackend: any ActionEngineInputBackend
private var traces: [ActionEngineCommandTrace] = []
private var heldCommandIDs: Set<String> = []
private var lastAcceptedCommandAt: RunTraceTimestamp?
public init(
configuration: ActionEngineConfiguration = ActionEngineConfiguration(),
- focusGuard: any ActionEngineFocusGuard = AlwaysSafeActionEngineFocusGuard()
+ focusGuard: any ActionEngineFocusGuard = AlwaysSafeActionEngineFocusGuard(),
+ inputBackend: any ActionEngineInputBackend = UnavailableActionEngineInputBackend()
) {
self.configuration = configuration
self.focusGuard = focusGuard
+ self.inputBackend = inputBackend
}
@discardableResult
@@ -214,17 +252,36 @@ public actor ActionEngineGuardrail {
heldCommandIDs.insert(command.id)
}
+ guard configuration.liveInputEnabled else {
+ return appendTrace(
+ command: command,
+ decision: .projectedDryRun,
+ focusGuardPassed: true,
+ permissionDecision: permissionDecision,
+ rateLimited: false,
+ releaseAll: false,
+ metadata: [
+ "heldInputCount": String(heldCommandIDs.count),
+ "liveInputBackend": "disabled"
+ ]
+ )
+ }
+
+ let backendResult = await inputBackend.execute(command)
+ var metadata = backendResult.metadata
+ metadata["heldInputCount"] = String(heldCommandIDs.count)
+ metadata["liveInputCompletedAt"] = String(backendResult.completedAt.monotonicUptimeNanoseconds)
+
return appendTrace(
command: command,
- decision: .projectedDryRun,
+ decision: backendResult.executed
+ ? .executedLive
+ : .denied(reason: "live input backend did not execute"),
focusGuardPassed: true,
permissionDecision: permissionDecision,
rateLimited: false,
releaseAll: false,
- metadata: [
- "heldInputCount": String(heldCommandIDs.count),
- "liveInputBackend": "notImplemented"
- ]
+ metadata: metadata
)
}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/DryRunReflexLoop.swift b/apps/Donkey/Sources/DonkeyRuntime/DryRunReflexLoop.swift
index dd603bfb..75988f95 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/DryRunReflexLoop.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/DryRunReflexLoop.swift
@@ -87,6 +87,7 @@ public struct DryRunReflexLoop: Sendable {
public var controllerPolicy: any DryRunControllerPolicy
public var actionProjector: any DryRunActionProjecting
public var worldStateProjector: any DryRunWorldStateProjecting
+ public var slowPlannerSidecar: DryRunSlowPlannerSidecar?
public var staleSignalThresholdMS: Double
public init(
@@ -96,6 +97,7 @@ public struct DryRunReflexLoop: Sendable {
worldStateProjector: (any DryRunWorldStateProjecting)? = nil,
controllerPolicy: any DryRunControllerPolicy = DeterministicControllerPolicy(),
actionProjector: any DryRunActionProjecting = DryRunActionProjector(),
+ slowPlannerSidecar: DryRunSlowPlannerSidecar? = nil,
staleSignalThresholdMS: Double = 250
) {
self.coordinator = coordinator
@@ -105,6 +107,7 @@ public struct DryRunReflexLoop: Sendable {
self.actionProjector = actionProjector
self.worldStateProjector = worldStateProjector
?? HotLoopWorldStateProjector(staleSignalThresholdMS: staleSignalThresholdMS)
+ self.slowPlannerSidecar = slowPlannerSidecar
self.staleSignalThresholdMS = staleSignalThresholdMS
}
@@ -258,6 +261,15 @@ public struct DryRunReflexLoop: Sendable {
)
await coordinator.appendReflexTrace(trace)
+ if let slowPlannerSidecar {
+ Task {
+ await slowPlannerSidecar.observe(
+ worldState: worldState,
+ action: action,
+ trace: trace
+ )
+ }
+ }
return (worldState, action)
}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/GuardedLiveActionSmoke.swift b/apps/Donkey/Sources/DonkeyRuntime/GuardedLiveActionSmoke.swift
new file mode 100644
index 00000000..cb33f36d
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/GuardedLiveActionSmoke.swift
@@ -0,0 +1,157 @@
+import DonkeyContracts
+import Foundation
+
+public enum GuardedLiveActionSmokeStatus: String, Codable, Equatable, Sendable {
+ case executed
+ case skipped
+ case denied
+}
+
+public struct GuardedLiveActionSmokeResult: Equatable, Sendable {
+ public var status: GuardedLiveActionSmokeStatus
+ public var reason: String
+ public var commandTrace: ActionEngineCommandTrace?
+ public var metadata: [String: String]
+
+ public init(
+ status: GuardedLiveActionSmokeStatus,
+ reason: String,
+ commandTrace: ActionEngineCommandTrace? = nil,
+ metadata: [String: String] = [:]
+ ) {
+ self.status = status
+ self.reason = reason
+ self.commandTrace = commandTrace
+ self.metadata = metadata
+ }
+}
+
+public struct GuardedLiveActionSmokeRunner: Sendable {
+ public var actionEngine: ActionEngineGuardrail
+
+ public init(actionEngine: ActionEngineGuardrail) {
+ self.actionEngine = actionEngine
+ }
+
+ public func run(
+ dryRunResult: DryRunReflexLoopResult,
+ latencyReport: ReflexLatencyReport,
+ session: RunSession,
+ issuedAt: RunTraceTimestamp
+ ) async -> GuardedLiveActionSmokeResult {
+ guard latencyReport.traceCount > 0,
+ latencyReport.softwareLoopMS.p95 != nil
+ else {
+ return GuardedLiveActionSmokeResult(
+ status: .skipped,
+ reason: "dry-run latency report is missing p95 evidence",
+ metadata: reportMetadata(latencyReport)
+ )
+ }
+
+ guard let state = dryRunResult.latestWorldState,
+ let action = dryRunResult.latestAction
+ else {
+ return GuardedLiveActionSmokeResult(
+ status: .skipped,
+ reason: "dry-run loop did not produce state and action"
+ )
+ }
+
+ guard action.metadata["fallback"] != "true" else {
+ return GuardedLiveActionSmokeResult(
+ status: .skipped,
+ reason: "latest dry-run action is a fallback",
+ metadata: [
+ "fallbackReason": action.metadata["fallbackReason"] ?? "unknown"
+ ]
+ )
+ }
+
+ guard let command = Self.command(
+ for: action,
+ state: state,
+ targetID: session.targetID,
+ issuedAt: issuedAt
+ ) else {
+ return GuardedLiveActionSmokeResult(
+ status: .skipped,
+ reason: "latest dry-run action cannot be mapped to a live command",
+ metadata: [
+ "action.kind": action.kind.rawValue
+ ]
+ )
+ }
+
+ let trace = await actionEngine.handle(
+ command,
+ permissionPolicy: session.permissionPolicy
+ )
+
+ switch trace.decision {
+ case .executedLive:
+ return GuardedLiveActionSmokeResult(
+ status: .executed,
+ reason: "guarded live action executed",
+ commandTrace: trace,
+ metadata: reportMetadata(latencyReport)
+ )
+ case .projectedDryRun:
+ return GuardedLiveActionSmokeResult(
+ status: .skipped,
+ reason: "action engine projected dry-run instead of live input",
+ commandTrace: trace,
+ metadata: reportMetadata(latencyReport)
+ )
+ case .denied(let reason):
+ return GuardedLiveActionSmokeResult(
+ status: .denied,
+ reason: reason,
+ commandTrace: trace,
+ metadata: reportMetadata(latencyReport)
+ )
+ }
+ }
+
+ public static func command(
+ for action: HotLoopControllerAction,
+ state: HotLoopWorldState,
+ targetID: String,
+ issuedAt: RunTraceTimestamp
+ ) -> ActionEngineCommand? {
+ switch action.kind {
+ case .tapTarget, .focusWindow, .switchTab, .activateCandidate:
+ guard let target = action.target else { return nil }
+ return ActionEngineCommand(
+ id: "live-smoke-\(action.id)",
+ traceID: action.traceID,
+ targetID: targetID,
+ stateID: state.id,
+ actionID: action.id,
+ kind: .tap,
+ issuedAt: issuedAt,
+ targetBounds: target,
+ metadata: [
+ "sourceActionKind": action.kind.rawValue,
+ "smoke": "guardedLiveAction"
+ ].merging(action.metadata) { current, _ in current }
+ )
+ case .observe, .wait, .openAppSwitcher:
+ return nil
+ }
+ }
+
+ private func reportMetadata(_ report: ReflexLatencyReport) -> [String: String] {
+ [
+ "dryRun.traceCount": String(report.traceCount),
+ "dryRun.softwareLoopP95MS": format(report.softwareLoopMS.p95),
+ "dryRun.droppedFrameCount": String(report.droppedFrameCount),
+ "dryRun.staleActionCount": String(report.staleActionCount)
+ ]
+ }
+
+ private func format(_ value: Double?) -> String {
+ guard let value else { return "unknown" }
+ return String(format: "%.2f", value)
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/RunCoordinator.swift b/apps/Donkey/Sources/DonkeyRuntime/RunCoordinator.swift
index 57c94d81..2b0a4a30 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/RunCoordinator.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/RunCoordinator.swift
@@ -329,7 +329,9 @@ private extension ReflexLatencyBreakdown {
values["latency.preprocessMS"] = preprocessMS.map { String($0) }
values["latency.modelInferenceMS"] = modelInferenceMS.map { String($0) }
values["latency.perceptionMS"] = perceptionMS.map { String($0) }
+ values["latency.stateUpdateMS"] = stateUpdateMS.map { String($0) }
values["latency.decisionMS"] = decisionMS.map { String($0) }
+ values["latency.actionProjectionMS"] = actionProjectionMS.map { String($0) }
values["latency.inputMS"] = inputMS.map { String($0) }
values["latency.softwareLoopMS"] = softwareLoopMS.map { String($0) }
values["latency.frameAgeMS"] = frameAgeMS.map { String($0) }
diff --git a/apps/Donkey/Sources/DonkeyRuntime/SlowPlannerSidecar.swift b/apps/Donkey/Sources/DonkeyRuntime/SlowPlannerSidecar.swift
new file mode 100644
index 00000000..ad270008
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/SlowPlannerSidecar.swift
@@ -0,0 +1,442 @@
+import DonkeyContracts
+import Foundation
+
+public enum SlowPlannerTriggerReason: String, Codable, Equatable, Hashable, Sendable {
+ case sceneChanged
+ case lowConfidence
+ case repeatedFailure
+ case goalCompleted
+ case userInstruction
+}
+
+public struct SlowPlannerScreenshotReference: Codable, Equatable, Sendable {
+ public var artifactID: String
+ public var summary: String
+ public var metadata: [String: String]
+
+ public init(
+ artifactID: String,
+ summary: String,
+ metadata: [String: String] = [:]
+ ) {
+ self.artifactID = artifactID
+ self.summary = summary
+ self.metadata = metadata
+ }
+}
+
+public struct SlowPlannerTraceSummary: Codable, Equatable, Sendable {
+ public var traceID: String
+ public var frameID: String
+ public var stateID: String
+ public var actionID: String?
+ public var actionKind: String?
+ public var confidence: Double?
+ public var fallbackReason: String?
+ public var softwareLoopMS: Double?
+
+ public init(
+ traceID: String,
+ frameID: String,
+ stateID: String,
+ actionID: String? = nil,
+ actionKind: String? = nil,
+ confidence: Double? = nil,
+ fallbackReason: String? = nil,
+ softwareLoopMS: Double? = nil
+ ) {
+ self.traceID = traceID
+ self.frameID = frameID
+ self.stateID = stateID
+ self.actionID = actionID
+ self.actionKind = actionKind
+ self.confidence = confidence
+ self.fallbackReason = fallbackReason
+ self.softwareLoopMS = softwareLoopMS
+ }
+}
+
+public struct SlowPlannerSnapshot: Codable, Equatable, Sendable {
+ public var id: String
+ public var triggerReasons: [SlowPlannerTriggerReason]
+ public var context: RunContextPackage
+ public var latestWorldState: HotLoopWorldState
+ public var latestAction: HotLoopControllerAction
+ public var traceSummaries: [SlowPlannerTraceSummary]
+ public var screenshotReferences: [SlowPlannerScreenshotReference]
+ public var metadata: [String: String]
+
+ public init(
+ id: String,
+ triggerReasons: [SlowPlannerTriggerReason],
+ context: RunContextPackage,
+ latestWorldState: HotLoopWorldState,
+ latestAction: HotLoopControllerAction,
+ traceSummaries: [SlowPlannerTraceSummary],
+ screenshotReferences: [SlowPlannerScreenshotReference] = [],
+ metadata: [String: String] = [:]
+ ) {
+ self.id = id
+ self.triggerReasons = triggerReasons
+ self.context = context
+ self.latestWorldState = latestWorldState
+ self.latestAction = latestAction
+ self.traceSummaries = traceSummaries
+ self.screenshotReferences = screenshotReferences
+ self.metadata = metadata
+ }
+}
+
+public struct SlowPlannerHintGenerationResult: Equatable, Sendable {
+ public var hint: StructuredPlannerHint?
+ public var metadata: [String: String]
+
+ public init(
+ hint: StructuredPlannerHint?,
+ metadata: [String: String] = [:]
+ ) {
+ self.hint = hint
+ self.metadata = metadata
+ }
+}
+
+public protocol SlowPlannerHintGenerating: Sendable {
+ func generatePlannerHint(
+ snapshot: SlowPlannerSnapshot
+ ) async -> SlowPlannerHintGenerationResult
+}
+
+public struct SlowPlannerTriggerPolicy: Equatable, Sendable {
+ public var lowConfidenceThreshold: Double
+ public var repeatedFailureThreshold: Int
+ public var triggerOnFirstScene: Bool
+
+ public init(
+ lowConfidenceThreshold: Double = 0.5,
+ repeatedFailureThreshold: Int = 2,
+ triggerOnFirstScene: Bool = true
+ ) {
+ self.lowConfidenceThreshold = lowConfidenceThreshold
+ self.repeatedFailureThreshold = max(1, repeatedFailureThreshold)
+ self.triggerOnFirstScene = triggerOnFirstScene
+ }
+
+ public func reasons(
+ state: HotLoopWorldState,
+ action: HotLoopControllerAction,
+ previousSceneSignature: String?,
+ consecutiveFailureCount: Int,
+ recentFailures: [RunFailureSummary],
+ userInstruction: String?
+ ) -> [SlowPlannerTriggerReason] {
+ var reasons: [SlowPlannerTriggerReason] = []
+ let signature = sceneSignature(for: state)
+
+ if previousSceneSignature == nil {
+ if triggerOnFirstScene {
+ reasons.append(.sceneChanged)
+ }
+ } else if previousSceneSignature != signature {
+ reasons.append(.sceneChanged)
+ }
+
+ if state.confidence < lowConfidenceThreshold
+ || action.confidence < lowConfidenceThreshold
+ || action.metadata["fallbackReason"] == "lowConfidence" {
+ reasons.append(.lowConfidence)
+ }
+
+ if consecutiveFailureCount >= repeatedFailureThreshold
+ || recentFailures.count >= repeatedFailureThreshold {
+ reasons.append(.repeatedFailure)
+ }
+
+ if action.metadata["goalCompleted"] == "true"
+ || action.metadata["fallbackReason"] == "alreadyFocused" {
+ reasons.append(.goalCompleted)
+ }
+
+ if userInstruction?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false {
+ reasons.append(.userInstruction)
+ }
+
+ return Array(Set(reasons)).sorted { $0.rawValue < $1.rawValue }
+ }
+
+ public func sceneSignature(for state: HotLoopWorldState) -> String {
+ [
+ state.targetID,
+ String(format: "%.2f", state.confidence),
+ state.signalSummaries
+ .map { "\($0.kind):\($0.observationCount)" }
+ .joined(separator: "|"),
+ state.actionAffordances
+ .map { "\($0.kind.rawValue):\($0.metadata["localNavigation.candidateID"] ?? $0.id)" }
+ .joined(separator: "|"),
+ state.metadata["localNavigation.focusedCandidateID"] ?? "",
+ state.metadata["localNavigation.frontmostCandidateID"] ?? ""
+ ].joined(separator: "::")
+ }
+}
+
+public actor ValidatedPlannerHintBus {
+ private var hints: [StructuredPlannerHint] = []
+ private var validationResults: [PlannerHintValidationResult] = []
+ private let capacity: Int
+
+ public init(capacity: Int = 10) {
+ self.capacity = max(1, capacity)
+ }
+
+ @discardableResult
+ public func publishIfValid(
+ _ hint: StructuredPlannerHint,
+ context: PlannerHintValidationContext
+ ) -> PlannerHintValidationResult {
+ let result = PlannerHintValidator.validate(hint, context: context)
+ validationResults.append(result)
+ validationResults = Array(validationResults.suffix(capacity))
+
+ if result.isValid {
+ hints.append(hint)
+ hints = Array(hints.suffix(capacity))
+ }
+
+ return result
+ }
+
+ public func latestValidHint(
+ context: PlannerHintValidationContext
+ ) -> StructuredPlannerHint? {
+ PlannerHintSelector.latestValidHint(
+ from: hints,
+ context: context
+ )
+ .latestValidHint
+ }
+
+ public func summaryHints(
+ now: RunTraceTimestamp
+ ) -> [RunPlannerHint] {
+ hints
+ .filter { !$0.isExpired(at: now) }
+ .map { $0.summaryHint(isValid: true) }
+ }
+
+ public func allHints() -> [StructuredPlannerHint] {
+ hints
+ }
+
+ public func allValidationResults() -> [PlannerHintValidationResult] {
+ validationResults
+ }
+}
+
+public struct PlannerHintAwareControllerPolicy: DryRunControllerPolicy {
+ public var base: any DryRunControllerPolicy
+ public var hintBus: ValidatedPlannerHintBus
+ public var unsafeActions: Set<HotLoopActionKind>
+ public var minimumConfidence: Double
+
+ public var name: String {
+ "\(base.name)+validated-planner-hints"
+ }
+
+ public init(
+ base: any DryRunControllerPolicy,
+ hintBus: ValidatedPlannerHintBus,
+ unsafeActions: Set<HotLoopActionKind> = [],
+ minimumConfidence: Double = 0.3
+ ) {
+ self.base = base
+ self.hintBus = hintBus
+ self.unsafeActions = unsafeActions
+ self.minimumConfidence = minimumConfidence
+ }
+
+ public func decide(state: HotLoopWorldState) async -> HotLoopControllerAction {
+ var action = await base.decide(state: state)
+ let context = PlannerHintValidationContext(
+ currentStateID: state.id,
+ unsafeActions: unsafeActions,
+ minimumConfidence: minimumConfidence,
+ now: state.observedAt
+ )
+
+ guard let hint = await hintBus.latestValidHint(context: context) else {
+ return action
+ }
+
+ action.plannerHintID = hint.id
+ action.metadata["plannerHintID"] = hint.id
+ action.metadata["plannerHintPolicyName"] = hint.policyName
+ action.metadata["plannerHintPreferredAction"] = String(hint.preferredActions.contains(action.kind))
+ action.metadata["plannerHintAvoidedAction"] = String(hint.avoidActions.contains(action.kind))
+ return action
+ }
+}
+
+public actor DryRunSlowPlannerSidecar {
+ private let coordinator: RunCoordinator
+ private let memory: InMemoryRunMemory?
+ private let hintBus: ValidatedPlannerHintBus
+ private let planner: any SlowPlannerHintGenerating
+ private let triggerPolicy: SlowPlannerTriggerPolicy
+ private let unsafeActions: Set<HotLoopActionKind>
+ private let screenshotReferences: [SlowPlannerScreenshotReference]
+ private let maxTraceSummaries: Int
+
+ private var previousSceneSignature: String?
+ private var consecutiveFailureCount = 0
+ private var snapshotCount = 0
+ private var plannerCallCount = 0
+ private var publishedHintCount = 0
+
+ public init(
+ coordinator: RunCoordinator,
+ memory: InMemoryRunMemory? = nil,
+ hintBus: ValidatedPlannerHintBus,
+ planner: any SlowPlannerHintGenerating,
+ triggerPolicy: SlowPlannerTriggerPolicy = SlowPlannerTriggerPolicy(),
+ unsafeActions: Set<HotLoopActionKind> = [],
+ screenshotReferences: [SlowPlannerScreenshotReference] = [],
+ maxTraceSummaries: Int = 5
+ ) {
+ self.coordinator = coordinator
+ self.memory = memory
+ self.hintBus = hintBus
+ self.planner = planner
+ self.triggerPolicy = triggerPolicy
+ self.unsafeActions = unsafeActions
+ self.screenshotReferences = screenshotReferences
+ self.maxTraceSummaries = max(1, maxTraceSummaries)
+ }
+
+ public func observe(
+ worldState: HotLoopWorldState,
+ action: HotLoopControllerAction,
+ trace: ReflexTraceRecord,
+ userInstruction: String? = nil
+ ) async {
+ let now = trace.timestamps.inputExecuted
+ ?? trace.timestamps.actionEnqueued
+ ?? worldState.observedAt
+ let memorySnapshot = await memory?.snapshot(now: now)
+ let recentFailures = memorySnapshot?.recentFailures ?? []
+ updateFailureCounter(action: action)
+
+ let reasons = triggerPolicy.reasons(
+ state: worldState,
+ action: action,
+ previousSceneSignature: previousSceneSignature,
+ consecutiveFailureCount: consecutiveFailureCount,
+ recentFailures: recentFailures,
+ userInstruction: userInstruction
+ )
+ previousSceneSignature = triggerPolicy.sceneSignature(for: worldState)
+ guard !reasons.isEmpty else { return }
+
+ let activeHints = await hintBus.summaryHints(now: now)
+ let summary = Self.worldStateSummary(for: worldState)
+ await memory?.rememberState(summary)
+
+ guard let context = await coordinator.buildContext(
+ latestWorldState: summary,
+ activeHints: activeHints,
+ recentFailures: recentFailures,
+ memorySnapshot: memorySnapshot
+ ) else {
+ return
+ }
+
+ let traces = await coordinator.reflexTraces()
+ snapshotCount += 1
+ let snapshot = SlowPlannerSnapshot(
+ id: "slow-planner-snapshot-\(snapshotCount)",
+ triggerReasons: reasons,
+ context: context,
+ latestWorldState: worldState,
+ latestAction: action,
+ traceSummaries: Self.traceSummaries(
+ from: traces.isEmpty ? [trace] : traces,
+ limit: maxTraceSummaries
+ ),
+ screenshotReferences: screenshotReferences,
+ metadata: [
+ "rawPixelsExposed": "false",
+ "triggerReasons": reasons.map(\.rawValue).joined(separator: ",")
+ ]
+ )
+
+ let decision = await coordinator.recordToolCall(
+ capability: .model,
+ toolName: "slow-planner-sidecar"
+ )
+ guard decision.isAllowed else { return }
+
+ plannerCallCount += 1
+ let result = await planner.generatePlannerHint(snapshot: snapshot)
+ guard let hint = result.hint else { return }
+
+ let validation = await hintBus.publishIfValid(
+ hint,
+ context: PlannerHintValidationContext(
+ currentStateID: worldState.id,
+ unsafeActions: unsafeActions,
+ now: now
+ )
+ )
+
+ if validation.isValid {
+ publishedHintCount += 1
+ let hints = await hintBus.summaryHints(now: now)
+ await memory?.setActiveHints(hints)
+ }
+ }
+
+ public func stats() -> (snapshotCount: Int, plannerCallCount: Int, publishedHintCount: Int) {
+ (snapshotCount, plannerCallCount, publishedHintCount)
+ }
+
+ private func updateFailureCounter(action: HotLoopControllerAction) {
+ if action.metadata["fallback"] == "true",
+ action.metadata["fallbackReason"] != "alreadyFocused" {
+ consecutiveFailureCount += 1
+ } else {
+ consecutiveFailureCount = 0
+ }
+ }
+
+ private static func worldStateSummary(for state: HotLoopWorldState) -> RunWorldStateSummary {
+ let signalSummary = state.signalSummaries
+ .map { "\($0.kind):\($0.observationCount)" }
+ .joined(separator: ",")
+ let affordanceSummary = state.actionAffordances
+ .map(\.kind.rawValue)
+ .joined(separator: ",")
+
+ return RunWorldStateSummary(
+ stateID: state.id,
+ summary: "confidence=\(state.confidence); signals=[\(signalSummary)]; affordances=[\(affordanceSummary)]",
+ confidence: state.confidence
+ )
+ }
+
+ private static func traceSummaries(
+ from traces: [ReflexTraceRecord],
+ limit: Int
+ ) -> [SlowPlannerTraceSummary] {
+ traces.suffix(limit).map { trace in
+ SlowPlannerTraceSummary(
+ traceID: trace.traceID,
+ frameID: trace.frameID,
+ stateID: trace.stateID,
+ actionID: trace.actionID,
+ actionKind: trace.metadata["action.kind"],
+ confidence: trace.confidence,
+ fallbackReason: trace.metadata["fallbackReason"],
+ softwareLoopMS: trace.latencyBreakdown.softwareLoopMS
+ )
+ }
+ }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/ActionEngineGuardrailTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ActionEngineGuardrailTests.swift
index 0d1f2b3e..f456231e 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/ActionEngineGuardrailTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ActionEngineGuardrailTests.swift
@@ -31,7 +31,30 @@ struct ActionEngineGuardrailTests {
#expect(trace.executed == false)
#expect(trace.liveInputEnabled == false)
#expect(trace.focusGuardPassed == true)
- #expect(trace.metadata["liveInputBackend"] == "notImplemented")
+ #expect(trace.metadata["liveInputBackend"] == "disabled")
+ }
+
+ @Test
+ func liveInputRequiresExplicitConfigurationPolicyAndFocusGuard() async {
+ let backend = RecordingInputBackend()
+ let engine = ActionEngineGuardrail(
+ configuration: ActionEngineConfiguration(liveInputEnabled: true),
+ inputBackend: backend
+ )
+ let policy = ToolCallPolicy(deniedCapabilities: [])
+
+ let trace = await engine.handle(
+ command(id: "tap-live", issuedAtMS: 0),
+ permissionPolicy: policy
+ )
+
+ #expect(trace.decision == .executedLive)
+ #expect(trace.executed == true)
+ #expect(trace.liveInputEnabled == true)
+ #expect(trace.focusGuardPassed == true)
+ #expect(trace.permissionDecision.isAllowed == true)
+ #expect(trace.metadata["liveInputBackend"] == "recording")
+ #expect(await backend.executedCommandIDs() == ["tap-live"])
}
@Test
@@ -140,3 +163,22 @@ private struct DenyingFocusGuard: ActionEngineFocusGuard {
false
}
}
+
+private actor RecordingInputBackend: ActionEngineInputBackend {
+ private var commandIDs: [String] = []
+
+ func execute(_ command: ActionEngineCommand) async -> ActionEngineInputBackendResult {
+ commandIDs.append(command.id)
+ return ActionEngineInputBackendResult(
+ executed: true,
+ completedAt: command.issuedAt,
+ metadata: [
+ "liveInputBackend": "recording"
+ ]
+ )
+ }
+
+ func executedCommandIDs() -> [String] {
+ commandIDs
+ }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/GuardedLiveActionSmokeTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/GuardedLiveActionSmokeTests.swift
new file mode 100644
index 00000000..31f8c8fc
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/GuardedLiveActionSmokeTests.swift
@@ -0,0 +1,326 @@
+import DonkeyContracts
+@testable import DonkeyRuntime
+import Foundation
+import Testing
+
+@Suite
+struct GuardedLiveActionSmokeTests {
+ @Test
+ func localNavigationLiveSmokeRequiresDryRunReportPolicyAndFocusGuard() async {
+ let dryRunCoordinator = RunCoordinator()
+ let dryRunSession = RunSession(
+ id: "dry-run-session",
+ userGoal: "focus Code",
+ targetID: "local-navigation"
+ )
+ let source = LocalNavigationMetadataFrameSource(
+ windowResolver: MacWindowResolver(
+ provider: FixtureWindowProvider(
+ windows: [
+ providerWindow(
+ windowID: 100,
+ processID: 1000,
+ appName: "Code",
+ bundleIdentifier: "com.microsoft.VSCode",
+ title: "Donkey"
+ ),
+ providerWindow(
+ windowID: 200,
+ processID: 2000,
+ appName: "Safari",
+ bundleIdentifier: "com.apple.Safari",
+ title: "Docs"
+ )
+ ],
+ frontmostProcessID: 2000,
+ focusedWindowID: 200
+ )
+ ),
+ timestampProvider: FixtureTimestampProvider(),
+ request: LocalNavigationMetadataFrameRequest(
+ traceID: "trace-local-nav-smoke",
+ requestedBundleIdentifier: "com.microsoft.VSCode"
+ )
+ )
+ let dryRunLoop = DryRunReflexLoop(
+ coordinator: dryRunCoordinator,
+ frameSource: source,
+ perceptionAdapter: LocalNavigationDryRunPerceptionAdapter(),
+ worldStateProjector: LocalNavigationDryRunWorldStateProjector(),
+ controllerPolicy: LocalNavigationDryRunControllerPolicy()
+ )
+
+ let dryRunResult = await dryRunLoop.run(session: dryRunSession)
+ let report = await ReflexLatencyReportBuilder.build(
+ from: dryRunCoordinator.reflexTraces(),
+ droppedFrameCount: dryRunResult.droppedFrameCount
+ )
+
+ #expect(dryRunSession.permissionPolicy.decision(for: .input).isAllowed == false)
+ #expect(report.traceCount == 1)
+ #expect(report.softwareLoopMS.p95 != nil)
+ #expect(dryRunResult.latestAction?.kind == .focusWindow)
+
+ let backend = RecordingSmokeInputBackend()
+ let runner = GuardedLiveActionSmokeRunner(
+ actionEngine: ActionEngineGuardrail(
+ configuration: ActionEngineConfiguration(liveInputEnabled: true),
+ focusGuard: AllowingFocusGuard(),
+ inputBackend: backend
+ )
+ )
+ let liveSession = RunSession(
+ id: "live-smoke-session",
+ userGoal: "focus Code",
+ targetID: "local-navigation",
+ permissionPolicy: ToolCallPolicy(deniedCapabilities: [])
+ )
+
+ let smoke = await runner.run(
+ dryRunResult: dryRunResult,
+ latencyReport: report,
+ session: liveSession,
+ issuedAt: timestamp(100)
+ )
+
+ #expect(smoke.status == .executed)
+ #expect(smoke.commandTrace?.decision == .executedLive)
+ #expect(smoke.commandTrace?.executed == true)
+ #expect(smoke.commandTrace?.focusGuardPassed == true)
+ #expect(smoke.commandTrace?.command.kind == .tap)
+ #expect(smoke.commandTrace?.command.metadata["sourceActionKind"] == "focusWindow")
+ #expect(await backend.executedCommandIDs() == ["live-smoke-action-local-nav-state-trace-local-nav-smoke"])
+ }
+
+ @Test
+ func liveSmokeIsDeniedWithoutExplicitInputPolicy() async {
+ let state = worldState()
+ let action = action(state: state)
+ let result = DryRunReflexLoopResult(
+ processedFrameCount: 1,
+ droppedFrameCount: 0,
+ latestWorldState: state,
+ latestAction: action
+ )
+ let report = reportForDryRun()
+ let backend = RecordingSmokeInputBackend()
+ let runner = GuardedLiveActionSmokeRunner(
+ actionEngine: ActionEngineGuardrail(
+ configuration: ActionEngineConfiguration(liveInputEnabled: true),
+ inputBackend: backend
+ )
+ )
+
+ let smoke = await runner.run(
+ dryRunResult: result,
+ latencyReport: report,
+ session: RunSession(id: "session-denied", userGoal: "focus", targetID: "target-1"),
+ issuedAt: timestamp(100)
+ )
+
+ #expect(smoke.status == .denied)
+ #expect(smoke.commandTrace?.decision == .denied(reason: "input permission denied"))
+ #expect(await backend.executedCommandIDs().isEmpty)
+ }
+
+ @Test
+ func liveSmokeIsDeniedWhenFocusGuardFailsAndReleasesHeldInputOnAbort() async {
+ let state = worldState()
+ let action = action(state: state)
+ let engine = ActionEngineGuardrail(
+ configuration: ActionEngineConfiguration(liveInputEnabled: true),
+ focusGuard: DenyingSmokeFocusGuard(),
+ inputBackend: RecordingSmokeInputBackend()
+ )
+ let runner = GuardedLiveActionSmokeRunner(actionEngine: engine)
+ let liveSession = RunSession(
+ id: "session-focus-denied",
+ userGoal: "focus",
+ targetID: "target-1",
+ permissionPolicy: ToolCallPolicy(deniedCapabilities: [])
+ )
+
+ let smoke = await runner.run(
+ dryRunResult: DryRunReflexLoopResult(
+ processedFrameCount: 1,
+ droppedFrameCount: 0,
+ latestWorldState: state,
+ latestAction: action
+ ),
+ latencyReport: reportForDryRun(),
+ session: liveSession,
+ issuedAt: timestamp(100)
+ )
+ #expect(smoke.status == .denied)
+ #expect(smoke.commandTrace?.decision == .denied(reason: "focus guard failed"))
+
+ let holdingEngine = ActionEngineGuardrail(
+ configuration: ActionEngineConfiguration(liveInputEnabled: true),
+ inputBackend: RecordingSmokeInputBackend()
+ )
+ _ = await holdingEngine.handle(
+ ActionEngineCommand(
+ id: "hold-1",
+ traceID: "trace-1",
+ targetID: "target-1",
+ kind: .key,
+ issuedAt: timestamp(110),
+ key: "Command",
+ holdDurationMS: 50
+ ),
+ permissionPolicy: ToolCallPolicy(deniedCapabilities: [])
+ )
+ #expect(await holdingEngine.heldInputCount() == 1)
+
+ let release = await holdingEngine.releaseAll(
+ traceID: "trace-1",
+ targetID: "target-1",
+ issuedAt: timestamp(120)
+ )
+
+ #expect(release.releaseAll == true)
+ #expect(release.metadata["heldInputReleased"] == "true")
+ #expect(await holdingEngine.heldInputCount() == 0)
+ }
+
+ private func worldState() -> HotLoopWorldState {
+ HotLoopWorldState(
+ id: "state-1",
+ traceID: "trace-1",
+ frameID: "frame-1",
+ targetID: "target-1",
+ observedAt: timestamp(10),
+ signalSummaries: [
+ HotLoopPerceptionSignalSummary(
+ id: "signal-1",
+ kind: "localNavigationMetadata",
+ confidence: 0.9,
+ observationCount: 1
+ )
+ ],
+ actionAffordances: [],
+ confidence: 0.9
+ )
+ }
+
+ private func action(state: HotLoopWorldState) -> HotLoopControllerAction {
+ HotLoopControllerAction(
+ id: "action-1",
+ traceID: state.traceID,
+ frameID: state.frameID,
+ stateID: state.id,
+ kind: .focusWindow,
+ target: HotLoopRect(x: 10, y: 20, width: 300, height: 200, space: .screen),
+ policyName: "local-navigation-controller-v1",
+ confidence: 0.9,
+ rationale: "focus target",
+ metadata: ["fallback": "false"]
+ )
+ }
+
+ private func reportForDryRun() -> ReflexLatencyReport {
+ ReflexLatencyReport(
+ mode: .endToEndDryRun,
+ traceCount: 1,
+ softwareLoopMS: ReflexLatencyPercentiles(p50: 4, p95: 4, p99: 4),
+ captureMS: ReflexLatencyPercentiles(p50: 0, p95: 0, p99: 0),
+ perceptionMS: ReflexLatencyPercentiles(p50: 1, p95: 1, p99: 1),
+ decisionMS: ReflexLatencyPercentiles(p50: 1, p95: 1, p99: 1),
+ inputMS: ReflexLatencyPercentiles(p50: 0, p95: 0, p99: 0)
+ )
+ }
+
+ private func providerWindow(
+ windowID: UInt32,
+ processID: Int32,
+ appName: String,
+ bundleIdentifier: String,
+ title: String
+ ) -> MacWindowProviderWindow {
+ MacWindowProviderWindow(
+ windowID: windowID,
+ processID: processID,
+ appName: appName,
+ bundleIdentifier: bundleIdentifier,
+ title: title,
+ bounds: WindowTargetBounds(x: 10, y: 20, width: 300, height: 200)
+ )
+ }
+
+ private func timestamp(_ milliseconds: UInt64) -> RunTraceTimestamp {
+ RunTraceTimestamp(
+ wallClock: Date(timeIntervalSince1970: Double(milliseconds) / 1_000),
+ monotonicUptimeNanoseconds: milliseconds * 1_000_000
+ )
+ }
+}
+
+private final class FixtureTimestampProvider: RunTraceTimestampProviding, @unchecked Sendable {
+ private var nextMilliseconds: UInt64 = 0
+
+ func now() -> RunTraceTimestamp {
+ let timestamp = RunTraceTimestamp(
+ wallClock: Date(timeIntervalSince1970: Double(nextMilliseconds) / 1_000),
+ monotonicUptimeNanoseconds: nextMilliseconds * 1_000_000
+ )
+ nextMilliseconds += 5
+ return timestamp
+ }
+}
+
+private struct FixtureWindowProvider: MacWindowMetadataProviding {
+ var fixtureWindows: [MacWindowProviderWindow]
+ var frontmostProcessID: Int32?
+ var focusedWindowID: UInt32?
+
+ init(
+ windows: [MacWindowProviderWindow],
+ frontmostProcessID: Int32? = nil,
+ focusedWindowID: UInt32? = nil
+ ) {
+ self.fixtureWindows = windows
+ self.frontmostProcessID = frontmostProcessID
+ self.focusedWindowID = focusedWindowID
+ }
+
+ func windows() -> [MacWindowProviderWindow] {
+ fixtureWindows
+ }
+
+ func frontmostProcessIdentifier() -> Int32? {
+ frontmostProcessID
+ }
+
+ func focusedWindowIdentifier() -> UInt32? {
+ focusedWindowID
+ }
+}
+
+private struct AllowingFocusGuard: ActionEngineFocusGuard {
+ func targetIsSafeForInput(targetID: String) async -> Bool {
+ true
+ }
+}
+
+private struct DenyingSmokeFocusGuard: ActionEngineFocusGuard {
+ func targetIsSafeForInput(targetID: String) async -> Bool {
+ false
+ }
+}
+
+private actor RecordingSmokeInputBackend: ActionEngineInputBackend {
+ private var commandIDs: [String] = []
+
+ func execute(_ command: ActionEngineCommand) async -> ActionEngineInputBackendResult {
+ commandIDs.append(command.id)
+ return ActionEngineInputBackendResult(
+ executed: true,
+ completedAt: command.issuedAt,
+ metadata: ["liveInputBackend": "recording-smoke"]
+ )
+ }
+
+ func executedCommandIDs() -> [String] {
+ commandIDs
+ }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/SlowPlannerSidecarTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/SlowPlannerSidecarTests.swift
new file mode 100644
index 00000000..1f8e987f
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/SlowPlannerSidecarTests.swift
@@ -0,0 +1,385 @@
+import DonkeyContracts
+@testable import DonkeyRuntime
+import Foundation
+import Testing
+
+@Suite
+struct SlowPlannerSidecarTests {
+ @Test
+ func sidecarBuildsCompactSnapshotAndPublishesOnlyValidatedHint() async {
+ let coordinator = RunCoordinator()
+ _ = await coordinator.start(session())
+ let memory = InMemoryRunMemory(
+ runID: "session-planner",
+ targetID: "target-1",
+ currentGoal: "switch to the docs tab"
+ )
+ await memory.rememberFailure(
+ RunFailureSummary(traceID: "trace-old", summary: "target not found")
+ )
+ await memory.append(
+ RunMemoryRecord(
+ id: "instruction-1",
+ scope: .run,
+ kind: .userInstruction,
+ runID: "session-planner",
+ value: "Prefer tabs with install docs",
+ createdAt: timestamp(1),
+ source: RunMemorySource(traceID: "trace-old", summary: "user instruction")
+ )
+ )
+
+ let state = worldState(confidence: 0.35)
+ let action = action(
+ state: state,
+ confidence: 0.35,
+ metadata: [
+ "fallback": "true",
+ "fallbackReason": "lowConfidence"
+ ]
+ )
+ let trace = trace(state: state, action: action)
+ await coordinator.appendReflexTrace(trace)
+
+ let planner = RecordingSlowPlanner()
+ await planner.enqueueHint(validHint(for: state, trace: trace))
+ let hintBus = ValidatedPlannerHintBus()
+ let sidecar = DryRunSlowPlannerSidecar(
+ coordinator: coordinator,
+ memory: memory,
+ hintBus: hintBus,
+ planner: planner,
+ screenshotReferences: [
+ SlowPlannerScreenshotReference(
+ artifactID: "screenshot-1",
+ summary: "manual screenshot artifact"
+ )
+ ]
+ )
+
+ await sidecar.observe(
+ worldState: state,
+ action: action,
+ trace: trace,
+ userInstruction: "Look for install docs"
+ )
+
+ let snapshots = await planner.snapshots()
+ #expect(snapshots.count == 1)
+ #expect(snapshots.first?.triggerReasons.contains(.lowConfidence) == true)
+ #expect(snapshots.first?.triggerReasons.contains(.userInstruction) == true)
+ #expect(snapshots.first?.context.latestWorldState?.stateID == state.id)
+ #expect(snapshots.first?.context.memorySnapshot?.currentGoal == "switch to the docs tab")
+ #expect(snapshots.first?.traceSummaries.map(\.traceID) == ["trace-1"])
+ #expect(snapshots.first?.screenshotReferences.map(\.artifactID) == ["screenshot-1"])
+
+ #expect((await hintBus.allHints()).map(\.id) == ["hint-valid"])
+ #expect((await memory.snapshot(now: timestamp(20))).activeHints.map(\.id) == ["hint-valid"])
+ #expect((await sidecar.stats()).publishedHintCount == 1)
+ }
+
+ @Test
+ func sidecarRejectsInvalidPlannerHintBeforeControllerPublication() async {
+ let coordinator = RunCoordinator()
+ _ = await coordinator.start(session())
+ let state = worldState(confidence: 0.2)
+ let action = action(
+ state: state,
+ confidence: 0.2,
+ metadata: [
+ "fallback": "true",
+ "fallbackReason": "lowConfidence"
+ ]
+ )
+ let trace = trace(state: state, action: action)
+ await coordinator.appendReflexTrace(trace)
+
+ let invalid = StructuredPlannerHint(
+ id: "hint-invalid",
+ goal: "tap directly",
+ policyName: "planner",
+ preferredActions: [.tapTarget],
+ confidence: 0.9,
+ createdAt: timestamp(10),
+ expiresAt: timestamp(1_000),
+ sourceTraceID: trace.traceID,
+ sourceFrameID: trace.frameID,
+ sourceStateID: state.id
+ )
+ let planner = RecordingSlowPlanner()
+ await planner.enqueueHint(invalid)
+ let hintBus = ValidatedPlannerHintBus()
+ let sidecar = DryRunSlowPlannerSidecar(
+ coordinator: coordinator,
+ hintBus: hintBus,
+ planner: planner,
+ unsafeActions: [.tapTarget]
+ )
+
+ await sidecar.observe(worldState: state, action: action, trace: trace)
+
+ #expect(await hintBus.allHints().isEmpty)
+ #expect((await hintBus.allValidationResults()).first?.issues == [.unsafeAction])
+ #expect((await sidecar.stats()).publishedHintCount == 0)
+ }
+
+ @Test
+ func hintAwareControllerReadsOnlyLatestValidatedHint() async {
+ let state = worldState(confidence: 0.9)
+ let trace = trace(state: state, action: action(state: state))
+ let hintBus = ValidatedPlannerHintBus()
+ _ = await hintBus.publishIfValid(
+ validHint(for: state, trace: trace),
+ context: PlannerHintValidationContext(
+ currentStateID: state.id,
+ now: timestamp(20)
+ )
+ )
+
+ let controller = PlannerHintAwareControllerPolicy(
+ base: FixedControllerPolicy(kind: .focusWindow),
+ hintBus: hintBus
+ )
+
+ let plannedAction = await controller.decide(state: state)
+
+ #expect(plannedAction.plannerHintID == "hint-valid")
+ #expect(plannedAction.metadata["plannerHintID"] == "hint-valid")
+ #expect(plannedAction.metadata["plannerHintPreferredAction"] == "true")
+ }
+
+ @Test
+ func slowPlannerLatencyDoesNotMoveReflexLatencyReport() async {
+ let frames = (0..<4).map { index in
+ frame(id: "frame-\(index + 1)", milliseconds: UInt64(index * 16))
+ }
+ let baselineCoordinator = RunCoordinator()
+ let baselineLoop = DryRunReflexLoop(
+ coordinator: baselineCoordinator,
+ frameSource: SyntheticFrameSource(frames: frames)
+ )
+ let baselineResult = await baselineLoop.run(session: session())
+ let baselineReport = await ReflexLatencyReportBuilder.build(
+ from: baselineCoordinator.reflexTraces(),
+ droppedFrameCount: baselineResult.droppedFrameCount
+ )
+
+ let sidecarCoordinator = RunCoordinator()
+ let planner = RecordingSlowPlanner(delayNanoseconds: 150_000_000)
+ let hintBus = ValidatedPlannerHintBus()
+ let sidecar = DryRunSlowPlannerSidecar(
+ coordinator: sidecarCoordinator,
+ hintBus: hintBus,
+ planner: planner
+ )
+ let loop = DryRunReflexLoop(
+ coordinator: sidecarCoordinator,
+ frameSource: SyntheticFrameSource(frames: frames),
+ slowPlannerSidecar: sidecar
+ )
+
+ let result = await loop.run(session: session())
+ let report = await ReflexLatencyReportBuilder.build(
+ from: sidecarCoordinator.reflexTraces(),
+ droppedFrameCount: result.droppedFrameCount
+ )
+
+ #expect(report.traceCount == baselineReport.traceCount)
+ #expect(report.softwareLoopMS.p95 == baselineReport.softwareLoopMS.p95)
+ #expect(report.decisionMS.p95 == baselineReport.decisionMS.p95)
+ }
+
+ private func session() -> RunSession {
+ RunSession(
+ id: "session-planner",
+ userGoal: "switch to the docs tab",
+ targetID: "target-1"
+ )
+ }
+
+ private func worldState(
+ confidence: Double,
+ id: String = "state-1"
+ ) -> HotLoopWorldState {
+ HotLoopWorldState(
+ id: id,
+ traceID: "trace-1",
+ frameID: "frame-1",
+ targetID: "target-1",
+ observedAt: timestamp(10),
+ signalSummaries: [
+ HotLoopPerceptionSignalSummary(
+ id: "signal-1",
+ kind: "localNavigationMetadata",
+ confidence: confidence,
+ sourceAgeMS: 5,
+ observationCount: 1
+ )
+ ],
+ actionAffordances: [
+ HotLoopActionAffordance(
+ id: "affordance-1",
+ kind: .focusWindow,
+ targetBounds: HotLoopRect(x: 0, y: 0, width: 100, height: 100, space: .screen),
+ confidence: confidence,
+ sourceSignalID: "signal-1",
+ metadata: [
+ "localNavigation.candidateID": "window-1",
+ "localNavigation.candidateKind": "window",
+ "localNavigation.safetyStatus": "allowed"
+ ]
+ )
+ ],
+ confidence: confidence
+ )
+ }
+
+ private func action(
+ state: HotLoopWorldState,
+ confidence: Double = 0.9,
+ metadata: [String: String] = ["fallback": "false"]
+ ) -> HotLoopControllerAction {
+ HotLoopControllerAction(
+ id: "action-\(state.id)",
+ traceID: state.traceID,
+ frameID: state.frameID,
+ stateID: state.id,
+ kind: .focusWindow,
+ policyName: "fixed",
+ confidence: confidence,
+ rationale: "fixture action",
+ metadata: metadata
+ )
+ }
+
+ private func trace(
+ state: HotLoopWorldState,
+ action: HotLoopControllerAction
+ ) -> ReflexTraceRecord {
+ ReflexTraceRecord(
+ traceID: state.traceID,
+ frameID: state.frameID,
+ stateID: state.id,
+ actionID: action.id,
+ timestamps: ReflexTraceTimeline(
+ captureStart: timestamp(1),
+ captureEnd: timestamp(2),
+ perceptionStart: timestamp(2),
+ perceptionEnd: timestamp(4),
+ stateUpdateStart: timestamp(4),
+ stateUpdateEnd: timestamp(5),
+ statePublished: timestamp(5),
+ controllerStart: timestamp(5),
+ controllerEnd: timestamp(6),
+ actionProjectionStart: timestamp(6),
+ actionProjectionEnd: timestamp(6),
+ actionEnqueued: timestamp(6),
+ inputExecuted: timestamp(6)
+ ),
+ controllerPolicy: action.policyName,
+ confidence: action.confidence,
+ metadata: [
+ "action.kind": action.kind.rawValue,
+ "fallbackReason": action.metadata["fallbackReason"] ?? ""
+ ]
+ )
+ }
+
+ private func validHint(
+ for state: HotLoopWorldState,
+ trace: ReflexTraceRecord
+ ) -> StructuredPlannerHint {
+ StructuredPlannerHint(
+ id: "hint-valid",
+ goal: "prefer focusing the requested target",
+ policyName: "planner",
+ preferredActions: [.focusWindow],
+ confidence: 0.9,
+ createdAt: timestamp(10),
+ expiresAt: timestamp(1_000),
+ sourceTraceID: trace.traceID,
+ sourceFrameID: trace.frameID,
+ sourceStateID: state.id
+ )
+ }
+
+ private func frame(id: String, milliseconds: UInt64) -> HotLoopFrame {
+ HotLoopFrame(
+ id: id,
+ traceID: "trace-\(id)",
+ targetID: "target-1",
+ capturedAt: timestamp(milliseconds),
+ sourceKind: .synthetic,
+ windowBounds: HotLoopRect(x: 0, y: 0, width: 400, height: 300, space: .screen),
+ crop: HotLoopCrop(
+ id: "crop-\(id)",
+ bounds: HotLoopRect(x: 0, y: 0, width: 400, height: 300, space: .window),
+ outputSize: HotLoopSize(width: 400, height: 300, space: .crop)
+ ),
+ pixelSize: HotLoopSize(width: 400, height: 300, space: .window),
+ metadata: [
+ "tapTargetX": "0.4",
+ "tapTargetY": "0.5",
+ "tapTargetWidth": "0.1",
+ "tapTargetHeight": "0.1",
+ "signalConfidence": "0.85"
+ ]
+ )
+ }
+
+ private func timestamp(_ milliseconds: UInt64) -> RunTraceTimestamp {
+ RunTraceTimestamp(
+ wallClock: Date(timeIntervalSince1970: Double(milliseconds) / 1_000),
+ monotonicUptimeNanoseconds: milliseconds * 1_000_000
+ )
+ }
+}
+
+private actor RecordingSlowPlanner: SlowPlannerHintGenerating {
+ private var queuedHints: [StructuredPlannerHint] = []
+ private var recordedSnapshots: [SlowPlannerSnapshot] = []
+ private let delayNanoseconds: UInt64
+
+ init(delayNanoseconds: UInt64 = 0) {
+ self.delayNanoseconds = delayNanoseconds
+ }
+
+ func enqueueHint(_ hint: StructuredPlannerHint) {
+ queuedHints.append(hint)
+ }
+
+ func snapshots() -> [SlowPlannerSnapshot] {
+ recordedSnapshots
+ }
+
+ func generatePlannerHint(
+ snapshot: SlowPlannerSnapshot
+ ) async -> SlowPlannerHintGenerationResult {
+ if delayNanoseconds > 0 {
+ try? await Task.sleep(nanoseconds: delayNanoseconds)
+ }
+ recordedSnapshots.append(snapshot)
+ return SlowPlannerHintGenerationResult(
+ hint: queuedHints.isEmpty ? nil : queuedHints.removeFirst()
+ )
+ }
+}
+
+private struct FixedControllerPolicy: DryRunControllerPolicy {
+ var kind: HotLoopActionKind
+ var name: String { "fixed-controller" }
+
+ func decide(state: HotLoopWorldState) async -> HotLoopControllerAction {
+ HotLoopControllerAction(
+ id: "action-\(state.id)",
+ traceID: state.traceID,
+ frameID: state.frameID,
+ stateID: state.id,
+ kind: kind,
+ policyName: name,
+ confidence: 0.9,
+ rationale: "fixed action",
+ metadata: ["fallback": "false"]
+ )
+ }
+}
diff --git a/docs/guides/minimal-run-coordinator.md b/docs/guides/minimal-run-coordinator.md
index 323cc003..b3ec1b83 100644
--- a/docs/guides/minimal-run-coordinator.md
+++ b/docs/guides/minimal-run-coordinator.md
@@ -24,14 +24,18 @@ 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 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 OS input is not implemented and remains disabled by default. Allowed commands are projected as dry-run traces, denied commands include explicit denial reasons, and `releaseAll` clears held-input state even before live input exists.
+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`.
Donkey also supports the first fast local-navigation dry-run slice end to end through the dry-run reflex loop. `LocalNavigationMetadataFrameSource` can turn macOS window candidate metadata and optional browser-tab metadata supplied by callers into metadata-only hot-loop frames. `LocalNavigationDryRunPerceptionAdapter` and `LocalNavigationDryRunWorldStateProjector` keep the local-navigation path swappable while preserving the no-remote-model fallback. `LocalNavigationControllerPolicy` can choose traceable dry-run semantic actions such as `focusWindow`, `activateCandidate`, `switchTab`, `wait`, or `observe` from typed state. This slice is metadata-only and side-effect free; live input and richer visual inference remain future work.
+Donkey also supports a guarded live-action smoke boundary for the first local-navigation behavior. `GuardedLiveActionSmokeRunner` requires an end-to-end dry-run result, a latency report with p95 evidence, a non-fallback latest action, explicit input policy allowance, and a passing action-engine focus guard before mapping semantic local-navigation actions to typed action-engine commands. The smoke path records replayable action traces and can execute only through an injected backend; no default OS input backend is enabled.
+
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 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 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.
@@ -61,7 +65,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, 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, 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.
+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.
## Technical Guidelines
@@ -86,12 +90,13 @@ This is a coordination, in-memory reflex trace, hot-loop contract, deterministic
- 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 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 action-engine commands typed and replayable. Guardrails must run before live input and record permission, focus, rate-limit, hold-duration, release, and execution status.
-- 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.
+- Keep action-engine commands typed and replayable. Guardrails must run before live input and record permission, focus, rate-limit, hold-duration, release, backend, and execution status.
+- 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.
- Use latency reports for any p50/p95/p99 claim. Reports should include dropped frames, stale actions, tick rates, and worst traces.
- Keep local-navigation decisions typed and side-effect free until the guarded live-action slice. Metadata projectors may use window, browser-tab, and Accessibility facts when available, but controllers should emit semantic actions only.
- Treat planner hints as validated, expiring advice. Controllers may use the latest valid hint, but planner output must never become direct input.
+- Keep slow planner work beside the reflex loop. Trigger it from compact state, trace, memory, and artifact references; never await model calls from the hot tick before recording the reflex trace.
- Keep model selection in `AIModelRegistry` data. Do not scatter provider model ids through planner code.
- Keep 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.
@@ -109,7 +114,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, 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, 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:
@@ -136,10 +141,12 @@ Remaining live verification is environment-dependent. On May 16, 2026, iPhone Mi
- 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`.
- 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`.
- Local-navigation contracts live in `apps/Donkey/Sources/DonkeyContracts/LocalNavigationContracts.swift`.
- Local-navigation metadata projection and dry-run action selection live in `apps/Donkey/Sources/DonkeyRuntime/LocalNavigationController.swift`.
- 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`.
- Memory contracts live in `apps/Donkey/Sources/DonkeyContracts/MemoryContracts.swift`.
diff --git a/plans/19-ai-harness.md b/plans/19-ai-harness.md
index 2f7c673c..ae10d5ec 100644
--- a/plans/19-ai-harness.md
+++ b/plans/19-ai-harness.md
@@ -594,3 +594,24 @@ The harness should degrade quietly and visibly.
- Model upgrades require replay/eval results before promotion.
- A failed model call cannot produce direct input.
- A trace can explain which memories and model outputs influenced a planner hint.
+
+## Current Supported Slice
+
+The AI harness foundation now supports the optional slow-path sidecar pieces needed by the first local-navigation loop:
+
+- structured planner hints with validation, expiry, latest-valid selection, and trace/state/model-call source links
+- a model registry and router boundary so default provider model ids live in registry entries instead of controller logic
+- a provider-neutral OpenAI Responses structured-output adapter with `store: false`, traceable failure results, and strict planner-hint decoding
+- 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
+
+## Remaining Future Work
+
+- Add embedding-backed semantic memory retrieval and explicit retrieval budgets.
+- Add local/Ollama slow-planner providers behind the same hint-generation boundary if needed.
+- 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 f6632c64..5cb69eff 100644
--- a/plans/20-off-the-shelf-run-loop.md
+++ b/plans/20-off-the-shelf-run-loop.md
@@ -415,9 +415,27 @@ Runtime: native core where the hot path needs it
## Current Supported Slice
-The runtime foundation now supports typed reflex trace records for the future hot loop. A trace can carry capture, preprocessing, model, perception, state, controller, action, and input timestamps; derive stage latency, software-loop latency, frame age, and state age from monotonic time; retain recent traces in a bounded in-memory store; and publish matching `reflex` events through `RunCoordinator`.
-
-This is still a boundary and observability slice. It does not capture frames continuously, run detector/OCR/model inference, execute controller actions, or persist high-volume replay traces.
+The runtime foundation now supports a product-shaped local-navigation slice of the off-the-shelf loop:
+
+- 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
+- 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
+- action-engine permission, focus, rate, hold-duration, release, and backend-execution guardrails
+- 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. It does not ship real detector/OCR/segmentation adapters, continuous streaming capture, a default OS input backend, high-volume persisted replay traces, or target-specific visual calibration.
+
+## Remaining Future Work
+
+- Add measured local detector/template/OCR adapters for real visual targets.
+- 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.
## Where To Look
diff --git a/plans/master-plan.md b/plans/master-plan.md
index 85a468e8..2c8a9885 100644
--- a/plans/master-plan.md
+++ b/plans/master-plan.md
@@ -51,8 +51,8 @@ The hot path must continue to work with the AI harness disabled.
- 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. 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, an OpenAI Responses structured-output adapter, source-linked memory, and replay/eval scaffolding are supported as optional sidecar pieces. The hot loop still runs without AI output.
+- 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. 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
@@ -68,20 +68,7 @@ The hot path must continue to work with the AI harness disabled.
## Active Queue
-1. 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.
-
-2. Enable guarded live-action smoke only after dry-run closeout.
- - Use fast local navigation as the first target 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.
-
-3. Close out the primary plans.
+1. 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.
@@ -90,9 +77,9 @@ The hot path must continue to work with the AI harness disabled.
## What Should Be Done Next
-Start with active task 1: integrate the slow planner beside the dry-run loop.
+Start with active task 1: close out the primary plans.
-This is the right next slice because the metadata-only local-navigation path now runs through the dry-run loop with browser-tab metadata when available, no remote-model dependency, queue depth 1, no hot-path image encoding, and stage-split latency traces. The next gap is proving optional planner calls can publish validated hints without moving reflex p95 latency.
+This is the right next slice because the metadata-only local-navigation path runs through the dry-run loop, the optional slow-planner sidecar can publish validated hints without moving reflex p95 latency, and the guarded live-action smoke boundary requires dry-run latency evidence, explicit input policy allowance, focus guard success, and replayable action traces. The remaining work is plan hygiene: decide which primary/supporting acceptance criteria are fully satisfied, move completed plans to `plans/done/`, and keep only clearly named future work active.
## Closeout Criteria