Open source CapCut alternative.
TypeScript
Replace JSONL memory with SQLite agent memory
David Le1f00bd9dddde
diff --git a/apps/Donkey/Package.swift b/apps/Donkey/Package.swiftindex dd9bdbf6..7b963aae 100644--- a/apps/Donkey/Package.swift+++ b/apps/Donkey/Package.swift@@ -30,7 +30,10 @@ let package = Package(),.target(name: "DonkeyRuntime",- dependencies: ["DonkeyContracts"]+ dependencies: ["DonkeyContracts"],+ linkerSettings: [+ .linkedLibrary("sqlite3")+ ]),.target(name: "DonkeyAI",diff --git a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swiftindex 1dbcc734..a8b8f2e2 100644--- a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift+++ b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift@@ -63,7 +63,7 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {var redactor: AIHarnessRedactorvar memoryRetriever: SemanticRunMemoryRetrievervar coordinatorRegistry: PointerPromptRunCoordinatorRegistry- var targetMemoryStore: TargetMemoryJSONLStore?+ var memoryStore: SQLiteAgentMemoryStore?var pointerCoachGuideResolver: any PointerCoachCursorGuideResolvinginit(@@ -73,7 +73,7 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {redactor: AIHarnessRedactor = AIHarnessRedactor(),memoryRetriever: SemanticRunMemoryRetriever = SemanticRunMemoryRetriever(),coordinatorRegistry: PointerPromptRunCoordinatorRegistry = PointerPromptRunCoordinatorRegistry(),- targetMemoryStore: TargetMemoryJSONLStore? = try? TargetMemoryJSONLStore(),+ memoryStore: SQLiteAgentMemoryStore? = .shared,pointerCoachGuideResolver: any PointerCoachCursorGuideResolving = ProcessBackedLocalLLMPointerCoachCursorGuideResolver()) {self.catalog = catalog@@ -83,7 +83,7 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {self.liveRunner = liveRunner ?? LocalAppTaskLiveRunner(catalog: catalog)self.redactor = redactorself.memoryRetriever = memoryRetriever- self.targetMemoryStore = targetMemoryStore+ self.memoryStore = memoryStoreself.pointerCoachGuideResolver = pointerCoachGuideResolver}@@ -98,7 +98,7 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {PointerCoachCursorGuideResolverRequest(command: command,runtimeCapabilities: Self.runtimeCapabilities(for: catalog),- cacheSnippets: LocalItemResolutionCache.shared.contextSnippets(for: command),+ cacheSnippets: memoryStore?.contextSnippets(for: command) ?? [],sourceTraceID: traceID))@@ -440,23 +440,19 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {command: String,resolution: LocalAppTaskCatalogResolution) async -> [RunMemorySemanticResult] {- guard let targetMemoryStore,- let targetID = semanticMemoryTargetID(for: resolution),- let records = try? await targetMemoryStore.records(targetID: targetID),- !records.isEmpty+ guard let memoryStore,+ let targetID = semanticMemoryTargetID(for: resolution)else {return []}- return await memoryRetriever.retrieve(- query: RunMemorySemanticQuery(+ return (try? memoryStore.search(query: AgentMemoryQuery(text: command,targetID: targetID,scope: .target,+ kinds: [.targetFact, .workflowMemory, .userInstruction],budget: RunMemoryRetrievalBudget(maxRecords: 3, maxPromptCharacters: 800)- ),- records: records- )+ ))) ?? []}private func semanticMemoryTargetID(@@ -629,7 +625,7 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {),recentEvents: context?.recentEvents ?? [],assets: context?.assets ?? [],- memory: LocalItemResolutionCache.shared.contextSnippets(for: command),+ memory: SQLiteAgentMemoryStore.shared?.contextSnippets(for: command) ?? [],policy: ["localInput": "guarded"])}diff --git a/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swift b/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swiftindex 48bf0e31..7781d3ae 100644--- a/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swift+++ b/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swift@@ -68,7 +68,7 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSinkself?.updateState = state}updateChecker.start()- LocalItemResolutionCache.shared.prewarmDefaultLocalItemsInBackground()+ SQLiteAgentMemoryStore.shared?.prewarmDefaultLocalItemsInBackground()checkForUpdates()}diff --git a/apps/Donkey/Sources/DonkeyAI/AIHarnessCompletion.swift b/apps/Donkey/Sources/DonkeyAI/AIHarnessCompletion.swiftindex 1753b4f8..fc2747a8 100644--- a/apps/Donkey/Sources/DonkeyAI/AIHarnessCompletion.swift+++ b/apps/Donkey/Sources/DonkeyAI/AIHarnessCompletion.swift@@ -169,7 +169,7 @@ public enum ProviderDecodedMemoryProposalHandler {public static func process(proposals: [RunMemoryWriteProposal],decidedAt: RunTraceTimestamp,- targetMemoryStore: TargetMemoryJSONLStore?+ memoryStore: SQLiteAgentMemoryStore?) async -> ProviderMemoryProposalProcessingResult {var decisions: [RunMemoryWriteDecision] = []var approvedCount = 0@@ -192,10 +192,9 @@ public enum ProviderDecodedMemoryProposalHandler {}approvedCount += 1- if let targetMemoryStore,- proposal.record.scope == .target {+ if let memoryStore {do {- let decision = try await targetMemoryStore.appendApprovedProposal(+ let decision = try memoryStore.appendApprovedProposal(proposal,decidedAt: decidedAt)diff --git a/apps/Donkey/Sources/DonkeyAI/OllamaPlannerHintAdapter.swift b/apps/Donkey/Sources/DonkeyAI/OllamaPlannerHintAdapter.swiftindex ceced236..106914ee 100644--- a/apps/Donkey/Sources/DonkeyAI/OllamaPlannerHintAdapter.swift+++ b/apps/Donkey/Sources/DonkeyAI/OllamaPlannerHintAdapter.swift@@ -7,16 +7,16 @@ public struct OllamaPlannerHintAdapter: Sendable {public var router: AIModelRouterpublic var httpClient: any AIHTTPClient- public var targetMemoryStore: TargetMemoryJSONLStore?+ public var memoryStore: SQLiteAgentMemoryStore?public init(router: AIModelRouter = AIModelRouter(registry: .defaultHybridPlanner),httpClient: any AIHTTPClient = URLSessionAIHTTPClient(),- targetMemoryStore: TargetMemoryJSONLStore? = try? TargetMemoryJSONLStore()+ memoryStore: SQLiteAgentMemoryStore? = .shared) {self.router = routerself.httpClient = httpClient- self.targetMemoryStore = targetMemoryStore+ self.memoryStore = memoryStore}public func generatePlannerHint(@@ -70,7 +70,7 @@ public struct OllamaPlannerHintAdapter: Sendable {let proposalProcessing = await ProviderDecodedMemoryProposalHandler.process(proposals: providerOutput.memoryWriteProposals,decidedAt: request.now,- targetMemoryStore: targetMemoryStore+ memoryStore: memoryStore)return PlannerHintAdapterResult(diff --git a/apps/Donkey/Sources/DonkeyAI/OpenAIPlannerHintAdapter.swift b/apps/Donkey/Sources/DonkeyAI/OpenAIPlannerHintAdapter.swiftindex ee271809..6d813e8f 100644--- a/apps/Donkey/Sources/DonkeyAI/OpenAIPlannerHintAdapter.swift+++ b/apps/Donkey/Sources/DonkeyAI/OpenAIPlannerHintAdapter.swift@@ -125,18 +125,18 @@ public struct OpenAIPlannerHintAdapter: Sendable {public var router: AIModelRouterpublic var httpClient: any AIHTTPClientpublic var environment: [String: String]- public var targetMemoryStore: TargetMemoryJSONLStore?+ public var memoryStore: SQLiteAgentMemoryStore?public init(router: AIModelRouter = AIModelRouter(),httpClient: any AIHTTPClient = URLSessionAIHTTPClient(),environment: [String: String] = ProcessInfo.processInfo.environment,- targetMemoryStore: TargetMemoryJSONLStore? = try? TargetMemoryJSONLStore()+ memoryStore: SQLiteAgentMemoryStore? = .shared) {self.router = routerself.httpClient = httpClientself.environment = environment- self.targetMemoryStore = targetMemoryStore+ self.memoryStore = memoryStore}public func generatePlannerHint(@@ -206,7 +206,7 @@ public struct OpenAIPlannerHintAdapter: Sendable {let proposalProcessing = await ProviderDecodedMemoryProposalHandler.process(proposals: providerOutput.memoryWriteProposals,decidedAt: request.now,- targetMemoryStore: targetMemoryStore+ memoryStore: memoryStore)return PlannerHintAdapterResult(diff --git a/apps/Donkey/Sources/DonkeyContracts/MemoryContracts.swift b/apps/Donkey/Sources/DonkeyContracts/MemoryContracts.swiftindex 0c39c226..7ac25546 100644--- a/apps/Donkey/Sources/DonkeyContracts/MemoryContracts.swift+++ b/apps/Donkey/Sources/DonkeyContracts/MemoryContracts.swift@@ -1,28 +1,33 @@import Foundation-public enum RunMemoryScope: String, Codable, Equatable, Sendable {+public enum AgentMemoryScope: String, Codable, CaseIterable, Equatable, Sendable {+ case globalcase runcase targetcase user}-public enum RunMemoryKind: String, Codable, Equatable, Sendable {+public enum AgentMemoryKind: String, Codable, CaseIterable, Equatable, Sendable {+ case localItem+ case negativeLookup+ case taskDefinition+ case targetFact+ case userInstruction+ case safetyStop+ case workflowMemorycase currentGoalcase activeHintcase recentStatecase failure- case userInstruction- case safetyStop- case targetFact}-public enum RunMemoryAuthor: String, Codable, Equatable, Sendable {+public enum AgentMemoryAuthor: String, Codable, CaseIterable, Equatable, Sendable {case deterministicRuntimecase usercase model}-public struct RunMemorySource: Codable, Equatable, Sendable {+public struct AgentMemorySource: Codable, Equatable, Sendable {public var traceID: String?public var frameID: String?public var stateID: String?@@ -63,10 +68,20 @@ public struct RunMemorySource: Codable, Equatable, Sendable {}}-public struct RunMemoryRecord: Codable, Equatable, Sendable {+public struct AgentMemoryEmbeddingMetadata: Codable, Equatable, Sendable {+ public var modelID: String+ public var dimensions: Int++ public init(modelID: String, dimensions: Int) {+ self.modelID = modelID+ self.dimensions = max(0, dimensions)+ }+}++public struct AgentMemoryRecord: Codable, Equatable, Sendable {public var id: String- public var scope: RunMemoryScope- public var kind: RunMemoryKind+ public var scope: AgentMemoryScope+ public var kind: AgentMemoryKindpublic var targetID: String?public var runID: String?public var userID: String?@@ -74,13 +89,17 @@ public struct RunMemoryRecord: Codable, Equatable, Sendable {public var createdAt: RunTraceTimestamppublic var expiresAt: RunTraceTimestamp?public var durable: Bool- public var source: RunMemorySource+ public var source: AgentMemorySourcepublic var metadata: [String: String]+ public var confidence: Double+ public var useCount: Int+ public var lastUsedAt: RunTraceTimestamp?+ public var embedding: AgentMemoryEmbeddingMetadata?public init(id: String,- scope: RunMemoryScope,- kind: RunMemoryKind,+ scope: AgentMemoryScope,+ kind: AgentMemoryKind,targetID: String? = nil,runID: String? = nil,userID: String? = nil,@@ -88,8 +107,12 @@ public struct RunMemoryRecord: Codable, Equatable, Sendable {createdAt: RunTraceTimestamp,expiresAt: RunTraceTimestamp? = nil,durable: Bool = false,- source: RunMemorySource,- metadata: [String: String] = [:]+ source: AgentMemorySource,+ metadata: [String: String] = [:],+ confidence: Double = 1,+ useCount: Int = 0,+ lastUsedAt: RunTraceTimestamp? = nil,+ embedding: AgentMemoryEmbeddingMetadata? = nil) {self.id = idself.scope = scope@@ -103,6 +126,10 @@ public struct RunMemoryRecord: Codable, Equatable, Sendable {self.durable = durableself.source = sourceself.metadata = metadata+ self.confidence = min(max(confidence, 0), 1)+ self.useCount = max(0, useCount)+ self.lastUsedAt = lastUsedAt+ self.embedding = embedding}public func isExpired(at timestamp: RunTraceTimestamp) -> Bool {@@ -115,27 +142,26 @@ public struct RunMemoryRecord: Codable, Equatable, Sendable {}}-public enum RunMemoryApprovalIssue: String, Codable, Equatable, Sendable {+public enum AgentMemoryApprovalIssue: String, Codable, CaseIterable, Equatable, Sendable {case emptyValuecase missingSourceLinkcase missingTargetIDcase missingRunIDcase missingUserIDcase missingRetention- case unsupportedScopecase sensitiveContent}-public struct RunMemoryWriteProposal: Codable, Equatable, Sendable {+public struct AgentMemoryWriteProposal: Codable, Equatable, Sendable {public var id: String- public var proposedBy: RunMemoryAuthor- public var record: RunMemoryRecord+ public var proposedBy: AgentMemoryAuthor+ public var record: AgentMemoryRecordpublic var rationale: Stringpublic init(id: String,- proposedBy: RunMemoryAuthor,- record: RunMemoryRecord,+ proposedBy: AgentMemoryAuthor,+ record: AgentMemoryRecord,rationale: String) {self.id = id@@ -145,19 +171,19 @@ public struct RunMemoryWriteProposal: Codable, Equatable, Sendable {}}-public struct RunMemoryWriteApproval: Codable, Equatable, Sendable {+public struct AgentMemoryWriteApproval: Codable, Equatable, Sendable {public var proposalID: Stringpublic var approved: Bool- public var issues: [RunMemoryApprovalIssue]+ public var issues: [AgentMemoryApprovalIssue]public var decidedAt: RunTraceTimestamppublic var approver: Stringpublic init(proposalID: String,approved: Bool,- issues: [RunMemoryApprovalIssue],+ issues: [AgentMemoryApprovalIssue],decidedAt: RunTraceTimestamp,- approver: String = "deterministic-memory-approver-v1"+ approver: String = "deterministic-agent-memory-approver-v1") {self.proposalID = proposalIDself.approved = approved@@ -167,15 +193,15 @@ public struct RunMemoryWriteApproval: Codable, Equatable, Sendable {}}-public struct RunMemoryWriteDecision: Codable, Equatable, Sendable {- public var proposal: RunMemoryWriteProposal- public var approval: RunMemoryWriteApproval- public var storedRecord: RunMemoryRecord?+public struct AgentMemoryWriteDecision: Codable, Equatable, Sendable {+ public var proposal: AgentMemoryWriteProposal+ public var approval: AgentMemoryWriteApproval+ public var storedRecord: AgentMemoryRecord?public init(- proposal: RunMemoryWriteProposal,- approval: RunMemoryWriteApproval,- storedRecord: RunMemoryRecord?+ proposal: AgentMemoryWriteProposal,+ approval: AgentMemoryWriteApproval,+ storedRecord: AgentMemoryRecord?) {self.proposal = proposalself.approval = approval@@ -188,18 +214,18 @@ public struct RunMemorySnapshot: Codable, Equatable, Sendable {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 var userInstructions: [AgentMemoryRecord]+ public var safetyStops: [AgentMemoryRecord]+ public var targetRecords: [AgentMemoryRecord]public init(currentGoal: String? = nil,activeHints: [RunPlannerHint] = [],recentStates: [RunWorldStateSummary] = [],recentFailures: [RunFailureSummary] = [],- userInstructions: [RunMemoryRecord] = [],- safetyStops: [RunMemoryRecord] = [],- targetRecords: [RunMemoryRecord] = []+ userInstructions: [AgentMemoryRecord] = [],+ safetyStops: [AgentMemoryRecord] = [],+ targetRecords: [AgentMemoryRecord] = []) {self.currentGoal = currentGoalself.activeHints = activeHints@@ -211,7 +237,7 @@ public struct RunMemorySnapshot: Codable, Equatable, Sendable {}}-public struct RunMemoryRetrievalBudget: Codable, Equatable, Sendable {+public struct AgentMemoryRetrievalBudget: Codable, Equatable, Sendable {public var maxRecords: Intpublic var maxPromptCharacters: Intpublic var minRelevance: Double@@ -227,53 +253,71 @@ public struct RunMemoryRetrievalBudget: Codable, Equatable, Sendable {}}-public struct RunMemorySemanticQuery: Codable, Equatable, Sendable {+public struct AgentMemoryQuery: Codable, Equatable, Sendable {public var text: Stringpublic var targetID: String?- public var scope: RunMemoryScope?- public var budget: RunMemoryRetrievalBudget+ public var runID: String?+ public var userID: String?+ public var scope: AgentMemoryScope?+ public var kinds: [AgentMemoryKind]+ public var budget: AgentMemoryRetrievalBudgetpublic var metadata: [String: String]public init(text: String,targetID: String? = nil,- scope: RunMemoryScope? = nil,- budget: RunMemoryRetrievalBudget = RunMemoryRetrievalBudget(),+ runID: String? = nil,+ userID: String? = nil,+ scope: AgentMemoryScope? = nil,+ kinds: [AgentMemoryKind] = [],+ budget: AgentMemoryRetrievalBudget = AgentMemoryRetrievalBudget(),metadata: [String: String] = [:]) {self.text = textself.targetID = targetID+ self.runID = runID+ self.userID = userIDself.scope = scope+ self.kinds = kindsself.budget = budgetself.metadata = metadata}}-public struct RunMemorySemanticResult: Codable, Equatable, Sendable {- public var record: RunMemoryRecord+public struct AgentMemorySearchResult: Codable, Equatable, Sendable {+ public var record: AgentMemoryRecordpublic var relevance: Doublepublic var embeddingModelID: String?+ public var lexicalScore: Double+ public var vectorScore: Double+ public var rankScore: Doublepublic var metadata: [String: String]public init(- record: RunMemoryRecord,+ record: AgentMemoryRecord,relevance: Double,embeddingModelID: String? = nil,+ lexicalScore: Double = 0,+ vectorScore: Double = 0,+ rankScore: Double? = nil,metadata: [String: String] = [:]) {self.record = recordself.relevance = min(max(relevance, 0), 1)self.embeddingModelID = embeddingModelID+ self.lexicalScore = min(max(lexicalScore, 0), 1)+ self.vectorScore = min(max(vectorScore, 0), 1)+ self.rankScore = rankScore ?? self.relevanceself.metadata = metadata}}-public enum RunMemoryApprover {+public enum AgentMemoryApprover {public static func evaluate(- _ proposal: RunMemoryWriteProposal,+ _ proposal: AgentMemoryWriteProposal,decidedAt: RunTraceTimestamp- ) -> RunMemoryWriteApproval {- var issues: [RunMemoryApprovalIssue] = []+ ) -> AgentMemoryWriteApproval {+ var issues: [AgentMemoryApprovalIssue] = []let record = proposal.recordif record.value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {@@ -289,6 +333,8 @@ public enum RunMemoryApprover {}switch record.scope {+ case .global:+ breakcase .run:if record.runID == nil {issues.append(.missingRunID)@@ -309,7 +355,7 @@ public enum RunMemoryApprover {}}- return RunMemoryWriteApproval(+ return AgentMemoryWriteApproval(proposalID: proposal.id,approved: issues.isEmpty,issues: Array(Set(issues)).sorted { $0.rawValue < $1.rawValue },@@ -332,3 +378,17 @@ public enum RunMemoryApprover {}}}++public typealias RunMemoryScope = AgentMemoryScope+public typealias RunMemoryKind = AgentMemoryKind+public typealias RunMemoryAuthor = AgentMemoryAuthor+public typealias RunMemorySource = AgentMemorySource+public typealias RunMemoryRecord = AgentMemoryRecord+public typealias RunMemoryApprovalIssue = AgentMemoryApprovalIssue+public typealias RunMemoryWriteProposal = AgentMemoryWriteProposal+public typealias RunMemoryWriteApproval = AgentMemoryWriteApproval+public typealias RunMemoryWriteDecision = AgentMemoryWriteDecision+public typealias RunMemoryRetrievalBudget = AgentMemoryRetrievalBudget+public typealias RunMemorySemanticQuery = AgentMemoryQuery+public typealias RunMemorySemanticResult = AgentMemorySearchResult+public typealias RunMemoryApprover = AgentMemoryApproverdiff --git a/apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnClassifier.swift b/apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnClassifier.swiftindex 5a3a0c05..d6c37405 100644--- a/apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnClassifier.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnClassifier.swift@@ -38,11 +38,16 @@ public struct AppHarnessTurnClassifier: Sendable {catalog _: LocalAppTaskCatalog) -> AppHarnessTurnClassification {let trimmedText = text.trimmingCharacters(in: .whitespacesAndNewlines)- let cacheCandidates = LocalItemResolutionCache.shared.search(query: trimmedText, limit: 3)+ let memoryCandidates = (try? SQLiteAgentMemoryStore.shared?.search(query: AgentMemoryQuery(+ text: trimmedText,+ scope: .global,+ kinds: [.localItem, .negativeLookup, .taskDefinition],+ budget: AgentMemoryRetrievalBudget(maxRecords: 3, maxPromptCharacters: 800, minRelevance: 0.05)+ ))) ?? []let classifierMetadata = ["classifier": "fast-local-v1",- "cache.candidateKinds": cacheCandidates.map(\.entry.kind).joined(separator: ","),- "cache.candidateNames": cacheCandidates.map(\.entry.displayName).joined(separator: ",")+ "memory.candidateKinds": memoryCandidates.map { $0.record.kind.rawValue }.joined(separator: ","),+ "memory.candidateNames": memoryCandidates.map(\.record.value).joined(separator: ",")]if let response = Self.simpleArithmeticResponse(for: trimmedText) {return AppHarnessTurnClassification(diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swiftindex df461fac..1b3d703e 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift@@ -37,7 +37,7 @@ public struct MacLocalAppAvailabilityProvider: LocalAppAvailabilityProviding {let appURL = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleIdentifier)if appURL == nil,- let cachedAvailability = LocalItemResolutionCache.shared.cachedAvailability(+ let cachedAvailability = SQLiteAgentMemoryStore.shared?.cachedAvailability(named: target.appName,preferredKind: .application) {@@ -53,7 +53,7 @@ public struct MacLocalAppAvailabilityProvider: LocalAppAvailabilityProviding {"provider": "mac-nsworkspace"])- LocalItemResolutionCache.shared.record(+ SQLiteAgentMemoryStore.shared?.record(availability: availability,query: target.appName,source: "bundleLookup"@@ -85,7 +85,7 @@ public struct MacLocalAppAvailabilityProvider: LocalAppAvailabilityProviding {)}- if let cachedAvailability = LocalItemResolutionCache.shared.cachedAvailability(+ if let cachedAvailability = SQLiteAgentMemoryStore.shared?.cachedAvailability(named: requestedName,preferredKind: preferredKind) {@@ -112,7 +112,7 @@ public struct MacLocalAppAvailabilityProvider: LocalAppAvailabilityProviding {"match": "runningApplication"])- LocalItemResolutionCache.shared.record(+ SQLiteAgentMemoryStore.shared?.record(availability: availability,query: requestedName,source: "runningApplication"@@ -130,7 +130,7 @@ public struct MacLocalAppAvailabilityProvider: LocalAppAvailabilityProviding {"requestedItemName": requestedName])- LocalItemResolutionCache.shared.record(+ SQLiteAgentMemoryStore.shared?.record(availability: availability,query: requestedName,source: "missingLookup"@@ -162,7 +162,7 @@ public struct MacLocalAppAvailabilityProvider: LocalAppAvailabilityProviding {"match": match.matchKind])- LocalItemResolutionCache.shared.record(+ SQLiteAgentMemoryStore.shared?.record(availability: availability,query: requestedName,source: match.providerdiff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskDefinitionLoader.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskDefinitionLoader.swiftindex 2fd33975..4fb259df 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskDefinitionLoader.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskDefinitionLoader.swift@@ -9,14 +9,14 @@ public enum LocalAppTaskDefinitionLoaderError: Error, Equatable, Sendable {public struct LocalAppTaskDefinitionLoader: Sendable {public var decoder: JSONDecoder- public var cache: LocalItemResolutionCache+ public var memoryStore: SQLiteAgentMemoryStore?public init(decoder: JSONDecoder = JSONDecoder(),- cache: LocalItemResolutionCache = .shared+ memoryStore: SQLiteAgentMemoryStore? = .shared) {self.decoder = decoder- self.cache = cache+ self.memoryStore = memoryStore}public static var defaultDirectoryURL: URL {@@ -57,16 +57,16 @@ public struct LocalAppTaskDefinitionLoader: Sendable {public func cachedDefinitions(from directoryURL: URL) throws -> [LocalAppTaskDefinition] {let definitions = try loadDirectory(directoryURL)- cache.prewarmTaskDefinitions(definitions)- return cache.taskDefinitions()+ memoryStore?.prewarmTaskDefinitions(definitions)+ return memoryStore?.taskDefinitions() ?? definitions}public func defaultDefinitions() -> [LocalAppTaskDefinition] {- cache.prewarmTaskDefinitions(Self.runtimeSeedDefinitions)+ memoryStore?.prewarmTaskDefinitions(Self.runtimeSeedDefinitions)if let generatedDefinitions = try? loadDirectory(Self.defaultDirectoryURL) {- cache.prewarmTaskDefinitions(generatedDefinitions)+ memoryStore?.prewarmTaskDefinitions(generatedDefinitions)}- return cache.taskDefinitions()+ return memoryStore?.taskDefinitions() ?? Self.runtimeSeedDefinitions}public static var runtimeSeedDefinitions: [LocalAppTaskDefinition] {diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalItemResolutionCache.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalItemResolutionCache.swiftdeleted file mode 100644index e71f9ecf..00000000--- a/apps/Donkey/Sources/DonkeyRuntime/LocalItemResolutionCache.swift+++ /dev/null@@ -1,739 +0,0 @@-import AppKit-import DonkeyContracts-import Foundation--public struct LocalItemResolutionCacheEntry: Codable, Equatable, Sendable {- public var id: String- public var query: String- public var normalizedQuery: String- public var displayName: String- public var normalizedDisplayName: String- public var kind: String- public var path: String?- public var bundleIdentifier: String?- public var isAvailable: Bool- public var source: String- public var match: String- public var firstResolvedAt: String- public var lastResolvedAt: String- public var useCount: Int- public var metadata: [String: String]- public var searchText: String-}--public struct LocalItemResolutionCacheSearchResult: Equatable, Sendable {- public var entry: LocalItemResolutionCacheEntry- public var score: Int-}--public struct LocalItemResolutionCachePrewarmOptions: Sendable {- public var applicationRoots: [URL]- public var fileRoots: [URL]- public var maxItemsPerRoot: Int-- public init(- applicationRoots: [URL],- fileRoots: [URL],- maxItemsPerRoot: Int = 600- ) {- self.applicationRoots = applicationRoots- self.fileRoots = fileRoots- self.maxItemsPerRoot = max(0, maxItemsPerRoot)- }-- public static func defaults() -> LocalItemResolutionCachePrewarmOptions {- let homeDirectory = FileManager.default.homeDirectoryForCurrentUser- return LocalItemResolutionCachePrewarmOptions(- applicationRoots: [- URL(fileURLWithPath: "/Applications", isDirectory: true),- URL(fileURLWithPath: "/Applications/Utilities", isDirectory: true),- URL(fileURLWithPath: "/System/Applications", isDirectory: true),- URL(fileURLWithPath: "/System/Applications/Utilities", isDirectory: true),- homeDirectory.appendingPathComponent("Applications", isDirectory: true)- ],- fileRoots: [- homeDirectory.appendingPathComponent("Desktop", isDirectory: true),- homeDirectory.appendingPathComponent("Documents", isDirectory: true),- homeDirectory.appendingPathComponent("Downloads", isDirectory: true)- ]- )- }-}--public final class LocalItemResolutionCache: @unchecked Sendable {- public static let shared = LocalItemResolutionCache()-- public static var defaultStoreURL: URL {- let applicationSupport = FileManager.default.urls(- for: .applicationSupportDirectory,- in: .userDomainMask- ).first ?? FileManager.default.homeDirectoryForCurrentUser- .appendingPathComponent("Library/Application Support", isDirectory: true)-- return applicationSupport- .appendingPathComponent("Donkey", isDirectory: true)- .appendingPathComponent("LocalItemResolutionCache", isDirectory: true)- .appendingPathComponent("local-item-cache.jsonl")- }-- private let storeURL: URL- private let lock = NSLock()- private var entriesByID: [String: LocalItemResolutionCacheEntry]- private var isPrewarming = false-- public init(storeURL: URL = LocalItemResolutionCache.defaultStoreURL) {- self.storeURL = storeURL- self.entriesByID = Self.loadEntries(from: storeURL)- }-- public func prewarmDefaultLocalItemsInBackground(- options: LocalItemResolutionCachePrewarmOptions = .defaults()- ) {- lock.lock()- guard !isPrewarming else {- lock.unlock()- return- }- isPrewarming = true- lock.unlock()-- Task.detached(priority: .utility) { [self] in- prewarmDefaultLocalItems(options: options)- finishPrewarming()- }- }-- public func prewarmDefaultLocalItems(- options: LocalItemResolutionCachePrewarmOptions = .defaults()- ) {- guard options.maxItemsPerRoot > 0 else { return }-- var entries: [LocalItemResolutionCacheEntry] = []- entries.append(contentsOf: prewarmEntries(- roots: options.applicationRoots,- allowedKinds: [.application],- maxItemsPerRoot: options.maxItemsPerRoot- ))- entries.append(contentsOf: prewarmEntries(- roots: options.fileRoots,- allowedKinds: [.folder, .file, .other],- maxItemsPerRoot: options.maxItemsPerRoot- ))- upsert(entries)- }-- public func prewarmTaskDefinitions(_ definitions: [LocalAppTaskDefinition]) {- upsert(definitions.map(Self.entry(taskDefinition:)))- }-- public func taskDefinitions() -> [LocalAppTaskDefinition] {- snapshotEntries()- .filter { $0.kind == Self.taskDefinitionKind && $0.isAvailable }- .compactMap(Self.taskDefinition(from:))- .sorted { lhs, rhs in- if lhs.taskType == rhs.taskType {- return lhs.targetApp.appName < rhs.targetApp.appName- }- return lhs.taskType < rhs.taskType- }- }-- public func record(- availability: LocalAppAvailability,- query: String,- source: String- ) {- upsert([Self.entry(availability: availability, query: query, source: source)])- }-- public func search(- query: String,- limit: Int = 5- ) -> [LocalItemResolutionCacheSearchResult] {- let lookupQuery = Self.lookupQuery(from: query)- guard !lookupQuery.isEmpty, limit > 0 else { return [] }-- let snapshot = snapshotEntries()- guard !snapshot.isEmpty else { return [] }-- let grepIDs = grepCandidateIDs(for: lookupQuery)- let grepCandidates: [LocalItemResolutionCacheEntry]- if let grepIDs, !grepIDs.isEmpty {- grepCandidates = snapshot.filter { grepIDs.contains($0.id) }- } else {- grepCandidates = snapshot- }-- let scored = Self.scoredResults(- entries: grepCandidates,- query: lookupQuery- )- if !scored.isEmpty {- return Array(scored.prefix(limit))- }-- return Array(Self.scoredResults(entries: snapshot, query: lookupQuery).prefix(limit))- }-- public func contextSnippets(- for query: String,- limit: Int = 4- ) -> [String] {- search(query: query, limit: limit).map { result in- let entry = result.entry- let status = entry.isAvailable ? "available" : "missing"- let path = entry.path.map { " path=\($0)" } ?? ""- let bundleIdentifier = entry.bundleIdentifier.map { " bundleIdentifier=\($0)" } ?? ""- let metadata = Self.snippetMetadata(entry.metadata)- return "local_resolution_cache: query=\"\(entry.query)\" status=\(status) name=\"\(entry.displayName)\" kind=\(entry.kind)\(path)\(bundleIdentifier) source=\(entry.source) match=\(entry.match) score=\(result.score)\(metadata)"- }- }-- func cachedAvailability(- named itemName: String,- preferredKind: LocalItemKind?- ) -> LocalAppAvailability? {- let requestedName = LocalAppLookup.cleanedLookupName(itemName)- guard !requestedName.isEmpty else { return nil }-- guard let result = search(query: requestedName, limit: 8).first(where: { result in- guard result.entry.isAvailable else { return false }- guard result.entry.kind != Self.taskDefinitionKind else { return false }- if let preferredKind {- return result.entry.kind == preferredKind.rawValue- }- return true- }) else {- return nil- }-- let entry = result.entry- let appURL = existingURL(for: entry)- guard appURL != nil || entry.bundleIdentifier != nil else { return nil }-- var metadata = entry.metadata- metadata["provider"] = "local-resolution-cache"- metadata["cache.id"] = entry.id- metadata["cache.source"] = entry.source- metadata["cache.match"] = entry.match- metadata["cache.score"] = String(result.score)- metadata["requestedItemName"] = requestedName- metadata["itemKind"] = entry.kind- metadata["itemURL"] = appURL?.path ?? entry.path ?? ""- metadata["bundleIdentifier"] = entry.bundleIdentifier ?? metadata["bundleIdentifier"] ?? ""- metadata["match"] = "cache"-- var targetMetadata = [- "localItem.kind": entry.kind,- "localItem.path": appURL?.path ?? entry.path ?? ""- ]- if let defaultApplication = metadata["defaultApplication"], !defaultApplication.isEmpty {- targetMetadata["localItem.defaultApplication"] = defaultApplication- }-- markUsed(entryID: entry.id)-- return LocalAppAvailability(- target: LocalAppTarget(- appName: entry.displayName,- bundleIdentifier: entry.bundleIdentifier,- titleContains: entry.displayName,- metadata: targetMetadata- ),- isInstalled: true,- appURL: appURL,- metadata: metadata- )- }-- private func prewarmEntries(- roots: [URL],- allowedKinds: Set<LocalItemKind>,- maxItemsPerRoot: Int- ) -> [LocalItemResolutionCacheEntry] {- var entries: [LocalItemResolutionCacheEntry] = []- for root in roots where FileManager.default.fileExists(atPath: root.path) {- guard let enumerator = FileManager.default.enumerator(- at: root,- includingPropertiesForKeys: [.isDirectoryKey, .contentModificationDateKey],- options: [.skipsHiddenFiles, .skipsPackageDescendants]- ) else {- continue- }-- var rootCount = 0- for case let itemURL as URL in enumerator {- let kind = LocalItemKind(url: itemURL)- guard allowedKinds.contains(kind) else { continue }-- entries.append(Self.entry(- url: itemURL,- query: Self.displayName(for: itemURL, kind: kind),- kind: kind,- source: "prewarm",- match: "prewarm",- metadata: [- "prewarm.root": root.path,- "parentDirectory": itemURL.deletingLastPathComponent().lastPathComponent,- "fileExtension": itemURL.pathExtension- ]- ))- rootCount += 1- if rootCount >= maxItemsPerRoot { break }- }- }- return entries- }-- private func upsert(_ entries: [LocalItemResolutionCacheEntry]) {- guard !entries.isEmpty else { return }-- lock.lock()- for entry in entries {- if var existing = entriesByID[entry.id] {- existing.query = entry.query- existing.normalizedQuery = entry.normalizedQuery- existing.displayName = entry.displayName- existing.normalizedDisplayName = entry.normalizedDisplayName- existing.kind = entry.kind- existing.path = entry.path- existing.bundleIdentifier = entry.bundleIdentifier- existing.isAvailable = entry.isAvailable- existing.source = entry.source- existing.match = entry.match- existing.lastResolvedAt = entry.lastResolvedAt- existing.useCount += max(1, entry.useCount)- existing.metadata = existing.metadata.merging(entry.metadata) { _, new in new }- existing.searchText = entry.searchText- entriesByID[entry.id] = existing- } else {- entriesByID[entry.id] = entry- }- }- persistLocked()- lock.unlock()- }-- private func markUsed(entryID: String) {- lock.lock()- if var entry = entriesByID[entryID] {- entry.useCount += 1- entry.lastResolvedAt = Self.timestamp()- entriesByID[entryID] = entry- persistLocked()- }- lock.unlock()- }-- private func snapshotEntries() -> [LocalItemResolutionCacheEntry] {- lock.lock()- let entries = Array(entriesByID.values)- lock.unlock()- return entries- }-- private func persistLocked() {- do {- try FileManager.default.createDirectory(- at: storeURL.deletingLastPathComponent(),- withIntermediateDirectories: true- )- let encoder = JSONEncoder()- encoder.outputFormatting = [.sortedKeys]- let text = try entriesByID.values- .sorted { lhs, rhs in- if lhs.kind == rhs.kind {- return lhs.normalizedDisplayName < rhs.normalizedDisplayName- }- return lhs.kind < rhs.kind- }- .map { entry in- let data = try encoder.encode(entry)- return String(decoding: data, as: UTF8.self)- }- .joined(separator: "\n")- try (text + "\n").write(to: storeURL, atomically: true, encoding: .utf8)- } catch {- return- }- }-- private func grepCandidateIDs(for query: String) -> Set<String>? {- guard FileManager.default.fileExists(atPath: storeURL.path) else { return nil }-- let token = query- .components(separatedBy: .whitespacesAndNewlines)- .filter { !$0.isEmpty }- .max(by: { $0.count < $1.count })- ?? query- guard !token.isEmpty else { return nil }-- let process = Process()- process.executableURL = URL(fileURLWithPath: "/usr/bin/grep")- process.arguments = ["-i", "-F", token, storeURL.path]-- let output = Pipe()- process.standardOutput = output- process.standardError = Pipe()-- do {- try process.run()- } catch {- return nil- }- process.waitUntilExit()-- let data = output.fileHandleForReading.readDataToEndOfFile()- guard let text = String(data: data, encoding: .utf8) else { return nil }-- let decoder = JSONDecoder()- return Set(text.split(whereSeparator: \.isNewline).compactMap { line in- try? decoder.decode(LocalItemResolutionCacheEntry.self, from: Data(line.utf8)).id- })- }-- private func existingURL(for entry: LocalItemResolutionCacheEntry) -> URL? {- if let path = entry.path {- let url = URL(fileURLWithPath: path)- if FileManager.default.fileExists(atPath: url.path) {- return url- }- }-- guard let bundleIdentifier = entry.bundleIdentifier else { return nil }- return NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleIdentifier)- }-- private func finishPrewarming() {- lock.lock()- isPrewarming = false- lock.unlock()- }-- private static func scoredResults(- entries: [LocalItemResolutionCacheEntry],- query: String- ) -> [LocalItemResolutionCacheSearchResult] {- let tokens = Set(query.split(separator: " ").map(String.init))- return entries- .compactMap { entry -> LocalItemResolutionCacheSearchResult? in- guard let score = score(entry: entry, query: query, tokens: tokens) else {- return nil- }- return LocalItemResolutionCacheSearchResult(entry: entry, score: score)- }- .sorted { lhs, rhs in- if lhs.score == rhs.score {- if lhs.entry.isAvailable == rhs.entry.isAvailable {- return lhs.entry.useCount > rhs.entry.useCount- }- return lhs.entry.isAvailable && !rhs.entry.isAvailable- }- return lhs.score < rhs.score- }- }-- private static func score(- entry: LocalItemResolutionCacheEntry,- query: String,- tokens: Set<String>- ) -> Int? {- let normalizedDisplayName = entry.normalizedDisplayName- let normalizedQuery = entry.normalizedQuery- let searchText = LocalAppLookup.normalized(entry.searchText)-- if normalizedDisplayName == query || normalizedQuery == query {- return entry.isAvailable ? 0 : 30- }- if normalizedDisplayName.hasPrefix(query) {- return entry.isAvailable ? 4 : 34- }- if normalizedDisplayName.contains(" \(query)") || normalizedDisplayName.contains(query) {- return entry.isAvailable ? 8 : 38- }-- let matchedTokenCount = tokens.filter { searchText.contains($0) }.count- guard matchedTokenCount > 0 else { return nil }-- let missingPenalty = entry.isAvailable ? 0 : 40- return missingPenalty + 60 - min(30, matchedTokenCount * 10) + max(0, normalizedDisplayName.count - query.count)- }-- private static func entry(- availability: LocalAppAvailability,- query: String,- source: String- ) -> LocalItemResolutionCacheEntry {- let kind = availability.metadata["itemKind"]- ?? availability.target.metadata["localItem.kind"]- ?? (availability.target.bundleIdentifier == nil ? "unknown" : LocalItemKind.application.rawValue)- let path = availability.metadata["itemURL"]- ?? availability.target.metadata["localItem.path"]- ?? availability.appURL?.path- let bundleIdentifier = availability.metadata["bundleIdentifier"]- ?? availability.target.bundleIdentifier- let displayName = availability.target.appName- let match = availability.metadata["match"]- ?? availability.metadata["reason"]- ?? (availability.isInstalled ? "resolved" : "missing")-- var metadata = availability.metadata- metadata["recordedQuery"] = query-- return LocalItemResolutionCacheEntry(- id: id(- kind: kind,- path: path,- bundleIdentifier: bundleIdentifier,- displayName: displayName,- query: query,- isAvailable: availability.isInstalled- ),- query: query,- normalizedQuery: lookupQuery(from: query),- displayName: displayName,- normalizedDisplayName: LocalAppLookup.normalized(displayName),- kind: kind,- path: path?.isEmpty == false ? path : nil,- bundleIdentifier: bundleIdentifier?.isEmpty == false ? bundleIdentifier : nil,- isAvailable: availability.isInstalled,- source: source,- match: match,- firstResolvedAt: timestamp(),- lastResolvedAt: timestamp(),- useCount: 1,- metadata: metadata,- searchText: searchText(- query: query,- displayName: displayName,- kind: kind,- path: path,- bundleIdentifier: bundleIdentifier,- metadata: metadata- )- )- }-- private static func entry(- url: URL,- query: String,- kind: LocalItemKind,- source: String,- match: String,- metadata: [String: String]- ) -> LocalItemResolutionCacheEntry {- let displayName = displayName(for: url, kind: kind)- let bundleIdentifier = kind == .application ? Bundle(url: url)?.bundleIdentifier : nil- var entryMetadata = metadata- entryMetadata["itemKind"] = kind.rawValue- entryMetadata["itemURL"] = url.path- entryMetadata["bundleIdentifier"] = bundleIdentifier ?? ""-- return LocalItemResolutionCacheEntry(- id: id(- kind: kind.rawValue,- path: url.path,- bundleIdentifier: bundleIdentifier,- displayName: displayName,- query: query,- isAvailable: true- ),- query: query,- normalizedQuery: lookupQuery(from: query),- displayName: displayName,- normalizedDisplayName: LocalAppLookup.normalized(displayName),- kind: kind.rawValue,- path: url.path,- bundleIdentifier: bundleIdentifier,- isAvailable: true,- source: source,- match: match,- firstResolvedAt: timestamp(),- lastResolvedAt: timestamp(),- useCount: 1,- metadata: entryMetadata,- searchText: searchText(- query: query,- displayName: displayName,- kind: kind.rawValue,- path: url.path,- bundleIdentifier: bundleIdentifier,- metadata: entryMetadata- )- )- }-- private static func entry(taskDefinition definition: LocalAppTaskDefinition) -> LocalItemResolutionCacheEntry {- let entityText = definition.entityRules- .map(\.name)- .joined(separator: " ")- let workflowText = definition.workflowSteps- .flatMap { step in [step.id, step.role.rawValue, step.summary] + step.metadata.flatMap { [$0.key, $0.value] } }- .joined(separator: " ")- var metadata = definition.metadata- metadata["taskType"] = definition.taskType- metadata["targetApp"] = definition.targetApp.appName- metadata["bundleIdentifier"] = definition.targetApp.bundleIdentifier ?? ""- metadata["entityNames"] = definition.entityRules.map(\.name).joined(separator: ",")- metadata["observationStrategies"] = definition.observationStrategies.map(\.rawValue).joined(separator: ",")- metadata["verificationEntityName"] = definition.verificationEntityName ?? ""-- if let encodedDefinition = encodedTaskDefinition(definition) {- metadata[Self.taskDefinitionJSONMetadataKey] = encodedDefinition- }-- return LocalItemResolutionCacheEntry(- id: "task-definition:\(definition.taskType)",- query: definition.taskType,- normalizedQuery: lookupQuery(from: definition.taskType),- displayName: Self.displayTitle(for: definition),- normalizedDisplayName: LocalAppLookup.normalized(Self.displayTitle(for: definition)),- kind: Self.taskDefinitionKind,- path: nil,- bundleIdentifier: definition.targetApp.bundleIdentifier,- isAvailable: true,- source: "task-definition-prewarm",- match: "capability",- firstResolvedAt: timestamp(),- lastResolvedAt: timestamp(),- useCount: 1,- metadata: metadata,- searchText: searchText(- query: definition.taskType,- displayName: Self.displayTitle(for: definition),- kind: Self.taskDefinitionKind,- path: nil,- bundleIdentifier: definition.targetApp.bundleIdentifier,- metadata: metadata.merging([- "taskText": "\(definition.taskType) \(entityText) \(workflowText)",- "targetAppTitle": definition.targetApp.titleContains ?? definition.targetApp.appName- ]) { current, _ in current }- )- )- }-- private static func encodedTaskDefinition(_ definition: LocalAppTaskDefinition) -> String? {- let encoder = JSONEncoder()- encoder.outputFormatting = [.sortedKeys]- guard let data = try? encoder.encode(definition) else { return nil }- return String(data: data, encoding: .utf8)- }-- private static func taskDefinition(from entry: LocalItemResolutionCacheEntry) -> LocalAppTaskDefinition? {- guard let encodedDefinition = entry.metadata[taskDefinitionJSONMetadataKey],- let data = encodedDefinition.data(using: .utf8)- else {- return nil- }- return try? JSONDecoder().decode(LocalAppTaskDefinition.self, from: data)- }-- private static func loadEntries(from storeURL: URL) -> [String: LocalItemResolutionCacheEntry] {- guard let text = try? String(contentsOf: storeURL, encoding: .utf8) else { return [:] }-- let decoder = JSONDecoder()- let entries = text- .split(whereSeparator: \.isNewline)- .compactMap { line in- try? decoder.decode(LocalItemResolutionCacheEntry.self, from: Data(line.utf8))- }- return Dictionary(uniqueKeysWithValues: entries.map { ($0.id, $0) })- }-- private static func id(- kind: String,- path: String?,- bundleIdentifier: String?,- displayName: String,- query: String,- isAvailable: Bool- ) -> String {- if !isAvailable {- return "missing:\(lookupQuery(from: query))"- }- if let bundleIdentifier, !bundleIdentifier.isEmpty {- return "\(kind):bundle:\(bundleIdentifier)"- }- if let path, !path.isEmpty {- return "\(kind):path:\(path)"- }- return "\(kind):name:\(LocalAppLookup.normalized(displayName))"- }-- private static func searchText(- query: String,- displayName: String,- kind: String,- path: String?,- bundleIdentifier: String?,- metadata: [String: String]- ) -> String {- (- [- query,- displayName,- LocalAppLookup.normalized(displayName),- kind,- path ?? "",- bundleIdentifier ?? ""- ] + metadata- .filter { $0.key != Self.taskDefinitionJSONMetadataKey }- .sorted { $0.key < $1.key }- .flatMap { [$0.key, $0.value] }- )- .filter { !$0.isEmpty }- .joined(separator: " ")- }-- private static func snippetMetadata(_ metadata: [String: String]) -> String {- let allowedKeys = [- "taskType",- "targetApp",- "itemKind",- "defaultApplication",- "entityNames",- "verificationMode",- "automationBackend",- "appleScript.action",- "screenshotFallback"- ]- let pairs = allowedKeys.compactMap { key -> String? in- guard let value = metadata[key], !value.isEmpty else { return nil }- return "\(key)=\(value)"- }- guard !pairs.isEmpty else { return "" }- return " metadata={\(pairs.joined(separator: ","))}"- }-- private static func lookupQuery(from query: String) -> String {- LocalAppLookup.cleanedLookupName(query)- }-- private static let taskDefinitionKind = "taskDefinition"- private static let taskDefinitionJSONMetadataKey = "taskDefinitionJSON"-- private static func displayName(for url: URL, kind: LocalItemKind) -> String {- if kind == .application,- let bundle = Bundle(url: url) {- return bundle.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String- ?? bundle.object(forInfoDictionaryKey: "CFBundleName") as? String- ?? url.deletingPathExtension().lastPathComponent- }-- return url.lastPathComponent- }-- private static func displayTitle(for definition: LocalAppTaskDefinition) -> String {- if let displayTitle = definition.metadata["displayTitle"], !displayTitle.isEmpty {- return displayTitle- }- return definition.taskType- .split(separator: "_")- .map { word in word.prefix(1).uppercased() + word.dropFirst() }- .joined(separator: " ")- }-- private static func timestamp() -> String {- ISO8601DateFormatter().string(from: Date())- }-}diff --git a/apps/Donkey/Sources/DonkeyRuntime/RunMemoryStore.swift b/apps/Donkey/Sources/DonkeyRuntime/RunMemoryStore.swiftindex 5f4eaa36..c8d7f9ec 100644--- a/apps/Donkey/Sources/DonkeyRuntime/RunMemoryStore.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/RunMemoryStore.swift@@ -1,12 +1,6 @@import DonkeyContractsimport Foundation-public enum TargetMemoryStoreError: Error, Equatable, Sendable {- case invalidIdentifier(String)- case missingScopeTarget- case writeNotApproved([RunMemoryApprovalIssue])-}-public actor InMemoryRunMemory {private let runID: Stringprivate let targetID: String@@ -74,202 +68,6 @@ public actor InMemoryRunMemory {}}-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 indiff --git a/apps/Donkey/Sources/DonkeyRuntime/SQLiteAgentMemoryStore.swift b/apps/Donkey/Sources/DonkeyRuntime/SQLiteAgentMemoryStore.swiftnew file mode 100644index 00000000..b6390c6f--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/SQLiteAgentMemoryStore.swift@@ -0,0 +1,1262 @@+import AppKit+import DonkeyContracts+import Foundation+import SQLite3++public enum AgentMemoryStoreError: Error, Equatable, Sendable {+ case openFailed(String)+ case sqliteFailure(String)+ case invalidIdentifier(String)+ case missingRequiredScope+}++public protocol AgentMemoryEmbeddingProviding: Sendable {+ var modelID: String { get }+ var dimensions: Int { get }+ func embedding(for text: String) -> [Float]+}++public struct HashingAgentMemoryEmbeddingProvider: AgentMemoryEmbeddingProviding {+ public let modelID = "local-hashing-agent-memory-embedding-v1"+ public let dimensions: Int++ public init(dimensions: Int = 256) {+ self.dimensions = max(1, dimensions)+ }++ public func embedding(for text: String) -> [Float] {+ var vector = Array(repeating: Float(0), count: dimensions)+ for token in Self.tokens(in: text) {+ let index = Int(Self.fnv1a(token) % UInt64(dimensions))+ vector[index] += 1+ }+ let magnitude = sqrt(vector.reduce(Float(0)) { $0 + $1 * $1 })+ guard magnitude > 0 else { return vector }+ return vector.map { $0 / magnitude }+ }++ static func tokens(in text: String) -> [String] {+ text+ .lowercased()+ .split { !$0.isLetter && !$0.isNumber }+ .map(String.init)+ }++ private static func fnv1a(_ token: String) -> UInt64 {+ var hash: UInt64 = 14_695_981_039_346_656_037+ for byte in token.utf8 {+ hash ^= UInt64(byte)+ hash &*= 1_099_511_628_211+ }+ return hash+ }+}++public struct AgentMemoryPrewarmOptions: Sendable {+ public var applicationRoots: [URL]+ public var fileRoots: [URL]+ public var maxItemsPerRoot: Int++ public init(+ applicationRoots: [URL],+ fileRoots: [URL],+ maxItemsPerRoot: Int = 600+ ) {+ self.applicationRoots = applicationRoots+ self.fileRoots = fileRoots+ self.maxItemsPerRoot = max(0, maxItemsPerRoot)+ }++ public static func defaults() -> AgentMemoryPrewarmOptions {+ let homeDirectory = FileManager.default.homeDirectoryForCurrentUser+ return AgentMemoryPrewarmOptions(+ applicationRoots: [+ URL(fileURLWithPath: "/Applications", isDirectory: true),+ URL(fileURLWithPath: "/Applications/Utilities", isDirectory: true),+ URL(fileURLWithPath: "/System/Applications", isDirectory: true),+ URL(fileURLWithPath: "/System/Applications/Utilities", isDirectory: true),+ homeDirectory.appendingPathComponent("Applications", isDirectory: true)+ ],+ fileRoots: [+ homeDirectory.appendingPathComponent("Desktop", isDirectory: true),+ homeDirectory.appendingPathComponent("Documents", isDirectory: true),+ homeDirectory.appendingPathComponent("Downloads", isDirectory: true)+ ]+ )+ }+}++public final class SQLiteAgentMemoryStore: @unchecked Sendable {+ public static let shared: SQLiteAgentMemoryStore? = try? SQLiteAgentMemoryStore()++ private let baseDirectory: URL+ private let storeURL: URL+ private let fileManager: FileManager+ private let embeddingProvider: any AgentMemoryEmbeddingProviding+ private let lock = NSRecursiveLock()+ private var db: OpaquePointer?+ private var isPrewarming = false++ public init(+ baseDirectory: URL? = nil,+ fileManager: FileManager = .default,+ embeddingProvider: any AgentMemoryEmbeddingProviding = HashingAgentMemoryEmbeddingProvider(),+ cleanupLegacyStores: Bool = true,+ legacyDonkeyDirectory: URL? = nil+ ) throws {+ self.fileManager = fileManager+ self.embeddingProvider = embeddingProvider+ let usingDefaultDirectory = baseDirectory == nil+ let resolvedBaseDirectory = try baseDirectory ?? Self.defaultBaseDirectory(fileManager: fileManager)+ self.baseDirectory = resolvedBaseDirectory+ self.storeURL = resolvedBaseDirectory.appendingPathComponent("agent-memory.sqlite", isDirectory: false)++ try fileManager.createDirectory(at: resolvedBaseDirectory, withIntermediateDirectories: true)+ if cleanupLegacyStores && (usingDefaultDirectory || legacyDonkeyDirectory != nil) {+ Self.deleteLegacyStores(fileManager: fileManager, donkeyDirectoryOverride: legacyDonkeyDirectory)+ }++ guard sqlite3_open_v2(storeURL.path, &db, SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE | SQLITE_OPEN_FULLMUTEX, nil) == SQLITE_OK else {+ throw AgentMemoryStoreError.openFailed(Self.message(from: db))+ }++ do {+ try configure()+ try createSchema()+ } catch {+ sqlite3_close(db)+ db = nil+ throw error+ }+ }++ deinit {+ if let db {+ sqlite3_close(db)+ }+ }++ 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("AgentMemory", isDirectory: true)+ }++ public func upsert(_ record: AgentMemoryRecord) throws {+ let searchText = Self.searchText(for: record)+ let vector = embeddingProvider.embedding(for: searchText)+ var storedRecord = record+ storedRecord.embedding = AgentMemoryEmbeddingMetadata(+ modelID: embeddingProvider.modelID,+ dimensions: vector.count+ )+ let recordJSON = String(decoding: try Self.encoder().encode(storedRecord), as: UTF8.self)++ lock.lock()+ defer { lock.unlock() }+ try transaction {+ let sql = """+ INSERT INTO memory_records (+ id, scope, kind, target_id, run_id, user_id, value,+ created_wall, created_uptime_ns, expires_wall, expires_uptime_ns,+ durable, source_json, metadata_json, confidence, use_count,+ last_used_wall, last_used_uptime_ns, search_text, record_json,+ embedding_model_id, embedding_dimensions, updated_wall+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ ON CONFLICT(id) DO UPDATE SET+ scope=excluded.scope,+ kind=excluded.kind,+ target_id=excluded.target_id,+ run_id=excluded.run_id,+ user_id=excluded.user_id,+ value=excluded.value,+ created_wall=excluded.created_wall,+ created_uptime_ns=excluded.created_uptime_ns,+ expires_wall=excluded.expires_wall,+ expires_uptime_ns=excluded.expires_uptime_ns,+ durable=excluded.durable,+ source_json=excluded.source_json,+ metadata_json=excluded.metadata_json,+ confidence=excluded.confidence,+ use_count=max(memory_records.use_count, excluded.use_count),+ last_used_wall=excluded.last_used_wall,+ last_used_uptime_ns=excluded.last_used_uptime_ns,+ search_text=excluded.search_text,+ record_json=excluded.record_json,+ embedding_model_id=excluded.embedding_model_id,+ embedding_dimensions=excluded.embedding_dimensions,+ updated_wall=excluded.updated_wall+ """+ let sourceJSON = String(decoding: try Self.encoder().encode(storedRecord.source), as: UTF8.self)+ let metadataJSON = String(decoding: try Self.encoder().encode(storedRecord.metadata), as: UTF8.self)+ try withStatement(sql) { statement in+ bind(storedRecord.id, to: statement, index: 1)+ bind(storedRecord.scope.rawValue, to: statement, index: 2)+ bind(storedRecord.kind.rawValue, to: statement, index: 3)+ bind(storedRecord.targetID, to: statement, index: 4)+ bind(storedRecord.runID, to: statement, index: 5)+ bind(storedRecord.userID, to: statement, index: 6)+ bind(storedRecord.value, to: statement, index: 7)+ bind(storedRecord.createdAt.wallClock.timeIntervalSince1970, to: statement, index: 8)+ bind(Int64(clamping: storedRecord.createdAt.monotonicUptimeNanoseconds), to: statement, index: 9)+ bind(storedRecord.expiresAt?.wallClock.timeIntervalSince1970, to: statement, index: 10)+ bind(storedRecord.expiresAt.map { Int64(clamping: $0.monotonicUptimeNanoseconds) }, to: statement, index: 11)+ bind(storedRecord.durable ? 1 : 0, to: statement, index: 12)+ bind(sourceJSON, to: statement, index: 13)+ bind(metadataJSON, to: statement, index: 14)+ bind(storedRecord.confidence, to: statement, index: 15)+ bind(Int64(storedRecord.useCount), to: statement, index: 16)+ bind(storedRecord.lastUsedAt?.wallClock.timeIntervalSince1970, to: statement, index: 17)+ bind(storedRecord.lastUsedAt.map { Int64(clamping: $0.monotonicUptimeNanoseconds) }, to: statement, index: 18)+ bind(searchText, to: statement, index: 19)+ bind(recordJSON, to: statement, index: 20)+ bind(embeddingProvider.modelID, to: statement, index: 21)+ bind(Int64(vector.count), to: statement, index: 22)+ bind(Date().timeIntervalSince1970, to: statement, index: 23)+ try stepDone(statement)+ }++ try deleteFTSAndEmbedding(recordID: storedRecord.id)+ try withStatement("INSERT INTO memory_fts(id, search_text, value) VALUES (?, ?, ?)") { statement in+ bind(storedRecord.id, to: statement, index: 1)+ bind(searchText, to: statement, index: 2)+ bind(storedRecord.value, to: statement, index: 3)+ try stepDone(statement)+ }+ try withStatement("INSERT INTO memory_embeddings(record_id, embedding_model_id, dimensions, vector) VALUES (?, ?, ?, ?)") { statement in+ bind(storedRecord.id, to: statement, index: 1)+ bind(embeddingProvider.modelID, to: statement, index: 2)+ bind(Int64(vector.count), to: statement, index: 3)+ bind(Self.vectorData(vector), to: statement, index: 4)+ try stepDone(statement)+ }+ }+ }++ @discardableResult+ public func appendApprovedProposal(+ _ proposal: AgentMemoryWriteProposal,+ decidedAt: RunTraceTimestamp+ ) throws -> AgentMemoryWriteDecision {+ let approval = AgentMemoryApprover.evaluate(proposal, decidedAt: decidedAt)+ guard approval.approved else {+ return AgentMemoryWriteDecision(proposal: proposal, approval: approval, storedRecord: nil)+ }+ try upsert(proposal.record)+ return AgentMemoryWriteDecision(proposal: proposal, approval: approval, storedRecord: proposal.record)+ }++ public func records(+ scope: AgentMemoryScope? = nil,+ kinds: [AgentMemoryKind] = [],+ targetID: String? = nil,+ runID: String? = nil,+ userID: String? = nil,+ now: RunTraceTimestamp? = nil+ ) throws -> [AgentMemoryRecord] {+ let filters = Self.filters(+ scope: scope,+ kinds: kinds,+ targetID: targetID,+ runID: runID,+ userID: userID,+ now: now+ )+ let sql = "SELECT record_json FROM memory_records \(filters.whereClause) ORDER BY created_wall ASC"+ lock.lock()+ defer { lock.unlock() }+ return try withStatement(sql) { statement in+ for (index, value) in filters.values.enumerated() {+ bind(value, to: statement, index: Int32(index + 1))+ }+ var records: [AgentMemoryRecord] = []+ while sqlite3_step(statement) == SQLITE_ROW {+ guard let text = columnString(statement, index: 0),+ let data = text.data(using: .utf8),+ let record = try? Self.decoder().decode(AgentMemoryRecord.self, from: data)+ else {+ continue+ }+ records.append(record)+ }+ return records+ }+ }++ public func search(query: AgentMemoryQuery) throws -> [AgentMemorySearchResult] {+ let normalizedQuery = LocalAppLookup.cleanedLookupName(query.text)+ guard !normalizedQuery.isEmpty, query.budget.maxRecords > 0 else { return [] }++ let now = Self.now()+ let candidates = try records(+ scope: query.scope,+ kinds: query.kinds,+ targetID: query.targetID,+ runID: query.runID,+ userID: query.userID,+ now: now+ )+ guard !candidates.isEmpty else { return [] }++ let ftsScores = (try? ftsScores(for: normalizedQuery)) ?? [:]+ let queryVector = embeddingProvider.embedding(for: normalizedQuery)+ var results: [AgentMemorySearchResult] = []+ results.reserveCapacity(candidates.count)++ for record in candidates {+ let text = Self.searchText(for: record)+ let lexicalScore = ftsScores[record.id] ?? Self.tokenOverlapScore(query: normalizedQuery, searchText: text)+ let vectorScore = Self.cosineSimilarity(queryVector, storedVector(recordID: record.id) ?? embeddingProvider.embedding(for: text))+ let exactScore = Self.exactLocalItemScore(record: record, query: normalizedQuery)+ let recencyScore = Self.recencyScore(record: record, now: now)+ let useScore = min(Double(record.useCount) / 10, 1)+ let availabilityScore = record.kind == .negativeLookup ? -0.2 : 0.05+ let rankScore: Double+ if exactScore > 0 {+ rankScore = 1 + exactScore + lexicalScore * 0.1 + useScore * 0.05+ } else {+ rankScore = lexicalScore * 0.42+ + vectorScore * 0.34+ + recencyScore * 0.08+ + useScore * 0.06+ + record.confidence * 0.05+ + availabilityScore+ }+ let relevance = min(max(rankScore, 0), 1)+ guard relevance >= query.budget.minRelevance else { continue }+ results.append(+ AgentMemorySearchResult(+ record: record,+ relevance: relevance,+ embeddingModelID: record.embedding?.modelID ?? embeddingProvider.modelID,+ lexicalScore: lexicalScore,+ vectorScore: vectorScore,+ rankScore: rankScore,+ metadata: [+ "retriever": "sqlite-agent-memory",+ "lexicalScore": Self.format(lexicalScore),+ "vectorScore": Self.format(vectorScore),+ "rankScore": Self.format(rankScore)+ ]+ )+ )+ }++ var promptCharacters = 0+ var bounded: [AgentMemorySearchResult] = []+ for result in results.sorted(by: Self.isBetterResult) {+ guard bounded.count < query.budget.maxRecords else { break }+ let nextCharacters = promptCharacters + result.record.value.count+ guard nextCharacters <= query.budget.maxPromptCharacters else { break }+ promptCharacters = nextCharacters+ bounded.append(result)+ }+ return bounded+ }++ @discardableResult+ public func delete(+ recordID: String? = nil,+ scope: AgentMemoryScope? = nil,+ kind: AgentMemoryKind? = nil,+ targetID: String? = nil,+ runID: String? = nil,+ userID: String? = nil+ ) throws -> Int {+ if let recordID {+ try validateIdentifier(recordID)+ }+ let filters = Self.filters(+ scope: scope,+ kinds: kind.map { [$0] } ?? [],+ targetID: targetID,+ runID: runID,+ userID: userID,+ now: nil,+ recordID: recordID+ )+ let ids = try recordIDs(whereClause: filters.whereClause, values: filters.values)+ guard !ids.isEmpty else { return 0 }++ lock.lock()+ defer { lock.unlock() }+ try transaction {+ for id in ids {+ try deleteFTSAndEmbedding(recordID: id)+ try withStatement("DELETE FROM memory_records WHERE id = ?") { statement in+ bind(id, to: statement, index: 1)+ try stepDone(statement)+ }+ }+ }+ return ids.count+ }++ public func exportJSONL(to url: URL) throws {+ let records = try records()+ var data = Data()+ let encoder = Self.encoder()+ for record in records.sorted(by: { $0.id < $1.id }) {+ var line = try encoder.encode(record)+ line.append(0x0A)+ data.append(line)+ }+ try fileManager.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)+ try data.write(to: url, options: .atomic)+ }++ public func prewarmDefaultLocalItemsInBackground(options: AgentMemoryPrewarmOptions = .defaults()) {+ lock.lock()+ guard !isPrewarming else {+ lock.unlock()+ return+ }+ isPrewarming = true+ lock.unlock()++ Task.detached(priority: .utility) { [self] in+ prewarmDefaultLocalItems(options: options)+ finishPrewarming()+ }+ }++ public func prewarmDefaultLocalItems(options: AgentMemoryPrewarmOptions = .defaults()) {+ guard options.maxItemsPerRoot > 0 else { return }++ let entries = prewarmRecords(+ roots: options.applicationRoots,+ allowedKinds: [.application],+ maxItemsPerRoot: options.maxItemsPerRoot+ ) + prewarmRecords(+ roots: options.fileRoots,+ allowedKinds: [.folder, .file, .other],+ maxItemsPerRoot: options.maxItemsPerRoot+ )+ for entry in entries {+ try? upsert(entry)+ }+ }++ public func prewarmTaskDefinitions(_ definitions: [LocalAppTaskDefinition]) {+ for definition in definitions {+ try? upsert(Self.record(taskDefinition: definition))+ }+ }++ public func taskDefinitions() -> [LocalAppTaskDefinition] {+ (try? records(scope: .global, kinds: [.taskDefinition], now: Self.now()))?+ .compactMap(Self.taskDefinition(from:))+ .sorted { lhs, rhs in+ if lhs.taskType == rhs.taskType {+ return lhs.targetApp.appName < rhs.targetApp.appName+ }+ return lhs.taskType < rhs.taskType+ } ?? []+ }++ public func record(+ availability: LocalAppAvailability,+ query: String,+ source: String+ ) {+ try? upsert(Self.record(availability: availability, query: query, source: source))+ }++ func cachedAvailability(+ named itemName: String,+ preferredKind: LocalItemKind?+ ) -> LocalAppAvailability? {+ let requestedName = LocalAppLookup.cleanedLookupName(itemName)+ guard !requestedName.isEmpty else { return nil }++ let results = (try? search(query: AgentMemoryQuery(+ text: requestedName,+ scope: .global,+ kinds: [.localItem],+ budget: AgentMemoryRetrievalBudget(maxRecords: 8, maxPromptCharacters: 1_000, minRelevance: 0)+ ))) ?? []++ for result in results {+ let record = result.record+ guard record.metadata[Self.localAvailableKey] == "true" else { continue }+ if let preferredKind,+ record.metadata[Self.localKindKey] != preferredKind.rawValue {+ continue+ }+ let appURL = existingURL(for: record)+ guard appURL != nil || record.metadata[Self.localBundleIdentifierKey]?.isEmpty == false else {+ continue+ }+ markUsed(recordID: record.id)++ var metadata = record.metadata+ metadata["provider"] = "sqlite-agent-memory"+ metadata["cache.id"] = record.id+ metadata["cache.score"] = Self.format(result.rankScore)+ metadata["requestedItemName"] = requestedName+ metadata["itemKind"] = metadata[Self.localKindKey] ?? ""+ metadata["itemURL"] = appURL?.path ?? metadata[Self.localPathKey] ?? ""+ metadata["bundleIdentifier"] = metadata[Self.localBundleIdentifierKey] ?? ""+ metadata["match"] = "agentMemory"++ var targetMetadata = [+ "localItem.kind": metadata[Self.localKindKey] ?? "",+ "localItem.path": appURL?.path ?? metadata[Self.localPathKey] ?? ""+ ]+ if let defaultApplication = metadata["defaultApplication"], !defaultApplication.isEmpty {+ targetMetadata["localItem.defaultApplication"] = defaultApplication+ }++ return LocalAppAvailability(+ target: LocalAppTarget(+ appName: metadata[Self.localDisplayNameKey] ?? record.value,+ bundleIdentifier: metadata[Self.localBundleIdentifierKey]?.nilIfEmpty,+ titleContains: metadata[Self.localDisplayNameKey] ?? record.value,+ metadata: targetMetadata+ ),+ isInstalled: true,+ appURL: appURL,+ metadata: metadata+ )+ }++ return nil+ }++ public func contextSnippets(for query: String, limit: Int = 4) -> [String] {+ let results = (try? search(query: AgentMemoryQuery(+ text: query,+ scope: .global,+ kinds: [.localItem, .negativeLookup, .taskDefinition],+ budget: AgentMemoryRetrievalBudget(maxRecords: limit, maxPromptCharacters: 1_600, minRelevance: 0.05)+ ))) ?? []++ return results.map { result in+ let record = result.record+ let status = record.kind == .negativeLookup ? "missing" : "available"+ let name = record.metadata[Self.localDisplayNameKey] ?? record.metadata["displayTitle"] ?? record.value+ let kind = record.metadata[Self.localKindKey] ?? record.kind.rawValue+ let path = record.metadata[Self.localPathKey].map { " path=\($0)" } ?? ""+ let bundleIdentifier = record.metadata[Self.localBundleIdentifierKey].map { " bundleIdentifier=\($0)" } ?? ""+ let metadata = Self.snippetMetadata(record.metadata)+ return "agent_memory: query=\"\(record.metadata[Self.localQueryKey] ?? record.value)\" status=\(status) name=\"\(name)\" kind=\(kind)\(path)\(bundleIdentifier) source=\(record.metadata[Self.localSourceKey] ?? record.source.summary) match=\(record.metadata[Self.localMatchKey] ?? "") score=\(Self.format(result.rankScore))\(metadata)"+ }+ }++ private func configure() throws {+ try execute("PRAGMA journal_mode=WAL")+ try execute("PRAGMA synchronous=NORMAL")+ try execute("PRAGMA foreign_keys=ON")+ }++ private func createSchema() throws {+ try execute("""+ CREATE TABLE IF NOT EXISTS memory_records (+ id TEXT PRIMARY KEY NOT NULL,+ scope TEXT NOT NULL,+ kind TEXT NOT NULL,+ target_id TEXT,+ run_id TEXT,+ user_id TEXT,+ value TEXT NOT NULL,+ created_wall REAL NOT NULL,+ created_uptime_ns INTEGER NOT NULL,+ expires_wall REAL,+ expires_uptime_ns INTEGER,+ durable INTEGER NOT NULL,+ source_json TEXT NOT NULL,+ metadata_json TEXT NOT NULL,+ confidence REAL NOT NULL,+ use_count INTEGER NOT NULL,+ last_used_wall REAL,+ last_used_uptime_ns INTEGER,+ search_text TEXT NOT NULL,+ record_json TEXT NOT NULL,+ embedding_model_id TEXT,+ embedding_dimensions INTEGER,+ updated_wall REAL NOT NULL+ )+ """)+ try execute("""+ CREATE VIRTUAL TABLE IF NOT EXISTS memory_fts+ USING fts5(id UNINDEXED, search_text, value, tokenize='unicode61')+ """)+ try execute("""+ CREATE TABLE IF NOT EXISTS memory_embeddings (+ record_id TEXT PRIMARY KEY NOT NULL,+ embedding_model_id TEXT NOT NULL,+ dimensions INTEGER NOT NULL,+ vector BLOB NOT NULL+ )+ """)+ try execute("CREATE INDEX IF NOT EXISTS idx_memory_scope_kind ON memory_records(scope, kind)")+ try execute("CREATE INDEX IF NOT EXISTS idx_memory_target ON memory_records(target_id)")+ try execute("CREATE INDEX IF NOT EXISTS idx_memory_run ON memory_records(run_id)")+ try execute("CREATE INDEX IF NOT EXISTS idx_memory_user ON memory_records(user_id)")+ try execute("PRAGMA user_version = 1")+ }++ private func prewarmRecords(+ roots: [URL],+ allowedKinds: Set<LocalItemKind>,+ maxItemsPerRoot: Int+ ) -> [AgentMemoryRecord] {+ var entries: [AgentMemoryRecord] = []+ for root in roots where fileManager.fileExists(atPath: root.path) {+ guard let enumerator = fileManager.enumerator(+ at: root,+ includingPropertiesForKeys: [.isDirectoryKey, .contentModificationDateKey],+ options: [.skipsHiddenFiles, .skipsPackageDescendants]+ ) else {+ continue+ }++ var rootCount = 0+ for case let itemURL as URL in enumerator {+ let kind = LocalItemKind(url: itemURL)+ guard allowedKinds.contains(kind) else { continue }++ entries.append(Self.record(+ url: itemURL,+ query: Self.displayName(for: itemURL, kind: kind),+ kind: kind,+ source: "prewarm",+ match: "prewarm",+ metadata: [+ "prewarm.root": root.path,+ "parentDirectory": itemURL.deletingLastPathComponent().lastPathComponent,+ "fileExtension": itemURL.pathExtension+ ]+ ))+ rootCount += 1+ if rootCount >= maxItemsPerRoot { break }+ }+ }+ return entries+ }++ private func markUsed(recordID: String) {+ guard var record = try? record(id: recordID) else { return }+ record.useCount += 1+ record.lastUsedAt = Self.now()+ try? upsert(record)+ }++ private func record(id: String) throws -> AgentMemoryRecord? {+ try records().first { $0.id == id }+ }++ private func existingURL(for record: AgentMemoryRecord) -> URL? {+ if let path = record.metadata[Self.localPathKey], !path.isEmpty {+ let url = URL(fileURLWithPath: path)+ if fileManager.fileExists(atPath: url.path) {+ return url+ }+ }+ guard let bundleIdentifier = record.metadata[Self.localBundleIdentifierKey], !bundleIdentifier.isEmpty else {+ return nil+ }+ return NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleIdentifier)+ }++ private func ftsScores(for query: String) throws -> [String: Double] {+ let tokens = Self.tokens(in: query)+ guard !tokens.isEmpty else { return [:] }+ let matchQuery = tokens.map { "\($0)*" }.joined(separator: " OR ")+ let sql = "SELECT id, bm25(memory_fts) FROM memory_fts WHERE memory_fts MATCH ? LIMIT 200"++ lock.lock()+ defer { lock.unlock() }+ return try withStatement(sql) { statement in+ bind(matchQuery, to: statement, index: 1)+ var scores: [String: Double] = [:]+ while sqlite3_step(statement) == SQLITE_ROW {+ guard let id = columnString(statement, index: 0) else { continue }+ let bm25 = sqlite3_column_double(statement, 1)+ scores[id] = max(scores[id] ?? 0, 1 / (1 + abs(bm25)))+ }+ return scores+ }+ }++ private func storedVector(recordID: String) -> [Float]? {+ lock.lock()+ defer { lock.unlock() }+ return try? withStatement("SELECT vector FROM memory_embeddings WHERE record_id = ?") { statement in+ bind(recordID, to: statement, index: 1)+ guard sqlite3_step(statement) == SQLITE_ROW,+ let blob = sqlite3_column_blob(statement, 0)+ else {+ return nil+ }+ let count = Int(sqlite3_column_bytes(statement, 0))+ let data = Data(bytes: blob, count: count)+ return Self.vector(from: data)+ }+ }++ private func recordIDs(whereClause: String, values: [SQLValue]) throws -> [String] {+ let sql = "SELECT id FROM memory_records \(whereClause)"+ lock.lock()+ defer { lock.unlock() }+ return try withStatement(sql) { statement in+ for (index, value) in values.enumerated() {+ bind(value, to: statement, index: Int32(index + 1))+ }+ var ids: [String] = []+ while sqlite3_step(statement) == SQLITE_ROW {+ if let id = columnString(statement, index: 0) {+ ids.append(id)+ }+ }+ return ids+ }+ }++ private func deleteFTSAndEmbedding(recordID: String) throws {+ try withStatement("DELETE FROM memory_fts WHERE id = ?") { statement in+ bind(recordID, to: statement, index: 1)+ try stepDone(statement)+ }+ try withStatement("DELETE FROM memory_embeddings WHERE record_id = ?") { statement in+ bind(recordID, to: statement, index: 1)+ try stepDone(statement)+ }+ }++ private func execute(_ sql: String) throws {+ guard sqlite3_exec(db, sql, nil, nil, nil) == SQLITE_OK else {+ throw AgentMemoryStoreError.sqliteFailure(Self.message(from: db))+ }+ }++ private func transaction(_ block: () throws -> Void) throws {+ try execute("BEGIN IMMEDIATE")+ do {+ try block()+ try execute("COMMIT")+ } catch {+ try? execute("ROLLBACK")+ throw error+ }+ }++ private func withStatement<T>(_ sql: String, _ body: (OpaquePointer) throws -> T) throws -> T {+ var statement: OpaquePointer?+ guard sqlite3_prepare_v2(db, sql, -1, &statement, nil) == SQLITE_OK, let statement else {+ throw AgentMemoryStoreError.sqliteFailure(Self.message(from: db))+ }+ defer { sqlite3_finalize(statement) }+ return try body(statement)+ }++ private func stepDone(_ statement: OpaquePointer) throws {+ guard sqlite3_step(statement) == SQLITE_DONE else {+ throw AgentMemoryStoreError.sqliteFailure(Self.message(from: db))+ }+ }++ private func bind(_ value: SQLValue, to statement: OpaquePointer, index: Int32) {+ switch value {+ case let .string(value):+ sqlite3_bind_text(statement, index, value, -1, SQLITE_TRANSIENT)+ case let .double(value):+ sqlite3_bind_double(statement, index, value)+ case let .int(value):+ sqlite3_bind_int64(statement, index, value)+ case .null:+ sqlite3_bind_null(statement, index)+ }+ }++ private func bind(_ value: String?, to statement: OpaquePointer, index: Int32) {+ guard let value else {+ sqlite3_bind_null(statement, index)+ return+ }+ sqlite3_bind_text(statement, index, value, -1, SQLITE_TRANSIENT)+ }++ private func bind(_ value: Double?, to statement: OpaquePointer, index: Int32) {+ guard let value else {+ sqlite3_bind_null(statement, index)+ return+ }+ sqlite3_bind_double(statement, index, value)+ }++ private func bind(_ value: Int64?, to statement: OpaquePointer, index: Int32) {+ guard let value else {+ sqlite3_bind_null(statement, index)+ return+ }+ sqlite3_bind_int64(statement, index, value)+ }++ private func bind(_ value: Int, to statement: OpaquePointer, index: Int32) {+ sqlite3_bind_int(statement, index, Int32(value))+ }++ private func bind(_ data: Data, to statement: OpaquePointer, index: Int32) {+ _ = data.withUnsafeBytes { rawBuffer in+ sqlite3_bind_blob(statement, index, rawBuffer.baseAddress, Int32(data.count), SQLITE_TRANSIENT)+ }+ }++ private func columnString(_ statement: OpaquePointer, index: Int32) -> String? {+ guard let cString = sqlite3_column_text(statement, index) else { return nil }+ return String(cString: cString)+ }++ private func validateIdentifier(_ value: String) throws {+ let allowedScalars = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-:")+ let isSafe = !value.isEmpty+ && value.count <= 256+ && value != "."+ && value != ".."+ && value.unicodeScalars.allSatisfy { allowedScalars.contains($0) }++ guard isSafe else {+ throw AgentMemoryStoreError.invalidIdentifier(value)+ }+ }++ private func finishPrewarming() {+ lock.lock()+ isPrewarming = false+ lock.unlock()+ }++ private static func filters(+ scope: AgentMemoryScope?,+ kinds: [AgentMemoryKind],+ targetID: String?,+ runID: String?,+ userID: String?,+ now: RunTraceTimestamp?,+ recordID: String? = nil+ ) -> (whereClause: String, values: [SQLValue]) {+ var clauses: [String] = []+ var values: [SQLValue] = []+ if let recordID {+ clauses.append("id = ?")+ values.append(.string(recordID))+ }+ if let scope {+ clauses.append("scope = ?")+ values.append(.string(scope.rawValue))+ }+ if !kinds.isEmpty {+ clauses.append("kind IN (\(Array(repeating: "?", count: kinds.count).joined(separator: ",")))")+ values.append(contentsOf: kinds.map { .string($0.rawValue) })+ }+ if let targetID {+ clauses.append("target_id = ?")+ values.append(.string(targetID))+ }+ if let runID {+ clauses.append("run_id = ?")+ values.append(.string(runID))+ }+ if let userID {+ clauses.append("user_id = ?")+ values.append(.string(userID))+ }+ if let now {+ clauses.append("(expires_wall IS NULL OR expires_wall > ?)")+ values.append(.double(now.wallClock.timeIntervalSince1970))+ }+ guard !clauses.isEmpty else { return ("", []) }+ return ("WHERE " + clauses.joined(separator: " AND "), values)+ }++ private static func record(+ availability: LocalAppAvailability,+ query: String,+ source: String+ ) -> AgentMemoryRecord {+ let kind = availability.metadata["itemKind"]+ ?? availability.target.metadata["localItem.kind"]+ ?? (availability.target.bundleIdentifier == nil ? "unknown" : LocalItemKind.application.rawValue)+ let path = availability.metadata["itemURL"]+ ?? availability.target.metadata["localItem.path"]+ ?? availability.appURL?.path+ let bundleIdentifier = availability.metadata["bundleIdentifier"]+ ?? availability.target.bundleIdentifier+ let displayName = availability.target.appName+ let match = availability.metadata["match"]+ ?? availability.metadata["reason"]+ ?? (availability.isInstalled ? "resolved" : "missing")++ var metadata = availability.metadata+ metadata[localQueryKey] = query+ metadata[localNormalizedQueryKey] = LocalAppLookup.cleanedLookupName(query)+ metadata[localDisplayNameKey] = displayName+ metadata[localNormalizedDisplayNameKey] = LocalAppLookup.normalized(displayName)+ metadata[localKindKey] = kind+ metadata[localPathKey] = path ?? ""+ metadata[localBundleIdentifierKey] = bundleIdentifier ?? ""+ metadata[localAvailableKey] = String(availability.isInstalled)+ metadata[localSourceKey] = source+ metadata[localMatchKey] = match++ return AgentMemoryRecord(+ id: localItemID(+ kind: kind,+ path: path,+ bundleIdentifier: bundleIdentifier,+ displayName: displayName,+ query: query,+ isAvailable: availability.isInstalled+ ),+ scope: .global,+ kind: availability.isInstalled ? .localItem : .negativeLookup,+ value: displayName,+ createdAt: now(),+ expiresAt: availability.isInstalled ? nil : now().adding(seconds: 86_400),+ durable: availability.isInstalled,+ source: AgentMemorySource(summary: source),+ metadata: metadata,+ confidence: availability.isInstalled ? 0.95 : 0.75,+ useCount: 1+ )+ }++ private static func record(+ url: URL,+ query: String,+ kind: LocalItemKind,+ source: String,+ match: String,+ metadata: [String: String]+ ) -> AgentMemoryRecord {+ let displayName = displayName(for: url, kind: kind)+ let bundleIdentifier = kind == .application ? Bundle(url: url)?.bundleIdentifier : nil+ var entryMetadata = metadata+ entryMetadata["itemKind"] = kind.rawValue+ entryMetadata["itemURL"] = url.path+ entryMetadata["bundleIdentifier"] = bundleIdentifier ?? ""+ entryMetadata[localQueryKey] = query+ entryMetadata[localNormalizedQueryKey] = LocalAppLookup.cleanedLookupName(query)+ entryMetadata[localDisplayNameKey] = displayName+ entryMetadata[localNormalizedDisplayNameKey] = LocalAppLookup.normalized(displayName)+ entryMetadata[localKindKey] = kind.rawValue+ entryMetadata[localPathKey] = url.path+ entryMetadata[localBundleIdentifierKey] = bundleIdentifier ?? ""+ entryMetadata[localAvailableKey] = "true"+ entryMetadata[localSourceKey] = source+ entryMetadata[localMatchKey] = match++ return AgentMemoryRecord(+ id: localItemID(+ kind: kind.rawValue,+ path: url.path,+ bundleIdentifier: bundleIdentifier,+ displayName: displayName,+ query: query,+ isAvailable: true+ ),+ scope: .global,+ kind: .localItem,+ value: displayName,+ createdAt: now(),+ durable: true,+ source: AgentMemorySource(summary: source),+ metadata: entryMetadata,+ confidence: 0.9,+ useCount: 1+ )+ }++ private static func record(taskDefinition definition: LocalAppTaskDefinition) -> AgentMemoryRecord {+ let entityText = definition.entityRules.map(\.name).joined(separator: " ")+ let workflowText = definition.workflowSteps+ .flatMap { step in [step.id, step.role.rawValue, step.summary] + step.metadata.flatMap { [$0.key, $0.value] } }+ .joined(separator: " ")+ let displayTitle = displayTitle(for: definition)+ var metadata = definition.metadata+ metadata["taskType"] = definition.taskType+ metadata["targetApp"] = definition.targetApp.appName+ metadata["bundleIdentifier"] = definition.targetApp.bundleIdentifier ?? ""+ metadata["entityNames"] = definition.entityRules.map(\.name).joined(separator: ",")+ metadata["observationStrategies"] = definition.observationStrategies.map(\.rawValue).joined(separator: ",")+ metadata["verificationEntityName"] = definition.verificationEntityName ?? ""+ metadata["displayTitle"] = displayTitle+ metadata["taskText"] = "\(definition.taskType) \(entityText) \(workflowText)"+ metadata["targetAppTitle"] = definition.targetApp.titleContains ?? definition.targetApp.appName+ if let encodedDefinition = encodedTaskDefinition(definition) {+ metadata[taskDefinitionJSONMetadataKey] = encodedDefinition+ }++ return AgentMemoryRecord(+ id: "task-definition:\(definition.taskType)",+ scope: .global,+ kind: .taskDefinition,+ value: displayTitle,+ createdAt: now(),+ durable: true,+ source: AgentMemorySource(summary: "task-definition-prewarm"),+ metadata: metadata,+ confidence: 1,+ useCount: 1+ )+ }++ private static func taskDefinition(from record: AgentMemoryRecord) -> LocalAppTaskDefinition? {+ guard let encodedDefinition = record.metadata[taskDefinitionJSONMetadataKey],+ let data = encodedDefinition.data(using: .utf8)+ else {+ return nil+ }+ return try? JSONDecoder().decode(LocalAppTaskDefinition.self, from: data)+ }++ private static func encodedTaskDefinition(_ definition: LocalAppTaskDefinition) -> String? {+ let encoder = JSONEncoder()+ encoder.outputFormatting = [.sortedKeys]+ guard let data = try? encoder.encode(definition) else { return nil }+ return String(data: data, encoding: .utf8)+ }++ private static func localItemID(+ kind: String,+ path: String?,+ bundleIdentifier: String?,+ displayName: String,+ query: String,+ isAvailable: Bool+ ) -> String {+ if !isAvailable {+ return "missing:\(LocalAppLookup.cleanedLookupName(query))"+ }+ if let bundleIdentifier, !bundleIdentifier.isEmpty {+ return "\(kind):bundle:\(bundleIdentifier)"+ }+ if let path, !path.isEmpty {+ return "\(kind):path:\(path)"+ }+ return "\(kind):name:\(LocalAppLookup.normalized(displayName))"+ }++ private static func searchText(for record: AgentMemoryRecord) -> String {+ (+ [+ record.id,+ record.scope.rawValue,+ record.kind.rawValue,+ record.targetID ?? "",+ record.runID ?? "",+ record.userID ?? "",+ record.value,+ record.source.summary+ ] + record.metadata+ .filter { $0.key != taskDefinitionJSONMetadataKey }+ .sorted { $0.key < $1.key }+ .flatMap { [$0.key, $0.value] }+ )+ .filter { !$0.isEmpty }+ .joined(separator: " ")+ }++ private static func displayName(for url: URL, kind: LocalItemKind) -> String {+ if kind == .application,+ let bundle = Bundle(url: url) {+ return bundle.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String+ ?? bundle.object(forInfoDictionaryKey: "CFBundleName") as? String+ ?? url.deletingPathExtension().lastPathComponent+ }+ return url.lastPathComponent+ }++ private static func displayTitle(for definition: LocalAppTaskDefinition) -> String {+ if let displayTitle = definition.metadata["displayTitle"], !displayTitle.isEmpty {+ return displayTitle+ }+ return definition.taskType+ .split(separator: "_")+ .map { word in word.prefix(1).uppercased() + word.dropFirst() }+ .joined(separator: " ")+ }++ private static func exactLocalItemScore(record: AgentMemoryRecord, query: String) -> Double {+ guard [.localItem, .negativeLookup, .taskDefinition].contains(record.kind) else { return 0 }+ let normalizedDisplayName = record.metadata[localNormalizedDisplayNameKey]+ ?? LocalAppLookup.normalized(record.value)+ let normalizedQuery = record.metadata[localNormalizedQueryKey]+ ?? LocalAppLookup.cleanedLookupName(record.value)+ if normalizedDisplayName == query || normalizedQuery == query { return 1 }+ if normalizedDisplayName.hasPrefix(query) { return 0.92 }+ if normalizedDisplayName.contains(" \(query)") || normalizedDisplayName.contains(query) { return 0.84 }+ return 0+ }++ private static func tokenOverlapScore(query: String, searchText: String) -> Double {+ let queryTokens = Set(tokens(in: query))+ guard !queryTokens.isEmpty else { return 0 }+ let searchText = LocalAppLookup.normalized(searchText)+ let matched = queryTokens.filter { searchText.contains($0) }.count+ return Double(matched) / Double(queryTokens.count)+ }++ private static func recencyScore(record: AgentMemoryRecord, now: RunTraceTimestamp) -> Double {+ let age = record.createdAt.wallClock.distance(to: now.wallClock)+ guard age > 0 else { return 1 }+ return max(0, min(1, 1 - age / (60 * 60 * 24 * 30)))+ }++ private static func cosineSimilarity(_ lhs: [Float], _ rhs: [Float]) -> Double {+ guard lhs.count == rhs.count, !lhs.isEmpty else { return 0 }+ let dot = zip(lhs, rhs).reduce(Float(0)) { $0 + $1.0 * $1.1 }+ let lhsMagnitude = sqrt(lhs.reduce(Float(0)) { $0 + $1 * $1 })+ let rhsMagnitude = sqrt(rhs.reduce(Float(0)) { $0 + $1 * $1 })+ guard lhsMagnitude > 0, rhsMagnitude > 0 else { return 0 }+ return Double(dot / (lhsMagnitude * rhsMagnitude))+ }++ private static func isBetterResult(lhs: AgentMemorySearchResult, rhs: AgentMemorySearchResult) -> Bool {+ if lhs.rankScore == rhs.rankScore {+ if lhs.record.useCount == rhs.record.useCount {+ return lhs.record.value.count < rhs.record.value.count+ }+ return lhs.record.useCount > rhs.record.useCount+ }+ return lhs.rankScore > rhs.rankScore+ }++ private static func tokens(in text: String) -> [String] {+ HashingAgentMemoryEmbeddingProvider.tokens(in: text)+ }++ private static func vectorData(_ vector: [Float]) -> Data {+ var data = Data(capacity: vector.count * MemoryLayout<UInt32>.size)+ for value in vector {+ var littleEndian = value.bitPattern.littleEndian+ data.append(Data(bytes: &littleEndian, count: MemoryLayout<UInt32>.size))+ }+ return data+ }++ private static func vector(from data: Data) -> [Float] {+ guard data.count % MemoryLayout<UInt32>.size == 0 else { return [] }+ var vector: [Float] = []+ vector.reserveCapacity(data.count / MemoryLayout<UInt32>.size)+ var offset = 0+ while offset < data.count {+ let bits = data[offset..<(offset + MemoryLayout<UInt32>.size)].reduce(UInt32(0)) { value, byte in+ (value >> 8) | (UInt32(byte) << 24)+ }+ vector.append(Float(bitPattern: UInt32(littleEndian: bits)))+ offset += MemoryLayout<UInt32>.size+ }+ return vector+ }++ private static func snippetMetadata(_ metadata: [String: String]) -> String {+ let allowedKeys = [+ "taskType",+ "targetApp",+ "itemKind",+ "defaultApplication",+ "entityNames",+ "verificationMode",+ "automationBackend",+ "appleScript.action",+ "screenshotFallback"+ ]+ let pairs = allowedKeys.compactMap { key -> String? in+ guard let value = metadata[key], !value.isEmpty else { return nil }+ return "\(key)=\(value)"+ }+ guard !pairs.isEmpty else { return "" }+ return " metadata={\(pairs.joined(separator: ","))}"+ }++ private static func now() -> RunTraceTimestamp {+ RunTraceTimestamp(+ wallClock: Date(),+ monotonicUptimeNanoseconds: UInt64(ProcessInfo.processInfo.systemUptime * 1_000_000_000)+ )+ }++ private static func format(_ value: Double) -> String {+ String(format: "%.3f", value)+ }++ private static func encoder() -> JSONEncoder {+ let encoder = JSONEncoder()+ encoder.outputFormatting = [.sortedKeys]+ return encoder+ }++ private static func decoder() -> JSONDecoder {+ JSONDecoder()+ }++ private static func message(from db: OpaquePointer?) -> String {+ guard let db, let message = sqlite3_errmsg(db) else { return "unknown sqlite error" }+ return String(cString: message)+ }++ private static func deleteLegacyStores(fileManager: FileManager, donkeyDirectoryOverride: URL? = nil) {+ let donkeyDirectory: URL+ if let donkeyDirectoryOverride {+ donkeyDirectory = donkeyDirectoryOverride+ } else {+ guard let applicationSupport = try? fileManager.url(+ for: .applicationSupportDirectory,+ in: .userDomainMask,+ appropriateFor: nil,+ create: false+ ) else {+ return+ }+ donkeyDirectory = applicationSupport.appendingPathComponent("Donkey", isDirectory: true)+ }+ for name in ["LocalItemResolutionCache", "TargetMemory"] {+ let url = donkeyDirectory.appendingPathComponent(name, isDirectory: true)+ try? fileManager.removeItem(at: url)+ }+ }++ private static let localQueryKey = "agentMemory.local.query"+ private static let localNormalizedQueryKey = "agentMemory.local.normalizedQuery"+ private static let localDisplayNameKey = "agentMemory.local.displayName"+ private static let localNormalizedDisplayNameKey = "agentMemory.local.normalizedDisplayName"+ private static let localKindKey = "agentMemory.local.kind"+ private static let localPathKey = "agentMemory.local.path"+ private static let localBundleIdentifierKey = "agentMemory.local.bundleIdentifier"+ private static let localAvailableKey = "agentMemory.local.available"+ private static let localSourceKey = "agentMemory.local.source"+ private static let localMatchKey = "agentMemory.local.match"+ private static let taskDefinitionJSONMetadataKey = "taskDefinitionJSON"+}++private enum SQLValue {+ case string(String)+ case double(Double)+ case int(Int64)+ case null+}++private extension String {+ var nilIfEmpty: String? {+ isEmpty ? nil : self+ }+}++private extension RunTraceTimestamp {+ func adding(seconds: TimeInterval) -> RunTraceTimestamp {+ RunTraceTimestamp(+ wallClock: wallClock.addingTimeInterval(seconds),+ monotonicUptimeNanoseconds: monotonicUptimeNanoseconds + UInt64(seconds * 1_000_000_000)+ )+ }+}++private let SQLITE_TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self)diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swiftindex a3046ac1..5a2bb911 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift@@ -647,7 +647,7 @@ struct AIHarnessAdapterTests {router: AIModelRouter(registry: AIModelRegistry(entries: [entry(id: "planner", modelID: "gpt-5.2")])),httpClient: httpClient,environment: ["OPENAI_API_KEY": "test-key"],- targetMemoryStore: nil+ memoryStore: nil)var request = adapterRequest()request.context.semanticMemoryResults = [@@ -676,7 +676,7 @@ struct AIHarnessAdapterTests {func openAIAdapterPersistsProviderMemoryProposalsWithValidatedHint() async throws {let root = temporaryDirectory()defer { try? FileManager.default.removeItem(at: root) }- let store = try TargetMemoryJSONLStore(baseDirectory: root)+ let store = try SQLiteAgentMemoryStore(baseDirectory: root, cleanupLegacyStores: false)let httpClient = FakeAIHTTPClient(data: responseData(outputText: providerOutput(@@ -696,11 +696,11 @@ struct AIHarnessAdapterTests {router: AIModelRouter(registry: AIModelRegistry(entries: [entry(id: "planner", modelID: "gpt-5.2")])),httpClient: httpClient,environment: ["OPENAI_API_KEY": "test-key"],- targetMemoryStore: store+ memoryStore: store)let result = await adapter.generatePlannerHint(adapterRequest())- let records = try await store.records(targetID: "target-1")+ let records = try store.records(scope: .target, kinds: [.targetFact], targetID: "target-1")#expect(result.hint?.id == "hint-memory")#expect(result.trace.status == .completed)@@ -725,7 +725,7 @@ struct AIHarnessAdapterTests {router: AIModelRouter(registry: AIModelRegistry(entries: [entry(id: "planner", modelID: "gpt-5.2")])),httpClient: httpClient,environment: ["OPENAI_API_KEY": "test-key"],- targetMemoryStore: nil+ memoryStore: nil)let result = await adapter.generatePlannerHint(adapterRequest())diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AgentMemoryStoreTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AgentMemoryStoreTests.swiftnew file mode 100644index 00000000..e0a9eae9--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AgentMemoryStoreTests.swift@@ -0,0 +1,219 @@+import DonkeyContracts+@testable import DonkeyRuntime+import Foundation+import Testing++@Suite+struct AgentMemoryStoreTests {+ @Test+ func storeRecordsResolvedAndMissingLookupsAsSearchableMemory() throws {+ let root = temporaryDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let store = try SQLiteAgentMemoryStore(baseDirectory: root, cleanupLegacyStores: false)++ store.record(+ availability: LocalAppAvailability(+ target: LocalAppTarget(+ appName: "Figma",+ bundleIdentifier: "com.figma.Desktop",+ titleContains: "Figma",+ metadata: [+ "localItem.kind": "application",+ "localItem.path": "/Applications/Figma.app"+ ]+ ),+ isInstalled: true,+ appURL: URL(fileURLWithPath: "/Applications/Figma.app"),+ metadata: [+ "provider": "test",+ "itemKind": "application",+ "itemURL": "/Applications/Figma.app",+ "bundleIdentifier": "com.figma.Desktop",+ "match": "exact"+ ]+ ),+ query: "figma",+ source: "unit"+ )+ store.record(+ availability: LocalAppAvailability(+ target: LocalAppTarget(appName: "Ghost Tool"),+ isInstalled: false,+ metadata: [+ "provider": "test",+ "reason": "localItemUnavailable",+ "requestedItemName": "ghost tool"+ ]+ ),+ query: "ghost tool",+ source: "unit-missing"+ )++ let figmaResult = try #require(try store.search(query: AgentMemoryQuery(+ text: "open figma",+ scope: .global,+ kinds: [.localItem],+ budget: AgentMemoryRetrievalBudget(maxRecords: 3, minRelevance: 0)+ )).first)+ #expect(figmaResult.record.value == "Figma")+ #expect(figmaResult.record.kind == .localItem)++ let missingSnippet = try #require(store.contextSnippets(for: "launch ghost tool").first)+ #expect(missingSnippet.contains("agent_memory:"))+ #expect(missingSnippet.contains("status=missing"))+ #expect(missingSnippet.contains("Ghost Tool"))+ }++ @Test+ func storePrewarmsFilesFromConfiguredDirectories() throws {+ let fileRoot = temporaryDirectory()+ let storeRoot = temporaryDirectory()+ defer {+ try? FileManager.default.removeItem(at: fileRoot)+ try? FileManager.default.removeItem(at: storeRoot)+ }+ try FileManager.default.createDirectory(at: fileRoot, withIntermediateDirectories: true)+ let fileURL = fileRoot.appendingPathComponent("Roadmap Notes.md")+ try "next steps".write(to: fileURL, atomically: true, encoding: .utf8)++ let store = try SQLiteAgentMemoryStore(baseDirectory: storeRoot, cleanupLegacyStores: false)+ store.prewarmDefaultLocalItems(+ options: AgentMemoryPrewarmOptions(+ applicationRoots: [],+ fileRoots: [fileRoot],+ maxItemsPerRoot: 10+ )+ )++ let result = try #require(try store.search(query: AgentMemoryQuery(+ text: "attach roadmap notes",+ scope: .global,+ kinds: [.localItem],+ budget: AgentMemoryRetrievalBudget(maxRecords: 3, minRelevance: 0)+ )).first)+ #expect(result.record.value == "Roadmap Notes.md")+ #expect(result.record.metadata["agentMemory.local.kind"] == "file")+ #expect(result.record.metadata["agentMemory.local.path"] == fileURL.path)+ #expect(result.record.metadata["agentMemory.local.source"] == "prewarm")+ }++ @Test+ func storePrewarmsTaskDefinitionsAsSearchableCapabilities() throws {+ let root = temporaryDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let store = try SQLiteAgentMemoryStore(baseDirectory: root, cleanupLegacyStores: false)++ store.prewarmTaskDefinitions(BuiltInLocalAppTaskDefinitions.benchmarkFixtures)++ let result = try #require(try store.search(query: AgentMemoryQuery(+ text: "media playback",+ scope: .global,+ kinds: [.taskDefinition],+ budget: AgentMemoryRetrievalBudget(maxRecords: 4, minRelevance: 0)+ )).first)+ #expect(result.record.kind == .taskDefinition)+ #expect(result.record.metadata["taskType"] == "media_playback")+ #expect(result.record.metadata["appleScript.action"] == "music.playMediaQuery")+ #expect(store.taskDefinitions().contains { $0.taskType == "media_playback" })+ #expect(store.cachedAvailability(named: "media playback", preferredKind: nil) == nil)+ }++ @Test+ func storeCombinesFTSAndVectorRetrievalWithPromptBudget() throws {+ let root = temporaryDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let store = try SQLiteAgentMemoryStore(baseDirectory: root, cleanupLegacyStores: false)++ try store.upsert(targetRecord(id: "weather", value: "Weather app search accepts city names."))+ try store.upsert(targetRecord(id: "music", value: "Music app can play an artist from the search field."))++ let results = try store.search(query: AgentMemoryQuery(+ text: "city weather search",+ targetID: "target-1",+ scope: .target,+ kinds: [.targetFact],+ budget: AgentMemoryRetrievalBudget(maxRecords: 1, maxPromptCharacters: 100, minRelevance: 0)+ ))++ #expect(results.map(\.record.id) == ["weather"])+ #expect(results.first?.lexicalScore ?? 0 > 0)+ #expect(results.first?.vectorScore ?? 0 > 0)+ }++ @Test+ func storeFiltersExpiredRecordsAndExportsJSONL() throws {+ let root = temporaryDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let store = try SQLiteAgentMemoryStore(baseDirectory: root, cleanupLegacyStores: false)++ try store.upsert(targetRecord(id: "expired", value: "old fact", expiresAt: timestamp(5)))+ try store.upsert(targetRecord(id: "live", value: "fresh fact", expiresAt: timestamp(1_000)))++ let records = try store.records(+ scope: .target,+ kinds: [.targetFact],+ targetID: "target-1",+ now: timestamp(20)+ )+ #expect(records.map(\.id) == ["live"])++ let exportURL = root.appendingPathComponent("export/memory.jsonl")+ try store.exportJSONL(to: exportURL)+ let text = try String(contentsOf: exportURL, encoding: .utf8)+ #expect(text.contains("\"id\":\"expired\""))+ #expect(text.contains("\"id\":\"live\""))+ }++ @Test+ func storeDeletesLegacyJSONLDirectoriesWhenConfigured() throws {+ let root = temporaryDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let legacyDonkey = root.appendingPathComponent("Donkey", isDirectory: true)+ let legacyCache = legacyDonkey.appendingPathComponent("LocalItemResolutionCache", isDirectory: true)+ let legacyTarget = legacyDonkey.appendingPathComponent("TargetMemory", isDirectory: true)+ try FileManager.default.createDirectory(at: legacyCache, withIntermediateDirectories: true)+ try FileManager.default.createDirectory(at: legacyTarget, withIntermediateDirectories: true)++ _ = try SQLiteAgentMemoryStore(+ baseDirectory: root.appendingPathComponent("AgentMemory", isDirectory: true),+ cleanupLegacyStores: true,+ legacyDonkeyDirectory: legacyDonkey+ )++ #expect(!FileManager.default.fileExists(atPath: legacyCache.path))+ #expect(!FileManager.default.fileExists(atPath: legacyTarget.path))+ }++ private func targetRecord(+ id: String,+ value: String,+ expiresAt: RunTraceTimestamp? = nil+ ) -> AgentMemoryRecord {+ AgentMemoryRecord(+ id: id,+ scope: .target,+ kind: .targetFact,+ targetID: "target-1",+ value: value,+ createdAt: timestamp(10),+ expiresAt: expiresAt,+ durable: expiresAt == nil,+ source: AgentMemorySource(traceID: "trace-1", summary: "test"),+ metadata: ["source": "unit"]+ )+ }++ 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(+ "DonkeyAgentMemoryTests-\(UUID().uuidString)",+ isDirectory: true+ )+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swiftindex 0d36d203..559638c9 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift@@ -375,14 +375,14 @@ struct LocalAppTaskTests {let fileURL = directoryURL.appendingPathComponent("notes.json")try JSONEncoder().encode(definition).write(to: fileURL)- let cacheURL = temporaryCacheURL()- defer { try? FileManager.default.removeItem(at: cacheURL.deletingLastPathComponent()) }- let cache = LocalItemResolutionCache(storeURL: cacheURL)- let definitions = try LocalAppTaskDefinitionLoader(cache: cache).cachedDefinitions(from: directoryURL)+ let storeURL = temporaryStoreDirectory()+ defer { try? FileManager.default.removeItem(at: storeURL) }+ let store = try SQLiteAgentMemoryStore(baseDirectory: storeURL, cleanupLegacyStores: false)+ let definitions = try LocalAppTaskDefinitionLoader(memoryStore: store).cachedDefinitions(from: directoryURL)let loaded = try #require(definitions.first(where: { $0.taskType == "notes_capture" }))#expect(loaded.targetApp.bundleIdentifier == "com.apple.Notes")#expect(loaded.metadata["source"] == "test-json")- #expect(cache.taskDefinitions().map(\.taskType).contains("notes_capture"))+ #expect(store.taskDefinitions().map(\.taskType).contains("notes_capture"))let catalog = LocalAppTaskCatalog(taskDefinitions: definitions,@@ -401,10 +401,10 @@ struct LocalAppTaskTests {@Testfunc defaultLocalCatalogLoadsRuntimeDefinitionsFromCache() {- let cacheURL = temporaryCacheURL()- defer { try? FileManager.default.removeItem(at: cacheURL.deletingLastPathComponent()) }- let cache = LocalItemResolutionCache(storeURL: cacheURL)- let loader = LocalAppTaskDefinitionLoader(cache: cache)+ let storeURL = temporaryStoreDirectory()+ defer { try? FileManager.default.removeItem(at: storeURL) }+ let store = try? SQLiteAgentMemoryStore(baseDirectory: storeURL, cleanupLegacyStores: false)+ let loader = LocalAppTaskDefinitionLoader(memoryStore: store)let catalog = LocalAppTaskCatalog.defaultLocal(availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: []),@@ -412,7 +412,7 @@ struct LocalAppTaskTests {)#expect(catalog.taskDefinitions.map(\.taskType) == ["app_open"])- #expect(cache.taskDefinitions().map(\.taskType) == ["app_open"])+ #expect(store?.taskDefinitions().map(\.taskType) == ["app_open"])#expect(catalog.taskDefinitions.contains { $0.targetApp.appName == "Weather" } == false)#expect(catalog.taskDefinitions.contains { $0.targetApp.appName == "Music" } == false)#expect(catalog.taskDefinitions.contains { $0.targetApp.appName == "Preview" } == false)@@ -931,10 +931,9 @@ struct LocalAppTaskTests {)}- private func temporaryCacheURL() -> URL {+ private func temporaryStoreDirectory() -> URL {FileManager.default.temporaryDirectory- .appendingPathComponent("donkey-task-cache-\(UUID().uuidString)", isDirectory: true)- .appendingPathComponent("cache.jsonl")+ .appendingPathComponent("donkey-task-memory-\(UUID().uuidString)", isDirectory: true)}}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalItemResolutionCacheTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalItemResolutionCacheTests.swiftdeleted file mode 100644index 8e9dd554..00000000--- a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalItemResolutionCacheTests.swift+++ /dev/null@@ -1,113 +0,0 @@-import DonkeyContracts-@testable import DonkeyRuntime-import Foundation-import Testing--@Suite-struct LocalItemResolutionCacheTests {- @Test- func cacheRecordsResolvedAndMissingLookupsAsSearchableMemory() throws {- let cacheURL = temporaryCacheURL()- defer { try? FileManager.default.removeItem(at: cacheURL.deletingLastPathComponent()) }- let cache = LocalItemResolutionCache(storeURL: cacheURL)-- cache.record(- availability: LocalAppAvailability(- target: LocalAppTarget(- appName: "Figma",- bundleIdentifier: "com.figma.Desktop",- titleContains: "Figma",- metadata: [- "localItem.kind": "application",- "localItem.path": "/Applications/Figma.app"- ]- ),- isInstalled: true,- appURL: URL(fileURLWithPath: "/Applications/Figma.app"),- metadata: [- "provider": "test",- "itemKind": "application",- "itemURL": "/Applications/Figma.app",- "bundleIdentifier": "com.figma.Desktop",- "match": "exact"- ]- ),- query: "figma",- source: "unit"- )- cache.record(- availability: LocalAppAvailability(- target: LocalAppTarget(appName: "Ghost Tool"),- isInstalled: false,- metadata: [- "provider": "test",- "reason": "localItemUnavailable",- "requestedItemName": "ghost tool"- ]- ),- query: "ghost tool",- source: "unit-missing"- )-- let figmaResult = try #require(cache.search(query: "open figma").first)- #expect(figmaResult.entry.displayName == "Figma")- #expect(figmaResult.entry.isAvailable)-- let missingSnippet = try #require(cache.contextSnippets(for: "launch ghost tool").first)- #expect(missingSnippet.contains("local_resolution_cache:"))- #expect(missingSnippet.contains("status=missing"))- #expect(missingSnippet.contains("Ghost Tool"))- }-- @Test- func cachePrewarmsFilesFromConfiguredDirectories() throws {- let rootURL = FileManager.default.temporaryDirectory- .appendingPathComponent("donkey-cache-test-\(UUID().uuidString)", isDirectory: true)- let cacheURL = temporaryCacheURL()- defer { try? FileManager.default.removeItem(at: cacheURL.deletingLastPathComponent()) }- try FileManager.default.createDirectory(at: rootURL, withIntermediateDirectories: true)- defer { try? FileManager.default.removeItem(at: rootURL) }-- let fileURL = rootURL.appendingPathComponent("Roadmap Notes.md")- try "next steps".write(to: fileURL, atomically: true, encoding: .utf8)-- let cache = LocalItemResolutionCache(storeURL: cacheURL)- cache.prewarmDefaultLocalItems(- options: LocalItemResolutionCachePrewarmOptions(- applicationRoots: [],- fileRoots: [rootURL],- maxItemsPerRoot: 10- )- )-- let result = try #require(cache.search(query: "attach roadmap notes").first)- #expect(result.entry.displayName == "Roadmap Notes.md")- #expect(result.entry.kind == "file")- #expect(result.entry.path == fileURL.path)- #expect(result.entry.source == "prewarm")- }-- @Test- func cachePrewarmsTaskDefinitionsAsSearchableCapabilities() throws {- let cacheURL = temporaryCacheURL()- defer { try? FileManager.default.removeItem(at: cacheURL.deletingLastPathComponent()) }- let cache = LocalItemResolutionCache(storeURL: cacheURL)-- cache.prewarmTaskDefinitions(BuiltInLocalAppTaskDefinitions.benchmarkFixtures)-- let result = try #require(cache.search(query: "media playback", limit: 4).first { result in- result.entry.kind == "taskDefinition"- })- #expect(result.entry.displayName == "media playback")- #expect(result.entry.metadata["taskType"] == "media_playback")- #expect(result.entry.metadata["appleScript.action"] == "music.playMediaQuery")- #expect(cache.taskDefinitions().contains { $0.taskType == "media_playback" })- #expect(cache.cachedAvailability(named: "media playback", preferredKind: nil) == nil)- }-- private func temporaryCacheURL() -> URL {- FileManager.default.temporaryDirectory- .appendingPathComponent("donkey-resolution-cache-\(UUID().uuidString)", isDirectory: true)- .appendingPathComponent("cache.jsonl")- }-}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/RunMemoryStoreTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/RunMemoryStoreTests.swiftindex d5add0de..bffdc2d8 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/RunMemoryStoreTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/RunMemoryStoreTests.swift@@ -53,11 +53,11 @@ struct RunMemoryStoreTests {}@Test- func targetMemoryJsonlStoresListsAndDeletesApprovedRecords() async throws {+ func sqliteAgentMemoryStoresListsAndDeletesApprovedRecords() throws {let root = temporaryDirectory()defer { try? FileManager.default.removeItem(at: root) }- let store = try TargetMemoryJSONLStore(baseDirectory: root)+ let store = try SQLiteAgentMemoryStore(baseDirectory: root, cleanupLegacyStores: false)let proposal = RunMemoryWriteProposal(id: "proposal-1",proposedBy: .model,@@ -65,28 +65,28 @@ struct RunMemoryStoreTests {rationale: "fixture-proven target fact")- let decision = try await store.appendApprovedProposal(proposal, decidedAt: timestamp(20))+ let decision = try 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")+ let records = try store.records(scope: .target, kinds: [.targetFact], targetID: "target-1")#expect(records.map(\.id) == ["memory-1"])- let scoped = try await store.records(targetID: "target-1", runID: "run-1", userID: "user-1")+ let scoped = try store.records(scope: .target, kinds: [.targetFact], 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")+ let deleted = try store.delete(recordID: "memory-1", scope: .target, targetID: "target-1")#expect(deleted == 1)- #expect(try await store.records(targetID: "target-1").isEmpty)+ #expect(try store.records(scope: .target, targetID: "target-1").isEmpty)}@Test- func rejectedMemoryProposalIsInspectableAndNotStored() async throws {+ func rejectedMemoryProposalIsInspectableAndNotStored() throws {let root = temporaryDirectory()defer { try? FileManager.default.removeItem(at: root) }- let store = try TargetMemoryJSONLStore(baseDirectory: root)+ let store = try SQLiteAgentMemoryStore(baseDirectory: root, cleanupLegacyStores: false)let proposal = RunMemoryWriteProposal(id: "proposal-rejected",proposedBy: .model,@@ -102,12 +102,12 @@ struct RunMemoryStoreTests {rationale: "bad proposal")- let decision = try await store.appendApprovedProposal(proposal, decidedAt: timestamp(20))+ let decision = try 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)+ #expect(try store.records(scope: .target, targetID: "target-1").isEmpty)}@Test