feat(studio): integrate memcard persistence and headless controls
Persist cartridge identity and slot configuration, add MemcardBoot and the MemcardBuffer SDK, and consume the runtime's negotiated memcard host controls with protected teardown. Qualify save/reopen and version upgrades through distinct configured runtime processes. Include specs, examples, regression evidence and the consolidated discussion lesson.
This commit is contained in:
@@ -28,7 +28,13 @@ public final class McpTaskTools {
|
||||
});
|
||||
for (var action : TaskTools.HeadlessAction.values()) {
|
||||
handlers.put("studio_headless_" + action.name().toLowerCase(Locale.ROOT), args -> {
|
||||
Map<String, Object> input = action == TaskTools.HeadlessAction.SET_INPUT ? input(args.path("input")) : Map.of();
|
||||
Map<String, Object> input = switch (action) {
|
||||
case SET_INPUT -> input(args.path("input"));
|
||||
case BOOT -> options(mapper, args, "memcard", "memcardChoice");
|
||||
case RESET, SHUTDOWN -> options(mapper, args, "discardUnsaved", "pendingWrites");
|
||||
case MEMCARD_MOUNT -> options(mapper, args, "path", "action", "access");
|
||||
default -> Map.of();
|
||||
};
|
||||
var result = tools.headless(root(args), task(args), action, args.path("buildId").asText(null), input);
|
||||
return result.capture() != null ? McpToolResult.capture(mapper, result.capture(), false)
|
||||
: McpToolResult.success(mapper, mapper.valueToTree(result.values()));
|
||||
@@ -37,6 +43,11 @@ public final class McpTaskTools {
|
||||
}
|
||||
return handlers;
|
||||
}
|
||||
private static Map<String, Object> options(ObjectMapper mapper, JsonNode args, String... names) {
|
||||
var result = new LinkedHashMap<String, Object>();
|
||||
for (var name : names) if (args.has(name)) result.put(name, mapper.convertValue(args.get(name), Object.class));
|
||||
return result;
|
||||
}
|
||||
private static Map<String, Object> input(JsonNode input) {
|
||||
var normalized = new LinkedHashMap<String, Object>();
|
||||
for (var name : List.of("up", "down", "left", "right", "a", "b", "x", "y", "l", "r", "start", "select", "touch"))
|
||||
|
||||
@@ -34,7 +34,7 @@ public final class ExternalRuntimeGateway implements RuntimeGateway {
|
||||
Consumer<RuntimeLogEntry> logs) throws Exception {
|
||||
final Consumer<RuntimeLogEntry> sink = Objects.requireNonNull(logs, "logs");
|
||||
final Path executable = resolveExecutable(setup);
|
||||
final Process process = new ProcessBuilder(executable.toString(), "debug", "build")
|
||||
final Process process = new ProcessBuilder(command(executable, project, setup))
|
||||
.directory(project.rootPath().toFile()).start();
|
||||
stream(process.getInputStream(), false, sink);
|
||||
stream(process.getErrorStream(), true, sink);
|
||||
@@ -61,6 +61,15 @@ public final class ExternalRuntimeGateway implements RuntimeGateway {
|
||||
}
|
||||
}
|
||||
|
||||
static java.util.List<String> command(Path executable, ProjectReference project, ProjectLocalStudioSetup setup) {
|
||||
var command = new java.util.ArrayList<>(java.util.List.of(executable.toString(), "debug", "build"));
|
||||
if (project.memcardSlots() != null) {
|
||||
command.add("--memcard");
|
||||
command.add(p.studio.core.project.ProjectCartridgeConfiguration.selectedImage(project, setup).toString());
|
||||
}
|
||||
return java.util.List.copyOf(command);
|
||||
}
|
||||
|
||||
private static Path resolveExecutable(ProjectLocalStudioSetup setup) throws IOException {
|
||||
if (setup.prometeuRuntimePath() == null) throw new IOException("prometeuRuntimePath is missing");
|
||||
final Path executable = Path.of(setup.prometeuRuntimePath()).resolve("prometeu").toAbsolutePath().normalize();
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
package p.studio.app.runtime;
|
||||
|
||||
import com.fasterxml.jackson.databind.*;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import static p.studio.app.runtime.HeadlessWire.*;
|
||||
|
||||
/** Projection of the provider's 1.1 extension; no storage or recovery policy. */
|
||||
final class HeadlessMemcard {
|
||||
private HeadlessMemcard() {}
|
||||
static void fields(JsonNode node, Set<String> allowed) {
|
||||
if (!node.isObject()) throw new IllegalArgumentException("Expected options object");
|
||||
node.fieldNames().forEachRemaining(key -> {
|
||||
if (!allowed.contains(key)) throw new IllegalArgumentException("Unknown option: " + key);
|
||||
});
|
||||
}
|
||||
static ObjectNode boot(ObjectMapper mapper, Path cartridge, JsonNode options) {
|
||||
fields(options, Set.of("memcard", "memcardChoice"));
|
||||
var result = mapper.createObjectNode().put("path", cartridge.toString());
|
||||
if (options.has("memcardChoice")) {
|
||||
String choice = options.path("memcardChoice").asText("");
|
||||
if (!Set.of("persistent", "memory_fresh", "memory_existing").contains(choice))
|
||||
throw new IllegalArgumentException("Invalid memcardChoice");
|
||||
result.put("memcardChoice", choice);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
static JsonNode mount(ObjectMapper mapper, Path project, JsonNode input) throws java.io.IOException {
|
||||
return mount(mapper, project, input, project.resolve(".studio/memcard.pmc"));
|
||||
}
|
||||
static JsonNode mount(ObjectMapper mapper, Path project, JsonNode input, Path selectedImage) throws java.io.IOException {
|
||||
fields(input, Set.of("path", "action", "access"));
|
||||
String action = input.path("action").asText(""), access = input.path("access").asText("");
|
||||
if (!Set.of("open", "create").contains(action) || !Set.of("read_write", "read_only").contains(access))
|
||||
throw new IllegalArgumentException("Explicit memcard action and access are required");
|
||||
Path path;
|
||||
if (!input.has("path")) {
|
||||
path = selectedImage;
|
||||
if (action.equals("create") && path.equals(project.resolve(".studio/memcard.pmc"))) Files.createDirectories(path.getParent());
|
||||
} else {
|
||||
if (!input.path("path").isTextual() || input.path("path").textValue().isBlank())
|
||||
throw new IllegalArgumentException("Invalid memcard path");
|
||||
path = project.resolve(input.path("path").textValue());
|
||||
}
|
||||
return mapper.createObjectNode().put("path", path.toAbsolutePath().normalize().toString())
|
||||
.put("action", action).put("access", access);
|
||||
}
|
||||
static JsonNode teardown(ObjectMapper mapper, Map<String, Object> options) {
|
||||
JsonNode node = mapper.valueToTree(options);
|
||||
fields(node, Set.of("discardUnsaved", "pendingWrites"));
|
||||
if (node.has("discardUnsaved") && !node.path("discardUnsaved").isBoolean())
|
||||
throw new IllegalArgumentException("discardUnsaved must be boolean");
|
||||
if (node.has("pendingWrites") && !Set.of("wait", "cancel").contains(node.path("pendingWrites").asText("")))
|
||||
throw new IllegalArgumentException("Invalid pendingWrites");
|
||||
return node;
|
||||
}
|
||||
static void state(JsonNode node) {
|
||||
for (var key : List.of("media", "session", "io", "recovery"))
|
||||
if (!node.path(key).isObject()) throw invalid("Missing memcard " + key);
|
||||
bools(node, "dirty");
|
||||
if (!node.path("dirtySlots").isArray() || node.path("dirtySlots").size() > 64) throw invalid("Invalid dirty slots");
|
||||
var slots = new HashSet<Integer>();
|
||||
for (var slot : node.path("dirtySlots")) {
|
||||
if (!slot.isIntegralNumber() || !slot.canConvertToInt() || slot.intValue() < 0 || slot.intValue() > 63 || !slots.add(slot.intValue()))
|
||||
throw invalid("Invalid dirty slot");
|
||||
}
|
||||
var media = node.path("media");
|
||||
nullableText(media, "path"); nullableText(media, "error"); nullableText(media, "access"); nullableText(media, "cardId");
|
||||
if (!media.path("cardId").isNull() && !media.path("cardId").textValue().matches("[0-9a-f]{32}")) throw invalid("Invalid card ID");
|
||||
decimal(media, "mountEpoch");
|
||||
member(media, "preparation", Set.of("idle", "pending", "ready", "failed"));
|
||||
bools(media, "recovered", "degraded", "writeBlocked");
|
||||
var session = node.path("session");
|
||||
if (!session.has("appId")) throw invalid("Missing memcard appId");
|
||||
if (!session.path("appId").isNull() && uint(session.path("appId")).bitLength() > 32) throw invalid("Invalid memcard appId");
|
||||
nullableText(session, "choice"); nullableText(session, "mode");
|
||||
member(session, "bootPhase", Set.of("idle", "loading", "choice_required", "preparing", "running", "failed"));
|
||||
bools(session, "bootAttempted", "resident", "actionRequired");
|
||||
bools(node.path("io"), "active", "deferred");
|
||||
member(node.path("io"), "phase", Set.of("idle", "preparing", "deferred", "queued", "running", "returned"));
|
||||
bools(node.path("recovery"), "removalPending", "reconciliationRequired", "restartRequired");
|
||||
if (!node.has("request")) throw invalid("Missing memcard request");
|
||||
var request = node.path("request");
|
||||
if (!request.isNull()) {
|
||||
decimal(request, "id");
|
||||
member(request, "state", Set.of("pending", "success", "failure", "indeterminate", "memory_only"));
|
||||
member(request, "operation", Set.of("commit", "presentation"));
|
||||
text(request, "reason"); nullableText(request, "storageError"); bools(request, "retained");
|
||||
if (!request.has("slot") || (!request.path("slot").isNull() && count(request, "slot") > 63)) throw invalid("Invalid request slot");
|
||||
}
|
||||
}
|
||||
private static void bools(JsonNode node, String... keys) {
|
||||
for (var key : keys) if (!node.path(key).isBoolean()) throw invalid("Invalid memcard " + key);
|
||||
}
|
||||
private static void nullableText(JsonNode node, String key) {
|
||||
if (!node.has(key) || !(node.path(key).isNull() || node.path(key).isTextual())) throw invalid("Invalid memcard " + key);
|
||||
}
|
||||
private static void decimal(JsonNode node, String key) {
|
||||
if (!text(node, key).matches("0|[1-9][0-9]*")) throw invalid("Invalid memcard " + key);
|
||||
if (new java.math.BigInteger(node.path(key).textValue()).bitLength() > 64) throw invalid("Invalid memcard uint64");
|
||||
}
|
||||
private static void member(JsonNode node, String key, Set<String> values) {
|
||||
if (!values.contains(text(node, key))) throw invalid("Invalid memcard " + key);
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,11 @@ public final class HeadlessProcessGateway implements HeadlessGateway {
|
||||
this.mapper = mapper; this.setup = setup; this.limits = limits;
|
||||
}
|
||||
@Override public Session boot(ProjectReference project, String buildId, ShipperPrepareResult build) throws Exception {
|
||||
String installation = setup.apply(project).prometeuRuntimePath();
|
||||
return boot(project, buildId, build, Map.of());
|
||||
}
|
||||
@Override public Session boot(ProjectReference project, String buildId, ShipperPrepareResult build, Map<String, Object> options) throws Exception {
|
||||
var localSetup = setup.apply(project);
|
||||
String installation = localSetup.prometeuRuntimePath();
|
||||
if (installation == null) throw new AutomationException(AutomationFailure.Code.RUNTIME_UNAVAILABLE, "Configure the project runtime installation first");
|
||||
Path executable = Path.of(installation).resolve(System.getProperty("os.name").startsWith("Windows") ? "prometeu.exe" : "prometeu").toAbsolutePath().normalize();
|
||||
if (!Files.isRegularFile(executable) || !Files.isExecutable(executable))
|
||||
@@ -35,7 +39,12 @@ public final class HeadlessProcessGateway implements HeadlessGateway {
|
||||
try { process = new ProcessBuilder(command).directory(root.toFile()).start(); }
|
||||
catch (java.io.IOException unavailable) { throw new AutomationException(AutomationFailure.Code.RUNTIME_UNAVAILABLE, "Cannot launch the configured runtime"); }
|
||||
var session = new HeadlessProcessSession(process, mapper, limits, buildId);
|
||||
try { session.initializeAndBoot(manifest.getParent()); return session; }
|
||||
try {
|
||||
session.initializeAndBoot(manifest.getParent(), root, project.memcardSlots() != null || !options.isEmpty(), options,
|
||||
localSetup.memcardPath() == null ? root.resolve(".studio/memcard.pmc")
|
||||
: p.studio.core.project.ProjectCartridgeConfiguration.selectedImage(project, localSetup));
|
||||
return session;
|
||||
}
|
||||
catch (Exception failure) { session.abort("Headless startup failed"); throw failure; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,6 +23,9 @@ final class HeadlessProcessSession implements HeadlessGateway.Session {
|
||||
private volatile String sessionId;
|
||||
private volatile JsonNode hello;
|
||||
private Path cartridge;
|
||||
private Path projectRoot;
|
||||
private Path selectedImage;
|
||||
private boolean memcardEnabled;
|
||||
private final CompletableFuture<JsonNode> greeting = new CompletableFuture<>();
|
||||
private final Map<String, Pending> pending = new ConcurrentHashMap<>();
|
||||
private final Set<ProcessHandle> descendants = ConcurrentHashMap.newKeySet();
|
||||
@@ -34,7 +37,7 @@ final class HeadlessProcessSession implements HeadlessGateway.Session {
|
||||
private final AtomicReference<Pending> advance = new AtomicReference<>();
|
||||
private final Deque<String> stderr = new ArrayDeque<>();
|
||||
private volatile boolean closing;
|
||||
private CompletableFuture<Void> shutdown;
|
||||
private CompletableFuture<TaskTools.HeadlessReply> shutdown;
|
||||
|
||||
HeadlessProcessSession(Process process, ObjectMapper source, HeadlessLimits limits, String buildId) {
|
||||
this.process = process; this.limits = limits; this.buildId = buildId;
|
||||
@@ -46,21 +49,57 @@ final class HeadlessProcessSession implements HeadlessGateway.Session {
|
||||
}
|
||||
|
||||
void initializeAndBoot(Path cartridge) throws Exception {
|
||||
initializeAndBoot(cartridge, cartridge, false, Map.of());
|
||||
}
|
||||
void initializeAndBoot(Path cartridge, Path projectRoot, boolean memcard, Map<String, Object> options) throws Exception {
|
||||
initializeAndBoot(cartridge, projectRoot, memcard, options, projectRoot.resolve(".studio/memcard.pmc"));
|
||||
}
|
||||
void initializeAndBoot(Path cartridge, Path projectRoot, boolean memcard, Map<String, Object> options, Path selectedImage) throws Exception {
|
||||
this.cartridge = cartridge;
|
||||
this.projectRoot = projectRoot;
|
||||
this.selectedImage = selectedImage;
|
||||
JsonNode bootOptions = mapper.valueToTree(options);
|
||||
HeadlessMemcard.boot(mapper, cartridge, bootOptions);
|
||||
long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(limits.handshakeTimeoutMs());
|
||||
hello = await(greeting, limits.handshakeTimeoutMs());
|
||||
version(hello.path("protocolVersion")); text(hello, "runtimeVersion"); capabilities(hello.path("capabilities"));
|
||||
var required = new HashSet<>(CAPABILITIES);
|
||||
if (memcard) {
|
||||
if (count(hello.path("protocolVersion"), "minor") < 1) throw incompatibleMemcard();
|
||||
boolean available = false;
|
||||
for (var capability : hello.path("capabilities")) if (capability.asText().equals("memcard")) available = true;
|
||||
if (!available) throw incompatibleMemcard();
|
||||
required.add("memcard");
|
||||
}
|
||||
var expected = mapper.valueToTree(limits);
|
||||
for (var fields = expected.fieldNames(); fields.hasNext();) {
|
||||
String field = fields.next();
|
||||
if (count(hello.path("limits"), field) != expected.path(field).longValue())
|
||||
throw new AutomationException(AutomationFailure.Code.RUNTIME_INCOMPATIBLE, "Runtime limits do not match launch configuration");
|
||||
}
|
||||
var init = mapper.createObjectNode(); init.putObject("protocolVersion").put("major", 1).put("minor", 0);
|
||||
init.set("requiredCapabilities", mapper.valueToTree(CAPABILITIES));
|
||||
var init = mapper.createObjectNode(); init.putObject("protocolVersion").put("major", 1).put("minor", memcard ? 1 : 0);
|
||||
init.set("requiredCapabilities", mapper.valueToTree(required));
|
||||
var negotiated = request("initialize", init, null, remaining(deadline));
|
||||
version(negotiated.path("protocolVersion")); capabilities(negotiated.path("capabilities"));
|
||||
state(request("boot", mapper.createObjectNode().put("path", cartridge.toString()), null, limits.callTimeoutMs()));
|
||||
if (memcard) {
|
||||
boolean available = false;
|
||||
for (var capability : negotiated.path("capabilities")) if (capability.asText().equals("memcard")) available = true;
|
||||
if (count(negotiated.path("protocolVersion"), "minor") < 1 || !available) throw incompatibleMemcard();
|
||||
}
|
||||
memcardEnabled = memcard;
|
||||
state(boot(bootOptions));
|
||||
}
|
||||
private static AutomationException incompatibleMemcard() {
|
||||
return new AutomationException(AutomationFailure.Code.RUNTIME_INCOMPATIBLE, "Configured runtime requires protocol 1.1 and memcard capability");
|
||||
}
|
||||
private JsonNode boot(JsonNode options) throws Exception {
|
||||
var params = HeadlessMemcard.boot(mapper, cartridge, options);
|
||||
if (options.has("memcard")) {
|
||||
if (!memcardEnabled) throw incompatibleMemcard();
|
||||
HeadlessMemcard.state(request("memcard_mount", HeadlessMemcard.mount(mapper, projectRoot, options.path("memcard"), selectedImage), null, limits.callTimeoutMs()));
|
||||
}
|
||||
if (options.has("memcardChoice") && !memcardEnabled) throw incompatibleMemcard();
|
||||
return request("boot", params, null, limits.callTimeoutMs());
|
||||
}
|
||||
@Override public String sessionId() { return sessionId; }
|
||||
@Override public long maxFramesPerAdvance() { return limits.maxFrames(); }
|
||||
@@ -68,16 +107,28 @@ final class HeadlessProcessSession implements HeadlessGateway.Session {
|
||||
boolean alive() { return process.isAlive() || descendants.stream().anyMatch(ProcessHandle::isAlive); }
|
||||
|
||||
@Override public TaskTools.HeadlessReply call(TaskTools.HeadlessAction action, Map<String, Object> input) throws Exception {
|
||||
if (action == TaskTools.HeadlessAction.SHUTDOWN) return await(stop(input).toCompletableFuture(), limits.shutdownTimeoutMs() + 1000);
|
||||
if (!work.tryLock()) throw new AutomationException(AutomationFailure.Code.BUSY, "Headless operation active");
|
||||
try {
|
||||
if (closing) throw new AutomationException(AutomationFailure.Code.BUSY, "Headless shutdown active");
|
||||
String command = switch (action) {
|
||||
case BOOT -> "boot";
|
||||
case RESET -> "reset"; case SET_INPUT -> "set_input"; case CLEAR_INPUT -> "clear_input";
|
||||
case CAPTURE -> "capture"; case STATE -> "get_state"; case FAULT -> "get_fault";
|
||||
case MEMCARD_STATE -> "get_memcard_state"; case MEMCARD_MOUNT -> "memcard_mount";
|
||||
case MEMCARD_UNMOUNT -> "memcard_unmount"; case MEMCARD_RECONCILE -> "memcard_reconcile";
|
||||
case MEMCARD_CONTINUE_IN_MEMORY -> "memcard_continue_in_memory";
|
||||
default -> throw new IllegalArgumentException("Use lifecycle methods for boot/shutdown");
|
||||
};
|
||||
var params = action == TaskTools.HeadlessAction.BOOT ? mapper.createObjectNode().put("path", cartridge.toString()) : mapper.valueToTree(input);
|
||||
var result = request(command, params, null, limits.callTimeoutMs());
|
||||
boolean memcardAction = action.name().startsWith("MEMCARD_");
|
||||
if (memcardAction && !memcardEnabled) throw incompatibleMemcard();
|
||||
JsonNode params = mapper.valueToTree(input);
|
||||
if (action == TaskTools.HeadlessAction.MEMCARD_MOUNT) params = HeadlessMemcard.mount(mapper, projectRoot, params, selectedImage);
|
||||
if (action == TaskTools.HeadlessAction.RESET) {
|
||||
params = HeadlessMemcard.teardown(mapper, input);
|
||||
if (!input.isEmpty() && !memcardEnabled) throw incompatibleMemcard();
|
||||
}
|
||||
var result = action == TaskTools.HeadlessAction.BOOT ? boot(params) : request(command, params, null, limits.callTimeoutMs());
|
||||
var values = new LinkedHashMap<String, Object>(); values.put("sessionId", sessionId); values.put("buildId", buildId);
|
||||
CanonicalCapture capture = null;
|
||||
switch (action) {
|
||||
@@ -87,8 +138,12 @@ final class HeadlessProcessSession implements HeadlessGateway.Session {
|
||||
values.put("runtimeVersion", text(hello, "runtimeVersion"));
|
||||
values.put("limits", mapper.convertValue(hello.path("limits"), Object.class));
|
||||
values.put("capabilities", mapper.convertValue(hello.path("capabilities"), Object.class));
|
||||
if (memcardEnabled && action == TaskTools.HeadlessAction.RESET) HeadlessMemcard.state(result.path("memcard"));
|
||||
}
|
||||
case FAULT -> { fault(result); values.put("fault", mapper.convertValue(result, Object.class)); }
|
||||
case MEMCARD_STATE, MEMCARD_MOUNT, MEMCARD_UNMOUNT, MEMCARD_RECONCILE, MEMCARD_CONTINUE_IN_MEMORY -> {
|
||||
HeadlessMemcard.state(result); values.put("memcard", mapper.convertValue(result, Object.class));
|
||||
}
|
||||
default -> { if (!result.isObject()) throw invalid("Invalid acknowledgement"); }
|
||||
}
|
||||
return new TaskTools.HeadlessReply(values, capture);
|
||||
@@ -101,6 +156,7 @@ final class HeadlessProcessSession implements HeadlessGateway.Session {
|
||||
if (!work.tryLock()) throw new AutomationException(AutomationFailure.Code.BUSY, "Headless operation active");
|
||||
boolean interrupted = false;
|
||||
try {
|
||||
if (closing) throw new AutomationException(AutomationFailure.Code.BUSY, "Headless shutdown active");
|
||||
var item = new Pending("advance", frames, progress); advance.set(item);
|
||||
send(item, mapper.createObjectNode().put("frames", frames));
|
||||
JsonNode result;
|
||||
@@ -121,6 +177,12 @@ final class HeadlessProcessSession implements HeadlessGateway.Session {
|
||||
case "completed" -> { if (completed != frames) throw invalid("Incomplete completed result"); yield AutomationOutcome.Kind.SUCCEEDED; }
|
||||
case "canceled" -> AutomationOutcome.Kind.CANCELLED;
|
||||
case "terminated" -> AutomationOutcome.Kind.TERMINATED;
|
||||
case "action_required" -> {
|
||||
if (!memcardEnabled) throw invalid("Unnegotiated memcard outcome");
|
||||
var nativeState = request("get_memcard_state", mapper.createObjectNode(), null, limits.callTimeoutMs());
|
||||
HeadlessMemcard.state(nativeState); diagnostics.add(nativeState.toString());
|
||||
yield AutomationOutcome.Kind.ACTION_REQUIRED;
|
||||
}
|
||||
case "faulted" -> { fault(result.path("fault")); if (result.path("fault").isNull()) throw invalid("Missing fault"); diagnostics.add(result.path("fault").toString()); yield AutomationOutcome.Kind.GUEST_FAULT; }
|
||||
case "host_error" -> { error(result.path("error")); diagnostics.add(result.path("error").toString()); yield AutomationOutcome.Kind.INFRASTRUCTURE_FAILURE; }
|
||||
default -> throw invalid("Unknown advance stop");
|
||||
@@ -150,26 +212,47 @@ final class HeadlessProcessSession implements HeadlessGateway.Session {
|
||||
abort("Headless session lost during cancellation");
|
||||
}
|
||||
}
|
||||
@Override public synchronized CompletionStage<Void> shutdown() {
|
||||
@Override public CompletionStage<Void> shutdown() { return stop(Map.of()).thenApply(ignored -> null); }
|
||||
@Override public CompletionStage<Void> shutdown(boolean discardUnsaved) {
|
||||
return stop(discardUnsaved ? Map.of("discardUnsaved", true, "pendingWrites", "cancel") : Map.of()).thenApply(ignored -> null);
|
||||
}
|
||||
@Override public synchronized CompletionStage<TaskTools.HeadlessReply> stop(Map<String, Object> policy) {
|
||||
var params = HeadlessMemcard.teardown(mapper, policy);
|
||||
if (!policy.isEmpty() && !memcardEnabled) return CompletableFuture.failedFuture(incompatibleMemcard());
|
||||
if (shutdown != null) {
|
||||
// The first forced shutdown reports infrastructure failure. An explicit human
|
||||
// retry may acknowledge completed cleanup, but never releases a living process.
|
||||
if (shutdown.isCompletedExceptionally() && dead.get() && !alive())
|
||||
shutdown = CompletableFuture.completedFuture(null);
|
||||
return shutdown;
|
||||
if (!shutdown.isCompletedExceptionally()) return shutdown;
|
||||
if (dead.get() && !alive()) return CompletableFuture.completedFuture(new TaskTools.HeadlessReply(Map.of("sessionId", sessionId), null));
|
||||
// A native refusal leaves this channel usable for an explicit retry.
|
||||
if (closing) return shutdown;
|
||||
}
|
||||
closing = true;
|
||||
shutdown = CompletableFuture.runAsync(() -> {
|
||||
shutdown = CompletableFuture.supplyAsync(() -> {
|
||||
long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(limits.shutdownTimeoutMs());
|
||||
try {
|
||||
if (!dead.get()) {
|
||||
var response = request("shutdown", mapper.createObjectNode(), null, remaining(deadline));
|
||||
var response = request("shutdown", params, null, remaining(deadline));
|
||||
if (!response.path("closed").isBoolean() || !response.path("closed").booleanValue()) throw invalid("Missing shutdown acknowledgement");
|
||||
if (memcardEnabled) HeadlessMemcard.state(response.path("memcard"));
|
||||
if (!process.waitFor(remaining(deadline), TimeUnit.MILLISECONDS)) throw new TimeoutException();
|
||||
terminate();
|
||||
if (alive()) throw infrastructure("Owned runtime process tree did not terminate");
|
||||
var values = new LinkedHashMap<String, Object>(); values.put("sessionId", sessionId);
|
||||
values.putAll(mapper.convertValue(response, new com.fasterxml.jackson.core.type.TypeReference<Map<String, Object>>() {}));
|
||||
return new TaskTools.HeadlessReply(values, null);
|
||||
}
|
||||
terminate();
|
||||
if (alive()) throw infrastructure("Owned runtime process tree did not terminate");
|
||||
return new TaskTools.HeadlessReply(Map.of("sessionId", sessionId), null);
|
||||
} catch (AutomationException refusal) {
|
||||
if (refusal.failure().code() == AutomationFailure.Code.MEMCARD_ERROR) {
|
||||
closing = false; throw new CompletionException(refusal);
|
||||
}
|
||||
abort("Headless shutdown failed"); throw infrastructure("Headless shutdown failed; owned process tree terminated; save publication outcome unknown");
|
||||
} catch (Exception failure) {
|
||||
abort("Headless shutdown failed"); throw infrastructure("Headless shutdown failed; owned process tree terminated");
|
||||
} finally { terminate(); if (alive()) throw infrastructure("Owned runtime process tree did not terminate"); }
|
||||
abort("Headless shutdown failed"); throw infrastructure("Headless shutdown failed; owned process tree terminated; save publication outcome unknown");
|
||||
}
|
||||
});
|
||||
return shutdown;
|
||||
}
|
||||
@@ -242,6 +325,12 @@ final class HeadlessProcessSession implements HeadlessGateway.Session {
|
||||
case "not_cancelable" -> AutomationFailure.Code.NOT_CANCELABLE;
|
||||
case "incompatible_version", "unsupported_capability" -> AutomationFailure.Code.RUNTIME_INCOMPATIBLE;
|
||||
case "limit_exceeded", "response_too_large" -> AutomationFailure.Code.LIMIT_EXCEEDED;
|
||||
case "memcard_error" -> {
|
||||
if (!memcardEnabled) throw invalid("Unnegotiated memcard error");
|
||||
text(error.path("details"), "operation"); text(error.path("details"), "reason");
|
||||
HeadlessMemcard.state(error.path("details").path("state"));
|
||||
yield AutomationFailure.Code.MEMCARD_ERROR;
|
||||
}
|
||||
default -> AutomationFailure.Code.INFRASTRUCTURE_FAILURE;
|
||||
};
|
||||
pending.remove(item.id);
|
||||
|
||||
@@ -44,7 +44,12 @@ final class HeadlessWire {
|
||||
case "float64", "string" -> data.isTextual();
|
||||
case "boolean" -> data.isBoolean();
|
||||
case "null" -> data.isNull();
|
||||
case "heap_ref" -> { uint(data); yield true; }
|
||||
case "heap_ref" -> {
|
||||
if (data.isObject()) {
|
||||
yield uint(data.path("index")).bitLength() <= 32 && uint(data.path("generation")).bitLength() <= 32;
|
||||
}
|
||||
uint(data); yield true;
|
||||
}
|
||||
default -> false;
|
||||
};
|
||||
if (!valid) throw invalid("Invalid typed stack value");
|
||||
|
||||
@@ -699,7 +699,7 @@
|
||||
{
|
||||
"name": "studio_headless_boot",
|
||||
"authority": "task",
|
||||
"description": "Boot the project's known build artifact in one managed headless session. Never accepts an arbitrary cartridge path.",
|
||||
"description": "Boot the project's known build artifact in one managed headless session. Never accepts an arbitrary cartridge path. Memcard requires an explicit choice and protocol 1.1 capability. Optional memcard prepares media before boot; create never replaces existing media.",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -716,6 +716,40 @@
|
||||
"buildId": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
"memcard": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"path": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Explicit image path; omitted selects .studio/memcard.pmc in this project."
|
||||
},
|
||||
"action": {
|
||||
"enum": [
|
||||
"open",
|
||||
"create"
|
||||
]
|
||||
},
|
||||
"access": {
|
||||
"enum": [
|
||||
"read_write",
|
||||
"read_only"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"action",
|
||||
"access"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"memcardChoice": {
|
||||
"enum": [
|
||||
"persistent",
|
||||
"memory_fresh",
|
||||
"memory_existing"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -797,7 +831,7 @@
|
||||
{
|
||||
"name": "studio_headless_reset",
|
||||
"authority": "task",
|
||||
"description": "reset the task-owned headless session; preserve runtime semantics and task authority.",
|
||||
"description": "reset the task-owned headless session; preserve runtime semantics and task authority. A native memcard refusal preserves the session and structured state for a later explicit decision.",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -810,6 +844,16 @@
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Current task identity obtained after human grant."
|
||||
},
|
||||
"discardUnsaved": {
|
||||
"type": "boolean",
|
||||
"description": "Explicit consent to discard remaining dirty game RAM. Default false."
|
||||
},
|
||||
"pendingWrites": {
|
||||
"enum": [
|
||||
"wait",
|
||||
"cancel"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -1261,7 +1305,7 @@
|
||||
{
|
||||
"name": "studio_headless_shutdown",
|
||||
"authority": "task",
|
||||
"description": "shutdown the task-owned headless session; preserve runtime semantics and task authority.",
|
||||
"description": "shutdown the task-owned headless session; preserve runtime semantics and task authority. A native memcard refusal preserves the session and structured state for a later explicit decision.",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -1274,6 +1318,16 @@
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Current task identity obtained after human grant."
|
||||
},
|
||||
"discardUnsaved": {
|
||||
"type": "boolean",
|
||||
"description": "Explicit consent to discard remaining dirty game RAM. Default false."
|
||||
},
|
||||
"pendingWrites": {
|
||||
"enum": [
|
||||
"wait",
|
||||
"cancel"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -1848,6 +1902,482 @@
|
||||
"operationId": "operation-advance",
|
||||
"cancellationRequested": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "studio_headless_memcard_state",
|
||||
"authority": "task",
|
||||
"description": "Observe native media, session, dirty RAM, request, IO and recovery state without executing the guest. Requires negotiated protocol 1.1 memcard capability.",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"projectRoot": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Absolute root of an open project. Never inferred from UI focus."
|
||||
},
|
||||
"taskId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Current task identity obtained after human grant."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"projectRoot",
|
||||
"taskId"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"outputSchema": {
|
||||
"type": "object",
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"status": {
|
||||
"const": "ok"
|
||||
},
|
||||
"value": {
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"status",
|
||||
"value"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"status": {
|
||||
"const": "error"
|
||||
},
|
||||
"error": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"code": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
"message": {
|
||||
"type": "string"
|
||||
},
|
||||
"runtimeError": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"code",
|
||||
"message"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"status",
|
||||
"error"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"annotations": {
|
||||
"readOnlyHint": true,
|
||||
"openWorldHint": false
|
||||
},
|
||||
"exampleArguments": {
|
||||
"projectRoot": "/projects/game",
|
||||
"taskId": "task-example"
|
||||
},
|
||||
"exampleValue": {
|
||||
"sessionId": "runtime-example"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "studio_headless_memcard_mount",
|
||||
"authority": "task",
|
||||
"description": "Explicitly open or create media after reset and before boot; create never replaces existing media. Requires negotiated protocol 1.1 memcard capability.",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"projectRoot": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Absolute root of an open project. Never inferred from UI focus."
|
||||
},
|
||||
"taskId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Current task identity obtained after human grant."
|
||||
},
|
||||
"path": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Explicit image path; omitted selects .studio/memcard.pmc in this project."
|
||||
},
|
||||
"action": {
|
||||
"enum": [
|
||||
"open",
|
||||
"create"
|
||||
]
|
||||
},
|
||||
"access": {
|
||||
"enum": [
|
||||
"read_write",
|
||||
"read_only"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"projectRoot",
|
||||
"taskId",
|
||||
"action",
|
||||
"access"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"outputSchema": {
|
||||
"type": "object",
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"status": {
|
||||
"const": "ok"
|
||||
},
|
||||
"value": {
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"status",
|
||||
"value"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"status": {
|
||||
"const": "error"
|
||||
},
|
||||
"error": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"code": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
"message": {
|
||||
"type": "string"
|
||||
},
|
||||
"runtimeError": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"code",
|
||||
"message"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"status",
|
||||
"error"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"annotations": {
|
||||
"readOnlyHint": true,
|
||||
"openWorldHint": false
|
||||
},
|
||||
"exampleArguments": {
|
||||
"projectRoot": "/projects/game",
|
||||
"taskId": "task-example",
|
||||
"action": "open",
|
||||
"access": "read_write"
|
||||
},
|
||||
"exampleValue": {
|
||||
"sessionId": "runtime-example"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "studio_headless_memcard_unmount",
|
||||
"authority": "task",
|
||||
"description": "Unmount idle media outside a resident game session. Requires negotiated protocol 1.1 memcard capability.",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"projectRoot": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Absolute root of an open project. Never inferred from UI focus."
|
||||
},
|
||||
"taskId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Current task identity obtained after human grant."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"projectRoot",
|
||||
"taskId"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"outputSchema": {
|
||||
"type": "object",
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"status": {
|
||||
"const": "ok"
|
||||
},
|
||||
"value": {
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"status",
|
||||
"value"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"status": {
|
||||
"const": "error"
|
||||
},
|
||||
"error": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"code": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
"message": {
|
||||
"type": "string"
|
||||
},
|
||||
"runtimeError": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"code",
|
||||
"message"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"status",
|
||||
"error"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"annotations": {
|
||||
"readOnlyHint": true,
|
||||
"openWorldHint": false
|
||||
},
|
||||
"exampleArguments": {
|
||||
"projectRoot": "/projects/game",
|
||||
"taskId": "task-example"
|
||||
},
|
||||
"exampleValue": {
|
||||
"sessionId": "runtime-example"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "studio_headless_memcard_reconcile",
|
||||
"authority": "task",
|
||||
"description": "Ask the runtime to revalidate the selected same card while suspended; preserves RAM and continuation. Requires negotiated protocol 1.1 memcard capability.",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"projectRoot": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Absolute root of an open project. Never inferred from UI focus."
|
||||
},
|
||||
"taskId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Current task identity obtained after human grant."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"projectRoot",
|
||||
"taskId"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"outputSchema": {
|
||||
"type": "object",
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"status": {
|
||||
"const": "ok"
|
||||
},
|
||||
"value": {
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"status",
|
||||
"value"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"status": {
|
||||
"const": "error"
|
||||
},
|
||||
"error": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"code": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
"message": {
|
||||
"type": "string"
|
||||
},
|
||||
"runtimeError": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"code",
|
||||
"message"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"status",
|
||||
"error"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"annotations": {
|
||||
"readOnlyHint": true,
|
||||
"openWorldHint": false
|
||||
},
|
||||
"exampleArguments": {
|
||||
"projectRoot": "/projects/game",
|
||||
"taskId": "task-example"
|
||||
},
|
||||
"exampleValue": {
|
||||
"sessionId": "runtime-example"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "studio_headless_memcard_continue_in_memory",
|
||||
"authority": "task",
|
||||
"description": "Explicitly continue a suspended session in RAM through the runtime; no durability claim. Requires negotiated protocol 1.1 memcard capability.",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"projectRoot": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Absolute root of an open project. Never inferred from UI focus."
|
||||
},
|
||||
"taskId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Current task identity obtained after human grant."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"projectRoot",
|
||||
"taskId"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"outputSchema": {
|
||||
"type": "object",
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"status": {
|
||||
"const": "ok"
|
||||
},
|
||||
"value": {
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"status",
|
||||
"value"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"status": {
|
||||
"const": "error"
|
||||
},
|
||||
"error": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"code": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
"message": {
|
||||
"type": "string"
|
||||
},
|
||||
"runtimeError": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"code",
|
||||
"message"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"status",
|
||||
"error"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"annotations": {
|
||||
"readOnlyHint": true,
|
||||
"openWorldHint": false
|
||||
},
|
||||
"exampleArguments": {
|
||||
"projectRoot": "/projects/game",
|
||||
"taskId": "task-example"
|
||||
},
|
||||
"exampleValue": {
|
||||
"sessionId": "runtime-example"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -128,6 +128,49 @@ class DevDesktopTest {
|
||||
assertEquals("external agent edit", form.draft);
|
||||
});
|
||||
}
|
||||
@Test void protectedReturnShowsExplicitDiscardAndCancelDoesNotGrantConsent() throws Exception {
|
||||
try (var pool = Executors.newSingleThreadExecutor()) {
|
||||
var authority = new DefaultAutomationSession(root, new ExecutorOperationExecutor(pool));
|
||||
var discarded = new java.util.concurrent.atomic.AtomicBoolean();
|
||||
authority.grant(false).toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
var task = authority.acquire().task();
|
||||
authority.attachRuntime(task, new ManagedHeadlessSession() {
|
||||
public String sessionId() { return "dirty"; }
|
||||
public void cancel() { }
|
||||
public CompletionStage<Void> shutdown() { return shutdown(false); }
|
||||
public CompletionStage<Void> shutdown(boolean consent) {
|
||||
if (!consent) return CompletableFuture.failedFuture(new AutomationException(new AutomationFailure(
|
||||
AutomationFailure.Code.MEMCARD_ERROR, "Unsaved changes", java.util.Map.of("reason", "unsaved_changes"))));
|
||||
discarded.set(true); return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
});
|
||||
var view = new DevWorkspace[1]; var stage = new Stage[1];
|
||||
try {
|
||||
fx(() -> {
|
||||
view[0] = new DevWorkspace(new ProjectReference("Dirty", "1", "pbs", 1, ProjectTarget.Game, root),
|
||||
authority, new I18nService(), new StudioEventBus());
|
||||
stage[0] = new Stage(); stage[0].setScene(new Scene(new VBox(view[0].rootNode()), 1050, 800)); stage[0].show(); view[0].load();
|
||||
assertFalse(view[0].rootNode().lookup("#dev-discard-game-data").isVisible());
|
||||
});
|
||||
assertEquals(ControlResult.Status.CLEANUP_FAILED, authority.reclaim().toCompletableFuture().get(5, TimeUnit.SECONDS).status());
|
||||
fx(() -> {
|
||||
var discard = (Button) view[0].rootNode().lookup("#dev-discard-game-data"); assertTrue(discard.isVisible());
|
||||
Platform.runLater(() -> javafx.stage.Window.getWindows().stream().filter(w -> w instanceof Stage && w != stage[0]).findFirst()
|
||||
.ifPresent(w -> ((Button) ((DialogPane) w.getScene().getRoot()).lookupButton(ButtonType.CANCEL)).fire()));
|
||||
discard.fire(); assertFalse(discarded.get());
|
||||
Platform.runLater(() -> javafx.stage.Window.getWindows().stream().filter(w -> w instanceof Stage && w != stage[0]).findFirst()
|
||||
.ifPresent(w -> ((Button) ((DialogPane) w.getScene().getRoot()).lookupButton(ButtonType.OK)).fire()));
|
||||
discard.fire();
|
||||
assertTrue(discarded.get()); assertTrue(authority.snapshot().manualAllowed());
|
||||
assertFalse(discard.isVisible());
|
||||
});
|
||||
} finally {
|
||||
fx(() -> { if (view[0] != null) view[0].unLoad(); if (stage[0] != null) stage[0].close(); });
|
||||
authority.reclaimDiscardingUnsavedGameData().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
authority.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test void preparesConnectionWithoutGrantAndRemainsAvailableWhenTransportStops() throws Exception {
|
||||
var mapper = new com.fasterxml.jackson.databind.ObjectMapper();
|
||||
|
||||
@@ -30,7 +30,7 @@ class StudioApplicationConfigurationTest {
|
||||
assertFalse(executor.isShutdown());
|
||||
assertTrue(mcp.isRunning());
|
||||
var tools = context.getBean(p.studio.app.mcp.McpToolRegistry.class).descriptors();
|
||||
org.junit.jupiter.api.Assertions.assertEquals(17, tools.size());
|
||||
org.junit.jupiter.api.Assertions.assertEquals(22, tools.size());
|
||||
assertTrue(context.getBean(p.studio.core.runtime.HeadlessGateway.class) instanceof p.studio.app.runtime.HeadlessProcessGateway);
|
||||
org.junit.jupiter.api.Assertions.assertEquals("studio_project_context", tools.get(0).path("name").asText());
|
||||
org.junit.jupiter.api.Assertions.assertEquals("studio_reference_read", tools.get(1).path("name").asText());
|
||||
|
||||
@@ -92,6 +92,16 @@ public final class InstalledKnowledgeProbe {
|
||||
check(listResult.diagnostics().stream().noneMatch(issue->issue.isError()),"Installed List/Cursor example must compile");
|
||||
Path fixtures=Path.of(System.getProperty("pbs.registryConformanceDirectory"));
|
||||
Files.createDirectories(fixtures);Files.write(fixtures.resolve("pbs-list-installed.pbx"),listResult.bytecodeBytes());
|
||||
check(docs.stream().anyMatch(r -> r.id().equals("pbs:sdk:game:1:sdk/mem/main.pbs")), "Missing installed mem SDK");
|
||||
var memcardResult = BuilderPipelineService.INSTANCE.compile(
|
||||
BuilderPipelineContext.fromConfig(new BuilderPipelineConfig(false, root.resolve("memcard").toString())), LogAggregator.stdout());
|
||||
check(memcardResult.diagnostics().stream().noneMatch(issue -> issue.isError()), "Installed opt-in memcard project must compile");
|
||||
check(memcardResult.bytecodeModule().functions().stream().filter(f -> f.metadata().role()
|
||||
== p.studio.compiler.models.registry.IRRegistry.Role.MEMCARD_BOOT).count() == 1, "Installed MemcardBoot role");
|
||||
check(memcardResult.bytecodeModule().syscalls().stream().anyMatch(s -> s.module().equals("mem")
|
||||
&& s.name().equals("slot_stat") && s.retSlots() == 7), "Installed memcard ABI must preserve all seven stat results");
|
||||
Files.write(fixtures.resolve("pbs-memcard-installed.pbx"), memcardResult.bytecodeBytes());
|
||||
System.out.println("Installed memcard execution fixture generated");
|
||||
System.out.println("Installed List/Cursor execution fixture generated");
|
||||
Path linkedRoot=Files.createDirectory(Path.of("linked-example")).toRealPath();
|
||||
Files.createDirectories(linkedRoot.resolve("src"));
|
||||
|
||||
@@ -20,6 +20,7 @@ class InstalledKnowledgeTest {
|
||||
assertTrue(log.contains("Installed Linked execution fixture generated"), log);
|
||||
assertTrue(log.contains("Installed map execution fixture generated"), log);
|
||||
assertTrue(log.contains("Installed stack-queue execution fixture generated"), log);
|
||||
assertTrue(log.contains("Installed memcard execution fixture generated"), log);
|
||||
}
|
||||
|
||||
@Test void installedCompilerAndSdkCarryTheSameVerifiedCatalog() throws Exception {
|
||||
|
||||
@@ -12,7 +12,7 @@ class McpContractTest {
|
||||
final McpToolCatalog catalog = new McpToolCatalog(mapper);
|
||||
|
||||
@Test void everyToolHasValidExampleAuthorityAndResultEnvelope() {
|
||||
assertEquals(17, catalog.names().size());
|
||||
assertEquals(22, catalog.names().size());
|
||||
for (var name : catalog.names()) {
|
||||
var definition = catalog.definition(name);
|
||||
assertDoesNotThrow(() -> catalog.validateArguments(name, definition.get("exampleArguments")), name + " arguments");
|
||||
|
||||
@@ -143,6 +143,36 @@ class McpTaskToolsTest {
|
||||
error("SESSION_NOT_FOUND", call("studio_headless_state", args()));
|
||||
assertEquals(ControlState.AGENT_WORKING, session.snapshot().state());
|
||||
}
|
||||
@Test void memcardOptionsAndNativeShutdownRefusalSurviveMcpWithoutDetachingSession() throws Exception {
|
||||
var bootOptions = new AtomicReference<Map<String, Object>>();
|
||||
service = new DefaultTaskTools(access, catalog, (project, sink) -> new ShipperPrepareResult(
|
||||
ShipperPreparationStatus.SUCCESS, List.of(), root.resolve("build/manifest.json"), List.of(), List.of()),
|
||||
Optional.of(new HeadlessGateway() {
|
||||
public Session boot(p.studio.api.project.ProjectReference project, String id, ShipperPrepareResult build) { throw new AssertionError("Options lost"); }
|
||||
public Session boot(p.studio.api.project.ProjectReference project, String id, ShipperPrepareResult build, Map<String, Object> options) {
|
||||
bootOptions.set(options); runtime = new FakeRuntime(id); return runtime;
|
||||
}
|
||||
}));
|
||||
tools = new McpToolRegistry(new McpToolCatalog(mapper), mapper, McpTaskTools.handlers(service, mapper, true));
|
||||
acquire(); call("studio_build_start", args().put("clientRequestId", "mem-build"));
|
||||
String build = completed("mem-build").path("result").path("buildId").asText();
|
||||
var boot = args().put("buildId", build).put("memcardChoice", "persistent");
|
||||
boot.putObject("memcard").put("action", "open").put("access", "read_write");
|
||||
value(call("studio_headless_boot", boot));
|
||||
assertEquals("persistent", bootOptions.get().get("memcardChoice"));
|
||||
assertEquals(Map.of("action", "open", "access", "read_write"), bootOptions.get().get("memcard"));
|
||||
runtime.refuseShutdown = true;
|
||||
var refusal = call("studio_headless_shutdown", args());
|
||||
error("MEMCARD_ERROR", refusal);
|
||||
assertEquals("unsaved_changes", refusal.path("structuredContent").path("error").path("runtimeError").path("details").path("reason").asText());
|
||||
assertFalse(runtime.stopped); assertEquals(task, session.snapshot().task().value());
|
||||
value(call("studio_headless_memcard_state", args()));
|
||||
assertEquals(TaskTools.HeadlessAction.MEMCARD_STATE, runtime.lastAction);
|
||||
value(call("studio_headless_shutdown", args().put("discardUnsaved", true).put("pendingWrites", "cancel")));
|
||||
assertEquals(Map.of("discardUnsaved", true, "pendingWrites", "cancel"), runtime.stopPolicy);
|
||||
assertTrue(runtime.stopped);
|
||||
error("SESSION_NOT_FOUND", call("studio_headless_state", args()));
|
||||
}
|
||||
|
||||
@Test void runtimeFaultAndBoundsDoNotRevokeTaskAndRebuildStopsRuntimeFirst() throws Exception {
|
||||
acquire(); String oldBuild = buildAndBoot(); runtime.kind = AutomationOutcome.Kind.GUEST_FAULT;
|
||||
@@ -291,7 +321,7 @@ class McpTaskToolsTest {
|
||||
assertEquals(401, client.send(unauthorized, java.net.http.HttpResponse.BodyHandlers.discarding()).statusCode());
|
||||
String first = connect(client, server), second = connect(client, server);
|
||||
var list = mapper.createObjectNode().put("jsonrpc", "2.0").put("id", 1).put("method", "tools/list");
|
||||
assertEquals(17, mapper.readTree(post(client, server, first, list).body()).path("result").path("tools").size());
|
||||
assertEquals(22, mapper.readTree(post(client, server, first, list).body()).path("result").path("tools").size());
|
||||
var context = value(httpCall(client, server, first, "studio_project_context", rootOnly()));
|
||||
assertTrue(context.path("languages").toString().contains("pbs"));
|
||||
value(httpCall(client, server, first, "studio_reference_read", rootOnly().put("referenceId", "pbs:quickstart").put("limit", 100)));
|
||||
@@ -391,12 +421,21 @@ class McpTaskToolsTest {
|
||||
CompletableFuture<Void> shutdownGate = CompletableFuture.completedFuture(null);
|
||||
TaskTools.HeadlessAction lastAction;
|
||||
volatile boolean stopped, hold, cancelled;
|
||||
boolean refuseShutdown;
|
||||
Map<String, Object> stopPolicy;
|
||||
volatile AutomationOutcome.Kind kind = AutomationOutcome.Kind.SUCCEEDED;
|
||||
Map<String, Object> input;
|
||||
FakeRuntime(String build) { this.build = build; }
|
||||
public String sessionId() { return id; }
|
||||
public void cancel() { cancelled = true; }
|
||||
public CompletionStage<Void> shutdown() { shutdownEntered.countDown(); return shutdownGate.thenRun(() -> stopped = true); }
|
||||
public CompletionStage<TaskTools.HeadlessReply> stop(Map<String, Object> policy) {
|
||||
stopPolicy = policy;
|
||||
if (refuseShutdown && !Boolean.TRUE.equals(policy.get("discardUnsaved")))
|
||||
return CompletableFuture.failedFuture(new AutomationException(new AutomationFailure(AutomationFailure.Code.MEMCARD_ERROR,
|
||||
"Unsaved changes", Map.of("code", "memcard_error", "details", Map.of("reason", "unsaved_changes")))));
|
||||
return shutdown().thenApply(v -> new TaskTools.HeadlessReply(Map.of("sessionId", id), null));
|
||||
}
|
||||
public long maxFramesPerAdvance() { return 600; }
|
||||
CanonicalCapture capture(long logical) { return new CanonicalCapture(id, build, logical, 900, 1, 1, 1,
|
||||
Base64.getDecoder().decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aK1kAAAAASUVORK5CYII=")); }
|
||||
|
||||
@@ -27,7 +27,7 @@ class StudioMcpStdioTest {
|
||||
var count = new AtomicInteger(); String pixels = "A".repeat(1024 * 1024 + 100);
|
||||
try (var process = new Connector(root); var server = server(count, pixels)) {
|
||||
process.initialize();
|
||||
assertEquals(17, process.request("tools/list", mapper.createObjectNode()).path("result").path("tools").size());
|
||||
assertEquals(22, process.request("tools/list", mapper.createObjectNode()).path("result").path("tools").size());
|
||||
var waiting = process.call("studio_project_context", root);
|
||||
assertEquals("WAITING_FOR_ACCESS", waiting.path("structuredContent").path("error").path("code").asText());
|
||||
assertFalse(Files.exists(root.resolve(".studio")));
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package p.studio.app.runtime;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.api.project.*;
|
||||
import p.studio.core.project.ProjectCartridgeConfiguration;
|
||||
import java.nio.file.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class DesktopMemcardSelectionTest {
|
||||
@TempDir Path root;
|
||||
@Test void debugAndHeadlessShareLocalSelectionAndNeverCreateMediaImplicitly() throws Exception {
|
||||
var project = new ProjectReference("game", "1", "pbs", 1, ProjectTarget.Game, root, 4294967295L, 1);
|
||||
for (String selected : new String[]{null, "../shared/saves.pmc"}) {
|
||||
var setup = new ProjectLocalStudioSetup("/runtime", null, null, selected);
|
||||
Path image = ProjectCartridgeConfiguration.selectedImage(project, setup);
|
||||
var command = ExternalRuntimeGateway.command(Path.of("/runtime/prometeu"), project, setup);
|
||||
assertEquals(java.util.List.of("/runtime/prometeu", "debug", "build", "--memcard", image.toString()), command);
|
||||
var mapper = new ObjectMapper();
|
||||
var mount = HeadlessMemcard.mount(mapper, root,
|
||||
mapper.createObjectNode().put("action", "open").put("access", "read_write"), image);
|
||||
assertEquals(image.toString(), mount.path("path").asText());
|
||||
assertFalse(Files.exists(image)); assertFalse(command.contains("--create-memcard"));
|
||||
}
|
||||
var ordinary = new ProjectReference("game", "1", "pbs", 1, ProjectTarget.Game, root);
|
||||
assertEquals(java.util.List.of("/runtime/prometeu", "debug", "build"),
|
||||
ExternalRuntimeGateway.command(Path.of("/runtime/prometeu"), ordinary, ProjectLocalStudioSetup.defaults()));
|
||||
}
|
||||
}
|
||||
@@ -35,7 +35,9 @@ public final class HeadlessFixture {
|
||||
if (mode.equals("utf8")) { System.out.write(new byte[]{(byte)0xff, 10}); System.out.flush(); Thread.sleep(60000); return; }
|
||||
var hello = MAPPER.createObjectNode().put("type", "hello").put("sessionId", "fixture").put("runtimeVersion", "fixture-only");
|
||||
hello.putObject("protocolVersion").put("major", mode.equals("major") ? 2 : 1).put("minor", 3);
|
||||
hello.set("capabilities", MAPPER.valueToTree(mode.equals("capabilities") ? Set.of("boot") : HeadlessWire.CAPABILITIES));
|
||||
var caps = new HashSet<>(HeadlessWire.CAPABILITIES);
|
||||
if (mode.startsWith("memcard")) caps.add("memcard");
|
||||
hello.set("capabilities", MAPPER.valueToTree(mode.equals("capabilities") ? Set.of("boot") : caps));
|
||||
hello.set("limits", MAPPER.valueToTree(limits(mode)));
|
||||
if (mode.equals("limits")) ((com.fasterxml.jackson.databind.node.ObjectNode) hello.path("limits")).put("maxFrames", 900);
|
||||
emit(hello);
|
||||
@@ -48,8 +50,13 @@ public final class HeadlessFixture {
|
||||
var reader = new BufferedReader(new InputStreamReader(System.in));
|
||||
for (String line; (line = reader.readLine()) != null;) {
|
||||
var request = MAPPER.readTree(line); String id = request.path("requestId").asText(), command = request.path("command").asText();
|
||||
Files.writeString(Path.of("requests.jsonl"), line + "\n", StandardOpenOption.CREATE, StandardOpenOption.APPEND);
|
||||
switch (command) {
|
||||
case "initialize" -> response(id, MAPPER.createObjectNode().setAll(Map.of("protocolVersion", hello.path("protocolVersion"), "capabilities", hello.path("capabilities"))));
|
||||
case "initialize" -> {
|
||||
var version = request.path("params").path("protocolVersion").deepCopy();
|
||||
if (mode.equals("memcard-negotiation")) ((com.fasterxml.jackson.databind.node.ObjectNode) version).put("minor", 0);
|
||||
response(id, MAPPER.createObjectNode().setAll(Map.of("protocolVersion", version, "capabilities", hello.path("capabilities"))));
|
||||
}
|
||||
case "boot", "reset" -> {
|
||||
if (mode.startsWith("load-fault-")) {
|
||||
var resource = "/runtime/fault-" + mode.substring("load-fault-".length()) + ".json";
|
||||
@@ -61,13 +68,14 @@ public final class HeadlessFixture {
|
||||
}
|
||||
case "get_state" -> { if (!mode.equals("hang-call")) response(id, state()); }
|
||||
case "get_fault" -> response(id, MAPPER.nullNode());
|
||||
case "get_memcard_state", "memcard_mount", "memcard_unmount", "memcard_reconcile", "memcard_continue_in_memory" -> response(id, memcardState());
|
||||
case "advance" -> {
|
||||
active = id; frames = request.path("params").path("frames").longValue();
|
||||
emit(MAPPER.createObjectNode().put("type", "progress").put("sessionId", "fixture").put("requestId", id)
|
||||
.put("requested", frames).put("completed", mode.equals("bad-progress") ? frames + 1 : 2));
|
||||
if (mode.equals("crash")) System.exit(23);
|
||||
if (mode.equals("hang-cancel") || mode.equals("cooperative") || mode.equals("descendant")) continue;
|
||||
response(id, MAPPER.createObjectNode().put("requested", frames).put("completed", frames).put("stop", "completed"));
|
||||
response(id, MAPPER.createObjectNode().put("requested", frames).put("completed", frames).put("stop", mode.equals("memcard-action") ? "action_required" : "completed"));
|
||||
}
|
||||
case "cancel" -> {
|
||||
if (mode.equals("hang-cancel") || mode.equals("descendant")) continue;
|
||||
@@ -81,10 +89,26 @@ public final class HeadlessFixture {
|
||||
.put("width", 1).put("height", 1).put("stridePixels", 3).put("logicalFrameIndex", new BigInteger("18446744073709551615"))
|
||||
.put("frameId", new BigInteger("9223372036854775808")).put("data", mode.equals("bad-png") ? "broken" : Base64.getEncoder().encodeToString(bytes.toByteArray())));
|
||||
}
|
||||
case "shutdown" -> { if (mode.equals("descendant")) continue; response(id, MAPPER.createObjectNode().put("closed", true)); return; }
|
||||
case "shutdown" -> {
|
||||
if (mode.equals("descendant")) continue;
|
||||
if (mode.startsWith("memcard") && !request.path("params").path("discardUnsaved").asBoolean(false)) {
|
||||
var error = MAPPER.createObjectNode().put("code", "memcard_error").put("message", "Unsaved changes");
|
||||
error.putObject("details").put("operation", "shutdown").put("reason", "unsaved_changes").set("state", memcardState());
|
||||
emit(MAPPER.createObjectNode().put("type", "response").put("sessionId", "fixture").put("requestId", id).set("error", error));
|
||||
continue;
|
||||
}
|
||||
var closed = MAPPER.createObjectNode().put("closed", true);
|
||||
if (mode.startsWith("memcard")) closed.set("memcard", memcardState());
|
||||
response(id, closed); return;
|
||||
}
|
||||
default -> response(id, MAPPER.createObjectNode());
|
||||
}
|
||||
}
|
||||
}
|
||||
static JsonNode memcardState() throws Exception {
|
||||
var state = MAPPER.readTree(HeadlessFixture.class.getResourceAsStream("/runtime/memcard-state.json"));
|
||||
if (mode.equals("memcard-malformed")) ((com.fasterxml.jackson.databind.node.ObjectNode) state.path("request")).put("id", -1);
|
||||
return state;
|
||||
}
|
||||
static String java() { return Path.of(System.getProperty("java.home"), "bin", "java").toString(); }
|
||||
}
|
||||
|
||||
@@ -280,7 +280,7 @@ class HeadlessMcpDesktopTest {
|
||||
@Test void fullHttpLoopMatchesRawRuntimePixelsAndDisplayedDevAcrossResetAndRebuild() throws Exception {
|
||||
assertEquals(401, post(request("ping")).statusCode());
|
||||
grant();
|
||||
assertEquals(17, mapper.readTree(post(request("tools/list")).body()).path("result").path("tools").size());
|
||||
assertEquals(22, mapper.readTree(post(request("tools/list")).body()).path("result").path("tools").size());
|
||||
assertTrue(value(call("studio_project_context", args())).path("languages").toString().contains("pbs"));
|
||||
value(call("studio_reference_read", args().put("referenceId", "pbs:quickstart").put("limit", 100)));
|
||||
var sdk = value(call("studio_reference_read", args().put("referenceId", "pbs:sdk:game:1:sdk/input/main.pbs").put("limit", 1000)));
|
||||
|
||||
@@ -44,6 +44,48 @@ class HeadlessProcessSessionTest {
|
||||
assertEquals(outcome.capture().frameId(), wire.path("structuredContent").path("value").path("frameId").bigIntegerValue());
|
||||
session.shutdown().toCompletableFuture().get(3, TimeUnit.SECONDS); assertFalse(session.alive());
|
||||
}
|
||||
@Test void memcardNegotiatesExplicitlyAndRefusedShutdownPreservesNativeStateAndRetry() throws Exception {
|
||||
var session = start("memcard");
|
||||
session.initializeAndBoot(root, root, true, Map.of("memcardChoice", "persistent", "memcard", Map.of("action", "open", "access", "read_write")));
|
||||
var failure = assertThrows(ExecutionException.class, () -> session.shutdown().toCompletableFuture().get(3, TimeUnit.SECONDS));
|
||||
var domain = (AutomationException) failure.getCause();
|
||||
assertEquals(AutomationFailure.Code.MEMCARD_ERROR, domain.failure().code());
|
||||
assertTrue(session.alive());
|
||||
var state = new ObjectMapper().valueToTree(session.call(TaskTools.HeadlessAction.MEMCARD_STATE, Map.of()).values());
|
||||
assertEquals("18446744073709551615", state.path("memcard").path("request").path("id").textValue());
|
||||
var wire = p.studio.app.mcp.McpToolResult.failure(new ObjectMapper(), domain.failure()).wire();
|
||||
assertEquals("unsaved_changes", wire.path("structuredContent").path("error").path("runtimeError").path("details").path("reason").asText());
|
||||
session.stop(Map.of("discardUnsaved", true, "pendingWrites", "cancel")).toCompletableFuture().get(3, TimeUnit.SECONDS);
|
||||
assertFalse(session.alive());
|
||||
var requests = Files.readAllLines(root.resolve("requests.jsonl")).stream().map(line -> {
|
||||
try { return new ObjectMapper().readTree(line); } catch (Exception e) { throw new RuntimeException(e); }
|
||||
}).toList();
|
||||
assertEquals(1, requests.getFirst().path("params").path("protocolVersion").path("minor").intValue());
|
||||
assertEquals("open", requests.get(1).path("params").path("action").asText());
|
||||
assertEquals(root.resolve(".studio/memcard.pmc").toString(), requests.get(1).path("params").path("path").asText());
|
||||
assertFalse(requests.get(3).path("params").has("discardUnsaved"));
|
||||
assertFalse(Files.exists(root.resolve(".studio/memcard.pmc")));
|
||||
}
|
||||
@Test void memcardRejectsOldProvidersAndBadNegotiationBeforeBootOrMount() throws Exception {
|
||||
for (var mode : List.of("normal", "memcard-negotiation")) {
|
||||
var session = start(mode);
|
||||
assertEquals(AutomationFailure.Code.RUNTIME_INCOMPATIBLE, assertThrows(AutomationException.class,
|
||||
() -> session.initializeAndBoot(root, root, true, Map.of("memcardChoice", "memory_fresh"))).failure().code());
|
||||
if (Files.exists(root.resolve("requests.jsonl"))) {
|
||||
var sent = Files.readString(root.resolve("requests.jsonl"));
|
||||
assertFalse(sent.contains("\"command\":\"boot\"")); assertFalse(sent.contains("memcard_mount"));
|
||||
}
|
||||
session.abort("test complete");
|
||||
}
|
||||
}
|
||||
@Test void residentMediaActionIsAnOutcomeAndMalformedNativeStateInvalidatesSession() throws Exception {
|
||||
var session = start("memcard-action"); session.initializeAndBoot(root, root, true, Map.of("memcardChoice", "memory_fresh"));
|
||||
assertEquals(AutomationOutcome.Kind.ACTION_REQUIRED, session.advance(3, ignored -> {}).kind());
|
||||
assertTrue(session.alive());
|
||||
var malformed = start("memcard-malformed"); malformed.initializeAndBoot(root, root, true, Map.of("memcardChoice", "memory_fresh"));
|
||||
assertThrows(AutomationException.class, () -> malformed.call(TaskTools.HeadlessAction.MEMCARD_STATE, Map.of()));
|
||||
assertFalse(malformed.alive());
|
||||
}
|
||||
@Test void rejectsBadHandshakeMalformedOversizedAndNonUtf8OutputAndCleansUp() throws Exception {
|
||||
for (var mode : List.of("major", "capabilities", "limits", "malformed", "oversized", "utf8", "wrong-session", "no-hello")) {
|
||||
var session = start(mode);
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
package p.studio.app.runtime;
|
||||
|
||||
import com.fasterxml.jackson.databind.*;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.api.automation.*;
|
||||
import p.studio.api.project.*;
|
||||
import p.studio.api.shipper.ShipperPrepareResult;
|
||||
import p.studio.app.operation.ExecutorOperationExecutor;
|
||||
import p.studio.core.project.*;
|
||||
import p.studio.core.shipper.*;
|
||||
import p.studio.compiler.messages.BuilderPipelineConfig;
|
||||
import p.studio.compiler.models.BuilderPipelineContext;
|
||||
import p.studio.compiler.workspaces.BuilderPipelineService;
|
||||
import p.studio.utilities.logs.LogAggregator;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** PBS/shipper -> configured dispatcher -> distinct OS processes; no native injection. */
|
||||
class MemcardInstalledRuntimeTest {
|
||||
@TempDir Path root;
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
static final String PREFIX = """
|
||||
import {Mem, MemcardBuffer} from @sdk:mem;
|
||||
import {Color} from @core:color;
|
||||
import {Gfx} from @sdk:gfx;
|
||||
declare global context: long = 0;
|
||||
""";
|
||||
static final String WRITER = PREFIX + """
|
||||
declare global request: long = 0;
|
||||
declare global saved: bool = false;
|
||||
[MemcardBoot] fn restore(c: long) -> int {
|
||||
context = c;
|
||||
let icon = new MemcardBuffer(560);
|
||||
if Mem.presentation(c, "Process persistence", 1 as long, 1, 1, icon, 0, 560) != 0 as long { return 1; }
|
||||
return 0;
|
||||
}
|
||||
[Frame] fn frame() -> void {
|
||||
if saved { Gfx.clear(Color.rgb(0, 255, 0)); return; }
|
||||
Gfx.clear(Color.rgb(255, 0, 0));
|
||||
if request == 0 as long {
|
||||
let bytes = new MemcardBuffer(4);
|
||||
bytes.write(0, 0); bytes.write(1, 127); bytes.write(2, 128); bytes.write(3, 255);
|
||||
let written = Mem.slot_write(context, 0, 0, bytes, 0, 4);
|
||||
if written.status != 0 as long or written.bytes_written != 4 as long { let fail = 1 / 0; }
|
||||
let commit = Mem.slot_commit(context, 0);
|
||||
if commit.status != 0 as long { let fail = 1 / 0; }
|
||||
request = commit.request;
|
||||
return;
|
||||
}
|
||||
let observation = Mem.query(context, request);
|
||||
if observation.status != 0 as long { let fail = 1 / 0; }
|
||||
if observation.state == 0 as long { return; }
|
||||
if observation.state != 1 as long { let fail = 1 / 0; }
|
||||
saved = true;
|
||||
}
|
||||
""";
|
||||
static final String READER = PREFIX + """
|
||||
[MemcardBoot] fn restore(c: long) -> int {
|
||||
context = c;
|
||||
let stat = Mem.slot_stat(c, 0);
|
||||
if stat.status != 0 as long { return 1; }
|
||||
if stat.used_bytes != 4 as long { return 1; }
|
||||
let bytes = new MemcardBuffer(4);
|
||||
let read = Mem.slot_read(c, 0, 0, bytes, 0, 4);
|
||||
if read.status != 0 as long { return 1; }
|
||||
if read.bytes_read != 4 as long { return 1; }
|
||||
if bytes.read(0) != 0 or bytes.read(1) != 127 or bytes.read(2) != 128 or bytes.read(3) != 255 { return 1; }
|
||||
return 0;
|
||||
}
|
||||
[Frame] fn frame() -> void { Gfx.clear(Color.rgb(0, 127, 255)); }
|
||||
""";
|
||||
private ShipperPrepareResult build(Path projectRoot, String source, String version, boolean optimized, p.packer.Packer packer) throws Exception {
|
||||
Files.createDirectories(projectRoot.resolve("src"));
|
||||
Files.writeString(projectRoot.resolve("prometeu.json"), """
|
||||
{"name":"process-memcard","version":"%s","language":"pbs","stdlib":"1","target":"Game",
|
||||
"dependencies":[],"app_id":4294967295,"memcard_slots":1}
|
||||
""".formatted(version));
|
||||
Files.writeString(projectRoot.resolve("src/mod.barrel"), "pub fn frame() -> void;");
|
||||
Files.writeString(projectRoot.resolve("src/main.pbs"), source);
|
||||
CompilerBuildGateway compiler = (project, log) -> {
|
||||
var result = BuilderPipelineService.INSTANCE.build(BuilderPipelineContext.fromConfig(
|
||||
new BuilderPipelineConfig(false, project.rootPath().toString())), LogAggregator.with(log));
|
||||
var compiled = result.compileResult();
|
||||
var program = optimized ? compiled.optimizedIrvm() : compiled.irvm();
|
||||
var module = new p.studio.compiler.backend.bytecode.BytecodeEmitter().emit(program.coherentEmissionPlan());
|
||||
new p.studio.compiler.backend.bytecode.BytecodePreloadVerifierService().verify(module);
|
||||
if (source.equals(READER)) verifyReadOnlyOracle(program.coherentEmissionPlan());
|
||||
try { Files.write(result.bytecodeArtifactPath(), module.serialize()); }
|
||||
catch (java.io.IOException failure) { throw new java.io.UncheckedIOException(failure); }
|
||||
return new CompilerBuildGateway.CompilerBuildOutput(result.bytecodeArtifactPath(),
|
||||
compiled.analysisSnapshot().irBackend().getReservedMetadata().requiredCapabilities().asList());
|
||||
};
|
||||
var setup = new ProjectLocalStudioSetupStore(mapper);
|
||||
var project = new ProjectCatalogService(projectRoot, mapper, setup).openProject(projectRoot);
|
||||
try (var workers = Executors.newSingleThreadExecutor()) {
|
||||
var build = new StudioShipperService(compiler, packer.workspaceService(), mapper, new ExecutorOperationExecutor(workers))
|
||||
.prepare(project, ignored -> {}).completion().toCompletableFuture().get(30, TimeUnit.SECONDS);
|
||||
assertTrue(build.success(), build.diagnostics().toString());
|
||||
var manifest = mapper.readTree(build.manifestPath().toFile());
|
||||
assertEquals(4294967295L, manifest.path("app_id").longValue()); assertEquals(version, manifest.path("app_version").asText());
|
||||
System.out.println("MEMCARD ARTIFACT " + mapper.writeValueAsString(Map.of(
|
||||
"optimized", optimized, "version", version, "producer", source.equals(WRITER) ? "writer" : source.equals(READER) ? "reader" : "dirty",
|
||||
"pbxSha256", sha(Files.readAllBytes(build.manifestPath().getParent().resolve("program.pbx"))),
|
||||
"manifestSha256", sha(Files.readAllBytes(build.manifestPath())),
|
||||
"sourceSha256", sha(source.getBytes(java.nio.charset.StandardCharsets.UTF_8)))));
|
||||
return build;
|
||||
}
|
||||
}
|
||||
private static String sha(byte[] bytes) throws Exception {
|
||||
return java.util.HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes));
|
||||
}
|
||||
private void verifyReadOnlyOracle(p.studio.compiler.backend.bytecode.BytecodeEmitter.EmissionPlan plan) {
|
||||
// SDK definitions may retain unused imports. Follow executable entry/roles,
|
||||
// including closure construction, rather than treating imports as calls.
|
||||
var pending = new ArrayDeque<Integer>(); pending.add(0);
|
||||
for (int i = 0; i < plan.functions().size(); i++)
|
||||
if (plan.functions().get(i).metadata().role() != p.studio.compiler.models.registry.IRRegistry.Role.NONE) pending.add(i);
|
||||
var visited = new HashSet<Integer>();
|
||||
while (!pending.isEmpty()) {
|
||||
int index = pending.remove(); if (!visited.add(index)) continue;
|
||||
for (var operation : plan.functions().get(index).operations()) {
|
||||
if (operation.kind() == p.studio.compiler.backend.bytecode.BytecodeEmitter.OperationKind.CALL_FUNC) pending.add(operation.immediate());
|
||||
if (operation.kind() == p.studio.compiler.backend.bytecode.BytecodeEmitter.OperationKind.REGISTRY) {
|
||||
var instruction = operation.registryInstruction();
|
||||
if (instruction.op().opcode() == 0x52) pending.add(instruction.immediate());
|
||||
assertNotEquals(0x53, instruction.op().opcode(), "Reader oracle must have a statically inspectable call graph");
|
||||
assertNotEquals(0x58, instruction.op().opcode(), "Reader oracle must have no dynamic contract call");
|
||||
}
|
||||
if (operation.syscallDecl() != null) assertFalse(Set.of("slot_write", "slot_commit", "slot_clear", "presentation", "publish_presentation")
|
||||
.contains(operation.syscallDecl().name()), "Reader must not reach a saving or presentation call");
|
||||
}
|
||||
}
|
||||
}
|
||||
private HeadlessProcessSession boot(Path projectRoot, ShipperPrepareResult build, Path image, String action, String choice, String access) throws Exception {
|
||||
String installation = System.getProperty("studio.test.runtimeInstall", "");
|
||||
assertFalse(installation.isBlank(), "Supply -PstudioRuntimeInstall=<configured runtime installation>");
|
||||
var store = new ProjectLocalStudioSetupStore(mapper);
|
||||
var project = new ProjectCatalogService(projectRoot, mapper, store).openProject(projectRoot);
|
||||
store.save(project, new ProjectLocalStudioSetup(installation, null));
|
||||
var session = (HeadlessProcessSession) new HeadlessProcessGateway(mapper, store::load).boot(project, "process-build", build,
|
||||
Map.of("memcard", Map.of("path", image.toString(), "action", action, "access", access), "memcardChoice", choice));
|
||||
System.out.println("MEMCARD process=" + session.pid() + " installation=" + installation + " choice=" + choice);
|
||||
return session;
|
||||
}
|
||||
private JsonNode memcard(HeadlessProcessSession session) throws Exception {
|
||||
return mapper.valueToTree(session.call(TaskTools.HeadlessAction.MEMCARD_STATE, Map.of()).values().get("memcard"));
|
||||
}
|
||||
private void close(HeadlessProcessSession session) throws Exception {
|
||||
try { session.shutdown().toCompletableFuture().get(7, TimeUnit.SECONDS); assertFalse(session.alive()); }
|
||||
finally { session.abort("test cleanup"); }
|
||||
}
|
||||
@Test void savesThenDifferentProcessesReadExactBytesAcrossVersionUpgradeWithoutResaving() throws Exception {
|
||||
try (var packer = p.packer.Packer.bootstrap(mapper, ignored -> {})) {
|
||||
for (boolean optimized : new boolean[]{false, true}) {
|
||||
Path project = root.resolve(optimized ? "optimized" : "ordinary");
|
||||
Path image = root.resolve(optimized ? "optimized.pmc" : "ordinary.pmc");
|
||||
var writer = boot(project, build(project, WRITER, "1", optimized, packer), image, "create", "persistent", "read_write");
|
||||
long writerPid = writer.pid();
|
||||
try {
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(15);
|
||||
JsonNode state;
|
||||
do {
|
||||
var outcome = writer.advance(1, ignored -> {});
|
||||
assertEquals(AutomationOutcome.Kind.SUCCEEDED, outcome.kind(), outcome.diagnostics().toString());
|
||||
state = memcard(writer);
|
||||
assertTrue(System.nanoTime() < deadline, state.toString());
|
||||
} while (!state.path("request").path("operation").asText().equals("commit") || !state.path("request").path("state").asText().equals("success"));
|
||||
assertFalse(state.path("dirty").booleanValue()); assertFalse(state.path("io").path("active").booleanValue());
|
||||
} finally { close(writer); }
|
||||
byte[] durable = Files.readAllBytes(image);
|
||||
for (String version : List.of("1", "2")) {
|
||||
var reader = boot(project, build(project, READER, version, optimized, packer), image, "open", "persistent", "read_write");
|
||||
assertNotEquals(writerPid, reader.pid());
|
||||
try {
|
||||
var outcome = reader.advance(2, ignored -> {});
|
||||
assertEquals(AutomationOutcome.Kind.SUCCEEDED, outcome.kind(), outcome.diagnostics().toString());
|
||||
assertNotNull(outcome.capture());
|
||||
var pixels = javax.imageio.ImageIO.read(new java.io.ByteArrayInputStream(outcome.capture().png()));
|
||||
assertEquals(0xff007fff, pixels.getRGB(0, 0), "Reader renders oracle only after exact bootstrap validation");
|
||||
var state = memcard(reader);
|
||||
assertTrue(state.path("request").isNull(), state.toString());
|
||||
assertEquals(4294967295L, state.path("session").path("appId").longValue());
|
||||
} finally { close(reader); }
|
||||
assertArrayEquals(durable, Files.readAllBytes(image), "Readback must not rewrite media");
|
||||
System.out.println("PASS PBS process save/reopen optimizer=" + optimized + " version=" + version + " unchangedImageSha256=" + sha(durable));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@Test void memoryOnlyShutdownRefusalKeepsSessionUntilExplicitDiscardAndOpenNeverCreates() throws Exception {
|
||||
try (var packer = p.packer.Packer.bootstrap(mapper, ignored -> {})) {
|
||||
Path project = root.resolve("memory");
|
||||
String dirty = PREFIX + """
|
||||
[MemcardBoot] fn restore(c: long) -> int {
|
||||
context = c;
|
||||
if Mem.presentation(c, "Dirty", 1 as long, 1, 1, new MemcardBuffer(560), 0, 560) != 0 as long { return 1; }
|
||||
return 0;
|
||||
}
|
||||
[Frame] fn frame() -> void {
|
||||
Mem.slot_write(context, 0, 0, new MemcardBuffer(1), 0, 1);
|
||||
Gfx.clear(Color.rgb(1, 2, 3));
|
||||
}
|
||||
""";
|
||||
var build = build(project, dirty, "1", true, packer);
|
||||
var store = new ProjectLocalStudioSetupStore(mapper);
|
||||
var reference = new ProjectCatalogService(project, mapper, store).openProject(project);
|
||||
store.save(reference, new ProjectLocalStudioSetup(System.getProperty("studio.test.runtimeInstall"), null));
|
||||
var gateway = new HeadlessProcessGateway(mapper, store::load);
|
||||
Path absent = root.resolve("absent.pmc");
|
||||
var failure = assertThrows(AutomationException.class, () -> gateway.boot(reference, "missing", build,
|
||||
Map.of("memcard", Map.of("path", absent.toString(), "action", "open", "access", "read_write"), "memcardChoice", "persistent")));
|
||||
assertEquals(AutomationFailure.Code.MEMCARD_ERROR, failure.failure().code()); assertFalse(Files.exists(absent));
|
||||
var memory = (HeadlessProcessSession) gateway.boot(reference, "memory", build, Map.of("memcardChoice", "memory_fresh"));
|
||||
try {
|
||||
assertEquals(AutomationOutcome.Kind.SUCCEEDED, memory.advance(1, ignored -> {}).kind());
|
||||
var refusal = assertThrows(ExecutionException.class, () -> memory.shutdown().toCompletableFuture().get(7, TimeUnit.SECONDS));
|
||||
assertEquals(AutomationFailure.Code.MEMCARD_ERROR, ((AutomationException) refusal.getCause()).failure().code());
|
||||
assertTrue(memory.alive()); assertTrue(memcard(memory).path("dirty").booleanValue());
|
||||
var resetRefusal = assertThrows(AutomationException.class, () -> memory.call(TaskTools.HeadlessAction.RESET, Map.of()));
|
||||
assertEquals(AutomationFailure.Code.MEMCARD_ERROR, resetRefusal.failure().code());
|
||||
assertTrue(memory.alive()); assertTrue(memcard(memory).path("dirty").booleanValue());
|
||||
memory.call(TaskTools.HeadlessAction.RESET, Map.of("discardUnsaved", true, "pendingWrites", "cancel"));
|
||||
assertFalse(memcard(memory).path("dirty").booleanValue());
|
||||
assertFalse(Files.exists(project.resolve(".studio/memcard.pmc")));
|
||||
memory.call(TaskTools.HeadlessAction.MEMCARD_MOUNT, Map.of("action", "create", "access", "read_write"));
|
||||
assertTrue(Files.isRegularFile(project.resolve(".studio/memcard.pmc")));
|
||||
memory.call(TaskTools.HeadlessAction.MEMCARD_UNMOUNT, Map.of());
|
||||
for (var recovery : List.of(TaskTools.HeadlessAction.MEMCARD_RECONCILE, TaskTools.HeadlessAction.MEMCARD_CONTINUE_IN_MEMORY)) {
|
||||
var rejected = assertThrows(AutomationException.class, () -> memory.call(recovery, Map.of()));
|
||||
assertEquals(AutomationFailure.Code.MEMCARD_ERROR, rejected.failure().code());
|
||||
var details = mapper.valueToTree(rejected.failure().runtimeError()).path("details");
|
||||
assertEquals("invalid_state", details.path("reason").asText());
|
||||
assertTrue(memory.alive());
|
||||
}
|
||||
memory.stop(Map.of("discardUnsaved", true, "pendingWrites", "cancel")).toCompletableFuture().get(7, TimeUnit.SECONDS);
|
||||
assertFalse(memory.alive());
|
||||
System.out.println("PASS protected reset/shutdown, explicit default-path create/unmount and native recovery refusal");
|
||||
} finally { memory.abort("test cleanup"); }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
{
|
||||
"media": {
|
||||
"path": null,
|
||||
"cardId": null,
|
||||
"access": null,
|
||||
"mountEpoch": "18446744073709551615",
|
||||
"preparation": "idle",
|
||||
"error": null,
|
||||
"recovered": false,
|
||||
"degraded": false,
|
||||
"writeBlocked": false
|
||||
},
|
||||
"session": {
|
||||
"appId": 4294967295,
|
||||
"choice": "memory_fresh",
|
||||
"mode": "memory_only",
|
||||
"bootAttempted": true,
|
||||
"bootPhase": "running",
|
||||
"resident": true,
|
||||
"actionRequired": false
|
||||
},
|
||||
"dirty": true,
|
||||
"dirtySlots": [
|
||||
0
|
||||
],
|
||||
"request": {
|
||||
"id": "18446744073709551615",
|
||||
"state": "memory_only",
|
||||
"reason": "none",
|
||||
"storageError": null,
|
||||
"operation": "commit",
|
||||
"slot": 0,
|
||||
"retained": true
|
||||
},
|
||||
"io": {
|
||||
"active": false,
|
||||
"deferred": false,
|
||||
"phase": "returned"
|
||||
},
|
||||
"recovery": {
|
||||
"removalPending": false,
|
||||
"reconciliationRequired": false,
|
||||
"restartRequired": false
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user