diff --git a/docs/specs/studio/11. MCP Tools and Project Knowledge Contract.md b/docs/specs/studio/11. MCP Tools and Project Knowledge Contract.md index 4a5c5e9b..c1f30af0 100644 --- a/docs/specs/studio/11. MCP Tools and Project Knowledge Contract.md +++ b/docs/specs/studio/11. MCP Tools and Project Knowledge Contract.md @@ -225,6 +225,50 @@ cross-project or old task identities cannot read/cancel cached work. Neither MCP JSON-RPC IDs nor runtime requestIds replace this identity. Restart never restores the registry, replays an advance or recovers authorization. +### 4.1 Task Work and Correlation + +`TaskTools` is the neutral service surface; MCP only validates schemas and projects +its results. The Core implementation admits work through `AutomationSession.submit` +and the existing operation executor, sharing DEV's busy state and cancellation. +Acquisition requires the prior human grant. Release reports `MANUAL` only after +managed cleanup and document refresh succeed; cleanup failures remain explicit. + +Admission and request registration are atomic per project. Deduplication uses the +operation kind and effective parameters, including requested frames. It is checked +after task authority and before busy/active-runtime validation, so a repeated +accepted start still resolves its original operation after that work has ended. +Rejected starts do not reserve clientRequestIds. Distinct requests cannot silently +queue behind busy work. Other projects remain independent. + +Polling returns `workerTerminated` separately from operation state. `CANCELLED` +may acknowledge interruption before the worker exits; it does not permit another +conflicting operation or manual control. Final results remain null until worker +termination. Progress contains only provider-reported counts and can be unknown. +A cooperative final capture is published to DEV before termination while the task +is still valid. A revoked task cannot publish a late frame or retrieve cached work. +Historical operation images are marked stale when they no longer match DEV's +current session/build/frame, or DEV has marked that capture stale. + +Build executes the same saved-project compiler/packer preparation as manual +Shipper, under task admission rather than a manual lease. It checks cancellation +between compilation, validation and packaging phases. A successful build receives +a task-local buildId; failed builds retain typed diagnostics and do not release +control. Before rebuilding, the managed runtime must finish shutdown and detach. +Old buildIds are invalidated before overwriting artifacts, including when the new +build fails. This is artifact correlation, not source snapshots or recovery. + +Headless handlers consume a neutral `HeadlessGateway` session port. Boot accepts +only a current successful task build; one runtime session may be attached at a +time. Input is normalized to a complete replacement snapshot. Advance limits come +from that session and are enforced without clamping. Shutdown detaches only after +managed cleanup finishes. Runtime process supervision and protocol mapping belong +to the application gateway delivered in step 22, not to MCP or the test doubles. + +Task-local operation/build records are discarded after worker termination on +return, revocation or project closure. Cleanup failures never restore authority; +the records are still discarded after managed work stops. Neither connection +disconnect nor polling silence discards an authorized task's records. + ## 5. Project Knowledge DTOs Neutral `ProjectKnowledge.Context` contains projectRoot/projectName, languages, @@ -357,8 +401,10 @@ or oversized input, closure, restart and old-token rejection. Provider doubles exist only in tests. Composition starts/closes transport with Studio. The production registry composes `studio_project_context`, `studio_reference_read` -and `studio_language_query` as of step 19; other -tools are advertised only when their functional handlers are connected. +and `studio_language_query`, plus control acquire/release, build start and operation +get/cancel as of step 20 (eight tools). Headless handlers are implemented and +tested against the neutral port, but are advertised only when a real +`HeadlessGateway` is composed in the integration phase. No fake runtime is shipped. DEV configuration-copy stays unavailable until step 21. Passing this transport gate is not the phase 3 or final external-agent acceptance gate. API/Core and JavaFX MUST NOT import MCP/HTTP implementations; architecture tests enforce it. diff --git a/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java b/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java index f19dbae9..eb57a3b1 100644 --- a/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java +++ b/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java @@ -176,7 +176,7 @@ public class StudioApplicationConfiguration { } @Bean - Shipper shipper(CompilerBuildGateway compiler, PackerWorkspaceService packer, ObjectMapper mapper, + StudioShipperService shipper(CompilerBuildGateway compiler, PackerWorkspaceService packer, ObjectMapper mapper, OperationExecutor operations, p.studio.api.automation.ProjectAccess access) { return new StudioShipperService(compiler, packer, mapper, operations, access); } @@ -313,12 +313,20 @@ public class StudioApplicationConfiguration { return new p.studio.core.language.TaskLanguageQueries(projects, language); } + @Bean + p.studio.api.automation.TaskTools taskTools(p.studio.core.project.ProjectAccessRegistry projects, + ProjectCatalog catalog, p.studio.core.shipper.SavedProjectPreparation shipper, + java.util.Optional headless) { + return new p.studio.core.session.DefaultTaskTools(projects, catalog, shipper, headless); + } + @Bean p.studio.app.mcp.McpToolRegistry mcpToolRegistry(p.studio.app.mcp.McpToolCatalog catalog, ObjectMapper mapper, - p.studio.api.automation.ProjectKnowledge knowledge, p.studio.api.automation.LanguageQueries language) { - // Control/build/runtime/operation providers are connected in PLN-0139 step 20. + p.studio.api.automation.ProjectKnowledge knowledge, p.studio.api.automation.LanguageQueries language, + p.studio.api.automation.TaskTools tasks, java.util.Optional headless) { var handlers = new java.util.LinkedHashMap<>(p.studio.app.mcp.McpProjectKnowledgeTools.handlers(knowledge, mapper)); handlers.putAll(p.studio.app.mcp.McpLanguageTools.handlers(language, mapper)); + handlers.putAll(p.studio.app.mcp.McpTaskTools.handlers(tasks, mapper, headless.isPresent())); return new p.studio.app.mcp.McpToolRegistry(catalog, mapper, handlers); } diff --git a/prometeu-app/src/main/java/p/studio/app/mcp/McpTaskTools.java b/prometeu-app/src/main/java/p/studio/app/mcp/McpTaskTools.java new file mode 100644 index 00000000..851cc6bf --- /dev/null +++ b/prometeu-app/src/main/java/p/studio/app/mcp/McpTaskTools.java @@ -0,0 +1,97 @@ +package p.studio.app.mcp; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import p.studio.api.automation.*; +import java.nio.file.Path; +import java.util.*; +import java.util.function.Function; + +/** Wire projection only; task authority, work and deduplication remain in Core. */ +public final class McpTaskTools { + private McpTaskTools() {} + public static Map> handlers(TaskTools tools, ObjectMapper mapper, boolean headlessAvailable) { + var handlers = new LinkedHashMap>(); + handlers.put("studio_control_acquire", args -> control(mapper, tools.acquire(root(args)))); + handlers.put("studio_control_release", args -> control(mapper, tools.release(root(args), task(args)).toCompletableFuture().join())); + handlers.put("studio_build_start", args -> receipt(mapper, tools.build(root(args), task(args), args.path("clientRequestId").asText()))); + handlers.put("studio_operation_get", args -> operation(mapper, tools.operation(root(args), task(args), + new OperationLookup(args.path("operationId").asText(null), args.path("clientRequestId").asText(null))))); + handlers.put("studio_operation_cancel", args -> McpToolResult.success(mapper, mapper.createObjectNode() + .put("operationId", args.path("operationId").asText()) + .put("cancellationRequested", tools.cancel(root(args), task(args), args.path("operationId").asText())))); + if (headlessAvailable) { + handlers.put("studio_headless_advance", args -> { + if (!args.path("frames").canConvertToLong()) throw new IllegalArgumentException("frames exceeds integer range"); + return receipt(mapper, tools.advance(root(args), task(args), args.path("clientRequestId").asText(), args.path("frames").longValue())); + }); + for (var action : TaskTools.HeadlessAction.values()) { + handlers.put("studio_headless_" + action.name().toLowerCase(Locale.ROOT), args -> { + Map input = action == TaskTools.HeadlessAction.SET_INPUT ? input(args.path("input")) : 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())); + }); + } + } + return handlers; + } + private static Map input(JsonNode input) { + var normalized = new LinkedHashMap(); + for (var name : List.of("up", "down", "left", "right", "a", "b", "x", "y", "l", "r", "start", "select", "touch")) + normalized.put(name, input.path(name).asBoolean(false)); + normalized.put("touchX", input.path("touchX").asInt(0)); + normalized.put("touchY", input.path("touchY").asInt(0)); + return Map.copyOf(normalized); + } + private static McpToolResult control(ObjectMapper mapper, ControlResult result) { + if (!result.success()) { + var code = switch (result.status()) { + case CLEANUP_FAILED -> AutomationFailure.Code.CLEANUP_FAILED; + case CLOSED -> AutomationFailure.Code.CLOSED; + case INVALID_TASK -> AutomationFailure.Code.INVALID_TASK; + case NOT_GRANTED -> AutomationFailure.Code.NOT_GRANTED; + default -> AutomationFailure.Code.BUSY; + }; + return McpToolResult.failure(mapper, new AutomationFailure(code, result.diagnostic())); + } + var value = mapper.createObjectNode().put("state", result.task() == null ? "MANUAL" : "AGENT_WORKING"); + if (result.task() != null) value.put("taskId", result.task().value()); + return McpToolResult.success(mapper, value); + } + private static ObjectNode identity(ObjectMapper mapper, TrackedOperation operation) { + return mapper.createObjectNode().put("operationId", operation.operation().id().value()) + .put("clientRequestId", operation.clientRequestId()).put("state", operation.operation().state().name()); + } + private static McpToolResult receipt(ObjectMapper mapper, TrackedOperation operation) { return McpToolResult.success(mapper, identity(mapper, operation)); } + private static McpToolResult operation(ObjectMapper mapper, TrackedOperation operation) { + var value = identity(mapper, operation); + value.put("workerTerminated", operation.workerTerminated()); + value.set("progress", mapper.valueToTree(operation.progress())); + value.set("failure", mapper.valueToTree(operation.failure())); + value.putNull("result"); + if (operation.buildResult() != null) { + var build = operation.buildResult(); + var result = value.putObject("result").put("kind", "build").put("status", build.status().name()); + result.put("buildId", operation.buildId()); + result.put("manifestPath", build.manifestPath() == null ? null : build.manifestPath().toString()); + result.set("emittedArtifacts", mapper.valueToTree(build.emittedArtifacts().stream().map(Path::toString).toList())); + result.set("diagnostics", mapper.valueToTree(build.diagnostics())); + var logs = result.putArray("logs"); + build.logs().forEach(log -> logs.addObject().put("source", log.source().name()).put("severity", log.severity().name()) + .put("message", log.message()).put("timestamp", log.timestamp().toString())); + } + CanonicalCapture capture = null; + if (operation.runtimeResult() != null) { + var runtime = operation.runtimeResult(); + var result = value.putObject("result").put("kind", "runtime").put("status", runtime.kind().name()) + .put("requestedFrames", runtime.requestedFrames()).put("completedFrames", runtime.completedFrames()); + result.set("diagnostics", mapper.valueToTree(runtime.diagnostics())); + capture = runtime.capture(); + } + return McpToolResult.successWithCapture(mapper, value, capture, operation.captureStale()); + } + private static Path root(JsonNode args) { return Path.of(args.path("projectRoot").asText()); } + private static String task(JsonNode args) { return args.path("taskId").asText(); } +} diff --git a/prometeu-app/src/main/java/p/studio/app/mcp/McpToolResult.java b/prometeu-app/src/main/java/p/studio/app/mcp/McpToolResult.java index 611e7374..2cecac13 100644 --- a/prometeu-app/src/main/java/p/studio/app/mcp/McpToolResult.java +++ b/prometeu-app/src/main/java/p/studio/app/mcp/McpToolResult.java @@ -32,6 +32,14 @@ public final class McpToolResult { .put("data", Base64.getEncoder().encodeToString(capture.png())); return result; } + public static McpToolResult successWithCapture(ObjectMapper mapper, ObjectNode value, CanonicalCapture capture, boolean stale) { + if (capture == null) return success(mapper, value); + var image = capture(mapper, capture, stale); + value.set("capture", image.wire.path("structuredContent").path("value")); + var result = success(mapper, value); + result.wire.withArray("content").add(image.wire.withArray("content").get(1).deepCopy()); + return result; + } private static McpToolResult envelope(ObjectMapper mapper, JsonNode data, boolean error) { var wire = mapper.createObjectNode().put("isError", error); wire.set("structuredContent", data); diff --git a/prometeu-app/src/test/java/p/studio/app/StudioApplicationConfigurationTest.java b/prometeu-app/src/test/java/p/studio/app/StudioApplicationConfigurationTest.java index f0f6ded7..08ab12b0 100644 --- a/prometeu-app/src/test/java/p/studio/app/StudioApplicationConfigurationTest.java +++ b/prometeu-app/src/test/java/p/studio/app/StudioApplicationConfigurationTest.java @@ -30,10 +30,12 @@ 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(3, tools.size()); + org.junit.jupiter.api.Assertions.assertEquals(8, tools.size()); 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()); - org.junit.jupiter.api.Assertions.assertEquals("studio_language_query", tools.get(2).path("name").asText()); + assertTrue(tools.toString().contains("studio_language_query")); + assertTrue(tools.toString().contains("studio_build_start")); + assertFalse(tools.toString().contains("studio_headless_boot")); } assertTrue(executor.isShutdown()); assertFalse(mcp.isRunning()); diff --git a/prometeu-app/src/test/java/p/studio/app/mcp/McpTaskToolsTest.java b/prometeu-app/src/test/java/p/studio/app/mcp/McpTaskToolsTest.java new file mode 100644 index 00000000..575b3440 --- /dev/null +++ b/prometeu-app/src/test/java/p/studio/app/mcp/McpTaskToolsTest.java @@ -0,0 +1,287 @@ +package p.studio.app.mcp; + +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.junit.jupiter.api.*; +import org.junit.jupiter.api.io.TempDir; +import p.studio.api.automation.*; +import p.studio.api.operation.*; +import p.studio.api.shipper.*; +import p.studio.app.operation.ExecutorOperationExecutor; +import p.studio.core.project.*; +import p.studio.core.runtime.HeadlessGateway; +import p.studio.core.session.*; +import p.studio.core.shipper.SavedProjectPreparation; +import java.nio.file.*; +import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.atomic.*; +import java.util.function.*; +import static org.junit.jupiter.api.Assertions.*; + +class McpTaskToolsTest { + @TempDir Path root; + final ObjectMapper mapper = new ObjectMapper(); + final ExecutorService workers = Executors.newCachedThreadPool(); + final ProjectAccessRegistry access = new ProjectAccessRegistry(); + final AtomicInteger builds = new AtomicInteger(); + final CountDownLatch buildEntered = new CountDownLatch(1), buildGate = new CountDownLatch(1); + volatile boolean holdBuild, failBuild, infrastructureFailure; + DefaultAutomationSession session; + DefaultTaskTools service; + ProjectCatalogService catalog; + McpToolRegistry tools; + FakeRuntime runtime; + String task; + + @BeforeEach void setup() throws Exception { + root = root.toRealPath(); + Files.writeString(root.resolve("prometeu.json"), "{\"name\":\"game\",\"version\":\"1.0.0\",\"language\":\"pbs\",\"stdlib\":\"1\",\"target\":\"Game\",\"dependencies\":[]}"); + catalog = new ProjectCatalogService(root.getParent(), mapper, new ProjectLocalStudioSetupStore(mapper)); + session = new DefaultAutomationSession(root, new ExecutorOperationExecutor(workers)); + access.register(root, session::enterManual, () -> !session.snapshot().closed(), session); + compose((project, sink) -> { + builds.incrementAndGet(); buildEntered.countDown(); + if (holdBuild) awaitGate(buildGate); + if (infrastructureFailure) throw new IllegalStateException("test failure"); + return failBuild ? ShipperPrepareResult.failed(List.of(), List.of("compile error")) + : new ShipperPrepareResult(ShipperPreparationStatus.SUCCESS, List.of(), root.resolve("build/manifest.json"), List.of(), List.of()); + }); + } + void compose(SavedProjectPreparation preparation) { + service = new DefaultTaskTools(access, catalog, preparation, Optional.of((project, buildId, build) -> { + runtime = new FakeRuntime(buildId); return runtime; + })); + tools = new McpToolRegistry(new McpToolCatalog(mapper), mapper, McpTaskTools.handlers(service, mapper, true)); + } + @AfterEach void close() throws Exception { + buildGate.countDown(); + if (runtime != null) runtime.gate.countDown(); + session.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS); + workers.shutdownNow(); + } + ObjectNode args() { var args = mapper.createObjectNode().put("projectRoot", root.toString()); if (task != null) args.put("taskId", task); return args; } + ObjectNode rootOnly() { return mapper.createObjectNode().put("projectRoot", root.toString()); } + JsonNode call(String name, ObjectNode args) { return tools.call(name, args).wire(); } + JsonNode value(JsonNode response) { assertFalse(response.path("isError").asBoolean(), response.toString()); return response.path("structuredContent").path("value"); } + void error(String code, JsonNode response) { assertEquals(code, response.path("structuredContent").path("error").path("code").asText(), response.toString()); } + void acquire() { session.grant(false).toCompletableFuture().join(); task = value(call("studio_control_acquire", rootOnly())).path("taskId").asText(); } + JsonNode poll(String request) { return value(call("studio_operation_get", args().put("clientRequestId", request))); } + JsonNode completed(String request) throws Exception { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + JsonNode result; + do { result = poll(request); if (!List.of("RUNNING", "PENDING").contains(result.path("state").asText())) return result; Thread.sleep(5); } + while (System.nanoTime() < deadline); + fail("Operation did not finish: " + result); return null; + } + String buildAndBoot() throws Exception { + call("studio_build_start", args().put("clientRequestId", "build")); + String id = completed("build").path("result").path("buildId").asText(); + value(call("studio_headless_boot", args().put("buildId", id))); + return id; + } + + @Test void grantIsHumanOnlyAndDuplicateBuildsShareOneOperationAcrossRacingClients() throws Exception { + error("NOT_GRANTED", call("studio_control_acquire", rootOnly())); + acquire(); holdBuild = true; + var start = new CountDownLatch(1); + var results = new ArrayList>(); + for (int n = 0; n < 20; n++) results.add(workers.submit(() -> { + start.await(); return value(call("studio_build_start", args().put("clientRequestId", "same"))).path("operationId").asText(); + })); + start.countDown(); + var ids = new HashSet(); for (var result : results) ids.add(result.get(2, TimeUnit.SECONDS)); + assertEquals(1, ids.size()); assertTrue(buildEntered.await(2, TimeUnit.SECONDS)); assertEquals(1, builds.get()); + assertEquals(ids.iterator().next(), poll("same").path("operationId").asText()); // lost receipt lookup + error("BUSY", call("studio_build_start", args().put("clientRequestId", "different"))); + error("CLIENT_REQUEST_CONFLICT", call("studio_headless_advance", args().put("clientRequestId", "same").put("frames", 1))); + assertThrows(ControlDeniedException.class, session::enterManual); + buildGate.countDown(); assertEquals("SUCCESS", completed("same").path("result").path("status").asText()); + value(call("studio_build_start", args().put("clientRequestId", "same"))); assertEquals(1, builds.get()); + } + + @Test void failuresRetainAuthorityAndFreshTaskOrServiceDoesNotRecoverOldOperations() throws Exception { + acquire(); failBuild = true; + value(call("studio_build_start", args().put("clientRequestId", "bad"))); + var result = completed("bad"); assertEquals("FAILED", result.path("result").path("status").asText()); + assertTrue(result.path("result").path("diagnostics").toString().contains("compile error")); + assertEquals(ControlState.AGENT_WORKING, session.snapshot().state()); + failBuild = false; infrastructureFailure = true; + value(call("studio_build_start", args().put("clientRequestId", "infra"))); + assertEquals("INFRASTRUCTURE_FAILURE", completed("infra").path("failure").path("code").asText()); + assertEquals(ControlState.AGENT_WORKING, session.snapshot().state()); + String old = task; + value(call("studio_control_release", args())); + error("INVALID_TASK", call("studio_operation_get", args().put("clientRequestId", "bad"))); + acquire(); assertNotEquals(old, task); + error("OPERATION_NOT_FOUND", call("studio_operation_get", args().put("clientRequestId", "bad"))); + var restarted = new DefaultTaskTools(access, catalog, (p, s) -> { throw new AssertionError("No replay"); }, Optional.empty()); + assertEquals(AutomationFailure.Code.OPERATION_NOT_FOUND, assertThrows(AutomationException.class, + () -> restarted.operation(root, task, new OperationLookup(null, "bad"))).failure().code()); + } + + @Test void headlessHandlersShareCanonicalPixelsWithDevAndNeverRepeatAnAdvance() throws Exception { + acquire(); buildAndBoot(); + value(call("studio_headless_set_input", args().set("input", mapper.createObjectNode().put("a", true)))); + assertEquals(true, runtime.input.get("a")); assertEquals(false, runtime.input.get("up")); assertEquals(0, runtime.input.get("touchY")); + var receipt = value(call("studio_headless_advance", args().put("clientRequestId", "advance").put("frames", 5))); + var result = completed("advance"); assertEquals(1, runtime.advances.get()); + assertEquals(5, result.path("progress").path("completedFrames").asInt()); + assertEquals(receipt.path("operationId"), value(call("studio_headless_advance", args().put("clientRequestId", "advance").put("frames", 5))).path("operationId")); + error("CLIENT_REQUEST_CONFLICT", call("studio_headless_advance", args().put("clientRequestId", "advance").put("frames", 6))); + var wire = call("studio_operation_get", args().put("clientRequestId", "advance")); + assertEquals("image", wire.path("content").get(1).path("type").asText()); + assertArrayEquals(session.snapshot().capture().png(), Base64.getDecoder().decode(wire.path("content").get(1).path("data").asText())); + assertEquals(900, result.path("capture").path("frameId").asInt()); + assertEquals(5, result.path("capture").path("logicalFrameIndex").asInt()); + value(call("studio_headless_capture", args())); + for (var operation : List.of("state", "fault", "clear_input", "reset")) value(call("studio_headless_" + operation, args())); + assertTrue(session.snapshot().stale()); + assertTrue(poll("advance").path("capture").path("stale").asBoolean()); + value(call("studio_headless_shutdown", args())); assertTrue(runtime.stopped); + error("SESSION_NOT_FOUND", call("studio_headless_state", args())); + assertEquals(ControlState.AGENT_WORKING, session.snapshot().state()); + } + + @Test void runtimeFaultAndBoundsDoNotRevokeTaskAndRebuildStopsRuntimeFirst() throws Exception { + acquire(); String oldBuild = buildAndBoot(); runtime.kind = AutomationOutcome.Kind.GUEST_FAULT; + value(call("studio_headless_advance", args().put("clientRequestId", "fault").put("frames", 2))); + assertEquals("GUEST_FAULT", completed("fault").path("result").path("status").asText()); + error("LIMIT_EXCEEDED", call("studio_headless_advance", args().put("clientRequestId", "large").put("frames", 601))); + error("BUSY", call("studio_headless_boot", args().put("buildId", oldBuild))); + value(call("studio_build_start", args().put("clientRequestId", "rebuild"))); + String next = completed("rebuild").path("result").path("buildId").asText(); assertTrue(runtime.stopped); + error("BUILD_NOT_FOUND", call("studio_headless_boot", args().put("buildId", oldBuild))); + value(call("studio_headless_boot", args().put("buildId", next))); + assertEquals(ControlState.AGENT_WORKING, session.snapshot().state()); + } + + @Test void cancellationPreservesKnownProgressAndReclaimWaitsForWorkerTermination() throws Exception { + acquire(); buildAndBoot(); runtime.hold = true; + String operation = value(call("studio_headless_advance", args().put("clientRequestId", "long").put("frames", 50))).path("operationId").asText(); + assertTrue(runtime.entered.await(2, TimeUnit.SECONDS)); + assertEquals(2, poll("long").path("progress").path("completedFrames").asInt()); + assertTrue(value(call("studio_operation_cancel", args().put("operationId", operation))).path("cancellationRequested").asBoolean()); + assertEquals(2, poll("long").path("progress").path("completedFrames").asInt()); + assertEquals("CANCELLED", poll("long").path("state").asText()); + assertFalse(poll("long").path("workerTerminated").asBoolean()); + error("BUSY", call("studio_build_start", args().put("clientRequestId", "blocked"))); + var returnControl = session.reclaim().toCompletableFuture(); assertFalse(returnControl.isDone()); + error("INVALID_TASK", call("studio_headless_advance", args().put("clientRequestId", "long").put("frames", 50))); + error("INVALID_TASK", call("studio_operation_cancel", args().put("operationId", operation))); + runtime.gate.countDown(); assertTrue(returnControl.get(2, TimeUnit.SECONDS).success()); + assertTrue(session.snapshot().manualAllowed()); assertTrue(runtime.stopped); + } + + @Test void anotherProjectCannotReadCachedWorkAndNoGatewayIsAdvertisedAsAvailable() throws Exception { + acquire(); buildAndBoot(); + Path other = Files.createDirectory(root.resolve("other")); + var another = new DefaultAutomationSession(other, new ExecutorOperationExecutor(workers)); + access.register(other, another::enterManual, () -> true, another); + another.grant(false).toCompletableFuture().join(); String otherTask = another.acquire().task().value(); + error("INVALID_TASK", call("studio_operation_get", args().put("projectRoot", other.toString()).put("clientRequestId", "build"))); + error("OPERATION_NOT_FOUND", call("studio_operation_get", args().put("projectRoot", other.toString()).put("taskId", otherTask).put("clientRequestId", "build"))); + assertFalse(McpTaskTools.handlers(service, mapper, false).containsKey("studio_headless_boot")); + another.closeAsync().toCompletableFuture().join(); + } + + @Test void cooperativeCancellationPublishesTheSameFinalKnownCaptureWithoutReleasingAuthority() throws Exception { + acquire(); buildAndBoot(); runtime.hold = true; + String operation = value(call("studio_headless_advance", args().put("clientRequestId", "cancelled").put("frames", 50))).path("operationId").asText(); + assertTrue(runtime.entered.await(2, TimeUnit.SECONDS)); + value(call("studio_operation_cancel", args().put("operationId", operation))); + runtime.gate.countDown(); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(2); + while (!poll("cancelled").path("workerTerminated").asBoolean() && System.nanoTime() < deadline) Thread.sleep(5); + var result = poll("cancelled"); + assertTrue(result.path("workerTerminated").asBoolean()); + assertEquals("CANCELLED", result.path("result").path("status").asText()); + assertEquals(2, result.path("progress").path("completedFrames").asInt()); + assertFalse(result.path("capture").path("stale").asBoolean()); + assertEquals(2, session.snapshot().capture().logicalFrameIndex()); + assertEquals(ControlState.AGENT_WORKING, session.snapshot().state()); + assertFalse(value(call("studio_operation_cancel", args().put("operationId", operation))).path("cancellationRequested").asBoolean()); + } + + @Test void realHttpBuildUsesExistingCompilerAndPackerAndRecoversReceiptByClientId() throws Exception { + var docs = p.studio.compiler.FrontendRegistryService.require("pbs").documentation().orElseThrow().references(1, p.studio.AppMode.Game); + for (var reference : docs) if (reference.id().startsWith("pbs:example:game:1:")) { + Path file = root.resolve(reference.id().substring("pbs:example:game:1:".length())); + Files.createDirectories(file.getParent()); Files.writeString(file, reference.text()); + } + try (var packer = p.packer.Packer.bootstrap(mapper, ignored -> {})) { + var shipper = new p.studio.core.shipper.StudioShipperService(new p.studio.app.compiler.CompilerBuildGatewayAdapter(), + packer.workspaceService(), mapper, new ExecutorOperationExecutor(workers), access); + compose(shipper); + try (var server = new LocalMcpServer(mapper, tools); var client = java.net.http.HttpClient.newHttpClient()) { + server.start(); + var initialize = mapper.createObjectNode().put("jsonrpc", "2.0").put("id", 1).put("method", "initialize"); + var params = initialize.putObject("params").put("protocolVersion", "2025-06-18"); + params.putObject("capabilities"); params.putObject("clientInfo").put("name", "task-test").put("version", "1"); + String connection = post(client, server, null, initialize).headers().firstValue("Mcp-Session-Id").orElseThrow(); + post(client, server, connection, mapper.createObjectNode().put("jsonrpc", "2.0").put("method", "notifications/initialized")); + error("NOT_GRANTED", httpCall(client, server, connection, "studio_control_acquire", rootOnly())); + session.grant(false).toCompletableFuture().join(); + task = value(httpCall(client, server, connection, "studio_control_acquire", rootOnly())).path("taskId").asText(); + assertThrows(ControlDeniedException.class, () -> shipper.prepare(catalog.openProject(root), ignored -> {})); + // Discard the initial response, as a client with a lost receipt would do. + httpCall(client, server, connection, "studio_build_start", args().put("clientRequestId", "http-build")); + var result = completed("http-build"); + assertEquals("SUCCESS", result.path("result").path("status").asText(), result.toString()); + assertTrue(Files.isRegularFile(Path.of(result.path("result").path("manifestPath").asText()))); + var recovered = value(httpCall(client, server, connection, "studio_operation_get", args().put("clientRequestId", "http-build"))); + assertEquals(result.path("operationId"), recovered.path("operationId")); + assertEquals(result.path("operationId"), value(httpCall(client, server, connection, "studio_build_start", args().put("clientRequestId", "http-build"))).path("operationId")); + value(httpCall(client, server, connection, "studio_control_release", args())); + error("INVALID_TASK", httpCall(client, server, connection, "studio_operation_get", args().put("clientRequestId", "http-build"))); + assertTrue(session.snapshot().manualAllowed()); + } + } + } + JsonNode httpCall(java.net.http.HttpClient client, LocalMcpServer server, String connection, String name, ObjectNode arguments) throws Exception { + var request = mapper.createObjectNode().put("jsonrpc", "2.0").put("id", UUID.randomUUID().toString()).put("method", "tools/call"); + request.putObject("params").put("name", name).set("arguments", arguments); + var response = post(client, server, connection, request); + assertEquals(200, response.statusCode(), response.body()); + var body = mapper.readTree(response.body()); assertFalse(body.has("error"), body.toString()); + return body.path("result"); + } + java.net.http.HttpResponse post(java.net.http.HttpClient client, LocalMcpServer server, String connection, JsonNode body) throws Exception { + var request = java.net.http.HttpRequest.newBuilder(server.connection().endpoint()).timeout(java.time.Duration.ofSeconds(10)) + .header("Authorization", server.connection().authorizationHeader()).header("Content-Type", "application/json") + .header("Accept", "application/json, text/event-stream").header("MCP-Protocol-Version", "2025-06-18"); + if (connection != null) request.header("Mcp-Session-Id", connection); + return client.send(request.POST(java.net.http.HttpRequest.BodyPublishers.ofString(body.toString())).build(), java.net.http.HttpResponse.BodyHandlers.ofString()); + } + + static void awaitGate(CountDownLatch gate) { + boolean interrupted = false; + while (true) { try { gate.await(); break; } catch (InterruptedException ignored) { interrupted = true; } } + if (interrupted) Thread.currentThread().interrupt(); + } + final class FakeRuntime implements HeadlessGateway.Session { + final String id = UUID.randomUUID().toString(), build; + final AtomicInteger advances = new AtomicInteger(); + final CountDownLatch entered = new CountDownLatch(1), gate = new CountDownLatch(1); + volatile boolean stopped, hold, cancelled; + volatile AutomationOutcome.Kind kind = AutomationOutcome.Kind.SUCCEEDED; + Map input; + FakeRuntime(String build) { this.build = build; } + public String sessionId() { return id; } + public void cancel() { cancelled = true; } + public CompletionStage shutdown() { stopped = true; return CompletableFuture.completedFuture(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=")); } + public TaskTools.HeadlessReply call(TaskTools.HeadlessAction action, Map input) { + this.input = input; + return new TaskTools.HeadlessReply(Map.of("sessionId", id), action == TaskTools.HeadlessAction.CAPTURE ? capture(5) : null); + } + public AutomationOutcome advance(long frames, Consumer progress) { + advances.incrementAndGet(); progress.accept(new TrackedOperation.Progress(frames, Math.min(2, frames))); entered.countDown(); + if (hold) awaitGate(gate); + long completed = cancelled ? Math.min(2, frames) : frames; + return new AutomationOutcome(cancelled ? AutomationOutcome.Kind.CANCELLED : kind, frames, completed, List.of(), capture(completed)); + } + } +} diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationSession.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationSession.java index 45474d50..0e4e568b 100644 --- a/prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationSession.java +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationSession.java @@ -16,6 +16,8 @@ public interface AutomationSession { /** Internal specialized service work, not a generic MCP shell/tool endpoint. */ OperationHandle submit(TaskIdentity task, String summary, Callable work); void attachRuntime(TaskIdentity task, ManagedHeadlessSession runtime); + /** Called only after shutdown has completed, before artifacts can be rebuilt. */ + void detachRuntime(TaskIdentity task, ManagedHeadlessSession runtime); void markCaptureStale(); /** Cleanup runs after workers stop and before returning manual control. */ void onTaskEnd(TaskIdentity task, Runnable cleanup); diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/TaskTools.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/TaskTools.java new file mode 100644 index 00000000..5f9ed6f7 --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/TaskTools.java @@ -0,0 +1,21 @@ +package p.studio.api.automation; + +import java.nio.file.Path; +import java.util.Map; +import java.util.concurrent.CompletionStage; + +/** Specialized automation services shared by adapters; never grants human permission. */ +public interface TaskTools { + ControlResult acquire(Path root); + CompletionStage release(Path root, String taskId); + TrackedOperation build(Path root, String taskId, String clientRequestId); + TrackedOperation advance(Path root, String taskId, String clientRequestId, long frames); + TrackedOperation operation(Path root, String taskId, OperationLookup lookup); + boolean cancel(Path root, String taskId, String operationId); + HeadlessReply headless(Path root, String taskId, HeadlessAction action, String buildId, Map input); + + enum HeadlessAction { BOOT, RESET, SET_INPUT, CLEAR_INPUT, CAPTURE, STATE, FAULT, SHUTDOWN } + record HeadlessReply(Map values, CanonicalCapture capture) { + public HeadlessReply { values = java.util.Collections.unmodifiableMap(new java.util.LinkedHashMap<>(values)); } + } +} diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/TrackedOperation.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/TrackedOperation.java index 6d04e1de..b7a641a1 100644 --- a/prometeu-studio-api/src/main/java/p/studio/api/automation/TrackedOperation.java +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/TrackedOperation.java @@ -6,7 +6,8 @@ import java.util.Objects; /** An operation outcome is not task authority. Null result means it is not available yet. */ public record TrackedOperation(OperationSnapshot operation, String clientRequestId, Progress progress, - String buildId, ShipperPrepareResult buildResult, AutomationOutcome runtimeResult, AutomationFailure failure) { + String buildId, ShipperPrepareResult buildResult, AutomationOutcome runtimeResult, AutomationFailure failure, + boolean workerTerminated, boolean captureStale) { public TrackedOperation { Objects.requireNonNull(operation); Objects.requireNonNull(clientRequestId); Objects.requireNonNull(progress); if (clientRequestId.isBlank()) throw new IllegalArgumentException("Empty client request identity"); diff --git a/prometeu-studio-core/src/main/java/p/studio/core/runtime/HeadlessGateway.java b/prometeu-studio-core/src/main/java/p/studio/core/runtime/HeadlessGateway.java new file mode 100644 index 00000000..81fd8180 --- /dev/null +++ b/prometeu-studio-core/src/main/java/p/studio/core/runtime/HeadlessGateway.java @@ -0,0 +1,18 @@ +package p.studio.core.runtime; + +import p.studio.api.automation.*; +import p.studio.api.project.ProjectReference; +import p.studio.api.shipper.ShipperPrepareResult; +import java.util.Map; +import java.util.function.Consumer; + +/** Neutral runtime port. The process adapter owns protocol, effective limits and supervision. */ +public interface HeadlessGateway { + Session boot(ProjectReference project, String buildId, ShipperPrepareResult build) throws Exception; + + interface Session extends ManagedHeadlessSession { + long maxFramesPerAdvance(); + TaskTools.HeadlessReply call(TaskTools.HeadlessAction action, Map input) throws Exception; + AutomationOutcome advance(long frames, Consumer progress) throws Exception; + } +} diff --git a/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultAutomationSession.java b/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultAutomationSession.java index 6a85eb47..b1bd6134 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultAutomationSession.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultAutomationSession.java @@ -180,7 +180,7 @@ public final class DefaultAutomationSession implements AutomationSession { CompletionStage shutdown = CompletableFuture.completedFuture(null); if (ownedRuntime != null) { ownedRuntime.cancel(); shutdown = ownedRuntime.shutdown(); } cleanup = CompletableFuture.allOf(stopped.toCompletableFuture(), shutdown.toCompletableFuture(), idle); - cleanup = cleanup.thenRun(() -> cleanups.forEach(Runnable::run)); + cleanup = cleanup.whenComplete((v, failure) -> cleanups.forEach(Runnable::run)); // Closing disposes documents; an explicit return must refresh them before unlocking. for (var p : participants) cleanup = cleanup.thenCompose(v -> { synchronized (this) { if (closed) return CompletableFuture.completedFuture(null); } @@ -207,7 +207,21 @@ public final class DefaultAutomationSession implements AutomationSession { requireTask(identity); if (busy) throw new ControlDeniedException(ControlResult.Status.BUSY); busy = true; record(summary); - try { active = executor.submit(summary, work); } + try { active = executor.submit(summary, () -> { + var result = work.call(); + // Cancellation acknowledgement can precede a cooperative final result. Publish + // its known frame before worker termination, but never after task revocation. + synchronized (this) { + if (valid(identity)) { + diagnostics = result.diagnostics(); + if (result.capture() != null && runtime != null && runtime.sessionId().equals(result.capture().sessionId())) { + capture = result.capture(); stale = false; + } + publish(); + } + } + return result; + }); } catch (RuntimeException failure) { busy = false; throw failure; } var operation = active; var subscription = operation.subscribe(s -> { synchronized (this) { if (active == operation) publish(); } }); @@ -235,6 +249,11 @@ public final class DefaultAutomationSession implements AutomationSession { runtime = Objects.requireNonNull(next); stale = capture != null; record("runtime " + next.sessionId()); publish(); } @Override public synchronized void markCaptureStale() { stale = capture != null; publish(); } + @Override public synchronized void detachRuntime(TaskIdentity identity, ManagedHeadlessSession previous) { + requireTask(identity); + if (runtime != previous) throw new IllegalStateException("Runtime ownership changed"); + runtime = null; stale = capture != null; publish(); + } private boolean valid(TaskIdentity identity) { return !closed && state == ControlState.AGENT_WORKING && task != null && task.equals(identity); } private void requireTask(TaskIdentity identity) { if (!valid(identity)) throw new ControlDeniedException(ControlResult.Status.INVALID_TASK); } private void record(String call) { calls.addLast(Objects.requireNonNullElse(call, "")); while (calls.size() > 50) calls.removeFirst(); } diff --git a/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultTaskTools.java b/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultTaskTools.java new file mode 100644 index 00000000..9ed4d4bf --- /dev/null +++ b/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultTaskTools.java @@ -0,0 +1,234 @@ +package p.studio.core.session; + +import p.studio.api.automation.*; +import p.studio.api.operation.*; +import p.studio.api.project.ProjectCatalog; +import p.studio.api.shipper.ShipperPrepareResult; +import p.studio.core.project.ProjectAccessRegistry; +import p.studio.core.runtime.HeadlessGateway; +import p.studio.core.shipper.SavedProjectPreparation; +import java.nio.file.Path; +import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicReference; + +/** Task-local correlation over the existing project authority and operation executor. */ +public final class DefaultTaskTools implements TaskTools { + private final ProjectAccessRegistry projects; + private final ProjectCatalog catalog; + private final SavedProjectPreparation shipper; + private final Optional gateway; + private final Map tasks = new ConcurrentHashMap<>(); + + public DefaultTaskTools(ProjectAccessRegistry projects, ProjectCatalog catalog, + SavedProjectPreparation shipper, Optional gateway) { + this.projects = projects; this.catalog = catalog; this.shipper = shipper; this.gateway = gateway; + } + + @Override public ControlResult acquire(Path root) { return projects.requireAutomation(root).acquire(); } + @Override public CompletionStage release(Path root, String id) { + var session = projects.requireAutomation(root); + return session.release(requireTask(session, id)); + } + + @Override public TrackedOperation build(Path root, String id, String request) { + return start(root, id, request, new Parameters("build", null), (data, record) -> { + stopRuntime(data); + data.session.markCaptureStale(); + // Artifacts are mutable in place. Old IDs must never boot newly overwritten files. + data.builds.clear(); + var result = shipper.prepareNow(catalog.openProject(data.task.projectRoot()), ignored -> {}); + record.build = result; + if (result.success() && !Thread.currentThread().isInterrupted()) { + record.buildId = UUID.randomUUID().toString(); + data.builds.put(record.buildId, result); + } + return new AutomationOutcome(AutomationOutcome.Kind.SUCCEEDED, 0, 0, result.diagnostics(), null); + }); + } + + @Override public TrackedOperation advance(Path root, String id, String request, long frames) { + if (frames < 0) throw new IllegalArgumentException("frames must be nonnegative"); + return start(root, id, request, new Parameters("advance", frames), (data, record) -> { + var runtime = requireRuntime(data); + var result = runtime.advance(frames, progress -> { + if (!Objects.equals(progress.requestedFrames(), frames)) throw new IllegalArgumentException("Invalid runtime progress"); + record.progress = progress; + }); + record.runtime = result; + record.progress = new TrackedOperation.Progress(result.requestedFrames(), result.completedFrames()); + return result; + }); + } + + private TrackedOperation start(Path root, String id, String request, Parameters parameters, Work work) { + if (request == null || request.isBlank()) throw new IllegalArgumentException("clientRequestId required"); + var session = projects.requireAutomation(root); + synchronized (session) { + var data = data(session, id); // Authority always precedes cache access, even for a duplicate. + var existing = data.requests.get(request); + if (existing != null) { + if (!existing.parameters.equals(parameters)) throw failure(AutomationFailure.Code.CLIENT_REQUEST_CONFLICT, "clientRequestId has different parameters"); + return tracked(data, existing); + } + if (parameters.frames != null && parameters.frames > requireRuntime(data).maxFramesPerAdvance()) + throw failure(AutomationFailure.Code.LIMIT_EXCEEDED, "Advance exceeds the runtime's effective frame limit"); + var record = new Record(request, parameters); + record.handle = session.submit(data.task, parameters.kind, () -> { + try { return work.run(data, record); } + catch (Exception error) { + if (error instanceof AutomationException domain) record.failure = domain.failure(); + else if (!(error instanceof InterruptedException) && !(error instanceof CancellationException)) + record.failure = new AutomationFailure(AutomationFailure.Code.INFRASTRUCTURE_FAILURE, "Managed operation failed"); + throw error; + } + }); + // Rejected work never reserves a request ID. The authority monitor makes start/dedup atomic. + data.requests.put(request, record); + data.operations.put(record.handle.id().value(), record); + record.handle.completion().whenComplete((result, error) -> { + if (error != null && !(error instanceof CancellationException) && record.failure == null) + record.failure = new AutomationFailure(AutomationFailure.Code.INFRASTRUCTURE_FAILURE, "Managed worker failed"); + }); + return tracked(data, record); + } + } + + @Override public TrackedOperation operation(Path root, String id, OperationLookup lookup) { + var session = projects.requireAutomation(root); + synchronized (session) { var data = data(session, id); return tracked(data, find(data, lookup)); } + } + + @Override public boolean cancel(Path root, String id, String operationId) { + var session = projects.requireAutomation(root); + synchronized (session) { + var data = data(session, id); + var record = find(data, new OperationLookup(operationId, null)); + var runtime = record.parameters.frames == null ? null : data.runtime; + if (record.handle.termination().toCompletableFuture().isDone()) return false; + // Keep admission closed until cancellation targets this operation, not its successor. + if (runtime != null) runtime.cancel(); + return record.handle.cancel(); + } + } + + @Override public HeadlessReply headless(Path root, String id, HeadlessAction action, String buildId, Map input) { + var session = projects.requireAutomation(root); + final OperationHandle handle; + var reply = new AtomicReference(); + synchronized (session) { + var data = data(session, id); + handle = session.submit(data.task, "headless " + action, () -> { + HeadlessReply result; + if (action == HeadlessAction.BOOT) { + if (data.runtime != null) throw failure(AutomationFailure.Code.BUSY, "A headless session is already active"); + var build = buildId == null ? null : data.builds.get(buildId); + if (build == null) throw failure(AutomationFailure.Code.BUILD_NOT_FOUND, "No successful current task build with this ID"); + var port = gateway.orElseThrow(() -> failure(AutomationFailure.Code.RUNTIME_UNAVAILABLE, "Headless process adapter is not composed")); + var runtime = port.boot(catalog.openProject(data.task.projectRoot()), buildId, build); + try { session.attachRuntime(data.task, runtime); } + catch (RuntimeException denied) { runtime.cancel(); runtime.shutdown().toCompletableFuture().join(); throw denied; } + data.runtime = runtime; + result = new HeadlessReply(Map.of("sessionId", runtime.sessionId(), "buildId", buildId), null); + } else if (action == HeadlessAction.SHUTDOWN) { + String sessionId = requireRuntime(data).sessionId(); + stopRuntime(data); + result = new HeadlessReply(Map.of("sessionId", sessionId), null); + } else { + result = requireRuntime(data).call(action, input); + if (action == HeadlessAction.RESET) session.markCaptureStale(); + } + reply.set(result); + return new AutomationOutcome(AutomationOutcome.Kind.SUCCEEDED, 0, 0, List.of(), result.capture()); + }); + } + try { + handle.completion().toCompletableFuture().get(); + handle.termination().toCompletableFuture().get(); + synchronized (session) { requireTask(session, id); return reply.get(); } + } catch (InterruptedException error) { + handle.cancel(); Thread.currentThread().interrupt(); + throw failure(AutomationFailure.Code.INFRASTRUCTURE_FAILURE, "Headless call interrupted"); + } catch (ExecutionException error) { + if (error.getCause() instanceof RuntimeException cause) throw cause; + throw failure(AutomationFailure.Code.INFRASTRUCTURE_FAILURE, "Headless call failed"); + } catch (CancellationException error) { + throw failure(AutomationFailure.Code.INFRASTRUCTURE_FAILURE, "Headless call cancelled"); + } + } + + private void stopRuntime(TaskData data) { + var runtime = data.runtime; + if (runtime == null) return; + runtime.cancel(); + runtime.shutdown().toCompletableFuture().join(); + data.session.detachRuntime(data.task, runtime); + data.runtime = null; + } + + private TaskData data(AutomationSession session, String id) { + var task = requireTask(session, id); + var data = tasks.get(task); + if (data == null) { + data = new TaskData(session, task); + tasks.put(task, data); + session.onTaskEnd(task, () -> tasks.remove(task)); + } + return data; + } + private static TaskIdentity requireTask(AutomationSession session, String id) { + var state = session.snapshot(); + if (state.closed() || state.state() != ControlState.AGENT_WORKING || state.task() == null || !state.task().value().equals(id)) + throw new ControlDeniedException(ControlResult.Status.INVALID_TASK); + return state.task(); + } + private static HeadlessGateway.Session requireRuntime(TaskData data) { + if (data.runtime == null) throw failure(AutomationFailure.Code.SESSION_NOT_FOUND, "No active task headless session"); + return data.runtime; + } + private static Record find(TaskData data, OperationLookup key) { + var record = key.operationId() == null ? data.requests.get(key.clientRequestId()) : data.operations.get(key.operationId()); + if (record == null) throw failure(AutomationFailure.Code.OPERATION_NOT_FOUND, "No such operation in this task"); + return record; + } + private static TrackedOperation tracked(TaskData data, Record record) { + // Results become final only when the worker has stopped, including acknowledged cancellation. + boolean done = record.handle.termination().toCompletableFuture().isDone(); + var snapshot = record.handle.snapshot(); + if (!done && (snapshot.state() == OperationState.SUCCEEDED || snapshot.state() == OperationState.FAILED)) + snapshot = new OperationSnapshot(snapshot.id(), OperationState.RUNNING, snapshot.updatedAt(), snapshot.summary()); + var current = data.session.snapshot(); + var captured = record.runtime == null ? null : record.runtime.capture(); + boolean stale = captured != null && (current.stale() || current.capture() == null + || !captured.sessionId().equals(current.capture().sessionId()) || !captured.buildId().equals(current.capture().buildId()) + || captured.logicalFrameIndex() != current.capture().logicalFrameIndex() || captured.frameId() != current.capture().frameId()); + return new TrackedOperation(snapshot, record.request, record.progress, + done ? record.buildId : null, done ? record.build : null, done ? record.runtime : null, done ? record.failure : null, + done, stale); + } + private static AutomationException failure(AutomationFailure.Code code, String message) { return new AutomationException(code, message); } + private record Parameters(String kind, Long frames) {} + @FunctionalInterface private interface Work { AutomationOutcome run(TaskData data, Record record) throws Exception; } + private static final class Record { + final String request; + final Parameters parameters; + OperationHandle handle; + volatile TrackedOperation.Progress progress; + volatile String buildId; + volatile ShipperPrepareResult build; + volatile AutomationOutcome runtime; + volatile AutomationFailure failure; + Record(String request, Parameters parameters) { + this.request = request; this.parameters = parameters; + progress = new TrackedOperation.Progress(parameters.frames, null); + } + } + private static final class TaskData { + final AutomationSession session; + final TaskIdentity task; + final Map requests = new HashMap<>(), operations = new HashMap<>(); + final Map builds = new ConcurrentHashMap<>(); + volatile HeadlessGateway.Session runtime; + TaskData(AutomationSession session, TaskIdentity task) { this.session = session; this.task = task; } + } +} diff --git a/prometeu-studio-core/src/main/java/p/studio/core/shipper/SavedProjectPreparation.java b/prometeu-studio-core/src/main/java/p/studio/core/shipper/SavedProjectPreparation.java new file mode 100644 index 00000000..372f85e0 --- /dev/null +++ b/prometeu-studio-core/src/main/java/p/studio/core/shipper/SavedProjectPreparation.java @@ -0,0 +1,12 @@ +package p.studio.core.shipper; + +import p.studio.api.project.ProjectReference; +import p.studio.api.shipper.ShipperPrepareResult; +import p.studio.api.shipper.ShipperLogEntry; +import java.util.function.Consumer; + +/** Internal work port: the caller owns admission and worker lifecycle. */ +@FunctionalInterface +public interface SavedProjectPreparation { + ShipperPrepareResult prepareNow(ProjectReference project, Consumer sink); +} diff --git a/prometeu-studio-core/src/main/java/p/studio/core/shipper/StudioShipperService.java b/prometeu-studio-core/src/main/java/p/studio/core/shipper/StudioShipperService.java index f44d6570..79dd95f2 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/shipper/StudioShipperService.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/shipper/StudioShipperService.java @@ -27,7 +27,7 @@ import java.util.List; import java.util.Objects; import java.util.function.Consumer; -public final class StudioShipperService implements Shipper { +public final class StudioShipperService implements Shipper, SavedProjectPreparation { private p.studio.api.automation.ProjectAccess access = new p.studio.core.project.ProjectAccessRegistry(); public StudioShipperService(CompilerBuildGateway compiler, PackerWorkspaceService packer, ObjectMapper mapper, OperationExecutor operations, p.studio.api.automation.ProjectAccess access) { this(compiler, packer, mapper, operations); @@ -54,14 +54,16 @@ public final class StudioShipperService implements Shipper { return access.submitManual(project.rootPath(), operations, "Build and pack " + project.name(), () -> prepareNow(project, sink)); } - private ShipperPrepareResult prepareNow(ProjectReference project, Consumer sink) { + @Override public ShipperPrepareResult prepareNow(ProjectReference project, Consumer sink) { Objects.requireNonNull(project, "project"); Objects.requireNonNull(sink, "sink"); final List logs = new ArrayList<>(); final List diagnostics = new ArrayList<>(); try { + checkCancelled(); final CompilerBuildGateway.CompilerBuildOutput build = compiler.compile(project, message -> emit(logs, sink, ShipperLogEntry.info(ShipperLogSource.BUILD, normalize(message)))); + checkCancelled(); if (build.bytecodeArtifact() != null) { emit(logs, sink, ShipperLogEntry.info(ShipperLogSource.BUILD, "Prepared program bytecode at " + build.bytecodeArtifact())); @@ -73,7 +75,9 @@ public final class StudioShipperService implements Shipper { if (!validation.canPack()) { return ShipperPrepareResult.failed(logs, diagnostics); } + checkCancelled(); final var packed = packer.packWorkspace(new PackWorkspaceRequest(context)); + checkCancelled(); emit(logs, sink, logFor(packed.status(), ShipperLogSource.PACK, packed.summary())); if (packed.status() != PackerOperationStatus.SUCCESS) { diagnostics.add(packed.summary()); @@ -92,6 +96,10 @@ public final class StudioShipperService implements Shipper { } } + private static void checkCancelled() { + if (Thread.currentThread().isInterrupted()) throw new java.util.concurrent.CancellationException("Build cancelled"); + } + private Path writeManifest(ProjectReference project, CompilerBuildGateway.CompilerBuildOutput build, List logs, Consumer sink) { final Path buildRoot = project.rootPath().resolve("build").toAbsolutePath().normalize();