Open source CapCut alternative.
TypeScript
feat(app): ground, compile-gate, and promote dynamic AppleScript via the app's real dictionary
David Le4e360d46cb0b
diff --git a/apps/Donkey/Sources/DonkeyAI/HostedAppleScriptGenerationAdapter.swift b/apps/Donkey/Sources/DonkeyAI/HostedAppleScriptGenerationAdapter.swiftindex 467b3609..ba96e5a8 100644--- a/apps/Donkey/Sources/DonkeyAI/HostedAppleScriptGenerationAdapter.swift+++ b/apps/Donkey/Sources/DonkeyAI/HostedAppleScriptGenerationAdapter.swift@@ -3,7 +3,7 @@ import DonkeyHarnessimport Foundationpublic struct HostedAppleScriptGenerationAdapter: Sendable {- public static let schemaID = "dynamic_applescript_generation_v1"+ public static let schemaID = "dynamic_applescript_generation_v2"public var router: AIModelRouterpublic var configuration: DonkeyBackendInferenceConfiguration?@@ -119,7 +119,9 @@ public struct HostedAppleScriptGenerationAdapter: Sendable {"provider": entry.provider.rawValue,"modelEntryID": entry.id,"safetyNotes": wire.safetyNotes.joined(separator: "\n"),- "expectedOutput": wire.expectedOutput+ "expectedOutput": wire.expectedOutput,+ "usedCommands": wire.usedCommands.joined(separator: "\n"),+ "parameterBindings": wire.parameterBindings.joined(separator: "\n")])} catch is CancellationError {@@ -164,7 +166,7 @@ public struct HostedAppleScriptGenerationAdapter: Sendable {],metadata: ["source_trace_id": request.sourceTraceID ?? "",- "prompt_version": "dynamic-applescript-generation-v1",+ "prompt_version": "dynamic-applescript-generation-v2","privacy.store": "false","model_entry_id": entry.id],@@ -183,6 +185,7 @@ public struct HostedAppleScriptGenerationAdapter: Sendable {entities: request.entities,allowedActions: request.allowedActions,verification: request.verification,+ scriptingDictionary: request.scriptingDictionaryDigest,worldFacts: request.worldFacts,metadata: request.metadata)@@ -199,7 +202,10 @@ public struct HostedAppleScriptGenerationAdapter: Sendable {"Do not build a full automation pipeline; Donkey handles observation, clicking, recovery, and verification as separate harness steps.","Use only the provided entities and allowed actions.","Do not use shell commands, System Events, keystrokes, key codes, file deletion, quitting apps, network calls, credential access, or unrelated applications.",- "Prefer app dictionary commands and return a concise structured text result with key=value fields when possible.",+ "When the task JSON includes a scriptingDictionary digest, it is the app's real declared vocabulary: use ONLY command, parameter, class, property, and enumeration names that appear in it, with their exact spelling. Never invent terminology that is not in the digest. If the goal cannot be expressed with the digest's commands, set canGenerate to false with a blockedReason instead of guessing.",+ "Provide a concrete value for every required parameter of every command you use; never leave placeholders or template tokens in the script.",+ "List every dictionary command the script uses in usedCommands, and every parameter you bound in parameterBindings as name=value entries.",+ "Return a concise structured text result with key=value fields when possible.","Do not execute anything. The harness will validate, permission-gate, execute, observe, and verify separately."].joined(separator: " ")@@ -207,7 +213,7 @@ public struct HostedAppleScriptGenerationAdapter: Sendable {["type": "object","additionalProperties": false,- "required": ["canGenerate", "blockedReason", "scriptSource", "summary", "safetyNotes", "expectedOutput"],+ "required": ["canGenerate", "blockedReason", "scriptSource", "summary", "safetyNotes", "expectedOutput", "usedCommands", "parameterBindings"],"properties": ["canGenerate": ["type": "boolean",@@ -233,6 +239,16 @@ public struct HostedAppleScriptGenerationAdapter: Sendable {"expectedOutput": ["type": "string","description": "Expected key=value style output or observation that should verify success."+ ],+ "usedCommands": [+ "type": "array",+ "items": ["type": "string"],+ "description": "Every scripting-dictionary command name the script uses, exactly as declared in the provided digest."+ ],+ "parameterBindings": [+ "type": "array",+ "items": ["type": "string"],+ "description": "Every parameter the script binds, as name=value entries, so the harness can verify no required parameter was left out."]]]@@ -254,6 +270,8 @@ private struct AppleScriptGenerationWire: Decodable {var summary: Stringvar safetyNotes: [String]var expectedOutput: String+ var usedCommands: [String]+ var parameterBindings: [String]init(from decoder: Decoder) throws {let container = try decoder.container(keyedBy: CodingKeys.self)@@ -265,6 +283,8 @@ private struct AppleScriptGenerationWire: Decodable {summary = try container.decodeIfPresent(String.self, forKey: .summary) ?? ""safetyNotes = try container.decodeIfPresent([String].self, forKey: .safetyNotes) ?? []expectedOutput = try container.decodeIfPresent(String.self, forKey: .expectedOutput) ?? ""+ usedCommands = try container.decodeIfPresent([String].self, forKey: .usedCommands) ?? []+ parameterBindings = try container.decodeIfPresent([String].self, forKey: .parameterBindings) ?? []// Models name the script field inconsistently (`scriptSource`, `appleScript`, `script`,// `source`). Accept any of them so a correct script isn't dropped over a key name.scriptSource = try container.decodeIfPresent(String.self, forKey: .scriptSource)@@ -276,6 +296,7 @@ private struct AppleScriptGenerationWire: Decodable {private enum CodingKeys: String, CodingKey {case canGenerate, blockedReason, scriptSource, summary, safetyNotes, expectedOutput+ case usedCommands, parameterBindingscase appleScript, script, source}}@@ -287,6 +308,7 @@ private struct AppleScriptGenerationPromptPayload: Encodable {var entities: [String: String]var allowedActions: Stringvar verification: String+ var scriptingDictionary: Stringvar worldFacts: [String: String]var metadata: [String: String]}diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swiftindex e85db491..b50f5024 100644--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift@@ -84,6 +84,9 @@ public struct HarnessScriptGenerationRequest: Equatable, Sendable {public var entities: [String: String]public var allowedActions: Stringpublic var verification: String+ /// The target app's real scripting-dictionary terminology (bounded digest). When present, the+ /// generator must write against these declared commands instead of guessing terminology.+ public var scriptingDictionaryDigest: Stringpublic var worldFacts: [String: String]public var sourceTraceID: String?public var metadata: [String: String]@@ -96,6 +99,7 @@ public struct HarnessScriptGenerationRequest: Equatable, Sendable {entities: [String: String] = [:],allowedActions: String = "",verification: String = "",+ scriptingDictionaryDigest: String = "",worldFacts: [String: String] = [:],sourceTraceID: String? = nil,metadata: [String: String] = [:]@@ -107,12 +111,26 @@ public struct HarnessScriptGenerationRequest: Equatable, Sendable {self.entities = entitiesself.allowedActions = allowedActionsself.verification = verification+ self.scriptingDictionaryDigest = scriptingDictionaryDigestself.worldFacts = worldFactsself.sourceTraceID = sourceTraceIDself.metadata = metadata}}+/// What the runtime knows about the target app's scripting dictionary, handed to the harness so+/// AppleScript generation is grounded in declared terminology and validation can cross-check the+/// commands a generated script claims to use.+public struct HarnessScriptingDictionarySnapshot: Equatable, Sendable {+ public var digest: String+ public var commandNames: [String]++ public init(digest: String, commandNames: [String] = []) {+ self.digest = digest+ self.commandNames = commandNames+ }+}+public struct HarnessScriptGenerationOutcome: Equatable, Sendable {public var succeeded: Boolpublic var source: String@@ -132,6 +150,29 @@ public struct HarnessScriptGenerationOutcome: Equatable, Sendable {}}+/// Result of deterministically compiling an AppleScript artifact against the target app's real+/// dictionary, without executing it. AppleScript resolves terminology at compile time, so this is+/// a 100%-accurate syntax+terminology gate; failures carry the actual compiler message so the+/// planner can regenerate with the precise error in context.+public struct HarnessScriptCompileOutcome: Equatable, Sendable {+ public var compiled: Bool+ public var errorMessage: String+ public var errorRangeDescription: String+ public var metadata: [String: String]++ public init(+ compiled: Bool,+ errorMessage: String = "",+ errorRangeDescription: String = "",+ metadata: [String: String] = [:]+ ) {+ self.compiled = compiled+ self.errorMessage = errorMessage+ self.errorRangeDescription = errorRangeDescription+ self.metadata = metadata+ }+}+public actor HarnessGeneratedScriptStore {private var artifactsByID: [String: HarnessGeneratedScriptArtifact]@@ -186,6 +227,12 @@ public struct HarnessBuiltInToolServices: Sendable {public var applicationLearningStore: HarnessApplicationLearningStorepublic var applicationSkillPackWriter: HarnessApplicationSkillPackWriter?public var appleScriptGenerator: (@Sendable (HarnessScriptGenerationRequest) async -> HarnessScriptGenerationOutcome)?+ /// The target app's parsed scripting dictionary (digest + command names), or nil when no+ /// dictionary can be read. Grounds `automation.applescript.generate` in real terminology.+ public var scriptingDictionaryProvider: (@Sendable (_ targetApp: String, _ bundleIdentifier: String?) async -> HarnessScriptingDictionarySnapshot?)?+ /// Compiles AppleScript source against the target app's dictionary without executing it.+ /// When absent, validation runs the static checks only.+ public var appleScriptCompiler: (@Sendable (_ source: String, _ targetApp: String?, _ bundleIdentifier: String?) async -> HarnessScriptCompileOutcome)?public var appleScriptExecutor: (@Sendable (HarnessGeneratedScriptArtifact, HarnessToolExecutionContext) async -> HarnessScriptExecutionOutcome)?public var skillScriptExecutor: (@Sendable (HarnessGeneratedScriptArtifact, HarnessToolExecutionContext) async -> HarnessScriptExecutionOutcome)?/// Native Donkey Command Layer backend. Returns a result for a recognized@@ -209,6 +256,8 @@ public struct HarnessBuiltInToolServices: Sendable {applicationLearningStore: HarnessApplicationLearningStore = HarnessApplicationLearningStore(),applicationSkillPackWriter: HarnessApplicationSkillPackWriter? = nil,appleScriptGenerator: (@Sendable (HarnessScriptGenerationRequest) async -> HarnessScriptGenerationOutcome)? = nil,+ scriptingDictionaryProvider: (@Sendable (_ targetApp: String, _ bundleIdentifier: String?) async -> HarnessScriptingDictionarySnapshot?)? = nil,+ appleScriptCompiler: (@Sendable (_ source: String, _ targetApp: String?, _ bundleIdentifier: String?) async -> HarnessScriptCompileOutcome)? = nil,appleScriptExecutor: (@Sendable (HarnessGeneratedScriptArtifact, HarnessToolExecutionContext) async -> HarnessScriptExecutionOutcome)? = nil,skillScriptExecutor: (@Sendable (HarnessGeneratedScriptArtifact, HarnessToolExecutionContext) async -> HarnessScriptExecutionOutcome)? = nil,commandExecutor: (@Sendable (HarnessToolExecutionContext) async -> HarnessToolResult?)? = nil,@@ -222,6 +271,8 @@ public struct HarnessBuiltInToolServices: Sendable {self.applicationLearningStore = applicationLearningStoreself.applicationSkillPackWriter = applicationSkillPackWriterself.appleScriptGenerator = appleScriptGenerator+ self.scriptingDictionaryProvider = scriptingDictionaryProvider+ self.appleScriptCompiler = appleScriptCompilerself.appleScriptExecutor = appleScriptExecutorself.skillScriptExecutor = skillScriptExecutorself.commandExecutor = commandExecutor@@ -530,10 +581,14 @@ public enum BuiltInHarnessToolExecutors {_ = await services.generatedScripts.reject(id: scriptID, reason: "emptyScriptSource")return failed(context, "Script artifact has no source to validate.", reason: "emptyScriptSource")}- if artifact.language == .appleScript,- let rejectionReason = appleScriptValidationRejectionReason(artifact: artifact, context: context) {- _ = await services.generatedScripts.reject(id: scriptID, reason: rejectionReason)- return failed(context, "AppleScript artifact failed validation.", reason: rejectionReason)+ if artifact.language == .appleScript {+ if let rejectionReason = appleScriptValidationRejectionReason(artifact: artifact, context: context) {+ _ = await services.generatedScripts.reject(id: scriptID, reason: rejectionReason)+ return failed(context, "AppleScript artifact failed validation.", reason: rejectionReason)+ }+ if let gateRejection = await appleScriptGateRejection(artifact: artifact, context: context, services: services) {+ return gateRejection+ }}let validated = await services.generatedScripts.validate(@@ -602,6 +657,15 @@ public enum BuiltInHarnessToolExecutors {)}let status: HarnessToolResultStatus = outcome.succeeded ? .succeeded : .failed+ var resultMetadata = outcome.metadata.merging([+ "scriptArtifactID": scriptID,+ "executor": "guardedScriptBackend"+ ]) { current, _ in current }+ if outcome.succeeded {+ resultMetadata.merge(+ await promoteVerifiedGeneratedScript(artifact: artifact, services: services)+ ) { current, _ in current }+ }return HarnessToolResult(callID: context.call.id,toolName: context.call.name,@@ -615,11 +679,137 @@ public enum BuiltInHarnessToolExecutors {"lastAcceptedTool": context.call.name]),- metadata: outcome.metadata.merging([- "scriptArtifactID": scriptID,- "executor": "guardedScriptBackend"- ]) { current, _ in current }+ metadata: resultMetadata+ )+ }++ // MARK: - Promotion of verified generated scripts++ /// A dynamically generated AppleScript that compiled, executed, and reported success is proven+ /// terminology for this app on this machine. Promote it into a learned skill pack so the next+ /// run of the same task goes `app_skill` → `skill_run` with zero model-generated script: fully+ /// deterministic on the second run. Returns promotion metadata for the tool result (empty when+ /// promotion doesn't apply or no skill-pack writer is configured).+ private static func promoteVerifiedGeneratedScript(+ artifact: HarnessGeneratedScriptArtifact,+ services: HarnessBuiltInToolServices+ ) async -> [String: String] {+ guard artifact.createdByToolName == "automation.applescript.generate",+ artifact.validationStatus == .validated,+ let writer = services.applicationSkillPackWriter,+ let appName = trimmed(artifact.metadata["targetApp"])+ else {+ return [:]+ }+ let bundleIdentifier = trimmed(artifact.metadata["bundleIdentifier"])+ let purpose = artifact.metadata["purpose"] ?? artifact.metadata["goal"] ?? artifact.id+ let usedCommands = (artifact.metadata["generation.usedCommands"] ?? "")+ .split(separator: "\n")+ .map { $0.trimmingCharacters(in: .whitespaces) }+ .filter { !$0.isEmpty }++ // Dedup key: same app + same dictionary-command signature lands in the same pack, so a+ // repeat success updates the promoted script instead of accumulating duplicates.+ let dedupSeed = usedCommands.isEmpty+ ? "\(appName) \(purpose)"+ : "\(appName) \(usedCommands.joined(separator: " "))"+ let skillID = "promoted-\(stableIDSeed(from: dedupSeed))"++ let bindings = (artifact.metadata["generation.parameterBindings"] ?? "")+ .split(separator: "\n")+ .map { $0.trimmingCharacters(in: .whitespaces) }+ .filter { !$0.isEmpty }+ let (promotedSource, parameterized) = parameterizedPromotionSource(artifact.source, bindings: bindings)++ let promoted = HarnessGeneratedScriptArtifact(+ id: "\(skillID)-run",+ language: .appleScript,+ source: promotedSource,+ validationStatus: .validated,+ createdByToolName: artifact.createdByToolName,+ ownerSkillID: skillID,+ metadata: [+ "purpose": purpose,+ "targetApp": appName,+ "bundleIdentifier": bundleIdentifier ?? "",+ "generation.usedCommands": usedCommands.joined(separator: "\n"),+ "promotion.sourceArtifactID": artifact.id,+ "promotion.parameterized": parameterized ? "true" : "false",+ "validation.policy": "promotedVerifiedScript",+ "validation.provenance": artifact.metadata["generation.backend"] ?? "dynamicAppleScriptGenerator"+ ]+ )+ let profile = HarnessApplicationProfile(+ skillID: skillID,+ appName: appName,+ bundleIdentifier: bundleIdentifier,+ learningGoal: purpose,+ observations: [],+ workflowRecipes: [+ HarnessApplicationWorkflowRecipe(+ id: "\(skillID)-workflow",+ name: purpose,+ summary: "Run the promoted verified script via skill_run (skillID=\(skillID), scriptID=\(promoted.id))\(parameterized ? ", passing the task's value as `input`" : "").",+ steps: [+ HarnessApplicationWorkflowStep(+ id: "run-promoted-script",+ summary: "Execute the verified AppleScript for: \(purpose)",+ toolName: "skill_run",+ inputHints: parameterized+ ? ["skillID": skillID, "scriptID": promoted.id, "input": "the task's user-specific value"]+ : ["skillID": skillID, "scriptID": promoted.id],+ safetyClass: .guardedInput,+ verification: "the script reports a successful structured status"+ )+ ],+ verificationCriteria: ["script output reports success"],+ metadata: ["source": "appleScriptPromotion"]+ )+ ],+ generatedScriptIDs: [promoted.id],+ metadata: [+ "source": "appleScriptPromotion",+ "promotion.sourceArtifactID": artifact.id+ ])+ guard let saved = try? writer.save(profile: profile, scripts: [promoted]) else { return [:] }+ return [+ "promotion.skillID": saved.skill.id,+ "promotion.scriptID": saved.skill.scripts.first?.id ?? promoted.id,+ "promotion.parameterized": parameterized ? "true" : "false"+ ]+ }++ /// Turns one task-specific value back into a reusable template: when a generator-reported+ /// parameter binding's value appears as a quoted string literal in the source, replace it with+ /// the `{query}` token the skill executor substitutes from `input` at run time. Matching is+ /// quote-bounded so command words are never rewritten; with no recoverable binding the script+ /// is promoted as-is (a fixed, still-deterministic workflow).+ private static func parameterizedPromotionSource(+ _ source: String,+ bindings: [String]+ ) -> (source: String, parameterized: Bool) {+ for binding in bindings {+ let parts = binding.split(separator: "=", maxSplits: 1)+ guard parts.count == 2 else { continue }+ let value = String(parts[1]).trimmingCharacters(in: .whitespacesAndNewlines)+ guard value.count >= 2 else { continue }+ let quoted = "\"\(appleScriptStringEscaped(value))\""+ if source.contains(quoted) {+ return (source.replacingOccurrences(of: quoted, with: "\"{query}\""), true)+ }+ }+ return (source, false)+ }++ /// Mirrors the runtime template renderer's escaping so a promoted `{query}` slot re-renders to+ /// exactly the literal the verified script contained.+ private static func appleScriptStringEscaped(_ value: String) -> String {+ value+ .replacingOccurrences(of: "\\", with: "\\\\")+ .replacingOccurrences(of: "\"", with: "\\\"")+ .replacingOccurrences(of: "\n", with: "\\n")+ .replacingOccurrences(of: "\r", with: "\\r")}// MARK: - Screen & Elements@@ -862,6 +1052,16 @@ public enum BuiltInHarnessToolExecutors {guard let generator = services.appleScriptGenerator else {return failed(context, "No dynamic AppleScript generation backend is configured.", reason: "missingAppleScriptGenerationBackend")}+ // Ground generation in the app's real scripting dictionary when one can be read, and+ // record the grounding on the artifact so validation can cross-check used commands.+ let dictionary = await services.scriptingDictionaryProvider?(+ targetApp,+ trimmed(context.call.input["bundleIdentifier"])+ )+ input["generation.dictionaryGrounded"] = dictionary == nil ? "false" : "true"+ if let dictionary, !dictionary.commandNames.isEmpty {+ input["dictionary.commandNames"] = dictionary.commandNames.joined(separator: "\n")+ }let outcome = await generator(HarnessScriptGenerationRequest(language: .appleScript,@@ -871,6 +1071,7 @@ public enum BuiltInHarnessToolExecutors {entities: scriptGenerationEntities(from: context),allowedActions: context.call.input["allowedActions"] ?? "",verification: context.call.input["verification"] ?? "",+ scriptingDictionaryDigest: dictionary?.digest ?? "",worldFacts: context.worldModel.facts,sourceTraceID: context.call.metadata["traceID"],metadata: context.call.input@@ -909,6 +1110,88 @@ public enum BuiltInHarnessToolExecutors {return await scriptGenerate(generatedContext, services: services, ownerSkillID: nil)}+ /// Template tokens the runtime's script renderer substitutes. Matching is against this known+ /// set only — never generic `{…}`, which AppleScript uses for list/record literals.+ private static let appleScriptTemplateTokens = [+ "{query}", "{rawQuery}", "{queryLiteral}",+ "{entityValue}", "{rawEntityValue}",+ "{targetApp}", "{rawTargetApp}",+ "{bundleIdentifier}", "{rawBundleIdentifier}",+ "{input}"+ ]++ /// Deterministic gates for dynamically generated AppleScript, beyond the static text checks:+ /// unresolved template tokens (a parameter was never bound), commands the target app's+ /// dictionary doesn't declare, and a real compile against the app's terminology. Skill-pack+ /// template artifacts are exempt — they legitimately carry tokens until execution renders them.+ private static func appleScriptGateRejection(+ artifact: HarnessGeneratedScriptArtifact,+ context: HarnessToolExecutionContext,+ services: HarnessBuiltInToolServices+ ) async -> HarnessToolResult? {+ guard artifact.createdByToolName == "automation.applescript.generate" else { return nil }++ if let token = appleScriptTemplateTokens.first(where: artifact.source.contains) {+ let reason = "unresolvedTemplatePlaceholder:\(token)"+ _ = await services.generatedScripts.reject(id: artifact.id, reason: reason)+ return failed(+ context,+ "Generated AppleScript still contains the unresolved template token \(token); every parameter must be bound to a concrete value before validation.",+ reason: reason+ )+ }++ if let unknownCommand = commandNotInDictionary(artifact: artifact) {+ let reason = "commandNotInDictionary:\(unknownCommand)"+ _ = await services.generatedScripts.reject(id: artifact.id, reason: reason)+ return failed(+ context,+ "Generated AppleScript uses the command \"\(unknownCommand)\", which the target app's scripting dictionary does not declare. Regenerate using only commands from the dictionary digest.",+ reason: reason+ )+ }++ guard let compiler = services.appleScriptCompiler else { return nil }+ let targetApp = trimmed(context.call.input["targetApp"] ?? artifact.metadata["targetApp"])+ let bundleIdentifier = trimmed(context.call.input["bundleIdentifier"] ?? artifact.metadata["bundleIdentifier"])+ let compile = await compiler(artifact.source, targetApp, bundleIdentifier)+ guard !compile.compiled else { return nil }+ _ = await services.generatedScripts.reject(id: artifact.id, reason: "appleScriptCompileFailed")+ return HarnessToolResult(+ callID: context.call.id,+ toolName: context.call.name,+ status: .failed,+ summary: compile.errorMessage.isEmpty+ ? "AppleScript failed to compile against the target app's dictionary."+ : "AppleScript failed to compile: \(compile.errorMessage)",+ metadata: compile.metadata.merging([+ "reason": "appleScriptCompileFailed",+ "compile.errorMessage": compile.errorMessage,+ "compile.errorRange": compile.errorRangeDescription+ ]) { current, _ in current }+ )+ }++ /// Cross-checks the commands the generator CLAIMED to use against the dictionary command list+ /// stamped on the artifact at generation time. Structured-output-on-structured-data matching:+ /// a cheap hallucination catch before the (heavier) compile gate.+ private static func commandNotInDictionary(artifact: HarnessGeneratedScriptArtifact) -> String? {+ guard let usedRaw = artifact.metadata["generation.usedCommands"],+ let declaredRaw = artifact.metadata["dictionary.commandNames"]+ else {+ return nil+ }+ let declared = Set(+ declaredRaw.split(separator: "\n").map { $0.trimmingCharacters(in: .whitespaces).lowercased() }+ )+ guard !declared.isEmpty else { return nil }+ return usedRaw+ .split(separator: "\n")+ .map { $0.trimmingCharacters(in: .whitespaces) }+ .filter { !$0.isEmpty }+ .first { !declared.contains($0.lowercased()) }+ }+private static func appleScriptValidationRejectionReason(artifact: HarnessGeneratedScriptArtifact,context: HarnessToolExecutionContext@@ -933,7 +1216,8 @@ public enum BuiltInHarnessToolExecutors {"empty trash","shutdown","restart",- "quit "+ "quit ",+ "eppc://"]if let denied = deniedFragments.first(where: lowercased.contains) {return "disallowedAppleScriptFragment:\(denied)"diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swiftindex c671926b..8e667605 100644--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift@@ -366,13 +366,16 @@ public enum BuiltInHarnessToolCatalog {descriptor("automation.applescript.validate",pluginID: "core.automation",- summary: "Validate a generated AppleScript artifact before execution.",+ summary: "Validate a generated AppleScript artifact before execution: static safety checks, unresolved-parameter detection, and a real compile against the target app's scripting dictionary, so wrong terminology is rejected here with the actual compiler error instead of failing at execution.",input: ["scriptArtifactID": "Generated AppleScript artifact identifier.","targetApp": "Resolved app name and bundle identifier.","validationPolicy": "Static checks, allowed APIs, target app, permissions, and review state."],- output: ["validationStatus": "validated or rejected with reason."],+ output: [+ "validationStatus": "validated or rejected with reason.",+ "compile.errorMessage": "The AppleScript compiler's actual error message when the compile gate rejects the script — regenerate with this error in context."+ ],permissions: [.appLookup],safety: .readOnly,requiredContext: ["generated AppleScript artifact", "validation policy"],diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppUserQueryHarnessServices.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppUserQueryHarnessServices.swiftindex 732abc0b..727c7116 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppUserQueryHarnessServices.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppUserQueryHarnessServices.swift@@ -7,6 +7,29 @@ public enum LocalAppUserQueryHarnessServices {HarnessBuiltInToolServices(skillRegistry: HarnessSkillRegistry(skills: BuiltInLocalAppSkillPacks.descriptors()),generatedScripts: HarnessGeneratedScriptStore(artifacts: builtInValidatedScriptArtifacts()),+ // Learned + promoted skill packs land under the default LearnedApplications root, where+ // BuiltInLocalAppSkillPacks re-discovers them (30s TTL) for app_skill / skill_run.+ applicationSkillPackWriter: HarnessApplicationSkillPackWriter(+ rootDirectory: HarnessApplicationSkillPackWriter.defaultRootDirectory()+ ),+ scriptingDictionaryProvider: { targetApp, bundleIdentifier in+ let lookup = await AppScriptingDictionaryService.shared.lookup(+ appName: targetApp,+ bundleIdentifier: bundleIdentifier ?? targetApp+ )+ guard lookup.dictionary != nil else { return nil }+ return HarnessScriptingDictionarySnapshot(+ digest: lookup.digest,+ commandNames: lookup.commandNames+ )+ },+ appleScriptCompiler: { source, targetApp, bundleIdentifier in+ await NSAppleScriptCompileGate().compile(+ source: source,+ targetApp: targetApp,+ bundleIdentifier: bundleIdentifier+ )+ },appleScriptExecutor: { artifact, context inawait executeSkillScript(artifact: artifact, context: context)},diff --git a/apps/Donkey/Sources/DonkeyRuntime/MacAppleScriptActionEngineInputBackend.swift b/apps/Donkey/Sources/DonkeyRuntime/MacAppleScriptActionEngineInputBackend.swiftindex e2279c8b..3eb79a06 100644--- a/apps/Donkey/Sources/DonkeyRuntime/MacAppleScriptActionEngineInputBackend.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/MacAppleScriptActionEngineInputBackend.swift@@ -1,4 +1,5 @@import DonkeyContracts+import DonkeyHarnessimport Foundationpublic struct AppleScriptExecutionResult: Equatable, Sendable {@@ -50,6 +51,106 @@ public struct NSAppleScriptRunner: AppleScriptRunning {}}+/// Deterministic AppleScript compile gate: compiles source against the target app's real+/// dictionary WITHOUT executing it, returning the actual compiler error on failure. AppleScript+/// resolves terminology at compile time from the bundle on disk, so this catches wrong commands,+/// wrong parameter names, and syntax errors before anything runs — and never launches the app.+public struct NSAppleScriptCompileGate: Sendable {+ public static let compileTimeoutSeconds: TimeInterval = 5++ private let bundleResolver: @Sendable (_ bundleIdentifier: String?, _ appName: String?) -> URL?++ public init(+ bundleResolver: @escaping @Sendable (_ bundleIdentifier: String?, _ appName: String?) -> URL? = { bundleIdentifier, appName in+ MacAppScriptabilityProbe().bundleURL(bundleIdentifier: bundleIdentifier, appName: appName)+ }+ ) {+ self.bundleResolver = bundleResolver+ }++ public func compile(+ source: String,+ targetApp: String?,+ bundleIdentifier: String?+ ) async -> HarnessScriptCompileOutcome {+ // Resolve the target bundle BEFORE constructing NSAppleScript: compiling a `tell+ // application` block for an app Launch Services can't resolve raises a blocking+ // "Where is application …?" chooser panel. An unresolvable target is a deterministic+ // rejection, not a dialog.+ if targetApp != nil || bundleIdentifier != nil {+ guard bundleResolver(bundleIdentifier, targetApp) != nil else {+ return HarnessScriptCompileOutcome(+ compiled: false,+ errorMessage: "Target app is not installed or resolvable: \(targetApp ?? bundleIdentifier ?? "").",+ metadata: ["reason": "targetAppUnresolvable"]+ )+ }+ }+ // The MainActor compile is uncancellable, so the timeout races it rather than cancelling:+ // on timeout the bounded answer wins and the orphaned compile finishes in the background.+ return await withCheckedContinuation { continuation in+ let once = ResumeOnce()+ Task { @MainActor in+ let outcome = Self.compileSync(source)+ if once.claim() { continuation.resume(returning: outcome) }+ }+ Task {+ try? await Task.sleep(nanoseconds: UInt64(Self.compileTimeoutSeconds * 1_000_000_000))+ guard once.claim() else { return }+ continuation.resume(+ returning: HarnessScriptCompileOutcome(+ compiled: false,+ errorMessage: "AppleScript compile timed out after \(Int(Self.compileTimeoutSeconds))s.",+ metadata: ["reason": "compileTimeout"]+ )+ )+ }+ }+ }++ @MainActor+ private static func compileSync(_ source: String) -> HarnessScriptCompileOutcome {+ guard let script = NSAppleScript(source: source) else {+ return HarnessScriptCompileOutcome(+ compiled: false,+ errorMessage: "AppleScript source could not be parsed.",+ metadata: ["reason": "sourceUnparseable"]+ )+ }+ var error: NSDictionary?+ guard script.compileAndReturnError(&error) else {+ let message = (error?[NSAppleScript.errorMessage] as? String)+ ?? (error?[NSAppleScript.errorBriefMessage] as? String)+ ?? "AppleScript failed to compile."+ var rangeDescription = ""+ if let rangeValue = error?[NSAppleScript.errorRange] as? NSValue {+ let range = rangeValue.rangeValue+ rangeDescription = "characters \(range.location)–\(range.location + range.length)"+ }+ return HarnessScriptCompileOutcome(+ compiled: false,+ errorMessage: message,+ errorRangeDescription: rangeDescription,+ metadata: ["reason": "compileFailed"]+ )+ }+ return HarnessScriptCompileOutcome(compiled: true)+ }++ private final class ResumeOnce: @unchecked Sendable {+ private let lock = NSLock()+ private var resumed = false++ func claim() -> Bool {+ lock.lock()+ defer { lock.unlock() }+ guard !resumed else { return false }+ resumed = true+ return true+ }+ }+}+public struct MacAppleScriptActionEngineInputBackend: ActionEngineInputBackend {private let runner: any AppleScriptRunningdiff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AppleScriptCompileGateTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AppleScriptCompileGateTests.swiftnew file mode 100644index 00000000..e673d3e7--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AppleScriptCompileGateTests.swift@@ -0,0 +1,309 @@+import DonkeyContracts+import DonkeyHarness+import DonkeyRuntime+import Foundation+import Testing++/// Validation of dynamically generated AppleScript is deterministic: unresolved template tokens,+/// commands outside the app's dictionary, and real compile failures are all rejected before+/// execution, with the actual error surfaced to the planner.+@Suite+struct AppleScriptCompileGateTests {+ private func registry(+ scriptStore: HarnessGeneratedScriptStore,+ compiler: (@Sendable (String, String?, String?) async -> HarnessScriptCompileOutcome)? = nil,+ generator: @escaping @Sendable (HarnessScriptGenerationRequest) async -> HarnessScriptGenerationOutcome+ ) -> HarnessToolRegistry {+ BuiltInHarnessToolCatalog.registryWithBuiltInExecutors(+ services: HarnessBuiltInToolServices(+ generatedScripts: scriptStore,+ appleScriptGenerator: generator,+ appleScriptCompiler: compiler+ )+ )+ }++ private func generate(+ _ registry: HarnessToolRegistry,+ artifactID: String,+ targetApp: String = "Notes"+ ) async -> HarnessToolResult {+ await registry.execute(+ HarnessToolCall(+ id: "\(artifactID)-generate",+ name: "automation.applescript.generate",+ input: [+ "scriptArtifactID": artifactID,+ "targetApp": targetApp,+ "goal": "do the thing"+ ]+ ),+ taskID: "task-compile-gate",+ worldModel: HarnessWorldModel(),+ grantedPermissions: [.appLookup]+ )+ }++ private func validate(+ _ registry: HarnessToolRegistry,+ artifactID: String,+ targetApp: String = "Notes"+ ) async -> HarnessToolResult {+ await registry.execute(+ HarnessToolCall(+ id: "\(artifactID)-validate",+ name: "automation.applescript.validate",+ input: ["scriptArtifactID": artifactID, "targetApp": targetApp]+ ),+ taskID: "task-compile-gate",+ worldModel: HarnessWorldModel(),+ grantedPermissions: [.appLookup]+ )+ }++ @Test+ func compileFailureRejectsTheArtifactWithTheRealCompilerError() async {+ let scriptStore = HarnessGeneratedScriptStore()+ let registry = registry(+ scriptStore: scriptStore,+ compiler: { source, targetApp, _ in+ #expect(source.contains("frobnicate"))+ #expect(targetApp == "Notes")+ return HarnessScriptCompileOutcome(+ compiled: false,+ errorMessage: "The variable frobnicate is not defined.",+ errorRangeDescription: "characters 28–38"+ )+ },+ generator: { _ in+ HarnessScriptGenerationOutcome(+ succeeded: true,+ source: #"tell application "Notes" to frobnicate"#,+ summary: "Bad terminology."+ )+ }+ )++ _ = await generate(registry, artifactID: "bad-terminology")+ let validated = await validate(registry, artifactID: "bad-terminology")+ let artifact = await scriptStore.artifact(id: "bad-terminology")++ #expect(validated.status == .failed)+ #expect(validated.metadata["reason"] == "appleScriptCompileFailed")+ #expect(validated.summary.contains("The variable frobnicate is not defined."))+ #expect(validated.metadata["compile.errorMessage"] == "The variable frobnicate is not defined.")+ #expect(validated.metadata["compile.errorRange"] == "characters 28–38")+ #expect(artifact?.validationStatus == .rejected)+ }++ @Test+ func compileSuccessValidatesTheArtifact() async {+ let scriptStore = HarnessGeneratedScriptStore()+ let registry = registry(+ scriptStore: scriptStore,+ compiler: { _, _, _ in HarnessScriptCompileOutcome(compiled: true) },+ generator: { _ in+ HarnessScriptGenerationOutcome(+ succeeded: true,+ source: #"tell application "Notes" to count notes"#,+ summary: "Counts notes."+ )+ }+ )++ _ = await generate(registry, artifactID: "good-script")+ let validated = await validate(registry, artifactID: "good-script")+ let artifact = await scriptStore.artifact(id: "good-script")++ #expect(validated.status == .succeeded)+ #expect(artifact?.validationStatus == .validated)+ }++ @Test+ func unresolvedTemplateTokensAreRejectedButRecordLiteralsAreNot() async {+ let scriptStore = HarnessGeneratedScriptStore()+ let registry = registry(+ scriptStore: scriptStore,+ compiler: { _, _, _ in HarnessScriptCompileOutcome(compiled: true) },+ generator: { _ in+ HarnessScriptGenerationOutcome(+ succeeded: true,+ source: #"tell application "Notes" to make new note with properties {name:"{query}"}"#,+ summary: "Left a placeholder unbound."+ )+ }+ )++ _ = await generate(registry, artifactID: "unbound-placeholder")+ let validated = await validate(registry, artifactID: "unbound-placeholder")++ #expect(validated.status == .failed)+ #expect(validated.metadata["reason"] == "unresolvedTemplatePlaceholder:{query}")++ // AppleScript record/list literals use braces too; only the known token set rejects.+ let literalRegistry = registry2(scriptStore: scriptStore)+ _ = await generate(literalRegistry, artifactID: "record-literal")+ let literalValidated = await validate(literalRegistry, artifactID: "record-literal")+ #expect(literalValidated.status == .succeeded)+ }++ private func registry2(scriptStore: HarnessGeneratedScriptStore) -> HarnessToolRegistry {+ registry(+ scriptStore: scriptStore,+ compiler: { _, _, _ in HarnessScriptCompileOutcome(compiled: true) },+ generator: { _ in+ HarnessScriptGenerationOutcome(+ succeeded: true,+ source: #"tell application "Notes" to make new note with properties {name:"Groceries", body:"eggs"}"#,+ summary: "Concrete record literal."+ )+ }+ )+ }++ @Test+ func usedCommandsOutsideTheDictionaryAreRejectedBeforeCompile() async {+ let scriptStore = HarnessGeneratedScriptStore()+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors(+ services: HarnessBuiltInToolServices(+ generatedScripts: scriptStore,+ appleScriptGenerator: { _ in+ HarnessScriptGenerationOutcome(+ succeeded: true,+ source: #"tell application "Notes" to teleport"#,+ summary: "Hallucinated command.",+ metadata: ["usedCommands": "teleport"]+ )+ },+ scriptingDictionaryProvider: { _, _ in+ HarnessScriptingDictionarySnapshot(+ digest: "command \"make\"; command \"show\"",+ commandNames: ["make", "show"]+ )+ },+ appleScriptCompiler: { _, _, _ in+ Issue.record("compile must not run when the cross-check already rejected")+ return HarnessScriptCompileOutcome(compiled: true)+ }+ )+ )++ _ = await generate(registry, artifactID: "hallucinated-command")+ let validated = await validate(registry, artifactID: "hallucinated-command")+ let artifact = await scriptStore.artifact(id: "hallucinated-command")++ #expect(validated.status == .failed)+ #expect(validated.metadata["reason"] == "commandNotInDictionary:teleport")+ #expect(artifact?.validationStatus == .rejected)+ }++ @Test+ func withoutACompilerStaticChecksStillValidate() async {+ let scriptStore = HarnessGeneratedScriptStore()+ let registry = registry(+ scriptStore: scriptStore,+ compiler: nil,+ generator: { _ in+ HarnessScriptGenerationOutcome(+ succeeded: true,+ source: #"tell application "Notes" to count notes"#,+ summary: "Counts notes."+ )+ }+ )++ _ = await generate(registry, artifactID: "no-compiler")+ let validated = await validate(registry, artifactID: "no-compiler")++ #expect(validated.status == .succeeded)+ }++ @Test+ func skillTemplateArtifactsKeepTheirTokensThroughValidation() async {+ // Skill-pack templates legitimately carry tokens until execution renders them; the+ // placeholder/compile gates apply only to the dynamic automation path.+ let scriptStore = HarnessGeneratedScriptStore()+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors(+ services: HarnessBuiltInToolServices(+ generatedScripts: scriptStore,+ appleScriptCompiler: { _, _, _ in+ Issue.record("skill templates must not be compile-gated")+ return HarnessScriptCompileOutcome(compiled: false)+ }+ )+ )++ _ = await registry.execute(+ HarnessToolCall(+ id: "skill-template-generate",+ name: "skill.script.generate",+ input: [+ "skillID": "music-helper",+ "scriptID": "play-template",+ "language": "appleScript",+ "purpose": "play a track",+ "scriptSource": #"tell application "Music" to play track "{query}""#+ ]+ ),+ taskID: "task-template",+ worldModel: HarnessWorldModel(),+ grantedPermissions: [.skillLookup]+ )+ let validated = await registry.execute(+ HarnessToolCall(+ id: "skill-template-validate",+ name: "skill.script.validate",+ input: ["scriptID": "play-template", "targetApp": "Music"]+ ),+ taskID: "task-template",+ worldModel: HarnessWorldModel(),+ grantedPermissions: [.skillLookup]+ )++ #expect(validated.status == .succeeded)+ }+}++/// Live compile-gate smokes against real installed apps. Run with:+/// DEVELOPER_DIR=… DONKEY_LIVE_SMOKE=1 swift test --filter NSAppleScriptCompileGateLiveTests+@Suite+struct NSAppleScriptCompileGateLiveTests {+ private var isEnabled: Bool {+ ProcessInfo.processInfo.environment["DONKEY_LIVE_SMOKE"] == "1"+ }++ @Test+ func compilesRealTerminologyAgainstFinder() async {+ guard isEnabled else { return }+ let outcome = await NSAppleScriptCompileGate().compile(+ source: #"tell application "Finder" to get name of home"#,+ targetApp: "Finder",+ bundleIdentifier: "com.apple.finder"+ )+ #expect(outcome.compiled, "\(outcome.errorMessage)")+ }++ @Test+ func rejectsFakeTerminologyWithARealCompilerMessage() async {+ guard isEnabled else { return }+ let outcome = await NSAppleScriptCompileGate().compile(+ source: #"tell application "Finder" to frobnicate the wuzzle"#,+ targetApp: "Finder",+ bundleIdentifier: "com.apple.finder"+ )+ #expect(!outcome.compiled)+ #expect(!outcome.errorMessage.isEmpty)+ }++ @Test+ func rejectsAnUnresolvableAppWithoutTouchingNSAppleScript() async {+ guard isEnabled else { return }+ let outcome = await NSAppleScriptCompileGate().compile(+ source: #"tell application "Definitely Not Installed 9000" to activate"#,+ targetApp: "Definitely Not Installed 9000",+ bundleIdentifier: nil+ )+ #expect(!outcome.compiled)+ #expect(outcome.metadata["reason"] == "targetAppUnresolvable")+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AppleScriptPromotionTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AppleScriptPromotionTests.swiftnew file mode 100644index 00000000..364b8fc5--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AppleScriptPromotionTests.swift@@ -0,0 +1,225 @@+import DonkeyContracts+import DonkeyHarness+import DonkeyRuntime+import Foundation+import Testing++/// A generated AppleScript that compiled, validated, and executed successfully is promoted into a+/// learned skill pack, so the next run of the same task is `app_skill` → `skill_run` with no model+/// in the loop.+@Suite+struct AppleScriptPromotionTests {+ private func makeRegistry(+ root: URL,+ scriptStore: HarnessGeneratedScriptStore,+ executionSucceeds: Bool = true,+ source: String = #"tell application "Notes" to make new note with properties {name:"Groceries"}"#,+ generationMetadata: [String: String] = [+ "usedCommands": "make",+ "parameterBindings": "name=Groceries"+ ]+ ) -> HarnessToolRegistry {+ BuiltInHarnessToolCatalog.registryWithBuiltInExecutors(+ services: HarnessBuiltInToolServices(+ generatedScripts: scriptStore,+ applicationSkillPackWriter: HarnessApplicationSkillPackWriter(rootDirectory: root),+ appleScriptGenerator: { _ in+ HarnessScriptGenerationOutcome(+ succeeded: true,+ source: source,+ summary: "Creates the note.",+ metadata: generationMetadata+ )+ },+ appleScriptExecutor: { _, _ in+ HarnessScriptExecutionOutcome(+ succeeded: executionSucceeds,+ summary: executionSucceeds ? "Done." : "Failed.",+ output: executionSucceeds ? "status=created" : "status=failed"+ )+ }+ )+ )+ }++ private func runPipeline(+ _ registry: HarnessToolRegistry,+ artifactID: String+ ) async -> HarnessToolResult {+ _ = await registry.execute(+ HarnessToolCall(+ id: "\(artifactID)-generate",+ name: "automation.applescript.generate",+ input: [+ "scriptArtifactID": artifactID,+ "targetApp": "Notes",+ "bundleIdentifier": "com.apple.Notes",+ "goal": "create the Groceries note"+ ]+ ),+ taskID: "task-promotion",+ worldModel: HarnessWorldModel(),+ grantedPermissions: [.appLookup]+ )+ _ = await registry.execute(+ HarnessToolCall(+ id: "\(artifactID)-validate",+ name: "automation.applescript.validate",+ input: ["scriptArtifactID": artifactID, "targetApp": "Notes"]+ ),+ taskID: "task-promotion",+ worldModel: HarnessWorldModel(),+ grantedPermissions: [.appLookup]+ )+ return await registry.execute(+ HarnessToolCall(+ id: "\(artifactID)-execute",+ name: "automation.applescript.execute",+ input: ["scriptArtifactID": artifactID, "targetApp": "Notes"]+ ),+ taskID: "task-promotion",+ worldModel: HarnessWorldModel(),+ grantedPermissions: [.appControl, .input]+ )+ }++ private func temporaryRoot() -> URL {+ FileManager.default.temporaryDirectory+ .appendingPathComponent("applescript-promotion-tests-\(UUID().uuidString)", isDirectory: true)+ }++ @Test+ func successfulExecutionPromotesAParameterizedSkillPack() async throws {+ let root = temporaryRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let registry = makeRegistry(root: root, scriptStore: HarnessGeneratedScriptStore())++ let executed = await runPipeline(registry, artifactID: "notes-create-groceries")++ #expect(executed.status == .succeeded)+ let skillID = try #require(executed.metadata["promotion.skillID"])+ #expect(executed.metadata["promotion.parameterized"] == "true")++ let skillDirectory = root.appendingPathComponent(skillID, isDirectory: true)+ let skillMarkdown = try String(+ contentsOf: skillDirectory.appendingPathComponent("SKILL.md"), encoding: .utf8+ )+ // The pack is app-matched (apps: frontmatter) so app_skill discovers it for Notes.+ #expect(skillMarkdown.contains("apps: Notes, com.apple.Notes"))++ let scriptID = try #require(executed.metadata["promotion.scriptID"])+ let promotedSource = try String(+ contentsOf: skillDirectory.appendingPathComponent("scripts/\(scriptID).applescript"),+ encoding: .utf8+ )+ // The task-specific value became a reusable slot…+ #expect(promotedSource.contains(#"{name:"{query}"}"#))+ // …and re-rendering the slot with the original value reproduces the verified script exactly.+ let rerendered = promotedSource.replacingOccurrences(of: "{query}", with: "Groceries")+ #expect(rerendered == #"tell application "Notes" to make new note with properties {name:"Groceries"}"#)+ }++ @Test+ func repeatSuccessUpdatesTheSamePackInsteadOfDuplicating() async throws {+ let root = temporaryRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let registry = makeRegistry(root: root, scriptStore: HarnessGeneratedScriptStore())++ let first = await runPipeline(registry, artifactID: "first-run")+ let second = await runPipeline(registry, artifactID: "second-run")++ // Same app + same dictionary-command signature → same pack, updated in place.+ #expect(first.metadata["promotion.skillID"] == second.metadata["promotion.skillID"])+ let packs = try FileManager.default.contentsOfDirectory(atPath: root.path)+ #expect(packs.count == 1)+ let scriptsPath = root+ .appendingPathComponent(packs[0], isDirectory: true)+ .appendingPathComponent("scripts", isDirectory: true)+ let scripts = try FileManager.default.contentsOfDirectory(atPath: scriptsPath.path)+ #expect(scripts.count == 1)+ }++ @Test+ func failedExecutionDoesNotPromote() async throws {+ let root = temporaryRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let registry = makeRegistry(+ root: root,+ scriptStore: HarnessGeneratedScriptStore(),+ executionSucceeds: false+ )++ let executed = await runPipeline(registry, artifactID: "failing-run")++ #expect(executed.status == .failed)+ #expect(executed.metadata["promotion.skillID"] == nil)+ #expect(!FileManager.default.fileExists(atPath: root.path))+ }++ @Test+ func unparameterizableScriptsPromoteAsFixedWorkflows() async throws {+ let root = temporaryRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let registry = makeRegistry(+ root: root,+ scriptStore: HarnessGeneratedScriptStore(),+ source: #"tell application "Notes" to count notes"#,+ generationMetadata: ["usedCommands": "count", "parameterBindings": ""]+ )++ let executed = await runPipeline(registry, artifactID: "count-notes")++ #expect(executed.status == .succeeded)+ let skillID = try #require(executed.metadata["promotion.skillID"])+ #expect(executed.metadata["promotion.parameterized"] == "false")+ let scriptID = try #require(executed.metadata["promotion.scriptID"])+ let promotedSource = try String(+ contentsOf: root+ .appendingPathComponent(skillID, isDirectory: true)+ .appendingPathComponent("scripts/\(scriptID).applescript"),+ encoding: .utf8+ )+ #expect(promotedSource == #"tell application "Notes" to count notes"#)+ }++ @Test+ func skillPackScriptsAreNotRePromoted() async throws {+ let root = temporaryRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ // A pre-validated skill-pack artifact (not created by automation.applescript.generate)+ // executes through skill.script.execute without triggering promotion.+ let artifact = HarnessGeneratedScriptArtifact(+ id: "builtin-script",+ language: .appleScript,+ source: #"tell application "Music" to play"#,+ validationStatus: .validated,+ createdByToolName: "built-in-skill-pack",+ ownerSkillID: "music-helper",+ metadata: ["targetApp": "Music"]+ )+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors(+ services: HarnessBuiltInToolServices(+ generatedScripts: HarnessGeneratedScriptStore(artifacts: [artifact]),+ applicationSkillPackWriter: HarnessApplicationSkillPackWriter(rootDirectory: root),+ skillScriptExecutor: { _, _ in+ HarnessScriptExecutionOutcome(succeeded: true, summary: "Played.", output: "status=played")+ }+ )+ )++ let executed = await registry.execute(+ HarnessToolCall(+ id: "builtin-execute",+ name: "skill.script.execute",+ input: ["scriptID": "builtin-script"]+ ),+ taskID: "task-builtin",+ worldModel: HarnessWorldModel(),+ grantedPermissions: [.appControl, .input]+ )++ #expect(executed.status == .succeeded)+ #expect(executed.metadata["promotion.skillID"] == nil)+ #expect(!FileManager.default.fileExists(atPath: root.path))+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/DictionaryGroundedAppleScriptTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/DictionaryGroundedAppleScriptTests.swiftnew file mode 100644index 00000000..809800f3--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/DictionaryGroundedAppleScriptTests.swift@@ -0,0 +1,167 @@+import DonkeyAI+import DonkeyContracts+import DonkeyHarness+import Foundation+import Testing++/// Dynamic AppleScript generation is grounded in the target app's parsed scripting dictionary:+/// the harness fetches the digest, hands it to the generator, and records the grounding (and the+/// dictionary's command names) on the artifact for validation to cross-check.+@Suite+struct DictionaryGroundedAppleScriptTests {+ // MARK: Harness executor++ @Test+ func generateHandsTheDictionaryDigestToTheGeneratorAndStampsTheArtifact() async {+ let scriptStore = HarnessGeneratedScriptStore()+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors(+ services: HarnessBuiltInToolServices(+ generatedScripts: scriptStore,+ appleScriptGenerator: { request in+ #expect(request.scriptingDictionaryDigest.contains("command \"make\""))+ return HarnessScriptGenerationOutcome(+ succeeded: true,+ source: #"tell application "Notes" to make new note"#,+ summary: "Creates a note.",+ metadata: ["generator": "test-child-llm", "usedCommands": "make"]+ )+ },+ scriptingDictionaryProvider: { targetApp, bundleIdentifier in+ #expect(targetApp == "Notes")+ #expect(bundleIdentifier == "com.apple.Notes")+ return HarnessScriptingDictionarySnapshot(+ digest: "app \"Notes\" scripting dictionary:\nsuite \"Notes Suite\":\n command \"make\"",+ commandNames: ["make", "show"]+ )+ }+ )+ )++ let generated = await registry.execute(+ HarnessToolCall(+ id: "grounded-generate",+ name: "automation.applescript.generate",+ input: [+ "scriptArtifactID": "grounded-notes-create",+ "targetApp": "Notes",+ "bundleIdentifier": "com.apple.Notes",+ "goal": "create a note"+ ]+ ),+ taskID: "task-grounded",+ worldModel: HarnessWorldModel(),+ grantedPermissions: [.appLookup]+ )+ let artifact = await scriptStore.artifact(id: "grounded-notes-create")++ #expect(generated.status == .succeeded)+ #expect(artifact?.metadata["generation.dictionaryGrounded"] == "true")+ #expect(artifact?.metadata["dictionary.commandNames"] == "make\nshow")+ #expect(artifact?.metadata["generation.usedCommands"] == "make")+ }++ @Test+ func generateWithoutADictionaryProceedsUngroundedButFlagged() async {+ let scriptStore = HarnessGeneratedScriptStore()+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors(+ services: HarnessBuiltInToolServices(+ generatedScripts: scriptStore,+ appleScriptGenerator: { request in+ #expect(request.scriptingDictionaryDigest.isEmpty)+ return HarnessScriptGenerationOutcome(+ succeeded: true,+ source: #"tell application "Obscure" to activate"#,+ summary: "Activates the app."+ )+ },+ scriptingDictionaryProvider: { _, _ in nil }+ )+ )++ let generated = await registry.execute(+ HarnessToolCall(+ id: "ungrounded-generate",+ name: "automation.applescript.generate",+ input: [+ "scriptArtifactID": "ungrounded-script",+ "targetApp": "Obscure",+ "goal": "activate"+ ]+ ),+ taskID: "task-ungrounded",+ worldModel: HarnessWorldModel(),+ grantedPermissions: [.appLookup]+ )+ let artifact = await scriptStore.artifact(id: "ungrounded-script")++ #expect(generated.status == .succeeded)+ #expect(artifact?.metadata["generation.dictionaryGrounded"] == "false")+ #expect(artifact?.metadata["dictionary.commandNames"] == nil)+ }++ // MARK: Hosted generation adapter++ @Test+ func adapterEmbedsTheDigestAndRequestsTheV2SchemaWithUsedCommands() async throws {+ let modelOutput = """+ {"canGenerate":true,"blockedReason":"","scriptSource":"tell application \\"Notes\\" to make new note with properties {name:\\"Groceries\\"}","summary":"Creates the Groceries note.","safetyNotes":[],"expectedOutput":"status=created","usedCommands":["make"],"parameterBindings":["with properties={name:Groceries}"]}+ """+ let httpClient = FixtureAppleScriptHTTPClient(+ data: try JSONSerialization.data(withJSONObject: ["output_text": modelOutput])+ )+ let adapter = HostedAppleScriptGenerationAdapter(+ configuration: DonkeyBackendInferenceConfiguration(+ baseURL: URL(string: "https://donkey.example")!,+ clientID: "client-1"+ ),+ httpClient: httpClient+ )++ let outcome = await adapter.generateAppleScript(+ HarnessScriptGenerationRequest(+ language: .appleScript,+ targetApp: "Notes",+ bundleIdentifier: "com.apple.Notes",+ goal: "create the Groceries note",+ scriptingDictionaryDigest: "suite \"Notes Suite\": command \"make\" -> note"+ )+ )++ #expect(outcome.succeeded)+ #expect(outcome.source.contains("make new note"))+ #expect(outcome.metadata["schemaID"] == "dynamic_applescript_generation_v2")+ #expect(outcome.metadata["usedCommands"] == "make")+ #expect(outcome.metadata["parameterBindings"] == "with properties={name:Groceries}")++ let request = try #require(httpClient.requests.first)+ let body = try #require(+ request.httpBody.flatMap { try? JSONSerialization.jsonObject(with: $0) } as? [String: Any]+ )+ let text = try #require(body["text"] as? [String: Any])+ let format = try #require(text["format"] as? [String: Any])+ #expect(format["name"] as? String == "dynamic_applescript_generation_v2")+ let bodyString = String(data: try #require(request.httpBody), encoding: .utf8) ?? ""+ // The digest rides inside the structured prompt payload.+ #expect(bodyString.contains("scriptingDictionary"))+ #expect(bodyString.contains("Notes Suite"))+ // The instructions hard-ground generation in the digest.+ #expect(bodyString.contains("use ONLY command, parameter, class, property, and enumeration names"))+ }+}++private final class FixtureAppleScriptHTTPClient: AIHTTPClient, @unchecked Sendable {+ var data: Data+ var requests: [URLRequest] = []++ init(data: Data) {+ self.data = data+ }++ func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {+ requests.append(request)+ return (+ data,+ HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: [:])!+ )+ }+}