Skip to content

Open source CapCut alternative.

TypeScript

Complete application learning harness slice

David Lee0cd408cd44f
diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessApplicationLearning.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessApplicationLearning.swift
new file mode 100644
index 00000000..ffadb661
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessApplicationLearning.swift
@@ -0,0 +1,544 @@
+import Foundation
+
+public struct HarnessApplicationLearningObservation: Codable, Equatable, Sendable {
+ public var id: String
+ public var title: String
+ public var focusedApp: String?
+ public var focusedWindowTitle: String?
+ public var screenshotArtifactURL: String?
+ public var accessibilityArtifactURL: String?
+ public var visibleText: [String: String]
+ public var elements: [HarnessWorldElement]
+ public var navigationPath: [String]
+ public var changedFromPrevious: String
+ public var safetyNotes: [String]
+ public var capturedAt: Date
+ public var metadata: [String: String]
+
+ public init(
+ id: String,
+ title: String,
+ focusedApp: String? = nil,
+ focusedWindowTitle: String? = nil,
+ screenshotArtifactURL: String? = nil,
+ accessibilityArtifactURL: String? = nil,
+ visibleText: [String: String] = [:],
+ elements: [HarnessWorldElement] = [],
+ navigationPath: [String] = [],
+ changedFromPrevious: String = "",
+ safetyNotes: [String] = [],
+ capturedAt: Date = Date(),
+ metadata: [String: String] = [:]
+ ) {
+ self.id = id
+ self.title = title
+ self.focusedApp = focusedApp
+ self.focusedWindowTitle = focusedWindowTitle
+ self.screenshotArtifactURL = screenshotArtifactURL
+ self.accessibilityArtifactURL = accessibilityArtifactURL
+ self.visibleText = visibleText
+ self.elements = elements
+ self.navigationPath = navigationPath
+ self.changedFromPrevious = changedFromPrevious
+ self.safetyNotes = safetyNotes
+ self.capturedAt = capturedAt
+ self.metadata = metadata
+ }
+}
+
+public struct HarnessApplicationWorkflowStep: Codable, Equatable, Sendable {
+ public var id: String
+ public var summary: String
+ public var toolName: String?
+ public var inputHints: [String: String]
+ public var safetyClass: HarnessToolSafetyClass
+ public var verification: String
+ public var metadata: [String: String]
+
+ public init(
+ id: String,
+ summary: String,
+ toolName: String? = nil,
+ inputHints: [String: String] = [:],
+ safetyClass: HarnessToolSafetyClass = .readOnly,
+ verification: String = "",
+ metadata: [String: String] = [:]
+ ) {
+ self.id = id
+ self.summary = summary
+ self.toolName = toolName
+ self.inputHints = inputHints
+ self.safetyClass = safetyClass
+ self.verification = verification
+ self.metadata = metadata
+ }
+}
+
+public struct HarnessApplicationWorkflowRecipe: Codable, Equatable, Sendable {
+ public var id: String
+ public var name: String
+ public var summary: String
+ public var steps: [HarnessApplicationWorkflowStep]
+ public var verificationCriteria: [String]
+ public var metadata: [String: String]
+
+ public init(
+ id: String,
+ name: String,
+ summary: String,
+ steps: [HarnessApplicationWorkflowStep] = [],
+ verificationCriteria: [String] = [],
+ metadata: [String: String] = [:]
+ ) {
+ self.id = id
+ self.name = name
+ self.summary = summary
+ self.steps = steps
+ self.verificationCriteria = verificationCriteria
+ self.metadata = metadata
+ }
+}
+
+public struct HarnessApplicationProfile: Codable, Equatable, Sendable {
+ public var skillID: String
+ public var appName: String
+ public var bundleIdentifier: String?
+ public var learningGoal: String
+ public var observations: [HarnessApplicationLearningObservation]
+ public var workflowRecipes: [HarnessApplicationWorkflowRecipe]
+ public var generatedScriptIDs: [String]
+ public var safetyNotes: [String]
+ public var generatedAt: Date
+ public var metadata: [String: String]
+
+ public init(
+ skillID: String,
+ appName: String,
+ bundleIdentifier: String? = nil,
+ learningGoal: String,
+ observations: [HarnessApplicationLearningObservation],
+ workflowRecipes: [HarnessApplicationWorkflowRecipe] = [],
+ generatedScriptIDs: [String] = [],
+ safetyNotes: [String] = [],
+ generatedAt: Date = Date(),
+ metadata: [String: String] = [:]
+ ) {
+ self.skillID = skillID
+ self.appName = appName
+ self.bundleIdentifier = bundleIdentifier
+ self.learningGoal = learningGoal
+ self.observations = observations
+ self.workflowRecipes = workflowRecipes
+ self.generatedScriptIDs = generatedScriptIDs
+ self.safetyNotes = safetyNotes
+ self.generatedAt = generatedAt
+ self.metadata = metadata
+ }
+}
+
+public struct HarnessApplicationLearningDraft: Codable, Equatable, Sendable {
+ public var id: String
+ public var taskID: String
+ public var skillID: String
+ public var appName: String
+ public var bundleIdentifier: String?
+ public var learningGoal: String
+ public var explorationPolicy: String
+ public var observations: [HarnessApplicationLearningObservation]
+ public var profile: HarnessApplicationProfile?
+ public var createdAt: Date
+ public var updatedAt: Date
+ public var metadata: [String: String]
+
+ public init(
+ id: String,
+ taskID: String,
+ skillID: String,
+ appName: String,
+ bundleIdentifier: String? = nil,
+ learningGoal: String,
+ explorationPolicy: String,
+ observations: [HarnessApplicationLearningObservation] = [],
+ profile: HarnessApplicationProfile? = nil,
+ createdAt: Date = Date(),
+ updatedAt: Date = Date(),
+ metadata: [String: String] = [:]
+ ) {
+ self.id = id
+ self.taskID = taskID
+ self.skillID = skillID
+ self.appName = appName
+ self.bundleIdentifier = bundleIdentifier
+ self.learningGoal = learningGoal
+ self.explorationPolicy = explorationPolicy
+ self.observations = observations
+ self.profile = profile
+ self.createdAt = createdAt
+ self.updatedAt = updatedAt
+ self.metadata = metadata
+ }
+}
+
+public struct HarnessApplicationSkillPackSaveResult: Codable, Equatable, Sendable {
+ public var skill: HarnessSkillDescriptor
+ public var directoryPath: String
+ public var writtenFiles: [String]
+ public var scriptCount: Int
+
+ public init(
+ skill: HarnessSkillDescriptor,
+ directoryPath: String,
+ writtenFiles: [String],
+ scriptCount: Int
+ ) {
+ self.skill = skill
+ self.directoryPath = directoryPath
+ self.writtenFiles = writtenFiles
+ self.scriptCount = scriptCount
+ }
+}
+
+public actor HarnessApplicationLearningStore {
+ private var draftsByID: [String: HarnessApplicationLearningDraft]
+
+ public init(drafts: [HarnessApplicationLearningDraft] = []) {
+ self.draftsByID = Dictionary(uniqueKeysWithValues: drafts.map { ($0.id, $0) })
+ }
+
+ @discardableResult
+ public func begin(
+ draftID: String,
+ taskID: String,
+ skillID: String,
+ appName: String,
+ bundleIdentifier: String?,
+ learningGoal: String,
+ explorationPolicy: String,
+ metadata: [String: String] = [:]
+ ) -> HarnessApplicationLearningDraft {
+ let draft = HarnessApplicationLearningDraft(
+ id: draftID,
+ taskID: taskID,
+ skillID: skillID,
+ appName: appName,
+ bundleIdentifier: bundleIdentifier,
+ learningGoal: learningGoal,
+ explorationPolicy: explorationPolicy,
+ metadata: metadata
+ )
+ draftsByID[draftID] = draft
+ return draft
+ }
+
+ public func draft(id: String) -> HarnessApplicationLearningDraft? {
+ draftsByID[id]
+ }
+
+ @discardableResult
+ public func record(
+ draftID: String,
+ observation: HarnessApplicationLearningObservation
+ ) -> HarnessApplicationLearningDraft? {
+ guard var draft = draftsByID[draftID] else { return nil }
+ if let index = draft.observations.firstIndex(where: { $0.id == observation.id }) {
+ draft.observations[index] = observation
+ } else {
+ draft.observations.append(observation)
+ }
+ draft.updatedAt = Date()
+ draftsByID[draftID] = draft
+ return draft
+ }
+
+ @discardableResult
+ public func distill(
+ draftID: String,
+ workflowRecipes: [HarnessApplicationWorkflowRecipe] = [],
+ generatedScriptIDs: [String] = [],
+ safetyNotes: [String] = [],
+ metadata: [String: String] = [:]
+ ) -> HarnessApplicationProfile? {
+ guard var draft = draftsByID[draftID],
+ !draft.observations.isEmpty
+ else {
+ return nil
+ }
+ let profile = HarnessApplicationProfile(
+ skillID: draft.skillID,
+ appName: draft.appName,
+ bundleIdentifier: draft.bundleIdentifier,
+ learningGoal: draft.learningGoal,
+ observations: draft.observations,
+ workflowRecipes: workflowRecipes.isEmpty ? Self.defaultRecipes(for: draft) : workflowRecipes,
+ generatedScriptIDs: generatedScriptIDs,
+ safetyNotes: Array(Set(draft.observations.flatMap(\.safetyNotes) + safetyNotes)).sorted(),
+ metadata: draft.metadata.merging(metadata) { current, _ in current }
+ )
+ draft.profile = profile
+ draft.updatedAt = Date()
+ draftsByID[draftID] = draft
+ return profile
+ }
+
+ private static func defaultRecipes(for draft: HarnessApplicationLearningDraft) -> [HarnessApplicationWorkflowRecipe] {
+ let steps = draft.observations.enumerated().map { index, observation in
+ HarnessApplicationWorkflowStep(
+ id: "observe-\(index + 1)",
+ summary: "Observe \(observation.title)",
+ toolName: "screen.observe",
+ inputHints: ["stateID": observation.id],
+ safetyClass: .readOnly,
+ verification: observation.focusedWindowTitle ?? observation.title
+ )
+ }
+ return [
+ HarnessApplicationWorkflowRecipe(
+ id: "inspect-\(slug(draft.appName))",
+ name: "Inspect \(draft.appName)",
+ summary: "Safely observe learned \(draft.appName) surfaces before acting.",
+ steps: steps,
+ verificationCriteria: draft.observations.map(\.title),
+ metadata: ["generated": "defaultObservationRecipe"]
+ )
+ ]
+ }
+
+ private static func slug(_ value: String) -> String {
+ value.lowercased()
+ .split { !$0.isLetter && !$0.isNumber }
+ .joined(separator: "-")
+ }
+}
+
+public struct HarnessApplicationSkillPackWriter: Sendable {
+ public var rootDirectory: URL
+
+ public init(rootDirectory: URL) {
+ self.rootDirectory = rootDirectory
+ }
+
+ public static func defaultRootDirectory() -> URL {
+ FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
+ .appendingPathComponent("Donkey", isDirectory: true)
+ .appendingPathComponent("Skills", isDirectory: true)
+ .appendingPathComponent("LearnedApplications", isDirectory: true)
+ }
+
+ public func save(
+ profile: HarnessApplicationProfile,
+ scripts: [HarnessGeneratedScriptArtifact] = []
+ ) throws -> HarnessApplicationSkillPackSaveResult {
+ let skillID = sanitizedSlug(profile.skillID.isEmpty ? "learned-\(profile.appName)" : profile.skillID)
+ var savedProfile = profile
+ savedProfile.generatedScriptIDs = Array(
+ Set(profile.generatedScriptIDs + scripts.filter { $0.validationStatus == .validated }.map(\.id))
+ ).sorted()
+ let skillDirectory = rootDirectory.appendingPathComponent(skillID, isDirectory: true)
+ let scriptsDirectory = skillDirectory.appendingPathComponent("scripts", isDirectory: true)
+ let evidenceDirectory = skillDirectory.appendingPathComponent("evidence", isDirectory: true)
+
+ try FileManager.default.createDirectory(at: scriptsDirectory, withIntermediateDirectories: true)
+ try FileManager.default.createDirectory(at: evidenceDirectory, withIntermediateDirectories: true)
+
+ var written: [String] = []
+ let skillMarkdown = skillMarkdown(for: savedProfile, skillID: skillID, scripts: scripts)
+ let skillMarkdownURL = skillDirectory.appendingPathComponent("SKILL.md")
+ try write(skillMarkdown, to: skillMarkdownURL)
+ written.append(skillMarkdownURL.path)
+
+ let encoder = JSONEncoder()
+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
+ encoder.dateEncodingStrategy = .iso8601
+ let profileURL = skillDirectory.appendingPathComponent("app-profile.json")
+ try encoder.encode(savedProfile).write(to: profileURL, options: .atomic)
+ written.append(profileURL.path)
+
+ let workflowsURL = skillDirectory.appendingPathComponent("workflows.json")
+ try encoder.encode(savedProfile.workflowRecipes).write(to: workflowsURL, options: .atomic)
+ written.append(workflowsURL.path)
+
+ let evidenceIndex = savedProfile.observations.map { observation in
+ HarnessApplicationEvidenceIndexEntry(
+ id: observation.id,
+ title: observation.title,
+ screenshotArtifactURL: observation.screenshotArtifactURL,
+ accessibilityArtifactURL: observation.accessibilityArtifactURL,
+ focusedWindowTitle: observation.focusedWindowTitle,
+ navigationPath: observation.navigationPath
+ )
+ }
+ let evidenceURL = evidenceDirectory.appendingPathComponent("index.json")
+ try encoder.encode(evidenceIndex).write(to: evidenceURL, options: .atomic)
+ written.append(evidenceURL.path)
+
+ var scriptDescriptors: [HarnessSkillScriptDescriptor] = []
+ for artifact in scripts where artifact.validationStatus == .validated {
+ let scriptName = "\(sanitizedSlug(artifact.id)).\(fileExtension(for: artifact.language))"
+ let scriptURL = scriptsDirectory.appendingPathComponent(scriptName)
+ try write(artifact.source, to: scriptURL)
+ written.append(scriptURL.path)
+ scriptDescriptors.append(
+ HarnessSkillScriptDescriptor(
+ id: sanitizedSlug(artifact.id),
+ language: skillLanguage(for: artifact.language),
+ purpose: artifact.metadata["purpose"] ?? artifact.id,
+ relativePath: "scripts/\(scriptName)",
+ generatedBy: artifact.createdByToolName,
+ validationStatus: .validated,
+ requiredPermissions: requiredPermissions(for: artifact.language),
+ safetyClass: artifact.language == .appleScript ? .guardedInput : .sensitive,
+ metadata: artifact.metadata.merging([
+ "scriptArtifactID": artifact.id,
+ "source": "applicationLearning"
+ ]) { current, _ in current }
+ )
+ )
+ }
+
+ let descriptor = HarnessSkillDescriptor(
+ id: skillID,
+ name: "\(profile.appName) Learned Application",
+ summary: "Learned surfaces and safe workflows for \(profile.appName).",
+ description: skillMarkdown,
+ sourceKind: .userDirectory,
+ instructionPath: skillMarkdownURL.path,
+ tags: ["application-learning", "learned-app", sanitizedSlug(profile.appName)],
+ providedToolNames: [
+ "screen.observe",
+ "elements.get",
+ "element.perform",
+ "state.verify"
+ ],
+ scripts: scriptDescriptors,
+ requiredPermissions: [.screenCapture, .accessibility],
+ metadata: [
+ "appName": profile.appName,
+ "bundleIdentifier": profile.bundleIdentifier ?? "",
+ "directory": skillDirectory.path,
+ "source": "applicationLearning"
+ ]
+ )
+
+ return HarnessApplicationSkillPackSaveResult(
+ skill: descriptor,
+ directoryPath: skillDirectory.path,
+ writtenFiles: written.sorted(),
+ scriptCount: scriptDescriptors.count
+ )
+ }
+
+ private struct HarnessApplicationEvidenceIndexEntry: Codable, Equatable {
+ var id: String
+ var title: String
+ var screenshotArtifactURL: String?
+ var accessibilityArtifactURL: String?
+ var focusedWindowTitle: String?
+ var navigationPath: [String]
+ }
+
+ private func skillMarkdown(
+ for profile: HarnessApplicationProfile,
+ skillID: String,
+ scripts: [HarnessGeneratedScriptArtifact]
+ ) -> String {
+ let visibleSurfaces = profile.observations
+ .map { "- \($0.title): \($0.focusedWindowTitle ?? "window unknown")" }
+ .joined(separator: "\n")
+ let workflows = profile.workflowRecipes
+ .map { "- \($0.name): \($0.summary)" }
+ .joined(separator: "\n")
+ let safety = profile.safetyNotes.isEmpty
+ ? "- Default to read-only observation and ask before destructive, send, purchase, or overwrite actions."
+ : profile.safetyNotes.map { "- \($0)" }.joined(separator: "\n")
+ let scriptLines = scripts
+ .filter { $0.validationStatus == .validated }
+ .map { "- \($0.id): \($0.metadata["purpose"] ?? $0.id)" }
+ .joined(separator: "\n")
+
+ return """
+ # \(profile.appName) Learned Application
+ id: \(skillID)
+ description: Learned surfaces and safe workflows for \(profile.appName).
+ tags: application-learning, learned-app, \(sanitizedSlug(profile.appName))
+ tools: screen.observe, elements.get, element.perform, state.verify
+
+ Use this skill when operating \(profile.appName) or a compatible app surface.
+
+ Learning goal: \(profile.learningGoal)
+
+ Prefer safe exploration first: observe the screen, inspect Accessibility elements, open menus or tabs only when the action is reversible, and ask before destructive, sending, purchasing, or save-overwrite actions.
+
+ ## Learned Surfaces
+
+ \(visibleSurfaces.isEmpty ? "- No surfaces recorded." : visibleSurfaces)
+
+ ## Workflow Recipes
+
+ \(workflows.isEmpty ? "- No workflow recipes recorded." : workflows)
+
+ ## Safety Notes
+
+ \(safety)
+
+ ## Scripts
+
+ \(scriptLines.isEmpty ? "- No validated scripts recorded." : scriptLines)
+ """
+ }
+
+ private func write(_ value: String, to url: URL) throws {
+ try value.write(to: url, atomically: true, encoding: .utf8)
+ }
+
+ private func sanitizedSlug(_ value: String) -> String {
+ let slug = value.lowercased()
+ .split { !$0.isLetter && !$0.isNumber }
+ .joined(separator: "-")
+ return slug.isEmpty ? "learned-application" : slug
+ }
+
+ private func fileExtension(for language: HarnessGeneratedScriptLanguage) -> String {
+ switch language {
+ case .appleScript:
+ return "applescript"
+ case .shell:
+ return "sh"
+ case .javaScript:
+ return "js"
+ case .python:
+ return "py"
+ case .swift:
+ return "swift"
+ case .unknown:
+ return "txt"
+ }
+ }
+
+ private func skillLanguage(for language: HarnessGeneratedScriptLanguage) -> HarnessSkillScriptLanguage {
+ switch language {
+ case .appleScript:
+ return .appleScript
+ case .shell:
+ return .shell
+ case .javaScript:
+ return .javaScript
+ case .python:
+ return .python
+ case .swift:
+ return .swift
+ case .unknown:
+ return .unknown
+ }
+ }
+
+ private func requiredPermissions(for language: HarnessGeneratedScriptLanguage) -> [HarnessPermission] {
+ switch language {
+ case .appleScript:
+ return [.appControl, .input]
+ case .shell, .javaScript, .python, .swift:
+ return [.input]
+ case .unknown:
+ return []
+ }
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift
index fb03c797..33d0a0de 100644
--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift
+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift
@@ -115,6 +115,15 @@ public actor HarnessGeneratedScriptStore {
artifactsByID[id]
}
+ public func artifacts(ownerSkillID: String? = nil) -> [HarnessGeneratedScriptArtifact] {
+ artifactsByID.values
+ .filter { artifact in
+ guard let ownerSkillID else { return true }
+ return artifact.ownerSkillID == ownerSkillID
+ }
+ .sorted { $0.id < $1.id }
+ }
+
public func validate(
id: String,
metadata: [String: String] = [:]
@@ -143,6 +152,8 @@ public struct HarnessBuiltInToolServices: Sendable {
public var appEntries: [HarnessAppLookupEntry]
public var skillRegistry: HarnessSkillRegistry?
public var generatedScripts: HarnessGeneratedScriptStore
+ public var applicationLearningStore: HarnessApplicationLearningStore
+ public var applicationSkillPackWriter: HarnessApplicationSkillPackWriter?
public var appleScriptExecutor: (@Sendable (HarnessGeneratedScriptArtifact, HarnessToolExecutionContext) async -> HarnessScriptExecutionOutcome)?
public var skillScriptExecutor: (@Sendable (HarnessGeneratedScriptArtifact, HarnessToolExecutionContext) async -> HarnessScriptExecutionOutcome)?
@@ -151,6 +162,8 @@ public struct HarnessBuiltInToolServices: Sendable {
appEntries: [HarnessAppLookupEntry] = [],
skillRegistry: HarnessSkillRegistry? = nil,
generatedScripts: HarnessGeneratedScriptStore = HarnessGeneratedScriptStore(),
+ applicationLearningStore: HarnessApplicationLearningStore = HarnessApplicationLearningStore(),
+ applicationSkillPackWriter: HarnessApplicationSkillPackWriter? = nil,
appleScriptExecutor: (@Sendable (HarnessGeneratedScriptArtifact, HarnessToolExecutionContext) async -> HarnessScriptExecutionOutcome)? = nil,
skillScriptExecutor: (@Sendable (HarnessGeneratedScriptArtifact, HarnessToolExecutionContext) async -> HarnessScriptExecutionOutcome)? = nil
) {
@@ -158,6 +171,8 @@ public struct HarnessBuiltInToolServices: Sendable {
self.appEntries = appEntries
self.skillRegistry = skillRegistry
self.generatedScripts = generatedScripts
+ self.applicationLearningStore = applicationLearningStore
+ self.applicationSkillPackWriter = applicationSkillPackWriter
self.appleScriptExecutor = appleScriptExecutor
self.skillScriptExecutor = skillScriptExecutor
}
@@ -216,6 +231,16 @@ public enum BuiltInHarnessToolExecutors {
return await appleScriptGenerate(context, services: services)
case "automation.applescript.execute":
return await scriptExecute(context, services: services, executor: services.appleScriptExecutor)
+ case "application.learning.start":
+ return await applicationLearningStart(context, services: services)
+ case "application.learning.captureState":
+ return await applicationLearningCaptureState(context, services: services)
+ case "application.learning.proposeExploration":
+ return applicationLearningProposeExploration(context)
+ case "application.learning.distill":
+ return await applicationLearningDistill(context, services: services)
+ case "application.learning.saveSkillPack":
+ return await applicationLearningSaveSkillPack(context, services: services)
case "state.verify":
return stateVerify(context)
case "run.pause", "run.resume", "run.recover", "run.cancel", "run.complete", "run.failSafe":
@@ -724,6 +749,267 @@ public enum BuiltInHarnessToolExecutors {
return await scriptGenerate(generatedContext, services: services, ownerSkillID: nil)
}
+ private static func applicationLearningStart(
+ _ context: HarnessToolExecutionContext,
+ services: HarnessBuiltInToolServices
+ ) async -> HarnessToolResult {
+ guard let appName = trimmed(context.call.input["appName"] ?? context.call.input["targetApp"] ?? context.worldModel.focusedApp) else {
+ return invalidInput(context, "application.learning.start requires a target app.")
+ }
+ let skillID = trimmed(context.call.input["skillID"]) ?? "learned-\(stableIDSeed(from: appName))"
+ let draftID = trimmed(context.call.input["draftID"]) ?? "\(context.taskID)-\(skillID)"
+ let learningGoal = trimmed(context.call.input["goal"]) ?? "Learn \(appName)."
+ let policy = trimmed(context.call.input["explorationPolicy"])
+ ?? "Safe exploration only: observe, inspect Accessibility elements, open reversible menus/tabs/fields, and ask before destructive, send, purchase, or save-overwrite actions."
+
+ let draft = await services.applicationLearningStore.begin(
+ draftID: draftID,
+ taskID: context.taskID,
+ skillID: skillID,
+ appName: appName,
+ bundleIdentifier: trimmed(context.call.input["bundleIdentifier"]),
+ learningGoal: learningGoal,
+ explorationPolicy: policy,
+ metadata: [
+ "createdBy": context.call.name,
+ "safeExploration": "true"
+ ]
+ )
+
+ return success(
+ context,
+ summary: "Started application learning draft for \(appName).",
+ facts: [
+ "application.learning.draftID": draft.id,
+ "application.learning.skillID": draft.skillID,
+ "application.learning.appName": draft.appName,
+ "application.learning.explorationPolicy": draft.explorationPolicy,
+ "lastAcceptedTool": context.call.name
+ ],
+ metadata: [
+ "draftID": draft.id,
+ "skillID": draft.skillID,
+ "appName": draft.appName,
+ "bundleIdentifier": draft.bundleIdentifier ?? ""
+ ]
+ )
+ }
+
+ private static func applicationLearningCaptureState(
+ _ context: HarnessToolExecutionContext,
+ services: HarnessBuiltInToolServices
+ ) async -> HarnessToolResult {
+ guard let draftID = trimmed(context.call.input["draftID"] ?? context.worldModel.facts["application.learning.draftID"]) else {
+ return invalidInput(context, "application.learning.captureState requires a learning draftID.")
+ }
+ guard await services.applicationLearningStore.draft(id: draftID) != nil else {
+ return failed(context, "Application learning draft was not found: \(draftID)", reason: "learningDraftNotFound")
+ }
+
+ let stateID = trimmed(context.call.input["stateID"])
+ ?? "state-\(stableIDSeed(from: context.call.input["title"] ?? context.worldModel.focusedWindowTitle ?? UUID().uuidString))"
+ let title = trimmed(context.call.input["title"])
+ ?? context.worldModel.focusedWindowTitle
+ ?? context.worldModel.focusedApp
+ ?? stateID
+ let observation = HarnessApplicationLearningObservation(
+ id: stateID,
+ title: title,
+ focusedApp: context.worldModel.focusedApp,
+ focusedWindowTitle: context.worldModel.focusedWindowTitle,
+ screenshotArtifactURL: trimmed(
+ context.call.input["screenshotArtifactURL"]
+ ?? context.worldModel.facts["screenshotArtifactURL"]
+ ?? context.worldModel.facts["screen.observe.screenshotArtifactURL"]
+ ),
+ accessibilityArtifactURL: trimmed(
+ context.call.input["accessibilityArtifactURL"]
+ ?? context.worldModel.facts["accessibilityArtifactURL"]
+ ?? context.worldModel.facts["screen.observe.accessibilityArtifactURL"]
+ ),
+ visibleText: context.worldModel.visibleText,
+ elements: context.worldModel.elements,
+ navigationPath: listValues(context.call.input["navigationPath"]),
+ changedFromPrevious: context.call.input["changedFromPrevious"] ?? "",
+ safetyNotes: listValues(context.call.input["safetyNotes"]),
+ metadata: [
+ "capturedBy": context.call.name,
+ "elementCount": String(context.worldModel.elements.count),
+ "visibleTextRegionCount": String(context.worldModel.visibleText.count)
+ ]
+ )
+
+ guard let draft = await services.applicationLearningStore.record(
+ draftID: draftID,
+ observation: observation
+ ) else {
+ return failed(context, "Application learning draft was not found: \(draftID)", reason: "learningDraftNotFound")
+ }
+
+ return success(
+ context,
+ summary: "Captured learned app state \(observation.title).",
+ facts: [
+ "application.learning.draftID": draft.id,
+ "application.learning.lastStateID": observation.id,
+ "application.learning.observationCount": String(draft.observations.count),
+ "application.learning.lastStateElementCount": String(observation.elements.count),
+ "lastAcceptedTool": context.call.name
+ ],
+ metadata: [
+ "draftID": draft.id,
+ "stateID": observation.id,
+ "observationCount": String(draft.observations.count),
+ "screenshotArtifactURL": observation.screenshotArtifactURL ?? "",
+ "accessibilityArtifactURL": observation.accessibilityArtifactURL ?? ""
+ ]
+ )
+ }
+
+ private static func applicationLearningProposeExploration(
+ _ context: HarnessToolExecutionContext
+ ) -> HarnessToolResult {
+ let candidates = context.worldModel.elements.compactMap { element -> String? in
+ guard element.isActionEligible,
+ let action = safeExplorationAction(for: element)
+ else {
+ return nil
+ }
+ return "\(element.id):\(action)"
+ }
+ let approvalCandidates = context.worldModel.elements.compactMap { element -> String? in
+ guard element.isActionEligible,
+ safeExplorationAction(for: element) == nil,
+ !element.actions.isEmpty
+ else {
+ return nil
+ }
+ return element.id
+ }
+
+ return success(
+ context,
+ summary: "Proposed \(candidates.count) safe exploration candidate(s).",
+ facts: [
+ "application.learning.safeExplorationCandidateCount": String(candidates.count),
+ "application.learning.safeExplorationCandidates": candidates.joined(separator: ","),
+ "application.learning.requiresApprovalCandidateIDs": approvalCandidates.joined(separator: ","),
+ "lastAcceptedTool": context.call.name
+ ],
+ metadata: [
+ "safeCandidateCount": String(candidates.count),
+ "safeCandidates": candidates.joined(separator: ","),
+ "requiresApprovalCandidateIDs": approvalCandidates.joined(separator: ",")
+ ]
+ )
+ }
+
+ private static func applicationLearningDistill(
+ _ context: HarnessToolExecutionContext,
+ services: HarnessBuiltInToolServices
+ ) async -> HarnessToolResult {
+ guard let draftID = trimmed(context.call.input["draftID"] ?? context.worldModel.facts["application.learning.draftID"]) else {
+ return invalidInput(context, "application.learning.distill requires a learning draftID.")
+ }
+ let workflowName = trimmed(context.call.input["workflowName"]) ?? "Safe inspection"
+ let workflowSummary = trimmed(context.call.input["workflowSummary"])
+ ?? "Use learned observations to inspect the application before taking guarded action."
+ let recipe = HarnessApplicationWorkflowRecipe(
+ id: stableIDSeed(from: workflowName),
+ name: workflowName,
+ summary: workflowSummary,
+ verificationCriteria: listValues(context.call.input["verificationCriteria"]),
+ metadata: ["createdBy": context.call.name]
+ )
+ let scriptIDs = listValues(context.call.input["scriptIDs"])
+ guard let profile = await services.applicationLearningStore.distill(
+ draftID: draftID,
+ workflowRecipes: [recipe],
+ generatedScriptIDs: scriptIDs,
+ safetyNotes: listValues(context.call.input["safetyNotes"]),
+ metadata: ["distilledBy": context.call.name]
+ ) else {
+ return failed(context, "Application learning draft has no observations to distill.", reason: "learningDraftNotReady")
+ }
+
+ return success(
+ context,
+ summary: "Distilled learned app profile for \(profile.appName).",
+ facts: [
+ "application.learning.draftID": draftID,
+ "application.learning.skillID": profile.skillID,
+ "application.learning.profile.appName": profile.appName,
+ "application.learning.profile.observationCount": String(profile.observations.count),
+ "application.learning.profile.workflowCount": String(profile.workflowRecipes.count),
+ "lastAcceptedTool": context.call.name
+ ],
+ metadata: [
+ "draftID": draftID,
+ "skillID": profile.skillID,
+ "observationCount": String(profile.observations.count),
+ "workflowCount": String(profile.workflowRecipes.count)
+ ]
+ )
+ }
+
+ private static func applicationLearningSaveSkillPack(
+ _ context: HarnessToolExecutionContext,
+ services: HarnessBuiltInToolServices
+ ) async -> HarnessToolResult {
+ guard let draftID = trimmed(context.call.input["draftID"] ?? context.worldModel.facts["application.learning.draftID"]) else {
+ return invalidInput(context, "application.learning.saveSkillPack requires a learning draftID.")
+ }
+ guard let draft = await services.applicationLearningStore.draft(id: draftID) else {
+ return failed(context, "Application learning draft was not found: \(draftID)", reason: "learningDraftNotFound")
+ }
+ let profile: HarnessApplicationProfile
+ if let existingProfile = draft.profile {
+ profile = existingProfile
+ } else if let distilledProfile = await services.applicationLearningStore.distill(draftID: draftID) {
+ profile = distilledProfile
+ } else {
+ return failed(context, "Application learning draft has no observations to save.", reason: "learningDraftNotReady")
+ }
+
+ let requestedScriptIDs = Set(listValues(context.call.input["scriptIDs"]))
+ let ownerScripts = await services.generatedScripts.artifacts(ownerSkillID: profile.skillID)
+ let extraScripts = requestedScriptIDs.isEmpty
+ ? []
+ : await services.generatedScripts.artifacts().filter { requestedScriptIDs.contains($0.id) }
+ let scripts = Array(
+ Dictionary(uniqueKeysWithValues: (ownerScripts + extraScripts).map { ($0.id, $0) })
+ .values
+ )
+ .sorted { $0.id < $1.id }
+ let writer = services.applicationSkillPackWriter
+ ?? HarnessApplicationSkillPackWriter(rootDirectory: HarnessApplicationSkillPackWriter.defaultRootDirectory())
+
+ do {
+ let result = try writer.save(profile: profile, scripts: scripts)
+ await services.skillRegistry?.register(result.skill)
+
+ return success(
+ context,
+ summary: "Saved learned application skill pack for \(profile.appName).",
+ facts: [
+ "application.learning.skillID": result.skill.id,
+ "application.learning.skillDirectory": result.directoryPath,
+ "application.learning.writtenFileCount": String(result.writtenFiles.count),
+ "application.learning.validatedScriptCount": String(result.scriptCount),
+ "lastAcceptedTool": context.call.name
+ ],
+ metadata: [
+ "skillID": result.skill.id,
+ "directory": result.directoryPath,
+ "writtenFiles": result.writtenFiles.joined(separator: "\n"),
+ "scriptCount": String(result.scriptCount)
+ ]
+ )
+ } catch {
+ return failed(context, "Failed to save learned application skill pack: \(error)", reason: "skillPackWriteFailed")
+ }
+ }
+
private static func stateVerify(_ context: HarnessToolExecutionContext) -> HarnessToolResult {
guard let criteria = trimmed(context.call.input["criteria"]) else {
return invalidInput(context, "state.verify requires criteria.")
@@ -843,6 +1129,41 @@ public enum BuiltInHarnessToolExecutors {
return !accepted.isDisjoint(with: available)
}
+ private static func safeExplorationAction(for element: HarnessWorldElement) -> String? {
+ let safety = normalized(element.metadata["learning.explorationSafety"] ?? element.metadata["safetyClass"] ?? "")
+ if ["destructive", "sensitive", "requiresapproval"].contains(safety) {
+ return nil
+ }
+ let actions = Set(element.actions.map(normalized))
+ if safety == "safe" || safety == "reversible" || safety == "readonly" {
+ if !actions.isDisjoint(with: ["focus", "axraise"]) { return "focus" }
+ if !actions.isDisjoint(with: ["press", "axpress"]) { return "press" }
+ if !actions.isDisjoint(with: ["scroll", "axscroll"]) { return "scroll" }
+ }
+
+ let role = normalized(element.role)
+ let reversibleRoles: Set<String> = [
+ "axmenu",
+ "axmenubaritem",
+ "axmenuitem",
+ "axpopupbutton",
+ "axtab",
+ "axtabgroup",
+ "axdisclosuretriangle"
+ ]
+ if reversibleRoles.contains(role),
+ !actions.isDisjoint(with: ["press", "axpress"]) {
+ return "press"
+ }
+ if !actions.isDisjoint(with: ["focus", "axraise"]) {
+ return "focus"
+ }
+ if !actions.isDisjoint(with: ["scroll", "axscroll"]) {
+ return "scroll"
+ }
+ return nil
+ }
+
private static func evidenceMatches(criteria: String, evidence: String) -> Bool {
let normalizedCriteria = normalized(criteria)
let normalizedEvidence = normalized(evidence)
@@ -884,6 +1205,16 @@ public enum BuiltInHarnessToolExecutors {
return slug.isEmpty ? UUID().uuidString : slug
}
+ private static func listValues(_ value: String?) -> [String] {
+ guard let value else { return [] }
+ return value
+ .split { character in
+ character == "," || character == "\n" || character == ";"
+ }
+ .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
+ .filter { !$0.isEmpty }
+ }
+
private static func tokens(in value: String) -> [String] {
normalized(value)
.split(separator: " ")
diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift
index c9b7c8fd..08054be2 100644
--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift
+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift
@@ -364,6 +364,95 @@ public enum BuiltInHarnessToolCatalog {
"requiresValidation": "true"
]
),
+ descriptor(
+ "application.learning.start",
+ pluginID: "core.application-learning",
+ summary: "Start a reusable skill-producing application learning draft for a resolved app.",
+ input: [
+ "appName": "Resolved application display name.",
+ "bundleIdentifier": "Optional resolved bundle identifier.",
+ "goal": "Learning goal or scope.",
+ "skillID": "Optional stable learned skill identifier.",
+ "explorationPolicy": "Safe exploration constraints."
+ ],
+ output: [
+ "draftID": "Learning draft identifier.",
+ "skillID": "Skill identifier that generated scripts can target."
+ ],
+ permissions: [.appLookup, .skillLookup],
+ safety: .readOnly,
+ requiredContext: ["structured intent", "resolved target app"],
+ verification: ["draft records safe exploration policy before any app interaction"]
+ ),
+ descriptor(
+ "application.learning.captureState",
+ pluginID: "core.application-learning",
+ summary: "Record a meaningful app state from screenshot, Accessibility, visible text, elements, and navigation evidence.",
+ input: [
+ "draftID": "Learning draft identifier.",
+ "stateID": "Stable state identifier.",
+ "title": "Human-readable state title.",
+ "screenshotArtifactURL": "Optional persisted screenshot artifact URL.",
+ "accessibilityArtifactURL": "Optional persisted Accessibility tree artifact URL.",
+ "navigationPath": "Comma-separated path used to reach this state.",
+ "changedFromPrevious": "Short description of the state transition.",
+ "safetyNotes": "Comma-separated state safety notes."
+ ],
+ output: ["observationCount": "Number of captured states in the draft."],
+ permissions: [.screenCapture, .accessibility],
+ safety: .readOnly,
+ requiredContext: ["focused target", "screen or Accessibility evidence"],
+ verification: ["captured state references bounded artifacts instead of embedding raw screenshots or trees"]
+ ),
+ descriptor(
+ "application.learning.proposeExploration",
+ pluginID: "core.application-learning",
+ summary: "Propose reversible Accessibility-backed exploration candidates and separate actions that need approval.",
+ input: ["draftID": "Optional learning draft identifier for traceability."],
+ output: [
+ "safeCandidates": "Element/action pairs that can be explored through guarded element.perform.",
+ "requiresApprovalCandidateIDs": "Action-eligible element IDs that need user approval or richer safety evidence."
+ ],
+ permissions: [.accessibility],
+ safety: .readOnly,
+ requiredContext: ["Accessibility element evidence"],
+ verification: ["safe candidates come from technical roles/actions or explicit element safety metadata, not raw command text"]
+ ),
+ descriptor(
+ "application.learning.distill",
+ pluginID: "core.application-learning",
+ summary: "Distill captured application states into an app profile and workflow recipes.",
+ input: [
+ "draftID": "Learning draft identifier.",
+ "workflowName": "Workflow recipe name.",
+ "workflowSummary": "Workflow recipe summary.",
+ "verificationCriteria": "Comma-separated verification criteria.",
+ "scriptIDs": "Optional generated script artifact identifiers.",
+ "safetyNotes": "Comma-separated durable safety notes."
+ ],
+ output: ["profile": "Distilled app profile summary and workflow counts."],
+ permissions: [.skillLookup],
+ safety: .readOnly,
+ requiredContext: ["captured learning observations"],
+ verification: ["profile contains at least one captured state before it can be saved"]
+ ),
+ descriptor(
+ "application.learning.saveSkillPack",
+ pluginID: "core.application-learning",
+ summary: "Save the distilled application profile as a reusable filesystem skill pack.",
+ input: [
+ "draftID": "Learning draft identifier.",
+ "scriptIDs": "Optional validated script artifact identifiers to include."
+ ],
+ output: [
+ "skillID": "Registered learned skill identifier.",
+ "directory": "Filesystem directory containing SKILL.md, profile, workflows, evidence index, and scripts."
+ ],
+ permissions: [.skillLookup],
+ safety: .sensitive,
+ requiredContext: ["distilled application profile", "validated generated scripts when included"],
+ verification: ["skill pack includes SKILL.md, app-profile.json, workflows.json, evidence index, and only validated scripts"]
+ ),
descriptor(
"state.verify",
pluginID: "core.verification",
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift
index 9d46b6f8..7e4ef1c3 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift
@@ -21,6 +21,11 @@ struct GenericHarnessTests {
#expect(names.contains("skill.script.execute"))
#expect(names.contains("automation.applescript.generate"))
#expect(names.contains("automation.applescript.execute"))
+ #expect(names.contains("application.learning.start"))
+ #expect(names.contains("application.learning.captureState"))
+ #expect(names.contains("application.learning.proposeExploration"))
+ #expect(names.contains("application.learning.distill"))
+ #expect(names.contains("application.learning.saveSkillPack"))
let generate = descriptors.first { $0.name == "automation.applescript.generate" }
#expect(generate?.metadata["modelBoundary"] == "required")
@@ -42,6 +47,14 @@ struct GenericHarnessTests {
let scriptExecute = descriptors.first { $0.name == "skill.script.execute" }
#expect(scriptExecute?.metadata["requiresValidatedScript"] == "true")
#expect(scriptExecute?.requiredPermissions == [.appControl, .input])
+
+ let learningCapture = descriptors.first { $0.name == "application.learning.captureState" }
+ #expect(learningCapture?.requiredPermissions == [.screenCapture, .accessibility])
+ #expect(learningCapture?.verificationHints.contains { $0.contains("bounded artifacts") } == true)
+
+ let learningExplore = descriptors.first { $0.name == "application.learning.proposeExploration" }
+ #expect(learningExplore?.requiredPermissions == [.accessibility])
+ #expect(learningExplore?.verificationHints.contains { $0.contains("technical roles/actions") } == true)
}
@Test
@@ -401,6 +414,217 @@ struct GenericHarnessTests {
#expect(executedSkillScript.observations.facts["script.executed.output"] == "prepared")
}
+ @Test
+ func applicationLearningFlowSavesSearchableSkillPackWithValidatedScripts() async throws {
+ let root = FileManager.default.temporaryDirectory
+ .appendingPathComponent("donkey-learned-skill-\(UUID().uuidString)", isDirectory: true)
+ defer {
+ try? FileManager.default.removeItem(at: root)
+ }
+
+ let skillRegistry = HarnessSkillRegistry()
+ let scriptStore = HarnessGeneratedScriptStore()
+ let learningStore = HarnessApplicationLearningStore()
+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors(
+ services: HarnessBuiltInToolServices(
+ skillRegistry: skillRegistry,
+ generatedScripts: scriptStore,
+ applicationLearningStore: learningStore,
+ applicationSkillPackWriter: HarnessApplicationSkillPackWriter(rootDirectory: root)
+ )
+ )
+ let baseWorld = HarnessWorldModel(
+ focusedApp: "DraftPad",
+ focusedWindowTitle: "DraftPad - Untitled",
+ visibleText: ["main": "Untitled document"],
+ elements: [
+ HarnessWorldElement(
+ id: "toolbar-new",
+ label: "New Document",
+ role: "AXButton",
+ isActionEligible: true,
+ actions: ["AXPress"],
+ metadata: ["scope": "toolbar"]
+ ),
+ HarnessWorldElement(
+ id: "editor",
+ label: "Editor",
+ role: "AXTextArea",
+ isActionEligible: true,
+ actions: ["AXSetValue"],
+ metadata: ["scope": "main"]
+ )
+ ],
+ facts: [
+ "screen.observe.screenshotArtifactURL": "file:///tmp/draftpad-main.png",
+ "screen.observe.accessibilityArtifactURL": "file:///tmp/draftpad-main-accessibility.json"
+ ]
+ )
+
+ let started = await registry.execute(
+ HarnessToolCall(
+ id: "learn-start",
+ name: "application.learning.start",
+ input: [
+ "appName": "DraftPad",
+ "bundleIdentifier": "com.example.DraftPad",
+ "goal": "Learn safe writing workflows.",
+ "skillID": "learned-draftpad"
+ ]
+ ),
+ taskID: "task-learn-draftpad",
+ worldModel: baseWorld,
+ grantedPermissions: [.appLookup, .skillLookup]
+ )
+ let capturedMain = await registry.execute(
+ HarnessToolCall(
+ id: "learn-capture-main",
+ name: "application.learning.captureState",
+ input: [
+ "draftID": "task-learn-draftpad-learned-draftpad",
+ "stateID": "main-editor",
+ "title": "Main editor",
+ "navigationPath": "launch",
+ "changedFromPrevious": "Initial focused window",
+ "safetyNotes": "Typing requires explicit user content"
+ ]
+ ),
+ taskID: "task-learn-draftpad",
+ worldModel: baseWorld,
+ grantedPermissions: [.screenCapture, .accessibility]
+ )
+ let menuWorld = HarnessWorldModel(
+ focusedApp: "DraftPad",
+ focusedWindowTitle: "DraftPad - File Menu",
+ visibleText: ["menu": "New Open Save Export"],
+ elements: [
+ HarnessWorldElement(
+ id: "file-new",
+ label: "New",
+ role: "AXMenuItem",
+ isActionEligible: true,
+ actions: ["AXPress"]
+ )
+ ],
+ facts: [
+ "screen.observe.screenshotArtifactURL": "file:///tmp/draftpad-menu.png",
+ "screen.observe.accessibilityArtifactURL": "file:///tmp/draftpad-menu-accessibility.json"
+ ]
+ )
+ let capturedMenu = await registry.execute(
+ HarnessToolCall(
+ id: "learn-capture-menu",
+ name: "application.learning.captureState",
+ input: [
+ "draftID": "task-learn-draftpad-learned-draftpad",
+ "stateID": "file-menu",
+ "title": "File menu",
+ "navigationPath": "launch, menu:file",
+ "changedFromPrevious": "Opened File menu"
+ ]
+ ),
+ taskID: "task-learn-draftpad",
+ worldModel: menuWorld,
+ grantedPermissions: [.screenCapture, .accessibility]
+ )
+ let proposedExploration = await registry.execute(
+ HarnessToolCall(
+ id: "learn-propose-exploration",
+ name: "application.learning.proposeExploration",
+ input: ["draftID": "task-learn-draftpad-learned-draftpad"]
+ ),
+ taskID: "task-learn-draftpad",
+ worldModel: menuWorld,
+ grantedPermissions: [.accessibility]
+ )
+ let generatedScript = await registry.execute(
+ HarnessToolCall(
+ id: "learn-script-generate",
+ name: "skill.script.generate",
+ input: [
+ "skillID": "learned-draftpad",
+ "scriptID": "focus-editor",
+ "language": "applescript",
+ "purpose": "Focus the DraftPad editor",
+ "scriptSource": #"tell application "DraftPad" to activate"#
+ ]
+ ),
+ taskID: "task-learn-draftpad",
+ worldModel: baseWorld,
+ grantedPermissions: [.skillLookup]
+ )
+ let validatedScript = await registry.execute(
+ HarnessToolCall(
+ id: "learn-script-validate",
+ name: "skill.script.validate",
+ input: [
+ "scriptID": "focus-editor",
+ "validationPolicy": "activate-only app automation"
+ ]
+ ),
+ taskID: "task-learn-draftpad",
+ worldModel: baseWorld,
+ grantedPermissions: [.skillLookup]
+ )
+ let distilled = await registry.execute(
+ HarnessToolCall(
+ id: "learn-distill",
+ name: "application.learning.distill",
+ input: [
+ "draftID": "task-learn-draftpad-learned-draftpad",
+ "workflowName": "Write a draft",
+ "workflowSummary": "Focus the editor, enter user-provided text, and verify the text is visible.",
+ "verificationCriteria": "editor visible, text visible",
+ "scriptIDs": "focus-editor"
+ ]
+ ),
+ taskID: "task-learn-draftpad",
+ worldModel: menuWorld,
+ grantedPermissions: [.skillLookup]
+ )
+ let saved = await registry.execute(
+ HarnessToolCall(
+ id: "learn-save",
+ name: "application.learning.saveSkillPack",
+ input: ["draftID": "task-learn-draftpad-learned-draftpad"]
+ ),
+ taskID: "task-learn-draftpad",
+ worldModel: menuWorld,
+ grantedPermissions: [.skillLookup]
+ )
+
+ #expect(started.status == .succeeded)
+ #expect(capturedMain.metadata["observationCount"] == "1")
+ #expect(capturedMenu.metadata["observationCount"] == "2")
+ #expect(proposedExploration.metadata["safeCandidates"] == "file-new:press")
+ #expect(generatedScript.metadata["validationStatus"] == HarnessSkillScriptValidationStatus.pendingValidation.rawValue)
+ #expect(validatedScript.metadata["validationStatus"] == HarnessSkillScriptValidationStatus.validated.rawValue)
+ #expect(distilled.metadata["workflowCount"] == "1")
+ #expect(saved.status == .succeeded)
+ #expect(saved.metadata["skillID"] == "learned-draftpad")
+ #expect(saved.metadata["scriptCount"] == "1")
+
+ let savedDirectory = root.appendingPathComponent("learned-draftpad", isDirectory: true)
+ let skillMarkdown = try String(
+ contentsOf: savedDirectory.appendingPathComponent("SKILL.md"),
+ encoding: .utf8
+ )
+ let profileData = try Data(contentsOf: savedDirectory.appendingPathComponent("app-profile.json"))
+ let profile = try JSONDecoder().decode(HarnessApplicationProfile.self, from: profileData)
+ let scriptSource = try String(
+ contentsOf: savedDirectory.appendingPathComponent("scripts/focus-editor.applescript"),
+ encoding: .utf8
+ )
+ let results = await skillRegistry.search(query: "DraftPad learned app")
+
+ #expect(skillMarkdown.contains("DraftPad Learned Application"))
+ #expect(profile.observations.map(\.id) == ["main-editor", "file-menu"])
+ #expect(profile.generatedScriptIDs == ["focus-editor"])
+ #expect(scriptSource.contains("DraftPad"))
+ #expect(results.first?.descriptor.id == "learned-draftpad")
+ #expect(results.first?.descriptor.scripts.first?.validationStatus == .validated)
+ }
+
@Test
func missingPermissionStopsTaskAndStoresContinuation() async {
let coordinator = HarnessTaskCoordinator()
diff --git a/docs/guides/agent-harness.md b/docs/guides/agent-harness.md
index 2026690f..41b6f47a 100644
--- a/docs/guides/agent-harness.md
+++ b/docs/guides/agent-harness.md
@@ -274,9 +274,14 @@ workflow recipes, evidence notes, and generated scripts together.
## Learning Applications
-"Learn an application" should be implemented as a skill-producing harness task.
-It explores an app safely, observes each state, distills durable knowledge, and
-saves a reusable application skill pack.
+"Learn an application" is supported as a skill-producing harness task. The
+generic built-in tools `application.learning.start`,
+`application.learning.captureState`,
+`application.learning.proposeExploration`, `application.learning.distill`, and
+`application.learning.saveSkillPack` coordinate the flow: start a safe learning
+draft, record bounded screenshot and Accessibility evidence, propose reversible
+exploration candidates from technical Accessibility roles/actions, distill an
+app profile and workflow recipes, and save a reusable skill pack.
For each meaningful state, the learner should gather:
@@ -303,9 +308,11 @@ The reusable output should be distilled, not just raw captures:
- safety notes
- optional redacted evidence artifacts
-Future agents use the learned app skill by searching for the relevant skill,
-loading its bounded instructions, and then using any validated scripts or
-workflow tools exposed by that skill.
+Validated generated scripts owned by the learned skill are copied into the
+skill-local `scripts/` directory when the pack is saved. Future agents use the
+learned app skill by searching for the relevant skill, loading its bounded
+instructions, and then using any validated scripts or workflow tools exposed by
+that skill.
## Intent Rules
diff --git a/plans/master-plan.md b/plans/master-plan.md
index 51d92e6b..2e553143 100644
--- a/plans/master-plan.md
+++ b/plans/master-plan.md
@@ -21,13 +21,10 @@ even when there are no active tasks.
## Current Sequence
-1. Build the application-learning task. It should safely explore an app, capture
- screenshots and Accessibility trees, distill surfaces/workflows, generate
- scripts where useful, validate them, and save a reusable skill pack.
-2. Wire interruption and permission gates into the UI. The notch/task UI should
+1. Wire interruption and permission gates into the UI. The notch/task UI should
control generic harness tasks and show the exact pending approval or
changed-course state.
-3. Delete old app-specific paths once the generic path covers them. Remove
+2. Delete old app-specific paths once the generic path covers them. Remove
hardcoded Music/Notes/Numbers/media/weather-style prompt rules, catalog
special cases, repair logic, and demo-only workflow branches.