Open source CapCut alternative.
TypeScript
refactor(app): scope harness run history to the current run
David Leddde6c5f12bb
diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessCoordinator.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessCoordinator.swiftindex d2e355b7..a546d3b1 100644--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessCoordinator.swift+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessCoordinator.swift@@ -218,6 +218,18 @@ public actor HarnessTaskCoordinator {public func startRunning(taskID: String, reason: String = "Task running") async -> HarnessTaskState? {await mutate(taskID: taskID, status: .running, summary: reason) { task intask.pendingContinuation = nil+ // A new run on a task whose previous run already ended must not inherit that run's+ // facts as current truth — observed live: a stale "10 songs added" fact convinced the+ // planner a brand-new playlist was already populated, so it skipped the add and then+ // spiraled on the (truthful) empty read. The tool history keeps the full record for+ // context; the facts re-derive from the fresh reads the completion gate already+ // requires. Gate resumes (clarify/permission) continue the SAME run — their history+ // does not end in a terminal lifecycle call — and keep their facts.+ let terminalNames: Set<String> = ["run.complete", "run.failSafe", "run.cancel"]+ if let last = task.toolHistory.last,+ terminalNames.contains(last.call.name), last.resultStatus == .succeeded {+ task.worldModel.facts = [:]+ }}}@@ -334,6 +346,17 @@ public actor HarnessTaskCoordinator {}}+ /// Appends a note to the most recent tool record's summary. The runtime uses this to warn the+ /// planner — in the history it reads every step — that it just repeated a call without learning+ /// anything, one step before the stall guard would end the run.+ public func annotateLastToolRecord(taskID: String, note: String) async -> HarnessTaskState? {+ await mutate(taskID: taskID, status: nil, summary: "Tool record annotated") { task in+ guard !task.toolHistory.isEmpty else { return }+ task.toolHistory[task.toolHistory.count - 1].summary += "\n\(note)"+ task.worldModel.attemptedToolCalls = task.toolHistory+ }+ }+private func setStatus(taskID: String,status: HarnessTaskStatus,diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swiftindex 383968eb..d662c965 100644--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift@@ -60,6 +60,7 @@ public struct GenericHarnessRuntime: Sendable {maxSteps: Int = 200,maxNoProgressSteps: Int = 6,maxIdenticalRepeats: Int = 3,+ maxRepeatedFailures: Int = 3,onStep: (@Sendable (HarnessStepExecutionResult) async -> Void)? = nil) async -> [HarnessStepExecutionResult] {var results: [HarnessStepExecutionResult] = []@@ -85,17 +86,36 @@ public struct GenericHarnessRuntime: Sendable {}// 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+ // progress and resets the streaks, so an arbitrarily long advancing run continues. Three// 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) {+ // the SAME call repeated with no progress (looping on one action), or — over the whole+ // tool history, immune to interleaved successes and varied input fields — the same tool+ // failing the same way again and again, or a trailing run of invalid calls across any+ // tools. Lifecycle calls are exempt from the repeat signal — they legitimately end the+ // run themselves.+ let repeatedSameCall = signature == lastCallSignature+ if Self.stepMadeProgress(+ before: task,+ after: step.task,+ result: step.toolResult,+ repeatedSameCall: repeatedSameCall+ ) {noProgressStreak = 0identicalNoProgressStreak = 0} else {noProgressStreak += 1if !call.name.hasPrefix("run."), signature == lastCallSignature {identicalNoProgressStreak += 1+ // One deterministic warning before the stall guard ends the run: annotate the+ // repeated record so the next planning prompt shows the model it is re-running+ // what it already knows (observed live: a planner re-read identical playlist+ // entries out of disbelief until the guard killed the run).+ _ = await coordinator.annotateLastToolRecord(+ taskID: taskID,+ note: "NOTE: this exact call already ran and returned the same result — you "+ + "already have this information. Do not repeat it; take the next action "+ + "toward the goal, or report the blocker honestly."+ )} else {identicalNoProgressStreak = 0}@@ -107,6 +127,10 @@ public struct GenericHarnessRuntime: Sendable {await failSafeStall(taskID: taskID, reason: "stuckRepeatingCall")break}+ if let reason = Self.repeatedFailureStallReason(after: step, threshold: maxRepeatedFailures) {+ await failSafeStall(taskID: taskID, reason: reason)+ break+ }}lastCallSignature = signature}@@ -119,7 +143,8 @@ public struct GenericHarnessRuntime: Sendable {private static func stepMadeProgress(before: HarnessTaskState,after: HarnessTaskState,- result: HarnessToolResult?+ result: HarnessToolResult?,+ repeatedSameCall: Bool) -> Bool {guard let result else { return false }guard result.status == .succeeded else { return false }@@ -127,6 +152,11 @@ public struct GenericHarnessRuntime: Sendable {|| before.worldModel.facts != after.worldModel.facts|| before.worldModel.visibleText != after.worldModel.visibleTextif worldChanged { return true }+ // Repeating the exact same call and learning nothing new is not progress, no matter what+ // the result reports — observed live: nine identical succeeded playlist-list reads, each+ // returning the same facts, kept resetting the streaks until the model hallucinated+ // completion.+ if repeatedSameCall { return false }// 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@@ -134,6 +164,43 @@ public struct GenericHarnessRuntime: Sendable {|| !result.observations.visibleText.isEmpty}+ /// Repeated-failure detection over the task's durable tool history, so it survives interleaved+ /// successes that reset the consecutive streaks. Matches only typed fields — tool names, result+ /// statuses, and tool-produced failure summaries (structured output, never user text). Catches+ /// two loops the consecutive-signature guard misses: the same tool failing the same way with+ /// other calls interleaved or minor input fields varied, and invalid calls alternating between+ /// tools. Summaries that embed variable data (positions, timestamps) won't match — acceptable;+ /// the streak guards remain the backstop.+ private static func repeatedFailureStallReason(+ after step: HarnessStepExecutionResult,+ threshold: Int+ ) -> String? {+ guard let result = step.toolResult,+ result.status == .failed || result.status == .invalidInput else { return nil }+ let history = Self.currentRunHistory(step.task.toolHistory)+ let identicalFailures = history.filter {+ $0.call.name == result.toolName+ && ($0.resultStatus == .failed || $0.resultStatus == .invalidInput)+ && $0.summary == result.summary+ }.count+ if identicalFailures >= threshold { return "stuckRepeatingFailure" }+ let trailingInvalidInput = history.reversed().prefix { $0.resultStatus == .invalidInput }.count+ if trailingInvalidInput >= threshold { return "repeatedInvalidInput" }+ return nil+ }++ /// The slice of tool history belonging to the current run: everything after the last succeeded+ /// terminal lifecycle call (run.complete / run.failSafe / run.cancel). A task resumed for a new+ /// user turn keeps its full history for context, but guards that reason about "this run" —+ /// duplicate actions, repeated failures — must not match records from a run that already ended.+ private static func currentRunHistory(_ history: [HarnessToolCallRecord]) -> ArraySlice<HarnessToolCallRecord> {+ let terminalNames: Set<String> = ["run.complete", "run.failSafe", "run.cancel"]+ guard let lastTerminal = history.lastIndex(where: {+ terminalNames.contains($0.call.name) && $0.resultStatus == .succeeded+ }) else { return history[...] }+ return history[history.index(after: lastTerminal)...]+ }+/// 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 {@@ -350,11 +417,26 @@ public struct GenericHarnessRuntime: Sendable {/// 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.+ /// completion. Both rules are scoped to the CURRENT run: a fresh turn on a resumed task must+ /// observe at least once before completing — world-model facts carried over from a previous run+ /// can be stale (observed live: the agent re-completed "create a playlist" from old facts after+ /// the user had deleted the playlist).private func completionEvidenceRejection(call: HarnessToolCall,task: HarnessTaskState) async -> HarnessToolResult? {+ let history = Self.currentRunHistory(task.toolHistory)+ if !task.toolHistory.isEmpty, !history.contains(where: { $0.resultStatus == .succeeded }) {+ return HarnessToolResult(+ callID: call.id,+ toolName: call.name,+ status: .failed,+ summary: "Not completing yet: nothing has been verified in this run — facts carried "+ + "over from a previous run may be stale. Run a read-only check confirming the "+ + "goal still holds (re-observe, a read command, or state.verify), then complete.",+ metadata: ["reason": "completionRequiresEvidence"]+ )+ }let descriptors = await registry.descriptors()let knownNames = Set(descriptors.map(\.name))let evidenceNames = Set(@@ -366,11 +448,11 @@ public struct GenericHarnessRuntime: Sendable {func isEvidence(_ record: HarnessToolCallRecord) -> Bool {evidenceNames.contains(record.call.name) || !knownNames.contains(record.call.name)}- let lastActionIndex = task.toolHistory.lastIndex {+ let lastActionIndex = history.lastIndex {$0.resultStatus == .succeeded && !isEvidence($0)}guard let lastActionIndex else { return nil }- let hasEvidenceAfterAction = task.toolHistory[task.toolHistory.index(after: lastActionIndex)...]+ let hasEvidenceAfterAction = history[history.index(after: lastActionIndex)...].contains { $0.resultStatus == .succeeded && isEvidence($0) }guard !hasEvidenceAfterAction else { return nil }return HarnessToolResult(@@ -383,19 +465,28 @@ public struct GenericHarnessRuntime: Sendable {}/// Rejects a state-changing call whose exact (tool, input) already succeeded earlier in this run —- /// re-running it only duplicates the side effect. Read-only tools and lifecycle calls are exempt.+ /// re-running it only duplicates the side effect. Read-only tools, a multi-action tool's declared+ /// read actions, lifecycle calls, and records from previous runs of a resumed task are exempt./// Returns a failed result that tells the planner to verify and complete instead of repeating.private func duplicateActionRejection(call: HarnessToolCall,task: HarnessTaskState) async -> HarnessToolResult? {guard !call.name.hasPrefix("run."), !call.name.hasPrefix("conversation.") else { return nil }- let readOnlyNames = Set(- await registry.descriptors().filter { $0.safetyClass == .readOnly }.map(\.name)- )+ let descriptors = await registry.descriptors()+ let readOnlyNames = Set(descriptors.filter { $0.safetyClass == .readOnly }.map(\.name))guard !readOnlyNames.contains(call.name) else { return nil }+ // A multi-action tool's read actions (list/entries style) are verification, not side+ // effects — exempt them by the descriptor's declared read-only action values, matched on+ // the typed `action` input.+ if let action = call.input["action"],+ let declared = descriptors.first(where: { $0.name == call.name })?+ .metadata[HarnessToolDescriptor.readOnlyActionsMetadataKey],+ declared.split(separator: ",").map({ $0.trimmingCharacters(in: .whitespaces) }).contains(action) {+ return nil+ }let signature = Self.canonicalInput(call.input)- let alreadySucceeded = task.toolHistory.contains { record in+ let alreadySucceeded = Self.currentRunHistory(task.toolHistory).contains { record inrecord.resultStatus == .succeeded&& record.call.name == call.name&& Self.canonicalInput(record.call.input) == signaturediff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swiftindex 9e989749..035e625e 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift@@ -378,6 +378,262 @@ struct GenericHarnessTests {#expect(finalTask?.status == .failedSafe)}+ @Test+ func duplicateGuardIgnoresActionsFromAFinishedRun() async {+ // A task resumed for a new user turn keeps its history, but "already done in this run" must+ // not match a run that already ended — the live failure: a verification re-list was blocked+ // because the same call succeeded hours earlier in a run that failed safe.+ let coordinator = HarnessTaskCoordinator()+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors()+ await registry.register(stubTool(name: "test.act", safetyClass: .guardedInput))+ let runtime = GenericHarnessRuntime(coordinator: coordinator, registry: registry)+ let task = await coordinator.createTask(id: "task-rerun", threadID: "t", goal: "rerun", grantedPermissions: [.lifecycle])++ let call = HarnessToolCall(name: "test.act", input: ["command": "make note"])+ let first = await runtime.executeToolCall(taskID: task.id, call: call)+ #expect(first?.toolResult?.status == .succeeded)+ _ = await runtime.executeToolCall(taskID: task.id, call: HarnessToolCall(name: "run.failSafe", input: ["reason": "test"]))++ _ = await coordinator.startRunning(taskID: task.id, reason: "follow-up turn")+ let repeated = await runtime.executeToolCall(taskID: task.id, call: HarnessToolCall(name: "test.act", input: ["command": "make note"]))++ #expect(repeated?.toolResult?.status == .succeeded)+ #expect(repeated?.toolResult?.metadata["reason"] != "duplicateAction")+ }++ @Test+ func duplicateGuardExemptsDeclaredReadOnlyActions() async {+ // A multi-action tool (music.playlist style) is state-changing overall, but its declared+ // read actions are verification — repeating them must never be blocked, while repeating a+ // state-changing action of the same tool still is.+ let coordinator = HarnessTaskCoordinator()+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors()+ await registry.register(+ HarnessTool(+ descriptor: HarnessToolDescriptor(+ name: "test.multi",+ pluginID: "test",+ summary: "multi-action",+ inputSchema: ["action": "list | create"],+ safetyClass: .reversible,+ metadata: [HarnessToolDescriptor.readOnlyActionsMetadataKey: "list,entries"]+ )+ ) { context in+ HarnessToolResult(callID: context.call.id, toolName: context.call.name, status: .succeeded, summary: "ok")+ }+ )+ let runtime = GenericHarnessRuntime(coordinator: coordinator, registry: registry)+ let task = await coordinator.createTask(id: "task-multi", threadID: "t", goal: "multi", grantedPermissions: [.lifecycle])++ let list = HarnessToolCall(name: "test.multi", input: ["action": "list"])+ _ = await runtime.executeToolCall(taskID: task.id, call: list)+ let repeatedList = await runtime.executeToolCall(taskID: task.id, call: HarnessToolCall(name: "test.multi", input: ["action": "list"]))+ #expect(repeatedList?.toolResult?.status == .succeeded)+ #expect(repeatedList?.toolResult?.metadata["reason"] != "duplicateAction")++ let create = HarnessToolCall(name: "test.multi", input: ["action": "create"])+ _ = await runtime.executeToolCall(taskID: task.id, call: create)+ let repeatedCreate = await runtime.executeToolCall(taskID: task.id, call: HarnessToolCall(name: "test.multi", input: ["action": "create"]))+ #expect(repeatedCreate?.toolResult?.metadata["reason"] == "duplicateAction")+ }++ @Test+ func runCompleteOnAResumedTaskRequiresFreshEvidence() async {+ // The live false-completion: a new turn resumed a task whose previous run had created and+ // verified everything, the user had since undone the result, and the model re-completed+ // from stale world facts without a single observation this run. A fresh run must succeed+ // at least one step (an observe is enough) before run.complete is accepted.+ let coordinator = HarnessTaskCoordinator()+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors()+ await registry.register(stubTool(name: "test.act", safetyClass: .guardedInput))+ await registry.register(+ HarnessTool(+ descriptor: HarnessToolDescriptor(name: "test.observe", pluginID: "test", summary: "observe", safetyClass: .readOnly)+ ) { context in+ HarnessToolResult(callID: context.call.id, toolName: context.call.name, status: .succeeded, summary: "observed")+ }+ )+ let runtime = GenericHarnessRuntime(coordinator: coordinator, registry: registry)+ let task = await coordinator.createTask(id: "task-stale", threadID: "t", goal: "stale", grantedPermissions: [.lifecycle])++ // Previous run: act, verify, complete.+ _ = await runtime.executeToolCall(taskID: task.id, call: HarnessToolCall(name: "test.act", input: ["command": "do it"]))+ _ = await runtime.executeToolCall(taskID: task.id, call: HarnessToolCall(name: "test.observe"))+ _ = await runtime.executeToolCall(taskID: task.id, call: HarnessToolCall(name: "run.complete", input: ["reason": "done"]))++ // A follow-up turn resumes the task; completing on stale facts alone is rejected.+ _ = await coordinator.startRunning(taskID: task.id, reason: "follow-up turn")+ let premature = await runtime.executeToolCall(taskID: task.id, call: HarnessToolCall(name: "run.complete", input: ["reason": "already done"]))+ #expect(premature?.toolResult?.status == .failed)+ #expect(premature?.toolResult?.metadata["reason"] == "completionRequiresEvidence")+ #expect(premature?.toolResult?.summary.contains("previous run") == true)++ // One succeeded observation this run unlocks completion.+ _ = await runtime.executeToolCall(taskID: task.id, call: HarnessToolCall(name: "test.observe"))+ let completed = await runtime.executeToolCall(taskID: task.id, call: HarnessToolCall(name: "run.complete", input: ["reason": "verified again"]))+ #expect(completed?.toolResult?.status == .succeeded)+ let finalTask = await coordinator.task(id: task.id)+ #expect(finalTask?.status == .completed)+ }++ @Test+ func runStopsWhenTheSameToolKeepsFailingTheSameWayDespiteInterleavedSuccesses() async {+ // The live failure mode: a broken tool fails identically on every call, but the planner+ // varies a minor input field and interleaves successful diagnostics that reset the+ // consecutive streaks. The history-based guard must still stop the run at the third+ // identical failure.+ struct StubAlternatingPlanner: HarnessNextStepPlanning {+ func planNextStep(for task: HarnessTaskState) async -> HarnessToolCall? {+ task.toolHistory.count.isMultiple(of: 2)+ ? HarnessToolCall(name: "test.fail", input: ["attempt": String(task.toolHistory.count)])+ : HarnessToolCall(name: "test.observe")+ }+ }+ let coordinator = HarnessTaskCoordinator()+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors()+ await registry.register(+ HarnessTool(+ descriptor: HarnessToolDescriptor(name: "test.fail", pluginID: "test", summary: "fail", safetyClass: .guardedInput)+ ) { context in+ HarnessToolResult(+ callID: context.call.id, toolName: context.call.name, status: .failed,+ summary: "create returned no item"+ )+ }+ )+ await registry.register(+ HarnessTool(+ descriptor: HarnessToolDescriptor(name: "test.observe", pluginID: "test", summary: "observe", safetyClass: .readOnly)+ ) { context in+ HarnessToolResult(+ callID: context.call.id, toolName: context.call.name, status: .succeeded,+ summary: "observed",+ observations: HarnessObservationDelta(facts: ["seen": context.call.id])+ )+ }+ )+ let runtime = GenericHarnessRuntime(coordinator: coordinator, registry: registry)+ let task = await coordinator.createTask(id: "task-refail", threadID: "t", goal: "refail", grantedPermissions: [.lifecycle])++ let steps = await runtime.run(taskID: task.id, planner: StubAlternatingPlanner(), maxSteps: 100)++ // Three identical failures with successful observes between them — stops at the third+ // failure (5 steps), far below what the no-progress streak alone would allow.+ let failures = steps.filter { $0.toolResult?.toolName == "test.fail" }+ #expect(failures.count == 3)+ #expect(steps.count == 5)+ let finalTask = await coordinator.task(id: task.id)+ #expect(finalTask?.status == .failedSafe)+ }++ @Test+ func startRunningClearsFactsCarriedOverFromAFinishedRun() async {+ // The live failure: a stale "added 10 songs" fact from a finished run convinced the planner+ // a brand-new playlist was already populated. A fresh run starts with fresh facts; a gate+ // resume (history not ending in a terminal lifecycle call) keeps them.+ let coordinator = HarnessTaskCoordinator()+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors()+ await registry.register(+ HarnessTool(+ descriptor: HarnessToolDescriptor(+ name: "test.act",+ pluginID: "test",+ summary: "act",+ safetyClass: .guardedInput,+ metadata: [HarnessToolDescriptor.resultIsEvidenceMetadataKey: "true"]+ )+ ) { context in+ HarnessToolResult(+ callID: context.call.id, toolName: context.call.name, status: .succeeded,+ summary: "did it",+ observations: HarnessObservationDelta(facts: ["added.count": "10"])+ )+ }+ )+ let runtime = GenericHarnessRuntime(coordinator: coordinator, registry: registry)+ let task = await coordinator.createTask(id: "task-fresh-facts", threadID: "t", goal: "facts", grantedPermissions: [.lifecycle])++ _ = await runtime.executeToolCall(taskID: task.id, call: HarnessToolCall(name: "test.act", input: ["n": "1"]))+ let midRun = await coordinator.startRunning(taskID: task.id, reason: "not a new run")+ #expect(midRun?.worldModel.facts["added.count"] == "10")++ _ = await runtime.executeToolCall(taskID: task.id, call: HarnessToolCall(name: "run.complete", input: ["reason": "done"]))+ let freshRun = await coordinator.startRunning(taskID: task.id, reason: "follow-up turn")+ #expect(freshRun?.worldModel.facts.isEmpty == true)+ #expect(freshRun?.toolHistory.isEmpty == false)+ }++ @Test+ func runStopsWhenIdenticalReadsLoopWithoutNewInformation() async {+ // The live loop: identical succeeded list reads, each reporting the same facts, counted as+ // progress and reset every streak. An exact repeat that leaves the world model unchanged+ // must not count as progress, even though it reports observations.+ struct StubRereadingPlanner: HarnessNextStepPlanning {+ func planNextStep(for task: HarnessTaskState) async -> HarnessToolCall? {+ HarnessToolCall(name: "test.list", input: ["action": "list"])+ }+ }+ let coordinator = HarnessTaskCoordinator()+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors()+ await registry.register(+ HarnessTool(+ descriptor: HarnessToolDescriptor(name: "test.list", pluginID: "test", summary: "list", safetyClass: .readOnly)+ ) { context in+ HarnessToolResult(+ callID: context.call.id, toolName: context.call.name, status: .succeeded,+ summary: "Library playlists (1): Favorite Songs",+ observations: HarnessObservationDelta(facts: ["playlist.count": "1"])+ )+ }+ )+ let runtime = GenericHarnessRuntime(coordinator: coordinator, registry: registry)+ let task = await coordinator.createTask(id: "task-reread", threadID: "t", goal: "reread", grantedPermissions: [.lifecycle])++ let steps = await runtime.run(taskID: task.id, planner: StubRereadingPlanner(), maxSteps: 100)++ // The first read adds the fact (real progress); repeats teach nothing and trip the+ // identical-call guard instead of looping.+ #expect(steps.count <= 4)+ let finalTask = await coordinator.task(id: task.id)+ #expect(finalTask?.status == .failedSafe)+ // The repeated record carries the warning the planner reads on its next step, so the model+ // gets one explicit chance to change course before the guard ends the run.+ #expect(finalTask?.toolHistory.contains { $0.summary.contains("Do not repeat it") } == true)+ }++ @Test+ func runStopsOnInvalidInputCallsAlternatingBetweenTools() async {+ // A degraded planner emitting malformed calls for different tools defeats the+ // identical-signature guard; the trailing invalid-input run must stop it anyway.+ struct StubMalformedPlanner: HarnessNextStepPlanning {+ func planNextStep(for task: HarnessTaskState) async -> HarnessToolCall? {+ HarnessToolCall(name: task.toolHistory.count.isMultiple(of: 2) ? "test.a" : "test.b")+ }+ }+ let coordinator = HarnessTaskCoordinator()+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors()+ for name in ["test.a", "test.b"] {+ await registry.register(+ HarnessTool(+ descriptor: HarnessToolDescriptor(name: name, pluginID: "test", summary: name, safetyClass: .readOnly)+ ) { context in+ HarnessToolResult(+ callID: context.call.id, toolName: context.call.name, status: .invalidInput,+ summary: "\(context.call.name) requires an action"+ )+ }+ )+ }+ let runtime = GenericHarnessRuntime(coordinator: coordinator, registry: registry)+ let task = await coordinator.createTask(id: "task-malformed", threadID: "t", goal: "malformed", grantedPermissions: [.lifecycle])++ let steps = await runtime.run(taskID: task.id, planner: StubMalformedPlanner(), maxSteps: 100)++ #expect(steps.count == 3)+ let finalTask = await coordinator.task(id: task.id)+ #expect(finalTask?.status == .failedSafe)+ }+@Testfunc longProgressingRunIsNotCutOffByAFixedCap() async {// Each step changes the world model (real progress), so a run longer than the old 40-step cap@@ -631,15 +887,14 @@ struct GenericHarnessTests {}@Test- func userQueryHarnessServicesExposeBuiltInMusicSkillScript() async throws {+ func builtInMusicSkillIsScriptFree() async throws {+ // Music playback is owned by the native music.* tools; the skill is guidance-only. A script+ // reappearing here would re-introduce the retired AppleScript/GUI playback path.let services = LocalAppUserQueryHarnessServices.builtInSkillBackedServices()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")- #expect(script?.validationStatus == .validated)- #expect(script?.language == .appleScript)+ #expect(musicSkill != nil)+ #expect(musicSkill?.scripts.isEmpty == true)}/// The summary is the tool-result body the planner reads, so a skill script's structured