Open source CapCut alternative.
TypeScript
Add action guardrails and dry-run latency reports
David Le7e5a85807dd2
diff --git a/apps/Donkey/Sources/Donkey/ManualCaptureDebugLaunchHandler.swift b/apps/Donkey/Sources/Donkey/ManualCaptureDebugLaunchHandler.swiftindex 9c84ef91..fa1216ac 100644--- a/apps/Donkey/Sources/Donkey/ManualCaptureDebugLaunchHandler.swift+++ b/apps/Donkey/Sources/Donkey/ManualCaptureDebugLaunchHandler.swift@@ -46,6 +46,14 @@ struct ManualCaptureDebugLaunchHandler {))return 0+ case .dryRunLatencyReport(let options):+ let report = await ReflexReplayBenchmark(+ mode: options.mode,+ frameCount: options.frameCount+ )+ .run()+ printLines(ReflexLatencyReportFormatter.lines(for: report))+ return 0}} catch {printError(ManualCaptureDebugCommandFormatter.errorLine(for: error))diff --git a/apps/Donkey/Sources/DonkeyRuntime/ActionEngineGuardrails.swift b/apps/Donkey/Sources/DonkeyRuntime/ActionEngineGuardrails.swiftnew file mode 100644index 00000000..316ae7c1--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/ActionEngineGuardrails.swift@@ -0,0 +1,281 @@+import DonkeyContracts+import Foundation++public enum ActionEngineCommandKind: String, Codable, Equatable, Sendable {+ case tap+ case swipe+ case key+ case mouse+ case controller+ case releaseAll+}++public struct ActionEngineCommand: Codable, Equatable, Sendable {+ public var id: String+ public var traceID: String+ public var targetID: String+ public var stateID: String?+ public var actionID: String?+ public var kind: ActionEngineCommandKind+ public var issuedAt: RunTraceTimestamp+ public var targetBounds: HotLoopRect?+ public var key: String?+ public var holdDurationMS: Double?+ public var metadata: [String: String]++ public init(+ id: String,+ traceID: String,+ targetID: String,+ stateID: String? = nil,+ actionID: String? = nil,+ kind: ActionEngineCommandKind,+ issuedAt: RunTraceTimestamp,+ targetBounds: HotLoopRect? = nil,+ key: String? = nil,+ holdDurationMS: Double? = nil,+ metadata: [String: String] = [:]+ ) {+ self.id = id+ self.traceID = traceID+ self.targetID = targetID+ self.stateID = stateID+ self.actionID = actionID+ self.kind = kind+ self.issuedAt = issuedAt+ self.targetBounds = targetBounds+ self.key = key+ self.holdDurationMS = holdDurationMS+ self.metadata = metadata+ }+}++public enum ActionEngineCommandDecision: Codable, Equatable, Sendable {+ case projectedDryRun+ case denied(reason: String)+}++public struct ActionEngineCommandTrace: Codable, Equatable, Sendable {+ public var command: ActionEngineCommand+ public var decision: ActionEngineCommandDecision+ public var recordedAt: RunTraceTimestamp+ public var executed: Bool+ public var liveInputEnabled: Bool+ public var focusGuardPassed: Bool+ public var permissionDecision: ToolCallDecision+ public var rateLimited: Bool+ public var releaseAll: Bool+ public var metadata: [String: String]++ public init(+ command: ActionEngineCommand,+ decision: ActionEngineCommandDecision,+ recordedAt: RunTraceTimestamp,+ executed: Bool,+ liveInputEnabled: Bool,+ focusGuardPassed: Bool,+ permissionDecision: ToolCallDecision,+ rateLimited: Bool,+ releaseAll: Bool,+ metadata: [String: String] = [:]+ ) {+ self.command = command+ self.decision = decision+ self.recordedAt = recordedAt+ self.executed = executed+ self.liveInputEnabled = liveInputEnabled+ self.focusGuardPassed = focusGuardPassed+ self.permissionDecision = permissionDecision+ self.rateLimited = rateLimited+ self.releaseAll = releaseAll+ self.metadata = metadata+ }+}++public struct ActionEngineConfiguration: Equatable, Sendable {+ public var liveInputEnabled: Bool+ public var minimumCommandIntervalMS: Double+ public var maximumHoldDurationMS: Double++ public init(+ liveInputEnabled: Bool = false,+ minimumCommandIntervalMS: Double = 20,+ maximumHoldDurationMS: Double = 500+ ) {+ self.liveInputEnabled = liveInputEnabled+ self.minimumCommandIntervalMS = minimumCommandIntervalMS+ self.maximumHoldDurationMS = maximumHoldDurationMS+ }+}++public protocol ActionEngineFocusGuard: Sendable {+ func targetIsSafeForInput(targetID: String) async -> Bool+}++public struct AlwaysSafeActionEngineFocusGuard: ActionEngineFocusGuard {+ public init() {}++ public func targetIsSafeForInput(targetID: String) async -> Bool {+ true+ }+}++public actor ActionEngineGuardrail {+ private let configuration: ActionEngineConfiguration+ private let focusGuard: any ActionEngineFocusGuard+ private var traces: [ActionEngineCommandTrace] = []+ private var heldCommandIDs: Set<String> = []+ private var lastAcceptedCommandAt: RunTraceTimestamp?++ public init(+ configuration: ActionEngineConfiguration = ActionEngineConfiguration(),+ focusGuard: any ActionEngineFocusGuard = AlwaysSafeActionEngineFocusGuard()+ ) {+ self.configuration = configuration+ self.focusGuard = focusGuard+ }++ @discardableResult+ public func handle(+ _ command: ActionEngineCommand,+ permissionPolicy: ToolCallPolicy = .default+ ) async -> ActionEngineCommandTrace {+ if command.kind == .releaseAll {+ heldCommandIDs.removeAll()+ return appendTrace(+ command: command,+ decision: .projectedDryRun,+ focusGuardPassed: true,+ permissionDecision: .allow,+ rateLimited: false,+ releaseAll: true,+ metadata: ["heldInputReleased": "true"]+ )+ }++ let permissionDecision = permissionPolicy.decision(for: .input)+ guard permissionDecision.isAllowed else {+ return appendTrace(+ command: command,+ decision: .denied(reason: "input permission denied"),+ focusGuardPassed: false,+ permissionDecision: permissionDecision,+ rateLimited: false,+ releaseAll: false+ )+ }++ let focusPassed = await focusGuard.targetIsSafeForInput(targetID: command.targetID)+ guard focusPassed else {+ return appendTrace(+ command: command,+ decision: .denied(reason: "focus guard failed"),+ focusGuardPassed: false,+ permissionDecision: permissionDecision,+ rateLimited: false,+ releaseAll: false+ )+ }++ if let holdDurationMS = command.holdDurationMS,+ holdDurationMS > configuration.maximumHoldDurationMS {+ return appendTrace(+ command: command,+ decision: .denied(reason: "hold duration exceeds maximum"),+ focusGuardPassed: true,+ permissionDecision: permissionDecision,+ rateLimited: false,+ releaseAll: false,+ metadata: [+ "maximumHoldDurationMS": String(configuration.maximumHoldDurationMS)+ ]+ )+ }++ if let lastAcceptedCommandAt,+ let elapsedMS = lastAcceptedCommandAt.milliseconds(until: command.issuedAt),+ elapsedMS < configuration.minimumCommandIntervalMS {+ return appendTrace(+ command: command,+ decision: .denied(reason: "rate limited"),+ focusGuardPassed: true,+ permissionDecision: permissionDecision,+ rateLimited: true,+ releaseAll: false,+ metadata: [+ "minimumCommandIntervalMS": String(configuration.minimumCommandIntervalMS),+ "elapsedMS": String(elapsedMS)+ ]+ )+ }++ lastAcceptedCommandAt = command.issuedAt+ if (command.holdDurationMS ?? 0) > 0 {+ heldCommandIDs.insert(command.id)+ }++ return appendTrace(+ command: command,+ decision: .projectedDryRun,+ focusGuardPassed: true,+ permissionDecision: permissionDecision,+ rateLimited: false,+ releaseAll: false,+ metadata: [+ "heldInputCount": String(heldCommandIDs.count),+ "liveInputBackend": "notImplemented"+ ]+ )+ }++ public func releaseAll(+ traceID: String,+ targetID: String,+ issuedAt: RunTraceTimestamp+ ) async -> ActionEngineCommandTrace {+ await handle(+ ActionEngineCommand(+ id: "release-all-\(traceID)",+ traceID: traceID,+ targetID: targetID,+ kind: .releaseAll,+ issuedAt: issuedAt+ ),+ permissionPolicy: ToolCallPolicy(deniedCapabilities: [])+ )+ }++ public func allTraces() -> [ActionEngineCommandTrace] {+ traces+ }++ public func heldInputCount() -> Int {+ heldCommandIDs.count+ }++ private func appendTrace(+ command: ActionEngineCommand,+ decision: ActionEngineCommandDecision,+ focusGuardPassed: Bool,+ permissionDecision: ToolCallDecision,+ rateLimited: Bool,+ releaseAll: Bool,+ metadata: [String: String] = [:]+ ) -> ActionEngineCommandTrace {+ let trace = ActionEngineCommandTrace(+ command: command,+ decision: decision,+ recordedAt: command.issuedAt,+ executed: false,+ liveInputEnabled: configuration.liveInputEnabled,+ focusGuardPassed: focusGuardPassed,+ permissionDecision: permissionDecision,+ rateLimited: rateLimited,+ releaseAll: releaseAll,+ metadata: metadata+ )++ traces.append(trace)+ return trace+ }+}diff --git a/apps/Donkey/Sources/DonkeyRuntime/ManualCaptureDebugCommand.swift b/apps/Donkey/Sources/DonkeyRuntime/ManualCaptureDebugCommand.swiftindex 0d62e675..595e5828 100644--- a/apps/Donkey/Sources/DonkeyRuntime/ManualCaptureDebugCommand.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/ManualCaptureDebugCommand.swift@@ -4,6 +4,7 @@ import Foundationpublic enum ManualCaptureDebugCommand: Equatable, Sendable {case listWindowCandidatescase manualCapture(ManualCaptureDebugCaptureOptions)+ case dryRunLatencyReport(DryRunLatencyReportDebugOptions)}public struct ManualCaptureDebugCaptureOptions: Equatable, Sendable {@@ -22,11 +23,26 @@ public struct ManualCaptureDebugCaptureOptions: Equatable, Sendable {}}+public struct DryRunLatencyReportDebugOptions: Equatable, Sendable {+ public var frameCount: Int+ public var mode: ReflexReplayBenchmarkMode++ public init(+ frameCount: Int = 30,+ mode: ReflexReplayBenchmarkMode = .endToEndDryRun+ ) {+ self.frameCount = frameCount+ self.mode = mode+ }+}+public enum ManualCaptureDebugCommandParseError: Error, Equatable, Sendable, CustomStringConvertible {case conflictingCommandscase missingCommandcase missingValue(String)case invalidWindowID(String)+ case invalidFrameCount(String)+ case invalidBenchmarkMode(String)case invalidIdentifier(option: String, value: String)case unsupportedOption(String)@@ -40,6 +56,10 @@ public enum ManualCaptureDebugCommandParseError: Error, Equatable, Sendable, Cusreturn "Missing value for \(option)."case .invalidWindowID(let value):return "Invalid --window-id value: \(value)."+ case .invalidFrameCount(let value):+ return "Invalid --frame-count value: \(value)."+ case .invalidBenchmarkMode(let value):+ return "Invalid --benchmark-mode value: \(value)."case .invalidIdentifier(let option, let value):return "Invalid \(option) value: \(value). Use letters, numbers, '.', '_', or '-'."case .unsupportedOption(let option):@@ -53,9 +73,12 @@ public enum ManualCaptureDebugCommandParser {normalizedArguments(arguments).contains { argument inargument == "--list-window-candidates"|| argument == "--manual-capture"+ || argument == "--dry-run-latency-report"|| argument == "--window-id"|| argument == "--run-id"|| argument == "--trace-id"+ || argument == "--frame-count"+ || argument == "--benchmark-mode"}}@@ -71,6 +94,8 @@ public enum ManualCaptureDebugCommandParser {var windowID: UInt32?var runID: String?var traceID: String?+ var frameCount = 30+ var benchmarkMode = ReflexReplayBenchmarkMode.endToEndDryRunvar index = 0while index < arguments.count {@@ -82,6 +107,9 @@ public enum ManualCaptureDebugCommandParser {case "--manual-capture":try setMode(.manualCapture, current: &mode)index += 1+ case "--dry-run-latency-report":+ try setMode(.dryRunLatencyReport, current: &mode)+ index += 1case "--window-id":let value = try value(after: argument, in: arguments, at: index)guard let parsed = UInt32(value) else {@@ -99,6 +127,20 @@ public enum ManualCaptureDebugCommandParser {try validateIdentifier(value, option: argument)traceID = valueindex += 2+ case "--frame-count":+ let value = try value(after: argument, in: arguments, at: index)+ guard let parsed = Int(value), parsed > 0 else {+ throw ManualCaptureDebugCommandParseError.invalidFrameCount(value)+ }+ frameCount = parsed+ index += 2+ case "--benchmark-mode":+ let value = try value(after: argument, in: arguments, at: index)+ guard let parsed = ReflexReplayBenchmarkMode(rawValue: value) else {+ throw ManualCaptureDebugCommandParseError.invalidBenchmarkMode(value)+ }+ benchmarkMode = parsed+ index += 2default:throw ManualCaptureDebugCommandParseError.unsupportedOption(argument)}@@ -110,13 +152,18 @@ public enum ManualCaptureDebugCommandParser {switch mode {case .listWindowCandidates:- guard windowID == nil, runID == nil, traceID == nil else {+ guard windowID == nil, runID == nil, traceID == nil, frameCount == 30, benchmarkMode == .endToEndDryRun else {throw ManualCaptureDebugCommandParseError.unsupportedOption(- "capture options require --manual-capture"+ "options are not supported with --list-window-candidates")}return .listWindowCandidatescase .manualCapture:+ guard frameCount == 30, benchmarkMode == .endToEndDryRun else {+ throw ManualCaptureDebugCommandParseError.unsupportedOption(+ "benchmark options require --dry-run-latency-report"+ )+ }return .manualCapture(ManualCaptureDebugCaptureOptions(selection: MacWindowSelectionRequest(windowID: windowID),@@ -124,6 +171,18 @@ public enum ManualCaptureDebugCommandParser {traceID: traceID))+ case .dryRunLatencyReport:+ guard windowID == nil, runID == nil, traceID == nil else {+ throw ManualCaptureDebugCommandParseError.unsupportedOption(+ "capture options require --manual-capture"+ )+ }+ return .dryRunLatencyReport(+ DryRunLatencyReportDebugOptions(+ frameCount: frameCount,+ mode: benchmarkMode+ )+ )}}@@ -263,4 +322,5 @@ public enum ManualCaptureDebugCommandFormatter {private enum ManualCaptureDebugCommandMode {case listWindowCandidatescase manualCapture+ case dryRunLatencyReport}diff --git a/apps/Donkey/Sources/DonkeyRuntime/ReflexLatencyReport.swift b/apps/Donkey/Sources/DonkeyRuntime/ReflexLatencyReport.swiftnew file mode 100644index 00000000..2e77c445--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/ReflexLatencyReport.swift@@ -0,0 +1,299 @@+import DonkeyContracts+import Foundation++public enum ReflexReplayBenchmarkMode: String, Codable, Equatable, Sendable {+ case captureOnly+ case controllerOnly+ case endToEndDryRun+}++public struct ReflexLatencyPercentiles: Codable, Equatable, Sendable {+ public var p50: Double?+ public var p95: Double?+ public var p99: Double?++ public init(p50: Double? = nil, p95: Double? = nil, p99: Double? = nil) {+ self.p50 = p50+ self.p95 = p95+ self.p99 = p99+ }+}++public struct ReflexWorstTrace: Codable, Equatable, Sendable {+ public var traceID: String+ public var frameID: String+ public var softwareLoopMS: Double?++ public init(traceID: String, frameID: String, softwareLoopMS: Double?) {+ self.traceID = traceID+ self.frameID = frameID+ self.softwareLoopMS = softwareLoopMS+ }+}++public struct ReflexLatencyReport: Codable, Equatable, Sendable {+ public var mode: ReflexReplayBenchmarkMode+ public var traceCount: Int+ public var softwareLoopMS: ReflexLatencyPercentiles+ public var captureMS: ReflexLatencyPercentiles+ public var perceptionMS: ReflexLatencyPercentiles+ public var decisionMS: ReflexLatencyPercentiles+ public var inputMS: ReflexLatencyPercentiles+ public var captureFPS: Double?+ public var perceptionFPS: Double?+ public var controllerTickRate: Double?+ public var droppedFrameCount: Int+ public var staleActionCount: Int+ public var worstTraces: [ReflexWorstTrace]+ public var metadata: [String: String]++ public init(+ mode: ReflexReplayBenchmarkMode,+ traceCount: Int,+ softwareLoopMS: ReflexLatencyPercentiles,+ captureMS: ReflexLatencyPercentiles,+ perceptionMS: ReflexLatencyPercentiles,+ decisionMS: ReflexLatencyPercentiles,+ inputMS: ReflexLatencyPercentiles,+ captureFPS: Double? = nil,+ perceptionFPS: Double? = nil,+ controllerTickRate: Double? = nil,+ droppedFrameCount: Int = 0,+ staleActionCount: Int = 0,+ worstTraces: [ReflexWorstTrace] = [],+ metadata: [String: String] = [:]+ ) {+ self.mode = mode+ self.traceCount = traceCount+ self.softwareLoopMS = softwareLoopMS+ self.captureMS = captureMS+ self.perceptionMS = perceptionMS+ self.decisionMS = decisionMS+ self.inputMS = inputMS+ self.captureFPS = captureFPS+ self.perceptionFPS = perceptionFPS+ self.controllerTickRate = controllerTickRate+ self.droppedFrameCount = droppedFrameCount+ self.staleActionCount = staleActionCount+ self.worstTraces = worstTraces+ self.metadata = metadata+ }+}++public struct ReflexBenchmarkBaseline: Codable, Equatable, Sendable {+ public var targetID: String+ public var machineClass: String+ public var report: ReflexLatencyReport++ public init(+ targetID: String,+ machineClass: String,+ report: ReflexLatencyReport+ ) {+ self.targetID = targetID+ self.machineClass = machineClass+ self.report = report+ }+}++public enum ReflexLatencyReportBuilder {+ public static func build(+ from traces: [ReflexTraceRecord],+ mode: ReflexReplayBenchmarkMode = .endToEndDryRun,+ droppedFrameCount: Int = 0,+ metadata: [String: String] = [:]+ ) -> ReflexLatencyReport {+ ReflexLatencyReport(+ mode: mode,+ traceCount: traces.count,+ softwareLoopMS: percentiles(traces.compactMap(\.latencyBreakdown.softwareLoopMS)),+ captureMS: percentiles(traces.compactMap(\.latencyBreakdown.captureMS)),+ perceptionMS: percentiles(traces.compactMap(\.latencyBreakdown.perceptionMS)),+ decisionMS: percentiles(traces.compactMap(\.latencyBreakdown.decisionMS)),+ inputMS: percentiles(traces.compactMap(\.latencyBreakdown.inputMS)),+ captureFPS: rate(+ count: traces.count,+ first: traces.compactMap(\.timestamps.captureEnd).first,+ last: traces.compactMap(\.timestamps.captureEnd).last+ ),+ perceptionFPS: rate(+ count: traces.count,+ first: traces.compactMap(\.timestamps.perceptionEnd).first,+ last: traces.compactMap(\.timestamps.perceptionEnd).last+ ),+ controllerTickRate: rate(+ count: traces.count,+ first: traces.compactMap(\.timestamps.controllerEnd).first,+ last: traces.compactMap(\.timestamps.controllerEnd).last+ ),+ droppedFrameCount: droppedFrameCount,+ staleActionCount: staleActionCount(in: traces),+ worstTraces: worstTraces(in: traces),+ metadata: metadata+ )+ }++ private static func percentiles(_ values: [Double]) -> ReflexLatencyPercentiles {+ guard !values.isEmpty else { return ReflexLatencyPercentiles() }++ let sorted = values.sorted()+ return ReflexLatencyPercentiles(+ p50: percentile(sorted, fraction: 0.50),+ p95: percentile(sorted, fraction: 0.95),+ p99: percentile(sorted, fraction: 0.99)+ )+ }++ private static func percentile(+ _ sortedValues: [Double],+ fraction: Double+ ) -> Double? {+ guard !sortedValues.isEmpty else { return nil }+ let index = min(+ sortedValues.count - 1,+ Int(Double(sortedValues.count - 1) * fraction)+ )+ return sortedValues[index]+ }++ private static func rate(+ count: Int,+ first: RunTraceTimestamp?,+ last: RunTraceTimestamp?+ ) -> Double? {+ guard count > 1,+ let first,+ let last,+ let spanMS = first.milliseconds(until: last),+ spanMS > 0+ else {+ return nil+ }++ return Double(count - 1) / (spanMS / 1_000)+ }++ private static func staleActionCount(in traces: [ReflexTraceRecord]) -> Int {+ traces.filter { trace in+ trace.metadata["action.fallback"] == "true"+ && trace.metadata["fallbackReason"] == "staleSignal"+ }+ .count+ }++ private static func worstTraces(in traces: [ReflexTraceRecord]) -> [ReflexWorstTrace] {+ traces+ .sorted {+ ($0.latencyBreakdown.softwareLoopMS ?? -.infinity)+ > ($1.latencyBreakdown.softwareLoopMS ?? -.infinity)+ }+ .prefix(5)+ .map {+ ReflexWorstTrace(+ traceID: $0.traceID,+ frameID: $0.frameID,+ softwareLoopMS: $0.latencyBreakdown.softwareLoopMS+ )+ }+ }+}++public enum ReflexLatencyReportFormatter {+ public static func lines(for report: ReflexLatencyReport) -> [String] {+ [+ "reflex latency report",+ "mode=\(report.mode.rawValue)",+ "traceCount=\(report.traceCount)",+ "softwareLoopMS=\(format(report.softwareLoopMS))",+ "captureMS=\(format(report.captureMS))",+ "perceptionMS=\(format(report.perceptionMS))",+ "decisionMS=\(format(report.decisionMS))",+ "inputMS=\(format(report.inputMS))",+ "captureFPS=\(format(report.captureFPS))",+ "perceptionFPS=\(format(report.perceptionFPS))",+ "controllerTickRate=\(format(report.controllerTickRate))",+ "droppedFrameCount=\(report.droppedFrameCount)",+ "staleActionCount=\(report.staleActionCount)",+ "worstTraces=\(report.worstTraces.map { "\($0.traceID):\($0.frameID):\(format($0.softwareLoopMS))" }.joined(separator: ","))"+ ]+ }++ private static func format(_ percentiles: ReflexLatencyPercentiles) -> String {+ "p50=\(format(percentiles.p50)),p95=\(format(percentiles.p95)),p99=\(format(percentiles.p99))"+ }++ private static func format(_ value: Double?) -> String {+ guard let value else { return "-" }+ return String(format: "%.2f", value)+ }+}++public struct ReflexReplayBenchmark: Sendable {+ public var mode: ReflexReplayBenchmarkMode+ public var frameCount: Int+ public var droppedFrameCount: Int++ public init(+ mode: ReflexReplayBenchmarkMode = .endToEndDryRun,+ frameCount: Int = 30,+ droppedFrameCount: Int = 0+ ) {+ self.mode = mode+ self.frameCount = frameCount+ self.droppedFrameCount = droppedFrameCount+ }++ public func run() async -> ReflexLatencyReport {+ let coordinator = RunCoordinator()+ let frames = (0..<frameCount).map { index in+ HotLoopFrame(+ id: "benchmark-frame-\(index + 1)",+ traceID: "benchmark-trace-\(index + 1)",+ targetID: "benchmark-target",+ capturedAt: timestamp(milliseconds: UInt64(index * 16)),+ sourceKind: .synthetic,+ windowBounds: HotLoopRect(x: 0, y: 0, width: 400, height: 300, space: .screen),+ crop: HotLoopCrop(+ id: "benchmark-crop",+ 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"+ ]+ )+ }+ let loop = DryRunReflexLoop(+ coordinator: coordinator,+ frameSource: RecordedFrameSource(frames: frames)+ )+ let result = await loop.run(+ session: RunSession(+ id: "benchmark-session",+ userGoal: "benchmark dry-run loop",+ targetID: "benchmark-target"+ )+ )++ return await ReflexLatencyReportBuilder.build(+ from: coordinator.reflexTraces(),+ mode: mode,+ droppedFrameCount: result.droppedFrameCount + droppedFrameCount,+ metadata: [+ "frameCount": String(frameCount)+ ]+ )+ }++ private func timestamp(milliseconds: UInt64) -> RunTraceTimestamp {+ RunTraceTimestamp(+ wallClock: Date(timeIntervalSince1970: Double(milliseconds) / 1_000),+ monotonicUptimeNanoseconds: milliseconds * 1_000_000+ )+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/ActionEngineGuardrailTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ActionEngineGuardrailTests.swiftnew file mode 100644index 00000000..0d1f2b3e--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ActionEngineGuardrailTests.swift@@ -0,0 +1,142 @@+import DonkeyContracts+@testable import DonkeyRuntime+import Foundation+import Testing++@Suite+struct ActionEngineGuardrailTests {+ @Test+ func defaultPolicyDeniesInputCommandBeforeExecution() async {+ let engine = ActionEngineGuardrail()++ let trace = await engine.handle(command(id: "tap-1", issuedAtMS: 0))++ #expect(trace.decision == .denied(reason: "input permission denied"))+ #expect(trace.executed == false)+ #expect(trace.permissionDecision.isAllowed == false)+ #expect(await engine.allTraces() == [trace])+ }++ @Test+ func allowedInputProjectsDryRunWithoutLiveExecution() async {+ let engine = ActionEngineGuardrail()+ let policy = ToolCallPolicy(deniedCapabilities: [])++ let trace = await engine.handle(+ command(id: "tap-allowed", issuedAtMS: 0),+ permissionPolicy: policy+ )++ #expect(trace.decision == .projectedDryRun)+ #expect(trace.executed == false)+ #expect(trace.liveInputEnabled == false)+ #expect(trace.focusGuardPassed == true)+ #expect(trace.metadata["liveInputBackend"] == "notImplemented")+ }++ @Test+ func focusGuardCanDenyInputCommand() async {+ let engine = ActionEngineGuardrail(focusGuard: DenyingFocusGuard())+ let policy = ToolCallPolicy(deniedCapabilities: [])++ let trace = await engine.handle(+ command(id: "tap-focus", issuedAtMS: 0),+ permissionPolicy: policy+ )++ #expect(trace.decision == .denied(reason: "focus guard failed"))+ #expect(trace.focusGuardPassed == false)+ }++ @Test+ func holdDurationAboveMaximumIsDenied() async {+ let engine = ActionEngineGuardrail(+ configuration: ActionEngineConfiguration(maximumHoldDurationMS: 100)+ )+ let policy = ToolCallPolicy(deniedCapabilities: [])++ let trace = await engine.handle(+ command(id: "key-hold", kind: .key, issuedAtMS: 0, holdDurationMS: 250),+ permissionPolicy: policy+ )++ #expect(trace.decision == .denied(reason: "hold duration exceeds maximum"))+ #expect(trace.metadata["maximumHoldDurationMS"] == "100.0")+ }++ @Test+ func rateLimitDeniesCommandsTooCloseTogether() async {+ let engine = ActionEngineGuardrail(+ configuration: ActionEngineConfiguration(minimumCommandIntervalMS: 20)+ )+ let policy = ToolCallPolicy(deniedCapabilities: [])++ _ = await engine.handle(+ command(id: "tap-1", issuedAtMS: 0),+ permissionPolicy: policy+ )+ let trace = await engine.handle(+ command(id: "tap-2", issuedAtMS: 10),+ permissionPolicy: policy+ )++ #expect(trace.decision == .denied(reason: "rate limited"))+ #expect(trace.rateLimited == true)+ #expect(trace.metadata["elapsedMS"] == "10.0")+ }++ @Test+ func releaseAllClearsHeldInputAndRecordsReplayableTrace() async {+ let engine = ActionEngineGuardrail()+ let policy = ToolCallPolicy(deniedCapabilities: [])++ _ = await engine.handle(+ command(id: "mouse-held", kind: .mouse, issuedAtMS: 0, holdDurationMS: 50),+ permissionPolicy: policy+ )+ #expect(await engine.heldInputCount() == 1)++ let release = await engine.releaseAll(+ traceID: "trace-1",+ targetID: "target-1",+ issuedAt: timestamp(100)+ )++ #expect(release.command.kind == .releaseAll)+ #expect(release.releaseAll == true)+ #expect(release.metadata["heldInputReleased"] == "true")+ #expect(await engine.heldInputCount() == 0)+ }++ private func command(+ id: String,+ kind: ActionEngineCommandKind = .tap,+ issuedAtMS: UInt64,+ holdDurationMS: Double? = nil+ ) -> ActionEngineCommand {+ ActionEngineCommand(+ id: id,+ traceID: "trace-1",+ targetID: "target-1",+ stateID: "state-1",+ actionID: "action-1",+ kind: kind,+ issuedAt: timestamp(issuedAtMS),+ targetBounds: HotLoopRect(x: 0.4, y: 0.5, width: 0.1, height: 0.1, space: .normalizedTarget),+ holdDurationMS: holdDurationMS+ )+ }++ private func timestamp(_ milliseconds: UInt64) -> RunTraceTimestamp {+ RunTraceTimestamp(+ wallClock: Date(timeIntervalSince1970: Double(milliseconds) / 1_000),+ monotonicUptimeNanoseconds: milliseconds * 1_000_000+ )+ }+}++private struct DenyingFocusGuard: ActionEngineFocusGuard {+ func targetIsSafeForInput(targetID: String) async -> Bool {+ false+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/ReflexLatencyReportTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ReflexLatencyReportTests.swiftnew file mode 100644index 00000000..968196c8--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ReflexLatencyReportTests.swift@@ -0,0 +1,139 @@+import DonkeyContracts+@testable import DonkeyRuntime+import Foundation+import Testing++@Suite+struct ReflexLatencyReportTests {+ @Test+ func reportBuilderComputesPercentilesRatesDroppedFramesAndWorstTraces() {+ let traces = [+ trace(index: 1, softwareLoopMS: 10, fallbackReason: nil),+ trace(index: 2, softwareLoopMS: 20, fallbackReason: "staleSignal"),+ trace(index: 3, softwareLoopMS: 30, fallbackReason: nil),+ trace(index: 4, softwareLoopMS: 40, fallbackReason: nil)+ ]++ let report = ReflexLatencyReportBuilder.build(+ from: traces,+ mode: .endToEndDryRun,+ droppedFrameCount: 2,+ metadata: ["targetID": "target-1"]+ )++ #expect(report.traceCount == 4)+ #expect(report.softwareLoopMS.p50 == 20)+ #expect(report.softwareLoopMS.p95 == 30)+ #expect(report.softwareLoopMS.p99 == 30)+ #expect(report.captureMS.p50 == 1)+ #expect(report.perceptionMS.p50 == 2)+ #expect(report.decisionMS.p50 == 1)+ #expect(report.inputMS.p50 == 1)+ #expect(isClose(report.captureFPS, to: 100))+ #expect(isClose(report.perceptionFPS, to: 100))+ #expect(isClose(report.controllerTickRate, to: 100))+ #expect(report.droppedFrameCount == 2)+ #expect(report.staleActionCount == 1)+ #expect(report.worstTraces.first?.traceID == "trace-4")+ #expect(report.metadata["targetID"] == "target-1")+ }++ @Test+ func reportFormatterPrintsCliFriendlyLines() {+ let report = ReflexLatencyReportBuilder.build(+ from: [trace(index: 1, softwareLoopMS: 10, fallbackReason: nil)],+ mode: .captureOnly,+ droppedFrameCount: 1+ )++ let lines = ReflexLatencyReportFormatter.lines(for: report)++ #expect(lines.contains("reflex latency report"))+ #expect(lines.contains("mode=captureOnly"))+ #expect(lines.contains("traceCount=1"))+ #expect(lines.contains("droppedFrameCount=1"))+ #expect(lines.contains("softwareLoopMS=p50=10.00,p95=10.00,p99=10.00"))+ }++ @Test+ func replayBenchmarkProducesDryRunReportFromSyntheticTraces() async {+ let report = await ReflexReplayBenchmark(+ mode: .controllerOnly,+ frameCount: 3+ )+ .run()++ #expect(report.mode == .controllerOnly)+ #expect(report.traceCount == 3)+ #expect(report.softwareLoopMS.p95 != nil)+ #expect(report.metadata["frameCount"] == "3")+ }++ @Test+ func debugParserAcceptsDryRunLatencyReportCommand() throws {+ let command = try ManualCaptureDebugCommandParser.parse(+ arguments: [+ "Donkey",+ "--",+ "--dry-run-latency-report",+ "--frame-count",+ "12",+ "--benchmark-mode",+ "controllerOnly"+ ]+ )++ #expect(command == .dryRunLatencyReport(+ DryRunLatencyReportDebugOptions(+ frameCount: 12,+ mode: .controllerOnly+ )+ ))+ }++ private func trace(+ index: Int,+ softwareLoopMS: UInt64,+ fallbackReason: String?+ ) -> ReflexTraceRecord {+ let baseMS = UInt64(index * 10)+ var metadata: [String: String] = [:]+ if let fallbackReason {+ metadata["action.fallback"] = "true"+ metadata["fallbackReason"] = fallbackReason+ }++ return ReflexTraceRecord(+ traceID: "trace-\(index)",+ frameID: "frame-\(index)",+ stateID: "state-\(index)",+ actionID: "action-\(index)",+ timestamps: ReflexTraceTimeline(+ captureStart: timestamp(baseMS),+ captureEnd: timestamp(baseMS + 1),+ perceptionStart: timestamp(baseMS + 1),+ perceptionEnd: timestamp(baseMS + 3),+ statePublished: timestamp(baseMS + 3),+ controllerStart: timestamp(baseMS + 3),+ controllerEnd: timestamp(baseMS + 4),+ actionEnqueued: timestamp(baseMS + softwareLoopMS),+ inputExecuted: timestamp(baseMS + softwareLoopMS + 1)+ ),+ controllerPolicy: "policy",+ confidence: 0.9,+ metadata: metadata+ )+ }++ private func timestamp(_ milliseconds: UInt64) -> RunTraceTimestamp {+ RunTraceTimestamp(+ wallClock: Date(timeIntervalSince1970: Double(milliseconds) / 1_000),+ monotonicUptimeNanoseconds: milliseconds * 1_000_000+ )+ }++ private func isClose(_ value: Double?, to expected: Double) -> Bool {+ guard let value else { return false }+ return abs(value - expected) < 0.0001+ }+}diff --git a/docs/guides/minimal-run-coordinator.md b/docs/guides/minimal-run-coordinator.mdindex b4598844..799870aa 100644--- a/docs/guides/minimal-run-coordinator.md+++ b/docs/guides/minimal-run-coordinator.md@@ -24,6 +24,10 @@ Donkey also supports a bounded target-window frame source for the dry-run hot-loDonkey 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 reflex latency reports and a synthetic replay benchmark. `ReflexLatencyReportBuilder` summarizes reflex traces into p50/p95/p99 latency, capture/perception/controller rates, dropped frames, stale actions, and worst traces. `ReflexReplayBenchmark` can generate deterministic dry-run traces for capture-only, controller-only, or end-to-end dry-run report modes. The installed debug entrypoint can print a CLI-friendly dry-run latency report with `--dry-run-latency-report`.+Donkey also supports 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@@ -45,7 +49,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, hot-loop contract, deterministic dry-run skeleton, bounded target-window frame-source, cheap metadata perception, deterministic controller, target-metadata, single-screenshot artifact, read-only Accessibility snapshot, and manual capture orchestration foundation only. It does not run real vision models or OCR, call LLMs, execute OS input, perform Accessibility actions, provide a manual capture UI, persist high-volume reflex traces to disk, or provide continuous streaming capture yet.+This is a coordination, in-memory reflex trace, hot-loop contract, deterministic dry-run skeleton, bounded target-window frame-source, cheap metadata perception, deterministic controller, action-engine guardrail, latency-report, target-metadata, single-screenshot artifact, read-only Accessibility snapshot, and manual capture orchestration foundation only. It does not run real vision models or OCR, call LLMs, execute OS input, perform Accessibility actions, provide a manual capture UI, persist high-volume reflex traces to disk, or provide continuous streaming capture yet.## Technical Guidelines@@ -69,7 +73,10 @@ 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.- 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 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.@@ -81,13 +88,14 @@ 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, artifact path validation, trace folder layout, JSONL event persistence, summary updates, deterministic window resolver behavior through fixture providers, candidate-list label snapshots, screenshot artifact metadata, bounded Accessibility serialization, missing Accessibility trust partial events, unsafe target refusal, overlap-sensitive capture refusal, manual capture event ordering through persisted coordinator events, and debug launch-argument parsing/formatting.+The runtime tests should cover lifecycle ordering, abort and timeout safety, latest-session queue drops, tool permission denial, event-store ordering, context compaction, reflex trace latency math, bounded in-memory reflex trace retention, reflex event publication, hot-loop contract Codable round trips, coordinate conversion, stale-signal marking, deterministic dry-run trace publication, queue-depth-1 dropped-frame counting, bounded target-window frame capture, target-frame safety and overlap refusal, target-frame no-artifact/no-encoding metadata, cheap perception signal projection, controller confidence/staleness fallback, controller p95 replay timing under 20ms, action-engine permission/focus/rate/hold/release guardrails, latency report percentiles and replay benchmark formatting, 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:```shswift run Donkey -- --list-window-candidatesswift run Donkey -- --manual-capture --window-id <id>+swift run Donkey -- --dry-run-latency-report --frame-count 30```Manual verification on May 16, 2026 confirmed that the list command enumerates current visible Mac windows and that manual capture against a normal Mac app window creates a run folder with 9 ordered coordinator events, one screenshot artifact, and one Accessibility artifact. The verified run targeted a non-frontmost, non-focused Fork window by durable `windowID`.@@ -105,6 +113,8 @@ Remaining live verification is environment-dependent. On May 16, 2026, iPhone Mi- The deterministic dry-run reflex skeleton lives in `apps/Donkey/Sources/DonkeyRuntime/DryRunReflexLoop.swift`.- Bounded target-window reflex frame capture lives in `apps/Donkey/Sources/DonkeyRuntime/TargetWindowFrameSource.swift`.- Cheap perception, world-state projection, deterministic controller policy, and dry-run action projection live in `apps/Donkey/Sources/DonkeyRuntime/CheapPerceptionAndController.swift`.+- Action-engine guardrails live in `apps/Donkey/Sources/DonkeyRuntime/ActionEngineGuardrails.swift`.+- Reflex latency reports and synthetic replay benchmarks live in `apps/Donkey/Sources/DonkeyRuntime/ReflexLatencyReport.swift`.- Recent reflex trace retention lives in `apps/Donkey/Sources/DonkeyRuntime/InMemoryReflexTraceStore.swift`.- macOS window resolution lives in `apps/Donkey/Sources/DonkeyRuntime/MacWindowResolver.swift`.- Target-window screenshot capture lives in `apps/Donkey/Sources/DonkeyRuntime/WindowScreenshotCaptureService.swift`.diff --git a/plans/master-plan.md b/plans/master-plan.mdindex 62530320..c50cd41f 100644--- a/plans/master-plan.md+++ b/plans/master-plan.md@@ -56,6 +56,8 @@ The hot path must continue to work with the AI harness disabled.- Bounded target-window frame capture exists for the dry-run hot-loop boundary with selected-window safety checks, optional crop metadata, monotonic capture/copy timing, and no PNG/JPEG artifact encoding.- A cheap deterministic perception adapter exists for fixture or recorded-frame metadata, with compact world-state projection and raw pixels kept behind the perception boundary.- A deterministic controller policy exists for the first supported dry-run behavior: tap a fresh high-confidence target affordance, otherwise fall back to traceable wait/observe actions.+- An action-engine guardrail boundary exists for typed commands, input permission checks, focus guard checks, rate limits, maximum hold durations, held-input release, and replayable command traces. Live OS input is still disabled.+- Reflex latency reports and synthetic replay benchmark modes exist for p50/p95/p99 latency, frame/controller rates, dropped frames, stale actions, and worst traces.## Non-Negotiable Rules@@ -78,21 +80,11 @@ The hot path must continue to work with the AI harness disabled.- [x] Add bounded target-window capture as a dry-run frame source without screenshot artifact writes.- [x] Add the first cheap perception adapter and compact world-state projector for deterministic metadata/fixture signals.- [x] Add deterministic controller policy and dry-run action projection with confidence-aware fallback and trace metadata.+- [x] Add action-engine guardrails and replayable command traces before live input.+- [x] Add latency reports and synthetic replay benchmark modes for reflex traces.## Remaining Tasks-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.@@ -146,9 +138,9 @@ The hot path must continue to work with the AI harness disabled.## What Should Be Done Next-Start with task 6: add action-engine guardrails before live input.+Start with task 8: add slow-path planner hint contracts.-This is the right next slice because the current runtime now has lifecycle, event, artifact, manual capture, reflex trace, shared hot-loop contracts, a synthetic/recorded-frame dry-run skeleton, bounded selected-window frame capture, cheap deterministic perception, and a dry-run controller policy. It still needs an action-engine command boundary and guardrails before any live input can be considered.+This is the right next slice because the current runtime now has lifecycle, event, artifact, manual capture, reflex trace, shared hot-loop contracts, a synthetic/recorded-frame dry-run skeleton, bounded selected-window frame capture, cheap deterministic perception, a dry-run controller policy, action-engine guardrails, and latency reports. It still needs validated, expiring slow-path planner hints before the AI harness can safely influence controller behavior.## Closeout Criteria