// SPDX-License-Identifier: GPL-3.0-or-later import XCTest import AppKit import CryptoKit import PDFKit import ImageIO /// Explicit opt-in qualification of the approved, published game packages. /// Ordinary test runs use authored fixtures elsewhere and skip this network case. /// No normal app settings, user disks, installed app or source checkout are opened. final class SoftwareLibraryPublishedGameTests: XCTestCase { private struct Fixture: Sendable { let slug: String let receiptDate: String let edition: String let diskSHA256: String let ramKiB: Int let keyboardOnly: Bool var receiptFilename: String { receiptDate + "-" + slug + "-downloads.json" } var releaseID: String { "vccplus." + slug + "." + edition } static let approved: [Fixture] = [ .init(slug: "bone-quest", receiptDate: "2026-11-11", edition: "2026-11-11", diskSHA256: "373a3f387daf541b1eb4edd3421a125dd57094e600ee48d162802ac22f65ceba", ramKiB: 512, keyboardOnly: true), .init(slug: "capital-quest", receiptDate: "2026-11-12", edition: "2026-11-12", diskSHA256: "3a1b42279e47460d06d3b9d31bdeac87d59ed67e6d67a1c5f1dbfa6fe884574e", ramKiB: 512, keyboardOnly: true), .init(slug: "quadrapassel", receiptDate: "2026-11-11", edition: "build-05", diskSHA256: "d05ab25fd90171b048cce54f3af18ca6d0bd81335e138044ff05315e99cbf582", ramKiB: 128, keyboardOnly: false) ] } private struct Game: Sendable { let fixture: Fixture let publicationID: String var slug: String { fixture.slug } let record: LibraryJSON let release: SoftwareLibraryRelease var owned: SoftwareLibraryOwnedGame { release.ownedGame! } } private struct Inputs: Sendable { let output: URL let games: [Game] let toolchain: URL? } private var macRoot: URL { URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() } private static var architecture: String { #if arch(arm64) return "arm64" #else return "x86_64" #endif } private func inputs() async throws -> Inputs { let environment = ProcessInfo.processInfo.environment guard let records = environment["VCC_EXCLUSIVE_RECEIPT_DIR"], let output = environment["VCC_EXCLUSIVE_ACCEPTANCE_ROOT"] else { throw XCTSkip("Set explicit published receipt and ignored acceptance-output directories to run real game qualification") } guard records.hasPrefix("/"), output.hasPrefix("/"), output.contains("/.build/") || output.hasPrefix("/private/tmp/") || output.hasPrefix("/tmp/") else { throw ProfileFailure.message("Published-game acceptance output must be an explicit ignored build or temporary directory") } let directory = URL(fileURLWithPath: output).appendingPathComponent("PublishedGames-" + Self.architecture + "-" + UUID().uuidString) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) let prepared: SoftwareLibraryCatalog? if let path = environment["VCC_EXCLUSIVE_CATALOG"] { prepared = try await SoftwareLibraryCatalog.load(from: URL(fileURLWithPath: path)) } else { prepared = nil } var games: [Game] = [] for fixture in Fixture.approved { let data = try Data(contentsOf: URL(fileURLWithPath: records).appendingPathComponent(fixture.receiptFilename)) guard let publicRecord = try JSONSerialization.jsonObject(with: data) as? [String: Any], publicRecord["state"] as? String == "verified", let publicationID = publicRecord["publicationId"] as? String, var record = publicRecord["contract"] as? [String: Any] else { throw ProfileFailure.message("A verified portable published-game record is required") } // The retained owner evidence explicitly records RGB. Mirror the // intake's documented effective recommendation without altering receipts. var setup = record["setup"] as! [String: Any] var configuration = setup["configuration"] as! [String: Any] configuration["video"] = "rgb" if fixture.keyboardOnly { configuration["controls"] = ["keyboard": "Use the keyboard to choose a mode, enter answers and submit with Enter; see the game manual for editing keys."] } setup["configuration"] = configuration; record["setup"] = setup let json = try JSONDecoder().decode(LibraryJSON.self, from: JSONSerialization.data(withJSONObject: record)) let owned = try XCTUnwrap(SoftwareLibraryOwnedGame.parse(json)) XCTAssertEqual(owned.releaseID, fixture.releaseID) XCTAssertEqual(owned.diskSHA256, fixture.diskSHA256) XCTAssertEqual(owned.ramKiB, fixture.ramKiB) XCTAssertEqual(owned.processor, "6809") let release: SoftwareLibraryRelease if let prepared { release = try XCTUnwrap(prepared.releases.first(where: { $0.id == owned.releaseID })) XCTAssertEqual(release.ownedGame?.gameID, owned.gameID) XCTAssertEqual(release.packageSHA256, owned.package.sha256) XCTAssertEqual(release.ownedGame?.diskSHA256, fixture.diskSHA256) XCTAssertEqual(release.ownedGame?.source.package, owned.source.package) XCTAssertEqual(release.ownedGame?.manualPDF, owned.manualPDF) XCTAssertEqual(release.setup.ramKiB, owned.ramKiB) XCTAssertEqual(release.setup.configuration["video"].string, "rgb") } else { release = SoftwareLibraryRelease(id: owned.releaseID, titleID: owned.gameID, name: owned.package.url.lastPathComponent, category: owned.primaryBrowseCategory, mediaType: "disk", contentRole: "software", sourceURL: owned.projectURL, modifiedAt: nil, modifiedPrecision: nil, modifiedTimezone: nil, packageSHA256: owned.package.sha256, byteSize: owned.package.byteSize, languageStatus: "english", metadata: .object(["owned_game": json, "title": json["title"], "system": .string("CoCo 3")]), setup: .init(status: "spot-checked", command: "DOS\r", instructions: "Approved published game; Cold Restart then DOS.", configuration: json["setup"]["configuration"], selectedMembers: json["setup"]["selected_members"], reasons: [], validation: json["setup"]["validation"]), assets: [], downloadURLs: [owned.package.url]) } try release.validatePresentationMetadata() games.append(Game(fixture: fixture, publicationID: publicationID, record: json, release: release)) } let toolchain = environment["VCC_EXCLUSIVE_TOOLCHAIN"].map { URL(fileURLWithPath: $0) } return Inputs(output: directory, games: games, toolchain: toolchain) } private func variant(_ release: SoftwareLibraryRelease, use6309: Bool) throws -> SoftwareLibraryRelease { var object = try JSONSerialization.jsonObject(with: JSONEncoder().encode(release)) as! [String: Any] var setup = object["setup"] as! [String: Any] var configuration = setup["configuration"] as! [String: Any] configuration["processor"] = use6309 ? "6309" : "6809" setup["configuration"] = configuration; object["setup"] = setup var metadata = object["metadata"] as! [String: Any] var owned = metadata["owned_game"] as! [String: Any] var ownedSetup = owned["setup"] as! [String: Any] var ownedConfiguration = ownedSetup["configuration"] as! [String: Any] ownedConfiguration["processor"] = use6309 ? "6309" : "6809" ownedSetup["configuration"] = ownedConfiguration; owned["setup"] = ownedSetup metadata["owned_game"] = owned; object["metadata"] = metadata // HD6309 is a test-only recipe variant, never written into the approved // canonical MC6809 catalog or portable publication record. return try JSONDecoder().decode(SoftwareLibraryRelease.self, from: JSONSerialization.data(withJSONObject: object)) } @MainActor private func step(_ operation: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot { await withCheckedContinuation { done in operation { done.resume(returning: $0) } } } @MainActor private func debugger(_ controller: VCCMachineController) async -> VCCDebuggerSnapshot { await withCheckedContinuation { done in controller.debuggerSnapshot(address: 0, followPC: false, memoryAddress: 0) { done.resume(returning: $0) } } } @MainActor private func settle(_ model: MachineModel) async throws { for _ in 0..<1000 { if !model.busy && !model.diskSaving { return } try await Task.sleep(nanoseconds: 10_000_000) } throw ProfileFailure.message("Published-game fixture did not settle") } @MainActor private func withMachine(output: URL, use6309: Bool, body: (MachineModel, VCCMachineController, UserDefaults) async throws -> Void) async throws { _ = NSApplication.shared // Standalone hostless runs still need AppKit's input lifecycle. let suite = "PublishedGame-" + UUID().uuidString let defaults = UserDefaults(suiteName: suite)! defer { defaults.removePersistentDomain(forName: suite) } let controller = VCCMachineController() let model = MachineModel(diskStore: .init(url: output.appendingPathComponent("Disks.json")), controller: controller, displayDefaults: defaults, inputStore: .init(url: output.appendingPathComponent("Input.json"))) do { try await settle(model) var profile = ConfigurationProfile(name: "Published-game acceptance") profile.systemROM = macRoot.appendingPathComponent("LocalResources/ROMs/coco3.rom") profile.media.rom = macRoot.appendingPathComponent("LocalResources/ROMs/disk11.rom") try XCTSkipUnless(FileManager.default.fileExists(atPath: profile.systemROM!.path) && FileManager.default.fileExists(atPath: profile.media.rom!.path), "Stage explicit local CoCo/Disk BASIC ROM inputs") profile.sound = false; profile.videoOutput = 0 profile.machine.ram = 2; profile.machine.use6309 = !use6309 profile.input.right.source = .keyboard; profile.input.left.source = .none var cartridges = CartridgeAssignments(); cartridges.multiPak = true; cartridges.mpiConfigured = true cartridges.physicalSlot = 4; cartridges.slots[4].kind = .floppy; profile.media.cartridges = cartridges await model.loadProfile(profile); XCTAssertNil(model.profileError) model.resume(); try await settle(model) try await body(model, controller, defaults) } catch { await withCheckedContinuation { done in model.shutdown { done.resume() } }; throw error } await withCheckedContinuation { done in model.shutdown { done.resume() } } } private static func sha(_ data: Data) -> String { SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() } private func artwork(_ descriptor: LibraryJSON, id: String) throws -> SoftwareLibraryAsset { let url = try XCTUnwrap(URL(string: XCTUnwrap(descriptor["url"].string))) let hash = try XCTUnwrap(descriptor["sha256"].string) let size = try XCTUnwrap(descriptor["byte_size"].integer) var asset = SoftwareLibraryAsset(id: id, name: id, kind: "screenshot", sourceURL: url, sha256: hash, byteSize: Int64(size), credit: "Published game title capture", matchStatus: "project-owned", matchReason: "Owner-supplied verified capture") asset.thumbnailURL = url; asset.thumbnailSHA256 = hash; asset.thumbnailByteSize = Int64(size) return asset } private struct Raster { let width: Int, height: Int let rgba: [UInt8] init(_ png: Data) throws { guard let source = CGImageSourceCreateWithData(png as CFData, nil), let image = CGImageSourceCreateImageAtIndex(source, 0, nil), image.width > 0, image.height > 0, image.width <= 1280, image.height <= 960 else { throw ProfileFailure.message("Published acceptance image could not be decoded") } width = image.width; height = image.height var pixels = [UInt8](repeating: 0, count: width * height * 4) let made = pixels.withUnsafeMutableBytes { bytes -> Bool in guard let context = CGContext(data: bytes.baseAddress, width: image.width, height: image.height, bitsPerComponent: 8, bytesPerRow: image.width * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue) else { return false } context.interpolationQuality = .none context.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height)) return true } guard made else { throw ProfileFailure.message("Published acceptance image could not be rendered") } rgba = pixels } func similarity(to reference: Raster) -> Double { var histogram: [UInt32: Int] = [:] for index in stride(from: 0, to: reference.rgba.count, by: 4) { let key = UInt32(reference.rgba[index]) << 16 | UInt32(reference.rgba[index + 1]) << 8 | UInt32(reference.rgba[index + 2]) histogram[key, default: 0] += 1 } let background = histogram.max(by: { $0.value < $1.value })?.key ?? 0 var matched = 0, foreground = 0 for y in 0.. 100 ? Double(matched) / Double(foreground) : 0 } } @MainActor private func waitForTitle(reference: Raster, controller: VCCMachineController, output: URL) async throws -> (VCCMachineSnapshot, Double) { var best: (VCCMachineSnapshot, Data, Double)? var readyFrames = 0 let started = await step(controller.snapshot) func retain(_ snapshot: VCCMachineSnapshot, png: Data, score: Double) throws { try png.write(to: output, options: .atomic) let metadata: [String: Any] = ["reference_width": reference.width, "reference_height": reference.height, "reference_uses_full_frame": reference.width == 640 && reference.height == 480, "foreground_similarity": score, "generation": snapshot.generation, "frame": snapshot.frames, "observed_fields": snapshot.frames - min(snapshot.frames, started.frames), "active_rect": [snapshot.activeVideoRect.minX, snapshot.activeVideoRect.minY, snapshot.activeVideoRect.width, snapshot.activeVideoRect.height]] try JSONSerialization.data(withJSONObject: metadata, options: [.prettyPrinted, .sortedKeys]) .write(to: output.deletingPathExtension().appendingPathExtension("json"), options: .atomic) } // Bone Quest's owner fixture waits up to 4,200 guest fields after DOS. // Allow that bounded boot interval without accepting a partial title. for _ in 0..<150 { let snapshot = await step(controller.snapshot) if snapshot.frames >= started.frames && snapshot.frames - started.frames > 4_500 { break } // Published helper captures can include the complete 640x480 raster // (e.g. 225-line GIME output centered vertically). Preserve that // reference coordinate system instead of stretching its black border // into the active picture. Legacy cropped references use active bounds. let area = reference.width == 640 && reference.height == 480 ? VideoGeometry.fullFrame : snapshot.activeVideoRect if snapshot.state == .running, snapshot.pasteRemaining == 0, let capture = try? ScreenCapture(pixels: snapshot.pixels, area: area), let png = try? capture.png(), let raster = try? Raster(png) { let score = raster.similarity(to: reference) if score > (best?.2 ?? -1) { best = (snapshot, png, score) } // A partly drawn logo is not a ready game. Require the complete // owner-supplied menu on successive observations, allowing a cursor blink. readyFrames = score >= 0.95 ? readyFrames + 1 : 0 if readyFrames >= 2 { try retain(snapshot, png: png, score: score) return (snapshot, score) } } try await Task.sleep(nanoseconds: 500_000_000) } if let best { try retain(best.0, png: best.1, score: best.2) } throw ProfileFailure.message("Published title capture did not match its owner reference; best foreground similarity \(best?.2 ?? 0). Inspect retained frame before changing the qualification.") } @MainActor private func qualifySourcesAndManual(_ game: Game, model: MachineModel, controller: VCCMachineController, defaults: UserDefaults, output: URL, toolchain: URL?) async throws -> [String: Any] { _ = await step(controller.pause); try await settle(model) let before = await debugger(controller) let importer = SoftwareLibrarySourceImporter(cacheDirectory: output.appendingPathComponent("Source originals")) let imported = try await importer.importProject(game.owned.source, to: output.appendingPathComponent("Editable Source With Spaces")) let project = try CMOCProject.open(at: imported.projectDirectory) let originalMakefile = try Data(contentsOf: project.makefileURL) XCTAssertEqual(project.configuration.entrySource, game.owned.source.entrySource) let workspace = CMOCDevelopmentModel(machine: model, toolchain: toolchain, defaults: defaults, buildRoot: output.appendingPathComponent("Workspace builds"), recoveryRoot: output.appendingPathComponent("Recovery")) let opened = try await workspace.openImportedProject(at: imported.projectDirectory, expectedProjectID: workspace.assistantProjectID, preferredConfiguration: game.owned.source.buildConfiguration) XCTAssertTrue(opened); XCTAssertFalse(workspace.building); XCTAssertNil(workspace.artifact) if let configuration = game.owned.source.buildConfiguration { XCTAssertEqual(workspace.configurationName, configuration) } XCTAssertEqual(workspace.configurationName, "Release", "The approved source package should open in its playable Release configuration") XCTAssertEqual(try Data(contentsOf: project.makefileURL), originalMakefile) let afterOpen = await debugger(controller) XCTAssertEqual(afterOpen.machine.generation, before.machine.generation) XCTAssertEqual(afterOpen.machine.cycles, before.machine.cycles) XCTAssertEqual(afterOpen.registers, before.registers) XCTAssertEqual(afterOpen.logicalMemory, before.logicalMemory) let manual = try await SoftwareLibraryManualCache().localCopy(for: XCTUnwrap(game.release.primaryManualAsset), directory: output.appendingPathComponent("Manuals")) let document = try XCTUnwrap(PDFDocument(url: manual)); XCTAssertGreaterThan(document.pageCount, 0) let offline = URLSessionConfiguration.ephemeral; offline.protocolClasses = [PublishedGameOfflineTransport.self] let cachedManual = try await SoftwareLibraryManualCache(session: URLSession(configuration: offline)) .localCopy(for: XCTUnwrap(game.release.primaryManualAsset), directory: output.appendingPathComponent("Manuals")) XCTAssertEqual(cachedManual, manual) let cover = try artwork(game.record["artwork"]["cover"], id: game.slug + "-cover") let coverData = try await SoftwareLibraryArtworkCache().thumbnail(for: cover, directory: output.appendingPathComponent("Artwork")) XCTAssertEqual(Self.sha(coverData), cover.thumbnailSHA256) var report: [String: Any] = ["source_zip_sha256": Self.sha(try Data(contentsOf: imported.originalPackage)), "source_open_without_build": true, "manual_pages": document.pageCount, "manual_sha256": Self.sha(try Data(contentsOf: manual)), "manual_cached_without_network": true, "cover_sha256": Self.sha(coverData), "configuration": workspace.configurationName] if let toolchain { let build = try await CMOCBuildService(toolchain: toolchain, buildRoot: output.appendingPathComponent("Source qualification")) .build(project: project, overlays: [:], action: .disk, configuration: "Release") XCTAssertEqual(build.diskSHA256, game.owned.diskSHA256, "The imported source must reproduce the approved disk with bundled tools") XCTAssertEqual(Self.sha(try Data(contentsOf: XCTUnwrap(build.diskURL))), game.owned.diskSHA256) report["rebuilt_disk_sha256"] = build.diskSHA256 report["source_build_configuration"] = build.configurationName } else { report["source_build"] = "Not requested: set VCC_EXCLUSIVE_TOOLCHAIN to the published app's Toolchain directory" } XCTAssertEqual(try Data(contentsOf: project.makefileURL), originalMakefile, "Source qualification must preserve the author's Makefile") report["makefile_sha256"] = Self.sha(originalMakefile) let afterBuild = await debugger(controller) XCTAssertEqual(afterBuild.machine.generation, before.machine.generation) XCTAssertEqual(afterBuild.machine.cycles, before.machine.cycles) XCTAssertEqual(afterBuild.registers, before.registers) XCTAssertEqual(afterBuild.logicalMemory, before.logicalMemory) return report } @MainActor func testPublishedFirstAndCachedPlaySourceAndManualAcceptance() async throws { let inputs = try await inputs() var results: [[String: Any]] = [] for game in inputs.games { let installRoot = inputs.output.appendingPathComponent(game.slug) let installer = SoftwareLibraryInstaller(root: installRoot.appendingPathComponent("Library")) let receipt = try await installer.install(game.release) let original = receipt.workingDirectory.deletingLastPathComponent().appendingPathComponent("Original/Files/" + game.owned.diskPath) XCTAssertEqual(Self.sha(try Data(contentsOf: original)), game.owned.diskSHA256) let hero = try artwork(game.record["artwork"]["hero"], id: game.slug + "-title") let referenceData = try await SoftwareLibraryArtworkCache().thumbnail(for: hero, directory: installRoot.appendingPathComponent("Artwork")) let reference = try Raster(referenceData) for use6309 in [false, true] { let output = installRoot.appendingPathComponent(use6309 ? "6309" : "6809") try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true) let release = try variant(game.release, use6309: use6309) try await withMachine(output: output, use6309: use6309) { model, controller, defaults in let plan = try SoftwareLibraryLaunchPlan.prepare(release: release, receipt: receipt) XCTAssertTrue(plan.usesCuratedStartup); XCTAssertEqual(plan.commands, ["DOS"]) XCTAssertEqual(plan.ramKiB, game.fixture.ramKiB) let before = await step(controller.snapshot) let prepared = try await model.prepareLibraryLaunch(plan) XCTAssertEqual(prepared.profile.input.right.source, game.fixture.keyboardOnly ? .none : .keyboard, "Keyboard-only recipes suppress keyboard joystick interception; joystick games preserve the user's assignment") let launched = try await model.launchLibrary(prepared); XCTAssertNil(launched.message) let (first, firstScore) = try await waitForTitle(reference: reference, controller: controller, output: output.appendingPathComponent("first-title.png")) XCTAssertNotEqual(first.generation, before.generation) XCTAssertEqual(first.use6309, use6309) XCTAssertEqual(first.ramConfiguration, game.fixture.ramKiB == 128 ? 0 : 1) XCTAssertEqual(first.videoOutput, 0); XCTAssertTrue(first.disks[0].mounted) var result: [String: Any] = ["id": game.owned.gameID, "cpu": use6309 ? "6309" : "6809", "release_id": game.owned.releaseID, "publication_id": game.publicationID, "receipt": game.fixture.receiptFilename, "ram_kib": plan.ramKiB, "first_foreground_similarity": firstScore, "reference_width": reference.width, "reference_height": reference.height, "first_generation": first.generation, "first_frame": first.frames, "canonical_recipe": !use6309, "disk_sha256": game.owned.diskSHA256] if !use6309 { result["source_and_manual"] = try await qualifySourcesAndManual(game, model: model, controller: controller, defaults: defaults, output: output, toolchain: inputs.toolchain) } else { _ = await step(controller.pause); try await settle(model) } let working = receipt.workingDirectory.appendingPathComponent(game.owned.diskPath) let savedBytes = try Data(contentsOf: working) let offline = URLSessionConfiguration.ephemeral; offline.protocolClasses = [PublishedGameOfflineTransport.self] let cached = try await SoftwareLibraryInstaller(root: installRoot.appendingPathComponent("Library"), session: URLSession(configuration: offline)) .install(game.release) XCTAssertEqual(cached.workingDirectory, receipt.workingDirectory) XCTAssertEqual(try Data(contentsOf: working), savedBytes, "Cached installation must not replace current writable bytes") let beforeCached = await step(controller.snapshot) let cachedPlan = try SoftwareLibraryLaunchPlan.prepare(release: release, receipt: cached) let cachedPrepared = try await model.prepareLibraryLaunch(cachedPlan) let cachedLaunch = try await model.launchLibrary(cachedPrepared); XCTAssertNil(cachedLaunch.message) let (second, cachedScore) = try await waitForTitle(reference: reference, controller: controller, output: output.appendingPathComponent("cached-title.png")) XCTAssertNotEqual(second.generation, beforeCached.generation) XCTAssertEqual(second.ramConfiguration, first.ramConfiguration); XCTAssertEqual(second.use6309, use6309) XCTAssertEqual(Self.sha(try Data(contentsOf: original)), game.owned.diskSHA256) result["cached_foreground_similarity"] = cachedScore result["cached_generation"] = second.generation result["cached_install_without_network"] = true result["working_sha_before_cached_play"] = Self.sha(savedBytes) results.append(result) try JSONSerialization.data(withJSONObject: results, options: [.prettyPrinted, .sortedKeys]) .write(to: inputs.output.appendingPathComponent("Acceptance.json"), options: .atomic) } } } XCTAssertEqual(results.count, Fixture.approved.count * 2) } } private final class PublishedGameOfflineTransport: URLProtocol, @unchecked Sendable { override class func canInit(with request: URLRequest) -> Bool { true } override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } override func startLoading() { client?.urlProtocol(self, didFailWithError: URLError(.notConnectedToInternet)) } override func stopLoading() { } }