Open source CapCut alternative.
TypeScript
Add cheap perception and deterministic dry-run controller
David Le6f0cca97d0e6
diff --git a/apps/Donkey/Sources/DonkeyRuntime/CheapPerceptionAndController.swift b/apps/Donkey/Sources/DonkeyRuntime/CheapPerceptionAndController.swiftnew file mode 100644index 00000000..9a618a4c--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/CheapPerceptionAndController.swift@@ -0,0 +1,267 @@+import DonkeyContracts+import Foundation++public struct CheapPerceptionAdapter: DryRunPerceptionAdapting {+ public var adapterName: String+ public var defaultSignalKind: String+ public var observationDelayMS: UInt64++ public init(+ adapterName: String = "cheap-metadata-perception",+ defaultSignalKind: String = "template",+ observationDelayMS: UInt64 = 2+ ) {+ self.adapterName = adapterName+ self.defaultSignalKind = defaultSignalKind+ self.observationDelayMS = observationDelayMS+ }++ public func perceive(frame: HotLoopFrame) async -> [HotLoopPerceptionSignal] {+ let confidence = Self.clampedConfidence(+ Double(frame.metadata["signalConfidence"] ?? "")+ ?? Double(frame.metadata["perception.confidence"] ?? "")+ ?? 1+ )+ let signalKind = frame.metadata["signalKind"]+ ?? frame.metadata["perception.kind"]+ ?? defaultSignalKind+ let observedAt = frame.capturedAt.addingMilliseconds(observationDelayMS)+ let observations = observations(from: frame, signalConfidence: confidence)++ return [+ HotLoopPerceptionSignal(+ id: "signal-\(frame.id)",+ traceID: frame.traceID,+ frameID: frame.id,+ kind: signalKind,+ capturedAt: frame.capturedAt,+ observedAt: observedAt,+ confidence: confidence,+ observations: observations,+ plannerHintID: frame.plannerHintID,+ metadata: [+ "adapter": adapterName,+ "rawPixelsExposed": "false"+ ]+ )+ ]+ }++ private func observations(+ from frame: HotLoopFrame,+ signalConfidence: Double+ ) -> [HotLoopPerceptionObservation] {+ guard let x = Double(frame.metadata["tapTargetX"] ?? frame.metadata["target.x"] ?? ""),+ let y = Double(frame.metadata["tapTargetY"] ?? frame.metadata["target.y"] ?? "")+ else {+ return []+ }++ let width = Double(frame.metadata["tapTargetWidth"] ?? frame.metadata["target.width"] ?? "") ?? 0.1+ let height = Double(frame.metadata["tapTargetHeight"] ?? frame.metadata["target.height"] ?? "") ?? 0.1+ let confidence = Self.clampedConfidence(+ Double(frame.metadata["tapTargetConfidence"] ?? frame.metadata["target.confidence"] ?? "")+ ?? signalConfidence+ )++ return [+ HotLoopPerceptionObservation(+ id: "observation-\(frame.id)",+ label: frame.metadata["tapTargetLabel"]+ ?? frame.metadata["target.label"]+ ?? "tap-target",+ bounds: HotLoopRect(+ x: x,+ y: y,+ width: width,+ height: height,+ space: .normalizedTarget+ ),+ confidence: confidence,+ metadata: [+ "source": "frame.metadata"+ ]+ )+ ]+ }++ private static func clampedConfidence(_ value: Double) -> Double {+ min(max(value, 0), 1)+ }+}++public struct HotLoopWorldStateProjector: Sendable {+ public var staleSignalThresholdMS: Double++ public init(staleSignalThresholdMS: Double = 250) {+ self.staleSignalThresholdMS = staleSignalThresholdMS+ }++ public func project(+ frame: HotLoopFrame,+ signals: [HotLoopPerceptionSignal],+ observedAt: RunTraceTimestamp+ ) -> HotLoopWorldState {+ HotLoopWorldState.build(+ id: "state-\(frame.id)",+ frame: frame,+ signals: signals,+ observedAt: observedAt,+ staleThresholdMS: staleSignalThresholdMS,+ actionAffordances: actionAffordances(from: signals),+ metadata: [+ "projector": "hot-loop-world-state-projector",+ "rawPixelsExposed": "false"+ ]+ )+ }++ 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 DeterministicControllerPolicy: DryRunControllerPolicy {+ public var name: String+ public var minimumActionConfidence: Double++ public init(+ name: String = "deterministic-tap-target-v1",+ minimumActionConfidence: Double = 0.6+ ) {+ self.name = name+ self.minimumActionConfidence = minimumActionConfidence+ }++ public func decide(state: HotLoopWorldState) async -> HotLoopControllerAction {+ if let affordance = state.actionAffordances+ .filter({ !state.staleSignalIDs.contains($0.sourceSignalID) })+ .sorted(by: { $0.confidence > $1.confidence })+ .first {+ if affordance.confidence >= minimumActionConfidence {+ return action(+ state: state,+ kind: .tapTarget,+ target: affordance.targetBounds,+ confidence: affordance.confidence,+ rationale: "Selected highest-confidence tap target affordance",+ metadata: [+ "fallback": "false",+ "sourceSignalID": affordance.sourceSignalID+ ]+ )+ }++ return action(+ state: state,+ kind: .wait,+ confidence: affordance.confidence,+ rationale: "Best affordance confidence is below action threshold",+ metadata: [+ "fallback": "true",+ "fallbackReason": "lowConfidence",+ "sourceSignalID": affordance.sourceSignalID,+ "minimumActionConfidence": String(minimumActionConfidence)+ ]+ )+ }++ if !state.signalSummaries.isEmpty {+ return action(+ state: state,+ kind: .wait,+ confidence: state.confidence,+ rationale: "Perception is present but no fresh action affordance is available",+ metadata: [+ "fallback": "true",+ "fallbackReason": state.staleSignalIDs.isEmpty ? "noAffordance" : "staleSignal"+ ]+ )+ }++ return action(+ state: state,+ kind: .observe,+ confidence: 0,+ rationale: "No perception signal is available",+ metadata: [+ "fallback": "true",+ "fallbackReason": "noSignal"+ ]+ )+ }++ private func action(+ state: HotLoopWorldState,+ kind: HotLoopActionKind,+ target: HotLoopRect? = nil,+ confidence: Double,+ rationale: String,+ metadata: [String: String]+ ) -> HotLoopControllerAction {+ HotLoopControllerAction(+ id: "action-\(state.id)",+ traceID: state.traceID,+ frameID: state.frameID,+ stateID: state.id,+ kind: kind,+ target: target,+ policyName: name,+ confidence: confidence,+ rationale: rationale,+ plannerHintID: state.plannerHintID,+ metadata: metadata+ )+ }+}++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,+ "fallback": action.metadata["fallback"] ?? "false"+ ]+ )+ }+}++private extension RunTraceTimestamp {+ func addingMilliseconds(_ milliseconds: UInt64) -> RunTraceTimestamp {+ RunTraceTimestamp(+ wallClock: wallClock.addingTimeInterval(Double(milliseconds) / 1_000),+ monotonicUptimeNanoseconds: monotonicUptimeNanoseconds + milliseconds * 1_000_000+ )+ }+}diff --git a/apps/Donkey/Sources/DonkeyRuntime/DryRunReflexLoop.swift b/apps/Donkey/Sources/DonkeyRuntime/DryRunReflexLoop.swiftindex 879ecea1..69448a6e 100644--- a/apps/Donkey/Sources/DonkeyRuntime/DryRunReflexLoop.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/DryRunReflexLoop.swift@@ -78,13 +78,14 @@ public struct DryRunReflexLoop: Sendable {public var perceptionAdapter: any DryRunPerceptionAdaptingpublic var controllerPolicy: any DryRunControllerPolicypublic var actionProjector: any DryRunActionProjecting+ public var worldStateProjector: HotLoopWorldStateProjectorpublic var staleSignalThresholdMS: Doublepublic init(coordinator: RunCoordinator,frameSource: any DryRunFrameSource,- perceptionAdapter: any DryRunPerceptionAdapting = SyntheticPerceptionAdapter(),- controllerPolicy: any DryRunControllerPolicy = InspectableDryRunControllerPolicy(),+ perceptionAdapter: any DryRunPerceptionAdapting = CheapPerceptionAdapter(),+ controllerPolicy: any DryRunControllerPolicy = DeterministicControllerPolicy(),actionProjector: any DryRunActionProjecting = DryRunActionProjector(),staleSignalThresholdMS: Double = 250) {@@ -93,6 +94,7 @@ public struct DryRunReflexLoop: Sendable {self.perceptionAdapter = perceptionAdapterself.controllerPolicy = controllerPolicyself.actionProjector = actionProjector+ self.worldStateProjector = HotLoopWorldStateProjector(staleSignalThresholdMS: staleSignalThresholdMS)self.staleSignalThresholdMS = staleSignalThresholdMS}@@ -149,14 +151,10 @@ public struct DryRunReflexLoop: Sendable {) 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)",+ let worldState = worldStateProjector.project(frame: frame,signals: signals,observedAt: observedAt,- staleThresholdMS: staleSignalThresholdMS,- actionAffordances: affordances)let controllerStart = observedAt.addingMilliseconds(1)let action = await controllerPolicy.decide(state: worldState)@@ -183,8 +181,11 @@ public struct DryRunReflexLoop: Sendable {metadata: ["dryRun.mode": result.mode.rawValue,"dryRun.executed": String(result.executed),- "dryRun.summary": result.summary- ]+ "dryRun.summary": result.summary,+ "action.kind": action.kind.rawValue,+ "action.rationale": action.rationale,+ "action.fallback": action.metadata["fallback"] ?? "false"+ ].merging(action.metadata, uniquingKeysWith: { current, _ in current }))await coordinator.appendReflexTrace(trace)@@ -205,21 +206,6 @@ public struct DryRunReflexLoop: Sendable {}}- 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 {@@ -250,123 +236,8 @@ public struct RecordedFrameSource: DryRunFrameSource {}}-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- ]- )- }-}+public typealias SyntheticPerceptionAdapter = CheapPerceptionAdapter+public typealias InspectableDryRunControllerPolicy = DeterministicControllerPolicyprivate extension RunTraceTimestamp {func addingMilliseconds(_ milliseconds: UInt64) -> RunTraceTimestamp {diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/CheapPerceptionAndControllerTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/CheapPerceptionAndControllerTests.swiftnew file mode 100644index 00000000..f31f28d9--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/CheapPerceptionAndControllerTests.swift@@ -0,0 +1,208 @@+import DonkeyContracts+@testable import DonkeyRuntime+import Foundation+import Testing++@Suite+struct CheapPerceptionAndControllerTests {+ @Test+ func cheapPerceptionAdapterBuildsDeterministicMetadataSignal() async throws {+ let frame = fixtureFrame(+ metadata: [+ "target.x": "0.25",+ "target.y": "0.4",+ "target.width": "0.2",+ "target.height": "0.1",+ "target.label": "play",+ "target.confidence": "0.7",+ "perception.kind": "template",+ "perception.confidence": "0.8"+ ]+ )++ let signals = await CheapPerceptionAdapter().perceive(frame: frame)+ let signal = try #require(signals.first)+ let observation = try #require(signal.observations.first)++ #expect(signal.kind == "template")+ #expect(signal.confidence == 0.8)+ #expect(signal.metadata["rawPixelsExposed"] == "false")+ #expect(signal.sourceAgeMS(at: timestamp(12)) == 2)+ #expect(observation.label == "play")+ #expect(observation.confidence == 0.7)+ #expect(observation.bounds == HotLoopRect(x: 0.25, y: 0.4, width: 0.2, height: 0.1, space: .normalizedTarget))+ }++ @Test+ func worldStateProjectorConvertsSignalsIntoCompactState() async throws {+ let frame = fixtureFrame()+ let signals = await CheapPerceptionAdapter().perceive(frame: frame)++ let state = HotLoopWorldStateProjector(staleSignalThresholdMS: 250).project(+ frame: frame,+ signals: signals,+ observedAt: timestamp(12)+ )++ #expect(state.id == "state-frame-1")+ #expect(state.signalSummaries.count == 1)+ #expect(state.signalSummaries.first?.sourceAgeMS == 2)+ #expect(state.actionAffordances.count == 1)+ #expect(state.actionAffordances.first?.kind == .tapTarget)+ #expect(state.metadata["rawPixelsExposed"] == "false")+ }++ @Test+ func deterministicControllerSelectsTapTargetForFreshConfidentAffordance() async {+ let state = worldState(confidence: 0.9, affordanceConfidence: 0.85)++ let action = await DeterministicControllerPolicy().decide(state: state)++ #expect(action.kind == .tapTarget)+ #expect(action.confidence == 0.85)+ #expect(action.policyName == "deterministic-tap-target-v1")+ #expect(action.metadata["fallback"] == "false")+ #expect(action.metadata["sourceSignalID"] == "signal-1")+ }++ @Test+ func deterministicControllerFallsBackWhenConfidenceIsLow() async {+ let state = worldState(confidence: 0.4, affordanceConfidence: 0.4)++ let action = await DeterministicControllerPolicy(minimumActionConfidence: 0.6).decide(state: state)++ #expect(action.kind == .wait)+ #expect(action.metadata["fallback"] == "true")+ #expect(action.metadata["fallbackReason"] == "lowConfidence")+ }++ @Test+ func deterministicControllerFallsBackWhenSignalIsStale() async {+ let state = worldState(+ confidence: 0.9,+ affordanceConfidence: 0.9,+ staleSignalIDs: ["signal-1"]+ )++ let action = await DeterministicControllerPolicy().decide(state: state)++ #expect(action.kind == .wait)+ #expect(action.metadata["fallback"] == "true")+ #expect(action.metadata["fallbackReason"] == "staleSignal")+ }++ @Test+ func dryRunTraceRecordsChosenActionMetadata() async {+ let coordinator = RunCoordinator()+ let loop = DryRunReflexLoop(+ coordinator: coordinator,+ frameSource: SyntheticFrameSource(frames: [fixtureFrame()])+ )++ _ = await loop.run(session: RunSession(id: "session-action", userGoal: "tap", targetID: "target-1"))++ let trace = await coordinator.latestReflexTrace()+ #expect(trace?.metadata["action.kind"] == "tapTarget")+ #expect(trace?.metadata["action.fallback"] == "false")+ #expect(trace?.metadata["action.rationale"] == "Selected highest-confidence tap target affordance")+ #expect(trace?.metadata["sourceSignalID"] == "signal-frame-1")+ }++ @Test+ func controllerReplayDecisionP95StaysUnder20MS() async {+ let policy = DeterministicControllerPolicy()+ let states = (0..<500).map { index in+ worldState(+ id: "state-\(index)",+ confidence: 0.9,+ affordanceConfidence: 0.85+ )+ }+ var durations: [Double] = []+ durations.reserveCapacity(states.count)++ for state in states {+ let start = ProcessInfo.processInfo.systemUptime+ _ = await policy.decide(state: state)+ let end = ProcessInfo.processInfo.systemUptime+ durations.append((end - start) * 1_000)+ }++ #expect(percentile95(durations) < 20)+ }++ private func fixtureFrame(metadata: [String: String] = [+ "tapTargetX": "0.4",+ "tapTargetY": "0.5",+ "tapTargetWidth": "0.1",+ "tapTargetHeight": "0.1",+ "tapTargetLabel": "start",+ "signalKind": "template",+ "signalConfidence": "0.85"+ ]) -> HotLoopFrame {+ HotLoopFrame(+ id: "frame-1",+ traceID: "trace-1",+ targetID: "target-1",+ capturedAt: timestamp(10),+ sourceKind: .recorded,+ windowBounds: HotLoopRect(x: 0, y: 0, width: 400, height: 300, space: .screen),+ crop: HotLoopCrop(+ id: "crop-1",+ 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: metadata+ )+ }++ private func worldState(+ id: String = "state-1",+ confidence: Double,+ affordanceConfidence: Double,+ staleSignalIDs: [String] = []+ ) -> HotLoopWorldState {+ HotLoopWorldState(+ id: id,+ traceID: "trace-1",+ frameID: "frame-1",+ targetID: "target-1",+ observedAt: timestamp(12),+ signalSummaries: [+ HotLoopPerceptionSignalSummary(+ id: "signal-1",+ kind: "template",+ confidence: confidence,+ sourceAgeMS: 2,+ observationCount: 1+ )+ ],+ staleSignalIDs: staleSignalIDs,+ actionAffordances: [+ HotLoopActionAffordance(+ id: "affordance-1",+ kind: .tapTarget,+ targetBounds: HotLoopRect(x: 0.4, y: 0.5, width: 0.1, height: 0.1, space: .normalizedTarget),+ confidence: affordanceConfidence,+ sourceSignalID: "signal-1"+ )+ ],+ confidence: confidence+ )+ }++ private func timestamp(_ milliseconds: UInt64) -> RunTraceTimestamp {+ RunTraceTimestamp(+ wallClock: Date(timeIntervalSince1970: Double(milliseconds) / 1_000),+ monotonicUptimeNanoseconds: milliseconds * 1_000_000+ )+ }++ private func percentile95(_ values: [Double]) -> Double {+ let sorted = values.sorted()+ guard !sorted.isEmpty else { return 0 }+ let index = min(sorted.count - 1, Int(Double(sorted.count - 1) * 0.95))+ return sorted[index]+ }+}diff --git a/docs/guides/minimal-run-coordinator.md b/docs/guides/minimal-run-coordinator.mdindex 611939f6..b4598844 100644--- a/docs/guides/minimal-run-coordinator.md+++ b/docs/guides/minimal-run-coordinator.md@@ -22,6 +22,8 @@ Donkey also supports a deterministic dry-run reflex loop skeleton. The loop consDonkey 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 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 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@@ -43,7 +45,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, 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.+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.## Technical Guidelines@@ -64,6 +66,9 @@ This is a coordination, in-memory reflex trace, hot-loop contract, deterministic- Keep reflex frame buffers at queue depth 1. Dropped frames are expected under pressure and should be counted.- Keep target-window reflex frames bounded by caller-provided frame count until a streaming capture loop exists.- Keep manual screenshot artifacts and high-resolution planner snapshots separate from reflex frames. The reflex frame source should not encode PNG/JPEG or write screenshot artifacts.+- Keep cheap perception deterministic and compact until real pixel/model adapters exist. Perception may summarize fixture or recorded-frame metadata, but controllers must only see typed signals, world state, and action affordances.+- Keep 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.- 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.@@ -76,7 +81,7 @@ From `apps/Donkey/`:swift test```-The runtime tests should cover lifecycle ordering, abort and timeout safety, latest-session queue drops, tool permission denial, event-store ordering, context compaction, reflex trace latency math, bounded in-memory reflex trace retention, reflex event publication, hot-loop contract Codable round trips, coordinate conversion, stale-signal marking, deterministic dry-run trace publication, queue-depth-1 dropped-frame counting, bounded target-window frame capture, target-frame safety and overlap refusal, target-frame no-artifact/no-encoding metadata, 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, 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:@@ -99,6 +104,7 @@ Remaining live verification is environment-dependent. On May 16, 2026, iPhone Mi- 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`.+- Cheap perception, world-state projection, deterministic controller policy, and dry-run action projection live in `apps/Donkey/Sources/DonkeyRuntime/CheapPerceptionAndController.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 134fdd4e..62530320 100644--- a/plans/master-plan.md+++ b/plans/master-plan.md@@ -54,6 +54,8 @@ The hot path must continue to work with the AI harness disabled.- Shared hot-loop contracts exist for frames, crops, explicit coordinate spaces, perception signals, compact world state, controller actions, action results, stale-signal marking, and trace-linked IDs.- A deterministic dry-run reflex loop skeleton exists for synthetic or recorded frame batches with latest-frame-wins queue depth 1, dropped-frame counting, dry-run action projection, and coordinator-published reflex traces.- Bounded target-window frame capture exists for the dry-run hot-loop boundary with selected-window safety checks, optional crop metadata, monotonic capture/copy timing, and no PNG/JPEG artifact encoding.+- A cheap deterministic perception adapter exists for fixture or recorded-frame metadata, with compact world-state projection and raw pixels kept behind the perception boundary.+- A deterministic controller policy exists for the first supported dry-run behavior: tap a fresh high-confidence target affordance, otherwise fall back to traceable wait/observe actions.## Non-Negotiable Rules@@ -74,23 +76,11 @@ The hot path must continue to work with the AI harness disabled.- [x] Define shared hot-loop contracts for typed frame, crop, world-state, perception-signal, controller-action, action-result, and coordinate conversion.- [x] Add deterministic dry-run reflex loop skeleton for synthetic or recorded frames only.- [x] Add bounded target-window capture as a dry-run frame source without screenshot artifact writes.+- [x] Add the first cheap perception adapter and compact world-state projector for deterministic metadata/fixture signals.+- [x] Add deterministic controller policy and dry-run action projection with confidence-aware fallback and trace metadata.## 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.@@ -156,9 +146,9 @@ The hot path must continue to work with the AI harness disabled.## What Should Be Done Next-Start with task 4: add the first cheap perception adapter.+Start with task 6: add action-engine guardrails before live input.-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.+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.## Closeout Criteria