Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
feat(lume): add schema-v3 product telemetry
Francesco Bonacci22ccc04ed09a
diff --git a/docs/content/docs/reference/lume/meta.json b/docs/content/docs/reference/lume/meta.jsonindex 57a2440d6b..9db9fefd4b 100644--- a/docs/content/docs/reference/lume/meta.json+++ b/docs/content/docs/reference/lume/meta.json@@ -1 +1 @@-{ "title": "Lume", "pages": ["cli-reference", "http-api", "mcp-tools", "limits"] }+{ "title": "Lume", "pages": ["cli-reference", "http-api", "mcp-tools", "telemetry", "limits"] }diff --git a/docs/content/docs/reference/lume/telemetry.mdx b/docs/content/docs/reference/lume/telemetry.mdxnew file mode 100644index 0000000000..01e24ab2b5--- /dev/null+++ b/docs/content/docs/reference/lume/telemetry.mdx@@ -0,0 +1,74 @@+---+title: Telemetry and privacy+description: Exact Lume telemetry controls, schema, and privacy boundaries.+---++Lume sends content-free, pseudonymous product telemetry to the PostHog EU ingest endpoint. Telemetry is enabled by default. The first-run notice appears before the first event, and the preference persists across upgrades.++Installation and release delivery is serialized across Lume processes. A success marker is written only after PostHog accepts the event. Failed lifecycle delivery is retried after a 15-minute backoff.++## Control telemetry++```bash+lume config telemetry status+lume config telemetry disable+lume config telemetry enable+lume config telemetry reset-id+```++`LUME_TELEMETRY_ENABLED` overrides the saved preference for the current process. Disabling telemetry stops every telemetry request but retains the installation ID. `reset-id` deletes the local pseudonymous ID and lifecycle markers while preserving the enabled or disabled preference.++## Separate update check++The telemetry setting does not control the read-only request to GitHub Releases made by `lume check-update`, `lume update`, or the MCP `check_for_update` tool. The update response is cached for up to 20 hours and does not include the telemetry installation ID.++Disable that request separately:++```bash+LUME_UPDATE_CHECK=false lume check-update+```++## Schema-v3 envelope++Every schema-v3 event has these fixed fields:++| Property | Meaning |+| --- | --- |+| `telemetry_schema_version` | Fixed integer `3` |+| `product_version` | Installed Lume version |+| `os_family` | Host family, currently `macos` |+| `os_major` | Host major operating-system version only |+| `arch` | Bounded host CPU architecture |+| `is_ci` | Whether a recognized CI environment is present |+| `is_synthetic` | Explicit Cua-owned test marker; `false` by default |+| `transport` | `cli`, `http`, or `mcp_stdio` |+| `process_session_id` | Random ID created once per process and never persisted |+| `id_persisted` | Whether the installation ID is durable |++Lume sets `$process_person_profile` to `false` and `$geoip_disable` to `true`. The installation UUID is used only as PostHog's `distinct_id`. Lume does not retain location derived from the request IP.++## Fixed events++| Event | Additional bounded properties |+| --- | --- |+| `lume_install` | install channel and product version |+| `lume_release_installed` | install channel and product version |+| `lume_operation_completed` | allowlisted operation, success, fixed error class, duration bucket, `accepted` or `completed` phase, and optional guest OS |+| `lume_vm_started` | guest OS and successful start signal |+| `lume_mcp_session_started` | fixed MCP protocol and stdio transport |+| `lume_mcp_tool_completed` | allowlisted tool and operation, success, fixed error class, and duration bucket |+| `lume_provisioning_started` | guest OS and whether provisioning is asynchronous |+| `lume_provisioning_completed` | guest OS, asynchronous flag, success, fixed error class, and coarse provisioning-duration bucket |+| `lume_update_checked` | fixed source and outcome, strict public target version, and cache-hit flag |+| `lume_update_apply_started` | strict public target version and fixed daemon-not-applicable state |+| `lume_update_apply_completed` | strict public target version, fixed outcome and failure class, and duration bucket |++Legacy per-command and `lume_api_*` attempt events remain during the schema migration. Analytics should use schema-v3 completion and lifecycle events for success, reliability, and active-installation metrics.++Routine telemetry is capped at 1,000 events per process per hour. One successful VM-start value event remains eligible after the cap so a noisy process cannot erase the active-installation signal.++## Data that is never collected++Telemetry builders accept only fixed event names and bounded properties. They do not accept VM or image names, registry or organization names, file paths, URLs, command arguments, MCP arguments or results, SSH commands or output, request or response bodies, unattended configuration, VNC credentials, VM contents, screenshots, or raw error messages.++`LUME_TELEMETRY_SYNTHETIC=true` marks Cua-owned certification traffic so production dashboards can exclude it. It does not enable telemetry when the saved preference or `LUME_TELEMETRY_ENABLED` disables telemetry.diff --git a/libs/lume/README.md b/libs/lume/README.mdindex 544cf708bb..62355c6ae9 100644--- a/libs/lume/README.md+++ b/libs/lume/README.md@@ -54,3 +54,6 @@ lume config telemetry reset-idprocess. A normal uninstall preserves the preference and pseudonymous installationID so a reinstall is recognized as returning. `uninstall.sh --purge` deletesthe ID, markers, configuration, cache, and VMs.++See [Telemetry and privacy](../../docs/content/docs/reference/lume/telemetry.mdx)+for the exact schema-v3 events, integrity controls, and excluded data.diff --git a/libs/lume/src/Commands/CheckUpdate.swift b/libs/lume/src/Commands/CheckUpdate.swiftindex 692e87afda..18ce95f1b9 100644--- a/libs/lume/src/Commands/CheckUpdate.swift+++ b/libs/lume/src/Commands/CheckUpdate.swift@@ -28,6 +28,7 @@ struct CheckUpdate: AsyncParsableCommand {}let state = await LumeVersionCheck.checkUpdateState(noCache: noCache)+ recordUpdateCheckTelemetry(state, source: "cli")if json {try printJSON(state)@@ -74,6 +75,7 @@ struct Update: AsyncParsableCommand {}let state = await LumeVersionCheck.checkUpdateState(noCache: false)+ recordUpdateCheckTelemetry(state, source: "cli")if json {try printJSON(state)@@ -105,7 +107,26 @@ struct Update: AsyncParsableCommand {print("Installing Lume \(latest)...")}- let status = try LumeVersionCheck.runInstallScript(version: latest)+ let applyStartedAt = Date()+ TelemetryClient.shared.recordUpdateApplyStarted(targetVersion: latest)+ let status: Int32+ do {+ status = try LumeVersionCheck.runInstallScript(version: latest)+ } catch {+ TelemetryClient.shared.recordUpdateApplyCompleted(+ targetVersion: latest,+ success: false,+ failureClass: "installer_launch",+ elapsed: Date().timeIntervalSince(applyStartedAt)+ )+ throw error+ }+ TelemetryClient.shared.recordUpdateApplyCompleted(+ targetVersion: latest,+ success: status == 0,+ failureClass: status == 0 ? "none" : "installer_exit",+ elapsed: Date().timeIntervalSince(applyStartedAt)+ )guard status == 0 else {if !json {print("Installer failed with exit status \(status).")@@ -120,6 +141,15 @@ struct Update: AsyncParsableCommand {}}+private func recordUpdateCheckTelemetry(_ state: LumeVersionCheck.State, source: String) {+ TelemetryClient.shared.recordUpdateChecked(+ source: source,+ outcome: state.error != nil ? "unavailable" : (state.updateAvailable ? "available" : "up_to_date"),+ targetVersion: state.latestVersion,+ cacheHit: state.cacheHit+ )+}+private func printJSON<T: Encodable>(_ value: T) throws {let encoder = JSONEncoder()encoder.keyEncodingStrategy = .convertToSnakeCasediff --git a/libs/lume/src/Commands/Convert.swift b/libs/lume/src/Commands/Convert.swiftindex 38aaca7032..ec550e37f7 100644--- a/libs/lume/src/Commands/Convert.swift+++ b/libs/lume/src/Commands/Convert.swift@@ -43,7 +43,7 @@ struct Convert: AsyncParsableCommand {func run() async throws {if verbose { Logger.setVerbose() }- TelemetryClient.shared.record(event: TelemetryEvent.push)+ TelemetryClient.shared.record(event: TelemetryEvent.convert)let targetComponents = targetImage.split(separator: ":")guard targetComponents.count == 2, let primaryTag = targetComponents.last else {diff --git a/libs/lume/src/LumeController.swift b/libs/lume/src/LumeController.swiftindex 2048fea855..1fbc5ff235 100644--- a/libs/lume/src/LumeController.swift+++ b/libs/lume/src/LumeController.swift@@ -516,6 +516,13 @@ final class LumeController {throw error}+ let provisioningStartedAt = Date()+ TelemetryClient.shared.recordProvisioningStarted(+ transport: .cli,+ guestOS: os,+ asynchronous: false+ )+do {// Use createInternal which handles all the actual worktry await createInternal(@@ -539,12 +546,28 @@ final class LumeController {// Clear provisioning marker on successvmDir.clearProvisioningMarker()Logger.info("Provisioning marker cleared", metadata: ["name": name])+ TelemetryClient.shared.recordProvisioningCompleted(+ transport: .cli,+ guestOS: os,+ asynchronous: false,+ success: true,+ errorClass: .none,+ elapsed: Date().timeIntervalSince(provisioningStartedAt)+ )} catch {// Clean up the pre-created directory on failure. If deletion fails, keep the// provisioning marker intact so the leftover VM remains discoverable.cleanupFailedCreateVMDirectory(vmDir, context: "creation")Logger.error("Failed to create VM", metadata: ["error": error.localizedDescription])+ TelemetryClient.shared.recordProvisioningCompleted(+ transport: .cli,+ guestOS: os,+ asynchronous: false,+ success: false,+ errorClass: .operationError,+ elapsed: Date().timeIntervalSince(provisioningStartedAt)+ )throw error}}@@ -574,7 +597,8 @@ final class LumeController {ipsw: String?,storage: String? = nil,unattendedConfig: UnattendedConfig? = nil,- networkMode: NetworkMode = .nat+ networkMode: NetworkMode = .nat,+ telemetryTransport: TelemetryTransport = .http) throws {Logger.info("Starting async VM creation",@@ -619,6 +643,12 @@ final class LumeController {throw error}+ let provisioningStartedAt = Date()+ TelemetryClient.shared.recordProvisioningStarted(+ transport: telemetryTransport,+ guestOS: os,+ asynchronous: true+ )Logger.info("Spawning background task for VM creation", metadata: ["name": name])// All parameters passed to Task are value types (Sendable)@@ -647,6 +677,14 @@ final class LumeController {// Clear marker on successvmDir.clearProvisioningMarker()Logger.info("Async VM creation completed successfully", metadata: ["name": name])+ TelemetryClient.shared.recordProvisioningCompleted(+ transport: telemetryTransport,+ guestOS: os,+ asynchronous: true,+ success: true,+ errorClass: .none,+ elapsed: Date().timeIntervalSince(provisioningStartedAt)+ )} catch {// Clean up the pre-created directory on failure. If deletion fails, keep the@@ -654,6 +692,14 @@ final class LumeController {controller.cleanupFailedCreateVMDirectory(vmDir, context: "async creation")Logger.error("Async VM creation failed",metadata: ["name": name, "error": error.localizedDescription])+ TelemetryClient.shared.recordProvisioningCompleted(+ transport: telemetryTransport,+ guestOS: os,+ asynchronous: true,+ success: false,+ errorClass: .operationError,+ elapsed: Date().timeIntervalSince(provisioningStartedAt)+ )}}}@@ -994,7 +1040,8 @@ final class LumeController {nvramPath: Path? = nil,usbMassStoragePaths: [Path]? = nil,networkMode: NetworkMode? = nil,- clipboard: Bool = false+ clipboard: Bool = false,+ telemetryTransport: TelemetryTransport = .cli) async throws {let normalizedName = normalizeVMName(name: name)Logger.info(@@ -1105,6 +1152,7 @@ final class LumeController {// Load the VM directly using the located VMDirectory and storage contextlet vm = try self.loadVM(vmDir: vmDir, storage: effectiveStorage, diskPath: diskPath, nvramPath: nvramPath)+ vm.telemetryTransport = telemetryTransportSharedVM.shared.setVM(name: normalizedName, vm: vm)try await vm.run(diff --git a/libs/lume/src/Main.swift b/libs/lume/src/Main.swiftindex 6ac85d579f..b2e67712ba 100644--- a/libs/lume/src/Main.swift+++ b/libs/lume/src/Main.swift@@ -102,12 +102,39 @@ extension Lume {}private static func executeCommand() async throws {- var command = try parseAsRoot()+ let arguments = Array(CommandLine.arguments.dropFirst())+ let shouldRecordCompletion = !isTelemetryManagementInvocation()+ let operation = TelemetryClient.commandOperation(arguments: arguments)+ let startedAt = Date()- if var asyncCommand = command as? AsyncParsableCommand {- try await asyncCommand.run()- } else {- try command.run()+ do {+ var command = try parseAsRoot()++ if var asyncCommand = command as? AsyncParsableCommand {+ try await asyncCommand.run()+ } else {+ try command.run()+ }+ if shouldRecordCompletion {+ TelemetryClient.shared.recordOperationCompleted(+ operation: operation,+ transport: .cli,+ success: true,+ errorClass: .none,+ elapsed: Date().timeIntervalSince(startedAt)+ )+ }+ } catch {+ if shouldRecordCompletion {+ TelemetryClient.shared.recordOperationCompleted(+ operation: operation,+ transport: .cli,+ success: false,+ errorClass: error is ValidationError ? .invalidParams : .operationError,+ elapsed: Date().timeIntervalSince(startedAt)+ )+ }+ throw error}}}diff --git a/libs/lume/src/Server/Handlers.swift b/libs/lume/src/Server/Handlers.swiftindex e3ffacc20a..9710011bda 100644--- a/libs/lume/src/Server/Handlers.swift+++ b/libs/lume/src/Server/Handlers.swift@@ -77,6 +77,7 @@ extension Server {let vmName = request.name ?? imageNameawait PullProgressTracker.shared.setProgress(0.0, for: vmName)+ let pullStartedAt = Date()Task.detached { @MainActor @Sendable indo {@@ -93,9 +94,23 @@ extension Server {)await PullProgressTracker.shared.complete(for: vmName)Logger.info("Async pull completed", metadata: ["name": vmName])+ TelemetryClient.shared.recordOperationCompleted(+ operation: "pull_start",+ transport: .http,+ success: true,+ errorClass: .none,+ elapsed: Date().timeIntervalSince(pullStartedAt)+ )} catch {await PullProgressTracker.shared.setError(error.localizedDescription, for: vmName)Logger.error("Async pull failed", metadata: ["name": vmName, "error": error.localizedDescription])+ TelemetryClient.shared.recordOperationCompleted(+ operation: "pull_start",+ transport: .http,+ success: false,+ errorClass: .operationError,+ elapsed: Date().timeIntervalSince(pullStartedAt)+ )}}@@ -585,6 +600,7 @@ extension Server {// Record telemetryTelemetryClient.shared.record(event: TelemetryEvent.apiPush)+ let pushStartedAt = Date()// Trigger push asynchronously, return Accepted immediatelyTask.detached { @MainActor @Sendable in@@ -606,10 +622,24 @@ extension Server {print("Background push completed successfully for image: \(request.imageName):\(request.tags.joined(separator: ","))")+ TelemetryClient.shared.recordOperationCompleted(+ operation: "push",+ transport: .http,+ success: true,+ errorClass: .none,+ elapsed: Date().timeIntervalSince(pushStartedAt)+ )} catch {print("Background push failed for image: \(request.imageName):\(request.tags.joined(separator: ",")) - Error: \(error.localizedDescription)")+ TelemetryClient.shared.recordOperationCompleted(+ operation: "push",+ transport: .http,+ success: false,+ errorClass: .operationError,+ elapsed: Date().timeIntervalSince(pushStartedAt)+ )}}@@ -950,7 +980,8 @@ extension Server {diskPath: diskPath,nvramPath: nvramPath,networkMode: networkMode,- clipboard: clipboard+ clipboard: clipboard,+ telemetryTransport: .http)Logger.info("VM started successfully in background task", metadata: ["name": name])} catch {diff --git a/libs/lume/src/Server/MCPServer.swift b/libs/lume/src/Server/MCPServer.swiftindex 310b89817f..72ac08d3e0 100644--- a/libs/lume/src/Server/MCPServer.swift+++ b/libs/lume/src/Server/MCPServer.swift@@ -27,6 +27,7 @@ final class LumeMCPServer {let transport = StdioTransport()try await mcpServer?.start(transport: transport)+ TelemetryClient.shared.recordMCPSessionStarted()await mcpServer?.waitUntilCompleted()}@@ -543,46 +544,62 @@ final class LumeMCPServer {// MARK: - Tool Call Handlerprivate func handleToolCall(_ params: CallTool.Parameters) async -> CallTool.Result {+ let startedAt = Date()+ let result: CallTool.Resultdo {switch params.name {case "lume_list_vms":- return try await handleListVMs(params.arguments)+ result = try await handleListVMs(params.arguments)case "lume_get_vm":- return try await handleGetVM(params.arguments)+ result = try await handleGetVM(params.arguments)case "lume_run_vm":- return try await handleRunVM(params.arguments)+ result = try await handleRunVM(params.arguments)case "lume_stop_vm":- return try await handleStopVM(params.arguments)+ result = try await handleStopVM(params.arguments)case "lume_clone_vm":- return try await handleCloneVM(params.arguments)+ result = try await handleCloneVM(params.arguments)case "lume_delete_vm":- return try await handleDeleteVM(params.arguments)+ result = try await handleDeleteVM(params.arguments)case "lume_exec":- return try await handleExec(params.arguments)+ result = try await handleExec(params.arguments)case "lume_create_vm":- return try await handleCreateVM(params.arguments)+ result = try await handleCreateVM(params.arguments)case "lume_resize_disk":- return try await handleResizeDisk(params.arguments)+ result = try await handleResizeDisk(params.arguments)case "check_for_update":- return try await handleCheckForUpdate(params.arguments)+ result = try await handleCheckForUpdate(params.arguments)default:- return CallTool.Result(+ result = CallTool.Result(content: [.text("Unknown tool: \(params.name)")],isError: true)}} catch {- return CallTool.Result(+ result = CallTool.Result(content: [.text("Error: \(error.localizedDescription)")],isError: true)}+ let success = result.isError != true+ TelemetryClient.shared.recordMCPToolCompleted(+ toolName: params.name,+ success: success,+ errorClass: success ? .none : (params.name == "check_for_update" ? .unavailable : .operationError),+ elapsed: Date().timeIntervalSince(startedAt)+ )+ return result}// MARK: - Tool Implementationsprivate func handleCheckForUpdate(_ args: [String: Value]?) async throws -> CallTool.Result {let state = await LumeVersionCheck.checkUpdateState(noCache: false)+ TelemetryClient.shared.recordUpdateChecked(+ source: "mcp",+ outcome: state.error != nil ? "unavailable" : (state.updateAvailable ? "available" : "up_to_date"),+ targetVersion: state.latestVersion,+ cacheHit: state.cacheHit+ )let encoder = JSONEncoder()encoder.keyEncodingStrategy = .convertToSnakeCaseencoder.outputFormatting = [.prettyPrinted, .sortedKeys]@@ -649,7 +666,8 @@ final class LumeMCPServer {noDisplay: noDisplay,sharedDirectories: sharedDirectories,storage: storage,- clipboard: clipboard+ clipboard: clipboard,+ telemetryTransport: .mcpStdio)} catch {Logger.error(@@ -827,7 +845,8 @@ final class LumeMCPServer {display: "1920x1080",ipsw: ipsw,storage: storage,- unattendedConfig: unattendedConfig+ unattendedConfig: unattendedConfig,+ telemetryTransport: .mcpStdio)var response = "VM '\(name)' creation started. Status: provisioning."diff --git a/libs/lume/src/Server/Server.swift b/libs/lume/src/Server/Server.swiftindex ee1fc4939c..6a5e8126b1 100644--- a/libs/lume/src/Server/Server.swift+++ b/libs/lume/src/Server/Server.swift@@ -473,7 +473,37 @@ final class Server: @unchecked Sendable {return HTTPResponse(statusCode: .notFound, body: "Not found")}- let response = try await route.handler(request)+ let operation = TelemetryClient.httpOperation(method: route.method, routePath: route.path)+ let startedAt = Date()+ let response: HTTPResponse+ do {+ response = try await route.handler(request)+ let success = response.statusCode.rawValue < 400+ let errorClass: TelemetryErrorClass+ switch response.statusCode {+ case .badRequest: errorClass = .invalidParams+ case .notFound: errorClass = .notFound+ case .internalServerError: errorClass = .internalError+ default: errorClass = .none+ }+ TelemetryClient.shared.recordOperationCompleted(+ operation: operation,+ transport: .http,+ success: success,+ errorClass: errorClass,+ elapsed: Date().timeIntervalSince(startedAt),+ phase: response.statusCode == .accepted ? "accepted" : "completed"+ )+ } catch {+ TelemetryClient.shared.recordOperationCompleted(+ operation: operation,+ transport: .http,+ success: false,+ errorClass: .internalError,+ elapsed: Date().timeIntervalSince(startedAt)+ )+ throw error+ }Logger.info("Sending response",diff --git a/libs/lume/src/Telemetry/TelemetryClient.swift b/libs/lume/src/Telemetry/TelemetryClient.swiftindex 70e074b874..536e7b7f47 100644--- a/libs/lume/src/Telemetry/TelemetryClient.swift+++ b/libs/lume/src/Telemetry/TelemetryClient.swift@@ -1,5 +1,25 @@+import Darwinimport Foundation+enum TelemetryTransport: String, Sendable {+ case cli+ case http+ case mcpStdio = "mcp_stdio"+}++enum TelemetryErrorClass: String, Sendable {+ case none+ case invalidParams = "invalid_params"+ case notFound = "not_found"+ case conflict+ case permissionDenied = "permission_denied"+ case unavailable+ case transportError = "transport_error"+ case operationError = "operation_error"+ case internalError = "internal_error"+ case unknownTool = "unknown_tool"+}+/// Pseudonymous, content-free product telemetry for Lume.////// Telemetry is enabled by default, can be persistently disabled through@@ -15,13 +35,17 @@ final class TelemetryClient: @unchecked Sendable {static let installationRecordedFileName = ".installation_recorded"static let releaseRecordedDirectoryName = ".telemetry_releases"static let lifecycleRetryAfterFileName = ".telemetry_retry_after"+ static let lifecycleLockFileName = ".telemetry_lifecycle.lock"static let envTelemetryEnabled = "LUME_TELEMETRY_ENABLED"static let envTelemetryDebug = "LUME_TELEMETRY_DEBUG"+ static let envTelemetrySynthetic = "LUME_TELEMETRY_SYNTHETIC"static let envInstallChannel = "LUME_INSTALL_CHANNEL"static let requestTimeout: TimeInterval = 3static let flushTimeout: TimeInterval = 1.5static let lifecycleRetryBackoff: TimeInterval = 15 * 60- static let schemaVersion = 2+ static let schemaVersion = 3+ static let routineEventLimitPerHour = 1_000+ static let routineEventWindow: TimeInterval = 60 * 60static let processSessionId = UUID().uuidStringstatic let allowedInstallChannels: Swift.Set<String> = ["install_script", "update_apply", "first_run",@@ -50,6 +74,10 @@ final class TelemetryClient: @unchecked Sendable {private let poster: Poster?private let preferenceProvider: @Sendable () -> Boolprivate let identityLock = NSLock()+ private let rateLimitLock = NSLock()+ private var rateLimitWindowStarted = Date()+ private var rateLimitCaptured = 0+ private var rateLimitCapturedValueEvent = falseprivate let pendingRequests = DispatchGroup()init(@@ -82,7 +110,10 @@ final class TelemetryClient: @unchecked Sendable {/// typed properties survive `sanitizeProperties`; strings originating/// from image names, VM names, paths, prompts, or arguments are dropped.func record(event: String, properties: [String: Any] = [:]) {- guard isEnabled(), let request = makeRequest(event: event, properties: properties) else {+ guard TelemetryEvent.allowed.contains(event), isEnabled(),+ shouldCaptureRoutineEvent(event: event),+ let request = makeRequest(event: event, properties: properties)+ else {return}@@ -93,12 +124,157 @@ final class TelemetryClient: @unchecked Sendable {}}+ func recordOperationCompleted(+ operation: String,+ transport: TelemetryTransport,+ success: Bool,+ errorClass: TelemetryErrorClass,+ elapsed: TimeInterval,+ guestOS: String? = nil,+ phase: String = "completed"+ ) {+ var properties: [String: Any] = [+ "operation": Self.normalizedOperation(operation),+ "transport": transport.rawValue,+ "success": success,+ "error_class": success ? TelemetryErrorClass.none.rawValue : errorClass.rawValue,+ "duration_bucket": Self.durationBucket(elapsed),+ "phase": phase == "accepted" ? "accepted" : "completed",+ ]+ if let guestOS {+ properties["guest_os"] = Self.normalizedGuestOS(guestOS)+ }+ record(event: TelemetryEvent.operationCompleted, properties: properties)+ }++ func recordMCPToolCompleted(+ toolName: String,+ success: Bool,+ errorClass: TelemetryErrorClass,+ elapsed: TimeInterval+ ) {+ record(+ event: TelemetryEvent.mcpToolCompleted,+ properties: [+ "tool_name": Self.normalizedMCPTool(toolName),+ "operation": Self.normalizedMCPToolOperation(toolName),+ "transport": TelemetryTransport.mcpStdio.rawValue,+ "success": success,+ "error_class": success ? TelemetryErrorClass.none.rawValue : errorClass.rawValue,+ "duration_bucket": Self.durationBucket(elapsed),+ ])+ }++ func recordMCPSessionStarted() {+ record(+ event: TelemetryEvent.mcpSessionStarted,+ properties: [+ "transport": TelemetryTransport.mcpStdio.rawValue,+ "protocol": "mcp",+ ])+ }++ func recordVMStarted(transport: TelemetryTransport, guestOS: String) {+ record(+ event: TelemetryEvent.vmStarted,+ properties: [+ "transport": transport.rawValue,+ "guest_os": Self.normalizedGuestOS(guestOS),+ "success": true,+ ])+ }++ func recordProvisioningStarted(+ transport: TelemetryTransport, guestOS: String, asynchronous: Bool+ ) {+ record(+ event: TelemetryEvent.provisioningStarted,+ properties: [+ "transport": transport.rawValue,+ "guest_os": Self.normalizedGuestOS(guestOS),+ "asynchronous": asynchronous,+ ])+ }++ func recordProvisioningCompleted(+ transport: TelemetryTransport,+ guestOS: String,+ asynchronous: Bool,+ success: Bool,+ errorClass: TelemetryErrorClass,+ elapsed: TimeInterval+ ) {+ record(+ event: TelemetryEvent.provisioningCompleted,+ properties: [+ "transport": transport.rawValue,+ "guest_os": Self.normalizedGuestOS(guestOS),+ "asynchronous": asynchronous,+ "success": success,+ "error_class": success ? TelemetryErrorClass.none.rawValue : errorClass.rawValue,+ "duration_bucket": Self.provisioningDurationBucket(elapsed),+ ])+ }++ func recordUpdateChecked(+ source: String, outcome: String, targetVersion: String?, cacheHit: Bool+ ) {+ var properties: [String: Any] = [+ "source": Self.normalizedUpdateSource(source),+ "outcome": Self.normalizedUpdateCheckOutcome(outcome),+ "cache_hit": cacheHit,+ "transport": source == "mcp"+ ? TelemetryTransport.mcpStdio.rawValue : TelemetryTransport.cli.rawValue,+ ]+ if let targetVersion = Self.strictReleaseVersion(targetVersion) {+ properties["target_version"] = targetVersion+ }+ record(event: TelemetryEvent.updateChecked, properties: properties)+ }++ func recordUpdateApplyStarted(targetVersion: String) {+ var properties: [String: Any] = [+ "transport": TelemetryTransport.cli.rawValue,+ "daemon_was_running": false,+ ]+ if let version = Self.strictReleaseVersion(targetVersion) {+ properties["target_version"] = version+ }+ record(event: TelemetryEvent.updateApplyStarted, properties: properties)+ }++ func recordUpdateApplyCompleted(+ targetVersion: String?, success: Bool, failureClass: String, elapsed: TimeInterval+ ) {+ var properties: [String: Any] = [+ "transport": TelemetryTransport.cli.rawValue,+ "outcome": success ? "success" : "failed",+ "failure_class": success ? "none" : Self.normalizedUpdateFailureClass(failureClass),+ "daemon_was_running": false,+ "duration_bucket": Self.durationBucket(elapsed),+ ]+ if let version = Self.strictReleaseVersion(targetVersion) {+ properties["target_version"] = version+ }+ record(event: TelemetryEvent.updateApplyCompleted, properties: properties)+ }+/// Record the legacy installation event once and the release event once/// per Lume version. Both events honor consent. Each marker is written/// only after its corresponding request receives HTTP 2xx.func recordInstallation(channel: String? = nil) async {guard isEnabled(), !lifecycleRetryDeferred() else { return }+ guard let lockFile = acquireLifecycleLock() else { return }+ defer {+ flock(lockFile, LOCK_UN)+ close(lockFile)+ }++ // A concurrent process may have recorded the lifecycle while this process+ // waited for the lock, so marker state must only be read after acquisition.+ guard !lifecycleRetryDeferred() else { return }+let installChannel = Self.normalizedInstallChannel(channel ?? ProcessInfo.processInfo.environment[Constants.envInstallChannel])@@ -221,6 +397,61 @@ final class TelemetryClient: @unchecked Sendable {return raw}+ static func commandOperation(arguments: [String]) -> String {+ guard let raw = arguments.first else { return "help" }+ switch raw {+ case "create", "pull", "push", "convert", "images", "clone", "get", "set", "run",+ "stop", "ssh", "sip", "ipsw", "serve", "delete", "prune", "config", "logs",+ "update", "setup":+ return raw+ case "ls": return "list"+ case "check-update": return "check_update"+ case "dump-docs": return "dump_docs"+ case "help", "--help", "-h": return "help"+ default: return "other"+ }+ }++ static func httpOperation(method: String, routePath: String) -> String {+ let key = "\(method.uppercased()) \(routePath)"+ return [+ "GET /lume/vms": "list", "GET /lume/vms/:name": "get",+ "DELETE /lume/vms/:name": "delete", "POST /lume/vms": "create",+ "POST /lume/vms/clone": "clone", "PATCH /lume/vms/:name": "set",+ "POST /lume/vms/:name/run": "run", "POST /lume/vms/:name/stop": "stop",+ "POST /lume/vms/:name/setup": "setup", "GET /lume/ipsw": "ipsw",+ "POST /lume/pull": "pull", "POST /lume/pull/start": "pull_start",+ "POST /lume/prune": "prune", "GET /lume/images": "images",+ "GET /lume/config": "config_get", "POST /lume/config": "config_update",+ "GET /lume/config/locations": "locations_list",+ "POST /lume/config/locations": "locations_add",+ "DELETE /lume/config/locations/:name": "locations_remove",+ "POST /lume/config/locations/default/:name": "locations_default",+ "GET /lume/logs": "logs", "POST /lume/vms/push": "push",+ "GET /lume/host/status": "host_status",+ ][key] ?? "other"+ }++ static func durationBucket(_ elapsed: TimeInterval) -> String {+ switch max(0, elapsed) {+ case ..<0.1: "lt_100ms"+ case ..<0.5: "100_499ms"+ case ..<2: "500ms_1_999ms"+ case ..<10: "2s_9_999ms"+ default: "gte_10s"+ }+ }++ static func provisioningDurationBucket(_ elapsed: TimeInterval) -> String {+ switch max(0, elapsed) {+ case ..<60: "lt_1min"+ case ..<300: "1_4min"+ case ..<900: "5_14min"+ case ..<1_800: "15_29min"+ default: "gte_30min"+ }+ }+// MARK: - Consent and identityprivate func effectiveState() -> (enabled: Bool, source: String, persistedEnabled: Bool) {@@ -281,10 +512,13 @@ final class TelemetryClient: @unchecked Sendable {eventProperties["product_version"] = Lume.Version.currenteventProperties["telemetry_schema_version"] = Constants.schemaVersioneventProperties["os_family"] = "macos"- eventProperties["os_major"] = String(ProcessInfo.processInfo.operatingSystemVersion.majorVersion)+ eventProperties["os_major"] = String(+ ProcessInfo.processInfo.operatingSystemVersion.majorVersion)eventProperties["arch"] = architecture()eventProperties["is_ci"] = isCI()- eventProperties["transport"] = transport(event: event, properties: properties)+ eventProperties["is_synthetic"] = isSynthetic()+ eventProperties["transport"] =+ eventProperties["transport"] as? String ?? transport(event: event, properties: properties)eventProperties["process_session_id"] = Constants.processSessionIdeventProperties["id_persisted"] = identity.persistedeventProperties["$lib"] = "lume-swift"@@ -318,16 +552,18 @@ final class TelemetryClient: @unchecked Sendable {if event == TelemetryEvent.serve, let mode = properties["mode"] as? String,mode == "mcp" || mode == "http"{- return mode+ return mode == "mcp" ? TelemetryTransport.mcpStdio.rawValue : TelemetryTransport.http.rawValue}return "cli"}private func sanitizeProperties(_ properties: [String: Any]) -> [String: Any] {let allowedKeys: Swift.Set<String> = [- "cpu", "disk_size", "disk_size_gb", "has_unattended", "headless",- "install_channel", "memory", "memory_gb", "mode", "os_type",- "product_version",+ "asynchronous", "cache_hit", "cpu", "daemon_was_running", "disk_size",+ "disk_size_gb", "duration_bucket", "error_class", "failure_class", "guest_os",+ "has_unattended", "headless", "install_channel", "memory", "memory_gb", "mode",+ "operation", "os_type", "outcome", "phase", "product_version", "protocol", "source",+ "success", "target_version", "tool_name", "transport",]var sanitized: [String: Any] = [:]for (key, value) in properties where allowedKeys.contains(key) {@@ -341,13 +577,15 @@ final class TelemetryClient: @unchecked Sendable {case let value as Double where value.isFinite:sanitized[key] = valuecase let value as String:- // Only bounded enums are accepted. User-derived strings such- // as image names and custom preset names never pass through.- let allowedValues: Swift.Set<String> = [- "custom", "first_run", "install_script", "linux", "macos",- "offline", "update_apply", "mcp", "http",- ]- sanitized[key] = allowedValues.contains(value) ? value : "unknown"+ if key == "target_version" {+ if let version = Self.strictReleaseVersion(value) {+ sanitized[key] = version+ }+ } else if Self.allowedPropertyValue(key: key, value: value) {+ sanitized[key] = value+ } else {+ sanitized[key] = "unknown"+ }default:continue}@@ -355,6 +593,115 @@ final class TelemetryClient: @unchecked Sendable {return sanitized}+ private static func allowedPropertyValue(key: String, value: String) -> Bool {+ switch key {+ case "duration_bucket":+ return [+ "lt_100ms", "100_499ms", "500ms_1_999ms", "2s_9_999ms", "gte_10s",+ "lt_1min", "1_4min", "5_14min", "15_29min", "gte_30min",+ ].contains(value)+ case "error_class":+ return [+ "none", "invalid_params", "not_found", "conflict", "permission_denied",+ "unavailable", "transport_error", "operation_error", "internal_error", "unknown_tool",+ ].contains(value)+ case "failure_class":+ return ["none", "installer_exit", "installer_launch", "unknown"].contains(value)+ case "guest_os", "os_type":+ return ["macos", "linux", "windows", "unknown"].contains(value)+ case "install_channel":+ return Constants.allowedInstallChannels.contains(value)+ case "mode":+ return ["custom", "offline", "mcp", "http"].contains(value)+ case "operation":+ return normalizedOperation(value) == value+ case "outcome":+ return ["up_to_date", "available", "unavailable", "success", "failed"].contains(value)+ case "phase":+ return ["accepted", "completed"].contains(value)+ case "protocol":+ return value == "mcp"+ case "source":+ return ["cli", "mcp", "background"].contains(value)+ case "tool_name":+ return normalizedMCPTool(value) == value+ case "transport":+ return ["cli", "http", "mcp_stdio"].contains(value)+ case "product_version":+ return strictReleaseVersion(value) != nil+ default:+ return false+ }+ }++ private static func normalizedOperation(_ raw: String) -> String {+ let allowed: Swift.Set<String> = [+ "check_update", "clone", "config", "config_get", "config_update", "convert", "create",+ "delete", "dump_docs", "exec", "get", "help", "host_status", "images", "ipsw", "list",+ "locations_add", "locations_default", "locations_list", "locations_remove", "logs", "pull",+ "pull_start", "prune", "push", "resize", "run", "serve", "set", "setup", "sip", "ssh",+ "stop", "update",+ ]+ return allowed.contains(raw) ? raw : "other"+ }++ private static func normalizedMCPTool(_ raw: String) -> String {+ let allowed: Swift.Set<String> = [+ "check_for_update", "lume_clone_vm", "lume_create_vm", "lume_delete_vm", "lume_exec",+ "lume_get_vm", "lume_list_vms", "lume_resize_disk", "lume_run_vm", "lume_stop_vm",+ ]+ return allowed.contains(raw) ? raw : "other"+ }++ private static func normalizedMCPToolOperation(_ tool: String) -> String {+ [+ "check_for_update": "check_update", "lume_clone_vm": "clone", "lume_create_vm": "create",+ "lume_delete_vm": "delete", "lume_exec": "exec", "lume_get_vm": "get",+ "lume_list_vms": "list", "lume_resize_disk": "resize", "lume_run_vm": "run",+ "lume_stop_vm": "stop",+ ][tool] ?? "other"+ }++ private static func normalizedGuestOS(_ raw: String) -> String {+ let value = raw.lowercased()+ return ["macos", "linux", "windows"].contains(value) ? value : "unknown"+ }++ private static func normalizedUpdateSource(_ raw: String) -> String {+ ["cli", "mcp", "background"].contains(raw) ? raw : "background"+ }++ private static func normalizedUpdateCheckOutcome(_ raw: String) -> String {+ ["up_to_date", "available", "unavailable"].contains(raw) ? raw : "unavailable"+ }++ private static func normalizedUpdateFailureClass(_ raw: String) -> String {+ ["installer_exit", "installer_launch"].contains(raw) ? raw : "unknown"+ }++ static func strictReleaseVersion(_ raw: String?) -> String? {+ guard let raw else { return nil }+ let value = raw.trimmingCharacters(in: .whitespacesAndNewlines)+ let normalized = value.hasPrefix("v") ? String(value.dropFirst()) : value+ guard !normalized.isEmpty, normalized.count <= 64, !normalized.contains("+") else { return nil }+ let split = normalized.split(separator: "-", maxSplits: 1, omittingEmptySubsequences: false)+ let core = split[0].split(separator: ".", omittingEmptySubsequences: false)+ guard core.count == 3,+ core.allSatisfy({+ !$0.isEmpty && $0.count <= 6 && $0.allSatisfy({ $0.isASCII && $0.isNumber })+ })+ else { return nil }+ if split.count == 2 {+ let suffix = split[1]+ guard !suffix.isEmpty, suffix.count <= 32,+ suffix.allSatisfy({+ $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "." || $0 == "-")+ })+ else { return nil }+ }+ return normalized+ }+private func send(request: URLRequest, event: String) async -> Bool {if let poster {return await poster(request)@@ -371,6 +718,25 @@ final class TelemetryClient: @unchecked Sendable {}}+ private func shouldCaptureRoutineEvent(event: String, now: Date = Date()) -> Bool {+ rateLimitLock.lock()+ defer { rateLimitLock.unlock() }+ if now.timeIntervalSince(rateLimitWindowStarted) >= Constants.routineEventWindow {+ rateLimitWindowStarted = now+ rateLimitCaptured = 0+ rateLimitCapturedValueEvent = false+ }+ let isValueEvent = event == TelemetryEvent.vmStarted+ guard rateLimitCaptured < Constants.routineEventLimitPerHour else {+ guard isValueEvent, !rateLimitCapturedValueEvent else { return false }+ rateLimitCapturedValueEvent = true+ return true+ }+ rateLimitCaptured += 1+ rateLimitCapturedValueEvent = rateLimitCapturedValueEvent || isValueEvent+ return true+ }+// MARK: - Paths and platform fieldsprivate var installationIdURL: URL {@@ -389,6 +755,26 @@ final class TelemetryClient: @unchecked Sendable {homeDirectory.appendingPathComponent(Constants.lifecycleRetryAfterFileName)}+ private var lifecycleLockURL: URL {+ homeDirectory.appendingPathComponent(Constants.lifecycleLockFileName)+ }++ private func acquireLifecycleLock() -> Int32? {+ do {+ try FileManager.default.createDirectory(at: homeDirectory, withIntermediateDirectories: true)+ } catch {+ debugLog("Failed to create lifecycle lock directory: \(error.localizedDescription)")+ return nil+ }+ let descriptor = Darwin.open(lifecycleLockURL.path, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR)+ guard descriptor >= 0 else { return nil }+ guard flock(descriptor, LOCK_EX | LOCK_NB) == 0 else {+ close(descriptor)+ return nil+ }+ return descriptor+ }+private func releaseMarkerURL(version: String) -> URL {let safeVersion = version.map { character -> Character incharacter.isLetter || character.isNumber || character == "." || character == "-"@@ -465,6 +851,11 @@ final class TelemetryClient: @unchecked Sendable {return variables.contains { ProcessInfo.processInfo.environment[$0] != nil }}+ private func isSynthetic() -> Bool {+ ProcessInfo.processInfo.environment[Constants.envTelemetrySynthetic]+ .flatMap(Self.parseBoolean) ?? false+ }+private func debugLog(_ message: String) {guard let value = ProcessInfo.processInfo.environment[Constants.envTelemetryDebug],Self.parseBoolean(value) == true@@ -484,11 +875,24 @@ enum TelemetryEvent {static let stop = "lume_stop"static let delete = "lume_delete"static let clone = "lume_clone"+ static let convert = "lume_convert"static let pull = "lume_pull"static let push = "lume_push"static let serve = "lume_serve"static let setup = "lume_setup"static let config = "lume_config"+ static let sip = "lume_sip"+ static let ssh = "lume_ssh"++ static let operationCompleted = "lume_operation_completed"+ static let mcpSessionStarted = "lume_mcp_session_started"+ static let mcpToolCompleted = "lume_mcp_tool_completed"+ static let vmStarted = "lume_vm_started"+ static let provisioningStarted = "lume_provisioning_started"+ static let provisioningCompleted = "lume_provisioning_completed"+ static let updateChecked = "lume_update_checked"+ static let updateApplyStarted = "lume_update_apply_started"+ static let updateApplyCompleted = "lume_update_apply_completed"static let apiVMList = "lume_api_vm_list"static let apiVMGet = "lume_api_vm_get"@@ -501,4 +905,14 @@ enum TelemetryEvent {static let apiPull = "lume_api_pull"static let apiPush = "lume_api_push"static let apiImages = "lume_api_images"++ static let allowed: Swift.Set<String> = [+ install, releaseInstalled, create, run, stop, delete, clone, convert, pull, push, serve, setup,+ config,+ sip, ssh, operationCompleted, mcpSessionStarted, mcpToolCompleted, vmStarted,+ provisioningStarted,+ provisioningCompleted, updateChecked, updateApplyStarted, updateApplyCompleted, apiVMList,+ apiVMGet, apiVMCreate, apiVMRun, apiVMStop, apiVMDelete, apiVMClone, apiVMUpdate, apiPull,+ apiPush, apiImages,+ ]}diff --git a/libs/lume/src/VM/VM.swift b/libs/lume/src/VM/VM.swiftindex c3fb83efb3..b8c7e26c63 100644--- a/libs/lume/src/VM/VM.swift+++ b/libs/lume/src/VM/VM.swift@@ -44,6 +44,7 @@ class VM {// MARK: - Propertiesvar vmDirContext: VMDirContext+ var telemetryTransport: TelemetryTransport?@MainActorprivate var virtualizationService: VMVirtualizationService?@@ -314,6 +315,12 @@ class VM {"Starting VM via virtualization service", metadata: ["name": vmDirContext.name])try await service.start()Logger.info("VM started successfully", metadata: ["name": vmDirContext.name])+ if let telemetryTransport {+ TelemetryClient.shared.recordVMStarted(+ transport: telemetryTransport,+ guestOS: vmDirContext.config.os+ )+ }// Open the VNC client only after VM start to avoid connecting to an empty framebuffer.if !noDisplay {diff --git a/libs/lume/tests/TelemetryClientTests.swift b/libs/lume/tests/TelemetryClientTests.swiftindex b13a0d3158..98e8c8b919 100644--- a/libs/lume/tests/TelemetryClientTests.swift+++ b/libs/lume/tests/TelemetryClientTests.swift@@ -35,20 +35,37 @@ private actor TelemetryRequestRecorder {&& properties["$geoip_disable"] as? Bool == true}- func hasV2Envelope(event: String) -> Bool {+ func hasV3Envelope(event: String, transport: String = "cli") -> Bool {guardlet payload = payloads.first(where: { $0["event"] as? String == event }),let properties = payload["properties"] as? [String: Any]else { return false }- return properties["telemetry_schema_version"] as? Int == 2+ return properties["telemetry_schema_version"] as? Int == 3&& properties["os_family"] as? String == "macos"&& Int(properties["os_major"] as? String ?? "") != nil&& properties["os"] == nil&& properties["os_version"] == nil- && properties["transport"] as? String == "cli"+ && properties["transport"] as? String == transport+ && properties["is_synthetic"] as? Bool == false&& (properties["process_session_id"] as? String).flatMap(UUID.init(uuidString:)) != nil}+ func stringProperty(event: String, key: String) -> String? {+ guard+ let payload = payloads.first(where: { $0["event"] as? String == event }),+ let properties = payload["properties"] as? [String: Any]+ else { return nil }+ return properties[key] as? String+ }++ func boolProperty(event: String, key: String) -> Bool? {+ guard+ let payload = payloads.first(where: { $0["event"] as? String == event }),+ let properties = payload["properties"] as? [String: Any]+ else { return nil }+ return properties[key] as? Bool+ }+func distinctIds() -> [String] {payloads.compactMap { $0["distinct_id"] as? String }}@@ -89,6 +106,27 @@ func installationMarkersRequireAcceptedRequests() async throws {#expect(await recorder.count() == 2)}+@Test("concurrent lifecycle registration is serialized by the filesystem lock")+func concurrentLifecycleRegistrationIsSerialized() async throws {+ let home = try telemetryTempDirectory()+ defer { try? FileManager.default.removeItem(at: home) }+ let recorder = TelemetryRequestRecorder()+ let poster: TelemetryClient.Poster = { request in await recorder.post(request) }+ let first = TelemetryClient(+ homeDirectory: home, poster: poster, preferenceProvider: { true })+ let second = TelemetryClient(+ homeDirectory: home, poster: poster, preferenceProvider: { true })++ async let firstRegistration: Void = first.recordInstallation(channel: "install_script")+ async let secondRegistration: Void = second.recordInstallation(channel: "install_script")+ _ = await (firstRegistration, secondRegistration)++ #expect(await recorder.count() == 2)+ #expect(+ Swift.Set(await recorder.events())+ == Swift.Set([TelemetryEvent.install, TelemetryEvent.releaseInstalled]))+}+@Test("failed installation requests defer retries without writing success markers")func failedInstallationRequestsDeferRetries() async throws {let home = try telemetryTempDirectory()@@ -182,7 +220,118 @@ func routinePayloadIsContentFree() async throws {#expect(await recorder.hasContentFreePayload(event: TelemetryEvent.pull))- #expect(await recorder.hasV2Envelope(event: TelemetryEvent.pull))+ #expect(await recorder.hasV3Envelope(event: TelemetryEvent.pull))+}++@Test("schema v3 completion events contain only bounded comparison fields")+func completionEventsUseBoundedSchema() async throws {+ let home = try telemetryTempDirectory()+ defer { try? FileManager.default.removeItem(at: home) }+ let recorder = TelemetryRequestRecorder()+ let client = TelemetryClient(+ homeDirectory: home,+ poster: { request in await recorder.post(request) },+ preferenceProvider: { true }+ )++ client.recordOperationCompleted(+ operation: "run",+ transport: .http,+ success: true,+ errorClass: .none,+ elapsed: 0.75,+ guestOS: "windows"+ )+ client.recordMCPToolCompleted(+ toolName: "lume_exec",+ success: false,+ errorClass: .operationError,+ elapsed: 12+ )+ client.recordVMStarted(transport: .mcpStdio, guestOS: "macos")+ client.recordUpdateChecked(+ source: "mcp", outcome: "available", targetVersion: "v1.2.3", cacheHit: true)+ #expect(await client.flush())++ #expect(+ await recorder.hasV3Envelope(event: TelemetryEvent.operationCompleted, transport: "http"))+ #expect(+ await recorder.stringProperty(event: TelemetryEvent.operationCompleted, key: "operation")+ == "run")+ #expect(+ await recorder.boolProperty(event: TelemetryEvent.operationCompleted, key: "success") == true)+ #expect(+ await recorder.stringProperty(event: TelemetryEvent.operationCompleted, key: "duration_bucket")+ == "500ms_1_999ms")+ #expect(+ await recorder.stringProperty(event: TelemetryEvent.operationCompleted, key: "guest_os")+ == "windows")++ #expect(+ await recorder.stringProperty(event: TelemetryEvent.mcpToolCompleted, key: "tool_name")+ == "lume_exec")+ #expect(+ await recorder.stringProperty(event: TelemetryEvent.mcpToolCompleted, key: "operation")+ == "exec")+ #expect(+ await recorder.stringProperty(event: TelemetryEvent.mcpToolCompleted, key: "error_class")+ == "operation_error")+ #expect(+ await recorder.stringProperty(event: TelemetryEvent.mcpToolCompleted, key: "duration_bucket")+ == "gte_10s")++ #expect(await recorder.boolProperty(event: TelemetryEvent.vmStarted, key: "success") == true)+ #expect(+ await recorder.stringProperty(event: TelemetryEvent.vmStarted, key: "guest_os") == "macos")++ #expect(+ await recorder.stringProperty(event: TelemetryEvent.updateChecked, key: "target_version")+ == "1.2.3")+ #expect(+ await recorder.boolProperty(event: TelemetryEvent.updateChecked, key: "cache_hit") == true)+ #expect(+ await recorder.stringProperty(event: TelemetryEvent.updateChecked, key: "transport")+ == "mcp_stdio")+}++@Test("telemetry mappings remain bounded and stable")+func telemetryMappingsAreBounded() {+ let commands = [+ "create": "create", "pull": "pull", "push": "push", "convert": "convert",+ "images": "images", "clone": "clone", "get": "get", "set": "set", "ls": "list",+ "run": "run", "stop": "stop", "ssh": "ssh", "sip": "sip", "ipsw": "ipsw",+ "serve": "serve", "delete": "delete", "prune": "prune", "config": "config",+ "logs": "logs", "check-update": "check_update", "update": "update", "setup": "setup",+ "dump-docs": "dump_docs",+ ]+ for (command, operation) in commands {+ #expect(TelemetryClient.commandOperation(arguments: [command]) == operation)+ }+ #expect(TelemetryClient.commandOperation(arguments: ["private-command"]) == "other")+ let routes = [+ "GET /lume/vms": "list", "GET /lume/vms/:name": "get",+ "DELETE /lume/vms/:name": "delete", "POST /lume/vms": "create",+ "POST /lume/vms/clone": "clone", "PATCH /lume/vms/:name": "set",+ "POST /lume/vms/:name/run": "run", "POST /lume/vms/:name/stop": "stop",+ "POST /lume/vms/:name/setup": "setup", "GET /lume/ipsw": "ipsw",+ "POST /lume/pull": "pull", "POST /lume/pull/start": "pull_start",+ "POST /lume/prune": "prune", "GET /lume/images": "images",+ "GET /lume/config": "config_get", "POST /lume/config": "config_update",+ "GET /lume/config/locations": "locations_list",+ "POST /lume/config/locations": "locations_add",+ "DELETE /lume/config/locations/:name": "locations_remove", "GET /lume/logs": "logs",+ "POST /lume/config/locations/default/:name": "locations_default",+ "POST /lume/vms/push": "push", "GET /lume/host/status": "host_status",+ ]+ for (route, operation) in routes {+ let pieces = route.split(separator: " ", maxSplits: 1).map(String.init)+ #expect(TelemetryClient.httpOperation(method: pieces[0], routePath: pieces[1]) == operation)+ }+ #expect(TelemetryClient.durationBucket(0.099) == "lt_100ms")+ #expect(TelemetryClient.durationBucket(0.1) == "100_499ms")+ #expect(TelemetryClient.provisioningDurationBucket(900) == "15_29min")+ #expect(TelemetryClient.strictReleaseVersion("v1.2.3") == "1.2.3")+ #expect(TelemetryClient.strictReleaseVersion("customer/path") == nil)}@Test("invalid persisted installation ID is replaced and never emitted")