connect MCP language queries to project LSP

This commit is contained in:
2026-09-29 09:21:59 +01:00
parent feb57c5298
commit c1834bad1f
24 changed files with 757 additions and 21 deletions
@@ -0,0 +1,10 @@
package p.studio.core.language;
import p.studio.api.automation.TaskIdentity;
import java.util.Map;
/** Application adapter to the existing language server; never a replacement compiler. */
public interface LanguageQueryPort {
Map<String, Object> query(TaskIdentity task, String operation, Map<String, Object> parameters) throws Exception;
void endTask(TaskIdentity task);
}
@@ -0,0 +1,55 @@
package p.studio.core.language;
import p.studio.api.automation.*;
import p.studio.core.project.ProjectAccessRegistry;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicReference;
/** Shares project admission, cancellation and DEV observation with other agent work. */
public final class TaskLanguageQueries implements LanguageQueries {
private final ProjectAccessRegistry projects;
private final LanguageQueryPort language;
private final Set<TaskIdentity> registered = ConcurrentHashMap.newKeySet();
public TaskLanguageQueries(ProjectAccessRegistry projects, LanguageQueryPort language) {
this.projects = Objects.requireNonNull(projects); this.language = Objects.requireNonNull(language);
}
@Override public Map<String, Object> query(Path root, String taskId, String operation, Map<String, Object> parameters) {
var session = projects.requireAutomation(root);
var task = requireTask(session, taskId);
if (registered.add(task)) {
try { session.onTaskEnd(task, () -> { try { language.endTask(task); } finally { registered.remove(task); } }); }
catch (RuntimeException failure) { registered.remove(task); throw failure; }
}
var result = new AtomicReference<Map<String, Object>>();
var handle = session.submit(task, "LSP " + operation, () -> {
result.set(language.query(task, operation, parameters));
return new AutomationOutcome(AutomationOutcome.Kind.SUCCEEDED, 0, 0, List.of(), null);
});
try {
handle.completion().toCompletableFuture().get(12, TimeUnit.SECONDS);
handle.termination().toCompletableFuture().get(1, TimeUnit.SECONDS);
requireTask(session, taskId);
return Objects.requireNonNull(result.get());
} catch (ExecutionException failure) {
if (failure.getCause() instanceof RuntimeException cause) throw cause;
throw new AutomationException(AutomationFailure.Code.INFRASTRUCTURE_FAILURE, "LSP query failed");
} catch (InterruptedException failure) {
handle.cancel(); Thread.currentThread().interrupt();
throw new AutomationException(AutomationFailure.Code.INFRASTRUCTURE_FAILURE, "LSP query interrupted");
} catch (TimeoutException | CancellationException failure) {
handle.cancel();
throw new AutomationException(AutomationFailure.Code.INFRASTRUCTURE_FAILURE, "LSP query cancelled or timed out");
}
}
private static TaskIdentity requireTask(AutomationSession session, String id) {
var snapshot = session.snapshot();
if (snapshot.closed() || snapshot.state() != ControlState.AGENT_WORKING || snapshot.task() == null || !snapshot.task().value().equals(id))
throw new ControlDeniedException(ControlResult.Status.INVALID_TASK);
return snapshot.task();
}
}
@@ -14,7 +14,7 @@ import p.studio.api.automation.AutomationFailure;
/** Application-composed routing only; authority is owned by each project session. */
public final class ProjectAccessRegistry implements ProjectAccess {
private record Entry(Supplier<ManualLease> authority, BooleanSupplier available) {}
private record Entry(Supplier<ManualLease> authority, BooleanSupplier available, p.studio.api.automation.AutomationSession automation) {}
private final Map<Path, Entry> projects = new HashMap<>();
public OperationSubscription register(Path root, Supplier<ManualLease> authority) {
@@ -22,12 +22,27 @@ public final class ProjectAccessRegistry implements ProjectAccess {
}
public synchronized OperationSubscription register(Path root, Supplier<ManualLease> authority, BooleanSupplier available) {
return register(root, authority, available, null);
}
public synchronized OperationSubscription register(Path root, Supplier<ManualLease> authority, BooleanSupplier available,
p.studio.api.automation.AutomationSession automation) {
Path key = canonical(root);
var entry = new Entry(java.util.Objects.requireNonNull(authority), java.util.Objects.requireNonNull(available));
var entry = new Entry(java.util.Objects.requireNonNull(authority), java.util.Objects.requireNonNull(available), automation);
if (projects.putIfAbsent(key, entry) != null) throw new IllegalStateException("Project already open: " + key);
return () -> { synchronized (this) { projects.remove(key, entry); } };
}
public p.studio.api.automation.AutomationSession requireAutomation(Path root) {
Path key = requireOpenRoot(root);
synchronized (this) {
var entry = projects.get(key);
if (entry == null || entry.automation() == null)
throw new AutomationException(AutomationFailure.Code.PROJECT_NOT_OPEN, "No open project automation session");
return entry.automation();
}
}
/** Exact root lookup, never focus-based or a descendant-path admission. No grant is needed. */
public Path requireOpenRoot(Path root) {
Path key = canonical(root);
@@ -25,6 +25,12 @@ public final class DefaultAutomationSession implements AutomationSession {
private List<String> diagnostics = List.of();
private CompletableFuture<ControlResult> returning;
private final List<Runnable> manualCancellation = new ArrayList<>();
private final List<Runnable> taskCleanup = new ArrayList<>();
@Override public synchronized void onTaskEnd(TaskIdentity identity, Runnable cleanup) {
requireTask(identity);
taskCleanup.add(Objects.requireNonNull(cleanup));
}
private CompletableFuture<Void> manualIdle = CompletableFuture.completedFuture(null);
public DefaultAutomationSession(Path root, OperationExecutor executor) {
@@ -150,6 +156,7 @@ public final class DefaultAutomationSession implements AutomationSession {
final List<Runnable> cancellations;
final List<DocumentHandoff> participants;
final CompletableFuture<Void> idle;
final List<Runnable> cleanups;
synchronized (this) {
if (requireIdentity && !valid(identity)) return result(ControlResult.Status.INVALID_TASK, "Task identity is not current");
if (closing) closed = true;
@@ -161,6 +168,7 @@ public final class DefaultAutomationSession implements AutomationSession {
operation = active; ownedRuntime = runtime; idle = manualIdle;
cancellations = closing ? List.copyOf(manualCancellation) : List.of();
participants = closing ? List.of() : List.copyOf(documents);
cleanups = List.copyOf(taskCleanup); taskCleanup.clear();
publish();
}
// Never call another service while holding the authority monitor: Debug owns its own lock.
@@ -172,6 +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));
// 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); }
@@ -34,7 +34,7 @@ public final class DefaultProjectSessionFactory implements ProjectSessionFactory
var automation = new DefaultAutomationSession(project.rootPath(), operations);
var ready = new java.util.concurrent.atomic.AtomicBoolean();
var registration = access.register(project.rootPath(), automation::enterManual,
() -> ready.get() && !automation.snapshot().closed());
() -> ready.get() && !automation.snapshot().closed(), automation);
try { lsp.boot(project); }
catch (RuntimeException failure) { registration.unsubscribe(); throw failure; }
ready.set(true);
@@ -15,7 +15,7 @@ class StudioModularityTest {
void verifiesStudioCoreApplicationModules() {
modules.verify();
assertEquals(
Set.of("project", "session", "assets", "shipper", "runtime", "execution"),
Set.of("project", "session", "assets", "shipper", "runtime", "execution", "language"),
modules.stream().map(module -> module.getIdentifier().toString()).collect(java.util.stream.Collectors.toSet()));
}
@@ -18,6 +18,23 @@ class DefaultAutomationSessionTest {
ControlResult await(CompletionStage<ControlResult> result) { return result.toCompletableFuture().join(); }
TaskIdentity start(DefaultAutomationSession s) { assertEquals(GRANTED, await(s.grant(false)).status()); return s.acquire().task(); }
@Test void taskCleanupRunsAfterWorkerTerminationAndBeforeManualControl() {
var s = session(); var task = start(s);
var cleaned = new java.util.concurrent.atomic.AtomicInteger();
s.onTaskEnd(task, () -> {
assertTrue(operations.last.stopped.isDone());
assertFalse(s.snapshot().manualAllowed());
cleaned.incrementAndGet();
});
s.submit(task, "language query", () -> new AutomationOutcome(AutomationOutcome.Kind.SUCCEEDED, 0, 0, List.of(), null));
var returning = s.reclaim().toCompletableFuture();
assertTrue(operations.last.cancelled); assertEquals(0, cleaned.get()); assertFalse(returning.isDone());
operations.last.finish();
assertEquals(RETURNED, returning.join().status()); assertEquals(1, cleaned.get());
s.closeAsync().toCompletableFuture().join(); assertEquals(1, cleaned.get());
assertThrows(ControlDeniedException.class, () -> s.onTaskEnd(task, () -> {}));
}
@Test void explicitGrantAndProjectScopedIdentityAreRequired() {
var s = session();
assertEquals(NOT_GRANTED, s.acquire().status());