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:
Brian Holman committed 2026-11-17 08:42:27 -07:00
1 parent 4abc194001
commit 5534005799
54 files changed
+2950 -435

No files matched your search

@@ -487,7 +487,8 @@ final class BASICDevelopmentModel: ObservableObject {
}
guard reviewIsCurrent?() != false, source == text else { return nil }
guard let snapshot = await machine.loadBASICSource(text, run: run, breakpoints: breakpoints,
review: prior.map { ($0, existing) }) else { message = machine.fileError ?? "BASIC transfer failed."; return nil }
review: prior.map { ($0, existing) },
reviewIsCurrent: reviewIsCurrent) else { message = machine.fileError ?? "BASIC transfer failed."; return nil }
machine.basicWorkspaceOwner = workspaceID
let loadedSource = reviewIsCurrent == nil ? await machine.readBASICSource() : snapshot.assistantLoadedSource
guard machine.basicWorkspaceOwner == workspaceID, source == text else { return nil }
+58 -7
View File
@@ -507,6 +507,8 @@ struct CMOCProjectConfiguration: Codable, Equatable, Sendable {
/// Additional build-produced floppy images reviewed for owned disk exchange.
/// These are outputs, not source inputs or arbitrary files to mount.
var playtestDisks: [String] = []
/// Concrete additional delivery files; outputDirectories are never export permissions.
var exportOutputs: [String] = []
var launchMode: CMOCLaunchMode = .quickload
var launchCommands: [String] = []
var configurations = [CMOCBuildConfiguration(name: "Debug"), CMOCBuildConfiguration(name: "Release", makeArguments: ["VCC_CONFIGURATION=Release"])]
@@ -521,7 +523,7 @@ struct CMOCProjectConfiguration: Codable, Equatable, Sendable {
var outputDirectories: [String] = []
var makefileSettings: CMOCMakefileSettings? = nil
init() {}
enum CodingKeys: CodingKey { case entrySource, makefile, buildTarget, cleanTarget, diskTarget, binary, diskImage, debugManifest, playtestDisks, launchMode, launchCommands, configurations, jobs, makefileSettings, bundledLibraries, buildSupportDirectories, resourceInputs, generatedInputs, outputDirectories }
enum CodingKeys: CodingKey { case entrySource, makefile, buildTarget, cleanTarget, diskTarget, binary, diskImage, debugManifest, playtestDisks, exportOutputs, launchMode, launchCommands, configurations, jobs, makefileSettings, bundledLibraries, buildSupportDirectories, resourceInputs, generatedInputs, outputDirectories }
init(from decoder: Decoder) throws {
self.init()
let c = try decoder.container(keyedBy: CodingKeys.self)
@@ -534,6 +536,7 @@ struct CMOCProjectConfiguration: Codable, Equatable, Sendable {
diskImage = try c.decodeIfPresent(String.self, forKey: .diskImage)
debugManifest = try c.decodeIfPresent(String.self, forKey: .debugManifest)
playtestDisks = try c.decodeIfPresent([String].self, forKey: .playtestDisks) ?? []
exportOutputs = try c.decodeIfPresent([String].self, forKey: .exportOutputs) ?? []
launchMode = try c.decodeIfPresent(CMOCLaunchMode.self, forKey: .launchMode) ?? launchMode
launchCommands = try c.decodeIfPresent([String].self, forKey: .launchCommands) ?? []
configurations = try c.decodeIfPresent([CMOCBuildConfiguration].self, forKey: .configurations) ?? configurations
@@ -554,6 +557,7 @@ struct CMOCProjectConfiguration: Codable, Equatable, Sendable {
try c.encodeIfPresent(diskImage, forKey: .diskImage); try c.encode(launchMode, forKey: .launchMode)
try c.encodeIfPresent(debugManifest, forKey: .debugManifest)
if !playtestDisks.isEmpty { try c.encode(playtestDisks, forKey: .playtestDisks) }
if !exportOutputs.isEmpty { try c.encode(exportOutputs, forKey: .exportOutputs) }
try c.encode(launchCommands, forKey: .launchCommands); try c.encode(configurations, forKey: .configurations)
try c.encode(jobs, forKey: .jobs); try c.encodeIfPresent(makefileSettings, forKey: .makefileSettings)
if !bundledLibraries.isEmpty { try c.encode(bundledLibraries, forKey: .bundledLibraries) }
@@ -592,7 +596,23 @@ struct CMOCProjectConfiguration: Codable, Equatable, Sendable {
throw CMOCBuildError.message("Additional playtest disks need distinct project-relative .dsk or .os9 output paths, separate from inputs and primary outputs.")
}
}
let concreteOutputs = ([binary, diskImage, debugManifest].compactMap { $0 } + playtestDisks +
let exportPaths = [binary, diskImage, debugManifest].compactMap { $0 } + playtestDisks + exportOutputs
guard exportPaths.count <= 64,
Set(exportPaths.map { $0.lowercased() }).count == exportPaths.count else {
throw CMOCBuildError.message("Declare at most 64 distinct concrete delivery outputs.")
}
for path in exportOutputs {
try CMOCProject.validateRelativePath(path)
guard !occupiedRoles.contains(path.lowercased()), path.split(separator: "/").count <= 32,
!path.split(separator: "/").contains(where: { [".git", ".hg", ".svn"].contains($0.lowercased()) }) else {
throw CMOCBuildError.message("Delivery outputs must be concrete generated files, separate from project inputs.")
}
}
let lowerExportPaths = exportPaths.map { $0.lowercased() }
guard !lowerExportPaths.contains(where: { path in lowerExportPaths.contains(where: { $0.hasPrefix(path + "/") }) }) else {
throw CMOCBuildError.message("Delivery output paths cannot overlap directories and files.")
}
let concreteOutputs = ([binary, diskImage, debugManifest].compactMap { $0 } + playtestDisks + exportOutputs +
(makefileSettings?.generatedResources.flatMap(\.outputs) ?? [])).map { $0.lowercased() }
let ordinaryInputs = [entrySource, makefile, CMOCProject.configurationFilename] + resourceInputs
let explicitInputs = ordinaryInputs + generatedInputs
@@ -820,7 +840,7 @@ struct CMOCProject: Equatable, Sendable {
for ext in ["map", "link"] { excluded.insert((stem + "." + ext).lowercased()) }
}
if let disk = configuration.diskImage { excluded.insert(disk.lowercased()) }
excluded.formUnion(configuration.playtestDisks.map { $0.lowercased() })
excluded.formUnion((configuration.playtestDisks + configuration.exportOutputs).map { $0.lowercased() })
if let manifest = configuration.debugManifest { excluded.insert(manifest.lowercased()) }
if let recipe = configuration.makefileSettings {
for path in recipe.generatedResources.flatMap(\.outputs) { excluded.insert(path.lowercased()) }
@@ -976,6 +996,20 @@ struct CMOCPlaytestDiskProduct: Codable, Equatable, Sendable {
let byteCount: Int
}
/// A concrete delivery product frozen at successful build completion.
struct CMOCBuildOutputProduct: Codable, Equatable, Sendable {
let relativePath: String
let byteCount: Int
let sha256: String
func identifier(artifactID: UUID) -> String {
CMOCProject.sha256(Data((artifactID.uuidString + "\n" + relativePath).utf8))
}
func fields(artifactID: UUID) -> [String: Any] {
["output_id": identifier(artifactID: artifactID), "path": relativePath,
"bytes": byteCount, "sha256": sha256]
}
}
struct CMOCBuildArtifact: Sendable {
let id: UUID
let directory: URL
@@ -998,6 +1032,7 @@ struct CMOCBuildArtifact: Sendable {
let playtestDiskProducts: [CMOCPlaytestDiskProduct]
let debugManifestRelativePath: String?
let outputPaths: [String]
let exportProducts: [CMOCBuildOutputProduct]
let configurationName: String
let action: CMOCBuildAction
var hasBinary: Bool { binaryRelativePath != nil && !binaryData.isEmpty }
@@ -1016,7 +1051,7 @@ struct CMOCBuildArtifact: Sendable {
entrySourcePath: String = "main.c", binaryRelativePath: String? = "main.bin", diskRelativePath: String? = nil,
outputPaths: [String] = [], configurationName: String = "Debug", action: CMOCBuildAction = .build,
debugManifestRelativePath: String? = nil, diskSHA256: String? = nil, buildOutput: CMOCBuildOutput? = nil,
playtestDiskProducts: [CMOCPlaytestDiskProduct] = []) {
playtestDiskProducts: [CMOCPlaytestDiskProduct] = [], exportProducts: [CMOCBuildOutputProduct] = []) {
self.id = id; self.directory = directory; self.source = source; self.sourceData = sourceData; self.sourceSHA256 = sourceSHA256
self.binaryData = binaryData; self.buildLog = buildLog; self.buildOutput = buildOutput; self.sources = sources ?? [entrySourcePath: sourceData]
self.sourceHashes = self.sources.mapValues(CMOCProject.sha256)
@@ -1026,6 +1061,7 @@ struct CMOCBuildArtifact: Sendable {
self.debugManifestRelativePath = debugManifestRelativePath
self.diskSHA256 = diskSHA256
self.playtestDiskProducts = playtestDiskProducts
self.exportProducts = exportProducts
self.configurationName = configurationName; self.action = action
}
func matches(source: String) -> Bool { sourceSHA256 == CMOCProject.sha256(Data(source.utf8)) }
@@ -1588,10 +1624,11 @@ final class CMOCBuildService: @unchecked Sendable {
let supportKey = CMOCProject.sha256(try libraryEncoder.encode(supportIdentity))
// A newly reviewed media declaration cannot inherit an incidental old
// image from an earlier cache. Empty declarations retain legacy keys.
let exportKey = settings.exportOutputs.isEmpty ? "" : "\nexport-outputs:" + CMOCProject.sha256(try libraryEncoder.encode(settings.exportOutputs))
let playtestMediaKey = settings.playtestDisks.isEmpty ? "" :
"\nplaytest-disks:" + CMOCProject.sha256(try libraryEncoder.encode(settings.playtestDisks))
let cacheKey = CMOCProject.sha256(Data((project.directory.resolvingSymlinksInPath().path + "\n" + name + "\n" +
configuration.makeArguments.joined(separator: "\n") + "\n" + libraryKey + "\n" + supportKey + "\n" + toolchain.path + "\n" + CMOCProject.sha256(manifest) + playtestMediaKey).utf8))
configuration.makeArguments.joined(separator: "\n") + "\n" + libraryKey + "\n" + supportKey + "\n" + toolchain.path + "\n" + CMOCProject.sha256(manifest) + playtestMediaKey + exportKey).utf8))
let cache = try incrementalWorkspaceRoot().appendingPathComponent(cacheKey)
let workspace = cache.appendingPathComponent("project")
let indexURL = cache.appendingPathComponent("inputs.json")
@@ -1750,6 +1787,19 @@ final class CMOCBuildService: @unchecked Sendable {
sha256: CMOCProject.sha256(data), byteCount: data.count))
}
}
var exportProducts: [CMOCBuildOutputProduct] = []
if requiresProducts {
let declared = [binaryPath, diskPath, settings.debugManifest.flatMap { products[$0] == nil ? nil : $0 }].compactMap { $0 } + settings.playtestDisks + settings.exportOutputs
var total = 0
for path in declared {
guard let data = products[path], data.count <= CMOCProject.maximumFileBytes,
total <= 128 * 1024 * 1024 - data.count else {
throw CMOCBuildError.validation(message: "Make did not produce a bounded declared delivery file: " + path, log: log, capture: combinedOutput)
}
total += data.count
exportProducts.append(CMOCBuildOutputProduct(relativePath: path, byteCount: data.count, sha256: CMOCProject.sha256(data)))
}
}
try control.checkCancellation(log: log)
let id = UUID()
let result = buildRoot.appendingPathComponent(id.uuidString)
@@ -1773,7 +1823,7 @@ final class CMOCBuildService: @unchecked Sendable {
binaryRelativePath: binaryPath, diskRelativePath: diskPath, outputPaths: products.keys.sorted(), configurationName: name, action: action,
debugManifestRelativePath: settings.debugManifest,
diskSHA256: diskPath.flatMap { products[$0] }.map(CMOCProject.sha256), buildOutput: combinedOutput,
playtestDiskProducts: playtestDiskProducts)
playtestDiskProducts: playtestDiskProducts, exportProducts: exportProducts)
try buildHistory.record(artifact, project: project.directory)
frozen = true; succeeded = true
return artifact
@@ -1831,7 +1881,8 @@ final class CMOCBuildService: @unchecked Sendable {
let physicalDirectory = URL(fileURLWithPath: String(cString: physicalPath), isDirectory: true)
free(physicalPath)
let artifact = CMOCBuildArtifact(id: id, directory: physicalDirectory, source: source,
sourceData: sourceData, sourceSHA256: CMOCProject.sha256(sourceData), binaryData: binary, buildLog: output.text, buildOutput: control.capturedOutput)
sourceData: sourceData, sourceSHA256: CMOCProject.sha256(sourceData), binaryData: binary, buildLog: output.text, buildOutput: control.capturedOutput,
exportProducts: [CMOCBuildOutputProduct(relativePath: "main.bin", byteCount: binary.count, sha256: CMOCProject.sha256(binary))])
try control.checkCancellation()
try buildHistory.record(artifact, project: project.directory)
succeeded = true
+1 -1
View File
@@ -97,7 +97,7 @@ struct CMOCProjectInputManifest: Equatable, Sendable {
let effective = CMOCProject(directory: project.directory, configuration: configuration)
let recipe = configuration.makefileSettings
let generatedOutputs = Set(recipe?.generatedResources.flatMap(\.outputs) ?? [])
var products = generatedOutputs.union(configuration.playtestDisks)
var products = generatedOutputs.union(configuration.playtestDisks).union(configuration.exportOutputs)
for path in [configuration.binary, configuration.diskImage, configuration.debugManifest].compactMap({ $0 }) {
products.insert(path)
}
+272
View File
@@ -0,0 +1,272 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import Foundation
import Darwin
/// A connection-scoped, revocable write grant. It never follows a user-selected
/// path supplied over MCP: the destination was selected in the native app.
final class MCPBuildExporter: @unchecked Sendable {
static let maximumFiles = 64
static let maximumSetBytes = 128 * 1024 * 1024
static let maximumSessionBytes = 512 * 1024 * 1024
static let maximumRequests = 64
struct Identity: Equatable, Sendable {
let device: dev_t
let inode: ino_t
init(_ value: stat) { device = value.st_dev; inode = value.st_ino }
}
struct Source: Sendable {
let artifactID: UUID
let directory: URL
let products: [CMOCBuildOutputProduct]
let identity: Identity
init(_ artifact: CMOCBuildArtifact) throws {
artifactID = artifact.id; directory = artifact.directory; products = artifact.exportProducts
let fd = try MCPBuildExporter.directory(artifact.directory)
defer { close(fd) }
identity = try MCPBuildExporter.identity(fd)
}
}
struct Delivery: Sendable {
let directory: String
let products: [CMOCBuildOutputProduct]
}
let destinationID = UUID().uuidString
private let root: URL
private let rootIdentity: Identity
private let state = NSLock()
private var valid = true
// Only used by authored race/failure fixtures, never populated by public input.
var beforeCommit: (@Sendable () throws -> Void)?
var afterFile: (@Sendable (Int) throws -> Void)?
init(destination: URL) throws {
root = destination.standardizedFileURL
let fd = try Self.directory(root); defer { close(fd) }
rootIdentity = try Self.identity(fd)
}
func invalidate() { state.lock(); valid = false; state.unlock() }
private func check() throws {
try Task.checkCancellation()
state.lock(); defer { state.unlock() }
guard valid else { throw Self.failure("access_denied") }
}
private static func failure(_ text: String) -> CMOCBuildError { .message(text) }
private static func identity(_ descriptor: Int32) throws -> Identity {
var value = stat()
guard fstat(descriptor, &value) == 0, value.st_mode & S_IFMT == S_IFDIR else {
throw failure("export_directory_unavailable")
}
return Identity(value)
}
/// Follow only Apple's standard /tmp and /var aliases, never arbitrary links.
private static func canonicalPath(_ url: URL) -> String {
let path = url.standardizedFileURL.path
return path == "/tmp" || path.hasPrefix("/tmp/") || path == "/var" || path.hasPrefix("/var/") ? "/private" + path : path
}
private static func directory(_ url: URL) throws -> Int32 {
let normalized = canonicalPath(url)
guard normalized.hasPrefix("/") else { throw failure("invalid_export_directory") }
var held = open("/", O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)
guard held >= 0 else { throw failure("export_directory_unavailable") }
do {
for component in normalized.split(separator: "/") {
let next = openat(held, String(component), O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)
guard next >= 0 else { throw failure("export_directory_changed_or_linked") }
close(held); held = next
}
return held
} catch { close(held); throw error }
}
private func destination() throws -> Int32 {
try check()
let fd = try Self.directory(root)
do {
guard try Self.identity(fd) == rootIdentity else { throw Self.failure("export_destination_changed") }
return fd
} catch { close(fd); throw error }
}
private func source(_ value: Source) throws -> Int32 {
try check()
let fd = try Self.directory(value.directory)
do {
guard try Self.identity(fd) == value.identity else { throw Self.failure("export_artifact_changed") }
return fd
} catch { close(fd); throw error }
}
private static func parent(_ root: Int32, path: String, create: Bool) throws -> (Int32, String) {
try CMOCProject.validateRelativePath(path)
let components = path.split(separator: "/").map(String.init)
guard components.count <= 32, components.allSatisfy({ $0.utf8.count <= 255 }) else { throw failure("invalid_export_path") }
var held = dup(root)
guard held >= 0 else { throw failure("export_directory_unavailable") }
do {
for component in components.dropLast() {
if create, mkdirat(held, component, 0o700) != 0, errno != EEXIST { throw failure("export_write_failed") }
let next = openat(held, component, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)
guard next >= 0 else { throw failure("export_path_changed_or_linked") }
close(held); held = next
}
return (held, components.last!)
} catch { close(held); throw error }
}
private func read(_ product: CMOCBuildOutputProduct, from directory: Int32) throws -> Data {
try check()
guard (0...CMOCProject.maximumFileBytes).contains(product.byteCount) else { throw Self.failure("export_output_too_large") }
let (parent, leaf) = try Self.parent(directory, path: product.relativePath, create: false)
defer { close(parent) }
let fd = openat(parent, leaf, O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC)
guard fd >= 0 else { throw Self.failure("export_output_unavailable") }
let file = FileHandle(fileDescriptor: fd, closeOnDealloc: true)
defer { try? file.close() }
var before = stat()
guard fstat(fd, &before) == 0, before.st_mode & S_IFMT == S_IFREG, before.st_nlink == 1,
before.st_size == off_t(product.byteCount) else { throw Self.failure("export_output_changed_or_linked") }
var data = Data()
while data.count < product.byteCount {
try check()
let chunk = try file.read(upToCount: min(65536, product.byteCount - data.count)) ?? Data()
guard !chunk.isEmpty else { throw Self.failure("export_output_changed") }
data.append(chunk)
}
var after = stat(), named = stat()
guard fstat(fd, &after) == 0, Identity(before) == Identity(after), before.st_size == after.st_size,
before.st_mtimespec.tv_sec == after.st_mtimespec.tv_sec, before.st_mtimespec.tv_nsec == after.st_mtimespec.tv_nsec,
fstatat(parent, leaf, &named, AT_SYMLINK_NOFOLLOW) == 0,
named.st_mode & S_IFMT == S_IFREG, named.st_nlink == 1, Identity(named) == Identity(after),
CMOCProject.sha256(data) == product.sha256 else { throw Self.failure("export_output_changed") }
return data
}
private func verifyContents(_ descriptor: Int32, products: [CMOCBuildOutputProduct], flush: Bool = false) throws {
let expected = Set(products.map(\.relativePath))
var observed: Set<String> = []
var visited = 0
func walk(_ fd: Int32, prefix: String, depth: Int) throws {
try check()
guard depth <= 32 else { throw Self.failure("export_delivery_changed") }
let copy = dup(fd)
guard copy >= 0, let stream = fdopendir(copy) else {
if copy >= 0 { close(copy) }; throw Self.failure("export_delivery_changed")
}
defer { closedir(stream) }
while let entry = readdir(stream) {
let name = withUnsafePointer(to: &entry.pointee.d_name) {
$0.withMemoryRebound(to: CChar.self, capacity: Int(entry.pointee.d_namlen) + 1) { String(cString: $0) }
}
if name == "." || name == ".." { continue }
visited += 1
guard visited <= Self.maximumFiles * 33 else { throw Self.failure("export_delivery_changed") }
let path = prefix.isEmpty ? name : prefix + "/" + name
var info = stat()
guard fstatat(fd, name, &info, AT_SYMLINK_NOFOLLOW) == 0 else { throw Self.failure("export_delivery_changed") }
if info.st_mode & S_IFMT == S_IFDIR {
guard expected.contains(where: { $0.hasPrefix(path + "/") }) else { throw Self.failure("export_delivery_changed") }
let child = openat(fd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)
guard child >= 0 else { throw Self.failure("export_delivery_changed") }
defer { close(child) }
try walk(child, prefix: path, depth: depth + 1)
} else {
guard info.st_mode & S_IFMT == S_IFREG, info.st_nlink == 1, expected.contains(path) else { throw Self.failure("export_delivery_changed") }
observed.insert(path)
}
}
if flush, fsync(fd) != 0 { throw Self.failure("export_write_failed") }
}
try walk(descriptor, prefix: "", depth: 0)
guard observed == expected else { throw Self.failure("export_delivery_changed") }
for product in products { _ = try read(product, from: descriptor) }
}
/// Creates a complete new set with an exclusive atomic directory rename.
/// No existing delivery is removed or repaired. The caller binds Source and
/// the request ID to the original connection/build/revision before calling.
func export(source value: Source, products: [CMOCBuildOutputProduct], setName: String) throws -> Delivery {
guard !products.isEmpty, products.count <= Self.maximumFiles,
Set(products.map { $0.relativePath.lowercased() }).count == products.count,
products.allSatisfy({ value.products.contains($0) && (0...CMOCProject.maximumFileBytes).contains($0.byteCount) }),
products.reduce(0, { $0 + $1.byteCount }) <= Self.maximumSetBytes,
setName.hasPrefix("VCC-"), setName.utf8.count < 200, !setName.contains("/") else { throw Self.failure("invalid_export_selection") }
let sourcePath = Self.canonicalPath(value.directory), destinationPath = Self.canonicalPath(root)
guard destinationPath != sourcePath, !destinationPath.hasPrefix(sourcePath + "/") else { throw Self.failure("export_destination_overlaps_artifact") }
let destination = try destination(), source = try source(value)
defer { close(destination); close(source) }
let stageName = ".vccplus-export-" + UUID().uuidString
guard mkdirat(destination, stageName, 0o700) == 0 else { throw Self.failure("export_write_failed") }
let stage = openat(destination, stageName, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)
guard stage >= 0 else { throw Self.failure("export_write_failed") }
defer { close(stage) }
var created: [(String, Identity)] = []
var committed = false
defer {
if !committed {
// Remove only this transaction's unchanged files; never recursively
// erase unexpected files planted in a failed staging directory.
for (path, identity) in created.reversed() {
if let (parent, leaf) = try? Self.parent(stage, path: path, create: false) {
var named = stat()
if fstatat(parent, leaf, &named, AT_SYMLINK_NOFOLLOW) == 0, Identity(named) == identity { _ = unlinkat(parent, leaf, 0) }
close(parent)
}
}
let directories = Set(products.flatMap { product -> [String] in
let parts = product.relativePath.split(separator: "/"); return (1..<parts.count).map { parts.prefix($0).joined(separator: "/") }
}).sorted { $0.count > $1.count }
for path in directories {
if let (parent, leaf) = try? Self.parent(stage, path: path, create: false) { _ = unlinkat(parent, leaf, AT_REMOVEDIR); close(parent) }
}
_ = unlinkat(destination, stageName, AT_REMOVEDIR)
}
}
for (index, product) in products.enumerated() {
let checkDestination = try self.destination(); close(checkDestination)
let checkSource = try self.source(value); close(checkSource)
let bytes = try read(product, from: source)
let (parent, leaf) = try Self.parent(stage, path: product.relativePath, create: true)
defer { close(parent) }
let fd = openat(parent, leaf, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o600)
guard fd >= 0 else { throw Self.failure("export_write_failed") }
let file = FileHandle(fileDescriptor: fd, closeOnDealloc: true)
defer { try? file.close() }
var info = stat()
guard fstat(fd, &info) == 0 else { throw Self.failure("export_write_failed") }
created.append((product.relativePath, Identity(info)))
for offset in stride(from: 0, to: bytes.count, by: 65536) {
try check()
try file.write(contentsOf: bytes.subdata(in: offset..<min(bytes.count, offset + 65536)))
}
guard fsync(fd) == 0 else { throw Self.failure("export_write_failed") }
try afterFile?(index)
}
// Verify the actual staged bytes and source hashes again before commit.
for product in products { _ = try read(product, from: stage); _ = try read(product, from: source) }
try beforeCommit?()
try verifyContents(stage, products: products, flush: true)
for product in products { _ = try read(product, from: source) }
let currentDestination = try self.destination(), currentSource = try self.source(value)
defer { close(currentDestination); close(currentSource) }
var stageInfo = stat(), namedStage = stat()
guard fstat(stage, &stageInfo) == 0, fstatat(destination, stageName, &namedStage, AT_SYMLINK_NOFOLLOW) == 0,
namedStage.st_mode & S_IFMT == S_IFDIR, Identity(stageInfo) == Identity(namedStage) else { throw Self.failure("export_staging_changed") }
try check()
// Revocation cannot race between the final authority check and rename.
state.lock()
guard valid, !Task.isCancelled else { state.unlock(); throw Self.failure("access_denied") }
let renamed = renameatx_np(destination, stageName, destination, setName, UInt32(RENAME_EXCL))
let renameError = errno
if renamed == 0 { committed = true }
state.unlock()
guard renamed == 0 else {
throw Self.failure(renameError == EEXIST ? "export_destination_conflict" : "export_commit_failed")
}
// The staged file data was flushed before rename; never delete an exposed
// delivery to roll back a directory-flush failure.
guard fsync(destination) == 0 else { throw Self.failure("export_commit_uncertain") }
return Delivery(directory: setName, products: products)
}
func verify(_ delivery: Delivery) throws {
let destination = try destination(); defer { close(destination) }
let directory = openat(destination, delivery.directory, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)
guard directory >= 0 else { throw Self.failure("export_delivery_changed") }
defer { close(directory) }
try verifyContents(directory, products: delivery.products)
let current = try self.destination(); close(current)
}
}
+162 -15
View File
@@ -94,7 +94,7 @@ struct MCPProjectRefreshRecord {
let next = offset + bounded.items.count
return (bounded.items, next < entries.count ? next : nil, bounded.truncated)
}
static let safeTools: Set<String> = ["get_capabilities", "get_machine_status", "get_build", "get_build_log", "get_project_refresh", "read_project_inputs", "refresh_project", "read_project_file", "get_proposal"]
static let safeTools: Set<String> = ["get_capabilities", "get_machine_status", "get_build", "get_build_log", "get_project_refresh", "read_project_inputs", "refresh_project", "read_project_file", "get_proposal", "export_build_outputs", "get_build_export"]
}
/// The grant binds reviewed drafts and build artifacts to one selected project.
@@ -152,9 +152,42 @@ final class MCPCMOC: ObservableObject {
private var approvedRecipeID: String?
@Published var allowProjectMakefile = false
@Published var allowPlaytests = false
@Published var allowBuildExport = false
@Published fileprivate private(set) var exportFolderName: String?
private var selectedExportDirectory: URL?
fileprivate var buildExporter: MCPBuildExporter?
private var exportSources: [String: (revision: Int, configuration: String, source: MCPBuildExporter.Source)] = [:]
private struct ExportRecord {
let identity: String
let base: [String: Any]
var status = "exporting"
var delivery: MCPBuildExporter.Delivery?
var reason: String?
var fields: [String: Any] {
var value = base
value["status"] = status; value["busy"] = status == "exporting"
if let delivery {
value["delivery_directory"] = delivery.directory
let artifactID = UUID(uuidString: base["artifact_id"] as? String ?? "")!
value["outputs"] = delivery.products.map { product -> [String: Any] in
var fields = product.fields(artifactID: artifactID)
fields["relative_filename"] = delivery.directory + "/" + product.relativePath
return fields
}
}
if let reason { value["error"] = reason }
return value
}
}
private var exportRecords: [String: ExportRecord] = [:]
private var exportRequests: [String: String] = [:]
private var exportWork: Task<Void, Never>?
private var exporting = false
private var exportReservedBytes = 0
fileprivate private(set) var playtestsApproved = false
private var callContextApproved = false
private var playtestMediaApproved = false
private var playtestMultiDriveApproved = false
#if DEBUG
private var regressionPlaytestHelper: URL?
private var regressionStarterKit: StarterKit?
@@ -376,9 +409,11 @@ final class MCPCMOC: ObservableObject {
#if DEBUG
func exportCallContextRegression(_ model: CMOCDevelopmentModel, at destination: URL, playtests: Bool = true,
helperURL: URL? = nil, roms: URL? = nil) async throws {
helperURL: URL? = nil, roms: URL? = nil, exportFolder: URL? = nil) async throws {
allowProjectMakefile = true
allowPlaytests = playtests
allowBuildExport = exportFolder != nil; selectedExportDirectory = exportFolder
exportFolderName = exportFolder?.lastPathComponent
try await grant(model, at: destination)
regressionPlaytestHelper = helperURL
regressionStarterKit = roms.map { StarterKit(directory: $0) }
@@ -401,7 +436,7 @@ final class MCPCMOC: ObservableObject {
private func sanitized(_ text: String) -> String {
var result = text
for root in [scratch, model?.project?.directory].compactMap({ $0 }) {
for root in [scratch, model?.project?.directory, selectedExportDirectory].compactMap({ $0 }) {
result = result.replacingOccurrences(of: root.path, with: "<project>")
}
return String(result.prefix(2000))
@@ -588,6 +623,8 @@ final class MCPCMOC: ObservableObject {
presentationIsCurrent: (@MainActor () -> Bool)? = nil) async throws {
let id = model.assistantProjectID, ticket = UUID(), secret = UUID().uuidString + UUID().uuidString
let approvedPlaytests = allowPlaytests
let approvedExport = allowBuildExport, approvedExportDirectory = selectedExportDirectory
if approvedExport && approvedExportDirectory == nil { throw problem("Choose a delivery folder before sharing build export access.") }
let cleanup = revoke()
session = ticket
pendingModel = model
@@ -597,6 +634,7 @@ final class MCPCMOC: ObservableObject {
guard let project = model.project else { throw problem("project_unavailable") }
let scope = try MCPCMOCProject(project: project, files: model.files.map(\.relativePath), customMake: allowProjectMakefile)
let captured = try await capture(model, scope: scope, updatedScope: true, expandedSupport: true)
let exporter = try await Task.detached { try approvedExport ? MCPBuildExporter(destination: approvedExportDirectory!) : nil }.value
guard session == ticket, model.assistantProjectID == id, presentationIsCurrent?() != false else { throw problem("stale_revision") }
let dir = FileManager.default.temporaryDirectory.appendingPathComponent("vcc-c-project-" + UUID().uuidString)
let handler: MCPTransport.Handler = { [weak self] data in
@@ -607,7 +645,7 @@ final class MCPCMOC: ObservableObject {
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700])
do {
let server = try MCPTransport(handler: handler)
let bytes = try JSONSerialization.data(withJSONObject: ["token": secret, "kind": "cmoc", "toolset": 12, "playtestVideo": approvedPlaytests, "playtestMedia": approvedPlaytests, "playtestCallContext": approvedPlaytests, "projectRefresh": true, "projectDiagnostics": true, "playtestAudio": approvedPlaytests, "playtestProcessors": approvedPlaytests, "playtestJoysticks": approvedPlaytests, "customMake": scope.customMake, "playtest": approvedPlaytests, "canPropose": true,
let bytes = try JSONSerialization.data(withJSONObject: ["token": secret, "kind": "cmoc", "toolset": 13, "buildExport": approvedExport, "playtestMultiDrive": approvedPlaytests, "playtestVideo": approvedPlaytests, "playtestMedia": approvedPlaytests, "playtestCallContext": approvedPlaytests, "projectRefresh": true, "projectDiagnostics": true, "playtestAudio": approvedPlaytests, "playtestProcessors": approvedPlaytests, "playtestJoysticks": approvedPlaytests, "customMake": scope.customMake, "playtest": approvedPlaytests, "canPropose": true,
"socket": server.unixPath, "port": Int(server.port), "version": 1])
return (server, try MCPGrantFile(create: destination, data: bytes))
} catch { try? FileManager.default.removeItem(at: dir); throw error }
@@ -616,12 +654,14 @@ final class MCPCMOC: ObservableObject {
Task.detached { server.stop(); file.remove(); try? FileManager.default.removeItem(at: dir) }
throw problem("stale_revision")
}
self.buildExporter = exporter
self.server = server; self.file = file; token = secret; projectID = id; self.model = model
scratch = dir; service = CMOCBuildService(toolchain: model.service.toolchain, buildRoot: dir.appendingPathComponent("Builds"))
snapshot = captured.live; diskSnapshot = captured.disk; workspaceEpoch = captured.epoch; makeSnapshot = captured.make; approvedInputs = captured.manifest; revision = 0
self.playtestsApproved = approvedPlaytests
self.callContextApproved = approvedPlaytests
self.playtestMediaApproved = approvedPlaytests
self.playtestMultiDriveApproved = approvedPlaytests
self.scope = captured.scope; templateDirectives = captured.directives; approvedRecipeID = captured.make?.recipeID
active = true; status = "Connected to " + (model.project?.directory.lastPathComponent ?? "Hello Disk")
}
@@ -629,8 +669,11 @@ final class MCPCMOC: ObservableObject {
@discardableResult func revoke() -> Task<Void, Never> {
let playtestCleanup = playtest?.invalidate()
let old = server, grant = file, dir = scratch, work = buildTask, guest = runTask
buildExporter?.invalidate(); buildExporter = nil
let exportTask = exportWork; exportTask?.cancel(); exportWork = nil
exportRecords.removeAll(); exportRequests.removeAll(); exportSources.removeAll(); exporting = false; exportReservedBytes = 0
session = UUID(); token = ""; projectID = nil; active = false; model = nil; pendingModel = nil
callContextApproved = false; playtestMediaApproved = false
callContextApproved = false; playtestMediaApproved = false; playtestMultiDriveApproved = false
#if DEBUG
regressionPlaytestHelper = nil; regressionStarterKit = nil
#endif
@@ -649,7 +692,7 @@ final class MCPCMOC: ObservableObject {
await startupCleanup?.value
await playtestCleanup?.value
old?.stop(); grant?.remove()
await work?.value; await guest?.value
await work?.value; await guest?.value; await exportTask?.value
if let dir { try? FileManager.default.removeItem(at: dir) }
}
}
@@ -698,7 +741,7 @@ final class MCPCMOC: ObservableObject {
if let latestRefreshID, let record = refreshRecords[latestRefreshID] { fields["refresh"] = projectRefreshFields(record) }
result = fields
case "get_capabilities" where args.isEmpty:
result = ["tools": Self.tools + (callContextApproved ? ["get_call_context"] : []) + (playtestMediaApproved ? ["list_playtest_media", "exchange_playtest_media"] : []) + (playtestsApproved ? ["list_playtest_disks", "start_playtest", "playtest_input", "get_playtest_input", "playtest_debug", "capture_playtest", "capture_playtest_graphics", "capture_playtest_audio", "start_playtest_video", "stop_playtest_video", "read_playtest_video", "restart_playtest", "stop_playtest"] : []), "playtest_media_exchange": playtestMediaApproved, "playtest_media_drive": "FD0", "playtest_media_maximum_disks": 9, "playtest_media_maximum_disk_bytes": 512 * 1024, "call_context": callContextApproved, "call_context_maximum_stack_bytes": 64, "input_diagnostics": true, "playtest_joystick_input": playtestsApproved, "playtest_joystick_interfaces": playtestsApproved ? ["standard"] : [], "playtest_joystick_axis_min": 0, "playtest_joystick_axis_max": 16383, "playtest_joystick_axis_center": 8191, "owned_playtests": playtestsApproved, "async_playtest_start": playtestsApproved, "retained_playtest_disks": playtestsApproved, "period_key": playtestsApproved, "graphics_buffer_capture": playtestsApproved, "custom_gime_canvases": playtestsApproved, "source_only_debugging": playtestsApproved, "verified_flat_debugging": playtestsApproved, "video_capture": playtestsApproved, "video_capture_maximum_fields": 3600, "video_capture_maximum_clips": 4, "video_capture_maximum_bytes": 64 * 1024 * 1024, "video_capture_retained_maximum_bytes": 256 * 1024 * 1024, "video_capture_chunk_maximum_bytes": 65536, "video_capture_guest_only": true, "video_capture_optional_audio": true, "video_capture_ui_cues": false, "audio_capture": playtestsApproved, "audio_capture_maximum_fields": 120, "audio_capture_maximum_clips": 16, "audio_capture_maximum_bytes": 4 * 1024 * 1024, "build_diagnostics": true, "project_refresh": true, "input_status": refreshProblem ?? "approved", "changed_input_paths": Array(observedInputChanges.prefix(128)).map(\.path), "changed_input_paths_total": observedInputChanges.count, "changed_input_paths_truncated": observedInputChanges.count > 128, "kind": "cmoc", "app": "VCC Plus OSS",
result = ["tools": Self.tools + (buildExporter != nil ? ["export_build_outputs", "get_build_export"] : []) + (callContextApproved ? ["get_call_context"] : []) + (playtestMediaApproved ? ["list_playtest_media", "exchange_playtest_media"] : []) + (playtestsApproved ? ["list_playtest_disks", "start_playtest", "playtest_input", "get_playtest_input", "playtest_debug", "capture_playtest", "capture_playtest_graphics", "capture_playtest_audio", "start_playtest_video", "stop_playtest_video", "read_playtest_video", "restart_playtest", "stop_playtest"] : []), "build_output_export": buildExporter != nil, "export_destinations": buildExporter.map { [["destination_id": $0.destinationID, "kind": "approved_folder"]] } ?? [], "export_maximum_files": MCPBuildExporter.maximumFiles, "export_maximum_file_bytes": CMOCProject.maximumFileBytes, "export_maximum_set_bytes": MCPBuildExporter.maximumSetBytes, "export_maximum_session_bytes": MCPBuildExporter.maximumSessionBytes, "export_maximum_requests": MCPBuildExporter.maximumRequests, "playtest_media_exchange": playtestMediaApproved, "playtest_media_drive": "FD0", "playtest_media_drives": playtestMultiDriveApproved ? [0, 1, 2, 3] : [0], "playtest_media_version": playtestMultiDriveApproved ? 2 : 1, "playtest_media_write_protection": playtestMultiDriveApproved, "playtest_media_maximum_disks": 9, "playtest_media_maximum_disk_bytes": 512 * 1024, "call_context": callContextApproved, "call_context_maximum_stack_bytes": 64, "input_diagnostics": true, "playtest_joystick_input": playtestsApproved, "playtest_joystick_interfaces": playtestsApproved ? ["standard"] : [], "playtest_joystick_axis_min": 0, "playtest_joystick_axis_max": 16383, "playtest_joystick_axis_center": 8191, "owned_playtests": playtestsApproved, "async_playtest_start": playtestsApproved, "retained_playtest_disks": playtestsApproved, "period_key": playtestsApproved, "graphics_buffer_capture": playtestsApproved, "custom_gime_canvases": playtestsApproved, "source_only_debugging": playtestsApproved, "verified_flat_debugging": playtestsApproved, "video_capture": playtestsApproved, "video_capture_maximum_fields": 3600, "video_capture_maximum_clips": 4, "video_capture_maximum_bytes": 64 * 1024 * 1024, "video_capture_retained_maximum_bytes": 256 * 1024 * 1024, "video_capture_chunk_maximum_bytes": 65536, "video_capture_guest_only": true, "video_capture_optional_audio": true, "video_capture_ui_cues": false, "audio_capture": playtestsApproved, "audio_capture_maximum_fields": 120, "audio_capture_maximum_clips": 16, "audio_capture_maximum_bytes": 4 * 1024 * 1024, "build_diagnostics": true, "project_refresh": true, "input_status": refreshProblem ?? "approved", "changed_input_paths": Array(observedInputChanges.prefix(128)).map(\.path), "changed_input_paths_total": observedInputChanges.count, "changed_input_paths_truncated": observedInputChanges.count > 128, "kind": "cmoc", "app": "VCC Plus OSS",
"mutation_request_limit": MCPPlaytest.mutationRequestLimit, "stop_retention_exempt": true,
"playtest_processors": playtestsApproved ? ["MC6809", "HD6309"] : [],
"playtest_default_processor": "MC6809", "playtest_processor_selection": playtestsApproved,
@@ -722,6 +765,12 @@ final class MCPCMOC: ObservableObject {
facts["run_requirement"] = playtestsApproved ? "Owned playtests may cold-boot a copy of the current artifact disk or a selected retained test disk in an isolated 512 KB MC6809 or HD6309 worker. MC6809 is the default; the guest controls HD6309 execution mode. Debug evidence stays bound to the current artifact and is checked against runtime bytes." : "Start in VCC Plus; source debugging requires a verified map matching the delivered binary."
return pack(["result": facts])
}
case "export_build_outputs":
result = try await exportBuildOutputs(args, projectID: id, owner: owner)
case "get_build_export":
guard args.count == 2, args["project_id"] as? String == id, buildExporter != nil,
let exportID = args["export_id"] as? String, let record = exportRecords[exportID] else { throw problem("unknown_export") }
result = record.fields
case "get_machine_status" where args.isEmpty:
let observed = await model.machine.mcpReadinessSnapshot()
let tools = CMOCBuildService.requiredExecutables + ["mcpp"] +
@@ -1098,6 +1147,7 @@ final class MCPCMOC: ObservableObject {
var origin = "verified_artifact"
var originArtifactID: String? = artifact.id.uuidString
var originArtifactDiskSHA256: String? = expectedDisk
var selectedWriteProtected: Bool?
if let retainedID, let retainedSHA {
start.updatePhase("reading_retained_disk")
let saved = try await MCPPlaytestDiskStore.load(directory: storage.directory, id: retainedID,
@@ -1105,12 +1155,13 @@ final class MCPCMOC: ObservableObject {
selectedDisk = saved.data; origin = saved.record.provenance.origin
originArtifactID = saved.record.provenance.originArtifactID
originArtifactDiskSHA256 = saved.record.provenance.originArtifactDiskSHA256
selectedWriteProtected = saved.record.provenance.writeProtected
}
guard current() else { throw problem("stale_run") }
let provenance = MCPPlaytestDiskStore.Provenance(projectKey: storage.key, artifactID: artifact.id.uuidString,
artifactDiskSHA256: expectedDisk, parentDiskID: retainedID, origin: origin,
originArtifactID: originArtifactID, originArtifactDiskSHA256: originArtifactDiskSHA256,
mediaKey: playtestMediaApproved ? "primary" : nil, mediaBaseSHA256: playtestMediaApproved ? expectedDisk : nil)
mediaKey: playtestMediaApproved ? "primary" : nil, mediaBaseSHA256: playtestMediaApproved ? expectedDisk : nil, writeProtected: selectedWriteProtected)
var media: [MCPPlaytestMedium]?
if playtestMediaApproved {
var selected = try await artifactMedia(artifact, projectKey: storage.key, primaryData: payload.2)
@@ -1128,7 +1179,7 @@ final class MCPCMOC: ObservableObject {
let origin = MCPPlaytestDiskStore.Provenance(projectKey: storage.key, artifactID: artifact.id.uuidString,
artifactDiskSHA256: expectedDisk, parentDiskID: diskID, origin: prior.origin,
originArtifactID: prior.originArtifactID, originArtifactDiskSHA256: prior.originArtifactDiskSHA256,
mediaKey: item.key, mediaBaseSHA256: item.baseSHA256)
mediaKey: item.key, mediaBaseSHA256: item.baseSHA256, writeProtected: prior.writeProtected)
selected[index] = MCPPlaytestMedium(id: item.id, name: item.name, key: item.key,
baseSHA256: item.baseSHA256, data: copy.data, provenance: origin)
}
@@ -1151,7 +1202,7 @@ final class MCPCMOC: ObservableObject {
bootCommands: scope.configuration.launchCommands.joined(separator: "\n") + "\n",
projectID: projectID!.uuidString, revision: revision, artifactID: artifact.id.uuidString, modules: modules, stopAt: stop, stopModule: stopModule, flatGuards: flatGuards, cpu: processor.workerCPU, helperURL: helperURL,
retentionDirectory: storage.directory, diskProvenance: provenance, resumedDiskID: retainedID,
graphicsBuffers: graphicsBuffers, runID: start.runID, media: media)
graphicsBuffers: graphicsBuffers, runID: start.runID, media: media, multiDrive: playtestMultiDriveApproved)
guard current() else { await owned.invalidate().value; throw problem("stale_run") }
playtest = owned
start.updatePhase("capturing_initial_state")
@@ -1387,6 +1438,63 @@ final class MCPCMOC: ObservableObject {
return Int(exactly: n)
}
private func exportBuildOutputs(_ arguments: [String: Any], projectID: String, owner: UUID) async throws -> [String: Any] {
guard arguments.count == 7, Set(arguments.keys) == ["project_id", "build_id", "artifact_id", "revision", "destination_id", "output_ids", "request_id"],
arguments["project_id"] as? String == projectID, let exporter = buildExporter,
arguments["destination_id"] as? String == exporter.destinationID,
let buildID = arguments["build_id"] as? String, builds[buildID]?["status"] as? String == "succeeded", let source = exportSources[buildID],
arguments["artifact_id"] as? String == source.source.artifactID.uuidString,
int(arguments["revision"]) == source.revision,
let outputs = arguments["output_ids"] as? [String], !outputs.isEmpty,
outputs.count <= MCPBuildExporter.maximumFiles, Set(outputs).count == outputs.count,
outputs.allSatisfy({ $0.utf8.count == 64 && $0.utf8.allSatisfy { (48...57).contains($0) || (97...102).contains($0) } }),
let request = arguments["request_id"] as? String, (1...128).contains(request.utf8.count) else { throw problem("invalid_export_selection") }
let catalog = Dictionary(uniqueKeysWithValues: source.source.products.map { ($0.identifier(artifactID: source.source.artifactID), $0) })
let selected = try outputs.sorted().map { id -> CMOCBuildOutputProduct in
guard let product = catalog[id] else { throw problem("undeclared_export_output") }; return product
}
let identityData = try JSONSerialization.data(withJSONObject: ["build_id": buildID, "artifact_id": source.source.artifactID.uuidString,
"revision": source.revision, "destination_id": exporter.destinationID, "outputs": outputs.sorted()], options: [.sortedKeys])
let identity = CMOCProject.sha256(identityData)
if let exportID = exportRequests[request], let record = exportRecords[exportID] {
guard record.identity == identity else { throw problem("request_id_conflict") }
if let delivery = record.delivery {
guard !exporting else { throw problem("export_busy_or_limit") }
exporting = true
defer { if session == owner { exporting = false } }
let work = Task.detached { try exporter.verify(delivery) }
try await withTaskCancellationHandler(operation: { try await work.value }, onCancel: { work.cancel() })
guard session == owner, active, buildExporter === exporter else { throw problem("access_denied") }
}
return record.fields
}
let count = selected.reduce(0) { $0 + $1.byteCount }
guard !exporting, exportRecords.count < MCPBuildExporter.maximumRequests,
count <= MCPBuildExporter.maximumSetBytes,
exportReservedBytes <= MCPBuildExporter.maximumSessionBytes - count else { throw problem("export_busy_or_limit") }
let exportID = UUID().uuidString
let name = "VCC-" + source.source.artifactID.uuidString + "-" + String(CMOCProject.sha256(Data(request.utf8)).prefix(16))
let record = ExportRecord(identity: identity, base: ["project_id": projectID, "build_id": buildID,
"artifact_id": source.source.artifactID.uuidString, "revision": source.revision, "configuration": source.configuration,
"destination_id": exporter.destinationID, "request_id": request, "export_id": exportID, "poll_tool": "get_build_export"])
exportRequests[request] = exportID; exportRecords[exportID] = record
exportReservedBytes += count; exporting = true
exportWork = Task {
let work = Task.detached { try exporter.export(source: source.source, products: selected, setName: name) }
do {
let delivery = try await withTaskCancellationHandler(operation: { try await work.value }, onCancel: { work.cancel() })
guard active, session == owner, buildExporter === exporter else { return }
exportRecords[exportID]?.delivery = delivery; exportRecords[exportID]?.status = "completed"
} catch {
guard active, session == owner, buildExporter === exporter else { return }
exportRecords[exportID]?.status = error is CancellationError ? "cancelled" : "failed"
exportRecords[exportID]?.reason = sanitized(error.localizedDescription)
}
if session == owner { exporting = false; exportWork = nil }
}
return record.fields
}
private func buildRecord(_ id: String) -> [String: Any]? {
guard var record = builds[id] else { return nil }
if record["revision"] as? Int != revision || refreshProblem != nil { record["status"] = "stale" }
@@ -1445,6 +1553,12 @@ final class MCPCMOC: ObservableObject {
}.value
guard session == owner, revision == expected, refreshProblem == nil, readyArtifact?.value.id == artifact.id else { throw problem("stale_revision") }
result["source_debugging"] = evidence
result["exportable_outputs"] = artifact.exportProducts.map { $0.fields(artifactID: artifact.id) }
if buildExporter != nil {
let source = try await Task.detached { try MCPBuildExporter.Source(artifact) }.value
guard session == owner, active else { throw problem("access_denied") }
exportSources[id] = (expected, artifact.configurationName, source)
}
result["playtest_disk_products"] = artifact.playtestDiskProducts.map {
["media_id": MCPPlaytestMedium.identifier(artifactID: artifact.id.uuidString, key: "disk:" + $0.relativePath),
"path": $0.relativePath, "bytes": $0.byteCount, "sha256": $0.sha256] as [String: Any]
@@ -1712,11 +1826,31 @@ final class MCPCMOC: ObservableObject {
view: MCPCMOCConsent(host: self, model: model))
consentPanel = w; consentModel = model; w.makeKeyAndOrderFront(nil)
}
fileprivate func chooseExportDirectory(_ model: CMOCDevelopmentModel) {
guard let owner = consentPanel, consentModel === model, !active, owner.isVisible, owner.attachedSheet == nil else { return }
let project = model.assistantProjectID, generation = session
let picker = NSOpenPanel(); picker.canChooseDirectories = true; picker.canChooseFiles = false
picker.allowsMultipleSelection = false; picker.canCreateDirectories = true
picker.title = "Choose Build Delivery Folder"; picker.prompt = "Approve Folder"
picker.message = "Allow this connection to create new build-delivery sets here. Existing files are never replaced."
picker.beginSheetModal(for: owner) { [weak self, weak owner, weak model] response in
Task { @MainActor in
guard let self, let owner, let model, self.consentPanel === owner, self.consentModel === model,
owner.isVisible, !self.active, self.session == generation, model.assistantProjectID == project,
response == .OK, let url = picker.url else { return }
do {
_ = try await Task.detached { try MCPBuildExporter(destination: url) }.value
guard self.session == generation, !self.active, self.consentModel === model else { return }
self.selectedExportDirectory = url; self.exportFolderName = url.lastPathComponent
} catch { self.status = "Could not approve that delivery folder. " + error.localizedDescription }
}
}
}
fileprivate func exportGrant(_ model: CMOCDevelopmentModel) {
guard let owner = consentPanel, consentModel === model, owner.isVisible,
!owner.isMiniaturized, owner.attachedSheet == nil else { return }
let project = model.assistantProjectID, generation = session
let approvedMake = allowProjectMakefile, approvedPlaytests = allowPlaytests
let approvedMake = allowProjectMakefile, approvedPlaytests = allowPlaytests, approvedExport = allowBuildExport, approvedFolder = selectedExportDirectory
let picker = NSSavePanel(); picker.title = "Share C Project for Reviewed Changes"
picker.message = "Choose a new private connection file for the local assistant."
picker.nameFieldStringValue = "VCC Plus OSS C Connection.json"
@@ -1726,7 +1860,8 @@ final class MCPCMOC: ObservableObject {
@MainActor func currentPresentation() -> Bool {
self.consentPanel === owner && self.consentModel === model && owner.isVisible &&
!owner.isMiniaturized && model.assistantProjectID == project &&
self.allowProjectMakefile == approvedMake && self.allowPlaytests == approvedPlaytests
self.allowProjectMakefile == approvedMake && self.allowPlaytests == approvedPlaytests &&
self.allowBuildExport == approvedExport && self.selectedExportDirectory == approvedFolder
}
guard currentPresentation(), self.session == generation else { return }
defer { if currentPresentation() { owner.makeKeyAndOrderFront(nil) } }
@@ -1872,11 +2007,22 @@ private struct MCPCMOCConsent: View {
if !host.active {
Toggle("Allow Disposable Playtests", isOn: $host.allowPlaytests)
if host.allowPlaytests {
Text("Allow the assistant to launch this project's built disk or resume a retained test disk in a separate 512 KB 6809 or 6309 CoCo, hold key combinations and standard joystick axes and buttons, read input diagnostics, capture its screen, declared graphics buffers and guest audio, record bounded MP4 gameplay clips with optional CoCo audio, inspect verified program stops and shared data, read up to 64 bytes at the paused test guest’s stack pointer with caller and argument interpretations only when verified, and restart its own writable test disks. Reviewed additional disk products can be inserted or ejected in the paused, idle test drive without a reset or advancing time; each private writable copy is retained. The guest controls 6309 execution mode. Audio capture advances the test guest. Mac windows, microphone and capture feedback cues are excluded. Retained originals and your current CoCo and media are preserved. Access ends when this connection or build changes.").font(.callout)
Text("Allow the assistant to launch this project's built disk or resume a retained test disk in a separate 512 KB 6809 or 6309 CoCo, hold key combinations and standard joystick axes and buttons, read input diagnostics, capture its screen, declared graphics buffers and guest audio, record bounded MP4 gameplay clips with optional CoCo audio, inspect verified program stops and shared data, read up to 64 bytes at the paused test guest’s stack pointer with caller and argument interpretations only when verified, and restart its own writable test disks. Reviewed additional disk products can be inserted or ejected in any of four paused test drives while the shared controller is idle without a reset or advancing time; each private writable copy is retained. The guest controls 6309 execution mode. Audio capture advances the test guest. Mac windows, microphone and capture feedback cues are excluded. Retained originals and your current CoCo and media are preserved. Access ends when this connection or build changes.").font(.callout)
}
if host.allowPlaytests, let media = model.project?.configuration.playtestDisks, !media.isEmpty {
Text("Additional playtest disks: " + media.joined(separator: ", ")).font(.callout).textSelection(.enabled)
}
Toggle("Allow Build Output Export", isOn: $host.allowBuildExport)
if host.allowBuildExport {
Text("Allow delivery of this connection's declared build products to one folder you approve. Each delivery creates a new set with verified original hashes; existing files are never replaced. Older successful builds remain selectable until access is revoked.").font(.callout)
HStack {
Button("Choose Delivery Folder…") { host.chooseExportDirectory(model) }
Text(host.exportFolderName ?? "No delivery folder selected").font(.callout)
}
if let paths = model.project?.configuration.exportOutputs, !paths.isEmpty {
Text("Additional delivery outputs: " + paths.joined(separator: ", ")).font(.callout).textSelection(.enabled)
}
}
Toggle("Use Project Makefile", isOn: $host.allowProjectMakefile)
if host.allowProjectMakefile {
Text("Allow builds using this project's existing Makefile and declared configurations. Make recipes and compiler inputs can execute local commands, just as Build does. Recipe or support-file changes require native review through project refresh.").font(.callout)
@@ -1892,7 +2038,8 @@ private struct MCPCMOCConsent: View {
}
Text("The assistant's model provider may receive the shared files and diagnostics.").font(.callout)
if host.active {
if host.playtestsApproved { Text("Disposable playtests and bounded read-only call context are enabled for this connection. Each test uses a separate CoCo and its own disk copies. Paused-drive media exchange is available for this connection's reviewed disk products.").font(.callout) }
if host.buildExporter != nil { Text("Build output export is enabled for the approved delivery folder. Revoke access to end this permission.").font(.callout) }
if host.playtestsApproved { Text("Disposable playtests and bounded read-only call context are enabled for this connection. Each test uses a separate CoCo and its own disk copies. Drive-targeted FD0–FD3 media exchange and insert-time write protection are available for this connection's reviewed disk products.").font(.callout) }
if let url = host.grantURL {
MCPChatGPTSetup(grantURL: url, firstPrompt: "Identify my shared VCC Plus C project and read its entry source. Describe its target and what the CoCo program does.")
}
@@ -1903,7 +2050,7 @@ private struct MCPCMOCConsent: View {
Button("Run C Build…") { Task { await host.run(selectedRun) } }.disabled(selectedRun == nil || host.running || host.building)
}
}
} else { Button("Save Private Connection…") { host.exportGrant(model) } }
} else { Button("Save Private Connection…") { host.exportGrant(model) }.disabled(host.allowBuildExport && host.exportFolderName == nil) }
if !host.runStatus.isEmpty { Text(host.runStatus).font(.callout).textSelection(.enabled) }
Text(host.status).font(.callout).textSelection(.enabled)
}.padding(18).frame(maxWidth: .infinity, alignment: .leading)
+305 -19
View File
@@ -59,15 +59,23 @@ struct MCPPlaytestDiskStore: Sendable {
let originArtifactDiskSHA256: String?
let mediaKey: String?
let mediaBaseSHA256: String?
let writeProtected: Bool?
init(projectKey: String?, artifactID: String?, artifactDiskSHA256: String?, parentDiskID: String? = nil,
origin: String = "verified_artifact", originArtifactID: String? = nil, originArtifactDiskSHA256: String? = nil,
mediaKey: String? = nil, mediaBaseSHA256: String? = nil) {
mediaKey: String? = nil, mediaBaseSHA256: String? = nil, writeProtected: Bool? = nil) {
self.projectKey = projectKey; self.artifactID = artifactID; self.artifactDiskSHA256 = artifactDiskSHA256
self.parentDiskID = parentDiskID; self.origin = origin
self.originArtifactID = originArtifactID ?? (origin == "verified_artifact" ? artifactID : nil)
self.originArtifactDiskSHA256 = originArtifactDiskSHA256 ?? (origin == "verified_artifact" ? artifactDiskSHA256 : nil)
self.mediaKey = mediaKey; self.mediaBaseSHA256 = mediaBaseSHA256
self.mediaKey = mediaKey; self.mediaBaseSHA256 = mediaBaseSHA256; self.writeProtected = writeProtected
}
func protecting(_ enabled: Bool) -> Self {
Self(projectKey: projectKey, artifactID: artifactID, artifactDiskSHA256: artifactDiskSHA256,
parentDiskID: parentDiskID, origin: origin, originArtifactID: originArtifactID,
originArtifactDiskSHA256: originArtifactDiskSHA256, mediaKey: mediaKey,
mediaBaseSHA256: mediaBaseSHA256, writeProtected: enabled)
}
var publicFields: [String: Any] {
@@ -76,6 +84,8 @@ struct MCPPlaytestDiskStore: Sendable {
"origin_artifact_id": originArtifactID as Any? ?? NSNull(),
"origin_artifact_disk_sha256": originArtifactDiskSHA256 as Any? ?? NSNull()]
if let parentDiskID { fields["parent_disk_id"] = parentDiskID }
fields["write_protected"] = writeProtected ?? false
fields["write_protection_recorded"] = writeProtected != nil
fields["media_key"] = mediaKey ?? "primary"
fields["media_base_sha256"] = (mediaBaseSHA256 ?? artifactDiskSHA256) as Any? ?? NSNull()
return fields
@@ -485,11 +495,19 @@ final class MCPPlaytest {
let source: MCPPlaytestMedium
var data: Data
var dirty = false
var writeProtected = false
var retained: MCPPlaytestDiskStore.Record?
var pendingRecordID: String?
}
private var media: [String: MediumState]?
private var mediaOrder: [String] = []
private let multiDrive: Bool
private var mountedMediaIDs: [String?] = Array(repeating: nil, count: 4)
private var pendingMediaDrive: Int?
private var lastSafeMediaExports: [Int: [String: Any]] = [:]
private var frozenDriveExports = Set<Int>()
private var mediaFreezeAcknowledged = false
private var mediaStopDrained = false
private var mountedMediaID: String?
private var mediaExchangeTask: Task<[String: Any], Error>?
private var mediaFailures: [String: (Data, String)] = [:]
@@ -499,16 +517,17 @@ final class MCPPlaytest {
private init(worker: Worker, projectID: String, revision: Int, artifactID: String, retentionDirectory: URL,
diskProvenance: MCPPlaytestDiskStore.Provenance, resumedDiskID: String?, runID: String,
processor: MCPPlaytestProcessor, media: [MCPPlaytestMedium]?,
processor: MCPPlaytestProcessor, media: [MCPPlaytestMedium]?, multiDrive: Bool,
videoArtifactWillVerify: (@Sendable (URL) throws -> Void)?) {
self.runID = runID
self.worker = worker; self.projectID = projectID; self.revision = revision; self.artifactID = artifactID
self.retentionDirectory = retentionDirectory; self.diskProvenance = diskProvenance; self.resumedDiskID = resumedDiskID
self.processor = processor
self.processor = processor; self.multiDrive = multiDrive
self.videoArtifactWillVerify = videoArtifactWillVerify
if let media {
self.media = Dictionary(uniqueKeysWithValues: media.map { ($0.id, MediumState(source: $0, data: $0.data)) })
self.media = Dictionary(uniqueKeysWithValues: media.map { ($0.id, MediumState(source: $0, data: $0.data, writeProtected: $0.provenance.writeProtected ?? false)) })
self.mediaOrder = media.map(\.id); self.mountedMediaID = media.first?.id
self.mountedMediaIDs[0] = media.first?.id
}
}
@@ -517,7 +536,7 @@ final class MCPPlaytest {
modules: [[String: Any]] = [], stopAt: UInt16? = nil, stopModule: String? = nil, flatGuards: [[String: Any]] = [], cpu: String = "6809", helperURL: URL? = nil, retentionDirectory: URL? = nil,
diskProvenance: MCPPlaytestDiskStore.Provenance? = nil, resumedDiskID: String? = nil,
graphicsBuffers: [[String: Any]] = [], runID: String = UUID().uuidString,
media: [MCPPlaytestMedium]? = nil,
media: [MCPPlaytestMedium]? = nil, multiDrive: Bool = false,
videoArtifactWillVerify: (@Sendable (URL) throws -> Void)? = nil) async throws -> MCPPlaytest {
guard let reservedID = UUID(uuidString: runID) else { throw failure("invalid_playtest_run_id") }
guard systemROM.count == 32768, diskROM.count == 8192, !disk.isEmpty, disk.count <= 512 * 1024,
@@ -561,12 +580,18 @@ final class MCPPlaytest {
let test = MCPPlaytest(worker: worker, projectID: projectID, revision: revision, artifactID: artifactID,
retentionDirectory: retentionDirectory ?? AppIdentity.supportDirectory.appendingPathComponent("Development Runs/Assistant Playtests"),
diskProvenance: provenance, resumedDiskID: resumedDiskID.map { UUID(uuidString: $0)!.uuidString }, runID: reservedID.uuidString,
processor: cpu == "6309" ? .hd6309 : .mc6809, media: media, videoArtifactWillVerify: videoArtifactWillVerify)
processor: cpu == "6309" ? .hd6309 : .mc6809, media: media, multiDrive: multiDrive, videoArtifactWillVerify: videoArtifactWillVerify)
var setup: [String: Any] = ["op": "init", "system_rom": systemROM.base64EncodedString(),
"disk_rom": diskROM.base64EncodedString(), "disk": disk.base64EncodedString(),
"boot_keys": paste.chords.map { NSNumber(value: $0) }, "modules": modules, "cpu": cpu,
"graphics_buffers": graphicsBuffers, "flat_guards": flatGuards]
if let media { setup["media_id"] = media[0].id }
if let protection = provenance.writeProtected { setup["write_protected"] = protection }
if multiDrive {
guard media != nil else { await test.invalidate().value; throw failure("invalid_playtest_media") }
setup["multi_drive"] = true
setup["write_protected"] = media?.first?.provenance.writeProtected ?? false
}
if let stopAt {
guard (modules.isEmpty && !flatGuards.isEmpty && stopModule == nil) ||
(!modules.isEmpty && flatGuards.isEmpty && stopModule != nil) else {
@@ -665,7 +690,237 @@ final class MCPPlaytest {
}
}
private func driveRow(_ status: [String: Any], drive: Int) throws -> [String: Any] {
guard let rows = status["drives"] as? [[String: Any]], rows.count == 4,
rows.enumerated().allSatisfy({ index, row in
guard let number = row["drive"] as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID() else { return false }
return number.doubleValue == Double(index)
}) else { throw Self.failure("invalid_playtest_media_reply") }
return rows[drive]
}
private func multiMediaFields(status: [String: Any]) -> [String: Any] {
var fields = status
let workerRows = status["drives"] as? [[String: Any]] ?? []
fields["media_contract_version"] = 2
fields["drive"] = "FD0" // Existing top-level compatibility field.
fields["drives"] = (0..<4).map { drive -> [String: Any] in
var row = workerRows.count == 4 ? workerRows[drive] : ["drive": drive, "label": "FD\(drive)", "unavailable": true]
if let id = row["media_id"] as? String, let item = media?[id] {
row["base_sha256"] = item.source.baseSHA256
row["media_sha256"] = row["disk_sha256"]
row["media_key"] = item.source.key
row["name"] = item.source.name
row["provenance"] = item.source.provenance.protecting(row["write_protected"] as? Bool ?? item.writeProtected).publicFields
row["modified_from_artifact"] = row["disk_sha256"] as? String != item.source.baseSHA256
let retained = item.retained
row["retained"] = retained?.diskSHA256 == row["disk_sha256"] as? String && retained?.provenance.writeProtected == row["write_protected"] as? Bool
if let retained { row["retained_disk"] = retained.publicFields }
}
return row
}
fields["media"] = mediaOrder.compactMap { id -> [String: Any]? in
guard let item = media?[id] else { return nil }
let mounted = workerRows.first { $0["media_id"] as? String == id && $0["disk_present"] as? Bool == true }
let hash = mounted?["disk_sha256"] as? String ?? CMOCProject.sha256(item.data)
let protection = mounted?["write_protected"] as? Bool ?? item.writeProtected
var row: [String: Any] = ["media_id": id, "name": item.source.name, "media_key": item.source.key,
"base_sha256": item.source.baseSHA256, "media_sha256": hash, "byte_count": item.data.count,
"inserted": mounted != nil, "drive": mounted?["drive"] as Any? ?? NSNull(),
"dirty": mounted?["disk_dirty"] as? Bool ?? item.dirty, "write_protected": protection,
"provenance": item.source.provenance.protecting(protection).publicFields,
"modified_from_artifact": hash != item.source.baseSHA256,
"retained": item.retained?.diskSHA256 == hash && item.retained?.provenance.writeProtected == protection]
if let retained = item.retained { row["retained_disk"] = retained.publicFields }
if let parent = item.source.provenance.parentDiskID { row["resumed_from_disk_id"] = parent }
if status["media_selection_uncertain"] as? Bool == true { row["placement_uncertain"] = true }
return row
}
return fields
}
/// One bounded worker message contains one drive's bytes plus a coherent
/// four-drive metadata observation. Never concatenate four disk payloads.
private func receiveMultiMediaExport(_ status: [String: Any], drive: Int) throws {
let row = try driveRow(status, drive: drive)
guard let exported = status["exported_drive"] as? [String: Any], NSDictionary(dictionary: exported).isEqual(to: row),
let present = row["disk_present"] as? Bool, let hash = row["disk_sha256"] as? String,
let protection = row["write_protected"] as? Bool else { throw Self.failure("invalid_playtest_media_reply") }
let id = row["media_id"] as? String
let pendingMatches = mediaCommitPending && pendingMediaDrive == drive && id == pendingMediaSelection
guard id == mountedMediaIDs[drive] || pendingMatches else { throw Self.failure("invalid_playtest_media_reply") }
if !present {
guard id == nil, hash.isEmpty, status["disk_base64"] == nil,
(row["byte_count"] as? NSNumber)?.intValue == 0 else { throw Self.failure("invalid_playtest_media_reply") }
mountedMediaIDs[drive] = nil
} else {
guard let id, var item = media?[id], let encoded = status["disk_base64"] as? String,
let bytes = Data(base64Encoded: encoded), !bytes.isEmpty, bytes.count <= 512 * 1024,
bytes.count == (row["byte_count"] as? NSNumber)?.intValue,
CMOCProject.sha256(bytes) == hash else { throw Self.failure("invalid_playtest_media_reply") }
if item.data != bytes || item.writeProtected != protection { item.pendingRecordID = nil }
item.data = bytes; item.dirty = row["disk_dirty"] as? Bool ?? false; item.writeProtected = protection
media?[id] = item; mountedMediaIDs[drive] = id
}
mountedMediaID = mountedMediaIDs[0]
}
private func exchangeMultiMedia(_ selected: String?, expectedSHA: String?, drive: Int,
writeProtected: Bool?, isCurrent: (() -> Bool)?) async throws -> [String: Any] {
guard valid, isCurrent?() != false else { throw Self.failure("stale_run") }
if let selected {
guard media?[selected] != nil else { throw Self.failure("invalid_playtest_media_selection") }
guard !mountedMediaIDs.enumerated().contains(where: { $0.offset != drive && $0.element == selected }) else {
throw Self.failure("playtest_media_already_inserted")
}
}
var frozen: [Int: [String: Any]] = [:]
for index in 0..<4 {
let snapshot = try await worker.request(["op": "export_media", "drive": index])
try receiveMultiMediaExport(snapshot, drive: index)
if let first = frozen[0] {
for key in ["field_clock", "cycles", "generation", "boot", "pc"] {
guard let a = first[key] as? NSNumber, let b = snapshot[key] as? NSNumber, a == b else {
throw WorkerTransportFailure(reason: "playtest_media_advanced_guest")
}
}
}
frozen[index] = snapshot
}
guard let before = frozen[drive] else { throw Self.failure("invalid_playtest_media_reply") }
let oldRow = try driveRow(before, drive: drive), expectedOldID = mountedMediaIDs[drive]
guard valid, isCurrent?() != false, let generation = oldRow["media_generation"] as? NSNumber,
let oldHash = oldRow["disk_sha256"] as? String else { throw Self.failure("stale_playtest_media") }
if let selected, let item = media?[selected], expectedSHA != CMOCProject.sha256(item.data) {
throw Self.failure("playtest_media_hash_mismatch")
}
var old: [String: Any] = ["media_id": expectedOldID as Any? ?? NSNull(), "media_sha256": oldHash,
"drive": drive, "dirty": oldRow["disk_dirty"] as? Bool ?? false, "retained": false,
"write_protected": oldRow["write_protected"] as? Bool ?? false]
if let expectedOldID {
let retained = try await retainMedium(expectedOldID)
old["retained"] = true; old["retained_disk"] = retained.publicFields
}
guard valid, isCurrent?() != false, mountedMediaIDs[drive] == expectedOldID else { throw Self.failure("stale_run") }
var request: [String: Any] = ["op": "exchange_media", "drive": drive,
"expected_media_generation": generation, "expected_disk_sha256": oldHash]
if let selected, let item = media?[selected] {
request["media_id"] = selected; request["disk_base64"] = item.data.base64EncodedString()
request["write_protected"] = writeProtected ?? item.writeProtected
}
lastSafeMediaExports = frozen
mediaCommitPending = true; pendingMediaDrive = drive; pendingMediaSelection = selected
let after: [String: Any]
do { after = try await worker.request(request) }
catch let error as WorkerRejection { mediaCommitPending = false; pendingMediaDrive = nil; pendingMediaSelection = nil; throw error }
// Acknowledged commit is authoritative even if the grant expires now.
mountedMediaIDs[drive] = selected; mountedMediaID = mountedMediaIDs[0]
mediaCommitPending = false; pendingMediaDrive = nil; pendingMediaSelection = nil
let next = try driveRow(after, drive: drive)
let selectedSHA = selected.flatMap { media?[$0] }.map { CMOCProject.sha256($0.data) } ?? ""
guard next["disk_sha256"] as? String == selectedSHA, next["media_id"] as? String == selected,
next["disk_present"] as? Bool == (selected != nil),
(next["media_generation"] as? NSNumber)?.intValue == generation.intValue + 1,
after["previous_disk_sha256"] as? String == oldHash else { throw WorkerTransportFailure(reason: "invalid_playtest_media_reply") }
if let selected, var item = media?[selected], let effective = next["write_protected"] as? Bool {
if effective != item.writeProtected { item.pendingRecordID = nil }
item.writeProtected = effective; media?[selected] = item
}
for index in 0..<4 where index != drive {
guard NSDictionary(dictionary: try driveRow(before, drive: index)).isEqual(to: try driveRow(after, drive: index)) else {
throw WorkerTransportFailure(reason: "playtest_unrelated_drive_changed")
}
}
for key in ["field_clock", "cycles", "generation", "boot", "pc"] {
guard let a = before[key] as? NSNumber, let b = after[key] as? NSNumber, a == b else { throw WorkerTransportFailure(reason: "playtest_media_advanced_guest") }
}
var result = mediaFields(status: after)
result["target_drive"] = drive; result["previous_media"] = old
result["exchange"] = selected == nil ? "ejected" : "inserted"
result["guest_advanced"] = false; result["guest_reset"] = false
return result
}
private func performMultiMediaPersistence() async throws -> [String: Any] {
if let pending = mediaExchangeTask { _ = await pending.result }
if finished, let finalReceipt { return finalReceipt }
if !mediaFreezeAcknowledged {
do {
var result = try await worker.request(["op": "stop"])
guard result["media_frozen"] as? Bool == true else { throw Self.failure("invalid_playtest_media_reply") }
_ = try driveRow(result, drive: 0)
mediaFreezeAcknowledged = true; exportedStatus = result
guard let primary = mediaOrder.first, let bytes = media?[primary]?.data else { throw Self.failure("invalid_playtest_media") }
exportedDisk = bytes // Retry marker, not a claim that all drives were drained.
do { try await retainVideoMetadata(result) }
catch { result["video_retention_error"] = "The video artifact could not be verified; disk retention continues."; exportedStatus = result }
} catch let error as WorkerTransportFailure {
// Only a fully observed paused four-drive export can recover a
// lost exchange reply. It is never substituted after execution.
guard lastSafeMediaExports.count == 4, let before = lastSafeMediaExports[0] else { throw error }
var result = before
result.removeValue(forKey: "disk_base64"); result.removeValue(forKey: "exported_drive")
result["media_selection_uncertain"] = true
result["uncertain_drives"] = pendingMediaDrive.map { [$0] } ?? Array(0..<4)
if var rows = result["drives"] as? [[String: Any]] {
for index in (pendingMediaDrive.map { [$0] } ?? Array(0..<4)) {
rows[index]["media_id"] = NSNull(); rows[index]["disk_present"] = NSNull()
rows[index]["inserted"] = NSNull(); rows[index]["selection_uncertain"] = true
rows[index]["disk_sha256"] = NSNull(); rows[index]["media_generation"] = NSNull()
mountedMediaIDs[index] = nil
}
result["drives"] = rows
if pendingMediaDrive == nil || pendingMediaDrive == 0 {
result["media_id"] = NSNull(); result["disk_present"] = NSNull(); result["disk_sha256"] = NSNull()
}
}
mountedMediaID = mountedMediaIDs[0]
exportedStatus = result; mediaFreezeAcknowledged = true; mediaStopDrained = true
frozenDriveExports = Set(0..<4)
exportedDisk = mediaOrder.first.flatMap { media?[$0]?.data }
}
}
do {
for drive in 0..<4 where !frozenDriveExports.contains(drive) {
let result = try await worker.request(["op": "export_media", "drive": drive])
try receiveMultiMediaExport(result, drive: drive)
// Each reply must match the STOP observation, with no execution
// or selection change while bounded exports are drained.
guard let frozen = exportedStatus,
NSDictionary(dictionary: try driveRow(frozen, drive: drive)).isEqual(to: try driveRow(result, drive: drive)) else {
throw Self.failure("playtest_frozen_media_changed")
}
frozenDriveExports.insert(drive)
}
if !mediaStopDrained {
do { _ = try await worker.request(["op": "finish_stop"]) }
catch is WorkerTransportFailure { /* Every mounted disk was already drained and verified. */ }
mediaStopDrained = true
}
var retained: [[String: Any]] = []
for id in mediaOrder {
let record = try await retainMedium(id)
var fields = record.publicFields; fields["media_id"] = id; fields["name"] = media?[id]?.source.name
retained.append(fields)
}
guard let primary = mediaOrder.first, let record = media?[primary]?.retained else { throw Self.failure("playtest_disk_export_failed") }
retainedDiskRecord = record; retainedDiskURL = try MCPPlaytestDiskStore.diskURL(directory: retentionDirectory, id: record.id)
var result = mediaFields(status: exportedStatus ?? [:])
result["disk_retained"] = true; result["retained_disk_id"] = record.id
result["retained_disk_sha256"] = record.diskSHA256; result["retained_disk"] = record.publicFields
result["retained_media"] = retained; result["status"] = "stopped"
finished = true; retentionError = nil; worker.close()
let receipt = scoped(result); finalReceipt = receipt
exportedDisk = nil; exportedStatus = nil; Self.pendingRetentions.removeValue(forKey: runID)
return receipt
} catch {
retentionError = error.localizedDescription; Self.pendingRetentions[runID] = self
throw error
}
}
private func mediaFields(status: [String: Any]) -> [String: Any] {
if multiDrive { return multiMediaFields(status: status) }
var fields = status
let actualID = status["media_id"] == nil ? mountedMediaID : status["media_id"] as? String
let present = status["disk_present"] as? Bool ?? (mountedMediaID != nil)
@@ -689,6 +944,7 @@ final class MCPPlaytest {
/// Only called with a bounded, complete export from the app-owned helper.
/// Keep these bytes even if the lease was revoked while the pipe was read.
private func receiveMediaExport(_ status: [String: Any]) throws {
if multiDrive { try receiveMultiMediaExport(status, drive: 0); return }
guard media != nil, let present = status["disk_present"] as? Bool else { throw Self.failure("invalid_playtest_media_reply") }
if !present {
guard (mountedMediaID == nil || (mediaCommitPending && pendingMediaSelection == nil)),
@@ -713,11 +969,22 @@ final class MCPPlaytest {
private func retainMedium(_ id: String) async throws -> MCPPlaytestDiskStore.Record {
guard var item = media?[id] else { throw Self.failure("invalid_playtest_media_selection") }
let hash = CMOCProject.sha256(item.data)
if let existing = item.retained, existing.diskSHA256 == hash { return existing }
if let existing = item.retained, existing.diskSHA256 == hash,
!multiDrive || existing.provenance.writeProtected == item.writeProtected {
guard let projectKey = existing.provenance.projectKey,
let artifactHash = existing.provenance.artifactDiskSHA256 else { throw Self.failure("invalid_playtest_disk_provenance") }
let loaded = try await MCPPlaytestDiskStore.load(directory: retentionDirectory, id: existing.id,
expectedSHA256: hash, projectKey: projectKey, artifactDiskSHA256: artifactHash,
mediaKey: existing.provenance.mediaKey ?? "primary", mediaBaseSHA256: existing.provenance.mediaBaseSHA256)
guard loaded.record.id == existing.id, loaded.record.runID == existing.runID,
loaded.record.provenance == existing.provenance, loaded.record.diskSHA256 == existing.diskSHA256,
loaded.record.byteCount == existing.byteCount, loaded.data == item.data else { throw Self.failure("retained_disk_changed") }
return existing
}
let recordID = item.pendingRecordID ?? UUID().uuidString
item.pendingRecordID = recordID; media?[id] = item
let stored = try await MCPPlaytestDiskStore.save(directory: retentionDirectory, runID: runID,
data: item.data, provenance: item.source.provenance, recordID: recordID)
data: item.data, provenance: multiDrive ? item.source.provenance.protecting(item.writeProtected) : item.source.provenance, recordID: recordID)
// The paused worker and serialized owner cannot change this medium
// during the off-main-thread durable write.
guard var current = media?[id], current.data == item.data else { throw Self.failure("playtest_media_changed") }
@@ -725,7 +992,9 @@ final class MCPPlaytest {
return stored
}
private func exchangeMedia(_ selected: String?, expectedSHA: String?, isCurrent: (() -> Bool)?) async throws -> [String: Any] {
private func exchangeMedia(_ selected: String?, expectedSHA: String?, isCurrent: (() -> Bool)?,
drive: Int = 0, writeProtected: Bool? = nil) async throws -> [String: Any] {
if multiDrive { return try await exchangeMultiMedia(selected, expectedSHA: expectedSHA, drive: drive, writeProtected: writeProtected, isCurrent: isCurrent) }
guard valid, isCurrent?() != false else { throw Self.failure("stale_run") }
let before = try await worker.request(["op": "export_media"])
let expectedOldID = mountedMediaID
@@ -751,6 +1020,7 @@ final class MCPPlaytest {
"expected_disk_sha256": oldHash]
if let selected, let item = media?[selected] {
request["media_id"] = selected; request["disk_base64"] = item.data.base64EncodedString()
if let protection = item.source.provenance.writeProtected { request["write_protected"] = protection }
}
lastSafeMediaExport = before
mediaCommitPending = true; pendingMediaSelection = selected
@@ -781,6 +1051,7 @@ final class MCPPlaytest {
}
private func performMediaPersistence() async throws -> [String: Any] {
if multiDrive { return try await performMultiMediaPersistence() }
if let pending = mediaExchangeTask { _ = await pending.result }
if finished, let finalReceipt { return finalReceipt }
if exportedDisk == nil {
@@ -835,6 +1106,8 @@ final class MCPPlaytest {
/// The host rechecks project/revision/artifact identity before dispatching.
/// Cached write receipts are still bound to this live lease, never replayed.
func reply(_ tool: String, arguments: [String: Any], isCurrent: (() -> Bool)? = nil) async throws -> [String: Any] {
var arguments = arguments
if tool == "exchange_playtest_media", multiDrive, arguments["drive"] == nil { arguments["drive"] = 0 }
guard valid, arguments["run_id"] as? String == runID else { throw Self.failure("stale_run") }
guard !busy else { throw Self.failure("playtest_busy") }
busy = true
@@ -903,10 +1176,22 @@ final class MCPPlaytest {
}
if tool == "exchange_playtest_media" {
guard media != nil, let action = arguments["action"] as? String,
["insert", "eject"].contains(action),
Set(arguments.keys) == (action == "insert" ? ["run_id", "request_id", "action", "media_id", "media_sha256"] : ["run_id", "request_id", "action"]) else {
throw Self.failure("invalid_arguments")
}
["insert", "eject"].contains(action) else { throw Self.failure("invalid_arguments") }
var required: Set<String> = action == "insert" ? ["run_id", "request_id", "action", "media_id", "media_sha256"] : ["run_id", "request_id", "action"]
if multiDrive { required.insert("drive") }
let optional: Set<String> = multiDrive && action == "insert" ? ["write_protected"] : []
guard required.isSubset(of: Set(arguments.keys)), Set(arguments.keys).isSubset(of: required.union(optional)) else { throw Self.failure("invalid_arguments") }
let drive: Int
if multiDrive {
guard let value = arguments["drive"] as? NSNumber, CFGetTypeID(value) != CFBooleanGetTypeID(),
value.doubleValue.isFinite, value.doubleValue == Double(value.intValue), (0...3).contains(value.intValue) else { throw Self.failure("invalid_arguments") }
drive = value.intValue
} else { drive = 0 }
let protection: Bool?
if let value = arguments["write_protected"] {
guard let number = value as? NSNumber, CFGetTypeID(number) == CFBooleanGetTypeID() else { throw Self.failure("invalid_arguments") }
protection = number.boolValue
} else { protection = nil }
let selected: String?
if action == "insert" {
guard let id = arguments["media_id"] as? String, media?[id] != nil,
@@ -918,7 +1203,7 @@ final class MCPPlaytest {
} else { selected = nil }
mutationRequestsAccepted += 1
accepted[requestID] = (signature, scoped(["request_id": requestID, "status": "interrupted"]))
let exchange = Task { try await self.exchangeMedia(selected, expectedSHA: arguments["media_sha256"] as? String, isCurrent: isCurrent) }
let exchange = Task { try await self.exchangeMedia(selected, expectedSHA: arguments["media_sha256"] as? String, isCurrent: isCurrent, drive: drive, writeProtected: protection) }
mediaExchangeTask = exchange
defer { mediaExchangeTask = nil }
var result: [String: Any]
@@ -1045,7 +1330,7 @@ final class MCPPlaytest {
}
}
do {
lastSafeMediaExport = nil
lastSafeMediaExport = nil; lastSafeMediaExports.removeAll()
var result = try await worker.request(request)
guard valid else { throw Self.failure("stale_run") }
try await retainVideoMetadata(result)
@@ -1089,7 +1374,7 @@ final class MCPPlaytest {
guard !busy else { throw Self.failure("playtest_busy") }
busy = true
defer { busy = false }
if let operation = request["op"] as? String, ["continue", "step", "stop_at"].contains(operation) { lastSafeMediaExport = nil }
if let operation = request["op"] as? String, ["continue", "step", "stop_at"].contains(operation) { lastSafeMediaExport = nil; lastSafeMediaExports.removeAll() }
let result = try await worker.request(request)
guard valid else { throw Self.failure("stale_run") }
try await retainVideoMetadata(result)
@@ -1097,7 +1382,7 @@ final class MCPPlaytest {
}
private func scoped(_ result: [String: Any]) -> [String: Any] {
var result = result
var result = multiDrive && media != nil ? mediaFields(status: result) : result
result["run_id"] = runID; result["project_id"] = projectID
result["revision"] = revision; result["artifact_id"] = artifactID
result["requested_processor"] = processor.rawValue
@@ -1122,7 +1407,8 @@ final class MCPPlaytest {
result["boot_disk_provenance"] = diskProvenance.publicFields
if let id = mountedMediaID, let current = media?[id] {
result["disk_origin"] = current.source.provenance.origin
result["disk_provenance"] = current.source.provenance.publicFields
let currentProtection = (result["drives"] as? [[String: Any]])?.first?["write_protected"] as? Bool ?? current.writeProtected
result["disk_provenance"] = multiDrive ? current.source.provenance.protecting(currentProtection).publicFields : current.source.provenance.publicFields
} else {
result["disk_origin"] = NSNull(); result["disk_provenance"] = NSNull()
}
+33 -10
View File
@@ -1227,7 +1227,8 @@ final class MachineModel: ObservableObject {
}
func loadBASICSource(_ source: String, run: Bool, breakpoints: Set<Int> = [],
review: (expected: VCCMachineSnapshot, existing: String)? = nil) async -> VCCMachineSnapshot? {
review: (expected: VCCMachineSnapshot, existing: String)? = nil,
reviewIsCurrent: (() -> Bool)? = nil) async -> VCCMachineSnapshot? {
guard !busy, !diskSaving, state != .closed else {
fileError = "The machine is busy. Try the BASIC transfer again when it is ready."
return nil
@@ -1235,17 +1236,39 @@ final class MachineModel: ObservableObject {
busy = true; inputEpoch += 1; fileError = nil
defer { busy = false }
let points = breakpoints.sorted().map { NSNumber(value: $0) }
let result = await diskStep { completion in
if let review {
controller.assistantLoad(source: source, breakpoints: points, expected: review.expected, existing: review.existing, completion: completion)
} else {
controller.basicLoadSource(source, run: run, breakpoints: points, completion: completion)
let retryDeadline = ContinuousClock.now.advanced(by: .seconds(2))
while true {
if review != nil {
guard reviewIsCurrent?() != false, !Task.isCancelled else {
fileError = Task.isCancelled ? "The BASIC transfer was cancelled." : "The approved revision or connection changed."
return nil
}
}
let result = await diskStep { completion in
if let review {
controller.assistantLoad(source: source, breakpoints: points, expected: review.expected, existing: review.existing, completion: completion)
} else {
controller.basicLoadSource(source, run: run, breakpoints: points, completion: completion)
}
}
if let error = result.errorMessage {
// A running ROM can leave its input loop between readiness and
// loading. This exact core refusal precedes every mutation;
// each retry rechecks the same reviewed machine/source/media.
guard review != nil, reviewIsCurrent != nil,
error == "Wait at the BASIC OK prompt before loading or running from the editor; use BREAK to stop the current program first",
ContinuousClock.now.advanced(by: .milliseconds(45)) < retryDeadline else {
fileError = error; return nil
}
do { try await Task.sleep(for: .milliseconds(45)) }
catch { fileError = "The BASIC transfer was cancelled."; return nil }
guard ContinuousClock.now < retryDeadline else { fileError = error; return nil }
continue // Approval and cancellation are rechecked after the wait.
}
binaryName = nil
if run { focusRequest += 1 }
return result
}
if let error = result.errorMessage { fileError = error; return nil }
binaryName = nil
if run { focusRequest += 1 }
return result
}
func configureBASICBreakpoints(_ lines: Set<Int>, source: String) async -> Bool {
guard !busy, !diskSaving, state != .closed else { return false }