1815 lines
131 KiB
Swift
1815 lines
131 KiB
Swift
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
import XCTest
|
|
|
|
@MainActor
|
|
final class MCPPlaytestTests: XCTestCase {
|
|
func testPhysicalKeysCoverGameplayWithoutHostLayoutOrArbitraryText() {
|
|
XCTAssertEqual(MCPPlaytest.chord("left"), UInt64(1) << 29)
|
|
XCTAssertEqual(MCPPlaytest.chord("right"), UInt64(1) << 30)
|
|
XCTAssertEqual(MCPPlaytest.chord("down"), UInt64(1) << 28)
|
|
XCTAssertEqual(MCPPlaytest.chord("z"), UInt64(1) << 26)
|
|
XCTAssertEqual(MCPPlaytest.chord("x"), UInt64(1) << 24)
|
|
XCTAssertEqual(MCPPlaytest.chord("space"), UInt64(1) << 31)
|
|
XCTAssertEqual(MCPPlaytest.chord("period"), UInt64(1) << 46)
|
|
XCTAssertEqual(MCPPlaytest.chord("period"), CocoKeyboard.chord(for: "."))
|
|
XCTAssertEqual(MCPPlaytest.chord("backspace"), MCPPlaytest.chord("left"))
|
|
for key in ["LEFT", "Z", "zx", "LOADM", "", "é", "\n", ".", "PERIOD"] { XCTAssertNil(MCPPlaytest.chord(key)) }
|
|
}
|
|
|
|
func testJoystickPlanValidationRejectsAmbiguousPortsAndUnsafeValues() throws {
|
|
let right: [String: Any] = ["port": "right", "x": 0, "y": 8191, "buttons": ["fire1"]]
|
|
XCTAssertEqual(try MCPPlaytestJoystick.snapshots([right]).first?["x"] as? Int, 0)
|
|
XCTAssertEqual(try MCPPlaytestJoystick.snapshots([]).count, 0)
|
|
var left = right; left["port"] = "left"; left["x"] = 16383; left["buttons"] = ["fire1", "fire2"]
|
|
XCTAssertEqual(try MCPPlaytestJoystick.snapshots([right, left]).count, 2)
|
|
XCTAssertThrowsError(try MCPPlaytestJoystick.snapshots([right, right]))
|
|
let invalidAxes: [Any] = [true, -1, 16384, 1.5, Double.nan, Double.infinity, "0", NSNull()]
|
|
for value in invalidAxes {
|
|
var bad = right; bad["x"] = value
|
|
XCTAssertThrowsError(try MCPPlaytestJoystick.snapshots([bad]))
|
|
}
|
|
let invalidUpdates: [[String: Any]] = [["port": "0"], ["buttons": ["fire3"]], ["buttons": ["fire1", "fire1"]], ["interface": "standard"]]
|
|
for update in invalidUpdates {
|
|
var bad = right; bad.merge(update) { _, new in new }
|
|
XCTAssertThrowsError(try MCPPlaytestJoystick.snapshots([bad]))
|
|
}
|
|
XCTAssertThrowsError(try MCPPlaytestJoystick.snapshots(NSNull()))
|
|
}
|
|
|
|
func testJoystickGuestAxesButtonsReleaseRetriesAndDiagnosticsOnBothProcessors() async throws {
|
|
let (helper, system, diskROM) = try inputs()
|
|
let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCJoystick-" + UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: root) }
|
|
let program = "10 CLS\n20 X=JOYSTK(0):Y=JOYSTK(1):U=JOYSTK(2):V=JOYSTK(3):B=PEEK(65280)AND15\n30 PRINT@0,\"R\";X;Y;\" \";\n40 PRINT@32,\"L\";U;V;\" \";\n50 PRINT@64,\"B\";B;\" \";\n60 K$=INKEY$:IF K$<>\"\" THEN PRINT@96,\"K \";K$;\" \";\n70 GOTO20\nRUN\n"
|
|
XCTAssertLessThanOrEqual(program.utf8.count, 256)
|
|
for cpu in ["6809", "6309"] {
|
|
let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: disk(), bootCommands: program,
|
|
projectID: "joystick-fixture", revision: 1, artifactID: UUID().uuidString, cpu: cpu,
|
|
helperURL: helper, retentionDirectory: root.appendingPathComponent(cpu))
|
|
defer { test.invalidate() }
|
|
assertProcessor(test.startReceipt, cpu: cpu)
|
|
let initial = try await test.reply("get_playtest_input", arguments: ["run_id": test.runID])
|
|
XCTAssertEqual((initial["input"] as? [String: Any])?["neutral"] as? Bool, true)
|
|
var sequence = 0
|
|
func hold(_ ports: [[String: Any]], keys: [String] = []) async throws -> [String: Any] {
|
|
sequence += 1
|
|
return try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": "joy-\(sequence)",
|
|
"steps": [["keys": keys, "fields": 18, "joysticks": ports]]])
|
|
}
|
|
func text(_ name: String) async throws -> String {
|
|
let capture = try await test.capture()
|
|
if let directory = ProcessInfo.processInfo.environment["VCC_TEST_GUEST_CAPTURES"],
|
|
let encoded = capture["png_base64"] as? String, let png = Data(base64Encoded: encoded) {
|
|
let folder = URL(fileURLWithPath: directory, isDirectory: true)
|
|
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
|
|
try png.write(to: folder.appendingPathComponent("joystick-\(cpu)-\(name).png"), options: .atomic)
|
|
}
|
|
return capture["screen_text"] as? String ?? ""
|
|
}
|
|
let ports: [[String: Any]] = [["port": "right", "x": 0, "y": 16383, "buttons": ["fire1"]],
|
|
["port": "left", "x": 16383, "y": 0, "buttons": ["fire2"]]]
|
|
let receipt = try await hold(ports)
|
|
XCTAssertEqual((receipt["input"] as? [String: Any])?["neutral"] as? Bool, true)
|
|
let trace = try XCTUnwrap(receipt["input_trace"] as? [[String: Any]])
|
|
XCTAssertEqual(trace.count, 1)
|
|
XCTAssertEqual(trace.first?["fields_advanced"] as? Int, 18)
|
|
let applied = try XCTUnwrap(trace.first?["input"] as? [String: Any])
|
|
XCTAssertEqual(applied["neutral"] as? Bool, false)
|
|
let appliedPorts = try XCTUnwrap(applied["ports"] as? [[String: Any]])
|
|
XCTAssertEqual(appliedPorts[0]["x"] as? Int, 0)
|
|
XCTAssertEqual(appliedPorts[1]["y"] as? Int, 0)
|
|
let observed = try await text("held")
|
|
XCTAssertNotNil(observed.range(of: #"R\s+0\s+63"#, options: .regularExpression), observed)
|
|
XCTAssertNotNil(observed.range(of: #"L\s+63\s+0"#, options: .regularExpression), observed)
|
|
XCTAssertNotNil(observed.range(of: #"B\s+6"#, options: .regularExpression), observed)
|
|
let retry = try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": "joy-1",
|
|
"steps": [["keys": [], "fields": 18, "joysticks": ports]]])
|
|
XCTAssertEqual(receipt["field_clock"] as? Int, retry["field_clock"] as? Int)
|
|
let before = try await test.reply("get_playtest_input", arguments: ["run_id": test.runID])
|
|
let again = try await test.reply("get_playtest_input", arguments: ["run_id": test.runID])
|
|
XCTAssertEqual(before["field_clock"] as? Int, again["field_clock"] as? Int)
|
|
XCTAssertEqual((again["input"] as? [String: Any])?["neutral"] as? Bool, true)
|
|
_ = try await hold([])
|
|
let neutral = try await text("released")
|
|
XCTAssertNotNil(neutral.range(of: #"R\s+3[12]\s+3[12]"#, options: .regularExpression), neutral)
|
|
XCTAssertNotNil(neutral.range(of: #"L\s+3[12]\s+3[12]"#, options: .regularExpression), neutral)
|
|
XCTAssertNotNil(neutral.range(of: #"B\s+15"#, options: .regularExpression), neutral)
|
|
for (port, fire, mask) in [("right", "fire1", 14), ("right", "fire2", 11), ("left", "fire1", 13), ("left", "fire2", 7)] {
|
|
_ = try await hold([["port": port, "x": 8191, "y": 8191, "buttons": [fire]]])
|
|
let seen = try await text("\(port)-\(fire)")
|
|
XCTAssertNotNil(seen.range(of: "B\\s+\(mask)(?:\\s|$)", options: .regularExpression), seen)
|
|
}
|
|
let combination = try await hold([["port": "right", "x": 16383, "y": 8191, "buttons": ["fire1", "fire2"]]], keys: ["shift", "a"])
|
|
let combinedTrace = try XCTUnwrap(combination["input_trace"] as? [[String: Any]])
|
|
XCTAssertEqual((combinedTrace.first?["input"] as? [String: Any])?["keyboard_held"] as? Bool, true)
|
|
let combinedText = try await text("combined")
|
|
XCTAssertNotNil(combinedText.range(of: #"B\s+10"#, options: .regularExpression), combinedText)
|
|
// CoCo joystick buttons share the keyboard's PIA rows. BASIC's
|
|
// scanner need not recognize a letter while those rows are low.
|
|
// Verify the Shift chord with axes held but the buttons released.
|
|
_ = try await hold([]) // Let the guest observe release before a fresh press.
|
|
_ = try await hold([["port": "right", "x": 16383, "y": 8191, "buttons": []]], keys: ["shift", "a"])
|
|
let shiftedText = try await text("shifted")
|
|
XCTAssertNotNil(shiftedText.range(of: #"K\s+A"#, options: .regularExpression), shiftedText)
|
|
let preInvalid = try await test.reply("get_playtest_input", arguments: ["run_id": test.runID])
|
|
do {
|
|
_ = try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": "bad-late",
|
|
"steps": [["keys": [], "fields": 3, "joysticks": ports],
|
|
["keys": [], "fields": 3, "joysticks": [["port": "right", "x": true, "y": 8191, "buttons": []]]]]])
|
|
XCTFail("Invalid late step must reject the complete plan")
|
|
} catch { }
|
|
let postInvalid = try await test.reply("get_playtest_input", arguments: ["run_id": test.runID])
|
|
XCTAssertEqual(preInvalid["field_clock"] as? Int, postInvalid["field_clock"] as? Int)
|
|
XCTAssertEqual((postInvalid["input"] as? [String: Any])?["neutral"] as? Bool, true)
|
|
let restarted = try await test.reply("restart_playtest", arguments: ["run_id": test.runID, "request_id": "restart-joy"])
|
|
XCTAssertEqual((restarted["input"] as? [String: Any])?["neutral"] as? Bool, true)
|
|
_ = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "stop-joy"])
|
|
}
|
|
}
|
|
|
|
/// Private JSONL fixtures exercise the child worker independently of public
|
|
/// host ownership/retention tests. Only authored bytes and opt-in ROMs enter it.
|
|
private final class MediaWorkerClient: @unchecked Sendable {
|
|
private let process = Process(), input = Pipe(), output = Pipe()
|
|
private let queue = DispatchQueue(label: "com.brianholman.vccplus.tests.media-worker")
|
|
private var buffered = Data()
|
|
init(_ helper: URL) throws {
|
|
process.executableURL = helper; process.standardInput = input; process.standardOutput = output
|
|
process.standardError = FileHandle.nullDevice
|
|
try process.run()
|
|
}
|
|
func close() { if process.isRunning { process.terminate() } }
|
|
deinit { close() }
|
|
func request(_ value: [String: Any]) async throws -> [String: Any] {
|
|
let encoded = try JSONSerialization.data(withJSONObject: value, options: [.sortedKeys])
|
|
return try await withCheckedThrowingContinuation { continuation in
|
|
queue.async { [self] in
|
|
let timeout = DispatchWorkItem { self.close() }
|
|
DispatchQueue.global().asyncAfter(deadline: .now() + 30, execute: timeout)
|
|
defer { timeout.cancel() }
|
|
do {
|
|
try input.fileHandleForWriting.write(contentsOf: encoded + Data([10]))
|
|
while !buffered.contains(10) {
|
|
let chunk = output.fileHandleForReading.availableData
|
|
guard !chunk.isEmpty, buffered.count + chunk.count <= 1024 * 1024 else {
|
|
throw NSError(domain: "MediaWorkerFixture", code: 1,
|
|
userInfo: [NSLocalizedDescriptionKey: "worker_reply_unavailable"])
|
|
}
|
|
buffered.append(chunk)
|
|
}
|
|
let end = buffered.firstIndex(of: 10)!
|
|
let line = Data(buffered[..<end]); buffered.removeSubrange(...end)
|
|
let reply = try XCTUnwrap(JSONSerialization.jsonObject(with: line) as? [String: Any])
|
|
if let error = reply["error"] as? String {
|
|
throw NSError(domain: "MediaWorkerFixture", code: 2, userInfo: [NSLocalizedDescriptionKey: error])
|
|
}
|
|
continuation.resume(returning: try XCTUnwrap(reply["result"] as? [String: Any]))
|
|
} catch { continuation.resume(throwing: error) }
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func testWorkerMediaExchangePreservesGuestAndSavedBytesOnBothProcessors() async throws {
|
|
let (helper, system, diskROM) = try inputs()
|
|
let original = disk()
|
|
// SAVE is guest Disk BASIC I/O, not debugger or host-memory injection.
|
|
let commands = try CocoPaste("10 PRINT 7\nSAVE\"TEST\"\n", mode: .text)
|
|
for cpu in ["6809", "6309"] {
|
|
let worker = try MediaWorkerClient(helper); defer { worker.close() }
|
|
let started = try await worker.request(["op": "init", "system_rom": system.base64EncodedString(),
|
|
"disk_rom": diskROM.base64EncodedString(), "disk": original.base64EncodedString(),
|
|
"boot_keys": commands.chords.map { NSNumber(value: $0) }, "cpu": cpu, "media_id": "home"])
|
|
assertProcessor(started, cpu: cpu)
|
|
XCTAssertNotEqual(started["disk_sha256"] as? String, CMOCProject.sha256(original))
|
|
do { _ = try await worker.request(["op": "export_media"]); XCTFail("Running export must fail") }
|
|
catch { XCTAssertTrue(error.localizedDescription.contains("playtest_not_stopped")) }
|
|
_ = try await worker.request(["op": "pause"])
|
|
let saved = try await worker.request(["op": "export_media"])
|
|
let savedBytes = try XCTUnwrap((saved["disk_base64"] as? String).flatMap { Data(base64Encoded: $0) })
|
|
let savedHash = try XCTUnwrap(saved["disk_sha256"] as? String)
|
|
XCTAssertEqual(CMOCProject.sha256(savedBytes), savedHash)
|
|
XCTAssertEqual(saved["disk_dirty"] as? Bool, true)
|
|
XCTAssertEqual(saved["media_generation"] as? Int, 0)
|
|
let before = try await worker.request(["op": "debug"])
|
|
let frame = try await worker.request(["op": "capture"])
|
|
var wrong = original; wrong[0] = 0x44 // Valid disk geometry; game payload is intentionally wrong.
|
|
let swap: [String: Any] = ["op": "exchange_media", "expected_media_generation": 0,
|
|
"expected_disk_sha256": savedHash, "media_id": "wrong-world", "disk_base64": wrong.base64EncodedString()]
|
|
let inserted = try await worker.request(swap)
|
|
XCTAssertEqual(inserted["disk_sha256"] as? String, CMOCProject.sha256(wrong))
|
|
XCTAssertEqual(inserted["media_generation"] as? Int, 1)
|
|
XCTAssertEqual(inserted["previous_disk_sha256"] as? String, savedHash)
|
|
XCTAssertEqual(inserted["advances_execution"] as? Bool, false)
|
|
for key in ["field_clock", "cycles", "generation", "pc", "boot"] {
|
|
XCTAssertEqual((before[key] as? NSNumber), (inserted[key] as? NSNumber), key)
|
|
}
|
|
let after = try await worker.request(["op": "debug"])
|
|
XCTAssertEqual(before["registers"] as? NSDictionary, after["registers"] as? NSDictionary)
|
|
XCTAssertEqual(before["logical_memory"] as? String, after["logical_memory"] as? String)
|
|
let sameFrame = try await worker.request(["op": "capture"])
|
|
XCTAssertEqual(frame["png_base64"] as? String, sameFrame["png_base64"] as? String)
|
|
do { _ = try await worker.request(swap); XCTFail("Stale generation must reject duplicate commit") }
|
|
catch { XCTAssertTrue(error.localizedDescription.contains("stale_media_exchange")) }
|
|
let invalidUpdates: [[String: Any]] = [
|
|
["disk_base64": Data([1, 2, 3, 4, 5, 6, 7]).base64EncodedString()],
|
|
["disk_base64": Data(repeating: 0, count: 512 * 1024 + 1).base64EncodedString()],
|
|
["media_id": "../outside"], ["expected_media_generation": true],
|
|
["expected_disk_sha256": savedHash]
|
|
]
|
|
for update in invalidUpdates {
|
|
var invalid: [String: Any] = ["op": "exchange_media", "expected_media_generation": 1,
|
|
"expected_disk_sha256": CMOCProject.sha256(wrong), "media_id": "next-world", "disk_base64": original.base64EncodedString()]
|
|
invalid.merge(update) { _, value in value }
|
|
do { _ = try await worker.request(invalid); XCTFail("Invalid exchange must fail") } catch { }
|
|
let unchanged = try await worker.request(["op": "export_media"])
|
|
XCTAssertEqual(unchanged["disk_sha256"] as? String, CMOCProject.sha256(wrong))
|
|
XCTAssertEqual(unchanged["media_generation"] as? Int, 1)
|
|
XCTAssertEqual(unchanged["field_clock"] as? Int, before["field_clock"] as? Int)
|
|
XCTAssertEqual(unchanged["cycles"] as? Int, before["cycles"] as? Int)
|
|
}
|
|
let empty = try await worker.request(["op": "exchange_media", "expected_media_generation": 1,
|
|
"expected_disk_sha256": CMOCProject.sha256(wrong)])
|
|
XCTAssertEqual(empty["disk_present"] as? Bool, false)
|
|
XCTAssertEqual(empty["disk_sha256"] as? String, "")
|
|
XCTAssertEqual(empty["disk_dirty"] as? Bool, false)
|
|
XCTAssertTrue(empty["media_id"] is NSNull)
|
|
let emptyExport = try await worker.request(["op": "export_media"])
|
|
XCTAssertNil(emptyExport["disk_base64"])
|
|
_ = try await worker.request(["op": "capture"])
|
|
let restored = try await worker.request(["op": "exchange_media", "expected_media_generation": 2,
|
|
"expected_disk_sha256": "", "media_id": "home", "disk_base64": savedBytes.base64EncodedString()])
|
|
XCTAssertEqual(restored["disk_sha256"] as? String, savedHash)
|
|
XCTAssertEqual(restored["media_generation"] as? Int, 3)
|
|
let retained = try await worker.request(["op": "stop"])
|
|
XCTAssertEqual(retained["disk_base64"] as? String, savedBytes.base64EncodedString())
|
|
}
|
|
}
|
|
|
|
func testWorkerMediaExchangeRejectsGuestBusyControllerAndHandlesEmptyRestart() async throws {
|
|
let (helper, system, diskROM) = try inputs()
|
|
for cpu in ["6809", "6309"] {
|
|
// A guest-issued read command with its motor off stays pending. It
|
|
// must block replacement even though the CPU is paused afterward.
|
|
let busy = try MediaWorkerClient(helper); defer { busy.close() }
|
|
let commands = try CocoPaste("POKE65344,1:POKE65352,128\n", mode: .text)
|
|
_ = try await busy.request(["op": "init", "system_rom": system.base64EncodedString(),
|
|
"disk_rom": diskROM.base64EncodedString(), "disk": disk().base64EncodedString(),
|
|
"boot_keys": commands.chords.map { NSNumber(value: $0) }, "cpu": cpu])
|
|
_ = try await busy.request(["op": "pause"])
|
|
let status = try await busy.request(["op": "media_status"])
|
|
XCTAssertEqual(status["floppy_busy"] as? Bool, true)
|
|
let busyRequests: [[String: Any]] = [["op": "export_media"], ["op": "exchange_media",
|
|
"expected_media_generation": 0, "expected_disk_sha256": CMOCProject.sha256(disk())]]
|
|
for request in busyRequests {
|
|
do { _ = try await busy.request(request); XCTFail("Pending FDC must block media change") }
|
|
catch { XCTAssertTrue(error.localizedDescription.contains("playtest_media_busy")) }
|
|
}
|
|
let unchanged = try await busy.request(["op": "media_status"])
|
|
for key in ["field_clock", "cycles", "generation", "pc", "boot", "media_generation"] {
|
|
XCTAssertEqual(status[key] as? NSNumber, unchanged[key] as? NSNumber, key)
|
|
}
|
|
XCTAssertEqual(status["disk_sha256"] as? String, unchanged["disk_sha256"] as? String)
|
|
let empty = try MediaWorkerClient(helper); defer { empty.close() }
|
|
let benign = try CocoPaste("PRINT 1\n", mode: .text)
|
|
_ = try await empty.request(["op": "init", "system_rom": system.base64EncodedString(),
|
|
"disk_rom": diskROM.base64EncodedString(), "disk": disk().base64EncodedString(),
|
|
"boot_keys": benign.chords.map { NSNumber(value: $0) }, "cpu": cpu])
|
|
_ = try await empty.request(["op": "pause"])
|
|
_ = try await empty.request(["op": "exchange_media", "expected_media_generation": 0,
|
|
"expected_disk_sha256": CMOCProject.sha256(disk())])
|
|
let rebooted = try await empty.request(["op": "restart"])
|
|
XCTAssertEqual(rebooted["disk_present"] as? Bool, false)
|
|
XCTAssertEqual(rebooted["media_generation"] as? Int, 1)
|
|
assertProcessor(rebooted, cpu: cpu)
|
|
let stopped = try await empty.request(["op": "stop"])
|
|
XCTAssertEqual(stopped["disk_present"] as? Bool, false)
|
|
XCTAssertNil(stopped["disk_base64"])
|
|
}
|
|
}
|
|
|
|
private func inputs() throws -> (URL, Data, Data) {
|
|
let resources = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
|
|
.appendingPathComponent("LocalResources")
|
|
let products = Bundle(for: Self.self).bundleURL.deletingLastPathComponent()
|
|
let helper = ProcessInfo.processInfo.environment["VCC_TEST_PLAYTEST_HELPER"].map { URL(fileURLWithPath: $0) }
|
|
?? products.appendingPathComponent("vcc-playtest")
|
|
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: helper.path), "Requires the built, isolated vcc-playtest helper.")
|
|
let kit = products.appendingPathComponent("VCC Plus OSS.app/Contents/Resources/StarterKit")
|
|
let pair = try playtestROMs(kit: kit, local: resources,
|
|
explicitSource: ProcessInfo.processInfo.environment["VCC_SOURCE_ROM_DIR"])
|
|
return (helper, pair.0, pair.1)
|
|
}
|
|
|
|
/// Prefer the resources selected by this build, including an explicit
|
|
/// VCC_SOURCE_ROM_DIR used during Xcode staging. Do not turn a malformed
|
|
/// selected bundle into an optional-input skip or fall back to other bytes.
|
|
private func playtestROMs(kit: URL, local: URL, explicitSource: String? = nil) throws -> (Data, Data) {
|
|
let manager = FileManager.default
|
|
let names = ["coco3.rom", "disk11.rom"]
|
|
func present(_ url: URL) -> Bool {
|
|
manager.fileExists(atPath: url.path) || ((try? url.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink) == true)
|
|
}
|
|
func read(_ url: URL, maximum: Int) throws -> Data {
|
|
let values = try url.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey])
|
|
guard values.isRegularFile == true, values.isSymbolicLink != true else {
|
|
throw ProfileFailure.message("Playtest ROM inputs must be regular files without links.")
|
|
}
|
|
let handle = try FileHandle(forReadingFrom: url)
|
|
defer { try? handle.close() }
|
|
let bytes = try handle.read(upToCount: maximum + 1) ?? Data()
|
|
guard !bytes.isEmpty, bytes.count <= maximum else {
|
|
throw ProfileFailure.message("Playtest ROM input has an invalid size: " + url.lastPathComponent)
|
|
}
|
|
return bytes
|
|
}
|
|
func pair(_ directory: URL, requireManifest: Bool) throws -> (Data, Data) {
|
|
let values = try directory.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
|
|
guard values.isDirectory == true, values.isSymbolicLink != true else {
|
|
throw ProfileFailure.message("Playtest ROM input directory must not be linked.")
|
|
}
|
|
let system = try read(directory.appendingPathComponent(names[0]), maximum: 32768)
|
|
try ROMImage.validate(system)
|
|
let disk = try read(directory.appendingPathComponent(names[1]), maximum: 8192)
|
|
guard disk.count == 8192 else { throw ProfileFailure.message("Playtests require an 8 KiB Disk BASIC ROM.") }
|
|
let manifest = directory.appendingPathComponent("ROMBuild.json")
|
|
if requireManifest || present(manifest) {
|
|
if requireManifest {
|
|
let members = try manager.contentsOfDirectory(atPath: directory.path)
|
|
guard Set(members) == Set(names + ["ROMBuild.json", "ROM_SOURCE_NOTICE.txt"]) else {
|
|
throw ProfileFailure.message("Source ROM fixture must contain exactly its two ROMs, manifest and notice.")
|
|
}
|
|
}
|
|
let raw = try read(manifest, maximum: 256 * 1024)
|
|
let notice = try read(directory.appendingPathComponent("ROM_SOURCE_NOTICE.txt"), maximum: 64 * 1024)
|
|
func integer(_ value: Any?, equals expected: Int) -> Bool {
|
|
guard let value = value as? NSNumber, CFGetTypeID(value) != CFBooleanGetTypeID() else { return false }
|
|
return value.doubleValue == Double(expected)
|
|
}
|
|
guard let text = String(data: notice, encoding: .utf8), !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
|
|
!notice.contains(0), let record = try JSONSerialization.jsonObject(with: raw) as? [String: Any],
|
|
integer(record["schemaVersion"], equals: 1), record["generator"] as? String == "vccplus-rom-build",
|
|
let source = record["source"] as? [String: Any], !source.isEmpty,
|
|
let roms = record["roms"] as? [String: [String: Any]], Set(roms.keys) == Set(names) else {
|
|
throw ProfileFailure.message("Playtest source ROM manifest or notice is invalid.")
|
|
}
|
|
for (name, bytes) in [(names[0], system), (names[1], disk)] {
|
|
guard let entry = roms[name], integer(entry["bytes"], equals: bytes.count),
|
|
entry["sha256"] as? String == CMOCProject.sha256(bytes) else {
|
|
throw ProfileFailure.message("Playtest source ROM bytes do not match the manifest: " + name)
|
|
}
|
|
}
|
|
}
|
|
return (system, disk)
|
|
}
|
|
if names.contains(where: { present(kit.appendingPathComponent($0)) }) || present(kit.appendingPathComponent("ROMBuild.json")) {
|
|
return try pair(kit, requireManifest: false)
|
|
}
|
|
if let explicitSource, !explicitSource.isEmpty {
|
|
return try pair(URL(fileURLWithPath: explicitSource, isDirectory: true), requireManifest: true)
|
|
}
|
|
let source = local.appendingPathComponent("SourceROMBundle")
|
|
if present(source) { return try pair(source, requireManifest: true) }
|
|
let legacy = local.appendingPathComponent("ROMs")
|
|
if names.contains(where: { present(legacy.appendingPathComponent($0)) }) { return try pair(legacy, requireManifest: false) }
|
|
throw XCTSkip("Provide a built source-ROM app, a SourceROMBundle, or a local BASIC ROM pair for guest checks.")
|
|
}
|
|
|
|
/// Authored bytes exercise lookup and validation only; they are not used as
|
|
/// substitute BASIC firmware for an executed guest compatibility check.
|
|
private func writeROMFixture(_ directory: URL, byte: UInt8, manifest: Bool) throws -> (Data, Data) {
|
|
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
|
var system = Data(repeating: byte, count: 32768)
|
|
system[32766] = 0x80; system[32767] = 0
|
|
let disk = Data(repeating: byte, count: 8192)
|
|
try system.write(to: directory.appendingPathComponent("coco3.rom"))
|
|
try disk.write(to: directory.appendingPathComponent("disk11.rom"))
|
|
if manifest {
|
|
let record: [String: Any] = ["schemaVersion": 1, "generator": "vccplus-rom-build", "source": ["fixture": true],
|
|
"roms": ["coco3.rom": ["bytes": system.count, "sha256": CMOCProject.sha256(system)],
|
|
"disk11.rom": ["bytes": disk.count, "sha256": CMOCProject.sha256(disk)]]]
|
|
try JSONSerialization.data(withJSONObject: record).write(to: directory.appendingPathComponent("ROMBuild.json"))
|
|
try Data("Authored test fixture, not firmware.\n".utf8).write(to: directory.appendingPathComponent("ROM_SOURCE_NOTICE.txt"))
|
|
}
|
|
return (system, disk)
|
|
}
|
|
|
|
func testROMFixtureSelectionUsesBuiltPairThenExplicitSourceCanonicalAndLegacy() throws {
|
|
let root = FileManager.default.temporaryDirectory.appendingPathComponent("PlaytestROMSelection-" + UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: root) }
|
|
let local = root.appendingPathComponent("LocalResources"), kit = root.appendingPathComponent("StarterKit")
|
|
let legacy = try writeROMFixture(local.appendingPathComponent("ROMs"), byte: 1, manifest: false)
|
|
let canonical = try writeROMFixture(local.appendingPathComponent("SourceROMBundle"), byte: 2, manifest: true)
|
|
let explicit = root.appendingPathComponent("Explicit Bundle")
|
|
let selected = try writeROMFixture(explicit, byte: 3, manifest: true)
|
|
let bundled = try writeROMFixture(kit, byte: 4, manifest: true)
|
|
XCTAssertEqual(try playtestROMs(kit: kit, local: local, explicitSource: explicit.path).0, bundled.0)
|
|
try FileManager.default.removeItem(at: kit)
|
|
XCTAssertEqual(try playtestROMs(kit: kit, local: local, explicitSource: explicit.path).0, selected.0)
|
|
XCTAssertEqual(try playtestROMs(kit: kit, local: local).1, canonical.1)
|
|
try FileManager.default.removeItem(at: local.appendingPathComponent("SourceROMBundle"))
|
|
XCTAssertEqual(try playtestROMs(kit: kit, local: local).0, legacy.0)
|
|
}
|
|
|
|
func testMalformedSelectedROMFixturesFailInsteadOfFallingBackOrSkipping() throws {
|
|
let root = FileManager.default.temporaryDirectory.appendingPathComponent("PlaytestROMInvalid-" + UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: root) }
|
|
let local = root.appendingPathComponent("LocalResources"), kit = root.appendingPathComponent("StarterKit")
|
|
_ = try writeROMFixture(local.appendingPathComponent("ROMs"), byte: 1, manifest: false)
|
|
let source = local.appendingPathComponent("SourceROMBundle")
|
|
_ = try writeROMFixture(source, byte: 2, manifest: true)
|
|
try Data([0]).write(to: source.appendingPathComponent("disk11.rom"))
|
|
XCTAssertThrowsError(try playtestROMs(kit: kit, local: local))
|
|
XCTAssertThrowsError(try playtestROMs(kit: kit, local: local, explicitSource: root.appendingPathComponent("Missing").path))
|
|
_ = try writeROMFixture(kit, byte: 4, manifest: true)
|
|
var wrong = try Data(contentsOf: kit.appendingPathComponent("disk11.rom")); wrong[0] ^= 1
|
|
try wrong.write(to: kit.appendingPathComponent("disk11.rom"))
|
|
XCTAssertThrowsError(try playtestROMs(kit: kit, local: local), "A bad bundled pair must not be hidden by fallback")
|
|
}
|
|
|
|
/// Authored empty DECB image: free granules and unused directory slots.
|
|
/// No external game, saved disk, or user's media is opened by this test.
|
|
private func disk() -> Data {
|
|
var disk = Data(repeating: 0, count: 35 * 18 * 256)
|
|
disk.replaceSubrange(((17*18+1)*256)..<((17*18+2)*256), with: repeatElement(UInt8(255),count:256))
|
|
disk.replaceSubrange(((17*18+2)*256)..<((17*18+11)*256), with: repeatElement(UInt8(255),count:9*256))
|
|
return disk
|
|
}
|
|
|
|
private func assertProcessor(_ receipt: [String: Any], cpu: String, native: Bool = false,
|
|
file: StaticString = #filePath, line: UInt = #line) {
|
|
XCTAssertEqual(receipt["cpu"] as? String, cpu, file: file, line: line)
|
|
XCTAssertEqual(receipt["processor"] as? String, cpu == "6309" ? "HD6309" : "MC6809", file: file, line: line)
|
|
XCTAssertEqual(receipt["execution_mode"] as? String,
|
|
cpu == "6309" ? (native ? "native" : "emulation") : "not_applicable", file: file, line: line)
|
|
if cpu == "6309" {
|
|
XCTAssertEqual(receipt["md_register"] as? Int, native ? 1 : 0, file: file, line: line)
|
|
} else {
|
|
XCTAssertTrue(receipt["md_register"] is NSNull, file: file, line: line)
|
|
}
|
|
}
|
|
|
|
func testAudioCapturesGuestToneSilencePitchDurationRetriesAndBootIdentity() async throws {
|
|
let (helper, system, diskROM) = try inputs()
|
|
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCCGuestAudio-" + UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: folder) }
|
|
let program = "10 CLS\n20 LINE INPUT \"TONE\";A$\n30 IF A$=\"L\" THEN SOUND 80,30\n40 IF A$=\"H\" THEN SOUND 180,30\n50 GOTO 20\nRUN\n"
|
|
let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: disk(), bootCommands: program,
|
|
projectID: "guest-audio-fixture", revision: 1, artifactID: UUID().uuidString,
|
|
helperURL: helper, retentionDirectory: folder)
|
|
defer { test.invalidate() }
|
|
assertProcessor(test.startReceipt, cpu: "6809") // Omitted CPU retains the public default.
|
|
func capture(_ id: String, fields: Int) async throws -> ([String: Any], [String: Any], Data, [Int]) {
|
|
let receipt = try await test.reply("capture_playtest_audio", arguments: ["run_id": test.runID, "request_id": id, "fields": fields])
|
|
assertProcessor(receipt, cpu: "6809")
|
|
let metadata = try XCTUnwrap(receipt["audio"] as? [String: Any])
|
|
let wav = try XCTUnwrap((receipt["audio_wav_base64"] as? String).flatMap { Data(base64Encoded: $0) })
|
|
XCTAssertEqual(String(data: wav.prefix(4), encoding: .ascii), "RIFF")
|
|
XCTAssertEqual(metadata["sha256"] as? String, CMOCProject.sha256(wav))
|
|
XCTAssertEqual(metadata["sample_rate"] as? Int, 44100)
|
|
XCTAssertEqual(metadata["channels"] as? Int, 2)
|
|
XCTAssertEqual(metadata["encoding"] as? String, "pcm_s16le")
|
|
XCTAssertEqual(metadata["sample_frames"] as? Int, (wav.count - 44) / 4)
|
|
XCTAssertEqual(metadata["sample_count"] as? Int, (wav.count - 44) / 2)
|
|
XCTAssertEqual(metadata["fields_advanced"] as? Int, fields)
|
|
XCTAssertEqual((metadata["field_end"] as? Int ?? -1) - (metadata["field_start"] as? Int ?? -1), fields)
|
|
XCTAssertEqual(receipt["state"] as? String, "paused")
|
|
let samples = stride(from: 44, to: wav.count, by: 4).map { i in
|
|
Int(Int16(bitPattern: UInt16(wav[i]) | (UInt16(wav[i+1]) << 8)))
|
|
}
|
|
if let directory = ProcessInfo.processInfo.environment["VCC_TEST_AUDIO_CAPTURES"] {
|
|
let root = URL(fileURLWithPath: directory, isDirectory: true)
|
|
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
|
try wav.write(to: root.appendingPathComponent(id + ".wav"), options: .atomic)
|
|
}
|
|
return (receipt, metadata, wav, samples)
|
|
}
|
|
func type(_ key: String, id: String) async throws {
|
|
_ = try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": id,
|
|
"steps": [["keys": [key], "fields": 6], ["keys": [], "fields": 6],
|
|
["keys": ["enter"], "fields": 6], ["keys": [], "fields": 6]]])
|
|
}
|
|
func transitions(_ values: [Int]) -> Int {
|
|
let mid = ((values.min() ?? 0) + (values.max() ?? 0)) / 2
|
|
return zip(values, values.dropFirst()).filter { pair in (pair.0 > mid) != (pair.1 > mid) }.count
|
|
}
|
|
let silence = try await capture("silence", fields: 30)
|
|
// Raw DAC silence can contain a DC offset; variation is the signal.
|
|
XCTAssertLessThan((silence.3.max() ?? 0) - (silence.3.min() ?? 0), 8)
|
|
try await type("l", id: "low-key")
|
|
let low = try await capture("low-tone", fields: 30)
|
|
XCTAssertGreaterThan((low.3.max() ?? 0) - (low.3.min() ?? 0), 100)
|
|
let retry = try await capture("low-tone", fields: 30)
|
|
XCTAssertEqual(retry.2, low.2)
|
|
let state = try await test.capture()
|
|
XCTAssertEqual(state["field_clock"] as? Int, low.0["field_clock"] as? Int)
|
|
_ = try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": "finish-low",
|
|
"steps": [["keys": [], "fields": 240]]])
|
|
try await type("h", id: "high-key")
|
|
let high = try await capture("high-tone", fields: 60)
|
|
XCTAssertGreaterThan(Double(transitions(high.3)) / 2, Double(transitions(low.3)) * 1.5)
|
|
XCTAssertEqual(Double(high.3.count) / Double(low.3.count), 2, accuracy: 0.01)
|
|
let beforeInvalid = try await test.capture()
|
|
for value: Any in [0, 121, -1, true, 1.5] {
|
|
await expectDiskFailure {
|
|
_ = try await test.reply("capture_playtest_audio", arguments: ["run_id": test.runID, "request_id": "invalid", "fields": value])
|
|
}
|
|
}
|
|
await expectDiskFailure {
|
|
_ = try await test.reply("capture_playtest_audio", arguments: ["run_id": "another-run", "request_id": "foreign", "fields": 1])
|
|
}
|
|
await expectDiskFailure {
|
|
_ = try await test.reply("capture_playtest_audio", arguments: ["run_id": test.runID, "request_id": "low-tone", "fields": 31])
|
|
}
|
|
let afterInvalid = try await test.capture()
|
|
XCTAssertEqual(beforeInvalid["field_clock"] as? Int, afterInvalid["field_clock"] as? Int)
|
|
let reboot = try await test.reply("restart_playtest", arguments: ["run_id": test.runID, "request_id": "reboot"])
|
|
let newBoot = try await capture("reboot-silence", fields: 1)
|
|
XCTAssertEqual(newBoot.0["boot"] as? Int, 2)
|
|
XCTAssertEqual(newBoot.0["artifact_id"] as? String, silence.0["artifact_id"] as? String)
|
|
XCTAssertEqual(newBoot.0["boot"] as? Int, reboot["boot"] as? Int)
|
|
let oldClip = try await test.reply("capture_playtest_audio", arguments: ["run_id": test.runID, "request_id": "low-tone", "fields": 30])
|
|
XCTAssertEqual(oldClip["boot"] as? Int, 1, "A retry identifies its original boot and does not recapture")
|
|
// Four unique clips above; the retry does not consume a slot.
|
|
for index in 4..<MCPPlaytest.audioCaptureLimit { _ = try await capture("short-\(index)", fields: 1) }
|
|
let budget = try await test.capture()
|
|
XCTAssertEqual(budget["remaining_audio_captures"] as? Int, 0)
|
|
await expectDiskFailure {
|
|
_ = try await test.reply("capture_playtest_audio", arguments: ["run_id": test.runID, "request_id": "over-budget", "fields": 1])
|
|
}
|
|
let still = try await test.capture()
|
|
XCTAssertEqual(still["field_clock"] as? Int, budget["field_clock"] as? Int)
|
|
let stopped = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "stop"])
|
|
XCTAssertEqual(stopped["disk_retained"] as? Bool, true)
|
|
}
|
|
|
|
func testStopRetentionRemainsAvailableAfterMutationRequestLimit() async throws {
|
|
let (helper, system, diskROM) = try inputs()
|
|
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCCRequestLimit-" + UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: folder) }
|
|
let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: disk(), bootCommands: "\n",
|
|
projectID: "request-limit-fixture", revision: 1, artifactID: UUID().uuidString,
|
|
helperURL: helper, retentionDirectory: folder)
|
|
defer { test.invalidate() }
|
|
for index in 0..<MCPPlaytest.mutationRequestLimit {
|
|
_ = try await test.reply("playtest_debug", arguments: ["run_id": test.runID, "request_id": "pause-\(index)", "action": "pause"])
|
|
}
|
|
let before = try await test.capture()
|
|
XCTAssertEqual(before["remaining_mutation_requests"] as? Int, 0)
|
|
do {
|
|
_ = try await test.reply("playtest_debug", arguments: ["run_id": test.runID, "request_id": "exhausted", "action": "step"])
|
|
XCTFail("Exhausted execution ledger accepted another mutation")
|
|
} catch { XCTAssertTrue(error.localizedDescription.contains("playtest_request_limit")) }
|
|
let stopped = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "stop"])
|
|
XCTAssertEqual(stopped["disk_retained"] as? Bool, true)
|
|
XCTAssertEqual(stopped["stop_retention_exempt"] as? Bool, true)
|
|
XCTAssertEqual(stopped["remaining_mutation_requests"] as? Int, 0)
|
|
let retry = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "stop"])
|
|
XCTAssertEqual(stopped["disk_sha256"] as? String, retry["disk_sha256"] as? String)
|
|
XCTAssertEqual(stopped["retained_disk_id"] as? String, retry["retained_disk_id"] as? String)
|
|
await expectDiskFailure {
|
|
_ = try await test.reply("stop_playtest", arguments: ["run_id": "another-run", "request_id": "stop"])
|
|
}
|
|
}
|
|
|
|
func testAudioByteBudgetSurvivesRestartAndStillPermitsCleanup() async throws {
|
|
let (helper, system, diskROM) = try inputs()
|
|
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCCAudioBudget-" + UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: folder) }
|
|
let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: disk(), bootCommands: "\n",
|
|
projectID: "audio-budget-fixture", revision: 1, artifactID: UUID().uuidString,
|
|
helperURL: helper, retentionDirectory: folder)
|
|
defer { test.invalidate() }
|
|
var bytes = 0, clips = 0, denied = false
|
|
for index in 0..<MCPPlaytest.audioCaptureLimit {
|
|
do {
|
|
let clip = try await test.reply("capture_playtest_audio", arguments: ["run_id": test.runID,
|
|
"request_id": "clip-\(index)", "fields": MCPPlaytest.audioFieldLimit])
|
|
let metadata = try XCTUnwrap(clip["audio"] as? [String: Any])
|
|
bytes += try XCTUnwrap(metadata["byte_count"] as? Int); clips += 1
|
|
XCTAssertLessThanOrEqual(bytes, MCPPlaytest.audioByteLimit)
|
|
} catch {
|
|
XCTAssertTrue(error.localizedDescription.contains("playtest_audio_capture_limit"))
|
|
denied = true; break
|
|
}
|
|
}
|
|
XCTAssertTrue(denied)
|
|
XCTAssertGreaterThan(clips, 1)
|
|
XCTAssertLessThan(clips, MCPPlaytest.audioCaptureLimit, "The independent byte bound must limit long clips first")
|
|
_ = try await test.reply("restart_playtest", arguments: ["run_id": test.runID, "request_id": "restart"])
|
|
let before = try await test.capture()
|
|
XCTAssertEqual(before["remaining_audio_bytes"] as? Int, MCPPlaytest.audioByteLimit - bytes)
|
|
await expectDiskFailure {
|
|
_ = try await test.reply("capture_playtest_audio", arguments: ["run_id": test.runID, "request_id": "after-restart", "fields": 1])
|
|
}
|
|
let after = try await test.capture()
|
|
XCTAssertEqual(before["field_clock"] as? Int, after["field_clock"] as? Int)
|
|
let stopped = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "stop"])
|
|
XCTAssertEqual(stopped["disk_retained"] as? Bool, true)
|
|
}
|
|
|
|
func testPeriodUsesGuestKeyboardWithReleaseEditingShiftAndIdempotency() async throws {
|
|
let (helper, system, diskROM) = try inputs()
|
|
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCCKeyboard-" + UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: folder) }
|
|
let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: disk(),
|
|
bootCommands: "10 CLS\n20 LINE INPUT \"NAME\";A$\n30 PRINT \"GOT:\";A$\n40 PRINT \"LEN:\";LEN(A$)\n50 GOTO 20\nRUN\n",
|
|
projectID: "keyboard-fixture", revision: 1, artifactID: UUID().uuidString, helperURL: helper, retentionDirectory: folder)
|
|
var sequence = 0
|
|
func input(_ keys: [String], fields: Int = 6) async throws -> [String: Any] {
|
|
sequence += 1
|
|
return try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": "key-\(sequence)",
|
|
"steps": [["keys": keys, "fields": fields], ["keys": [], "fields": 6]]])
|
|
}
|
|
func capture(_ name: String) async throws -> String {
|
|
let result = try await test.capture()
|
|
if let directory = ProcessInfo.processInfo.environment["VCC_TEST_GUEST_CAPTURES"],
|
|
let encoded = result["png_base64"] as? String, let png = Data(base64Encoded: encoded) {
|
|
let root = URL(fileURLWithPath: directory, isDirectory: true)
|
|
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
|
try png.write(to: root.appendingPathComponent(name + ".png"), options: .atomic)
|
|
}
|
|
return result["screen_text"] as? String ?? ""
|
|
}
|
|
let initial = try await capture("keyboard-ready")
|
|
XCTAssertFalse(initial.contains("?SN ERROR"), initial)
|
|
let request: [String: Any] = ["run_id": test.runID, "request_id": "one-period",
|
|
"steps": [["keys": ["period"], "fields": 6], ["keys": [], "fields": 6]]]
|
|
let press = try await test.reply("playtest_input", arguments: request)
|
|
let retry = try await test.reply("playtest_input", arguments: request)
|
|
XCTAssertEqual(press["field_clock"] as? Int, retry["field_clock"] as? Int)
|
|
_ = try await input(["enter"])
|
|
let single = try await capture("single-period")
|
|
XCTAssertTrue(single.contains("GOT:."), single)
|
|
XCTAssertTrue(single.range(of: #"LEN:\s*1(?:\s|$)"#, options: .regularExpression) != nil, single)
|
|
for key in ["s", "t", "period", "space", "p", "a", "u", "x", "backspace", "l"] { _ = try await input([key]) }
|
|
_ = try await input(["enter"])
|
|
let edited = try await capture("st-paul")
|
|
XCTAssertTrue(edited.contains("GOT:ST. PAUL"), edited)
|
|
_ = try await input(["shift", "period"])
|
|
_ = try await input(["enter"])
|
|
let shifted = try await capture("shift-period")
|
|
XCTAssertTrue(shifted.contains("GOT:>"), shifted)
|
|
_ = try await input(["period"], fields: 120)
|
|
_ = try await input(["enter"])
|
|
let held = try await capture("held-period")
|
|
XCTAssertTrue(held.contains("GOT:."), held)
|
|
_ = try await input(["a"])
|
|
_ = try await input(["enter"])
|
|
let released = try await capture("released-period")
|
|
XCTAssertTrue(released.contains("GOT:A"), released)
|
|
let before = try await test.capture()
|
|
for keys in [["."], ["not-a-key"], ["period", "period"]] {
|
|
await expectDiskFailure { _ = try await test.reply("playtest_input", arguments: ["run_id": test.runID,
|
|
"request_id": "bad-key", "steps": [["keys": keys, "fields": 6]]]) }
|
|
}
|
|
let after = try await test.capture()
|
|
XCTAssertEqual(before["field_clock"] as? Int, after["field_clock"] as? Int)
|
|
_ = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "stop"])
|
|
}
|
|
|
|
func testFramebufferDeclarationsAreBoundedAndSeparateFromCode() throws {
|
|
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCCGraphicsManifest-" + UUID().uuidString)
|
|
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
|
|
defer { try? FileManager.default.removeItem(at: folder) }
|
|
let bytes = Data([0x12, 0x20, 0xfd]), binary = Data([0, 0, 3, 0x30, 0]) + bytes + Data([255, 0, 0, 0x30, 0])
|
|
let files = ["program.bin": binary, "program.map": Data("Section: code (main.o) load at 3000, length 0003\n".utf8), "code.raw": bytes]
|
|
for (name, data) in files { try data.write(to: folder.appendingPathComponent(name)) }
|
|
func file(_ name: String) -> [String: String] { ["path": name, "sha256": CMOCProject.sha256(files[name]!)] }
|
|
let base: [String: Any] = ["version": 1, "entryPoint": 0x3000, "binary": file("program.bin"), "linkMap": file("program.map"), "sources": [:],
|
|
"artifacts": ["code.raw": CMOCProject.sha256(bytes)], "modules": [["id": "main", "sections": ["code"], "codeSections": ["code"],
|
|
"image": ["path": "code.raw", "logicalAddress": 0x3000], "pages": [["logicalPage": 1, "physicalPage": 57]]]]]
|
|
func parse(_ buffers: [[String: Any]]) throws -> CMOCBankedDebugLayout {
|
|
var manifest = base; manifest["framebuffers"] = buffers
|
|
return try CMOCBankedDebugLayout.parse(data: JSONSerialization.data(withJSONObject: manifest), directory: folder,
|
|
sources: [:], binary: binary, binaryPath: "program.bin", allowedOutputs: Array(files.keys))
|
|
}
|
|
let valid: [String: Any] = ["id": "back", "physicalAddress": 0x60000, "mode": "hscreen2"]
|
|
XCTAssertEqual(try parse([valid]).framebuffers.first?.workerFields["physical_address"] as? Int, 0x60000)
|
|
let canvas: [String: Any] = ["id": "canvas0", "physicalAddress": 0, "mode": "current_gime", "canvasBytes": 65536]
|
|
let canvas1: [String: Any] = ["id": "canvas1", "physicalAddress": 0x20000, "mode": "current_gime", "canvasBytes": 65536]
|
|
let custom = try parse([canvas, canvas1])
|
|
XCTAssertEqual(custom.framebuffers.count, 2)
|
|
XCTAssertEqual(custom.framebuffers[0].workerFields["canvas_bytes"] as? Int, 65536)
|
|
for changes: [String: Any] in [["canvasBytes": 0], ["canvasBytes": 4096], ["canvasBytes": 60000],
|
|
["canvasBytes": 16 * 1024 * 1024], ["physicalAddress": 8192],
|
|
["physicalAddress": 8 * 1024 * 1024]] {
|
|
var invalid = canvas; invalid.merge(changes, uniquingKeysWith: { _, new in new })
|
|
XCTAssertThrowsError(try parse([invalid]))
|
|
}
|
|
var noSize = canvas; noSize.removeValue(forKey: "canvasBytes")
|
|
XCTAssertThrowsError(try parse([noSize]))
|
|
var fixedWithSize = valid; fixedWithSize["canvasBytes"] = 65536
|
|
XCTAssertThrowsError(try parse([fixedWithSize]))
|
|
var overlaps = canvas1; overlaps["physicalAddress"] = 32768; overlaps["canvasBytes"] = 32768
|
|
XCTAssertThrowsError(try parse([canvas, overlaps]))
|
|
for invalid in [[valid, valid], [["id": "../back", "physicalAddress": 0, "mode": "hscreen2"]],
|
|
[["id": "displayed", "physicalAddress": 0, "mode": "hscreen2"]],
|
|
[["id": "back", "physicalAddress": -1, "mode": "hscreen2"]],
|
|
[["id": "back", "physicalAddress": 0, "mode": "guess"]]] {
|
|
XCTAssertThrowsError(try parse(invalid))
|
|
}
|
|
}
|
|
|
|
func testGraphicsCaptureUsesOnePausedStateAndDeclaredBuffersOnly() async throws {
|
|
let (helper, system, diskROM) = try inputs()
|
|
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCCGraphicsCapture-" + UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: folder) }
|
|
let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: disk(),
|
|
bootCommands: "10 HSCREEN 2\n20 HCLS 3\n30 GOTO 30\nRUN\n", projectID: "graphics-fixture", revision: 1,
|
|
artifactID: UUID().uuidString, helperURL: helper, retentionDirectory: folder,
|
|
graphicsBuffers: [["id": "back", "physical_address": 0x68000, "mode": "hscreen2"]])
|
|
await expectDiskFailure { _ = try await test.reply("capture_playtest_graphics", arguments: ["run_id": test.runID]) }
|
|
_ = try await test.reply("playtest_debug", arguments: ["run_id": test.runID, "request_id": "pause", "action": "pause"])
|
|
let before = try await test.capture()
|
|
let result = try await test.reply("capture_playtest_graphics", arguments: ["run_id": test.runID, "buffer_id": "back"])
|
|
let buffers = try XCTUnwrap(result["buffers"] as? [[String: Any]])
|
|
XCTAssertEqual(buffers.count, 2)
|
|
XCTAssertEqual(buffers.first?["id"] as? String, "displayed")
|
|
XCTAssertEqual(buffers.last?["id"] as? String, "back")
|
|
XCTAssertEqual(buffers.last?["physical_address"] as? Int, 0x68000)
|
|
for buffer in buffers {
|
|
XCTAssertEqual(buffer["cycles"] as? Int, before["cycles"] as? Int)
|
|
XCTAssertEqual(buffer["generation"] as? Int, before["generation"] as? Int)
|
|
let data = try XCTUnwrap((buffer["png_base64"] as? String).flatMap { Data(base64Encoded: $0) })
|
|
XCTAssertEqual(Array(data.prefix(8)), [137,80,78,71,13,10,26,10])
|
|
}
|
|
XCTAssertNotEqual(buffers.first?["png_base64"] as? String, buffers.last?["png_base64"] as? String)
|
|
for invalid: [String: Any] in [["run_id": test.runID, "buffer_id": "unknown"],
|
|
["run_id": test.runID, "buffer_id": "../private"],
|
|
["run_id": test.runID, "address": 0]] {
|
|
await expectDiskFailure { _ = try await test.reply("capture_playtest_graphics", arguments: invalid) }
|
|
}
|
|
let after = try await test.capture()
|
|
XCTAssertEqual(before["field_clock"] as? Int, after["field_clock"] as? Int)
|
|
XCTAssertEqual(before["cycles"] as? Int, after["cycles"] as? Int)
|
|
XCTAssertEqual(before["disk_sha256"] as? String, after["disk_sha256"] as? String)
|
|
_ = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "stop"])
|
|
}
|
|
|
|
func testOwnedWorkerRetryBoundsClockSaveAndColdRestartOnBothCPUs() async throws {
|
|
let (helper,system,diskROM) = try inputs()
|
|
let retention = FileManager.default.temporaryDirectory.appendingPathComponent("VCCPlaytestStore-" + UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: retention) }
|
|
for cpu in ["6809","6309"] {
|
|
let original = disk()
|
|
let test = try await MCPPlaytest.start(systemROM: system,diskROM: diskROM,disk: original,
|
|
bootCommands: "10 PRINT 42\nSAVE\"TEST\"\n",projectID: "authored-test",revision: 1,
|
|
artifactID: UUID().uuidString,cpu: cpu,helperURL: helper,retentionDirectory: retention)
|
|
defer { test.invalidate() }
|
|
let first = test.startReceipt
|
|
assertProcessor(first, cpu: cpu)
|
|
XCTAssertEqual(first["ram_kb"] as? Int,512)
|
|
XCTAssertTrue(first["isolated"] as? Bool == true)
|
|
XCTAssertEqual(first["remaining_boots"] as? Int,15)
|
|
XCTAssertGreaterThan(first["remaining_field_budget"] as? Int ?? 0,0)
|
|
XCTAssertLessThan(first["remaining_field_budget"] as? Int ?? 216000,216000)
|
|
XCTAssertGreaterThan(first["disk_writes"] as? Int ?? 0,0)
|
|
XCTAssertNotEqual(first["disk_original_sha256"] as? String,first["disk_sha256"] as? String)
|
|
let request: [String: Any] = ["run_id":test.runID,"request_id":"walk",
|
|
"steps":[["keys":["right","x","z"],"fields":60]]]
|
|
let receipt = try await test.reply("playtest_input",arguments: request)
|
|
assertProcessor(receipt, cpu: cpu)
|
|
XCTAssertEqual(receipt["field_clock"] as? Int,(first["field_clock"] as? Int ?? 0)+60)
|
|
XCTAssertEqual(receipt["remaining_field_budget"] as? Int,(first["remaining_field_budget"] as? Int ?? 0)-60)
|
|
let retry = try await test.reply("playtest_input",arguments: request)
|
|
XCTAssertEqual(retry["field_clock"] as? Int,receipt["field_clock"] as? Int)
|
|
var conflict = request; conflict["steps"] = [["keys":["left"],"fields":60]]
|
|
do { _ = try await test.reply("playtest_input",arguments: conflict); XCTFail("Conflicting retry executed") }
|
|
catch { XCTAssertTrue(error.localizedDescription.contains("request_conflict")) }
|
|
for fields: Any in [true,0,-1,601,1.5] {
|
|
let invalid: [String: Any] = ["run_id":test.runID,"request_id":"invalid",
|
|
"steps":[["keys":["right"],"fields":fields]]]
|
|
do { _ = try await test.reply("playtest_input",arguments: invalid); XCTFail("Unbounded input executed") }
|
|
catch { XCTAssertTrue(error.localizedDescription.contains("invalid_arguments")) }
|
|
}
|
|
let capture = try await test.capture()
|
|
assertProcessor(capture, cpu: cpu)
|
|
XCTAssertEqual(capture["field_clock"] as? Int,receipt["field_clock"] as? Int)
|
|
let png = try XCTUnwrap((capture["png_base64"] as? String).flatMap { Data(base64Encoded:$0) })
|
|
XCTAssertEqual(Array(png.prefix(8)),[137,80,78,71,13,10,26,10])
|
|
let restarted = try await test.reply("restart_playtest",arguments:["run_id":test.runID,"request_id":"cold"])
|
|
assertProcessor(restarted, cpu: cpu)
|
|
XCTAssertEqual(restarted["boot"] as? Int,2)
|
|
XCTAssertEqual(restarted["remaining_boots"] as? Int,14)
|
|
XCTAssertEqual(restarted["disk_original_sha256"] as? String,first["disk_original_sha256"] as? String)
|
|
XCTAssertEqual(restarted["disk_sha256"] as? String,first["disk_sha256"] as? String)
|
|
let stopped = try await test.reply("stop_playtest",arguments:["run_id":test.runID,"request_id":"stop"])
|
|
assertProcessor(stopped, cpu: cpu)
|
|
XCTAssertTrue(stopped["disk_retained"] as? Bool == true)
|
|
XCTAssertNil(stopped["disk_base64"])
|
|
let saved = try XCTUnwrap(test.retainedDiskURL)
|
|
XCTAssertNotEqual(try Data(contentsOf:saved),original)
|
|
try FileManager.default.removeItem(at:saved.deletingLastPathComponent())
|
|
}
|
|
}
|
|
func testRevocationAwaitsOwnedDiskRetentionInSelectedResultsFolder() async throws {
|
|
let (helper, system, diskROM) = try inputs()
|
|
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCCPlaytestRetention-" + UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: folder) }
|
|
let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: disk(),
|
|
bootCommands: "10 PRINT 7\nSAVE\"TEST\"\n", projectID: "authored-retention", revision: 1,
|
|
artifactID: UUID().uuidString, helperURL: helper, retentionDirectory: folder)
|
|
let expected = try XCTUnwrap(test.startReceipt["disk_sha256"] as? String)
|
|
await test.invalidate().value
|
|
let saved = try XCTUnwrap(test.retainedDiskURL)
|
|
XCTAssertEqual(saved.deletingLastPathComponent().deletingLastPathComponent().resolvingSymlinksInPath(), folder.resolvingSymlinksInPath())
|
|
let records = try await MCPPlaytestDiskStore.list(directory: folder, projectKey: CMOCProject.sha256(Data("authored-retention".utf8)))
|
|
XCTAssertEqual(records.map(\.id), [test.runID])
|
|
XCTAssertEqual(records.first?.diskSHA256, expected)
|
|
XCTAssertEqual(CMOCProject.sha256(try Data(contentsOf: saved)), expected)
|
|
do { _ = try await test.capture(); XCTFail("A revoked run remained accessible") }
|
|
catch { XCTAssertTrue(error.localizedDescription.contains("stale_run")) }
|
|
}
|
|
|
|
func testNamedStopUsesSelectedPhysicalModuleAndFrozenSafeCapture() async throws {
|
|
let (helper,system,diskROM) = try inputs()
|
|
var image = disk()
|
|
let code = Data([0x12,0x20,0xfd]) // NOP; BRA back to NOP.
|
|
let binary = Data([0,0,3,0x30,0]) + code + Data([255,0,0,0x30,0])
|
|
image.replaceSubrange(0..<binary.count,with:binary)
|
|
image[(17*18+1)*256] = 0xc1
|
|
var entry = Data(repeating:0,count:32)
|
|
entry.replaceSubrange(0..<11,with:Data("PROBE BIN".utf8))
|
|
entry[11] = 2; entry[15] = UInt8(binary.count)
|
|
let directory = (17*18+2)*256
|
|
image.replaceSubrange(directory..<(directory+32),with:entry)
|
|
let modules: [[String: Any]] = [("main",57),("overlay",49)].map { name,page in
|
|
["id":name,"pages":[["logical_page":1,"physical_page":page]],
|
|
"guards":[["address":0x3000,"bytes_base64":code.base64EncodedString()]]]
|
|
}
|
|
let retention = FileManager.default.temporaryDirectory.appendingPathComponent("VCCPlaytestStop-" + UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: retention) }
|
|
let test = try await MCPPlaytest.start(systemROM:system,diskROM:diskROM,disk:image,
|
|
bootCommands:"LOADM\"PROBE\":EXEC\n",projectID:"authored-bank-test",revision:1,
|
|
artifactID:UUID().uuidString,modules:modules,stopAt:0x3000,stopModule:"overlay",helperURL:helper,retentionDirectory:retention)
|
|
defer { test.invalidate() }
|
|
// Both modules contain the same logical address and bytes. Only one
|
|
// physical mapping belongs to the named function requested by the user.
|
|
XCTAssertEqual(test.startReceipt["state"] as? String,"running")
|
|
_ = try await test.reply("playtest_debug",arguments:["run_id":test.runID,"request_id":"main-stop",
|
|
"action":"stop_at","address":0x3000,"module_id":"main", "selection":"function_entry:probe"])
|
|
do {
|
|
_ = try await test.reply("playtest_debug",arguments:["run_id":test.runID,"request_id":"main-stop",
|
|
"action":"stop_at","address":0x3000,"module_id":"main", "selection":"c_line:probe"])
|
|
XCTFail("A changed stop selection reused a write request ID")
|
|
} catch { XCTAssertTrue(error.localizedDescription.contains("request_conflict")) }
|
|
let stop = try await test.reply("playtest_input",arguments:["run_id":test.runID,"request_id":"advance",
|
|
"steps":[["keys":[],"fields":60]]])
|
|
XCTAssertEqual(stop["state"] as? String,"paused")
|
|
let capture = try await test.debugCapture()
|
|
XCTAssertEqual(capture["pc"] as? Int,0x3000)
|
|
XCTAssertTrue(capture["attached"] as? Bool == true)
|
|
XCTAssertEqual((capture["physical_pages"] as? [String:Int])?["1"],57)
|
|
let memory = try XCTUnwrap((capture["logical_memory"] as? String).flatMap { Data(base64Encoded:$0) })
|
|
let available = try XCTUnwrap((capture["available"] as? String).flatMap { Data(base64Encoded:$0) })
|
|
XCTAssertEqual(memory.count,65536)
|
|
XCTAssertEqual(Data(memory[0x3000..<0x3003]),code)
|
|
XCTAssertEqual(available[0xff00],0)
|
|
XCTAssertEqual(available[0x3000],1)
|
|
let frozen = memory
|
|
_ = try await test.reply("playtest_debug",arguments:["run_id":test.runID,"request_id":"step","action":"step"])
|
|
let next = try await test.debugCapture()
|
|
XCTAssertEqual(next["pc"] as? Int,0x3001)
|
|
XCTAssertEqual(Data(frozen[0x3000..<0x3003]),code)
|
|
_ = try await test.reply("playtest_debug",arguments:["run_id":test.runID,"request_id":"continue","action":"continue"])
|
|
_ = try await test.reply("playtest_debug",arguments:["run_id":test.runID,"request_id":"pause","action":"pause"])
|
|
let continued = try await test.debugCapture()
|
|
XCTAssertTrue(continued["attached"] as? Bool == true, "Continue releases stop points while preserving verified module evidence")
|
|
XCTAssertEqual(continued["pc"] as? Int,0x3001)
|
|
_ = try await test.reply("playtest_input",arguments:["run_id":test.runID,"request_id":"play-from-pause",
|
|
"steps":[["keys":[],"fields":60]]])
|
|
_ = try await test.reply("playtest_debug",arguments:["run_id":test.runID,"request_id":"pause-after-play","action":"pause"])
|
|
let played = try await test.debugCapture()
|
|
XCTAssertTrue(played["attached"] as? Bool == true, "Field-counted input from a stop retains inspectable source evidence")
|
|
_ = try await test.reply("stop_playtest",arguments:["run_id":test.runID,"request_id":"stop"])
|
|
if let disk = test.retainedDiskURL { try FileManager.default.removeItem(at:disk.deletingLastPathComponent()) }
|
|
}
|
|
|
|
func testFlatOwnedStopUsesVerifiedBytesAndActualRuntimeMapping() async throws {
|
|
let (helper, system, diskROM) = try inputs()
|
|
// Guest instructions assign42 to a global, then loop at a verified stop.
|
|
let code = Data([0x86, 0x2a, 0xb7, 0x50, 0, 0x12, 0x20, 0xfd])
|
|
let binary = Data([0, 0, UInt8(code.count), 0x30, 0]) + code + Data([255, 0, 0, 0x30, 0])
|
|
var image = disk(); image.replaceSubrange(0..<binary.count, with: binary)
|
|
image[(17*18+1)*256] = 0xc1
|
|
var entry = Data(repeating: 0, count: 32)
|
|
entry.replaceSubrange(0..<11, with: Data("PROBE BIN".utf8))
|
|
entry[11] = 2; entry[15] = UInt8(binary.count)
|
|
let directory = (17*18+2)*256
|
|
image.replaceSubrange(directory..<(directory+32), with: entry)
|
|
let artifactID = UUID().uuidString
|
|
for cpu in ["6809", "6309"] {
|
|
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCCFlatStop-" + UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: folder) }
|
|
let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: image,
|
|
bootCommands: "LOADM\"PROBE\":EXEC\n", projectID: "flat-stop-fixture", revision: 1,
|
|
artifactID: artifactID, stopAt: 0x3005,
|
|
flatGuards: [["address": 0x3000, "bytes_base64": code.base64EncodedString()]],
|
|
cpu: cpu, helperURL: helper, retentionDirectory: folder)
|
|
defer { test.invalidate() }
|
|
assertProcessor(test.startReceipt, cpu: cpu)
|
|
XCTAssertEqual(test.startReceipt["artifact_id"] as? String, artifactID)
|
|
XCTAssertEqual(test.startReceipt["disk_original_sha256"] as? String, CMOCProject.sha256(image))
|
|
XCTAssertEqual(test.startReceipt["state"] as? String, "paused")
|
|
let captured = try await test.debugCapture()
|
|
assertProcessor(captured, cpu: cpu)
|
|
let registers = try XCTUnwrap(captured["registers"] as? [String: Int])
|
|
for name in ["E", "F", "V", "W", "MD"] {
|
|
if cpu == "6309" { XCTAssertNotNil(registers[name]) }
|
|
else { XCTAssertNil(registers[name], "MC6809 must not advertise fabricated 6309 registers") }
|
|
}
|
|
XCTAssertEqual(captured["pc"] as? Int, 0x3005)
|
|
XCTAssertEqual(captured["attached"] as? Bool, true)
|
|
let pages = try XCTUnwrap(captured["physical_pages"] as? [String: Int])
|
|
XCTAssertNotNil(pages["1"])
|
|
let memory = try XCTUnwrap((captured["logical_memory"] as? String).flatMap { Data(base64Encoded: $0) })
|
|
XCTAssertEqual(memory[0x5000], 42)
|
|
let frame = try await test.capture()
|
|
assertProcessor(frame, cpu: cpu)
|
|
XCTAssertEqual(frame["run_id"] as? String, test.runID)
|
|
XCTAssertEqual(frame["artifact_id"] as? String, artifactID)
|
|
XCTAssertNotNil((frame["png_base64"] as? String).flatMap { Data(base64Encoded: $0) })
|
|
let early = try await test.reply("capture_playtest_audio", arguments: ["run_id": test.runID, "request_id": "short-at-stop", "fields": 120])
|
|
assertProcessor(early, cpu: cpu)
|
|
XCTAssertEqual(early["run_id"] as? String, test.runID)
|
|
XCTAssertEqual(early["artifact_id"] as? String, artifactID)
|
|
let interval = try XCTUnwrap(early["audio"] as? [String: Any])
|
|
XCTAssertEqual(interval["completed"] as? Bool, false)
|
|
XCTAssertLessThan(try XCTUnwrap(interval["fields_advanced"] as? Int), 120)
|
|
XCTAssertEqual(early["state"] as? String, "paused", "Audio must preserve the verified breakpoint")
|
|
_ = try await test.reply("playtest_debug", arguments: ["run_id": test.runID, "request_id": "continue", "action": "continue"])
|
|
_ = try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": "run", "steps": [["keys": [], "fields": 2]]])
|
|
_ = try await test.reply("playtest_debug", arguments: ["run_id": test.runID, "request_id": "pause", "action": "pause"])
|
|
let paused = try await test.debugCapture()
|
|
XCTAssertEqual(paused["attached"] as? Bool, true)
|
|
XCTAssertEqual(paused["physical_pages"] as? [String: Int], pages)
|
|
_ = try await test.reply("playtest_debug", arguments: ["run_id": test.runID, "request_id": "stop-at", "action": "stop_at",
|
|
"address": 0x3005, "selection": "function_entry:probe"])
|
|
_ = try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": "reach", "steps": [["keys": [], "fields": 2]]])
|
|
let stopped = try await test.debugCapture()
|
|
XCTAssertEqual(stopped["pc"] as? Int, 0x3005)
|
|
XCTAssertEqual(stopped["attached"] as? Bool, true)
|
|
_ = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "stop"])
|
|
}
|
|
}
|
|
|
|
func testOrdinaryGuestCallStackCaptureIsReadOnlyOnBothProcessorsAnd6309NativeMode() async throws {
|
|
let (helper, system, diskROM) = try inputs()
|
|
let arguments: [UInt16] = [0x0102, 0x2030, 0x7f80, 0xa0b0, 0xc0d0, 0xdead, 0xbeef]
|
|
for (cpu, native) in [("6809", false), ("6309", false), ("6309", true)] {
|
|
var code = Data()
|
|
var instructions: [CMOCProjectSourceMap.Instruction] = []
|
|
func emit(_ bytes: [UInt8], _ assembly: String, line: Int = 1) {
|
|
instructions.append(.init(sourcePath: "fixture.c", sourceLine: line,
|
|
address: UInt16(0x3000 + code.count), bytes: bytes, assembly: assembly))
|
|
code.append(contentsOf: bytes)
|
|
}
|
|
// This is an authored LOADM program, not host register/memory writes.
|
|
// The guest initializes its own stack/frame register, pushes ordinary
|
|
// right-to-left word arguments, and executes a real extended JSR.
|
|
emit([0x1a, 0x50], "ORCC #$50")
|
|
emit([0x10, 0xce, 0x70, 0], "LDS #$7000")
|
|
emit([0xce, 0x6a, 0x5a], "LDU #$6A5A")
|
|
if native { emit([0x11, 0x3d, 1], "LDMD #1") }
|
|
else { for _ in 0..<3 { emit([0x12], "NOP") } }
|
|
emit([0xbd, 0x30, 0x40], "JSR caller")
|
|
// After both ordinary callees return, PIA writes produce single-bit
|
|
// sound for comparison with an otherwise identical uninspected run.
|
|
for (value, port) in [(UInt8(0), UInt16(0xff23)), (2, 0xff22), (4, 0xff23)] {
|
|
emit([0x86, value], "LDA #PIA value")
|
|
emit([0xb7, UInt8(port >> 8), UInt8(port & 255)], "STA PIA")
|
|
}
|
|
emit([0x86, 0], "LDA #0")
|
|
let tone = 0x3000 + code.count
|
|
emit([0xb7, 0xff, 0x22], "STA $FF22")
|
|
emit([0x88, 2], "EORA #2")
|
|
let next = 0x3000 + code.count + 2
|
|
emit([0x20, UInt8(bitPattern: Int8(tone - next))], "BRA tone")
|
|
while code.count < 0x40 { code.append(0x12) }
|
|
emit([0x34, 0x40], "PSHS U", line: 8)
|
|
emit([0x33, 0xe4], "LEAU ,S", line: 8)
|
|
for word in arguments.reversed() {
|
|
emit([0xcc, UInt8(word >> 8), UInt8(word & 255)], "LDD #argument", line: 12)
|
|
emit([0x34, 0x06], "PSHS D", line: 12)
|
|
}
|
|
emit([0xbd, 0x31, 0], "JSR $3100", line: 12)
|
|
let returnPC = UInt16(0x3000 + code.count)
|
|
emit([0x32, 0x6e], "LEAS 14,S", line: 13)
|
|
let callerEnd = 0x3000 + code.count
|
|
emit([0x32, 0xc4], "LEAS ,U", line: 14)
|
|
emit([0x35, 0xc0], "PULS U,PC", line: 14)
|
|
while code.count < 0x100 { code.append(0x12) }
|
|
emit([0x34, 0x40], "PSHS U", line: 20)
|
|
emit([0x33, 0xe4], "LEAU ,S", line: 20)
|
|
emit([0x12], "NOP", line: 21)
|
|
emit([0x32, 0xc4], "LEAS ,U", line: 22)
|
|
emit([0x35, 0xc0], "PULS U,PC", line: 22)
|
|
let binary = Data([0, UInt8(code.count >> 8), UInt8(code.count & 255), 0x30, 0])
|
|
+ code + Data([255, 0, 0, 0x30, 0])
|
|
let map = CMOCProjectSourceMap(entryPoint: 0x3000, binarySHA256: CMOCProject.sha256(binary),
|
|
sourceHashes: [:], instructions: instructions, objectHashes: [:], listingHashes: [:], linkMapSHA256: "",
|
|
flatCodeGuards: [.init(address: 0x3000, bytes: Array(code))])
|
|
let word = CMOCVariableDebug.CType(name: "unsigned int", kind: "integer", size: 2, signed: false)
|
|
let metadata = CMOCVariableDebug(functions: [
|
|
.init(name: "caller", sourcePath: "fixture.c", entry: 0x3040, body: 0x3044, end: callerEnd, frame: true),
|
|
.init(name: "callee", sourcePath: "fixture.c", entry: 0x3100, body: 0x3104, end: 0x3105, frame: true)
|
|
], variables: arguments.indices.map { index in
|
|
.init(name: "argument\(index + 1)", sourcePath: "fixture.c", line: 20, type: word,
|
|
address: nil, offset: 4 + index * 2, scope: 0x3104..<0x3105, isStatic: false)
|
|
}, sourceMap: map)
|
|
var image = disk(); image.replaceSubrange(0..<binary.count, with: binary)
|
|
image[(17 * 18 + 1) * 256] = UInt8(0xc0 + (binary.count + 255) / 256)
|
|
var entry = Data(repeating: 0, count: 32)
|
|
entry.replaceSubrange(0..<11, with: Data("PROBE BIN".utf8)); entry[11] = 2
|
|
let lastSectorBytes = (binary.count - 1) % 256 + 1
|
|
entry[14] = UInt8(lastSectorBytes >> 8); entry[15] = UInt8(lastSectorBytes & 255)
|
|
image.replaceSubrange(((17 * 18 + 2) * 256)..<((17 * 18 + 2) * 256 + 32), with: entry)
|
|
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCCOwnedCall-" + UUID().uuidString)
|
|
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false,
|
|
attributes: [.posixPermissions: 0o700])
|
|
defer { if FileManager.default.fileExists(atPath: folder.path) { try? FileManager.default.removeItem(at: folder) } }
|
|
let artifactID = UUID().uuidString
|
|
var clips: [Data] = []
|
|
var postAudio: [[String: Any]] = []
|
|
// Both workers execute exactly the same guest operations. Only the
|
|
// first receives repeated private read-only debug captures.
|
|
for inspect in [true, false] {
|
|
let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: image,
|
|
bootCommands: "LOADM\"PROBE\":EXEC\n", projectID: "ordinary-call-fixture", revision: 1,
|
|
artifactID: artifactID, stopAt: 0x3100,
|
|
flatGuards: [["address": 0x3000, "bytes_base64": code.base64EncodedString()]],
|
|
cpu: cpu, helperURL: helper, retentionDirectory: folder.appendingPathComponent(inspect ? "inspected" : "control"))
|
|
do {
|
|
assertProcessor(test.startReceipt, cpu: cpu, native: native)
|
|
XCTAssertEqual(test.startReceipt["ram_kb"] as? Int, 512)
|
|
XCTAssertEqual(test.startReceipt["state"] as? String, "paused")
|
|
XCTAssertEqual(test.startReceipt["pc"] as? Int, 0x3100)
|
|
func check(_ capture: [String: Any], framed: Bool) throws {
|
|
assertProcessor(capture, cpu: cpu, native: native)
|
|
XCTAssertEqual(capture["attached"] as? Bool, true)
|
|
let registers = try XCTUnwrap(capture["registers"] as? [String: Int])
|
|
let s = try XCTUnwrap(registers["S"])
|
|
XCTAssertEqual(s, framed ? 0x6fea : 0x6fec)
|
|
XCTAssertEqual(registers["U"], framed ? 0x6fea : 0x6ffc)
|
|
XCTAssertEqual(registers["PC"], framed ? 0x3104 : 0x3100)
|
|
let memory = try XCTUnwrap((capture["logical_memory"] as? String).flatMap { Data(base64Encoded: $0) })
|
|
let available = try XCTUnwrap((capture["available"] as? String).flatMap { Data(base64Encoded: $0) })
|
|
XCTAssertEqual(memory.count, 65536); XCTAssertEqual(available.count, 65536)
|
|
XCTAssertEqual(available[0xff00], 0)
|
|
XCTAssertTrue(available[s..<(s + 64)].allSatisfy { $0 == 1 })
|
|
XCTAssertTrue(map.verifiesRuntime(memory: memory, available: available))
|
|
let start = s + (framed ? 2 : 0)
|
|
func word(_ at: Int) -> UInt16 { UInt16(memory[at]) << 8 | UInt16(memory[at + 1]) }
|
|
if framed { XCTAssertEqual(word(s), 0x6ffc) }
|
|
XCTAssertEqual(word(start), returnPC)
|
|
XCTAssertEqual(arguments.indices.map { word(start + 2 + $0 * 2) }, arguments)
|
|
let pages = try XCTUnwrap(capture["physical_pages"] as? [String: Int])
|
|
XCTAssertNotNil(pages[String(s / 8192)])
|
|
let physical = Dictionary(uniqueKeysWithValues: pages.compactMap { key, value in Int(key).map { ($0, value) } })
|
|
let context = CMOCOwnedCallContext.capture(map: map, metadata: metadata,
|
|
pc: UInt16(registers["PC"]!), s: UInt16(s), u: UInt16(registers["U"]!),
|
|
memory: memory, available: available, physicalPages: physical, sharedPaths: ["fixture.c"])
|
|
XCTAssertEqual(context["status"] as? String, "available")
|
|
let stack = try XCTUnwrap(context["stack_window"] as? [String: Any])
|
|
XCTAssertEqual(stack["address"] as? Int, s); XCTAssertEqual(stack["count"] as? Int, 64)
|
|
XCTAssertEqual(stack["bytes"] as? [UInt8], Array(memory[s..<(s + 64)]))
|
|
XCTAssertEqual(stack["interpretation"] as? String, "uninterpreted")
|
|
XCTAssertEqual((stack["words_be"] as? [[String: Any]])?.count, 32)
|
|
let caller = try XCTUnwrap(context["caller"] as? [String: Any])
|
|
XCTAssertEqual(caller["status"] as? String, "available")
|
|
XCTAssertEqual(caller["function"] as? String, "caller")
|
|
XCTAssertEqual(caller["return_address"] as? Int, Int(returnPC))
|
|
XCTAssertEqual(caller["callee_phase"] as? String, framed ? "mapped_body" : "function_entry")
|
|
let parameters = try XCTUnwrap(context["arguments"] as? [String: Any])
|
|
XCTAssertEqual(parameters["status"] as? String, "available")
|
|
XCTAssertEqual(parameters["all_recorded_parameters_available"] as? Bool, true)
|
|
XCTAssertEqual(parameters["recorded_parameter_count"] as? Int, arguments.count)
|
|
let items = try XCTUnwrap(parameters["items"] as? [[String: Any]])
|
|
XCTAssertEqual(items.compactMap { ($0["value"] as? NSNumber)?.uint16Value }, arguments)
|
|
}
|
|
func frozen(_ initial: [String: Any], framed: Bool) async throws {
|
|
try check(initial, framed: framed)
|
|
let canonical = try JSONSerialization.data(withJSONObject: initial, options: .sortedKeys)
|
|
_ = try await test.pausePlaytest()
|
|
for _ in 0..<3 {
|
|
let repeated = try await test.debugCapture()
|
|
try check(repeated, framed: framed)
|
|
XCTAssertEqual(CMOCProject.sha256(try JSONSerialization.data(withJSONObject: repeated, options: .sortedKeys)),
|
|
CMOCProject.sha256(canonical), "Inspection must preserve clocks, registers, mapping, memory, disk events and guest identity")
|
|
}
|
|
}
|
|
if inspect { let captured = try await test.debugCapture(); try await frozen(captured, framed: false) }
|
|
_ = try await test.reply("playtest_debug", arguments: ["run_id": test.runID, "request_id": "body",
|
|
"action": "stop_at", "address": 0x3104, "selection": "c_line:callee"])
|
|
_ = try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": "reach-body",
|
|
"steps": [["keys": [], "fields": 2]]])
|
|
if inspect { let captured = try await test.debugCapture(); try await frozen(captured, framed: true) }
|
|
_ = try await test.continuePlaytest()
|
|
let audio = try await test.reply("capture_playtest_audio", arguments: ["run_id": test.runID,
|
|
"request_id": "ordinary-guest-audio", "fields": 3])
|
|
let wav = try XCTUnwrap((audio["audio_wav_base64"] as? String).flatMap { Data(base64Encoded: $0) })
|
|
XCTAssertGreaterThan(wav.count, 44)
|
|
let samples = stride(from: 44, to: wav.count, by: 2).map { offset in
|
|
Int16(bitPattern: UInt16(wav[offset]) | UInt16(wav[offset + 1]) << 8)
|
|
}
|
|
XCTAssertGreaterThan(Set(samples).count, 1, "The ordinary guest must generate a real signal for the PCM comparison")
|
|
clips.append(wav); postAudio.append(audio)
|
|
if inspect {
|
|
let returned = try await test.debugCapture()
|
|
XCTAssertEqual((returned["registers"] as? [String: Int])?["S"], 0x7000)
|
|
XCTAssertEqual((returned["registers"] as? [String: Int])?["U"], 0x6a5a)
|
|
let restart = try await test.reply("restart_playtest", arguments: ["run_id": test.runID, "request_id": "cold"])
|
|
XCTAssertEqual(restart["boot"] as? Int, 2)
|
|
XCTAssertNotEqual(restart["generation"] as? Int, audio["generation"] as? Int)
|
|
XCTAssertEqual(restart["artifact_id"] as? String, audio["artifact_id"] as? String)
|
|
let restarted = try await test.debugCapture()
|
|
try check(restarted, framed: true)
|
|
}
|
|
_ = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "retain"])
|
|
XCTAssertEqual(try Data(contentsOf: XCTUnwrap(test.retainedDiskURL)), image)
|
|
} catch {
|
|
// Retention must finish before deleting the fixture root,
|
|
// including failures before the normal explicit stop.
|
|
await test.invalidate().value
|
|
throw error
|
|
}
|
|
await test.invalidate().value
|
|
}
|
|
XCTAssertEqual(clips[0], clips[1], "Read-only stack capture must leave subsequent guest PCM identical to an uninspected run")
|
|
for key in ["field_clock", "cycles", "machine_frame", "pc", "disk_reads", "disk_writes", "disk_dirty", "disk_sha256"] {
|
|
XCTAssertEqual(postAudio[0][key] as? NSObject, postAudio[1][key] as? NSObject, key)
|
|
}
|
|
}
|
|
}
|
|
|
|
func testHD6309GuestLDMDChangesActualModeRegistersAndColdRestartResetsMode() async throws {
|
|
let (helper, system, diskROM) = try inputs()
|
|
// Authored guest code only: mask IRQ/FIRQ, LDW #$1234, TFR W,V,
|
|
// assign 42 to a global, LDMD #1, then loop. No host register/memory writes.
|
|
let code = Data([0x1a, 0x50, 0x10, 0x86, 0x12, 0x34, 0x1f, 0x67,
|
|
0x86, 0x2a, 0xb7, 0x50, 0, 0x11, 0x3d, 1, 0x12, 0x20, 0xfd])
|
|
let binary = Data([0, 0, UInt8(code.count), 0x30, 0]) + code + Data([255, 0, 0, 0x30, 0])
|
|
var image = disk(); image.replaceSubrange(0..<binary.count, with: binary)
|
|
image[(17*18+1)*256] = 0xc1
|
|
var entry = Data(repeating: 0, count: 32)
|
|
entry.replaceSubrange(0..<11, with: Data("PROBE BIN".utf8))
|
|
entry[11] = 2; entry[15] = UInt8(binary.count)
|
|
let directory = (17*18+2)*256
|
|
image.replaceSubrange(directory..<(directory+32), with: entry)
|
|
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCCNative6309-" + UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: folder) }
|
|
let artifactID = UUID().uuidString
|
|
let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: image,
|
|
bootCommands: "LOADM\"PROBE\":EXEC\n", projectID: "native-mode-fixture", revision: 1,
|
|
artifactID: artifactID, stopAt: 0x3000,
|
|
flatGuards: [["address": 0x3000, "bytes_base64": code.base64EncodedString()]],
|
|
cpu: "6309", helperURL: helper, retentionDirectory: folder)
|
|
defer { test.invalidate() }
|
|
assertProcessor(test.startReceipt, cpu: "6309")
|
|
XCTAssertEqual(test.startReceipt["pc"] as? Int, 0x3000)
|
|
let entryCapture = try await test.debugCapture()
|
|
assertProcessor(entryCapture, cpu: "6309")
|
|
XCTAssertEqual((entryCapture["registers"] as? [String: Int])?["MD"], 0)
|
|
|
|
_ = try await test.reply("playtest_debug", arguments: ["run_id": test.runID, "request_id": "after-ldmd",
|
|
"action": "stop_at", "address": 0x3010, "selection": "function_entry:native_loop"])
|
|
let reached = try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": "execute-ldmd",
|
|
"steps": [["keys": [], "fields": 2]]])
|
|
assertProcessor(reached, cpu: "6309", native: true)
|
|
let native = try await test.debugCapture()
|
|
assertProcessor(native, cpu: "6309", native: true)
|
|
XCTAssertEqual(native["pc"] as? Int, 0x3010)
|
|
XCTAssertEqual(native["attached"] as? Bool, true)
|
|
let registers = try XCTUnwrap(native["registers"] as? [String: Int])
|
|
XCTAssertEqual(registers["E"], 0x12); XCTAssertEqual(registers["F"], 0x34)
|
|
XCTAssertEqual(registers["W"], 0x1234); XCTAssertEqual(registers["V"], 0x1234)
|
|
XCTAssertEqual(registers["MD"], 1)
|
|
let memory = try XCTUnwrap((native["logical_memory"] as? String).flatMap { Data(base64Encoded: $0) })
|
|
XCTAssertEqual(memory[0x5000], 42)
|
|
|
|
_ = try await test.continuePlaytest()
|
|
let audioRequest: [String: Any] = ["run_id": test.runID, "request_id": "native-audio", "fields": 2]
|
|
let audio = try await test.reply("capture_playtest_audio", arguments: audioRequest)
|
|
assertProcessor(audio, cpu: "6309", native: true)
|
|
XCTAssertEqual(audio["run_id"] as? String, test.runID)
|
|
XCTAssertEqual(audio["artifact_id"] as? String, artifactID)
|
|
XCTAssertEqual((audio["audio"] as? [String: Any])?["fields_advanced"] as? Int, 2)
|
|
let retry = try await test.reply("capture_playtest_audio", arguments: audioRequest)
|
|
XCTAssertEqual(retry["field_clock"] as? Int, audio["field_clock"] as? Int)
|
|
XCTAssertEqual(retry["audio_wav_base64"] as? String, audio["audio_wav_base64"] as? String)
|
|
let frame = try await test.capture()
|
|
assertProcessor(frame, cpu: "6309", native: true)
|
|
XCTAssertEqual(frame["run_id"] as? String, test.runID)
|
|
XCTAssertEqual(frame["artifact_id"] as? String, artifactID)
|
|
let png = try XCTUnwrap((frame["png_base64"] as? String).flatMap { Data(base64Encoded: $0) })
|
|
XCTAssertEqual(Array(png.prefix(8)), [137, 80, 78, 71, 13, 10, 26, 10])
|
|
|
|
// A cold boot must really reset MD before guest LDMD runs again.
|
|
_ = try await test.reply("playtest_debug", arguments: ["run_id": test.runID, "request_id": "entry-on-next-boot",
|
|
"action": "stop_at", "address": 0x3000, "selection": "function_entry:entry"])
|
|
let cold = try await test.reply("restart_playtest", arguments: ["run_id": test.runID, "request_id": "cold"])
|
|
assertProcessor(cold, cpu: "6309")
|
|
XCTAssertEqual(cold["boot"] as? Int, 2); XCTAssertEqual(cold["pc"] as? Int, 0x3000)
|
|
XCTAssertEqual(cold["disk_original_sha256"] as? String, CMOCProject.sha256(image))
|
|
let reset = try await test.debugCapture()
|
|
assertProcessor(reset, cpu: "6309")
|
|
XCTAssertEqual((reset["registers"] as? [String: Int])?["MD"], 0)
|
|
let stopRequest: [String: Any] = ["run_id": test.runID, "request_id": "retain"]
|
|
let retained = try await test.reply("stop_playtest", arguments: stopRequest)
|
|
assertProcessor(retained, cpu: "6309")
|
|
XCTAssertEqual(retained["disk_retained"] as? Bool, true)
|
|
XCTAssertEqual(try Data(contentsOf: XCTUnwrap(test.retainedDiskURL)), image)
|
|
let retainedRetry = try await test.reply("stop_playtest", arguments: stopRequest)
|
|
XCTAssertEqual(retainedRetry["retained_disk_id"] as? String, retained["retained_disk_id"] as? String)
|
|
}
|
|
|
|
private func expectDiskFailure(_ operation: () async throws -> Void, file: StaticString = #filePath, line: UInt = #line) async {
|
|
do { try await operation(); XCTFail("Invalid retained-disk operation succeeded", file: file, line: line) }
|
|
catch { }
|
|
}
|
|
|
|
func testRetainedDiskStoreReloadScopeHashesAndImmutableParents() async throws {
|
|
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCCDurableDisks-" + UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: folder) }
|
|
let key = CMOCProject.sha256(Data("project-a".utf8)), otherKey = CMOCProject.sha256(Data("project-b".utf8))
|
|
let original = disk(), artifactSHA = CMOCProject.sha256(original), artifact = UUID().uuidString, id = UUID().uuidString
|
|
var saved = original; saved[0] = 7
|
|
let provenance = MCPPlaytestDiskStore.Provenance(projectKey: key, artifactID: artifact, artifactDiskSHA256: artifactSHA)
|
|
let record = try await MCPPlaytestDiskStore.save(directory: folder, runID: id, data: saved, provenance: provenance)
|
|
XCTAssertEqual(record.diskSHA256, CMOCProject.sha256(saved))
|
|
XCTAssertEqual(record.provenance.originArtifactID, artifact)
|
|
XCTAssertEqual(record.provenance.originArtifactDiskSHA256, artifactSHA)
|
|
XCTAssertNil(record.publicFields["project_key"]); XCTAssertNil(record.publicFields["path"])
|
|
// Stateless lookup simulates a fresh app/store instance, without relying
|
|
// on the original worker or an in-memory run receipt.
|
|
let listed = try await MCPPlaytestDiskStore.list(directory: folder, projectKey: key)
|
|
XCTAssertEqual(listed.map(\.id), [id]); XCTAssertEqual(listed.first?.byteCount, saved.count)
|
|
let otherProjectDisks = try await MCPPlaytestDiskStore.list(directory: folder, projectKey: otherKey)
|
|
XCTAssertTrue(otherProjectDisks.isEmpty)
|
|
let loaded = try await MCPPlaytestDiskStore.load(directory: folder, id: id, expectedSHA256: record.diskSHA256,
|
|
projectKey: key, artifactDiskSHA256: artifactSHA)
|
|
XCTAssertEqual(loaded.data, saved)
|
|
for (hash, project, produced) in [(String(repeating: "0", count: 64), key, artifactSHA),
|
|
(record.diskSHA256, otherKey, artifactSHA),
|
|
(record.diskSHA256, key, String(repeating: "f", count: 64))] {
|
|
await expectDiskFailure { _ = try await MCPPlaytestDiskStore.load(directory: folder, id: id,
|
|
expectedSHA256: hash, projectKey: project, artifactDiskSHA256: produced) }
|
|
}
|
|
let childID = UUID().uuidString
|
|
var child = loaded.data; child[1] = 9
|
|
let childProof = MCPPlaytestDiskStore.Provenance(projectKey: key, artifactID: UUID().uuidString,
|
|
artifactDiskSHA256: artifactSHA, parentDiskID: id, origin: record.provenance.origin,
|
|
originArtifactID: record.provenance.originArtifactID, originArtifactDiskSHA256: record.provenance.originArtifactDiskSHA256)
|
|
let childRecord = try await MCPPlaytestDiskStore.save(directory: folder, runID: childID, data: child, provenance: childProof)
|
|
XCTAssertEqual(childRecord.provenance.originArtifactID, artifact)
|
|
XCTAssertEqual(childRecord.provenance.parentDiskID, id)
|
|
XCTAssertEqual(try Data(contentsOf: MCPPlaytestDiskStore.diskURL(directory: folder, id: id)), saved)
|
|
await expectDiskFailure { _ = try await MCPPlaytestDiskStore.save(directory: folder, runID: id, data: child, provenance: provenance) }
|
|
XCTAssertEqual(try Data(contentsOf: MCPPlaytestDiskStore.diskURL(directory: folder, id: id)), saved)
|
|
let diskURL = try MCPPlaytestDiskStore.diskURL(directory: folder, id: id)
|
|
try child.write(to: diskURL, options: .atomic)
|
|
await expectDiskFailure { _ = try await MCPPlaytestDiskStore.load(directory: folder, id: id,
|
|
expectedSHA256: record.diskSHA256, projectKey: key, artifactDiskSHA256: artifactSHA) }
|
|
try saved.write(to: diskURL, options: .atomic)
|
|
let sidecar = diskURL.deletingLastPathComponent().appendingPathComponent("record.json")
|
|
var metadata = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(contentsOf: sidecar)) as? [String: Any])
|
|
metadata["runID"] = UUID().uuidString
|
|
try JSONSerialization.data(withJSONObject: metadata).write(to: sidecar, options: .atomic)
|
|
let validRecords = try await MCPPlaytestDiskStore.list(directory: folder, projectKey: key)
|
|
XCTAssertFalse(validRecords.contains { $0.id == id })
|
|
await expectDiskFailure { _ = try await MCPPlaytestDiskStore.load(directory: folder, id: id,
|
|
expectedSHA256: record.diskSHA256, projectKey: key, artifactDiskSHA256: artifactSHA) }
|
|
}
|
|
|
|
func testLegacyReceiptIsExplicitUnlistedAndDoesNotInventArtifactOrigin() async throws {
|
|
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCCLegacyDisks-" + UUID().uuidString)
|
|
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
|
|
defer { try? FileManager.default.removeItem(at: folder) }
|
|
let id = UUID().uuidString, bytes = disk(), hash = CMOCProject.sha256(bytes)
|
|
let legacy = folder.appendingPathComponent(id + ".dsk")
|
|
try bytes.write(to: legacy, options: .atomic)
|
|
let key = CMOCProject.sha256(Data("current-project".utf8)), fresh = CMOCProject.sha256(Data("different-produced-disk".utf8))
|
|
let unlistedLegacyDisks = try await MCPPlaytestDiskStore.list(directory: folder, projectKey: key)
|
|
XCTAssertTrue(unlistedLegacyDisks.isEmpty)
|
|
let loaded = try await MCPPlaytestDiskStore.load(directory: folder, id: id, expectedSHA256: hash,
|
|
projectKey: key, artifactDiskSHA256: fresh)
|
|
XCTAssertEqual(loaded.data, bytes); XCTAssertEqual(loaded.record.provenance.origin, "legacy_receipt")
|
|
XCTAssertNil(loaded.record.provenance.projectKey); XCTAssertNil(loaded.record.provenance.artifactID)
|
|
XCTAssertNil(loaded.record.provenance.artifactDiskSHA256); XCTAssertNil(loaded.record.createdAt)
|
|
XCTAssertTrue(loaded.record.publicFields["artifact_id"] is NSNull)
|
|
for supplied in ["../" + id, id + "/other", "not-a-uuid"] {
|
|
await expectDiskFailure { _ = try await MCPPlaytestDiskStore.load(directory: folder, id: supplied,
|
|
expectedSHA256: hash, projectKey: key, artifactDiskSHA256: fresh) }
|
|
}
|
|
await expectDiskFailure { _ = try await MCPPlaytestDiskStore.load(directory: folder, id: id,
|
|
expectedSHA256: String(repeating: "0", count: 64), projectKey: key, artifactDiskSHA256: fresh) }
|
|
let childID = UUID().uuidString
|
|
var child = loaded.data; child[0] = 1
|
|
let proof = MCPPlaytestDiskStore.Provenance(projectKey: key, artifactID: UUID().uuidString,
|
|
artifactDiskSHA256: fresh, parentDiskID: id, origin: loaded.record.provenance.origin)
|
|
await expectDiskFailure { _ = try await MCPPlaytestDiskStore.save(directory: folder, runID: id, data: child, provenance: proof) }
|
|
XCTAssertEqual(try Data(contentsOf: legacy), bytes, "A new record cannot shadow an existing legacy receipt identity")
|
|
let record = try await MCPPlaytestDiskStore.save(directory: folder, runID: childID, data: child, provenance: proof)
|
|
XCTAssertEqual(record.provenance.origin, "legacy_receipt")
|
|
XCTAssertNil(record.provenance.originArtifactID); XCTAssertNil(record.provenance.originArtifactDiskSHA256)
|
|
XCTAssertEqual(record.provenance.artifactDiskSHA256, fresh, "Current execution identity stays separate from unknown historical origin")
|
|
XCTAssertEqual(try Data(contentsOf: legacy), bytes)
|
|
let listed = try await MCPPlaytestDiskStore.list(directory: folder, projectKey: key)
|
|
XCTAssertEqual(listed.map(\.id), [childID])
|
|
let reloaded = try await MCPPlaytestDiskStore.load(directory: folder, id: childID, expectedSHA256: record.diskSHA256,
|
|
projectKey: key, artifactDiskSHA256: fresh)
|
|
XCTAssertEqual(reloaded.data, child); XCTAssertEqual(reloaded.record.provenance.origin, "legacy_receipt")
|
|
}
|
|
|
|
func testRetainedStoreRejectsLinksBoundsAndIncompletePublishedRecords() async throws {
|
|
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCCDiskPaths-" + UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: folder) }
|
|
let key = CMOCProject.sha256(Data("scope".utf8)), bytes = disk(), hash = CMOCProject.sha256(bytes), id = UUID().uuidString
|
|
let proof = MCPPlaytestDiskStore.Provenance(projectKey: key, artifactID: UUID().uuidString, artifactDiskSHA256: hash)
|
|
_ = try await MCPPlaytestDiskStore.save(directory: folder, runID: id, data: bytes, provenance: proof)
|
|
let diskURL = try MCPPlaytestDiskStore.diskURL(directory: folder, id: id)
|
|
let outside = folder.appendingPathComponent("outside.dsk")
|
|
try FileManager.default.moveItem(at: diskURL, to: outside)
|
|
try FileManager.default.createSymbolicLink(at: diskURL, withDestinationURL: outside)
|
|
await expectDiskFailure { _ = try await MCPPlaytestDiskStore.load(directory: folder, id: id, expectedSHA256: hash,
|
|
projectKey: key, artifactDiskSHA256: hash) }
|
|
let unlistedLegacyDisks = try await MCPPlaytestDiskStore.list(directory: folder, projectKey: key)
|
|
XCTAssertTrue(unlistedLegacyDisks.isEmpty)
|
|
try FileManager.default.removeItem(at: diskURL)
|
|
try FileManager.default.moveItem(at: outside, to: diskURL)
|
|
let link = folder.appendingPathComponent("root-link")
|
|
try FileManager.default.createSymbolicLink(at: link, withDestinationURL: folder)
|
|
await expectDiskFailure { _ = try await MCPPlaytestDiskStore.list(directory: link, projectKey: key) }
|
|
let orphanID = UUID().uuidString
|
|
try FileManager.default.createDirectory(at: folder.appendingPathComponent(orphanID), withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700])
|
|
try bytes.write(to: folder.appendingPathComponent(orphanID + ".dsk"))
|
|
let completeRecords = try await MCPPlaytestDiskStore.list(directory: folder, projectKey: key)
|
|
XCTAssertFalse(completeRecords.contains { $0.id == orphanID })
|
|
await expectDiskFailure { _ = try await MCPPlaytestDiskStore.load(directory: folder, id: orphanID, expectedSHA256: hash,
|
|
projectKey: key, artifactDiskSHA256: hash) }
|
|
for invalid in [Data(), Data(repeating: 0, count: 512 * 1024 + 1)] {
|
|
await expectDiskFailure { _ = try await MCPPlaytestDiskStore.save(directory: folder, runID: UUID().uuidString, data: invalid, provenance: proof) }
|
|
}
|
|
await expectDiskFailure { _ = try await MCPPlaytestDiskStore.load(directory: folder, id: id,
|
|
expectedSHA256: hash.uppercased(), projectKey: key, artifactDiskSHA256: hash) }
|
|
}
|
|
|
|
func testFailedRetentionCanRetryAfterWorkerExitWithoutLosingSavedDisk() async throws {
|
|
let (helper, system, diskROM) = try inputs()
|
|
let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCRetentionRetry-" + UUID().uuidString)
|
|
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
|
|
defer { try? FileManager.default.removeItem(at: root) }
|
|
let blocked = root.appendingPathComponent("retained")
|
|
try Data("not a directory".utf8).write(to: blocked)
|
|
let original = disk()
|
|
let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: original,
|
|
bootCommands: "10 PRINT 9\nSAVE\"TEST\"\n", projectID: "retry-retention", revision: 1,
|
|
artifactID: UUID().uuidString, helperURL: helper, retentionDirectory: blocked)
|
|
let expected = try XCTUnwrap(test.startReceipt["disk_sha256"] as? String)
|
|
let stop: [String: Any] = ["run_id": test.runID, "request_id": "retain"]
|
|
await expectDiskFailure { _ = try await test.reply("stop_playtest", arguments: stop) }
|
|
XCTAssertNil(test.retainedDiskURL); XCTAssertNotNil(test.retentionError)
|
|
let pending = try await test.capture()
|
|
XCTAssertEqual(pending["status"] as? String, "retention_pending")
|
|
for index in 0..<8 {
|
|
do {
|
|
_ = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "different-stop-\(index)"])
|
|
XCTFail("A second cleanup identity bypassed bounded retention retries")
|
|
} catch { XCTAssertTrue(error.localizedDescription.contains("request_conflict")) }
|
|
}
|
|
await expectDiskFailure { try await test.retainForReplacement() }
|
|
try FileManager.default.removeItem(at: blocked)
|
|
let receipt = try await test.reply("stop_playtest", arguments: stop)
|
|
XCTAssertEqual(receipt["retained_disk_sha256"] as? String, expected)
|
|
XCTAssertEqual(receipt["retained_disk_id"] as? String, test.runID)
|
|
XCTAssertTrue(receipt["disk_retained"] as? Bool == true)
|
|
XCTAssertNil(test.retentionError)
|
|
XCTAssertEqual(CMOCProject.sha256(try Data(contentsOf: XCTUnwrap(test.retainedDiskURL))), expected)
|
|
XCTAssertNotEqual(expected, CMOCProject.sha256(original))
|
|
await test.invalidate().value
|
|
|
|
let revokePath = root.appendingPathComponent("revoked")
|
|
try Data("blocked".utf8).write(to: revokePath)
|
|
let revoked = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: original,
|
|
bootCommands: "10 PRINT 11\nSAVE\"TEST\"\n", projectID: "retry-revoke", revision: 1,
|
|
artifactID: UUID().uuidString, helperURL: helper, retentionDirectory: revokePath)
|
|
let revokedSHA = try XCTUnwrap(revoked.startReceipt["disk_sha256"] as? String)
|
|
await revoked.invalidate().value
|
|
XCTAssertNotNil(revoked.retentionError)
|
|
try FileManager.default.removeItem(at: revokePath)
|
|
try await revoked.retainForReplacement()
|
|
XCTAssertEqual(CMOCProject.sha256(try Data(contentsOf: XCTUnwrap(revoked.retainedDiskURL))), revokedSHA)
|
|
do { _ = try await revoked.capture(); XCTFail("Recovered revoked run became accessible") }
|
|
catch { XCTAssertTrue(error.localizedDescription.contains("stale_run")) }
|
|
}
|
|
|
|
private func declaredMedia(artifact: String, project: String, primary: Data, world: Data)
|
|
-> (key: String, proof: MCPPlaytestDiskStore.Provenance, media: [MCPPlaytestMedium]) {
|
|
let key = CMOCProject.sha256(Data(project.utf8)), primaryHash = CMOCProject.sha256(primary)
|
|
func medium(_ mediaKey: String, _ name: String, _ bytes: Data) -> MCPPlaytestMedium {
|
|
let hash = CMOCProject.sha256(bytes)
|
|
let proof = MCPPlaytestDiskStore.Provenance(projectKey: key, artifactID: artifact,
|
|
artifactDiskSHA256: primaryHash, mediaKey: mediaKey, mediaBaseSHA256: hash)
|
|
return MCPPlaytestMedium(id: MCPPlaytestMedium.identifier(artifactID: artifact, key: mediaKey),
|
|
name: name, key: mediaKey, baseSHA256: hash, data: bytes, provenance: proof)
|
|
}
|
|
let media = [medium("primary", "home.dsk", primary), medium("disk:world.dsk", "world.dsk", world)]
|
|
return (key, media[0].provenance, media)
|
|
}
|
|
|
|
private func ownedMediaRow(_ value: [String: Any], id: String) throws -> [String: Any] {
|
|
let rows = try XCTUnwrap(value["media"] as? [[String: Any]])
|
|
return try XCTUnwrap(rows.first { $0["media_id"] as? String == id })
|
|
}
|
|
|
|
func testOwnedMediaSwapsKeepGuestSavesRetriesAndAllRetainedDisksOnBothProcessors() async throws {
|
|
let (helper, system, diskROM) = try inputs()
|
|
let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCOwnedMedia-" + UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: root) }
|
|
let original = disk(); var world = original; world[0] = 0x44
|
|
// Both writes are guest SAVE commands. The W key selects a second SAVE
|
|
// after the host exchanges disks at an ordinary paused prompt/loop.
|
|
let program = "10 CLS:SAVE\"HOME\"\n20 A$=INKEY$:IFA$=\"\"THEN20\n30 IFA$=\"W\"THEN SAVE\"WORLD\":PRINT\"WORLD SAVED\"\n40 GOTO20\nRUN\n"
|
|
for cpu in ["6809", "6309"] {
|
|
let declaration = declaredMedia(artifact: UUID().uuidString, project: "media-save-" + cpu, primary: original, world: world)
|
|
let store = root.appendingPathComponent(cpu)
|
|
let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: original, bootCommands: program,
|
|
projectID: "media-save-" + cpu, revision: 1, artifactID: declaration.proof.artifactID!, cpu: cpu,
|
|
helperURL: helper, retentionDirectory: store, diskProvenance: declaration.proof, media: declaration.media)
|
|
defer { test.invalidate() }
|
|
let homeID = declaration.media[0].id, worldID = declaration.media[1].id
|
|
let savedHome = try XCTUnwrap(test.startReceipt["disk_sha256"] as? String)
|
|
XCTAssertNotEqual(savedHome, CMOCProject.sha256(original))
|
|
XCTAssertGreaterThan(test.startReceipt["disk_writes"] as? Int ?? 0, 0)
|
|
_ = try await test.pausePlaytest()
|
|
let before = try await test.capture()
|
|
let exchange: [String: Any] = ["run_id": test.runID, "request_id": "world-1", "action": "insert",
|
|
"media_id": worldID, "media_sha256": CMOCProject.sha256(world)]
|
|
let inserted = try await test.reply("exchange_playtest_media", arguments: exchange)
|
|
assertProcessor(inserted, cpu: cpu)
|
|
XCTAssertEqual(inserted["media_id"] as? String, worldID)
|
|
XCTAssertEqual(inserted["disk_sha256"] as? String, CMOCProject.sha256(world))
|
|
XCTAssertEqual(inserted["guest_advanced"] as? Bool, false)
|
|
XCTAssertEqual(inserted["guest_reset"] as? Bool, false)
|
|
for key in ["field_clock", "cycles", "generation", "pc", "boot"] {
|
|
XCTAssertEqual(before[key] as? NSNumber, inserted[key] as? NSNumber, key)
|
|
}
|
|
let prior = try XCTUnwrap(inserted["previous_media"] as? [String: Any])
|
|
XCTAssertEqual(prior["media_sha256"] as? String, savedHome)
|
|
XCTAssertEqual(prior["retained"] as? Bool, true)
|
|
let retry = try await test.reply("exchange_playtest_media", arguments: exchange)
|
|
XCTAssertEqual(inserted["media_generation"] as? Int, retry["media_generation"] as? Int)
|
|
XCTAssertEqual(inserted["mutation_requests_used"] as? Int, retry["mutation_requests_used"] as? Int)
|
|
await expectDiskFailure {
|
|
var conflict = exchange; conflict["action"] = "eject"; conflict.removeValue(forKey: "media_id"); conflict.removeValue(forKey: "media_sha256")
|
|
_ = try await test.reply("exchange_playtest_media", arguments: conflict)
|
|
}
|
|
_ = try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": "save-world",
|
|
"steps": [["keys": ["w"], "fields": 18], ["keys": [], "fields": 180]]])
|
|
_ = try await test.pausePlaytest()
|
|
let savedWorldState = try await test.capture()
|
|
let savedWorld = try XCTUnwrap(savedWorldState["disk_sha256"] as? String)
|
|
XCTAssertNotEqual(savedWorld, CMOCProject.sha256(world))
|
|
XCTAssertEqual(savedWorldState["disk_dirty"] as? Bool, true)
|
|
let home = try await test.reply("exchange_playtest_media", arguments: ["run_id": test.runID, "request_id": "home-1",
|
|
"action": "insert", "media_id": homeID, "media_sha256": savedHome])
|
|
XCTAssertEqual(home["disk_sha256"] as? String, savedHome)
|
|
let listing = try await test.reply("list_playtest_media", arguments: ["run_id": test.runID])
|
|
XCTAssertEqual(try ownedMediaRow(listing, id: worldID)["media_sha256"] as? String, savedWorld)
|
|
let restarted = try await test.reply("restart_playtest", arguments: ["run_id": test.runID, "request_id": "cold-home"])
|
|
XCTAssertEqual(restarted["boot"] as? Int, 2)
|
|
XCTAssertEqual(restarted["media_id"] as? String, homeID)
|
|
XCTAssertEqual(restarted["disk_sha256"] as? String, savedHome)
|
|
_ = try await test.pausePlaytest()
|
|
let resumedWorld = try await test.reply("exchange_playtest_media", arguments: ["run_id": test.runID, "request_id": "world-2",
|
|
"action": "insert", "media_id": worldID, "media_sha256": savedWorld])
|
|
XCTAssertEqual(resumedWorld["disk_sha256"] as? String, savedWorld)
|
|
let ejected = try await test.reply("exchange_playtest_media", arguments: ["run_id": test.runID, "request_id": "eject", "action": "eject"])
|
|
XCTAssertEqual(ejected["disk_present"] as? Bool, false)
|
|
let stop = ["run_id": test.runID, "request_id": "stop"]
|
|
let stopped = try await test.reply("stop_playtest", arguments: stop)
|
|
XCTAssertEqual(stopped["disk_present"] as? Bool, false)
|
|
let retained = try XCTUnwrap(stopped["retained_media"] as? [[String: Any]])
|
|
XCTAssertEqual(retained.count, 2)
|
|
for (index, hash) in [savedHome, savedWorld].enumerated() {
|
|
let row = try XCTUnwrap(retained.first { $0["media_id"] as? String == declaration.media[index].id })
|
|
let id = try XCTUnwrap(row["retained_disk_id"] as? String)
|
|
let loaded = try await MCPPlaytestDiskStore.load(directory: store, id: id, expectedSHA256: hash,
|
|
projectKey: declaration.key, artifactDiskSHA256: declaration.proof.artifactDiskSHA256!,
|
|
mediaKey: declaration.media[index].key, mediaBaseSHA256: declaration.media[index].baseSHA256)
|
|
XCTAssertEqual(loaded.record.provenance.projectKey, declaration.key)
|
|
XCTAssertEqual(loaded.record.provenance.mediaKey, declaration.media[index].key)
|
|
XCTAssertEqual(CMOCProject.sha256(loaded.data), hash)
|
|
let directoryEntry = (17 * 18 + 2) * 256
|
|
XCTAssertEqual(String(decoding: loaded.data[directoryEntry..<(directoryEntry + 8)], as: UTF8.self)
|
|
.trimmingCharacters(in: .whitespaces), index == 0 ? "HOME" : "WORLD")
|
|
}
|
|
let stoppedRetry = try await test.reply("stop_playtest", arguments: stop)
|
|
XCTAssertEqual(stopped["retained_disk_id"] as? String, stoppedRetry["retained_disk_id"] as? String)
|
|
XCTAssertEqual(CMOCProject.sha256(original), declaration.media[0].baseSHA256)
|
|
XCTAssertEqual(CMOCProject.sha256(world), declaration.media[1].baseSHA256)
|
|
await test.invalidate().value
|
|
}
|
|
}
|
|
|
|
func testOwnedMediaRetentionFailureLeavesDirtyPausedDiskUsableOnBothProcessors() async throws {
|
|
let (helper, system, diskROM) = try inputs()
|
|
let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCMediaFailure-" + UUID().uuidString)
|
|
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
|
|
defer { try? FileManager.default.removeItem(at: root) }
|
|
for cpu in ["6809", "6309"] {
|
|
let original = disk(); var world = original; world[0] = 0x45
|
|
let declaration = declaredMedia(artifact: UUID().uuidString, project: "media-failure-" + cpu, primary: original, world: world)
|
|
let blocked = root.appendingPathComponent(cpu); try Data("blocked".utf8).write(to: blocked)
|
|
let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: original,
|
|
bootCommands: "10 PRINT 17\nSAVE\"HOME\"\n", projectID: "media-failure-" + cpu, revision: 1,
|
|
artifactID: declaration.proof.artifactID!, cpu: cpu, helperURL: helper, retentionDirectory: blocked,
|
|
diskProvenance: declaration.proof, media: declaration.media)
|
|
defer { test.invalidate() }
|
|
_ = try await test.pausePlaytest()
|
|
let before = try await test.capture()
|
|
let request: [String: Any] = ["run_id": test.runID, "request_id": "blocked-world", "action": "insert",
|
|
"media_id": declaration.media[1].id, "media_sha256": CMOCProject.sha256(world)]
|
|
await expectDiskFailure { _ = try await test.reply("exchange_playtest_media", arguments: request) }
|
|
let unchanged = try await test.capture()
|
|
for key in ["field_clock", "cycles", "generation", "pc", "boot", "media_generation"] {
|
|
XCTAssertEqual(before[key] as? NSNumber, unchanged[key] as? NSNumber, key)
|
|
}
|
|
XCTAssertEqual(unchanged["media_id"] as? String, declaration.media[0].id)
|
|
XCTAssertEqual(unchanged["disk_sha256"] as? String, before["disk_sha256"] as? String)
|
|
XCTAssertEqual(unchanged["disk_dirty"] as? Bool, true)
|
|
try FileManager.default.removeItem(at: blocked)
|
|
// The rejected request is immutable even once the disk problem is fixed.
|
|
await expectDiskFailure { _ = try await test.reply("exchange_playtest_media", arguments: request) }
|
|
var fresh = request; fresh["request_id"] = "fixed-world"
|
|
let inserted = try await test.reply("exchange_playtest_media", arguments: fresh)
|
|
XCTAssertEqual(inserted["media_id"] as? String, declaration.media[1].id)
|
|
XCTAssertEqual(inserted["media_generation"] as? Int, 1)
|
|
let previous = try XCTUnwrap(inserted["previous_media"] as? [String: Any])
|
|
XCTAssertEqual(previous["retained"] as? Bool, true)
|
|
let stopped = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "stop"])
|
|
XCTAssertEqual((stopped["retained_media"] as? [[String: Any]])?.count, 2)
|
|
await test.invalidate().value
|
|
}
|
|
}
|
|
|
|
func testOwnedMediaStaleCommitCallbackPreservesTheCurrentDiskOnBothProcessors() async throws {
|
|
let (helper, system, diskROM) = try inputs()
|
|
let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCMediaStale-" + UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: root) }
|
|
for cpu in ["6809", "6309"] {
|
|
let original = disk(); var world = original; world[0] = 0x46
|
|
let declaration = declaredMedia(artifact: UUID().uuidString, project: "media-stale-" + cpu, primary: original, world: world)
|
|
let store = root.appendingPathComponent(cpu)
|
|
let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: original,
|
|
bootCommands: "10 PRINT 23\nSAVE\"HOME\"\n", projectID: "media-stale-" + cpu, revision: 1,
|
|
artifactID: declaration.proof.artifactID!, cpu: cpu, helperURL: helper, retentionDirectory: store,
|
|
diskProvenance: declaration.proof, media: declaration.media)
|
|
defer { test.invalidate() }
|
|
_ = try await test.pausePlaytest()
|
|
let before = try await test.capture()
|
|
do {
|
|
_ = try await test.reply("exchange_playtest_media", arguments: ["run_id": test.runID, "request_id": "stale",
|
|
"action": "insert", "media_id": declaration.media[1].id, "media_sha256": CMOCProject.sha256(world)],
|
|
isCurrent: { !FileManager.default.fileExists(atPath: store.path) })
|
|
XCTFail("Loss of the current-artifact boundary during durable retention must prevent commit")
|
|
} catch { XCTAssertEqual(error.localizedDescription, "stale_run") }
|
|
XCTAssertTrue(FileManager.default.fileExists(atPath: store.path), "The guard was rechecked after durable retention yielded")
|
|
let after = try await test.capture()
|
|
XCTAssertEqual(after["media_id"] as? String, declaration.media[0].id)
|
|
XCTAssertEqual(after["media_generation"] as? Int, 0)
|
|
XCTAssertEqual(after["disk_sha256"] as? String, before["disk_sha256"] as? String)
|
|
XCTAssertEqual(after["field_clock"] as? Int, before["field_clock"] as? Int)
|
|
_ = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "stop"])
|
|
await test.invalidate().value
|
|
}
|
|
}
|
|
|
|
func testOwnedMediaStopRetainsAllAfterBudgetAndRetriesFailedPersistence() async throws {
|
|
let (helper, system, diskROM) = try inputs()
|
|
let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCMediaStopBudget-" + UUID().uuidString)
|
|
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
|
|
defer { try? FileManager.default.removeItem(at: root) }
|
|
let blocked = root.appendingPathComponent("retained"); try Data("blocked".utf8).write(to: blocked)
|
|
let original = disk(); var world = original; world[0] = 0x47
|
|
let declaration = declaredMedia(artifact: UUID().uuidString, project: "media-stop-budget", primary: original, world: world)
|
|
let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: original,
|
|
bootCommands: "10 PRINT 31\nSAVE\"HOME\"\n", projectID: "media-stop-budget", revision: 1,
|
|
artifactID: declaration.proof.artifactID!, helperURL: helper, retentionDirectory: blocked,
|
|
diskProvenance: declaration.proof, media: declaration.media)
|
|
defer { test.invalidate() }
|
|
for index in 0..<MCPPlaytest.mutationRequestLimit {
|
|
_ = try await test.reply("playtest_debug", arguments: ["run_id": test.runID, "request_id": "pause-\(index)", "action": "pause"])
|
|
}
|
|
let current = try await test.capture()
|
|
XCTAssertEqual(current["remaining_mutation_requests"] as? Int, 0)
|
|
await expectDiskFailure {
|
|
_ = try await test.reply("exchange_playtest_media", arguments: ["run_id": test.runID, "request_id": "over-budget",
|
|
"action": "insert", "media_id": declaration.media[1].id, "media_sha256": CMOCProject.sha256(world)])
|
|
}
|
|
let stop = ["run_id": test.runID, "request_id": "stop"]
|
|
await expectDiskFailure { _ = try await test.reply("stop_playtest", arguments: stop) }
|
|
XCTAssertNotNil(test.retentionError)
|
|
let pending = try await test.capture()
|
|
XCTAssertEqual(pending["status"] as? String, "retention_pending")
|
|
try FileManager.default.removeItem(at: blocked)
|
|
let stopped = try await test.reply("stop_playtest", arguments: stop)
|
|
XCTAssertEqual(stopped["remaining_mutation_requests"] as? Int, 0)
|
|
XCTAssertEqual(stopped["disk_retained"] as? Bool, true)
|
|
XCTAssertEqual((stopped["retained_media"] as? [[String: Any]])?.count, 2)
|
|
XCTAssertNil(test.retentionError)
|
|
XCTAssertEqual(stopped["retained_disk_sha256"] as? String, current["disk_sha256"] as? String)
|
|
let retry = try await test.reply("stop_playtest", arguments: stop)
|
|
XCTAssertEqual(stopped["retained_disk_id"] as? String, retry["retained_disk_id"] as? String)
|
|
await expectDiskFailure { _ = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "other-stop"]) }
|
|
await test.invalidate().value
|
|
}
|
|
|
|
func testAdditionalMediaStoreRequiresExactProjectAndBothBaseIdentities() async throws {
|
|
let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCMediaProvenance-" + UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: root) }
|
|
let original = disk(); var world = original; world[0] = 0x48
|
|
let declaration = declaredMedia(artifact: UUID().uuidString, project: "media-provenance", primary: original, world: world)
|
|
let run = UUID().uuidString, worldRecordID = UUID().uuidString
|
|
let primary = try await MCPPlaytestDiskStore.save(directory: root, runID: run, data: original, provenance: declaration.proof)
|
|
XCTAssertEqual(primary.version, 1); XCTAssertEqual(primary.id, run)
|
|
let additional = try await MCPPlaytestDiskStore.save(directory: root, runID: run, data: world,
|
|
provenance: declaration.media[1].provenance, recordID: worldRecordID)
|
|
XCTAssertEqual(additional.version, 2); XCTAssertEqual(additional.runID, run); XCTAssertEqual(additional.id, worldRecordID)
|
|
let loaded = try await MCPPlaytestDiskStore.load(directory: root, id: additional.id, expectedSHA256: additional.diskSHA256,
|
|
projectKey: declaration.key, artifactDiskSHA256: declaration.proof.artifactDiskSHA256!,
|
|
mediaKey: declaration.media[1].key, mediaBaseSHA256: declaration.media[1].baseSHA256)
|
|
XCTAssertEqual(loaded.data, world)
|
|
for (project, artifactBase, mediaKey, mediaBase) in [
|
|
(CMOCProject.sha256(Data("other-project".utf8)), declaration.proof.artifactDiskSHA256!, declaration.media[1].key, declaration.media[1].baseSHA256),
|
|
(declaration.key, String(repeating: "f", count: 64), declaration.media[1].key, declaration.media[1].baseSHA256),
|
|
(declaration.key, declaration.proof.artifactDiskSHA256!, "disk:other.dsk", declaration.media[1].baseSHA256),
|
|
(declaration.key, declaration.proof.artifactDiskSHA256!, declaration.media[1].key, String(repeating: "e", count: 64)),
|
|
(declaration.key, declaration.proof.artifactDiskSHA256!, "primary", declaration.media[1].baseSHA256)] {
|
|
await expectDiskFailure {
|
|
_ = try await MCPPlaytestDiskStore.load(directory: root, id: additional.id, expectedSHA256: additional.diskSHA256,
|
|
projectKey: project, artifactDiskSHA256: artifactBase, mediaKey: mediaKey, mediaBaseSHA256: mediaBase)
|
|
}
|
|
}
|
|
let primaryAgain = try await MCPPlaytestDiskStore.load(directory: root, id: primary.id, expectedSHA256: primary.diskSHA256,
|
|
projectKey: declaration.key, artifactDiskSHA256: declaration.proof.artifactDiskSHA256!)
|
|
XCTAssertEqual(primaryAgain.data, original, "The existing primary-store selection remains compatible")
|
|
let legacyID = UUID().uuidString
|
|
try original.write(to: root.appendingPathComponent(legacyID + ".dsk"))
|
|
await expectDiskFailure {
|
|
_ = try await MCPPlaytestDiskStore.load(directory: root, id: legacyID, expectedSHA256: CMOCProject.sha256(original),
|
|
projectKey: declaration.key, artifactDiskSHA256: declaration.proof.artifactDiskSHA256!,
|
|
mediaKey: declaration.media[1].key, mediaBaseSHA256: declaration.media[1].baseSHA256)
|
|
}
|
|
let legacy = try await MCPPlaytestDiskStore.load(directory: root, id: legacyID, expectedSHA256: CMOCProject.sha256(original),
|
|
projectKey: declaration.key, artifactDiskSHA256: declaration.proof.artifactDiskSHA256!)
|
|
XCTAssertEqual(legacy.record.version, 0); XCTAssertEqual(legacy.record.provenance.origin, "legacy_receipt")
|
|
XCTAssertEqual(legacy.data, original)
|
|
}
|
|
|
|
/// Negative wire fixtures are deliberately not emulators. Real guest storage
|
|
/// evidence comes from the separate both-CPU worker/public-host tests.
|
|
private func faultingMediaHelper(_ mode: String, worldID: String, root: URL) throws -> URL {
|
|
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
|
let path = root.appendingPathComponent("wire-fixture")
|
|
let source = """
|
|
#!/usr/bin/env python3
|
|
import sys,json,base64,hashlib,os
|
|
mode=\(String(reflecting: mode))
|
|
world_id=\(String(reflecting: worldID))
|
|
data=b''; media_id=None; cpu='6809'; generation=0
|
|
def status():
|
|
return {'cpu':cpu,'processor':'HD6309' if cpu=='6309' else 'MC6809',
|
|
'state':'paused','media_id':media_id,'media_generation':generation,
|
|
'disk_present':media_id is not None,'disk_sha256':hashlib.sha256(data).hexdigest() if media_id else '',
|
|
'disk_dirty':False,'floppy_busy':False,'field_clock':0,'cycles':100,'generation':1,'boot':1,'pc':100}
|
|
for line in sys.stdin:
|
|
r=json.loads(line); op=r['op']; end=False
|
|
if op=='init':
|
|
data=base64.b64decode(r['disk']); media_id=r['media_id']; cpu=r['cpu']; out=status()
|
|
elif op=='export_media':
|
|
out=status(); out['disk_base64']=base64.b64encode(data).decode()
|
|
if mode=='wrong-export': out['media_id']=world_id
|
|
elif op=='media_status' or op=='capture': out=status()
|
|
elif op=='exchange_media':
|
|
if mode not in ('exit-after-commit','mark-after-commit'):
|
|
print(json.dumps({'error':'unexpected_commit'}),flush=True); continue
|
|
old_hash=hashlib.sha256(data).hexdigest()
|
|
data=base64.b64decode(r['disk_base64']); media_id=r['media_id']; generation+=1
|
|
if mode=='exit-after-commit': os._exit(0)
|
|
with open(os.path.join(os.path.dirname(__file__),'committed'),'w') as marker: marker.write('committed')
|
|
out=status(); out['previous_disk_sha256']=old_hash
|
|
elif op=='stop':
|
|
out=status(); out['disk_base64']=base64.b64encode(data).decode(); end=True
|
|
else:
|
|
print(json.dumps({'error':'unexpected_operation'}),flush=True); continue
|
|
print(json.dumps({'result':out}),flush=True)
|
|
if end: break
|
|
"""
|
|
try Data(source.utf8).write(to: path)
|
|
try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: path.path)
|
|
return path
|
|
}
|
|
|
|
func testAcknowledgedSwapWithLateOwnershipLossRetainsCommittedReceipt() async throws {
|
|
let root = FileManager.default.temporaryDirectory.appendingPathComponent("MediaLateOwnership-" + UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: root) }
|
|
let original = disk(); var world = original; world[0] = 0x49
|
|
let declaration = declaredMedia(artifact: UUID().uuidString, project: "late-ownership", primary: original, world: world)
|
|
let helper = try faultingMediaHelper("mark-after-commit", worldID: declaration.media[1].id, root: root)
|
|
let marker = root.appendingPathComponent("committed")
|
|
let test = try await MCPPlaytest.start(systemROM: Data(repeating: 0, count: 32768), diskROM: Data(repeating: 0, count: 8192),
|
|
disk: original, bootCommands: "\n", projectID: "late-ownership", revision: 0, artifactID: declaration.proof.artifactID!,
|
|
helperURL: helper, retentionDirectory: root.appendingPathComponent("retained"),
|
|
diskProvenance: declaration.proof, media: declaration.media)
|
|
defer { test.invalidate() }
|
|
let before = try await test.capture()
|
|
let request: [String: Any] = ["run_id": test.runID, "request_id": "committed-world", "action": "insert",
|
|
"media_id": declaration.media[1].id, "media_sha256": declaration.media[1].baseSHA256]
|
|
do {
|
|
// The wire fixture changes this boundary only after applying the
|
|
// swap, avoiding a dependency on the number of authority checks.
|
|
_ = try await test.reply("exchange_playtest_media", arguments: request,
|
|
isCurrent: { !FileManager.default.fileExists(atPath: marker.path) })
|
|
XCTFail("A committed exchange must not send a success reply through expired authority")
|
|
} catch { XCTAssertEqual(error.localizedDescription, "stale_run_after_commit") }
|
|
XCTAssertTrue(FileManager.default.fileExists(atPath: marker.path))
|
|
let after = try await test.capture()
|
|
XCTAssertEqual(after["media_id"] as? String, declaration.media[1].id)
|
|
XCTAssertEqual(after["media_generation"] as? Int, 1)
|
|
for key in ["field_clock", "cycles", "generation", "boot", "pc"] {
|
|
XCTAssertEqual(before[key] as? NSNumber, after[key] as? NSNumber, key)
|
|
}
|
|
// Inspect the component's retained outcome, not a renewed external
|
|
// grant: the production host rejects this stale lease before dispatch.
|
|
let receipt = try await test.reply("exchange_playtest_media", arguments: request)
|
|
XCTAssertEqual(receipt["exchange"] as? String, "inserted")
|
|
XCTAssertEqual(receipt["media_generation"] as? Int, 1)
|
|
XCTAssertEqual(receipt["disk_sha256"] as? String, CMOCProject.sha256(world))
|
|
let replayed = try await test.capture()
|
|
XCTAssertEqual(replayed["media_generation"] as? Int, 1, "Receipt replay must not perform another exchange")
|
|
await test.invalidate().value
|
|
let stopped = try XCTUnwrap(test.finalReceipt)
|
|
let retained = try XCTUnwrap(stopped["retained_media"] as? [[String: Any]])
|
|
XCTAssertEqual(retained.count, 2)
|
|
for (index, expected) in [original, world].enumerated() {
|
|
let row = try XCTUnwrap(retained.first { $0["media_id"] as? String == declaration.media[index].id })
|
|
XCTAssertEqual(row["disk_sha256"] as? String, CMOCProject.sha256(expected))
|
|
}
|
|
}
|
|
|
|
func testWrongKnownExportIdentityCannotOverwriteAnotherPrivateMedium() async throws {
|
|
let root = FileManager.default.temporaryDirectory.appendingPathComponent("MediaWrongReply-" + UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: root) }
|
|
let original = disk(); var world = original; world[0] = 0x44
|
|
let declaration = declaredMedia(artifact: UUID().uuidString, project: "wrong-reply", primary: original, world: world)
|
|
let helper = try faultingMediaHelper("wrong-export", worldID: declaration.media[1].id, root: root)
|
|
let store = root.appendingPathComponent("retained")
|
|
let test = try await MCPPlaytest.start(systemROM: Data(repeating: 0, count: 32768), diskROM: Data(repeating: 0, count: 8192),
|
|
disk: original, bootCommands: "\n", projectID: "wrong-reply", revision: 0, artifactID: declaration.proof.artifactID!,
|
|
helperURL: helper, retentionDirectory: store, diskProvenance: declaration.proof, media: declaration.media)
|
|
await expectDiskFailure {
|
|
_ = try await test.reply("exchange_playtest_media", arguments: ["run_id": test.runID, "request_id": "bad-export",
|
|
"action": "insert", "media_id": declaration.media[1].id, "media_sha256": declaration.media[1].baseSHA256])
|
|
}
|
|
let inventory = try await test.reply("list_playtest_media", arguments: ["run_id": test.runID])
|
|
XCTAssertEqual(try ownedMediaRow(inventory, id: declaration.media[1].id)["media_sha256"] as? String, CMOCProject.sha256(world))
|
|
let stopped = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "stop"])
|
|
let records = try XCTUnwrap(stopped["retained_media"] as? [[String: Any]])
|
|
let saved = try XCTUnwrap(records.first { $0["media_id"] as? String == declaration.media[1].id })
|
|
XCTAssertEqual(saved["disk_sha256"] as? String, CMOCProject.sha256(world))
|
|
}
|
|
|
|
func testLostSwapReplyRetainsEveryFrozenCopyWithUncertainSelection() async throws {
|
|
let root = FileManager.default.temporaryDirectory.appendingPathComponent("MediaLostReply-" + UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: root) }
|
|
let original = disk(); var world = original; world[0] = 0x44
|
|
let declaration = declaredMedia(artifact: UUID().uuidString, project: "lost-reply", primary: original, world: world)
|
|
let helper = try faultingMediaHelper("exit-after-commit", worldID: declaration.media[1].id, root: root)
|
|
let store = root.appendingPathComponent("retained")
|
|
let test = try await MCPPlaytest.start(systemROM: Data(repeating: 0, count: 32768), diskROM: Data(repeating: 0, count: 8192),
|
|
disk: original, bootCommands: "\n", projectID: "lost-reply", revision: 0, artifactID: declaration.proof.artifactID!,
|
|
helperURL: helper, retentionDirectory: store, diskProvenance: declaration.proof, media: declaration.media)
|
|
await expectDiskFailure {
|
|
_ = try await test.reply("exchange_playtest_media", arguments: ["run_id": test.runID, "request_id": "lost-commit",
|
|
"action": "insert", "media_id": declaration.media[1].id, "media_sha256": declaration.media[1].baseSHA256])
|
|
}
|
|
await test.invalidate().value
|
|
let receipt = try XCTUnwrap(test.finalReceipt)
|
|
XCTAssertEqual(receipt["media_selection_uncertain"] as? Bool, true)
|
|
XCTAssertNil(test.retentionError)
|
|
let records = try XCTUnwrap(receipt["retained_media"] as? [[String: Any]])
|
|
XCTAssertEqual(records.count, 2)
|
|
for (index, medium) in declaration.media.enumerated() {
|
|
let saved = try XCTUnwrap(records.first { $0["media_id"] as? String == medium.id })
|
|
let copy = try await MCPPlaytestDiskStore.load(directory: store,
|
|
id: try XCTUnwrap(saved["retained_disk_id"] as? String), expectedSHA256: try XCTUnwrap(saved["disk_sha256"] as? String),
|
|
projectKey: declaration.key, artifactDiskSHA256: declaration.proof.artifactDiskSHA256!,
|
|
mediaKey: medium.key, mediaBaseSHA256: medium.baseSHA256)
|
|
XCTAssertEqual(copy.data, index == 0 ? original : world)
|
|
}
|
|
}
|
|
|
|
}
|