Skip to content

Open source CapCut alternative.

TypeScript

feat(app): progress-based step budget, evidence-gated completion, and crash-safe narration

David Le2e2cf6aed348
diff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
index 09410b62..43839c6d 100644
--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
@@ -361,9 +361,10 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
bundleIdentifier: bundleIdentifier,
analyzer: analyzer
)
- // Register the AX/vision see/act tools only when this turn holds their permissions, mirroring
- // the built-in descriptor filter so the planner is never offered a tool it can't run.
- for tool in axProvider.makeTools() + visionProvider.makeTools()
+ let pointerProvider = PointerComputerUseToolProvider(appName: appName, bundleIdentifier: bundleIdentifier)
+ // Register the AX/vision/pointer see/act tools only when this turn holds their permissions,
+ // mirroring the built-in descriptor filter so the planner is never offered a tool it can't run.
+ for tool in axProvider.makeTools() + visionProvider.makeTools() + pointerProvider.makeTools()
where Set(tool.descriptor.requiredPermissions).isSubset(of: granted) {
await registry.register(tool)
}
@@ -401,7 +402,13 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
if visualize != nil || progress != nil {
onStep = { (step: HarnessStepExecutionResult) async -> Void in
await MainActor.run {
- if let progress, let narration = Self.stepNarration(for: step, planner: planner) {
+ // Every step narrates through the spawn label (a lightweight text update), so the
+ // user is kept informed even on steps that don't move the pointer — observe, shell,
+ // wait, verify. The cursor itself only travels (a heavier window-animating overlay
+ // playback) on steps that actually moved it; re-running that playback every step
+ // thrashes window layout, so it stays gated to real pointer moves.
+ let narration = Self.stepNarration(for: step, planner: planner)
+ if let progress, let narration {
progress(narration)
}
guard let present = visualize else { return }
@@ -416,7 +423,9 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
}
}
}
- let runSteps = await runtime.run(taskID: taskID, planner: planner, maxSteps: 24, onStep: onStep)
+ // Step budget is progress-based, not a fixed count: the runtime keeps going while the task
+ // advances and stops fast when it stalls or loops, so a long legitimate task isn't cut off.
+ let runSteps = await runtime.run(taskID: taskID, planner: planner, onStep: onStep)
VisionWarmCacheActivity.shared.resume()
let finalTask = await genericHarnessLifecycle.coordinator.task(id: taskID)
diff --git a/apps/Donkey/Sources/DonkeyHarness/DonkeyCommandLayer.swift b/apps/Donkey/Sources/DonkeyHarness/DonkeyCommandLayer.swift
index 2f2dd4ae..e43106b4 100644
--- a/apps/Donkey/Sources/DonkeyHarness/DonkeyCommandLayer.swift
+++ b/apps/Donkey/Sources/DonkeyHarness/DonkeyCommandLayer.swift
@@ -30,14 +30,19 @@ public enum DonkeyCommandLayer {
name: Command.shellExec.rawValue,
pluginID: pluginID,
summary: "Run a single-line shell command on the user's Mac and return its output. This is your primary, expert tool: prefer it for finding files (`mdfind`, `ls -t`, `find`), launching or quitting apps (`open -a \"App Name\"`, `osascript -e 'quit app \"App Name\"'`), reading state (`date`, `pmset -g batt`, `system_profiler`), and changing settings (`defaults write`, `networksetup -set…`). Read-only commands run immediately; anything that changes state asks the user for one-time or always-allow consent first, so you may freely propose it. Destructive or privileged commands (`sudo`, `rm`, `dd`, piping into a shell) ask every time.",
- inputSchema: ["command": "A safe, single-line shell command, e.g. `open -a \"App Name\"`, `osascript -e '…'`, or `date`."],
+ inputSchema: [
+ "command": "A safe, single-line shell command, e.g. `open -a \"App Name\"`, `osascript -e '…'`, or `date`.",
+ "timeoutSeconds": "Time budget for known-slow commands (default 12, max 120)."
+ ],
+ optionalInputKeys: ["timeoutSeconds"],
outputSchema: [
- "stdout": "Captured standard output (trimmed).",
+ "stdout": "Captured standard output (trimmed; long output is truncated with an explicit marker).",
"exitCode": "Process exit code."
],
requiredPermissions: [.appControl, .input],
safetyClass: .guardedInput,
- verificationHints: ["the command exits with code 0"]
+ verificationHints: ["the command exits with code 0"],
+ metadata: [HarnessToolDescriptor.resultIsEvidenceMetadataKey: "true"]
),
HarnessToolDescriptor(
name: Command.appsList.rawValue,
@@ -87,7 +92,8 @@ public enum DonkeyCommandLayer {
outputSchema: ["status": "Structured status the script reports."],
requiredPermissions: [.appControl, .input],
safetyClass: .guardedInput,
- verificationHints: ["the script reports a successful structured status"]
+ verificationHints: ["the script reports a successful structured status"],
+ metadata: [HarnessToolDescriptor.resultIsEvidenceMetadataKey: "true"]
)
]
}
diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift
index d9c16b9f..b155d8ca 100644
--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift
+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift
@@ -282,6 +282,8 @@ public enum BuiltInHarnessToolExecutors {
return await applicationLearningSaveSkillPack(context, services: services)
case "state.verify":
return stateVerify(context)
+ case "wait":
+ return await timingWait(context)
case "run.pause", "run.resume", "run.recover", "run.cancel", "run.complete", "run.failSafe":
return lifecycle(context)
default:
@@ -1235,6 +1237,18 @@ public enum BuiltInHarnessToolExecutors {
"app.lookup"
]
+ private static func timingWait(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {
+ let requested = context.call.input["seconds"].flatMap(Double.init) ?? 1
+ let seconds = min(max(requested, 0.1), 10)
+ try? await Task.sleep(nanoseconds: UInt64(seconds * 1_000_000_000))
+ return success(
+ context,
+ summary: "Waited \(String(format: "%.1f", seconds))s for the app to settle.",
+ facts: ["lastAcceptedTool": context.call.name],
+ metadata: ["seconds": String(format: "%.1f", seconds)]
+ )
+ }
+
private static func stateVerify(_ context: HarnessToolExecutionContext) -> HarnessToolResult {
guard let criteria = trimmed(context.call.input["criteria"]) else {
// Planners sometimes append a verify step without echoing explicit criteria. Verify against
diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift
index af163fb0..5fe41afe 100644
--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift
+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift
@@ -38,21 +38,34 @@ public struct GenericHarnessRuntime: Sendable {
/// Runs the harness loop driven by per-observation re-planning: observe → plan one step → execute
/// → record observation → re-plan, repeating until the planner stops, a gate stops the task, the
- /// task becomes non-executable (e.g. `run.complete`/`run.failSafe`), or `maxSteps` is reached.
+ /// task becomes non-executable (e.g. `run.complete`/`run.failSafe`), the run stalls, or the
+ /// runaway ceiling `maxSteps` is reached.
+ ///
+ /// Step budget is governed by *progress*, not a fixed count: a long task that keeps advancing
+ /// runs to completion, while a task that spins stops fast. `maxSteps` is only a runaway backstop
+ /// set far above any real task. Two stall signals end the run as a `failSafe`:
+ ///
+ /// - **No progress**: `maxNoProgressSteps` consecutive steps that neither change the world model
+ /// nor record a succeeded state-changing action — the loop is busy but getting nowhere.
+ /// - **Exact repeat**: the same tool with the same input chosen `maxIdenticalRepeats` times — the
+ /// planner is looping on one call.
///
/// The planner is consulted with the *current* task each iteration, so it sees the world model the
/// previous tool produced — that is what makes this a real harness loop rather than a fixed plan.
- /// `onStep`, when provided, is awaited after each executed step with that step's result. It lets a
- /// caller react to realtime loop progress (e.g. drive a cursor-path overlay toward the target the
- /// step just acted on) without the runtime knowing anything about the UI.
+ /// `onStep`, when provided, is awaited after each executed step with that step's result.
@discardableResult
public func run(
taskID: String,
planner: any HarnessNextStepPlanning,
- maxSteps: Int = 16,
+ maxSteps: Int = 200,
+ maxNoProgressSteps: Int = 6,
+ maxIdenticalRepeats: Int = 3,
onStep: (@Sendable (HarnessStepExecutionResult) async -> Void)? = nil
) async -> [HarnessStepExecutionResult] {
var results: [HarnessStepExecutionResult] = []
+ var noProgressStreak = 0
+ var identicalNoProgressStreak = 0
+ var lastCallSignature: String?
for _ in 0..<maxSteps {
guard let task = await coordinator.task(id: taskID), task.status.canExecuteTools else {
break
@@ -60,6 +73,8 @@ public struct GenericHarnessRuntime: Sendable {
guard let call = await planner.planNextStep(for: task) else {
break
}
+ let signature = call.name + "\u{1}" + Self.canonicalInput(call.input)
+
guard let step = await executeToolCall(taskID: taskID, call: call) else {
break
}
@@ -68,10 +83,71 @@ public struct GenericHarnessRuntime: Sendable {
if step.stoppedForGate || !step.task.status.canExecuteTools {
break
}
+
+ // Stall detection — a step that changes the world or records a succeeded action is
+ // progress and resets the streaks, so an arbitrarily long advancing run continues. Two
+ // signals end a stuck run: enough consecutive no-progress steps (busy but going nowhere),
+ // or the SAME call repeated with no progress (looping on one action). Lifecycle calls are
+ // exempt from the repeat signal — they legitimately end the run themselves.
+ if Self.stepMadeProgress(before: task, after: step.task, result: step.toolResult) {
+ noProgressStreak = 0
+ identicalNoProgressStreak = 0
+ } else {
+ noProgressStreak += 1
+ if !call.name.hasPrefix("run."), signature == lastCallSignature {
+ identicalNoProgressStreak += 1
+ } else {
+ identicalNoProgressStreak = 0
+ }
+ if noProgressStreak >= maxNoProgressSteps {
+ await failSafeStall(taskID: taskID, reason: "noProgress")
+ break
+ }
+ if identicalNoProgressStreak + 1 >= maxIdenticalRepeats {
+ await failSafeStall(taskID: taskID, reason: "stuckRepeatingCall")
+ break
+ }
+ }
+ lastCallSignature = signature
}
return results
}
+ /// A step advanced the task if it changed the observed world (elements, facts, or visible text)
+ /// or recorded a succeeded state-changing action. A failed step, or a re-observation that returns
+ /// the same world, is no progress. Used to detect a busy-but-stuck loop.
+ private static func stepMadeProgress(
+ before: HarnessTaskState,
+ after: HarnessTaskState,
+ result: HarnessToolResult?
+ ) -> Bool {
+ guard let result else { return false }
+ guard result.status == .succeeded else { return false }
+ let worldChanged = before.worldModel.elements != after.worldModel.elements
+ || before.worldModel.facts != after.worldModel.facts
+ || before.worldModel.visibleText != after.worldModel.visibleText
+ if worldChanged { return true }
+ // A succeeded action that reports observations (a click, a shell command) counts as progress
+ // even when the merged world model looks unchanged.
+ return !result.observations.facts.isEmpty
+ || !result.observations.elements.isEmpty
+ || !result.observations.visibleText.isEmpty
+ }
+
+ /// Canonical, order-independent serialization of a tool call's input, so the same call is
+ /// recognized regardless of key ordering.
+ private static func canonicalInput(_ input: [String: String]) -> String {
+ input.sorted { $0.key < $1.key }
+ .map { "\($0.key)=\($0.value)" }
+ .joined(separator: "\u{1f}")
+ }
+
+ /// Moves the task to a failed-safe stall state with a typed reason, so a stuck run ends cleanly
+ /// instead of burning the whole runaway ceiling.
+ private func failSafeStall(taskID: String, reason: String) async {
+ _ = await coordinator.failSafe(taskID: taskID, reason: "Run stopped: \(reason).")
+ }
+
public func executeToolCall(
taskID: String,
call: HarnessToolCall
@@ -144,6 +220,20 @@ public struct GenericHarnessRuntime: Sendable {
)
}
+ // Completion must be evidence-backed, enforced by the runtime rather than left to prompt
+ // guidance: after the last state-changing step there must be at least one later succeeded
+ // step (a re-observe, read command, or verification) before run.complete is accepted.
+ if call.name == "run.complete", let blocked = await completionEvidenceRejection(call: call, task: task) {
+ guard let updatedTask = await coordinator.recordToolResult(
+ taskID: taskID,
+ call: call,
+ result: blocked
+ ) else {
+ return nil
+ }
+ return HarnessStepExecutionResult(task: updatedTask, toolResult: blocked, stoppedForGate: false)
+ }
+
let result = await registry.execute(
call,
taskID: taskID,
@@ -239,6 +329,44 @@ public struct GenericHarnessRuntime: Sendable {
return await executeToolCall(taskID: taskID, call: call)
}
+ /// Rejects a `run.complete` whose most recent succeeded state-changing step has no succeeded
+ /// evidence step after it: acting and immediately declaring victory is exactly the unverified
+ /// completion the harness must not accept. Evidence steps are read-only tools plus tools whose
+ /// descriptors declare their result is itself evidence (e.g. a shell command's output and exit
+ /// code). Conversation-only and pure-read tasks have no state-changing step and complete freely.
+ /// Tools the registry no longer knows count as evidence so stale history can never wedge
+ /// completion.
+ private func completionEvidenceRejection(
+ call: HarnessToolCall,
+ task: HarnessTaskState
+ ) async -> HarnessToolResult? {
+ let descriptors = await registry.descriptors()
+ let knownNames = Set(descriptors.map(\.name))
+ let evidenceNames = Set(
+ descriptors.filter {
+ $0.safetyClass == .readOnly
+ || $0.metadata[HarnessToolDescriptor.resultIsEvidenceMetadataKey] == "true"
+ }.map(\.name)
+ )
+ func isEvidence(_ record: HarnessToolCallRecord) -> Bool {
+ evidenceNames.contains(record.call.name) || !knownNames.contains(record.call.name)
+ }
+ let lastActionIndex = task.toolHistory.lastIndex {
+ $0.resultStatus == .succeeded && !isEvidence($0)
+ }
+ guard let lastActionIndex else { return nil }
+ let hasEvidenceAfterAction = task.toolHistory[task.toolHistory.index(after: lastActionIndex)...]
+ .contains { $0.resultStatus == .succeeded && isEvidence($0) }
+ guard !hasEvidenceAfterAction else { return nil }
+ return HarnessToolResult(
+ callID: call.id,
+ toolName: call.name,
+ status: .failed,
+ summary: "Not completing yet: the last action has not been verified. Run a read-only check first (re-observe, a read command, or state.verify) confirming the goal, then complete.",
+ metadata: ["reason": "completionRequiresEvidence"]
+ )
+ }
+
private func applyLifecycleResult(
taskID: String,
call: HarnessToolCall,
diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift
index f14c48d1..d6f44e7c 100644
--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift
+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift
@@ -1,6 +1,12 @@
import Foundation
public struct HarnessToolDescriptor: Codable, Equatable, Sendable {
+ /// Descriptor metadata key a tool sets to "true" when its successful result is itself
+ /// verification evidence (e.g. a shell command returning output and exit code). The runtime's
+ /// completion gate accepts such a step as the post-action check; other state-changing tools
+ /// need a later read-only observation before `run.complete` is accepted.
+ public static let resultIsEvidenceMetadataKey = "resultIsEvidence"
+
public var name: String
public var pluginID: String
public var summary: String
@@ -488,6 +494,15 @@ public enum BuiltInHarnessToolCatalog {
permissions: [.verification],
safety: .readOnly
),
+ descriptor(
+ "wait",
+ pluginID: "core.timing",
+ summary: "Pause briefly while the app settles (a page loads, a window opens, an animation finishes), then re-plan. Prefer this over re-observing in a tight loop when the UI is still catching up.",
+ input: ["seconds": "How long to wait, 0.1–10 (default 1)."],
+ permissions: [],
+ safety: .readOnly,
+ verification: ["re-observe after waiting to confirm the expected state arrived"]
+ ),
descriptor(
"run.pause",
pluginID: "core.lifecycle",
diff --git a/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift b/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift
index 1889648a..249cb614 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift
@@ -277,11 +277,20 @@ public enum DonkeyCommandBackends {
/// Max characters accepted for a one-line command.
private static let shellCommandMaxLength = 400
- /// Seconds before a command is terminated.
+ /// Seconds before a command is terminated when the call does not set its own budget.
private static let shellTimeout: TimeInterval = 12
+ /// Upper bound for a caller-provided `timeoutSeconds`, so a planner mistake can never hang a run.
+ private static let shellTimeoutMax: TimeInterval = 120
/// Max stdout characters returned to the model.
private static let shellOutputMaxLength = 4_000
+ /// Truncates output to the model-facing cap, announcing the cut instead of trimming silently —
+ /// the model must know it saw a prefix, not the whole output.
+ private static func boundedOutput(_ output: String) -> (text: String, truncated: Bool) {
+ guard output.count > shellOutputMaxLength else { return (output, false) }
+ return (String(output.prefix(shellOutputMaxLength)) + "\n… [output truncated]", true)
+ }
+
private static func shellExec(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {
guard let command = trimmed(context.call.input["command"]) ?? trimmed(context.call.input["cmd"]) else {
return invalidInput(context, "shell_exec requires a one-line `command`.")
@@ -303,31 +312,38 @@ public enum DonkeyCommandBackends {
}
}
+ let timeout = context.call.input["timeoutSeconds"].flatMap(Double.init)
+ .map { min(max($0, 1), shellTimeoutMax) } ?? shellTimeout
let result = await Task.detached(priority: .userInitiated) {
- runShellSync(command, timeout: shellTimeout)
+ runShellSync(command, timeout: timeout)
}.value
- let stdout = String(result.stdout.prefix(shellOutputMaxLength))
+ let stdout = boundedOutput(result.stdout)
guard result.exitCode == 0 else {
+ let stderr = boundedOutput(result.stderr)
return HarnessToolResult(
callID: context.call.id,
toolName: context.call.name,
status: .failed,
- summary: "Command exited with code \(result.exitCode).",
+ summary: result.timedOut
+ ? "Command timed out after \(Int(timeout))s and was terminated. Pass timeoutSeconds (max \(Int(shellTimeoutMax))) for known-slow commands."
+ : "Command exited with code \(result.exitCode).",
metadata: [
"executor": "donkeyCommandLayer",
"reason": result.timedOut ? "timedOut" : "nonZeroExit",
"exitCode": String(result.exitCode),
- "stdout": stdout,
- "stderr": String(result.stderr.prefix(shellOutputMaxLength))
+ "stdout": stdout.text,
+ "stderr": stderr.text,
+ "stdoutTruncated": String(stdout.truncated),
+ "timeoutSeconds": String(Int(timeout))
]
)
}
return success(
context,
- summary: stdout.isEmpty ? "Command ran (no output)." : stdout,
+ summary: stdout.text.isEmpty ? "Command ran (no output)." : stdout.text,
facts: ["lastShellExitCode": "0"],
- metadata: ["stdout": stdout, "exitCode": "0"]
+ metadata: ["stdout": stdout.text, "exitCode": "0", "stdoutTruncated": String(stdout.truncated)]
)
}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift
index cb8599eb..9ccce08f 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift
@@ -211,6 +211,200 @@ struct GenericHarnessTests {
#expect(finalTask?.status == .completed)
}
+ @Test
+ func runStopsWhenThePlannerLoopsOnTheSameCall() async {
+ // A planner that keeps choosing the identical observation never converges. The runtime must
+ // detect the exact repeat and fail safe quickly instead of burning the whole ceiling.
+ struct StubLoopingPlanner: HarnessNextStepPlanning {
+ func planNextStep(for task: HarnessTaskState) async -> HarnessToolCall? {
+ HarnessToolCall(name: "test.noop", input: ["k": "v"])
+ }
+ }
+ let coordinator = HarnessTaskCoordinator()
+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors()
+ // A tool that succeeds but reports no observations, so every call is no-progress.
+ await registry.register(
+ HarnessTool(
+ descriptor: HarnessToolDescriptor(name: "test.noop", pluginID: "test", summary: "noop", safetyClass: .readOnly)
+ ) { context in
+ HarnessToolResult(callID: context.call.id, toolName: context.call.name, status: .succeeded, summary: "noop")
+ }
+ )
+ let runtime = GenericHarnessRuntime(coordinator: coordinator, registry: registry)
+ let task = await coordinator.createTask(id: "task-loop", threadID: "t", goal: "loop", grantedPermissions: [.lifecycle])
+
+ let steps = await runtime.run(taskID: task.id, planner: StubLoopingPlanner(), maxSteps: 100)
+
+ // Stops after the repeat guard trips (well under the ceiling), not 100 steps.
+ #expect(steps.count < 5)
+ let finalTask = await coordinator.task(id: task.id)
+ #expect(finalTask?.status == .failedSafe)
+ }
+
+ @Test
+ func runStopsWhenStepsStopMakingProgress() async {
+ // Distinct calls that each succeed but never change the world model are still a stall.
+ struct StubBusyPlanner: HarnessNextStepPlanning {
+ func planNextStep(for task: HarnessTaskState) async -> HarnessToolCall? {
+ HarnessToolCall(name: "test.noop", input: ["n": String(task.toolHistory.count)])
+ }
+ }
+ let coordinator = HarnessTaskCoordinator()
+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors()
+ await registry.register(
+ HarnessTool(
+ descriptor: HarnessToolDescriptor(name: "test.noop", pluginID: "test", summary: "noop", safetyClass: .readOnly)
+ ) { context in
+ HarnessToolResult(callID: context.call.id, toolName: context.call.name, status: .succeeded, summary: "noop")
+ }
+ )
+ let runtime = GenericHarnessRuntime(coordinator: coordinator, registry: registry)
+ let task = await coordinator.createTask(id: "task-stall", threadID: "t", goal: "stall", grantedPermissions: [.lifecycle])
+
+ let steps = await runtime.run(taskID: task.id, planner: StubBusyPlanner(), maxSteps: 100, maxNoProgressSteps: 4)
+
+ #expect(steps.count <= 5)
+ let finalTask = await coordinator.task(id: task.id)
+ #expect(finalTask?.status == .failedSafe)
+ }
+
+ @Test
+ func longProgressingRunIsNotCutOffByAFixedCap() async {
+ // Each step changes the world model (real progress), so a run longer than the old 40-step cap
+ // completes instead of being truncated — the point of progress-based budgeting.
+ struct StubProgressingPlanner: HarnessNextStepPlanning {
+ func planNextStep(for task: HarnessTaskState) async -> HarnessToolCall? {
+ let done = (task.worldModel.facts["count"].flatMap(Int.init) ?? 0) >= 60
+ return done
+ ? HarnessToolCall(name: "run.complete", input: ["reason": "done"])
+ : HarnessToolCall(name: "test.advance")
+ }
+ }
+ let coordinator = HarnessTaskCoordinator()
+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors()
+ await registry.register(
+ HarnessTool(
+ descriptor: HarnessToolDescriptor(name: "test.advance", pluginID: "test", summary: "advance", safetyClass: .readOnly)
+ ) { context in
+ let next = (context.worldModel.facts["count"].flatMap(Int.init) ?? 0) + 1
+ return HarnessToolResult(
+ callID: context.call.id, toolName: context.call.name, status: .succeeded,
+ summary: "advanced to \(next)",
+ observations: HarnessObservationDelta(facts: ["count": String(next)])
+ )
+ }
+ )
+ let runtime = GenericHarnessRuntime(coordinator: coordinator, registry: registry)
+ let task = await coordinator.createTask(id: "task-long", threadID: "t", goal: "count to 60", grantedPermissions: [.lifecycle])
+
+ let steps = await runtime.run(taskID: task.id, planner: StubProgressingPlanner())
+
+ // 60 advances + 1 complete — well past the old 40 cap.
+ #expect(steps.count == 61)
+ let finalTask = await coordinator.task(id: task.id)
+ #expect(finalTask?.status == .completed)
+ }
+
+ @Test
+ func runCompleteIsRejectedUntilTheLastActionIsVerified() async {
+ // Acting and immediately declaring victory must not complete the task: the runtime rejects
+ // the unverified run.complete, the planner re-observes, and only then completion lands.
+ struct StubActThenCompletePlanner: HarnessNextStepPlanning {
+ func planNextStep(for task: HarnessTaskState) async -> HarnessToolCall? {
+ switch task.toolHistory.last.map({ ($0.call.name, $0.resultStatus) }) {
+ case nil:
+ return HarnessToolCall(name: "test.act")
+ case ("test.act", .succeeded)?:
+ return HarnessToolCall(name: "run.complete", input: ["reason": "claimed done"])
+ case ("run.complete", .failed)?:
+ return HarnessToolCall(name: "test.observe")
+ default:
+ return HarnessToolCall(name: "run.complete", input: ["reason": "verified done"])
+ }
+ }
+ }
+
+ let coordinator = HarnessTaskCoordinator()
+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors()
+ await registry.register(stubTool(name: "test.act", safetyClass: .guardedInput))
+ await registry.register(stubTool(name: "test.observe", safetyClass: .readOnly))
+ let runtime = GenericHarnessRuntime(coordinator: coordinator, registry: registry)
+ let task = await coordinator.createTask(
+ id: "task-complete-evidence",
+ threadID: "thread-complete-evidence",
+ goal: "act then verify",
+ grantedPermissions: [.lifecycle]
+ )
+
+ let steps = await runtime.run(taskID: task.id, planner: StubActThenCompletePlanner(), maxSteps: 6)
+
+ #expect(steps.map { $0.toolResult?.toolName } == ["test.act", "run.complete", "test.observe", "run.complete"])
+ #expect(steps[1].toolResult?.status == .failed)
+ #expect(steps[1].toolResult?.metadata["reason"] == "completionRequiresEvidence")
+ #expect(steps[1].task.status == .running)
+ let finalTask = await coordinator.task(id: task.id)
+ #expect(finalTask?.status == .completed)
+ }
+
+ @Test
+ func runCompleteIsAcceptedWhenTheLastActionCarriesItsOwnEvidence() async {
+ // Tools that declare their result is evidence (e.g. a shell command's output/exit code)
+ // satisfy the completion gate without a separate re-observe step.
+ struct StubActThenCompletePlanner: HarnessNextStepPlanning {
+ func planNextStep(for task: HarnessTaskState) async -> HarnessToolCall? {
+ task.toolHistory.isEmpty
+ ? HarnessToolCall(name: "test.evidence-act")
+ : HarnessToolCall(name: "run.complete", input: ["reason": "command output confirms"])
+ }
+ }
+
+ let coordinator = HarnessTaskCoordinator()
+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors()
+ await registry.register(
+ stubTool(
+ name: "test.evidence-act",
+ safetyClass: .guardedInput,
+ metadata: [HarnessToolDescriptor.resultIsEvidenceMetadataKey: "true"]
+ )
+ )
+ let runtime = GenericHarnessRuntime(coordinator: coordinator, registry: registry)
+ let task = await coordinator.createTask(
+ id: "task-complete-self-evidence",
+ threadID: "thread-complete-self-evidence",
+ goal: "act with evidence",
+ grantedPermissions: [.lifecycle]
+ )
+
+ let steps = await runtime.run(taskID: task.id, planner: StubActThenCompletePlanner(), maxSteps: 4)
+
+ #expect(steps.map { $0.toolResult?.toolName } == ["test.evidence-act", "run.complete"])
+ let finalTask = await coordinator.task(id: task.id)
+ #expect(finalTask?.status == .completed)
+ }
+
+ private func stubTool(
+ name: String,
+ safetyClass: HarnessToolSafetyClass,
+ metadata: [String: String] = [:]
+ ) -> HarnessTool {
+ HarnessTool(
+ descriptor: HarnessToolDescriptor(
+ name: name,
+ pluginID: "test",
+ summary: "Stub tool.",
+ safetyClass: safetyClass,
+ metadata: metadata
+ )
+ ) { context in
+ HarnessToolResult(
+ callID: context.call.id,
+ toolName: context.call.name,
+ status: .succeeded,
+ summary: "ok"
+ )
+ }
+ }
+
@Test
func skillRegistryCanRegisterAndSearchSkills() async {
let registry = HarnessSkillRegistry()
@@ -322,18 +516,18 @@ struct GenericHarnessTests {
@Test
func builtInLocalAppSkillPacksProvideBoundedIntentGuidance() async throws {
let skills = BuiltInLocalAppSkillPacks.descriptors()
- #expect(skills.contains { $0.id == "music-media" })
- #expect(skills.contains { $0.id == "browser-navigation" })
+ #expect(skills.contains { $0.id == "music" })
+ #expect(skills.contains { $0.id == "browser" })
}
@Test
func userQueryHarnessServicesExposeBuiltInMusicSkillScript() async throws {
let services = LocalAppUserQueryHarnessServices.builtInSkillBackedServices()
- let musicSkill = await services.skillRegistry?.descriptor(id: "music-media")
+ let musicSkill = await services.skillRegistry?.descriptor(id: "music")
let script = await services.generatedScripts.artifact(id: "scripts-play-media-by-search")
#expect(musicSkill?.scripts.contains { $0.id == "scripts-play-media-by-search" } == true)
- #expect(script?.ownerSkillID == "music-media")
+ #expect(script?.ownerSkillID == "music")
#expect(script?.validationStatus == .validated)
#expect(script?.language == .appleScript)
}
@@ -1105,8 +1299,9 @@ struct GenericHarnessTests {
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 profile = try HarnessApplicationSkillPackWriter.loadProfile(
+ from: savedDirectory.appendingPathComponent("app-profile.json")
+ )
let scriptSource = try String(
contentsOf: savedDirectory.appendingPathComponent("scripts/focus-editor.applescript"),
encoding: .utf8
@@ -1114,11 +1309,22 @@ struct GenericHarnessTests {
let results = await skillRegistry.search(query: "DraftPad learned app")
#expect(skillMarkdown.contains("DraftPad Learned Application"))
+ // The saved pack must name its app in `apps:` frontmatter so later sessions match it to
+ // DraftPad by display name or bundle id, exactly like a built-in pack.
+ #expect(skillMarkdown.contains("apps: DraftPad, com.example.DraftPad"))
#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)
+ #expect(results.first?.descriptor.metadata["apps"]?.contains("DraftPad") == true)
+
+ // Cross-session discovery: a fresh filesystem source over the saved root re-discovers the
+ // pack with its app mapping intact — this is how learning compounds across sessions.
+ let rediscovered = HarnessSkillFileSystemSource(roots: [root], sourceKind: .userDirectory).discover()
+ let rediscoveredPack = try #require(rediscovered.first { $0.id == "learned-draftpad" })
+ #expect(rediscoveredPack.metadata["apps"]?.contains("com.example.DraftPad") == true)
+ #expect(rediscoveredPack.scripts.map(\.relativePath) == ["scripts/focus-editor.applescript"])
}
@Test