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.
This commit is contained in:
1 parent
4abc194001
commit
5534005799
54 files changed
+2950
-435
No files matched your search
@@ -16,8 +16,8 @@ final class AssemblyBuildServiceTests: XCTestCase {
|
||||
override func setUpWithError() throws {
|
||||
root = FileManager.default.temporaryDirectory.appendingPathComponent("Assembly tests " + UUID().uuidString)
|
||||
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
||||
runtime = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
|
||||
.appendingPathComponent("LocalResources/ToolchainBundle")
|
||||
runtime = vccQualificationToolchain(URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
|
||||
.appendingPathComponent("LocalResources/ToolchainBundle"))
|
||||
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: runtime.appendingPathComponent("bin/lwasm").path),
|
||||
"Stage the bundled LWTools runtime for assembly workflow tests.")
|
||||
}
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import XCTest
|
||||
import AppKit
|
||||
|
||||
/// The interpreter is the tokenizer oracle. Optional private ROMs never enter Git.
|
||||
@MainActor
|
||||
final class BASICBridgeTests: XCTestCase {
|
||||
override func setUp() async throws {
|
||||
try await super.setUp()
|
||||
await MainActor.run { _ = NSApplication.shared }
|
||||
}
|
||||
|
||||
private func command(_ body: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot {
|
||||
await withCheckedContinuation { continuation in body { continuation.resume(returning: $0) } }
|
||||
}
|
||||
@@ -184,7 +190,121 @@ final class BASICBridgeTests: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testReviewedBASICLoadRetriesOnlyPromptRefusalAndPreservesReviewAuthority() async throws {
|
||||
_ = NSApplication.shared
|
||||
let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
|
||||
let roms = mac.appendingPathComponent("LocalResources/ROMs")
|
||||
for file in ["coco3.rom", "disk11.rom"] {
|
||||
try XCTSkipUnless(FileManager.default.fileExists(atPath: roms.appendingPathComponent(file).path), "Stage private BASIC ROMs")
|
||||
}
|
||||
let suite = "ReviewedBASICRetry-" + UUID().uuidString
|
||||
let root = FileManager.default.temporaryDirectory.appendingPathComponent(suite)
|
||||
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
||||
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
|
||||
defer { defaults.removePersistentDomain(forName: suite); try? FileManager.default.removeItem(at: root) }
|
||||
let controller = VCCMachineController()
|
||||
let machine = MachineModel(diskStore: .init(url: root.appendingPathComponent("drives.json")), controller: controller,
|
||||
displayDefaults: defaults, inputStore: .init(url: root.appendingPathComponent("input.json")))
|
||||
do {
|
||||
for _ in 0..<300 where machine.busy { try await Task.sleep(for: .milliseconds(20)) }
|
||||
for use6309 in [false, true] {
|
||||
try await MCPBASICRun.bootFixture(machine, romDirectory: roms, use6309: use6309)
|
||||
let emptySource = await machine.readBASICSource()
|
||||
let existing = try XCTUnwrap(emptySource)
|
||||
let initial = await machine.mcpMachineSnapshot()
|
||||
// Held Shift deterministically causes the exact read-only core
|
||||
// refusal. Release only when approval is checked after that
|
||||
// refused attempt and its retry wait, never before dispatch.
|
||||
controller.setKeyboardMask(CocoKeyboard.shift)
|
||||
var approvalChecks = 0
|
||||
let loaded = await machine.loadBASICSource("10 GOTO 10\n", run: true,
|
||||
review: (initial, existing), reviewIsCurrent: {
|
||||
approvalChecks += 1
|
||||
if approvalChecks == 2 { controller.setKeyboardMask(0) }
|
||||
return true
|
||||
})
|
||||
XCTAssertGreaterThanOrEqual(approvalChecks, 2)
|
||||
let started = try XCTUnwrap(loaded, machine.fileError ?? "Reviewed retry failed")
|
||||
XCTAssertEqual(started.generation, initial.generation)
|
||||
XCTAssertEqual(started.debuggerProgramRevision, initial.debuggerProgramRevision + 1,
|
||||
"Only the successful queue transaction may install the program")
|
||||
try await settle(controller)
|
||||
let source = await machine.readBASICSource()
|
||||
let runningSource = try XCTUnwrap(source)
|
||||
let expected = await machine.mcpMachineSnapshot()
|
||||
let original = try await programBytes(controller)
|
||||
let replacement = "10 PRINT 99\n"
|
||||
|
||||
var staleChecks = 0
|
||||
let stale = await machine.loadBASICSource(replacement, run: true, review: (initial, runningSource),
|
||||
reviewIsCurrent: { staleChecks += 1; return true })
|
||||
XCTAssertNil(stale); XCTAssertEqual(staleChecks, 1)
|
||||
XCTAssertEqual(machine.fileError, "The CoCo or its loaded program changed. Start a new reviewed run.")
|
||||
|
||||
var sourceChecks = 0
|
||||
let changedSource = await machine.loadBASICSource(replacement, run: true,
|
||||
review: (expected, runningSource + "20 REM NOT REVIEWED\n"),
|
||||
reviewIsCurrent: { sourceChecks += 1; return true })
|
||||
XCTAssertNil(changedSource); XCTAssertEqual(sourceChecks, 1)
|
||||
XCTAssertEqual(machine.fileError, "The program in BASIC memory changed. Review it before continuing.")
|
||||
|
||||
var revokedChecks = 0
|
||||
let revoked = await machine.loadBASICSource(replacement, run: true, review: (expected, runningSource),
|
||||
reviewIsCurrent: { revokedChecks += 1; return revokedChecks == 1 })
|
||||
XCTAssertNil(revoked); XCTAssertEqual(revokedChecks, 2)
|
||||
XCTAssertEqual(machine.fileError, "The approved revision or connection changed.")
|
||||
|
||||
var cancelledChecks = 0
|
||||
let cancelled = Task { @MainActor in
|
||||
await machine.loadBASICSource(replacement, run: true, review: (expected, runningSource),
|
||||
reviewIsCurrent: {
|
||||
cancelledChecks += 1
|
||||
if cancelledChecks == 2 { withUnsafeCurrentTask { $0?.cancel() } }
|
||||
return true
|
||||
})
|
||||
}
|
||||
let cancelledResult = await cancelled.value
|
||||
XCTAssertNil(cancelledResult); XCTAssertEqual(cancelledChecks, 2)
|
||||
XCTAssertEqual(machine.fileError, "The BASIC transfer was cancelled.")
|
||||
|
||||
var boundedChecks = 0
|
||||
let clock = ContinuousClock()
|
||||
let began = clock.now
|
||||
let bounded = await machine.loadBASICSource(replacement, run: true, review: (expected, runningSource),
|
||||
reviewIsCurrent: { boundedChecks += 1; return true })
|
||||
XCTAssertNil(bounded); XCTAssertGreaterThan(boundedChecks, 2)
|
||||
XCTAssertLessThan(clock.now - began, .seconds(3), "An executing program must not cause unbounded retry")
|
||||
XCTAssertEqual(machine.fileError, "Wait at the BASIC OK prompt before loading or running from the editor; use BREAK to stop the current program first")
|
||||
|
||||
controller.setKeyboardMask(CocoKeyboard.shift)
|
||||
let legacyBegan = clock.now
|
||||
let legacy = await machine.loadBASICSource(replacement, run: true, review: (expected, runningSource))
|
||||
controller.setKeyboardMask(0)
|
||||
XCTAssertNil(legacy)
|
||||
XCTAssertLessThan(clock.now - legacyBegan, .seconds(1), "A review tuple without live approval must remain a single attempt")
|
||||
XCTAssertEqual(machine.fileError, "Wait at the BASIC OK prompt before loading or running from the editor; use BREAK to stop the current program first")
|
||||
|
||||
var ordinaryChecks = 0
|
||||
let ordinary = await machine.loadBASICSource(replacement, run: true,
|
||||
reviewIsCurrent: { ordinaryChecks += 1; return true })
|
||||
XCTAssertNil(ordinary); XCTAssertEqual(ordinaryChecks, 0, "Ordinary loading remains a single unreviewed operation")
|
||||
let after = await machine.mcpMachineSnapshot()
|
||||
XCTAssertEqual(after.generation, expected.generation)
|
||||
XCTAssertEqual(after.debuggerProgramRevision, expected.debuggerProgramRevision)
|
||||
let preserved = try await programBytes(controller)
|
||||
XCTAssertEqual(preserved, original)
|
||||
XCTAssertEqual(after.disks.first?.name, expected.disks.first?.name)
|
||||
XCTAssertEqual(after.disks.first?.mounted, expected.disks.first?.mounted)
|
||||
}
|
||||
} catch {
|
||||
await withCheckedContinuation { done in machine.shutdown { done.resume() } }
|
||||
throw error
|
||||
}
|
||||
await withCheckedContinuation { done in machine.shutdown { done.resume() } }
|
||||
}
|
||||
|
||||
func testReviewedBASICRunChecksRealMenuColorsPromptAndStaleSource() async throws {
|
||||
_ = NSApplication.shared // This fixture also runs alone in Apple's hostless XCTest runner.
|
||||
let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
|
||||
let roms = mac.appendingPathComponent("LocalResources/ROMs")
|
||||
for file in ["coco3.rom", "disk11.rom"] {
|
||||
@@ -310,7 +430,7 @@ final class BASICBridgeTests: XCTestCase {
|
||||
|
||||
func testPlanetEditorStartersAcceptKeyboardAndReturnToBASIC() async throws {
|
||||
let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
|
||||
let tools = mac.appendingPathComponent("LocalResources/ToolchainBundle")
|
||||
let tools = vccQualificationToolchain(mac.appendingPathComponent("LocalResources/ToolchainBundle"))
|
||||
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: tools.appendingPathComponent("bin/lwasm").path))
|
||||
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: tools.appendingPathComponent("bin/cmoc").path))
|
||||
let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
@@ -377,7 +497,7 @@ final class BASICBridgeTests: XCTestCase {
|
||||
|
||||
func testExportedBootDisksRunByDOSAndByTheirManualCommands() async throws {
|
||||
let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
|
||||
let tools = mac.appendingPathComponent("LocalResources/ToolchainBundle")
|
||||
let tools = vccQualificationToolchain(mac.appendingPathComponent("LocalResources/ToolchainBundle"))
|
||||
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: tools.appendingPathComponent("bin/cmoc").path))
|
||||
let service = AssemblyBuildService(toolchain: tools)
|
||||
let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
@@ -440,7 +560,7 @@ final class BASICBridgeTests: XCTestCase {
|
||||
|
||||
func testAssembledProgramRunsInAllBASICPresetsAndFromDiskBASICExport() async throws {
|
||||
let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
|
||||
let tools = mac.appendingPathComponent("LocalResources/ToolchainBundle")
|
||||
let tools = vccQualificationToolchain(mac.appendingPathComponent("LocalResources/ToolchainBundle"))
|
||||
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: tools.appendingPathComponent("bin/lwasm").path),
|
||||
"Stage the local universal toolchain")
|
||||
let service = AssemblyBuildService(toolchain: tools)
|
||||
|
||||
@@ -3,6 +3,17 @@ import XCTest
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
|
||||
/// Explicit test-only input keeps compiler qualification away from normal app staging.
|
||||
/// Xcode forwards TEST_RUNNER_VCC_TEST_TOOLCHAIN_DIR to this environment variable.
|
||||
func vccQualificationToolchain(_ fallback: URL) -> URL {
|
||||
guard let path = ProcessInfo.processInfo.environment["VCC_TEST_TOOLCHAIN_DIR"] else { return fallback }
|
||||
XCTAssertTrue(path.hasPrefix("/"), "Compiler qualification requires an absolute runtime path")
|
||||
let candidate = URL(fileURLWithPath: path, isDirectory: true)
|
||||
XCTAssertTrue(FileManager.default.isExecutableFile(atPath: candidate.appendingPathComponent("bin/cmoc").path),
|
||||
"Explicit compiler qualification input is unavailable; do not silently use another runtime")
|
||||
return candidate
|
||||
}
|
||||
|
||||
final class CMOCBuildServiceTests: XCTestCase {
|
||||
private var folder: URL!
|
||||
override func setUpWithError() throws {
|
||||
@@ -146,8 +157,8 @@ final class CMOCBuildServiceTests: XCTestCase {
|
||||
}
|
||||
|
||||
func testAssistantBuildsOrdinarySourcesWithOnlyItsOwnRecipe() async throws {
|
||||
let runtime = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
|
||||
.appendingPathComponent("LocalResources/ToolchainBundle")
|
||||
let runtime = vccQualificationToolchain(URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
|
||||
.appendingPathComponent("LocalResources/ToolchainBundle"))
|
||||
guard FileManager.default.isExecutableFile(atPath: runtime.appendingPathComponent("bin/cmoc").path) else {
|
||||
throw XCTSkip("Stage the bundled CMOC tools")
|
||||
}
|
||||
@@ -609,7 +620,7 @@ final class CMOCBuildServiceTests: XCTestCase {
|
||||
}
|
||||
|
||||
func testRealBundledToolsExposeCompilerAssemblerLinkerAndMakeFailures() async throws {
|
||||
let runtime = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("LocalResources/ToolchainBundle")
|
||||
let runtime = vccQualificationToolchain(URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("LocalResources/ToolchainBundle"))
|
||||
try XCTSkipUnless(CMOCBuildService.requiredExecutables.allSatisfy {
|
||||
FileManager.default.isExecutableFile(atPath: runtime.appendingPathComponent("bin/" + $0).path)
|
||||
}, "Stage the bundled CMOC/LWTools/Make runtime")
|
||||
@@ -1205,7 +1216,7 @@ final class CMOCBuildServiceTests: XCTestCase {
|
||||
|
||||
func testBundledLibrariesBuildUnmodifiedCoCoLettersMakefile() async throws {
|
||||
let repo = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
|
||||
let runtime = repo.appendingPathComponent("platforms/macos/LocalResources/ToolchainBundle")
|
||||
let runtime = vccQualificationToolchain(repo.appendingPathComponent("platforms/macos/LocalResources/ToolchainBundle"))
|
||||
try XCTSkipUnless(FileManager.default.fileExists(atPath: runtime.appendingPathComponent("share/cmoc/lib/libdskcon-standalone.a").path), "Stage the optional standalone disk library")
|
||||
let root = folder.appendingPathComponent("CoCo Letters")
|
||||
try FileManager.default.copyItem(at: repo.appendingPathComponent("third_party/examples/coco-letters"), to: root)
|
||||
@@ -1418,7 +1429,7 @@ final class CMOCBuildServiceTests: XCTestCase {
|
||||
XCTAssertEqual(artifact.sources["main.c"], Data(CMOCProject.starterSource.utf8))
|
||||
}
|
||||
func testGeneratedMakefileBuildsMultipleCFilesDependenciesResourcesAndDiskWithBundledTools() async throws {
|
||||
let runtime = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("LocalResources/ToolchainBundle")
|
||||
let runtime = vccQualificationToolchain(URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("LocalResources/ToolchainBundle"))
|
||||
guard FileManager.default.isExecutableFile(atPath: runtime.appendingPathComponent("bin/perl").path) else { throw XCTSkip("Stage the complete bundled compiler and Perl runtime") }
|
||||
var generated = CMOCMakefileSettings()
|
||||
generated.sources = ["main.c", "src/game.c", "generated/data.c"]
|
||||
|
||||
@@ -18,7 +18,7 @@ final class CMOCCallStackIntegrationTests: XCTestCase {
|
||||
}
|
||||
private func fixture(optimized: Bool = false) async throws -> Fixture {
|
||||
let resources = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("LocalResources")
|
||||
let toolchain = resources.appendingPathComponent("ToolchainBundle")
|
||||
let toolchain = vccQualificationToolchain(resources.appendingPathComponent("ToolchainBundle"))
|
||||
let rom = resources.appendingPathComponent("ROMs/coco3.rom")
|
||||
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path)
|
||||
&& FileManager.default.fileExists(atPath: rom.path), "Local licensed CoCo ROM and staged toolchain are required")
|
||||
|
||||
@@ -131,7 +131,7 @@ final class CMOCDevelopmentTests: XCTestCase {
|
||||
}
|
||||
@MainActor func testCompiledEditedProgramStopsAtVerifiedCLineOnBothCPUs() async throws {
|
||||
let resources = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("LocalResources")
|
||||
let toolchain = resources.appendingPathComponent("ToolchainBundle")
|
||||
let toolchain = vccQualificationToolchain(resources.appendingPathComponent("ToolchainBundle"))
|
||||
let romURL = resources.appendingPathComponent("ROMs/coco3.rom")
|
||||
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path)
|
||||
&& FileManager.default.fileExists(atPath: romURL.path), "Local licensed CoCo ROM and staged toolchain are required")
|
||||
@@ -178,7 +178,7 @@ final class CMOCDevelopmentTests: XCTestCase {
|
||||
@MainActor private func checkDiskAPIRoundTrip(standalone: Bool) async throws {
|
||||
let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
|
||||
let resources = mac.appendingPathComponent("LocalResources")
|
||||
let toolchain = resources.appendingPathComponent("ToolchainBundle")
|
||||
let toolchain = vccQualificationToolchain(resources.appendingPathComponent("ToolchainBundle"))
|
||||
let romURL = resources.appendingPathComponent("ROMs/coco3.rom")
|
||||
let diskROMURL = resources.appendingPathComponent("ROMs/disk11.rom")
|
||||
try XCTSkipUnless(FileManager.default.fileExists(atPath: toolchain.appendingPathComponent("share/cmoc/lib/libdecbfile.a").path)
|
||||
@@ -321,9 +321,9 @@ final class CMOCDevelopmentTests: XCTestCase {
|
||||
}
|
||||
@MainActor func testCallerSelectionPreservesExecutionAndResetsOnStepOrStaleSource() async throws {
|
||||
let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
|
||||
let staged = mac.appendingPathComponent("LocalResources/ToolchainBundle")
|
||||
let staged = vccQualificationToolchain(mac.appendingPathComponent("LocalResources/ToolchainBundle"))
|
||||
let bundled = Bundle.main.resourceURL!.appendingPathComponent("Toolchain")
|
||||
let toolchain = FileManager.default.isExecutableFile(atPath: bundled.appendingPathComponent("bin/cmoc").path) ? bundled : staged
|
||||
let toolchain = vccQualificationToolchain(FileManager.default.isExecutableFile(atPath: bundled.appendingPathComponent("bin/cmoc").path) ? bundled : staged)
|
||||
let romURL = mac.appendingPathComponent("LocalResources/ROMs/coco3.rom")
|
||||
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path)
|
||||
&& FileManager.default.fileExists(atPath: romURL.path), "Stage the local compiler and CoCo ROM")
|
||||
@@ -488,7 +488,7 @@ final class CMOCDevelopmentTests: XCTestCase {
|
||||
@MainActor func testDefaultHelloDiskLaunchRunsWithoutImplicitBreakpointAndHonorsExplicitStops() async throws {
|
||||
let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
|
||||
let resources = mac.appendingPathComponent("LocalResources")
|
||||
let tools = resources.appendingPathComponent("ToolchainBundle")
|
||||
let tools = vccQualificationToolchain(resources.appendingPathComponent("ToolchainBundle"))
|
||||
let rom = resources.appendingPathComponent("ROMs/coco3.rom"), diskROM = resources.appendingPathComponent("ROMs/disk11.rom")
|
||||
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: tools.appendingPathComponent("bin/cmoc").path) &&
|
||||
FileManager.default.fileExists(atPath: rom.path) && FileManager.default.fileExists(atPath: diskROM.path), "Stage local tools and ROMs")
|
||||
@@ -599,9 +599,9 @@ final class CMOCDevelopmentTests: XCTestCase {
|
||||
|
||||
@MainActor func testRealBuildMappingBecomesStaleWhenEditorChanges() async throws {
|
||||
let bundled = Bundle.main.resourceURL!.appendingPathComponent("Toolchain")
|
||||
let staged = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
|
||||
.appendingPathComponent("LocalResources/ToolchainBundle")
|
||||
let toolchain = FileManager.default.isExecutableFile(atPath: bundled.appendingPathComponent("bin/cmoc").path) ? bundled : staged
|
||||
let staged = vccQualificationToolchain(URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
|
||||
.appendingPathComponent("LocalResources/ToolchainBundle"))
|
||||
let toolchain = vccQualificationToolchain(FileManager.default.isExecutableFile(atPath: bundled.appendingPathComponent("bin/cmoc").path) ? bundled : staged)
|
||||
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path),
|
||||
"This integration check requires the bundled development toolchain")
|
||||
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCDevelopmentTests-\(UUID().uuidString)")
|
||||
|
||||
@@ -18,7 +18,7 @@ final class CMOCFloatingPointIntegrationTests: XCTestCase {
|
||||
}
|
||||
private func fixture() async throws -> Fixture {
|
||||
let resources = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("LocalResources")
|
||||
let toolchain = resources.appendingPathComponent("ToolchainBundle")
|
||||
let toolchain = vccQualificationToolchain(resources.appendingPathComponent("ToolchainBundle"))
|
||||
let rom = resources.appendingPathComponent("ROMs/coco3.rom")
|
||||
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path)
|
||||
&& FileManager.default.fileExists(atPath: rom.path), "Local licensed CoCo ROM and staged toolchain are required")
|
||||
|
||||
@@ -191,7 +191,7 @@ final class CMOCNavigationTests: XCTestCase {
|
||||
}
|
||||
@MainActor func testReferenceNavigationKeepsSuccessfulBuildIdentity() async throws {
|
||||
let resources = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("LocalResources")
|
||||
let toolchain = resources.appendingPathComponent("ToolchainBundle")
|
||||
let toolchain = vccQualificationToolchain(resources.appendingPathComponent("ToolchainBundle"))
|
||||
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path), "Staged toolchain required")
|
||||
let root = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCNavigationBuild-" + UUID().uuidString)
|
||||
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
||||
|
||||
@@ -19,7 +19,7 @@ final class CMOCSourceDebugTests: XCTestCase {
|
||||
}
|
||||
private func fixture() async throws -> Fixture {
|
||||
let resources = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("LocalResources")
|
||||
let toolchain = resources.appendingPathComponent("ToolchainBundle")
|
||||
let toolchain = vccQualificationToolchain(resources.appendingPathComponent("ToolchainBundle"))
|
||||
let rom = resources.appendingPathComponent("ROMs/coco3.rom")
|
||||
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path)
|
||||
&& FileManager.default.fileExists(atPath: rom.path), "Local licensed CoCo ROM and staged toolchain are required")
|
||||
|
||||
@@ -1046,7 +1046,7 @@ final class CMOCMultiFileExecutionTests: XCTestCase {
|
||||
@MainActor func testHelloDiskDOSAndLOADMRunTheSameProgramOnBothCPUs() async throws {
|
||||
let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
|
||||
let resources = mac.appendingPathComponent("LocalResources")
|
||||
let runtime = resources.appendingPathComponent("ToolchainBundle")
|
||||
let runtime = vccQualificationToolchain(resources.appendingPathComponent("ToolchainBundle"))
|
||||
let romURL = resources.appendingPathComponent("ROMs/coco3.rom"), diskROMURL = resources.appendingPathComponent("ROMs/disk11.rom")
|
||||
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: runtime.appendingPathComponent("bin/cmoc").path) && FileManager.default.fileExists(atPath: romURL.path) && FileManager.default.fileExists(atPath: diskROMURL.path), "Stage local tools and ROMs")
|
||||
let root = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCHelloDOS-" + UUID().uuidString)
|
||||
@@ -1100,7 +1100,7 @@ final class CMOCMultiFileExecutionTests: XCTestCase {
|
||||
|
||||
@MainActor func testMultiFileQuickloadAndDiskBootStopAtVerifiedSourceOnBothCPUs() async throws {
|
||||
let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
|
||||
let resources = mac.appendingPathComponent("LocalResources"), toolchain = resources.appendingPathComponent("ToolchainBundle")
|
||||
let resources = mac.appendingPathComponent("LocalResources"), toolchain = vccQualificationToolchain(resources.appendingPathComponent("ToolchainBundle"))
|
||||
let romURL = resources.appendingPathComponent("ROMs/coco3.rom"), diskROMURL = resources.appendingPathComponent("ROMs/disk11.rom")
|
||||
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path) &&
|
||||
FileManager.default.fileExists(atPath: romURL.path) && FileManager.default.fileExists(atPath: diskROMURL.path),
|
||||
@@ -1240,7 +1240,7 @@ final class CMOCLiveBreakpointModelTests: XCTestCase {
|
||||
}
|
||||
@MainActor func testPausedLiveToggleKeepsInstructionUpdatesAndRejectsUnobservedMemoryEdits() async throws {
|
||||
let resources = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("LocalResources")
|
||||
let toolchain = resources.appendingPathComponent("ToolchainBundle"), romURL = resources.appendingPathComponent("ROMs/coco3.rom")
|
||||
let toolchain = vccQualificationToolchain(resources.appendingPathComponent("ToolchainBundle")), romURL = resources.appendingPathComponent("ROMs/coco3.rom")
|
||||
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path) &&
|
||||
FileManager.default.fileExists(atPath: romURL.path), "Staged tools and a licensed local CoCo ROM are required")
|
||||
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCLiveBreakpoints-" + UUID().uuidString)
|
||||
|
||||
@@ -263,8 +263,8 @@ final class CMOCVariableDebugTests: XCTestCase {
|
||||
XCTAssertThrowsError(try parse(floating(5, String(repeating: "x", count: 129))))
|
||||
}
|
||||
func testCompilerTagsActualFloatingFormatsIncludingNestedTypes() throws {
|
||||
let runtime = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
|
||||
.appendingPathComponent("LocalResources/ToolchainBundle")
|
||||
let runtime = vccQualificationToolchain(URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
|
||||
.appendingPathComponent("LocalResources/ToolchainBundle"))
|
||||
let compiler = runtime.appendingPathComponent("bin/cmoc")
|
||||
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: compiler.path), "Staged compiler required")
|
||||
let root = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCFloatFormats-" + UUID().uuidString)
|
||||
@@ -318,7 +318,7 @@ final class CMOCVariableDebugTests: XCTestCase {
|
||||
}
|
||||
func testMetadataPathsDoNotDependOnLiveIncrementalWorkspaceLifetime() async throws {
|
||||
let resources = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("LocalResources")
|
||||
let toolchain = resources.appendingPathComponent("ToolchainBundle")
|
||||
let toolchain = vccQualificationToolchain(resources.appendingPathComponent("ToolchainBundle"))
|
||||
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path), "Staged compiler required")
|
||||
let root = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCMetadataLive-" + UUID().uuidString)
|
||||
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
||||
@@ -348,7 +348,7 @@ final class CMOCVariableDebugTests: XCTestCase {
|
||||
func testLongCompilerTypeRecordsUseOnlyVerifiedMatchingAssembly() async throws {
|
||||
let resources = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
|
||||
.appendingPathComponent("LocalResources")
|
||||
let toolchain = resources.appendingPathComponent("ToolchainBundle")
|
||||
let toolchain = vccQualificationToolchain(resources.appendingPathComponent("ToolchainBundle"))
|
||||
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path), "Staged compiler required")
|
||||
let root = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCLongMetadata-" + UUID().uuidString)
|
||||
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
||||
|
||||
@@ -18,7 +18,7 @@ final class CMOCVariableTreeIntegrationTests: XCTestCase {
|
||||
}
|
||||
private func fixture() async throws -> Fixture {
|
||||
let resources = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("LocalResources")
|
||||
let toolchain = resources.appendingPathComponent("ToolchainBundle")
|
||||
let toolchain = vccQualificationToolchain(resources.appendingPathComponent("ToolchainBundle"))
|
||||
let rom = resources.appendingPathComponent("ROMs/coco3.rom")
|
||||
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path)
|
||||
&& FileManager.default.fileExists(atPath: rom.path), "Local licensed CoCo ROM and staged toolchain are required")
|
||||
|
||||
@@ -16,7 +16,7 @@ final class CMOCWorkflowHardeningTests: XCTestCase {
|
||||
return try XCTUnwrap(value)
|
||||
}
|
||||
@MainActor func testFailedCancelledAndCleanBuildsKeepLastRunnableAndLoadedIdentity() async throws {
|
||||
let toolchain = resources.appendingPathComponent("ToolchainBundle")
|
||||
let toolchain = vccQualificationToolchain(resources.appendingPathComponent("ToolchainBundle"))
|
||||
let rom = resources.appendingPathComponent("ROMs/coco3.rom")
|
||||
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path)
|
||||
&& FileManager.default.fileExists(atPath: rom.path), "Staged toolchain and local CoCo ROM required")
|
||||
@@ -102,7 +102,7 @@ final class CMOCWorkflowHardeningTests: XCTestCase {
|
||||
}
|
||||
}
|
||||
@MainActor func testMissingOpenFilesPreserveTextAndInvalidateBuildWithoutRecreatingFiles() async throws {
|
||||
let toolchain = resources.appendingPathComponent("ToolchainBundle")
|
||||
let toolchain = vccQualificationToolchain(resources.appendingPathComponent("ToolchainBundle"))
|
||||
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path), "Staged toolchain required")
|
||||
let root = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCMissingFiles-\(UUID().uuidString)")
|
||||
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
||||
|
||||
@@ -0,0 +1,321 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
import AppKit
|
||||
import Darwin
|
||||
import XCTest
|
||||
|
||||
final class MCPBuildExportTests: XCTestCase {
|
||||
private var root: URL!
|
||||
override func setUpWithError() throws {
|
||||
root = FileManager.default.temporaryDirectory.appendingPathComponent("VCC export tests " + UUID().uuidString)
|
||||
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: false)
|
||||
}
|
||||
override func tearDownWithError() throws { if let root { try? FileManager.default.removeItem(at: root) } }
|
||||
private func artifact(_ name: String = "Artifact", files: [String: Data] = ["GAME.BIN": Data([0,1,2]), "HOME.DSK": Data(repeating: 1, count: 161280), "DATA.DSK": Data(repeating: 2, count: 161280), "COCOMAN.dsk": Data(repeating: 1, count: 161280)]) throws -> CMOCBuildArtifact {
|
||||
let directory = root.appendingPathComponent(name)
|
||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false)
|
||||
for (path,data) in files {
|
||||
let url = directory.appendingPathComponent(path)
|
||||
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
try data.write(to: url)
|
||||
}
|
||||
let source = Data("int main(void){return 0;}".utf8)
|
||||
try source.write(to: directory.appendingPathComponent("main.c"))
|
||||
return CMOCBuildArtifact(id: UUID(), directory: directory, source: String(decoding: source, as: UTF8.self), sourceData: source,
|
||||
sourceSHA256: CMOCProject.sha256(source), binaryData: files["GAME.BIN"] ?? Data(), buildLog: "",
|
||||
outputPaths: Array(files.keys) + ["main.c"],
|
||||
exportProducts: files.map { CMOCBuildOutputProduct(relativePath: $0.key, byteCount: $0.value.count, sha256: CMOCProject.sha256($0.value)) }.sorted { $0.relativePath < $1.relativePath })
|
||||
}
|
||||
private func destination(_ name: String = "Deliveries") throws -> URL {
|
||||
let url = root.appendingPathComponent(name)
|
||||
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: false)
|
||||
return url
|
||||
}
|
||||
func testSeparateExactSetsPreserveAliasesAndOriginalIdentity() throws {
|
||||
let release = try artifact("Release"), debug = try artifact("Debug", files: ["GAME.BIN":Data([4,5,6]),"HOME.DSK":Data(repeating:3,count:161280),"DATA.DSK":Data(repeating:4,count:161280),"COCOMAN.dsk":Data(repeating:3,count:161280)])
|
||||
let folder = try destination(), exporter = try MCPBuildExporter(destination: folder)
|
||||
for (name,artifact) in [("VCC-Release",release),("VCC-Debug",debug)] {
|
||||
let source = try MCPBuildExporter.Source(artifact)
|
||||
XCTAssertEqual(source.artifactID,artifact.id)
|
||||
let delivery = try exporter.export(source: source, products: artifact.exportProducts, setName: name)
|
||||
try exporter.verify(delivery)
|
||||
for product in delivery.products {
|
||||
let bytes=try Data(contentsOf:folder.appendingPathComponent(name).appendingPathComponent(product.relativePath))
|
||||
XCTAssertEqual(bytes.count,product.byteCount);XCTAssertEqual(CMOCProject.sha256(bytes),product.sha256)
|
||||
}
|
||||
XCTAssertEqual(try Data(contentsOf:folder.appendingPathComponent(name+"/HOME.DSK")),try Data(contentsOf:folder.appendingPathComponent(name+"/COCOMAN.dsk")))
|
||||
XCTAssertThrowsError(try exporter.export(source:source,products:artifact.exportProducts,setName:name))
|
||||
}
|
||||
XCTAssertNotEqual(release.exportProducts.first?.identifier(artifactID:release.id),debug.exportProducts.first?.identifier(artifactID:debug.id))
|
||||
}
|
||||
func testUndeclaredAndTraversalSelectionsNeverCopySource() throws {
|
||||
let artifact=try artifact(),exporter=try MCPBuildExporter(destination:destination()),source=try MCPBuildExporter.Source(artifact)
|
||||
for path in ["main.c","../outside","/etc/passwd"] {
|
||||
let product=CMOCBuildOutputProduct(relativePath:path,byteCount:1,sha256:CMOCProject.sha256(Data([0])))
|
||||
XCTAssertThrowsError(try exporter.export(source:source,products:[product],setName:"VCC-Invalid"))
|
||||
}
|
||||
XCTAssertThrowsError(try exporter.export(source:source,products:artifact.exportProducts,setName:"VCC-../escape"))
|
||||
}
|
||||
func testChangedOutputAndLinkedLeafAreRejected() throws {
|
||||
let artifact=try artifact(),source=try MCPBuildExporter.Source(artifact),exporter=try MCPBuildExporter(destination:destination())
|
||||
let output=artifact.directory.appendingPathComponent("GAME.BIN")
|
||||
try Data([9,9,9]).write(to:output)
|
||||
XCTAssertThrowsError(try exporter.export(source:source,products:artifact.exportProducts,setName:"VCC-Changed"))
|
||||
try FileManager.default.removeItem(at:output)
|
||||
let external=root.appendingPathComponent("outside.bin");try Data([0,1,2]).write(to:external)
|
||||
try FileManager.default.createSymbolicLink(at:output,withDestinationURL:external)
|
||||
XCTAssertThrowsError(try exporter.export(source:source,products:artifact.exportProducts,setName:"VCC-Linked"))
|
||||
try FileManager.default.removeItem(at:output)
|
||||
try FileManager.default.linkItem(at:external,to:output)
|
||||
XCTAssertThrowsError(try exporter.export(source:source,products:artifact.exportProducts,setName:"VCC-HardLinked"))
|
||||
XCTAssertEqual(try Data(contentsOf:external),Data([0,1,2]))
|
||||
}
|
||||
func testLinkedParentAndReplacedArtifactDirectoryAreRejected() throws {
|
||||
let artifact=try artifact(files:["nested/GAME.BIN":Data([1])]),source=try MCPBuildExporter.Source(artifact)
|
||||
let exporter=try MCPBuildExporter(destination:destination())
|
||||
let parent=artifact.directory.appendingPathComponent("nested"),moved=root.appendingPathComponent("moved")
|
||||
try FileManager.default.moveItem(at:parent,to:moved)
|
||||
try FileManager.default.createSymbolicLink(at:parent,withDestinationURL:moved)
|
||||
XCTAssertThrowsError(try exporter.export(source:source,products:artifact.exportProducts,setName:"VCC-Parent"))
|
||||
let movedArtifact=root.appendingPathComponent("Old Artifact")
|
||||
try FileManager.default.moveItem(at:artifact.directory,to:movedArtifact)
|
||||
try FileManager.default.createDirectory(at:artifact.directory,withIntermediateDirectories:false)
|
||||
XCTAssertThrowsError(try exporter.export(source:source,products:artifact.exportProducts,setName:"VCC-Replaced"))
|
||||
}
|
||||
func testChangedAndLinkedDestinationAreRejected() throws {
|
||||
let artifact=try artifact(),source=try MCPBuildExporter.Source(artifact),folder=try destination()
|
||||
let exporter=try MCPBuildExporter(destination:folder),moved=root.appendingPathComponent("Old Delivery Folder")
|
||||
try FileManager.default.moveItem(at:folder,to:moved)
|
||||
try FileManager.default.createDirectory(at:folder,withIntermediateDirectories:false)
|
||||
XCTAssertThrowsError(try exporter.export(source:source,products:artifact.exportProducts,setName:"VCC-Replaced"))
|
||||
try FileManager.default.removeItem(at:folder)
|
||||
try FileManager.default.createSymbolicLink(at:folder,withDestinationURL:moved)
|
||||
XCTAssertThrowsError(try MCPBuildExporter(destination:folder))
|
||||
XCTAssertThrowsError(try exporter.export(source:source,products:artifact.exportProducts,setName:"VCC-Linked"))
|
||||
}
|
||||
func testReplacementBetweenStagingAndCommitDoesNotPublish() throws {
|
||||
let artifact=try artifact(),source=try MCPBuildExporter.Source(artifact),folder=try destination(),moved=root.appendingPathComponent("Moved")
|
||||
let exporter=try MCPBuildExporter(destination:folder)
|
||||
exporter.beforeCommit = {
|
||||
try FileManager.default.moveItem(at:folder,to:moved)
|
||||
try FileManager.default.createDirectory(at:folder,withIntermediateDirectories:false)
|
||||
}
|
||||
XCTAssertThrowsError(try exporter.export(source:source,products:artifact.exportProducts,setName:"VCC-Race"))
|
||||
XCTAssertFalse(FileManager.default.fileExists(atPath:folder.appendingPathComponent("VCC-Race").path))
|
||||
XCTAssertFalse(FileManager.default.fileExists(atPath:moved.appendingPathComponent("VCC-Race").path))
|
||||
}
|
||||
func testRevocationBeforeCommitAndPartialFailureKeepPriorData() throws {
|
||||
let artifact=try artifact(),source=try MCPBuildExporter.Source(artifact),folder=try destination()
|
||||
let prior=folder.appendingPathComponent("prior.txt");try Data("keep".utf8).write(to:prior)
|
||||
let exporter=try MCPBuildExporter(destination:folder)
|
||||
exporter.beforeCommit = { exporter.invalidate() }
|
||||
XCTAssertThrowsError(try exporter.export(source:source,products:artifact.exportProducts,setName:"VCC-Revoked"))
|
||||
let failing=try MCPBuildExporter(destination:folder)
|
||||
failing.afterFile = { _ in throw POSIXError(.ENOSPC) }
|
||||
XCTAssertThrowsError(try failing.export(source:source,products:artifact.exportProducts,setName:"VCC-Failed"))
|
||||
XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath:folder.path),["prior.txt"])
|
||||
XCTAssertEqual(try Data(contentsOf:prior),Data("keep".utf8))
|
||||
}
|
||||
func testRetryVerificationRefusesChangedMissingExtraOrLinkedDeliveredBytes() throws {
|
||||
let artifact=try artifact(),source=try MCPBuildExporter.Source(artifact),folder=try destination(),exporter=try MCPBuildExporter(destination:folder)
|
||||
let delivery=try exporter.export(source:source,products:artifact.exportProducts,setName:"VCC-Delivery")
|
||||
let product=folder.appendingPathComponent("VCC-Delivery/GAME.BIN")
|
||||
try Data([7,7,7]).write(to:product)
|
||||
XCTAssertThrowsError(try exporter.verify(delivery))
|
||||
try Data([0,1,2]).write(to:product)
|
||||
try exporter.verify(delivery)
|
||||
let extra=folder.appendingPathComponent("VCC-Delivery/unrequested.txt");try Data([1]).write(to:extra)
|
||||
XCTAssertThrowsError(try exporter.verify(delivery))
|
||||
try FileManager.default.removeItem(at:extra);try FileManager.default.removeItem(at:product)
|
||||
XCTAssertThrowsError(try exporter.verify(delivery))
|
||||
try FileManager.default.createSymbolicLink(at:product,withDestinationURL:artifact.directory.appendingPathComponent("GAME.BIN"))
|
||||
XCTAssertThrowsError(try exporter.verify(delivery))
|
||||
}
|
||||
func testConcurrentDestinationConflictCannotReplacePriorSet() throws {
|
||||
let artifact=try artifact(),source=try MCPBuildExporter.Source(artifact),folder=try destination(),exporter=try MCPBuildExporter(destination:folder)
|
||||
let prior=folder.appendingPathComponent("VCC-Conflict")
|
||||
exporter.beforeCommit = { try FileManager.default.createDirectory(at:prior,withIntermediateDirectories:false);try Data("preserve".utf8).write(to:prior.appendingPathComponent("mine")) }
|
||||
XCTAssertThrowsError(try exporter.export(source:source,products:artifact.exportProducts,setName:"VCC-Conflict"))
|
||||
XCTAssertEqual(try Data(contentsOf:prior.appendingPathComponent("mine")),Data("preserve".utf8))
|
||||
}
|
||||
func testCancellationLeavesNoPartialSet() async throws {
|
||||
let artifact=try artifact(),source=try MCPBuildExporter.Source(artifact),folder=try destination(),exporter=try MCPBuildExporter(destination:folder)
|
||||
let work=Task.detached { () throws -> Void in
|
||||
withUnsafeCurrentTask { $0?.cancel() }
|
||||
_ = try exporter.export(source:source,products:artifact.exportProducts,setName:"VCC-Cancelled")
|
||||
}
|
||||
do { try await work.value;XCTFail("Cancelled export succeeded") } catch { XCTAssertTrue(error is CancellationError) }
|
||||
XCTAssertTrue(try FileManager.default.contentsOfDirectory(atPath:folder.path).isEmpty)
|
||||
}
|
||||
func testDeclaredExportConfigurationSeparatesInputsAndDirectories() throws {
|
||||
var config=CMOCProjectConfiguration();config.exportOutputs=["delivery/alias.dsk"]
|
||||
XCTAssertEqual(try config.validated().exportOutputs,["delivery/alias.dsk"])
|
||||
config.exportOutputs=["main.c"];XCTAssertThrowsError(try config.validated())
|
||||
config.exportOutputs=["../secret"];XCTAssertThrowsError(try config.validated())
|
||||
config.exportOutputs=["a","a/b"];XCTAssertThrowsError(try config.validated())
|
||||
config.exportOutputs=["A.dsk","a.DSK"];XCTAssertThrowsError(try config.validated())
|
||||
config.exportOutputs=[".git/config"];XCTAssertThrowsError(try config.validated())
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
final class MCPBuildExportAccessTests: XCTestCase {
|
||||
#if DEBUG
|
||||
func testPublicHelperBuildsReleaseThenDebugAndExportsOriginalProductsWithScopedPermission() async throws {
|
||||
_ = NSApplication.shared
|
||||
let resources = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("LocalResources")
|
||||
let toolchain = vccQualificationToolchain(resources.appendingPathComponent("ToolchainBundle"))
|
||||
let helper = Bundle(for: Self.self).bundleURL.deletingLastPathComponent().appendingPathComponent("vcc-mcp")
|
||||
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: helper.path) && FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path), "Build the public helper and stage the reviewed compiler runtime.")
|
||||
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("MCP public build export " + UUID().uuidString)
|
||||
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false)
|
||||
let suite = "MCPBuildExport." + UUID().uuidString, defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
|
||||
defer { defaults.removePersistentDomain(forName: suite); try? FileManager.default.removeItem(at: folder) }
|
||||
let machine = MachineModel(diskStore: .init(url: folder.appendingPathComponent("disks.json")), displayDefaults: defaults,
|
||||
inputStore: .init(url: folder.appendingPathComponent("input.json")), restoreMediaOnLaunch: false)
|
||||
defer { machine.shutdown() }
|
||||
let model = CMOCDevelopmentModel(machine: machine, toolchain: toolchain, defaults: defaults,
|
||||
buildRoot: folder.appendingPathComponent("Builds"), recoveryRoot: folder.appendingPathComponent("Recovery"))
|
||||
var project = try CMOCProject.create(at: folder.appendingPathComponent("Project"))
|
||||
var configuration = project.configuration
|
||||
configuration.binary = "GAME.BIN"; configuration.diskImage = "HOME.DSK"; configuration.diskTarget = "all"
|
||||
configuration.playtestDisks = ["DATA.DSK"]; configuration.exportOutputs = ["COCOMAN.dsk"]
|
||||
try JSONEncoder().encode(configuration).write(to: project.directory.appendingPathComponent(CMOCProject.configurationFilename))
|
||||
let source = """
|
||||
#include <cmoc.h>
|
||||
int main(void) {
|
||||
#ifdef RELEASE
|
||||
printf("NORMAL RELEASE\\n");
|
||||
#else
|
||||
printf("NORMAL DEBUG\\n");
|
||||
#endif
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
try Data(source.utf8).write(to: project.directory.appendingPathComponent("main.c"))
|
||||
let makefile = """
|
||||
ifeq ($(VCC_CONFIGURATION),Release)
|
||||
FLAGS = -O2 -DRELEASE
|
||||
else
|
||||
FLAGS = -O0 -fno-omit-frame-pointer
|
||||
endif
|
||||
all: GAME.BIN HOME.DSK DATA.DSK COCOMAN.dsk
|
||||
GAME.BIN: main.c
|
||||
\tcmoc --coco --intermediate $(FLAGS) -o GAME.BIN main.c
|
||||
HOME.DSK: GAME.BIN
|
||||
\tperl -e 'print "\\xff" x 161280' > HOME.DSK
|
||||
\twritecocofile HOME.DSK GAME.BIN
|
||||
DATA.DSK:
|
||||
\tperl -e 'print "\\xff" x 161280' > DATA.DSK
|
||||
COCOMAN.dsk: HOME.DSK
|
||||
\tcp HOME.DSK COCOMAN.dsk
|
||||
clean:
|
||||
\trm -f GAME.BIN HOME.DSK DATA.DSK COCOMAN.dsk
|
||||
"""
|
||||
try Data(makefile.utf8).write(to: project.directory.appendingPathComponent("Makefile"))
|
||||
project = try CMOCProject.open(at: project.directory); try model.adopt(project)
|
||||
let destination = folder.appendingPathComponent("Delivery")
|
||||
try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: false)
|
||||
let host = MCPCMOC(), grant = folder.appendingPathComponent("grant.json")
|
||||
let clientSource = resources.deletingLastPathComponent().appendingPathComponent("Tools/MCP/test-helper.py")
|
||||
func run(_ script: String) async throws -> String {
|
||||
try await Task.detached {
|
||||
let process = Process(), output = Pipe()
|
||||
process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
|
||||
process.arguments = ["python3", "-c", script, clientSource.path, helper.path, grant.path, destination.path]
|
||||
process.standardOutput = output; process.standardError = output
|
||||
let deadline = DispatchWorkItem { if process.isRunning { process.terminate() } }
|
||||
DispatchQueue.global().asyncAfter(deadline: .now() + 150, execute: deadline)
|
||||
defer { deadline.cancel() }
|
||||
try process.run(); let bytes = try output.fileHandleForReading.readToEnd() ?? Data(); process.waitUntilExit()
|
||||
let text = String(decoding: bytes, as: UTF8.self)
|
||||
guard process.terminationStatus == 0 else { throw NSError(domain: "MCPBuildExportFixture", code: Int(process.terminationStatus), userInfo: [NSLocalizedDescriptionKey: text]) }
|
||||
return text
|
||||
}.value
|
||||
}
|
||||
let setup = """
|
||||
import importlib.util,json,sys,time,hashlib
|
||||
from pathlib import Path
|
||||
spec=importlib.util.spec_from_file_location('client',sys.argv[1]);m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m)
|
||||
def result(c,tool,**args):
|
||||
reply=c.call(tool,**args)['result']
|
||||
assert not reply.get('isError'),(tool,reply)
|
||||
return reply['structuredContent']
|
||||
"""
|
||||
do {
|
||||
try await host.exportCallContextRegression(model, at: grant, playtests: false, exportFolder: destination)
|
||||
let passed = try await run(setup + """
|
||||
|
||||
with m.Client(sys.argv[2],Path(sys.argv[3])) as c:
|
||||
c.handshake('2025-11-25')
|
||||
catalog={t['name']:t for t in c.request('tools/list')['result']['tools']}
|
||||
assert {'export_build_outputs','get_build_export'} <= set(catalog)
|
||||
caps=result(c,'get_capabilities');project=caps['project_id'];revision=caps['revision']
|
||||
dest=caps['export_destinations'][0]['destination_id']
|
||||
builds=[]
|
||||
for configuration in ('Release','Debug'):
|
||||
build=result(c,'build_project',project_id=project,revision=revision,request_id='build-'+configuration,configuration=configuration,action='disk')
|
||||
for _ in range(1600):
|
||||
state=result(c,'get_build',build_id=build['build_id'])
|
||||
if state['status']!='building':break
|
||||
time.sleep(.025)
|
||||
assert state['status']=='succeeded',state
|
||||
assert len(state['exportable_outputs'])==4,state
|
||||
builds.append(state)
|
||||
directories=[]
|
||||
for index,state in enumerate(builds):
|
||||
args=dict(project_id=project,build_id=state['build_id'],artifact_id=state['artifact_id'],revision=state['revision'],destination_id=dest,output_ids=[p['output_id'] for p in state['exportable_outputs']],request_id='deliver-'+str(index))
|
||||
accepted=result(c,'export_build_outputs',**args)
|
||||
for _ in range(800):
|
||||
exported=result(c,'get_build_export',project_id=project,export_id=accepted['export_id'])
|
||||
if not exported['busy']:break
|
||||
time.sleep(.01)
|
||||
assert exported['status']=='completed',exported
|
||||
assert exported['artifact_id']==state['artifact_id'] and exported['build_id']==state['build_id']
|
||||
assert exported['revision']==state['revision'] and exported['configuration']==state['configuration']
|
||||
directories.append(exported['delivery_directory'])
|
||||
expected={p['output_id']:p for p in state['exportable_outputs']}
|
||||
for p in exported['outputs']:
|
||||
data=(Path(sys.argv[4])/p['relative_filename']).read_bytes()
|
||||
assert len(data)==p['bytes']==expected[p['output_id']]['bytes']
|
||||
assert hashlib.sha256(data).hexdigest()==p['sha256']==expected[p['output_id']]['sha256']
|
||||
home=Path(sys.argv[4])/exported['delivery_directory']/'HOME.DSK'
|
||||
alias=home.with_name('COCOMAN.dsk');assert home.read_bytes()==alias.read_bytes()
|
||||
retry=result(c,'export_build_outputs',**args);assert retry==exported,(retry,exported)
|
||||
for changed in ({'artifact_id':'wrong'},{'build_id':'wrong'},{'project_id':'wrong'},{'revision':revision+1},{'destination_id':'wrong'},{'output_ids':['main.c']},{'output_ids':[args['output_ids'][0]]}):
|
||||
rejected=c.call('export_build_outputs',**{**args,**changed})
|
||||
assert rejected.get('error') or rejected.get('result',{}).get('isError'),rejected
|
||||
if index==1:
|
||||
home.write_bytes(b'changed by owner')
|
||||
rejected=c.call('export_build_outputs',**args)
|
||||
assert rejected['result'].get('isError'),rejected
|
||||
assert home.read_bytes()==b'changed by owner'
|
||||
assert len(set(directories))==2
|
||||
assert len(list(Path(sys.argv[4]).iterdir()))==2
|
||||
print('PASS real approved Make Release/Debug builds and exact separate four-product exports; retries, alias identity, identity/destination/selection conflicts and tamper refusal')
|
||||
""")
|
||||
XCTAssertTrue(passed.contains("PASS real approved Make"), passed)
|
||||
await host.revoke().value
|
||||
try await host.exportCallContextRegression(model, at: grant, playtests: false)
|
||||
let refused = try await run(setup + """
|
||||
|
||||
with m.Client(sys.argv[2],Path(sys.argv[3])) as c:
|
||||
c.handshake('2025-11-25')
|
||||
names={t['name'] for t in c.request('tools/list')['result']['tools']}
|
||||
assert 'export_build_outputs' not in names and 'get_build_export' not in names
|
||||
assert not result(c,'get_capabilities')['build_output_export']
|
||||
# Forging grant metadata can expose a helper schema, but not host permission.
|
||||
path=Path(sys.argv[3]);grant=json.loads(path.read_text());grant['toolset']=13;grant['buildExport']=True;path.write_text(json.dumps(grant));path.chmod(0o600)
|
||||
with m.Client(sys.argv[2],path) as c:
|
||||
c.handshake('2025-11-25')
|
||||
caps=result(c,'get_capabilities');assert not caps['build_output_export']
|
||||
rejected=c.call('export_build_outputs',project_id=caps['project_id'],build_id='wrong',artifact_id='wrong',revision=caps['revision'],destination_id='wrong',output_ids=['x'*64],request_id='forged')
|
||||
assert rejected['result'].get('isError'),rejected
|
||||
print('PASS absent native consent and forged client permission cannot authorize export')
|
||||
""")
|
||||
XCTAssertTrue(refused.contains("PASS absent native consent"), refused)
|
||||
await host.revoke().value
|
||||
} catch { await host.revoke().value; throw error }
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -89,7 +89,7 @@ final class MCPCallContextAccessTests: XCTestCase {
|
||||
|
||||
func testRealCGrantOwnsFrozenSevenArgumentContextAndRejectsStaleAuthority() async throws {
|
||||
_ = NSApplication.shared
|
||||
let localToolchainBundle = resources.appendingPathComponent("ToolchainBundle")
|
||||
let localToolchainBundle = vccQualificationToolchain(resources.appendingPathComponent("ToolchainBundle"))
|
||||
let roms = resources.appendingPathComponent("ROMs")
|
||||
try XCTSkipUnless(["cmoc", "make", "perl", "writecocofile"].allSatisfy {
|
||||
FileManager.default.isExecutableFile(atPath: localToolchainBundle.appendingPathComponent("bin/" + $0).path)
|
||||
@@ -156,7 +156,7 @@ final class MCPCallContextAccessTests: XCTestCase {
|
||||
do {
|
||||
try await host.exportCallContextRegression(model, at: grantFile, helperURL: worker, roms: roms)
|
||||
let grant = try readGrant(grantFile)
|
||||
XCTAssertEqual(grant["toolset"] as? Int, 12)
|
||||
XCTAssertEqual(grant["toolset"] as? Int, 13)
|
||||
XCTAssertEqual(grant["playtestVideo"] as? Bool, true)
|
||||
XCTAssertEqual(grant["playtestCallContext"] as? Bool, true)
|
||||
let capabilities = try await result("get_capabilities", grant: grant)
|
||||
@@ -333,7 +333,7 @@ final class MCPCallContextAccessTests: XCTestCase {
|
||||
let machine = MachineModel(diskStore: .init(url: root.appendingPathComponent("disks.json")), displayDefaults: defaults,
|
||||
inputStore: .init(url: root.appendingPathComponent("input.json")), restoreMediaOnLaunch: false)
|
||||
defer { machine.shutdown() }
|
||||
let model = CMOCDevelopmentModel(machine: machine, toolchain: resources.appendingPathComponent("ToolchainBundle"),
|
||||
let model = CMOCDevelopmentModel(machine: machine, toolchain: vccQualificationToolchain(resources.appendingPathComponent("ToolchainBundle")),
|
||||
defaults: defaults, buildRoot: root.appendingPathComponent("Builds"), recoveryRoot: root.appendingPathComponent("Recovery"))
|
||||
let project = try CMOCProject.create(at: root.appendingPathComponent("Project"))
|
||||
try model.adopt(project)
|
||||
@@ -408,7 +408,7 @@ final class MCPCallContextAccessTests: XCTestCase {
|
||||
|
||||
func testPublicMediaGrantBindsArtifactsRetainsEveryDiskAndResumesOnBothProcessors() async throws {
|
||||
_ = NSApplication.shared
|
||||
let toolchain = resources.appendingPathComponent("ToolchainBundle")
|
||||
let toolchain = vccQualificationToolchain(resources.appendingPathComponent("ToolchainBundle"))
|
||||
let roms = resources.appendingPathComponent("ROMs")
|
||||
try XCTSkipUnless(["cmoc", "make", "perl", "writecocofile"].allSatisfy {
|
||||
FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/" + $0).path)
|
||||
@@ -469,11 +469,16 @@ final class MCPCallContextAccessTests: XCTestCase {
|
||||
do {
|
||||
try await host.exportCallContextRegression(model, at: grantFile, helperURL: worker, roms: roms)
|
||||
let grant = try readGrant(grantFile)
|
||||
XCTAssertEqual(grant["toolset"] as? Int, 12)
|
||||
XCTAssertEqual(grant["toolset"] as? Int, 13)
|
||||
XCTAssertEqual(grant["playtestVideo"] as? Bool, true)
|
||||
XCTAssertEqual(grant["playtestMedia"] as? Bool, true)
|
||||
XCTAssertEqual(grant["playtestMultiDrive"] as? Bool, true)
|
||||
XCTAssertEqual(grant["buildExport"] as? Bool, false)
|
||||
let capabilities = try await result("get_capabilities", grant: grant)
|
||||
XCTAssertEqual(capabilities["playtest_media_exchange"] as? Bool, true)
|
||||
XCTAssertEqual(capabilities["playtest_media_drives"] as? [Int], [0, 1, 2, 3])
|
||||
XCTAssertEqual(capabilities["playtest_media_version"] as? Int, 2)
|
||||
XCTAssertEqual(capabilities["playtest_media_write_protection"] as? Bool, true)
|
||||
XCTAssertEqual((capabilities["tools"] as? [String])?.count, 35)
|
||||
let scope: [String: Any] = ["project_id": try XCTUnwrap(capabilities["project_id"] as? String),
|
||||
"revision": try XCTUnwrap(capabilities["revision"] as? Int)]
|
||||
|
||||
@@ -96,7 +96,7 @@ final class MCPDebuggerInspectionTests: XCTestCase {
|
||||
}
|
||||
|
||||
func testOrdinaryCMOCStopsAtMainWithCompiledWatchAndNoDisk() async throws {
|
||||
let root = try directory(), toolchain = resources.appendingPathComponent("ToolchainBundle")
|
||||
let root = try directory(), toolchain = vccQualificationToolchain(resources.appendingPathComponent("ToolchainBundle"))
|
||||
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path),
|
||||
"Requires the local staged toolchain.")
|
||||
let machine = try await machine(at: root, enhanced: true)
|
||||
@@ -142,7 +142,7 @@ final class MCPDebuggerInspectionTests: XCTestCase {
|
||||
XCTAssertNotEqual(paused.debuggerProgramRevision, snapshot.machine.debuggerProgramRevision)
|
||||
}
|
||||
func testHelloDiskKeepsCapturedInspectionAfterContinueAndEject() async throws {
|
||||
let root = try directory(), toolchain = resources.appendingPathComponent("ToolchainBundle")
|
||||
let root = try directory(), toolchain = vccQualificationToolchain(resources.appendingPathComponent("ToolchainBundle"))
|
||||
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path),
|
||||
"Requires the local staged toolchain.")
|
||||
let machine = try await machine(at: root, enhanced: false)
|
||||
|
||||
@@ -1829,6 +1829,469 @@ final class MCPPlaytestTests: XCTestCase {
|
||||
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)
|
||||
|
||||
@@ -220,7 +220,7 @@ final class SoftwareLibraryCuratedLaunchTests: XCTestCase {
|
||||
@MainActor func testRealDOSStartupLoadsAuthoredHelloDiskOnBothCPUs() async throws {
|
||||
let fixture = try Fixture(); defer { fixture.cleanup() }
|
||||
let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
|
||||
let tools = mac.appendingPathComponent("LocalResources/ToolchainBundle")
|
||||
let tools = vccQualificationToolchain(mac.appendingPathComponent("LocalResources/ToolchainBundle"))
|
||||
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: tools.appendingPathComponent("bin/cmoc").path), "Stage optional bundled tools")
|
||||
_ = try fixture.initialProfile(realROMs: true)
|
||||
let template = mac.deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("examples/cmoc/HelloDisk")
|
||||
|
||||
@@ -27,6 +27,32 @@ final class SoftwareLibraryPublishedGameTests: XCTestCase {
|
||||
diskSHA256: "d05ab25fd90171b048cce54f3af18ca6d0bd81335e138044ff05315e99cbf582", ramKiB: 128, keyboardOnly: false)
|
||||
]
|
||||
}
|
||||
/// These are candidate source-rebuild identities, not publication receipts.
|
||||
/// Independently replayed in owned folders with the pinned unsigned development
|
||||
/// runtime; this is not execution of the Developer ID-signed packaged compiler.
|
||||
private struct CandidateSourceBaseline: Sendable {
|
||||
let sourceZIP: String
|
||||
let makefile: String
|
||||
let binary: String
|
||||
let disk: String
|
||||
static let runtimeManifest = "a4dd934aed84a0b139e1d88b8a607d52ff7f6fc66c3bd3be30db7fd5d40dcbef"
|
||||
static let compiler = "5769c5ffe14f0adad61c41aa72337261acc6fd882e7e6656bdcf350b414930a1"
|
||||
static let wrapper = "b83e6ea79da5160cd85f5b7665524f19f717a4a6e76e12e661900dc071a1cea6"
|
||||
static let reviewed: [String: Self] = [
|
||||
"bone-quest": .init(sourceZIP: "99f9770965f9d2061f764ebe704da95f7f037a42c5df21a959b558b25d704da6",
|
||||
makefile: "b0e9816d4b1712cd903b1e51ebb5c80901fb45ba4233f6b091e6e97fe5cdd1d7",
|
||||
binary: "f57e5818d070009cb2713fe4d70f8f0cba2bd2e5c54833d4911348a708bdb0f0",
|
||||
disk: "8614c31b92a5f3b70b7b35792414b7fd43042614de2bda4b6ff508711f157a8d"),
|
||||
"capital-quest": .init(sourceZIP: "5f0cbc6ad58594a1c21a77079b2db4a2862546b6f701c2d515fe04f9727568f3",
|
||||
makefile: "880c46b17747ed0cbe33c386b21f319b9e453ab64cab185bd7f802293226a886",
|
||||
binary: "9b2fe10ebca6c515d3cb45f649ea772058be4186b8abac3fec95c3b69d955e6b",
|
||||
disk: "28a07495e1afa5702fd7c9def0aa2c94d8671ec6cfd6de2c57d5b92b4aa0c930"),
|
||||
"quadrapassel": .init(sourceZIP: "710c8e1e9d6cfbd800d5719e30ad2057aa9bade8c81f8d1e5374634b4d208438",
|
||||
makefile: "70144a013bdf2ad4c7ea996b53a1d304d7f440236d91f22fc7e63481fb258a92",
|
||||
binary: "4893e44f7ba33c3fa3b8f8268588104038dd402fae7cd3dcdbeeca11aa3e6df5",
|
||||
disk: "49e931b0530214d9cdb2afd4f5a1f3819695b3267e70fec04dcc69f86fc5ce9f")
|
||||
]
|
||||
}
|
||||
private struct Game: Sendable {
|
||||
let fixture: Fixture
|
||||
let publicationID: String
|
||||
@@ -148,7 +174,7 @@ final class SoftwareLibraryPublishedGameTests: XCTestCase {
|
||||
}
|
||||
throw ProfileFailure.message("Published-game fixture did not settle")
|
||||
}
|
||||
@MainActor private func withMachine(output: URL, use6309: Bool,
|
||||
@MainActor private func withMachine(output: URL, use6309: Bool, startingMachine: MachineSettings? = nil,
|
||||
body: (MachineModel, VCCMachineController, UserDefaults) async throws -> Void) async throws {
|
||||
_ = NSApplication.shared // Standalone hostless runs still need AppKit's input lifecycle.
|
||||
let suite = "PublishedGame-" + UUID().uuidString
|
||||
@@ -166,6 +192,7 @@ final class SoftwareLibraryPublishedGameTests: XCTestCase {
|
||||
&& FileManager.default.fileExists(atPath: profile.media.rom!.path), "Stage explicit local CoCo/Disk BASIC ROM inputs")
|
||||
profile.sound = false; profile.videoOutput = 0
|
||||
profile.machine.ram = 2; profile.machine.use6309 = !use6309
|
||||
if let startingMachine { profile.machine = startingMachine }
|
||||
profile.input.right.source = .keyboard; profile.input.left.source = .none
|
||||
var cartridges = CartridgeAssignments(); cartridges.multiPak = true; cartridges.mpiConfigured = true
|
||||
cartridges.physicalSlot = 4; cartridges.slots[4].kind = .floppy; profile.media.cartridges = cartridges
|
||||
@@ -209,6 +236,32 @@ final class SoftwareLibraryPublishedGameTests: XCTestCase {
|
||||
guard made else { throw ProfileFailure.message("Published acceptance image could not be rendered") }
|
||||
rgba = pixels
|
||||
}
|
||||
func changedPixelFraction(comparedTo before: Raster) -> Double {
|
||||
guard width == before.width, height == before.height else { return 1 }
|
||||
var changed = 0
|
||||
for offset in stride(from: 0, to: rgba.count, by: 4) {
|
||||
if (0..<3).contains(where: { abs(Int(rgba[offset + $0]) - Int(before.rgba[offset + $0])) > 28 }) { changed += 1 }
|
||||
}
|
||||
return Double(changed) / Double(width * height)
|
||||
}
|
||||
/// Compare only authored, static PLAY UI in the 320x192 reference.
|
||||
/// Coordinates map through the captured active picture, never full-frame
|
||||
/// borders. Black background, pieces, preview tiles and numbers are omitted.
|
||||
func staticForegroundMatch(to reference: Raster, regions: [CGRect]) -> (score: Double, pixels: Int, matched: Int) {
|
||||
var foreground = 0, matched = 0
|
||||
for region in regions {
|
||||
guard region.minX >= 0, region.minY >= 0,
|
||||
region.maxX <= CGFloat(reference.width), region.maxY <= CGFloat(reference.height) else { return (0, 0, 0) }
|
||||
for y in Int(region.minY)..<Int(region.maxY) { for x in Int(region.minX)..<Int(region.maxX) {
|
||||
let r = (y * reference.width + x) * 4
|
||||
if (0..<3).allSatisfy({ reference.rgba[r + $0] <= 28 }) { continue }
|
||||
foreground += 1
|
||||
let a = ((y * height / reference.height) * width + x * width / reference.width) * 4
|
||||
if (0..<3).allSatisfy({ abs(Int(rgba[a + $0]) - Int(reference.rgba[r + $0])) <= 28 }) { matched += 1 }
|
||||
} }
|
||||
}
|
||||
return (foreground > 100 ? Double(matched) / Double(foreground) : 0, foreground, matched)
|
||||
}
|
||||
func similarity(to reference: Raster) -> Double {
|
||||
var histogram: [UInt32: Int] = [:]
|
||||
for index in stride(from: 0, to: reference.rgba.count, by: 4) {
|
||||
@@ -325,6 +378,257 @@ final class SoftwareLibraryPublishedGameTests: XCTestCase {
|
||||
XCTAssertEqual(afterBuild.logicalMemory, before.logicalMemory)
|
||||
return report
|
||||
}
|
||||
@MainActor private func startCandidateDOS(_ model: MachineModel, controller: VCCMachineController) async throws {
|
||||
// Native owned-media qualification observes the core's readiness only.
|
||||
// The shared-program MCP screen surface intentionally rejects writable
|
||||
// disks; it is not the permission path for this disposable native session.
|
||||
// Visible OK precedes BASIC's direct-input loop, so require both actual
|
||||
// direct input and a stable final OK on mature guest fields before typing.
|
||||
let initial = await step(controller.snapshot)
|
||||
guard initial.errorMessage == nil else {
|
||||
throw ProfileFailure.message(initial.errorMessage ?? "Candidate Disk BASIC startup failed")
|
||||
}
|
||||
var ready = false, readyObservations = 0
|
||||
var firstReadyField: UInt64?
|
||||
var lastText = "(unavailable)"
|
||||
var last = initial
|
||||
let deadline = ContinuousClock.now.advanced(by: .seconds(15))
|
||||
while ContinuousClock.now < deadline {
|
||||
let readiness = await step(controller.assistantReadiness)
|
||||
let (text, snapshot): (String?, VCCMachineSnapshot) = await withCheckedContinuation { done in
|
||||
controller.inspectScreenText { done.resume(returning: ($0, $1)) }
|
||||
}
|
||||
last = snapshot; lastText = text ?? "(unavailable)"
|
||||
guard readiness.errorMessage == nil, snapshot.errorMessage == nil,
|
||||
readiness.state == .running, snapshot.state == .running,
|
||||
readiness.generation == initial.generation, snapshot.generation == initial.generation else {
|
||||
throw ProfileFailure.message(snapshot.errorMessage ?? readiness.errorMessage ?? "Candidate Disk BASIC changed during startup readiness checks")
|
||||
}
|
||||
let lines = (text ?? "").split(separator: "\n").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
|
||||
guard !lines.contains(where: { $0.hasPrefix("?") }) else {
|
||||
throw ProfileFailure.message("Candidate Disk BASIC reported an error before DOS; no command was sent")
|
||||
}
|
||||
if readiness.assistantDirectPrompt?.boolValue == true,
|
||||
readiness.assistantEmptyBASIC?.boolValue == true,
|
||||
lines.last == "OK", readiness.pasteRemaining == 0, snapshot.pasteRemaining == 0 {
|
||||
readyObservations += 1
|
||||
if firstReadyField == nil { firstReadyField = readiness.frames }
|
||||
if readyObservations >= 2, let firstReadyField, readiness.frames >= firstReadyField + 6 {
|
||||
ready = true; break
|
||||
}
|
||||
} else { readyObservations = 0; firstReadyField = nil }
|
||||
try await Task.sleep(for: .milliseconds(100))
|
||||
}
|
||||
guard ready else {
|
||||
throw ProfileFailure.message("Candidate disk did not reach stable native direct Disk BASIC readiness; no command was sent. Screen: " + lastText +
|
||||
String(format: " PC %04X, frame %llu.", last.programCounter, last.frames))
|
||||
}
|
||||
try await settle(model)
|
||||
guard model.canPaste else { throw ProfileFailure.message("Candidate Disk BASIC was not ready for ordinary keyboard input") }
|
||||
model.startPaste(try CocoPaste("DOS\n", mode: .text))
|
||||
try await settle(model)
|
||||
}
|
||||
|
||||
/// The published-binary test below deliberately retains its original hash
|
||||
/// contract. This separate opt-in checks the reviewed compiler's different
|
||||
/// outputs and actually boots those outputs, never a substituted old disk.
|
||||
@MainActor func testReviewedCMOC101SourceRebuildsBootAndRespondOnBothGuestCPUs() async throws {
|
||||
guard let path = ProcessInfo.processInfo.environment["VCC_TEST_TOOLCHAIN_DIR"] else {
|
||||
throw XCTSkip("Set the pinned unsigned development toolchain and private published-game fixture inputs for current-compiler qualification")
|
||||
}
|
||||
guard path.hasPrefix("/") else { throw ProfileFailure.message("Candidate compiler qualification requires an absolute runtime path") }
|
||||
let toolchain = URL(fileURLWithPath: path)
|
||||
let manifestData = try Data(contentsOf: toolchain.appendingPathComponent("manifest.json"))
|
||||
let compilerData = try Data(contentsOf: toolchain.appendingPathComponent("libexec/cmoc"))
|
||||
let wrapperData = try Data(contentsOf: toolchain.appendingPathComponent("bin/cmoc"))
|
||||
guard Self.sha(manifestData) == CandidateSourceBaseline.runtimeManifest,
|
||||
Self.sha(compilerData) == CandidateSourceBaseline.compiler,
|
||||
Self.sha(wrapperData) == CandidateSourceBaseline.wrapper else {
|
||||
throw ProfileFailure.message("Unknown candidate compiler/runtime identity: independently review and qualify new rebuild baselines before accepting these bytes")
|
||||
}
|
||||
let inputs = try await inputs()
|
||||
var results: [[String: Any]] = []
|
||||
for game in inputs.games {
|
||||
guard let expected = CandidateSourceBaseline.reviewed[game.slug],
|
||||
game.owned.source.package.sha256 == expected.sourceZIP else {
|
||||
throw ProfileFailure.message("The published source package has no reviewed candidate rebuild baseline")
|
||||
}
|
||||
let gameOutput = inputs.output.appendingPathComponent(game.slug)
|
||||
try FileManager.default.createDirectory(at: gameOutput, withIntermediateDirectories: true)
|
||||
let importer = SoftwareLibrarySourceImporter(cacheDirectory: gameOutput.appendingPathComponent("Candidate source originals"))
|
||||
let imported = try await importer.importProject(game.owned.source, to: gameOutput.appendingPathComponent("Candidate Source With Spaces"))
|
||||
guard Self.sha(try Data(contentsOf: imported.originalPackage)) == expected.sourceZIP else {
|
||||
throw ProfileFailure.message("Candidate source archive differs from the reviewed immutable package")
|
||||
}
|
||||
let project = try CMOCProject.open(at: imported.projectDirectory)
|
||||
let originalInputs = try project.inputFiles()
|
||||
let originalMakefile = try Data(contentsOf: project.makefileURL)
|
||||
guard Self.sha(originalMakefile) == expected.makefile else {
|
||||
throw ProfileFailure.message("Candidate source Makefile differs from the reviewed unmodified recipe")
|
||||
}
|
||||
let build = try await CMOCBuildService(toolchain: toolchain, buildRoot: gameOutput.appendingPathComponent("Candidate source qualification"))
|
||||
.build(project: project, overlays: [:], action: .disk, configuration: "Release")
|
||||
let disk = try Data(contentsOf: XCTUnwrap(build.diskURL))
|
||||
guard Self.sha(build.binaryData) == expected.binary, build.diskSHA256 == expected.disk,
|
||||
Self.sha(disk) == expected.disk else {
|
||||
throw ProfileFailure.message("Candidate compiler output differs from the independently replayed exact BIN/DSK baseline")
|
||||
}
|
||||
XCTAssertEqual(build.configurationName, "Release")
|
||||
XCTAssertEqual(try project.inputFiles(), originalInputs, "Candidate compilation must preserve every imported input")
|
||||
XCTAssertEqual(try Data(contentsOf: project.makefileURL), originalMakefile)
|
||||
let hero = try artwork(game.record["artwork"]["hero"], id: game.slug + "-candidate-title")
|
||||
let referenceData = try await SoftwareLibraryArtworkCache().thumbnail(for: hero, directory: gameOutput.appendingPathComponent("Artwork"))
|
||||
let reference = try Raster(referenceData)
|
||||
let gameplayReferenceSHA = "dd6c5b0e02e3a7c995056a436a4379ab617c7a0c60ddf246ad5ac9163e5239b8"
|
||||
// Source-authored stable captions and all four well borders only.
|
||||
// Exclude board cells, NEXT/HOLD previews and changing score values.
|
||||
let gameplayStaticRegions: [CGRect] = [
|
||||
CGRect(x: 32, y: 0, width: 168, height: 8),
|
||||
CGRect(x: 32, y: 32, width: 40, height: 8),
|
||||
CGRect(x: 32, y: 64, width: 40, height: 8),
|
||||
CGRect(x: 32, y: 96, width: 40, height: 8),
|
||||
CGRect(x: 216, y: 24, width: 32, height: 8),
|
||||
CGRect(x: 216, y: 80, width: 32, height: 8),
|
||||
CGRect(x: 32, y: 144, width: 48, height: 8),
|
||||
CGRect(x: 32, y: 168, width: 72, height: 8),
|
||||
CGRect(x: 118, y: 22, width: 84, height: 2),
|
||||
CGRect(x: 118, y: 184, width: 84, height: 2),
|
||||
CGRect(x: 118, y: 24, width: 2, height: 160),
|
||||
CGRect(x: 200, y: 24, width: 2, height: 160)
|
||||
]
|
||||
let gameplayReference: Raster?
|
||||
if game.slug == "quadrapassel" {
|
||||
let gameplayData = try Data(contentsOf: imported.projectDirectory.appendingPathComponent("docs/manual/images/gameplay.png"))
|
||||
guard Self.sha(gameplayData) == gameplayReferenceSHA else {
|
||||
throw ProfileFailure.message("The source-authored Quadrapassel PLAY reference changed; review it before accepting gameplay qualification")
|
||||
}
|
||||
let raster = try Raster(gameplayData)
|
||||
guard raster.width == 320, raster.height == 192 else {
|
||||
throw ProfileFailure.message("The reviewed Quadrapassel PLAY reference must use its authored 320x192 coordinates")
|
||||
}
|
||||
gameplayReference = raster
|
||||
} else { gameplayReference = nil }
|
||||
for use6309 in [false, true] {
|
||||
let output = gameOutput.appendingPathComponent(use6309 ? "candidate-6309" : "candidate-6809")
|
||||
try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)
|
||||
let working = output.appendingPathComponent("CandidateWorking.DSK")
|
||||
try disk.write(to: working, options: .withoutOverwriting)
|
||||
var settings = MachineSettings()
|
||||
settings.use6309 = use6309; settings.ram = game.fixture.ramKiB == 128 ? 0 : 1
|
||||
try await withMachine(output: output, use6309: use6309, startingMachine: settings) { model, controller, _ in
|
||||
try await model.insertDiskFromMedia(working, drive: 0, execution: .run, reset: .coldRestart)
|
||||
try await startCandidateDOS(model, controller: controller)
|
||||
let (first, titleSimilarity) = try await waitForTitle(reference: reference, controller: controller,
|
||||
output: output.appendingPathComponent("candidate-first-title.png"))
|
||||
XCTAssertEqual(first.use6309, use6309)
|
||||
XCTAssertEqual(first.ramConfiguration, UInt(settings.ram))
|
||||
XCTAssertEqual(first.videoOutput, 0); XCTAssertTrue(first.disks[0].mounted)
|
||||
XCTAssertFalse(first.debuggerDevelopmentAttached)
|
||||
XCTAssertNil(first.errorMessage)
|
||||
XCTAssertEqual(first.cpuOverclock, 1); XCTAssertEqual(first.frameInterval, 1); XCTAssertFalse(first.fastForward)
|
||||
// An idle title must remain recognizable before ordinary input.
|
||||
// A cursor blink or an animated tile alone cannot qualify a start.
|
||||
try await Task.sleep(nanoseconds: 500_000_000)
|
||||
let idle = await step(controller.snapshot)
|
||||
let titleArea = reference.width == 640 && reference.height == 480 ? VideoGeometry.fullFrame : idle.activeVideoRect
|
||||
let idleRaster = try Raster(ScreenCapture(pixels: idle.pixels, area: titleArea).png())
|
||||
let idleTitleSimilarity = idleRaster.similarity(to: reference)
|
||||
guard idle.state == .running, idle.generation == first.generation, idle.errorMessage == nil,
|
||||
idleTitleSimilarity >= 0.95 else {
|
||||
throw ProfileFailure.message("Candidate title changed before start input; inspect the idle scene before accepting a transition")
|
||||
}
|
||||
let beforePixels = try ScreenCapture(pixels: first.pixels, area: VideoGeometry.fullFrame).png()
|
||||
let before = try Raster(beforePixels)
|
||||
let key = game.slug == "quadrapassel" ? " " : "1"
|
||||
var keyboard = CocoKeyboard()
|
||||
keyboard.press(code: game.slug == "quadrapassel" ? 49 : 18, characters: key)
|
||||
let mask = keyboard.mask
|
||||
XCTAssertNotEqual(mask, 0)
|
||||
controller.setKeyboardMask(mask)
|
||||
try await Task.sleep(nanoseconds: 200_000_000)
|
||||
controller.setKeyboardMask(0)
|
||||
var progress: (VCCMachineSnapshot, Data, Double, Double)?
|
||||
var gameplayProof: (score: Double, pixels: Int, matched: Int)?
|
||||
var changedFrames = 0
|
||||
for _ in 0..<80 {
|
||||
try await Task.sleep(nanoseconds: 100_000_000)
|
||||
let snapshot = await step(controller.snapshot)
|
||||
guard snapshot.state == .running, snapshot.generation == first.generation,
|
||||
snapshot.frames > idle.frames + 4, snapshot.pasteRemaining == 0, snapshot.errorMessage == nil else { continue }
|
||||
let png = try ScreenCapture(pixels: snapshot.pixels, area: VideoGeometry.fullFrame).png()
|
||||
let difference = try Raster(png).changedPixelFraction(comparedTo: before)
|
||||
let sceneArea = reference.width == 640 && reference.height == 480 ? VideoGeometry.fullFrame : snapshot.activeVideoRect
|
||||
let scene = try Raster(ScreenCapture(pixels: snapshot.pixels, area: sceneArea).png())
|
||||
let titleSimilarity = scene.similarity(to: reference)
|
||||
let staticMatch: (score: Double, pixels: Int, matched: Int)?
|
||||
if let gameplayReference {
|
||||
let activeScene = try Raster(ScreenCapture(pixels: snapshot.pixels, area: snapshot.activeVideoRect).png())
|
||||
staticMatch = activeScene.staticForegroundMatch(to: gameplayReference, regions: gameplayStaticRegions)
|
||||
} else { staticMatch = nil }
|
||||
let gameplayReady = staticMatch.map { $0.score >= 0.95 && $0.pixels > 100 } ?? true
|
||||
changedFrames = difference >= 0.005 && titleSimilarity < 0.90 && gameplayReady ? changedFrames + 1 : 0
|
||||
if changedFrames >= 2 {
|
||||
progress = (snapshot, png, difference, titleSimilarity); gameplayProof = staticMatch; break
|
||||
}
|
||||
}
|
||||
guard let progress else { throw ProfileFailure.message("Candidate-built game did not leave its stable title scene after normal start input") }
|
||||
let (guestText, inspected): (String?, VCCMachineSnapshot) = await withCheckedContinuation { done in
|
||||
controller.inspectScreenText { done.resume(returning: ($0, $1)) }
|
||||
}
|
||||
XCTAssertNil(inspected.errorMessage)
|
||||
XCTAssertEqual(inspected.generation, first.generation)
|
||||
if let guestText {
|
||||
let lines = guestText.uppercased().split(whereSeparator: \.isNewline).map { $0.trimmingCharacters(in: .whitespaces) }
|
||||
guard !lines.contains(where: { $0 == "OK" || $0.hasPrefix("?") }) else {
|
||||
throw ProfileFailure.message("Candidate start input returned to BASIC or an error prompt instead of remaining in the game")
|
||||
}
|
||||
}
|
||||
XCTAssertEqual(progress.0.cpuOverclock, 1); XCTAssertEqual(progress.0.frameInterval, 1); XCTAssertFalse(progress.0.fastForward)
|
||||
try progress.1.write(to: output.appendingPathComponent("candidate-after-start-key.png"), options: .atomic)
|
||||
_ = await step(controller.pause); try await settle(model)
|
||||
let retainedBeforeRestart = try await model.snapshotDiskCopy(inDrive: 0)
|
||||
model.reset(); try await settle(model); model.resume(); try await settle(model)
|
||||
let retainedAfterRestart = try await model.snapshotDiskCopy(inDrive: 0)
|
||||
XCTAssertEqual(retainedAfterRestart, retainedBeforeRestart, "Cold restart must keep the owned working disk rather than replace it from a published package")
|
||||
try await startCandidateDOS(model, controller: controller)
|
||||
let (second, restartSimilarity) = try await waitForTitle(reference: reference, controller: controller,
|
||||
output: output.appendingPathComponent("candidate-restarted-title.png"))
|
||||
XCTAssertNotEqual(second.generation, first.generation)
|
||||
XCTAssertEqual(second.use6309, use6309); XCTAssertEqual(second.ramConfiguration, UInt(settings.ram))
|
||||
XCTAssertNil(second.errorMessage)
|
||||
XCTAssertEqual(second.cpuOverclock, 1); XCTAssertEqual(second.frameInterval, 1); XCTAssertFalse(second.fastForward)
|
||||
XCTAssertEqual(Self.sha(try Data(contentsOf: XCTUnwrap(build.diskURL))), expected.disk, "The frozen candidate artifact must not be the guest's writable copy")
|
||||
var gameplayReceipt: [String: Any] = [:]
|
||||
if let gameplayProof {
|
||||
gameplayReceipt = ["gameplay_reference_sha256": gameplayReferenceSHA,
|
||||
"gameplay_reference_size": [320, 192],
|
||||
"gameplay_static_regions": gameplayStaticRegions.map { [Int($0.minX), Int($0.minY), Int($0.width), Int($0.height)] },
|
||||
"gameplay_static_foreground_pixels": gameplayProof.pixels,
|
||||
"gameplay_static_matched_pixels": gameplayProof.matched,
|
||||
"gameplay_static_foreground_similarity": gameplayProof.score,
|
||||
"gameplay_static_matching_observations": changedFrames]
|
||||
}
|
||||
results.append(["game": game.slug, "cpu": use6309 ? "6309" : "6809", "host_architecture": Self.architecture,
|
||||
"source_zip_sha256": expected.sourceZIP, "makefile_sha256": expected.makefile,
|
||||
"compiler_sha256": CandidateSourceBaseline.compiler, "runtime_manifest_sha256": CandidateSourceBaseline.runtimeManifest,
|
||||
"runtime_kind": "pinned_unsigned_development_runtime", "packaged_compiler_execution": false,
|
||||
"configuration": "Release", "candidate_binary_sha256": expected.binary, "candidate_disk_sha256": expected.disk,
|
||||
"published_disk_sha256": game.fixture.diskSHA256, "candidate_is_published": false,
|
||||
"ram_kib": game.fixture.ramKiB, "first_title_foreground_similarity": titleSimilarity,
|
||||
"restart_title_foreground_similarity": restartSimilarity, "normal_start_key": key == " " ? "space" : key,
|
||||
"idle_title_foreground_similarity": idleTitleSimilarity, "post_start_title_foreground_similarity": progress.3,
|
||||
"stock_speed": true, "basic_or_error_prompt_after_start": false,
|
||||
"visible_changed_pixel_fraction": progress.2, "normal_input_fields_advanced": progress.0.frames - first.frames,
|
||||
"working_disk_preserved_across_restart": true,
|
||||
"coverage": "Exact unsigned-development-runtime rebuild, normal DOS startup, rendered title, ordinary start-key title-to-game transition and cold restart; not packaged compiler execution or a full game playthrough"].merging(gameplayReceipt) { _, proof in proof })
|
||||
try JSONSerialization.data(withJSONObject: results, options: [.prettyPrinted, .sortedKeys])
|
||||
.write(to: inputs.output.appendingPathComponent("CandidateSourceAcceptance.json"), options: .atomic)
|
||||
}
|
||||
}
|
||||
}
|
||||
XCTAssertEqual(results.count, Fixture.approved.count * 2)
|
||||
}
|
||||
|
||||
@MainActor func testPublishedFirstAndCachedPlaySourceAndManualAcceptance() async throws {
|
||||
let inputs = try await inputs()
|
||||
var results: [[String: Any]] = []
|
||||
|
||||
Reference in new issue
Block a user