expose task control and deduplicated operations through MCP

This commit is contained in:
2026-09-29 10:26:19 +01:00
parent c1834bad1f
commit 20bbbd26bd
14 changed files with 775 additions and 12 deletions
@@ -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<String, Object> input) throws Exception;
AutomationOutcome advance(long frames, Consumer<TrackedOperation.Progress> progress) throws Exception;
}
}
@@ -180,7 +180,7 @@ public final class DefaultAutomationSession implements AutomationSession {
CompletionStage<Void> 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(); }
@@ -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<HeadlessGateway> gateway;
private final Map<TaskIdentity, TaskData> tasks = new ConcurrentHashMap<>();
public DefaultTaskTools(ProjectAccessRegistry projects, ProjectCatalog catalog,
SavedProjectPreparation shipper, Optional<HeadlessGateway> 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<ControlResult> 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<String, Object> input) {
var session = projects.requireAutomation(root);
final OperationHandle<AutomationOutcome> handle;
var reply = new AtomicReference<HeadlessReply>();
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<AutomationOutcome> 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<String, Record> requests = new HashMap<>(), operations = new HashMap<>();
final Map<String, ShipperPrepareResult> builds = new ConcurrentHashMap<>();
volatile HeadlessGateway.Session runtime;
TaskData(AutomationSession session, TaskIdentity task) { this.session = session; this.task = task; }
}
}
@@ -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<ShipperLogEntry> sink);
}
@@ -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<ShipperLogEntry> sink) {
@Override public ShipperPrepareResult prepareNow(ProjectReference project, Consumer<ShipperLogEntry> sink) {
Objects.requireNonNull(project, "project");
Objects.requireNonNull(sink, "sink");
final List<ShipperLogEntry> logs = new ArrayList<>();
final List<String> 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<ShipperLogEntry> logs, Consumer<ShipperLogEntry> sink) {
final Path buildRoot = project.rootPath().resolve("build").toAbsolutePath().normalize();