Skip to content

Open source CapCut alternative.

TypeScript

Add artifact store

David Leea43fa1c24c2
diff --git a/apps/Donkey/Sources/DonkeyContracts/RunLoopContracts.swift b/apps/Donkey/Sources/DonkeyContracts/RunLoopContracts.swift
index 79df28a4..ce2a122c 100644
--- a/apps/Donkey/Sources/DonkeyContracts/RunLoopContracts.swift
+++ b/apps/Donkey/Sources/DonkeyContracts/RunLoopContracts.swift
@@ -1,6 +1,6 @@
import Foundation
-public enum RunLifecycleState: String, Equatable, Sendable {
+public enum RunLifecycleState: String, Codable, Equatable, Sendable {
case idle
case starting
case running
@@ -21,14 +21,14 @@ public enum RunLifecycleState: String, Equatable, Sendable {
}
}
-public enum RunEventStream: String, Equatable, Sendable {
+public enum RunEventStream: String, Codable, Equatable, Sendable {
case assistant
case tool
case lifecycle
case reflex
}
-public enum ToolCallCapability: String, CaseIterable, Equatable, Hashable, Sendable {
+public enum ToolCallCapability: String, CaseIterable, Codable, Equatable, Hashable, Sendable {
case capture
case accessibility
case model
@@ -38,7 +38,7 @@ public enum ToolCallCapability: String, CaseIterable, Equatable, Hashable, Senda
case controller
}
-public enum ToolCallDecision: Equatable, Sendable {
+public enum ToolCallDecision: Codable, Equatable, Sendable {
case allow
case deny(reason: String)
case ask(reason: String)
@@ -48,7 +48,7 @@ public enum ToolCallDecision: Equatable, Sendable {
}
}
-public struct ToolCallPolicy: Equatable, Sendable {
+public struct ToolCallPolicy: Codable, Equatable, Sendable {
public var allowedCapabilities: Set<ToolCallCapability>
public var deniedCapabilities: Set<ToolCallCapability>
public var approvalRequiredCapabilities: Set<ToolCallCapability>
@@ -91,7 +91,7 @@ public struct ToolCallPolicy: Equatable, Sendable {
public static let `default` = ToolCallPolicy()
}
-public struct RunSession: Equatable, Sendable {
+public struct RunSession: Codable, Equatable, Sendable {
public var id: String
public var userGoal: String
public var targetID: String
@@ -116,7 +116,7 @@ public struct RunSession: Equatable, Sendable {
}
}
-public struct AssistantRunEvent: Equatable, Sendable {
+public struct AssistantRunEvent: Codable, Equatable, Sendable {
public var message: String
public init(message: String) {
@@ -124,7 +124,7 @@ public struct AssistantRunEvent: Equatable, Sendable {
}
}
-public struct ToolRunEvent: Equatable, Sendable {
+public struct ToolRunEvent: Codable, Equatable, Sendable {
public var capability: ToolCallCapability
public var decision: ToolCallDecision
public var toolName: String?
@@ -140,7 +140,7 @@ public struct ToolRunEvent: Equatable, Sendable {
}
}
-public struct LifecycleRunEvent: Equatable, Sendable {
+public struct LifecycleRunEvent: Codable, Equatable, Sendable {
public var state: RunLifecycleState
public var reason: String?
@@ -150,7 +150,7 @@ public struct LifecycleRunEvent: Equatable, Sendable {
}
}
-public struct ReflexRunEvent: Equatable, Sendable {
+public struct ReflexRunEvent: Codable, Equatable, Sendable {
public var frameID: String?
public var stateID: String?
public var actionID: String?
@@ -169,14 +169,14 @@ public struct ReflexRunEvent: Equatable, Sendable {
}
}
-public enum RunEventPayload: Equatable, Sendable {
+public enum RunEventPayload: Codable, Equatable, Sendable {
case assistant(AssistantRunEvent)
case tool(ToolRunEvent)
case lifecycle(LifecycleRunEvent)
case reflex(ReflexRunEvent)
}
-public struct RunEvent: Equatable, Sendable {
+public struct RunEvent: Codable, Equatable, Sendable {
public var sequence: Int
public var stream: RunEventStream
public var summary: String
@@ -210,7 +210,7 @@ public struct RunEvent: Equatable, Sendable {
}
}
-public struct RunWorldStateSummary: Equatable, Sendable {
+public struct RunWorldStateSummary: Codable, Equatable, Sendable {
public var stateID: String
public var summary: String
public var confidence: Double
@@ -222,7 +222,7 @@ public struct RunWorldStateSummary: Equatable, Sendable {
}
}
-public struct RunPlannerHint: Equatable, Sendable {
+public struct RunPlannerHint: Codable, Equatable, Sendable {
public var id: String
public var summary: String
public var isValid: Bool
@@ -234,7 +234,7 @@ public struct RunPlannerHint: Equatable, Sendable {
}
}
-public struct RunFailureSummary: Equatable, Sendable {
+public struct RunFailureSummary: Codable, Equatable, Sendable {
public var traceID: String
public var summary: String
@@ -244,7 +244,7 @@ public struct RunFailureSummary: Equatable, Sendable {
}
}
-public struct RunContextPackage: Equatable, Sendable {
+public struct RunContextPackage: Codable, Equatable, Sendable {
public var sessionID: String
public var userGoal: String
public var targetID: String
@@ -277,3 +277,105 @@ public struct RunContextPackage: Equatable, Sendable {
self.recentFailures = recentFailures
}
}
+
+public struct RunTraceTimestamp: Codable, Equatable, Sendable {
+ public var wallClock: Date
+ public var monotonicUptimeNanoseconds: UInt64
+
+ public init(
+ wallClock: Date,
+ monotonicUptimeNanoseconds: UInt64
+ ) {
+ self.wallClock = wallClock
+ self.monotonicUptimeNanoseconds = monotonicUptimeNanoseconds
+ }
+}
+
+public enum RunArtifactKind: String, Codable, Equatable, Sendable {
+ case screenshot
+ case accessibilitySnapshot
+
+ public var directoryName: String {
+ switch self {
+ case .screenshot:
+ return "screenshots"
+ case .accessibilitySnapshot:
+ return "accessibility"
+ }
+ }
+}
+
+public struct RunArtifactRecord: Codable, Equatable, Sendable {
+ public var artifactID: String
+ public var kind: RunArtifactKind
+ public var relativePath: String
+ public var contentType: String
+ public var byteCount: Int64
+ public var createdAt: RunTraceTimestamp
+ public var metadata: [String: String]
+
+ public init(
+ artifactID: String,
+ kind: RunArtifactKind,
+ relativePath: String,
+ contentType: String,
+ byteCount: Int64,
+ createdAt: RunTraceTimestamp,
+ metadata: [String: String] = [:]
+ ) {
+ self.artifactID = artifactID
+ self.kind = kind
+ self.relativePath = relativePath
+ self.contentType = contentType
+ self.byteCount = byteCount
+ self.createdAt = createdAt
+ self.metadata = metadata
+ }
+}
+
+public struct RunTraceSummary: Codable, Equatable, Sendable {
+ public var runID: String
+ public var traceID: String
+ public var session: RunSession
+ public var startedAt: RunTraceTimestamp
+ public var updatedAt: RunTraceTimestamp
+ public var eventCount: Int
+ public var artifacts: [RunArtifactRecord]
+
+ public init(
+ runID: String,
+ traceID: String,
+ session: RunSession,
+ startedAt: RunTraceTimestamp,
+ updatedAt: RunTraceTimestamp,
+ eventCount: Int = 0,
+ artifacts: [RunArtifactRecord] = []
+ ) {
+ self.runID = runID
+ self.traceID = traceID
+ self.session = session
+ self.startedAt = startedAt
+ self.updatedAt = updatedAt
+ self.eventCount = eventCount
+ self.artifacts = artifacts
+ }
+}
+
+public struct RunTraceEventRecord: Codable, Equatable, Sendable {
+ public var runID: String
+ public var traceID: String
+ public var recordedAt: RunTraceTimestamp
+ public var event: RunEvent
+
+ public init(
+ runID: String,
+ traceID: String,
+ recordedAt: RunTraceTimestamp,
+ event: RunEvent
+ ) {
+ self.runID = runID
+ self.traceID = traceID
+ self.recordedAt = recordedAt
+ self.event = event
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalRunArtifactStore.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalRunArtifactStore.swift
new file mode 100644
index 00000000..703f6d6a
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalRunArtifactStore.swift
@@ -0,0 +1,255 @@
+import DonkeyContracts
+import Foundation
+
+public enum LocalRunArtifactStoreError: Error, Equatable, Sendable {
+ case invalidIdentifier(String)
+ case missingSummary(String)
+ case unsafeRelativePath(String)
+}
+
+public struct LocalRunArtifactPath: Equatable, Sendable {
+ public var artifactID: String
+ public var relativePath: String
+ public var fileURL: URL
+
+ public init(artifactID: String, relativePath: String, fileURL: URL) {
+ self.artifactID = artifactID
+ self.relativePath = relativePath
+ self.fileURL = fileURL
+ }
+}
+
+public actor LocalRunArtifactStore {
+ private let baseDirectory: URL
+ private let fileManager: FileManager
+
+ public init(
+ baseDirectory: URL? = nil,
+ fileManager: FileManager = .default
+ ) throws {
+ self.fileManager = fileManager
+ self.baseDirectory = try baseDirectory ?? Self.defaultBaseDirectory(fileManager: fileManager)
+ }
+
+ public static func defaultBaseDirectory(
+ fileManager: FileManager = .default
+ ) throws -> URL {
+ let applicationSupport = try fileManager.url(
+ for: .applicationSupportDirectory,
+ in: .userDomainMask,
+ appropriateFor: nil,
+ create: false
+ )
+
+ return applicationSupport
+ .appendingPathComponent("Donkey", isDirectory: true)
+ .appendingPathComponent("Runs", isDirectory: true)
+ }
+
+ @discardableResult
+ public func prepareRun(
+ session: RunSession,
+ traceID: String = UUID().uuidString
+ ) throws -> RunTraceSummary {
+ try validateIdentifier(session.id)
+ try validateIdentifier(traceID)
+
+ let runDirectory = try runDirectory(for: session.id)
+ try fileManager.createDirectory(
+ at: runDirectory,
+ withIntermediateDirectories: true
+ )
+ try fileManager.createDirectory(
+ at: runDirectory.appendingPathComponent("screenshots", isDirectory: true),
+ withIntermediateDirectories: true
+ )
+ try fileManager.createDirectory(
+ at: runDirectory.appendingPathComponent("accessibility", isDirectory: true),
+ withIntermediateDirectories: true
+ )
+
+ let eventsURL = eventsURL(forRunDirectory: runDirectory)
+ if !fileManager.fileExists(atPath: eventsURL.path) {
+ try Data().write(to: eventsURL, options: .atomic)
+ }
+
+ let now = makeTimestamp()
+ let summary = RunTraceSummary(
+ runID: session.id,
+ traceID: traceID,
+ session: session,
+ startedAt: now,
+ updatedAt: now
+ )
+
+ try writeSummary(summary)
+ return summary
+ }
+
+ @discardableResult
+ public func appendEvent(
+ _ event: RunEvent,
+ runID: String
+ ) throws -> RunTraceEventRecord {
+ var summary = try summary(runID: runID)
+ let record = RunTraceEventRecord(
+ runID: summary.runID,
+ traceID: summary.traceID,
+ recordedAt: makeTimestamp(),
+ event: event
+ )
+ var line = try Self.encoder().encode(record)
+ line.append(0x0A)
+
+ let eventsURL = try runDirectory(for: runID).appendingPathComponent(
+ "events.jsonl",
+ isDirectory: false
+ )
+ let handle = try FileHandle(forWritingTo: eventsURL)
+ defer { try? handle.close() }
+ try handle.seekToEnd()
+ try handle.write(contentsOf: line)
+
+ summary.eventCount += 1
+ summary.updatedAt = record.recordedAt
+ try writeSummary(summary)
+
+ return record
+ }
+
+ public func reserveArtifactPath(
+ runID: String,
+ artifactID: String,
+ kind: RunArtifactKind,
+ fileExtension: String
+ ) throws -> LocalRunArtifactPath {
+ try validateIdentifier(runID)
+ try validateIdentifier(artifactID)
+
+ let sanitizedExtension = fileExtension.trimmingCharacters(in: CharacterSet(charactersIn: "."))
+ try validateIdentifier(sanitizedExtension)
+
+ let relativePath = "\(kind.directoryName)/\(artifactID).\(sanitizedExtension)"
+ try validateRelativePath(relativePath, expectedDirectory: kind.directoryName)
+
+ let fileURL = try runDirectory(for: runID).appendingPathComponent(
+ relativePath,
+ isDirectory: false
+ )
+ return LocalRunArtifactPath(
+ artifactID: artifactID,
+ relativePath: relativePath,
+ fileURL: fileURL
+ )
+ }
+
+ @discardableResult
+ public func recordArtifact(
+ runID: String,
+ artifactID: String,
+ kind: RunArtifactKind,
+ relativePath: String,
+ contentType: String,
+ byteCount: Int64,
+ metadata: [String: String] = [:]
+ ) throws -> RunArtifactRecord {
+ try validateIdentifier(artifactID)
+ try validateRelativePath(relativePath, expectedDirectory: kind.directoryName)
+
+ var summary = try summary(runID: runID)
+ let record = RunArtifactRecord(
+ artifactID: artifactID,
+ kind: kind,
+ relativePath: relativePath,
+ contentType: contentType,
+ byteCount: byteCount,
+ createdAt: makeTimestamp(),
+ metadata: metadata
+ )
+
+ summary.artifacts.append(record)
+ summary.updatedAt = record.createdAt
+ try writeSummary(summary)
+
+ return record
+ }
+
+ public func summary(runID: String) throws -> RunTraceSummary {
+ try validateIdentifier(runID)
+
+ let url = try summaryURL(for: runID)
+ guard fileManager.fileExists(atPath: url.path) else {
+ throw LocalRunArtifactStoreError.missingSummary(runID)
+ }
+
+ let data = try Data(contentsOf: url)
+ return try Self.decoder().decode(RunTraceSummary.self, from: data)
+ }
+
+ public func runDirectory(for runID: String) throws -> URL {
+ try validateIdentifier(runID)
+ return baseDirectory.appendingPathComponent(runID, isDirectory: true)
+ }
+
+ private func writeSummary(_ summary: RunTraceSummary) throws {
+ let data = try Self.encoder().encode(summary)
+ try data.write(to: try summaryURL(for: summary.runID), options: .atomic)
+ }
+
+ private func summaryURL(for runID: String) throws -> URL {
+ try runDirectory(for: runID).appendingPathComponent("summary.json", isDirectory: false)
+ }
+
+ private func eventsURL(forRunDirectory runDirectory: URL) -> URL {
+ runDirectory.appendingPathComponent("events.jsonl", isDirectory: false)
+ }
+
+ private func validateIdentifier(_ value: String) throws {
+ let allowedScalars = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-")
+ let isSafe = !value.isEmpty
+ && value.count <= 128
+ && value != "."
+ && value != ".."
+ && value.unicodeScalars.allSatisfy { allowedScalars.contains($0) }
+
+ guard isSafe else {
+ throw LocalRunArtifactStoreError.invalidIdentifier(value)
+ }
+ }
+
+ private func validateRelativePath(
+ _ relativePath: String,
+ expectedDirectory: String
+ ) throws {
+ let components = relativePath.split(separator: "/", omittingEmptySubsequences: false)
+ let isSafe = !relativePath.isEmpty
+ && !relativePath.hasPrefix("/")
+ && !relativePath.contains("\\")
+ && components.count == 2
+ && components.first.map(String.init) == expectedDirectory
+ && components.allSatisfy { component in
+ !component.isEmpty && component != "." && component != ".."
+ }
+
+ guard isSafe else {
+ throw LocalRunArtifactStoreError.unsafeRelativePath(relativePath)
+ }
+ }
+
+ private func makeTimestamp() -> RunTraceTimestamp {
+ RunTraceTimestamp(
+ wallClock: Date(),
+ monotonicUptimeNanoseconds: UInt64(ProcessInfo.processInfo.systemUptime * 1_000_000_000)
+ )
+ }
+
+ private static func encoder() -> JSONEncoder {
+ let encoder = JSONEncoder()
+ encoder.outputFormatting = [.sortedKeys]
+ return encoder
+ }
+
+ private static func decoder() -> JSONDecoder {
+ JSONDecoder()
+ }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalRunArtifactStoreTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalRunArtifactStoreTests.swift
new file mode 100644
index 00000000..6f7cc94b
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalRunArtifactStoreTests.swift
@@ -0,0 +1,230 @@
+import DonkeyContracts
+@testable import DonkeyRuntime
+import Foundation
+import Testing
+
+@Suite
+struct LocalRunArtifactStoreTests {
+ @Test
+ func prepareRunCreatesTraceLayoutAndSummary() async throws {
+ let root = temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let store = try LocalRunArtifactStore(baseDirectory: root)
+ let session = RunSession(
+ id: "run-1",
+ userGoal: "capture context",
+ targetID: "target-1"
+ )
+
+ let summary = try await store.prepareRun(session: session, traceID: "trace-1")
+ let runDirectory = root.appendingPathComponent("run-1", isDirectory: true)
+
+ #expect(summary.runID == "run-1")
+ #expect(summary.traceID == "trace-1")
+ #expect(summary.eventCount == 0)
+ #expect(summary.artifacts.isEmpty)
+ #expect(fileExists(runDirectory.appendingPathComponent("events.jsonl")))
+ #expect(fileExists(runDirectory.appendingPathComponent("summary.json")))
+ #expect(directoryExists(runDirectory.appendingPathComponent("screenshots")))
+ #expect(directoryExists(runDirectory.appendingPathComponent("accessibility")))
+
+ let storedSummary = try await store.summary(runID: "run-1")
+ #expect(storedSummary == summary)
+ }
+
+ @Test
+ func appendEventWritesJsonlInCallOrderAndUpdatesSummary() async throws {
+ let root = temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let store = try LocalRunArtifactStore(baseDirectory: root)
+ let session = RunSession(
+ id: "run-events",
+ userGoal: "record events",
+ targetID: "target-1"
+ )
+ _ = try await store.prepareRun(session: session, traceID: "trace-events")
+
+ let firstEvent = RunEvent(
+ sequence: 1,
+ stream: .tool,
+ summary: "capture tool call allowed",
+ payload: .tool(
+ ToolRunEvent(
+ capability: .capture,
+ decision: .allow,
+ toolName: "manual-capture"
+ )
+ )
+ )
+ let secondEvent = RunEvent(
+ sequence: 2,
+ stream: .lifecycle,
+ summary: "Run completed",
+ payload: .lifecycle(
+ LifecycleRunEvent(state: .completed, reason: "capture complete")
+ )
+ )
+
+ _ = try await store.appendEvent(firstEvent, runID: "run-events")
+ _ = try await store.appendEvent(secondEvent, runID: "run-events")
+
+ let eventsURL = root
+ .appendingPathComponent("run-events", isDirectory: true)
+ .appendingPathComponent("events.jsonl")
+ let records = try jsonlRecords(from: eventsURL)
+
+ #expect(records.map(\.event.sequence) == [1, 2])
+ #expect(records.map(\.event.summary) == [
+ "capture tool call allowed",
+ "Run completed"
+ ])
+ #expect(records.allSatisfy { $0.runID == "run-events" })
+ #expect(records.allSatisfy { $0.traceID == "trace-events" })
+
+ let summary = try await store.summary(runID: "run-events")
+ #expect(summary.eventCount == 2)
+ }
+
+ @Test
+ func recordArtifactUsesSafeRelativePathAndUpdatesSummary() async throws {
+ let root = temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let store = try LocalRunArtifactStore(baseDirectory: root)
+ let session = RunSession(
+ id: "run-artifact",
+ userGoal: "record artifact",
+ targetID: "target-1"
+ )
+ _ = try await store.prepareRun(session: session, traceID: "trace-artifact")
+
+ let reservedPath = try await store.reserveArtifactPath(
+ runID: "run-artifact",
+ artifactID: "screenshot-1",
+ kind: .screenshot,
+ fileExtension: "png"
+ )
+ let record = try await store.recordArtifact(
+ runID: "run-artifact",
+ artifactID: reservedPath.artifactID,
+ kind: .screenshot,
+ relativePath: reservedPath.relativePath,
+ contentType: "image/png",
+ byteCount: 42,
+ metadata: ["target": "target-1"]
+ )
+
+ #expect(reservedPath.relativePath == "screenshots/screenshot-1.png")
+ #expect(reservedPath.fileURL == root
+ .appendingPathComponent("run-artifact", isDirectory: true)
+ .appendingPathComponent("screenshots/screenshot-1.png"))
+ #expect(record.relativePath == "screenshots/screenshot-1.png")
+ #expect(record.kind == .screenshot)
+ #expect(record.contentType == "image/png")
+ #expect(record.byteCount == 42)
+
+ let summary = try await store.summary(runID: "run-artifact")
+ #expect(summary.artifacts == [record])
+ }
+
+ @Test
+ func unsafeRunIdentifiersAreRejected() async throws {
+ let root = temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let store = try LocalRunArtifactStore(baseDirectory: root)
+ let session = RunSession(
+ id: "../bad",
+ userGoal: "escape",
+ targetID: "target-1"
+ )
+
+ do {
+ _ = try await store.prepareRun(session: session, traceID: "trace-1")
+ Issue.record("Expected unsafe run id to be rejected")
+ } catch LocalRunArtifactStoreError.invalidIdentifier(let value) {
+ #expect(value == "../bad")
+ } catch {
+ Issue.record("Unexpected error: \(error)")
+ }
+ }
+
+ @Test
+ func unsafeArtifactPathsAreRejected() async throws {
+ let root = temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let store = try LocalRunArtifactStore(baseDirectory: root)
+ let session = RunSession(
+ id: "run-unsafe-artifact",
+ userGoal: "record artifact",
+ targetID: "target-1"
+ )
+ _ = try await store.prepareRun(session: session, traceID: "trace-1")
+
+ do {
+ _ = try await store.recordArtifact(
+ runID: "run-unsafe-artifact",
+ artifactID: "artifact-1",
+ kind: .screenshot,
+ relativePath: "../artifact-1.png",
+ contentType: "image/png",
+ byteCount: 1
+ )
+ Issue.record("Expected unsafe artifact path to be rejected")
+ } catch LocalRunArtifactStoreError.unsafeRelativePath(let value) {
+ #expect(value == "../artifact-1.png")
+ } catch {
+ Issue.record("Unexpected error: \(error)")
+ }
+ }
+
+ @Test
+ func defaultBaseDirectoryUsesApplicationSupportDonkeyRuns() throws {
+ let baseDirectory = try LocalRunArtifactStore.defaultBaseDirectory()
+ let path = baseDirectory.path
+
+ #expect(path.contains("Application Support"))
+ #expect(path.hasSuffix("Donkey/Runs"))
+ }
+
+ private func temporaryDirectory() -> URL {
+ FileManager.default.temporaryDirectory.appendingPathComponent(
+ "DonkeyArtifactStoreTests-\(UUID().uuidString)",
+ isDirectory: true
+ )
+ }
+
+ private func fileExists(_ url: URL) -> Bool {
+ var isDirectory = ObjCBool(false)
+ let exists = FileManager.default.fileExists(
+ atPath: url.path,
+ isDirectory: &isDirectory
+ )
+ return exists && !isDirectory.boolValue
+ }
+
+ private func directoryExists(_ url: URL) -> Bool {
+ var isDirectory = ObjCBool(false)
+ let exists = FileManager.default.fileExists(
+ atPath: url.path,
+ isDirectory: &isDirectory
+ )
+ return exists && isDirectory.boolValue
+ }
+
+ private func jsonlRecords(from url: URL) throws -> [RunTraceEventRecord] {
+ let data = try Data(contentsOf: url)
+ let text = String(decoding: data, as: UTF8.self)
+ return try text
+ .split(separator: "\n")
+ .map { line in
+ try JSONDecoder().decode(
+ RunTraceEventRecord.self,
+ from: Data(line.utf8)
+ )
+ }
+ }
+}
diff --git a/docs/guides/minimal-run-coordinator.md b/docs/guides/minimal-run-coordinator.md
index 5909efa4..ef8f6428 100644
--- a/docs/guides/minimal-run-coordinator.md
+++ b/docs/guides/minimal-run-coordinator.md
@@ -14,13 +14,26 @@ The coordinator can:
- mark aborts and timeouts as requiring held-input release
- build bounded planner context from the current session, world-state summary, transcript summary, valid hints, and recent failures
-This is a coordination foundation only. It does not capture the screen, run perception models, call LLMs, or execute OS input.
+Donkey also supports a local run artifact store for durable trace data. Installed app runs are stored under `~/Library/Application Support/Donkey/Runs/<run-id>/`; tests and development tools may pass an explicit base directory override. Each prepared run creates:
+
+```text
+events.jsonl
+summary.json
+screenshots/
+accessibility/
+```
+
+The artifact store can append ordered event records, reserve safe screenshot or Accessibility artifact paths, record artifact metadata, and keep `summary.json` current.
+
+This is a coordination and trace foundation only. It does not capture the screen, run perception models, call LLMs, execute OS input, or wire coordinator events into disk persistence yet.
## Technical Guidelines
- Keep shared event, policy, lifecycle, and context types in `DonkeyContracts`.
- Keep coordinator state and append ordering in `DonkeyRuntime`; UI code should read status through narrow provider boundaries.
- Treat `RunCoordinator` as the owner of lifecycle and event ordering, not as the owner of perception, controller internals, or input backends.
+- Treat `LocalRunArtifactStore` as a persistence sink for trace records and artifact metadata. It should not own lifecycle state or decide whether tool calls are allowed.
+- Keep mutable installed-app run artifacts in Application Support, not inside the `.app` bundle and not relative to process working directory.
- Keep input actions denied unless a caller provides a policy that explicitly allows them.
- Preserve latest-request-wins behavior for live-control sessions so stale work cannot build up behind the reflex loop.
- Use sampled or summarized reflex events until a measured trace sink exists.
@@ -33,10 +46,11 @@ From `apps/Donkey/`:
swift test
```
-The runtime tests should cover lifecycle ordering, abort and timeout safety, latest-session queue drops, tool permission denial, event-store ordering, and context compaction.
+The runtime tests should cover lifecycle ordering, abort and timeout safety, latest-session queue drops, tool permission denial, event-store ordering, context compaction, artifact path validation, trace folder layout, JSONL event persistence, and summary updates.
## Source Entry Points
- Runtime contracts live in `apps/Donkey/Sources/DonkeyContracts/RunLoopContracts.swift`.
- Runtime coordination lives in `apps/Donkey/Sources/DonkeyRuntime/`.
+- Local artifact persistence lives in `apps/Donkey/Sources/DonkeyRuntime/LocalRunArtifactStore.swift`.
- The source plan remains active in `plans/20-off-the-shelf-run-loop.md`.
diff --git a/plans/00-overview.md b/plans/00-overview.md
index 32d7935e..acf03446 100644
--- a/plans/00-overview.md
+++ b/plans/00-overview.md
@@ -6,6 +6,12 @@ Build a desktop AI agent that can play iPhone games through Apple's iPhone Mirro
iPhone games are the first product focus. Gaming is the latency proof. The larger platform is real-time desktop and mobile-app control from the Mac.
+## Current Master Plan
+
+Start with [master-plan.md](master-plan.md).
+
+That plan coordinates the next sequence of edits across capture, Accessibility, trace artifacts, and runtime events. Treat older active plans as background or cleanup targets while `22` is open.
+
## Near-Term Focus
Become genuinely good at playing iPhone games through iPhone Mirroring.
@@ -54,6 +60,7 @@ Every frame should use local, bounded-cost logic:
## Plan Breakdown
+- [master-plan.md](master-plan.md): current master plan for manual screenshot, Accessibility tree, and trace artifact capture for any target window
- [01-latency-budget.md](01-latency-budget.md): hard timing budget and optimization priorities
- [02-capture-and-perception.md](02-capture-and-perception.md): screen capture, visual parsing, and world-state updates
- [03-fast-controller.md](03-fast-controller.md): real-time controller design
@@ -74,7 +81,6 @@ Every frame should use local, bounded-cost logic:
- [18-macos-accessibility.md](18-macos-accessibility.md): macOS Accessibility tree/action backend
- [19-ai-harness.md](19-ai-harness.md): slow-path memory, LLM/VLM connection, model routing, and update plan
- [20-off-the-shelf-run-loop.md](20-off-the-shelf-run-loop.md): off-the-shelf perception, deterministic control, and low-latency runtime stack
-- [22-manual-target-context-capture.md](22-manual-target-context-capture.md): manual screenshot, Accessibility tree, and trace artifact capture for one run
## System Priorities
diff --git a/plans/22-manual-target-context-capture.md b/plans/master-plan.md
similarity index 62%
rename from plans/22-manual-target-context-capture.md
rename to plans/master-plan.md
index cddb969a..d9f53a4f 100644
--- a/plans/22-manual-target-context-capture.md
+++ b/plans/master-plan.md
@@ -1,4 +1,4 @@
-# Manual Target Context Capture
+# Manual Target Context Capture Master Plan
## Goal
@@ -8,6 +8,23 @@ One manual command or UI action should create a run session, select any visible
This should prove the data path before continuous capture, perception models, or synthetic input are added.
+## Master Plan Role
+
+Use this document as the current active master plan for the next sequence of work.
+
+It coordinates the order of plan edits and implementation slices needed to move Donkey from a runtime coordinator shell into real target-window context capture. Start here before editing the older active plans.
+
+Edit sequence:
+
+1. Keep this plan as the implementation driver until manual target context capture is supported.
+2. Update [18-macos-accessibility.md](18-macos-accessibility.md) only for Accessibility details that are still future-facing after read-only AX snapshots exist.
+3. Update [02-capture-and-perception.md](02-capture-and-perception.md) only for capture/perception boundaries that remain after manual screenshots are supported.
+4. Update [06-benchmarking.md](06-benchmarking.md) only for trace/artifact measurement rules that remain broader than this milestone.
+5. Update [20-off-the-shelf-run-loop.md](20-off-the-shelf-run-loop.md) only for the larger runtime/perception loop that remains after the minimal coordinator and manual capture pieces are documented.
+6. When this milestone is implemented, write or update the supported guide in `docs/guides/`, then move this plan to `plans/done/`.
+
+Do not spread implementation instructions across multiple active plans while this one is still open. Use linked plans for background and cleanup targets, not as competing sources of truth.
+
## Related Plans And Guides
- [20-off-the-shelf-run-loop.md](20-off-the-shelf-run-loop.md): runtime shell, event streams, session lifecycle, and coordinator boundary
@@ -39,7 +56,7 @@ In scope:
- iPhone Mirroring as one supported target option, not a special-only path
- screenshot artifact metadata and PNG output
- shallow Accessibility tree snapshot with roles, labels/titles, values, frames, pid, and window metadata
-- local trace folder for one run
+- local trace folder for one run, stored under Application Support by default
- ordered runtime events for capture and persistence
- privacy-oriented redaction boundaries for sensitive windows
@@ -82,10 +99,10 @@ Out of scope:
- Start with one manual screenshot per run.
- Capture the explicitly selected target window bounds, not the whole desktop by default.
-- Store screenshots under:
+- Store screenshots under the prepared run folder:
```text
-runs/<run-id>/screenshots/<artifact-id>.png
+<run-folder>/screenshots/<artifact-id>.png
```
- Write sidecar metadata:
@@ -106,10 +123,10 @@ runs/<run-id>/screenshots/<artifact-id>.png
- resolve a selected target window by pid/title/window metadata when possible
- read a shallow AX tree with bounded depth and child count
- serialize role, title/label, value summary, frame, enabled/focused state, and action names
-- Store AX snapshots under:
+- Store AX snapshots under the prepared run folder:
```text
-runs/<run-id>/accessibility/<artifact-id>.json
+<run-folder>/accessibility/<artifact-id>.json
```
- Keep the tree bounded. Do not dump arbitrarily large app trees.
@@ -117,18 +134,24 @@ runs/<run-id>/accessibility/<artifact-id>.json
### Trace Artifact Store
-- Add a simple local run artifact layout:
+Supported as the first vertical slice. `LocalRunArtifactStore` prepares durable run folders, appends JSONL event records, reserves safe artifact paths, records artifact metadata, and updates summaries.
+
+Installed Donkey stores runs under:
+
+```text
+~/Library/Application Support/Donkey/Runs/<run-id>/
+```
+
+Tests and development tools may pass an explicit base directory override. Each run folder contains:
```text
-runs/<run-id>/
- events.jsonl
- summary.json
- screenshots/
- accessibility/
+events.jsonl
+summary.json
+screenshots/
+accessibility/
```
-- Write event and artifact records in append order.
-- Keep the artifact store simple and local for this milestone. It can become async or buffered later.
+- Keep the artifact store simple and local for this milestone. It can become async or buffered after coordinator capture events are wired to disk.
### Context Assembly
@@ -149,7 +172,7 @@ runs/<run-id>/
- Missing Accessibility permission produces a clear event and a partial run summary instead of crashing.
- Input and Accessibility actions remain disabled.
- Sensitive/system/payment/login windows are refused or marked as safety stops.
-- Unit tests cover metadata serialization, bounded AX tree serialization, policy denial for input, and run artifact path generation.
+- Unit tests cover metadata serialization, run artifact path generation, artifact summary updates, bounded AX tree serialization, and policy denial for input.
- Manual verification works against at least two different windows, such as iPhone Mirroring and a normal Mac app window.
## Handoff Notes For The Next LLM
@@ -166,12 +189,20 @@ runs/<run-id>/
## What Should Be Done Next
-Start with the smallest read-only vertical slice:
-
-1. Add the local `runs/<run-id>/` artifact writer.
-2. Add window enumeration and target selection metadata.
-3. Add one target-scoped screenshot artifact.
-4. Add shallow Accessibility tree capture behind permission checks.
-5. Wire those steps through `RunCoordinator` events.
-6. Add tests for artifact metadata and bounded AX serialization.
-7. Manually verify against iPhone Mirroring and at least one other visible Mac app window.
+Continue the read-only vertical slice from the completed local artifact writer:
+
+1. Add window enumeration and target selection metadata.
+ - Add a macOS window resolver in `DonkeyRuntime` that returns visible candidate windows with window id, pid, app name or bundle id, title, bounds, and frontmost/focus metadata.
+ - Support explicit selection by window id and a focused-window default when no explicit target is provided.
+ - Treat iPhone Mirroring as a normal visible candidate, not a special-only path.
+ - Add conservative safety metadata so later capture can refuse obvious system, login, payment, or unknown sensitive surfaces.
+ - Add tests for metadata serialization, target selection rules, focused-window fallback, and safety classification.
+2. Add one target-scoped screenshot artifact.
+ - Capture the selected target bounds, write PNG bytes through `LocalRunArtifactStore`, and record screenshot artifact metadata.
+3. Add shallow Accessibility tree capture behind permission checks.
+ - Serialize a bounded AX snapshot when trusted and record a clear partial-run event when not trusted.
+4. Wire the manual capture flow through `RunCoordinator` events.
+ - Emit ordered lifecycle/tool events for target resolution, screenshot capture, AX snapshot, artifact persistence, completion, and failure paths.
+5. Add integration tests and manual verification.
+ - Cover artifact metadata, bounded AX serialization, policy denial for input, and partial summaries.
+ - Manually verify against iPhone Mirroring and at least one other visible Mac app window.