Open source CapCut alternative.
TypeScript
feat(app): thread the harness step planner as a moving conversation
David Le41e650d1c7e9
diff --git a/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift b/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swiftindex d2149bb5..40ab9f42 100644--- a/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift+++ b/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift@@ -144,6 +144,17 @@ public enum DonkeyPrompts {editing in a design app). LEAVE IT EMPTY when an expert would use system tools instead — finding files,opening or quitting apps, reading or changing settings or state — and for pure conversation.If it clearly concerns the current app's UI, use "\(frontmostAppName)".+ - actionSurface: does this turn operate an app's interface, or produce a result with no app at all?+ - "guiApp": the work happens inside a macOS app's GUI — a named app, or the one in front+ ("\(frontmostAppName)"). Use this whenever the user is operating, editing, or controlling an app.+ - "appless": the deliverable is an artifact or a system change the agent produces with system,+ web, and generative tools — making an image, a chart, a PDF, or a file; fetching or+ researching something; reading or changing a setting. There is no app to drive; the result is+ the file, the answer, or the changed state. Choose this whenever the request is about the+ OUTCOME, not about working in some app — even if an app happens to be in front. When in doubt+ for an "act" turn whose point is a produced result rather than operating an app, prefer+ "appless". Always "appless" for an empty targetAppName that is a system-tool task; always+ "guiApp" when targetAppName is set. Irrelevant for "converse"/"clarify" — leave "guiApp".- parameters: the concrete details needed to do it (e.g. title, recipient, query, value), asstring key/values. Omit what is not specified.- successCriteria: what would be visible on screen once the goal is done.@@ -223,6 +234,12 @@ public enum DonkeyPrompts {/// condensed to "tool → status" so the model never loses sight of its own earlier trajectory.public static let harnessStepMaxDetailedHistorySteps = 12+ /// Per-step cap on a rendered summary in the history block. One huge output (a full `ls` of a busy+ /// folder, a long file read) must not dominate the trail and bury the small, relevant results around+ /// it — that buried a clip's `ffprobe` duration under a Downloads listing and the planner re-ran it+ /// until the run stalled. The planner can always re-read specifics; this only bounds the recap.+ public static let harnessStepSummaryMaxLength = 600+/// Distills a finished run into at most one durable, general operating lesson for the agent's future/// self. Fed the run's goal, terminal outcome, and full thread trace; returns strict JSON. The model/// is told to stay general (an operating rule, never task-specific facts or anything about this@@ -255,7 +272,13 @@ public enum DonkeyPrompts {"""}- public static func harnessStep(+ /// The STATIC half of the planning prompt — the system instructions sent once and cacheable. Doctrine,+ /// the goal, the parsed understanding, recalled lessons, the app/skill guides, the tool list, and the+ /// reply shape: none of it changes step to step within a turn. The per-step state (facts, windows,+ /// observed elements, follow-ups, the retry note) moves forward separately in `harnessTurnState`, and+ /// the run's history threads as real turns, so the request reads as a conversation that advances rather+ /// than one monolithic prompt re-sent every step.+ public static func harnessSystemInstructions(task: HarnessAgentState,descriptors: [HarnessToolDescriptor],appName: String,@@ -263,42 +286,8 @@ public enum DonkeyPrompts {understanding: HarnessRequestUnderstanding?,skillCatalog: String? = nil,preloadedSkillGuides: [String] = [],- lessons: String? = nil,- rollingContext: String? = nil,- retryNote: String? = nil,- openWindows: [MacWindowTargetCandidate] = []+ lessons: String? = nil) -> String {- let elementsBlock = harnessStepElementsBlock(task.worldModel.elements)- let windowsBlock = harnessStepWindowsBlock(openWindows)-- // Follow-up instructions the user added after the task started are surfaced in their own block- // below (right under the goal), so they are excluded from the generic facts dump here.- let displayFacts = task.worldModel.facts- .filter { $0.key != HarnessAgentCoordinator.additionalInstructionsFactKey }- let factsBlock = displayFacts.isEmpty- ? ""- : "\nKnown state:\n" + displayFacts.sorted { $0.key < $1.key }- .map { " \($0.key) = \($0.value)" }.joined(separator: "\n") + "\n"-- let followUpInstructions = task.worldModel.facts[HarnessAgentCoordinator.additionalInstructionsFactKey]?- .trimmingCharacters(in: .whitespacesAndNewlines) ?? ""- let followUpBlock = followUpInstructions.isEmpty- ? ""- : "\nADDITIONAL INSTRUCTIONS FROM THE USER (sent after the task started — fold them into your "- + "current work; do NOT restart from scratch or redo completed steps):\n"- + String(followUpInstructions.prefix(800)) + "\n"-- let historyBlock = harnessStepHistoryBlock(task.toolHistory)-- // Cross-turn conversation memory: recent conversation events plus a rolling summary of older- // turns. Distinct from the tool-history block above — that is what THIS run did; this is what the- // whole conversation is about, including compacted earlier turns. The full record is on disk.- let trimmedRollingContext = rollingContext?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""- let rollingContextBlock = trimmedRollingContext.isEmpty- ? ""- : "\nCONVERSATION SO FAR (rolling summary of older turns + recent events; the full record is "- + "on disk):\n\(trimmedRollingContext)\n"-let toolsBlock = descriptors.sorted { $0.name < $1.name }.map { descriptor -> String in@@ -368,10 +357,7 @@ public enum DonkeyPrompts {entirely with system tools and have no on-screen UI target; reach for the GUI only when the tasktruly needs it.GOAL: \(goalText)- \(followUpBlock)\(understandingBlock)\(lessonsBlock)\(rollingContextBlock)- \(historyBlock)- \(factsBlock)\(guidanceBlock)\(preloadedSkillsBlock)\(skillCatalogBlock)\(windowsBlock)- \(elementsBlock)+ \(understandingBlock)\(lessonsBlock)\(guidanceBlock)\(preloadedSkillsBlock)\(skillCatalogBlock)AVAILABLE TOOLS:\(toolsBlock)@@ -466,10 +452,93 @@ public enum DonkeyPrompts {now I'll make the edit."). Say what you're doing this step and why in one breath. This narrates the \process; it is NOT the result. Reporting what is now true for the user is done only in conversation.respond \and run.complete, which still report the result, not the steps. Keep narration to one sentence; do not \- restate the whole plan or repeat the previous step.\(retryNote.map { "\nIMPORTANT: \($0)" } ?? "")+ restate the whole plan or repeat the previous step."""}+ /// The DYNAMIC half of the planning prompt — the FINAL user turn in the threaded request. Everything+ /// here can change between steps: follow-up instructions the user added mid-run, the rolling+ /// conversation summary, the known facts, the windows on screen, the freshly observed elements, and the+ /// per-attempt retry note. The static doctrine/goal/tools live in `harnessSystemInstructions`; only this+ /// turn-state advances each step, alongside the run's history threaded as real turns.+ public static func harnessTurnState(+ task: HarnessAgentState,+ openWindows: [MacWindowTargetCandidate] = [],+ rollingContext: String? = nil,+ retryNote: String? = nil+ ) -> String {+ let elementsBlock = harnessStepElementsBlock(task.worldModel.elements)+ let windowsBlock = harnessStepWindowsBlock(openWindows)++ // Follow-up instructions the user added after the task started get their own block so they are+ // excluded from the generic facts dump.+ let displayFacts = task.worldModel.facts+ .filter { $0.key != HarnessAgentCoordinator.additionalInstructionsFactKey }+ let factsBlock = displayFacts.isEmpty+ ? ""+ : "\nKnown state:\n" + displayFacts.sorted { $0.key < $1.key }+ .map { " \($0.key) = \($0.value)" }.joined(separator: "\n") + "\n"++ let followUpInstructions = task.worldModel.facts[HarnessAgentCoordinator.additionalInstructionsFactKey]?+ .trimmingCharacters(in: .whitespacesAndNewlines) ?? ""+ let followUpBlock = followUpInstructions.isEmpty+ ? ""+ : "\nADDITIONAL INSTRUCTIONS FROM THE USER (sent after the task started — fold them into your "+ + "current work; do NOT restart from scratch or redo completed steps):\n"+ + String(followUpInstructions.prefix(800)) + "\n"++ // Cross-turn conversation memory: recent events plus a rolling summary of older turns. Distinct+ // from the step turns — that is what THIS run did; this is what the whole conversation is about,+ // including compacted earlier turns. The full record is on disk.+ let trimmedRollingContext = rollingContext?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""+ let rollingContextBlock = trimmedRollingContext.isEmpty+ ? ""+ : "\nCONVERSATION SO FAR (rolling summary of older turns + recent events; the full record is "+ + "on disk):\n\(trimmedRollingContext)\n"++ return """+ \(followUpBlock)\(rollingContextBlock)\(factsBlock)\(windowsBlock)+ \(elementsBlock)++ Choose the single next tool now, given the state above and the steps already taken. Reply with \+ exactly one JSON object in the shape specified.\(retryNote.map { "\nIMPORTANT: \($0)" } ?? "")+ """+ }++ /// One-document rendering of the whole planning prompt — system instructions, the history trail, and+ /// the current turn state, concatenated. The planner sends the SPLIT form (cached instructions + a+ /// threaded conversation); this single-string wrapper backs the prompt-contains tests and any caller+ /// that wants the entire prompt as one value.+ public static func harnessStep(+ task: HarnessAgentState,+ descriptors: [HarnessToolDescriptor],+ appName: String,+ appGuidance: String?,+ understanding: HarnessRequestUnderstanding?,+ skillCatalog: String? = nil,+ preloadedSkillGuides: [String] = [],+ lessons: String? = nil,+ rollingContext: String? = nil,+ retryNote: String? = nil,+ openWindows: [MacWindowTargetCandidate] = []+ ) -> String {+ harnessSystemInstructions(+ task: task, descriptors: descriptors, appName: appName, appGuidance: appGuidance,+ understanding: understanding, skillCatalog: skillCatalog,+ preloadedSkillGuides: preloadedSkillGuides, lessons: lessons+ )+ + "\n\n" + harnessStepHistoryBlock(task.toolHistory) + "\n"+ + harnessTurnState(task: task, openWindows: openWindows, rollingContext: rollingContext, retryNote: retryNote)+ }++ /// The condensed "tool → status" trail for steps older than the detailed window, as one line. Threaded+ /// into the planning conversation as a single preamble turn so a long run keeps sight of where it has+ /// been even though only the most recent steps are sent as full turns.+ public static func harnessStepCondensedHistoryLine(_ evicted: [HarnessToolCallRecord]) -> String {+ let condensed = evicted.map { "\($0.call.name) → \($0.resultStatus.rawValue)" }.joined(separator: "; ")+ return "Earlier steps 1-\(evicted.count) (condensed): \(condensed)"+ }+/// Renders the other windows currently on screen — across every app and display — so the planner/// knows what *else* exists in the world and can switch to or target a window that isn't in front./// A request often lives in a window the user isn't looking at; the planner needs it to exist here@@ -579,7 +648,12 @@ public enum DonkeyPrompts {.joined(separator: "; ")lines.append(" Earlier steps 1-\(evicted.count) (condensed): \(condensed)")}- lines += recent.map { " \($0.call.name): \($0.summary)" }+ lines += recent.map { record in+ let summary = record.summary.count > harnessStepSummaryMaxLength+ ? String(record.summary.prefix(harnessStepSummaryMaxLength)) + " …[truncated]"+ : record.summary+ return " \(record.call.name): \(summary)"+ }return "Steps already taken (most recent last):\n" + lines.joined(separator: "\n")}diff --git a/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift b/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swiftindex fc3bcea8..c2218ec5 100644--- a/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift+++ b/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift@@ -411,7 +411,10 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {private static let maxOutputTokensCap = 8_000private func decide(task: HarnessAgentState, rollingContext: String?, retryNote: String?, attempt: Int) async throws -> Decision {- let prompt = DonkeyPrompts.harnessStep(+ // Static doctrine, goal, tools, and skills go in the cached system slot; only the dynamic turn+ // state and the run's history move forward in `input`, so the request reads as a thread that+ // advances rather than one monolithic prompt re-sent every step.+ let instructions = DonkeyPrompts.harnessSystemInstructions(task: task,descriptors: descriptors,appName: appName,@@ -419,13 +422,21 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {understanding: understanding,skillCatalog: skillCatalog,preloadedSkillGuides: preloadedSkillGuides,- lessons: recalledLessons,+ lessons: recalledLessons+ )+ let turnState = DonkeyPrompts.harnessTurnState(+ task: task,+ openWindows: openWindows(),rollingContext: rollingContext,- retryNote: retryNote,- openWindows: openWindows()+ retryNote: retryNote)+ let conversation = Self.conversationTurns(toolHistory: task.toolHistory, currentState: turnState)let imageDataURL = await captureScreenshot()- let request = responseRequest(prompt: prompt, attempt: attempt, imageDataURL: imageDataURL)+ let request = responseRequest(instructions: instructions, conversation: conversation, attempt: attempt, imageDataURL: imageDataURL)+ // The trace records exactly what was sent — the cached instructions followed by the conversation+ // turns — so the thread shows the model's true context even though the wire form is now a moving+ // thread rather than one prompt.+ let tracePrompt = Self.tracePrompt(instructions: instructions, conversation: conversation)let backend = self.backendlet startedAt = RunTraceTimestamp.now()let response: RemoteInferenceJSONValue@@ -435,7 +446,7 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {}} catch {recordPlannerCall(- prompt: prompt,+ prompt: tracePrompt,response: String(String(describing: error).prefix(500)),finishReason: nil,attempt: attempt,@@ -451,19 +462,19 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {let finishReason = RemoteInferenceResponseHelpers.providerFinishReason(from: response)if let finishReason, Self.contentFilterFinishReasons.contains(finishReason) {recordPlannerCall(- prompt: prompt, response: String(raw.prefix(500)), finishReason: finishReason,+ prompt: tracePrompt, response: String(raw.prefix(500)), finishReason: finishReason,attempt: attempt, status: .filtered, startedAt: startedAt, endedAt: endedAt)throw PlanningError.blockedByContentFilter(finishReason: finishReason, raw: String(raw.prefix(500)))}recordPlannerCall(- prompt: prompt, response: String(raw.prefix(2_000)), finishReason: finishReason,+ prompt: tracePrompt, response: String(raw.prefix(2_000)), finishReason: finishReason,attempt: attempt, status: .empty, startedAt: startedAt, endedAt: endedAt)throw PlanningError.missingOutputText(finishReason: finishReason, raw: String(raw.prefix(2_000)))}recordPlannerCall(- prompt: prompt,+ prompt: tracePrompt,response: text,finishReason: RemoteInferenceResponseHelpers.providerFinishReason(from: response),attempt: attempt,@@ -505,29 +516,41 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {))}- private func responseRequest(prompt: String, attempt: Int, imageDataURL: String? = nil) -> RemoteInferenceResponseCreateRequest {+ private func responseRequest(+ instructions: String,+ conversation: [Turn],+ attempt: Int,+ imageDataURL: String? = nil+ ) -> RemoteInferenceResponseCreateRequest {let maxOutputTokens = min(Self.baseMaxOutputTokens * (attempt + 1), Self.maxOutputTokensCap)- // Text part always; the compressed screenshot is appended as an image part when available so a- // multimodal model sees the screen. Both server adapters accept `input_image` + `image_url`.- var content: [RemoteInferenceJSONValue] = [- .object([- "type": .string("input_text"),- "text": .string(prompt)+ // The conversation threads as real messages: a user request/result is role "user", the model's own+ // prior decisions are role "assistant" (the server maps that to the provider's model role). The+ // compressed screenshot rides on the FINAL turn (the current state) so a multimodal model sees the+ // screen exactly where the latest observation is. Both server adapters accept `input_image`.+ let lastIndex = conversation.indices.last+ let messages: [RemoteInferenceJSONValue] = conversation.enumerated().map { index, turn in+ var content: [RemoteInferenceJSONValue] = [+ .object([+ "type": .string("input_text"),+ "text": .string(turn.text)+ ])+ ]+ if index == lastIndex, let imageDataURL, !imageDataURL.isEmpty {+ content.append(.object([+ "type": .string("input_image"),+ "image_url": .string(imageDataURL)+ ]))+ }+ return .object([+ "role": .string(turn.role),+ "content": .array(content)])- ]- if let imageDataURL, !imageDataURL.isEmpty {- content.append(.object([- "type": .string("input_image"),- "image_url": .string(imageDataURL)- ]))}return RemoteInferenceResponseCreateRequest(- input: .array([- .object([- "role": .string("user"),- "content": .array(content)- ])- ]),+ input: .array(messages),+ // Static doctrine, tools, goal, and skills are sent once in the cached system slot; only the+ // moving conversation lives in `input`.+ instructions: instructions,store: false,// Plain JSON mode, deliberately WITHOUT a response schema. Constrained decoding broke// the decision's `input` object two ways live: with `input` described only by@@ -542,7 +565,7 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {"type": .string("json_object")])],- metadata: ["source": "hosted-harness-step-planner", "prompt_version": "harness-step-v1"],+ metadata: ["source": "hosted-harness-step-planner", "prompt_version": "harness-step-v2-threaded"],parameters: ["temperature": .number(0),"max_output_tokens": .number(Double(maxOutputTokens)),@@ -551,4 +574,61 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {)}+ // MARK: - Threaded conversation++ /// One message in the threaded planning request: a role ("user" or "assistant") and its text. The+ /// conversation is the run's history turned into a forward-moving thread — each past step becomes the+ /// assistant decision it made and the user-visible result it produced — capped by the current turn+ /// state as the final user message. The computer-use request shape, not one prompt re-sent each step.+ private struct Turn: Sendable {+ var role: String+ var text: String+ }++ /// Build the planning conversation from the run's history plus the current state. Steps older than the+ /// detailed window collapse into one condensed preamble turn (so a long run never forgets its earlier+ /// trajectory without resending every step); the recent steps become assistant/user turn pairs; the+ /// current turn state is the final user message the model answers.+ private static func conversationTurns(toolHistory: [HarnessToolCallRecord], currentState: String) -> [Turn] {+ var turns: [Turn] = []+ let recent = Array(toolHistory.suffix(DonkeyPrompts.harnessStepMaxDetailedHistorySteps))+ let evicted = Array(toolHistory.dropLast(recent.count))+ if !evicted.isEmpty {+ turns.append(Turn(role: "user", text: DonkeyPrompts.harnessStepCondensedHistoryLine(evicted)))+ }+ for record in recent {+ turns.append(Turn(role: "assistant", text: renderDecision(record.call)))+ turns.append(Turn(role: "user", text: renderResult(record)))+ }+ turns.append(Turn(role: "user", text: currentState))+ return turns+ }++ /// The assistant turn for a past step: the decision JSON it produced, reconstructed from the recorded+ /// call so the thread reads as the model's own prior choices — the same shape it must keep emitting.+ private static func renderDecision(_ call: HarnessToolCall) -> String {+ let object: [String: Any] = ["tool": call.name, "input": call.input]+ if let data = try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]),+ let string = String(data: data, encoding: .utf8) {+ return string+ }+ return "{\"tool\":\"\(call.name)\"}"+ }++ /// The user turn for a past step: the observed result the tool produced, capped the same way the+ /// history block caps a single summary so one huge output can't dominate the thread.+ private static func renderResult(_ record: HarnessToolCallRecord) -> String {+ let summary = record.summary.count > DonkeyPrompts.harnessStepSummaryMaxLength+ ? String(record.summary.prefix(DonkeyPrompts.harnessStepSummaryMaxLength)) + " …[truncated]"+ : record.summary+ return "Result of \(record.call.name) [\(record.resultStatus.rawValue)]: \(summary)"+ }++ /// The trace's faithful rendering of the request: the cached system instructions, then each+ /// conversation turn labeled by role — so the thread shows exactly what the model saw.+ private static func tracePrompt(instructions: String, conversation: [Turn]) -> String {+ let turns = conversation.map { "[\($0.role)]\n\($0.text)" }.joined(separator: "\n\n")+ return instructions + "\n\n──────── conversation ────────\n\n" + turns+ }+}diff --git a/apps/Donkey/Sources/DonkeyContracts/RemoteInferenceContracts.swift b/apps/Donkey/Sources/DonkeyContracts/RemoteInferenceContracts.swiftindex b4937ef6..b6bce112 100644--- a/apps/Donkey/Sources/DonkeyContracts/RemoteInferenceContracts.swift+++ b/apps/Donkey/Sources/DonkeyContracts/RemoteInferenceContracts.swift@@ -168,6 +168,11 @@ public struct RemoteInferenceResponseCreateRequest: Codable, Equatable, Sendablepublic var donkeyProvider: String?public var model: String?public var input: RemoteInferenceJSONValue+ /// System instruction sent once per request (the provider maps it to its own system slot and can cache+ /// it). The planner puts its static doctrine, tool list, goal, and skills here, so only the dynamic+ /// conversation turns live in `input` — the request reads as a thread that moves forward, not a+ /// monolithic prompt re-sent every step.+ public var instructions: String?public var store: Boolpublic var text: RemoteInferenceJSONObject?public var tools: [RemoteInferenceJSONObject]@@ -179,6 +184,7 @@ public struct RemoteInferenceResponseCreateRequest: Codable, Equatable, SendabledonkeyProvider: String? = nil,model: String? = nil,input: RemoteInferenceJSONValue,+ instructions: String? = nil,store: Bool = false,text: RemoteInferenceJSONObject? = nil,tools: [RemoteInferenceJSONObject] = [],@@ -189,6 +195,7 @@ public struct RemoteInferenceResponseCreateRequest: Codable, Equatable, Sendableself.donkeyProvider = donkeyProviderself.model = modelself.input = input+ self.instructions = instructionsself.store = storeself.text = textself.tools = tools@@ -202,6 +209,7 @@ public struct RemoteInferenceResponseCreateRequest: Codable, Equatable, Sendabletry container.encodeIfPresent(donkeyProvider, forKey: DynamicCodingKey("donkeyProvider"))try container.encodeIfPresent(model, forKey: DynamicCodingKey("model"))try container.encode(input, forKey: DynamicCodingKey("input"))+ try container.encodeIfPresent(instructions, forKey: DynamicCodingKey("instructions"))try container.encode(store, forKey: DynamicCodingKey("store"))try container.encode(false, forKey: DynamicCodingKey("stream"))try container.encodeIfPresent(text, forKey: DynamicCodingKey("text"))diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessStepPromptTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessStepPromptTests.swiftindex db1313ae..c018658a 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessStepPromptTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessStepPromptTests.swift@@ -24,7 +24,9 @@ struct HarnessStepPromptTests {understanding: nil,skillCatalog: catalog)- #expect(prompt.contains("authoritative playbooks for these apps/domains"))+ #expect(prompt.contains("OTHER AVAILABLE SKILLS"))+ #expect(prompt.contains("authoritative playbooks"))+ #expect(prompt.contains("skill.load"))#expect(prompt.contains("scripts-save-note"))#expect(prompt.contains("skill_run"))}@@ -40,7 +42,7 @@ struct HarnessStepPromptTests {understanding: nil,skillCatalog: nil)- #expect(!prompt.contains("authoritative playbooks for these apps/domains"))+ #expect(!prompt.contains("OTHER AVAILABLE SKILLS"))}private func window(app: String, title: String, frontmost: Bool) -> MacWindowTargetCandidate {diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessStepPlannerTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessStepPlannerTests.swiftindex ad3ea3e9..e6d30108 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessStepPlannerTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessStepPlannerTests.swift@@ -456,6 +456,45 @@ struct HostedHarnessStepPlannerTests {#expect(body.contains("Summary of step 15."))}+ @Test+ func threadsStaticDoctrineAsInstructionsAndHistoryAsConversationTurns() async throws {+ // The frontier shape: the static doctrine, goal, and tool list go in the cached `instructions`+ // slot (sent once, not re-sent each step), and the run's history becomes a forward-moving message+ // thread — the model's prior decision as an assistant turn, the tool's result as a user turn —+ // capped by the current state as the final user turn. This is how the planner "behaves like Claude":+ // a conversation that advances, not one monolithic prompt rebuilt every step.+ let httpClient = FixtureHTTPClient(data: cannedDecision(tool: "ax.observe"), statusCode: 200)+ let planner = makePlanner(httpClient: httpClient, understanding: nil)+ let prior = HarnessToolCallRecord(+ call: HarnessToolCall(name: "shell_exec", input: ["command": "ls ~/Downloads"]),+ resultStatus: .succeeded,+ summary: "listed three files"+ )++ let call = await planner.planNextStep(for: task(goal: "tidy my downloads", toolHistory: [prior]))+ #expect(call?.name == "ax.observe")++ let body = try #require(+ try JSONSerialization.jsonObject(with: Data(requestBodyString(httpClient).utf8)) as? [String: Any]+ )+ // Static doctrine lives in the cached system slot, not a user message.+ let instructions = try #require(body["instructions"] as? String)+ #expect(instructions.contains("AVAILABLE TOOLS"))+ #expect(instructions.contains("GOAL: tidy my downloads"))+ // `input` is a forward-moving thread: the prior decision as an assistant turn, its result as a+ // user turn, and the current state as the final user turn.+ let input = try #require(body["input"] as? [[String: Any]])+ let roles = input.map { $0["role"] as? String }+ #expect(roles.contains("assistant"))+ #expect(roles.last == "user")+ // The prior step's decision and result both ride in the conversation, not in the instructions.+ let conversationText = String(describing: input)+ #expect(conversationText.contains("shell_exec"))+ #expect(conversationText.contains("listed three files"))+ // The goal is NOT duplicated into a user turn — it lives in the instructions.+ #expect(!conversationText.contains("GOAL: tidy my downloads"))+ }+// MARK: - Helpersprivate func makePlanner(