Skip to content

Open source CapCut alternative.

TypeScript

feat(harness): distill and recall durable run lessons

David Lef0e441c965a4
diff --git a/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift b/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift
index 2934ab09..8e268eee 100644
--- a/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift
+++ b/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift
@@ -1,5 +1,6 @@
import DonkeyContracts
import DonkeyHarness
+import DonkeyRuntime
import Foundation
/// The single home for the prompts that define how Donkey behaves — edit agent
@@ -27,7 +28,7 @@ import Foundation
/// - Narrow task adapters keep their specialized prompts next to their parsing:
/// `VisionActionPlanner`, `GeminiVertexVisionBoxPlanner`,
/// `DebugUIInspectionHostedAdapter`, `HostedAppleScriptGenerationAdapter`,
-/// `HostedTaskFollowUpResolver`, and `HostedLocalAppCatalogProfileGenerator`.
+/// `HostedConversationFollowUpResolver`, and `HostedLocalAppCatalogProfileGenerator`.
public enum DonkeyPrompts {
// MARK: - Realtime command session
@@ -195,6 +196,38 @@ public enum DonkeyPrompts {
/// condensed to "tool → status" so the model never loses sight of its own earlier trajectory.
public static let harnessStepMaxDetailedHistorySteps = 12
+ /// 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
+ /// user's data) and to return an empty lesson when there is nothing worth carrying forward — most
+ /// clean runs teach nothing new, so an empty result is the expected common case.
+ public static func runLessonDistillation(goal: String, outcome: String, thread: String) -> String {
+ """
+ You are reviewing a finished run of a macOS agent to capture what it should LEARN for next time.
+ Read the run and decide whether there is ONE durable, general operating lesson worth remembering —
+ a rule about HOW to work (which tool to reach for, a trap to avoid, a faster path) that would help
+ on FUTURE, different tasks.
+
+ GOAL: \(goal)
+ OUTCOME: \(outcome)
+
+ A good lesson is:
+ - General craft, reusable across tasks — NOT a fact about this specific task, file, app, or person.
+ - Actionable and imperative, addressed to your future self ("When X, do Y, because Z").
+ - Earned by what actually happened here: a mistake that cost time, or a move that clearly worked.
+
+ Do NOT save: anything specific to this user, their files, their data, or this one request; secrets
+ or personal data; a restatement of the goal; or generic advice this run did not actually teach. If
+ the run went smoothly and taught nothing new, return an empty lesson — that is the common case.
+
+ 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>}
+
+ THREAD:
+ \(thread)
+ """
+ }
+
public static func harnessStep(
task: HarnessAgentState,
descriptors: [HarnessToolDescriptor],
@@ -202,6 +235,7 @@ public enum DonkeyPrompts {
appGuidance: String?,
understanding: HarnessRequestUnderstanding?,
skillCatalog: String? = nil,
+ lessons: String? = nil,
rollingContext: String? = nil,
retryNote: String? = nil,
openWindows: [MacWindowTargetCandidate] = []
@@ -266,19 +300,34 @@ public enum DonkeyPrompts {
skillCatalogBlock = ""
}
+ // The command-line tools Donkey bundles and signs, sorted for a stable prompt. Sourced from the
+ // single Swift list so it never drifts. Stated to the planner as guaranteed-present standalone
+ // binaries so it invokes them by bare name instead of probing for them or reaching for a Python /
+ // pip path — both of which trip the consent gate and never run the tool we actually ship.
+ let bundledToolsList = BundledTools.executableNames.sorted().joined(separator: ", ")
+
// Prefer the restated goal parsed once up front; fall back to the raw task goal when no
// understanding was produced.
let restatedGoal = understanding?.restatedGoal
let goalText = (restatedGoal?.isEmpty == false ? restatedGoal : nil) ?? task.goal
let understandingBlock = self.understandingBlock(understanding)
+ // Durable operating lessons recalled from earlier runs with a related goal. Placed high, right
+ // under the goal, so a known trap (e.g. a search that times out) steers the very first step
+ // instead of being re-discovered the hard way. Empty when nothing relevant was learned before.
+ let trimmedLessons = lessons?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ let lessonsBlock = trimmedLessons.isEmpty
+ ? ""
+ : "\nLESSONS FROM PAST RUNS (hard-won operating knowledge from earlier tasks — apply when "
+ + "relevant; they reflect what worked or failed before):\n\(trimmedLessons)\n"
+
return """
You are an expert macOS power user. Choose ONE tool to run next, then you will see the result
and choose again. Work toward the goal in small, verifiable steps. Many tasks are solved
entirely with system tools and have no on-screen UI target; reach for the GUI only when the task
truly needs it.
GOAL: \(goalText)
- \(followUpBlock)\(understandingBlock)\(rollingContextBlock)
+ \(followUpBlock)\(understandingBlock)\(lessonsBlock)\(rollingContextBlock)
\(historyBlock)
\(factsBlock)\(guidanceBlock)\(skillCatalogBlock)\(windowsBlock)
\(elementsBlock)
@@ -292,7 +341,12 @@ public enum DonkeyPrompts {
pmset -g batt, system_profiler, defaults read), and change settings (defaults write,
networksetup). Read-only commands run instantly; state-changing ones ask the user for
one-time or always-allow consent, so propose them freely rather than avoiding them.
- - Discover what's available by DOING, not by guessing or pre-checking. Run the command you
+ - Donkey ships these command-line tools and guarantees them on PATH as standalone binaries —
+ run the one you need by its BARE NAME and nothing else: \(bundledToolsList). They are not
+ Python packages and not optional: never invoke one through `python3 -m …` or `pip`, never
+ run `which`/`--version`/any check to confirm it exists, and never probe first — just use it
+ directly (e.g. `yt-dlp -P ~/Downloads 'URL'`, then `ffmpeg -i in.mp4 …`). Single-quote any URL.
+ - Discover what ELSE is available by DOING, not by guessing or pre-checking. Run the command you
need by bare name; don't probe whether a tool exists first. If it fails with `command not
found`, adapt: reach for another tool that does the job, or — if the task genuinely needs
that one — report what's missing. Never install software or use a package manager (pip,
diff --git a/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift b/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift
index 234e038c..586a6f98 100644
--- a/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift
+++ b/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift
@@ -25,6 +25,10 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {
/// so the planner can route to an authoritative playbook even when no GUI app is the drive target —
/// e.g. playing music or saving a note by script. nil when no skills are installed.
private let skillCatalog: String?
+ /// Durable operating lessons recalled from past runs whose goal resembled this one, pre-formatted as a
+ /// bounded bullet block and rendered into every step's prompt. Computed once at run start (the goal
+ /// doesn't change mid-run), so it's a constant here. nil when nothing relevant was learned before.
+ private let recalledLessons: String?
private let uptimeMS: @Sendable () -> Double
/// Optional turn-trace sink. Every planning call — the first sample, each retry, and the failure
/// shapes (empty reply, content filter, transport error) — is recorded here with its clipped prompt,
@@ -77,6 +81,7 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {
appGuidance: String?,
understanding: HarnessRequestUnderstanding? = nil,
skillCatalog: String? = nil,
+ recalledLessons: String? = nil,
trace: (any HarnessTurnTracing)? = nil,
openWindows: @escaping @Sendable () -> [MacWindowTargetCandidate] = { [] },
captureScreenshot: @escaping @Sendable () async -> String? = { nil },
@@ -88,6 +93,7 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {
self.appGuidance = appGuidance
self.understanding = understanding
self.skillCatalog = skillCatalog
+ self.recalledLessons = recalledLessons
self.trace = trace
self.openWindows = openWindows
self.captureScreenshot = captureScreenshot
@@ -379,6 +385,7 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {
appGuidance: appGuidance,
understanding: understanding,
skillCatalog: skillCatalog,
+ lessons: recalledLessons,
rollingContext: rollingContext,
retryNote: retryNote,
openWindows: openWindows()
diff --git a/apps/Donkey/Sources/DonkeyContracts/HarnessTraceContracts.swift b/apps/Donkey/Sources/DonkeyContracts/HarnessTraceContracts.swift
index d89aedbb..a4af7efe 100644
--- a/apps/Donkey/Sources/DonkeyContracts/HarnessTraceContracts.swift
+++ b/apps/Donkey/Sources/DonkeyContracts/HarnessTraceContracts.swift
@@ -12,6 +12,8 @@ public enum TraceModelCallKind: String, Codable, Equatable, Sendable {
case conversationalReply
/// The background call that rewrites the compacted thread summary.
case conversationSummary
+ /// The background call that distills a finished run into a durable operating lesson for next time.
+ case lessonDistillation
}
/// What came back from a model call. Distinguishes the failure shapes the planner already separates
diff --git a/apps/Donkey/Sources/DonkeyRuntime/HarnessTurnTrace.swift b/apps/Donkey/Sources/DonkeyRuntime/HarnessTurnTrace.swift
index b13d6f78..00ee68bc 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/HarnessTurnTrace.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/HarnessTurnTrace.swift
@@ -128,6 +128,7 @@ public final class HarnessTurnTrace: HarnessTurnTracing, @unchecked Sendable {
case .plannerStep: return "planner step"
case .conversationalReply: return "conversational reply"
case .conversationSummary: return "thread summary"
+ case .lessonDistillation: return "lesson distillation"
}
}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/RunLessonMemory.swift b/apps/Donkey/Sources/DonkeyRuntime/RunLessonMemory.swift
new file mode 100644
index 00000000..f935a4b7
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/RunLessonMemory.swift
@@ -0,0 +1,162 @@
+import DonkeyContracts
+import Foundation
+
+/// Turns a finished run into durable, recallable operating knowledge — the write-and-recall halves of
+/// the harness's self-improving loop. A run that struggled or failed is distilled (by an LLM, upstream)
+/// into one general operating lesson; that lesson is stored as a durable global memory and surfaced to
+/// the planner on later turns whose goal is related, so the agent stops repeating a mistake it has
+/// already paid for once.
+///
+/// The store, approval gate, and ranked retrieval are the existing agent-memory machinery. This type
+/// only frames lessons within it: how a lesson is parsed from the distiller, how it becomes a deduped
+/// write proposal, and how past lessons render into a bounded prompt block. Lessons reuse the
+/// `workflowMemory` kind (a learned operating procedure) and carry a `lesson:` id prefix so recall pulls
+/// only lessons, never any other workflow record that kind may someday hold.
+public enum RunLessonMemory {
+ /// The distiller's structured verdict for one finished run.
+ public struct Distillation: Equatable, Sendable {
+ /// One imperative operating rule for the agent's future self. Empty means "nothing worth saving".
+ public var lesson: String
+ /// A short phrase naming the kind of task the lesson applies to — extra retrieval text so a
+ /// future goal matches the lesson even when its wording differs from the original run's goal.
+ public var cue: String
+ /// The model's 0–1 confidence that this is a real, general lesson.
+ public var confidence: Double
+
+ public init(lesson: String, cue: String, confidence: Double) {
+ self.lesson = lesson
+ self.cue = cue
+ self.confidence = min(max(confidence, 0), 1)
+ }
+ }
+
+ /// A lesson is a learned operating procedure; reuse that kind rather than growing the enum.
+ static let kind: AgentMemoryKind = .workflowMemory
+ /// Records carry this id prefix so recall fetches only lessons out of the shared kind.
+ static let idPrefix = "lesson:"
+ /// A lesson must clear this confidence to be written — keeps low-signal guesses out of memory.
+ static let minWriteConfidence = 0.55
+ /// Recall stays small so lessons inform the planner without crowding the per-step prompt.
+ static let recallBudget = AgentMemoryRetrievalBudget(
+ maxRecords: 4,
+ maxPromptCharacters: 800,
+ minRelevance: 0.18
+ )
+
+ /// Parse the distiller's JSON reply. Returns nil when the reply is unusable or carries no lesson, so
+ /// the caller simply writes nothing — the common case for a clean run.
+ public static func parse(_ raw: String) -> Distillation? {
+ guard let data = jsonObjectData(in: raw),
+ let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
+ else {
+ return nil
+ }
+ let lesson = ((object["lesson"] as? String) ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !lesson.isEmpty else { return nil }
+ let cue = ((object["cue"] as? String) ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ let confidence = (object["confidence"] as? Double)
+ ?? (object["confidence"] as? Int).map(Double.init)
+ ?? (object["confidence"] as? String).flatMap(Double.init)
+ ?? 0
+ return Distillation(lesson: lesson, cue: cue, confidence: confidence)
+ }
+
+ /// Build a durable global lesson proposal, deduped by lesson content so re-learning the same rule
+ /// refreshes the one record instead of piling up copies. Returns nil for an empty or low-confidence
+ /// lesson, so the caller skips the write. The `cue` and originating goal ride along as metadata and
+ /// search text, broadening the goals a future turn can match the lesson against.
+ public static func proposal(
+ for distillation: Distillation,
+ goal: String,
+ outcome: String,
+ traceID: String,
+ now: RunTraceTimestamp
+ ) -> AgentMemoryWriteProposal? {
+ let lesson = distillation.lesson.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !lesson.isEmpty, distillation.confidence >= minWriteConfidence else { return nil }
+
+ let id = idPrefix + stableHash(normalized(lesson))
+ var metadata = ["lesson": "true", "outcome": outcome]
+ if !distillation.cue.isEmpty { metadata["cue"] = distillation.cue }
+ let trimmedGoal = goal.trimmingCharacters(in: .whitespacesAndNewlines)
+ if !trimmedGoal.isEmpty { metadata["learnedFromGoal"] = String(trimmedGoal.prefix(200)) }
+
+ let record = AgentMemoryRecord(
+ id: id,
+ scope: .global,
+ kind: kind,
+ value: lesson,
+ createdAt: now,
+ durable: true,
+ source: AgentMemorySource(traceID: traceID, summary: "post-run lesson distillation"),
+ metadata: metadata,
+ confidence: distillation.confidence
+ )
+ return AgentMemoryWriteProposal(
+ id: id,
+ proposedBy: .model,
+ record: record,
+ rationale: "Operating lesson distilled from run \(traceID) (outcome=\(outcome))."
+ )
+ }
+
+ /// Recall the most relevant past lessons for a goal, formatted as a bounded prompt block, or nil when
+ /// there are none. Ranking, scoping, and budgeting are the store's; this only filters the ranked
+ /// results to lesson records and frames them as a bullet list.
+ public static func recall(
+ forGoal goal: String,
+ store: SQLiteAgentMemoryStore?,
+ now: RunTraceTimestamp = .now()
+ ) -> String? {
+ let trimmedGoal = goal.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmedGoal.isEmpty, let store else { return nil }
+
+ let query = AgentMemoryQuery(
+ text: trimmedGoal,
+ scope: .global,
+ kinds: [kind],
+ budget: recallBudget
+ )
+ let lessons = ((try? store.search(query: query)) ?? [])
+ .map(\.record)
+ .filter { $0.id.hasPrefix(idPrefix) }
+ .map { $0.value.trimmingCharacters(in: .whitespacesAndNewlines) }
+ .filter { !$0.isEmpty }
+ guard !lessons.isEmpty else { return nil }
+ return lessons.map { "- \($0)" }.joined(separator: "\n")
+ }
+
+ // MARK: - Helpers
+
+ /// Lowercased, whitespace-collapsed lesson text, so trivially different phrasings of the same rule
+ /// hash to one id and dedup to a single record.
+ static func normalized(_ text: String) -> String {
+ text.lowercased()
+ .components(separatedBy: .whitespacesAndNewlines)
+ .filter { !$0.isEmpty }
+ .joined(separator: " ")
+ }
+
+ /// FNV-1a over the UTF-8 bytes — a stable, process-independent hash. Swift's `Hasher` is seeded per
+ /// process, so it cannot key a durable record id that must stay constant across launches.
+ static func stableHash(_ text: String) -> String {
+ var hash: UInt64 = 0xcbf2_9ce4_8422_2325
+ for byte in text.utf8 {
+ hash ^= UInt64(byte)
+ hash = hash &* 0x100_0000_01b3
+ }
+ return String(hash, radix: 16)
+ }
+
+ /// Extract the first balanced top-level JSON object from a reply that may be fenced or prefixed with
+ /// prose. Returns nil when there is no `{ … }` span.
+ private static func jsonObjectData(in text: String) -> Data? {
+ guard let start = text.firstIndex(of: "{"),
+ let end = text.lastIndex(of: "}"),
+ start < end
+ else {
+ return nil
+ }
+ return String(text[start...end]).data(using: .utf8)
+ }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/RunLessonMemoryTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/RunLessonMemoryTests.swift
new file mode 100644
index 00000000..d8fe6aa0
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/RunLessonMemoryTests.swift
@@ -0,0 +1,177 @@
+import DonkeyContracts
+@testable import DonkeyRuntime
+import Foundation
+import Testing
+
+@Suite
+struct RunLessonMemoryTests {
+ // MARK: - parse
+
+ @Test
+ func parsesCleanLessonJSON() {
+ let raw = #"{"lesson": "Use mdfind to locate files.", "cue": "finding files", "confidence": 0.8}"#
+ let distillation = RunLessonMemory.parse(raw)
+ #expect(distillation?.lesson == "Use mdfind to locate files.")
+ #expect(distillation?.cue == "finding files")
+ #expect(distillation?.confidence == 0.8)
+ }
+
+ @Test
+ func parsesLessonFromFencedOrPrefixedReply() {
+ let raw = """
+ Here is the lesson:
+ ```json
+ {"lesson": "Prefer mdfind over a broad find.", "cue": "file search", "confidence": 0.7}
+ ```
+ """
+ let distillation = RunLessonMemory.parse(raw)
+ #expect(distillation?.lesson == "Prefer mdfind over a broad find.")
+ #expect(distillation?.confidence == 0.7)
+ }
+
+ @Test
+ func parseReturnsNilForEmptyLesson() {
+ #expect(RunLessonMemory.parse(#"{"lesson": "", "cue": "x", "confidence": 0.9}"#) == nil)
+ #expect(RunLessonMemory.parse(#"{"lesson": " ", "confidence": 0.9}"#) == nil)
+ }
+
+ @Test
+ func parseReturnsNilForUnusableReply() {
+ #expect(RunLessonMemory.parse("no json here") == nil)
+ #expect(RunLessonMemory.parse("") == nil)
+ }
+
+ @Test
+ func parseAcceptsConfidenceAsIntOrString() {
+ #expect(RunLessonMemory.parse(#"{"lesson": "a", "confidence": 1}"#)?.confidence == 1)
+ #expect(RunLessonMemory.parse(#"{"lesson": "a", "confidence": "0.6"}"#)?.confidence == 0.6)
+ // Missing confidence defaults to 0 (and would be rejected at write time).
+ #expect(RunLessonMemory.parse(#"{"lesson": "a"}"#)?.confidence == 0)
+ }
+
+ @Test
+ func parseClampsConfidenceToUnitRange() {
+ #expect(RunLessonMemory.parse(#"{"lesson": "a", "confidence": 5}"#)?.confidence == 1)
+ #expect(RunLessonMemory.parse(#"{"lesson": "a", "confidence": -3}"#)?.confidence == 0)
+ }
+
+ // MARK: - proposal
+
+ @Test
+ func proposalBuildsDurableGlobalLessonRecord() {
+ let distillation = RunLessonMemory.Distillation(
+ lesson: "Use mdfind to locate a named file.",
+ cue: "finding files",
+ confidence: 0.9
+ )
+ let proposal = RunLessonMemory.proposal(
+ for: distillation,
+ goal: "fill out a form",
+ outcome: "failedSafe",
+ traceID: "trace-1",
+ now: .now()
+ )
+ let record = proposal?.record
+ #expect(record?.scope == .global)
+ #expect(record?.kind == .workflowMemory)
+ #expect(record?.durable == true)
+ #expect(record?.id.hasPrefix("lesson:") == true)
+ #expect(record?.value == "Use mdfind to locate a named file.")
+ #expect(record?.source.traceID == "trace-1")
+ #expect(record?.source.isLinked == true)
+ #expect(record?.metadata["lesson"] == "true")
+ #expect(record?.metadata["outcome"] == "failedSafe")
+ #expect(record?.metadata["cue"] == "finding files")
+ #expect(proposal?.proposedBy == .model)
+ }
+
+ @Test
+ func proposalRejectsLowConfidence() {
+ let weak = RunLessonMemory.Distillation(lesson: "Maybe do X.", cue: "", confidence: 0.4)
+ #expect(RunLessonMemory.proposal(for: weak, goal: "g", outcome: "ok", traceID: "t", now: .now()) == nil)
+ }
+
+ @Test
+ func proposalDedupsByNormalizedLessonText() {
+ let a = RunLessonMemory.Distillation(lesson: "Use mdfind to locate files.", cue: "x", confidence: 0.9)
+ let b = RunLessonMemory.Distillation(lesson: " use MDFIND to LOCATE files. ", cue: "y", confidence: 0.7)
+ let idA = RunLessonMemory.proposal(for: a, goal: "g", outcome: "ok", traceID: "t1", now: .now())?.record.id
+ let idB = RunLessonMemory.proposal(for: b, goal: "g", outcome: "ok", traceID: "t2", now: .now())?.record.id
+ #expect(idA != nil)
+ #expect(idA == idB)
+
+ let c = RunLessonMemory.Distillation(lesson: "A different lesson entirely.", cue: "z", confidence: 0.9)
+ let idC = RunLessonMemory.proposal(for: c, goal: "g", outcome: "ok", traceID: "t3", now: .now())?.record.id
+ #expect(idC != idA)
+ }
+
+ // MARK: - recall (round-trip through the real store)
+
+ @Test
+ func recallSurfacesAStoredLessonForARelatedGoal() throws {
+ let root = temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let store = try SQLiteAgentMemoryStore(baseDirectory: root, cleanupLegacyStores: false)
+
+ let distillation = RunLessonMemory.Distillation(
+ lesson: "When locating a named file on macOS, use mdfind rather than a broad recursive find.",
+ cue: "locating files on macOS",
+ confidence: 0.9
+ )
+ let proposal = try #require(
+ RunLessonMemory.proposal(
+ for: distillation,
+ goal: "find a file",
+ outcome: "failedSafe",
+ traceID: "trace-1",
+ now: .now()
+ )
+ )
+ _ = try store.appendApprovedProposal(proposal, decidedAt: .now())
+
+ let block = RunLessonMemory.recall(forGoal: "locate a named file on macOS with mdfind", store: store)
+ #expect(block?.contains("use mdfind rather than a broad recursive find") == true)
+ #expect(block?.hasPrefix("- ") == true)
+ }
+
+ @Test
+ func recallIgnoresNonLessonWorkflowRecords() throws {
+ let root = temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let store = try SQLiteAgentMemoryStore(baseDirectory: root, cleanupLegacyStores: false)
+
+ // A workflowMemory record that is NOT a lesson (no `lesson:` id prefix) must never leak into recall.
+ let nonLesson = AgentMemoryRecord(
+ id: "workflow:locate-files",
+ scope: .global,
+ kind: .workflowMemory,
+ value: "Some other workflow about locating files on macOS with mdfind.",
+ createdAt: .now(),
+ durable: true,
+ source: AgentMemorySource(traceID: "trace-x", summary: "not a lesson")
+ )
+ try store.upsert(nonLesson)
+
+ let block = RunLessonMemory.recall(forGoal: "locate files on macOS with mdfind", store: store)
+ #expect(block == nil)
+ }
+
+ @Test
+ func recallReturnsNilWhenStoreHasNoLessons() throws {
+ let root = temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let store = try SQLiteAgentMemoryStore(baseDirectory: root, cleanupLegacyStores: false)
+ #expect(RunLessonMemory.recall(forGoal: "anything at all", store: store) == nil)
+ #expect(RunLessonMemory.recall(forGoal: "", store: store) == nil)
+ #expect(RunLessonMemory.recall(forGoal: "x", store: nil) == nil)
+ }
+
+ // MARK: - Helpers
+
+ private func temporaryDirectory() -> URL {
+ FileManager.default.temporaryDirectory.appendingPathComponent(
+ "DonkeyRunLessonMemoryTests-\(UUID().uuidString)",
+ isDirectory: true
+ )
+ }
+}