Skip to content

Open source CapCut alternative.

TypeScript

feat(app): add files.describe file-understanding tool

David Lea69f593f727a
diff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
index 50d5d32f..1173eaa6 100644
--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
@@ -374,6 +374,10 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
let hostedWebFetch = HostedWebFetch(backend: backend)
harnessServices.webSearcher = { query in await hostedWebSearch.search(query) }
harnessServices.webFetcher = { url in await hostedWebFetch.fetch(url) }
+ // File understanding behind files.describe: OCR + dimensions for images/screenshots, text for
+ // PDFs, Foundation content for text files. Cached per file so the describe pass and any later
+ // operation reuse one understanding.
+ harnessServices.fileUnderstanding = { url in await FileUnderstandingProvider.understand(url) }
let granted = Self.userQueryGrantedPermissions
let replacedBuiltIns: Set<String> = ["screen.observe", "elements.get", "element.perform", "text.enter", "keyboard.press"]
let builtInDescriptors = BuiltInHarnessToolCatalog.descriptors.filter { descriptor in
diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift
index b50f5024..659a7498 100644
--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift
+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift
@@ -248,6 +248,11 @@ public struct HarnessBuiltInToolServices: Sendable {
/// Web fetch/navigation: a URL in, the page's readable text out, or nil on failure. Backs the
/// `web.fetch` tool so the agent can read a page it found or was given.
public var webFetcher: (@Sendable (String) async -> String?)?
+ /// The file-understanding layer behind `files.describe`: a file URL in, a structured
+ /// `FileUnderstanding` out (OCR for images, text for PDFs, dimensions/metadata), or nil to fall
+ /// back to the built-in Foundation understanding. The runtime supplies this; without it the tool
+ /// still understands text files from their content.
+ public var fileUnderstanding: (@Sendable (URL) async -> FileUnderstanding?)?
public init(
memoryEntries: [HarnessMemoryEntry] = [],
@@ -263,7 +268,8 @@ public struct HarnessBuiltInToolServices: Sendable {
commandExecutor: (@Sendable (HarnessToolExecutionContext) async -> HarnessToolResult?)? = nil,
textGenerator: (@Sendable (String) async -> String?)? = nil,
webSearcher: (@Sendable (String) async -> String?)? = nil,
- webFetcher: (@Sendable (String) async -> String?)? = nil
+ webFetcher: (@Sendable (String) async -> String?)? = nil,
+ fileUnderstanding: (@Sendable (URL) async -> FileUnderstanding?)? = nil
) {
self.memoryEntries = memoryEntries
self.skillRegistry = skillRegistry
@@ -279,6 +285,7 @@ public struct HarnessBuiltInToolServices: Sendable {
self.textGenerator = textGenerator
self.webSearcher = webSearcher
self.webFetcher = webFetcher
+ self.fileUnderstanding = fileUnderstanding
}
}
@@ -355,6 +362,8 @@ public enum BuiltInHarnessToolExecutors {
return await webSearch(context, services: services)
case "web.fetch":
return await webFetch(context, services: services)
+ case "files.describe":
+ return await filesDescribe(context, services: services)
case "wait":
return await timingWait(context)
case "run.pause", "run.resume", "run.recover", "run.cancel", "run.complete", "run.failSafe":
diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessFileTools.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessFileTools.swift
new file mode 100644
index 00000000..46ac81cc
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessFileTools.swift
@@ -0,0 +1,125 @@
+import Foundation
+
+/// The file-understanding layer as a tool. `files.describe` turns a batch of files into structured
+/// understanding (kind, summary, extracted text, attributes); the planner then composes the actual
+/// operation from general primitives — `llm.generate` to decide names/labels/tags from the
+/// understanding, `shell_exec` (`mv`, `sips`, `ffmpeg`) to apply it, `state.verify` to confirm.
+///
+/// There is deliberately NO per-operation file tool. Understanding is a real primitive because reading
+/// content across modalities is hard; the operation ("rename these", "resize those") is just the model
+/// reasoning over that understanding, the same way it reasons about any other goal. A `files.rename`
+/// or `files.suggest_names` tool would hardcode one ask into the registry — exactly what the planner's
+/// general reasoning is supposed to replace.
+public enum FileToolSupport {
+ static let defaultMaxFiles = 50
+ static let hardMaxFiles = 200
+
+ /// The files to describe: an explicit `paths` list wins; otherwise the regular (non-hidden,
+ /// non-dir) files directly inside `directory`, capped at `maxFiles`. Returns the URLs and whether
+ /// the cap truncated the set.
+ public static func resolveFiles(
+ directory: String?,
+ paths: [String],
+ maxFiles: Int,
+ fileManager: FileManager = .default
+ ) -> (files: [URL], truncated: Bool) {
+ var resolved: [URL] = []
+ if !paths.isEmpty {
+ resolved = paths.map { URL(fileURLWithPath: ($0 as NSString).expandingTildeInPath) }
+ } else if let directory, !directory.isEmpty {
+ let dirURL = URL(fileURLWithPath: (directory as NSString).expandingTildeInPath)
+ let contents = (try? fileManager.contentsOfDirectory(
+ at: dirURL,
+ includingPropertiesForKeys: [.isRegularFileKey],
+ options: [.skipsHiddenFiles]
+ )) ?? []
+ resolved = contents
+ .filter { url in
+ (try? url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true
+ }
+ .sorted { $0.lastPathComponent < $1.lastPathComponent }
+ }
+ let cap = min(max(maxFiles, 1), hardMaxFiles)
+ guard resolved.count > cap else { return (resolved, false) }
+ return (Array(resolved.prefix(cap)), true)
+ }
+}
+
+extension BuiltInHarnessToolExecutors {
+ /// The understanding path behind `files.describe`: the runtime's `fileUnderstanding` hook (OCR for
+ /// images, text for PDFs, …) gets first crack; otherwise the deterministic Foundation understanding.
+ static func understanding(
+ for url: URL,
+ services: HarnessBuiltInToolServices
+ ) async -> FileUnderstanding {
+ if let hook = services.fileUnderstanding, let understood = await hook(url) {
+ return understood
+ }
+ return FileUnderstandingEngine.foundationUnderstanding(for: url)
+ }
+
+ /// `files.describe`: resolve files and return one structured `FileUnderstanding` each so the planner
+ /// can reason about what files contain before deciding any operation. Read-only sensing.
+ static func filesDescribe(
+ _ context: HarnessToolExecutionContext,
+ services: HarnessBuiltInToolServices
+ ) async -> HarnessToolResult {
+ let directory = context.call.input["directory"]?.trimmingCharacters(in: .whitespacesAndNewlines)
+ let paths = (context.call.input["paths"])
+ .map { $0.split { $0 == "\n" || $0 == "," }.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty } }
+ ?? []
+ guard (directory?.isEmpty == false) || !paths.isEmpty else {
+ return HarnessToolResult(
+ callID: context.call.id,
+ toolName: context.call.name,
+ status: .invalidInput,
+ summary: "files.describe requires a `directory` or a `paths` list.",
+ metadata: ["executor": "builtInGeneric", "reason": "invalidInput"]
+ )
+ }
+ let maxFiles = context.call.input["maxFiles"].flatMap(Int.init) ?? FileToolSupport.defaultMaxFiles
+ let (files, truncated) = FileToolSupport.resolveFiles(directory: directory, paths: paths, maxFiles: maxFiles)
+ guard !files.isEmpty else {
+ return HarnessToolResult(
+ callID: context.call.id,
+ toolName: context.call.name,
+ status: .failed,
+ summary: "No files found to describe.",
+ metadata: ["executor": "builtInGeneric", "reason": "noFilesFound"]
+ )
+ }
+
+ var understandings: [FileUnderstanding] = []
+ for url in files {
+ understandings.append(await understanding(for: url, services: services))
+ }
+
+ let encoder = JSONEncoder()
+ encoder.outputFormatting = [.sortedKeys]
+ let json = (try? encoder.encode(understandings)).flatMap { String(data: $0, encoding: .utf8) } ?? "[]"
+ let preview = understandings.prefix(10)
+ .map { "\($0.fileName): \($0.summary)" }
+ .joined(separator: "\n")
+ return HarnessToolResult(
+ callID: context.call.id,
+ toolName: context.call.name,
+ status: .succeeded,
+ summary: truncated
+ ? "Described \(understandings.count) file(s) (capped).\n\(preview)"
+ : "Described \(understandings.count) file(s).\n\(preview)",
+ observations: HarnessObservationDelta(
+ facts: [
+ "files.describe.count": String(understandings.count),
+ "files.describe.truncated": String(truncated),
+ "lastAcceptedTool": context.call.name
+ ]
+ ),
+ metadata: [
+ "executor": "builtInGeneric",
+ "understanding": json,
+ "count": String(understandings.count),
+ "truncated": String(truncated)
+ ]
+ )
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessFileUnderstanding.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessFileUnderstanding.swift
new file mode 100644
index 00000000..b4864f38
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessFileUnderstanding.swift
@@ -0,0 +1,153 @@
+import Foundation
+import UniformTypeIdentifiers
+
+/// A modality-agnostic, structured description of one file — the output of the file-understanding
+/// layer that every file "ask" (rename, tag, sort, summarize, …) consumes. Understanding is the hard,
+/// reusable half of working with files; the ask is the cheap, swappable half. Keeping them separate
+/// means a new ask reuses this verbatim, and a new modality (audio, video) only extends the router
+/// that fills this in.
+///
+/// `textContent` is bounded extracted text — file body, OCR, or (later) a transcript — and may be
+/// empty for content with no readable text. `summary` is a short line safe to show or feed a model
+/// even when there is no text. Richer fields land in `attributes` (dimensions, duration, dates).
+public struct FileUnderstanding: Sendable, Equatable, Codable {
+ public enum Kind: String, Sendable, Codable {
+ case text, image, pdf, audio, video, binary, unknown
+ }
+
+ public var path: String
+ public var fileName: String
+ public var fileExtension: String
+ public var kind: Kind
+ public var byteSize: Int?
+ public var textContent: String
+ public var summary: String
+ public var attributes: [String: String]
+
+ public init(
+ path: String,
+ fileName: String,
+ fileExtension: String,
+ kind: Kind,
+ byteSize: Int? = nil,
+ textContent: String = "",
+ summary: String = "",
+ attributes: [String: String] = [:]
+ ) {
+ self.path = path
+ self.fileName = fileName
+ self.fileExtension = fileExtension
+ self.kind = kind
+ self.byteSize = byteSize
+ self.textContent = textContent
+ self.summary = summary
+ self.attributes = attributes
+ }
+
+ /// The bounded signal an ask hands to a model: the extracted text when there is any, otherwise the
+ /// deterministic summary so even a text-free file (a photo, an archive) still carries something to
+ /// reason about.
+ public func contentForReasoning(limit: Int) -> String {
+ let body = textContent.isEmpty ? summary : textContent
+ guard body.count > limit else { return body }
+ return String(body.prefix(limit))
+ }
+}
+
+/// The file-understanding router's deterministic, always-available core: classify a file by modality
+/// and build a Foundation-only understanding (text body for text files, metadata for everything else).
+/// Richer modality work — OCR for images, text for PDFs, later transcription for audio/video — is
+/// supplied by the runtime through the tool's `fileUnderstanding` hook, which starts from this base
+/// and enriches it. Routing lives here so the set of modalities is one obvious place to extend.
+public enum FileUnderstandingEngine {
+ static let textReadByteLimit = 64 * 1024
+ public static let textContentCharLimit = 1_500
+
+ /// Modality from the extension, resolved through the OS Uniform Type registry rather than a
+ /// hand-maintained list: `UTType` already knows that `.heic` is an image and `.mkv` is a movie,
+ /// and stays correct as the system learns new types. An extensionless or unrecognized file falls
+ /// through to content sniffing in `foundationUnderstanding`. This is type detection, not semantic
+ /// intent — a typed-field lookup, never a model call.
+ public static func classify(fileExtension: String) -> FileUnderstanding.Kind {
+ guard let type = UTType(filenameExtension: fileExtension.lowercased()) else {
+ return .unknown
+ }
+ if type.conforms(to: .pdf) { return .pdf }
+ if type.conforms(to: .image) { return .image }
+ if type.conforms(to: .movie) || type.conforms(to: .video) { return .video }
+ if type.conforms(to: .audio) { return .audio }
+ if type.conforms(to: .text) { return .text }
+ return .unknown
+ }
+
+ public static func foundationUnderstanding(
+ for url: URL,
+ fileManager: FileManager = .default
+ ) -> FileUnderstanding {
+ let ext = url.pathExtension
+ var kind = classify(fileExtension: ext)
+ let attrs = try? fileManager.attributesOfItem(atPath: url.path)
+ let byteSize = (attrs?[.size] as? NSNumber)?.intValue
+ var attributes: [String: String] = [:]
+ if let modified = attrs?[.modificationDate] as? Date {
+ attributes["modified"] = ISO8601DateFormatter().string(from: modified)
+ }
+
+ var textContent = ""
+ if kind == .text || kind == .unknown {
+ if let data = readBounded(url), let text = decodeText(data) {
+ textContent = boundedText(text)
+ kind = .text
+ } else if kind == .unknown {
+ kind = .binary
+ }
+ }
+
+ return FileUnderstanding(
+ path: url.path,
+ fileName: url.lastPathComponent,
+ fileExtension: ext,
+ kind: kind,
+ byteSize: byteSize,
+ textContent: textContent,
+ summary: summaryLine(kind: kind, fileExtension: ext, byteSize: byteSize, hasText: !textContent.isEmpty, attributes: attributes),
+ attributes: attributes
+ )
+ }
+
+ public static func summaryLine(
+ kind: FileUnderstanding.Kind,
+ fileExtension: String,
+ byteSize: Int?,
+ hasText: Bool,
+ attributes: [String: String]
+ ) -> String {
+ var parts = ["\(kind.rawValue)\(fileExtension.isEmpty ? "" : " (.\(fileExtension.lowercased()))")"]
+ if let dimensions = attributes["dimensions"] { parts.append(dimensions) }
+ if let duration = attributes["duration"] { parts.append(duration) }
+ if let byteSize { parts.append("\(byteSize) bytes") }
+ if !hasText, kind != .text { parts.append("no readable text content") }
+ return parts.joined(separator: ", ")
+ }
+
+ static func readBounded(_ url: URL) -> Data? {
+ guard let handle = try? FileHandle(forReadingFrom: url) else { return nil }
+ defer { try? handle.close() }
+ return try? handle.read(upToCount: textReadByteLimit)
+ }
+
+ /// Text, or nil for binary. A NUL byte in the sampled prefix is the reliable binary tell; UTF-8
+ /// then Latin-1 (which never fails) is the fallback only after that check rules out true binary.
+ static func decodeText(_ data: Data) -> String? {
+ guard !data.isEmpty else { return nil }
+ if data.prefix(8_000).contains(0) { return nil }
+ if let utf8 = String(data: data, encoding: .utf8) { return utf8 }
+ return String(data: data, encoding: .isoLatin1)
+ }
+
+ public static func boundedText(_ text: String) -> String {
+ let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard trimmed.count > textContentCharLimit else { return trimmed }
+ return String(trimmed.prefix(textContentCharLimit))
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift
index f33795c0..6aebd3c0 100644
--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift
+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift
@@ -513,6 +513,25 @@ public enum BuiltInHarnessToolCatalog {
verification: ["the returned text (or file) contains the requested content"],
metadata: [HarnessToolDescriptor.resultIsEvidenceMetadataKey: "true"]
),
+ descriptor(
+ "files.describe",
+ pluginID: "core.files",
+ summary: "Understand a batch of files: for a `directory` (or explicit `paths`) it returns one structured description per file — kind (text/image/pdf/audio/video/binary), a summary, extracted text (OCR for images, text for PDFs), byte size, and attributes like dimensions. This is the file-understanding layer every file task builds on: call it first to learn what files contain, then carry out the operation yourself with general tools — `llm.generate` to decide new names/labels from the content, `shell_exec` to apply (`mv` to rename, `sips`/`ffmpeg` to resize/convert), and verify. Read-only — it changes nothing.",
+ input: [
+ "directory": "Folder whose files should be described (every regular, non-hidden file in it).",
+ "paths": "Explicit comma/newline-separated file paths to describe instead of a whole directory.",
+ "maxFiles": "Optional cap on how many files to process (default 50, max 200)."
+ ],
+ output: [
+ "understanding": "JSON array of {path, fileName, kind, summary, textContent, byteSize, attributes} per file.",
+ "count": "How many files were described."
+ ],
+ optionalInputKeys: ["directory", "paths", "maxFiles"],
+ permissions: [],
+ safety: .sensitive,
+ verification: ["the returned understanding covers the requested files"],
+ metadata: [HarnessToolDescriptor.resultIsEvidenceMetadataKey: "true"]
+ ),
descriptor(
"web.search",
pluginID: "core.web",
@@ -624,6 +643,7 @@ public enum BuiltInHarnessToolCatalog {
summary: String,
input: [String: String] = [:],
output: [String: String] = [:],
+ optionalInputKeys: [String] = [],
permissions: [HarnessPermission],
safety: HarnessToolSafetyClass,
requiredContext: [String] = [],
@@ -635,6 +655,7 @@ public enum BuiltInHarnessToolCatalog {
pluginID: pluginID,
summary: summary,
inputSchema: input,
+ optionalInputKeys: optionalInputKeys,
outputSchema: output,
requiredPermissions: permissions,
safetyClass: safety,
diff --git a/apps/Donkey/Sources/DonkeyRuntime/FileUnderstandingProvider.swift b/apps/Donkey/Sources/DonkeyRuntime/FileUnderstandingProvider.swift
new file mode 100644
index 00000000..d0298b2a
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/FileUnderstandingProvider.swift
@@ -0,0 +1,143 @@
+import CoreGraphics
+import DonkeyHarness
+import Foundation
+import ImageIO
+import PDFKit
+import Vision
+
+/// The runtime side of the file-understanding layer (behind the harness `fileUnderstanding` hook).
+/// It starts from the deterministic Foundation understanding and enriches the richer modalities:
+/// images get Vision OCR plus pixel dimensions, PDFs get their text. Audio and video are recognized
+/// as kinds but not yet transcribed — that branch is where transcription/keyframe work will plug in.
+///
+/// Results are cached per file identity (path + size + modification date) in a shared actor, so the
+/// expensive step (OCR) runs once and every later ask — describe, then rename — reuses it.
+public enum FileUnderstandingProvider {
+ static let characterLimit = FileUnderstandingEngine.textContentCharLimit
+
+ public static func understand(_ url: URL) async -> FileUnderstanding? {
+ let identity = FileUnderstandingCache.identity(for: url)
+ if let identity, let cached = await FileUnderstandingCache.shared.value(for: identity) {
+ return cached
+ }
+ let understanding = await Task.detached(priority: .utility) { enrichedUnderstanding(url) }.value
+ if let identity {
+ await FileUnderstandingCache.shared.store(understanding, for: identity)
+ }
+ return understanding
+ }
+
+ static func enrichedUnderstanding(_ url: URL) -> FileUnderstanding {
+ var understanding = FileUnderstandingEngine.foundationUnderstanding(for: url)
+ switch understanding.kind {
+ case .image:
+ if let dimensions = imageDimensions(url) {
+ understanding.attributes["dimensions"] = dimensions
+ }
+ if let text = recognizeText(in: url) {
+ understanding.textContent = text
+ }
+ case .pdf:
+ if let text = pdfText(in: url) {
+ understanding.textContent = text
+ }
+ case .text, .audio, .video, .binary, .unknown:
+ break
+ }
+ understanding.summary = FileUnderstandingEngine.summaryLine(
+ kind: understanding.kind,
+ fileExtension: understanding.fileExtension,
+ byteSize: understanding.byteSize,
+ hasText: !understanding.textContent.isEmpty,
+ attributes: understanding.attributes
+ )
+ return understanding
+ }
+
+ static func imageDimensions(_ url: URL) -> String? {
+ guard let source = CGImageSourceCreateWithURL(url as CFURL, nil),
+ let props = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],
+ let width = props[kCGImagePropertyPixelWidth] as? Int,
+ let height = props[kCGImagePropertyPixelHeight] as? Int
+ else {
+ return nil
+ }
+ return "\(width)x\(height)"
+ }
+
+ /// On-device OCR of an image. Returns recognized lines, or nil when the image has no readable text
+ /// (e.g. a photo) so understanding falls back to dimensions/metadata rather than empty text.
+ static func recognizeText(in url: URL) -> String? {
+ guard let source = CGImageSourceCreateWithURL(url as CFURL, nil),
+ let image = CGImageSourceCreateImageAtIndex(source, 0, nil)
+ else {
+ return nil
+ }
+ let request = VNRecognizeTextRequest()
+ request.recognitionLevel = .accurate
+ request.usesLanguageCorrection = true
+ let handler = VNImageRequestHandler(cgImage: image, options: [:])
+ guard (try? handler.perform([request])) != nil else { return nil }
+ let text = (request.results ?? [])
+ .compactMap { $0.topCandidates(1).first?.string }
+ .joined(separator: "\n")
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !text.isEmpty else { return nil }
+ return String(text.prefix(characterLimit))
+ }
+
+ static func pdfText(in url: URL) -> String? {
+ guard let document = PDFDocument(url: url) else { return nil }
+ var collected = ""
+ for index in 0..<document.pageCount {
+ if let page = document.page(at: index), let pageText = page.string {
+ collected += pageText + "\n"
+ }
+ if collected.count >= characterLimit { break }
+ }
+ let trimmed = collected.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else { return nil }
+ return String(trimmed.prefix(characterLimit))
+ }
+}
+
+/// Shared session cache so understanding (OCR especially) is computed once per file and reused across
+/// every ask. Keyed on path + size + modification date, so editing a file invalidates its entry.
+actor FileUnderstandingCache {
+ static let shared = FileUnderstandingCache()
+ private static let maxEntries = 500
+
+ struct Identity: Hashable {
+ var path: String
+ var size: Int
+ var modified: TimeInterval
+ }
+
+ private var entries: [Identity: FileUnderstanding] = [:]
+ private var order: [Identity] = []
+
+ static func identity(for url: URL) -> Identity? {
+ guard let attrs = try? FileManager.default.attributesOfItem(atPath: url.path),
+ let size = (attrs[.size] as? NSNumber)?.intValue,
+ let modified = attrs[.modificationDate] as? Date
+ else {
+ return nil
+ }
+ return Identity(path: url.path, size: size, modified: modified.timeIntervalSince1970)
+ }
+
+ func value(for identity: Identity) -> FileUnderstanding? {
+ entries[identity]
+ }
+
+ func store(_ understanding: FileUnderstanding, for identity: Identity) {
+ if entries[identity] == nil {
+ order.append(identity)
+ if order.count > Self.maxEntries {
+ let evicted = order.removeFirst()
+ entries[evicted] = nil
+ }
+ }
+ entries[identity] = understanding
+ }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/FileToolsTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/FileToolsTests.swift
new file mode 100644
index 00000000..ec14601b
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/FileToolsTests.swift
@@ -0,0 +1,89 @@
+import DonkeyHarness
+import Foundation
+import Testing
+
+@Suite
+struct FileToolSupportTests {
+ @Test
+ func resolvesRegularFilesInDirectorySkippingHiddenAndSubdirs() throws {
+ let fm = FileManager.default
+ let dir = fm.temporaryDirectory.appendingPathComponent("fts-\(UUID().uuidString)")
+ try fm.createDirectory(at: dir, withIntermediateDirectories: true)
+ defer { try? fm.removeItem(at: dir) }
+ try "x".write(to: dir.appendingPathComponent("one.txt"), atomically: true, encoding: .utf8)
+ try "y".write(to: dir.appendingPathComponent("two.md"), atomically: true, encoding: .utf8)
+ try "z".write(to: dir.appendingPathComponent(".hidden"), atomically: true, encoding: .utf8)
+ try fm.createDirectory(at: dir.appendingPathComponent("sub"), withIntermediateDirectories: true)
+
+ let (files, truncated) = FileToolSupport.resolveFiles(directory: dir.path, paths: [], maxFiles: 50)
+ #expect(!truncated)
+ #expect(files.map(\.lastPathComponent) == ["one.txt", "two.md"])
+ }
+
+ @Test
+ func explicitPathsWinOverDirectory() {
+ let (files, _) = FileToolSupport.resolveFiles(directory: "/tmp", paths: ["/tmp/a.txt", "/tmp/b.txt"], maxFiles: 50)
+ #expect(files.map(\.lastPathComponent) == ["a.txt", "b.txt"])
+ }
+
+ @Test
+ func capTruncatesLargeSets() {
+ let paths = (0..<10).map { "/tmp/f\($0).txt" }
+ let (files, truncated) = FileToolSupport.resolveFiles(directory: nil, paths: paths, maxFiles: 3)
+ #expect(files.count == 3)
+ #expect(truncated)
+ }
+}
+
+@Suite
+struct FileUnderstandingEngineTests {
+ @Test
+ func classifiesByExtensionThroughTheTypeRegistry() {
+ #expect(FileUnderstandingEngine.classify(fileExtension: "md") == .text)
+ #expect(FileUnderstandingEngine.classify(fileExtension: "swift") == .text)
+ #expect(FileUnderstandingEngine.classify(fileExtension: "PNG") == .image)
+ #expect(FileUnderstandingEngine.classify(fileExtension: "heic") == .image)
+ #expect(FileUnderstandingEngine.classify(fileExtension: "pdf") == .pdf)
+ #expect(FileUnderstandingEngine.classify(fileExtension: "m4a") == .audio)
+ #expect(FileUnderstandingEngine.classify(fileExtension: "mov") == .video)
+ #expect(FileUnderstandingEngine.classify(fileExtension: "zzznotatype") == .unknown)
+ }
+
+ @Test
+ func textFileUnderstandingReadsContent() throws {
+ let fm = FileManager.default
+ let url = fm.temporaryDirectory.appendingPathComponent("fue-\(UUID().uuidString).txt")
+ try "Hello, this is the body of a note about budgets.".write(to: url, atomically: true, encoding: .utf8)
+ defer { try? fm.removeItem(at: url) }
+ let u = FileUnderstandingEngine.foundationUnderstanding(for: url)
+ #expect(u.kind == .text)
+ #expect(u.textContent.contains("budgets"))
+ #expect(u.fileExtension == "txt")
+ }
+
+ @Test
+ func binaryFileUnderstandingHasNoTextAndIsClassifiedBinary() throws {
+ let fm = FileManager.default
+ // Unknown extension with binary content sniffs to .binary, not .text.
+ let url = fm.temporaryDirectory.appendingPathComponent("fue-\(UUID().uuidString).zzznotatype")
+ try Data([0x00, 0x01, 0x02, 0x00, 0xFF]).write(to: url)
+ defer { try? fm.removeItem(at: url) }
+ let u = FileUnderstandingEngine.foundationUnderstanding(for: url)
+ #expect(u.kind == .binary)
+ #expect(u.textContent.isEmpty)
+ #expect(u.summary.contains("no readable text content"))
+ }
+
+ @Test
+ func contentForReasoningFallsBackToSummaryWhenNoText() {
+ let u = FileUnderstanding(
+ path: "/tmp/a.heic",
+ fileName: "a.heic",
+ fileExtension: "heic",
+ kind: .image,
+ textContent: "",
+ summary: "image (.heic), 4032x3024, no readable text content"
+ )
+ #expect(u.contentForReasoning(limit: 1_000).contains("4032x3024"))
+ }
+}