Skip to content

Open source CapCut alternative.

TypeScript

Add memory, replay eval, and local navigation dry-run

David Le201e76ccf5dd
diff --git a/apps/Donkey/Sources/DonkeyAI/AIReplayEvaluation.swift b/apps/Donkey/Sources/DonkeyAI/AIReplayEvaluation.swift
new file mode 100644
index 00000000..8a3b4153
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyAI/AIReplayEvaluation.swift
@@ -0,0 +1,188 @@
+import DonkeyContracts
+import Foundation
+
+public struct PlannerHintReplayCase: Codable, Equatable, Sendable {
+ public var id: String
+ public var trace: ReflexTraceRecord
+ public var hint: StructuredPlannerHint?
+ public var validationIssues: [PlannerHintValidationIssue]
+ public var modelTrace: AIModelCallTrace?
+ public var memoryDecisions: [RunMemoryWriteDecision]
+ public var fallbackCount: Int
+ public var recoverySucceeded: Bool
+ public var estimatedCostUSD: Double
+
+ public init(
+ id: String,
+ trace: ReflexTraceRecord,
+ hint: StructuredPlannerHint?,
+ validationIssues: [PlannerHintValidationIssue],
+ modelTrace: AIModelCallTrace? = nil,
+ memoryDecisions: [RunMemoryWriteDecision] = [],
+ fallbackCount: Int = 0,
+ recoverySucceeded: Bool = false,
+ estimatedCostUSD: Double = 0
+ ) {
+ self.id = id
+ self.trace = trace
+ self.hint = hint
+ self.validationIssues = validationIssues
+ self.modelTrace = modelTrace
+ self.memoryDecisions = memoryDecisions
+ self.fallbackCount = fallbackCount
+ self.recoverySucceeded = recoverySucceeded
+ self.estimatedCostUSD = estimatedCostUSD
+ }
+}
+
+public struct AIReplayEvalMetrics: Codable, Equatable, Sendable {
+ public var caseCount: Int
+ public var schemaValidCount: Int
+ public var hintAcceptedCount: Int
+ public var memoryWriteAcceptedCount: Int
+ public var memoryWriteRejectedCount: Int
+ public var fallbackCount: Int
+ public var recoverySuccessCount: Int
+ public var totalEstimatedCostUSD: Double
+ public var averageModelLatencyMS: Double?
+ public var p95ModelLatencyMS: Double?
+
+ public init(
+ caseCount: Int,
+ schemaValidCount: Int,
+ hintAcceptedCount: Int,
+ memoryWriteAcceptedCount: Int,
+ memoryWriteRejectedCount: Int,
+ fallbackCount: Int,
+ recoverySuccessCount: Int,
+ totalEstimatedCostUSD: Double,
+ averageModelLatencyMS: Double?,
+ p95ModelLatencyMS: Double?
+ ) {
+ self.caseCount = caseCount
+ self.schemaValidCount = schemaValidCount
+ self.hintAcceptedCount = hintAcceptedCount
+ self.memoryWriteAcceptedCount = memoryWriteAcceptedCount
+ self.memoryWriteRejectedCount = memoryWriteRejectedCount
+ self.fallbackCount = fallbackCount
+ self.recoverySuccessCount = recoverySuccessCount
+ self.totalEstimatedCostUSD = totalEstimatedCostUSD
+ self.averageModelLatencyMS = averageModelLatencyMS
+ self.p95ModelLatencyMS = p95ModelLatencyMS
+ }
+}
+
+public struct AIReplayEvalReport: Codable, Equatable, Sendable {
+ public var suiteID: String
+ public var promptVersion: String
+ public var modelEntryID: String
+ public var generatedAt: RunTraceTimestamp
+ public var metrics: AIReplayEvalMetrics
+ public var caseIDs: [String]
+
+ public init(
+ suiteID: String,
+ promptVersion: String,
+ modelEntryID: String,
+ generatedAt: RunTraceTimestamp,
+ metrics: AIReplayEvalMetrics,
+ caseIDs: [String]
+ ) {
+ self.suiteID = suiteID
+ self.promptVersion = promptVersion
+ self.modelEntryID = modelEntryID
+ self.generatedAt = generatedAt
+ self.metrics = metrics
+ self.caseIDs = caseIDs
+ }
+}
+
+public struct AIModelUpdateChecklist: Codable, Equatable, Sendable {
+ public var modelEntryID: String
+ public var promptVersion: String
+ public var lastVerifiedAt: Date
+ public var docsURLs: [URL]
+ public var evalSuiteID: String
+ public var rollbackModelID: String
+ public var evalReportID: String?
+ public var notes: [String]
+
+ public init(
+ modelEntryID: String,
+ promptVersion: String,
+ lastVerifiedAt: Date,
+ docsURLs: [URL],
+ evalSuiteID: String,
+ rollbackModelID: String,
+ evalReportID: String? = nil,
+ notes: [String] = []
+ ) {
+ self.modelEntryID = modelEntryID
+ self.promptVersion = promptVersion
+ self.lastVerifiedAt = lastVerifiedAt
+ self.docsURLs = docsURLs
+ self.evalSuiteID = evalSuiteID
+ self.rollbackModelID = rollbackModelID
+ self.evalReportID = evalReportID
+ self.notes = notes
+ }
+
+ enum CodingKeys: String, CodingKey {
+ case modelEntryID = "model_entry_id"
+ case promptVersion = "prompt_version"
+ case lastVerifiedAt = "last_verified_at"
+ case docsURLs = "docs_urls"
+ case evalSuiteID = "eval_suite_id"
+ case rollbackModelID = "rollback_model_id"
+ case evalReportID = "eval_report_id"
+ case notes
+ }
+}
+
+public enum PlannerHintReplayEvaluator {
+ public static func evaluate(
+ suiteID: String,
+ promptVersion: String,
+ modelEntryID: String,
+ cases: [PlannerHintReplayCase],
+ generatedAt: RunTraceTimestamp
+ ) -> AIReplayEvalReport {
+ let latencies = cases.compactMap { $0.modelTrace?.latencyMS }.sorted()
+ let acceptedMemoryWrites = cases.flatMap(\.memoryDecisions).filter(\.approval.approved).count
+ let rejectedMemoryWrites = cases.flatMap(\.memoryDecisions).filter { !$0.approval.approved }.count
+
+ let metrics = AIReplayEvalMetrics(
+ caseCount: cases.count,
+ schemaValidCount: cases.filter { $0.hint != nil }.count,
+ hintAcceptedCount: cases.filter { $0.hint != nil && $0.validationIssues.isEmpty }.count,
+ memoryWriteAcceptedCount: acceptedMemoryWrites,
+ memoryWriteRejectedCount: rejectedMemoryWrites,
+ fallbackCount: cases.reduce(0) { $0 + $1.fallbackCount },
+ recoverySuccessCount: cases.filter(\.recoverySucceeded).count,
+ totalEstimatedCostUSD: cases.reduce(0) { $0 + $1.estimatedCostUSD },
+ averageModelLatencyMS: average(latencies),
+ p95ModelLatencyMS: percentile(latencies, percentile: 0.95)
+ )
+
+ return AIReplayEvalReport(
+ suiteID: suiteID,
+ promptVersion: promptVersion,
+ modelEntryID: modelEntryID,
+ generatedAt: generatedAt,
+ metrics: metrics,
+ caseIDs: cases.map(\.id)
+ )
+ }
+
+ private static func average(_ values: [Double]) -> Double? {
+ guard !values.isEmpty else { return nil }
+ return values.reduce(0, +) / Double(values.count)
+ }
+
+ private static func percentile(_ sortedValues: [Double], percentile: Double) -> Double? {
+ guard !sortedValues.isEmpty else { return nil }
+ let clamped = max(0, min(1, percentile))
+ let index = Int((Double(sortedValues.count - 1) * clamped).rounded(.up))
+ return sortedValues[index]
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyAI/OpenAIPlannerHintAdapter.swift b/apps/Donkey/Sources/DonkeyAI/OpenAIPlannerHintAdapter.swift
index de0289cd..978f4b20 100644
--- a/apps/Donkey/Sources/DonkeyAI/OpenAIPlannerHintAdapter.swift
+++ b/apps/Donkey/Sources/DonkeyAI/OpenAIPlannerHintAdapter.swift
@@ -278,11 +278,32 @@ public struct OpenAIPlannerHintAdapter: Sendable {
"latest_state: \(request.context.latestWorldState?.summary ?? "none")",
"source_state_id: \(request.sourceStateID ?? "none")",
"valid_hints: \(request.context.activeHints.map(\.summary).joined(separator: " | "))",
- "recent_failures: \(request.context.recentFailures.map(\.summary).joined(separator: " | "))"
+ "recent_failures: \(request.context.recentFailures.map(\.summary).joined(separator: " | "))",
+ "memory: \(memoryText(for: request.context.memorySnapshot))"
]
.joined(separator: "\n")
}
+ private func memoryText(for snapshot: RunMemorySnapshot?) -> String {
+ guard let snapshot else { return "none" }
+
+ let parts = [
+ snapshot.currentGoal.map { "goal=\($0)" },
+ snapshot.recentStates.last.map { "latestMemoryState=\($0.summary)" },
+ nonEmpty("instructions", snapshot.userInstructions.map(\.value)),
+ nonEmpty("safetyStops", snapshot.safetyStops.map(\.value)),
+ nonEmpty("target", snapshot.targetRecords.map(\.value))
+ ]
+ .compactMap { $0 }
+
+ return parts.isEmpty ? "none" : parts.joined(separator: " | ")
+ }
+
+ private func nonEmpty(_ label: String, _ values: [String]) -> String? {
+ guard !values.isEmpty else { return nil }
+ return "\(label)=\(values.joined(separator: "; "))"
+ }
+
private func plannerHintJSONSchema() -> [String: Any] {
[
"type": "object",
diff --git a/apps/Donkey/Sources/DonkeyContracts/HotLoopContracts.swift b/apps/Donkey/Sources/DonkeyContracts/HotLoopContracts.swift
index 8a4837c9..2006da4b 100644
--- a/apps/Donkey/Sources/DonkeyContracts/HotLoopContracts.swift
+++ b/apps/Donkey/Sources/DonkeyContracts/HotLoopContracts.swift
@@ -487,6 +487,10 @@ public enum HotLoopActionKind: String, CaseIterable, Codable, Equatable, Hashabl
case observe
case wait
case tapTarget
+ case focusWindow
+ case switchTab
+ case openAppSwitcher
+ case activateCandidate
}
public struct HotLoopControllerAction: Codable, Equatable, Sendable {
diff --git a/apps/Donkey/Sources/DonkeyContracts/LocalNavigationContracts.swift b/apps/Donkey/Sources/DonkeyContracts/LocalNavigationContracts.swift
new file mode 100644
index 00000000..cc58db7c
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyContracts/LocalNavigationContracts.swift
@@ -0,0 +1,128 @@
+import Foundation
+
+public enum LocalNavigationCandidateKind: String, Codable, Equatable, Sendable {
+ case window
+ case browserTab
+ case app
+ case focusedSurface
+}
+
+public struct LocalNavigationCandidate: Codable, Equatable, Sendable {
+ public var id: String
+ public var kind: LocalNavigationCandidateKind
+ public var appName: String?
+ public var bundleIdentifier: String?
+ public var title: String?
+ public var bounds: HotLoopRect?
+ public var isFrontmost: Bool
+ public var isFocused: Bool
+ public var safetyStatus: WindowTargetSafetyStatus
+ public var confidence: Double
+ public var sourceAgeMS: Double?
+ public var metadata: [String: String]
+
+ public init(
+ id: String,
+ kind: LocalNavigationCandidateKind,
+ appName: String? = nil,
+ bundleIdentifier: String? = nil,
+ title: String? = nil,
+ bounds: HotLoopRect? = nil,
+ isFrontmost: Bool = false,
+ isFocused: Bool = false,
+ safetyStatus: WindowTargetSafetyStatus = .allowed,
+ confidence: Double,
+ sourceAgeMS: Double? = nil,
+ metadata: [String: String] = [:]
+ ) {
+ self.id = id
+ self.kind = kind
+ self.appName = appName
+ self.bundleIdentifier = bundleIdentifier
+ self.title = title
+ self.bounds = bounds
+ self.isFrontmost = isFrontmost
+ self.isFocused = isFocused
+ self.safetyStatus = safetyStatus
+ self.confidence = confidence
+ self.sourceAgeMS = sourceAgeMS
+ self.metadata = metadata
+ }
+}
+
+public struct LocalNavigationWorldState: Codable, Equatable, Sendable {
+ public var id: String
+ public var traceID: String
+ public var frameID: String
+ public var targetID: String
+ public var observedAt: RunTraceTimestamp
+ public var candidates: [LocalNavigationCandidate]
+ public var focusedCandidateID: String?
+ public var frontmostCandidateID: String?
+ public var requestedBundleIdentifier: String?
+ public var requestedTitleContains: String?
+ public var confidence: Double
+ public var metadata: [String: String]
+
+ public init(
+ id: String,
+ traceID: String,
+ frameID: String,
+ targetID: String,
+ observedAt: RunTraceTimestamp,
+ candidates: [LocalNavigationCandidate],
+ focusedCandidateID: String? = nil,
+ frontmostCandidateID: String? = nil,
+ requestedBundleIdentifier: String? = nil,
+ requestedTitleContains: String? = nil,
+ confidence: Double,
+ metadata: [String: String] = [:]
+ ) {
+ self.id = id
+ self.traceID = traceID
+ self.frameID = frameID
+ self.targetID = targetID
+ self.observedAt = observedAt
+ self.candidates = candidates
+ self.focusedCandidateID = focusedCandidateID
+ self.frontmostCandidateID = frontmostCandidateID
+ self.requestedBundleIdentifier = requestedBundleIdentifier
+ self.requestedTitleContains = requestedTitleContains
+ self.confidence = confidence
+ self.metadata = metadata
+ }
+
+ public func hotLoopWorldState() -> HotLoopWorldState {
+ HotLoopWorldState(
+ id: id,
+ traceID: traceID,
+ frameID: frameID,
+ targetID: targetID,
+ observedAt: observedAt,
+ signalSummaries: [
+ HotLoopPerceptionSignalSummary(
+ id: "signal-\(id)",
+ kind: "localNavigationMetadata",
+ confidence: confidence,
+ sourceAgeMS: candidates.compactMap(\.sourceAgeMS).max(),
+ observationCount: candidates.count
+ )
+ ],
+ actionAffordances: candidates.map { candidate in
+ HotLoopActionAffordance(
+ id: "affordance-\(candidate.id)",
+ kind: candidate.kind == .browserTab ? .switchTab : .focusWindow,
+ targetBounds: candidate.bounds,
+ confidence: candidate.confidence,
+ sourceSignalID: "signal-\(id)"
+ )
+ },
+ confidence: confidence,
+ metadata: metadata.merging([
+ "localNavigation.candidateCount": String(candidates.count),
+ "localNavigation.focusedCandidateID": focusedCandidateID ?? "",
+ "localNavigation.frontmostCandidateID": frontmostCandidateID ?? ""
+ ]) { current, _ in current }
+ )
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyContracts/MemoryContracts.swift b/apps/Donkey/Sources/DonkeyContracts/MemoryContracts.swift
new file mode 100644
index 00000000..eec35dca
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyContracts/MemoryContracts.swift
@@ -0,0 +1,257 @@
+import Foundation
+
+public enum RunMemoryScope: String, Codable, Equatable, Sendable {
+ case run
+ case target
+ case user
+}
+
+public enum RunMemoryKind: String, Codable, Equatable, Sendable {
+ case currentGoal
+ case activeHint
+ case recentState
+ case failure
+ case userInstruction
+ case safetyStop
+ case targetFact
+}
+
+public enum RunMemoryAuthor: String, Codable, Equatable, Sendable {
+ case deterministicRuntime
+ case user
+ case model
+}
+
+public struct RunMemorySource: Codable, Equatable, Sendable {
+ public var traceID: String?
+ public var frameID: String?
+ public var stateID: String?
+ public var actionID: String?
+ public var plannerHintID: String?
+ public var modelCallID: String?
+ public var eventSequence: Int?
+ public var summary: String
+
+ public init(
+ traceID: String? = nil,
+ frameID: String? = nil,
+ stateID: String? = nil,
+ actionID: String? = nil,
+ plannerHintID: String? = nil,
+ modelCallID: String? = nil,
+ eventSequence: Int? = nil,
+ summary: String
+ ) {
+ self.traceID = traceID
+ self.frameID = frameID
+ self.stateID = stateID
+ self.actionID = actionID
+ self.plannerHintID = plannerHintID
+ self.modelCallID = modelCallID
+ self.eventSequence = eventSequence
+ self.summary = summary
+ }
+
+ public var isLinked: Bool {
+ traceID != nil
+ || frameID != nil
+ || stateID != nil
+ || actionID != nil
+ || plannerHintID != nil
+ || modelCallID != nil
+ || eventSequence != nil
+ }
+}
+
+public struct RunMemoryRecord: Codable, Equatable, Sendable {
+ public var id: String
+ public var scope: RunMemoryScope
+ public var kind: RunMemoryKind
+ public var targetID: String?
+ public var runID: String?
+ public var userID: String?
+ public var value: String
+ public var createdAt: RunTraceTimestamp
+ public var expiresAt: RunTraceTimestamp?
+ public var durable: Bool
+ public var source: RunMemorySource
+ public var metadata: [String: String]
+
+ public init(
+ id: String,
+ scope: RunMemoryScope,
+ kind: RunMemoryKind,
+ targetID: String? = nil,
+ runID: String? = nil,
+ userID: String? = nil,
+ value: String,
+ createdAt: RunTraceTimestamp,
+ expiresAt: RunTraceTimestamp? = nil,
+ durable: Bool = false,
+ source: RunMemorySource,
+ metadata: [String: String] = [:]
+ ) {
+ self.id = id
+ self.scope = scope
+ self.kind = kind
+ self.targetID = targetID
+ self.runID = runID
+ self.userID = userID
+ self.value = value
+ self.createdAt = createdAt
+ self.expiresAt = expiresAt
+ self.durable = durable
+ self.source = source
+ self.metadata = metadata
+ }
+
+ public func isExpired(at timestamp: RunTraceTimestamp) -> Bool {
+ guard let expiresAt else { return false }
+ return expiresAt.milliseconds(until: timestamp) != nil
+ }
+
+ public var hasRequiredRetention: Bool {
+ expiresAt != nil || durable
+ }
+}
+
+public enum RunMemoryApprovalIssue: String, Codable, Equatable, Sendable {
+ case emptyValue
+ case missingSourceLink
+ case missingTargetID
+ case missingRunID
+ case missingUserID
+ case missingRetention
+ case unsupportedScope
+}
+
+public struct RunMemoryWriteProposal: Codable, Equatable, Sendable {
+ public var id: String
+ public var proposedBy: RunMemoryAuthor
+ public var record: RunMemoryRecord
+ public var rationale: String
+
+ public init(
+ id: String,
+ proposedBy: RunMemoryAuthor,
+ record: RunMemoryRecord,
+ rationale: String
+ ) {
+ self.id = id
+ self.proposedBy = proposedBy
+ self.record = record
+ self.rationale = rationale
+ }
+}
+
+public struct RunMemoryWriteApproval: Codable, Equatable, Sendable {
+ public var proposalID: String
+ public var approved: Bool
+ public var issues: [RunMemoryApprovalIssue]
+ public var decidedAt: RunTraceTimestamp
+ public var approver: String
+
+ public init(
+ proposalID: String,
+ approved: Bool,
+ issues: [RunMemoryApprovalIssue],
+ decidedAt: RunTraceTimestamp,
+ approver: String = "deterministic-memory-approver-v1"
+ ) {
+ self.proposalID = proposalID
+ self.approved = approved
+ self.issues = issues
+ self.decidedAt = decidedAt
+ self.approver = approver
+ }
+}
+
+public struct RunMemoryWriteDecision: Codable, Equatable, Sendable {
+ public var proposal: RunMemoryWriteProposal
+ public var approval: RunMemoryWriteApproval
+ public var storedRecord: RunMemoryRecord?
+
+ public init(
+ proposal: RunMemoryWriteProposal,
+ approval: RunMemoryWriteApproval,
+ storedRecord: RunMemoryRecord?
+ ) {
+ self.proposal = proposal
+ self.approval = approval
+ self.storedRecord = storedRecord
+ }
+}
+
+public struct RunMemorySnapshot: Codable, Equatable, Sendable {
+ public var currentGoal: String?
+ public var activeHints: [RunPlannerHint]
+ public var recentStates: [RunWorldStateSummary]
+ public var recentFailures: [RunFailureSummary]
+ public var userInstructions: [RunMemoryRecord]
+ public var safetyStops: [RunMemoryRecord]
+ public var targetRecords: [RunMemoryRecord]
+
+ public init(
+ currentGoal: String? = nil,
+ activeHints: [RunPlannerHint] = [],
+ recentStates: [RunWorldStateSummary] = [],
+ recentFailures: [RunFailureSummary] = [],
+ userInstructions: [RunMemoryRecord] = [],
+ safetyStops: [RunMemoryRecord] = [],
+ targetRecords: [RunMemoryRecord] = []
+ ) {
+ self.currentGoal = currentGoal
+ self.activeHints = activeHints
+ self.recentStates = recentStates
+ self.recentFailures = recentFailures
+ self.userInstructions = userInstructions
+ self.safetyStops = safetyStops
+ self.targetRecords = targetRecords
+ }
+}
+
+public enum RunMemoryApprover {
+ public static func evaluate(
+ _ proposal: RunMemoryWriteProposal,
+ decidedAt: RunTraceTimestamp
+ ) -> RunMemoryWriteApproval {
+ var issues: [RunMemoryApprovalIssue] = []
+ let record = proposal.record
+
+ if record.value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ issues.append(.emptyValue)
+ }
+
+ if !record.source.isLinked {
+ issues.append(.missingSourceLink)
+ }
+
+ switch record.scope {
+ case .run:
+ if record.runID == nil {
+ issues.append(.missingRunID)
+ }
+ case .target:
+ if record.targetID == nil {
+ issues.append(.missingTargetID)
+ }
+ if !record.hasRequiredRetention {
+ issues.append(.missingRetention)
+ }
+ case .user:
+ if record.userID == nil {
+ issues.append(.missingUserID)
+ }
+ if !record.hasRequiredRetention {
+ issues.append(.missingRetention)
+ }
+ }
+
+ return RunMemoryWriteApproval(
+ proposalID: proposal.id,
+ approved: issues.isEmpty,
+ issues: Array(Set(issues)).sorted { $0.rawValue < $1.rawValue },
+ decidedAt: decidedAt
+ )
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyContracts/RunLoopContracts.swift b/apps/Donkey/Sources/DonkeyContracts/RunLoopContracts.swift
index 989d4a42..748dc4b0 100644
--- a/apps/Donkey/Sources/DonkeyContracts/RunLoopContracts.swift
+++ b/apps/Donkey/Sources/DonkeyContracts/RunLoopContracts.swift
@@ -257,6 +257,7 @@ public struct RunContextPackage: Codable, Equatable, Sendable {
public var droppedTranscriptCharacterCount: Int
public var activeHints: [RunPlannerHint]
public var recentFailures: [RunFailureSummary]
+ public var memorySnapshot: RunMemorySnapshot?
public init(
sessionID: String,
@@ -267,7 +268,8 @@ public struct RunContextPackage: Codable, Equatable, Sendable {
transcriptSummary: String,
droppedTranscriptCharacterCount: Int = 0,
activeHints: [RunPlannerHint] = [],
- recentFailures: [RunFailureSummary] = []
+ recentFailures: [RunFailureSummary] = [],
+ memorySnapshot: RunMemorySnapshot? = nil
) {
self.sessionID = sessionID
self.userGoal = userGoal
@@ -278,6 +280,7 @@ public struct RunContextPackage: Codable, Equatable, Sendable {
self.droppedTranscriptCharacterCount = droppedTranscriptCharacterCount
self.activeHints = activeHints
self.recentFailures = recentFailures
+ self.memorySnapshot = memorySnapshot
}
}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalNavigationController.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalNavigationController.swift
new file mode 100644
index 00000000..ed22b124
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalNavigationController.swift
@@ -0,0 +1,232 @@
+import DonkeyContracts
+import Foundation
+
+public struct LocalNavigationMetadataProjector: Sendable {
+ public var staleSourceThresholdMS: Double
+
+ public init(staleSourceThresholdMS: Double = 250) {
+ self.staleSourceThresholdMS = staleSourceThresholdMS
+ }
+
+ public func project(
+ snapshot: MacWindowCandidateListSnapshot,
+ traceID: String,
+ targetID: String,
+ observedAt: RunTraceTimestamp,
+ sourceCapturedAt: RunTraceTimestamp,
+ requestedBundleIdentifier: String? = nil,
+ requestedTitleContains: String? = nil
+ ) -> LocalNavigationWorldState {
+ let sourceAgeMS = sourceCapturedAt.milliseconds(until: observedAt)
+ let candidates = snapshot.candidates.map { labeled in
+ candidate(
+ labeled: labeled,
+ sourceAgeMS: sourceAgeMS
+ )
+ }
+ let usableCandidates = candidates.filter { $0.safetyStatus == .allowed }
+ let confidence = usableCandidates.isEmpty
+ ? 0
+ : usableCandidates.map(\.confidence).reduce(0, +) / Double(usableCandidates.count)
+
+ return LocalNavigationWorldState(
+ id: "local-nav-state-\(traceID)",
+ traceID: traceID,
+ frameID: "local-nav-frame-\(traceID)",
+ targetID: targetID,
+ observedAt: observedAt,
+ candidates: candidates,
+ focusedCandidateID: candidates.first(where: \.isFocused)?.id,
+ frontmostCandidateID: candidates.first(where: \.isFrontmost)?.id,
+ requestedBundleIdentifier: requestedBundleIdentifier,
+ requestedTitleContains: requestedTitleContains,
+ confidence: min(max(confidence, 0), 1),
+ metadata: [
+ "projector": "local-navigation-metadata-projector",
+ "rawPixelsExposed": "false",
+ "sourceAgeMS": sourceAgeMS.map { String($0) } ?? "unknown",
+ "stale": String((sourceAgeMS ?? Double.greatestFiniteMagnitude) > staleSourceThresholdMS)
+ ]
+ )
+ }
+
+ private func candidate(
+ labeled: LabeledMacWindowTargetCandidate,
+ sourceAgeMS: Double?
+ ) -> LocalNavigationCandidate {
+ let window = labeled.candidate
+ return LocalNavigationCandidate(
+ id: "window-\(window.windowID)",
+ kind: .window,
+ appName: window.appName,
+ bundleIdentifier: window.bundleIdentifier,
+ title: window.title,
+ bounds: HotLoopRect(
+ x: window.bounds.x,
+ y: window.bounds.y,
+ width: window.bounds.width,
+ height: window.bounds.height,
+ space: .screen
+ ),
+ isFrontmost: window.isFrontmost,
+ isFocused: window.isFocused,
+ safetyStatus: window.safetyAssessment.status,
+ confidence: confidence(for: window),
+ sourceAgeMS: sourceAgeMS,
+ metadata: [
+ "label": labeled.label,
+ "windowID": String(window.windowID),
+ "processID": String(window.processID),
+ "isVisible": String(window.isVisible),
+ "isOnScreen": String(window.isOnScreen)
+ ]
+ )
+ }
+
+ private func confidence(for window: MacWindowTargetCandidate) -> Double {
+ guard window.isVisible, window.isOnScreen else { return 0 }
+
+ switch window.safetyAssessment.status {
+ case .allowed:
+ var confidence = 0.75
+ if window.isFrontmost { confidence += 0.1 }
+ if window.isFocused { confidence += 0.1 }
+ if window.bundleIdentifier != nil { confidence += 0.05 }
+ return min(confidence, 1)
+ case .reviewRequired:
+ return 0.3
+ case .blocked:
+ return 0
+ }
+ }
+}
+
+public struct LocalNavigationControllerPolicy: Sendable {
+ public var name: String
+ public var minimumConfidence: Double
+
+ public init(
+ name: String = "local-navigation-controller-v1",
+ minimumConfidence: Double = 0.6
+ ) {
+ self.name = name
+ self.minimumConfidence = minimumConfidence
+ }
+
+ public func decide(state: LocalNavigationWorldState) -> HotLoopControllerAction {
+ let candidates = state.candidates
+ .filter { $0.safetyStatus == .allowed && $0.confidence >= minimumConfidence }
+ let requestedCandidate = candidates
+ .filter { matchesRequest($0, state: state) }
+ .sorted { $0.confidence > $1.confidence }
+ .first
+
+ if let requestedCandidate {
+ if requestedCandidate.isFocused {
+ return action(
+ state: state,
+ candidate: requestedCandidate,
+ kind: .wait,
+ confidence: requestedCandidate.confidence,
+ rationale: "Requested navigation target is already focused",
+ fallback: true,
+ fallbackReason: "alreadyFocused"
+ )
+ }
+
+ return action(
+ state: state,
+ candidate: requestedCandidate,
+ kind: requestedCandidate.kind == .browserTab ? .switchTab : .focusWindow,
+ confidence: requestedCandidate.confidence,
+ rationale: "Selected requested local navigation target",
+ fallback: false
+ )
+ }
+
+ if state.requestedBundleIdentifier != nil || state.requestedTitleContains != nil {
+ return action(
+ state: state,
+ candidate: nil,
+ kind: .observe,
+ confidence: state.confidence,
+ rationale: "Requested navigation target was not found",
+ fallback: true,
+ fallbackReason: "targetNotFound"
+ )
+ }
+
+ guard let best = candidates
+ .filter({ !$0.isFocused })
+ .sorted(by: { $0.confidence > $1.confidence })
+ .first
+ else {
+ return action(
+ state: state,
+ candidate: nil,
+ kind: state.candidates.isEmpty ? .observe : .wait,
+ confidence: state.confidence,
+ rationale: state.candidates.isEmpty
+ ? "No local navigation candidates are available"
+ : "No unfocused safe candidate is available",
+ fallback: true,
+ fallbackReason: state.candidates.isEmpty ? "noCandidates" : "noUnfocusedCandidate"
+ )
+ }
+
+ return action(
+ state: state,
+ candidate: best,
+ kind: .activateCandidate,
+ confidence: best.confidence,
+ rationale: "Selected highest-confidence safe local navigation candidate",
+ fallback: false
+ )
+ }
+
+ private func matchesRequest(
+ _ candidate: LocalNavigationCandidate,
+ state: LocalNavigationWorldState
+ ) -> Bool {
+ let bundleMatches = state.requestedBundleIdentifier.map { requested in
+ candidate.bundleIdentifier == requested
+ } ?? true
+ let titleMatches = state.requestedTitleContains.map { requested in
+ candidate.title?.localizedCaseInsensitiveContains(requested) == true
+ } ?? true
+ return bundleMatches && titleMatches
+ }
+
+ private func action(
+ state: LocalNavigationWorldState,
+ candidate: LocalNavigationCandidate?,
+ kind: HotLoopActionKind,
+ confidence: Double,
+ rationale: String,
+ fallback: Bool,
+ fallbackReason: String? = nil
+ ) -> HotLoopControllerAction {
+ var metadata = [
+ "fallback": String(fallback),
+ "localNavigation": "true"
+ ]
+ metadata["candidateID"] = candidate?.id
+ metadata["candidateKind"] = candidate?.kind.rawValue
+ metadata["bundleIdentifier"] = candidate?.bundleIdentifier
+ metadata["title"] = candidate?.title
+ metadata["fallbackReason"] = fallbackReason
+
+ return HotLoopControllerAction(
+ id: "action-\(state.id)",
+ traceID: state.traceID,
+ frameID: state.frameID,
+ stateID: state.id,
+ kind: kind,
+ target: candidate?.bounds,
+ policyName: name,
+ confidence: confidence,
+ rationale: rationale,
+ metadata: metadata
+ )
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/RunContextAssembler.swift b/apps/Donkey/Sources/DonkeyRuntime/RunContextAssembler.swift
index 50555841..59ff4354 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/RunContextAssembler.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/RunContextAssembler.swift
@@ -13,9 +13,11 @@ public struct RunContextAssembler: Equatable, Sendable {
latestWorldState: RunWorldStateSummary? = nil,
transcriptSummary: String = "",
activeHints: [RunPlannerHint] = [],
- recentFailures: [RunFailureSummary] = []
+ recentFailures: [RunFailureSummary] = [],
+ memorySnapshot: RunMemorySnapshot? = nil
) -> RunContextPackage {
let boundedTranscript = bounded(transcriptSummary)
+ let validHints = activeHints.filter(\.isValid)
return RunContextPackage(
sessionID: session.id,
@@ -25,8 +27,9 @@ public struct RunContextAssembler: Equatable, Sendable {
latestWorldState: latestWorldState,
transcriptSummary: boundedTranscript.text,
droppedTranscriptCharacterCount: boundedTranscript.droppedCount,
- activeHints: activeHints.filter(\.isValid),
- recentFailures: recentFailures
+ activeHints: validHints,
+ recentFailures: recentFailures,
+ memorySnapshot: boundedMemorySnapshot(memorySnapshot, fallbackHints: validHints, fallbackFailures: recentFailures)
)
}
@@ -38,4 +41,28 @@ public struct RunContextAssembler: Equatable, Sendable {
let suffix = String(text.suffix(maxTranscriptCharacters))
return (suffix, text.count - suffix.count)
}
+
+ private func boundedMemorySnapshot(
+ _ snapshot: RunMemorySnapshot?,
+ fallbackHints: [RunPlannerHint],
+ fallbackFailures: [RunFailureSummary]
+ ) -> RunMemorySnapshot? {
+ guard var snapshot else { return nil }
+
+ snapshot.activeHints = snapshot.activeHints.filter(\.isValid)
+ if snapshot.activeHints.isEmpty {
+ snapshot.activeHints = fallbackHints
+ }
+ if snapshot.recentFailures.isEmpty {
+ snapshot.recentFailures = fallbackFailures
+ }
+
+ snapshot.recentStates = Array(snapshot.recentStates.suffix(5))
+ snapshot.recentFailures = Array(snapshot.recentFailures.suffix(5))
+ snapshot.userInstructions = Array(snapshot.userInstructions.suffix(5))
+ snapshot.safetyStops = Array(snapshot.safetyStops.suffix(5))
+ snapshot.targetRecords = Array(snapshot.targetRecords.suffix(10))
+
+ return snapshot
+ }
}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/RunCoordinator.swift b/apps/Donkey/Sources/DonkeyRuntime/RunCoordinator.swift
index e782f250..57c94d81 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/RunCoordinator.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/RunCoordinator.swift
@@ -185,7 +185,8 @@ public actor RunCoordinator {
latestWorldState: RunWorldStateSummary? = nil,
transcriptSummary: String = "",
activeHints: [RunPlannerHint] = [],
- recentFailures: [RunFailureSummary] = []
+ recentFailures: [RunFailureSummary] = [],
+ memorySnapshot: RunMemorySnapshot? = nil
) -> RunContextPackage? {
guard let currentSession else { return nil }
@@ -194,7 +195,8 @@ public actor RunCoordinator {
latestWorldState: latestWorldState,
transcriptSummary: transcriptSummary,
activeHints: activeHints,
- recentFailures: recentFailures
+ recentFailures: recentFailures,
+ memorySnapshot: memorySnapshot
)
}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/RunMemoryStore.swift b/apps/Donkey/Sources/DonkeyRuntime/RunMemoryStore.swift
new file mode 100644
index 00000000..5f4eaa36
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/RunMemoryStore.swift
@@ -0,0 +1,281 @@
+import DonkeyContracts
+import Foundation
+
+public enum TargetMemoryStoreError: Error, Equatable, Sendable {
+ case invalidIdentifier(String)
+ case missingScopeTarget
+ case writeNotApproved([RunMemoryApprovalIssue])
+}
+
+public actor InMemoryRunMemory {
+ private let runID: String
+ private let targetID: String
+ private let capacity: Int
+ private var currentGoal: String?
+ private var activeHints: [RunPlannerHint] = []
+ private var recentStates: [RunWorldStateSummary] = []
+ private var recentFailures: [RunFailureSummary] = []
+ private var records: [RunMemoryRecord] = []
+
+ public init(
+ runID: String,
+ targetID: String,
+ currentGoal: String? = nil,
+ capacity: Int = 20
+ ) {
+ self.runID = runID
+ self.targetID = targetID
+ self.currentGoal = currentGoal
+ self.capacity = max(1, capacity)
+ }
+
+ public func updateGoal(_ goal: String?) {
+ currentGoal = goal
+ }
+
+ public func setActiveHints(_ hints: [RunPlannerHint]) {
+ activeHints = Array(hints.filter(\.isValid).suffix(capacity))
+ }
+
+ public func rememberState(_ state: RunWorldStateSummary) {
+ recentStates.append(state)
+ recentStates = Array(recentStates.suffix(capacity))
+ }
+
+ public func rememberFailure(_ failure: RunFailureSummary) {
+ recentFailures.append(failure)
+ recentFailures = Array(recentFailures.suffix(capacity))
+ }
+
+ public func append(_ record: RunMemoryRecord) {
+ records.append(record)
+ records = Array(records.suffix(capacity))
+ }
+
+ public func delete(recordID: String) {
+ records.removeAll { $0.id == recordID }
+ }
+
+ public func snapshot(now: RunTraceTimestamp? = nil) -> RunMemorySnapshot {
+ let liveRecords = records.filter { record in
+ guard let now else { return true }
+ return !record.isExpired(at: now)
+ }
+
+ return RunMemorySnapshot(
+ currentGoal: currentGoal,
+ activeHints: activeHints,
+ recentStates: Array(recentStates.suffix(capacity)),
+ recentFailures: Array(recentFailures.suffix(capacity)),
+ userInstructions: liveRecords.filtered(kind: .userInstruction, runID: runID, targetID: targetID),
+ safetyStops: liveRecords.filtered(kind: .safetyStop, runID: runID, targetID: targetID),
+ targetRecords: liveRecords.filter { $0.scope == .target && $0.targetID == targetID }
+ )
+ }
+}
+
+public actor TargetMemoryJSONLStore {
+ private let baseDirectory: URL
+ private let fileManager: FileManager
+
+ public init(
+ baseDirectory: URL? = nil,
+ fileManager: FileManager = .default
+ ) throws {
+ self.fileManager = fileManager
+ self.baseDirectory = try baseDirectory ?? Self.defaultBaseDirectory(fileManager: fileManager)
+ }
+
+ public static func defaultBaseDirectory(
+ fileManager: FileManager = .default
+ ) throws -> URL {
+ let applicationSupport = try fileManager.url(
+ for: .applicationSupportDirectory,
+ in: .userDomainMask,
+ appropriateFor: nil,
+ create: false
+ )
+
+ return applicationSupport
+ .appendingPathComponent("Donkey", isDirectory: true)
+ .appendingPathComponent("TargetMemory", isDirectory: true)
+ }
+
+ @discardableResult
+ public func appendApprovedProposal(
+ _ proposal: RunMemoryWriteProposal,
+ decidedAt: RunTraceTimestamp
+ ) throws -> RunMemoryWriteDecision {
+ let approval = RunMemoryApprover.evaluate(proposal, decidedAt: decidedAt)
+ guard approval.approved else {
+ return RunMemoryWriteDecision(
+ proposal: proposal,
+ approval: approval,
+ storedRecord: nil
+ )
+ }
+
+ let record = proposal.record
+ guard record.scope == .target else {
+ throw TargetMemoryStoreError.missingScopeTarget
+ }
+ guard let targetID = record.targetID else {
+ throw TargetMemoryStoreError.missingScopeTarget
+ }
+
+ try validateIdentifier(targetID)
+ try validateIdentifier(record.id)
+ try fileManager.createDirectory(
+ at: targetDirectory(for: targetID),
+ withIntermediateDirectories: true
+ )
+
+ var line = try Self.encoder().encode(record)
+ line.append(0x0A)
+
+ let url = memoryURL(for: targetID)
+ if !fileManager.fileExists(atPath: url.path) {
+ try Data().write(to: url, options: .atomic)
+ }
+ let handle = try FileHandle(forWritingTo: url)
+ defer { try? handle.close() }
+ try handle.seekToEnd()
+ try handle.write(contentsOf: line)
+
+ return RunMemoryWriteDecision(
+ proposal: proposal,
+ approval: approval,
+ storedRecord: record
+ )
+ }
+
+ public func records(
+ targetID: String,
+ now: RunTraceTimestamp? = nil
+ ) throws -> [RunMemoryRecord] {
+ try validateIdentifier(targetID)
+ let url = memoryURL(for: targetID)
+ guard fileManager.fileExists(atPath: url.path) else {
+ return []
+ }
+
+ let data = try Data(contentsOf: url)
+ let text = String(decoding: data, as: UTF8.self)
+ return try text
+ .split(separator: "\n")
+ .map { line in
+ try Self.decoder().decode(
+ RunMemoryRecord.self,
+ from: Data(line.utf8)
+ )
+ }
+ .filter { record in
+ guard let now else { return true }
+ return !record.isExpired(at: now)
+ }
+ }
+
+ public func records(
+ targetID: String,
+ runID: String? = nil,
+ userID: String? = nil,
+ now: RunTraceTimestamp? = nil
+ ) throws -> [RunMemoryRecord] {
+ if let runID {
+ try validateIdentifier(runID)
+ }
+ if let userID {
+ try validateIdentifier(userID)
+ }
+
+ return try records(targetID: targetID, now: now).filter { record in
+ if let runID, record.runID != runID { return false }
+ if let userID, record.userID != userID { return false }
+ return true
+ }
+ }
+
+ @discardableResult
+ public func delete(
+ targetID: String,
+ recordID: String? = nil,
+ runID: String? = nil,
+ userID: String? = nil
+ ) throws -> Int {
+ try validateIdentifier(targetID)
+ if let recordID {
+ try validateIdentifier(recordID)
+ }
+ if let runID {
+ try validateIdentifier(runID)
+ }
+ if let userID {
+ try validateIdentifier(userID)
+ }
+
+ let url = memoryURL(for: targetID)
+ guard fileManager.fileExists(atPath: url.path) else {
+ return 0
+ }
+
+ let existing = try records(targetID: targetID)
+ let remaining = existing.filter { record in
+ if let recordID, record.id == recordID { return false }
+ if let runID, record.runID == runID { return false }
+ if let userID, record.userID == userID { return false }
+ return true
+ }
+ let deletedCount = existing.count - remaining.count
+
+ var data = Data()
+ for record in remaining {
+ var line = try Self.encoder().encode(record)
+ line.append(0x0A)
+ data.append(line)
+ }
+ try data.write(to: url, options: .atomic)
+
+ return deletedCount
+ }
+
+ private func targetDirectory(for targetID: String) -> URL {
+ baseDirectory.appendingPathComponent(targetID, isDirectory: true)
+ }
+
+ private func memoryURL(for targetID: String) -> URL {
+ targetDirectory(for: targetID).appendingPathComponent("memory.jsonl", isDirectory: false)
+ }
+
+ private func validateIdentifier(_ value: String) throws {
+ let allowedScalars = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-")
+ let isSafe = !value.isEmpty
+ && value.count <= 128
+ && value != "."
+ && value != ".."
+ && value.unicodeScalars.allSatisfy { allowedScalars.contains($0) }
+
+ guard isSafe else {
+ throw TargetMemoryStoreError.invalidIdentifier(value)
+ }
+ }
+
+ private static func encoder() -> JSONEncoder {
+ let encoder = JSONEncoder()
+ encoder.outputFormatting = [.sortedKeys]
+ return encoder
+ }
+
+ private static func decoder() -> JSONDecoder {
+ JSONDecoder()
+ }
+}
+
+private extension Array where Element == RunMemoryRecord {
+ func filtered(kind: RunMemoryKind, runID: String, targetID: String) -> [RunMemoryRecord] {
+ filter { record in
+ record.kind == kind
+ && (record.runID == nil || record.runID == runID)
+ && (record.targetID == nil || record.targetID == targetID)
+ }
+ }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AIReplayEvaluationTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AIReplayEvaluationTests.swift
new file mode 100644
index 00000000..451e5c11
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AIReplayEvaluationTests.swift
@@ -0,0 +1,161 @@
+import DonkeyAI
+import DonkeyContracts
+import Foundation
+import Testing
+
+@Suite
+struct AIReplayEvaluationTests {
+ @Test
+ func replayEvaluatorSummarizesModelPromptPromotionMetrics() {
+ let accepted = PlannerHintReplayCase(
+ id: "case-accepted",
+ trace: trace(id: "trace-1"),
+ hint: hint(id: "hint-1"),
+ validationIssues: [],
+ modelTrace: modelTrace(id: "call-1", latencyMS: 20),
+ memoryDecisions: [memoryDecision(approved: true)],
+ fallbackCount: 1,
+ recoverySucceeded: true,
+ estimatedCostUSD: 0.01
+ )
+ let rejected = PlannerHintReplayCase(
+ id: "case-rejected",
+ trace: trace(id: "trace-2"),
+ hint: hint(id: "hint-2"),
+ validationIssues: [.staleStateReference],
+ modelTrace: modelTrace(id: "call-2", latencyMS: 40),
+ memoryDecisions: [memoryDecision(approved: false)],
+ fallbackCount: 2,
+ recoverySucceeded: false,
+ estimatedCostUSD: 0.02
+ )
+
+ let report = PlannerHintReplayEvaluator.evaluate(
+ suiteID: "planner-replay-v1",
+ promptVersion: "planner-hint-v2",
+ modelEntryID: "openai-planner",
+ cases: [accepted, rejected],
+ generatedAt: timestamp(100)
+ )
+
+ #expect(report.caseIDs == ["case-accepted", "case-rejected"])
+ #expect(report.metrics.caseCount == 2)
+ #expect(report.metrics.schemaValidCount == 2)
+ #expect(report.metrics.hintAcceptedCount == 1)
+ #expect(report.metrics.memoryWriteAcceptedCount == 1)
+ #expect(report.metrics.memoryWriteRejectedCount == 1)
+ #expect(report.metrics.fallbackCount == 3)
+ #expect(report.metrics.recoverySuccessCount == 1)
+ #expect(report.metrics.averageModelLatencyMS == 30)
+ #expect(report.metrics.p95ModelLatencyMS == 40)
+ #expect(abs(report.metrics.totalEstimatedCostUSD - 0.03) < 0.0001)
+ }
+
+ @Test
+ func modelUpdateChecklistEncodesRequiredPromotionFields() throws {
+ let checklist = AIModelUpdateChecklist(
+ modelEntryID: "openai-planner",
+ promptVersion: "planner-hint-v2",
+ lastVerifiedAt: Date(timeIntervalSince1970: 1_000),
+ docsURLs: [URL(string: "https://platform.openai.com/docs/api-reference/responses/create")!],
+ evalSuiteID: "planner-replay-v1",
+ rollbackModelID: "openai-planner-rollback",
+ evalReportID: "report-1",
+ notes: ["dry-run only"]
+ )
+
+ let data = try JSONEncoder().encode(checklist)
+ let object = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])
+
+ #expect(object["last_verified_at"] != nil)
+ #expect(object["docs_urls"] != nil)
+ #expect(object["eval_suite_id"] as? String == "planner-replay-v1")
+ #expect(object["rollback_model_id"] as? String == "openai-planner-rollback")
+ }
+
+ private func trace(id: String) -> ReflexTraceRecord {
+ ReflexTraceRecord(
+ traceID: id,
+ frameID: "frame-\(id)",
+ stateID: "state-\(id)",
+ actionID: "action-\(id)",
+ timestamps: ReflexTraceTimeline(
+ captureStart: timestamp(1),
+ captureEnd: timestamp(2),
+ controllerStart: timestamp(3),
+ controllerEnd: timestamp(4),
+ actionEnqueued: timestamp(5),
+ inputExecuted: timestamp(6)
+ ),
+ controllerPolicy: "deterministic-controller",
+ confidence: 0.8
+ )
+ }
+
+ private func hint(id: String) -> StructuredPlannerHint {
+ StructuredPlannerHint(
+ id: id,
+ goal: "avoid hazards",
+ policyName: "planner-policy",
+ preferredActions: [.wait],
+ avoidActions: [.tapTarget],
+ confidence: 0.8,
+ createdAt: timestamp(10),
+ expiresAt: timestamp(100),
+ sourceTraceID: "trace-1",
+ sourceStateID: "state-1"
+ )
+ }
+
+ private func modelTrace(id: String, latencyMS: Double) -> AIModelCallTrace {
+ AIModelCallTrace(
+ id: id,
+ role: .plannerHint,
+ provider: .openAI,
+ modelID: "gpt-5.2",
+ promptVersion: "planner-hint-v2",
+ schemaID: "planner_hint_v1",
+ latencyMS: latencyMS,
+ timeoutMS: 8_000,
+ status: .completed,
+ validationStatus: "schemaDecoded",
+ sourceTraceID: "trace-1"
+ )
+ }
+
+ private func memoryDecision(approved: Bool) -> RunMemoryWriteDecision {
+ let proposal = RunMemoryWriteProposal(
+ id: approved ? "proposal-approved" : "proposal-rejected",
+ proposedBy: .model,
+ record: RunMemoryRecord(
+ id: approved ? "memory-approved" : "memory-rejected",
+ scope: .target,
+ kind: .targetFact,
+ targetID: "target-1",
+ value: "target fact",
+ createdAt: timestamp(10),
+ expiresAt: timestamp(100),
+ source: RunMemorySource(traceID: "trace-1", summary: "trace")
+ ),
+ rationale: "eval fixture"
+ )
+ let approval = RunMemoryWriteApproval(
+ proposalID: proposal.id,
+ approved: approved,
+ issues: approved ? [] : [.missingSourceLink],
+ decidedAt: timestamp(20)
+ )
+ return RunMemoryWriteDecision(
+ proposal: proposal,
+ approval: approval,
+ storedRecord: approved ? proposal.record : nil
+ )
+ }
+
+ private func timestamp(_ milliseconds: UInt64) -> RunTraceTimestamp {
+ RunTraceTimestamp(
+ wallClock: Date(timeIntervalSince1970: Double(milliseconds) / 1_000),
+ monotonicUptimeNanoseconds: milliseconds * 1_000_000
+ )
+ }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalNavigationControllerTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalNavigationControllerTests.swift
new file mode 100644
index 00000000..bc2c465a
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalNavigationControllerTests.swift
@@ -0,0 +1,187 @@
+import DonkeyContracts
+@testable import DonkeyRuntime
+import Foundation
+import Testing
+
+@Suite
+struct LocalNavigationControllerTests {
+ @Test
+ func metadataProjectorBuildsTypedLocalNavigationWorldState() {
+ let projector = LocalNavigationMetadataProjector()
+
+ let state = projector.project(
+ snapshot: MacWindowCandidateListSnapshot(candidates: [
+ window(
+ id: 100,
+ appName: "Code",
+ bundleIdentifier: "com.microsoft.VSCode",
+ title: "Donkey",
+ isFrontmost: false,
+ isFocused: false
+ ),
+ window(
+ id: 200,
+ appName: "Safari",
+ bundleIdentifier: "com.apple.Safari",
+ title: "Docs",
+ isFrontmost: true,
+ isFocused: true
+ )
+ ]),
+ traceID: "trace-nav",
+ targetID: "local-navigation",
+ observedAt: timestamp(20),
+ sourceCapturedAt: timestamp(10),
+ requestedBundleIdentifier: "com.microsoft.VSCode"
+ )
+
+ #expect(state.candidates.map(\.id) == ["window-100", "window-200"])
+ #expect(state.focusedCandidateID == "window-200")
+ #expect(state.frontmostCandidateID == "window-200")
+ #expect(state.requestedBundleIdentifier == "com.microsoft.VSCode")
+ #expect(state.hotLoopWorldState().actionAffordances.count == 2)
+ #expect(state.hotLoopWorldState().metadata["localNavigation.candidateCount"] == "2")
+ }
+
+ @Test
+ func controllerSelectsRequestedWindowFocusAction() {
+ let state = navigationState(
+ requestedBundleIdentifier: "com.microsoft.VSCode",
+ windows: [
+ window(
+ id: 100,
+ appName: "Code",
+ bundleIdentifier: "com.microsoft.VSCode",
+ title: "Donkey",
+ isFrontmost: false,
+ isFocused: false
+ ),
+ window(
+ id: 200,
+ appName: "Safari",
+ bundleIdentifier: "com.apple.Safari",
+ title: "Docs",
+ isFrontmost: true,
+ isFocused: true
+ )
+ ]
+ )
+
+ let action = LocalNavigationControllerPolicy().decide(state: state)
+
+ #expect(action.kind == .focusWindow)
+ #expect(action.metadata["candidateID"] == "window-100")
+ #expect(action.metadata["bundleIdentifier"] == "com.microsoft.VSCode")
+ #expect(action.metadata["fallback"] == "false")
+ }
+
+ @Test
+ func controllerFallsBackWhenRequestedTargetIsAlreadyFocusedOrMissing() {
+ let alreadyFocused = navigationState(
+ requestedBundleIdentifier: "com.apple.Safari",
+ windows: [
+ window(
+ id: 200,
+ appName: "Safari",
+ bundleIdentifier: "com.apple.Safari",
+ title: "Docs",
+ isFrontmost: true,
+ isFocused: true
+ )
+ ]
+ )
+ let wait = LocalNavigationControllerPolicy().decide(state: alreadyFocused)
+ #expect(wait.kind == .wait)
+ #expect(wait.metadata["fallbackReason"] == "alreadyFocused")
+
+ let missing = navigationState(
+ requestedBundleIdentifier: "com.apple.Terminal",
+ windows: [
+ window(
+ id: 200,
+ appName: "Safari",
+ bundleIdentifier: "com.apple.Safari",
+ title: "Docs",
+ isFrontmost: true,
+ isFocused: true
+ )
+ ]
+ )
+ let observe = LocalNavigationControllerPolicy().decide(state: missing)
+ #expect(observe.kind == .observe)
+ #expect(observe.metadata["fallbackReason"] == "targetNotFound")
+ }
+
+ @Test
+ func blockedWindowsAreNotSelectedForNavigation() {
+ let state = navigationState(
+ requestedBundleIdentifier: "com.apple.systempreferences",
+ windows: [
+ window(
+ id: 300,
+ appName: "System Settings",
+ bundleIdentifier: "com.apple.systempreferences",
+ title: "Passwords",
+ isFrontmost: false,
+ isFocused: false,
+ safetyStatus: .blocked
+ )
+ ]
+ )
+
+ let action = LocalNavigationControllerPolicy().decide(state: state)
+
+ #expect(action.kind == .observe)
+ #expect(action.metadata["fallbackReason"] == "targetNotFound")
+ }
+
+ private func navigationState(
+ requestedBundleIdentifier: String?,
+ windows: [MacWindowTargetCandidate]
+ ) -> LocalNavigationWorldState {
+ LocalNavigationMetadataProjector().project(
+ snapshot: MacWindowCandidateListSnapshot(candidates: windows),
+ traceID: "trace-nav",
+ targetID: "local-navigation",
+ observedAt: timestamp(20),
+ sourceCapturedAt: timestamp(10),
+ requestedBundleIdentifier: requestedBundleIdentifier
+ )
+ }
+
+ private func window(
+ id: UInt32,
+ appName: String,
+ bundleIdentifier: String,
+ title: String,
+ isFrontmost: Bool,
+ isFocused: Bool,
+ safetyStatus: WindowTargetSafetyStatus = .allowed
+ ) -> MacWindowTargetCandidate {
+ MacWindowTargetCandidate(
+ windowID: id,
+ processID: Int32(id),
+ appName: appName,
+ bundleIdentifier: bundleIdentifier,
+ title: title,
+ bounds: WindowTargetBounds(x: 10, y: 20, width: 300, height: 200),
+ isVisible: true,
+ isOnScreen: true,
+ isFrontmost: isFrontmost,
+ isFocused: isFocused,
+ isIPhoneMirroring: false,
+ safetyAssessment: WindowTargetSafetyAssessment(
+ status: safetyStatus,
+ reasons: safetyStatus == .blocked ? [.passwordSurface] : [],
+ summary: safetyStatus.rawValue
+ )
+ )
+ }
+
+ private func timestamp(_ milliseconds: UInt64) -> RunTraceTimestamp {
+ RunTraceTimestamp(
+ wallClock: Date(timeIntervalSince1970: Double(milliseconds) / 1_000),
+ monotonicUptimeNanoseconds: milliseconds * 1_000_000
+ )
+ }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/RunMemoryStoreTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/RunMemoryStoreTests.swift
new file mode 100644
index 00000000..049ba05f
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/RunMemoryStoreTests.swift
@@ -0,0 +1,194 @@
+import DonkeyContracts
+@testable import DonkeyRuntime
+import Foundation
+import Testing
+
+@Suite
+struct RunMemoryStoreTests {
+ @Test
+ func deterministicApproverRequiresSourceLinkAndTargetRetention() {
+ let proposal = RunMemoryWriteProposal(
+ id: "proposal-1",
+ proposedBy: .model,
+ record: RunMemoryRecord(
+ id: "memory-1",
+ scope: .target,
+ kind: .targetFact,
+ targetID: "target-1",
+ value: "jump button is lower right",
+ createdAt: timestamp(10),
+ source: RunMemorySource(summary: "model guessed")
+ ),
+ rationale: "remember target layout"
+ )
+
+ let approval = RunMemoryApprover.evaluate(proposal, decidedAt: timestamp(20))
+
+ #expect(approval.approved == false)
+ #expect(approval.issues == [.missingRetention, .missingSourceLink])
+ }
+
+ @Test
+ func targetMemoryJsonlStoresListsAndDeletesApprovedRecords() async throws {
+ let root = temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let store = try TargetMemoryJSONLStore(baseDirectory: root)
+ let proposal = RunMemoryWriteProposal(
+ id: "proposal-1",
+ proposedBy: .model,
+ record: targetRecord(id: "memory-1", runID: "run-1", userID: "user-1"),
+ rationale: "fixture-proven target fact"
+ )
+
+ let decision = try await store.appendApprovedProposal(proposal, decidedAt: timestamp(20))
+
+ #expect(decision.approval.approved == true)
+ #expect(decision.storedRecord?.id == "memory-1")
+
+ let records = try await store.records(targetID: "target-1")
+ #expect(records.map(\.id) == ["memory-1"])
+
+ let scoped = try await store.records(targetID: "target-1", runID: "run-1", userID: "user-1")
+ #expect(scoped.map(\.id) == ["memory-1"])
+
+ let deleted = try await store.delete(targetID: "target-1", recordID: "memory-1")
+ #expect(deleted == 1)
+ #expect(try await store.records(targetID: "target-1").isEmpty)
+ }
+
+ @Test
+ func rejectedMemoryProposalIsInspectableAndNotStored() async throws {
+ let root = temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let store = try TargetMemoryJSONLStore(baseDirectory: root)
+ let proposal = RunMemoryWriteProposal(
+ id: "proposal-rejected",
+ proposedBy: .model,
+ record: RunMemoryRecord(
+ id: "memory-rejected",
+ scope: .target,
+ kind: .targetFact,
+ targetID: "target-1",
+ value: "",
+ createdAt: timestamp(10),
+ source: RunMemorySource(traceID: "trace-1", summary: "empty proposal")
+ ),
+ rationale: "bad proposal"
+ )
+
+ let decision = try await store.appendApprovedProposal(proposal, decidedAt: timestamp(20))
+
+ #expect(decision.approval.approved == false)
+ #expect(decision.storedRecord == nil)
+ #expect(decision.approval.issues == [.emptyValue, .missingRetention])
+ #expect(try await store.records(targetID: "target-1").isEmpty)
+ }
+
+ @Test
+ func inProcessRunMemoryBuildsBoundedSnapshot() async {
+ let memory = InMemoryRunMemory(
+ runID: "run-1",
+ targetID: "target-1",
+ currentGoal: "avoid hazards",
+ capacity: 2
+ )
+
+ await memory.setActiveHints([
+ RunPlannerHint(id: "hint-expired", summary: "old", isValid: false),
+ RunPlannerHint(id: "hint-live", summary: "stay center", isValid: true)
+ ])
+ await memory.rememberState(RunWorldStateSummary(stateID: "state-1", summary: "left lane", confidence: 0.8))
+ await memory.rememberState(RunWorldStateSummary(stateID: "state-2", summary: "center lane", confidence: 0.9))
+ await memory.rememberFailure(RunFailureSummary(traceID: "trace-1", summary: "missed obstacle"))
+ await memory.append(instructionRecord(id: "instruction-1", value: "do not tap ads"))
+ await memory.append(safetyStopRecord(id: "stop-1", value: "operator stopped after focus loss"))
+
+ let snapshot = await memory.snapshot(now: timestamp(40))
+
+ #expect(snapshot.currentGoal == "avoid hazards")
+ #expect(snapshot.activeHints.map(\.id) == ["hint-live"])
+ #expect(snapshot.recentStates.map(\.stateID) == ["state-1", "state-2"])
+ #expect(snapshot.recentFailures.map(\.traceID) == ["trace-1"])
+ #expect(snapshot.userInstructions.map(\.value) == ["do not tap ads"])
+ #expect(snapshot.safetyStops.map(\.value) == ["operator stopped after focus loss"])
+ }
+
+ @Test
+ func contextAssemblerCarriesMemorySnapshot() {
+ let assembler = RunContextAssembler()
+ let session = RunSession(id: "run-1", userGoal: "avoid hazards", targetID: "target-1")
+ let snapshot = RunMemorySnapshot(
+ currentGoal: "avoid hazards",
+ activeHints: [RunPlannerHint(id: "hint-1", summary: "stay center", isValid: true)],
+ recentStates: [RunWorldStateSummary(stateID: "state-1", summary: "center", confidence: 0.9)],
+ targetRecords: [targetRecord(id: "memory-1", runID: "run-1", userID: "user-1")]
+ )
+
+ let context = assembler.build(
+ session: session,
+ transcriptSummary: "",
+ memorySnapshot: snapshot
+ )
+
+ #expect(context.memorySnapshot?.currentGoal == "avoid hazards")
+ #expect(context.memorySnapshot?.targetRecords.map(\.id) == ["memory-1"])
+ }
+
+ private func targetRecord(id: String, runID: String, userID: String) -> RunMemoryRecord {
+ RunMemoryRecord(
+ id: id,
+ scope: .target,
+ kind: .targetFact,
+ targetID: "target-1",
+ runID: runID,
+ userID: userID,
+ value: "jump button is lower right",
+ createdAt: timestamp(10),
+ expiresAt: timestamp(1_000),
+ durable: false,
+ source: RunMemorySource(traceID: "trace-1", stateID: "state-1", summary: "recorded trace")
+ )
+ }
+
+ private func instructionRecord(id: String, value: String) -> RunMemoryRecord {
+ RunMemoryRecord(
+ id: id,
+ scope: .run,
+ kind: .userInstruction,
+ targetID: "target-1",
+ runID: "run-1",
+ value: value,
+ createdAt: timestamp(10),
+ source: RunMemorySource(eventSequence: 1, summary: "user instruction")
+ )
+ }
+
+ private func safetyStopRecord(id: String, value: String) -> RunMemoryRecord {
+ RunMemoryRecord(
+ id: id,
+ scope: .run,
+ kind: .safetyStop,
+ targetID: "target-1",
+ runID: "run-1",
+ value: value,
+ createdAt: timestamp(20),
+ source: RunMemorySource(traceID: "trace-stop", summary: "abort")
+ )
+ }
+
+ private func timestamp(_ milliseconds: UInt64) -> RunTraceTimestamp {
+ RunTraceTimestamp(
+ wallClock: Date(timeIntervalSince1970: Double(milliseconds) / 1_000),
+ monotonicUptimeNanoseconds: milliseconds * 1_000_000
+ )
+ }
+
+ private func temporaryDirectory() -> URL {
+ FileManager.default.temporaryDirectory.appendingPathComponent(
+ "DonkeyMemoryStoreTests-\(UUID().uuidString)",
+ isDirectory: true
+ )
+ }
+}
diff --git a/docs/guides/minimal-run-coordinator.md b/docs/guides/minimal-run-coordinator.md
index bd0efe96..fe300a8e 100644
--- a/docs/guides/minimal-run-coordinator.md
+++ b/docs/guides/minimal-run-coordinator.md
@@ -28,12 +28,18 @@ Donkey also supports the first action-engine guardrail boundary. `ActionEngineGu
Donkey also supports reflex latency reports and a synthetic replay benchmark. `ReflexLatencyReportBuilder` summarizes reflex traces into p50/p95/p99 latency, capture/perception/controller rates, dropped frames, stale actions, and worst traces. `ReflexReplayBenchmark` can generate deterministic dry-run traces for capture-only, controller-only, or end-to-end dry-run report modes. The installed debug entrypoint can print a CLI-friendly dry-run latency report with `--dry-run-latency-report`.
+Donkey also supports the first fast local-navigation dry-run slice. `LocalNavigationMetadataProjector` turns macOS window candidate metadata into typed local-navigation world state with frontmost/focused candidates, safe focus candidates, confidence, source age, and no raw pixels. `LocalNavigationControllerPolicy` can choose traceable dry-run semantic actions such as `focusWindow`, `activateCandidate`, `switchTab`, `wait`, or `observe` from that typed state. This slice is metadata-only and side-effect free; browser-tab metadata adapters, live input, and richer visual inference remain future work.
+
Donkey also supports slow-path planner hint contracts. `StructuredPlannerHint` carries a goal, policy, priorities, regions of interest, preferred and avoided semantic actions, confidence, expiry, and source trace/frame/state/model-call ids. Planner hints are advisory only; they are validated for unknown actions, unsafe actions, stale state references, low-confidence replacement, and expiry before selection. `PlannerHintSelector` chooses the latest valid hint, and the reflex loop remains able to run without any planner hint.
Donkey also supports the first AI harness model registry and router boundary. `AIModelRegistry` stores model roles, providers, literal model ids, endpoints, capabilities, timeouts, prompt versions, eval status, docs URLs, and rollback ids as registry data. `AIModelRouter` routes slow-path jobs by job type, risk, privacy mode, latency tolerance, capabilities, and failed-model history. Literal provider model ids should stay in registry entries, not planner/controller logic.
Donkey also supports the first provider-neutral planner-hint adapter boundary using OpenAI's Responses API. `OpenAIPlannerHintAdapter` reads `OPENAI_API_KEY` from the environment, routes through the model registry, sends a structured-output Responses request with `store: false`, decodes a strict planner-hint JSON response, and records a model-call trace with role, provider, model id, prompt version, schema id, latency, timeout, validation status, and source trace/state ids. Missing credentials, cancellation, timeout, rate limit, invalid output, and provider outage return traceable failures without stopping the reflex loop. Official OpenAI docs were rechecked on May 16, 2026 for the Responses API, `text.format` JSON schema structured outputs, `store: false`, and current model registry default guidance.
+Donkey also supports the first memory boundary for slow-path context. Short-term run memory is in-process and bounded; it can retain the current goal, active valid hints, recent world states, recent failures, user instructions, safety stops, and target records for context assembly. Target memory is stored as scoped, source-linked JSONL records under Application Support by default, with tests and tools able to pass an explicit base directory. Model-proposed memory writes go through a deterministic approver before storage. Target and user scoped records require either an expiry timestamp or an explicit durable flag, and records can be listed or deleted by target, run, user, or record id.
+
+Donkey also supports a replay/eval scaffold for model and prompt changes. Planner-hint replay cases summarize recorded traces, decoded hints, validation issues, model-call latency, estimated cost, fallback count, recovery success, and memory-write decisions. `PlannerHintReplayEvaluator` aggregates schema validity, hint acceptance, memory write acceptance and rejection, latency, cost, fallbacks, and recovery success into a promotion report. `AIModelUpdateChecklist` records the model entry, prompt version, `last_verified_at`, docs URLs, eval suite id, rollback model id, and optional report id before model or prompt promotion.
+
Donkey also supports a local run artifact store for durable trace data. Installed app runs are stored under `~/Library/Application Support/Donkey/Runs/<run-id>/`; tests and development tools may pass an explicit base directory override. Each prepared run creates:
```text
@@ -55,7 +61,7 @@ Donkey supports a runtime-level manual target context capture service that wires
The installed executable also supports a developer-only launch-argument entrypoint for manual verification. `--list-window-candidates` prints the current candidate-list labels and durable `windowID` values. `--manual-capture` runs one manual capture, optionally with `--window-id <id>`, `--run-id <safe-id>`, and `--trace-id <safe-id>`, then prints the run folder and artifact paths. These commands are non-interactive and exit before showing the pointer prompt overlay.
-This is a coordination, in-memory reflex trace, hot-loop contract, deterministic dry-run skeleton, bounded target-window frame-source, cheap metadata perception, deterministic controller, action-engine guardrail, latency-report, planner-hint contract, model-registry/router, provider-neutral AI adapter, target-metadata, single-screenshot artifact, read-only Accessibility snapshot, and manual capture orchestration foundation only. It does not run real vision models or OCR, execute OS input, perform Accessibility actions, provide a manual capture UI, persist high-volume reflex traces to disk, provide continuous streaming capture, or make model calls required for reflex ticks.
+This is a coordination, in-memory reflex trace, hot-loop contract, deterministic dry-run skeleton, bounded target-window frame-source, cheap metadata perception, deterministic controller, local-navigation dry-run, action-engine guardrail, latency-report, planner-hint contract, model-registry/router, provider-neutral AI adapter, memory, replay/eval, target-metadata, single-screenshot artifact, read-only Accessibility snapshot, and manual capture orchestration foundation only. It does not run real vision models or OCR, execute OS input, perform Accessibility actions, provide a manual capture UI, persist high-volume reflex traces to disk, provide continuous streaming capture, or make model calls required for reflex ticks.
## Technical Guidelines
@@ -83,10 +89,14 @@ This is a coordination, in-memory reflex trace, hot-loop contract, deterministic
- Keep live OS input disabled until a later smoke slice explicitly wires a real backend. The guardrail boundary may project dry-run commands and release held state, but should not synthesize OS events.
- Use monotonic timestamps for latency math. Wall-clock timestamps are for human labels and trace correlation only.
- Use latency reports for any p50/p95/p99 claim. Reports should include dropped frames, stale actions, tick rates, and worst traces.
+- Keep local-navigation decisions typed and side-effect free until the guarded live-action slice. Metadata projectors may use window and Accessibility facts, but controllers should emit semantic actions only.
- Treat planner hints as validated, expiring advice. Controllers may use the latest valid hint, but planner output must never become direct input.
- Keep model selection in `AIModelRegistry` data. Do not scatter provider model ids through planner code.
- Keep privacy-sensitive Responses API calls configured with `store: false` unless an explicit later policy changes that default.
- Treat provider failures as sidecar failures. Missing credentials, timeout, rate limit, invalid output, or outage should leave the controller running on local state and existing valid hints.
+- Keep memory writes source-linked and scoped. Model-proposed memory writes must pass the deterministic approver before storage; target and user records require TTL or explicit durable retention.
+- Keep target memory inspectable and deleteable by target, run, user, and record id. Do not use memory JSONL as an opaque cache.
+- Promote model or prompt changes only after replay/eval records schema validity, hint acceptance, memory acceptance, latency, cost, fallback count, recovery success, docs URLs, and rollback model id.
- Keep reflex trace retention bounded. The current in-memory store is for recent status and tests, not high-volume replay persistence.
- Use sampled or summarized reflex events until a measured disk trace sink exists.
@@ -98,7 +108,7 @@ From `apps/Donkey/`:
swift test
```
-The runtime tests should cover lifecycle ordering, abort and timeout safety, latest-session queue drops, tool permission denial, event-store ordering, context compaction, reflex trace latency math, bounded in-memory reflex trace retention, reflex event publication, hot-loop contract Codable round trips, coordinate conversion, stale-signal marking, deterministic dry-run trace publication, queue-depth-1 dropped-frame counting, bounded target-window frame capture, target-frame safety and overlap refusal, target-frame no-artifact/no-encoding metadata, cheap perception signal projection, controller confidence/staleness fallback, controller p95 replay timing under 20ms, action-engine permission/focus/rate/hold/release guardrails, latency report percentiles and replay benchmark formatting, planner hint validation/expiry/latest-selection, model registry routing, OpenAI Responses request shaping and failure handling, artifact path validation, trace folder layout, JSONL event persistence, summary updates, deterministic window resolver behavior through fixture providers, candidate-list label snapshots, screenshot artifact metadata, bounded Accessibility serialization, missing Accessibility trust partial events, unsafe target refusal, overlap-sensitive capture refusal, manual capture event ordering through persisted coordinator events, and debug launch-argument parsing/formatting.
+The runtime tests should cover lifecycle ordering, abort and timeout safety, latest-session queue drops, tool permission denial, event-store ordering, context compaction, reflex trace latency math, bounded in-memory reflex trace retention, reflex event publication, hot-loop contract Codable round trips, coordinate conversion, stale-signal marking, deterministic dry-run trace publication, queue-depth-1 dropped-frame counting, bounded target-window frame capture, target-frame safety and overlap refusal, target-frame no-artifact/no-encoding metadata, cheap perception signal projection, controller confidence/staleness fallback, controller p95 replay timing under 20ms, local-navigation metadata projection and action selection, action-engine permission/focus/rate/hold/release guardrails, latency report percentiles and replay benchmark formatting, planner hint validation/expiry/latest-selection, model registry routing, OpenAI Responses request shaping and failure handling, memory approval/storage/list/delete/context snapshots, replay/eval metric aggregation and model update checklist fields, artifact path validation, trace folder layout, JSONL event persistence, summary updates, deterministic window resolver behavior through fixture providers, candidate-list label snapshots, screenshot artifact metadata, bounded Accessibility serialization, missing Accessibility trust partial events, unsafe target refusal, overlap-sensitive capture refusal, manual capture event ordering through persisted coordinator events, and debug launch-argument parsing/formatting.
Manual smoke commands:
@@ -126,8 +136,13 @@ Remaining live verification is environment-dependent. On May 16, 2026, iPhone Mi
- Cheap perception, world-state projection, deterministic controller policy, and dry-run action projection live in `apps/Donkey/Sources/DonkeyRuntime/CheapPerceptionAndController.swift`.
- Action-engine guardrails live in `apps/Donkey/Sources/DonkeyRuntime/ActionEngineGuardrails.swift`.
- Reflex latency reports and synthetic replay benchmarks live in `apps/Donkey/Sources/DonkeyRuntime/ReflexLatencyReport.swift`.
+- Local-navigation contracts live in `apps/Donkey/Sources/DonkeyContracts/LocalNavigationContracts.swift`.
+- Local-navigation metadata projection and dry-run action selection live in `apps/Donkey/Sources/DonkeyRuntime/LocalNavigationController.swift`.
- AI model registry and routing live in `apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift`.
- The first OpenAI Responses planner-hint adapter lives in `apps/Donkey/Sources/DonkeyAI/OpenAIPlannerHintAdapter.swift`.
+- Memory contracts live in `apps/Donkey/Sources/DonkeyContracts/MemoryContracts.swift`.
+- Short-term run memory and target-memory JSONL storage live in `apps/Donkey/Sources/DonkeyRuntime/RunMemoryStore.swift`.
+- Replay/eval scaffolding lives in `apps/Donkey/Sources/DonkeyAI/AIReplayEvaluation.swift`.
- Recent reflex trace retention lives in `apps/Donkey/Sources/DonkeyRuntime/InMemoryReflexTraceStore.swift`.
- macOS window resolution lives in `apps/Donkey/Sources/DonkeyRuntime/MacWindowResolver.swift`.
- Target-window screenshot capture lives in `apps/Donkey/Sources/DonkeyRuntime/WindowScreenshotCaptureService.swift`.
diff --git a/plans/master-plan.md b/plans/master-plan.md
index 744bf5e8..0f183c1f 100644
--- a/plans/master-plan.md
+++ b/plans/master-plan.md
@@ -26,14 +26,14 @@ When a supporting plan has no remaining active work, either move it to `plans/do
## Milestone Goal
-Build the first product-shaped loop where Donkey can run a target-window session with local, bounded reflex behavior and an optional slow AI sidecar:
+Build the first product-shaped loop where Donkey can run a local navigation session with bounded reflex behavior and an optional slow AI sidecar:
```text
-target window capture
- -> crop / normalize
- -> local perception or cheap template signal
+local desktop/window/browser context
+ -> focused capture / Accessibility / browser-tab metadata
+ -> local perception or cheap metadata/template signal
-> compact world state
- -> deterministic controller
+ -> deterministic navigation controller
-> dry-run action trace first, guarded live action later
-> latency report and replayable trace
@@ -50,9 +50,9 @@ The hot path must continue to work with the AI harness disabled.
## Supported Boundary
- Runtime shell: minimal run coordination, ordered events, bounded context assembly, local run artifacts, manual target context capture, in-memory reflex trace retention, and latency reports are supported.
-- Reflex hot path: typed frame/world-state/action contracts, deterministic dry-run loop, bounded target-window frame source, cheap metadata perception, deterministic controller, and dry-run action projection are supported. Live OS input is not supported.
+- Reflex hot path: typed frame/world-state/action contracts, deterministic dry-run loop, bounded target-window frame source, cheap metadata perception, deterministic controller, metadata-only local-navigation dry-run action selection, and dry-run action projection are supported. Live OS input is not supported.
- Safety boundary: action-engine command contracts, permission/focus/rate/hold/release guardrails, and replayable command traces are supported before live input.
-- Slow AI boundary: structured planner hints, validation/expiry/latest-valid selection, model registry/router, and an OpenAI Responses structured-output adapter are supported as optional sidecar pieces. The hot loop still runs without AI output.
+- Slow AI boundary: structured planner hints, validation/expiry/latest-valid selection, model registry/router, an OpenAI Responses structured-output adapter, source-linked memory, and replay/eval scaffolding are supported as optional sidecar pieces. The hot loop still runs without AI output.
- Source of truth: detailed supported behavior lives in `docs/guides/minimal-run-coordinator.md`; historical implementation details should be found with search in `docs/`, `plans/`, and git history, not duplicated here.
## Non-Negotiable Rules
@@ -68,32 +68,27 @@ The hot path must continue to work with the AI harness disabled.
## Active Queue
-1. Add short-term and target memory.
- - Build short-term run memory in process for current goal, active hints, recent states, failures, user instructions, and safety stops.
- - Add target memory as scoped, source-linked JSONL records.
- - Require TTL or deliberate durable target scope.
- - Add deterministic approval for model-proposed memory writes.
- - Make memory records inspectable and deleteable by target, run, and user scope.
+1. Finish fast local navigation dry-run closeout.
+ - Wire local-navigation metadata projection into the dry-run reflex loop instead of testing it only as a standalone projector/controller.
+ - Add browser-tab metadata where available and keep window metadata as the no-remote-model fallback.
+ - Add a swappable local perception adapter for fast inference experiments, but keep navigation working without remote models or chat LLMs.
+ - Measure metadata read, crop/resize/normalize if used, inference if used, world-state update, controller decision, and action projection separately with p50/p95/p99 latency.
+ - Keep the reflex queue latest-frame/latest-state-wins with queue depth 1, stale-result dropping, and no PNG/JPEG encode/decode in the hot path.
-2. Add replay/eval for model and prompt changes.
- - Evaluate planner hints against recorded traces before promotion.
- - Track schema validity, hint acceptance, memory write acceptance, latency, cost, fallback count, and recovery success.
- - Add a model update checklist that records `last_verified_at`, docs URLs, eval suite id, and rollback model id.
-
-3. Integrate slow planner beside the dry-run loop.
+2. Integrate slow planner beside the dry-run loop.
- Trigger planner calls on scene change, low confidence, repeated failure, goal completion, or user instruction.
- Build compact snapshots from world state, trace summaries, optional screenshots, and memory.
- Publish only validated hints to the controller.
- Prove planner latency does not move p95 reflex latency.
-4. Enable guarded live-action smoke only after dry-run closeout.
- - Pick one target and one behavior.
+3. Enable guarded live-action smoke only after dry-run closeout.
+ - Use fast local navigation as the first target behavior.
- Run end-to-end dry-run with input disabled and latency report passing.
- Enable live input only with explicit policy allowance and focus guard.
- Verify abort and timeout release held input.
- Record trace evidence for every action.
-5. Close out the primary plans.
+4. Close out the primary plans.
- Update supported behavior guides in `docs/guides/`.
- Move `plans/20-off-the-shelf-run-loop.md` to `plans/done/` when the reflex loop acceptance criteria are supported.
- Move `plans/19-ai-harness.md` to `plans/done/` when the AI harness acceptance criteria are supported.
@@ -102,16 +97,16 @@ The hot path must continue to work with the AI harness disabled.
## What Should Be Done Next
-Start with active task 1: add short-term and target memory.
+Start with active task 1: finish fast local navigation dry-run closeout.
-This is the right next slice because the current boundary has a dry-run reflex path, guardrails, latency reporting, validated planner hints, model routing, and the first slow-path adapter. It still needs scoped short-term and target memory before planner hints and future memory writes can be source-linked, inspectable, and deleteable.
+This is the right next slice because the first metadata-only local-navigation projector and controller can now choose traceable dry-run focus actions with the AI harness disabled. It still needs loop integration, browser-tab metadata where available, and measured local-navigation latency before guarded live input is considered.
## Closeout Criteria
This master plan is complete when:
-- The off-the-shelf run loop can run a selected target in dry-run mode end to end.
-- A selected first behavior can be exercised with guarded live input after dry-run success.
+- The off-the-shelf run loop can run fast local navigation in dry-run mode end to end.
+- The first local-navigation behavior can be exercised with guarded live input after dry-run success.
- Capture, perception, controller, action, and input stages are measured with monotonic timestamps.
- p50 and p95 reflex latency are reported for the first supported target.
- The hot loop still works with the AI harness disabled.