Open source CapCut alternative.
TypeScript
Use AppHarnessDecision for harness routing
David Lead5b9475e9b5
diff --git a/AGENTS.md b/AGENTS.mdindex d75e9441..b62b220d 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -29,4 +29,5 @@ Before changing `site/` UI, routes, API handlers, or data access patterns:- When work completes a master-plan slice, update the master plan's supported/current-boundary language and next steps in the same change.- Keep guides explanatory. They should teach what the system is, how it works, and which boundaries matter; do not turn guides into feature inventories, implementation logs, duplicated code, or long file lists.- Keep guide source entrypoints short and readable. Do not write exhaustive file inventories. Prefer a small maintainer map by subsystem or one to seven high-signal paths, and link to a source path only when it gives someone a clear place to start.+- Build forward by default. Prefer updating callers and contracts to the new supported shape instead of preserving old compatibility paths; ask before adding or keeping backwards-compatibility shims.- Keep this file stable and lightweight.diff --git a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swiftindex db623282..3de27892 100644--- a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift+++ b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift@@ -6,7 +6,7 @@ import Foundationstruct PointerPromptCommandHandlingResult: Equatable, Sendable {var status: LocalAppTaskLiveRunStatusvar threadStatus: PointerPromptTaskStatus- var routeKind: AppHarnessTurnRouteKind+ var decision: AppHarnessDecisionvar summary: Stringvar taskLabel: String?var traceID: String@@ -82,23 +82,23 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {request: Self.harnessRequest(command: command, context: context),traceID: traceID)- switch routing.outcome.kind {- case .conversation, .assistantResponse:+ switch routing.outcome.decision.kind {+ case .respond:return PointerPromptCommandHandlingResult(status: .completed,threadStatus: .chatting,- routeKind: routing.outcome.kind,+ decision: routing.outcome.decision,summary: routing.outcome.assistantResponse ?? "Tell me what local app task you want to work on.",taskLabel: nil,traceID: traceID,metadata: Self.contextPacketMetadata(routing.contextPacket, outcome: routing.outcome),documentReviewRequest: nil)- case .clarification:+ case .askClarification:return PointerPromptCommandHandlingResult(status: .needsConfirmation,threadStatus: .waitingForClarification,- routeKind: routing.outcome.kind,+ decision: routing.outcome.decision,summary: routing.outcome.assistantResponse ?? "What detail should I use?",taskLabel: nil,traceID: traceID,@@ -109,14 +109,14 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {return PointerPromptCommandHandlingResult(status: .completed,threadStatus: .chatting,- routeKind: routing.outcome.kind,+ decision: routing.outcome.decision,summary: "",taskLabel: nil,traceID: traceID,metadata: Self.contextPacketMetadata(routing.contextPacket, outcome: routing.outcome),documentReviewRequest: nil)- case .actionableIntent, .review, .execution, .failure:+ case .openReview, .runLocalTask:break}@@ -151,7 +151,7 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {traceID: traceID,resolution: resolution,metadata: [- "appHarness.route": routing.outcome.kind.rawValue,+ "appHarness.decision": routing.outcome.decision.kind.rawValue,"appHarness.context.promptCharacters": String(routing.contextPacket.promptText.count),"appHarness.context.redactionCount": String(routing.contextPacket.redactionCount),"intentParser": "localModel",@@ -185,7 +185,7 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {let handlingResult = PointerPromptCommandHandlingResult(status: result.status,threadStatus: threadStatus(for: result),- routeKind: routing.outcome.kind,+ decision: routing.outcome.decision,summary: summary(for: result),taskLabel: taskLabel(for: result),traceID: traceID,@@ -390,7 +390,8 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {outcome: AppHarnessRoutingOutcome) -> [String: String] {[- "appHarness.route": outcome.kind.rawValue,+ "appHarness.decision": outcome.decision.kind.rawValue,+ "appHarness.decision.traceID": outcome.decision.traceID,"appHarness.missingDetail": outcome.missingDetail ?? "","appHarness.context.traceID": packet.traceID,"appHarness.context.eventCount": String(packet.recentEvents.count),diff --git a/apps/Donkey/Sources/DonkeyAI/LocalModelPriorityWorker.swift b/apps/Donkey/Sources/DonkeyAI/LocalModelPriorityWorker.swiftnew file mode 100644index 00000000..8f9b1348--- /dev/null+++ b/apps/Donkey/Sources/DonkeyAI/LocalModelPriorityWorker.swift@@ -0,0 +1,224 @@+import Foundation++public enum LocalModelWorkKind: String, Codable, Equatable, Sendable {+ case taskIntent+ case plannerHint+ case memoryProposal+ case replayEvaluation+}++public enum LocalModelWorkPriority: Int, Codable, Comparable, Sendable {+ case userInteractive = 0+ case plannerHint = 10+ case memory = 20+ case replay = 30++ public static func < (lhs: LocalModelWorkPriority, rhs: LocalModelWorkPriority) -> Bool {+ lhs.rawValue < rhs.rawValue+ }+}++public struct LocalModelWorkContext: Sendable {+ public var id: String+ public var kind: LocalModelWorkKind+ public var priority: LocalModelWorkPriority+ public var metadata: [String: String]+ private var cancellationStatus: @Sendable () async -> Bool++ public init(+ id: String,+ kind: LocalModelWorkKind,+ priority: LocalModelWorkPriority,+ metadata: [String: String] = [:],+ cancellationStatus: @escaping @Sendable () async -> Bool+ ) {+ self.id = id+ self.kind = kind+ self.priority = priority+ self.metadata = metadata+ self.cancellationStatus = cancellationStatus+ }++ public func isCancelled() async -> Bool {+ await cancellationStatus()+ }+}++public struct LocalModelPriorityWorkerSnapshot: Equatable, Sendable {+ public var currentWorkID: String?+ public var currentPriority: LocalModelWorkPriority?+ public var queuedCount: Int+ public var cancelledWorkIDs: Set<String>++ public init(+ currentWorkID: String?,+ currentPriority: LocalModelWorkPriority?,+ queuedCount: Int,+ cancelledWorkIDs: Set<String>+ ) {+ self.currentWorkID = currentWorkID+ self.currentPriority = currentPriority+ self.queuedCount = queuedCount+ self.cancelledWorkIDs = cancelledWorkIDs+ }+}++public actor LocalModelPriorityWorker {+ private struct WorkTicket: Equatable, Sendable {+ var id: String+ var kind: LocalModelWorkKind+ var priority: LocalModelWorkPriority+ var sequence: Int+ var metadata: [String: String]+ }++ private var queue: [WorkTicket] = []+ private var waiters: [String: CheckedContinuation<Void, Never>] = [:]+ private var current: WorkTicket?+ private var cancelledWorkIDs: Set<String> = []+ private var nextSequence = 0++ public init() {}++ public func submit<T: Sendable>(+ kind: LocalModelWorkKind,+ priority: LocalModelWorkPriority,+ metadata: [String: String] = [:],+ operation: @escaping @Sendable (LocalModelWorkContext) async -> T+ ) async -> T {+ let ticket = enqueue(kind: kind, priority: priority, metadata: metadata)+ await waitUntilReady(ticket)+ let context = LocalModelWorkContext(+ id: ticket.id,+ kind: kind,+ priority: priority,+ metadata: metadata,+ cancellationStatus: { [weak self] in+ guard let self else { return true }+ return await self.isCancelled(workID: ticket.id)+ }+ )+ let result = await operation(context)+ finish(ticket)+ return result+ }++ public func submit<T: Sendable>(+ kind: LocalModelWorkKind,+ priority: LocalModelWorkPriority,+ metadata: [String: String] = [:],+ operation: @escaping @Sendable () async -> T+ ) async -> T {+ await submit(+ kind: kind,+ priority: priority,+ metadata: metadata+ ) { _ in+ await operation()+ }+ }++ public func cancelCurrent() {+ guard let current else { return }+ cancelledWorkIDs.insert(current.id)+ }++ public func snapshot() -> LocalModelPriorityWorkerSnapshot {+ LocalModelPriorityWorkerSnapshot(+ currentWorkID: current?.id,+ currentPriority: current?.priority,+ queuedCount: queue.count,+ cancelledWorkIDs: cancelledWorkIDs+ )+ }++ public func isCancelled(workID: String) -> Bool {+ cancelledWorkIDs.contains(workID)+ }++ private func enqueue(+ kind: LocalModelWorkKind,+ priority: LocalModelWorkPriority,+ metadata: [String: String]+ ) -> WorkTicket {+ nextSequence += 1+ let ticket = WorkTicket(+ id: "\(kind.rawValue)-\(UUID().uuidString)",+ kind: kind,+ priority: priority,+ sequence: nextSequence,+ metadata: metadata+ )+ queue.append(ticket)+ queue.sort { lhs, rhs in+ if lhs.priority == rhs.priority {+ return lhs.sequence < rhs.sequence+ }+ return lhs.priority < rhs.priority+ }++ if let current, priority < current.priority {+ cancelledWorkIDs.insert(current.id)+ }++ return ticket+ }++ private func waitUntilReady(_ ticket: WorkTicket) async {+ await withCheckedContinuation { continuation in+ waiters[ticket.id] = continuation+ startNextIfIdle()+ }+ }++ private func finish(_ ticket: WorkTicket) {+ if current?.id == ticket.id {+ current = nil+ } else {+ queue.removeAll { $0.id == ticket.id }+ }+ cancelledWorkIDs.remove(ticket.id)+ startNextIfIdle()+ }++ private func startNextIfIdle() {+ guard current == nil, !queue.isEmpty else { return }+ let next = queue.removeFirst()+ current = next+ let continuation = waiters.removeValue(forKey: next.id)+ continuation?.resume()+ }+}++public enum LocalModelWorkScheduling {+ public static let shared = LocalModelPriorityWorker()+}++public struct PriorityQueuedTaskIntentParsingAdapter: TaskIntentParsingAdapter {+ public var base: any TaskIntentParsingAdapter+ public var worker: LocalModelPriorityWorker++ public init(+ base: any TaskIntentParsingAdapter,+ worker: LocalModelPriorityWorker = LocalModelWorkScheduling.shared+ ) {+ self.base = base+ self.worker = worker+ }++ public func parseTaskIntent(_ request: TaskIntentAdapterRequest) async -> TaskIntentAdapterResult {+ let priority: LocalModelWorkPriority = request.routeRequest.latencyTolerance == .interactive+ ? .userInteractive+ : .plannerHint+ return await worker.submit(+ kind: .taskIntent,+ priority: priority,+ metadata: [+ "sourceTraceID": request.sourceTraceID,+ "latencyTolerance": request.routeRequest.latencyTolerance.rawValue+ ]+ ) {+ await base.parseTaskIntent(request)+ }+ }+}diff --git a/apps/Donkey/Sources/DonkeyAI/OllamaTaskIntentAdapter.swift b/apps/Donkey/Sources/DonkeyAI/OllamaTaskIntentAdapter.swiftindex 188cb386..51691059 100644--- a/apps/Donkey/Sources/DonkeyAI/OllamaTaskIntentAdapter.swift+++ b/apps/Donkey/Sources/DonkeyAI/OllamaTaskIntentAdapter.swift@@ -422,7 +422,9 @@ public struct LocalModelTaskIntentResolver: Sendable {public init(catalog: LocalAppTaskCatalog,- adapter: any TaskIntentParsingAdapter = ProcessBackedLocalLLMTaskIntentAdapter()+ adapter: any TaskIntentParsingAdapter = PriorityQueuedTaskIntentParsingAdapter(+ base: ProcessBackedLocalLLMTaskIntentAdapter()+ )) {self.catalog = catalogself.adapter = adapterdiff --git a/apps/Donkey/Sources/DonkeyContracts/AppHarnessContracts.swift b/apps/Donkey/Sources/DonkeyContracts/AppHarnessContracts.swiftindex 9c552d03..14cf125b 100644--- a/apps/Donkey/Sources/DonkeyContracts/AppHarnessContracts.swift+++ b/apps/Donkey/Sources/DonkeyContracts/AppHarnessContracts.swift@@ -7,17 +7,75 @@ public enum AppHarnessTurnSource: String, Codable, Equatable, Sendable {case assetEvent}-public enum AppHarnessTurnRouteKind: String, Codable, Equatable, Sendable {- case conversation- case clarification- case actionableIntent- case review- case execution- case failure- case assistantResponse+public enum AppHarnessDecisionKind: String, Codable, Equatable, Sendable {+ case respond+ case askClarification+ case openReview+ case runLocalTaskcase noOp}+public struct AppHarnessDecision: Codable, Equatable, Sendable {+ public var kind: AppHarnessDecisionKind+ public var message: String?+ public var missingDetail: String?+ public var taskIntentID: String?+ public var traceID: String+ public var metadata: [String: String]++ public init(+ kind: AppHarnessDecisionKind,+ message: String? = nil,+ missingDetail: String? = nil,+ taskIntentID: String? = nil,+ traceID: String,+ metadata: [String: String] = [:]+ ) {+ self.kind = kind+ self.message = message+ self.missingDetail = missingDetail+ self.taskIntentID = taskIntentID+ self.traceID = traceID+ self.metadata = metadata+ }+}++public enum AppHarnessContextItemKind: String, Codable, Equatable, Sendable {+ case currentTurn+ case recentEvent+ case transientCorrection+ case asset+ case memory+ case runtimeCapability+ case targetState+ case policy+}++public struct AppHarnessContextCompactionRecord: Codable, Equatable, Sendable {+ public var itemKind: AppHarnessContextItemKind+ public var originalCount: Int+ public var includedCount: Int+ public var droppedCount: Int+ public var truncatedCount: Int+ public var metadata: [String: String]++ public init(+ itemKind: AppHarnessContextItemKind,+ originalCount: Int,+ includedCount: Int,+ droppedCount: Int = 0,+ truncatedCount: Int = 0,+ metadata: [String: String] = [:]+ ) {+ self.itemKind = itemKind+ self.originalCount = max(0, originalCount)+ self.includedCount = max(0, includedCount)+ self.droppedCount = max(0, droppedCount)+ self.truncatedCount = max(0, truncatedCount)+ self.metadata = metadata+ }+}+public struct AppHarnessTurn: Codable, Equatable, Sendable {public var id: Stringpublic var text: String@@ -78,6 +136,7 @@ public struct AppHarnessContextPacket: Codable, Equatable, Sendable {public var policy: [String: String]public var promptText: Stringpublic var redactionCount: Int+ public var compactionRecords: [AppHarnessContextCompactionRecord]public var metadata: [String: String]public init(@@ -91,6 +150,7 @@ public struct AppHarnessContextPacket: Codable, Equatable, Sendable {policy: [String: String] = [:],promptText: String,redactionCount: Int = 0,+ compactionRecords: [AppHarnessContextCompactionRecord] = [],metadata: [String: String] = [:]) {self.traceID = traceID@@ -103,6 +163,7 @@ public struct AppHarnessContextPacket: Codable, Equatable, Sendable {self.policy = policyself.promptText = promptTextself.redactionCount = redactionCount+ self.compactionRecords = compactionRecordsself.metadata = metadata}}diff --git a/apps/Donkey/Sources/DonkeyContracts/TaskIntentContracts.swift b/apps/Donkey/Sources/DonkeyContracts/TaskIntentContracts.swiftindex 90bb9b8d..47e6d743 100644--- a/apps/Donkey/Sources/DonkeyContracts/TaskIntentContracts.swift+++ b/apps/Donkey/Sources/DonkeyContracts/TaskIntentContracts.swift@@ -95,6 +95,62 @@ public enum LocalAppTaskStepRole: String, Codable, Equatable, Sendable {case custom}+public enum LocalAppTaskWorkflowStage: String, Codable, CaseIterable, Equatable, Sendable {+ case parseIntent+ case resolveApp+ case observe+ case dryRun+ case approval+ case execute+ case verify+}++public enum LocalAppTaskWorkflowStageStatus: String, Codable, Equatable, Sendable {+ case pending+ case started+ case completed+ case waiting+ case skipped+ case blocked+ case failed+}++public struct LocalAppTaskWorkflowStageState: Codable, Equatable, Sendable {+ public var stage: LocalAppTaskWorkflowStage+ public var status: LocalAppTaskWorkflowStageStatus+ public var summary: String+ public var metadata: [String: String]++ public init(+ stage: LocalAppTaskWorkflowStage,+ status: LocalAppTaskWorkflowStageStatus = .pending,+ summary: String = "",+ metadata: [String: String] = [:]+ ) {+ self.stage = stage+ self.status = status+ self.summary = summary+ self.metadata = metadata+ }+}++public struct LocalAppTaskWorkflowProgress: Codable, Equatable, Sendable {+ public var stages: [LocalAppTaskWorkflowStageState]+ public var metadata: [String: String]++ public init(+ stages: [LocalAppTaskWorkflowStageState] = [],+ metadata: [String: String] = [:]+ ) {+ self.stages = stages+ self.metadata = metadata+ }++ public func state(for stage: LocalAppTaskWorkflowStage) -> LocalAppTaskWorkflowStageState? {+ stages.first { $0.stage == stage }+ }+}+public struct LocalAppTaskWorkflowStepDefinition: Codable, Equatable, Sendable {public var id: Stringpublic var role: LocalAppTaskStepRolediff --git a/apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnRouter.swift b/apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnRouter.swiftindex 70d3d0df..f959d9f1 100644--- a/apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnRouter.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnRouter.swift@@ -55,20 +55,20 @@ public struct AppHarnessTurnRequest: Equatable, Sendable {}public struct AppHarnessRoutingOutcome: Equatable, Sendable {- public var kind: AppHarnessTurnRouteKind+ public var decision: AppHarnessDecisionpublic var assistantResponse: String?public var missingDetail: String?public var resolution: LocalAppTaskCatalogResolution?public var metadata: [String: String]public init(- kind: AppHarnessTurnRouteKind,+ decision: AppHarnessDecision,assistantResponse: String? = nil,missingDetail: String? = nil,resolution: LocalAppTaskCatalogResolution? = nil,metadata: [String: String] = [:]) {- self.kind = kind+ self.decision = decisionself.assistantResponse = assistantResponseself.missingDetail = missingDetailself.resolution = resolution@@ -99,45 +99,111 @@ public struct AppHarnessContextPacketBuilder: Sendable {traceID: String) -> AppHarnessContextPacket {var redactionCount = 0+ var compactionRecords: [AppHarnessContextCompactionRecord] = []var turn = request.turnlet redactedTurn = Self.redacted(turn.text)redactionCount += redactedTurn.count- turn.text = Self.truncated(redactedTurn.text, maxLength: limits.maxPromptCharacters)+ let boundedTurn = Self.bounded(redactedTurn.text, maxLength: limits.maxPromptCharacters)+ turn.text = boundedTurn.text+ compactionRecords.append(+ AppHarnessContextCompactionRecord(+ itemKind: .currentTurn,+ originalCount: request.turn.text.isEmpty ? 0 : 1,+ includedCount: turn.text.isEmpty ? 0 : 1,+ truncatedCount: boundedTurn.wasTruncated ? 1 : 0,+ metadata: ["traceID": traceID]+ )+ )- let events = request.recentEvents- .suffix(limits.maxRecentEvents)- .map { event in- let redacted = Self.redacted(event.text)- redactionCount += redacted.count- return AppHarnessContextEvent(+ let preparedEvents = request.recentEvents.map { event -> PreparedHarnessContextEvent in+ let redacted = Self.redacted(event.text)+ redactionCount += redacted.count+ let bounded = Self.bounded(redacted.text, maxLength: limits.maxEventTextCharacters)+ return PreparedHarnessContextEvent(+ event: AppHarnessContextEvent(role: event.role,- text: Self.truncated(redacted.text, maxLength: limits.maxEventTextCharacters),+ text: bounded.text,sequence: event.sequence- )- }+ ),+ sourceID: event.id,+ isTransientCorrection: Self.isTransientCorrection(event),+ wasTruncated: bounded.wasTruncated+ )+ }+ let eventCompaction = Self.compactEvents(+ preparedEvents,+ limit: limits.maxRecentEvents+ )+ let events = eventCompaction.events+ compactionRecords.append(contentsOf: eventCompaction.records)let assets = request.assets.suffix(limits.maxAssets)- .map { asset in- AppHarnessContextAsset(- displayName: Self.truncated(asset.displayName, maxLength: limits.maxAssetNameCharacters),+ .map { asset -> AppHarnessContextAsset in+ let boundedName = Self.bounded(asset.displayName, maxLength: limits.maxAssetNameCharacters)+ return AppHarnessContextAsset(+ displayName: boundedName.text,contentType: asset.contentType,byteCount: asset.byteCount)}+ compactionRecords.append(+ AppHarnessContextCompactionRecord(+ itemKind: .asset,+ originalCount: request.assets.count,+ includedCount: assets.count,+ droppedCount: max(0, request.assets.count - assets.count),+ truncatedCount: request.assets.suffix(limits.maxAssets).filter {+ $0.displayName.count > limits.maxAssetNameCharacters+ }.count+ )+ )let memory = request.memory.prefix(limits.maxMemoryItems).map { item -> String inlet redacted = Self.redacted(item)redactionCount += redacted.count- return Self.truncated(redacted.text, maxLength: limits.maxMemoryTextCharacters)+ return Self.bounded(redacted.text, maxLength: limits.maxMemoryTextCharacters).text}+ compactionRecords.append(+ AppHarnessContextCompactionRecord(+ itemKind: .memory,+ originalCount: request.memory.count,+ includedCount: memory.count,+ droppedCount: max(0, request.memory.count - memory.count),+ truncatedCount: request.memory.prefix(limits.maxMemoryItems).filter {+ Self.redacted($0).text.count > limits.maxMemoryTextCharacters+ }.count+ )+ )let runtimeCapabilities = catalog.taskDefinitions.map { "\($0.taskType):\($0.targetApp.appName)" }.sorted()- let promptText = Self.truncated(+ compactionRecords.append(+ AppHarnessContextCompactionRecord(+ itemKind: .runtimeCapability,+ originalCount: catalog.taskDefinitions.count,+ includedCount: runtimeCapabilities.count+ )+ )+ compactionRecords.append(+ AppHarnessContextCompactionRecord(+ itemKind: .targetState,+ originalCount: request.targetState.count,+ includedCount: request.targetState.count+ )+ )+ compactionRecords.append(+ AppHarnessContextCompactionRecord(+ itemKind: .policy,+ originalCount: request.policy.count,+ includedCount: request.policy.count+ )+ )++ let promptBounds = Self.bounded(Self.promptText(turn: turn,events: events,@@ -149,6 +215,7 @@ public struct AppHarnessContextPacketBuilder: Sendable {),maxLength: limits.maxPromptCharacters)+ let promptText = promptBounds.textreturn AppHarnessContextPacket(traceID: traceID,@@ -161,10 +228,16 @@ public struct AppHarnessContextPacketBuilder: Sendable {policy: request.policy,promptText: promptText,redactionCount: redactionCount,+ compactionRecords: compactionRecords,metadata: ["bounds.maxRecentEvents": String(limits.maxRecentEvents),"bounds.maxAssets": String(limits.maxAssets),"bounds.maxPromptCharacters": String(limits.maxPromptCharacters),+ "compaction.recordCount": String(compactionRecords.count),+ "compaction.promptTruncated": String(promptBounds.wasTruncated),+ "events.originalCount": String(request.recentEvents.count),+ "events.droppedCount": String(eventCompaction.droppedCount),+ "events.droppedTransientCorrectionCount": String(eventCompaction.droppedTransientCorrectionCount),"events.includedCount": String(events.count),"assets.includedCount": String(assets.count),"memory.includedCount": String(memory.count),@@ -239,14 +312,125 @@ public struct AppHarnessContextPacketBuilder: Sendable {return (redacted, count)}- private static func truncated(_ text: String, maxLength: Int) -> String {- guard text.count > maxLength else { return text }+ private static func bounded(_ text: String, maxLength: Int) -> (text: String, wasTruncated: Bool) {+ guard text.count > maxLength else { return (text, false) }let endIndex = text.index(text.startIndex, offsetBy: maxLength)- return String(text[..<endIndex]).trimmingCharacters(in: .whitespacesAndNewlines) + "..."+ return (String(text[..<endIndex]).trimmingCharacters(in: .whitespacesAndNewlines) + "...", true)+ }++ private static func compactEvents(+ _ preparedEvents: [PreparedHarnessContextEvent],+ limit: Int+ ) -> HarnessEventCompactionResult {+ guard limit > 0 else {+ let transientCount = preparedEvents.filter(\.isTransientCorrection).count+ return HarnessEventCompactionResult(+ events: [],+ records: [+ AppHarnessContextCompactionRecord(+ itemKind: .recentEvent,+ originalCount: preparedEvents.count,+ includedCount: 0,+ droppedCount: preparedEvents.count,+ truncatedCount: 0+ ),+ AppHarnessContextCompactionRecord(+ itemKind: .transientCorrection,+ originalCount: transientCount,+ includedCount: 0,+ droppedCount: transientCount,+ truncatedCount: 0+ )+ ],+ droppedCount: preparedEvents.count,+ droppedTransientCorrectionCount: transientCount+ )+ }++ let selected: [PreparedHarnessContextEvent]+ if preparedEvents.count <= limit {+ selected = preparedEvents+ } else {+ let nonTransient = preparedEvents.filter { !$0.isTransientCorrection }+ var chosen = Array(nonTransient.suffix(limit))+ if chosen.count < limit {+ let chosenIDs = Set(chosen.map(\.sourceID))+ let fill = preparedEvents+ .filter { $0.isTransientCorrection && !chosenIDs.contains($0.sourceID) }+ .suffix(limit - chosen.count)+ chosen.append(contentsOf: fill)+ }+ selected = chosen.sorted { lhs, rhs in+ if lhs.event.sequence == rhs.event.sequence {+ return lhs.sourceID < rhs.sourceID+ }+ return lhs.event.sequence < rhs.event.sequence+ }+ }++ let selectedIDs = Set(selected.map(\.sourceID))+ let dropped = preparedEvents.filter { !selectedIDs.contains($0.sourceID) }+ let transientOriginal = preparedEvents.filter(\.isTransientCorrection).count+ let transientIncluded = selected.filter(\.isTransientCorrection).count+ let transientDropped = dropped.filter(\.isTransientCorrection).count+ let recentTruncated = selected.filter { !$0.isTransientCorrection && $0.wasTruncated }.count+ let transientTruncated = selected.filter { $0.isTransientCorrection && $0.wasTruncated }.count++ return HarnessEventCompactionResult(+ events: selected.map(\.event),+ records: [+ AppHarnessContextCompactionRecord(+ itemKind: .recentEvent,+ originalCount: preparedEvents.count,+ includedCount: selected.count,+ droppedCount: dropped.count,+ truncatedCount: recentTruncated,+ metadata: ["strategy": "dropTransientCorrectionsFirst"]+ ),+ AppHarnessContextCompactionRecord(+ itemKind: .transientCorrection,+ originalCount: transientOriginal,+ includedCount: transientIncluded,+ droppedCount: transientDropped,+ truncatedCount: transientTruncated,+ metadata: ["strategy": "dropBeforeDurableEvents"]+ )+ ],+ droppedCount: dropped.count,+ droppedTransientCorrectionCount: transientDropped+ )+ }++ private static func isTransientCorrection(_ event: PointerPromptTaskEvent) -> Bool {+ let normalized = LocalAppTaskIntentParser.normalizedPhrase(event.text)+ guard event.role == .assistant || event.role == .system else { return false }++ return normalized.contains("retry")+ || normalized.contains("try again")+ || normalized.contains("invalid format")+ || normalized.contains("invalid output")+ || normalized.contains("unknown tool")+ || normalized.contains("missing prerequisite")+ || normalized.contains("step nudge")+ || normalized.contains("retry nudge")}}+private struct PreparedHarnessContextEvent: Equatable, Sendable {+ var event: AppHarnessContextEvent+ var sourceID: String+ var isTransientCorrection: Bool+ var wasTruncated: Bool+}++private struct HarnessEventCompactionResult: Equatable, Sendable {+ var events: [AppHarnessContextEvent]+ var records: [AppHarnessContextCompactionRecord]+ var droppedCount: Int+ var droppedTransientCorrectionCount: Int+}+public struct AppHarnessTurnRouter: Sendable {public var catalog: LocalAppTaskCatalogpublic var contextBuilder: AppHarnessContextPacketBuilder@@ -272,7 +456,14 @@ public struct AppHarnessTurnRouter: Sendable {guard !trimmedText.isEmpty else {return AppHarnessRoutingResult(contextPacket: packet,- outcome: AppHarnessRoutingOutcome(kind: .noOp)+ outcome: AppHarnessRoutingOutcome(+ decision: AppHarnessDecision(+ kind: .noOp,+ traceID: traceID,+ metadata: ["router": "emptyTurn"]+ ),+ metadata: ["router": "emptyTurn"]+ ))}@@ -282,18 +473,31 @@ public struct AppHarnessTurnRouter: Sendable {return AppHarnessRoutingResult(contextPacket: packet,outcome: AppHarnessRoutingOutcome(- kind: .actionableIntent,+ decision: decision(+ kind: .runLocalTask,+ traceID: traceID,+ resolution: deterministicResolution,+ metadata: ["router": "deterministicCatalog"]+ ),resolution: deterministicResolution,metadata: ["router": "deterministicCatalog"]))case .needsConfirmation:let missingDetail = deterministicResolution.metadata["reason"] ?? "detail"+ let response = clarificationPrompt(for: missingDetail, resolution: deterministicResolution)return AppHarnessRoutingResult(contextPacket: packet,outcome: AppHarnessRoutingOutcome(- kind: .clarification,- assistantResponse: clarificationPrompt(for: missingDetail, resolution: deterministicResolution),+ decision: decision(+ kind: .askClarification,+ traceID: traceID,+ message: response,+ missingDetail: missingDetail,+ resolution: deterministicResolution,+ metadata: ["router": "deterministicCatalog"]+ ),+ assistantResponse: response,missingDetail: missingDetail,resolution: deterministicResolution,metadata: ["router": "deterministicCatalog"]@@ -303,7 +507,12 @@ public struct AppHarnessTurnRouter: Sendable {return AppHarnessRoutingResult(contextPacket: packet,outcome: AppHarnessRoutingOutcome(- kind: .actionableIntent,+ decision: decision(+ kind: .runLocalTask,+ traceID: traceID,+ resolution: deterministicResolution,+ metadata: ["router": "deterministicCatalog"]+ ),resolution: deterministicResolution,metadata: ["router": "deterministicCatalog"])@@ -316,7 +525,12 @@ public struct AppHarnessTurnRouter: Sendable {return AppHarnessRoutingResult(contextPacket: packet,outcome: AppHarnessRoutingOutcome(- kind: .actionableIntent,+ decision: decision(+ kind: .runLocalTask,+ traceID: traceID,+ resolution: deterministicResolution,+ metadata: ["router": "followUpActionContext"]+ ),resolution: deterministicResolution,metadata: ["router": "followUpActionContext"])@@ -324,21 +538,35 @@ public struct AppHarnessTurnRouter: Sendable {}if Self.isConversational(trimmedText) {+ let response = conversationResponse(for: trimmedText)return AppHarnessRoutingResult(contextPacket: packet,outcome: AppHarnessRoutingOutcome(- kind: .conversation,- assistantResponse: conversationResponse(for: trimmedText),+ decision: decision(+ kind: .respond,+ traceID: traceID,+ message: response,+ metadata: ["router": "conversationRules"]+ ),+ assistantResponse: response,metadata: ["router": "conversationRules"]))}+ let response = "What would you like Donkey to do?"return AppHarnessRoutingResult(contextPacket: packet,outcome: AppHarnessRoutingOutcome(- kind: .clarification,- assistantResponse: "What would you like Donkey to do?",+ decision: decision(+ kind: .askClarification,+ traceID: traceID,+ message: response,+ missingDetail: "actionable request",+ resolution: deterministicResolution,+ metadata: ["router": "unsupportedClarification"]+ ),+ assistantResponse: response,missingDetail: "actionable request",resolution: deterministicResolution,metadata: ["router": "unsupportedClarification"]@@ -346,6 +574,27 @@ public struct AppHarnessTurnRouter: Sendable {)}+ private func decision(+ kind: AppHarnessDecisionKind,+ traceID: String,+ message: String? = nil,+ missingDetail: String? = nil,+ resolution: LocalAppTaskCatalogResolution? = nil,+ metadata: [String: String] = [:]+ ) -> AppHarnessDecision {+ AppHarnessDecision(+ kind: kind,+ message: message,+ missingDetail: missingDetail,+ taskIntentID: resolution?.intent?.intentID,+ traceID: traceID,+ metadata: metadata.merging([+ "structuredDecision": "true",+ "resolution.status": resolution?.status.rawValue ?? "none"+ ]) { current, _ in current }+ )+ }+private func conversationResponse(for text: String) -> String {let normalized = LocalAppTaskIntentParser.normalizedPhrase(text)if normalized.contains("what can") || normalized.contains("help") || normalized.contains("capabil") {diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swiftindex 43eaa6a3..5662396f 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift@@ -22,6 +22,7 @@ public struct LocalAppTaskLiveRunResult: Equatable, Sendable {public var observation: LocalAppTaskObservation?public var documentFormFillPlan: DocumentFormFillPlan?public var actionTraces: [ActionEngineCommandTrace]+ public var workflowProgress: LocalAppTaskWorkflowProgresspublic var metadata: [String: String]public init(@@ -34,6 +35,7 @@ public struct LocalAppTaskLiveRunResult: Equatable, Sendable {observation: LocalAppTaskObservation? = nil,documentFormFillPlan: DocumentFormFillPlan? = nil,actionTraces: [ActionEngineCommandTrace] = [],+ workflowProgress: LocalAppTaskWorkflowProgress = LocalAppTaskWorkflowProgress(),metadata: [String: String] = [:]) {self.command = command@@ -45,6 +47,7 @@ public struct LocalAppTaskLiveRunResult: Equatable, Sendable {self.observation = observationself.documentFormFillPlan = documentFormFillPlanself.actionTraces = actionTraces+ self.workflowProgress = workflowProgressself.metadata = metadata}}@@ -112,26 +115,54 @@ public struct LocalAppTaskLiveRunner: Sendable {) async -> LocalAppTaskLiveRunResult {let runStartedAt = Self.uptimeMilliseconds()var runMetadata = metadata+ var stepTracker = LocalAppTaskStepTracker(metadata: ["traceID": traceID])+ stepTracker.complete(+ .parseIntent,+ summary: "Task intent parsed or supplied",+ metadata: ["parser": metadata["intentParser"] ?? resolution.intent?.parserSource.rawValue ?? "external"]+ )guard resolution.status == .resolved else {+ stepTracker.block(+ .resolveApp,+ summary: "Local app task could not be resolved",+ metadata: ["resolution.status": resolution.status.rawValue]+ )await publishUnresolvedRun(command: command,traceID: traceID,resolution: resolution)+ let progress = stepTracker.snapshot()return unresolvedResult(command: command,traceID: traceID,resolution: resolution,+ workflowProgress: progress,metadata: metadata.merging(["latency.totalMS": Self.formatLatency(Self.uptimeMilliseconds() - runStartedAt)- ]) { current, _ in current }+ ], uniquingKeysWith: { current, _ in current }).merging(+ Self.workflowProgressMetadata(progress),+ uniquingKeysWith: { current, _ in current }+ ))}+ stepTracker.start(+ .resolveApp,+ summary: "Resolving task definition and target app",+ metadata: ["resolution.status": resolution.status.rawValue]+ )+guard let definition = resolution.definition,var intent = resolution.intent,let availability = resolution.availabilityelse {+ stepTracker.fail(+ .resolveApp,+ summary: "Local app task resolution was incomplete",+ metadata: ["reason": "incompleteResolution"]+ )+ let progress = stepTracker.snapshot()await publishRunStart(command: command,traceID: traceID,@@ -151,13 +182,26 @@ public struct LocalAppTaskLiveRunner: Sendable {traceID: traceID,status: .failedSafe,resolution: resolution,+ workflowProgress: progress,metadata: runMetadata.merging(["reason": "incompleteResolution","latency.totalMS": Self.formatLatency(Self.uptimeMilliseconds() - runStartedAt)- ]) { current, _ in current }+ ], uniquingKeysWith: { current, _ in current }).merging(+ Self.workflowProgressMetadata(progress),+ uniquingKeysWith: { current, _ in current }+ ))}+ stepTracker.complete(+ .resolveApp,+ summary: "Resolved task definition and target app",+ metadata: [+ "taskType": definition.taskType,+ "targetApp": definition.targetApp.appName+ ]+ )+intent.metadata["traceID"] = traceIDlet adapter = catalog.adapter(for: definition)await publishRunStart(@@ -167,6 +211,7 @@ public struct LocalAppTaskLiveRunner: Sendable {)if definition.metadata["guardedLiveDefault"] == "reviewOnly" {let contextStartedAt = Self.uptimeMilliseconds()+ stepTracker.start(.observe, summary: "Capturing local app task context")await coordinator?.recordToolEvent(capability: .capture,decision: permissionPolicy.decision(for: .capture),@@ -178,6 +223,12 @@ public struct LocalAppTaskLiveRunner: Sendable {runMetadata["latency.observationMS"] = Self.formatLatency(Self.uptimeMilliseconds() - contextStartedAt)+ stepTracker.complete(+ .observe,+ summary: "Captured local app task context",+ metadata: ["observer": "local-app-task-context"]+ )+ stepTracker.start(.dryRun, summary: "Planning review-first document form fill")let documentPlan = documentFormFillPlanner.plan(intent: intent,definition: definition,@@ -199,6 +250,22 @@ public struct LocalAppTaskLiveRunner: Sendable {])let initialPlan = adapter.dryRunPlan(for: intent, observation: observation)+ stepTracker.complete(+ .dryRun,+ summary: "Built review-first document form-fill plan",+ metadata: ["terminalState": initialPlan.terminalState.rawValue]+ )+ stepTracker.wait(+ .approval,+ summary: "Waiting for user review before Accessibility execution",+ metadata: [+ "documentFormFillPlan.status": documentPlan.status.rawValue,+ "proposalCount": String(documentPlan.proposals.count)+ ]+ )+ stepTracker.skip(.execute, summary: "Execution waits for user approval")+ stepTracker.skip(.verify, summary: "Verification waits for approved execution")+ let progress = stepTracker.snapshot()await coordinator?.complete(reason: "Local app task requires document review")return LocalAppTaskLiveRunResult(command: command,@@ -209,17 +276,22 @@ public struct LocalAppTaskLiveRunner: Sendable {finalPlan: initialPlan,observation: observation,documentFormFillPlan: documentPlan,+ workflowProgress: progress,metadata: runMetadata.merging(["reason": "reviewOnlyTask","documentFormFillPlan.status": documentPlan.status.rawValue,"documentFormFillPlan.proposalCount": String(documentPlan.proposals.count),"latency.totalMS": Self.formatLatency(Self.uptimeMilliseconds() - runStartedAt)- ]) { current, _ in current }+ ], uniquingKeysWith: { current, _ in current }).merging(+ Self.workflowProgressMetadata(progress),+ uniquingKeysWith: { current, _ in current }+ ))}await coordinator?.waitIfPaused()let launchStartedAt = Self.uptimeMilliseconds()+ stepTracker.start(.observe, summary: "Launching or focusing target app for observation")await coordinator?.recordToolEvent(capability: .input,decision: permissionPolicy.decision(for: .input),@@ -236,8 +308,26 @@ public struct LocalAppTaskLiveRunner: Sendable {availability: availability)runMetadata["latency.launchFocusMS"] = Self.formatLatency(Self.uptimeMilliseconds() - launchStartedAt)+ stepTracker.complete(+ .observe,+ summary: "Observed target app after launch or focus",+ metadata: [+ "appIsRunning": String(launchObservation.appIsRunning),+ "appIsFocused": String(launchObservation.appIsFocused)+ ]+ )+ stepTracker.start(.dryRun, summary: "Projecting guarded local-app workflow")let initialPlan = adapter.dryRunPlan(for: intent, observation: launchObservation)guard initialPlan.canAttemptGuardedLive else {+ stepTracker.block(+ .dryRun,+ summary: "Dry-run plan blocked live input",+ metadata: ["terminalState": initialPlan.terminalState.rawValue]+ )+ stepTracker.skip(.approval, summary: "No approval requested for blocked dry run")+ stepTracker.skip(.execute, summary: "Execution skipped because dry run blocked")+ stepTracker.skip(.verify, summary: "Verification skipped because dry run blocked")+ let progress = stepTracker.snapshot()await coordinator?.pause(reason: "Local app task dry-run plan blocked live input")return LocalAppTaskLiveRunResult(command: command,@@ -246,12 +336,22 @@ public struct LocalAppTaskLiveRunner: Sendable {resolution: resolution,initialPlan: initialPlan,observation: launchObservation,+ workflowProgress: progress,metadata: runMetadata.merging(["reason": "dryRunPlanBlocked","latency.totalMS": Self.formatLatency(Self.uptimeMilliseconds() - runStartedAt)- ]) { current, _ in current }+ ], uniquingKeysWith: { current, _ in current }).merging(+ Self.workflowProgressMetadata(progress),+ uniquingKeysWith: { current, _ in current }+ ))}+ stepTracker.complete(+ .dryRun,+ summary: "Dry-run plan allows guarded live execution",+ metadata: ["terminalState": initialPlan.terminalState.rawValue]+ )+ stepTracker.skip(.approval, summary: "No review gate required for this local-app task")var actionTraces: [ActionEngineCommandTrace] = []var accessibilityActionMS = 0.0@@ -304,6 +404,7 @@ public struct LocalAppTaskLiveRunner: Sendable {}var keyboardActionMS = 0.0+ stepTracker.start(.execute, summary: "Executing guarded local-app actions")for (index, actionCommand) in commands.enumerated() {await coordinator?.waitIfPaused()let spacedCommand = actionCommand.withIssuedAt(Self.now(advancedByMilliseconds: Double(index) * 40))@@ -339,6 +440,14 @@ public struct LocalAppTaskLiveRunner: Sendable {}guard trace.executed || trace.decision == ActionEngineCommandDecision.projectedDryRun else {+ stepTracker.fail(+ .execute,+ summary: "Guarded local-app action was denied",+ metadata: [+ "actionDeniedReason": decisionReason(trace.decision),+ "commandID": trace.command.id+ ]+ )let observationStartedAt = Self.uptimeMilliseconds()await coordinator?.recordToolEvent(capability: .perception,@@ -357,6 +466,7 @@ public struct LocalAppTaskLiveRunner: Sendable {Self.uptimeMilliseconds() - verificationStartedAt)await coordinator?.fail(reason: "Local app task action was denied")+ let progress = stepTracker.snapshot()return LocalAppTaskLiveRunResult(command: command,traceID: traceID,@@ -366,6 +476,7 @@ public struct LocalAppTaskLiveRunner: Sendable {finalPlan: finalPlan,observation: finalObservation,actionTraces: actionTraces,+ workflowProgress: progress,metadata: runMetadata.merging(["reason": "actionDenied","actionDeniedReason": decisionReason(trace.decision),@@ -373,16 +484,28 @@ public struct LocalAppTaskLiveRunner: Sendable {"actionDeniedFocusGuardPassed": String(trace.focusGuardPassed),"latency.keyboardActionMS": Self.formatLatency(keyboardActionMS),"latency.totalMS": Self.formatLatency(Self.uptimeMilliseconds() - runStartedAt)- ]) { current, _ in current }+ ], uniquingKeysWith: { current, _ in current }).merging(+ Self.workflowProgressMetadata(progress),+ uniquingKeysWith: { current, _ in current }+ ))}}runMetadata["latency.keyboardActionMS"] = Self.formatLatency(keyboardActionMS)+ stepTracker.complete(+ .execute,+ summary: "Guarded local-app actions completed",+ metadata: [+ "executedCommandCount": String(actionTraces.filter(\.executed).count),+ "projectedCommandCount": String(actionTraces.filter { $0.decision == .projectedDryRun }.count)+ ]+ )await coordinator?.waitIfPaused()try? await Task.sleep(nanoseconds: 700_000_000)await coordinator?.waitIfPaused()let observationStartedAt = Self.uptimeMilliseconds()+ stepTracker.start(.verify, summary: "Observing target app for result verification")await coordinator?.recordToolEvent(capability: .perception,decision: permissionPolicy.decision(for: .perception),@@ -405,10 +528,21 @@ public struct LocalAppTaskLiveRunner: Sendable {}let status = status(for: finalPlan.terminalState)if status == .completed {+ stepTracker.complete(+ .verify,+ summary: "Local app task result verified",+ metadata: ["terminalState": finalPlan.terminalState.rawValue]+ )await coordinator?.complete(reason: "Local app task completed")} else {+ stepTracker.block(+ .verify,+ summary: "Local app task needs user review after verification",+ metadata: ["terminalState": finalPlan.terminalState.rawValue]+ )await coordinator?.pause(reason: "Local app task needs user review")}+ let progress = stepTracker.snapshot()return LocalAppTaskLiveRunResult(command: command,traceID: traceID,@@ -418,10 +552,14 @@ public struct LocalAppTaskLiveRunner: Sendable {finalPlan: finalPlan,observation: finalObservation,actionTraces: actionTraces,+ workflowProgress: progress,metadata: runMetadata.merging(["executedCommandCount": String(actionTraces.filter(\.executed).count),"projectedCommandCount": String(actionTraces.filter { $0.decision == .projectedDryRun }.count)- ]) { current, _ in current }+ ], uniquingKeysWith: { current, _ in current }).merging(+ Self.workflowProgressMetadata(progress),+ uniquingKeysWith: { current, _ in current }+ ))}@@ -451,6 +589,7 @@ public struct LocalAppTaskLiveRunner: Sendable {command: String,traceID: String,resolution: LocalAppTaskCatalogResolution,+ workflowProgress: LocalAppTaskWorkflowProgress,metadata: [String: String]) -> LocalAppTaskLiveRunResult {let status: LocalAppTaskLiveRunStatus@@ -470,6 +609,7 @@ public struct LocalAppTaskLiveRunner: Sendable {traceID: traceID,status: status,resolution: resolution,+ workflowProgress: workflowProgress,metadata: metadata)}@@ -606,6 +746,16 @@ public struct LocalAppTaskLiveRunner: Sendable {private static func formatLatency(_ milliseconds: Double) -> String {String(format: "%.3f", max(0, milliseconds))}++ private static func workflowProgressMetadata(+ _ progress: LocalAppTaskWorkflowProgress+ ) -> [String: String] {+ Dictionary(+ uniqueKeysWithValues: progress.stages.map { state in+ ("workflow.\(state.stage.rawValue).status", state.status.rawValue)+ }+ )+ }}public struct MacLocalAppFocusGuard: ActionEngineFocusGuard {diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskStepTracker.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskStepTracker.swiftnew file mode 100644index 00000000..032de3bc--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskStepTracker.swift@@ -0,0 +1,114 @@+import DonkeyContracts+import Foundation++public struct LocalAppTaskStepTracker: Sendable {+ private var states: [LocalAppTaskWorkflowStage: LocalAppTaskWorkflowStageState]+ private var metadata: [String: String]++ public init(metadata: [String: String] = [:]) {+ self.metadata = metadata+ self.states = Dictionary(+ uniqueKeysWithValues: LocalAppTaskWorkflowStage.allCases.map { stage in+ (+ stage,+ LocalAppTaskWorkflowStageState(+ stage: stage,+ status: .pending,+ summary: Self.defaultSummary(for: stage)+ )+ )+ }+ )+ }++ public mutating func start(+ _ stage: LocalAppTaskWorkflowStage,+ summary: String? = nil,+ metadata: [String: String] = [:]+ ) {+ update(stage, status: .started, summary: summary, metadata: metadata)+ }++ public mutating func complete(+ _ stage: LocalAppTaskWorkflowStage,+ summary: String? = nil,+ metadata: [String: String] = [:]+ ) {+ update(stage, status: .completed, summary: summary, metadata: metadata)+ }++ public mutating func wait(+ _ stage: LocalAppTaskWorkflowStage,+ summary: String? = nil,+ metadata: [String: String] = [:]+ ) {+ update(stage, status: .waiting, summary: summary, metadata: metadata)+ }++ public mutating func skip(+ _ stage: LocalAppTaskWorkflowStage,+ summary: String? = nil,+ metadata: [String: String] = [:]+ ) {+ update(stage, status: .skipped, summary: summary, metadata: metadata)+ }++ public mutating func block(+ _ stage: LocalAppTaskWorkflowStage,+ summary: String? = nil,+ metadata: [String: String] = [:]+ ) {+ update(stage, status: .blocked, summary: summary, metadata: metadata)+ }++ public mutating func fail(+ _ stage: LocalAppTaskWorkflowStage,+ summary: String? = nil,+ metadata: [String: String] = [:]+ ) {+ update(stage, status: .failed, summary: summary, metadata: metadata)+ }++ public mutating func mergeMetadata(_ values: [String: String]) {+ metadata.merge(values) { current, _ in current }+ }++ public func snapshot(metadata extraMetadata: [String: String] = [:]) -> LocalAppTaskWorkflowProgress {+ LocalAppTaskWorkflowProgress(+ stages: LocalAppTaskWorkflowStage.allCases.compactMap { states[$0] },+ metadata: metadata.merging(extraMetadata) { current, _ in current }+ )+ }++ private mutating func update(+ _ stage: LocalAppTaskWorkflowStage,+ status: LocalAppTaskWorkflowStageStatus,+ summary: String?,+ metadata newMetadata: [String: String]+ ) {+ var state = states[stage] ?? LocalAppTaskWorkflowStageState(stage: stage)+ state.status = status+ state.summary = summary ?? state.summary+ state.metadata.merge(newMetadata) { current, _ in current }+ states[stage] = state+ }++ private static func defaultSummary(for stage: LocalAppTaskWorkflowStage) -> String {+ switch stage {+ case .parseIntent:+ return "Parse task intent"+ case .resolveApp:+ return "Resolve task and target app"+ case .observe:+ return "Observe target app state"+ case .dryRun:+ return "Project guarded workflow"+ case .approval:+ return "Check user review or approval boundary"+ case .execute:+ return "Execute guarded local-app actions"+ case .verify:+ return "Verify local-app task result"+ }+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swiftindex eadbc70d..ca960dc5 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift@@ -86,6 +86,46 @@ struct AIHarnessAdapterTests {#expect(selected.timeoutMS == 4_000)}+ @Test+ func localModelPriorityWorkerPreemptsLowerPriorityWorkCooperatively() async throws {+ let worker = LocalModelPriorityWorker()+ let recorder = LocalModelPriorityWorkerRecorder()++ let lowPriority = Task {+ await worker.submit(kind: .plannerHint, priority: .replay) { context in+ await recorder.append("low-start")+ while !(await context.isCancelled()) {+ try? await Task.sleep(nanoseconds: 5_000_000)+ }+ await recorder.append("low-cancelled")+ return "low"+ }+ }++ for _ in 0..<100 where !(await recorder.events().contains("low-start")) {+ try await Task.sleep(nanoseconds: 1_000_000)+ }+ #expect(await recorder.events().contains("low-start"))++ let highPriority = Task {+ await worker.submit(kind: .taskIntent, priority: .userInteractive) {+ await recorder.append("high-run")+ return "high"+ }+ }++ let highResult = await highPriority.value+ let lowResult = await lowPriority.value+ let events = await recorder.events()+ let snapshot = await worker.snapshot()++ #expect(highResult == "high")+ #expect(lowResult == "low")+ #expect(events == ["low-start", "low-cancelled", "high-run"])+ #expect(snapshot.currentWorkID == nil)+ #expect(snapshot.queuedCount == 0)+ }+@Testfunc voiceTranscriptionRouteSelectsLocalParakeetModel() throws {let router = AIModelRouter(registry: .defaultHybridPlanner)@@ -1119,6 +1159,18 @@ private struct UnavailableTaskIntentAdapter: TaskIntentParsingAdapter {}}+private actor LocalModelPriorityWorkerRecorder {+ private var values: [String] = []++ func append(_ value: String) {+ values.append(value)+ }++ func events() -> [String] {+ values+ }+}+private final class FakeAIHTTPClient: AIHTTPClient, @unchecked Sendable {var data: Datavar statusCode: Intdiff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AppHarnessTurnRouterTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AppHarnessTurnRouterTests.swiftindex 0f43807f..d51c7256 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/AppHarnessTurnRouterTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AppHarnessTurnRouterTests.swift@@ -13,7 +13,8 @@ struct AppHarnessTurnRouterTests {traceID: "trace-chat")- #expect(result.outcome.kind == .conversation)+ #expect(result.outcome.decision.kind == .respond)+ #expect(result.outcome.decision.traceID == "trace-chat")#expect(result.outcome.resolution == nil)#expect(result.outcome.assistantResponse?.contains("local app task") == true)}@@ -27,7 +28,8 @@ struct AppHarnessTurnRouterTests {traceID: "trace-action")- #expect(result.outcome.kind == .actionableIntent)+ #expect(result.outcome.decision.kind == .runLocalTask)+ #expect(result.outcome.decision.taskIntentID == result.outcome.resolution?.intent?.intentID)#expect(result.outcome.resolution?.status == .resolved)#expect(result.outcome.resolution?.intent?.normalizedEntities["city"] == "San Francisco")}@@ -42,7 +44,7 @@ struct AppHarnessTurnRouterTests {)#expect(result.contextPacket.currentTurn.source == .voiceTranscript)- #expect(result.outcome.kind == .actionableIntent)+ #expect(result.outcome.decision.kind == .runLocalTask)#expect(result.outcome.resolution?.status == .resolved)#expect(result.outcome.resolution?.intent?.normalizedEntities["city"] == "San Francisco")}@@ -56,7 +58,8 @@ struct AppHarnessTurnRouterTests {traceID: "trace-clarify")- #expect(result.outcome.kind == .clarification)+ #expect(result.outcome.decision.kind == .askClarification)+ #expect(result.outcome.decision.missingDetail == "city")#expect(result.outcome.missingDetail == "city")#expect(result.outcome.assistantResponse == "Which city should I use?")}@@ -132,6 +135,53 @@ struct AppHarnessTurnRouterTests {#expect(result.contextPacket.promptText.contains("[redacted-email]"))#expect(result.contextPacket.promptText.contains("[redacted-secret]"))#expect(result.contextPacket.redactionCount == 3)+ #expect(result.contextPacket.compactionRecords.contains {+ $0.itemKind == .recentEvent && $0.originalCount == 3 && $0.includedCount == 2+ })+ }++ @Test+ func contextCompactionDropsTransientCorrectionsBeforeDurableEvents() {+ let limits = AppHarnessContextPacketLimits(+ maxRecentEvents: 2,+ maxAssets: 0,+ maxPromptCharacters: 600+ )+ let result = router(limits: limits).route(+ request: AppHarnessTurnRequest(+ turn: AppHarnessTurn(text: "thanks", source: .typedPrompt),+ recentEvents: [+ PointerPromptTaskEvent(+ id: "event-1",+ taskID: "task-1",+ role: .assistant,+ text: "Retry nudge: invalid output, try again.",+ sequence: 1+ ),+ PointerPromptTaskEvent(+ id: "event-2",+ taskID: "task-1",+ role: .user,+ text: "show me the weather for SF",+ sequence: 2+ ),+ PointerPromptTaskEvent(+ id: "event-3",+ taskID: "task-1",+ role: .assistant,+ text: "Opening Weather for San Francisco.",+ sequence: 3+ )+ ]+ ),+ traceID: "trace-typed-compaction"+ )++ #expect(result.contextPacket.recentEvents.map(\.sequence) == [2, 3])+ #expect(result.contextPacket.metadata["events.droppedTransientCorrectionCount"] == "1")+ #expect(result.contextPacket.compactionRecords.contains {+ $0.itemKind == .transientCorrection && $0.droppedCount == 1+ })}private func router(diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swiftindex 85a86f9a..30bdc977 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift@@ -383,6 +383,8 @@ struct LocalAppTaskTests {#expect(result.documentFormFillPlan?.status == .readyForReview)#expect(result.documentFormFillPlan?.proposals.first?.proposedValue == "Grace Hopper")#expect(result.metadata["reason"] == "reviewOnlyTask")+ #expect(result.workflowProgress.state(for: .approval)?.status == .waiting)+ #expect(result.workflowProgress.state(for: .execute)?.status == .skipped)}@Test @MainActor@@ -428,6 +430,13 @@ struct LocalAppTaskTests {#expect(await backend.executedKeys() == ["Command+F", "San Francisco", "Return", "Return"])#expect(controller.launchCount == 1)#expect(controller.observeCount == 1)+ #expect(result.workflowProgress.state(for: .parseIntent)?.status == .completed)+ #expect(result.workflowProgress.state(for: .resolveApp)?.status == .completed)+ #expect(result.workflowProgress.state(for: .dryRun)?.status == .completed)+ #expect(result.workflowProgress.state(for: .approval)?.status == .skipped)+ #expect(result.workflowProgress.state(for: .execute)?.status == .completed)+ #expect(result.workflowProgress.state(for: .verify)?.status == .completed)+ #expect(result.metadata["workflow.verify.status"] == "completed")}@Test @MainActordiff --git a/docs/guides/agent-harness.md b/docs/guides/agent-harness.mdindex f2baa325..608519b3 100644--- a/docs/guides/agent-harness.md+++ b/docs/guides/agent-harness.md@@ -47,6 +47,12 @@ inside the thread. The user should not need to know whether a turn was answeredby a chat response, a local model classifier, deterministic parsing, or aguarded runtime path.+Routing outcomes carry a structured `AppHarnessDecision`. The decision names the+next supported harness action:+respond, ask for clarification, open review, run a local task, or no-op. This+keeps model-assisted routing in a typed decision space instead of treating free+text as an implicit action signal.+## Context EngineeringThe harness builds context deliberately for each job. It should never dump raw,@@ -67,6 +73,12 @@ can include richer app and observation facts, but should still stay bounded andinspectable. Memory retrieval should use target/scope filters, relevancethresholds, and prompt-character budgets before summaries are added.+Context compaction is typed and inspectable. Current turns, policy, active+target state, runtime capabilities, and trace identifiers are preserved first.+Transient retry/correction events are dropped before durable thread events,+and packet metadata records what was included, dropped, or truncated by item+kind.+## Routing OutcomesConversation is a first-class outcome. Greetings, "what can you do?", small@@ -104,6 +116,11 @@ runtime safety model. Local-app work flows through typed contracts, catalogresolution, observation, dry-run projection, guardrails, and verification beforeor during live control.+Local-app workflow progress is tracked outside prompt/context text. Each run+records typed stage state for intent parsing, task/app resolution, observation,+dry-run projection, approval/review, guarded execution, and verification. The+model can be told about this state, but the runner owns it.+Live input remains guarded. The action engine checks permission policy, targetfocus, rate limits, hold duration, and backend evidence before issuing input.The macOS keyboard and Accessibility backends are intentionally narrow. They@@ -120,6 +137,10 @@ summarize UI observations. Provider-backed planners and memory proposals remainslow-path helpers and must fail without stopping local control on existingvalidated state.+Local model work that shares the same runtime capacity should enter a priority+worker. Interactive task-intent parsing runs at user-interactive priority and+can cooperatively preempt lower-priority planner, memory, or replay jobs.+## State And ObservabilityTask-thread state and action-run state are related but distinct. A thread can bediff --git a/plans/master-plan.md b/plans/master-plan.mdindex 43c36ba2..76c0a3bf 100644--- a/plans/master-plan.md+++ b/plans/master-plan.md@@ -30,3 +30,6 @@ No active implementation tasks.- Runtime, input, and latency claims should be tied to verifiable local traces.- Task threads are conversations first; action execution is a routed outcome ofthe agent harness, not the default meaning of every prompt turn.+- Harness routing decisions, context compaction, local-app workflow progress,+ and shared local-model work scheduling are typed runtime state, not implicit+ prompt text.