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

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

2122 lines
152 KiB
Swift
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// SPDX-License-Identifier: GPL-3.0-or-later
import AppKit
import SwiftUI
import Combine
import Darwin
/// A bounded receipt for one accepted startup. Long preparation and boot work
/// is polled through get_run rather than held inside a transport request.
@MainActor
final class MCPOwnedPlaytestStart {
let identity: String
let requestID: String
let runID: String
let projectID: String
let revision: Int
let artifactID: String
let processor: MCPPlaytestProcessor
private(set) var status = "starting"
private(set) var phase = "preparing_debug_metadata"
private(set) var settled = false
private var task: Task<Void, Never>?
private var receipt: [String: Any]?
private var reason: String?
private let redactionRoots: [URL]
init(identity: String, requestID: String, runID: String = UUID().uuidString,
projectID: String, revision: Int, artifactID: String, processor: MCPPlaytestProcessor = .mc6809,
redactionRoots: [URL] = []) {
self.identity = identity; self.requestID = requestID; self.runID = runID
self.projectID = projectID; self.revision = revision; self.artifactID = artifactID
self.processor = processor
self.redactionRoots = redactionRoots
}
var acceptingResult: Bool { status == "starting" && !Task.isCancelled }
func updatePhase(_ phase: String) { if status == "starting" { self.phase = phase } }
func launch(_ operation: @escaping @MainActor (MCPOwnedPlaytestStart) async throws -> [String: Any]) {
guard task == nil else { return }
task = Task {
defer { settled = true }
do {
var result = try await operation(self)
guard acceptingResult else { status = "cancelled"; return }
result.removeValue(forKey: "png_base64")
receipt = result; status = "ready"; phase = "ready"
} catch {
guard status == "starting", !Task.isCancelled else { status = "cancelled"; return }
reason = CMOCBuildFailureReport.fields(for: error, redacting: redactionRoots)["reason"] as? String
status = "failed"
}
}
}
func cancel() {
guard !settled else { return }
status = "cancelling"
task?.cancel()
}
func waitForCompletion() async { await task?.value }
var fields: [String: Any] {
var value: [String: Any] = ["project_id": projectID, "revision": revision, "artifact_id": artifactID,
"request_id": requestID, "run_id": runID, "owned_playtest": true, "requested_processor": processor.rawValue,
"status": status, "phase": phase, "busy": !settled]
if !settled { value["poll_tool"] = "get_run" }
if let reason { value["error"] = reason }
if let receipt { value["receipt"] = receipt }
return value
}
}
/// Public refresh receipts expose relative input evidence, never candidate bytes.
struct MCPProjectRefreshRecord {
let id: String
let requestID: String
let expectedRevision: Int
let identity: String
let changes: [CMOCProjectInputManifest.Change]
var status: String
var revision: Int
var reason: String? = nil
var fields: [String: Any] {
let catalog = CMOCSourceMap.boundedJSONCatalog(Array(changes.prefix(64)).map(\.publicFields))
var value: [String: Any] = ["refresh_id": id, "request_id": requestID, "status": status,
"expected_revision": expectedRevision, "revision": revision,
"changed_inputs": catalog.items, "changed_inputs_total": changes.count, "changed_inputs_truncated": catalog.items.count != changes.count,
"changed_input_paths": Array(changes.prefix(128)).map(\.path),
"changed_input_paths_total": changes.count, "changed_input_paths_truncated": changes.count > 128,
"requires_review": changes.contains(where: \.requiresReview)]
if let reason { value["reason"] = reason }
return value
}
static func inputPage(_ entries: [CMOCProjectInputManifest.Entry], offset: Int, limit: Int)
-> (rows: [[String: Any]], nextOffset: Int?, truncated: Bool) {
let selected = offset < entries.count ? Array(entries.dropFirst(offset).prefix(limit)) : []
let bounded = CMOCSourceMap.boundedJSONCatalog(selected.map(\.publicFields), maximumBytes: 128 * 1024)
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", "export_build_outputs", "get_build_export"]
}
/// The grant binds reviewed drafts and build artifacts to one selected project.
@MainActor
final class MCPCMOC: ObservableObject {
static let shared = MCPCMOC()
private var scope: MCPCMOCProject?
private var approvedInputs: CMOCProjectInputManifest?
private var observedInputChanges: [CMOCProjectInputManifest.Change] = []
private var lastAcceptedInputChanges: [CMOCProjectInputManifest.Change] = []
private var refreshRecords: [String: MCPProjectRefreshRecord] = [:]
private var refreshRequests: [String: String] = [:]
private var latestRefreshID: String?
private var refreshCandidate: RefreshCandidate?
private var refreshPanel: NSPanel?
private var refreshProblem: String?
private var refreshApprovingID: String?
private struct CapturedInputs {
let live: [String: String]
let disk: [String: String]
let epoch: Int
let directives: [String: Set<String>]
let make: MCPCMOCMakeInputs?
let manifest: CMOCProjectInputManifest
let scope: MCPCMOCProject
let project: CMOCProject
}
private struct RefreshCandidate {
let refreshID: String
let owner: UUID
let captured: CapturedInputs
}
private static let headers = MCPCMOCProject.libraryHeaders.map { "@toolchain/include/" + $0 }
private static let tools = ["get_capabilities", "refresh_project", "get_project_refresh", "read_project_inputs", "get_machine_status", "get_debug_snapshot", "read_debug_memory", "search_help", "read_topic", "read_project_file", "build_project", "get_build", "get_build_log", "propose_fix", "propose_project_edits", "get_proposal", "get_run", "read_screen_text", "send_keys"]
private weak var model: CMOCDevelopmentModel?
private weak var pendingModel: CMOCDevelopmentModel?
private var projectID: UUID?
private var session = UUID()
private var token = ""
private var server: MCPTransport?
private var file: MCPGrantFile?
fileprivate var grantURL: URL? { file?.url }
private var scratch: URL?
private var service: CMOCBuildService?
private var buildTask: Task<Void, Never>?
private var runTask: Task<Void, Never>?
private var panel: NSPanel?
private var consentPanel: NSPanel?
private weak var consentModel: CMOCDevelopmentModel?
private var workspaceEpoch = -1
private var revision = 0
private var snapshot: [String: String] = [:]
private var diskSnapshot: [String: String] = [:]
private var makeSnapshot: MCPCMOCMakeInputs?
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?
#endif
private var playtest: MCPPlaytest?
private var playtestStarts: [String: MCPOwnedPlaytestStart] = [:]
private var latestPlaytestStart: MCPOwnedPlaytestStart?
private var playtestStartupCleanup: Task<Void, Never>?
private var playtestBusy = false
private var readyDebugMetadata: (artifactID: UUID, map: CMOCProjectSourceMap, variables: CMOCVariableDebug?, variableError: String?)?
private var ownedInspection: (id: String, run: String, clock: Int, memory: Data, ranges: [Range<Int>], fields: [String: Any], fingerprint: String, callContext: [String: Any]?)?
private var templateDirectives: [String: Set<String>] = [:]
private var readyArtifact: (revision: Int, value: CMOCBuildArtifact)?
private var buildRequests: [String: String] = [:]
private var latestBuildID: String?
private var builds: [String: [String: Any]] = [:]
private var buildReports: [String: CMOCBuildReport] = [:]
private var proposals: [String: Proposal] = [:]
private var proposalRequests: [String: String] = [:]
private var runID: String?
private var liveIO: MCPCompiledRunIO?
private var inspection: MCPDebuggerInspection?
private var runRevision: Int?
fileprivate private(set) var runReceipt: [String: Any]?
fileprivate var usesDiskRecipe: Bool { scope?.helloDisk == true }
fileprivate var readyToRun: Bool {
readyArtifact?.revision == revision && proposal?.status != "pending" && (!usesDiskRecipe || proposal?.applied == revision)
}
fileprivate struct RunSelection {
let artifactID: UUID
let proposalID: String?
}
fileprivate var runSelection: RunSelection? {
guard readyToRun, let artifact = readyArtifact else { return nil }
return RunSelection(artifactID: artifact.value.id, proposalID: proposal?.id)
}
@Published private(set) var status = ""
@Published private(set) var active = false
@Published private(set) var proposal: Proposal?
@Published private(set) var building = false
@Published private(set) var running = false
@Published private(set) var runStatus = ""
@Published private(set) var buildStatus = ""
private var fixtureLabel: String?
private var regression = false
#if DEBUG
private var fixtureWindow: NSWindow?
private var fixtureRunAlert: NSAlert?
private var fixtureDirectory: URL?
#endif
struct Proposal {
let id = UUID().uuidString
let request: String, path: String, line: Int, before: String, after: String, revision: Int
var edits: [MCPCMOCEdit]? = nil
var status = "pending"
var applied: Int?
var result: [String: Any] {
var value: [String: Any] = ["proposal_id": id, "path": path, "line_number": line, "before": before,
"after": after, "revision": revision, "status": status]
if let edits {
value = ["proposal_id": id, "revision": revision, "status": status, "files": edits.map(\.path)]
}
if let applied { value["applied_revision"] = applied }
return value
}
}
private func problem(_ text: String) -> CMOCBuildError { .message(text) }
private func capture(_ model: CMOCDevelopmentModel, scope: MCPCMOCProject, updatedScope: Bool = false, expandedSupport: Bool = false) async throws -> CapturedInputs {
guard let project = model.project else { throw problem("project_unavailable") }
let template = Bundle.main.resourceURL?.appendingPathComponent("DevelopmentTemplates/HelloDisk")
let workspace = model.assistantProjectID, epoch = model.assistantEditEpoch
let overlays = Dictionary(uniqueKeysWithValues: model.documents.filter { !$0.generated && !$0.reference && $0.dirty }.map { ($0.id, $0.text) })
let paths = scope.paths
let dirty = model.documents.filter { !$0.generated && !$0.reference && ($0.dirty || $0.conflict) }.map { ($0.id, $0.savedText) }
let result = try await Task.detached(priority: .userInitiated) {
var live: [String: String] = [:], disk: [String: String] = [:]
var directives: [String: Set<String>] = [:]
let manifest = try CMOCProjectInputManifest.capture(project: project, overlays: overlays,
approvedSupportDirectories: expandedSupport ? nil : scope.configuration.buildSupportDirectories)
let capturedProject = CMOCProject(directory: project.directory, configuration: manifest.configuration)
let effectiveScope = updatedScope ? try MCPCMOCProject(project: capturedProject, files: manifest.sharedPaths, customMake: scope.customMake) : scope
if scope.customMake {
for path in effectiveScope.paths {
guard let bytes = manifest.files[path], let text = String(data: bytes, encoding: .utf8), !bytes.contains(0) else {
throw CMOCBuildError.message("unreadable_project_text: " + path)
}
let diskText = try project.readText(relativePath: path)
if let original = dirty.first(where: { $0.0 == path }), original.1 != diskText {
throw CMOCBuildError.message("external_file_change: " + path)
}
try effectiveScope.validate(text, path: path)
live[path] = text; disk[path] = diskText
}
guard live.values.reduce(0, { $0 + $1.utf8.count }) <= 16 * 1024 * 1024 else {
throw CMOCBuildError.message("shared_text_too_large")
}
let make = MCPCMOCMakeInputs(makefile: manifest.configuration.makefile, files: manifest.files,
permissions: manifest.permissions, modificationDates: manifest.modificationDates,
overlayPaths: manifest.overlayPaths, support: manifest.support)
return (live, disk, directives, Optional(make), manifest, effectiveScope, capturedProject)
}
let installed = template.map { CMOCProject(directory: $0) }
let controls = effectiveScope.helloDisk ? MCPCMOCProject.diskControls : []
for path in (updatedScope ? effectiveScope.paths : paths) + controls {
let diskText = try project.readText(relativePath: path)
guard diskText.utf8.count <= 65536, (overlays[path]?.utf8.count ?? 0) <= 65536 else {
throw CMOCBuildError.message("file_too_large")
}
if let original = dirty.first(where: { $0.0 == path }), original.1 != diskText {
throw CMOCBuildError.message("external_file_change")
}
let text = overlays[path] ?? diskText
let trusted = effectiveScope.helloDisk ? try installed?.readText(relativePath: path) : nil
if controls.contains(path) {
guard text == trusted, diskText == trusted else { throw CMOCBuildError.message("unsupported_project_recipe") }
continue
}
if path.hasSuffix(".c") || path.hasSuffix(".h") {
let allowed = trusted.map { Set($0.components(separatedBy: .newlines).filter { $0.contains("#") }) }
try effectiveScope.validate(text, path: path, trusted: allowed)
directives[path] = allowed
}
live[path] = text
disk[path] = diskText
}
return (live, disk, directives, nil as MCPCMOCMakeInputs?,
manifest.restricting(to: Set(effectiveScope.paths + controls)), effectiveScope, capturedProject)
}.value
guard model.assistantProjectID == workspace, model.assistantEditEpoch == epoch else { throw problem("stale_revision") }
return CapturedInputs(live: result.0, disk: result.1, epoch: epoch, directives: result.2,
make: result.3, manifest: result.4, scope: result.5, project: result.6)
}
/// Native review already advanced the revision. Keep its frozen Make inputs
/// in step so the next poll does not count that same edit a second time.
private func recordReviewedMakeEdits(_ model: CMOCDevelopmentModel) {
guard let make = makeSnapshot else { return }
var files = make.files
for (path, text) in snapshot { files[path] = Data(text.utf8) }
makeSnapshot = MCPCMOCMakeInputs(makefile: make.makefile, files: files, permissions: make.permissions,
modificationDates: make.modificationDates, overlayPaths: Set(model.overlays.keys), support: make.support)
}
private func clearBuildAndLiveControls() {
let retiredRun = playtest?.invalidate(); playtest = nil
ownedInspection = nil
let starts = Array(playtestStarts.values), previousCleanup = playtestStartupCleanup
for start in starts { start.cancel() }
playtestStartupCleanup = Task {
await previousCleanup?.value
for start in starts { await start.waitForCompletion() }
await retiredRun?.value
}
playtestStarts.removeAll(); latestPlaytestStart = nil; playtestBusy = false
readyArtifact = nil
readyDebugMetadata = nil
liveIO?.invalidate()
liveIO = nil
}
private func adoptCaptured(_ captured: CapturedInputs, model: CMOCDevelopmentModel, advanceRevision: Bool) throws {
let diskFiles = captured.manifest.files.merging(captured.disk.mapValues { Data($0.utf8) }) { _, disk in disk }
try model.acceptAssistantProjectRefresh(captured.project, diskFiles: diskFiles,
projectID: model.assistantProjectID, epoch: captured.epoch)
if advanceRevision { revision += 1; clearBuildAndLiveControls() }
if let approvedInputs {
let changes = captured.manifest.changes(from: approvedInputs)
if !changes.isEmpty { lastAcceptedInputChanges = changes }
}
snapshot = captured.live; diskSnapshot = captured.disk; workspaceEpoch = captured.epoch
makeSnapshot = captured.make; templateDirectives = captured.directives
scope = captured.scope; approvedInputs = captured.manifest; approvedRecipeID = captured.make?.recipeID
observedInputChanges = []; refreshProblem = nil
if var p = proposal, p.status == "pending", advanceRevision { p.status = "stale"; update(p) }
}
private func refresh(_ model: CMOCDevelopmentModel) async throws {
let owner = session
guard active, self.model === model, projectID == model.assistantProjectID else { throw problem("access_denied") }
guard let scope else { throw problem("project_unavailable") }
do {
let captured = try await capture(model, scope: scope, updatedScope: true)
guard session == owner, active, self.model === model, projectID == model.assistantProjectID else { throw problem("access_denied") }
let changes = approvedInputs.map { captured.manifest.changes(from: $0) } ?? []
if changes.contains(where: \.requiresReview) {
if refreshProblem == nil { clearBuildAndLiveControls() }
if let candidate = refreshCandidate, candidate.captured.manifest != captured.manifest,
var record = refreshRecords[candidate.refreshID] {
record.status = "rejected"; record.reason = "Inputs changed while review was open. Request a new refresh."
refreshRecords[record.id] = record; refreshCandidate = nil
refreshPanel?.close(); refreshPanel = nil; refreshProblem = "project_refresh_required"
}
observedInputChanges = changes
if refreshProblem == nil { refreshProblem = "project_refresh_required" }
return
}
if let candidate = refreshCandidate, candidate.captured.manifest.identity != captured.manifest.identity {
if var record = refreshRecords[candidate.refreshID], record.status == "pending" {
record.status = "rejected"; record.reason = "Inputs changed while review was open. Request a new refresh."; refreshRecords[record.id] = record
}
refreshCandidate = nil; refreshPanel?.close(); refreshPanel = nil
}
let changed = captured.live != snapshot || captured.disk != diskSnapshot || captured.manifest != approvedInputs
if changed {
// A native reviewed edit already moved the revision and updated
// snapshot/epoch; only rebind its canonical manifest here.
let alreadyReviewed = captured.live == snapshot && captured.disk == diskSnapshot && captured.epoch == workspaceEpoch && captured.make == makeSnapshot
try adoptCaptured(captured, model: model, advanceRevision: !alreadyReviewed)
} else { workspaceEpoch = captured.epoch; makeSnapshot = captured.make; observedInputChanges = []; refreshProblem = nil }
} catch {
guard session == owner, active else { throw problem("access_denied") }
if refreshProblem == nil { clearBuildAndLiveControls() }
refreshProblem = sanitized(error.localizedDescription)
}
}
#if DEBUG
func exportCallContextRegression(_ model: CMOCDevelopmentModel, at destination: URL, playtests: Bool = true,
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) }
}
func installProjectRefreshRegression(_ model: CMOCDevelopmentModel, artifact: CMOCBuildArtifact) async throws {
guard let project = model.project else { throw problem("project_unavailable") }
let scope = try MCPCMOCProject(project: project, files: model.files.map(\.relativePath), customMake: true)
let captured = try await capture(model, scope: scope, updatedScope: true, expandedSupport: true)
self.model = model; self.scope = captured.scope; self.projectID = model.assistantProjectID; active = true
snapshot = captured.live; diskSnapshot = captured.disk; workspaceEpoch = captured.epoch
approvedInputs = captured.manifest; makeSnapshot = captured.make; approvedRecipeID = captured.make?.recipeID
revision = 0; readyArtifact = (0, artifact)
}
func projectRefreshRegression(_ model: CMOCDevelopmentModel) async throws -> (revision: Int, artifactID: UUID?) {
try await refresh(model)
return (revision, readyArtifact?.value.id)
}
#endif
private func sanitized(_ text: String) -> String {
var result = text
for root in [scratch, model?.project?.directory, selectedExportDirectory].compactMap({ $0 }) {
result = result.replacingOccurrences(of: root.path, with: "<project>")
}
return String(result.prefix(2000))
}
private func projectRefreshFields(_ record: MCPProjectRefreshRecord) -> [String: Any] {
var fields = record.fields; fields["project_id"] = projectID?.uuidString
fields["current_revision"] = revision
return fields
}
private func requestProjectRefresh(_ arguments: [String: Any], model: CMOCDevelopmentModel, owner: UUID) async throws -> [String: Any] {
guard arguments.count == 3, arguments["project_id"] as? String == projectID?.uuidString,
let request = arguments["request_id"] as? String, (1...128).contains(request.utf8.count),
let expected = int(arguments["revision"]), let scope else { throw problem("invalid_arguments") }
if let existing = refreshRequests[request], let record = refreshRecords[existing] {
guard record.expectedRevision == expected else { throw problem("request_id_conflict") }
if record.status == "pending" { showProjectRefresh(record) }
return projectRefreshFields(record)
}
guard expected == revision else { throw problem("stale_revision") }
guard refreshRecords.count < 64, !building, !running, !playtestBusy,
!model.building, !model.commanding, proposal?.status != "pending" else { throw problem("busy_or_review_pending") }
let captured = try await capture(model, scope: scope, updatedScope: true)
guard active, session == owner, self.model === model else { throw problem("access_denied") }
if let existing = refreshRequests[request], let record = refreshRecords[existing] {
guard record.expectedRevision == expected else { throw problem("request_id_conflict") }
return projectRefreshFields(record)
}
guard expected == revision, captured.epoch == model.assistantEditEpoch else { throw problem("stale_revision") }
let changes = approvedInputs.map { captured.manifest.changes(from: $0) } ?? []
let review = changes.contains(where: \.requiresReview)
let id = UUID().uuidString
var record = MCPProjectRefreshRecord(id: id, requestID: request, expectedRevision: expected,
identity: captured.manifest.identity, changes: changes, status: review ? "pending" : changes.isEmpty ? "unchanged" : "approved", revision: revision)
if review {
clearBuildAndLiveControls(); observedInputChanges = changes; refreshProblem = "project_refresh_pending"
if let old = refreshCandidate, var previous = refreshRecords[old.refreshID], previous.status == "pending" {
previous.status = "rejected"; previous.reason = "Replaced by a newer refresh request."; refreshRecords[previous.id] = previous
}
refreshCandidate = .init(refreshID: id, owner: owner, captured: captured)
} else {
let changed = captured.live != snapshot || captured.disk != diskSnapshot || captured.manifest != approvedInputs
try adoptCaptured(captured, model: model, advanceRevision: changed)
record.revision = revision
}
refreshRecords[id] = record; refreshRequests[request] = id; latestRefreshID = id
if review { showProjectRefresh(record) }
return projectRefreshFields(record)
}
private func showProjectRefresh(_ record: MCPProjectRefreshRecord) {
guard record.status == "pending" else { return }
refreshPanel?.close()
func describe(_ entry: CMOCProjectInputManifest.Entry?) -> String {
guard let entry else { return "absent" }
return "role=\(entry.role), included=\(entry.included), executable=\(entry.executable), permissions=\(entry.permissions.map { String($0, radix: 8) } ?? "unchanged/non-control"), SHA-256=\(entry.sha256 ?? "none")"
}
func kind(_ entry: CMOCProjectInputManifest.Entry?) -> String {
guard let entry, entry.included else { return "not shared" }
switch entry.role {
case "header": return "shared header"
case "source": return "shared source file"
case "recipe": return "build recipe"
case "project_settings": return "project settings"
case "generator": return "build script"
case "executable": return "build tool"
case "support", "pending_support_root": return entry.role == "pending_support_root" ? "support folder" : "support file"
case "generated_input": return "generated input"
case "resource": return "project resource"
default: return "shared file"
}
}
func capitalized(_ text: String) -> String { text.prefix(1).uppercased() + String(text.dropFirst()) }
func summary(_ change: CMOCProjectInputManifest.Change) -> String {
let old = change.previous, new = change.current
if old?.included != true { return "Added " + kind(new) }
if new?.included != true { return "Removed " + kind(old) }
if old?.role != new?.role { return "Changed from " + kind(old) + " to " + kind(new) }
if old?.permissions != new?.permissions || old?.executable != new?.executable {
return capitalized(kind(new)) + " permissions changed"
}
return capitalized(kind(new)) + " changed"
}
let before = approvedInputs
let after = refreshCandidate?.refreshID == record.id ? refreshCandidate?.captured.manifest : nil
func preview(_ manifest: CMOCProjectInputManifest?, path: String) -> String {
guard let data = manifest?.files[path] ?? manifest?.support.files[path] else { return "Absent" }
guard data.count <= 64 * 1024, !data.contains(0), let text = String(data: data, encoding: .utf8) else {
return "\(data.count) bytes. Review this file locally; its exact contents are identified under Verification Details."
}
return text
}
let view = VStack(alignment: .leading, spacing: 14) {
Text("Review Project Input Changes").font(.title2.bold())
Text("Approve \(record.changes.count == 1 ? "this 1 change" : "these \(record.changes.count) changes") to the shared files, build recipe and support files. Approval updates what the assistant can use and does not run the project. Your unsaved edits are kept.")
if record.changes.contains(where: { $0.current?.role == "pending_support_root" }) {
Text("New support folders have not been opened. Approving gives the assistant access to the entire named folder; its contents will be read after approval.")
.font(.callout).foregroundStyle(.secondary)
}
ScrollView {
LazyVStack(alignment: .leading, spacing: 16) {
ForEach(record.changes, id: \.path) { change in
VStack(alignment: .leading, spacing: 4) {
Text(change.path).font(.system(.body, design: .monospaced)).fontWeight(.semibold)
Text(summary(change)).font(.callout)
Text("Before: " + capitalized(kind(change.previous)) + " · After: " + capitalized(kind(change.current)))
.font(.caption).foregroundStyle(.secondary)
DisclosureGroup("Verification Details") {
Text("Before: " + describe(change.previous))
Text("After: " + describe(change.current))
}.font(.system(.caption, design: .monospaced))
DisclosureGroup("Compare File Contents") {
Text("Before").fontWeight(.semibold)
Text(preview(before, path: change.path))
Text("After").fontWeight(.semibold)
Text(preview(after, path: change.path))
}.font(.system(.caption, design: .monospaced))
}.textSelection(.enabled)
}
}.frame(maxWidth: .infinity, alignment: .leading)
}.frame(maxWidth: .infinity, maxHeight: .infinity)
HStack {
Button("Reject") { self.decideProjectRefresh(record.id, approve: false) }
Spacer()
Button("Approve Refresh") { self.decideProjectRefresh(record.id, approve: true) }.keyboardShortcut(.defaultAction)
}
}.padding(20)
let panel = window("Review Project Refresh", width: 760, height: 520, scrolls: false, view: view)
refreshPanel = panel; panel.makeKeyAndOrderFront(nil)
}
private func decideProjectRefresh(_ id: String, approve: Bool) {
guard let candidate = refreshCandidate, candidate.refreshID == id,
var record = refreshRecords[id], record.status == "pending" else { return }
if !approve {
record.status = "rejected"; record.reason = "The project input changes were rejected locally."
refreshRecords[id] = record; refreshProblem = "project_refresh_rejected"
refreshCandidate = nil; refreshPanel?.close(); refreshPanel = nil
return
}
guard refreshApprovingID != id else { return }
refreshApprovingID = id
Task {
defer { if refreshApprovingID == id { refreshApprovingID = nil } }
do {
guard let model, active, session == candidate.owner, let scope,
revision == record.expectedRevision else { throw problem("stale_revision") }
let fresh = try await capture(model, scope: scope, updatedScope: true)
guard active, session == candidate.owner, self.model === model,
refreshCandidate?.refreshID == id, fresh.manifest == candidate.captured.manifest,
fresh.epoch == candidate.captured.epoch, fresh.epoch == model.assistantEditEpoch,
revision == record.expectedRevision else { throw problem("stale_revision") }
// Only this explicit native action authorizes reading newly
// named support roots. Recheck the limited review basis both
// before and after that read; no unapproved member names/hash
// are included in pending public receipts.
let authorized = try await capture(model, scope: scope, updatedScope: true, expandedSupport: true)
guard authorized.manifest.files == fresh.manifest.files,
authorized.manifest.permissions == fresh.manifest.permissions,
authorized.manifest.configuration == fresh.manifest.configuration,
fresh.manifest.support.files.allSatisfy({ authorized.manifest.support.files[$0.key] == $0.value }),
fresh.manifest.support.permissions.allSatisfy({ authorized.manifest.support.permissions[$0.key] == $0.value }) else {
throw problem("stale_revision")
}
let finalBasis = try await capture(model, scope: scope, updatedScope: true)
guard active, session == candidate.owner, self.model === model,
refreshCandidate?.refreshID == id, finalBasis.manifest == candidate.captured.manifest,
finalBasis.epoch == candidate.captured.epoch, authorized.epoch == finalBasis.epoch,
finalBasis.epoch == model.assistantEditEpoch, revision == record.expectedRevision else { throw problem("stale_revision") }
try adoptCaptured(authorized, model: model, advanceRevision: true)
record.status = "approved"; record.revision = revision
} catch {
guard active, session == candidate.owner, refreshCandidate?.refreshID == id else { return }
record.status = "rejected"; record.reason = sanitized(error.localizedDescription); refreshProblem = "project_refresh_rejected"
}
guard active, session == candidate.owner, refreshCandidate?.refreshID == id else { return }
refreshRecords[id] = record; refreshCandidate = nil
refreshPanel?.close(); refreshPanel = nil
}
}
private func grant(_ model: CMOCDevelopmentModel, at destination: URL,
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
defer { if session == ticket { pendingModel = nil } }
await cleanup.value
guard session == ticket, model.assistantProjectID == id, presentationIsCurrent?() != false else { throw problem("access_denied") }
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
guard let self else { return Data(#"{"error":"access_denied"}"#.utf8) }
return await self.reply(data, owner: ticket)
}
let (server, file) = try await Task.detached {
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": 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 }
}.value
guard session == ticket, model.assistantProjectID == id, presentationIsCurrent?() != false else {
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")
}
@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; playtestMultiDriveApproved = false
#if DEBUG
regressionPlaytestHelper = nil; regressionStarterKit = nil
#endif
server = nil; file = nil; scratch = nil; service = nil; scope = nil
snapshot.removeAll(); diskSnapshot.removeAll(); templateDirectives.removeAll(); makeSnapshot = nil; approvedRecipeID = nil
approvedInputs = nil; observedInputChanges = []; lastAcceptedInputChanges = []; refreshRecords.removeAll(); refreshRequests.removeAll(); latestRefreshID = nil
refreshCandidate = nil; refreshProblem = nil; refreshApprovingID = nil; refreshPanel?.close(); refreshPanel = nil
work?.cancel(); guest?.cancel(); buildTask = nil; runTask = nil
builds.removeAll(); buildReports.removeAll(); latestBuildID = nil; buildRequests.removeAll(); clearBuildAndLiveControls(); building = false
proposals.removeAll(); proposalRequests.removeAll(); proposal = nil; status = ""
runID = nil; inspection = nil
runRevision = nil; runReceipt = nil; running = false; runStatus = ""; buildStatus = ""
panel?.close(); panel = nil
let startupCleanup = playtestStartupCleanup
return Task.detached {
await startupCleanup?.value
await playtestCleanup?.value
old?.stop(); grant?.remove()
await work?.value; await guest?.value; await exportTask?.value
if let dir { try? FileManager.default.removeItem(at: dir) }
}
}
func closing(_ model: CMOCDevelopmentModel) {
if self.model === model || pendingModel === model { revoke() }
if consentModel === model { consentPanel?.close(); consentPanel = nil; consentModel = nil }
}
private func reply(_ data: Data, owner: UUID) async -> Data {
func pack(_ value: [String: Any]) -> Data { (try? JSONSerialization.data(withJSONObject: value)) ?? Data() }
guard active, session == owner, let model, scope != nil, model.assistantProjectID == projectID, let id = projectID?.uuidString,
let r = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any], r["token"] as? String == token,
r["version"] as? Int == 1, let tool = r["tool"] as? String, let args = r["arguments"] as? [String: Any]
else { return pack(["error": "access_denied"]) }
func currentGrant() -> Bool {
active && session == owner && self.model === model && model.assistantProjectID == projectID
}
if tool == "search_help" || tool == "read_topic" {
let reply = await MCPHelpIndex.toolResult(tool, arguments: args)
guard currentGrant() else { return pack(["error": "access_denied"]) }
return pack(reply)
}
do {
if tool != "refresh_project" { try await refresh(model) }
guard currentGrant(), let scope else { return pack(["error": "access_denied"]) }
if let refreshProblem, !MCPProjectRefreshRecord.safeTools.contains(tool) { throw problem(refreshProblem) }
let result: [String: Any]
switch tool {
case "refresh_project":
result = try await requestProjectRefresh(args, model: model, owner: owner)
case "get_project_refresh" where args.count == 2:
guard args["project_id"] as? String == id, let refreshID = args["refresh_id"] as? String,
let record = refreshRecords[refreshID] else { throw problem("unknown_project_refresh") }
result = projectRefreshFields(record)
case "read_project_inputs":
guard Set(args.keys).isSubset(of: ["project_id", "offset", "limit"]), args["project_id"] as? String == id,
let manifest = approvedInputs else { throw problem("invalid_arguments") }
let offset = args["offset"] == nil ? 0 : int(args["offset"])
let limit = args["limit"] == nil ? 128 : int(args["limit"])
guard let offset, let limit, offset >= 0, (1...256).contains(limit) else { throw problem("invalid_arguments") }
let page = MCPProjectRefreshRecord.inputPage(manifest.entries, offset: offset, limit: limit)
var fields: [String: Any] = ["project_id": id, "revision": revision, "input_identity": manifest.identity,
"entries": page.rows, "offset": offset, "total": manifest.entries.count,
"next_offset": page.nextOffset as Any? ?? NSNull(), "page_truncated": page.truncated,
"status": refreshProblem ?? "approved"]
if let latestRefreshID, let record = refreshRecords[latestRefreshID] { fields["refresh"] = projectRefreshFields(record) }
result = fields
case "get_capabilities" where args.isEmpty:
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,
"app_version": Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "unknown",
"app_build": Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "unknown", "project_id": id, "revision": revision,
"entry": scope.entry, "target": "CoCo Disk BASIC", "build_recipe": scope.customMake ? "approved_make" : scope.helloDisk ? "installed_hello_disk" : "bundled_cmoc", "files": scope.paths, "headers": Self.headers, "session_id": owner.uuidString, "version": 1,
"banked_debug_manifest_versions": [1, 2], "verified_code_overlays": true,
"overlay_residency_evidence": "complete_mapped_code_bytes"]
if scope.customMake {
var facts = result
facts["recipe_id"] = approvedRecipeID
facts["build_actions"] = scope.configuration.diskTarget == nil ? ["build"] : ["build", "disk"]
facts["configurations"] = scope.configuration.configurations.map(\.name)
facts["configuration"] = model.configurationName
facts["targets"] = ["build": scope.configuration.buildTarget, "disk": scope.configuration.diskTarget ?? ""]
facts["build_support_directories"] = scope.configuration.buildSupportDirectories
facts["playtest_disk_products"] = scope.configuration.playtestDisks
facts["function_entry_stops"] = playtestsApproved
facts["launch_mode"] = scope.configuration.launchMode.rawValue
facts["launch_commands"] = scope.configuration.launchCommands
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"] +
(scope.helloDisk ? ["perl", "writecocofile", "install-coco-boot-loader"] : [])
var build = await MCPMachineStatus.missingToolBlockers(in: model.service.toolchain, requiring: tools)
var run: [String] = []
if refreshProblem != nil {
build.append("Refresh the changed project inputs and complete native review before building.")
run.append("Project inputs changed; refresh and rebuild before running.")
}
if builds.count >= 32 { build.append("Reconnect to start another build.") }
if building || running || model.building || model.commanding { build.append("Wait for the current operation to finish.") }
if readyArtifact?.revision != revision { run.append("Build the current project revision successfully.") }
if proposal?.status == "pending" { run.append("Review the pending C source change.") }
else if !readyToRun && readyArtifact?.revision == revision { run.append("Apply a source change to run the reviewed Hello Disk build.") }
if model.machine.busy || building || running || model.commanding { run.append("Wait for the current operation to finish.") }
result = MCPMachineStatus.result(observed, workspace: .cmoc(needsFloppy: scope.helloDisk),
buildBlockers: build, runBlockers: run, lastBuild: latestBuildID.flatMap(buildRecord),
profile: model.machine.usageProfile, input: model.machine.inputDiagnostics(machine: observed))
case "read_project_file" where args.count == 2:
guard args["project_id"] as? String == id, let path = args["path"] as? String else { throw problem("access_denied") }
let text: String
if Self.headers.contains(path) {
let url = model.service.toolchain.appendingPathComponent("share/cmoc/include").appendingPathComponent((path as NSString).lastPathComponent)
text = try await Task.detached { try CMOCProject.readText(url, maximumBytes: 65536) }.value
guard active, session == owner, model.assistantProjectID == projectID else { throw problem("access_denied") }
} else { text = try read(path) }
result = ["project_id": id, "revision": revision, "path": path, "text": text]
case "build_project" where args.count >= 3 && args.count <= 5:
guard args["project_id"] as? String == id else { throw problem("access_denied") }
guard Set(args.keys).isSubset(of: ["project_id", "revision", "request_id", "action", "configuration"]),
scope.customMake || args.count == 3,
args["action"] == nil || args["action"] is String,
args["configuration"] == nil || args["configuration"] is String else { throw problem("invalid_arguments") }
result = try startBuild(request: args["request_id"] as? String, revision: int(args["revision"]), model: model,
action: args["action"] as? String, configuration: args["configuration"] as? String)
case "get_build" where args.count == 1:
guard let id = args["build_id"] as? String, let build = buildRecord(id) else { throw problem("unknown_build") }
result = build
case "get_build_log":
guard Set(args.keys).isSubset(of: ["build_id", "offset", "limit"]),
let buildID = args["build_id"] as? String, let build = buildRecord(buildID) else { throw problem("unknown_build") }
guard let report = buildReports[buildID] else { throw problem("build_log_pending") }
let offset = args["offset"] == nil ? 0 : int(args["offset"])
let limit = args["limit"] == nil ? 16_384 : int(args["limit"])
guard let offset, let limit else { throw problem("invalid_arguments") }
var page = try report.logPage(offset: offset, limit: limit)
for key in ["build_id", "project_id", "revision", "action", "configuration", "status"] { page[key] = build[key] }
result = page
case "propose_fix" where args.count == 6:
guard args["project_id"] as? String == id else { throw problem("access_denied") }
result = try propose(args)
case "propose_project_edits" where args.count == 4:
guard args["project_id"] as? String == id else { throw problem("access_denied") }
result = try proposeEdits(args, scope: scope)
case "get_proposal" where args.count == 1:
guard let id = args["proposal_id"] as? String, let p = proposals[id] else { throw problem("unknown_proposal") }
result = p.result
case "list_playtest_media":
guard playtestMediaApproved,
Set(args.keys).isSubset(of: ["project_id", "revision", "artifact_id", "run_id"]),
(3...4).contains(args.count), args["project_id"] as? String == id,
int(args["revision"]) == revision, let ready = readyArtifact, ready.revision == revision,
args["artifact_id"] as? String == ready.value.id.uuidString else { throw problem("invalid_playtest_selection") }
let storage = try retainedDiskContext(model)
let products = try await artifactMedia(ready.value, projectKey: storage.key)
guard currentGrant(), readyArtifact?.value.id == ready.value.id,
workspaceEpoch == model.assistantEditEpoch else { throw problem("stale_run") }
let retained = try await MCPPlaytestDiskStore.list(directory: storage.directory, projectKey: storage.key)
guard currentGrant(), readyArtifact?.value.id == ready.value.id,
workspaceEpoch == model.assistantEditEpoch else { throw problem("stale_run") }
var state: [String: Any] = [:]
if let supplied = args["run_id"] {
guard let run = supplied as? String, let owned = playtest, owned.runID == run,
ownsPlaytest(owned, artifact: ready.value, owner: owner), !playtestBusy else { throw problem("stale_run") }
playtestBusy = true
do {
state = try await owned.reply("list_playtest_media", arguments: ["run_id": run])
playtestBusy = false
} catch { playtestBusy = false; throw error }
guard ownsPlaytest(owned, artifact: ready.value, owner: owner) else { throw problem("stale_run") }
}
var rows = state["media"] as? [[String: Any]] ?? products.map { item in
["media_id": item.id, "name": item.name, "media_key": item.key, "base_sha256": item.baseSHA256,
"media_sha256": item.baseSHA256, "byte_count": item.data.count, "inserted": false, "dirty": false, "retained": false]
}
for index in rows.indices {
guard let key = rows[index]["media_key"] as? String,
let product = products.first(where: { $0.key == key }) else { continue }
let choices = retained.filter {
$0.provenance.artifactDiskSHA256 == ready.value.diskSHA256 &&
($0.provenance.mediaKey ?? "primary") == key &&
($0.provenance.mediaBaseSHA256 ?? $0.provenance.artifactDiskSHA256) == product.baseSHA256
}
rows[index]["retained_disks"] = Array(choices.prefix(16)).map(\.publicFields)
rows[index]["retained_disk_count"] = choices.count
rows[index]["retained_disks_truncated"] = choices.count > 16
}
state["media"] = rows; state["project_id"] = id; state["revision"] = revision
state["artifact_id"] = ready.value.id.uuidString; state["drive"] = "FD0"
result = state
case "list_playtest_disks":
guard playtestsApproved, args.count == 1, args["project_id"] as? String == id else { throw problem("access_denied") }
let storage = try retainedDiskContext(model)
let records = try await MCPPlaytestDiskStore.list(directory: storage.directory, projectKey: storage.key)
guard currentGrant(), workspaceEpoch == model.assistantEditEpoch else { throw problem("stale_run") }
// The legacy endpoint selects only the primary boot disk.
// Additional media histories belong to list_playtest_media.
result = ["project_id": id, "disks": records.filter { ($0.provenance.mediaKey ?? "primary") == "primary" }.map(\.publicFields)]
case "start_playtest":
guard playtestsApproved else { throw problem("access_denied") }
result = try await startPlaytest(args, model: model, owner: owner)
case "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", "exchange_playtest_media":
if tool == "stop_playtest", playtestsApproved, args.count == 2,
let runID = args["run_id"] as? String, let request = args["request_id"] as? String,
(1...128).contains(request.utf8.count),
let start = playtestStarts.values.first(where: { $0.runID == runID }), start.status != "ready" {
guard start.revision == revision, start.artifactID == readyArtifact?.value.id.uuidString else { throw problem("stale_run") }
start.cancel()
result = start.fields
break
}
guard tool != "exchange_playtest_media" || playtestMediaApproved else { throw problem("access_denied") }
guard playtestsApproved, let owned = playtest, args["run_id"] as? String == owned.runID,
let artifact = readyArtifact, artifact.revision == revision,
owned.artifactID == artifact.value.id.uuidString, !playtestBusy else { throw problem("stale_run") }
playtestBusy = true
defer { playtestBusy = false }
if !["capture_playtest", "capture_playtest_graphics", "get_playtest_input", "start_playtest_video", "stop_playtest_video", "read_playtest_video"].contains(tool) { ownedInspection = nil }
var request = args
if tool == "playtest_debug" {
guard Set(args.keys).isSubset(of: ["run_id", "request_id", "action", "function", "stop_kind"]), let action = args["action"] as? String else { throw problem("invalid_arguments") }
if action == "stop_at" {
guard (4...5).contains(args.count), let function = args["function"] as? String else { throw problem("invalid_arguments") }
let kind = try functionStopKind(args["stop_kind"])
request.removeValue(forKey: "function"); request.removeValue(forKey: "stop_kind")
request["selection"] = kind + ":" + function
let point = try await verifiedFunction(function, artifact: artifact.value, kind: kind)
request["address"] = Int(point.address)
if let module = point.moduleID { request["module_id"] = module }
} else if args.count != 3 { throw problem("invalid_arguments") }
}
guard ownsPlaytest(owned, artifact: artifact.value, owner: owner) else { throw problem("stale_run") }
result = try await owned.reply(tool, arguments: request, isCurrent: { self.ownsPlaytest(owned, artifact: artifact.value, owner: owner) })
guard ownsPlaytest(owned, artifact: artifact.value, owner: owner) else { throw problem("stale_run") }
case "read_screen_text", "send_keys":
guard let io = liveIO, let runID, args["run_id"] as? String == runID,
let artifact = readyArtifact, artifact.revision == revision, runRevision == revision,
inspection?.fields["artifact_id"] as? String == artifact.value.id.uuidString else { throw problem("stale_run") }
result = try await io.reply(tool, arguments: args)
guard currentGrant(), liveIO === io, self.runID == runID, runRevision == revision,
model.assistantEditEpoch == workspaceEpoch, readyArtifact?.value.id == artifact.value.id else {
throw problem("stale_run")
}
case "get_call_context":
guard callContextApproved, playtestsApproved,
Set(args.keys) == ["run_id", "snapshot_id"],
let owned = playtest, args["run_id"] as? String == owned.runID,
!playtestBusy, let artifact = readyArtifact, artifact.revision == revision,
artifact.value.id.uuidString == owned.artifactID else { throw problem("access_denied") }
playtestBusy = true; defer { playtestBusy = false }
result = try await ownedDebugReply(tool, arguments: args, owned: owned, artifact: artifact.value, owner: owner)
case "get_debug_snapshot", "read_debug_memory":
if let owned = playtest, args["run_id"] as? String == owned.runID {
guard playtestsApproved, !playtestBusy, let artifact = readyArtifact, artifact.revision == revision,
artifact.value.id.uuidString == owned.artifactID else { throw problem("stale_run") }
playtestBusy = true; defer { playtestBusy = false }
result = try await ownedDebugReply(tool, arguments: args, owned: owned, artifact: artifact.value, owner: owner)
break
}
guard let runID, args["run_id"] as? String == runID, runRevision == revision,
let artifact = readyArtifact, let inspection, inspection.runID == runID,
inspection.fields["artifact_id"] as? String == artifact.value.id.uuidString else { throw problem("stale_run") }
let now = await model.machine.mcpMachineSnapshot()
guard currentGrant(), self.runID == runID, runRevision == revision, workspaceEpoch == model.assistantEditEpoch,
readyArtifact?.value.id == artifact.value.id,
MCPDebuggerInspection.sameProgram(now, inspection.machine) else { throw problem("stale_run") }
result = try inspection.reply(tool: tool, arguments: args)
case "get_run" where args.count == 2:
guard args["project_id"] as? String == id else { throw problem("access_denied") }
if let start = latestPlaytestStart, start.status != "ready" {
guard int(args["revision"]) == revision, start.revision == revision,
start.artifactID == readyArtifact?.value.id.uuidString else { throw problem("stale_revision") }
result = start.fields
break
}
if let owned = playtest, int(args["revision"]) == owned.revision, let artifact = readyArtifact {
guard ownsPlaytest(owned, artifact: artifact.value, owner: owner), !playtestBusy else { throw problem("stale_run") }
playtestBusy = true; defer { playtestBusy = false }
var receipt = try await owned.capture()
receipt.removeValue(forKey: "png_base64")
guard ownsPlaytest(owned, artifact: artifact.value, owner: owner) else { throw problem("stale_run") }
result = ["project_id": id, "revision": revision, "run_id": owned.runID, "artifact_id": artifact.value.id.uuidString,
"owned_playtest": true, "requested_processor": owned.processor.rawValue,
"status": "ready", "phase": "ready", "busy": false, "receipt": receipt]
break
}
guard runRevision != nil else { throw problem("no_run") }
guard int(args["revision"]) == revision, runRevision == revision else { throw problem("stale_revision") }
var state: [String: Any] = ["project_id": id, "revision": revision, "busy": running, "status": runStatus]
state["run_id"] = runID as Any? ?? NSNull()
if let runReceipt { state["receipt"] = runReceipt }
if let io = liveIO, let inspection, let runID {
let observed = await model.machine.mcpMachineSnapshot()
guard currentGrant(), liveIO === io, self.runID == runID, runRevision == revision,
workspaceEpoch == model.assistantEditEpoch,
MCPDebuggerInspection.sameProgram(observed, inspection.machine),
observed.debuggerDevelopmentAttached else { throw problem("stale_run") }
if observed.assistantCompiledReturned {
let text = try await io.finalScreenText()
guard currentGrant(), liveIO === io, self.runID == runID, runRevision == revision,
workspaceEpoch == model.assistantEditEpoch else { throw problem("stale_run") }
if let text { state["final_screen_text"] = text }
state["status"] = "finished"
runStatus = "The C program returned to BASIC."
} else {
state["status"] = observed.state == .paused ? "paused" : "running"
}
}
result = state
default: throw problem("invalid_arguments")
}
guard currentGrant() else { return pack(["error": "access_denied"]) }
return pack(["result": result])
} catch {
guard currentGrant() else { return pack(["error": "access_denied"]) }
let message = sanitized(error.localizedDescription)
let stale = message.contains("stale") || refreshProblem != nil || message.contains("external_file_change")
if stale {
let changes = observedInputChanges.isEmpty ? lastAcceptedInputChanges : observedInputChanges
var details: [String: Any] = ["error": message, "current_revision": revision,
"current_artifact_id": readyArtifact?.value.id.uuidString as Any? ?? NSNull(),
"changed_input_paths": Array(changes.prefix(128)).map(\.path),
"changed_input_paths_total": changes.count, "changed_input_paths_truncated": changes.count > 128, "input_status": refreshProblem ?? "approved"]
if let expected = int(args["revision"]) { details["expected_revision"] = expected }
if let expected = args["artifact_id"] as? String { details["expected_artifact_id"] = expected }
if let latestRefreshID { details["refresh_id"] = latestRefreshID }
return pack(["error": message, "error_details": details])
}
return pack(["error": message])
}
}
private func ownsPlaytest(_ owned: MCPPlaytest, artifact: CMOCBuildArtifact, owner: UUID) -> Bool {
active && session == owner && playtest === owned && readyArtifact?.value.id == artifact.id &&
readyArtifact?.revision == revision && owned.revision == revision &&
workspaceEpoch == model?.assistantEditEpoch && projectID == model?.assistantProjectID
}
private func retainedDiskContext(_ model: CMOCDevelopmentModel) throws -> (directory: URL, key: String) {
guard let project = model.project else { throw problem("project_unavailable") }
let identity = project.directory.standardizedFileURL.resolvingSymlinksInPath().path
return (model.machine.developmentRunDirectory.appendingPathComponent("Assistant Playtests"),
CMOCProject.sha256(Data(identity.utf8)))
}
private func startPlaytest(_ arguments: [String: Any], model: CMOCDevelopmentModel, owner: UUID) async throws -> [String: Any] {
guard Set(arguments.keys).isSubset(of: ["project_id", "revision", "artifact_id", "request_id", "stop_function", "stop_kind", "retained_disk_id", "retained_disk_sha256", "processor", "retained_media"]),
(4...10).contains(arguments.count), arguments["project_id"] as? String == projectID?.uuidString,
int(arguments["revision"]) == revision, let request = arguments["request_id"] as? String,
(1...128).contains(request.utf8.count), let ready = readyArtifact, ready.revision == revision,
arguments["artifact_id"] as? String == ready.value.id.uuidString,
!building, !running, proposal?.status != "pending", let scope else { throw problem("invalid_playtest_selection") }
let artifact = ready.value
let processor = try MCPPlaytestProcessor.selected(arguments["processor"])
let function = arguments["stop_function"] as? String
let kind = try functionStopKind(arguments["stop_kind"])
guard arguments["stop_kind"] == nil || function != nil else { throw problem("invalid_arguments") }
guard arguments["stop_function"] == nil || (function != nil && !(function?.isEmpty ?? true)) else { throw problem("invalid_arguments") }
let retainedID = arguments["retained_disk_id"] as? String
let retainedSHA = arguments["retained_disk_sha256"] as? String
var retainedMedia: [[String: String]] = []
if let value = arguments["retained_media"] {
guard playtestMediaApproved, let records = value as? [[String: String]], (1...8).contains(records.count),
Set(records.compactMap { $0["media_id"] }).count == records.count,
records.allSatisfy({ Set($0.keys) == ["media_id", "retained_disk_id", "retained_disk_sha256"] }) else {
throw problem("invalid_retained_media_selection")
}
let allowed = Set(artifact.playtestDiskProducts.map {
MCPPlaytestMedium.identifier(artifactID: artifact.id.uuidString, key: "disk:" + $0.relativePath)
})
guard records.allSatisfy({ allowed.contains($0["media_id"] ?? "") }) else { throw problem("invalid_retained_media_selection") }
retainedMedia = records
}
guard (arguments["retained_disk_id"] == nil && arguments["retained_disk_sha256"] == nil) ||
(retainedID != nil && retainedSHA != nil) else { throw problem("invalid_retained_disk_selection") }
let selection: [String: Any] = ["artifact": artifact.id.uuidString, "revision": revision, "stop_kind": kind, "processor": processor.rawValue,
"function": function as Any? ?? NSNull(), "retained_media": retainedMedia, "retained_disk_id": retainedID as Any? ?? NSNull(),
"retained_disk_sha256": retainedSHA as Any? ?? NSNull()]
let identity = CMOCProject.sha256(try JSONSerialization.data(withJSONObject: selection, options: [.sortedKeys]))
if let existing = playtestStarts[request] {
guard existing.identity == identity,
existing.status != "ready" || playtest?.runID == existing.runID else { throw problem("request_id_conflict") }
return existing.fields
}
guard !playtestBusy else { throw problem("playtest_busy") }
#if DEBUG
let selectedKit = regressionStarterKit ?? StarterKit.bundled
#else
let selectedKit = StarterKit.bundled
#endif
guard playtestStarts.count < 16, let diskURL = artifact.diskURL, let kit = selectedKit else { throw problem("disk_playtest_unavailable") }
let start = MCPOwnedPlaytestStart(identity: identity, requestID: request, projectID: projectID!.uuidString,
revision: revision, artifactID: artifact.id.uuidString, processor: processor,
redactionRoots: [scratch, artifact.directory, artifact.compilationDirectory].compactMap { $0 })
let priorCleanup = playtestStartupCleanup
playtestStarts[request] = start; latestPlaytestStart = start; playtestBusy = true
start.launch { [self] start in
defer { if latestPlaytestStart === start { playtestBusy = false } }
return try await preparePlaytest(start, artifact: artifact, diskURL: diskURL, kit: kit,
function: function, kind: kind, retainedID: retainedID, retainedSHA: retainedSHA, retainedMedia: retainedMedia, processor: processor,
model: model, owner: owner, scope: scope, priorCleanup: priorCleanup)
}
return start.fields
}
private func preparePlaytest(_ start: MCPOwnedPlaytestStart, artifact: CMOCBuildArtifact, diskURL: URL,
kit: StarterKit, function: String?, kind: String, retainedID: String?, retainedSHA: String?, retainedMedia: [[String: String]], processor: MCPPlaytestProcessor,
model: CMOCDevelopmentModel, owner: UUID, scope: MCPCMOCProject,
priorCleanup: Task<Void, Never>?) async throws -> [String: Any] {
func current() -> Bool {
start.acceptingResult && latestPlaytestStart === start && active && session == owner &&
self.model === model && readyArtifact?.value.id == artifact.id && readyArtifact?.revision == revision &&
start.revision == revision && workspaceEpoch == model.assistantEditEpoch && projectID == model.assistantProjectID
}
guard current() else { throw problem("stale_run") }
start.updatePhase("waiting_for_previous_startup_cleanup")
await priorCleanup?.value
guard current() else { throw problem("stale_run") }
start.updatePhase("preparing_debug_metadata")
var modules: [[String: Any]] = [], flatGuards: [[String: Any]] = [], stop: UInt16?, stopModule: String?
var graphicsBuffers: [[String: Any]] = []
let evidence: (map: CMOCProjectSourceMap, variables: CMOCVariableDebug?, variableError: String?)?
do { evidence = try await debugMetadata(artifact) }
catch {
if artifact.debugManifestRelativePath != nil || function != nil { throw error }
evidence = nil // A playable build need not have source debug evidence.
}
if let evidence {
let map = evidence.map
guard current() else { throw problem("stale_run") }
if let function {
let point = try await verifiedFunction(function, artifact: artifact, kind: kind)
stop = point.address; stopModule = point.moduleID
}
if let layout = map.bankedLayout {
graphicsBuffers = layout.framebuffers.map(\.workerFields)
modules = layout.modules.compactMap { module in
let code = module.codeGuards
guard !code.isEmpty else { return nil }
var definition: [String: Any] = ["id": module.id, "pages": module.pages.map { ["logical_page": $0.logicalPage, "physical_page": $0.physicalPage] },
"guards": code.map { ["address": Int($0.address), "bytes_base64": Data($0.bytes).base64EncodedString()] }]
if let overlay = module.overlay {
definition["overlay_group"] = overlay.group; definition["overlay_owner"] = overlay.owner
}
return definition
}
} else {
flatGuards = map.flatCodeGuards.map(\.workerFields)
guard !flatGuards.isEmpty else { throw problem("verified_flat_code_unavailable") }
}
}
guard current() else { throw problem("stale_run") }
start.updatePhase("reading_artifact")
let payload = try await Task.detached {
(try ROMImage.read(kit.directory.appendingPathComponent("coco3.rom")),
try DiskFiles.readROM(kit.directory.appendingPathComponent("disk11.rom")),
try artifact.playtestPrimaryDiskData())
}.value
guard current() else { throw problem("stale_run") }
guard let expectedDisk = artifact.diskSHA256, CMOCProject.sha256(payload.2) == expectedDisk else { throw problem("artifact_disk_changed") }
let storage = try retainedDiskContext(model)
var selectedDisk = payload.2
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,
expectedSHA256: retainedSHA, projectKey: storage.key, artifactDiskSHA256: expectedDisk)
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, writeProtected: selectedWriteProtected)
var media: [MCPPlaytestMedium]?
if playtestMediaApproved {
var selected = try await artifactMedia(artifact, projectKey: storage.key, primaryData: payload.2)
guard current(), let primary = selected.first else { throw problem("stale_run") }
selected[0] = MCPPlaytestMedium(id: primary.id, name: primary.name, key: primary.key,
baseSHA256: primary.baseSHA256, data: selectedDisk, provenance: provenance)
for saved in retainedMedia {
guard let id = saved["media_id"], let index = selected.firstIndex(where: { $0.id == id }), index > 0,
let diskID = saved["retained_disk_id"], let hash = saved["retained_disk_sha256"] else { throw problem("invalid_retained_media_selection") }
let item = selected[index]
let copy = try await MCPPlaytestDiskStore.load(directory: storage.directory, id: diskID, expectedSHA256: hash,
projectKey: storage.key, artifactDiskSHA256: expectedDisk, mediaKey: item.key, mediaBaseSHA256: item.baseSHA256)
guard current() else { throw problem("stale_run") }
let prior = copy.record.provenance
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, writeProtected: prior.writeProtected)
selected[index] = MCPPlaytestMedium(id: item.id, name: item.name, key: item.key,
baseSHA256: item.baseSHA256, data: copy.data, provenance: origin)
}
media = selected
}
if let previous = playtest {
start.updatePhase("retaining_previous_run")
try await previous.retainForReplacement()
guard playtest === previous else { throw problem("stale_run") }
playtest = nil
}
ownedInspection = nil
guard current() else { throw problem("stale_run") }
start.updatePhase("booting")
var helperURL: URL?
#if DEBUG
helperURL = regressionPlaytestHelper
#endif
let owned = try await MCPPlaytest.start(systemROM: payload.0, diskROM: payload.1, disk: selectedDisk,
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, multiDrive: playtestMultiDriveApproved)
guard current() else { await owned.invalidate().value; throw problem("stale_run") }
playtest = owned
start.updatePhase("capturing_initial_state")
do {
let result = try await owned.capture()
guard current(), ownsPlaytest(owned, artifact: artifact, owner: owner) else { throw problem("stale_run") }
return result
} catch {
await owned.invalidate().value
if playtest === owned { playtest = nil }
throw error
}
}
private func artifactMedia(_ artifact: CMOCBuildArtifact, projectKey: String, primaryData: Data? = nil) async throws -> [MCPPlaytestMedium] {
try await Task.detached {
let primary = try primaryData ?? artifact.playtestPrimaryDiskData()
guard let base = artifact.diskSHA256, CMOCProject.sha256(primary) == base else { throw ProfileFailure.message("artifact_disk_changed") }
func medium(key: String, name: String, hash: String, bytes: Data) -> MCPPlaytestMedium {
let origin = MCPPlaytestDiskStore.Provenance(projectKey: projectKey, artifactID: artifact.id.uuidString,
artifactDiskSHA256: base, mediaKey: key, mediaBaseSHA256: hash)
return MCPPlaytestMedium(id: MCPPlaytestMedium.identifier(artifactID: artifact.id.uuidString, key: key),
name: name, key: key, baseSHA256: hash, data: bytes, provenance: origin)
}
var result = [medium(key: "primary", name: artifact.diskRelativePath ?? "Boot disk", hash: base, bytes: primary)]
for product in artifact.playtestDiskProducts {
let bytes = try artifact.playtestDiskData(for: product)
result.append(medium(key: "disk:" + product.relativePath, name: product.relativePath, hash: product.sha256, bytes: bytes))
}
return result
}.value
}
private func debugMetadata(_ artifact: CMOCBuildArtifact) async throws -> (map: CMOCProjectSourceMap, variables: CMOCVariableDebug?, variableError: String?) {
if let cached = readyDebugMetadata, cached.artifactID == artifact.id { return (cached.map, cached.variables, cached.variableError) }
let owner = session
let verified = try await Task.detached {
let map = try CMOCProjectSourceMap.parse(artifact: artifact)
do { return (map, Optional(try CMOCVariableDebug.parse(artifact: artifact, verifiedMap: map)), Optional<String>.none) }
catch { return (map, Optional<CMOCVariableDebug>.none, Optional(error.localizedDescription)) }
}.value
guard active, session == owner, readyArtifact?.value.id == artifact.id, readyArtifact?.revision == revision,
workspaceEpoch == model?.assistantEditEpoch, projectID == model?.assistantProjectID else { throw problem("stale_run") }
readyDebugMetadata = (artifact.id, verified.0, verified.1, verified.2)
return verified
}
private func functionStopKind(_ value: Any?) throws -> String {
guard value != nil else { return "c_line" }
guard let kind = value as? String, ["c_line", "function_entry"].contains(kind) else { throw problem("invalid_arguments") }
return kind
}
private func verifiedFunction(_ name: String, artifact: CMOCBuildArtifact, kind: String = "c_line") async throws -> (address: UInt16, moduleID: String?) {
let (map, metadata, _) = try await debugMetadata(artifact)
if kind == "function_entry", let function = metadata?.entryFunction(named: name), let address = UInt16(exactly: function.entry) {
return (address, function.moduleID)
}
if kind == "function_entry", let symbol = map.executableSymbol(named: name) { return (symbol.address, symbol.moduleID) }
if kind == "c_line", let point = metadata?.breakpointInstruction(named: name) { return (point.address, point.moduleID) }
throw problem("verified_function_unavailable: Choose a function from the build receipt's functions or function_entries list for the selected stop kind.")
}
private func ownedDebugReply(_ tool: String, arguments: [String: Any], owned: MCPPlaytest,
artifact: CMOCBuildArtifact, owner: UUID) async throws -> [String: Any] {
let capture = try await owned.debugCapture()
guard ownsPlaytest(owned, artifact: artifact, owner: owner),
capture["processor"] as? String == owned.processor.rawValue,
capture["paused"] as? Bool == true, capture["attached"] as? Bool == true,
let clock = capture["field_clock"] as? Int,
let captureFingerprint = Self.ownedCaptureFingerprint(capture) else { throw problem("verified_pause_required") }
if tool == "get_call_context" {
guard callContextApproved, Set(arguments.keys) == ["run_id", "snapshot_id"],
let previous = ownedInspection, previous.run == owned.runID,
arguments["snapshot_id"] as? String == previous.id,
previous.clock == clock, previous.fingerprint == captureFingerprint,
var context = previous.callContext else { throw problem("stale_or_unavailable_call_context") }
for key in ["run_id", "snapshot_id", "artifact_id", "project_id", "revision", "processor", "requested_processor",
"execution_mode", "md_register", "field_clock", "boot", "stop_kind", "mapping_fingerprint", "program_revision", "residency_fingerprint", "overlay_residency"] {
context[key] = previous.fields[key] ?? NSNull()
}
return context
}
if tool == "read_debug_memory" {
guard arguments.count == 4, let previous = ownedInspection, previous.run == owned.runID,
previous.clock == clock, arguments["snapshot_id"] as? String == previous.id,
previous.fingerprint == captureFingerprint,
let address = int(arguments["address"]), let count = int(arguments["count"]),
(1...256).contains(count), address >= 0, address <= 0xff00 - count,
previous.ranges.contains(where: { $0.contains(address) && address + count <= $0.upperBound }) else { throw problem("stale_or_unavailable_memory") }
return ["run_id": owned.runID, "snapshot_id": previous.id, "address": address, "count": count,
"bytes": Array(previous.memory[address..<(address + count)]).map(Int.init)]
}
guard arguments.count == 1, let encoded = capture["logical_memory"] as? String,
let memory = Data(base64Encoded: encoded), memory.count == 65536,
let encodedAvailable = capture["available"] as? String, let available = Data(base64Encoded: encodedAvailable), available.count == memory.count,
let pc = capture["pc"] as? Int, let address = UInt16(exactly: pc),
let registers = capture["registers"] as? [String: Int],
let stackPointer = registers["S"].flatMap({ UInt16(exactly: $0) }),
let framePointer = registers["U"].flatMap({ UInt16(exactly: $0) }),
let rawPages = capture["physical_pages"] as? [String: Int] else { throw problem("invalid_worker_capture") }
let pages = Dictionary(uniqueKeysWithValues: rawPages.compactMap { key, value in Int(key).map { ($0, value) } })
let (verifiedMap, verifiedMetadata, variableError) = try await debugMetadata(artifact)
guard ownsPlaytest(owned, artifact: artifact, owner: owner) else { throw problem("stale_run") }
let map = verifiedMap.projected(physicalPages: pages, memory: memory, available: available)
if verifiedMap.bankedLayout?.overlayGroups.isEmpty == false {
guard let residency = capture["residency_fingerprint"] as? String, UInt64(residency) != nil,
residency != "0" else { throw problem("overlay_residency_unavailable") }
}
let metadata = verifiedMetadata?.projected(physicalPages: pages, memory: memory, available: available)
let shared = Set(scope?.paths ?? [])
let point = map.instruction(at: address).flatMap { shared.contains($0.sourcePath) ? $0 : nil }
let function = metadata?.entryFunction(containing: address).flatMap { shared.contains($0.sourcePath) ? $0 : nil }
let executable = map.executableLocation(at: address, memory: memory, available: available, sharedPaths: shared)
guard point != nil || function != nil || executable != nil,
map.verifiesRuntime(memory: memory, available: available) else { throw problem("stale_program_bytes") }
if let point {
guard pc + point.bytes.count <= memory.count, point.bytes == Array(memory[pc..<(pc + point.bytes.count)]) else { throw problem("stale_program_bytes") }
}
let evaluator = metadata.map { CMOCWatchEvaluator(metadata: $0, context: .init(pc: address, u: UInt16(registers["U"] ?? 0), memory: memory, available: available), frameLocalsAvailable: false) }
var ranges = map.instructions.filter { shared.contains($0.sourcePath) }.map { Int($0.address)..<(Int($0.address) + $0.bytes.count) }
ranges += map.executableCodeRanges(sharedPaths: shared)
ranges += (metadata?.functions ?? []).compactMap { function -> Range<Int>? in
guard shared.contains(function.sourcePath), metadata?.entryFunction(named: function.name) != nil else { return nil }
return function.entry..<function.end
}
ranges += (metadata?.variables ?? []).compactMap { variable in
guard shared.contains(variable.sourcePath), let start = variable.address, variable.type.size > 0,
start >= 0, start + variable.type.size <= 0xfe00 else { return nil }
return start..<(start + variable.type.size)
}
var permitted = IndexSet()
for range in ranges where available[range].allSatisfy({ $0 != 0 }) { permitted.insert(integersIn: range) }
ranges = Array(permitted.rangeView)
let watches: [[String: Any]] = evaluator == nil ? [] : (model?.watches.map { name in
guard name.range(of: #"^[A-Za-z_][A-Za-z_0-9]*$"#, options: .regularExpression) != nil else {
return ["name": name, "unavailable": "Only locally configured named variables are shared."]
}
let value = evaluator!.evaluate(name)
if let error = value.error { return ["name": name, "unavailable": error] }
var row: [String: Any] = ["name": name, "type": value.typeName, "value": value.value]
if let address = value.address, let variable = metadata?.variables.first(where: { $0.name == name && $0.address == Int(address) }),
ranges.contains(where: { $0.contains(Int(address)) && Int(address) + variable.type.size <= $0.upperBound }) {
row["address"] = Int(address); row["byte_count"] = variable.type.size
if let moduleID = variable.moduleID { row["module_id"] = moduleID }
if let page = pages[Int(address) / 8192] { row["physical_address"] = page * 8192 + Int(address) % 8192 }
}
return row
} ?? [])
let globals = CMOCPublicDebugEvidence.globals(metadata: metadata, sharedPaths: shared,
context: .init(pc: address, u: UInt16(registers["U"] ?? 0), memory: memory, available: available),
permittedRanges: ranges, physicalPages: pages)
let snapshot = UUID().uuidString
let sourceStop: [String: Any]? = point.map { point in
let physical: Int? = point.physicalAddress.map { Int($0) }
?? pages[pc / 8192].map { $0 * 8192 + pc % 8192 }
return ["path": point.sourcePath, "line": point.sourceLine, "address": pc,
"module_id": point.moduleID as Any? ?? NSNull(), "physical_address": physical as Any? ?? NSNull()]
}
let functionStop: [String: Any]? = function.map { function in
var declaration: [String: Any] = ["path": function.sourcePath]
if let line = function.sourceLine { declaration["line"] = line }
let physical = function.moduleID.flatMap { map.bankedLayout?.module(id: $0)?.physicalAddress(pc) }.map { Int($0) }
?? pages[pc / 8192].map { $0 * 8192 + pc % 8192 }
return ["name": function.name, "entry_address": function.entry, "address": pc, "at_entry": pc == function.entry,
"instruction_offset": pc - function.entry, "module_id": function.moduleID as Any? ?? NSNull(),
"physical_address": physical as Any? ?? NSNull(), "declaration": declaration]
}
let sharedModules = map.sharedExecutableModuleIDs(paths: shared)
let symbols = map.executableSymbols.filter { $0.address == address && sharedModules.contains($0.moduleID) }.map { symbol in
["name": symbol.name, "address": Int(symbol.address), "module_id": symbol.moduleID,
"physical_address": symbol.physicalAddress, "object_path": symbol.objectPath, "section": symbol.sectionName] as [String: Any]
}
let symbolCatalog = CMOCSourceMap.boundedJSONCatalog(symbols)
let executableStop: [String: Any]? = executable.map { location in
["address": pc, "module_id": location.moduleID, "physical_address": location.physicalAddress,
"code_range": ["address": location.codeRange.lowerBound, "count": location.codeRange.count]]
}
let stopKind = function?.entry == pc ? "function_entry" : point != nil ? "c_line" : !symbols.isEmpty ? "symbol_entry" : "assembly_instruction"
let fields: [String: Any] = ["run_id": owned.runID, "snapshot_id": snapshot, "artifact_id": artifact.id.uuidString,
"project_id": owned.projectID, "revision": owned.revision, "status": "paused", "processor": capture["processor"] as Any? ?? NSNull(),
"requested_processor": owned.processor.rawValue, "execution_mode": capture["execution_mode"] as Any? ?? NSNull(),
"md_register": capture["md_register"] as Any? ?? NSNull(), "field_clock": clock, "boot": capture["boot"] as Any? ?? NSNull(),
"registers": registers, "stop_kind": stopKind, "source_stop": sourceStop as Any? ?? NSNull(),
"function_stop": functionStop as Any? ?? NSNull(), "watches": watches,
"globals": globals.items, "globals_total": globals.total, "globals_truncated": globals.truncated,
"mapping_fingerprint": capture["mapping_fingerprint"] as Any? ?? NSNull(),
"program_revision": capture["program_revision"] as Any? ?? NSNull(),
"residency_fingerprint": capture["residency_fingerprint"] as Any? ?? "0",
"overlay_residency": map.bankedLayout?.overlayGroups.map { group in
let activeOwners = Set(map.bankedLayout!.modules.compactMap { module -> String? in
guard map.activeModuleIDs?.contains(module.id) == true, let overlay = module.overlay,
overlay.group == group.id else { return nil }
return overlay.owner
})
return ["group": group.id, "owner": activeOwners.count == 1 ? activeOwners.first! as Any : NSNull(),
"status": activeOwners.count == 1 ? "verified" : "unavailable"] as [String: Any]
} ?? [],
"physical_pages": rawPages,
"symbol_stop": symbols.count == 1 ? symbolCatalog.items.first as Any? ?? NSNull() : NSNull(),
"symbols_at_pc": symbolCatalog.items, "symbols_at_pc_total": symbolCatalog.total, "symbols_at_pc_truncated": symbolCatalog.truncated,
"executable_stop": executableStop as Any? ?? NSNull(),
"source_debugging": ["status": metadata == nil ? "source_only" : "verified", "source_map": "verified", "variables": metadata == nil ? "unavailable" : "verified"],
"watch_status": metadata == nil ? String((variableError ?? "Typed C metadata is unavailable; verified code inspection remains available.").prefix(2000)) : "Verified globals; C frame locals are unavailable for owned entry and instruction stops.",
"memory_ranges": ranges.map { ["address": $0.lowerBound, "count": $0.count] }]
let context = callContextApproved ? CMOCOwnedCallContext.capture(map: map, metadata: metadata, pc: address,
s: stackPointer, u: framePointer, memory: memory, available: available,
physicalPages: pages, sharedPaths: shared) : nil
ownedInspection = (snapshot, owned.runID, clock, memory, ranges, fields, captureFingerprint, context)
return fields
}
/// Guest identity only: request budgets may change while a nonadvancing read is serviced.
/// Boot/mapping/register/memory changes invalidate a call context even at the same field clock.
static func ownedCaptureFingerprint(_ capture: [String: Any]) -> String? {
let keys = ["boot", "field_clock", "machine_frame", "cycles", "generation", "pc", "registers", "processor", "execution_mode",
"mapping_fingerprint", "program_revision", "physical_pages", "logical_memory", "available"]
guard keys.allSatisfy({ capture[$0] != nil }) else { return nil }
var state = Dictionary(uniqueKeysWithValues: keys.map { ($0, capture[$0]!) })
state["md_register"] = capture["md_register"] ?? NSNull()
state["residency_fingerprint"] = capture["residency_fingerprint"] ?? "0"
guard JSONSerialization.isValidJSONObject(state),
let bytes = try? JSONSerialization.data(withJSONObject: state, options: [.sortedKeys]) else { return nil }
return CMOCSourceMap.sha256(bytes)
}
private func read(_ path: String) throws -> String {
if let text = snapshot[path] { return text }
throw problem("access_denied")
}
private func int(_ value: Any?) -> Int? {
guard let n = value as? NSNumber, CFGetTypeID(n) != CFBooleanGetTypeID(), !["f","d"].contains(String(cString: n.objCType)) else { return nil }
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" }
return record
}
private func startBuild(request: String?, revision expected: Int?, model: CMOCDevelopmentModel, action requestedAction: String? = nil, configuration requestedConfiguration: String? = nil) throws -> [String: Any] {
guard refreshProblem == nil, let request, (1...128).contains(request.utf8.count), let expected, let scratch, let service, let scope else { throw problem("invalid_arguments") }
let action: CMOCBuildAction = scope.customMake ? (CMOCBuildAction(rawValue: requestedAction ?? "build") ?? .custom) : (scope.helloDisk ? .disk : .build)
let configuration = scope.customMake ? (requestedConfiguration ?? model.configurationName) : "Debug"
guard [.build, .disk].contains(action), action != .disk || scope.helloDisk || scope.configuration.diskTarget != nil,
!scope.customMake || scope.configuration.configurations.contains(where: { $0.name == configuration }) else {
throw problem("unsupported_build_selection: Choose a declared build/disk action and configuration from get_capabilities.")
}
guard proposalRequests[request] == nil else { throw problem("request_id_conflict") }
if let id = buildRequests[request], let old = buildRecord(id) {
guard old["revision"] as? Int == expected, old["action"] as? String == action.rawValue, old["configuration"] as? String == configuration else { throw problem("request_id_conflict") }
return old
}
guard revision == expected else { throw problem("stale_revision") }
guard !building, !running, !model.building, !model.commanding else { throw problem("busy") }
guard builds.count < 32 else { throw problem("session_build_limit") }
let id = UUID().uuidString, owner = session, inputs = snapshot, make = makeSnapshot
let base: [String: Any] = ["build_id": id, "project_id": model.assistantProjectID.uuidString, "revision": expected, "action": action.rawValue, "configuration": configuration, "recipe_id": approvedRecipeID as Any? ?? NSNull()]
var initial = base; initial["status"] = "building"
latestBuildID = id
builds[id] = initial; buildRequests[request] = id
clearBuildAndLiveControls()
building = true; buildStatus = scope.customMake ? "Building the approved Make project…" : "Building the captured C sources…"
buildTask = Task {
var result = base
do {
let project = try await Task.detached { try scope.snapshotProject(at: scope.customMake ? scratch.appendingPathComponent("Source-" + id).appendingPathComponent("project") : scratch.appendingPathComponent("Source-" + id), inputs: inputs,
buildInputs: make?.files, support: make?.support, permissions: make?.permissions ?? [:],
modificationDates: make?.modificationDates ?? [:], overlayPaths: make?.overlayPaths ?? []) }.value
try Task.checkCancellation()
let artifact = try await service.build(project: project, overlays: inputs, action: action, configuration: configuration)
try Task.checkCancellation()
try await refresh(model)
guard session == owner, revision == expected, refreshProblem == nil else { throw problem("stale_revision") }
readyArtifact = (expected, artifact)
result["status"] = "succeeded"; result["artifact_id"] = artifact.id.uuidString
result["diagnostics"] = []
if scope.customMake {
result["log"] = String(artifact.buildLog.suffix(32_000)).replacingOccurrences(of: scratch.path, with: "<build>")
result["outputs"] = try await Task.detached {
try [artifact.binaryRelativePath, artifact.diskRelativePath, artifact.debugManifestRelativePath].compactMap { path -> [String: Any]? in
guard let path else { return nil }
let bytes = try Data(contentsOf: artifact.fileURL(path))
return ["path": path, "bytes": bytes.count, "sha256": CMOCProject.sha256(bytes)]
}
}.value
} else { result["log"] = scope.helloDisk ? "Bundled CMOC compiled and linked HELLO.BIN and built HELLO.DSK." : "Bundled CMOC compiled and linked main.bin." }
let evidence = await Task.detached {
CMOCPublicDebugEvidence.fields(artifact: artifact, sharedPaths: Set(scope.paths))
}.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]
}
if let manifestPath = artifact.debugManifestRelativePath {
result["debug_manifest"] = await Task.detached { () -> [String: Any] in
var fields: [String: Any] = ["path": manifestPath]
if let bytes = try? Data(contentsOf: artifact.fileURL(manifestPath)), bytes.count <= 1024 * 1024 {
fields["sha256"] = CMOCProject.sha256(bytes); fields["bytes"] = bytes.count
if bytes.count <= 128 * 1024, let text = String(data: bytes, encoding: .utf8) { fields["text"] = text }
}
return fields
}.value
}
let report = CMOCBuildReport(artifact: artifact, redacting: [scratch], visiblePaths: Set(scope.paths))
buildReports[id] = report
for (key, value) in report.fields() { result[key] = value }
} catch {
guard session == owner else { return }
result["status"] = "failed"
let report = CMOCBuildReport(error: error, redacting: [scratch], visiblePaths: Set(scope.paths))
buildReports[id] = report
for (key, value) in report.fields() { result[key] = value }
}
guard session == owner else { return }
builds[id] = result; building = false; buildStatus = result["log"] as? String ?? ""
}
return initial
}
private func propose(_ args: [String: Any]) throws -> [String: Any] {
guard let path = args["path"] as? String, let number = int(args["line_number"]), number > 0,
let expected = int(args["revision"]), let replacement = args["replacement"] as? String,
let request = args["request_id"] as? String, (1...128).contains(request.utf8.count),
(1...512).contains(replacement.utf8.count), replacement.utf8.allSatisfy({ $0 == 9 || (32...126).contains($0) })
else { throw problem("invalid_arguments") }
guard buildRequests[request] == nil else { throw problem("request_id_conflict") }
if let id = proposalRequests[request], let old = proposals[id] {
guard old.edits == nil, old.revision == expected, old.path == path, old.line == number, old.after == replacement else { throw problem("request_id_conflict") }
return old.result
}
guard expected == revision else { throw problem("stale_revision") }
guard !running, proposal?.status != "pending", proposals.count < 64 else { throw problem("review_pending_or_limit") }
guard path.hasSuffix(".c") || path.hasSuffix(".h"), let text = snapshot[path] else { throw problem("access_denied") }
let reported = builds.values.contains { build in
guard build["status"] as? String == "failed", build["revision"] as? Int == expected,
let rows = build["diagnostics"] as? [[String: Any]] else { return false }
return rows.contains { $0["path"] as? String == path && $0["line"] as? Int == number }
}
guard reported else { throw problem("missing_compiler_diagnostic") }
guard let range = line(number, in: text) else { throw problem("line_not_found") }
let before = (text as NSString).substring(with: range)
guard before != replacement else { throw problem("unchanged_line") }
guard let scope else { throw problem("access_denied") }
try scope.validate((text as NSString).replacingCharacters(in: range, with: replacement), path: path, trusted: templateDirectives[path])
let p = Proposal(request: request, path: path, line: number, before: before, after: replacement, revision: expected)
proposalRequests[request] = p.id; update(p)
if let model { showReview(model) }
return p.result
}
private func proposeEdits(_ args: [String: Any], scope: MCPCMOCProject) throws -> [String: Any] {
guard let request = args["request_id"] as? String, (1...128).contains(request.utf8.count),
let expected = int(args["revision"]), let rows = args["edits"] as? [[String: Any]], (1...8).contains(rows.count) else {
throw problem("invalid_arguments")
}
var replacements: [String: String] = [:]
var size = 0
for row in rows {
guard row.count == 2, let path = row["path"] as? String, let text = row["source"] as? String,
replacements[path] == nil, text.utf8.allSatisfy({ $0 == 9 || $0 == 10 || $0 == 13 || (32...126).contains($0) })
else { throw problem("invalid_arguments") }
size += text.utf8.count
guard size <= 16384 else { throw problem("patch_too_large") }
replacements[path] = text
}
guard buildRequests[request] == nil else { throw problem("request_id_conflict") }
if let id = proposalRequests[request], let old = proposals[id] {
guard let edits = old.edits, old.revision == expected,
Dictionary(uniqueKeysWithValues: edits.map { ($0.path, $0.after) }) == replacements else { throw problem("request_id_conflict") }
return old.result
}
guard expected == revision else { throw problem("stale_revision") }
guard !running, proposal?.status != "pending", proposals.count < 64 else { throw problem("review_pending_or_limit") }
let edits = try replacements.keys.sorted().map { path -> MCPCMOCEdit in
guard path.hasSuffix(".c") || path.hasSuffix(".h"), let before = snapshot[path], let after = replacements[path] else { throw problem("access_denied") }
guard !before.utf8.elementsEqual(after.utf8) else { throw problem("unchanged_file") }
try scope.validate(after, path: path, trusted: templateDirectives[path])
return MCPCMOCEdit(path: path, before: before, after: after)
}
let p = Proposal(request: request, path: "", line: 0, before: "", after: "", revision: expected, edits: edits)
proposalRequests[request] = p.id; update(p)
if let model { showReview(model) }
return p.result
}
private func update(_ p: Proposal) { proposal = p; proposals[p.id] = p }
private func line(_ number: Int, in source: String) -> NSRange? {
guard number > 0 else { return nil }
let value = source as NSString
var at = 0, row = 1
while at < value.length {
var start = 0, end = 0, contents = 0
value.getLineStart(&start, end: &end, contentsEnd: &contents, for: NSRange(location: at, length: 0))
if row == number { return NSRange(location: start, length: contents - start) }
at = end; row += 1
}
return nil
}
fileprivate func decide(_ id: String, apply: Bool) async {
guard let model, var p = proposal, p.id == id, p.status == "pending" else { return }
if !apply { p.status = "cancelled"; update(p); return }
do {
try await refresh(model)
guard refreshProblem == nil, proposal?.id == id, proposal?.status == "pending", p.revision == revision else { return }
guard !model.building, !model.commanding, !running else { throw problem("The workspace is busy.") }
if let edits = p.edits {
try model.applyAssistantEdits(edits, disk: diskSnapshot, projectID: model.assistantProjectID, epoch: workspaceEpoch)
for edit in edits { snapshot[edit.path] = edit.after }
revision += 1; workspaceEpoch = model.assistantEditEpoch; recordReviewedMakeEdits(model); clearBuildAndLiveControls()
p.status = "applied"; p.applied = revision; update(p)
buildStatus = "Changes applied to the open project drafts. Rebuild to check them."
return
}
model.openFile(p.path, line: p.line)
// A tab switch installs that document's NSTextView on SwiftUI's next update.
for _ in 0..<20 where model.assistantEditorFile != p.path { try await Task.sleep(for: .milliseconds(20)) }
try await refresh(model)
guard active, refreshProblem == nil, projectID == model.assistantProjectID, proposal?.id == id, proposal?.status == "pending",
revision == p.revision, workspaceEpoch == model.assistantEditEpoch,
model.selectedFile == p.path, let editor = model.assistantEditor, editor.window != nil,
editor.isEditable, !editor.hasMarkedText(), editor.undoManager != nil,
editor.string == snapshot[p.path], let range = line(p.line, in: editor.string),
(editor.string as NSString).substring(with: range) == p.before else { throw problem("stale_revision") }
editor.breakUndoCoalescing()
editor.insertText(p.after, replacementRange: range)
editor.breakUndoCoalescing()
guard model.source == (snapshot[p.path]! as NSString).replacingCharacters(in: range, with: p.after) else {
throw problem("The editor could not apply this repair.")
}
editor.undoManager?.setActionName("Assistant C Repair")
revision += 1; workspaceEpoch = model.assistantEditEpoch; snapshot[p.path] = model.source; recordReviewedMakeEdits(model); clearBuildAndLiveControls()
p.status = "applied"; p.applied = revision; update(p)
buildStatus = "Rebuild the repaired revision to check the compiler result."
} catch { status = error.localizedDescription }
}
fileprivate func undo(_ id: String) async {
guard let model, var p = proposal, p.id == id, p.status == "applied", !running, !building else { return }
do {
try await refresh(model)
guard proposal?.id == id, proposal?.status == "applied", p.applied == revision,
!running, !building, !model.commanding, !model.building else { return }
if let edits = p.edits {
let reverse = edits.map { MCPCMOCEdit(path: $0.path, before: $0.after, after: $0.before) }
try model.applyAssistantEdits(reverse, disk: diskSnapshot, projectID: model.assistantProjectID, epoch: workspaceEpoch, undoing: true)
for edit in reverse { snapshot[edit.path] = edit.after }
revision += 1; workspaceEpoch = model.assistantEditEpoch; recordReviewedMakeEdits(model); clearBuildAndLiveControls()
p.status = "undone"; update(p); buildStatus = "All reviewed file changes were undone."
return
}
guard model.assistantEditorFile == p.path, model.selectedFile == p.path,
let manager = model.assistantEditor?.undoManager, manager.undoActionName == "Assistant C Repair", manager.canUndo,
let changed = line(p.line, in: model.source), (model.source as NSString).substring(with: changed) == p.after else { return }
let restored = (model.source as NSString).replacingCharacters(in: changed, with: p.before)
manager.undo()
let restoredEpoch = model.assistantEditEpoch
try await refresh(model)
guard proposal?.id == id, proposal?.status == "applied", workspaceEpoch == restoredEpoch,
revision == (p.applied ?? -1) + 1, snapshot[p.path]?.utf8.elementsEqual(restored.utf8) == true else { return }
p.status = "undone"; update(p); buildStatus = "Edit undone."
} catch { status = error.localizedDescription }
}
fileprivate func rebuild(_ proposalID: String) async {
guard let model, let selected = proposal, selected.id == proposalID, let expected = selected.applied else { return }
do {
try await refresh(model)
guard proposal?.id == proposalID, proposal?.status == "applied", revision == expected else { return }
_ = try startBuild(request: UUID().uuidString, revision: expected, model: model)
} catch { status = error.localizedDescription }
}
private func runAlert() -> NSAlert {
let alert = NSAlert()
alert.messageText = "Run this C build in the CoCo?"
alert.informativeText = "Inspect at main pauses at the first verified C statement. Play in CoCo continues from that statement and lets the connected assistant read the game screen and send keys during this run."
let cancel = alert.addButton(withTitle: "Cancel")
cancel.keyEquivalent = "\u{1b}"
alert.addButton(withTitle: "Play in CoCo")
alert.addButton(withTitle: "Inspect at main")
return alert
}
fileprivate func run(_ selected: RunSelection?, fixturePlay: Bool = false) async {
guard let selected, !running, !building, let model, let scope,
proposal?.id == selected.proposalID, readyArtifact?.value.id == selected.artifactID else { return }
let proposalID = selected.proposalID
do {
try await refresh(model)
guard refreshProblem == nil, !running, !building, proposal?.id == proposalID, readyToRun, let artifact = readyArtifact,
artifact.value.id == selected.artifactID else {
throw problem("Rebuild this revision successfully before running.")
}
let owner = session, epoch = workspaceEpoch, expected = revision
guard !model.commanding, !model.building else { throw problem("The C workbench is busy.") }
var play = regression && fixturePlay && !scope.helloDisk
if !scope.helloDisk && !regression {
let readiness = await model.machine.mcpReadinessSnapshot()
guard session == owner, self.model === model, workspaceEpoch == model.assistantEditEpoch,
readyArtifact?.value.id == artifact.value.id else { throw problem("stale_revision") }
if readiness.assistantEmptyBASIC?.boolValue == false { throw problem(MCPMachineStatus.occupiedBASICGuidance) }
let alert = runAlert()
switch alert.runModal() {
case .alertSecondButtonReturn: play = true
case .alertThirdButtonReturn: play = false
default: return
}
try await refresh(model)
guard session == owner, revision == expected, refreshProblem == nil, readyArtifact?.value.id == artifact.value.id,
proposal?.id == proposalID, !building, !running, !model.commanding, !model.building else { throw problem("stale_revision") }
}
let id = UUID().uuidString
liveIO?.invalidate(); liveIO = nil
runID = id; inspection = nil
runRevision = revision; running = true; runReceipt = nil; runStatus = "Running the reviewed binary in the CoCo…"
let current: @MainActor () -> Bool = { [weak self, weak model] in
guard let self, let model else { return false }
return self.active && self.refreshProblem == nil && self.session == owner && self.projectID == model.assistantProjectID &&
self.revision == expected && model.assistantEditEpoch == epoch && self.proposal?.id == proposalID
}
runTask = Task {
do {
let saveStop: MCPCMOCGuest.SaveStop = { capture, info, point in
guard current(), self.runID == id, let project = self.projectID else { throw CancellationError() }
self.inspection = try MCPCMOCGuest.inspection(runID: id, revision: expected, projectID: project.uuidString,
build: artifact.value, capture: capture, info: info, point: point, watches: model.watches, sharedPaths: Set(scope.paths))
}
let receipt: [String: Any]
if scope.helloDisk {
receipt = try await MCPCMOCGuest.run(model: model, build: artifact.value, isCurrent: current, saveStop: saveStop)
} else {
receipt = try await MCPCMOCGuest.runOrdinary(model: model, build: artifact.value, play: play, isCurrent: current, saveStop: saveStop)
}
try await refresh(model)
guard current() else { throw problem("stale_revision") }
runReceipt = receipt
if play, let stop = inspection {
liveIO = MCPCompiledRunIO(machine: model.machine, runID: id, expected: stop.machine, assembly: false)
runStatus = "Continued from main. Your assistant can read the CoCo screen and send game keys through MCP. To play yourself, choose Input → Focus CoCo Display."
} else {
runStatus = scope.helloDisk ? "Finished guest verification." : "Paused at a C source statement."
}
if let panel {
let visible = (panel.screen ?? NSScreen.main)?.visibleFrame.height ?? 800
let height = min(max(480, visible - 100), 760)
panel.setContentSize(NSSize(width: max(panel.frame.width, 645), height: height))
}
} catch { if session == owner { runStatus = error.localizedDescription } }
if session == owner { running = false }
}
} catch { status = error.localizedDescription }
}
func showAccess(_ model: CMOCDevelopmentModel) {
consentPanel?.close()
let w = window("C Project Assistant Access", width: 560, height: 380,
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, 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"
picker.beginSheetModal(for: owner) { [weak self, weak owner, weak model] response in
Task { @MainActor [weak self, weak owner, weak model] in
guard let self, let owner, let model else { return }
@MainActor func currentPresentation() -> Bool {
self.consentPanel === owner && self.consentModel === model && owner.isVisible &&
!owner.isMiniaturized && model.assistantProjectID == project &&
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) } }
guard response == .OK, let url = picker.url else { return }
do { try await self.grant(model, at: url, presentationIsCurrent: currentPresentation) }
catch { if currentPresentation() { self.status = error.localizedDescription } }
}
}
}
private func window<V: View>(_ title: String, width: CGFloat, height: CGFloat, scrolls: Bool = true, view: V) -> NSPanel {
let w = NSPanel(contentRect: NSRect(x: 0, y: 0, width: width, height: height),
styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: false)
w.title = title; w.isReleasedWhenClosed = false; w.contentMinSize = NSSize(width: 405, height: 220)
let content = NSHostingView(rootView: Group { if scrolls { ScrollView { view } } else { view } })
content.sizingOptions = []; w.contentView = content; w.center()
return w
}
fileprivate func showReview(_ model: CMOCDevelopmentModel) {
guard self.model === model else { return }
if panel == nil {
let title = "Review C Changes" + (fixtureLabel.map { " — " + $0 } ?? "")
panel = window(title, width: 645, height: 435, scrolls: false, view: MCPCMOCReview(host: self))
#if DEBUG
if let fixtureLabel, let w = panel, let screen = w.screen?.visibleFrame {
let offset = min(screen.width / 4, max(0, (screen.width - w.frame.width) / 2))
w.setFrameOrigin(NSPoint(x: screen.midX - w.frame.width / 2 + (fixtureLabel.lowercased().contains("ollama") ? offset : -offset), y: w.frame.minY))
}
#endif
}
if !regression { panel?.makeKeyAndOrderFront(nil); NSApp.requestUserAttention(.informationalRequest) }
#if DEBUG
if let fixtureDirectory, let panel { try? Data(String(panel.windowNumber).utf8).write(to: fixtureDirectory.appendingPathComponent("review-window-id")) }
#endif
}
#if DEBUG
func fixture(_ model: CMOCDevelopmentModel, directory: URL, roms: URL) async throws {
var info = stat()
guard lstat(directory.path, &info) == 0, info.st_mode & S_IFMT == S_IFDIR, info.st_uid == geteuid(), info.st_mode & 0o077 == 0 else { throw POSIXError(.EACCES) }
fixtureDirectory = directory
let args = CommandLine.arguments
regression = args.contains("--mcp-c-regression")
if let i = args.firstIndex(of: "--mcp-c-label"), args.indices.contains(i + 1) { fixtureLabel = args[i + 1] }
try await MCPBASICRun.bootFixture(model.machine, romDirectory: roms)
if regression, let i = args.firstIndex(of: "--mcp-c-make-project"), args.indices.contains(i + 1) {
allowProjectMakefile = true
try model.adopt(CMOCProject.open(at: URL(fileURLWithPath: args[i + 1])))
} else if regression && args.contains("--mcp-c-ordinary") {
let project = try CMOCProject.create(at: directory.appendingPathComponent("C Project"))
try Data("#include <cmoc.h>\n#include \"value.h\"\nint main(void) { printf(\"VALUE %d\\n\", value()); return 0; }\n".utf8).write(to: project.sourceURL)
try Data("int value(void);\n".utf8).write(to: project.directory.appendingPathComponent("value.h"))
try Data("#include \"value.h\"\nint value(void) { return 6; }\n".utf8).write(to: project.directory.appendingPathComponent("value.c"))
try Data("$(error The personal Makefile must never run under the assistant grant)\n".utf8).write(to: project.makefileURL)
try model.adopt(project)
} else {
let project = try CMOCProject.createHelloDisk(at: directory.appendingPathComponent("Hello Disk"))
try model.adopt(project)
let good = "printf(\"GENERATED WORD COUNT: %u\\n\", generatedWordCount);"
guard model.source.contains(good) else { throw problem("The installed example did not match the diagnostic fixture.") }
model.source = model.source.replacingOccurrences(of: good, with: good.replacingOccurrences(of: "generatedWordCount", with: "generatedWordCounts"))
// Persist the authored broken training input, so a cancelled review can be closed normally.
guard model.save() else { throw problem("Could not create the disposable fixture source.") }
}
let w = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1100, height: 755), styleMask: [.titled, .resizable, .miniaturizable], backing: .buffered, defer: false)
w.title = "C Development — " + (fixtureLabel ?? "Compiler Repair")
let view = NSHostingView(rootView: CMOCDevelopmentView(model: model))
view.sizingOptions = []; w.contentView = view; w.center(); fixtureWindow = w
if regression { w.orderBack(nil) } else { w.orderFront(nil) }
view.layoutSubtreeIfNeeded()
let pairing = directory.appendingPathComponent("grant.json")
try await grant(model, at: pairing)
guard regression else { return }
try Data().write(to: directory.appendingPathComponent("regression-fixture"), options: .withoutOverwriting)
Task { @MainActor in
func take(_ name: String) -> Bool { unlink(directory.appendingPathComponent(name).path) == 0 }
func mark(_ name: String) { try? Data().write(to: directory.appendingPathComponent(name)) }
while true {
try? await Task.sleep(for: .milliseconds(150))
if take("show-access") { showAccess(model); mark("access-shown") }
if take("show-review"), let panel {
panel.orderBack(nil)
try? await Task.sleep(for: .milliseconds(250))
mark("review-shown")
}
if take("apply"), let p = proposal { await decide(p.id, apply: true); mark("applied") }
if take("cancel"), let p = proposal { await decide(p.id, apply: false); mark("cancelled") }
if take("undo"), let p = proposal { await undo(p.id); mark("undone") }
if take("edit") { model.source += "\n/* Independent native edit */\n"; mark("edited") }
if take("run") { await run(runSelection); mark("run-started") }
if take("play") { await run(runSelection, fixturePlay: true); mark("play-started") }
if take("show-run-options"), runSelection != nil, !usesDiskRecipe {
let alert = runAlert()
alert.layout()
fixtureRunAlert = alert
let w = alert.window
w.center(); w.alphaValue = 1; w.orderFront(nil)
try? await Task.sleep(for: .milliseconds(350))
w.contentView?.layoutSubtreeIfNeeded()
w.displayIfNeeded()
if let content = w.contentView, let bitmap = content.bitmapImageRepForCachingDisplay(in: content.bounds) {
content.cacheDisplay(in: content.bounds, to: bitmap)
try? bitmap.representation(using: .png, properties: [:])?.write(to: directory.appendingPathComponent("run-options-content.png"))
}
try? Data(String(w.windowNumber).utf8).write(to: directory.appendingPathComponent("run-options-window-id"))
mark("run-options-shown")
}
if take("hide-run-options") { fixtureRunAlert?.window.orderOut(nil); fixtureRunAlert = nil; mark("run-options-hidden") }
if take("replay-stale-review"), let selected = runSelection, let prior = proposals.keys.first(where: { $0 != selected.proposalID }) {
await undo(prior)
await rebuild(prior)
await run(RunSelection(artifactID: UUID(), proposalID: selected.proposalID))
mark("stale-review-replayed")
}
if take("revoke") { await revoke().value; mark("revoked") }
if take("reconnect") { try? await grant(model, at: pairing); if active { mark("reconnected") } }
if take("capture-result"), let panel, runReceipt != nil {
panel.orderFront(nil); try? await Task.sleep(for: .milliseconds(300))
let tool = Process(); tool.executableURL = URL(fileURLWithPath: "/usr/sbin/screencapture")
tool.arguments = ["-x", "-o", "-l", String(panel.windowNumber), directory.appendingPathComponent("verified.png").path]
tool.terminationHandler = { _ in Task { @MainActor in panel.orderOut(nil) } }
do { try tool.run() } catch { panel.orderOut(nil) }
}
if take("quit") {
await revoke().value
_ = model.save()
NSApp.perform(#selector(NSApplication.terminate(_:)), with: nil, afterDelay: 0)
return
}
}
}
}
#endif
}
private struct MCPCMOCConsent: View {
@ObservedObject var host: MCPCMOC
let model: CMOCDevelopmentModel
var body: some View {
let selectedRun = host.runSelection
VStack(alignment: .leading, spacing: 12) {
Text(model.project?.directory.lastPathComponent ?? "C Development").font(.headline)
Text("Share this project’s C sources and headers, or the installed Hello Disk example with its word list. The assistant can read machine and build status, compile shared drafts, and propose changes. Review and apply edits here. Start guest execution from VCC Plus.")
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 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)
if let paths = model.project?.configuration.buildSupportDirectories, !paths.isEmpty {
Text("Build support: " + paths.joined(separator: ", ")).font(.callout).textSelection(.enabled)
}
}
}
if let project = model.project, let shared = try? MCPCMOCProject(project: project, files: model.files.map(\.relativePath), customMake: host.allowProjectMakefile) {
DisclosureGroup("Files shared (\(shared.paths.count))") {
Text(shared.paths.joined(separator: "\n")).font(.system(.caption, design: .monospaced)).textSelection(.enabled)
}
}
Text("The assistant's model provider may receive the shared files and diagnostics.").font(.callout)
if host.active {
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.")
}
HStack {
Button("Revoke Access") { host.revoke() }
if host.proposal != nil { Button("Review Changes…") { host.showReview(model) } }
if !host.usesDiskRecipe {
Button("Run C Build…") { Task { await host.run(selectedRun) } }.disabled(selectedRun == nil || host.running || host.building)
}
}
} 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)
}
}
private struct MCPCMOCReview: View {
@ObservedObject var host: MCPCMOC
@State private var selectedPath: String?
var body: some View {
let selectedRun = host.runSelection
if let p = host.proposal {
GeometryReader { geometry in
ScrollView {
VStack(alignment: .leading, spacing: 12) {
Label(p.edits.map { "Review \($0.count) C project \($0.count == 1 ? "file" : "files")" } ?? "\(p.path) · line \(p.line)", systemImage: "curlybraces").font(.headline)
Text(p.applied.map { "Reviewed revision \(p.revision) → applied revision \($0)" } ?? "Draft revision \(p.revision)").foregroundStyle(.secondary)
if let edits = p.edits, let file = edits.first(where: { $0.path == selectedPath }) ?? edits.first {
Picker("File", selection: Binding(get: { file.path }, set: { selectedPath = $0 })) {
ForEach(edits, id: \.path) { Text($0.path).tag($0.path) }
}.accessibilityLabel("Changed project file")
ScrollView {
VStack(alignment: .leading, spacing: 8) {
code("Before", file.before, .red)
code(p.applied == nil ? "Proposed" : "Applied", file.after, .green)
}
}.frame(height: max(90, geometry.size.height - (p.status == "pending" ? 185 : 280)))
} else {
code(p.applied == nil ? "Current" : "Before", p.before, .red)
code(p.applied == nil ? "Proposed" : "Applied", p.after, .green)
}
if p.status == "pending" {
HStack {
Button(p.edits == nil ? "Cancel Repair" : "Cancel Changes") { Task { await host.decide(p.id, apply: false) } }
Button(p.edits == nil ? "Apply Repair" : "Apply All Changes") { Task { await host.decide(p.id, apply: true) } }.buttonStyle(.borderedProminent)
}
} else if p.status == "applied" {
HStack {
Button(p.edits == nil ? "Undo Repair" : "Undo All Changes") { Task { await host.undo(p.id) } }
Button("Rebuild") { Task { await host.rebuild(p.id) } }
Button(host.usesDiskRecipe ? "Run and Verify" : "Run C Build…") { Task { await host.run(selectedRun) } }
.disabled(selectedRun == nil)
.help("Run the current compiled program in the CoCo.")
}.disabled(host.building || host.running)
if host.usesDiskRecipe { Text("Run temporarily mounts the built disk in an empty FD0 and starts the compiled program at a blank Disk BASIC prompt.").font(.caption) }
} else { Text(p.status == "stale" ? "The project changed. Read the new revision before proposing a repair." : p.status.capitalized) }
if !host.buildStatus.isEmpty { Text(host.buildStatus).font(.callout).textSelection(.enabled) }
if !host.runStatus.isEmpty { Text(host.runStatus).font(.headline) }
if let receipt = host.runReceipt, let point = receipt["source_stop"] as? [String: Any],
let path = point["path"] as? String, let line = point["line"] as? Int, let address = point["address"] as? Int {
Text(String(format: "Source stop · %@:%d at $%04X", path, line, address))
if let screen = receipt["screen"] as? String {
Text(screen.trimmingCharacters(in: .whitespacesAndNewlines))
.font(.system(.caption, design: .monospaced)).textSelection(.enabled)
}
}
if !host.status.isEmpty { Text(host.status).font(.caption).foregroundStyle(.secondary).textSelection(.enabled) }
}.padding(18).frame(maxWidth: .infinity, alignment: .leading)
}
}
}
}
private func code(_ label: String, _ text: String, _ color: Color) -> some View {
VStack(alignment: .leading, spacing: 4) {
Text(label).font(.caption.weight(.semibold)); Text(text).font(.system(.body, design: .monospaced)).textSelection(.enabled)
}.padding(10).frame(maxWidth: .infinity, alignment: .leading).background(color.opacity(0.1), in: RoundedRectangle(cornerRadius: 5))
}
}