Sync source edition with VCC Plus 3.7.0 build 63

This commit is contained in:
Brian Holman committed 2026-11-14 01:43:46 -07:00
1 parent c652a5276d
commit b2ecec4d87
86 files changed
+10519 -472

No files matched your search

+426 -1
View File
@@ -1,8 +1,225 @@
// 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)
@@ -551,7 +768,11 @@ final class MCPPlaytestTests: XCTestCase {
projectID: "request-limit-fixture", revision: 1, artifactID: UUID().uuidString,
helperURL: helper, retentionDirectory: folder)
defer { test.invalidate() }
for index in 0..<MCPPlaytest.mutationRequestLimit {
_ = try await test.reply("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()
@@ -560,6 +781,18 @@ final class MCPPlaytestTests: XCTestCase {
_ = 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)
@@ -886,6 +1119,198 @@ final class MCPPlaytestTests: XCTestCase {
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.