Open source CapCut alternative.
TypeScript
Add hot-loop contracts and target-window frame source
David Lec43b089feb84
diff --git a/apps/Donkey/Sources/DonkeyContracts/HotLoopContracts.swift b/apps/Donkey/Sources/DonkeyContracts/HotLoopContracts.swiftnew file mode 100644index 00000000..698b8007--- /dev/null+++ b/apps/Donkey/Sources/DonkeyContracts/HotLoopContracts.swift@@ -0,0 +1,575 @@+import Foundation++public enum HotLoopCoordinateSpace: String, Codable, Equatable, Sendable {+ case screen+ case window+ case crop+ case normalizedTarget+}++public struct HotLoopPoint: Codable, Equatable, Sendable {+ public var x: Double+ public var y: Double+ public var space: HotLoopCoordinateSpace++ public init(x: Double, y: Double, space: HotLoopCoordinateSpace) {+ self.x = x+ self.y = y+ self.space = space+ }+}++public struct HotLoopSize: Codable, Equatable, Sendable {+ public var width: Double+ public var height: Double+ public var space: HotLoopCoordinateSpace++ public init(width: Double, height: Double, space: HotLoopCoordinateSpace) {+ self.width = width+ self.height = height+ self.space = space+ }++ public var hasPositiveArea: Bool {+ width > 0 && height > 0+ }+}++public struct HotLoopRect: Codable, Equatable, Sendable {+ public var origin: HotLoopPoint+ public var size: HotLoopSize++ public init(origin: HotLoopPoint, size: HotLoopSize) {+ self.origin = origin+ self.size = size+ }++ public init(+ x: Double,+ y: Double,+ width: Double,+ height: Double,+ space: HotLoopCoordinateSpace+ ) {+ self.origin = HotLoopPoint(x: x, y: y, space: space)+ self.size = HotLoopSize(width: width, height: height, space: space)+ }++ public var space: HotLoopCoordinateSpace {+ origin.space+ }++ public var hasPositiveArea: Bool {+ size.hasPositiveArea && origin.space == size.space+ }+}++public struct HotLoopCoordinateMapper: Codable, Equatable, Sendable {+ public var windowBoundsInScreen: HotLoopRect+ public var cropBoundsInWindow: HotLoopRect++ public init(+ windowBoundsInScreen: HotLoopRect,+ cropBoundsInWindow: HotLoopRect+ ) {+ self.windowBoundsInScreen = windowBoundsInScreen+ self.cropBoundsInWindow = cropBoundsInWindow+ }++ public func convert(+ _ point: HotLoopPoint,+ to targetSpace: HotLoopCoordinateSpace+ ) -> HotLoopPoint? {+ guard let windowPoint = pointInWindowSpace(point) else { return nil }+ return pointFromWindowSpace(windowPoint, to: targetSpace)+ }++ public func convert(+ _ rect: HotLoopRect,+ to targetSpace: HotLoopCoordinateSpace+ ) -> HotLoopRect? {+ guard rect.hasPositiveArea,+ let origin = convert(rect.origin, to: targetSpace),+ let size = convert(rect.size, from: rect.space, to: targetSpace)+ else {+ return nil+ }++ return HotLoopRect(origin: origin, size: size)+ }++ public func convert(+ _ size: HotLoopSize,+ from sourceSpace: HotLoopCoordinateSpace,+ to targetSpace: HotLoopCoordinateSpace+ ) -> HotLoopSize? {+ guard size.hasPositiveArea,+ sourceSpace == size.space,+ cropBoundsInWindow.hasPositiveArea,+ windowBoundsInScreen.hasPositiveArea+ else {+ return nil+ }++ if sourceSpace == targetSpace {+ return size+ }++ let windowSize: HotLoopSize+ switch sourceSpace {+ case .screen, .window:+ windowSize = HotLoopSize(+ width: size.width,+ height: size.height,+ space: .window+ )+ case .crop:+ windowSize = HotLoopSize(+ width: size.width,+ height: size.height,+ space: .window+ )+ case .normalizedTarget:+ windowSize = HotLoopSize(+ width: size.width * cropBoundsInWindow.size.width,+ height: size.height * cropBoundsInWindow.size.height,+ space: .window+ )+ }++ switch targetSpace {+ case .screen, .window:+ return HotLoopSize(+ width: windowSize.width,+ height: windowSize.height,+ space: targetSpace+ )+ case .crop:+ return HotLoopSize(+ width: windowSize.width,+ height: windowSize.height,+ space: .crop+ )+ case .normalizedTarget:+ return HotLoopSize(+ width: windowSize.width / cropBoundsInWindow.size.width,+ height: windowSize.height / cropBoundsInWindow.size.height,+ space: .normalizedTarget+ )+ }+ }++ private func pointInWindowSpace(_ point: HotLoopPoint) -> HotLoopPoint? {+ guard cropBoundsInWindow.hasPositiveArea,+ windowBoundsInScreen.hasPositiveArea+ else {+ return nil+ }++ switch point.space {+ case .screen:+ return HotLoopPoint(+ x: point.x - windowBoundsInScreen.origin.x,+ y: point.y - windowBoundsInScreen.origin.y,+ space: .window+ )+ case .window:+ return point+ case .crop:+ return HotLoopPoint(+ x: point.x + cropBoundsInWindow.origin.x,+ y: point.y + cropBoundsInWindow.origin.y,+ space: .window+ )+ case .normalizedTarget:+ return HotLoopPoint(+ x: cropBoundsInWindow.origin.x + point.x * cropBoundsInWindow.size.width,+ y: cropBoundsInWindow.origin.y + point.y * cropBoundsInWindow.size.height,+ space: .window+ )+ }+ }++ private func pointFromWindowSpace(+ _ point: HotLoopPoint,+ to targetSpace: HotLoopCoordinateSpace+ ) -> HotLoopPoint? {+ guard point.space == .window,+ cropBoundsInWindow.hasPositiveArea,+ windowBoundsInScreen.hasPositiveArea+ else {+ return nil+ }++ switch targetSpace {+ case .screen:+ return HotLoopPoint(+ x: point.x + windowBoundsInScreen.origin.x,+ y: point.y + windowBoundsInScreen.origin.y,+ space: .screen+ )+ case .window:+ return point+ case .crop:+ return HotLoopPoint(+ x: point.x - cropBoundsInWindow.origin.x,+ y: point.y - cropBoundsInWindow.origin.y,+ space: .crop+ )+ case .normalizedTarget:+ return HotLoopPoint(+ x: (point.x - cropBoundsInWindow.origin.x) / cropBoundsInWindow.size.width,+ y: (point.y - cropBoundsInWindow.origin.y) / cropBoundsInWindow.size.height,+ space: .normalizedTarget+ )+ }+ }+}++public struct HotLoopCrop: Codable, Equatable, Sendable {+ public var id: String+ public var bounds: HotLoopRect+ public var outputSize: HotLoopSize++ public init(+ id: String,+ bounds: HotLoopRect,+ outputSize: HotLoopSize+ ) {+ self.id = id+ self.bounds = bounds+ self.outputSize = outputSize+ }+}++public enum HotLoopFrameSourceKind: String, Codable, Equatable, Sendable {+ case synthetic+ case recorded+ case targetWindow+}++public struct HotLoopFrame: Codable, Equatable, Sendable {+ public var id: String+ public var traceID: String+ public var targetID: String+ public var capturedAt: RunTraceTimestamp+ public var sourceKind: HotLoopFrameSourceKind+ public var windowBounds: HotLoopRect+ public var crop: HotLoopCrop?+ public var pixelSize: HotLoopSize+ public var plannerHintID: String?+ public var metadata: [String: String]++ public init(+ id: String,+ traceID: String,+ targetID: String,+ capturedAt: RunTraceTimestamp,+ sourceKind: HotLoopFrameSourceKind,+ windowBounds: HotLoopRect,+ crop: HotLoopCrop? = nil,+ pixelSize: HotLoopSize,+ plannerHintID: String? = nil,+ metadata: [String: String] = [:]+ ) {+ self.id = id+ self.traceID = traceID+ self.targetID = targetID+ self.capturedAt = capturedAt+ self.sourceKind = sourceKind+ self.windowBounds = windowBounds+ self.crop = crop+ self.pixelSize = pixelSize+ self.plannerHintID = plannerHintID+ self.metadata = metadata+ }+}++public struct HotLoopPerceptionObservation: Codable, Equatable, Sendable {+ public var id: String+ public var label: String+ public var bounds: HotLoopRect?+ public var confidence: Double+ public var metadata: [String: String]++ public init(+ id: String,+ label: String,+ bounds: HotLoopRect? = nil,+ confidence: Double,+ metadata: [String: String] = [:]+ ) {+ self.id = id+ self.label = label+ self.bounds = bounds+ self.confidence = confidence+ self.metadata = metadata+ }+}++public struct HotLoopPerceptionSignal: Codable, Equatable, Sendable {+ public var id: String+ public var traceID: String+ public var frameID: String+ public var kind: String+ public var capturedAt: RunTraceTimestamp+ public var observedAt: RunTraceTimestamp+ public var confidence: Double+ public var observations: [HotLoopPerceptionObservation]+ public var plannerHintID: String?+ public var metadata: [String: String]++ public init(+ id: String,+ traceID: String,+ frameID: String,+ kind: String,+ capturedAt: RunTraceTimestamp,+ observedAt: RunTraceTimestamp,+ confidence: Double,+ observations: [HotLoopPerceptionObservation] = [],+ plannerHintID: String? = nil,+ metadata: [String: String] = [:]+ ) {+ self.id = id+ self.traceID = traceID+ self.frameID = frameID+ self.kind = kind+ self.capturedAt = capturedAt+ self.observedAt = observedAt+ self.confidence = confidence+ self.observations = observations+ self.plannerHintID = plannerHintID+ self.metadata = metadata+ }++ public func sourceAgeMS(at timestamp: RunTraceTimestamp) -> Double? {+ capturedAt.milliseconds(until: timestamp)+ }++ public func isStale(+ at timestamp: RunTraceTimestamp,+ thresholdMS: Double+ ) -> Bool {+ guard let age = sourceAgeMS(at: timestamp) else { return true }+ return age > thresholdMS+ }+}++public struct HotLoopPerceptionSignalSummary: Codable, Equatable, Sendable {+ public var id: String+ public var kind: String+ public var confidence: Double+ public var sourceAgeMS: Double?+ public var observationCount: Int++ public init(+ id: String,+ kind: String,+ confidence: Double,+ sourceAgeMS: Double? = nil,+ observationCount: Int+ ) {+ self.id = id+ self.kind = kind+ self.confidence = confidence+ self.sourceAgeMS = sourceAgeMS+ self.observationCount = observationCount+ }+}++public struct HotLoopActionAffordance: Codable, Equatable, Sendable {+ public var id: String+ public var kind: HotLoopActionKind+ public var targetBounds: HotLoopRect?+ public var confidence: Double+ public var sourceSignalID: String++ public init(+ id: String,+ kind: HotLoopActionKind,+ targetBounds: HotLoopRect? = nil,+ confidence: Double,+ sourceSignalID: String+ ) {+ self.id = id+ self.kind = kind+ self.targetBounds = targetBounds+ self.confidence = confidence+ self.sourceSignalID = sourceSignalID+ }+}++public struct HotLoopWorldState: Codable, Equatable, Sendable {+ public var id: String+ public var traceID: String+ public var frameID: String+ public var targetID: String+ public var observedAt: RunTraceTimestamp+ public var signalSummaries: [HotLoopPerceptionSignalSummary]+ public var staleSignalIDs: [String]+ public var actionAffordances: [HotLoopActionAffordance]+ public var confidence: Double+ public var plannerHintID: String?+ public var metadata: [String: String]++ public init(+ id: String,+ traceID: String,+ frameID: String,+ targetID: String,+ observedAt: RunTraceTimestamp,+ signalSummaries: [HotLoopPerceptionSignalSummary],+ staleSignalIDs: [String] = [],+ actionAffordances: [HotLoopActionAffordance] = [],+ confidence: Double,+ plannerHintID: String? = nil,+ metadata: [String: String] = [:]+ ) {+ self.id = id+ self.traceID = traceID+ self.frameID = frameID+ self.targetID = targetID+ self.observedAt = observedAt+ self.signalSummaries = signalSummaries+ self.staleSignalIDs = staleSignalIDs+ self.actionAffordances = actionAffordances+ self.confidence = confidence+ self.plannerHintID = plannerHintID+ self.metadata = metadata+ }++ public static func build(+ id: String,+ frame: HotLoopFrame,+ signals: [HotLoopPerceptionSignal],+ observedAt: RunTraceTimestamp,+ staleThresholdMS: Double,+ actionAffordances: [HotLoopActionAffordance] = [],+ metadata: [String: String] = [:]+ ) -> HotLoopWorldState {+ let summaries = signals.map { signal in+ HotLoopPerceptionSignalSummary(+ id: signal.id,+ kind: signal.kind,+ confidence: signal.confidence,+ sourceAgeMS: signal.sourceAgeMS(at: observedAt),+ observationCount: signal.observations.count+ )+ }+ let staleSignalIDs = signals+ .filter { $0.isStale(at: observedAt, thresholdMS: staleThresholdMS) }+ .map(\.id)+ let confidence: Double+ if signals.isEmpty {+ confidence = 0+ } else {+ confidence = signals.map(\.confidence).reduce(0, +) / Double(signals.count)+ }++ return HotLoopWorldState(+ id: id,+ traceID: frame.traceID,+ frameID: frame.id,+ targetID: frame.targetID,+ observedAt: observedAt,+ signalSummaries: summaries,+ staleSignalIDs: staleSignalIDs,+ actionAffordances: actionAffordances,+ confidence: confidence,+ plannerHintID: frame.plannerHintID,+ metadata: metadata+ )+ }+}++public enum HotLoopActionKind: String, Codable, Equatable, Sendable {+ case observe+ case wait+ case tapTarget+}++public struct HotLoopControllerAction: Codable, Equatable, Sendable {+ public var id: String+ public var traceID: String+ public var frameID: String+ public var stateID: String+ public var kind: HotLoopActionKind+ public var target: HotLoopRect?+ public var policyName: String+ public var confidence: Double+ public var rationale: String+ public var plannerHintID: String?+ public var metadata: [String: String]++ public init(+ id: String,+ traceID: String,+ frameID: String,+ stateID: String,+ kind: HotLoopActionKind,+ target: HotLoopRect? = nil,+ policyName: String,+ confidence: Double,+ rationale: String,+ plannerHintID: String? = nil,+ metadata: [String: String] = [:]+ ) {+ self.id = id+ self.traceID = traceID+ self.frameID = frameID+ self.stateID = stateID+ self.kind = kind+ self.target = target+ self.policyName = policyName+ self.confidence = confidence+ self.rationale = rationale+ self.plannerHintID = plannerHintID+ self.metadata = metadata+ }+}++public enum HotLoopActionExecutionMode: String, Codable, Equatable, Sendable {+ case dryRun+ case live+}++public struct HotLoopActionResult: Codable, Equatable, Sendable {+ public var id: String+ public var traceID: String+ public var frameID: String+ public var stateID: String+ public var actionID: String+ public var mode: HotLoopActionExecutionMode+ public var executed: Bool+ public var enqueuedAt: RunTraceTimestamp+ public var completedAt: RunTraceTimestamp+ public var summary: String+ public var metadata: [String: String]++ public init(+ id: String,+ traceID: String,+ frameID: String,+ stateID: String,+ actionID: String,+ mode: HotLoopActionExecutionMode,+ executed: Bool,+ enqueuedAt: RunTraceTimestamp,+ completedAt: RunTraceTimestamp,+ summary: String,+ metadata: [String: String] = [:]+ ) {+ self.id = id+ self.traceID = traceID+ self.frameID = frameID+ self.stateID = stateID+ self.actionID = actionID+ self.mode = mode+ self.executed = executed+ self.enqueuedAt = enqueuedAt+ self.completedAt = completedAt+ self.summary = summary+ self.metadata = metadata+ }+}diff --git a/apps/Donkey/Sources/DonkeyRuntime/DryRunReflexLoop.swift b/apps/Donkey/Sources/DonkeyRuntime/DryRunReflexLoop.swiftnew file mode 100644index 00000000..879ecea1--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/DryRunReflexLoop.swift@@ -0,0 +1,386 @@+import DonkeyContracts+import Foundation++public protocol DryRunFrameSource: Sendable {+ func frameBatches() async -> [[HotLoopFrame]]+}++public protocol DryRunPerceptionAdapting: Sendable {+ func perceive(frame: HotLoopFrame) async -> [HotLoopPerceptionSignal]+}++public protocol DryRunControllerPolicy: Sendable {+ var name: String { get }+ func decide(state: HotLoopWorldState) async -> HotLoopControllerAction+}++public protocol DryRunActionProjecting: Sendable {+ func project(+ action: HotLoopControllerAction,+ state: HotLoopWorldState+ ) async -> HotLoopActionResult+}++public enum DryRunReflexLoopCompletion: Equatable, Sendable {+ case complete(reason: String)+ case abort(reason: String)+ case timeout(reason: String)+ case pause(reason: String)+}++public struct DryRunReflexLoopResult: Equatable, Sendable {+ public var processedFrameCount: Int+ public var droppedFrameCount: Int+ public var latestWorldState: HotLoopWorldState?+ public var latestAction: HotLoopControllerAction?++ public init(+ processedFrameCount: Int,+ droppedFrameCount: Int,+ latestWorldState: HotLoopWorldState? = nil,+ latestAction: HotLoopControllerAction? = nil+ ) {+ self.processedFrameCount = processedFrameCount+ self.droppedFrameCount = droppedFrameCount+ self.latestWorldState = latestWorldState+ self.latestAction = latestAction+ }+}++public actor LatestHotLoopFrameBuffer {+ private var latestFrame: HotLoopFrame?+ private var droppedFrameCount = 0++ public init() {}++ public func offer(_ frame: HotLoopFrame) {+ if latestFrame != nil {+ droppedFrameCount += 1+ }++ latestFrame = frame+ }++ public func takeLatest() -> HotLoopFrame? {+ let frame = latestFrame+ latestFrame = nil+ return frame+ }++ public func droppedCount() -> Int {+ droppedFrameCount+ }+}++public struct DryRunReflexLoop: Sendable {+ public var coordinator: RunCoordinator+ public var frameSource: any DryRunFrameSource+ public var perceptionAdapter: any DryRunPerceptionAdapting+ public var controllerPolicy: any DryRunControllerPolicy+ public var actionProjector: any DryRunActionProjecting+ public var staleSignalThresholdMS: Double++ public init(+ coordinator: RunCoordinator,+ frameSource: any DryRunFrameSource,+ perceptionAdapter: any DryRunPerceptionAdapting = SyntheticPerceptionAdapter(),+ controllerPolicy: any DryRunControllerPolicy = InspectableDryRunControllerPolicy(),+ actionProjector: any DryRunActionProjecting = DryRunActionProjector(),+ staleSignalThresholdMS: Double = 250+ ) {+ self.coordinator = coordinator+ self.frameSource = frameSource+ self.perceptionAdapter = perceptionAdapter+ self.controllerPolicy = controllerPolicy+ self.actionProjector = actionProjector+ self.staleSignalThresholdMS = staleSignalThresholdMS+ }++ @discardableResult+ public func run(+ session: RunSession,+ completion: DryRunReflexLoopCompletion = .complete(reason: "Dry-run reflex loop completed")+ ) async -> DryRunReflexLoopResult {+ _ = await coordinator.start(session)++ let buffer = LatestHotLoopFrameBuffer()+ var processedFrameCount = 0+ var latestWorldState: HotLoopWorldState?+ var latestAction: HotLoopControllerAction?++ for batch in await frameSource.frameBatches() {+ for frame in batch {+ await buffer.offer(frame)+ }++ guard !Task.isCancelled else {+ await coordinator.abort(reason: "Dry-run reflex loop task cancelled")+ break+ }++ guard !(await coordinator.snapshot().lifecycleState.isTerminal) else {+ break+ }++ guard let frame = await buffer.takeLatest() else {+ continue+ }++ let tick = await process(frame: frame)+ processedFrameCount += 1+ latestWorldState = tick.worldState+ latestAction = tick.action+ }++ if !(await coordinator.snapshot().lifecycleState.isTerminal) {+ await finish(completion)+ }++ return DryRunReflexLoopResult(+ processedFrameCount: processedFrameCount,+ droppedFrameCount: await buffer.droppedCount(),+ latestWorldState: latestWorldState,+ latestAction: latestAction+ )+ }++ private func process(+ frame: HotLoopFrame+ ) async -> (worldState: HotLoopWorldState, action: HotLoopControllerAction) {+ let signals = await perceptionAdapter.perceive(frame: frame)+ let observedAt = signals.map(\.observedAt).maxByMonotonicUptime() ?? frame.capturedAt.addingMilliseconds(2)+ let affordances = actionAffordances(from: signals)+ let worldState = HotLoopWorldState.build(+ id: "state-\(frame.id)",+ frame: frame,+ signals: signals,+ observedAt: observedAt,+ staleThresholdMS: staleSignalThresholdMS,+ actionAffordances: affordances+ )+ let controllerStart = observedAt.addingMilliseconds(1)+ let action = await controllerPolicy.decide(state: worldState)+ let result = await actionProjector.project(action: action, state: worldState)+ let trace = ReflexTraceRecord(+ traceID: frame.traceID,+ frameID: frame.id,+ stateID: worldState.id,+ actionID: action.id,+ timestamps: ReflexTraceTimeline(+ captureStart: frame.capturedAt,+ captureEnd: frame.capturedAt,+ perceptionStart: frame.capturedAt,+ perceptionEnd: observedAt,+ statePublished: observedAt,+ controllerStart: controllerStart,+ controllerEnd: result.enqueuedAt,+ actionEnqueued: result.enqueuedAt,+ inputExecuted: result.completedAt+ ),+ controllerPolicy: action.policyName,+ confidence: action.confidence,+ plannerHintID: action.plannerHintID,+ metadata: [+ "dryRun.mode": result.mode.rawValue,+ "dryRun.executed": String(result.executed),+ "dryRun.summary": result.summary+ ]+ )++ await coordinator.appendReflexTrace(trace)++ return (worldState, action)+ }++ private func finish(_ completion: DryRunReflexLoopCompletion) async {+ switch completion {+ case .complete(let reason):+ await coordinator.complete(reason: reason)+ case .abort(let reason):+ await coordinator.abort(reason: reason)+ case .timeout(let reason):+ await coordinator.timeout(reason: reason)+ case .pause(let reason):+ await coordinator.pause(reason: reason)+ }+ }++ private func actionAffordances(+ from signals: [HotLoopPerceptionSignal]+ ) -> [HotLoopActionAffordance] {+ signals.flatMap { signal in+ signal.observations.map { observation in+ HotLoopActionAffordance(+ id: "affordance-\(observation.id)",+ kind: .tapTarget,+ targetBounds: observation.bounds,+ confidence: min(signal.confidence, observation.confidence),+ sourceSignalID: signal.id+ )+ }+ }+ }+}++public struct SyntheticFrameSource: DryRunFrameSource {+ public var batches: [[HotLoopFrame]]++ public init(frames: [HotLoopFrame]) {+ self.batches = frames.map { [$0] }+ }++ public init(batches: [[HotLoopFrame]]) {+ self.batches = batches+ }++ public func frameBatches() async -> [[HotLoopFrame]] {+ batches+ }+}++public struct RecordedFrameSource: DryRunFrameSource {+ public var frames: [HotLoopFrame]++ public init(frames: [HotLoopFrame]) {+ self.frames = frames+ }++ public func frameBatches() async -> [[HotLoopFrame]] {+ frames.map { [$0] }+ }+}++public struct SyntheticPerceptionAdapter: DryRunPerceptionAdapting {+ public init() {}++ public func perceive(frame: HotLoopFrame) async -> [HotLoopPerceptionSignal] {+ let confidence = Double(frame.metadata["signalConfidence"] ?? "") ?? 1+ let observedAt = frame.capturedAt.addingMilliseconds(2)+ let observation = observation(from: frame, confidence: confidence)++ return [+ HotLoopPerceptionSignal(+ id: "signal-\(frame.id)",+ traceID: frame.traceID,+ frameID: frame.id,+ kind: frame.metadata["signalKind"] ?? "synthetic",+ capturedAt: frame.capturedAt,+ observedAt: observedAt,+ confidence: confidence,+ observations: observation.map { [$0] } ?? [],+ plannerHintID: frame.plannerHintID+ )+ ]+ }++ private func observation(+ from frame: HotLoopFrame,+ confidence: Double+ ) -> HotLoopPerceptionObservation? {+ guard let x = Double(frame.metadata["tapTargetX"] ?? ""),+ let y = Double(frame.metadata["tapTargetY"] ?? "")+ else {+ return nil+ }++ let width = Double(frame.metadata["tapTargetWidth"] ?? "") ?? 0.1+ let height = Double(frame.metadata["tapTargetHeight"] ?? "") ?? 0.1++ return HotLoopPerceptionObservation(+ id: "observation-\(frame.id)",+ label: frame.metadata["tapTargetLabel"] ?? "tap-target",+ bounds: HotLoopRect(+ x: x,+ y: y,+ width: width,+ height: height,+ space: .normalizedTarget+ ),+ confidence: confidence+ )+ }+}++public struct InspectableDryRunControllerPolicy: DryRunControllerPolicy {+ public var name: String++ public init(name: String = "inspectable-dry-run") {+ self.name = name+ }++ public func decide(state: HotLoopWorldState) async -> HotLoopControllerAction {+ if let affordance = state.actionAffordances.first(where: { $0.kind == .tapTarget }) {+ return HotLoopControllerAction(+ id: "action-\(state.id)",+ traceID: state.traceID,+ frameID: state.frameID,+ stateID: state.id,+ kind: .tapTarget,+ target: affordance.targetBounds,+ policyName: name,+ confidence: affordance.confidence,+ rationale: "Synthetic tap target affordance is available",+ plannerHintID: state.plannerHintID+ )+ }++ let kind: HotLoopActionKind = state.signalSummaries.isEmpty ? .observe : .wait+ return HotLoopControllerAction(+ id: "action-\(state.id)",+ traceID: state.traceID,+ frameID: state.frameID,+ stateID: state.id,+ kind: kind,+ policyName: name,+ confidence: state.confidence,+ rationale: kind == .observe ? "No perception signal is available" : "No safe action affordance is available",+ plannerHintID: state.plannerHintID+ )+ }+}++public struct DryRunActionProjector: DryRunActionProjecting {+ public init() {}++ public func project(+ action: HotLoopControllerAction,+ state: HotLoopWorldState+ ) async -> HotLoopActionResult {+ let enqueuedAt = state.observedAt.addingMilliseconds(2)+ let completedAt = enqueuedAt++ return HotLoopActionResult(+ id: "result-\(action.id)",+ traceID: action.traceID,+ frameID: action.frameID,+ stateID: action.stateID,+ actionID: action.id,+ mode: .dryRun,+ executed: false,+ enqueuedAt: enqueuedAt,+ completedAt: completedAt,+ summary: "Dry-run projected \(action.kind.rawValue)",+ metadata: [+ "policyName": action.policyName,+ "rationale": action.rationale+ ]+ )+ }+}++private extension RunTraceTimestamp {+ func addingMilliseconds(_ milliseconds: UInt64) -> RunTraceTimestamp {+ RunTraceTimestamp(+ wallClock: wallClock.addingTimeInterval(Double(milliseconds) / 1_000),+ monotonicUptimeNanoseconds: monotonicUptimeNanoseconds + milliseconds * 1_000_000+ )+ }+}++private extension Array where Element == RunTraceTimestamp {+ func maxByMonotonicUptime() -> RunTraceTimestamp? {+ self.max { lhs, rhs in+ lhs.monotonicUptimeNanoseconds < rhs.monotonicUptimeNanoseconds+ }+ }+}diff --git a/apps/Donkey/Sources/DonkeyRuntime/TargetWindowFrameSource.swift b/apps/Donkey/Sources/DonkeyRuntime/TargetWindowFrameSource.swiftnew file mode 100644index 00000000..7e53e891--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/TargetWindowFrameSource.swift@@ -0,0 +1,402 @@+import CoreGraphics+import DonkeyContracts+import Foundation+import ScreenCaptureKit++public struct TargetWindowFrameCaptureRequest: Equatable, Sendable {+ public var selection: MacWindowSelectionRequest+ public var targetID: String+ public var traceID: String+ public var frameIDPrefix: String+ public var maxFrameCount: Int+ public var cropBoundsInWindow: HotLoopRect?+ public var plannerHintID: String?++ public init(+ selection: MacWindowSelectionRequest = MacWindowSelectionRequest(),+ targetID: String,+ traceID: String,+ frameIDPrefix: String = "target-frame",+ maxFrameCount: Int,+ cropBoundsInWindow: HotLoopRect? = nil,+ plannerHintID: String? = nil+ ) {+ self.selection = selection+ self.targetID = targetID+ self.traceID = traceID+ self.frameIDPrefix = frameIDPrefix+ self.maxFrameCount = maxFrameCount+ self.cropBoundsInWindow = cropBoundsInWindow+ self.plannerHintID = plannerHintID+ }+}++public struct TargetWindowFrameCaptureResult: Equatable, Sendable {+ public var target: MacWindowTargetCandidate+ public var frames: [HotLoopFrame]+ public var captureMethod: WindowScreenshotCaptureMethod+ public var overlapStatus: WindowScreenshotOverlapStatus++ public init(+ target: MacWindowTargetCandidate,+ frames: [HotLoopFrame],+ captureMethod: WindowScreenshotCaptureMethod,+ overlapStatus: WindowScreenshotOverlapStatus+ ) {+ self.target = target+ self.frames = frames+ self.captureMethod = captureMethod+ self.overlapStatus = overlapStatus+ }+}++struct CapturedTargetWindowFrame: Equatable, Sendable {+ var imageWidth: Int+ var imageHeight: Int+ var captureMethod: WindowScreenshotCaptureMethod+ var coordinateSpace: String++ init(+ imageWidth: Int,+ imageHeight: Int,+ captureMethod: WindowScreenshotCaptureMethod,+ coordinateSpace: String+ ) {+ self.imageWidth = imageWidth+ self.imageHeight = imageHeight+ self.captureMethod = captureMethod+ self.coordinateSpace = coordinateSpace+ }+}++protocol TargetWindowFrameCapturing: Sendable {+ var captureMethod: WindowScreenshotCaptureMethod { get }+ var requiresOverlapFreeTarget: Bool { get }++ func captureFrame(+ target: MacWindowTargetCandidate+ ) async throws -> CapturedTargetWindowFrame+}++protocol RunTraceTimestampProviding: Sendable {+ func now() -> RunTraceTimestamp+}++public final class TargetWindowFrameCaptureService: @unchecked Sendable {+ private let windowResolver: MacWindowResolver+ private let capturer: any TargetWindowFrameCapturing+ private let timestampProvider: any RunTraceTimestampProviding++ public convenience init() {+ self.init(+ windowResolver: MacWindowResolver(),+ capturer: ScreenCaptureKitTargetWindowFrameCapturer(),+ timestampProvider: SystemRunTraceTimestampProvider()+ )+ }++ init(+ windowResolver: MacWindowResolver,+ capturer: any TargetWindowFrameCapturing,+ timestampProvider: any RunTraceTimestampProviding = SystemRunTraceTimestampProvider()+ ) {+ self.windowResolver = windowResolver+ self.capturer = capturer+ self.timestampProvider = timestampProvider+ }++ public func captureFrames(+ request: TargetWindowFrameCaptureRequest+ ) async throws -> TargetWindowFrameCaptureResult {+ let candidates = windowResolver.enumerateCandidates()+ let target = try selectTarget(request.selection, from: candidates)+ guard target.safetyAssessment.status == .allowed else {+ throw WindowScreenshotCaptureError.unsafeTarget(+ windowID: target.windowID,+ status: target.safetyAssessment.status+ )+ }++ let overlapStatus = try validateOverlap(+ for: target,+ in: candidates+ )+ let frameCount = max(0, request.maxFrameCount)+ var frames: [HotLoopFrame] = []+ frames.reserveCapacity(frameCount)++ for index in 0..<frameCount {+ frames.append(+ try await captureFrame(+ request: request,+ target: target,+ frameIndex: index+ )+ )+ }++ return TargetWindowFrameCaptureResult(+ target: target,+ frames: frames,+ captureMethod: capturer.captureMethod,+ overlapStatus: overlapStatus+ )+ }++ private func captureFrame(+ request: TargetWindowFrameCaptureRequest,+ target: MacWindowTargetCandidate,+ frameIndex: Int+ ) async throws -> HotLoopFrame {+ let captureStart = timestampProvider.now()+ let captured: CapturedTargetWindowFrame+ do {+ captured = try await capturer.captureFrame(target: target)+ } catch let error as WindowScreenshotCaptureError {+ throw error+ } catch {+ throw WindowScreenshotCaptureError.captureFailed(+ windowID: target.windowID,+ reason: String(describing: error)+ )+ }++ let captureEnd = timestampProvider.now()+ let copyStart = timestampProvider.now()+ let frame = HotLoopFrame(+ id: "\(request.frameIDPrefix)-\(frameIndex + 1)",+ traceID: request.traceID,+ targetID: request.targetID,+ capturedAt: captureEnd,+ sourceKind: .targetWindow,+ windowBounds: HotLoopRect(+ x: target.bounds.x,+ y: target.bounds.y,+ width: target.bounds.width,+ height: target.bounds.height,+ space: .screen+ ),+ crop: crop(+ request.cropBoundsInWindow,+ fallbackWidth: captured.imageWidth,+ fallbackHeight: captured.imageHeight+ ),+ pixelSize: HotLoopSize(+ width: Double(captured.imageWidth),+ height: Double(captured.imageHeight),+ space: .window+ ),+ plannerHintID: request.plannerHintID,+ metadata: metadata(+ target: target,+ captured: captured,+ captureStart: captureStart,+ captureEnd: captureEnd,+ copyStart: copyStart,+ copyEnd: timestampProvider.now()+ )+ )++ return frame+ }++ private func selectTarget(+ _ selection: MacWindowSelectionRequest,+ from candidates: [MacWindowTargetCandidate]+ ) throws -> MacWindowTargetCandidate {+ guard !candidates.isEmpty else {+ throw MacWindowResolverError.noVisibleWindows+ }++ if let windowID = selection.windowID {+ guard let target = candidates.first(where: { $0.windowID == windowID }) else {+ throw MacWindowResolverError.windowNotFound(windowID: windowID)+ }++ return target+ }++ if let focused = candidates.first(where: \.isFocused) {+ return focused+ }++ if let frontmost = candidates.first(where: \.isFrontmost) {+ return frontmost+ }++ throw MacWindowResolverError.noFocusedWindow+ }++ private func validateOverlap(+ for target: MacWindowTargetCandidate,+ in candidates: [MacWindowTargetCandidate]+ ) throws -> WindowScreenshotOverlapStatus {+ guard capturer.requiresOverlapFreeTarget else {+ return .notRequired+ }++ guard let targetIndex = candidates.firstIndex(where: { $0.windowID == target.windowID }) else {+ return .clear+ }++ if let occludingWindow = candidates[..<targetIndex].first(where: { candidate in+ candidate.windowID != target.windowID+ && candidate.isVisible+ && candidate.isOnScreen+ && candidate.bounds.intersects(target.bounds)+ }) {+ throw WindowScreenshotCaptureError.occludedTarget(+ windowID: target.windowID,+ occludingWindowID: occludingWindow.windowID+ )+ }++ return .clear+ }++ private func crop(+ _ cropBoundsInWindow: HotLoopRect?,+ fallbackWidth: Int,+ fallbackHeight: Int+ ) -> HotLoopCrop? {+ guard let cropBoundsInWindow else { return nil }++ return HotLoopCrop(+ id: "target-window-crop",+ bounds: cropBoundsInWindow,+ outputSize: HotLoopSize(+ width: min(Double(fallbackWidth), cropBoundsInWindow.size.width),+ height: min(Double(fallbackHeight), cropBoundsInWindow.size.height),+ space: .crop+ )+ )+ }++ private func metadata(+ target: MacWindowTargetCandidate,+ captured: CapturedTargetWindowFrame,+ captureStart: RunTraceTimestamp,+ captureEnd: RunTraceTimestamp,+ copyStart: RunTraceTimestamp,+ copyEnd: RunTraceTimestamp+ ) -> [String: String] {+ var metadata = [+ "target.windowID": String(target.windowID),+ "target.processID": String(target.processID),+ "target.bounds.x": String(target.bounds.x),+ "target.bounds.y": String(target.bounds.y),+ "target.bounds.width": String(target.bounds.width),+ "target.bounds.height": String(target.bounds.height),+ "target.isIPhoneMirroring": String(target.isIPhoneMirroring),+ "target.safety.status": target.safetyAssessment.status.rawValue,+ "capture.method": captured.captureMethod.rawValue,+ "capture.coordinateSpace": captured.coordinateSpace,+ "capture.imageWidth": String(captured.imageWidth),+ "capture.imageHeight": String(captured.imageHeight),+ "capture.latencyMS": String(captureStart.milliseconds(until: captureEnd) ?? 0),+ "capture.copyCostMS": String(copyStart.milliseconds(until: copyEnd) ?? 0),+ "capture.encoded": "false",+ "capture.artifactWritten": "false"+ ]++ if let appName = target.appName {+ metadata["target.appName"] = appName+ }++ if let bundleIdentifier = target.bundleIdentifier {+ metadata["target.bundleIdentifier"] = bundleIdentifier+ }++ if let title = target.title {+ metadata["target.title"] = title+ }++ return metadata+ }+}++public struct TargetWindowFrameSource: DryRunFrameSource {+ public let service: TargetWindowFrameCaptureService+ public let request: TargetWindowFrameCaptureRequest++ public init(+ service: TargetWindowFrameCaptureService = TargetWindowFrameCaptureService(),+ request: TargetWindowFrameCaptureRequest+ ) {+ self.service = service+ self.request = request+ }++ public func frameBatches() async -> [[HotLoopFrame]] {+ do {+ return try await service.captureFrames(request: request).frames.map { [$0] }+ } catch {+ return []+ }+ }+}++private final class ScreenCaptureKitTargetWindowFrameCapturer: TargetWindowFrameCapturing {+ var captureMethod: WindowScreenshotCaptureMethod {+ .screenCaptureKitDesktopIndependentWindow+ }++ var requiresOverlapFreeTarget: Bool {+ false+ }++ func captureFrame(+ target: MacWindowTargetCandidate+ ) async throws -> CapturedTargetWindowFrame {+ let content = try await SCShareableContent.current+ guard let window = content.windows.first(where: { $0.windowID == target.windowID }) else {+ throw WindowScreenshotCaptureError.targetWindowUnavailable(windowID: target.windowID)+ }++ let filter = SCContentFilter(desktopIndependentWindow: window)+ let contentInfo = SCShareableContent.info(for: filter)+ let scale = CGFloat(contentInfo.pointPixelScale)+ let configuration = SCStreamConfiguration()+ configuration.width = max(1, Int(ceil(contentInfo.contentRect.width * scale)))+ configuration.height = max(1, Int(ceil(contentInfo.contentRect.height * scale)))+ configuration.showsCursor = false+ configuration.capturesAudio = false+ configuration.ignoreShadowsSingleWindow = true+ configuration.ignoreGlobalClipSingleWindow = true++ let image = try await SCScreenshotManager.captureImage(+ contentFilter: filter,+ configuration: configuration+ )++ return CapturedTargetWindowFrame(+ imageWidth: image.width,+ imageHeight: image.height,+ captureMethod: .screenCaptureKitDesktopIndependentWindow,+ coordinateSpace: "screenCaptureKit.contentRect.pixels"+ )+ }+}++private struct SystemRunTraceTimestampProvider: RunTraceTimestampProviding {+ func now() -> RunTraceTimestamp {+ RunTraceTimestamp(+ wallClock: Date(),+ monotonicUptimeNanoseconds: UInt64(ProcessInfo.processInfo.systemUptime * 1_000_000_000)+ )+ }+}++private extension WindowTargetBounds {+ func intersects(_ other: WindowTargetBounds) -> Bool {+ let maxX = x + width+ let maxY = y + height+ let otherMaxX = other.x + other.width+ let otherMaxY = other.y + other.height++ return x < otherMaxX+ && maxX > other.x+ && y < otherMaxY+ && maxY > other.y+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/DryRunReflexLoopTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/DryRunReflexLoopTests.swiftnew file mode 100644index 00000000..cec82b28--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/DryRunReflexLoopTests.swift@@ -0,0 +1,225 @@+import DonkeyContracts+@testable import DonkeyRuntime+import Foundation+import Testing++@Suite+struct DryRunReflexLoopTests {+ @Test+ func syntheticFramesProduceOrderedReflexEventsAndTraces() async {+ let coordinator = RunCoordinator()+ let loop = DryRunReflexLoop(+ coordinator: coordinator,+ frameSource: SyntheticFrameSource(+ frames: [+ frame(id: "frame-1", milliseconds: 10),+ frame(id: "frame-2", milliseconds: 20)+ ]+ )+ )++ let result = await loop.run(session: session())++ #expect(result.processedFrameCount == 2)+ #expect(result.droppedFrameCount == 0)+ #expect(result.latestWorldState?.frameID == "frame-2")+ #expect(result.latestAction?.kind == .tapTarget)++ let events = await coordinator.events()+ #expect(events.map(\.sequence) == [1, 2, 3, 4, 5, 6])+ #expect(events.map(\.stream) == [+ .lifecycle,+ .lifecycle,+ .reflex,+ .reflex,+ .lifecycle,+ .lifecycle+ ])++ let traces = await coordinator.reflexTraces()+ #expect(traces.map(\.frameID) == ["frame-1", "frame-2"])+ #expect(traces.map(\.actionID) == ["action-state-frame-1", "action-state-frame-2"])+ #expect(traces.allSatisfy { $0.metadata["dryRun.executed"] == "false" })+ }++ @Test+ func latestFrameWinsBufferDropsStaleFrames() async {+ let coordinator = RunCoordinator()+ let loop = DryRunReflexLoop(+ coordinator: coordinator,+ frameSource: SyntheticFrameSource(+ batches: [[+ frame(id: "frame-stale-1", milliseconds: 10),+ frame(id: "frame-stale-2", milliseconds: 20),+ frame(id: "frame-latest", milliseconds: 30)+ ]]+ )+ )++ let result = await loop.run(session: session())++ #expect(result.processedFrameCount == 1)+ #expect(result.droppedFrameCount == 2)+ #expect(result.latestWorldState?.frameID == "frame-latest")+ #expect((await coordinator.reflexTraces()).map(\.frameID) == ["frame-latest"])+ }++ @Test+ func dryRunLoopCompletesThroughCoordinator() async {+ let coordinator = RunCoordinator()+ let loop = DryRunReflexLoop(+ coordinator: coordinator,+ frameSource: SyntheticFrameSource(frames: [frame(id: "frame-1", milliseconds: 10)])+ )++ _ = await loop.run(+ session: session(),+ completion: .complete(reason: "fixture complete")+ )++ let snapshot = await coordinator.snapshot()+ #expect(snapshot.lifecycleState == .completed)++ let events = await coordinator.events()+ #expect(lifecycleStates(in: events).suffix(2) == [.stopping, .completed])+ }++ @Test+ func dryRunLoopAbortRequestsInputReleaseWithoutInputToolExecution() async {+ let coordinator = RunCoordinator()+ let loop = DryRunReflexLoop(+ coordinator: coordinator,+ frameSource: SyntheticFrameSource(frames: [frame(id: "frame-abort", milliseconds: 10)])+ )++ _ = await loop.run(+ session: session(),+ completion: .abort(reason: "operator abort")+ )++ let events = await coordinator.events()+ #expect(lifecycleStates(in: events).last == .aborted)+ #expect(events.last?.requiresInputRelease == true)+ #expect(!eventsContainInputToolCall(events))+ }++ @Test+ func dryRunLoopTimeoutRequestsInputReleaseWithoutInputToolExecution() async {+ let coordinator = RunCoordinator()+ let loop = DryRunReflexLoop(+ coordinator: coordinator,+ frameSource: SyntheticFrameSource(frames: [frame(id: "frame-timeout", milliseconds: 10)])+ )++ _ = await loop.run(+ session: session(),+ completion: .timeout(reason: "deadline")+ )++ let events = await coordinator.events()+ #expect(lifecycleStates(in: events).last == .timedOut)+ #expect(events.last?.requiresInputRelease == true)+ #expect(!eventsContainInputToolCall(events))+ }++ @Test+ func emittedTraceLinksFrameStateActionPlannerHintAndLatency() async {+ let coordinator = RunCoordinator()+ let loop = DryRunReflexLoop(+ coordinator: coordinator,+ frameSource: SyntheticFrameSource(+ frames: [+ frame(+ id: "frame-linked",+ milliseconds: 10,+ plannerHintID: "hint-1"+ )+ ]+ )+ )++ _ = await loop.run(session: session())++ let trace = await coordinator.latestReflexTrace()+ #expect(trace?.traceID == "trace-frame-linked")+ #expect(trace?.frameID == "frame-linked")+ #expect(trace?.stateID == "state-frame-linked")+ #expect(trace?.actionID == "action-state-frame-linked")+ #expect(trace?.plannerHintID == "hint-1")+ #expect(trace?.latencyBreakdown.perceptionMS == 2)+ #expect(trace?.latencyBreakdown.decisionMS == 1)+ #expect(trace?.metadata["dryRun.mode"] == "dryRun")+ }++ private func session() -> RunSession {+ RunSession(+ id: "session-dry-run",+ userGoal: "tap visible target",+ targetID: "target-1"+ )+ }++ private func frame(+ id: String,+ milliseconds: UInt64,+ plannerHintID: String? = nil+ ) -> 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),+ plannerHintID: plannerHintID,+ metadata: [+ "tapTargetX": "0.4",+ "tapTargetY": "0.5",+ "tapTargetWidth": "0.1",+ "tapTargetHeight": "0.1",+ "tapTargetLabel": "start",+ "signalKind": "template",+ "signalConfidence": "0.85"+ ]+ )+ }++ private func timestamp(_ milliseconds: UInt64) -> RunTraceTimestamp {+ RunTraceTimestamp(+ wallClock: Date(timeIntervalSince1970: Double(milliseconds) / 1_000),+ monotonicUptimeNanoseconds: milliseconds * 1_000_000+ )+ }++ private func lifecycleStates(in events: [RunEvent]) -> [RunLifecycleState] {+ events.compactMap { event in+ guard case .lifecycle(let payload) = event.payload else { return nil }+ return payload.state+ }+ }++ private func eventsContainInputToolCall(_ events: [RunEvent]) -> Bool {+ events.contains { event in+ guard case .tool(let payload) = event.payload else { return false }+ return payload.capability == .input+ }+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/HotLoopContractsTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/HotLoopContractsTests.swiftnew file mode 100644index 00000000..2462357e--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/HotLoopContractsTests.swift@@ -0,0 +1,212 @@+import DonkeyContracts+import Foundation+import Testing++@Suite+struct HotLoopContractsTests {+ @Test+ func hotLoopContractsRoundTripThroughCodable() throws {+ let frame = syntheticFrame(id: "frame-1")+ let signal = HotLoopPerceptionSignal(+ id: "signal-1",+ traceID: "trace-1",+ frameID: frame.id,+ kind: "template",+ capturedAt: timestamp(10),+ observedAt: timestamp(12),+ confidence: 0.8,+ observations: [+ HotLoopPerceptionObservation(+ id: "observation-1",+ label: "button",+ bounds: HotLoopRect(+ x: 0.4,+ y: 0.5,+ width: 0.1,+ height: 0.1,+ space: .normalizedTarget+ ),+ confidence: 0.75+ )+ ],+ plannerHintID: "hint-1"+ )+ let affordance = HotLoopActionAffordance(+ id: "affordance-1",+ kind: .tapTarget,+ targetBounds: signal.observations[0].bounds,+ confidence: 0.75,+ sourceSignalID: signal.id+ )+ let worldState = HotLoopWorldState.build(+ id: "state-1",+ frame: frame,+ signals: [signal],+ observedAt: timestamp(12),+ staleThresholdMS: 250,+ actionAffordances: [affordance]+ )+ let action = HotLoopControllerAction(+ id: "action-1",+ traceID: frame.traceID,+ frameID: frame.id,+ stateID: worldState.id,+ kind: .tapTarget,+ target: affordance.targetBounds,+ policyName: "test-policy",+ confidence: 0.75,+ rationale: "fixture target"+ )+ let result = HotLoopActionResult(+ id: "result-1",+ traceID: frame.traceID,+ frameID: frame.id,+ stateID: worldState.id,+ actionID: action.id,+ mode: .dryRun,+ executed: false,+ enqueuedAt: timestamp(13),+ completedAt: timestamp(13),+ summary: "projected"+ )++ try roundTrip(frame)+ try roundTrip(frame.crop)+ try roundTrip(signal)+ try roundTrip(worldState)+ try roundTrip(action)+ try roundTrip(result)+ }++ @Test+ func coordinateMapperConvertsAcrossSpaces() throws {+ let mapper = HotLoopCoordinateMapper(+ windowBoundsInScreen: HotLoopRect(+ x: 100,+ y: 200,+ width: 400,+ height: 300,+ space: .screen+ ),+ cropBoundsInWindow: HotLoopRect(+ x: 50,+ y: 40,+ width: 200,+ height: 100,+ space: .window+ )+ )++ let screenPoint = HotLoopPoint(x: 200, y: 290, space: .screen)+ let windowPoint = try #require(mapper.convert(screenPoint, to: .window))+ let cropPoint = try #require(mapper.convert(windowPoint, to: .crop))+ let normalizedPoint = try #require(mapper.convert(cropPoint, to: .normalizedTarget))+ let convertedBackToScreen = try #require(mapper.convert(normalizedPoint, to: .screen))++ #expect(windowPoint == HotLoopPoint(x: 100, y: 90, space: .window))+ #expect(cropPoint == HotLoopPoint(x: 50, y: 50, space: .crop))+ #expect(normalizedPoint == HotLoopPoint(x: 0.25, y: 0.5, space: .normalizedTarget))+ #expect(convertedBackToScreen == screenPoint)++ let screenRect = HotLoopRect(+ x: 150,+ y: 240,+ width: 100,+ height: 50,+ space: .screen+ )+ let normalizedRect = try #require(mapper.convert(screenRect, to: .normalizedTarget))++ #expect(normalizedRect.origin == HotLoopPoint(x: 0, y: 0, space: .normalizedTarget))+ #expect(normalizedRect.size == HotLoopSize(width: 0.5, height: 0.5, space: .normalizedTarget))+ }++ @Test+ func coordinateMapperReturnsNilForZeroAreaBounds() {+ let mapper = HotLoopCoordinateMapper(+ windowBoundsInScreen: HotLoopRect(+ x: 0,+ y: 0,+ width: 0,+ height: 300,+ space: .screen+ ),+ cropBoundsInWindow: HotLoopRect(+ x: 0,+ y: 0,+ width: 200,+ height: 100,+ space: .window+ )+ )++ #expect(mapper.convert(HotLoopPoint(x: 1, y: 1, space: .screen), to: .window) == nil)+ }++ @Test+ func worldStateMarksStaleSignalsBySourceAge() {+ let frame = syntheticFrame(id: "frame-stale")+ let signal = HotLoopPerceptionSignal(+ id: "signal-stale",+ traceID: frame.traceID,+ frameID: frame.id,+ kind: "template",+ capturedAt: timestamp(0),+ observedAt: timestamp(10),+ confidence: 0.9+ )++ let state = HotLoopWorldState.build(+ id: "state-stale",+ frame: frame,+ signals: [signal],+ observedAt: timestamp(300),+ staleThresholdMS: 250+ )++ #expect(state.staleSignalIDs == ["signal-stale"])+ #expect(state.signalSummaries.first?.sourceAgeMS == 300)+ }++ private func roundTrip<T: Codable & Equatable>(_ value: T) throws {+ let data = try JSONEncoder().encode(value)+ let decoded = try JSONDecoder().decode(T.self, from: data)+ #expect(decoded == value)+ }++ private func syntheticFrame(id: String) -> HotLoopFrame {+ HotLoopFrame(+ id: id,+ traceID: "trace-\(id)",+ targetID: "target-1",+ capturedAt: timestamp(10),+ sourceKind: .synthetic,+ windowBounds: HotLoopRect(+ x: 100,+ y: 200,+ width: 400,+ height: 300,+ space: .screen+ ),+ crop: HotLoopCrop(+ id: "crop-1",+ bounds: HotLoopRect(+ x: 50,+ y: 40,+ width: 200,+ height: 100,+ space: .window+ ),+ outputSize: HotLoopSize(width: 200, height: 100, space: .crop)+ ),+ pixelSize: HotLoopSize(width: 400, height: 300, space: .window)+ )+ }++ private func timestamp(_ milliseconds: UInt64) -> RunTraceTimestamp {+ RunTraceTimestamp(+ wallClock: Date(timeIntervalSince1970: 0),+ monotonicUptimeNanoseconds: milliseconds * 1_000_000+ )+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/TargetWindowFrameSourceTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/TargetWindowFrameSourceTests.swiftnew file mode 100644index 00000000..67f872d6--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/TargetWindowFrameSourceTests.swift@@ -0,0 +1,307 @@+import DonkeyContracts+@testable import DonkeyRuntime+import Foundation+import Testing++@Suite+struct TargetWindowFrameSourceTests {+ @Test+ func captureFramesProducesBoundedTargetWindowHotLoopFrames() async throws {+ let capturer = FakeTargetWindowFrameCapturer(+ imageWidth: 320,+ imageHeight: 240+ )+ let service = makeService(+ windows: [+ fixtureWindow(+ windowID: 10,+ processID: 100,+ appName: "Preview",+ title: "Target"+ )+ ],+ frontmostProcessID: 100,+ capturer: capturer+ )++ let result = try await service.captureFrames(+ request: TargetWindowFrameCaptureRequest(+ selection: MacWindowSelectionRequest(windowID: 10),+ targetID: "target-1",+ traceID: "trace-window",+ frameIDPrefix: "window-frame",+ maxFrameCount: 2,+ plannerHintID: "hint-1"+ )+ )++ #expect(result.target.windowID == 10)+ #expect(result.captureMethod == .screenCaptureKitDesktopIndependentWindow)+ #expect(result.overlapStatus == .notRequired)+ #expect(capturer.capturedWindowIDs == [10, 10])+ #expect(result.frames.map(\.id) == ["window-frame-1", "window-frame-2"])+ #expect(result.frames.allSatisfy { $0.sourceKind == .targetWindow })+ #expect(result.frames.allSatisfy { $0.traceID == "trace-window" })+ #expect(result.frames.allSatisfy { $0.targetID == "target-1" })+ #expect(result.frames.allSatisfy { $0.plannerHintID == "hint-1" })+ #expect(result.frames.first?.pixelSize == HotLoopSize(width: 320, height: 240, space: .window))+ #expect(result.frames.first?.windowBounds == HotLoopRect(x: 0, y: 0, width: 100, height: 100, space: .screen))+ #expect(result.frames.first?.metadata["capture.encoded"] == "false")+ #expect(result.frames.first?.metadata["capture.artifactWritten"] == "false")+ #expect(result.frames.first?.metadata["capture.latencyMS"] == "5.0")+ #expect(result.frames.first?.metadata["capture.copyCostMS"] == "2.0")+ }++ @Test+ func captureFramesAppliesOptionalCropWithoutWritingPlannerSnapshotArtifact() async throws {+ let service = makeService(+ windows: [+ fixtureWindow(windowID: 22, processID: 200, appName: "Game")+ ],+ frontmostProcessID: 200,+ capturer: FakeTargetWindowFrameCapturer(+ imageWidth: 400,+ imageHeight: 300+ )+ )+ let cropBounds = HotLoopRect(+ x: 25,+ y: 50,+ width: 200,+ height: 100,+ space: .window+ )++ let result = try await service.captureFrames(+ request: TargetWindowFrameCaptureRequest(+ selection: MacWindowSelectionRequest(windowID: 22),+ targetID: "target-game",+ traceID: "trace-crop",+ maxFrameCount: 1,+ cropBoundsInWindow: cropBounds+ )+ )++ #expect(result.frames.first?.crop?.bounds == cropBounds)+ #expect(result.frames.first?.crop?.outputSize == HotLoopSize(width: 200, height: 100, space: .crop))+ #expect(result.frames.first?.metadata["capture.artifactWritten"] == "false")+ }++ @Test+ func unsafeTargetRefusesBeforeCapturingFrames() async throws {+ let capturer = FakeTargetWindowFrameCapturer()+ let service = makeService(+ windows: [+ fixtureWindow(windowID: 10, processID: 100, appName: "Safari", title: "Checkout Payment")+ ],+ frontmostProcessID: 100,+ capturer: capturer+ )++ do {+ _ = try await service.captureFrames(+ request: TargetWindowFrameCaptureRequest(+ selection: MacWindowSelectionRequest(windowID: 10),+ targetID: "target-1",+ traceID: "trace-unsafe",+ maxFrameCount: 1+ )+ )+ Issue.record("Expected unsafe target to be refused")+ } catch WindowScreenshotCaptureError.unsafeTarget(let windowID, let status) {+ #expect(windowID == 10)+ #expect(status == .blocked)+ } catch {+ Issue.record("Unexpected error: \(error)")+ }++ #expect(capturer.capturedWindowIDs.isEmpty)+ }++ @Test+ func overlapSensitiveFrameBackendRefusesOccludedTarget() async throws {+ let capturer = FakeTargetWindowFrameCapturer(+ captureMethod: .boundsCrop,+ requiresOverlapFreeTarget: true+ )+ let service = makeService(+ windows: [+ fixtureWindow(+ windowID: 1,+ processID: 100,+ appName: "Occluder",+ bounds: WindowTargetBounds(x: 25, y: 25, width: 50, height: 50)+ ),+ fixtureWindow(+ windowID: 2,+ processID: 200,+ appName: "Target",+ bounds: WindowTargetBounds(x: 0, y: 0, width: 100, height: 100)+ )+ ],+ frontmostProcessID: 200,+ capturer: capturer+ )++ do {+ _ = try await service.captureFrames(+ request: TargetWindowFrameCaptureRequest(+ selection: MacWindowSelectionRequest(windowID: 2),+ targetID: "target-1",+ traceID: "trace-occluded",+ maxFrameCount: 1+ )+ )+ Issue.record("Expected occluded target to be refused")+ } catch WindowScreenshotCaptureError.occludedTarget(let windowID, let occludingWindowID) {+ #expect(windowID == 2)+ #expect(occludingWindowID == 1)+ } catch {+ Issue.record("Unexpected error: \(error)")+ }++ #expect(capturer.capturedWindowIDs.isEmpty)+ }++ @Test+ func targetWindowFrameSourceFeedsDryRunFrameBatches() async {+ let service = makeService(+ windows: [+ fixtureWindow(windowID: 30, processID: 300, appName: "Game")+ ],+ frontmostProcessID: 300,+ capturer: FakeTargetWindowFrameCapturer()+ )+ let source = TargetWindowFrameSource(+ service: service,+ request: TargetWindowFrameCaptureRequest(+ selection: MacWindowSelectionRequest(windowID: 30),+ targetID: "target-game",+ traceID: "trace-source",+ frameIDPrefix: "source-frame",+ maxFrameCount: 2+ )+ )++ let batches = await source.frameBatches()++ #expect(batches.count == 2)+ #expect(batches.allSatisfy { $0.count == 1 })+ #expect(batches.flatMap { $0 }.map(\.id) == ["source-frame-1", "source-frame-2"])+ }++ private func makeService(+ windows: [MacWindowProviderWindow],+ frontmostProcessID: Int32? = nil,+ focusedWindowID: UInt32? = nil,+ capturer: FakeTargetWindowFrameCapturer+ ) -> TargetWindowFrameCaptureService {+ TargetWindowFrameCaptureService(+ windowResolver: MacWindowResolver(+ provider: FixtureWindowProvider(+ windows: windows,+ frontmostProcessID: frontmostProcessID,+ focusedWindowID: focusedWindowID+ )+ ),+ capturer: capturer,+ timestampProvider: FixtureTimestampProvider()+ )+ }++ private func fixtureWindow(+ windowID: UInt32,+ processID: Int32,+ appName: String? = nil,+ bundleIdentifier: String? = nil,+ title: String? = nil,+ bounds: WindowTargetBounds = WindowTargetBounds(+ x: 0,+ y: 0,+ width: 100,+ height: 100+ )+ ) -> MacWindowProviderWindow {+ MacWindowProviderWindow(+ windowID: windowID,+ processID: processID,+ appName: appName,+ bundleIdentifier: bundleIdentifier,+ title: title,+ bounds: bounds+ )+ }+}++private final class FakeTargetWindowFrameCapturer: TargetWindowFrameCapturing, @unchecked Sendable {+ var imageWidth: Int+ var imageHeight: Int+ var captureMethod: WindowScreenshotCaptureMethod+ var requiresOverlapFreeTarget: Bool+ var capturedWindowIDs: [UInt32] = []++ init(+ imageWidth: Int = 100,+ imageHeight: Int = 100,+ captureMethod: WindowScreenshotCaptureMethod = .screenCaptureKitDesktopIndependentWindow,+ requiresOverlapFreeTarget: Bool = false+ ) {+ self.imageWidth = imageWidth+ self.imageHeight = imageHeight+ self.captureMethod = captureMethod+ self.requiresOverlapFreeTarget = requiresOverlapFreeTarget+ }++ func captureFrame(+ target: MacWindowTargetCandidate+ ) async throws -> CapturedTargetWindowFrame {+ capturedWindowIDs.append(target.windowID)+ return CapturedTargetWindowFrame(+ imageWidth: imageWidth,+ imageHeight: imageHeight,+ captureMethod: captureMethod,+ coordinateSpace: "fixture.window.pixels"+ )+ }+}++private final class FixtureTimestampProvider: RunTraceTimestampProviding, @unchecked Sendable {+ private var nextMilliseconds: UInt64 = 0++ func now() -> RunTraceTimestamp {+ defer { nextMilliseconds += nextMilliseconds % 4 == 0 ? 5 : nextMilliseconds % 4 == 1 ? 1 : 2 }++ return RunTraceTimestamp(+ wallClock: Date(timeIntervalSince1970: Double(nextMilliseconds) / 1_000),+ monotonicUptimeNanoseconds: nextMilliseconds * 1_000_000+ )+ }+}++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+ }+}diff --git a/docs/guides/minimal-run-coordinator.md b/docs/guides/minimal-run-coordinator.mdindex eb3a6155..611939f6 100644--- a/docs/guides/minimal-run-coordinator.md+++ b/docs/guides/minimal-run-coordinator.md@@ -16,6 +16,12 @@ The coordinator can:Donkey also supports the first real reflex trace shape for the off-the-shelf run loop. Reflex traces can carry monotonic timing checkpoints for capture, preprocessing, model inference, perception, state publication, controller decision, action enqueue, and input execution. The shared contracts derive stage latency, software-loop latency, frame age, and state age from monotonic timestamps only. `RunCoordinator` can append a `ReflexTraceRecord`, retain it in a bounded in-memory trace store, and publish a matching `reflex` event with compact latency metadata.+Donkey also supports shared hot-loop contracts for deterministic reflex-loop slices. Frames, crops, coordinate spaces, perception signals, compact world states, controller actions, and action results are typed, Codable, Sendable contracts. Coordinate spaces are explicit across screen, window, crop, and normalized target space. Perception signals carry confidence and monotonic source age, and stale signals are marked on world state instead of being silently reused.++Donkey also supports a deterministic dry-run reflex loop skeleton. The loop consumes synthetic or recorded frame batches through a latest-frame-wins buffer with queue depth 1, counts dropped frames, converts signals into compact world state, chooses an inspectable semantic action, projects the action in dry-run mode without OS input, and publishes `ReflexTraceRecord` samples through `RunCoordinator`. This skeleton is for contract validation and replayable tests only; target-window continuous capture and live input are not supported yet.++Donkey also supports a bounded target-window frame source for the dry-run hot-loop boundary. The frame source reuses macOS window selection and safety checks, captures selected windows through ScreenCaptureKit's desktop-independent window path, returns `HotLoopFrame` metadata for a caller-provided maximum frame count, and records capture latency and copy cost with monotonic timestamps. This path does not write screenshot artifacts and does not PNG/JPEG encode or decode frames. High-resolution manual screenshot artifacts remain separate from reflex frames.+Donkey also supports a 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@@ -37,7 +43,7 @@ Donkey supports a runtime-level manual target context capture service that wiresThe 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, target-metadata, single-screenshot artifact, read-only Accessibility snapshot, and manual capture orchestration foundation only. It does not run perception models, call LLMs, execute OS input, perform Accessibility actions, provide a manual capture UI, persist high-volume reflex traces to disk, or provide the full real-time capture/perception/controller loop yet.+This is a coordination, in-memory reflex trace, hot-loop contract, deterministic dry-run skeleton, bounded target-window frame-source, target-metadata, single-screenshot artifact, read-only Accessibility snapshot, and manual capture orchestration foundation only. It does not run real perception models, 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.## Technical Guidelines@@ -53,6 +59,11 @@ This is a coordination, in-memory reflex trace, target-metadata, single-screensh- Keep mutable installed-app run artifacts in Application Support, not inside the `.app` bundle and not relative to process working directory.- Keep input actions denied unless a caller provides a policy that explicitly allows them.- Preserve latest-request-wins behavior for live-control sessions so stale work cannot build up behind the reflex loop.+- Keep hot-loop data flowing through `DonkeyContracts` types. Controllers should consume `HotLoopWorldState`, not raw screenshots, detector tensors, or untyped metadata.+- Keep dry-run action projection side-effect free. It records semantic action intent and trace evidence, but never calls the input capability.+- Keep reflex frame buffers at queue depth 1. Dropped frames are expected under pressure and should be counted.+- Keep target-window reflex frames bounded by caller-provided frame count until a streaming capture loop exists.+- Keep manual screenshot artifacts and high-resolution planner snapshots separate from reflex frames. The reflex frame source should not encode PNG/JPEG or write screenshot artifacts.- Use monotonic timestamps for latency math. Wall-clock timestamps are for human labels and trace correlation only.- 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.@@ -65,7 +76,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, 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, 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:@@ -83,8 +94,11 @@ Remaining live verification is environment-dependent. On May 16, 2026, iPhone Mi## Source Entry Points- Runtime contracts live in `apps/Donkey/Sources/DonkeyContracts/RunLoopContracts.swift`.+- Hot-loop contracts live in `apps/Donkey/Sources/DonkeyContracts/HotLoopContracts.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`.+- Bounded target-window reflex frame capture lives in `apps/Donkey/Sources/DonkeyRuntime/TargetWindowFrameSource.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/00-overview.md b/plans/00-overview.mdindex 3e6e5d5c..4fc27326 100644--- a/plans/00-overview.md+++ b/plans/00-overview.md@@ -6,11 +6,11 @@ Build a desktop AI agent that can play iPhone games through Apple's iPhone MirroiPhone games are the first product focus. Gaming is the latency proof. The larger platform is real-time desktop and mobile-app control from the Mac.-## Current Focus+## Current Master Plan-The manual target context capture milestone is complete in [done/manual-target-context-capture-master-plan.md](done/manual-target-context-capture-master-plan.md).+Start with [master-plan.md](master-plan.md).-Continue feature work from [20-off-the-shelf-run-loop.md](20-off-the-shelf-run-loop.md), with [02-capture-and-perception.md](02-capture-and-perception.md), [06-benchmarking.md](06-benchmarking.md), and [18-macos-accessibility.md](18-macos-accessibility.md) as the near-term supporting plans.+That plan coordinates the next sequence of edits across the off-the-shelf run loop and AI harness, with latency, capture/perception, controller, planner, action-engine, and benchmarking plans as supporting constraints. The manual target context capture milestone is complete in [done/manual-target-context-capture-master-plan.md](done/manual-target-context-capture-master-plan.md).## Near-Term Focus@@ -61,6 +61,7 @@ Every frame should use local, bounded-cost logic:## Plan Breakdown- [done/manual-target-context-capture-master-plan.md](done/manual-target-context-capture-master-plan.md): completed manual screenshot, Accessibility tree, and trace artifact capture milestone+- [master-plan.md](master-plan.md): current master plan for closing out the off-the-shelf run loop and AI harness milestones- [01-latency-budget.md](01-latency-budget.md): hard timing budget and optimization priorities- [02-capture-and-perception.md](02-capture-and-perception.md): screen capture, visual parsing, and world-state updates- [03-fast-controller.md](03-fast-controller.md): real-time controller designdiff --git a/plans/master-plan.md b/plans/master-plan.mdnew file mode 100644index 00000000..134fdd4e--- /dev/null+++ b/plans/master-plan.md@@ -0,0 +1,177 @@+# Real-Time Run Loop And AI Harness Master Plan++This file is the active task queue for closing out the off-the-shelf real-time run loop and slow-path AI harness milestones.++Primary plans:++- `plans/20-off-the-shelf-run-loop.md`+- `plans/19-ai-harness.md`++Supporting plans:++- `plans/01-latency-budget.md`+- `plans/02-capture-and-perception.md`+- `plans/03-fast-controller.md`+- `plans/04-slow-planner.md`+- `plans/05-action-engine.md`+- `plans/06-benchmarking.md`++Supported behavior and engineering guidance belong in `docs/guides/`. This master plan should shrink as slices become supported.++## 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.++## Milestone Goal++Build the first product-shaped loop where Donkey can run a target-window session with local, bounded reflex behavior and an optional slow AI sidecar:++```text+target window capture+ -> crop / normalize+ -> local perception or cheap template signal+ -> compact world state+ -> deterministic controller+ -> dry-run action trace first, guarded live action later+ -> latency report and replayable trace++slow AI harness+ -> compact snapshot+ -> model router+ -> structured planner hint+ -> validated hint bus+ -> scoped memory proposal+```++The hot path must continue to work with the AI harness disabled.++## Current Supported Baseline++- 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.++## Non-Negotiable Rules++- No remote model call, chat LLM call, or general VLM call may be required for a reflex tick.+- The reflex path uses latest-frame-wins queues; stale frames are dropped and counted.+- The controller consumes typed world state, not raw screenshots.+- The action engine owns OS input; controller policies emit semantic commands only.+- Input starts in dry-run mode. Live input requires policy allowance, focus guard success, and emergency release support.+- Planner output is a validated, expiring hint. It is never direct input.+- 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.++## Remaining Tasks++4. Add the first cheap perception adapter.+ - Start with deterministic template, color, edge, OCR-crop stub, or synthetic detector signal before adding heavier models.+ - Convert perception output into compact world state.+ - Include signal confidence and age.+ - Keep detector tensors, masks, and raw pixels behind perception boundaries.+ - Add replay tests from recorded or fixture frames.++5. Add deterministic controller and dry-run action projection.+ - Define policy selection and one inspectable rule/state-machine policy for the first supported behavior.+ - Emit semantic action commands with state id, action id, policy name, confidence, and rationale metadata.+ - Add confidence-aware fallback behavior.+ - Record every chosen action in traces.+ - Prove controller p95 decision time under 20ms in replay.++6. Add action-engine guardrails before live input.+ - Define command interface for tap, swipe, key, mouse, controller, and `release_all`.+ - Add focus guard, permission policy check, held-input release, rate limits, and maximum hold durations.+ - Keep live input disabled by default until dry-run traces and guard behavior pass.+ - Add replayable command traces.++7. Add latency reports and replay benchmark mode.+ - Produce a CLI latency report from reflex traces.+ - Report p50/p95/p99, capture FPS, perception FPS, controller tick rate, dropped frames, stale actions, and worst traces.+ - Add capture-only, controller-only, and end-to-end dry-run benchmark modes.+ - Add baseline files per target and machine class when a real target is selected.++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.++## What Should Be Done Next++Start with task 4: add the first cheap perception adapter.++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, and bounded selected-window frame capture. It still needs a cheap deterministic perception adapter that converts fixture or target-window frame metadata into compact world state before controller replay can become target-shaped.++## Closeout Criteria++This master plan is complete when:++- The off-the-shelf run loop can run a selected target in dry-run mode end to end.+- A selected first behavior can be exercised with guarded live input after dry-run success.+- Capture, perception, controller, action, and input stages are measured with monotonic timestamps.+- p50 and p95 reflex latency are reported for the first supported target.+- The hot loop still works with the AI harness disabled.+- Planner hints are structured, validated, expiring, trace-linked, and optional.+- Memory writes are source-linked, scoped, inspectable, deleteable, and deterministically approved.+- Model routing uses registry roles instead of scattered literal model ids.+- Replay/eval exists for controller traces and model/prompt changes.+- Supported behavior is documented in `docs/guides/`.+- `plans/19-ai-harness.md` and `plans/20-off-the-shelf-run-loop.md` are moved to `plans/done/`.