Skip to content

Open source CapCut alternative.

TypeScript

Add manual capture debug entrypoint

David Le354e69ae2c14
diff --git a/apps/Donkey/Sources/DonkeyRuntime/MacAccessibilitySnapshotCaptureService.swift b/apps/Donkey/Sources/DonkeyRuntime/MacAccessibilitySnapshotCaptureService.swift
index 5f3cc0ab..600e9bb4 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/MacAccessibilitySnapshotCaptureService.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/MacAccessibilitySnapshotCaptureService.swift
@@ -9,6 +9,7 @@ public enum MacAccessibilitySnapshotCaptureError: Error, Equatable, Sendable {
windowID: UInt32,
status: WindowTargetSafetyStatus
)
+ case accessibilityNotTrusted(windowID: UInt32)
case captureFailed(windowID: UInt32, reason: String)
}
@@ -81,7 +82,8 @@ public final class MacAccessibilitySnapshotCaptureService {
runID: String,
selection: MacWindowSelectionRequest = MacWindowSelectionRequest(),
limits: MacAccessibilitySnapshotLimits = .default,
- artifactID: String = "accessibility-\(UUID().uuidString)"
+ artifactID: String = "accessibility-\(UUID().uuidString)",
+ recordsPermissionDeniedEvent: Bool = true
) async throws -> MacAccessibilitySnapshotCaptureOutcome {
let summary: RunTraceSummary
do {
@@ -99,6 +101,12 @@ public final class MacAccessibilitySnapshotCaptureService {
}
guard capturer.trustStatus() == .trusted else {
+ guard recordsPermissionDeniedEvent else {
+ throw MacAccessibilitySnapshotCaptureError.accessibilityNotTrusted(
+ windowID: target.windowID
+ )
+ }
+
let eventRecord = try await artifactStore.appendEvent(
permissionDeniedEvent(
summary: summary,
diff --git a/apps/Donkey/Sources/DonkeyRuntime/ManualTargetContextCaptureService.swift b/apps/Donkey/Sources/DonkeyRuntime/ManualTargetContextCaptureService.swift
new file mode 100644
index 00000000..760a28df
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/ManualTargetContextCaptureService.swift
@@ -0,0 +1,541 @@
+import DonkeyContracts
+import Foundation
+
+public enum ManualTargetContextCaptureError: Error, Equatable, Sendable {
+ case targetResolutionFailed(String)
+ case unsafeTarget(windowID: UInt32, status: WindowTargetSafetyStatus)
+ case policyDenied(capability: ToolCallCapability, reason: String)
+ case screenshotFailed(String)
+ case accessibilityFailed(String)
+}
+
+public enum ManualAccessibilityCaptureOutcome: Equatable, Sendable {
+ case captured(MacAccessibilitySnapshotCaptureResult)
+ case permissionDenied
+ case skipped(reason: String)
+}
+
+public struct ManualTargetContextCaptureResult: Equatable, Sendable {
+ public var session: RunSession
+ public var traceSummary: RunTraceSummary
+ public var target: MacWindowTargetCandidate
+ public var screenshot: WindowScreenshotCaptureResult
+ public var accessibility: ManualAccessibilityCaptureOutcome
+
+ public init(
+ session: RunSession,
+ traceSummary: RunTraceSummary,
+ target: MacWindowTargetCandidate,
+ screenshot: WindowScreenshotCaptureResult,
+ accessibility: ManualAccessibilityCaptureOutcome
+ ) {
+ self.session = session
+ self.traceSummary = traceSummary
+ self.target = target
+ self.screenshot = screenshot
+ self.accessibility = accessibility
+ }
+}
+
+protocol WindowScreenshotCaptureServicing {
+ func captureScreenshot(
+ runID: String,
+ selection: MacWindowSelectionRequest,
+ artifactID: String
+ ) async throws -> WindowScreenshotCaptureResult
+}
+
+extension WindowScreenshotCaptureService: WindowScreenshotCaptureServicing {}
+
+protocol MacAccessibilitySnapshotCaptureServicing {
+ func captureSnapshot(
+ runID: String,
+ selection: MacWindowSelectionRequest,
+ limits: MacAccessibilitySnapshotLimits,
+ artifactID: String,
+ recordsPermissionDeniedEvent: Bool
+ ) async throws -> MacAccessibilitySnapshotCaptureOutcome
+}
+
+extension MacAccessibilitySnapshotCaptureService: MacAccessibilitySnapshotCaptureServicing {}
+
+public final class ManualTargetContextCaptureService {
+ private let coordinator: RunCoordinator
+ private let artifactStore: LocalRunArtifactStore
+ private let windowResolver: MacWindowResolver
+ private let screenshotService: any WindowScreenshotCaptureServicing
+ private let accessibilityService: any MacAccessibilitySnapshotCaptureServicing
+
+ public convenience init(
+ coordinator: RunCoordinator = RunCoordinator(),
+ artifactStore: LocalRunArtifactStore
+ ) {
+ let windowResolver = MacWindowResolver()
+ self.init(
+ coordinator: coordinator,
+ artifactStore: artifactStore,
+ windowResolver: windowResolver,
+ screenshotService: WindowScreenshotCaptureService(artifactStore: artifactStore),
+ accessibilityService: MacAccessibilitySnapshotCaptureService(artifactStore: artifactStore)
+ )
+ }
+
+ init(
+ coordinator: RunCoordinator,
+ artifactStore: LocalRunArtifactStore,
+ windowResolver: MacWindowResolver,
+ screenshotService: any WindowScreenshotCaptureServicing,
+ accessibilityService: any MacAccessibilitySnapshotCaptureServicing
+ ) {
+ self.coordinator = coordinator
+ self.artifactStore = artifactStore
+ self.windowResolver = windowResolver
+ self.screenshotService = screenshotService
+ self.accessibilityService = accessibilityService
+ }
+
+ public func capture(
+ session: RunSession,
+ selection: MacWindowSelectionRequest = MacWindowSelectionRequest(),
+ traceID: String = UUID().uuidString,
+ screenshotArtifactID: String = "screenshot-\(UUID().uuidString)",
+ accessibilityArtifactID: String = "accessibility-\(UUID().uuidString)",
+ accessibilityLimits: MacAccessibilitySnapshotLimits = .default
+ ) async throws -> ManualTargetContextCaptureResult {
+ var lastPersistedSequence = await coordinator.events().last?.sequence ?? 0
+ let traceSummary = try await artifactStore.prepareRun(
+ session: session,
+ traceID: traceID
+ )
+ await coordinator.setTraceID(traceSummary.traceID)
+ _ = await coordinator.start(session)
+ try await persistNewCoordinatorEvents(
+ runID: session.id,
+ lastPersistedSequence: &lastPersistedSequence
+ )
+
+ let target: MacWindowTargetCandidate
+ do {
+ target = try windowResolver.selectTarget(selection)
+ } catch {
+ await recordTargetResolutionFailure(error, traceID: traceSummary.traceID)
+ try await failRun(
+ runID: session.id,
+ reason: "Manual capture failed during target resolution",
+ lastPersistedSequence: &lastPersistedSequence
+ )
+ throw ManualTargetContextCaptureError.targetResolutionFailed(String(describing: error))
+ }
+
+ let targetMetadata = metadata(for: target)
+ guard target.safetyAssessment.status == .allowed else {
+ await coordinator.recordToolEvent(
+ capability: .capture,
+ decision: .deny(reason: target.safetyAssessment.summary),
+ toolName: "mac-window-resolver",
+ summary: "Target window refused",
+ traceID: traceSummary.traceID,
+ metadata: targetMetadata
+ )
+ try await failRun(
+ runID: session.id,
+ reason: "Manual capture refused unsafe target",
+ lastPersistedSequence: &lastPersistedSequence
+ )
+ throw ManualTargetContextCaptureError.unsafeTarget(
+ windowID: target.windowID,
+ status: target.safetyAssessment.status
+ )
+ }
+
+ let captureDecision = session.permissionPolicy.decision(for: .capture)
+ guard captureDecision.isAllowed else {
+ await coordinator.recordToolEvent(
+ capability: .capture,
+ decision: captureDecision,
+ toolName: "mac-window-resolver",
+ summary: "Target resolution denied by policy",
+ traceID: traceSummary.traceID,
+ metadata: targetMetadata
+ )
+ try await failRun(
+ runID: session.id,
+ reason: "Manual capture denied by capture policy",
+ lastPersistedSequence: &lastPersistedSequence
+ )
+ throw policyDeniedError(capability: .capture, decision: captureDecision)
+ }
+
+ await coordinator.recordToolEvent(
+ capability: .capture,
+ decision: .allow,
+ toolName: "mac-window-resolver",
+ summary: "Target window resolved",
+ traceID: traceSummary.traceID,
+ metadata: targetMetadata
+ )
+ try await persistNewCoordinatorEvents(
+ runID: session.id,
+ lastPersistedSequence: &lastPersistedSequence
+ )
+
+ let screenshot = try await captureScreenshot(
+ runID: session.id,
+ selection: MacWindowSelectionRequest(windowID: target.windowID),
+ artifactID: screenshotArtifactID,
+ targetMetadata: targetMetadata,
+ traceID: traceSummary.traceID,
+ policy: session.permissionPolicy,
+ lastPersistedSequence: &lastPersistedSequence
+ )
+
+ let accessibility = try await captureAccessibility(
+ runID: session.id,
+ selection: MacWindowSelectionRequest(windowID: target.windowID),
+ artifactID: accessibilityArtifactID,
+ limits: accessibilityLimits,
+ targetMetadata: targetMetadata,
+ traceID: traceSummary.traceID,
+ policy: session.permissionPolicy,
+ lastPersistedSequence: &lastPersistedSequence
+ )
+
+ let completionReason: String
+ switch accessibility {
+ case .captured:
+ completionReason = "Manual capture completed"
+ case .permissionDenied, .skipped:
+ completionReason = "Manual capture completed with partial Accessibility context"
+ }
+ await coordinator.complete(reason: completionReason)
+ try await persistNewCoordinatorEvents(
+ runID: session.id,
+ lastPersistedSequence: &lastPersistedSequence
+ )
+
+ let currentSummary = try await artifactStore.summary(runID: session.id)
+ return ManualTargetContextCaptureResult(
+ session: session,
+ traceSummary: currentSummary,
+ target: target,
+ screenshot: screenshot,
+ accessibility: accessibility
+ )
+ }
+
+ private func captureScreenshot(
+ runID: String,
+ selection: MacWindowSelectionRequest,
+ artifactID: String,
+ targetMetadata: [String: String],
+ traceID: String,
+ policy: ToolCallPolicy,
+ lastPersistedSequence: inout Int
+ ) async throws -> WindowScreenshotCaptureResult {
+ await coordinator.recordToolEvent(
+ capability: .capture,
+ decision: .allow,
+ toolName: "window-screenshot-capture",
+ summary: "Screenshot capture started",
+ traceID: traceID,
+ metadata: targetMetadata
+ )
+ try await persistNewCoordinatorEvents(
+ runID: runID,
+ lastPersistedSequence: &lastPersistedSequence
+ )
+
+ let persistenceDecision = policy.decision(for: .persistence)
+ guard persistenceDecision.isAllowed else {
+ await coordinator.recordToolEvent(
+ capability: .persistence,
+ decision: persistenceDecision,
+ toolName: "local-run-artifact-store",
+ summary: "Screenshot artifact persistence denied by policy",
+ traceID: traceID,
+ metadata: targetMetadata
+ )
+ try await failRun(
+ runID: runID,
+ reason: "Manual capture denied by persistence policy",
+ lastPersistedSequence: &lastPersistedSequence
+ )
+ throw policyDeniedError(capability: .persistence, decision: persistenceDecision)
+ }
+
+ do {
+ let result = try await screenshotService.captureScreenshot(
+ runID: runID,
+ selection: selection,
+ artifactID: artifactID
+ )
+ await coordinator.recordToolEvent(
+ capability: .persistence,
+ decision: .allow,
+ toolName: "local-run-artifact-store",
+ summary: "Screenshot artifact persisted",
+ traceID: traceID,
+ metadata: targetMetadata.merging(
+ artifactMetadata(result.artifact)
+ ) { current, _ in current }
+ )
+ try await persistNewCoordinatorEvents(
+ runID: runID,
+ lastPersistedSequence: &lastPersistedSequence
+ )
+ return result
+ } catch {
+ await coordinator.recordToolEvent(
+ capability: .capture,
+ decision: .deny(reason: String(describing: error)),
+ toolName: "window-screenshot-capture",
+ summary: "Screenshot capture failed",
+ traceID: traceID,
+ metadata: targetMetadata
+ )
+ try await failRun(
+ runID: runID,
+ reason: "Manual capture failed during screenshot capture",
+ lastPersistedSequence: &lastPersistedSequence
+ )
+ throw ManualTargetContextCaptureError.screenshotFailed(String(describing: error))
+ }
+ }
+
+ private func captureAccessibility(
+ runID: String,
+ selection: MacWindowSelectionRequest,
+ artifactID: String,
+ limits: MacAccessibilitySnapshotLimits,
+ targetMetadata: [String: String],
+ traceID: String,
+ policy: ToolCallPolicy,
+ lastPersistedSequence: inout Int
+ ) async throws -> ManualAccessibilityCaptureOutcome {
+ let accessibilityDecision = policy.decision(for: .accessibility)
+ guard accessibilityDecision.isAllowed else {
+ await coordinator.recordToolEvent(
+ capability: .accessibility,
+ decision: accessibilityDecision,
+ toolName: "mac-accessibility-snapshot",
+ summary: "Accessibility snapshot denied by policy",
+ traceID: traceID,
+ metadata: targetMetadata
+ )
+ try await persistNewCoordinatorEvents(
+ runID: runID,
+ lastPersistedSequence: &lastPersistedSequence
+ )
+ return .skipped(reason: "Accessibility snapshot denied by policy")
+ }
+
+ let persistenceDecision = policy.decision(for: .persistence)
+ guard persistenceDecision.isAllowed else {
+ await coordinator.recordToolEvent(
+ capability: .persistence,
+ decision: persistenceDecision,
+ toolName: "local-run-artifact-store",
+ summary: "Accessibility artifact persistence denied by policy",
+ traceID: traceID,
+ metadata: targetMetadata
+ )
+ try await persistNewCoordinatorEvents(
+ runID: runID,
+ lastPersistedSequence: &lastPersistedSequence
+ )
+ return .skipped(reason: "Accessibility artifact persistence denied by policy")
+ }
+
+ do {
+ let outcome = try await accessibilityService.captureSnapshot(
+ runID: runID,
+ selection: selection,
+ limits: limits,
+ artifactID: artifactID,
+ recordsPermissionDeniedEvent: false
+ )
+ switch outcome {
+ case .captured(let result):
+ await coordinator.recordToolEvent(
+ capability: .accessibility,
+ decision: .allow,
+ toolName: "mac-accessibility-snapshot",
+ summary: "Accessibility snapshot captured",
+ traceID: traceID,
+ metadata: targetMetadata
+ )
+ await coordinator.recordToolEvent(
+ capability: .persistence,
+ decision: .allow,
+ toolName: "local-run-artifact-store",
+ summary: "Accessibility artifact persisted",
+ traceID: traceID,
+ metadata: targetMetadata.merging(
+ artifactMetadata(result.artifact)
+ ) { current, _ in current }
+ )
+ try await persistNewCoordinatorEvents(
+ runID: runID,
+ lastPersistedSequence: &lastPersistedSequence
+ )
+ return .captured(result)
+ case .permissionDenied:
+ try await recordAccessibilityPermissionDenied(
+ runID: runID,
+ traceID: traceID,
+ targetMetadata: targetMetadata,
+ lastPersistedSequence: &lastPersistedSequence
+ )
+ return .permissionDenied
+ }
+ } catch MacAccessibilitySnapshotCaptureError.accessibilityNotTrusted {
+ try await recordAccessibilityPermissionDenied(
+ runID: runID,
+ traceID: traceID,
+ targetMetadata: targetMetadata,
+ lastPersistedSequence: &lastPersistedSequence
+ )
+ return .permissionDenied
+ } catch {
+ await coordinator.recordToolEvent(
+ capability: .accessibility,
+ decision: .deny(reason: String(describing: error)),
+ toolName: "mac-accessibility-snapshot",
+ summary: "Accessibility snapshot failed",
+ traceID: traceID,
+ metadata: targetMetadata
+ )
+ try await failRun(
+ runID: runID,
+ reason: "Manual capture failed during Accessibility snapshot",
+ lastPersistedSequence: &lastPersistedSequence
+ )
+ throw ManualTargetContextCaptureError.accessibilityFailed(String(describing: error))
+ }
+ }
+
+ private func recordAccessibilityPermissionDenied(
+ runID: String,
+ traceID: String,
+ targetMetadata: [String: String],
+ lastPersistedSequence: inout Int
+ ) async throws {
+ await coordinator.recordToolEvent(
+ capability: .accessibility,
+ decision: .deny(reason: "Accessibility permission is not granted"),
+ toolName: "mac-accessibility-snapshot",
+ summary: "Accessibility permission is not granted",
+ traceID: traceID,
+ metadata: targetMetadata.merging(
+ ["accessibility.trustStatus": MacAccessibilityTrustStatus.notTrusted.rawValue]
+ ) { current, _ in current }
+ )
+ try await persistNewCoordinatorEvents(
+ runID: runID,
+ lastPersistedSequence: &lastPersistedSequence
+ )
+ }
+
+ private func recordTargetResolutionFailure(
+ _ error: Error,
+ traceID: String
+ ) async {
+ await coordinator.recordToolEvent(
+ capability: .capture,
+ decision: .deny(reason: String(describing: error)),
+ toolName: "mac-window-resolver",
+ summary: "Target window resolution failed",
+ traceID: traceID,
+ metadata: ["error": String(describing: error)]
+ )
+ }
+
+ private func failRun(
+ runID: String,
+ reason: String,
+ lastPersistedSequence: inout Int
+ ) async throws {
+ try await persistNewCoordinatorEvents(
+ runID: runID,
+ lastPersistedSequence: &lastPersistedSequence
+ )
+ await coordinator.fail(reason: reason)
+ try await persistNewCoordinatorEvents(
+ runID: runID,
+ lastPersistedSequence: &lastPersistedSequence
+ )
+ }
+
+ private func persistNewCoordinatorEvents(
+ runID: String,
+ lastPersistedSequence: inout Int
+ ) async throws {
+ let events = await coordinator.events()
+ .filter { $0.sequence > lastPersistedSequence }
+ .sorted { $0.sequence < $1.sequence }
+
+ for event in events {
+ _ = try await artifactStore.appendEvent(event, runID: runID)
+ lastPersistedSequence = event.sequence
+ }
+ }
+
+ private func policyDeniedError(
+ capability: ToolCallCapability,
+ decision: ToolCallDecision
+ ) -> ManualTargetContextCaptureError {
+ switch decision {
+ case .allow:
+ return .policyDenied(
+ capability: capability,
+ reason: "\(capability.rawValue) policy unexpectedly allowed"
+ )
+ case .deny(let reason), .ask(let reason):
+ return .policyDenied(capability: capability, reason: reason)
+ }
+ }
+
+ private func metadata(
+ for target: MacWindowTargetCandidate
+ ) -> [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.isVisible": String(target.isVisible),
+ "target.isOnScreen": String(target.isOnScreen),
+ "target.isFrontmost": String(target.isFrontmost),
+ "target.isFocused": String(target.isFocused),
+ "target.isIPhoneMirroring": String(target.isIPhoneMirroring),
+ "target.safety.status": target.safetyAssessment.status.rawValue,
+ "target.safety.reasons": target.safetyAssessment.reasons.map(\.rawValue).joined(separator: ",")
+ ]
+
+ 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
+ }
+
+ private func artifactMetadata(_ artifact: RunArtifactRecord) -> [String: String] {
+ [
+ "artifact.id": artifact.artifactID,
+ "artifact.kind": artifact.kind.rawValue,
+ "artifact.relativePath": artifact.relativePath,
+ "artifact.contentType": artifact.contentType,
+ "artifact.byteCount": String(artifact.byteCount)
+ ]
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/RunCoordinator.swift b/apps/Donkey/Sources/DonkeyRuntime/RunCoordinator.swift
index 965bf513..5ab4249c 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/RunCoordinator.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/RunCoordinator.swift
@@ -8,6 +8,7 @@ public actor RunCoordinator {
private var currentSession: RunSession?
private var lifecycleState: RunLifecycleState = .idle
private var requiresInputRelease = false
+ private var activeTraceID: String?
public init(
sessionQueue: LatestRunSessionQueue = LatestRunSessionQueue(),
@@ -23,6 +24,10 @@ public actor RunCoordinator {
await sessionQueue.submit(session)
}
+ public func setTraceID(_ traceID: String?) {
+ activeTraceID = traceID
+ }
+
@discardableResult
public func startNext() async -> RunSessionTicket? {
guard let ticket = await sessionQueue.nextLatest() else { return nil }
@@ -87,20 +92,42 @@ public actor RunCoordinator {
capability: ToolCallCapability,
toolName: String? = nil
) async -> ToolCallDecision {
- let decision = activePolicy().decision(for: capability)
+ let event = await recordToolEvent(
+ capability: capability,
+ toolName: toolName
+ )
+ guard case .tool(let payload) = event.payload else {
+ return .deny(reason: "\(capability.rawValue) tool event was not recorded")
+ }
+
+ return payload.decision
+ }
+
+ @discardableResult
+ public func recordToolEvent(
+ capability: ToolCallCapability,
+ decision explicitDecision: ToolCallDecision? = nil,
+ toolName: String? = nil,
+ summary: String? = nil,
+ traceID: String? = nil,
+ metadata: [String: String] = [:]
+ ) async -> RunEvent {
+ let decision = explicitDecision ?? activePolicy().decision(for: capability)
let event = RunEvent(
stream: .tool,
- summary: "\(capability.rawValue) tool call \(decision.summaryFragment)",
+ summary: summary ?? "\(capability.rawValue) tool call \(decision.summaryFragment)",
payload: .tool(
ToolRunEvent(
capability: capability,
decision: decision,
toolName: toolName
)
- )
+ ),
+ traceID: traceID ?? activeTraceID,
+ metadata: metadata
)
- await eventStore.append(event)
- return decision
+
+ return await eventStore.append(event)
}
public func appendReflexSample(
@@ -120,7 +147,7 @@ public actor RunCoordinator {
actionID: actionID
)
),
- traceID: traceID
+ traceID: traceID ?? activeTraceID
)
)
}
@@ -177,6 +204,7 @@ public actor RunCoordinator {
reason: reason
)
),
+ traceID: activeTraceID,
requiresInputRelease: requiresInputRelease
)
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/ManualTargetContextCaptureServiceTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ManualTargetContextCaptureServiceTests.swift
new file mode 100644
index 00000000..57b20c0b
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ManualTargetContextCaptureServiceTests.swift
@@ -0,0 +1,569 @@
+import DonkeyContracts
+@testable import DonkeyRuntime
+import Foundation
+import Testing
+
+@Suite
+struct ManualTargetContextCaptureServiceTests {
+ @Test
+ func happyPathCreatesArtifactsAndPersistsOrderedCoordinatorEvents() async throws {
+ let root = temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let store = try LocalRunArtifactStore(baseDirectory: root)
+ let coordinator = RunCoordinator()
+ let screenshotCapturer = FakeWindowScreenshotCapturer()
+ let accessibilityCapturer = FakeMacAccessibilitySnapshotCapturer(
+ tree: MacAccessibilitySnapshotTreeBuilder.build(
+ root: RawMacAccessibilitySnapshotNode(
+ role: "AXWindow",
+ title: "Manual Target",
+ children: [
+ RawMacAccessibilitySnapshotNode(role: "AXButton", title: "OK")
+ ]
+ ),
+ limits: .default
+ )
+ )
+ let service = makeService(
+ store: store,
+ coordinator: coordinator,
+ windows: [
+ fixtureWindow(windowID: 10, processID: 100, appName: "Notes", title: "Manual Target")
+ ],
+ frontmostProcessID: 100,
+ screenshotCapturer: screenshotCapturer,
+ accessibilityCapturer: accessibilityCapturer
+ )
+
+ let result = try await service.capture(
+ session: RunSession(id: "run-manual", userGoal: "capture context", targetID: "target-1"),
+ traceID: "trace-manual",
+ screenshotArtifactID: "screenshot-manual",
+ accessibilityArtifactID: "accessibility-manual"
+ )
+
+ #expect(result.target.windowID == 10)
+ #expect(result.screenshot.artifact.relativePath == "screenshots/screenshot-manual.png")
+ guard case .captured(let accessibilityResult) = result.accessibility else {
+ Issue.record("Expected Accessibility capture")
+ return
+ }
+ #expect(accessibilityResult.artifact.relativePath == "accessibility/accessibility-manual.json")
+ #expect(screenshotCapturer.capturedWindowIDs == [10])
+ #expect(accessibilityCapturer.capturedWindowIDs == [10])
+
+ let summary = try await store.summary(runID: "run-manual")
+ #expect(summary.artifacts.map(\.kind) == [.screenshot, .accessibilitySnapshot])
+ #expect(summary.eventCount == 9)
+ #expect(fileExists(root
+ .appendingPathComponent("run-manual", isDirectory: true)
+ .appendingPathComponent("screenshots/screenshot-manual.png")))
+ #expect(fileExists(root
+ .appendingPathComponent("run-manual", isDirectory: true)
+ .appendingPathComponent("accessibility/accessibility-manual.json")))
+
+ let records = try jsonlRecords(
+ from: root
+ .appendingPathComponent("run-manual", isDirectory: true)
+ .appendingPathComponent("events.jsonl")
+ )
+ #expect(records.map(\.event.sequence) == Array(1...9))
+ #expect(records.map(\.event.stream) == [
+ .lifecycle,
+ .lifecycle,
+ .tool,
+ .tool,
+ .tool,
+ .tool,
+ .tool,
+ .lifecycle,
+ .lifecycle
+ ])
+ #expect(records.map(\.event.summary) == [
+ "Run starting",
+ "Run running",
+ "Target window resolved",
+ "Screenshot capture started",
+ "Screenshot artifact persisted",
+ "Accessibility snapshot captured",
+ "Accessibility artifact persisted",
+ "Run stopping",
+ "Run completed"
+ ])
+ #expect(records.allSatisfy { $0.traceID == "trace-manual" })
+ #expect(records.allSatisfy { $0.event.traceID == "trace-manual" })
+ #expect(toolPayloads(in: records).allSatisfy { $0.capability != .input })
+ }
+
+ @Test
+ func labeledWindowSelectionUsesDurableWindowIDForBothCaptureServices() async throws {
+ let root = temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let store = try LocalRunArtifactStore(baseDirectory: root)
+ let windows = [
+ fixtureWindow(windowID: 11, processID: 100, appName: "Terminal"),
+ fixtureWindow(windowID: 22, processID: 200, appName: "Safari")
+ ]
+ let snapshot = MacWindowResolver(
+ provider: FixtureWindowProvider(
+ windows: windows,
+ frontmostProcessID: 100
+ )
+ )
+ .enumerateCandidateList()
+ let screenshotCapturer = FakeWindowScreenshotCapturer()
+ let accessibilityCapturer = FakeMacAccessibilitySnapshotCapturer()
+ let service = makeService(
+ store: store,
+ coordinator: RunCoordinator(),
+ windows: windows,
+ frontmostProcessID: 100,
+ screenshotCapturer: screenshotCapturer,
+ accessibilityCapturer: accessibilityCapturer
+ )
+
+ guard let selection = snapshot.selectionRequest(forLabel: "window 2") else {
+ Issue.record("Expected window 2 selection")
+ return
+ }
+ let result = try await service.capture(
+ session: RunSession(id: "run-labeled-manual", userGoal: "capture context", targetID: "target-1"),
+ selection: selection,
+ traceID: "trace-labeled-manual",
+ screenshotArtifactID: "screenshot-labeled-manual",
+ accessibilityArtifactID: "accessibility-labeled-manual"
+ )
+
+ #expect(result.target.windowID == 22)
+ #expect(screenshotCapturer.capturedWindowIDs == [22])
+ #expect(accessibilityCapturer.capturedWindowIDs == [22])
+ }
+
+ @Test
+ func missingAccessibilityTrustRecordsCoordinatorPartialEventAndNoAXArtifact() async throws {
+ let root = temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let store = try LocalRunArtifactStore(baseDirectory: root)
+ let accessibilityCapturer = FakeMacAccessibilitySnapshotCapturer(trustStatus: .notTrusted)
+ let service = makeService(
+ store: store,
+ coordinator: RunCoordinator(),
+ windows: [
+ fixtureWindow(windowID: 10, processID: 100, appName: "Notes")
+ ],
+ frontmostProcessID: 100,
+ screenshotCapturer: FakeWindowScreenshotCapturer(),
+ accessibilityCapturer: accessibilityCapturer
+ )
+
+ let result = try await service.capture(
+ session: RunSession(id: "run-manual-ax-denied", userGoal: "capture context", targetID: "target-1"),
+ traceID: "trace-manual-ax-denied",
+ screenshotArtifactID: "screenshot-manual-ax-denied",
+ accessibilityArtifactID: "accessibility-manual-ax-denied"
+ )
+
+ guard case .permissionDenied = result.accessibility else {
+ Issue.record("Expected Accessibility permission denial")
+ return
+ }
+ #expect(accessibilityCapturer.capturedWindowIDs.isEmpty)
+
+ let summary = try await store.summary(runID: "run-manual-ax-denied")
+ #expect(summary.artifacts.map(\.kind) == [.screenshot])
+ #expect(summary.eventCount == 8)
+ #expect(!fileExists(root
+ .appendingPathComponent("run-manual-ax-denied", isDirectory: true)
+ .appendingPathComponent("accessibility/accessibility-manual-ax-denied.json")))
+
+ let records = try jsonlRecords(
+ from: root
+ .appendingPathComponent("run-manual-ax-denied", isDirectory: true)
+ .appendingPathComponent("events.jsonl")
+ )
+ #expect(records.map(\.event.summary).filter { $0 == "Accessibility permission is not granted" }.count == 1)
+ #expect(records.map(\.event.summary).contains("Run completed"))
+ #expect(toolPayloads(in: records).filter { $0.capability == .accessibility && !$0.decision.isAllowed }.count == 1)
+ }
+
+ @Test
+ func unsafeTargetFailsBeforeCaptureArtifacts() async throws {
+ let root = temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let store = try LocalRunArtifactStore(baseDirectory: root)
+ let screenshotCapturer = FakeWindowScreenshotCapturer()
+ let accessibilityCapturer = FakeMacAccessibilitySnapshotCapturer()
+ let service = makeService(
+ store: store,
+ coordinator: RunCoordinator(),
+ windows: [
+ fixtureWindow(windowID: 10, processID: 100, appName: "Safari", title: "Checkout Payment")
+ ],
+ frontmostProcessID: 100,
+ screenshotCapturer: screenshotCapturer,
+ accessibilityCapturer: accessibilityCapturer
+ )
+
+ do {
+ _ = try await service.capture(
+ session: RunSession(id: "run-manual-unsafe", userGoal: "capture context", targetID: "target-1"),
+ traceID: "trace-manual-unsafe",
+ screenshotArtifactID: "screenshot-manual-unsafe",
+ accessibilityArtifactID: "accessibility-manual-unsafe"
+ )
+ Issue.record("Expected unsafe target refusal")
+ } catch ManualTargetContextCaptureError.unsafeTarget(let windowID, let status) {
+ #expect(windowID == 10)
+ #expect(status == .blocked)
+ } catch {
+ Issue.record("Unexpected error: \(error)")
+ }
+
+ #expect(screenshotCapturer.capturedWindowIDs.isEmpty)
+ #expect(accessibilityCapturer.capturedWindowIDs.isEmpty)
+ let summary = try await store.summary(runID: "run-manual-unsafe")
+ #expect(summary.artifacts.isEmpty)
+ #expect(summary.eventCount == 4)
+
+ let records = try jsonlRecords(
+ from: root
+ .appendingPathComponent("run-manual-unsafe", isDirectory: true)
+ .appendingPathComponent("events.jsonl")
+ )
+ #expect(records.map(\.event.summary) == [
+ "Run starting",
+ "Run running",
+ "Target window refused",
+ "Run failed"
+ ])
+ }
+
+ @Test
+ func screenshotFailureRecordsFailureAndNoArtifacts() async throws {
+ let root = temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let store = try LocalRunArtifactStore(baseDirectory: root)
+ let screenshotCapturer = FakeWindowScreenshotCapturer(error: FixtureScreenshotError.failed)
+ let accessibilityCapturer = FakeMacAccessibilitySnapshotCapturer()
+ let service = makeService(
+ store: store,
+ coordinator: RunCoordinator(),
+ windows: [
+ fixtureWindow(windowID: 10, processID: 100, appName: "Notes")
+ ],
+ frontmostProcessID: 100,
+ screenshotCapturer: screenshotCapturer,
+ accessibilityCapturer: accessibilityCapturer
+ )
+
+ do {
+ _ = try await service.capture(
+ session: RunSession(id: "run-manual-screenshot-failure", userGoal: "capture context", targetID: "target-1"),
+ traceID: "trace-manual-screenshot-failure",
+ screenshotArtifactID: "screenshot-manual-failure",
+ accessibilityArtifactID: "accessibility-manual-failure"
+ )
+ Issue.record("Expected screenshot failure")
+ } catch ManualTargetContextCaptureError.screenshotFailed(let reason) {
+ #expect(reason.contains("failed"))
+ } catch {
+ Issue.record("Unexpected error: \(error)")
+ }
+
+ #expect(screenshotCapturer.capturedWindowIDs == [10])
+ #expect(accessibilityCapturer.capturedWindowIDs.isEmpty)
+ let summary = try await store.summary(runID: "run-manual-screenshot-failure")
+ #expect(summary.artifacts.isEmpty)
+
+ let records = try jsonlRecords(
+ from: root
+ .appendingPathComponent("run-manual-screenshot-failure", isDirectory: true)
+ .appendingPathComponent("events.jsonl")
+ )
+ #expect(records.map(\.event.summary).contains("Screenshot capture failed"))
+ #expect(records.map(\.event.summary).last == "Run failed")
+ #expect(!fileExists(root
+ .appendingPathComponent("run-manual-screenshot-failure", isDirectory: true)
+ .appendingPathComponent("screenshots/screenshot-manual-failure.png")))
+ }
+
+ @Test
+ func persistencePolicyDenialStopsBeforeDeniedWrite() async throws {
+ let root = temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let store = try LocalRunArtifactStore(baseDirectory: root)
+ let screenshotCapturer = FakeWindowScreenshotCapturer()
+ let accessibilityCapturer = FakeMacAccessibilitySnapshotCapturer()
+ let service = makeService(
+ store: store,
+ coordinator: RunCoordinator(),
+ windows: [
+ fixtureWindow(windowID: 10, processID: 100, appName: "Notes")
+ ],
+ frontmostProcessID: 100,
+ screenshotCapturer: screenshotCapturer,
+ accessibilityCapturer: accessibilityCapturer
+ )
+ let session = RunSession(
+ id: "run-manual-persistence-denied",
+ userGoal: "capture context",
+ targetID: "target-1",
+ permissionPolicy: ToolCallPolicy(deniedCapabilities: [.input, .persistence])
+ )
+
+ do {
+ _ = try await service.capture(
+ session: session,
+ traceID: "trace-manual-persistence-denied",
+ screenshotArtifactID: "screenshot-denied",
+ accessibilityArtifactID: "accessibility-denied"
+ )
+ Issue.record("Expected persistence policy denial")
+ } catch ManualTargetContextCaptureError.policyDenied(let capability, let reason) {
+ #expect(capability == .persistence)
+ #expect(reason == "persistence capability is denied by policy")
+ } catch {
+ Issue.record("Unexpected error: \(error)")
+ }
+
+ #expect(screenshotCapturer.capturedWindowIDs.isEmpty)
+ #expect(accessibilityCapturer.capturedWindowIDs.isEmpty)
+ let summary = try await store.summary(runID: "run-manual-persistence-denied")
+ #expect(summary.artifacts.isEmpty)
+
+ let records = try jsonlRecords(
+ from: root
+ .appendingPathComponent("run-manual-persistence-denied", isDirectory: true)
+ .appendingPathComponent("events.jsonl")
+ )
+ #expect(records.map(\.event.summary).contains("Screenshot artifact persistence denied by policy"))
+ #expect(records.map(\.event.summary).last == "Run failed")
+ }
+
+ private func makeService(
+ store: LocalRunArtifactStore,
+ coordinator: RunCoordinator,
+ windows: [MacWindowProviderWindow],
+ frontmostProcessID: Int32? = nil,
+ focusedWindowID: UInt32? = nil,
+ screenshotCapturer: FakeWindowScreenshotCapturer,
+ accessibilityCapturer: FakeMacAccessibilitySnapshotCapturer
+ ) -> ManualTargetContextCaptureService {
+ let windowResolver = MacWindowResolver(
+ provider: FixtureWindowProvider(
+ windows: windows,
+ frontmostProcessID: frontmostProcessID,
+ focusedWindowID: focusedWindowID
+ )
+ )
+ let screenshotService = WindowScreenshotCaptureService(
+ artifactStore: store,
+ windowResolver: MacWindowResolver(
+ provider: FixtureWindowProvider(
+ windows: windows,
+ frontmostProcessID: frontmostProcessID,
+ focusedWindowID: focusedWindowID
+ )
+ ),
+ capturer: screenshotCapturer
+ )
+ let accessibilityService = MacAccessibilitySnapshotCaptureService(
+ artifactStore: store,
+ windowResolver: MacWindowResolver(
+ provider: FixtureWindowProvider(
+ windows: windows,
+ frontmostProcessID: frontmostProcessID,
+ focusedWindowID: focusedWindowID
+ )
+ ),
+ capturer: accessibilityCapturer
+ )
+
+ return ManualTargetContextCaptureService(
+ coordinator: coordinator,
+ artifactStore: store,
+ windowResolver: windowResolver,
+ screenshotService: screenshotService,
+ accessibilityService: accessibilityService
+ )
+ }
+
+ 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 func temporaryDirectory() -> URL {
+ FileManager.default.temporaryDirectory.appendingPathComponent(
+ "DonkeyManualTargetContextCaptureTests-\(UUID().uuidString)",
+ isDirectory: true
+ )
+ }
+
+ private func fileExists(_ url: URL) -> Bool {
+ var isDirectory = ObjCBool(false)
+ let exists = FileManager.default.fileExists(
+ atPath: url.path,
+ isDirectory: &isDirectory
+ )
+ return exists && !isDirectory.boolValue
+ }
+
+ private func jsonlRecords(from url: URL) throws -> [RunTraceEventRecord] {
+ let data = try Data(contentsOf: url)
+ let text = String(decoding: data, as: UTF8.self)
+ return try text
+ .split(separator: "\n")
+ .map { line in
+ try JSONDecoder().decode(
+ RunTraceEventRecord.self,
+ from: Data(line.utf8)
+ )
+ }
+ }
+
+ private func toolPayloads(in records: [RunTraceEventRecord]) -> [ToolRunEvent] {
+ records.compactMap { record in
+ guard case .tool(let payload) = record.event.payload else {
+ return nil
+ }
+
+ return payload
+ }
+ }
+}
+
+private final class FakeWindowScreenshotCapturer: WindowScreenshotCapturing {
+ var pngData: Data
+ var imageWidth: Int
+ var imageHeight: Int
+ var captureMethod: WindowScreenshotCaptureMethod
+ var requiresOverlapFreeTarget: Bool
+ var error: Error?
+ var capturedWindowIDs: [UInt32] = []
+
+ init(
+ pngData: Data = Data([0x89, 0x50, 0x4E, 0x47]),
+ imageWidth: Int = 100,
+ imageHeight: Int = 100,
+ captureMethod: WindowScreenshotCaptureMethod = .screenCaptureKitDesktopIndependentWindow,
+ requiresOverlapFreeTarget: Bool = false,
+ error: Error? = nil
+ ) {
+ self.pngData = pngData
+ self.imageWidth = imageWidth
+ self.imageHeight = imageHeight
+ self.captureMethod = captureMethod
+ self.requiresOverlapFreeTarget = requiresOverlapFreeTarget
+ self.error = error
+ }
+
+ func capture(
+ target: MacWindowTargetCandidate
+ ) async throws -> CapturedWindowScreenshot {
+ capturedWindowIDs.append(target.windowID)
+ if let error {
+ throw error
+ }
+
+ return CapturedWindowScreenshot(
+ pngData: pngData,
+ imageWidth: imageWidth,
+ imageHeight: imageHeight,
+ captureMethod: captureMethod,
+ coordinateSpace: "fixture.pixels"
+ )
+ }
+}
+
+private final class FakeMacAccessibilitySnapshotCapturer: MacAccessibilitySnapshotCapturing {
+ var trust: MacAccessibilityTrustStatus
+ var tree: MacAccessibilitySnapshotTree
+ var error: Error?
+ var capturedWindowIDs: [UInt32] = []
+
+ init(
+ trustStatus: MacAccessibilityTrustStatus = .trusted,
+ tree: MacAccessibilitySnapshotTree = MacAccessibilitySnapshotTreeBuilder.build(
+ root: RawMacAccessibilitySnapshotNode(role: "AXWindow", title: "Window"),
+ limits: .default
+ ),
+ error: Error? = nil
+ ) {
+ self.trust = trustStatus
+ self.tree = tree
+ self.error = error
+ }
+
+ func trustStatus() -> MacAccessibilityTrustStatus {
+ trust
+ }
+
+ func captureTree(
+ target: MacWindowTargetCandidate,
+ limits: MacAccessibilitySnapshotLimits
+ ) throws -> MacAccessibilitySnapshotTree {
+ capturedWindowIDs.append(target.windowID)
+ if let error {
+ throw error
+ }
+
+ return tree
+ }
+}
+
+private enum FixtureScreenshotError: Error {
+ case failed
+}
+
+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.md
index 39eaa7e6..b8dc3300 100644
--- a/docs/guides/minimal-run-coordinator.md
+++ b/docs/guides/minimal-run-coordinator.md
@@ -31,7 +31,9 @@ Donkey can create a single read-only target-window screenshot artifact after a r
Donkey can also create a shallow read-only Accessibility snapshot artifact after a run folder has been prepared. The Accessibility snapshot service resolves the same target-window selection, refuses blocked or review-required safety surfaces, checks Accessibility trust without prompting, writes a bounded JSON tree under `accessibility/` when trusted, and records artifact metadata in `summary.json`. If Accessibility trust is missing, the service appends a clear partial-run tool event to `events.jsonl` and does not create an artifact.
-This is a coordination, trace, target-metadata, single-screenshot artifact, and read-only Accessibility snapshot foundation only. It does not run perception models, call LLMs, execute OS input, perform Accessibility actions, provide a manual capture UI, or wire the full capture flow through `RunCoordinator` events yet.
+Donkey supports a runtime-level manual target context capture service that wires one read-only capture run through `RunCoordinator`. The service prepares the run folder, starts the session, resolves the target once, passes explicit durable `windowID` selection to screenshot and Accessibility capture services, records coordinator-assigned lifecycle and tool events, persists those events to `events.jsonl`, and completes the run after screenshot success. Missing Accessibility trust is a partial completion: the coordinator records one permission-denied tool event, the screenshot artifact remains, and no Accessibility artifact is created.
+
+This is a coordination, 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, or perform manual verification against live apps yet.
## Technical Guidelines
@@ -42,6 +44,7 @@ This is a coordination, trace, target-metadata, single-screenshot artifact, and
- Treat macOS window resolution as read-only metadata collection. Safety classifications should be conservative and used by later capture code to refuse or stop on sensitive surfaces.
- Treat target-window screenshot capture as a one-shot artifact write, not a continuous capture loop. ScreenCaptureKit desktop-independent window capture is preferred because overlapping windows do not contaminate the selected target artifact.
- Treat Accessibility snapshot capture as read-only inspection. Keep trees bounded, redact long text values, avoid permission prompts in the capture service, and never perform AX actions from this path.
+- Treat manual target context capture as orchestration. `RunCoordinator` owns event order and policy decisions, while screenshot, Accessibility, and artifact-store services remain capture/persistence workers.
- 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.
@@ -55,7 +58,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, 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, and overlap-sensitive capture refusal.
+The runtime tests should cover lifecycle ordering, abort and timeout safety, latest-session queue drops, tool permission denial, event-store ordering, context compaction, 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, and manual capture event ordering through persisted coordinator events.
## Source Entry Points
@@ -66,5 +69,6 @@ The runtime tests should cover lifecycle ordering, abort and timeout safety, lat
- Target-window screenshot capture lives in `apps/Donkey/Sources/DonkeyRuntime/WindowScreenshotCaptureService.swift`.
- Accessibility snapshot contracts live in `apps/Donkey/Sources/DonkeyContracts/AccessibilitySnapshotContracts.swift`.
- Read-only Accessibility snapshot capture lives in `apps/Donkey/Sources/DonkeyRuntime/MacAccessibilitySnapshotCaptureService.swift`.
+- Manual target context capture orchestration lives in `apps/Donkey/Sources/DonkeyRuntime/ManualTargetContextCaptureService.swift`.
- Local artifact persistence lives in `apps/Donkey/Sources/DonkeyRuntime/LocalRunArtifactStore.swift`.
- The manual capture source plan remains active in `plans/master-plan.md`.
diff --git a/plans/master-plan.md b/plans/master-plan.md
index 14b9c120..90f53253 100644
--- a/plans/master-plan.md
+++ b/plans/master-plan.md
@@ -73,14 +73,17 @@ Out of scope:
### Runtime And Permission Integration
-- Add a capture-facing service in `DonkeyRuntime` that works with `RunCoordinator`.
-- Extend the current tool capability policy only as needed for read-only capture:
- - screenshot/window capture
- - Accessibility tree read
- - trace persistence
-- Keep input/action capabilities denied by default.
-- Emit `tool` events for target resolution, screenshot capture, Accessibility snapshot, and artifact persistence.
-- Emit `lifecycle` events for manual capture start, completion, abort, timeout, and failure.
+Supported as the fifth vertical slice. `ManualTargetContextCaptureService` orchestrates one read-only capture run through `RunCoordinator`, `LocalRunArtifactStore`, target-window resolution, screenshot capture, and Accessibility snapshot capture.
+
+The service prepares the run folder, starts the session, resolves the target once, passes explicit durable `windowID` selection to capture services, records coordinator-assigned lifecycle/tool events, persists those events to `events.jsonl`, and completes the run after screenshot success. Missing Accessibility trust is treated as partial completion: the coordinator records one permission-denied tool event, no Accessibility artifact is written, and the screenshot artifact remains.
+
+Current boundaries:
+
+- The API is runtime-level only. No manual command shell or UI entrypoint has been added yet.
+- Screenshot success is required for completion. Target-resolution, screenshot, persistence, and safety-stop failures fail the run.
+- Accessibility trust denial is the only supported partial-completion AX failure. Other AX capture failures fail the run.
+- Input/action capabilities remain denied by default, and the manual capture service emits no input tool events.
+- Standalone screenshot and Accessibility capture services remain usable independently; standalone missing-AX-trust behavior still records its own partial event unless the orchestrator asks it not to.
### Target Window Resolution
@@ -124,9 +127,10 @@ Current boundaries:
- The snapshot path is read-only. It records available AX action names but never performs Accessibility actions.
- Missing Accessibility trust creates an `events.jsonl` partial-run event and no artifact; the service does not open System Settings or request trust.
+- Manual capture orchestration can suppress the standalone permission event so missing trust is recorded once through `RunCoordinator`.
- AX window matching is best effort by pid, title, focus, and frame metadata. Selection remains durable by `windowID` at the resolver/capture boundary.
- Trees are bounded by depth, children per node, total nodes, and text length. Long text values are summarized with redaction markers.
-- The service does not publish ordered `RunCoordinator` events yet.
+- Ordered `RunCoordinator` events are published by the manual capture orchestrator, not by the standalone AX snapshot service.
### Trace Artifact Store
@@ -186,10 +190,14 @@ accessibility/
## What Should Be Done Next
-Continue the read-only vertical slice from the completed local artifact writer, window resolver, candidate-list API, screenshot artifact service, and Accessibility snapshot service:
-
-1. Wire the manual capture flow through `RunCoordinator` events.
- - Emit ordered lifecycle/tool events for target resolution, screenshot capture, AX snapshot, artifact persistence, completion, and failure paths.
-2. Add integration tests and manual verification.
- - Cover artifact metadata, bounded AX serialization, policy denial for input, and partial summaries.
- - Manually verify against iPhone Mirroring and at least one other visible Mac app window, including an overlapped-window scenario.
+Continue from the completed local artifact writer, window resolver, candidate-list API, screenshot artifact service, Accessibility snapshot service, and runtime-level manual capture event wiring:
+
+1. Add an integration/manual verification entrypoint.
+ - Provide a small debug command, developer hook, or equivalent UI action that invokes the existing runtime-level manual capture service without adding synthetic input.
+2. Manually verify against real windows.
+ - Test at least iPhone Mirroring and one normal Mac app window.
+ - Include an overlapped-window scenario and an Accessibility-trust-missing scenario.
+ - Confirm the trace folder contains ordered coordinator events, one screenshot artifact, and an Accessibility artifact only when permission is available.
+3. Close out the milestone after verification.
+ - Keep the supported guide current.
+ - Move this plan to `plans/done/` once the manual entrypoint and verification are complete.