Files
VCCPlusOSS/platforms/macos/Tests/MCPPlaytestTests.swift
T
Brian Holman 5534005799 Sync VCC Plus 3.7.1 build 67 source
Refresh reviewed MCP output export, four-drive owned playtests, bounded BASIC readiness, and pinned CMOC 0.1.101 source/patches. Preserve independent source-edition identity, empty libraries, notices and privacy boundaries.

Validated 74 export/privacy checks, pinned dependency sources, and an independent unsigned universal Release build. A subsequent documentation-only correction removes an excluded qualification link; all build inputs remain identical.
2026-11-17 08:42:27 -07:00

2703 lines
199 KiB
Swift

// SPDX-License-Identifier: GPL-3.0-or-later
import XCTest
import AVFoundation
import Darwin
@MainActor
final class MCPPlaytestTests: XCTestCase {
func testMissingOrChangedVideoDoesNotPreventGuestDiskRetention() async throws {
let (helper, system, diskROM) = try inputs()
for mediaEnabled in [false, true] {
let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCVideoDiskSafety-" + UUID().uuidString)
defer { try? FileManager.default.removeItem(at: root) }
let original = disk(), artifact = UUID().uuidString
let baseHash = CMOCProject.sha256(original)
let provenance = MCPPlaytestDiskStore.Provenance(projectKey: CMOCProject.sha256(Data("video-disk-safety".utf8)),
artifactID: artifact, artifactDiskSHA256: baseHash, mediaKey: mediaEnabled ? "primary" : nil,
mediaBaseSHA256: mediaEnabled ? baseHash : nil)
let media: [MCPPlaytestMedium]? = mediaEnabled ? [MCPPlaytestMedium(id: MCPPlaytestMedium.identifier(artifactID: artifact, key: "primary"),
name: "HOME.dsk", key: "primary", baseSHA256: baseHash, data: original, provenance: provenance)] : nil
let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: original,
bootCommands: "10 PRINT 37\nSAVE\"TEST\"\n", projectID: "video-disk-safety", revision: 1,
artifactID: artifact, helperURL: helper, retentionDirectory: root, diskProvenance: provenance, media: media,
videoArtifactWillVerify: { clip in
// Fail exactly at first host registration, after the real
// worker finalized its MP4 and before the host reads it.
if mediaEnabled { try Data([0,1,2,3]).write(to: clip, options: .atomic) }
else { try FileManager.default.removeItem(at: clip) }
})
defer { test.invalidate() }
let savedHash = try XCTUnwrap(test.startReceipt["disk_sha256"] as? String)
XCTAssertNotEqual(savedHash, CMOCProject.sha256(original), "An ordinary guest SAVE must change the retained disk")
_ = try await test.reply("start_playtest_video", arguments: ["run_id": test.runID, "request_id": "begin", "include_audio": false, "max_fields": 120])
let input = try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": "fields", "steps": [["keys": [], "fields": 3]]])
let video = try XCTUnwrap(input["video_recording"] as? [String: Any])
let id = try XCTUnwrap(video["clip_id"] as? String)
let stopped = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "stop"])
XCTAssertEqual(stopped["disk_retained"] as? Bool, true)
XCTAssertNotNil(stopped["video_retention_error"], "A separate artifact failure must remain visible")
let retained = try XCTUnwrap(test.retainedDiskURL)
XCTAssertEqual(CMOCProject.sha256(try Data(contentsOf: retained)), savedHash)
await expectDiskFailure { _ = try await test.reply("read_playtest_video", arguments: ["run_id": test.runID, "clip_id": id]) }
}
}
private func videoBytes(_ test: MCPPlaytest, metadata: [String: Any]) async throws -> Data {
let id = try XCTUnwrap(metadata["clip_id"] as? String)
let size = try XCTUnwrap(metadata["byte_count"] as? Int)
XCTAssertGreaterThan(size, 0); XCTAssertLessThanOrEqual(size, 64 * 1024 * 1024)
var data = Data(), offset = 0
while offset < size {
let arguments: [String: Any] = ["run_id": test.runID, "clip_id": id, "offset": offset, "limit": 4096]
let chunk = try await test.reply("read_playtest_video", arguments: arguments)
XCTAssertEqual(chunk["clip_id"] as? String, id)
XCTAssertEqual(chunk["offset"] as? Int, offset)
XCTAssertEqual(chunk["byte_count"] as? Int, size)
XCTAssertEqual(chunk["mime_type"] as? String, "video/mp4")
XCTAssertEqual(chunk["sha256"] as? String, metadata["sha256"] as? String)
let bytes = try XCTUnwrap((chunk["video_chunk_base64"] as? String).flatMap { Data(base64Encoded: $0) })
XCTAssertFalse(bytes.isEmpty); XCTAssertLessThanOrEqual(bytes.count, 4096)
guard !bytes.isEmpty else { throw ProfileFailure.message("Empty video chunk before EOF") }
data.append(bytes); offset += bytes.count
XCTAssertEqual(chunk["next_offset"] as? Int, offset)
XCTAssertEqual(chunk["eof"] as? Bool, offset == size)
let retry = try await test.reply("read_playtest_video", arguments: arguments)
XCTAssertEqual(retry["video_chunk_base64"] as? String, chunk["video_chunk_base64"] as? String)
}
XCTAssertEqual(data.count, size); XCTAssertEqual(CMOCProject.sha256(data), metadata["sha256"] as? String)
let eof = try await test.reply("read_playtest_video", arguments: ["run_id": test.runID, "clip_id": id, "offset": size])
XCTAssertEqual(eof["eof"] as? Bool, true); XCTAssertEqual(eof["video_chunk_base64"] as? String, "")
return data
}
private func decodedVideoAudio(_ url: URL) async throws -> (Float, Float, Int) {
let asset = AVURLAsset(url: url)
let tracks = try await asset.loadTracks(withMediaType: .audio)
let track = try XCTUnwrap(tracks.first)
let reader = try AVAssetReader(asset: asset)
let output = AVAssetReaderTrackOutput(track: track, outputSettings: [AVFormatIDKey: kAudioFormatLinearPCM,
AVLinearPCMIsFloatKey: true, AVLinearPCMBitDepthKey: 32, AVLinearPCMIsNonInterleaved: false])
reader.add(output); XCTAssertTrue(reader.startReading())
var minimum: Float = 1, maximum: Float = -1, count = 0
while let sample = output.copyNextSampleBuffer() {
let buffer = try XCTUnwrap(CMSampleBufferGetDataBuffer(sample))
var data = Data(count: CMBlockBufferGetDataLength(buffer))
XCTAssertEqual(data.withUnsafeMutableBytes {
CMBlockBufferCopyDataBytes(buffer, atOffset: 0, dataLength: $0.count, destination: $0.baseAddress!)
}, noErr)
data.withUnsafeBytes { raw in
for value in raw.bindMemory(to: Float.self) { minimum = min(minimum, value); maximum = max(maximum, value); count += 1 }
}
}
XCTAssertEqual(reader.status, .completed); XCTAssertGreaterThan(count, 0)
return (minimum, maximum, count)
}
func testOwnedVideoRecordsActualFieldsAudioChoiceAndRetryIdentityOnBothProcessors() async throws {
let (helper, system, diskROM) = try inputs()
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCCOwnedVideo-" + UUID().uuidString)
defer { try? FileManager.default.removeItem(at: folder) }
for cpu in ["6809", "6309"] {
let root = folder.appendingPathComponent(cpu)
let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: disk(),
bootCommands: "10 CLS 3:PRINT \"VIDEO\"\n20 SOUND 80,255:GOTO20\nRUN\n",
projectID: "video-fixture", revision: 1, artifactID: UUID().uuidString, cpu: cpu,
helperURL: helper, retentionDirectory: root)
do {
let before = try await test.capture()
for value: Any in [0, 3601, true, 1.5] {
await expectDiskFailure {
_ = try await test.reply("start_playtest_video", arguments: ["run_id": test.runID, "request_id": "invalid", "max_fields": value])
}
}
for value: Any in [1, "yes"] {
await expectDiskFailure {
_ = try await test.reply("start_playtest_video", arguments: ["run_id": test.runID, "request_id": "invalid-audio", "include_audio": value])
}
}
await expectDiskFailure { _ = try await test.reply("start_playtest_video", arguments: ["run_id": "foreign", "request_id": "foreign"]) }
let afterInvalid = try await test.capture()
XCTAssertEqual(afterInvalid["field_clock"] as? Int, before["field_clock"] as? Int)
for includeAudio in [true, false] {
let key = includeAudio ? "audio" : "silent"
let starting = try await test.capture()
let startArgs: [String: Any] = ["run_id": test.runID, "request_id": "begin-" + key,
"include_audio": includeAudio, "max_fields": 120]
let started = try await test.reply("start_playtest_video", arguments: startArgs)
XCTAssertEqual(started["field_clock"] as? Int, starting["field_clock"] as? Int, "Starting video must not execute the guest")
let startRetry = try await test.reply("start_playtest_video", arguments: startArgs)
XCTAssertEqual(startRetry as NSDictionary, started as NSDictionary)
await expectDiskFailure {
_ = try await test.reply("start_playtest_video", arguments: ["run_id": test.runID, "request_id": "begin-" + key, "include_audio": !includeAudio, "max_fields": 120])
}
await expectDiskFailure {
_ = try await test.reply("restart_playtest", arguments: ["run_id": test.runID, "request_id": "restart-" + key])
}
let inputArgs: [String: Any] = ["run_id": test.runID, "request_id": "fields-" + key,
"steps": [["keys": ["space"], "fields": 30], ["keys": [], "fields": 30]]]
let input = try await test.reply("playtest_input", arguments: inputArgs)
assertProcessor(input, cpu: cpu)
let trace = try XCTUnwrap(input["input_trace"] as? [[String: Any]])
XCTAssertEqual(trace.count, 2); XCTAssertEqual(trace[0]["fields_advanced"] as? Int, 30)
XCTAssertEqual((trace[0]["input"] as? [String: Any])?["neutral"] as? Bool, false)
XCTAssertEqual((trace[1]["input"] as? [String: Any])?["neutral"] as? Bool, true)
let inputRetry = try await test.reply("playtest_input", arguments: inputArgs)
XCTAssertEqual(inputRetry["field_clock"] as? Int, input["field_clock"] as? Int)
let stopArgs: [String: Any] = ["run_id": test.runID, "request_id": "end-" + key]
let stopped = try await test.reply("stop_playtest_video", arguments: stopArgs)
let stopRetry = try await test.reply("stop_playtest_video", arguments: stopArgs)
XCTAssertEqual(stopRetry as NSDictionary, stopped as NSDictionary)
XCTAssertEqual(stopped["field_clock"] as? Int, input["field_clock"] as? Int, "Stopping video must not execute the guest")
let video = try XCTUnwrap(stopped["video"] as? [String: Any])
XCTAssertEqual(video["include_audio"] as? Bool, includeAudio)
XCTAssertEqual(video["fields_recorded"] as? Int, 60)
XCTAssertEqual(video["truncated"] as? Bool, false)
XCTAssertEqual((video["field_end"] as? Int ?? -1) - (video["field_start"] as? Int ?? -1), 60)
let movie = root.appendingPathComponent(key + ".mp4")
try await videoBytes(test, metadata: video).write(to: movie)
let asset = AVURLAsset(url: movie)
let duration = try await asset.load(.duration).seconds
XCTAssertEqual(duration, 1, accuracy: 0.05)
let tracks = try await asset.loadTracks(withMediaType: .video)
XCTAssertEqual(tracks.count, 1)
let dimensions = try await XCTUnwrap(tracks.first).load(.naturalSize)
XCTAssertEqual(dimensions, CGSize(width: 1280, height: 960))
let generator = AVAssetImageGenerator(asset: asset)
let frame = try await generator.image(at: .zero).image
XCTAssertEqual(frame.width, 1280); XCTAssertEqual(frame.height, 960)
let samples = try await decodedVideoAudio(movie)
if includeAudio { XCTAssertGreaterThan(samples.1 - samples.0, 0.01, "A real guest SOUND program must reach the delivered MP4") }
else { XCTAssertLessThan(max(abs(samples.0), abs(samples.1)), 0.00001, "Silent video must exclude guest audio and all UI cues") }
if !includeAudio {
let id = try XCTUnwrap(video["clip_id"] as? String)
let retained = root.appendingPathComponent("Videos/\(test.runID)/\(id)/Clip.mp4")
try FileManager.default.removeItem(at: retained)
XCTAssertEqual(mkfifo(retained.path, 0o600), 0)
let began = ContinuousClock.now
await expectDiskFailure { _ = try await test.reply("read_playtest_video", arguments: ["run_id": test.runID, "clip_id": id]) }
XCTAssertLessThan(began.duration(to: .now), .seconds(2), "A replaced FIFO must not block the ownership lease before validation")
}
let clipID = try XCTUnwrap(video["clip_id"] as? String)
await expectDiskFailure { _ = try await test.reply("read_playtest_video", arguments: ["run_id": test.runID, "clip_id": clipID, "offset": -1]) }
await expectDiskFailure { _ = try await test.reply("read_playtest_video", arguments: ["run_id": test.runID, "clip_id": UUID().uuidString]) }
await expectDiskFailure { _ = try await test.reply("read_playtest_video", arguments: ["run_id": "foreign", "clip_id": clipID]) }
}
let retained = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "retain"])
XCTAssertEqual(retained["disk_retained"] as? Bool, true)
XCTAssertEqual(try Data(contentsOf: XCTUnwrap(test.retainedDiskURL)), disk())
} catch { await test.invalidate().value; throw error }
await test.invalidate().value
}
}
func testVideoFieldBoundAndRunStopRetainCompletedClipsWithoutMoreExecution() async throws {
let (helper, system, diskROM) = try inputs()
let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCVideoBounds-" + UUID().uuidString)
defer { try? FileManager.default.removeItem(at: root) }
let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: disk(),
bootCommands: "10 CLS:PRINT \"BOUNDED VIDEO\"\n20 GOTO20\nRUN\n", projectID: "video-bound", revision: 1,
artifactID: UUID().uuidString, helperURL: helper, retentionDirectory: root)
do {
_ = try await test.reply("start_playtest_video", arguments: ["run_id": test.runID, "request_id": "begin-limit", "max_fields": 2])
let input = try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": "cross-limit", "steps": [["keys": [], "fields": 5]]])
let limited = try await test.reply("stop_playtest_video", arguments: ["run_id": test.runID, "request_id": "end-limit"])
let video = try XCTUnwrap(limited["video"] as? [String: Any])
XCTAssertEqual(video["fields_recorded"] as? Int, 2); XCTAssertEqual(video["truncated"] as? Bool, true)
XCTAssertEqual(video["reason"] as? String, "field_limit"); XCTAssertEqual(video["completed"] as? Bool, true)
XCTAssertEqual(limited["field_clock"] as? Int, input["field_clock"] as? Int)
_ = try await videoBytes(test, metadata: video)
_ = try await test.reply("start_playtest_video", arguments: ["run_id": test.runID, "request_id": "begin-cleanup", "include_audio": false])
let last = try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": "cleanup-fields", "steps": [["keys": [], "fields": 3]]])
let stopped = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "retain-with-video"])
XCTAssertEqual(stopped["disk_retained"] as? Bool, true)
XCTAssertEqual(stopped["field_clock"] as? Int, last["field_clock"] as? Int)
let finalVideo = try XCTUnwrap(stopped["video"] as? [String: Any])
XCTAssertEqual(finalVideo["fields_recorded"] as? Int, 3)
XCTAssertEqual(finalVideo["reason"] as? String, "run_stopped"); XCTAssertEqual(finalVideo["truncated"] as? Bool, false)
_ = try await videoBytes(test, metadata: finalVideo)
XCTAssertEqual(try Data(contentsOf: XCTUnwrap(test.retainedDiskURL)), disk())
} catch { await test.invalidate().value; throw error }
await test.invalidate().value
}
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() }
_ = try await test.reply("start_playtest_video", arguments: ["run_id": test.runID, "request_id": "video-before-limit", "include_audio": false])
_ = try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": "video-fields", "steps": [["keys": [], "fields": 2]]])
let budget = try await test.capture()
let remaining = try XCTUnwrap(budget["remaining_mutation_requests"] as? Int)
for index in 0..<remaining {
_ = 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 finishedVideo = try await test.reply("stop_playtest_video", arguments: ["run_id": test.runID, "request_id": "finish-video-after-limit"])
let clip = try XCTUnwrap(finishedVideo["video"] as? [String: Any])
XCTAssertEqual(clip["fields_recorded"] as? Int, 2)
_ = try await videoBytes(test, metadata: clip)
for index in 0..<32 {
do {
_ = try await test.reply("stop_playtest_video", arguments: ["run_id": test.runID, "request_id": "extra-video-stop-\(index)"])
XCTFail("A cleanup exemption must not retain unlimited distinct stop receipts")
} catch { XCTAssertTrue(error.localizedDescription.contains("request_conflict")) }
}
let sameVideoStop = try await test.reply("stop_playtest_video", arguments: ["run_id": test.runID, "request_id": "finish-video-after-limit"])
XCTAssertEqual(sameVideoStop as NSDictionary, finishedVideo as NSDictionary)
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()) }
}
private enum PhysicalOverlayLoad { case complete, partial, corrupted }
/// Authored LOADM guest: real 6809 instructions copy two immutable code
/// pieces into the same physical RAM. The ROM pair still comes from the
/// selected build resources through inputs(); these bytes are not firmware.
private func physicalOverlayFixture(_ mode: PhysicalOverlayLoad) throws -> (disk: Data, modules: [[String: Any]], a: Data, b: Data) {
let a = Data([0x12, 0x86, 0x11, 0xb7, 0x50, 0x00, 0x7e, 0x11, 0x00])
let b = mode == .complete
? Data([0x12, 0x86, 0x22, 0xb7, 0x50, 0x00, 0x7e, 0x12, 0x00])
: Data([0x12, 0x86, 0x22, 0xb7, 0x50, 0x00, 0x20, 0xf8])
let witnessA = Data([0x12, 0x86, 0xa1, 0x39]), witnessB = Data([0x12, 0x86, 0xb2, 0x39])
func raw(_ code: Data, _ witness: Data) -> Data {
code + Data(repeating: 0x12, count: 0x20 - code.count) + witness
}
let rawA = raw(a, witnessA), rawB = raw(b, witnessB)
func loader(_ source: UInt16, count: Int, corruptWitness: Bool = false) -> Data {
// LDX #$4000; LDY #source; LDB #count;
// copy: LDA ,Y+; STA ,X+; DECB; BNE copy.
var code = Data([0x8e, 0x40, 0, 0x10, 0x8e, UInt8(source >> 8), UInt8(source & 255),
0xc6, UInt8(count), 0xa6, 0xa0, 0xa7, 0x80, 0x5a, 0x26, 0xf9])
if corruptWitness { code.append(contentsOf: [0x86, 0xc3, 0xb7, 0x40, 0x22]) } // Guest LDA/STA.
code.append(contentsOf: [0x7e, 0x40, 0])
return code
}
let loadA = loader(0x2000, count: rawA.count)
let loadB = loader(0x2100, count: mode == .partial ? b.count : rawB.count, corruptWitness: mode == .corrupted)
let blocks: [(UInt16, Data)] = [(0x1000, loadA), (0x1100, loadB), (0x1200, loadA), (0x2000, rawA), (0x2100, rawB)]
var binary = Data()
for (address, bytes) in blocks {
binary.append(contentsOf: [0, UInt8(bytes.count >> 8), UInt8(bytes.count & 255), UInt8(address >> 8), UInt8(address & 255)])
binary.append(bytes)
}
binary.append(contentsOf: [255, 0, 0, 0x10, 0])
guard binary.count < 256 else { throw ProfileFailure.message("The authored overlay fixture must fit one DECB sector.") }
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)
func guardBytes(_ address: Int, _ bytes: Data) -> [String: Any] {
["address": address, "bytes_base64": bytes.base64EncodedString()]
}
func piece(_ id: String, owner: String, address: Int, bytes: Data) -> [String: Any] {
["id": id, "overlay_group": "stage-code", "overlay_owner": owner,
"pages": [["logical_page": 2, "physical_page": 58]], "guards": [guardBytes(address, bytes)]]
}
let modules = [
piece("a-entry", owner: "A", address: 0x4000, bytes: a),
piece("a-witness", owner: "A", address: 0x4020, bytes: witnessA),
piece("b-entry", owner: "B", address: 0x4000, bytes: b),
piece("b-witness", owner: "B", address: 0x4020, bytes: witnessB),
["id": "loader", "pages": [["logical_page": 0, "physical_page": 56]],
"guards": [guardBytes(0x1000, loadA), guardBytes(0x1100, loadB), guardBytes(0x1200, loadA)]]
]
return (image, modules, a, b)
}
func testPhysicalCodeOverlayWorkerFollowsActualGuestCopiesAndRetainsDiskOnBothProcessors() async throws {
let (helper, system, diskROM) = try inputs()
let fixture = try physicalOverlayFixture(.complete)
let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCPhysicalOverlay-" + UUID().uuidString)
defer { try? FileManager.default.removeItem(at: root) }
for cpu in ["6809", "6309"] {
let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: fixture.disk,
// Buffer disk operations in one BASIC command before SAVE runs,
// so subsequent pasted characters cannot arrive during disk I/O.
bootCommands: "10 PRINT 7\nSAVE\"MARKER\":LOADM\"PROBE\":EXEC\n", projectID: "physical-overlay-worker",
revision: 1, artifactID: UUID().uuidString, modules: fixture.modules, stopAt: 0x4000,
stopModule: "a-entry", cpu: cpu, helperURL: helper, retentionDirectory: root.appendingPathComponent(cpu))
defer { test.invalidate() }
if test.startReceipt["state"] as? String != "paused" {
let screen = try await test.capture()
_ = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "failed-start-cleanup"])
XCTFail("Overlay guest did not reach A: \(screen["screen_text"] ?? "no screen text"); PC \(screen["pc"] ?? "unknown")")
return
}
XCTAssertEqual(test.startReceipt["ram_kb"] as? Int, 512)
assertProcessor(test.startReceipt, cpu: cpu)
XCTAssertNotEqual(test.startReceipt["disk_sha256"] as? String, CMOCProject.sha256(fixture.disk), "SAVE must actually modify the disposable guest disk")
func captured(_ expected: Data, witness: UInt8) async throws -> [String: Any] {
let capture = try await test.debugCapture()
assertProcessor(capture, cpu: cpu)
XCTAssertEqual(capture["pc"] as? Int, 0x4000)
XCTAssertEqual(capture["attached"] as? Bool, true)
XCTAssertEqual((capture["physical_pages"] as? [String: Int])?["2"], 58)
let memory = try XCTUnwrap((capture["logical_memory"] as? String).flatMap { Data(base64Encoded: $0) })
XCTAssertEqual(Data(memory[0x4000..<(0x4000 + expected.count)]), expected)
XCTAssertEqual(memory[0x4022], witness)
XCTAssertNotEqual(capture["residency_fingerprint"] as? String, "0")
return capture
}
let first = try await captured(fixture.a, witness: 0xa1)
let firstResidency = try XCTUnwrap(first["residency_fingerprint"] as? String)
func stop(_ module: String, request: String) async throws {
_ = try await test.reply("playtest_debug", arguments: ["run_id": test.runID, "request_id": request,
"action": "stop_at", "address": 0x4000, "module_id": module, "selection": "function_entry:" + module])
let receipt = try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": request + "-advance",
"steps": [["keys": [], "fields": 2]]])
XCTAssertEqual(receipt["state"] as? String, "paused")
}
// The entry opcode, logical address and physical page are identical.
// Asking for B must run past A and let the guest loader install B.
try await stop("b-entry", request: "owner-b")
let second = try await captured(fixture.b, witness: 0xb2)
XCTAssertNotEqual(second["residency_fingerprint"] as? String, firstResidency)
XCTAssertEqual(second["mapping_fingerprint"] as? String, first["mapping_fingerprint"] as? String)
XCTAssertEqual(second["program_revision"] as? Int, first["program_revision"] as? Int)
let secondMemory = try XCTUnwrap((second["logical_memory"] as? String).flatMap { Data(base64Encoded: $0) })
XCTAssertEqual(secondMemory[0x5000], 0x11, "A executed its own guest STA before loading B")
try await stop("a-entry", request: "owner-a-again")
let third = try await captured(fixture.a, witness: 0xa1)
XCTAssertEqual(third["residency_fingerprint"] as? String, firstResidency)
let thirdMemory = try XCTUnwrap((third["logical_memory"] as? String).flatMap { Data(base64Encoded: $0) })
XCTAssertEqual(thirdMemory[0x5000], 0x22, "B executed its own guest STA before restoring A")
let restarted = try await test.reply("restart_playtest", arguments: ["run_id": test.runID, "request_id": "restart"])
XCTAssertEqual(restarted["boot"] as? Int, 2)
XCTAssertEqual(restarted["disk_sha256"] as? String, test.startReceipt["disk_sha256"] as? String)
XCTAssertEqual(restarted["disk_original_sha256"] as? String, CMOCProject.sha256(fixture.disk))
_ = try await captured(fixture.a, witness: 0xa1)
let stopped = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "stop"])
XCTAssertEqual(stopped["disk_retained"] as? Bool, true)
let saved = try XCTUnwrap(test.retainedDiskURL)
XCTAssertEqual(CMOCProject.sha256(try Data(contentsOf: saved)), restarted["disk_sha256"] as? String)
}
}
func testPhysicalCodeOverlayWorkerRejectsPartialAndCorruptedOwnerWitnessesOnBothProcessors() async throws {
let (helper, system, diskROM) = try inputs()
let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCPhysicalOverlayPartial-" + UUID().uuidString)
defer { try? FileManager.default.removeItem(at: root) }
for cpu in ["6809", "6309"] {
for (name, mode, witness) in [("partial", PhysicalOverlayLoad.partial, UInt8(0xa1)), ("corrupted", .corrupted, UInt8(0xc3))] {
let fixture = try physicalOverlayFixture(mode)
let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: fixture.disk,
bootCommands: "LOADM\"PROBE\":EXEC\n", projectID: "physical-overlay-invalid-worker", revision: 1,
artifactID: UUID().uuidString, modules: fixture.modules, stopAt: 0x4000, stopModule: "a-entry",
cpu: cpu, helperURL: helper, retentionDirectory: root.appendingPathComponent(cpu + "-" + name))
defer { test.invalidate() }
let valid = try await test.debugCapture()
XCTAssertEqual(valid["attached"] as? Bool, true)
_ = try await test.reply("playtest_debug", arguments: ["run_id": test.runID, "request_id": "want-b",
"action": "stop_at", "address": 0x4000, "module_id": "b-entry", "selection": "function_entry:b-entry"])
let advanced = try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": "load-invalid",
"steps": [["keys": [], "fields": 2]]])
XCTAssertEqual(advanced["state"] as? String, "running", "An invalid owner must not qualify B's stop")
_ = try await test.reply("playtest_debug", arguments: ["run_id": test.runID, "request_id": "pause", "action": "pause"])
let invalid = try await test.debugCapture()
assertProcessor(invalid, cpu: cpu)
XCTAssertEqual(invalid["attached"] as? Bool, false)
XCTAssertEqual(invalid["mapping_fingerprint"] as? String, valid["mapping_fingerprint"] as? String)
XCTAssertNotEqual(invalid["residency_fingerprint"] as? String, valid["residency_fingerprint"] as? String)
let pc = try XCTUnwrap(invalid["pc"] as? Int)
XCTAssertTrue((0x4000..<0x4008).contains(pc), "Pause observes the actual guest loop, not a manufactured PC")
let memory = try XCTUnwrap((invalid["logical_memory"] as? String).flatMap { Data(base64Encoded: $0) })
XCTAssertEqual(Data(memory[0x4000..<(0x4000 + fixture.b.count)]), fixture.b, "B's entry alone is insufficient proof")
XCTAssertEqual(memory[0x4022], witness, "The guest partial copy/corruption must remain visible in the full capture")
XCTAssertEqual(memory[0x5000], 0x22)
_ = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "stop"])
}
}
}
func testPhysicalOverlayWireRejectsEmbeddedNULIdentityBeforeGuestExecution() async throws {
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 fixture = try physicalOverlayFixture(.complete)
let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCOverlayWire-" + UUID().uuidString)
defer { try? FileManager.default.removeItem(at: root) }
for field in ["overlay_group", "overlay_owner"] {
var modules = fixture.modules
modules[0][field] = "a\0alias"
do {
// These deliberately unusable ROM bytes must never execute.
// This is a wire validation check, not a firmware/CPU pass.
let run = try await MCPPlaytest.start(systemROM: Data(repeating: 0, count: 32768),
diskROM: Data(repeating: 0, count: 8192), disk: fixture.disk, bootCommands: "\n",
projectID: "overlay-wire-invalid", revision: 1, artifactID: UUID().uuidString,
modules: modules, stopAt: 0x4000, stopModule: "a-entry", cpu: "6809", helperURL: helper,
retentionDirectory: root.appendingPathComponent(field))
await run.invalidate().value
XCTFail("An embedded NUL in \(field) crossed the worker boundary")
} catch {
XCTAssertTrue(error.localizedDescription.contains("invalid_overlay_identity"), error.localizedDescription)
}
}
}
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")) }
}
func testOwnedMultipleDrivesReadBothWriteOnlyHomeAndRetainIndependentlyOnBothProcessors() async throws {
let (helper, system, diskROM) = try inputs()
for cpu in ["6809", "6309"] {
for homeDrive in 0...2 {
let dataDrive = homeDrive + 1
let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCMultiDrive-" + UUID().uuidString)
defer { try? FileManager.default.removeItem(at: root) }
var home = disk(), data = disk()
home.replaceSubrange(0..<4, with: Data("HOME".utf8))
data.replaceSubrange(0..<4, with: Data("DATA".utf8))
let declaration = declaredMedia(artifact: UUID().uuidString, project: "multi-drive-\(cpu)-\(homeDrive)", primary: home, world: data)
// DSKI$ returns two 128-byte strings per sector. Reserve a
// normal BASIC string heap for both disks and the save buffers.
let source = "CLEAR2000\n5 H=\(homeDrive):D=\(dataDrive)\n10 IFINKEY$=\"\"THEN10\n20 DSKI$H,0,1,A$,B$:DSKI$D,0,1,C$,E$:PRINTLEFT$(A$,4);\":\";LEFT$(C$,4)\n30 A$=\"SAVE\"+STRING$(124,88):B$=STRING$(128,89):DSKO$H,0,2,A$,B$:DSKI$H,0,2,A$,B$:PRINTLEFT$(A$,4):GOTO10\nRUN\n"
let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: home,
bootCommands: source, projectID: "multi-drive-\(cpu)-\(homeDrive)", revision: 1,
artifactID: declaration.proof.artifactID!, cpu: cpu, helperURL: helper,
retentionDirectory: root, diskProvenance: declaration.proof, media: declaration.media, multiDrive: true)
defer { test.invalidate() }
_ = try await test.pausePlaytest()
func exchange(_ drive: Int, _ id: String?, _ hash: String?, _ requestID: String, protection: Bool? = nil) async throws -> [String: Any] {
var request: [String: Any] = ["run_id": test.runID, "request_id": requestID, "action": id == nil ? "eject" : "insert", "drive": drive]
if let id { request["media_id"] = id; request["media_sha256"] = hash }
if let protection { request["write_protected"] = protection }
return try await test.reply("exchange_playtest_media", arguments: request)
}
let before = try await test.capture()
XCTAssertEqual((before["drives"] as? [[String: Any]])?.count, 4)
for invalid: Any in [true, 1.5, -1, 4, "1"] {
await expectDiskFailure {
_ = try await test.reply("exchange_playtest_media", arguments: ["run_id": test.runID, "request_id": "invalid-drive", "action": "eject", "drive": invalid])
}
}
for invalid: Any in [1, "true"] {
await expectDiskFailure {
_ = try await test.reply("exchange_playtest_media", arguments: ["run_id": test.runID, "request_id": "invalid-protection", "action": "insert", "drive": dataDrive,
"media_id": declaration.media[1].id, "media_sha256": declaration.media[1].baseSHA256, "write_protected": invalid])
}
}
await expectDiskFailure {
_ = try await exchange(dataDrive, declaration.media[0].id, declaration.media[0].baseSHA256, "duplicate-mount")
}
if homeDrive != 0 {
_ = try await exchange(0, nil, nil, "eject-home")
_ = try await exchange(homeDrive, declaration.media[0].id, declaration.media[0].baseSHA256, "move-home")
}
let inserted = try await exchange(dataDrive, declaration.media[1].id, declaration.media[1].baseSHA256, "data", protection: true)
let insertedRows = try XCTUnwrap(inserted["drives"] as? [[String: Any]])
XCTAssertEqual(insertedRows[dataDrive]["write_protected"] as? Bool, true)
XCTAssertEqual(insertedRows[homeDrive]["write_protected"] as? Bool, false)
XCTAssertEqual(inserted["field_clock"] as? Int, before["field_clock"] as? Int)
XCTAssertEqual(inserted["target_drive"] as? Int, dataDrive)
XCTAssertEqual(inserted["media_id"] as? String, homeDrive == 0 ? declaration.media[0].id : nil)
let retry = try await exchange(dataDrive, declaration.media[1].id, declaration.media[1].baseSHA256, "data", protection: true)
XCTAssertEqual(inserted as NSDictionary, retry as NSDictionary)
await expectDiskFailure { _ = try await exchange(homeDrive, declaration.media[1].id, declaration.media[1].baseSHA256, "data", protection: true) }
await expectDiskFailure { _ = try await exchange(dataDrive, declaration.media[1].id, declaration.media[1].baseSHA256, "data", protection: false) }
_ = try await test.continuePlaytest()
_ = try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": "read-and-save", "steps": [["keys": ["r"], "fields": 18], ["keys": [], "fields": 420]]])
_ = try await test.pausePlaytest()
let saved = try await test.capture()
let text = saved["screen_text"] as? String ?? ""
XCTAssertTrue(text.contains("HOME:DATA"), text)
XCTAssertTrue(text.contains("SAVE"), text)
let rows = try XCTUnwrap(saved["drives"] as? [[String: Any]])
XCTAssertGreaterThan((rows[homeDrive]["disk_reads"] as? Int) ?? 0, 0)
XCTAssertGreaterThan((rows[homeDrive]["disk_writes"] as? Int) ?? 0, 0)
XCTAssertGreaterThan((rows[dataDrive]["disk_reads"] as? Int) ?? 0, 0)
XCTAssertEqual(rows[dataDrive]["disk_writes"] as? Int, 0)
XCTAssertEqual(rows[dataDrive]["disk_sha256"] as? String, CMOCProject.sha256(data))
XCTAssertNotEqual(rows[homeDrive]["disk_sha256"] as? String, CMOCProject.sha256(home))
let restarted = try await test.reply("restart_playtest", arguments: ["run_id": test.runID, "request_id": "restart-all"])
let restartedRows = try XCTUnwrap(restarted["drives"] as? [[String: Any]])
for drive in 0..<4 {
XCTAssertEqual(restartedRows[drive]["media_id"] as? String, rows[drive]["media_id"] as? String)
XCTAssertEqual(restartedRows[drive]["disk_sha256"] as? String, rows[drive]["disk_sha256"] as? String)
XCTAssertEqual(restartedRows[drive]["write_protected"] as? Bool, rows[drive]["write_protected"] as? Bool)
}
let stopArgs: [String: Any] = ["run_id": test.runID, "request_id": "stop"]
let stopped = try await test.reply("stop_playtest", arguments: stopArgs)
let repeated = try await test.reply("stop_playtest", arguments: stopArgs)
XCTAssertEqual(stopped as NSDictionary, repeated as NSDictionary)
let retained = try XCTUnwrap(stopped["retained_media"] as? [[String: Any]])
XCTAssertEqual(retained.count, 2)
XCTAssertEqual(Set(retained.compactMap { $0["retained_disk_id"] as? String }).count, 2)
for (index, medium) in declaration.media.enumerated() {
let record = try XCTUnwrap(retained.first { $0["media_id"] as? String == medium.id })
let id = try XCTUnwrap(record["retained_disk_id"] as? String), hash = try XCTUnwrap(record["disk_sha256"] as? String)
let loaded = try await MCPPlaytestDiskStore.load(directory: root, id: id, expectedSHA256: hash,
projectKey: declaration.key, artifactDiskSHA256: declaration.proof.artifactDiskSHA256!,
mediaKey: medium.key, mediaBaseSHA256: medium.baseSHA256)
XCTAssertEqual(loaded.record.provenance.writeProtected, index == 1)
if index == 1 { XCTAssertEqual(loaded.data, data) }
else { XCTAssertEqual(String(decoding: loaded.data[256..<260], as: UTF8.self), "SAVE") }
}
}
}
}
func testMultiDriveDefaultFD0RetryIdentityAndIndependentEqualByteCopies() async throws {
let (helper, system, diskROM) = try inputs()
let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCMultiIdentity-" + UUID().uuidString)
defer { try? FileManager.default.removeItem(at: root) }
let original = disk(), declaration = declaredMedia(artifact: UUID().uuidString, project: "multi-identity", primary: original, world: original)
let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: original,
bootCommands: "10 GOTO10\nRUN\n", projectID: "multi-identity", revision: 1,
artifactID: declaration.proof.artifactID!, helperURL: helper, retentionDirectory: root,
diskProvenance: declaration.proof, media: declaration.media, multiDrive: true)
defer { test.invalidate() }
_ = try await test.pausePlaytest()
let omitted: [String: Any] = ["run_id": test.runID, "request_id": "default-eject", "action": "eject"]
let ejected = try await test.reply("exchange_playtest_media", arguments: omitted)
var explicit = omitted; explicit["drive"] = 0
let explicitRetry = try await test.reply("exchange_playtest_media", arguments: explicit)
XCTAssertEqual(explicitRetry as NSDictionary, ejected as NSDictionary)
for drive in 0...1 {
_ = try await test.reply("exchange_playtest_media", arguments: ["run_id": test.runID, "request_id": "insert-\(drive)", "action": "insert", "drive": drive,
"media_id": declaration.media[drive].id, "media_sha256": declaration.media[drive].baseSHA256])
}
let snapshot = try await test.capture()
let rows = try XCTUnwrap(snapshot["drives"] as? [[String: Any]])
XCTAssertNotEqual(rows[0]["media_id"] as? String, rows[1]["media_id"] as? String)
XCTAssertEqual(rows[0]["disk_sha256"] as? String, rows[1]["disk_sha256"] as? String)
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)
}
func testMultiDriveStopDrainsFourLargeDisksWithinTheExistingWireLimit() async throws {
let (helper, system, diskROM) = try inputs()
let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCFourDriveDrain-" + UUID().uuidString)
defer { try? FileManager.default.removeItem(at: root) }
let artifact = UUID().uuidString, project = "four-drive-drain", projectKey = CMOCProject.sha256(Data(project.utf8))
let base = disk(), primaryHash = CMOCProject.sha256(base)
let media = (0..<4).map { index -> MCPPlaytestMedium in
// 80-track single-sided raw images are valid and fit the per-image
// budget. Four base64 payloads would exceed the 1 MiB wire bound.
var bytes = index == 0 ? base : Data(repeating: UInt8(40 + index), count: 80 * 18 * 256)
bytes[0] = UInt8(index)
let key = index == 0 ? "primary" : "disk:drive\(index).dsk", hash = CMOCProject.sha256(bytes)
let proof = MCPPlaytestDiskStore.Provenance(projectKey: projectKey, artifactID: artifact,
artifactDiskSHA256: primaryHash, mediaKey: key, mediaBaseSHA256: hash)
return MCPPlaytestMedium(id: MCPPlaytestMedium.identifier(artifactID: artifact, key: key), name: "drive\(index).dsk",
key: key, baseSHA256: hash, data: bytes, provenance: proof)
}
// Keep primary hash and actual bytes identical for artifact binding.
let primary = media[0]
let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: primary.data,
bootCommands: "10 GOTO10\nRUN\n", projectID: project, revision: 1, artifactID: artifact,
helperURL: helper, retentionDirectory: root, diskProvenance: primary.provenance, media: media, multiDrive: true)
defer { test.invalidate() }
_ = try await test.pausePlaytest()
for drive in 1...3 {
_ = try await test.reply("exchange_playtest_media", arguments: ["run_id": test.runID, "request_id": "drive-\(drive)", "action": "insert", "drive": drive,
"media_id": media[drive].id, "media_sha256": media[drive].baseSHA256])
}
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]])
XCTAssertEqual(records.count, 4)
for medium in media {
let record = try XCTUnwrap(records.first { $0["media_id"] as? String == medium.id })
XCTAssertEqual(record["disk_sha256"] as? String, medium.baseSHA256)
let id = try XCTUnwrap(record["retained_disk_id"] as? String)
XCTAssertEqual(try Data(contentsOf: MCPPlaytestDiskStore.diskURL(directory: root, id: id)), medium.data)
}
}
func testMultiDriveRetentionCanRetryAfterFrozenWorkerExit() async throws {
let (helper, system, diskROM) = try inputs()
let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCMultiRetentionRetry-" + 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 folder".utf8).write(to: blocked)
let original = disk(); var data = disk(); data[0] = 81
let declaration = declaredMedia(artifact: UUID().uuidString, project: "multi-retention-retry", primary: original, world: data)
let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: original,
bootCommands: "10 PRINT 47\nSAVE\"HOME\"\n", projectID: "multi-retention-retry", revision: 1,
artifactID: declaration.proof.artifactID!, helperURL: helper, retentionDirectory: blocked,
diskProvenance: declaration.proof, media: declaration.media, multiDrive: true)
defer { test.invalidate() }
_ = try await test.pausePlaytest()
_ = try await test.reply("exchange_playtest_media", arguments: ["run_id": test.runID, "request_id": "data", "action": "insert", "drive": 1,
"media_id": declaration.media[1].id, "media_sha256": declaration.media[1].baseSHA256])
let before = try await test.capture()
let beforeRows = try XCTUnwrap(before["drives"] as? [[String: Any]])
let stop: [String: Any] = ["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)
XCTAssertNil(test.retentionError)
let records = try XCTUnwrap(stopped["retained_media"] as? [[String: Any]])
XCTAssertEqual(records.count, 2)
for index in 0...1 {
let record = try XCTUnwrap(records.first { $0["media_id"] as? String == declaration.media[index].id })
XCTAssertEqual(record["disk_sha256"] as? String, beforeRows[index]["disk_sha256"] as? String)
}
}
func testOwnedDriveProtectionBlocksGuestWriteAndCanBeChangedWithReview() async throws {
let (helper, system, diskROM) = try inputs()
for cpu in ["6809", "6309"] {
let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCOwnedWriteProtect-" + UUID().uuidString)
defer { try? FileManager.default.removeItem(at: root) }
let original = disk(), declaration = declaredMedia(artifact: UUID().uuidString, project: "protected-" + cpu, primary: original, world: original)
let program = "CLEAR2000\n10 IFINKEY$=\"\"THEN10\n20 A$=STRING$(128,88):B$=STRING$(128,89):DSKO$0,0,2,A$,B$:PRINT\"WROTE HOME\":GOTO10\nRUN\n"
let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: original,
bootCommands: program, projectID: "protected-" + cpu, revision: 1, artifactID: declaration.proof.artifactID!, cpu: cpu,
helperURL: helper, retentionDirectory: root, diskProvenance: declaration.proof, media: declaration.media, multiDrive: true)
defer { test.invalidate() }
_ = try await test.pausePlaytest()
_ = try await test.reply("exchange_playtest_media", arguments: ["run_id": test.runID, "request_id": "protect", "action": "insert",
"media_id": declaration.media[0].id, "media_sha256": declaration.media[0].baseSHA256, "write_protected": true])
_ = try await test.continuePlaytest()
_ = try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": "protected-write",
"steps": [["keys": ["r"], "fields": 18], ["keys": [], "fields": 180]]])
_ = try await test.pausePlaytest()
let refused = try await test.capture()
let rows = try XCTUnwrap(refused["drives"] as? [[String: Any]])
XCTAssertEqual(rows[0]["disk_sha256"] as? String, declaration.media[0].baseSHA256)
XCTAssertEqual(rows[0]["disk_writes"] as? Int, 0)
XCTAssertTrue((refused["screen_text"] as? String ?? "").contains("WP ERROR"), refused["screen_text"] as? String ?? "")
_ = try await test.reply("exchange_playtest_media", arguments: ["run_id": test.runID, "request_id": "unprotect", "action": "insert", "drive": 0,
"media_id": declaration.media[0].id, "media_sha256": declaration.media[0].baseSHA256, "write_protected": false])
_ = try await test.reply("restart_playtest", arguments: ["run_id": test.runID, "request_id": "restart"])
_ = try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": "writable-write",
"steps": [["keys": ["r"], "fields": 18], ["keys": [], "fields": 240]]])
_ = try await test.pausePlaytest()
let written = try await test.capture()
let writtenRows = try XCTUnwrap(written["drives"] as? [[String: Any]])
XCTAssertGreaterThan(writtenRows[0]["disk_writes"] as? Int ?? 0, 0)
XCTAssertNotEqual(writtenRows[0]["disk_sha256"] as? String, declaration.media[0].baseSHA256)
XCTAssertTrue((written["screen_text"] as? String ?? "").contains("WROTE HOME"))
_ = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "stop"])
}
}
func testMultiDriveExchangeChecksSharedControllerAndMalformedDriveBeforeMutation() async throws {
let (helper, system, diskROM) = try inputs()
for cpu in ["6809", "6309"] {
let worker = try MediaWorkerClient(helper); defer { worker.close() }
// Real guest selects FD0 and starts a read with motor disabled;
// even an otherwise empty FD3 must refuse its own exchange.
let commands = try CocoPaste("POKE65344,1:POKE65352,128\n", mode: .text)
_ = try await worker.request(["op": "init", "system_rom": system.base64EncodedString(), "disk_rom": diskROM.base64EncodedString(),
"disk": disk().base64EncodedString(), "boot_keys": commands.chords.map { NSNumber(value: $0) }, "cpu": cpu, "multi_drive": true])
_ = try await worker.request(["op": "pause"])
let before = try await worker.request(["op": "media_status"])
XCTAssertEqual(before["floppy_busy"] as? Bool, true)
for drive: Any in [true, 1.25, -1, 4] {
await expectDiskFailure {
_ = try await worker.request(["op": "exchange_media", "drive": drive, "expected_media_generation": 0, "expected_disk_sha256": ""])
}
}
do {
_ = try await worker.request(["op": "exchange_media", "drive": 3, "expected_media_generation": 0, "expected_disk_sha256": ""])
XCTFail("A pending FD0 command must block FD3 replacement")
} catch { XCTAssertTrue(error.localizedDescription.contains("playtest_media_busy")) }
let after = try await worker.request(["op": "media_status"])
XCTAssertEqual(before["drives"] as? NSArray, after["drives"] as? NSArray)
for key in ["field_clock", "cycles", "generation", "pc", "boot"] { XCTAssertEqual(before[key] as? NSNumber, after[key] as? NSNumber) }
let frozen = try await worker.request(["op": "stop"])
XCTAssertEqual(frozen["media_frozen"] as? Bool, true)
for drive in 0..<4 { _ = try await worker.request(["op": "export_media", "drive": drive]) }
_ = try await worker.request(["op": "finish_stop"])
}
}
/// These are bounded negative protocol fixtures, not emulator evidence.
/// Actual guest I/O is covered by the independent both-CPU tests above.
private func faultingMultiDriveHelper(_ mode: String, root: URL) throws -> URL {
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
let path = root.appendingPathComponent("multi-wire-fixture")
let source = """
#!/usr/bin/env python3
import sys,json,base64,hashlib,os
mode=\(String(reflecting: mode))
disks=[None]*4; ids=[None]*4; gens=[0]*4; protections=[False]*4; originals=['']*4
cpu='6809'; frozen=False; failed_export=False
def digest(data): return hashlib.sha256(data).hexdigest() if data else ''
def row(drive):
data=disks[drive]
return {'drive':drive,'label':'FD'+str(drive),'inserted':data is not None,'disk_present':data is not None,
'media_id':ids[drive],'disk_original_sha256':originals[drive],'disk_sha256':digest(data),
'media_generation':gens[drive],'byte_count':len(data) if data else 0,'disk_dirty':False,
'write_protected':protections[drive],'disk_reads':0,'disk_writes':0,'mount_read_bytes':0,'mount_write_bytes':0}
def status():
first=row(0)
return {'cpu':cpu,'processor':'HD6309' if cpu=='6309' else 'MC6809','state':'paused',
'media_id':first['media_id'],'disk_present':first['disk_present'],'disk_sha256':first['disk_sha256'],
'disk_original_sha256':first['disk_original_sha256'],'media_generation':gens[0],
'disk_dirty':False,'floppy_busy':False,'field_clock':0,'cycles':100,'generation':1,'boot':1,'pc':100,
'drives':[row(d) for d in range(4)]}
for line in sys.stdin:
r=json.loads(line); op=r['op']; end=False
with open(os.path.join(os.path.dirname(__file__),'trace.jsonl'),'a') as trace: trace.write(json.dumps(r)+'\\n')
if op=='init':
disks[0]=base64.b64decode(r['disk']); ids[0]=r['media_id']; cpu=r['cpu']; originals[0]=digest(disks[0]); out=status()
elif op=='export_media':
drive=r['drive']
if mode=='partial-stop' and frozen and drive==2 and not os.path.exists(os.path.join(os.path.dirname(__file__),'retry')):
print(json.dumps({'error':'fixture_partial_drain'}),flush=True); continue
out=status(); out['exported_drive']=row(drive)
if disks[drive] is not None: out['disk_base64']=base64.b64encode(disks[drive]).decode()
if mode=='wrong-target' and not frozen and drive==1 and not failed_export:
out['exported_drive']['media_id']='foreign'; failed_export=True
elif op in ('media_status','capture','pause'): out=status()
elif op=='exchange_media':
drive=r['drive']; old=digest(disks[drive]); ids[drive]=r.get('media_id')
disks[drive]=base64.b64decode(r['disk_base64']) if ids[drive] else None
protections[drive]=r.get('write_protected',False); originals[drive]=digest(disks[drive]); gens[drive]+=1
if mode=='exit-after-commit': os._exit(0)
if mode=='mark-after-commit':
with open(os.path.join(os.path.dirname(__file__),'committed'),'w') as marker: marker.write('committed')
out=status(); out['previous_disk_sha256']=old; out['target_drive']=drive
elif op=='stop':
frozen=True; out=status(); out['media_frozen']=True
elif op=='finish_stop': out=status(); 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 testMultiDriveLostCommitRetainsAllFrozenCopiesAndMarksOnlyTargetUncertain() async throws {
let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCMultiLostReply-" + UUID().uuidString)
defer { try? FileManager.default.removeItem(at: root) }
let helper = try faultingMultiDriveHelper("exit-after-commit", root: root)
let original = disk(); var data = disk(); data[0] = 93
let declaration = declaredMedia(artifact: UUID().uuidString, project: "multi-lost", primary: original, world: data)
let test = try await MCPPlaytest.start(systemROM: Data(repeating: 0, count: 32768), diskROM: Data(repeating: 0, count: 8192), disk: original,
bootCommands: "PRINT1\n", projectID: "multi-lost", revision: 1, artifactID: declaration.proof.artifactID!, helperURL: helper,
retentionDirectory: root.appendingPathComponent("retained"), diskProvenance: declaration.proof, media: declaration.media, multiDrive: true)
await expectDiskFailure {
_ = try await test.reply("exchange_playtest_media", arguments: ["run_id": test.runID,"request_id":"lost","action":"insert","drive":1,
"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)
XCTAssertEqual(receipt["uncertain_drives"] as? [Int], [1])
let drives = try XCTUnwrap(receipt["drives"] as? [[String: Any]])
XCTAssertEqual(drives[0]["media_id"] as? String, declaration.media[0].id)
XCTAssertTrue(drives[1]["media_id"] is NSNull)
let retained = try XCTUnwrap(receipt["retained_media"] as? [[String: Any]])
XCTAssertEqual(retained.count, 2)
for medium in declaration.media {
let row = try XCTUnwrap(retained.first { $0["media_id"] as? String == medium.id })
XCTAssertEqual(row["disk_sha256"] as? String, medium.baseSHA256)
}
}
func testMultiDrivePartialDrainRetriesWithoutASecondStopOrRepeatedEarlierExport() async throws {
let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCMultiPartialDrain-" + UUID().uuidString)
defer { try? FileManager.default.removeItem(at: root) }
let helper = try faultingMultiDriveHelper("partial-stop", root: root)
let original = disk(), declaration = declaredMedia(artifact: UUID().uuidString, project: "multi-partial", primary: original, world: original)
let test = try await MCPPlaytest.start(systemROM: Data(repeating: 0, count: 32768), diskROM: Data(repeating: 0, count: 8192), disk: original,
bootCommands: "PRINT1\n", projectID: "multi-partial", revision: 1, artifactID: declaration.proof.artifactID!, helperURL: helper,
retentionDirectory: root.appendingPathComponent("retained"), diskProvenance: declaration.proof, media: declaration.media, multiDrive: true)
defer { test.invalidate() }
let stop: [String: Any] = ["run_id":test.runID,"request_id":"stop"]
await expectDiskFailure { _ = try await test.reply("stop_playtest", arguments: stop) }
XCTAssertNotNil(test.retentionError)
try Data("retry".utf8).write(to: root.appendingPathComponent("retry"))
let stopped = try await test.reply("stop_playtest", arguments: stop)
XCTAssertEqual(stopped["disk_retained"] as? Bool, true)
let trace = try String(contentsOf: root.appendingPathComponent("trace.jsonl"), encoding: .utf8).split(separator:"\n").map {
try XCTUnwrap(JSONSerialization.jsonObject(with: Data($0.utf8)) as? [String: Any])
}
XCTAssertEqual(trace.filter { $0["op"] as? String == "stop" }.count, 1)
for drive in 0...1 { XCTAssertEqual(trace.filter { $0["op"] as? String == "export_media" && $0["drive"] as? Int == drive }.count, 1) }
XCTAssertEqual(trace.filter { $0["op"] as? String == "export_media" && $0["drive"] as? Int == 2 }.count, 2)
}
func testMultiDriveWrongExportTargetCannotPoisonAnotherMedium() async throws {
let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCMultiWrongExport-" + UUID().uuidString)
defer { try? FileManager.default.removeItem(at: root) }
let helper = try faultingMultiDriveHelper("wrong-target", root: root)
let original = disk(); var data = disk(); data[0] = 95
let declaration = declaredMedia(artifact: UUID().uuidString, project: "multi-wrong", primary: original, world: data)
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: "PRINT1\n", projectID: "multi-wrong", revision: 1, artifactID: declaration.proof.artifactID!, helperURL: helper,
retentionDirectory: store, diskProvenance: declaration.proof, media: declaration.media, multiDrive: true)
defer { test.invalidate() }
await expectDiskFailure {
_ = try await test.reply("exchange_playtest_media", arguments: ["run_id":test.runID,"request_id":"wrong","action":"insert","drive":1,
"media_id":declaration.media[1].id,"media_sha256":declaration.media[1].baseSHA256])
}
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]])
for medium in declaration.media {
let record = try XCTUnwrap(records.first { $0["media_id"] as? String == medium.id })
let id = try XCTUnwrap(record["retained_disk_id"] as? String)
XCTAssertEqual(try Data(contentsOf: MCPPlaytestDiskStore.diskURL(directory: store,id:id)), medium.data)
}
}
func testMultiDriveRechecksRetainedOutgoingBytesBeforeAnotherReplacement() async throws {
let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCMultiRetentionEvidence-" + UUID().uuidString)
defer { try? FileManager.default.removeItem(at: root) }
let helper = try faultingMultiDriveHelper("normal", root: root)
let original = disk(); var data = disk(); data[0] = 97
let declaration = declaredMedia(artifact: UUID().uuidString, project: "multi-retained-evidence", primary: original, world: data)
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: "PRINT1\n", projectID: "multi-retained-evidence", revision: 1, artifactID: declaration.proof.artifactID!, helperURL: helper,
retentionDirectory: store, diskProvenance: declaration.proof, media: declaration.media, multiDrive: true)
defer { test.invalidate() }
let eject = try await test.reply("exchange_playtest_media", arguments: ["run_id":test.runID,"request_id":"eject","action":"eject"])
let previous = try XCTUnwrap(eject["previous_media"] as? [String: Any])
let retained = try XCTUnwrap(previous["retained_disk"] as? [String: Any])
let retainedID = try XCTUnwrap(retained["retained_disk_id"] as? String)
_ = try await test.reply("exchange_playtest_media", arguments: ["run_id":test.runID,"request_id":"restore","action":"insert",
"media_id":declaration.media[0].id,"media_sha256":declaration.media[0].baseSHA256])
let url = try MCPPlaytestDiskStore.diskURL(directory: store,id:retainedID)
try data.write(to: url)
await expectDiskFailure {
_ = try await test.reply("exchange_playtest_media", arguments: ["run_id":test.runID,"request_id":"changed-evidence","action":"insert",
"media_id":declaration.media[1].id,"media_sha256":declaration.media[1].baseSHA256])
}
let unchanged = try await test.capture()
XCTAssertEqual(unchanged["media_id"] as? String, declaration.media[0].id)
XCTAssertEqual(unchanged["disk_sha256"] as? String, declaration.media[0].baseSHA256)
XCTAssertEqual(try Data(contentsOf:url), data, "The failed swap must not silently repair changed retention evidence")
try original.write(to:url)
_ = try await test.reply("stop_playtest", arguments:["run_id":test.runID,"request_id":"stop"])
}
func testMultiDriveLateAuthorityLossPreservesAcknowledgedTargetReceipt() async throws {
let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCMultiLateAuthority-" + UUID().uuidString)
defer { try? FileManager.default.removeItem(at: root) }
let helper = try faultingMultiDriveHelper("mark-after-commit", root:root)
let original = disk(); var data = disk(); data[0] = 99
let declaration = declaredMedia(artifact: UUID().uuidString, project:"multi-late-authority", primary:original,world:data)
let test = try await MCPPlaytest.start(systemROM:Data(repeating:0,count:32768),diskROM:Data(repeating:0,count:8192),disk:original,
bootCommands:"PRINT1\n",projectID:"multi-late-authority",revision:1,artifactID:declaration.proof.artifactID!,helperURL:helper,
retentionDirectory:root.appendingPathComponent("retained"),diskProvenance:declaration.proof,media:declaration.media,multiDrive:true)
defer { test.invalidate() }
let request: [String:Any] = ["run_id":test.runID,"request_id":"commit","action":"insert","drive":1,"write_protected":true,
"media_id":declaration.media[1].id,"media_sha256":declaration.media[1].baseSHA256]
do {
_ = try await test.reply("exchange_playtest_media",arguments:request,isCurrent:{ !FileManager.default.fileExists(atPath:root.appendingPathComponent("committed").path) })
XCTFail("A committed exchange cannot return through expired authority")
} catch { XCTAssertTrue(error.localizedDescription.contains("stale_run_after_commit")) }
let acknowledged = try await test.reply("exchange_playtest_media",arguments:request)
XCTAssertEqual(acknowledged["target_drive"] as? Int,1)
let rows = try XCTUnwrap(acknowledged["drives"] as? [[String:Any]])
XCTAssertEqual(rows[1]["media_id"] as? String,declaration.media[1].id)
XCTAssertEqual(rows[1]["media_generation"] as? Int,1)
XCTAssertEqual(rows[1]["write_protected"] as? Bool,true)
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]])
XCTAssertEqual(records.first { $0["media_id"] as? String == declaration.media[1].id }?["write_protected"] as? Bool,true)
}
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)
}
}
}