Open source CapCut alternative.
TypeScript
feat(app): harden the harness for long file and form runs
David Le3731c53d96d0
diff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swiftindex fdfd45bd..c20ffd80 100644--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift@@ -278,6 +278,7 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {conversationID: genericPreparedTurn.conversation.id,agentID: genericPreparedTurn.agent.id,preparedTurnMetadata: Self.genericHarnessMetadata(preparedTurn: genericPreparedTurn),+ assets: context?.assets ?? [],visualize: context?.agentVisualizationChanged,progress: Self.progressLabeler(context?.spawnProgressChanged),answerStream: Self.answerDeltaSink(context?.spawnProgressChanged)@@ -338,6 +339,11 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {/// Task metadata keys for the drive target resolved on the first run, so a resume drives the same app.static let driveTargetAppMetadataKey = "harness.driveTargetApp"static let driveTargetBundleMetadataKey = "harness.driveTargetBundleID"+ /// Task metadata key for the turn's understanding, persisted as JSON on the run that produced it so a+ /// pure continuation of the SAME turn (gate approval, auto-resume) reuses it instead of recomputing.+ /// Recomputing on resume cost a model round-trip and could silently drift the goal, parameter keys, and+ /// chosen skills mid-task (observed: a resume re-typed `pdf_path` as `pdf_form`).+ static let understandingMetadataKey = "harness.understandingJSON"/// Shared resume path: re-run an existing task's persisted goal as a fresh loop (its stored world/// model and history carry the work forward), pinned to the target the task resolved on its first run.@@ -358,12 +364,18 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {let bundle = task.metadata[Self.driveTargetBundleMetadataKey]forcedDriveTarget = (app, (bundle?.isEmpty == false) ? bundle : nil)}+ // A resume continues the SAME turn, so reuse the understanding the first run produced rather than+ // re-deriving it from the goal text (which drifts the goal/params/skills and costs a round-trip).+ // Nil when none was persisted (an older task, or understanding was unavailable first time), in which+ // case the loop recomputes as before.+ let preresolvedUnderstanding = HarnessRequestUnderstanding.decode(task.metadata[Self.understandingMetadataKey])return await runHarnessLoop(command: task.goal,traceID: "\(tracePrefix)-\(UUID().uuidString)",conversationID: task.conversationID,agentID: task.id,preparedTurnMetadata: [:],+ preresolvedUnderstanding: preresolvedUnderstanding,forcedExecutionPreference: forcedExecutionPreference,forcedDriveTarget: forcedDriveTarget,visualize: context?.agentVisualizationChanged,@@ -445,6 +457,8 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {conversationID: String,agentID: String,preparedTurnMetadata: [String: String],+ assets: [UserQueryConversationAsset] = [],+ preresolvedUnderstanding: HarnessRequestUnderstanding? = nil,forcedExecutionPreference: ExecutionPreference? = nil,forcedDriveTarget: (appName: String, bundleIdentifier: String?)? = nil,visualize: (@MainActor @Sendable (AgentVisualizationPlan) -> Void)? = nil,@@ -495,6 +509,30 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {// traceable in the thread file. The model boundaries hold it as `any HarnessTurnTracing`.let trace = HarnessTurnTrace(transcript: transcript)+ // User-attached files (multiple supported): register the user-uploaded ones onto the conversation+ // workspace so the planner sees them — with their on-disk paths — every step and can read or act on+ // them (files.describe, image.edit, the data/pdf skills), and pass their names/types to the+ // understanding boundary so it reads the turn against them ("turn THIS into a headshot") instead of+ // misclassifying. Gated on the typed asset source, never the user's words. The record persists in+ // conversation metadata, so a later resume still sees them.+ let userAttachments = assets.filter { $0.source == .userUploaded }+ let attachmentInfos = userAttachments.map {+ HarnessAttachmentInfo(displayName: $0.displayName, contentType: $0.contentType)+ }+ if !userAttachments.isEmpty {+ let records = userAttachments.compactMap {+ asset -> (path: String, displayName: String, contentType: String, byteCount: Int?)? in+ guard let path = Self.localPath(forAssetURLString: asset.urlString) else { return nil }+ return (path, asset.displayName, asset.contentType, asset.byteCount.map(Int.init))+ }+ await genericHarnessLifecycle.coordinator.recordWorkspaceAttachments(+ conversationID: conversationID, attachments: records, at: Date()+ )+ // Project the workspace (now carrying the attachments) into the world model immediately, so the+ // planner's first step already sees them rather than waiting for the next per-step refresh.+ await genericHarnessLifecycle.coordinator.refreshWorkspaceFact(agentID: agentID)+ }+// Understand the request ONCE before the loop: restate the goal, identify the target app,// extract parameters, and decide whether to clarify. Degrades to driving the raw command when// it returns nil — or when the call outlives its deadline — so a backend hiccup never@@ -509,20 +547,40 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {// understanding and routes any converse reply through the context-aware responder below.let priorEvents = await genericHarnessLifecycle.conversationStore.events(conversationID: conversationID)let isFreshTurn = !priorEvents.contains { $0.role == .assistant }- let understanding = await AIDeadline.race(seconds: Self.understandingTimeoutSeconds) {- if isFreshTurn {- return await understandingBoundary.understandStreaming(+ // A pure continuation of the same turn (gate approval, auto-resume) arrives with the understanding+ // the first run produced and skips the boundary entirely — no second round-trip, and the goal,+ // parameters, and chosen skills stay exactly what the turn started with. Only a fresh or follow-up+ // turn (new user text) recomputes; that result is persisted below so the next resume can reuse it.+ let understanding: HarnessRequestUnderstanding?+ if let preresolvedUnderstanding {+ understanding = preresolvedUnderstanding+ transcript.systemEvent("Continuing with the original understanding (no re-derivation on resume).")+ } else {+ understanding = await AIDeadline.race(seconds: Self.understandingTimeoutSeconds) {+ if isFreshTurn {+ return await understandingBoundary.understandStreaming(+ command: command,+ frontmostAppName: frontmostAppName,+ skillCatalog: skillSelectionCatalog,+ attachments: attachmentInfos,+ onReplyDelta: answerStream ?? { _ in }+ )+ }+ return await understandingBoundary.understand(command: command,frontmostAppName: frontmostAppName,skillCatalog: skillSelectionCatalog,- onReplyDelta: answerStream ?? { _ in }+ attachments: attachmentInfos+ )+ }+ // Persist the freshly computed understanding on the root agent so a later resume of THIS turn+ // reuses it instead of re-deriving (which drifts goal/params/skills). Best-effort: a nil+ // understanding (classifier unavailable) records nothing and the resume recomputes as before.+ if let understanding, let json = understanding.encodedJSON() {+ await genericHarnessLifecycle.coordinator.recordMetadata(+ agentID: agentID, [Self.understandingMetadataKey: json])}- return await understandingBoundary.understand(- command: command,- frontmostAppName: frontmostAppName,- skillCatalog: skillSelectionCatalog- )}// TWO-TIER SPLIT. A turn the understanding boundary typed `.converse` (a greeting, a thanks, a@@ -619,10 +677,15 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {bundleIdentifier: bundleIdentifier)?.id.lowercased(): nil+ // Preload at most two authoritative guides, each at a budget that fits a full skill (several —+ // media, music, pdf, system-tools — are 5–11 KB): a guide truncated mid-section is the same+ // silent-truncation trap as a clipped file read — the planner follows half a playbook and improvises+ // the rest. Two guides at this cap is a deliberate prompt-size trade for keeping the playbook the+ // task depends on intact.let preloadedSkillGuides: [String] = (understanding?.relevantSkillIDs ?? []).filter { $0.lowercased() != appSkillID }.prefix(2)- .compactMap { BuiltInLocalAppSkillPacks.skillGuidance(forID: $0) }+ .compactMap { BuiltInLocalAppSkillPacks.skillGuidance(forID: $0, maxCharacters: 8_000) }// Drive the frontmost app through the GENERIC HARNESS LOOP: the harness re-plans after every// observation, consulting `HostedHarnessStepPlanner` (the model boundary) to pick the next@@ -660,6 +723,53 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {harnessServices.imageGenerator = { request inawait imageGenerator.generate(request)}+ // Generative text/image-to-video behind video.generate. Provider stays unset so the backend+ // routes kind=video to its configured video model (Veo); this adapter encodes any input+ // image, then submits and polls the long-running job before writing the returned clip.+ let videoGenerator = HostedVideoGenerator(backend: backend)+ harnessServices.videoGenerator = { request in+ await videoGenerator.generate(request)+ }+ // On-device, word-level transcription behind `transcribe`: Apple's SpeechAnalyzer / SFSpeech with+ // per-word time ranges. This is the precise timing the media skill cuts filler words and silence+ // against — far tighter than an llm.generate SRT — and the audio never leaves the machine.+ let speechTranscriber = AppleSpeechVoiceTranscriptionRuntime()+ harnessServices.transcriber = { request in+ do {+ let transcript = try await speechTranscriber.transcribeFile(+ at: URL(fileURLWithPath: request.filePath),+ preferredLocale: request.localeIdentifier+ .flatMap { $0.isEmpty ? nil : Locale(identifier: $0) } ?? .current+ )+ return HarnessTranscriptionResult(+ text: transcript.text,+ words: transcript.words.map {+ HarnessTranscriptionWord(+ text: $0.text,+ startMS: $0.startMS,+ endMS: $0.endMS,+ confidence: $0.confidence+ )+ },+ localeIdentifier: transcript.localeIdentifier,+ backend: transcript.backend+ )+ } catch {+ return HarnessTranscriptionResult(+ text: "",+ words: [],+ localeIdentifier: nil,+ backend: "apple",+ failureReason: String(describing: error)+ )+ }+ }+ // Deterministic filler-word / silence editor behind `media.cut`: the engine runs the bundled+ // ffmpeg over fixed cut math (MediaCutPlanner), so tightening a recording is reliable rather than+ // an ffmpeg filtergraph the planner hand-builds each time.+ harnessServices.mediaCutter = { request in+ await MediaCutEngine.run(request)+ }// Same boundary, multimodal arm: transcribe/translate/caption a local audio or video file// (the media skill extracts audio and reaches for this to subtitle a clip).harnessServices.mediaGenerator = { prompt, fileURL, mimeType in@@ -1039,6 +1149,7 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {"genericHarness.shellConsent.tier": continuation?.metadata["shell.tier"] ?? "","genericHarness.shellConsent.reason": continuation?.metadata["shell.reason"] ?? "","genericHarness.shellConsent.allowAlways": continuation?.metadata["shell.allowAlways"] ?? "",+ "genericHarness.choiceForm": continuation?.metadata["choiceForm"] ?? "","genericHarness.missingPermissions": missingPermissions]let result = UserQueryCommandHandlingResult(@@ -1584,6 +1695,14 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {)).sorted()}+ /// Resolve a stored asset's `urlString` (a `file://` URL written when the asset was copied into+ /// Application Support, or already an absolute path) to an on-disk path; nil for anything non-local.+ private static func localPath(forAssetURLString urlString: String) -> String? {+ if let url = URL(string: urlString), url.isFileURL { return url.path }+ if urlString.hasPrefix("/") { return urlString }+ return nil+ }+private static func harnessRequest(command: String,context: UserQueryCommandContext?@@ -1625,7 +1744,8 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {"genericHarness.shellConsent.command": runStep?.task.pendingContinuation?.metadata["shell.command"] ?? "","genericHarness.shellConsent.tier": runStep?.task.pendingContinuation?.metadata["shell.tier"] ?? "","genericHarness.shellConsent.reason": runStep?.task.pendingContinuation?.metadata["shell.reason"] ?? "",- "genericHarness.shellConsent.allowAlways": runStep?.task.pendingContinuation?.metadata["shell.allowAlways"] ?? ""+ "genericHarness.shellConsent.allowAlways": runStep?.task.pendingContinuation?.metadata["shell.allowAlways"] ?? "",+ "genericHarness.choiceForm": runStep?.task.pendingContinuation?.metadata["choiceForm"] ?? ""]}}diff --git a/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift b/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swiftindex 40ab9f42..98082d28 100644--- a/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift+++ b/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift@@ -105,13 +105,20 @@ public enum DonkeyPrompts {public static func requestUnderstanding(command: String,frontmostAppName: String,- skillCatalog: String? = nil+ skillCatalog: String? = nil,+ attachments: [HarnessAttachmentInfo] = []) -> String {let trimmedCatalog = skillCatalog?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""let skillsBlock = trimmedCatalog.isEmpty? "": "\nSKILLS (each is an authoritative playbook for its domain; the one(s) you name in "+ "relevantSkillIDs get loaded for the planner):\n\(trimmedCatalog)\n"+ let attachmentsBlock = attachments.isEmpty+ ? ""+ : "\nATTACHED FILES — the user attached these to THIS turn; the request is almost certainly "+ + "about them (\"this photo\", \"these\", \"it\"), so this is an \"act\" turn that operates "+ + "on these files (the planner reads/edits them at their paths):\n"+ + attachments.map { "- \($0.displayName) (\($0.contentType))" }.joined(separator: "\n") + "\n"return """You are the first step of a macOS agent. Read the user's request and return a precise, structuredunderstanding of EXACTLY what they want. You do not act or choose tools here — a separate planner@@ -120,7 +127,7 @@ public enum DonkeyPrompts {The app currently in front of the user is "\(frontmostAppName)".USER REQUEST: \(command)- \(skillsBlock)+ \(attachmentsBlock)\(skillsBlock)Fill the fields:- turnKind: what this turn fundamentally is. Decide this FIRST and let it govern everything else:- "converse": a greeting ("hi", "hey", "yo"), thanks, acknowledgement, small talk, or a@@ -158,6 +165,13 @@ public enum DonkeyPrompts {- 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.+ - plan: for an "act" turn, a SHORT ordered list (usually 3–6 items) of the real steps to the+ deliverable — what an expert would actually do, end to end, INCLUDING the hard part. Name the+ decisive step explicitly so the planner aims at it instead of circling acquisition: e.g. filling+ an official form is "read the data → list the form's fields → MAP fields to the data and COMPUTE+ the derived values (the hard step) → write the filled file → verify", not just "open the form".+ One imperative phrase per step; mark the hard/decisive ones (a mapping, a calculation, a+ transform). Leave empty for a trivial one-step task and for "converse"/"clarify".- needsClarification: set true exactly when turnKind is "clarify" — the request is genuinelyambiguous or missing detail that you cannot reasonably resolve, or it is destructive without aclear target. Always false for "converse" and for an under-specified but low-risk, reversible@@ -240,6 +254,27 @@ public enum DonkeyPrompts {/// until the run stalled. The planner can always re-read specifics; this only bounds the recap.public static let harnessStepSummaryMaxLength = 600+ /// The MOST RECENT step's result is the observation the planner acts on right now, so it is rendered+ /// at the full capture budget instead of the 600-char recap cap. Clipping the just-produced result+ /// below what the tool actually captured made a complete small read (e.g. a 1.2 KB text file read with+ /// `cat`) look truncated: the planner saw "…[truncated]", concluded it hadn't seen the whole file, and+ /// looped re-reading it (`cat | cat`, then `python3 …`) — every re-read re-clipped, so it never escaped.+ /// Matching the shell-output capture cap means a read that fit in the capture is shown in full; older+ /// results still collapse to `harnessStepSummaryMaxLength`.+ public static let harnessLatestResultMaxLength = 4_000++ /// The marker appended when a tool result is shortened FOR THE PROMPT (context-window trimming), with+ /// the full size named. This is deliberately not the word "truncated": a bare "…[truncated]" reads+ /// identically whether the harness shortened its own view or the source DATA is partial, and a real run+ /// conflated the two — it saw the marker on a fully-captured 1.2 KB file, decided the file was partial,+ /// and re-read it (cat → python3) into a permission gate. Naming the cause and the full byte count, and+ /// stating that re-reading won't restore it, stops that category error. The full result stays in the+ /// run record; only this rendered view is shortened.+ public static func contextTrimNotice(fullCharacterCount count: Int) -> String {+ " …[context-trimmed for prompt; full output was \(count) chars and is already captured — "+ + "re-running the read will NOT lengthen this view]"+ }+/// 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@@ -264,8 +299,15 @@ public enum DonkeyPrompts {or personal data; a restatement of the goal; or generic advice this run did not actually teach. Ifthe run went smoothly and taught nothing new, return an empty lesson — that is the common case.+ NEVER save a lesson about working around the harness's own guardrails. If the run hit an+ "already done / you already have this" guard, a stall/no-progress stop, or a permission gate, the+ lesson is NOT how to slip past it (perturbing the command, repeating to evade the check) — that is+ backwards and harmful. The guard means the run was looping or needed consent; the lesson, if any, is+ to advance, verify, or ask. Prefer an empty lesson; and if the only lesson you can draw would teach+ slipping past such a guard, set "unsafe": true so it is discarded.+Return STRICT JSON and nothing else:- {"lesson": "<one imperative sentence, or empty string if nothing is worth saving>", "cue": "<short phrase naming the kind of task this applies to>", "confidence": <0.0-1.0>}+ {"lesson": "<one imperative sentence, or empty string if nothing is worth saving>", "cue": "<short phrase naming the kind of task this applies to>", "confidence": <0.0-1.0>, "unsafe": <true only if the lesson teaches defeating a harness guardrail, else false>}THREAD:\(thread)@@ -351,6 +393,37 @@ public enum DonkeyPrompts {: "\nLESSONS FROM PAST RUNS (hard-won operating knowledge from earlier tasks — apply when "+ "relevant; they reflect what worked or failed before):\n\(trimmedLessons)\n"+ // GUI-operation craft only earns its place when the turn actually drives an app's interface. The+ // understanding boundary types that as actionSurface, so on an appless turn (the deliverable is a+ // file, answer, or system change) the full cluster below is dead weight on every cached step.+ // Collapse it to a one-line fallback pointer there; the elements block still names the SEE tools if+ // a step unexpectedly needs the GUI. guiApp — and the safe default when no understanding was+ // produced — gets the full craft.+ let drivesGUI = understanding?.actionSurface != .appless+ let guiOperationGuidance = drivesGUI ? """+ - Only operate the GUI when the task genuinely needs it (canvas/Electron/proprietary UI, or no+ system-tool equivalent). When you do: SEE before you act — prefer ax.observe (fast,+ structured) for native apps; use vision.capture when Accessibility is missing or insufficient+ — then act on a specific element by passing its id from the list above in "input". The see/act+ tools focus the target app for you, so do NOT `open -a`/activate it first as a prerequisite —+ go straight to ax.observe. Re-issuing a focus/open step instead of advancing is a loop that+ burns the run.+ - The action you need may not be a visible button. Figure it out like a person would, using the+ general actions: RIGHT-CLICK an item (ax.click/vision.click button=right) to open its full+ context menu — that is where Delete / Remove / Rename / "…from Library" usually live; or+ select/open the item first and use its focused "⋯" / "More" / gear OVERFLOW menu; mouse.scroll+ to bring offscreen items or controls into view; use the menu bar; or select an item and press+ the matching key. After any of these, SEE again and read the+ WHOLE menu before clicking — a context menu, popup, or confirmation dialog is just more+ elements to observe, and the right entry is often a small labeled row near the bottom of a long+ menu. Don't conclude something is impossible until you've tried these; only report it+ unsupported if a skill says so or the paths are exhausted.+ """ : """+ - This turn's deliverable is a file, answer, or system change, not an app's UI — stay in system,+ web, and generative tools. Only if a step genuinely needs the GUI, SEE first (ax.observe, or+ vision.capture when Accessibility is thin) and act on an element by its id.+ """+return """You are an expert macOS power user. Choose ONE tool to run next, then you will see the resultand choose again. Work toward the goal in small, verifiable steps. Many tasks are solved@@ -380,23 +453,7 @@ public enum DonkeyPrompts {found`, adapt: reach for another tool that does the job, or — if the task genuinely needsthat one — report what's missing. Never install software or use a package manager (pip,brew, npm, etc.); a missing tool is reported, not fetched.- - Only operate the GUI when the task genuinely needs it (canvas/Electron/proprietary UI, or no- system-tool equivalent). When you do: SEE before you act — prefer ax.observe (fast,- structured) for native apps; use vision.capture when Accessibility is missing or insufficient- — then act on a specific element by passing its id from the list above in "input". The see/act- tools focus the target app for you, so do NOT `open -a`/activate it first as a prerequisite —- go straight to ax.observe. Re-issuing a focus/open step instead of advancing is a loop that- burns the run.- - The action you need may not be a visible button. Figure it out like a person would, using the- general actions: RIGHT-CLICK an item (ax.click/vision.click button=right) to open its full- context menu — that is where Delete / Remove / Rename / "…from Library" usually live; or- select/open the item first and use its focused "⋯" / "More" / gear OVERFLOW menu; mouse.scroll- to bring offscreen items or controls into view; use the menu bar; or select an item and press- the matching key. After any of these, SEE again and read the- WHOLE menu before clicking — a context menu, popup, or confirmation dialog is just more- elements to observe, and the right entry is often a small labeled row near the bottom of a long- menu. Don't conclude something is impossible until you've tried these; only report it- unsupported if a skill says so or the paths are exhausted.+ \(guiOperationGuidance)- Operating a specific app — even by script (playing music, saving a note, sending mail)? If itappears in INSTALLED APP SKILLS above, consult that skill FIRST (app_skill) and run itsvalidated scripts (skill_run) before hand-writing osascript: the skill is the authority and@@ -409,6 +466,12 @@ public enum DonkeyPrompts {thing: a better query, a different tool or layer, activating the app, a more specificelement. Never re-run the same tool with the same input, and after one or two informedretries stop and report the blocker instead of trying a third variation.+ - An "already done / you already have this result" reply is a LOOP signal, not an obstacle. It+ means the output is already in your context — read it and take the NEXT action toward the goal.+ Do NOT perturb the command (whitespace, a dummy comment, piping to cat, a fresh interpreter) to+ get past the guard; that is how a finished read becomes a permission gate. Same for a context+ marker like "[context-trimmed; full output already captured]" — the data is complete, your view+ of it was shortened; re-reading cannot lengthen it, so proceed with what you have.- Need a current fact you can't be sure of (an artist's latest album, today's news, a price, anaddress)? Use web.search to find it and web.fetch to read a result in full — don't guess anddon't drive a browser GUI for this. Never write factual or creative material (a tracklist,@@ -417,6 +480,15 @@ public enum DonkeyPrompts {which kills the step. To build a long note/document, generate it with llm.generate (or fetchit) using toFile=true, then assemble the note from the returned file — never refuse a taskas "too long".+ - Keep a conversation's files together. The `workspace` line under Known state is what you've+ already produced and where (the filesystem is truth — `ls` to reconcile); reuse it on+ follow-ups, never re-create it. Save where the user named; otherwise pick a sensible base+ (~/Downloads, ~/Desktop, ~/Documents). One file stays loose there; when a SECOND related file+ appears, mkdir a clearly-named folder and mv the earlier one(s) in (a visible step) before+ writing more. A task that is multi-file from the start (an app, a site) gets its folder up front.+ Intermediate and produced files (a `fields.json` dump, a generated PDF, a copied input) belong in+ the workspace folder, never loose in your home directory. And don't COPY a found input next to+ yourself just to shorten a path — read and write it where it already lives, by absolute path.- If the request is a question or chit-chat rather than an action, answer withconversation.respond (set input.response), then run.complete.- If a required detail is missing and you cannot safely proceed, use user.clarify@@ -470,10 +542,10 @@ public enum DonkeyPrompts {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 }+ // Follow-up instructions the user added after the task started get their own block below, and the+ // machine-readable workspace base dir is executor-only — both are hidden from this generic facts+ // dump centrally via `modelFacingFacts`.+ let displayFacts = task.worldModel.modelFacingFactslet factsBlock = displayFacts.isEmpty? "": "\nKnown state:\n" + displayFacts.sorted { $0.key < $1.key }@@ -648,9 +720,12 @@ public enum DonkeyPrompts {.joined(separator: "; ")lines.append(" Earlier steps 1-\(evicted.count) (condensed): \(condensed)")}- lines += recent.map { record in- let summary = record.summary.count > harnessStepSummaryMaxLength- ? String(record.summary.prefix(harnessStepSummaryMaxLength)) + " …[truncated]"+ lines += recent.enumerated().map { index, record in+ // The last recent record is the result the planner is acting on this step — show it in full+ // so a complete small read never reads as truncated and sends the planner re-reading in a loop.+ let cap = index == recent.count - 1 ? harnessLatestResultMaxLength : harnessStepSummaryMaxLength+ let summary = record.summary.count > cap+ ? String(record.summary.prefix(cap)) + contextTrimNotice(fullCharacterCount: record.summary.count): record.summaryreturn " \(record.call.name): \(summary)"}@@ -675,6 +750,15 @@ public enum DonkeyPrompts {if let criteria = understanding.successCriteria, !criteria.isEmpty {lines.append(" Success when: \(criteria)")}+ if !understanding.plan.isEmpty {+ // The up-front plan, shown every step so the planner works toward the decisive step instead of+ // re-deriving the task shape and circling acquisition. Advisory — the planner still picks each+ // tool — but it is the agreed route; don't get stuck on step 1 when the point is step 3.+ let steps = understanding.plan.enumerated()+ .map { " \($0.offset + 1). \($0.element)" }+ .joined(separator: "\n")+ lines.append(" Plan (the route to the deliverable — aim at the decisive step, don't circle the easy ones):\n\(steps)")+ }guard !lines.isEmpty else { return "" }return "WHAT THE USER WANTS:\n" + lines.joined(separator: "\n") + "\n"}diff --git a/apps/Donkey/Sources/DonkeyAI/HostedHarnessRequestUnderstanding.swift b/apps/Donkey/Sources/DonkeyAI/HostedHarnessRequestUnderstanding.swiftindex 9d99f394..e64c23da 100644--- a/apps/Donkey/Sources/DonkeyAI/HostedHarnessRequestUnderstanding.swift+++ b/apps/Donkey/Sources/DonkeyAI/HostedHarnessRequestUnderstanding.swift@@ -8,7 +8,7 @@ import Foundation/// criteria, and a clarify gate. The per-step `HostedHarnessStepPlanner` still chooses every tool —/// this only sharpens what "the goal" means and which app to drive, so the planner stops re-deriving/// intent from a raw string on every step.-public struct HarnessRequestUnderstanding: Sendable, Equatable {+public struct HarnessRequestUnderstanding: Sendable, Equatable, Codable {/// What this turn fundamentally is: a conversation, an action on the Mac, or a clarifying question./// Decided here, before any action machinery exists, and the single fact the caller routes on —/// only `.act` ever reaches the action planner. A `.converse` turn is answered by a responder that@@ -31,6 +31,12 @@ public struct HarnessRequestUnderstanding: Sendable, Equatable {public var parameters: [String: String]/// What, observable on screen, would mean the goal is done.public var successCriteria: String?+ /// A short ordered plan for an `.act` turn — the few real steps to the deliverable, named up front so+ /// the planner works toward the point instead of re-deriving the shape each step and circling the easy+ /// parts. Each step is one imperative phrase; the hard/decisive ones (a mapping, a computation) are+ /// flagged in the text. Empty for `.converse`/`.clarify` and for trivial one-step tasks. Advisory, not+ /// harness-tracked: the planner still chooses each tool and the done-gate enforces real progress.+ public var plan: [String]/// True only when the request is genuinely ambiguous or missing critical detail and cannot be/// safely resolved with reasonable defaults.public var needsClarification: Bool@@ -60,6 +66,7 @@ public struct HarnessRequestUnderstanding: Sendable, Equatable {actionSurface: HarnessActionSurface = .guiApp,parameters: [String: String] = [:],successCriteria: String? = nil,+ plan: [String] = [],needsClarification: Bool = false,clarifyingQuestion: String? = nil,executionPreference: ExecutionPreference = .background,@@ -72,12 +79,28 @@ public struct HarnessRequestUnderstanding: Sendable, Equatable {self.actionSurface = actionSurfaceself.parameters = parametersself.successCriteria = successCriteria+ self.plan = planself.needsClarification = needsClarificationself.clarifyingQuestion = clarifyingQuestionself.executionPreference = executionPreferenceself.relevantSkillIDs = relevantSkillIDsself.conversationReply = conversationReply}++ /// Serialize to a compact JSON string for persistence (e.g. the root agent's metadata), so a later+ /// continuation of the SAME turn — a permission-gate approval or an unattended auto-resume — can reuse+ /// the original understanding instead of recomputing it. Returns nil only if encoding fails.+ public func encodedJSON() -> String? {+ guard let data = try? JSONEncoder().encode(self) else { return nil }+ return String(data: data, encoding: .utf8)+ }++ /// Decode a persisted understanding produced by `encodedJSON()`. Returns nil for a nil/empty/garbled+ /// value, so a missing or stale record falls back to recomputing rather than crashing.+ public static func decode(_ json: String?) -> HarnessRequestUnderstanding? {+ guard let json, !json.isEmpty, let data = json.data(using: .utf8) else { return nil }+ return try? JSONDecoder().decode(HarnessRequestUnderstanding.self, from: data)+ }}/// Makes the single hosted call that produces a `HarnessRequestUnderstanding`. Mirrors the request /@@ -107,18 +130,25 @@ public final class HostedHarnessRequestUnderstanding {public func understand(command: String,frontmostAppName: String,- skillCatalog: String? = nil+ skillCatalog: String? = nil,+ attachments: [HarnessAttachmentInfo] = []) async -> HarnessRequestUnderstanding? {let prompt = DonkeyPrompts.requestUnderstanding(command: command,frontmostAppName: frontmostAppName,- skillCatalog: skillCatalog+ skillCatalog: skillCatalog,+ attachments: attachments)for _ in 0..<Self.maxAttempts {let startedAt = RunTraceTimestamp.now()do {let response = try await backend.createResponse(- responseRequest(command: command, frontmostAppName: frontmostAppName, skillCatalog: skillCatalog)+ responseRequest(+ command: command,+ frontmostAppName: frontmostAppName,+ skillCatalog: skillCatalog,+ attachments: attachments+ ))let endedAt = RunTraceTimestamp.now()let finishReason = RemoteInferenceResponseHelpers.providerFinishReason(from: response)@@ -167,12 +197,14 @@ public final class HostedHarnessRequestUnderstanding {command: String,frontmostAppName: String,skillCatalog: String? = nil,+ attachments: [HarnessAttachmentInfo] = [],onReplyDelta: @escaping @MainActor @Sendable (String) -> Void) async -> HarnessRequestUnderstanding? {let prompt = DonkeyPrompts.requestUnderstanding(command: command,frontmostAppName: frontmostAppName,- skillCatalog: skillCatalog+ skillCatalog: skillCatalog,+ attachments: attachments)let startedAt = RunTraceTimestamp.now()let streamer = ReplyFieldStreamer()@@ -226,6 +258,9 @@ public final class HostedHarnessRequestUnderstanding {actionSurface: wire.actionSurface.flatMap { HarnessActionSurface(rawValue: $0) } ?? .guiApp,parameters: wire.parameters ?? [:],successCriteria: wire.successCriteria.flatMap { $0.isEmpty ? nil : $0 },+ plan: (wire.plan ?? [])+ .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }+ .filter { !$0.isEmpty },needsClarification: wire.needsClarification ?? false,clarifyingQuestion: wire.clarifyingQuestion.flatMap { $0.isEmpty ? nil : $0 },executionPreference: wire.executionPreference@@ -267,6 +302,7 @@ public final class HostedHarnessRequestUnderstanding {var actionSurface: String?var parameters: [String: String]?var successCriteria: String?+ var plan: [String]?var needsClarification: Bool?var clarifyingQuestion: String?var executionPreference: String?@@ -274,7 +310,7 @@ public final class HostedHarnessRequestUnderstanding {var conversationReply: String?private enum CodingKeys: String, CodingKey {- case turnKind, restatedGoal, targetAppName, actionSurface, parameters, successCriteria, needsClarification, clarifyingQuestion+ case turnKind, restatedGoal, targetAppName, actionSurface, parameters, successCriteria, plan, needsClarification, clarifyingQuestioncase executionPreference, relevantSkillIDs, conversationReply}@@ -285,6 +321,7 @@ public final class HostedHarnessRequestUnderstanding {targetAppName = try container.decodeIfPresent(String.self, forKey: .targetAppName)actionSurface = try container.decodeIfPresent(String.self, forKey: .actionSurface)successCriteria = try container.decodeIfPresent(String.self, forKey: .successCriteria)+ plan = try container.decodeIfPresent([String].self, forKey: .plan)clarifyingQuestion = try container.decodeIfPresent(String.self, forKey: .clarifyingQuestion)needsClarification = try container.decodeIfPresent(Bool.self, forKey: .needsClarification)executionPreference = try container.decodeIfPresent(String.self, forKey: .executionPreference)@@ -325,7 +362,8 @@ public final class HostedHarnessRequestUnderstanding {private func responseRequest(command: String,frontmostAppName: String,- skillCatalog: String?+ skillCatalog: String?,+ attachments: [HarnessAttachmentInfo] = []) -> RemoteInferenceResponseCreateRequest {RemoteInferenceResponseCreateRequest(input: .array([@@ -337,7 +375,8 @@ public final class HostedHarnessRequestUnderstanding {"text": .string(DonkeyPrompts.requestUnderstanding(command: command,frontmostAppName: frontmostAppName,- skillCatalog: skillCatalog+ skillCatalog: skillCatalog,+ attachments: attachments))])])@@ -369,6 +408,10 @@ public final class HostedHarnessRequestUnderstanding {"additionalProperties": .object(["type": .string("string")])]),"successCriteria": .object(["type": .string("string")]),+ "plan": .object([+ "type": .string("array"),+ "items": .object(["type": .string("string")])+ ]),"needsClarification": .object(["type": .string("boolean")]),"clarifyingQuestion": .object(["type": .string("string")]),"executionPreference": .object([diff --git a/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift b/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swiftindex c2218ec5..7b4f6a89 100644--- a/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift+++ b/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift@@ -157,13 +157,23 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {retryNote = Self.retryNote(after: error)continue}- lastNarration = decision.narration.flatMap { $0.isEmpty ? nil : $0 } ?? lastNarration+ // This step's narration only — never inherit the previous step's line. A reply that omits+ // narration used to fall back to `lastNarration`, which pinned one step's account onto later,+ // unrelated steps (observed: "I will load the PDF skill" shown for the file-search and+ // field-listing steps that followed it). Resolve it per step and, when the model gives none,+ // synthesize a line from the chosen tool so the pointer still updates every step — accurately,+ // without misattribution. Assigned to `lastNarration` only on the path that actually returns a+ // call, so a retried attempt can't leave a stale line behind.+ let stepNarration = decision.narration.flatMap {+ $0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? nil : $0+ }lastThinking = decision.thinking.flatMap { $0.isEmpty ? nil : $0 }guard let toolName = decision.tool.flatMap({ $0.isEmpty ? nil : $0 }) else {lastPlanningErrors.append("planning attempt \(attempt + 1)/\(Self.maxPlanAttempts): reply named no tool")guard attempt < lastAttempt else {+ lastNarration = stepNarration ?? "I couldn't settle on a next step, so I stopped."return HarnessToolCall(name: "run.failSafe", input: ["reason": "plannerReturnedNoTool"])}retryNote = "Your previous reply named no tool. Pick exactly one tool from AVAILABLE TOOLS; "@@ -218,11 +228,28 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {if !readOnlyToolNames.contains(toolName), firstActionUptimeMS == nil {firstActionUptimeMS = uptimeMS()}+ lastNarration = stepNarration ?? Self.fallbackNarration(tool: toolName, input: providedInput)return HarnessToolCall(name: toolName, input: providedInput)}return failSafeCall(after: lastFailure)}+ /// A neutral one-line account synthesized for a step whose reply carried no narration, so the live+ /// pointer still updates for THIS step instead of repeating the previous step's line. Derived from the+ /// step's own tool call, never from prior narration: for `shell_exec` the command itself is the most+ /// informative and keeps consecutive steps distinct; everything else names the tool. Kept short so it+ /// reads cleanly in the notch.+ static func fallbackNarration(tool: String, input: [String: String]) -> String {+ if tool == "shell_exec",+ let command = input["command"]?.trimmingCharacters(in: .whitespacesAndNewlines),+ !command.isEmpty {+ let firstLine = command.split(whereSeparator: \.isNewline).first.map(String.init) ?? command+ let clipped = firstLine.count > 80 ? String(firstLine.prefix(80)) + "…" : firstLine+ return "Running `\(clipped)`."+ }+ return "Running `\(tool)`."+ }+/// The corrective note fed back on the next attempt. A content-filter block gets a/// strategy-changing note — the filter is deterministic on the content, so re-asking for the same/// reply verbatim just re-trips it; the model must obtain the content as data instead of writing@@ -596,9 +623,14 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {if !evicted.isEmpty {turns.append(Turn(role: "user", text: DonkeyPrompts.harnessStepCondensedHistoryLine(evicted)))}- for record in recent {+ for (index, record) in recent.enumerated() {turns.append(Turn(role: "assistant", text: renderDecision(record.call)))- turns.append(Turn(role: "user", text: renderResult(record)))+ // The final recent record is the observation this step plans against — render it at the full+ // capture budget so a complete small read isn't shown as "…[truncated]" and re-read in a loop.+ let cap = index == recent.count - 1+ ? DonkeyPrompts.harnessLatestResultMaxLength+ : DonkeyPrompts.harnessStepSummaryMaxLength+ turns.append(Turn(role: "user", text: renderResult(record, maxSummaryLength: cap)))}turns.append(Turn(role: "user", text: currentState))return turns@@ -617,9 +649,13 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {/// 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]"+ private static func renderResult(+ _ record: HarnessToolCallRecord,+ maxSummaryLength: Int = DonkeyPrompts.harnessStepSummaryMaxLength+ ) -> String {+ let summary = record.summary.count > maxSummaryLength+ ? String(record.summary.prefix(maxSummaryLength))+ + DonkeyPrompts.contextTrimNotice(fullCharacterCount: record.summary.count): record.summaryreturn "Result of \(record.call.name) [\(record.resultStatus.rawValue)]: \(summary)"}diff --git a/apps/Donkey/Sources/DonkeyAI/VisionComputerUseTools.swift b/apps/Donkey/Sources/DonkeyAI/VisionComputerUseTools.swiftindex 653706f8..321029fb 100644--- a/apps/Donkey/Sources/DonkeyAI/VisionComputerUseTools.swift+++ b/apps/Donkey/Sources/DonkeyAI/VisionComputerUseTools.swift@@ -102,7 +102,10 @@ public final class VisionComputerUseToolProvider {outputSchema: ["elements": "Detected element IDs, labels, roles, and click eligibility."],requiredPermissions: [.screenCapture],safetyClass: .readOnly,- verificationHints: ["fresh capture reflects the current on-screen state"]+ verificationHints: ["fresh capture reflects the current on-screen state"],+ // A screen capture reflects live state, so the run's read cache must never serve a prior+ // capture — re-capturing is the point of calling it again.+ metadata: [HarnessToolDescriptor.volatileResultMetadataKey: "true"]),HarnessToolDescriptor(name: ToolName.click,diff --git a/apps/Donkey/Sources/DonkeyContracts/HarnessAttachmentInfo.swift b/apps/Donkey/Sources/DonkeyContracts/HarnessAttachmentInfo.swiftnew file mode 100644index 00000000..237e29af--- /dev/null+++ b/apps/Donkey/Sources/DonkeyContracts/HarnessAttachmentInfo.swift@@ -0,0 +1,16 @@+import Foundation++/// A file the user attached to their turn, described for the understanding boundary so the turn is read+/// against it ("turn THIS into a headshot", "summarize THESE") instead of being misclassified. Only the+/// name and type travel here — never the bytes — because the planner reads or acts on the file at its+/// path through general tools (`files.describe`, `image.edit`, the data/pdf skills). Several attachments+/// at once are normal; this is one entry per file.+public struct HarnessAttachmentInfo: Sendable, Equatable {+ public var displayName: String+ public var contentType: String++ public init(displayName: String, contentType: String) {+ self.displayName = displayName+ self.contentType = contentType+ }+}diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swiftindex f3db417f..e9d06f67 100644--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift@@ -228,17 +228,22 @@ public struct HarnessImageGenerationRequest: Sendable {public var inputImagePaths: [String]public var model: String?public var outputDirectory: String?+ /// The conversation workspace folder, when one exists. Used as the default output base so a generated+ /// image lands beside the turn's other deliverables instead of in ~/Downloads.+ public var workspaceBaseDir: String?public init(prompt: String,inputImagePaths: [String] = [],model: String? = nil,- outputDirectory: String? = nil+ outputDirectory: String? = nil,+ workspaceBaseDir: String? = nil) {self.prompt = promptself.inputImagePaths = inputImagePathsself.model = modelself.outputDirectory = outputDirectory+ self.workspaceBaseDir = workspaceBaseDir}}@@ -254,6 +259,176 @@ public struct HarnessImageGenerationResult: Sendable {}}+public struct HarnessVideoGenerationRequest: Sendable {+ public var prompt: String+ /// Optional first-frame image to animate (image-to-video). Empty for plain text-to-video.+ public var inputImagePaths: [String]+ public var model: String?+ public var outputDirectory: String?+ /// Optional speed/quality tier (e.g. "fast", "standard", "high") the user picked. The backend maps it+ /// to its configured per-tier video model; nil uses the default model.+ public var tier: String?+ /// Whether to generate audio with the video. nil uses the backend default (on).+ public var audio: Bool?+ /// Veo knobs the planner may set; nil leaves the model/back-end default in place.+ public var aspectRatio: String?+ public var durationSeconds: Int?+ public var negativePrompt: String?+ /// The conversation workspace folder, when one exists. Used as the default output base so a generated+ /// clip lands beside the turn's other deliverables instead of in ~/Downloads.+ public var workspaceBaseDir: String?++ public init(+ prompt: String,+ inputImagePaths: [String] = [],+ model: String? = nil,+ outputDirectory: String? = nil,+ tier: String? = nil,+ audio: Bool? = nil,+ aspectRatio: String? = nil,+ durationSeconds: Int? = nil,+ negativePrompt: String? = nil,+ workspaceBaseDir: String? = nil+ ) {+ self.prompt = prompt+ self.inputImagePaths = inputImagePaths+ self.model = model+ self.outputDirectory = outputDirectory+ self.tier = tier+ self.audio = audio+ self.aspectRatio = aspectRatio+ self.durationSeconds = durationSeconds+ self.negativePrompt = negativePrompt+ self.workspaceBaseDir = workspaceBaseDir+ }+}++public struct HarnessVideoGenerationResult: Sendable {+ public var savedPaths: [String]+ /// Set when no video was produced — the provider/model's reason, surfaced to the planner so it+ /// can adjust rather than being told a flat "no video, do not retry".+ public var failureReason: String?++ public init(savedPaths: [String], failureReason: String? = nil) {+ self.savedPaths = savedPaths+ self.failureReason = failureReason+ }+}++/// One spoken word with its on-device-measured time span. The precise per-word boundary the planner+/// needs to cut filler words or silence, or to find an exact spoken moment — accurate to tens of+/// milliseconds, far tighter than a model-authored SRT.+public struct HarnessTranscriptionWord: Sendable {+ public var text: String+ public var startMS: Int+ public var endMS: Int+ public var confidence: Double++ public init(text: String, startMS: Int, endMS: Int, confidence: Double = 1) {+ self.text = text+ self.startMS = startMS+ self.endMS = endMS+ self.confidence = confidence+ }+}++/// Request for `transcribe`: a local audio (or directly-readable) file to transcribe on-device, with+/// an optional BCP-47 locale override. The runtime supplies the backend; without it the tool reports+/// unavailable.+public struct HarnessTranscriptionRequest: Sendable {+ public var filePath: String+ public var localeIdentifier: String?++ public init(filePath: String, localeIdentifier: String? = nil) {+ self.filePath = filePath+ self.localeIdentifier = localeIdentifier+ }+}++/// Result of an on-device transcription: the plain transcript plus per-word timings. `failureReason`+/// is set (with empty words/text) when the file could not be transcribed — surfaced so the planner+/// can adjust (e.g. extract compact audio first) instead of being told a flat "no transcript".+public struct HarnessTranscriptionResult: Sendable {+ public var text: String+ public var words: [HarnessTranscriptionWord]+ public var localeIdentifier: String?+ public var backend: String+ public var failureReason: String?++ public init(+ text: String,+ words: [HarnessTranscriptionWord],+ localeIdentifier: String? = nil,+ backend: String,+ failureReason: String? = nil+ ) {+ self.text = text+ self.words = words+ self.localeIdentifier = localeIdentifier+ self.backend = backend+ self.failureReason = failureReason+ }+}++/// Request for `media.cut`: a deterministic editor that removes spans from a media file and rejoins the+/// kept parts frame-accurate (the Descript/auto-editor approach, in code, not composed by the model).+/// Removals come from any combination of filler words (matched in the `transcribe` JSON at+/// `transcriptPath`), detected silence, and explicit caller-judged spans.+public struct HarnessMediaCutRequest: Sendable {+ public var inputPath: String+ public var outputPath: String?+ public var removeFillers: Bool+ public var removeSilence: Bool+ public var transcriptPath: String?+ /// Lexicon override for filler matching; empty uses the engine's default unambiguous set.+ public var fillerWords: [String]+ /// Caller-judged removal spans as `"start-end,start-end"` seconds (e.g. a discourse "like").+ public var explicitRemovals: String?++ public init(+ inputPath: String,+ outputPath: String? = nil,+ removeFillers: Bool = false,+ removeSilence: Bool = false,+ transcriptPath: String? = nil,+ fillerWords: [String] = [],+ explicitRemovals: String? = nil+ ) {+ self.inputPath = inputPath+ self.outputPath = outputPath+ self.removeFillers = removeFillers+ self.removeSilence = removeSilence+ self.transcriptPath = transcriptPath+ self.fillerWords = fillerWords+ self.explicitRemovals = explicitRemovals+ }+}++/// Result of a `media.cut`: the written file, how many spans were cut, and the before/after durations so+/// the planner can verify the edit landed. `failureReason` is set (with no usable output) when the cut+/// could not be produced. `removedSpanCount == 0` is a clean outcome (nothing matched), not a failure.+public struct HarnessMediaCutResult: Sendable {+ public var outputPath: String+ public var removedSpanCount: Int+ public var inputDurationSec: Double+ public var outputDurationSec: Double+ public var failureReason: String?++ public init(+ outputPath: String,+ removedSpanCount: Int,+ inputDurationSec: Double,+ outputDurationSec: Double,+ failureReason: String? = nil+ ) {+ self.outputPath = outputPath+ self.removedSpanCount = removedSpanCount+ self.inputDurationSec = inputDurationSec+ self.outputDurationSec = outputDurationSec+ self.failureReason = failureReason+ }+}+/// The typed request for the `web.automate` hosted tool: a natural-language task,/// an optional starting URL, and an optional JSON-schema string for structured/// output. Declared in DonkeyHarness so the executor can pass it across the@@ -357,6 +532,19 @@ public struct HarnessBuiltInToolServices: Sendable {/// the saved output file paths out (or nil on failure). The runtime supplies an adapter that/// routes through the hosted asset API to an image model; without it the tools report unavailable.public var imageGenerator: (@Sendable (HarnessImageGenerationRequest) async -> HarnessImageGenerationResult?)?+ /// Generative text/image-to-video behind `video.generate`: a request in, the saved output file+ /// paths out (or nil on failure). The runtime supplies an adapter that routes through the hosted+ /// asset API to a video model (Veo); without it the tool reports unavailable. Video generation is+ /// a long-running job, so the adapter submits and polls behind this single call.+ public var videoGenerator: (@Sendable (HarnessVideoGenerationRequest) async -> HarnessVideoGenerationResult?)?+ /// On-device, word-level transcription behind `transcribe`: a media file in, the transcript with+ /// per-word timings out (or nil when no backend is wired). The runtime supplies an Apple+ /// speech-to-text adapter; audio never leaves the machine.+ public var transcriber: (@Sendable (HarnessTranscriptionRequest) async -> HarnessTranscriptionResult?)?+ /// Deterministic filler-word/silence editor behind `media.cut`: a request in, the written cut out (or+ /// nil when no backend is wired). The runtime supplies an engine that runs the bundled ffmpeg; the cut+ /// math is fixed code, not composed by the model.+ public var mediaCutter: (@Sendable (HarnessMediaCutRequest) async -> HarnessMediaCutResult?)?public init(memoryEntries: [HarnessMemoryEntry] = [],@@ -377,7 +565,10 @@ public struct HarnessBuiltInToolServices: Sendable {webFetcher: (@Sendable (String) async -> String?)? = nil,webAutomator: (@Sendable (HarnessWebAutomateRequest) async -> HarnessWebAutomateOutcome)? = nil,fileUnderstanding: (@Sendable (URL) async -> FileUnderstanding?)? = nil,- imageGenerator: (@Sendable (HarnessImageGenerationRequest) async -> HarnessImageGenerationResult?)? = nil+ imageGenerator: (@Sendable (HarnessImageGenerationRequest) async -> HarnessImageGenerationResult?)? = nil,+ videoGenerator: (@Sendable (HarnessVideoGenerationRequest) async -> HarnessVideoGenerationResult?)? = nil,+ transcriber: (@Sendable (HarnessTranscriptionRequest) async -> HarnessTranscriptionResult?)? = nil,+ mediaCutter: (@Sendable (HarnessMediaCutRequest) async -> HarnessMediaCutResult?)? = nil) {self.memoryEntries = memoryEntriesself.skillRegistry = skillRegistry@@ -398,6 +589,9 @@ public struct HarnessBuiltInToolServices: Sendable {self.webAutomator = webAutomatorself.fileUnderstanding = fileUnderstandingself.imageGenerator = imageGenerator+ self.videoGenerator = videoGenerator+ self.transcriber = transcriber+ self.mediaCutter = mediaCutter}}@@ -424,6 +618,8 @@ public enum BuiltInHarnessToolExecutors {return conversationRespond(context)case "user.clarify":return userClarify(context)+ case "user.choose":+ return userChoose(context)case "permission.request":return permissionRequest(context)case "memory.retrieve":@@ -484,6 +680,12 @@ public enum BuiltInHarnessToolExecutors {return await imageGenerate(context, services: services, requiresInput: true)case "image.generate":return await imageGenerate(context, services: services, requiresInput: false)+ case "video.generate":+ return await videoGenerate(context, services: services)+ case "transcribe":+ return await transcribe(context, services: services)+ case "media.cut":+ return await mediaCut(context, services: services)case "wait":return await timingWait(context)case "run.pause", "run.resume", "run.recover", "run.cancel", "run.complete", "run.failSafe":@@ -530,6 +732,31 @@ public enum BuiltInHarnessToolExecutors {)}+ /// Surfaces a generative options form (buttons / dropdowns / toggles) and stops the task until the+ /// user submits their choices. The form arrives as JSON in `form`; it's re-serialized into the gate+ /// metadata so the notch can render it, and the title becomes the plain-text fallback question. On+ /// submit the selection comes back as the user's clarification answer ("Selected options: …"), which+ /// the planner reads to make its next call. A malformed/empty form falls back to a plain clarify.+ private static func userChoose(_ context: HarnessToolExecutionContext) -> HarnessToolResult {+ guard let formJSON = trimmed(context.call.input["form"]),+ let form = HarnessChoiceForm.decode(fromJSON: formJSON),+ let canonicalJSON = form.encodedJSON() else {+ return invalidInput(+ context,+ "user.choose requires a `form` JSON object with a non-empty `fields` array."+ )+ }+ let question = form.title.isEmpty ? "Choose how I should proceed." : form.title+ return HarnessToolResult(+ callID: context.call.id,+ toolName: context.call.name,+ status: .waitingForUser,+ summary: "Task stopped for the user to choose options.",+ question: question,+ metadata: ["gate": "choiceForm", "choiceForm": canonicalJSON]+ )+ }+private static func permissionRequest(_ context: HarnessToolExecutionContext) -> HarnessToolResult {let permissions = context.call.input["permission"].map { [$0] }@@ -566,8 +793,11 @@ public enum BuiltInHarnessToolExecutors {.filter { entry in matches(tokens: tokens, values: [entry.id, entry.summary, entry.value] + Array(entry.metadata.values)) }.prefix(8).map { "\($0.id): \($0.summary)" }- let worldMatches = (context.worldModel.facts.map { "\($0.key): \($0.value)" }- + context.worldModel.visibleText.map { "\($0.key): \($0.value)" })+ // Show only model-facing facts — the machine-only keys (workspace base dir, raw follow-up+ // instructions) are hidden centrally so they never leak into retrieved snippets.+ let worldFacts = context.worldModel.modelFacingFacts+ .map { "\($0.key): \($0.value)" }+ let worldMatches = (worldFacts + context.worldModel.visibleText.map { "\($0.key): \($0.value)" }).filter { matches(tokens: tokens, values: [$0]) }.prefix(8)let snippets = Array(configuredMatches + worldMatches)@@ -1801,7 +2031,9 @@ public enum BuiltInHarnessToolExecutors {prompt: prompt,inputImagePaths: inputPaths,model: trimmed(context.call.input["model"]),- outputDirectory: trimmed(context.call.input["outDir"])+ outputDirectory: trimmed(context.call.input["outDir"]),+ workspaceBaseDir: context.worldModel.facts[ConversationWorkspace.baseDirFactKey]+ .flatMap { $0.isEmpty ? nil : $0 })guard let result = await generator(request) else {return failed(context, "The image model is unavailable right now.", reason: "imageGeneratorUnavailable")@@ -1825,6 +2057,211 @@ public enum BuiltInHarnessToolExecutors {)}+ private static func videoGenerate(+ _ context: HarnessToolExecutionContext,+ services: HarnessBuiltInToolServices+ ) async -> HarnessToolResult {+ guard let generator = services.videoGenerator else {+ return failed(context, "No video model is wired for \(context.call.name).", reason: "videoGeneratorUnavailable")+ }+ guard let prompt = trimmed(context.call.input["prompt"]) else {+ return invalidInput(context, "\(context.call.name) requires a `prompt` describing the video.")+ }+ var inputPaths: [String] = []+ if let inputPath = trimmed(context.call.input["inputPath"]) {+ inputPaths.append(inputPath)+ }+ let audio = trimmed(context.call.input["audio"]).map { boolFlag($0) }+ let request = HarnessVideoGenerationRequest(+ prompt: prompt,+ inputImagePaths: inputPaths,+ model: trimmed(context.call.input["model"]),+ outputDirectory: trimmed(context.call.input["outDir"]),+ tier: trimmed(context.call.input["tier"]),+ audio: audio,+ aspectRatio: trimmed(context.call.input["aspectRatio"]),+ durationSeconds: trimmed(context.call.input["durationSeconds"]).flatMap { Int($0) },+ negativePrompt: trimmed(context.call.input["negativePrompt"]),+ workspaceBaseDir: context.worldModel.facts[ConversationWorkspace.baseDirFactKey]+ .flatMap { $0.isEmpty ? nil : $0 }+ )+ guard let result = await generator(request) else {+ return failed(context, "The video model is unavailable right now.", reason: "videoGeneratorUnavailable")+ }+ guard !result.savedPaths.isEmpty else {+ return failed(+ context,+ result.failureReason ?? "The video model returned no video.",+ reason: "videoGenerationFailed"+ )+ }+ let joined = result.savedPaths.joined(separator: ", ")+ return success(+ context,+ summary: "Saved \(result.savedPaths.count) video(s) → \(joined)",+ facts: ["lastAcceptedTool": context.call.name],+ metadata: [+ "paths": result.savedPaths.joined(separator: "\n"),+ "count": String(result.savedPaths.count)+ ]+ )+ }++ /// On-device transcription with per-word timings behind `transcribe`. Writes the transcript and its+ /// word timings as a JSON file (so a long transcript bypasses the shell command-length limit) and+ /// returns its path, plus the plain text inline. The word timings are what the media skill reads+ /// back to cut filler words or silence; an empty result carries the backend's reason so the planner+ /// can extract compact audio and retry rather than give up.+ private static func transcribe(+ _ context: HarnessToolExecutionContext,+ services: HarnessBuiltInToolServices+ ) async -> HarnessToolResult {+ guard let transcriber = services.transcriber else {+ return failed(context, "No on-device transcription backend is wired for transcribe.", reason: "transcriberUnavailable")+ }+ guard let filePath = trimmed(context.call.input["filePath"]) else {+ return invalidInput(context, "transcribe requires a `filePath` to a local audio or video file.")+ }+ let fileURL = URL(fileURLWithPath: (filePath as NSString).expandingTildeInPath)+ guard FileManager.default.fileExists(atPath: fileURL.path) else {+ return invalidInput(context, "transcribe `filePath` does not exist: \(filePath).")+ }+ let request = HarnessTranscriptionRequest(+ filePath: fileURL.path,+ localeIdentifier: trimmed(context.call.input["locale"])+ )+ guard let result = await transcriber(request) else {+ return failed(context, "On-device transcription is unavailable right now.", reason: "transcriberUnavailable")+ }+ guard !result.words.isEmpty || !result.text.isEmpty else {+ let hint = "extract compact audio first (e.g. ffmpeg -i in.mp4 -vn -ac 1 audio.m4a) and transcribe that"+ let reason = result.failureReason.map { "Transcription failed: \($0). Then \(hint)." }+ ?? "Transcription produced no words — \(hint)."+ return failed(context, reason, reason: "transcriptionFailed")+ }++ // Persist text + per-word timings (seconds) as JSON the planner reads back to build the cut list.+ let wordObjects: [[String: Any]] = result.words.map { word in+ [+ "text": word.text,+ "start": Double(word.startMS) / 1000.0,+ "end": Double(word.endMS) / 1000.0+ ]+ }+ let payload: [String: Any] = [+ "text": result.text,+ "locale": result.localeIdentifier ?? "",+ "backend": result.backend,+ "wordCount": result.words.count,+ "words": wordObjects+ ]+ // Write into the conversation workspace (not the temp dir): the per-word-timing JSON is a real+ // deliverable the planner must hand to media.cut as `transcriptPath`, and the workspace tracker+ // skips temp-dir paths — a transcript left in temp never enters the workspace summary, so after+ // context compaction the planner loses the path and can't run the filler-word cut it transcribed for.+ let url = Self.resolveWritePath("donkey-transcript-\(context.call.id).json", in: context.worldModel)+ do {+ try FileManager.default.createDirectory(+ at: url.deletingLastPathComponent(),+ withIntermediateDirectories: true+ )+ let data = try JSONSerialization.data(withJSONObject: payload, options: [.prettyPrinted, .sortedKeys])+ try data.write(to: url, options: .atomic)+ } catch {+ return failed(context, "Could not write the transcript file: \(error)", reason: "fileWriteFailed")+ }+ let preview = result.text.count > 400 ? String(result.text.prefix(400)) + "…" : result.text+ return success(+ context,+ summary: "Transcribed \(result.words.count) timed words (\(result.backend)) → \(url.path)",+ facts: ["lastAcceptedTool": context.call.name],+ metadata: [+ "filePath": url.path,+ "text": preview,+ "wordCount": String(result.words.count)+ ]+ )+ }++ /// Deterministic filler-word/silence editor behind `media.cut`. The planner says WHAT to remove+ /// (fillers via the transcript, silence, explicit spans); the wired engine does the span math, builds+ /// the ffmpeg filtergraph, and renders the cut — none of it composed here. `removedSpanCount == 0`+ /// (nothing matched) is reported as a clean no-op, not a failure.+ private static func mediaCut(+ _ context: HarnessToolExecutionContext,+ services: HarnessBuiltInToolServices+ ) async -> HarnessToolResult {+ guard let cutter = services.mediaCutter else {+ return failed(context, "No media-cut engine is wired for media.cut.", reason: "mediaCutterUnavailable")+ }+ guard let inputPath = trimmed(context.call.input["inputPath"]) else {+ return invalidInput(context, "media.cut requires an `inputPath` to the video or audio file.")+ }+ let inputURL = URL(fileURLWithPath: (inputPath as NSString).expandingTildeInPath)+ guard FileManager.default.fileExists(atPath: inputURL.path) else {+ return invalidInput(context, "media.cut `inputPath` does not exist: \(inputPath).")+ }+ let removeFillers = boolFlag(context.call.input["removeFillers"])+ let removeSilence = boolFlag(context.call.input["removeSilence"])+ let explicit = trimmed(context.call.input["removeSpans"])+ guard removeFillers || removeSilence || explicit != nil else {+ return invalidInput(context, "media.cut needs at least one of removeFillers=true, removeSilence=true, or removeSpans.")+ }+ let transcriptPath = trimmed(context.call.input["transcriptPath"]).map { ($0 as NSString).expandingTildeInPath }+ if removeFillers, transcriptPath == nil {+ return invalidInput(context, "media.cut removeFillers=true requires `transcriptPath` to the transcribe JSON.")+ }+ // Split on commas/newlines only — NOT spaces — so a multi-word filler phrase like "you know"+ // stays one entry instead of shattering into the common words "you" and "know".+ let fillerWords = (trimmed(context.call.input["fillerWords"]) ?? "")+ .split(whereSeparator: { $0 == "," || $0 == "\n" })+ .map { $0.trimmingCharacters(in: .whitespaces) }+ .filter { !$0.isEmpty }+ let request = HarnessMediaCutRequest(+ inputPath: inputURL.path,+ outputPath: trimmed(context.call.input["outputPath"]).map { ($0 as NSString).expandingTildeInPath },+ removeFillers: removeFillers,+ removeSilence: removeSilence,+ transcriptPath: transcriptPath,+ fillerWords: fillerWords,+ explicitRemovals: explicit+ )+ guard let result = await cutter(request) else {+ return failed(context, "The media-cut engine is unavailable right now.", reason: "mediaCutterUnavailable")+ }+ if let reason = result.failureReason {+ return failed(context, "media.cut failed: \(reason)", reason: "mediaCutFailed")+ }+ let removedSec = max(0, result.inputDurationSec - result.outputDurationSec)+ if result.removedSpanCount == 0 {+ return success(+ context,+ summary: "media.cut found nothing to remove — left \(result.outputPath) unchanged.",+ facts: ["lastAcceptedTool": context.call.name],+ metadata: ["filePath": result.outputPath, "removedSpans": "0"]+ )+ }+ return success(+ context,+ summary: String(+ format: "Cut %d span(s), removed %.1fs — %.1fs → %.1fs → %@",+ result.removedSpanCount, removedSec, result.inputDurationSec, result.outputDurationSec, result.outputPath+ ),+ facts: ["lastAcceptedTool": context.call.name],+ metadata: [+ "filePath": result.outputPath,+ "removedSpans": String(result.removedSpanCount),+ "inputDurationSec": String(format: "%.3f", result.inputDurationSec),+ "outputDurationSec": String(format: "%.3f", result.outputDurationSec)+ ]+ )+ }++ /// A loose boolean flag from a tool input — "true"/"on"/"yes"/"1" (case-insensitive) is true.+ private static func boolFlag(_ value: String?) -> Bool {+ ["true", "on", "yes", "1"].contains((value ?? "").trimmingCharacters(in: .whitespaces).lowercased())+ }+private static func webSearch(_ context: HarnessToolExecutionContext,services: HarnessBuiltInToolServices@@ -1966,8 +2403,11 @@ public enum BuiltInHarnessToolExecutors {metadata: ["verified": String(verified), "criteria.inferred": "true"])}+ // Keep the machine-only keys out of the evidence the planner reads (the `workspace` summary fact,+ // which lists produced files, still counts).let evidence = (- context.worldModel.facts.map { "\($0.key): \($0.value)" }+ context.worldModel.modelFacingFacts+ .map { "\($0.key): \($0.value)" }+ context.worldModel.visibleText.map { "\($0.key): \($0.value)" }+ context.worldModel.attemptedToolCalls.map { "\($0.call.name): \($0.summary)" }).joined(separator: "\n")diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessContracts.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessContracts.swiftindex ec1530e8..007b8358 100644--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessContracts.swift+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessContracts.swift@@ -167,6 +167,21 @@ public struct HarnessWorldModel: Codable, Equatable, Sendable {self.updatedAt = updatedAt}+ /// Fact keys that are machine state for executors, not context for the model: the workspace resolve+ /// directory and the raw follow-up-instructions block (which the planner prompt shows in its own block).+ /// Every model-facing facts view hides these via `modelFacingFacts`, so an internal key added later is+ /// hidden everywhere at once instead of in separate hand-maintained filters that drift apart.+ public static let modelHiddenFactKeys: Set<String> = [+ ConversationWorkspace.baseDirFactKey,+ HarnessAgentCoordinator.additionalInstructionsFactKey+ ]++ /// `facts` with the machine-only keys removed — the view safe to surface to the model (planner prompt,+ /// `memory.retrieve` snippets, `run.complete` evidence).+ public var modelFacingFacts: [String: String] {+ facts.filter { !Self.modelHiddenFactKeys.contains($0.key) }+ }+public func merging(result: HarnessToolResult) -> HarnessWorldModel {var model = selfmodel.visibleText.merge(result.observations.visibleText) { _, new in new }diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessCoordinator.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessCoordinator.swiftindex 6eedcfef..f434d57b 100644--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessCoordinator.swift+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessCoordinator.swift@@ -453,14 +453,16 @@ public actor HarnessAgentCoordinator {agentID: String,question: String,pendingToolCall: HarnessToolCall? = nil,- reason: String = "Task needs user clarification"+ reason: String = "Task needs user clarification",+ metadata: [String: String] = [:]) async -> HarnessAgentState? {await mutate(agentID: agentID, status: .waitingForUser, summary: reason) { task intask.pendingContinuation = HarnessPendingContinuation(stage: .clarification,reason: reason,question: question,- pendingToolCall: pendingToolCall+ pendingToolCall: pendingToolCall,+ metadata: metadata)}}@@ -510,7 +512,7 @@ public actor HarnessAgentCoordinator {call: HarnessToolCall,result: HarnessToolResult) async -> HarnessAgentState? {- await mutate(agentID: agentID, status: nil, summary: "Tool result recorded") { task in+ let updated = await mutate(agentID: agentID, status: nil, summary: "Tool result recorded") { task intask.toolHistory.append(HarnessToolCallRecord(call: call,@@ -522,6 +524,132 @@ public actor HarnessAgentCoordinator {task.worldModel = task.worldModel.merging(result: result)task.worldModel.attemptedToolCalls = task.toolHistory}+ // Capture any deliverable this step produced into the conversation workspace. Keys ONLY off+ // typed result fields (status, toolName, metadata file paths) — never user text — so the+ // planner gains durable memory of what it has created and where, surviving compaction.+ if result.status == .succeeded {+ let produced = Self.producedFilePaths(from: result)+ if !produced.isEmpty {+ await recordWorkspaceDeliverables(+ conversationID: updated?.conversationID,+ kind: result.toolName,+ files: produced,+ at: result.completedAt+ )+ }+ }+ return updated+ }++ /// Pull the absolute on-disk path(s) a tool result reported, from its typed metadata only. Reads the+ /// canonical `filePath`/`path` keys plus the newline-joined `paths` (image generation), drops anything+ /// under the temporary directory (intermediate scratch from `llm.generate`/`web.fetch toFile`, which is+ /// assembled into a real deliverable later), and de-duplicates. No natural-language matching.+ static func producedFilePaths(from result: HarnessToolResult) -> [(path: String, byteCount: Int?)] {+ var raws: [String] = []+ if let single = result.metadata["filePath"] ?? result.metadata["path"], !single.isEmpty {+ raws.append(single)+ }+ if let multi = result.metadata["paths"] {+ raws.append(contentsOf: multi.split(separator: "\n").map(String.init))+ }+ let byteCount = result.metadata["bytes"].flatMap { Int($0) }+ let tempPrefix = FileManager.default.temporaryDirectory.standardizedFileURL.path+ var seen = Set<String>()+ var out: [(String, Int?)] = []+ for raw in raws {+ let std = ConversationWorkspace.standardize(raw)+ guard !std.isEmpty, !std.hasPrefix(tempPrefix), !seen.contains(std) else { continue }+ seen.insert(std)+ out.append((std, byteCount))+ }+ return out+ }++ // MARK: - Conversation workspace++ /// The conversation's durable workspace record (files produced, chosen base, promoted folder), or nil+ /// if nothing has been produced yet. Stored in `HarnessConversation.metadata` so it spans every root+ /// agent in the conversation.+ public func conversationWorkspace(conversationID: String) async -> ConversationWorkspace? {+ guard let convo = await conversationStore?.conversation(id: conversationID) else { return nil }+ return ConversationWorkspace.decode(convo.metadata[ConversationWorkspace.metadataKey])+ }++ /// Record produced deliverables onto the conversation workspace, creating the conversation record if+ /// this is the first one. Loads → updates → persists the canonical copy in conversation metadata.+ public func recordWorkspaceDeliverables(+ conversationID: String?,+ kind: String,+ files: [(path: String, byteCount: Int?)],+ at date: Date+ ) async {+ guard let conversationID, let store = conversationStore, !files.isEmpty else { return }+ var convo = await store.conversation(id: conversationID)+ ?? HarnessConversation(id: conversationID, title: "")+ var workspace = ConversationWorkspace.decode(convo.metadata[ConversationWorkspace.metadataKey])+ ?? ConversationWorkspace()+ for file in files {+ workspace.record(path: file.path, kind: kind, byteCount: file.byteCount, at: date)+ }+ convo.metadata[ConversationWorkspace.metadataKey] = workspace.encodedJSON()+ convo.updatedAt = date+ await store.upsertConversation(convo)+ }++ /// Record the files the user attached onto the conversation workspace, so the planner sees them — with+ /// their paths — every step and can read or act on them. The input mirror of `recordWorkspaceDeliverables`:+ /// same load → update → persist of the canonical copy in conversation metadata. Persists across resumes+ /// and across root agents in the conversation.+ public func recordWorkspaceAttachments(+ conversationID: String?,+ attachments: [(path: String, displayName: String, contentType: String, byteCount: Int?)],+ at date: Date+ ) async {+ guard let conversationID, let store = conversationStore, !attachments.isEmpty else { return }+ var convo = await store.conversation(id: conversationID)+ ?? HarnessConversation(id: conversationID, title: "")+ var workspace = ConversationWorkspace.decode(convo.metadata[ConversationWorkspace.metadataKey])+ ?? ConversationWorkspace()+ for attachment in attachments {+ workspace.recordAttachment(+ path: attachment.path,+ displayName: attachment.displayName,+ contentType: attachment.contentType,+ byteCount: attachment.byteCount,+ at: date+ )+ }+ convo.metadata[ConversationWorkspace.metadataKey] = workspace.encodedJSON()+ convo.updatedAt = date+ await store.upsertConversation(convo)+ }++ /// Project the conversation workspace into the agent's world model facts so the planner sees, every+ /// step, what it has produced and where (and executors get the machine-readable resolve directory).+ /// Quiet: persists the snapshot without a lifecycle event, since this is per-step bookkeeping, not a+ /// step. A no-op when the conversation has produced nothing yet, so converse turns stay clean.+ public func refreshWorkspaceFact(agentID: String) async {+ let existing: HarnessAgentState?+ if let cached = tasksByID[agentID] {+ existing = cached+ } else {+ existing = await conversationStore?.agentSnapshot(id: agentID)+ }+ guard var task = existing,+ let workspace = await conversationWorkspace(conversationID: task.conversationID) else { return }+ let newSummary = workspace.plannerSummary()+ let newBase = workspace.currentBaseDirectory.flatMap { $0.isEmpty ? nil : $0 }+ // Per-step bookkeeping runs every planning iteration. Persisting re-serializes the WHOLE+ // conversation store to disk, so skip it when neither workspace fact actually changed — otherwise a+ // long run does one redundant full-store write per step, growing with conversation size.+ guard task.worldModel.facts[ConversationWorkspace.summaryFactKey] != newSummary+ || task.worldModel.facts[ConversationWorkspace.baseDirFactKey] != newBase else { return }+ task.worldModel.facts[ConversationWorkspace.summaryFactKey] = newSummary+ task.worldModel.facts[ConversationWorkspace.baseDirFactKey] = newBase+ task.updatedAt = Date()+ tasksByID[agentID] = task+ await conversationStore?.upsertAgentSnapshot(task)}/// Appends a note to the most recent tool record's summary. The runtime uses this to warn thediff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessFileTools.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessFileTools.swiftindex 83e80cca..1b3fe701 100644--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessFileTools.swift+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessFileTools.swift@@ -159,7 +159,7 @@ extension BuiltInHarnessToolExecutors {}let append = mode == "append"- let url = URL(fileURLWithPath: (rawPath as NSString).expandingTildeInPath).standardizedFileURL+ let url = Self.resolveWritePath(rawPath, in: context.worldModel)let fileManager = FileManager.defaultdo {try fileManager.createDirectory(@@ -196,10 +196,39 @@ extension BuiltInHarnessToolExecutors {),metadata: ["executor": "builtInGeneric",+ // `filePath` is the canonical key the workspace tracker reads; `path` is kept for+ // existing callers that already consume it.+ "filePath": url.path,"path": url.path,"bytes": String(bytes),"mode": mode])}++ /// Resolve where `files.write` should write. An absolute or `~`-prefixed path is honored exactly, so+ /// a path the user named always wins. A RELATIVE path resolves against the conversation workspace's+ /// current directory (the `workspace.baseDir` fact the runtime maintains) when one exists — this is+ /// how the planner keeps a task's files together by writing `report/chart.svg` instead of recomputing+ /// the absolute base each step. With no workspace yet, a relative path falls back to the user's home,+ /// matching where shell commands run.+ static func resolveWritePath(_ rawPath: String, in worldModel: HarnessWorldModel) -> URL {+ let expanded = (rawPath as NSString).expandingTildeInPath+ if expanded.hasPrefix("/") {+ return URL(fileURLWithPath: expanded).standardizedFileURL+ }+ // A relative path stays inside its base — the workspace folder when one exists, else home. Keep+ // only the non-traversal components so a stray `../../x` can't climb out of the workspace; subfolders+ // (`report/chart.svg`) still resolve normally.+ let base: URL+ if let workspace = worldModel.facts[ConversationWorkspace.baseDirFactKey], !workspace.isEmpty {+ base = URL(fileURLWithPath: (workspace as NSString).expandingTildeInPath, isDirectory: true)+ } else {+ base = FileManager.default.homeDirectoryForCurrentUser+ }+ let safeComponents = expanded+ .split(separator: "/", omittingEmptySubsequences: true)+ .filter { $0 != ".." && $0 != "." }+ return safeComponents.reduce(base) { $0.appendingPathComponent(String($1)) }.standardizedFileURL+ }}diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swiftindex 8ff52d62..92e4baa5 100644--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift@@ -94,8 +94,17 @@ public struct GenericHarnessRuntime: Sendable {// produced anything still fails safe — the stall guard's guarantee is preserved.var hadRealWork = falsevar stepsSinceWorldChange = 0- // Names of read-only tools, so only a world-changing NON-read-only success counts as real work.- let readOnlyToolNames = Set((await registry.descriptors()).filter { $0.safetyClass == .readOnly }.map(\.name))+ // Whether the deliverable-progress gate has already nudged this run (one-shot, so a long+ // legitimate acquisition isn't repeatedly scolded).+ var reconNudged = false+ // Names of NON-producing tools, so only a world-changing success that actually produces something+ // counts as "real work". This is every read-only tool PLUS the cacheable reads (files.describe,+ // transcribe) — those are classed `.sensitive` for permissions but are still reconnaissance, not a+ // deliverable, so they must not flip the recon done-gate's `hadRealWork`.+ let nonProducingToolNames = Set((await registry.descriptors()).filter {+ $0.safetyClass == .readOnly+ || $0.metadata[HarnessToolDescriptor.cacheableReadMetadataKey] == "true"+ }.map(\.name))// Mark this task as having a live loop. While marked, an enqueued follow-up is guaranteed delivery:// it is drained at the top of each iteration, and the only stop that actually ends the run is one@@ -134,6 +143,9 @@ public struct GenericHarnessRuntime: Sendable {}iterations += 1+ // Project the conversation's workspace memory (files produced, chosen base, promoted folder)+ // into the world model before planning so it survives compaction and reaches every step.+ await coordinator.refreshWorkspaceFact(agentID: agentID)guard let task = await coordinator.agent(id: agentID), task.status.canExecuteTools else {if await coordinator.endRunUnlessPending(agentID: agentID) { break loop } else { continue loop }}@@ -173,7 +185,7 @@ public struct GenericHarnessRuntime: Sendable {stepsSinceWorldChange = 0if step.toolResult?.status == .succeeded,!call.name.hasPrefix("run."),- !readOnlyToolNames.contains(call.name) {+ !nonProducingToolNames.contains(call.name) {hadRealWork = true}} else {@@ -183,6 +195,21 @@ public struct GenericHarnessRuntime: Sendable {if await coordinator.endRunUnlessPending(agentID: agentID) { break loop } else { continue loop }}+ // Deliverable-progress done-gate. Once enough steps have passed with no PRODUCING action yet+ // (hadRealWork still false — only reads/observations), nudge once: produce the result now or+ // report the specific blocker. A one-shot annotation, not a hard stop, so a legitimately long+ // acquisition isn't killed; the stall guards below still backstop a true loop.+ if !hadRealWork, !reconNudged, iterations >= Self.maxReconStepsBeforeNudge {+ reconNudged = true+ _ = await coordinator.annotateLastToolRecord(+ agentID: agentID,+ note: "NOTE: \(iterations) steps in and nothing has been produced toward the deliverable "+ + "yet — only reconnaissance (locating, reading, listing). Stop scouting: take the "+ + "action that creates the result now, or if you are blocked, report the specific "+ + "blocker honestly. Do not re-read or re-list what you already have."+ )+ }+// 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. Three// signals end a stuck run: enough consecutive no-progress steps (busy but going nowhere),@@ -336,6 +363,13 @@ public struct GenericHarnessRuntime: Sendable {/// by the step-budget path to tell re-verification (conclude) from genuine progress (time out).private static let spinStepsBeforeConclude = 3+ /// How many steps a run may take while producing NOTHING toward the deliverable (only reconnaissance —+ /// locating, reading, listing) before the loop nudges it to produce-or-report. The no-progress streak+ /// resets on any world-model change, so a string of distinct successful reads looks like progress and+ /// never trips it (observed: 16 steps of recon, zero fields filled). This gate watches a different+ /// thing — whether any *producing* action has happened yet — so pure scouting can't run forever.+ private static let maxReconStepsBeforeNudge = 8+/// Ends a stalled run. A QUIET stall — the planner stopped advancing but isn't thrashing/// (`noProgress`) — can be a finished task that is merely re-verifying itself, so if it did real work/// and the goal is evidence-backed, conclude as COMPLETE rather than fail. Every OTHER stall is the@@ -486,7 +520,8 @@ public struct GenericHarnessRuntime: Sendable {guard let stoppedTask = await coordinator.waitForUser(agentID: agentID,question: result.question ?? "What detail should I use?",- pendingToolCall: call+ pendingToolCall: call,+ metadata: result.metadata) else {return nil}@@ -608,34 +643,50 @@ 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, 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.+ /// Both halves of "you already ran this exact (tool, input) and it succeeded this run":+ /// - a tool that OPTS IN to caching (`cacheableRead`) → serve the prior result from the run's READ+ /// CACHE instead of re-executing, so an identical re-read costs nothing.+ /// - a STATE-CHANGING tool → reject the repeat (re-running duplicates the side effect) and hand the+ /// prior result back so the planner isn't blind and advances instead of looping.+ /// Caching is opt-in — and gated on the FLAG, not the safety class — because "read-only" does not imply+ /// "pure": a counter, a clock, a directory being written all read without side effects yet return+ /// different values each call, so a blanket read-only cache would serve stale data. Only a tool that+ /// declares its identical-input result stable opts in. A read whose resource a later state-changing step+ /// may have altered is re-run, not served stale. Plain read-only tools that don't opt in, a multi-action+ /// tool's declared read actions, lifecycle calls, and records from previous runs are all exempt (re-run).private func duplicateActionRejection(call: HarnessToolCall,task: HarnessAgentState) async -> HarnessToolResult? {guard !call.name.hasPrefix("run."), !call.name.hasPrefix("conversation.") else { return nil }let descriptors = await registry.descriptors()- let readOnlyNames = Set(descriptors.filter { $0.safetyClass == .readOnly }.map(\.name))- guard !readOnlyNames.contains(call.name) else { return nil }+ let descriptor = descriptors.first { $0.name == call.name }+ let isReadOnly = descriptor?.safetyClass == .readOnly+ // Cache-eligible iff the tool explicitly asserts a stable read AND isn't a live observation. The+ // flag — not the safety class — is the gate: a pure read (a file's contents) may be classed+ // `.sensitive` for permissions yet still be safe to cache.+ let isCacheableRead = descriptor?.metadata[HarnessToolDescriptor.cacheableReadMetadataKey] == "true"+ && descriptor?.metadata[HarnessToolDescriptor.volatileResultMetadataKey] != "true"// 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],+ let declared = descriptor?.metadata[HarnessToolDescriptor.readOnlyActionsMetadataKey],declared.split(separator: ",").map({ $0.trimmingCharacters(in: .whitespaces) }).contains(action) {return nil}+ // A plain read-only tool that doesn't opt into caching re-runs freely (re-reading/observing is+ // cheap and legitimately reflects fresh state).+ if isReadOnly, !isCacheableRead { return nil }let signature = Self.canonicalInput(call.input)- let priorRecord = Self.currentRunHistory(task.toolHistory).last { record in+ let runHistory = Self.currentRunHistory(task.toolHistory)+ guard let priorIndex = runHistory.lastIndex(where: { record inrecord.resultStatus == .succeeded&& record.call.name == call.name&& Self.canonicalInput(record.call.input) == signature- }- guard let priorRecord else { return nil }+ }) else { return nil }+ let priorRecord = runHistory[priorIndex]+// Hand the earlier RESULT back, not just "don't repeat". The planner usually re-runs a call// because its result fell out of the compacted context — so withholding it leaves the planner// blind and it loops on the same call until the stall guard kills the run (observed live: a@@ -643,9 +694,41 @@ public struct GenericHarnessRuntime: Sendable {// the prior output gives the planner what it was after so it can move on. Bounded so a large// listing can't bloat the next prompt.let priorOutput = priorRecord.summary.trimmingCharacters(in: .whitespacesAndNewlines)+ // Echo the prior result with a generous bound. When it is clipped, say WHY in the same terms the+ // planner prompt uses for trimmed history: the full output is already captured and re-running won't+ // lengthen this view. A bare "[truncated]" marker reads as a truncated FILE and sends the planner+ // re-reading the same content through ever-fancier commands — the loop this echo exists to stop.+ let dedupEchoMaxLength = 2_000+ let echoBody = priorOutput.count > dedupEchoMaxLength+ ? String(priorOutput.prefix(dedupEchoMaxLength))+ + " …[view trimmed; the full \(priorOutput.count)-char output is already captured — "+ + "re-running this read will NOT lengthen it]"+ : priorOutputlet resultBlock = priorOutput.isEmpty? ""- : " It already returned:\n\(String(priorOutput.prefix(500)))\n"+ : " It already returned:\n\(echoBody)\n"++ if isCacheableRead {+ // Read cache. Only serve the cached value when nothing the run has done since could have+ // changed what this read sees: a succeeded state-changing step in between means the resource+ // may differ now, so let it re-run rather than serve stale.+ let readOnlyNames = Set(descriptors.filter { $0.safetyClass == .readOnly }.map(\.name))+ let stateChangedSince = runHistory[runHistory.index(after: priorIndex)...].contains { record in+ record.resultStatus == .succeeded+ && !record.call.name.hasPrefix("run.")+ && !record.call.name.hasPrefix("conversation.")+ && !readOnlyNames.contains(record.call.name)+ }+ if stateChangedSince { return nil }+ return HarnessToolResult(+ callID: call.id,+ toolName: call.name,+ status: .succeeded,+ summary: "Served from this run's read cache: `\(call.name)` already ran with this exact input and nothing you've done since changes what it sees.\(resultBlock)Use this; don't re-read it.",+ metadata: ["reason": "readCacheHit", "servedFromCache": "true"]+ )+ }+return HarnessToolResult(callID: call.id,toolName: call.name,diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swiftindex f4c300e4..b131bef1 100644--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift@@ -14,6 +14,21 @@ public struct HarnessToolDescriptor: Codable, Equatable, Sendable {/// must never block the re-read its own rejection message asks for.public static let readOnlyActionsMetadataKey = "readOnlyActions"+ /// Descriptor metadata key a tool sets to "true" when its result reflects LIVE, moment-to-moment+ /// state that can change on its own between identical calls — a screen observation, a capture. The+ /// run's read cache must never serve such a tool from a prior result: re-observing is the whole+ /// point, and a cached screen would be stale.+ public static let volatileResultMetadataKey = "volatileResult"++ /// Descriptor metadata key a READ-ONLY tool sets to "true" to opt INTO the run's read cache: an+ /// identical repeat is served from the prior result instead of re-executing. Opt-in, not the default,+ /// because "read-only" (needs no permission) does NOT imply "pure" — a counter, a clock, `date`, a+ /// directory another process is filling all read without side effects yet return different values each+ /// call, and caching those would serve stale data. Only a tool whose identical-input result is stable+ /// between calls (a file's contents, a parsed document) sets this. A state-changing step since the+ /// cached read still invalidates it.+ public static let cacheableReadMetadataKey = "cacheableRead"+public var name: Stringpublic var pluginID: Stringpublic var summary: String@@ -188,6 +203,14 @@ public enum BuiltInHarnessToolCatalog {permissions: [.userPrompt],safety: .readOnly),+ descriptor(+ "user.choose",+ pluginID: "core.user",+ summary: "Surface a small interactive options panel (buttons, dropdowns, toggles) and stop the task until the user submits their choices — use when a request has a few meaningful settings worth letting the user pick before you commit (e.g. video speed/quality and audio). ALWAYS guess sensible defaults from the user's words so they can submit in one tap. The `form` is a JSON object: {\"title\":\"…\",\"submitLabel\":\"Generate\",\"fields\":[…]}. Each field is {\"id\":\"<key>\",\"label\":\"…\",\"help\":\"<optional>\",\"control\":\"segmented\"|\"dropdown\"|\"toggle\", and for segmented/dropdown \"options\":[{\"id\":\"<value>\",\"label\":\"…\",\"detail\":\"<optional>\"}] with \"selected\":\"<default option id>\"; for toggle \"on\":true|false}. The answer comes back as \"Selected options: id=value, …\" — read it to make your next call. Don't use this for a free-text question (use user.clarify) or for required missing info you can't default.",+ input: ["form": "A JSON object describing the options panel: a title, optional submitLabel, and a fields array of typed controls (segmented/dropdown/toggle) each with a guessed default."],+ permissions: [.userPrompt],+ safety: .readOnly+ ),descriptor("permission.request",pluginID: "core.permission",@@ -542,14 +565,19 @@ public enum BuiltInHarnessToolCatalog {permissions: [],safety: .sensitive,verification: ["the returned understanding covers the requested files"],- metadata: [HarnessToolDescriptor.resultIsEvidenceMetadataKey: "true"]+ // A pure read of files' contents: an identical re-describe (same paths, no write since)+ // returns the same understanding, so it's safe to serve from the run's read cache.+ metadata: [+ HarnessToolDescriptor.resultIsEvidenceMetadataKey: "true",+ HarnessToolDescriptor.cacheableReadMetadataKey: "true"+ ]),descriptor("files.write",pluginID: "core.files",- summary: "Write text to a file: pass an absolute `path` and the full `content`, and it is saved (creating any missing parent folders). This is how you persist anything you composed when the content is multi-line or too long to inline in a shell command — a subtitle (.srt) file, a script, a config, a note, a document body. Use it instead of a `cat`/`echo` heredoc in shell_exec. Overwrites by default; pass mode=append to add to the end. Pair it with llm.generate (which returns text) to write generated content exactly where you need it, then act on the file (e.g. `ffmpeg -vf subtitles=…`).",+ summary: "Write text to a file: pass a `path` and the full `content`, and it is saved (creating any missing parent folders). This is how you persist anything you composed when the content is multi-line or too long to inline in a shell command — a subtitle (.srt) file, a script, a config, a note, a document body. Use it instead of a `cat`/`echo` heredoc in shell_exec. A relative `path` (e.g. `notes.md` or `Sources/App.swift`) lands inside the conversation's workspace folder; an absolute or ~ path is written exactly as given. Overwrites by default; pass mode=append to add to the end. Pair it with llm.generate (which returns text) to write generated content exactly where you need it, then act on the file (e.g. `ffmpeg -vf subtitles=…`).",input: [- "path": "Absolute destination path, e.g. /Users/you/Downloads/ko.srt (a leading ~ is expanded).",+ "path": "Destination path. Relative (e.g. report/chart.svg) resolves inside the conversation workspace; absolute (e.g. /Users/you/Downloads/ko.srt, leading ~ expanded) is used exactly.","content": "The full text to write.","mode": "\"overwrite\" (default) replaces the file; \"append\" adds to the end."],@@ -587,7 +615,7 @@ public enum BuiltInHarnessToolCatalog {descriptor("image.generate",pluginID: "core.image",- summary: "Generate a brand-new image from a text `prompt` with a generative image model — use when there is no source image to edit. Writes a new image file and returns its path. Costs image-generation credits per image.",+ summary: "Generate a brand-new image from a text `prompt` with a generative image model — use for photographic or artistic imagery when there is no source image to edit. NOT for charts, diagrams, infographics, posters, standings, or anything containing real text or data: a generative model garbles text and numbers. For those, write HTML/SVG and render it with `image_render` (see the `design` skill). Writes a new image file and returns its path. Costs image-generation credits per image.",input: ["prompt": "Description of the image to create.","model": "Optional model id override; omit to use the default image model.",@@ -603,6 +631,75 @@ public enum BuiltInHarnessToolCatalog {verification: ["the returned image file exists"],metadata: [HarnessToolDescriptor.resultIsEvidenceMetadataKey: "true"]),+ descriptor(+ "video.generate",+ pluginID: "core.video",+ summary: "Generate a short video clip from a text `prompt` with a generative video model — use when the user asks for a video, clip, animation, or moving footage of a scene. Optionally pass `inputPath` to animate a still image (image-to-video). Generation takes up to a few minutes; this call waits for the result, then writes one .mp4 to Downloads and returns its path. Costs video-generation credits per clip (much more than an image), so confirm before generating several. Not for editing or trimming an existing video file — use the `media` skill (ffmpeg) for that, and not for slideshows of stills.",+ input: [+ "prompt": "Description of the video to create — the scene, action, camera, and mood.",+ "inputPath": "Optional path to a still image to animate as the first frame (image-to-video).",+ "tier": "Optional speed/quality tier the user chose (e.g. \"fast\", \"standard\", \"high\"); omit for the default.",+ "audio": "Optional \"true\"/\"false\" — whether to generate audio with the video. Omit for the default (on).",+ "model": "Optional model id override; omit to use the default video model.",+ "aspectRatio": "Optional aspect ratio, e.g. \"16:9\" (landscape) or \"9:16\" (portrait).",+ "durationSeconds": "Optional clip length in seconds; omit for the model default.",+ "negativePrompt": "Optional description of what to keep out of the video.",+ "outDir": "Optional output directory for the result; omit to save to Downloads."+ ],+ output: [+ "paths": "Newline-separated paths to the saved video file(s).",+ "count": "How many videos were saved."+ ],+ optionalInputKeys: ["inputPath", "tier", "audio", "model", "aspectRatio", "durationSeconds", "negativePrompt", "outDir"],+ permissions: [],+ safety: .reversible,+ verification: ["the returned video file exists"],+ metadata: [HarnessToolDescriptor.resultIsEvidenceMetadataKey: "true"]+ ),+ descriptor(+ "transcribe",+ pluginID: "core.media",+ summary: "Transcribe a local audio file ON-DEVICE into text WITH PER-WORD TIMESTAMPS — fast, private, and far more precise than an llm.generate SRT. Use it whenever you need to know exactly WHEN words are spoken: to cut filler words (um, uh) or silence, locate a quoted moment, chapter a recording, or build tight captions. Writes a JSON file ({text, words:[{text, start, end}]}, times in seconds) and returns its path, plus the plain transcript inline. Hand it compact audio (extract it first with ffmpeg if the source is a video); if it reports no transcript, extract audio and retry. For plain text without timing, llm.generate is fine.",+ input: [+ "filePath": "Path to the local audio file to transcribe (extract audio from a video first).",+ "locale": "Optional BCP-47 locale (e.g. en-US, es-ES); defaults to the system locale, falling back to en-US."+ ],+ output: [+ "filePath": "Path to the JSON file holding the full transcript and per-word timings.",+ "text": "The plain transcript text (a preview when long).",+ "wordCount": "How many timed words were produced."+ ],+ optionalInputKeys: ["locale"],+ permissions: [],+ safety: .sensitive,+ verification: ["the returned transcript text and per-word timings match the spoken audio"],+ metadata: [HarnessToolDescriptor.resultIsEvidenceMetadataKey: "true"]+ ),+ descriptor(+ "media.cut",+ pluginID: "core.media",+ summary: "Remove filler words and/or silence from a video or audio file and rejoin the kept parts — a DETERMINISTIC, frame-accurate editor (the engine does the span math and ffmpeg render, you just say what to remove). This is the reliable way to tighten a recording; do NOT hand-build select/trim/concat ffmpeg yourself. Set removeFillers=true with `transcriptPath` (run `transcribe` first) to cut um/uh/er, and/or removeSilence=true to cut dead air. Pass `removeSpans` for caller-judged cuts (a flubbed line, a discourse \"like\"). Writes a new file (never overwrites the source) and reports how much was removed; finding nothing to cut is a clean result, not an error.",+ input: [+ "inputPath": "Path to the source video or audio file to tighten.",+ "removeFillers": "\"true\" to cut filler words (um, uh, er, …) — requires transcriptPath.",+ "transcriptPath": "Path to the JSON written by `transcribe` (per-word timings); required when removeFillers=true.",+ "removeSilence": "\"true\" to cut silent/dead-air sections.",+ "removeSpans": "Optional explicit ranges to remove, seconds, as \"start-end,start-end\" (e.g. a flubbed take).",+ "fillerWords": "Optional comma-separated lexicon override; omit for the default um,uh,er,… set.",+ "outputPath": "Optional output path; omit to write <name>-tightened next to the source."+ ],+ output: [+ "filePath": "Path to the written, tightened file.",+ "removedSpans": "How many spans were cut (0 means nothing matched; the file is unchanged).",+ "inputDurationSec": "Source duration in seconds.",+ "outputDurationSec": "Result duration in seconds."+ ],+ optionalInputKeys: ["removeFillers", "transcriptPath", "removeSilence", "removeSpans", "fillerWords", "outputPath"],+ permissions: [],+ safety: .reversible,+ verification: ["the output file exists and its duration equals the input minus the removed spans"],+ metadata: [HarnessToolDescriptor.resultIsEvidenceMetadataKey: "true"]+ ),descriptor("web.search",pluginID: "core.web",diff --git a/apps/Donkey/Sources/DonkeyRuntime/AXComputerUseTools.swift b/apps/Donkey/Sources/DonkeyRuntime/AXComputerUseTools.swiftindex 1702926f..03a13677 100644--- a/apps/Donkey/Sources/DonkeyRuntime/AXComputerUseTools.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/AXComputerUseTools.swift@@ -66,7 +66,10 @@ public final class AXComputerUseToolProvider {outputSchema: ["elements": "Accessibility control IDs, labels, roles, and click eligibility."],requiredPermissions: [.accessibility],safetyClass: .readOnly,- verificationHints: ["fresh observation reflects the current control state"]+ verificationHints: ["fresh observation reflects the current control state"],+ // A screen read reflects live state that changes on its own, so the run's read cache must+ // never serve a prior observation — re-observing is the whole point of calling it again.+ metadata: [HarnessToolDescriptor.volatileResultMetadataKey: "true"]),HarnessToolDescriptor(name: ToolName.click,diff --git a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/pdf/SKILL.md b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/pdf/SKILL.mdindex 8886abf3..6ec7413f 100644--- a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/pdf/SKILL.md+++ b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/pdf/SKILL.md@@ -32,7 +32,15 @@ happen in Preview. Creating files is reversible (consent gate).## Fill a PDF form — use pdf-fill (`pdf-fill`)`pdf-fill` writes a NEW file; it never edits in place. All I/O is JSON. Start by asking it what kind of form this is:-- `pdf-fill list in.pdf` lists the fillable (AcroForm) fields: `{name, type, value, page, rect}`.+- `pdf-fill list in.pdf --pretty > fields.json` — ALWAYS redirect the field list to a file. A real form (a tax or government form) has hundreds of fields; dumping that to stdout floods the next step's context and times out the read on volume. Write it to a file, then inspect it (`head`, count with a `lit`/`jq` pass), and work from the file.+- The list entries are `{name, type, value, page, rect}`. Field NAMES on official forms are opaque (`topmostSubform[0].Page1[0].f1_11[0]`) and carry no meaning on their own, so you must recover what each field IS before filling it — don't guess from the name.++### Filling an official form (tax / government / insurance) — recover labels, then map and compute+Opaque field names plus loose source data is a mapping problem, not a typing problem. Plan it as **read the data → recover each field's label → map data to fields → compute the derived values → write → verify**, and front-load the mapping and computation rather than circling the easy reads.+- Recover labels by position: a field's caption is the text printed next to it. Get the page text with boxes (`lit parse in.pdf --format json`) and join each field's `rect` from `pdf-fill list` to the nearest text run (the label is usually just left of, or above, the box). pdf-fill rects are bottom-left-origin PDF points; lit boxes are top-left — convert with the page height from `pdf-fill pages in.pdf`. Now you have `field → label`, which is what to map the data onto.+- Map the source data to fields by MEANING (you do this — match "gross receipts/total sales" to the receipts line, "officer compensation" to that line, etc.), then build the `{fieldName: value}` object and write it with `pdf-fill set`.+- Compute the derived values the data doesn't state outright — most official forms have them. A 1120, for instance, needs net receipts (gross − returns), total income, total deductions, taxable income, and tax (21% of taxable income). Work these out explicitly before filling; don't leave them blank and don't expect them in the data.+- If labels can't be recovered from the text layer (a scanned/flattened form), fall back to vision: rasterize a page (`lit screenshot`) and read the layout.- **Has fields (non-empty list) → set them.** Build a `{fieldName: value}` map and pipe it in: `echo '{"FullName":"Ada","Agree":true}' | pdf-fill set in.pdf --data - -o out.pdf`. Text and dropdown fields take strings; checkboxes take `true`/`false`. The result reports `applied` and `missing` so you can see any name that did not match.- **No fields (empty list) → it is a flat or scanned form; overlay text by position.** Get the labels and their boxes with `lit parse in.pdf --format json`, then stamp values next to them: `echo '[{"page":0,"x":120,"y":700,"text":"Ada Lovelace","size":12}]' | pdf-fill overlay in.pdf --data - -o out.pdf`. Coordinates are PDF points from the BOTTOM-left; lit boxes are top-left, so convert with the page height from `pdf-fill pages in.pdf` (`y_pdf = height - y_top - h`). Valid stamps are written even if some items are bad; the result reports `stamped` and any `skipped` items (with index and reason), so check `skipped` to catch dropped values.- To make the result non-editable (e.g. before sending it on), `pdf-fill flatten out.pdf -o final.pdf` burns the values into the page. It reports `processedPages`/`totalPages`; if it includes `droppedPages`/`warning`, some pages were lost — do not treat that output as complete.diff --git a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/system-tools/SKILL.md b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/system-tools/SKILL.mdindex dbd20e9e..10b9f168 100644--- a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/system-tools/SKILL.md+++ b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/system-tools/SKILL.md@@ -19,9 +19,11 @@ Use `shell_exec` as the first choice for anything an expert terminal user would- Keep parentheses out of commands. The safety classifier treats `(`/`)` (subshells, `find \( \)`, glob qualifiers like `(N)`) as separate commands and will prompt for approval on an otherwise read-only command. The `ls … | grep -iE` form above is parenthesis-free and runs instantly.## Find and inspect files-- Spotlight search by name or content: `mdfind -name report.pdf`, `mdfind "kMDItemTextContent == '*invoice*'"`.+- Check the obvious places FIRST: `ls -t ~/Desktop ~/Downloads ~/Documents .`. A file the user just made, downloaded, or moved is usually here, and this beats Spotlight for fresh files.+- `mdfind` searches the Spotlight INDEX, which lags reality: a file created or moved seconds ago may not be indexed yet, so `mdfind` can return nothing — or a stale OLDER copy in a different folder. Don't trust an `mdfind` hit as "the" file when the direct `ls` above found the named file in a user folder; prefer that copy.+- Spotlight search by name or content (after the direct checks): `mdfind -name report.pdf`, `mdfind "kMDItemTextContent == '*invoice*'"`.- Newest of one type / largest in a folder: `ls -t ~/Downloads/*.pdf | head -1`, `ls -S ~/Downloads | head`. For several types at once, use the `ls … | grep -iE` form from Shell safety above.-- Walk a tree: `find ~/Documents -name '*.key' -mtime -7`.+- Walk a tree, but always SCOPED to a folder: `find ~/Documents -name '*.key' -mtime -7`. Never run a bare `find .` or `find ~` — from home it walks the whole tree and times out before it reaches anything.- Read metadata or contents: `mdls file.pdf`, `stat -f '%Sm %N' file`, `cat file`, `head -50 file`.## Open, launch, and quitdiff --git a/apps/Donkey/Sources/DonkeyRuntime/RunLessonMemory.swift b/apps/Donkey/Sources/DonkeyRuntime/RunLessonMemory.swiftindex f935a4b7..d98c860e 100644--- a/apps/Donkey/Sources/DonkeyRuntime/RunLessonMemory.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/RunLessonMemory.swift@@ -22,11 +22,17 @@ public enum RunLessonMemory {public var cue: String/// The model's 0–1 confidence that this is a real, general lesson.public var confidence: Double+ /// The distiller's own typed judgment that this lesson would teach DEFEATING a harness guardrail+ /// (slipping past a duplicate/stall/permission guard). A lesson flagged here is dropped at write+ /// time. This is a structured field from the model — never inferred by string-matching the lesson+ /// text, which over-flags benign craft ("work around the check by asking first").+ public var defeatsGuardrail: Bool- public init(lesson: String, cue: String, confidence: Double) {+ public init(lesson: String, cue: String, confidence: Double, defeatsGuardrail: Bool = false) {self.lesson = lessonself.cue = cueself.confidence = min(max(confidence, 0), 1)+ self.defeatsGuardrail = defeatsGuardrail}}@@ -58,7 +64,15 @@ public enum RunLessonMemory {?? (object["confidence"] as? Int).map(Double.init)?? (object["confidence"] as? String).flatMap(Double.init)?? 0- return Distillation(lesson: lesson, cue: cue, confidence: confidence)+ let defeatsGuardrail = (object["unsafe"] as? Bool)+ ?? (object["unsafe"] as? String).map { ["true", "yes", "1"].contains($0.lowercased()) }+ ?? false+ return Distillation(+ lesson: lesson,+ cue: cue,+ confidence: confidence,+ defeatsGuardrail: defeatsGuardrail+ )}/// Build a durable global lesson proposal, deduped by lesson content so re-learning the same rule@@ -74,6 +88,11 @@ public enum RunLessonMemory {) -> AgentMemoryWriteProposal? {let lesson = distillation.lesson.trimmingCharacters(in: .whitespacesAndNewlines)guard !lesson.isEmpty, distillation.confidence >= minWriteConfidence else { return nil }+ // Never store a lesson that teaches the agent to DEFEAT a harness guardrail — the save-time half of+ // the governance rule. A guard firing means "you are looping" or "this needs consent"; a lesson that+ // says to slip past it is actively harmful. The judgment is the distiller's typed `defeatsGuardrail`+ // flag, decided where the run's full context is, not guessed by matching words in the lesson text.+ guard !distillation.defeatsGuardrail else { return nil }let id = idPrefix + stableHash(normalized(lesson))var metadata = ["lesson": "true", "outcome": outcome]diff --git a/apps/Donkey/Sources/DonkeyRuntime/ShellCommandClassifier.swift b/apps/Donkey/Sources/DonkeyRuntime/ShellCommandClassifier.swiftindex 6711c791..41261656 100644--- a/apps/Donkey/Sources/DonkeyRuntime/ShellCommandClassifier.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/ShellCommandClassifier.swift@@ -441,7 +441,16 @@ public enum ShellCommandClassifier {"say": "speaks text aloud","tee": "writes output to a file","screencapture": "captures the screen to a file",- "afplay": "plays an audio file"+ "afplay": "plays an audio file",+ // Scripting interpreters macOS ships (or that the data skill leans on): recognized here so they+ // surface a clear "runs a … script" consent prompt the user can always-allow, instead of falling+ // through to the opaque "unrecognized command" tier. Reversible (not read) because `-c`/`-e` can+ // run arbitrary code, but never a per-call surprise the way an unknown executable was.+ "python3": "runs a Python script",+ "python": "runs a Python script",+ "ruby": "runs a Ruby script",+ "perl": "runs a Perl script",+ "node": "runs a Node script"]/// Destructive / privileged / network-egress — prompt every time, neverdiff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/ConversationWorkspaceTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ConversationWorkspaceTests.swiftindex 3986c23b..a8798c6e 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/ConversationWorkspaceTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ConversationWorkspaceTests.swift@@ -116,6 +116,15 @@ struct FilesWritePathResolutionTests {let url = BuiltInHarnessToolExecutors.resolveWritePath("notes.txt", in: worldModel(baseDir: nil))#expect(url.path == NSHomeDirectory() + "/notes.txt")}++ @Test+ func relativeTraversalCannotEscapeWorkspaceBase() {+ let url = BuiltInHarnessToolExecutors.resolveWritePath(+ "../../secret/notes.md",+ in: worldModel(baseDir: "/Users/x/Downloads/proj")+ )+ #expect(url.path == "/Users/x/Downloads/proj/secret/notes.md")+ }}/// The runtime capture + projection: a succeeded file-producing step is recorded into the conversation@@ -235,11 +244,20 @@ struct CommandBackendDestinationTests {}@Test- func absoluteDestinationIsHonored() {+ func absoluteDestinationIsReRootedUnderBase() {+ // No-consent tool: an absolute destination is confined under base, never honored as-is.let url = DonkeyCommandBackends.resolveOutputDestination("/Users/x/Desktop/out.pdf", baseDir: "/Users/x/Downloads/report", format: "pdf", defaultName: "image")- #expect(url.path == "/Users/x/Desktop/out.pdf")+ #expect(url.path == "/Users/x/Downloads/report/Users/x/Desktop/out.pdf")+ }++ @Test+ func traversalDestinationCannotEscapeBase() {+ let url = DonkeyCommandBackends.resolveOutputDestination(+ "../../../../etc/cron.d/evil", baseDir: "/Users/x/Downloads/report", format: "png", defaultName: "image"+ )+ #expect(url.path == "/Users/x/Downloads/report/etc/cron.d/evil.png")}@Testdiff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swiftindex fea2321b..712485f1 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift@@ -713,6 +713,51 @@ struct GenericHarnessTests {#expect(repeatedCreate?.toolResult?.metadata["reason"] == "duplicateAction")}+ @Test+ func readCacheServesAnOptedInPureReadButNotAPlainReadOnlyTool() async {+ // A tool that opts into caching serves an identical repeat from cache; a plain read-only tool that+ // does not opt in re-runs every time (it may read evolving state — a counter, a clock, a listing).+ let coordinator = HarnessAgentCoordinator()+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors()+ await registry.register(stubTool(+ name: "pure.read", safetyClass: .readOnly,+ metadata: [HarnessToolDescriptor.cacheableReadMetadataKey: "true"]+ ))+ await registry.register(stubTool(name: "plain.read", safetyClass: .readOnly))+ let runtime = GenericHarnessRuntime(coordinator: coordinator, registry: registry)+ let task = await coordinator.createAgent(id: "task-cache", conversationID: "t", goal: "cache", grantedPermissions: [.lifecycle])++ let firstPure = await runtime.executeToolCall(agentID: task.id, call: HarnessToolCall(name: "pure.read", input: ["path": "x"]))+ #expect(firstPure?.toolResult?.metadata["servedFromCache"] != "true")+ let secondPure = await runtime.executeToolCall(agentID: task.id, call: HarnessToolCall(name: "pure.read", input: ["path": "x"]))+ #expect(secondPure?.toolResult?.status == .succeeded)+ #expect(secondPure?.toolResult?.metadata["servedFromCache"] == "true")++ _ = await runtime.executeToolCall(agentID: task.id, call: HarnessToolCall(name: "plain.read", input: [:]))+ let secondPlain = await runtime.executeToolCall(agentID: task.id, call: HarnessToolCall(name: "plain.read", input: [:]))+ #expect(secondPlain?.toolResult?.metadata["servedFromCache"] != "true")+ }++ @Test+ func readCacheIsInvalidatedByAStateChangingStep() async {+ // A state-changing step between two identical reads means the resource may have changed, so the+ // second read re-runs rather than serving a possibly-stale cached value.+ let coordinator = HarnessAgentCoordinator()+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors()+ await registry.register(stubTool(+ name: "pure.read", safetyClass: .readOnly,+ metadata: [HarnessToolDescriptor.cacheableReadMetadataKey: "true"]+ ))+ await registry.register(stubTool(name: "do.write", safetyClass: .guardedInput))+ let runtime = GenericHarnessRuntime(coordinator: coordinator, registry: registry)+ let task = await coordinator.createAgent(id: "task-inv", conversationID: "t", goal: "inv", grantedPermissions: [.lifecycle])++ _ = await runtime.executeToolCall(agentID: task.id, call: HarnessToolCall(name: "pure.read", input: ["path": "x"]))+ _ = await runtime.executeToolCall(agentID: task.id, call: HarnessToolCall(name: "do.write", input: ["path": "x"]))+ let afterWrite = await runtime.executeToolCall(agentID: task.id, call: HarnessToolCall(name: "pure.read", input: ["path": "x"]))+ #expect(afterWrite?.toolResult?.metadata["servedFromCache"] != "true")+ }+@Testfunc runCompleteOnAResumedTaskRequiresFreshEvidence() async {// The live false-completion: a new turn resumed a task whose previous run had created anddiff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessPromptEval/HarnessEvalFixture.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessPromptEval/HarnessEvalFixture.swiftindex e9c62c20..cc608ad6 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessPromptEval/HarnessEvalFixture.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessPromptEval/HarnessEvalFixture.swift@@ -113,6 +113,31 @@ struct HarnessEvalToolInput: Decodable, Sendable {var contains: [String]}+/// A prior file the conversation already produced, used to seed the workspace so a single-turn fixture can+/// model a FOLLOW-UP ("I already made these; now do one more"). Paths are stored home-relative (`~/…`) so+/// no real username is committed; the workspace standardizes them to the live home at runtime.+struct HarnessEvalWorkspaceFile: Decodable, Sendable {+ var path: String+ var kind: String?+}++/// Seeds the conversation workspace before the run. `files` are recorded in order, so the same+/// promotion logic the runtime uses (anchor-base + folder detection) decides the seeded shape.+struct HarnessEvalWorkspaceSeed: Decodable, Sendable {+ var files: [HarnessEvalWorkspaceFile]?++ func build() -> ConversationWorkspace? {+ guard let files, !files.isEmpty else { return nil }+ var workspace = ConversationWorkspace()+ // A fixed timestamp keeps the seed deterministic; the value is never asserted on.+ let seededAt = Date(timeIntervalSince1970: 1_700_000_000)+ for file in files {+ workspace.record(path: file.path, kind: file.kind ?? "files.write", byteCount: nil, at: seededAt)+ }+ return workspace+ }+}+/// The decoded `scenario.json`. Every field is optional with a sensible default so a folder needs nothing/// beyond `prompt.txt` to run.struct HarnessEvalScenarioSpec: Decodable, Sendable {@@ -121,6 +146,8 @@ struct HarnessEvalScenarioSpec: Decodable, Sendable {var disk: [HarnessEvalDiskEntry]?var responses: [HarnessEvalResponseRule]?var expect: HarnessEvalExpect?+ /// Prior files this conversation produced, surfaced to the planner as the `workspace` line.+ var workspace: HarnessEvalWorkspaceSeed?init() {}}@@ -195,7 +222,8 @@ struct HarnessEvalFixture: Sendable, CustomStringConvertible {name: name,prompt: prompt,frontmostApp: spec.frontmostApp ?? "Finder",- maxSteps: spec.maxSteps ?? 16+ maxSteps: spec.maxSteps ?? 16,+ workspaceSeed: spec.workspace?.build()) { call, knownFiles inif let rule = targetedRules.first(where: { $0.matches(call) }) {return rule.stub(in: dir)diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessPromptEval/HarnessPromptEvalRunner.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessPromptEval/HarnessPromptEvalRunner.swiftindex bd755c22..529ddfa2 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessPromptEval/HarnessPromptEvalRunner.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessPromptEval/HarnessPromptEvalRunner.swift@@ -63,18 +63,25 @@ struct HarnessEvalScenario: Sendable {/// the static disk plus everything earlier steps produced — so a discovery/probe stub can surface an/// output a prior step created, not just the fixture's declared inputs.var respond: @Sendable (HarnessToolCall, [String]) -> HarnessEvalStub?+ /// Prior conversation workspace to seed before the run, so a single-turn fixture can model a FOLLOW-UP:+ /// "I already produced these files; now do one more." The runner writes it into the conversation store+ /// so the real `refreshWorkspaceFact` projection surfaces the `workspace` line to the planner, exactly+ /// as in production. Nil for a first-turn scenario (the workspace starts empty).+ var workspaceSeed: ConversationWorkspace?init(name: String,prompt: String,frontmostApp: String = "Finder",maxSteps: Int = 16,+ workspaceSeed: ConversationWorkspace? = nil,respond: @escaping @Sendable (HarnessToolCall, [String]) -> HarnessEvalStub? = { _, _ in nil }) {self.name = nameself.prompt = promptself.frontmostApp = frontmostAppself.maxSteps = maxSteps+ self.workspaceSeed = workspaceSeedself.respond = respond}}@@ -204,13 +211,26 @@ enum HarnessEvalRunner {}let registry = HarnessToolRegistry(tools: tools)- let coordinator = HarnessAgentCoordinator()+ // A real store so the conversation workspace persists and the runtime's per-step+ // `refreshWorkspaceFact` projection surfaces the `workspace` line to the planner, as in production.+ let store = InMemoryHarnessConversationStore()+ let coordinator = HarnessAgentCoordinator(conversationStore: store)let goal = (understanding?.restatedGoal).flatMap { $0.isEmpty ? nil : $0 } ?? scenario.promptlet agent = await coordinator.createAgent(conversationID: conversationID,goal: goal,grantedPermissions: Set(HarnessPermission.allCases))+ // Seed a prior workspace so a fixture can model the second turn of a multi-file task.+ if let seed = scenario.workspaceSeed, let encoded = seed.encodedJSON() {+ await store.upsertConversation(+ HarnessConversation(+ id: conversationID,+ title: scenario.prompt,+ metadata: [ConversationWorkspace.metadataKey: encoded]+ )+ )+ }let planner = HostedHarnessStepPlanner(backend: backend,diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessRequestUnderstandingTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessRequestUnderstandingTests.swiftindex e34e5ab3..4691d03e 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessRequestUnderstandingTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessRequestUnderstandingTests.swift@@ -72,6 +72,41 @@ struct HostedHarnessRequestUnderstandingTests {"""#)#expect(result?.actionSurface == .guiApp)}++ @Test+ func understandingSurvivesAJSONRoundTripForResumeReuse() {+ // A resume reuses the first run's understanding by decoding what it persisted, instead of+ // re-deriving it (which drifted goal/params/skills mid-task). Every field a resume depends on must+ // survive the round trip exactly.+ let original = HarnessRequestUnderstanding(+ turnKind: .act,+ restatedGoal: "Fill out the f1120.pdf form using the data from 1120data.txt.",+ targetAppName: "",+ actionSurface: .appless,+ parameters: ["pdf_path": "f1120.pdf", "data_path": "1120data.txt"],+ successCriteria: "The PDF is filled.",+ plan: ["read the data", "list the form's fields", "map and compute", "write", "verify"],+ needsClarification: false,+ executionPreference: .background,+ relevantSkillIDs: ["pdf", "data"]+ )++ let decoded = HarnessRequestUnderstanding.decode(original.encodedJSON())++ #expect(decoded == original)+ // The exact failure the reuse prevents: a resume that recomputed re-typed `pdf_path` as `pdf_form`.+ #expect(decoded?.parameters["pdf_path"] == "f1120.pdf")+ #expect(decoded?.parameters["pdf_form"] == nil)+ }++ @Test+ func decodeReturnsNilForMissingOrGarbledPersistedUnderstanding() {+ // A task with no persisted understanding (older task, or it was unavailable first time) or a+ // corrupt value must fall back to recomputing, never crash.+ #expect(HarnessRequestUnderstanding.decode(nil) == nil)+ #expect(HarnessRequestUnderstanding.decode("") == nil)+ #expect(HarnessRequestUnderstanding.decode("{not json") == nil)+ }}private final class SingleResponseHTTPClient: AIHTTPClient, @unchecked Sendable {diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessStepPlannerTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessStepPlannerTests.swiftindex e6d30108..215b1058 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessStepPlannerTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessStepPlannerTests.swift@@ -305,6 +305,48 @@ struct HostedHarnessStepPlannerTests {#expect(narration == longNarration)}+ @Test+ func omittedNarrationFallsBackToTheToolNeverThePreviousStepsLine() async {+ // The carryover bug: a reply that omits `narration` used to keep the prior step's line+ // (`?? lastNarration`), pinning one step's account onto a later, unrelated step — observed as+ // "I will load the PDF skill" shown for the file-search and field-listing steps after it. The+ // first reply narrates; the second omits narration, and its `lastNarration` must be a line+ // synthesized from its OWN command, not the first step's narration.+ let httpClient = SequencedHTTPClient(responses: [+ (Data(#"{"output_text":"{\"tool\":\"shell_exec\",\"input\":{\"command\":\"echo first\"},\"narration\":\"Loading the PDF skill.\"}"}"#.utf8), 200),+ (Data(#"{"output_text":"{\"tool\":\"shell_exec\",\"input\":{\"command\":\"ls -la\"}}"}"#.utf8), 200)+ ])+ let planner = HostedHarnessStepPlanner(+ backend: DonkeyBackendInferenceClient(+ configuration: DonkeyBackendInferenceConfiguration(+ baseURL: URL(string: "https://donkey.example")!,+ clientID: "client-1"+ ),+ httpClient: httpClient+ ),+ descriptors: [+ HarnessToolDescriptor(+ name: "shell_exec",+ pluginID: "core",+ summary: "Run a single-line command.",+ inputSchema: ["command": "The command."],+ safetyClass: .guardedInput+ )+ ],+ appName: "Notes",+ appGuidance: nil,+ understanding: nil+ )++ _ = await planner.planNextStep(for: task(goal: "fill the form", toolHistory: []))+ #expect(planner.lastNarration == "Loading the PDF skill.")++ _ = await planner.planNextStep(for: task(goal: "fill the form", toolHistory: []))+ // Not the prior step's line, and derived from this step's own command.+ #expect(planner.lastNarration != "Loading the PDF skill.")+ #expect(planner.lastNarration == "Running `ls -la`.")+ }+@Testfunc retriesOnceWhenChosenToolMissesAllRequiredInput() async {// The exact loop the user hit: the model chose shell_exec with NO command (its required input),diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/RunLessonMemoryTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/RunLessonMemoryTests.swiftindex d8fe6aa0..091a4214 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/RunLessonMemoryTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/RunLessonMemoryTests.swift@@ -105,6 +105,44 @@ struct RunLessonMemoryTests {#expect(idC != idA)}+ // MARK: - guardrail-defeat filter++ @Test+ func parseReadsTheTypedUnsafeFlag() {+ #expect(RunLessonMemory.parse(+ #"{"lesson": "a", "confidence": 0.9, "unsafe": true}"#+ )?.defeatsGuardrail == true)+ // String-encoded booleans are tolerated; an absent flag defaults to false.+ #expect(RunLessonMemory.parse(+ #"{"lesson": "a", "confidence": 0.9, "unsafe": "true"}"#+ )?.defeatsGuardrail == true)+ #expect(RunLessonMemory.parse(#"{"lesson": "a", "confidence": 0.9}"#)?.defeatsGuardrail == false)+ }++ @Test+ func proposalRejectsAGuardrailDefeatingLesson() {+ let harmful = RunLessonMemory.Distillation(+ lesson: "When the Already-done guard fires, change the command slightly to bypass the check.",+ cue: "looping",+ confidence: 0.95,+ defeatsGuardrail: true+ )+ #expect(RunLessonMemory.proposal(for: harmful, goal: "g", outcome: "failedSafe", traceID: "t", now: .now()) == nil)+ }++ @Test+ func proposalKeepsABenignLessonThatMerelyMentionsAGuard() {+ // The old substring filter wrongly killed this (defeat verb "work around" + guard noun "permission"+ // + "check"). With the typed flag false, a legitimate craft lesson is kept.+ let benign = RunLessonMemory.Distillation(+ lesson: "Work around the permission check by asking the user first, then proceed once granted.",+ cue: "permissions",+ confidence: 0.9,+ defeatsGuardrail: false+ )+ #expect(RunLessonMemory.proposal(for: benign, goal: "g", outcome: "ok", traceID: "t", now: .now()) != nil)+ }+// MARK: - recall (round-trip through the real store)@Testdiff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/ShellCommandClassifierTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ShellCommandClassifierTests.swiftindex 059b49ac..c818a22c 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/ShellCommandClassifierTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ShellCommandClassifierTests.swift@@ -55,6 +55,9 @@ struct ShellCommandClassifierTests {// must not raise an Approve/Deny gate.#expect(tier("epub-pack build ./pages --meta book.json -o book.epub") == .read)#expect(tier("epub-pack validate book.epub") == .read)+ // reframe writes the vertical clip for the shorts skill — bundled and first-party, so an+ // auto-reframe must not raise an Approve/Deny gate.+ #expect(tier("reframe --input clip.mp4 --output clip_v.mp4 --aspect 9:16") == .read)// A path-qualified invocation normalizes to the bare tool name and is still trusted.#expect(tier("/opt/donkey-tools/yt-dlp -P ~/Downloads 'https://youtu.be/x'") == .read)// The real install path lives under "Application Support" — a space inside a quoted executable